Free cookie consent management tool by TermsFeed Policy Generator

source: branches/dataset-ids-2695/HeuristicLab.Problems.DataAnalysis.Views/3.4/Regression/RegressionSolutionLineChartViewBase.cs @ 15297

Last change on this file since 15297 was 15297, checked in by gkronber, 7 years ago

#2695: added a parameter to DataAnalysisProblemData to select an id column and extended RegressionLinechartViewBase to show the id on the xAxis

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