Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.EvolutionTracking/HeuristicLab.EvolutionTracking.Views/3.4/GenealogyGraphChart.cs @ 11552

Last change on this file since 11552 was 11506, checked in by bburlacu, 10 years ago

#1772: Updated views (fixed position and anchors).

File size: 13.7 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2014 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.Drawing;
25using System.Drawing.Drawing2D;
26using System.Linq;
27using System.Windows.Forms;
28using HeuristicLab.Common;
29using HeuristicLab.Visualization;
30
31namespace HeuristicLab.EvolutionTracking.Views {
32  public partial class GenealogyGraphChart : ChartControl {
33    private IGenealogyGraph genealogyGraph;
34
35    private const double XIncrement = 30;
36    private const double YIncrement = 30;
37    private const double Diameter = 20;
38
39    private readonly Brush defaultBrush;
40    private readonly Pen defaultPen;
41
42    public IGenealogyGraph GenealogyGraph {
43      get { return genealogyGraph; }
44      set {
45        if (value == null) return;
46        genealogyGraph = value;
47        Clear();
48        DrawGraph(XIncrement, YIncrement, Diameter);
49      }
50    }
51
52    public IGenealogyGraphNode SelectedGraphNode {
53      get {
54        return SelectedVisualNode == null ? null : SelectedVisualNode.Data;
55      }
56    }
57
58    private void Clear() {
59      nodeMap = new Dictionary<IGenealogyGraphNode, VisualGenealogyGraphNode>();
60      arcMap = new Dictionary<Tuple<VisualGenealogyGraphNode, VisualGenealogyGraphNode>, VisualGenealogyGraphArc>();
61
62      Chart.Group.Clear();
63    }
64
65    private Dictionary<IGenealogyGraphNode, VisualGenealogyGraphNode> nodeMap;
66    private Dictionary<Tuple<VisualGenealogyGraphNode, VisualGenealogyGraphNode>, VisualGenealogyGraphArc> arcMap;
67
68    #region chart modes
69    public bool SimpleLineages { get; set; }
70    public bool LockGenealogy { get; set; }
71    public bool TraceFragments { get; set; }
72    #endregion
73
74    private Visualization.Rectangle TargetRectangle { get; set; }
75    private bool DrawInProgress { get; set; } // do not try to update the chart while the drawing is not finished
76    protected VisualGenealogyGraphNode SelectedVisualNode { get; set; }
77
78    private VisualGenealogyGraphNode GetMappedNode(IGenealogyGraphNode node) {
79      VisualGenealogyGraphNode v;
80      nodeMap.TryGetValue(node, out v);
81      return v;
82    }
83
84    private VisualGenealogyGraphArc GetMappedArc(IGenealogyGraphNode source, IGenealogyGraphNode target) {
85      VisualGenealogyGraphNode visualSource, visualTarget;
86      nodeMap.TryGetValue(source, out visualSource);
87      nodeMap.TryGetValue(target, out visualTarget);
88
89      if (visualSource == null || visualTarget == null) return null;
90
91      VisualGenealogyGraphArc arc;
92      arcMap.TryGetValue(new Tuple<VisualGenealogyGraphNode, VisualGenealogyGraphNode>(visualSource, visualTarget), out arc);
93      return arc;
94    }
95
96    public GenealogyGraphChart()
97      : base() {
98      InitializeComponent();
99
100      defaultBrush = new SolidBrush(Color.Transparent);
101      defaultPen = new Pen(Color.DarkGray);
102    }
103
104    protected virtual void DrawGraph(double xIncrement, double yIncrement, double diameter) {
105      Chart.UpdateEnabled = false;
106      DrawInProgress = true;
107
108      var ranks = GenealogyGraph.Ranks.Select(t => new { Rank = t.Key, Nodes = t.Value }).OrderBy(p => p.Rank).ToList();
109      double x = 0;
110      double y = PreferredSize.Height + yIncrement + 2 * diameter;
111
112      foreach (var rank in ranks) {
113        var nodes = rank.Nodes.ToList();
114        nodes.Sort((a, b) => b.CompareTo(a)); // sort descending by quality
115        var nl = Environment.NewLine;
116
117        foreach (var node in nodes) {
118          var brush = new SolidBrush(node.GetColor());
119          var visualNode = new VisualGenealogyGraphNode(Chart, x, y, x + diameter, y + diameter, defaultPen, brush) {
120            Data = node,
121            ToolTipText = "Rank: " + node.Rank + nl +
122                          "Quality: " + String.Format("{0:0.0000}", node.Quality) + nl +
123                          "IsElite: " + node.IsElite + nl +
124                          "In/Out Degree: " + node.InDegree + " " + node.OutDegree
125          };
126          Chart.Group.Add(visualNode);
127          nodeMap.Add(node, visualNode);
128
129          x += xIncrement;
130        }
131        y -= yIncrement;
132        x = 0;
133      }
134
135      // add arcs
136      foreach (var node in GenealogyGraph.Vertices) {
137        if (!node.InArcs.Any()) continue;
138        var visualNode = GetMappedNode(node);
139
140        if (visualNode == null) continue;
141        foreach (var arc in node.InArcs) {
142          var parent = arc.Source;
143          var visualParent = GetMappedNode(parent);
144          if (visualParent == null) continue;
145          var pen = Pens.Transparent;
146          var visualArc = AddArc(Chart, visualParent, visualNode, pen);
147          visualArc.OneLayerDown(); // send it behind the visual nodes
148          if (!arcMap.ContainsKey(Tuple.Create(visualParent, visualNode))) {
149            arcMap.Add(Tuple.Create(visualParent, visualNode), visualArc);
150          }
151        }
152      }
153      // TODO: connect elites
154
155      Chart.UpdateEnabled = true;
156      Chart.EnforceUpdate();
157
158      DrawInProgress = false;
159    }
160
161    public event MouseEventHandler GenealogyGraphNodeClicked;
162    protected void OnGenealogyGraphNodeClicked(object sender, MouseEventArgs e) {
163      var clicked = GenealogyGraphNodeClicked;
164      if (clicked != null) clicked(sender, e);
165    }
166
167    public event MouseEventHandler GenealogyGraphNodeDoubleClicked;
168    protected void OnGenealogyGraphNodeDoubleClicked(object sender, MouseEventArgs e) {
169      var doubleClicked = GenealogyGraphNodeDoubleClicked;
170      if (doubleClicked != null)
171        doubleClicked(sender, e);
172    }
173    #region event handlers
174
175    protected override void pictureBox_MouseMove(object sender, MouseEventArgs e) {
176      if (!DrawInProgress) {
177        switch (e.Button) {
178          case MouseButtons.Left:
179            Chart.Mode = ChartMode.Select;
180            Cursor = Cursors.Default;
181            break;
182          case MouseButtons.Middle:
183            Chart.Mode = ChartMode.Move;
184            Cursor = Cursors.Hand;
185            break;
186        }
187      }
188      base.pictureBox_MouseMove(sender, e);
189    }
190    protected override void pictureBox_MouseUp(object sender, MouseEventArgs e) {
191      Cursor = Cursors.Default;
192      if (Chart.Mode == ChartMode.Move) {
193        Chart.Mode = ChartMode.Select;
194        return;
195      }
196      if (Chart.Mode != ChartMode.Select) {
197        base.pictureBox_MouseUp(sender, e);
198        return;
199      }
200      var visualNodes = Chart.GetAllPrimitives(e.Location).Where(p => p is VisualGenealogyGraphNode).ToList();
201      if (!visualNodes.Any()) {
202        SelectedVisualNode = null;
203        return;
204      }
205      if (SelectedVisualNode == visualNodes[0]) return;
206      SelectedVisualNode = visualNodes[0] as VisualGenealogyGraphNode;
207      if (SelectedVisualNode == null) return;
208
209      if (!LockGenealogy) {
210        // new node has been selected, clean up
211        Chart.UpdateEnabled = false;
212        if (ModifierKeys != Keys.Shift) {
213          // clear colors
214          ClearPrimitives();
215        }
216        // use a rectangle to highlight the currently selected genealogy graph node
217        var graphNode = SelectedVisualNode.Data;
218        var visualNode = GetMappedNode(graphNode);
219
220        DrawLineage(visualNode, n => SimpleLineages ? n.IncomingArcs.Take(1) : n.IncomingArcs, a => a.Source);
221        ((SolidBrush)visualNode.Brush).Color = Color.Transparent;
222        DrawLineage(visualNode, n => n.OutgoingArcs, a => a.Target);
223      }
224
225      MarkSelectedNode();
226
227      // update
228      Chart.UpdateEnabled = true;
229      Chart.EnforceUpdate();
230
231      if (SelectedVisualNode != null)
232        /* emit clicked event */
233        OnGenealogyGraphNodeClicked(SelectedVisualNode, e);
234
235      base.pictureBox_MouseUp(sender, e);
236    }
237    #endregion
238
239    private static void DrawLineage(VisualGenealogyGraphNode node, Func<VisualGenealogyGraphNode, IEnumerable<VisualGenealogyGraphArc>> arcSelector, Func<VisualGenealogyGraphArc, VisualGenealogyGraphNode> nodeSelector) {
240      var brush = (SolidBrush)node.Brush;
241      if (brush.Color != Color.Transparent) return; // this lineage was already drawn (avoid redrawing common ancestors)
242      brush.Color = node.Data.GetColor();
243      var arcs = arcSelector(node);
244      var pen = new Pen(Color.Transparent);
245      foreach (var arc in arcs) {
246        var source = arc.Source.Data;
247        var target = arc.Target.Data;
248        var start = new Point((int)arc.Start.X, (int)arc.Start.Y);
249        var end = new Point((int)arc.End.X, (int)arc.End.Y);
250        arc.Pen = pen;
251        arc.Pen.Brush = new LinearGradientBrush(start, end, source.GetColor(), target.GetColor());
252        DrawLineage(nodeSelector(arc), arcSelector, nodeSelector);
253      }
254    }
255
256    public void HighlightHotPaths() {
257      Chart.UpdateEnabled = false;
258      ClearPrimitives();
259      var arcs = GenealogyGraph.Vertices.SelectMany(n => n.InArcs).ToList();
260      foreach (var arc in arcs) { arc.Weight = 1.0; } // reset weights
261      var rank = GenealogyGraph.Ranks.Keys.Max();
262      foreach (var ggn in GenealogyGraph.Ranks[rank]) {
263        foreach (var ancestor in ggn.Ancestors) {
264          foreach (var arc in ancestor.InArcs) {
265            arc.Weight++;
266          }
267        }
268      }
269      double max = arcs.Max(a => a.Weight);
270      double min = arcs.Min(a => a.Weight);
271
272      if (min.IsAlmost(max)) return;
273      //translate interval (min,max) to interval (0,255)
274      foreach (var arc in arcs) {
275        var vArc = GetMappedArc(arc.Source, arc.Target);
276        int colorIndex = (int)Math.Round((arc.Weight - min) * 255 / (max - min));
277        if (colorIndex > 254) colorIndex = 254;
278        vArc.Pen = new Pen(ColorGradient.Colors[colorIndex]);
279        //        vArc.Pen.Brush = new SolidBrush(ColorGradient.Colors[colorIndex]);
280      }
281      Chart.UpdateEnabled = true;
282      Chart.EnforceUpdate();
283    }
284
285    void MarkSelectedNode() {
286      var center = SelectedVisualNode.Center;
287      var size = SelectedVisualNode.Size;
288      double x1 = center.X - size.Width / 2;
289      double x2 = x1 + size.Width;
290      double y1 = center.Y - size.Height / 2;
291      double y2 = y1 + size.Height;
292      if (TargetRectangle == null) {
293        TargetRectangle = new Visualization.Rectangle(Chart, x1, y1, x2, y2, new Pen(Color.Black), null);
294        Chart.Group.Add(TargetRectangle);
295      } else {
296        TargetRectangle.SetPosition(x1, y1, x2, y2);
297      }
298    }
299
300    private static VisualGenealogyGraphArc AddArc(IChart chart, VisualGenealogyGraphNode source, VisualGenealogyGraphNode target, Pen pen, Brush brush = null) {
301      var arc = new VisualGenealogyGraphArc(chart, source, target, pen) { Brush = brush };
302      arc.UpdatePosition();
303      source.OutgoingArcs.Add(arc);
304      target.IncomingArcs.Add(arc);
305      chart.Group.Add(arc);
306      return arc;
307    }
308
309    public virtual void ClearPrimitives() {
310      foreach (var primitive in Chart.Group.Primitives) {
311        if (primitive is VisualGenealogyGraphArc) {
312          primitive.Pen = Pens.Transparent;
313        } else if (primitive is VisualGenealogyGraphNode) {
314          primitive.Brush = new SolidBrush(Color.Transparent);
315          primitive.Pen = new Pen(Color.DarkGray);
316        }
317      }
318    }
319
320    public void HighlightNodes(IEnumerable<IGenealogyGraphNode> nodes) {
321      Chart.UpdateEnabled = false;
322      ClearPrimitives();
323      foreach (var node in nodes) {
324        var graphNode = GetMappedNode(node);
325        graphNode.Brush = new SolidBrush(node.GetColor());
326      }
327      Chart.UpdateEnabled = true;
328      Chart.EnforceUpdate();
329    }
330
331    public void HighlightAll() {
332      Chart.UpdateEnabled = false;
333      foreach (var visualNode in nodeMap.Values) {
334        visualNode.Brush = new SolidBrush(visualNode.Data.GetColor());
335      }
336      foreach (var arc in arcMap.Values) {
337        var source = arc.Source.Data;
338        var target = arc.Target.Data;
339        var start = new Point((int)arc.Start.X, (int)arc.Start.Y);
340        var end = new Point((int)arc.End.X, (int)arc.End.Y);
341        arc.Pen.Brush = new LinearGradientBrush(start, end, source.GetColor(), target.GetColor());
342      }
343      Chart.UpdateEnabled = true;
344      Chart.EnforceUpdate();
345    }
346
347    public void HighlightArc(IGenealogyGraphNode source, IGenealogyGraphNode target) {
348      var arc = GetMappedArc(source, target) ??
349                AddArc(Chart, GetMappedNode(source), GetMappedNode(target), new Pen(Color.Transparent));
350      var start = new Point((int)arc.Start.X, (int)arc.Start.Y);
351      var end = new Point((int)arc.End.X, (int)arc.End.Y);
352      arc.Pen = new Pen(Color.Transparent);
353      arc.Pen.Brush = new LinearGradientBrush(start, end, source.GetColor(), target.GetColor());
354    }
355  }
356
357  internal static class Util {
358    public static Color GetColor(this IGenealogyGraphNode node) {
359      var colorIndex = (int)Math.Round(node.Quality * ColorGradient.Colors.Count);
360      if (colorIndex >= ColorGradient.Colors.Count) return ColorGradient.Colors.Last();
361      return ColorGradient.Colors[colorIndex];
362    }
363  }
364}
Note: See TracBrowser for help on using the repository browser.