Free cookie consent management tool by TermsFeed Policy Generator

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

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

Show actual X and Y values in the tooltip. This is important for sub-entry bubble charts where the actual values are hidden in enumerations. #286 (Variable-usage diagrams for the CEDMA frontend)

File size: 14.3 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> records;
59    private Results results;
60    private Dictionary<IPrimitive, ResultsEntry> primitiveToEntryDictionary;
61    //private Dictionary<ResultsEntry, IList<IPrimitive>> entryToPrimitivesDictionary;
62    private Random random = new Random();
63    private Group points;
64
65    public BubbleChart(Results results, PointD lowerLeft, PointD upperRight)
66      : base(lowerLeft, upperRight) {
67      records = new List<ResultsEntry>();
68      primitiveToEntryDictionary = new Dictionary<IPrimitive, ResultsEntry>();
69      //entryToPrimitivesDictionary = new Dictionary<ResultsEntry, IList<IPrimitive>>();
70      this.results = results;
71
72      foreach (var resultsEntry in results.GetEntries()) {
73        if (resultsEntry.Get(X_JITTER) == null)
74          resultsEntry.Set(X_JITTER, random.NextDouble() * 2.0 - 1.0);
75        if (resultsEntry.Get(Y_JITTER) == null)
76          resultsEntry.Set(Y_JITTER, random.NextDouble() * 2.0 - 1.0);
77        records.Add(resultsEntry);
78      }
79
80      results.Changed += new EventHandler(results_Changed);
81    }
82
83    void results_Changed(object sender, EventArgs e) {
84      Repaint();
85      EnforceUpdate();
86    }
87
88    public BubbleChart(Results results, double x1, double y1, double x2, double y2)
89      : this(results, new PointD(x1, y1), new PointD(x2, y2)) {
90    }
91
92    public void SetBubbleSizeDimension(string dimension, bool inverted) {
93      this.sizeDimension = dimension;
94      this.invertSize = inverted;
95      Repaint();
96      EnforceUpdate();
97    }
98
99    public void ShowXvsY(string xDimension, string yDimension) {
100      if (this.xDimension != xDimension || this.yDimension != yDimension) {
101        this.xDimension = xDimension;
102        this.yDimension = yDimension;
103
104        ResetViewSize();
105        Repaint();
106        ZoomToViewSize();
107      }
108    }
109
110    internal void SetJitter(double xJitterFactor, double yJitterFactor) {
111      this.xJitterFactor = xJitterFactor * maxXJitterPercent * Size.Width;
112      this.yJitterFactor = yJitterFactor * maxYJitterPercent * Size.Height;
113      Repaint();
114      EnforceUpdate();
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 = records
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      //entryToPrimitivesDictionary.Clear();
136      points = new Group(this);
137      Group.Add(new Axis(this, 0, 0, AxisType.Both));
138      UpdateViewSize(0, 0, 5);
139      foreach (ResultsEntry r in records) {
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)) {
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)) {
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            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        } else if (results.MultiDimensionalOrdinalVariables.Contains(xDimension)) {
159          var path = xDimension.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim());
160          IEnumerable<ResultsEntry> subEntries = (IEnumerable<ResultsEntry>)r.Get(path.ElementAt(0));
161          foreach (ResultsEntry subEntry in subEntries) {
162            xs.Add(Convert.ToDouble(subEntry.Get(path.ElementAt(1))) + (double)r.Get(X_JITTER) * xJitterFactor);
163            actualXValues.Add(subEntry.Get(path.ElementAt(1)));
164          }
165        } else {
166          xs.Add(double.NaN);
167          actualXValues.Add("NaN");
168        }
169        if (results.OrdinalVariables.Contains(yDimension)) {
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)) {
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            ys.Add(results.IndexOfCategoricalValue(yDimension, subEntry.Get(path.ElementAt(1))) + (double)r.Get(Y_JITTER) * yJitterFactor);
180            actualYValues.Add(subEntry.Get(path.ElementAt(1)));
181          }
182        } else if (results.MultiDimensionalOrdinalVariables.Contains(yDimension)) {
183          var path = yDimension.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim());
184          IEnumerable<ResultsEntry> subEntries = (IEnumerable<ResultsEntry>)r.Get(path.ElementAt(0));
185          foreach (ResultsEntry subEntry in subEntries) {
186            ys.Add(Convert.ToDouble(subEntry.Get(path.ElementAt(1))) + (double)r.Get(Y_JITTER) * yJitterFactor);
187            actualYValues.Add(subEntry.Get(path.ElementAt(1)));
188          }
189        } else {
190          ys.Add(double.NaN);
191          actualYValues.Add("NaN");
192        }
193        size = CalculateSize(Convert.ToDouble(r.Get(sizeDimension)), minSize, maxSize);
194        Debug.Assert(xs.Count() == ys.Count() || xs.Count() == 1 || ys.Count() == 1);
195        int n = Math.Max(xs.Count(), ys.Count());
196        for (int i = 0; i < n; i++) {
197          double x = xs[Math.Min(i, xs.Count() - 1)];
198          double y = ys[Math.Min(i, ys.Count() - 1)];
199          string actualXValue = actualXValues[Math.Min(i, actualXValues.Count() - 1)].ToString();
200          string actualYValue = actualYValues[Math.Min(i, actualYValues.Count() - 1)].ToString();
201          if (double.IsInfinity(x) || x == double.MaxValue || x == double.MinValue) x = double.NaN;
202          if (double.IsInfinity(y) || y == double.MaxValue || y == double.MinValue) y = double.NaN;
203          if (!double.IsNaN(x) && !double.IsNaN(y)) {
204            UpdateViewSize(x, y, size);
205            int alpha = CalculateAlpha(size);
206            Pen pen = new Pen(Color.FromArgb(alpha, r.Selected ? selectionColor : defaultColor));
207            Brush brush = pen.Brush;
208            FixedSizeCircle c = new FixedSizeCircle(this, x, y, size, pen, brush);
209            c.ToolTipText = xDimension + " = " + actualXValue + Environment.NewLine +
210              yDimension + " = " + actualYValue + Environment.NewLine +
211              r.GetToolTipText();
212            points.Add(c);
213            if (!r.Selected) c.IntoBackground();
214            primitiveToEntryDictionary[c] = r;
215            //if (!entryToPrimitivesDictionary.ContainsKey(r)) entryToPrimitivesDictionary[r] = new List<IPrimitive>();
216            //entryToPrimitivesDictionary[r].Add(c);
217          }
218        }
219      }
220      Group.Add(points);
221      UpdateEnabled = true;
222    }
223
224    private int CalculateSize(double size, double minSize, double maxSize) {
225      if (double.IsNaN(size) || double.IsInfinity(size) || size == double.MaxValue || size == double.MinValue) return minBubbleSize;
226      if (size > maxSize) size = maxSize;
227      if (size < minSize) size = minSize;
228      if (Math.Abs(maxSize - minSize) < 1.0E-10) return minBubbleSize;
229      double sizeDifference = ((size - minSize) / (maxSize - minSize) * (maxBubbleSize - minBubbleSize));
230      if (invertSize) return maxBubbleSize - (int)sizeDifference;
231      else return minBubbleSize + (int)sizeDifference;
232    }
233
234    private int CalculateAlpha(int size) {
235      return maxAlpha - (int)((double)(size - minBubbleSize) / (double)(maxBubbleSize - minBubbleSize) * (double)(maxAlpha - minAlpha));
236    }
237
238    private void ZoomToViewSize() {
239      if (minX < maxX && minY < maxY) {
240        // enlarge view by 5% on each side
241        double width = maxX - minX;
242        double height = maxY - minY;
243        minX = minX - width * 0.05;
244        maxX = maxX + width * 0.05;
245        minY = minY - height * 0.05;
246        maxY = maxY + height * 0.05;
247        ZoomIn(minX, minY, maxX, maxY);
248      }
249    }
250
251    private void UpdateViewSize(double x, double y, double size) {
252      if (x - size < minX) minX = x - size;
253      if (x + size > maxX) maxX = x + size;
254      if (y - size < minY) minY = y + size;
255      if (y + size > maxY) maxY = y + size;
256    }
257
258    private void ResetViewSize() {
259      minX = double.PositiveInfinity;
260      maxX = double.NegativeInfinity;
261      minY = double.PositiveInfinity;
262      maxY = double.NegativeInfinity;
263    }
264
265    internal ResultsEntry GetResultsEntry(Point point) {
266      ResultsEntry r = null;
267      IPrimitive p = points.GetPrimitive(TransformPixelToWorld(point));
268      if (p != null) {
269        primitiveToEntryDictionary.TryGetValue(p, out r);
270      }
271      return r;
272    }
273
274    public override void MouseDrag(Point start, Point end, MouseButtons button) {
275      if (button == MouseButtons.Left && Mode == ChartMode.Select) {
276        PointD a = TransformPixelToWorld(start);
277        PointD b = TransformPixelToWorld(end);
278        double minX = Math.Min(a.X, b.X);
279        double minY = Math.Min(a.Y, b.Y);
280        double maxX = Math.Max(a.X, b.X);
281        double maxY = Math.Max(a.Y, b.Y);
282        HeuristicLab.Charting.Rectangle rect = new HeuristicLab.Charting.Rectangle(this, minX, minY, maxX, maxY);
283
284        List<IPrimitive> primitives = new List<IPrimitive>();
285        primitives.AddRange(points.Primitives);
286
287        foreach (FixedSizeCircle p in primitives) {
288          if (rect.ContainsPoint(p.Point)) {
289            ResultsEntry r;
290            primitiveToEntryDictionary.TryGetValue(p, out r);
291            if (r != null) r.ToggleSelected();
292          }
293        }
294        if (primitives.Count() > 0) results.FireChanged();
295      } else {
296        base.MouseDrag(start, end, button);
297      }
298    }
299
300    public override void MouseClick(Point point, MouseButtons button) {
301      if (button == MouseButtons.Left) {
302        ResultsEntry r = GetResultsEntry(point);
303        if (r != null) {
304          r.ToggleSelected();
305          results.FireChanged();
306        }
307      } else {
308        base.MouseClick(point, button);
309      }
310    }
311
312    public override void MouseDoubleClick(Point point, MouseButtons button) {
313      if (button == MouseButtons.Left) {
314        ResultsEntry entry = GetResultsEntry(point);
315        if (entry != null) {
316          string serializedData = (string)entry.Get(Ontology.SerializedData.Uri.Replace(Ontology.CedmaNameSpace, ""));
317          var model = (IItem)PersistenceManager.RestoreFromGZip(Convert.FromBase64String(serializedData));
318          PluginManager.ControlManager.ShowControl(model.CreateView());
319        }
320      } else {
321        base.MouseDoubleClick(point, button);
322      }
323    }
324  }
325}
Note: See TracBrowser for help on using the repository browser.