Free cookie consent management tool by TermsFeed Policy Generator

source: stable/HeuristicLab.Optimization.Views/3.3/RunCollectionViews/RunCollectionBubbleChartView.cs @ 16837

Last change on this file since 16837 was 16837, checked in by gkronber, 5 years ago

#2995: merged r16681 from trunk to stable

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