Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 3338 was 3338, checked in by gkronber, 12 years ago

Fixed bugs related to dynamic symbol constraints with ADFs. #290 (Implement ADFs)

File size: 7.6 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        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.Where(s => s.Name == selectedDefunBranch.FunctionName).SingleOrDefault();
116        if (matchingSymbol != null) {
117          subtree.Grammar.SetMinSubtreeCount(matchingSymbol, selectedDefunBranch.NumberOfArguments);
118          subtree.Grammar.SetMaxSubtreeCount(matchingSymbol, selectedDefunBranch.NumberOfArguments);
119        }
120      }
121      return true;
122    }
123
124    private static void ReplaceArgumentsInBranch(SymbolicExpressionTreeNode branch, IList<SymbolicExpressionTreeNode> argumentTrees) {
125      // check if any subtree is an argument node
126      for (int subtreeIndex = 0; subtreeIndex < branch.SubTrees.Count; subtreeIndex++) {
127        var subtree = branch.SubTrees[subtreeIndex];
128        var argNode = subtree as ArgumentTreeNode;
129        if (argNode != null) {
130          // replace argument nodes by a clone of the original subtree that provided the result for the argument node
131          branch.SubTrees[subtreeIndex] = (SymbolicExpressionTreeNode)argumentTrees[argNode.Symbol.ArgumentIndex].Clone();
132        } else {
133          // recursively replace arguments in all branches
134          ReplaceArgumentsInBranch(subtree, argumentTrees);
135        }
136      }
137    }
138
139    private static SymbolicExpressionTreeNode MakeArgumentNode(int argIndex) {
140      var node = (ArgumentTreeNode)(new Argument(argIndex)).CreateTreeNode();
141      return node;
142    }
143  }
144}
Note: See TracBrowser for help on using the repository browser.