Free cookie consent management tool by TermsFeed Policy Generator

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

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

#1890: Removed not used private class.

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