Free cookie consent management tool by TermsFeed Policy Generator

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

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

#1772: Improved TraceCalculator performance by caching node lists (2.5-3x speed increase). Removed old tracing code. Insignificant change to the SymbolicDataAnalysisExpressionBeforeManipulatorOperator (rephrased a comment).

File size: 10.9 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>, Tuple<int, int>> 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>, Tuple<int, int>>();
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> PartialTrace(IGenealogyGraphNode<ISymbolicExpressionTree> node,
63      int subtreeIndex, ISymbolicExpressionTreeNode subtree) {
64      traceGraph = new GenealogyGraph<ISymbolicExpressionTree>();
65      traceMap = new Dictionary<IGenealogyGraphNode<ISymbolicExpressionTree>, Tuple<int, int>>();
66      return null;
67    }
68
69    public IGenealogyGraph<ISymbolicExpressionTree> Trace(IGenealogyGraphNode<ISymbolicExpressionTree> node, int subtreeIndex) {
70      traceGraph = new GenealogyGraph<ISymbolicExpressionTree>();
71      traceMap = new Dictionary<IGenealogyGraphNode<ISymbolicExpressionTree>, Tuple<int, int>>();
72      nodeListCache = new Dictionary<ISymbolicExpressionTree, List<ISymbolicExpressionTreeNode>>();
73      TraceRecursive(node, subtreeIndex);
74      return traceGraph;
75    }
76
77    /// <summary>
78    /// This method starts from a given vertex in the genealogy graph and works its way
79    /// up the ancestry trying to track the structure of the subtree given by subtreeIndex.
80    /// This method will skip genealogy graph nodes that did not have an influence on the
81    /// structure of the tracked subtree.
82    ///
83    /// Only genealogy nodes which did have an influence are added (as copies) to the trace
84    /// and are consequently called 'trace nodes'.
85    ///
86    /// The arcs connecting trace nodes hold information about the locations of the subtrees
87    /// and fragments that have been swapped in the form of a tuple (si, fi, lastSi, lastFi),
88    /// where:
89    /// - si is the subtree index in the current trace node
90    /// - fi is the fragment index in the current trace node
91    /// - lastSi is the subtree index in the previous trace node
92    /// - lastFi is the subtree index in the previous trace node
93    /// </summary>
94    /// <param name="node">The current node in the genealogy graph</param>
95    /// <param name="subtreeIndex">The index of the traced subtree</param>
96    /// <param name="last">The last added node in the trace graph</param>
97    private void TraceRecursive(IGenealogyGraphNode<ISymbolicExpressionTree> node, int subtreeIndex, IGenealogyGraphNode<ISymbolicExpressionTree> last = null) {
98      var g = node;
99      int si = subtreeIndex;
100      while (g.Parents.Any()) {
101        Debug.Assert(si < g.Data.Length);
102        var parents = g.Parents.ToList();
103        var fragment = (IFragment<ISymbolicExpressionTreeNode>)g.InArcs.Last().Data;
104        if (fragment == null) {
105          // TODO: think about what the correct behavior should be here (seems good so far)
106          // the node is either an elite node or (in rare cases) no fragment was transferred
107          g = parents[0];
108          continue;
109        }
110
111        int fi = fragment.Index1;               // fragment index
112        int fl = fragment.Root.GetLength();     // fragment length
113        int sl = NodeAt(g.Data, si).GetLength(); // subtree length
114
115        #region trace crossover
116        if (parents.Count == 2) {
117          if (fi == si) {
118            g = parents[1];
119            si = fragment.Index2;
120            continue;
121          }
122          if (fi < si) {
123            if (fi + fl > si) {
124              // fragment contains subtree
125              g = parents[1];
126              si += fragment.Index2 - fi;
127            } else {
128              // fragment distinct from subtree
129              g = parents[0];
130              si += NodeAt(g.Data, fi).GetLength() - fl;
131            }
132            continue;
133          }
134          if (fi > si) {
135            if (fi < si + sl) {
136              // subtree contains fragment => branching point in the fragment graph
137              var n = GetTraceNode(g, si, fi);
138              TraceRecursive(parents[0], si, n);
139              TraceRecursive(parents[1], fragment.Index2, n);
140              break;
141            } else {
142              // subtree and fragment are distinct.
143              g = parents[0];
144              continue;
145            }
146          }
147        }
148        #endregion
149        #region trace mutation
150        // mutation is handled in a simple way: we branch every time there is an overlap between the subtree and the fragment
151        // (since mutation effects can be quite unpredictable: replace branch, change node, shake tree, etc)
152        if (parents.Count == 1) {
153          Debug.Assert(fragment.Index1 == fragment.Index2);
154          // check if the subtree and the fragment overlap => branch out
155          if ((si == fi) || (si < fi && fi < si + sl) || (fi < si && si < fi + fl)) {
156            var n = GetTraceNode(g, si, fi);
157            int i = si < fi ? si : fi;
158            TraceRecursive(parents[0], i, n);
159            break;
160          } else {
161            // if they don't overlap, go up
162            g = parents[0];
163            if (fi < si)
164              si += NodeAt(g.Data, fi).GetLength() - fl;
165            continue;
166          }
167        }
168        #endregion
169        throw new InvalidOperationException("A node cannot have more than two parents");
170      }
171      // when we are out of the while the last vertex must be connected with the current one
172      ConnectLast(g, si, last);
173    }
174
175    /// <summary>
176    /// Get the trace node from the trace graph which corresponds to node g from the genealogy graph.
177    /// 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.
178    /// </summary>
179    /// <param name="g">The genealogy graph node</param>
180    /// <param name="si">The subtree index</param>
181    /// <param name="fi">The fragment index</param>
182    /// <returns></returns>
183    private IGenealogyGraphNode<ISymbolicExpressionTree> GetTraceNode(IGenealogyGraphNode<ISymbolicExpressionTree> g, int si, int fi) {
184      var n = traceGraph.GetByContent(g.Data);
185      if (n == null) {
186        n = g.Copy();
187        traceGraph.AddVertex(n);
188        Debug.Assert(!traceMap.ContainsKey(n));
189        traceMap[n] = new Tuple<int, int>(si, fi);
190      }
191      return n;
192    }
193
194    // caching node lists brings ~2.5-2.7x speed improvement (since graph nodes are visited multiple times)
195    // this caching will be even more effective with larger tree sizes
196    private ISymbolicExpressionTreeNode NodeAt(ISymbolicExpressionTree tree, int index) {
197      List<ISymbolicExpressionTreeNode> list;
198      nodeListCache.TryGetValue(tree, out list);
199      if (list == null) {
200        list = tree.IterateNodesPrefix().ToList();
201        nodeListCache[tree] = list;
202      }
203      return list[index];
204    }
205
206    /// <summary>
207    /// 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
208    /// of the genealogy graph node @g. 
209    /// </summary>
210    /// <param name="g">The current node in the genealogy graph</param>
211    /// <param name="si">The index of the traced subtree</param>
212    /// <param name="last">The last added node in the trace graph</param>
213    private void ConnectLast(IGenealogyGraphNode<ISymbolicExpressionTree> g, int si, IGenealogyGraphNode<ISymbolicExpressionTree> last) {
214      IFragment<ISymbolicExpressionTreeNode> fragment = g.Parents.Any() ? (IFragment<ISymbolicExpressionTreeNode>)g.InArcs.Last().Data : null;
215      int fi = fragment == null ? 0 : fragment.Index1; // fragment index
216      var n = GetTraceNode(g, si, fi); // will append n to the trace graph if it does not exist
217      if (last == null)
218        return;
219      var lastTraceData = traceMap[last];
220      int lastSi = lastTraceData.Item1; // last subtree index (index of the traced subtree in the parent)
221      int lastFi = lastTraceData.Item2; // last fragment index (index of the fragment in the parent)
222      var td = new Tuple<int, int, int, int>(si, fi, lastSi, lastFi); // trace data
223      var arc = n.InArcs.SingleOrDefault(a => a.Source == last && a.Data.Equals(td));
224      if (arc == null) {
225        arc = new GenealogyGraphArc(last, n) { Data = td };
226        traceGraph.AddArc(arc);
227      }
228    }
229  }
230
231  internal static class Util {
232    // shallow node copy (does not clone the data or the arcs)
233    #region some helper methods for shortening the tracing code
234    public static IGenealogyGraphNode<ISymbolicExpressionTree> Copy(this IGenealogyGraphNode<ISymbolicExpressionTree> node) {
235      return new GenealogyGraphNode<ISymbolicExpressionTree>(node.Data) { Rank = node.Rank, Quality = node.Quality };
236    }
237    #endregion
238  }
239}
Note: See TracBrowser for help on using the repository browser.