Free cookie consent management tool by TermsFeed Policy Generator

source: branches/GP-MoveOperators/HeuristicLab.Analysis.Views/3.3/DataTableView.cs @ 11290

Last change on this file since 11290 was 8660, checked in by gkronber, 12 years ago

#1847 merged r8205:8635 from trunk into branch

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