Changeset 5686 for branches/DataAnalysis Refactoring/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding
- Timestamp:
- 03/15/11 13:34:38 (14 years ago)
- 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 22 22 using System; 23 23 using System.Collections.Generic; 24 using System.Diagnostics; 24 25 using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding; 25 26 using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Creators; … … 30 31 [TestClass] 31 32 public class ProbabilisticTreeCreaterTest { 32 private const int POPULATION_SIZE = 1000 ;33 private const int POPULATION_SIZE = 10000; 33 34 private const int MAX_TREE_SIZE = 100; 34 35 private const int MAX_TREE_HEIGHT = 10; … … 53 54 var grammar = Grammars.CreateSimpleArithmeticGrammar(); 54 55 var random = new MersenneTwister(31415); 56 var stopwatch = new Stopwatch(); 57 stopwatch.Start(); 55 58 for (int i = 0; i < POPULATION_SIZE; i++) { 56 59 randomTrees.Add(ProbabilisticTreeCreator.Create(random, grammar, MAX_TREE_SIZE, MAX_TREE_HEIGHT, 0, 0)); 57 60 } 61 stopwatch.Stop(); 58 62 59 63 foreach (var tree in randomTrees) { 60 64 Util.IsValid(tree); 61 65 } 66 double msPerRandomTreeCreation = stopwatch.ElapsedMilliseconds / (double)POPULATION_SIZE; 67 62 68 Console.WriteLine("ProbabilisticTreeCreator: " + Environment.NewLine + 69 msPerRandomTreeCreation + " ms per random tree (~" + Math.Round(1000.0 / (msPerRandomTreeCreation)) + "random trees / s)" + Environment.NewLine + 63 70 Util.GetSizeDistributionString(randomTrees, 105, 5) + Environment.NewLine + 64 71 Util.GetFunctionDistributionString(randomTrees) + Environment.NewLine + … … 66 73 Util.GetTerminalDistributionString(randomTrees) + Environment.NewLine 67 74 ); 75 Assert.IsTrue(Math.Round(1000.0 / (msPerRandomTreeCreation)) > 2000); // must achieve more than 2000 random trees / s 68 76 } 69 77 … … 74 82 var grammar = Grammars.CreateArithmeticAndAdfGrammar(); 75 83 var random = new MersenneTwister(31415); 84 var stopwatch = new Stopwatch(); 85 stopwatch.Start(); 76 86 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) 78 91 Util.IsValid(tree); 79 randomTrees.Add(tree); 80 } 92 93 double msPerRandomTreeCreation = stopwatch.ElapsedMilliseconds / (double)POPULATION_SIZE; 94 81 95 Console.WriteLine("ProbabilisticTreeCreator: " + Environment.NewLine + 96 msPerRandomTreeCreation + " ms per random tree (~" + Math.Round(1000.0 / (msPerRandomTreeCreation)) + "random trees / s)" + Environment.NewLine + 82 97 Util.GetSizeDistributionString(randomTrees, 105, 5) + Environment.NewLine + 83 98 Util.GetFunctionDistributionString(randomTrees) + Environment.NewLine + … … 85 100 Util.GetTerminalDistributionString(randomTrees) + Environment.NewLine 86 101 ); 102 103 Assert.IsTrue(Math.Round(1000.0 / (msPerRandomTreeCreation)) > 2000); // must achieve more than 2000 random trees / s 87 104 } 88 105 } -
branches/DataAnalysis Refactoring/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/ArchitectureManipulators/ArgumentCreater.cs
r5549 r5686 26 26 using HeuristicLab.Core; 27 27 using HeuristicLab.Data; 28 using HeuristicLab.Parameters; 28 29 using HeuristicLab.Persistence.Default.CompositeSerializers.Storable; 29 using HeuristicLab.Parameters;30 30 31 31 namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding { … … 126 126 where node.SubTrees.Count() > 0 127 127 from subtree in node.SubTrees 128 select new { Parent = node, ReplacedChildIndex = node.IndexOfSubTree(subtree), ReplacedChild = subtree }).ToList();128 select new CutPoint(node, subtree)).ToList(); 129 129 130 130 if (cutPoints.Count() == 0) … … 133 133 var selectedCutPoint = cutPoints[random.Next(cutPoints.Count)]; 134 134 // 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); 138 138 139 139 // find all old invocations of the selected ADF and attach a cloned version of the replaced branch (with all argument-nodes expanded) … … 167 167 defunBranch.NumberOfArguments++; 168 168 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); 171 170 // allow the argument as child of any other symbol 172 171 foreach (var symb in defunBranch.Grammar.Symbols) 173 for (int i = 0; i < defunBranch.Grammar.GetMax SubtreeCount(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); 175 174 } 176 175 foreach (var subtree in tree.Root.SubTrees) { … … 178 177 var matchingSymbol = subtree.Grammar.Symbols.OfType<InvokeFunction>().Where(s => s.FunctionName == defunBranch.FunctionName).SingleOrDefault(); 179 178 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); 185 183 } 186 184 } -
branches/DataAnalysis Refactoring/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/ArchitectureManipulators/ArgumentDeleter.cs
r5510 r5686 84 84 var matchingInvokeSymbol = subtree.Grammar.Symbols.OfType<InvokeFunction>().Where(s => s.FunctionName == selectedDefunBranch.FunctionName).SingleOrDefault(); 85 85 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); 88 87 } 89 88 } -
branches/DataAnalysis Refactoring/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/ArchitectureManipulators/ArgumentDuplicater.cs
r5529 r5686 107 107 // register the new argument symbol and increase the number of arguments of the ADF 108 108 selectedDefunBranch.Grammar.AddSymbol(newArgSymbol); 109 selectedDefunBranch.Grammar.SetMinSubtreeCount(newArgSymbol, 0); 110 selectedDefunBranch.Grammar.SetMaxSubtreeCount(newArgSymbol, 0); 109 selectedDefunBranch.Grammar.SetSubtreeCount(newArgSymbol, 0, 0); 111 110 // allow the argument as child of any other symbol 112 111 foreach (var symb in selectedDefunBranch.Grammar.Symbols) 113 for (int i = 0; i < selectedDefunBranch.Grammar.GetMax SubtreeCount(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); 115 114 } 116 115 selectedDefunBranch.NumberOfArguments++; … … 122 121 select symb).SingleOrDefault(); 123 122 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); 129 127 } 130 128 } -
branches/DataAnalysis Refactoring/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/ArchitectureManipulators/GrammarModifier.cs
r5499 r5686 21 21 22 22 using System.Collections.Generic; 23 using System.Linq; 23 24 24 25 namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding { 25 26 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); 28 29 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); 33 31 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 } 34 43 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 } 42 58 } 43 59 } 44 60 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 } 56 76 } 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 } 64 78 } 65 79 } 66 67 80 } 68 81 } -
branches/DataAnalysis Refactoring/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/ArchitectureManipulators/SubroutineCreater.cs
r5549 r5686 27 27 using HeuristicLab.Core; 28 28 using HeuristicLab.Data; 29 using HeuristicLab.Parameters; 29 30 using HeuristicLab.Persistence.Default.CompositeSerializers.Storable; 30 using HeuristicLab.Parameters;31 31 32 32 namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding { … … 61 61 private SubroutineCreater(bool deserializing) : base(deserializing) { } 62 62 private SubroutineCreater(SubroutineCreater original, Cloner cloner) : base(original, cloner) { } 63 public SubroutineCreater() : base() { 63 public SubroutineCreater() 64 : base() { 64 65 Parameters.Add(new ValueLookupParameter<IntValue>(MaximumSymbolicExpressionTreeLengthParameterName, "The maximal length (number of nodes) of the symbolic expression tree.")); 65 66 Parameters.Add(new ValueLookupParameter<IntValue>(MaximumSymbolicExpressionTreeDepthParameterName, "The maximal depth of the symbolic expression tree (a tree with one node has depth = 0).")); … … 109 110 110 111 // select a random cut point in the selected branch 111 var allCutPoints = from parent in selectedBody.IterateNodesPrefix()112 from subtree in parent.SubTrees113 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(); 114 115 if (allCutPoints.Count() == 0) 115 116 // no cut points => abort … … 118 119 var selectedCutPoint = allCutPoints.SelectRandom(random); 119 120 // 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; 122 123 // disconnect the function body from the tree 123 selectedCutPoint.Parent.RemoveSubTree(selectedCutPoint. ReplacedBranchIndex);124 selectedCutPoint.Parent.RemoveSubTree(selectedCutPoint.ChildIndex); 124 125 // disconnect the argument branches from the function 125 functionBody = DisconnectBranches(functionBody, argument Branches);126 functionBody = DisconnectBranches(functionBody, argumentCutPoints); 126 127 // insert a function invocation symbol instead 127 128 var invokeNode = (InvokeFunctionTreeNode)(new InvokeFunction(newFunctionName)).CreateTreeNode(); 128 selectedCutPoint.Parent.InsertSubTree(selectedCutPoint. ReplacedBranchIndex, invokeNode);129 selectedCutPoint.Parent.InsertSubTree(selectedCutPoint.ChildIndex, invokeNode); 129 130 // add the branches selected as argument as subtrees of the function invocation node 130 foreach (var argument Branch in argumentBranches)131 invokeNode.AddSubTree(argument Branch);131 foreach (var argumentCutPoint in argumentCutPoints) 132 invokeNode.AddSubTree(argumentCutPoint.Child); 132 133 133 134 // insert a new function defining branch … … 138 139 // the grammar in the newly defined function is a clone of the grammar of the originating branch 139 140 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(); 142 143 foreach (var oldArgSymb in oldArgumentSymbols) 143 144 defunNode.Grammar.RemoveSymbol(oldArgSymb); … … 146 147 select node.Symbol.ArgumentIndex).Distinct(); 147 148 // add argument symbols to grammar of function defining branch 148 GrammarModifier.Add DynamicArguments(defunNode.Grammar, defunNode.Symbol, newArgumentIndexes);149 GrammarModifier.AddArgumentSymbol(selectedBody.Grammar, defunNode.Grammar, newArgumentIndexes, argumentCutPoints); 149 150 defunNode.NumberOfArguments = newArgumentIndexes.Count(); 150 if (defunNode.NumberOfArguments != argument Branches.Count) throw new InvalidOperationException();151 if (defunNode.NumberOfArguments != argumentCutPoints.Count) throw new InvalidOperationException(); 151 152 // 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); 159 154 160 155 // when the new function body was taken from another function definition … … 168 163 // when the original branch can be invoked from the subtree then also allow invocation of the function 169 164 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); 177 166 } 178 167 } … … 181 170 } 182 171 183 private static ISymbolicExpressionTreeNode DisconnectBranches(ISymbolicExpressionTreeNode node, List< ISymbolicExpressionTreeNode> argumentBranches) {184 i f (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) { 186 175 var argSymbol = new Argument(argumentIndex); 187 176 return argSymbol.CreateTreeNode(); … … 192 181 // recursively apply function for subtrees or append a argument terminal node 193 182 foreach (var subtree in subtrees) { 194 node.AddSubTree(DisconnectBranches(subtree, argument Branches));183 node.AddSubTree(DisconnectBranches(subtree, argumentCutPoints)); 195 184 } 196 185 return node; 197 186 } 198 187 199 private static List< ISymbolicExpressionTreeNode> SelectRandomArgumentBranches(ISymbolicExpressionTreeNode selectedRoot,188 private static List<CutPoint> SelectRandomArgumentBranches(ISymbolicExpressionTreeNode selectedRoot, 200 189 IRandom random, 201 190 double cutProbability, … … 203 192 // breadth first determination of argument cut-off points 204 193 // 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>(); 206 195 if (selectedRoot is ArgumentTreeNode) { 207 argumentBranches.Add( selectedRoot);196 argumentBranches.Add(new CutPoint(selectedRoot.Parent, selectedRoot)); 208 197 return argumentBranches; 209 198 } else { … … 213 202 select nArgumentsInTree).ToList(); 214 203 // 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 215 205 var minNewArgumentsForSubtrees = numberOfArgumentsInSubtrees.Select(x => x > 0 ? 1 : 0).ToList(); 216 206 if (minNewArgumentsForSubtrees.Sum() > maxArguments) { 217 argumentBranches.Add( selectedRoot);207 argumentBranches.Add(new CutPoint(selectedRoot.Parent, selectedRoot)); 218 208 return argumentBranches; 219 209 } 220 210 // cut-off in the sub-trees in random order 221 211 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); 223 215 foreach (var subtreeIndex in randomIndexes) { 224 216 var subtree = selectedRoot.GetSubTree(subtreeIndex); … … 237 229 } else { 238 230 // cut-off at current sub-tree 239 argumentBranches.Add( subtree);231 argumentBranches.Add(new CutPoint(subtree.Parent, subtree)); 240 232 } 241 233 } -
branches/DataAnalysis Refactoring/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/ArchitectureManipulators/SubroutineDeleter.cs
r5549 r5686 26 26 using HeuristicLab.Data; 27 27 using HeuristicLab.Persistence.Default.CompositeSerializers.Storable; 28 using System.Collections.Generic;29 28 30 29 namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding { … … 87 86 from subtree in node.SubTrees.OfType<InvokeFunctionTreeNode>() 88 87 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(); 90 89 while (invocationCutPoint != null) { 91 90 // deletion by random regeneration 92 91 ISymbolicExpressionTreeNode replacementTree = null; 93 var allowedSymbolsList = invocationCutPoint.Parent.Grammar.GetAllowed Symbols(invocationCutPoint.Parent.Symbol, invocationCutPoint.ReplacedChildIndex).ToList();92 var allowedSymbolsList = invocationCutPoint.Parent.Grammar.GetAllowedChildSymbols(invocationCutPoint.Parent.Symbol, invocationCutPoint.ChildIndex).ToList(); 94 93 var weights = allowedSymbolsList.Select(s => s.InitialFrequency); 95 94 var selectedSymbol = allowedSymbolsList.SelectRandom(weights, random); 96 95 97 int minPossibleLength = invocationCutPoint.Parent.Grammar.GetMin ExpressionLength(selectedSymbol);98 int maxLength = Math.Max(minPossibleLength, invocationCutPoint. ReplacedChild.GetLength());99 int minPossibleDepth = invocationCutPoint.Parent.Grammar.GetMin ExpressionDepth(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()); 101 100 replacementTree = selectedSymbol.CreateTreeNode(); 102 101 if (replacementTree.HasLocalParameters) 103 102 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); 106 105 107 ProbabilisticTreeCreator.PTC2(random, replacementTree, maxLength, maxDepth , 0, 0);106 ProbabilisticTreeCreator.PTC2(random, replacementTree, maxLength, maxDepth); 108 107 109 108 invocationCutPoint = (from node in symbolicExpressionTree.IterateNodesPrefix() 110 109 from subtree in node.SubTrees.OfType<InvokeFunctionTreeNode>() 111 110 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(); 113 112 } 114 113 } -
branches/DataAnalysis Refactoring/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/ArchitectureManipulators/SubroutineDuplicater.cs
r5510 r5686 79 79 select symb).SingleOrDefault(); 80 80 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 } 82 102 } 83 103 // in the current subtree: -
branches/DataAnalysis Refactoring/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Creators/ProbabilisticTreeCreator.cs
r5618 r5686 23 23 using System.Collections.Generic; 24 24 using System.Linq; 25 using System.Text;26 25 using HeuristicLab.Common; 27 26 using HeuristicLab.Core; … … 34 33 [Item("ProbabilisticTreeCreator", "An operator that creates new symbolic expression trees with uniformly distributed length")] 35 34 public class ProbabilisticTreeCreator : SymbolicExpressionTreeCreator, 36 ISymbolicExpressionTreeSizeConstraintOperator, ISymbolicExpressionTreeGrammarBasedOperator , ISymbolicExpressionTreeArchitectureAlteringOperator{35 ISymbolicExpressionTreeSizeConstraintOperator, ISymbolicExpressionTreeGrammarBasedOperator { 37 36 private const int MAX_TRIES = 100; 38 37 private const string MaximumSymbolicExpressionTreeLengthParameterName = "MaximumSymbolicExpressionTreeLength"; 39 38 private const string MaximumSymbolicExpressionTreeDepthParameterName = "MaximumSymbolicExpressionTreeDepth"; 40 private const string MaximumFunctionDefinitionsParameterName = "MaximumFunctionDefinitions";41 private const string MaximumFunctionArgumentsParameterName = "MaximumFunctionArguments";42 39 private const string SymbolicExpressionTreeGrammarParameterName = "SymbolicExpressionTreeGrammar"; 43 40 #region Parameter Properties … … 48 45 get { return (IValueLookupParameter<IntValue>)Parameters[MaximumSymbolicExpressionTreeDepthParameterName]; } 49 46 } 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]; } 58 49 } 59 50 #endregion … … 65 56 get { return MaximumSymbolicExpressionTreeDepthParameter.ActualValue; } 66 57 } 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 { 74 59 get { return SymbolicExpressionTreeGrammarParameter.ActualValue; } 75 60 } … … 83 68 Parameters.Add(new ValueLookupParameter<IntValue>(MaximumSymbolicExpressionTreeLengthParameterName, "The maximal length (number of nodes) of the symbolic expression tree.")); 84 69 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.")); 88 71 } 89 72 … … 93 76 94 77 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) { 103 84 SymbolicExpressionTree tree = new SymbolicExpressionTree(); 104 var rootNode = (SymbolicExpressionTreeTopLevelNode)grammar. StartSymbol.CreateTreeNode();85 var rootNode = (SymbolicExpressionTreeTopLevelNode)grammar.ProgramRootSymbol.CreateTreeNode(); 105 86 if (rootNode.HasLocalParameters) rootNode.ResetLocalParameters(random); 106 87 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; 108 94 return tree; 109 95 } … … 115 101 } 116 102 117 public static ISymbolicExpressionTreeNodePTC2(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) { 119 105 // tree length is limited by the grammar and by the explicit size constraints 120 int allowedMinLength = seedNode.Grammar.GetMin ExpressionLength(seedNode.Symbol);121 int allowedMaxLength = Math.Min(maxLength, seedNode.Grammar.GetMax ExpressionLength(seedNode.Symbol));106 int allowedMinLength = seedNode.Grammar.GetMinimumExpressionLength(seedNode.Symbol); 107 int allowedMaxLength = Math.Min(maxLength, seedNode.Grammar.GetMaximumExpressionLength(seedNode.Symbol)); 122 108 int tries = 0; 123 109 while (tries++ < MAX_TRIES) { … … 125 111 int targetTreeLength; 126 112 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); 130 116 131 117 // if successful => check constraints and return the tree if everything looks ok 132 118 if (success && seedNode.GetLength() <= maxLength && seedNode.GetDepth() <= maxDepth) { 133 return seedNode;119 return; 134 120 } else { 135 121 // clean seedNode … … 142 128 143 129 private static bool CreateFullTreeFromSeed(IRandom random, ISymbolicExpressionTreeNode root, ISymbolicExpressionTreeGrammar globalGrammar, 144 int targetLength, int maxDepth , int maxFunctionDefinitions, int maxFunctionArguments) {130 int targetLength, int maxDepth) { 145 131 try { 146 TryCreateFullTreeFromSeed(random, root, globalGrammar, targetLength, maxDepth , maxFunctionDefinitions, maxFunctionArguments);132 TryCreateFullTreeFromSeed(random, root, globalGrammar, targetLength, maxDepth); 147 133 return true; 148 134 } … … 151 137 152 138 private static void TryCreateFullTreeFromSeed(IRandom random, ISymbolicExpressionTreeNode root, ISymbolicExpressionTreeGrammar globalGrammar, 153 int targetLength, int maxDepth , int maxFunctionDefinitions, int maxFunctionArguments) {139 int targetLength, int maxDepth) { 154 140 List<TreeExtensionPoint> extensionPoints = new List<TreeExtensionPoint>(); 155 141 int currentLength = 1; 156 int totalListMinLength = globalGrammar.GetMin ExpressionLength(root.Symbol) - 1;142 int totalListMinLength = globalGrammar.GetMinimumExpressionLength(root.Symbol) - 1; 157 143 int actualArity = SampleArity(random, root, targetLength); 158 144 for (int i = 0; i < actualArity; i++) { … … 170 156 int argumentIndex = nextExtension.ChildIndex; 171 157 int extensionDepth = nextExtension.ExtensionPointDepth; 172 if (extensionDepth + parent.Grammar.GetMin ExpressionDepth(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); 174 160 } else { 175 161 var allowedSymbols = (from s in parent.Grammar.Symbols 176 where parent.Grammar.IsAllowedChild (parent.Symbol, s, argumentIndex)177 where parent.Grammar.GetMin ExpressionDepth(s) + extensionDepth - 1 < maxDepth178 where parent.Grammar.GetMax ExpressionLength(s) > targetLength - totalListMinLength - currentLength162 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 179 165 select s) 180 166 .ToList(); … … 186 172 parent.InsertSubTree(argumentIndex, newTree); 187 173 188 InitializeNewTreeNode(random, root, newTree, maxFunctionDefinitions, maxFunctionArguments); 174 var topLevelNode = newTree as SymbolicExpressionTreeTopLevelNode; 175 if (topLevelNode != null) 176 topLevelNode.SetGrammar((ISymbolicExpressionTreeGrammar)root.Grammar.Clone()); 189 177 190 178 currentLength++; … … 198 186 extensionPoints.Add(new TreeExtensionPoint { Parent = newTree, ChildIndex = i, ExtensionPointDepth = extensionDepth + 1 }); 199 187 } 200 totalListMinLength += newTree.Grammar.GetMin ExpressionLength(newTree.Symbol);188 totalListMinLength += newTree.Grammar.GetMinimumExpressionLength(newTree.Symbol); 201 189 } 202 190 } … … 209 197 int a = nextExtension.ChildIndex; 210 198 int d = nextExtension.ExtensionPointDepth; 211 ReplaceWithMinimalTree(random, root, parent, a , maxFunctionDefinitions, maxFunctionArguments);199 ReplaceWithMinimalTree(random, root, parent, a); 212 200 } 213 201 } 214 202 215 203 private static void ReplaceWithMinimalTree(IRandom random, ISymbolicExpressionTreeNode root, ISymbolicExpressionTreeNode parent, 216 int argumentIndex, int maxFunctionDefinitions, int maxFunctionArguments) {204 int childIndex) { 217 205 // determine possible symbols that will lead to the smallest possible tree 218 var possibleSymbols = (from s in parent.Grammar.GetAllowed Symbols(parent.Symbol, argumentIndex)219 group s by parent.Grammar.GetMin ExpressionLength(s) into g206 var possibleSymbols = (from s in parent.Grammar.GetAllowedChildSymbols(parent.Symbol, childIndex) 207 group s by parent.Grammar.GetMinimumExpressionLength(s) into g 220 208 orderby g.Key 221 209 select g).First().ToList(); … … 224 212 var tree = selectedSymbol.CreateTreeNode(); 225 213 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++) { 230 222 // insert a dummy sub-tree and add the pending extension to the list 231 223 var dummy = new SymbolicExpressionTreeNode(); 232 224 tree.AddSubTree(dummy); 233 225 // 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); 278 227 } 279 228 } … … 285 234 private static int SampleArity(IRandom random, ISymbolicExpressionTreeNode node, int targetLength) { 286 235 // select actualArity randomly with the constraint that the sub-trees in the minimal arity can become large enough 287 int minArity = node.Grammar.GetMin SubtreeCount(node.Symbol);288 int maxArity = node.Grammar.GetMax SubtreeCount(node.Symbol);236 int minArity = node.Grammar.GetMinimumSubtreeCount(node.Symbol); 237 int maxArity = node.Grammar.GetMaximumSubtreeCount(node.Symbol); 289 238 if (maxArity > targetLength) { 290 239 maxArity = targetLength; … … 294 243 long aggregatedLongestExpressionLength = 0; 295 244 for (int i = 0; i < maxArity; i++) { 296 aggregatedLongestExpressionLength += (from s in node.Grammar.GetAllowed Symbols(node.Symbol, i)297 select node.Grammar.GetMax ExpressionLength(s)).Max();245 aggregatedLongestExpressionLength += (from s in node.Grammar.GetAllowedChildSymbols(node.Symbol, i) 246 select node.Grammar.GetMaximumExpressionLength(s)).Max(); 298 247 if (aggregatedLongestExpressionLength < targetLength) minArity = i; 299 248 else break; … … 304 253 long aggregatedShortestExpressionLength = 0; 305 254 for (int i = 0; i < maxArity; i++) { 306 aggregatedShortestExpressionLength += (from s in node.Grammar.GetAllowed Symbols(node.Symbol, i)307 select node.Grammar.GetMin ExpressionLength(s)).Min();255 aggregatedShortestExpressionLength += (from s in node.Grammar.GetAllowedChildSymbols(node.Symbol, i) 256 select node.Grammar.GetMinimumExpressionLength(s)).Min(); 308 257 if (aggregatedShortestExpressionLength > targetLength) { 309 258 maxArity = i; -
branches/DataAnalysis Refactoring/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Crossovers/SubtreeCrossover.cs
r5549 r5686 120 120 // check syntax constraints of direct parent - child relation 121 121 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; 123 123 124 124 bool result = true; … … 128 128 result && 129 129 parent.Grammar.ContainsSymbol(n.Symbol) && 130 n.Sub Trees.Count() >= parent.Grammar.GetMinSubtreeCount(n.Symbol) &&131 n.Sub Trees.Count() <= parent.Grammar.GetMaxSubtreeCount(n.Symbol);130 n.SubtreesCount >= parent.Grammar.GetMinimumSubtreeCount(n.Symbol) && 131 n.SubtreesCount <= parent.Grammar.GetMaximumSubtreeCount(n.Symbol); 132 132 }); 133 133 return result; … … 136 136 private static void SelectCrossoverPoint(IRandom random, ISymbolicExpressionTree parent0, double internalNodeProbability, int maxBranchLength, int maxBranchDepth, out ISymbolicExpressionTreeNode crossoverPoint, out int subtreeIndex) { 137 137 if (internalNodeProbability < 0.0 || internalNodeProbability > 1.0) throw new ArgumentException("internalNodeProbability"); 138 List<C rossoverPoint> internalCrossoverPoints = new List<CrossoverPoint>();139 List<C rossoverPoint> leafCrossoverPoints = new List<CrossoverPoint>();138 List<CutPoint> internalCrossoverPoints = new List<CutPoint>(); 139 List<CutPoint> leafCrossoverPoints = new List<CutPoint>(); 140 140 parent0.Root.ForEachNodePostfix((n) => { 141 if (n.SubTrees. Count() > 0&& n != parent0.Root) {141 if (n.SubTrees.Any() && n != parent0.Root) { 142 142 foreach (var child in n.SubTrees) { 143 143 if (child.GetLength() <= maxBranchLength && 144 144 child.GetDepth() <= maxBranchDepth) { 145 if (child.SubTrees. Count() > 0)146 internalCrossoverPoints.Add(new C rossoverPoint(n, child));145 if (child.SubTrees.Any()) 146 internalCrossoverPoints.Add(new CutPoint(n, child)); 147 147 else 148 leafCrossoverPoints.Add(new C rossoverPoint(n, child));148 leafCrossoverPoints.Add(new CutPoint(n, child)); 149 149 } 150 150 } … … 158 158 var selectedCrossoverPoint = internalCrossoverPoints[random.Next(internalCrossoverPoints.Count)]; 159 159 crossoverPoint = selectedCrossoverPoint.Parent; 160 subtreeIndex = selectedCrossoverPoint. SubtreeIndex;160 subtreeIndex = selectedCrossoverPoint.ChildIndex; 161 161 } else { 162 162 // otherwise select external node 163 163 var selectedCrossoverPoint = leafCrossoverPoints[random.Next(leafCrossoverPoints.Count)]; 164 164 crossoverPoint = selectedCrossoverPoint.Parent; 165 subtreeIndex = selectedCrossoverPoint. SubtreeIndex;165 subtreeIndex = selectedCrossoverPoint.ChildIndex; 166 166 } 167 167 } else if (leafCrossoverPoints.Count > 0) { … … 169 169 var selectedCrossoverPoint = leafCrossoverPoints[random.Next(leafCrossoverPoints.Count)]; 170 170 crossoverPoint = selectedCrossoverPoint.Parent; 171 subtreeIndex = selectedCrossoverPoint. SubtreeIndex;171 subtreeIndex = selectedCrossoverPoint.ChildIndex; 172 172 } else { 173 173 // otherwise select internal crossover point 174 174 var selectedCrossoverPoint = internalCrossoverPoints[random.Next(internalCrossoverPoints.Count)]; 175 175 crossoverPoint = selectedCrossoverPoint.Parent; 176 subtreeIndex = selectedCrossoverPoint. SubtreeIndex;176 subtreeIndex = selectedCrossoverPoint.ChildIndex; 177 177 } 178 178 } … … 185 185 // select internal node if possible 186 186 allowedInternalBranches = (from branch in branches 187 where branch.SubTrees. Count() > 0187 where branch.SubTrees.Any() 188 188 select branch).ToList(); 189 189 if (allowedInternalBranches.Count > 0) { … … 192 192 // no internal nodes allowed => select leaf nodes 193 193 allowedLeafBranches = (from branch in branches 194 where branch.SubTrees.Count() == 0194 where !branch.SubTrees.Any() 195 195 select branch).ToList(); 196 196 return allowedLeafBranches.SelectRandom(random); … … 199 199 // select leaf node if possible 200 200 allowedLeafBranches = (from branch in branches 201 where branch.SubTrees.Count() == 0201 where !branch.SubTrees.Any() 202 202 select branch).ToList(); 203 203 if (allowedLeafBranches.Count > 0) { … … 205 205 } else { 206 206 allowedInternalBranches = (from branch in branches 207 where branch.SubTrees. Count() > 0207 where branch.SubTrees.Any() 208 208 select branch).ToList(); 209 209 return allowedInternalBranches.SelectRandom(random); -
branches/DataAnalysis Refactoring/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/CutPoint.cs
r5674 r5686 22 22 23 23 namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding { 24 internal class C rossoverPoint {24 internal class CutPoint { 25 25 public ISymbolicExpressionTreeNode Parent { get; set; } 26 26 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; } 29 30 } 30 public C rossoverPoint(ISymbolicExpressionTreeNode parent, ISymbolicExpressionTreeNode child) {31 public CutPoint(ISymbolicExpressionTreeNode parent, ISymbolicExpressionTreeNode child) { 31 32 this.Parent = parent; 32 33 this.Child = child; 34 this.childIndex = parent.IndexOfSubTree(child); 33 35 } 34 36 } -
branches/DataAnalysis Refactoring/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding-3.4.csproj
r5635 r5686 124 124 <Compile Include="Compiler\SymbolicExpressionTreeCompiler.cs" /> 125 125 <Compile Include="Interfaces\IReadOnlySymbol.cs" /> 126 <Compile Include="Interfaces\ISymbolicExpressionGrammar.cs" /> 127 <Compile Include="Interfaces\ISymbolicExpressionGrammarBase.cs" /> 126 128 <Compile Include="Interfaces\ISymbolicExpressionTreeGrammar.cs" /> 127 129 <Compile Include="Interfaces\Operators\ISymbolicExpressionTreeArchitectureAlteringOperator.cs" /> 128 130 <Compile Include="Interfaces\Operators\ISymbolicExpressionTreeGrammarBasedOperator.cs" /> 129 131 <Compile Include="Creators\SymbolicExpressionTreeCreator.cs" /> 130 <Compile Include="C rossovers\CrossoverPoint.cs" />132 <Compile Include="CutPoint.cs" /> 131 133 <Compile Include="Crossovers\SymbolicExpressionTreeCrossover.cs" /> 132 134 <Compile Include="Formatters\SymbolicExpressionTreeStringFormatter.cs" /> … … 147 149 <Compile Include="Manipulators\OnePointShaker.cs" /> 148 150 <Compile Include="Manipulators\SymbolicExpressionTreeManipulator.cs" /> 151 <Compile Include="SymbolicExpressionGrammarBase.cs" /> 152 <Compile Include="SymbolicExpressionGrammar.cs" /> 149 153 <Compile Include="SymbolicExpressionTreeGrammar.cs" /> 150 154 <Compile Include="SymbolicExpressionTreeTopLevelNode.cs" /> … … 152 156 <SubType>Code</SubType> 153 157 </Compile> 154 <Compile Include="GlobalSymbolicExpressionGrammar.cs" />155 158 <Compile Include="EnumerableExtensions.cs" /> 156 <Compile Include="DefaultSymbolicExpressionGrammar.cs">157 <SubType>Code</SubType>158 </Compile>159 159 <Compile Include="SymbolicExpressionTreeOperator.cs" /> 160 160 <Compile Include="SymbolicExpressionTreeTerminalNode.cs" /> -
branches/DataAnalysis Refactoring/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Interfaces/ISymbolicExpressionTreeGrammar.cs
r5529 r5686 21 21 22 22 using System.Collections.Generic; 23 using HeuristicLab.Core; 23 namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding { 24 public interface ISymbolicExpressionTreeGrammar : ISymbolicExpressionGrammarBase { 24 25 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); 29 28 void AddSymbol(ISymbol symbol); 30 29 void RemoveSymbol(ISymbol symbol); 31 30 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); 35 35 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); 46 37 } 47 38 } -
branches/DataAnalysis Refactoring/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Interfaces/ISymbolicExpressionTreeNode.cs
r5549 r5686 19 19 */ 20 20 #endregion 21 using System; 21 22 using System.Collections.Generic; 23 using HeuristicLab.Common; 22 24 using HeuristicLab.Core; 23 using System;24 using HeuristicLab.Common;25 25 namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding { 26 26 public interface ISymbolicExpressionTreeNode : IDeepCloneable { … … 39 39 40 40 IEnumerable<ISymbolicExpressionTreeNode> SubTrees { get; } 41 int SubtreesCount { get; } 41 42 ISymbolicExpressionTreeNode GetSubTree(int index); 42 43 int IndexOfSubTree(ISymbolicExpressionTreeNode tree); -
branches/DataAnalysis Refactoring/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Interfaces/Operators/ISymbolicExpressionTreeGrammarBasedOperator.cs
r5499 r5686 27 27 /// </summary> 28 28 public interface ISymbolicExpressionTreeGrammarBasedOperator : ISymbolicExpressionTreeOperator { 29 IValueLookupParameter<ISymbolicExpression TreeGrammar> SymbolicExpressionTreeGrammarParameter { get; }29 IValueLookupParameter<ISymbolicExpressionGrammar> SymbolicExpressionTreeGrammarParameter { get; } 30 30 } 31 31 } -
branches/DataAnalysis Refactoring/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Manipulators/ChangeNodeTypeManipulation.cs
r5567 r5686 20 20 #endregion 21 21 22 using System;23 using System.Collections.Generic;24 22 using System.Linq; 25 23 using HeuristicLab.Common; 26 24 using HeuristicLab.Core; 27 using HeuristicLab.Data;28 25 using HeuristicLab.Persistence.Default.CompositeSerializers.Storable; 29 26 … … 53 50 let existingSubtreeCount = subtree.SubTrees.Count() 54 51 // find possible symbols for the node (also considering the existing branches below it) 55 let allowedSymbols = (from symbol in parent.Grammar.GetAllowed Symbols(parent.Symbol, subtreeIndex)52 let allowedSymbols = (from symbol in parent.Grammar.GetAllowedChildSymbols(parent.Symbol, subtreeIndex) 56 53 // do not replace the existing symbol with itself 57 54 where symbol.Name != subtree.Symbol.Name 58 where existingSubtreeCount <= parent.Grammar.GetMax SubtreeCount(symbol)59 where existingSubtreeCount >= parent.Grammar.GetMin SubtreeCount(symbol)55 where existingSubtreeCount <= parent.Grammar.GetMaximumSubtreeCount(symbol) 56 where existingSubtreeCount >= parent.Grammar.GetMinimumSubtreeCount(symbol) 60 57 // keep only symbols that are still possible considering the existing sub-trees 61 58 where (from existingSubtreeIndex in Enumerable.Range(0, existingSubtreeCount) 62 59 let existingSubtree = subtree.GetSubTree(existingSubtreeIndex) 63 select parent.Grammar.IsAllowedChild (symbol, existingSubtree.Symbol, existingSubtreeIndex))60 select parent.Grammar.IsAllowedChildSymbol(symbol, existingSubtree.Symbol, existingSubtreeIndex)) 64 61 .All(x => x == true) 65 62 select symbol) -
branches/DataAnalysis Refactoring/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Manipulators/ReplaceBranchManipulation.cs
r5569 r5686 20 20 #endregion 21 21 22 using System;23 using System.Collections.Generic;24 22 using System.Linq; 25 23 using HeuristicLab.Common; 26 24 using HeuristicLab.Core; 27 25 using HeuristicLab.Data; 26 using HeuristicLab.Parameters; 28 27 using HeuristicLab.Persistence.Default.CompositeSerializers.Storable; 29 using HeuristicLab.Parameters;30 28 31 29 namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding { … … 77 75 let maxDepth = maxTreeDepth - symbolicExpressionTree.Depth + subtree.GetDepth() 78 76 // find possible symbols for the node (also considering the existing branches below it) 79 let allowedSymbols = (from symbol in parent.Grammar.GetAllowed Symbols(parent.Symbol, subtreeIndex)77 let allowedSymbols = (from symbol in parent.Grammar.GetAllowedChildSymbols(parent.Symbol, subtreeIndex) 80 78 // do not replace symbol with the same symbol 81 79 where symbol.Name != subtree.Symbol.Name 82 where parent.Grammar.GetMin ExpressionDepth(symbol) <= maxDepth83 where parent.Grammar.GetMin ExpressionLength(symbol) <= maxLength80 where parent.Grammar.GetMinimumExpressionDepth(symbol) <= maxDepth 81 where parent.Grammar.GetMinimumExpressionLength(symbol) <= maxLength 84 82 select symbol) 85 83 .ToList() … … 107 105 selectedManipulationPoint.Parent.RemoveSubTree(selectedManipulationPoint.Index); 108 106 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); 110 108 } 111 109 } -
branches/DataAnalysis Refactoring/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/SymbolicExpressionTreeGrammar.cs
r5499 r5686 20 20 #endregion 21 21 22 using System; 23 using System.Collections.Generic; 24 using System.Linq; 22 25 using HeuristicLab.Common; 23 26 using HeuristicLab.Persistence.Default.CompositeSerializers.Storable; 24 27 25 28 namespace 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 { 30 31 [StorableConstructor] 31 32 private SymbolicExpressionTreeGrammar(bool deserializing) : base(deserializing) { } 32 // don't call storable ctor of base class to prevent full cloning33 // instead use storable ctor to initialize an empty grammar and fill with InizializeShallowClone34 33 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; 38 36 } 39 private SymbolicExpressionTreeGrammar() : base() { }40 41 37 public override IDeepCloneable Clone(Cloner cloner) { 42 38 return new SymbolicExpressionTreeGrammar(this, cloner); 43 39 } 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 } 44 118 } 45 119 } -
branches/DataAnalysis Refactoring/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/SymbolicExpressionTreeNode.cs
r5549 r5686 22 22 using System; 23 23 using System.Collections.Generic; 24 using System.Linq;25 24 using HeuristicLab.Common; 26 25 using HeuristicLab.Core; … … 126 125 public virtual void ShakeLocalParameters(IRandom random, double shakingFactor) { } 127 126 127 public int SubtreesCount { 128 get { 129 if (subTrees == null) return 0; 130 return subTrees.Count; 131 } 132 } 133 128 134 public virtual ISymbolicExpressionTreeNode GetSubTree(int index) { 129 135 return subTrees[index]; -
branches/DataAnalysis Refactoring/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/SymbolicExpressionTreeTerminalNode.cs
r5510 r5686 22 22 using System; 23 23 using System.Collections.Generic; 24 using System.Linq; 24 25 using HeuristicLab.Common; 25 26 using HeuristicLab.Persistence.Default.CompositeSerializers.Storable; 26 using System.Linq;27 27 28 28 namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding { -
branches/DataAnalysis Refactoring/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Tests/AllArchitectureAlteringOperatorsTest.cs
r5549 r5686 56 56 var grammar = Grammars.CreateArithmeticAndAdfGrammar(); 57 57 var random = new MersenneTwister(31415); 58 SymbolicExpressionTreeStringFormatter formatter = new SymbolicExpressionTreeStringFormatter(); 58 59 IntValue maxTreeSize = new IntValue(MAX_TREE_LENGTH); 59 60 IntValue maxTreeHeigth = new IntValue(MAX_TREE_DEPTH); … … 61 62 IntValue maxArgs = new IntValue(3); 62 63 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); 64 65 Util.IsValid(tree); 65 66 trees.Add(tree); 66 67 } 67 68 Stopwatch stopwatch = new Stopwatch(); 68 stopwatch.Start();69 69 int failedEvents = 0; 70 70 for (int g = 0; g < N_ITERATIONS; g++) { … … 72 72 if (random.NextDouble() < 0.5) { 73 73 // manipulate 74 stopwatch.Start(); 74 75 var selectedTree = (ISymbolicExpressionTree)trees.SelectRandom(random).Clone(); 76 var oldTree = (ISymbolicExpressionTree)selectedTree.Clone(); 77 var oldFormatedTree = formatter.Format(oldTree); 75 78 bool success = false; 76 switch (random.Next(6)) { 79 int sw = random.Next(6); 80 switch (sw) { 77 81 case 0: success = ArgumentCreater.CreateNewArgument(random, selectedTree, MAX_TREE_LENGTH, MAX_TREE_DEPTH, 3, 3); break; 78 82 case 1: success = ArgumentDeleter.DeleteArgument(random, selectedTree, 3, 3); break; … … 82 86 case 5: success = SubroutineDeleter.DeleteSubroutine(random, selectedTree, 3, 3); break; 83 87 } 88 stopwatch.Stop(); 84 89 if (!success) failedEvents++; 90 var newFormatedTree = formatter.Format(selectedTree); 85 91 Util.IsValid(selectedTree); 86 92 newTrees.Add(selectedTree); … … 98 104 trees = newTrees; 99 105 } 100 stopwatch.Stop();101 106 var msPerOperation = stopwatch.ElapsedMilliseconds / (double)POPULATION_SIZE / (double)N_ITERATIONS; 102 107 Console.WriteLine("AllArchitectureAlteringOperators: " + Environment.NewLine + -
branches/DataAnalysis Refactoring/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Tests/ArgumentCreaterTest.cs
r5549 r5686 21 21 22 22 using System; 23 using System.Collections.Generic; 23 24 using System.Linq; 24 using System.Collections.Generic;25 25 using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding; 26 26 using HeuristicLab.Random; … … 57 57 ISymbolicExpressionTree tree; 58 58 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); 60 61 } while (!TreeHasAdfWithParameter(tree, 3)); 61 62 var success = ArgumentCreater.CreateNewArgument(random, tree, 60000, 100, 3, 3); … … 66 67 // difficult to make sure that create argument operations succeed because trees are macro-expanded can potentially become very big 67 68 // => just test if only a small proportion fails 68 Assert.IsTrue(failedOps < POPULATION_SIZE * 0.01 69 Assert.IsTrue(failedOps < POPULATION_SIZE * 0.01); // only 1% may fail 69 70 Console.WriteLine("ArgumentCreator: " + Environment.NewLine + 70 71 "Failed operations: " + failedOps * 100.0 / POPULATION_SIZE + " %" + Environment.NewLine + … … 77 78 78 79 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; 80 81 var firstAdf = tree.Root.GetSubTree(1); 81 return firstAdf.Grammar.GetAllowed Symbols(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; 82 83 } 83 84 } -
branches/DataAnalysis Refactoring/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Tests/ArgumentDeleterTest.cs
r5549 r5686 56 56 ISymbolicExpressionTree tree = null; 57 57 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); 59 60 } while (!TreeHasAdfWithArguments(tree)); 60 61 var success = ArgumentDeleter.DeleteArgument(random, tree, 3, 3); … … 73 74 if (tree.Root.SubTrees.Count() != 2) return false; 74 75 var firstAdf = tree.Root.GetSubTree(1); 75 return firstAdf.Grammar.GetAllowed Symbols(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; 76 77 } 77 78 } -
branches/DataAnalysis Refactoring/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Tests/ArgumentDuplicaterTest.cs
r5549 r5686 21 21 22 22 using System; 23 using System.Collections.Generic; 23 24 using System.Linq; 24 using System.Collections.Generic;25 25 using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding; 26 26 using HeuristicLab.Random; … … 56 56 ISymbolicExpressionTree tree = null; 57 57 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)); 60 61 var success = ArgumentDuplicater.DuplicateArgument(random, tree, 3, 3); 61 62 Assert.IsTrue(success); … … 74 75 if (tree.Root.SubTrees.Count() != 2) return false; 75 76 var firstAdf = tree.Root.GetSubTree(1); 76 return firstAdf.Grammar.GetAllowed Symbols(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; 77 78 } 78 79 } -
branches/DataAnalysis Refactoring/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Tests/ChangeNodeTypeManipulationTest.cs
r5567 r5686 55 55 int failedEvents = 0; 56 56 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); 58 58 string originalTree = formatter.Format(tree); 59 59 ChangeNodeTypeManipulation.ChangeNodeType(random, tree); -
branches/DataAnalysis Refactoring/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Tests/Grammars.cs
r5567 r5686 94 94 } 95 95 96 private class SimpleArithmeticGrammar : DefaultSymbolicExpressionGrammar {96 private class SimpleArithmeticGrammar : SymbolicExpressionGrammar { 97 97 protected SimpleArithmeticGrammar(SimpleArithmeticGrammar original, Cloner cloner) : base(original, cloner) { } 98 98 public SimpleArithmeticGrammar() … … 119 119 120 120 foreach (var funSymb in functionSymbols) { 121 SetMinSubtreeCount(funSymb, 1); 122 SetMaxSubtreeCount(funSymb, 3); 121 SetSubtreeCount(funSymb, 1, 3); 123 122 } 124 SetMinSubtreeCount(terminal, 0); 125 SetMaxSubtreeCount(terminal, 0); 123 SetSubtreeCount(terminal, 0, 0); 126 124 125 SetSubtreeCount(StartSymbol, 1, 1); 127 126 // allow each symbol as child of the start symbol 128 127 foreach (var symb in allSymbols) { 129 SetAllowedChild(StartSymbol, symb, 0); 128 AddAllowedChildSymbol(StartSymbol, symb); 129 AddAllowedChildSymbol(DefunSymbol, symb); 130 130 } 131 131 132 132 // 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 } 138 137 } 139 138 } 140 139 } 141 140 142 public static ISymbolicExpression TreeGrammar CreateSimpleArithmeticGrammar() {143 var g = new GlobalSymbolicExpressionGrammar(new SimpleArithmeticGrammar());144 g.Max FunctionArguments = 0;145 g.Min FunctionArguments = 0;146 g.Max FunctionDefinitions = 0;147 g.Min FunctionDefinitions = 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; 148 147 return g; 149 148 } 150 149 151 public static ISymbolicExpression TreeGrammar CreateArithmeticAndAdfGrammar() {152 var g = new GlobalSymbolicExpressionGrammar(new SimpleArithmeticGrammar());153 g.Max FunctionArguments = 3;154 g.Min FunctionArguments = 0;155 g.Max FunctionDefinitions = 3;156 g.Min FunctionDefinitions = 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; 157 156 return g; 158 157 } -
branches/DataAnalysis Refactoring/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Tests/ProbabilisticTreeCreaterTest.cs
r5549 r5686 22 22 using System; 23 23 using System.Collections.Generic; 24 using System.Diagnostics; 24 25 using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding; 25 26 using HeuristicLab.Random; 26 27 using Microsoft.VisualStudio.TestTools.UnitTesting; 27 using System.Diagnostics;28 28 29 29 namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding_3._4.Tests { … … 56 56 stopwatch.Start(); 57 57 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)); 59 59 } 60 60 stopwatch.Stop(); … … 72 72 Util.GetTerminalDistributionString(randomTrees) + Environment.NewLine 73 73 ); 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 104 75 } 105 76 } -
branches/DataAnalysis Refactoring/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Tests/ReplaceBranchManipulationTest.cs
r5549 r5686 54 54 var random = new MersenneTwister(31415); 55 55 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); 57 58 string originalTree = formatter.Format(tree); 58 59 ReplaceBranchManipulation.ReplaceRandomBranch(random, tree, MAX_TREE_LENGTH, MAX_TREE_DEPTH); -
branches/DataAnalysis Refactoring/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Tests/SubroutineCreaterTest.cs
r5549 r5686 21 21 22 22 using System; 23 using System.Linq;24 23 using System.Collections.Generic; 25 24 using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding; … … 55 54 for (int i = 0; i < POPULATION_SIZE; i++) { 56 55 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); 60 57 var success = SubroutineCreater.CreateSubroutine(random, tree, MAX_TREE_LENGTH, MAX_TREE_DEPTH, 3, 3); 61 58 Assert.IsTrue(success); … … 70 67 ); 71 68 } 72 73 private bool OneMoreAdfAllowed(ISymbolicExpressionTree tree) {74 return tree.Length < 80 && tree.Root.SubTrees.Count() < 4;75 }76 69 } 77 70 } -
branches/DataAnalysis Refactoring/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Tests/SubroutineDeleterTest.cs
r5549 r5686 21 21 22 22 using System; 23 using System.Collections.Generic; 23 24 using System.Linq; 24 using System.Collections.Generic;25 25 using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding; 26 26 using HeuristicLab.Random; … … 56 56 ISymbolicExpressionTree tree = null; 57 57 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); 59 61 } while (!HasAtLeastOneAdf(tree)); 60 62 var success = SubroutineDeleter.DeleteSubroutine(random, tree, 3, 3); -
branches/DataAnalysis Refactoring/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Tests/SubroutineDuplicaterTest.cs
r5549 r5686 21 21 22 22 using System; 23 using System.Collections.Generic; 23 24 using System.Linq; 24 using System.Collections.Generic;25 25 using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding; 26 26 using HeuristicLab.Random; … … 56 56 ISymbolicExpressionTree tree = null; 57 57 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); 59 61 } while (!HasOneAdf(tree)); 60 62 var success = SubroutineDuplicater.DuplicateSubroutine(random, tree, 3, 3); -
branches/DataAnalysis Refactoring/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Tests/SubtreeCrossoverTest.cs
r5549 r5686 56 56 57 57 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); 59 61 } 60 62 Stopwatch stopwatch = new Stopwatch(); … … 83 85 ); 84 86 85 Assert.IsTrue(Math.Round(1000.0 / (msPerCrossoverEvent)) > 2 000); // must achieve more than 2000 x-overs/s87 Assert.IsTrue(Math.Round(1000.0 / (msPerCrossoverEvent)) > 2500); // must achieve more than 1500 x-overs/s 86 88 } 87 89 } -
branches/DataAnalysis Refactoring/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Tests/Util.cs
r5549 r5686 120 120 foreach (var defunTreeNode in tree.Root.SubTrees.OfType<DefunTreeNode>()) { 121 121 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 122 134 var invoke = new InvokeFunction(defunTreeNode.FunctionName); 123 135 foreach (var otherRootNode in tree.Root.SubTrees) { 124 136 if (otherRootNode.Grammar.ContainsSymbol(invoke)) { 125 Assert.IsTrue(otherRootNode.Grammar.GetMin SubtreeCount(invoke) == arity);126 Assert.IsTrue(otherRootNode.Grammar.GetMax SubtreeCount(invoke) == arity);137 Assert.IsTrue(otherRootNode.Grammar.GetMinimumSubtreeCount(invoke) == arity); 138 Assert.IsTrue(otherRootNode.Grammar.GetMaximumSubtreeCount(invoke) == arity); 127 139 } 128 140 } 141 129 142 } 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) { 132 144 Assert.AreNotSame(subtree.Grammar, tree.Root.Grammar); 145 IsValid(subtree.Grammar); 146 } 147 148 IsValid(tree.Root.Grammar); 133 149 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 } 134 161 } 135 162 … … 138 165 where symb.Name == treeNode.Symbol.Name 139 166 select symb).SingleOrDefault(); 140 Assert.IsTrue(treeNode.SubTrees.Count() >= treeNode.Grammar.GetMin SubtreeCount(matchingSymbol));141 Assert.IsTrue(treeNode.SubTrees.Count() <= treeNode.Grammar.GetMax SubtreeCount(matchingSymbol));167 Assert.IsTrue(treeNode.SubTrees.Count() >= treeNode.Grammar.GetMinimumSubtreeCount(matchingSymbol)); 168 Assert.IsTrue(treeNode.SubTrees.Count() <= treeNode.Grammar.GetMaximumSubtreeCount(matchingSymbol)); 142 169 Assert.AreNotEqual(0.0, matchingSymbol.InitialFrequency); // check that no deactivated symbols occur in the tree 143 170 for (int i = 0; i < treeNode.SubTrees.Count(); i++) { 144 Assert.IsTrue(treeNode.Grammar.GetAllowed Symbols(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)); 145 172 IsValid(treeNode.GetSubTree(i)); 146 173 }
Note: See TracChangeset
for help on using the changeset viewer.