Free cookie consent management tool by TermsFeed Policy Generator

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

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

#1081: Corrected time series solution results and implemented new models.

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