Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 15580 was 15266, checked in by mkommend, 7 years ago

#2810: Moved condition to check for SizeDimension.Constant to the top.

File size: 37.1 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 {
[15264]437
438        IItem value = Content.GetValue(run, columnName);
[3524]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;
[15264]453        } else {
454          int columnIndex = Matrix.ColumnNames.ToList().IndexOf(columnName);
[3524]455          ret = GetCategoricalValue(columnIndex, value.ToString());
[15264]456        }
[3447]457
[3524]458        return ret;
459      }
[3349]460    }
[11007]461    private double? GetCategoricalValue(int dimension, string value) {
[9235]462      if (!this.categoricalMapping.ContainsKey(dimension)) {
[3349]463        this.categoricalMapping[dimension] = new Dictionary<object, double>();
[9435]464        var orderedCategories = Content.Where(r => r.Visible && Content.GetValue(r, dimension) != null).Select(r => Content.GetValue(r, dimension).ToString())
465                                    .Distinct().OrderBy(x => x, new NaturalStringComparer());
[9235]466        int count = 1;
467        foreach (var category in orderedCategories) {
468          this.categoricalMapping[dimension].Add(category, count);
469          count++;
470        }
[3349]471      }
[11007]472      if (!this.categoricalMapping[dimension].ContainsKey(value)) return null;
[3524]473      return this.categoricalMapping[dimension][value];
[3349]474    }
[9235]475
[3524]476    private double GetValue(IRun run, AxisDimension axisDimension) {
477      double value = double.NaN;
478      switch (axisDimension) {
479        case AxisDimension.Index: {
[9235]480            value = runToIndexMapping[run];
[3524]481            break;
482          }
483        default: {
484            throw new ArgumentException("No handling strategy for " + axisDimension.ToString() + " is defined.");
485          }
486      }
487      return value;
488    }
489    private double GetValue(IRun run, SizeDimension sizeDimension) {
490      double value = double.NaN;
491      switch (sizeDimension) {
492        case SizeDimension.Constant: {
493            value = 2;
494            break;
495          }
496        default: {
497            throw new ArgumentException("No handling strategy for " + sizeDimension.ToString() + " is defined.");
498          }
499      }
500      return value;
501    }
[3707]502    private void UpdateCursorInterval() {
[9312]503      double xMin = double.MaxValue;
504      double xMax = double.MinValue;
505      double yMin = double.MaxValue;
506      double yMax = double.MinValue;
[3349]507
[9312]508      foreach (var point in chart.Series[0].Points) {
509        if (point.IsEmpty) continue;
510        if (point.XValue < xMin) xMin = point.XValue;
511        if (point.XValue > xMax) xMax = point.XValue;
512        if (point.YValues[0] < yMin) yMin = point.YValues[0];
513        if (point.YValues[0] > yMax) yMax = point.YValues[0];
514      }
515
516      double xRange = 0.0;
517      double yRange = 0.0;
518      if (xMin != double.MaxValue && xMax != double.MinValue) xRange = xMax - xMin;
519      if (yMin != double.MaxValue && yMax != double.MinValue) yRange = yMax - yMin;
520
[4049]521      if (xRange.IsAlmost(0.0)) xRange = 1.0;
522      if (yRange.IsAlmost(0.0)) yRange = 1.0;
[3707]523      double xDigits = (int)Math.Log10(xRange) - 3;
524      double yDigits = (int)Math.Log10(yRange) - 3;
525      double xZoomInterval = Math.Pow(10, xDigits);
526      double yZoomInterval = Math.Pow(10, yDigits);
527      this.chart.ChartAreas[0].CursorX.Interval = xZoomInterval;
528      this.chart.ChartAreas[0].CursorY.Interval = yZoomInterval;
[4049]529
530      //code to handle TimeSpanValues correct
531      int axisDimensionCount = Enum.GetNames(typeof(AxisDimension)).Count();
532      int columnIndex = xAxisComboBox.SelectedIndex - axisDimensionCount;
533      if (columnIndex >= 0 && Content.GetValue(0, columnIndex) is TimeSpanValue)
534        this.chart.ChartAreas[0].CursorX.Interval = 1;
535      columnIndex = yAxisComboBox.SelectedIndex - axisDimensionCount;
536      if (columnIndex >= 0 && Content.GetValue(0, columnIndex) is TimeSpanValue)
537        this.chart.ChartAreas[0].CursorY.Interval = 1;
[3707]538    }
539
[4888]540    #region Drag & drop and tooltip
[6026]541    private void chart_MouseDoubleClick(object sender, MouseEventArgs e) {
[6094]542      HitTestResult h = this.chart.HitTest(e.X, e.Y, ChartElementType.DataPoint);
[3411]543      if (h.ChartElementType == ChartElementType.DataPoint) {
[3459]544        IRun run = (IRun)((DataPoint)h.Object).Tag;
[5976]545        IContentView view = MainFormManager.MainForm.ShowContent(run);
546        if (view != null) {
547          view.ReadOnly = this.ReadOnly;
548          view.Locked = this.Locked;
549        }
[6026]550
551        this.chart.ChartAreas[0].CursorX.SelectionStart = this.chart.ChartAreas[0].CursorX.SelectionEnd;
552        this.chart.ChartAreas[0].CursorY.SelectionStart = this.chart.ChartAreas[0].CursorY.SelectionEnd;
[3411]553      }
[6096]554      UpdateAxisLabels();
[3411]555    }
556
[3428]557    private void chart_MouseUp(object sender, MouseEventArgs e) {
[9312]558      if (!isSelecting) return;
[3428]559
[9312]560      System.Windows.Forms.DataVisualization.Charting.Cursor xCursor = chart.ChartAreas[0].CursorX;
561      System.Windows.Forms.DataVisualization.Charting.Cursor yCursor = chart.ChartAreas[0].CursorY;
[3428]562
[9312]563      double minX = Math.Min(xCursor.SelectionStart, xCursor.SelectionEnd);
564      double maxX = Math.Max(xCursor.SelectionStart, xCursor.SelectionEnd);
565      double minY = Math.Min(yCursor.SelectionStart, yCursor.SelectionEnd);
566      double maxY = Math.Max(yCursor.SelectionStart, yCursor.SelectionEnd);
567
[9435]568      if (Control.ModifierKeys != Keys.Control) {
569        ClearSelectedRuns();
570      }
571
[9312]572      //check for click to select a single model
573      if (minX == maxX && minY == maxY) {
[9332]574        HitTestResult hitTest = chart.HitTest(e.X, e.Y, ChartElementType.DataPoint);
[9312]575        if (hitTest.ChartElementType == ChartElementType.DataPoint) {
576          int pointIndex = hitTest.PointIndex;
577          var point = chart.Series[0].Points[pointIndex];
578          IRun run = (IRun)point.Tag;
[9447]579          if (selectedRuns.Contains(run)) {
580            point.MarkerStyle = MarkerStyle.Circle;
581            point.Color = Color.FromArgb(255 - LogTransform(transparencyTrackBar.Value), run.Color);
582            selectedRuns.Remove(run);
583          } else {
584            point.Color = Color.Red;
585            point.MarkerStyle = MarkerStyle.Cross;
586            selectedRuns.Add(run);
587          }
[9435]588        }
[9312]589      } else {
590        foreach (DataPoint point in this.chart.Series[0].Points) {
[9435]591          if (point.XValue < minX || point.XValue > maxX) continue;
592          if (point.YValues[0] < minY || point.YValues[0] > maxY) continue;
[9312]593          point.MarkerStyle = MarkerStyle.Cross;
594          point.Color = Color.Red;
595          IRun run = (IRun)point.Tag;
596          selectedRuns.Add(run);
[3428]597        }
598      }
[9315]599
[9312]600      this.chart.ChartAreas[0].CursorX.SelectionStart = this.chart.ChartAreas[0].CursorX.SelectionEnd;
601      this.chart.ChartAreas[0].CursorY.SelectionStart = this.chart.ChartAreas[0].CursorY.SelectionEnd;
[9315]602      this.OnChanged();
[3428]603    }
604
[3411]605    private void chart_MouseMove(object sender, MouseEventArgs e) {
[9312]606      if (Control.MouseButtons != MouseButtons.None) return;
[3487]607      HitTestResult h = this.chart.HitTest(e.X, e.Y);
[3524]608      string newTooltipText = string.Empty;
[3487]609      string oldTooltipText;
610      if (h.ChartElementType == ChartElementType.DataPoint) {
611        IRun run = (IRun)((DataPoint)h.Object).Tag;
[3524]612        newTooltipText = BuildTooltip(run);
[4212]613      } else if (h.ChartElementType == ChartElementType.AxisLabels) {
614        newTooltipText = ((CustomLabel)h.Object).ToolTip;
[3524]615      }
616
[3487]617      oldTooltipText = this.tooltip.GetToolTip(chart);
618      if (newTooltipText != oldTooltipText)
619        this.tooltip.SetToolTip(chart, newTooltipText);
[3411]620    }
[3524]621
622    private string BuildTooltip(IRun run) {
623      string tooltip;
624      tooltip = run.Name + System.Environment.NewLine;
625
[15264]626      string xString = GetTooltipValue(run, (string)xAxisComboBox.SelectedItem);
627      string yString = GetTooltipValue(run, (string)yAxisComboBox.SelectedItem);
628      string sizeString = GetTooltipValue(run, (string)sizeComboBox.SelectedItem);
[3524]629
630      tooltip += xAxisComboBox.SelectedItem + " : " + xString + Environment.NewLine;
631      tooltip += yAxisComboBox.SelectedItem + " : " + yString + Environment.NewLine;
632      tooltip += sizeComboBox.SelectedItem + " : " + sizeString + Environment.NewLine;
633
634      return tooltip;
635    }
[15264]636
637    private string GetTooltipValue(IRun run, string columnName) {
[15266]638      if (columnName == SizeDimension.Constant.ToString())
639        return string.Empty;
640
[15264]641      int columnIndex = Matrix.ColumnNames.ToList().IndexOf(columnName);
642
643      //handle non-numeric values correctly
644      if (categoricalMapping.ContainsKey(columnIndex)) {
645        return Content.GetValue(run, columnName).ToString();
646      }
647
648      double? value = GetValue(run, columnName);
649      if (!value.HasValue) return string.Empty;
650
651      string valueString = value.Value.ToString();
652
653      //code to handle TimeSpanValues correctly
654      if (columnIndex > 0 && Content.GetValue(0, columnIndex) is TimeSpanValue) {
655        TimeSpan time = TimeSpan.FromSeconds(value.Value);
656        valueString = string.Format("{0:00}:{1:00}:{2:00.00}", (int)time.TotalHours, time.Minutes, time.Seconds);
657      }
658
659      return valueString;
660    }
[3411]661    #endregion
662
663    #region GUI events and updating
664    private double GetXJitter(IRun run) {
665      if (!this.xJitter.ContainsKey(run))
666        this.xJitter[run] = random.NextDouble() * 2.0 - 1.0;
667      return this.xJitter[run];
668    }
669    private double GetYJitter(IRun run) {
670      if (!this.yJitter.ContainsKey(run))
671        this.yJitter[run] = random.NextDouble() * 2.0 - 1.0;
672      return this.yJitter[run];
673    }
674    private void jitterTrackBar_ValueChanged(object sender, EventArgs e) {
675      this.xJitterFactor = xTrackBar.Value / 100.0;
676      this.yJitterFactor = yTrackBar.Value / 100.0;
[5824]677      UpdateDataPointJitter();
[3411]678    }
[5330]679    private void sizeTrackBar_ValueChanged(object sender, EventArgs e) {
680      UpdateMarkerSizes();
681    }
[3411]682
[5330]683    private void AxisComboBox_SelectedValueChanged(object sender, EventArgs e) {
[4812]684      bool axisSelected = xAxisComboBox.SelectedIndex != -1 && yAxisComboBox.SelectedIndex != -1;
685      xTrackBar.Enabled = yTrackBar.Enabled = axisSelected;
686      colorXAxisButton.Enabled = colorYAxisButton.Enabled = axisSelected;
[4845]687
[6094]688      xAxisValue = (string)xAxisComboBox.SelectedItem;
689      yAxisValue = (string)yAxisComboBox.SelectedItem;
690      sizeAxisValue = (string)sizeComboBox.SelectedItem;
[4845]691
[3411]692      UpdateDataPoints();
693      UpdateAxisLabels();
694    }
[3349]695    private void UpdateAxisLabels() {
696      Axis xAxis = this.chart.ChartAreas[0].AxisX;
697      Axis yAxis = this.chart.ChartAreas[0].AxisY;
[3536]698      int axisDimensionCount = Enum.GetNames(typeof(AxisDimension)).Count();
[11095]699      //mkommend: combobox.SelectedIndex could not be used as this changes during hovering over possible values
[11024]700      var xSAxisSelectedIndex = xAxisValue == null ? 0 : xAxisComboBox.Items.IndexOf(xAxisValue);
701      var ySAxisSelectedIndex = yAxisValue == null ? 0 : xAxisComboBox.Items.IndexOf(yAxisValue);
702      SetCustomAxisLabels(xAxis, xSAxisSelectedIndex - axisDimensionCount);
703      SetCustomAxisLabels(yAxis, ySAxisSelectedIndex - axisDimensionCount);
704      if (xAxisValue != null)
705        xAxis.Title = xAxisValue;
[11344]706      if (yAxisValue != null)
707        yAxis.Title = yAxisValue;
[3349]708    }
[4049]709
710    private void chart_AxisViewChanged(object sender, System.Windows.Forms.DataVisualization.Charting.ViewEventArgs e) {
711      this.UpdateAxisLabels();
712    }
713
[3411]714    private void SetCustomAxisLabels(Axis axis, int dimension) {
715      axis.CustomLabels.Clear();
[3349]716      if (categoricalMapping.ContainsKey(dimension)) {
717        foreach (var pair in categoricalMapping[dimension]) {
[3536]718          string labelText = pair.Key.ToString();
[4212]719          CustomLabel label = new CustomLabel();
720          label.ToolTip = labelText;
[3543]721          if (labelText.Length > 25)
722            labelText = labelText.Substring(0, 25) + " ... ";
[4212]723          label.Text = labelText;
[3349]724          label.GridTicks = GridTickTypes.TickMark;
[4212]725          label.FromPosition = pair.Value - 0.5;
726          label.ToPosition = pair.Value + 0.5;
727          axis.CustomLabels.Add(label);
[3349]728        }
[4049]729      } else if (dimension > 0 && Content.GetValue(0, dimension) is TimeSpanValue) {
730        this.chart.ChartAreas[0].RecalculateAxesScale();
731        for (double i = axis.Minimum; i <= axis.Maximum; i += axis.LabelStyle.Interval) {
732          TimeSpan time = TimeSpan.FromSeconds(i);
[6096]733          string x = string.Format("{0:00}:{1:00}:{2:00}", time.Hours, time.Minutes, time.Seconds);
[4058]734          axis.CustomLabels.Add(i - axis.LabelStyle.Interval / 2, i + axis.LabelStyle.Interval / 2, x);
[4049]735        }
[3349]736      }
737    }
[3411]738
739    private void zoomButton_CheckedChanged(object sender, EventArgs e) {
740      this.isSelecting = selectButton.Checked;
[9435]741      this.colorRunsButton.Enabled = this.isSelecting;
[9312]742      this.colorDialogButton.Enabled = this.isSelecting;
743      this.hideRunsButton.Enabled = this.isSelecting;
[3411]744      this.chart.ChartAreas[0].AxisX.ScaleView.Zoomable = !isSelecting;
745      this.chart.ChartAreas[0].AxisY.ScaleView.Zoomable = !isSelecting;
[9312]746      ClearSelectedRuns();
[3411]747    }
[4653]748
[6673]749    private void ContextMenuStrip_Opening(object sender, System.ComponentModel.CancelEventArgs e) {
[9448]750      hideRunsToolStripMenuItem.Visible = selectedRuns.Any();
[9435]751    }
[6673]752
[9435]753    private void unhideAllRunToolStripMenuItem_Click(object sender, EventArgs e) {
754      visibilityConstraint.ConstraintData.Clear();
755      if (Content.Constraints.Contains(visibilityConstraint)) Content.Constraints.Remove(visibilityConstraint);
[6673]756    }
[9435]757    private void hideRunsToolStripMenuItem_Click(object sender, EventArgs e) {
[15122]758      HideRuns(selectedRuns);
[9435]759      //could not use ClearSelectedRuns as the runs are not visible anymore
760      selectedRuns.Clear();
[6673]761    }
[9312]762    private void hideRunsButton_Click(object sender, EventArgs e) {
[15122]763      HideRuns(selectedRuns);
[9435]764      //could not use ClearSelectedRuns as the runs are not visible anymore
765      selectedRuns.Clear();
[9312]766    }
[6673]767
[9435]768    private void HideRuns(IEnumerable<IRun> runs) {
[15122]769      Content.UpdateOfRunsInProgress = true;
[9435]770      visibilityConstraint.Active = false;
771      if (!Content.Constraints.Contains(visibilityConstraint)) Content.Constraints.Add(visibilityConstraint);
[9448]772      foreach (var run in runs) {
[9435]773        visibilityConstraint.ConstraintData.Add(run);
774      }
775      visibilityConstraint.Active = true;
[15122]776      Content.UpdateOfRunsInProgress = false;
[9435]777    }
778
[9312]779    private void ClearSelectedRuns() {
780      foreach (var run in selectedRuns) {
781        foreach (var point in runToDataPointMapping[run]) {
782          point.MarkerStyle = MarkerStyle.Circle;
[9404]783          point.Color = Color.FromArgb(255 - LogTransform(transparencyTrackBar.Value), run.Color);
[9312]784        }
785      }
786      selectedRuns.Clear();
787    }
788
[9404]789    // returns a value in [0..255]
790    private int LogTransform(int x) {
791      double min = transparencyTrackBar.Minimum;
792      double max = transparencyTrackBar.Maximum;
793      double r = (x - min) / (max - min);  // r \in [0..1]
[9441]794      double l = Math.Max(Math.Min((1.0 - Math.Pow(0.05, r)) / 0.95, 1), 0); // l \in [0..1]
[9404]795      return (int)Math.Round(255.0 * l);
796    }
797
[4653]798    private void openBoxPlotViewToolStripMenuItem_Click(object sender, EventArgs e) {
799      RunCollectionBoxPlotView boxplotView = new RunCollectionBoxPlotView();
800      boxplotView.Content = this.Content;
801      boxplotView.xAxisComboBox.SelectedItem = xAxisComboBox.SelectedItem;
802      boxplotView.yAxisComboBox.SelectedItem = yAxisComboBox.SelectedItem;
803      boxplotView.Show();
804    }
[9190]805
806    private void getDataAsMatrixToolStripMenuItem_Click(object sender, EventArgs e) {
807      int xCol = Matrix.ColumnNames.ToList().IndexOf(xAxisValue);
[9267]808      int yCol = Matrix.ColumnNames.ToList().IndexOf(yAxisValue);
809
[9190]810      var grouped = new Dictionary<string, List<string>>();
811      Dictionary<double, string> reverseMapping = null;
812      if (categoricalMapping.ContainsKey(xCol))
813        reverseMapping = categoricalMapping[xCol].ToDictionary(x => x.Value, y => y.Key.ToString());
814      foreach (var run in Content.Where(r => r.Visible)) {
815        var x = GetValue(run, xAxisValue);
[9267]816        object y;
817        if (categoricalMapping.ContainsKey(yCol))
818          y = Content.GetValue(run, yAxisValue);
819        else y = GetValue(run, yAxisValue);
820        if (!(x.HasValue && y != null)) continue;
[9190]821
822        var category = reverseMapping == null ? x.Value.ToString() : reverseMapping[x.Value];
823        if (!grouped.ContainsKey(category)) grouped[category] = new List<string>();
[9267]824        grouped[category].Add(y.ToString());
[9190]825      }
826
827      if (!grouped.Any()) return;
828      var matrix = new StringMatrix(grouped.Values.Max(x => x.Count), grouped.Count) {
829        ColumnNames = grouped.Keys.ToArray()
830      };
831      int i = 0;
832      foreach (var col in matrix.ColumnNames) {
833        int j = 0;
834        foreach (var y in grouped[col])
835          matrix[j++, i] = y;
836        i++;
837      }
[9267]838      matrix.SortableView = false;
839      var view = MainFormManager.MainForm.ShowContent(matrix);
840      view.ReadOnly = true;
[9190]841    }
[9276]842
843    private void transparencyTrackBar_ValueChanged(object sender, EventArgs e) {
[9312]844      foreach (var run in Content)
845        UpdateRun(run);
[9276]846    }
[3411]847    #endregion
[4799]848
[9312]849    #region coloring
[9435]850    private void colorResetToolStripMenuItem_Click(object sender, EventArgs e) {
851      Content.UpdateOfRunsInProgress = true;
852
853      IEnumerable<IRun> runs;
854      if (selectedRuns.Any()) runs = selectedRuns;
855      else runs = Content;
856
857      foreach (var run in runs)
858        run.Color = Color.Black;
859      ClearSelectedRuns();
860
861      Content.UpdateOfRunsInProgress = false;
862    }
[9312]863    private void colorDialogButton_Click(object sender, EventArgs e) {
864      if (colorDialog.ShowDialog(this) == DialogResult.OK) {
[9435]865        this.colorRunsButton.Image = this.GenerateImage(16, 16, this.colorDialog.Color);
866        colorRunsButton_Click(sender, e);
[9312]867      }
868    }
869    private Image GenerateImage(int width, int height, Color fillColor) {
870      Image colorImage = new Bitmap(width, height);
871      using (Graphics gfx = Graphics.FromImage(colorImage)) {
872        using (SolidBrush brush = new SolidBrush(fillColor)) {
873          gfx.FillRectangle(brush, 0, 0, width, height);
874        }
875      }
876      return colorImage;
877    }
878
879    private void colorRunsButton_Click(object sender, EventArgs e) {
880      if (!selectedRuns.Any()) return;
881      Content.UpdateOfRunsInProgress = true;
882      foreach (var run in selectedRuns)
883        run.Color = colorDialog.Color;
884
885      ClearSelectedRuns();
886      Content.UpdateOfRunsInProgress = false;
887    }
888
[4799]889    private void colorXAxisButton_Click(object sender, EventArgs e) {
[4845]890      ColorRuns(xAxisValue);
[4799]891    }
892    private void colorYAxisButton_Click(object sender, EventArgs e) {
[4845]893      ColorRuns(yAxisValue);
894    }
895    private void ColorRuns(string axisValue) {
[9235]896      var runs = Content.Where(r => r.Visible).Select(r => new { Run = r, Value = GetValue(r, axisValue) }).Where(r => r.Value.HasValue).ToList();
[4845]897      double minValue = runs.Min(r => r.Value.Value);
898      double maxValue = runs.Max(r => r.Value.Value);
899      double range = maxValue - minValue;
[9236]900      // UpdateOfRunsInProgress has to be set to true, otherwise run_Changed is called all the time (also in other views)
901      Content.UpdateOfRunsInProgress = true;
[9235]902      if (range.IsAlmost(0)) {
903        Color c = ColorGradient.Colors[0];
904        runs.ForEach(r => r.Run.Color = c);
905      } else {
906        int maxColorIndex = ColorGradient.Colors.Count - 1;
907        foreach (var r in runs) {
908          int colorIndex = (int)(maxColorIndex * (r.Value - minValue) / (range));
909          r.Run.Color = ColorGradient.Colors[colorIndex];
910        }
[4799]911      }
[9236]912      Content.UpdateOfRunsInProgress = false;
[4799]913    }
914    #endregion
[3349]915  }
916}
Note: See TracBrowser for help on using the repository browser.