Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2971_named_intervals/HeuristicLab.Problems.DataAnalysis.Views/3.4/Regression/RegressionSolutionLineChartViewBase.cs @ 18190

Last change on this file since 18190 was 17208, checked in by gkronber, 5 years ago

#2971: merged r17180:17184 from trunk to branch

File size: 14.5 KB
RevLine 
[3408]1#region License Information
2/* HeuristicLab
[17208]3 * Copyright (C) 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();
[15810]75        var targetValues = Content.ProblemData.Dataset.GetDoubleValues(Content.ProblemData.TargetVariable);
[15785]76
77
[15810]78        this.chart.Series[TARGETVARIABLE_SERIES_NAME].Points.DataBindXY(rows.ToArray(), targetValues.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();
[15810]166      double targetValuesRange = targetValues.Where(v => !double.IsInfinity(v) && !double.IsNaN(v)).Max() -
167                                 targetValues.Where(v => !double.IsInfinity(v) && !double.IsNaN(v)).Min();
[3707]168      double interestingValuesRange = Math.Min(Math.Max(targetValuesRange, 1.0), Math.Max(estimatedValuesRange, 1.0));
169      double digits = (int)Math.Log10(interestingValuesRange) - 3;
170      double yZoomInterval = Math.Max(Math.Pow(10, digits), 10E-5);
171      this.chart.ChartAreas[0].CursorY.Interval = yZoomInterval;
172    }
173
[3442]174    #region events
175    protected override void RegisterContentEvents() {
176      base.RegisterContentEvents();
[5663]177      Content.ModelChanged += new EventHandler(Content_ModelChanged);
[3442]178      Content.ProblemDataChanged += new EventHandler(Content_ProblemDataChanged);
[3408]179    }
[3442]180    protected override void DeregisterContentEvents() {
181      base.DeregisterContentEvents();
[5663]182      Content.ModelChanged -= new EventHandler(Content_ModelChanged);
[3442]183      Content.ProblemDataChanged -= new EventHandler(Content_ProblemDataChanged);
[3408]184    }
185
[6679]186    protected override void OnContentChanged() {
187      base.OnContentChanged();
188      RedrawChart();
189    }
[3916]190    private void Content_ProblemDataChanged(object sender, EventArgs e) {
[3462]191      RedrawChart();
[3408]192    }
[5663]193    private void Content_ModelChanged(object sender, EventArgs e) {
[3462]194      RedrawChart();
[3442]195    }
196
[5006]197
[6679]198
[5006]199    private void Chart_MouseDoubleClick(object sender, MouseEventArgs e) {
200      HitTestResult result = chart.HitTest(e.X, e.Y);
201      if (result.ChartArea != null && (result.ChartElementType == ChartElementType.PlottingArea ||
202                                       result.ChartElementType == ChartElementType.Gridlines) ||
203                                       result.ChartElementType == ChartElementType.StripLines) {
204        foreach (var axis in result.ChartArea.Axes)
205          axis.ScaleView.ZoomReset(int.MaxValue);
206      }
207    }
[3442]208    #endregion
[3408]209
210    private void UpdateStripLines() {
211      this.chart.ChartAreas[0].AxisX.StripLines.Clear();
[6238]212
213      int[] attr = new int[Content.ProblemData.Dataset.Rows + 1]; // add a virtual last row that is again empty to simplify loop further down
[8139]214      foreach (var row in Content.ProblemData.TrainingIndices) {
[6238]215        attr[row] += 1;
216      }
[8139]217      foreach (var row in Content.ProblemData.TestIndices) {
[6238]218        attr[row] += 2;
219      }
220      int start = 0;
221      int curAttr = attr[start];
222      for (int row = 0; row < attr.Length; row++) {
223        if (attr[row] != curAttr) {
224          switch (curAttr) {
225            case 0: break;
226            case 1:
227              this.CreateAndAddStripLine("Training", start, row, Color.FromArgb(40, Color.Green), Color.Transparent);
228              break;
229            case 2:
230              this.CreateAndAddStripLine("Test", start, row, Color.FromArgb(40, Color.Red), Color.Transparent);
231              break;
232            case 3:
233              this.CreateAndAddStripLine("Training and Test", start, row, Color.FromArgb(40, Color.Green), Color.FromArgb(40, Color.Red), ChartHatchStyle.WideUpwardDiagonal);
234              break;
235            default:
236              // should not happen
237              break;
238          }
239          curAttr = attr[row];
240          start = row;
241        }
242      }
[3408]243    }
244
[6238]245    private void CreateAndAddStripLine(string title, int start, int end, Color color, Color secondColor, ChartHatchStyle hatchStyle = ChartHatchStyle.None) {
[3408]246      StripLine stripLine = new StripLine();
[6238]247      stripLine.BackColor = color;
248      stripLine.BackSecondaryColor = secondColor;
249      stripLine.BackHatchStyle = hatchStyle;
[3408]250      stripLine.Text = title;
251      stripLine.Font = new Font("Times New Roman", 12, FontStyle.Bold);
[6252]252      // strip range is [start .. end] inclusive, but we evaluate [start..end[ (end is exclusive)
253      // the strip should be by one longer (starting at start - 0.5 and ending at end + 0.5)
[6520]254      stripLine.StripWidth = end - start;
[6252]255      stripLine.IntervalOffset = start - 0.5; // start slightly to the left of the first point to clearly indicate the first point in the partition
[3408]256      this.chart.ChartAreas[0].AxisX.StripLines.Add(stripLine);
257    }
[6679]258
[14531]259    public void ToggleSeriesData(Series series) {
[6679]260      if (series.Points.Count > 0) {  //checks if series is shown
261        if (this.chart.Series.Any(s => s != series && s.Points.Count > 0)) {
[7406]262          ClearPointsQuick(series.Points);
[6679]263        }
264      } else if (Content != null) {
265
[14422]266        int[] indices = null;
[8485]267        double[] predictedValues = null;
[6679]268        switch (series.Name) {
269          case ESTIMATEDVALUES_ALL_SERIES_NAME:
[14422]270            GetAllValuesSeries(out indices, out predictedValues);
[6679]271            break;
272          case ESTIMATEDVALUES_TRAINING_SERIES_NAME:
[14422]273            GetTrainingSeries(out indices, out predictedValues);
[6679]274            break;
275          case ESTIMATEDVALUES_TEST_SERIES_NAME:
[14422]276            GetTestSeries(out indices, out predictedValues);
[6679]277            break;
278        }
[8485]279        if (predictedValues.Length > 0) {
280          series.Points.DataBindXY(indices, predictedValues);
281          this.InsertEmptyPoints(series);
282        }
[6679]283        chart.Legends[series.Legend].ForeColor = Color.Black;
284        UpdateCursorInterval();
[6775]285        chart.Refresh();
[6679]286      }
287    }
288
[7406]289    // workaround as per http://stackoverflow.com/questions/5744930/datapointcollection-clear-performance
290    private static void ClearPointsQuick(DataPointCollection points) {
291      points.SuspendUpdates();
292      while (points.Count > 0)
293        points.RemoveAt(points.Count - 1);
294      points.ResumeUpdates();
295    }
296
[6679]297    private void chart_MouseMove(object sender, MouseEventArgs e) {
298      HitTestResult result = chart.HitTest(e.X, e.Y);
299      if (result.ChartElementType == ChartElementType.LegendItem && result.Series.Name != TARGETVARIABLE_SERIES_NAME)
300        Cursor = Cursors.Hand;
301      else
302        Cursor = Cursors.Default;
303    }
304    private void chart_MouseDown(object sender, MouseEventArgs e) {
305      HitTestResult result = chart.HitTest(e.X, e.Y);
306      if (result.ChartElementType == ChartElementType.LegendItem && result.Series.Name != TARGETVARIABLE_SERIES_NAME) {
307        ToggleSeriesData(result.Series);
308      }
309    }
310
311    private void chart_CustomizeLegend(object sender, CustomizeLegendEventArgs e) {
312      if (chart.Series.Count != 4) return;
313      e.LegendItems[0].Cells[1].ForeColor = this.chart.Series[TARGETVARIABLE_SERIES_NAME].Points.Count == 0 ? Color.Gray : Color.Black;
314      e.LegendItems[1].Cells[1].ForeColor = this.chart.Series[ESTIMATEDVALUES_TRAINING_SERIES_NAME].Points.Count == 0 ? Color.Gray : Color.Black;
315      e.LegendItems[2].Cells[1].ForeColor = this.chart.Series[ESTIMATEDVALUES_TEST_SERIES_NAME].Points.Count == 0 ? Color.Gray : Color.Black;
316      e.LegendItems[3].Cells[1].ForeColor = this.chart.Series[ESTIMATEDVALUES_ALL_SERIES_NAME].Points.Count == 0 ? Color.Gray : Color.Black;
317    }
[3408]318  }
319}
Note: See TracBrowser for help on using the repository browser.