Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.3/ArchitectureAlteringOperators/ArgumentDuplicater.cs @ 3369

Last change on this file since 3369 was 3360, checked in by gkronber, 15 years ago

Fixed bugs in ADF operators and added test classes for ADF operators. #290 (Implement ADFs)

File size: 6.3 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.Core;
25using HeuristicLab.Data;
26using HeuristicLab.Operators;
27using HeuristicLab.Optimization;
28using HeuristicLab.Parameters;
29using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
30using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.GeneralSymbols;
31using System.Collections.Generic;
32using System.Text;
33using System.Diagnostics;
34
35namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.ArchitectureAlteringOperators {
36  /// <summary>
37  /// Manipulates a symbolic expression by duplicating an existing argument node of a function-defining branch.
38  /// As described in Koza, Bennett, Andre, Keane, Genetic Programming III - Darwinian Invention and Problem Solving, 1999, pp. 94
39  /// </summary>
40  [Item("ArgumentDuplicater", "Manipulates a symbolic expression by duplicating an existing argument node of a function-defining branch.")]
41  [StorableClass]
42  public sealed class ArgumentDuplicater : SymbolicExpressionTreeArchitectureAlteringOperator {
43    public override sealed void ModifyArchitecture(
44      IRandom random,
45      SymbolicExpressionTree symbolicExpressionTree,
46      ISymbolicExpressionGrammar grammar,
47      IntValue maxTreeSize, IntValue maxTreeHeight,
48      IntValue maxFunctionDefiningBranches, IntValue maxFunctionArguments,
49      out bool success) {
50      success = DuplicateArgument(random, symbolicExpressionTree, grammar, maxTreeSize.Value, maxTreeHeight.Value, maxFunctionDefiningBranches.Value, maxFunctionArguments.Value);
51    }
52
53    public static bool DuplicateArgument(
54      IRandom random,
55      SymbolicExpressionTree symbolicExpressionTree,
56      ISymbolicExpressionGrammar grammar,
57      int maxTreeSize, int maxTreeHeight,
58      int maxFunctionDefiningBranches, int maxFunctionArguments) {
59      var functionDefiningBranches = symbolicExpressionTree.IterateNodesPrefix().OfType<DefunTreeNode>();
60
61      var allowedArgumentIndexes = Enumerable.Range(0, maxFunctionArguments);
62      if (functionDefiningBranches.Count() == 0)
63        // no function defining branches => abort
64        return false;
65
66      var selectedDefunBranch = functionDefiningBranches.SelectRandom(random);
67      var argumentSymbols = selectedDefunBranch.Grammar.Symbols.OfType<Argument>();
68      if (argumentSymbols.Count() == 0 || argumentSymbols.Count() >= maxFunctionArguments)
69        // when no argument or number of arguments is already at max allowed value => abort
70        return false;
71      var selectedArgumentSymbol = argumentSymbols.SelectRandom(random);
72      var takenIndexes = argumentSymbols.Select(s => s.ArgumentIndex);
73      var newArgumentIndex = allowedArgumentIndexes.Except(takenIndexes).First();
74
75      var newArgSymbol = new Argument(newArgumentIndex);
76
77      // replace existing references to the original argument with references to the new argument randomly in the selectedBranch
78      var argumentNodes = selectedDefunBranch.IterateNodesPrefix().OfType<ArgumentTreeNode>();
79      foreach (var argNode in argumentNodes) {
80        if (argNode.Symbol == selectedArgumentSymbol) {
81          if (random.NextDouble() < 0.5) {
82            argNode.Symbol = newArgSymbol;
83          }
84        }
85      }
86      // find invocations of the functions and duplicate the matching argument branch
87      var invocationNodes = from node in symbolicExpressionTree.IterateNodesPrefix().OfType<InvokeFunctionTreeNode>()
88                            where node.Symbol.FunctionName == selectedDefunBranch.FunctionName
89                            select node;
90      foreach (var invokeNode in invocationNodes) {
91        var argumentBranch = invokeNode.SubTrees[selectedArgumentSymbol.ArgumentIndex];
92        var clonedArgumentBranch = (SymbolicExpressionTreeNode)argumentBranch.Clone();
93        invokeNode.InsertSubTree(newArgumentIndex, clonedArgumentBranch);
94      }
95      // register the new argument symbol and increase the number of arguments of the ADF
96      selectedDefunBranch.Grammar.AddSymbol(newArgSymbol);
97      selectedDefunBranch.Grammar.SetMinSubtreeCount(newArgSymbol, 0);
98      selectedDefunBranch.Grammar.SetMaxSubtreeCount(newArgSymbol, 0);
99      // allow the argument as child of any other symbol
100      foreach (var symb in selectedDefunBranch.Grammar.Symbols)
101        for (int i = 0; i < selectedDefunBranch.Grammar.GetMaxSubtreeCount(symb); i++) {
102          selectedDefunBranch.Grammar.SetAllowedChild(symb, newArgSymbol, i);
103        }
104      selectedDefunBranch.NumberOfArguments++;
105
106      // increase the arity of the changed ADF in all branches that can use this ADF
107      foreach (var subtree in symbolicExpressionTree.Root.SubTrees) {
108        var matchingInvokeSymbol = (from symb in subtree.Grammar.Symbols.OfType<InvokeFunction>()
109                                    where symb.FunctionName == selectedDefunBranch.FunctionName
110                                    select symb).SingleOrDefault();
111        if (matchingInvokeSymbol != null) {
112          subtree.Grammar.SetMinSubtreeCount(matchingInvokeSymbol, selectedDefunBranch.NumberOfArguments);
113          subtree.Grammar.SetMaxSubtreeCount(matchingInvokeSymbol, selectedDefunBranch.NumberOfArguments);
114          foreach (var child in subtree.GetAllowedSymbols(0)) {
115            for (int i = 0; i < subtree.Grammar.GetMaxSubtreeCount(matchingInvokeSymbol); i++) {
116              subtree.Grammar.SetAllowedChild(matchingInvokeSymbol, child, i);
117            }
118          }
119        }
120      }
121      return true;
122    }
123  }
124}
Note: See TracBrowser for help on using the repository browser.