Free cookie consent management tool by TermsFeed Policy Generator

source: branches/3.0/sources/HeuristicLab.StructureIdentification/Recombination/SinglePointCrossOver.cs @ 7460

Last change on this file since 7460 was 23, checked in by gkronber, 17 years ago

changed boolean variable BalanceTrees to double BalancedTreesRate (ticket #11)

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