Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 4883 was 4883, checked in by mkommend, 13 years ago

Improved performance of all RunCollectionViews (ticket #1284).

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