Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 14330 was 14277, checked in by gkronber, 8 years ago

#2650: merged r14245:14273 from trunk to branch (fixing conflicts in RegressionSolutionTargetResponseGradientView)

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