Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2901_StaticSelectionMethods/HeuristicLab.Optimization.Views/3.3/RunCollectionViews/RunCollectionBubbleChartView.cs @ 16375

Last change on this file since 16375 was 15583, checked in by swagner, 7 years ago

#2640: Updated year of copyrights in license headers

File size: 37.1 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2018 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
438        IItem value = Content.GetValue(run, columnName);
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          int columnIndex = Matrix.ColumnNames.ToList().IndexOf(columnName);
455          ret = GetCategoricalValue(columnIndex, value.ToString());
456        }
457
458        return ret;
459      }
460    }
461    private double? GetCategoricalValue(int dimension, string value) {
462      if (!this.categoricalMapping.ContainsKey(dimension)) {
463        this.categoricalMapping[dimension] = new Dictionary<object, double>();
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());
466        int count = 1;
467        foreach (var category in orderedCategories) {
468          this.categoricalMapping[dimension].Add(category, count);
469          count++;
470        }
471      }
472      if (!this.categoricalMapping[dimension].ContainsKey(value)) return null;
473      return this.categoricalMapping[dimension][value];
474    }
475
476    private double GetValue(IRun run, AxisDimension axisDimension) {
477      double value = double.NaN;
478      switch (axisDimension) {
479        case AxisDimension.Index: {
480            value = runToIndexMapping[run];
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    }
502    private void UpdateCursorInterval() {
503      double xMin = double.MaxValue;
504      double xMax = double.MinValue;
505      double yMin = double.MaxValue;
506      double yMax = double.MinValue;
507
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
521      if (xRange.IsAlmost(0.0)) xRange = 1.0;
522      if (yRange.IsAlmost(0.0)) yRange = 1.0;
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;
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;
538    }
539
540    #region Drag & drop and tooltip
541    private void chart_MouseDoubleClick(object sender, MouseEventArgs e) {
542      HitTestResult h = this.chart.HitTest(e.X, e.Y, ChartElementType.DataPoint);
543      if (h.ChartElementType == ChartElementType.DataPoint) {
544        IRun run = (IRun)((DataPoint)h.Object).Tag;
545        IContentView view = MainFormManager.MainForm.ShowContent(run);
546        if (view != null) {
547          view.ReadOnly = this.ReadOnly;
548          view.Locked = this.Locked;
549        }
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;
553      }
554      UpdateAxisLabels();
555    }
556
557    private void chart_MouseUp(object sender, MouseEventArgs e) {
558      if (!isSelecting) return;
559
560      System.Windows.Forms.DataVisualization.Charting.Cursor xCursor = chart.ChartAreas[0].CursorX;
561      System.Windows.Forms.DataVisualization.Charting.Cursor yCursor = chart.ChartAreas[0].CursorY;
562
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
568      if (Control.ModifierKeys != Keys.Control) {
569        ClearSelectedRuns();
570      }
571
572      //check for click to select a single model
573      if (minX == maxX && minY == maxY) {
574        HitTestResult hitTest = chart.HitTest(e.X, e.Y, ChartElementType.DataPoint);
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;
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          }
588        }
589      } else {
590        foreach (DataPoint point in this.chart.Series[0].Points) {
591          if (point.XValue < minX || point.XValue > maxX) continue;
592          if (point.YValues[0] < minY || point.YValues[0] > maxY) continue;
593          point.MarkerStyle = MarkerStyle.Cross;
594          point.Color = Color.Red;
595          IRun run = (IRun)point.Tag;
596          selectedRuns.Add(run);
597        }
598      }
599
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;
602      this.OnChanged();
603    }
604
605    private void chart_MouseMove(object sender, MouseEventArgs e) {
606      if (Control.MouseButtons != MouseButtons.None) return;
607      HitTestResult h = this.chart.HitTest(e.X, e.Y);
608      string newTooltipText = string.Empty;
609      string oldTooltipText;
610      if (h.ChartElementType == ChartElementType.DataPoint) {
611        IRun run = (IRun)((DataPoint)h.Object).Tag;
612        newTooltipText = BuildTooltip(run);
613      } else if (h.ChartElementType == ChartElementType.AxisLabels) {
614        newTooltipText = ((CustomLabel)h.Object).ToolTip;
615      }
616
617      oldTooltipText = this.tooltip.GetToolTip(chart);
618      if (newTooltipText != oldTooltipText)
619        this.tooltip.SetToolTip(chart, newTooltipText);
620    }
621
622    private string BuildTooltip(IRun run) {
623      string tooltip;
624      tooltip = run.Name + System.Environment.NewLine;
625
626      string xString = GetTooltipValue(run, (string)xAxisComboBox.SelectedItem);
627      string yString = GetTooltipValue(run, (string)yAxisComboBox.SelectedItem);
628      string sizeString = GetTooltipValue(run, (string)sizeComboBox.SelectedItem);
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    }
636
637    private string GetTooltipValue(IRun run, string columnName) {
638      if (columnName == SizeDimension.Constant.ToString())
639        return string.Empty;
640
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    }
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;
677      UpdateDataPointJitter();
678    }
679    private void sizeTrackBar_ValueChanged(object sender, EventArgs e) {
680      UpdateMarkerSizes();
681    }
682
683    private void AxisComboBox_SelectedValueChanged(object sender, EventArgs e) {
684      bool axisSelected = xAxisComboBox.SelectedIndex != -1 && yAxisComboBox.SelectedIndex != -1;
685      xTrackBar.Enabled = yTrackBar.Enabled = axisSelected;
686      colorXAxisButton.Enabled = colorYAxisButton.Enabled = axisSelected;
687
688      xAxisValue = (string)xAxisComboBox.SelectedItem;
689      yAxisValue = (string)yAxisComboBox.SelectedItem;
690      sizeAxisValue = (string)sizeComboBox.SelectedItem;
691
692      UpdateDataPoints();
693      UpdateAxisLabels();
694    }
695    private void UpdateAxisLabels() {
696      Axis xAxis = this.chart.ChartAreas[0].AxisX;
697      Axis yAxis = this.chart.ChartAreas[0].AxisY;
698      int axisDimensionCount = Enum.GetNames(typeof(AxisDimension)).Count();
699      //mkommend: combobox.SelectedIndex could not be used as this changes during hovering over possible values
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;
706      if (yAxisValue != null)
707        yAxis.Title = yAxisValue;
708    }
709
710    private void chart_AxisViewChanged(object sender, System.Windows.Forms.DataVisualization.Charting.ViewEventArgs e) {
711      this.UpdateAxisLabels();
712    }
713
714    private void SetCustomAxisLabels(Axis axis, int dimension) {
715      axis.CustomLabels.Clear();
716      if (categoricalMapping.ContainsKey(dimension)) {
717        foreach (var pair in categoricalMapping[dimension]) {
718          string labelText = pair.Key.ToString();
719          CustomLabel label = new CustomLabel();
720          label.ToolTip = labelText;
721          if (labelText.Length > 25)
722            labelText = labelText.Substring(0, 25) + " ... ";
723          label.Text = labelText;
724          label.GridTicks = GridTickTypes.TickMark;
725          label.FromPosition = pair.Value - 0.5;
726          label.ToPosition = pair.Value + 0.5;
727          axis.CustomLabels.Add(label);
728        }
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);
733          string x = string.Format("{0:00}:{1:00}:{2:00}", time.Hours, time.Minutes, time.Seconds);
734          axis.CustomLabels.Add(i - axis.LabelStyle.Interval / 2, i + axis.LabelStyle.Interval / 2, x);
735        }
736      }
737    }
738
739    private void zoomButton_CheckedChanged(object sender, EventArgs e) {
740      this.isSelecting = selectButton.Checked;
741      this.colorRunsButton.Enabled = this.isSelecting;
742      this.colorDialogButton.Enabled = this.isSelecting;
743      this.hideRunsButton.Enabled = this.isSelecting;
744      this.chart.ChartAreas[0].AxisX.ScaleView.Zoomable = !isSelecting;
745      this.chart.ChartAreas[0].AxisY.ScaleView.Zoomable = !isSelecting;
746      ClearSelectedRuns();
747    }
748
749    private void ContextMenuStrip_Opening(object sender, System.ComponentModel.CancelEventArgs e) {
750      hideRunsToolStripMenuItem.Visible = selectedRuns.Any();
751    }
752
753    private void unhideAllRunToolStripMenuItem_Click(object sender, EventArgs e) {
754      visibilityConstraint.ConstraintData.Clear();
755      if (Content.Constraints.Contains(visibilityConstraint)) Content.Constraints.Remove(visibilityConstraint);
756    }
757    private void hideRunsToolStripMenuItem_Click(object sender, EventArgs e) {
758      HideRuns(selectedRuns);
759      //could not use ClearSelectedRuns as the runs are not visible anymore
760      selectedRuns.Clear();
761    }
762    private void hideRunsButton_Click(object sender, EventArgs e) {
763      HideRuns(selectedRuns);
764      //could not use ClearSelectedRuns as the runs are not visible anymore
765      selectedRuns.Clear();
766    }
767
768    private void HideRuns(IEnumerable<IRun> runs) {
769      Content.UpdateOfRunsInProgress = true;
770      visibilityConstraint.Active = false;
771      if (!Content.Constraints.Contains(visibilityConstraint)) Content.Constraints.Add(visibilityConstraint);
772      foreach (var run in runs) {
773        visibilityConstraint.ConstraintData.Add(run);
774      }
775      visibilityConstraint.Active = true;
776      Content.UpdateOfRunsInProgress = false;
777    }
778
779    private void ClearSelectedRuns() {
780      foreach (var run in selectedRuns) {
781        foreach (var point in runToDataPointMapping[run]) {
782          point.MarkerStyle = MarkerStyle.Circle;
783          point.Color = Color.FromArgb(255 - LogTransform(transparencyTrackBar.Value), run.Color);
784        }
785      }
786      selectedRuns.Clear();
787    }
788
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]
794      double l = Math.Max(Math.Min((1.0 - Math.Pow(0.05, r)) / 0.95, 1), 0); // l \in [0..1]
795      return (int)Math.Round(255.0 * l);
796    }
797
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    }
805
806    private void getDataAsMatrixToolStripMenuItem_Click(object sender, EventArgs e) {
807      int xCol = Matrix.ColumnNames.ToList().IndexOf(xAxisValue);
808      int yCol = Matrix.ColumnNames.ToList().IndexOf(yAxisValue);
809
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);
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;
821
822        var category = reverseMapping == null ? x.Value.ToString() : reverseMapping[x.Value];
823        if (!grouped.ContainsKey(category)) grouped[category] = new List<string>();
824        grouped[category].Add(y.ToString());
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      }
838      matrix.SortableView = false;
839      var view = MainFormManager.MainForm.ShowContent(matrix);
840      view.ReadOnly = true;
841    }
842
843    private void transparencyTrackBar_ValueChanged(object sender, EventArgs e) {
844      foreach (var run in Content)
845        UpdateRun(run);
846    }
847    #endregion
848
849    #region coloring
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    }
863    private void colorDialogButton_Click(object sender, EventArgs e) {
864      if (colorDialog.ShowDialog(this) == DialogResult.OK) {
865        this.colorRunsButton.Image = this.GenerateImage(16, 16, this.colorDialog.Color);
866        colorRunsButton_Click(sender, e);
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
889    private void colorXAxisButton_Click(object sender, EventArgs e) {
890      ColorRuns(xAxisValue);
891    }
892    private void colorYAxisButton_Click(object sender, EventArgs e) {
893      ColorRuns(yAxisValue);
894    }
895    private void ColorRuns(string axisValue) {
896      var runs = Content.Where(r => r.Visible).Select(r => new { Run = r, Value = GetValue(r, axisValue) }).Where(r => r.Value.HasValue).ToList();
897      double minValue = runs.Min(r => r.Value.Value);
898      double maxValue = runs.Max(r => r.Value.Value);
899      double range = maxValue - minValue;
900      // UpdateOfRunsInProgress has to be set to true, otherwise run_Changed is called all the time (also in other views)
901      Content.UpdateOfRunsInProgress = true;
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        }
911      }
912      Content.UpdateOfRunsInProgress = false;
913    }
914    #endregion
915  }
916}
Note: See TracBrowser for help on using the repository browser.