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

Last change on this file since 7977 was 7977, checked in by mkommend, 9 years ago

#1869: Added methods to handle collection of data rows in DataTableView.

File size: 29.1 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        AddDataRows(Content.Rows);
107        ConfigureChartArea(chart.ChartAreas[0]);
108        RecalculateAxesScale(chart.ChartAreas[0]);
109      }
110    }
111
112    protected override void SetEnabledStateOfControls() {
113      base.SetEnabledStateOfControls();
114      chart.Enabled = Content != null;
115    }
116
117    public void ShowConfiguration() {
118      if (Content != null) {
119        using (DataTableVisualPropertiesDialog dialog = new DataTableVisualPropertiesDialog(Content)) {
120          dialog.ShowDialog(this);
121        }
122      } else MessageBox.Show("Nothing to configure.");
123    }
124    protected virtual void AddDataRows(IEnumerable<DataRow> rows) {
125      foreach (var row in rows) {
126        RegisterDataRowEvents(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        chart.Series.Add(series);
133      }
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
192      string xAxisTitle = string.IsNullOrEmpty(Content.VisualProperties.XAxisTitle)
193                      ? "X"
194                      : Content.VisualProperties.XAxisTitle;
195      string yAxisTitle = string.IsNullOrEmpty(Content.VisualProperties.YAxisTitle)
196                            ? "Y"
197                            : Content.VisualProperties.YAxisTitle;
198      series.ToolTip =
199        series.LegendText + Environment.NewLine +
200        xAxisTitle + " = " + "#INDEX," + Environment.NewLine +
201        yAxisTitle + " = " + "#VAL";
202    }
203
204    private void ConfigureChartArea(ChartArea area) {
205      if (Content.VisualProperties.TitleFont != null) chart.Titles[0].Font = Content.VisualProperties.TitleFont;
206      if (!Content.VisualProperties.TitleColor.IsEmpty) chart.Titles[0].ForeColor = Content.VisualProperties.TitleColor;
207      chart.Titles[0].Text = Content.VisualProperties.Title;
208
209      if (Content.VisualProperties.AxisTitleFont != null) area.AxisX.TitleFont = Content.VisualProperties.AxisTitleFont;
210      if (!Content.VisualProperties.AxisTitleColor.IsEmpty) area.AxisX.TitleForeColor = Content.VisualProperties.AxisTitleColor;
211      area.AxisX.Title = Content.VisualProperties.XAxisTitle;
212
213      if (Content.VisualProperties.AxisTitleFont != null) area.AxisX2.TitleFont = Content.VisualProperties.AxisTitleFont;
214      if (!Content.VisualProperties.AxisTitleColor.IsEmpty) area.AxisX2.TitleForeColor = Content.VisualProperties.AxisTitleColor;
215      area.AxisX2.Title = Content.VisualProperties.SecondXAxisTitle;
216
217      if (Content.VisualProperties.AxisTitleFont != null) area.AxisY.TitleFont = Content.VisualProperties.AxisTitleFont;
218      if (!Content.VisualProperties.AxisTitleColor.IsEmpty) area.AxisY.TitleForeColor = Content.VisualProperties.AxisTitleColor;
219      area.AxisY.Title = Content.VisualProperties.YAxisTitle;
220
221      if (Content.VisualProperties.AxisTitleFont != null) area.AxisY2.TitleFont = Content.VisualProperties.AxisTitleFont;
222      if (!Content.VisualProperties.AxisTitleColor.IsEmpty) area.AxisY2.TitleForeColor = Content.VisualProperties.AxisTitleColor;
223      area.AxisY2.Title = Content.VisualProperties.SecondYAxisTitle;
224    }
225
226    private void RecalculateAxesScale(ChartArea area) {
227      // Reset the axes bounds so that RecalculateAxesScale() will assign new bounds
228      foreach (Axis a in area.Axes) {
229        a.Minimum = double.NaN;
230        a.Maximum = double.NaN;
231      }
232      area.RecalculateAxesScale();
233      area.AxisX.IsMarginVisible = false;
234      area.AxisX2.IsMarginVisible = false;
235
236      if (!Content.VisualProperties.XAxisMinimumAuto && !double.IsNaN(Content.VisualProperties.XAxisMinimumFixedValue)) area.AxisX.Minimum = Content.VisualProperties.XAxisMinimumFixedValue;
237      if (!Content.VisualProperties.XAxisMaximumAuto && !double.IsNaN(Content.VisualProperties.XAxisMaximumFixedValue)) area.AxisX.Maximum = Content.VisualProperties.XAxisMaximumFixedValue;
238      if (!Content.VisualProperties.SecondXAxisMinimumAuto && !double.IsNaN(Content.VisualProperties.SecondXAxisMinimumFixedValue)) area.AxisX2.Minimum = Content.VisualProperties.SecondXAxisMinimumFixedValue;
239      if (!Content.VisualProperties.SecondXAxisMaximumAuto && !double.IsNaN(Content.VisualProperties.SecondXAxisMaximumFixedValue)) area.AxisX2.Maximum = Content.VisualProperties.SecondXAxisMaximumFixedValue;
240      if (!Content.VisualProperties.YAxisMinimumAuto && !double.IsNaN(Content.VisualProperties.YAxisMinimumFixedValue)) area.AxisY.Minimum = Content.VisualProperties.YAxisMinimumFixedValue;
241      if (!Content.VisualProperties.YAxisMaximumAuto && !double.IsNaN(Content.VisualProperties.YAxisMaximumFixedValue)) area.AxisY.Maximum = Content.VisualProperties.YAxisMaximumFixedValue;
242      if (!Content.VisualProperties.SecondYAxisMinimumAuto && !double.IsNaN(Content.VisualProperties.SecondYAxisMinimumFixedValue)) area.AxisY2.Minimum = Content.VisualProperties.SecondYAxisMinimumFixedValue;
243      if (!Content.VisualProperties.SecondYAxisMaximumAuto && !double.IsNaN(Content.VisualProperties.SecondYAxisMaximumFixedValue)) area.AxisY2.Maximum = Content.VisualProperties.SecondYAxisMaximumFixedValue;
244      if (area.AxisX.Minimum >= area.AxisX.Maximum) area.AxisX.Maximum = area.AxisX.Minimum + 1;
245      if (area.AxisX2.Minimum >= area.AxisX2.Maximum) area.AxisX2.Maximum = area.AxisX2.Minimum + 1;
246      if (area.AxisY.Minimum >= area.AxisY.Maximum) area.AxisY.Maximum = area.AxisY.Minimum + 1;
247      if (area.AxisY2.Minimum >= area.AxisY2.Maximum) area.AxisY2.Maximum = area.AxisY2.Minimum + 1;
248    }
249
250    protected virtual void UpdateYCursorInterval() {
251      double interestingValuesRange = (
252        from series in chart.Series
253        where series.Enabled
254        let values = (from point in series.Points
255                      where !point.IsEmpty
256                      select point.YValues[0]).DefaultIfEmpty(1.0)
257        let range = values.Max() - values.Min()
258        where range > 0.0
259        select range
260        ).DefaultIfEmpty(1.0).Min();
261
262      double digits = (int)Math.Log10(interestingValuesRange) - 3;
263      double yZoomInterval = Math.Pow(10, digits);
264      this.chart.ChartAreas[0].CursorY.Interval = yZoomInterval;
265    }
266
267    protected virtual void RemoveDataRows(IEnumerable<DataRow> rows) {
268      foreach (var row in rows) {
269        DeregisterDataRowEvents(row);
270        Series series = chart.Series[row.Name];
271        chart.Series.Remove(series);
272        if (invisibleSeries.Contains(series))
273          invisibleSeries.Remove(series);
274      }
275      RecalculateAxesScale(chart.ChartAreas[0]);
276    }
277
278    #region Event Handlers
279    #region Content Event Handlers
280    protected override void Content_NameChanged(object sender, EventArgs e) {
281      if (InvokeRequired)
282        Invoke(new EventHandler(Content_NameChanged), sender, e);
283      else {
284        chart.Titles[0].Text = Content.Name;
285        base.Content_NameChanged(sender, e);
286      }
287    }
288    private void Content_VisualPropertiesChanged(object sender, EventArgs e) {
289      if (InvokeRequired)
290        Invoke(new EventHandler(Content_VisualPropertiesChanged), sender, e);
291      else {
292        ConfigureChartArea(chart.ChartAreas[0]);
293        RecalculateAxesScale(chart.ChartAreas[0]); // axes min/max could have changed
294      }
295    }
296    #endregion
297    #region Rows Event Handlers
298    private void Rows_ItemsAdded(object sender, CollectionItemsChangedEventArgs<DataRow> e) {
299      if (InvokeRequired)
300        Invoke(new CollectionItemsChangedEventHandler<DataRow>(Rows_ItemsAdded), sender, e);
301      else {
302        AddDataRows(e.Items);
303      }
304    }
305    private void Rows_ItemsRemoved(object sender, CollectionItemsChangedEventArgs<DataRow> e) {
306      if (InvokeRequired)
307        Invoke(new CollectionItemsChangedEventHandler<DataRow>(Rows_ItemsRemoved), sender, e);
308      else {
309        RemoveDataRows(e.Items);
310      }
311    }
312    private void Rows_ItemsReplaced(object sender, CollectionItemsChangedEventArgs<DataRow> e) {
313      if (InvokeRequired)
314        Invoke(new CollectionItemsChangedEventHandler<DataRow>(Rows_ItemsReplaced), sender, e);
315      else {
316        RemoveDataRows(e.OldItems);
317        AddDataRows(e.Items);
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        RemoveDataRows(e.OldItems);
325        AddDataRows(e.Items);
326      }
327    }
328    #endregion
329    #region Row Event Handlers
330    private void Row_VisualPropertiesChanged(object sender, EventArgs e) {
331      if (InvokeRequired)
332        Invoke(new EventHandler(Row_VisualPropertiesChanged), sender, e);
333      else {
334        DataRow row = (DataRow)sender;
335        Series series = chart.Series[row.Name];
336        series.Points.Clear();
337        ConfigureSeries(series, row);
338        FillSeriesWithRowValues(series, row);
339        RecalculateAxesScale(chart.ChartAreas[0]);
340      }
341    }
342    private void Row_NameChanged(object sender, EventArgs e) {
343      if (InvokeRequired)
344        Invoke(new EventHandler(Row_NameChanged), sender, e);
345      else {
346        DataRow row = (DataRow)sender;
347        chart.Series[row.Name].Name = row.Name;
348      }
349    }
350    #endregion
351    #region Values Event Handlers
352    private void Values_ItemsAdded(object sender, CollectionItemsChangedEventArgs<IndexedItem<double>> e) {
353      if (InvokeRequired)
354        Invoke(new CollectionItemsChangedEventHandler<IndexedItem<double>>(Values_ItemsAdded), sender, e);
355      else {
356        DataRow row = null;
357        valuesRowsTable.TryGetValue((IObservableList<double>)sender, out row);
358        if (row != null) {
359          Series rowSeries = chart.Series[row.Name];
360          if (!invisibleSeries.Contains(rowSeries)) {
361            rowSeries.Points.Clear();
362            FillSeriesWithRowValues(rowSeries, row);
363            RecalculateAxesScale(chart.ChartAreas[0]);
364            UpdateYCursorInterval();
365          }
366        }
367      }
368    }
369    private void Values_ItemsRemoved(object sender, CollectionItemsChangedEventArgs<IndexedItem<double>> e) {
370      if (InvokeRequired)
371        Invoke(new CollectionItemsChangedEventHandler<IndexedItem<double>>(Values_ItemsRemoved), sender, e);
372      else {
373        DataRow row = null;
374        valuesRowsTable.TryGetValue((IObservableList<double>)sender, out row);
375        if (row != null) {
376          Series rowSeries = chart.Series[row.Name];
377          if (!invisibleSeries.Contains(rowSeries)) {
378            rowSeries.Points.Clear();
379            FillSeriesWithRowValues(rowSeries, row);
380            RecalculateAxesScale(chart.ChartAreas[0]);
381            UpdateYCursorInterval();
382          }
383        }
384      }
385    }
386    private void Values_ItemsReplaced(object sender, CollectionItemsChangedEventArgs<IndexedItem<double>> e) {
387      if (InvokeRequired)
388        Invoke(new CollectionItemsChangedEventHandler<IndexedItem<double>>(Values_ItemsReplaced), sender, e);
389      else {
390        DataRow row = null;
391        valuesRowsTable.TryGetValue((IObservableList<double>)sender, out row);
392        if (row != null) {
393          Series rowSeries = chart.Series[row.Name];
394          if (!invisibleSeries.Contains(rowSeries)) {
395            if (row.VisualProperties.ChartType == DataRowVisualProperties.DataRowChartType.Histogram) {
396              rowSeries.Points.Clear();
397              FillSeriesWithRowValues(rowSeries, row);
398            } else {
399              foreach (IndexedItem<double> item in e.Items) {
400                if (IsInvalidValue(item.Value))
401                  rowSeries.Points[item.Index].IsEmpty = true;
402                else {
403                  rowSeries.Points[item.Index].YValues = new double[] { item.Value };
404                  rowSeries.Points[item.Index].IsEmpty = false;
405                }
406              }
407            }
408            RecalculateAxesScale(chart.ChartAreas[0]);
409            UpdateYCursorInterval();
410          }
411        }
412      }
413    }
414    private void Values_ItemsMoved(object sender, CollectionItemsChangedEventArgs<IndexedItem<double>> e) {
415      if (InvokeRequired)
416        Invoke(new CollectionItemsChangedEventHandler<IndexedItem<double>>(Values_ItemsMoved), sender, e);
417      else {
418        DataRow row = null;
419        valuesRowsTable.TryGetValue((IObservableList<double>)sender, out row);
420        if (row != null) {
421          Series rowSeries = chart.Series[row.Name];
422          if (!invisibleSeries.Contains(rowSeries)) {
423            rowSeries.Points.Clear();
424            FillSeriesWithRowValues(rowSeries, row);
425            RecalculateAxesScale(chart.ChartAreas[0]);
426            UpdateYCursorInterval();
427          }
428        }
429      }
430    }
431
432    private void Values_CollectionReset(object sender, CollectionItemsChangedEventArgs<IndexedItem<double>> e) {
433      if (InvokeRequired)
434        Invoke(new CollectionItemsChangedEventHandler<IndexedItem<double>>(Values_CollectionReset), sender, e);
435      else {
436        DataRow row = null;
437        valuesRowsTable.TryGetValue((IObservableList<double>)sender, out row);
438        if (row != null) {
439          Series rowSeries = chart.Series[row.Name];
440          if (!invisibleSeries.Contains(rowSeries)) {
441            rowSeries.Points.Clear();
442            FillSeriesWithRowValues(rowSeries, row);
443            RecalculateAxesScale(chart.ChartAreas[0]);
444            UpdateYCursorInterval();
445          }
446        }
447      }
448    }
449    #endregion
450    #endregion
451
452    #region Chart Event Handlers
453    private void chart_MouseDown(object sender, MouseEventArgs e) {
454      HitTestResult result = chart.HitTest(e.X, e.Y);
455      if (result.ChartElementType == ChartElementType.LegendItem) {
456        ToggleSeriesVisible(result.Series);
457      }
458    }
459    private void chart_MouseMove(object sender, MouseEventArgs e) {
460      HitTestResult result = chart.HitTest(e.X, e.Y);
461      if (result.ChartElementType == ChartElementType.LegendItem)
462        this.Cursor = Cursors.Hand;
463      else
464        this.Cursor = Cursors.Default;
465    }
466    private void chart_CustomizeLegend(object sender, CustomizeLegendEventArgs e) {
467      foreach (LegendItem legendItem in e.LegendItems) {
468        var series = chart.Series[legendItem.SeriesName];
469        if (series != null) {
470          bool seriesIsInvisible = invisibleSeries.Contains(series);
471          foreach (LegendCell cell in legendItem.Cells) {
472            cell.ForeColor = seriesIsInvisible ? Color.Gray : Color.Black;
473          }
474        }
475      }
476    }
477    #endregion
478
479    private void ToggleSeriesVisible(Series series) {
480      if (!invisibleSeries.Contains(series)) {
481        series.Points.Clear();
482        invisibleSeries.Add(series);
483      } else {
484        invisibleSeries.Remove(series);
485        if (Content != null) {
486
487          var row = (from r in Content.Rows
488                     where r.Name == series.Name
489                     select r).Single();
490          FillSeriesWithRowValues(series, row);
491          this.chart.Legends[series.Legend].ForeColor = Color.Black;
492          RecalculateAxesScale(chart.ChartAreas[0]);
493          UpdateYCursorInterval();
494        }
495      }
496    }
497
498    private void FillSeriesWithRowValues(Series series, DataRow row) {
499      switch (row.VisualProperties.ChartType) {
500        case DataRowVisualProperties.DataRowChartType.Histogram:
501          CalculateHistogram(series, row);
502          break;
503        default: {
504            for (int i = 0; i < row.Values.Count; i++) {
505              var value = row.Values[i];
506              DataPoint point = new DataPoint();
507              point.XValue = row.VisualProperties.StartIndexZero ? i : i + 1;
508              if (IsInvalidValue(value))
509                point.IsEmpty = true;
510              else
511                point.YValues = new double[] { value };
512              series.Points.Add(point);
513            }
514          }
515          break;
516      }
517    }
518
519    protected virtual void CalculateHistogram(Series series, DataRow row) {
520      series.Points.Clear();
521      if (!row.Values.Any()) return;
522      int bins = row.VisualProperties.Bins;
523
524      double minValue = row.Values.Min();
525      double maxValue = row.Values.Max();
526      double intervalWidth = (maxValue - minValue) / bins;
527      if (intervalWidth < 0) return;
528      if (intervalWidth == 0) {
529        series.Points.AddXY(minValue, row.Values.Count);
530        return;
531      }
532
533      if (!row.VisualProperties.ExactBins) {
534        intervalWidth = HumanRoundRange(intervalWidth);
535        minValue = Math.Floor(minValue / intervalWidth) * intervalWidth;
536        maxValue = Math.Ceiling(maxValue / intervalWidth) * intervalWidth;
537      }
538
539      double intervalCenter = intervalWidth / 2;
540
541      double min = 0.0;
542      if (!Double.IsNaN(Content.VisualProperties.XAxisMinimumFixedValue) && !Content.VisualProperties.XAxisMinimumAuto)
543        min = Content.VisualProperties.XAxisMinimumFixedValue;
544      else min = minValue;
545
546      double axisInterval = intervalWidth / row.VisualProperties.ScaleFactor;
547
548      var area = chart.ChartAreas[0];
549      area.AxisX.Interval = axisInterval;
550
551      series.SetCustomProperty("PointWidth", "1"); // 0.8 is the default value
552
553      // get the range or intervals which define the grouping of the frequency values
554      var doubleRange = DoubleRange(min, maxValue + intervalWidth, intervalWidth).Skip(1).ToList();
555
556      // aggregate the row values by unique key and frequency value
557      var valueFrequencies = (from v in row.Values
558                              where !IsInvalidValue(v)
559                              orderby v
560                              group v by v into g
561                              select new Tuple<double, double>(g.First(), g.Count())).ToList();
562
563      // shift the chart to the left so the bars are placed on the intervals
564      if (valueFrequencies.First().Item1 < doubleRange.First())
565        series.Points.Add(new DataPoint(min - intervalWidth, 0));
566
567      // add data points
568      int j = 0;
569      foreach (var d in doubleRange) {
570        double sum = 0.0;
571        // sum the frequency values that fall within the same interval
572        while (j < valueFrequencies.Count && valueFrequencies[j].Item1 < d) {
573          sum += valueFrequencies[j].Item2;
574          ++j;
575        }
576        string xAxisTitle = string.IsNullOrEmpty(Content.VisualProperties.XAxisTitle)
577                              ? "X"
578                              : Content.VisualProperties.XAxisTitle;
579        string yAxisTitle = string.IsNullOrEmpty(Content.VisualProperties.YAxisTitle)
580                              ? "Y"
581                              : Content.VisualProperties.YAxisTitle;
582        series.Points.Add(new DataPoint(d - intervalCenter, sum) {
583          ToolTip =
584            xAxisTitle + ": [" + (d - intervalWidth) + "-" + d + ")" + Environment.NewLine +
585            yAxisTitle + ": " + sum
586        });
587      }
588    }
589
590    #region Helpers
591    public static IEnumerable<double> DoubleRange(double min, double max, double step) {
592      double i;
593      for (i = min; i <= max; i += step)
594        yield return i;
595
596      if (i != max + step)
597        yield return i;
598    }
599
600    protected void RemoveCustomPropertyIfExists(Series series, string property) {
601      if (series.IsCustomPropertySet(property)) series.DeleteCustomProperty(property);
602    }
603
604    private double HumanRoundRange(double range) {
605      double base10 = Math.Pow(10.0, Math.Floor(Math.Log10(range)));
606      double rounding = range / base10;
607      if (rounding <= 1.5) rounding = 1;
608      else if (rounding <= 2.25) rounding = 2;
609      else if (rounding <= 3.75) rounding = 2.5;
610      else if (rounding <= 7.5) rounding = 5;
611      else rounding = 10;
612      return rounding * base10;
613    }
614
615    private double HumanRoundMax(double max) {
616      double base10;
617      if (max > 0) base10 = Math.Pow(10.0, Math.Floor(Math.Log10(max)));
618      else base10 = Math.Pow(10.0, Math.Ceiling(Math.Log10(-max)));
619      double rounding = (max > 0) ? base10 : -base10;
620      while (rounding < max) rounding += base10;
621      return rounding;
622    }
623
624    private ChartDashStyle ConvertLineStyle(DataRowVisualProperties.DataRowLineStyle dataRowLineStyle) {
625      switch (dataRowLineStyle) {
626        case DataRowVisualProperties.DataRowLineStyle.Dash:
627          return ChartDashStyle.Dash;
628        case DataRowVisualProperties.DataRowLineStyle.DashDot:
629          return ChartDashStyle.DashDot;
630        case DataRowVisualProperties.DataRowLineStyle.DashDotDot:
631          return ChartDashStyle.DashDotDot;
632        case DataRowVisualProperties.DataRowLineStyle.Dot:
633          return ChartDashStyle.Dot;
634        case DataRowVisualProperties.DataRowLineStyle.NotSet:
635          return ChartDashStyle.NotSet;
636        case DataRowVisualProperties.DataRowLineStyle.Solid:
637          return ChartDashStyle.Solid;
638        default:
639          return ChartDashStyle.NotSet;
640      }
641    }
642
643    protected static bool IsInvalidValue(double x) {
644      return double.IsNaN(x) || x < (double)decimal.MinValue || x > (double)decimal.MaxValue;
645    }
646    #endregion
647  }
648}
Note: See TracBrowser for help on using the repository browser.