Free cookie consent management tool by TermsFeed Policy Generator

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

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

#2956: Added intermediate of a-priori knowledge

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