Free cookie consent management tool by TermsFeed Policy Generator

source: branches/OaaS/HeuristicLab.Problems.DataAnalysis.Symbolic.Views/3.4/InteractiveSymbolicDataAnalysisSolutionSimplifierView.cs @ 13417

Last change on this file since 13417 was 9363, checked in by spimming, 12 years ago

#1888:

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