Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.TreeSimplifierView/HeuristicLab.Problems.DataAnalysis.Symbolic.Views/3.4/InteractiveSymbolicDataAnalysisSolutionSimplifierView.cs @ 7372

Last change on this file since 7372 was 7372, checked in by bburlacu, 12 years ago

#1763: Intermediate commit with work done on the SymbolicExpressionTreeChart view (proxy right click events to nodes, methods for changing the weight/value of variable/constant nodes).

File size: 10.8 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2012 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using System;
23using System.Collections.Generic;
24using System.Drawing;
25using System.Linq;
26using System.Windows.Forms;
27using HeuristicLab.Common;
28using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
29using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views;
30using HeuristicLab.MainForm.WindowsForms;
31
32namespace HeuristicLab.Problems.DataAnalysis.Symbolic.Views {
33  public abstract partial class InteractiveSymbolicDataAnalysisSolutionSimplifierView : AsynchronousContentView {
34    private Dictionary<ISymbolicExpressionTreeNode, ISymbolicExpressionTreeNode> replacementNodes;
35    private Dictionary<ISymbolicExpressionTreeNode, double> nodeImpacts;
36    private bool updateInProgress = false;
37
38    public InteractiveSymbolicDataAnalysisSolutionSimplifierView() {
39      InitializeComponent();
40      this.replacementNodes = new Dictionary<ISymbolicExpressionTreeNode, ISymbolicExpressionTreeNode>();
41      this.nodeImpacts = new Dictionary<ISymbolicExpressionTreeNode, double>();
42      this.Caption = "Interactive Solution Simplifier";
43    }
44
45    public new ISymbolicDataAnalysisSolution Content {
46      get { return (ISymbolicDataAnalysisSolution)base.Content; }
47      set { base.Content = value; }
48    }
49
50    protected override void RegisterContentEvents() {
51      base.RegisterContentEvents();
52      Content.ModelChanged += new EventHandler(Content_ModelChanged);
53      Content.ProblemDataChanged += new EventHandler(Content_ProblemDataChanged);
54    }
55    protected override void DeregisterContentEvents() {
56      base.DeregisterContentEvents();
57      Content.ModelChanged -= new EventHandler(Content_ModelChanged);
58      Content.ProblemDataChanged -= new EventHandler(Content_ProblemDataChanged);
59    }
60
61    private void Content_ModelChanged(object sender, EventArgs e) {
62      OnModelChanged();
63    }
64    private void Content_ProblemDataChanged(object sender, EventArgs e) {
65      OnProblemDataChanged();
66    }
67
68    protected virtual void OnModelChanged() {
69      this.CalculateReplacementNodesAndNodeImpacts();
70    }
71
72    protected virtual void OnProblemDataChanged() {
73      this.CalculateReplacementNodesAndNodeImpacts();
74    }
75
76    protected override void OnContentChanged() {
77      base.OnContentChanged();
78      this.CalculateReplacementNodesAndNodeImpacts();
79      this.viewHost.Content = this.Content;
80    }
81
82    private void CalculateReplacementNodesAndNodeImpacts() {
83      if (Content != null && Content.Model != null && Content.ProblemData != null) {
84        var tree = Content.Model.SymbolicExpressionTree;
85        var replacementValues = CalculateReplacementValues(tree);
86        foreach (var pair in replacementValues) {
87          if (!(pair.Key is ConstantTreeNode)) {
88            replacementNodes[pair.Key] = MakeConstantTreeNode(pair.Value);
89          }
90        }
91        nodeImpacts = CalculateImpactValues(Content.Model.SymbolicExpressionTree);
92
93        if (!updateInProgress) {
94          // automatically fold all branches with impact = 1
95          List<ISymbolicExpressionTreeNode> nodeList = Content.Model.SymbolicExpressionTree.Root.GetSubtree(0).IterateNodesPrefix().ToList();
96          foreach (var parent in nodeList) {
97            for (int subTreeIndex = 0; subTreeIndex < parent.SubtreeCount; subTreeIndex++) {
98              var child = parent.GetSubtree(subTreeIndex);
99              if (!(child.Symbol is Constant) && nodeImpacts[child].IsAlmost(0.0)) {
100                SwitchNodeWithReplacementNode(parent, subTreeIndex);
101              }
102            }
103          }
104        }
105
106        // show only interesting part of solution
107        if (tree.Root.SubtreeCount > 1)
108          this.treeChart.Tree = new SymbolicExpressionTree(tree.Root); // RPB + ADFs
109        else
110          this.treeChart.Tree = new SymbolicExpressionTree(tree.Root.GetSubtree(0).GetSubtree(0)); // 1st child of RPB
111        this.PaintNodeImpacts();
112      }
113    }
114
115    protected abstract Dictionary<ISymbolicExpressionTreeNode, double> CalculateReplacementValues(ISymbolicExpressionTree tree);
116    protected abstract Dictionary<ISymbolicExpressionTreeNode, double> CalculateImpactValues(ISymbolicExpressionTree tree);
117    protected abstract void UpdateModel(ISymbolicExpressionTree tree);
118
119    private ConstantTreeNode MakeConstantTreeNode(double value) {
120      Constant constant = new Constant();
121      constant.MinValue = value - 1;
122      constant.MaxValue = value + 1;
123      ConstantTreeNode constantTreeNode = (ConstantTreeNode)constant.CreateTreeNode();
124      constantTreeNode.Value = value;
125      return constantTreeNode;
126    }
127
128    private void treeChart_SymbolicExpressionTreeNodeDoubleClicked(object sender, MouseEventArgs e) {
129      VisualSymbolicExpressionTreeNode visualTreeNode = (VisualSymbolicExpressionTreeNode)sender;
130      var tree = Content.Model.SymbolicExpressionTree;
131      foreach (SymbolicExpressionTreeNode treeNode in tree.IterateNodesPostfix()) {
132        for (int i = 0; i < treeNode.SubtreeCount; i++) {
133          ISymbolicExpressionTreeNode subTree = treeNode.GetSubtree(i);
134          // only allow to replace nodes for which a replacement value is known (replacement value for ADF nodes are not available)
135          if (subTree == visualTreeNode.SymbolicExpressionTreeNode && replacementNodes.ContainsKey(subTree)) {
136            SwitchNodeWithReplacementNode(treeNode, i);
137
138            // show only interesting part of solution
139            if (tree.Root.SubtreeCount > 1)
140              this.treeChart.Tree = new SymbolicExpressionTree(tree.Root); // RPB + ADFs
141            else
142              this.treeChart.Tree = new SymbolicExpressionTree(tree.Root.GetSubtree(0).GetSubtree(0)); // 1st child of RPB
143
144            updateInProgress = true;
145            UpdateModel(tree);
146            updateInProgress = false;
147            return; // break all loops
148          }
149        }
150      }
151    }
152
153    private void treeChart_SymbolicExpressionTreeNodeClicked(object sender, MouseEventArgs e) {
154      if (e.Button == MouseButtons.Right) {
155        var visualTreeNode = sender as VisualSymbolicExpressionTreeNode;
156        var node = visualTreeNode.SymbolicExpressionTreeNode;
157        // on a right click we want to show the option of changing the node value (if the node is a constant) or the weight (if the node is a variable)
158        var menu = treeChart.ContextMenuStrip;
159        ToolStripItem[] items = menu.Items.Find("changeValueToolStripMenuItem", false);
160        ToolStripItem changeValueMenuItem = null;
161        if (items.Length > 0) {
162          changeValueMenuItem = items[0];
163        }
164
165        if (node.Symbol is Constant || node.Symbol is Variable) {
166          if (changeValueMenuItem != null) {
167            changeValueMenuItem.Enabled = true;
168            changeValueMenuItem.Visible = true;
169          }
170        } else {
171          if (changeValueMenuItem != null) {
172            changeValueMenuItem.Enabled = false;
173            changeValueMenuItem.Visible = false;
174          }
175        }
176      }
177    }
178
179    private void SwitchNodeWithReplacementNode(ISymbolicExpressionTreeNode parent, int subTreeIndex) {
180      ISymbolicExpressionTreeNode subTree = parent.GetSubtree(subTreeIndex);
181      parent.RemoveSubtree(subTreeIndex);
182      if (replacementNodes.ContainsKey(subTree)) {
183        var replacementNode = replacementNodes[subTree];
184        parent.InsertSubtree(subTreeIndex, replacementNode);
185        // exchange key and value
186        replacementNodes.Remove(subTree);
187        replacementNodes.Add(replacementNode, subTree);
188      }
189    }
190
191    private void PaintNodeImpacts() {
192      var impacts = nodeImpacts.Values;
193      double max = impacts.Max();
194      double min = impacts.Min();
195      foreach (ISymbolicExpressionTreeNode treeNode in Content.Model.SymbolicExpressionTree.IterateNodesPostfix()) {
196        if (!(treeNode is ConstantTreeNode) && nodeImpacts.ContainsKey(treeNode)) {
197          double impact = nodeImpacts[treeNode];
198          VisualSymbolicExpressionTreeNode visualTree = treeChart.GetVisualSymbolicExpressionTreeNode(treeNode);
199
200          // impact = 0 if no change
201          // impact < 0 if new solution is better
202          // impact > 0 if new solution is worse
203          if (impact < 0.0) {
204            // min is guaranteed to be < 0
205            visualTree.FillColor = Color.FromArgb((int)(impact / min * 255), Color.Red);
206          } else if (impact.IsAlmost(0.0)) {
207            visualTree.FillColor = Color.White;
208          } else {
209            // max is guaranteed to be > 0
210            visualTree.FillColor = Color.FromArgb((int)(impact / max * 255), Color.Green);
211          }
212          visualTree.ToolTip += Environment.NewLine + "Node impact: " + impact;
213          var constantReplacementNode = replacementNodes[treeNode] as ConstantTreeNode;
214          if (constantReplacementNode != null) {
215            visualTree.ToolTip += Environment.NewLine + "Replacement value: " + constantReplacementNode.Value;
216          }
217        }
218      }
219      this.PaintCollapsedNodes();
220      this.treeChart.Repaint();
221    }
222
223    private void PaintCollapsedNodes() {
224      foreach (ISymbolicExpressionTreeNode treeNode in Content.Model.SymbolicExpressionTree.IterateNodesPostfix()) {
225        if (treeNode is ConstantTreeNode && replacementNodes.ContainsKey(treeNode))
226          this.treeChart.GetVisualSymbolicExpressionTreeNode(treeNode).LineColor = Color.DarkOrange;
227        else {
228          VisualSymbolicExpressionTreeNode visNode = treeChart.GetVisualSymbolicExpressionTreeNode(treeNode);
229          if (visNode != null)
230            visNode.LineColor = Color.Black;
231        }
232      }
233    }
234
235    private void btnSimplify_Click(object sender, EventArgs e) {
236      SymbolicDataAnalysisExpressionTreeSimplifier simplifier = new SymbolicDataAnalysisExpressionTreeSimplifier();
237      var simplifiedExpressionTree = simplifier.Simplify(Content.Model.SymbolicExpressionTree);
238      UpdateModel(simplifiedExpressionTree);
239    }
240
241    protected abstract void btnOptimizeConstants_Click(object sender, EventArgs e);
242  }
243}
Note: See TracBrowser for help on using the repository browser.