Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 9229 was 9229, checked in by mkommend, 11 years ago

#1789: Implemented inverting of the bubble size in the RunCollectionBubbleChartView.

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