Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/ArchitectureManipulators/SubroutineCreater.cs @ 12356

Last change on this file since 12356 was 12012, checked in by ascheibe, 10 years ago

#2212 merged r12008, r12009, r12010 back into trunk

File size: 14.8 KB
RevLine 
[3294]1#region License Information
2/* HeuristicLab
[12012]3 * Copyright (C) 2002-2015 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
[3294]4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using System;
[4068]23using System.Collections.Generic;
[3294]24using System.Linq;
[4068]25using System.Text;
[4722]26using HeuristicLab.Common;
[3294]27using HeuristicLab.Core;
28using HeuristicLab.Data;
[5686]29using HeuristicLab.Parameters;
[3294]30using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
31
[5499]32namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding {
[3294]33  /// <summary>
34  /// Manipulates a symbolic expression by adding one new function-defining branch containing
35  /// a proportion of a preexisting branch and by creating a reference to the new branch.
36  /// As described in Koza, Bennett, Andre, Keane, Genetic Programming III - Darwinian Invention and Problem Solving, 1999, pp. 97
37  /// </summary>
[5510]38  [Item("SubroutineCreater", "Manipulates a symbolic expression by adding one new function-defining branch containing a proportion of a preexisting branch and by creating a reference to the new branch. As described in Koza, Bennett, Andre, Keane, Genetic Programming III - Darwinian Invention and Problem Solving, 1999, pp. 97")]
[3294]39  [StorableClass]
[5510]40  public sealed class SubroutineCreater : SymbolicExpressionTreeArchitectureManipulator, ISymbolicExpressionTreeSizeConstraintOperator {
[3360]41    private const double ARGUMENT_CUTOFF_PROBABILITY = 0.05;
[5510]42    private const string MaximumSymbolicExpressionTreeLengthParameterName = "MaximumSymbolicExpressionTreeLength";
43    private const string MaximumSymbolicExpressionTreeDepthParameterName = "MaximumSymbolicExpressionTreeDepth";
44    #region Parameter Properties
45    public IValueLookupParameter<IntValue> MaximumSymbolicExpressionTreeLengthParameter {
46      get { return (IValueLookupParameter<IntValue>)Parameters[MaximumSymbolicExpressionTreeLengthParameterName]; }
47    }
48    public IValueLookupParameter<IntValue> MaximumSymbolicExpressionTreeDepthParameter {
49      get { return (IValueLookupParameter<IntValue>)Parameters[MaximumSymbolicExpressionTreeDepthParameterName]; }
50    }
51    #endregion
52    #region Properties
53    public IntValue MaximumSymbolicExpressionTreeLength {
54      get { return MaximumSymbolicExpressionTreeLengthParameter.ActualValue; }
55    }
56    public IntValue MaximumSymbolicExpressionTreeDepth {
57      get { return MaximumSymbolicExpressionTreeDepthParameter.ActualValue; }
58    }
59    #endregion
[4722]60    [StorableConstructor]
61    private SubroutineCreater(bool deserializing) : base(deserializing) { }
62    private SubroutineCreater(SubroutineCreater original, Cloner cloner) : base(original, cloner) { }
[5686]63    public SubroutineCreater()
64      : base() {
[5510]65      Parameters.Add(new ValueLookupParameter<IntValue>(MaximumSymbolicExpressionTreeLengthParameterName, "The maximal length (number of nodes) of the symbolic expression tree."));
66      Parameters.Add(new ValueLookupParameter<IntValue>(MaximumSymbolicExpressionTreeDepthParameterName, "The maximal depth of the symbolic expression tree (a tree with one node has depth = 0)."));
67    }
[4722]68
69    public override IDeepCloneable Clone(Cloner cloner) {
70      return new SubroutineCreater(this, cloner);
71    }
72
[3294]73    public override sealed void ModifyArchitecture(
74      IRandom random,
[5510]75      ISymbolicExpressionTree symbolicExpressionTree,
76      IntValue maxFunctionDefinitions, IntValue maxFunctionArguments) {
77      CreateSubroutine(random, symbolicExpressionTree, MaximumSymbolicExpressionTreeLength.Value, MaximumSymbolicExpressionTreeDepth.Value, maxFunctionDefinitions.Value, maxFunctionArguments.Value);
[3294]78    }
79
80    public static bool CreateSubroutine(
81      IRandom random,
[5510]82      ISymbolicExpressionTree symbolicExpressionTree,
83      int maxTreeLength, int maxTreeDepth,
84      int maxFunctionDefinitions, int maxFunctionArguments) {
[3294]85      var functionDefiningBranches = symbolicExpressionTree.IterateNodesPrefix().OfType<DefunTreeNode>();
[5510]86      if (functionDefiningBranches.Count() >= maxFunctionDefinitions)
[3294]87        // allowed maximum number of ADF reached => abort
88        return false;
[5549]89      if (symbolicExpressionTree.Length + 4 > maxTreeLength)
90        // defining a new function causes an length increase by 4 nodes (max) if the max tree length is reached => abort
[3360]91        return false;
[5510]92      string formatString = new StringBuilder().Append('0', (int)Math.Log10(maxFunctionDefinitions * 10 - 1)).ToString(); // >= 100 functions => ###
93      var allowedFunctionNames = from index in Enumerable.Range(0, maxFunctionDefinitions)
[3294]94                                 select "ADF" + index.ToString(formatString);
[3360]95
96      // select a random body (either the result producing branch or an ADF branch)
[5733]97      var bodies = from node in symbolicExpressionTree.Root.Subtrees
[5549]98                   select new { Tree = node, Length = node.GetLength() };
99      var totalNumberOfBodyNodes = bodies.Select(x => x.Length).Sum();
[3294]100      int r = random.Next(totalNumberOfBodyNodes);
101      int aggregatedNumberOfBodyNodes = 0;
[5510]102      ISymbolicExpressionTreeNode selectedBody = null;
[3294]103      foreach (var body in bodies) {
[5549]104        aggregatedNumberOfBodyNodes += body.Length;
[3294]105        if (aggregatedNumberOfBodyNodes > r)
106          selectedBody = body.Tree;
107      }
108      // sanity check
109      if (selectedBody == null) throw new InvalidOperationException();
[3360]110
111      // select a random cut point in the selected branch
[5686]112      var allCutPoints = (from parent in selectedBody.IterateNodesPrefix()
[5733]113                          from subtree in parent.Subtrees
[5686]114                          select new CutPoint(parent, subtree)).ToList();
[3360]115      if (allCutPoints.Count() == 0)
[3294]116        // no cut points => abort
117        return false;
[3360]118      string newFunctionName = allowedFunctionNames.Except(functionDefiningBranches.Select(x => x.FunctionName)).First();
119      var selectedCutPoint = allCutPoints.SelectRandom(random);
[3294]120      // select random branches as argument cut-off points (replaced by argument terminal nodes in the function)
[5686]121      List<CutPoint> argumentCutPoints = SelectRandomArgumentBranches(selectedCutPoint.Child, random, ARGUMENT_CUTOFF_PROBABILITY, maxFunctionArguments);
122      ISymbolicExpressionTreeNode functionBody = selectedCutPoint.Child;
[3294]123      // disconnect the function body from the tree
[5733]124      selectedCutPoint.Parent.RemoveSubtree(selectedCutPoint.ChildIndex);
[3294]125      // disconnect the argument branches from the function
[5686]126      functionBody = DisconnectBranches(functionBody, argumentCutPoints);
[3360]127      // insert a function invocation symbol instead
128      var invokeNode = (InvokeFunctionTreeNode)(new InvokeFunction(newFunctionName)).CreateTreeNode();
[5733]129      selectedCutPoint.Parent.InsertSubtree(selectedCutPoint.ChildIndex, invokeNode);
[3360]130      // add the branches selected as argument as subtrees of the function invocation node
[5686]131      foreach (var argumentCutPoint in argumentCutPoints)
[5733]132        invokeNode.AddSubtree(argumentCutPoint.Child);
[3294]133
134      // insert a new function defining branch
135      var defunNode = (DefunTreeNode)(new Defun()).CreateTreeNode();
[3360]136      defunNode.FunctionName = newFunctionName;
[5733]137      defunNode.AddSubtree(functionBody);
138      symbolicExpressionTree.Root.AddSubtree(defunNode);
[3360]139      // the grammar in the newly defined function is a clone of the grammar of the originating branch
[5510]140      defunNode.SetGrammar((ISymbolicExpressionTreeGrammar)selectedBody.Grammar.Clone());
[8148]141
142      var allowedChildSymbols = selectedBody.Grammar.GetAllowedChildSymbols(selectedBody.Symbol);
143      foreach (var allowedChildSymbol in allowedChildSymbols)
144        defunNode.Grammar.AddAllowedChildSymbol(defunNode.Symbol, allowedChildSymbol);
145      var maxSubtrees = selectedBody.Grammar.GetMaximumSubtreeCount(selectedBody.Symbol);
146      for (int i = 0; i < maxSubtrees; i++) {
147        foreach (var allowedChildSymbol in selectedBody.Grammar.GetAllowedChildSymbols(selectedBody.Symbol, i))
148          defunNode.Grammar.AddAllowedChildSymbol(defunNode.Symbol, allowedChildSymbol);
149      }
150
[5686]151      // remove all argument symbols from grammar except that one contained in cutpoints
152      var oldArgumentSymbols = selectedBody.Grammar.Symbols.OfType<Argument>().ToList();
[3360]153      foreach (var oldArgSymb in oldArgumentSymbols)
154        defunNode.Grammar.RemoveSymbol(oldArgSymb);
155      // find unique argument indexes and matching symbols in the function defining branch
156      var newArgumentIndexes = (from node in defunNode.IterateNodesPrefix().OfType<ArgumentTreeNode>()
157                                select node.Symbol.ArgumentIndex).Distinct();
158      // add argument symbols to grammar of function defining branch
[5686]159      GrammarModifier.AddArgumentSymbol(selectedBody.Grammar, defunNode.Grammar, newArgumentIndexes, argumentCutPoints);
[3360]160      defunNode.NumberOfArguments = newArgumentIndexes.Count();
[5686]161      if (defunNode.NumberOfArguments != argumentCutPoints.Count) throw new InvalidOperationException();
[3360]162      // add invoke symbol for newly defined function to the original branch
[5686]163      GrammarModifier.AddInvokeSymbol(selectedBody.Grammar, defunNode.FunctionName, defunNode.NumberOfArguments, selectedCutPoint, argumentCutPoints);
[3360]164
165      // when the new function body was taken from another function definition
166      // add invoke symbol for newly defined function to all branches that are allowed to invoke the original branch
167      if (selectedBody.Symbol is Defun) {
168        var originalFunctionDefinition = selectedBody as DefunTreeNode;
[5733]169        foreach (var subtree in symbolicExpressionTree.Root.Subtrees) {
[3360]170          var originalBranchInvokeSymbol = (from symb in subtree.Grammar.Symbols.OfType<InvokeFunction>()
171                                            where symb.FunctionName == originalFunctionDefinition.FunctionName
172                                            select symb).SingleOrDefault();
173          // when the original branch can be invoked from the subtree then also allow invocation of the function
174          if (originalBranchInvokeSymbol != null) {
[5686]175            GrammarModifier.AddInvokeSymbol(subtree.Grammar, defunNode.FunctionName, defunNode.NumberOfArguments, selectedCutPoint, argumentCutPoints);
[3360]176          }
177        }
[3294]178      }
179      return true;
180    }
181
[5686]182    private static ISymbolicExpressionTreeNode DisconnectBranches(ISymbolicExpressionTreeNode node, List<CutPoint> argumentCutPoints) {
183      int argumentIndex = argumentCutPoints.FindIndex(x => x.Child == node);
184      if (argumentIndex != -1) {
[3360]185        var argSymbol = new Argument(argumentIndex);
186        return argSymbol.CreateTreeNode();
187      }
[3294]188      // remove the subtrees so that we can clone only the root node
[5733]189      List<ISymbolicExpressionTreeNode> subtrees = new List<ISymbolicExpressionTreeNode>(node.Subtrees);
190      while (node.Subtrees.Count() > 0) node.RemoveSubtree(0);
[3294]191      // recursively apply function for subtrees or append a argument terminal node
192      foreach (var subtree in subtrees) {
[5733]193        node.AddSubtree(DisconnectBranches(subtree, argumentCutPoints));
[3294]194      }
195      return node;
196    }
197
[5686]198    private static List<CutPoint> SelectRandomArgumentBranches(ISymbolicExpressionTreeNode selectedRoot,
[3294]199      IRandom random,
[3360]200      double cutProbability,
[3294]201      int maxArguments) {
[3360]202      // breadth first determination of argument cut-off points
203      // we must make sure that we cut off all original argument nodes and that the number of new argument is smaller than the limit
[5686]204      List<CutPoint> argumentBranches = new List<CutPoint>();
[3360]205      if (selectedRoot is ArgumentTreeNode) {
[5686]206        argumentBranches.Add(new CutPoint(selectedRoot.Parent, selectedRoot));
[3360]207        return argumentBranches;
208      } else {
209        // get the number of argument nodes (which must be cut-off) in the sub-trees
[5733]210        var numberOfArgumentsInSubtrees = (from subtree in selectedRoot.Subtrees
[3360]211                                           let nArgumentsInTree = subtree.IterateNodesPrefix().OfType<ArgumentTreeNode>().Count()
212                                           select nArgumentsInTree).ToList();
213        // determine the minimal number of new argument nodes for each sub-tree
[5686]214        //if we exceed the maxArguments return the same cutpoint as the start cutpoint to create a ADF that returns only its argument
[3360]215        var minNewArgumentsForSubtrees = numberOfArgumentsInSubtrees.Select(x => x > 0 ? 1 : 0).ToList();
216        if (minNewArgumentsForSubtrees.Sum() > maxArguments) {
[5686]217          argumentBranches.Add(new CutPoint(selectedRoot.Parent, selectedRoot));
[3360]218          return argumentBranches;
[3294]219        }
[3360]220        // cut-off in the sub-trees in random order
[5733]221        var randomIndexes = (from index in Enumerable.Range(0, selectedRoot.Subtrees.Count())
[5686]222                             select new { Index = index, OrderValue = random.NextDouble() })
223                             .OrderBy(x => x.OrderValue)
224                             .Select(x => x.Index);
[3360]225        foreach (var subtreeIndex in randomIndexes) {
[5733]226          var subtree = selectedRoot.GetSubtree(subtreeIndex);
[3360]227          minNewArgumentsForSubtrees[subtreeIndex] = 0;
228          // => cut-off at 0..n points somewhere in the current sub-tree
229          // determine the maximum number of new arguments that should be created in the branch
230          // as the maximum for the whole branch minus already added arguments minus minimal number of arguments still left
231          int maxArgumentsFromBranch = maxArguments - argumentBranches.Count - minNewArgumentsForSubtrees.Sum();
232          // when no argument is allowed from the current branch then we have to include the whole branch into the function
233          // otherwise: choose randomly wether to cut off immediately or wether to extend the function body into the branch
234          if (maxArgumentsFromBranch == 0) {
235            // don't cut at all => the whole sub-tree branch is included in the function body
236            // (we already checked ahead of time that there are no arguments left over in the subtree)
237          } else if (random.NextDouble() >= cutProbability) {
238            argumentBranches.AddRange(SelectRandomArgumentBranches(subtree, random, cutProbability, maxArgumentsFromBranch));
239          } else {
240            // cut-off at current sub-tree
[5686]241            argumentBranches.Add(new CutPoint(subtree.Parent, subtree));
[3360]242          }
243        }
244        return argumentBranches;
[3294]245      }
246    }
247  }
248}
Note: See TracBrowser for help on using the repository browser.