Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.StructureIdentification/TreeGardener.cs @ 183

Last change on this file since 183 was 182, checked in by gkronber, 17 years ago

fixed #127

File size: 20.9 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2008 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.Text;
25using HeuristicLab.Core;
26using HeuristicLab.Constraints;
27using System.Diagnostics;
28using HeuristicLab.Data;
29using System.Linq;
30using HeuristicLab.Random;
31using HeuristicLab.Operators;
32using HeuristicLab.Selection;
33using HeuristicLab.Functions;
34using System.Collections;
35
36namespace HeuristicLab.StructureIdentification {
37  internal class TreeGardener {
38    private IRandom random;
39    private GPOperatorLibrary funLibrary;
40    private List<IFunction> functions;
41
42    private List<IFunction> terminals;
43    internal IList<IFunction> Terminals {
44      get { return terminals; }
45    }
46
47    private List<IFunction> allFunctions;
48    internal IList<IFunction> AllFunctions {
49      get { return allFunctions; }
50    }
51
52    #region constructors
53    internal TreeGardener(IRandom random, GPOperatorLibrary funLibrary) {
54      this.random = random;
55      this.funLibrary = funLibrary;
56      this.allFunctions = new List<IFunction>();
57      terminals = new List<IFunction>();
58      functions = new List<IFunction>();
59      // init functions and terminals based on constraints
60      foreach(IFunction fun in funLibrary.Group.Operators) {
61        int maxA, minA;
62        GetMinMaxArity(fun, out minA, out maxA);
63        if(maxA == 0) {
64          terminals.Add(fun);
65          allFunctions.Add(fun);
66        } else {
67          functions.Add(fun);
68          allFunctions.Add(fun);
69        }
70      }
71    }
72    #endregion
73
74    #region random initialization
75    /// <summary>
76    /// Creates a random balanced tree with a maximal size and height. When the max-height or max-size are 1 it will return a random terminal.
77    /// In other cases it will return either a terminal (tree of size 1) or any other tree with a function in it's root (at least height 2).
78    /// </summary>
79    /// <param name="maxTreeSize">Maximal size of the tree (number of nodes).</param>
80    /// <param name="maxTreeHeight">Maximal height of the tree.</param>
81    /// <returns></returns>
82    internal IFunctionTree CreateBalancedRandomTree(int maxTreeSize, int maxTreeHeight) {
83      IFunctionTree root = CreateRandomRoot(maxTreeSize, maxTreeHeight);
84      MakeBalancedTree(root, maxTreeSize - 1, maxTreeHeight - 1);
85      return root;
86    }
87
88    /// <summary>
89    /// Creates a random (unbalanced) tree with a maximal size and height. When the max-height or max-size are 1 it will return a random terminal.
90    /// In other cases it will return either a terminal (tree of size 1) or any other tree with a function in it's root (at least height 2).
91    /// </summary>
92    /// <param name="maxTreeSize">Maximal size of the tree (number of nodes).</param>
93    /// <param name="maxTreeHeight">Maximal height of the tree.</param>
94    /// <returns></returns>
95    internal IFunctionTree CreateUnbalancedRandomTree(int maxTreeSize, int maxTreeHeight) {
96      IFunctionTree root = CreateRandomRoot(maxTreeSize, maxTreeHeight);
97      MakeUnbalancedTree(root, maxTreeSize - 1, maxTreeHeight - 1);
98      return root;
99    }
100
101    /// <summary>
102    /// selects a random function from allowedFunctions and creates a random (unbalanced) tree with maximal size and height.
103    /// </summary>
104    /// <param name="allowedFunctions">Set of allowed functions.</param>
105    /// <param name="maxTreeSize">Maximal size of the tree (number of nodes).</param>
106    /// <param name="maxTreeHeight">Maximal height of the tree.</param>
107    /// <returns>New random unbalanced tree</returns>
108    internal IFunctionTree CreateRandomTree(ICollection<IFunction> allowedFunctions, int maxTreeSize, int maxTreeHeight) {
109      // default is non-balanced trees
110      return CreateRandomTree(allowedFunctions, maxTreeSize, maxTreeHeight, false);
111    }
112
113    /// <summary>
114    /// Selects a random function from allowedFunctions and creates a (un)balanced random tree with maximal size and height.
115    /// Max-size and max-height are not accepted as hard constraints, if all functions in the set of allowed functions would
116    /// lead to a bigger tree then the limits are automatically extended to guarantee that we can build a tree.
117    /// </summary>
118    /// <param name="allowedFunctions">Set of allowed functions.</param>
119    /// <param name="maxTreeSize">Maximal size of the tree (number of nodes).</param>
120    /// <param name="maxTreeHeight">Maximal height of the tree.</param>
121    /// <param name="balanceTrees">Flag determining whether the tree should be balanced or not.</param>
122    /// <returns>New random tree</returns>
123    internal IFunctionTree CreateRandomTree(ICollection<IFunction> allowedFunctions, int maxTreeSize, int maxTreeHeight, bool balanceTrees) {
124      // get the minimal needed height based on allowed functions and extend the max-height if necessary
125      int minTreeHeight = allowedFunctions.Select(f => ((IntData)f.GetVariable(GPOperatorLibrary.MIN_TREE_HEIGHT).Value).Data).Min();
126      if(minTreeHeight > maxTreeHeight)
127        maxTreeHeight = minTreeHeight;
128      // get the minimal needed size based on allowed functions and extend the max-size if necessary
129      int minTreeSize = allowedFunctions.Select(f => ((IntData)f.GetVariable(GPOperatorLibrary.MIN_TREE_SIZE).Value).Data).Min();
130      if(minTreeSize > maxTreeSize)
131        maxTreeSize = minTreeSize;
132
133      // select a random value for the size and height
134      int treeHeight = random.Next(minTreeHeight, maxTreeHeight + 1);
135      int treeSize = random.Next(minTreeSize, maxTreeSize + 1);
136
137      // filter the set of allowed functions and select only from those that fit into the given maximal size and height limits
138      IFunction[] possibleFunctions = allowedFunctions.Where(f => ((IntData)f.GetVariable(GPOperatorLibrary.MIN_TREE_HEIGHT).Value).Data <= treeHeight &&
139        ((IntData)f.GetVariable(GPOperatorLibrary.MIN_TREE_SIZE).Value).Data <= treeSize).ToArray();
140      IFunction selectedFunction = RandomSelect(possibleFunctions);
141
142      // build the tree
143      IFunctionTree root = new FunctionTree(selectedFunction);
144      if(balanceTrees) {
145        MakeBalancedTree(root, maxTreeSize - 1, maxTreeHeight - 1);
146      } else {
147        MakeUnbalancedTree(root, maxTreeSize - 1, maxTreeHeight - 1);
148      }
149      return root;
150    }
151
152    internal CompositeOperation CreateInitializationOperation(ICollection<IFunctionTree> trees, IScope scope) {
153      // needed for the parameter shaking operation
154      CompositeOperation initializationOperation = new CompositeOperation();
155      Scope tempScope = new Scope("Temp. initialization scope");
156
157      var parametricTrees = trees.Where(t => t.Function.GetVariable(GPOperatorLibrary.INITIALIZATION) != null);
158      foreach(IFunctionTree tree in parametricTrees) {
159        // enqueue an initialization operation for each operator with local variables
160        IOperator initialization = (IOperator)tree.Function.GetVariable(GPOperatorLibrary.INITIALIZATION).Value;
161        Scope initScope = new Scope();
162        // copy the local variables into a temporary scope used for initialization
163        foreach(IVariable variable in tree.LocalVariables) {
164          initScope.AddVariable(variable);
165        }
166        tempScope.AddSubScope(initScope);
167        initializationOperation.AddOperation(new AtomicOperation(initialization, initScope));
168      }
169      Scope backupScope = new Scope("backup");
170      foreach(Scope subScope in scope.SubScopes) {
171        backupScope.AddSubScope(subScope);
172      }
173      scope.AddSubScope(tempScope);
174      scope.AddSubScope(backupScope);
175      // add an operation to remove the temporary scopes       
176      initializationOperation.AddOperation(new AtomicOperation(new RightReducer(), scope));
177      return initializationOperation;
178    }
179    #endregion
180
181    #region tree information gathering
182    internal int GetTreeSize(IFunctionTree tree) {
183      return 1 + tree.SubTrees.Sum(f => GetTreeSize(f));
184    }
185
186    internal int GetTreeHeight(IFunctionTree tree) {
187      if(tree.SubTrees.Count == 0) return 1;
188      return 1 + tree.SubTrees.Max(f => GetTreeHeight(f));
189    }
190
191    internal IFunctionTree GetRandomParentNode(IFunctionTree tree) {
192      List<IFunctionTree> parentNodes = new List<IFunctionTree>();
193
194      // add null for the parent of the root node
195      parentNodes.Add(null);
196
197      TreeForEach(tree, delegate(IFunctionTree possibleParentNode) {
198        if(possibleParentNode.SubTrees.Count > 0) {
199          parentNodes.Add(possibleParentNode);
200        }
201      });
202
203      return parentNodes[random.Next(parentNodes.Count)];
204    }
205
206    internal ICollection<IFunctionTree> GetAllSubTrees(IFunctionTree root) {
207      List<IFunctionTree> allTrees = new List<IFunctionTree>();
208      TreeForEach(root, t => { allTrees.Add(t); });
209      return allTrees;
210    }
211
212    /// <summary>
213    /// returns the height level of branch in the tree
214    /// if the branch == tree => 1
215    /// if branch is in the sub-trees of tree => 2
216    /// ...
217    /// if branch is not found => -1
218    /// </summary>
219    /// <param name="tree">root of the function tree to process</param>
220    /// <param name="branch">branch that is searched in the tree</param>
221    /// <returns></returns>
222    internal int GetBranchLevel(IFunctionTree tree, IFunctionTree branch) {
223      return GetBranchLevelHelper(tree, branch, 1);
224    }
225
226    // 'tail-recursive' helper
227    private int GetBranchLevelHelper(IFunctionTree tree, IFunctionTree branch, int level) {
228      if(branch == tree) return level;
229
230      foreach(IFunctionTree subTree in tree.SubTrees) {
231        int result = GetBranchLevelHelper(subTree, branch, level + 1);
232        if(result != -1) return result;
233      }
234
235      return -1;
236    }
237
238    internal bool IsValidTree(IFunctionTree tree) {
239      foreach(IConstraint constraint in tree.Function.Constraints) {
240        if(constraint is NumberOfSubOperatorsConstraint) {
241          int max = ((NumberOfSubOperatorsConstraint)constraint).MaxOperators.Data;
242          int min = ((NumberOfSubOperatorsConstraint)constraint).MinOperators.Data;
243          if(tree.SubTrees.Count < min || tree.SubTrees.Count > max)
244            return false;
245        }
246      }
247      foreach(IFunctionTree subTree in tree.SubTrees) {
248        if(!IsValidTree(subTree)) return false;
249      }
250      return true;
251    }
252
253    // returns a random branch from the specified level in the tree
254    internal IFunctionTree GetRandomBranch(IFunctionTree tree, int level) {
255      if(level == 0) return tree;
256      List<IFunctionTree> branches = GetBranchesAtLevel(tree, level);
257      return branches[random.Next(branches.Count)];
258    }
259    #endregion
260
261    #region function information (arity, allowed childs and parents)
262    internal ICollection<IFunction> GetPossibleParents(List<IFunction> list) {
263      List<IFunction> result = new List<IFunction>();
264      foreach(IFunction f in functions) {
265        if(IsPossibleParent(f, list)) {
266          result.Add(f);
267        }
268      }
269      return result;
270    }
271
272    private bool IsPossibleParent(IFunction f, List<IFunction> children) {
273      int minArity;
274      int maxArity;
275      GetMinMaxArity(f, out minArity, out maxArity);
276
277      // note: we can't assume that the operators in the children list have different types!
278
279      // when the maxArity of this function is smaller than the list of operators that
280      // should be included as sub-operators then it can't be a parent
281      if(maxArity < children.Count()) {
282        return false;
283      }
284      int nSlots = Math.Max(minArity, children.Count);
285
286      SubOperatorsConstraintAnalyser analyzer = new SubOperatorsConstraintAnalyser();
287      analyzer.AllPossibleOperators = children.Cast<IOperator>().ToArray<IOperator>();
288
289      List<HashSet<IFunction>> slotSets = new List<HashSet<IFunction>>();
290
291      // we iterate through all slots for sub-trees and calculate the set of
292      // allowed functions for this slot.
293      // we only count those slots that can hold at least one of the children that we should combine
294      for(int slot = 0; slot < nSlots; slot++) {
295        HashSet<IFunction> functionSet = new HashSet<IFunction>(analyzer.GetAllowedOperators(f, slot).Cast<IFunction>());
296        if(functionSet.Count() > 0) {
297          slotSets.Add(functionSet);
298        }
299      }
300
301      // ok at the end of this operation we know how many slots of the parent can actually
302      // hold one of our children.
303      // if the number of slots is smaller than the number of children we can be sure that
304      // we can never combine all children as sub-trees of the function and thus the function
305      // can't be a parent.
306      if(slotSets.Count() < children.Count()) {
307        return false;
308      }
309
310      // finally we sort the sets by size and beginning from the first set select one
311      // function for the slot and thus remove it as possible sub-tree from the remaining sets.
312      // when we can successfully assign all available children to a slot the function is a valid parent
313      // when only a subset of all children can be assigned to slots the function is no valid parent
314      slotSets.Sort((p, q) => p.Count() - q.Count());
315
316      int assignments = 0;
317      for(int i = 0; i < slotSets.Count() - 1; i++) {
318        if(slotSets[i].Count > 0) {
319          IFunction selected = slotSets[i].ElementAt(0);
320          assignments++;
321          for(int j = i + 1; j < slotSets.Count(); j++) {
322            slotSets[j].Remove(selected);
323          }
324        }
325      }
326
327      // sanity check
328      if(assignments > children.Count) throw new InvalidProgramException();
329      return assignments == children.Count - 1;
330    }
331    internal IList<IFunction> GetAllowedParents(IFunction child, int childIndex) {
332      List<IFunction> parents = new List<IFunction>();
333      foreach(IFunction function in functions) {
334        ICollection<IFunction> allowedSubFunctions = GetAllowedSubFunctions(function, childIndex);
335        if(allowedSubFunctions.Contains(child)) {
336          parents.Add(function);
337        }
338      }
339      return parents;
340    }
341    internal bool IsTerminal(IFunction f) {
342      int minArity;
343      int maxArity;
344      GetMinMaxArity(f, out minArity, out maxArity);
345      return minArity == 0 && maxArity == 0;
346    }
347    internal IList<IFunction> GetAllowedSubFunctions(IFunction f, int index) {
348      if(f == null) {
349        return allFunctions;
350      } else {
351        ItemList slotList = (ItemList)f.GetVariable(GPOperatorLibrary.ALLOWED_SUBOPERATORS).Value;
352        List<IFunction> result = new List<IFunction>();
353        foreach(IFunction function in (ItemList)slotList[index]) {
354          result.Add(function);
355        }
356        return result;
357      }
358    }
359    internal void GetMinMaxArity(IFunction f, out int minArity, out int maxArity) {
360      foreach(IConstraint constraint in f.Constraints) {
361        NumberOfSubOperatorsConstraint theConstraint = constraint as NumberOfSubOperatorsConstraint;
362        if(theConstraint != null) {
363          minArity = theConstraint.MinOperators.Data;
364          maxArity = theConstraint.MaxOperators.Data;
365          return;
366        }
367      }
368      // the default arity is 2
369      minArity = 2;
370      maxArity = 2;
371    }
372    #endregion
373
374    #region private utility methods
375    private IFunctionTree CreateRandomRoot(int maxTreeSize, int maxTreeHeight) {
376      if(maxTreeHeight == 1 || maxTreeSize == 1) {
377        IFunction selectedTerminal = RandomSelect(terminals);
378        return new FunctionTree(selectedTerminal);
379      } else {
380        IFunction[] possibleFunctions = allFunctions.Where(f => GetMinimalTreeHeight(f) <= maxTreeHeight &&
381          GetMinimalTreeSize(f) <= maxTreeSize).ToArray();
382        IFunction selectedFunction = RandomSelect(possibleFunctions);
383        return new FunctionTree(selectedFunction);
384      }
385    }
386
387    private void MakeUnbalancedTree(IFunctionTree parent, int maxTreeSize, int maxTreeHeight) {
388      if(maxTreeHeight == 0 || maxTreeSize == 0) return;
389      int minArity;
390      int maxArity;
391      GetMinMaxArity(parent.Function, out minArity, out maxArity);
392      if(maxArity >= maxTreeSize) {
393        maxArity = maxTreeSize;
394      }
395      int actualArity = random.Next(minArity, maxArity + 1);
396      if(actualArity > 0) {
397        int maxSubTreeSize = maxTreeSize / actualArity;
398        for(int i = 0; i < actualArity; i++) {
399          IFunction[] possibleFunctions = GetAllowedSubFunctions(parent.Function, i).Where(f => GetMinimalTreeHeight(f) <= maxTreeHeight &&
400            GetMinimalTreeSize(f) <= maxSubTreeSize).ToArray();
401          IFunction selectedFunction = RandomSelect(possibleFunctions);
402          FunctionTree newSubTree = new FunctionTree(selectedFunction);
403          MakeUnbalancedTree(newSubTree, maxSubTreeSize - 1, maxTreeHeight - 1);
404          parent.InsertSubTree(i, newSubTree);
405        }
406      }
407    }
408
409    // NOTE: this method doesn't build fully balanced trees because we have constraints on the
410    // types of possible sub-functions which can indirectly impose a limit for the depth of a given sub-tree
411    private void MakeBalancedTree(IFunctionTree parent, int maxTreeSize, int maxTreeHeight) {
412      if(maxTreeHeight == 0 || maxTreeSize == 0) return;
413      int minArity;
414      int maxArity;
415      GetMinMaxArity(parent.Function, out minArity, out maxArity);
416      if(maxArity >= maxTreeSize) {
417        maxArity = maxTreeSize;
418      }
419      int actualArity = random.Next(minArity, maxArity + 1);
420      if(actualArity > 0) {
421        int maxSubTreeSize = maxTreeSize / actualArity;
422        for(int i = 0; i < actualArity; i++) {
423          if(maxTreeHeight == 1 || maxSubTreeSize == 1) {
424            IFunction[] possibleTerminals = GetAllowedSubFunctions(parent.Function, i).Where(f => IsTerminal(f)).ToArray();
425            IFunction selectedTerminal = RandomSelect(possibleTerminals);
426            IFunctionTree newTree = new FunctionTree(selectedTerminal);
427            parent.InsertSubTree(i, newTree);
428          } else {
429            IFunction[] possibleFunctions = GetAllowedSubFunctions(parent.Function, i).Where(
430              f => GetMinimalTreeHeight(f) <= maxTreeHeight &&
431              GetMinimalTreeSize(f) <= maxSubTreeSize &&
432              !IsTerminal(f)).ToArray();
433            IFunction selectedFunction = RandomSelect(possibleFunctions);
434            FunctionTree newTree = new FunctionTree(selectedFunction);
435            parent.InsertSubTree(i, newTree);
436            MakeBalancedTree(newTree, maxSubTreeSize - 1, maxTreeHeight - 1);
437          }
438        }
439      }
440    }
441
442    private int GetMinimalTreeHeight(IOperator op) {
443      return ((IntData)op.GetVariable(GPOperatorLibrary.MIN_TREE_HEIGHT).Value).Data;
444    }
445
446    private int GetMinimalTreeSize(IOperator op) {
447      return ((IntData)op.GetVariable(GPOperatorLibrary.MIN_TREE_SIZE).Value).Data;
448    }
449
450    private void TreeForEach(IFunctionTree tree, Action<IFunctionTree> action) {
451      action(tree);
452      foreach(IFunctionTree subTree in tree.SubTrees) {
453        TreeForEach(subTree, action);
454      }
455    }
456
457    private List<IFunctionTree> GetBranchesAtLevel(IFunctionTree tree, int level) {
458      if(level == 1) return new List<IFunctionTree>(tree.SubTrees);
459
460      List<IFunctionTree> branches = new List<IFunctionTree>();
461      foreach(IFunctionTree subTree in tree.SubTrees) {
462        branches.AddRange(GetBranchesAtLevel(subTree, level - 1));
463      }
464      return branches;
465    }
466
467    private IFunction RandomSelect(IList<IFunction> functionSet) {
468      double[] accumulatedTickets = new double[functionSet.Count];
469      double ticketAccumulator = 0;
470      int i = 0;
471      // precalculate the slot-sizes
472      foreach(IFunction function in functionSet) {
473        ticketAccumulator += ((DoubleData)function.GetVariable(GPOperatorLibrary.TICKETS).Value).Data;
474        accumulatedTickets[i] = ticketAccumulator;
475        i++;
476      }
477      // throw ball
478      double r = random.NextDouble() * ticketAccumulator;
479      // find the slot that has been hit
480      for(i = 0; i < accumulatedTickets.Length; i++) {
481        if(r < accumulatedTickets[i]) return functionSet[i];
482      }
483      // sanity check
484      throw new InvalidProgramException(); // should never happen
485    }
486
487    #endregion
488
489  }
490}
Note: See TracBrowser for help on using the repository browser.