Free cookie consent management tool by TermsFeed Policy Generator

source: branches/OaaS/HeuristicLab.Optimization.Views/3.3/RunCollectionViews/RunCollectionBubbleChartView.cs @ 13451

Last change on this file since 13451 was 9363, checked in by spimming, 12 years ago

#1888:

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