Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/HeuristicLab.Analysis.Views/3.3/ScatterPlotView.cs @ 17277

Last change on this file since 17277 was 17180, checked in by swagner, 5 years ago

#2875: Removed years in copyrights

File size: 36.8 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 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
21
22using System;
23using System.Collections.Generic;
24using System.Drawing;
25using System.Linq;
26using System.Text;
27using System.Windows.Forms;
28using System.Windows.Forms.DataVisualization.Charting;
29using HeuristicLab.Collections;
30using HeuristicLab.Common;
31using HeuristicLab.Core.Views;
32using HeuristicLab.MainForm;
33
34namespace HeuristicLab.Analysis.Views {
35  [View("ScatterPlot View")]
36  [Content(typeof(ScatterPlot), true)]
37  public partial class ScatterPlotView : NamedItemView, IConfigureableView {
38    protected List<Series> invisibleSeries;
39    protected Dictionary<IObservableList<Point2D<double>>, ScatterPlotDataRow> pointsRowsTable;
40    protected Dictionary<Series, Series> seriesToRegressionSeriesTable;
41    private double xMin, xMax, yMin, yMax;
42    protected bool showChartOnly = false;
43
44    public new ScatterPlot Content {
45      get { return (ScatterPlot)base.Content; }
46      set { base.Content = value; }
47    }
48
49    public bool ShowChartOnly {
50      get { return showChartOnly; }
51      set {
52        if (showChartOnly != value) {
53          showChartOnly = value;
54          UpdateControlsVisibility();
55        }
56      }
57    }
58
59    public ScatterPlotView() {
60      InitializeComponent();
61      pointsRowsTable = new Dictionary<IObservableList<Point2D<double>>, ScatterPlotDataRow>();
62      seriesToRegressionSeriesTable = new Dictionary<Series, Series>();
63      invisibleSeries = new List<Series>();
64      chart.CustomizeAllChartAreas();
65      chart.ChartAreas[0].CursorX.Interval = 1;
66      chart.ContextMenuStrip.Items.Add(configureToolStripMenuItem);
67    }
68
69    #region Event Handler Registration
70    protected override void DeregisterContentEvents() {
71      foreach (ScatterPlotDataRow row in Content.Rows)
72        DeregisterScatterPlotDataRowEvents(row);
73      Content.VisualPropertiesChanged -= new EventHandler(Content_VisualPropertiesChanged);
74      Content.Rows.ItemsAdded -= new CollectionItemsChangedEventHandler<ScatterPlotDataRow>(Rows_ItemsAdded);
75      Content.Rows.ItemsRemoved -= new CollectionItemsChangedEventHandler<ScatterPlotDataRow>(Rows_ItemsRemoved);
76      Content.Rows.ItemsReplaced -= new CollectionItemsChangedEventHandler<ScatterPlotDataRow>(Rows_ItemsReplaced);
77      Content.Rows.CollectionReset -= new CollectionItemsChangedEventHandler<ScatterPlotDataRow>(Rows_CollectionReset);
78      base.DeregisterContentEvents();
79    }
80    protected override void RegisterContentEvents() {
81      base.RegisterContentEvents();
82      Content.VisualPropertiesChanged += new EventHandler(Content_VisualPropertiesChanged);
83      Content.Rows.ItemsAdded += new CollectionItemsChangedEventHandler<ScatterPlotDataRow>(Rows_ItemsAdded);
84      Content.Rows.ItemsRemoved += new CollectionItemsChangedEventHandler<ScatterPlotDataRow>(Rows_ItemsRemoved);
85      Content.Rows.ItemsReplaced += new CollectionItemsChangedEventHandler<ScatterPlotDataRow>(Rows_ItemsReplaced);
86      Content.Rows.CollectionReset += new CollectionItemsChangedEventHandler<ScatterPlotDataRow>(Rows_CollectionReset);
87    }
88
89    protected virtual void RegisterScatterPlotDataRowEvents(ScatterPlotDataRow row) {
90      row.NameChanged += new EventHandler(Row_NameChanged);
91      row.VisualPropertiesChanged += new EventHandler(Row_VisualPropertiesChanged);
92      pointsRowsTable.Add(row.Points, row);
93      row.Points.ItemsAdded += new CollectionItemsChangedEventHandler<IndexedItem<Point2D<double>>>(Points_ItemsAdded);
94      row.Points.ItemsRemoved += new CollectionItemsChangedEventHandler<IndexedItem<Point2D<double>>>(Points_ItemsRemoved);
95      row.Points.ItemsReplaced += new CollectionItemsChangedEventHandler<IndexedItem<Point2D<double>>>(Points_ItemsReplaced);
96      row.Points.CollectionReset += new CollectionItemsChangedEventHandler<IndexedItem<Point2D<double>>>(Points_CollectionReset);
97    }
98    protected virtual void DeregisterScatterPlotDataRowEvents(ScatterPlotDataRow row) {
99      row.Points.ItemsAdded -= new CollectionItemsChangedEventHandler<IndexedItem<Point2D<double>>>(Points_ItemsAdded);
100      row.Points.ItemsRemoved -= new CollectionItemsChangedEventHandler<IndexedItem<Point2D<double>>>(Points_ItemsRemoved);
101      row.Points.ItemsReplaced -= new CollectionItemsChangedEventHandler<IndexedItem<Point2D<double>>>(Points_ItemsReplaced);
102      row.Points.CollectionReset -= new CollectionItemsChangedEventHandler<IndexedItem<Point2D<double>>>(Points_CollectionReset);
103      pointsRowsTable.Remove(row.Points);
104      row.VisualPropertiesChanged -= new EventHandler(Row_VisualPropertiesChanged);
105      row.NameChanged -= new EventHandler(Row_NameChanged);
106    }
107    #endregion
108
109    protected override void OnContentChanged() {
110      base.OnContentChanged();
111      invisibleSeries.Clear();
112      chart.Titles[0].Text = string.Empty;
113      chart.ChartAreas[0].AxisX.Title = string.Empty;
114      chart.ChartAreas[0].AxisY.Title = string.Empty;
115      chart.Series.Clear();
116      if (Content != null) {
117        chart.Titles[0].Text = Content.Name;
118        chart.Titles[0].Visible = !string.IsNullOrEmpty(Content.Name);
119        AddScatterPlotDataRows(Content.Rows);
120        ConfigureChartArea(chart.ChartAreas[0]);
121        RecalculateMinMaxPointValues();
122        RecalculateAxesScale(chart.ChartAreas[0]);
123      }
124    }
125
126    protected override void SetEnabledStateOfControls() {
127      base.SetEnabledStateOfControls();
128      chart.Enabled = Content != null;
129    }
130
131    public void ShowConfiguration() {
132      if (Content != null) {
133        using (ScatterPlotVisualPropertiesDialog dialog = new ScatterPlotVisualPropertiesDialog(Content)) {
134          dialog.ShowDialog(this);
135        }
136      } else MessageBox.Show("Nothing to configure.");
137    }
138
139    protected void UpdateControlsVisibility() {
140      if (InvokeRequired)
141        Invoke(new Action(UpdateControlsVisibility));
142      else {
143        foreach (Control c in Controls) {
144          if (c == chart) continue;
145          c.Visible = !showChartOnly;
146        }
147        chart.Dock = showChartOnly ? DockStyle.Fill : DockStyle.None;
148      }
149    }
150
151    protected virtual void AddScatterPlotDataRows(IEnumerable<ScatterPlotDataRow> rows) {
152      foreach (var row in rows) {
153        RegisterScatterPlotDataRowEvents(row);
154        Series series = new Series(row.Name) { Tag = row };
155
156        if (row.VisualProperties.DisplayName.Trim() != String.Empty) series.LegendText = row.VisualProperties.DisplayName;
157        else series.LegendText = row.Name;
158
159        var regressionSeries = new Series(row.Name + "_Regression") {
160          Tag = row,
161          ChartType = SeriesChartType.Line,
162          BorderDashStyle = ChartDashStyle.Dot,
163          IsVisibleInLegend = false,
164          Color = Color.Transparent // to avoid auto color assignment via color palette
165        };
166
167        seriesToRegressionSeriesTable.Add(series, regressionSeries);
168        ConfigureSeries(series, regressionSeries, row);
169        FillSeriesWithRowValues(series, row);
170
171        chart.Series.Add(series);
172        chart.Series.Add(regressionSeries);
173        FillRegressionSeries(regressionSeries, row);
174      }
175      ConfigureChartArea(chart.ChartAreas[0]);
176      RecalculateMinMaxPointValues();
177      RecalculateAxesScale(chart.ChartAreas[0]);
178      UpdateYCursorInterval();
179      UpdateRegressionSeriesColors();
180    }
181
182    protected virtual void RemoveScatterPlotDataRows(IEnumerable<ScatterPlotDataRow> rows) {
183      foreach (var row in rows) {
184        DeregisterScatterPlotDataRowEvents(row);
185        Series series = chart.Series[row.Name];
186        chart.Series.Remove(series);
187        if (invisibleSeries.Contains(series))
188          invisibleSeries.Remove(series);
189        chart.Series.Remove(seriesToRegressionSeriesTable[series]);
190        seriesToRegressionSeriesTable.Remove(series);
191      }
192      RecalculateMinMaxPointValues();
193      RecalculateAxesScale(chart.ChartAreas[0]);
194    }
195
196    private void ConfigureSeries(Series series, Series regressionSeries, ScatterPlotDataRow row) {
197      series.BorderWidth = 1;
198      series.BorderDashStyle = ChartDashStyle.Solid;
199      series.BorderColor = Color.Empty;
200
201      if (row.VisualProperties.Color != Color.Empty)
202        series.Color = row.VisualProperties.Color;
203      else series.Color = Color.Empty;
204      series.IsVisibleInLegend = row.VisualProperties.IsVisibleInLegend;
205      series.ChartType = SeriesChartType.FastPoint;
206      series.MarkerSize = row.VisualProperties.PointSize;
207      series.MarkerStyle = ConvertPointStyle(row.VisualProperties.PointStyle);
208      series.XAxisType = AxisType.Primary;
209      series.YAxisType = AxisType.Primary;
210
211      if (row.VisualProperties.DisplayName.Trim() != String.Empty) series.LegendText = row.VisualProperties.DisplayName;
212      else series.LegendText = row.Name;
213
214      string xAxisTitle = string.IsNullOrEmpty(Content.VisualProperties.XAxisTitle)
215                      ? "X"
216                      : Content.VisualProperties.XAxisTitle;
217      string yAxisTitle = string.IsNullOrEmpty(Content.VisualProperties.YAxisTitle)
218                            ? "Y"
219                            : Content.VisualProperties.YAxisTitle;
220      series.ToolTip =
221        series.LegendText + Environment.NewLine +
222        xAxisTitle + " = " + "#VALX," + Environment.NewLine +
223        yAxisTitle + " = " + "#VAL";
224
225      regressionSeries.BorderWidth = Math.Max(1, row.VisualProperties.PointSize / 2);
226      regressionSeries.IsVisibleInLegend = row.VisualProperties.IsRegressionVisibleInLegend &&
227        row.VisualProperties.RegressionType != ScatterPlotDataRowVisualProperties.ScatterPlotDataRowRegressionType.None;
228      regressionSeries.LegendText = string.IsNullOrEmpty(row.VisualProperties.RegressionDisplayName)
229        ? string.Format("{0}({1})", row.VisualProperties.RegressionType, row.Name)
230        : row.VisualProperties.RegressionDisplayName;
231    }
232
233    private void ConfigureChartArea(ChartArea area) {
234      if (Content.VisualProperties.TitleFont != null) chart.Titles[0].Font = Content.VisualProperties.TitleFont;
235      if (!Content.VisualProperties.TitleColor.IsEmpty) chart.Titles[0].ForeColor = Content.VisualProperties.TitleColor;
236      chart.Titles[0].Text = Content.VisualProperties.Title;
237      chart.Titles[0].Visible = !string.IsNullOrEmpty(Content.VisualProperties.Title);
238
239      if (Content.VisualProperties.AxisTitleFont != null) area.AxisX.TitleFont = Content.VisualProperties.AxisTitleFont;
240      if (!Content.VisualProperties.AxisTitleColor.IsEmpty) area.AxisX.TitleForeColor = Content.VisualProperties.AxisTitleColor;
241      area.AxisX.Title = Content.VisualProperties.XAxisTitle;
242      area.AxisX.MajorGrid.Enabled = Content.VisualProperties.XAxisGrid;
243
244      if (Content.VisualProperties.AxisTitleFont != null) area.AxisY.TitleFont = Content.VisualProperties.AxisTitleFont;
245      if (!Content.VisualProperties.AxisTitleColor.IsEmpty) area.AxisY.TitleForeColor = Content.VisualProperties.AxisTitleColor;
246      area.AxisY.Title = Content.VisualProperties.YAxisTitle;
247      area.AxisY.MajorGrid.Enabled = Content.VisualProperties.YAxisGrid;
248    }
249
250    private void RecalculateAxesScale(ChartArea area) {
251      area.AxisX.Minimum = CalculateMinBound(xMin);
252      area.AxisX.Maximum = CalculateMaxBound(xMax);
253      if (area.AxisX.Minimum == area.AxisX.Maximum) {
254        area.AxisX.Minimum = xMin - 0.5;
255        area.AxisX.Maximum = xMax + 0.5;
256      }
257      area.AxisY.Minimum = CalculateMinBound(yMin);
258      area.AxisY.Maximum = CalculateMaxBound(yMax);
259      if (area.AxisY.Minimum == area.AxisY.Maximum) {
260        area.AxisY.Minimum = yMin - 0.5;
261        area.AxisY.Maximum = yMax + 0.5;
262      }
263      if (xMax - xMin > 0) area.CursorX.Interval = Math.Pow(10, Math.Floor(Math.Log10(area.AxisX.Maximum - area.AxisX.Minimum) - 3));
264      else area.CursorX.Interval = 1;
265      area.AxisX.IsMarginVisible = false;
266
267      if (!Content.VisualProperties.XAxisMinimumAuto && !double.IsNaN(Content.VisualProperties.XAxisMinimumFixedValue)) area.AxisX.Minimum = Content.VisualProperties.XAxisMinimumFixedValue;
268      if (!Content.VisualProperties.XAxisMaximumAuto && !double.IsNaN(Content.VisualProperties.XAxisMaximumFixedValue)) area.AxisX.Maximum = Content.VisualProperties.XAxisMaximumFixedValue;
269      if (!Content.VisualProperties.YAxisMinimumAuto && !double.IsNaN(Content.VisualProperties.YAxisMinimumFixedValue)) area.AxisY.Minimum = Content.VisualProperties.YAxisMinimumFixedValue;
270      if (!Content.VisualProperties.YAxisMaximumAuto && !double.IsNaN(Content.VisualProperties.YAxisMaximumFixedValue)) area.AxisY.Maximum = Content.VisualProperties.YAxisMaximumFixedValue;
271    }
272
273    private static double CalculateMinBound(double min) {
274      if (min == 0) return 0;
275      var scale = Math.Pow(10, Math.Floor(Math.Log10(Math.Abs(min))));
276      return scale * (Math.Floor(min / scale));
277    }
278
279    private static double CalculateMaxBound(double max) {
280      if (max == 0) return 0;
281      var scale = Math.Pow(10, Math.Floor(Math.Log10(Math.Abs(max))));
282      return scale * (Math.Ceiling(max / scale));
283    }
284
285    protected virtual void UpdateYCursorInterval() {
286      double interestingValuesRange = (
287        from series in chart.Series
288        where series.Enabled
289        let values = (from point in series.Points
290                      where !point.IsEmpty
291                      select point.YValues[0]).DefaultIfEmpty(1.0)
292        let range = values.Max() - values.Min()
293        where range > 0.0
294        select range
295        ).DefaultIfEmpty(1.0).Min();
296
297      double digits = (int)Math.Log10(interestingValuesRange) - 3;
298      double yZoomInterval = Math.Pow(10, digits);
299      this.chart.ChartAreas[0].CursorY.Interval = yZoomInterval;
300    }
301
302    protected void UpdateRegressionSeriesColors() {
303      chart.ApplyPaletteColors();
304      foreach (var row in Content.Rows) {
305        var series = chart.Series[row.Name];
306        var regressionSeries = seriesToRegressionSeriesTable[series];
307        regressionSeries.Color = series.Color;
308      }
309    }
310
311    #region Event Handlers
312    #region Content Event Handlers
313    protected override void Content_NameChanged(object sender, EventArgs e) {
314      if (InvokeRequired)
315        Invoke(new EventHandler(Content_NameChanged), sender, e);
316      else {
317        Content.VisualProperties.Title = Content.Name;
318        base.Content_NameChanged(sender, e);
319      }
320    }
321    private void Content_VisualPropertiesChanged(object sender, EventArgs e) {
322      if (InvokeRequired)
323        Invoke(new EventHandler(Content_VisualPropertiesChanged), sender, e);
324      else {
325        ConfigureChartArea(chart.ChartAreas[0]);
326        RecalculateAxesScale(chart.ChartAreas[0]); // axes min/max could have changed
327      }
328    }
329    #endregion
330    #region Rows Event Handlers
331    private void Rows_ItemsAdded(object sender, CollectionItemsChangedEventArgs<ScatterPlotDataRow> e) {
332      if (InvokeRequired)
333        Invoke(new CollectionItemsChangedEventHandler<ScatterPlotDataRow>(Rows_ItemsAdded), sender, e);
334      else {
335        AddScatterPlotDataRows(e.Items);
336      }
337    }
338    private void Rows_ItemsRemoved(object sender, CollectionItemsChangedEventArgs<ScatterPlotDataRow> e) {
339      if (InvokeRequired)
340        Invoke(new CollectionItemsChangedEventHandler<ScatterPlotDataRow>(Rows_ItemsRemoved), sender, e);
341      else {
342        RemoveScatterPlotDataRows(e.Items);
343      }
344    }
345    private void Rows_ItemsReplaced(object sender, CollectionItemsChangedEventArgs<ScatterPlotDataRow> e) {
346      if (InvokeRequired)
347        Invoke(new CollectionItemsChangedEventHandler<ScatterPlotDataRow>(Rows_ItemsReplaced), sender, e);
348      else {
349        RemoveScatterPlotDataRows(e.OldItems);
350        AddScatterPlotDataRows(e.Items);
351      }
352    }
353    private void Rows_CollectionReset(object sender, CollectionItemsChangedEventArgs<ScatterPlotDataRow> e) {
354      if (InvokeRequired)
355        Invoke(new CollectionItemsChangedEventHandler<ScatterPlotDataRow>(Rows_CollectionReset), sender, e);
356      else {
357        RemoveScatterPlotDataRows(e.OldItems);
358        AddScatterPlotDataRows(e.Items);
359      }
360    }
361    #endregion
362    #region Row Event Handlers
363    private void Row_VisualPropertiesChanged(object sender, EventArgs e) {
364      if (InvokeRequired)
365        Invoke(new EventHandler(Row_VisualPropertiesChanged), sender, e);
366      else {
367        ScatterPlotDataRow row = (ScatterPlotDataRow)sender;
368        Series series = chart.Series[row.Name];
369        Series regressionSeries = seriesToRegressionSeriesTable[series];
370        series.Points.Clear();
371        regressionSeries.Points.Clear();
372        ConfigureSeries(series, regressionSeries, row);
373        FillSeriesWithRowValues(series, row);
374        FillRegressionSeries(regressionSeries, row);
375        RecalculateMinMaxPointValues();
376        RecalculateAxesScale(chart.ChartAreas[0]);
377        UpdateRegressionSeriesColors();
378      }
379    }
380    private void Row_NameChanged(object sender, EventArgs e) {
381      if (InvokeRequired)
382        Invoke(new EventHandler(Row_NameChanged), sender, e);
383      else {
384        ScatterPlotDataRow row = (ScatterPlotDataRow)sender;
385        chart.Series[row.Name].Name = row.Name;
386      }
387    }
388    #endregion
389    #region Points Event Handlers
390    private void Points_ItemsAdded(object sender, CollectionItemsChangedEventArgs<IndexedItem<Point2D<double>>> e) {
391      if (InvokeRequired)
392        Invoke(new CollectionItemsChangedEventHandler<IndexedItem<Point2D<double>>>(Points_ItemsAdded), sender, e);
393      else {
394        ScatterPlotDataRow row = null;
395        pointsRowsTable.TryGetValue((IObservableList<Point2D<double>>)sender, out row);
396        if (row != null) {
397          Series rowSeries = chart.Series[row.Name];
398          Series regressionSeries = seriesToRegressionSeriesTable[rowSeries];
399          if (!invisibleSeries.Contains(rowSeries)) {
400            rowSeries.Points.Clear();
401            regressionSeries.Points.Clear();
402            FillSeriesWithRowValues(rowSeries, row);
403            FillRegressionSeries(regressionSeries, row);
404            RecalculateMinMaxPointValues();
405            RecalculateAxesScale(chart.ChartAreas[0]);
406            UpdateYCursorInterval();
407          }
408        }
409      }
410    }
411    private void Points_ItemsRemoved(object sender, CollectionItemsChangedEventArgs<IndexedItem<Point2D<double>>> e) {
412      if (InvokeRequired)
413        Invoke(new CollectionItemsChangedEventHandler<IndexedItem<Point2D<double>>>(Points_ItemsRemoved), sender, e);
414      else {
415        ScatterPlotDataRow row = null;
416        pointsRowsTable.TryGetValue((IObservableList<Point2D<double>>)sender, out row);
417        if (row != null) {
418          Series rowSeries = chart.Series[row.Name];
419          Series regressionSeries = seriesToRegressionSeriesTable[rowSeries];
420          if (!invisibleSeries.Contains(rowSeries)) {
421            rowSeries.Points.Clear();
422            regressionSeries.Points.Clear();
423            FillSeriesWithRowValues(rowSeries, row);
424            FillRegressionSeries(regressionSeries, row);
425            RecalculateMinMaxPointValues();
426            RecalculateAxesScale(chart.ChartAreas[0]);
427            UpdateYCursorInterval();
428          }
429        }
430      }
431    }
432    private void Points_ItemsReplaced(object sender, CollectionItemsChangedEventArgs<IndexedItem<Point2D<double>>> e) {
433      if (InvokeRequired)
434        Invoke(new CollectionItemsChangedEventHandler<IndexedItem<Point2D<double>>>(Points_ItemsReplaced), sender, e);
435      else {
436        ScatterPlotDataRow row = null;
437        pointsRowsTable.TryGetValue((IObservableList<Point2D<double>>)sender, out row);
438        if (row != null) {
439          Series rowSeries = chart.Series[row.Name];
440          Series regressionSeries = seriesToRegressionSeriesTable[rowSeries];
441          if (!invisibleSeries.Contains(rowSeries)) {
442            rowSeries.Points.Clear();
443            regressionSeries.Points.Clear();
444            FillSeriesWithRowValues(rowSeries, row);
445            FillRegressionSeries(regressionSeries, row);
446            RecalculateMinMaxPointValues();
447            RecalculateAxesScale(chart.ChartAreas[0]);
448            UpdateYCursorInterval();
449          }
450        }
451      }
452    }
453    private void Points_CollectionReset(object sender, CollectionItemsChangedEventArgs<IndexedItem<Point2D<double>>> e) {
454      if (InvokeRequired)
455        Invoke(new CollectionItemsChangedEventHandler<IndexedItem<Point2D<double>>>(Points_CollectionReset), sender, e);
456      else {
457        ScatterPlotDataRow row = null;
458        pointsRowsTable.TryGetValue((IObservableList<Point2D<double>>)sender, out row);
459        if (row != null) {
460          Series rowSeries = chart.Series[row.Name];
461          Series regressionSeries = seriesToRegressionSeriesTable[rowSeries];
462          if (!invisibleSeries.Contains(rowSeries)) {
463            rowSeries.Points.Clear();
464            regressionSeries.Points.Clear();
465            FillSeriesWithRowValues(rowSeries, row);
466            FillRegressionSeries(regressionSeries, row);
467            RecalculateMinMaxPointValues();
468            RecalculateAxesScale(chart.ChartAreas[0]);
469            UpdateYCursorInterval();
470          }
471        }
472      }
473    }
474    #endregion
475    private void configureToolStripMenuItem_Click(object sender, System.EventArgs e) {
476      ShowConfiguration();
477    }
478    #endregion
479
480    #region Chart Event Handlers
481    private void chart_MouseDoubleClick(object sender, MouseEventArgs e) {
482      HitTestResult result = chart.HitTest(e.X, e.Y, ChartElementType.DataPoint);
483      if (result.ChartElementType != ChartElementType.DataPoint) return;
484
485      var series = result.Series;
486      var dataPoint = series.Points[result.PointIndex];
487      var tag = dataPoint.Tag;
488      var content = tag as IContent;
489
490      if (tag == null) return;
491      if (content == null) return;
492
493      MainFormManager.MainForm.ShowContent(content);
494    }
495
496    private void chart_MouseDown(object sender, MouseEventArgs e) {
497      HitTestResult result = chart.HitTest(e.X, e.Y);
498      if (result.ChartElementType == ChartElementType.LegendItem) {
499        ToggleSeriesVisible(result.Series);
500      }
501    }
502    private void chart_MouseMove(object sender, MouseEventArgs e) {
503      HitTestResult result = chart.HitTest(e.X, e.Y);
504      if (result.ChartElementType == ChartElementType.LegendItem)
505        this.Cursor = Cursors.Hand;
506      else
507        this.Cursor = Cursors.Default;
508    }
509    private void chart_CustomizeLegend(object sender, CustomizeLegendEventArgs e) {
510      foreach (LegendItem legendItem in e.LegendItems) {
511        var series = chart.Series[legendItem.SeriesName];
512        if (series != null) {
513          bool seriesIsInvisible = invisibleSeries.Contains(series);
514          foreach (LegendCell cell in legendItem.Cells) {
515            cell.ForeColor = seriesIsInvisible ? Color.Gray : Color.Black;
516          }
517        }
518      }
519    }
520    #endregion
521
522    private void ToggleSeriesVisible(Series series) {
523      if (!invisibleSeries.Contains(series)) {
524        series.Points.Clear();
525        invisibleSeries.Add(series);
526        RecalculateMinMaxPointValues();
527      } else {
528        invisibleSeries.Remove(series);
529        if (Content != null) {
530          var row = (ScatterPlotDataRow)series.Tag;
531          if (seriesToRegressionSeriesTable.ContainsKey(series))
532            FillSeriesWithRowValues(series, row);
533          else
534            FillRegressionSeries(series, row);
535          RecalculateMinMaxPointValues();
536          this.chart.Legends[series.Legend].ForeColor = Color.Black;
537          RecalculateAxesScale(chart.ChartAreas[0]);
538          UpdateYCursorInterval();
539        }
540      }
541    }
542
543    private void RecalculateMinMaxPointValues() {
544      yMin = xMin = double.MaxValue;
545      yMax = xMax = double.MinValue;
546      foreach (var s in chart.Series.Where(x => x.Enabled)) {
547        foreach (var p in s.Points) {
548          double x = p.XValue, y = p.YValues[0];
549          if (xMin > x) xMin = x;
550          if (xMax < x) xMax = x;
551          if (yMin > y) yMin = y;
552          if (yMax < y) yMax = y;
553        }
554      }
555    }
556
557    private void FillSeriesWithRowValues(Series series, ScatterPlotDataRow row) {
558      bool zerosOnly = true;
559      for (int i = 0; i < row.Points.Count; i++) {
560        var value = row.Points[i];
561        DataPoint point = new DataPoint();
562        if (IsInvalidValue(value.X) || IsInvalidValue(value.Y))
563          point.IsEmpty = true;
564        else {
565          point.XValue = value.X;
566          point.YValues = new double[] { value.Y };
567        }
568        point.Tag = value.Tag;
569        series.Points.Add(point);
570        if (value.X != 0.0f)
571          zerosOnly = false;
572      }
573      if (zerosOnly) // if all x-values are zero, the x-values are interpreted as 1, 2, 3, ...
574        series.Points.Add(new DataPoint(1, 1) { IsEmpty = true });
575      double correlation = Correlation(row.Points);
576      series.LegendToolTip = string.Format("Correlation (R²) = {0:G4}", correlation * correlation);
577    }
578
579    private void FillRegressionSeries(Series regressionSeries, ScatterPlotDataRow row) {
580      if (row.VisualProperties.RegressionType == ScatterPlotDataRowVisualProperties.ScatterPlotDataRowRegressionType.None
581        || invisibleSeries.Contains(regressionSeries))
582        return;
583
584      double[] coefficients;
585      if (!Fitting(row, out coefficients)) {
586        regressionSeries.LegendToolTip = "Could not calculate regression.";
587        return;
588      }
589
590      // Fill regrssion series
591      double min = row.Points.Min(p => p.X), max = row.Points.Max(p => p.X);
592      double range = max - min, delta = range / Math.Max(row.Points.Count - 1, 50);
593      if (range > double.Epsilon) {
594        for (double x = min; x <= max; x += delta) {
595          regressionSeries.Points.AddXY(x, Estimate(x, row, coefficients));
596        }
597      }
598
599      // Correlation
600      var data = row.Points.Select(p => new Point2D<double>(p.Y, Estimate(p.X, row, coefficients)));
601      double correlation = Correlation(data.ToList());
602      regressionSeries.LegendToolTip = GetStringFormula(row, coefficients) + Environment.NewLine +
603                                       string.Format("Correlation (R²) = {0:G4}", correlation * correlation);
604      regressionSeries.ToolTip = GetStringFormula(row, coefficients);
605    }
606
607    #region Helpers
608    private MarkerStyle ConvertPointStyle(ScatterPlotDataRowVisualProperties.ScatterPlotDataRowPointStyle pointStyle) {
609      switch (pointStyle) {
610        case ScatterPlotDataRowVisualProperties.ScatterPlotDataRowPointStyle.Circle:
611          return MarkerStyle.Circle;
612        case ScatterPlotDataRowVisualProperties.ScatterPlotDataRowPointStyle.Cross:
613          return MarkerStyle.Cross;
614        case ScatterPlotDataRowVisualProperties.ScatterPlotDataRowPointStyle.Diamond:
615          return MarkerStyle.Diamond;
616        case ScatterPlotDataRowVisualProperties.ScatterPlotDataRowPointStyle.Square:
617          return MarkerStyle.Square;
618        case ScatterPlotDataRowVisualProperties.ScatterPlotDataRowPointStyle.Star4:
619          return MarkerStyle.Star4;
620        case ScatterPlotDataRowVisualProperties.ScatterPlotDataRowPointStyle.Star5:
621          return MarkerStyle.Star5;
622        case ScatterPlotDataRowVisualProperties.ScatterPlotDataRowPointStyle.Star6:
623          return MarkerStyle.Star6;
624        case ScatterPlotDataRowVisualProperties.ScatterPlotDataRowPointStyle.Star10:
625          return MarkerStyle.Star10;
626        case ScatterPlotDataRowVisualProperties.ScatterPlotDataRowPointStyle.Triangle:
627          return MarkerStyle.Triangle;
628        default:
629          return MarkerStyle.None;
630      }
631    }
632
633    protected static bool IsInvalidValue(double x) {
634      return double.IsNaN(x) || x < (double)decimal.MinValue || x > (double)decimal.MaxValue;
635    }
636    #endregion
637
638    #region Correlation and Fitting Helper
639    protected static double Correlation(IList<Point2D<double>> values) {
640      // sums of x, y, x squared etc.
641      double sx = 0.0;
642      double sy = 0.0;
643      double sxx = 0.0;
644      double syy = 0.0;
645      double sxy = 0.0;
646
647      int n = 0;
648      for (int i = 0; i < values.Count; i++) {
649        double x = values[i].X;
650        double y = values[i].Y;
651        if (IsInvalidValue(x) || IsInvalidValue(y))
652          continue;
653
654        sx += x;
655        sy += y;
656        sxx += x * x;
657        syy += y * y;
658        sxy += x * y;
659        n++;
660      }
661
662      // covariation
663      double cov = sxy / n - sx * sy / n / n;
664      // standard error of x
665      double sigmaX = Math.Sqrt(sxx / n - sx * sx / n / n);
666      // standard error of y
667      double sigmaY = Math.Sqrt(syy / n - sy * sy / n / n);
668
669      // correlation
670      return cov / sigmaX / sigmaY;
671    }
672
673    protected static bool Fitting(ScatterPlotDataRow row, out double[] coefficients) {
674      if (!IsValidRegressionData(row)) {
675        coefficients = new double[0];
676        return false;
677      }
678
679      var xs = row.Points.Select(p => p.X).ToList();
680      var ys = row.Points.Select(p => p.Y).ToList();
681
682      // Input transformations
683      double[,] matrix;
684      int nRows;
685      switch (row.VisualProperties.RegressionType) {
686        case ScatterPlotDataRowVisualProperties.ScatterPlotDataRowRegressionType.Linear:
687          matrix = CreateMatrix(out nRows, ys, xs);
688          break;
689        case ScatterPlotDataRowVisualProperties.ScatterPlotDataRowRegressionType.Polynomial:
690          var xss = Enumerable.Range(1, row.VisualProperties.PolynomialRegressionOrder)
691            .Select(o => xs.Select(x => Math.Pow(x, o)).ToList())
692            .Reverse(); // higher order first
693          matrix = CreateMatrix(out nRows, ys, xss.ToArray());
694          break;
695        case ScatterPlotDataRowVisualProperties.ScatterPlotDataRowRegressionType.Exponential:
696          matrix = CreateMatrix(out nRows, ys.Select(y => Math.Log(y)).ToList(), xs);
697          break;
698        case ScatterPlotDataRowVisualProperties.ScatterPlotDataRowRegressionType.Power:
699          matrix = CreateMatrix(out nRows, ys.Select(y => Math.Log(y)).ToList(), xs.Select(x => Math.Log(x)).ToList());
700          break;
701        case ScatterPlotDataRowVisualProperties.ScatterPlotDataRowRegressionType.Logarithmic:
702          matrix = CreateMatrix(out nRows, ys, xs.Select(x => Math.Log(x)).ToList());
703          break;
704        default:
705          throw new ArgumentException("Unknown RegressionType: " + row.VisualProperties.RegressionType);
706      }
707
708      // Linear fitting
709      bool success = LinearFitting(matrix, nRows, out coefficients);
710      if (!success) return false;
711
712      // Output transformation
713      switch (row.VisualProperties.RegressionType) {
714        case ScatterPlotDataRowVisualProperties.ScatterPlotDataRowRegressionType.Exponential:
715        case ScatterPlotDataRowVisualProperties.ScatterPlotDataRowRegressionType.Power:
716          coefficients[1] = Math.Exp(coefficients[1]);
717          break;
718      }
719
720      return true;
721    }
722    protected static bool IsValidRegressionData(ScatterPlotDataRow row) {
723      // No invalid values allowed
724      for (int i = 0; i < row.Points.Count; i++) {
725        if (IsInvalidValue(row.Points[i].X) || IsInvalidValue(row.Points[i].Y))
726          return false;
727      }
728      // Exp, Power and Log Regression do not work with negative values
729      switch (row.VisualProperties.RegressionType) {
730        case ScatterPlotDataRowVisualProperties.ScatterPlotDataRowRegressionType.Exponential:
731          for (int i = 0; i < row.Points.Count; i++) {
732            if (row.Points[i].Y <= 0)
733              return false;
734          }
735          break;
736        case ScatterPlotDataRowVisualProperties.ScatterPlotDataRowRegressionType.Power:
737          for (int i = 0; i < row.Points.Count; i++) {
738            if (row.Points[i].X <= 0 || row.Points[i].Y <= 0)
739              return false;
740          }
741          break;
742        case ScatterPlotDataRowVisualProperties.ScatterPlotDataRowRegressionType.Logarithmic:
743          for (int i = 0; i < row.Points.Count; i++) {
744            if (row.Points[i].X <= 0)
745              return false;
746          }
747          break;
748      }
749      return true;
750    }
751    protected static double[,] CreateMatrix(out int nRows, IList<double> ys, params IList<double>[] xss) {
752      var matrix = new double[ys.Count, xss.Length + 1];
753      int rowIdx = 0;
754      for (int i = 0; i < ys.Count; i++) {
755        if (IsInvalidValue(ys[i]) || xss.Any(xs => IsInvalidValue(xs[i])))
756          continue;
757        for (int j = 0; j < xss.Length; j++) {
758          matrix[rowIdx, j] = xss[j][i];
759        }
760        matrix[rowIdx, xss.Length] = ys[i];
761        rowIdx++;
762      }
763      nRows = rowIdx;
764      return matrix;
765    }
766
767    protected static bool LinearFitting(double[,] xsy, int nRows, out double[] coefficients) {
768      int nFeatures = xsy.GetLength(1) - 1;
769
770      alglib.linearmodel lm;
771      alglib.lrreport ar;
772      int retVal;
773      alglib.lrbuild(xsy, nRows, nFeatures, out retVal, out lm, out ar);
774      if (retVal != 1) {
775        coefficients = new double[0];
776        return false;
777      }
778
779      alglib.lrunpack(lm, out coefficients, out nFeatures);
780      return true;
781    }
782
783    protected static double Estimate(double x, ScatterPlotDataRow row, double[] coefficients) {
784      switch (row.VisualProperties.RegressionType) {
785        case ScatterPlotDataRowVisualProperties.ScatterPlotDataRowRegressionType.Linear:
786          return coefficients[0] * x + coefficients[1];
787        case ScatterPlotDataRowVisualProperties.ScatterPlotDataRowRegressionType.Polynomial:
788          return coefficients
789            .Reverse() // to match index and order
790            .Select((c, o) => c * Math.Pow(x, o))
791            .Sum();
792        case ScatterPlotDataRowVisualProperties.ScatterPlotDataRowRegressionType.Exponential:
793          return coefficients[1] * Math.Exp(coefficients[0] * x);
794        case ScatterPlotDataRowVisualProperties.ScatterPlotDataRowRegressionType.Power:
795          return coefficients[1] * Math.Pow(x, coefficients[0]);
796        case ScatterPlotDataRowVisualProperties.ScatterPlotDataRowRegressionType.Logarithmic:
797          return coefficients[0] * Math.Log(x) + coefficients[1];
798        default:
799          throw new ArgumentException("Unknown RegressionType: " + row.VisualProperties.RegressionType);
800      }
801    }
802
803    protected static string GetStringFormula(ScatterPlotDataRow row, double[] coefficients) {
804      switch (row.VisualProperties.RegressionType) {
805        case ScatterPlotDataRowVisualProperties.ScatterPlotDataRowRegressionType.Linear:
806          return string.Format("{0:G4} x {1} {2:G4}", coefficients[0], Sign(coefficients[1]), Math.Abs(coefficients[1]));
807        case ScatterPlotDataRowVisualProperties.ScatterPlotDataRowRegressionType.Polynomial:
808          var sb = new StringBuilder();
809          sb.AppendFormat("{0:G4}{1}", coefficients[0], PolyFactor(coefficients.Length - 1));
810          foreach (var x in coefficients
811            .Reverse() // match index and order
812            .Select((c, o) => new { c, o })
813            .Reverse() // higher order first
814            .Skip(1)) // highest order poly already added
815            sb.AppendFormat(" {0} {1:G4}{2}", Sign(x.c), Math.Abs(x.c), PolyFactor(x.o));
816          return sb.ToString();
817        case ScatterPlotDataRowVisualProperties.ScatterPlotDataRowRegressionType.Exponential:
818          return string.Format("{0:G4} e^({1:G4} x)", coefficients[1], coefficients[0]);
819        case ScatterPlotDataRowVisualProperties.ScatterPlotDataRowRegressionType.Power:
820          return string.Format("{0:G4} x^({1:G4})", coefficients[1], coefficients[0]);
821        case ScatterPlotDataRowVisualProperties.ScatterPlotDataRowRegressionType.Logarithmic:
822          return string.Format("{0:G4} ln(x) {1} {2:G4}", coefficients[0], Sign(coefficients[1]), Math.Abs(coefficients[1]));
823        default:
824          throw new ArgumentException("Unknown RegressionType: " + row.VisualProperties.RegressionType);
825      }
826    }
827    private static string Sign(double value) {
828      return value >= 0 ? "+" : "-";
829    }
830    private static string PolyFactor(int order) {
831      if (order == 0) return "";
832      if (order == 1) return " x";
833      if (order == 2) return " x²";
834      if (order == 3) return " x³";
835      return " x^" + order;
836    }
837    #endregion
838  }
839}
Note: See TracBrowser for help on using the repository browser.