Free cookie consent management tool by TermsFeed Policy Generator

source: branches/FunctionsAndStructIdRefactoring/HeuristicLab.StructureIdentification/Recombination/SinglePointCrossOver.cs @ 148

Last change on this file since 148 was 143, checked in by gkronber, 17 years ago

worked on #112 in the refactoring branch

File size: 13.0 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.Linq;
25using System.Text;
26using HeuristicLab.Core;
27using HeuristicLab.Operators;
28using HeuristicLab.Random;
29using HeuristicLab.Data;
30using HeuristicLab.Constraints;
31using HeuristicLab.Functions;
32
33namespace HeuristicLab.StructureIdentification {
34  public class SinglePointCrossOver : OperatorBase {
35
36    public override string Description {
37      get {
38        return "TASK";
39      }
40    }
41    public SinglePointCrossOver()
42      : base() {
43      AddVariableInfo(new VariableInfo("Random", "Pseudo random number generator", typeof(MersenneTwister), VariableKind.In));
44      AddVariableInfo(new VariableInfo("OperatorLibrary", "The operator library containing all available operators", typeof(GPOperatorLibrary), VariableKind.In));
45      AddVariableInfo(new VariableInfo("MaxTreeHeight", "The maximal allowed height of the tree", typeof(IntData), VariableKind.In));
46      AddVariableInfo(new VariableInfo("MaxTreeSize", "The maximal allowed size (number of nodes) of the tree", typeof(IntData), VariableKind.In));
47      AddVariableInfo(new VariableInfo("FunctionTree", "The tree to mutate", typeof(IFunctionTree), VariableKind.In | VariableKind.New));
48      AddVariableInfo(new VariableInfo("TreeSize", "The size (number of nodes) of the tree", typeof(IntData), VariableKind.New));
49      AddVariableInfo(new VariableInfo("TreeHeight", "The height of the tree", typeof(IntData), VariableKind.New));
50    }
51
52    public override IOperation Apply(IScope scope) {
53      MersenneTwister random = GetVariableValue<MersenneTwister>("Random", scope, true);
54      GPOperatorLibrary opLibrary = GetVariableValue<GPOperatorLibrary>("OperatorLibrary", scope, true);
55      int maxTreeHeight = GetVariableValue<IntData>("MaxTreeHeight", scope, true).Data;
56      int maxTreeSize = GetVariableValue<IntData>("MaxTreeSize", scope, true).Data;
57
58      TreeGardener gardener = new TreeGardener(random, opLibrary);
59
60      if((scope.SubScopes.Count % 2) != 0)
61        throw new InvalidOperationException("Number of parents is not even");
62
63      CompositeOperation initOperations = new CompositeOperation();
64
65      int children = scope.SubScopes.Count / 2;
66      for(int i = 0; i < children; i++) {
67        IScope parent1 = scope.SubScopes[0];
68        scope.RemoveSubScope(parent1);
69        IScope parent2 = scope.SubScopes[0];
70        scope.RemoveSubScope(parent2);
71        IScope child = new Scope(i.ToString());
72        IOperation childInitOperation = Cross(gardener, maxTreeSize, maxTreeHeight, scope, random, parent1, parent2, child);
73        initOperations.AddOperation(childInitOperation);
74        scope.AddSubScope(child);
75      }
76
77      return initOperations;
78    }
79
80
81    private IOperation Cross(TreeGardener gardener, int maxTreeSize, int maxTreeHeight,
82      IScope scope, MersenneTwister random, IScope parent1, IScope parent2, IScope child) {
83      List<IFunctionTree> newBranches;
84      IFunctionTree newTree = Cross(gardener, parent1, parent2,
85        random, maxTreeSize, maxTreeHeight, out newBranches);
86
87      if(!gardener.IsValidTree(newTree)) {
88        throw new InvalidProgramException();
89      }
90
91      int newTreeSize = gardener.GetTreeSize(newTree);
92      int newTreeHeight = gardener.GetTreeHeight(newTree);
93      child.AddVariable(new HeuristicLab.Core.Variable("FunctionTree", newTree));
94      child.AddVariable(new HeuristicLab.Core.Variable("TreeSize", new IntData(newTreeSize)));
95      child.AddVariable(new HeuristicLab.Core.Variable("TreeHeight", new IntData(newTreeHeight)));
96
97      // check if the size of the new tree is still in the allowed bounds
98      if (newTreeHeight > maxTreeHeight ||
99        newTreeSize > maxTreeSize) {
100        throw new InvalidProgramException();
101      }
102      return gardener.CreateInitializationOperation(newBranches, child);
103    }
104
105
106    private IFunctionTree Cross(TreeGardener gardener, IScope f, IScope g, MersenneTwister random, int maxTreeSize, int maxTreeHeight, out List<IFunctionTree> newBranches) {
107      IFunctionTree tree0 = f.GetVariableValue<IFunctionTree>("FunctionTree", false);
108      int tree0Height = f.GetVariableValue<IntData>("TreeHeight", false).Data;
109      int tree0Size = f.GetVariableValue<IntData>("TreeSize", false).Data;
110
111      IFunctionTree tree1 = g.GetVariableValue<IFunctionTree>("FunctionTree", false);
112      int tree1Height = g.GetVariableValue<IntData>("TreeHeight", false).Data;
113      int tree1Size = g.GetVariableValue<IntData>("TreeSize", false).Data;
114
115      if(tree0Size == 1 && tree1Size == 1) {
116        return CombineTerminals(gardener, tree0, tree1, random, maxTreeHeight, out newBranches);
117      } else {
118        // we are going to insert tree1 into tree0 at a random place so we have to make sure that tree0 is not a terminal
119        // in case both trees are higher than 1 we swap the trees with probability 50%
120        if(tree0Height == 1 || (tree1Height > 1 && random.Next(2) == 0)) {
121          IFunctionTree tmp = tree0; tree0 = tree1; tree1 = tmp;
122          int tmpHeight = tree0Height; tree0Height = tree1Height; tree1Height = tmpHeight;
123          int tmpSize = tree0Size; tree0Size = tree1Size; tree1Size = tmpSize;
124        }
125
126        // save the root because later on we change tree0 and tree1 while searching a valid tree configuration
127        IFunctionTree root = tree0;
128        int rootSize = tree0Size;
129
130        // select a random suboperators of the two trees at a random level
131        int tree0Level = random.Next(tree0Height - 1); // since we checked before that the height of tree0 is > 1 this is OK
132        int tree1Level = random.Next(tree1Height);
133        tree0 = gardener.GetRandomBranch(tree0, tree0Level);
134        tree1 = gardener.GetRandomBranch(tree1, tree1Level);
135
136        // recalculate the size and height of tree1 (the one that we want to insert) because we need to check constraints later on
137        tree1Size = gardener.GetTreeSize(tree1);
138        tree1Height = gardener.GetTreeHeight(tree1);
139
140        List<int> possibleChildIndices = new List<int>();
141        TreeGardener.FunctionEqualityComparer comparer = new TreeGardener.FunctionEqualityComparer();
142
143        // Now tree0 is supposed to take tree1 as one if its children. If this is not possible,
144        // then go down in either of the two trees as far as possible. If even then it is not possible
145        // to merge the trees then throw an exception
146        // find the list of allowed indices (regarding allowed sub-operators, maxTreeSize and maxTreeHeight)
147        for(int i = 0; i < tree0.SubTrees.Count; i++) {
148          int subTreeSize = gardener.GetTreeSize(tree0.SubTrees[i]);
149
150          // the index is ok when the function is allowed as sub-tree and we don't violate the maxSize and maxHeight constraints
151          if(GetAllowedOperators(tree0.Function, i).Contains(tree1.Function, comparer) &&
152            rootSize - subTreeSize + tree1Size < maxTreeSize &&
153            tree0Level + tree1Height < maxTreeHeight) {
154            possibleChildIndices.Add(i);
155          }
156        }
157
158        while(possibleChildIndices.Count == 0) {
159          // ok we couln't find a possible configuration given the current tree0 and tree1
160          // possible reasons for this are:
161          //  - tree1 is not allowed as sub-tree of tree0
162          //  - appending tree1 as child of tree0 would create a tree that exceedes the maxTreeHeight
163          //  - replacing any child of tree0 with tree1 woulde create a tree that exceedes the maxTeeSize
164          // thus we have to either:
165          //  - go up in tree0 => the insert position allows larger trees
166          //  - go down in tree1 => the tree that is inserted becomes smaller
167          //  - however we have to get lucky to solve the 'allowed sub-trees' problem
168          if(tree1Height == 1 || (tree0Level>0 && random.Next(2) == 0)) {
169            // go up in tree0
170            tree0Level--;
171            tree0 = gardener.GetRandomBranch(root, tree0Level);
172          } else if(tree1.SubTrees.Count > 0) {
173            // go down in node2:
174            tree1 = tree1.SubTrees[random.Next(tree1.SubTrees.Count)];
175            tree1Size = gardener.GetTreeSize(tree1);
176            tree1Height = gardener.GetTreeHeight(tree1);
177          } else {
178            // could neither go up or down ... don't know what to do ... give up
179            throw new InvalidProgramException();
180          }
181
182          // recalculate the list of possible indices
183          possibleChildIndices.Clear();
184          for(int i = 0; i < tree0.SubTrees.Count; i++) {
185            int subTreeSize = gardener.GetTreeSize(tree0.SubTrees[i]);
186
187            // when the function is allowed as sub-tree and we don't violate the maxSize and maxHeight constraints
188            // the index is ok
189            if(GetAllowedOperators(tree0.Function, i).Contains(tree1.Function, comparer) &&
190              rootSize - subTreeSize + tree1Size < maxTreeSize &&
191              tree0Level + tree1Height < maxTreeHeight) {
192              possibleChildIndices.Add(i);
193            }
194          }
195        }
196
197        // no possible configuration found this indicates that there is a bigger problem
198        if(possibleChildIndices.Count == 0) {
199          throw new InvalidProgramException();
200        }
201
202        // replace the existing sub-tree at a random index in tree0 with tree1
203        int selectedIndex = possibleChildIndices[random.Next(possibleChildIndices.Count)];
204        tree0.RemoveSubTree(selectedIndex);
205        tree0.InsertSubTree(selectedIndex, tree1);
206
207        // no new operators where needed
208        newBranches = new List<IFunctionTree>();
209        return root;
210      }
211    }
212
213    private ICollection<IFunction> GetAllowedOperators(IFunction f, int i) {
214      ItemList slotList = (ItemList)f.GetVariable(GPOperatorLibrary.ALLOWED_SUBOPERATORS).Value;
215      return ((ItemList)slotList[i]).Cast<IFunction>().ToArray();
216    }
217
218    private IFunctionTree CombineTerminals(TreeGardener gardener, IFunctionTree f, IFunctionTree g, MersenneTwister random, int maxTreeHeight, out List<IFunctionTree> newBranches) {
219      newBranches = new List<IFunctionTree>();
220      ICollection<IFunction> possibleParents = gardener.GetPossibleParents(new List<IFunction>() { f.Function, g.Function });
221      if(possibleParents.Count == 0) throw new InvalidProgramException();
222
223      IFunctionTree parent = new FunctionTree(possibleParents.ElementAt(random.Next(possibleParents.Count())));
224
225      int minArity;
226      int maxArity;
227      gardener.GetMinMaxArity(parent.Function, out minArity, out maxArity);
228
229      int nSlots = Math.Max(2, minArity);
230
231      HashSet<IFunction>[] slotSets = new HashSet<IFunction>[nSlots];
232
233      SubOperatorsConstraintAnalyser analyser = new SubOperatorsConstraintAnalyser();
234      analyser.AllPossibleOperators = new List<IOperator>() { g.Function, f.Function };
235      for(int slot = 0; slot < nSlots; slot++) {
236        HashSet<IFunction> slotSet = new HashSet<IFunction>(analyser.GetAllowedOperators(parent.Function, slot).Cast<IFunction>());
237        slotSets[slot] = slotSet;
238      }
239
240      int[] slotSequence = Enumerable.Range(0, slotSets.Count()).OrderBy(slot => slotSets[slot].Count()).ToArray();
241
242      IFunctionTree[] selectedFunctionTrees = new IFunctionTree[nSlots];
243      for(int i = 0; i < slotSequence.Length; i++) {
244        int slot = slotSequence[i];
245        HashSet<IFunction> slotSet = slotSets[slot];
246        if(slotSet.Count() == 0) {
247          var allowedFunctions = GetAllowedOperators(parent.Function, slot);
248          selectedFunctionTrees[slot] = gardener.CreateRandomTree(allowedFunctions, 1, 1, true);
249          newBranches.AddRange(gardener.GetAllSubTrees(selectedFunctionTrees[slot]));
250        } else {
251          IFunction selectedFunction = slotSet.ElementAt(random.Next(slotSet.Count()));
252          selectedFunctionTrees[slot] = new FunctionTree(selectedFunction);
253          for(int j = i + 1; j < slotSequence.Length; j++) {
254            int otherSlot = slotSequence[j];
255            slotSets[otherSlot].Remove(selectedFunction);
256          }
257        }
258      }
259
260      for(int i = 0; i < selectedFunctionTrees.Length; i++) {
261        parent.InsertSubTree(i, selectedFunctionTrees[i]);
262      }
263
264      return parent;
265    }
266  }
267}
Note: See TracBrowser for help on using the repository browser.