1 | #region License Information
|
---|
2 | /* HeuristicLab
|
---|
3 | * Copyright (C) 2002-2010 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 |
|
---|
22 | using System;
|
---|
23 | using System.Collections.Generic;
|
---|
24 | using System.Linq;
|
---|
25 | using HeuristicLab.Common;
|
---|
26 | using HeuristicLab.Core;
|
---|
27 | using HeuristicLab.Data;
|
---|
28 | using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Symbols;
|
---|
29 | using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
|
---|
30 |
|
---|
31 | namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.ArchitectureManipulators {
|
---|
32 | /// <summary>
|
---|
33 | /// Creates a new argument within one function-defining branch of a symbolic expression tree.
|
---|
34 | /// As described in Koza, Bennett, Andre, Keane, Genetic Programming III - Darwinian Invention and Problem Solving, 1999, pp. 106
|
---|
35 | /// </summary>
|
---|
36 | [Item("ArgumentCreater", "Manipulates a symbolic expression by creating a new argument within one function-defining branch.")]
|
---|
37 | [StorableClass]
|
---|
38 | public sealed class ArgumentCreater : SymbolicExpressionTreeArchitectureManipulator {
|
---|
39 | [StorableConstructor]
|
---|
40 | private ArgumentCreater(bool deserializing) : base(deserializing) { }
|
---|
41 | private ArgumentCreater(ArgumentCreater original, Cloner cloner) : base(original, cloner) { }
|
---|
42 | public ArgumentCreater() : base() { }
|
---|
43 | public override sealed void ModifyArchitecture(
|
---|
44 | IRandom random,
|
---|
45 | SymbolicExpressionTree symbolicExpressionTree,
|
---|
46 | ISymbolicExpressionGrammar grammar,
|
---|
47 | IntValue maxTreeSize, IntValue maxTreeHeight,
|
---|
48 | IntValue maxFunctionDefiningBranches, IntValue maxFunctionArguments,
|
---|
49 | out bool success) {
|
---|
50 | success = CreateNewArgument(random, symbolicExpressionTree, grammar, maxTreeSize.Value, maxTreeHeight.Value, maxFunctionDefiningBranches.Value, maxFunctionArguments.Value);
|
---|
51 | }
|
---|
52 |
|
---|
53 | public override IDeepCloneable Clone(Cloner cloner) {
|
---|
54 | return new ArgumentCreater(this, cloner);
|
---|
55 | }
|
---|
56 |
|
---|
57 | public static bool CreateNewArgument(
|
---|
58 | IRandom random,
|
---|
59 | SymbolicExpressionTree symbolicExpressionTree,
|
---|
60 | ISymbolicExpressionGrammar grammar,
|
---|
61 | int maxTreeSize, int maxTreeHeight,
|
---|
62 | int maxFunctionDefiningBranches, int maxFunctionArguments) {
|
---|
63 | // work on a copy in case we find out later that the tree would be too big
|
---|
64 | // in this case it's easiest to simply return the original tree.
|
---|
65 | SymbolicExpressionTree clonedTree = (SymbolicExpressionTree)symbolicExpressionTree.Clone();
|
---|
66 |
|
---|
67 | var functionDefiningBranches = clonedTree.IterateNodesPrefix().OfType<DefunTreeNode>();
|
---|
68 | if (functionDefiningBranches.Count() == 0)
|
---|
69 | // no function defining branch found => abort
|
---|
70 | return false;
|
---|
71 |
|
---|
72 | // select a random function defining branch
|
---|
73 | var selectedDefunBranch = functionDefiningBranches.SelectRandom(random);
|
---|
74 | var definedArguments = (from symbol in selectedDefunBranch.Grammar.Symbols.OfType<Argument>()
|
---|
75 | select symbol.ArgumentIndex).Distinct();
|
---|
76 | if (definedArguments.Count() >= maxFunctionArguments)
|
---|
77 | // max number of arguments reached => abort
|
---|
78 | return false;
|
---|
79 |
|
---|
80 | var allowedArgumentIndexes = Enumerable.Range(0, maxFunctionArguments);
|
---|
81 | var newArgumentIndex = allowedArgumentIndexes.Except(definedArguments).First();
|
---|
82 | ArgumentTreeNode newArgumentNode = MakeArgumentNode(newArgumentIndex);
|
---|
83 |
|
---|
84 | // this operation potentially creates very big trees so the access to the size property might throw overflow exception
|
---|
85 | try {
|
---|
86 | if (CreateNewArgumentForDefun(random, clonedTree, selectedDefunBranch, newArgumentNode) && clonedTree.Size <= maxTreeSize && clonedTree.Height <= maxTreeHeight) {
|
---|
87 |
|
---|
88 | // size constraints are fulfilled
|
---|
89 | // replace root of original tree with root of manipulated tree
|
---|
90 | symbolicExpressionTree.Root = clonedTree.Root;
|
---|
91 | return true;
|
---|
92 | } else {
|
---|
93 | // keep originalTree
|
---|
94 | return false;
|
---|
95 | }
|
---|
96 | }
|
---|
97 | catch (OverflowException) {
|
---|
98 | // keep original tree
|
---|
99 | return false;
|
---|
100 | }
|
---|
101 | }
|
---|
102 |
|
---|
103 | private static bool CreateNewArgumentForDefun(IRandom random, SymbolicExpressionTree tree, DefunTreeNode defunBranch, ArgumentTreeNode newArgumentNode) {
|
---|
104 | // select a random cut point in the function defining branch
|
---|
105 | // the branch at the cut point is to be replaced by a new argument node
|
---|
106 | var cutPoints = (from node in defunBranch.IterateNodesPrefix()
|
---|
107 | where node.SubTrees.Count > 0
|
---|
108 | from subtree in node.SubTrees
|
---|
109 | select new { Parent = node, ReplacedChildIndex = node.SubTrees.IndexOf(subtree), ReplacedChild = subtree }).ToList();
|
---|
110 |
|
---|
111 | if (cutPoints.Count() == 0)
|
---|
112 | // no cut point found => abort;
|
---|
113 | return false;
|
---|
114 | var selectedCutPoint = cutPoints[random.Next(cutPoints.Count)];
|
---|
115 | // replace the branch at the cut point with an argument node
|
---|
116 | var replacedBranch = selectedCutPoint.ReplacedChild;
|
---|
117 | selectedCutPoint.Parent.RemoveSubTree(selectedCutPoint.ReplacedChildIndex);
|
---|
118 | selectedCutPoint.Parent.InsertSubTree(selectedCutPoint.ReplacedChildIndex, newArgumentNode);
|
---|
119 |
|
---|
120 | // find all old invocations of the selected ADF and attach a cloned version of the replaced branch (with all argument-nodes expanded)
|
---|
121 | // iterate in post-fix order to make sure that the subtrees of n are already adapted when n is processed
|
---|
122 | var invocationNodes = (from node in tree.IterateNodesPostfix().OfType<InvokeFunctionTreeNode>()
|
---|
123 | where node.Symbol.FunctionName == defunBranch.FunctionName
|
---|
124 | where node.SubTrees.Count == defunBranch.NumberOfArguments
|
---|
125 | select node).ToList();
|
---|
126 | // do this repeatedly until no matching invocations are found
|
---|
127 | while (invocationNodes.Count > 0) {
|
---|
128 | List<SymbolicExpressionTreeNode> newlyAddedBranches = new List<SymbolicExpressionTreeNode>();
|
---|
129 | foreach (var invocationNode in invocationNodes) {
|
---|
130 | // check that the invocation node really has the correct number of arguments
|
---|
131 | if (invocationNode.SubTrees.Count != defunBranch.NumberOfArguments) throw new InvalidOperationException();
|
---|
132 | // append a new argument branch after expanding all argument nodes
|
---|
133 | var clonedBranch = (SymbolicExpressionTreeNode)replacedBranch.Clone();
|
---|
134 | clonedBranch = ReplaceArgumentsInBranch(clonedBranch, invocationNode.SubTrees);
|
---|
135 | invocationNode.InsertSubTree(newArgumentNode.Symbol.ArgumentIndex, clonedBranch);
|
---|
136 | newlyAddedBranches.Add(clonedBranch);
|
---|
137 | }
|
---|
138 | // iterate in post-fix order to make sure that the subtrees of n are already adapted when n is processed
|
---|
139 | invocationNodes = (from newlyAddedBranch in newlyAddedBranches
|
---|
140 | from node in newlyAddedBranch.IterateNodesPostfix().OfType<InvokeFunctionTreeNode>()
|
---|
141 | where node.Symbol.FunctionName == defunBranch.FunctionName
|
---|
142 | where node.SubTrees.Count == defunBranch.NumberOfArguments
|
---|
143 | select node).ToList();
|
---|
144 | }
|
---|
145 | // increase expected number of arguments of function defining branch
|
---|
146 | // it's possible that the number of actually referenced arguments was reduced (all references were replaced by a single new argument)
|
---|
147 | // but the number of expected arguments is increased anyway
|
---|
148 | defunBranch.NumberOfArguments++;
|
---|
149 | defunBranch.Grammar.AddSymbol(newArgumentNode.Symbol);
|
---|
150 | defunBranch.Grammar.SetMinSubtreeCount(newArgumentNode.Symbol, 0);
|
---|
151 | defunBranch.Grammar.SetMaxSubtreeCount(newArgumentNode.Symbol, 0);
|
---|
152 | // allow the argument as child of any other symbol
|
---|
153 | foreach (var symb in defunBranch.Grammar.Symbols)
|
---|
154 | for (int i = 0; i < defunBranch.Grammar.GetMaxSubtreeCount(symb); i++) {
|
---|
155 | defunBranch.Grammar.SetAllowedChild(symb, newArgumentNode.Symbol, i);
|
---|
156 | }
|
---|
157 | foreach (var subtree in tree.Root.SubTrees) {
|
---|
158 | // when the changed function is known in the branch then update the number of arguments
|
---|
159 | var matchingSymbol = subtree.Grammar.Symbols.OfType<InvokeFunction>().Where(s => s.FunctionName == defunBranch.FunctionName).SingleOrDefault();
|
---|
160 | if (matchingSymbol != null) {
|
---|
161 | subtree.Grammar.SetMinSubtreeCount(matchingSymbol, defunBranch.NumberOfArguments);
|
---|
162 | subtree.Grammar.SetMaxSubtreeCount(matchingSymbol, defunBranch.NumberOfArguments);
|
---|
163 | foreach (var child in subtree.GetAllowedSymbols(0)) {
|
---|
164 | for (int i = 0; i < subtree.Grammar.GetMaxSubtreeCount(matchingSymbol); i++) {
|
---|
165 | subtree.Grammar.SetAllowedChild(matchingSymbol, child, i);
|
---|
166 | }
|
---|
167 | }
|
---|
168 | }
|
---|
169 | }
|
---|
170 |
|
---|
171 | return true;
|
---|
172 | }
|
---|
173 |
|
---|
174 | private static SymbolicExpressionTreeNode ReplaceArgumentsInBranch(SymbolicExpressionTreeNode branch, IList<SymbolicExpressionTreeNode> argumentTrees) {
|
---|
175 | ArgumentTreeNode argNode = branch as ArgumentTreeNode;
|
---|
176 | if (argNode != null) {
|
---|
177 | // replace argument nodes by a clone of the original subtree that provided the result for the argument node
|
---|
178 | return (SymbolicExpressionTreeNode)argumentTrees[argNode.Symbol.ArgumentIndex].Clone();
|
---|
179 | } else {
|
---|
180 | // call recursively for all subtree
|
---|
181 | List<SymbolicExpressionTreeNode> subtrees = new List<SymbolicExpressionTreeNode>(branch.SubTrees);
|
---|
182 | while (branch.SubTrees.Count > 0) branch.RemoveSubTree(0);
|
---|
183 | foreach (var subtree in subtrees) {
|
---|
184 | branch.AddSubTree(ReplaceArgumentsInBranch(subtree, argumentTrees));
|
---|
185 | }
|
---|
186 | return branch;
|
---|
187 | }
|
---|
188 | }
|
---|
189 |
|
---|
190 | private static ArgumentTreeNode MakeArgumentNode(int argIndex) {
|
---|
191 | var node = (ArgumentTreeNode)(new Argument(argIndex)).CreateTreeNode();
|
---|
192 | return node;
|
---|
193 | }
|
---|
194 | }
|
---|
195 | }
|
---|