Free cookie consent management tool by TermsFeed Policy Generator

source: branches/SymbolicExpressionTreeEncoding/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Creators/FullTreeCreator.cs @ 12313

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

#2320: Simplified TreeCreators.

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