Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Creators/FullTreeCreator.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.1 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("FullTreeCreator", "An operator that creates new symbolic expression trees using the 'Full' method")]
33  public class FullTreeCreator : 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 FullTreeCreator(bool deserializing) : base(deserializing) { }
72    protected FullTreeCreator(FullTreeCreator original, Cloner cloner) : base(original, cloner) { }
73
74    public FullTreeCreator()
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 FullTreeCreator(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 'Full' method.
104    /// Function symbols are used for all nodes situated on a level above the maximum tree depth.
105    /// Nodes on the last tree level will have Terminal symbols.
106    /// </summary>
107    /// <param name="random">Random generator</param>
108    /// <param name="grammar">Available tree grammar</param>
109    /// <param name="maxTreeDepth">Maximum tree depth</param>
110    /// <returns></returns>
111    public static ISymbolicExpressionTree Create(IRandom random, ISymbolicExpressionGrammar grammar, int maxTreeDepth) {
112      var tree = new SymbolicExpressionTree();
113      var rootNode = (SymbolicExpressionTreeTopLevelNode)grammar.ProgramRootSymbol.CreateTreeNode();
114      if (rootNode.HasLocalParameters) rootNode.ResetLocalParameters(random);
115      rootNode.SetGrammar(new SymbolicExpressionTreeGrammar(grammar));
116
117      var startNode = (SymbolicExpressionTreeTopLevelNode)grammar.StartSymbol.CreateTreeNode();
118      startNode.SetGrammar(new SymbolicExpressionTreeGrammar(grammar));
119      if (startNode.HasLocalParameters) startNode.ResetLocalParameters(random);
120
121      rootNode.AddSubtree(startNode);
122
123      Grow(random, startNode, maxTreeDepth - 2);
124      tree.Root = rootNode;
125      return tree;
126    }
127
128    public static void Grow(IRandom random, ISymbolicExpressionTreeNode seedNode, int maxDepth) {
129      // make sure it is possible to create a trees smaller than maxDepth
130      if (seedNode.Grammar.GetMinimumExpressionDepth(seedNode.Symbol) > maxDepth)
131        throw new ArgumentException("Cannot create trees of depth " + maxDepth + " or smaller because of grammar constraints.", "maxDepth");
132
133
134      int arity = seedNode.Grammar.GetMaximumSubtreeCount(seedNode.Symbol);
135      // Throw an exception if the seedNode happens to be a terminal, since in this case we cannot grow a tree.
136      if (arity <= 0)
137        throw new ArgumentException("Cannot grow tree. Seed node shouldn't have arity zero.");
138
139      for (var i = 0; i != arity; ++i) {
140        var possibleSymbols = seedNode.Grammar.GetAllowedChildSymbols(seedNode.Symbol,i).Where(s => s.InitialFrequency > 0.0 && seedNode.Grammar.GetMaximumSubtreeCount(s) > 0);
141        var selectedSymbol = possibleSymbols.SelectRandom(random);
142        var tree = selectedSymbol.CreateTreeNode();
143        if (tree.HasLocalParameters) tree.ResetLocalParameters(random);
144        seedNode.AddSubtree(tree);
145      }
146
147      // Only iterate over the non-terminal nodes (those which have arity > 0)
148      // Start from depth 2 since the first two levels are formed by the rootNode and the seedNode
149      foreach (var subTree in seedNode.Subtrees.Where(subTree => subTree.Grammar.GetMaximumSubtreeCount(subTree.Symbol) != 0))
150        RecursiveGrowFull(random, subTree, 2, maxDepth);
151    }
152
153    public static void RecursiveGrowFull(IRandom random, ISymbolicExpressionTreeNode root, int currentDepth, int maxDepth) {
154      var arity = root.Grammar.GetMaximumSubtreeCount(root.Symbol);
155      // In the 'Full' grow method, we cannot have terminals on the intermediate tree levels.
156      if (arity <= 0)
157        throw new ArgumentException("Cannot grow node of arity zero. Expected a function node.");
158
159
160      for (var i = 0; i != arity; ++i) {
161        var possibleSymbols = currentDepth < maxDepth ?
162          root.Grammar.GetAllowedChildSymbols(root.Symbol,i).Where(s => s.InitialFrequency > 0.0 && root.Grammar.GetMaximumSubtreeCount(s) > 0) :
163          root.Grammar.GetAllowedChildSymbols(root.Symbol,i).Where(s => s.InitialFrequency > 0.0 && root.Grammar.GetMaximumSubtreeCount(s) == 0);
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.Where(subTree => subTree.Grammar.GetMaximumSubtreeCount(subTree.Symbol) != 0))
171        RecursiveGrowFull(random, subTree, currentDepth + 1, maxDepth);
172    }
173  }
174}
Note: See TracBrowser for help on using the repository browser.