Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 7403 was 7304, checked in by gkronber, 13 years ago

#1738 changed tooltip for data rows in the DataTableView

File size: 29.5 KB
RevLine 
[2908]1#region License Information
2/* HeuristicLab
[7259]3 * Copyright (C) 2002-2012 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
[2908]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;
[4068]23using System.Collections.Generic;
24using System.Drawing;
[3703]25using System.Linq;
[4068]26using System.Windows.Forms;
[2908]27using System.Windows.Forms.DataVisualization.Charting;
28using HeuristicLab.Collections;
29using HeuristicLab.Core.Views;
30using HeuristicLab.MainForm;
31
32namespace HeuristicLab.Analysis.Views {
[2917]33  [View("DataTable View")]
[2908]34  [Content(typeof(DataTable), true)]
[6342]35  public partial class DataTableView : NamedItemView, IConfigureableView {
[5097]36    protected List<Series> invisibleSeries;
37    protected Dictionary<IObservableList<double>, DataRow> valuesRowsTable;
[7244]38
[2908]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>();
[3703]47      invisibleSeries = new List<Series>();
[4636]48      chart.CustomizeAllChartAreas();
49      chart.ChartAreas[0].CursorX.Interval = 1;
[2908]50    }
51
[6342]52    #region Event Handler Registration
[2908]53    protected override void DeregisterContentEvents() {
54      foreach (DataRow row in Content.Rows)
55        DeregisterDataRowEvents(row);
[4870]56      Content.VisualPropertiesChanged -= new EventHandler(Content_VisualPropertiesChanged);
[2908]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();
[4870]65      Content.VisualPropertiesChanged += new EventHandler(Content_VisualPropertiesChanged);
[2908]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
[6342]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
[2908]96    protected override void OnContentChanged() {
97      base.OnContentChanged();
[3703]98      invisibleSeries.Clear();
[4637]99      chart.Titles[0].Text = string.Empty;
[4870]100      chart.ChartAreas[0].AxisX.Title = string.Empty;
101      chart.ChartAreas[0].AxisY.Title = string.Empty;
102      chart.ChartAreas[0].AxisY2.Title = string.Empty;
[2908]103      chart.Series.Clear();
[3454]104      if (Content != null) {
[4637]105        chart.Titles[0].Text = Content.Name;
[2908]106        foreach (DataRow row in Content.Rows)
107          AddDataRow(row);
[6342]108        ConfigureChartArea(chart.ChartAreas[0]);
109        RecalculateAxesScale(chart.ChartAreas[0]);
[2908]110      }
111    }
112
[3904]113    protected override void SetEnabledStateOfControls() {
114      base.SetEnabledStateOfControls();
[3454]115      chart.Enabled = Content != null;
116    }
117
[6342]118    public void ShowConfiguration() {
119      if (Content != null) {
[7244]120        using (DataTableVisualPropertiesDialog dialog = new DataTableVisualPropertiesDialog(Content)) {
121          dialog.ShowDialog(this);
122        }
[6342]123      } else MessageBox.Show("Nothing to configure.");
124    }
[5097]125
126    protected virtual void AddDataRow(DataRow row) {
[2908]127      Series series = new Series(row.Name);
[6628]128      if (row.VisualProperties.DisplayName.Trim() != String.Empty) series.LegendText = row.VisualProperties.DisplayName;
129      else series.LegendText = row.Name;
[6342]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;
[7126]148      series.IsVisibleInLegend = row.VisualProperties.IsVisibleInLegend;
[6342]149
[4644]150      switch (row.VisualProperties.ChartType) {
151        case DataRowVisualProperties.DataRowChartType.Line:
152          series.ChartType = SeriesChartType.FastLine;
[6342]153          series.BorderWidth = row.VisualProperties.LineWidth;
154          series.BorderDashStyle = ConvertLineStyle(row.VisualProperties.LineStyle);
[4644]155          break;
156        case DataRowVisualProperties.DataRowChartType.Bars:
[6342]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          }
[4644]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;
[6342]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;
[7297]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;
[4644]183        default:
184          series.ChartType = SeriesChartType.FastPoint;
185          break;
186      }
187      series.YAxisType = row.VisualProperties.SecondYAxis ? AxisType.Secondary : AxisType.Primary;
[6342]188      series.XAxisType = row.VisualProperties.SecondXAxis ? AxisType.Secondary : AxisType.Primary;
[6628]189      if (row.VisualProperties.DisplayName.Trim() != String.Empty) series.LegendText = row.VisualProperties.DisplayName;
190      else series.LegendText = row.Name;
[7304]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";
[2908]202    }
[3703]203
[6342]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;
[7224]207      chart.Titles[0].Text = Content.VisualProperties.Title;
[5097]208
[6342]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;
[6676]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;
[6342]248    }
249
[5097]250    protected virtual void UpdateYCursorInterval() {
[6342]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();
[3703]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
[5097]267
268    protected virtual void RemoveDataRow(DataRow row) {
[2908]269      Series series = chart.Series[row.Name];
270      chart.Series.Remove(series);
[3703]271      if (invisibleSeries.Contains(series))
272        invisibleSeries.Remove(series);
[6342]273      RecalculateAxesScale(chart.ChartAreas[0]);
[2908]274    }
275
[6342]276    #region Event Handlers
277    #region Content Event Handlers
[2908]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    }
[4870]286    private void Content_VisualPropertiesChanged(object sender, EventArgs e) {
287      if (InvokeRequired)
288        Invoke(new EventHandler(Content_VisualPropertiesChanged), sender, e);
289      else {
[6342]290        ConfigureChartArea(chart.ChartAreas[0]);
291        RecalculateAxesScale(chart.ChartAreas[0]); // axes min/max could have changed
[4870]292      }
293    }
[6342]294    #endregion
295    #region Rows Event Handlers
[2908]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        foreach (DataRow row in e.Items) {
301          AddDataRow(row);
302          RegisterDataRowEvents(row);
303        }
304      }
305    }
306    private void Rows_ItemsRemoved(object sender, CollectionItemsChangedEventArgs<DataRow> e) {
307      if (InvokeRequired)
308        Invoke(new CollectionItemsChangedEventHandler<DataRow>(Rows_ItemsRemoved), sender, e);
309      else {
310        foreach (DataRow row in e.Items) {
311          DeregisterDataRowEvents(row);
312          RemoveDataRow(row);
313        }
314      }
315    }
316    private void Rows_ItemsReplaced(object sender, CollectionItemsChangedEventArgs<DataRow> e) {
317      if (InvokeRequired)
318        Invoke(new CollectionItemsChangedEventHandler<DataRow>(Rows_ItemsReplaced), sender, e);
319      else {
320        foreach (DataRow row in e.OldItems) {
321          DeregisterDataRowEvents(row);
322          RemoveDataRow(row);
323        }
324        foreach (DataRow row in e.Items) {
325          AddDataRow(row);
326          RegisterDataRowEvents(row);
327        }
328      }
329    }
330    private void Rows_CollectionReset(object sender, CollectionItemsChangedEventArgs<DataRow> e) {
331      if (InvokeRequired)
332        Invoke(new CollectionItemsChangedEventHandler<DataRow>(Rows_CollectionReset), sender, e);
333      else {
334        foreach (DataRow row in e.OldItems) {
335          DeregisterDataRowEvents(row);
336          RemoveDataRow(row);
337        }
338        foreach (DataRow row in e.Items) {
339          AddDataRow(row);
340          RegisterDataRowEvents(row);
341        }
342      }
343    }
[6342]344    #endregion
345    #region Row Event Handlers
[4644]346    private void Row_VisualPropertiesChanged(object sender, EventArgs e) {
347      if (InvokeRequired)
348        Invoke(new EventHandler(Row_VisualPropertiesChanged), sender, e);
349      else {
350        DataRow row = (DataRow)sender;
[6342]351        Series series = chart.Series[row.Name];
352        series.Points.Clear();
353        ConfigureSeries(series, row);
354        FillSeriesWithRowValues(series, row);
355        RecalculateAxesScale(chart.ChartAreas[0]);
[4644]356      }
357    }
[2908]358    private void Row_NameChanged(object sender, EventArgs e) {
359      if (InvokeRequired)
360        Invoke(new EventHandler(Row_NameChanged), sender, e);
361      else {
362        DataRow row = (DataRow)sender;
363        chart.Series[row.Name].Name = row.Name;
364      }
365    }
[6342]366    #endregion
367    #region Values Event Handlers
[2908]368    private void Values_ItemsAdded(object sender, CollectionItemsChangedEventArgs<IndexedItem<double>> e) {
369      if (InvokeRequired)
370        Invoke(new CollectionItemsChangedEventHandler<IndexedItem<double>>(Values_ItemsAdded), sender, e);
371      else {
[3561]372        DataRow row = null;
373        valuesRowsTable.TryGetValue((IObservableList<double>)sender, out row);
374        if (row != null) {
[3703]375          Series rowSeries = chart.Series[row.Name];
376          if (!invisibleSeries.Contains(rowSeries)) {
[4778]377            rowSeries.Points.Clear();
378            FillSeriesWithRowValues(rowSeries, row);
[6342]379            RecalculateAxesScale(chart.ChartAreas[0]);
[3703]380            UpdateYCursorInterval();
[3080]381          }
382        }
[2908]383      }
384    }
385    private void Values_ItemsRemoved(object sender, CollectionItemsChangedEventArgs<IndexedItem<double>> e) {
386      if (InvokeRequired)
387        Invoke(new CollectionItemsChangedEventHandler<IndexedItem<double>>(Values_ItemsRemoved), sender, e);
388      else {
[3561]389        DataRow row = null;
390        valuesRowsTable.TryGetValue((IObservableList<double>)sender, out row);
391        if (row != null) {
[3703]392          Series rowSeries = chart.Series[row.Name];
393          if (!invisibleSeries.Contains(rowSeries)) {
[4778]394            rowSeries.Points.Clear();
395            FillSeriesWithRowValues(rowSeries, row);
[6342]396            RecalculateAxesScale(chart.ChartAreas[0]);
[3703]397            UpdateYCursorInterval();
398          }
[3561]399        }
[2908]400      }
401    }
402    private void Values_ItemsReplaced(object sender, CollectionItemsChangedEventArgs<IndexedItem<double>> e) {
403      if (InvokeRequired)
404        Invoke(new CollectionItemsChangedEventHandler<IndexedItem<double>>(Values_ItemsReplaced), sender, e);
405      else {
[3561]406        DataRow row = null;
407        valuesRowsTable.TryGetValue((IObservableList<double>)sender, out row);
408        if (row != null) {
[3703]409          Series rowSeries = chart.Series[row.Name];
410          if (!invisibleSeries.Contains(rowSeries)) {
[6342]411            if (row.VisualProperties.ChartType == DataRowVisualProperties.DataRowChartType.Histogram) {
412              rowSeries.Points.Clear();
413              FillSeriesWithRowValues(rowSeries, row);
414            } else {
415              foreach (IndexedItem<double> item in e.Items) {
416                if (IsInvalidValue(item.Value))
417                  rowSeries.Points[item.Index].IsEmpty = true;
418                else {
419                  rowSeries.Points[item.Index].YValues = new double[] { item.Value };
420                  rowSeries.Points[item.Index].IsEmpty = false;
421                }
[3703]422              }
[3561]423            }
[6342]424            RecalculateAxesScale(chart.ChartAreas[0]);
[3703]425            UpdateYCursorInterval();
[3530]426          }
[3080]427        }
[2908]428      }
429    }
430    private void Values_ItemsMoved(object sender, CollectionItemsChangedEventArgs<IndexedItem<double>> e) {
431      if (InvokeRequired)
432        Invoke(new CollectionItemsChangedEventHandler<IndexedItem<double>>(Values_ItemsMoved), sender, e);
433      else {
[3561]434        DataRow row = null;
435        valuesRowsTable.TryGetValue((IObservableList<double>)sender, out row);
436        if (row != null) {
[3703]437          Series rowSeries = chart.Series[row.Name];
438          if (!invisibleSeries.Contains(rowSeries)) {
[4778]439            rowSeries.Points.Clear();
440            FillSeriesWithRowValues(rowSeries, row);
[6342]441            RecalculateAxesScale(chart.ChartAreas[0]);
[3703]442            UpdateYCursorInterval();
[3530]443          }
[3080]444        }
[2908]445      }
446    }
[3530]447
[2908]448    private void Values_CollectionReset(object sender, CollectionItemsChangedEventArgs<IndexedItem<double>> e) {
449      if (InvokeRequired)
450        Invoke(new CollectionItemsChangedEventHandler<IndexedItem<double>>(Values_CollectionReset), sender, e);
451      else {
[3561]452        DataRow row = null;
453        valuesRowsTable.TryGetValue((IObservableList<double>)sender, out row);
454        if (row != null) {
[3703]455          Series rowSeries = chart.Series[row.Name];
456          if (!invisibleSeries.Contains(rowSeries)) {
457            rowSeries.Points.Clear();
[4778]458            FillSeriesWithRowValues(rowSeries, row);
[6342]459            RecalculateAxesScale(chart.ChartAreas[0]);
[4778]460            UpdateYCursorInterval();
[3530]461          }
[3080]462        }
[2908]463      }
464    }
465    #endregion
[6342]466    #endregion
[4623]467
[6342]468    #region Chart Event Handlers
[3703]469    private void chart_MouseDown(object sender, MouseEventArgs e) {
470      HitTestResult result = chart.HitTest(e.X, e.Y);
471      if (result.ChartElementType == ChartElementType.LegendItem) {
472        ToggleSeriesVisible(result.Series);
473      }
474    }
[6342]475    private void chart_MouseMove(object sender, MouseEventArgs e) {
476      HitTestResult result = chart.HitTest(e.X, e.Y);
477      if (result.ChartElementType == ChartElementType.LegendItem)
478        this.Cursor = Cursors.Hand;
479      else
480        this.Cursor = Cursors.Default;
481    }
482    private void chart_CustomizeLegend(object sender, CustomizeLegendEventArgs e) {
483      foreach (LegendItem legendItem in e.LegendItems) {
484        var series = chart.Series[legendItem.SeriesName];
485        if (series != null) {
486          bool seriesIsInvisible = invisibleSeries.Contains(series);
487          foreach (LegendCell cell in legendItem.Cells) {
488            cell.ForeColor = seriesIsInvisible ? Color.Gray : Color.Black;
489          }
490        }
491      }
492    }
493    #endregion
[3530]494
[3703]495    private void ToggleSeriesVisible(Series series) {
496      if (!invisibleSeries.Contains(series)) {
497        series.Points.Clear();
498        invisibleSeries.Add(series);
499      } else {
500        invisibleSeries.Remove(series);
501        if (Content != null) {
502
503          var row = (from r in Content.Rows
504                     where r.Name == series.Name
505                     select r).Single();
506          FillSeriesWithRowValues(series, row);
507          this.chart.Legends[series.Legend].ForeColor = Color.Black;
[6342]508          RecalculateAxesScale(chart.ChartAreas[0]);
[3703]509          UpdateYCursorInterval();
510        }
511      }
512    }
513
514    private void FillSeriesWithRowValues(Series series, DataRow row) {
[6342]515      switch (row.VisualProperties.ChartType) {
516        case DataRowVisualProperties.DataRowChartType.Histogram:
517          CalculateHistogram(series, row);
518          break;
519        default: {
520            for (int i = 0; i < row.Values.Count; i++) {
521              var value = row.Values[i];
522              DataPoint point = new DataPoint();
523              point.XValue = row.VisualProperties.StartIndexZero ? i : i + 1;
524              if (IsInvalidValue(value))
525                point.IsEmpty = true;
526              else
527                point.YValues = new double[] { value };
528              series.Points.Add(point);
529            }
530          }
531          break;
[3703]532      }
533    }
534
[6342]535    protected virtual void CalculateHistogram(Series series, DataRow row) {
536      series.Points.Clear();
537      if (!row.Values.Any()) return;
538      int bins = row.VisualProperties.Bins;
539
540      double minValue = row.Values.Min();
541      double maxValue = row.Values.Max();
542      double intervalWidth = (maxValue - minValue) / bins;
543      if (intervalWidth < 0) return;
544      if (intervalWidth == 0) {
545        series.Points.AddXY(minValue, row.Values.Count);
546        return;
547      }
548
549      if (!row.VisualProperties.ExactBins) {
550        intervalWidth = HumanRoundRange(intervalWidth);
551        minValue = Math.Floor(minValue / intervalWidth) * intervalWidth;
552        maxValue = Math.Ceiling(maxValue / intervalWidth) * intervalWidth;
553      }
554
[7223]555      double intervalCenter = intervalWidth / 2;
556
557      double min = 0.0;
[6978]558      if (!Double.IsNaN(Content.VisualProperties.XAxisMinimumFixedValue) && !Content.VisualProperties.XAxisMinimumAuto)
[7223]559        min = Content.VisualProperties.XAxisMinimumFixedValue;
560      else min = minValue;
[6978]561
[7223]562      double axisInterval = intervalWidth / row.VisualProperties.ScaleFactor;
[6978]563
[7223]564      var area = chart.ChartAreas[0];
565      area.AxisX.Interval = axisInterval;
[6978]566
[7223]567      series.SetCustomProperty("PointWidth", "1"); // 0.8 is the default value
568
569      // get the range or intervals which define the grouping of the frequency values
570      var doubleRange = DoubleRange(min, maxValue + intervalWidth, intervalWidth).Skip(1).ToList();
571
572      // aggregate the row values by unique key and frequency value
573      var valueFrequencies = (from v in row.Values
574                              where !IsInvalidValue(v)
575                              orderby v
576                              group v by v into g
577                              select new Tuple<double, double>(g.First(), g.Count())).ToList();
578
579      // shift the chart to the left so the bars are placed on the intervals
580      if (valueFrequencies.First().Item1 < doubleRange.First())
581        series.Points.Add(new DataPoint(min - intervalWidth, 0));
582
583      // add data points
584      int j = 0;
585      foreach (var d in doubleRange) {
586        double sum = 0.0;
587        // sum the frequency values that fall within the same interval
588        while (j < valueFrequencies.Count && valueFrequencies[j].Item1 < d) {
589          sum += valueFrequencies[j].Item2;
590          ++j;
[3703]591        }
[7304]592        string xAxisTitle = string.IsNullOrEmpty(Content.VisualProperties.XAxisTitle)
593                              ? "X"
594                              : Content.VisualProperties.XAxisTitle;
595        string yAxisTitle = string.IsNullOrEmpty(Content.VisualProperties.YAxisTitle)
596                              ? "Y"
597                              : Content.VisualProperties.YAxisTitle;
598        series.Points.Add(new DataPoint(d - intervalCenter, sum) {
599          ToolTip =
600            xAxisTitle + ": [" + (d - intervalWidth) + "-" + d + ")" + Environment.NewLine +
601            yAxisTitle + ": " + sum
602        });
[3703]603      }
604    }
605
[6342]606    #region Helpers
[7223]607    public static IEnumerable<double> DoubleRange(double min, double max, double step) {
608      double i;
609      for (i = min; i <= max; i += step)
610        yield return i;
611
612      if (i != max + step)
613        yield return i;
614    }
615
[6342]616    protected void RemoveCustomPropertyIfExists(Series series, string property) {
617      if (series.IsCustomPropertySet(property)) series.DeleteCustomProperty(property);
618    }
[5097]619
[6342]620    private double HumanRoundRange(double range) {
621      double base10 = Math.Pow(10.0, Math.Floor(Math.Log10(range)));
622      double rounding = range / base10;
623      if (rounding <= 1.5) rounding = 1;
624      else if (rounding <= 2.25) rounding = 2;
625      else if (rounding <= 3.75) rounding = 2.5;
626      else if (rounding <= 7.5) rounding = 5;
627      else rounding = 10;
628      return rounding * base10;
629    }
630
631    private double HumanRoundMax(double max) {
632      double base10;
633      if (max > 0) base10 = Math.Pow(10.0, Math.Floor(Math.Log10(max)));
634      else base10 = Math.Pow(10.0, Math.Ceiling(Math.Log10(-max)));
635      double rounding = (max > 0) ? base10 : -base10;
636      while (rounding < max) rounding += base10;
637      return rounding;
638    }
639
640    private ChartDashStyle ConvertLineStyle(DataRowVisualProperties.DataRowLineStyle dataRowLineStyle) {
641      switch (dataRowLineStyle) {
642        case DataRowVisualProperties.DataRowLineStyle.Dash:
643          return ChartDashStyle.Dash;
644        case DataRowVisualProperties.DataRowLineStyle.DashDot:
645          return ChartDashStyle.DashDot;
646        case DataRowVisualProperties.DataRowLineStyle.DashDotDot:
647          return ChartDashStyle.DashDotDot;
648        case DataRowVisualProperties.DataRowLineStyle.Dot:
649          return ChartDashStyle.Dot;
650        case DataRowVisualProperties.DataRowLineStyle.NotSet:
651          return ChartDashStyle.NotSet;
652        case DataRowVisualProperties.DataRowLineStyle.Solid:
653          return ChartDashStyle.Solid;
654        default:
655          return ChartDashStyle.NotSet;
656      }
657    }
658
[5097]659    protected static bool IsInvalidValue(double x) {
[3530]660      return double.IsNaN(x) || x < (double)decimal.MinValue || x > (double)decimal.MaxValue;
661    }
[6342]662    #endregion
[2908]663  }
664}
Note: See TracBrowser for help on using the repository browser.