Free cookie consent management tool by TermsFeed Policy Generator

source: branches/DataAnalysis/HeuristicLab.Problems.DataAnalysis.Views/3.3/Symbolic/InteractiveSymbolicRegressionSolutionSimplifierView.cs @ 4462

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

Changed symbolic simplifier to work for multi-variate models and return a symbolic expression tree that can be directly evaluated. #1142

File size: 10.7 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        SymbolicExpressionTree tree = (SymbolicExpressionTree)simplifiedExpressionTree.Clone();
88        double originalTrainingMeanSquaredError = SymbolicRegressionMeanSquaredErrorEvaluator.Calculate(
89            Content.Model.Interpreter, tree, Content.LowerEstimationLimit, Content.UpperEstimationLimit,
90            Content.ProblemData.Dataset, Content.ProblemData.TargetVariable.Value,
91            Enumerable.Range(samplesStart, samplesEnd - samplesStart));
92
93        this.CalculateReplacementNodes();
94
95        this.CalculateNodeImpacts(tree, tree.Root.SubTrees[0], originalTrainingMeanSquaredError);
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      this.treeChart.Tree = new SymbolicExpressionTree(simplifiedExpressionTree.Root.SubTrees[0].SubTrees[0]);
171
172      SymbolicExpressionTree tree = (SymbolicExpressionTree)simplifiedExpressionTree.Clone();
173
174      this.Content.ModelChanged -= new EventHandler(Content_ModelChanged);
175      this.Content.Model = new SymbolicRegressionModel(Content.Model.Interpreter, tree);
176      this.Content.ModelChanged += new EventHandler(Content_ModelChanged);
177
178      this.PaintNodeImpacts();
179    }
180
181    private void PaintNodeImpacts() {
182      var impacts = nodeImpacts.Values;
183      double max = impacts.Max();
184      double min = impacts.Min();
185      foreach (SymbolicExpressionTreeNode treeNode in simplifiedExpressionTree.IterateNodesPostfix()) {
186        if (!(treeNode is ConstantTreeNode) && nodeImpacts.ContainsKey(treeNode)) {
187          double impact = this.nodeImpacts[treeNode];
188          double replacementValue = this.replacementNodes[treeNode].Value;
189          VisualSymbolicExpressionTreeNode visualTree = treeChart.GetVisualSymbolicExpressionTreeNode(treeNode);
190
191          if (impact < 1.0) {
192            visualTree.FillColor = Color.FromArgb((int)((1.0 - impact) * 255), Color.Red);
193          } else {
194            visualTree.FillColor = Color.FromArgb((int)((impact - 1.0) / max * 255), Color.Green);
195          }
196          visualTree.ToolTip += Environment.NewLine + "Node impact: " + impact;
197          visualTree.ToolTip += Environment.NewLine + "Replacement value: " + replacementValue;
198        }
199      }
200      this.PaintCollapsedNodes();
201      this.treeChart.Repaint();
202    }
203
204    private void PaintCollapsedNodes() {
205      foreach (SymbolicExpressionTreeNode treeNode in simplifiedExpressionTree.IterateNodesPostfix()) {
206        if (treeNode is ConstantTreeNode && replacementNodes.ContainsValue((ConstantTreeNode)treeNode))
207          this.treeChart.GetVisualSymbolicExpressionTreeNode(treeNode).LineColor = Color.DarkOrange;
208        else
209          this.treeChart.GetVisualSymbolicExpressionTreeNode(treeNode).LineColor = Color.Black;
210      }
211    }
212
213    private void btnSimplify_Click(object sender, EventArgs e) {
214      this.CalculateReplacementNodesAndNodeImpacts();
215    }
216  }
217}
Note: See TracBrowser for help on using the repository browser.