Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Problems.DataAnalysis.Symbolic.Views/3.4/InteractiveSymbolicDataAnalysisSolutionSimplifierView.cs @ 11086

Last change on this file since 11086 was 11086, checked in by bburlacu, 10 years ago

#1763: Introduced tree editing functionality directly into the trunk code, with minor changes: simplified drawing (eg when highlighting subtrees from the clipboard), fixed small bug in MinArity function. The branch can be deleted.

File size: 12.3 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2014 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> foldedNodes;
35    private Dictionary<ISymbolicExpressionTreeNode, ISymbolicExpressionTreeNode> changedNodes;
36    private Dictionary<ISymbolicExpressionTreeNode, double> nodeImpacts;
37
38    private enum TreeState { Valid, Invalid }
39    private TreeState treeState;
40
41    protected InteractiveSymbolicDataAnalysisSolutionSimplifierView() {
42      InitializeComponent();
43      foldedNodes = new Dictionary<ISymbolicExpressionTreeNode, ISymbolicExpressionTreeNode>();
44      changedNodes = new Dictionary<ISymbolicExpressionTreeNode, ISymbolicExpressionTreeNode>();
45      nodeImpacts = new Dictionary<ISymbolicExpressionTreeNode, double>();
46      this.Caption = "Interactive Solution Simplifier";
47
48      // initialize the tree modifier that will be used to perform edit operations over the tree
49      treeChart.ModifyTree = Modify;
50    }
51
52    /// <summary>
53    /// Remove, Replace or Insert subtrees
54    /// </summary>
55    /// <param name="tree">The symbolic expression tree</param>
56    /// <param name="parent">The insertion point (ie, the parent node who will receive a new child)</param>
57    /// <param name="oldChild">The subtree to be replaced</param>
58    /// <param name="newChild">The replacement subtree</param>
59    /// <param name="removeSubtree">Flag used to indicate if whole subtrees should be removed (default behavior), or just the subtree root</param>
60    private void Modify(ISymbolicExpressionTree tree, ISymbolicExpressionTreeNode parent,
61      ISymbolicExpressionTreeNode oldChild, ISymbolicExpressionTreeNode newChild, bool removeSubtree = true) {
62      if (oldChild == null && newChild == null)
63        throw new ArgumentNullException("Cannot deduce operation type from the arguments. Please provide non null operands.");
64      if (oldChild == null) {
65        // insertion operation
66        parent.AddSubtree(newChild);
67        newChild.Parent = parent;
68      } else if (newChild == null) {
69        // removal operation
70        parent.RemoveSubtree(parent.IndexOfSubtree(oldChild));
71        if (!removeSubtree) {
72          for (int i = oldChild.SubtreeCount - 1; i >= 0; --i) {
73            var subtree = oldChild.GetSubtree(i);
74            oldChild.RemoveSubtree(i);
75            parent.AddSubtree(subtree);
76          }
77        }
78      } else {
79        // replacement operation
80        var replacementIndex = parent.IndexOfSubtree(oldChild);
81        parent.RemoveSubtree(replacementIndex);
82        parent.InsertSubtree(replacementIndex, newChild);
83        newChild.Parent = parent;
84        if (changedNodes.ContainsKey(oldChild)) {
85          changedNodes.Add(newChild, changedNodes[oldChild]); // so that on double click the original node is restored
86          changedNodes.Remove(oldChild);
87        } else {
88          changedNodes.Add(newChild, oldChild);
89        }
90      }
91      treeState = IsValid(tree) ? TreeState.Valid : TreeState.Invalid;
92      switch (treeState) {
93        case TreeState.Valid:
94          this.grpViewHost.Enabled = true;
95          UpdateModel(Content.Model.SymbolicExpressionTree);
96          break;
97        case TreeState.Invalid:
98          this.grpViewHost.Enabled = false;
99          break;
100      }
101    }
102
103    // the optimizer always assumes 2 children for multiplication and addition nodes
104    // thus, we enforce that the tree stays valid so that the constant optimization won't throw an exception
105    // by returning 2 as the minimum allowed arity for addition and multiplication symbols
106    private readonly Func<ISymbol, int> GetMinArity = symbol => {
107      var min = symbol.MinimumArity;
108      if (symbol is Multiplication || symbol is Division) return Math.Max(2, min);
109      return min;
110    };
111    private bool IsValid(ISymbolicExpressionTree tree) {
112      treeChart.Tree = tree;
113      treeChart.Repaint();
114      bool valid = !tree.IterateNodesPostfix().Any(node => node.SubtreeCount < GetMinArity(node.Symbol) || node.SubtreeCount > node.Symbol.MaximumArity);
115      if (valid) {
116        btnOptimizeConstants.Enabled = true;
117        btnSimplify.Enabled = true;
118        treeStatusValue.Text = "Valid";
119        treeStatusValue.ForeColor = Color.Green;
120      } else {
121        btnOptimizeConstants.Enabled = false;
122        btnSimplify.Enabled = false;
123        treeStatusValue.Text = "Invalid";
124        treeStatusValue.ForeColor = Color.Red;
125      }
126      this.Refresh();
127      return valid;
128    }
129
130    public new ISymbolicDataAnalysisSolution Content {
131      get { return (ISymbolicDataAnalysisSolution)base.Content; }
132      set { base.Content = value; }
133    }
134
135    protected override void RegisterContentEvents() {
136      base.RegisterContentEvents();
137      Content.ModelChanged += Content_Changed;
138      Content.ProblemDataChanged += Content_Changed;
139      treeChart.Repainted += treeChart_Repainted;
140    }
141    protected override void DeregisterContentEvents() {
142      base.DeregisterContentEvents();
143      Content.ModelChanged -= Content_Changed;
144      Content.ProblemDataChanged -= Content_Changed;
145      treeChart.Repainted -= treeChart_Repainted;
146    }
147
148    private void Content_Changed(object sender, EventArgs e) {
149      UpdateView();
150    }
151
152    protected override void OnContentChanged() {
153      base.OnContentChanged();
154      foldedNodes = new Dictionary<ISymbolicExpressionTreeNode, ISymbolicExpressionTreeNode>();
155      UpdateView();
156      viewHost.Content = this.Content;
157    }
158
159    private void treeChart_Repainted(object sender, EventArgs e) {
160      if (nodeImpacts != null && nodeImpacts.Count > 0)
161        PaintNodeImpacts();
162    }
163
164    private void UpdateView() {
165      if (Content == null || Content.Model == null || Content.ProblemData == null) return;
166      var tree = Content.Model.SymbolicExpressionTree;
167      treeChart.Tree = tree.Root.SubtreeCount > 1 ? new SymbolicExpressionTree(tree.Root) : new SymbolicExpressionTree(tree.Root.GetSubtree(0).GetSubtree(0));
168
169      var impactAndReplacementValues = CalculateImpactAndReplacementValues(tree);
170      var replacementValues = impactAndReplacementValues.ToDictionary(x => x.Key, x => x.Value.Item2);
171      foreach (var pair in replacementValues.Where(pair => !(pair.Key is ConstantTreeNode))) {
172        foldedNodes[pair.Key] = MakeConstantTreeNode(pair.Value);
173      }
174      nodeImpacts = impactAndReplacementValues.ToDictionary(x => x.Key, x => x.Value.Item1);
175      PaintNodeImpacts();
176    }
177
178    protected abstract Dictionary<ISymbolicExpressionTreeNode, double> CalculateReplacementValues(ISymbolicExpressionTree tree);
179    protected abstract Dictionary<ISymbolicExpressionTreeNode, double> CalculateImpactValues(ISymbolicExpressionTree tree);
180    protected abstract Dictionary<ISymbolicExpressionTreeNode, Tuple<double, double>> CalculateImpactAndReplacementValues(ISymbolicExpressionTree tree);
181    protected abstract void UpdateModel(ISymbolicExpressionTree tree);
182
183    private static ConstantTreeNode MakeConstantTreeNode(double value) {
184      var constant = new Constant { MinValue = value - 1, MaxValue = value + 1 };
185      var constantTreeNode = (ConstantTreeNode)constant.CreateTreeNode();
186      constantTreeNode.Value = value;
187      return constantTreeNode;
188    }
189
190    private void treeChart_SymbolicExpressionTreeNodeDoubleClicked(object sender, MouseEventArgs e) {
191      if (treeState == TreeState.Invalid) return;
192      var visualNode = (VisualTreeNode<ISymbolicExpressionTreeNode>)sender;
193      if (visualNode.Content == null) { throw new Exception("VisualNode content cannot be null."); }
194      var symbExprTreeNode = (SymbolicExpressionTreeNode)visualNode.Content;
195      var tree = Content.Model.SymbolicExpressionTree;
196      var parent = symbExprTreeNode.Parent;
197      int indexOfSubtree = parent.IndexOfSubtree(symbExprTreeNode);
198      if (changedNodes.ContainsKey(symbExprTreeNode)) {
199        // undo node change
200        parent.RemoveSubtree(indexOfSubtree);
201        var originalNode = changedNodes[symbExprTreeNode];
202        parent.InsertSubtree(indexOfSubtree, originalNode);
203        changedNodes.Remove(symbExprTreeNode);
204      } else if (foldedNodes.ContainsKey(symbExprTreeNode)) {
205        // undo node folding
206        SwitchNodeWithReplacementNode(parent, indexOfSubtree);
207      }
208      UpdateModel(tree);
209    }
210
211    private void SwitchNodeWithReplacementNode(ISymbolicExpressionTreeNode parent, int subTreeIndex) {
212      ISymbolicExpressionTreeNode subTree = parent.GetSubtree(subTreeIndex);
213      if (foldedNodes.ContainsKey(subTree)) {
214        parent.RemoveSubtree(subTreeIndex);
215        var replacementNode = foldedNodes[subTree];
216        parent.InsertSubtree(subTreeIndex, replacementNode);
217        // exchange key and value
218        foldedNodes.Remove(subTree);
219        foldedNodes.Add(replacementNode, subTree);
220      }
221    }
222
223    private void PaintNodeImpacts() {
224      var impacts = nodeImpacts.Values;
225      double max = impacts.Max();
226      double min = impacts.Min();
227      foreach (ISymbolicExpressionTreeNode treeNode in Content.Model.SymbolicExpressionTree.IterateNodesPostfix()) {
228        VisualTreeNode<ISymbolicExpressionTreeNode> visualTree = treeChart.GetVisualSymbolicExpressionTreeNode(treeNode);
229
230        if (!(treeNode is ConstantTreeNode) && nodeImpacts.ContainsKey(treeNode)) {
231          visualTree.ToolTip = visualTree.Content.ToString();
232          double impact = nodeImpacts[treeNode];
233
234          // impact = 0 if no change
235          // impact < 0 if new solution is better
236          // impact > 0 if new solution is worse
237          if (impact < 0.0) {
238            // min is guaranteed to be < 0
239            visualTree.FillColor = Color.FromArgb((int)(impact / min * 255), Color.Red);
240          } else if (impact.IsAlmost(0.0)) {
241            visualTree.FillColor = Color.White;
242          } else {
243            // max is guaranteed to be > 0
244            visualTree.FillColor = Color.FromArgb((int)(impact / max * 255), Color.Green);
245          }
246          visualTree.ToolTip += Environment.NewLine + "Node impact: " + impact;
247          var constantReplacementNode = foldedNodes[treeNode] as ConstantTreeNode;
248          if (constantReplacementNode != null) {
249            visualTree.ToolTip += Environment.NewLine + "Replacement value: " + constantReplacementNode.Value;
250          }
251        }
252        if (visualTree != null)
253          if (changedNodes.ContainsKey(treeNode)) {
254            visualTree.LineColor = Color.DodgerBlue;
255          } else if (treeNode is ConstantTreeNode && foldedNodes.ContainsKey(treeNode)) {
256            visualTree.LineColor = Color.DarkOrange;
257          }
258      }
259      treeChart.RepaintNodes();
260    }
261
262    private void btnSimplify_Click(object sender, EventArgs e) {
263      var simplifier = new SymbolicDataAnalysisExpressionTreeSimplifier();
264      var simplifiedExpressionTree = simplifier.Simplify(Content.Model.SymbolicExpressionTree);
265      UpdateModel(simplifiedExpressionTree);
266    }
267
268    protected abstract void btnOptimizeConstants_Click(object sender, EventArgs e);
269  }
270}
Note: See TracBrowser for help on using the repository browser.