Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 18086 was 18086, checked in by mkommend, 2 years ago

#2521: Merged trunk changes into branch.

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