Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 7297 was 7297, checked in by abeham, 11 years ago

#1748: Added option to display row as StepLine

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