Free cookie consent management tool by TermsFeed Policy Generator

source: stable/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/ArchitectureManipulators/ArgumentCreater.cs @ 17387

Last change on this file since 17387 was 17181, checked in by swagner, 5 years ago

#2875: Merged r17180 from trunk to stable

File size: 11.9 KB
RevLine 
[3294]1#region License Information
2/* HeuristicLab
[17181]3 * Copyright (C) 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
[4722]22using System;
[4068]23using System.Collections.Generic;
[3294]24using System.Linq;
[4722]25using HeuristicLab.Common;
[3294]26using HeuristicLab.Core;
27using HeuristicLab.Data;
[5686]28using HeuristicLab.Parameters;
[17097]29using HEAL.Attic;
[12706]30using HeuristicLab.Random;
[3294]31
[5499]32namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding {
[3294]33  /// <summary>
34  /// Creates a new argument within one function-defining branch of a symbolic expression tree.
35  /// As described in Koza, Bennett, Andre, Keane, Genetic Programming III - Darwinian Invention and Problem Solving, 1999, pp. 106
36  /// </summary>
[5510]37  [Item("ArgumentCreater", "Manipulates a symbolic expression by creating a new argument within one function-defining branch. As described in Koza, Bennett, Andre, Keane, Genetic Programming III - Darwinian Invention and Problem Solving, 1999, pp. 106")]
[17097]38  [StorableType("2AC1EE1A-B2B4-47E7-97AF-BFC9FB2D7BA2")]
[5510]39  public sealed class ArgumentCreater : SymbolicExpressionTreeArchitectureManipulator, ISymbolicExpressionTreeSizeConstraintOperator {
40    private const string MaximumSymbolicExpressionTreeLengthParameterName = "MaximumSymbolicExpressionTreeLength";
41    private const string MaximumSymbolicExpressionTreeDepthParameterName = "MaximumSymbolicExpressionTreeDepth";
42    #region Parameter Properties
43    public IValueLookupParameter<IntValue> MaximumSymbolicExpressionTreeLengthParameter {
44      get { return (IValueLookupParameter<IntValue>)Parameters[MaximumSymbolicExpressionTreeLengthParameterName]; }
45    }
46    public IValueLookupParameter<IntValue> MaximumSymbolicExpressionTreeDepthParameter {
47      get { return (IValueLookupParameter<IntValue>)Parameters[MaximumSymbolicExpressionTreeDepthParameterName]; }
48    }
49    #endregion
50    #region Properties
51    public IntValue MaximumSymbolicExpressionTreeLength {
52      get { return MaximumSymbolicExpressionTreeLengthParameter.ActualValue; }
53    }
54    public IntValue MaximumSymbolicExpressionTreeDepth {
55      get { return MaximumSymbolicExpressionTreeDepthParameter.ActualValue; }
56    }
57    #endregion
[4722]58    [StorableConstructor]
[17097]59    private ArgumentCreater(StorableConstructorFlag _) : base(_) { }
[4722]60    private ArgumentCreater(ArgumentCreater original, Cloner cloner) : base(original, cloner) { }
[5510]61    public ArgumentCreater()
62      : base() {
63      Parameters.Add(new ValueLookupParameter<IntValue>(MaximumSymbolicExpressionTreeLengthParameterName, "The maximal length (number of nodes) of the symbolic expression tree."));
64      Parameters.Add(new ValueLookupParameter<IntValue>(MaximumSymbolicExpressionTreeDepthParameterName, "The maximal depth of the symbolic expression tree (a tree with one node has depth = 0)."));
65    }
66
[3294]67    public override sealed void ModifyArchitecture(
68      IRandom random,
[5510]69      ISymbolicExpressionTree symbolicExpressionTree,
70      IntValue maxFunctionDefinitions, IntValue maxFunctionArguments) {
71      CreateNewArgument(random, symbolicExpressionTree, MaximumSymbolicExpressionTreeLength.Value, MaximumSymbolicExpressionTreeDepth.Value, maxFunctionDefinitions.Value, maxFunctionArguments.Value);
[3294]72    }
73
[4722]74    public override IDeepCloneable Clone(Cloner cloner) {
75      return new ArgumentCreater(this, cloner);
76    }
77
[3294]78    public static bool CreateNewArgument(
79      IRandom random,
[5510]80      ISymbolicExpressionTree symbolicExpressionTree,
81      int maxTreeLength, int maxTreeDepth,
82      int maxFunctionDefinitions, int maxFunctionArguments) {
[4524]83      // work on a copy in case we find out later that the tree would be too big
84      // in this case it's easiest to simply return the original tree.
[5510]85      ISymbolicExpressionTree clonedTree = (ISymbolicExpressionTree)symbolicExpressionTree.Clone();
[3294]86
[12706]87      var functionDefiningBranches = clonedTree.IterateNodesPrefix().OfType<DefunTreeNode>().ToList();
88      if (!functionDefiningBranches.Any())
[3294]89        // no function defining branch found => abort
90        return false;
[3338]91
[3294]92      // select a random function defining branch
[12706]93      var selectedDefunBranch = functionDefiningBranches.SampleRandom(random);
94
[3338]95      var definedArguments = (from symbol in selectedDefunBranch.Grammar.Symbols.OfType<Argument>()
96                              select symbol.ArgumentIndex).Distinct();
97      if (definedArguments.Count() >= maxFunctionArguments)
98        // max number of arguments reached => abort
99        return false;
[4524]100
101      var allowedArgumentIndexes = Enumerable.Range(0, maxFunctionArguments);
102      var newArgumentIndex = allowedArgumentIndexes.Except(definedArguments).First();
103      ArgumentTreeNode newArgumentNode = MakeArgumentNode(newArgumentIndex);
104
[5549]105      // this operation potentially creates very big trees so the access to the length property might throw overflow exception
[4524]106      try {
[5549]107        if (CreateNewArgumentForDefun(random, clonedTree, selectedDefunBranch, newArgumentNode) && clonedTree.Length <= maxTreeLength && clonedTree.Depth <= maxTreeDepth) {
[4524]108
109          // size constraints are fulfilled
110          // replace root of original tree with root of manipulated tree
111          symbolicExpressionTree.Root = clonedTree.Root;
112          return true;
113        } else {
114          // keep originalTree
115          return false;
116        }
117      }
118      catch (OverflowException) {
119        // keep original tree
120        return false;
121      }
122    }
123
[5510]124    private static bool CreateNewArgumentForDefun(IRandom random, ISymbolicExpressionTree tree, DefunTreeNode defunBranch, ArgumentTreeNode newArgumentNode) {
[3294]125      // select a random cut point in the function defining branch
126      // the branch at the cut point is to be replaced by a new argument node
[4524]127      var cutPoints = (from node in defunBranch.IterateNodesPrefix()
[5792]128                       where node.Subtrees.Count() > 0 &&
129                             !node.IterateNodesPrefix().OfType<ArgumentTreeNode>().Any() &&
130                             !node.IterateNodesPrefix().OfType<InvokeFunctionTreeNode>().Any()
[5733]131                       from subtree in node.Subtrees
[5686]132                       select new CutPoint(node, subtree)).ToList();
[3294]133
134      if (cutPoints.Count() == 0)
135        // no cut point found => abort;
136        return false;
137      var selectedCutPoint = cutPoints[random.Next(cutPoints.Count)];
138      // replace the branch at the cut point with an argument node
[5686]139      var replacedBranch = selectedCutPoint.Child;
[5733]140      selectedCutPoint.Parent.RemoveSubtree(selectedCutPoint.ChildIndex);
141      selectedCutPoint.Parent.InsertSubtree(selectedCutPoint.ChildIndex, newArgumentNode);
[4106]142
[4524]143      // find all old invocations of the selected ADF and attach a cloned version of the replaced branch (with all argument-nodes expanded)
144      // iterate in post-fix order to make sure that the subtrees of n are already adapted when n is processed
145      var invocationNodes = (from node in tree.IterateNodesPostfix().OfType<InvokeFunctionTreeNode>()
146                             where node.Symbol.FunctionName == defunBranch.FunctionName
[5733]147                             where node.Subtrees.Count() == defunBranch.NumberOfArguments
[4477]148                             select node).ToList();
[4106]149      // do this repeatedly until no matching invocations are found     
[4524]150      while (invocationNodes.Count > 0) {
[5510]151        List<ISymbolicExpressionTreeNode> newlyAddedBranches = new List<ISymbolicExpressionTreeNode>();
[4106]152        foreach (var invocationNode in invocationNodes) {
[4524]153          // check that the invocation node really has the correct number of arguments
[5733]154          if (invocationNode.Subtrees.Count() != defunBranch.NumberOfArguments) throw new InvalidOperationException();
[4106]155          // append a new argument branch after expanding all argument nodes
[5510]156          var clonedBranch = (ISymbolicExpressionTreeNode)replacedBranch.Clone();
[5733]157          clonedBranch = ReplaceArgumentsInBranch(clonedBranch, invocationNode.Subtrees);
158          invocationNode.InsertSubtree(newArgumentNode.Symbol.ArgumentIndex, clonedBranch);
[4106]159          newlyAddedBranches.Add(clonedBranch);
160        }
[4524]161        // iterate in post-fix order to make sure that the subtrees of n are already adapted when n is processed
[4477]162        invocationNodes = (from newlyAddedBranch in newlyAddedBranches
[4524]163                           from node in newlyAddedBranch.IterateNodesPostfix().OfType<InvokeFunctionTreeNode>()
164                           where node.Symbol.FunctionName == defunBranch.FunctionName
[5733]165                           where node.Subtrees.Count() == defunBranch.NumberOfArguments
[4477]166                           select node).ToList();
[3294]167      }
[3338]168      // increase expected number of arguments of function defining branch
169      // it's possible that the number of actually referenced arguments was reduced (all references were replaced by a single new argument)
170      // but the number of expected arguments is increased anyway
[4524]171      defunBranch.NumberOfArguments++;
172      defunBranch.Grammar.AddSymbol(newArgumentNode.Symbol);
[5686]173      defunBranch.Grammar.SetSubtreeCount(newArgumentNode.Symbol, 0, 0);
[3338]174      // allow the argument as child of any other symbol
[5792]175      GrammarModifier.SetAllowedParentSymbols(defunBranch.Grammar, selectedCutPoint.Child.Symbol, newArgumentNode.Symbol);
176
[5733]177      foreach (var subtree in tree.Root.Subtrees) {
[3338]178        // when the changed function is known in the branch then update the number of arguments
[4524]179        var matchingSymbol = subtree.Grammar.Symbols.OfType<InvokeFunction>().Where(s => s.FunctionName == defunBranch.FunctionName).SingleOrDefault();
[3338]180        if (matchingSymbol != null) {
[5686]181          subtree.Grammar.SetSubtreeCount(matchingSymbol, defunBranch.NumberOfArguments, defunBranch.NumberOfArguments);
[5792]182          foreach (var symb in subtree.Grammar.Symbols) {
183            if (symb is StartSymbol || symb is ProgramRootSymbol) continue;
[6918]184            if (symb.Name == matchingSymbol.Name) continue; //don't allow invoke as child of invoke
[5792]185            if (subtree.Grammar.IsAllowedChildSymbol(selectedCutPoint.Parent.Symbol, symb, selectedCutPoint.ChildIndex))
186              subtree.Grammar.AddAllowedChildSymbol(matchingSymbol, symb, newArgumentNode.Symbol.ArgumentIndex);
[3360]187          }
[3294]188        }
189      }
[4524]190
[3294]191      return true;
192    }
193
[5510]194    private static ISymbolicExpressionTreeNode ReplaceArgumentsInBranch(ISymbolicExpressionTreeNode branch, IEnumerable<ISymbolicExpressionTreeNode> argumentTrees) {
[4524]195      ArgumentTreeNode argNode = branch as ArgumentTreeNode;
196      if (argNode != null) {
[3360]197        // replace argument nodes by a clone of the original subtree that provided the result for the argument node
[5510]198        return (SymbolicExpressionTreeNode)argumentTrees.ElementAt(argNode.Symbol.ArgumentIndex).Clone();
[3360]199      } else {
200        // call recursively for all subtree
[5733]201        List<ISymbolicExpressionTreeNode> subtrees = new List<ISymbolicExpressionTreeNode>(branch.Subtrees);
202        while (branch.Subtrees.Count() > 0) branch.RemoveSubtree(0);
[3360]203        foreach (var subtree in subtrees) {
[5733]204          branch.AddSubtree(ReplaceArgumentsInBranch(subtree, argumentTrees));
[3294]205        }
[3360]206        return branch;
[3294]207      }
208    }
209
[4524]210    private static ArgumentTreeNode MakeArgumentNode(int argIndex) {
[3338]211      var node = (ArgumentTreeNode)(new Argument(argIndex)).CreateTreeNode();
[3294]212      return node;
213    }
214  }
215}
Note: See TracBrowser for help on using the repository browser.