Free cookie consent management tool by TermsFeed Policy Generator

source: branches/DataAnalysis/HeuristicLab.Problems.DataAnalysis.MultiVariate.TimeSeriesPrognosis.Views/3.3/InteractiveSymbolicTimeSeriesPrognosisSolutionSimplifierView.cs @ 4464

Last change on this file since 4464 was 4464, checked in by gkronber, 12 years ago

Fixed bugs in views for manual simplification of symbolic models. #1142

File size: 12.5 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.Symbolic;
33using HeuristicLab.Problems.DataAnalysis.Symbolic.Symbols;
34using HeuristicLab.Problems.DataAnalysis.MultiVariate.TimeSeriesPrognosis.Symbolic;
35using HeuristicLab.Problems.DataAnalysis.MultiVariate.TimeSeriesPrognosis.Symbolic.Interfaces;
36using HeuristicLab.Problems.DataAnalysis.MultiVariate.TimeSeriesPrognosis.Symbolic.Evaluators;
37using HeuristicLab.Data;
38
39namespace HeuristicLab.Problems.DataAnalysis.MultiVariate.TimeSeriesPrognosis.Views {
40  public partial class InteractiveSymbolicTimeSeriesPrognosisSolutionSimplifierView : AsynchronousContentView {
41    private SymbolicExpressionTree simplifiedExpressionTree;
42    private ISymbolicTimeSeriesExpressionInterpreter interpreter;
43    private DoubleArray lowerEstimationLimit;
44    private DoubleArray upperEstimationLimit;
45    private string conditionVariableName;
46    private IEnumerable<string> targetVariables;
47    private int horizon;
48    private Dictionary<SymbolicExpressionTreeNode, ConstantTreeNode> replacementNodes;
49    private Dictionary<SymbolicExpressionTreeNode, double> nodeImpacts;
50
51    public InteractiveSymbolicTimeSeriesPrognosisSolutionSimplifierView() {
52      InitializeComponent();
53      this.replacementNodes = new Dictionary<SymbolicExpressionTreeNode, ConstantTreeNode>();
54      this.nodeImpacts = new Dictionary<SymbolicExpressionTreeNode, double>();
55      this.simplifiedExpressionTree = null;
56      this.Caption = "Interactive Solution Simplifier";
57    }
58
59    public new SymbolicTimeSeriesPrognosisSolution Content {
60      get { return (SymbolicTimeSeriesPrognosisSolution)base.Content; }
61      set { base.Content = value; }
62    }
63
64    protected override void RegisterContentEvents() {
65      base.RegisterContentEvents();
66      Content.ModelChanged += new EventHandler(Content_ModelChanged);
67      Content.ProblemDataChanged += new EventHandler(Content_ProblemDataChanged);
68    }
69    protected override void DeregisterContentEvents() {
70      base.DeregisterContentEvents();
71      Content.ModelChanged -= new EventHandler(Content_ModelChanged);
72      Content.ProblemDataChanged -= new EventHandler(Content_ProblemDataChanged);
73    }
74
75    private void Content_ModelChanged(object sender, EventArgs e) {
76      this.CalculateReplacementNodesAndNodeImpacts();
77    }
78    private void Content_ProblemDataChanged(object sender, EventArgs e) {
79      this.CalculateReplacementNodesAndNodeImpacts();
80    }
81
82    protected override void OnContentChanged() {
83      base.OnContentChanged();
84      this.CalculateReplacementNodesAndNodeImpacts();
85      this.viewHost.Content = this.Content;
86    }
87
88    private void CalculateReplacementNodesAndNodeImpacts() {
89      this.replacementNodes.Clear();
90      this.nodeImpacts.Clear();
91      if (Content != null && Content.Model != null && Content.ProblemData != null) {
92        SymbolicSimplifier simplifier = new SymbolicSimplifier();
93        simplifiedExpressionTree = simplifier.Simplify(Content.Model.SymbolicExpressionTree);
94        int samplesStart = Content.ProblemData.TrainingSamplesStart.Value;
95        int samplesEnd = Content.ProblemData.TrainingSamplesEnd.Value;
96
97        double[] alpha, beta;
98        double quality;
99        conditionVariableName = Content.ConditionalEvaluationVariable;
100        targetVariables = Content.ProblemData.TargetVariables.CheckedItems.Select(x => x.Value.Value);
101        int nTargetVariables = Content.ProblemData.TargetVariables.CheckedItems.Count();
102        lowerEstimationLimit = new DoubleArray(Enumerable.Repeat(double.NegativeInfinity, nTargetVariables).ToArray());
103        upperEstimationLimit = new DoubleArray(Enumerable.Repeat(double.PositiveInfinity, nTargetVariables).ToArray());
104        interpreter = Content.Model.Interpreter;
105        horizon = Content.Horizon;
106        IEnumerable<int> rows = Enumerable.Range(samplesStart, samplesEnd - samplesStart);
107        SymbolicTimeSeriesPrognosisScaledNormalizedMseEvaluator.CalculateScalingParameters(simplifiedExpressionTree,
108          Content.ProblemData, interpreter,
109          conditionVariableName, rows,
110          out beta, out alpha);
111
112        quality = SymbolicTimeSeriesPrognosisScaledNormalizedMseEvaluator.Evaluate(simplifiedExpressionTree, Content.ProblemData, interpreter,
113          conditionVariableName, rows, horizon,
114          lowerEstimationLimit, upperEstimationLimit,
115          beta, alpha);
116
117        this.CalculateReplacementNodes();
118
119        this.CalculateNodeImpacts(simplifiedExpressionTree, simplifiedExpressionTree.Root, quality);
120        // show only interesing part
121        this.treeChart.Tree = new SymbolicExpressionTree(simplifiedExpressionTree.Root.SubTrees[0]);
122        this.PaintNodeImpacts();
123      }
124    }
125
126    private void CalculateReplacementNodes() {
127      IEnumerable<int> trainingSamples = Enumerable.Range(Content.ProblemData.TrainingSamplesStart.Value, Content.ProblemData.TrainingSamplesEnd.Value - Content.ProblemData.TrainingSamplesStart.Value);
128      SymbolicExpressionTreeNode root = new ProgramRootSymbol().CreateTreeNode();
129      SymbolicExpressionTreeNode start = new StartSymbol().CreateTreeNode();
130      root.AddSubTree(start);
131      SymbolicExpressionTree tree = new SymbolicExpressionTree(root);
132      foreach (SymbolicExpressionTreeNode node in this.simplifiedExpressionTree.IterateNodesPrefix()) {
133        if (!(node.Symbol is StartSymbol || node.Symbol is ProgramRootSymbol)) {
134          while (start.SubTrees.Count > 0) start.RemoveSubTree(0);
135          start.AddSubTree(node);
136          double constantTreeNodeValue = interpreter.GetSymbolicExpressionTreeValues(tree, Content.ProblemData.Dataset, targetVariables, trainingSamples, 1).Select(x => x[0]).Median();
137          ConstantTreeNode constantTreeNode = MakeConstantTreeNode(constantTreeNodeValue);
138          replacementNodes[node] = constantTreeNode;
139        }
140      }
141    }
142
143    private void CalculateNodeImpacts(SymbolicExpressionTree tree, SymbolicExpressionTreeNode currentTreeNode, double originalQuality) {
144      foreach (SymbolicExpressionTreeNode childNode in currentTreeNode.SubTrees.ToList()) {
145        if (!(childNode.Symbol is StartSymbol || childNode.Symbol is ProgramRootSymbol)) {
146          SwitchNode(currentTreeNode, childNode, replacementNodes[childNode]);
147          int samplesStart = Content.ProblemData.TrainingSamplesStart.Value;
148          int samplesEnd = Content.ProblemData.TrainingSamplesEnd.Value;
149          double[] alpha;
150          double[] beta;
151          int horizon = Content.Horizon;
152          IEnumerable<int> rows = Enumerable.Range(samplesStart, samplesEnd - samplesStart);         
153          SymbolicTimeSeriesPrognosisScaledNormalizedMseEvaluator.CalculateScalingParameters(tree,
154            Content.ProblemData, interpreter,
155            conditionVariableName, rows,
156            out beta, out alpha);
157
158          double newQuality = SymbolicTimeSeriesPrognosisScaledNormalizedMseEvaluator.Evaluate(tree, Content.ProblemData, interpreter,
159            conditionVariableName, rows, horizon,
160            lowerEstimationLimit, upperEstimationLimit,
161            beta, alpha);
162
163          nodeImpacts[childNode] = newQuality / originalQuality;
164          SwitchNode(currentTreeNode, replacementNodes[childNode], childNode);
165        }
166        CalculateNodeImpacts(tree, childNode, originalQuality);
167      }
168    }
169
170    private void SwitchNode(SymbolicExpressionTreeNode root, SymbolicExpressionTreeNode oldBranch, SymbolicExpressionTreeNode newBranch) {
171      for (int i = 0; i < root.SubTrees.Count; i++) {
172        if (root.SubTrees[i] == oldBranch) {
173          root.RemoveSubTree(i);
174          root.InsertSubTree(i, newBranch);
175          return;
176        }
177      }
178    }
179
180    private ConstantTreeNode MakeConstantTreeNode(double value) {
181      Constant constant = new Constant();
182      constant.MinValue = value - 1;
183      constant.MaxValue = value + 1;
184      ConstantTreeNode constantTreeNode = (ConstantTreeNode)constant.CreateTreeNode();
185      constantTreeNode.Value = value;
186      return constantTreeNode;
187    }
188
189    private void treeChart_SymbolicExpressionTreeNodeDoubleClicked(object sender, MouseEventArgs e) {
190      VisualSymbolicExpressionTreeNode visualTreeNode = (VisualSymbolicExpressionTreeNode)sender;
191      foreach (SymbolicExpressionTreeNode treeNode in simplifiedExpressionTree.IterateNodesPostfix()) {
192        for (int i = 0; i < treeNode.SubTrees.Count; i++) {
193          SymbolicExpressionTreeNode subTree = treeNode.SubTrees[i];
194          if (subTree == visualTreeNode.SymbolicExpressionTreeNode) {
195            if (replacementNodes.ContainsKey(subTree)) {
196              treeNode.RemoveSubTree(i);
197              treeNode.InsertSubTree(i, replacementNodes[subTree]);
198            } else if (subTree is ConstantTreeNode && replacementNodes.ContainsValue((ConstantTreeNode)subTree)) {
199              treeNode.RemoveSubTree(i);
200              treeNode.InsertSubTree(i, replacementNodes.Where(v => v.Value == subTree).Single().Key);
201            }
202            // if no replacement value is known do nothing
203          }
204        }
205      }
206      // show only interesting part
207      this.treeChart.Tree = new SymbolicExpressionTree(simplifiedExpressionTree.Root.SubTrees[0]);
208
209      SymbolicExpressionTree tree = (SymbolicExpressionTree)simplifiedExpressionTree.Clone();
210
211      this.Content.ModelChanged -= new EventHandler(Content_ModelChanged);
212      this.Content.Model = new SymbolicTimeSeriesPrognosisModel(Content.Model.Interpreter, tree);
213      this.Content.ModelChanged += new EventHandler(Content_ModelChanged);
214
215      this.PaintNodeImpacts();
216    }
217
218    private void PaintNodeImpacts() {
219      var impacts = nodeImpacts.Values;
220      double max = impacts.Max();
221      double min = impacts.Min();
222      foreach (SymbolicExpressionTreeNode treeNode in simplifiedExpressionTree.IterateNodesPostfix()) {
223        if (!(treeNode is ConstantTreeNode) && nodeImpacts.ContainsKey(treeNode)) {
224          double impact = nodeImpacts[treeNode];
225          double replacementValue = replacementNodes[treeNode].Value;
226          VisualSymbolicExpressionTreeNode visualTree = treeChart.GetVisualSymbolicExpressionTreeNode(treeNode);
227
228          if (impact < 1.0) {
229            visualTree.FillColor = Color.FromArgb((int)((1.0 - impact) * 255), Color.Red);
230          } else {
231            visualTree.FillColor = Color.FromArgb((int)((impact - 1.0) / max * 255), Color.Green);
232          }
233          visualTree.ToolTip += Environment.NewLine + "Node impact: " + impact;
234          visualTree.ToolTip += Environment.NewLine + "Replacement value: " + replacementValue;
235        }
236      }
237      this.PaintCollapsedNodes();
238      this.treeChart.Repaint();
239    }
240
241    private void PaintCollapsedNodes() {
242      foreach (SymbolicExpressionTreeNode treeNode in simplifiedExpressionTree.IterateNodesPostfix()) {
243        if (treeNode is ConstantTreeNode && replacementNodes.ContainsValue((ConstantTreeNode)treeNode))
244          this.treeChart.GetVisualSymbolicExpressionTreeNode(treeNode).LineColor = Color.DarkOrange;
245        else {
246          VisualSymbolicExpressionTreeNode visNode = treeChart.GetVisualSymbolicExpressionTreeNode(treeNode);
247          if (visNode != null)
248            visNode.LineColor = Color.Black;
249        }
250      }
251    }
252
253    private void btnSimplify_Click(object sender, EventArgs e) {
254      this.CalculateReplacementNodesAndNodeImpacts();
255    }
256  }
257}
Note: See TracBrowser for help on using the repository browser.