Free cookie consent management tool by TermsFeed Policy Generator

source: branches/3040_VectorBasedGP/HeuristicLab.Problems.DataAnalysis.Symbolic.Views/3.4/InteractiveSymbolicDataAnalysisSolutionSimplifierView.cs @ 18242

Last change on this file since 18242 was 17825, checked in by pfleck, 4 years ago

#3040 Merged trunk into branch.

File size: 20.2 KB
RevLine 
[3915]1#region License Information
2/* HeuristicLab
[17180]3 * Copyright (C) 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;
[16430]26using System.Threading;
[15371]27using System.Threading.Tasks;
[3915]28using System.Windows.Forms;
29using HeuristicLab.Common;
30using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
[4068]31using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views;
[15371]32using HeuristicLab.MainForm;
[3915]33using HeuristicLab.MainForm.WindowsForms;
34
[5699]35namespace HeuristicLab.Problems.DataAnalysis.Symbolic.Views {
36  public abstract partial class InteractiveSymbolicDataAnalysisSolutionSimplifierView : AsynchronousContentView {
[17825]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>();
[11086]41
[15371]42    private readonly ISymbolicDataAnalysisSolutionImpactValuesCalculator impactCalculator;
43
[16430]44    private readonly Progress progress = new Progress();
45    private CancellationTokenSource cancellationTokenSource;
[15371]46
[9006]47    private enum TreeState { Valid, Invalid }
[11086]48    private TreeState treeState;
[3915]49
[15371]50    protected InteractiveSymbolicDataAnalysisSolutionSimplifierView(ISymbolicDataAnalysisSolutionImpactValuesCalculator impactCalculator) {
[3915]51      InitializeComponent();
52      this.Caption = "Interactive Solution Simplifier";
[15371]53      this.impactCalculator = impactCalculator;
[11086]54
55      // initialize the tree modifier that will be used to perform edit operations over the tree
56      treeChart.ModifyTree = Modify;
[3915]57    }
58
[11086]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();
[14494]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
[11086]125      if (valid) {
[14494]126        // check if all variables are contained in the dataset
[17593]127        var variables = new HashSet<string>(Content.ProblemData.Dataset.VariableNames);
[14494]128        valid = nodes.OfType<VariableTreeNode>().All(x => variables.Contains(x.VariableName));
129      }
130
131      if (valid) {
[11086]132        btnOptimizeConstants.Enabled = true;
[17633]133        btnVectorOptimizeConstants.Enabled = true;
134        nudLearningRate.Enabled = true;
[17786]135        btnUnrollingVectorOptimizeConstants.Enabled = true;
136        btnDiffSharpOptimizeConstants.Enabled = true;
[11086]137        btnSimplify.Enabled = true;
[11111]138        treeStatusValue.Visible = false;
[11086]139      } else {
140        btnOptimizeConstants.Enabled = false;
[17633]141        btnVectorOptimizeConstants.Enabled = false;
142        nudLearningRate.Enabled = false;
[17786]143        btnUnrollingVectorOptimizeConstants.Enabled = false;
144        btnDiffSharpOptimizeConstants.Enabled = false;
[11086]145        btnSimplify.Enabled = false;
[11111]146        treeStatusValue.Visible = true;
[11086]147      }
148      this.Refresh();
149      return valid;
150    }
151
[5699]152    public new ISymbolicDataAnalysisSolution Content {
153      get { return (ISymbolicDataAnalysisSolution)base.Content; }
[3915]154      set { base.Content = value; }
155    }
156
157    protected override void RegisterContentEvents() {
158      base.RegisterContentEvents();
[8946]159      Content.ModelChanged += Content_Changed;
160      Content.ProblemDataChanged += Content_Changed;
[10564]161      treeChart.Repainted += treeChart_Repainted;
[16430]162      Progress.ShowOnControl(grpSimplify, progress);
163      progress.StopRequested += progress_StopRequested;
[3915]164    }
165    protected override void DeregisterContentEvents() {
166      base.DeregisterContentEvents();
[8946]167      Content.ModelChanged -= Content_Changed;
168      Content.ProblemDataChanged -= Content_Changed;
[10564]169      treeChart.Repainted -= treeChart_Repainted;
[16430]170      Progress.HideFromControl(grpSimplify, false);
171      progress.StopRequested -= progress_StopRequested;
[3915]172    }
173
[8946]174    private void Content_Changed(object sender, EventArgs e) {
175      UpdateView();
[17456]176      SetEnabledStateOfControls();
[3915]177    }
[5699]178
[3915]179    protected override void OnContentChanged() {
180      base.OnContentChanged();
[17825]181      foldedNodes.Clear();
182      changedNodes.Clear();
183      nodeIntervals.Clear();
184      nodeImpacts.Clear();
[8946]185      UpdateView();
186      viewHost.Content = this.Content;
[3915]187    }
188
[10564]189    private void treeChart_Repainted(object sender, EventArgs e) {
190      if (nodeImpacts != null && nodeImpacts.Count > 0)
191        PaintNodeImpacts();
192    }
193
[16430]194    private void progress_StopRequested(object sender, EventArgs e) {
195      cancellationTokenSource.Cancel();
196    }
197
[15371]198    private async void UpdateView() {
[8946]199      if (Content == null || Content.Model == null || Content.ProblemData == null) return;
200      var tree = Content.Model.SymbolicExpressionTree;
[8990]201      treeChart.Tree = tree.Root.SubtreeCount > 1 ? new SymbolicExpressionTree(tree.Root) : new SymbolicExpressionTree(tree.Root.GetSubtree(0).GetSubtree(0));
[3915]202
[15400]203      progress.Start("Calculate Impact and Replacement Values ...");
[17456]204      cancellationTokenSource = new CancellationTokenSource();
[16430]205      progress.CanBeStopped = true;
206      try {
[17456]207        var impactAndReplacementValues = await Task.Run(() => CalculateImpactAndReplacementValues(tree));
208        try {
209          await Task.Delay(300, cancellationTokenSource.Token); // wait for progressbar to finish animation
210        } catch (OperationCanceledException) { }
211
212        var replacementValues = impactAndReplacementValues.ToDictionary(x => x.Key, x => x.Value.Item2);
213        foreach (var pair in replacementValues.Where(pair => !(pair.Key is ConstantTreeNode))) {
214          foldedNodes[pair.Key] = MakeConstantTreeNode(pair.Value);
215        }
[17825]216       
217        foreach (var pair in impactAndReplacementValues) {
218          nodeImpacts[pair.Key] = pair.Value.Item1;
219        }
[17456]220
[17825]221        if (IntervalInterpreter.IsCompatible(tree)) {
222          var regressionProblemData = Content.ProblemData as IRegressionProblemData;
223          if (regressionProblemData != null) {
224            var interpreter = new IntervalInterpreter();
225            var variableRanges = regressionProblemData.VariableRanges.GetReadonlyDictionary();
226            IDictionary<ISymbolicExpressionTreeNode, Interval> intervals;
227            interpreter.GetSymbolicExpressionTreeIntervals(tree, variableRanges, out intervals);
228            foreach (var kvp in intervals) {
229              nodeIntervals[kvp.Key] = kvp.Value;
230            }
231          }
232        }
[17456]233      } finally {
234        progress.Finish();
[8946]235      }
[17456]236
[16430]237      progress.CanBeStopped = false;
[8946]238      PaintNodeImpacts();
[3915]239    }
240
[15371]241    protected virtual Dictionary<ISymbolicExpressionTreeNode, Tuple<double, double>> CalculateImpactAndReplacementValues(ISymbolicExpressionTree tree) {
242      var impactAndReplacementValues = new Dictionary<ISymbolicExpressionTreeNode, Tuple<double, double>>();
243      foreach (var node in tree.Root.GetSubtree(0).GetSubtree(0).IterateNodesPrefix()) {
[16430]244        if (progress.ProgressState == ProgressState.StopRequested) continue;
[15371]245        double impactValue, replacementValue, newQualityForImpactsCalculation;
246        impactCalculator.CalculateImpactAndReplacementValues(Content.Model, node, Content.ProblemData, Content.ProblemData.TrainingIndices, out impactValue, out replacementValue, out newQualityForImpactsCalculation);
247        double newProgressValue = progress.ProgressValue + 1.0 / (tree.Length - 2);
248        progress.ProgressValue = Math.Min(newProgressValue, 1);
249        impactAndReplacementValues.Add(node, new Tuple<double, double>(impactValue, replacementValue));
250      }
251      return impactAndReplacementValues;
252    }
253
[17786]254    protected virtual void UpdateModel(ISymbolicExpressionTree tree) { }
[3915]255
[17472]256    protected virtual ISymbolicExpressionTree OptimizeConstants(ISymbolicExpressionTree tree, CancellationToken cancellationToken, IProgress progress) {
[15400]257      return tree;
[15371]258    }
[17633]259    protected virtual ISymbolicExpressionTree VectorOptimizeConstants(ISymbolicExpressionTree tree, CancellationToken cancellationToken, IProgress progress) {
260      return tree;
261    }
[17786]262    protected virtual ISymbolicExpressionTree UnrollingVectorOptimizeConstants(ISymbolicExpressionTree tree, CancellationToken cancellationToken, IProgress progress) {
263      return tree;
264    }
265    protected virtual ISymbolicExpressionTree DiffSharpVectorOptimizeConstants(ISymbolicExpressionTree tree, CancellationToken cancellationToken, IProgress progress) {
266      return tree;
267    }
[15371]268
[8946]269    private static ConstantTreeNode MakeConstantTreeNode(double value) {
270      var constant = new Constant { MinValue = value - 1, MaxValue = value + 1 };
271      var constantTreeNode = (ConstantTreeNode)constant.CreateTreeNode();
[3915]272      constantTreeNode.Value = value;
273      return constantTreeNode;
274    }
275
276    private void treeChart_SymbolicExpressionTreeNodeDoubleClicked(object sender, MouseEventArgs e) {
[11086]277      if (treeState == TreeState.Invalid) return;
[10521]278      var visualNode = (VisualTreeNode<ISymbolicExpressionTreeNode>)sender;
[11086]279      if (visualNode.Content == null) { throw new Exception("VisualNode content cannot be null."); }
[10521]280      var symbExprTreeNode = (SymbolicExpressionTreeNode)visualNode.Content;
[11086]281      var tree = Content.Model.SymbolicExpressionTree;
[9006]282      var parent = symbExprTreeNode.Parent;
283      int indexOfSubtree = parent.IndexOfSubtree(symbExprTreeNode);
[11086]284      if (changedNodes.ContainsKey(symbExprTreeNode)) {
285        // undo node change
286        parent.RemoveSubtree(indexOfSubtree);
287        var originalNode = changedNodes[symbExprTreeNode];
288        parent.InsertSubtree(indexOfSubtree, originalNode);
289        changedNodes.Remove(symbExprTreeNode);
290      } else if (foldedNodes.ContainsKey(symbExprTreeNode)) {
291        // undo node folding
292        SwitchNodeWithReplacementNode(parent, indexOfSubtree);
293      }
294      UpdateModel(tree);
[3915]295    }
296
[5729]297    private void SwitchNodeWithReplacementNode(ISymbolicExpressionTreeNode parent, int subTreeIndex) {
[5736]298      ISymbolicExpressionTreeNode subTree = parent.GetSubtree(subTreeIndex);
[9006]299      if (foldedNodes.ContainsKey(subTree)) {
[10799]300        parent.RemoveSubtree(subTreeIndex);
[9006]301        var replacementNode = foldedNodes[subTree];
[5736]302        parent.InsertSubtree(subTreeIndex, replacementNode);
[5729]303        // exchange key and value
[9006]304        foldedNodes.Remove(subTree);
305        foldedNodes.Add(replacementNode, subTree);
[5729]306      }
[5455]307    }
308
[3915]309    private void PaintNodeImpacts() {
310      var impacts = nodeImpacts.Values;
311      double max = impacts.Max();
312      double min = impacts.Min();
[11086]313      foreach (ISymbolicExpressionTreeNode treeNode in Content.Model.SymbolicExpressionTree.IterateNodesPostfix()) {
[10521]314        VisualTreeNode<ISymbolicExpressionTreeNode> visualTree = treeChart.GetVisualSymbolicExpressionTreeNode(treeNode);
[8946]315
[4477]316        if (!(treeNode is ConstantTreeNode) && nodeImpacts.ContainsKey(treeNode)) {
[11086]317          visualTree.ToolTip = visualTree.Content.ToString();
[5729]318          double impact = nodeImpacts[treeNode];
[5722]319
[5717]320          // impact = 0 if no change
321          // impact < 0 if new solution is better
322          // impact > 0 if new solution is worse
323          if (impact < 0.0) {
[5729]324            // min is guaranteed to be < 0
[5717]325            visualTree.FillColor = Color.FromArgb((int)(impact / min * 255), Color.Red);
[5729]326          } else if (impact.IsAlmost(0.0)) {
327            visualTree.FillColor = Color.White;
[5717]328          } else {
[5729]329            // max is guaranteed to be > 0
[5717]330            visualTree.FillColor = Color.FromArgb((int)(impact / max * 255), Color.Green);
331          }
[3915]332          visualTree.ToolTip += Environment.NewLine + "Node impact: " + impact;
[9006]333          var constantReplacementNode = foldedNodes[treeNode] as ConstantTreeNode;
[5729]334          if (constantReplacementNode != null) {
335            visualTree.ToolTip += Environment.NewLine + "Replacement value: " + constantReplacementNode.Value;
336          }
[6108]337        }
[17825]338        if (visualTree != null) {
339          if (nodeIntervals.ContainsKey(treeNode))
340            visualTree.ToolTip += String.Format($"{Environment.NewLine}Intervals: [{nodeIntervals[treeNode].LowerBound:G5} ... {nodeIntervals[treeNode].UpperBound:G5}]");
[11086]341          if (changedNodes.ContainsKey(treeNode)) {
342            visualTree.LineColor = Color.DodgerBlue;
343          } else if (treeNode is ConstantTreeNode && foldedNodes.ContainsKey(treeNode)) {
[9043]344            visualTree.LineColor = Color.DarkOrange;
345          }
[17825]346        }
[3915]347      }
[8980]348      treeChart.RepaintNodes();
[3915]349    }
[3927]350
351    private void btnSimplify_Click(object sender, EventArgs e) {
[17593]352      if (Content.Model.Interpreter is SymbolicDataAnalysisExpressionTreeVectorInterpreter interpreter) { // TODO: Own interface for data-dependent node-types-interpreter?
[17604]353        var simplifier = new VectorTreeSimplifier(interpreter);
[17593]354        var simplifiedExpressionTree = simplifier.Simplify(Content.Model.SymbolicExpressionTree);
355        UpdateModel(simplifiedExpressionTree);
356      } else {
357        var simplifiedExpressionTree = TreeSimplifier.Simplify(Content.Model.SymbolicExpressionTree);
358        UpdateModel(simplifiedExpressionTree);
359      }
[3927]360    }
[6256]361
[15371]362    private async void btnOptimizeConstants_Click(object sender, EventArgs e) {
[15400]363      progress.Start("Optimizing Constants ...");
[17456]364      cancellationTokenSource = new CancellationTokenSource();
365      progress.CanBeStopped = true;
366      try {
367        var tree = (ISymbolicExpressionTree)Content.Model.SymbolicExpressionTree.Clone();
368
[17472]369        var newTree = await Task.Run(() => OptimizeConstants(tree, cancellationTokenSource.Token, progress), cancellationTokenSource.Token);
[17456]370        try {
371          await Task.Delay(300, cancellationTokenSource.Token); // wait for progressbar to finish animation
372        } catch (OperationCanceledException) { }
373        UpdateModel(newTree); // triggers progress.Finish after calculating the node impacts when model is changed
374      } catch {
375        progress.Finish();
376      }
[15371]377    }
[17633]378
379    private async void btnVectorOptimizeConstants_Click(object sender, EventArgs e) {
380      progress.Start("Optimizing Constants ...");
381      cancellationTokenSource = new CancellationTokenSource();
382      progress.CanBeStopped = true;
383      try {
384        var tree = (ISymbolicExpressionTree)Content.Model.SymbolicExpressionTree.Clone();
385
386        var newTree = await Task.Run(() => VectorOptimizeConstants(tree, cancellationTokenSource.Token, progress), cancellationTokenSource.Token);
387        try {
388          await Task.Delay(300, cancellationTokenSource.Token); // wait for progressbar to finish animation
389        } catch (OperationCanceledException) { }
390        UpdateModel(newTree); // triggers progress.Finish after calculating the node impacts when model is changed
391      } catch {
392        progress.Finish();
393      }
394    }
[17786]395
396    private async void btnUnrollingVectorOptimizeConstants_Click(object sender, EventArgs e) {
397      progress.Start("Optimizing Constants ...");
398      cancellationTokenSource = new CancellationTokenSource();
399      progress.CanBeStopped = true;
400      try {
401        var tree = (ISymbolicExpressionTree)Content.Model.SymbolicExpressionTree.Clone();
402
403        var newTree = await Task.Run(() => UnrollingVectorOptimizeConstants(tree, cancellationTokenSource.Token, progress), cancellationTokenSource.Token);
404        try {
405          await Task.Delay(300, cancellationTokenSource.Token); // wait for progressbar to finish animation
406        } catch (OperationCanceledException) { }
407        UpdateModel(newTree); // triggers progress.Finish after calculating the node impacts when model is changed
408      } catch {
409        progress.Finish();
410      }
411    }
412
413    private async void btnDiffSharpOptimizeConstants_Click(object sender, EventArgs e) {
414      progress.Start("Optimizing Constants ...");
415      cancellationTokenSource = new CancellationTokenSource();
416      progress.CanBeStopped = true;
417      try {
418        var tree = (ISymbolicExpressionTree)Content.Model.SymbolicExpressionTree.Clone();
419
420        var newTree = await Task.Run(() => DiffSharpVectorOptimizeConstants(tree, cancellationTokenSource.Token, progress), cancellationTokenSource.Token);
421        try {
422          await Task.Delay(300, cancellationTokenSource.Token); // wait for progressbar to finish animation
423        } catch (OperationCanceledException) { }
424        UpdateModel(newTree); // triggers progress.Finish after calculating the node impacts when model is changed
425      } catch {
426        progress.Finish();
427      }
428    }
[3915]429  }
430}
Note: See TracBrowser for help on using the repository browser.