Free cookie consent management tool by TermsFeed Policy Generator

source: branches/3106_AnalyticContinuedFractionsRegression/HeuristicLab.Problems.DataAnalysis.Views/3.4/Regression/RegressionSolutionLineChartViewBase.cs @ 18183

Last change on this file since 18183 was 17970, checked in by gkronber, 4 years ago

#3106 merged r17856:17969 from trunk to branch

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