Free cookie consent management tool by TermsFeed Policy Generator

source: branches/DataAnalysis Refactoring/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/ArchitectureManipulators/ArgumentDuplicater.cs @ 5529

Last change on this file since 5529 was 5529, checked in by gkronber, 13 years ago

#1418 Removed grammar specific members from ISymbolicExpressionTreeNode interface.

File size: 7.3 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.SetMinSubtreeCount(newArgSymbol, 0);
110      selectedDefunBranch.Grammar.SetMaxSubtreeCount(newArgSymbol, 0);
111      // allow the argument as child of any other symbol
112      foreach (var symb in selectedDefunBranch.Grammar.Symbols)
113        for (int i = 0; i < selectedDefunBranch.Grammar.GetMaxSubtreeCount(symb); i++) {
114          selectedDefunBranch.Grammar.SetAllowedChild(symb, newArgSymbol, i);
115        }
116      selectedDefunBranch.NumberOfArguments++;
117
118      // increase the arity of the changed ADF in all branches that can use this ADF
119      foreach (var subtree in symbolicExpressionTree.Root.SubTrees) {
120        var matchingInvokeSymbol = (from symb in subtree.Grammar.Symbols.OfType<InvokeFunction>()
121                                    where symb.FunctionName == selectedDefunBranch.FunctionName
122                                    select symb).SingleOrDefault();
123        if (matchingInvokeSymbol != null) {
124          subtree.Grammar.SetMinSubtreeCount(matchingInvokeSymbol, selectedDefunBranch.NumberOfArguments);
125          subtree.Grammar.SetMaxSubtreeCount(matchingInvokeSymbol, selectedDefunBranch.NumberOfArguments);
126          foreach (var child in subtree.Grammar.GetAllowedSymbols(subtree.Symbol, 0)) {
127            for (int i = 0; i < subtree.Grammar.GetMaxSubtreeCount(matchingInvokeSymbol); i++) {
128              subtree.Grammar.SetAllowedChild(matchingInvokeSymbol, child, i);
129            }
130          }
131        }
132      }
133      return true;
134    }
135  }
136}
Note: See TracBrowser for help on using the repository browser.