Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/HeuristicLab.Analysis.Views/3.3/DataTableView.cs @ 18223

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

#2875: Removed years in copyrights

File size: 34.4 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using System;
23using System.Collections.Generic;
24using System.Drawing;
25using System.Linq;
26using System.Windows.Forms;
27using System.Windows.Forms.DataVisualization.Charting;
28using HeuristicLab.Collections;
29using HeuristicLab.Core.Views;
30using HeuristicLab.MainForm;
31
32namespace HeuristicLab.Analysis.Views {
33  [View("DataTable View")]
34  [Content(typeof(DataTable), true)]
35  public partial class DataTableView : NamedItemView, IConfigureableView {
36    protected List<Series> invisibleSeries;
37    protected Dictionary<IObservableList<double>, DataRow> valuesRowsTable;
38    protected bool showChartOnly = false;
39
40    public new DataTable Content {
41      get { return (DataTable)base.Content; }
42      set { base.Content = value; }
43    }
44
45    public bool ShowChartOnly {
46      get { return showChartOnly; }
47      set {
48        if (showChartOnly != value) {
49          showChartOnly = value;
50          UpdateControlsVisibility();
51        }
52      }
53    }
54
55    public DataTableView() {
56      InitializeComponent();
57      valuesRowsTable = new Dictionary<IObservableList<double>, DataRow>();
58      invisibleSeries = new List<Series>();
59      chart.CustomizeAllChartAreas();
60      chart.ChartAreas[0].CursorX.Interval = 1;
61      chart.ContextMenuStrip.Items.Add(configureToolStripMenuItem);
62    }
63
64    #region Event Handler Registration
65    protected override void DeregisterContentEvents() {
66      foreach (DataRow row in Content.Rows)
67        DeregisterDataRowEvents(row);
68      Content.VisualPropertiesChanged -= new EventHandler(Content_VisualPropertiesChanged);
69      Content.Rows.ItemsAdded -= new CollectionItemsChangedEventHandler<DataRow>(Rows_ItemsAdded);
70      Content.Rows.ItemsRemoved -= new CollectionItemsChangedEventHandler<DataRow>(Rows_ItemsRemoved);
71      Content.Rows.ItemsReplaced -= new CollectionItemsChangedEventHandler<DataRow>(Rows_ItemsReplaced);
72      Content.Rows.CollectionReset -= new CollectionItemsChangedEventHandler<DataRow>(Rows_CollectionReset);
73      base.DeregisterContentEvents();
74    }
75    protected override void RegisterContentEvents() {
76      base.RegisterContentEvents();
77      Content.VisualPropertiesChanged += new EventHandler(Content_VisualPropertiesChanged);
78      Content.Rows.ItemsAdded += new CollectionItemsChangedEventHandler<DataRow>(Rows_ItemsAdded);
79      Content.Rows.ItemsRemoved += new CollectionItemsChangedEventHandler<DataRow>(Rows_ItemsRemoved);
80      Content.Rows.ItemsReplaced += new CollectionItemsChangedEventHandler<DataRow>(Rows_ItemsReplaced);
81      Content.Rows.CollectionReset += new CollectionItemsChangedEventHandler<DataRow>(Rows_CollectionReset);
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        chart.Titles[0].Visible = !string.IsNullOrEmpty(Content.Name);
117        AddDataRows(Content.Rows);
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<DataRow>(Content)) {
131          dialog.ShowDialog(this);
132        }
133      } else MessageBox.Show("Nothing to configure.");
134    }
135
136    protected void UpdateControlsVisibility() {
137      if (InvokeRequired)
138        Invoke(new Action(UpdateControlsVisibility));
139      else {
140        foreach (Control c in Controls) {
141          if (c == chart) continue;
142          c.Visible = !showChartOnly;
143        }
144        chart.Dock = showChartOnly ? DockStyle.Fill : DockStyle.None;
145      }
146    }
147
148    protected virtual void AddDataRows(IEnumerable<DataRow> rows) {
149      foreach (var row in rows) {
150        RegisterDataRowEvents(row);
151        var series = new Series(row.Name) {
152          Tag = row
153        };
154        if (row.VisualProperties.DisplayName.Trim() != String.Empty) series.LegendText = row.VisualProperties.DisplayName;
155        else series.LegendText = row.Name;
156        ConfigureSeries(series, row);
157        FillSeriesWithRowValues(series, row);
158        chart.Series.Add(series);
159      }
160      ConfigureChartArea(chart.ChartAreas[0]);
161      RecalculateAxesScale(chart.ChartAreas[0]);
162      UpdateYCursorInterval();
163      UpdateHistogramTransparency();
164    }
165
166    protected virtual void RemoveDataRows(IEnumerable<DataRow> rows) {
167      foreach (var row in rows) {
168        DeregisterDataRowEvents(row);
169        Series series = chart.Series[row.Name];
170        chart.Series.Remove(series);
171        if (invisibleSeries.Contains(series))
172          invisibleSeries.Remove(series);
173      }
174      RecalculateAxesScale(chart.ChartAreas[0]);
175    }
176
177    private void ConfigureSeries(Series series, DataRow row) {
178      RemoveCustomPropertyIfExists(series, "PointWidth");
179      series.BorderWidth = 1;
180      series.BorderDashStyle = ChartDashStyle.Solid;
181      series.BorderColor = Color.Empty;
182
183      if (row.VisualProperties.Color != Color.Empty)
184        series.Color = row.VisualProperties.Color;
185      else series.Color = Color.Empty;
186      series.IsVisibleInLegend = row.VisualProperties.IsVisibleInLegend;
187
188      switch (row.VisualProperties.ChartType) {
189        case DataRowVisualProperties.DataRowChartType.Line:
190          series.ChartType = SeriesChartType.FastLine;
191          series.BorderWidth = row.VisualProperties.LineWidth;
192          series.BorderDashStyle = ConvertLineStyle(row.VisualProperties.LineStyle);
193          break;
194        case DataRowVisualProperties.DataRowChartType.Bars:
195          // Bar is incompatible with anything but Bar and StackedBar*
196          if (!chart.Series.Any(x => x.ChartType != SeriesChartType.Bar && x.ChartType != SeriesChartType.StackedBar && x.ChartType != SeriesChartType.StackedBar100))
197            series.ChartType = SeriesChartType.Bar;
198          else {
199            series.ChartType = SeriesChartType.FastPoint; //default
200            row.VisualProperties.ChartType = DataRowVisualProperties.DataRowChartType.Points;
201          }
202          break;
203        case DataRowVisualProperties.DataRowChartType.Columns:
204          series.ChartType = SeriesChartType.Column;
205          break;
206        case DataRowVisualProperties.DataRowChartType.Points:
207          series.ChartType = SeriesChartType.FastPoint;
208          break;
209        case DataRowVisualProperties.DataRowChartType.Histogram:
210          bool stacked = Content.VisualProperties.HistogramAggregation == DataTableVisualProperties.DataTableHistogramAggregation.Stacked;
211          series.ChartType = stacked ? SeriesChartType.StackedColumn : SeriesChartType.Column;
212          bool sideBySide = Content.VisualProperties.HistogramAggregation == DataTableVisualProperties.DataTableHistogramAggregation.SideBySide;
213          series.SetCustomProperty("DrawSideBySide", sideBySide ? "True" : "False");
214          series.SetCustomProperty("PointWidth", "1");
215          if (!series.Color.IsEmpty && series.Color.GetBrightness() < 0.25)
216            series.BorderColor = Color.White;
217          else series.BorderColor = Color.Black;
218          break;
219        case DataRowVisualProperties.DataRowChartType.StepLine:
220          series.ChartType = SeriesChartType.StepLine;
221          series.BorderWidth = row.VisualProperties.LineWidth;
222          series.BorderDashStyle = ConvertLineStyle(row.VisualProperties.LineStyle);
223          break;
224        default:
225          series.ChartType = SeriesChartType.FastPoint;
226          break;
227      }
228      series.YAxisType = row.VisualProperties.SecondYAxis ? AxisType.Secondary : AxisType.Primary;
229      series.XAxisType = row.VisualProperties.SecondXAxis ? AxisType.Secondary : AxisType.Primary;
230      if (row.VisualProperties.DisplayName.Trim() != String.Empty) series.LegendText = row.VisualProperties.DisplayName;
231      else series.LegendText = row.Name;
232
233      string xAxisTitle = string.IsNullOrEmpty(Content.VisualProperties.XAxisTitle)
234                      ? "X"
235                      : Content.VisualProperties.XAxisTitle;
236      string yAxisTitle = string.IsNullOrEmpty(Content.VisualProperties.YAxisTitle)
237                            ? "Y"
238                            : Content.VisualProperties.YAxisTitle;
239      series.ToolTip =
240        series.LegendText + Environment.NewLine +
241        xAxisTitle + " = " + "#INDEX," + Environment.NewLine +
242        yAxisTitle + " = " + "#VAL";
243    }
244
245    private void ConfigureChartArea(ChartArea area) {
246      if (Content.VisualProperties.TitleFont != null) chart.Titles[0].Font = Content.VisualProperties.TitleFont;
247      if (!Content.VisualProperties.TitleColor.IsEmpty) chart.Titles[0].ForeColor = Content.VisualProperties.TitleColor;
248      chart.Titles[0].Text = Content.VisualProperties.Title;
249      chart.Titles[0].Visible = !string.IsNullOrEmpty(Content.VisualProperties.Title);
250
251      if (Content.VisualProperties.AxisTitleFont != null) area.AxisX.TitleFont = Content.VisualProperties.AxisTitleFont;
252      if (!Content.VisualProperties.AxisTitleColor.IsEmpty) area.AxisX.TitleForeColor = Content.VisualProperties.AxisTitleColor;
253      area.AxisX.Title = Content.VisualProperties.XAxisTitle;
254
255      if (Content.VisualProperties.AxisTitleFont != null) area.AxisX2.TitleFont = Content.VisualProperties.AxisTitleFont;
256      if (!Content.VisualProperties.AxisTitleColor.IsEmpty) area.AxisX2.TitleForeColor = Content.VisualProperties.AxisTitleColor;
257      area.AxisX2.Title = Content.VisualProperties.SecondXAxisTitle;
258
259      if (Content.VisualProperties.AxisTitleFont != null) area.AxisY.TitleFont = Content.VisualProperties.AxisTitleFont;
260      if (!Content.VisualProperties.AxisTitleColor.IsEmpty) area.AxisY.TitleForeColor = Content.VisualProperties.AxisTitleColor;
261      area.AxisY.Title = Content.VisualProperties.YAxisTitle;
262
263      if (Content.VisualProperties.AxisTitleFont != null) area.AxisY2.TitleFont = Content.VisualProperties.AxisTitleFont;
264      if (!Content.VisualProperties.AxisTitleColor.IsEmpty) area.AxisY2.TitleForeColor = Content.VisualProperties.AxisTitleColor;
265      area.AxisY2.Title = Content.VisualProperties.SecondYAxisTitle;
266
267      area.AxisX.IsLogarithmic = Content.VisualProperties.XAxisLogScale;
268      area.AxisX2.IsLogarithmic = Content.VisualProperties.SecondXAxisLogScale;
269      area.AxisY.IsLogarithmic = Content.VisualProperties.YAxisLogScale;
270      area.AxisY2.IsLogarithmic = Content.VisualProperties.SecondYAxisLogScale;
271    }
272
273    private void RecalculateAxesScale(ChartArea area) {
274      // Reset the axes bounds so that RecalculateAxesScale() will assign new bounds
275      foreach (Axis a in area.Axes) {
276        a.Minimum = double.NaN;
277        a.Maximum = double.NaN;
278      }
279      area.RecalculateAxesScale();
280      area.AxisX.IsMarginVisible = false;
281      area.AxisX2.IsMarginVisible = false;
282
283      if (!Content.VisualProperties.XAxisMinimumAuto && !double.IsNaN(Content.VisualProperties.XAxisMinimumFixedValue)) area.AxisX.Minimum = Content.VisualProperties.XAxisMinimumFixedValue;
284      if (!Content.VisualProperties.XAxisMaximumAuto && !double.IsNaN(Content.VisualProperties.XAxisMaximumFixedValue)) area.AxisX.Maximum = Content.VisualProperties.XAxisMaximumFixedValue;
285      if (!Content.VisualProperties.SecondXAxisMinimumAuto && !double.IsNaN(Content.VisualProperties.SecondXAxisMinimumFixedValue)) area.AxisX2.Minimum = Content.VisualProperties.SecondXAxisMinimumFixedValue;
286      if (!Content.VisualProperties.SecondXAxisMaximumAuto && !double.IsNaN(Content.VisualProperties.SecondXAxisMaximumFixedValue)) area.AxisX2.Maximum = Content.VisualProperties.SecondXAxisMaximumFixedValue;
287      if (!Content.VisualProperties.YAxisMinimumAuto && !double.IsNaN(Content.VisualProperties.YAxisMinimumFixedValue)) area.AxisY.Minimum = Content.VisualProperties.YAxisMinimumFixedValue;
288      if (!Content.VisualProperties.YAxisMaximumAuto && !double.IsNaN(Content.VisualProperties.YAxisMaximumFixedValue)) area.AxisY.Maximum = Content.VisualProperties.YAxisMaximumFixedValue;
289      if (!Content.VisualProperties.SecondYAxisMinimumAuto && !double.IsNaN(Content.VisualProperties.SecondYAxisMinimumFixedValue)) area.AxisY2.Minimum = Content.VisualProperties.SecondYAxisMinimumFixedValue;
290      if (!Content.VisualProperties.SecondYAxisMaximumAuto && !double.IsNaN(Content.VisualProperties.SecondYAxisMaximumFixedValue)) area.AxisY2.Maximum = Content.VisualProperties.SecondYAxisMaximumFixedValue;
291      if (area.AxisX.Minimum >= area.AxisX.Maximum) area.AxisX.Maximum = area.AxisX.Minimum + 1;
292      if (area.AxisX2.Minimum >= area.AxisX2.Maximum) area.AxisX2.Maximum = area.AxisX2.Minimum + 1;
293      if (area.AxisY.Minimum >= area.AxisY.Maximum) area.AxisY.Maximum = area.AxisY.Minimum + 1;
294      if (area.AxisY2.Minimum >= area.AxisY2.Maximum) area.AxisY2.Maximum = area.AxisY2.Minimum + 1;
295    }
296
297    protected virtual void UpdateYCursorInterval() {
298      double interestingValuesRange = (
299        from series in chart.Series
300        where series.Enabled
301        let values = (from point in series.Points
302                      where !point.IsEmpty
303                      select point.YValues[0]).DefaultIfEmpty(1.0)
304        let range = values.Max() - values.Min()
305        where range > 0.0
306        select range
307        ).DefaultIfEmpty(1.0).Min();
308
309      double digits = (int)Math.Log10(interestingValuesRange) - 3;
310      double yZoomInterval = Math.Pow(10, digits);
311      this.chart.ChartAreas[0].CursorY.Interval = yZoomInterval;
312    }
313
314    protected void UpdateHistogramTransparency() {
315      if (Content.Rows.Any(r => RequiresTransparency(r) && r.VisualProperties.Color.IsEmpty)) {
316        foreach (var series in chart.Series) // sync colors before applying palette colors
317          series.Color = ((DataRow)series.Tag).VisualProperties.Color;
318        chart.ApplyPaletteColors();
319      }
320
321      var numTransparent = Content.Rows.Count(RequiresTransparency);
322      if (numTransparent <= 1) return;
323      foreach (var series in chart.Series) {
324        var row = (DataRow)series.Tag;
325        if (!RequiresTransparency(row))
326          continue;
327        var baseColor = row.VisualProperties.Color;
328        if (baseColor.IsEmpty) baseColor = series.Color;
329        series.Color = Color.FromArgb(180, baseColor);
330      }
331    }
332    private bool RequiresTransparency(DataRow row) {
333      return row.VisualProperties.ChartType == DataRowVisualProperties.DataRowChartType.Histogram
334             && Content.VisualProperties.HistogramAggregation == DataTableVisualProperties.DataTableHistogramAggregation.Overlapping;
335    }
336
337    #region Event Handlers
338    #region Content Event Handlers
339    private void Content_VisualPropertiesChanged(object sender, EventArgs e) {
340      if (InvokeRequired)
341        Invoke(new EventHandler(Content_VisualPropertiesChanged), sender, e);
342      else {
343        ConfigureChartArea(chart.ChartAreas[0]);
344        RecalculateAxesScale(chart.ChartAreas[0]); // axes min/max could have changed
345
346        chart.Update(); // side-by-side and stacked histograms are not always correctly displayed without an update
347        // (chart update is required before the series are updated, otherwise the widths of the bars are updated incorrectly)
348        foreach (var row in Content.Rows.Where(r => r.VisualProperties.ChartType == DataRowVisualProperties.DataRowChartType.Histogram))
349          Row_VisualPropertiesChanged(row, EventArgs.Empty); // Histogram properties could have changed
350      }
351    }
352    #endregion
353    #region Rows Event Handlers
354    private void Rows_ItemsAdded(object sender, CollectionItemsChangedEventArgs<DataRow> e) {
355      if (InvokeRequired)
356        Invoke(new CollectionItemsChangedEventHandler<DataRow>(Rows_ItemsAdded), sender, e);
357      else {
358        AddDataRows(e.Items);
359      }
360    }
361    private void Rows_ItemsRemoved(object sender, CollectionItemsChangedEventArgs<DataRow> e) {
362      if (InvokeRequired)
363        Invoke(new CollectionItemsChangedEventHandler<DataRow>(Rows_ItemsRemoved), sender, e);
364      else {
365        RemoveDataRows(e.Items);
366      }
367    }
368    private void Rows_ItemsReplaced(object sender, CollectionItemsChangedEventArgs<DataRow> e) {
369      if (InvokeRequired)
370        Invoke(new CollectionItemsChangedEventHandler<DataRow>(Rows_ItemsReplaced), sender, e);
371      else {
372        RemoveDataRows(e.OldItems);
373        AddDataRows(e.Items);
374      }
375    }
376    private void Rows_CollectionReset(object sender, CollectionItemsChangedEventArgs<DataRow> e) {
377      if (InvokeRequired)
378        Invoke(new CollectionItemsChangedEventHandler<DataRow>(Rows_CollectionReset), sender, e);
379      else {
380        RemoveDataRows(e.OldItems);
381        AddDataRows(e.Items);
382      }
383    }
384    #endregion
385    #region Row Event Handlers
386    private void Row_VisualPropertiesChanged(object sender, EventArgs e) {
387      if (InvokeRequired)
388        Invoke(new EventHandler(Row_VisualPropertiesChanged), sender, e);
389      else {
390        DataRow row = (DataRow)sender;
391        Series series = chart.Series[row.Name];
392        ClearPoints(series.Points);
393        ConfigureSeries(series, row);
394        if (!invisibleSeries.Contains(series)) {
395          FillSeriesWithRowValues(series, row);
396          RecalculateAxesScale(chart.ChartAreas[0]);
397          UpdateHistogramTransparency();
398        }
399      }
400    }
401    private void Row_NameChanged(object sender, EventArgs e) {
402      if (InvokeRequired)
403        Invoke(new EventHandler(Row_NameChanged), sender, e);
404      else {
405        DataRow row = (DataRow)sender;
406        chart.Series[row.Name].Name = row.Name;
407      }
408    }
409    #endregion
410    #region Values Event Handlers
411    private void Values_ItemsAdded(object sender, CollectionItemsChangedEventArgs<IndexedItem<double>> e) {
412      if (InvokeRequired)
413        Invoke(new CollectionItemsChangedEventHandler<IndexedItem<double>>(Values_ItemsAdded), sender, e);
414      else {
415        DataRow row = null;
416        valuesRowsTable.TryGetValue((IObservableList<double>)sender, out row);
417        if (row != null) {
418          Series rowSeries = chart.Series[row.Name];
419          if (!invisibleSeries.Contains(rowSeries)) {
420            ClearPoints(rowSeries.Points);
421            FillSeriesWithRowValues(rowSeries, row);
422            RecalculateAxesScale(chart.ChartAreas[0]);
423            UpdateYCursorInterval();
424          }
425        }
426      }
427    }
428    private void Values_ItemsRemoved(object sender, CollectionItemsChangedEventArgs<IndexedItem<double>> e) {
429      if (InvokeRequired)
430        Invoke(new CollectionItemsChangedEventHandler<IndexedItem<double>>(Values_ItemsRemoved), sender, e);
431      else {
432        DataRow row = null;
433        valuesRowsTable.TryGetValue((IObservableList<double>)sender, out row);
434        if (row != null) {
435          Series rowSeries = chart.Series[row.Name];
436          if (!invisibleSeries.Contains(rowSeries)) {
437            ClearPoints(rowSeries.Points);
438            FillSeriesWithRowValues(rowSeries, row);
439            RecalculateAxesScale(chart.ChartAreas[0]);
440            UpdateYCursorInterval();
441          }
442        }
443      }
444    }
445    private void Values_ItemsReplaced(object sender, CollectionItemsChangedEventArgs<IndexedItem<double>> e) {
446      if (InvokeRequired)
447        Invoke(new CollectionItemsChangedEventHandler<IndexedItem<double>>(Values_ItemsReplaced), sender, e);
448      else {
449        DataRow row = null;
450        valuesRowsTable.TryGetValue((IObservableList<double>)sender, out row);
451        if (row != null) {
452          Series rowSeries = chart.Series[row.Name];
453          if (!invisibleSeries.Contains(rowSeries)) {
454            if (row.VisualProperties.ChartType == DataRowVisualProperties.DataRowChartType.Histogram) {
455              ClearPoints(rowSeries.Points);
456              FillSeriesWithRowValues(rowSeries, row);
457            } else {
458              foreach (IndexedItem<double> item in e.Items) {
459                if (IsInvalidValue(item.Value))
460                  rowSeries.Points[item.Index].IsEmpty = true;
461                else {
462                  rowSeries.Points[item.Index].YValues = new double[] { item.Value };
463                  rowSeries.Points[item.Index].IsEmpty = false;
464                }
465              }
466            }
467            RecalculateAxesScale(chart.ChartAreas[0]);
468            UpdateYCursorInterval();
469          }
470        }
471      }
472    }
473    private void Values_ItemsMoved(object sender, CollectionItemsChangedEventArgs<IndexedItem<double>> e) {
474      if (InvokeRequired)
475        Invoke(new CollectionItemsChangedEventHandler<IndexedItem<double>>(Values_ItemsMoved), sender, e);
476      else {
477        DataRow row = null;
478        valuesRowsTable.TryGetValue((IObservableList<double>)sender, out row);
479        if (row != null) {
480          Series rowSeries = chart.Series[row.Name];
481          if (!invisibleSeries.Contains(rowSeries)) {
482            ClearPoints(rowSeries.Points);
483            FillSeriesWithRowValues(rowSeries, row);
484            RecalculateAxesScale(chart.ChartAreas[0]);
485            UpdateYCursorInterval();
486          }
487        }
488      }
489    }
490
491    private void Values_CollectionReset(object sender, CollectionItemsChangedEventArgs<IndexedItem<double>> e) {
492      if (InvokeRequired)
493        Invoke(new CollectionItemsChangedEventHandler<IndexedItem<double>>(Values_CollectionReset), sender, e);
494      else {
495        DataRow row = null;
496        valuesRowsTable.TryGetValue((IObservableList<double>)sender, out row);
497        if (row != null) {
498          Series rowSeries = chart.Series[row.Name];
499          if (!invisibleSeries.Contains(rowSeries)) {
500            ClearPoints(rowSeries.Points);
501            FillSeriesWithRowValues(rowSeries, row);
502            RecalculateAxesScale(chart.ChartAreas[0]);
503            UpdateYCursorInterval();
504          }
505        }
506      }
507    }
508    #endregion
509    private void configureToolStripMenuItem_Click(object sender, EventArgs e) {
510      ShowConfiguration();
511    }
512    #endregion
513
514    #region Chart Event Handlers
515    private void chart_MouseDown(object sender, MouseEventArgs e) {
516      HitTestResult result = chart.HitTest(e.X, e.Y);
517      if (result.ChartElementType == ChartElementType.LegendItem) {
518        ToggleSeriesVisible(result.Series);
519      }
520    }
521    private void chart_MouseMove(object sender, MouseEventArgs e) {
522      HitTestResult result = chart.HitTest(e.X, e.Y);
523      if (result.ChartElementType == ChartElementType.LegendItem)
524        this.Cursor = Cursors.Hand;
525      else
526        this.Cursor = Cursors.Default;
527    }
528    private void chart_CustomizeLegend(object sender, CustomizeLegendEventArgs e) {
529      foreach (LegendItem legendItem in e.LegendItems) {
530        var series = chart.Series[legendItem.SeriesName];
531        if (series != null) {
532          bool seriesIsInvisible = invisibleSeries.Contains(series);
533          foreach (LegendCell cell in legendItem.Cells) {
534            cell.ForeColor = seriesIsInvisible ? Color.Gray : Color.Black;
535          }
536        }
537      }
538    }
539    #endregion
540
541    private void ToggleSeriesVisible(Series series) {
542      if (!invisibleSeries.Contains(series)) {
543        ClearPoints(series.Points);
544        invisibleSeries.Add(series);
545      } else {
546        invisibleSeries.Remove(series);
547        if (Content != null) {
548
549          var row = (from r in Content.Rows
550                     where r.Name == series.Name
551                     select r).Single();
552          FillSeriesWithRowValues(series, row);
553          this.chart.Legends[series.Legend].ForeColor = Color.Black;
554          RecalculateAxesScale(chart.ChartAreas[0]);
555          UpdateYCursorInterval();
556        }
557      }
558    }
559
560    private void FillSeriesWithRowValues(Series series, DataRow row) {
561      switch (row.VisualProperties.ChartType) {
562        case DataRowVisualProperties.DataRowChartType.Histogram:
563          // when a single histogram is updated, all histograms must be updated. otherwise the value ranges may not be equal.
564          var histograms = Content.Rows
565            .Where(r => r.VisualProperties.ChartType == DataRowVisualProperties.DataRowChartType.Histogram)
566            .ToList();
567          CalculateHistogram(series, row, histograms);
568          foreach (var h in from r in histograms
569                            where r != row
570                            let s = chart.Series.FindByName(r.Name)
571                            where s != null
572                            where !invisibleSeries.Contains(s)
573                            select new { row = r, series = s }) {
574            ClearPoints(h.series.Points);
575            CalculateHistogram(h.series, h.row, histograms);
576          }
577          break;
578        default: {
579            bool yLogarithmic = series.YAxisType == AxisType.Primary
580                                  ? Content.VisualProperties.YAxisLogScale
581                                  : Content.VisualProperties.SecondYAxisLogScale;
582            bool xLogarithmic = series.XAxisType == AxisType.Primary
583                                  ? Content.VisualProperties.XAxisLogScale
584                                  : Content.VisualProperties.SecondXAxisLogScale;
585            for (int i = 0; i < row.Values.Count; i++) {
586              var value = row.Values[i];
587              var point = new DataPoint();
588              point.XValue = row.VisualProperties.StartIndexZero && !xLogarithmic ? i : i + 1;
589              if (IsInvalidValue(value) || (yLogarithmic && value <= 0))
590                point.IsEmpty = true;
591              else
592                point.YValues = new double[] { value };
593              series.Points.Add(point);
594            }
595          }
596          break;
597      }
598    }
599
600    protected virtual void CalculateHistogram(Series series, DataRow row, IEnumerable<DataRow> histogramRows) {
601      ClearPoints(series.Points);
602      if (!row.Values.Any()) return;
603
604      var validValues = histogramRows.SelectMany(r => r.Values).Where(x => !IsInvalidValue(x)).ToList();
605      if (!validValues.Any()) return;
606
607      int bins = Content.VisualProperties.HistogramBins;
608      decimal minValue = (decimal)validValues.Min();
609      decimal maxValue = (decimal)validValues.Max();
610      decimal intervalWidth = (maxValue - minValue) / bins;
611      if (intervalWidth < 0) return;
612      if (intervalWidth == 0) {
613        series.Points.AddXY(minValue, row.Values.Count);
614        return;
615      }
616
617      if (!Content.VisualProperties.HistogramExactBins) {
618        intervalWidth = (decimal)HumanRoundRange((double)intervalWidth);
619        minValue = Math.Floor(minValue / intervalWidth) * intervalWidth;
620        maxValue = Math.Ceiling(maxValue / intervalWidth) * intervalWidth;
621      }
622
623      decimal intervalCenter = intervalWidth / 2;
624
625      decimal min = 0.0m, max = 0.0m;
626      if (!Double.IsNaN(Content.VisualProperties.XAxisMinimumFixedValue) && !Content.VisualProperties.XAxisMinimumAuto)
627        min = (decimal)Content.VisualProperties.XAxisMinimumFixedValue;
628      else min = minValue;
629      if (!Double.IsNaN(Content.VisualProperties.XAxisMaximumFixedValue) && !Content.VisualProperties.XAxisMaximumAuto)
630        max = (decimal)Content.VisualProperties.XAxisMaximumFixedValue;
631      else max = maxValue + intervalWidth;
632
633      double axisInterval = (double)intervalWidth / row.VisualProperties.ScaleFactor;
634
635      var area = chart.ChartAreas[0];
636      area.AxisX.Interval = axisInterval;
637
638      series.SetCustomProperty("PointWidth", "1"); // 0.8 is the default value
639
640      // get the range or intervals which define the grouping of the frequency values
641      var range = Range(min, max, intervalWidth).Skip(1).ToList();
642
643      // aggregate the row values by unique key and frequency value
644      var valueFrequencies = (from v in row.Values
645                              where !IsInvalidValue(v)
646                              orderby v
647                              group v by v into g
648                              select new Tuple<double, double>(g.First(), g.Count())).ToList();
649
650      // ensure that each column is displayed completely on the chart by adding two dummy datapoints on the upper and lower range
651      series.Points.Add(new DataPoint((double)(min - intervalWidth), 0));
652      series.Points.Add(new DataPoint((double)(max + intervalWidth), 0));
653
654      // add data points
655      int j = 0;
656      int overallCount = row.Values.Count(x => !IsInvalidValue(x));
657      foreach (var d in range) {
658        double sum = 0.0;
659        // sum the frequency values that fall within the same interval
660        while (j < valueFrequencies.Count && (decimal)valueFrequencies[j].Item1 < d) {
661          sum += valueFrequencies[j].Item2;
662          ++j;
663        }
664        string xAxisTitle = string.IsNullOrEmpty(Content.VisualProperties.XAxisTitle)
665                              ? "X"
666                              : Content.VisualProperties.XAxisTitle;
667        string yAxisTitle = string.IsNullOrEmpty(Content.VisualProperties.YAxisTitle)
668                              ? "Y"
669                              : Content.VisualProperties.YAxisTitle;
670        series.Points.Add(new DataPoint((double)(d - intervalCenter), sum) {
671          ToolTip =
672            string.Format("{0}: [{1} - {2})", xAxisTitle, (d - intervalWidth), d) + Environment.NewLine +
673            string.Format("{0}: {1} ({2:F2}%)", yAxisTitle, sum, sum / overallCount * 100)
674        });
675      }
676    }
677
678    #region Helpers
679    public static IEnumerable<decimal> Range(decimal min, decimal max, decimal step) {
680      decimal i;
681      for (i = min; i <= max; i += step)
682        yield return i;
683
684      if (i != max + step)
685        yield return i;
686    }
687
688    protected void RemoveCustomPropertyIfExists(Series series, string property) {
689      if (series.IsCustomPropertySet(property)) series.DeleteCustomProperty(property);
690    }
691
692    private double HumanRoundRange(double range) {
693      double base10 = Math.Pow(10.0, Math.Floor(Math.Log10(range)));
694      double rounding = range / base10;
695      if (rounding <= 1.5) rounding = 1;
696      else if (rounding <= 2.25) rounding = 2;
697      else if (rounding <= 3.75) rounding = 2.5;
698      else if (rounding <= 7.5) rounding = 5;
699      else rounding = 10;
700      return rounding * base10;
701    }
702
703    private double HumanRoundMax(double max) {
704      double base10;
705      if (max > 0) base10 = Math.Pow(10.0, Math.Floor(Math.Log10(max)));
706      else base10 = Math.Pow(10.0, Math.Ceiling(Math.Log10(-max)));
707      double rounding = (max > 0) ? base10 : -base10;
708      while (rounding < max) rounding += base10;
709      return rounding;
710    }
711
712    private ChartDashStyle ConvertLineStyle(DataRowVisualProperties.DataRowLineStyle dataRowLineStyle) {
713      switch (dataRowLineStyle) {
714        case DataRowVisualProperties.DataRowLineStyle.Dash:
715          return ChartDashStyle.Dash;
716        case DataRowVisualProperties.DataRowLineStyle.DashDot:
717          return ChartDashStyle.DashDot;
718        case DataRowVisualProperties.DataRowLineStyle.DashDotDot:
719          return ChartDashStyle.DashDotDot;
720        case DataRowVisualProperties.DataRowLineStyle.Dot:
721          return ChartDashStyle.Dot;
722        case DataRowVisualProperties.DataRowLineStyle.NotSet:
723          return ChartDashStyle.NotSet;
724        case DataRowVisualProperties.DataRowLineStyle.Solid:
725          return ChartDashStyle.Solid;
726        default:
727          return ChartDashStyle.NotSet;
728      }
729    }
730
731    protected static bool IsInvalidValue(double x) {
732      return double.IsNaN(x) || x < (double)decimal.MinValue || x > (double)decimal.MaxValue;
733    }
734
735    // workaround for performance problem as described in https://stackoverflow.com/questions/5744930/datapointcollection-clear-performance
736    public static void ClearPoints(DataPointCollection points) {
737      points.SuspendUpdates();
738      while (points.Count > 0)
739        points.RemoveAt(points.Count - 1);
740      points.ResumeUpdates();
741    }
742    #endregion
743  }
744}
Note: See TracBrowser for help on using the repository browser.