ECF 1.5
TreeMutPermutation.cpp
1#include "../ECF_base.h"
2#include "Tree.h"
3#include "TreeMutPermutation.h"
4#include <stdio.h>
5
6
7namespace Tree
8{
9
11{
12 myGenotype_->registerParameter(state, "mut.permutation", (voidP) new double(0), ECF::DOUBLE);
13}
14
15
17{
18 voidP sptr = myGenotype_->getParameterValue(state, "mut.permutation");
19 probability_ = *((double*)sptr.get());
20 return true;
21}
22
23
24bool TreeMutPermutation::mutate(GenotypeP gene)
25{
26 Tree* tree = (Tree*) (gene.get());
27
28 // try to select a node with >1 args
29 uint iNode, nArgs;
30 uint tries = 0;
31 do {
32 iNode = state_->getRandomizer()->getRandomInteger((int) tree->size());
33 tries++;
34 } while((nArgs = tree->at(iNode)->primitive_->getNumberOfArguments()) < 2 && tries < 4);
35
36 if(nArgs < 2)
37 return false;
38
39 // build permutation vector
40 std::vector<uint> permutation;
41 permutation.resize(nArgs);
42
43 for(uint i = 0; i < nArgs; i++) {
44 permutation[i] = i;
45 }
46 uint ind1, ind2, temp;
47 for(uint i = 0; i < nArgs - 1; i++) {
48 ind1 = permutation[i];
49 ind2 = state_->getRandomizer()->getRandomInteger((int) i, (int) nArgs - 1);
50 temp = permutation[ind1];
51 permutation[ind1] = permutation[ind2];
52 permutation[ind2] = temp;
53 }
54
55 // record original children node's offsets
56 std::vector<uint> offsets;
57 offsets.push_back(1);
58 for(uint i = 1; i < nArgs; i++) {
59 offsets.push_back(offsets[i - 1] + tree->at(iNode + offsets[i - 1])->size_);
60 }
61
62 // reorder mutated nodes
63 std::vector<NodeP> mutNodes;
64 mutNodes.assign(tree->begin() + iNode, tree->begin() + iNode + tree->at(iNode)->size_);
65
66 uint iCopiedTo = 1;
67 for(uint iArg = 0; iArg < nArgs; iArg++) {
68 uint nNodes = mutNodes[offsets[permutation[iArg]]]->size_;
69 for(uint i = 0; i < nNodes; i++, iCopiedTo++) {
70 tree->at(iNode + iCopiedTo) = mutNodes[offsets[permutation[iArg]] + i];
71 }
72 }
73
74 return true;
75}
76
77}
double probability_
probability of usage of this mutation operator
Definition: Mutation.h:40
GenotypeP myGenotype_
pointer to the Genotype that defines this MutationOp
Definition: Mutation.h:41
Tree class - implements genotype as a tree.
Definition: Tree_c.h:29
void registerParameters(StateP)
Register parameters with the system. Called before MutationOp::initialize.
bool mutate(GenotypeP gene)
Performs mutation of a genotype object. The genotype object must be initialized!
bool initialize(StateP)
Initialize mutation operator. Called before first mutation operation.