Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.StructureIdentification/Recombination/SinglePointCrossOver.cs @ 2

Last change on this file since 2 was 2, checked in by swagner, 17 years ago

Added HeuristicLab 3.0 sources from former SVN repository at revision 52

File size: 12.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.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("BalanceTrees", "Determines if the trees should be balanced", typeof(BoolData), VariableKind.In));
47      AddVariableInfo(new VariableInfo("OperatorTree", "The tree to mutate", typeof(IOperator), VariableKind.In));
48      AddVariableInfo(new VariableInfo("TreeSize", "The size (number of nodes) of the tree", typeof(IntData), VariableKind.In));
49      AddVariableInfo(new VariableInfo("TreeHeight", "The height of the tree", typeof(IntData), VariableKind.In));
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<IOperator> newOperators;
84      IOperator newTree = Cross(gardener, parent1, parent2,
85        random, maxTreeSize, maxTreeHeight, out newOperators);
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 Variable("OperatorTree", newTree));
94      child.AddVariable(new Variable("TreeSize", new IntData(newTreeSize)));
95      child.AddVariable(new 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
103
104      return gardener.CreateInitializationOperation(newOperators, child);
105    }
106
107
108    private IOperator Cross(TreeGardener gardener, IScope f, IScope g, MersenneTwister random, int maxTreeSize, int maxTreeHeight, out List<IOperator> newOperators) {
109      IOperator tree0 = f.GetVariableValue<IOperator>("OperatorTree", false);
110      int tree0Height = f.GetVariableValue<IntData>("TreeHeight", false).Data;
111      int tree0Size = f.GetVariableValue<IntData>("TreeSize", false).Data;
112
113      IOperator tree1 = g.GetVariableValue<IOperator>("OperatorTree", false);
114      int tree1Height = g.GetVariableValue<IntData>("TreeHeight", false).Data;
115      int tree1Size = g.GetVariableValue<IntData>("TreeSize", false).Data;
116
117      if(tree0Size == 1 && tree1Size == 1) {
118        return CombineTerminals(gardener, tree0, tree1, random, maxTreeHeight, out newOperators);
119      } else {
120        // we are going to insert tree1 into tree0 at a random place so we have to make sure that tree0 is not a terminal
121        // in case both trees are higher than 1 we swap the trees with probability 50%
122        if(tree0Height == 1 || (tree1Height > 1 && random.Next(2) == 0)) {
123          IOperator tmp = tree0; tree0 = tree1; tree1 = tmp;
124          int tmpHeight = tree0Height; tree0Height = tree1Height; tree1Height = tmpHeight;
125          int tmpSize = tree0Size; tree0Size = tree1Size; tree1Size = tmpSize;
126        }
127
128        // save the root because later on we change tree0 and tree1 while searching a valid tree configuration
129        IOperator root = tree0;
130        int rootSize = tree0Size;
131
132        // select a random suboperators of the two trees at a random level
133        int tree0Level = random.Next(tree0Height - 1); // since we checked before that the height of tree0 is > 1 this is OK
134        int tree1Level = random.Next(tree1Height);
135        tree0 = gardener.GetRandomNode(tree0, tree0Level);
136        tree1 = gardener.GetRandomNode(tree1, tree1Level);
137
138        // recalculate the size and height of tree1 (the one that we want to insert) because we need to check constraints later on
139        tree1Size = gardener.GetTreeSize(tree1);
140        tree1Height = gardener.GetTreeHeight(tree1);
141
142        List<int> possibleChildIndices = new List<int>();
143        TreeGardener.OperatorEqualityComparer comparer = new TreeGardener.OperatorEqualityComparer();
144
145        // Now tree0 is supposed to take tree1 as one if its children. If this is not possible,
146        // then go down in either of the two trees as far as possible. If even then it is not possible
147        // to merge the trees then throw an exception
148        // find the list of allowed indices (regarding allowed sub-operators, maxTreeSize and maxTreeHeight)
149        for(int i = 0; i < tree0.SubOperators.Count; i++) {
150          int subOperatorSize = gardener.GetTreeSize(tree0.SubOperators[i]);
151
152          // the index is ok when the operator is allowed as sub-operator and we don't violate the maxSize and maxHeight constraints
153          if(GetAllowedOperators(tree0, i).Contains(tree1, comparer) &&
154            rootSize - subOperatorSize + tree1Size < maxTreeSize &&
155            tree0Level + tree1Height < maxTreeHeight) {
156            possibleChildIndices.Add(i);
157          }
158        }
159
160        while(possibleChildIndices.Count == 0) {
161          // ok we couln't find a possible configuration given the current tree0 and tree1
162          // possible reasons for this are:
163          //  - tree1 is not allowed as sub-operator of tree0
164          //  - appending tree1 as child of tree0 would create a tree that exceedes the maxTreeHeight
165          //  - replacing any child of tree0 with tree1 woulde create a tree that exceedes the maxTeeSize
166          // thus we have to either:
167          //  - go up in tree0 => the insert position allows larger trees
168          //  - go down in tree1 => the tree that is inserted becomes smaller
169          //  - however we have to get lucky to solve the 'allowed sub-operators' problem
170          if(tree1Height == 1 || (tree0Level>0 && random.Next(2) == 0)) {
171            // go up in tree0
172            tree0Level--;
173            tree0 = gardener.GetRandomNode(root, tree0Level);
174          } else if(tree1.SubOperators.Count > 0) {
175            // go down in node2:
176            tree1 = tree1.SubOperators[random.Next(tree1.SubOperators.Count)];
177            tree1Size = gardener.GetTreeSize(tree1);
178            tree1Height = gardener.GetTreeHeight(tree1);
179          } else {
180            // could neither go up or down ... don't know what to do ... give up
181            throw new InvalidProgramException();
182          }
183
184          // recalculate the list of possible indices
185          possibleChildIndices.Clear();
186          for(int i = 0; i < tree0.SubOperators.Count; i++) {
187            int subOperatorSize = gardener.GetTreeSize(tree0.SubOperators[i]);
188
189            // when the operator is allowed as sub-operator and we don't violate the maxSize and maxHeight constraints
190            // the index is ok
191            if(GetAllowedOperators(tree0, i).Contains(tree1, comparer) &&
192              rootSize - subOperatorSize + tree1Size < maxTreeSize &&
193              tree0Level + tree1Height < maxTreeHeight) {
194              possibleChildIndices.Add(i);
195            }
196          }
197        }
198
199        // no possible configuration found this indicates that there is a bigger problem
200        if(possibleChildIndices.Count == 0) {
201          throw new InvalidProgramException();
202        }
203
204        // replace the existing sub-tree at a random index in tree0 with tree1
205        int selectedIndex = possibleChildIndices[random.Next(possibleChildIndices.Count)];
206        tree0.RemoveSubOperator(selectedIndex);
207        tree0.AddSubOperator(tree1, selectedIndex);
208
209        // no new operators where needed
210        newOperators = new List<IOperator>();
211        return root;
212      }
213    }
214
215    private ICollection<IOperator> GetAllowedOperators(IOperator tree0, int i) {
216      ItemList slotList = (ItemList)tree0.GetVariable(GPOperatorLibrary.ALLOWED_SUBOPERATORS).Value;
217      return ((ItemList)slotList[i]).OfType<IOperator>().ToArray();
218    }
219
220    private IOperator CombineTerminals(TreeGardener gardener, IOperator f, IOperator g, MersenneTwister random, int maxTreeHeight, out List<IOperator> newOperators) {
221      newOperators = new List<IOperator>();
222      ICollection<IOperator> possibleParents = gardener.GetPossibleParents(new List<IOperator>() { f, g });
223      if(possibleParents.Count == 0) throw new InvalidProgramException();
224
225      IOperator parent = (IOperator)possibleParents.ElementAt(random.Next(possibleParents.Count())).Clone();
226
227      int minArity;
228      int maxArity;
229      gardener.GetMinMaxArity(parent, out minArity, out maxArity);
230
231      int nSlots = Math.Max(2, minArity);
232
233      HashSet<IOperator>[] slotSets = new HashSet<IOperator>[nSlots];
234
235      SubOperatorsConstraintAnalyser analyser = new SubOperatorsConstraintAnalyser();
236      analyser.AllPossibleOperators = new List<IOperator>() { g, f };
237      for(int slot = 0; slot < nSlots; slot++) {
238        HashSet<IOperator> slotSet = new HashSet<IOperator>(analyser.GetAllowedOperators(parent, slot));
239        slotSets[slot] = slotSet;
240      }
241
242      int[] slotSequence = Enumerable.Range(0, slotSets.Count()).OrderBy(slot => slotSets[slot].Count()).ToArray();
243
244      IOperator[] selectedOperators = new IOperator[nSlots];
245      for(int i = 0; i < slotSequence.Length; i++) {
246        int slot = slotSequence[i];
247        HashSet<IOperator> slotSet = slotSets[slot];
248        if(slotSet.Count() == 0) {
249          var allowedOperators = GetAllowedOperators(parent, slot);
250          selectedOperators[slot] = gardener.CreateRandomTree(allowedOperators, 1, 1, true);
251          newOperators.AddRange(gardener.GetAllOperators(selectedOperators[slot]));
252        } else {
253          IOperator selectedOperator = slotSet.ElementAt(random.Next(slotSet.Count()));
254          selectedOperators[slot] = selectedOperator;
255          for(int j = i + 1; j < slotSequence.Length; j++) {
256            int otherSlot = slotSequence[j];
257            slotSets[otherSlot].Remove(selectedOperator);
258          }
259        }
260      }
261
262      for(int i = 0; i < selectedOperators.Length; i++) {
263        parent.AddSubOperator(selectedOperators[i], i);
264      }
265
266      return parent;
267    }
268  }
269}
Note: See TracBrowser for help on using the repository browser.