Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2956_apriori_knowledge/HeuristicLab.Problems.DataAnalysis.Symbolic.Views/3.4/InteractiveSymbolicDataAnalysisSolutionSimplifierView.cs @ 16824

Last change on this file since 16824 was 16313, checked in by chaider, 6 years ago

#2956:

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