Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 17495 was 17180, checked in by swagner, 5 years ago

#2875: Removed years in copyrights

File size: 14.5 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 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.Drawing;
23using System.Linq;
24using System.Windows.Forms;
25using System.Windows.Forms.DataVisualization.Charting;
26using HeuristicLab.MainForm;
27using HeuristicLab.Visualization.ChartControlsExtensions;
28
29namespace HeuristicLab.Problems.DataAnalysis.Views {
30  [View("Line Chart")]
31  [Content(typeof(IRegressionSolution))]
32  public abstract partial class RegressionSolutionLineChartViewBase : DataAnalysisSolutionEvaluationView {
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)";
37
38    public new IRegressionSolution Content {
39      get { return (IRegressionSolution)base.Content; }
40      set { base.Content = value; }
41    }
42
43    protected RegressionSolutionLineChartViewBase()
44      : base() {
45      InitializeComponent();
46      //configure axis
47      this.chart.CustomizeAllChartAreas();
48      this.chart.ChartAreas[0].CursorX.IsUserSelectionEnabled = true;
49      this.chart.ChartAreas[0].AxisX.ScaleView.Zoomable = true;
50      this.chart.ChartAreas[0].AxisX.IsStartedFromZero = true;
51      this.chart.ChartAreas[0].CursorX.Interval = 1;
52
53      this.chart.ChartAreas[0].CursorY.IsUserSelectionEnabled = true;
54      this.chart.ChartAreas[0].AxisY.ScaleView.Zoomable = true;
55      this.chart.ChartAreas[0].CursorY.Interval = 0;
56    }
57
58    protected abstract void GetTrainingSeries(out int[] idx, out double[] y);
59
60    protected abstract void GetTestSeries(out int[] x, out double[] y);
61
62    protected abstract void GetAllValuesSeries(out int[] x, out double[] y);
63
64    protected virtual void RedrawChart() {
65      this.chart.Series.Clear();
66      if (Content != null) {
67        this.chart.ChartAreas[0].AxisX.Minimum = 0;
68        this.chart.ChartAreas[0].AxisX.Maximum = Content.ProblemData.Dataset.Rows - 1;
69
70        this.chart.Series.Add(TARGETVARIABLE_SERIES_NAME);
71        this.chart.Series[TARGETVARIABLE_SERIES_NAME].LegendText = TARGETVARIABLE_SERIES_NAME;
72        this.chart.Series[TARGETVARIABLE_SERIES_NAME].ChartType = SeriesChartType.FastLine;
73
74        var rows = Enumerable.Range(0, Content.ProblemData.Dataset.Rows).ToArray();
75        var targetValues = Content.ProblemData.Dataset.GetDoubleValues(Content.ProblemData.TargetVariable);
76
77
78        this.chart.Series[TARGETVARIABLE_SERIES_NAME].Points.DataBindXY(rows.ToArray(), targetValues.Select(v => double.IsInfinity(v) ? double.NaN : v).ToArray());
79        // training series
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;
83        this.chart.Series[ESTIMATEDVALUES_TRAINING_SERIES_NAME].EmptyPointStyle.Color = this.chart.Series[ESTIMATEDVALUES_TRAINING_SERIES_NAME].Color;
84        int[] trainingIdx;
85        double[] trainingY;
86        GetTrainingSeries(out trainingIdx, out trainingY);
87        this.chart.Series[ESTIMATEDVALUES_TRAINING_SERIES_NAME].Points.DataBindXY(trainingIdx, trainingY);
88        this.InsertEmptyPoints(this.chart.Series[ESTIMATEDVALUES_TRAINING_SERIES_NAME]);
89        this.chart.Series[ESTIMATEDVALUES_TRAINING_SERIES_NAME].Tag = Content;
90
91        // test series
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;
95        int[] testIdx;
96        double[] testY;
97        GetTestSeries(out testIdx, out testY);
98        this.chart.Series[ESTIMATEDVALUES_TEST_SERIES_NAME].Points.DataBindXY(testIdx, testY);
99        this.InsertEmptyPoints(this.chart.Series[ESTIMATEDVALUES_TEST_SERIES_NAME]);
100        this.chart.Series[ESTIMATEDVALUES_TEST_SERIES_NAME].Tag = Content;
101
102        // series of remaining points
103        int[] allIdx;
104        double[] allEstimatedValues;
105        GetAllValuesSeries(out allIdx, out allEstimatedValues);
106
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;
110        if (allEstimatedValues.Length > 0) {
111          this.chart.Series[ESTIMATEDVALUES_ALL_SERIES_NAME].Points.DataBindXY(allIdx, allEstimatedValues);
112          this.InsertEmptyPoints(this.chart.Series[ESTIMATEDVALUES_ALL_SERIES_NAME]);
113        }
114        this.chart.Series[ESTIMATEDVALUES_ALL_SERIES_NAME].Tag = Content;
115        this.ToggleSeriesData(this.chart.Series[ESTIMATEDVALUES_ALL_SERIES_NAME]);
116
117        // set the y-axis
118        var axisY = this.chart.ChartAreas[0].AxisY;
119        axisY.Title = Content.ProblemData.TargetVariable;
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
137        UpdateCursorInterval();
138        this.UpdateStripLines();
139      }
140    }
141
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
162    private void UpdateCursorInterval() {
163      var estimatedValues = this.chart.Series[ESTIMATEDVALUES_TRAINING_SERIES_NAME].Points.Select(x => x.YValues[0]).DefaultIfEmpty(1.0);
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();
166      double targetValuesRange = targetValues.Where(v => !double.IsInfinity(v) && !double.IsNaN(v)).Max() -
167                                 targetValues.Where(v => !double.IsInfinity(v) && !double.IsNaN(v)).Min();
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
174    #region events
175    protected override void RegisterContentEvents() {
176      base.RegisterContentEvents();
177      Content.ModelChanged += new EventHandler(Content_ModelChanged);
178      Content.ProblemDataChanged += new EventHandler(Content_ProblemDataChanged);
179    }
180    protected override void DeregisterContentEvents() {
181      base.DeregisterContentEvents();
182      Content.ModelChanged -= new EventHandler(Content_ModelChanged);
183      Content.ProblemDataChanged -= new EventHandler(Content_ProblemDataChanged);
184    }
185
186    protected override void OnContentChanged() {
187      base.OnContentChanged();
188      RedrawChart();
189    }
190    private void Content_ProblemDataChanged(object sender, EventArgs e) {
191      RedrawChart();
192    }
193    private void Content_ModelChanged(object sender, EventArgs e) {
194      RedrawChart();
195    }
196
197
198
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    }
208    #endregion
209
210    private void UpdateStripLines() {
211      this.chart.ChartAreas[0].AxisX.StripLines.Clear();
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
214      foreach (var row in Content.ProblemData.TrainingIndices) {
215        attr[row] += 1;
216      }
217      foreach (var row in Content.ProblemData.TestIndices) {
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      }
243    }
244
245    private void CreateAndAddStripLine(string title, int start, int end, Color color, Color secondColor, ChartHatchStyle hatchStyle = ChartHatchStyle.None) {
246      StripLine stripLine = new StripLine();
247      stripLine.BackColor = color;
248      stripLine.BackSecondaryColor = secondColor;
249      stripLine.BackHatchStyle = hatchStyle;
250      stripLine.Text = title;
251      stripLine.Font = new Font("Times New Roman", 12, FontStyle.Bold);
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)
254      stripLine.StripWidth = end - start;
255      stripLine.IntervalOffset = start - 0.5; // start slightly to the left of the first point to clearly indicate the first point in the partition
256      this.chart.ChartAreas[0].AxisX.StripLines.Add(stripLine);
257    }
258
259    public void ToggleSeriesData(Series series) {
260      if (series.Points.Count > 0) {  //checks if series is shown
261        if (this.chart.Series.Any(s => s != series && s.Points.Count > 0)) {
262          ClearPointsQuick(series.Points);
263        }
264      } else if (Content != null) {
265
266        int[] indices = null;
267        double[] predictedValues = null;
268        switch (series.Name) {
269          case ESTIMATEDVALUES_ALL_SERIES_NAME:
270            GetAllValuesSeries(out indices, out predictedValues);
271            break;
272          case ESTIMATEDVALUES_TRAINING_SERIES_NAME:
273            GetTrainingSeries(out indices, out predictedValues);
274            break;
275          case ESTIMATEDVALUES_TEST_SERIES_NAME:
276            GetTestSeries(out indices, out predictedValues);
277            break;
278        }
279        if (predictedValues.Length > 0) {
280          series.Points.DataBindXY(indices, predictedValues);
281          this.InsertEmptyPoints(series);
282        }
283        chart.Legends[series.Legend].ForeColor = Color.Black;
284        UpdateCursorInterval();
285        chart.Refresh();
286      }
287    }
288
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
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    }
318  }
319}
Note: See TracBrowser for help on using the repository browser.