Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.TimeSeries/HeuristicLab.Problems.DataAnalysis.Views/3.4/TimeSeriesPrognosis/TimeSeriesPrognosisSolutionLineChartView.cs @ 8430

Last change on this file since 8430 was 8430, checked in by mkommend, 12 years ago

#1081: Intermediate commit of trunk updates - interpreter changes must be redone.

File size: 15.5 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2011 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
21
22using System;
23using System.Collections.Generic;
24using System.Drawing;
25using System.Linq;
26using System.Windows.Forms;
27using System.Windows.Forms.DataVisualization.Charting;
28using HeuristicLab.Common;
29using HeuristicLab.MainForm;
30using HeuristicLab.MainForm.WindowsForms;
31
32namespace HeuristicLab.Problems.DataAnalysis.Views {
33  [View("Line Chart")]
34  [Content(typeof(ITimeSeriesPrognosisSolution))]
35  public partial class TimeSeriesPrognosisSolutionLineChartView : DataAnalysisSolutionEvaluationView {
36    private const string TARGETVARIABLE_SERIES_NAME = "Target Variable";
37    private const string PROGNOSEDVALUES_TRAINING_SERIES_NAME = "Prognosed Values (training)";
38    private const string PROGNOSEDVALUES_TEST_SERIES_NAME = "Prognosed Values (test)";
39    private const string PROGNOSEDVALUES_ALL_SERIES_NAME = "Prognosed Values (all samples)";
40    private int testPrognosisStart;
41
42    public new ITimeSeriesPrognosisSolution Content {
43      get { return (ITimeSeriesPrognosisSolution)base.Content; }
44      set { base.Content = value; }
45    }
46
47    public TimeSeriesPrognosisSolutionLineChartView()
48      : base() {
49      InitializeComponent();
50      //configure axis
51      this.chart.CustomizeAllChartAreas();
52      this.chart.ChartAreas[0].CursorX.IsUserSelectionEnabled = true;
53      this.chart.ChartAreas[0].CursorX.Interval = 1;
54      this.chart.ChartAreas[0].AxisX.ScaleView.Zoomable = true;
55      this.chart.ChartAreas[0].AxisX.IsStartedFromZero = true;
56
57      this.chart.ChartAreas[0].CursorY.IsUserSelectionEnabled = true;
58      this.chart.ChartAreas[0].CursorY.Interval = 0.1;
59      this.chart.ChartAreas[0].AxisY.ScaleView.Zoomable = true;
60
61      this.chart.SuppressExceptions = false;
62    }
63
64    private 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        string targetVariable = Content.ProblemData.TargetVariable;
70
71        this.chart.Series.Add(TARGETVARIABLE_SERIES_NAME);
72        this.chart.Series[TARGETVARIABLE_SERIES_NAME].LegendText = targetVariable;
73        this.chart.Series[TARGETVARIABLE_SERIES_NAME].ChartType = SeriesChartType.FastLine;
74        AddDataPoints(chart.Series[TARGETVARIABLE_SERIES_NAME].Points, Enumerable.Range(0, Content.ProblemData.Dataset.Rows), Content.ProblemData.Dataset.GetDoubleValues(targetVariable));
75        //this.chart.Series[TARGETVARIABLE_SERIES_NAME].Points.DataBindXY(Enumerable.Range(0, Content.ProblemData.Dataset.Rows).ToArray(),
76        //  Content.ProblemData.Dataset.GetDoubleValues(targetVariable).ToArray());
77
78        this.chart.Series.Add(PROGNOSEDVALUES_TRAINING_SERIES_NAME);
79        this.chart.Series[PROGNOSEDVALUES_TRAINING_SERIES_NAME].LegendText = PROGNOSEDVALUES_TRAINING_SERIES_NAME;
80        this.chart.Series[PROGNOSEDVALUES_TRAINING_SERIES_NAME].ChartType = SeriesChartType.FastLine;
81        if (prognosedValuesCheckbox.Checked) {
82          //this.chart.Series[PROGNOSEDVALUES_TRAINING_SERIES_NAME].Points
83          //  .DataBindXY(Content.ProblemData.TrainingIndices.ToArray(),
84          //              Content.GetPrognosedValues(Content.ProblemData.TrainingIndices.Take(1), Content.ProblemData.TrainingIndices.Count().ToEnumerable()).First().ToArray());
85          AddDataPoints(chart.Series[PROGNOSEDVALUES_TRAINING_SERIES_NAME].Points, Content.ProblemData.TrainingIndices, Content.GetPrognosedValues(Content.ProblemData.TrainingIndices.Take(1), Content.ProblemData.TrainingIndices.Count().ToEnumerable()).First());
86        } else {
87          //this.chart.Series[PROGNOSEDVALUES_TRAINING_SERIES_NAME].Points
88          //  .DataBindXY(Content.ProblemData.TrainingIndices.ToArray(),
89          //              Content.GetPrognosedValues(Content.ProblemData.TrainingIndices, Enumerable.Repeat(1, Content.ProblemData.TrainingIndices.Count())).SelectMany(x => x).ToArray());
90          AddDataPoints(chart.Series[PROGNOSEDVALUES_TRAINING_SERIES_NAME].Points, Content.ProblemData.TrainingIndices, Content.GetPrognosedValues(Content.ProblemData.TrainingIndices, Enumerable.Repeat(1, Content.ProblemData.TrainingIndices.Count())).SelectMany(x => x));
91        }
92        this.chart.Series[PROGNOSEDVALUES_TRAINING_SERIES_NAME].Tag = Content;
93        this.chart.DataManipulator.InsertEmptyPoints(1, IntervalType.Number, PROGNOSEDVALUES_TRAINING_SERIES_NAME);
94        this.chart.Series[PROGNOSEDVALUES_TRAINING_SERIES_NAME].EmptyPointStyle.BorderWidth = 0;
95        this.chart.Series[PROGNOSEDVALUES_TRAINING_SERIES_NAME].EmptyPointStyle.MarkerStyle = MarkerStyle.None;
96
97
98        this.chart.Series.Add(PROGNOSEDVALUES_TEST_SERIES_NAME);
99        this.chart.Series[PROGNOSEDVALUES_TEST_SERIES_NAME].LegendText = PROGNOSEDVALUES_TEST_SERIES_NAME;
100        this.chart.Series[PROGNOSEDVALUES_TEST_SERIES_NAME].ChartType = SeriesChartType.FastLine;
101        if (prognosedValuesCheckbox.Checked) {
102          //this.chart.Series[PROGNOSEDVALUES_TEST_SERIES_NAME].Points
103          //  .DataBindXY(Content.ProblemData.TestIndices.ToArray(),
104          //              Content.GetPrognosedValues(Content.ProblemData.TestIndices.Take(1), Content.ProblemData.TestIndices.Count().ToEnumerable()).First().ToArray());
105          AddDataPoints(chart.Series[PROGNOSEDVALUES_TEST_SERIES_NAME].Points, Content.ProblemData.TestIndices, Content.GetPrognosedValues(Content.ProblemData.TestIndices.Take(1), Content.ProblemData.TestIndices.Count().ToEnumerable()).First());
106        } else {
107          //this.chart.Series[PROGNOSEDVALUES_TEST_SERIES_NAME].Points
108          //  .DataBindXY(Content.ProblemData.TestIndices.ToArray(),
109          //              Content.GetPrognosedValues(Content.ProblemData.TestIndices, Enumerable.Repeat(1, Content.ProblemData.TestIndices.Count())).SelectMany(x => x).ToArray());
110          AddDataPoints(chart.Series[PROGNOSEDVALUES_TEST_SERIES_NAME].Points, Content.ProblemData.TestIndices, Content.GetPrognosedValues(Content.ProblemData.TestIndices, Enumerable.Repeat(1, Content.ProblemData.TestIndices.Count())).SelectMany(x => x));
111        }
112        this.chart.Series[PROGNOSEDVALUES_TEST_SERIES_NAME].Tag = Content;
113        UpdateCursorInterval();
114        this.UpdateStripLines();
115      }
116      chart.Refresh();
117    }
118
119    private void AddDataPoints(DataPointCollection points, IEnumerable<int> xValues, IEnumerable<double> yValues) {
120      var xValuesEnumerator = xValues.GetEnumerator();
121      var yValuesEnumerator = yValues.GetEnumerator();
122
123      while (xValuesEnumerator.MoveNext() & yValuesEnumerator.MoveNext()) {
124        var xValue = xValuesEnumerator.Current;
125        var yValue = yValuesEnumerator.Current;
126
127        if (yValue < (double)decimal.MaxValue && yValue > (double)decimal.MinValue) {
128          DataPoint dataPoint = new DataPoint(xValue, yValue);
129          points.Add(dataPoint);
130        }
131      }
132    }
133
134    private void UpdateCursorInterval() {
135      var estimatedValues = this.chart.Series[PROGNOSEDVALUES_TRAINING_SERIES_NAME].Points.Select(x => x.YValues[0]).DefaultIfEmpty(1.0);
136      var targetValues = this.chart.Series[TARGETVARIABLE_SERIES_NAME].Points.Select(x => x.YValues[0]).DefaultIfEmpty(1.0);
137      double estimatedValuesRange = estimatedValues.Max() - estimatedValues.Min();
138      double targetValuesRange = targetValues.Max() - targetValues.Min();
139      double interestingValuesRange = Math.Min(Math.Max(targetValuesRange, 1.0), Math.Max(estimatedValuesRange, 1.0));
140      double digits = (int)Math.Log10(interestingValuesRange) - 3;
141      double yZoomInterval = Math.Max(Math.Pow(10, digits), 10E-5);
142      this.chart.ChartAreas[0].CursorY.Interval = yZoomInterval;
143    }
144
145    #region events
146    protected override void RegisterContentEvents() {
147      base.RegisterContentEvents();
148      Content.ModelChanged += new EventHandler(Content_ModelChanged);
149      Content.ProblemDataChanged += new EventHandler(Content_ProblemDataChanged);
150    }
151    protected override void DeregisterContentEvents() {
152      base.DeregisterContentEvents();
153      Content.ModelChanged -= new EventHandler(Content_ModelChanged);
154      Content.ProblemDataChanged -= new EventHandler(Content_ProblemDataChanged);
155    }
156
157    protected override void OnContentChanged() {
158      base.OnContentChanged();
159      RedrawChart();
160    }
161
162    private void Content_ProblemDataChanged(object sender, EventArgs e) {
163      RedrawChart();
164    }
165    private void Content_ModelChanged(object sender, EventArgs e) {
166      RedrawChart();
167    }
168
169    private void targetVariableComboBox_SelectedIndexChanged(object sender, EventArgs e) {
170      RedrawChart();
171    }
172    private void prognosedValuesCheckbox_CheckedChanged(object sender, EventArgs e) {
173      RedrawChart();
174    }
175
176    private void Chart_MouseDoubleClick(object sender, MouseEventArgs e) {
177      HitTestResult result = chart.HitTest(e.X, e.Y);
178      if (result.ChartArea != null && (result.ChartElementType == ChartElementType.PlottingArea ||
179                                       result.ChartElementType == ChartElementType.Gridlines) ||
180                                       result.ChartElementType == ChartElementType.StripLines) {
181        foreach (var axis in result.ChartArea.Axes)
182          axis.ScaleView.ZoomReset(int.MaxValue);
183      }
184    }
185    #endregion
186
187    private void UpdateStripLines() {
188      this.chart.ChartAreas[0].AxisX.StripLines.Clear();
189
190      int[] attr = new int[Content.ProblemData.Dataset.Rows + 1]; // add a virtual last row that is again empty to simplify loop further down
191      foreach (var row in Content.ProblemData.TrainingIndices) {
192        attr[row] += 1;
193      }
194      foreach (var row in Content.ProblemData.TestIndices) {
195        attr[row] += 2;
196      }
197      int start = 0;
198      int curAttr = attr[start];
199      for (int row = 0; row < attr.Length; row++) {
200        if (attr[row] != curAttr) {
201          switch (curAttr) {
202            case 0: break;
203            case 1:
204              this.CreateAndAddStripLine("Training", start, row, Color.FromArgb(40, Color.Green), Color.Transparent);
205              break;
206            case 2:
207              this.CreateAndAddStripLine("Test", start, row, Color.FromArgb(40, Color.Red), Color.Transparent);
208              break;
209            case 3:
210              this.CreateAndAddStripLine("Training and Test", start, row, Color.FromArgb(40, Color.Green), Color.FromArgb(40, Color.Red), ChartHatchStyle.WideUpwardDiagonal);
211              break;
212            default: throw new NotSupportedException();
213          }
214          curAttr = attr[row];
215          start = row;
216        }
217      }
218    }
219
220    private void CreateAndAddStripLine(string title, int start, int end, Color color, Color secondColor, ChartHatchStyle hatchStyle = ChartHatchStyle.None) {
221      StripLine stripLine = new StripLine();
222      stripLine.BackColor = color;
223      stripLine.BackSecondaryColor = secondColor;
224      stripLine.BackHatchStyle = hatchStyle;
225      stripLine.Text = title;
226      stripLine.Font = new Font("Times New Roman", 12, FontStyle.Bold);
227      // strip range is [start .. end] inclusive, but we evaluate [start..end[ (end is exclusive)
228      // the strip should be by one longer (starting at start - 0.5 and ending at end + 0.5)
229      stripLine.StripWidth = end - start;
230      stripLine.IntervalOffset = start - 0.5; // start slightly to the left of the first point to clearly indicate the first point in the partition
231      this.chart.ChartAreas[0].AxisX.StripLines.Add(stripLine);
232    }
233
234    private void ToggleSeriesData(Series series) {
235      if (series.Points.Count > 0) {  //checks if series is shown
236        if (this.chart.Series.Any(s => s != series && s.Points.Count > 0)) {
237          series.Points.Clear();
238        }
239      } else if (Content != null) {
240        IEnumerable<int> Indices = null;
241        IEnumerable<double> predictedValues = null;
242
243        switch (series.Name) {
244          case PROGNOSEDVALUES_TRAINING_SERIES_NAME:
245            Indices = Content.ProblemData.TrainingIndices.ToArray();
246            predictedValues = Content.GetPrognosedValues(Content.ProblemData.TrainingIndices.Take(1), Content.ProblemData.TrainingPartition.Size.ToEnumerable()).First();
247            break;
248          case PROGNOSEDVALUES_TEST_SERIES_NAME:
249            testPrognosisStart = Content.ProblemData.TestPartition.Start;
250            Indices = Content.ProblemData.TestIndices.ToArray();
251            predictedValues = Content.GetPrognosedValues(Content.ProblemData.TestIndices.Take(1), Content.ProblemData.TestPartition.Size.ToEnumerable()).First();
252            break;
253        }
254        series.Points.DataBindXY(Indices, predictedValues);
255        chart.DataManipulator.InsertEmptyPoints(1, IntervalType.Number, series.Name);
256        chart.Legends[series.Legend].ForeColor = Color.Black;
257        UpdateCursorInterval();
258        chart.Refresh();
259      }
260    }
261
262    private void chart_MouseMove(object sender, MouseEventArgs e) {
263      //HitTestResult result = chart.HitTest(e.X, e.Y);
264      //if (result.ChartElementType == ChartElementType.LegendItem && result.Series.Name != TARGETVARIABLE_SERIES_NAME)
265      //  Cursor = Cursors.Hand;
266      //else
267      //  Cursor = Cursors.Default;
268    }
269
270    private void chart_MouseDown(object sender, MouseEventArgs e) {
271      //HitTestResult result = chart.HitTest(e.X, e.Y);
272      //if (result.ChartElementType == ChartElementType.LegendItem && result.Series.Name != TARGETVARIABLE_SERIES_NAME) {
273      //  ToggleSeriesData(result.Series);
274      //} else if (result.ChartElementType == ChartElementType.Axis || result.ChartElementType == ChartElementType.AxisLabels ||
275      //  result.ChartElementType == ChartElementType.TickMarks) {
276      //  chart.ChartAreas[0].CursorX.SetCursorPixelPosition(new Point(e.X, e.Y), true);
277      //  int pos = (int)Math.Round(chart.ChartAreas[0].CursorX.Position);
278      //  if (pos >= Content.ProblemData.TestPartition.Start && pos < Content.ProblemData.TestPartition.End) {
279      //    testPrognosisStart = pos;
280      //    RedrawChart();
281      //  }
282      //}
283    }
284
285    private void chart_CustomizeLegend(object sender, CustomizeLegendEventArgs e) {
286      if (chart.Series.Count != 4) return;
287      e.LegendItems[0].Cells[1].ForeColor = this.chart.Series[TARGETVARIABLE_SERIES_NAME].Points.Count == 0 ? Color.Gray : Color.Black;
288      e.LegendItems[1].Cells[1].ForeColor = this.chart.Series[PROGNOSEDVALUES_TRAINING_SERIES_NAME].Points.Count == 0 ? Color.Gray : Color.Black;
289      e.LegendItems[2].Cells[1].ForeColor = this.chart.Series[PROGNOSEDVALUES_TEST_SERIES_NAME].Points.Count == 0 ? Color.Gray : Color.Black;
290      e.LegendItems[3].Cells[1].ForeColor = this.chart.Series[PROGNOSEDVALUES_ALL_SERIES_NAME].Points.Count == 0 ? Color.Gray : Color.Black;
291    }
292  }
293}
Note: See TracBrowser for help on using the repository browser.