Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Creators/ProbabilisticTreeCreator.cs @ 13339

Last change on this file since 13339 was 13227, checked in by mkommend, 9 years ago

#2510: Added method for creating trees with a specific length to the PTC2 and adapted the according unit test.

File size: 16.1 KB
RevLine 
[645]1#region License Information
2/* HeuristicLab
[12012]3 * Copyright (C) 2002-2015 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
[645]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
[3462]22using System;
[4068]23using System.Collections.Generic;
[3462]24using System.Linq;
[4722]25using HeuristicLab.Common;
[645]26using HeuristicLab.Core;
[4068]27using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
[7012]28using HeuristicLab.PluginInfrastructure;
[645]29
[5499]30namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding {
[7012]31  [NonDiscoverableType]
[3223]32  [StorableClass]
[5549]33  [Item("ProbabilisticTreeCreator", "An operator that creates new symbolic expression trees with uniformly distributed length")]
[5618]34  public class ProbabilisticTreeCreator : SymbolicExpressionTreeCreator,
[5686]35    ISymbolicExpressionTreeSizeConstraintOperator, ISymbolicExpressionTreeGrammarBasedOperator {
[3369]36    private const int MAX_TRIES = 100;
[5499]37
[4722]38    [StorableConstructor]
[5618]39    protected ProbabilisticTreeCreator(bool deserializing) : base(deserializing) { }
40    protected ProbabilisticTreeCreator(ProbabilisticTreeCreator original, Cloner cloner) : base(original, cloner) { }
[5499]41    public ProbabilisticTreeCreator()
42      : base() {
[12422]43
[5499]44    }
[3338]45
[4722]46    public override IDeepCloneable Clone(Cloner cloner) {
47      return new ProbabilisticTreeCreator(this, cloner);
[645]48    }
49
[6233]50
[5510]51    protected override ISymbolicExpressionTree Create(IRandom random) {
[12422]52      return Create(random, ClonedSymbolicExpressionTreeGrammarParameter.ActualValue,
53        MaximumSymbolicExpressionTreeLengthParameter.ActualValue.Value, MaximumSymbolicExpressionTreeDepthParameter.ActualValue.Value);
[2447]54    }
55
[7012]56    public override ISymbolicExpressionTree CreateTree(IRandom random, ISymbolicExpressionGrammar grammar, int maxTreeLength, int maxTreeDepth) {
57      return Create(random, grammar, maxTreeLength, maxTreeDepth);
58    }
59
60    public static ISymbolicExpressionTree Create(IRandom random, ISymbolicExpressionGrammar grammar, int maxTreeLength, int maxTreeDepth) {
[3223]61      SymbolicExpressionTree tree = new SymbolicExpressionTree();
[5686]62      var rootNode = (SymbolicExpressionTreeTopLevelNode)grammar.ProgramRootSymbol.CreateTreeNode();
[3442]63      if (rootNode.HasLocalParameters) rootNode.ResetLocalParameters(random);
[11496]64      rootNode.SetGrammar(grammar.CreateExpressionTreeGrammar());
65
[5686]66      var startNode = (SymbolicExpressionTreeTopLevelNode)grammar.StartSymbol.CreateTreeNode();
67      if (startNode.HasLocalParameters) startNode.ResetLocalParameters(random);
[11496]68      startNode.SetGrammar(grammar.CreateExpressionTreeGrammar());
69
[5733]70      rootNode.AddSubtree(startNode);
[5686]71      PTC2(random, startNode, maxTreeLength, maxTreeDepth);
72      tree.Root = rootNode;
[3223]73      return tree;
74    }
75
[13227]76    public static ISymbolicExpressionTree CreateExpressionTree(IRandom random, ISymbolicExpressionGrammar grammar, int targetLength,
77      int maxTreeDepth) {
78      SymbolicExpressionTree tree = new SymbolicExpressionTree();
79      var rootNode = (SymbolicExpressionTreeTopLevelNode)grammar.ProgramRootSymbol.CreateTreeNode();
80      if (rootNode.HasLocalParameters) rootNode.ResetLocalParameters(random);
81      rootNode.SetGrammar(grammar.CreateExpressionTreeGrammar());
82
83      var startNode = (SymbolicExpressionTreeTopLevelNode)grammar.StartSymbol.CreateTreeNode();
84      if (startNode.HasLocalParameters) startNode.ResetLocalParameters(random);
85      startNode.SetGrammar(grammar.CreateExpressionTreeGrammar());
86
87      rootNode.AddSubtree(startNode);
88      bool success = TryCreateFullTreeFromSeed(random, startNode, targetLength - 2, maxTreeDepth - 1);
89      if (!success) throw new InvalidOperationException(string.Format("Could not create a tree with target length {0} and max depth {1}", targetLength, maxTreeDepth));
90
91      tree.Root = rootNode;
92      return tree;
93
94    }
95
[3338]96    private class TreeExtensionPoint {
[5499]97      public ISymbolicExpressionTreeNode Parent { get; set; }
[3338]98      public int ChildIndex { get; set; }
99      public int ExtensionPointDepth { get; set; }
[6911]100      public int MaximumExtensionLength { get; set; }
101      public int MinimumExtensionLength { get; set; }
[3223]102    }
[3360]103
[5686]104    public static void PTC2(IRandom random, ISymbolicExpressionTreeNode seedNode,
105      int maxLength, int maxDepth) {
[6009]106      // make sure it is possible to create a trees smaller than maxLength and maxDepth
107      if (seedNode.Grammar.GetMinimumExpressionLength(seedNode.Symbol) > maxLength)
108        throw new ArgumentException("Cannot create trees of length " + maxLength + " or shorter because of grammar constraints.", "maxLength");
109      if (seedNode.Grammar.GetMinimumExpressionDepth(seedNode.Symbol) > maxDepth)
110        throw new ArgumentException("Cannot create trees of depth " + maxDepth + " or smaller because of grammar constraints.", "maxDepth");
111
[5549]112      // tree length is limited by the grammar and by the explicit size constraints
[5686]113      int allowedMinLength = seedNode.Grammar.GetMinimumExpressionLength(seedNode.Symbol);
[6911]114      int allowedMaxLength = Math.Min(maxLength, seedNode.Grammar.GetMaximumExpressionLength(seedNode.Symbol, maxDepth));
[3369]115      int tries = 0;
116      while (tries++ < MAX_TRIES) {
[5549]117        // select a target tree length uniformly in the possible range (as determined by explicit limits and limits of the grammar)
118        int targetTreeLength;
119        targetTreeLength = random.Next(allowedMinLength, allowedMaxLength + 1);
[5686]120        if (targetTreeLength <= 1 || maxDepth <= 1) return;
[3369]121
[6911]122        bool success = TryCreateFullTreeFromSeed(random, seedNode, targetTreeLength - 1, maxDepth - 1);
[3369]123
[4189]124        // if successful => check constraints and return the tree if everything looks ok       
[5549]125        if (success && seedNode.GetLength() <= maxLength && seedNode.GetDepth() <= maxDepth) {
[5686]126          return;
[3369]127        } else {
128          // clean seedNode
[13227]129          while (seedNode.Subtrees.Any()) seedNode.RemoveSubtree(0);
[3360]130        }
[5549]131        // try a different length MAX_TRIES times
[3369]132      }
[3825]133      throw new ArgumentException("Couldn't create a random valid tree.");
[3338]134    }
135
[6911]136    private static bool TryCreateFullTreeFromSeed(IRandom random, ISymbolicExpressionTreeNode root,
[5686]137      int targetLength, int maxDepth) {
[3338]138      List<TreeExtensionPoint> extensionPoints = new List<TreeExtensionPoint>();
[6911]139      int currentLength = 0;
140      int actualArity = SampleArity(random, root, targetLength, maxDepth);
[5727]141      if (actualArity < 0) return false;
142
[3223]143      for (int i = 0; i < actualArity; i++) {
144        // insert a dummy sub-tree and add the pending extension to the list
[3338]145        var dummy = new SymbolicExpressionTreeNode();
[5733]146        root.AddSubtree(dummy);
[6911]147        var x = new TreeExtensionPoint { Parent = root, ChildIndex = i, ExtensionPointDepth = 0 };
148        FillExtensionLengths(x, maxDepth);
149        extensionPoints.Add(x);
[3223]150      }
[8311]151      //necessary to use long data type as the extension point length could be int.MaxValue
152      long minExtensionPointsLength = extensionPoints.Select(x => (long)x.MinimumExtensionLength).Sum();
153      long maxExtensionPointsLength = extensionPoints.Select(x => (long)x.MaximumExtensionLength).Sum();
[6911]154
[3223]155      // while there are pending extension points and we have not reached the limit of adding new extension points
[6911]156      while (extensionPoints.Count > 0 && minExtensionPointsLength + currentLength <= targetLength) {
[3294]157        int randomIndex = random.Next(extensionPoints.Count);
[3338]158        TreeExtensionPoint nextExtension = extensionPoints[randomIndex];
[3294]159        extensionPoints.RemoveAt(randomIndex);
[5499]160        ISymbolicExpressionTreeNode parent = nextExtension.Parent;
[3338]161        int argumentIndex = nextExtension.ChildIndex;
162        int extensionDepth = nextExtension.ExtensionPointDepth;
[6911]163
164        if (parent.Grammar.GetMinimumExpressionDepth(parent.Symbol) > maxDepth - extensionDepth) {
[5686]165          ReplaceWithMinimalTree(random, root, parent, argumentIndex);
[6911]166          int insertedTreeLength = parent.GetSubtree(argumentIndex).GetLength();
167          currentLength += insertedTreeLength;
168          minExtensionPointsLength -= insertedTreeLength;
169          maxExtensionPointsLength -= insertedTreeLength;
[3223]170        } else {
[6911]171          //remove currently chosen extension point from calculation
172          minExtensionPointsLength -= nextExtension.MinimumExtensionLength;
173          maxExtensionPointsLength -= nextExtension.MaximumExtensionLength;
174
175          var symbols = from s in parent.Grammar.GetAllowedChildSymbols(parent.Symbol, argumentIndex)
176                        where s.InitialFrequency > 0.0
177                        where parent.Grammar.GetMinimumExpressionDepth(s) <= maxDepth - extensionDepth
178                        where parent.Grammar.GetMinimumExpressionLength(s) <= targetLength - currentLength - minExtensionPointsLength
179                        select s;
180          if (maxExtensionPointsLength < targetLength - currentLength)
181            symbols = from s in symbols
182                      where parent.Grammar.GetMaximumExpressionLength(s, maxDepth - extensionDepth) >= targetLength - currentLength - maxExtensionPointsLength
183                      select s;
184          var allowedSymbols = symbols.ToList();
185
[6233]186          if (allowedSymbols.Count == 0) return false;
[5499]187          var weights = allowedSymbols.Select(x => x.InitialFrequency).ToList();
[12422]188
189#pragma warning disable 612, 618
[5499]190          var selectedSymbol = allowedSymbols.SelectRandom(weights, random);
[12422]191#pragma warning restore 612, 618
192
[5499]193          ISymbolicExpressionTreeNode newTree = selectedSymbol.CreateTreeNode();
[3442]194          if (newTree.HasLocalParameters) newTree.ResetLocalParameters(random);
[5733]195          parent.RemoveSubtree(argumentIndex);
196          parent.InsertSubtree(argumentIndex, newTree);
[3338]197
[5686]198          var topLevelNode = newTree as SymbolicExpressionTreeTopLevelNode;
199          if (topLevelNode != null)
200            topLevelNode.SetGrammar((ISymbolicExpressionTreeGrammar)root.Grammar.Clone());
[3338]201
[5549]202          currentLength++;
[6911]203          actualArity = SampleArity(random, newTree, targetLength - currentLength, maxDepth - extensionDepth);
[5727]204          if (actualArity < 0) return false;
[3223]205          for (int i = 0; i < actualArity; i++) {
206            // insert a dummy sub-tree and add the pending extension to the list
[3338]207            var dummy = new SymbolicExpressionTreeNode();
[5733]208            newTree.AddSubtree(dummy);
[6911]209            var x = new TreeExtensionPoint { Parent = newTree, ChildIndex = i, ExtensionPointDepth = extensionDepth + 1 };
210            FillExtensionLengths(x, maxDepth);
211            extensionPoints.Add(x);
212            maxExtensionPointsLength += x.MaximumExtensionLength;
213            minExtensionPointsLength += x.MinimumExtensionLength;
[3223]214          }
215        }
216      }
217      // fill all pending extension points
[3294]218      while (extensionPoints.Count > 0) {
219        int randomIndex = random.Next(extensionPoints.Count);
[3338]220        TreeExtensionPoint nextExtension = extensionPoints[randomIndex];
[3294]221        extensionPoints.RemoveAt(randomIndex);
[5499]222        ISymbolicExpressionTreeNode parent = nextExtension.Parent;
[3338]223        int a = nextExtension.ChildIndex;
[5686]224        ReplaceWithMinimalTree(random, root, parent, a);
[3223]225      }
[5727]226      return true;
[2210]227    }
[3223]228
[5499]229    private static void ReplaceWithMinimalTree(IRandom random, ISymbolicExpressionTreeNode root, ISymbolicExpressionTreeNode parent,
[5686]230      int childIndex) {
[3338]231      // determine possible symbols that will lead to the smallest possible tree
[5686]232      var possibleSymbols = (from s in parent.Grammar.GetAllowedChildSymbols(parent.Symbol, childIndex)
[5925]233                             where s.InitialFrequency > 0.0
[5686]234                             group s by parent.Grammar.GetMinimumExpressionLength(s) into g
[3338]235                             orderby g.Key
[5499]236                             select g).First().ToList();
237      var weights = possibleSymbols.Select(x => x.InitialFrequency).ToList();
[12422]238
239#pragma warning disable 612, 618
[5499]240      var selectedSymbol = possibleSymbols.SelectRandom(weights, random);
[12422]241#pragma warning restore 612, 618
242
[3338]243      var tree = selectedSymbol.CreateTreeNode();
[3442]244      if (tree.HasLocalParameters) tree.ResetLocalParameters(random);
[5733]245      parent.RemoveSubtree(childIndex);
246      parent.InsertSubtree(childIndex, tree);
[5686]247
248      var topLevelNode = tree as SymbolicExpressionTreeTopLevelNode;
249      if (topLevelNode != null)
250        topLevelNode.SetGrammar((ISymbolicExpressionTreeGrammar)root.Grammar.Clone());
251
252      for (int i = 0; i < tree.Grammar.GetMinimumSubtreeCount(tree.Symbol); i++) {
[3338]253        // insert a dummy sub-tree and add the pending extension to the list
254        var dummy = new SymbolicExpressionTreeNode();
[5733]255        tree.AddSubtree(dummy);
[3338]256        // replace the just inserted dummy by recursive application
[5686]257        ReplaceWithMinimalTree(random, root, tree, i);
[3338]258      }
259    }
[3360]260
[6911]261    private static void FillExtensionLengths(TreeExtensionPoint extension, int maxDepth) {
262      var grammar = extension.Parent.Grammar;
263      int maxLength = int.MinValue;
264      int minLength = int.MaxValue;
265      foreach (ISymbol s in grammar.GetAllowedChildSymbols(extension.Parent.Symbol, extension.ChildIndex)) {
266        if (s.InitialFrequency > 0.0) {
267          int max = grammar.GetMaximumExpressionLength(s, maxDepth - extension.ExtensionPointDepth);
268          maxLength = Math.Max(maxLength, max);
269          int min = grammar.GetMinimumExpressionLength(s);
270          minLength = Math.Min(minLength, min);
271        }
272      }
273
274      extension.MaximumExtensionLength = maxLength;
275      extension.MinimumExtensionLength = minLength;
[3338]276    }
277
[6911]278    private static int SampleArity(IRandom random, ISymbolicExpressionTreeNode node, int targetLength, int maxDepth) {
[3223]279      // select actualArity randomly with the constraint that the sub-trees in the minimal arity can become large enough
[5686]280      int minArity = node.Grammar.GetMinimumSubtreeCount(node.Symbol);
281      int maxArity = node.Grammar.GetMaximumSubtreeCount(node.Symbol);
[5549]282      if (maxArity > targetLength) {
283        maxArity = targetLength;
[3223]284      }
[6911]285      if (minArity == maxArity) return minArity;
286
[5549]287      // the min number of sub-trees has to be set to a value that is large enough so that the largest possible tree is at least tree length
288      // if 1..3 trees are possible and the largest possible first sub-tree is smaller larger than the target length then minArity should be at least 2
[3237]289      long aggregatedLongestExpressionLength = 0;
[3223]290      for (int i = 0; i < maxArity; i++) {
[5686]291        aggregatedLongestExpressionLength += (from s in node.Grammar.GetAllowedChildSymbols(node.Symbol, i)
[5925]292                                              where s.InitialFrequency > 0.0
[6911]293                                              select node.Grammar.GetMaximumExpressionLength(s, maxDepth)).Max();
[6803]294        if (i > minArity && aggregatedLongestExpressionLength < targetLength) minArity = i + 1;
[3223]295        else break;
296      }
297
[5549]298      // the max number of sub-trees has to be set to a value that is small enough so that the smallest possible tree is at most tree length
299      // if 1..3 trees are possible and the smallest possible first sub-tree is already larger than the target length then maxArity should be at most 0
[3237]300      long aggregatedShortestExpressionLength = 0;
[3223]301      for (int i = 0; i < maxArity; i++) {
[5686]302        aggregatedShortestExpressionLength += (from s in node.Grammar.GetAllowedChildSymbols(node.Symbol, i)
[5925]303                                               where s.InitialFrequency > 0.0
[5686]304                                               select node.Grammar.GetMinimumExpressionLength(s)).Min();
[5549]305        if (aggregatedShortestExpressionLength > targetLength) {
[3223]306          maxArity = i;
307          break;
308        }
309      }
[5727]310      if (minArity > maxArity) return -1;
[3223]311      return random.Next(minArity, maxArity + 1);
312    }
[6911]313
[2447]314  }
[645]315}
Note: See TracBrowser for help on using the repository browser.