Free cookie consent management tool by TermsFeed Policy Generator

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

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

#1772: Small fix to fragment tracing.

File size: 7.6 KB
RevLine 
[10884]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
[10755]22using System;
[10752]23using System.Collections.Generic;
24using System.IO;
25using System.Linq;
[11253]26using HeuristicLab.Core;
[10752]27using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
28using HeuristicLab.EvolutionTracking;
29
[10827]30namespace HeuristicLab.Problems.DataAnalysis.Symbolic {
[10752]31  public static class SymbolicDataAnalysisExpressionTracing {
[10888]32    public static FragmentGraph TraceSubtree(IGenealogyGraphNode<ISymbolicExpressionTree> graphNode, int subtreeIndex) {
[11233]33      var graph = new FragmentGraph();
[11318]34      var vertices = Trace(graphNode, subtreeIndex).ToList();
35      graph.AddVertices(vertices);
[10752]36      return graph;
37    }
[10888]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) {
[10752]46      var node = graphNode; // current node
47      var index = subtreeIndex; // current index
48      var parent = parentNode; // current parent
[10755]49
[10752]50      while (true) {
[10755]51        if (!node.Parents.Any()) {
[11318]52          // no tracing if there are no parents, return a fragment node representing the current trace
53          var fragmentNode = new FragmentNode(node) { SubtreeIndex = index };
[10755]54          if (parent != null) {
[10888]55            var arc = new Arc(parent, fragmentNode);
[11233]56            parent.AddArc(arc);
57            fragmentNode.AddArc(arc);
[10755]58          }
[11318]59          yield return fragmentNode;
[10755]60          break;
[10752]61        }
[10827]62        var parents = node.Parents.ToList();
[11350]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
[10827]68          node = parents[0];
[10752]69          continue;
[10827]70        }
[11318]71
[10827]72        var fragmentLength = fragment.Root.GetLength();
[11253]73        var tree = node.Data;
[10755]74        var subtree = tree.NodeAt(index);
75        var subtreeLength = subtree.GetLength();
76
[10888]77        #region mutation tracing
[10827]78        if (parents.Count == 1) {
79          // we are tracing a mutation operation
[11233]80          var fragmentNode = new FragmentNode(node) {
[10888]81            SubtreeIndex = index,
82            FragmentIndex = fragment.Index1
[10827]83          };
84          if (parent != null) {
[10888]85            var arc = new Arc(parent, fragmentNode);
[11233]86            parent.AddArc(arc);
87            fragmentNode.AddArc(arc);
[10827]88          }
[10888]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 {
[11253]96              index += node.Data.NodeAt(fragment.Index1).GetLength() - fragmentLength;
[10888]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
[10827]107          yield return fragmentNode;
[10888]108          var up = Trace(node, index, fragmentNode);
[10827]109          foreach (var v in up) { yield return v; }
110          break;
111        }
[10888]112        #endregion
[10755]113
[10888]114        #region crossover tracing
[10827]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;
[10752]121          }
[10827]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
[11253]130              index += node.Data.NodeAt(fragment.Index1).GetLength() - fragmentLength; // subtreeIndex must be adjusted according to swapped fragments sizes
[10755]131            }
[10827]132            continue;
133          }
[10755]134
[10827]135          if (fragment.Index1 > index) {
136            if (fragment.Index1 < index + subtreeLength) {
[11318]137              // subtree contains fragment => branching point in the fragment graph
[11233]138              var fragmentNode = new FragmentNode(node) {
[10888]139                SubtreeIndex = index,
140                FragmentIndex = fragment.Index1
[10827]141              };
142              if (parent != null) {
[10888]143                var arc = new Arc(parent, fragmentNode);
[11233]144                parent.AddArc(arc);
145                fragmentNode.AddArc(arc);
[10827]146              }
147              yield return fragmentNode;
[10755]148
[11253]149              if (parents[1].Data.NodeAt(fragment.Index2).GetLength() != fragmentLength) {
[10827]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
[10755]159            }
[10752]160          }
161        }
[10888]162        #endregion
[10752]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.