Free cookie consent management tool by TermsFeed Policy Generator

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

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

#1772: Fixed unit test errors.

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