Free cookie consent management tool by TermsFeed Policy Generator

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

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

#2099 renamed run collection views

File size: 36.3 KB
RevLine 
[3349]1#region License Information
2/* HeuristicLab
[9456]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;
[9229]28using HeuristicLab.Common;
29using HeuristicLab.Core;
30using HeuristicLab.Data;
31using HeuristicLab.MainForm;
32using HeuristicLab.MainForm.WindowsForms;
[3349]33
34namespace HeuristicLab.Optimization.Views {
[9910]35  [View("Bubble Chart")]
[3349]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
[9312]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
[9435]58    private RunCollectionContentConstraint visibilityConstraint = new RunCollectionContentConstraint() { Active = true };
59
[3349]60    public RunCollectionBubbleChartView() {
61      InitializeComponent();
[3411]62
[9435]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
[9435]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    }
[9312]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);
[9312]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);
[9312]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) {
[9312]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);
[9312]142        UpdateCursorInterval();
143        chart.ChartAreas[0].RecalculateAxesScale();
144        UpdateAxisLabels();
[3632]145      }
[3614]146    }
147
[9312]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) {
[9312]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          }
[9312]170          if (selectedRuns.Contains(run)) {
171            point.Color = Color.Red;
172            point.MarkerStyle = MarkerStyle.Cross;
173          } else {
[9435]174            point.Color = Color.FromArgb(255 - LogTransform(transparencyTrackBar.Value), ((IRun)point.Tag).Color);
[9312]175            point.MarkerStyle = MarkerStyle.Circle;
176          }
177
[4799]178        }
[9312]179        if (!run.Visible) runToDataPointMapping.Remove(run);
180      } else {
181        AddDataPoint(run);
182      }
[4883]183
[9312]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();
[9235]196      RebuildInverseIndex();
[3349]197    }
[9235]198
199    private void RebuildInverseIndex() {
200      if (Content != null) {
[9312]201        runToIndexMapping.Clear();
[9235]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        }
[9235]252        if (changed) {
[3701]253          UpdateDataPoints();
[9235]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();
[9235]270        RebuildInverseIndex();
[3349]271        UpdateDataPoints();
[9235]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();
[9312]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() {
[9229]309      var series = chart.Series[0];
[9340]310      if (series.Points.Count <= 0) return;
311
[9229]312      var sizeValues = series.Points.Select(p => p.YValues[1]);
[5330]313      double minSizeValue = sizeValues.Min();
314      double maxSizeValue = sizeValues.Max();
[9229]315      double sizeRange = maxSizeValue - minSizeValue;
[5330]316
[9435]317      const int smallestBubbleSize = 7;
[9229]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);
[9229]322        if (sizeRange > double.Epsilon) {
323          relativeSize /= sizeRange;
[5348]324
[9229]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
[9229]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
[9435]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);
[9312]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) {
[9235]441      if (!this.categoricalMapping.ContainsKey(dimension)) {
[3349]442        this.categoricalMapping[dimension] = new Dictionary<object, double>();
[9435]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());
[9235]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    }
[9235]453
[3524]454    private double GetValue(IRun run, AxisDimension axisDimension) {
455      double value = double.NaN;
456      switch (axisDimension) {
457        case AxisDimension.Index: {
[9235]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() {
[9312]481      double xMin = double.MaxValue;
482      double xMax = double.MinValue;
483      double yMin = double.MaxValue;
484      double yMax = double.MinValue;
[3349]485
[9312]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) {
[9312]536      if (!isSelecting) return;
[3428]537
[9312]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
[9312]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
[9435]546      if (Control.ModifierKeys != Keys.Control) {
547        ClearSelectedRuns();
548      }
549
[9312]550      //check for click to select a single model
551      if (minX == maxX && minY == maxY) {
[9332]552        HitTestResult hitTest = chart.HitTest(e.X, e.Y, ChartElementType.DataPoint);
[9312]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;
[9447]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          }
[9435]566        }
[9312]567      } else {
568        foreach (DataPoint point in this.chart.Series[0].Points) {
[9435]569          if (point.XValue < minX || point.XValue > maxX) continue;
570          if (point.YValues[0] < minY || point.YValues[0] > maxY) continue;
[9312]571          point.MarkerStyle = MarkerStyle.Cross;
572          point.Color = Color.Red;
573          IRun run = (IRun)point.Tag;
574          selectedRuns.Add(run);
[3428]575        }
576      }
[9315]577
[9312]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;
[9315]580      this.OnChanged();
[3428]581    }
582
[3411]583    private void chart_MouseMove(object sender, MouseEventArgs e) {
[9312]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;
[9435]708      this.colorRunsButton.Enabled = this.isSelecting;
[9312]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;
[9312]713      ClearSelectedRuns();
[3411]714    }
[4653]715
[6673]716    private void ContextMenuStrip_Opening(object sender, System.ComponentModel.CancelEventArgs e) {
[9448]717      hideRunsToolStripMenuItem.Visible = selectedRuns.Any();
[9435]718    }
[6673]719
[9435]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    }
[9435]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    }
[9312]729    private void hideRunsButton_Click(object sender, EventArgs e) {
[9435]730      HideRuns(selectedRuns);
731      //could not use ClearSelectedRuns as the runs are not visible anymore
732      selectedRuns.Clear();
[9312]733    }
[6673]734
[9435]735    private void HideRuns(IEnumerable<IRun> runs) {
736      visibilityConstraint.Active = false;
737      if (!Content.Constraints.Contains(visibilityConstraint)) Content.Constraints.Add(visibilityConstraint);
[9448]738      foreach (var run in runs) {
[9435]739        visibilityConstraint.ConstraintData.Add(run);
740      }
741      visibilityConstraint.Active = true;
742    }
743
[9312]744    private void ClearSelectedRuns() {
745      foreach (var run in selectedRuns) {
746        foreach (var point in runToDataPointMapping[run]) {
747          point.MarkerStyle = MarkerStyle.Circle;
[9404]748          point.Color = Color.FromArgb(255 - LogTransform(transparencyTrackBar.Value), run.Color);
[9312]749        }
750      }
751      selectedRuns.Clear();
752    }
753
[9404]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]
[9441]759      double l = Math.Max(Math.Min((1.0 - Math.Pow(0.05, r)) / 0.95, 1), 0); // l \in [0..1]
[9404]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    }
[9190]770
771    private void getDataAsMatrixToolStripMenuItem_Click(object sender, EventArgs e) {
772      int xCol = Matrix.ColumnNames.ToList().IndexOf(xAxisValue);
[9267]773      int yCol = Matrix.ColumnNames.ToList().IndexOf(yAxisValue);
774
[9190]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);
[9267]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;
[9190]786
787        var category = reverseMapping == null ? x.Value.ToString() : reverseMapping[x.Value];
788        if (!grouped.ContainsKey(category)) grouped[category] = new List<string>();
[9267]789        grouped[category].Add(y.ToString());
[9190]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      }
[9267]803      matrix.SortableView = false;
804      var view = MainFormManager.MainForm.ShowContent(matrix);
805      view.ReadOnly = true;
[9190]806    }
[9276]807
808    private void transparencyTrackBar_ValueChanged(object sender, EventArgs e) {
[9312]809      foreach (var run in Content)
810        UpdateRun(run);
[9276]811    }
[3411]812    #endregion
[4799]813
[9312]814    #region coloring
[9435]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    }
[9312]828    private void colorDialogButton_Click(object sender, EventArgs e) {
829      if (colorDialog.ShowDialog(this) == DialogResult.OK) {
[9435]830        this.colorRunsButton.Image = this.GenerateImage(16, 16, this.colorDialog.Color);
831        colorRunsButton_Click(sender, e);
[9312]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) {
[9235]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;
[9236]865      // UpdateOfRunsInProgress has to be set to true, otherwise run_Changed is called all the time (also in other views)
866      Content.UpdateOfRunsInProgress = true;
[9235]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      }
[9236]877      Content.UpdateOfRunsInProgress = false;
[4799]878    }
879    #endregion
[3349]880  }
881}
Note: See TracBrowser for help on using the repository browser.