Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2521_ProblemRefactoring/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Creators/ProbabilisticTreeCreator.cs @ 17654

Last change on this file since 17654 was 17654, checked in by abeham, 4 years ago

#2521: removed NonDicoverableType attribute from tree creators in the symbolic expression tree encoding

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