Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 12214 was 12009, checked in by ascheibe, 10 years ago

#2212 updated copyright year

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