Free cookie consent management tool by TermsFeed Policy Generator

source: branches/Sliding Window GP/HeuristicLab.Problems.DataAnalysis.Symbolic.Views/3.4/SlidingWindowBestSolutionsCollectionView.cs @ 10402

Last change on this file since 10402 was 10402, checked in by bburlacu, 11 years ago

#1837: Added missing license information headers. Added storable constructors and changed properties in SlidingWindowBestSolutionsCollection to return IEnumerables instead of Lists.

File size: 7.1 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2014 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.Linq;
25using System.Windows.Forms;
26using HeuristicLab.Core.Views;
27using HeuristicLab.Data;
28using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
29using HeuristicLab.MainForm;
30using HeuristicLab.Optimization;
31using HeuristicLab.Optimization.Views;
32
33namespace HeuristicLab.Problems.DataAnalysis.Symbolic.Views {
34  [View("Sliding Window Best Solutions View")]
35  [Content(typeof(SlidingWindowBestSolutionsCollection), true)]
36  public partial class SlidingWindowBestSolutionsCollectionView : ItemView {
37    public new SlidingWindowBestSolutionsCollection Content {
38      get { return (SlidingWindowBestSolutionsCollection)base.Content; }
39      set { base.Content = value; }
40    }
41    public SlidingWindowBestSolutionsCollectionView() {
42      InitializeComponent();
43
44      qualityMeasure = (int)QualityMeasures.PEARSON;
45    }
46
47    enum QualityMeasures { PEARSON, MSE };
48
49    private int qualityMeasure;
50
51    protected override void DeregisterContentEvents() {
52      // TODO: Deregister your event handlers here
53      enhancedStringConvertibleMatrixView.DataGridView.CellDoubleClick -= enhancedStringConvertibleMatrixView_cellDoubleClick;
54      base.DeregisterContentEvents();
55    }
56
57    protected override void RegisterContentEvents() {
58      base.RegisterContentEvents();
59      enhancedStringConvertibleMatrixView.DataGridView.CellDoubleClick += enhancedStringConvertibleMatrixView_cellDoubleClick;
60      // TODO: Register your event handlers here
61    }
62
63    public void enhancedStringConvertibleMatrixView_cellDoubleClick(object sender, DataGridViewCellEventArgs e) {
64      var dataGridView = (DataGridView)sender;
65      var cell = dataGridView.SelectedCells[0];
66      var bestSolutions = Content.BestSolutions.ToList();
67      var tree = bestSolutions[cell.RowIndex];
68      var model = Content.CreateModel(tree, Content.Interpreter);
69      var solution = Content.CreateSolution(model, Content.ProblemData);
70      var result = new Result("Sliding Window Solution", solution);
71      var view = MainFormManager.MainForm.ShowContent(result, typeof(ResultView));
72      if (view != null) {
73        view.ReadOnly = ReadOnly;
74        view.Locked = Locked;
75      }
76    }
77
78    #region Event Handlers (Content)
79    // TODO: Put event handlers of the content here
80    #endregion
81
82    protected override void OnContentChanged() {
83      base.OnContentChanged();
84      if (Content == null) {
85        // TODO: Add code when content has been changed and is null
86      } else {
87        // TODO: Add code when content has been changed and is not null
88        UpdateQualitiesMap();
89      }
90    }
91
92    protected override void SetEnabledStateOfControls() {
93      base.SetEnabledStateOfControls();
94      // TODO: Enable or disable controls based on whether the content is null or the view is set readonly
95    }
96
97    #region Event Handlers (child controls)
98    // TODO: Put event handlers of child controls here.
99    #endregion
100
101    private void comboBox1_SelectedIndexChanged(object sender, System.EventArgs e) {
102      var combobox = (ComboBox)sender;
103      switch ((string)combobox.SelectedItem) {
104        case "Pearson R2": {
105            qualityMeasure = (int)QualityMeasures.PEARSON;
106            break;
107          }
108        case "Mean Squared Error": {
109            qualityMeasure = (int)QualityMeasures.MSE;
110            break;
111          }
112      }
113      UpdateQualitiesMap();
114    }
115
116    private void UpdateQualitiesMap() {
117      var bestSolutions = Content.BestSolutions.ToList();
118      var swPositions = Content.SlidingWindowPositions.ToList();
119      var qualitiesMap = new DoubleMatrix(bestSolutions.Count, swPositions.Count + 1);
120      qualitiesMap.ColumnNames = Content.SlidingWindowPositions.Select(x => x.Start + "-" + x.End).Concat(new List<string> { "Training" });
121      qualitiesMap.RowNames = Enumerable.Range(1, bestSolutions.Count).Select(x => "M" + x);
122      double min = 0, max = 0;
123
124      for (int i = 0; i < qualitiesMap.Columns - 1; ++i) {
125        var pos = swPositions[i];
126        var rows = Enumerable.Range(pos.Start, pos.End - pos.Start).ToList();
127
128        for (int j = 0; j < qualitiesMap.Rows; ++j) {
129          var tree = bestSolutions[j];
130          var q = CalculateQuality(tree, rows);
131          if (min > q) min = q;
132          if (max < q) max = q;
133          qualitiesMap[j, i] = q;
134        }
135      }
136      // deal separately with the last column which represents the whole training partition interval
137      for (int j = 0; j < qualitiesMap.Rows; ++j) {
138        var tree = bestSolutions[j];
139        var q = CalculateQuality(tree, Content.ProblemData.TrainingIndices);
140        if (min > q) min = q;
141        if (max < q) max = q;
142        qualitiesMap[j, qualitiesMap.Columns - 1] = q;
143      }
144
145      enhancedStringConvertibleMatrixView.Minimum = min;
146      enhancedStringConvertibleMatrixView.Maximum = max;
147      enhancedStringConvertibleMatrixView.Content = qualitiesMap;
148    }
149
150    private string GetTargetVariable(IDataAnalysisProblemData problemData) {
151      var regressionProblemData = problemData as IRegressionProblemData;
152      var classificationProblemData = problemData as IClassificationProblemData;
153      if (regressionProblemData != null) return regressionProblemData.TargetVariable;
154      if (classificationProblemData != null) return classificationProblemData.TargetVariable;
155      throw new NotSupportedException();
156    }
157
158    private double CalculateQuality(ISymbolicExpressionTree tree, IEnumerable<int> rows) {
159      var estimatedValues = Content.Interpreter.GetSymbolicExpressionTreeValues(tree, Content.ProblemData.Dataset, rows);
160      var originalValues = Content.ProblemData.Dataset.GetDoubleValues(GetTargetVariable(Content.ProblemData), rows);
161      double quality = 0;
162      var errorState = new OnlineCalculatorError();
163      switch ((QualityMeasures)qualityMeasure) {
164        case QualityMeasures.PEARSON:
165          quality = OnlinePearsonsRSquaredCalculator.Calculate(estimatedValues, originalValues, out errorState);
166          break;
167        case QualityMeasures.MSE:
168          quality = OnlineMeanSquaredErrorCalculator.Calculate(estimatedValues, originalValues, out errorState);
169          break;
170      }
171      return errorState == OnlineCalculatorError.None ? quality : double.NaN;
172    }
173  }
174}
Note: See TracBrowser for help on using the repository browser.