Free cookie consent management tool by TermsFeed Policy Generator

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

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

#1772: Removed Storable property from Vertex in- and outArcs as it causes a stack overflow exception during serialization. Added a list of arcs to the DirectedGraph class which is persisted. The Vertex in- and outArcs lists are then restored by the graph after the deserialization. Renamed Nodes data member to Vertices.

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