Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.Problems.Orienteering/HeuristicLab.Optimization.Views/3.3/RunCollectionViews/RunCollectionBoxPlotView.cs @ 12694

Last change on this file since 12694 was 12694, checked in by abeham, 9 years ago

#2208: merged trunk changes

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