Free cookie consent management tool by TermsFeed Policy Generator

source: branches/PerformanceComparison/HeuristicLab.Optimization.Views/3.3/RunCollectionViews/RunCollectionBubbleChartView.cs @ 15256

Last change on this file since 15256 was 15256, checked in by abeham, 7 years ago

#2457: merged trunk into branch

File size: 37.2 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2016 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using System;
23using System.Collections.Generic;
24using System.ComponentModel;
25using System.Drawing;
26using System.Linq;
27using System.Windows.Forms;
28using System.Windows.Forms.DataVisualization.Charting;
29using HeuristicLab.Common;
30using HeuristicLab.Core;
31using HeuristicLab.Data;
32using HeuristicLab.MainForm;
33using HeuristicLab.MainForm.WindowsForms;
34
35namespace HeuristicLab.Optimization.Views {
36  [View("Bubble Chart")]
37  [Content(typeof(RunCollection), false)]
38  public partial class RunCollectionBubbleChartView : AsynchronousContentView {
39    private enum SizeDimension { Constant = 0 }
40    private enum AxisDimension { Index = 0 }
41
42    private string xAxisValue;
43    private string yAxisValue;
44    private string sizeAxisValue;
45
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();
54    private double xJitterFactor = 0.0;
55    private double yJitterFactor = 0.0;
56    private bool isSelecting = false;
57    private bool suppressUpdates = false;
58
59    private readonly RunCollectionContentConstraint visibilityConstraint = new RunCollectionContentConstraint() { Active = true };
60
61    public RunCollectionBubbleChartView() {
62      InitializeComponent();
63
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());
71      chart.ContextMenuStrip.Opening += new System.ComponentModel.CancelEventHandler(ContextMenuStrip_Opening);
72
73      colorDialog.Color = Color.Orange;
74      colorRunsButton.Image = this.GenerateImage(16, 16, this.colorDialog.Color);
75      isSelecting = false;
76
77      chart.CustomizeAllChartAreas();
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;
82    }
83
84    public new RunCollection Content {
85      get { return (RunCollection)base.Content; }
86      set { base.Content = value; }
87    }
88    public IStringConvertibleMatrix Matrix {
89      get { return this.Content; }
90    }
91    public IEnumerable<IRun> SelectedRuns {
92      get { return selectedRuns; }
93    }
94
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
112    protected override void RegisterContentEvents() {
113      base.RegisterContentEvents();
114      Content.Reset += new EventHandler(Content_Reset);
115      Content.ColumnNamesChanged += new EventHandler(Content_ColumnNamesChanged);
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);
119      Content.OptimizerNameChanged += new EventHandler(Content_AlgorithmNameChanged);
120      Content.UpdateOfRunsInProgressChanged += new EventHandler(Content_UpdateOfRunsInProgressChanged);
121      RegisterRunEvents(Content);
122    }
123    protected override void DeregisterContentEvents() {
124      base.DeregisterContentEvents();
125      Content.Reset -= new EventHandler(Content_Reset);
126      Content.ColumnNamesChanged -= new EventHandler(Content_ColumnNamesChanged);
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);
130      Content.OptimizerNameChanged -= new EventHandler(Content_AlgorithmNameChanged);
131      Content.UpdateOfRunsInProgressChanged -= new EventHandler(Content_UpdateOfRunsInProgressChanged);
132      DeregisterRunEvents(Content);
133    }
134    protected virtual void RegisterRunEvents(IEnumerable<IRun> runs) {
135      foreach (IRun run in runs)
136        run.PropertyChanged += run_PropertyChanged;
137    }
138    protected virtual void DeregisterRunEvents(IEnumerable<IRun> runs) {
139      foreach (IRun run in runs)
140        run.PropertyChanged -= run_PropertyChanged;
141    }
142
143    private void Content_CollectionReset(object sender, HeuristicLab.Collections.CollectionItemsChangedEventArgs<IRun> e) {
144      DeregisterRunEvents(e.OldItems);
145      RegisterRunEvents(e.Items);
146    }
147    private void Content_ItemsRemoved(object sender, HeuristicLab.Collections.CollectionItemsChangedEventArgs<IRun> e) {
148      DeregisterRunEvents(e.Items);
149    }
150    private void Content_ItemsAdded(object sender, HeuristicLab.Collections.CollectionItemsChangedEventArgs<IRun> e) {
151      RegisterRunEvents(e.Items);
152    }
153    private void run_PropertyChanged(object sender, PropertyChangedEventArgs e) {
154      if (suppressUpdates) return;
155      if (InvokeRequired)
156        this.Invoke((Action<object, PropertyChangedEventArgs>)run_PropertyChanged, sender, e);
157      else {
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        }
165      }
166    }
167
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
175        UpdateDataPoints();
176        UpdateAxisLabels();
177      }
178    }
179
180    private void UpdateRun(IRun run) {
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;
186          }
187          if (selectedRuns.Contains(run)) {
188            point.Color = Color.Red;
189            point.MarkerStyle = MarkerStyle.Cross;
190          } else {
191            point.Color = Color.FromArgb(255 - LogTransform(transparencyTrackBar.Value), ((IRun)point.Tag).Color);
192            point.MarkerStyle = MarkerStyle.Circle;
193          }
194
195        }
196        if (!run.Visible) runToDataPointMapping.Remove(run);
197      } else {
198        AddDataPoint(run);
199      }
200
201      if (this.chart.Series[0].Points.Count == 0)
202        noRunsLabel.Visible = true;
203      else
204        noRunsLabel.Visible = false;
205    }
206
207    protected override void OnContentChanged() {
208      base.OnContentChanged();
209      UpdateComboBoxes();
210      UpdateDataPoints();
211      UpdateCaption();
212    }
213
214    private void RebuildInverseIndex() {
215      if (Content != null) {
216        runToIndexMapping.Clear();
217        int i = 0;
218        foreach (var run in Content) {
219          runToIndexMapping.Add(run, i);
220          i++;
221        }
222      }
223    }
224
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
232    private void UpdateCaption() {
233      Caption = Content != null ? Content.OptimizerName + " Bubble Chart" : ViewAttribute.GetViewName(GetType());
234    }
235
236    private void UpdateComboBoxes() {
237      string selectedXAxis = (string)this.xAxisComboBox.SelectedItem;
238      string selectedYAxis = (string)this.yAxisComboBox.SelectedItem;
239      string selectedSizeAxis = (string)this.sizeComboBox.SelectedItem;
240      this.xAxisComboBox.Items.Clear();
241      this.yAxisComboBox.Items.Clear();
242      this.sizeComboBox.Items.Clear();
243      if (Content != null) {
244        string[] additionalAxisDimension = Enum.GetNames(typeof(AxisDimension));
245        this.xAxisComboBox.Items.AddRange(additionalAxisDimension);
246        var comparer = new HeuristicLab.Common.NaturalStringComparer();
247        var sortedColumnNames = Matrix.ColumnNames.ToArray();
248        sortedColumnNames.StableSort(comparer);
249        this.xAxisComboBox.Items.AddRange(sortedColumnNames);
250        this.yAxisComboBox.Items.AddRange(additionalAxisDimension);
251        this.yAxisComboBox.Items.AddRange(sortedColumnNames);
252        string[] additionalSizeDimension = Enum.GetNames(typeof(SizeDimension));
253        this.sizeComboBox.Items.AddRange(additionalSizeDimension);
254        this.sizeComboBox.Items.AddRange(sortedColumnNames);
255        this.sizeComboBox.SelectedItem = SizeDimension.Constant.ToString();
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        }
270        if (changed) {
271          UpdateDataPoints();
272          UpdateAxisLabels();
273        }
274      }
275    }
276
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
283    private void Content_Reset(object sender, EventArgs e) {
284      if (suppressUpdates) return;
285      if (InvokeRequired)
286        Invoke(new EventHandler(Content_Reset), sender, e);
287      else {
288        UpdateDataPoints();
289        UpdateAxisLabels();
290      }
291    }
292
293    private void UpdateDataPoints() {
294      Series series = this.chart.Series[0];
295      series.Points.Clear();
296      runToDataPointMapping.Clear();
297      categoricalMapping.Clear();
298      selectedRuns.Clear();
299      RebuildInverseIndex();
300
301      chart.ChartAreas[0].AxisX.IsMarginVisible = xAxisValue != AxisDimension.Index.ToString();
302      chart.ChartAreas[0].AxisY.IsMarginVisible = yAxisValue != AxisDimension.Index.ToString();
303
304      if (Content != null) {
305        foreach (IRun run in this.Content)
306          this.AddDataPoint(run);
307
308        if (this.chart.Series[0].Points.Count == 0)
309          noRunsLabel.Visible = true;
310        else {
311          noRunsLabel.Visible = false;
312          UpdateMarkerSizes();
313          UpdateCursorInterval();
314        }
315      }
316      xTrackBar.Value = 0;
317      yTrackBar.Value = 0;
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();
325    }
326
327    private void UpdateMarkerSizes() {
328      var series = chart.Series[0];
329      if (series.Points.Count <= 0) return;
330
331      var sizeValues = series.Points.Select(p => p.YValues[1]);
332      double minSizeValue = sizeValues.Min();
333      double maxSizeValue = sizeValues.Max();
334      double sizeRange = maxSizeValue - minSizeValue;
335
336      const int smallestBubbleSize = 7;
337
338      foreach (DataPoint point in series.Points) {
339        //calculates the relative size of the data point  0 <= relativeSize <= 1
340        double relativeSize = (point.YValues[1] - minSizeValue);
341        if (sizeRange > double.Epsilon) {
342          relativeSize /= sizeRange;
343
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;
347
348        double sizeChange = Math.Abs(sizeTrackBar.Value) * relativeSize;
349        point.MarkerSize = (int)Math.Round(sizeChange + smallestBubbleSize);
350      }
351    }
352
353    private void UpdateDataPointJitter() {
354      var xAxis = this.chart.ChartAreas[0].AxisX;
355      var yAxis = this.chart.ChartAreas[0].AxisY;
356
357      double xAxisRange = xAxis.Maximum - xAxis.Minimum;
358      double yAxisRange = yAxis.Maximum - yAxis.Minimum;
359
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))
366          xValue += 0.1 * GetXJitter(run) * xJitterFactor * (xAxisRange);
367        if (!yJitterFactor.IsAlmost(0.0))
368          yValue += 0.1 * GetYJitter(run) * yJitterFactor * (yAxisRange);
369
370        point.XValue = xValue;
371        point.YValues[0] = yValue;
372      }
373
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      }
382    }
383
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
402    private void AddDataPoint(IRun run) {
403      double? xValue;
404      double? yValue;
405      double? sizeValue;
406      Series series = this.chart.Series[0];
407
408      xValue = GetValue(run, xAxisValue);
409      yValue = GetValue(run, yAxisValue);
410      sizeValue = GetValue(run, sizeAxisValue);
411
412      if (xValue.HasValue && yValue.HasValue && sizeValue.HasValue) {
413        xValue = xValue.Value;
414        yValue = yValue.Value;
415
416        if (run.Visible) {
417          DataPoint point = new DataPoint(xValue.Value, new double[] { yValue.Value, sizeValue.Value });
418          point.Tag = run;
419          series.Points.Add(point);
420          if (!runToDataPointMapping.ContainsKey(run)) runToDataPointMapping.Add(run, new List<DataPoint>());
421          runToDataPointMapping[run].Add(point);
422          UpdateRun(run);
423        }
424      }
425    }
426    private double? GetValue(IRun run, string columnName) {
427      if (run == null || string.IsNullOrEmpty(columnName))
428        return null;
429
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;
441
442        DoubleValue doubleValue = value as DoubleValue;
443        IntValue intValue = value as IntValue;
444        TimeSpanValue timeSpanValue = value as TimeSpanValue;
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)
450          ret = intValue.Value;
451        else if (timeSpanValue != null) {
452          ret = timeSpanValue.Value.TotalSeconds;
453        } else
454          ret = GetCategoricalValue(columnIndex, value.ToString());
455
456        return ret;
457      }
458    }
459    private double? GetCategoricalValue(int dimension, string value) {
460      if (!this.categoricalMapping.ContainsKey(dimension)) {
461        this.categoricalMapping[dimension] = new Dictionary<object, double>();
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());
464        int count = 1;
465        foreach (var category in orderedCategories) {
466          this.categoricalMapping[dimension].Add(category, count);
467          count++;
468        }
469      }
470      if (!this.categoricalMapping[dimension].ContainsKey(value)) return null;
471      return this.categoricalMapping[dimension][value];
472    }
473
474    private double GetValue(IRun run, AxisDimension axisDimension) {
475      double value = double.NaN;
476      switch (axisDimension) {
477        case AxisDimension.Index: {
478            value = runToIndexMapping[run];
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    }
500    private void UpdateCursorInterval() {
501      double xMin = double.MaxValue;
502      double xMax = double.MinValue;
503      double yMin = double.MaxValue;
504      double yMax = double.MinValue;
505
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
519      if (xRange.IsAlmost(0.0)) xRange = 1.0;
520      if (yRange.IsAlmost(0.0)) yRange = 1.0;
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;
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;
536    }
537
538    #region Drag & drop and tooltip
539    private void chart_MouseDoubleClick(object sender, MouseEventArgs e) {
540      HitTestResult h = this.chart.HitTest(e.X, e.Y, ChartElementType.DataPoint);
541      if (h.ChartElementType == ChartElementType.DataPoint) {
542        IRun run = (IRun)((DataPoint)h.Object).Tag;
543        IContentView view = MainFormManager.MainForm.ShowContent(run);
544        if (view != null) {
545          view.ReadOnly = this.ReadOnly;
546          view.Locked = this.Locked;
547        }
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;
551      }
552      UpdateAxisLabels();
553    }
554
555    private void chart_MouseUp(object sender, MouseEventArgs e) {
556      if (!isSelecting) return;
557
558      System.Windows.Forms.DataVisualization.Charting.Cursor xCursor = chart.ChartAreas[0].CursorX;
559      System.Windows.Forms.DataVisualization.Charting.Cursor yCursor = chart.ChartAreas[0].CursorY;
560
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
566      if (Control.ModifierKeys != Keys.Control) {
567        ClearSelectedRuns();
568      }
569
570      //check for click to select a single model
571      if (minX == maxX && minY == maxY) {
572        HitTestResult hitTest = chart.HitTest(e.X, e.Y, ChartElementType.DataPoint);
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;
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          }
586        }
587      } else {
588        foreach (DataPoint point in this.chart.Series[0].Points) {
589          if (point.XValue < minX || point.XValue > maxX) continue;
590          if (point.YValues[0] < minY || point.YValues[0] > maxY) continue;
591          point.MarkerStyle = MarkerStyle.Cross;
592          point.Color = Color.Red;
593          IRun run = (IRun)point.Tag;
594          selectedRuns.Add(run);
595        }
596      }
597
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;
600      this.OnChanged();
601    }
602
603    private void chart_MouseMove(object sender, MouseEventArgs e) {
604      if (Control.MouseButtons != MouseButtons.None) return;
605      HitTestResult h = this.chart.HitTest(e.X, e.Y);
606      string newTooltipText = string.Empty;
607      string oldTooltipText;
608      if (h.ChartElementType == ChartElementType.DataPoint) {
609        IRun run = (IRun)((DataPoint)h.Object).Tag;
610        newTooltipText = BuildTooltip(run);
611      } else if (h.ChartElementType == ChartElementType.AxisLabels) {
612        newTooltipText = ((CustomLabel)h.Object).ToolTip;
613      }
614
615      oldTooltipText = this.tooltip.GetToolTip(chart);
616      if (newTooltipText != oldTooltipText)
617        this.tooltip.SetToolTip(chart, newTooltipText);
618    }
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
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);
637        xString = string.Format("{0:00}:{1:00}:{2:00.00}", (int)time.TotalHours, time.Minutes, time.Seconds);
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);
642        yString = string.Format("{0:00}:{1:00}:{2:00.00}", (int)time.TotalHours, time.Minutes, time.Seconds);
643      }
644
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    }
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;
667      UpdateDataPointJitter();
668    }
669    private void sizeTrackBar_ValueChanged(object sender, EventArgs e) {
670      UpdateMarkerSizes();
671    }
672
673    private void AxisComboBox_SelectedValueChanged(object sender, EventArgs e) {
674      bool axisSelected = xAxisComboBox.SelectedIndex != -1 && yAxisComboBox.SelectedIndex != -1;
675      xTrackBar.Enabled = yTrackBar.Enabled = axisSelected;
676      colorXAxisButton.Enabled = colorYAxisButton.Enabled = axisSelected;
677
678      xAxisValue = (string)xAxisComboBox.SelectedItem;
679      yAxisValue = (string)yAxisComboBox.SelectedItem;
680      sizeAxisValue = (string)sizeComboBox.SelectedItem;
681
682      UpdateDataPoints();
683      UpdateAxisLabels();
684    }
685    private void UpdateAxisLabels() {
686      Axis xAxis = this.chart.ChartAreas[0].AxisX;
687      Axis yAxis = this.chart.ChartAreas[0].AxisY;
688      int axisDimensionCount = Enum.GetNames(typeof(AxisDimension)).Count();
689      //mkommend: combobox.SelectedIndex could not be used as this changes during hovering over possible values
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;
696      if (yAxisValue != null)
697        yAxis.Title = yAxisValue;
698    }
699
700    private void chart_AxisViewChanged(object sender, System.Windows.Forms.DataVisualization.Charting.ViewEventArgs e) {
701      this.UpdateAxisLabels();
702    }
703
704    private void SetCustomAxisLabels(Axis axis, int dimension) {
705      axis.CustomLabels.Clear();
706      if (categoricalMapping.ContainsKey(dimension)) {
707        foreach (var pair in categoricalMapping[dimension]) {
708          string labelText = pair.Key.ToString();
709          CustomLabel label = new CustomLabel();
710          label.ToolTip = labelText;
711          if (labelText.Length > 25)
712            labelText = labelText.Substring(0, 25) + " ... ";
713          label.Text = labelText;
714          label.GridTicks = GridTickTypes.TickMark;
715          label.FromPosition = pair.Value - 0.5;
716          label.ToPosition = pair.Value + 0.5;
717          axis.CustomLabels.Add(label);
718        }
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);
723          string x = string.Format("{0:00}:{1:00}:{2:00}", time.Hours, time.Minutes, time.Seconds);
724          axis.CustomLabels.Add(i - axis.LabelStyle.Interval / 2, i + axis.LabelStyle.Interval / 2, x);
725        }
726      }
727    }
728
729    private void zoomButton_CheckedChanged(object sender, EventArgs e) {
730      this.isSelecting = selectButton.Checked;
731      this.colorRunsButton.Enabled = this.isSelecting;
732      this.colorDialogButton.Enabled = this.isSelecting;
733      this.hideRunsButton.Enabled = this.isSelecting;
734      this.chart.ChartAreas[0].AxisX.ScaleView.Zoomable = !isSelecting;
735      this.chart.ChartAreas[0].AxisY.ScaleView.Zoomable = !isSelecting;
736      ClearSelectedRuns();
737    }
738
739    private void ContextMenuStrip_Opening(object sender, System.ComponentModel.CancelEventArgs e) {
740      hideRunsToolStripMenuItem.Visible = selectedRuns.Any();
741    }
742
743    private void unhideAllRunToolStripMenuItem_Click(object sender, EventArgs e) {
744      visibilityConstraint.ConstraintData.Clear();
745      if (Content.Constraints.Contains(visibilityConstraint)) Content.Constraints.Remove(visibilityConstraint);
746    }
747    private void hideRunsToolStripMenuItem_Click(object sender, EventArgs e) {
748      HideRuns(selectedRuns);
749      //could not use ClearSelectedRuns as the runs are not visible anymore
750      selectedRuns.Clear();
751    }
752    private void hideRunsButton_Click(object sender, EventArgs e) {
753      HideRuns(selectedRuns);
754      //could not use ClearSelectedRuns as the runs are not visible anymore
755      selectedRuns.Clear();
756    }
757
758    private void HideRuns(IEnumerable<IRun> runs) {
759      Content.UpdateOfRunsInProgress = true;
760      visibilityConstraint.Active = false;
761      if (!Content.Constraints.Contains(visibilityConstraint)) Content.Constraints.Add(visibilityConstraint);
762      foreach (var run in runs) {
763        visibilityConstraint.ConstraintData.Add(run);
764      }
765      visibilityConstraint.Active = true;
766      Content.UpdateOfRunsInProgress = false;
767    }
768
769    private void ClearSelectedRuns() {
770      foreach (var run in selectedRuns) {
771        foreach (var point in runToDataPointMapping[run]) {
772          point.MarkerStyle = MarkerStyle.Circle;
773          point.Color = Color.FromArgb(255 - LogTransform(transparencyTrackBar.Value), run.Color);
774        }
775      }
776      selectedRuns.Clear();
777    }
778
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]
784      double l = Math.Max(Math.Min((1.0 - Math.Pow(0.05, r)) / 0.95, 1), 0); // l \in [0..1]
785      return (int)Math.Round(255.0 * l);
786    }
787
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    }
795
796    private void getDataAsMatrixToolStripMenuItem_Click(object sender, EventArgs e) {
797      int xCol = Matrix.ColumnNames.ToList().IndexOf(xAxisValue);
798      int yCol = Matrix.ColumnNames.ToList().IndexOf(yAxisValue);
799
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);
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;
811
812        var category = reverseMapping == null ? x.Value.ToString() : reverseMapping[x.Value];
813        if (!grouped.ContainsKey(category)) grouped[category] = new List<string>();
814        grouped[category].Add(y.ToString());
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      }
828      matrix.SortableView = false;
829      var view = MainFormManager.MainForm.ShowContent(matrix);
830      view.ReadOnly = true;
831    }
832
833    private void transparencyTrackBar_ValueChanged(object sender, EventArgs e) {
834      foreach (var run in Content)
835        UpdateRun(run);
836    }
837    #endregion
838
839    #region coloring
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    }
853    private void colorDialogButton_Click(object sender, EventArgs e) {
854      if (colorDialog.ShowDialog(this) == DialogResult.OK) {
855        this.colorRunsButton.Image = this.GenerateImage(16, 16, this.colorDialog.Color);
856        colorRunsButton_Click(sender, e);
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
879    private void colorXAxisButton_Click(object sender, EventArgs e) {
880      ColorRuns(xAxisValue);
881    }
882    private void colorYAxisButton_Click(object sender, EventArgs e) {
883      ColorRuns(yAxisValue);
884    }
885    private void ColorRuns(string axisValue) {
886      var runs = Content.Where(r => r.Visible).Select(r => new { Run = r, Value = GetValue(r, axisValue) }).Where(r => r.Value.HasValue).ToList();
887      double minValue = runs.Min(r => r.Value.Value);
888      double maxValue = runs.Max(r => r.Value.Value);
889      double range = maxValue - minValue;
890      // UpdateOfRunsInProgress has to be set to true, otherwise run_Changed is called all the time (also in other views)
891      Content.UpdateOfRunsInProgress = true;
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        }
901      }
902      Content.UpdateOfRunsInProgress = false;
903    }
904    #endregion
905  }
906}
Note: See TracBrowser for help on using the repository browser.