Free cookie consent management tool by TermsFeed Policy Generator

source: branches/symbreg-factors-2650/HeuristicLab.Analysis.Views/3.3/ScatterPlotControl.cs @ 14498

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

#2650: merged r14457:14494 from trunk to branch (resolving conflicts)

File size: 33.7 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      for (int i = 0; i < row.Points.Count; i++) {
511        var value = row.Points[i];
512        DataPoint point = new DataPoint();
513        if (IsInvalidValue(value.X) || IsInvalidValue(value.Y))
514          point.IsEmpty = true;
515        else {
516          point.XValue = value.X;
517          point.YValues = new double[] { value.Y };
518        }
519        series.Points.Add(point);
520      }
521      double correlation = Correlation(row.Points);
522      series.LegendToolTip = string.Format("Correlation (R²) = {0:G4}", correlation * correlation);
523    }
524
525    private void FillRegressionSeries(Series regressionSeries, ScatterPlotDataRow row) {
526      if (row.VisualProperties.RegressionType == ScatterPlotDataRowVisualProperties.ScatterPlotDataRowRegressionType.None
527        || invisibleSeries.Contains(regressionSeries))
528        return;
529
530      double[] coefficients;
531      if (!Fitting(row, out coefficients))
532        return;
533
534      // Fill regrssion series
535      var validPoints = row.Points.Where(p => !IsInvalidValue(p.X));
536      double min = validPoints.Min(p => p.X), max = validPoints.Max(p => p.X);
537      double range = max - min, delta = range / row.Points.Count;
538      for (double x = min; x < max; x += delta) {
539        regressionSeries.Points.AddXY(x, Estimate(x, row, coefficients));
540      }
541
542      // Correlation
543      var data = row.Points.Select(p => new Point2D<double>(p.Y, Estimate(p.X, row, coefficients)));
544      double correlation = Correlation(data.ToList());
545      regressionSeries.LegendToolTip = GetStringFormula(row, coefficients) + Environment.NewLine +
546                                       string.Format("Correlation (R²) = {0:G4}", correlation * correlation);
547      regressionSeries.ToolTip = GetStringFormula(row, coefficients);
548    }
549
550    #region Helpers
551    private MarkerStyle ConvertPointStyle(ScatterPlotDataRowVisualProperties.ScatterPlotDataRowPointStyle pointStyle) {
552      switch (pointStyle) {
553        case ScatterPlotDataRowVisualProperties.ScatterPlotDataRowPointStyle.Circle:
554          return MarkerStyle.Circle;
555        case ScatterPlotDataRowVisualProperties.ScatterPlotDataRowPointStyle.Cross:
556          return MarkerStyle.Cross;
557        case ScatterPlotDataRowVisualProperties.ScatterPlotDataRowPointStyle.Diamond:
558          return MarkerStyle.Diamond;
559        case ScatterPlotDataRowVisualProperties.ScatterPlotDataRowPointStyle.Square:
560          return MarkerStyle.Square;
561        case ScatterPlotDataRowVisualProperties.ScatterPlotDataRowPointStyle.Star4:
562          return MarkerStyle.Star4;
563        case ScatterPlotDataRowVisualProperties.ScatterPlotDataRowPointStyle.Star5:
564          return MarkerStyle.Star5;
565        case ScatterPlotDataRowVisualProperties.ScatterPlotDataRowPointStyle.Star6:
566          return MarkerStyle.Star6;
567        case ScatterPlotDataRowVisualProperties.ScatterPlotDataRowPointStyle.Star10:
568          return MarkerStyle.Star10;
569        case ScatterPlotDataRowVisualProperties.ScatterPlotDataRowPointStyle.Triangle:
570          return MarkerStyle.Triangle;
571        default:
572          return MarkerStyle.None;
573      }
574    }
575
576    protected static bool IsInvalidValue(double x) {
577      return double.IsNaN(x) || x < (double)decimal.MinValue || x > (double)decimal.MaxValue;
578    }
579    #endregion
580
581    #region Correlation and Fitting Helper
582    protected static double Correlation(IList<Point2D<double>> values) {
583      // sums of x, y, x squared etc.
584      double sx = 0.0;
585      double sy = 0.0;
586      double sxx = 0.0;
587      double syy = 0.0;
588      double sxy = 0.0;
589
590      int n = 0;
591      for (int i = 0; i < values.Count; i++) {
592        double x = values[i].X;
593        double y = values[i].Y;
594        if (IsInvalidValue(x) || IsInvalidValue(y))
595          continue;
596
597        sx += x;
598        sy += y;
599        sxx += x * x;
600        syy += y * y;
601        sxy += x * y;
602        n++;
603      }
604
605      // covariation
606      double cov = sxy / n - sx * sy / n / n;
607      // standard error of x
608      double sigmaX = Math.Sqrt(sxx / n -  sx * sx / n / n);
609      // standard error of y
610      double sigmaY = Math.Sqrt(syy / n -  sy * sy / n / n);
611
612      // correlation
613      return cov / sigmaX / sigmaY;
614    }
615
616    protected static bool Fitting(ScatterPlotDataRow row, out double[] coefficients) {
617      var xs = row.Points.Select(p => p.X).ToList();
618      var ys = row.Points.Select(p => p.Y).ToList();
619
620      // Input transformations
621      double[,] matrix;
622      int nRows;
623      switch (row.VisualProperties.RegressionType) {
624        case ScatterPlotDataRowVisualProperties.ScatterPlotDataRowRegressionType.Linear:
625          matrix = CreateMatrix(out nRows, ys, xs);
626          break;
627        case ScatterPlotDataRowVisualProperties.ScatterPlotDataRowRegressionType.Polynomial:
628          var xss = Enumerable.Range(1, row.VisualProperties.PolynomialRegressionOrder)
629            .Select(o => xs.Select(x => Math.Pow(x, o)).ToList())
630            .Reverse(); // higher order first
631          matrix = CreateMatrix(out nRows, ys, xss.ToArray());
632          break;
633        case ScatterPlotDataRowVisualProperties.ScatterPlotDataRowRegressionType.Exponential:
634          matrix = CreateMatrix(out nRows, ys.Select(y => Math.Log(y)).ToList(), xs);
635          break;
636        case ScatterPlotDataRowVisualProperties.ScatterPlotDataRowRegressionType.Power:
637          matrix = CreateMatrix(out nRows, ys.Select(y => Math.Log(y)).ToList(), xs.Select(x => Math.Log(x)).ToList());
638          break;
639        case ScatterPlotDataRowVisualProperties.ScatterPlotDataRowRegressionType.Logarithmic:
640          matrix = CreateMatrix(out nRows, ys, xs.Select(x => Math.Log(x)).ToList());
641          break;
642        default:
643          throw new ArgumentException("Unknown RegressionType: " + row.VisualProperties.RegressionType);
644      }
645
646      // Linear fitting
647      bool success = LinearFitting(matrix, nRows, out coefficients);
648      if (!success) return success;
649
650      // Output transformation
651      switch (row.VisualProperties.RegressionType) {
652        case ScatterPlotDataRowVisualProperties.ScatterPlotDataRowRegressionType.Exponential:
653        case ScatterPlotDataRowVisualProperties.ScatterPlotDataRowRegressionType.Power:
654          coefficients[1] = Math.Exp(coefficients[1]);
655          break;
656      }
657
658      return true;
659    }
660    protected static double[,] CreateMatrix(out int nRows, IList<double> ys, params IList<double>[] xss) {
661      var matrix = new double[ys.Count, xss.Length + 1];
662      int rowIdx = 0;
663      for (int i = 0; i < ys.Count; i++) {
664        if (IsInvalidValue(ys[i]) || xss.Any(xs => IsInvalidValue(xs[i])))
665          continue;
666        for (int j = 0; j < xss.Length; j++) {
667          matrix[rowIdx, j] = xss[j][i];
668        }
669        matrix[rowIdx, xss.Length] = ys[i];
670        rowIdx++;
671      }
672      nRows = rowIdx;
673      return matrix;
674    }
675
676    protected static bool LinearFitting(double[,] xsy, int nRows, out double[] coefficients) {
677      int nFeatures = xsy.GetLength(1) - 1;
678
679      alglib.linearmodel lm;
680      alglib.lrreport ar;
681      int retVal;
682      alglib.lrbuild(xsy, nRows, nFeatures, out retVal, out lm, out ar);
683      if (retVal != 1) {
684        coefficients = new double[0];
685        return false;
686      }
687
688      alglib.lrunpack(lm, out coefficients, out nFeatures);
689      return true;
690    }
691
692    protected static double Estimate(double x, ScatterPlotDataRow row, double[] coefficients) {
693      switch (row.VisualProperties.RegressionType) {
694        case ScatterPlotDataRowVisualProperties.ScatterPlotDataRowRegressionType.Linear:
695          return coefficients[0] * x + coefficients[1];
696        case ScatterPlotDataRowVisualProperties.ScatterPlotDataRowRegressionType.Polynomial:
697          return coefficients
698            .Reverse() // to match index and order
699            .Select((c, o) => c * Math.Pow(x, o))
700            .Sum();
701        case ScatterPlotDataRowVisualProperties.ScatterPlotDataRowRegressionType.Exponential:
702          return coefficients[1] * Math.Exp(coefficients[0] * x);
703        case ScatterPlotDataRowVisualProperties.ScatterPlotDataRowRegressionType.Power:
704          return coefficients[1] * Math.Pow(x, coefficients[0]);
705        case ScatterPlotDataRowVisualProperties.ScatterPlotDataRowRegressionType.Logarithmic:
706          return coefficients[0] * Math.Log(x) + coefficients[1];
707        default:
708          throw new ArgumentException("Unknown RegressionType: " + row.VisualProperties.RegressionType);
709      }
710    }
711
712    protected static string GetStringFormula(ScatterPlotDataRow row, double[] coefficients) {
713      switch (row.VisualProperties.RegressionType) {
714        case ScatterPlotDataRowVisualProperties.ScatterPlotDataRowRegressionType.Linear:
715          return string.Format("{0:G4} x {1} {2:G4}", coefficients[0], Sign(coefficients[1]), Math.Abs(coefficients[1]));
716        case ScatterPlotDataRowVisualProperties.ScatterPlotDataRowRegressionType.Polynomial:
717          var sb = new StringBuilder();
718          sb.AppendFormat("{0:G4}{1}", coefficients[0], PolyFactor(coefficients.Length - 1));
719          foreach (var x in coefficients
720            .Reverse() // match index and order
721            .Select((c, o) => new { c, o })
722            .Reverse() // higher order first
723            .Skip(1)) // highest order poly already added
724            sb.AppendFormat(" {0} {1:G4}{2}", Sign(x.c), Math.Abs(x.c), PolyFactor(x.o));
725          return sb.ToString();
726        case ScatterPlotDataRowVisualProperties.ScatterPlotDataRowRegressionType.Exponential:
727          return string.Format("{0:G4} e^({1:G4} x)", coefficients[1], coefficients[0]);
728        case ScatterPlotDataRowVisualProperties.ScatterPlotDataRowRegressionType.Power:
729          return string.Format("{0:G4} x^({1:G4})", coefficients[1], coefficients[0]);
730        case ScatterPlotDataRowVisualProperties.ScatterPlotDataRowRegressionType.Logarithmic:
731          return string.Format("{0:G4} ln(x) {1} {2:G4}", coefficients[0], Sign(coefficients[1]), Math.Abs(coefficients[1]));
732        default:
733          throw new ArgumentException("Unknown RegressionType: " + row.VisualProperties.RegressionType);
734      }
735    }
736    private static string Sign(double value) {
737      return value >= 0 ? "+" : "-";
738    }
739    private static string PolyFactor(int order) {
740      if (order == 0) return "";
741      if (order == 1) return " x";
742      if (order == 2) return " x²";
743      if (order == 3) return " x³";
744      return " x^" + order;
745    }
746    #endregion
747  }
748}
Note: See TracBrowser for help on using the repository browser.