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

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

#1654: Added performance improvements for Full- and GrowTreeCreator.

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