Free cookie consent management tool by TermsFeed Policy Generator

source: branches/1772_HeuristicLab.EvolutionTracking/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views/3.4/LayoutEngines/ReingoldTilfordLayoutEngine.cs @ 17578

Last change on this file since 17578 was 15351, checked in by bburlacu, 7 years ago

#1772: Merge trunk changes, add a couple of convenience parameters to the SchemaCreator.

File size: 10.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.Linq;
26
27namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views {
28  public class ReingoldTilfordLayoutEngine<T> : ILayoutEngine<T> where T : class {
29    public int NodeWidth { get; set; }
30    public int NodeHeight { get; set; }
31    private int minHorizontalSpacing = 5;
32    public int HorizontalSpacing {
33      get { return minHorizontalSpacing; }
34      set { minHorizontalSpacing = value; }
35    }
36
37    private int minVerticalSpacing = 5;
38    public int VerticalSpacing {
39      get { return minVerticalSpacing; }
40      set { minVerticalSpacing = value; }
41    }
42
43    private readonly Func<T, IEnumerable<T>> GetChildren;
44
45    public ReingoldTilfordLayoutEngine(Func<T, IEnumerable<T>> GetChildren) {
46      this.GetChildren = GetChildren;
47    }
48
49    public IEnumerable<VisualTreeNode<T>> CalculateLayout(T root) {
50      return CalculateLayout(root, 0, 0);
51    }
52
53    public IEnumerable<VisualTreeNode<T>> CalculateLayout(T root, float width, float height) {
54      Dictionary<T, LayoutNode<T>> layoutNodeMap = new Dictionary<T, LayoutNode<T>>();
55      var layoutRoot = new LayoutNode<T> { Content = root, Width = NodeWidth, Height = NodeHeight, };
56      layoutRoot.Ancestor = layoutRoot;
57      Expand(layoutRoot, layoutNodeMap);
58
59      FirstWalk(layoutRoot);
60      SecondWalk(layoutRoot, -layoutRoot.Prelim);
61      NormalizeCoordinates(layoutNodeMap.Values);
62      if (width > 0 && height > 0) {
63        FitToBounds(width, height, layoutNodeMap.Values);
64        Center(width, height, layoutNodeMap.Values);
65      }
66
67      return layoutNodeMap.Values.Select(x => new VisualTreeNode<T>(x.Content) {
68        Width = (int)Math.Round(x.Width),
69        Height = (int)Math.Round(x.Height),
70        X = (int)Math.Round(x.X),
71        Y = (int)Math.Round(x.Y)
72      });
73    }
74
75    private void Expand(LayoutNode<T> lRoot, Dictionary<T, LayoutNode<T>> map) {
76      map.Add(lRoot.Content, lRoot);
77      var children = GetChildren(lRoot.Content).ToList();
78      if (!children.Any()) return;
79      lRoot.Children = new List<LayoutNode<T>>(children.Count);
80      for (int i = 0; i < children.Count; ++i) {
81        var node = new LayoutNode<T> {
82          Content = children[i],
83          Number = i,
84          Parent = lRoot,
85          Level = lRoot.Level + 1,
86          Width = NodeWidth,
87          Height = NodeHeight
88        };
89        node.Ancestor = node;
90        lRoot.Children.Add(node);
91        Expand(node, map);
92      }
93    }
94
95
96    /// <summary>
97    /// Transform LayoutNode coordinates so that all coordinates are positive and start from (0,0)
98    /// </summary>
99    private static void NormalizeCoordinates(IEnumerable<LayoutNode<T>> nodes) {
100      float xmin = 0, ymin = 0;
101      foreach (var node in nodes) {
102        if (xmin > node.X) xmin = node.X;
103        if (ymin > node.Y) ymin = node.Y;
104      }
105      foreach (var node in nodes) {
106        node.X -= xmin;
107        node.Y -= ymin;
108      }
109    }
110
111    private void Center(float width, float height, IEnumerable<LayoutNode<T>> nodes) {
112      // center layout on screen
113      var bounds = Bounds(nodes);
114      float dx = 0, dy = 0;
115      if (width > bounds.Width) { dx = (width - bounds.Width) / 2f; }
116      if (height > bounds.Height) { dy = (height - bounds.Height) / 2f; }
117      foreach (var node in nodes) { node.Translate(dx, dy); }
118    }
119
120    private void FitToBounds(float width, float height, IEnumerable<LayoutNode<T>> nodes) {
121      var bounds = Bounds(nodes);
122      var myWidth = bounds.Width;
123      var myHeight = bounds.Height;
124
125      if (myWidth <= width && myHeight <= height) return; // no need to fit since we are within bounds
126
127      var layers = nodes.GroupBy(node => node.Level, node => node).ToList();
128
129      if (myWidth > width) {
130        // need to scale horizontally
131        float x = width / myWidth;
132        foreach (var node in layers.SelectMany(g => g)) {
133          node.X *= x;
134          node.Width *= x;
135        }
136        float spacing = minHorizontalSpacing * x;
137        foreach (var layer in layers) {
138          var nodesLayer = layer.ToList();
139          float minWidth = float.MaxValue;
140          for (int i = 0; i < nodesLayer.Count - 1; ++i) { minWidth = Math.Min(minWidth, nodesLayer[i + 1].X - nodesLayer[i].X); }
141          float w = Math.Min(NodeWidth, minWidth - spacing);
142          foreach (var node in nodesLayer) {
143            node.X += (node.Width - w) / 2f;
144            node.Width = w;
145            //this is a simple solution to ensure that the leftmost and rightmost nodes are not drawn partially offscreen due to scaling and offset
146            //this should work well enough 99.9% of the time with no noticeable visual difference
147            if (node.X < 0) {
148              node.Width += node.X;
149              node.X = 0;
150            } else if (node.X + node.Width > width) {
151              node.Width = width - node.X;
152            }
153          }
154        }
155      }
156      if (myHeight > height) {
157        // need to scale vertically
158        float x = height / myHeight;
159        foreach (var node in layers.SelectMany(g => g)) {
160          node.Y *= x;
161          node.Height *= x;
162        }
163      }
164    }
165
166
167    /// <summary>
168    /// Returns the bounding box for this layout. When the layout is normalized, the rectangle should be [0,0,xmin,xmax].
169    /// </summary>
170    /// <returns></returns>
171    private RectangleF Bounds(IEnumerable<LayoutNode<T>> nodes) {
172      float xmin = 0, xmax = 0, ymin = 0, ymax = 0;
173      foreach (LayoutNode<T> node in nodes) {
174        float x = node.X, y = node.Y;
175        if (xmin > x) xmin = x;
176        if (xmax < x) xmax = x;
177        if (ymin > y) ymin = y;
178        if (ymax < y) ymax = y;
179      }
180      return new RectangleF(xmin, ymin, xmax + NodeWidth, ymax + NodeHeight);
181    }
182
183    #region methods specific to the reingold-tilford layout algorithm
184    private void FirstWalk(LayoutNode<T> v) {
185      LayoutNode<T> w;
186      if (v.IsLeaf) {
187        w = v.LeftSibling;
188        if (w != null) {
189          v.Prelim = w.Prelim + minHorizontalSpacing + NodeWidth;
190        }
191      } else {
192        var defaultAncestor = v.Children[0]; // leftmost child
193
194        foreach (var child in v.Children) {
195          FirstWalk(child);
196          Apportion(child, ref defaultAncestor);
197        }
198        ExecuteShifts(v);
199        var leftmost = v.Children.First();
200        var rightmost = v.Children.Last();
201        float midPoint = (leftmost.Prelim + rightmost.Prelim) / 2;
202        w = v.LeftSibling;
203        if (w != null) {
204          v.Prelim = w.Prelim + minHorizontalSpacing + NodeWidth;
205          v.Mod = v.Prelim - midPoint;
206        } else {
207          v.Prelim = midPoint;
208        }
209      }
210    }
211
212    private void SecondWalk(LayoutNode<T> v, float m) {
213      v.X = v.Prelim + m;
214      v.Y = v.Level * (minVerticalSpacing + NodeHeight);
215      if (v.IsLeaf) return;
216      foreach (var child in v.Children) {
217        SecondWalk(child, m + v.Mod);
218      }
219    }
220
221    private void Apportion(LayoutNode<T> v, ref LayoutNode<T> defaultAncestor) {
222      var w = v.LeftSibling;
223      if (w == null) return;
224      LayoutNode<T> vip = v;
225      LayoutNode<T> vop = v;
226      LayoutNode<T> vim = w;
227      LayoutNode<T> vom = vip.LeftmostSibling;
228
229      float sip = vip.Mod;
230      float sop = vop.Mod;
231      float sim = vim.Mod;
232      float som = vom.Mod;
233
234      while (vim.NextRight != null && vip.NextLeft != null) {
235        vim = vim.NextRight;
236        vip = vip.NextLeft;
237        vom = vom.NextLeft;
238        vop = vop.NextRight;
239        vop.Ancestor = v;
240        float shift = (vim.Prelim + sim) - (vip.Prelim + sip) + minHorizontalSpacing + NodeWidth;
241        if (shift > 0) {
242          var ancestor = Ancestor(vim, v) ?? defaultAncestor;
243          MoveSubtree(ancestor, v, shift);
244          sip += shift;
245          sop += shift;
246        }
247        sim += vim.Mod;
248        sip += vip.Mod;
249        som += vom.Mod;
250        sop += vop.Mod;
251      }
252      if (vim.NextRight != null && vop.NextRight == null) {
253        vop.Thread = vim.NextRight;
254        vop.Mod += (sim - sop);
255      }
256      if (vip.NextLeft != null && vom.NextLeft == null) {
257        vom.Thread = vip.NextLeft;
258        vom.Mod += (sip - som);
259        defaultAncestor = v;
260      }
261    }
262
263    private void MoveSubtree(LayoutNode<T> wm, LayoutNode<T> wp, float shift) {
264      int subtrees = wp.Number - wm.Number; // TODO: Investigate possible bug (if the value ever happens to be zero) - happens when the tree is actually a graph (but that's outside the use case of this algorithm which only works with trees)
265      if (subtrees == 0) throw new Exception("MoveSubtree failed: check if object is really a tree (no cycles)");
266      wp.Change -= shift / subtrees;
267      wp.Shift += shift;
268      wm.Change += shift / subtrees;
269      wp.Prelim += shift;
270      wp.Mod += shift;
271    }
272
273    private void ExecuteShifts(LayoutNode<T> v) {
274      if (v.IsLeaf) return;
275      float shift = 0;
276      float change = 0;
277      for (int i = v.Children.Count - 1; i >= 0; --i) {
278        var w = v.Children[i];
279        w.Prelim += shift;
280        w.Mod += shift;
281        change += w.Change;
282        shift += (w.Shift + change);
283      }
284    }
285
286    private LayoutNode<T> Ancestor(LayoutNode<T> u, LayoutNode<T> v) {
287      var ancestor = u.Ancestor;
288      if (ancestor == null) return null;
289      return ancestor.Parent == v.Parent ? ancestor : null;
290    }
291    #endregion
292  }
293}
Note: See TracBrowser for help on using the repository browser.