Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.3/ArchitectureAlteringOperators/ArgumentCreater.cs @ 3360

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

Fixed bugs in ADF operators and added test classes for ADF operators. #290 (Implement ADFs)

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