Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 7990 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
RevLine 
[3408]1#region License Information
2/* HeuristicLab
[7259]3 * Copyright (C) 2002-2012 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
[3408]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;
[6679]22using System.Collections.Generic;
[3408]23using System.Drawing;
24using System.Linq;
25using System.Windows.Forms;
[4068]26using System.Windows.Forms.DataVisualization.Charting;
[3408]27using HeuristicLab.MainForm;
28
[3442]29namespace HeuristicLab.Problems.DataAnalysis.Views {
[5975]30  [View("Line Chart")]
[5663]31  [Content(typeof(IRegressionSolution))]
[6642]32  public partial class RegressionSolutionLineChartView : DataAnalysisSolutionEvaluationView {
[6238]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)";
[6679]36    private const string ESTIMATEDVALUES_ALL_SERIES_NAME = "Estimated Values (all samples)";
[3442]37
[5663]38    public new IRegressionSolution Content {
39      get { return (IRegressionSolution)base.Content; }
[3916]40      set { base.Content = value; }
[3442]41    }
42
[5663]43    public RegressionSolutionLineChartView()
[3408]44      : base() {
45      InitializeComponent();
46      //configure axis
[4651]47      this.chart.CustomizeAllChartAreas();
[3408]48      this.chart.ChartAreas[0].CursorX.IsUserSelectionEnabled = true;
49      this.chart.ChartAreas[0].AxisX.ScaleView.Zoomable = true;
[6238]50      this.chart.ChartAreas[0].AxisX.IsStartedFromZero = true;
[3707]51      this.chart.ChartAreas[0].CursorX.Interval = 1;
[3408]52
53      this.chart.ChartAreas[0].CursorY.IsUserSelectionEnabled = true;
54      this.chart.ChartAreas[0].AxisY.ScaleView.Zoomable = true;
[3442]55      this.chart.ChartAreas[0].CursorY.Interval = 0;
[3408]56    }
57
[3462]58    private void RedrawChart() {
[3442]59      this.chart.Series.Clear();
[4011]60      if (Content != null) {
[6238]61        this.chart.ChartAreas[0].AxisX.Minimum = 0;
62        this.chart.ChartAreas[0].AxisX.Maximum = Content.ProblemData.Dataset.Rows - 1;
63
[4011]64        this.chart.Series.Add(TARGETVARIABLE_SERIES_NAME);
[5663]65        this.chart.Series[TARGETVARIABLE_SERIES_NAME].LegendText = Content.ProblemData.TargetVariable;
[4011]66        this.chart.Series[TARGETVARIABLE_SERIES_NAME].ChartType = SeriesChartType.FastLine;
[6238]67        this.chart.Series[TARGETVARIABLE_SERIES_NAME].Points.DataBindXY(Enumerable.Range(0, Content.ProblemData.Dataset.Rows).ToArray(),
[6740]68          Content.ProblemData.Dataset.GetDoubleValues(Content.ProblemData.TargetVariable).ToArray());
[7327]69        // training series
[6238]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;
[7333]73        this.chart.Series[ESTIMATEDVALUES_TRAINING_SERIES_NAME].EmptyPointStyle.Color = this.chart.Series[ESTIMATEDVALUES_TRAINING_SERIES_NAME].Color;
[6679]74        this.chart.Series[ESTIMATEDVALUES_TRAINING_SERIES_NAME].Points.DataBindXY(Content.ProblemData.TrainingIndizes.ToArray(), Content.EstimatedTrainingValues.ToArray());
[7406]75        this.InsertEmptyPoints(this.chart.Series[ESTIMATEDVALUES_TRAINING_SERIES_NAME]);
[6238]76        this.chart.Series[ESTIMATEDVALUES_TRAINING_SERIES_NAME].Tag = Content;
[7327]77        // test series
[6238]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;
[6679]81        this.chart.Series[ESTIMATEDVALUES_TEST_SERIES_NAME].Points.DataBindXY(Content.ProblemData.TestIndizes.ToArray(), Content.EstimatedTestValues.ToArray());
[7406]82        this.InsertEmptyPoints(this.chart.Series[ESTIMATEDVALUES_TEST_SERIES_NAME]);
[6238]83        this.chart.Series[ESTIMATEDVALUES_TEST_SERIES_NAME].Tag = Content;
[7327]84        // series of remaining points
[6679]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);
[7406]92        this.InsertEmptyPoints(this.chart.Series[ESTIMATEDVALUES_ALL_SERIES_NAME]);
[6679]93        this.chart.Series[ESTIMATEDVALUES_ALL_SERIES_NAME].Tag = Content;
94        this.ToggleSeriesData(this.chart.Series[ESTIMATEDVALUES_ALL_SERIES_NAME]);
95
[4011]96        UpdateCursorInterval();
[6238]97        this.UpdateStripLines();
[4011]98      }
[3408]99    }
100
[7406]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
[3707]121    private void UpdateCursorInterval() {
[6238]122      var estimatedValues = this.chart.Series[ESTIMATEDVALUES_TRAINING_SERIES_NAME].Points.Select(x => x.YValues[0]).DefaultIfEmpty(1.0);
[3707]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
[3442]132    #region events
133    protected override void RegisterContentEvents() {
134      base.RegisterContentEvents();
[5663]135      Content.ModelChanged += new EventHandler(Content_ModelChanged);
[3442]136      Content.ProblemDataChanged += new EventHandler(Content_ProblemDataChanged);
[3408]137    }
[3442]138    protected override void DeregisterContentEvents() {
139      base.DeregisterContentEvents();
[5663]140      Content.ModelChanged -= new EventHandler(Content_ModelChanged);
[3442]141      Content.ProblemDataChanged -= new EventHandler(Content_ProblemDataChanged);
[3408]142    }
143
[6679]144    protected override void OnContentChanged() {
145      base.OnContentChanged();
146      RedrawChart();
147    }
[3916]148    private void Content_ProblemDataChanged(object sender, EventArgs e) {
[3462]149      RedrawChart();
[3408]150    }
[5663]151    private void Content_ModelChanged(object sender, EventArgs e) {
[3462]152      RedrawChart();
[3442]153    }
154
[5006]155
[6679]156
[5006]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    }
[3442]166    #endregion
[3408]167
168    private void UpdateStripLines() {
169      this.chart.ChartAreas[0].AxisX.StripLines.Clear();
[6238]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      }
[3408]201    }
202
[6238]203    private void CreateAndAddStripLine(string title, int start, int end, Color color, Color secondColor, ChartHatchStyle hatchStyle = ChartHatchStyle.None) {
[3408]204      StripLine stripLine = new StripLine();
[6238]205      stripLine.BackColor = color;
206      stripLine.BackSecondaryColor = secondColor;
207      stripLine.BackHatchStyle = hatchStyle;
[3408]208      stripLine.Text = title;
209      stripLine.Font = new Font("Times New Roman", 12, FontStyle.Bold);
[6252]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)
[6520]212      stripLine.StripWidth = end - start;
[6252]213      stripLine.IntervalOffset = start - 0.5; // start slightly to the left of the first point to clearly indicate the first point in the partition
[3408]214      this.chart.ChartAreas[0].AxisX.StripLines.Add(stripLine);
215    }
[6679]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)) {
[7406]220          ClearPointsQuick(series.Points);
[6679]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);
[7406]243        this.InsertEmptyPoints(series);
[6679]244        chart.Legends[series.Legend].ForeColor = Color.Black;
245        UpdateCursorInterval();
[6775]246        chart.Refresh();
[6679]247      }
248    }
249
[7406]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
[6679]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    }
[3408]279  }
280}
Note: See TracBrowser for help on using the repository browser.