Free cookie consent management tool by TermsFeed Policy Generator

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

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

#1772: Improved FragmentGraphView.

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