Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 15787 was 15787, checked in by fholzing, 6 years ago

#2383: Made the filtering a little bit more robust

File size: 14.8 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;
[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))]
[14486]33  public abstract partial class RegressionSolutionLineChartViewBase : 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
[14486]44    protected RegressionSolutionLineChartViewBase()
[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
[14486]59    protected abstract void GetTrainingSeries(out int[] idx, out double[] y);
[14422]60
[14486]61    protected abstract void GetTestSeries(out int[] x, out double[] y);
[14422]62
[14486]63    protected abstract void GetAllValuesSeries(out int[] x, out double[] y);
[14422]64
[14483]65    protected virtual void RedrawChart() {
[3442]66      this.chart.Series.Clear();
[4011]67      if (Content != null) {
[6238]68        this.chart.ChartAreas[0].AxisX.Minimum = 0;
69        this.chart.ChartAreas[0].AxisX.Maximum = Content.ProblemData.Dataset.Rows - 1;
70
[4011]71        this.chart.Series.Add(TARGETVARIABLE_SERIES_NAME);
[14255]72        this.chart.Series[TARGETVARIABLE_SERIES_NAME].LegendText = TARGETVARIABLE_SERIES_NAME;
[4011]73        this.chart.Series[TARGETVARIABLE_SERIES_NAME].ChartType = SeriesChartType.FastLine;
[15785]74
75        var rows = Enumerable.Range(0, Content.ProblemData.Dataset.Rows).ToArray();
76        var targetVariables = Content.ProblemData.Dataset.GetDoubleValues(Content.ProblemData.TargetVariable).ToArray();
77        List<int> xVals = new List<int>();
78        List<double> yVals = new List<double>();
79
80        for (int i = 0; i < rows.Length; i++) {
[15787]81          if (!double.IsInfinity(targetVariables[i]) && !double.IsNaN(targetVariables[i])) {
[15785]82            xVals.Add(rows[i]);
83            yVals.Add(targetVariables[i]);
84          }
85        }
86
87        this.chart.Series[TARGETVARIABLE_SERIES_NAME].Points.DataBindXY(xVals.ToArray(), yVals.ToArray());
[7327]88        // training series
[6238]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;
[7333]92        this.chart.Series[ESTIMATEDVALUES_TRAINING_SERIES_NAME].EmptyPointStyle.Color = this.chart.Series[ESTIMATEDVALUES_TRAINING_SERIES_NAME].Color;
[14422]93        int[] trainingIdx;
94        double[] trainingY;
95        GetTrainingSeries(out trainingIdx, out trainingY);
96        this.chart.Series[ESTIMATEDVALUES_TRAINING_SERIES_NAME].Points.DataBindXY(trainingIdx, trainingY);
[7406]97        this.InsertEmptyPoints(this.chart.Series[ESTIMATEDVALUES_TRAINING_SERIES_NAME]);
[6238]98        this.chart.Series[ESTIMATEDVALUES_TRAINING_SERIES_NAME].Tag = Content;
[14422]99
[7327]100        // test series
[6238]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;
[14422]104        int[] testIdx;
105        double[] testY;
106        GetTestSeries(out testIdx, out testY);
107        this.chart.Series[ESTIMATEDVALUES_TEST_SERIES_NAME].Points.DataBindXY(testIdx, testY);
[7406]108        this.InsertEmptyPoints(this.chart.Series[ESTIMATEDVALUES_TEST_SERIES_NAME]);
[6238]109        this.chart.Series[ESTIMATEDVALUES_TEST_SERIES_NAME].Tag = Content;
[14422]110
[7327]111        // series of remaining points
[14422]112        int[] allIdx;
113        double[] allEstimatedValues;
114        GetAllValuesSeries(out allIdx, out allEstimatedValues);
115
[6679]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;
[14422]119        if (allEstimatedValues.Length > 0) {
120          this.chart.Series[ESTIMATEDVALUES_ALL_SERIES_NAME].Points.DataBindXY(allIdx, allEstimatedValues);
[8485]121          this.InsertEmptyPoints(this.chart.Series[ESTIMATEDVALUES_ALL_SERIES_NAME]);
122        }
[6679]123        this.chart.Series[ESTIMATEDVALUES_ALL_SERIES_NAME].Tag = Content;
124        this.ToggleSeriesData(this.chart.Series[ESTIMATEDVALUES_ALL_SERIES_NAME]);
125
[14255]126        // set the y-axis
[14008]127        var axisY = this.chart.ChartAreas[0].AxisY;
[14255]128        axisY.Title = Content.ProblemData.TargetVariable;
[14008]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
[4011]146        UpdateCursorInterval();
[6238]147        this.UpdateStripLines();
[4011]148      }
[3408]149    }
150
[7406]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
[3707]171    private void UpdateCursorInterval() {
[6238]172      var estimatedValues = this.chart.Series[ESTIMATEDVALUES_TRAINING_SERIES_NAME].Points.Select(x => x.YValues[0]).DefaultIfEmpty(1.0);
[3707]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();
[15785]175      double targetValuesRange = targetValues.Where(v => !double.IsInfinity(v)).Max() - targetValues.Where(v => !double.IsNaN(v) && !double.IsNegativeInfinity(v)).Min();
[3707]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
[3442]182    #region events
183    protected override void RegisterContentEvents() {
184      base.RegisterContentEvents();
[5663]185      Content.ModelChanged += new EventHandler(Content_ModelChanged);
[3442]186      Content.ProblemDataChanged += new EventHandler(Content_ProblemDataChanged);
[3408]187    }
[3442]188    protected override void DeregisterContentEvents() {
189      base.DeregisterContentEvents();
[5663]190      Content.ModelChanged -= new EventHandler(Content_ModelChanged);
[3442]191      Content.ProblemDataChanged -= new EventHandler(Content_ProblemDataChanged);
[3408]192    }
193
[6679]194    protected override void OnContentChanged() {
195      base.OnContentChanged();
196      RedrawChart();
197    }
[3916]198    private void Content_ProblemDataChanged(object sender, EventArgs e) {
[3462]199      RedrawChart();
[3408]200    }
[5663]201    private void Content_ModelChanged(object sender, EventArgs e) {
[3462]202      RedrawChart();
[3442]203    }
204
[5006]205
[6679]206
[5006]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    }
[3442]216    #endregion
[3408]217
218    private void UpdateStripLines() {
219      this.chart.ChartAreas[0].AxisX.StripLines.Clear();
[6238]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
[8139]222      foreach (var row in Content.ProblemData.TrainingIndices) {
[6238]223        attr[row] += 1;
224      }
[8139]225      foreach (var row in Content.ProblemData.TestIndices) {
[6238]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      }
[3408]251    }
252
[6238]253    private void CreateAndAddStripLine(string title, int start, int end, Color color, Color secondColor, ChartHatchStyle hatchStyle = ChartHatchStyle.None) {
[3408]254      StripLine stripLine = new StripLine();
[6238]255      stripLine.BackColor = color;
256      stripLine.BackSecondaryColor = secondColor;
257      stripLine.BackHatchStyle = hatchStyle;
[3408]258      stripLine.Text = title;
259      stripLine.Font = new Font("Times New Roman", 12, FontStyle.Bold);
[6252]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)
[6520]262      stripLine.StripWidth = end - start;
[6252]263      stripLine.IntervalOffset = start - 0.5; // start slightly to the left of the first point to clearly indicate the first point in the partition
[3408]264      this.chart.ChartAreas[0].AxisX.StripLines.Add(stripLine);
265    }
[6679]266
[14531]267    public void ToggleSeriesData(Series series) {
[6679]268      if (series.Points.Count > 0) {  //checks if series is shown
269        if (this.chart.Series.Any(s => s != series && s.Points.Count > 0)) {
[7406]270          ClearPointsQuick(series.Points);
[6679]271        }
272      } else if (Content != null) {
273
[14422]274        int[] indices = null;
[8485]275        double[] predictedValues = null;
[6679]276        switch (series.Name) {
277          case ESTIMATEDVALUES_ALL_SERIES_NAME:
[14422]278            GetAllValuesSeries(out indices, out predictedValues);
[6679]279            break;
280          case ESTIMATEDVALUES_TRAINING_SERIES_NAME:
[14422]281            GetTrainingSeries(out indices, out predictedValues);
[6679]282            break;
283          case ESTIMATEDVALUES_TEST_SERIES_NAME:
[14422]284            GetTestSeries(out indices, out predictedValues);
[6679]285            break;
286        }
[8485]287        if (predictedValues.Length > 0) {
288          series.Points.DataBindXY(indices, predictedValues);
289          this.InsertEmptyPoints(series);
290        }
[6679]291        chart.Legends[series.Legend].ForeColor = Color.Black;
292        UpdateCursorInterval();
[6775]293        chart.Refresh();
[6679]294      }
295    }
296
[7406]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
[6679]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    }
[3408]326  }
327}
Note: See TracBrowser for help on using the repository browser.