Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Analysis.Views/3.3/ScatterPlotControl.cs @ 14516

Last change on this file since 14516 was 14516, checked in by pfleck, 7 years ago

#2713 Fixed an charting issue that wrongly interprets scatterplot data if all x-values are zero.

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