Free cookie consent management tool by TermsFeed Policy Generator

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

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

#1763: Improved alignment of node edit dialogs. Removed GroupSymbols from the list of available symbols when inserting new nodes. Added additional condition disallowing paste operations when it exceeds a symbols max arity. Moved tree status indicator to lower left and changed visibility to appear only when the tree is invalid.

File size: 12.2 KB
RevLine 
[3915]1#region License Information
2/* HeuristicLab
[11086]3 * Copyright (C) 2002-2014 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
[3915]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;
[4068]29using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views;
[3915]30using HeuristicLab.MainForm.WindowsForms;
31
[5699]32namespace HeuristicLab.Problems.DataAnalysis.Symbolic.Views {
33  public abstract partial class InteractiveSymbolicDataAnalysisSolutionSimplifierView : AsynchronousContentView {
[9006]34    private Dictionary<ISymbolicExpressionTreeNode, ISymbolicExpressionTreeNode> foldedNodes;
[11086]35    private Dictionary<ISymbolicExpressionTreeNode, ISymbolicExpressionTreeNode> changedNodes;
[5699]36    private Dictionary<ISymbolicExpressionTreeNode, double> nodeImpacts;
[11086]37
[9006]38    private enum TreeState { Valid, Invalid }
[11086]39    private TreeState treeState;
[3915]40
[11086]41    protected InteractiveSymbolicDataAnalysisSolutionSimplifierView() {
[3915]42      InitializeComponent();
[9006]43      foldedNodes = new Dictionary<ISymbolicExpressionTreeNode, ISymbolicExpressionTreeNode>();
[11086]44      changedNodes = new Dictionary<ISymbolicExpressionTreeNode, ISymbolicExpressionTreeNode>();
[8946]45      nodeImpacts = new Dictionary<ISymbolicExpressionTreeNode, double>();
[3915]46      this.Caption = "Interactive Solution Simplifier";
[11086]47
48      // initialize the tree modifier that will be used to perform edit operations over the tree
49      treeChart.ModifyTree = Modify;
[3915]50    }
51
[11086]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;
[11111]118        treeStatusValue.Visible = false;
[11086]119      } else {
120        btnOptimizeConstants.Enabled = false;
121        btnSimplify.Enabled = false;
[11111]122        treeStatusValue.Visible = true;
[11086]123      }
124      this.Refresh();
125      return valid;
126    }
127
[5699]128    public new ISymbolicDataAnalysisSolution Content {
129      get { return (ISymbolicDataAnalysisSolution)base.Content; }
[3915]130      set { base.Content = value; }
131    }
132
133    protected override void RegisterContentEvents() {
134      base.RegisterContentEvents();
[8946]135      Content.ModelChanged += Content_Changed;
136      Content.ProblemDataChanged += Content_Changed;
[10564]137      treeChart.Repainted += treeChart_Repainted;
[3915]138    }
139    protected override void DeregisterContentEvents() {
140      base.DeregisterContentEvents();
[8946]141      Content.ModelChanged -= Content_Changed;
142      Content.ProblemDataChanged -= Content_Changed;
[10564]143      treeChart.Repainted -= treeChart_Repainted;
[3915]144    }
145
[8946]146    private void Content_Changed(object sender, EventArgs e) {
147      UpdateView();
[3915]148    }
[5699]149
[3915]150    protected override void OnContentChanged() {
151      base.OnContentChanged();
[9006]152      foldedNodes = new Dictionary<ISymbolicExpressionTreeNode, ISymbolicExpressionTreeNode>();
[8946]153      UpdateView();
154      viewHost.Content = this.Content;
[3915]155    }
156
[10564]157    private void treeChart_Repainted(object sender, EventArgs e) {
158      if (nodeImpacts != null && nodeImpacts.Count > 0)
159        PaintNodeImpacts();
160    }
161
[8946]162    private void UpdateView() {
163      if (Content == null || Content.Model == null || Content.ProblemData == null) return;
164      var tree = Content.Model.SymbolicExpressionTree;
[8990]165      treeChart.Tree = tree.Root.SubtreeCount > 1 ? new SymbolicExpressionTree(tree.Root) : new SymbolicExpressionTree(tree.Root.GetSubtree(0).GetSubtree(0));
[3915]166
[10492]167      var impactAndReplacementValues = CalculateImpactAndReplacementValues(tree);
168      var replacementValues = impactAndReplacementValues.ToDictionary(x => x.Key, x => x.Value.Item2);
[8946]169      foreach (var pair in replacementValues.Where(pair => !(pair.Key is ConstantTreeNode))) {
[9006]170        foldedNodes[pair.Key] = MakeConstantTreeNode(pair.Value);
[8946]171      }
[11086]172      nodeImpacts = impactAndReplacementValues.ToDictionary(x => x.Key, x => x.Value.Item1);
[8946]173      PaintNodeImpacts();
[3915]174    }
175
[5717]176    protected abstract Dictionary<ISymbolicExpressionTreeNode, double> CalculateReplacementValues(ISymbolicExpressionTree tree);
177    protected abstract Dictionary<ISymbolicExpressionTreeNode, double> CalculateImpactValues(ISymbolicExpressionTree tree);
[10492]178    protected abstract Dictionary<ISymbolicExpressionTreeNode, Tuple<double, double>> CalculateImpactAndReplacementValues(ISymbolicExpressionTree tree);
[5717]179    protected abstract void UpdateModel(ISymbolicExpressionTree tree);
[3915]180
[8946]181    private static ConstantTreeNode MakeConstantTreeNode(double value) {
182      var constant = new Constant { MinValue = value - 1, MaxValue = value + 1 };
183      var constantTreeNode = (ConstantTreeNode)constant.CreateTreeNode();
[3915]184      constantTreeNode.Value = value;
185      return constantTreeNode;
186    }
187
188    private void treeChart_SymbolicExpressionTreeNodeDoubleClicked(object sender, MouseEventArgs e) {
[11086]189      if (treeState == TreeState.Invalid) return;
[10521]190      var visualNode = (VisualTreeNode<ISymbolicExpressionTreeNode>)sender;
[11086]191      if (visualNode.Content == null) { throw new Exception("VisualNode content cannot be null."); }
[10521]192      var symbExprTreeNode = (SymbolicExpressionTreeNode)visualNode.Content;
[11086]193      var tree = Content.Model.SymbolicExpressionTree;
[9006]194      var parent = symbExprTreeNode.Parent;
195      int indexOfSubtree = parent.IndexOfSubtree(symbExprTreeNode);
[11086]196      if (changedNodes.ContainsKey(symbExprTreeNode)) {
197        // undo node change
198        parent.RemoveSubtree(indexOfSubtree);
199        var originalNode = changedNodes[symbExprTreeNode];
200        parent.InsertSubtree(indexOfSubtree, originalNode);
201        changedNodes.Remove(symbExprTreeNode);
202      } else if (foldedNodes.ContainsKey(symbExprTreeNode)) {
203        // undo node folding
204        SwitchNodeWithReplacementNode(parent, indexOfSubtree);
205      }
206      UpdateModel(tree);
[3915]207    }
208
[5729]209    private void SwitchNodeWithReplacementNode(ISymbolicExpressionTreeNode parent, int subTreeIndex) {
[5736]210      ISymbolicExpressionTreeNode subTree = parent.GetSubtree(subTreeIndex);
[9006]211      if (foldedNodes.ContainsKey(subTree)) {
[10799]212        parent.RemoveSubtree(subTreeIndex);
[9006]213        var replacementNode = foldedNodes[subTree];
[5736]214        parent.InsertSubtree(subTreeIndex, replacementNode);
[5729]215        // exchange key and value
[9006]216        foldedNodes.Remove(subTree);
217        foldedNodes.Add(replacementNode, subTree);
[5729]218      }
[5455]219    }
220
[3915]221    private void PaintNodeImpacts() {
222      var impacts = nodeImpacts.Values;
223      double max = impacts.Max();
224      double min = impacts.Min();
[11086]225      foreach (ISymbolicExpressionTreeNode treeNode in Content.Model.SymbolicExpressionTree.IterateNodesPostfix()) {
[10521]226        VisualTreeNode<ISymbolicExpressionTreeNode> visualTree = treeChart.GetVisualSymbolicExpressionTreeNode(treeNode);
[8946]227
[4477]228        if (!(treeNode is ConstantTreeNode) && nodeImpacts.ContainsKey(treeNode)) {
[11086]229          visualTree.ToolTip = visualTree.Content.ToString();
[5729]230          double impact = nodeImpacts[treeNode];
[5722]231
[5717]232          // impact = 0 if no change
233          // impact < 0 if new solution is better
234          // impact > 0 if new solution is worse
235          if (impact < 0.0) {
[5729]236            // min is guaranteed to be < 0
[5717]237            visualTree.FillColor = Color.FromArgb((int)(impact / min * 255), Color.Red);
[5729]238          } else if (impact.IsAlmost(0.0)) {
239            visualTree.FillColor = Color.White;
[5717]240          } else {
[5729]241            // max is guaranteed to be > 0
[5717]242            visualTree.FillColor = Color.FromArgb((int)(impact / max * 255), Color.Green);
243          }
[3915]244          visualTree.ToolTip += Environment.NewLine + "Node impact: " + impact;
[9006]245          var constantReplacementNode = foldedNodes[treeNode] as ConstantTreeNode;
[5729]246          if (constantReplacementNode != null) {
247            visualTree.ToolTip += Environment.NewLine + "Replacement value: " + constantReplacementNode.Value;
248          }
[6108]249        }
[9043]250        if (visualTree != null)
[11086]251          if (changedNodes.ContainsKey(treeNode)) {
252            visualTree.LineColor = Color.DodgerBlue;
253          } else if (treeNode is ConstantTreeNode && foldedNodes.ContainsKey(treeNode)) {
[9043]254            visualTree.LineColor = Color.DarkOrange;
255          }
[3915]256      }
[8980]257      treeChart.RepaintNodes();
[3915]258    }
[3927]259
260    private void btnSimplify_Click(object sender, EventArgs e) {
[8946]261      var simplifier = new SymbolicDataAnalysisExpressionTreeSimplifier();
[5722]262      var simplifiedExpressionTree = simplifier.Simplify(Content.Model.SymbolicExpressionTree);
263      UpdateModel(simplifiedExpressionTree);
[3927]264    }
[6256]265
266    protected abstract void btnOptimizeConstants_Click(object sender, EventArgs e);
[3915]267  }
268}
Note: See TracBrowser for help on using the repository browser.