Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 4524 was 4249, checked in by mkommend, 14 years ago

Refactored grammars (ticket #1028).

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