Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/ArchitectureManipulators/ArgumentDuplicater.cs @ 5906

Last change on this file since 5906 was 5809, checked in by mkommend, 14 years ago

#1418: Reintegrated branch into trunk.

File size: 7.2 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2011 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.Persistence.Default.CompositeSerializers.Storable;
29
30namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding {
31  /// <summary>
32  /// Manipulates a symbolic expression by duplicating an existing argument node of a function-defining branch.
33  /// As described in Koza, Bennett, Andre, Keane, Genetic Programming III - Darwinian Invention and Problem Solving, 1999, pp. 94
34  /// </summary>
35  [Item("ArgumentDuplicater", "Manipulates a symbolic expression by duplicating an existing argument node of a function-defining branch. As described in Koza, Bennett, Andre, Keane, Genetic Programming III - Darwinian Invention and Problem Solving, 1999, pp. 94")]
36  [StorableClass]
37  public sealed class ArgumentDuplicater : SymbolicExpressionTreeArchitectureManipulator {
38    [StorableConstructor]
39    private ArgumentDuplicater(bool deserializing) : base(deserializing) { }
40    private ArgumentDuplicater(ArgumentDuplicater original, Cloner cloner) : base(original, cloner) { }
41    public ArgumentDuplicater() : base() { }
42
43    public override sealed void ModifyArchitecture(
44      IRandom random,
45      ISymbolicExpressionTree symbolicExpressionTree,
46      IntValue maxFunctionDefinitions, IntValue maxFunctionArguments) {
47      DuplicateArgument(random, symbolicExpressionTree, maxFunctionDefinitions.Value, maxFunctionArguments.Value);
48    }
49
50    public override IDeepCloneable Clone(Cloner cloner) {
51      return new ArgumentDuplicater(this, cloner);
52    }
53
54    public static bool DuplicateArgument(
55      IRandom random,
56      ISymbolicExpressionTree symbolicExpressionTree,
57      int maxFunctionDefinitions, int maxFunctionArguments) {
58      var functionDefiningBranches = symbolicExpressionTree.IterateNodesPrefix().OfType<DefunTreeNode>();
59
60      var allowedArgumentIndexes = Enumerable.Range(0, maxFunctionArguments);
61      if (functionDefiningBranches.Count() == 0)
62        // no function defining branches => abort
63        return false;
64
65      var selectedDefunBranch = functionDefiningBranches.SelectRandom(random);
66      var argumentSymbols = selectedDefunBranch.Grammar.Symbols.OfType<Argument>();
67      if (argumentSymbols.Count() == 0 || argumentSymbols.Count() >= maxFunctionArguments)
68        // when no argument or number of arguments is already at max allowed value => abort
69        return false;
70      var selectedArgumentSymbol = argumentSymbols.SelectRandom(random);
71      var takenIndexes = argumentSymbols.Select(s => s.ArgumentIndex);
72      var newArgumentIndex = allowedArgumentIndexes.Except(takenIndexes).First();
73
74      var newArgSymbol = new Argument(newArgumentIndex);
75
76      // replace existing references to the original argument with references to the new argument randomly in the selectedBranch
77      var argumentNodes = selectedDefunBranch.IterateNodesPrefix().OfType<ArgumentTreeNode>();
78      foreach (var argNode in argumentNodes) {
79        if (argNode.Symbol == selectedArgumentSymbol) {
80          if (random.NextDouble() < 0.5) {
81            argNode.Symbol = newArgSymbol;
82          }
83        }
84      }
85      // find invocations of the functions and duplicate the matching argument branch
86      var invocationNodes = (from node in symbolicExpressionTree.IterateNodesPrefix().OfType<InvokeFunctionTreeNode>()
87                             where node.Symbol.FunctionName == selectedDefunBranch.FunctionName
88                             where node.Subtrees.Count() == selectedDefunBranch.NumberOfArguments
89                             select node).ToList();
90      // do this repeatedly until no matching invocations are found     
91      while (invocationNodes.Count() > 0) {
92        List<ISymbolicExpressionTreeNode> newlyAddedBranches = new List<ISymbolicExpressionTreeNode>();
93        foreach (var invokeNode in invocationNodes) {
94          // check that the invocation node really has the correct number of arguments
95          if (invokeNode.Subtrees.Count() != selectedDefunBranch.NumberOfArguments) throw new InvalidOperationException();
96          var argumentBranch = invokeNode.GetSubtree(selectedArgumentSymbol.ArgumentIndex);
97          var clonedArgumentBranch = (ISymbolicExpressionTreeNode)argumentBranch.Clone();
98          invokeNode.InsertSubtree(newArgumentIndex, clonedArgumentBranch);
99          newlyAddedBranches.Add(clonedArgumentBranch);
100        }
101        invocationNodes = (from newlyAddedBranch in newlyAddedBranches
102                           from node in newlyAddedBranch.IterateNodesPrefix().OfType<InvokeFunctionTreeNode>()
103                           where node.Symbol.FunctionName == selectedDefunBranch.FunctionName
104                           where node.Subtrees.Count() == selectedDefunBranch.NumberOfArguments
105                           select node).ToList();
106      }
107      // register the new argument symbol and increase the number of arguments of the ADF
108      selectedDefunBranch.Grammar.AddSymbol(newArgSymbol);
109      selectedDefunBranch.Grammar.SetSubtreeCount(newArgSymbol, 0, 0);
110      // allow the duplicated argument as child of all other arguments where the orginal argument was allowed
111      GrammarModifier.SetAllowedParentSymbols(selectedDefunBranch.Grammar, selectedArgumentSymbol, newArgSymbol);
112      selectedDefunBranch.NumberOfArguments++;
113
114      // increase the arity of the changed ADF in all branches that can use this ADF
115      foreach (var subtree in symbolicExpressionTree.Root.Subtrees) {
116        var matchingInvokeSymbol = (from symb in subtree.Grammar.Symbols.OfType<InvokeFunction>()
117                                    where symb.FunctionName == selectedDefunBranch.FunctionName
118                                    select symb).SingleOrDefault();
119        if (matchingInvokeSymbol != null) {
120          subtree.Grammar.SetSubtreeCount(matchingInvokeSymbol, selectedDefunBranch.NumberOfArguments, selectedDefunBranch.NumberOfArguments);
121          foreach (var symb in subtree.Grammar.Symbols) {
122            if (symb is StartSymbol || symb is ProgramRootSymbol) continue;
123            if (subtree.Grammar.IsAllowedChildSymbol(matchingInvokeSymbol, symb, selectedArgumentSymbol.ArgumentIndex))
124              subtree.Grammar.AddAllowedChildSymbol(matchingInvokeSymbol, symb, newArgumentIndex);
125          }
126        }
127      }
128      return true;
129    }
130  }
131}
Note: See TracBrowser for help on using the repository browser.