Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 11890 was 11344, checked in by abeham, 10 years ago

#2120:

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