Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.EvolutionTracking/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Tracking/SymbolicDataAnalysisExpressionTracing.cs @ 11387

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

#1772: Small fix to fragment tracing.

File size: 7.6 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.IO;
25using System.Linq;
26using HeuristicLab.Core;
27using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
28using HeuristicLab.EvolutionTracking;
29
30namespace HeuristicLab.Problems.DataAnalysis.Symbolic {
31  public static class SymbolicDataAnalysisExpressionTracing {
32    public static FragmentGraph TraceSubtree(IGenealogyGraphNode<ISymbolicExpressionTree> graphNode, int subtreeIndex) {
33      var graph = new FragmentGraph();
34      var vertices = Trace(graphNode, subtreeIndex).ToList();
35      graph.AddVertices(vertices);
36      return graph;
37    }
38    /// <summary>
39    /// Traces a subtree in a genealogy of individuals, tracking down it's genetic components
40    /// </summary>
41    /// <param name="graphNode">The point in the genealogy where to start the tracing from</param>
42    /// <param name="subtreeIndex">The traced subtree preorder index in the current tree</param>
43    /// <param name="parentNode">The parent node in the fragment graph if there is any</param>
44    /// <returns></returns>
45    private static IEnumerable<FragmentNode> Trace(IGenealogyGraphNode<ISymbolicExpressionTree> graphNode, int subtreeIndex, FragmentNode parentNode = null) {
46      var node = graphNode; // current node
47      var index = subtreeIndex; // current index
48      var parent = parentNode; // current parent
49
50      while (true) {
51        if (!node.Parents.Any()) {
52          // no tracing if there are no parents, return a fragment node representing the current trace
53          var fragmentNode = new FragmentNode(node) { SubtreeIndex = index };
54          if (parent != null) {
55            var arc = new Arc(parent, fragmentNode);
56            parent.AddArc(arc);
57            fragmentNode.AddArc(arc);
58          }
59          yield return fragmentNode;
60          break;
61        }
62        var parents = node.Parents.ToList();
63        var fragment = (IFragment<ISymbolicExpressionTreeNode>)node.InArcs.Last().Data;
64
65        if (fragment == null) {
66          // fragment == null can only mean that the individual is the previous generation elite
67          // which got introduced in the next generation. skip elite, go up the graph to original individual
68          node = parents[0];
69          continue;
70        }
71
72        var fragmentLength = fragment.Root.GetLength();
73        var tree = node.Data;
74        var subtree = tree.NodeAt(index);
75        var subtreeLength = subtree.GetLength();
76
77        #region mutation tracing
78        if (parents.Count == 1) {
79          // we are tracing a mutation operation
80          var fragmentNode = new FragmentNode(node) {
81            SubtreeIndex = index,
82            FragmentIndex = fragment.Index1
83          };
84          if (parent != null) {
85            var arc = new Arc(parent, fragmentNode);
86            parent.AddArc(arc);
87            fragmentNode.AddArc(arc);
88          }
89          node = parents[0];
90          if (subtreeIndex == fragment.Index1) {
91            // index stays the same
92          } else if (fragment.Index1 < subtreeIndex) {
93            if (subtreeIndex < fragment.Index1 + fragmentLength) {
94              // subtree contained in fragment, index stays the same
95            } else {
96              index += node.Data.NodeAt(fragment.Index1).GetLength() - fragmentLength;
97            }
98          } else if (subtreeIndex < fragment.Index1) {
99            if (fragment.Index1 < subtreeIndex + subtreeLength) {
100              // subtree contains fragment
101              index = fragment.Index1;
102            } else {
103              // index stays the same
104            }
105          }
106
107          yield return fragmentNode;
108          var up = Trace(node, index, fragmentNode);
109          foreach (var v in up) { yield return v; }
110          break;
111        }
112        #endregion
113
114        #region crossover tracing
115        if (parents.Count == 2) {
116          // we are tracing a crossover operation
117          if (fragment.Index1 == index) {
118            node = parents[1]; // take second parent which contains the fragment
119            index = fragment.Index2;
120            continue;
121          }
122
123          if (fragment.Index1 < index) {
124            if (fragment.Index1 + fragmentLength > index) {
125              node = parents[1]; // fragment contains subtree, take second parent
126              index += fragment.Index2 - fragment.Index1; // the subtree has the same index relative to the fragment
127            } else {
128              // fragment distinct from subtree
129              node = parents[0]; // take first parent which contains the subtree
130              index += node.Data.NodeAt(fragment.Index1).GetLength() - fragmentLength; // subtreeIndex must be adjusted according to swapped fragments sizes
131            }
132            continue;
133          }
134
135          if (fragment.Index1 > index) {
136            if (fragment.Index1 < index + subtreeLength) {
137              // subtree contains fragment => branching point in the fragment graph
138              var fragmentNode = new FragmentNode(node) {
139                SubtreeIndex = index,
140                FragmentIndex = fragment.Index1
141              };
142              if (parent != null) {
143                var arc = new Arc(parent, fragmentNode);
144                parent.AddArc(arc);
145                fragmentNode.AddArc(arc);
146              }
147              yield return fragmentNode;
148
149              if (parents[1].Data.NodeAt(fragment.Index2).GetLength() != fragmentLength) {
150                throw new Exception("Fragment lengths should match!");
151              }
152              // the two paths below ("left" and "right") correspond to the subtree and the fragment, respectively
153              var left = Trace(parents[0], index, fragmentNode); // trace subtree
154              var right = Trace(parents[1], fragment.Index2, fragmentNode); // trace fragment
155              foreach (var v in left.Concat(right)) { yield return v; }
156              break;
157            } else {
158              node = parents[0]; // fragment distinct from subtree: update node, index remains unchanged
159            }
160          }
161        }
162        #endregion
163      }
164    }
165
166    private static string ViewAsText(this ISymbolicExpressionTreeNode root) {
167      var writer = new StringWriter();
168      SymbolicExpressionTreeHierarchicalFormatter.RenderNode(writer, root, string.Empty);
169      return writer.ToString();
170    }
171    #region some helper methods for shortening the tracing code
172    private static ISymbolicExpressionTreeNode NodeAt(this ISymbolicExpressionTree tree, int position) {
173      return NodeAt(tree.Root, position);
174    }
175    private static ISymbolicExpressionTreeNode NodeAt(this ISymbolicExpressionTreeNode root, int position) {
176      return root.IterateNodesPrefix().ElementAt(position);
177    }
178    #endregion
179  }
180}
Note: See TracBrowser for help on using the repository browser.