Free cookie consent management tool by TermsFeed Policy Generator

source: stable/HeuristicLab.Problems.DataAnalysis.Views/3.4/Regression/RegressionSolutionLineChartViewBase.cs @ 15137

Last change on this file since 15137 was 14942, checked in by gkronber, 8 years ago

#2718: merged r14531,r14532,r14940 from trunk to stable

File size: 14.3 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2016 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
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.Collections.Generic;
23using System.Drawing;
24using System.Linq;
25using System.Windows.Forms;
26using System.Windows.Forms.DataVisualization.Charting;
27using HeuristicLab.MainForm;
28using HeuristicLab.Visualization.ChartControlsExtensions;
29
30namespace HeuristicLab.Problems.DataAnalysis.Views {
31  [View("Line Chart")]
32  [Content(typeof(IRegressionSolution))]
33  public abstract partial class RegressionSolutionLineChartViewBase : DataAnalysisSolutionEvaluationView {
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)";
38
39    public new IRegressionSolution Content {
40      get { return (IRegressionSolution)base.Content; }
41      set { base.Content = value; }
42    }
43
44    protected RegressionSolutionLineChartViewBase()
45      : base() {
46      InitializeComponent();
47      //configure axis
48      this.chart.CustomizeAllChartAreas();
49      this.chart.ChartAreas[0].CursorX.IsUserSelectionEnabled = true;
50      this.chart.ChartAreas[0].AxisX.ScaleView.Zoomable = true;
51      this.chart.ChartAreas[0].AxisX.IsStartedFromZero = true;
52      this.chart.ChartAreas[0].CursorX.Interval = 1;
53
54      this.chart.ChartAreas[0].CursorY.IsUserSelectionEnabled = true;
55      this.chart.ChartAreas[0].AxisY.ScaleView.Zoomable = true;
56      this.chart.ChartAreas[0].CursorY.Interval = 0;
57    }
58
59    protected abstract void GetTrainingSeries(out int[] idx, out double[] y);
60
61    protected abstract void GetTestSeries(out int[] x, out double[] y);
62
63    protected abstract void GetAllValuesSeries(out int[] x, out double[] y);
64
65    protected virtual void RedrawChart() {
66      this.chart.Series.Clear();
67      if (Content != null) {
68        this.chart.ChartAreas[0].AxisX.Minimum = 0;
69        this.chart.ChartAreas[0].AxisX.Maximum = Content.ProblemData.Dataset.Rows - 1;
70
71        this.chart.Series.Add(TARGETVARIABLE_SERIES_NAME);
72        this.chart.Series[TARGETVARIABLE_SERIES_NAME].LegendText = TARGETVARIABLE_SERIES_NAME;
73        this.chart.Series[TARGETVARIABLE_SERIES_NAME].ChartType = SeriesChartType.FastLine;
74        this.chart.Series[TARGETVARIABLE_SERIES_NAME].Points.DataBindXY(Enumerable.Range(0, Content.ProblemData.Dataset.Rows).ToArray(),
75          Content.ProblemData.Dataset.GetDoubleValues(Content.ProblemData.TargetVariable).ToArray());
76        // training series
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;
80        this.chart.Series[ESTIMATEDVALUES_TRAINING_SERIES_NAME].EmptyPointStyle.Color = this.chart.Series[ESTIMATEDVALUES_TRAINING_SERIES_NAME].Color;
81        int[] trainingIdx;
82        double[] trainingY;
83        GetTrainingSeries(out trainingIdx, out trainingY);
84        this.chart.Series[ESTIMATEDVALUES_TRAINING_SERIES_NAME].Points.DataBindXY(trainingIdx, trainingY);
85        this.InsertEmptyPoints(this.chart.Series[ESTIMATEDVALUES_TRAINING_SERIES_NAME]);
86        this.chart.Series[ESTIMATEDVALUES_TRAINING_SERIES_NAME].Tag = Content;
87
88        // test series
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;
92        int[] testIdx;
93        double[] testY;
94        GetTestSeries(out testIdx, out testY);
95        this.chart.Series[ESTIMATEDVALUES_TEST_SERIES_NAME].Points.DataBindXY(testIdx, testY);
96        this.InsertEmptyPoints(this.chart.Series[ESTIMATEDVALUES_TEST_SERIES_NAME]);
97        this.chart.Series[ESTIMATEDVALUES_TEST_SERIES_NAME].Tag = Content;
98
99        // series of remaining points
100        int[] allIdx;
101        double[] allEstimatedValues;
102        GetAllValuesSeries(out allIdx, out allEstimatedValues);
103
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;
107        if (allEstimatedValues.Length > 0) {
108          this.chart.Series[ESTIMATEDVALUES_ALL_SERIES_NAME].Points.DataBindXY(allIdx, allEstimatedValues);
109          this.InsertEmptyPoints(this.chart.Series[ESTIMATEDVALUES_ALL_SERIES_NAME]);
110        }
111        this.chart.Series[ESTIMATEDVALUES_ALL_SERIES_NAME].Tag = Content;
112        this.ToggleSeriesData(this.chart.Series[ESTIMATEDVALUES_ALL_SERIES_NAME]);
113
114        // set the y-axis
115        var axisY = this.chart.ChartAreas[0].AxisY;
116        axisY.Title = Content.ProblemData.TargetVariable;
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
134        UpdateCursorInterval();
135        this.UpdateStripLines();
136      }
137    }
138
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
159    private void UpdateCursorInterval() {
160      var estimatedValues = this.chart.Series[ESTIMATEDVALUES_TRAINING_SERIES_NAME].Points.Select(x => x.YValues[0]).DefaultIfEmpty(1.0);
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
170    #region events
171    protected override void RegisterContentEvents() {
172      base.RegisterContentEvents();
173      Content.ModelChanged += new EventHandler(Content_ModelChanged);
174      Content.ProblemDataChanged += new EventHandler(Content_ProblemDataChanged);
175    }
176    protected override void DeregisterContentEvents() {
177      base.DeregisterContentEvents();
178      Content.ModelChanged -= new EventHandler(Content_ModelChanged);
179      Content.ProblemDataChanged -= new EventHandler(Content_ProblemDataChanged);
180    }
181
182    protected override void OnContentChanged() {
183      base.OnContentChanged();
184      RedrawChart();
185    }
186    private void Content_ProblemDataChanged(object sender, EventArgs e) {
187      RedrawChart();
188    }
189    private void Content_ModelChanged(object sender, EventArgs e) {
190      RedrawChart();
191    }
192
193
194
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    }
204    #endregion
205
206    private void UpdateStripLines() {
207      this.chart.ChartAreas[0].AxisX.StripLines.Clear();
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
210      foreach (var row in Content.ProblemData.TrainingIndices) {
211        attr[row] += 1;
212      }
213      foreach (var row in Content.ProblemData.TestIndices) {
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      }
239    }
240
241    private void CreateAndAddStripLine(string title, int start, int end, Color color, Color secondColor, ChartHatchStyle hatchStyle = ChartHatchStyle.None) {
242      StripLine stripLine = new StripLine();
243      stripLine.BackColor = color;
244      stripLine.BackSecondaryColor = secondColor;
245      stripLine.BackHatchStyle = hatchStyle;
246      stripLine.Text = title;
247      stripLine.Font = new Font("Times New Roman", 12, FontStyle.Bold);
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)
250      stripLine.StripWidth = end - start;
251      stripLine.IntervalOffset = start - 0.5; // start slightly to the left of the first point to clearly indicate the first point in the partition
252      this.chart.ChartAreas[0].AxisX.StripLines.Add(stripLine);
253    }
254
255    public void ToggleSeriesData(Series series) {
256      if (series.Points.Count > 0) {  //checks if series is shown
257        if (this.chart.Series.Any(s => s != series && s.Points.Count > 0)) {
258          ClearPointsQuick(series.Points);
259        }
260      } else if (Content != null) {
261
262        int[] indices = null;
263        double[] predictedValues = null;
264        switch (series.Name) {
265          case ESTIMATEDVALUES_ALL_SERIES_NAME:
266            GetAllValuesSeries(out indices, out predictedValues);
267            break;
268          case ESTIMATEDVALUES_TRAINING_SERIES_NAME:
269            GetTrainingSeries(out indices, out predictedValues);
270            break;
271          case ESTIMATEDVALUES_TEST_SERIES_NAME:
272            GetTestSeries(out indices, out predictedValues);
273            break;
274        }
275        if (predictedValues.Length > 0) {
276          series.Points.DataBindXY(indices, predictedValues);
277          this.InsertEmptyPoints(series);
278        }
279        chart.Legends[series.Legend].ForeColor = Color.Black;
280        UpdateCursorInterval();
281        chart.Refresh();
282      }
283    }
284
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
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    }
314  }
315}
Note: See TracBrowser for help on using the repository browser.