Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 8835 was 8835, checked in by mkommend, 12 years ago

#1918: Refactored jittering in BubbleChartView to calculate axis range before the data points are modified and removed 'strange' method.

File size: 28.7 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      xTrackBar.Value = 0;
262      yTrackBar.Value = 0;
263    }
264
265    private void UpdateMarkerSizes() {
266      double[] sizeValues = this.chart.Series[0].Points.Select(p => p.YValues[1]).ToArray();
267      double minSizeValue = sizeValues.Min();
268      double maxSizeValue = sizeValues.Max();
269
270      for (int i = 0; i < sizeValues.Length; i++) {
271        DataPoint point = this.chart.Series[0].Points[i];
272        double sizeRange = maxSizeValue - minSizeValue;
273        double relativeSize = (point.YValues[1] - minSizeValue);
274
275        if (sizeRange > double.Epsilon) relativeSize /= sizeRange;
276        else relativeSize = 1;
277
278        point.MarkerSize = (int)Math.Round((sizeTrackBar.Value - sizeTrackBar.Minimum) * relativeSize + sizeTrackBar.Minimum);
279      }
280    }
281
282
283    private class AxisParameters {
284      public double min, max, majorGridInterval, majorTickMarkInterval, labelStyleInterval;
285    }
286    private void UpdateDataPointJitter() {
287      var xAxis = this.chart.ChartAreas[0].AxisX;
288      var yAxis = this.chart.ChartAreas[0].AxisY;
289
290      double xAxisRange = xAxis.Maximum - xAxis.Minimum;
291      double yAxisRange = yAxis.Maximum - yAxis.Minimum;
292
293      foreach (DataPoint point in chart.Series[0].Points) {
294        IRun run = (IRun)point.Tag;
295        double xValue = GetValue(run, xAxisValue).Value;
296        double yValue = GetValue(run, yAxisValue).Value;
297
298        if (!xJitterFactor.IsAlmost(0.0))
299          xValue += 0.1 * GetXJitter(run) * xJitterFactor * (xAxisRange);
300        if (!yJitterFactor.IsAlmost(0.0))
301          yValue += 0.1 * GetYJitter(run) * yJitterFactor * (yAxisRange);
302
303        point.XValue = xValue;
304        point.YValues[0] = yValue;
305      }
306
307    }
308
309    private void AddDataPoint(IRun run) {
310      double? xValue;
311      double? yValue;
312      double? sizeValue;
313      Series series = this.chart.Series[0];
314
315      xValue = GetValue(run, xAxisValue);
316      yValue = GetValue(run, yAxisValue);
317      sizeValue = GetValue(run, sizeAxisValue);
318
319      if (xValue.HasValue && yValue.HasValue && sizeValue.HasValue) {
320        xValue = xValue.Value;
321
322        yValue = yValue.Value;
323
324        if (run.Visible) {
325          DataPoint point = new DataPoint(xValue.Value, new double[] { yValue.Value, sizeValue.Value });
326          point.Tag = run;
327          point.Color = run.Color;
328          series.Points.Add(point);
329          if (!runToDataPointMapping.ContainsKey(run)) runToDataPointMapping.Add(run, new List<DataPoint>());
330          runToDataPointMapping[run].Add(point);
331        }
332      }
333    }
334    private double? GetValue(IRun run, string columnName) {
335      if (run == null || string.IsNullOrEmpty(columnName))
336        return null;
337
338      if (Enum.IsDefined(typeof(AxisDimension), columnName)) {
339        AxisDimension axisDimension = (AxisDimension)Enum.Parse(typeof(AxisDimension), columnName);
340        return GetValue(run, axisDimension);
341      } else if (Enum.IsDefined(typeof(SizeDimension), columnName)) {
342        SizeDimension sizeDimension = (SizeDimension)Enum.Parse(typeof(SizeDimension), columnName);
343        return GetValue(run, sizeDimension);
344      } else {
345        int columnIndex = Matrix.ColumnNames.ToList().IndexOf(columnName);
346        IItem value = Content.GetValue(run, columnIndex);
347        if (value == null)
348          return null;
349
350        DoubleValue doubleValue = value as DoubleValue;
351        IntValue intValue = value as IntValue;
352        TimeSpanValue timeSpanValue = value as TimeSpanValue;
353        double? ret = null;
354        if (doubleValue != null) {
355          if (!double.IsNaN(doubleValue.Value) && !double.IsInfinity(doubleValue.Value))
356            ret = doubleValue.Value;
357        } else if (intValue != null)
358          ret = intValue.Value;
359        else if (timeSpanValue != null) {
360          ret = timeSpanValue.Value.TotalSeconds;
361        } else
362          ret = GetCategoricalValue(columnIndex, value.ToString());
363
364        return ret;
365      }
366    }
367    private double GetCategoricalValue(int dimension, string value) {
368      if (!this.categoricalMapping.ContainsKey(dimension))
369        this.categoricalMapping[dimension] = new Dictionary<object, double>();
370      if (!this.categoricalMapping[dimension].ContainsKey(value)) {
371        if (this.categoricalMapping[dimension].Values.Count == 0)
372          this.categoricalMapping[dimension][value] = 1.0;
373        else
374          this.categoricalMapping[dimension][value] = this.categoricalMapping[dimension].Values.Max() + 1.0;
375      }
376      return this.categoricalMapping[dimension][value];
377    }
378    private double GetValue(IRun run, AxisDimension axisDimension) {
379      double value = double.NaN;
380      switch (axisDimension) {
381        case AxisDimension.Index: {
382            value = Content.ToList().IndexOf(run);
383            break;
384          }
385        default: {
386            throw new ArgumentException("No handling strategy for " + axisDimension.ToString() + " is defined.");
387          }
388      }
389      return value;
390    }
391    private double GetValue(IRun run, SizeDimension sizeDimension) {
392      double value = double.NaN;
393      switch (sizeDimension) {
394        case SizeDimension.Constant: {
395            value = 2;
396            break;
397          }
398        default: {
399            throw new ArgumentException("No handling strategy for " + sizeDimension.ToString() + " is defined.");
400          }
401      }
402      return value;
403    }
404    private void UpdateCursorInterval() {
405      Series series = chart.Series[0];
406      double[] xValues = (from point in series.Points
407                          where !point.IsEmpty
408                          select point.XValue)
409                    .DefaultIfEmpty(1.0)
410                    .ToArray();
411      double[] yValues = (from point in series.Points
412                          where !point.IsEmpty
413                          select point.YValues[0])
414                    .DefaultIfEmpty(1.0)
415                    .ToArray();
416
417      double xRange = xValues.Max() - xValues.Min();
418      double yRange = yValues.Max() - yValues.Min();
419      if (xRange.IsAlmost(0.0)) xRange = 1.0;
420      if (yRange.IsAlmost(0.0)) yRange = 1.0;
421      double xDigits = (int)Math.Log10(xRange) - 3;
422      double yDigits = (int)Math.Log10(yRange) - 3;
423      double xZoomInterval = Math.Pow(10, xDigits);
424      double yZoomInterval = Math.Pow(10, yDigits);
425      this.chart.ChartAreas[0].CursorX.Interval = xZoomInterval;
426      this.chart.ChartAreas[0].CursorY.Interval = yZoomInterval;
427
428      //code to handle TimeSpanValues correct
429      int axisDimensionCount = Enum.GetNames(typeof(AxisDimension)).Count();
430      int columnIndex = xAxisComboBox.SelectedIndex - axisDimensionCount;
431      if (columnIndex >= 0 && Content.GetValue(0, columnIndex) is TimeSpanValue)
432        this.chart.ChartAreas[0].CursorX.Interval = 1;
433      columnIndex = yAxisComboBox.SelectedIndex - axisDimensionCount;
434      if (columnIndex >= 0 && Content.GetValue(0, columnIndex) is TimeSpanValue)
435        this.chart.ChartAreas[0].CursorY.Interval = 1;
436    }
437
438    #region Drag & drop and tooltip
439    private void chart_MouseDoubleClick(object sender, MouseEventArgs e) {
440      HitTestResult h = this.chart.HitTest(e.X, e.Y, ChartElementType.DataPoint);
441      if (h.ChartElementType == ChartElementType.DataPoint) {
442        IRun run = (IRun)((DataPoint)h.Object).Tag;
443        IContentView view = MainFormManager.MainForm.ShowContent(run);
444        if (view != null) {
445          view.ReadOnly = this.ReadOnly;
446          view.Locked = this.Locked;
447        }
448
449        this.chart.ChartAreas[0].CursorX.SelectionStart = this.chart.ChartAreas[0].CursorX.SelectionEnd;
450        this.chart.ChartAreas[0].CursorY.SelectionStart = this.chart.ChartAreas[0].CursorY.SelectionEnd;
451      }
452      UpdateAxisLabels();
453    }
454
455    private void chart_MouseUp(object sender, MouseEventArgs e) {
456      if (isSelecting) {
457        System.Windows.Forms.DataVisualization.Charting.Cursor xCursor = chart.ChartAreas[0].CursorX;
458        System.Windows.Forms.DataVisualization.Charting.Cursor yCursor = chart.ChartAreas[0].CursorY;
459
460        double minX = Math.Min(xCursor.SelectionStart, xCursor.SelectionEnd);
461        double maxX = Math.Max(xCursor.SelectionStart, xCursor.SelectionEnd);
462        double minY = Math.Min(yCursor.SelectionStart, yCursor.SelectionEnd);
463        double maxY = Math.Max(yCursor.SelectionStart, yCursor.SelectionEnd);
464
465        //check for click to select model
466        if (minX == maxX && minY == maxY) {
467          HitTestResult hitTest = chart.HitTest(e.X, e.Y);
468          if (hitTest.ChartElementType == ChartElementType.DataPoint) {
469            int pointIndex = hitTest.PointIndex;
470            IRun run = (IRun)this.chart.Series[0].Points[pointIndex].Tag;
471            run.Color = colorDialog.Color;
472          }
473        } else {
474          List<DataPoint> selectedPoints = new List<DataPoint>();
475          foreach (DataPoint p in this.chart.Series[0].Points) {
476            if (p.XValue >= minX && p.XValue < maxX &&
477              p.YValues[0] >= minY && p.YValues[0] < maxY) {
478              selectedPoints.Add(p);
479            }
480          }
481          foreach (DataPoint p in selectedPoints) {
482            IRun run = (IRun)p.Tag;
483            run.Color = colorDialog.Color;
484          }
485        }
486        this.chart.ChartAreas[0].CursorX.SelectionStart = this.chart.ChartAreas[0].CursorX.SelectionEnd;
487        this.chart.ChartAreas[0].CursorY.SelectionStart = this.chart.ChartAreas[0].CursorY.SelectionEnd;
488      }
489    }
490
491    private void chart_MouseMove(object sender, MouseEventArgs e) {
492      HitTestResult h = this.chart.HitTest(e.X, e.Y);
493      string newTooltipText = string.Empty;
494      string oldTooltipText;
495      if (h.ChartElementType == ChartElementType.DataPoint) {
496        IRun run = (IRun)((DataPoint)h.Object).Tag;
497        newTooltipText = BuildTooltip(run);
498      } else if (h.ChartElementType == ChartElementType.AxisLabels) {
499        newTooltipText = ((CustomLabel)h.Object).ToolTip;
500      }
501
502      oldTooltipText = this.tooltip.GetToolTip(chart);
503      if (newTooltipText != oldTooltipText)
504        this.tooltip.SetToolTip(chart, newTooltipText);
505    }
506
507    private string BuildTooltip(IRun run) {
508      string tooltip;
509      tooltip = run.Name + System.Environment.NewLine;
510
511      double? xValue = this.GetValue(run, (string)xAxisComboBox.SelectedItem);
512      double? yValue = this.GetValue(run, (string)yAxisComboBox.SelectedItem);
513      double? sizeValue = this.GetValue(run, (string)sizeComboBox.SelectedItem);
514
515      string xString = xValue == null ? string.Empty : xValue.Value.ToString();
516      string yString = yValue == null ? string.Empty : yValue.Value.ToString();
517      string sizeString = sizeValue == null ? string.Empty : sizeValue.Value.ToString();
518
519      //code to handle TimeSpanValues correct
520      int axisDimensionCount = Enum.GetNames(typeof(AxisDimension)).Count();
521      int columnIndex = xAxisComboBox.SelectedIndex - axisDimensionCount;
522      if (xValue.HasValue && columnIndex > 0 && Content.GetValue(0, columnIndex) is TimeSpanValue) {
523        TimeSpan time = TimeSpan.FromSeconds(xValue.Value);
524        xString = string.Format("{0:00}:{1:00}:{2:00.00}", (int)time.TotalHours, time.Minutes, time.Seconds);
525      }
526      columnIndex = yAxisComboBox.SelectedIndex - axisDimensionCount;
527      if (yValue.HasValue && columnIndex > 0 && Content.GetValue(0, columnIndex) is TimeSpanValue) {
528        TimeSpan time = TimeSpan.FromSeconds(yValue.Value);
529        yString = string.Format("{0:00}:{1:00}:{2:00.00}", (int)time.TotalHours, time.Minutes, time.Seconds);
530      }
531
532      tooltip += xAxisComboBox.SelectedItem + " : " + xString + Environment.NewLine;
533      tooltip += yAxisComboBox.SelectedItem + " : " + yString + Environment.NewLine;
534      tooltip += sizeComboBox.SelectedItem + " : " + sizeString + Environment.NewLine;
535
536      return tooltip;
537    }
538    #endregion
539
540    #region GUI events and updating
541    private double GetXJitter(IRun run) {
542      if (!this.xJitter.ContainsKey(run))
543        this.xJitter[run] = random.NextDouble() * 2.0 - 1.0;
544      return this.xJitter[run];
545    }
546    private double GetYJitter(IRun run) {
547      if (!this.yJitter.ContainsKey(run))
548        this.yJitter[run] = random.NextDouble() * 2.0 - 1.0;
549      return this.yJitter[run];
550    }
551    private void jitterTrackBar_ValueChanged(object sender, EventArgs e) {
552      this.xJitterFactor = xTrackBar.Value / 100.0;
553      this.yJitterFactor = yTrackBar.Value / 100.0;
554      UpdateDataPointJitter();
555    }
556    private void sizeTrackBar_ValueChanged(object sender, EventArgs e) {
557      UpdateMarkerSizes();
558    }
559
560    private void AxisComboBox_SelectedValueChanged(object sender, EventArgs e) {
561      bool axisSelected = xAxisComboBox.SelectedIndex != -1 && yAxisComboBox.SelectedIndex != -1;
562      xTrackBar.Enabled = yTrackBar.Enabled = axisSelected;
563      colorXAxisButton.Enabled = colorYAxisButton.Enabled = axisSelected;
564
565      xAxisValue = (string)xAxisComboBox.SelectedItem;
566      yAxisValue = (string)yAxisComboBox.SelectedItem;
567      sizeAxisValue = (string)sizeComboBox.SelectedItem;
568
569      UpdateDataPoints();
570      UpdateAxisLabels();
571    }
572    private void UpdateAxisLabels() {
573      Axis xAxis = this.chart.ChartAreas[0].AxisX;
574      Axis yAxis = this.chart.ChartAreas[0].AxisY;
575      int axisDimensionCount = Enum.GetNames(typeof(AxisDimension)).Count();
576      SetCustomAxisLabels(xAxis, xAxisComboBox.SelectedIndex - axisDimensionCount);
577      SetCustomAxisLabels(yAxis, yAxisComboBox.SelectedIndex - axisDimensionCount);
578      if (xAxisComboBox.SelectedItem != null)
579        xAxis.Title = xAxisComboBox.SelectedItem.ToString();
580      if (yAxisComboBox.SelectedItem != null)
581        yAxis.Title = yAxisComboBox.SelectedItem.ToString();
582    }
583
584    private void chart_AxisViewChanged(object sender, System.Windows.Forms.DataVisualization.Charting.ViewEventArgs e) {
585      this.UpdateAxisLabels();
586    }
587
588    private void SetCustomAxisLabels(Axis axis, int dimension) {
589      axis.CustomLabels.Clear();
590      if (categoricalMapping.ContainsKey(dimension)) {
591        foreach (var pair in categoricalMapping[dimension]) {
592          string labelText = pair.Key.ToString();
593          CustomLabel label = new CustomLabel();
594          label.ToolTip = labelText;
595          if (labelText.Length > 25)
596            labelText = labelText.Substring(0, 25) + " ... ";
597          label.Text = labelText;
598          label.GridTicks = GridTickTypes.TickMark;
599          label.FromPosition = pair.Value - 0.5;
600          label.ToPosition = pair.Value + 0.5;
601          axis.CustomLabels.Add(label);
602        }
603      } else if (dimension > 0 && Content.GetValue(0, dimension) is TimeSpanValue) {
604        this.chart.ChartAreas[0].RecalculateAxesScale();
605        for (double i = axis.Minimum; i <= axis.Maximum; i += axis.LabelStyle.Interval) {
606          TimeSpan time = TimeSpan.FromSeconds(i);
607          string x = string.Format("{0:00}:{1:00}:{2:00}", time.Hours, time.Minutes, time.Seconds);
608          axis.CustomLabels.Add(i - axis.LabelStyle.Interval / 2, i + axis.LabelStyle.Interval / 2, x);
609        }
610      }
611    }
612
613    private void zoomButton_CheckedChanged(object sender, EventArgs e) {
614      this.isSelecting = selectButton.Checked;
615      this.colorButton.Enabled = this.isSelecting;
616      this.chart.ChartAreas[0].AxisX.ScaleView.Zoomable = !isSelecting;
617      this.chart.ChartAreas[0].AxisY.ScaleView.Zoomable = !isSelecting;
618    }
619    private void colorButton_Click(object sender, EventArgs e) {
620      if (colorDialog.ShowDialog(this) == DialogResult.OK) {
621        this.colorButton.Image = this.GenerateImage(16, 16, this.colorDialog.Color);
622      }
623    }
624    private Image GenerateImage(int width, int height, Color fillColor) {
625      Image colorImage = new Bitmap(width, height);
626      using (Graphics gfx = Graphics.FromImage(colorImage)) {
627        using (SolidBrush brush = new SolidBrush(fillColor)) {
628          gfx.FillRectangle(brush, 0, 0, width, height);
629        }
630      }
631      return colorImage;
632    }
633
634    private IRun runToHide = null;
635    private void ContextMenuStrip_Opening(object sender, System.ComponentModel.CancelEventArgs e) {
636      var pos = Control.MousePosition;
637      var chartPos = chart.PointToClient(pos);
638
639      HitTestResult h = this.chart.HitTest(chartPos.X, chartPos.Y);
640      if (h.ChartElementType == ChartElementType.DataPoint) {
641        runToHide = (IRun)((DataPoint)h.Object).Tag;
642        hideRunToolStripMenuItem.Visible = true;
643      } else {
644        runToHide = null;
645        hideRunToolStripMenuItem.Visible = false;
646      }
647
648    }
649    private void hideRunToolStripMenuItem_Click(object sender, EventArgs e) {
650      var constraint = Content.Constraints.OfType<RunCollectionContentConstraint>().Where(c => c.Active).FirstOrDefault();
651      if (constraint == null) {
652        constraint = new RunCollectionContentConstraint();
653        Content.Constraints.Add(constraint);
654        constraint.Active = true;
655      }
656      constraint.ConstraintData.Add(runToHide);
657    }
658
659    private void openBoxPlotViewToolStripMenuItem_Click(object sender, EventArgs e) {
660      RunCollectionBoxPlotView boxplotView = new RunCollectionBoxPlotView();
661      boxplotView.Content = this.Content;
662      boxplotView.xAxisComboBox.SelectedItem = xAxisComboBox.SelectedItem;
663      boxplotView.yAxisComboBox.SelectedItem = yAxisComboBox.SelectedItem;
664      boxplotView.Show();
665    }
666    #endregion
667
668    #region Automatic coloring
669    private void colorXAxisButton_Click(object sender, EventArgs e) {
670      ColorRuns(xAxisValue);
671    }
672
673    private void colorYAxisButton_Click(object sender, EventArgs e) {
674      ColorRuns(yAxisValue);
675    }
676
677    private void ColorRuns(string axisValue) {
678      var runs = Content.Where(r => r.Visible).Select(r => new { Run = r, Value = GetValue(r, axisValue) }).Where(r => r.Value.HasValue);
679      double minValue = runs.Min(r => r.Value.Value);
680      double maxValue = runs.Max(r => r.Value.Value);
681      double range = maxValue - minValue;
682
683      foreach (var r in runs) {
684        int colorIndex = 0;
685        if (!range.IsAlmost(0)) colorIndex = (int)((ColorGradient.Colors.Count - 1) * (r.Value.Value - minValue) / (range));
686        r.Run.Color = ColorGradient.Colors[colorIndex];
687      }
688    }
689    #endregion
690  }
691}
Note: See TracBrowser for help on using the repository browser.