source: branches/symbreg-factors-2650/HeuristicLab.Problems.DataAnalysis.Views/3.4/Regression/RegressionSolutionLineChartViewBase.cs @ 14542

Last change on this file since 14542 was 14542, checked in by gkronber, 4 years ago

#2650: merged r14504:14533 from trunk to branch

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