Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Creators/FullTreeCreator.cs @ 12337

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

#2212 merged r12008, r12009, r12010 back into trunk

File size: 8.5 KB
RevLine 
[6887]1#region License Information
2/* HeuristicLab
[12012]3 * Copyright (C) 2002-2015 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
[6887]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;
[7012]29using HeuristicLab.PluginInfrastructure;
[6887]30
31namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding {
[7012]32  [NonDiscoverableType]
[6887]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    }
[7076]54
[7012]55    public IntValue MaximumSymbolicExpressionTreeLength {
56      get { return MaximumSymbolicExpressionTreeLengthParameter.ActualValue; }
57    }
[6887]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() {
[7236]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)."));
[6887]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) {
[11496]79      return Create(random, ClonedSymbolicExpressionTreeGrammarParameter.ActualValue, MaximumSymbolicExpressionTreeLength.Value, MaximumSymbolicExpressionTreeDepth.Value);
[6887]80    }
81
[7012]82    public override ISymbolicExpressionTree CreateTree(IRandom random, ISymbolicExpressionGrammar grammar, int maxTreeLength, int maxTreeDepth) {
[7076]83      return Create(random, grammar, maxTreeLength, maxTreeDepth);
[7012]84    }
85
[6887]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>
[7012]94    /// <param name="maxTreeLength">Maximum tree length. This parameter is not used.</param>
[6887]95    /// <returns></returns>
[7012]96    public static ISymbolicExpressionTree Create(IRandom random, ISymbolicExpressionGrammar grammar, int maxTreeLength, int maxTreeDepth) {
[6887]97      var tree = new SymbolicExpressionTree();
98      var rootNode = (SymbolicExpressionTreeTopLevelNode)grammar.ProgramRootSymbol.CreateTreeNode();
99      if (rootNode.HasLocalParameters) rootNode.ResetLocalParameters(random);
[11496]100      rootNode.SetGrammar(grammar.CreateExpressionTreeGrammar());
[6887]101
102      var startNode = (SymbolicExpressionTreeTopLevelNode)grammar.StartSymbol.CreateTreeNode();
[7236]103      if (startNode.HasLocalParameters) startNode.ResetLocalParameters(random);
[11496]104      startNode.SetGrammar(grammar.CreateExpressionTreeGrammar());
[6887]105
106      rootNode.AddSubtree(startNode);
107
[7236]108      Create(random, startNode, maxTreeDepth - 2);
[6887]109      tree.Root = rootNode;
110      return tree;
111    }
112
[7236]113    public static void Create(IRandom random, ISymbolicExpressionTreeNode seedNode, int maxDepth) {
[6887]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);
[6888]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)
[6944]122        throw new ArgumentException("Cannot grow tree. Seed node shouldn't have arity zero.");
[6887]123
[7236]124      var allowedSymbols = seedNode.Grammar.AllowedSymbols
125        .Where(s => s.InitialFrequency > 0.0 && seedNode.Grammar.GetMaximumSubtreeCount(s) > 0)
126        .ToList();
[7108]127
[7236]128      for (var i = 0; i < arity; i++) {
129        var possibleSymbols = allowedSymbols
130          .Where(s => seedNode.Grammar.IsAllowedChildSymbol(seedNode.Symbol, s, i))
131          .ToList();
[7961]132        var weights = possibleSymbols.Select(s => s.InitialFrequency).ToList();
133        var selectedSymbol = possibleSymbols.SelectRandom(weights, random);
[6887]134        var tree = selectedSymbol.CreateTreeNode();
135        if (tree.HasLocalParameters) tree.ResetLocalParameters(random);
136        seedNode.AddSubtree(tree);
137      }
138
[6888]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
[7236]141      foreach (var subTree in seedNode.Subtrees)
142        if (subTree.Grammar.GetMaximumSubtreeCount(subTree.Symbol) > 0)
143          RecursiveCreate(random, subTree, 2, maxDepth);
[6887]144    }
145
[7236]146    private static void RecursiveCreate(IRandom random, ISymbolicExpressionTreeNode root, int currentDepth, int maxDepth) {
[6887]147      var arity = root.Grammar.GetMaximumSubtreeCount(root.Symbol);
[6888]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.");
[6887]151
[7236]152      var allowedSymbols = root.Grammar.AllowedSymbols
153        .Where(s => s.InitialFrequency > 0.0)
154        .ToList();
[7108]155
[7236]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();
[7108]162        if (!possibleSymbols.Any())
163          throw new InvalidOperationException("No symbols are available for the tree.");
[7961]164        var weights = possibleSymbols.Select(s => s.InitialFrequency).ToList();
[7964]165        var selectedSymbol = possibleSymbols.SelectRandom(weights, random);
[6887]166        var tree = selectedSymbol.CreateTreeNode();
167        if (tree.HasLocalParameters) tree.ResetLocalParameters(random);
168        root.AddSubtree(tree);
169      }
170
[7236]171      foreach (var subTree in root.Subtrees)
172        if (subTree.Grammar.GetMaximumSubtreeCount(subTree.Symbol) > 0)
173          RecursiveCreate(random, subTree, currentDepth + 1, maxDepth);
[6887]174    }
175  }
[7964]176}
Note: See TracBrowser for help on using the repository browser.