Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Problems.DataAnalysis.Views/3.4/Regression/RegressionSolutionLineChartView.cs @ 7677

Last change on this file since 7677 was 7406, checked in by bburlacu, 13 years ago

#1756: Fixed line chart behavior for cases when the data point series are not continuous (some indices are not consecutive).

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