Index: branches/HeuristicLab.EvolutionaryTracking/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Formatters/SymbolicExpressionTreeLatexFormatter.cs
===================================================================
--- branches/HeuristicLab.EvolutionaryTracking/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Formatters/SymbolicExpressionTreeLatexFormatter.cs	(revision 9963)
+++ branches/HeuristicLab.EvolutionaryTracking/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Formatters/SymbolicExpressionTreeLatexFormatter.cs	(revision 9963)
@@ -0,0 +1,97 @@
+﻿#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2013 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+#endregion
+
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Linq;
+using System.Text;
+using HeuristicLab.Common;
+using HeuristicLab.Core;
+
+namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding {
+  [Item("LaTeX/PDF Formatter", "Formatter for symbolic expression trees for use with latex.")]
+  public class SymbolicExpressionTreeLatexFormatter : NamedItem, ISymbolicExpressionTreeStringFormatter {
+    private readonly static Dictionary<string, string> symbolNameMap = new Dictionary<string, string>
+    {
+      {"ProgramRootSymbol", "Prog"},
+      {"StartSymbol","RPB"}
+    };
+    private readonly ReingoldTilfordLayoutEngine<ISymbolicExpressionTreeNode> layoutEngine = new ReingoldTilfordLayoutEngine<ISymbolicExpressionTreeNode>();
+    private readonly SymbolicExpressionTreeLayoutAdapter layoutAdapter = new SymbolicExpressionTreeLayoutAdapter();
+
+    public SymbolicExpressionTreeLatexFormatter() {
+      layoutEngine = new ReingoldTilfordLayoutEngine<ISymbolicExpressionTreeNode>();
+    }
+
+    protected SymbolicExpressionTreeLatexFormatter(SymbolicExpressionTreeLatexFormatter original, Cloner cloner)
+      : base(original, cloner) {
+    }
+
+    public override IDeepCloneable Clone(Cloner cloner) {
+      return new SymbolicExpressionTreeLatexFormatter(this, cloner);
+    }
+
+    public string Format(ISymbolicExpressionTree symbolicExpressionTree) {
+      var layoutNodes = layoutAdapter.Convert(symbolicExpressionTree).ToList();
+      layoutEngine.Root = layoutNodes[0];
+      foreach (var ln in layoutNodes)
+        layoutEngine.AddNode(ln.Content, ln);
+      layoutEngine.CalculateLayout();
+      var nodeCoordinates = layoutEngine.GetNodeCoordinates();
+      var sb = new StringBuilder();
+      var nl = Environment.NewLine;
+      double ws = 1;
+      double hs = 0.7;
+
+      sb.Append("\\documentclass[class=minimal,border=0pt]{standalone}" + nl +
+                "\\usepackage{tikz}" + nl +
+                "\\begin{document}" + nl +
+                "\\begin{tikzpicture}" + nl +
+                "\\def\\ws{1}" + nl +
+                "\\def\\hs{0.7}" + nl);
+
+      var nodeIndices = new Dictionary<ISymbolicExpressionTreeNode, int>();
+      var nodes = symbolicExpressionTree.IterateNodesBreadth().ToList();
+      for (int i = 0; i < nodes.Count; ++i) {
+        var node = nodes[i];
+        nodeIndices.Add(node, i);
+        var coord = nodeCoordinates[node];
+        var nodeName = symbolNameMap.ContainsKey(node.Symbol.Name) ? symbolNameMap[node.Symbol.Name] : node.ToString();
+        sb.AppendLine(string.Format(CultureInfo.InvariantCulture, "\\node ({0}) at (\\ws*{1},\\hs*{2}) {{{3}}};", i, ws * coord.X, -hs * coord.Y, EscapeLatexString(nodeName)));
+      }
+
+      for (int i = 0; i < nodes.Count; ++i) {
+        foreach (var s in nodes[i].Subtrees) {
+          sb.AppendLine(string.Format(CultureInfo.InvariantCulture, "\\draw ({0}) -- ({1});", i, nodeIndices[s]));
+        }
+      }
+
+      sb.Append("\\end{tikzpicture}" + nl +
+                "\\end{document}" + nl);
+      return sb.ToString();
+    }
+
+    private static string EscapeLatexString(string s) {
+      return s.Replace("\\", "\\\\").Replace("{", "\\{").Replace("}", "\\}").Replace("_", "\\_");
+    }
+  }
+}
Index: branches/HeuristicLab.EvolutionaryTracking/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding-3.4.csproj
===================================================================
--- branches/HeuristicLab.EvolutionaryTracking/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding-3.4.csproj	(revision 9835)
+++ branches/HeuristicLab.EvolutionaryTracking/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding-3.4.csproj	(revision 9963)
@@ -191,8 +191,11 @@
     <Compile Include="Crossovers\TracingSymbolicExpressionTreeCrossover.cs" />
     <Compile Include="Formatters\SymbolicExpressionTreeGraphvizFormatter.cs" />
+    <Compile Include="Formatters\SymbolicExpressionTreeLatexFormatter.cs" />
     <Compile Include="Fragment.cs" />
     <Compile Include="GenericWrapper.cs" />
     <Compile Include="GeneticExchange.cs" />
     <Compile Include="Interfaces\IFragment.cs" />
+    <Compile Include="Interfaces\ILayoutAdapter.cs" />
+    <Compile Include="Interfaces\ILayoutNode.cs" />
     <Compile Include="Interfaces\IReadOnlySymbol.cs" />
     <Compile Include="Interfaces\ISymbolicExpressionGrammar.cs" />
@@ -217,4 +220,7 @@
     <Compile Include="Interfaces\Operators\ISymbolicExpressionTreeSizeConstraintOperator.cs" />
     <Compile Include="Interfaces\Operators\ITracingSymbolicExpressionTreeOperator.cs" />
+    <Compile Include="LayoutEngines\LayoutNode.cs" />
+    <Compile Include="LayoutEngines\ReingoldTilfordLayoutEngine.cs" />
+    <Compile Include="LayoutEngines\SymbolicExpressionTreeLayoutAdapter.cs" />
     <Compile Include="Manipulators\ChangeNodeTypeManipulation.cs" />
     <Compile Include="Interfaces\Operators\ISymbolicExpressionTreeManipulator.cs" />
@@ -240,5 +246,4 @@
     <Compile Include="Interfaces\Operators\ISymbolicExpressionTreeOperator.cs" />
     <Compile Include="SymbolicExpressionTree.cs" />
-    <Compile Include="Properties\AssemblyInfo.cs" />
     <Compile Include="SymbolicExpressionTreeNode.cs" />
     <Compile Include="Symbols\Argument.cs" />
@@ -258,4 +263,5 @@
     <None Include="Plugin.cs.frame" />
     <None Include="Properties\AssemblyInfo.cs.frame" />
+    <Compile Include="Properties\AssemblyInfo.cs" />
   </ItemGroup>
   <ItemGroup>
Index: branches/HeuristicLab.EvolutionaryTracking/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Interfaces/ILayoutAdapter.cs
===================================================================
--- branches/HeuristicLab.EvolutionaryTracking/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Interfaces/ILayoutAdapter.cs	(revision 9963)
+++ branches/HeuristicLab.EvolutionaryTracking/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Interfaces/ILayoutAdapter.cs	(revision 9963)
@@ -0,0 +1,8 @@
+﻿using System;
+using System.Collections.Generic;
+
+namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding {
+  public interface ILayoutAdapter<T> where T : class {
+    IEnumerable<ILayoutNode<T>> Convert(T root, Func<T, ILayoutNode<T>> convertFunc);
+  }
+}
Index: branches/HeuristicLab.EvolutionaryTracking/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Interfaces/ILayoutNode.cs
===================================================================
--- branches/HeuristicLab.EvolutionaryTracking/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Interfaces/ILayoutNode.cs	(revision 9963)
+++ branches/HeuristicLab.EvolutionaryTracking/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Interfaces/ILayoutNode.cs	(revision 9963)
@@ -0,0 +1,49 @@
+﻿#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2013 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+#endregion
+
+using System.Collections.Generic;
+namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding {
+  public interface ILayoutNode<T> where T : class {
+    ILayoutNode<T> NextLeft { get; }
+    ILayoutNode<T> NextRight { get; }
+    ILayoutNode<T> LeftSibling { get; }
+    ILayoutNode<T> LeftmostSibling { get; }
+
+    ILayoutNode<T> Thread { get; set; }
+    ILayoutNode<T> Ancestor { get; set; }
+    ILayoutNode<T> Parent { get; set; }
+    List<ILayoutNode<T>> Children { get; set; }
+
+    float Mod { get; set; }
+    float Prelim { get; set; }
+    float Change { get; set; }
+    float Shift { get; set; }
+    int Number { get; set; }
+    int Level { get; set; }
+
+    float X { get; set; }
+    float Y { get; set; }
+
+    bool IsLeaf { get; }
+
+    T Content { get; set; }
+  }
+}
Index: branches/HeuristicLab.EvolutionaryTracking/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/LayoutEngines/LayoutNode.cs
===================================================================
--- branches/HeuristicLab.EvolutionaryTracking/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/LayoutEngines/LayoutNode.cs	(revision 9963)
+++ branches/HeuristicLab.EvolutionaryTracking/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/LayoutEngines/LayoutNode.cs	(revision 9963)
@@ -0,0 +1,69 @@
+﻿#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2013 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+#endregion
+
+using System.Collections.Generic;
+using System.Linq;
+
+namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.LayoutEngines {
+  public class LayoutNode<T> : ILayoutNode<T> where T : class {
+    public ILayoutNode<T> NextLeft {
+      get {
+        return Children == null ? Thread : Children.First();
+      }
+    }
+    public ILayoutNode<T> NextRight {
+      get {
+        return Children == null ? Thread : Children.Last();
+      }
+    }
+    public ILayoutNode<T> LeftSibling {
+      get {
+        if (Parent == null) return null;
+        return Number == 0 ? null : Parent.Children[Number - 1];
+      }
+    }
+    public ILayoutNode<T> LeftmostSibling {
+      get {
+        if (Parent == null) return null;
+        return Number == 0 ? null : Parent.Children[0];
+      }
+    }
+
+    public ILayoutNode<T> Thread { get; set; }
+    public ILayoutNode<T> Ancestor { get; set; }
+    public ILayoutNode<T> Parent { get; set; }
+    public List<ILayoutNode<T>> Children { get; set; }
+    public float Mod { get; set; }
+    public float Prelim { get; set; }
+    public float Change { get; set; }
+    public float Shift { get; set; }
+    public int Number { get; set; }
+    public int Level { get; set; }
+    public float X { get; set; }
+    public float Y { get; set; }
+
+    public bool IsLeaf {
+      get { return Children == null || Children.Count == 0; }
+    }
+
+    public T Content { get; set; }
+  }
+}
Index: branches/HeuristicLab.EvolutionaryTracking/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/LayoutEngines/ReingoldTilfordLayoutEngine.cs
===================================================================
--- branches/HeuristicLab.EvolutionaryTracking/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/LayoutEngines/ReingoldTilfordLayoutEngine.cs	(revision 9963)
+++ branches/HeuristicLab.EvolutionaryTracking/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/LayoutEngines/ReingoldTilfordLayoutEngine.cs	(revision 9963)
@@ -0,0 +1,243 @@
+﻿
+using System;
+using System.Collections.Generic;
+using System.Drawing;
+using System.Linq;
+
+namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding {
+  public class ReingoldTilfordLayoutEngine<T> where T : class {
+    private readonly Dictionary<T, ILayoutNode<T>> nodes; // provides a reverse mapping T => ILayoutNode
+
+    public ReingoldTilfordLayoutEngine() {
+      nodes = new Dictionary<T, ILayoutNode<T>>();
+    }
+
+    public Dictionary<T, ILayoutNode<T>> Nodes { get { return nodes; } }
+
+    public void AddNode(T content, ILayoutNode<T> node) {
+      if (nodes.ContainsKey(content)) {
+        throw new ArgumentException("Content already present in the dictionary.");
+      }
+      nodes.Add(content, node);
+    }
+
+    public ILayoutNode<T> GetNode(T content) {
+      ILayoutNode<T> ILayoutNode;
+      nodes.TryGetValue(content, out ILayoutNode);
+      return ILayoutNode;
+    }
+
+    private float minHorizontalSpacing = 5;
+    public float MinHorizontalSpacing {
+      get { return minHorizontalSpacing; }
+      set { minHorizontalSpacing = value; }
+    }
+
+    private float minVerticalSpacing = 5;
+    public float MinVerticalSpacing {
+      get { return minVerticalSpacing; }
+      set { minVerticalSpacing = value; }
+    }
+
+    private ILayoutNode<T> root;
+    public ILayoutNode<T> Root {
+      get { return root; }
+      set {
+        root = value;
+      }
+    }
+
+    /// <summary>
+    /// Returns a string containing all the coordinates (useful for debugging).
+    /// </summary>
+    /// <returns></returns>
+    public string DumpCoordinates() {
+      if (nodes == null || nodes.Count == 0) return string.Empty;
+      return nodes.Values.Aggregate("", (current, node) => current + (node.X + " " + node.Y + Environment.NewLine));
+    }
+
+    public void ResetCoordinates() {
+      foreach (var node in nodes.Values) {
+        node.X = 0;
+        node.Y = 0;
+      }
+    }
+
+    /// <summary>
+    /// Transform ILayoutNode coordinates so that all coordinates are positive and start from 0.
+    /// </summary>
+    private void NormalizeCoordinates() {
+      var list = nodes.Values.ToList();
+      float xmin = 0, ymin = 0;
+      for (int i = 0; i != list.Count; ++i) {
+        if (xmin > list[i].X) xmin = list[i].X;
+        if (ymin > list[i].Y) ymin = list[i].Y;
+      }
+      for (int i = 0; i != list.Count; ++i) {
+        list[i].X -= xmin;
+        list[i].Y -= ymin;
+      }
+    }
+
+    public void Reset() {
+      root = null;
+      nodes.Clear();
+    }
+
+    public void ResetParameters() {
+      foreach (var layoutNode in nodes.Values) {
+        // reset layout-related parameters 
+        layoutNode.Ancestor = layoutNode;
+        layoutNode.Thread = null;
+        layoutNode.Change = 0;
+        layoutNode.Shift = 0;
+        layoutNode.Prelim = 0;
+        layoutNode.Mod = 0;
+      }
+    }
+
+    public void CalculateLayout() {
+      if (root == null)
+        throw new Exception("Root cannot be null.");
+      ResetCoordinates(); // reset node X,Y coordinates
+      ResetParameters(); // reset node parameters like Mod, Shift etc. 
+      FirstWalk(root);
+      SecondWalk(root, -root.Prelim);
+      NormalizeCoordinates();
+    }
+
+    /// <summary>
+    /// Returns a map of coordinates for each ILayoutNode in the symbolic expression tree.
+    /// </summary>
+    /// <returns></returns>
+    public Dictionary<T, PointF> GetNodeCoordinates() {
+      return nodes.ToDictionary(x => x.Key, x => new PointF(x.Value.X, x.Value.Y));
+    }
+
+    /// <summary>
+    /// Returns the bounding box for this layout. When the layout is normalized, the rectangle should be [0,0,xmin,xmax].
+    /// </summary>
+    /// <returns></returns>
+    public RectangleF Bounds() {
+      float xmin, xmax, ymin, ymax; xmin = xmax = ymin = ymax = 0;
+      var list = nodes.Values.ToList();
+      for (int i = 0; i != list.Count; ++i) {
+        float x = list[i].X, y = list[i].Y;
+        if (xmin > x) xmin = x;
+        if (xmax < x) xmax = x;
+        if (ymin > y) ymin = y;
+        if (ymax < y) ymax = y;
+      }
+      return new RectangleF(xmin, ymin, xmax + minHorizontalSpacing, ymax + minVerticalSpacing);
+    }
+
+    private void FirstWalk(ILayoutNode<T> v) {
+      ILayoutNode<T> w;
+      if (v.IsLeaf) {
+        w = v.LeftSibling;
+        if (w != null) {
+          v.Prelim = w.Prelim + minHorizontalSpacing;
+        }
+      } else {
+        var defaultAncestor = v.Children[0]; // leftmost child
+
+        foreach (var child in v.Children) {
+          FirstWalk(child);
+          Apportion(child, ref defaultAncestor);
+        }
+        ExecuteShifts(v);
+        var leftmost = v.Children.First();
+        var rightmost = v.Children.Last();
+        float midPoint = (leftmost.Prelim + rightmost.Prelim) / 2;
+        w = v.LeftSibling;
+        if (w != null) {
+          v.Prelim = w.Prelim + minHorizontalSpacing;
+          v.Mod = v.Prelim - midPoint;
+        } else {
+          v.Prelim = midPoint;
+        }
+      }
+    }
+
+    private void SecondWalk(ILayoutNode<T> v, float m) {
+      if (!nodes.Values.Contains(v)) throw new Exception("Layout node not present in dictionary!");
+      v.X = v.Prelim + m;
+      v.Y = v.Level * minVerticalSpacing;
+      if (v.IsLeaf) return;
+      foreach (var child in v.Children) {
+        SecondWalk(child, m + v.Mod);
+      }
+    }
+
+    private void Apportion(ILayoutNode<T> v, ref ILayoutNode<T> defaultAncestor) {
+      var w = v.LeftSibling;
+      if (w == null) return;
+      ILayoutNode<T> vip = v;
+      ILayoutNode<T> vop = v;
+      ILayoutNode<T> vim = w;
+      ILayoutNode<T> vom = vip.LeftmostSibling;
+
+      float sip = vip.Mod;
+      float sop = vop.Mod;
+      float sim = vim.Mod;
+      float som = vom.Mod;
+
+      while (vim.NextRight != null && vip.NextLeft != null) {
+        vim = vim.NextRight;
+        vip = vip.NextLeft;
+        vom = vom.NextLeft;
+        vop = vop.NextRight;
+        vop.Ancestor = v;
+        float shift = (vim.Prelim + sim) - (vip.Prelim + sip) + minHorizontalSpacing;
+        if (shift > 0) {
+          var ancestor = Ancestor(vim, v) ?? defaultAncestor;
+          MoveSubtree(ancestor, v, shift);
+          sip += shift;
+          sop += shift;
+        }
+        sim += vim.Mod;
+        sip += vip.Mod;
+        som += vom.Mod;
+        sop += vop.Mod;
+      }
+      if (vim.NextRight != null && vop.NextRight == null) {
+        vop.Thread = vim.NextRight;
+        vop.Mod += (sim - sop);
+      }
+      if (vip.NextLeft != null && vom.NextLeft == null) {
+        vom.Thread = vip.NextLeft;
+        vom.Mod += (sip - som);
+        defaultAncestor = v;
+      }
+    }
+
+    private void MoveSubtree(ILayoutNode<T> wm, ILayoutNode<T> wp, float shift) {
+      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
+      if (subtrees == 0) throw new Exception();
+      wp.Change -= shift / subtrees;
+      wp.Shift += shift;
+      wm.Change += shift / subtrees;
+      wp.Prelim += shift;
+      wp.Mod += shift;
+    }
+
+    private void ExecuteShifts(ILayoutNode<T> v) {
+      if (v.IsLeaf) return;
+      float shift = 0;
+      float change = 0;
+      for (int i = v.Children.Count - 1; i >= 0; --i) {
+        var w = v.Children[i];
+        w.Prelim += shift;
+        w.Mod += shift;
+        change += w.Change;
+        shift += (w.Shift + change);
+      }
+    }
+
+    private ILayoutNode<T> Ancestor(ILayoutNode<T> u, ILayoutNode<T> v) {
+      var ancestor = u.Ancestor;
+      if (ancestor == null) return null;
+      return ancestor.Parent == v.Parent ? ancestor : null;
+    }
+  }
+}
Index: branches/HeuristicLab.EvolutionaryTracking/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/LayoutEngines/SymbolicExpressionTreeLayoutAdapter.cs
===================================================================
--- branches/HeuristicLab.EvolutionaryTracking/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/LayoutEngines/SymbolicExpressionTreeLayoutAdapter.cs	(revision 9963)
+++ branches/HeuristicLab.EvolutionaryTracking/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/LayoutEngines/SymbolicExpressionTreeLayoutAdapter.cs	(revision 9963)
@@ -0,0 +1,76 @@
+﻿#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2013 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+#endregion
+
+using System;
+using System.Collections.Generic;
+using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.LayoutEngines;
+
+namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding {
+  // adapter class that provides some conversion methods from symbolic expression trees to layout nodes (preserving the tree structure)
+  public class SymbolicExpressionTreeLayoutAdapter : ILayoutAdapter<ISymbolicExpressionTreeNode> {
+    // default conversion function between ISymbolicExpressionTreeNode and ILayoutNode<ISymbolicExpressionTree>
+    ILayoutNode<ISymbolicExpressionTreeNode> defaultConvert(ISymbolicExpressionTreeNode node) {
+      var layoutNode = new LayoutNode<ISymbolicExpressionTreeNode> { Content = node };
+      layoutNode.Ancestor = layoutNode;
+      return layoutNode;
+    }
+
+    public IEnumerable<ILayoutNode<ISymbolicExpressionTreeNode>> Convert(ISymbolicExpressionTree tree, Func<ISymbolicExpressionTreeNode, ILayoutNode<ISymbolicExpressionTreeNode>> convertFunc = null) {
+      return Convert(tree.Root, convertFunc);
+    }
+    // translate the symbolic expression tree structure to a layout node tree structure
+    // return an enumerable containing all the layout nodes
+    public IEnumerable<ILayoutNode<ISymbolicExpressionTreeNode>> Convert(ISymbolicExpressionTreeNode root, Func<ISymbolicExpressionTreeNode, ILayoutNode<ISymbolicExpressionTreeNode>> convertFunc = null) {
+      var rootLayoutNode = convertFunc == null ? defaultConvert(root) : convertFunc(root);
+      rootLayoutNode.Ancestor = rootLayoutNode;
+
+      if (root.SubtreeCount > 0) {
+        rootLayoutNode.Children = new List<ILayoutNode<ISymbolicExpressionTreeNode>>(root.SubtreeCount);
+        Expand(rootLayoutNode, convertFunc);
+      }
+
+      var list = new List<ILayoutNode<ISymbolicExpressionTreeNode>> { rootLayoutNode };
+      int i = 0;
+      while (i < list.Count) {
+        if (list[i].Children != null)
+          foreach (ILayoutNode<ISymbolicExpressionTreeNode> child in list[i].Children)
+            list.Add(child);
+        ++i;
+      }
+      return list;
+    }
+
+    private void Expand(ILayoutNode<ISymbolicExpressionTreeNode> layoutNode, Func<ISymbolicExpressionTreeNode, ILayoutNode<ISymbolicExpressionTreeNode>> convertFunc = null) {
+      if (layoutNode.Children == null) return;
+      for (int i = 0; i < layoutNode.Content.SubtreeCount; ++i) {
+        var subtree = layoutNode.Content.GetSubtree(i);
+        var childLayoutNode = convertFunc == null ? defaultConvert(subtree) : convertFunc(subtree);
+        childLayoutNode.Parent = layoutNode;
+        childLayoutNode.Number = i;
+        childLayoutNode.Level = layoutNode.Level + 1;
+        childLayoutNode.Ancestor = childLayoutNode;
+        childLayoutNode.Children = subtree.SubtreeCount > 0 ? new List<ILayoutNode<ISymbolicExpressionTreeNode>>(subtree.SubtreeCount) : null;
+        layoutNode.Children.Add(childLayoutNode);
+        Expand(childLayoutNode, convertFunc);
+      }
+    }
+  }
+}
