Free cookie consent management tool by TermsFeed Policy Generator

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

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

#1789: Added possibility to set transparency of the bubbles

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