Free cookie consent management tool by TermsFeed Policy Generator

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

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

Fixed #692 (Zooming in bubble chart zooms to incorrect region for large zoom factors).

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 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)) {
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 int CalculateSize(double size, double minSize, double maxSize) {
233      if (double.IsNaN(size) || double.IsInfinity(size) || size == double.MaxValue || size == double.MinValue) return minBubbleSize;
234      if (size > maxSize) size = maxSize;
235      if (size < minSize) size = minSize;
236      if (Math.Abs(maxSize - minSize) < 1.0E-10) return minBubbleSize;
237      double sizeDifference = ((size - minSize) / (maxSize - minSize) * (maxBubbleSize - minBubbleSize));
238      if (invertSize) return maxBubbleSize - (int)sizeDifference;
239      else return minBubbleSize + (int)sizeDifference;
240    }
241
242    private int CalculateAlpha(int size) {
243      return (minAlpha + maxAlpha) / 2;
244    }
245
246    private void ZoomToViewSize() {
247      if (minX < maxX && minY < maxY) {
248        // enlarge view by 5% on each side
249        double width = maxX - minX;
250        double height = maxY - minY;
251        minX = minX - width * 0.05;
252        maxX = maxX + width * 0.05;
253        minY = minY - height * 0.05;
254        maxY = maxY + height * 0.05;
255        ZoomIn(minX, minY, maxX, maxY);
256      }
257    }
258
259    private void UpdateViewSize(double x, double y, double size) {
260      if (x - size < minX) minX = x - size;
261      if (x + size > maxX) maxX = x + size;
262      if (y - size < minY) minY = y + size;
263      if (y + size > maxY) maxY = y + size;
264    }
265
266    private void ResetViewSize() {
267      minX = double.PositiveInfinity;
268      maxX = double.NegativeInfinity;
269      minY = double.PositiveInfinity;
270      maxY = double.NegativeInfinity;
271    }
272
273    internal ResultsEntry GetResultsEntry(Point point) {
274      ResultsEntry r = null;
275      IPrimitive p = points.GetPrimitive(TransformPixelToWorld(point));
276      if (p != null) {
277        primitiveToEntryDictionary.TryGetValue(p, out r);
278      }
279      return r;
280    }
281
282    public override void MouseDrag(Point start, Point end, MouseButtons button) {
283      if (button == MouseButtons.Left && Mode == ChartMode.Select) {
284        PointD a = TransformPixelToWorld(start);
285        PointD b = TransformPixelToWorld(end);
286        double minX = Math.Min(a.X, b.X);
287        double minY = Math.Min(a.Y, b.Y);
288        double maxX = Math.Max(a.X, b.X);
289        double maxY = Math.Max(a.Y, b.Y);
290        HeuristicLab.Charting.Rectangle rect = new HeuristicLab.Charting.Rectangle(this, minX, minY, maxX, maxY);
291
292        List<IPrimitive> primitives = new List<IPrimitive>();
293        primitives.AddRange(points.Primitives);
294
295        foreach (FixedSizeCircle p in primitives) {
296          if (rect.ContainsPoint(p.Point)) {
297            ResultsEntry r;
298            primitiveToEntryDictionary.TryGetValue(p, out r);
299            if (r != null) r.ToggleSelected();
300          }
301        }
302        if (primitives.Count() > 0) results.FireChanged();
303      } else {
304        base.MouseDrag(start, end, button);
305      }
306    }
307
308    public override void MouseClick(Point point, MouseButtons button) {
309      if (button == MouseButtons.Left) {
310        ResultsEntry r = GetResultsEntry(point);
311        if (r != null) {
312          r.ToggleSelected();
313          results.FireChanged();
314        }
315      } else {
316        base.MouseClick(point, button);
317      }
318    }
319
320    public override void MouseDoubleClick(Point point, MouseButtons button) {
321      if (button == MouseButtons.Left) {
322        ResultsEntry entry = GetResultsEntry(point);
323        if (entry != null) {
324          string serializedData = (string)entry.Get(Ontology.SerializedData.Uri.Replace(Ontology.CedmaNameSpace, ""));
325          var model = (IItem)PersistenceManager.RestoreFromGZip(Convert.FromBase64String(serializedData));
326          PluginManager.ControlManager.ShowControl(model.CreateView());
327        }
328      } else {
329        base.MouseDoubleClick(point, button);
330      }
331    }
332
333    internal void ToggleSelected() {
334      foreach (ResultsEntry entry in results.GetEntries()) {
335        entry.ToggleSelected();
336      }
337      results.FireChanged();
338    }
339
340    internal void ClearSelection() {
341      foreach (ResultsEntry entry in results.GetEntries().Where(x=>x.Selected)) {
342        entry.ToggleSelected();
343      }
344      results.FireChanged();
345    }
346
347    internal void ApplyFilter(Func<ResultsEntry, bool> filterPred) {
348      foreach (ResultsEntry r in results.GetEntries()) {
349        if (filterPred(r)) {
350          r.Visible = false;
351          r.Selected = false;
352          filteredEntries.Add(r);
353        }
354      }
355      results.FireChanged();
356    }
357
358    internal void ClearFilter() {
359      foreach (ResultsEntry r in filteredEntries) {
360        r.Visible = true;
361      }
362      filteredEntries.Clear();
363      results.FireChanged();
364    }
365  }
366}
Note: See TracBrowser for help on using the repository browser.