Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Analysis.Views/3.3/DataTableControl.cs @ 14508

Last change on this file since 14508 was 14508, checked in by pfleck, 7 years ago

#2715 Only use valid values for calculating min/max for histograms to avoid conversion errors from NaN.

File size: 31.2 KB
RevLine 
[2908]1#region License Information
2/* HeuristicLab
[14185]3 * Copyright (C) 2002-2016 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;
[14435]28using HeuristicLab.Collections;
[2908]29
30namespace HeuristicLab.Analysis.Views {
[14439]31  public partial class DataTableControl : UserControl {
[5097]32    protected List<Series> invisibleSeries;
33    protected Dictionary<IObservableList<double>, DataRow> valuesRowsTable;
[7244]34
[14439]35    private DataTable content;
36    public DataTable Content {
37      get { return content; }
38      set {
39        if (value == content) return;
40        if (content != null) DeregisterContentEvents();
41        content = value;
42        if (content != null) RegisterContentEvents();
43        OnContentChanged();
44        SetEnabledStateOfControls();
45      }
[2908]46    }
47
[14439]48    public DataTableControl() {
[2908]49      InitializeComponent();
50      valuesRowsTable = new Dictionary<IObservableList<double>, DataRow>();
[3703]51      invisibleSeries = new List<Series>();
[4636]52      chart.CustomizeAllChartAreas();
53      chart.ChartAreas[0].CursorX.Interval = 1;
[14435]54      chart.ContextMenuStrip.Items.Add(configureToolStripMenuItem);
[2908]55    }
56
[6342]57    #region Event Handler Registration
[14439]58    protected virtual void DeregisterContentEvents() {
[2908]59      foreach (DataRow row in Content.Rows)
60        DeregisterDataRowEvents(row);
[4870]61      Content.VisualPropertiesChanged -= new EventHandler(Content_VisualPropertiesChanged);
[2908]62      Content.Rows.ItemsAdded -= new CollectionItemsChangedEventHandler<DataRow>(Rows_ItemsAdded);
63      Content.Rows.ItemsRemoved -= new CollectionItemsChangedEventHandler<DataRow>(Rows_ItemsRemoved);
64      Content.Rows.ItemsReplaced -= new CollectionItemsChangedEventHandler<DataRow>(Rows_ItemsReplaced);
65      Content.Rows.CollectionReset -= new CollectionItemsChangedEventHandler<DataRow>(Rows_CollectionReset);
66    }
[14439]67    protected virtual void RegisterContentEvents() {
[4870]68      Content.VisualPropertiesChanged += new EventHandler(Content_VisualPropertiesChanged);
[2908]69      Content.Rows.ItemsAdded += new CollectionItemsChangedEventHandler<DataRow>(Rows_ItemsAdded);
70      Content.Rows.ItemsRemoved += new CollectionItemsChangedEventHandler<DataRow>(Rows_ItemsRemoved);
71      Content.Rows.ItemsReplaced += new CollectionItemsChangedEventHandler<DataRow>(Rows_ItemsReplaced);
72      Content.Rows.CollectionReset += new CollectionItemsChangedEventHandler<DataRow>(Rows_CollectionReset);
73    }
74
[6342]75    protected virtual void RegisterDataRowEvents(DataRow row) {
76      row.NameChanged += new EventHandler(Row_NameChanged);
77      row.VisualPropertiesChanged += new EventHandler(Row_VisualPropertiesChanged);
78      valuesRowsTable.Add(row.Values, row);
79      row.Values.ItemsAdded += new CollectionItemsChangedEventHandler<IndexedItem<double>>(Values_ItemsAdded);
80      row.Values.ItemsRemoved += new CollectionItemsChangedEventHandler<IndexedItem<double>>(Values_ItemsRemoved);
81      row.Values.ItemsReplaced += new CollectionItemsChangedEventHandler<IndexedItem<double>>(Values_ItemsReplaced);
82      row.Values.ItemsMoved += new CollectionItemsChangedEventHandler<IndexedItem<double>>(Values_ItemsMoved);
83      row.Values.CollectionReset += new CollectionItemsChangedEventHandler<IndexedItem<double>>(Values_CollectionReset);
84    }
85    protected virtual void DeregisterDataRowEvents(DataRow row) {
86      row.Values.ItemsAdded -= new CollectionItemsChangedEventHandler<IndexedItem<double>>(Values_ItemsAdded);
87      row.Values.ItemsRemoved -= new CollectionItemsChangedEventHandler<IndexedItem<double>>(Values_ItemsRemoved);
88      row.Values.ItemsReplaced -= new CollectionItemsChangedEventHandler<IndexedItem<double>>(Values_ItemsReplaced);
89      row.Values.ItemsMoved -= new CollectionItemsChangedEventHandler<IndexedItem<double>>(Values_ItemsMoved);
90      row.Values.CollectionReset -= new CollectionItemsChangedEventHandler<IndexedItem<double>>(Values_CollectionReset);
91      valuesRowsTable.Remove(row.Values);
92      row.VisualPropertiesChanged -= new EventHandler(Row_VisualPropertiesChanged);
93      row.NameChanged -= new EventHandler(Row_NameChanged);
94    }
95    #endregion
96
[14439]97    protected virtual void 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;
[14438]106        chart.Titles[0].Visible = !string.IsNullOrEmpty(Content.Name);
[7977]107        AddDataRows(Content.Rows);
[6342]108        ConfigureChartArea(chart.ChartAreas[0]);
109        RecalculateAxesScale(chart.ChartAreas[0]);
[2908]110      }
111    }
112
[14439]113    protected virtual void SetEnabledStateOfControls() {
[3454]114      chart.Enabled = Content != null;
115    }
116
[6342]117    public void ShowConfiguration() {
118      if (Content != null) {
[9258]119        using (var dialog = new DataTableVisualPropertiesDialog(Content)) {
[7244]120          dialog.ShowDialog(this);
121        }
[6342]122      } else MessageBox.Show("Nothing to configure.");
123    }
[7977]124    protected virtual void AddDataRows(IEnumerable<DataRow> rows) {
125      foreach (var row in rows) {
126        RegisterDataRowEvents(row);
[9258]127        var series = new Series(row.Name);
[7977]128        if (row.VisualProperties.DisplayName.Trim() != String.Empty) series.LegendText = row.VisualProperties.DisplayName;
129        else series.LegendText = row.Name;
130        ConfigureSeries(series, row);
131        FillSeriesWithRowValues(series, row);
132        chart.Series.Add(series);
133      }
[6342]134      ConfigureChartArea(chart.ChartAreas[0]);
135      RecalculateAxesScale(chart.ChartAreas[0]);
136      UpdateYCursorInterval();
137    }
138
[7979]139    protected virtual void RemoveDataRows(IEnumerable<DataRow> rows) {
140      foreach (var row in rows) {
141        DeregisterDataRowEvents(row);
142        Series series = chart.Series[row.Name];
143        chart.Series.Remove(series);
144        if (invisibleSeries.Contains(series))
145          invisibleSeries.Remove(series);
146      }
147      RecalculateAxesScale(chart.ChartAreas[0]);
148    }
149
[6342]150    private void ConfigureSeries(Series series, DataRow row) {
151      RemoveCustomPropertyIfExists(series, "PointWidth");
152      series.BorderWidth = 1;
153      series.BorderDashStyle = ChartDashStyle.Solid;
154      series.BorderColor = Color.Empty;
155
156      if (row.VisualProperties.Color != Color.Empty)
157        series.Color = row.VisualProperties.Color;
158      else series.Color = Color.Empty;
[7126]159      series.IsVisibleInLegend = row.VisualProperties.IsVisibleInLegend;
[6342]160
[4644]161      switch (row.VisualProperties.ChartType) {
162        case DataRowVisualProperties.DataRowChartType.Line:
163          series.ChartType = SeriesChartType.FastLine;
[6342]164          series.BorderWidth = row.VisualProperties.LineWidth;
165          series.BorderDashStyle = ConvertLineStyle(row.VisualProperties.LineStyle);
[4644]166          break;
167        case DataRowVisualProperties.DataRowChartType.Bars:
[6342]168          // Bar is incompatible with anything but Bar and StackedBar*
169          if (!chart.Series.Any(x => x.ChartType != SeriesChartType.Bar && x.ChartType != SeriesChartType.StackedBar && x.ChartType != SeriesChartType.StackedBar100))
170            series.ChartType = SeriesChartType.Bar;
171          else {
172            series.ChartType = SeriesChartType.FastPoint; //default
173            row.VisualProperties.ChartType = DataRowVisualProperties.DataRowChartType.Points;
174          }
[4644]175          break;
176        case DataRowVisualProperties.DataRowChartType.Columns:
177          series.ChartType = SeriesChartType.Column;
178          break;
179        case DataRowVisualProperties.DataRowChartType.Points:
180          series.ChartType = SeriesChartType.FastPoint;
181          break;
[6342]182        case DataRowVisualProperties.DataRowChartType.Histogram:
[14457]183          series.ChartType = SeriesChartType.StackedColumn;
[6342]184          series.SetCustomProperty("PointWidth", "1");
185          if (!series.Color.IsEmpty && series.Color.GetBrightness() < 0.25)
186            series.BorderColor = Color.White;
187          else series.BorderColor = Color.Black;
188          break;
[7297]189        case DataRowVisualProperties.DataRowChartType.StepLine:
190          series.ChartType = SeriesChartType.StepLine;
191          series.BorderWidth = row.VisualProperties.LineWidth;
192          series.BorderDashStyle = ConvertLineStyle(row.VisualProperties.LineStyle);
193          break;
[4644]194        default:
195          series.ChartType = SeriesChartType.FastPoint;
196          break;
197      }
198      series.YAxisType = row.VisualProperties.SecondYAxis ? AxisType.Secondary : AxisType.Primary;
[6342]199      series.XAxisType = row.VisualProperties.SecondXAxis ? AxisType.Secondary : AxisType.Primary;
[6628]200      if (row.VisualProperties.DisplayName.Trim() != String.Empty) series.LegendText = row.VisualProperties.DisplayName;
201      else series.LegendText = row.Name;
[7304]202
203      string xAxisTitle = string.IsNullOrEmpty(Content.VisualProperties.XAxisTitle)
204                      ? "X"
205                      : Content.VisualProperties.XAxisTitle;
206      string yAxisTitle = string.IsNullOrEmpty(Content.VisualProperties.YAxisTitle)
207                            ? "Y"
208                            : Content.VisualProperties.YAxisTitle;
209      series.ToolTip =
210        series.LegendText + Environment.NewLine +
211        xAxisTitle + " = " + "#INDEX," + Environment.NewLine +
212        yAxisTitle + " = " + "#VAL";
[2908]213    }
[3703]214
[6342]215    private void ConfigureChartArea(ChartArea area) {
216      if (Content.VisualProperties.TitleFont != null) chart.Titles[0].Font = Content.VisualProperties.TitleFont;
217      if (!Content.VisualProperties.TitleColor.IsEmpty) chart.Titles[0].ForeColor = Content.VisualProperties.TitleColor;
[7224]218      chart.Titles[0].Text = Content.VisualProperties.Title;
[14438]219      chart.Titles[0].Visible = !string.IsNullOrEmpty(Content.VisualProperties.Title);
[5097]220
[6342]221      if (Content.VisualProperties.AxisTitleFont != null) area.AxisX.TitleFont = Content.VisualProperties.AxisTitleFont;
222      if (!Content.VisualProperties.AxisTitleColor.IsEmpty) area.AxisX.TitleForeColor = Content.VisualProperties.AxisTitleColor;
223      area.AxisX.Title = Content.VisualProperties.XAxisTitle;
224
225      if (Content.VisualProperties.AxisTitleFont != null) area.AxisX2.TitleFont = Content.VisualProperties.AxisTitleFont;
226      if (!Content.VisualProperties.AxisTitleColor.IsEmpty) area.AxisX2.TitleForeColor = Content.VisualProperties.AxisTitleColor;
227      area.AxisX2.Title = Content.VisualProperties.SecondXAxisTitle;
228
229      if (Content.VisualProperties.AxisTitleFont != null) area.AxisY.TitleFont = Content.VisualProperties.AxisTitleFont;
230      if (!Content.VisualProperties.AxisTitleColor.IsEmpty) area.AxisY.TitleForeColor = Content.VisualProperties.AxisTitleColor;
231      area.AxisY.Title = Content.VisualProperties.YAxisTitle;
232
233      if (Content.VisualProperties.AxisTitleFont != null) area.AxisY2.TitleFont = Content.VisualProperties.AxisTitleFont;
234      if (!Content.VisualProperties.AxisTitleColor.IsEmpty) area.AxisY2.TitleForeColor = Content.VisualProperties.AxisTitleColor;
235      area.AxisY2.Title = Content.VisualProperties.SecondYAxisTitle;
[9258]236
237      area.AxisX.IsLogarithmic = Content.VisualProperties.XAxisLogScale;
238      area.AxisX2.IsLogarithmic = Content.VisualProperties.SecondXAxisLogScale;
239      area.AxisY.IsLogarithmic = Content.VisualProperties.YAxisLogScale;
240      area.AxisY2.IsLogarithmic = Content.VisualProperties.SecondYAxisLogScale;
[6342]241    }
242
243    private void RecalculateAxesScale(ChartArea area) {
244      // Reset the axes bounds so that RecalculateAxesScale() will assign new bounds
245      foreach (Axis a in area.Axes) {
246        a.Minimum = double.NaN;
247        a.Maximum = double.NaN;
248      }
249      area.RecalculateAxesScale();
250      area.AxisX.IsMarginVisible = false;
251      area.AxisX2.IsMarginVisible = false;
252
253      if (!Content.VisualProperties.XAxisMinimumAuto && !double.IsNaN(Content.VisualProperties.XAxisMinimumFixedValue)) area.AxisX.Minimum = Content.VisualProperties.XAxisMinimumFixedValue;
254      if (!Content.VisualProperties.XAxisMaximumAuto && !double.IsNaN(Content.VisualProperties.XAxisMaximumFixedValue)) area.AxisX.Maximum = Content.VisualProperties.XAxisMaximumFixedValue;
255      if (!Content.VisualProperties.SecondXAxisMinimumAuto && !double.IsNaN(Content.VisualProperties.SecondXAxisMinimumFixedValue)) area.AxisX2.Minimum = Content.VisualProperties.SecondXAxisMinimumFixedValue;
256      if (!Content.VisualProperties.SecondXAxisMaximumAuto && !double.IsNaN(Content.VisualProperties.SecondXAxisMaximumFixedValue)) area.AxisX2.Maximum = Content.VisualProperties.SecondXAxisMaximumFixedValue;
257      if (!Content.VisualProperties.YAxisMinimumAuto && !double.IsNaN(Content.VisualProperties.YAxisMinimumFixedValue)) area.AxisY.Minimum = Content.VisualProperties.YAxisMinimumFixedValue;
258      if (!Content.VisualProperties.YAxisMaximumAuto && !double.IsNaN(Content.VisualProperties.YAxisMaximumFixedValue)) area.AxisY.Maximum = Content.VisualProperties.YAxisMaximumFixedValue;
259      if (!Content.VisualProperties.SecondYAxisMinimumAuto && !double.IsNaN(Content.VisualProperties.SecondYAxisMinimumFixedValue)) area.AxisY2.Minimum = Content.VisualProperties.SecondYAxisMinimumFixedValue;
260      if (!Content.VisualProperties.SecondYAxisMaximumAuto && !double.IsNaN(Content.VisualProperties.SecondYAxisMaximumFixedValue)) area.AxisY2.Maximum = Content.VisualProperties.SecondYAxisMaximumFixedValue;
[6676]261      if (area.AxisX.Minimum >= area.AxisX.Maximum) area.AxisX.Maximum = area.AxisX.Minimum + 1;
262      if (area.AxisX2.Minimum >= area.AxisX2.Maximum) area.AxisX2.Maximum = area.AxisX2.Minimum + 1;
263      if (area.AxisY.Minimum >= area.AxisY.Maximum) area.AxisY.Maximum = area.AxisY.Minimum + 1;
264      if (area.AxisY2.Minimum >= area.AxisY2.Maximum) area.AxisY2.Maximum = area.AxisY2.Minimum + 1;
[6342]265    }
266
[5097]267    protected virtual void UpdateYCursorInterval() {
[6342]268      double interestingValuesRange = (
269        from series in chart.Series
270        where series.Enabled
271        let values = (from point in series.Points
272                      where !point.IsEmpty
273                      select point.YValues[0]).DefaultIfEmpty(1.0)
274        let range = values.Max() - values.Min()
275        where range > 0.0
276        select range
277        ).DefaultIfEmpty(1.0).Min();
[3703]278
279      double digits = (int)Math.Log10(interestingValuesRange) - 3;
280      double yZoomInterval = Math.Pow(10, digits);
281      this.chart.ChartAreas[0].CursorY.Interval = yZoomInterval;
282    }
283
[6342]284    #region Event Handlers
285    #region Content Event Handlers
[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 {
[7977]300        AddDataRows(e.Items);
[2908]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 {
[7977]307        RemoveDataRows(e.Items);
[2908]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 {
[7977]314        RemoveDataRows(e.OldItems);
315        AddDataRows(e.Items);
[2908]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 {
[7977]322        RemoveDataRows(e.OldItems);
323        AddDataRows(e.Items);
[2908]324      }
325    }
[6342]326    #endregion
327    #region Row Event Handlers
[4644]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;
[6342]333        Series series = chart.Series[row.Name];
334        series.Points.Clear();
335        ConfigureSeries(series, row);
336        FillSeriesWithRowValues(series, row);
337        RecalculateAxesScale(chart.ChartAreas[0]);
[4644]338      }
339    }
[2908]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    }
[6342]348    #endregion
349    #region Values Event Handlers
[2908]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 {
[3561]354        DataRow row = null;
355        valuesRowsTable.TryGetValue((IObservableList<double>)sender, out row);
356        if (row != null) {
[3703]357          Series rowSeries = chart.Series[row.Name];
358          if (!invisibleSeries.Contains(rowSeries)) {
[4778]359            rowSeries.Points.Clear();
360            FillSeriesWithRowValues(rowSeries, row);
[6342]361            RecalculateAxesScale(chart.ChartAreas[0]);
[3703]362            UpdateYCursorInterval();
[3080]363          }
364        }
[2908]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 {
[3561]371        DataRow row = null;
372        valuesRowsTable.TryGetValue((IObservableList<double>)sender, out row);
373        if (row != null) {
[3703]374          Series rowSeries = chart.Series[row.Name];
375          if (!invisibleSeries.Contains(rowSeries)) {
[4778]376            rowSeries.Points.Clear();
377            FillSeriesWithRowValues(rowSeries, row);
[6342]378            RecalculateAxesScale(chart.ChartAreas[0]);
[3703]379            UpdateYCursorInterval();
380          }
[3561]381        }
[2908]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 {
[3561]388        DataRow row = null;
389        valuesRowsTable.TryGetValue((IObservableList<double>)sender, out row);
390        if (row != null) {
[3703]391          Series rowSeries = chart.Series[row.Name];
392          if (!invisibleSeries.Contains(rowSeries)) {
[6342]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                }
[3703]404              }
[3561]405            }
[6342]406            RecalculateAxesScale(chart.ChartAreas[0]);
[3703]407            UpdateYCursorInterval();
[3530]408          }
[3080]409        }
[2908]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 {
[3561]416        DataRow row = null;
417        valuesRowsTable.TryGetValue((IObservableList<double>)sender, out row);
418        if (row != null) {
[3703]419          Series rowSeries = chart.Series[row.Name];
420          if (!invisibleSeries.Contains(rowSeries)) {
[4778]421            rowSeries.Points.Clear();
422            FillSeriesWithRowValues(rowSeries, row);
[6342]423            RecalculateAxesScale(chart.ChartAreas[0]);
[3703]424            UpdateYCursorInterval();
[3530]425          }
[3080]426        }
[2908]427      }
428    }
[3530]429
[2908]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 {
[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)) {
439            rowSeries.Points.Clear();
[4778]440            FillSeriesWithRowValues(rowSeries, row);
[6342]441            RecalculateAxesScale(chart.ChartAreas[0]);
[4778]442            UpdateYCursorInterval();
[3530]443          }
[3080]444        }
[2908]445      }
446    }
447    #endregion
[14435]448    private void configureToolStripMenuItem_Click(object sender, EventArgs e) {
449      ShowConfiguration();
450    }
[6342]451    #endregion
[4623]452
[6342]453    #region Chart Event Handlers
[3703]454    private void chart_MouseDown(object sender, MouseEventArgs e) {
455      HitTestResult result = chart.HitTest(e.X, e.Y);
456      if (result.ChartElementType == ChartElementType.LegendItem) {
457        ToggleSeriesVisible(result.Series);
458      }
459    }
[6342]460    private void chart_MouseMove(object sender, MouseEventArgs e) {
461      HitTestResult result = chart.HitTest(e.X, e.Y);
462      if (result.ChartElementType == ChartElementType.LegendItem)
463        this.Cursor = Cursors.Hand;
464      else
465        this.Cursor = Cursors.Default;
466    }
467    private void chart_CustomizeLegend(object sender, CustomizeLegendEventArgs e) {
468      foreach (LegendItem legendItem in e.LegendItems) {
469        var series = chart.Series[legendItem.SeriesName];
470        if (series != null) {
471          bool seriesIsInvisible = invisibleSeries.Contains(series);
472          foreach (LegendCell cell in legendItem.Cells) {
473            cell.ForeColor = seriesIsInvisible ? Color.Gray : Color.Black;
474          }
475        }
476      }
477    }
478    #endregion
[3530]479
[3703]480    private void ToggleSeriesVisible(Series series) {
481      if (!invisibleSeries.Contains(series)) {
482        series.Points.Clear();
483        invisibleSeries.Add(series);
484      } else {
485        invisibleSeries.Remove(series);
486        if (Content != null) {
487
488          var row = (from r in Content.Rows
489                     where r.Name == series.Name
490                     select r).Single();
491          FillSeriesWithRowValues(series, row);
492          this.chart.Legends[series.Legend].ForeColor = Color.Black;
[6342]493          RecalculateAxesScale(chart.ChartAreas[0]);
[3703]494          UpdateYCursorInterval();
495        }
496      }
497    }
498
499    private void FillSeriesWithRowValues(Series series, DataRow row) {
[6342]500      switch (row.VisualProperties.ChartType) {
501        case DataRowVisualProperties.DataRowChartType.Histogram:
[14457]502          // when a single histogram is updated, all histograms must be updated. otherwise the value ranges and bin sizes may not be equal.
503          var histograms = Content.Rows
504            .Where(r => r.VisualProperties.ChartType == DataRowVisualProperties.DataRowChartType.Histogram)
505            .ToList();
506          CalculateHistogram(series, row, histograms);
507          foreach (var h in from r in histograms
508                            where r != row
509                            let s = chart.Series.FindByName(r.Name)
510                            where s != null
511                            where !invisibleSeries.Contains(s)
512                            select new { row = r, series = s }) {
513            h.series.Points.Clear();
514            CalculateHistogram(h.series, h.row, histograms);
515          }
[6342]516          break;
517        default: {
[9258]518            bool yLogarithmic = series.YAxisType == AxisType.Primary
519                                  ? Content.VisualProperties.YAxisLogScale
520                                  : Content.VisualProperties.SecondYAxisLogScale;
521            bool xLogarithmic = series.XAxisType == AxisType.Primary
522                                  ? Content.VisualProperties.XAxisLogScale
523                                  : Content.VisualProperties.SecondXAxisLogScale;
[6342]524            for (int i = 0; i < row.Values.Count; i++) {
525              var value = row.Values[i];
[9258]526              var point = new DataPoint();
527              point.XValue = row.VisualProperties.StartIndexZero && !xLogarithmic ? i : i + 1;
528              if (IsInvalidValue(value) || (yLogarithmic && value <= 0))
[6342]529                point.IsEmpty = true;
530              else
531                point.YValues = new double[] { value };
532              series.Points.Add(point);
533            }
534          }
535          break;
[3703]536      }
537    }
538
[14457]539    protected virtual void CalculateHistogram(Series series, DataRow row, IEnumerable<DataRow> histogramRows) {
[6342]540      series.Points.Clear();
541      if (!row.Values.Any()) return;
542
[14508]543      var validValues = histogramRows.SelectMany(r => r.Values).Where(x => !IsInvalidValue(x)).ToList();
544      if (!validValues.Any()) return;
545
[14457]546      int bins = histogramRows.Max(r => r.VisualProperties.Bins);
[14508]547      decimal minValue = (decimal)validValues.Min();
548      decimal maxValue = (decimal)validValues.Max();
[14458]549      decimal intervalWidth = (maxValue - minValue) / bins;
[6342]550      if (intervalWidth < 0) return;
551      if (intervalWidth == 0) {
552        series.Points.AddXY(minValue, row.Values.Count);
553        return;
554      }
555
[14457]556      if (!histogramRows.Any(r => r.VisualProperties.ExactBins)) {
[14458]557        intervalWidth = (decimal)HumanRoundRange((double)intervalWidth);
[6342]558        minValue = Math.Floor(minValue / intervalWidth) * intervalWidth;
559        maxValue = Math.Ceiling(maxValue / intervalWidth) * intervalWidth;
560      }
561
[14458]562      decimal intervalCenter = intervalWidth / 2;
[7223]563
[14458]564      decimal min = 0.0m, max = 0.0m;
[6978]565      if (!Double.IsNaN(Content.VisualProperties.XAxisMinimumFixedValue) && !Content.VisualProperties.XAxisMinimumAuto)
[14458]566        min = (decimal)Content.VisualProperties.XAxisMinimumFixedValue;
[7223]567      else min = minValue;
[8339]568      if (!Double.IsNaN(Content.VisualProperties.XAxisMaximumFixedValue) && !Content.VisualProperties.XAxisMaximumAuto)
[14458]569        max = (decimal)Content.VisualProperties.XAxisMaximumFixedValue;
[8339]570      else max = maxValue + intervalWidth;
[6978]571
[14458]572      double axisInterval = (double)intervalWidth / row.VisualProperties.ScaleFactor;
[6978]573
[7223]574      var area = chart.ChartAreas[0];
575      area.AxisX.Interval = axisInterval;
[6978]576
[7223]577      series.SetCustomProperty("PointWidth", "1"); // 0.8 is the default value
578
579      // get the range or intervals which define the grouping of the frequency values
[14458]580      var range = Range(min, max, intervalWidth).Skip(1).ToList();
[7223]581
582      // aggregate the row values by unique key and frequency value
583      var valueFrequencies = (from v in row.Values
584                              where !IsInvalidValue(v)
585                              orderby v
586                              group v by v into g
587                              select new Tuple<double, double>(g.First(), g.Count())).ToList();
588
[14457]589      // ensure that each column is displayed completely on the chart by adding two dummy datapoints on the upper and lower range
[14458]590      series.Points.Add(new DataPoint((double)(min - intervalWidth), 0));
591      series.Points.Add(new DataPoint((double)(max + intervalWidth), 0));
[7223]592
593      // add data points
594      int j = 0;
[14458]595      foreach (var d in range) {
[7223]596        double sum = 0.0;
597        // sum the frequency values that fall within the same interval
[14458]598        while (j < valueFrequencies.Count && (decimal)valueFrequencies[j].Item1 < d) {
[7223]599          sum += valueFrequencies[j].Item2;
600          ++j;
[3703]601        }
[7304]602        string xAxisTitle = string.IsNullOrEmpty(Content.VisualProperties.XAxisTitle)
603                              ? "X"
604                              : Content.VisualProperties.XAxisTitle;
605        string yAxisTitle = string.IsNullOrEmpty(Content.VisualProperties.YAxisTitle)
606                              ? "Y"
607                              : Content.VisualProperties.YAxisTitle;
[14458]608        series.Points.Add(new DataPoint((double)(d - intervalCenter), sum) {
[7304]609          ToolTip =
610            xAxisTitle + ": [" + (d - intervalWidth) + "-" + d + ")" + Environment.NewLine +
611            yAxisTitle + ": " + sum
612        });
[3703]613      }
614    }
615
[6342]616    #region Helpers
[14458]617    public static IEnumerable<decimal> Range(decimal min, decimal max, decimal step) {
618      decimal i;
[7223]619      for (i = min; i <= max; i += step)
620        yield return i;
621
622      if (i != max + step)
623        yield return i;
624    }
625
[6342]626    protected void RemoveCustomPropertyIfExists(Series series, string property) {
627      if (series.IsCustomPropertySet(property)) series.DeleteCustomProperty(property);
628    }
[5097]629
[6342]630    private double HumanRoundRange(double range) {
631      double base10 = Math.Pow(10.0, Math.Floor(Math.Log10(range)));
632      double rounding = range / base10;
633      if (rounding <= 1.5) rounding = 1;
634      else if (rounding <= 2.25) rounding = 2;
635      else if (rounding <= 3.75) rounding = 2.5;
636      else if (rounding <= 7.5) rounding = 5;
637      else rounding = 10;
638      return rounding * base10;
639    }
640
641    private double HumanRoundMax(double max) {
642      double base10;
643      if (max > 0) base10 = Math.Pow(10.0, Math.Floor(Math.Log10(max)));
644      else base10 = Math.Pow(10.0, Math.Ceiling(Math.Log10(-max)));
645      double rounding = (max > 0) ? base10 : -base10;
646      while (rounding < max) rounding += base10;
647      return rounding;
648    }
649
650    private ChartDashStyle ConvertLineStyle(DataRowVisualProperties.DataRowLineStyle dataRowLineStyle) {
651      switch (dataRowLineStyle) {
652        case DataRowVisualProperties.DataRowLineStyle.Dash:
653          return ChartDashStyle.Dash;
654        case DataRowVisualProperties.DataRowLineStyle.DashDot:
655          return ChartDashStyle.DashDot;
656        case DataRowVisualProperties.DataRowLineStyle.DashDotDot:
657          return ChartDashStyle.DashDotDot;
658        case DataRowVisualProperties.DataRowLineStyle.Dot:
659          return ChartDashStyle.Dot;
660        case DataRowVisualProperties.DataRowLineStyle.NotSet:
661          return ChartDashStyle.NotSet;
662        case DataRowVisualProperties.DataRowLineStyle.Solid:
663          return ChartDashStyle.Solid;
664        default:
665          return ChartDashStyle.NotSet;
666      }
667    }
668
[5097]669    protected static bool IsInvalidValue(double x) {
[3530]670      return double.IsNaN(x) || x < (double)decimal.MinValue || x > (double)decimal.MaxValue;
671    }
[6342]672    #endregion
[2908]673  }
674}
Note: See TracBrowser for help on using the repository browser.