Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Optimization.Views/3.3/RunCollectionViews/RunCollectionBoxPlotView.cs @ 9235

Last change on this file since 9235 was 9235, checked in by mkommend, 12 years ago

#2016: Implemented changes in BubbleChart and BoxPlots to improve the coloring and the display of categorical values.

File size: 18.7 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2012 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.Linq;
25using System.Windows.Forms;
26using System.Windows.Forms.DataVisualization.Charting;
27using HeuristicLab.Common;
28using HeuristicLab.Core;
29using HeuristicLab.Data;
30using HeuristicLab.MainForm;
31using HeuristicLab.MainForm.WindowsForms;
32
33namespace HeuristicLab.Optimization.Views {
34  [View("RunCollection BoxPlots")]
35  [Content(typeof(RunCollection), false)]
36  public partial class RunCollectionBoxPlotView : AsynchronousContentView {
37    private enum AxisDimension { Color = 0 }
38    private const string BoxPlotSeriesName = "BoxPlotSeries";
39    private const string BoxPlotChartAreaName = "BoxPlotChartArea";
40
41    private bool suppressUpdates = false;
42    private string xAxisValue;
43    private string yAxisValue;
44    private Dictionary<int, Dictionary<object, double>> categoricalMapping;
45    private SortedDictionary<double, Series> seriesCache;
46
47    public RunCollectionBoxPlotView() {
48      InitializeComponent();
49      categoricalMapping = new Dictionary<int, Dictionary<object, double>>();
50      seriesCache = new SortedDictionary<double, Series>();
51      chart.ChartAreas[0].Visible = false;
52      chart.Series.Clear();
53      chart.ChartAreas.Add(BoxPlotChartAreaName);
54      chart.CustomizeAllChartAreas();
55      chart.ChartAreas[BoxPlotChartAreaName].Axes.ToList().ForEach(x => { x.ScaleView.Zoomable = true; x.ScaleView.MinSize = 0; });
56      chart.ChartAreas[BoxPlotChartAreaName].CursorX.Interval = 0.5;
57      chart.ChartAreas[BoxPlotChartAreaName].CursorY.Interval = 1e-5;
58    }
59
60    public new RunCollection Content {
61      get { return (RunCollection)base.Content; }
62      set { base.Content = value; }
63    }
64    public IStringConvertibleMatrix Matrix {
65      get { return this.Content; }
66    }
67
68    #region RunCollection and Run events
69    protected override void RegisterContentEvents() {
70      base.RegisterContentEvents();
71      Content.Reset += new EventHandler(Content_Reset);
72      Content.ColumnNamesChanged += new EventHandler(Content_ColumnNamesChanged);
73      Content.ItemsAdded += new HeuristicLab.Collections.CollectionItemsChangedEventHandler<IRun>(Content_ItemsAdded);
74      Content.ItemsRemoved += new HeuristicLab.Collections.CollectionItemsChangedEventHandler<IRun>(Content_ItemsRemoved);
75      Content.CollectionReset += new HeuristicLab.Collections.CollectionItemsChangedEventHandler<IRun>(Content_CollectionReset);
76      Content.UpdateOfRunsInProgressChanged += new EventHandler(Content_UpdateOfRunsInProgressChanged);
77      Content.OptimizerNameChanged += new EventHandler(Content_AlgorithmNameChanged);
78      RegisterRunEvents(Content);
79    }
80    protected override void DeregisterContentEvents() {
81      base.DeregisterContentEvents();
82      Content.Reset -= new EventHandler(Content_Reset);
83      Content.ColumnNamesChanged -= new EventHandler(Content_ColumnNamesChanged);
84      Content.ItemsAdded -= new HeuristicLab.Collections.CollectionItemsChangedEventHandler<IRun>(Content_ItemsAdded);
85      Content.ItemsRemoved -= new HeuristicLab.Collections.CollectionItemsChangedEventHandler<IRun>(Content_ItemsRemoved);
86      Content.CollectionReset -= new HeuristicLab.Collections.CollectionItemsChangedEventHandler<IRun>(Content_CollectionReset);
87      Content.UpdateOfRunsInProgressChanged -= new EventHandler(Content_UpdateOfRunsInProgressChanged);
88      Content.OptimizerNameChanged -= new EventHandler(Content_AlgorithmNameChanged);
89      DeregisterRunEvents(Content);
90    }
91
92    protected virtual void RegisterRunEvents(IEnumerable<IRun> runs) {
93      foreach (IRun run in runs)
94        run.Changed += new EventHandler(run_Changed);
95    }
96    protected virtual void DeregisterRunEvents(IEnumerable<IRun> runs) {
97      foreach (IRun run in runs)
98        run.Changed -= new EventHandler(run_Changed);
99    }
100
101    private void Content_CollectionReset(object sender, HeuristicLab.Collections.CollectionItemsChangedEventArgs<IRun> e) {
102      DeregisterRunEvents(e.OldItems);
103      RegisterRunEvents(e.Items);
104    }
105    private void Content_ItemsRemoved(object sender, HeuristicLab.Collections.CollectionItemsChangedEventArgs<IRun> e) {
106      DeregisterRunEvents(e.Items);
107    }
108    private void Content_ItemsAdded(object sender, HeuristicLab.Collections.CollectionItemsChangedEventArgs<IRun> e) {
109      RegisterRunEvents(e.Items);
110    }
111    private void Content_UpdateOfRunsInProgressChanged(object sender, EventArgs e) {
112      if (InvokeRequired)
113        Invoke(new EventHandler(Content_UpdateOfRunsInProgressChanged), sender, e);
114      else {
115        suppressUpdates = Content.UpdateOfRunsInProgress;
116        if (!suppressUpdates) UpdateDataPoints();
117      }
118    }
119
120    private void Content_Reset(object sender, EventArgs e) {
121      if (InvokeRequired)
122        Invoke(new EventHandler(Content_Reset), sender, e);
123      else {
124        this.categoricalMapping.Clear();
125        UpdateDataPoints();
126        UpdateAxisLabels();
127      }
128    }
129    private void Content_ColumnNamesChanged(object sender, EventArgs e) {
130      if (InvokeRequired)
131        Invoke(new EventHandler(Content_ColumnNamesChanged), sender, e);
132      else {
133        UpdateComboBoxes();
134      }
135    }
136    private void run_Changed(object sender, EventArgs e) {
137      if (InvokeRequired)
138        this.Invoke(new EventHandler(run_Changed), sender, e);
139      else if (!suppressUpdates) {
140        IRun run = (IRun)sender;
141        UpdateDataPoints();
142      }
143    }
144
145    private void Content_AlgorithmNameChanged(object sender, EventArgs e) {
146      if (InvokeRequired)
147        Invoke(new EventHandler(Content_AlgorithmNameChanged), sender, e);
148      else UpdateCaption();
149    }
150    #endregion
151
152    #region update comboboxes, datapoints, runs
153    protected override void OnContentChanged() {
154      base.OnContentChanged();
155      this.categoricalMapping.Clear();
156      UpdateComboBoxes();
157      UpdateDataPoints();
158      UpdateCaption();
159    }
160
161    private void UpdateCaption() {
162      Caption = Content != null ? Content.OptimizerName + " Box Plots" : ViewAttribute.GetViewName(GetType());
163    }
164
165    private void UpdateComboBoxes() {
166      string selectedXAxis = (string)this.xAxisComboBox.SelectedItem;
167      string selectedYAxis = (string)this.yAxisComboBox.SelectedItem;
168      this.xAxisComboBox.Items.Clear();
169      this.yAxisComboBox.Items.Clear();
170      if (Content != null) {
171        string[] additionalAxisDimension = Enum.GetNames(typeof(AxisDimension));
172        this.xAxisComboBox.Items.AddRange(additionalAxisDimension);
173        this.xAxisComboBox.Items.AddRange(Matrix.ColumnNames.ToArray());
174        this.yAxisComboBox.Items.AddRange(additionalAxisDimension);
175        this.yAxisComboBox.Items.AddRange(Matrix.ColumnNames.ToArray());
176
177        bool changed = false;
178        if (selectedXAxis != null && xAxisComboBox.Items.Contains(selectedXAxis)) {
179          xAxisComboBox.SelectedItem = selectedXAxis;
180          changed = true;
181        }
182        if (selectedYAxis != null && yAxisComboBox.Items.Contains(selectedYAxis)) {
183          yAxisComboBox.SelectedItem = selectedYAxis;
184          changed = true;
185        }
186        if (changed)
187          UpdateDataPoints();
188      }
189    }
190
191    private void UpdateDataPoints() {
192      this.chart.Series.Clear();
193      this.seriesCache.Clear();
194      if (Content != null) {
195        foreach (IRun run in this.Content.Where(r => r.Visible))
196          this.AddDataPoint(run);
197        foreach (Series s in this.seriesCache.Values)
198          this.chart.Series.Add(s);
199
200        UpdateStatistics();
201        if (seriesCache.Count > 0) {
202          Series boxPlotSeries = CreateBoxPlotSeries();
203          this.chart.Series.Add(boxPlotSeries);
204        }
205
206        UpdateAxisLabels();
207      }
208      UpdateNoRunsVisibleLabel();
209    }
210
211    private void UpdateStatistics() {
212      DoubleMatrix matrix = new DoubleMatrix(9, seriesCache.Count);
213      matrix.SortableView = false;
214      List<string> columnNames = new List<string>();
215      foreach (Series series in seriesCache.Values) {
216        DataPoint datapoint = series.Points.FirstOrDefault();
217        if (datapoint != null) {
218          IRun run = (IRun)datapoint.Tag;
219          string selectedAxis = (string)xAxisComboBox.SelectedItem;
220          IItem value = null;
221
222          if (Enum.IsDefined(typeof(AxisDimension), selectedAxis)) {
223            AxisDimension axisDimension = (AxisDimension)Enum.Parse(typeof(AxisDimension), selectedAxis);
224            switch (axisDimension) {
225              case AxisDimension.Color: value = new StringValue(run.Color.ToString());
226                break;
227            }
228          } else value = Content.GetValue(run, selectedAxis);
229          string columnName = string.Empty;
230          if (value is DoubleValue || value is IntValue)
231            columnName = selectedAxis + ": ";
232          columnName += value.ToString();
233          columnNames.Add(columnName);
234        }
235      }
236      matrix.ColumnNames = columnNames;
237      matrix.RowNames = new string[] { "Count", "Minimum", "Maximum", "Average", "Median", "Standard Deviation", "Variance", "25th Percentile", "75th Percentile" };
238
239      for (int i = 0; i < seriesCache.Count; i++) {
240        Series series = seriesCache.ElementAt(i).Value;
241        double[] seriesValues = series.Points.Select(p => p.YValues[0]).OrderBy(d => d).ToArray();
242        matrix[0, i] = seriesValues.Length;
243        matrix[1, i] = seriesValues.Min();
244        matrix[2, i] = seriesValues.Max();
245        matrix[3, i] = seriesValues.Average();
246        matrix[4, i] = seriesValues.Median();
247        matrix[5, i] = seriesValues.StandardDeviation();
248        matrix[6, i] = seriesValues.Variance();
249        matrix[7, i] = seriesValues.Percentile(0.25);
250        matrix[8, i] = seriesValues.Percentile(0.75);
251      }
252      statisticsMatrixView.Content = matrix;
253    }
254
255    private Series CreateBoxPlotSeries() {
256      Series boxPlotSeries = new Series(BoxPlotSeriesName);
257      string seriesNames = string.Concat(seriesCache.Keys.Select(x => x.ToString() + ";").ToArray());
258      seriesNames = seriesNames.Remove(seriesNames.Length - 1); //delete last ; from string
259
260      boxPlotSeries.ChartArea = BoxPlotChartAreaName;
261      boxPlotSeries.ChartType = SeriesChartType.BoxPlot;
262      boxPlotSeries["BoxPlotSeries"] = seriesNames;
263      boxPlotSeries["BoxPlotShowUnusualValues"] = "true";
264      boxPlotSeries["PointWidth"] = "0.4";
265      boxPlotSeries.BackGradientStyle = System.Windows.Forms.DataVisualization.Charting.GradientStyle.VerticalCenter;
266      boxPlotSeries.BackSecondaryColor = System.Drawing.Color.FromArgb(130, 224, 64, 10);
267      boxPlotSeries.BorderColor = System.Drawing.Color.FromArgb(64, 64, 64);
268      boxPlotSeries.Color = System.Drawing.Color.FromArgb(224, 64, 10);
269
270      return boxPlotSeries;
271    }
272
273    private void AddDataPoint(IRun run) {
274      double? xValue;
275      double? yValue;
276
277      if (!xAxisComboBox.DroppedDown)
278        this.xAxisValue = (string)xAxisComboBox.SelectedItem;
279      if (!yAxisComboBox.DroppedDown)
280        this.yAxisValue = (string)yAxisComboBox.SelectedItem;
281
282      xValue = GetValue(run, this.xAxisValue);
283      yValue = GetValue(run, this.yAxisValue);
284
285      if (xValue.HasValue && yValue.HasValue) {
286        if (!this.seriesCache.ContainsKey(xValue.Value))
287          seriesCache[xValue.Value] = new Series(xValue.Value.ToString());
288
289        Series series = seriesCache[xValue.Value];
290        DataPoint point = new DataPoint(xValue.Value, yValue.Value);
291        point.Tag = run;
292        series.Points.Add(point);
293      }
294    }
295    #endregion
296
297    #region get values from run
298    private double? GetValue(IRun run, string columnName) {
299      if (run == null || string.IsNullOrEmpty(columnName))
300        return null;
301
302      if (Enum.IsDefined(typeof(AxisDimension), columnName)) {
303        AxisDimension axisDimension = (AxisDimension)Enum.Parse(typeof(AxisDimension), columnName);
304        return GetValue(run, axisDimension);
305      } else {
306        int columnIndex = Matrix.ColumnNames.ToList().IndexOf(columnName);
307        IItem value = Content.GetValue(run, columnIndex);
308        if (value == null)
309          return null;
310
311        DoubleValue doubleValue = value as DoubleValue;
312        IntValue intValue = value as IntValue;
313        TimeSpanValue timeSpanValue = value as TimeSpanValue;
314        double? ret = null;
315        if (doubleValue != null) {
316          if (!double.IsNaN(doubleValue.Value) && !double.IsInfinity(doubleValue.Value))
317            ret = doubleValue.Value;
318        } else if (intValue != null)
319          ret = intValue.Value;
320        else if (timeSpanValue != null) {
321          ret = timeSpanValue.Value.TotalSeconds;
322        } else
323          ret = GetCategoricalValue(columnIndex, value.ToString());
324
325        return ret;
326      }
327    }
328    private double GetCategoricalValue(int dimension, string value) {
329      if (!this.categoricalMapping.ContainsKey(dimension)) {
330        this.categoricalMapping[dimension] = new Dictionary<object, double>();
331        var orderedCategories = Content.Select(r => Content.GetValue(r, dimension).ToString())
332                                .Distinct()
333                                .OrderBy(x => x, new NaturalStringComparer());
334        int count = 1;
335        foreach (var category in orderedCategories) {
336          this.categoricalMapping[dimension].Add(category, count);
337          count++;
338        }
339      }
340      return this.categoricalMapping[dimension][value];
341    }
342    private double GetValue(IRun run, AxisDimension axisDimension) {
343      double value = double.NaN;
344      switch (axisDimension) {
345        case AxisDimension.Color: {
346            value = GetCategoricalValue(-1, run.Color.ToString());
347            break;
348          }
349        default: {
350            throw new ArgumentException("No handling strategy for " + axisDimension.ToString() + " is defined.");
351          }
352      }
353      return value;
354    }
355    #endregion
356
357    #region GUI events
358    private void UpdateNoRunsVisibleLabel() {
359      if (this.chart.Series.Count > 0) {
360        noRunsLabel.Visible = false;
361        showStatisticsCheckBox.Enabled = true;
362        splitContainer.Panel2Collapsed = !showStatisticsCheckBox.Checked;
363      } else {
364        noRunsLabel.Visible = true;
365        showStatisticsCheckBox.Enabled = false;
366        splitContainer.Panel2Collapsed = true;
367      }
368    }
369
370    private void AxisComboBox_SelectedIndexChanged(object sender, EventArgs e) {
371      UpdateDataPoints();
372    }
373    private void UpdateAxisLabels() {
374      Axis xAxis = this.chart.ChartAreas[BoxPlotChartAreaName].AxisX;
375      Axis yAxis = this.chart.ChartAreas[BoxPlotChartAreaName].AxisY;
376      int axisDimensionCount = Enum.GetNames(typeof(AxisDimension)).Count();
377      SetCustomAxisLabels(xAxis, xAxisComboBox.SelectedIndex - axisDimensionCount);
378      SetCustomAxisLabels(yAxis, yAxisComboBox.SelectedIndex - axisDimensionCount);
379      if (xAxisComboBox.SelectedItem != null)
380        xAxis.Title = xAxisComboBox.SelectedItem.ToString();
381      if (yAxisComboBox.SelectedItem != null)
382        yAxis.Title = yAxisComboBox.SelectedItem.ToString();
383    }
384
385    private void chart_AxisViewChanged(object sender, System.Windows.Forms.DataVisualization.Charting.ViewEventArgs e) {
386      this.UpdateAxisLabels();
387    }
388
389    private void SetCustomAxisLabels(Axis axis, int dimension) {
390      axis.CustomLabels.Clear();
391      if (categoricalMapping.ContainsKey(dimension)) {
392        foreach (var pair in categoricalMapping[dimension]) {
393          string labelText = pair.Key.ToString();
394          CustomLabel label = new CustomLabel();
395          label.ToolTip = labelText;
396          if (labelText.Length > 25)
397            labelText = labelText.Substring(0, 25) + " ... ";
398          label.Text = labelText;
399          label.GridTicks = GridTickTypes.TickMark;
400          label.FromPosition = pair.Value - 0.5;
401          label.ToPosition = pair.Value + 0.5;
402          axis.CustomLabels.Add(label);
403        }
404      } else if (dimension > 0 && Content.GetValue(0, dimension) is TimeSpanValue) {
405        this.chart.ChartAreas[0].RecalculateAxesScale();
406        Axis correspondingAxis = this.chart.ChartAreas[0].Axes.Where(x => x.Name == axis.Name).SingleOrDefault();
407        if (correspondingAxis == null)
408          correspondingAxis = axis;
409        for (double i = correspondingAxis.Minimum; i <= correspondingAxis.Maximum; i += correspondingAxis.LabelStyle.Interval) {
410          TimeSpan time = TimeSpan.FromSeconds(i);
411          string x = string.Format("{0:00}:{1:00}:{2:00}", (int)time.Hours, time.Minutes, time.Seconds);
412          axis.CustomLabels.Add(i - correspondingAxis.LabelStyle.Interval / 2, i + correspondingAxis.LabelStyle.Interval / 2, x);
413        }
414      } else if (chart.ChartAreas[BoxPlotChartAreaName].AxisX == axis) {
415        double position = 1.0;
416        foreach (Series series in chart.Series) {
417          if (series.Name != BoxPlotSeriesName) {
418            string labelText = series.Points[0].XValue.ToString();
419            CustomLabel label = new CustomLabel();
420            label.FromPosition = position - 0.5;
421            label.ToPosition = position + 0.5;
422            label.GridTicks = GridTickTypes.TickMark;
423            label.Text = labelText;
424            axis.CustomLabels.Add(label);
425            position++;
426          }
427        }
428      }
429    }
430
431    private void chart_MouseMove(object sender, MouseEventArgs e) {
432      string newTooltipText = string.Empty;
433      string oldTooltipText;
434      HitTestResult h = this.chart.HitTest(e.X, e.Y);
435      if (h.ChartElementType == ChartElementType.AxisLabels) {
436        newTooltipText = ((CustomLabel)h.Object).ToolTip;
437      }
438
439      oldTooltipText = this.tooltip.GetToolTip(chart);
440      if (newTooltipText != oldTooltipText)
441        this.tooltip.SetToolTip(chart, newTooltipText);
442    }
443    #endregion
444
445    private void showStatisticsCheckBox_CheckedChanged(object sender, EventArgs e) {
446      splitContainer.Panel2Collapsed = !showStatisticsCheckBox.Checked;
447    }
448
449  }
450}
Note: See TracBrowser for help on using the repository browser.