Free cookie consent management tool by TermsFeed Policy Generator

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

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

#1772: Improved the way the TraceCalculator handles mutations, worked on the SymbolicDataAnalysisPoly10Analyzer (analyzer that tries to identify building blocks for the Poly-10 problem by doing a semantic comparison).

File size: 9.7 KB
RevLine 
[11493]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;
[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 {
36    private readonly IGenealogyGraph<ISymbolicExpressionTree> traceGraph;
37    private readonly Dictionary<IGenealogyGraphNode<ISymbolicExpressionTree>, Tuple<int, int>> traceMap;
38
39    public IGenealogyGraph<ISymbolicExpressionTree> TraceGraph { get { return traceGraph; } }
40
41    public TraceCalculator() {
42      traceGraph = new GenealogyGraph<ISymbolicExpressionTree>();
43      traceMap = new Dictionary<IGenealogyGraphNode<ISymbolicExpressionTree>, Tuple<int, int>>();
44    }
45
46    protected TraceCalculator(TraceCalculator original, Cloner cloner)
47      : base(original, cloner) {
48    }
49
50    public override IDeepCloneable Clone(Cloner cloner) {
51      return new TraceCalculator(this, cloner);
52    }
53
54    public static IGenealogyGraph<ISymbolicExpressionTree> TraceSubtree(IGenealogyGraphNode<ISymbolicExpressionTree> node, int subtreeIndex) {
55      var tc = new TraceCalculator();
56      tc.Trace(node, subtreeIndex);
57      return tc.TraceGraph;
58    }
59
[11476]60    public IGenealogyGraph<ISymbolicExpressionTree> Trace(IGenealogyGraphNode<ISymbolicExpressionTree> node, int subtreeIndex) {
61      traceGraph.Clear();
62      traceMap.Clear();
63      Trace(node, subtreeIndex, null);
64      return traceGraph;
65    }
66
[11473]67    /// <summary>
68    /// This method starts from a given vertex in the genealogy graph and works its way
69    /// up the ancestry trying to track the structure of the subtree given by subtreeIndex.
70    /// This method will skip genealogy graph nodes that did not have an influence on the
71    /// structure of the tracked subtree.
72    ///
73    /// Only genealogy nodes which did have an influence are added (as copies) to the trace
74    /// and are consequently called 'trace nodes'.
75    ///
76    /// The arcs connecting trace nodes hold information about the locations of the subtrees
77    /// and fragments that have been swapped in the form of a tuple (si, fi, lastSi, lastFi),
78    /// where:
79    /// - si is the subtree index in the current trace node
80    /// - fi is the fragment index in the current trace node
81    /// - lastSi is the subtree index in the previous trace node
82    /// - lastFi is the subtree index in the previous trace node
83    /// </summary>
84    /// <param name="g">The current node in the genealogy graph</param>
85    /// <param name="si">The index of the traced subtree</param>
86    /// <param name="last">The last added node in the trace graph</param>
[11476]87    private void Trace(IGenealogyGraphNode<ISymbolicExpressionTree> g, int si, IGenealogyGraphNode<ISymbolicExpressionTree> last = null) {
[11473]88      while (g.Parents.Any()) {
89        var parents = g.Parents.ToList();
90        var fragment = (IFragment<ISymbolicExpressionTreeNode>)g.InArcs.Last().Data;
[11458]91        if (fragment == null) {
92          // the node is either an elite node or (in rare cases) no fragment was transferred
[11473]93          g = parents[0];
[11458]94          continue;
95        }
96
[11493]97        int fi = fragment.Index1;               // fragment index
98        int fl = fragment.Root.GetLength();     // fragment length
99        int sl = g.Data.NodeAt(si).GetLength(); // subtree length
[11458]100
101        #region trace crossover
102        if (parents.Count == 2) {
[11493]103          if (fi == si) {
[11473]104            g = parents[1];
105            si = fragment.Index2;
[11458]106            continue;
107          }
[11493]108          if (fi < si) {
109            if (fi + fl > si) {
[11458]110              // fragment contains subtree
[11473]111              g = parents[1];
[11493]112              si += fragment.Index2 - fi;
[11458]113            } else {
114              // fragment distinct from subtree
[11473]115              g = parents[0];
[11493]116              si += g.Data.NodeAt(fi).GetLength() - fl;
[11458]117            }
118            continue;
119          }
[11493]120          if (fi > si) {
121            if (fi < si + sl) {
[11458]122              // subtree contains fragment => branching point in the fragment graph
[11493]123              var n = GetTraceNode(g, si, fi);
[11473]124              Trace(parents[0], si, n);
125              Trace(parents[1], fragment.Index2, n);
[11458]126              break;
127            } else {
128              // subtree and fragment are distinct.
[11473]129              g = parents[0];
[11458]130              continue;
131            }
132          }
133        }
134        #endregion
135        #region trace mutation
[11493]136        // mutation is handled in a simple way: we branch every time there is an overlap between the subtree and the fragment
137        // (since mutation effects can be quite unpredictable: replace branch, change node, shake tree, etc)
[11458]138        if (parents.Count == 1) {
[11493]139          Debug.Assert(fragment.Index1 == fragment.Index2);
140          // check if the subtree and the fragment overlap => branch out
141          if ((si == fi) || (si < fi && fi < si + sl) || (fi < si && si < fi + fl)) {
142            var n = GetTraceNode(g, si, fi);
143            int i = si < fi ? si : fi;
144            Trace(parents[0], i, n);
[11473]145            break;
[11493]146          } else {
147            // if they don't overlap, go up
148            g = parents[0];
149            if (fi < si)
150              si += g.Data.NodeAt(fi).GetLength() - fl;
[11473]151            continue;
[11458]152          }
[11473]153        }
[11458]154        #endregion
[11473]155        throw new InvalidOperationException("A node cannot have more than two parents");
[11458]156      }
[11473]157      // when we are out of the while the last vertex must be connected with the current one
158      ConnectLast(g, si, last);
[11458]159    }
[11473]160
161    /// <summary>
[11493]162    /// Get the trace node from the trace graph which corresponds to node g from the genealogy graph.
163    /// 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.
164    /// </summary>
165    /// <param name="g">The genealogy graph node</param>
166    /// <param name="si">The subtree index</param>
167    /// <param name="fi">The fragment index</param>
168    /// <returns></returns>
169    private IGenealogyGraphNode<ISymbolicExpressionTree> GetTraceNode(IGenealogyGraphNode<ISymbolicExpressionTree> g, int si, int fi) {
170      var n = traceGraph.GetByContent(g.Data);
171      if (n == null) {
172        n = g.Copy();
173        traceGraph.AddVertex(n);
174        Debug.Assert(!traceMap.ContainsKey(n));
175        traceMap[n] = new Tuple<int, int>(si, fi);
176      }
177      return n;
178    }
179
180    /// <summary>
[11473]181    /// 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
182    /// of the genealogy graph node @g. 
183    /// </summary>
184    /// <param name="g">The current node in the genealogy graph</param>
185    /// <param name="si">The index of the traced subtree</param>
186    /// <param name="last">The last added node in the trace graph</param>
187    private void ConnectLast(IGenealogyGraphNode<ISymbolicExpressionTree> g, int si, IGenealogyGraphNode<ISymbolicExpressionTree> last) {
188      IFragment<ISymbolicExpressionTreeNode> fragment = g.Parents.Any() ? (IFragment<ISymbolicExpressionTreeNode>)g.InArcs.Last().Data : null;
189      var n = traceGraph.GetByContent(g.Data);
190      if (n == null) {
191        n = g.Copy();
192        traceGraph.AddVertex(n);
193      }
194      int fi = fragment == null ? 0 : fragment.Index1; // fragment index
195      traceMap[n] = new Tuple<int, int>(si, fi);
196      if (last == null)
197        return;
198      var lastTraceData = traceMap[last];
199      int lastSi = lastTraceData.Item1; // last subtree index
200      int lastFi = lastTraceData.Item2; // last fragment index
201      var td = new Tuple<int, int, int, int>(si, fi, lastSi, lastFi); // trace data
202      var arc = n.InArcs.SingleOrDefault(a => a.Source == last && a.Data.Equals(td));
203      if (arc != null)
204        return;
[11476]205      arc = new GenealogyGraphArc(last, n) { Data = td };
[11473]206      traceGraph.AddArc(arc);
207    }
[11458]208  }
209
210  internal static class Util {
[11473]211    // shallow node copy (does not clone the data or the arcs)
[11458]212    public static IGenealogyGraphNode<ISymbolicExpressionTree> Copy(this IGenealogyGraphNode<ISymbolicExpressionTree> node) {
213      return new GenealogyGraphNode<ISymbolicExpressionTree>(node.Data) { Rank = node.Rank, Quality = node.Quality };
214    }
215    #region some helper methods for shortening the tracing code
216    public static ISymbolicExpressionTreeNode NodeAt(this ISymbolicExpressionTree tree, int index) {
217      return NodeAt(tree.Root, index);
218    }
219    public static ISymbolicExpressionTreeNode NodeAt(this ISymbolicExpressionTreeNode root, int index) {
220      return root.IterateNodesPrefix().ElementAt(index);
221    }
222    #endregion
223  }
224}
Note: See TracBrowser for help on using the repository browser.