Free cookie consent management tool by TermsFeed Policy Generator

source: branches/3140_NumberSymbol/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Creators/FullTreeCreator.cs @ 18091

Last change on this file since 18091 was 18064, checked in by mkommend, 3 years ago

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

File size: 7.1 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("1A36CB91-B3AD-4D3D-B44F-2CA5508C55ED")]
32  [Item("FullTreeCreator", "An operator that creates new symbolic expression trees using the 'Full' method")]
33  public class FullTreeCreator : SymbolicExpressionTreeCreator,
34                                 ISymbolicExpressionTreeSizeConstraintOperator,
35                                 ISymbolicExpressionTreeGrammarBasedOperator {
36
37    [StorableConstructor]
38    protected FullTreeCreator(StorableConstructorFlag _) : base(_) { }
39    protected FullTreeCreator(FullTreeCreator original, Cloner cloner) : base(original, cloner) { }
40
41    public FullTreeCreator() : base() { }
42
43    public override IDeepCloneable Clone(Cloner cloner) {
44      return new FullTreeCreator(this, cloner);
45    }
46
47
48    public override ISymbolicExpressionTree CreateTree(IRandom random, ISymbolicExpressionGrammar grammar, int maxTreeLength, int maxTreeDepth) {
49      return Create(random, grammar, maxTreeLength, maxTreeDepth);
50    }
51
52    /// <summary>
53    /// Create a symbolic expression tree using the 'Full' method.
54    /// Function symbols are used for all nodes situated on a level above the maximum tree depth.
55    /// Nodes on the last tree level will have Terminal symbols.
56    /// </summary>
57    /// <param name="random">Random generator</param>
58    /// <param name="grammar">Available tree grammar</param>
59    /// <param name="maxTreeDepth">Maximum tree depth</param>
60    /// <param name="maxTreeLength">Maximum tree length. This parameter is not used.</param>
61    /// <returns></returns>
62    public static ISymbolicExpressionTree Create(IRandom random, ISymbolicExpressionGrammar grammar, int maxTreeLength, int maxTreeDepth) {
63      var tree = new SymbolicExpressionTree();
64      var rootNode = (SymbolicExpressionTreeTopLevelNode)grammar.ProgramRootSymbol.CreateTreeNode();
65      if (rootNode.HasLocalParameters) rootNode.ResetLocalParameters(random);
66      rootNode.SetGrammar(grammar.CreateExpressionTreeGrammar());
67
68      var startNode = (SymbolicExpressionTreeTopLevelNode)grammar.StartSymbol.CreateTreeNode();
69      if (startNode.HasLocalParameters) startNode.ResetLocalParameters(random);
70      startNode.SetGrammar(grammar.CreateExpressionTreeGrammar());
71
72      rootNode.AddSubtree(startNode);
73
74      Create(random, startNode, maxTreeDepth-1);
75      tree.Root = rootNode;
76      return tree;
77    }
78
79    public static void Create(IRandom random, ISymbolicExpressionTreeNode seedNode, int maxDepth) {
80      // make sure it is possible to create a trees smaller than maxDepth
81      if (seedNode.Grammar.GetMinimumExpressionDepth(seedNode.Symbol) > maxDepth)
82        throw new ArgumentException("Cannot create trees of depth " + maxDepth + " or smaller because of grammar constraints.", "maxDepth");
83
84
85      int arity = seedNode.Grammar.GetMaximumSubtreeCount(seedNode.Symbol);
86      // Throw an exception if the seedNode happens to be a terminal, since in this case we cannot grow a tree.
87      if (arity <= 0)
88        throw new ArgumentException("Cannot grow tree. Seed node shouldn't have arity zero.");
89
90      var allowedSymbols = seedNode.Grammar.AllowedSymbols
91        .Where(s => s.InitialFrequency > 0.0 && seedNode.Grammar.GetMaximumSubtreeCount(s) > 0)
92        .ToList();
93
94      for (var i = 0; i < arity; i++) {
95        var possibleSymbols = allowedSymbols
96          .Where(s => seedNode.Grammar.IsAllowedChildSymbol(seedNode.Symbol, s, i)
97                   && seedNode.Grammar.GetMinimumExpressionDepth(s) <= maxDepth
98                   && seedNode.Grammar.GetMaximumExpressionDepth(s) >= maxDepth)
99          .ToList();
100        var weights = possibleSymbols.Select(s => s.InitialFrequency).ToList();
101
102#pragma warning disable 612, 618
103        var selectedSymbol = possibleSymbols.SelectRandom(weights, random);
104#pragma warning restore 612, 618
105
106        var tree = selectedSymbol.CreateTreeNode();
107        if (tree.HasLocalParameters) tree.ResetLocalParameters(random);
108        seedNode.AddSubtree(tree);
109      }
110
111      // Only iterate over the non-terminal nodes (those which have arity > 0)
112      // Start from depth 2 since the first two levels are formed by the rootNode and the seedNode
113      foreach (var subTree in seedNode.Subtrees)
114        if (subTree.Grammar.GetMaximumSubtreeCount(subTree.Symbol) > 0)
115          RecursiveCreate(random, subTree, 2, maxDepth);
116    }
117
118    private static void RecursiveCreate(IRandom random, ISymbolicExpressionTreeNode root, int currentDepth, int maxDepth) {
119      var arity = root.Grammar.GetMaximumSubtreeCount(root.Symbol);
120      // In the 'Full' grow method, we cannot have terminals on the intermediate tree levels.
121      if (arity <= 0)
122        throw new ArgumentException("Cannot grow node of arity zero. Expected a function node.");
123
124      var allowedSymbols = root.Grammar.AllowedSymbols
125        .Where(s => s.InitialFrequency > 0.0)
126        .ToList();
127
128      for (var i = 0; i < arity; i++) {
129        var possibleSymbols = allowedSymbols
130          .Where(s => root.Grammar.IsAllowedChildSymbol(root.Symbol, s, i) &&
131            root.Grammar.GetMinimumExpressionDepth(s) - 1 <= maxDepth - currentDepth &&
132            root.Grammar.GetMaximumExpressionDepth(s) > maxDepth - currentDepth)
133          .ToList();
134        if (!possibleSymbols.Any())
135          throw new InvalidOperationException("No symbols are available for the tree.");
136        var weights = possibleSymbols.Select(s => s.InitialFrequency).ToList();
137
138#pragma warning disable 612, 618
139        var selectedSymbol = possibleSymbols.SelectRandom(weights, random);
140#pragma warning restore 612, 618
141
142        var tree = selectedSymbol.CreateTreeNode();
143        if (tree.HasLocalParameters) tree.ResetLocalParameters(random);
144        root.AddSubtree(tree);
145      }
146
147      //additional levels should only be added if the maximum depth is not reached yet
148      if (maxDepth > currentDepth) {
149        foreach (var subTree in root.Subtrees)
150          if (subTree.Grammar.GetMaximumSubtreeCount(subTree.Symbol) > 0)
151            RecursiveCreate(random, subTree, currentDepth + 1, maxDepth);
152      }
153    }
154  }
155}
Note: See TracBrowser for help on using the repository browser.