source: branches/2839_HiveProjectManagement/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/ArchitectureManipulators/ArgumentCreater.cs @ 16057

Last change on this file since 16057 was 16057, checked in by jkarder, 15 months ago

#2839:

File size: 11.9 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2018 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
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;
23using System.Collections.Generic;
24using System.Linq;
25using HeuristicLab.Common;
26using HeuristicLab.Core;
27using HeuristicLab.Data;
28using HeuristicLab.Parameters;
29using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
30using HeuristicLab.Random;
31
32namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding {
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>
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")]
38  [StorableClass]
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
58    [StorableConstructor]
59    private ArgumentCreater(bool deserializing) : base(deserializing) { }
60    private ArgumentCreater(ArgumentCreater original, Cloner cloner) : base(original, cloner) { }
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
67    public override sealed void ModifyArchitecture(
68      IRandom random,
69      ISymbolicExpressionTree symbolicExpressionTree,
70      IntValue maxFunctionDefinitions, IntValue maxFunctionArguments) {
71      CreateNewArgument(random, symbolicExpressionTree, MaximumSymbolicExpressionTreeLength.Value, MaximumSymbolicExpressionTreeDepth.Value, maxFunctionDefinitions.Value, maxFunctionArguments.Value);
72    }
73
74    public override IDeepCloneable Clone(Cloner cloner) {
75      return new ArgumentCreater(this, cloner);
76    }
77
78    public static bool CreateNewArgument(
79      IRandom random,
80      ISymbolicExpressionTree symbolicExpressionTree,
81      int maxTreeLength, int maxTreeDepth,
82      int maxFunctionDefinitions, int maxFunctionArguments) {
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.
85      ISymbolicExpressionTree clonedTree = (ISymbolicExpressionTree)symbolicExpressionTree.Clone();
86
87      var functionDefiningBranches = clonedTree.IterateNodesPrefix().OfType<DefunTreeNode>().ToList();
88      if (!functionDefiningBranches.Any())
89        // no function defining branch found => abort
90        return false;
91
92      // select a random function defining branch
93      var selectedDefunBranch = functionDefiningBranches.SampleRandom(random);
94
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;
100
101      var allowedArgumentIndexes = Enumerable.Range(0, maxFunctionArguments);
102      var newArgumentIndex = allowedArgumentIndexes.Except(definedArguments).First();
103      ArgumentTreeNode newArgumentNode = MakeArgumentNode(newArgumentIndex);
104
105      // this operation potentially creates very big trees so the access to the length property might throw overflow exception
106      try {
107        if (CreateNewArgumentForDefun(random, clonedTree, selectedDefunBranch, newArgumentNode) && clonedTree.Length <= maxTreeLength && clonedTree.Depth <= maxTreeDepth) {
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
124    private static bool CreateNewArgumentForDefun(IRandom random, ISymbolicExpressionTree tree, DefunTreeNode defunBranch, ArgumentTreeNode newArgumentNode) {
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
127      var cutPoints = (from node in defunBranch.IterateNodesPrefix()
128                       where node.Subtrees.Count() > 0 &&
129                             !node.IterateNodesPrefix().OfType<ArgumentTreeNode>().Any() &&
130                             !node.IterateNodesPrefix().OfType<InvokeFunctionTreeNode>().Any()
131                       from subtree in node.Subtrees
132                       select new CutPoint(node, subtree)).ToList();
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
139      var replacedBranch = selectedCutPoint.Child;
140      selectedCutPoint.Parent.RemoveSubtree(selectedCutPoint.ChildIndex);
141      selectedCutPoint.Parent.InsertSubtree(selectedCutPoint.ChildIndex, newArgumentNode);
142
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
147                             where node.Subtrees.Count() == defunBranch.NumberOfArguments
148                             select node).ToList();
149      // do this repeatedly until no matching invocations are found     
150      while (invocationNodes.Count > 0) {
151        List<ISymbolicExpressionTreeNode> newlyAddedBranches = new List<ISymbolicExpressionTreeNode>();
152        foreach (var invocationNode in invocationNodes) {
153          // check that the invocation node really has the correct number of arguments
154          if (invocationNode.Subtrees.Count() != defunBranch.NumberOfArguments) throw new InvalidOperationException();
155          // append a new argument branch after expanding all argument nodes
156          var clonedBranch = (ISymbolicExpressionTreeNode)replacedBranch.Clone();
157          clonedBranch = ReplaceArgumentsInBranch(clonedBranch, invocationNode.Subtrees);
158          invocationNode.InsertSubtree(newArgumentNode.Symbol.ArgumentIndex, clonedBranch);
159          newlyAddedBranches.Add(clonedBranch);
160        }
161        // iterate in post-fix order to make sure that the subtrees of n are already adapted when n is processed
162        invocationNodes = (from newlyAddedBranch in newlyAddedBranches
163                           from node in newlyAddedBranch.IterateNodesPostfix().OfType<InvokeFunctionTreeNode>()
164                           where node.Symbol.FunctionName == defunBranch.FunctionName
165                           where node.Subtrees.Count() == defunBranch.NumberOfArguments
166                           select node).ToList();
167      }
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
171      defunBranch.NumberOfArguments++;
172      defunBranch.Grammar.AddSymbol(newArgumentNode.Symbol);
173      defunBranch.Grammar.SetSubtreeCount(newArgumentNode.Symbol, 0, 0);
174      // allow the argument as child of any other symbol
175      GrammarModifier.SetAllowedParentSymbols(defunBranch.Grammar, selectedCutPoint.Child.Symbol, newArgumentNode.Symbol);
176
177      foreach (var subtree in tree.Root.Subtrees) {
178        // when the changed function is known in the branch then update the number of arguments
179        var matchingSymbol = subtree.Grammar.Symbols.OfType<InvokeFunction>().Where(s => s.FunctionName == defunBranch.FunctionName).SingleOrDefault();
180        if (matchingSymbol != null) {
181          subtree.Grammar.SetSubtreeCount(matchingSymbol, defunBranch.NumberOfArguments, defunBranch.NumberOfArguments);
182          foreach (var symb in subtree.Grammar.Symbols) {
183            if (symb is StartSymbol || symb is ProgramRootSymbol) continue;
184            if (symb.Name == matchingSymbol.Name) continue; //don't allow invoke as child of invoke
185            if (subtree.Grammar.IsAllowedChildSymbol(selectedCutPoint.Parent.Symbol, symb, selectedCutPoint.ChildIndex))
186              subtree.Grammar.AddAllowedChildSymbol(matchingSymbol, symb, newArgumentNode.Symbol.ArgumentIndex);
187          }
188        }
189      }
190
191      return true;
192    }
193
194    private static ISymbolicExpressionTreeNode ReplaceArgumentsInBranch(ISymbolicExpressionTreeNode branch, IEnumerable<ISymbolicExpressionTreeNode> argumentTrees) {
195      ArgumentTreeNode argNode = branch as ArgumentTreeNode;
196      if (argNode != null) {
197        // replace argument nodes by a clone of the original subtree that provided the result for the argument node
198        return (SymbolicExpressionTreeNode)argumentTrees.ElementAt(argNode.Symbol.ArgumentIndex).Clone();
199      } else {
200        // call recursively for all subtree
201        List<ISymbolicExpressionTreeNode> subtrees = new List<ISymbolicExpressionTreeNode>(branch.Subtrees);
202        while (branch.Subtrees.Count() > 0) branch.RemoveSubtree(0);
203        foreach (var subtree in subtrees) {
204          branch.AddSubtree(ReplaceArgumentsInBranch(subtree, argumentTrees));
205        }
206        return branch;
207      }
208    }
209
210    private static ArgumentTreeNode MakeArgumentNode(int argIndex) {
211      var node = (ArgumentTreeNode)(new Argument(argIndex)).CreateTreeNode();
212      return node;
213    }
214  }
215}
Note: See TracBrowser for help on using the repository browser.