Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 6944 was 6944, checked in by mkommend, 12 years ago

#1654: Corrected bug in Full- and GrowTreeCreator.

File size: 9.2 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2011 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;
29
30namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding {
31  [StorableClass]
32  [Item("GrowTreeCreator", "An operator that creates new symbolic expression trees using the 'Grow' method")]
33  public class GrowTreeCreator : SymbolicExpressionTreeCreator,
34                                 ISymbolicExpressionTreeSizeConstraintOperator,
35                                 ISymbolicExpressionTreeGrammarBasedOperator {
36    private const string MaximumSymbolicExpressionTreeLengthParameterName = "MaximumSymbolicExpressionTreeLength";
37    private const string MaximumSymbolicExpressionTreeDepthParameterName = "MaximumSymbolicExpressionTreeDepth";
38    private const string SymbolicExpressionTreeGrammarParameterName = "SymbolicExpressionTreeGrammar";
39    private const string ClonedSymbolicExpressionTreeGrammarParameterName = "ClonedSymbolicExpressionTreeGrammar";
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    public IValueLookupParameter<ISymbolicExpressionGrammar> SymbolicExpressionTreeGrammarParameter {
51      get { return (IValueLookupParameter<ISymbolicExpressionGrammar>)Parameters[SymbolicExpressionTreeGrammarParameterName]; }
52    }
53
54    public ILookupParameter<ISymbolicExpressionGrammar> ClonedSymbolicExpressionTreeGrammarParameter {
55      get { return (ILookupParameter<ISymbolicExpressionGrammar>)Parameters[ClonedSymbolicExpressionTreeGrammarParameterName]; }
56    }
57
58    #endregion
59    #region Properties
60    public IntValue MaximumSymbolicExpressionTreeDepth {
61      get { return MaximumSymbolicExpressionTreeDepthParameter.ActualValue; }
62    }
63
64    public ISymbolicExpressionGrammar SymbolicExpressionTreeGrammar {
65      get { return ClonedSymbolicExpressionTreeGrammarParameter.ActualValue; }
66    }
67
68    #endregion
69
70    [StorableConstructor]
71    protected GrowTreeCreator(bool deserializing) : base(deserializing) { }
72    protected GrowTreeCreator(GrowTreeCreator original, Cloner cloner) : base(original, cloner) { }
73
74    public GrowTreeCreator()
75      : base() {
76      Parameters.Add(new ValueLookupParameter<IntValue>(MaximumSymbolicExpressionTreeLengthParameterName, "The maximal length (number of nodes) of the symbolic expression tree."));
77      Parameters.Add(new ValueLookupParameter<IntValue>(MaximumSymbolicExpressionTreeDepthParameterName, "The maximal depth of the symbolic expression tree (a tree with one node has depth = 0)."));
78      Parameters.Add(new ValueLookupParameter<ISymbolicExpressionGrammar>(SymbolicExpressionTreeGrammarParameterName, "The tree grammar that defines the correct syntax of symbolic expression trees that should be created."));
79      Parameters.Add(new LookupParameter<ISymbolicExpressionGrammar>(ClonedSymbolicExpressionTreeGrammarParameterName, "An immutable clone of the concrete grammar that is actually used to create and manipulate trees."));
80    }
81
82    public override IDeepCloneable Clone(Cloner cloner) {
83      return new GrowTreeCreator(this, cloner);
84    }
85
86    public override IOperation Apply() {
87      if (ClonedSymbolicExpressionTreeGrammarParameter.ActualValue == null) {
88        SymbolicExpressionTreeGrammarParameter.ActualValue.ReadOnly = true;
89        IScope globalScope = ExecutionContext.Scope;
90        while (globalScope.Parent != null)
91          globalScope = globalScope.Parent;
92
93        globalScope.Variables.Add(new Variable(ClonedSymbolicExpressionTreeGrammarParameterName, (ISymbolicExpressionGrammar)SymbolicExpressionTreeGrammarParameter.ActualValue.Clone()));
94      }
95      return base.Apply();
96    }
97
98    protected override ISymbolicExpressionTree Create(IRandom random) {
99      return Create(random, SymbolicExpressionTreeGrammar, MaximumSymbolicExpressionTreeDepth.Value);
100    }
101
102    /// <summary>
103    /// Create a symbolic expression tree using the 'Grow' method.
104    /// All symbols are allowed for nodes, so the resulting trees can be of any shape and size.
105    /// </summary>
106    /// <param name="random">Random generator</param>
107    /// <param name="grammar">Available tree grammar</param>
108    /// <param name="maxTreeDepth">Maximum tree depth</param>
109    /// <returns></returns>
110    public static ISymbolicExpressionTree Create(IRandom random, ISymbolicExpressionGrammar grammar, int maxTreeDepth) {
111      var tree = new SymbolicExpressionTree();
112      var rootNode = (SymbolicExpressionTreeTopLevelNode)grammar.ProgramRootSymbol.CreateTreeNode();
113      rootNode.SetGrammar(new SymbolicExpressionTreeGrammar(grammar));
114      if (rootNode.HasLocalParameters) rootNode.ResetLocalParameters(random);
115
116      var startNode = (SymbolicExpressionTreeTopLevelNode)grammar.StartSymbol.CreateTreeNode();
117      startNode.SetGrammar(new SymbolicExpressionTreeGrammar(grammar));
118      if (startNode.HasLocalParameters) startNode.ResetLocalParameters(random);
119
120      rootNode.AddSubtree(startNode);
121
122      Grow(random, startNode, maxTreeDepth - 2);
123      tree.Root = rootNode;
124      return tree;
125    }
126
127    public static void Grow(IRandom random, ISymbolicExpressionTreeNode seedNode, int maxDepth) {
128      // make sure it is possible to create a trees smaller than maxDepth
129      if (seedNode.Grammar.GetMinimumExpressionDepth(seedNode.Symbol) > maxDepth)
130        throw new ArgumentException("Cannot create trees of depth " + maxDepth + " or smaller because of grammar constraints.", "maxDepth");
131
132      var arity = SampleArity(random, seedNode);
133      // throw an exception if the seedNode happens to be a terminal, since in this case we cannot grow a tree
134      if (arity <= 0)
135        throw new ArgumentException("Cannot grow tree. Seed node shouldn't have arity zero.");
136
137
138      for (var i = 0; i != arity; ++i) {
139        var possibleSymbols = seedNode.Grammar.GetAllowedChildSymbols(seedNode.Symbol, i).Where(s => s.InitialFrequency > 0.0);
140        var selectedSymbol = possibleSymbols.SelectRandom(random);
141        var tree = selectedSymbol.CreateTreeNode();
142        if (tree.HasLocalParameters) tree.ResetLocalParameters(random);
143        seedNode.AddSubtree(tree);
144      }
145
146      // Only iterate over the non-terminal nodes (those which have arity > 0)
147      // Start from depth 2 since the first two levels are formed by the rootNode and the seedNode
148      foreach (var subTree in seedNode.Subtrees.Where(subTree => subTree.Grammar.GetMaximumSubtreeCount(subTree.Symbol) != 0))
149        RecursiveGrow(random, subTree, 2, maxDepth);
150    }
151
152    public static void RecursiveGrow(IRandom random, ISymbolicExpressionTreeNode root, int currentDepth, int maxDepth) {
153      var arity = SampleArity(random, root);
154      if (arity <= 0)
155        throw new ArgumentException("Cannot grow node of arity zero. Expected a function node.");
156
157
158      for (var i = 0; i != arity; ++i) {
159        var possibleSymbols = currentDepth < maxDepth
160                                ? root.Grammar.GetAllowedChildSymbols(root.Symbol,i).Where(s => s.InitialFrequency > 0.0)
161                                : root.Grammar.GetAllowedChildSymbols(root.Symbol,i).Where(
162                                  s => s.InitialFrequency > 0.0 && root.Grammar.GetMaximumSubtreeCount(s) == 0);
163        var selectedSymbol = possibleSymbols.SelectRandom(random);
164        var tree = selectedSymbol.CreateTreeNode();
165        if (tree.HasLocalParameters) tree.ResetLocalParameters(random);
166        root.AddSubtree(tree);
167      }
168
169      foreach (var subTree in root.Subtrees.Where(subTree => subTree.Grammar.GetMaximumSubtreeCount(subTree.Symbol) != 0))
170        RecursiveGrow(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.