Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 14449 was 14449, checked in by gkronber, 7 years ago

#2650: merged r14422:14443 from trunk to branches resolving conflicts

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