source: trunk/HeuristicLab.Problems.DataAnalysis.Views/3.4/Regression/RegressionSolutionLineChartViewBase.cs @ 15793

Last change on this file since 15793 was 15793, checked in by fholzing, 20 months ago

#2383: LineCharts will now show a gap instead of hiding NaN/Inf

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