Free cookie consent management tool by TermsFeed Policy Generator

source: branches/CEDMA-Exporter-715/sources/HeuristicLab.CEDMA.Charting/3.3/BubbleChart.cs @ 3599

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

Fixed #703 (Overflow error in CEDMA Bubble Chart)

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