Free cookie consent management tool by TermsFeed Policy Generator

source: branches/GP.Grammar.Editor/HeuristicLab.Problems.DataAnalysis.Views/3.4/Regression/RegressionSolutionLineChartView.cs @ 6955

Last change on this file since 6955 was 6784, checked in by mkommend, 13 years ago

#1479: Integrated trunk changes.

File size: 13.0 KB
RevLine 
[3408]1#region License Information
2/* HeuristicLab
[5445]3 * Copyright (C) 2002-2011 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
[3408]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;
[6784]22using System.Collections.Generic;
[3408]23using System.Drawing;
24using System.Linq;
25using System.Windows.Forms;
[4068]26using System.Windows.Forms.DataVisualization.Charting;
[3408]27using HeuristicLab.MainForm;
28using HeuristicLab.MainForm.WindowsForms;
29
[3442]30namespace HeuristicLab.Problems.DataAnalysis.Views {
[5975]31  [View("Line Chart")]
[5663]32  [Content(typeof(IRegressionSolution))]
[6647]33  public partial class RegressionSolutionLineChartView : DataAnalysisSolutionEvaluationView {
[6238]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)";
[6784]37    private const string ESTIMATEDVALUES_ALL_SERIES_NAME = "Estimated Values (all samples)";
[3442]38
[5663]39    public new IRegressionSolution Content {
40      get { return (IRegressionSolution)base.Content; }
[3916]41      set { base.Content = value; }
[3442]42    }
43
[5663]44    public RegressionSolutionLineChartView()
[3408]45      : base() {
46      InitializeComponent();
47      //configure axis
[4651]48      this.chart.CustomizeAllChartAreas();
[3408]49      this.chart.ChartAreas[0].CursorX.IsUserSelectionEnabled = true;
50      this.chart.ChartAreas[0].AxisX.ScaleView.Zoomable = true;
[6238]51      this.chart.ChartAreas[0].AxisX.IsStartedFromZero = true;
[3707]52      this.chart.ChartAreas[0].CursorX.Interval = 1;
[3408]53
54      this.chart.ChartAreas[0].CursorY.IsUserSelectionEnabled = true;
55      this.chart.ChartAreas[0].AxisY.ScaleView.Zoomable = true;
[3442]56      this.chart.ChartAreas[0].CursorY.Interval = 0;
[3408]57    }
58
[3462]59    private void RedrawChart() {
[3442]60      this.chart.Series.Clear();
[4011]61      if (Content != null) {
[6238]62        this.chart.ChartAreas[0].AxisX.Minimum = 0;
63        this.chart.ChartAreas[0].AxisX.Maximum = Content.ProblemData.Dataset.Rows - 1;
64
[4011]65        this.chart.Series.Add(TARGETVARIABLE_SERIES_NAME);
[5663]66        this.chart.Series[TARGETVARIABLE_SERIES_NAME].LegendText = Content.ProblemData.TargetVariable;
[4011]67        this.chart.Series[TARGETVARIABLE_SERIES_NAME].ChartType = SeriesChartType.FastLine;
[6238]68        this.chart.Series[TARGETVARIABLE_SERIES_NAME].Points.DataBindXY(Enumerable.Range(0, Content.ProblemData.Dataset.Rows).ToArray(),
[6784]69          Content.ProblemData.Dataset.GetDoubleValues(Content.ProblemData.TargetVariable).ToArray());
[3462]70
[6238]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;
[6784]74        this.chart.Series[ESTIMATEDVALUES_TRAINING_SERIES_NAME].Points.DataBindXY(Content.ProblemData.TrainingIndizes.ToArray(), Content.EstimatedTrainingValues.ToArray());
[6238]75        this.chart.Series[ESTIMATEDVALUES_TRAINING_SERIES_NAME].Tag = Content;
[6784]76        this.chart.DataManipulator.InsertEmptyPoints(1, IntervalType.Number, ESTIMATEDVALUES_TRAINING_SERIES_NAME);
77        this.chart.Series[ESTIMATEDVALUES_TRAINING_SERIES_NAME].EmptyPointStyle.BorderWidth = 0;
78        this.chart.Series[ESTIMATEDVALUES_TRAINING_SERIES_NAME].EmptyPointStyle.MarkerStyle = MarkerStyle.None;
[6238]79
[6784]80
[6238]81        this.chart.Series.Add(ESTIMATEDVALUES_TEST_SERIES_NAME);
82        this.chart.Series[ESTIMATEDVALUES_TEST_SERIES_NAME].LegendText = ESTIMATEDVALUES_TEST_SERIES_NAME;
83        this.chart.Series[ESTIMATEDVALUES_TEST_SERIES_NAME].ChartType = SeriesChartType.FastLine;
[6784]84        this.chart.Series[ESTIMATEDVALUES_TEST_SERIES_NAME].Points.DataBindXY(Content.ProblemData.TestIndizes.ToArray(), Content.EstimatedTestValues.ToArray());
[6238]85        this.chart.Series[ESTIMATEDVALUES_TEST_SERIES_NAME].Tag = Content;
[6784]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.EstimatedValues.ToArray();
90        List<double> allEstimatedValues = allIndizes.Select(index => estimatedValues[index]).ToList();
91
92        this.chart.Series.Add(ESTIMATEDVALUES_ALL_SERIES_NAME);
93        this.chart.Series[ESTIMATEDVALUES_ALL_SERIES_NAME].LegendText = ESTIMATEDVALUES_ALL_SERIES_NAME;
94        this.chart.Series[ESTIMATEDVALUES_ALL_SERIES_NAME].ChartType = SeriesChartType.FastLine;
95        this.chart.Series[ESTIMATEDVALUES_ALL_SERIES_NAME].Points.DataBindXY(allIndizes, allEstimatedValues);
96        this.chart.Series[ESTIMATEDVALUES_ALL_SERIES_NAME].Tag = Content;
97        this.chart.DataManipulator.InsertEmptyPoints(1, IntervalType.Number, ESTIMATEDVALUES_ALL_SERIES_NAME);
98        this.chart.Series[ESTIMATEDVALUES_TRAINING_SERIES_NAME].EmptyPointStyle.BorderWidth = 0;
99        this.chart.Series[ESTIMATEDVALUES_TRAINING_SERIES_NAME].EmptyPointStyle.MarkerStyle = MarkerStyle.None;
100        this.ToggleSeriesData(this.chart.Series[ESTIMATEDVALUES_ALL_SERIES_NAME]);
101
[4011]102        UpdateCursorInterval();
[6238]103        this.UpdateStripLines();
[4011]104      }
[3408]105    }
106
[3707]107    private void UpdateCursorInterval() {
[6238]108      var estimatedValues = this.chart.Series[ESTIMATEDVALUES_TRAINING_SERIES_NAME].Points.Select(x => x.YValues[0]).DefaultIfEmpty(1.0);
[3707]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
[3442]118    #region events
119    protected override void RegisterContentEvents() {
120      base.RegisterContentEvents();
[5663]121      Content.ModelChanged += new EventHandler(Content_ModelChanged);
[3442]122      Content.ProblemDataChanged += new EventHandler(Content_ProblemDataChanged);
[3408]123    }
[3442]124    protected override void DeregisterContentEvents() {
125      base.DeregisterContentEvents();
[5663]126      Content.ModelChanged -= new EventHandler(Content_ModelChanged);
[3442]127      Content.ProblemDataChanged -= new EventHandler(Content_ProblemDataChanged);
[3408]128    }
129
[6784]130    protected override void OnContentChanged() {
131      base.OnContentChanged();
132      RedrawChart();
133    }
[3916]134    private void Content_ProblemDataChanged(object sender, EventArgs e) {
[3462]135      RedrawChart();
[3408]136    }
[5663]137    private void Content_ModelChanged(object sender, EventArgs e) {
[3462]138      RedrawChart();
[3442]139    }
140
[5006]141
[6784]142
[5006]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    }
[3442]152    #endregion
[3408]153
154    private void UpdateStripLines() {
155      this.chart.ChartAreas[0].AxisX.StripLines.Clear();
[6238]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      }
[3408]187    }
188
[6238]189    private void CreateAndAddStripLine(string title, int start, int end, Color color, Color secondColor, ChartHatchStyle hatchStyle = ChartHatchStyle.None) {
[3408]190      StripLine stripLine = new StripLine();
[6238]191      stripLine.BackColor = color;
192      stripLine.BackSecondaryColor = secondColor;
193      stripLine.BackHatchStyle = hatchStyle;
[3408]194      stripLine.Text = title;
195      stripLine.Font = new Font("Times New Roman", 12, FontStyle.Bold);
[6252]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)
[6618]198      stripLine.StripWidth = end - start;
[6252]199      stripLine.IntervalOffset = start - 0.5; // start slightly to the left of the first point to clearly indicate the first point in the partition
[3408]200      this.chart.ChartAreas[0].AxisX.StripLines.Add(stripLine);
201    }
[6784]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 ESTIMATEDVALUES_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.EstimatedValues.ToArray();
217            predictedValues = indizes.Select(index => estimatedValues[index]).ToList();
218            break;
219          case ESTIMATEDVALUES_TRAINING_SERIES_NAME:
220            indizes = Content.ProblemData.TrainingIndizes.ToArray();
221            predictedValues = Content.EstimatedTrainingValues.ToArray();
222            break;
223          case ESTIMATEDVALUES_TEST_SERIES_NAME:
224            indizes = Content.ProblemData.TestIndizes.ToArray();
225            predictedValues = Content.EstimatedTestValues.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[ESTIMATEDVALUES_TRAINING_SERIES_NAME].Points.Count == 0 ? Color.Gray : Color.Black;
254      e.LegendItems[2].Cells[1].ForeColor = this.chart.Series[ESTIMATEDVALUES_TEST_SERIES_NAME].Points.Count == 0 ? Color.Gray : Color.Black;
255      e.LegendItems[3].Cells[1].ForeColor = this.chart.Series[ESTIMATEDVALUES_ALL_SERIES_NAME].Points.Count == 0 ? Color.Gray : Color.Black;
256    }
[3408]257  }
258}
Note: See TracBrowser for help on using the repository browser.