Free cookie consent management tool by TermsFeed Policy Generator

source: branches/PersistenceSpeedUp/HeuristicLab.Analysis.Views/3.3/DataTableView.cs @ 9330

Last change on this file since 9330 was 6760, checked in by epitzer, 13 years ago

#1530 integrate changes from trunk

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