source: branches/DataPreprocessing/HeuristicLab.DataPreprocessing.Views/3.3/PreprocessingDataTableView.cs @ 10847

Last change on this file since 10847 was 10847, checked in by aesterer, 6 years ago

Added coloring feature for line chart

File size: 33.5 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2013 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.Windows.Forms;
27using System.Windows.Forms.DataVisualization.Charting;
28using HeuristicLab.Collections;
29using HeuristicLab.Core.Views;
30using HeuristicLab.DataPreprocessing.Implementations;
31using HeuristicLab.MainForm;
32
33namespace HeuristicLab.Analysis.Views {
34  [View("Preprocessing DataTable View")]
35  [Content(typeof(PreprocessingDataTable), false)]
36  public partial class PreprocessingDataTableView : ItemView, IConfigureableView {
37    protected List<Series> invisibleSeries;
38    protected Dictionary<IObservableList<double>, DataRow> valuesRowsTable;
39
40    public new PreprocessingDataTable Content {
41      get { return (PreprocessingDataTable)base.Content; }
42      set { base.Content = value; }
43    }
44
45    public PreprocessingDataTableView() {
46      InitializeComponent();
47      valuesRowsTable = new Dictionary<IObservableList<double>, DataRow>();
48      invisibleSeries = new List<Series>();
49      chart.CustomizeAllChartAreas();
50      chart.ChartAreas[0].CursorX.Interval = 1;
51    }
52
53    #region Event Handler Registration
54    protected override void DeregisterContentEvents() {
55      foreach (DataRow row in Content.Rows)
56        DeregisterDataRowEvents(row);
57      Content.VisualPropertiesChanged -= new EventHandler(Content_VisualPropertiesChanged);
58      Content.Rows.ItemsAdded -= new CollectionItemsChangedEventHandler<DataRow>(Rows_ItemsAdded);
59      Content.Rows.ItemsRemoved -= new CollectionItemsChangedEventHandler<DataRow>(Rows_ItemsRemoved);
60      Content.Rows.ItemsReplaced -= new CollectionItemsChangedEventHandler<DataRow>(Rows_ItemsReplaced);
61      Content.Rows.CollectionReset -= new CollectionItemsChangedEventHandler<DataRow>(Rows_CollectionReset);
62
63      Content.SelectedRows.ItemsAdded -= new CollectionItemsChangedEventHandler<DataRow>(Rows_ItemsAdded);
64      Content.SelectedRows.ItemsRemoved -= new CollectionItemsChangedEventHandler<DataRow>(Rows_ItemsRemoved);
65      Content.SelectedRows.ItemsReplaced -= new CollectionItemsChangedEventHandler<DataRow>(Rows_ItemsReplaced);
66      Content.SelectedRows.CollectionReset -= new CollectionItemsChangedEventHandler<DataRow>(Rows_CollectionReset);
67      base.DeregisterContentEvents();
68    }
69    protected override void RegisterContentEvents() {
70      base.RegisterContentEvents();
71      Content.VisualPropertiesChanged += new EventHandler(Content_VisualPropertiesChanged);
72      Content.Rows.ItemsAdded += new CollectionItemsChangedEventHandler<DataRow>(Rows_ItemsAdded);
73      Content.Rows.ItemsRemoved += new CollectionItemsChangedEventHandler<DataRow>(Rows_ItemsRemoved);
74      Content.Rows.ItemsReplaced += new CollectionItemsChangedEventHandler<DataRow>(Rows_ItemsReplaced);
75      Content.Rows.CollectionReset += new CollectionItemsChangedEventHandler<DataRow>(Rows_CollectionReset);
76
77      Content.SelectedRows.ItemsAdded += new CollectionItemsChangedEventHandler<DataRow>(SelectedRows_ItemsAdded);
78      Content.SelectedRows.ItemsRemoved += new CollectionItemsChangedEventHandler<DataRow>(SelectedRows_ItemsRemoved);
79      Content.SelectedRows.ItemsReplaced += new CollectionItemsChangedEventHandler<DataRow>(SelectedRows_ItemsReplaced);
80      Content.SelectedRows.CollectionReset += new CollectionItemsChangedEventHandler<DataRow>(SelectedRows_CollectionReset);
81    }
82
83
84    protected virtual void RegisterDataRowEvents(DataRow row) {
85      row.NameChanged += new EventHandler(Row_NameChanged);
86      row.VisualPropertiesChanged += new EventHandler(Row_VisualPropertiesChanged);
87      valuesRowsTable.Add(row.Values, row);
88      row.Values.ItemsAdded += new CollectionItemsChangedEventHandler<IndexedItem<double>>(Values_ItemsAdded);
89      row.Values.ItemsRemoved += new CollectionItemsChangedEventHandler<IndexedItem<double>>(Values_ItemsRemoved);
90      row.Values.ItemsReplaced += new CollectionItemsChangedEventHandler<IndexedItem<double>>(Values_ItemsReplaced);
91      row.Values.ItemsMoved += new CollectionItemsChangedEventHandler<IndexedItem<double>>(Values_ItemsMoved);
92      row.Values.CollectionReset += new CollectionItemsChangedEventHandler<IndexedItem<double>>(Values_CollectionReset);
93    }
94    protected virtual void DeregisterDataRowEvents(DataRow row) {
95      row.Values.ItemsAdded -= new CollectionItemsChangedEventHandler<IndexedItem<double>>(Values_ItemsAdded);
96      row.Values.ItemsRemoved -= new CollectionItemsChangedEventHandler<IndexedItem<double>>(Values_ItemsRemoved);
97      row.Values.ItemsReplaced -= new CollectionItemsChangedEventHandler<IndexedItem<double>>(Values_ItemsReplaced);
98      row.Values.ItemsMoved -= new CollectionItemsChangedEventHandler<IndexedItem<double>>(Values_ItemsMoved);
99      row.Values.CollectionReset -= new CollectionItemsChangedEventHandler<IndexedItem<double>>(Values_CollectionReset);
100      valuesRowsTable.Remove(row.Values);
101      row.VisualPropertiesChanged -= new EventHandler(Row_VisualPropertiesChanged);
102      row.NameChanged -= new EventHandler(Row_NameChanged);
103    }
104    #endregion
105
106    protected override void OnContentChanged() {
107      base.OnContentChanged();
108      invisibleSeries.Clear();
109      //chart.Titles[0].Text = string.Empty;
110      chart.ChartAreas[0].AxisX.Title = string.Empty;
111      chart.ChartAreas[0].AxisY.Title = string.Empty;
112      chart.ChartAreas[0].AxisY2.Title = string.Empty;
113      chart.Series.Clear();
114      if (Content != null) {
115        //chart.Titles[0].Text = Content.Name;
116        AddDataRows(Content.Rows);
117        AddSelectedDataRows(Content.SelectedRows);
118        ConfigureChartArea(chart.ChartAreas[0]);
119        RecalculateAxesScale(chart.ChartAreas[0]);
120      }
121    }
122
123    protected override void SetEnabledStateOfControls() {
124      base.SetEnabledStateOfControls();
125      chart.Enabled = Content != null;
126    }
127
128    public void ShowConfiguration() {
129      if (Content != null) {
130        using (var dialog = new DataTableVisualPropertiesDialog(Content)) {
131          dialog.ShowDialog(this);
132        }
133      } else MessageBox.Show("Nothing to configure.");
134    }
135    protected virtual void AddDataRows(IEnumerable<DataRow> rows) {
136      foreach (var row in rows) {
137        RegisterDataRowEvents(row);
138        var series = new Series(row.Name);
139        if (row.VisualProperties.DisplayName.Trim() != String.Empty) series.LegendText = row.VisualProperties.DisplayName;
140        else series.LegendText = row.Name;
141        ConfigureSeries(series, row);
142        FillSeriesWithRowValues(series, row);
143        chart.Series.Add(series);
144      }
145
146      ConfigureChartArea(chart.ChartAreas[0]);
147      RecalculateAxesScale(chart.ChartAreas[0]);
148      UpdateYCursorInterval();
149    }
150
151    protected virtual void AddSelectedDataRows(IEnumerable<DataRow> rows) {
152      foreach (var row in rows) {
153        if (row.VisualProperties.ChartType == DataRowVisualProperties.DataRowChartType.Line) {
154          row.VisualProperties.IsVisibleInLegend = false;
155
156          //add selected to name in order to avoid naming conflict
157          var series = new Series(row.Name+"(Selected)");
158          ConfigureSeries(series, row);
159          FillSeriesWithRowValues(series, row);
160          chart.Series.Add(series);
161        }
162      }
163    }
164
165    protected virtual void RemoveSelectedDataRows(IEnumerable<DataRow> rows) {
166      foreach (var row in rows) {
167        Series series = chart.Series[row.Name + "(Selected)"];
168        chart.Series.Remove(series);
169      }
170    }
171
172    protected virtual void RemoveDataRows(IEnumerable<DataRow> rows) {
173      foreach (var row in rows) {
174        DeregisterDataRowEvents(row);
175        Series series = chart.Series[row.Name];
176        chart.Series.Remove(series);
177        if (invisibleSeries.Contains(series))
178          invisibleSeries.Remove(series);
179      }
180      RecalculateAxesScale(chart.ChartAreas[0]);
181    }
182
183    private void ConfigureSeries(Series series, DataRow row) {
184      RemoveCustomPropertyIfExists(series, "PointWidth");
185      series.BorderWidth = 1;
186      series.BorderDashStyle = ChartDashStyle.Solid;
187      series.BorderColor = Color.Empty;
188
189      if (row.VisualProperties.Color != Color.Empty)
190        series.Color = row.VisualProperties.Color;
191      else series.Color = Color.Empty;
192      series.IsVisibleInLegend = row.VisualProperties.IsVisibleInLegend;
193
194      switch (row.VisualProperties.ChartType) {
195        case DataRowVisualProperties.DataRowChartType.Line:
196          series.ChartType = SeriesChartType.FastLine;
197          series.BorderWidth = row.VisualProperties.LineWidth;
198          series.BorderDashStyle = ConvertLineStyle(row.VisualProperties.LineStyle);
199          break;
200        case DataRowVisualProperties.DataRowChartType.Bars:
201          // Bar is incompatible with anything but Bar and StackedBar*
202          if (!chart.Series.Any(x => x.ChartType != SeriesChartType.Bar && x.ChartType != SeriesChartType.StackedBar && x.ChartType != SeriesChartType.StackedBar100))
203            series.ChartType = SeriesChartType.Bar;
204          else {
205            series.ChartType = SeriesChartType.FastPoint; //default
206            row.VisualProperties.ChartType = DataRowVisualProperties.DataRowChartType.Points;
207          }
208          break;
209        case DataRowVisualProperties.DataRowChartType.Columns:
210          series.ChartType = SeriesChartType.Column;
211          break;
212        case DataRowVisualProperties.DataRowChartType.Points:
213          series.ChartType = SeriesChartType.FastPoint;
214          break;
215        case DataRowVisualProperties.DataRowChartType.Histogram:
216          series.ChartType = SeriesChartType.Column;
217          series.SetCustomProperty("PointWidth", "1");
218          if (!series.Color.IsEmpty && series.Color.GetBrightness() < 0.25)
219            series.BorderColor = Color.White;
220          else series.BorderColor = Color.Black;
221          break;
222        case DataRowVisualProperties.DataRowChartType.StepLine:
223          series.ChartType = SeriesChartType.StepLine;
224          series.BorderWidth = row.VisualProperties.LineWidth;
225          series.BorderDashStyle = ConvertLineStyle(row.VisualProperties.LineStyle);
226          break;
227        default:
228          series.ChartType = SeriesChartType.FastPoint;
229          break;
230      }
231      series.YAxisType = row.VisualProperties.SecondYAxis ? AxisType.Secondary : AxisType.Primary;
232      series.XAxisType = row.VisualProperties.SecondXAxis ? AxisType.Secondary : AxisType.Primary;
233      if (row.VisualProperties.DisplayName.Trim() != String.Empty) series.LegendText = row.VisualProperties.DisplayName;
234      else series.LegendText = row.Name;
235
236      string xAxisTitle = string.IsNullOrEmpty(Content.VisualProperties.XAxisTitle)
237                      ? "X"
238                      : Content.VisualProperties.XAxisTitle;
239      string yAxisTitle = string.IsNullOrEmpty(Content.VisualProperties.YAxisTitle)
240                            ? "Y"
241                            : Content.VisualProperties.YAxisTitle;
242      series.ToolTip =
243        series.LegendText + Environment.NewLine +
244        xAxisTitle + " = " + "#INDEX," + Environment.NewLine +
245        yAxisTitle + " = " + "#VAL";
246    }
247
248    private void ConfigureChartArea(ChartArea area) {
249      if (Content.VisualProperties.TitleFont != null) chart.Titles[0].Font = Content.VisualProperties.TitleFont;
250      if (!Content.VisualProperties.TitleColor.IsEmpty) chart.Titles[0].ForeColor = Content.VisualProperties.TitleColor;
251      chart.Titles[0].Text = Content.VisualProperties.Title;
252
253      if (Content.VisualProperties.AxisTitleFont != null) area.AxisX.TitleFont = Content.VisualProperties.AxisTitleFont;
254      if (!Content.VisualProperties.AxisTitleColor.IsEmpty) area.AxisX.TitleForeColor = Content.VisualProperties.AxisTitleColor;
255      area.AxisX.Title = Content.VisualProperties.XAxisTitle;
256
257      if (Content.VisualProperties.AxisTitleFont != null) area.AxisX2.TitleFont = Content.VisualProperties.AxisTitleFont;
258      if (!Content.VisualProperties.AxisTitleColor.IsEmpty) area.AxisX2.TitleForeColor = Content.VisualProperties.AxisTitleColor;
259      area.AxisX2.Title = Content.VisualProperties.SecondXAxisTitle;
260
261      if (Content.VisualProperties.AxisTitleFont != null) area.AxisY.TitleFont = Content.VisualProperties.AxisTitleFont;
262      if (!Content.VisualProperties.AxisTitleColor.IsEmpty) area.AxisY.TitleForeColor = Content.VisualProperties.AxisTitleColor;
263      area.AxisY.Title = Content.VisualProperties.YAxisTitle;
264
265      if (Content.VisualProperties.AxisTitleFont != null) area.AxisY2.TitleFont = Content.VisualProperties.AxisTitleFont;
266      if (!Content.VisualProperties.AxisTitleColor.IsEmpty) area.AxisY2.TitleForeColor = Content.VisualProperties.AxisTitleColor;
267      area.AxisY2.Title = Content.VisualProperties.SecondYAxisTitle;
268
269      area.AxisX.IsLogarithmic = Content.VisualProperties.XAxisLogScale;
270      area.AxisX2.IsLogarithmic = Content.VisualProperties.SecondXAxisLogScale;
271      area.AxisY.IsLogarithmic = Content.VisualProperties.YAxisLogScale;
272      area.AxisY2.IsLogarithmic = Content.VisualProperties.SecondYAxisLogScale;
273    }
274
275    private void RecalculateAxesScale(ChartArea area) {
276      // Reset the axes bounds so that RecalculateAxesScale() will assign new bounds
277      foreach (Axis a in area.Axes) {
278        a.Minimum = double.NaN;
279        a.Maximum = double.NaN;
280      }
281      area.RecalculateAxesScale();
282      area.AxisX.IsMarginVisible = false;
283      area.AxisX2.IsMarginVisible = false;
284
285      if (!Content.VisualProperties.XAxisMinimumAuto && !double.IsNaN(Content.VisualProperties.XAxisMinimumFixedValue)) area.AxisX.Minimum = Content.VisualProperties.XAxisMinimumFixedValue;
286      if (!Content.VisualProperties.XAxisMaximumAuto && !double.IsNaN(Content.VisualProperties.XAxisMaximumFixedValue)) area.AxisX.Maximum = Content.VisualProperties.XAxisMaximumFixedValue;
287      if (!Content.VisualProperties.SecondXAxisMinimumAuto && !double.IsNaN(Content.VisualProperties.SecondXAxisMinimumFixedValue)) area.AxisX2.Minimum = Content.VisualProperties.SecondXAxisMinimumFixedValue;
288      if (!Content.VisualProperties.SecondXAxisMaximumAuto && !double.IsNaN(Content.VisualProperties.SecondXAxisMaximumFixedValue)) area.AxisX2.Maximum = Content.VisualProperties.SecondXAxisMaximumFixedValue;
289      if (!Content.VisualProperties.YAxisMinimumAuto && !double.IsNaN(Content.VisualProperties.YAxisMinimumFixedValue)) area.AxisY.Minimum = Content.VisualProperties.YAxisMinimumFixedValue;
290      if (!Content.VisualProperties.YAxisMaximumAuto && !double.IsNaN(Content.VisualProperties.YAxisMaximumFixedValue)) area.AxisY.Maximum = Content.VisualProperties.YAxisMaximumFixedValue;
291      if (!Content.VisualProperties.SecondYAxisMinimumAuto && !double.IsNaN(Content.VisualProperties.SecondYAxisMinimumFixedValue)) area.AxisY2.Minimum = Content.VisualProperties.SecondYAxisMinimumFixedValue;
292      if (!Content.VisualProperties.SecondYAxisMaximumAuto && !double.IsNaN(Content.VisualProperties.SecondYAxisMaximumFixedValue)) area.AxisY2.Maximum = Content.VisualProperties.SecondYAxisMaximumFixedValue;
293      if (area.AxisX.Minimum >= area.AxisX.Maximum) area.AxisX.Maximum = area.AxisX.Minimum + 1;
294      if (area.AxisX2.Minimum >= area.AxisX2.Maximum) area.AxisX2.Maximum = area.AxisX2.Minimum + 1;
295      if (area.AxisY.Minimum >= area.AxisY.Maximum) area.AxisY.Maximum = area.AxisY.Minimum + 1;
296      if (area.AxisY2.Minimum >= area.AxisY2.Maximum) area.AxisY2.Maximum = area.AxisY2.Minimum + 1;
297    }
298
299    protected virtual void UpdateYCursorInterval() {
300      double interestingValuesRange = (
301        from series in chart.Series
302        where series.Enabled
303        let values = (from point in series.Points
304                      where !point.IsEmpty
305                      select point.YValues[0]).DefaultIfEmpty(1.0)
306        let range = values.Max() - values.Min()
307        where range > 0.0
308        select range
309        ).DefaultIfEmpty(1.0).Min();
310
311      double digits = (int)Math.Log10(interestingValuesRange) - 3;
312      double yZoomInterval = Math.Pow(10, digits);
313      this.chart.ChartAreas[0].CursorY.Interval = yZoomInterval;
314    }
315
316    #region Event Handlers
317    #region Content Event Handlers
318    private void Content_VisualPropertiesChanged(object sender, EventArgs e) {
319      if (InvokeRequired)
320        Invoke(new EventHandler(Content_VisualPropertiesChanged), sender, e);
321      else {
322        ConfigureChartArea(chart.ChartAreas[0]);
323        RecalculateAxesScale(chart.ChartAreas[0]); // axes min/max could have changed
324      }
325    }
326    #endregion
327    #region Rows Event Handlers
328
329    private void SelectedRows_CollectionReset(object sender, CollectionItemsChangedEventArgs<DataRow> e) {
330      if (InvokeRequired)
331        Invoke(new CollectionItemsChangedEventHandler<DataRow>(Rows_ItemsReplaced), sender, e);
332      else {
333        RemoveSelectedDataRows(e.OldItems);
334        AddSelectedDataRows(e.Items);
335      }
336    }
337
338    private void SelectedRows_ItemsReplaced(object sender, CollectionItemsChangedEventArgs<DataRow> e) {
339      if (InvokeRequired)
340        Invoke(new CollectionItemsChangedEventHandler<DataRow>(Rows_ItemsReplaced), sender, e);
341      else {
342        RemoveSelectedDataRows(e.OldItems);
343        AddSelectedDataRows(e.Items);
344      }
345    }
346
347    private void SelectedRows_ItemsRemoved(object sender, CollectionItemsChangedEventArgs<DataRow> e) {
348      if (InvokeRequired)
349        Invoke(new CollectionItemsChangedEventHandler<DataRow>(Rows_ItemsRemoved), sender, e);
350      else {
351        RemoveSelectedDataRows(e.Items);
352      }
353    }
354
355    private void SelectedRows_ItemsAdded(object sender, CollectionItemsChangedEventArgs<DataRow> e) {
356      if (InvokeRequired)
357        Invoke(new CollectionItemsChangedEventHandler<DataRow>(Rows_ItemsAdded), sender, e);
358      else {
359        AddSelectedDataRows(e.Items);
360      }
361    }
362
363
364    private void Rows_ItemsAdded(object sender, CollectionItemsChangedEventArgs<DataRow> e) {
365      if (InvokeRequired)
366        Invoke(new CollectionItemsChangedEventHandler<DataRow>(Rows_ItemsAdded), sender, e);
367      else {
368        AddDataRows(e.Items);
369      }
370    }
371    private void Rows_ItemsRemoved(object sender, CollectionItemsChangedEventArgs<DataRow> e) {
372      if (InvokeRequired)
373        Invoke(new CollectionItemsChangedEventHandler<DataRow>(Rows_ItemsRemoved), sender, e);
374      else {
375        RemoveDataRows(e.Items);
376      }
377    }
378    private void Rows_ItemsReplaced(object sender, CollectionItemsChangedEventArgs<DataRow> e) {
379      if (InvokeRequired)
380        Invoke(new CollectionItemsChangedEventHandler<DataRow>(Rows_ItemsReplaced), sender, e);
381      else {
382        RemoveDataRows(e.OldItems);
383        AddDataRows(e.Items);
384      }
385    }
386    private void Rows_CollectionReset(object sender, CollectionItemsChangedEventArgs<DataRow> e) {
387      if (InvokeRequired)
388        Invoke(new CollectionItemsChangedEventHandler<DataRow>(Rows_CollectionReset), sender, e);
389      else {
390        RemoveDataRows(e.OldItems);
391        AddDataRows(e.Items);
392      }
393    }
394    #endregion
395    #region Row Event Handlers
396    private void Row_VisualPropertiesChanged(object sender, EventArgs e) {
397      if (InvokeRequired)
398        Invoke(new EventHandler(Row_VisualPropertiesChanged), sender, e);
399      else {
400        DataRow row = (DataRow)sender;
401        Series series = chart.Series[row.Name];
402        series.Points.Clear();
403        ConfigureSeries(series, row);
404        FillSeriesWithRowValues(series, row);
405        RecalculateAxesScale(chart.ChartAreas[0]);
406      }
407    }
408    private void Row_NameChanged(object sender, EventArgs e) {
409      if (InvokeRequired)
410        Invoke(new EventHandler(Row_NameChanged), sender, e);
411      else {
412        DataRow row = (DataRow)sender;
413        chart.Series[row.Name].Name = row.Name;
414      }
415    }
416    #endregion
417    #region Values Event Handlers
418    private void Values_ItemsAdded(object sender, CollectionItemsChangedEventArgs<IndexedItem<double>> e) {
419      if (InvokeRequired)
420        Invoke(new CollectionItemsChangedEventHandler<IndexedItem<double>>(Values_ItemsAdded), sender, e);
421      else {
422        DataRow row = null;
423        valuesRowsTable.TryGetValue((IObservableList<double>)sender, out row);
424        if (row != null) {
425          Series rowSeries = chart.Series[row.Name];
426          if (!invisibleSeries.Contains(rowSeries)) {
427            rowSeries.Points.Clear();
428            FillSeriesWithRowValues(rowSeries, row);
429            RecalculateAxesScale(chart.ChartAreas[0]);
430            UpdateYCursorInterval();
431          }
432        }
433      }
434    }
435    private void Values_ItemsRemoved(object sender, CollectionItemsChangedEventArgs<IndexedItem<double>> e) {
436      if (InvokeRequired)
437        Invoke(new CollectionItemsChangedEventHandler<IndexedItem<double>>(Values_ItemsRemoved), sender, e);
438      else {
439        DataRow row = null;
440        valuesRowsTable.TryGetValue((IObservableList<double>)sender, out row);
441        if (row != null) {
442          Series rowSeries = chart.Series[row.Name];
443          if (!invisibleSeries.Contains(rowSeries)) {
444            rowSeries.Points.Clear();
445            FillSeriesWithRowValues(rowSeries, row);
446            RecalculateAxesScale(chart.ChartAreas[0]);
447            UpdateYCursorInterval();
448          }
449        }
450      }
451    }
452    private void Values_ItemsReplaced(object sender, CollectionItemsChangedEventArgs<IndexedItem<double>> e) {
453      if (InvokeRequired)
454        Invoke(new CollectionItemsChangedEventHandler<IndexedItem<double>>(Values_ItemsReplaced), sender, e);
455      else {
456        DataRow row = null;
457        valuesRowsTable.TryGetValue((IObservableList<double>)sender, out row);
458        if (row != null) {
459          Series rowSeries = chart.Series[row.Name];
460          if (!invisibleSeries.Contains(rowSeries)) {
461            if (row.VisualProperties.ChartType == DataRowVisualProperties.DataRowChartType.Histogram) {
462              rowSeries.Points.Clear();
463              FillSeriesWithRowValues(rowSeries, row);
464            } else {
465              foreach (IndexedItem<double> item in e.Items) {
466                if (IsInvalidValue(item.Value))
467                  rowSeries.Points[item.Index].IsEmpty = true;
468                else {
469                  rowSeries.Points[item.Index].YValues = new double[] { item.Value };
470                  rowSeries.Points[item.Index].IsEmpty = false;
471                }
472              }
473            }
474            RecalculateAxesScale(chart.ChartAreas[0]);
475            UpdateYCursorInterval();
476          }
477        }
478      }
479    }
480    private void Values_ItemsMoved(object sender, CollectionItemsChangedEventArgs<IndexedItem<double>> e) {
481      if (InvokeRequired)
482        Invoke(new CollectionItemsChangedEventHandler<IndexedItem<double>>(Values_ItemsMoved), sender, e);
483      else {
484        DataRow row = null;
485        valuesRowsTable.TryGetValue((IObservableList<double>)sender, out row);
486        if (row != null) {
487          Series rowSeries = chart.Series[row.Name];
488          if (!invisibleSeries.Contains(rowSeries)) {
489            rowSeries.Points.Clear();
490            FillSeriesWithRowValues(rowSeries, row);
491            RecalculateAxesScale(chart.ChartAreas[0]);
492            UpdateYCursorInterval();
493          }
494        }
495      }
496    }
497
498    private void Values_CollectionReset(object sender, CollectionItemsChangedEventArgs<IndexedItem<double>> e) {
499      if (InvokeRequired)
500        Invoke(new CollectionItemsChangedEventHandler<IndexedItem<double>>(Values_CollectionReset), sender, e);
501      else {
502        DataRow row = null;
503        valuesRowsTable.TryGetValue((IObservableList<double>)sender, out row);
504        if (row != null) {
505          Series rowSeries = chart.Series[row.Name];
506          if (!invisibleSeries.Contains(rowSeries)) {
507            rowSeries.Points.Clear();
508            FillSeriesWithRowValues(rowSeries, row);
509            RecalculateAxesScale(chart.ChartAreas[0]);
510            UpdateYCursorInterval();
511          }
512        }
513      }
514    }
515    #endregion
516    #endregion
517
518    #region Chart Event Handlers
519    private void chart_MouseDown(object sender, MouseEventArgs e) {
520      HitTestResult result = chart.HitTest(e.X, e.Y);
521      if (result.ChartElementType == ChartElementType.LegendItem) {
522        ToggleSeriesVisible(result.Series);
523      }
524    }
525    private void chart_MouseMove(object sender, MouseEventArgs e) {
526      HitTestResult result = chart.HitTest(e.X, e.Y);
527      if (result.ChartElementType == ChartElementType.LegendItem)
528        this.Cursor = Cursors.Hand;
529      else
530        this.Cursor = Cursors.Default;
531    }
532    private void chart_CustomizeLegend(object sender, CustomizeLegendEventArgs e) {
533      foreach (LegendItem legendItem in e.LegendItems) {
534        var series = chart.Series[legendItem.SeriesName];
535        if (series != null) {
536          bool seriesIsInvisible = invisibleSeries.Contains(series);
537          foreach (LegendCell cell in legendItem.Cells) {
538            cell.ForeColor = seriesIsInvisible ? Color.Gray : Color.Black;
539          }
540        }
541      }
542    }
543    #endregion
544
545    private void ToggleSeriesVisible(Series series) {
546      if (!invisibleSeries.Contains(series)) {
547        series.Points.Clear();
548        invisibleSeries.Add(series);
549      } else {
550        invisibleSeries.Remove(series);
551        if (Content != null) {
552
553          var row = (from r in Content.Rows
554                     where r.Name == series.Name
555                     select r).Single();
556          FillSeriesWithRowValues(series, row);
557          this.chart.Legends[series.Legend].ForeColor = Color.Black;
558          RecalculateAxesScale(chart.ChartAreas[0]);
559          UpdateYCursorInterval();
560        }
561      }
562    }
563
564    private void FillSeriesWithRowValues(Series series, DataRow row) {
565      switch (row.VisualProperties.ChartType) {
566        case DataRowVisualProperties.DataRowChartType.Histogram:
567          CalculateHistogram(series, row);
568          break;
569        default: {
570            bool yLogarithmic = series.YAxisType == AxisType.Primary
571                                  ? Content.VisualProperties.YAxisLogScale
572                                  : Content.VisualProperties.SecondYAxisLogScale;
573            bool xLogarithmic = series.XAxisType == AxisType.Primary
574                                  ? Content.VisualProperties.XAxisLogScale
575                                  : Content.VisualProperties.SecondXAxisLogScale;
576            for (int i = 0; i < row.Values.Count; i++) {
577              var value = row.Values[i];
578              var point = new DataPoint();
579              point.XValue = row.VisualProperties.StartIndexZero && !xLogarithmic ? i : i + 1;
580              if (IsInvalidValue(value) || (yLogarithmic && value <= 0))
581                point.IsEmpty = true;
582              else
583                point.YValues = new double[] { value };
584              series.Points.Add(point);
585            }
586          }
587          break;
588      }
589    }
590
591    // get minimum ignores nan values
592    private double GetMinimum(IEnumerable<double> values) {
593      double min = Double.MaxValue;
594
595      foreach (double value in values) {
596        if (!Double.IsNaN(value) && value < min)
597          min = value;
598      }
599      return min;
600    }
601
602    //get maximium ignores nan values
603    private double GetMaximum(IEnumerable<double> values) {
604      double max = Double.MinValue;
605
606      foreach (double value in values) {
607        if (!Double.IsNaN(value) && value > max)
608          max = value;
609      }
610      return max;
611    }
612
613    protected virtual void CalculateHistogram(Series series, DataRow row) {
614      series.Points.Clear();
615      if (!row.Values.Any()) return;
616      int bins = row.VisualProperties.Bins;
617
618      double minValue = GetMinimum(row.Values);
619      double maxValue = GetMaximum(row.Values);
620      double intervalWidth = (maxValue - minValue) / bins;
621      if (intervalWidth < 0) return;
622      if (intervalWidth == 0) {
623        series.Points.AddXY(minValue, row.Values.Count);
624        return;
625      }
626
627
628      if (!row.VisualProperties.ExactBins) {
629        intervalWidth = HumanRoundRange(intervalWidth);
630        minValue = Math.Floor(minValue / intervalWidth) * intervalWidth;
631        maxValue = Math.Ceiling(maxValue / intervalWidth) * intervalWidth;
632      }
633
634      double intervalCenter = intervalWidth / 2;
635
636      double min = 0.0, max = 0.0;
637      if (!Double.IsNaN(Content.VisualProperties.XAxisMinimumFixedValue) && !Content.VisualProperties.XAxisMinimumAuto)
638        min = Content.VisualProperties.XAxisMinimumFixedValue;
639      else min = minValue;
640      if (!Double.IsNaN(Content.VisualProperties.XAxisMaximumFixedValue) && !Content.VisualProperties.XAxisMaximumAuto)
641        max = Content.VisualProperties.XAxisMaximumFixedValue;
642      else max = maxValue + intervalWidth;
643
644      double axisInterval = intervalWidth / row.VisualProperties.ScaleFactor;
645
646      var area = chart.ChartAreas[0];
647      area.AxisX.Interval = axisInterval;
648
649      series.SetCustomProperty("PointWidth", "1"); // 0.8 is the default value
650
651      // get the range or intervals which define the grouping of the frequency values
652      var doubleRange = DoubleRange(min, max, intervalWidth).Skip(1).ToList();
653
654      // aggregate the row values by unique key and frequency value
655      var valueFrequencies = (from v in row.Values
656                              where !IsInvalidValue(v)
657                              orderby v
658                              group v by v into g
659                              select new Tuple<double, double>(g.First(), g.Count())).ToList();
660
661      // shift the chart to the left so the bars are placed on the intervals
662      if (valueFrequencies.First().Item1 < doubleRange.First())
663        series.Points.Add(new DataPoint(min - intervalWidth, 0));
664
665      // add data points
666      int j = 0;
667      foreach (var d in doubleRange) {
668        double sum = 0.0;
669        // sum the frequency values that fall within the same interval
670        while (j < valueFrequencies.Count && valueFrequencies[j].Item1 < d) {
671          sum += valueFrequencies[j].Item2;
672          ++j;
673        }
674        string xAxisTitle = string.IsNullOrEmpty(Content.VisualProperties.XAxisTitle)
675                              ? "X"
676                              : Content.VisualProperties.XAxisTitle;
677        string yAxisTitle = string.IsNullOrEmpty(Content.VisualProperties.YAxisTitle)
678                              ? "Y"
679                              : Content.VisualProperties.YAxisTitle;
680        series.Points.Add(new DataPoint(d - intervalCenter, sum) {
681          ToolTip =
682            xAxisTitle + ": [" + (d - intervalWidth) + "-" + d + ")" + Environment.NewLine +
683            yAxisTitle + ": " + sum
684        });
685      }
686    }
687
688    #region Helpers
689    public static IEnumerable<double> DoubleRange(double min, double max, double step) {
690      double i;
691      for (i = min; i <= max; i += step)
692        yield return i;
693
694      if (i != max + step)
695        yield return i;
696    }
697
698    protected void RemoveCustomPropertyIfExists(Series series, string property) {
699      if (series.IsCustomPropertySet(property)) series.DeleteCustomProperty(property);
700    }
701
702    private double HumanRoundRange(double range) {
703      double base10 = Math.Pow(10.0, Math.Floor(Math.Log10(range)));
704      double rounding = range / base10;
705      if (rounding <= 1.5) rounding = 1;
706      else if (rounding <= 2.25) rounding = 2;
707      else if (rounding <= 3.75) rounding = 2.5;
708      else if (rounding <= 7.5) rounding = 5;
709      else rounding = 10;
710      return rounding * base10;
711    }
712
713    private double HumanRoundMax(double max) {
714      double base10;
715      if (max > 0) base10 = Math.Pow(10.0, Math.Floor(Math.Log10(max)));
716      else base10 = Math.Pow(10.0, Math.Ceiling(Math.Log10(-max)));
717      double rounding = (max > 0) ? base10 : -base10;
718      while (rounding < max) rounding += base10;
719      return rounding;
720    }
721
722    private ChartDashStyle ConvertLineStyle(DataRowVisualProperties.DataRowLineStyle dataRowLineStyle) {
723      switch (dataRowLineStyle) {
724        case DataRowVisualProperties.DataRowLineStyle.Dash:
725          return ChartDashStyle.Dash;
726        case DataRowVisualProperties.DataRowLineStyle.DashDot:
727          return ChartDashStyle.DashDot;
728        case DataRowVisualProperties.DataRowLineStyle.DashDotDot:
729          return ChartDashStyle.DashDotDot;
730        case DataRowVisualProperties.DataRowLineStyle.Dot:
731          return ChartDashStyle.Dot;
732        case DataRowVisualProperties.DataRowLineStyle.NotSet:
733          return ChartDashStyle.NotSet;
734        case DataRowVisualProperties.DataRowLineStyle.Solid:
735          return ChartDashStyle.Solid;
736        default:
737          return ChartDashStyle.NotSet;
738      }
739    }
740
741    protected static bool IsInvalidValue(double x) {
742      return double.IsNaN(x) || x < (double)decimal.MinValue || x > (double)decimal.MaxValue;
743    }
744    #endregion
745  }
746}
Note: See TracBrowser for help on using the repository browser.