Free cookie consent management tool by TermsFeed Policy Generator

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

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

Implemented filtering of result entries in bubble chart and table view. #691 (CEDMA result views should allow filtering of displayed results)

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      //      records = new List<ResultsEntry>();
67      primitiveToEntryDictionary = new Dictionary<IPrimitive, ResultsEntry>();
68      this.results = results;
69      filteredEntries = new List<ResultsEntry>();
70
71      foreach (var resultsEntry in results.GetEntries()) {
72        if (resultsEntry.Get(X_JITTER) == null)
73          resultsEntry.Set(X_JITTER, random.NextDouble() * 2.0 - 1.0);
74        if (resultsEntry.Get(Y_JITTER) == null)
75          resultsEntry.Set(Y_JITTER, random.NextDouble() * 2.0 - 1.0);
76        //        records.Add(resultsEntry);
77      }
78
79      results.Changed += new EventHandler(results_Changed);
80    }
81
82    void results_Changed(object sender, EventArgs e) {
83      Repaint();
84      EnforceUpdate();
85    }
86
87    public BubbleChart(Results results, double x1, double y1, double x2, double y2)
88      : this(results, new PointD(x1, y1), new PointD(x2, y2)) {
89    }
90
91    public void SetBubbleSizeDimension(string dimension, bool inverted) {
92      this.sizeDimension = dimension;
93      this.invertSize = inverted;
94      Repaint();
95      EnforceUpdate();
96    }
97
98    public void ShowXvsY(string xDimension, string yDimension) {
99      if (this.xDimension != xDimension || this.yDimension != yDimension) {
100        this.xDimension = xDimension;
101        this.yDimension = yDimension;
102
103        ResetViewSize();
104        Repaint();
105        ZoomToViewSize();
106      }
107    }
108
109    internal void SetJitter(double xJitterFactor, double yJitterFactor) {
110      this.xJitterFactor = xJitterFactor * maxXJitterPercent * Size.Width;
111      this.yJitterFactor = yJitterFactor * maxYJitterPercent * Size.Height;
112      Repaint();
113      EnforceUpdate();
114    }
115
116    public override void Render(Graphics graphics, int width, int height) {
117      graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
118      base.Render(graphics, width, height);
119    }
120
121    private void Repaint() {
122      if (xDimension == null || yDimension == null) return;
123      double maxSize = 1;
124      double minSize = 1;
125      if (sizeDimension != null && results.OrdinalVariables.Contains(sizeDimension)) {
126        var sizes = results.GetEntries()
127          .Select(x => Convert.ToDouble(x.Get(sizeDimension)))
128          .Where(size => !double.IsInfinity(size) && size != double.MaxValue && size != double.MinValue)
129          .OrderBy(r => r);
130        minSize = sizes.ElementAt((int)(sizes.Count() * 0.1));
131        maxSize = sizes.ElementAt((int)(sizes.Count() * 0.9));
132      } else {
133        minSize = 1;
134        maxSize = 1;
135      }
136      UpdateEnabled = false;
137      Group.Clear();
138      primitiveToEntryDictionary.Clear();
139      points = new Group(this);
140      Group.Add(new Axis(this, 0, 0, AxisType.Both));
141      UpdateViewSize(0, 0, 5);
142      foreach (ResultsEntry r in results.GetEntries().Where(x => x.Visible)) {
143        List<double> xs = new List<double>();
144        List<double> ys = new List<double>();
145        List<object> actualXValues = new List<object>();
146        List<object> actualYValues = new List<object>();
147        int size;
148        if (results.OrdinalVariables.Contains(xDimension) && r.Get(xDimension) != null) {
149          xs.Add(Convert.ToDouble(r.Get(xDimension)) + (double)r.Get(X_JITTER) * xJitterFactor);
150          actualXValues.Add(r.Get(xDimension));
151        } else if (results.CategoricalVariables.Contains(xDimension) && r.Get(xDimension) != null) {
152          xs.Add(results.IndexOfCategoricalValue(xDimension, r.Get(xDimension)) + (double)r.Get(X_JITTER) * xJitterFactor);
153          actualXValues.Add(r.Get(xDimension));
154        } else if (results.MultiDimensionalCategoricalVariables.Contains(xDimension)) {
155          var path = xDimension.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim());
156          IEnumerable<ResultsEntry> subEntries = (IEnumerable<ResultsEntry>)r.Get(path.ElementAt(0));
157          foreach (ResultsEntry subEntry in subEntries) {
158            if (subEntry.Get(path.ElementAt(1)) != null) {
159              xs.Add(results.IndexOfCategoricalValue(xDimension, subEntry.Get(path.ElementAt(1))) + (double)r.Get(X_JITTER) * xJitterFactor);
160              actualXValues.Add(subEntry.Get(path.ElementAt(1)));
161            }
162          }
163        } else if (results.MultiDimensionalOrdinalVariables.Contains(xDimension)) {
164          var path = xDimension.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim());
165          IEnumerable<ResultsEntry> subEntries = (IEnumerable<ResultsEntry>)r.Get(path.ElementAt(0));
166          foreach (ResultsEntry subEntry in subEntries) {
167            if (subEntry.Get(path.ElementAt(1)) != null) {
168              xs.Add(Convert.ToDouble(subEntry.Get(path.ElementAt(1))) + (double)r.Get(X_JITTER) * xJitterFactor);
169              actualXValues.Add(subEntry.Get(path.ElementAt(1)));
170            }
171          }
172        }
173        if (results.OrdinalVariables.Contains(yDimension) && r.Get(yDimension) != null) {
174          ys.Add(Convert.ToDouble(r.Get(yDimension)) + (double)r.Get(Y_JITTER) * yJitterFactor);
175          actualYValues.Add(r.Get(yDimension));
176        } else if (results.CategoricalVariables.Contains(yDimension) && r.Get(yDimension) != null) {
177          ys.Add(results.IndexOfCategoricalValue(yDimension, r.Get(yDimension)) + (double)r.Get(Y_JITTER) * yJitterFactor);
178          actualYValues.Add(r.Get(yDimension));
179        } else if (results.MultiDimensionalCategoricalVariables.Contains(yDimension)) {
180          var path = yDimension.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim());
181          IEnumerable<ResultsEntry> subEntries = (IEnumerable<ResultsEntry>)r.Get(path.ElementAt(0));
182          foreach (ResultsEntry subEntry in subEntries) {
183            if (subEntry.Get(path.ElementAt(1)) != null) {
184              ys.Add(results.IndexOfCategoricalValue(yDimension, subEntry.Get(path.ElementAt(1))) + (double)r.Get(Y_JITTER) * yJitterFactor);
185              actualYValues.Add(subEntry.Get(path.ElementAt(1)));
186            }
187          }
188        } else if (results.MultiDimensionalOrdinalVariables.Contains(yDimension)) {
189          var path = yDimension.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim());
190          IEnumerable<ResultsEntry> subEntries = (IEnumerable<ResultsEntry>)r.Get(path.ElementAt(0));
191          foreach (ResultsEntry subEntry in subEntries) {
192            if (subEntry.Get(path.ElementAt(1)) != null) {
193              ys.Add(Convert.ToDouble(subEntry.Get(path.ElementAt(1))) + (double)r.Get(Y_JITTER) * yJitterFactor);
194              actualYValues.Add(subEntry.Get(path.ElementAt(1)));
195            }
196          }
197        }
198        if (xs.Count() == 0) {
199          xs.Add(double.NaN);
200          actualXValues.Add("NaN");
201        }
202        if (ys.Count() == 0) {
203          ys.Add(double.NaN);
204          actualYValues.Add("NaN");
205        }
206        size = CalculateSize(Convert.ToDouble(r.Get(sizeDimension)), minSize, maxSize);
207        Debug.Assert(xs.Count() == ys.Count() || xs.Count() == 1 || ys.Count() == 1);
208        int n = Math.Max(xs.Count(), ys.Count());
209        for (int i = 0; i < n; i++) {
210          double x = xs[Math.Min(i, xs.Count() - 1)];
211          double y = ys[Math.Min(i, ys.Count() - 1)];
212          if (double.IsInfinity(x) || x == double.MaxValue || x == double.MinValue) x = double.NaN;
213          if (double.IsInfinity(y) || y == double.MaxValue || y == double.MinValue) y = double.NaN;
214          if (!double.IsNaN(x) && !double.IsNaN(y)) {
215            string actualXValue = actualXValues[Math.Min(i, actualXValues.Count() - 1)].ToString();
216            string actualYValue = actualYValues[Math.Min(i, actualYValues.Count() - 1)].ToString();
217            UpdateViewSize(x, y, size);
218            int alpha = CalculateAlpha(size);
219            Pen pen = new Pen(Color.FromArgb(alpha, r.Selected ? selectionColor : defaultColor));
220            Brush brush = pen.Brush;
221            FixedSizeCircle c = new FixedSizeCircle(this, x, y, size, pen, brush);
222            c.ToolTipText = xDimension + " = " + actualXValue + Environment.NewLine +
223              yDimension + " = " + actualYValue + Environment.NewLine +
224              r.GetToolTipText();
225            points.Add(c);
226            if (!r.Selected) c.IntoBackground();
227            primitiveToEntryDictionary[c] = r;
228          }
229        }
230      }
231      Group.Add(points);
232      UpdateEnabled = true;
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          string serializedData = (string)entry.Get(Ontology.SerializedData.Uri.Replace(Ontology.CedmaNameSpace, ""));
328          var model = (IItem)PersistenceManager.RestoreFromGZip(Convert.FromBase64String(serializedData));
329          PluginManager.ControlManager.ShowControl(model.CreateView());
330        }
331      } else {
332        base.MouseDoubleClick(point, button);
333      }
334    }
335
336    internal void ToggleSelected() {
337      foreach (ResultsEntry entry in results.GetEntries()) {
338        entry.ToggleSelected();
339      }
340      results.FireChanged();
341    }
342
343    internal void ClearSelection() {
344      foreach (ResultsEntry entry in results.GetEntries().Where(x=>x.Selected)) {
345        entry.ToggleSelected();
346      }
347      results.FireChanged();
348    }
349
350    internal void ApplyFilter(Func<ResultsEntry, bool> filterPred) {
351      foreach (ResultsEntry r in results.GetEntries()) {
352        if (filterPred(r)) {
353          r.Visible = false;
354          r.Selected = false;
355          filteredEntries.Add(r);
356        }
357      }
358      results.FireChanged();
359    }
360
361    internal void ClearFilter() {
362      foreach (ResultsEntry r in filteredEntries) {
363        r.Visible = true;
364      }
365      filteredEntries.Clear();
366      results.FireChanged();
367    }
368  }
369}
Note: See TracBrowser for help on using the repository browser.