Free cookie consent management tool by TermsFeed Policy Generator

source: branches/ChangeDatasetOfRegressionModel/HeuristicLab.Problems.DataAnalysis.Views/3.4/Regression/RegressionSolutionLineChartView.cs @ 7330

Last change on this file since 7330 was 7327, checked in by bburlacu, 13 years ago

#1756: Fixed speed issue in RegressionSolutionLineChartView. The problem was an unnecessary call to the InsertEmptyPoints procedure. The MSDN website (http://msdn.microsoft.com/en-us/library/dd456677.aspx) specifies the context in which this method is useful: when the data points have no Y value. In our case however there are no such points, so by removed the calls the performance becomes similar to the scatter plot (which also does not insert empty points).

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