Free cookie consent management tool by TermsFeed Policy Generator

source: stable/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Creators/FullTreeCreator.cs @ 12009

Last change on this file since 12009 was 12009, checked in by ascheibe, 10 years ago

#2212 updated copyright year

File size: 8.5 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2015 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("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
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    #endregion
50    #region Properties
51    public IntValue MaximumSymbolicExpressionTreeDepth {
52      get { return MaximumSymbolicExpressionTreeDepthParameter.ActualValue; }
53    }
54
55    public IntValue MaximumSymbolicExpressionTreeLength {
56      get { return MaximumSymbolicExpressionTreeLengthParameter.ActualValue; }
57    }
58
59    #endregion
60
61    [StorableConstructor]
62    protected FullTreeCreator(bool deserializing) : base(deserializing) { }
63    protected FullTreeCreator(FullTreeCreator original, Cloner cloner) : base(original, cloner) { }
64
65    public FullTreeCreator()
66      : base() {
67      Parameters.Add(new ValueLookupParameter<IntValue>(MaximumSymbolicExpressionTreeLengthParameterName,
68        "The maximal length (number of nodes) of the symbolic expression tree (this parameter is ignored)."));
69      Parameters.Add(new ValueLookupParameter<IntValue>(MaximumSymbolicExpressionTreeDepthParameterName,
70        "The maximal depth of the symbolic expression tree (a tree with one node has depth = 0)."));
71    }
72
73    public override IDeepCloneable Clone(Cloner cloner) {
74      return new FullTreeCreator(this, cloner);
75    }
76
77
78    protected override ISymbolicExpressionTree Create(IRandom random) {
79      return Create(random, ClonedSymbolicExpressionTreeGrammarParameter.ActualValue, MaximumSymbolicExpressionTreeLength.Value, MaximumSymbolicExpressionTreeDepth.Value);
80    }
81
82    public override ISymbolicExpressionTree CreateTree(IRandom random, ISymbolicExpressionGrammar grammar, int maxTreeLength, int maxTreeDepth) {
83      return Create(random, grammar, maxTreeLength, maxTreeDepth);
84    }
85
86    /// <summary>
87    /// Create a symbolic expression tree using the 'Full' method.
88    /// Function symbols are used for all nodes situated on a level above the maximum tree depth.
89    /// Nodes on the last tree level will have Terminal symbols.
90    /// </summary>
91    /// <param name="random">Random generator</param>
92    /// <param name="grammar">Available tree grammar</param>
93    /// <param name="maxTreeDepth">Maximum tree depth</param>
94    /// <param name="maxTreeLength">Maximum tree length. This parameter is not used.</param>
95    /// <returns></returns>
96    public static ISymbolicExpressionTree Create(IRandom random, ISymbolicExpressionGrammar grammar, int maxTreeLength, int maxTreeDepth) {
97      var tree = new SymbolicExpressionTree();
98      var rootNode = (SymbolicExpressionTreeTopLevelNode)grammar.ProgramRootSymbol.CreateTreeNode();
99      if (rootNode.HasLocalParameters) rootNode.ResetLocalParameters(random);
100      rootNode.SetGrammar(grammar.CreateExpressionTreeGrammar());
101
102      var startNode = (SymbolicExpressionTreeTopLevelNode)grammar.StartSymbol.CreateTreeNode();
103      if (startNode.HasLocalParameters) startNode.ResetLocalParameters(random);
104      startNode.SetGrammar(grammar.CreateExpressionTreeGrammar());
105
106      rootNode.AddSubtree(startNode);
107
108      Create(random, startNode, maxTreeDepth - 2);
109      tree.Root = rootNode;
110      return tree;
111    }
112
113    public static void Create(IRandom random, ISymbolicExpressionTreeNode seedNode, int maxDepth) {
114      // make sure it is possible to create a trees smaller than maxDepth
115      if (seedNode.Grammar.GetMinimumExpressionDepth(seedNode.Symbol) > maxDepth)
116        throw new ArgumentException("Cannot create trees of depth " + maxDepth + " or smaller because of grammar constraints.", "maxDepth");
117
118
119      int arity = seedNode.Grammar.GetMaximumSubtreeCount(seedNode.Symbol);
120      // Throw an exception if the seedNode happens to be a terminal, since in this case we cannot grow a tree.
121      if (arity <= 0)
122        throw new ArgumentException("Cannot grow tree. Seed node shouldn't have arity zero.");
123
124      var allowedSymbols = seedNode.Grammar.AllowedSymbols
125        .Where(s => s.InitialFrequency > 0.0 && seedNode.Grammar.GetMaximumSubtreeCount(s) > 0)
126        .ToList();
127
128      for (var i = 0; i < arity; i++) {
129        var possibleSymbols = allowedSymbols
130          .Where(s => seedNode.Grammar.IsAllowedChildSymbol(seedNode.Symbol, s, i))
131          .ToList();
132        var weights = possibleSymbols.Select(s => s.InitialFrequency).ToList();
133        var selectedSymbol = possibleSymbols.SelectRandom(weights, random);
134        var tree = selectedSymbol.CreateTreeNode();
135        if (tree.HasLocalParameters) tree.ResetLocalParameters(random);
136        seedNode.AddSubtree(tree);
137      }
138
139      // Only iterate over the non-terminal nodes (those which have arity > 0)
140      // Start from depth 2 since the first two levels are formed by the rootNode and the seedNode
141      foreach (var subTree in seedNode.Subtrees)
142        if (subTree.Grammar.GetMaximumSubtreeCount(subTree.Symbol) > 0)
143          RecursiveCreate(random, subTree, 2, maxDepth);
144    }
145
146    private static void RecursiveCreate(IRandom random, ISymbolicExpressionTreeNode root, int currentDepth, int maxDepth) {
147      var arity = root.Grammar.GetMaximumSubtreeCount(root.Symbol);
148      // In the 'Full' grow method, we cannot have terminals on the intermediate tree levels.
149      if (arity <= 0)
150        throw new ArgumentException("Cannot grow node of arity zero. Expected a function node.");
151
152      var allowedSymbols = root.Grammar.AllowedSymbols
153        .Where(s => s.InitialFrequency > 0.0)
154        .ToList();
155
156      for (var i = 0; i < arity; i++) {
157        var possibleSymbols = allowedSymbols
158          .Where(s => root.Grammar.IsAllowedChildSymbol(root.Symbol, s, i) &&
159            root.Grammar.GetMinimumExpressionDepth(s) - 1 <= maxDepth - currentDepth &&
160            root.Grammar.GetMaximumExpressionDepth(s) > maxDepth - currentDepth)
161          .ToList();
162        if (!possibleSymbols.Any())
163          throw new InvalidOperationException("No symbols are available for the tree.");
164        var weights = possibleSymbols.Select(s => s.InitialFrequency).ToList();
165        var selectedSymbol = possibleSymbols.SelectRandom(weights, random);
166        var tree = selectedSymbol.CreateTreeNode();
167        if (tree.HasLocalParameters) tree.ResetLocalParameters(random);
168        root.AddSubtree(tree);
169      }
170
171      foreach (var subTree in root.Subtrees)
172        if (subTree.Grammar.GetMaximumSubtreeCount(subTree.Symbol) > 0)
173          RecursiveCreate(random, subTree, currentDepth + 1, maxDepth);
174    }
175  }
176}
Note: See TracBrowser for help on using the repository browser.