Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 15008 was 14982, checked in by pfleck, 8 years ago

#2713 Reverted the separation of the DataTable/ScatterPlotView in -View and -Control.
Instead, a ShowName property is added to control whether the name-textbox and the info-label from the NamedItemView are shown.

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