• Main Page
  • Modules
  • Classes
  • Files
  • File List

D:/Projekt/ECF_trunk/ECF/tree/TreeMutShrink.cpp

00001 #include "../ECF_base.h"
00002 #include "Tree.h"
00003 #include "TreeMutShrink.h"
00004 #include <stdio.h>
00005 
00006 
00007 namespace Tree
00008 {
00009 
00010 void TreeMutShrink::registerParameters(StateP state)
00011 {
00012     myGenotype_->registerParameter(state, "mut.shrink", (voidP) new double(0), ECF::DOUBLE);
00013 }
00014 
00015 
00016 bool TreeMutShrink::initialize(StateP state)
00017 {
00018     voidP sptr = myGenotype_->getParameterValue(state, "mut.shrink");
00019     probability_ = *((double*)sptr.get());
00020     return true;
00021 }
00022 
00023 
00024 bool TreeMutShrink::mutate(GenotypeP gene)
00025 {
00026     Tree* tree = (Tree*) (gene.get());
00027 
00028     // try to select random node in tree which is not a terminal
00029     // (it is silly to shrink just a terminal :))
00030     uint chosenNode;
00031     uint chosenNodeSubtreeSize;
00032     uint tries = 0;
00033     do {
00034         chosenNode = state_->getRandomizer()->getRandomInteger((int) tree->size());
00035         chosenNodeSubtreeSize = tree->at(chosenNode)->size_;
00036         tries++;
00037     } while(chosenNodeSubtreeSize == 1 && tries < 4);
00038 
00039     if(chosenNodeSubtreeSize == 1) {
00040         ECF_LOG(state_, 5, "TreeMutShrink not successful.");
00041         return false;
00042     }
00043 
00044     // first of all, make a copy and clear the original
00045     Tree* copyTree = tree->copy();
00046     tree->clear();
00047 
00048     std::stringstream log;
00049     log << "TreeMutShrink successful (";
00050 
00051     uint i = 0;
00052 
00053     // copy all nodes before chosen subtree to original
00054     for( ; i < chosenNode; i++) {
00055         NodeP node = static_cast<NodeP> (new Node(copyTree->at(i)->primitive_));
00056         tree->addNode(node);
00057     }
00058 
00059     log << "shrinkedSubtree = ";
00060     for( ; i < chosenNode + chosenNodeSubtreeSize; i++) {
00061         // these nodes are skipped because they are elements of the chosen subtree
00062         log << copyTree->at(i)->primitive_->getName() << " ";
00063     }
00064 
00065     // chosen subtree is shrinked to a random terminal
00066     Node* node = new Node;
00067     node->setPrimitive(copyTree->primitiveSet_->getRandomTerminal());
00068     tree->addNode(node);
00069     log << ", shrinkedTo = " << node->primitive_->getName() << ")";
00070 
00071     // copy all nodes after chosen subtree to original
00072     for( ; i < copyTree->size(); i++) {
00073         NodeP node = static_cast<NodeP> (new Node(copyTree->at(i)->primitive_));
00074         tree->addNode(node);
00075     }
00076 
00077     tree->update();
00078     delete copyTree;
00079 
00080     ECF_LOG(state_, 5, log.str());
00081 
00082     return true;
00083 }
00084 
00085 }

Generated on Tue Nov 4 2014 13:04:31 for ECF by  doxygen 1.7.1