Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 8832 was 8832, checked in by gkronber, 12 years ago

#1918 suggested fix for strange method SetAutomaticUpdateOfAxis(). Exception is gone but don't know if originally intended functionality is still intact.

File size: 29.9 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2012 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
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;
28using HeuristicLab.Common;
29using HeuristicLab.Core;
30using HeuristicLab.Data;
31using HeuristicLab.MainForm;
32using HeuristicLab.MainForm.WindowsForms;
33
34namespace HeuristicLab.Optimization.Views {
35  [View("RunCollection BubbleChart")]
36  [Content(typeof(RunCollection), false)]
37  public partial class RunCollectionBubbleChartView : AsynchronousContentView {
38    private enum SizeDimension { Constant = 0 }
39    private enum AxisDimension { Index = 0 }
40
41    private string xAxisValue;
42    private string yAxisValue;
43    private string sizeAxisValue;
44
45    private Dictionary<IRun, List<DataPoint>> runToDataPointMapping;
46    private Dictionary<int, Dictionary<object, double>> categoricalMapping;
47    private Dictionary<IRun, double> xJitter;
48    private Dictionary<IRun, double> yJitter;
49    private double xJitterFactor = 0.0;
50    private double yJitterFactor = 0.0;
51    private Random random;
52    private bool isSelecting = false;
53    private bool suppressUpdates = false;
54
55    public RunCollectionBubbleChartView() {
56      InitializeComponent();
57
58      chart.ContextMenuStrip.Items.Insert(0, hideRunToolStripMenuItem);
59      chart.ContextMenuStrip.Items.Insert(1, openBoxPlotViewToolStripMenuItem);
60      chart.ContextMenuStrip.Opening += new System.ComponentModel.CancelEventHandler(ContextMenuStrip_Opening);
61
62      runToDataPointMapping = new Dictionary<IRun, List<DataPoint>>();
63      categoricalMapping = new Dictionary<int, Dictionary<object, double>>();
64      xJitter = new Dictionary<IRun, double>();
65      yJitter = new Dictionary<IRun, double>();
66      random = new Random();
67
68      colorDialog.Color = Color.Black;
69      colorButton.Image = this.GenerateImage(16, 16, this.colorDialog.Color);
70      isSelecting = false;
71
72      chart.CustomizeAllChartAreas();
73      chart.ChartAreas[0].CursorX.Interval = 1;
74      chart.ChartAreas[0].CursorY.Interval = 1;
75      chart.ChartAreas[0].AxisX.ScaleView.Zoomable = !this.isSelecting;
76      chart.ChartAreas[0].AxisY.ScaleView.Zoomable = !this.isSelecting;
77    }
78
79    public new RunCollection Content {
80      get { return (RunCollection)base.Content; }
81      set { base.Content = value; }
82    }
83    public IStringConvertibleMatrix Matrix {
84      get { return this.Content; }
85    }
86
87    protected override void RegisterContentEvents() {
88      base.RegisterContentEvents();
89      Content.Reset += new EventHandler(Content_Reset);
90      Content.ColumnNamesChanged += new EventHandler(Content_ColumnNamesChanged);
91      Content.ItemsAdded += new HeuristicLab.Collections.CollectionItemsChangedEventHandler<IRun>(Content_ItemsAdded);
92      Content.ItemsRemoved += new HeuristicLab.Collections.CollectionItemsChangedEventHandler<IRun>(Content_ItemsRemoved);
93      Content.CollectionReset += new HeuristicLab.Collections.CollectionItemsChangedEventHandler<IRun>(Content_CollectionReset);
94      Content.UpdateOfRunsInProgressChanged += new EventHandler(Content_UpdateOfRunsInProgressChanged);
95      Content.AlgorithmNameChanged += new EventHandler(Content_AlgorithmNameChanged);
96      RegisterRunEvents(Content);
97    }
98    protected override void DeregisterContentEvents() {
99      base.DeregisterContentEvents();
100      Content.Reset -= new EventHandler(Content_Reset);
101      Content.ColumnNamesChanged -= new EventHandler(Content_ColumnNamesChanged);
102      Content.ItemsAdded -= new HeuristicLab.Collections.CollectionItemsChangedEventHandler<IRun>(Content_ItemsAdded);
103      Content.ItemsRemoved -= new HeuristicLab.Collections.CollectionItemsChangedEventHandler<IRun>(Content_ItemsRemoved);
104      Content.CollectionReset -= new HeuristicLab.Collections.CollectionItemsChangedEventHandler<IRun>(Content_CollectionReset);
105      Content.UpdateOfRunsInProgressChanged -= new EventHandler(Content_UpdateOfRunsInProgressChanged);
106      Content.AlgorithmNameChanged -= new EventHandler(Content_AlgorithmNameChanged);
107      DeregisterRunEvents(Content);
108    }
109    protected virtual void RegisterRunEvents(IEnumerable<IRun> runs) {
110      foreach (IRun run in runs)
111        run.Changed += new EventHandler(run_Changed);
112    }
113    protected virtual void DeregisterRunEvents(IEnumerable<IRun> runs) {
114      foreach (IRun run in runs)
115        run.Changed -= new EventHandler(run_Changed);
116    }
117
118    private void Content_CollectionReset(object sender, HeuristicLab.Collections.CollectionItemsChangedEventArgs<IRun> e) {
119      DeregisterRunEvents(e.OldItems);
120      RegisterRunEvents(e.Items);
121    }
122    private void Content_ItemsRemoved(object sender, HeuristicLab.Collections.CollectionItemsChangedEventArgs<IRun> e) {
123      DeregisterRunEvents(e.Items);
124    }
125    private void Content_ItemsAdded(object sender, HeuristicLab.Collections.CollectionItemsChangedEventArgs<IRun> e) {
126      RegisterRunEvents(e.Items);
127    }
128    private void run_Changed(object sender, EventArgs e) {
129      if (InvokeRequired)
130        this.Invoke(new EventHandler(run_Changed), sender, e);
131      else {
132        IRun run = (IRun)sender;
133        UpdateRun(run);
134      }
135    }
136
137    private void UpdateRun(IRun run) {
138      if (!suppressUpdates) {
139        if (runToDataPointMapping.ContainsKey(run)) {
140          foreach (DataPoint point in runToDataPointMapping[run]) {
141            point.Color = run.Color;
142            if (!run.Visible) {
143              this.chart.Series[0].Points.Remove(point);
144              UpdateCursorInterval();
145              chart.ChartAreas[0].RecalculateAxesScale();
146            }
147          }
148          if (!run.Visible) runToDataPointMapping.Remove(run);
149        } else {
150          AddDataPoint(run);
151          UpdateCursorInterval();
152          chart.ChartAreas[0].RecalculateAxesScale();
153        }
154
155        if (this.chart.Series[0].Points.Count == 0)
156          noRunsLabel.Visible = true;
157        else
158          noRunsLabel.Visible = false;
159      }
160    }
161
162    protected override void OnContentChanged() {
163      base.OnContentChanged();
164      this.categoricalMapping.Clear();
165      UpdateComboBoxes();
166      UpdateDataPoints();
167      UpdateCaption();
168    }
169    private void Content_ColumnNamesChanged(object sender, EventArgs e) {
170      if (InvokeRequired)
171        Invoke(new EventHandler(Content_ColumnNamesChanged), sender, e);
172      else
173        UpdateComboBoxes();
174    }
175
176    private void UpdateCaption() {
177      Caption = Content != null ? Content.AlgorithmName + "Bubble Chart" : ViewAttribute.GetViewName(GetType());
178    }
179
180    private void UpdateComboBoxes() {
181      string selectedXAxis = (string)this.xAxisComboBox.SelectedItem;
182      string selectedYAxis = (string)this.yAxisComboBox.SelectedItem;
183      string selectedSizeAxis = (string)this.sizeComboBox.SelectedItem;
184      this.xAxisComboBox.Items.Clear();
185      this.yAxisComboBox.Items.Clear();
186      this.sizeComboBox.Items.Clear();
187      if (Content != null) {
188        string[] additionalAxisDimension = Enum.GetNames(typeof(AxisDimension));
189        this.xAxisComboBox.Items.AddRange(additionalAxisDimension);
190        this.xAxisComboBox.Items.AddRange(Matrix.ColumnNames.ToArray());
191        this.yAxisComboBox.Items.AddRange(additionalAxisDimension);
192        this.yAxisComboBox.Items.AddRange(Matrix.ColumnNames.ToArray());
193        string[] additionalSizeDimension = Enum.GetNames(typeof(SizeDimension));
194        this.sizeComboBox.Items.AddRange(additionalSizeDimension);
195        this.sizeComboBox.Items.AddRange(Matrix.ColumnNames.ToArray());
196        this.sizeComboBox.SelectedItem = SizeDimension.Constant.ToString();
197
198        bool changed = false;
199        if (selectedXAxis != null && xAxisComboBox.Items.Contains(selectedXAxis)) {
200          xAxisComboBox.SelectedItem = selectedXAxis;
201          changed = true;
202        }
203        if (selectedYAxis != null && yAxisComboBox.Items.Contains(selectedYAxis)) {
204          yAxisComboBox.SelectedItem = selectedYAxis;
205          changed = true;
206        }
207        if (selectedSizeAxis != null && sizeComboBox.Items.Contains(selectedSizeAxis)) {
208          sizeComboBox.SelectedItem = selectedSizeAxis;
209          changed = true;
210        }
211        if (changed)
212          UpdateDataPoints();
213      }
214    }
215
216
217    private void Content_UpdateOfRunsInProgressChanged(object sender, EventArgs e) {
218      if (InvokeRequired)
219        Invoke(new EventHandler(Content_UpdateOfRunsInProgressChanged), sender, e);
220      else {
221        suppressUpdates = Content.UpdateOfRunsInProgress;
222        if (!suppressUpdates) UpdateDataPoints();
223      }
224    }
225
226    private void Content_AlgorithmNameChanged(object sender, EventArgs e) {
227      if (InvokeRequired)
228        Invoke(new EventHandler(Content_AlgorithmNameChanged), sender, e);
229      else UpdateCaption();
230    }
231
232    private void Content_Reset(object sender, EventArgs e) {
233      if (InvokeRequired)
234        Invoke(new EventHandler(Content_Reset), sender, e);
235      else {
236        this.categoricalMapping.Clear();
237        UpdateDataPoints();
238      }
239    }
240
241    private void UpdateDataPoints() {
242      Series series = this.chart.Series[0];
243      series.Points.Clear();
244      runToDataPointMapping.Clear();
245
246      chart.ChartAreas[0].AxisX.IsMarginVisible = xAxisValue != AxisDimension.Index.ToString();
247      chart.ChartAreas[0].AxisY.IsMarginVisible = yAxisValue != AxisDimension.Index.ToString();
248
249      if (Content != null) {
250        foreach (IRun run in this.Content)
251          this.AddDataPoint(run);
252
253        if (this.chart.Series[0].Points.Count == 0)
254          noRunsLabel.Visible = true;
255        else {
256          noRunsLabel.Visible = false;
257          UpdateMarkerSizes();
258          UpdateCursorInterval();
259        }
260      }
261      var xAxis = chart.ChartAreas[0].AxisX;
262      var yAxis = chart.ChartAreas[0].AxisY;
263      xTrackBar.Value = 0;
264      yTrackBar.Value = 0;
265    }
266
267    private void UpdateMarkerSizes() {
268      double[] sizeValues = this.chart.Series[0].Points.Select(p => p.YValues[1]).ToArray();
269      double minSizeValue = sizeValues.Min();
270      double maxSizeValue = sizeValues.Max();
271
272      for (int i = 0; i < sizeValues.Length; i++) {
273        DataPoint point = this.chart.Series[0].Points[i];
274        double sizeRange = maxSizeValue - minSizeValue;
275        double relativeSize = (point.YValues[1] - minSizeValue);
276
277        if (sizeRange > double.Epsilon) relativeSize /= sizeRange;
278        else relativeSize = 1;
279
280        point.MarkerSize = (int)Math.Round((sizeTrackBar.Value - sizeTrackBar.Minimum) * relativeSize + sizeTrackBar.Minimum);
281      }
282    }
283
284
285    private class AxisParameters {
286      public double min, max, majorGridInterval, majorTickMarkInterval, labelStyleInterval;
287    }
288    private void UpdateDataPointJitter() {
289      var xAxis = this.chart.ChartAreas[0].AxisX;
290      var yAxis = this.chart.ChartAreas[0].AxisY;
291
292
293      // disable automatic update of axis
294      var disabledParameters = new AxisParameters();
295      disabledParameters.min = disabledParameters.max = disabledParameters.majorGridInterval = disabledParameters.majorTickMarkInterval = disabledParameters.labelStyleInterval = double.NaN;
296
297      AxisParameters savedXParameters, savedYParameters;
298      savedXParameters = SetAxisParameters(xAxis, disabledParameters);
299      savedYParameters = SetAxisParameters(yAxis, disabledParameters);
300
301      foreach (DataPoint point in chart.Series[0].Points) {
302        IRun run = (IRun)point.Tag;
303        double xValue = GetValue(run, xAxisValue).Value;
304        double yValue = GetValue(run, yAxisValue).Value;
305
306        if (!xJitterFactor.IsAlmost(0.0))
307          xValue += 0.1 * GetXJitter(run) * xJitterFactor * (savedXParameters.max - savedXParameters.min);
308        if (!yJitterFactor.IsAlmost(0.0))
309          yValue += 0.1 * GetYJitter(run) * yJitterFactor * (savedYParameters.max - savedYParameters.min);
310
311        point.XValue = xValue;
312        point.YValues[0] = yValue;
313      }
314      SetAxisParameters(xAxis, savedXParameters);
315      SetAxisParameters(yAxis, savedYParameters);
316    }
317
318    private AxisParameters SetAxisParameters(Axis axis, AxisParameters @new) {
319      var old = new AxisParameters();
320      old.min = axis.Minimum;
321      old.max = axis.Maximum;
322      old.majorGridInterval = axis.MajorGrid.Interval;
323      old.majorTickMarkInterval = axis.MajorTickMark.Interval;
324      old.labelStyleInterval = axis.LabelStyle.Interval;
325
326      axis.Maximum = @new.max;
327      axis.Minimum = @new.min;
328      axis.MajorGrid.Interval = @new.majorGridInterval;
329      axis.MajorTickMark.Interval = @new.majorTickMarkInterval;
330      axis.LabelStyle.Interval = @new.labelStyleInterval;
331      return old;
332    }
333
334    private void AddDataPoint(IRun run) {
335      double? xValue;
336      double? yValue;
337      double? sizeValue;
338      Series series = this.chart.Series[0];
339
340      xValue = GetValue(run, xAxisValue);
341      yValue = GetValue(run, yAxisValue);
342      sizeValue = GetValue(run, sizeAxisValue);
343
344      if (xValue.HasValue && yValue.HasValue && sizeValue.HasValue) {
345        xValue = xValue.Value;
346
347        yValue = yValue.Value;
348
349        if (run.Visible) {
350          DataPoint point = new DataPoint(xValue.Value, new double[] { yValue.Value, sizeValue.Value });
351          point.Tag = run;
352          point.Color = run.Color;
353          series.Points.Add(point);
354          if (!runToDataPointMapping.ContainsKey(run)) runToDataPointMapping.Add(run, new List<DataPoint>());
355          runToDataPointMapping[run].Add(point);
356        }
357      }
358    }
359    private double? GetValue(IRun run, string columnName) {
360      if (run == null || string.IsNullOrEmpty(columnName))
361        return null;
362
363      if (Enum.IsDefined(typeof(AxisDimension), columnName)) {
364        AxisDimension axisDimension = (AxisDimension)Enum.Parse(typeof(AxisDimension), columnName);
365        return GetValue(run, axisDimension);
366      } else if (Enum.IsDefined(typeof(SizeDimension), columnName)) {
367        SizeDimension sizeDimension = (SizeDimension)Enum.Parse(typeof(SizeDimension), columnName);
368        return GetValue(run, sizeDimension);
369      } else {
370        int columnIndex = Matrix.ColumnNames.ToList().IndexOf(columnName);
371        IItem value = Content.GetValue(run, columnIndex);
372        if (value == null)
373          return null;
374
375        DoubleValue doubleValue = value as DoubleValue;
376        IntValue intValue = value as IntValue;
377        TimeSpanValue timeSpanValue = value as TimeSpanValue;
378        double? ret = null;
379        if (doubleValue != null) {
380          if (!double.IsNaN(doubleValue.Value) && !double.IsInfinity(doubleValue.Value))
381            ret = doubleValue.Value;
382        } else if (intValue != null)
383          ret = intValue.Value;
384        else if (timeSpanValue != null) {
385          ret = timeSpanValue.Value.TotalSeconds;
386        } else
387          ret = GetCategoricalValue(columnIndex, value.ToString());
388
389        return ret;
390      }
391    }
392    private double GetCategoricalValue(int dimension, string value) {
393      if (!this.categoricalMapping.ContainsKey(dimension))
394        this.categoricalMapping[dimension] = new Dictionary<object, double>();
395      if (!this.categoricalMapping[dimension].ContainsKey(value)) {
396        if (this.categoricalMapping[dimension].Values.Count == 0)
397          this.categoricalMapping[dimension][value] = 1.0;
398        else
399          this.categoricalMapping[dimension][value] = this.categoricalMapping[dimension].Values.Max() + 1.0;
400      }
401      return this.categoricalMapping[dimension][value];
402    }
403    private double GetValue(IRun run, AxisDimension axisDimension) {
404      double value = double.NaN;
405      switch (axisDimension) {
406        case AxisDimension.Index: {
407            value = Content.ToList().IndexOf(run);
408            break;
409          }
410        default: {
411            throw new ArgumentException("No handling strategy for " + axisDimension.ToString() + " is defined.");
412          }
413      }
414      return value;
415    }
416    private double GetValue(IRun run, SizeDimension sizeDimension) {
417      double value = double.NaN;
418      switch (sizeDimension) {
419        case SizeDimension.Constant: {
420            value = 2;
421            break;
422          }
423        default: {
424            throw new ArgumentException("No handling strategy for " + sizeDimension.ToString() + " is defined.");
425          }
426      }
427      return value;
428    }
429    private void UpdateCursorInterval() {
430      Series series = chart.Series[0];
431      double[] xValues = (from point in series.Points
432                          where !point.IsEmpty
433                          select point.XValue)
434                    .DefaultIfEmpty(1.0)
435                    .ToArray();
436      double[] yValues = (from point in series.Points
437                          where !point.IsEmpty
438                          select point.YValues[0])
439                    .DefaultIfEmpty(1.0)
440                    .ToArray();
441
442      double xRange = xValues.Max() - xValues.Min();
443      double yRange = yValues.Max() - yValues.Min();
444      if (xRange.IsAlmost(0.0)) xRange = 1.0;
445      if (yRange.IsAlmost(0.0)) yRange = 1.0;
446      double xDigits = (int)Math.Log10(xRange) - 3;
447      double yDigits = (int)Math.Log10(yRange) - 3;
448      double xZoomInterval = Math.Pow(10, xDigits);
449      double yZoomInterval = Math.Pow(10, yDigits);
450      this.chart.ChartAreas[0].CursorX.Interval = xZoomInterval;
451      this.chart.ChartAreas[0].CursorY.Interval = yZoomInterval;
452
453      //code to handle TimeSpanValues correct
454      int axisDimensionCount = Enum.GetNames(typeof(AxisDimension)).Count();
455      int columnIndex = xAxisComboBox.SelectedIndex - axisDimensionCount;
456      if (columnIndex >= 0 && Content.GetValue(0, columnIndex) is TimeSpanValue)
457        this.chart.ChartAreas[0].CursorX.Interval = 1;
458      columnIndex = yAxisComboBox.SelectedIndex - axisDimensionCount;
459      if (columnIndex >= 0 && Content.GetValue(0, columnIndex) is TimeSpanValue)
460        this.chart.ChartAreas[0].CursorY.Interval = 1;
461    }
462
463    #region Drag & drop and tooltip
464    private void chart_MouseDoubleClick(object sender, MouseEventArgs e) {
465      HitTestResult h = this.chart.HitTest(e.X, e.Y, ChartElementType.DataPoint);
466      if (h.ChartElementType == ChartElementType.DataPoint) {
467        IRun run = (IRun)((DataPoint)h.Object).Tag;
468        IContentView view = MainFormManager.MainForm.ShowContent(run);
469        if (view != null) {
470          view.ReadOnly = this.ReadOnly;
471          view.Locked = this.Locked;
472        }
473
474        this.chart.ChartAreas[0].CursorX.SelectionStart = this.chart.ChartAreas[0].CursorX.SelectionEnd;
475        this.chart.ChartAreas[0].CursorY.SelectionStart = this.chart.ChartAreas[0].CursorY.SelectionEnd;
476      }
477      UpdateAxisLabels();
478    }
479
480    private void chart_MouseUp(object sender, MouseEventArgs e) {
481      if (isSelecting) {
482        System.Windows.Forms.DataVisualization.Charting.Cursor xCursor = chart.ChartAreas[0].CursorX;
483        System.Windows.Forms.DataVisualization.Charting.Cursor yCursor = chart.ChartAreas[0].CursorY;
484
485        double minX = Math.Min(xCursor.SelectionStart, xCursor.SelectionEnd);
486        double maxX = Math.Max(xCursor.SelectionStart, xCursor.SelectionEnd);
487        double minY = Math.Min(yCursor.SelectionStart, yCursor.SelectionEnd);
488        double maxY = Math.Max(yCursor.SelectionStart, yCursor.SelectionEnd);
489
490        //check for click to select model
491        if (minX == maxX && minY == maxY) {
492          HitTestResult hitTest = chart.HitTest(e.X, e.Y);
493          if (hitTest.ChartElementType == ChartElementType.DataPoint) {
494            int pointIndex = hitTest.PointIndex;
495            IRun run = (IRun)this.chart.Series[0].Points[pointIndex].Tag;
496            run.Color = colorDialog.Color;
497          }
498        } else {
499          List<DataPoint> selectedPoints = new List<DataPoint>();
500          foreach (DataPoint p in this.chart.Series[0].Points) {
501            if (p.XValue >= minX && p.XValue < maxX &&
502              p.YValues[0] >= minY && p.YValues[0] < maxY) {
503              selectedPoints.Add(p);
504            }
505          }
506          foreach (DataPoint p in selectedPoints) {
507            IRun run = (IRun)p.Tag;
508            run.Color = colorDialog.Color;
509          }
510        }
511        this.chart.ChartAreas[0].CursorX.SelectionStart = this.chart.ChartAreas[0].CursorX.SelectionEnd;
512        this.chart.ChartAreas[0].CursorY.SelectionStart = this.chart.ChartAreas[0].CursorY.SelectionEnd;
513      }
514    }
515
516    private void chart_MouseMove(object sender, MouseEventArgs e) {
517      HitTestResult h = this.chart.HitTest(e.X, e.Y);
518      string newTooltipText = string.Empty;
519      string oldTooltipText;
520      if (h.ChartElementType == ChartElementType.DataPoint) {
521        IRun run = (IRun)((DataPoint)h.Object).Tag;
522        newTooltipText = BuildTooltip(run);
523      } else if (h.ChartElementType == ChartElementType.AxisLabels) {
524        newTooltipText = ((CustomLabel)h.Object).ToolTip;
525      }
526
527      oldTooltipText = this.tooltip.GetToolTip(chart);
528      if (newTooltipText != oldTooltipText)
529        this.tooltip.SetToolTip(chart, newTooltipText);
530    }
531
532    private string BuildTooltip(IRun run) {
533      string tooltip;
534      tooltip = run.Name + System.Environment.NewLine;
535
536      double? xValue = this.GetValue(run, (string)xAxisComboBox.SelectedItem);
537      double? yValue = this.GetValue(run, (string)yAxisComboBox.SelectedItem);
538      double? sizeValue = this.GetValue(run, (string)sizeComboBox.SelectedItem);
539
540      string xString = xValue == null ? string.Empty : xValue.Value.ToString();
541      string yString = yValue == null ? string.Empty : yValue.Value.ToString();
542      string sizeString = sizeValue == null ? string.Empty : sizeValue.Value.ToString();
543
544      //code to handle TimeSpanValues correct
545      int axisDimensionCount = Enum.GetNames(typeof(AxisDimension)).Count();
546      int columnIndex = xAxisComboBox.SelectedIndex - axisDimensionCount;
547      if (xValue.HasValue && columnIndex > 0 && Content.GetValue(0, columnIndex) is TimeSpanValue) {
548        TimeSpan time = TimeSpan.FromSeconds(xValue.Value);
549        xString = string.Format("{0:00}:{1:00}:{2:00.00}", (int)time.TotalHours, time.Minutes, time.Seconds);
550      }
551      columnIndex = yAxisComboBox.SelectedIndex - axisDimensionCount;
552      if (yValue.HasValue && columnIndex > 0 && Content.GetValue(0, columnIndex) is TimeSpanValue) {
553        TimeSpan time = TimeSpan.FromSeconds(yValue.Value);
554        yString = string.Format("{0:00}:{1:00}:{2:00.00}", (int)time.TotalHours, time.Minutes, time.Seconds);
555      }
556
557      tooltip += xAxisComboBox.SelectedItem + " : " + xString + Environment.NewLine;
558      tooltip += yAxisComboBox.SelectedItem + " : " + yString + Environment.NewLine;
559      tooltip += sizeComboBox.SelectedItem + " : " + sizeString + Environment.NewLine;
560
561      return tooltip;
562    }
563    #endregion
564
565    #region GUI events and updating
566    private double GetXJitter(IRun run) {
567      if (!this.xJitter.ContainsKey(run))
568        this.xJitter[run] = random.NextDouble() * 2.0 - 1.0;
569      return this.xJitter[run];
570    }
571    private double GetYJitter(IRun run) {
572      if (!this.yJitter.ContainsKey(run))
573        this.yJitter[run] = random.NextDouble() * 2.0 - 1.0;
574      return this.yJitter[run];
575    }
576    private void jitterTrackBar_ValueChanged(object sender, EventArgs e) {
577      this.xJitterFactor = xTrackBar.Value / 100.0;
578      this.yJitterFactor = yTrackBar.Value / 100.0;
579      UpdateDataPointJitter();
580    }
581    private void sizeTrackBar_ValueChanged(object sender, EventArgs e) {
582      UpdateMarkerSizes();
583    }
584
585    private void AxisComboBox_SelectedValueChanged(object sender, EventArgs e) {
586      bool axisSelected = xAxisComboBox.SelectedIndex != -1 && yAxisComboBox.SelectedIndex != -1;
587      xTrackBar.Enabled = yTrackBar.Enabled = axisSelected;
588      colorXAxisButton.Enabled = colorYAxisButton.Enabled = axisSelected;
589
590      xAxisValue = (string)xAxisComboBox.SelectedItem;
591      yAxisValue = (string)yAxisComboBox.SelectedItem;
592      sizeAxisValue = (string)sizeComboBox.SelectedItem;
593
594      UpdateDataPoints();
595      UpdateAxisLabels();
596    }
597    private void UpdateAxisLabels() {
598      Axis xAxis = this.chart.ChartAreas[0].AxisX;
599      Axis yAxis = this.chart.ChartAreas[0].AxisY;
600      int axisDimensionCount = Enum.GetNames(typeof(AxisDimension)).Count();
601      SetCustomAxisLabels(xAxis, xAxisComboBox.SelectedIndex - axisDimensionCount);
602      SetCustomAxisLabels(yAxis, yAxisComboBox.SelectedIndex - axisDimensionCount);
603      if (xAxisComboBox.SelectedItem != null)
604        xAxis.Title = xAxisComboBox.SelectedItem.ToString();
605      if (yAxisComboBox.SelectedItem != null)
606        yAxis.Title = yAxisComboBox.SelectedItem.ToString();
607    }
608
609    private void chart_AxisViewChanged(object sender, System.Windows.Forms.DataVisualization.Charting.ViewEventArgs e) {
610      this.UpdateAxisLabels();
611    }
612
613    private void SetCustomAxisLabels(Axis axis, int dimension) {
614      axis.CustomLabels.Clear();
615      if (categoricalMapping.ContainsKey(dimension)) {
616        foreach (var pair in categoricalMapping[dimension]) {
617          string labelText = pair.Key.ToString();
618          CustomLabel label = new CustomLabel();
619          label.ToolTip = labelText;
620          if (labelText.Length > 25)
621            labelText = labelText.Substring(0, 25) + " ... ";
622          label.Text = labelText;
623          label.GridTicks = GridTickTypes.TickMark;
624          label.FromPosition = pair.Value - 0.5;
625          label.ToPosition = pair.Value + 0.5;
626          axis.CustomLabels.Add(label);
627        }
628      } else if (dimension > 0 && Content.GetValue(0, dimension) is TimeSpanValue) {
629        this.chart.ChartAreas[0].RecalculateAxesScale();
630        for (double i = axis.Minimum; i <= axis.Maximum; i += axis.LabelStyle.Interval) {
631          TimeSpan time = TimeSpan.FromSeconds(i);
632          string x = string.Format("{0:00}:{1:00}:{2:00}", time.Hours, time.Minutes, time.Seconds);
633          axis.CustomLabels.Add(i - axis.LabelStyle.Interval / 2, i + axis.LabelStyle.Interval / 2, x);
634        }
635      }
636    }
637
638    private void zoomButton_CheckedChanged(object sender, EventArgs e) {
639      this.isSelecting = selectButton.Checked;
640      this.colorButton.Enabled = this.isSelecting;
641      this.chart.ChartAreas[0].AxisX.ScaleView.Zoomable = !isSelecting;
642      this.chart.ChartAreas[0].AxisY.ScaleView.Zoomable = !isSelecting;
643    }
644    private void colorButton_Click(object sender, EventArgs e) {
645      if (colorDialog.ShowDialog(this) == DialogResult.OK) {
646        this.colorButton.Image = this.GenerateImage(16, 16, this.colorDialog.Color);
647      }
648    }
649    private Image GenerateImage(int width, int height, Color fillColor) {
650      Image colorImage = new Bitmap(width, height);
651      using (Graphics gfx = Graphics.FromImage(colorImage)) {
652        using (SolidBrush brush = new SolidBrush(fillColor)) {
653          gfx.FillRectangle(brush, 0, 0, width, height);
654        }
655      }
656      return colorImage;
657    }
658
659    private IRun runToHide = null;
660    private void ContextMenuStrip_Opening(object sender, System.ComponentModel.CancelEventArgs e) {
661      var pos = Control.MousePosition;
662      var chartPos = chart.PointToClient(pos);
663
664      HitTestResult h = this.chart.HitTest(chartPos.X, chartPos.Y);
665      if (h.ChartElementType == ChartElementType.DataPoint) {
666        runToHide = (IRun)((DataPoint)h.Object).Tag;
667        hideRunToolStripMenuItem.Visible = true;
668      } else {
669        runToHide = null;
670        hideRunToolStripMenuItem.Visible = false;
671      }
672
673    }
674    private void hideRunToolStripMenuItem_Click(object sender, EventArgs e) {
675      var constraint = Content.Constraints.OfType<RunCollectionContentConstraint>().Where(c => c.Active).FirstOrDefault();
676      if (constraint == null) {
677        constraint = new RunCollectionContentConstraint();
678        Content.Constraints.Add(constraint);
679        constraint.Active = true;
680      }
681      constraint.ConstraintData.Add(runToHide);
682    }
683
684    private void openBoxPlotViewToolStripMenuItem_Click(object sender, EventArgs e) {
685      RunCollectionBoxPlotView boxplotView = new RunCollectionBoxPlotView();
686      boxplotView.Content = this.Content;
687      boxplotView.xAxisComboBox.SelectedItem = xAxisComboBox.SelectedItem;
688      boxplotView.yAxisComboBox.SelectedItem = yAxisComboBox.SelectedItem;
689      boxplotView.Show();
690    }
691    #endregion
692
693    #region Automatic coloring
694    private void colorXAxisButton_Click(object sender, EventArgs e) {
695      ColorRuns(xAxisValue);
696    }
697
698    private void colorYAxisButton_Click(object sender, EventArgs e) {
699      ColorRuns(yAxisValue);
700    }
701
702    private void ColorRuns(string axisValue) {
703      var runs = Content.Where(r => r.Visible).Select(r => new { Run = r, Value = GetValue(r, axisValue) }).Where(r => r.Value.HasValue);
704      double minValue = runs.Min(r => r.Value.Value);
705      double maxValue = runs.Max(r => r.Value.Value);
706      double range = maxValue - minValue;
707
708      foreach (var r in runs) {
709        int colorIndex = 0;
710        if (!range.IsAlmost(0)) colorIndex = (int)((ColorGradient.Colors.Count - 1) * (r.Value.Value - minValue) / (range));
711        r.Run.Color = ColorGradient.Colors[colorIndex];
712      }
713    }
714    #endregion
715  }
716}
Note: See TracBrowser for help on using the repository browser.