Free cookie consent management tool by TermsFeed Policy Generator

source: branches/dataset-ids-2695/HeuristicLab.Problems.DataAnalysis.Views/3.4/Regression/RegressionSolutionLineChartViewBase.cs @ 15298

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

#2695: removed commented code and unused usings

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