Free cookie consent management tool by TermsFeed Policy Generator

source: branches/dataset-ids-2695/HeuristicLab.Problems.DataAnalysis.Views/3.4/Regression/RegressionSolutionLineChartViewBase.cs @ 15298

Last change on this file since 15298 was 15298, checked in by gkronber, 7 years ago

#2695: removed commented code and unused usings

File size: 14.5 KB
RevLine 
[3408]1#region License Information
2/* HeuristicLab
[14185]3 * Copyright (C) 2002-2016 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;
22using System.Drawing;
23using System.Linq;
24using System.Windows.Forms;
[4068]25using System.Windows.Forms.DataVisualization.Charting;
[3408]26using HeuristicLab.MainForm;
[14008]27using HeuristicLab.Visualization.ChartControlsExtensions;
[3408]28
[3442]29namespace HeuristicLab.Problems.DataAnalysis.Views {
[5975]30  [View("Line Chart")]
[5663]31  [Content(typeof(IRegressionSolution))]
[14486]32  public abstract partial class RegressionSolutionLineChartViewBase : DataAnalysisSolutionEvaluationView {
[14483]33    protected const string TARGETVARIABLE_SERIES_NAME = "Target Variable";
34    protected const string ESTIMATEDVALUES_TRAINING_SERIES_NAME = "Estimated Values (training)";
35    protected const string ESTIMATEDVALUES_TEST_SERIES_NAME = "Estimated Values (test)";
36    protected const string ESTIMATEDVALUES_ALL_SERIES_NAME = "Estimated Values (all samples)";
[3442]37
[5663]38    public new IRegressionSolution Content {
39      get { return (IRegressionSolution)base.Content; }
[3916]40      set { base.Content = value; }
[3442]41    }
42
[14486]43    protected RegressionSolutionLineChartViewBase()
[3408]44      : base() {
45      InitializeComponent();
46      //configure axis
[4651]47      this.chart.CustomizeAllChartAreas();
[3408]48      this.chart.ChartAreas[0].CursorX.IsUserSelectionEnabled = true;
49      this.chart.ChartAreas[0].AxisX.ScaleView.Zoomable = true;
[6238]50      this.chart.ChartAreas[0].AxisX.IsStartedFromZero = true;
[3707]51      this.chart.ChartAreas[0].CursorX.Interval = 1;
[3408]52
53      this.chart.ChartAreas[0].CursorY.IsUserSelectionEnabled = true;
54      this.chart.ChartAreas[0].AxisY.ScaleView.Zoomable = true;
[3442]55      this.chart.ChartAreas[0].CursorY.Interval = 0;
[3408]56    }
57
[14486]58    protected abstract void GetTrainingSeries(out int[] idx, out double[] y);
[14422]59
[15297]60    protected abstract void GetTestSeries(out int[] idx, out double[] y);
[14422]61
[15297]62    protected abstract void GetAllValuesSeries(out int[] idx, out double[] y);
[14422]63
[14483]64    protected virtual void RedrawChart() {
[3442]65      this.chart.Series.Clear();
[4011]66      if (Content != null) {
[15297]67        var allIds = Content.ProblemData.AllIds;
[6238]68        this.chart.ChartAreas[0].AxisX.Minimum = 0;
[15297]69        this.chart.ChartAreas[0].AxisX.Maximum = Content.ProblemData.AllIndices.Last();
[6238]70
[4011]71        this.chart.Series.Add(TARGETVARIABLE_SERIES_NAME);
[14255]72        this.chart.Series[TARGETVARIABLE_SERIES_NAME].LegendText = TARGETVARIABLE_SERIES_NAME;
[4011]73        this.chart.Series[TARGETVARIABLE_SERIES_NAME].ChartType = SeriesChartType.FastLine;
[15297]74        var ids = Content.ProblemData.AllIds.OfType<object>().Select(o => o.ToString()).ToArray();
75        var vals = Content.ProblemData.Dataset.GetDoubleValues(Content.ProblemData.TargetVariable).ToArray();
76
77        for (int i = 0; i < ids.Length; i++) {
[15298]78          chart.Series[TARGETVARIABLE_SERIES_NAME].Points.Add(new DataPoint()
79          {
80            AxisLabel = ids[i], XValue = i, YValues = new double[] { vals[i] }
81          });
[15297]82        }
[6238]83        this.chart.Series.Add(ESTIMATEDVALUES_TRAINING_SERIES_NAME);
84        this.chart.Series[ESTIMATEDVALUES_TRAINING_SERIES_NAME].LegendText = ESTIMATEDVALUES_TRAINING_SERIES_NAME;
85        this.chart.Series[ESTIMATEDVALUES_TRAINING_SERIES_NAME].ChartType = SeriesChartType.FastLine;
[7333]86        this.chart.Series[ESTIMATEDVALUES_TRAINING_SERIES_NAME].EmptyPointStyle.Color = this.chart.Series[ESTIMATEDVALUES_TRAINING_SERIES_NAME].Color;
[14422]87        int[] trainingIdx;
88        double[] trainingY;
89        GetTrainingSeries(out trainingIdx, out trainingY);
90        this.chart.Series[ESTIMATEDVALUES_TRAINING_SERIES_NAME].Points.DataBindXY(trainingIdx, trainingY);
[7406]91        this.InsertEmptyPoints(this.chart.Series[ESTIMATEDVALUES_TRAINING_SERIES_NAME]);
[6238]92        this.chart.Series[ESTIMATEDVALUES_TRAINING_SERIES_NAME].Tag = Content;
[14422]93
[7327]94        // test series
[6238]95        this.chart.Series.Add(ESTIMATEDVALUES_TEST_SERIES_NAME);
96        this.chart.Series[ESTIMATEDVALUES_TEST_SERIES_NAME].LegendText = ESTIMATEDVALUES_TEST_SERIES_NAME;
97        this.chart.Series[ESTIMATEDVALUES_TEST_SERIES_NAME].ChartType = SeriesChartType.FastLine;
[14422]98        int[] testIdx;
99        double[] testY;
100        GetTestSeries(out testIdx, out testY);
101        this.chart.Series[ESTIMATEDVALUES_TEST_SERIES_NAME].Points.DataBindXY(testIdx, testY);
[7406]102        this.InsertEmptyPoints(this.chart.Series[ESTIMATEDVALUES_TEST_SERIES_NAME]);
[6238]103        this.chart.Series[ESTIMATEDVALUES_TEST_SERIES_NAME].Tag = Content;
[14422]104
[7327]105        // series of remaining points
[14422]106        int[] allIdx;
107        double[] allEstimatedValues;
108        GetAllValuesSeries(out allIdx, out allEstimatedValues);
109
[6679]110        this.chart.Series.Add(ESTIMATEDVALUES_ALL_SERIES_NAME);
111        this.chart.Series[ESTIMATEDVALUES_ALL_SERIES_NAME].LegendText = ESTIMATEDVALUES_ALL_SERIES_NAME;
112        this.chart.Series[ESTIMATEDVALUES_ALL_SERIES_NAME].ChartType = SeriesChartType.FastLine;
[14422]113        if (allEstimatedValues.Length > 0) {
114          this.chart.Series[ESTIMATEDVALUES_ALL_SERIES_NAME].Points.DataBindXY(allIdx, allEstimatedValues);
[8485]115          this.InsertEmptyPoints(this.chart.Series[ESTIMATEDVALUES_ALL_SERIES_NAME]);
116        }
[6679]117        this.chart.Series[ESTIMATEDVALUES_ALL_SERIES_NAME].Tag = Content;
118        this.ToggleSeriesData(this.chart.Series[ESTIMATEDVALUES_ALL_SERIES_NAME]);
119
[14255]120        // set the y-axis
[14008]121        var axisY = this.chart.ChartAreas[0].AxisY;
[14255]122        axisY.Title = Content.ProblemData.TargetVariable;
[14008]123        double min = double.MaxValue, max = double.MinValue;
124        foreach (var point in chart.Series.SelectMany(x => x.Points)) {
125          if (!point.YValues.Any() || double.IsInfinity(point.YValues[0]) || double.IsNaN(point.YValues[0]))
126            continue;
127          var y = point.YValues[0];
128          if (y < min)
129            min = y;
130          if (y > max)
131            max = y;
132        }
133
134        double axisMin, axisMax, axisInterval;
135        ChartUtil.CalculateOptimalAxisInterval(min, max, out axisMin, out axisMax, out axisInterval);
136        axisY.Minimum = axisMin;
137        axisY.Maximum = axisMax;
138        axisY.Interval = axisInterval;
139
[4011]140        UpdateCursorInterval();
[15297]141        UpdateStripLines();
[4011]142      }
[3408]143    }
144
[7406]145    private void InsertEmptyPoints(Series series) {
146      int i = 0;
147      while (i < series.Points.Count - 1) {
148        if (series.Points[i].IsEmpty) {
149          ++i;
150          continue;
151        }
152
153        var p1 = series.Points[i];
154        var p2 = series.Points[i + 1];
155        // check for consecutive indices
156        if ((int)p2.XValue - (int)p1.XValue != 1) {
157          // insert an empty point between p1 and p2 so that the line will be invisible (transparent)
158          var p = new DataPoint((int)((p1.XValue + p2.XValue) / 2), 0.0) { IsEmpty = true };
159          series.Points.Insert(i + 1, p);
160        }
161        ++i;
162      }
163    }
164
[3707]165    private void UpdateCursorInterval() {
[6238]166      var estimatedValues = this.chart.Series[ESTIMATEDVALUES_TRAINING_SERIES_NAME].Points.Select(x => x.YValues[0]).DefaultIfEmpty(1.0);
[3707]167      var targetValues = this.chart.Series[TARGETVARIABLE_SERIES_NAME].Points.Select(x => x.YValues[0]).DefaultIfEmpty(1.0);
168      double estimatedValuesRange = estimatedValues.Max() - estimatedValues.Min();
169      double targetValuesRange = targetValues.Max() - targetValues.Min();
170      double interestingValuesRange = Math.Min(Math.Max(targetValuesRange, 1.0), Math.Max(estimatedValuesRange, 1.0));
171      double digits = (int)Math.Log10(interestingValuesRange) - 3;
172      double yZoomInterval = Math.Max(Math.Pow(10, digits), 10E-5);
173      this.chart.ChartAreas[0].CursorY.Interval = yZoomInterval;
174    }
175
[3442]176    #region events
177    protected override void RegisterContentEvents() {
178      base.RegisterContentEvents();
[5663]179      Content.ModelChanged += new EventHandler(Content_ModelChanged);
[3442]180      Content.ProblemDataChanged += new EventHandler(Content_ProblemDataChanged);
[3408]181    }
[3442]182    protected override void DeregisterContentEvents() {
183      base.DeregisterContentEvents();
[5663]184      Content.ModelChanged -= new EventHandler(Content_ModelChanged);
[3442]185      Content.ProblemDataChanged -= new EventHandler(Content_ProblemDataChanged);
[3408]186    }
187
[6679]188    protected override void OnContentChanged() {
189      base.OnContentChanged();
190      RedrawChart();
191    }
[3916]192    private void Content_ProblemDataChanged(object sender, EventArgs e) {
[3462]193      RedrawChart();
[3408]194    }
[5663]195    private void Content_ModelChanged(object sender, EventArgs e) {
[3462]196      RedrawChart();
[3442]197    }
198
[5006]199
[6679]200
[5006]201    private void Chart_MouseDoubleClick(object sender, MouseEventArgs e) {
202      HitTestResult result = chart.HitTest(e.X, e.Y);
203      if (result.ChartArea != null && (result.ChartElementType == ChartElementType.PlottingArea ||
204                                       result.ChartElementType == ChartElementType.Gridlines) ||
205                                       result.ChartElementType == ChartElementType.StripLines) {
206        foreach (var axis in result.ChartArea.Axes)
207          axis.ScaleView.ZoomReset(int.MaxValue);
208      }
209    }
[3442]210    #endregion
[3408]211
212    private void UpdateStripLines() {
213      this.chart.ChartAreas[0].AxisX.StripLines.Clear();
[6238]214
215      int[] attr = new int[Content.ProblemData.Dataset.Rows + 1]; // add a virtual last row that is again empty to simplify loop further down
[8139]216      foreach (var row in Content.ProblemData.TrainingIndices) {
[6238]217        attr[row] += 1;
218      }
[8139]219      foreach (var row in Content.ProblemData.TestIndices) {
[6238]220        attr[row] += 2;
221      }
222      int start = 0;
223      int curAttr = attr[start];
224      for (int row = 0; row < attr.Length; row++) {
225        if (attr[row] != curAttr) {
226          switch (curAttr) {
227            case 0: break;
228            case 1:
229              this.CreateAndAddStripLine("Training", start, row, Color.FromArgb(40, Color.Green), Color.Transparent);
230              break;
231            case 2:
232              this.CreateAndAddStripLine("Test", start, row, Color.FromArgb(40, Color.Red), Color.Transparent);
233              break;
234            case 3:
235              this.CreateAndAddStripLine("Training and Test", start, row, Color.FromArgb(40, Color.Green), Color.FromArgb(40, Color.Red), ChartHatchStyle.WideUpwardDiagonal);
236              break;
237            default:
238              // should not happen
239              break;
240          }
241          curAttr = attr[row];
242          start = row;
243        }
244      }
[3408]245    }
246
[6238]247    private void CreateAndAddStripLine(string title, int start, int end, Color color, Color secondColor, ChartHatchStyle hatchStyle = ChartHatchStyle.None) {
[3408]248      StripLine stripLine = new StripLine();
[6238]249      stripLine.BackColor = color;
250      stripLine.BackSecondaryColor = secondColor;
251      stripLine.BackHatchStyle = hatchStyle;
[3408]252      stripLine.Text = title;
253      stripLine.Font = new Font("Times New Roman", 12, FontStyle.Bold);
[6252]254      // strip range is [start .. end] inclusive, but we evaluate [start..end[ (end is exclusive)
255      // the strip should be by one longer (starting at start - 0.5 and ending at end + 0.5)
[6520]256      stripLine.StripWidth = end - start;
[6252]257      stripLine.IntervalOffset = start - 0.5; // start slightly to the left of the first point to clearly indicate the first point in the partition
[3408]258      this.chart.ChartAreas[0].AxisX.StripLines.Add(stripLine);
259    }
[6679]260
[14531]261    public void ToggleSeriesData(Series series) {
[6679]262      if (series.Points.Count > 0) {  //checks if series is shown
263        if (this.chart.Series.Any(s => s != series && s.Points.Count > 0)) {
[7406]264          ClearPointsQuick(series.Points);
[6679]265        }
266      } else if (Content != null) {
267
[14422]268        int[] indices = null;
[8485]269        double[] predictedValues = null;
[6679]270        switch (series.Name) {
271          case ESTIMATEDVALUES_ALL_SERIES_NAME:
[14422]272            GetAllValuesSeries(out indices, out predictedValues);
[6679]273            break;
274          case ESTIMATEDVALUES_TRAINING_SERIES_NAME:
[14422]275            GetTrainingSeries(out indices, out predictedValues);
[6679]276            break;
277          case ESTIMATEDVALUES_TEST_SERIES_NAME:
[14422]278            GetTestSeries(out indices, out predictedValues);
[6679]279            break;
280        }
[8485]281        if (predictedValues.Length > 0) {
282          series.Points.DataBindXY(indices, predictedValues);
283          this.InsertEmptyPoints(series);
284        }
[6679]285        chart.Legends[series.Legend].ForeColor = Color.Black;
286        UpdateCursorInterval();
[6775]287        chart.Refresh();
[6679]288      }
289    }
290
[7406]291    // workaround as per http://stackoverflow.com/questions/5744930/datapointcollection-clear-performance
292    private static void ClearPointsQuick(DataPointCollection points) {
293      points.SuspendUpdates();
294      while (points.Count > 0)
295        points.RemoveAt(points.Count - 1);
296      points.ResumeUpdates();
297    }
298
[6679]299    private void chart_MouseMove(object sender, MouseEventArgs e) {
300      HitTestResult result = chart.HitTest(e.X, e.Y);
301      if (result.ChartElementType == ChartElementType.LegendItem && result.Series.Name != TARGETVARIABLE_SERIES_NAME)
302        Cursor = Cursors.Hand;
303      else
304        Cursor = Cursors.Default;
305    }
306    private void chart_MouseDown(object sender, MouseEventArgs e) {
307      HitTestResult result = chart.HitTest(e.X, e.Y);
308      if (result.ChartElementType == ChartElementType.LegendItem && result.Series.Name != TARGETVARIABLE_SERIES_NAME) {
309        ToggleSeriesData(result.Series);
310      }
311    }
312
313    private void chart_CustomizeLegend(object sender, CustomizeLegendEventArgs e) {
314      if (chart.Series.Count != 4) return;
315      e.LegendItems[0].Cells[1].ForeColor = this.chart.Series[TARGETVARIABLE_SERIES_NAME].Points.Count == 0 ? Color.Gray : Color.Black;
316      e.LegendItems[1].Cells[1].ForeColor = this.chart.Series[ESTIMATEDVALUES_TRAINING_SERIES_NAME].Points.Count == 0 ? Color.Gray : Color.Black;
317      e.LegendItems[2].Cells[1].ForeColor = this.chart.Series[ESTIMATEDVALUES_TEST_SERIES_NAME].Points.Count == 0 ? Color.Gray : Color.Black;
318      e.LegendItems[3].Cells[1].ForeColor = this.chart.Series[ESTIMATEDVALUES_ALL_SERIES_NAME].Points.Count == 0 ? Color.Gray : Color.Black;
319    }
[3408]320  }
321}
Note: See TracBrowser for help on using the repository browser.