Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Optimization.Views/3.3/RunCollectionViews/RunCollectionBubbleChartView.cs @ 14889

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

#2779: added a solution view which uses the bubblechart for interactive visualization of model residuals. (HACK)

File size: 37.2 KB
RevLine 
[3349]1#region License Information
2/* HeuristicLab
[14185]3 * Copyright (C) 2002-2016 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
[3349]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;
[11344]24using System.ComponentModel;
[3349]25using System.Drawing;
26using System.Linq;
27using System.Windows.Forms;
28using System.Windows.Forms.DataVisualization.Charting;
[9229]29using HeuristicLab.Common;
30using HeuristicLab.Core;
31using HeuristicLab.Data;
32using HeuristicLab.MainForm;
33using HeuristicLab.MainForm.WindowsForms;
[3349]34
35namespace HeuristicLab.Optimization.Views {
[9910]36  [View("Bubble Chart")]
[3349]37  [Content(typeof(RunCollection), false)]
38  public partial class RunCollectionBubbleChartView : AsynchronousContentView {
[3524]39    private enum SizeDimension { Constant = 0 }
40    private enum AxisDimension { Index = 0 }
41
[3726]42    private string xAxisValue;
43    private string yAxisValue;
44    private string sizeAxisValue;
45
[9312]46    private readonly Dictionary<IRun, List<DataPoint>> runToDataPointMapping = new Dictionary<IRun, List<DataPoint>>();
47    private readonly Dictionary<IRun, int> runToIndexMapping = new Dictionary<IRun, int>();
48    private readonly Dictionary<int, Dictionary<object, double>> categoricalMapping = new Dictionary<int, Dictionary<object, double>>();
49    private readonly Dictionary<IRun, double> xJitter = new Dictionary<IRun, double>();
50    private readonly Dictionary<IRun, double> yJitter = new Dictionary<IRun, double>();
51
52    private readonly HashSet<IRun> selectedRuns = new HashSet<IRun>();
53    private readonly Random random = new Random();
[3411]54    private double xJitterFactor = 0.0;
55    private double yJitterFactor = 0.0;
56    private bool isSelecting = false;
[4883]57    private bool suppressUpdates = false;
[3349]58
[11007]59    private readonly RunCollectionContentConstraint visibilityConstraint = new RunCollectionContentConstraint() { Active = true };
[9435]60
[3349]61    public RunCollectionBubbleChartView() {
62      InitializeComponent();
[3411]63
[9435]64      chart.ContextMenuStrip.Items.Insert(0, openBoxPlotViewToolStripMenuItem);
65      chart.ContextMenuStrip.Items.Insert(1, getDataAsMatrixToolStripMenuItem);
66      chart.ContextMenuStrip.Items.Insert(2, new ToolStripSeparator());
67      chart.ContextMenuStrip.Items.Insert(3, hideRunsToolStripMenuItem);
68      chart.ContextMenuStrip.Items.Insert(4, unhideAllRunToolStripMenuItem);
69      chart.ContextMenuStrip.Items.Insert(5, colorResetToolStripMenuItem);
70      chart.ContextMenuStrip.Items.Insert(6, new ToolStripSeparator());
[6673]71      chart.ContextMenuStrip.Opening += new System.ComponentModel.CancelEventHandler(ContextMenuStrip_Opening);
72
[9435]73      colorDialog.Color = Color.Orange;
74      colorRunsButton.Image = this.GenerateImage(16, 16, this.colorDialog.Color);
[4635]75      isSelecting = false;
[4846]76
[4636]77      chart.CustomizeAllChartAreas();
[4635]78      chart.ChartAreas[0].CursorX.Interval = 1;
79      chart.ChartAreas[0].CursorY.Interval = 1;
80      chart.ChartAreas[0].AxisX.ScaleView.Zoomable = !this.isSelecting;
81      chart.ChartAreas[0].AxisY.ScaleView.Zoomable = !this.isSelecting;
[3349]82    }
83
84    public new RunCollection Content {
85      get { return (RunCollection)base.Content; }
86      set { base.Content = value; }
87    }
[3447]88    public IStringConvertibleMatrix Matrix {
89      get { return this.Content; }
90    }
[9312]91    public IEnumerable<IRun> SelectedRuns {
92      get { return selectedRuns; }
93    }
[3447]94
[14889]95    public string SelectedXAxis {
96      get { return xAxisValue; }
97      set {
98        if (xAxisComboBox.Items.Contains(value)) {
99          xAxisComboBox.SelectedItem = value;
100        }
101      }
102    }
103    public string SelectedYAxis {
104      get { return yAxisValue; }
105      set {
106        if (yAxisComboBox.Items.Contains(value)) {
107          yAxisComboBox.SelectedItem = value;
108        }
109      }
110    }
111
[3349]112    protected override void RegisterContentEvents() {
113      base.RegisterContentEvents();
114      Content.Reset += new EventHandler(Content_Reset);
115      Content.ColumnNamesChanged += new EventHandler(Content_ColumnNamesChanged);
[3428]116      Content.ItemsAdded += new HeuristicLab.Collections.CollectionItemsChangedEventHandler<IRun>(Content_ItemsAdded);
117      Content.ItemsRemoved += new HeuristicLab.Collections.CollectionItemsChangedEventHandler<IRun>(Content_ItemsRemoved);
118      Content.CollectionReset += new HeuristicLab.Collections.CollectionItemsChangedEventHandler<IRun>(Content_CollectionReset);
[9312]119      Content.OptimizerNameChanged += new EventHandler(Content_AlgorithmNameChanged);
[4888]120      Content.UpdateOfRunsInProgressChanged += new EventHandler(Content_UpdateOfRunsInProgressChanged);
[3448]121      RegisterRunEvents(Content);
122    }
[3349]123    protected override void DeregisterContentEvents() {
124      base.DeregisterContentEvents();
125      Content.Reset -= new EventHandler(Content_Reset);
126      Content.ColumnNamesChanged -= new EventHandler(Content_ColumnNamesChanged);
[3428]127      Content.ItemsAdded -= new HeuristicLab.Collections.CollectionItemsChangedEventHandler<IRun>(Content_ItemsAdded);
128      Content.ItemsRemoved -= new HeuristicLab.Collections.CollectionItemsChangedEventHandler<IRun>(Content_ItemsRemoved);
129      Content.CollectionReset -= new HeuristicLab.Collections.CollectionItemsChangedEventHandler<IRun>(Content_CollectionReset);
[9312]130      Content.OptimizerNameChanged -= new EventHandler(Content_AlgorithmNameChanged);
[4888]131      Content.UpdateOfRunsInProgressChanged -= new EventHandler(Content_UpdateOfRunsInProgressChanged);
[3448]132      DeregisterRunEvents(Content);
133    }
[4094]134    protected virtual void RegisterRunEvents(IEnumerable<IRun> runs) {
135      foreach (IRun run in runs)
[11344]136        run.PropertyChanged += run_PropertyChanged;
[4094]137    }
[3448]138    protected virtual void DeregisterRunEvents(IEnumerable<IRun> runs) {
139      foreach (IRun run in runs)
[11344]140        run.PropertyChanged -= run_PropertyChanged;
[3349]141    }
[3428]142
143    private void Content_CollectionReset(object sender, HeuristicLab.Collections.CollectionItemsChangedEventArgs<IRun> e) {
[3448]144      DeregisterRunEvents(e.OldItems);
145      RegisterRunEvents(e.Items);
[3428]146    }
147    private void Content_ItemsRemoved(object sender, HeuristicLab.Collections.CollectionItemsChangedEventArgs<IRun> e) {
[3449]148      DeregisterRunEvents(e.Items);
[3428]149    }
150    private void Content_ItemsAdded(object sender, HeuristicLab.Collections.CollectionItemsChangedEventArgs<IRun> e) {
[3448]151      RegisterRunEvents(e.Items);
[3428]152    }
[11344]153    private void run_PropertyChanged(object sender, PropertyChangedEventArgs e) {
[9312]154      if (suppressUpdates) return;
[3632]155      if (InvokeRequired)
[11344]156        this.Invoke((Action<object, PropertyChangedEventArgs>)run_PropertyChanged, sender, e);
[3632]157      else {
[11344]158        if (e.PropertyName == "Color" || e.PropertyName == "Visible") {
159          IRun run = (IRun)sender;
160          UpdateRun(run);
161          UpdateCursorInterval();
162          chart.ChartAreas[0].RecalculateAxesScale();
163          UpdateAxisLabels();
164        }
[3632]165      }
[3614]166    }
167
[9312]168    private void Content_UpdateOfRunsInProgressChanged(object sender, EventArgs e) {
169      if (InvokeRequired)
170        this.Invoke(new EventHandler(Content_UpdateOfRunsInProgressChanged), sender, e);
171      else {
172        suppressUpdates = Content.UpdateOfRunsInProgress;
173        if (suppressUpdates) return;
174
[11007]175        UpdateDataPoints();
[9312]176        UpdateAxisLabels();
177      }
178    }
179
[3614]180    private void UpdateRun(IRun run) {
[9312]181      if (runToDataPointMapping.ContainsKey(run)) {
182        foreach (DataPoint point in runToDataPointMapping[run]) {
183          if (!run.Visible) {
184            this.chart.Series[0].Points.Remove(point);
185            continue;
[4883]186          }
[9312]187          if (selectedRuns.Contains(run)) {
188            point.Color = Color.Red;
189            point.MarkerStyle = MarkerStyle.Cross;
190          } else {
[9435]191            point.Color = Color.FromArgb(255 - LogTransform(transparencyTrackBar.Value), ((IRun)point.Tag).Color);
[9312]192            point.MarkerStyle = MarkerStyle.Circle;
193          }
194
[4799]195        }
[9312]196        if (!run.Visible) runToDataPointMapping.Remove(run);
197      } else {
198        AddDataPoint(run);
199      }
[4883]200
[9312]201      if (this.chart.Series[0].Points.Count == 0)
202        noRunsLabel.Visible = true;
203      else
204        noRunsLabel.Visible = false;
[3428]205    }
206
[3349]207    protected override void OnContentChanged() {
208      base.OnContentChanged();
[3499]209      UpdateComboBoxes();
210      UpdateDataPoints();
[8738]211      UpdateCaption();
[3349]212    }
[9235]213
214    private void RebuildInverseIndex() {
215      if (Content != null) {
[9312]216        runToIndexMapping.Clear();
[9235]217        int i = 0;
218        foreach (var run in Content) {
219          runToIndexMapping.Add(run, i);
220          i++;
221        }
222      }
223    }
224
[3349]225    private void Content_ColumnNamesChanged(object sender, EventArgs e) {
226      if (InvokeRequired)
227        Invoke(new EventHandler(Content_ColumnNamesChanged), sender, e);
228      else
229        UpdateComboBoxes();
230    }
231
[8738]232    private void UpdateCaption() {
[8962]233      Caption = Content != null ? Content.OptimizerName + " Bubble Chart" : ViewAttribute.GetViewName(GetType());
[8738]234    }
235
[3349]236    private void UpdateComboBoxes() {
[3701]237      string selectedXAxis = (string)this.xAxisComboBox.SelectedItem;
238      string selectedYAxis = (string)this.yAxisComboBox.SelectedItem;
239      string selectedSizeAxis = (string)this.sizeComboBox.SelectedItem;
[3349]240      this.xAxisComboBox.Items.Clear();
241      this.yAxisComboBox.Items.Clear();
[3411]242      this.sizeComboBox.Items.Clear();
[3499]243      if (Content != null) {
[3524]244        string[] additionalAxisDimension = Enum.GetNames(typeof(AxisDimension));
245        this.xAxisComboBox.Items.AddRange(additionalAxisDimension);
[14889]246        var comparer = new HeuristicLab.Common.NaturalStringComparer();
247        var sortedColumnNames = Matrix.ColumnNames.ToArray();
248        sortedColumnNames.StableSort(comparer);
249        this.xAxisComboBox.Items.AddRange(sortedColumnNames);
[3524]250        this.yAxisComboBox.Items.AddRange(additionalAxisDimension);
[14889]251        this.yAxisComboBox.Items.AddRange(sortedColumnNames);
[3524]252        string[] additionalSizeDimension = Enum.GetNames(typeof(SizeDimension));
253        this.sizeComboBox.Items.AddRange(additionalSizeDimension);
[14889]254        this.sizeComboBox.Items.AddRange(sortedColumnNames);
[3524]255        this.sizeComboBox.SelectedItem = SizeDimension.Constant.ToString();
[3701]256
257        bool changed = false;
258        if (selectedXAxis != null && xAxisComboBox.Items.Contains(selectedXAxis)) {
259          xAxisComboBox.SelectedItem = selectedXAxis;
260          changed = true;
261        }
262        if (selectedYAxis != null && yAxisComboBox.Items.Contains(selectedYAxis)) {
263          yAxisComboBox.SelectedItem = selectedYAxis;
264          changed = true;
265        }
266        if (selectedSizeAxis != null && sizeComboBox.Items.Contains(selectedSizeAxis)) {
267          sizeComboBox.SelectedItem = selectedSizeAxis;
268          changed = true;
269        }
[9235]270        if (changed) {
[3701]271          UpdateDataPoints();
[9235]272          UpdateAxisLabels();
273        }
[3499]274      }
[3349]275    }
276
[8738]277    private void Content_AlgorithmNameChanged(object sender, EventArgs e) {
278      if (InvokeRequired)
279        Invoke(new EventHandler(Content_AlgorithmNameChanged), sender, e);
280      else UpdateCaption();
281    }
282
[3349]283    private void Content_Reset(object sender, EventArgs e) {
[12077]284      if (suppressUpdates) return;
[3349]285      if (InvokeRequired)
286        Invoke(new EventHandler(Content_Reset), sender, e);
287      else {
288        UpdateDataPoints();
[9235]289        UpdateAxisLabels();
[3349]290      }
291    }
292
293    private void UpdateDataPoints() {
294      Series series = this.chart.Series[0];
295      series.Points.Clear();
[4799]296      runToDataPointMapping.Clear();
[11007]297      categoricalMapping.Clear();
[9312]298      selectedRuns.Clear();
[11007]299      RebuildInverseIndex();
[6096]300
301      chart.ChartAreas[0].AxisX.IsMarginVisible = xAxisValue != AxisDimension.Index.ToString();
302      chart.ChartAreas[0].AxisY.IsMarginVisible = yAxisValue != AxisDimension.Index.ToString();
303
[3499]304      if (Content != null) {
305        foreach (IRun run in this.Content)
306          this.AddDataPoint(run);
[3543]307
308        if (this.chart.Series[0].Points.Count == 0)
309          noRunsLabel.Visible = true;
[4209]310        else {
[3543]311          noRunsLabel.Visible = false;
[5330]312          UpdateMarkerSizes();
[4209]313          UpdateCursorInterval();
314        }
[3499]315      }
[5824]316      xTrackBar.Value = 0;
317      yTrackBar.Value = 0;
[9068]318
319      //needed to set axis back to automatic and refresh them, otherwise their values may remain NaN
320      var xAxis = chart.ChartAreas[0].AxisX;
321      var yAxis = chart.ChartAreas[0].AxisY;
322      SetAutomaticUpdateOfAxis(xAxis, true);
323      SetAutomaticUpdateOfAxis(yAxis, true);
324      chart.Refresh();
[3428]325    }
[5330]326
327    private void UpdateMarkerSizes() {
[9229]328      var series = chart.Series[0];
[9340]329      if (series.Points.Count <= 0) return;
330
[9229]331      var sizeValues = series.Points.Select(p => p.YValues[1]);
[5330]332      double minSizeValue = sizeValues.Min();
333      double maxSizeValue = sizeValues.Max();
[9229]334      double sizeRange = maxSizeValue - minSizeValue;
[5330]335
[9435]336      const int smallestBubbleSize = 7;
[9229]337
338      foreach (DataPoint point in series.Points) {
339        //calculates the relative size of the data point  0 <= relativeSize <= 1
[5348]340        double relativeSize = (point.YValues[1] - minSizeValue);
[9229]341        if (sizeRange > double.Epsilon) {
342          relativeSize /= sizeRange;
[5348]343
[9229]344          //invert bubble sizes if the value of the trackbar is negative
345          if (sizeTrackBar.Value < 0) relativeSize = Math.Abs(relativeSize - 1);
346        } else relativeSize = 1;
[5348]347
[9229]348        double sizeChange = Math.Abs(sizeTrackBar.Value) * relativeSize;
349        point.MarkerSize = (int)Math.Round(sizeChange + smallestBubbleSize);
[5330]350      }
351    }
352
[5824]353    private void UpdateDataPointJitter() {
354      var xAxis = this.chart.ChartAreas[0].AxisX;
355      var yAxis = this.chart.ChartAreas[0].AxisY;
356
[8835]357      double xAxisRange = xAxis.Maximum - xAxis.Minimum;
358      double yAxisRange = yAxis.Maximum - yAxis.Minimum;
[8832]359
[5824]360      foreach (DataPoint point in chart.Series[0].Points) {
361        IRun run = (IRun)point.Tag;
362        double xValue = GetValue(run, xAxisValue).Value;
363        double yValue = GetValue(run, yAxisValue).Value;
364
365        if (!xJitterFactor.IsAlmost(0.0))
[8835]366          xValue += 0.1 * GetXJitter(run) * xJitterFactor * (xAxisRange);
[5824]367        if (!yJitterFactor.IsAlmost(0.0))
[8835]368          yValue += 0.1 * GetYJitter(run) * yJitterFactor * (yAxisRange);
[5824]369
370        point.XValue = xValue;
371        point.YValues[0] = yValue;
372      }
373
[9435]374      if (xJitterFactor.IsAlmost(0.0) && yJitterFactor.IsAlmost(0.0)) {
375        SetAutomaticUpdateOfAxis(xAxis, true);
376        SetAutomaticUpdateOfAxis(yAxis, true);
377        chart.ChartAreas[0].RecalculateAxesScale();
378      } else {
379        SetAutomaticUpdateOfAxis(xAxis, false);
380        SetAutomaticUpdateOfAxis(yAxis, false);
381      }
[5824]382    }
383
[9068]384    // sets an axis to automatic or restrains it to its current values
385    // this is used that none of the set values is changed when jitter is applied, so that the chart stays the same
386    private void SetAutomaticUpdateOfAxis(Axis axis, bool enabled) {
387      if (enabled) {
388        axis.Maximum = double.NaN;
389        axis.Minimum = double.NaN;
390        axis.MajorGrid.Interval = double.NaN;
391        axis.MajorTickMark.Interval = double.NaN;
392        axis.LabelStyle.Interval = double.NaN;
393      } else {
394        axis.Minimum = axis.Minimum;
395        axis.Maximum = axis.Maximum;
396        axis.MajorGrid.Interval = axis.MajorGrid.Interval;
397        axis.MajorTickMark.Interval = axis.MajorTickMark.Interval;
398        axis.LabelStyle.Interval = axis.LabelStyle.Interval;
399      }
400    }
401
[3428]402    private void AddDataPoint(IRun run) {
[3349]403      double? xValue;
404      double? yValue;
[3411]405      double? sizeValue;
[3428]406      Series series = this.chart.Series[0];
[3726]407
[4845]408      xValue = GetValue(run, xAxisValue);
409      yValue = GetValue(run, yAxisValue);
410      sizeValue = GetValue(run, sizeAxisValue);
[3726]411
[3543]412      if (xValue.HasValue && yValue.HasValue && sizeValue.HasValue) {
[3701]413        xValue = xValue.Value;
414        yValue = yValue.Value;
[5824]415
[3428]416        if (run.Visible) {
[3411]417          DataPoint point = new DataPoint(xValue.Value, new double[] { yValue.Value, sizeValue.Value });
[3428]418          point.Tag = run;
[3411]419          series.Points.Add(point);
[4883]420          if (!runToDataPointMapping.ContainsKey(run)) runToDataPointMapping.Add(run, new List<DataPoint>());
421          runToDataPointMapping[run].Add(point);
[9312]422          UpdateRun(run);
[3411]423        }
[3349]424      }
425    }
[3524]426    private double? GetValue(IRun run, string columnName) {
427      if (run == null || string.IsNullOrEmpty(columnName))
[3349]428        return null;
429
[3524]430      if (Enum.IsDefined(typeof(AxisDimension), columnName)) {
431        AxisDimension axisDimension = (AxisDimension)Enum.Parse(typeof(AxisDimension), columnName);
432        return GetValue(run, axisDimension);
433      } else if (Enum.IsDefined(typeof(SizeDimension), columnName)) {
434        SizeDimension sizeDimension = (SizeDimension)Enum.Parse(typeof(SizeDimension), columnName);
435        return GetValue(run, sizeDimension);
436      } else {
437        int columnIndex = Matrix.ColumnNames.ToList().IndexOf(columnName);
438        IItem value = Content.GetValue(run, columnIndex);
439        if (value == null)
440          return null;
[3447]441
[3524]442        DoubleValue doubleValue = value as DoubleValue;
443        IntValue intValue = value as IntValue;
[4049]444        TimeSpanValue timeSpanValue = value as TimeSpanValue;
[3543]445        double? ret = null;
446        if (doubleValue != null) {
447          if (!double.IsNaN(doubleValue.Value) && !double.IsInfinity(doubleValue.Value))
448            ret = doubleValue.Value;
449        } else if (intValue != null)
[3524]450          ret = intValue.Value;
[4049]451        else if (timeSpanValue != null) {
452          ret = timeSpanValue.Value.TotalSeconds;
453        } else
[3524]454          ret = GetCategoricalValue(columnIndex, value.ToString());
[3447]455
[3524]456        return ret;
457      }
[3349]458    }
[11007]459    private double? GetCategoricalValue(int dimension, string value) {
[9235]460      if (!this.categoricalMapping.ContainsKey(dimension)) {
[3349]461        this.categoricalMapping[dimension] = new Dictionary<object, double>();
[9435]462        var orderedCategories = Content.Where(r => r.Visible && Content.GetValue(r, dimension) != null).Select(r => Content.GetValue(r, dimension).ToString())
463                                    .Distinct().OrderBy(x => x, new NaturalStringComparer());
[9235]464        int count = 1;
465        foreach (var category in orderedCategories) {
466          this.categoricalMapping[dimension].Add(category, count);
467          count++;
468        }
[3349]469      }
[11007]470      if (!this.categoricalMapping[dimension].ContainsKey(value)) return null;
[3524]471      return this.categoricalMapping[dimension][value];
[3349]472    }
[9235]473
[3524]474    private double GetValue(IRun run, AxisDimension axisDimension) {
475      double value = double.NaN;
476      switch (axisDimension) {
477        case AxisDimension.Index: {
[9235]478            value = runToIndexMapping[run];
[3524]479            break;
480          }
481        default: {
482            throw new ArgumentException("No handling strategy for " + axisDimension.ToString() + " is defined.");
483          }
484      }
485      return value;
486    }
487    private double GetValue(IRun run, SizeDimension sizeDimension) {
488      double value = double.NaN;
489      switch (sizeDimension) {
490        case SizeDimension.Constant: {
491            value = 2;
492            break;
493          }
494        default: {
495            throw new ArgumentException("No handling strategy for " + sizeDimension.ToString() + " is defined.");
496          }
497      }
498      return value;
499    }
[3707]500    private void UpdateCursorInterval() {
[9312]501      double xMin = double.MaxValue;
502      double xMax = double.MinValue;
503      double yMin = double.MaxValue;
504      double yMax = double.MinValue;
[3349]505
[9312]506      foreach (var point in chart.Series[0].Points) {
507        if (point.IsEmpty) continue;
508        if (point.XValue < xMin) xMin = point.XValue;
509        if (point.XValue > xMax) xMax = point.XValue;
510        if (point.YValues[0] < yMin) yMin = point.YValues[0];
511        if (point.YValues[0] > yMax) yMax = point.YValues[0];
512      }
513
514      double xRange = 0.0;
515      double yRange = 0.0;
516      if (xMin != double.MaxValue && xMax != double.MinValue) xRange = xMax - xMin;
517      if (yMin != double.MaxValue && yMax != double.MinValue) yRange = yMax - yMin;
518
[4049]519      if (xRange.IsAlmost(0.0)) xRange = 1.0;
520      if (yRange.IsAlmost(0.0)) yRange = 1.0;
[3707]521      double xDigits = (int)Math.Log10(xRange) - 3;
522      double yDigits = (int)Math.Log10(yRange) - 3;
523      double xZoomInterval = Math.Pow(10, xDigits);
524      double yZoomInterval = Math.Pow(10, yDigits);
525      this.chart.ChartAreas[0].CursorX.Interval = xZoomInterval;
526      this.chart.ChartAreas[0].CursorY.Interval = yZoomInterval;
[4049]527
528      //code to handle TimeSpanValues correct
529      int axisDimensionCount = Enum.GetNames(typeof(AxisDimension)).Count();
530      int columnIndex = xAxisComboBox.SelectedIndex - axisDimensionCount;
531      if (columnIndex >= 0 && Content.GetValue(0, columnIndex) is TimeSpanValue)
532        this.chart.ChartAreas[0].CursorX.Interval = 1;
533      columnIndex = yAxisComboBox.SelectedIndex - axisDimensionCount;
534      if (columnIndex >= 0 && Content.GetValue(0, columnIndex) is TimeSpanValue)
535        this.chart.ChartAreas[0].CursorY.Interval = 1;
[3707]536    }
537
[4888]538    #region Drag & drop and tooltip
[6026]539    private void chart_MouseDoubleClick(object sender, MouseEventArgs e) {
[6094]540      HitTestResult h = this.chart.HitTest(e.X, e.Y, ChartElementType.DataPoint);
[3411]541      if (h.ChartElementType == ChartElementType.DataPoint) {
[3459]542        IRun run = (IRun)((DataPoint)h.Object).Tag;
[5976]543        IContentView view = MainFormManager.MainForm.ShowContent(run);
544        if (view != null) {
545          view.ReadOnly = this.ReadOnly;
546          view.Locked = this.Locked;
547        }
[6026]548
549        this.chart.ChartAreas[0].CursorX.SelectionStart = this.chart.ChartAreas[0].CursorX.SelectionEnd;
550        this.chart.ChartAreas[0].CursorY.SelectionStart = this.chart.ChartAreas[0].CursorY.SelectionEnd;
[3411]551      }
[6096]552      UpdateAxisLabels();
[3411]553    }
554
[3428]555    private void chart_MouseUp(object sender, MouseEventArgs e) {
[9312]556      if (!isSelecting) return;
[3428]557
[9312]558      System.Windows.Forms.DataVisualization.Charting.Cursor xCursor = chart.ChartAreas[0].CursorX;
559      System.Windows.Forms.DataVisualization.Charting.Cursor yCursor = chart.ChartAreas[0].CursorY;
[3428]560
[9312]561      double minX = Math.Min(xCursor.SelectionStart, xCursor.SelectionEnd);
562      double maxX = Math.Max(xCursor.SelectionStart, xCursor.SelectionEnd);
563      double minY = Math.Min(yCursor.SelectionStart, yCursor.SelectionEnd);
564      double maxY = Math.Max(yCursor.SelectionStart, yCursor.SelectionEnd);
565
[9435]566      if (Control.ModifierKeys != Keys.Control) {
567        ClearSelectedRuns();
568      }
569
[9312]570      //check for click to select a single model
571      if (minX == maxX && minY == maxY) {
[9332]572        HitTestResult hitTest = chart.HitTest(e.X, e.Y, ChartElementType.DataPoint);
[9312]573        if (hitTest.ChartElementType == ChartElementType.DataPoint) {
574          int pointIndex = hitTest.PointIndex;
575          var point = chart.Series[0].Points[pointIndex];
576          IRun run = (IRun)point.Tag;
[9447]577          if (selectedRuns.Contains(run)) {
578            point.MarkerStyle = MarkerStyle.Circle;
579            point.Color = Color.FromArgb(255 - LogTransform(transparencyTrackBar.Value), run.Color);
580            selectedRuns.Remove(run);
581          } else {
582            point.Color = Color.Red;
583            point.MarkerStyle = MarkerStyle.Cross;
584            selectedRuns.Add(run);
585          }
[9435]586        }
[9312]587      } else {
588        foreach (DataPoint point in this.chart.Series[0].Points) {
[9435]589          if (point.XValue < minX || point.XValue > maxX) continue;
590          if (point.YValues[0] < minY || point.YValues[0] > maxY) continue;
[9312]591          point.MarkerStyle = MarkerStyle.Cross;
592          point.Color = Color.Red;
593          IRun run = (IRun)point.Tag;
594          selectedRuns.Add(run);
[3428]595        }
596      }
[9315]597
[9312]598      this.chart.ChartAreas[0].CursorX.SelectionStart = this.chart.ChartAreas[0].CursorX.SelectionEnd;
599      this.chart.ChartAreas[0].CursorY.SelectionStart = this.chart.ChartAreas[0].CursorY.SelectionEnd;
[9315]600      this.OnChanged();
[3428]601    }
602
[3411]603    private void chart_MouseMove(object sender, MouseEventArgs e) {
[9312]604      if (Control.MouseButtons != MouseButtons.None) return;
[3487]605      HitTestResult h = this.chart.HitTest(e.X, e.Y);
[3524]606      string newTooltipText = string.Empty;
[3487]607      string oldTooltipText;
608      if (h.ChartElementType == ChartElementType.DataPoint) {
609        IRun run = (IRun)((DataPoint)h.Object).Tag;
[3524]610        newTooltipText = BuildTooltip(run);
[4212]611      } else if (h.ChartElementType == ChartElementType.AxisLabels) {
612        newTooltipText = ((CustomLabel)h.Object).ToolTip;
[3524]613      }
614
[3487]615      oldTooltipText = this.tooltip.GetToolTip(chart);
616      if (newTooltipText != oldTooltipText)
617        this.tooltip.SetToolTip(chart, newTooltipText);
[3411]618    }
[3524]619
620    private string BuildTooltip(IRun run) {
621      string tooltip;
622      tooltip = run.Name + System.Environment.NewLine;
623
624      double? xValue = this.GetValue(run, (string)xAxisComboBox.SelectedItem);
625      double? yValue = this.GetValue(run, (string)yAxisComboBox.SelectedItem);
626      double? sizeValue = this.GetValue(run, (string)sizeComboBox.SelectedItem);
627
628      string xString = xValue == null ? string.Empty : xValue.Value.ToString();
629      string yString = yValue == null ? string.Empty : yValue.Value.ToString();
630      string sizeString = sizeValue == null ? string.Empty : sizeValue.Value.ToString();
631
[4049]632      //code to handle TimeSpanValues correct
633      int axisDimensionCount = Enum.GetNames(typeof(AxisDimension)).Count();
634      int columnIndex = xAxisComboBox.SelectedIndex - axisDimensionCount;
635      if (xValue.HasValue && columnIndex > 0 && Content.GetValue(0, columnIndex) is TimeSpanValue) {
636        TimeSpan time = TimeSpan.FromSeconds(xValue.Value);
[4212]637        xString = string.Format("{0:00}:{1:00}:{2:00.00}", (int)time.TotalHours, time.Minutes, time.Seconds);
[4049]638      }
639      columnIndex = yAxisComboBox.SelectedIndex - axisDimensionCount;
640      if (yValue.HasValue && columnIndex > 0 && Content.GetValue(0, columnIndex) is TimeSpanValue) {
641        TimeSpan time = TimeSpan.FromSeconds(yValue.Value);
[4212]642        yString = string.Format("{0:00}:{1:00}:{2:00.00}", (int)time.TotalHours, time.Minutes, time.Seconds);
[4049]643      }
644
[3524]645      tooltip += xAxisComboBox.SelectedItem + " : " + xString + Environment.NewLine;
646      tooltip += yAxisComboBox.SelectedItem + " : " + yString + Environment.NewLine;
647      tooltip += sizeComboBox.SelectedItem + " : " + sizeString + Environment.NewLine;
648
649      return tooltip;
650    }
[3411]651    #endregion
652
653    #region GUI events and updating
654    private double GetXJitter(IRun run) {
655      if (!this.xJitter.ContainsKey(run))
656        this.xJitter[run] = random.NextDouble() * 2.0 - 1.0;
657      return this.xJitter[run];
658    }
659    private double GetYJitter(IRun run) {
660      if (!this.yJitter.ContainsKey(run))
661        this.yJitter[run] = random.NextDouble() * 2.0 - 1.0;
662      return this.yJitter[run];
663    }
664    private void jitterTrackBar_ValueChanged(object sender, EventArgs e) {
665      this.xJitterFactor = xTrackBar.Value / 100.0;
666      this.yJitterFactor = yTrackBar.Value / 100.0;
[5824]667      UpdateDataPointJitter();
[3411]668    }
[5330]669    private void sizeTrackBar_ValueChanged(object sender, EventArgs e) {
670      UpdateMarkerSizes();
671    }
[3411]672
[5330]673    private void AxisComboBox_SelectedValueChanged(object sender, EventArgs e) {
[4812]674      bool axisSelected = xAxisComboBox.SelectedIndex != -1 && yAxisComboBox.SelectedIndex != -1;
675      xTrackBar.Enabled = yTrackBar.Enabled = axisSelected;
676      colorXAxisButton.Enabled = colorYAxisButton.Enabled = axisSelected;
[4845]677
[6094]678      xAxisValue = (string)xAxisComboBox.SelectedItem;
679      yAxisValue = (string)yAxisComboBox.SelectedItem;
680      sizeAxisValue = (string)sizeComboBox.SelectedItem;
[4845]681
[3411]682      UpdateDataPoints();
683      UpdateAxisLabels();
684    }
[3349]685    private void UpdateAxisLabels() {
686      Axis xAxis = this.chart.ChartAreas[0].AxisX;
687      Axis yAxis = this.chart.ChartAreas[0].AxisY;
[3536]688      int axisDimensionCount = Enum.GetNames(typeof(AxisDimension)).Count();
[11095]689      //mkommend: combobox.SelectedIndex could not be used as this changes during hovering over possible values
[11024]690      var xSAxisSelectedIndex = xAxisValue == null ? 0 : xAxisComboBox.Items.IndexOf(xAxisValue);
691      var ySAxisSelectedIndex = yAxisValue == null ? 0 : xAxisComboBox.Items.IndexOf(yAxisValue);
692      SetCustomAxisLabels(xAxis, xSAxisSelectedIndex - axisDimensionCount);
693      SetCustomAxisLabels(yAxis, ySAxisSelectedIndex - axisDimensionCount);
694      if (xAxisValue != null)
695        xAxis.Title = xAxisValue;
[11344]696      if (yAxisValue != null)
697        yAxis.Title = yAxisValue;
[3349]698    }
[4049]699
700    private void chart_AxisViewChanged(object sender, System.Windows.Forms.DataVisualization.Charting.ViewEventArgs e) {
701      this.UpdateAxisLabels();
702    }
703
[3411]704    private void SetCustomAxisLabels(Axis axis, int dimension) {
705      axis.CustomLabels.Clear();
[3349]706      if (categoricalMapping.ContainsKey(dimension)) {
707        foreach (var pair in categoricalMapping[dimension]) {
[3536]708          string labelText = pair.Key.ToString();
[4212]709          CustomLabel label = new CustomLabel();
710          label.ToolTip = labelText;
[3543]711          if (labelText.Length > 25)
712            labelText = labelText.Substring(0, 25) + " ... ";
[4212]713          label.Text = labelText;
[3349]714          label.GridTicks = GridTickTypes.TickMark;
[4212]715          label.FromPosition = pair.Value - 0.5;
716          label.ToPosition = pair.Value + 0.5;
717          axis.CustomLabels.Add(label);
[3349]718        }
[4049]719      } else if (dimension > 0 && Content.GetValue(0, dimension) is TimeSpanValue) {
720        this.chart.ChartAreas[0].RecalculateAxesScale();
721        for (double i = axis.Minimum; i <= axis.Maximum; i += axis.LabelStyle.Interval) {
722          TimeSpan time = TimeSpan.FromSeconds(i);
[6096]723          string x = string.Format("{0:00}:{1:00}:{2:00}", time.Hours, time.Minutes, time.Seconds);
[4058]724          axis.CustomLabels.Add(i - axis.LabelStyle.Interval / 2, i + axis.LabelStyle.Interval / 2, x);
[4049]725        }
[3349]726      }
727    }
[3411]728
729    private void zoomButton_CheckedChanged(object sender, EventArgs e) {
730      this.isSelecting = selectButton.Checked;
[9435]731      this.colorRunsButton.Enabled = this.isSelecting;
[9312]732      this.colorDialogButton.Enabled = this.isSelecting;
733      this.hideRunsButton.Enabled = this.isSelecting;
[3411]734      this.chart.ChartAreas[0].AxisX.ScaleView.Zoomable = !isSelecting;
735      this.chart.ChartAreas[0].AxisY.ScaleView.Zoomable = !isSelecting;
[9312]736      ClearSelectedRuns();
[3411]737    }
[4653]738
[6673]739    private void ContextMenuStrip_Opening(object sender, System.ComponentModel.CancelEventArgs e) {
[9448]740      hideRunsToolStripMenuItem.Visible = selectedRuns.Any();
[9435]741    }
[6673]742
[9435]743    private void unhideAllRunToolStripMenuItem_Click(object sender, EventArgs e) {
744      visibilityConstraint.ConstraintData.Clear();
745      if (Content.Constraints.Contains(visibilityConstraint)) Content.Constraints.Remove(visibilityConstraint);
[6673]746    }
[9435]747    private void hideRunsToolStripMenuItem_Click(object sender, EventArgs e) {
[11007]748      //ToList is necessary to prevent lazy evaluation
749      HideRuns(selectedRuns.ToList());
[9435]750      //could not use ClearSelectedRuns as the runs are not visible anymore
751      selectedRuns.Clear();
[6673]752    }
[9312]753    private void hideRunsButton_Click(object sender, EventArgs e) {
[11007]754      //ToList is necessary to prevent lazy evaluation
755      HideRuns(selectedRuns.ToList());
[9435]756      //could not use ClearSelectedRuns as the runs are not visible anymore
757      selectedRuns.Clear();
[9312]758    }
[6673]759
[9435]760    private void HideRuns(IEnumerable<IRun> runs) {
761      visibilityConstraint.Active = false;
762      if (!Content.Constraints.Contains(visibilityConstraint)) Content.Constraints.Add(visibilityConstraint);
[9448]763      foreach (var run in runs) {
[9435]764        visibilityConstraint.ConstraintData.Add(run);
765      }
766      visibilityConstraint.Active = true;
767    }
768
[9312]769    private void ClearSelectedRuns() {
770      foreach (var run in selectedRuns) {
771        foreach (var point in runToDataPointMapping[run]) {
772          point.MarkerStyle = MarkerStyle.Circle;
[9404]773          point.Color = Color.FromArgb(255 - LogTransform(transparencyTrackBar.Value), run.Color);
[9312]774        }
775      }
776      selectedRuns.Clear();
777    }
778
[9404]779    // returns a value in [0..255]
780    private int LogTransform(int x) {
781      double min = transparencyTrackBar.Minimum;
782      double max = transparencyTrackBar.Maximum;
783      double r = (x - min) / (max - min);  // r \in [0..1]
[9441]784      double l = Math.Max(Math.Min((1.0 - Math.Pow(0.05, r)) / 0.95, 1), 0); // l \in [0..1]
[9404]785      return (int)Math.Round(255.0 * l);
786    }
787
[4653]788    private void openBoxPlotViewToolStripMenuItem_Click(object sender, EventArgs e) {
789      RunCollectionBoxPlotView boxplotView = new RunCollectionBoxPlotView();
790      boxplotView.Content = this.Content;
791      boxplotView.xAxisComboBox.SelectedItem = xAxisComboBox.SelectedItem;
792      boxplotView.yAxisComboBox.SelectedItem = yAxisComboBox.SelectedItem;
793      boxplotView.Show();
794    }
[9190]795
796    private void getDataAsMatrixToolStripMenuItem_Click(object sender, EventArgs e) {
797      int xCol = Matrix.ColumnNames.ToList().IndexOf(xAxisValue);
[9267]798      int yCol = Matrix.ColumnNames.ToList().IndexOf(yAxisValue);
799
[9190]800      var grouped = new Dictionary<string, List<string>>();
801      Dictionary<double, string> reverseMapping = null;
802      if (categoricalMapping.ContainsKey(xCol))
803        reverseMapping = categoricalMapping[xCol].ToDictionary(x => x.Value, y => y.Key.ToString());
804      foreach (var run in Content.Where(r => r.Visible)) {
805        var x = GetValue(run, xAxisValue);
[9267]806        object y;
807        if (categoricalMapping.ContainsKey(yCol))
808          y = Content.GetValue(run, yAxisValue);
809        else y = GetValue(run, yAxisValue);
810        if (!(x.HasValue && y != null)) continue;
[9190]811
812        var category = reverseMapping == null ? x.Value.ToString() : reverseMapping[x.Value];
813        if (!grouped.ContainsKey(category)) grouped[category] = new List<string>();
[9267]814        grouped[category].Add(y.ToString());
[9190]815      }
816
817      if (!grouped.Any()) return;
818      var matrix = new StringMatrix(grouped.Values.Max(x => x.Count), grouped.Count) {
819        ColumnNames = grouped.Keys.ToArray()
820      };
821      int i = 0;
822      foreach (var col in matrix.ColumnNames) {
823        int j = 0;
824        foreach (var y in grouped[col])
825          matrix[j++, i] = y;
826        i++;
827      }
[9267]828      matrix.SortableView = false;
829      var view = MainFormManager.MainForm.ShowContent(matrix);
830      view.ReadOnly = true;
[9190]831    }
[9276]832
833    private void transparencyTrackBar_ValueChanged(object sender, EventArgs e) {
[9312]834      foreach (var run in Content)
835        UpdateRun(run);
[9276]836    }
[3411]837    #endregion
[4799]838
[9312]839    #region coloring
[9435]840    private void colorResetToolStripMenuItem_Click(object sender, EventArgs e) {
841      Content.UpdateOfRunsInProgress = true;
842
843      IEnumerable<IRun> runs;
844      if (selectedRuns.Any()) runs = selectedRuns;
845      else runs = Content;
846
847      foreach (var run in runs)
848        run.Color = Color.Black;
849      ClearSelectedRuns();
850
851      Content.UpdateOfRunsInProgress = false;
852    }
[9312]853    private void colorDialogButton_Click(object sender, EventArgs e) {
854      if (colorDialog.ShowDialog(this) == DialogResult.OK) {
[9435]855        this.colorRunsButton.Image = this.GenerateImage(16, 16, this.colorDialog.Color);
856        colorRunsButton_Click(sender, e);
[9312]857      }
858    }
859    private Image GenerateImage(int width, int height, Color fillColor) {
860      Image colorImage = new Bitmap(width, height);
861      using (Graphics gfx = Graphics.FromImage(colorImage)) {
862        using (SolidBrush brush = new SolidBrush(fillColor)) {
863          gfx.FillRectangle(brush, 0, 0, width, height);
864        }
865      }
866      return colorImage;
867    }
868
869    private void colorRunsButton_Click(object sender, EventArgs e) {
870      if (!selectedRuns.Any()) return;
871      Content.UpdateOfRunsInProgress = true;
872      foreach (var run in selectedRuns)
873        run.Color = colorDialog.Color;
874
875      ClearSelectedRuns();
876      Content.UpdateOfRunsInProgress = false;
877    }
878
[4799]879    private void colorXAxisButton_Click(object sender, EventArgs e) {
[4845]880      ColorRuns(xAxisValue);
[4799]881    }
882    private void colorYAxisButton_Click(object sender, EventArgs e) {
[4845]883      ColorRuns(yAxisValue);
884    }
885    private void ColorRuns(string axisValue) {
[9235]886      var runs = Content.Where(r => r.Visible).Select(r => new { Run = r, Value = GetValue(r, axisValue) }).Where(r => r.Value.HasValue).ToList();
[4845]887      double minValue = runs.Min(r => r.Value.Value);
888      double maxValue = runs.Max(r => r.Value.Value);
889      double range = maxValue - minValue;
[9236]890      // UpdateOfRunsInProgress has to be set to true, otherwise run_Changed is called all the time (also in other views)
891      Content.UpdateOfRunsInProgress = true;
[9235]892      if (range.IsAlmost(0)) {
893        Color c = ColorGradient.Colors[0];
894        runs.ForEach(r => r.Run.Color = c);
895      } else {
896        int maxColorIndex = ColorGradient.Colors.Count - 1;
897        foreach (var r in runs) {
898          int colorIndex = (int)(maxColorIndex * (r.Value - minValue) / (range));
899          r.Run.Color = ColorGradient.Colors[colorIndex];
900        }
[4799]901      }
[9236]902      Content.UpdateOfRunsInProgress = false;
[4799]903    }
904    #endregion
[3349]905  }
906}
Note: See TracBrowser for help on using the repository browser.