Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Creators/GrowTreeCreator.cs @ 13042

Last change on this file since 13042 was 12844, checked in by mkommend, 9 years ago

#2458: Adapted tree creators to work with the same depth restriction as the PTC2 (excluding the root symbol).

File size: 6.9 KB
RevLine 
[6887]1#region License Information
2/* HeuristicLab
[12012]3 * Copyright (C) 2002-2015 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
[6887]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.Persistence.Default.CompositeSerializers.Storable;
[7012]27using HeuristicLab.PluginInfrastructure;
[6887]28
29namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding {
[7012]30  [NonDiscoverableType]
[6887]31  [StorableClass]
32  [Item("GrowTreeCreator", "An operator that creates new symbolic expression trees using the 'Grow' method")]
[12422]33  public class GrowTreeCreator : SymbolicExpressionTreeCreator {
[6887]34    [StorableConstructor]
35    protected GrowTreeCreator(bool deserializing) : base(deserializing) { }
36    protected GrowTreeCreator(GrowTreeCreator original, Cloner cloner) : base(original, cloner) { }
37
[12422]38    public GrowTreeCreator() : base() { }
[6887]39
40    public override IDeepCloneable Clone(Cloner cloner) {
41      return new GrowTreeCreator(this, cloner);
42    }
43
44
45    protected override ISymbolicExpressionTree Create(IRandom random) {
[11496]46      return Create(random, ClonedSymbolicExpressionTreeGrammarParameter.ActualValue,
[12422]47        MaximumSymbolicExpressionTreeLengthParameter.ActualValue.Value, MaximumSymbolicExpressionTreeDepthParameter.ActualValue.Value);
[6887]48    }
49
[7012]50    public override ISymbolicExpressionTree CreateTree(IRandom random, ISymbolicExpressionGrammar grammar, int maxTreeLength, int maxTreeDepth) {
51      return Create(random, grammar, maxTreeLength, maxTreeDepth);
52    }
53
[6887]54    /// <summary>
55    /// Create a symbolic expression tree using the 'Grow' method.
56    /// All symbols are allowed for nodes, so the resulting trees can be of any shape and size.
57    /// </summary>
58    /// <param name="random">Random generator</param>
59    /// <param name="grammar">Available tree grammar</param>
60    /// <param name="maxTreeDepth">Maximum tree depth</param>
[7012]61    /// <param name="maxTreeLength">Maximum tree length. This parameter is not used.</param>
[6887]62    /// <returns></returns>
[7012]63    public static ISymbolicExpressionTree Create(IRandom random, ISymbolicExpressionGrammar grammar, int maxTreeLength, int maxTreeDepth) {
[6887]64      var tree = new SymbolicExpressionTree();
65      var rootNode = (SymbolicExpressionTreeTopLevelNode)grammar.ProgramRootSymbol.CreateTreeNode();
66      if (rootNode.HasLocalParameters) rootNode.ResetLocalParameters(random);
[11496]67      rootNode.SetGrammar(grammar.CreateExpressionTreeGrammar());
[6887]68
[11496]69
[6887]70      var startNode = (SymbolicExpressionTreeTopLevelNode)grammar.StartSymbol.CreateTreeNode();
[7236]71      if (startNode.HasLocalParameters) startNode.ResetLocalParameters(random);
[11496]72      startNode.SetGrammar(grammar.CreateExpressionTreeGrammar());
[6887]73
74      rootNode.AddSubtree(startNode);
75
[12844]76      Create(random, startNode, maxTreeDepth - 1);
[6887]77      tree.Root = rootNode;
78      return tree;
79    }
80
[7236]81    public static void Create(IRandom random, ISymbolicExpressionTreeNode seedNode, int maxDepth) {
[6887]82      // make sure it is possible to create a trees smaller than maxDepth
83      if (seedNode.Grammar.GetMinimumExpressionDepth(seedNode.Symbol) > maxDepth)
84        throw new ArgumentException("Cannot create trees of depth " + maxDepth + " or smaller because of grammar constraints.", "maxDepth");
85
86      var arity = SampleArity(random, seedNode);
[6888]87      // throw an exception if the seedNode happens to be a terminal, since in this case we cannot grow a tree
[6944]88      if (arity <= 0)
89        throw new ArgumentException("Cannot grow tree. Seed node shouldn't have arity zero.");
[6887]90
[12422]91      var allowedSymbols = seedNode.Grammar.AllowedSymbols.Where(s => s.InitialFrequency > 0.0).ToList();
[6887]92
[7236]93      for (var i = 0; i < arity; i++) {
[12422]94        var possibleSymbols = allowedSymbols.Where(s => seedNode.Grammar.IsAllowedChildSymbol(seedNode.Symbol, s, i)).ToList();
[7961]95        var weights = possibleSymbols.Select(s => s.InitialFrequency).ToList();
[12422]96
97#pragma warning disable 612, 618
[7961]98        var selectedSymbol = possibleSymbols.SelectRandom(weights, random);
[12422]99#pragma warning restore 612, 618
100
[6887]101        var tree = selectedSymbol.CreateTreeNode();
102        if (tree.HasLocalParameters) tree.ResetLocalParameters(random);
103        seedNode.AddSubtree(tree);
104      }
105
[6888]106      // Only iterate over the non-terminal nodes (those which have arity > 0)
107      // Start from depth 2 since the first two levels are formed by the rootNode and the seedNode
[7236]108      foreach (var subTree in seedNode.Subtrees)
109        if (subTree.Grammar.GetMaximumSubtreeCount(subTree.Symbol) > 0)
110          RecursiveCreate(random, subTree, 2, maxDepth);
[6887]111    }
112
[7236]113    private static void RecursiveCreate(IRandom random, ISymbolicExpressionTreeNode root, int currentDepth, int maxDepth) {
[6887]114      var arity = SampleArity(random, root);
[12422]115      if (arity == 0)
116        return;
[6887]117
[7961]118      var allowedSymbols = root.Grammar.AllowedSymbols.Where(s => s.InitialFrequency > 0.0).ToList();
[7108]119
[7236]120      for (var i = 0; i < arity; i++) {
[12422]121        var possibleSymbols = allowedSymbols.Where(s => root.Grammar.IsAllowedChildSymbol(root.Symbol, s, i) &&
122                                                        root.Grammar.GetMinimumExpressionDepth(s) - 1 <= maxDepth - currentDepth).ToList();
[7961]123
[7108]124        if (!possibleSymbols.Any())
125          throw new InvalidOperationException("No symbols are available for the tree.");
[12422]126
[7961]127        var weights = possibleSymbols.Select(s => s.InitialFrequency).ToList();
[12422]128#pragma warning disable 612, 618
[7961]129        var selectedSymbol = possibleSymbols.SelectRandom(weights, random);
[12422]130#pragma warning restore 612, 618
131
[6887]132        var tree = selectedSymbol.CreateTreeNode();
133        if (tree.HasLocalParameters) tree.ResetLocalParameters(random);
134        root.AddSubtree(tree);
135      }
136
[12422]137      if (maxDepth > currentDepth)
138        foreach (var subTree in root.Subtrees)
139          if (subTree.Grammar.GetMaximumSubtreeCount(subTree.Symbol) != 0)
140            RecursiveCreate(random, subTree, currentDepth + 1, maxDepth);
[6887]141    }
142
143    private static int SampleArity(IRandom random, ISymbolicExpressionTreeNode node) {
144      var minArity = node.Grammar.GetMinimumSubtreeCount(node.Symbol);
145      var maxArity = node.Grammar.GetMaximumSubtreeCount(node.Symbol);
146
147      return random.Next(minArity, maxArity + 1);
148    }
149  }
[7961]150}
Note: See TracBrowser for help on using the repository browser.