Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Problems.DataAnalysis.Views/3.4/Regression/RegressionSolutionLineChartView.cs @ 14483

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

#2718: suggestion for residuals line chart

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