Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.CEDMA.Charting/3.3/BubbleChart.cs @ 2240

Last change on this file since 2240 was 2240, checked in by gkronber, 15 years ago

Removed obsolete CEDMA plugins. #712

File size: 15.5 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2008 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.Text;
25using System.Drawing;
26using System.Linq;
27using HeuristicLab.Charting;
28using System.Windows.Forms;
29using HeuristicLab.CEDMA.Core;
30using HeuristicLab.PluginInfrastructure;
31using HeuristicLab.Core;
32using System.Diagnostics;
33
34namespace HeuristicLab.CEDMA.Charting {
35  public class BubbleChart : Chart {
36    private const string X_JITTER = "__X_JITTER";
37    private const string Y_JITTER = "__Y_JITTER";
38    private const double maxXJitterPercent = 0.05;
39    private const double maxYJitterPercent = 0.05;
40    private const int minBubbleSize = 5;
41    private const int maxBubbleSize = 30;
42    private const int maxAlpha = 255;
43    private const int minAlpha = 50;
44    private static readonly Color defaultColor = Color.Blue;
45    private static readonly Color selectionColor = Color.Red;
46
47    private double xJitterFactor = 0.0;
48    private double yJitterFactor = 0.0;
49    private string xDimension;
50    private string yDimension;
51    private string sizeDimension;
52    private bool invertSize;
53    private double minX = double.PositiveInfinity;
54    private double minY = double.PositiveInfinity;
55    private double maxX = double.NegativeInfinity;
56    private double maxY = double.NegativeInfinity;
57    private List<ResultsEntry> filteredEntries;
58    private Results results;
59    private Dictionary<IPrimitive, ResultsEntry> primitiveToEntryDictionary;
60    private Random random = new Random();
61    private Group points;
62
63    public BubbleChart(Results results, PointD lowerLeft, PointD upperRight)
64      : base(lowerLeft, upperRight) {
65      primitiveToEntryDictionary = new Dictionary<IPrimitive, ResultsEntry>();
66      this.results = results;
67      filteredEntries = new List<ResultsEntry>();
68
69      foreach (var resultsEntry in results.GetEntries()) {
70        if (resultsEntry.Get(X_JITTER) == null)
71          resultsEntry.Set(X_JITTER, random.NextDouble() * 2.0 - 1.0);
72        if (resultsEntry.Get(Y_JITTER) == null)
73          resultsEntry.Set(Y_JITTER, random.NextDouble() * 2.0 - 1.0);
74      }
75      results.Changed += new EventHandler(results_Changed);
76    }
77
78    void results_Changed(object sender, EventArgs e) {
79      Repaint();
80      EnforceUpdate();
81    }
82
83    public BubbleChart(Results results, double x1, double y1, double x2, double y2)
84      : this(results, new PointD(x1, y1), new PointD(x2, y2)) {
85    }
86
87    public void SetBubbleSizeDimension(string dimension, bool inverted) {
88      this.sizeDimension = dimension;
89      this.invertSize = inverted;
90      Repaint();
91      EnforceUpdate();
92    }
93
94    public void ShowXvsY(string xDimension, string yDimension) {
95      if (this.xDimension != xDimension || this.yDimension != yDimension) {
96        this.xDimension = xDimension;
97        this.yDimension = yDimension;
98
99        ResetViewSize();
100        Repaint();
101        ZoomToViewSize();
102      }
103    }
104
105    internal void SetJitter(double xJitterFactor, double yJitterFactor) {
106      this.xJitterFactor = xJitterFactor * maxXJitterPercent * Size.Width;
107      this.yJitterFactor = yJitterFactor * maxYJitterPercent * Size.Height;
108      Repaint();
109      EnforceUpdate();
110    }
111
112    public override void Render(Graphics graphics, int width, int height) {
113      graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
114      base.Render(graphics, width, height);
115    }
116
117    private void Repaint() {
118      if (xDimension == null || yDimension == null) return;
119      double maxSize = 1;
120      double minSize = 1;
121      if (sizeDimension != null && results.OrdinalVariables.Contains(sizeDimension)) {
122        var sizes = results.GetEntries()
123          .Select(x => Convert.ToDouble(x.Get(sizeDimension)))
124          .Where(size => !double.IsInfinity(size) && size != double.MaxValue && size != double.MinValue)
125          .OrderBy(r => r);
126        minSize = sizes.ElementAt((int)(sizes.Count() * 0.1));
127        maxSize = sizes.ElementAt((int)(sizes.Count() * 0.9));
128      } else {
129        minSize = 1;
130        maxSize = 1;
131      }
132      UpdateEnabled = false;
133      Group.Clear();
134      primitiveToEntryDictionary.Clear();
135      points = new Group(this);
136      Group.Add(new Axis(this, 0, 0, AxisType.Both));
137      UpdateViewSize(0, 0, TransformPixelToWorld(new Size(5, 0)).Width);
138      foreach (ResultsEntry r in results.GetEntries().Where(x => x.Visible)) {
139        List<double> xs = new List<double>();
140        List<double> ys = new List<double>();
141        List<object> actualXValues = new List<object>();
142        List<object> actualYValues = new List<object>();
143        int size;
144        if (results.OrdinalVariables.Contains(xDimension) && r.Get(xDimension) != null) {
145          xs.Add(Convert.ToDouble(r.Get(xDimension)) + (double)r.Get(X_JITTER) * xJitterFactor);
146          actualXValues.Add(r.Get(xDimension));
147        } else if (results.CategoricalVariables.Contains(xDimension) && r.Get(xDimension) != null) {
148          xs.Add(results.IndexOfCategoricalValue(xDimension, r.Get(xDimension)) + (double)r.Get(X_JITTER) * xJitterFactor);
149          actualXValues.Add(r.Get(xDimension));
150        } else if (results.MultiDimensionalCategoricalVariables.Contains(xDimension)) {
151          var path = xDimension.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim());
152          IEnumerable<ResultsEntry> subEntries = (IEnumerable<ResultsEntry>)r.Get(path.ElementAt(0));
153          foreach (ResultsEntry subEntry in subEntries) {
154            if (subEntry.Get(path.ElementAt(1)) != null) {
155              xs.Add(results.IndexOfCategoricalValue(xDimension, subEntry.Get(path.ElementAt(1))) + (double)r.Get(X_JITTER) * xJitterFactor);
156              actualXValues.Add(subEntry.Get(path.ElementAt(1)));
157            }
158          }
159        } else if (results.MultiDimensionalOrdinalVariables.Contains(xDimension)) {
160          var path = xDimension.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim());
161          IEnumerable<ResultsEntry> subEntries = (IEnumerable<ResultsEntry>)r.Get(path.ElementAt(0));
162          foreach (ResultsEntry subEntry in subEntries) {
163            if (subEntry.Get(path.ElementAt(1)) != null) {
164              xs.Add(Convert.ToDouble(subEntry.Get(path.ElementAt(1))) + (double)r.Get(X_JITTER) * xJitterFactor);
165              actualXValues.Add(subEntry.Get(path.ElementAt(1)));
166            }
167          }
168        }
169        if (results.OrdinalVariables.Contains(yDimension) && r.Get(yDimension) != null) {
170          ys.Add(Convert.ToDouble(r.Get(yDimension)) + (double)r.Get(Y_JITTER) * yJitterFactor);
171          actualYValues.Add(r.Get(yDimension));
172        } else if (results.CategoricalVariables.Contains(yDimension) && r.Get(yDimension) != null) {
173          ys.Add(results.IndexOfCategoricalValue(yDimension, r.Get(yDimension)) + (double)r.Get(Y_JITTER) * yJitterFactor);
174          actualYValues.Add(r.Get(yDimension));
175        } else if (results.MultiDimensionalCategoricalVariables.Contains(yDimension)) {
176          var path = yDimension.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim());
177          IEnumerable<ResultsEntry> subEntries = (IEnumerable<ResultsEntry>)r.Get(path.ElementAt(0));
178          foreach (ResultsEntry subEntry in subEntries) {
179            if (subEntry.Get(path.ElementAt(1)) != null) {
180              ys.Add(results.IndexOfCategoricalValue(yDimension, subEntry.Get(path.ElementAt(1))) + (double)r.Get(Y_JITTER) * yJitterFactor);
181              actualYValues.Add(subEntry.Get(path.ElementAt(1)));
182            }
183          }
184        } else if (results.MultiDimensionalOrdinalVariables.Contains(yDimension)) {
185          var path = yDimension.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim());
186          IEnumerable<ResultsEntry> subEntries = (IEnumerable<ResultsEntry>)r.Get(path.ElementAt(0));
187          foreach (ResultsEntry subEntry in subEntries) {
188            if (subEntry.Get(path.ElementAt(1)) != null) {
189              ys.Add(Convert.ToDouble(subEntry.Get(path.ElementAt(1))) + (double)r.Get(Y_JITTER) * yJitterFactor);
190              actualYValues.Add(subEntry.Get(path.ElementAt(1)));
191            }
192          }
193        }
194        if (xs.Count() == 0) {
195          xs.Add(double.NaN);
196          actualXValues.Add("NaN");
197        }
198        if (ys.Count() == 0) {
199          ys.Add(double.NaN);
200          actualYValues.Add("NaN");
201        }
202        size = CalculateSize(Convert.ToDouble(r.Get(sizeDimension)), minSize, maxSize);
203        Debug.Assert(xs.Count() == ys.Count() || xs.Count() == 1 || ys.Count() == 1);
204        int n = Math.Max(xs.Count(), ys.Count());
205        for (int i = 0; i < n; i++) {
206          double x = xs[Math.Min(i, xs.Count() - 1)];
207          double y = ys[Math.Min(i, ys.Count() - 1)];
208          if (double.IsInfinity(x) || x == double.MaxValue || x == double.MinValue) x = double.NaN;
209          if (double.IsInfinity(y) || y == double.MaxValue || y == double.MinValue) y = double.NaN;
210          if (!double.IsNaN(x) && !double.IsNaN(y) && IsReasonablePoint(new PointD(x,y))) {
211            string actualXValue = actualXValues[Math.Min(i, actualXValues.Count() - 1)].ToString();
212            string actualYValue = actualYValues[Math.Min(i, actualYValues.Count() - 1)].ToString();
213            UpdateViewSize(x, y, TransformPixelToWorld(new Size(size, 0)).Width);
214            int alpha = CalculateAlpha(size);
215            Pen pen = new Pen(Color.FromArgb(alpha, r.Selected ? selectionColor : defaultColor));
216            Brush brush = pen.Brush;
217            FixedSizeCircle c = new FixedSizeCircle(this, x, y, size, pen, brush);
218            c.ToolTipText = xDimension + " = " + actualXValue + Environment.NewLine +
219              yDimension + " = " + actualYValue + Environment.NewLine +
220              r.GetToolTipText();
221            points.Add(c);
222            if (!r.Selected) c.IntoBackground();
223            primitiveToEntryDictionary[c] = r;
224          }
225        }
226      }
227      Group.Add(points);
228      UpdateEnabled = true;
229    }
230
231    private bool IsReasonablePoint(PointD pointD) {
232      return pointD.X > LowerLeft.X && pointD.X < UpperRight.X && pointD.Y > LowerLeft.Y && pointD.Y < UpperRight.Y;
233    }
234
235    private int CalculateSize(double size, double minSize, double maxSize) {
236      if (double.IsNaN(size) || double.IsInfinity(size) || size == double.MaxValue || size == double.MinValue) return minBubbleSize;
237      if (size > maxSize) size = maxSize;
238      if (size < minSize) size = minSize;
239      if (Math.Abs(maxSize - minSize) < 1.0E-10) return minBubbleSize;
240      double sizeDifference = ((size - minSize) / (maxSize - minSize) * (maxBubbleSize - minBubbleSize));
241      if (invertSize) return maxBubbleSize - (int)sizeDifference;
242      else return minBubbleSize + (int)sizeDifference;
243    }
244
245    private int CalculateAlpha(int size) {
246      return (minAlpha + maxAlpha) / 2;
247    }
248
249    private void ZoomToViewSize() {
250      if (minX < maxX && minY < maxY) {
251        // enlarge view by 5% on each side
252        double width = maxX - minX;
253        double height = maxY - minY;
254        minX = minX - width * 0.05;
255        maxX = maxX + width * 0.05;
256        minY = minY - height * 0.05;
257        maxY = maxY + height * 0.05;
258        ZoomIn(minX, minY, maxX, maxY);
259      }
260    }
261
262    private void UpdateViewSize(double x, double y, double size) {
263      if (x - size < minX) minX = x - size;
264      if (x + size > maxX) maxX = x + size;
265      if (y - size < minY) minY = y + size;
266      if (y + size > maxY) maxY = y + size;
267    }
268
269    private void ResetViewSize() {
270      minX = double.PositiveInfinity;
271      maxX = double.NegativeInfinity;
272      minY = double.PositiveInfinity;
273      maxY = double.NegativeInfinity;
274    }
275
276    internal ResultsEntry GetResultsEntry(Point point) {
277      ResultsEntry r = null;
278      IPrimitive p = points.GetPrimitive(TransformPixelToWorld(point));
279      if (p != null) {
280        primitiveToEntryDictionary.TryGetValue(p, out r);
281      }
282      return r;
283    }
284
285    public override void MouseDrag(Point start, Point end, MouseButtons button) {
286      if (button == MouseButtons.Left && Mode == ChartMode.Select) {
287        PointD a = TransformPixelToWorld(start);
288        PointD b = TransformPixelToWorld(end);
289        double minX = Math.Min(a.X, b.X);
290        double minY = Math.Min(a.Y, b.Y);
291        double maxX = Math.Max(a.X, b.X);
292        double maxY = Math.Max(a.Y, b.Y);
293        HeuristicLab.Charting.Rectangle rect = new HeuristicLab.Charting.Rectangle(this, minX, minY, maxX, maxY);
294
295        List<IPrimitive> primitives = new List<IPrimitive>();
296        primitives.AddRange(points.Primitives);
297
298        foreach (FixedSizeCircle p in primitives) {
299          if (rect.ContainsPoint(p.Point)) {
300            ResultsEntry r;
301            primitiveToEntryDictionary.TryGetValue(p, out r);
302            if (r != null) r.ToggleSelected();
303          }
304        }
305        if (primitives.Count() > 0) results.FireChanged();
306      } else {
307        base.MouseDrag(start, end, button);
308      }
309    }
310
311    public override void MouseClick(Point point, MouseButtons button) {
312      if (button == MouseButtons.Left) {
313        ResultsEntry r = GetResultsEntry(point);
314        if (r != null) {
315          r.ToggleSelected();
316          results.FireChanged();
317        }
318      } else {
319        base.MouseClick(point, button);
320      }
321    }
322
323    public override void MouseDoubleClick(Point point, MouseButtons button) {
324      if (button == MouseButtons.Left) {
325        ResultsEntry entry = GetResultsEntry(point);
326        if (entry != null) {
327          var model = (IItem)PersistenceManager.RestoreFromGZip((byte[])entry.Get("PersistedData"));
328          PluginManager.ControlManager.ShowControl(model.CreateView());
329        }
330      } else {
331        base.MouseDoubleClick(point, button);
332      }
333    }
334
335    internal void ToggleSelected() {
336      foreach (ResultsEntry entry in results.GetEntries()) {
337        entry.ToggleSelected();
338      }
339      results.FireChanged();
340    }
341
342    internal void ClearSelection() {
343      foreach (ResultsEntry entry in results.GetEntries().Where(x=>x.Selected)) {
344        entry.ToggleSelected();
345      }
346      results.FireChanged();
347    }
348
349    internal void ApplyFilter(Func<ResultsEntry, bool> filterPred) {
350      foreach (ResultsEntry r in results.GetEntries()) {
351        if (filterPred(r)) {
352          r.Visible = false;
353          r.Selected = false;
354          filteredEntries.Add(r);
355        }
356      }
357      results.FireChanged();
358    }
359
360    internal void ClearFilter() {
361      foreach (ResultsEntry r in filteredEntries) {
362        r.Visible = true;
363      }
364      filteredEntries.Clear();
365      results.FireChanged();
366    }
367  }
368}
Note: See TracBrowser for help on using the repository browser.