Free cookie consent management tool by TermsFeed Policy Generator

source: stable/HeuristicLab.Analysis.Views/3.3/DataTableView.cs @ 16408

Last change on this file since 16408 was 15584, checked in by swagner, 7 years ago

#2640: Updated year of copyrights in license headers on stable

File size: 34.3 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.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(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    protected override void Content_NameChanged(object sender, EventArgs e) {
340      if (InvokeRequired)
341        Invoke(new EventHandler(Content_NameChanged), sender, e);
342      else {
343        Content.VisualProperties.Title = Content.Name;
344        base.Content_NameChanged(sender, e);
345      }
346    }
347    private void Content_VisualPropertiesChanged(object sender, EventArgs e) {
348      if (InvokeRequired)
349        Invoke(new EventHandler(Content_VisualPropertiesChanged), sender, e);
350      else {
351        ConfigureChartArea(chart.ChartAreas[0]);
352        RecalculateAxesScale(chart.ChartAreas[0]); // axes min/max could have changed
353
354        chart.Update(); // side-by-side and stacked histograms are not always correctly displayed without an update
355        // (chart update is required before the series are updated, otherwise the widths of the bars are updated incorrectly)
356        foreach (var row in Content.Rows.Where(r => r.VisualProperties.ChartType == DataRowVisualProperties.DataRowChartType.Histogram))
357          Row_VisualPropertiesChanged(row, EventArgs.Empty); // Histogram properties could have changed
358      }
359    }
360    #endregion
361    #region Rows Event Handlers
362    private void Rows_ItemsAdded(object sender, CollectionItemsChangedEventArgs<DataRow> e) {
363      if (InvokeRequired)
364        Invoke(new CollectionItemsChangedEventHandler<DataRow>(Rows_ItemsAdded), sender, e);
365      else {
366        AddDataRows(e.Items);
367      }
368    }
369    private void Rows_ItemsRemoved(object sender, CollectionItemsChangedEventArgs<DataRow> e) {
370      if (InvokeRequired)
371        Invoke(new CollectionItemsChangedEventHandler<DataRow>(Rows_ItemsRemoved), sender, e);
372      else {
373        RemoveDataRows(e.Items);
374      }
375    }
376    private void Rows_ItemsReplaced(object sender, CollectionItemsChangedEventArgs<DataRow> e) {
377      if (InvokeRequired)
378        Invoke(new CollectionItemsChangedEventHandler<DataRow>(Rows_ItemsReplaced), sender, e);
379      else {
380        RemoveDataRows(e.OldItems);
381        AddDataRows(e.Items);
382      }
383    }
384    private void Rows_CollectionReset(object sender, CollectionItemsChangedEventArgs<DataRow> e) {
385      if (InvokeRequired)
386        Invoke(new CollectionItemsChangedEventHandler<DataRow>(Rows_CollectionReset), sender, e);
387      else {
388        RemoveDataRows(e.OldItems);
389        AddDataRows(e.Items);
390      }
391    }
392    #endregion
393    #region Row Event Handlers
394    private void Row_VisualPropertiesChanged(object sender, EventArgs e) {
395      if (InvokeRequired)
396        Invoke(new EventHandler(Row_VisualPropertiesChanged), sender, e);
397      else {
398        DataRow row = (DataRow)sender;
399        Series series = chart.Series[row.Name];
400        series.Points.Clear();
401        ConfigureSeries(series, row);
402        if (!invisibleSeries.Contains(series)) {
403          FillSeriesWithRowValues(series, row);
404          RecalculateAxesScale(chart.ChartAreas[0]);
405          UpdateHistogramTransparency();
406        }
407      }
408    }
409    private void Row_NameChanged(object sender, EventArgs e) {
410      if (InvokeRequired)
411        Invoke(new EventHandler(Row_NameChanged), sender, e);
412      else {
413        DataRow row = (DataRow)sender;
414        chart.Series[row.Name].Name = row.Name;
415      }
416    }
417    #endregion
418    #region Values Event Handlers
419    private void Values_ItemsAdded(object sender, CollectionItemsChangedEventArgs<IndexedItem<double>> e) {
420      if (InvokeRequired)
421        Invoke(new CollectionItemsChangedEventHandler<IndexedItem<double>>(Values_ItemsAdded), sender, e);
422      else {
423        DataRow row = null;
424        valuesRowsTable.TryGetValue((IObservableList<double>)sender, out row);
425        if (row != null) {
426          Series rowSeries = chart.Series[row.Name];
427          if (!invisibleSeries.Contains(rowSeries)) {
428            rowSeries.Points.Clear();
429            FillSeriesWithRowValues(rowSeries, row);
430            RecalculateAxesScale(chart.ChartAreas[0]);
431            UpdateYCursorInterval();
432          }
433        }
434      }
435    }
436    private void Values_ItemsRemoved(object sender, CollectionItemsChangedEventArgs<IndexedItem<double>> e) {
437      if (InvokeRequired)
438        Invoke(new CollectionItemsChangedEventHandler<IndexedItem<double>>(Values_ItemsRemoved), sender, e);
439      else {
440        DataRow row = null;
441        valuesRowsTable.TryGetValue((IObservableList<double>)sender, out row);
442        if (row != null) {
443          Series rowSeries = chart.Series[row.Name];
444          if (!invisibleSeries.Contains(rowSeries)) {
445            rowSeries.Points.Clear();
446            FillSeriesWithRowValues(rowSeries, row);
447            RecalculateAxesScale(chart.ChartAreas[0]);
448            UpdateYCursorInterval();
449          }
450        }
451      }
452    }
453    private void Values_ItemsReplaced(object sender, CollectionItemsChangedEventArgs<IndexedItem<double>> e) {
454      if (InvokeRequired)
455        Invoke(new CollectionItemsChangedEventHandler<IndexedItem<double>>(Values_ItemsReplaced), sender, e);
456      else {
457        DataRow row = null;
458        valuesRowsTable.TryGetValue((IObservableList<double>)sender, out row);
459        if (row != null) {
460          Series rowSeries = chart.Series[row.Name];
461          if (!invisibleSeries.Contains(rowSeries)) {
462            if (row.VisualProperties.ChartType == DataRowVisualProperties.DataRowChartType.Histogram) {
463              rowSeries.Points.Clear();
464              FillSeriesWithRowValues(rowSeries, row);
465            } else {
466              foreach (IndexedItem<double> item in e.Items) {
467                if (IsInvalidValue(item.Value))
468                  rowSeries.Points[item.Index].IsEmpty = true;
469                else {
470                  rowSeries.Points[item.Index].YValues = new double[] { item.Value };
471                  rowSeries.Points[item.Index].IsEmpty = false;
472                }
473              }
474            }
475            RecalculateAxesScale(chart.ChartAreas[0]);
476            UpdateYCursorInterval();
477          }
478        }
479      }
480    }
481    private void Values_ItemsMoved(object sender, CollectionItemsChangedEventArgs<IndexedItem<double>> e) {
482      if (InvokeRequired)
483        Invoke(new CollectionItemsChangedEventHandler<IndexedItem<double>>(Values_ItemsMoved), sender, e);
484      else {
485        DataRow row = null;
486        valuesRowsTable.TryGetValue((IObservableList<double>)sender, out row);
487        if (row != null) {
488          Series rowSeries = chart.Series[row.Name];
489          if (!invisibleSeries.Contains(rowSeries)) {
490            rowSeries.Points.Clear();
491            FillSeriesWithRowValues(rowSeries, row);
492            RecalculateAxesScale(chart.ChartAreas[0]);
493            UpdateYCursorInterval();
494          }
495        }
496      }
497    }
498
499    private void Values_CollectionReset(object sender, CollectionItemsChangedEventArgs<IndexedItem<double>> e) {
500      if (InvokeRequired)
501        Invoke(new CollectionItemsChangedEventHandler<IndexedItem<double>>(Values_CollectionReset), sender, e);
502      else {
503        DataRow row = null;
504        valuesRowsTable.TryGetValue((IObservableList<double>)sender, out row);
505        if (row != null) {
506          Series rowSeries = chart.Series[row.Name];
507          if (!invisibleSeries.Contains(rowSeries)) {
508            rowSeries.Points.Clear();
509            FillSeriesWithRowValues(rowSeries, row);
510            RecalculateAxesScale(chart.ChartAreas[0]);
511            UpdateYCursorInterval();
512          }
513        }
514      }
515    }
516    #endregion
517    private void configureToolStripMenuItem_Click(object sender, EventArgs e) {
518      ShowConfiguration();
519    }
520    #endregion
521
522    #region Chart Event Handlers
523    private void chart_MouseDown(object sender, MouseEventArgs e) {
524      HitTestResult result = chart.HitTest(e.X, e.Y);
525      if (result.ChartElementType == ChartElementType.LegendItem) {
526        ToggleSeriesVisible(result.Series);
527      }
528    }
529    private void chart_MouseMove(object sender, MouseEventArgs e) {
530      HitTestResult result = chart.HitTest(e.X, e.Y);
531      if (result.ChartElementType == ChartElementType.LegendItem)
532        this.Cursor = Cursors.Hand;
533      else
534        this.Cursor = Cursors.Default;
535    }
536    private void chart_CustomizeLegend(object sender, CustomizeLegendEventArgs e) {
537      foreach (LegendItem legendItem in e.LegendItems) {
538        var series = chart.Series[legendItem.SeriesName];
539        if (series != null) {
540          bool seriesIsInvisible = invisibleSeries.Contains(series);
541          foreach (LegendCell cell in legendItem.Cells) {
542            cell.ForeColor = seriesIsInvisible ? Color.Gray : Color.Black;
543          }
544        }
545      }
546    }
547    #endregion
548
549    private void ToggleSeriesVisible(Series series) {
550      if (!invisibleSeries.Contains(series)) {
551        series.Points.Clear();
552        invisibleSeries.Add(series);
553      } else {
554        invisibleSeries.Remove(series);
555        if (Content != null) {
556
557          var row = (from r in Content.Rows
558                     where r.Name == series.Name
559                     select r).Single();
560          FillSeriesWithRowValues(series, row);
561          this.chart.Legends[series.Legend].ForeColor = Color.Black;
562          RecalculateAxesScale(chart.ChartAreas[0]);
563          UpdateYCursorInterval();
564        }
565      }
566    }
567
568    private void FillSeriesWithRowValues(Series series, DataRow row) {
569      switch (row.VisualProperties.ChartType) {
570        case DataRowVisualProperties.DataRowChartType.Histogram:
571          // when a single histogram is updated, all histograms must be updated. otherwise the value ranges may not be equal.
572          var histograms = Content.Rows
573            .Where(r => r.VisualProperties.ChartType == DataRowVisualProperties.DataRowChartType.Histogram)
574            .ToList();
575          CalculateHistogram(series, row, histograms);
576          foreach (var h in from r in histograms
577                            where r != row
578                            let s = chart.Series.FindByName(r.Name)
579                            where s != null
580                            where !invisibleSeries.Contains(s)
581                            select new { row = r, series = s }) {
582            h.series.Points.Clear();
583            CalculateHistogram(h.series, h.row, histograms);
584          }
585          break;
586        default: {
587            bool yLogarithmic = series.YAxisType == AxisType.Primary
588                                  ? Content.VisualProperties.YAxisLogScale
589                                  : Content.VisualProperties.SecondYAxisLogScale;
590            bool xLogarithmic = series.XAxisType == AxisType.Primary
591                                  ? Content.VisualProperties.XAxisLogScale
592                                  : Content.VisualProperties.SecondXAxisLogScale;
593            for (int i = 0; i < row.Values.Count; i++) {
594              var value = row.Values[i];
595              var point = new DataPoint();
596              point.XValue = row.VisualProperties.StartIndexZero && !xLogarithmic ? i : i + 1;
597              if (IsInvalidValue(value) || (yLogarithmic && value <= 0))
598                point.IsEmpty = true;
599              else
600                point.YValues = new double[] { value };
601              series.Points.Add(point);
602            }
603          }
604          break;
605      }
606    }
607
608    protected virtual void CalculateHistogram(Series series, DataRow row, IEnumerable<DataRow> histogramRows) {
609      series.Points.Clear();
610      if (!row.Values.Any()) return;
611
612      var validValues = histogramRows.SelectMany(r => r.Values).Where(x => !IsInvalidValue(x)).ToList();
613      if (!validValues.Any()) return;
614
615      int bins = Content.VisualProperties.HistogramBins;
616      decimal minValue = (decimal)validValues.Min();
617      decimal maxValue = (decimal)validValues.Max();
618      decimal intervalWidth = (maxValue - minValue) / bins;
619      if (intervalWidth < 0) return;
620      if (intervalWidth == 0) {
621        series.Points.AddXY(minValue, row.Values.Count);
622        return;
623      }
624
625      if (!Content.VisualProperties.HistogramExactBins) {
626        intervalWidth = (decimal)HumanRoundRange((double)intervalWidth);
627        minValue = Math.Floor(minValue / intervalWidth) * intervalWidth;
628        maxValue = Math.Ceiling(maxValue / intervalWidth) * intervalWidth;
629      }
630
631      decimal intervalCenter = intervalWidth / 2;
632
633      decimal min = 0.0m, max = 0.0m;
634      if (!Double.IsNaN(Content.VisualProperties.XAxisMinimumFixedValue) && !Content.VisualProperties.XAxisMinimumAuto)
635        min = (decimal)Content.VisualProperties.XAxisMinimumFixedValue;
636      else min = minValue;
637      if (!Double.IsNaN(Content.VisualProperties.XAxisMaximumFixedValue) && !Content.VisualProperties.XAxisMaximumAuto)
638        max = (decimal)Content.VisualProperties.XAxisMaximumFixedValue;
639      else max = maxValue + intervalWidth;
640
641      double axisInterval = (double)intervalWidth / row.VisualProperties.ScaleFactor;
642
643      var area = chart.ChartAreas[0];
644      area.AxisX.Interval = axisInterval;
645
646      series.SetCustomProperty("PointWidth", "1"); // 0.8 is the default value
647
648      // get the range or intervals which define the grouping of the frequency values
649      var range = Range(min, max, intervalWidth).Skip(1).ToList();
650
651      // aggregate the row values by unique key and frequency value
652      var valueFrequencies = (from v in row.Values
653                              where !IsInvalidValue(v)
654                              orderby v
655                              group v by v into g
656                              select new Tuple<double, double>(g.First(), g.Count())).ToList();
657
658      // ensure that each column is displayed completely on the chart by adding two dummy datapoints on the upper and lower range
659      series.Points.Add(new DataPoint((double)(min - intervalWidth), 0));
660      series.Points.Add(new DataPoint((double)(max + intervalWidth), 0));
661
662      // add data points
663      int j = 0;
664      int overallCount = row.Values.Count(x => !IsInvalidValue(x));
665      foreach (var d in range) {
666        double sum = 0.0;
667        // sum the frequency values that fall within the same interval
668        while (j < valueFrequencies.Count && (decimal)valueFrequencies[j].Item1 < d) {
669          sum += valueFrequencies[j].Item2;
670          ++j;
671        }
672        string xAxisTitle = string.IsNullOrEmpty(Content.VisualProperties.XAxisTitle)
673                              ? "X"
674                              : Content.VisualProperties.XAxisTitle;
675        string yAxisTitle = string.IsNullOrEmpty(Content.VisualProperties.YAxisTitle)
676                              ? "Y"
677                              : Content.VisualProperties.YAxisTitle;
678        series.Points.Add(new DataPoint((double)(d - intervalCenter), sum) {
679          ToolTip =
680            string.Format("{0}: [{1} - {2})", xAxisTitle, (d - intervalWidth), d) + Environment.NewLine +
681            string.Format("{0}: {1} ({2:F2}%)", yAxisTitle, sum, sum / overallCount * 100)
682        });
683      }
684    }
685
686    #region Helpers
687    public static IEnumerable<decimal> Range(decimal min, decimal max, decimal step) {
688      decimal i;
689      for (i = min; i <= max; i += step)
690        yield return i;
691
692      if (i != max + step)
693        yield return i;
694    }
695
696    protected void RemoveCustomPropertyIfExists(Series series, string property) {
697      if (series.IsCustomPropertySet(property)) series.DeleteCustomProperty(property);
698    }
699
700    private double HumanRoundRange(double range) {
701      double base10 = Math.Pow(10.0, Math.Floor(Math.Log10(range)));
702      double rounding = range / base10;
703      if (rounding <= 1.5) rounding = 1;
704      else if (rounding <= 2.25) rounding = 2;
705      else if (rounding <= 3.75) rounding = 2.5;
706      else if (rounding <= 7.5) rounding = 5;
707      else rounding = 10;
708      return rounding * base10;
709    }
710
711    private double HumanRoundMax(double max) {
712      double base10;
713      if (max > 0) base10 = Math.Pow(10.0, Math.Floor(Math.Log10(max)));
714      else base10 = Math.Pow(10.0, Math.Ceiling(Math.Log10(-max)));
715      double rounding = (max > 0) ? base10 : -base10;
716      while (rounding < max) rounding += base10;
717      return rounding;
718    }
719
720    private ChartDashStyle ConvertLineStyle(DataRowVisualProperties.DataRowLineStyle dataRowLineStyle) {
721      switch (dataRowLineStyle) {
722        case DataRowVisualProperties.DataRowLineStyle.Dash:
723          return ChartDashStyle.Dash;
724        case DataRowVisualProperties.DataRowLineStyle.DashDot:
725          return ChartDashStyle.DashDot;
726        case DataRowVisualProperties.DataRowLineStyle.DashDotDot:
727          return ChartDashStyle.DashDotDot;
728        case DataRowVisualProperties.DataRowLineStyle.Dot:
729          return ChartDashStyle.Dot;
730        case DataRowVisualProperties.DataRowLineStyle.NotSet:
731          return ChartDashStyle.NotSet;
732        case DataRowVisualProperties.DataRowLineStyle.Solid:
733          return ChartDashStyle.Solid;
734        default:
735          return ChartDashStyle.NotSet;
736      }
737    }
738
739    protected static bool IsInvalidValue(double x) {
740      return double.IsNaN(x) || x < (double)decimal.MinValue || x > (double)decimal.MaxValue;
741    }
742    #endregion
743  }
744}
Note: See TracBrowser for help on using the repository browser.