Free cookie consent management tool by TermsFeed Policy Generator

source: branches/PersistenceSpeedUp/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Creators/ProbabilisticTreeCreator.cs @ 16375

Last change on this file since 16375 was 6760, checked in by epitzer, 13 years ago

#1530 integrate changes from trunk

File size: 16.5 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2011 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 HeuristicLab.Data;
28using HeuristicLab.Parameters;
29using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
30
31namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding {
32  [StorableClass]
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    private const string MaximumSymbolicExpressionTreeLengthParameterName = "MaximumSymbolicExpressionTreeLength";
38    private const string MaximumSymbolicExpressionTreeDepthParameterName = "MaximumSymbolicExpressionTreeDepth";
39    private const string SymbolicExpressionTreeGrammarParameterName = "SymbolicExpressionTreeGrammar";
40    private const string ClonedSymbolicExpressionTreeGrammarParameterName = "ClonedSymbolicExpressionTreeGrammar";
41    #region Parameter Properties
42    public IValueLookupParameter<IntValue> MaximumSymbolicExpressionTreeLengthParameter {
43      get { return (IValueLookupParameter<IntValue>)Parameters[MaximumSymbolicExpressionTreeLengthParameterName]; }
44    }
45    public IValueLookupParameter<IntValue> MaximumSymbolicExpressionTreeDepthParameter {
46      get { return (IValueLookupParameter<IntValue>)Parameters[MaximumSymbolicExpressionTreeDepthParameterName]; }
47    }
48    public IValueLookupParameter<ISymbolicExpressionGrammar> SymbolicExpressionTreeGrammarParameter {
49      get { return (IValueLookupParameter<ISymbolicExpressionGrammar>)Parameters[SymbolicExpressionTreeGrammarParameterName]; }
50    }
51    public ILookupParameter<ISymbolicExpressionGrammar> ClonedSymbolicExpressionTreeGrammarParameter {
52      get { return (ILookupParameter<ISymbolicExpressionGrammar>)Parameters[ClonedSymbolicExpressionTreeGrammarParameterName]; }
53    }
54    #endregion
55    #region Properties
56    public IntValue MaximumSymbolicExpressionTreeLength {
57      get { return MaximumSymbolicExpressionTreeLengthParameter.ActualValue; }
58    }
59    public IntValue MaximumSymbolicExpressionTreeDepth {
60      get { return MaximumSymbolicExpressionTreeDepthParameter.ActualValue; }
61    }
62    public ISymbolicExpressionGrammar SymbolicExpressionTreeGrammar {
63      get { return ClonedSymbolicExpressionTreeGrammarParameter.ActualValue; }
64    }
65    #endregion
66
67    [StorableConstructor]
68    protected ProbabilisticTreeCreator(bool deserializing) : base(deserializing) { }
69    protected ProbabilisticTreeCreator(ProbabilisticTreeCreator original, Cloner cloner) : base(original, cloner) { }
70    public ProbabilisticTreeCreator()
71      : base() {
72      Parameters.Add(new ValueLookupParameter<IntValue>(MaximumSymbolicExpressionTreeLengthParameterName, "The maximal length (number of nodes) of the symbolic expression tree."));
73      Parameters.Add(new ValueLookupParameter<IntValue>(MaximumSymbolicExpressionTreeDepthParameterName, "The maximal depth of the symbolic expression tree (a tree with one node has depth = 0)."));
74      Parameters.Add(new ValueLookupParameter<ISymbolicExpressionGrammar>(SymbolicExpressionTreeGrammarParameterName, "The tree grammar that defines the correct syntax of symbolic expression trees that should be created."));
75      Parameters.Add(new LookupParameter<ISymbolicExpressionGrammar>(ClonedSymbolicExpressionTreeGrammarParameterName, "An immutable clone of the concrete grammar that is actually used to create and manipulate trees."));
76    }
77
78    public override IDeepCloneable Clone(Cloner cloner) {
79      return new ProbabilisticTreeCreator(this, cloner);
80    }
81    [StorableHook(HookType.AfterDeserialization)]
82    private void AfterDeserialization() {
83      if (!Parameters.ContainsKey(ClonedSymbolicExpressionTreeGrammarParameterName))
84        Parameters.Add(new LookupParameter<ISymbolicExpressionGrammar>(ClonedSymbolicExpressionTreeGrammarParameterName, "An immutable clone of the concrete grammar that is actually used to create and manipulate trees."));
85    }
86
87    public override IOperation Apply() {
88      if (ClonedSymbolicExpressionTreeGrammarParameter.ActualValue == null) {
89        SymbolicExpressionTreeGrammarParameter.ActualValue.ReadOnly = true;
90        IScope globalScope = ExecutionContext.Scope;
91        while (globalScope.Parent != null)
92          globalScope = globalScope.Parent;
93
94        globalScope.Variables.Add(new Variable(ClonedSymbolicExpressionTreeGrammarParameterName, (ISymbolicExpressionGrammar)SymbolicExpressionTreeGrammarParameter.ActualValue.Clone()));
95      }
96      return base.Apply();
97    }
98
99    protected override ISymbolicExpressionTree Create(IRandom random) {
100      return Create(random, SymbolicExpressionTreeGrammar, MaximumSymbolicExpressionTreeLength.Value, MaximumSymbolicExpressionTreeDepth.Value);
101    }
102
103    public static ISymbolicExpressionTree Create(IRandom random, ISymbolicExpressionGrammar grammar,
104      int maxTreeLength, int maxTreeDepth) {
105      SymbolicExpressionTree tree = new SymbolicExpressionTree();
106      var rootNode = (SymbolicExpressionTreeTopLevelNode)grammar.ProgramRootSymbol.CreateTreeNode();
107      if (rootNode.HasLocalParameters) rootNode.ResetLocalParameters(random);
108      rootNode.SetGrammar(new SymbolicExpressionTreeGrammar(grammar));
109      var startNode = (SymbolicExpressionTreeTopLevelNode)grammar.StartSymbol.CreateTreeNode();
110      startNode.SetGrammar(new SymbolicExpressionTreeGrammar(grammar));
111      if (startNode.HasLocalParameters) startNode.ResetLocalParameters(random);
112      rootNode.AddSubtree(startNode);
113      PTC2(random, startNode, maxTreeLength, maxTreeDepth);
114      tree.Root = rootNode;
115      return tree;
116    }
117
118    private class TreeExtensionPoint {
119      public ISymbolicExpressionTreeNode Parent { get; set; }
120      public int ChildIndex { get; set; }
121      public int ExtensionPointDepth { get; set; }
122    }
123
124    public static void PTC2(IRandom random, ISymbolicExpressionTreeNode seedNode,
125      int maxLength, int maxDepth) {
126      // make sure it is possible to create a trees smaller than maxLength and maxDepth
127      if (seedNode.Grammar.GetMinimumExpressionLength(seedNode.Symbol) > maxLength)
128        throw new ArgumentException("Cannot create trees of length " + maxLength + " or shorter because of grammar constraints.", "maxLength");
129      if (seedNode.Grammar.GetMinimumExpressionDepth(seedNode.Symbol) > maxDepth)
130        throw new ArgumentException("Cannot create trees of depth " + maxDepth + " or smaller because of grammar constraints.", "maxDepth");
131
132      // tree length is limited by the grammar and by the explicit size constraints
133      int allowedMinLength = seedNode.Grammar.GetMinimumExpressionLength(seedNode.Symbol);
134      int allowedMaxLength = Math.Min(maxLength, seedNode.Grammar.GetMaximumExpressionLength(seedNode.Symbol));
135      int tries = 0;
136      while (tries++ < MAX_TRIES) {
137        // select a target tree length uniformly in the possible range (as determined by explicit limits and limits of the grammar)
138        int targetTreeLength;
139        targetTreeLength = random.Next(allowedMinLength, allowedMaxLength + 1);
140        if (targetTreeLength <= 1 || maxDepth <= 1) return;
141
142        bool success = TryCreateFullTreeFromSeed(random, seedNode, seedNode.Grammar, targetTreeLength, maxDepth);
143
144        // if successful => check constraints and return the tree if everything looks ok       
145        if (success && seedNode.GetLength() <= maxLength && seedNode.GetDepth() <= maxDepth) {
146          return;
147        } else {
148          // clean seedNode
149          while (seedNode.Subtrees.Count() > 0) seedNode.RemoveSubtree(0);
150        }
151        // try a different length MAX_TRIES times
152      }
153      throw new ArgumentException("Couldn't create a random valid tree.");
154    }
155
156    private static bool TryCreateFullTreeFromSeed(IRandom random, ISymbolicExpressionTreeNode root, ISymbolicExpressionTreeGrammar globalGrammar,
157      int targetLength, int maxDepth) {
158      List<TreeExtensionPoint> extensionPoints = new List<TreeExtensionPoint>();
159      int currentLength = 1;
160      int totalListMinLength = globalGrammar.GetMinimumExpressionLength(root.Symbol) - 1;
161      int actualArity = SampleArity(random, root, targetLength);
162      if (actualArity < 0) return false;
163
164      for (int i = 0; i < actualArity; i++) {
165        // insert a dummy sub-tree and add the pending extension to the list
166        var dummy = new SymbolicExpressionTreeNode();
167        root.AddSubtree(dummy);
168        extensionPoints.Add(new TreeExtensionPoint { Parent = root, ChildIndex = i, ExtensionPointDepth = 0 });
169      }
170      // while there are pending extension points and we have not reached the limit of adding new extension points
171      while (extensionPoints.Count > 0 && totalListMinLength + currentLength < targetLength) {
172        int randomIndex = random.Next(extensionPoints.Count);
173        TreeExtensionPoint nextExtension = extensionPoints[randomIndex];
174        extensionPoints.RemoveAt(randomIndex);
175        ISymbolicExpressionTreeNode parent = nextExtension.Parent;
176        int argumentIndex = nextExtension.ChildIndex;
177        int extensionDepth = nextExtension.ExtensionPointDepth;
178        if (parent.Grammar.GetMinimumExpressionDepth(parent.Symbol) >= maxDepth - extensionDepth) {
179          ReplaceWithMinimalTree(random, root, parent, argumentIndex);
180        } else {
181          var allowedSymbols = (from s in parent.Grammar.Symbols
182                                where s.InitialFrequency > 0.0
183                                where parent.Grammar.IsAllowedChildSymbol(parent.Symbol, s, argumentIndex)
184                                where parent.Grammar.GetMinimumExpressionDepth(s) < maxDepth - extensionDepth + 1
185                                where parent.Grammar.GetMaximumExpressionLength(s) > targetLength - totalListMinLength - currentLength
186                                select s)
187                               .ToList();
188          if (allowedSymbols.Count == 0) return false;
189          var weights = allowedSymbols.Select(x => x.InitialFrequency).ToList();
190          var selectedSymbol = allowedSymbols.SelectRandom(weights, random);
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          totalListMinLength--;
202
203          actualArity = SampleArity(random, newTree, targetLength - currentLength);
204          if (actualArity < 0) return false;
205          for (int i = 0; i < actualArity; i++) {
206            // insert a dummy sub-tree and add the pending extension to the list
207            var dummy = new SymbolicExpressionTreeNode();
208            newTree.AddSubtree(dummy);
209            extensionPoints.Add(new TreeExtensionPoint { Parent = newTree, ChildIndex = i, ExtensionPointDepth = extensionDepth + 1 });
210          }
211          totalListMinLength += newTree.Grammar.GetMinimumExpressionLength(newTree.Symbol);
212        }
213      }
214      // fill all pending extension points
215      while (extensionPoints.Count > 0) {
216        int randomIndex = random.Next(extensionPoints.Count);
217        TreeExtensionPoint nextExtension = extensionPoints[randomIndex];
218        extensionPoints.RemoveAt(randomIndex);
219        ISymbolicExpressionTreeNode parent = nextExtension.Parent;
220        int a = nextExtension.ChildIndex;
221        int d = nextExtension.ExtensionPointDepth;
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      var selectedSymbol = possibleSymbols.SelectRandom(weights, random);
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 bool IsTopLevelBranch(ISymbolicExpressionTreeNode root, ISymbolicExpressionTreeNode branch) {
256      return branch is SymbolicExpressionTreeTopLevelNode;
257    }
258
259    private static int SampleArity(IRandom random, ISymbolicExpressionTreeNode node, int targetLength) {
260      // select actualArity randomly with the constraint that the sub-trees in the minimal arity can become large enough
261      int minArity = node.Grammar.GetMinimumSubtreeCount(node.Symbol);
262      int maxArity = node.Grammar.GetMaximumSubtreeCount(node.Symbol);
263      if (maxArity > targetLength) {
264        maxArity = targetLength;
265      }
266      // 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
267      // 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
268      long aggregatedLongestExpressionLength = 0;
269      for (int i = 0; i < maxArity; i++) {
270        aggregatedLongestExpressionLength += (from s in node.Grammar.GetAllowedChildSymbols(node.Symbol, i)
271                                              where s.InitialFrequency > 0.0
272                                              select node.Grammar.GetMaximumExpressionLength(s)).Max();
273        if (aggregatedLongestExpressionLength < targetLength) minArity = i + 1;
274        else break;
275      }
276
277      // 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
278      // 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
279      long aggregatedShortestExpressionLength = 0;
280      for (int i = 0; i < maxArity; i++) {
281        aggregatedShortestExpressionLength += (from s in node.Grammar.GetAllowedChildSymbols(node.Symbol, i)
282                                               where s.InitialFrequency > 0.0
283                                               select node.Grammar.GetMinimumExpressionLength(s)).Min();
284        if (aggregatedShortestExpressionLength > targetLength) {
285          maxArity = i;
286          break;
287        }
288      }
289      if (minArity > maxArity) return -1;
290      return random.Next(minArity, maxArity + 1);
291    }
292  }
293}
Note: See TracBrowser for help on using the repository browser.