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

Last change on this file since 18064 was 18064, checked in by mkommend, 8 weeks ago

#2997: Simplified tree creator interface and removed cloning of grammars,

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