Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Problems.DataAnalysis.Views/3.3/Symbolic/InteractiveSymbolicRegressionSolutionSimplifierView.cs @ 3985

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

Fixed statements that modify the list of sub-trees of a SymbolicExpressionTreeNodes directly. #938

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