Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 14455 was 14185, checked in by swagner, 8 years ago

#2526: Updated year of copyrights in license headers

File size: 36.7 KB
RevLine 
[3349]1#region License Information
2/* HeuristicLab
[14185]3 * Copyright (C) 2002-2016 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) {
[12077]264      if (suppressUpdates) return;
[3349]265      if (InvokeRequired)
266        Invoke(new EventHandler(Content_Reset), sender, e);
267      else {
268        UpdateDataPoints();
[9235]269        UpdateAxisLabels();
[3349]270      }
271    }
272
273    private void UpdateDataPoints() {
274      Series series = this.chart.Series[0];
275      series.Points.Clear();
[4799]276      runToDataPointMapping.Clear();
[11007]277      categoricalMapping.Clear();
[9312]278      selectedRuns.Clear();
[11007]279      RebuildInverseIndex();
[6096]280
281      chart.ChartAreas[0].AxisX.IsMarginVisible = xAxisValue != AxisDimension.Index.ToString();
282      chart.ChartAreas[0].AxisY.IsMarginVisible = yAxisValue != AxisDimension.Index.ToString();
283
[3499]284      if (Content != null) {
285        foreach (IRun run in this.Content)
286          this.AddDataPoint(run);
[3543]287
288        if (this.chart.Series[0].Points.Count == 0)
289          noRunsLabel.Visible = true;
[4209]290        else {
[3543]291          noRunsLabel.Visible = false;
[5330]292          UpdateMarkerSizes();
[4209]293          UpdateCursorInterval();
294        }
[3499]295      }
[5824]296      xTrackBar.Value = 0;
297      yTrackBar.Value = 0;
[9068]298
299      //needed to set axis back to automatic and refresh them, otherwise their values may remain NaN
300      var xAxis = chart.ChartAreas[0].AxisX;
301      var yAxis = chart.ChartAreas[0].AxisY;
302      SetAutomaticUpdateOfAxis(xAxis, true);
303      SetAutomaticUpdateOfAxis(yAxis, true);
304      chart.Refresh();
[3428]305    }
[5330]306
307    private void UpdateMarkerSizes() {
[9229]308      var series = chart.Series[0];
[9340]309      if (series.Points.Count <= 0) return;
310
[9229]311      var sizeValues = series.Points.Select(p => p.YValues[1]);
[5330]312      double minSizeValue = sizeValues.Min();
313      double maxSizeValue = sizeValues.Max();
[9229]314      double sizeRange = maxSizeValue - minSizeValue;
[5330]315
[9435]316      const int smallestBubbleSize = 7;
[9229]317
318      foreach (DataPoint point in series.Points) {
319        //calculates the relative size of the data point  0 <= relativeSize <= 1
[5348]320        double relativeSize = (point.YValues[1] - minSizeValue);
[9229]321        if (sizeRange > double.Epsilon) {
322          relativeSize /= sizeRange;
[5348]323
[9229]324          //invert bubble sizes if the value of the trackbar is negative
325          if (sizeTrackBar.Value < 0) relativeSize = Math.Abs(relativeSize - 1);
326        } else relativeSize = 1;
[5348]327
[9229]328        double sizeChange = Math.Abs(sizeTrackBar.Value) * relativeSize;
329        point.MarkerSize = (int)Math.Round(sizeChange + smallestBubbleSize);
[5330]330      }
331    }
332
[5824]333    private void UpdateDataPointJitter() {
334      var xAxis = this.chart.ChartAreas[0].AxisX;
335      var yAxis = this.chart.ChartAreas[0].AxisY;
336
[8835]337      double xAxisRange = xAxis.Maximum - xAxis.Minimum;
338      double yAxisRange = yAxis.Maximum - yAxis.Minimum;
[8832]339
[5824]340      foreach (DataPoint point in chart.Series[0].Points) {
341        IRun run = (IRun)point.Tag;
342        double xValue = GetValue(run, xAxisValue).Value;
343        double yValue = GetValue(run, yAxisValue).Value;
344
345        if (!xJitterFactor.IsAlmost(0.0))
[8835]346          xValue += 0.1 * GetXJitter(run) * xJitterFactor * (xAxisRange);
[5824]347        if (!yJitterFactor.IsAlmost(0.0))
[8835]348          yValue += 0.1 * GetYJitter(run) * yJitterFactor * (yAxisRange);
[5824]349
350        point.XValue = xValue;
351        point.YValues[0] = yValue;
352      }
353
[9435]354      if (xJitterFactor.IsAlmost(0.0) && yJitterFactor.IsAlmost(0.0)) {
355        SetAutomaticUpdateOfAxis(xAxis, true);
356        SetAutomaticUpdateOfAxis(yAxis, true);
357        chart.ChartAreas[0].RecalculateAxesScale();
358      } else {
359        SetAutomaticUpdateOfAxis(xAxis, false);
360        SetAutomaticUpdateOfAxis(yAxis, false);
361      }
[5824]362    }
363
[9068]364    // sets an axis to automatic or restrains it to its current values
365    // this is used that none of the set values is changed when jitter is applied, so that the chart stays the same
366    private void SetAutomaticUpdateOfAxis(Axis axis, bool enabled) {
367      if (enabled) {
368        axis.Maximum = double.NaN;
369        axis.Minimum = double.NaN;
370        axis.MajorGrid.Interval = double.NaN;
371        axis.MajorTickMark.Interval = double.NaN;
372        axis.LabelStyle.Interval = double.NaN;
373      } else {
374        axis.Minimum = axis.Minimum;
375        axis.Maximum = axis.Maximum;
376        axis.MajorGrid.Interval = axis.MajorGrid.Interval;
377        axis.MajorTickMark.Interval = axis.MajorTickMark.Interval;
378        axis.LabelStyle.Interval = axis.LabelStyle.Interval;
379      }
380    }
381
[3428]382    private void AddDataPoint(IRun run) {
[3349]383      double? xValue;
384      double? yValue;
[3411]385      double? sizeValue;
[3428]386      Series series = this.chart.Series[0];
[3726]387
[4845]388      xValue = GetValue(run, xAxisValue);
389      yValue = GetValue(run, yAxisValue);
390      sizeValue = GetValue(run, sizeAxisValue);
[3726]391
[3543]392      if (xValue.HasValue && yValue.HasValue && sizeValue.HasValue) {
[3701]393        xValue = xValue.Value;
394        yValue = yValue.Value;
[5824]395
[3428]396        if (run.Visible) {
[3411]397          DataPoint point = new DataPoint(xValue.Value, new double[] { yValue.Value, sizeValue.Value });
[3428]398          point.Tag = run;
[3411]399          series.Points.Add(point);
[4883]400          if (!runToDataPointMapping.ContainsKey(run)) runToDataPointMapping.Add(run, new List<DataPoint>());
401          runToDataPointMapping[run].Add(point);
[9312]402          UpdateRun(run);
[3411]403        }
[3349]404      }
405    }
[3524]406    private double? GetValue(IRun run, string columnName) {
407      if (run == null || string.IsNullOrEmpty(columnName))
[3349]408        return null;
409
[3524]410      if (Enum.IsDefined(typeof(AxisDimension), columnName)) {
411        AxisDimension axisDimension = (AxisDimension)Enum.Parse(typeof(AxisDimension), columnName);
412        return GetValue(run, axisDimension);
413      } else if (Enum.IsDefined(typeof(SizeDimension), columnName)) {
414        SizeDimension sizeDimension = (SizeDimension)Enum.Parse(typeof(SizeDimension), columnName);
415        return GetValue(run, sizeDimension);
416      } else {
417        int columnIndex = Matrix.ColumnNames.ToList().IndexOf(columnName);
418        IItem value = Content.GetValue(run, columnIndex);
419        if (value == null)
420          return null;
[3447]421
[3524]422        DoubleValue doubleValue = value as DoubleValue;
423        IntValue intValue = value as IntValue;
[4049]424        TimeSpanValue timeSpanValue = value as TimeSpanValue;
[3543]425        double? ret = null;
426        if (doubleValue != null) {
427          if (!double.IsNaN(doubleValue.Value) && !double.IsInfinity(doubleValue.Value))
428            ret = doubleValue.Value;
429        } else if (intValue != null)
[3524]430          ret = intValue.Value;
[4049]431        else if (timeSpanValue != null) {
432          ret = timeSpanValue.Value.TotalSeconds;
433        } else
[3524]434          ret = GetCategoricalValue(columnIndex, value.ToString());
[3447]435
[3524]436        return ret;
437      }
[3349]438    }
[11007]439    private double? GetCategoricalValue(int dimension, string value) {
[9235]440      if (!this.categoricalMapping.ContainsKey(dimension)) {
[3349]441        this.categoricalMapping[dimension] = new Dictionary<object, double>();
[9435]442        var orderedCategories = Content.Where(r => r.Visible && Content.GetValue(r, dimension) != null).Select(r => Content.GetValue(r, dimension).ToString())
443                                    .Distinct().OrderBy(x => x, new NaturalStringComparer());
[9235]444        int count = 1;
445        foreach (var category in orderedCategories) {
446          this.categoricalMapping[dimension].Add(category, count);
447          count++;
448        }
[3349]449      }
[11007]450      if (!this.categoricalMapping[dimension].ContainsKey(value)) return null;
[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();
[11095]669      //mkommend: combobox.SelectedIndex could not be used as this changes during hovering over possible values
[11024]670      var xSAxisSelectedIndex = xAxisValue == null ? 0 : xAxisComboBox.Items.IndexOf(xAxisValue);
671      var ySAxisSelectedIndex = yAxisValue == null ? 0 : xAxisComboBox.Items.IndexOf(yAxisValue);
672      SetCustomAxisLabels(xAxis, xSAxisSelectedIndex - axisDimensionCount);
673      SetCustomAxisLabels(yAxis, ySAxisSelectedIndex - axisDimensionCount);
674      if (xAxisValue != null)
675        xAxis.Title = xAxisValue;
[11344]676      if (yAxisValue != null)
677        yAxis.Title = yAxisValue;
[3349]678    }
[4049]679
680    private void chart_AxisViewChanged(object sender, System.Windows.Forms.DataVisualization.Charting.ViewEventArgs e) {
681      this.UpdateAxisLabels();
682    }
683
[3411]684    private void SetCustomAxisLabels(Axis axis, int dimension) {
685      axis.CustomLabels.Clear();
[3349]686      if (categoricalMapping.ContainsKey(dimension)) {
687        foreach (var pair in categoricalMapping[dimension]) {
[3536]688          string labelText = pair.Key.ToString();
[4212]689          CustomLabel label = new CustomLabel();
690          label.ToolTip = labelText;
[3543]691          if (labelText.Length > 25)
692            labelText = labelText.Substring(0, 25) + " ... ";
[4212]693          label.Text = labelText;
[3349]694          label.GridTicks = GridTickTypes.TickMark;
[4212]695          label.FromPosition = pair.Value - 0.5;
696          label.ToPosition = pair.Value + 0.5;
697          axis.CustomLabels.Add(label);
[3349]698        }
[4049]699      } else if (dimension > 0 && Content.GetValue(0, dimension) is TimeSpanValue) {
700        this.chart.ChartAreas[0].RecalculateAxesScale();
701        for (double i = axis.Minimum; i <= axis.Maximum; i += axis.LabelStyle.Interval) {
702          TimeSpan time = TimeSpan.FromSeconds(i);
[6096]703          string x = string.Format("{0:00}:{1:00}:{2:00}", time.Hours, time.Minutes, time.Seconds);
[4058]704          axis.CustomLabels.Add(i - axis.LabelStyle.Interval / 2, i + axis.LabelStyle.Interval / 2, x);
[4049]705        }
[3349]706      }
707    }
[3411]708
709    private void zoomButton_CheckedChanged(object sender, EventArgs e) {
710      this.isSelecting = selectButton.Checked;
[9435]711      this.colorRunsButton.Enabled = this.isSelecting;
[9312]712      this.colorDialogButton.Enabled = this.isSelecting;
713      this.hideRunsButton.Enabled = this.isSelecting;
[3411]714      this.chart.ChartAreas[0].AxisX.ScaleView.Zoomable = !isSelecting;
715      this.chart.ChartAreas[0].AxisY.ScaleView.Zoomable = !isSelecting;
[9312]716      ClearSelectedRuns();
[3411]717    }
[4653]718
[6673]719    private void ContextMenuStrip_Opening(object sender, System.ComponentModel.CancelEventArgs e) {
[9448]720      hideRunsToolStripMenuItem.Visible = selectedRuns.Any();
[9435]721    }
[6673]722
[9435]723    private void unhideAllRunToolStripMenuItem_Click(object sender, EventArgs e) {
724      visibilityConstraint.ConstraintData.Clear();
725      if (Content.Constraints.Contains(visibilityConstraint)) Content.Constraints.Remove(visibilityConstraint);
[6673]726    }
[9435]727    private void hideRunsToolStripMenuItem_Click(object sender, EventArgs e) {
[11007]728      //ToList is necessary to prevent lazy evaluation
729      HideRuns(selectedRuns.ToList());
[9435]730      //could not use ClearSelectedRuns as the runs are not visible anymore
731      selectedRuns.Clear();
[6673]732    }
[9312]733    private void hideRunsButton_Click(object sender, EventArgs e) {
[11007]734      //ToList is necessary to prevent lazy evaluation
735      HideRuns(selectedRuns.ToList());
[9435]736      //could not use ClearSelectedRuns as the runs are not visible anymore
737      selectedRuns.Clear();
[9312]738    }
[6673]739
[9435]740    private void HideRuns(IEnumerable<IRun> runs) {
741      visibilityConstraint.Active = false;
742      if (!Content.Constraints.Contains(visibilityConstraint)) Content.Constraints.Add(visibilityConstraint);
[9448]743      foreach (var run in runs) {
[9435]744        visibilityConstraint.ConstraintData.Add(run);
745      }
746      visibilityConstraint.Active = true;
747    }
748
[9312]749    private void ClearSelectedRuns() {
750      foreach (var run in selectedRuns) {
751        foreach (var point in runToDataPointMapping[run]) {
752          point.MarkerStyle = MarkerStyle.Circle;
[9404]753          point.Color = Color.FromArgb(255 - LogTransform(transparencyTrackBar.Value), run.Color);
[9312]754        }
755      }
756      selectedRuns.Clear();
757    }
758
[9404]759    // returns a value in [0..255]
760    private int LogTransform(int x) {
761      double min = transparencyTrackBar.Minimum;
762      double max = transparencyTrackBar.Maximum;
763      double r = (x - min) / (max - min);  // r \in [0..1]
[9441]764      double l = Math.Max(Math.Min((1.0 - Math.Pow(0.05, r)) / 0.95, 1), 0); // l \in [0..1]
[9404]765      return (int)Math.Round(255.0 * l);
766    }
767
[4653]768    private void openBoxPlotViewToolStripMenuItem_Click(object sender, EventArgs e) {
769      RunCollectionBoxPlotView boxplotView = new RunCollectionBoxPlotView();
770      boxplotView.Content = this.Content;
771      boxplotView.xAxisComboBox.SelectedItem = xAxisComboBox.SelectedItem;
772      boxplotView.yAxisComboBox.SelectedItem = yAxisComboBox.SelectedItem;
773      boxplotView.Show();
774    }
[9190]775
776    private void getDataAsMatrixToolStripMenuItem_Click(object sender, EventArgs e) {
777      int xCol = Matrix.ColumnNames.ToList().IndexOf(xAxisValue);
[9267]778      int yCol = Matrix.ColumnNames.ToList().IndexOf(yAxisValue);
779
[9190]780      var grouped = new Dictionary<string, List<string>>();
781      Dictionary<double, string> reverseMapping = null;
782      if (categoricalMapping.ContainsKey(xCol))
783        reverseMapping = categoricalMapping[xCol].ToDictionary(x => x.Value, y => y.Key.ToString());
784      foreach (var run in Content.Where(r => r.Visible)) {
785        var x = GetValue(run, xAxisValue);
[9267]786        object y;
787        if (categoricalMapping.ContainsKey(yCol))
788          y = Content.GetValue(run, yAxisValue);
789        else y = GetValue(run, yAxisValue);
790        if (!(x.HasValue && y != null)) continue;
[9190]791
792        var category = reverseMapping == null ? x.Value.ToString() : reverseMapping[x.Value];
793        if (!grouped.ContainsKey(category)) grouped[category] = new List<string>();
[9267]794        grouped[category].Add(y.ToString());
[9190]795      }
796
797      if (!grouped.Any()) return;
798      var matrix = new StringMatrix(grouped.Values.Max(x => x.Count), grouped.Count) {
799        ColumnNames = grouped.Keys.ToArray()
800      };
801      int i = 0;
802      foreach (var col in matrix.ColumnNames) {
803        int j = 0;
804        foreach (var y in grouped[col])
805          matrix[j++, i] = y;
806        i++;
807      }
[9267]808      matrix.SortableView = false;
809      var view = MainFormManager.MainForm.ShowContent(matrix);
810      view.ReadOnly = true;
[9190]811    }
[9276]812
813    private void transparencyTrackBar_ValueChanged(object sender, EventArgs e) {
[9312]814      foreach (var run in Content)
815        UpdateRun(run);
[9276]816    }
[3411]817    #endregion
[4799]818
[9312]819    #region coloring
[9435]820    private void colorResetToolStripMenuItem_Click(object sender, EventArgs e) {
821      Content.UpdateOfRunsInProgress = true;
822
823      IEnumerable<IRun> runs;
824      if (selectedRuns.Any()) runs = selectedRuns;
825      else runs = Content;
826
827      foreach (var run in runs)
828        run.Color = Color.Black;
829      ClearSelectedRuns();
830
831      Content.UpdateOfRunsInProgress = false;
832    }
[9312]833    private void colorDialogButton_Click(object sender, EventArgs e) {
834      if (colorDialog.ShowDialog(this) == DialogResult.OK) {
[9435]835        this.colorRunsButton.Image = this.GenerateImage(16, 16, this.colorDialog.Color);
836        colorRunsButton_Click(sender, e);
[9312]837      }
838    }
839    private Image GenerateImage(int width, int height, Color fillColor) {
840      Image colorImage = new Bitmap(width, height);
841      using (Graphics gfx = Graphics.FromImage(colorImage)) {
842        using (SolidBrush brush = new SolidBrush(fillColor)) {
843          gfx.FillRectangle(brush, 0, 0, width, height);
844        }
845      }
846      return colorImage;
847    }
848
849    private void colorRunsButton_Click(object sender, EventArgs e) {
850      if (!selectedRuns.Any()) return;
851      Content.UpdateOfRunsInProgress = true;
852      foreach (var run in selectedRuns)
853        run.Color = colorDialog.Color;
854
855      ClearSelectedRuns();
856      Content.UpdateOfRunsInProgress = false;
857    }
858
[4799]859    private void colorXAxisButton_Click(object sender, EventArgs e) {
[4845]860      ColorRuns(xAxisValue);
[4799]861    }
862    private void colorYAxisButton_Click(object sender, EventArgs e) {
[4845]863      ColorRuns(yAxisValue);
864    }
865    private void ColorRuns(string axisValue) {
[9235]866      var runs = Content.Where(r => r.Visible).Select(r => new { Run = r, Value = GetValue(r, axisValue) }).Where(r => r.Value.HasValue).ToList();
[4845]867      double minValue = runs.Min(r => r.Value.Value);
868      double maxValue = runs.Max(r => r.Value.Value);
869      double range = maxValue - minValue;
[9236]870      // UpdateOfRunsInProgress has to be set to true, otherwise run_Changed is called all the time (also in other views)
871      Content.UpdateOfRunsInProgress = true;
[9235]872      if (range.IsAlmost(0)) {
873        Color c = ColorGradient.Colors[0];
874        runs.ForEach(r => r.Run.Color = c);
875      } else {
876        int maxColorIndex = ColorGradient.Colors.Count - 1;
877        foreach (var r in runs) {
878          int colorIndex = (int)(maxColorIndex * (r.Value - minValue) / (range));
879          r.Run.Color = ColorGradient.Colors[colorIndex];
880        }
[4799]881      }
[9236]882      Content.UpdateOfRunsInProgress = false;
[4799]883    }
884    #endregion
[3349]885  }
886}
Note: See TracBrowser for help on using the repository browser.