Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2520_PersistenceReintegration/HeuristicLab.Problems.DataAnalysis.Symbolic.Views/3.4/InteractiveSymbolicDataAnalysisSolutionSimplifierView.cs @ 16713

Last change on this file since 16713 was 16453, checked in by jkarder, 6 years ago

#2520: updated year of copyrights

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