Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Problems.DataAnalysis.Views/3.4/TimeSeriesPrognosis/TimeSeriesPrognosisSolutionLineChartView.cs @ 6802

Last change on this file since 6802 was 6802, checked in by gkronber, 13 years ago

#1081 added classes (problem, evaluators, analyzers, solution, model, online-calculators, and views) for time series prognosis problems and added an algorithm implementation to generation linear AR (auto-regressive) time series prognosis solution.

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