Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 9190 was 9190, checked in by abeham, 11 years ago

#2008: Added option to obtain a matrix representation of a bubble chart view

File size: 31.1 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 HeuristicLab.Common;
23using HeuristicLab.Core;
24using HeuristicLab.Data;
25using HeuristicLab.MainForm;
26using HeuristicLab.MainForm.WindowsForms;
27using System;
28using System.Collections.Generic;
29using System.Drawing;
30using System.Linq;
31using System.Windows.Forms;
32using System.Windows.Forms.DataVisualization.Charting;
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      double[] sizeValues = this.chart.Series[0].Points.Select(p => p.YValues[1]).ToArray();
275      double minSizeValue = sizeValues.Min();
276      double maxSizeValue = sizeValues.Max();
277
278      for (int i = 0; i < sizeValues.Length; i++) {
279        DataPoint point = this.chart.Series[0].Points[i];
280        double sizeRange = maxSizeValue - minSizeValue;
281        double relativeSize = (point.YValues[1] - minSizeValue);
282
283        if (sizeRange > double.Epsilon) relativeSize /= sizeRange;
284        else relativeSize = 1;
285
286        point.MarkerSize = (int)Math.Round((sizeTrackBar.Value - sizeTrackBar.Minimum) * relativeSize + sizeTrackBar.Minimum);
287      }
288    }
289
290    private void UpdateDataPointJitter() {
291      var xAxis = this.chart.ChartAreas[0].AxisX;
292      var yAxis = this.chart.ChartAreas[0].AxisY;
293
294      SetAutomaticUpdateOfAxis(xAxis, false);
295      SetAutomaticUpdateOfAxis(yAxis, false);
296
297      double xAxisRange = xAxis.Maximum - xAxis.Minimum;
298      double yAxisRange = yAxis.Maximum - yAxis.Minimum;
299
300      foreach (DataPoint point in chart.Series[0].Points) {
301        IRun run = (IRun)point.Tag;
302        double xValue = GetValue(run, xAxisValue).Value;
303        double yValue = GetValue(run, yAxisValue).Value;
304
305        if (!xJitterFactor.IsAlmost(0.0))
306          xValue += 0.1 * GetXJitter(run) * xJitterFactor * (xAxisRange);
307        if (!yJitterFactor.IsAlmost(0.0))
308          yValue += 0.1 * GetYJitter(run) * yJitterFactor * (yAxisRange);
309
310        point.XValue = xValue;
311        point.YValues[0] = yValue;
312      }
313
314    }
315
316    // sets an axis to automatic or restrains it to its current values
317    // this is used that none of the set values is changed when jitter is applied, so that the chart stays the same
318    private void SetAutomaticUpdateOfAxis(Axis axis, bool enabled) {
319      if (enabled) {
320        axis.Maximum = double.NaN;
321        axis.Minimum = double.NaN;
322        axis.MajorGrid.Interval = double.NaN;
323        axis.MajorTickMark.Interval = double.NaN;
324        axis.LabelStyle.Interval = double.NaN;
325      } else {
326        axis.Minimum = axis.Minimum;
327        axis.Maximum = axis.Maximum;
328        axis.MajorGrid.Interval = axis.MajorGrid.Interval;
329        axis.MajorTickMark.Interval = axis.MajorTickMark.Interval;
330        axis.LabelStyle.Interval = axis.LabelStyle.Interval;
331      }
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
692    private void getDataAsMatrixToolStripMenuItem_Click(object sender, EventArgs e) {
693      int xCol = Matrix.ColumnNames.ToList().IndexOf(xAxisValue);
694      var grouped = new Dictionary<string, List<string>>();
695      Dictionary<double, string> reverseMapping = null;
696      if (categoricalMapping.ContainsKey(xCol))
697        reverseMapping = categoricalMapping[xCol].ToDictionary(x => x.Value, y => y.Key.ToString());
698      foreach (var run in Content.Where(r => r.Visible)) {
699        var x = GetValue(run, xAxisValue);
700        var y = GetValue(run, yAxisValue);
701        if (!(x.HasValue && y.HasValue)) continue;
702
703        var category = reverseMapping == null ? x.Value.ToString() : reverseMapping[x.Value];
704        if (!grouped.ContainsKey(category)) grouped[category] = new List<string>();
705        grouped[category].Add(y.Value.ToString());
706      }
707
708      if (!grouped.Any()) return;
709      var matrix = new StringMatrix(grouped.Values.Max(x => x.Count), grouped.Count) {
710        ColumnNames = grouped.Keys.ToArray()
711      };
712      int i = 0;
713      foreach (var col in matrix.ColumnNames) {
714        int j = 0;
715        foreach (var y in grouped[col])
716          matrix[j++, i] = y;
717        i++;
718      }
719
720      MainFormManager.MainForm.ShowContent(matrix);
721    }
722    #endregion
723
724    #region Automatic coloring
725    private void colorXAxisButton_Click(object sender, EventArgs e) {
726      ColorRuns(xAxisValue);
727    }
728
729    private void colorYAxisButton_Click(object sender, EventArgs e) {
730      ColorRuns(yAxisValue);
731    }
732
733    private void ColorRuns(string axisValue) {
734      var runs = Content.Where(r => r.Visible).Select(r => new { Run = r, Value = GetValue(r, axisValue) }).Where(r => r.Value.HasValue);
735      double minValue = runs.Min(r => r.Value.Value);
736      double maxValue = runs.Max(r => r.Value.Value);
737      double range = maxValue - minValue;
738
739      foreach (var r in runs) {
740        int colorIndex = 0;
741        if (!range.IsAlmost(0)) colorIndex = (int)((ColorGradient.Colors.Count - 1) * (r.Value.Value - minValue) / (range));
742        r.Run.Color = ColorGradient.Colors[colorIndex];
743      }
744    }
745    #endregion
746  }
747}
Note: See TracBrowser for help on using the repository browser.