Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 7335 was 7335, checked in by bburlacu, 12 years ago

#1756: Also removed the InsertEmptyPoints call from inside the ToggleSeriesData method.

File size: 12.9 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;
28using HeuristicLab.MainForm.WindowsForms;
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 = Content.ProblemData.TargetVariable;
67        this.chart.Series[TARGETVARIABLE_SERIES_NAME].ChartType = SeriesChartType.FastLine;
68        this.chart.Series[TARGETVARIABLE_SERIES_NAME].EmptyPointStyle.Color = this.chart.Series[TARGETVARIABLE_SERIES_NAME].Color;
69        this.chart.Series[TARGETVARIABLE_SERIES_NAME].Points.DataBindXY(Enumerable.Range(0, Content.ProblemData.Dataset.Rows).ToArray(),
70          Content.ProblemData.Dataset.GetDoubleValues(Content.ProblemData.TargetVariable).ToArray());
71        // training series
72        this.chart.Series.Add(ESTIMATEDVALUES_TRAINING_SERIES_NAME);
73        this.chart.Series[ESTIMATEDVALUES_TRAINING_SERIES_NAME].LegendText = ESTIMATEDVALUES_TRAINING_SERIES_NAME;
74        this.chart.Series[ESTIMATEDVALUES_TRAINING_SERIES_NAME].ChartType = SeriesChartType.FastLine;
75        this.chart.Series[ESTIMATEDVALUES_TRAINING_SERIES_NAME].EmptyPointStyle.Color = this.chart.Series[ESTIMATEDVALUES_TRAINING_SERIES_NAME].Color;
76        this.chart.Series[ESTIMATEDVALUES_TRAINING_SERIES_NAME].Points.DataBindXY(Content.ProblemData.TrainingIndizes.ToArray(), Content.EstimatedTrainingValues.ToArray());
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].EmptyPointStyle.Color = this.chart.Series[ESTIMATEDVALUES_TEST_SERIES_NAME].Color;
83        this.chart.Series[ESTIMATEDVALUES_TEST_SERIES_NAME].Points.DataBindXY(Content.ProblemData.TestIndizes.ToArray(), Content.EstimatedTestValues.ToArray());
84        this.chart.Series[ESTIMATEDVALUES_TEST_SERIES_NAME].Tag = Content;
85        // series of remaining points
86        int[] allIndizes = Enumerable.Range(0, Content.ProblemData.Dataset.Rows).Except(Content.ProblemData.TrainingIndizes).Except(Content.ProblemData.TestIndizes).ToArray();
87        var estimatedValues = Content.EstimatedValues.ToArray();
88        List<double> allEstimatedValues = allIndizes.Select(index => estimatedValues[index]).ToList();
89
90        this.chart.Series.Add(ESTIMATEDVALUES_ALL_SERIES_NAME);
91        this.chart.Series[ESTIMATEDVALUES_ALL_SERIES_NAME].LegendText = ESTIMATEDVALUES_ALL_SERIES_NAME;
92        this.chart.Series[ESTIMATEDVALUES_ALL_SERIES_NAME].ChartType = SeriesChartType.FastLine;
93        this.chart.Series[ESTIMATEDVALUES_ALL_SERIES_NAME].EmptyPointStyle.Color = this.chart.Series[ESTIMATEDVALUES_ALL_SERIES_NAME].Color;
94        this.chart.Series[ESTIMATEDVALUES_ALL_SERIES_NAME].Points.DataBindXY(allIndizes, allEstimatedValues);
95        this.chart.Series[ESTIMATEDVALUES_ALL_SERIES_NAME].Tag = Content;
96        this.ToggleSeriesData(this.chart.Series[ESTIMATEDVALUES_ALL_SERIES_NAME]);
97
98        UpdateCursorInterval();
99        this.UpdateStripLines();
100      }
101    }
102
103    private void UpdateCursorInterval() {
104      var estimatedValues = this.chart.Series[ESTIMATEDVALUES_TRAINING_SERIES_NAME].Points.Select(x => x.YValues[0]).DefaultIfEmpty(1.0);
105      var targetValues = this.chart.Series[TARGETVARIABLE_SERIES_NAME].Points.Select(x => x.YValues[0]).DefaultIfEmpty(1.0);
106      double estimatedValuesRange = estimatedValues.Max() - estimatedValues.Min();
107      double targetValuesRange = targetValues.Max() - targetValues.Min();
108      double interestingValuesRange = Math.Min(Math.Max(targetValuesRange, 1.0), Math.Max(estimatedValuesRange, 1.0));
109      double digits = (int)Math.Log10(interestingValuesRange) - 3;
110      double yZoomInterval = Math.Max(Math.Pow(10, digits), 10E-5);
111      this.chart.ChartAreas[0].CursorY.Interval = yZoomInterval;
112    }
113
114    #region events
115    protected override void RegisterContentEvents() {
116      base.RegisterContentEvents();
117      Content.ModelChanged += new EventHandler(Content_ModelChanged);
118      Content.ProblemDataChanged += new EventHandler(Content_ProblemDataChanged);
119    }
120    protected override void DeregisterContentEvents() {
121      base.DeregisterContentEvents();
122      Content.ModelChanged -= new EventHandler(Content_ModelChanged);
123      Content.ProblemDataChanged -= new EventHandler(Content_ProblemDataChanged);
124    }
125
126    protected override void OnContentChanged() {
127      base.OnContentChanged();
128      RedrawChart();
129    }
130    private void Content_ProblemDataChanged(object sender, EventArgs e) {
131      RedrawChart();
132    }
133    private void Content_ModelChanged(object sender, EventArgs e) {
134      RedrawChart();
135    }
136
137
138
139    private void Chart_MouseDoubleClick(object sender, MouseEventArgs e) {
140      HitTestResult result = chart.HitTest(e.X, e.Y);
141      if (result.ChartArea != null && (result.ChartElementType == ChartElementType.PlottingArea ||
142                                       result.ChartElementType == ChartElementType.Gridlines) ||
143                                       result.ChartElementType == ChartElementType.StripLines) {
144        foreach (var axis in result.ChartArea.Axes)
145          axis.ScaleView.ZoomReset(int.MaxValue);
146      }
147    }
148    #endregion
149
150    private void UpdateStripLines() {
151      this.chart.ChartAreas[0].AxisX.StripLines.Clear();
152
153      int[] attr = new int[Content.ProblemData.Dataset.Rows + 1]; // add a virtual last row that is again empty to simplify loop further down
154      foreach (var row in Content.ProblemData.TrainingIndizes) {
155        attr[row] += 1;
156      }
157      foreach (var row in Content.ProblemData.TestIndizes) {
158        attr[row] += 2;
159      }
160      int start = 0;
161      int curAttr = attr[start];
162      for (int row = 0; row < attr.Length; row++) {
163        if (attr[row] != curAttr) {
164          switch (curAttr) {
165            case 0: break;
166            case 1:
167              this.CreateAndAddStripLine("Training", start, row, Color.FromArgb(40, Color.Green), Color.Transparent);
168              break;
169            case 2:
170              this.CreateAndAddStripLine("Test", start, row, Color.FromArgb(40, Color.Red), Color.Transparent);
171              break;
172            case 3:
173              this.CreateAndAddStripLine("Training and Test", start, row, Color.FromArgb(40, Color.Green), Color.FromArgb(40, Color.Red), ChartHatchStyle.WideUpwardDiagonal);
174              break;
175            default:
176              // should not happen
177              break;
178          }
179          curAttr = attr[row];
180          start = row;
181        }
182      }
183    }
184
185    private void CreateAndAddStripLine(string title, int start, int end, Color color, Color secondColor, ChartHatchStyle hatchStyle = ChartHatchStyle.None) {
186      StripLine stripLine = new StripLine();
187      stripLine.BackColor = color;
188      stripLine.BackSecondaryColor = secondColor;
189      stripLine.BackHatchStyle = hatchStyle;
190      stripLine.Text = title;
191      stripLine.Font = new Font("Times New Roman", 12, FontStyle.Bold);
192      // strip range is [start .. end] inclusive, but we evaluate [start..end[ (end is exclusive)
193      // the strip should be by one longer (starting at start - 0.5 and ending at end + 0.5)
194      stripLine.StripWidth = end - start;
195      stripLine.IntervalOffset = start - 0.5; // start slightly to the left of the first point to clearly indicate the first point in the partition
196      this.chart.ChartAreas[0].AxisX.StripLines.Add(stripLine);
197    }
198
199    private void ToggleSeriesData(Series series) {
200      if (series.Points.Count > 0) {  //checks if series is shown
201        if (this.chart.Series.Any(s => s != series && s.Points.Count > 0)) {
202          series.Points.Clear();
203        }
204      } else if (Content != null) {
205        string targetVariableName = Content.ProblemData.TargetVariable;
206
207        IEnumerable<int> indizes = null;
208        IEnumerable<double> predictedValues = null;
209        switch (series.Name) {
210          case ESTIMATEDVALUES_ALL_SERIES_NAME:
211            indizes = Enumerable.Range(0, Content.ProblemData.Dataset.Rows).Except(Content.ProblemData.TrainingIndizes).Except(Content.ProblemData.TestIndizes).ToArray();
212            var estimatedValues = Content.EstimatedValues.ToArray();
213            predictedValues = indizes.Select(index => estimatedValues[index]).ToList();
214            break;
215          case ESTIMATEDVALUES_TRAINING_SERIES_NAME:
216            indizes = Content.ProblemData.TrainingIndizes.ToArray();
217            predictedValues = Content.EstimatedTrainingValues.ToArray();
218            break;
219          case ESTIMATEDVALUES_TEST_SERIES_NAME:
220            indizes = Content.ProblemData.TestIndizes.ToArray();
221            predictedValues = Content.EstimatedTestValues.ToArray();
222            break;
223        }
224        series.Points.DataBindXY(indizes, predictedValues);
225        chart.Legends[series.Legend].ForeColor = Color.Black;
226        UpdateCursorInterval();
227        chart.Refresh();
228      }
229    }
230
231    private void chart_MouseMove(object sender, MouseEventArgs e) {
232      HitTestResult result = chart.HitTest(e.X, e.Y);
233      if (result.ChartElementType == ChartElementType.LegendItem && result.Series.Name != TARGETVARIABLE_SERIES_NAME)
234        Cursor = Cursors.Hand;
235      else
236        Cursor = Cursors.Default;
237    }
238    private void chart_MouseDown(object sender, MouseEventArgs e) {
239      HitTestResult result = chart.HitTest(e.X, e.Y);
240      if (result.ChartElementType == ChartElementType.LegendItem && result.Series.Name != TARGETVARIABLE_SERIES_NAME) {
241        ToggleSeriesData(result.Series);
242      }
243    }
244
245    private void chart_CustomizeLegend(object sender, CustomizeLegendEventArgs e) {
246      if (chart.Series.Count != 4) return;
247      e.LegendItems[0].Cells[1].ForeColor = this.chart.Series[TARGETVARIABLE_SERIES_NAME].Points.Count == 0 ? Color.Gray : Color.Black;
248      e.LegendItems[1].Cells[1].ForeColor = this.chart.Series[ESTIMATEDVALUES_TRAINING_SERIES_NAME].Points.Count == 0 ? Color.Gray : Color.Black;
249      e.LegendItems[2].Cells[1].ForeColor = this.chart.Series[ESTIMATEDVALUES_TEST_SERIES_NAME].Points.Count == 0 ? Color.Gray : Color.Black;
250      e.LegendItems[3].Cells[1].ForeColor = this.chart.Series[ESTIMATEDVALUES_ALL_SERIES_NAME].Points.Count == 0 ? Color.Gray : Color.Black;
251    }
252  }
253}
Note: See TracBrowser for help on using the repository browser.