Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HiveStatistics/sources/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/ArchitectureManipulators/ArgumentDuplicater.cs @ 11202

Last change on this file since 11202 was 11202, checked in by ascheibe, 10 years ago

merged trunk into hive statistics branch

File size: 7.2 KB
RevLine 
[3294]1#region License Information
2/* HeuristicLab
[11202]3 * Copyright (C) 2002-2014 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
[3294]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
[4722]22using System;
23using System.Collections.Generic;
[3294]24using System.Linq;
[4722]25using HeuristicLab.Common;
[3294]26using HeuristicLab.Core;
27using HeuristicLab.Data;
28using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
29
[5499]30namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding {
[3294]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>
[5510]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")]
[3294]36  [StorableClass]
[3534]37  public sealed class ArgumentDuplicater : SymbolicExpressionTreeArchitectureManipulator {
[4722]38    [StorableConstructor]
39    private ArgumentDuplicater(bool deserializing) : base(deserializing) { }
40    private ArgumentDuplicater(ArgumentDuplicater original, Cloner cloner) : base(original, cloner) { }
41    public ArgumentDuplicater() : base() { }
42
[3294]43    public override sealed void ModifyArchitecture(
44      IRandom random,
[5510]45      ISymbolicExpressionTree symbolicExpressionTree,
46      IntValue maxFunctionDefinitions, IntValue maxFunctionArguments) {
47      DuplicateArgument(random, symbolicExpressionTree, maxFunctionDefinitions.Value, maxFunctionArguments.Value);
[3294]48    }
49
[4722]50    public override IDeepCloneable Clone(Cloner cloner) {
51      return new ArgumentDuplicater(this, cloner);
52    }
53
[3294]54    public static bool DuplicateArgument(
55      IRandom random,
[5510]56      ISymbolicExpressionTree symbolicExpressionTree,
57      int maxFunctionDefinitions, int maxFunctionArguments) {
[3294]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
[3360]65      var selectedDefunBranch = functionDefiningBranches.SelectRandom(random);
66      var argumentSymbols = selectedDefunBranch.Grammar.Symbols.OfType<Argument>();
67      if (argumentSymbols.Count() == 0 || argumentSymbols.Count() >= maxFunctionArguments)
[3294]68        // when no argument or number of arguments is already at max allowed value => abort
69        return false;
[3360]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
[3294]76      // replace existing references to the original argument with references to the new argument randomly in the selectedBranch
[3360]77      var argumentNodes = selectedDefunBranch.IterateNodesPrefix().OfType<ArgumentTreeNode>();
[3294]78      foreach (var argNode in argumentNodes) {
[3360]79        if (argNode.Symbol == selectedArgumentSymbol) {
[3294]80          if (random.NextDouble() < 0.5) {
[3360]81            argNode.Symbol = newArgSymbol;
[3294]82          }
83        }
84      }
85      // find invocations of the functions and duplicate the matching argument branch
[4477]86      var invocationNodes = (from node in symbolicExpressionTree.IterateNodesPrefix().OfType<InvokeFunctionTreeNode>()
87                             where node.Symbol.FunctionName == selectedDefunBranch.FunctionName
[5733]88                             where node.Subtrees.Count() == selectedDefunBranch.NumberOfArguments
[4477]89                             select node).ToList();
[4106]90      // do this repeatedly until no matching invocations are found     
91      while (invocationNodes.Count() > 0) {
[5510]92        List<ISymbolicExpressionTreeNode> newlyAddedBranches = new List<ISymbolicExpressionTreeNode>();
[4106]93        foreach (var invokeNode in invocationNodes) {
[4524]94          // check that the invocation node really has the correct number of arguments
[5733]95          if (invokeNode.Subtrees.Count() != selectedDefunBranch.NumberOfArguments) throw new InvalidOperationException();
96          var argumentBranch = invokeNode.GetSubtree(selectedArgumentSymbol.ArgumentIndex);
[5510]97          var clonedArgumentBranch = (ISymbolicExpressionTreeNode)argumentBranch.Clone();
[5733]98          invokeNode.InsertSubtree(newArgumentIndex, clonedArgumentBranch);
[4106]99          newlyAddedBranches.Add(clonedArgumentBranch);
100        }
[4477]101        invocationNodes = (from newlyAddedBranch in newlyAddedBranches
102                           from node in newlyAddedBranch.IterateNodesPrefix().OfType<InvokeFunctionTreeNode>()
103                           where node.Symbol.FunctionName == selectedDefunBranch.FunctionName
[5733]104                           where node.Subtrees.Count() == selectedDefunBranch.NumberOfArguments
[4477]105                           select node).ToList();
[3294]106      }
[3360]107      // register the new argument symbol and increase the number of arguments of the ADF
108      selectedDefunBranch.Grammar.AddSymbol(newArgSymbol);
[5686]109      selectedDefunBranch.Grammar.SetSubtreeCount(newArgSymbol, 0, 0);
[5792]110      // allow the duplicated argument as child of all other arguments where the orginal argument was allowed
111      GrammarModifier.SetAllowedParentSymbols(selectedDefunBranch.Grammar, selectedArgumentSymbol, newArgSymbol);
[3294]112      selectedDefunBranch.NumberOfArguments++;
[3360]113
[3294]114      // increase the arity of the changed ADF in all branches that can use this ADF
[5733]115      foreach (var subtree in symbolicExpressionTree.Root.Subtrees) {
[3360]116        var matchingInvokeSymbol = (from symb in subtree.Grammar.Symbols.OfType<InvokeFunction>()
117                                    where symb.FunctionName == selectedDefunBranch.FunctionName
118                                    select symb).SingleOrDefault();
119        if (matchingInvokeSymbol != null) {
[5686]120          subtree.Grammar.SetSubtreeCount(matchingInvokeSymbol, selectedDefunBranch.NumberOfArguments, selectedDefunBranch.NumberOfArguments);
[5792]121          foreach (var symb in subtree.Grammar.Symbols) {
122            if (symb is StartSymbol || symb is ProgramRootSymbol) continue;
123            if (subtree.Grammar.IsAllowedChildSymbol(matchingInvokeSymbol, symb, selectedArgumentSymbol.ArgumentIndex))
124              subtree.Grammar.AddAllowedChildSymbol(matchingInvokeSymbol, symb, newArgumentIndex);
[3360]125          }
[3294]126        }
127      }
128      return true;
129    }
130  }
131}
Note: See TracBrowser for help on using the repository browser.