Free cookie consent management tool by TermsFeed Policy Generator

source: branches/GeneralizedQAP/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Creators/FullTreeCreator.cs @ 6900

Last change on this file since 6900 was 6900, checked in by abeham, 13 years ago

#1614

  • updated branch from trunk
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.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("FullTreeCreator", "An operator that creates new symbolic expression trees using the 'Full' method")]
35  public class FullTreeCreator : 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 ISymbolicExpressionGrammar SymbolicExpressionTreeGrammar {
67      get { return ClonedSymbolicExpressionTreeGrammarParameter.ActualValue; }
68    }
69
70    #endregion
71
72    [StorableConstructor]
73    protected FullTreeCreator(bool deserializing) : base(deserializing) { }
74    protected FullTreeCreator(FullTreeCreator original, Cloner cloner) : base(original, cloner) { }
75
76    public FullTreeCreator()
77      : base() {
78      Parameters.Add(new ValueLookupParameter<IntValue>(MaximumSymbolicExpressionTreeLengthParameterName, "The maximal length (number of nodes) of the symbolic expression tree."));
79      Parameters.Add(new ValueLookupParameter<IntValue>(MaximumSymbolicExpressionTreeDepthParameterName, "The maximal depth of the symbolic expression tree (a tree with one node has depth = 0)."));
80      Parameters.Add(new ValueLookupParameter<ISymbolicExpressionGrammar>(SymbolicExpressionTreeGrammarParameterName, "The tree grammar that defines the correct syntax of symbolic expression trees that should be created."));
81      Parameters.Add(new LookupParameter<ISymbolicExpressionGrammar>(ClonedSymbolicExpressionTreeGrammarParameterName, "An immutable clone of the concrete grammar that is actually used to create and manipulate trees."));
82    }
83
84    public override IDeepCloneable Clone(Cloner cloner) {
85      return new FullTreeCreator(this, cloner);
86    }
87
88    public override IOperation Apply() {
89      if (ClonedSymbolicExpressionTreeGrammarParameter.ActualValue == null) {
90        SymbolicExpressionTreeGrammarParameter.ActualValue.ReadOnly = true;
91        IScope globalScope = ExecutionContext.Scope;
92        while (globalScope.Parent != null)
93          globalScope = globalScope.Parent;
94
95        globalScope.Variables.Add(new Variable(ClonedSymbolicExpressionTreeGrammarParameterName, (ISymbolicExpressionGrammar)SymbolicExpressionTreeGrammarParameter.ActualValue.Clone()));
96      }
97      return base.Apply();
98    }
99
100    protected override ISymbolicExpressionTree Create(IRandom random) {
101      return Create(random, SymbolicExpressionTreeGrammar, MaximumSymbolicExpressionTreeDepth.Value);
102    }
103
104    /// <summary>
105    /// Create a symbolic expression tree using the 'Full' method.
106    /// Function symbols are used for all nodes situated on a level above the maximum tree depth.
107    /// Nodes on the last tree level will have Terminal symbols.
108    /// </summary>
109    /// <param name="random">Random generator</param>
110    /// <param name="grammar">Available tree grammar</param>
111    /// <param name="maxTreeDepth">Maximum tree depth</param>
112    /// <returns></returns>
113    public static ISymbolicExpressionTree Create(IRandom random, ISymbolicExpressionGrammar grammar, int maxTreeDepth) {
114      var tree = new SymbolicExpressionTree();
115      var rootNode = (SymbolicExpressionTreeTopLevelNode)grammar.ProgramRootSymbol.CreateTreeNode();
116      if (rootNode.HasLocalParameters) rootNode.ResetLocalParameters(random);
117      rootNode.SetGrammar(new SymbolicExpressionTreeGrammar(grammar));
118
119      var startNode = (SymbolicExpressionTreeTopLevelNode)grammar.StartSymbol.CreateTreeNode();
120      startNode.SetGrammar(new SymbolicExpressionTreeGrammar(grammar));
121      if (startNode.HasLocalParameters) startNode.ResetLocalParameters(random);
122
123      rootNode.AddSubtree(startNode);
124
125      Grow(random, startNode, maxTreeDepth - 2);
126      tree.Root = rootNode;
127      return tree;
128    }
129
130    public static void Grow(IRandom random, ISymbolicExpressionTreeNode seedNode, int maxDepth) {
131      // make sure it is possible to create a trees smaller than maxDepth
132      if (seedNode.Grammar.GetMinimumExpressionDepth(seedNode.Symbol) > maxDepth)
133        throw new ArgumentException("Cannot create trees of depth " + maxDepth + " or smaller because of grammar constraints.", "maxDepth");
134
135      var possibleSymbols = seedNode.Grammar.GetAllowedChildSymbols(seedNode.Symbol).Where(s => s.InitialFrequency > 0.0 && seedNode.Grammar.GetMaximumSubtreeCount(s) > 0).ToList();
136
137      int arity = seedNode.Grammar.GetMaximumSubtreeCount(seedNode.Symbol);
138      // Throw an exception if the seedNode happens to be a terminal, since in this case we cannot grow a tree.
139      if (arity <= 0)
140        throw new ArgumentException("Cannot grow tree. Seed node shouldn't have arity zero.");
141
142      for (var i = 0; i != arity; ++i) {
143        var selectedSymbol = possibleSymbols.SelectRandom(random);
144        var tree = selectedSymbol.CreateTreeNode();
145        if (tree.HasLocalParameters) tree.ResetLocalParameters(random);
146        seedNode.AddSubtree(tree);
147      }
148
149      // Only iterate over the non-terminal nodes (those which have arity > 0)
150      // Start from depth 2 since the first two levels are formed by the rootNode and the seedNode
151      foreach (var subTree in seedNode.Subtrees.Where(subTree => subTree.Grammar.GetMaximumSubtreeCount(subTree.Symbol) != 0))
152        RecursiveGrowFull(random, subTree, 2, maxDepth);
153    }
154
155    public static void RecursiveGrowFull(IRandom random, ISymbolicExpressionTreeNode root, int currentDepth, int maxDepth) {
156      var arity = root.Grammar.GetMaximumSubtreeCount(root.Symbol);
157      // In the 'Full' grow method, we cannot have terminals on the intermediate tree levels.
158      if (arity <= 0)
159        throw new ArgumentException("Cannot grow node of arity zero. Expected a function node.");
160
161      var possibleSymbols = currentDepth < maxDepth ?
162        root.Grammar.GetAllowedChildSymbols(root.Symbol).Where(s => s.InitialFrequency > 0.0 && root.Grammar.GetMaximumSubtreeCount(s) > 0).ToList() :
163        root.Grammar.GetAllowedChildSymbols(root.Symbol).Where(s => s.InitialFrequency > 0.0 && root.Grammar.GetMaximumSubtreeCount(s) == 0).ToList();
164
165      for (var i = 0; i != arity; ++i) {
166        var selectedSymbol = possibleSymbols.SelectRandom(random);
167        var tree = selectedSymbol.CreateTreeNode();
168        if (tree.HasLocalParameters) tree.ResetLocalParameters(random);
169        root.AddSubtree(tree);
170      }
171
172      foreach (var subTree in root.Subtrees.Where(subTree => subTree.Grammar.GetMaximumSubtreeCount(subTree.Symbol) != 0))
173        RecursiveGrowFull(random, subTree, currentDepth + 1, maxDepth);
174    }
175  }
176}
Note: See TracBrowser for help on using the repository browser.