Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 9404 was 9404, checked in by gkronber, 11 years ago

#1789 added logarithmic scaling for transparency value

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