Free cookie consent management tool by TermsFeed Policy Generator

source: branches/PersistenceOverhaul/HeuristicLab.Optimization.Views/3.3/RunCollectionViews/RunCollectionBubbleChartView.cs @ 17597

Last change on this file since 17597 was 12077, checked in by abeham, 10 years ago

#2270: Added suppressUpdates check for Content_Reset events

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