Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.EvolutionaryTracking/HeuristicLab.Optimization.Views/3.3/RunCollectionViews/RunCollectionBubbleChartView.cs @ 12726

Last change on this file since 12726 was 9835, checked in by bburlacu, 11 years ago

#1772: Merged remaining trunk changes into the EvolutionaryTracking branch.

File size: 36.3 KB
RevLine 
[3349]1#region License Information
2/* HeuristicLab
[9835]3 * Copyright (C) 2002-2013 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
[3349]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;
[9421]28using HeuristicLab.Common;
29using HeuristicLab.Core;
30using HeuristicLab.Data;
31using HeuristicLab.MainForm;
32using HeuristicLab.MainForm.WindowsForms;
[3349]33
34namespace HeuristicLab.Optimization.Views {
35  [View("RunCollection BubbleChart")]
36  [Content(typeof(RunCollection), false)]
37  public partial class RunCollectionBubbleChartView : AsynchronousContentView {
[3524]38    private enum SizeDimension { Constant = 0 }
39    private enum AxisDimension { Index = 0 }
40
[3726]41    private string xAxisValue;
42    private string yAxisValue;
43    private string sizeAxisValue;
44
[9421]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();
[3411]53    private double xJitterFactor = 0.0;
54    private double yJitterFactor = 0.0;
55    private bool isSelecting = false;
[4883]56    private bool suppressUpdates = false;
[3349]57
[9835]58    private RunCollectionContentConstraint visibilityConstraint = new RunCollectionContentConstraint() { Active = true };
[9421]59
[3349]60    public RunCollectionBubbleChartView() {
61      InitializeComponent();
[3411]62
[9835]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());
[6673]70      chart.ContextMenuStrip.Opening += new System.ComponentModel.CancelEventHandler(ContextMenuStrip_Opening);
71
[9835]72      colorDialog.Color = Color.Orange;
73      colorRunsButton.Image = this.GenerateImage(16, 16, this.colorDialog.Color);
[4635]74      isSelecting = false;
[4846]75
[4636]76      chart.CustomizeAllChartAreas();
[4635]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;
[3349]81    }
82
83    public new RunCollection Content {
84      get { return (RunCollection)base.Content; }
85      set { base.Content = value; }
86    }
[3447]87    public IStringConvertibleMatrix Matrix {
88      get { return this.Content; }
89    }
[9421]90    public IEnumerable<IRun> SelectedRuns {
91      get { return selectedRuns; }
92    }
[3447]93
[3349]94    protected override void RegisterContentEvents() {
95      base.RegisterContentEvents();
96      Content.Reset += new EventHandler(Content_Reset);
97      Content.ColumnNamesChanged += new EventHandler(Content_ColumnNamesChanged);
[3428]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);
[9421]101      Content.OptimizerNameChanged += new EventHandler(Content_AlgorithmNameChanged);
[4888]102      Content.UpdateOfRunsInProgressChanged += new EventHandler(Content_UpdateOfRunsInProgressChanged);
[3448]103      RegisterRunEvents(Content);
104    }
[3349]105    protected override void DeregisterContentEvents() {
106      base.DeregisterContentEvents();
107      Content.Reset -= new EventHandler(Content_Reset);
108      Content.ColumnNamesChanged -= new EventHandler(Content_ColumnNamesChanged);
[3428]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);
[9421]112      Content.OptimizerNameChanged -= new EventHandler(Content_AlgorithmNameChanged);
[4888]113      Content.UpdateOfRunsInProgressChanged -= new EventHandler(Content_UpdateOfRunsInProgressChanged);
[3448]114      DeregisterRunEvents(Content);
115    }
[4094]116    protected virtual void RegisterRunEvents(IEnumerable<IRun> runs) {
117      foreach (IRun run in runs)
118        run.Changed += new EventHandler(run_Changed);
119    }
[3448]120    protected virtual void DeregisterRunEvents(IEnumerable<IRun> runs) {
121      foreach (IRun run in runs)
[3428]122        run.Changed -= new EventHandler(run_Changed);
[3349]123    }
[3428]124
125    private void Content_CollectionReset(object sender, HeuristicLab.Collections.CollectionItemsChangedEventArgs<IRun> e) {
[3448]126      DeregisterRunEvents(e.OldItems);
127      RegisterRunEvents(e.Items);
[3428]128    }
129    private void Content_ItemsRemoved(object sender, HeuristicLab.Collections.CollectionItemsChangedEventArgs<IRun> e) {
[3449]130      DeregisterRunEvents(e.Items);
[3428]131    }
132    private void Content_ItemsAdded(object sender, HeuristicLab.Collections.CollectionItemsChangedEventArgs<IRun> e) {
[3448]133      RegisterRunEvents(e.Items);
[3428]134    }
135    private void run_Changed(object sender, EventArgs e) {
[9421]136      if (suppressUpdates) return;
[3632]137      if (InvokeRequired)
138        this.Invoke(new EventHandler(run_Changed), sender, e);
139      else {
140        IRun run = (IRun)sender;
141        UpdateRun(run);
[9421]142        UpdateCursorInterval();
143        chart.ChartAreas[0].RecalculateAxesScale();
144        UpdateAxisLabels();
[3632]145      }
[3614]146    }
147
[9421]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
[3614]163    private void UpdateRun(IRun run) {
[9421]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;
[4883]169          }
[9421]170          if (selectedRuns.Contains(run)) {
171            point.Color = Color.Red;
172            point.MarkerStyle = MarkerStyle.Cross;
173          } else {
[9835]174            point.Color = Color.FromArgb(255 - LogTransform(transparencyTrackBar.Value), ((IRun)point.Tag).Color);
[9421]175            point.MarkerStyle = MarkerStyle.Circle;
176          }
177
[4799]178        }
[9421]179        if (!run.Visible) runToDataPointMapping.Remove(run);
180      } else {
181        AddDataPoint(run);
182      }
[4883]183
[9421]184      if (this.chart.Series[0].Points.Count == 0)
185        noRunsLabel.Visible = true;
186      else
187        noRunsLabel.Visible = false;
[3428]188    }
189
[3349]190    protected override void OnContentChanged() {
191      base.OnContentChanged();
[3411]192      this.categoricalMapping.Clear();
[3499]193      UpdateComboBoxes();
194      UpdateDataPoints();
[8738]195      UpdateCaption();
[9421]196      RebuildInverseIndex();
[3349]197    }
[9421]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
[3349]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
[8738]217    private void UpdateCaption() {
[8962]218      Caption = Content != null ? Content.OptimizerName + " Bubble Chart" : ViewAttribute.GetViewName(GetType());
[8738]219    }
220
[3349]221    private void UpdateComboBoxes() {
[3701]222      string selectedXAxis = (string)this.xAxisComboBox.SelectedItem;
223      string selectedYAxis = (string)this.yAxisComboBox.SelectedItem;
224      string selectedSizeAxis = (string)this.sizeComboBox.SelectedItem;
[3349]225      this.xAxisComboBox.Items.Clear();
226      this.yAxisComboBox.Items.Clear();
[3411]227      this.sizeComboBox.Items.Clear();
[3499]228      if (Content != null) {
[3524]229        string[] additionalAxisDimension = Enum.GetNames(typeof(AxisDimension));
230        this.xAxisComboBox.Items.AddRange(additionalAxisDimension);
[3499]231        this.xAxisComboBox.Items.AddRange(Matrix.ColumnNames.ToArray());
[3524]232        this.yAxisComboBox.Items.AddRange(additionalAxisDimension);
[3499]233        this.yAxisComboBox.Items.AddRange(Matrix.ColumnNames.ToArray());
[3524]234        string[] additionalSizeDimension = Enum.GetNames(typeof(SizeDimension));
235        this.sizeComboBox.Items.AddRange(additionalSizeDimension);
[3499]236        this.sizeComboBox.Items.AddRange(Matrix.ColumnNames.ToArray());
[3524]237        this.sizeComboBox.SelectedItem = SizeDimension.Constant.ToString();
[3701]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        }
[9421]252        if (changed) {
[3701]253          UpdateDataPoints();
[9421]254          UpdateAxisLabels();
255        }
[3499]256      }
[3349]257    }
258
[8738]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
[3349]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();
[9421]270        RebuildInverseIndex();
[3349]271        UpdateDataPoints();
[9421]272        UpdateAxisLabels();
[3349]273      }
274    }
275
276    private void UpdateDataPoints() {
277      Series series = this.chart.Series[0];
278      series.Points.Clear();
[4799]279      runToDataPointMapping.Clear();
[9421]280      selectedRuns.Clear();
[6096]281
282      chart.ChartAreas[0].AxisX.IsMarginVisible = xAxisValue != AxisDimension.Index.ToString();
283      chart.ChartAreas[0].AxisY.IsMarginVisible = yAxisValue != AxisDimension.Index.ToString();
284
[3499]285      if (Content != null) {
286        foreach (IRun run in this.Content)
287          this.AddDataPoint(run);
[3543]288
289        if (this.chart.Series[0].Points.Count == 0)
290          noRunsLabel.Visible = true;
[4209]291        else {
[3543]292          noRunsLabel.Visible = false;
[5330]293          UpdateMarkerSizes();
[4209]294          UpdateCursorInterval();
295        }
[3499]296      }
[5824]297      xTrackBar.Value = 0;
298      yTrackBar.Value = 0;
[9068]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();
[3428]306    }
[5330]307
308    private void UpdateMarkerSizes() {
[9421]309      var series = chart.Series[0];
310      if (series.Points.Count <= 0) return;
311
312      var sizeValues = series.Points.Select(p => p.YValues[1]);
[5330]313      double minSizeValue = sizeValues.Min();
314      double maxSizeValue = sizeValues.Max();
[9421]315      double sizeRange = maxSizeValue - minSizeValue;
[5330]316
[9835]317      const int smallestBubbleSize = 7;
[9421]318
319      foreach (DataPoint point in series.Points) {
320        //calculates the relative size of the data point  0 <= relativeSize <= 1
[5348]321        double relativeSize = (point.YValues[1] - minSizeValue);
[9421]322        if (sizeRange > double.Epsilon) {
323          relativeSize /= sizeRange;
[5348]324
[9421]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;
[5348]328
[9421]329        double sizeChange = Math.Abs(sizeTrackBar.Value) * relativeSize;
330        point.MarkerSize = (int)Math.Round(sizeChange + smallestBubbleSize);
[5330]331      }
332    }
333
[5824]334    private void UpdateDataPointJitter() {
335      var xAxis = this.chart.ChartAreas[0].AxisX;
336      var yAxis = this.chart.ChartAreas[0].AxisY;
337
[8835]338      double xAxisRange = xAxis.Maximum - xAxis.Minimum;
339      double yAxisRange = yAxis.Maximum - yAxis.Minimum;
[8832]340
[5824]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))
[8835]347          xValue += 0.1 * GetXJitter(run) * xJitterFactor * (xAxisRange);
[5824]348        if (!yJitterFactor.IsAlmost(0.0))
[8835]349          yValue += 0.1 * GetYJitter(run) * yJitterFactor * (yAxisRange);
[5824]350
351        point.XValue = xValue;
352        point.YValues[0] = yValue;
353      }
354
[9835]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      }
[5824]363    }
364
[9068]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
[3428]383    private void AddDataPoint(IRun run) {
[3349]384      double? xValue;
385      double? yValue;
[3411]386      double? sizeValue;
[3428]387      Series series = this.chart.Series[0];
[3726]388
[4845]389      xValue = GetValue(run, xAxisValue);
390      yValue = GetValue(run, yAxisValue);
391      sizeValue = GetValue(run, sizeAxisValue);
[3726]392
[3543]393      if (xValue.HasValue && yValue.HasValue && sizeValue.HasValue) {
[3701]394        xValue = xValue.Value;
395        yValue = yValue.Value;
[5824]396
[3428]397        if (run.Visible) {
[3411]398          DataPoint point = new DataPoint(xValue.Value, new double[] { yValue.Value, sizeValue.Value });
[3428]399          point.Tag = run;
[3411]400          series.Points.Add(point);
[4883]401          if (!runToDataPointMapping.ContainsKey(run)) runToDataPointMapping.Add(run, new List<DataPoint>());
402          runToDataPointMapping[run].Add(point);
[9421]403          UpdateRun(run);
[3411]404        }
[3349]405      }
406    }
[3524]407    private double? GetValue(IRun run, string columnName) {
408      if (run == null || string.IsNullOrEmpty(columnName))
[3349]409        return null;
410
[3524]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;
[3447]422
[3524]423        DoubleValue doubleValue = value as DoubleValue;
424        IntValue intValue = value as IntValue;
[4049]425        TimeSpanValue timeSpanValue = value as TimeSpanValue;
[3543]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)
[3524]431          ret = intValue.Value;
[4049]432        else if (timeSpanValue != null) {
433          ret = timeSpanValue.Value.TotalSeconds;
434        } else
[3524]435          ret = GetCategoricalValue(columnIndex, value.ToString());
[3447]436
[3524]437        return ret;
438      }
[3349]439    }
[3524]440    private double GetCategoricalValue(int dimension, string value) {
[9421]441      if (!this.categoricalMapping.ContainsKey(dimension)) {
[3349]442        this.categoricalMapping[dimension] = new Dictionary<object, double>();
[9835]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());
[9421]445        int count = 1;
446        foreach (var category in orderedCategories) {
447          this.categoricalMapping[dimension].Add(category, count);
448          count++;
449        }
[3349]450      }
[3524]451      return this.categoricalMapping[dimension][value];
[3349]452    }
[9421]453
[3524]454    private double GetValue(IRun run, AxisDimension axisDimension) {
455      double value = double.NaN;
456      switch (axisDimension) {
457        case AxisDimension.Index: {
[9421]458            value = runToIndexMapping[run];
[3524]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    }
[3707]480    private void UpdateCursorInterval() {
[9421]481      double xMin = double.MaxValue;
482      double xMax = double.MinValue;
483      double yMin = double.MaxValue;
484      double yMax = double.MinValue;
[3349]485
[9421]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
[4049]499      if (xRange.IsAlmost(0.0)) xRange = 1.0;
500      if (yRange.IsAlmost(0.0)) yRange = 1.0;
[3707]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;
[4049]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;
[3707]516    }
517
[4888]518    #region Drag & drop and tooltip
[6026]519    private void chart_MouseDoubleClick(object sender, MouseEventArgs e) {
[6094]520      HitTestResult h = this.chart.HitTest(e.X, e.Y, ChartElementType.DataPoint);
[3411]521      if (h.ChartElementType == ChartElementType.DataPoint) {
[3459]522        IRun run = (IRun)((DataPoint)h.Object).Tag;
[5976]523        IContentView view = MainFormManager.MainForm.ShowContent(run);
524        if (view != null) {
525          view.ReadOnly = this.ReadOnly;
526          view.Locked = this.Locked;
527        }
[6026]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;
[3411]531      }
[6096]532      UpdateAxisLabels();
[3411]533    }
534
[3428]535    private void chart_MouseUp(object sender, MouseEventArgs e) {
[9421]536      if (!isSelecting) return;
[3428]537
[9421]538      System.Windows.Forms.DataVisualization.Charting.Cursor xCursor = chart.ChartAreas[0].CursorX;
539      System.Windows.Forms.DataVisualization.Charting.Cursor yCursor = chart.ChartAreas[0].CursorY;
[3428]540
[9421]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
[9835]546      if (Control.ModifierKeys != Keys.Control) {
547        ClearSelectedRuns();
548      }
549
[9421]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;
[9835]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        }
[9421]567      } else {
568        foreach (DataPoint point in this.chart.Series[0].Points) {
[9835]569          if (point.XValue < minX || point.XValue > maxX) continue;
570          if (point.YValues[0] < minY || point.YValues[0] > maxY) continue;
[9421]571          point.MarkerStyle = MarkerStyle.Cross;
572          point.Color = Color.Red;
573          IRun run = (IRun)point.Tag;
574          selectedRuns.Add(run);
[3428]575        }
576      }
[9421]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();
[3428]581    }
582
[3411]583    private void chart_MouseMove(object sender, MouseEventArgs e) {
[9421]584      if (Control.MouseButtons != MouseButtons.None) return;
[3487]585      HitTestResult h = this.chart.HitTest(e.X, e.Y);
[3524]586      string newTooltipText = string.Empty;
[3487]587      string oldTooltipText;
588      if (h.ChartElementType == ChartElementType.DataPoint) {
589        IRun run = (IRun)((DataPoint)h.Object).Tag;
[3524]590        newTooltipText = BuildTooltip(run);
[4212]591      } else if (h.ChartElementType == ChartElementType.AxisLabels) {
592        newTooltipText = ((CustomLabel)h.Object).ToolTip;
[3524]593      }
594
[3487]595      oldTooltipText = this.tooltip.GetToolTip(chart);
596      if (newTooltipText != oldTooltipText)
597        this.tooltip.SetToolTip(chart, newTooltipText);
[3411]598    }
[3524]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
[4049]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);
[4212]617        xString = string.Format("{0:00}:{1:00}:{2:00.00}", (int)time.TotalHours, time.Minutes, time.Seconds);
[4049]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);
[4212]622        yString = string.Format("{0:00}:{1:00}:{2:00.00}", (int)time.TotalHours, time.Minutes, time.Seconds);
[4049]623      }
624
[3524]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    }
[3411]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;
[5824]647      UpdateDataPointJitter();
[3411]648    }
[5330]649    private void sizeTrackBar_ValueChanged(object sender, EventArgs e) {
650      UpdateMarkerSizes();
651    }
[3411]652
[5330]653    private void AxisComboBox_SelectedValueChanged(object sender, EventArgs e) {
[4812]654      bool axisSelected = xAxisComboBox.SelectedIndex != -1 && yAxisComboBox.SelectedIndex != -1;
655      xTrackBar.Enabled = yTrackBar.Enabled = axisSelected;
656      colorXAxisButton.Enabled = colorYAxisButton.Enabled = axisSelected;
[4845]657
[6094]658      xAxisValue = (string)xAxisComboBox.SelectedItem;
659      yAxisValue = (string)yAxisComboBox.SelectedItem;
660      sizeAxisValue = (string)sizeComboBox.SelectedItem;
[4845]661
[3411]662      UpdateDataPoints();
663      UpdateAxisLabels();
664    }
[3349]665    private void UpdateAxisLabels() {
666      Axis xAxis = this.chart.ChartAreas[0].AxisX;
667      Axis yAxis = this.chart.ChartAreas[0].AxisY;
[3536]668      int axisDimensionCount = Enum.GetNames(typeof(AxisDimension)).Count();
669      SetCustomAxisLabels(xAxis, xAxisComboBox.SelectedIndex - axisDimensionCount);
670      SetCustomAxisLabels(yAxis, yAxisComboBox.SelectedIndex - axisDimensionCount);
[4635]671      if (xAxisComboBox.SelectedItem != null)
672        xAxis.Title = xAxisComboBox.SelectedItem.ToString();
673      if (yAxisComboBox.SelectedItem != null)
674        yAxis.Title = yAxisComboBox.SelectedItem.ToString();
[3349]675    }
[4049]676
677    private void chart_AxisViewChanged(object sender, System.Windows.Forms.DataVisualization.Charting.ViewEventArgs e) {
678      this.UpdateAxisLabels();
679    }
680
[3411]681    private void SetCustomAxisLabels(Axis axis, int dimension) {
682      axis.CustomLabels.Clear();
[3349]683      if (categoricalMapping.ContainsKey(dimension)) {
684        foreach (var pair in categoricalMapping[dimension]) {
[3536]685          string labelText = pair.Key.ToString();
[4212]686          CustomLabel label = new CustomLabel();
687          label.ToolTip = labelText;
[3543]688          if (labelText.Length > 25)
689            labelText = labelText.Substring(0, 25) + " ... ";
[4212]690          label.Text = labelText;
[3349]691          label.GridTicks = GridTickTypes.TickMark;
[4212]692          label.FromPosition = pair.Value - 0.5;
693          label.ToPosition = pair.Value + 0.5;
694          axis.CustomLabels.Add(label);
[3349]695        }
[4049]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);
[6096]700          string x = string.Format("{0:00}:{1:00}:{2:00}", time.Hours, time.Minutes, time.Seconds);
[4058]701          axis.CustomLabels.Add(i - axis.LabelStyle.Interval / 2, i + axis.LabelStyle.Interval / 2, x);
[4049]702        }
[3349]703      }
704    }
[3411]705
706    private void zoomButton_CheckedChanged(object sender, EventArgs e) {
707      this.isSelecting = selectButton.Checked;
[9835]708      this.colorRunsButton.Enabled = this.isSelecting;
[9421]709      this.colorDialogButton.Enabled = this.isSelecting;
710      this.hideRunsButton.Enabled = this.isSelecting;
[3411]711      this.chart.ChartAreas[0].AxisX.ScaleView.Zoomable = !isSelecting;
712      this.chart.ChartAreas[0].AxisY.ScaleView.Zoomable = !isSelecting;
[9421]713      ClearSelectedRuns();
[3411]714    }
[4653]715
[6673]716    private void ContextMenuStrip_Opening(object sender, System.ComponentModel.CancelEventArgs e) {
[9835]717      hideRunsToolStripMenuItem.Visible = selectedRuns.Any();
718    }
[6673]719
[9835]720    private void unhideAllRunToolStripMenuItem_Click(object sender, EventArgs e) {
721      visibilityConstraint.ConstraintData.Clear();
722      if (Content.Constraints.Contains(visibilityConstraint)) Content.Constraints.Remove(visibilityConstraint);
[6673]723    }
[9835]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();
[6673]728    }
[9421]729    private void hideRunsButton_Click(object sender, EventArgs e) {
[9835]730      HideRuns(selectedRuns);
731      //could not use ClearSelectedRuns as the runs are not visible anymore
732      selectedRuns.Clear();
[9421]733    }
[6673]734
[9835]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
[9421]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]
[9835]759      double l = Math.Max(Math.Min((1.0 - Math.Pow(0.05, r)) / 0.95, 1), 0); // l \in [0..1]
[9421]760      return (int)Math.Round(255.0 * l);
761    }
762
[4653]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    }
[9240]770
771    private void getDataAsMatrixToolStripMenuItem_Click(object sender, EventArgs e) {
772      int xCol = Matrix.ColumnNames.ToList().IndexOf(xAxisValue);
[9421]773      int yCol = Matrix.ColumnNames.ToList().IndexOf(yAxisValue);
774
[9240]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);
[9421]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;
[9240]786
787        var category = reverseMapping == null ? x.Value.ToString() : reverseMapping[x.Value];
788        if (!grouped.ContainsKey(category)) grouped[category] = new List<string>();
[9421]789        grouped[category].Add(y.ToString());
[9240]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      }
[9421]803      matrix.SortableView = false;
804      var view = MainFormManager.MainForm.ShowContent(matrix);
805      view.ReadOnly = true;
806    }
[9240]807
[9421]808    private void transparencyTrackBar_ValueChanged(object sender, EventArgs e) {
809      foreach (var run in Content)
810        UpdateRun(run);
[9240]811    }
[3411]812    #endregion
[4799]813
[9421]814    #region coloring
[9835]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    }
[9421]828    private void colorDialogButton_Click(object sender, EventArgs e) {
829      if (colorDialog.ShowDialog(this) == DialogResult.OK) {
[9835]830        this.colorRunsButton.Image = this.GenerateImage(16, 16, this.colorDialog.Color);
831        colorRunsButton_Click(sender, e);
[9421]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
[4799]854    private void colorXAxisButton_Click(object sender, EventArgs e) {
[4845]855      ColorRuns(xAxisValue);
[4799]856    }
857    private void colorYAxisButton_Click(object sender, EventArgs e) {
[4845]858      ColorRuns(yAxisValue);
859    }
860    private void ColorRuns(string axisValue) {
[9421]861      var runs = Content.Where(r => r.Visible).Select(r => new { Run = r, Value = GetValue(r, axisValue) }).Where(r => r.Value.HasValue).ToList();
[4845]862      double minValue = runs.Min(r => r.Value.Value);
863      double maxValue = runs.Max(r => r.Value.Value);
864      double range = maxValue - minValue;
[9421]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        }
[4799]876      }
[9421]877      Content.UpdateOfRunsInProgress = false;
[4799]878    }
879    #endregion
[3349]880  }
881}
Note: See TracBrowser for help on using the repository browser.