Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 6887 was 6887, checked in by bburlacu, 13 years ago

#1654: Implemented first versions of the Grow, Full and RampedHalfAndHalf tree creators.

File size: 8.7 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.Collections.Generic;
24using System.ComponentModel;
25using System.Linq;
26using HeuristicLab.Common;
27using HeuristicLab.Core;
28using HeuristicLab.Data;
29using HeuristicLab.Parameters;
30using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
31
32namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding {
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 {
58        return
59            (ILookupParameter<ISymbolicExpressionGrammar>)
60            Parameters[ClonedSymbolicExpressionTreeGrammarParameterName];
61      }
62    }
63
64    #endregion
65    #region Properties
66    public IntValue MaximumSymbolicExpressionTreeDepth {
67      get { return MaximumSymbolicExpressionTreeDepthParameter.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, MaximumSymbolicExpressionTreeDepth.Value);
106    }
107
108    /// <summary>
109    /// Create a symbolic expression tree using the 'Grow' method.
110    /// All symbols are allowed for nodes, so the resulting trees can be of any shape and size.
111    /// </summary>
112    /// <param name="random">Random generator</param>
113    /// <param name="grammar">Available tree grammar</param>
114    /// <param name="maxTreeDepth">Maximum tree depth</param>
115    /// <returns></returns>
116    public static ISymbolicExpressionTree Create(IRandom random, ISymbolicExpressionGrammar grammar, int maxTreeDepth) {
117      var tree = new SymbolicExpressionTree();
118      var rootNode = (SymbolicExpressionTreeTopLevelNode)grammar.ProgramRootSymbol.CreateTreeNode();
119      rootNode.SetGrammar(new SymbolicExpressionTreeGrammar(grammar));
120      if (rootNode.HasLocalParameters) rootNode.ResetLocalParameters(random);
121
122      var startNode = (SymbolicExpressionTreeTopLevelNode)grammar.StartSymbol.CreateTreeNode();
123      startNode.SetGrammar(new SymbolicExpressionTreeGrammar(grammar));
124      if (startNode.HasLocalParameters) startNode.ResetLocalParameters(random);
125
126      rootNode.AddSubtree(startNode);
127
128      Grow(random, startNode, maxTreeDepth - 2);
129      tree.Root = rootNode;
130      return tree;
131    }
132
133    public static void Grow(IRandom random, ISymbolicExpressionTreeNode seedNode, int maxDepth) {
134      // make sure it is possible to create a trees smaller than maxDepth
135      if (seedNode.Grammar.GetMinimumExpressionDepth(seedNode.Symbol) > maxDepth)
136        throw new ArgumentException("Cannot create trees of depth " + maxDepth + " or smaller because of grammar constraints.", "maxDepth");
137
138      var arity = SampleArity(random, seedNode);
139      if (arity <= 0) return; // maybe throw an exception here? But this should never happen.
140
141      var possibleSymbols = seedNode.Grammar.GetAllowedChildSymbols(seedNode.Symbol).Where(s => s.InitialFrequency > 0.0).ToList();
142
143      for (var i = 0; i != arity; ++i) {
144        var selectedSymbol = possibleSymbols.SelectRandom(random);
145        var tree = selectedSymbol.CreateTreeNode();
146        if (tree.HasLocalParameters) tree.ResetLocalParameters(random);
147        seedNode.AddSubtree(tree);
148      }
149
150      foreach (var subTree in seedNode.Subtrees) {
151        RecursiveGrow(random, subTree, 0, maxDepth);
152      }
153    }
154
155    public static void RecursiveGrow(IRandom random, ISymbolicExpressionTreeNode root, int currentDepth, int maxDepth) {
156      var arity = SampleArity(random, root);
157      if (arity <= 0) return;
158
159      var possibleSymbols = currentDepth < maxDepth ?
160        root.Grammar.GetAllowedChildSymbols(root.Symbol).Where(s => s.InitialFrequency > 0.0).ToList() :
161        root.Grammar.GetAllowedChildSymbols(root.Symbol).Where(s => s.InitialFrequency > 0.0 && root.Grammar.GetMaximumSubtreeCount(s) == 0).ToList();
162
163      for (var i = 0; i != arity; ++i) {
164        var selectedSymbol = possibleSymbols.SelectRandom(random);
165        var tree = selectedSymbol.CreateTreeNode();
166        if (tree.HasLocalParameters) tree.ResetLocalParameters(random);
167        root.AddSubtree(tree);
168      }
169
170      foreach (var subTree in root.Subtrees) {
171        RecursiveGrow(random, subTree, currentDepth + 1, maxDepth);
172      }
173    }
174
175    private static int SampleArity(IRandom random, ISymbolicExpressionTreeNode node) {
176      var minArity = node.Grammar.GetMinimumSubtreeCount(node.Symbol);
177      var maxArity = node.Grammar.GetMaximumSubtreeCount(node.Symbol);
178
179      return random.Next(minArity, maxArity + 1);
180    }
181  }
182}
Note: See TracBrowser for help on using the repository browser.