Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 7807 was 7259, checked in by swagner, 13 years ago

Updated year of copyrights to 2012 (#1716)

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