source: branches/2971_named_intervals/HeuristicLab.Problems.DataAnalysis.Symbolic.Views/3.4/InteractiveSymbolicDataAnalysisSolutionSimplifierView.cs @ 17207

Last change on this file since 17207 was 17207, checked in by gkronber, 6 weeks ago

#2971: merged r17180:17184 from trunk to branch

File size: 15.7 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 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.Threading;
27using System.Threading.Tasks;
28using System.Windows.Forms;
29using HeuristicLab.Common;
30using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
31using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views;
32using HeuristicLab.MainForm;
33using HeuristicLab.MainForm.WindowsForms;
34
35namespace HeuristicLab.Problems.DataAnalysis.Symbolic.Views {
36  public abstract partial class InteractiveSymbolicDataAnalysisSolutionSimplifierView : AsynchronousContentView {
37    private readonly Dictionary<ISymbolicExpressionTreeNode, ISymbolicExpressionTreeNode> foldedNodes = new Dictionary<ISymbolicExpressionTreeNode, ISymbolicExpressionTreeNode>();
38    private readonly Dictionary<ISymbolicExpressionTreeNode, ISymbolicExpressionTreeNode> changedNodes = new Dictionary<ISymbolicExpressionTreeNode, ISymbolicExpressionTreeNode>();
39    private readonly Dictionary<ISymbolicExpressionTreeNode, Interval> nodeIntervals = new Dictionary<ISymbolicExpressionTreeNode, Interval>();
40    private readonly Dictionary<ISymbolicExpressionTreeNode, double> nodeImpacts = new Dictionary<ISymbolicExpressionTreeNode, double>();
41
42    private readonly ISymbolicDataAnalysisSolutionImpactValuesCalculator impactCalculator;
43
44    private readonly Progress progress = new Progress();
45    private CancellationTokenSource cancellationTokenSource;
46
47    private enum TreeState { Valid, Invalid }
48    private TreeState treeState;
49
50    protected InteractiveSymbolicDataAnalysisSolutionSimplifierView(ISymbolicDataAnalysisSolutionImpactValuesCalculator impactCalculator) {
51      InitializeComponent();
52      this.Caption = "Interactive Solution Simplifier";
53      this.impactCalculator = impactCalculator;
54
55      // initialize the tree modifier that will be used to perform edit operations over the tree
56      treeChart.ModifyTree = Modify;
57    }
58
59    /// <summary>
60    /// Remove, Replace or Insert subtrees
61    /// </summary>
62    /// <param name="tree">The symbolic expression tree</param>
63    /// <param name="parent">The insertion point (ie, the parent node who will receive a new child)</param>
64    /// <param name="oldChild">The subtree to be replaced</param>
65    /// <param name="newChild">The replacement subtree</param>
66    /// <param name="removeSubtree">Flag used to indicate if whole subtrees should be removed (default behavior), or just the subtree root</param>
67    private void Modify(ISymbolicExpressionTree tree, ISymbolicExpressionTreeNode parent,
68      ISymbolicExpressionTreeNode oldChild, ISymbolicExpressionTreeNode newChild, bool removeSubtree = true) {
69      if (oldChild == null && newChild == null)
70        throw new ArgumentNullException("Cannot deduce operation type from the arguments. Please provide non null operands.");
71      if (oldChild == null) {
72        // insertion operation
73        parent.AddSubtree(newChild);
74        newChild.Parent = parent;
75      } else if (newChild == null) {
76        // removal operation
77        parent.RemoveSubtree(parent.IndexOfSubtree(oldChild));
78        if (!removeSubtree) {
79          for (int i = oldChild.SubtreeCount - 1; i >= 0; --i) {
80            var subtree = oldChild.GetSubtree(i);
81            oldChild.RemoveSubtree(i);
82            parent.AddSubtree(subtree);
83          }
84        }
85      } else {
86        // replacement operation
87        var replacementIndex = parent.IndexOfSubtree(oldChild);
88        parent.RemoveSubtree(replacementIndex);
89        parent.InsertSubtree(replacementIndex, newChild);
90        newChild.Parent = parent;
91        if (changedNodes.ContainsKey(oldChild)) {
92          changedNodes.Add(newChild, changedNodes[oldChild]); // so that on double click the original node is restored
93          changedNodes.Remove(oldChild);
94        } else {
95          changedNodes.Add(newChild, oldChild);
96        }
97      }
98      treeState = IsValid(tree) ? TreeState.Valid : TreeState.Invalid;
99      switch (treeState) {
100        case TreeState.Valid:
101          this.grpViewHost.Enabled = true;
102          UpdateModel(Content.Model.SymbolicExpressionTree);
103          break;
104        case TreeState.Invalid:
105          this.grpViewHost.Enabled = false;
106          break;
107      }
108    }
109
110    // the optimizer always assumes 2 children for multiplication and addition nodes
111    // thus, we enforce that the tree stays valid so that the constant optimization won't throw an exception
112    // by returning 2 as the minimum allowed arity for addition and multiplication symbols
113    private readonly Func<ISymbol, int> GetMinArity = symbol => {
114      var min = symbol.MinimumArity;
115      if (symbol is Multiplication || symbol is Division) return Math.Max(2, min);
116      return min;
117    };
118    private bool IsValid(ISymbolicExpressionTree tree) {
119      treeChart.Tree = tree;
120      treeChart.Repaint();
121      // check if all nodes have a legal arity
122      var nodes = tree.IterateNodesPostfix().ToList();
123      bool valid = !nodes.Any(node => node.SubtreeCount < GetMinArity(node.Symbol) || node.SubtreeCount > node.Symbol.MaximumArity);
124
125      if (valid) {
126        // check if all variables are contained in the dataset
127        var variables = new HashSet<string>(Content.ProblemData.Dataset.DoubleVariables);
128        valid = nodes.OfType<VariableTreeNode>().All(x => variables.Contains(x.VariableName));
129      }
130
131      if (valid) {
132        btnOptimizeConstants.Enabled = true;
133        btnSimplify.Enabled = true;
134        treeStatusValue.Visible = false;
135      } else {
136        btnOptimizeConstants.Enabled = false;
137        btnSimplify.Enabled = false;
138        treeStatusValue.Visible = true;
139      }
140      this.Refresh();
141      return valid;
142    }
143
144    public new ISymbolicDataAnalysisSolution Content {
145      get { return (ISymbolicDataAnalysisSolution)base.Content; }
146      set { base.Content = value; }
147    }
148
149    protected override void RegisterContentEvents() {
150      base.RegisterContentEvents();
151      Content.ModelChanged += Content_Changed;
152      Content.ProblemDataChanged += Content_Changed;
153      treeChart.Repainted += treeChart_Repainted;
154      Progress.ShowOnControl(grpSimplify, progress);
155      progress.StopRequested += progress_StopRequested;
156    }
157    protected override void DeregisterContentEvents() {
158      base.DeregisterContentEvents();
159      Content.ModelChanged -= Content_Changed;
160      Content.ProblemDataChanged -= Content_Changed;
161      treeChart.Repainted -= treeChart_Repainted;
162      Progress.HideFromControl(grpSimplify, false);
163      progress.StopRequested -= progress_StopRequested;
164    }
165
166    private void Content_Changed(object sender, EventArgs e) {
167      UpdateView();
168    }
169
170    protected override void OnContentChanged() {
171      base.OnContentChanged();
172      foldedNodes.Clear();
173      changedNodes.Clear();
174      nodeIntervals.Clear();
175      nodeImpacts.Clear();
176      UpdateView();
177      viewHost.Content = this.Content;
178    }
179
180    private void treeChart_Repainted(object sender, EventArgs e) {
181      if (nodeImpacts != null && nodeImpacts.Count > 0)
182        PaintNodeImpacts();
183    }
184
185    private void progress_StopRequested(object sender, EventArgs e) {
186      cancellationTokenSource.Cancel();
187    }
188
189    private async void UpdateView() {
190      if (Content == null || Content.Model == null || Content.ProblemData == null) return;
191      var tree = Content.Model.SymbolicExpressionTree;
192      treeChart.Tree = tree.Root.SubtreeCount > 1 ? new SymbolicExpressionTree(tree.Root) : new SymbolicExpressionTree(tree.Root.GetSubtree(0).GetSubtree(0));
193
194      progress.Start("Calculate Impact and Replacement Values ...");
195      progress.CanBeStopped = true;
196      cancellationTokenSource = new CancellationTokenSource();
197
198      var impactAndReplacementValues = await Task.Run(() => CalculateImpactAndReplacementValues(tree));
199
200      try {
201        await Task.Delay(500, cancellationTokenSource.Token); // wait for progressbar to finish animation
202      } catch (OperationCanceledException) { }
203      var replacementValues = impactAndReplacementValues.ToDictionary(x => x.Key, x => x.Value.Item2);
204      foreach (var pair in replacementValues.Where(pair => !(pair.Key is ConstantTreeNode))) {
205        foldedNodes[pair.Key] = MakeConstantTreeNode(pair.Value);
206      }
207 
208      foreach (var kvp in impactAndReplacementValues) {
209        nodeImpacts[kvp.Key] = kvp.Value.Item1;
210      }
211
212      var regressionProblemData = Content.ProblemData as IRegressionProblemData;
213      if (regressionProblemData != null) {
214        var interpreter = new IntervalInterpreter();
215        var variableRanges = regressionProblemData.VariableRanges.GetIntervals();
216        IDictionary<ISymbolicExpressionTreeNode, Interval> intervals;
217        interpreter.GetSymbolicExpressionTreeIntervals(tree, variableRanges, out intervals);
218        foreach (var kvp in intervals) {
219          nodeIntervals[kvp.Key] = kvp.Value;
220        }
221      }
222     
223
224      progress.Finish();
225      progress.CanBeStopped = false;
226      PaintNodeImpacts();
227    }
228
229    protected virtual Dictionary<ISymbolicExpressionTreeNode, Tuple<double, double>> CalculateImpactAndReplacementValues(ISymbolicExpressionTree tree) {
230      var impactAndReplacementValues = new Dictionary<ISymbolicExpressionTreeNode, Tuple<double, double>>();
231      foreach (var node in tree.Root.GetSubtree(0).GetSubtree(0).IterateNodesPrefix()) {
232        if (progress.ProgressState == ProgressState.StopRequested) continue;
233        double impactValue, replacementValue, newQualityForImpactsCalculation;
234        impactCalculator.CalculateImpactAndReplacementValues(Content.Model, node, Content.ProblemData, Content.ProblemData.TrainingIndices, out impactValue, out replacementValue, out newQualityForImpactsCalculation);
235        double newProgressValue = progress.ProgressValue + 1.0 / (tree.Length - 2);
236        progress.ProgressValue = Math.Min(newProgressValue, 1);
237        impactAndReplacementValues.Add(node, new Tuple<double, double>(impactValue, replacementValue));
238      }
239      return impactAndReplacementValues;
240    }
241
242    protected abstract void UpdateModel(ISymbolicExpressionTree tree);
243
244    protected virtual ISymbolicExpressionTree OptimizeConstants(ISymbolicExpressionTree tree, IProgress progress) {
245      return tree;
246    }
247
248    private static ConstantTreeNode MakeConstantTreeNode(double value) {
249      var constant = new Constant { MinValue = value - 1, MaxValue = value + 1 };
250      var constantTreeNode = (ConstantTreeNode)constant.CreateTreeNode();
251      constantTreeNode.Value = value;
252      return constantTreeNode;
253    }
254
255    private void treeChart_SymbolicExpressionTreeNodeDoubleClicked(object sender, MouseEventArgs e) {
256      if (treeState == TreeState.Invalid) return;
257      var visualNode = (VisualTreeNode<ISymbolicExpressionTreeNode>)sender;
258      if (visualNode.Content == null) { throw new Exception("VisualNode content cannot be null."); }
259      var symbExprTreeNode = (SymbolicExpressionTreeNode)visualNode.Content;
260      var tree = Content.Model.SymbolicExpressionTree;
261      var parent = symbExprTreeNode.Parent;
262      int indexOfSubtree = parent.IndexOfSubtree(symbExprTreeNode);
263      if (changedNodes.ContainsKey(symbExprTreeNode)) {
264        // undo node change
265        parent.RemoveSubtree(indexOfSubtree);
266        var originalNode = changedNodes[symbExprTreeNode];
267        parent.InsertSubtree(indexOfSubtree, originalNode);
268        changedNodes.Remove(symbExprTreeNode);
269      } else if (foldedNodes.ContainsKey(symbExprTreeNode)) {
270        // undo node folding
271        SwitchNodeWithReplacementNode(parent, indexOfSubtree);
272      }
273      UpdateModel(tree);
274    }
275
276    private void SwitchNodeWithReplacementNode(ISymbolicExpressionTreeNode parent, int subTreeIndex) {
277      ISymbolicExpressionTreeNode subTree = parent.GetSubtree(subTreeIndex);
278      if (foldedNodes.ContainsKey(subTree)) {
279        parent.RemoveSubtree(subTreeIndex);
280        var replacementNode = foldedNodes[subTree];
281        parent.InsertSubtree(subTreeIndex, replacementNode);
282        // exchange key and value
283        foldedNodes.Remove(subTree);
284        foldedNodes.Add(replacementNode, subTree);
285      }
286    }
287
288    private void PaintNodeImpacts() {
289      var impacts = nodeImpacts.Values;
290      double max = impacts.Max();
291      double min = impacts.Min();
292      foreach (ISymbolicExpressionTreeNode treeNode in Content.Model.SymbolicExpressionTree.IterateNodesPostfix()) {
293        VisualTreeNode<ISymbolicExpressionTreeNode> visualTree = treeChart.GetVisualSymbolicExpressionTreeNode(treeNode);
294
295        if (!(treeNode is ConstantTreeNode) && nodeImpacts.ContainsKey(treeNode)) {
296          visualTree.ToolTip = visualTree.Content.ToString();
297          double impact = nodeImpacts[treeNode];
298
299          // impact = 0 if no change
300          // impact < 0 if new solution is better
301          // impact > 0 if new solution is worse
302          if (impact < 0.0) {
303            // min is guaranteed to be < 0
304            visualTree.FillColor = Color.FromArgb((int)(impact / min * 255), Color.Red);
305          } else if (impact.IsAlmost(0.0)) {
306            visualTree.FillColor = Color.White;
307          } else {
308            // max is guaranteed to be > 0
309            visualTree.FillColor = Color.FromArgb((int)(impact / max * 255), Color.Green);
310          }
311          visualTree.ToolTip += Environment.NewLine + "Node impact: " + impact;
312          var constantReplacementNode = foldedNodes[treeNode] as ConstantTreeNode;
313          if (constantReplacementNode != null) {
314            visualTree.ToolTip += Environment.NewLine + "Replacement value: " + constantReplacementNode.Value;
315          }
316        }
317        if (visualTree != null) {
318          if (nodeIntervals.ContainsKey(treeNode))
319            visualTree.ToolTip += String.Format($"{Environment.NewLine}Intervals: [{nodeIntervals[treeNode].LowerBound:G5} ... {nodeIntervals[treeNode].UpperBound:G5}]");
320          if (changedNodes.ContainsKey(treeNode)) {
321            visualTree.LineColor = Color.DodgerBlue;
322          } else if (treeNode is ConstantTreeNode && foldedNodes.ContainsKey(treeNode)) {
323            visualTree.LineColor = Color.DarkOrange;
324          }
325        }
326      }
327      treeChart.RepaintNodes();
328    }
329
330    private void btnSimplify_Click(object sender, EventArgs e) {
331      var simplifiedExpressionTree = TreeSimplifier.Simplify(Content.Model.SymbolicExpressionTree);
332      UpdateModel(simplifiedExpressionTree);
333    }
334
335    private async void btnOptimizeConstants_Click(object sender, EventArgs e) {
336      progress.Start("Optimizing Constants ...");
337      var tree = (ISymbolicExpressionTree)Content.Model.SymbolicExpressionTree.Clone();
338      var newTree = await Task.Run(() => OptimizeConstants(tree, progress));
339      await Task.Delay(500); // wait for progressbar to finish animation
340      UpdateModel(newTree); // UpdateModel calls Progress.Finish (via Content_Changed)
341    }
342  }
343}
Note: See TracBrowser for help on using the repository browser.