Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.EvolutionTracking/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Tracking/TraceCalculator.cs @ 11968

Last change on this file since 11968 was 11968, checked in by bburlacu, 9 years ago

#1772: Small performance tweaks to the TraceCalculator. Reverted SubtreeCrossover to old behavior: do not clone subtrees (as it breaks tracing).

File size: 12.0 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.Diagnostics;
25using System.Linq;
26using HeuristicLab.Common;
27using HeuristicLab.Core;
28using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
29using HeuristicLab.EvolutionTracking;
30using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
31
32namespace HeuristicLab.Problems.DataAnalysis.Symbolic {
33  [Item("TraceCalculator", "Walks a genealogy graph and produces a trace of the specified subtree")]
34  [StorableClass]
35  public class TraceCalculator : Item {
36    private IGenealogyGraph<ISymbolicExpressionTree> traceGraph;
37    private Dictionary<IGenealogyGraphNode<ISymbolicExpressionTree>, TraceData> traceMap;
38    private Dictionary<ISymbolicExpressionTree, List<ISymbolicExpressionTreeNode>> nodeListCache;
39
40    public IGenealogyGraph<ISymbolicExpressionTree> TraceGraph { get { return traceGraph; } }
41
42    public TraceCalculator() {
43      traceGraph = new GenealogyGraph<ISymbolicExpressionTree>();
44      traceMap = new Dictionary<IGenealogyGraphNode<ISymbolicExpressionTree>, TraceData>();
45      nodeListCache = new Dictionary<ISymbolicExpressionTree, List<ISymbolicExpressionTreeNode>>();
46    }
47
48    protected TraceCalculator(TraceCalculator original, Cloner cloner)
49      : base(original, cloner) {
50    }
51
52    public override IDeepCloneable Clone(Cloner cloner) {
53      return new TraceCalculator(this, cloner);
54    }
55
56    public static IGenealogyGraph<ISymbolicExpressionTree> TraceSubtree(IGenealogyGraphNode<ISymbolicExpressionTree> node, int subtreeIndex) {
57      var tc = new TraceCalculator();
58      tc.Trace(node, subtreeIndex);
59      return tc.TraceGraph;
60    }
61
62    public IGenealogyGraph<ISymbolicExpressionTree> Trace(IGenealogyGraphNode<ISymbolicExpressionTree> node, int subtreeIndex) {
63      traceGraph = new GenealogyGraph<ISymbolicExpressionTree>();
64      traceMap = new Dictionary<IGenealogyGraphNode<ISymbolicExpressionTree>, TraceData>();
65      nodeListCache = new Dictionary<ISymbolicExpressionTree, List<ISymbolicExpressionTreeNode>>();
66      TraceRecursive(node, subtreeIndex);
67      return traceGraph;
68    }
69
70    /// <summary>
71    /// This method starts from a given vertex in the genealogy graph and works its way
72    /// up the ancestry trying to track the structure of the subtree given by subtreeIndex.
73    /// This method will skip genealogy graph nodes that did not have an influence on the
74    /// structure of the tracked subtree.
75    ///
76    /// Only genealogy nodes which did have an influence are added (as copies) to the trace
77    /// and are consequently called 'trace nodes'.
78    ///
79    /// The arcs connecting trace nodes hold information about the locations of the subtrees
80    /// and fragments that have been swapped in the form of a tuple (si, fi, lastSi, lastFi),
81    /// where:
82    /// - si is the subtree index in the current trace node
83    /// - fi is the fragment index in the current trace node
84    /// - lastSi is the subtree index in the previous trace node
85    /// - lastFi is the subtree index in the previous trace node
86    /// </summary>
87    /// <param name="node">The current node in the genealogy graph</param>
88    /// <param name="subtreeIndex">The index of the traced subtree</param>
89    /// <param name="last">The last added node in the trace graph</param>
90    private void TraceRecursive(IGenealogyGraphNode<ISymbolicExpressionTree> node, int subtreeIndex, IGenealogyGraphNode<ISymbolicExpressionTree> last = null) {
91      var g = node;
92      int si = subtreeIndex; // subtree index
93      int fi = 0; // fragment index
94      while (((List<IArc>)((IVertex)g).InArcs).Count > 0) {
95        //      while (g.Parents.Any()) {
96        Debug.Assert(si < g.Data.Length);
97        var inArcs = (List<IArc>)((IVertex)g).InArcs;
98        var fragment = (IFragment<ISymbolicExpressionTreeNode>)((IGenealogyGraphArc)inArcs.Last()).Data;
99        if (fragment == null) {
100          // TODO: think about what the correct behavior should be here (seems good so far)
101          // the node is either an elite node or (in rare cases) no fragment was transferred
102          g = (IGenealogyGraphNode<ISymbolicExpressionTree>)inArcs[0].Source;
103          continue;
104        }
105
106        fi = fragment.Index1;               // fragment index
107        int fl = fragment.Root.GetLength();     // fragment length
108        int sl = NodeAt(g.Data, si).GetLength(); // subtree length
109
110        #region trace crossover
111        if (inArcs.Count == 2) {
112          var parent0 = (IGenealogyGraphNode<ISymbolicExpressionTree>)inArcs[0].Source;
113          var parent1 = (IGenealogyGraphNode<ISymbolicExpressionTree>)inArcs[1].Source;
114          if (fi == si) {
115            g = parent1;
116            si = fragment.Index2;
117            continue;
118          }
119          if (fi < si) {
120            if (fi + fl > si) {
121              // fragment contains subtree
122              g = parent1;
123              si += fragment.Index2 - fi;
124            } else {
125              // fragment distinct from subtree
126              g = parent0;
127              si += NodeAt(g.Data, fi).GetLength() - fl;
128            }
129            continue;
130          }
131          if (fi > si) {
132            if (fi < si + sl) {
133              // subtree contains fragment => branching point in the fragment graph
134              var n = AddTraceNode(g, si, fi); // current node becomes "last" as we restart tracing from the parent
135              TraceRecursive(parent0, si, n);
136              TraceRecursive(parent1, fragment.Index2, n);
137              break;
138            } else {
139              // subtree and fragment are distinct.
140              g = parent0;
141              continue;
142            }
143          }
144        }
145        #endregion
146        #region trace mutation
147        // mutation is handled in a simple way: we branch every time there is an overlap between the subtree and the fragment
148        // (since mutation effects can be quite unpredictable: replace branch, change node, shake tree, etc)
149        if (inArcs.Count == 1) {
150          var parent0 = (IGenealogyGraphNode<ISymbolicExpressionTree>)inArcs[0].Source;
151          Debug.Assert(fragment.Index1 == fragment.Index2);
152          // check if the subtree and the fragment overlap => branch out
153          if ((si == fi) || (si < fi && fi < si + sl) || (fi < si && si < fi + fl)) {
154            var n = AddTraceNode(g, si, fi); // current node becomes "last" as we restart tracing from the parent
155            int i = si < fi ? si : fi;
156            TraceRecursive(parent0, i, n);
157            break;
158          } else {
159            // if they don't overlap, go up
160            g = parent0;
161            if (fi < si)
162              si += NodeAt(g.Data, fi).GetLength() - fl;
163            continue;
164          }
165        }
166        #endregion
167        throw new InvalidOperationException("A node cannot have more than two parents");
168      }
169      // when we are out of the while the last vertex must be connected with the current one
170      // if there is no last vertex, it means the tracing reached the top of the genealogy graph
171      var current = AddTraceNode(g, si, fi);
172      if (last != null)
173        ConnectLast(current, last, si, fi);
174    }
175
176    /// <summary>
177    /// Get the trace node from the trace graph which corresponds to node g from the genealogy graph.
178    /// If the trace graph does not contain such a node, one is created by performing a shallow copy of g, then inserted into the trace graph.
179    /// </summary>
180    /// <param name="g">The genealogy graph node</param>
181    /// <param name="si">The subtree index</param>
182    /// <param name="fi">The fragment index</param>
183    /// <returns></returns>
184    private IGenealogyGraphNode<ISymbolicExpressionTree> AddTraceNode(IGenealogyGraphNode<ISymbolicExpressionTree> g, int si, int fi) {
185      var n = traceGraph.GetByContent(g.Data);
186      if (n == null) {
187        n = g.Copy();
188        traceGraph.AddVertex(n);
189        Debug.Assert(!traceMap.ContainsKey(n));
190        traceMap[n] = new TraceData(si, fi, -1, -1); // only the first two fields are needed
191      }
192      return n;
193    }
194
195    // caching node lists brings ~2.5-2.7x speed improvement (since graph nodes are visited multiple times)
196    // this caching will be even more effective with larger tree sizes
197    private ISymbolicExpressionTreeNode NodeAt(ISymbolicExpressionTree tree, int index) {
198      List<ISymbolicExpressionTreeNode> list;
199      nodeListCache.TryGetValue(tree, out list);
200      if (list == null) {
201        list = tree.IterateNodesPrefix().ToList();
202        nodeListCache[tree] = list;
203      }
204      return list[index];
205    }
206
207    /// <summary>
208    /// Connect the current node of the trace graph with the node that was previously added (@last). The current node of the trace graph is determined by the content
209    /// of the genealogy graph node @g. 
210    /// </summary>
211    /// <param name="current">The current node in the genealogy graph</param>
212    /// <param name="last">The last added node in the trace graph</param>   
213    /// <param name="si">The index of the traced subtree</param>
214    /// <param name="fi">The index of the fragment</param>
215    private void ConnectLast(IGenealogyGraphNode<ISymbolicExpressionTree> current, IGenealogyGraphNode<ISymbolicExpressionTree> last, int si, int fi) {
216      var lastTraceData = traceMap[last];
217      int lastSi = lastTraceData.SubtreeIndex; // last subtree index (index of the traced subtree in the previous trace node)
218      int lastFi = lastTraceData.FragmentIndex; // last fragment index (index of the fragment in the previous trace node)
219      var td = new TraceData(si, fi, lastSi, lastFi); // trace data
220      //var arc = current.OutArcs.SingleOrDefault(a => a.Target == last && a.Data.Equals(td));
221      var outArcs = (List<IArc>)((IVertex)current).OutArcs;
222      var arc = outArcs.FirstOrDefault(a => a.Target == last && ((IArc<IDeepCloneable>)a).Data.Equals(td));
223      if (arc == null) {
224        arc = new GenealogyGraphArc(current, last) { Data = td };
225        traceGraph.AddArc(arc);
226      }
227    }
228  }
229  // this class is here to help clarify the semantics
230  public class TraceData : Tuple<int, int, int, int>, IDeepCloneable {
231    public TraceData(int currentSubtreeIndex, int currentFragmentIndex, int lastSubtreeIndex, int lastFragmentIndex)
232      : base(currentSubtreeIndex, currentFragmentIndex, lastSubtreeIndex, lastFragmentIndex) {
233    }
234
235    public int SubtreeIndex { get { return Item1; } }
236    public int FragmentIndex { get { return Item2; } }
237    public int LastSubtreeIndex { get { return Item3; } }
238    public int LastFragmentIndex { get { return Item4; } }
239    public object Clone() {
240      return new TraceData(SubtreeIndex, FragmentIndex, LastSubtreeIndex, LastFragmentIndex);
241    }
242
243    public IDeepCloneable Clone(Cloner cloner) {
244      return cloner.Clone(this);
245    }
246  }
247
248  internal static class Util {
249    // shallow node copy (does not clone the data or the arcs)
250    #region some helper methods for shortening the tracing code
251    public static IGenealogyGraphNode<ISymbolicExpressionTree> Copy(this IGenealogyGraphNode<ISymbolicExpressionTree> node) {
252      return new GenealogyGraphNode<ISymbolicExpressionTree>(node.Data) { Rank = node.Rank, Quality = node.Quality };
253    }
254    #endregion
255  }
256}
Note: See TracBrowser for help on using the repository browser.