Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 17690 was 17180, checked in by swagner, 5 years ago

#2875: Removed years in copyrights

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