Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2915-AbsoluteSymbol/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Creators/GrowTreeCreator.cs @ 15982

Last change on this file since 15982 was 15583, checked in by swagner, 7 years ago

#2640: Updated year of copyrights in license headers

File size: 6.9 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2018 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.Persistence.Default.CompositeSerializers.Storable;
27using HeuristicLab.PluginInfrastructure;
28
29namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding {
30  [NonDiscoverableType]
31  [StorableClass]
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(bool deserializing) : base(deserializing) { }
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
45    protected override ISymbolicExpressionTree Create(IRandom random) {
46      return Create(random, ClonedSymbolicExpressionTreeGrammarParameter.ActualValue,
47        MaximumSymbolicExpressionTreeLengthParameter.ActualValue.Value, MaximumSymbolicExpressionTreeDepthParameter.ActualValue.Value);
48    }
49
50    public override ISymbolicExpressionTree CreateTree(IRandom random, ISymbolicExpressionGrammar grammar, int maxTreeLength, int maxTreeDepth) {
51      return Create(random, grammar, maxTreeLength, maxTreeDepth);
52    }
53
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>
61    /// <param name="maxTreeLength">Maximum tree length. This parameter is not used.</param>
62    /// <returns></returns>
63    public static ISymbolicExpressionTree Create(IRandom random, ISymbolicExpressionGrammar grammar, int maxTreeLength, int maxTreeDepth) {
64      var tree = new SymbolicExpressionTree();
65      var rootNode = (SymbolicExpressionTreeTopLevelNode)grammar.ProgramRootSymbol.CreateTreeNode();
66      if (rootNode.HasLocalParameters) rootNode.ResetLocalParameters(random);
67      rootNode.SetGrammar(grammar.CreateExpressionTreeGrammar());
68
69
70      var startNode = (SymbolicExpressionTreeTopLevelNode)grammar.StartSymbol.CreateTreeNode();
71      if (startNode.HasLocalParameters) startNode.ResetLocalParameters(random);
72      startNode.SetGrammar(grammar.CreateExpressionTreeGrammar());
73
74      rootNode.AddSubtree(startNode);
75
76      Create(random, startNode, maxTreeDepth - 1);
77      tree.Root = rootNode;
78      return tree;
79    }
80
81    public static void Create(IRandom random, ISymbolicExpressionTreeNode seedNode, int maxDepth) {
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);
87      // throw an exception if the seedNode happens to be a terminal, since in this case we cannot grow a tree
88      if (arity <= 0)
89        throw new ArgumentException("Cannot grow tree. Seed node shouldn't have arity zero.");
90
91      var allowedSymbols = seedNode.Grammar.AllowedSymbols.Where(s => s.InitialFrequency > 0.0).ToList();
92
93      for (var i = 0; i < arity; i++) {
94        var possibleSymbols = allowedSymbols.Where(s => seedNode.Grammar.IsAllowedChildSymbol(seedNode.Symbol, s, i)).ToList();
95        var weights = possibleSymbols.Select(s => s.InitialFrequency).ToList();
96
97#pragma warning disable 612, 618
98        var selectedSymbol = possibleSymbols.SelectRandom(weights, random);
99#pragma warning restore 612, 618
100
101        var tree = selectedSymbol.CreateTreeNode();
102        if (tree.HasLocalParameters) tree.ResetLocalParameters(random);
103        seedNode.AddSubtree(tree);
104      }
105
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
108      foreach (var subTree in seedNode.Subtrees)
109        if (subTree.Grammar.GetMaximumSubtreeCount(subTree.Symbol) > 0)
110          RecursiveCreate(random, subTree, 2, maxDepth);
111    }
112
113    private static void RecursiveCreate(IRandom random, ISymbolicExpressionTreeNode root, int currentDepth, int maxDepth) {
114      var arity = SampleArity(random, root);
115      if (arity == 0)
116        return;
117
118      var allowedSymbols = root.Grammar.AllowedSymbols.Where(s => s.InitialFrequency > 0.0).ToList();
119
120      for (var i = 0; i < arity; i++) {
121        var possibleSymbols = allowedSymbols.Where(s => root.Grammar.IsAllowedChildSymbol(root.Symbol, s, i) &&
122                                                        root.Grammar.GetMinimumExpressionDepth(s) - 1 <= maxDepth - currentDepth).ToList();
123
124        if (!possibleSymbols.Any())
125          throw new InvalidOperationException("No symbols are available for the tree.");
126
127        var weights = possibleSymbols.Select(s => s.InitialFrequency).ToList();
128#pragma warning disable 612, 618
129        var selectedSymbol = possibleSymbols.SelectRandom(weights, random);
130#pragma warning restore 612, 618
131
132        var tree = selectedSymbol.CreateTreeNode();
133        if (tree.HasLocalParameters) tree.ResetLocalParameters(random);
134        root.AddSubtree(tree);
135      }
136
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);
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  }
150}
Note: See TracBrowser for help on using the repository browser.