Free cookie consent management tool by TermsFeed Policy Generator

Ignore:
Timestamp:
03/15/11 13:34:38 (13 years ago)
Author:
mkommend
Message:

#1418: Finally added results from the grammar refactoring.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • branches/DataAnalysis Refactoring/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/ArchitectureManipulators/SubroutineCreater.cs

    r5549 r5686  
    2727using HeuristicLab.Core;
    2828using HeuristicLab.Data;
     29using HeuristicLab.Parameters;
    2930using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
    30 using HeuristicLab.Parameters;
    3131
    3232namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding {
     
    6161    private SubroutineCreater(bool deserializing) : base(deserializing) { }
    6262    private SubroutineCreater(SubroutineCreater original, Cloner cloner) : base(original, cloner) { }
    63     public SubroutineCreater() : base() {
     63    public SubroutineCreater()
     64      : base() {
    6465      Parameters.Add(new ValueLookupParameter<IntValue>(MaximumSymbolicExpressionTreeLengthParameterName, "The maximal length (number of nodes) of the symbolic expression tree."));
    6566      Parameters.Add(new ValueLookupParameter<IntValue>(MaximumSymbolicExpressionTreeDepthParameterName, "The maximal depth of the symbolic expression tree (a tree with one node has depth = 0)."));
     
    109110
    110111      // select a random cut point in the selected branch
    111       var allCutPoints = from parent in selectedBody.IterateNodesPrefix()
    112                          from subtree in parent.SubTrees
    113                          select new { Parent = parent, ReplacedBranchIndex = parent.IndexOfSubTree(subtree), ReplacedBranch = subtree };
     112      var allCutPoints = (from parent in selectedBody.IterateNodesPrefix()
     113                          from subtree in parent.SubTrees
     114                          select new CutPoint(parent, subtree)).ToList();
    114115      if (allCutPoints.Count() == 0)
    115116        // no cut points => abort
     
    118119      var selectedCutPoint = allCutPoints.SelectRandom(random);
    119120      // select random branches as argument cut-off points (replaced by argument terminal nodes in the function)
    120       List<ISymbolicExpressionTreeNode> argumentBranches = SelectRandomArgumentBranches(selectedCutPoint.ReplacedBranch, random, ARGUMENT_CUTOFF_PROBABILITY, maxFunctionArguments);
    121       ISymbolicExpressionTreeNode functionBody = selectedCutPoint.ReplacedBranch;
     121      List<CutPoint> argumentCutPoints = SelectRandomArgumentBranches(selectedCutPoint.Child, random, ARGUMENT_CUTOFF_PROBABILITY, maxFunctionArguments);
     122      ISymbolicExpressionTreeNode functionBody = selectedCutPoint.Child;
    122123      // disconnect the function body from the tree
    123       selectedCutPoint.Parent.RemoveSubTree(selectedCutPoint.ReplacedBranchIndex);
     124      selectedCutPoint.Parent.RemoveSubTree(selectedCutPoint.ChildIndex);
    124125      // disconnect the argument branches from the function
    125       functionBody = DisconnectBranches(functionBody, argumentBranches);
     126      functionBody = DisconnectBranches(functionBody, argumentCutPoints);
    126127      // insert a function invocation symbol instead
    127128      var invokeNode = (InvokeFunctionTreeNode)(new InvokeFunction(newFunctionName)).CreateTreeNode();
    128       selectedCutPoint.Parent.InsertSubTree(selectedCutPoint.ReplacedBranchIndex, invokeNode);
     129      selectedCutPoint.Parent.InsertSubTree(selectedCutPoint.ChildIndex, invokeNode);
    129130      // add the branches selected as argument as subtrees of the function invocation node
    130       foreach (var argumentBranch in argumentBranches)
    131         invokeNode.AddSubTree(argumentBranch);
     131      foreach (var argumentCutPoint in argumentCutPoints)
     132        invokeNode.AddSubTree(argumentCutPoint.Child);
    132133
    133134      // insert a new function defining branch
     
    138139      // the grammar in the newly defined function is a clone of the grammar of the originating branch
    139140      defunNode.SetGrammar((ISymbolicExpressionTreeGrammar)selectedBody.Grammar.Clone());
    140       // remove all argument symbols from grammar
    141       var oldArgumentSymbols = defunNode.Grammar.Symbols.OfType<Argument>().ToList();
     141      // remove all argument symbols from grammar except that one contained in cutpoints
     142      var oldArgumentSymbols = selectedBody.Grammar.Symbols.OfType<Argument>().ToList();
    142143      foreach (var oldArgSymb in oldArgumentSymbols)
    143144        defunNode.Grammar.RemoveSymbol(oldArgSymb);
     
    146147                                select node.Symbol.ArgumentIndex).Distinct();
    147148      // add argument symbols to grammar of function defining branch
    148       GrammarModifier.AddDynamicArguments(defunNode.Grammar, defunNode.Symbol, newArgumentIndexes);
     149      GrammarModifier.AddArgumentSymbol(selectedBody.Grammar, defunNode.Grammar, newArgumentIndexes, argumentCutPoints);
    149150      defunNode.NumberOfArguments = newArgumentIndexes.Count();
    150       if (defunNode.NumberOfArguments != argumentBranches.Count) throw new InvalidOperationException();
     151      if (defunNode.NumberOfArguments != argumentCutPoints.Count) throw new InvalidOperationException();
    151152      // add invoke symbol for newly defined function to the original branch
    152       var allowedParents = from symb in selectedBody.Grammar.Symbols
    153                            where !(symb is ProgramRootSymbol)
    154                            select symb;
    155       var allowedChildren = from symb in selectedBody.Grammar.Symbols
    156                             where selectedBody.Grammar.IsAllowedChild(selectedBody.Symbol, symb, 0)
    157                             select symb;
    158       GrammarModifier.AddDynamicSymbol(selectedBody.Grammar, selectedBody.Symbol, defunNode.FunctionName, defunNode.NumberOfArguments);
     153      GrammarModifier.AddInvokeSymbol(selectedBody.Grammar, defunNode.FunctionName, defunNode.NumberOfArguments, selectedCutPoint, argumentCutPoints);
    159154
    160155      // when the new function body was taken from another function definition
     
    168163          // when the original branch can be invoked from the subtree then also allow invocation of the function
    169164          if (originalBranchInvokeSymbol != null) {
    170             allowedParents = from symb in subtree.Grammar.Symbols
    171                              where !(symb is ProgramRootSymbol)
    172                              select symb;
    173             allowedChildren = from symb in subtree.Grammar.Symbols
    174                               where subtree.Grammar.IsAllowedChild(subtree.Symbol, symb, 0)
    175                               select symb;
    176             GrammarModifier.AddDynamicSymbol(subtree.Grammar, subtree.Symbol, defunNode.FunctionName, defunNode.NumberOfArguments);
     165            GrammarModifier.AddInvokeSymbol(subtree.Grammar, defunNode.FunctionName, defunNode.NumberOfArguments, selectedCutPoint, argumentCutPoints);
    177166          }
    178167        }
     
    181170    }
    182171
    183     private static ISymbolicExpressionTreeNode DisconnectBranches(ISymbolicExpressionTreeNode node, List<ISymbolicExpressionTreeNode> argumentBranches) {
    184       if (argumentBranches.Contains(node)) {
    185         var argumentIndex = argumentBranches.IndexOf(node);
     172    private static ISymbolicExpressionTreeNode DisconnectBranches(ISymbolicExpressionTreeNode node, List<CutPoint> argumentCutPoints) {
     173      int argumentIndex = argumentCutPoints.FindIndex(x => x.Child == node);
     174      if (argumentIndex != -1) {
    186175        var argSymbol = new Argument(argumentIndex);
    187176        return argSymbol.CreateTreeNode();
     
    192181      // recursively apply function for subtrees or append a argument terminal node
    193182      foreach (var subtree in subtrees) {
    194         node.AddSubTree(DisconnectBranches(subtree, argumentBranches));
     183        node.AddSubTree(DisconnectBranches(subtree, argumentCutPoints));
    195184      }
    196185      return node;
    197186    }
    198187
    199     private static List<ISymbolicExpressionTreeNode> SelectRandomArgumentBranches(ISymbolicExpressionTreeNode selectedRoot,
     188    private static List<CutPoint> SelectRandomArgumentBranches(ISymbolicExpressionTreeNode selectedRoot,
    200189      IRandom random,
    201190      double cutProbability,
     
    203192      // breadth first determination of argument cut-off points
    204193      // we must make sure that we cut off all original argument nodes and that the number of new argument is smaller than the limit
    205       List<ISymbolicExpressionTreeNode> argumentBranches = new List<ISymbolicExpressionTreeNode>();
     194      List<CutPoint> argumentBranches = new List<CutPoint>();
    206195      if (selectedRoot is ArgumentTreeNode) {
    207         argumentBranches.Add(selectedRoot);
     196        argumentBranches.Add(new CutPoint(selectedRoot.Parent, selectedRoot));
    208197        return argumentBranches;
    209198      } else {
     
    213202                                           select nArgumentsInTree).ToList();
    214203        // determine the minimal number of new argument nodes for each sub-tree
     204        //if we exceed the maxArguments return the same cutpoint as the start cutpoint to create a ADF that returns only its argument
    215205        var minNewArgumentsForSubtrees = numberOfArgumentsInSubtrees.Select(x => x > 0 ? 1 : 0).ToList();
    216206        if (minNewArgumentsForSubtrees.Sum() > maxArguments) {
    217           argumentBranches.Add(selectedRoot);
     207          argumentBranches.Add(new CutPoint(selectedRoot.Parent, selectedRoot));
    218208          return argumentBranches;
    219209        }
    220210        // cut-off in the sub-trees in random order
    221211        var randomIndexes = (from index in Enumerable.Range(0, selectedRoot.SubTrees.Count())
    222                              select new { Index = index, OrderValue = random.NextDouble() }).OrderBy(x => x.OrderValue).Select(x => x.Index);
     212                             select new { Index = index, OrderValue = random.NextDouble() })
     213                             .OrderBy(x => x.OrderValue)
     214                             .Select(x => x.Index);
    223215        foreach (var subtreeIndex in randomIndexes) {
    224216          var subtree = selectedRoot.GetSubTree(subtreeIndex);
     
    237229          } else {
    238230            // cut-off at current sub-tree
    239             argumentBranches.Add(subtree);
     231            argumentBranches.Add(new CutPoint(subtree.Parent, subtree));
    240232          }
    241233        }
Note: See TracChangeset for help on using the changeset viewer.