Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Algorithms.DataAnalysis.Views/3.4/GaussianProcessRegressionSolutionLineChartView.cs @ 8475

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

#1902 fixed bug in calculation of variance in GPR model

File size: 15.0 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2012 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
21using System;
22using System.Collections.Generic;
23using System.Drawing;
24using System.Linq;
25using System.Windows.Forms;
26using System.Windows.Forms.DataVisualization.Charting;
27using HeuristicLab.MainForm;
28using HeuristicLab.Problems.DataAnalysis.Views;
29
30namespace HeuristicLab.Algorithms.DataAnalysis.Views {
31  [View("Line Chart 2")]
32  [Content(typeof(GaussianProcessRegressionSolution))]
33  public partial class GaussianProcessRegressionSolutionLineChartView : DataAnalysisSolutionEvaluationView {
34    private const string TARGETVARIABLE_SERIES_NAME = "Target Variable";
35    private const string ESTIMATEDVALUES_TRAINING_SERIES_NAME = "Estimated Values (training)";
36    private const string ESTIMATEDVALUES_TEST_SERIES_NAME = "Estimated Values (test)";
37    private const string ESTIMATEDVALUES_ALL_SERIES_NAME = "Estimated Values (all samples)";
38
39    public new GaussianProcessRegressionSolution Content {
40      get { return (GaussianProcessRegressionSolution)base.Content; }
41      set { base.Content = value; }
42    }
43
44    public GaussianProcessRegressionSolutionLineChartView()
45      : base() {
46      InitializeComponent();
47      //configure axis
48      this.chart.CustomizeAllChartAreas();
49      this.chart.ChartAreas[0].CursorX.IsUserSelectionEnabled = true;
50      this.chart.ChartAreas[0].AxisX.ScaleView.Zoomable = true;
51      this.chart.ChartAreas[0].AxisX.IsStartedFromZero = true;
52      this.chart.ChartAreas[0].CursorX.Interval = 1;
53
54      this.chart.ChartAreas[0].CursorY.IsUserSelectionEnabled = true;
55      this.chart.ChartAreas[0].AxisY.ScaleView.Zoomable = true;
56      this.chart.ChartAreas[0].CursorY.Interval = 0;
57    }
58
59    private void RedrawChart() {
60      this.chart.Series.Clear();
61      if (Content != null) {
62        this.chart.ChartAreas[0].AxisX.Minimum = 0;
63        this.chart.ChartAreas[0].AxisX.Maximum = Content.ProblemData.Dataset.Rows - 1;
64
65        // training series
66        this.chart.Series.Add(ESTIMATEDVALUES_TRAINING_SERIES_NAME);
67        this.chart.Series[ESTIMATEDVALUES_TRAINING_SERIES_NAME].LegendText = ESTIMATEDVALUES_TRAINING_SERIES_NAME;
68        this.chart.Series[ESTIMATEDVALUES_TRAINING_SERIES_NAME].ChartType = SeriesChartType.Range;
69        this.chart.Series[ESTIMATEDVALUES_TRAINING_SERIES_NAME].EmptyPointStyle.Color = this.chart.Series[ESTIMATEDVALUES_TRAINING_SERIES_NAME].Color;
70        var mean = Content.EstimatedTrainingValues.ToArray();
71        var s2 = Content.EstimatedTrainingVariance.ToArray();
72        var lower = mean.Zip(s2, (m, s) => m - 1.96 * Math.Sqrt(s)).ToArray();
73        var upper = mean.Zip(s2, (m, s) => m + 1.96 * Math.Sqrt(s)).ToArray();
74        this.chart.Series[ESTIMATEDVALUES_TRAINING_SERIES_NAME].Points.DataBindXY(Content.ProblemData.TrainingIndices.ToArray(), lower, upper);
75        this.InsertEmptyPoints(this.chart.Series[ESTIMATEDVALUES_TRAINING_SERIES_NAME]);
76        this.chart.Series[ESTIMATEDVALUES_TRAINING_SERIES_NAME].Tag = Content;
77
78        // test series
79        this.chart.Series.Add(ESTIMATEDVALUES_TEST_SERIES_NAME);
80        this.chart.Series[ESTIMATEDVALUES_TEST_SERIES_NAME].LegendText = ESTIMATEDVALUES_TEST_SERIES_NAME;
81        this.chart.Series[ESTIMATEDVALUES_TEST_SERIES_NAME].ChartType = SeriesChartType.Range;
82
83        mean = Content.EstimatedTestValues.ToArray();
84        s2 = Content.EstimatedTestVariance.ToArray();
85        lower = mean.Zip(s2, (m, s) => m - 1.96 * Math.Sqrt(s)).ToArray();
86        upper = mean.Zip(s2, (m, s) => m + 1.96 * Math.Sqrt(s)).ToArray();
87        this.chart.Series[ESTIMATEDVALUES_TEST_SERIES_NAME].Points.DataBindXY(Content.ProblemData.TestIndices.ToArray(), lower, upper);
88        this.InsertEmptyPoints(this.chart.Series[ESTIMATEDVALUES_TEST_SERIES_NAME]);
89        this.chart.Series[ESTIMATEDVALUES_TEST_SERIES_NAME].Tag = Content;
90
91        // series of remaining points
92        int[] allIndices = Enumerable.Range(0, Content.ProblemData.Dataset.Rows).Except(Content.ProblemData.TrainingIndices).Except(Content.ProblemData.TestIndices).ToArray();
93        var estimatedValues = Content.EstimatedValues.ToArray();
94        List<double> allEstimatedValues = allIndices.Select(index => estimatedValues[index]).ToList();
95        this.chart.Series.Add(ESTIMATEDVALUES_ALL_SERIES_NAME);
96        this.chart.Series[ESTIMATEDVALUES_ALL_SERIES_NAME].LegendText = ESTIMATEDVALUES_ALL_SERIES_NAME;
97        this.chart.Series[ESTIMATEDVALUES_ALL_SERIES_NAME].ChartType = SeriesChartType.Range;
98        this.chart.Series[ESTIMATEDVALUES_ALL_SERIES_NAME].Points.DataBindXY(allIndices, allEstimatedValues);
99        this.InsertEmptyPoints(this.chart.Series[ESTIMATEDVALUES_ALL_SERIES_NAME]);
100        this.chart.Series[ESTIMATEDVALUES_ALL_SERIES_NAME].Tag = Content;
101
102        // target
103        this.chart.Series.Add(TARGETVARIABLE_SERIES_NAME);
104        this.chart.Series[TARGETVARIABLE_SERIES_NAME].LegendText = Content.ProblemData.TargetVariable;
105        this.chart.Series[TARGETVARIABLE_SERIES_NAME].ChartType = SeriesChartType.FastLine;
106        this.chart.Series[TARGETVARIABLE_SERIES_NAME].Points.DataBindXY(Enumerable.Range(0, Content.ProblemData.Dataset.Rows).ToArray(),
107          Content.ProblemData.Dataset.GetDoubleValues(Content.ProblemData.TargetVariable).ToArray());
108
109        this.ToggleSeriesData(this.chart.Series[ESTIMATEDVALUES_ALL_SERIES_NAME]);
110
111        UpdateCursorInterval();
112        this.UpdateStripLines();
113      }
114    }
115
116    private void InsertEmptyPoints(Series series) {
117      int i = 0;
118      while (i < series.Points.Count - 1) {
119        if (series.Points[i].IsEmpty) {
120          ++i;
121          continue;
122        }
123
124        var p1 = series.Points[i];
125        var p2 = series.Points[i + 1];
126        // check for consecutive indices
127        if ((int)p2.XValue - (int)p1.XValue != 1) {
128          // insert an empty point between p1 and p2 so that the line will be invisible (transparent)
129          var p = new DataPoint((int)((p1.XValue + p2.XValue) / 2), 0.0) { IsEmpty = true };
130          series.Points.Insert(i + 1, p);
131        }
132        ++i;
133      }
134    }
135
136    private void UpdateCursorInterval() {
137      var estimatedValues = this.chart.Series[ESTIMATEDVALUES_TRAINING_SERIES_NAME].Points.Select(x => x.YValues[0]).DefaultIfEmpty(1.0);
138      var targetValues = this.chart.Series[TARGETVARIABLE_SERIES_NAME].Points.Select(x => x.YValues[0]).DefaultIfEmpty(1.0);
139      double estimatedValuesRange = estimatedValues.Max() - estimatedValues.Min();
140      double targetValuesRange = targetValues.Max() - targetValues.Min();
141      double interestingValuesRange = Math.Min(Math.Max(targetValuesRange, 1.0), Math.Max(estimatedValuesRange, 1.0));
142      double digits = (int)Math.Log10(interestingValuesRange) - 3;
143      double yZoomInterval = Math.Max(Math.Pow(10, digits), 10E-5);
144      this.chart.ChartAreas[0].CursorY.Interval = yZoomInterval;
145    }
146
147    #region events
148    protected override void RegisterContentEvents() {
149      base.RegisterContentEvents();
150      Content.ModelChanged += new EventHandler(Content_ModelChanged);
151      Content.ProblemDataChanged += new EventHandler(Content_ProblemDataChanged);
152    }
153    protected override void DeregisterContentEvents() {
154      base.DeregisterContentEvents();
155      Content.ModelChanged -= new EventHandler(Content_ModelChanged);
156      Content.ProblemDataChanged -= new EventHandler(Content_ProblemDataChanged);
157    }
158
159    protected override void OnContentChanged() {
160      base.OnContentChanged();
161      RedrawChart();
162    }
163    private void Content_ProblemDataChanged(object sender, EventArgs e) {
164      RedrawChart();
165    }
166    private void Content_ModelChanged(object sender, EventArgs e) {
167      RedrawChart();
168    }
169
170
171
172    private void Chart_MouseDoubleClick(object sender, MouseEventArgs e) {
173      HitTestResult result = chart.HitTest(e.X, e.Y);
174      if (result.ChartArea != null && (result.ChartElementType == ChartElementType.PlottingArea ||
175                                       result.ChartElementType == ChartElementType.Gridlines) ||
176                                       result.ChartElementType == ChartElementType.StripLines) {
177        foreach (var axis in result.ChartArea.Axes)
178          axis.ScaleView.ZoomReset(int.MaxValue);
179      }
180    }
181    #endregion
182
183    private void UpdateStripLines() {
184      this.chart.ChartAreas[0].AxisX.StripLines.Clear();
185
186      int[] attr = new int[Content.ProblemData.Dataset.Rows + 1]; // add a virtual last row that is again empty to simplify loop further down
187      foreach (var row in Content.ProblemData.TrainingIndices) {
188        attr[row] += 1;
189      }
190      foreach (var row in Content.ProblemData.TestIndices) {
191        attr[row] += 2;
192      }
193      int start = 0;
194      int curAttr = attr[start];
195      for (int row = 0; row < attr.Length; row++) {
196        if (attr[row] != curAttr) {
197          switch (curAttr) {
198            case 0: break;
199            case 1:
200              this.CreateAndAddStripLine("Training", start, row, Color.FromArgb(40, Color.Green), Color.Transparent);
201              break;
202            case 2:
203              this.CreateAndAddStripLine("Test", start, row, Color.FromArgb(40, Color.Red), Color.Transparent);
204              break;
205            case 3:
206              this.CreateAndAddStripLine("Training and Test", start, row, Color.FromArgb(40, Color.Green), Color.FromArgb(40, Color.Red), ChartHatchStyle.WideUpwardDiagonal);
207              break;
208            default:
209              // should not happen
210              break;
211          }
212          curAttr = attr[row];
213          start = row;
214        }
215      }
216    }
217
218    private void CreateAndAddStripLine(string title, int start, int end, Color color, Color secondColor, ChartHatchStyle hatchStyle = ChartHatchStyle.None) {
219      StripLine stripLine = new StripLine();
220      stripLine.BackColor = color;
221      stripLine.BackSecondaryColor = secondColor;
222      stripLine.BackHatchStyle = hatchStyle;
223      stripLine.Text = title;
224      stripLine.Font = new Font("Times New Roman", 12, FontStyle.Bold);
225      // strip range is [start .. end] inclusive, but we evaluate [start..end[ (end is exclusive)
226      // the strip should be by one longer (starting at start - 0.5 and ending at end + 0.5)
227      stripLine.StripWidth = end - start;
228      stripLine.IntervalOffset = start - 0.5; // start slightly to the left of the first point to clearly indicate the first point in the partition
229      this.chart.ChartAreas[0].AxisX.StripLines.Add(stripLine);
230    }
231
232    private void ToggleSeriesData(Series series) {
233      if (series.Points.Count > 0) {  //checks if series is shown
234        if (this.chart.Series.Any(s => s != series && s.Points.Count > 0)) {
235          ClearPointsQuick(series.Points);
236        }
237      } else if (Content != null) {
238        string targetVariableName = Content.ProblemData.TargetVariable;
239
240        IEnumerable<int> indices = null;
241        IEnumerable<double> mean = null;
242        IEnumerable<double> s2 = null;
243        double[] lower = null;
244        double[] upper = null;
245        switch (series.Name) {
246          case ESTIMATEDVALUES_ALL_SERIES_NAME:
247            indices = Enumerable.Range(0, Content.ProblemData.Dataset.Rows).Except(Content.ProblemData.TrainingIndices).Except(Content.ProblemData.TestIndices).ToArray();
248            mean = Content.EstimatedValues.ToArray();
249            s2 = Content.EstimatedVariance.ToArray();
250            lower = mean.Zip(s2, (m, s) => m - 1.96 * Math.Sqrt(s)).ToArray();
251            upper = mean.Zip(s2, (m, s) => m + 1.96 * Math.Sqrt(s)).ToArray();
252            lower = indices.Select(index => lower[index]).ToArray();
253            upper = indices.Select(index => upper[index]).ToArray();
254            break;
255          case ESTIMATEDVALUES_TRAINING_SERIES_NAME:
256            indices = Content.ProblemData.TrainingIndices.ToArray();
257            mean = Content.EstimatedTrainingValues.ToArray();
258            s2 = Content.EstimatedTrainingVariance.ToArray();
259            lower = mean.Zip(s2, (m, s) => m - 1.96 * Math.Sqrt(s)).ToArray();
260            upper = mean.Zip(s2, (m, s) => m + 1.96 * Math.Sqrt(s)).ToArray();
261            break;
262          case ESTIMATEDVALUES_TEST_SERIES_NAME:
263            indices = Content.ProblemData.TestIndices.ToArray();
264            mean = Content.EstimatedTestValues.ToArray();
265            s2 = Content.EstimatedTestVariance.ToArray();
266            lower = mean.Zip(s2, (m, s) => m - s).ToArray();
267            upper = mean.Zip(s2, (m, s) => m + s).ToArray();
268            break;
269        }
270        series.Points.DataBindXY(indices, lower, upper);
271        this.InsertEmptyPoints(series);
272        chart.Legends[series.Legend].ForeColor = Color.Black;
273        UpdateCursorInterval();
274        chart.Refresh();
275      }
276    }
277
278    // workaround as per http://stackoverflow.com/questions/5744930/datapointcollection-clear-performance
279    private static void ClearPointsQuick(DataPointCollection points) {
280      points.SuspendUpdates();
281      while (points.Count > 0)
282        points.RemoveAt(points.Count - 1);
283      points.ResumeUpdates();
284    }
285
286    private void chart_MouseMove(object sender, MouseEventArgs e) {
287      HitTestResult result = chart.HitTest(e.X, e.Y);
288      if (result.ChartElementType == ChartElementType.LegendItem && result.Series.Name != TARGETVARIABLE_SERIES_NAME)
289        Cursor = Cursors.Hand;
290      else
291        Cursor = Cursors.Default;
292    }
293    private void chart_MouseDown(object sender, MouseEventArgs e) {
294      HitTestResult result = chart.HitTest(e.X, e.Y);
295      if (result.ChartElementType == ChartElementType.LegendItem && result.Series.Name != TARGETVARIABLE_SERIES_NAME) {
296        ToggleSeriesData(result.Series);
297      }
298    }
299
300    private void chart_CustomizeLegend(object sender, CustomizeLegendEventArgs e) {
301      if (chart.Series.Count != 4) return;
302      e.LegendItems[0].Cells[1].ForeColor = this.chart.Series[TARGETVARIABLE_SERIES_NAME].Points.Count == 0 ? Color.Gray : Color.Black;
303      e.LegendItems[1].Cells[1].ForeColor = this.chart.Series[ESTIMATEDVALUES_TRAINING_SERIES_NAME].Points.Count == 0 ? Color.Gray : Color.Black;
304      e.LegendItems[2].Cells[1].ForeColor = this.chart.Series[ESTIMATEDVALUES_TEST_SERIES_NAME].Points.Count == 0 ? Color.Gray : Color.Black;
305      e.LegendItems[3].Cells[1].ForeColor = this.chart.Series[ESTIMATEDVALUES_ALL_SERIES_NAME].Points.Count == 0 ? Color.Gray : Color.Black;
306    }
307  }
308}
Note: See TracBrowser for help on using the repository browser.