Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Problems.DataAnalysis.Views/3.4/Regression/RegressionSolutionScatterPlotView.cs @ 13825

Last change on this file since 13825 was 13764, checked in by bburlacu, 9 years ago

#2594: Add ChartUtil methods and improved scaling in RegressionSolutionScatterPlotView.

File size: 12.0 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2015 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.Drawing;
23using System.Linq;
24using System.Windows.Forms;
25using System.Windows.Forms.DataVisualization.Charting;
26using HeuristicLab.MainForm;
27using HeuristicLab.MainForm.WindowsForms;
28using HeuristicLab.Visualization.ChartControlsExtensions;
29
30namespace HeuristicLab.Problems.DataAnalysis.Views {
31  [View("Scatter Plot")]
32  [Content(typeof(IRegressionSolution))]
33  public partial class RegressionSolutionScatterPlotView : DataAnalysisSolutionEvaluationView {
34    private const string ALL_SERIES = "All samples";
35    private const string TRAINING_SERIES = "Training samples";
36    private const string TEST_SERIES = "Test samples";
37
38    public new IRegressionSolution Content {
39      get { return (IRegressionSolution)base.Content; }
40      set { base.Content = value; }
41    }
42
43    public RegressionSolutionScatterPlotView()
44      : base() {
45      InitializeComponent();
46
47      this.chart.Series.Add(ALL_SERIES);
48      this.chart.Series[ALL_SERIES].LegendText = ALL_SERIES;
49      this.chart.Series[ALL_SERIES].ChartType = SeriesChartType.FastPoint;
50
51      this.chart.Series.Add(TRAINING_SERIES);
52      this.chart.Series[TRAINING_SERIES].LegendText = TRAINING_SERIES;
53      this.chart.Series[TRAINING_SERIES].ChartType = SeriesChartType.FastPoint;
54      this.chart.Series[TRAINING_SERIES].Points.Add(1.0);
55
56      this.chart.Series.Add(TEST_SERIES);
57      this.chart.Series[TEST_SERIES].LegendText = TEST_SERIES;
58      this.chart.Series[TEST_SERIES].ChartType = SeriesChartType.FastPoint;
59
60      this.chart.TextAntiAliasingQuality = TextAntiAliasingQuality.High;
61      this.chart.AxisViewChanged += new EventHandler<System.Windows.Forms.DataVisualization.Charting.ViewEventArgs>(chart_AxisViewChanged);
62
63      //configure axis
64      this.chart.CustomizeAllChartAreas();
65      this.chart.ChartAreas[0].AxisX.Title = "Estimated Values";
66      this.chart.ChartAreas[0].CursorX.IsUserSelectionEnabled = true;
67      this.chart.ChartAreas[0].AxisX.ScaleView.Zoomable = true;
68      this.chart.ChartAreas[0].CursorX.Interval = 1;
69      this.chart.ChartAreas[0].CursorY.Interval = 1;
70
71      this.chart.ChartAreas[0].AxisY.Title = "Target Values";
72      this.chart.ChartAreas[0].CursorY.IsUserSelectionEnabled = true;
73      this.chart.ChartAreas[0].AxisY.ScaleView.Zoomable = true;
74      this.chart.ChartAreas[0].AxisY.IsStartedFromZero = true;
75    }
76
77    protected override void RegisterContentEvents() {
78      base.RegisterContentEvents();
79      Content.ModelChanged += new EventHandler(Content_ModelChanged);
80      Content.ProblemDataChanged += new EventHandler(Content_ProblemDataChanged);
81    }
82    protected override void DeregisterContentEvents() {
83      base.DeregisterContentEvents();
84      Content.ModelChanged -= new EventHandler(Content_ModelChanged);
85      Content.ProblemDataChanged -= new EventHandler(Content_ProblemDataChanged);
86    }
87
88
89    private void Content_ProblemDataChanged(object sender, EventArgs e) {
90      UpdateChart();
91    }
92    private void Content_ModelChanged(object sender, EventArgs e) {
93      UpdateSeries();
94    }
95
96    protected override void OnContentChanged() {
97      base.OnContentChanged();
98      UpdateChart();
99    }
100
101    private void UpdateChart() {
102      if (InvokeRequired) Invoke((Action)UpdateChart);
103      else {
104        if (Content != null) {
105          this.UpdateSeries();
106          if (!this.chart.Series.Any(s => s.Points.Count > 0))
107            this.ClearChart();
108        }
109      }
110    }
111
112    private void UpdateCursorInterval() {
113      var estimatedValues = this.chart.Series[ALL_SERIES].Points.Select(x => x.XValue).DefaultIfEmpty(1.0);
114      var targetValues = this.chart.Series[ALL_SERIES].Points.Select(x => x.YValues[0]).DefaultIfEmpty(1.0);
115      double estimatedValuesRange = estimatedValues.Max() - estimatedValues.Min();
116      double targetValuesRange = targetValues.Max() - targetValues.Min();
117      double interestingValuesRange = Math.Min(Math.Max(targetValuesRange, 1.0), Math.Max(estimatedValuesRange, 1.0));
118      double digits = (int)Math.Log10(interestingValuesRange) - 3;
119      double zoomInterval = Math.Max(Math.Pow(10, digits), 10E-5);
120      this.chart.ChartAreas[0].CursorX.Interval = zoomInterval;
121      this.chart.ChartAreas[0].CursorY.Interval = zoomInterval;
122
123      this.chart.ChartAreas[0].AxisX.ScaleView.SmallScrollSize = zoomInterval;
124      this.chart.ChartAreas[0].AxisY.ScaleView.SmallScrollSize = zoomInterval;
125
126      this.chart.ChartAreas[0].AxisX.ScaleView.SmallScrollMinSizeType = DateTimeIntervalType.Number;
127      this.chart.ChartAreas[0].AxisX.ScaleView.SmallScrollMinSize = zoomInterval;
128      this.chart.ChartAreas[0].AxisY.ScaleView.SmallScrollMinSizeType = DateTimeIntervalType.Number;
129      this.chart.ChartAreas[0].AxisY.ScaleView.SmallScrollMinSize = zoomInterval;
130
131      if (digits < 0) {
132        this.chart.ChartAreas[0].AxisX.LabelStyle.Format = "F" + (int)Math.Abs(digits);
133        this.chart.ChartAreas[0].AxisY.LabelStyle.Format = "F" + (int)Math.Abs(digits);
134      } else {
135        this.chart.ChartAreas[0].AxisX.LabelStyle.Format = "F0";
136        this.chart.ChartAreas[0].AxisY.LabelStyle.Format = "F0";
137      }
138    }
139
140
141    private void UpdateSeries() {
142      if (InvokeRequired) Invoke((Action)UpdateSeries);
143      else {
144        string targetVariableName = Content.ProblemData.TargetVariable;
145        var dataset = Content.ProblemData.Dataset;
146        if (this.chart.Series[ALL_SERIES].Points.Count > 0)
147          this.chart.Series[ALL_SERIES].Points.DataBindXY(Content.EstimatedValues.ToArray(), "",
148            dataset.GetDoubleValues(targetVariableName).ToArray(), "");
149        if (this.chart.Series[TRAINING_SERIES].Points.Count > 0)
150          this.chart.Series[TRAINING_SERIES].Points.DataBindXY(Content.EstimatedTrainingValues.ToArray(), "",
151            dataset.GetDoubleValues(targetVariableName, Content.ProblemData.TrainingIndices).ToArray(), "");
152        if (this.chart.Series[TEST_SERIES].Points.Count > 0)
153          this.chart.Series[TEST_SERIES].Points.DataBindXY(Content.EstimatedTestValues.ToArray(), "",
154           dataset.GetDoubleValues(targetVariableName, Content.ProblemData.TestIndices).ToArray(), "");
155
156        double max = Content.EstimatedTrainingValues.Concat(Content.EstimatedTestValues.Concat(Content.EstimatedValues.Concat(dataset.GetDoubleValues(targetVariableName)))).Max();
157        double min = Content.EstimatedTrainingValues.Concat(Content.EstimatedTestValues.Concat(Content.EstimatedValues.Concat(dataset.GetDoubleValues(targetVariableName)))).Min();
158
159        double axisMin, axisMax, axisInterval;
160        ChartUtil.CalculateAxisInterval(min, max, 5, out axisMin, out axisMax, out axisInterval);
161        this.chart.ChartAreas[0].AxisX.Maximum = axisMax;
162        this.chart.ChartAreas[0].AxisX.Minimum = axisMin;
163        this.chart.ChartAreas[0].AxisX.Interval = axisInterval;
164        this.chart.ChartAreas[0].AxisY.Maximum = axisMax;
165        this.chart.ChartAreas[0].AxisY.Minimum = axisMin;
166        this.chart.ChartAreas[0].AxisY.Interval = axisInterval;
167
168        UpdateCursorInterval();
169      }
170    }
171
172    private void ClearChart() {
173      this.chart.Series[ALL_SERIES].Points.Clear();
174      this.chart.Series[TRAINING_SERIES].Points.Clear();
175      this.chart.Series[TEST_SERIES].Points.Clear();
176    }
177
178    private void ToggleSeriesData(Series series) {
179      if (series.Points.Count > 0) {  //checks if series is shown
180        if (this.chart.Series.Any(s => s != series && s.Points.Count > 0)) {
181          series.Points.Clear();
182        }
183      } else if (Content != null) {
184        string targetVariableName = Content.ProblemData.TargetVariable;
185
186        double[] predictedValues = null;
187        double[] targetValues = null;
188        switch (series.Name) {
189          case ALL_SERIES:
190            predictedValues = Content.EstimatedValues.ToArray();
191            targetValues = Content.ProblemData.Dataset.GetDoubleValues(targetVariableName).ToArray();
192            break;
193          case TRAINING_SERIES:
194            predictedValues = Content.EstimatedTrainingValues.ToArray();
195            targetValues = Content.ProblemData.Dataset.GetDoubleValues(targetVariableName, Content.ProblemData.TrainingIndices).ToArray();
196            break;
197          case TEST_SERIES:
198            predictedValues = Content.EstimatedTestValues.ToArray();
199            targetValues = Content.ProblemData.Dataset.GetDoubleValues(targetVariableName, Content.ProblemData.TestIndices).ToArray();
200            break;
201        }
202        if (predictedValues.Length == targetValues.Length)
203          series.Points.DataBindXY(predictedValues, "", targetValues, "");
204        this.chart.Legends[series.Legend].ForeColor = Color.Black;
205        UpdateCursorInterval();
206      }
207    }
208
209    private void chart_MouseDown(object sender, MouseEventArgs e) {
210      HitTestResult result = chart.HitTest(e.X, e.Y);
211      if (result.ChartElementType == ChartElementType.LegendItem) {
212        this.ToggleSeriesData(result.Series);
213      }
214    }
215
216    private void chart_MouseMove(object sender, MouseEventArgs e) {
217      HitTestResult result = chart.HitTest(e.X, e.Y);
218      if (result.ChartElementType == ChartElementType.LegendItem)
219        this.Cursor = Cursors.Hand;
220      else
221        this.Cursor = Cursors.Default;
222    }
223
224    private void chart_AxisViewChanged(object sender, System.Windows.Forms.DataVisualization.Charting.ViewEventArgs e) {
225      this.chart.ChartAreas[0].AxisX.ScaleView.Size = e.NewSize;
226      this.chart.ChartAreas[0].AxisY.ScaleView.Size = e.NewSize;
227    }
228
229    private void chart_CustomizeLegend(object sender, CustomizeLegendEventArgs e) {
230      e.LegendItems[0].Cells[1].ForeColor = this.chart.Series[ALL_SERIES].Points.Count == 0 ? Color.Gray : Color.Black;
231      e.LegendItems[1].Cells[1].ForeColor = this.chart.Series[TRAINING_SERIES].Points.Count == 0 ? Color.Gray : Color.Black;
232      e.LegendItems[2].Cells[1].ForeColor = this.chart.Series[TEST_SERIES].Points.Count == 0 ? Color.Gray : Color.Black;
233    }
234
235    private void chart_PostPaint(object sender, ChartPaintEventArgs e) {
236      var chartArea = e.ChartElement as ChartArea;
237      if (chartArea != null) {
238        ChartGraphics chartGraphics = e.ChartGraphics;
239        using (Pen p = new Pen(Color.DarkGray)) {
240          double xmin = chartArea.AxisX.ScaleView.ViewMinimum;
241          double xmax = chartArea.AxisX.ScaleView.ViewMaximum;
242          double ymin = chartArea.AxisY.ScaleView.ViewMinimum;
243          double ymax = chartArea.AxisY.ScaleView.ViewMaximum;
244
245          if (xmin > ymax || ymin > xmax) return;
246
247          PointF start = PointF.Empty;
248          start.X = (float)chartGraphics.GetPositionFromAxis(chartArea.Name, chartArea.AxisX.AxisName, Math.Max(xmin, ymin));
249          start.Y = (float)chartGraphics.GetPositionFromAxis(chartArea.Name, chartArea.AxisY.AxisName, Math.Max(xmin, ymin));
250          PointF end = PointF.Empty;
251          end.X = (float)chartGraphics.GetPositionFromAxis(chartArea.Name, chartArea.AxisX.AxisName, Math.Min(xmax, ymax));
252          end.Y = (float)chartGraphics.GetPositionFromAxis(chartArea.Name, chartArea.AxisY.AxisName, Math.Min(xmax, ymax));
253
254          chartGraphics.Graphics.DrawLine(p, chartGraphics.GetAbsolutePoint(start), chartGraphics.GetAbsolutePoint(end));
255        }
256      }
257    }
258  }
259}
Note: See TracBrowser for help on using the repository browser.