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

Last change on this file since 11638 was 11638, checked in by bburlacu, 5 years ago

#1772: Merged trunk changes. Updated PhenotypicSimilarityCalculator, updated FragmentGraphView.

File size: 9.7 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 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
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
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>
87    private void Trace(IGenealogyGraphNode<ISymbolicExpressionTree> g, int si, IGenealogyGraphNode<ISymbolicExpressionTree> last = null) {
88      while (g.Parents.Any()) {
89        var parents = g.Parents.ToList();
90        var fragment = (IFragment<ISymbolicExpressionTreeNode>)g.InArcs.Last().Data;
91        if (fragment == null) {
92          //          if (parents.Count == 2)
93          //            throw new Exception("There should always be a crossover fragment.");
94          // the node is either an elite node or (in rare cases) no fragment was transferred
95          g = parents[0];
96          continue;
97        }
98
99        int fi = fragment.Index1;               // fragment index
100        int fl = fragment.Root.GetLength();     // fragment length
101        int sl = g.Data.NodeAt(si).GetLength(); // subtree length
102
103        #region trace crossover
104        if (parents.Count == 2) {
105          if (fi == si) {
106            g = parents[1];
107            si = fragment.Index2;
108            continue;
109          }
110          if (fi < si) {
111            if (fi + fl > si) {
112              // fragment contains subtree
113              g = parents[1];
114              si += fragment.Index2 - fi;
115            } else {
116              // fragment distinct from subtree
117              g = parents[0];
118              si += g.Data.NodeAt(fi).GetLength() - fl;
119            }
120            continue;
121          }
122          if (fi > si) {
123            if (fi < si + sl) {
124              // subtree contains fragment => branching point in the fragment graph
125              var n = GetTraceNode(g, si, fi);
126              Trace(parents[0], si, n);
127              Trace(parents[1], fragment.Index2, n);
128              break;
129            } else {
130              // subtree and fragment are distinct.
131              g = parents[0];
132              continue;
133            }
134          }
135        }
136        #endregion
137        #region trace mutation
138        // mutation is handled in a simple way: we branch every time there is an overlap between the subtree and the fragment
139        // (since mutation effects can be quite unpredictable: replace branch, change node, shake tree, etc)
140        if (parents.Count == 1) {
141          Debug.Assert(fragment.Index1 == fragment.Index2);
142          // check if the subtree and the fragment overlap => branch out
143          if ((si == fi) || (si < fi && fi < si + sl) || (fi < si && si < fi + fl)) {
144            var n = GetTraceNode(g, si, fi);
145            int i = si < fi ? si : fi;
146            Trace(parents[0], i, n);
147            break;
148          } else {
149            // if they don't overlap, go up
150            g = parents[0];
151            if (fi < si)
152              si += g.Data.NodeAt(fi).GetLength() - fl;
153            continue;
154          }
155        }
156        #endregion
157        throw new InvalidOperationException("A node cannot have more than two parents");
158      }
159      // when we are out of the while the last vertex must be connected with the current one
160      ConnectLast(g, si, last);
161    }
162
163    /// <summary>
164    /// Get the trace node from the trace graph which corresponds to node g from the genealogy graph.
165    /// 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.
166    /// </summary>
167    /// <param name="g">The genealogy graph node</param>
168    /// <param name="si">The subtree index</param>
169    /// <param name="fi">The fragment index</param>
170    /// <returns></returns>
171    private IGenealogyGraphNode<ISymbolicExpressionTree> GetTraceNode(IGenealogyGraphNode<ISymbolicExpressionTree> g, int si, int fi) {
172      var n = traceGraph.GetByContent(g.Data);
173      if (n == null) {
174        n = g.Copy();
175        traceGraph.AddVertex(n);
176        Debug.Assert(!traceMap.ContainsKey(n));
177        traceMap[n] = new Tuple<int, int>(si, fi);
178      }
179      return n;
180    }
181
182    /// <summary>
183    /// 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
184    /// of the genealogy graph node @g. 
185    /// </summary>
186    /// <param name="g">The current node in the genealogy graph</param>
187    /// <param name="si">The index of the traced subtree</param>
188    /// <param name="last">The last added node in the trace graph</param>
189    private void ConnectLast(IGenealogyGraphNode<ISymbolicExpressionTree> g, int si, IGenealogyGraphNode<ISymbolicExpressionTree> last) {
190      IFragment<ISymbolicExpressionTreeNode> fragment = g.Parents.Any() ? (IFragment<ISymbolicExpressionTreeNode>)g.InArcs.Last().Data : null;
191      int fi = fragment == null ? 0 : fragment.Index1; // fragment index
192      var n = GetTraceNode(g, si, fi); // will append n to the trace graph if it does not exist
193      if (last == null)
194        return;
195      var lastTraceData = traceMap[last];
196      int lastSi = lastTraceData.Item1; // last subtree index
197      int lastFi = lastTraceData.Item2; // last fragment index
198      var td = new Tuple<int, int, int, int>(si, fi, lastSi, lastFi); // trace data
199      var arc = n.InArcs.SingleOrDefault(a => a.Source == last && a.Data.Equals(td));
200      if (arc == null) {
201        arc = new GenealogyGraphArc(last, n) { Data = td };
202        traceGraph.AddArc(arc);
203      }
204    }
205  }
206
207  internal static class Util {
208    // shallow node copy (does not clone the data or the arcs)
209    public static IGenealogyGraphNode<ISymbolicExpressionTree> Copy(this IGenealogyGraphNode<ISymbolicExpressionTree> node) {
210      return new GenealogyGraphNode<ISymbolicExpressionTree>(node.Data) { Rank = node.Rank, Quality = node.Quality };
211    }
212    #region some helper methods for shortening the tracing code
213    public static ISymbolicExpressionTreeNode NodeAt(this ISymbolicExpressionTree tree, int index) {
214      return NodeAt(tree.Root, index);
215    }
216    public static ISymbolicExpressionTreeNode NodeAt(this ISymbolicExpressionTreeNode root, int index) {
217      return root.IterateNodesPrefix().ElementAt(index);
218    }
219    #endregion
220  }
221}
Note: See TracBrowser for help on using the repository browser.