Free cookie consent management tool by TermsFeed Policy Generator

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

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

#2713 Added new ToolStripMenuItem to the chart for DataTableView and ScatterPlotView to open the configuration dialog.

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