Free cookie consent management tool by TermsFeed Policy Generator

source: branches/symbreg-factors-2650/HeuristicLab.Analysis.Views/3.3/DataTableControl.cs @ 14498

Last change on this file since 14498 was 14498, checked in by gkronber, 7 years ago

#2650: merged r14457:14494 from trunk to branch (resolving conflicts)

File size: 31.0 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2016 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;
29
30namespace HeuristicLab.Analysis.Views {
31  public partial class DataTableControl : UserControl {
32    protected List<Series> invisibleSeries;
33    protected Dictionary<IObservableList<double>, DataRow> valuesRowsTable;
34
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      }
46    }
47
48    public DataTableControl() {
49      InitializeComponent();
50      valuesRowsTable = new Dictionary<IObservableList<double>, DataRow>();
51      invisibleSeries = new List<Series>();
52      chart.CustomizeAllChartAreas();
53      chart.ChartAreas[0].CursorX.Interval = 1;
54      chart.ContextMenuStrip.Items.Add(configureToolStripMenuItem);
55    }
56
57    #region Event Handler Registration
58    protected virtual void DeregisterContentEvents() {
59      foreach (DataRow row in Content.Rows)
60        DeregisterDataRowEvents(row);
61      Content.VisualPropertiesChanged -= new EventHandler(Content_VisualPropertiesChanged);
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    }
67    protected virtual void RegisterContentEvents() {
68      Content.VisualPropertiesChanged += new EventHandler(Content_VisualPropertiesChanged);
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
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
97    protected virtual void OnContentChanged() {
98      invisibleSeries.Clear();
99      chart.Titles[0].Text = string.Empty;
100      chart.ChartAreas[0].AxisX.Title = string.Empty;
101      chart.ChartAreas[0].AxisY.Title = string.Empty;
102      chart.ChartAreas[0].AxisY2.Title = string.Empty;
103      chart.Series.Clear();
104      if (Content != null) {
105        chart.Titles[0].Text = Content.Name;
106        chart.Titles[0].Visible = !string.IsNullOrEmpty(Content.Name);
107        AddDataRows(Content.Rows);
108        ConfigureChartArea(chart.ChartAreas[0]);
109        RecalculateAxesScale(chart.ChartAreas[0]);
110      }
111    }
112
113    protected virtual void SetEnabledStateOfControls() {
114      chart.Enabled = Content != null;
115    }
116
117    public void ShowConfiguration() {
118      if (Content != null) {
119        using (var dialog = new DataTableVisualPropertiesDialog(Content)) {
120          dialog.ShowDialog(this);
121        }
122      } else MessageBox.Show("Nothing to configure.");
123    }
124    protected virtual void AddDataRows(IEnumerable<DataRow> rows) {
125      foreach (var row in rows) {
126        RegisterDataRowEvents(row);
127        var series = new Series(row.Name);
128        if (row.VisualProperties.DisplayName.Trim() != String.Empty) series.LegendText = row.VisualProperties.DisplayName;
129        else series.LegendText = row.Name;
130        ConfigureSeries(series, row);
131        FillSeriesWithRowValues(series, row);
132        chart.Series.Add(series);
133      }
134      ConfigureChartArea(chart.ChartAreas[0]);
135      RecalculateAxesScale(chart.ChartAreas[0]);
136      UpdateYCursorInterval();
137    }
138
139    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
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;
159      series.IsVisibleInLegend = row.VisualProperties.IsVisibleInLegend;
160
161      switch (row.VisualProperties.ChartType) {
162        case DataRowVisualProperties.DataRowChartType.Line:
163          series.ChartType = SeriesChartType.FastLine;
164          series.BorderWidth = row.VisualProperties.LineWidth;
165          series.BorderDashStyle = ConvertLineStyle(row.VisualProperties.LineStyle);
166          break;
167        case DataRowVisualProperties.DataRowChartType.Bars:
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          }
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;
182        case DataRowVisualProperties.DataRowChartType.Histogram:
183          series.ChartType = SeriesChartType.StackedColumn;
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;
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;
194        default:
195          series.ChartType = SeriesChartType.FastPoint;
196          break;
197      }
198      series.YAxisType = row.VisualProperties.SecondYAxis ? AxisType.Secondary : AxisType.Primary;
199      series.XAxisType = row.VisualProperties.SecondXAxis ? AxisType.Secondary : AxisType.Primary;
200      if (row.VisualProperties.DisplayName.Trim() != String.Empty) series.LegendText = row.VisualProperties.DisplayName;
201      else series.LegendText = row.Name;
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";
213    }
214
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;
218      chart.Titles[0].Text = Content.VisualProperties.Title;
219      chart.Titles[0].Visible = !string.IsNullOrEmpty(Content.VisualProperties.Title);
220
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;
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;
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;
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;
265    }
266
267    protected virtual void UpdateYCursorInterval() {
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();
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
284    #region Event Handlers
285    #region Content Event Handlers
286    private void Content_VisualPropertiesChanged(object sender, EventArgs e) {
287      if (InvokeRequired)
288        Invoke(new EventHandler(Content_VisualPropertiesChanged), sender, e);
289      else {
290        ConfigureChartArea(chart.ChartAreas[0]);
291        RecalculateAxesScale(chart.ChartAreas[0]); // axes min/max could have changed
292      }
293    }
294    #endregion
295    #region Rows Event Handlers
296    private void Rows_ItemsAdded(object sender, CollectionItemsChangedEventArgs<DataRow> e) {
297      if (InvokeRequired)
298        Invoke(new CollectionItemsChangedEventHandler<DataRow>(Rows_ItemsAdded), sender, e);
299      else {
300        AddDataRows(e.Items);
301      }
302    }
303    private void Rows_ItemsRemoved(object sender, CollectionItemsChangedEventArgs<DataRow> e) {
304      if (InvokeRequired)
305        Invoke(new CollectionItemsChangedEventHandler<DataRow>(Rows_ItemsRemoved), sender, e);
306      else {
307        RemoveDataRows(e.Items);
308      }
309    }
310    private void Rows_ItemsReplaced(object sender, CollectionItemsChangedEventArgs<DataRow> e) {
311      if (InvokeRequired)
312        Invoke(new CollectionItemsChangedEventHandler<DataRow>(Rows_ItemsReplaced), sender, e);
313      else {
314        RemoveDataRows(e.OldItems);
315        AddDataRows(e.Items);
316      }
317    }
318    private void Rows_CollectionReset(object sender, CollectionItemsChangedEventArgs<DataRow> e) {
319      if (InvokeRequired)
320        Invoke(new CollectionItemsChangedEventHandler<DataRow>(Rows_CollectionReset), sender, e);
321      else {
322        RemoveDataRows(e.OldItems);
323        AddDataRows(e.Items);
324      }
325    }
326    #endregion
327    #region Row Event Handlers
328    private void Row_VisualPropertiesChanged(object sender, EventArgs e) {
329      if (InvokeRequired)
330        Invoke(new EventHandler(Row_VisualPropertiesChanged), sender, e);
331      else {
332        DataRow row = (DataRow)sender;
333        Series series = chart.Series[row.Name];
334        series.Points.Clear();
335        ConfigureSeries(series, row);
336        FillSeriesWithRowValues(series, row);
337        RecalculateAxesScale(chart.ChartAreas[0]);
338      }
339    }
340    private void Row_NameChanged(object sender, EventArgs e) {
341      if (InvokeRequired)
342        Invoke(new EventHandler(Row_NameChanged), sender, e);
343      else {
344        DataRow row = (DataRow)sender;
345        chart.Series[row.Name].Name = row.Name;
346      }
347    }
348    #endregion
349    #region Values Event Handlers
350    private void Values_ItemsAdded(object sender, CollectionItemsChangedEventArgs<IndexedItem<double>> e) {
351      if (InvokeRequired)
352        Invoke(new CollectionItemsChangedEventHandler<IndexedItem<double>>(Values_ItemsAdded), sender, e);
353      else {
354        DataRow row = null;
355        valuesRowsTable.TryGetValue((IObservableList<double>)sender, out row);
356        if (row != null) {
357          Series rowSeries = chart.Series[row.Name];
358          if (!invisibleSeries.Contains(rowSeries)) {
359            rowSeries.Points.Clear();
360            FillSeriesWithRowValues(rowSeries, row);
361            RecalculateAxesScale(chart.ChartAreas[0]);
362            UpdateYCursorInterval();
363          }
364        }
365      }
366    }
367    private void Values_ItemsRemoved(object sender, CollectionItemsChangedEventArgs<IndexedItem<double>> e) {
368      if (InvokeRequired)
369        Invoke(new CollectionItemsChangedEventHandler<IndexedItem<double>>(Values_ItemsRemoved), sender, e);
370      else {
371        DataRow row = null;
372        valuesRowsTable.TryGetValue((IObservableList<double>)sender, out row);
373        if (row != null) {
374          Series rowSeries = chart.Series[row.Name];
375          if (!invisibleSeries.Contains(rowSeries)) {
376            rowSeries.Points.Clear();
377            FillSeriesWithRowValues(rowSeries, row);
378            RecalculateAxesScale(chart.ChartAreas[0]);
379            UpdateYCursorInterval();
380          }
381        }
382      }
383    }
384    private void Values_ItemsReplaced(object sender, CollectionItemsChangedEventArgs<IndexedItem<double>> e) {
385      if (InvokeRequired)
386        Invoke(new CollectionItemsChangedEventHandler<IndexedItem<double>>(Values_ItemsReplaced), sender, e);
387      else {
388        DataRow row = null;
389        valuesRowsTable.TryGetValue((IObservableList<double>)sender, out row);
390        if (row != null) {
391          Series rowSeries = chart.Series[row.Name];
392          if (!invisibleSeries.Contains(rowSeries)) {
393            if (row.VisualProperties.ChartType == DataRowVisualProperties.DataRowChartType.Histogram) {
394              rowSeries.Points.Clear();
395              FillSeriesWithRowValues(rowSeries, row);
396            } else {
397              foreach (IndexedItem<double> item in e.Items) {
398                if (IsInvalidValue(item.Value))
399                  rowSeries.Points[item.Index].IsEmpty = true;
400                else {
401                  rowSeries.Points[item.Index].YValues = new double[] { item.Value };
402                  rowSeries.Points[item.Index].IsEmpty = false;
403                }
404              }
405            }
406            RecalculateAxesScale(chart.ChartAreas[0]);
407            UpdateYCursorInterval();
408          }
409        }
410      }
411    }
412    private void Values_ItemsMoved(object sender, CollectionItemsChangedEventArgs<IndexedItem<double>> e) {
413      if (InvokeRequired)
414        Invoke(new CollectionItemsChangedEventHandler<IndexedItem<double>>(Values_ItemsMoved), sender, e);
415      else {
416        DataRow row = null;
417        valuesRowsTable.TryGetValue((IObservableList<double>)sender, out row);
418        if (row != null) {
419          Series rowSeries = chart.Series[row.Name];
420          if (!invisibleSeries.Contains(rowSeries)) {
421            rowSeries.Points.Clear();
422            FillSeriesWithRowValues(rowSeries, row);
423            RecalculateAxesScale(chart.ChartAreas[0]);
424            UpdateYCursorInterval();
425          }
426        }
427      }
428    }
429
430    private void Values_CollectionReset(object sender, CollectionItemsChangedEventArgs<IndexedItem<double>> e) {
431      if (InvokeRequired)
432        Invoke(new CollectionItemsChangedEventHandler<IndexedItem<double>>(Values_CollectionReset), sender, e);
433      else {
434        DataRow row = null;
435        valuesRowsTable.TryGetValue((IObservableList<double>)sender, out row);
436        if (row != null) {
437          Series rowSeries = chart.Series[row.Name];
438          if (!invisibleSeries.Contains(rowSeries)) {
439            rowSeries.Points.Clear();
440            FillSeriesWithRowValues(rowSeries, row);
441            RecalculateAxesScale(chart.ChartAreas[0]);
442            UpdateYCursorInterval();
443          }
444        }
445      }
446    }
447    #endregion
448    private void configureToolStripMenuItem_Click(object sender, EventArgs e) {
449      ShowConfiguration();
450    }
451    #endregion
452
453    #region Chart Event Handlers
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    }
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
479
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;
493          RecalculateAxesScale(chart.ChartAreas[0]);
494          UpdateYCursorInterval();
495        }
496      }
497    }
498
499    private void FillSeriesWithRowValues(Series series, DataRow row) {
500      switch (row.VisualProperties.ChartType) {
501        case DataRowVisualProperties.DataRowChartType.Histogram:
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          }
516          break;
517        default: {
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;
524            for (int i = 0; i < row.Values.Count; i++) {
525              var value = row.Values[i];
526              var point = new DataPoint();
527              point.XValue = row.VisualProperties.StartIndexZero && !xLogarithmic ? i : i + 1;
528              if (IsInvalidValue(value) || (yLogarithmic && value <= 0))
529                point.IsEmpty = true;
530              else
531                point.YValues = new double[] { value };
532              series.Points.Add(point);
533            }
534          }
535          break;
536      }
537    }
538
539    protected virtual void CalculateHistogram(Series series, DataRow row, IEnumerable<DataRow> histogramRows) {
540      series.Points.Clear();
541      if (!row.Values.Any()) return;
542
543      int bins = histogramRows.Max(r => r.VisualProperties.Bins);
544      decimal minValue = (decimal)histogramRows.Min(r => r.Values.Min());
545      decimal maxValue = (decimal)histogramRows.Max(r => r.Values.Max());
546      decimal intervalWidth = (maxValue - minValue) / bins;
547      if (intervalWidth < 0) return;
548      if (intervalWidth == 0) {
549        series.Points.AddXY(minValue, row.Values.Count);
550        return;
551      }
552
553      if (!histogramRows.Any(r => r.VisualProperties.ExactBins)) {
554        intervalWidth = (decimal)HumanRoundRange((double)intervalWidth);
555        minValue = Math.Floor(minValue / intervalWidth) * intervalWidth;
556        maxValue = Math.Ceiling(maxValue / intervalWidth) * intervalWidth;
557      }
558
559      decimal intervalCenter = intervalWidth / 2;
560
561      decimal min = 0.0m, max = 0.0m;
562      if (!Double.IsNaN(Content.VisualProperties.XAxisMinimumFixedValue) && !Content.VisualProperties.XAxisMinimumAuto)
563        min = (decimal)Content.VisualProperties.XAxisMinimumFixedValue;
564      else min = minValue;
565      if (!Double.IsNaN(Content.VisualProperties.XAxisMaximumFixedValue) && !Content.VisualProperties.XAxisMaximumAuto)
566        max = (decimal)Content.VisualProperties.XAxisMaximumFixedValue;
567      else max = maxValue + intervalWidth;
568
569      double axisInterval = (double)intervalWidth / row.VisualProperties.ScaleFactor;
570
571      var area = chart.ChartAreas[0];
572      area.AxisX.Interval = axisInterval;
573
574      series.SetCustomProperty("PointWidth", "1"); // 0.8 is the default value
575
576      // get the range or intervals which define the grouping of the frequency values
577      var range = Range(min, max, intervalWidth).Skip(1).ToList();
578
579      // aggregate the row values by unique key and frequency value
580      var valueFrequencies = (from v in row.Values
581                              where !IsInvalidValue(v)
582                              orderby v
583                              group v by v into g
584                              select new Tuple<double, double>(g.First(), g.Count())).ToList();
585
586      // ensure that each column is displayed completely on the chart by adding two dummy datapoints on the upper and lower range
587      series.Points.Add(new DataPoint((double)(min - intervalWidth), 0));
588      series.Points.Add(new DataPoint((double)(max + intervalWidth), 0));
589
590      // add data points
591      int j = 0;
592      foreach (var d in range) {
593        double sum = 0.0;
594        // sum the frequency values that fall within the same interval
595        while (j < valueFrequencies.Count && (decimal)valueFrequencies[j].Item1 < d) {
596          sum += valueFrequencies[j].Item2;
597          ++j;
598        }
599        string xAxisTitle = string.IsNullOrEmpty(Content.VisualProperties.XAxisTitle)
600                              ? "X"
601                              : Content.VisualProperties.XAxisTitle;
602        string yAxisTitle = string.IsNullOrEmpty(Content.VisualProperties.YAxisTitle)
603                              ? "Y"
604                              : Content.VisualProperties.YAxisTitle;
605        series.Points.Add(new DataPoint((double)(d - intervalCenter), sum) {
606          ToolTip =
607            xAxisTitle + ": [" + (d - intervalWidth) + "-" + d + ")" + Environment.NewLine +
608            yAxisTitle + ": " + sum
609        });
610      }
611    }
612
613    #region Helpers
614    public static IEnumerable<decimal> Range(decimal min, decimal max, decimal step) {
615      decimal i;
616      for (i = min; i <= max; i += step)
617        yield return i;
618
619      if (i != max + step)
620        yield return i;
621    }
622
623    protected void RemoveCustomPropertyIfExists(Series series, string property) {
624      if (series.IsCustomPropertySet(property)) series.DeleteCustomProperty(property);
625    }
626
627    private double HumanRoundRange(double range) {
628      double base10 = Math.Pow(10.0, Math.Floor(Math.Log10(range)));
629      double rounding = range / base10;
630      if (rounding <= 1.5) rounding = 1;
631      else if (rounding <= 2.25) rounding = 2;
632      else if (rounding <= 3.75) rounding = 2.5;
633      else if (rounding <= 7.5) rounding = 5;
634      else rounding = 10;
635      return rounding * base10;
636    }
637
638    private double HumanRoundMax(double max) {
639      double base10;
640      if (max > 0) base10 = Math.Pow(10.0, Math.Floor(Math.Log10(max)));
641      else base10 = Math.Pow(10.0, Math.Ceiling(Math.Log10(-max)));
642      double rounding = (max > 0) ? base10 : -base10;
643      while (rounding < max) rounding += base10;
644      return rounding;
645    }
646
647    private ChartDashStyle ConvertLineStyle(DataRowVisualProperties.DataRowLineStyle dataRowLineStyle) {
648      switch (dataRowLineStyle) {
649        case DataRowVisualProperties.DataRowLineStyle.Dash:
650          return ChartDashStyle.Dash;
651        case DataRowVisualProperties.DataRowLineStyle.DashDot:
652          return ChartDashStyle.DashDot;
653        case DataRowVisualProperties.DataRowLineStyle.DashDotDot:
654          return ChartDashStyle.DashDotDot;
655        case DataRowVisualProperties.DataRowLineStyle.Dot:
656          return ChartDashStyle.Dot;
657        case DataRowVisualProperties.DataRowLineStyle.NotSet:
658          return ChartDashStyle.NotSet;
659        case DataRowVisualProperties.DataRowLineStyle.Solid:
660          return ChartDashStyle.Solid;
661        default:
662          return ChartDashStyle.NotSet;
663      }
664    }
665
666    protected static bool IsInvalidValue(double x) {
667      return double.IsNaN(x) || x < (double)decimal.MinValue || x > (double)decimal.MaxValue;
668    }
669    #endregion
670  }
671}
Note: See TracBrowser for help on using the repository browser.