Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 5925 was 5925, checked in by gkronber, 13 years ago

#1418 fixed bugs in symbolic expression tree operators.

File size: 14.4 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    #region Parameter Properties
41    public IValueLookupParameter<IntValue> MaximumSymbolicExpressionTreeLengthParameter {
42      get { return (IValueLookupParameter<IntValue>)Parameters[MaximumSymbolicExpressionTreeLengthParameterName]; }
43    }
44    public IValueLookupParameter<IntValue> MaximumSymbolicExpressionTreeDepthParameter {
45      get { return (IValueLookupParameter<IntValue>)Parameters[MaximumSymbolicExpressionTreeDepthParameterName]; }
46    }
47    public IValueLookupParameter<ISymbolicExpressionGrammar> SymbolicExpressionTreeGrammarParameter {
48      get { return (IValueLookupParameter<ISymbolicExpressionGrammar>)Parameters[SymbolicExpressionTreeGrammarParameterName]; }
49    }
50    #endregion
51    #region Properties
52    public IntValue MaximumSymbolicExpressionTreeLength {
53      get { return MaximumSymbolicExpressionTreeLengthParameter.ActualValue; }
54    }
55    public IntValue MaximumSymbolicExpressionTreeDepth {
56      get { return MaximumSymbolicExpressionTreeDepthParameter.ActualValue; }
57    }
58    public ISymbolicExpressionGrammar SymbolicExpressionTreeGrammar {
59      get { return SymbolicExpressionTreeGrammarParameter.ActualValue; }
60    }
61    #endregion
62
63    [StorableConstructor]
64    protected ProbabilisticTreeCreator(bool deserializing) : base(deserializing) { }
65    protected ProbabilisticTreeCreator(ProbabilisticTreeCreator original, Cloner cloner) : base(original, cloner) { }
66    public ProbabilisticTreeCreator()
67      : base() {
68      Parameters.Add(new ValueLookupParameter<IntValue>(MaximumSymbolicExpressionTreeLengthParameterName, "The maximal length (number of nodes) of the symbolic expression tree."));
69      Parameters.Add(new ValueLookupParameter<IntValue>(MaximumSymbolicExpressionTreeDepthParameterName, "The maximal depth of the symbolic expression tree (a tree with one node has depth = 0)."));
70      Parameters.Add(new ValueLookupParameter<ISymbolicExpressionGrammar>(SymbolicExpressionTreeGrammarParameterName, "The tree grammar that defines the correct syntax of symbolic expression trees that should be created."));
71    }
72
73    public override IDeepCloneable Clone(Cloner cloner) {
74      return new ProbabilisticTreeCreator(this, cloner);
75    }
76
77    protected override ISymbolicExpressionTree Create(IRandom random) {
78      return Create(random, SymbolicExpressionTreeGrammar, MaximumSymbolicExpressionTreeLength.Value, MaximumSymbolicExpressionTreeDepth.Value);
79
80    }
81
82    public static ISymbolicExpressionTree Create(IRandom random, ISymbolicExpressionGrammar grammar,
83      int maxTreeLength, int maxTreeDepth) {
84      SymbolicExpressionTree tree = new SymbolicExpressionTree();
85      var rootNode = (SymbolicExpressionTreeTopLevelNode)grammar.ProgramRootSymbol.CreateTreeNode();
86      if (rootNode.HasLocalParameters) rootNode.ResetLocalParameters(random);
87      rootNode.SetGrammar(new SymbolicExpressionTreeGrammar(grammar));
88      var startNode = (SymbolicExpressionTreeTopLevelNode)grammar.StartSymbol.CreateTreeNode();
89      startNode.SetGrammar(new SymbolicExpressionTreeGrammar(grammar));
90      if (startNode.HasLocalParameters) startNode.ResetLocalParameters(random);
91      rootNode.AddSubtree(startNode);
92      PTC2(random, startNode, maxTreeLength, maxTreeDepth);
93      tree.Root = rootNode;
94      return tree;
95    }
96
97    private class TreeExtensionPoint {
98      public ISymbolicExpressionTreeNode Parent { get; set; }
99      public int ChildIndex { get; set; }
100      public int ExtensionPointDepth { get; set; }
101    }
102
103    public static void PTC2(IRandom random, ISymbolicExpressionTreeNode seedNode,
104      int maxLength, int maxDepth) {
105      // tree length is limited by the grammar and by the explicit size constraints
106      int allowedMinLength = seedNode.Grammar.GetMinimumExpressionLength(seedNode.Symbol);
107      int allowedMaxLength = Math.Min(maxLength, seedNode.Grammar.GetMaximumExpressionLength(seedNode.Symbol));
108      int tries = 0;
109      while (tries++ < MAX_TRIES) {
110        // select a target tree length uniformly in the possible range (as determined by explicit limits and limits of the grammar)
111        int targetTreeLength;
112        targetTreeLength = random.Next(allowedMinLength, allowedMaxLength + 1);
113        if (targetTreeLength <= 1 || maxDepth <= 1) return;
114
115        bool success = TryCreateFullTreeFromSeed(random, seedNode, seedNode.Grammar, targetTreeLength, maxDepth);
116
117        // if successful => check constraints and return the tree if everything looks ok       
118        if (success && seedNode.GetLength() <= maxLength && seedNode.GetDepth() <= maxDepth) {
119          return;
120        } else {
121          // clean seedNode
122          while (seedNode.Subtrees.Count() > 0) seedNode.RemoveSubtree(0);
123        }
124        // try a different length MAX_TRIES times
125      }
126      throw new ArgumentException("Couldn't create a random valid tree.");
127    }
128
129    private static bool TryCreateFullTreeFromSeed(IRandom random, ISymbolicExpressionTreeNode root, ISymbolicExpressionTreeGrammar globalGrammar,
130      int targetLength, int maxDepth) {
131      List<TreeExtensionPoint> extensionPoints = new List<TreeExtensionPoint>();
132      int currentLength = 1;
133      int totalListMinLength = globalGrammar.GetMinimumExpressionLength(root.Symbol) - 1;
134      int actualArity = SampleArity(random, root, targetLength);
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        extensionPoints.Add(new TreeExtensionPoint { Parent = root, ChildIndex = i, ExtensionPointDepth = 0 });
142      }
143      // while there are pending extension points and we have not reached the limit of adding new extension points
144      while (extensionPoints.Count > 0 && totalListMinLength + currentLength < targetLength) {
145        int randomIndex = random.Next(extensionPoints.Count);
146        TreeExtensionPoint nextExtension = extensionPoints[randomIndex];
147        extensionPoints.RemoveAt(randomIndex);
148        ISymbolicExpressionTreeNode parent = nextExtension.Parent;
149        int argumentIndex = nextExtension.ChildIndex;
150        int extensionDepth = nextExtension.ExtensionPointDepth;
151        if (extensionDepth + parent.Grammar.GetMinimumExpressionDepth(parent.Symbol) >= maxDepth) {
152          ReplaceWithMinimalTree(random, root, parent, argumentIndex);
153        } else {
154          var allowedSymbols = (from s in parent.Grammar.Symbols
155                                where s.InitialFrequency > 0.0
156                                where parent.Grammar.IsAllowedChildSymbol(parent.Symbol, s, argumentIndex)
157                                where parent.Grammar.GetMinimumExpressionDepth(s) + extensionDepth - 1 < maxDepth
158                                where parent.Grammar.GetMaximumExpressionLength(s) > targetLength - totalListMinLength - currentLength
159                                select s)
160                               .ToList();
161          var weights = allowedSymbols.Select(x => x.InitialFrequency).ToList();
162          var selectedSymbol = allowedSymbols.SelectRandom(weights, random);
163          ISymbolicExpressionTreeNode newTree = selectedSymbol.CreateTreeNode();
164          if (newTree.HasLocalParameters) newTree.ResetLocalParameters(random);
165          parent.RemoveSubtree(argumentIndex);
166          parent.InsertSubtree(argumentIndex, newTree);
167
168          var topLevelNode = newTree as SymbolicExpressionTreeTopLevelNode;
169          if (topLevelNode != null)
170            topLevelNode.SetGrammar((ISymbolicExpressionTreeGrammar)root.Grammar.Clone());
171
172          currentLength++;
173          totalListMinLength--;
174
175          actualArity = SampleArity(random, newTree, targetLength - currentLength);
176          if (actualArity < 0) return false;
177          for (int i = 0; i < actualArity; i++) {
178            // insert a dummy sub-tree and add the pending extension to the list
179            var dummy = new SymbolicExpressionTreeNode();
180            newTree.AddSubtree(dummy);
181            extensionPoints.Add(new TreeExtensionPoint { Parent = newTree, ChildIndex = i, ExtensionPointDepth = extensionDepth + 1 });
182          }
183          totalListMinLength += newTree.Grammar.GetMinimumExpressionLength(newTree.Symbol);
184        }
185      }
186      // fill all pending extension points
187      while (extensionPoints.Count > 0) {
188        int randomIndex = random.Next(extensionPoints.Count);
189        TreeExtensionPoint nextExtension = extensionPoints[randomIndex];
190        extensionPoints.RemoveAt(randomIndex);
191        ISymbolicExpressionTreeNode parent = nextExtension.Parent;
192        int a = nextExtension.ChildIndex;
193        int d = nextExtension.ExtensionPointDepth;
194        ReplaceWithMinimalTree(random, root, parent, a);
195      }
196      return true;
197    }
198
199    private static void ReplaceWithMinimalTree(IRandom random, ISymbolicExpressionTreeNode root, ISymbolicExpressionTreeNode parent,
200      int childIndex) {
201      // determine possible symbols that will lead to the smallest possible tree
202      var possibleSymbols = (from s in parent.Grammar.GetAllowedChildSymbols(parent.Symbol, childIndex)
203                             where s.InitialFrequency > 0.0
204                             group s by parent.Grammar.GetMinimumExpressionLength(s) into g
205                             orderby g.Key
206                             select g).First().ToList();
207      var weights = possibleSymbols.Select(x => x.InitialFrequency).ToList();
208      var selectedSymbol = possibleSymbols.SelectRandom(weights, random);
209      var tree = selectedSymbol.CreateTreeNode();
210      if (tree.HasLocalParameters) tree.ResetLocalParameters(random);
211      parent.RemoveSubtree(childIndex);
212      parent.InsertSubtree(childIndex, tree);
213
214      var topLevelNode = tree as SymbolicExpressionTreeTopLevelNode;
215      if (topLevelNode != null)
216        topLevelNode.SetGrammar((ISymbolicExpressionTreeGrammar)root.Grammar.Clone());
217
218      for (int i = 0; i < tree.Grammar.GetMinimumSubtreeCount(tree.Symbol); i++) {
219        // insert a dummy sub-tree and add the pending extension to the list
220        var dummy = new SymbolicExpressionTreeNode();
221        tree.AddSubtree(dummy);
222        // replace the just inserted dummy by recursive application
223        ReplaceWithMinimalTree(random, root, tree, i);
224      }
225    }
226
227    private static bool IsTopLevelBranch(ISymbolicExpressionTreeNode root, ISymbolicExpressionTreeNode branch) {
228      return branch is SymbolicExpressionTreeTopLevelNode;
229    }
230
231    private static int SampleArity(IRandom random, ISymbolicExpressionTreeNode node, int targetLength) {
232      // select actualArity randomly with the constraint that the sub-trees in the minimal arity can become large enough
233      int minArity = node.Grammar.GetMinimumSubtreeCount(node.Symbol);
234      int maxArity = node.Grammar.GetMaximumSubtreeCount(node.Symbol);
235      if (maxArity > targetLength) {
236        maxArity = targetLength;
237      }
238      // 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
239      // 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
240      long aggregatedLongestExpressionLength = 0;
241      for (int i = 0; i < maxArity; i++) {
242        aggregatedLongestExpressionLength += (from s in node.Grammar.GetAllowedChildSymbols(node.Symbol, i)
243                                              where s.InitialFrequency > 0.0
244                                              select node.Grammar.GetMaximumExpressionLength(s)).Max();
245        if (aggregatedLongestExpressionLength < targetLength) minArity = i + 1;
246        else break;
247      }
248
249      // 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
250      // 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
251      long aggregatedShortestExpressionLength = 0;
252      for (int i = 0; i < maxArity; i++) {
253        aggregatedShortestExpressionLength += (from s in node.Grammar.GetAllowedChildSymbols(node.Symbol, i)
254                                               where s.InitialFrequency > 0.0
255                                               select node.Grammar.GetMinimumExpressionLength(s)).Min();
256        if (aggregatedShortestExpressionLength > targetLength) {
257          maxArity = i;
258          break;
259        }
260      }
261      if (minArity > maxArity) return -1;
262      return random.Next(minArity, maxArity + 1);
263    }
264  }
265}
Note: See TracBrowser for help on using the repository browser.