Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 12940 was 12287, checked in by bburlacu, 10 years ago

#1772: Added storable attributes to the before/after evolution tracking operators in HeuristicLab.Problems.DataAnalysis.Symbolic. Very small changes to the trace calculator (updated license header, removed old sample count code).

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