Free cookie consent management tool by TermsFeed Policy Generator

source: branches/GP.Symbols (TimeLag, Diff, Integral)/HeuristicLab.Problems.DataAnalysis.Views/3.3/Symbolic/InteractiveSymbolicRegressionSolutionSimplifierView.cs @ 5723

Last change on this file since 5723 was 4477, checked in by gkronber, 14 years ago

Merged r4458, r4459,r4462,r4464 from data analysis exploration branch into trunk. #1142

File size: 10.9 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2010 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.Windows.Forms;
27using HeuristicLab.Common;
28using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
29using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Symbols;
30using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views;
31using HeuristicLab.MainForm.WindowsForms;
32using HeuristicLab.Problems.DataAnalysis.Regression.Symbolic;
33using HeuristicLab.Problems.DataAnalysis.Symbolic;
34using HeuristicLab.Problems.DataAnalysis.Symbolic.Symbols;
35
36namespace HeuristicLab.Problems.DataAnalysis.Views.Symbolic {
37  public partial class InteractiveSymbolicRegressionSolutionSimplifierView : AsynchronousContentView {
38    private SymbolicExpressionTree simplifiedExpressionTree;
39    private Dictionary<SymbolicExpressionTreeNode, ConstantTreeNode> replacementNodes;
40    private Dictionary<SymbolicExpressionTreeNode, double> nodeImpacts;
41
42    public InteractiveSymbolicRegressionSolutionSimplifierView() {
43      InitializeComponent();
44      this.replacementNodes = new Dictionary<SymbolicExpressionTreeNode, ConstantTreeNode>();
45      this.nodeImpacts = new Dictionary<SymbolicExpressionTreeNode, double>();
46      this.simplifiedExpressionTree = null;
47      this.Caption = "Interactive Solution Simplifier";
48    }
49
50    public new SymbolicRegressionSolution Content {
51      get { return (SymbolicRegressionSolution)base.Content; }
52      set { base.Content = value; }
53    }
54
55    protected override void RegisterContentEvents() {
56      base.RegisterContentEvents();
57      Content.ModelChanged += new EventHandler(Content_ModelChanged);
58      Content.ProblemDataChanged += new EventHandler(Content_ProblemDataChanged);
59    }
60    protected override void DeregisterContentEvents() {
61      base.DeregisterContentEvents();
62      Content.ModelChanged -= new EventHandler(Content_ModelChanged);
63      Content.ProblemDataChanged -= new EventHandler(Content_ProblemDataChanged);
64    }
65
66    private void Content_ModelChanged(object sender, EventArgs e) {
67      this.CalculateReplacementNodesAndNodeImpacts();
68    }
69    private void Content_ProblemDataChanged(object sender, EventArgs e) {
70      this.CalculateReplacementNodesAndNodeImpacts();
71    }
72
73    protected override void OnContentChanged() {
74      base.OnContentChanged();
75      this.CalculateReplacementNodesAndNodeImpacts();
76      this.viewHost.Content = this.Content;
77    }
78
79    private void CalculateReplacementNodesAndNodeImpacts() {
80      this.replacementNodes.Clear();
81      this.nodeImpacts.Clear();
82      if (Content != null && Content.Model != null && Content.ProblemData != null) {
83        SymbolicSimplifier simplifier = new SymbolicSimplifier();
84        simplifiedExpressionTree = simplifier.Simplify(Content.Model.SymbolicExpressionTree);
85        int samplesStart = Content.ProblemData.TrainingSamplesStart.Value;
86        int samplesEnd = Content.ProblemData.TrainingSamplesEnd.Value;
87        double originalTrainingMeanSquaredError = SymbolicRegressionMeanSquaredErrorEvaluator.Calculate(
88            Content.Model.Interpreter, simplifiedExpressionTree, Content.LowerEstimationLimit, Content.UpperEstimationLimit,
89            Content.ProblemData.Dataset, Content.ProblemData.TargetVariable.Value,
90            Enumerable.Range(samplesStart, samplesEnd - samplesStart));
91
92        this.CalculateReplacementNodes();
93
94        this.CalculateNodeImpacts(simplifiedExpressionTree, simplifiedExpressionTree.Root.SubTrees[0], originalTrainingMeanSquaredError);
95        // show only interesting part of solution
96        this.treeChart.Tree = new SymbolicExpressionTree(simplifiedExpressionTree.Root.SubTrees[0].SubTrees[0]);
97        this.PaintNodeImpacts();
98      }
99    }
100
101    private void CalculateReplacementNodes() {
102      ISymbolicExpressionTreeInterpreter interpreter = Content.Model.Interpreter;
103      IEnumerable<int> trainingSamples = Enumerable.Range(Content.ProblemData.TrainingSamplesStart.Value, Content.ProblemData.TrainingSamplesEnd.Value - Content.ProblemData.TrainingSamplesStart.Value);
104      SymbolicExpressionTreeNode root = new ProgramRootSymbol().CreateTreeNode();
105      SymbolicExpressionTreeNode start = new StartSymbol().CreateTreeNode();
106      root.AddSubTree(start);
107      SymbolicExpressionTree tree = new SymbolicExpressionTree(root);
108      foreach (SymbolicExpressionTreeNode node in this.simplifiedExpressionTree.IterateNodesPrefix()) {
109        if (!(node.Symbol is ProgramRootSymbol || node.Symbol is StartSymbol)) {
110          while (start.SubTrees.Count > 0) start.RemoveSubTree(0);
111          start.AddSubTree(node);
112          double constantTreeNodeValue = interpreter.GetSymbolicExpressionTreeValues(tree, Content.ProblemData.Dataset, trainingSamples).Median();
113          ConstantTreeNode constantTreeNode = MakeConstantTreeNode(constantTreeNodeValue);
114          replacementNodes[node] = constantTreeNode;
115        }
116      }
117    }
118
119    private void CalculateNodeImpacts(SymbolicExpressionTree tree, SymbolicExpressionTreeNode currentTreeNode, double originalTrainingMeanSquaredError) {
120      foreach (SymbolicExpressionTreeNode childNode in currentTreeNode.SubTrees.ToList()) {
121        SwitchNode(currentTreeNode, childNode, replacementNodes[childNode]);
122        int samplesStart = Content.ProblemData.TrainingSamplesStart.Value;
123        int samplesEnd = Content.ProblemData.TrainingSamplesEnd.Value;
124        double newTrainingMeanSquaredError = SymbolicRegressionMeanSquaredErrorEvaluator.Calculate(
125          Content.Model.Interpreter, tree,
126          Content.LowerEstimationLimit, Content.UpperEstimationLimit,
127          Content.ProblemData.Dataset, Content.ProblemData.TargetVariable.Value,
128          Enumerable.Range(samplesStart, samplesEnd - samplesStart));
129        nodeImpacts[childNode] = newTrainingMeanSquaredError / originalTrainingMeanSquaredError;
130        SwitchNode(currentTreeNode, replacementNodes[childNode], childNode);
131        CalculateNodeImpacts(tree, childNode, originalTrainingMeanSquaredError);
132      }
133    }
134
135    private void SwitchNode(SymbolicExpressionTreeNode root, SymbolicExpressionTreeNode oldBranch, SymbolicExpressionTreeNode newBranch) {
136      for (int i = 0; i < root.SubTrees.Count; i++) {
137        if (root.SubTrees[i] == oldBranch) {
138          root.RemoveSubTree(i);
139          root.InsertSubTree(i, newBranch);
140          return;
141        }
142      }
143    }
144
145    private ConstantTreeNode MakeConstantTreeNode(double value) {
146      Constant constant = new Constant();
147      constant.MinValue = value - 1;
148      constant.MaxValue = value + 1;
149      ConstantTreeNode constantTreeNode = (ConstantTreeNode)constant.CreateTreeNode();
150      constantTreeNode.Value = value;
151      return constantTreeNode;
152    }
153
154    private void treeChart_SymbolicExpressionTreeNodeDoubleClicked(object sender, MouseEventArgs e) {
155      VisualSymbolicExpressionTreeNode visualTreeNode = (VisualSymbolicExpressionTreeNode)sender;
156      foreach (SymbolicExpressionTreeNode treeNode in simplifiedExpressionTree.IterateNodesPostfix()) {
157        for (int i = 0; i < treeNode.SubTrees.Count; i++) {
158          SymbolicExpressionTreeNode subTree = treeNode.SubTrees[i];
159          if (subTree == visualTreeNode.SymbolicExpressionTreeNode) {
160            treeNode.RemoveSubTree(i);
161            if (replacementNodes.ContainsKey(subTree))
162              treeNode.InsertSubTree(i, replacementNodes[subTree]);
163            else if (subTree is ConstantTreeNode && replacementNodes.ContainsValue((ConstantTreeNode)subTree))
164              treeNode.InsertSubTree(i, replacementNodes.Where(v => v.Value == subTree).Single().Key);
165            else if (!(subTree is ConstantTreeNode))
166              throw new InvalidOperationException("Could not find replacement value.");
167          }
168        }
169      }
170
171      // show only interesting part of solution
172      this.treeChart.Tree = new SymbolicExpressionTree(simplifiedExpressionTree.Root.SubTrees[0].SubTrees[0]);
173
174      SymbolicExpressionTree tree = (SymbolicExpressionTree)simplifiedExpressionTree.Clone();
175
176      this.Content.ModelChanged -= new EventHandler(Content_ModelChanged);
177      this.Content.Model = new SymbolicRegressionModel(Content.Model.Interpreter, tree);
178      this.Content.ModelChanged += new EventHandler(Content_ModelChanged);
179
180      this.PaintNodeImpacts();
181    }
182
183    private void PaintNodeImpacts() {
184      var impacts = nodeImpacts.Values;
185      double max = impacts.Max();
186      double min = impacts.Min();
187      foreach (SymbolicExpressionTreeNode treeNode in simplifiedExpressionTree.IterateNodesPostfix()) {
188        if (!(treeNode is ConstantTreeNode) && nodeImpacts.ContainsKey(treeNode)) {
189          double impact = this.nodeImpacts[treeNode];
190          double replacementValue = this.replacementNodes[treeNode].Value;
191          VisualSymbolicExpressionTreeNode visualTree = treeChart.GetVisualSymbolicExpressionTreeNode(treeNode);
192
193          if (impact < 1.0) {
194            visualTree.FillColor = Color.FromArgb((int)((1.0 - impact) * 255), Color.Red);
195          } else {
196            visualTree.FillColor = Color.FromArgb((int)((impact - 1.0) / max * 255), Color.Green);
197          }
198          visualTree.ToolTip += Environment.NewLine + "Node impact: " + impact;
199          visualTree.ToolTip += Environment.NewLine + "Replacement value: " + replacementValue;
200        }
201      }
202      this.PaintCollapsedNodes();
203      this.treeChart.Repaint();
204    }
205
206    private void PaintCollapsedNodes() {
207      foreach (SymbolicExpressionTreeNode treeNode in simplifiedExpressionTree.IterateNodesPostfix()) {
208        if (treeNode is ConstantTreeNode && replacementNodes.ContainsValue((ConstantTreeNode)treeNode))
209          this.treeChart.GetVisualSymbolicExpressionTreeNode(treeNode).LineColor = Color.DarkOrange;
210        else {
211          VisualSymbolicExpressionTreeNode visNode = treeChart.GetVisualSymbolicExpressionTreeNode(treeNode);
212          if (visNode != null)
213            visNode.LineColor = Color.Black;
214        }
215      }
216    }
217
218    private void btnSimplify_Click(object sender, EventArgs e) {
219      this.CalculateReplacementNodesAndNodeImpacts();
220    }
221  }
222}
Note: See TracBrowser for help on using the repository browser.