Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 12332 was 12012, checked in by ascheibe, 10 years ago

#2212 merged r12008, r12009, r12010 back into trunk

File size: 8.4 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("GrowTreeCreator", "An operator that creates new symbolic expression trees using the 'Grow' method")]
35  public class GrowTreeCreator : SymbolicExpressionTreeCreator,
36                                 ISymbolicExpressionTreeSizeConstraintOperator,
37                                 ISymbolicExpressionTreeGrammarBasedOperator {
38    private const string MaximumSymbolicExpressionTreeLengthParameterName = "MaximumSymbolicExpressionTreeLength";
39    private const string MaximumSymbolicExpressionTreeDepthParameterName = "MaximumSymbolicExpressionTreeDepth";
40
41    #region Parameter Properties
42    public IValueLookupParameter<IntValue> MaximumSymbolicExpressionTreeLengthParameter {
43      get { return (IValueLookupParameter<IntValue>)Parameters[MaximumSymbolicExpressionTreeLengthParameterName]; }
44    }
45
46    public IValueLookupParameter<IntValue> MaximumSymbolicExpressionTreeDepthParameter {
47      get { return (IValueLookupParameter<IntValue>)Parameters[MaximumSymbolicExpressionTreeDepthParameterName]; }
48    }
49
50    #endregion
51    #region Properties
52    public IntValue MaximumSymbolicExpressionTreeDepth {
53      get { return MaximumSymbolicExpressionTreeDepthParameter.ActualValue; }
54    }
55
56    public IntValue MaximumSymbolicExpressionTreeLength {
57      get { return MaximumSymbolicExpressionTreeLengthParameter.ActualValue; }
58    }
59    #endregion
60
61    [StorableConstructor]
62    protected GrowTreeCreator(bool deserializing) : base(deserializing) { }
63    protected GrowTreeCreator(GrowTreeCreator original, Cloner cloner) : base(original, cloner) { }
64
65    public GrowTreeCreator()
66      : base() {
67      Parameters.Add(new ValueLookupParameter<IntValue>(MaximumSymbolicExpressionTreeLengthParameterName,
68        "The maximal length (number of nodes) of the symbolic expression tree (this parameter is ignored)."));
69      Parameters.Add(new ValueLookupParameter<IntValue>(MaximumSymbolicExpressionTreeDepthParameterName,
70        "The maximal depth of the symbolic expression tree (a tree with one node has depth = 0)."));
71    }
72
73    public override IDeepCloneable Clone(Cloner cloner) {
74      return new GrowTreeCreator(this, cloner);
75    }
76
77
78    protected override ISymbolicExpressionTree Create(IRandom random) {
79      return Create(random, ClonedSymbolicExpressionTreeGrammarParameter.ActualValue,
80        MaximumSymbolicExpressionTreeLength.Value, MaximumSymbolicExpressionTreeDepth.Value);
81    }
82
83    public override ISymbolicExpressionTree CreateTree(IRandom random, ISymbolicExpressionGrammar grammar, int maxTreeLength, int maxTreeDepth) {
84      return Create(random, grammar, maxTreeLength, maxTreeDepth);
85    }
86
87    /// <summary>
88    /// Create a symbolic expression tree using the 'Grow' method.
89    /// All symbols are allowed for nodes, so the resulting trees can be of any shape and size.
90    /// </summary>
91    /// <param name="random">Random generator</param>
92    /// <param name="grammar">Available tree grammar</param>
93    /// <param name="maxTreeDepth">Maximum tree depth</param>
94    /// <param name="maxTreeLength">Maximum tree length. This parameter is not used.</param>
95    /// <returns></returns>
96    public static ISymbolicExpressionTree Create(IRandom random, ISymbolicExpressionGrammar grammar, int maxTreeLength, int maxTreeDepth) {
97      var tree = new SymbolicExpressionTree();
98      var rootNode = (SymbolicExpressionTreeTopLevelNode)grammar.ProgramRootSymbol.CreateTreeNode();
99      if (rootNode.HasLocalParameters) rootNode.ResetLocalParameters(random);
100      rootNode.SetGrammar(grammar.CreateExpressionTreeGrammar());
101
102
103      var startNode = (SymbolicExpressionTreeTopLevelNode)grammar.StartSymbol.CreateTreeNode();
104      if (startNode.HasLocalParameters) startNode.ResetLocalParameters(random);
105      startNode.SetGrammar(grammar.CreateExpressionTreeGrammar());
106
107      rootNode.AddSubtree(startNode);
108
109      Create(random, startNode, maxTreeDepth - 2);
110      tree.Root = rootNode;
111      return tree;
112    }
113
114    public static void Create(IRandom random, ISymbolicExpressionTreeNode seedNode, int maxDepth) {
115      // make sure it is possible to create a trees smaller than maxDepth
116      if (seedNode.Grammar.GetMinimumExpressionDepth(seedNode.Symbol) > maxDepth)
117        throw new ArgumentException("Cannot create trees of depth " + maxDepth + " or smaller because of grammar constraints.", "maxDepth");
118
119      var arity = SampleArity(random, seedNode);
120      // throw an exception if the seedNode happens to be a terminal, since in this case we cannot grow a tree
121      if (arity <= 0)
122        throw new ArgumentException("Cannot grow tree. Seed node shouldn't have arity zero.");
123
124      var allowedSymbols = seedNode.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 => seedNode.Grammar.IsAllowedChildSymbol(seedNode.Symbol, s, i))
131          .ToList();
132        var weights = possibleSymbols.Select(s => s.InitialFrequency).ToList();
133        var selectedSymbol = possibleSymbols.SelectRandom(weights, random);
134        var tree = selectedSymbol.CreateTreeNode();
135        if (tree.HasLocalParameters) tree.ResetLocalParameters(random);
136        seedNode.AddSubtree(tree);
137      }
138
139      // Only iterate over the non-terminal nodes (those which have arity > 0)
140      // Start from depth 2 since the first two levels are formed by the rootNode and the seedNode
141      foreach (var subTree in seedNode.Subtrees)
142        if (subTree.Grammar.GetMaximumSubtreeCount(subTree.Symbol) > 0)
143          RecursiveCreate(random, subTree, 2, maxDepth);
144    }
145
146    private static void RecursiveCreate(IRandom random, ISymbolicExpressionTreeNode root, int currentDepth, int maxDepth) {
147      var arity = SampleArity(random, root);
148      if (arity <= 0)
149        throw new ArgumentException("Cannot grow node of arity zero. Expected a function node.");
150
151      var allowedSymbols = root.Grammar.AllowedSymbols.Where(s => s.InitialFrequency > 0.0).ToList();
152
153      for (var i = 0; i < arity; i++) {
154        var possibleSymbols = allowedSymbols
155          .Where(s => root.Grammar.IsAllowedChildSymbol(root.Symbol, s, i) &&
156            root.Grammar.GetMinimumExpressionDepth(s) - 1 <= maxDepth - currentDepth)
157          .ToList();
158
159        if (!possibleSymbols.Any())
160          throw new InvalidOperationException("No symbols are available for the tree.");
161        var weights = possibleSymbols.Select(s => s.InitialFrequency).ToList();
162        var selectedSymbol = possibleSymbols.SelectRandom(weights, random);
163        var tree = selectedSymbol.CreateTreeNode();
164        if (tree.HasLocalParameters) tree.ResetLocalParameters(random);
165        root.AddSubtree(tree);
166      }
167
168      foreach (var subTree in root.Subtrees)
169        if (subTree.Grammar.GetMaximumSubtreeCount(subTree.Symbol) != 0)
170          RecursiveCreate(random, subTree, currentDepth + 1, maxDepth);
171    }
172
173    private static int SampleArity(IRandom random, ISymbolicExpressionTreeNode node) {
174      var minArity = node.Grammar.GetMinimumSubtreeCount(node.Symbol);
175      var maxArity = node.Grammar.GetMaximumSubtreeCount(node.Symbol);
176
177      return random.Next(minArity, maxArity + 1);
178    }
179  }
180}
Note: See TracBrowser for help on using the repository browser.