Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.3/ArchitectureAlteringOperators/SubroutineDuplicater.cs @ 3534

Last change on this file since 3534 was 3534, checked in by gkronber, 14 years ago

Added interfaces for symbolic expression tree operators and added multi manipulation operators. #937 (Data types and operators for symbolic expression tree encoding)

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