Free cookie consent management tool by TermsFeed Policy Generator

source: stable/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Creators/GrowTreeCreator.cs @ 9672

Last change on this file since 9672 was 9456, checked in by swagner, 12 years ago

Updated copyright year and added some missing license headers (#1889)

File size: 10.3 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2013 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 ClonedSymbolicExpressionTreeGrammar {
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,
83        "The maximal length (number of nodes) of the symbolic expression tree (this parameter is ignored)."));
84      Parameters.Add(new ValueLookupParameter<IntValue>(MaximumSymbolicExpressionTreeDepthParameterName,
85        "The maximal depth of the symbolic expression tree (a tree with one node has depth = 0)."));
86      Parameters.Add(new ValueLookupParameter<ISymbolicExpressionGrammar>(SymbolicExpressionTreeGrammarParameterName,
87        "The tree grammar that defines the correct syntax of symbolic expression trees that should be created."));
88      Parameters.Add(new LookupParameter<ISymbolicExpressionGrammar>(ClonedSymbolicExpressionTreeGrammarParameterName,
89        "An immutable clone of the concrete grammar that is actually used to create and manipulate trees."));
90    }
91
92    public override IDeepCloneable Clone(Cloner cloner) {
93      return new GrowTreeCreator(this, cloner);
94    }
95
96    public override IOperation Apply() {
97      if (ClonedSymbolicExpressionTreeGrammarParameter.ActualValue == null) {
98        SymbolicExpressionTreeGrammarParameter.ActualValue.ReadOnly = true;
99        IScope globalScope = ExecutionContext.Scope;
100        while (globalScope.Parent != null)
101          globalScope = globalScope.Parent;
102
103        globalScope.Variables.Add(new Variable(ClonedSymbolicExpressionTreeGrammarParameterName,
104          (ISymbolicExpressionGrammar)SymbolicExpressionTreeGrammarParameter.ActualValue.Clone()));
105      }
106      return base.Apply();
107    }
108
109    protected override ISymbolicExpressionTree Create(IRandom random) {
110      return Create(random, ClonedSymbolicExpressionTreeGrammar,
111        MaximumSymbolicExpressionTreeLength.Value, MaximumSymbolicExpressionTreeDepth.Value);
112    }
113
114    public override ISymbolicExpressionTree CreateTree(IRandom random, ISymbolicExpressionGrammar grammar, int maxTreeLength, int maxTreeDepth) {
115      return Create(random, grammar, maxTreeLength, maxTreeDepth);
116    }
117
118    /// <summary>
119    /// Create a symbolic expression tree using the 'Grow' method.
120    /// All symbols are allowed for nodes, so the resulting trees can be of any shape and size.
121    /// </summary>
122    /// <param name="random">Random generator</param>
123    /// <param name="grammar">Available tree grammar</param>
124    /// <param name="maxTreeDepth">Maximum tree depth</param>
125    /// <param name="maxTreeLength">Maximum tree length. This parameter is not used.</param>
126    /// <returns></returns>
127    public static ISymbolicExpressionTree Create(IRandom random, ISymbolicExpressionGrammar grammar, int maxTreeLength, int maxTreeDepth) {
128      var tree = new SymbolicExpressionTree();
129      var rootNode = (SymbolicExpressionTreeTopLevelNode)grammar.ProgramRootSymbol.CreateTreeNode();
130      rootNode.SetGrammar(new SymbolicExpressionTreeGrammar(grammar));
131      if (rootNode.HasLocalParameters) rootNode.ResetLocalParameters(random);
132
133      var startNode = (SymbolicExpressionTreeTopLevelNode)grammar.StartSymbol.CreateTreeNode();
134      if (startNode.HasLocalParameters) startNode.ResetLocalParameters(random);
135      startNode.SetGrammar(new SymbolicExpressionTreeGrammar(grammar));
136
137      rootNode.AddSubtree(startNode);
138
139      Create(random, startNode, maxTreeDepth - 2);
140      tree.Root = rootNode;
141      return tree;
142    }
143
144    public static void Create(IRandom random, ISymbolicExpressionTreeNode seedNode, int maxDepth) {
145      // make sure it is possible to create a trees smaller than maxDepth
146      if (seedNode.Grammar.GetMinimumExpressionDepth(seedNode.Symbol) > maxDepth)
147        throw new ArgumentException("Cannot create trees of depth " + maxDepth + " or smaller because of grammar constraints.", "maxDepth");
148
149      var arity = SampleArity(random, seedNode);
150      // throw an exception if the seedNode happens to be a terminal, since in this case we cannot grow a tree
151      if (arity <= 0)
152        throw new ArgumentException("Cannot grow tree. Seed node shouldn't have arity zero.");
153
154      var allowedSymbols = seedNode.Grammar.AllowedSymbols
155        .Where(s => s.InitialFrequency > 0.0)
156        .ToList();
157
158      for (var i = 0; i < arity; i++) {
159        var possibleSymbols = allowedSymbols
160          .Where(s => seedNode.Grammar.IsAllowedChildSymbol(seedNode.Symbol, s, i))
161          .ToList();
162        var weights = possibleSymbols.Select(s => s.InitialFrequency).ToList();
163        var selectedSymbol = possibleSymbols.SelectRandom(weights, random);
164        var tree = selectedSymbol.CreateTreeNode();
165        if (tree.HasLocalParameters) tree.ResetLocalParameters(random);
166        seedNode.AddSubtree(tree);
167      }
168
169      // Only iterate over the non-terminal nodes (those which have arity > 0)
170      // Start from depth 2 since the first two levels are formed by the rootNode and the seedNode
171      foreach (var subTree in seedNode.Subtrees)
172        if (subTree.Grammar.GetMaximumSubtreeCount(subTree.Symbol) > 0)
173          RecursiveCreate(random, subTree, 2, maxDepth);
174    }
175
176    private static void RecursiveCreate(IRandom random, ISymbolicExpressionTreeNode root, int currentDepth, int maxDepth) {
177      var arity = SampleArity(random, root);
178      if (arity <= 0)
179        throw new ArgumentException("Cannot grow node of arity zero. Expected a function node.");
180
181      var allowedSymbols = root.Grammar.AllowedSymbols.Where(s => s.InitialFrequency > 0.0).ToList();
182
183      for (var i = 0; i < arity; i++) {
184        var possibleSymbols = allowedSymbols
185          .Where(s => root.Grammar.IsAllowedChildSymbol(root.Symbol, s, i) &&
186            root.Grammar.GetMinimumExpressionDepth(s) - 1 <= maxDepth - currentDepth)
187          .ToList();
188
189        if (!possibleSymbols.Any())
190          throw new InvalidOperationException("No symbols are available for the tree.");
191        var weights = possibleSymbols.Select(s => s.InitialFrequency).ToList();
192        var selectedSymbol = possibleSymbols.SelectRandom(weights, random);
193        var tree = selectedSymbol.CreateTreeNode();
194        if (tree.HasLocalParameters) tree.ResetLocalParameters(random);
195        root.AddSubtree(tree);
196      }
197
198      foreach (var subTree in root.Subtrees)
199        if (subTree.Grammar.GetMaximumSubtreeCount(subTree.Symbol) != 0)
200          RecursiveCreate(random, subTree, currentDepth + 1, maxDepth);
201    }
202
203    private static int SampleArity(IRandom random, ISymbolicExpressionTreeNode node) {
204      var minArity = node.Grammar.GetMinimumSubtreeCount(node.Symbol);
205      var maxArity = node.Grammar.GetMaximumSubtreeCount(node.Symbol);
206
207      return random.Next(minArity, maxArity + 1);
208    }
209  }
210}
Note: See TracBrowser for help on using the repository browser.