Free cookie consent management tool by TermsFeed Policy Generator

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

#1418: Finally added results from the grammar refactoring.

Location:
branches/DataAnalysis Refactoring/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding
Files:
4 added
32 edited
1 moved

Legend:

Unmodified
Added
Removed
  • branches/DataAnalysis Refactoring/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.3/Tests/ProbabilisticTreeCreaterTest.cs

    r5445 r5686  
    2222using System;
    2323using System.Collections.Generic;
     24using System.Diagnostics;
    2425using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
    2526using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Creators;
     
    3031  [TestClass]
    3132  public class ProbabilisticTreeCreaterTest {
    32     private const int POPULATION_SIZE = 1000;
     33    private const int POPULATION_SIZE = 10000;
    3334    private const int MAX_TREE_SIZE = 100;
    3435    private const int MAX_TREE_HEIGHT = 10;
     
    5354      var grammar = Grammars.CreateSimpleArithmeticGrammar();
    5455      var random = new MersenneTwister(31415);
     56      var stopwatch = new Stopwatch();
     57      stopwatch.Start();
    5558      for (int i = 0; i < POPULATION_SIZE; i++) {
    5659        randomTrees.Add(ProbabilisticTreeCreator.Create(random, grammar, MAX_TREE_SIZE, MAX_TREE_HEIGHT, 0, 0));
    5760      }
     61      stopwatch.Stop();
    5862
    5963      foreach (var tree in randomTrees) {
    6064        Util.IsValid(tree);
    6165      }
     66      double msPerRandomTreeCreation = stopwatch.ElapsedMilliseconds / (double)POPULATION_SIZE;
     67
    6268      Console.WriteLine("ProbabilisticTreeCreator: " + Environment.NewLine +
     69        msPerRandomTreeCreation + " ms per random tree (~" + Math.Round(1000.0 / (msPerRandomTreeCreation)) + "random trees / s)" + Environment.NewLine +
    6370        Util.GetSizeDistributionString(randomTrees, 105, 5) + Environment.NewLine +
    6471        Util.GetFunctionDistributionString(randomTrees) + Environment.NewLine +
     
    6673        Util.GetTerminalDistributionString(randomTrees) + Environment.NewLine
    6774        );
     75      Assert.IsTrue(Math.Round(1000.0 / (msPerRandomTreeCreation)) > 2000); // must achieve more than 2000 random trees / s
    6876    }
    6977
     
    7482      var grammar = Grammars.CreateArithmeticAndAdfGrammar();
    7583      var random = new MersenneTwister(31415);
     84      var stopwatch = new Stopwatch();
     85      stopwatch.Start();
    7686      for (int i = 0; i < POPULATION_SIZE; i++) {
    77         var tree = ProbabilisticTreeCreator.Create(random, grammar, MAX_TREE_SIZE, MAX_TREE_HEIGHT, 3, 3);
     87        randomTrees.Add(ProbabilisticTreeCreator.Create(random, grammar, MAX_TREE_SIZE, MAX_TREE_HEIGHT, 3, 3));
     88      }
     89      stopwatch.Stop();
     90      foreach (var tree in randomTrees)
    7891        Util.IsValid(tree);
    79         randomTrees.Add(tree);
    80       }
     92
     93      double msPerRandomTreeCreation = stopwatch.ElapsedMilliseconds / (double)POPULATION_SIZE;
     94
    8195      Console.WriteLine("ProbabilisticTreeCreator: " + Environment.NewLine +
     96        msPerRandomTreeCreation + " ms per random tree (~" + Math.Round(1000.0 / (msPerRandomTreeCreation)) + "random trees / s)" + Environment.NewLine +
    8297        Util.GetSizeDistributionString(randomTrees, 105, 5) + Environment.NewLine +
    8398        Util.GetFunctionDistributionString(randomTrees) + Environment.NewLine +
     
    85100        Util.GetTerminalDistributionString(randomTrees) + Environment.NewLine
    86101        );
     102
     103      Assert.IsTrue(Math.Round(1000.0 / (msPerRandomTreeCreation)) > 2000); // must achieve more than 2000 random trees / s
    87104    }
    88105  }
  • branches/DataAnalysis Refactoring/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/ArchitectureManipulators/ArgumentCreater.cs

    r5549 r5686  
    2626using HeuristicLab.Core;
    2727using HeuristicLab.Data;
     28using HeuristicLab.Parameters;
    2829using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
    29 using HeuristicLab.Parameters;
    3030
    3131namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding {
     
    126126                       where node.SubTrees.Count() > 0
    127127                       from subtree in node.SubTrees
    128                        select new { Parent = node, ReplacedChildIndex = node.IndexOfSubTree(subtree), ReplacedChild = subtree }).ToList();
     128                       select new CutPoint(node, subtree)).ToList();
    129129
    130130      if (cutPoints.Count() == 0)
     
    133133      var selectedCutPoint = cutPoints[random.Next(cutPoints.Count)];
    134134      // replace the branch at the cut point with an argument node
    135       var replacedBranch = selectedCutPoint.ReplacedChild;
    136       selectedCutPoint.Parent.RemoveSubTree(selectedCutPoint.ReplacedChildIndex);
    137       selectedCutPoint.Parent.InsertSubTree(selectedCutPoint.ReplacedChildIndex, newArgumentNode);
     135      var replacedBranch = selectedCutPoint.Child;
     136      selectedCutPoint.Parent.RemoveSubTree(selectedCutPoint.ChildIndex);
     137      selectedCutPoint.Parent.InsertSubTree(selectedCutPoint.ChildIndex, newArgumentNode);
    138138
    139139      // find all old invocations of the selected ADF and attach a cloned version of the replaced branch (with all argument-nodes expanded)
     
    167167      defunBranch.NumberOfArguments++;
    168168      defunBranch.Grammar.AddSymbol(newArgumentNode.Symbol);
    169       defunBranch.Grammar.SetMinSubtreeCount(newArgumentNode.Symbol, 0);
    170       defunBranch.Grammar.SetMaxSubtreeCount(newArgumentNode.Symbol, 0);
     169      defunBranch.Grammar.SetSubtreeCount(newArgumentNode.Symbol, 0, 0);
    171170      // allow the argument as child of any other symbol
    172171      foreach (var symb in defunBranch.Grammar.Symbols)
    173         for (int i = 0; i < defunBranch.Grammar.GetMaxSubtreeCount(symb); i++) {
    174           defunBranch.Grammar.SetAllowedChild(symb, newArgumentNode.Symbol, i);
     172        for (int i = 0; i < defunBranch.Grammar.GetMaximumSubtreeCount(symb); i++) {
     173          defunBranch.Grammar.AddAllowedChildSymbol(symb, newArgumentNode.Symbol, i);
    175174        }
    176175      foreach (var subtree in tree.Root.SubTrees) {
     
    178177        var matchingSymbol = subtree.Grammar.Symbols.OfType<InvokeFunction>().Where(s => s.FunctionName == defunBranch.FunctionName).SingleOrDefault();
    179178        if (matchingSymbol != null) {
    180           subtree.Grammar.SetMinSubtreeCount(matchingSymbol, defunBranch.NumberOfArguments);
    181           subtree.Grammar.SetMaxSubtreeCount(matchingSymbol, defunBranch.NumberOfArguments);
    182           foreach (var child in subtree.Grammar.GetAllowedSymbols(subtree.Symbol, 0)) {
    183             for (int i = 0; i < subtree.Grammar.GetMaxSubtreeCount(matchingSymbol); i++) {
    184               subtree.Grammar.SetAllowedChild(matchingSymbol, child, i);
     179          subtree.Grammar.SetSubtreeCount(matchingSymbol, defunBranch.NumberOfArguments, defunBranch.NumberOfArguments);
     180          foreach (var child in subtree.Grammar.GetAllowedChildSymbols(subtree.Symbol, 0)) {
     181            for (int i = 0; i < subtree.Grammar.GetMaximumSubtreeCount(matchingSymbol); i++) {
     182              subtree.Grammar.AddAllowedChildSymbol(matchingSymbol, child, i);
    185183            }
    186184          }
  • branches/DataAnalysis Refactoring/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/ArchitectureManipulators/ArgumentDeleter.cs

    r5510 r5686  
    8484        var matchingInvokeSymbol = subtree.Grammar.Symbols.OfType<InvokeFunction>().Where(s => s.FunctionName == selectedDefunBranch.FunctionName).SingleOrDefault();
    8585        if (matchingInvokeSymbol != null) {
    86           subtree.Grammar.SetMinSubtreeCount(matchingInvokeSymbol, selectedDefunBranch.NumberOfArguments);
    87           subtree.Grammar.SetMaxSubtreeCount(matchingInvokeSymbol, selectedDefunBranch.NumberOfArguments);
     86          subtree.Grammar.SetSubtreeCount(matchingInvokeSymbol, selectedDefunBranch.NumberOfArguments, selectedDefunBranch.NumberOfArguments);
    8887        }
    8988      }
  • branches/DataAnalysis Refactoring/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/ArchitectureManipulators/ArgumentDuplicater.cs

    r5529 r5686  
    107107      // register the new argument symbol and increase the number of arguments of the ADF
    108108      selectedDefunBranch.Grammar.AddSymbol(newArgSymbol);
    109       selectedDefunBranch.Grammar.SetMinSubtreeCount(newArgSymbol, 0);
    110       selectedDefunBranch.Grammar.SetMaxSubtreeCount(newArgSymbol, 0);
     109      selectedDefunBranch.Grammar.SetSubtreeCount(newArgSymbol, 0, 0);
    111110      // allow the argument as child of any other symbol
    112111      foreach (var symb in selectedDefunBranch.Grammar.Symbols)
    113         for (int i = 0; i < selectedDefunBranch.Grammar.GetMaxSubtreeCount(symb); i++) {
    114           selectedDefunBranch.Grammar.SetAllowedChild(symb, newArgSymbol, i);
     112        for (int i = 0; i < selectedDefunBranch.Grammar.GetMaximumSubtreeCount(symb); i++) {
     113          selectedDefunBranch.Grammar.AddAllowedChildSymbol(symb, newArgSymbol, i);
    115114        }
    116115      selectedDefunBranch.NumberOfArguments++;
     
    122121                                    select symb).SingleOrDefault();
    123122        if (matchingInvokeSymbol != null) {
    124           subtree.Grammar.SetMinSubtreeCount(matchingInvokeSymbol, selectedDefunBranch.NumberOfArguments);
    125           subtree.Grammar.SetMaxSubtreeCount(matchingInvokeSymbol, selectedDefunBranch.NumberOfArguments);
    126           foreach (var child in subtree.Grammar.GetAllowedSymbols(subtree.Symbol, 0)) {
    127             for (int i = 0; i < subtree.Grammar.GetMaxSubtreeCount(matchingInvokeSymbol); i++) {
    128               subtree.Grammar.SetAllowedChild(matchingInvokeSymbol, child, i);
     123          subtree.Grammar.SetSubtreeCount(matchingInvokeSymbol, selectedDefunBranch.NumberOfArguments, selectedDefunBranch.NumberOfArguments);
     124          foreach (var child in subtree.Grammar.GetAllowedChildSymbols(subtree.Symbol, 0)) {
     125            for (int i = 0; i < subtree.Grammar.GetMaximumSubtreeCount(matchingInvokeSymbol); i++) {
     126              subtree.Grammar.AddAllowedChildSymbol(matchingInvokeSymbol, child, i);
    129127            }
    130128          }
  • branches/DataAnalysis Refactoring/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/ArchitectureManipulators/GrammarModifier.cs

    r5499 r5686  
    2121
    2222using System.Collections.Generic;
     23using System.Linq;
    2324
    2425namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding {
    2526  public static class GrammarModifier {
    26     public static void AddDynamicSymbol(ISymbolicExpressionTreeGrammar grammar, ISymbol classRepresentative, string symbolName, int nArgs) {
    27       var invokeSym = new InvokeFunction(symbolName);
     27    internal static void AddInvokeSymbol(ISymbolicExpressionTreeGrammar grammar, string functionName, int nArgs, CutPoint startCutPoint, IEnumerable<CutPoint> argumentCutPoints) {
     28      var invokeSym = new InvokeFunction(functionName);
    2829      grammar.AddSymbol(invokeSym);
    29       grammar.SetMinSubtreeCount(invokeSym, nArgs);
    30       grammar.SetMaxSubtreeCount(invokeSym, nArgs);
    31       SetSyntaxConstraints(grammar, classRepresentative, invokeSym);
    32     }
     30      grammar.SetSubtreeCount(invokeSym, nArgs, nArgs);
    3331
     32      //allow invoke symbol everywhere, where the child of the startCutPoint was allowed
     33      foreach (ISymbol parent in grammar.Symbols) {
     34        if (grammar.IsAllowedChildSymbol(parent, startCutPoint.Child.Symbol))
     35          grammar.AddAllowedChildSymbol(parent, invokeSym);
     36        else {
     37          for (int i = 0; i < grammar.GetMaximumSubtreeCount(parent); i++) {
     38            if (grammar.IsAllowedChildSymbol(parent, startCutPoint.Child.Symbol, i))
     39              grammar.AddAllowedChildSymbol(parent, invokeSym, i);
     40          }
     41        }
     42      }
    3443
    35     public static void AddDynamicArguments(ISymbolicExpressionTreeGrammar grammar, ISymbol classRepresentative, IEnumerable<int> argumentIndexes) {
    36       foreach (int argIndex in argumentIndexes) {
    37         var argSymbol = new Argument(argIndex);
    38         grammar.AddSymbol(argSymbol);
    39         grammar.SetMinSubtreeCount(argSymbol, 0);
    40         grammar.SetMaxSubtreeCount(argSymbol, 0);
    41         SetSyntaxConstraints(grammar, classRepresentative, argSymbol);
     44      if (nArgs > 0) {
     45        //set allowed child symbols of invoke symbol
     46        foreach (ISymbol child in grammar.Symbols) {
     47          if (argumentCutPoints.All(x => grammar.IsAllowedChildSymbol(x.Parent.Symbol, child)))
     48            grammar.AddAllowedChildSymbol(invokeSym, child);
     49          else {
     50            int i = 0;
     51            foreach (CutPoint argumentCutPoint in argumentCutPoints) {
     52              if (grammar.IsAllowedChildSymbol(argumentCutPoint.Parent.Symbol, child, argumentCutPoint.ChildIndex))
     53                grammar.AddAllowedChildSymbol(invokeSym, child, i);
     54              i++;
     55            }
     56          }
     57        }
    4258      }
    4359    }
    4460
    45     private static void SetSyntaxConstraints(ISymbolicExpressionTreeGrammar grammar, ISymbol classRepresentative, Symbol newSymbol) {
    46       // allow symbol as child of the representative first to make sure that the symbol
    47       // is in the list of parents and children
    48       for (int i = 0; i < grammar.GetMaxSubtreeCount(classRepresentative); i++) {
    49         grammar.SetAllowedChild(classRepresentative, newSymbol, i);
    50       }
    51       // for all available symbols add the new symbol as allowed child iff the available symbol is an allowed child of the class representative
    52       foreach (var parent in grammar.Symbols) {
    53         if (grammar.IsAllowedChild(classRepresentative, parent, 0))
    54           for (int arg = 0; arg < grammar.GetMaxSubtreeCount(parent); arg++) {
    55             grammar.SetAllowedChild(parent, newSymbol, arg);
     61    internal static void AddArgumentSymbol(ISymbolicExpressionTreeGrammar originalGrammar, ISymbolicExpressionTreeGrammar grammar, IEnumerable<int> argumentIndexes, IEnumerable<CutPoint> argumentCutPoints) {
     62      foreach (var pair in argumentIndexes.Zip(argumentCutPoints, (a, b) => new { Index = a, CutPoint = b })) {
     63        var argSymbol = new Argument(pair.Index);
     64        grammar.AddSymbol(argSymbol);
     65        grammar.SetSubtreeCount(argSymbol, 0, 0);
     66
     67        foreach (ISymbol parent in originalGrammar.Symbols) {
     68          if (parent is StartSymbol || parent is ProgramRootSymbol) continue;
     69          if (originalGrammar.IsAllowedChildSymbol(parent, pair.CutPoint.Child.Symbol))
     70            grammar.AddAllowedChildSymbol(parent, argSymbol);
     71          else {
     72            for (int i = 0; i < originalGrammar.GetMaximumSubtreeCount(parent); i++) {
     73              if (originalGrammar.IsAllowedChildSymbol(parent, pair.CutPoint.Child.Symbol, i))
     74                grammar.AddAllowedChildSymbol(parent, argSymbol, i);
     75            }
    5676          }
    57       }
    58       // for all available symbols add the new symbol as allowed parent iff the available symbol is an allowed child of the class representative
    59       foreach (var child in grammar.Symbols) {
    60         if (grammar.IsAllowedChild(classRepresentative, child, 0))
    61           for (int arg = 0; arg < grammar.GetMaxSubtreeCount(newSymbol); arg++) {
    62             grammar.SetAllowedChild(newSymbol, child, arg);
    63           }
     77        }
    6478      }
    6579    }
    66 
    6780  }
    6881}
  • 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        }
  • branches/DataAnalysis Refactoring/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/ArchitectureManipulators/SubroutineDeleter.cs

    r5549 r5686  
    2626using HeuristicLab.Data;
    2727using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
    28 using System.Collections.Generic;
    2928
    3029namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding {
     
    8786                                from subtree in node.SubTrees.OfType<InvokeFunctionTreeNode>()
    8887                                where subtree.Symbol.FunctionName == selectedDefunBranch.FunctionName
    89                                 select new { Parent = node, ReplacedChildIndex = node.IndexOfSubTree(subtree), ReplacedChild = subtree }).FirstOrDefault();
     88                                select new CutPoint(node, subtree)).FirstOrDefault();
    9089      while (invocationCutPoint != null) {
    9190        // deletion by random regeneration
    9291        ISymbolicExpressionTreeNode replacementTree = null;
    93         var allowedSymbolsList = invocationCutPoint.Parent.Grammar.GetAllowedSymbols(invocationCutPoint.Parent.Symbol, invocationCutPoint.ReplacedChildIndex).ToList();
     92        var allowedSymbolsList = invocationCutPoint.Parent.Grammar.GetAllowedChildSymbols(invocationCutPoint.Parent.Symbol, invocationCutPoint.ChildIndex).ToList();
    9493        var weights = allowedSymbolsList.Select(s => s.InitialFrequency);
    9594        var selectedSymbol = allowedSymbolsList.SelectRandom(weights, random);
    9695
    97         int minPossibleLength = invocationCutPoint.Parent.Grammar.GetMinExpressionLength(selectedSymbol);
    98         int maxLength = Math.Max(minPossibleLength, invocationCutPoint.ReplacedChild.GetLength());
    99         int minPossibleDepth = invocationCutPoint.Parent.Grammar.GetMinExpressionDepth(selectedSymbol);
    100         int maxDepth = Math.Max(minPossibleDepth, invocationCutPoint.ReplacedChild.GetDepth());
     96        int minPossibleLength = invocationCutPoint.Parent.Grammar.GetMinimumExpressionLength(selectedSymbol);
     97        int maxLength = Math.Max(minPossibleLength, invocationCutPoint.Child.GetLength());
     98        int minPossibleDepth = invocationCutPoint.Parent.Grammar.GetMinimumExpressionDepth(selectedSymbol);
     99        int maxDepth = Math.Max(minPossibleDepth, invocationCutPoint.Child.GetDepth());
    101100        replacementTree = selectedSymbol.CreateTreeNode();
    102101        if (replacementTree.HasLocalParameters)
    103102          replacementTree.ResetLocalParameters(random);
    104         invocationCutPoint.Parent.RemoveSubTree(invocationCutPoint.ReplacedChildIndex);
    105         invocationCutPoint.Parent.InsertSubTree(invocationCutPoint.ReplacedChildIndex, replacementTree);
     103        invocationCutPoint.Parent.RemoveSubTree(invocationCutPoint.ChildIndex);
     104        invocationCutPoint.Parent.InsertSubTree(invocationCutPoint.ChildIndex, replacementTree);
    106105
    107         ProbabilisticTreeCreator.PTC2(random, replacementTree, maxLength, maxDepth, 0, 0);
     106        ProbabilisticTreeCreator.PTC2(random, replacementTree, maxLength, maxDepth);
    108107
    109108        invocationCutPoint = (from node in symbolicExpressionTree.IterateNodesPrefix()
    110109                              from subtree in node.SubTrees.OfType<InvokeFunctionTreeNode>()
    111110                              where subtree.Symbol.FunctionName == selectedDefunBranch.FunctionName
    112                               select new { Parent = node, ReplacedChildIndex = node.IndexOfSubTree(subtree), ReplacedChild = subtree }).FirstOrDefault();
     111                              select new CutPoint(node, subtree)).FirstOrDefault();
    113112      }
    114113    }
  • branches/DataAnalysis Refactoring/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/ArchitectureManipulators/SubroutineDuplicater.cs

    r5510 r5686  
    7979                                    select symb).SingleOrDefault();
    8080        if (matchingInvokeSymbol != null) {
    81           GrammarModifier.AddDynamicSymbol(subtree.Grammar, subtree.Symbol, duplicatedDefunBranch.FunctionName, duplicatedDefunBranch.NumberOfArguments);
     81          var invokeSymbol = new InvokeFunction(duplicatedDefunBranch.FunctionName);
     82          subtree.Grammar.AddSymbol(invokeSymbol);
     83          subtree.Grammar.SetSubtreeCount(invokeSymbol, duplicatedDefunBranch.NumberOfArguments, duplicatedDefunBranch.NumberOfArguments);
     84
     85          foreach (Symbol symbol in subtree.Grammar.Symbols) {
     86            if (subtree.Grammar.IsAllowedChildSymbol(symbol, matchingInvokeSymbol))
     87              subtree.Grammar.AddAllowedChildSymbol(symbol, invokeSymbol);
     88            else {
     89              for (int i = 0; i < subtree.Grammar.GetMaximumSubtreeCount(symbol); i++)
     90                if (subtree.Grammar.IsAllowedChildSymbol(symbol, matchingInvokeSymbol, i))
     91                  subtree.Grammar.AddAllowedChildSymbol(symbol, matchingInvokeSymbol, i);
     92            }
     93          }
     94
     95          foreach (Symbol symbol in subtree.Grammar.GetAllowedChildSymbols(matchingInvokeSymbol))
     96            if (symbol != invokeSymbol) //avoid duplicate entry invokesymbol / invokesymbol
     97              subtree.Grammar.AddAllowedChildSymbol(invokeSymbol, symbol);
     98          for (int i = 0; i < subtree.Grammar.GetMaximumSubtreeCount(matchingInvokeSymbol); i++) {
     99            foreach (Symbol symbol in subtree.Grammar.GetAllowedChildSymbols(matchingInvokeSymbol, i).Except(subtree.Grammar.GetAllowedChildSymbols(matchingInvokeSymbol)))
     100              subtree.Grammar.AddAllowedChildSymbol(invokeSymbol, symbol, i);
     101          }
    82102        }
    83103        // in the current subtree:
  • branches/DataAnalysis Refactoring/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Creators/ProbabilisticTreeCreator.cs

    r5618 r5686  
    2323using System.Collections.Generic;
    2424using System.Linq;
    25 using System.Text;
    2625using HeuristicLab.Common;
    2726using HeuristicLab.Core;
     
    3433  [Item("ProbabilisticTreeCreator", "An operator that creates new symbolic expression trees with uniformly distributed length")]
    3534  public class ProbabilisticTreeCreator : SymbolicExpressionTreeCreator,
    36     ISymbolicExpressionTreeSizeConstraintOperator, ISymbolicExpressionTreeGrammarBasedOperator, ISymbolicExpressionTreeArchitectureAlteringOperator {
     35    ISymbolicExpressionTreeSizeConstraintOperator, ISymbolicExpressionTreeGrammarBasedOperator {
    3736    private const int MAX_TRIES = 100;
    3837    private const string MaximumSymbolicExpressionTreeLengthParameterName = "MaximumSymbolicExpressionTreeLength";
    3938    private const string MaximumSymbolicExpressionTreeDepthParameterName = "MaximumSymbolicExpressionTreeDepth";
    40     private const string MaximumFunctionDefinitionsParameterName = "MaximumFunctionDefinitions";
    41     private const string MaximumFunctionArgumentsParameterName = "MaximumFunctionArguments";
    4239    private const string SymbolicExpressionTreeGrammarParameterName = "SymbolicExpressionTreeGrammar";
    4340    #region Parameter Properties
     
    4845      get { return (IValueLookupParameter<IntValue>)Parameters[MaximumSymbolicExpressionTreeDepthParameterName]; }
    4946    }
    50     public IValueLookupParameter<IntValue> MaximumFunctionDefinitionsParameter {
    51       get { return (IValueLookupParameter<IntValue>)Parameters[MaximumFunctionDefinitionsParameterName]; }
    52     }
    53     public IValueLookupParameter<IntValue> MaximumFunctionArgumentsParameter {
    54       get { return (IValueLookupParameter<IntValue>)Parameters[MaximumFunctionArgumentsParameterName]; }
    55     }
    56     public IValueLookupParameter<ISymbolicExpressionTreeGrammar> SymbolicExpressionTreeGrammarParameter {
    57       get { return (IValueLookupParameter<ISymbolicExpressionTreeGrammar>)Parameters[SymbolicExpressionTreeGrammarParameterName]; }
     47    public IValueLookupParameter<ISymbolicExpressionGrammar> SymbolicExpressionTreeGrammarParameter {
     48      get { return (IValueLookupParameter<ISymbolicExpressionGrammar>)Parameters[SymbolicExpressionTreeGrammarParameterName]; }
    5849    }
    5950    #endregion
     
    6556      get { return MaximumSymbolicExpressionTreeDepthParameter.ActualValue; }
    6657    }
    67     public IntValue MaximumFunctionDefinitions {
    68       get { return MaximumFunctionDefinitionsParameter.ActualValue; }
    69     }
    70     public IntValue MaximumFunctionArguments {
    71       get { return MaximumFunctionArgumentsParameter.ActualValue; }
    72     }
    73     public ISymbolicExpressionTreeGrammar SymbolicExpressionTreeGrammar {
     58    public ISymbolicExpressionGrammar SymbolicExpressionTreeGrammar {
    7459      get { return SymbolicExpressionTreeGrammarParameter.ActualValue; }
    7560    }
     
    8368      Parameters.Add(new ValueLookupParameter<IntValue>(MaximumSymbolicExpressionTreeLengthParameterName, "The maximal length (number of nodes) of the symbolic expression tree."));
    8469      Parameters.Add(new ValueLookupParameter<IntValue>(MaximumSymbolicExpressionTreeDepthParameterName, "The maximal depth of the symbolic expression tree (a tree with one node has depth = 0)."));
    85       Parameters.Add(new ValueLookupParameter<IntValue>(MaximumFunctionDefinitionsParameterName, "The maximum allowed number of automatically defined functions."));
    86       Parameters.Add(new ValueLookupParameter<IntValue>(MaximumFunctionArgumentsParameterName, "The maximum allowed number of arguments of automatically defined functions."));
    87       Parameters.Add(new ValueLookupParameter<ISymbolicExpressionTreeGrammar>(SymbolicExpressionTreeGrammarParameterName, "The tree grammar that defines the correct syntax of symbolic expression trees that should be created."));
     70      Parameters.Add(new ValueLookupParameter<ISymbolicExpressionGrammar>(SymbolicExpressionTreeGrammarParameterName, "The tree grammar that defines the correct syntax of symbolic expression trees that should be created."));
    8871    }
    8972
     
    9376
    9477    protected override ISymbolicExpressionTree Create(IRandom random) {
    95       return Create(random, SymbolicExpressionTreeGrammar, MaximumSymbolicExpressionTreeLength.Value, MaximumSymbolicExpressionTreeDepth.Value,
    96         MaximumFunctionDefinitions.Value, MaximumFunctionArguments.Value);
    97     }
    98 
    99     public static ISymbolicExpressionTree Create(IRandom random, ISymbolicExpressionTreeGrammar grammar,
    100       int maxTreeLength, int maxTreeDepth,
    101       int maxFunctionDefinitions, int maxFunctionArguments
    102       ) {
     78      return Create(random, SymbolicExpressionTreeGrammar, MaximumSymbolicExpressionTreeLength.Value, MaximumSymbolicExpressionTreeDepth.Value);
     79
     80    }
     81
     82    public static ISymbolicExpressionTree Create(IRandom random, ISymbolicExpressionGrammar grammar,
     83      int maxTreeLength, int maxTreeDepth) {
    10384      SymbolicExpressionTree tree = new SymbolicExpressionTree();
    104       var rootNode = (SymbolicExpressionTreeTopLevelNode)grammar.StartSymbol.CreateTreeNode();
     85      var rootNode = (SymbolicExpressionTreeTopLevelNode)grammar.ProgramRootSymbol.CreateTreeNode();
    10586      if (rootNode.HasLocalParameters) rootNode.ResetLocalParameters(random);
    10687      rootNode.SetGrammar(new SymbolicExpressionTreeGrammar(grammar));
    107       tree.Root = PTC2(random, rootNode, maxTreeLength, maxTreeDepth, maxFunctionDefinitions, maxFunctionArguments);
     88      var startNode = (SymbolicExpressionTreeTopLevelNode)grammar.StartSymbol.CreateTreeNode();
     89      startNode.SetGrammar(new SymbolicExpressionTreeGrammar(grammar));
     90      if (startNode.HasLocalParameters) startNode.ResetLocalParameters(random);
     91      rootNode.AddSubTree(startNode);
     92      PTC2(random, startNode, maxTreeLength, maxTreeDepth);
     93      tree.Root = rootNode;
    10894      return tree;
    10995    }
     
    115101    }
    116102
    117     public static ISymbolicExpressionTreeNode PTC2(IRandom random, ISymbolicExpressionTreeNode seedNode,
    118       int maxLength, int maxDepth, int maxFunctionDefinitions, int maxFunctionArguments) {
     103    public static void PTC2(IRandom random, ISymbolicExpressionTreeNode seedNode,
     104      int maxLength, int maxDepth) {
    119105      // tree length is limited by the grammar and by the explicit size constraints
    120       int allowedMinLength = seedNode.Grammar.GetMinExpressionLength(seedNode.Symbol);
    121       int allowedMaxLength = Math.Min(maxLength, seedNode.Grammar.GetMaxExpressionLength(seedNode.Symbol));
     106      int allowedMinLength = seedNode.Grammar.GetMinimumExpressionLength(seedNode.Symbol);
     107      int allowedMaxLength = Math.Min(maxLength, seedNode.Grammar.GetMaximumExpressionLength(seedNode.Symbol));
    122108      int tries = 0;
    123109      while (tries++ < MAX_TRIES) {
     
    125111        int targetTreeLength;
    126112        targetTreeLength = random.Next(allowedMinLength, allowedMaxLength + 1);
    127         if (targetTreeLength <= 1 || maxDepth <= 1) return seedNode;
    128 
    129         bool success = CreateFullTreeFromSeed(random, seedNode, seedNode.Grammar, targetTreeLength, maxDepth, maxFunctionDefinitions, maxFunctionArguments);
     113        if (targetTreeLength <= 1 || maxDepth <= 1) return;
     114
     115        bool success = CreateFullTreeFromSeed(random, seedNode, seedNode.Grammar, targetTreeLength, maxDepth);
    130116
    131117        // if successful => check constraints and return the tree if everything looks ok       
    132118        if (success && seedNode.GetLength() <= maxLength && seedNode.GetDepth() <= maxDepth) {
    133           return seedNode;
     119          return;
    134120        } else {
    135121          // clean seedNode
     
    142128
    143129    private static bool CreateFullTreeFromSeed(IRandom random, ISymbolicExpressionTreeNode root, ISymbolicExpressionTreeGrammar globalGrammar,
    144       int targetLength, int maxDepth, int maxFunctionDefinitions, int maxFunctionArguments) {
     130      int targetLength, int maxDepth) {
    145131      try {
    146         TryCreateFullTreeFromSeed(random, root, globalGrammar, targetLength, maxDepth, maxFunctionDefinitions, maxFunctionArguments);
     132        TryCreateFullTreeFromSeed(random, root, globalGrammar, targetLength, maxDepth);
    147133        return true;
    148134      }
     
    151137
    152138    private static void TryCreateFullTreeFromSeed(IRandom random, ISymbolicExpressionTreeNode root, ISymbolicExpressionTreeGrammar globalGrammar,
    153       int targetLength, int maxDepth, int maxFunctionDefinitions, int maxFunctionArguments) {
     139      int targetLength, int maxDepth) {
    154140      List<TreeExtensionPoint> extensionPoints = new List<TreeExtensionPoint>();
    155141      int currentLength = 1;
    156       int totalListMinLength = globalGrammar.GetMinExpressionLength(root.Symbol) - 1;
     142      int totalListMinLength = globalGrammar.GetMinimumExpressionLength(root.Symbol) - 1;
    157143      int actualArity = SampleArity(random, root, targetLength);
    158144      for (int i = 0; i < actualArity; i++) {
     
    170156        int argumentIndex = nextExtension.ChildIndex;
    171157        int extensionDepth = nextExtension.ExtensionPointDepth;
    172         if (extensionDepth + parent.Grammar.GetMinExpressionDepth(parent.Symbol) >= maxDepth) {
    173           ReplaceWithMinimalTree(random, root, parent, argumentIndex, maxFunctionDefinitions, maxFunctionArguments);
     158        if (extensionDepth + parent.Grammar.GetMinimumExpressionDepth(parent.Symbol) >= maxDepth) {
     159          ReplaceWithMinimalTree(random, root, parent, argumentIndex);
    174160        } else {
    175161          var allowedSymbols = (from s in parent.Grammar.Symbols
    176                                 where parent.Grammar.IsAllowedChild(parent.Symbol, s, argumentIndex)
    177                                 where parent.Grammar.GetMinExpressionDepth(s) + extensionDepth - 1 < maxDepth
    178                                 where parent.Grammar.GetMaxExpressionLength(s) > targetLength - totalListMinLength - currentLength
     162                                where parent.Grammar.IsAllowedChildSymbol(parent.Symbol, s, argumentIndex)
     163                                where parent.Grammar.GetMinimumExpressionDepth(s) + extensionDepth - 1 < maxDepth
     164                                where parent.Grammar.GetMaximumExpressionLength(s) > targetLength - totalListMinLength - currentLength
    179165                                select s)
    180166                               .ToList();
     
    186172          parent.InsertSubTree(argumentIndex, newTree);
    187173
    188           InitializeNewTreeNode(random, root, newTree, maxFunctionDefinitions, maxFunctionArguments);
     174          var topLevelNode = newTree as SymbolicExpressionTreeTopLevelNode;
     175          if (topLevelNode != null)
     176            topLevelNode.SetGrammar((ISymbolicExpressionTreeGrammar)root.Grammar.Clone());
    189177
    190178          currentLength++;
     
    198186            extensionPoints.Add(new TreeExtensionPoint { Parent = newTree, ChildIndex = i, ExtensionPointDepth = extensionDepth + 1 });
    199187          }
    200           totalListMinLength += newTree.Grammar.GetMinExpressionLength(newTree.Symbol);
     188          totalListMinLength += newTree.Grammar.GetMinimumExpressionLength(newTree.Symbol);
    201189        }
    202190      }
     
    209197        int a = nextExtension.ChildIndex;
    210198        int d = nextExtension.ExtensionPointDepth;
    211         ReplaceWithMinimalTree(random, root, parent, a, maxFunctionDefinitions, maxFunctionArguments);
     199        ReplaceWithMinimalTree(random, root, parent, a);
    212200      }
    213201    }
    214202
    215203    private static void ReplaceWithMinimalTree(IRandom random, ISymbolicExpressionTreeNode root, ISymbolicExpressionTreeNode parent,
    216       int argumentIndex, int maxFunctionDefinitions, int maxFunctionArguments) {
     204      int childIndex) {
    217205      // determine possible symbols that will lead to the smallest possible tree
    218       var possibleSymbols = (from s in parent.Grammar.GetAllowedSymbols(parent.Symbol, argumentIndex)
    219                              group s by parent.Grammar.GetMinExpressionLength(s) into g
     206      var possibleSymbols = (from s in parent.Grammar.GetAllowedChildSymbols(parent.Symbol, childIndex)
     207                             group s by parent.Grammar.GetMinimumExpressionLength(s) into g
    220208                             orderby g.Key
    221209                             select g).First().ToList();
     
    224212      var tree = selectedSymbol.CreateTreeNode();
    225213      if (tree.HasLocalParameters) tree.ResetLocalParameters(random);
    226       parent.RemoveSubTree(argumentIndex);
    227       parent.InsertSubTree(argumentIndex, tree);
    228       InitializeNewTreeNode(random, root, tree, maxFunctionDefinitions, maxFunctionArguments);
    229       for (int i = 0; i < tree.Grammar.GetMinSubtreeCount(tree.Symbol); i++) {
     214      parent.RemoveSubTree(childIndex);
     215      parent.InsertSubTree(childIndex, tree);
     216
     217      var topLevelNode = tree as SymbolicExpressionTreeTopLevelNode;
     218      if (topLevelNode != null)
     219        topLevelNode.SetGrammar((ISymbolicExpressionTreeGrammar)root.Grammar.Clone());
     220
     221      for (int i = 0; i < tree.Grammar.GetMinimumSubtreeCount(tree.Symbol); i++) {
    230222        // insert a dummy sub-tree and add the pending extension to the list
    231223        var dummy = new SymbolicExpressionTreeNode();
    232224        tree.AddSubTree(dummy);
    233225        // replace the just inserted dummy by recursive application
    234         ReplaceWithMinimalTree(random, root, tree, i, maxFunctionDefinitions, maxFunctionArguments);
    235       }
    236     }
    237 
    238     private static void InitializeNewTreeNode(IRandom random, ISymbolicExpressionTreeNode root, ISymbolicExpressionTreeNode newTree, int maxFunctionDefinitions, int maxFunctionArguments) {
    239       // NB it is assumed that defuns are only allowed as children of root and nowhere else
    240       // also assumes that newTree is already attached to root somewhere
    241       if (IsTopLevelBranch(root, newTree)) {
    242         ((SymbolicExpressionTreeTopLevelNode)newTree).SetGrammar((ISymbolicExpressionTreeGrammar)root.Grammar.Clone());
    243 
    244         // allow invokes of existing ADFs with higher index
    245         int argIndex = root.IndexOfSubTree(newTree);
    246         for (int i = argIndex + 1; i < root.SubTrees.Count(); i++) {
    247           var otherDefunNode = root.GetSubTree(i) as DefunTreeNode;
    248           if (otherDefunNode != null) {
    249             GrammarModifier.AddDynamicSymbol(newTree.Grammar, newTree.Symbol, otherDefunNode.FunctionName, otherDefunNode.NumberOfArguments);
    250           }
    251         }
    252       }
    253       if (newTree.Symbol is Defun) {
    254         var defunTree = newTree as DefunTreeNode;
    255         string formatString = new StringBuilder().Append('0', (int)Math.Log10(maxFunctionDefinitions * 10 - 1)).ToString(); // >= 100 functions => ###
    256         var allowedNames = from index in Enumerable.Range(0, maxFunctionDefinitions)
    257                            select "ADF" + index.ToString(formatString);
    258         var takenNames = (from node in root.IterateNodesPrefix().OfType<DefunTreeNode>()
    259                           select node.FunctionName).Distinct();
    260         var remainingNames = allowedNames.Except(takenNames).ToList();
    261         string functionName = remainingNames[random.Next(remainingNames.Count)];
    262         // set name and number of arguments of the ADF
    263         int nArgs = random.Next(maxFunctionArguments);
    264         defunTree.FunctionName = functionName;
    265         defunTree.NumberOfArguments = nArgs;
    266         if (nArgs > 0) {
    267           GrammarModifier.AddDynamicArguments(defunTree.Grammar, defunTree.Symbol, Enumerable.Range(0, nArgs));
    268         }
    269         // in existing branches with smaller index allow invoke of current function
    270         int argIndex = root.IndexOfSubTree(newTree);
    271         for (int i = 0; i < argIndex; i++) {
    272           // if not dummy node
    273           if (root.GetSubTree(i).Symbol != null) {
    274             var existingBranch = root.GetSubTree(i);
    275             GrammarModifier.AddDynamicSymbol(existingBranch.Grammar, existingBranch.Symbol, functionName, nArgs);
    276           }
    277         }
     226        ReplaceWithMinimalTree(random, root, tree, i);
    278227      }
    279228    }
     
    285234    private static int SampleArity(IRandom random, ISymbolicExpressionTreeNode node, int targetLength) {
    286235      // select actualArity randomly with the constraint that the sub-trees in the minimal arity can become large enough
    287       int minArity = node.Grammar.GetMinSubtreeCount(node.Symbol);
    288       int maxArity = node.Grammar.GetMaxSubtreeCount(node.Symbol);
     236      int minArity = node.Grammar.GetMinimumSubtreeCount(node.Symbol);
     237      int maxArity = node.Grammar.GetMaximumSubtreeCount(node.Symbol);
    289238      if (maxArity > targetLength) {
    290239        maxArity = targetLength;
     
    294243      long aggregatedLongestExpressionLength = 0;
    295244      for (int i = 0; i < maxArity; i++) {
    296         aggregatedLongestExpressionLength += (from s in node.Grammar.GetAllowedSymbols(node.Symbol, i)
    297                                               select node.Grammar.GetMaxExpressionLength(s)).Max();
     245        aggregatedLongestExpressionLength += (from s in node.Grammar.GetAllowedChildSymbols(node.Symbol, i)
     246                                              select node.Grammar.GetMaximumExpressionLength(s)).Max();
    298247        if (aggregatedLongestExpressionLength < targetLength) minArity = i;
    299248        else break;
     
    304253      long aggregatedShortestExpressionLength = 0;
    305254      for (int i = 0; i < maxArity; i++) {
    306         aggregatedShortestExpressionLength += (from s in node.Grammar.GetAllowedSymbols(node.Symbol, i)
    307                                                select node.Grammar.GetMinExpressionLength(s)).Min();
     255        aggregatedShortestExpressionLength += (from s in node.Grammar.GetAllowedChildSymbols(node.Symbol, i)
     256                                               select node.Grammar.GetMinimumExpressionLength(s)).Min();
    308257        if (aggregatedShortestExpressionLength > targetLength) {
    309258          maxArity = i;
  • branches/DataAnalysis Refactoring/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Crossovers/SubtreeCrossover.cs

    r5549 r5686  
    120120      // check syntax constraints of direct parent - child relation
    121121      if (!parent.Grammar.ContainsSymbol(branch.Symbol) ||
    122           !parent.Grammar.IsAllowedChild(parent.Symbol, branch.Symbol, replacedSubtreeIndex)) return false;
     122          !parent.Grammar.IsAllowedChildSymbol(parent.Symbol, branch.Symbol, replacedSubtreeIndex)) return false;
    123123
    124124      bool result = true;
     
    128128          result &&
    129129          parent.Grammar.ContainsSymbol(n.Symbol) &&
    130           n.SubTrees.Count() >= parent.Grammar.GetMinSubtreeCount(n.Symbol) &&
    131           n.SubTrees.Count() <= parent.Grammar.GetMaxSubtreeCount(n.Symbol);
     130          n.SubtreesCount >= parent.Grammar.GetMinimumSubtreeCount(n.Symbol) &&
     131          n.SubtreesCount <= parent.Grammar.GetMaximumSubtreeCount(n.Symbol);
    132132      });
    133133      return result;
     
    136136    private static void SelectCrossoverPoint(IRandom random, ISymbolicExpressionTree parent0, double internalNodeProbability, int maxBranchLength, int maxBranchDepth, out ISymbolicExpressionTreeNode crossoverPoint, out int subtreeIndex) {
    137137      if (internalNodeProbability < 0.0 || internalNodeProbability > 1.0) throw new ArgumentException("internalNodeProbability");
    138       List<CrossoverPoint> internalCrossoverPoints = new List<CrossoverPoint>();
    139       List<CrossoverPoint> leafCrossoverPoints = new List<CrossoverPoint>();
     138      List<CutPoint> internalCrossoverPoints = new List<CutPoint>();
     139      List<CutPoint> leafCrossoverPoints = new List<CutPoint>();
    140140      parent0.Root.ForEachNodePostfix((n) => {
    141         if (n.SubTrees.Count() > 0 && n != parent0.Root) {
     141        if (n.SubTrees.Any() && n != parent0.Root) {
    142142          foreach (var child in n.SubTrees) {
    143143            if (child.GetLength() <= maxBranchLength &&
    144144                child.GetDepth() <= maxBranchDepth) {
    145               if (child.SubTrees.Count() > 0)
    146                 internalCrossoverPoints.Add(new CrossoverPoint(n, child));
     145              if (child.SubTrees.Any())
     146                internalCrossoverPoints.Add(new CutPoint(n, child));
    147147              else
    148                 leafCrossoverPoints.Add(new CrossoverPoint(n, child));
     148                leafCrossoverPoints.Add(new CutPoint(n, child));
    149149            }
    150150          }
     
    158158          var selectedCrossoverPoint = internalCrossoverPoints[random.Next(internalCrossoverPoints.Count)];
    159159          crossoverPoint = selectedCrossoverPoint.Parent;
    160           subtreeIndex = selectedCrossoverPoint.SubtreeIndex;
     160          subtreeIndex = selectedCrossoverPoint.ChildIndex;
    161161        } else {
    162162          // otherwise select external node
    163163          var selectedCrossoverPoint = leafCrossoverPoints[random.Next(leafCrossoverPoints.Count)];
    164164          crossoverPoint = selectedCrossoverPoint.Parent;
    165           subtreeIndex = selectedCrossoverPoint.SubtreeIndex;
     165          subtreeIndex = selectedCrossoverPoint.ChildIndex;
    166166        }
    167167      } else if (leafCrossoverPoints.Count > 0) {
     
    169169        var selectedCrossoverPoint = leafCrossoverPoints[random.Next(leafCrossoverPoints.Count)];
    170170        crossoverPoint = selectedCrossoverPoint.Parent;
    171         subtreeIndex = selectedCrossoverPoint.SubtreeIndex;
     171        subtreeIndex = selectedCrossoverPoint.ChildIndex;
    172172      } else {
    173173        // otherwise select internal crossover point
    174174        var selectedCrossoverPoint = internalCrossoverPoints[random.Next(internalCrossoverPoints.Count)];
    175175        crossoverPoint = selectedCrossoverPoint.Parent;
    176         subtreeIndex = selectedCrossoverPoint.SubtreeIndex;
     176        subtreeIndex = selectedCrossoverPoint.ChildIndex;
    177177      }
    178178    }
     
    185185        // select internal node if possible
    186186        allowedInternalBranches = (from branch in branches
    187                                    where branch.SubTrees.Count() > 0
     187                                   where branch.SubTrees.Any()
    188188                                   select branch).ToList();
    189189        if (allowedInternalBranches.Count > 0) {
     
    192192          // no internal nodes allowed => select leaf nodes
    193193          allowedLeafBranches = (from branch in branches
    194                                  where branch.SubTrees.Count() == 0
     194                                 where !branch.SubTrees.Any()
    195195                                 select branch).ToList();
    196196          return allowedLeafBranches.SelectRandom(random);
     
    199199        // select leaf node if possible
    200200        allowedLeafBranches = (from branch in branches
    201                                where branch.SubTrees.Count() == 0
     201                               where !branch.SubTrees.Any()
    202202                               select branch).ToList();
    203203        if (allowedLeafBranches.Count > 0) {
     
    205205        } else {
    206206          allowedInternalBranches = (from branch in branches
    207                                      where branch.SubTrees.Count() > 0
     207                                     where branch.SubTrees.Any()
    208208                                     select branch).ToList();
    209209          return allowedInternalBranches.SelectRandom(random);
  • branches/DataAnalysis Refactoring/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/CutPoint.cs

    r5674 r5686  
    2222
    2323namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding {
    24   internal class CrossoverPoint {
     24  internal class CutPoint {
    2525    public ISymbolicExpressionTreeNode Parent { get; set; }
    2626    public ISymbolicExpressionTreeNode Child { get; set; }
    27     public int SubtreeIndex {
    28       get { return Parent.IndexOfSubTree(Child); }
     27    private int childIndex;
     28    public int ChildIndex {
     29      get { return childIndex; }
    2930    }
    30     public CrossoverPoint(ISymbolicExpressionTreeNode parent, ISymbolicExpressionTreeNode child) {
     31    public CutPoint(ISymbolicExpressionTreeNode parent, ISymbolicExpressionTreeNode child) {
    3132      this.Parent = parent;
    3233      this.Child = child;
     34      this.childIndex = parent.IndexOfSubTree(child);
    3335    }
    3436  }
  • branches/DataAnalysis Refactoring/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding-3.4.csproj

    r5635 r5686  
    124124    <Compile Include="Compiler\SymbolicExpressionTreeCompiler.cs" />
    125125    <Compile Include="Interfaces\IReadOnlySymbol.cs" />
     126    <Compile Include="Interfaces\ISymbolicExpressionGrammar.cs" />
     127    <Compile Include="Interfaces\ISymbolicExpressionGrammarBase.cs" />
    126128    <Compile Include="Interfaces\ISymbolicExpressionTreeGrammar.cs" />
    127129    <Compile Include="Interfaces\Operators\ISymbolicExpressionTreeArchitectureAlteringOperator.cs" />
    128130    <Compile Include="Interfaces\Operators\ISymbolicExpressionTreeGrammarBasedOperator.cs" />
    129131    <Compile Include="Creators\SymbolicExpressionTreeCreator.cs" />
    130     <Compile Include="Crossovers\CrossoverPoint.cs" />
     132    <Compile Include="CutPoint.cs" />
    131133    <Compile Include="Crossovers\SymbolicExpressionTreeCrossover.cs" />
    132134    <Compile Include="Formatters\SymbolicExpressionTreeStringFormatter.cs" />
     
    147149    <Compile Include="Manipulators\OnePointShaker.cs" />
    148150    <Compile Include="Manipulators\SymbolicExpressionTreeManipulator.cs" />
     151    <Compile Include="SymbolicExpressionGrammarBase.cs" />
     152    <Compile Include="SymbolicExpressionGrammar.cs" />
    149153    <Compile Include="SymbolicExpressionTreeGrammar.cs" />
    150154    <Compile Include="SymbolicExpressionTreeTopLevelNode.cs" />
     
    152156      <SubType>Code</SubType>
    153157    </Compile>
    154     <Compile Include="GlobalSymbolicExpressionGrammar.cs" />
    155158    <Compile Include="EnumerableExtensions.cs" />
    156     <Compile Include="DefaultSymbolicExpressionGrammar.cs">
    157       <SubType>Code</SubType>
    158     </Compile>
    159159    <Compile Include="SymbolicExpressionTreeOperator.cs" />
    160160    <Compile Include="SymbolicExpressionTreeTerminalNode.cs" />
  • branches/DataAnalysis Refactoring/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Interfaces/ISymbolicExpressionTreeGrammar.cs

    r5529 r5686  
    2121
    2222using System.Collections.Generic;
    23 using HeuristicLab.Core;
     23namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding {
     24  public interface ISymbolicExpressionTreeGrammar : ISymbolicExpressionGrammarBase {
    2425
    25 namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding {
    26   public interface ISymbolicExpressionTreeGrammar : IItem {
    27     IEnumerable<ISymbol> Symbols { get; }
    28     ISymbol StartSymbol { get; }
     26    IEnumerable<ISymbol> ModifyableSymbols { get; }
     27    bool IsModifyableSymbol(ISymbol symbol);
    2928    void AddSymbol(ISymbol symbol);
    3029    void RemoveSymbol(ISymbol symbol);
    3130
    32     bool ContainsSymbol(ISymbol symbol);
    33     void SetAllowedChild(ISymbol parent, ISymbol child, int argumentIndex);
    34     bool IsAllowedChild(ISymbol parent, ISymbol child, int argumentIndex);
     31    void AddAllowedChildSymbol(ISymbol parent, ISymbol child);
     32    void AddAllowedChildSymbol(ISymbol parent, ISymbol child, int argumentIndex);
     33    void RemoveAllowedChildSymbol(ISymbol parent, ISymbol child);
     34    void RemoveAllowedChildSymbol(ISymbol parent, ISymbol child, int argumentIndex);
    3535
    36     IEnumerable<ISymbol> GetAllowedSymbols(ISymbol parent, int argumentIndex);
    37 
    38     int GetMinExpressionLength(ISymbol start);
    39     int GetMaxExpressionLength(ISymbol start);
    40     int GetMinExpressionDepth(ISymbol start);
    41 
    42     int GetMinSubtreeCount(ISymbol symbol);
    43     void SetMinSubtreeCount(ISymbol symbol, int value);
    44     int GetMaxSubtreeCount(ISymbol symbol);
    45     void SetMaxSubtreeCount(ISymbol symbol, int value);
     36    void SetSubtreeCount(ISymbol symbol, int minimumSubtreeCount, int maximumSubtreeCount);
    4637  }
    4738}
  • branches/DataAnalysis Refactoring/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Interfaces/ISymbolicExpressionTreeNode.cs

    r5549 r5686  
    1919 */
    2020#endregion
     21using System;
    2122using System.Collections.Generic;
     23using HeuristicLab.Common;
    2224using HeuristicLab.Core;
    23 using System;
    24 using HeuristicLab.Common;
    2525namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding {
    2626  public interface ISymbolicExpressionTreeNode : IDeepCloneable {
     
    3939
    4040    IEnumerable<ISymbolicExpressionTreeNode> SubTrees { get; }
     41    int SubtreesCount { get; }
    4142    ISymbolicExpressionTreeNode GetSubTree(int index);
    4243    int IndexOfSubTree(ISymbolicExpressionTreeNode tree);
  • branches/DataAnalysis Refactoring/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Interfaces/Operators/ISymbolicExpressionTreeGrammarBasedOperator.cs

    r5499 r5686  
    2727  /// </summary>
    2828  public interface ISymbolicExpressionTreeGrammarBasedOperator : ISymbolicExpressionTreeOperator {
    29     IValueLookupParameter<ISymbolicExpressionTreeGrammar> SymbolicExpressionTreeGrammarParameter { get; }
     29    IValueLookupParameter<ISymbolicExpressionGrammar> SymbolicExpressionTreeGrammarParameter { get; }
    3030  }
    3131}
  • branches/DataAnalysis Refactoring/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Manipulators/ChangeNodeTypeManipulation.cs

    r5567 r5686  
    2020#endregion
    2121
    22 using System;
    23 using System.Collections.Generic;
    2422using System.Linq;
    2523using HeuristicLab.Common;
    2624using HeuristicLab.Core;
    27 using HeuristicLab.Data;
    2825using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
    2926
     
    5350                                let existingSubtreeCount = subtree.SubTrees.Count()
    5451                                // find possible symbols for the node (also considering the existing branches below it)
    55                                 let allowedSymbols = (from symbol in parent.Grammar.GetAllowedSymbols(parent.Symbol, subtreeIndex)
     52                                let allowedSymbols = (from symbol in parent.Grammar.GetAllowedChildSymbols(parent.Symbol, subtreeIndex)
    5653                                                      // do not replace the existing symbol with itself
    5754                                                      where symbol.Name != subtree.Symbol.Name
    58                                                       where existingSubtreeCount <= parent.Grammar.GetMaxSubtreeCount(symbol)
    59                                                       where existingSubtreeCount >= parent.Grammar.GetMinSubtreeCount(symbol)
     55                                                      where existingSubtreeCount <= parent.Grammar.GetMaximumSubtreeCount(symbol)
     56                                                      where existingSubtreeCount >= parent.Grammar.GetMinimumSubtreeCount(symbol)
    6057                                                      // keep only symbols that are still possible considering the existing sub-trees
    6158                                                      where (from existingSubtreeIndex in Enumerable.Range(0, existingSubtreeCount)
    6259                                                             let existingSubtree = subtree.GetSubTree(existingSubtreeIndex)
    63                                                              select parent.Grammar.IsAllowedChild(symbol, existingSubtree.Symbol, existingSubtreeIndex))
     60                                                             select parent.Grammar.IsAllowedChildSymbol(symbol, existingSubtree.Symbol, existingSubtreeIndex))
    6461                                                             .All(x => x == true)
    6562                                                      select symbol)
  • branches/DataAnalysis Refactoring/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Manipulators/ReplaceBranchManipulation.cs

    r5569 r5686  
    2020#endregion
    2121
    22 using System;
    23 using System.Collections.Generic;
    2422using System.Linq;
    2523using HeuristicLab.Common;
    2624using HeuristicLab.Core;
    2725using HeuristicLab.Data;
     26using HeuristicLab.Parameters;
    2827using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
    29 using HeuristicLab.Parameters;
    3028
    3129namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding {
     
    7775                                let maxDepth = maxTreeDepth - symbolicExpressionTree.Depth + subtree.GetDepth()
    7876                                // find possible symbols for the node (also considering the existing branches below it)
    79                                 let allowedSymbols = (from symbol in parent.Grammar.GetAllowedSymbols(parent.Symbol, subtreeIndex)
     77                                let allowedSymbols = (from symbol in parent.Grammar.GetAllowedChildSymbols(parent.Symbol, subtreeIndex)
    8078                                                      // do not replace symbol with the same symbol
    8179                                                      where symbol.Name != subtree.Symbol.Name
    82                                                       where parent.Grammar.GetMinExpressionDepth(symbol) <= maxDepth
    83                                                       where parent.Grammar.GetMinExpressionLength(symbol) <= maxLength
     80                                                      where parent.Grammar.GetMinimumExpressionDepth(symbol) <= maxDepth
     81                                                      where parent.Grammar.GetMinimumExpressionLength(symbol) <= maxLength
    8482                                                      select symbol)
    8583                                                      .ToList()
     
    107105      selectedManipulationPoint.Parent.RemoveSubTree(selectedManipulationPoint.Index);
    108106      selectedManipulationPoint.Parent.InsertSubTree(selectedManipulationPoint.Index, seedNode);
    109       seedNode = ProbabilisticTreeCreator.PTC2(random, seedNode, selectedManipulationPoint.MaxLength, selectedManipulationPoint.MaxDepth, 0, 0);
     107      ProbabilisticTreeCreator.PTC2(random, seedNode, selectedManipulationPoint.MaxLength, selectedManipulationPoint.MaxDepth);
    110108    }
    111109  }
  • branches/DataAnalysis Refactoring/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/SymbolicExpressionTreeGrammar.cs

    r5499 r5686  
    2020#endregion
    2121
     22using System;
     23using System.Collections.Generic;
     24using System.Linq;
    2225using HeuristicLab.Common;
    2326using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
    2427
    2528namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding {
    26   public sealed class SymbolicExpressionTreeGrammar : DefaultSymbolicExpressionGrammar {
    27     public SymbolicExpressionTreeGrammar(ISymbolicExpressionTreeGrammar grammar)
    28       : base(grammar) {
    29     }
     29  [StorableClass]
     30  internal sealed class SymbolicExpressionTreeGrammar : SymbolicExpressionGrammarBase, ISymbolicExpressionTreeGrammar {
    3031    [StorableConstructor]
    3132    private SymbolicExpressionTreeGrammar(bool deserializing) : base(deserializing) { }
    32     // don't call storable ctor of base class to prevent full cloning
    33     // instead use storable ctor to initialize an empty grammar and fill with InizializeShallowClone
    3433    private SymbolicExpressionTreeGrammar(SymbolicExpressionTreeGrammar original, Cloner cloner)
    35       : base(false) {
    36       cloner.RegisterClonedObject(original, this);
    37       InitializeShallowClone(original);
     34      : base(original, cloner) {
     35      this.grammar = original.grammar;
    3836    }
    39     private SymbolicExpressionTreeGrammar() : base() { }
    40 
    4137    public override IDeepCloneable Clone(Cloner cloner) {
    4238      return new SymbolicExpressionTreeGrammar(this, cloner);
    4339    }
     40
     41    private ISymbolicExpressionGrammar grammar;
     42    public SymbolicExpressionTreeGrammar(ISymbolicExpressionGrammar grammar)
     43      : base() {
     44      if (grammar == null) throw new ArgumentNullException();
     45      this.grammar = grammar;
     46    }
     47
     48    public override IEnumerable<ISymbol> Symbols {
     49      get { return grammar.Symbols.Union(base.Symbols); }
     50    }
     51    public override IEnumerable<ISymbol> AllowedSymbols {
     52      get { return base.AllowedSymbols; }
     53    }
     54    public IEnumerable<ISymbol> ModifyableSymbols {
     55      get { return base.symbols.Values; }
     56    }
     57    public bool IsModifyableSymbol(ISymbol symbol) {
     58      return base.symbols.ContainsKey(symbol.Name);
     59    }
     60
     61    public override bool ContainsSymbol(ISymbol symbol) {
     62      return grammar.ContainsSymbol(symbol) || base.ContainsSymbol(symbol);
     63    }
     64    public override ISymbol GetSymbol(string symbolName) {
     65      var symbol = grammar.GetSymbol(symbolName);
     66      if (symbol != null) return symbol;
     67      symbol = base.GetSymbol(symbolName);
     68      if (symbol != null) return symbol;
     69      throw new ArgumentException();
     70    }
     71
     72    public override bool IsAllowedChildSymbol(ISymbol parent, ISymbol child) {
     73      return grammar.IsAllowedChildSymbol(parent, child) || base.IsAllowedChildSymbol(parent, child);
     74    }
     75    public override bool IsAllowedChildSymbol(ISymbol parent, ISymbol child, int argumentIndex) {
     76      return grammar.IsAllowedChildSymbol(parent, child, argumentIndex) || base.IsAllowedChildSymbol(parent, child, argumentIndex);
     77    }
     78    public override IEnumerable<ISymbol> GetAllowedChildSymbols(ISymbol parent) {
     79      return grammar.GetAllowedChildSymbols(parent).Union(base.GetAllowedChildSymbols(parent));
     80    }
     81    public override IEnumerable<ISymbol> GetAllowedChildSymbols(ISymbol parent, int argumentIndex) {
     82      return grammar.GetAllowedChildSymbols(parent, argumentIndex).Union(base.GetAllowedChildSymbols(parent, argumentIndex));
     83    }
     84
     85    public override int GetMinimumSubtreeCount(ISymbol symbol) {
     86      if (grammar.ContainsSymbol(symbol)) return grammar.GetMinimumSubtreeCount(symbol);
     87      return base.GetMinimumSubtreeCount(symbol);
     88    }
     89    public override int GetMaximumSubtreeCount(ISymbol symbol) {
     90      if (grammar.ContainsSymbol(symbol)) return grammar.GetMaximumSubtreeCount(symbol);
     91      return base.GetMaximumSubtreeCount(symbol);
     92    }
     93
     94    void ISymbolicExpressionTreeGrammar.AddSymbol(ISymbol symbol) {
     95      base.AddSymbol(symbol);
     96    }
     97    void ISymbolicExpressionTreeGrammar.RemoveSymbol(ISymbol symbol) {
     98      if (!IsModifyableSymbol(symbol)) throw new InvalidOperationException();
     99      base.RemoveSymbol(symbol);
     100    }
     101    void ISymbolicExpressionTreeGrammar.AddAllowedChildSymbol(ISymbol parent, ISymbol child) {
     102      base.AddAllowedChildSymbol(parent, child);
     103    }
     104    void ISymbolicExpressionTreeGrammar.AddAllowedChildSymbol(ISymbol parent, ISymbol child, int argumentIndex) {
     105      base.AddAllowedChildSymbol(parent, child, argumentIndex);
     106    }
     107    void ISymbolicExpressionTreeGrammar.RemoveAllowedChildSymbol(ISymbol parent, ISymbol child) {
     108      base.RemoveAllowedChildSymbol(parent, child);
     109    }
     110    void ISymbolicExpressionTreeGrammar.RemoveAllowedChildSymbol(ISymbol parent, ISymbol child, int argumentIndex) {
     111      base.RemoveAllowedChildSymbol(parent, child, argumentIndex);
     112    }
     113
     114    void ISymbolicExpressionTreeGrammar.SetSubtreeCount(ISymbol symbol, int minimumSubtreeCount, int maximumSubtreeCount) {
     115      if (!IsModifyableSymbol(symbol)) throw new InvalidOperationException();
     116      base.SetSubtreeCount(symbol, minimumSubtreeCount, maximumSubtreeCount);
     117    }
    44118  }
    45119}
  • branches/DataAnalysis Refactoring/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/SymbolicExpressionTreeNode.cs

    r5549 r5686  
    2222using System;
    2323using System.Collections.Generic;
    24 using System.Linq;
    2524using HeuristicLab.Common;
    2625using HeuristicLab.Core;
     
    126125    public virtual void ShakeLocalParameters(IRandom random, double shakingFactor) { }
    127126
     127    public int SubtreesCount {
     128      get {
     129        if (subTrees == null) return 0;
     130        return subTrees.Count;
     131      }
     132    }
     133
    128134    public virtual ISymbolicExpressionTreeNode GetSubTree(int index) {
    129135      return subTrees[index];
  • branches/DataAnalysis Refactoring/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/SymbolicExpressionTreeTerminalNode.cs

    r5510 r5686  
    2222using System;
    2323using System.Collections.Generic;
     24using System.Linq;
    2425using HeuristicLab.Common;
    2526using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
    26 using System.Linq;
    2727
    2828namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding {
  • branches/DataAnalysis Refactoring/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Tests/AllArchitectureAlteringOperatorsTest.cs

    r5549 r5686  
    5656      var grammar = Grammars.CreateArithmeticAndAdfGrammar();
    5757      var random = new MersenneTwister(31415);
     58      SymbolicExpressionTreeStringFormatter formatter = new SymbolicExpressionTreeStringFormatter();
    5859      IntValue maxTreeSize = new IntValue(MAX_TREE_LENGTH);
    5960      IntValue maxTreeHeigth = new IntValue(MAX_TREE_DEPTH);
     
    6162      IntValue maxArgs = new IntValue(3);
    6263      for (int i = 0; i < POPULATION_SIZE; i++) {
    63         var tree = ProbabilisticTreeCreator.Create(random, grammar, MAX_TREE_LENGTH, MAX_TREE_DEPTH, 3, 3);
     64        var tree = ProbabilisticTreeCreator.Create(random, grammar, MAX_TREE_LENGTH, MAX_TREE_DEPTH);
    6465        Util.IsValid(tree);
    6566        trees.Add(tree);
    6667      }
    6768      Stopwatch stopwatch = new Stopwatch();
    68       stopwatch.Start();
    6969      int failedEvents = 0;
    7070      for (int g = 0; g < N_ITERATIONS; g++) {
     
    7272          if (random.NextDouble() < 0.5) {
    7373            // manipulate
     74            stopwatch.Start();
    7475            var selectedTree = (ISymbolicExpressionTree)trees.SelectRandom(random).Clone();
     76            var oldTree = (ISymbolicExpressionTree)selectedTree.Clone();
     77            var oldFormatedTree = formatter.Format(oldTree);
    7578            bool success = false;
    76             switch (random.Next(6)) {
     79            int sw = random.Next(6);
     80            switch (sw) {
    7781              case 0: success = ArgumentCreater.CreateNewArgument(random, selectedTree, MAX_TREE_LENGTH, MAX_TREE_DEPTH, 3, 3); break;
    7882              case 1: success = ArgumentDeleter.DeleteArgument(random, selectedTree, 3, 3); break;
     
    8286              case 5: success = SubroutineDeleter.DeleteSubroutine(random, selectedTree, 3, 3); break;
    8387            }
     88            stopwatch.Stop();
    8489            if (!success) failedEvents++;
     90            var newFormatedTree = formatter.Format(selectedTree);
    8591            Util.IsValid(selectedTree);
    8692            newTrees.Add(selectedTree);
     
    98104        trees = newTrees;
    99105      }
    100       stopwatch.Stop();
    101106      var msPerOperation = stopwatch.ElapsedMilliseconds / (double)POPULATION_SIZE / (double)N_ITERATIONS;
    102107      Console.WriteLine("AllArchitectureAlteringOperators: " + Environment.NewLine +
  • branches/DataAnalysis Refactoring/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Tests/ArgumentCreaterTest.cs

    r5549 r5686  
    2121
    2222using System;
     23using System.Collections.Generic;
    2324using System.Linq;
    24 using System.Collections.Generic;
    2525using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
    2626using HeuristicLab.Random;
     
    5757        ISymbolicExpressionTree tree;
    5858        do {
    59           tree = ProbabilisticTreeCreator.Create(random, grammar, MAX_TREE_LENGTH, MAX_TREE_DEPTH, 3, 3);
     59          tree = ProbabilisticTreeCreator.Create(random, grammar, MAX_TREE_LENGTH, MAX_TREE_DEPTH);
     60          SubroutineCreater.CreateSubroutine(random, tree, MAX_TREE_LENGTH, MAX_TREE_DEPTH, 3, 3);
    6061        } while (!TreeHasAdfWithParameter(tree, 3));
    6162        var success = ArgumentCreater.CreateNewArgument(random, tree, 60000, 100, 3, 3);
     
    6667      // difficult to make sure that create argument operations succeed because trees are macro-expanded can potentially become very big
    6768      // => just test if only a small proportion fails
    68       Assert.IsTrue(failedOps < POPULATION_SIZE * 0.01 ); // only 1% may fail
     69      Assert.IsTrue(failedOps < POPULATION_SIZE * 0.01); // only 1% may fail
    6970      Console.WriteLine("ArgumentCreator: " + Environment.NewLine +
    7071        "Failed operations: " + failedOps * 100.0 / POPULATION_SIZE + " %" + Environment.NewLine +
     
    7778
    7879    private bool TreeHasAdfWithParameter(ISymbolicExpressionTree tree, int maxParameters) {
    79       if(tree.Root.SubTrees.Count() != 2 ) return false;
     80      if (tree.Root.SubTrees.Count() != 2) return false;
    8081      var firstAdf = tree.Root.GetSubTree(1);
    81       return firstAdf.Grammar.GetAllowedSymbols(firstAdf.Symbol, 0).Where(x => x is Argument).Count() < maxParameters;
     82      return firstAdf.Grammar.GetAllowedChildSymbols(firstAdf.Symbol, 0).Where(x => x is Argument).Count() < maxParameters;
    8283    }
    8384  }
  • branches/DataAnalysis Refactoring/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Tests/ArgumentDeleterTest.cs

    r5549 r5686  
    5656        ISymbolicExpressionTree tree = null;
    5757        do {
    58           tree = ProbabilisticTreeCreator.Create(random, grammar, MAX_TREE_LENGTH, MAX_TREE_DEPTH, 3, 3);
     58          tree = ProbabilisticTreeCreator.Create(random, grammar, MAX_TREE_LENGTH, MAX_TREE_DEPTH);
     59          SubroutineCreater.CreateSubroutine(random, tree, MAX_TREE_LENGTH, MAX_TREE_DEPTH, 3, 3);
    5960        } while (!TreeHasAdfWithArguments(tree));
    6061        var success = ArgumentDeleter.DeleteArgument(random, tree, 3, 3);
     
    7374      if (tree.Root.SubTrees.Count() != 2) return false;
    7475      var firstAdf = tree.Root.GetSubTree(1);
    75       return firstAdf.Grammar.GetAllowedSymbols(firstAdf.Symbol, 0).Where(x => x is Argument).Count() >= 2;
     76      return firstAdf.Grammar.GetAllowedChildSymbols(firstAdf.Symbol, 0).Where(x => x is Argument).Count() >= 2;
    7677    }
    7778  }
  • branches/DataAnalysis Refactoring/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Tests/ArgumentDuplicaterTest.cs

    r5549 r5686  
    2121
    2222using System;
     23using System.Collections.Generic;
    2324using System.Linq;
    24 using System.Collections.Generic;
    2525using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
    2626using HeuristicLab.Random;
     
    5656        ISymbolicExpressionTree tree = null;
    5757        do {
    58           tree = ProbabilisticTreeCreator.Create(random, grammar, MAX_TREE_LENGTH, MAX_TREE_DEPTH, 3, 3);
    59         } while(!HasAdfWithArguments(tree));
     58          tree = ProbabilisticTreeCreator.Create(random, grammar, MAX_TREE_LENGTH, MAX_TREE_DEPTH);
     59          SubroutineCreater.CreateSubroutine(random, tree, MAX_TREE_LENGTH, MAX_TREE_DEPTH, 3, 3);
     60        } while (!HasAdfWithArguments(tree));
    6061        var success = ArgumentDuplicater.DuplicateArgument(random, tree, 3, 3);
    6162        Assert.IsTrue(success);
     
    7475      if (tree.Root.SubTrees.Count() != 2) return false;
    7576      var firstAdf = tree.Root.GetSubTree(1);
    76       return firstAdf.Grammar.GetAllowedSymbols(firstAdf.Symbol, 0).Where(x => x is Argument).Count() == 1;
     77      return firstAdf.Grammar.GetAllowedChildSymbols(firstAdf.Symbol, 0).Where(x => x is Argument).Count() == 1;
    7778    }
    7879  }
  • branches/DataAnalysis Refactoring/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Tests/ChangeNodeTypeManipulationTest.cs

    r5567 r5686  
    5555      int failedEvents = 0;
    5656      for (int i = 0; i < POPULATION_SIZE; i++) {
    57         var tree = ProbabilisticTreeCreator.Create(random, grammar, MAX_TREE_LENGTH, MAX_TREE_DEPTH, 3, 3);
     57        var tree = ProbabilisticTreeCreator.Create(random, grammar, MAX_TREE_LENGTH, MAX_TREE_DEPTH);
    5858        string originalTree = formatter.Format(tree);
    5959        ChangeNodeTypeManipulation.ChangeNodeType(random, tree);
  • branches/DataAnalysis Refactoring/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Tests/Grammars.cs

    r5567 r5686  
    9494    }
    9595
    96     private class SimpleArithmeticGrammar : DefaultSymbolicExpressionGrammar {
     96    private class SimpleArithmeticGrammar : SymbolicExpressionGrammar {
    9797      protected SimpleArithmeticGrammar(SimpleArithmeticGrammar original, Cloner cloner) : base(original, cloner) { }
    9898      public SimpleArithmeticGrammar()
     
    119119
    120120        foreach (var funSymb in functionSymbols) {
    121           SetMinSubtreeCount(funSymb, 1);
    122           SetMaxSubtreeCount(funSymb, 3);
     121          SetSubtreeCount(funSymb, 1, 3);
    123122        }
    124         SetMinSubtreeCount(terminal, 0);
    125         SetMaxSubtreeCount(terminal, 0);
     123        SetSubtreeCount(terminal, 0, 0);
    126124
     125        SetSubtreeCount(StartSymbol, 1, 1);
    127126        // allow each symbol as child of the start symbol
    128127        foreach (var symb in allSymbols) {
    129           SetAllowedChild(StartSymbol, symb, 0);
     128          AddAllowedChildSymbol(StartSymbol, symb);
     129          AddAllowedChildSymbol(DefunSymbol, symb);
    130130        }
    131131
    132132        // allow each symbol as child of every other symbol (except for terminals that have maxSubtreeCount == 0)
    133         foreach (var parent in allSymbols) {
    134           for (int i = 0; i < GetMaxSubtreeCount(parent); i++)
    135             foreach (var child in allSymbols) {
    136               SetAllowedChild(parent, child, i);
    137             }
     133        foreach (var parent in functionSymbols) {
     134          foreach (var child in allSymbols) {
     135            AddAllowedChildSymbol(parent, child);
     136          }
    138137        }
    139138      }
    140139    }
    141140
    142     public static ISymbolicExpressionTreeGrammar CreateSimpleArithmeticGrammar() {
    143       var g = new GlobalSymbolicExpressionGrammar(new SimpleArithmeticGrammar());
    144       g.MaxFunctionArguments = 0;
    145       g.MinFunctionArguments = 0;
    146       g.MaxFunctionDefinitions = 0;
    147       g.MinFunctionDefinitions = 0;
     141    public static ISymbolicExpressionGrammar CreateSimpleArithmeticGrammar() {
     142      var g = new SimpleArithmeticGrammar();
     143      g.MaximumFunctionArguments = 0;
     144      g.MinimumFunctionArguments = 0;
     145      g.MaximumFunctionDefinitions = 0;
     146      g.MinimumFunctionDefinitions = 0;
    148147      return g;
    149148    }
    150149
    151     public static ISymbolicExpressionTreeGrammar CreateArithmeticAndAdfGrammar() {
    152       var g = new GlobalSymbolicExpressionGrammar(new SimpleArithmeticGrammar());
    153       g.MaxFunctionArguments = 3;
    154       g.MinFunctionArguments = 0;
    155       g.MaxFunctionDefinitions = 3;
    156       g.MinFunctionDefinitions = 0;
     150    public static ISymbolicExpressionGrammar CreateArithmeticAndAdfGrammar() {
     151      var g = new SimpleArithmeticGrammar();
     152      g.MaximumFunctionArguments = 3;
     153      g.MinimumFunctionArguments = 0;
     154      g.MaximumFunctionDefinitions = 3;
     155      g.MinimumFunctionDefinitions = 0;
    157156      return g;
    158157    }
  • branches/DataAnalysis Refactoring/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Tests/ProbabilisticTreeCreaterTest.cs

    r5549 r5686  
    2222using System;
    2323using System.Collections.Generic;
     24using System.Diagnostics;
    2425using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
    2526using HeuristicLab.Random;
    2627using Microsoft.VisualStudio.TestTools.UnitTesting;
    27 using System.Diagnostics;
    2828
    2929namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding_3._4.Tests {
     
    5656      stopwatch.Start();
    5757      for (int i = 0; i < POPULATION_SIZE; i++) {
    58         randomTrees.Add(ProbabilisticTreeCreator.Create(random, grammar, MAX_TREE_LENGTH, MAX_TREE_DEPTH, 0, 0));
     58        randomTrees.Add(ProbabilisticTreeCreator.Create(random, grammar, MAX_TREE_LENGTH, MAX_TREE_DEPTH));
    5959      }
    6060      stopwatch.Stop();
     
    7272        Util.GetTerminalDistributionString(randomTrees) + Environment.NewLine
    7373        );
    74       Assert.IsTrue(Math.Round(1000.0 / (msPerRandomTreeCreation)) > 2000); // must achieve more than 2000 random trees / s
    75     }
    76 
    77 
    78     [TestMethod()]
    79     public void ProbabilisticTreeCreaterWithAdfDistributionsTest() {
    80       var randomTrees = new List<ISymbolicExpressionTree>();
    81       var grammar = Grammars.CreateArithmeticAndAdfGrammar();
    82       var random = new MersenneTwister(31415);
    83       var stopwatch = new Stopwatch();
    84       stopwatch.Start();
    85       for (int i = 0; i < POPULATION_SIZE; i++) {
    86         var tree = ProbabilisticTreeCreator.Create(random, grammar, MAX_TREE_LENGTH, MAX_TREE_DEPTH, 3, 3);
    87         randomTrees.Add(tree);
    88       }
    89       stopwatch.Stop();
    90       foreach (var tree in randomTrees)
    91         Util.IsValid(tree);
    92 
    93       double msPerRandomTreeCreation = stopwatch.ElapsedMilliseconds / (double)POPULATION_SIZE;
    94 
    95       Console.WriteLine("ProbabilisticTreeCreator: " + Environment.NewLine +
    96         msPerRandomTreeCreation + " ms per random tree (~" + Math.Round(1000.0 / (msPerRandomTreeCreation)) + "random trees / s)" + Environment.NewLine +
    97         Util.GetSizeDistributionString(randomTrees, 105, 5) + Environment.NewLine +
    98         Util.GetFunctionDistributionString(randomTrees) + Environment.NewLine +
    99         Util.GetNumberOfSubTreesDistributionString(randomTrees) + Environment.NewLine +
    100         Util.GetTerminalDistributionString(randomTrees) + Environment.NewLine
    101         );
    102 
    103       Assert.IsTrue(Math.Round(1000.0 / (msPerRandomTreeCreation)) > 2000); // must achieve more than 2000 random trees / s
     74      Assert.IsTrue(Math.Round(1000.0 / (msPerRandomTreeCreation)) > 500); // must achieve more than 500 random trees / s
    10475    }
    10576  }
  • branches/DataAnalysis Refactoring/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Tests/ReplaceBranchManipulationTest.cs

    r5549 r5686  
    5454      var random = new MersenneTwister(31415);
    5555      for (int i = 0; i < POPULATION_SIZE; i++) {
    56         var tree = ProbabilisticTreeCreator.Create(random, grammar, MAX_TREE_LENGTH, MAX_TREE_DEPTH, 3, 3);
     56        var tree = ProbabilisticTreeCreator.Create(random, grammar, MAX_TREE_LENGTH, MAX_TREE_DEPTH);
     57        SubroutineCreater.CreateSubroutine(random, tree, MAX_TREE_LENGTH, MAX_TREE_DEPTH, 3, 3);
    5758        string originalTree = formatter.Format(tree);
    5859        ReplaceBranchManipulation.ReplaceRandomBranch(random, tree, MAX_TREE_LENGTH, MAX_TREE_DEPTH);
  • branches/DataAnalysis Refactoring/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Tests/SubroutineCreaterTest.cs

    r5549 r5686  
    2121
    2222using System;
    23 using System.Linq;
    2423using System.Collections.Generic;
    2524using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
     
    5554      for (int i = 0; i < POPULATION_SIZE; i++) {
    5655        ISymbolicExpressionTree tree = null;
    57         do {
    58           tree = ProbabilisticTreeCreator.Create(random, grammar, MAX_TREE_LENGTH, MAX_TREE_DEPTH, 3, 3);
    59         } while ( !OneMoreAdfAllowed(tree));
     56        tree = ProbabilisticTreeCreator.Create(random, grammar, MAX_TREE_LENGTH - 10, MAX_TREE_DEPTH);
    6057        var success = SubroutineCreater.CreateSubroutine(random, tree, MAX_TREE_LENGTH, MAX_TREE_DEPTH, 3, 3);
    6158        Assert.IsTrue(success);
     
    7067        );
    7168    }
    72 
    73     private bool OneMoreAdfAllowed(ISymbolicExpressionTree tree) {
    74       return tree.Length < 80 && tree.Root.SubTrees.Count() < 4;
    75     }
    7669  }
    7770}
  • branches/DataAnalysis Refactoring/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Tests/SubroutineDeleterTest.cs

    r5549 r5686  
    2121
    2222using System;
     23using System.Collections.Generic;
    2324using System.Linq;
    24 using System.Collections.Generic;
    2525using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
    2626using HeuristicLab.Random;
     
    5656        ISymbolicExpressionTree tree = null;
    5757        do {
    58           tree = ProbabilisticTreeCreator.Create(random, grammar, MAX_TREE_LENGTH, MAX_TREE_DEPTH, 3, 3);
     58          tree = ProbabilisticTreeCreator.Create(random, grammar, MAX_TREE_LENGTH, MAX_TREE_DEPTH);
     59          SubroutineCreater.CreateSubroutine(random, tree, MAX_TREE_LENGTH, MAX_TREE_DEPTH, 3, 3);
     60          SubroutineCreater.CreateSubroutine(random, tree, MAX_TREE_LENGTH, MAX_TREE_DEPTH, 3, 3);
    5961        } while (!HasAtLeastOneAdf(tree));
    6062        var success = SubroutineDeleter.DeleteSubroutine(random, tree, 3, 3);
  • branches/DataAnalysis Refactoring/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Tests/SubroutineDuplicaterTest.cs

    r5549 r5686  
    2121
    2222using System;
     23using System.Collections.Generic;
    2324using System.Linq;
    24 using System.Collections.Generic;
    2525using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
    2626using HeuristicLab.Random;
     
    5656        ISymbolicExpressionTree tree = null;
    5757        do {
    58           tree = ProbabilisticTreeCreator.Create(random, grammar, MAX_TREE_LENGTH, MAX_TREE_DEPTH, 3, 3);
     58          tree = ProbabilisticTreeCreator.Create(random, grammar, MAX_TREE_LENGTH, MAX_TREE_DEPTH);
     59          for (int j = random.Next(3); j < 3; j++)
     60            SubroutineCreater.CreateSubroutine(random, tree, 100, 10, 3, 3);
    5961        } while (!HasOneAdf(tree));
    6062        var success = SubroutineDuplicater.DuplicateSubroutine(random, tree, 3, 3);
  • branches/DataAnalysis Refactoring/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Tests/SubtreeCrossoverTest.cs

    r5549 r5686  
    5656
    5757      for (int i = 0; i < POPULATION_SIZE; i++) {
    58         trees.Add(ProbabilisticTreeCreator.Create(random, grammar, 100, 10, 3, 3));
     58        trees.Add(ProbabilisticTreeCreator.Create(random, grammar, 100, 10));
     59        for (int j = random.Next(3); j < 3; j++)
     60          SubroutineCreater.CreateSubroutine(random, trees[i], 100, 10, 3, 3);
    5961      }
    6062      Stopwatch stopwatch = new Stopwatch();
     
    8385        );
    8486
    85       Assert.IsTrue(Math.Round(1000.0 / (msPerCrossoverEvent)) > 2000); // must achieve more than 2000 x-overs/s
     87      Assert.IsTrue(Math.Round(1000.0 / (msPerCrossoverEvent)) > 2500); // must achieve more than 1500 x-overs/s
    8688    }
    8789  }
  • branches/DataAnalysis Refactoring/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Tests/Util.cs

    r5549 r5686  
    120120      foreach (var defunTreeNode in tree.Root.SubTrees.OfType<DefunTreeNode>()) {
    121121        int arity = defunTreeNode.NumberOfArguments;
     122
     123        foreach (var argTreenode in defunTreeNode.IterateNodesPrefix().OfType<ArgumentTreeNode>()) {
     124          Assert.IsTrue(argTreenode.SubtreesCount == 0);
     125          Assert.IsTrue(((Argument)argTreenode.Symbol).ArgumentIndex < arity);
     126        }
     127
     128        foreach (var argSymbol in Enumerable.Range(0, defunTreeNode.NumberOfArguments).Select(x => new Argument(x))) {
     129          Assert.IsTrue(defunTreeNode.Grammar.ContainsSymbol(argSymbol));
     130          Assert.IsTrue(defunTreeNode.Grammar.GetMaximumSubtreeCount(argSymbol) == 0);
     131          Assert.IsTrue(defunTreeNode.Grammar.GetMinimumSubtreeCount(argSymbol) == 0);
     132        }
     133
    122134        var invoke = new InvokeFunction(defunTreeNode.FunctionName);
    123135        foreach (var otherRootNode in tree.Root.SubTrees) {
    124136          if (otherRootNode.Grammar.ContainsSymbol(invoke)) {
    125             Assert.IsTrue(otherRootNode.Grammar.GetMinSubtreeCount(invoke) == arity);
    126             Assert.IsTrue(otherRootNode.Grammar.GetMaxSubtreeCount(invoke) == arity);
     137            Assert.IsTrue(otherRootNode.Grammar.GetMinimumSubtreeCount(invoke) == arity);
     138            Assert.IsTrue(otherRootNode.Grammar.GetMaximumSubtreeCount(invoke) == arity);
    127139          }
    128140        }
     141
    129142      }
    130       //Assert.AreEqual(tree.Root.Symbol, tree.Root.Grammar.StartSymbol);
    131       foreach (var subtree in tree.Root.SubTrees)
     143      foreach (var subtree in tree.Root.SubTrees) {
    132144        Assert.AreNotSame(subtree.Grammar, tree.Root.Grammar);
     145        IsValid(subtree.Grammar);
     146      }
     147
     148      IsValid(tree.Root.Grammar);
    133149      IsValid(tree.Root);
     150    }
     151
     152    public static void IsValid(ISymbolicExpressionTreeGrammar grammar) {
     153      Assert.IsTrue(grammar.Symbols.Count() == grammar.Symbols.Distinct().Count());
     154      foreach (ISymbol symbol in grammar.Symbols) {
     155        Assert.IsTrue(grammar.GetMinimumSubtreeCount(symbol) <= grammar.GetMaximumExpressionLength(symbol));
     156        Assert.IsTrue(grammar.GetAllowedChildSymbols(symbol).Count() == grammar.GetAllowedChildSymbols(symbol).Distinct().Count());
     157        for (int i = 0; i < grammar.GetMaximumSubtreeCount(symbol); i++) {
     158          Assert.IsTrue(grammar.GetAllowedChildSymbols(symbol, i).Count() == grammar.GetAllowedChildSymbols(symbol, i).Distinct().Count());
     159        }
     160      }
    134161    }
    135162
     
    138165                            where symb.Name == treeNode.Symbol.Name
    139166                            select symb).SingleOrDefault();
    140       Assert.IsTrue(treeNode.SubTrees.Count() >= treeNode.Grammar.GetMinSubtreeCount(matchingSymbol));
    141       Assert.IsTrue(treeNode.SubTrees.Count() <= treeNode.Grammar.GetMaxSubtreeCount(matchingSymbol));
     167      Assert.IsTrue(treeNode.SubTrees.Count() >= treeNode.Grammar.GetMinimumSubtreeCount(matchingSymbol));
     168      Assert.IsTrue(treeNode.SubTrees.Count() <= treeNode.Grammar.GetMaximumSubtreeCount(matchingSymbol));
    142169      Assert.AreNotEqual(0.0, matchingSymbol.InitialFrequency); // check that no deactivated symbols occur in the tree
    143170      for (int i = 0; i < treeNode.SubTrees.Count(); i++) {
    144         Assert.IsTrue(treeNode.Grammar.GetAllowedSymbols(treeNode.Symbol, i).Select(x => x.Name).Contains(treeNode.GetSubTree(i).Symbol.Name));
     171        Assert.IsTrue(treeNode.Grammar.GetAllowedChildSymbols(treeNode.Symbol, i).Select(x => x.Name).Contains(treeNode.GetSubTree(i).Symbol.Name));
    145172        IsValid(treeNode.GetSubTree(i));
    146173      }
Note: See TracChangeset for help on using the changeset viewer.