Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.3/ArchitectureManipulators/ArgumentCreater.cs @ 4047

Last change on this file since 4047 was 3985, checked in by gkronber, 14 years ago

Fixed statements that modify the list of sub-trees of a SymbolicExpressionTreeNodes directly. #938

File size: 7.9 KB
Line 
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
22using System;
23using System.Linq;
24using HeuristicLab.Common;
25using HeuristicLab.Core;
26using HeuristicLab.Data;
27using HeuristicLab.Operators;
28using HeuristicLab.Optimization;
29using HeuristicLab.Parameters;
30using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
31using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Symbols;
32using System.Collections.Generic;
33using System.Text;
34using System.Diagnostics;
35
36namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.ArchitectureManipulators {
37  /// <summary>
38  /// Creates a new argument within one function-defining branch of a symbolic expression tree.
39  /// As described in Koza, Bennett, Andre, Keane, Genetic Programming III - Darwinian Invention and Problem Solving, 1999, pp. 106
40  /// </summary>
41  [Item("ArgumentCreater", "Manipulates a symbolic expression by creating a new argument within one function-defining branch.")]
42  [StorableClass]
43  public sealed class ArgumentCreater : SymbolicExpressionTreeArchitectureManipulator {
44    public override sealed void ModifyArchitecture(
45      IRandom random,
46      SymbolicExpressionTree symbolicExpressionTree,
47      ISymbolicExpressionGrammar grammar,
48      IntValue maxTreeSize, IntValue maxTreeHeight,
49      IntValue maxFunctionDefiningBranches, IntValue maxFunctionArguments,
50      out bool success) {
51      success = CreateNewArgument(random, symbolicExpressionTree, grammar, maxTreeSize.Value, maxTreeHeight.Value, maxFunctionDefiningBranches.Value, maxFunctionArguments.Value);
52    }
53
54    public static bool CreateNewArgument(
55      IRandom random,
56      SymbolicExpressionTree symbolicExpressionTree,
57      ISymbolicExpressionGrammar grammar,
58      int maxTreeSize, int maxTreeHeight,
59      int maxFunctionDefiningBranches, int maxFunctionArguments) {
60
61      var functionDefiningBranches = symbolicExpressionTree.IterateNodesPrefix().OfType<DefunTreeNode>();
62
63      if (functionDefiningBranches.Count() == 0)
64        // no function defining branch found => abort
65        return false;
66
67      // select a random function defining branch
68      var selectedDefunBranch = functionDefiningBranches.SelectRandom(random);
69      var definedArguments = (from symbol in selectedDefunBranch.Grammar.Symbols.OfType<Argument>()
70                              select symbol.ArgumentIndex).Distinct();
71      if (definedArguments.Count() >= maxFunctionArguments)
72        // max number of arguments reached => abort
73        return false;
74      // select a random cut point in the function defining branch
75      // the branch at the cut point is to be replaced by a new argument node
76      var cutPoints = (from node in selectedDefunBranch.IterateNodesPrefix()
77                       where node.SubTrees.Count > 0
78                       from subtree in node.SubTrees
79                       select new { Parent = node, ReplacedChildIndex = node.SubTrees.IndexOf(subtree), ReplacedChild = subtree }).ToList();
80
81      if (cutPoints.Count() == 0)
82        // no cut point found => abort;
83        return false;
84      var selectedCutPoint = cutPoints[random.Next(cutPoints.Count)];
85      var allowedArgumentIndexes = Enumerable.Range(0, maxFunctionArguments);
86      var newArgumentIndex = allowedArgumentIndexes.Except(definedArguments).First();
87      // replace the branch at the cut point with an argument node
88      var newArgNode = MakeArgumentNode(newArgumentIndex);
89      var replacedBranch = selectedCutPoint.ReplacedChild;
90      selectedCutPoint.Parent.RemoveSubTree(selectedCutPoint.ReplacedChildIndex);
91      selectedCutPoint.Parent.InsertSubTree(selectedCutPoint.ReplacedChildIndex, newArgNode);
92      // find all invocations of the selected ADF and attach a cloned version of the replaced branch (with all argument-nodes expanded)
93      var invocationNodes = from node in symbolicExpressionTree.IterateNodesPrefix().OfType<InvokeFunctionTreeNode>()
94                            where node.Symbol.FunctionName == selectedDefunBranch.FunctionName
95                            select node;
96      foreach (var invocationNode in invocationNodes) {
97        // append a new argument branch after expanding all argument nodes
98        var clonedBranch = (SymbolicExpressionTreeNode)replacedBranch.Clone();
99        clonedBranch = ReplaceArgumentsInBranch(clonedBranch, invocationNode.SubTrees);
100        invocationNode.InsertSubTree(newArgumentIndex, clonedBranch);
101      }
102      // increase expected number of arguments of function defining branch
103      // it's possible that the number of actually referenced arguments was reduced (all references were replaced by a single new argument)
104      // but the number of expected arguments is increased anyway
105      selectedDefunBranch.NumberOfArguments++;
106      selectedDefunBranch.Grammar.AddSymbol(newArgNode.Symbol);
107      selectedDefunBranch.Grammar.SetMinSubtreeCount(newArgNode.Symbol, 0);
108      selectedDefunBranch.Grammar.SetMaxSubtreeCount(newArgNode.Symbol, 0);
109      // allow the argument as child of any other symbol
110      foreach (var symb in selectedDefunBranch.Grammar.Symbols)
111        for (int i = 0; i < selectedDefunBranch.Grammar.GetMaxSubtreeCount(symb); i++) {
112          selectedDefunBranch.Grammar.SetAllowedChild(symb, newArgNode.Symbol, i);
113        }
114      foreach (var subtree in symbolicExpressionTree.Root.SubTrees) {
115        // when the changed function is known in the branch then update the number of arguments
116        var matchingSymbol = subtree.Grammar.Symbols.OfType<InvokeFunction>().Where(s => s.FunctionName == selectedDefunBranch.FunctionName).SingleOrDefault();
117        if (matchingSymbol != null) {
118          subtree.Grammar.SetMinSubtreeCount(matchingSymbol, selectedDefunBranch.NumberOfArguments);
119          subtree.Grammar.SetMaxSubtreeCount(matchingSymbol, selectedDefunBranch.NumberOfArguments);
120          foreach (var child in subtree.GetAllowedSymbols(0)) {
121            for (int i = 0; i < subtree.Grammar.GetMaxSubtreeCount(matchingSymbol); i++) {
122              subtree.Grammar.SetAllowedChild(matchingSymbol, child, i);
123            }
124          }
125        }
126      }
127      return true;
128    }
129
130    private static SymbolicExpressionTreeNode ReplaceArgumentsInBranch(SymbolicExpressionTreeNode branch, IList<SymbolicExpressionTreeNode> argumentTrees) {
131      if (branch is ArgumentTreeNode) {
132        var argNode = branch as ArgumentTreeNode;
133        // replace argument nodes by a clone of the original subtree that provided the result for the argument node
134        return (SymbolicExpressionTreeNode)argumentTrees[argNode.Symbol.ArgumentIndex].Clone();
135      } else {
136        // call recursively for all subtree
137        List<SymbolicExpressionTreeNode> subtrees = new List<SymbolicExpressionTreeNode>(branch.SubTrees);
138        while (branch.SubTrees.Count > 0) branch.RemoveSubTree(0);
139        foreach (var subtree in subtrees) {
140          branch.AddSubTree(ReplaceArgumentsInBranch(subtree, argumentTrees));
141        }
142        return branch;
143      }
144    }
145
146    private static SymbolicExpressionTreeNode MakeArgumentNode(int argIndex) {
147      var node = (ArgumentTreeNode)(new Argument(argIndex)).CreateTreeNode();
148      return node;
149    }
150  }
151}
Note: See TracBrowser for help on using the repository browser.