Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 11187 was 11171, checked in by ascheibe, 10 years ago

#2115 merged r11170 (copyright update) into trunk

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