Free cookie consent management tool by TermsFeed Policy Generator

source: branches/gteufl/HeuristicLab.Optimization.Views/3.3/RunCollectionViews/RunCollectionBubbleChartView.cs @ 12560

Last change on this file since 12560 was 9910, checked in by ascheibe, 11 years ago

#2099 renamed run collection views

File size: 36.3 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2013 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 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        foreach (var run in Content) UpdateRun(run);
156        UpdateMarkerSizes();
157        UpdateCursorInterval();
158        chart.ChartAreas[0].RecalculateAxesScale();
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      this.categoricalMapping.Clear();
193      UpdateComboBoxes();
194      UpdateDataPoints();
195      UpdateCaption();
196      RebuildInverseIndex();
197    }
198
199    private void RebuildInverseIndex() {
200      if (Content != null) {
201        runToIndexMapping.Clear();
202        int i = 0;
203        foreach (var run in Content) {
204          runToIndexMapping.Add(run, i);
205          i++;
206        }
207      }
208    }
209
210    private void Content_ColumnNamesChanged(object sender, EventArgs e) {
211      if (InvokeRequired)
212        Invoke(new EventHandler(Content_ColumnNamesChanged), sender, e);
213      else
214        UpdateComboBoxes();
215    }
216
217    private void UpdateCaption() {
218      Caption = Content != null ? Content.OptimizerName + " Bubble Chart" : ViewAttribute.GetViewName(GetType());
219    }
220
221    private void UpdateComboBoxes() {
222      string selectedXAxis = (string)this.xAxisComboBox.SelectedItem;
223      string selectedYAxis = (string)this.yAxisComboBox.SelectedItem;
224      string selectedSizeAxis = (string)this.sizeComboBox.SelectedItem;
225      this.xAxisComboBox.Items.Clear();
226      this.yAxisComboBox.Items.Clear();
227      this.sizeComboBox.Items.Clear();
228      if (Content != null) {
229        string[] additionalAxisDimension = Enum.GetNames(typeof(AxisDimension));
230        this.xAxisComboBox.Items.AddRange(additionalAxisDimension);
231        this.xAxisComboBox.Items.AddRange(Matrix.ColumnNames.ToArray());
232        this.yAxisComboBox.Items.AddRange(additionalAxisDimension);
233        this.yAxisComboBox.Items.AddRange(Matrix.ColumnNames.ToArray());
234        string[] additionalSizeDimension = Enum.GetNames(typeof(SizeDimension));
235        this.sizeComboBox.Items.AddRange(additionalSizeDimension);
236        this.sizeComboBox.Items.AddRange(Matrix.ColumnNames.ToArray());
237        this.sizeComboBox.SelectedItem = SizeDimension.Constant.ToString();
238
239        bool changed = false;
240        if (selectedXAxis != null && xAxisComboBox.Items.Contains(selectedXAxis)) {
241          xAxisComboBox.SelectedItem = selectedXAxis;
242          changed = true;
243        }
244        if (selectedYAxis != null && yAxisComboBox.Items.Contains(selectedYAxis)) {
245          yAxisComboBox.SelectedItem = selectedYAxis;
246          changed = true;
247        }
248        if (selectedSizeAxis != null && sizeComboBox.Items.Contains(selectedSizeAxis)) {
249          sizeComboBox.SelectedItem = selectedSizeAxis;
250          changed = true;
251        }
252        if (changed) {
253          UpdateDataPoints();
254          UpdateAxisLabels();
255        }
256      }
257    }
258
259    private void Content_AlgorithmNameChanged(object sender, EventArgs e) {
260      if (InvokeRequired)
261        Invoke(new EventHandler(Content_AlgorithmNameChanged), sender, e);
262      else UpdateCaption();
263    }
264
265    private void Content_Reset(object sender, EventArgs e) {
266      if (InvokeRequired)
267        Invoke(new EventHandler(Content_Reset), sender, e);
268      else {
269        this.categoricalMapping.Clear();
270        RebuildInverseIndex();
271        UpdateDataPoints();
272        UpdateAxisLabels();
273      }
274    }
275
276    private void UpdateDataPoints() {
277      Series series = this.chart.Series[0];
278      series.Points.Clear();
279      runToDataPointMapping.Clear();
280      selectedRuns.Clear();
281
282      chart.ChartAreas[0].AxisX.IsMarginVisible = xAxisValue != AxisDimension.Index.ToString();
283      chart.ChartAreas[0].AxisY.IsMarginVisible = yAxisValue != AxisDimension.Index.ToString();
284
285      if (Content != null) {
286        foreach (IRun run in this.Content)
287          this.AddDataPoint(run);
288
289        if (this.chart.Series[0].Points.Count == 0)
290          noRunsLabel.Visible = true;
291        else {
292          noRunsLabel.Visible = false;
293          UpdateMarkerSizes();
294          UpdateCursorInterval();
295        }
296      }
297      xTrackBar.Value = 0;
298      yTrackBar.Value = 0;
299
300      //needed to set axis back to automatic and refresh them, otherwise their values may remain NaN
301      var xAxis = chart.ChartAreas[0].AxisX;
302      var yAxis = chart.ChartAreas[0].AxisY;
303      SetAutomaticUpdateOfAxis(xAxis, true);
304      SetAutomaticUpdateOfAxis(yAxis, true);
305      chart.Refresh();
306    }
307
308    private void UpdateMarkerSizes() {
309      var series = chart.Series[0];
310      if (series.Points.Count <= 0) return;
311
312      var sizeValues = series.Points.Select(p => p.YValues[1]);
313      double minSizeValue = sizeValues.Min();
314      double maxSizeValue = sizeValues.Max();
315      double sizeRange = maxSizeValue - minSizeValue;
316
317      const int smallestBubbleSize = 7;
318
319      foreach (DataPoint point in series.Points) {
320        //calculates the relative size of the data point  0 <= relativeSize <= 1
321        double relativeSize = (point.YValues[1] - minSizeValue);
322        if (sizeRange > double.Epsilon) {
323          relativeSize /= sizeRange;
324
325          //invert bubble sizes if the value of the trackbar is negative
326          if (sizeTrackBar.Value < 0) relativeSize = Math.Abs(relativeSize - 1);
327        } else relativeSize = 1;
328
329        double sizeChange = Math.Abs(sizeTrackBar.Value) * relativeSize;
330        point.MarkerSize = (int)Math.Round(sizeChange + smallestBubbleSize);
331      }
332    }
333
334    private void UpdateDataPointJitter() {
335      var xAxis = this.chart.ChartAreas[0].AxisX;
336      var yAxis = this.chart.ChartAreas[0].AxisY;
337
338      double xAxisRange = xAxis.Maximum - xAxis.Minimum;
339      double yAxisRange = yAxis.Maximum - yAxis.Minimum;
340
341      foreach (DataPoint point in chart.Series[0].Points) {
342        IRun run = (IRun)point.Tag;
343        double xValue = GetValue(run, xAxisValue).Value;
344        double yValue = GetValue(run, yAxisValue).Value;
345
346        if (!xJitterFactor.IsAlmost(0.0))
347          xValue += 0.1 * GetXJitter(run) * xJitterFactor * (xAxisRange);
348        if (!yJitterFactor.IsAlmost(0.0))
349          yValue += 0.1 * GetYJitter(run) * yJitterFactor * (yAxisRange);
350
351        point.XValue = xValue;
352        point.YValues[0] = yValue;
353      }
354
355      if (xJitterFactor.IsAlmost(0.0) && yJitterFactor.IsAlmost(0.0)) {
356        SetAutomaticUpdateOfAxis(xAxis, true);
357        SetAutomaticUpdateOfAxis(yAxis, true);
358        chart.ChartAreas[0].RecalculateAxesScale();
359      } else {
360        SetAutomaticUpdateOfAxis(xAxis, false);
361        SetAutomaticUpdateOfAxis(yAxis, false);
362      }
363    }
364
365    // sets an axis to automatic or restrains it to its current values
366    // this is used that none of the set values is changed when jitter is applied, so that the chart stays the same
367    private void SetAutomaticUpdateOfAxis(Axis axis, bool enabled) {
368      if (enabled) {
369        axis.Maximum = double.NaN;
370        axis.Minimum = double.NaN;
371        axis.MajorGrid.Interval = double.NaN;
372        axis.MajorTickMark.Interval = double.NaN;
373        axis.LabelStyle.Interval = double.NaN;
374      } else {
375        axis.Minimum = axis.Minimum;
376        axis.Maximum = axis.Maximum;
377        axis.MajorGrid.Interval = axis.MajorGrid.Interval;
378        axis.MajorTickMark.Interval = axis.MajorTickMark.Interval;
379        axis.LabelStyle.Interval = axis.LabelStyle.Interval;
380      }
381    }
382
383    private void AddDataPoint(IRun run) {
384      double? xValue;
385      double? yValue;
386      double? sizeValue;
387      Series series = this.chart.Series[0];
388
389      xValue = GetValue(run, xAxisValue);
390      yValue = GetValue(run, yAxisValue);
391      sizeValue = GetValue(run, sizeAxisValue);
392
393      if (xValue.HasValue && yValue.HasValue && sizeValue.HasValue) {
394        xValue = xValue.Value;
395        yValue = yValue.Value;
396
397        if (run.Visible) {
398          DataPoint point = new DataPoint(xValue.Value, new double[] { yValue.Value, sizeValue.Value });
399          point.Tag = run;
400          series.Points.Add(point);
401          if (!runToDataPointMapping.ContainsKey(run)) runToDataPointMapping.Add(run, new List<DataPoint>());
402          runToDataPointMapping[run].Add(point);
403          UpdateRun(run);
404        }
405      }
406    }
407    private double? GetValue(IRun run, string columnName) {
408      if (run == null || string.IsNullOrEmpty(columnName))
409        return null;
410
411      if (Enum.IsDefined(typeof(AxisDimension), columnName)) {
412        AxisDimension axisDimension = (AxisDimension)Enum.Parse(typeof(AxisDimension), columnName);
413        return GetValue(run, axisDimension);
414      } else if (Enum.IsDefined(typeof(SizeDimension), columnName)) {
415        SizeDimension sizeDimension = (SizeDimension)Enum.Parse(typeof(SizeDimension), columnName);
416        return GetValue(run, sizeDimension);
417      } else {
418        int columnIndex = Matrix.ColumnNames.ToList().IndexOf(columnName);
419        IItem value = Content.GetValue(run, columnIndex);
420        if (value == null)
421          return null;
422
423        DoubleValue doubleValue = value as DoubleValue;
424        IntValue intValue = value as IntValue;
425        TimeSpanValue timeSpanValue = value as TimeSpanValue;
426        double? ret = null;
427        if (doubleValue != null) {
428          if (!double.IsNaN(doubleValue.Value) && !double.IsInfinity(doubleValue.Value))
429            ret = doubleValue.Value;
430        } else if (intValue != null)
431          ret = intValue.Value;
432        else if (timeSpanValue != null) {
433          ret = timeSpanValue.Value.TotalSeconds;
434        } else
435          ret = GetCategoricalValue(columnIndex, value.ToString());
436
437        return ret;
438      }
439    }
440    private double GetCategoricalValue(int dimension, string value) {
441      if (!this.categoricalMapping.ContainsKey(dimension)) {
442        this.categoricalMapping[dimension] = new Dictionary<object, double>();
443        var orderedCategories = Content.Where(r => r.Visible && Content.GetValue(r, dimension) != null).Select(r => Content.GetValue(r, dimension).ToString())
444                                    .Distinct().OrderBy(x => x, new NaturalStringComparer());
445        int count = 1;
446        foreach (var category in orderedCategories) {
447          this.categoricalMapping[dimension].Add(category, count);
448          count++;
449        }
450      }
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      SetCustomAxisLabels(xAxis, xAxisComboBox.SelectedIndex - axisDimensionCount);
670      SetCustomAxisLabels(yAxis, yAxisComboBox.SelectedIndex - axisDimensionCount);
671      if (xAxisComboBox.SelectedItem != null)
672        xAxis.Title = xAxisComboBox.SelectedItem.ToString();
673      if (yAxisComboBox.SelectedItem != null)
674        yAxis.Title = yAxisComboBox.SelectedItem.ToString();
675    }
676
677    private void chart_AxisViewChanged(object sender, System.Windows.Forms.DataVisualization.Charting.ViewEventArgs e) {
678      this.UpdateAxisLabels();
679    }
680
681    private void SetCustomAxisLabels(Axis axis, int dimension) {
682      axis.CustomLabels.Clear();
683      if (categoricalMapping.ContainsKey(dimension)) {
684        foreach (var pair in categoricalMapping[dimension]) {
685          string labelText = pair.Key.ToString();
686          CustomLabel label = new CustomLabel();
687          label.ToolTip = labelText;
688          if (labelText.Length > 25)
689            labelText = labelText.Substring(0, 25) + " ... ";
690          label.Text = labelText;
691          label.GridTicks = GridTickTypes.TickMark;
692          label.FromPosition = pair.Value - 0.5;
693          label.ToPosition = pair.Value + 0.5;
694          axis.CustomLabels.Add(label);
695        }
696      } else if (dimension > 0 && Content.GetValue(0, dimension) is TimeSpanValue) {
697        this.chart.ChartAreas[0].RecalculateAxesScale();
698        for (double i = axis.Minimum; i <= axis.Maximum; i += axis.LabelStyle.Interval) {
699          TimeSpan time = TimeSpan.FromSeconds(i);
700          string x = string.Format("{0:00}:{1:00}:{2:00}", time.Hours, time.Minutes, time.Seconds);
701          axis.CustomLabels.Add(i - axis.LabelStyle.Interval / 2, i + axis.LabelStyle.Interval / 2, x);
702        }
703      }
704    }
705
706    private void zoomButton_CheckedChanged(object sender, EventArgs e) {
707      this.isSelecting = selectButton.Checked;
708      this.colorRunsButton.Enabled = this.isSelecting;
709      this.colorDialogButton.Enabled = this.isSelecting;
710      this.hideRunsButton.Enabled = this.isSelecting;
711      this.chart.ChartAreas[0].AxisX.ScaleView.Zoomable = !isSelecting;
712      this.chart.ChartAreas[0].AxisY.ScaleView.Zoomable = !isSelecting;
713      ClearSelectedRuns();
714    }
715
716    private void ContextMenuStrip_Opening(object sender, System.ComponentModel.CancelEventArgs e) {
717      hideRunsToolStripMenuItem.Visible = selectedRuns.Any();
718    }
719
720    private void unhideAllRunToolStripMenuItem_Click(object sender, EventArgs e) {
721      visibilityConstraint.ConstraintData.Clear();
722      if (Content.Constraints.Contains(visibilityConstraint)) Content.Constraints.Remove(visibilityConstraint);
723    }
724    private void hideRunsToolStripMenuItem_Click(object sender, EventArgs e) {
725      HideRuns(selectedRuns);
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      HideRuns(selectedRuns);
731      //could not use ClearSelectedRuns as the runs are not visible anymore
732      selectedRuns.Clear();
733    }
734
735    private void HideRuns(IEnumerable<IRun> runs) {
736      visibilityConstraint.Active = false;
737      if (!Content.Constraints.Contains(visibilityConstraint)) Content.Constraints.Add(visibilityConstraint);
738      foreach (var run in runs) {
739        visibilityConstraint.ConstraintData.Add(run);
740      }
741      visibilityConstraint.Active = true;
742    }
743
744    private void ClearSelectedRuns() {
745      foreach (var run in selectedRuns) {
746        foreach (var point in runToDataPointMapping[run]) {
747          point.MarkerStyle = MarkerStyle.Circle;
748          point.Color = Color.FromArgb(255 - LogTransform(transparencyTrackBar.Value), run.Color);
749        }
750      }
751      selectedRuns.Clear();
752    }
753
754    // returns a value in [0..255]
755    private int LogTransform(int x) {
756      double min = transparencyTrackBar.Minimum;
757      double max = transparencyTrackBar.Maximum;
758      double r = (x - min) / (max - min);  // r \in [0..1]
759      double l = Math.Max(Math.Min((1.0 - Math.Pow(0.05, r)) / 0.95, 1), 0); // l \in [0..1]
760      return (int)Math.Round(255.0 * l);
761    }
762
763    private void openBoxPlotViewToolStripMenuItem_Click(object sender, EventArgs e) {
764      RunCollectionBoxPlotView boxplotView = new RunCollectionBoxPlotView();
765      boxplotView.Content = this.Content;
766      boxplotView.xAxisComboBox.SelectedItem = xAxisComboBox.SelectedItem;
767      boxplotView.yAxisComboBox.SelectedItem = yAxisComboBox.SelectedItem;
768      boxplotView.Show();
769    }
770
771    private void getDataAsMatrixToolStripMenuItem_Click(object sender, EventArgs e) {
772      int xCol = Matrix.ColumnNames.ToList().IndexOf(xAxisValue);
773      int yCol = Matrix.ColumnNames.ToList().IndexOf(yAxisValue);
774
775      var grouped = new Dictionary<string, List<string>>();
776      Dictionary<double, string> reverseMapping = null;
777      if (categoricalMapping.ContainsKey(xCol))
778        reverseMapping = categoricalMapping[xCol].ToDictionary(x => x.Value, y => y.Key.ToString());
779      foreach (var run in Content.Where(r => r.Visible)) {
780        var x = GetValue(run, xAxisValue);
781        object y;
782        if (categoricalMapping.ContainsKey(yCol))
783          y = Content.GetValue(run, yAxisValue);
784        else y = GetValue(run, yAxisValue);
785        if (!(x.HasValue && y != null)) continue;
786
787        var category = reverseMapping == null ? x.Value.ToString() : reverseMapping[x.Value];
788        if (!grouped.ContainsKey(category)) grouped[category] = new List<string>();
789        grouped[category].Add(y.ToString());
790      }
791
792      if (!grouped.Any()) return;
793      var matrix = new StringMatrix(grouped.Values.Max(x => x.Count), grouped.Count) {
794        ColumnNames = grouped.Keys.ToArray()
795      };
796      int i = 0;
797      foreach (var col in matrix.ColumnNames) {
798        int j = 0;
799        foreach (var y in grouped[col])
800          matrix[j++, i] = y;
801        i++;
802      }
803      matrix.SortableView = false;
804      var view = MainFormManager.MainForm.ShowContent(matrix);
805      view.ReadOnly = true;
806    }
807
808    private void transparencyTrackBar_ValueChanged(object sender, EventArgs e) {
809      foreach (var run in Content)
810        UpdateRun(run);
811    }
812    #endregion
813
814    #region coloring
815    private void colorResetToolStripMenuItem_Click(object sender, EventArgs e) {
816      Content.UpdateOfRunsInProgress = true;
817
818      IEnumerable<IRun> runs;
819      if (selectedRuns.Any()) runs = selectedRuns;
820      else runs = Content;
821
822      foreach (var run in runs)
823        run.Color = Color.Black;
824      ClearSelectedRuns();
825
826      Content.UpdateOfRunsInProgress = false;
827    }
828    private void colorDialogButton_Click(object sender, EventArgs e) {
829      if (colorDialog.ShowDialog(this) == DialogResult.OK) {
830        this.colorRunsButton.Image = this.GenerateImage(16, 16, this.colorDialog.Color);
831        colorRunsButton_Click(sender, e);
832      }
833    }
834    private Image GenerateImage(int width, int height, Color fillColor) {
835      Image colorImage = new Bitmap(width, height);
836      using (Graphics gfx = Graphics.FromImage(colorImage)) {
837        using (SolidBrush brush = new SolidBrush(fillColor)) {
838          gfx.FillRectangle(brush, 0, 0, width, height);
839        }
840      }
841      return colorImage;
842    }
843
844    private void colorRunsButton_Click(object sender, EventArgs e) {
845      if (!selectedRuns.Any()) return;
846      Content.UpdateOfRunsInProgress = true;
847      foreach (var run in selectedRuns)
848        run.Color = colorDialog.Color;
849
850      ClearSelectedRuns();
851      Content.UpdateOfRunsInProgress = false;
852    }
853
854    private void colorXAxisButton_Click(object sender, EventArgs e) {
855      ColorRuns(xAxisValue);
856    }
857    private void colorYAxisButton_Click(object sender, EventArgs e) {
858      ColorRuns(yAxisValue);
859    }
860    private void ColorRuns(string axisValue) {
861      var runs = Content.Where(r => r.Visible).Select(r => new { Run = r, Value = GetValue(r, axisValue) }).Where(r => r.Value.HasValue).ToList();
862      double minValue = runs.Min(r => r.Value.Value);
863      double maxValue = runs.Max(r => r.Value.Value);
864      double range = maxValue - minValue;
865      // UpdateOfRunsInProgress has to be set to true, otherwise run_Changed is called all the time (also in other views)
866      Content.UpdateOfRunsInProgress = true;
867      if (range.IsAlmost(0)) {
868        Color c = ColorGradient.Colors[0];
869        runs.ForEach(r => r.Run.Color = c);
870      } else {
871        int maxColorIndex = ColorGradient.Colors.Count - 1;
872        foreach (var r in runs) {
873          int colorIndex = (int)(maxColorIndex * (r.Value - minValue) / (range));
874          r.Run.Color = ColorGradient.Colors[colorIndex];
875        }
876      }
877      Content.UpdateOfRunsInProgress = false;
878    }
879    #endregion
880  }
881}
Note: See TracBrowser for help on using the repository browser.