ECF 1.5
TreeMutShrink.cpp
1#include "../ECF_base.h"
2#include "Tree.h"
3#include "TreeMutShrink.h"
4#include <stdio.h>
5
6
7namespace Tree
8{
9
11{
12 myGenotype_->registerParameter(state, "mut.shrink", (voidP) new double(0), ECF::DOUBLE);
13}
14
15
16bool TreeMutShrink::initialize(StateP state)
17{
18 voidP sptr = myGenotype_->getParameterValue(state, "mut.shrink");
19 probability_ = *((double*)sptr.get());
20 return true;
21}
22
23
24bool TreeMutShrink::mutate(GenotypeP gene)
25{
26 Tree* tree = (Tree*) (gene.get());
27
28 // try to select random node in tree which is not a terminal
29 // (it is silly to shrink just a terminal :))
30 uint chosenNode;
31 uint chosenNodeSubtreeSize;
32 uint tries = 0;
33 do {
34 chosenNode = state_->getRandomizer()->getRandomInteger((int) tree->size());
35 chosenNodeSubtreeSize = tree->at(chosenNode)->size_;
36 tries++;
37 } while(chosenNodeSubtreeSize == 1 && tries < 4);
38
39 if(chosenNodeSubtreeSize == 1) {
40 ECF_LOG(state_, 5, "TreeMutShrink not successful.");
41 return false;
42 }
43
44 // first of all, make a copy and clear the original
45 Tree* copyTree = tree->copy();
46 tree->clear();
47
48 std::stringstream log;
49 log << "TreeMutShrink successful (";
50
51 uint i = 0;
52
53 // copy all nodes before chosen subtree to original
54 for( ; i < chosenNode; i++) {
55 NodeP node = static_cast<NodeP> (new Node(copyTree->at(i)->primitive_));
56 tree->addNode(node);
57 }
58
59 log << "shrinkedSubtree = ";
60 for( ; i < chosenNode + chosenNodeSubtreeSize; i++) {
61 // these nodes are skipped because they are elements of the chosen subtree
62 log << copyTree->at(i)->primitive_->getName() << " ";
63 }
64
65 // chosen subtree is shrinked to a random terminal
66 Node* node = new Node;
67 node->setPrimitive(copyTree->primitiveSet_->getRandomTerminal());
68 tree->addNode(node);
69 log << ", shrinkedTo = " << node->primitive_->getName() << ")";
70
71 // copy all nodes after chosen subtree to original
72 for( ; i < copyTree->size(); i++) {
73 NodeP node = static_cast<NodeP> (new Node(copyTree->at(i)->primitive_));
74 tree->addNode(node);
75 }
76
77 tree->update();
78 delete copyTree;
79
80 ECF_LOG(state_, 5, log.str());
81
82 return true;
83}
84
85}
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
Node base class (Tree genotype)
Definition: Node.h:20
Tree class - implements genotype as a tree.
Definition: Tree_c.h:29
bool initialize(StateP)
Initialize mutation operator. Called before first mutation operation.
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!
Definition: nodes.h:92