Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 18064 was 18064, checked in by mkommend, 3 years ago

#2997: Simplified tree creator interface and removed cloning of grammars,

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