Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.3/ArchitectureManipulators/SubroutineDuplicater.cs @ 5386

Last change on this file since 5386 was 4722, checked in by swagner, 14 years ago

Merged cloning refactoring branch back into trunk (#922)

File size: 6.0 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.Collections.Generic;
24using System.Linq;
25using System.Text;
26using HeuristicLab.Common;
27using HeuristicLab.Core;
28using HeuristicLab.Data;
29using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Symbols;
30using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
31
32namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.ArchitectureManipulators {
33  /// <summary>
34  /// Manipulates a symbolic expression by duplicating a preexisting function-defining branch.
35  /// As described in Koza, Bennett, Andre, Keane, Genetic Programming III - Darwinian Invention and Problem Solving, 1999, pp. 88
36  /// </summary>
37  [Item("SubroutineDuplicater", "Manipulates a symbolic expression by duplicating a preexisting function-defining branch.")]
38  [StorableClass]
39  public sealed class SubroutineDuplicater : SymbolicExpressionTreeArchitectureManipulator {
40    [StorableConstructor]
41    private SubroutineDuplicater(bool deserializing) : base(deserializing) { }
42    private SubroutineDuplicater(SubroutineDuplicater original, Cloner cloner)
43      : base(original, cloner) {
44    }
45    public SubroutineDuplicater() : base() { }
46
47    public override IDeepCloneable Clone(Cloner cloner) {
48      return new SubroutineDuplicater(this, cloner);
49    }
50
51    public override sealed void ModifyArchitecture(
52      IRandom random,
53      SymbolicExpressionTree symbolicExpressionTree,
54      ISymbolicExpressionGrammar grammar,
55      IntValue maxTreeSize, IntValue maxTreeHeight,
56      IntValue maxFunctionDefiningBranches, IntValue maxFunctionArguments,
57      out bool success) {
58      success = DuplicateSubroutine(random, symbolicExpressionTree, grammar, maxTreeSize.Value, maxTreeHeight.Value, maxFunctionDefiningBranches.Value, maxFunctionArguments.Value);
59    }
60
61    public static bool DuplicateSubroutine(
62      IRandom random,
63      SymbolicExpressionTree symbolicExpressionTree,
64      ISymbolicExpressionGrammar grammar,
65      int maxTreeSize, int maxTreeHeight,
66      int maxFunctionDefiningBranches, int maxFunctionArguments) {
67      var functionDefiningBranches = symbolicExpressionTree.IterateNodesPrefix().OfType<DefunTreeNode>();
68      if (functionDefiningBranches.Count() == 0 || functionDefiningBranches.Count() == maxFunctionDefiningBranches)
69        // no function defining branches to duplicate or already reached the max number of ADFs
70        return false;
71
72      string formatString = new StringBuilder().Append('0', (int)Math.Log10(maxFunctionDefiningBranches) + 1).ToString(); // >= 100 functions => ###
73      var allowedFunctionNames = from index in Enumerable.Range(0, maxFunctionDefiningBranches)
74                                 select "ADF" + index.ToString(formatString);
75      var selectedBranch = functionDefiningBranches.SelectRandom(random);
76      var duplicatedDefunBranch = (DefunTreeNode)selectedBranch.Clone();
77      string newFunctionName = allowedFunctionNames.Except(UsedFunctionNames(symbolicExpressionTree)).First();
78      duplicatedDefunBranch.FunctionName = newFunctionName;
79      symbolicExpressionTree.Root.AddSubTree(duplicatedDefunBranch);
80      duplicatedDefunBranch.SetGrammar((ISymbolicExpressionGrammar)selectedBranch.Grammar.Clone());
81      // add an invoke symbol for each branch that is allowed to invoke the original function
82      foreach (var subtree in symbolicExpressionTree.Root.SubTrees.OfType<SymbolicExpressionTreeTopLevelNode>()) {
83        var matchingInvokeSymbol = (from symb in subtree.Grammar.Symbols.OfType<InvokeFunction>()
84                                    where symb.FunctionName == selectedBranch.FunctionName
85                                    select symb).SingleOrDefault();
86        if (matchingInvokeSymbol != null) {
87          GrammarModifier.AddDynamicSymbol(subtree.Grammar, subtree.Symbol, duplicatedDefunBranch.FunctionName, duplicatedDefunBranch.NumberOfArguments);
88        }
89        // in the current subtree:
90        // for all invoke nodes of the original function replace the invoke of the original function with an invoke of the new function randomly
91        var originalFunctionInvocations = from node in subtree.IterateNodesPrefix().OfType<InvokeFunctionTreeNode>()
92                                          where node.Symbol.FunctionName == selectedBranch.FunctionName
93                                          select node;
94        foreach (var originalFunctionInvokeNode in originalFunctionInvocations) {
95          var newInvokeSymbol = (from symb in subtree.Grammar.Symbols.OfType<InvokeFunction>()
96                                 where symb.FunctionName == duplicatedDefunBranch.FunctionName
97                                 select symb).Single();
98          // flip coin wether to replace with newly defined function
99          if (random.NextDouble() < 0.5) {
100            originalFunctionInvokeNode.Symbol = newInvokeSymbol;
101          }
102        }
103      }
104      return true;
105    }
106
107    private static IEnumerable<string> UsedFunctionNames(SymbolicExpressionTree symbolicExpressionTree) {
108      return from node in symbolicExpressionTree.IterateNodesPrefix()
109             where node.Symbol is Defun
110             select ((DefunTreeNode)node).FunctionName;
111    }
112  }
113}
Note: See TracBrowser for help on using the repository browser.