Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 15592 was 15583, checked in by swagner, 7 years ago

#2640: Updated year of copyrights in license headers

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