bool scoutBeesPhase(StateP state, DemeP deme){ IndividualP unimproved ; double maxTrial = 0; for( uint i = 0; i < deme->getSize(); i++ ) { // for each food source IndividualP food = deme->at(i); //get food source's trial variable FloatingPointP flp = boost::dynamic_pointer_cast<FloatingPoint::FloatingPoint> (food->getGenotype(1)); double &trial = flp->realValue[0]; //remember the source if its trial exceeded limit if (trial > limit && trial >maxTrial){ unimproved = food; maxTrial = trial; } } //if there is a food source that exceeded the limit, replace it with a random one if (unimproved != NULL){ FloatingPointP flp = boost::dynamic_pointer_cast<FloatingPoint::FloatingPoint> (unimproved->getGenotype(1)); double &trial = flp->realValue[0]; trial = 0; flp = boost::dynamic_pointer_cast<FloatingPoint::FloatingPoint> (unimproved->getGenotype(0)); flp->initialize(state); evaluate(unimproved); } return true; }
//! create donor vectors (the same number as the population size) void DifferentialEvolution::createDonorVectors(DemeP deme, StateP state) { IndividualP ind1, ind2, ind3; // select three different population members ind1 = selRandomOp->select(*deme); ind2 = selRandomOp->select(*deme); while (ind1->index == ind2->index) ind2 = selRandomOp->select(*deme); ind3 = selRandomOp->select(*deme); while (ind1->index == ind3->index || ind2->index == ind3->index) ind3 = selRandomOp->select(*deme); // get their genotypes FloatingPoint::FloatingPoint* flp1 = (FloatingPoint::FloatingPoint*) (ind1->getGenotype().get()); FloatingPoint::FloatingPoint* flp2 = (FloatingPoint::FloatingPoint*) (ind2->getGenotype().get()); FloatingPoint::FloatingPoint* flp3 = (FloatingPoint::FloatingPoint*) (ind3->getGenotype().get()); // create new individual to contain new donor vector IndividualP v (new Individual(state)); FloatingPoint::FloatingPoint* b = (FloatingPoint::FloatingPoint*) v->getGenotype().get(); double donor_value; // calculate new donor vector elements for(uint i = 0; i < flp2->realValue.size(); i++){ donor_value = flp1->realValue[i] + Fconst_ * (flp2->realValue[i] - flp3->realValue[i]); b->realValue[i] = donor_value; } donor_vector.push_back(v); }
bool birthPhase(StateP state, DemeP deme, std::vector<IndividualP> &clones) { //number of new antibodies (randomly created) uint birthNumber = deme->getSize() - clones.size(); //if no new antibodies are needed, return (this if part is optional, code works fine w/o it) if (birthNumber == 0) return true; IndividualP newAntibody = copy(deme->at(0)); FloatingPointP flp = boost::dynamic_pointer_cast<FloatingPoint::FloatingPoint> (newAntibody->getGenotype(0)); for (uint i = 0; i<birthNumber; i++){ //create a random antibody flp->initialize(state); evaluate(newAntibody); //reset its age flp = boost::dynamic_pointer_cast<FloatingPoint::FloatingPoint> (newAntibody->getGenotype(1)); double &age = flp->realValue[0]; age = 0; //add it to the clones vector clones.push_back(copy(newAntibody)); } return true; }
bool agingPhase(StateP state, DemeP deme, std::vector<IndividualP> &clones) { //sort std::sort (clones.begin(), clones.end(), sortPopulationByFitness); std::vector<IndividualP> temp_clones; for (uint i = 0; i < clones.size(); i++){// for each antibody IndividualP antibody = clones.at(i); //age each antibody FloatingPointP flp = boost::dynamic_pointer_cast<FloatingPoint::FloatingPoint> (antibody->getGenotype(1)); double &age = flp->realValue[0]; age += 1; // static aging: if an antibody exceeds tauB number of trials, it is replaced with a new randomly created antibody if (age <=tauB) temp_clones.push_back(antibody); // if elitism = true , preserve the best antibody regardless of its age else if (elitism == "true" && i == 0) temp_clones.push_back(antibody); } clones = temp_clones; return true; }
FitnessP SymbRegEvalOp::evaluate(IndividualP individual) { // stvaranje zeljenog Fintess objekta: FitnessP fitness = static_cast<FitnessP> (new FitnessMin); // dohvat genotipa jedinke TreeP tree = boost::dynamic_pointer_cast<Tree::Tree> (individual->getGenotype()); //Tree* tree = (Tree*) individual->at(0).get(); double value = 0; for(uint i = 0; i < nSamples; i++) { tree->setTerminalValue("X", &domain[i]); /* for(uint term = 0; term < tree->primitiveSet_->terminalSet.size(); term++) tree->primitiveSet_->terminalSet[term]->value = domain[i]; */ double result; tree->execute(&result); value += fabs(codomain[i] - result); } fitness->setValue(value); // primjer koristenja vlastitog tipa podatka za terminale //my_type x; //x.b = true; //x.v = false; //tree->setTerminalValue("term", &x); //tree->execute(&x); //fitness->setValue(x.v); return fitness; }
bool hypermutationPhase(StateP state, DemeP deme, std::vector<IndividualP> &clones) { uint M; // M - number of mutations of a single antibody uint k; //sort std::sort (clones.begin(), clones.end(), sortPopulationByFitness); for( uint i = 0; i < clones.size(); i++ ){ // for each antibody in vector clones IndividualP antibody = clones.at(i); FloatingPointP flp = boost::dynamic_pointer_cast<FloatingPoint::FloatingPoint> (antibody->getGenotype(0)); std::vector< double > &antibodyVars = flp->realValue; k = 1 + i/(dup+1); M =(int) ((1- 1/(double)(k)) * (c*dimension) + (c*dimension)); // mutate M times for (uint j = 0; j < M; j++){ uint param = state->getRandomizer()->getRandomInteger((int)antibodyVars.size()); double randDouble1 = state->getRandomizer()->getRandomDouble(); double randDouble2 = state->getRandomizer()->getRandomDouble(); double value = antibodyVars[param] + (1-2*randDouble1)* 0.2 * (ubound - lbound) * pow(2, -16*randDouble2 ); if (value > ubound) value = ubound; else if (value <lbound) value = lbound; //produce a mutation on the antibody antibodyVars[param] = value; } FitnessP parentFitness = antibody->fitness; evaluate(antibody); // if the clone is better than its parent, reset clone's age if(antibody-> fitness->isBetterThan(parentFitness)){ flp = boost::dynamic_pointer_cast<FloatingPoint::FloatingPoint> (antibody->getGenotype(1)); double &age = flp->realValue[0]; age = 0; } } return true; }
FitnessP ModularRobotEvalOp::evaluate(IndividualP individual) { //-- Create a fitness object to maximize the objective (distance travelled in m) FitnessP fitness (new FitnessMax); //-- We get the genotype: FloatingPoint::FloatingPoint* genotype = (FloatingPoint::FloatingPoint*) individual->getGenotype(0).get(); //-- Value to store the fitness (distance travelled) double fitness_value = 0; //-- Here we record the genotypes on a gait table file: std::cout << "[Evolve] Convert to gait table!" << std::endl; genotypeToRobot( genotype ); //-- Reset the robot: std::cout << "[Evolve] Reset!" << std::endl; robotInterface->reset(); //-- Run the robot: std::cout << "[Evolve] Run!" << std::endl; //-- Here you put the main loop unsigned long elapsed_time = 0; //-- Should be in uS unsigned long max_time_us = max_runtime*1000; joint_values.clear(); for (int i = 0; i < (int) n_modules; i++) joint_values.push_back(0); while( elapsed_time < max_time_us ) { //-- Update joint values for ( int i = 0; i < (int) oscillators.size(); i++) joint_values[i] = oscillators[i]->calculatePos(elapsed_time); //-- Send joint values robotInterface->sendJointValues(joint_values, timestep); elapsed_time+=(unsigned long) (timestep*1000); //std::cout << "[Evolve] Time: " << elapsed_time << "us" << std::endl; } //-- Select the fitness value (distance travelled in m) fitness_value = robotInterface->getTravelledDistance(); //-- Set the fitness value fitness->setValue( fitness_value); std::cout << "[Evolve] Return!" << std::endl; return fitness; }
// fitness funkcija se brine za postavljanje čvorova koji su prije inicijalizirani // fitnessInc treba biti implementiran za povećavanje fitnessa FitnessP RegEvalOp::evaluate(IndividualP individual) { FitnessP fitness(new FitnessMax); Tree::Tree *tree = (Tree::Tree *) individual->getGenotype(0).get(); double value = fitnessEvaluation(domain, codomain, tree); fitness->setValue(value); value = fitnessEvaluation(testDomain, testCodomain, tree); testValues[individual->index] = value; return fitness; }
FitnessP CgdaPaintFitnessFunction::evaluate(IndividualP individual) { // Evaluation creates a new fitness object using a smart pointer // in our case, we try to minimize the function value, so we use FitnessMin fitness (for minimization problems) FitnessP fitness (new FitnessMin); // we define FloatingPoint as the only genotype (in the configuration file) FloatingPoint::FloatingPoint* gen = (FloatingPoint::FloatingPoint*) individual->getGenotype().get(); // we implement the fitness function 'as is', without any translation // the number of variables is read from the genotype itself (size of 'realValue' vactor) double value =0; value= getCustomFitness(gen->realValue); fitness->setValue(value); return fitness; }
FitnessP GAFitnessEvalOp::evaluate(IndividualP individual) { FitnessP fitness = static_cast<FitnessP> (new FitnessMin); double value = infinitePrice; BinaryP bin = boost::dynamic_pointer_cast<Binary> (individual->getGenotype()); if(selector_.isInProgress()) { selector_.clearSelection(); for(uint i = 0; i < bin->realValue.size(); ++i) { // int intVal = (int) bin->realValue.at(i); // if(intVal < 0) intVal = 0; int intVal = getSelectCount(bin, i, ubound_); // debugFitnessElements(bin->realValue.at(i), ubound_, // selector_.getInitialSelectLimit(selector_.getOffer(i)), intVal); selector_.selectOffer(selector_.getOffer(i), intVal); } if(selector_.isCurrentSelectionFeasible()) { value = selector_.selection().getTotalPrice(); selector_.updateBestSelection(selector_.selection()); } else { const int C = 100; int flow = selector_.calcMaxFlow(); int total = selector_.total_disj_req_quantity(); value = selector_.worst_acceptable_price()+1 + C*(total*total - flow*flow); double d = 0; for(uint i = 0; i < bin->realValue.size(); ++i) { const PurchasableOffer& offer = selector_.getOffer(i); // d += pow(selector_.selection().getOfferCount(offer), 2.0); d += pow(selector_.getInitialSelectLimit(offer) -selector_.selection().getOfferCount(offer), 2.0); } value += C - log(1+d); } } fitness->setValue(value); return fitness; }
/** * \brief Mutate an individual. * * May mutate one or more genotypes in given individual. * Determines which MutationOp to use on each genotype. */ bool Mutation::mutate(IndividualP ind) { ind->fitness->setInvalid(); // set mutation context state_->getContext()->mutatedIndividual = ind; ECF_LOG(state_, 5, "Mutating individual: " + ind->toString()); currentInd = ind; // if mutating a random genotype if(mutateGenotypes_ == RANDOM_GENOTYPE) { uint iGenotype = state_->getRandomizer()->getRandomInteger((int)ind->size()); if(protectedGenotypes_[iGenotype]) return false; // choose operator uint iOperator; if(opProb[iGenotype][0] < 0) iOperator = state_->getRandomizer()->getRandomInteger((int)operators[iGenotype].size()); else { double random = state_->getRandomizer()->getRandomDouble(); iOperator = 0; while(opProb[iGenotype][iOperator] < random) iOperator++; } operators[iGenotype][iOperator]->mutate(ind->at(iGenotype)); } // if mutating all genotypes in the individual else if(mutateGenotypes_ == ALL_GENOTYPES) { for(uint iGenotype = 0; iGenotype < ind->size(); iGenotype++) { if(protectedGenotypes_[iGenotype]) continue; // choose operator uint iOperator; if(opProb[iGenotype][0] < 0) iOperator = state_->getRandomizer()->getRandomInteger((int)operators[iGenotype].size()); else { double random = state_->getRandomizer()->getRandomDouble(); iOperator = 0; while(opProb[iGenotype][iOperator] < random) iOperator++; } operators[iGenotype][0]->mutate(ind->at(iGenotype)); } } ECF_LOG(state_, 5, "Mutated individual: " + ind->toString()); return true; }
bool createNewFoodSource(IndividualP food, StateP state, DemeP deme) { //for each food source find a neighbour IndividualP neighbour; do{ neighbour = selRandomOp->select(*deme); }while(food->index == neighbour->index); //potential new food source IndividualP newFood = copy(food); FloatingPointP flp = boost::dynamic_pointer_cast<FloatingPoint::FloatingPoint> (food->getGenotype(0)); std::vector< double > &foodVars = flp->realValue; flp = boost::dynamic_pointer_cast<FloatingPoint::FloatingPoint> (neighbour->getGenotype(0)); std::vector< double > &neighbourVars = flp->realValue; flp = boost::dynamic_pointer_cast<FloatingPoint::FloatingPoint> (newFood->getGenotype(0)); std::vector< double > &newFoodVars = flp->realValue; uint param = state->getRandomizer()->getRandomInteger((int)foodVars.size()); double factor = state->getRandomizer()->getRandomDouble(); double value = foodVars[param] * (1-2*factor)*(foodVars[param]-neighbourVars[param]); if (value > ubound) value = ubound; else if (value <lbound) value = lbound; //produce a modification on the food source (discover a new food source) newFoodVars[param] = value; evaluate(newFood); flp = boost::dynamic_pointer_cast<FloatingPoint::FloatingPoint> (food->getGenotype(1)); double &foodTrial = flp->realValue[0]; // d) if the fitness value of the new food source is better than that of the original source, // memorize the new source, forget the old one and set trial to 0 // otherwise keep the old one and increment trial if(newFood->fitness->isBetterThan( food->fitness) ) { foodVars[param] = value; evaluate(food); foodTrial = 0; } else { foodTrial +=1; } return true; }
FitnessP MazeEnv::evaluate(IndividualP ind) { FitnessP fitness = static_cast<FitnessP> (new FitnessMax); fitness->setValue(0); int move = 0; BitStringP bstring = boost::dynamic_pointer_cast<BitString::BitString> (ind->getGenotype(1)); //TODO napravit neku metodu za pretvaranje bitstringa u int i obratno for (int i =0; i < 3; i++){ move *= 2; if (bstring->bits[i]) move += 1; } //make move only if there is no wall on target location pair<int, int> pos = makeMove(position, move); if (getLocation(pos) != MZ_WALL) { position = pos; if (changePositionEvent) changePositionEvent(pos); } return fitness; }
FitnessP Mux11EvalOp::evaluate(IndividualP individual) { // we try to minimize the function value, so we use FitnessMin fitness (for minimization problems) FitnessP fitness(new FitnessMin); // get the genotype we defined in the configuration file Tree::Tree* tree = (Tree::Tree*) individual->getGenotype().get(); // (you can also use boost smart pointers:) //TreeP tree = boost::static_pointer_cast<Tree::Tree> (individual->getGenotype()); int value = 0; for (uint a = 0; a < 8; a++) { bool a0 = a & 1; bool a1 = a & 2; bool a2 = a & 4; tree->setTerminalValue("a0", &a0); tree->setTerminalValue("a1", &a1); tree->setTerminalValue("a2", &a2); for (uint i = 0; i < 256; i++) { bool d0 = i & 1; bool d1 = i & 2; bool d2 = i & 4; bool d3 = i & 8; bool d4 = i & 16; bool d5 = i & 32; bool d6 = i & 64; bool d7 = i & 128; tree->setTerminalValue("d0", &d0); tree->setTerminalValue("d1", &d1); tree->setTerminalValue("d2", &d2); tree->setTerminalValue("d3", &d3); tree->setTerminalValue("d4", &d4); tree->setTerminalValue("d5", &d5); tree->setTerminalValue("d6", &d6); tree->setTerminalValue("d7", &d7); bool functionValue = false; switch (a) { case 0: functionValue = d0; break; case 1: functionValue = d1; break; case 2: functionValue = d2; break; case 3: functionValue = d3; break; case 4: functionValue = d4; break; case 5: functionValue = d5; break; case 6: functionValue = d6; break; case 7: functionValue = d7; break; } bool result; tree->execute(&result); int intResult = 0; if (result) { intResult = 1; } int intFunctionValue = 0; if (functionValue) { intFunctionValue = 1; } value += abs(intResult - intFunctionValue); } } //cout << tree->toString(); fitness->setValue(value); return fitness; }
bool PSOInheritance::advanceGeneration(StateP state, DemeP deme) { // a) For each particle: // 1) If the fitness value is better than the best fitness value (pBest) in history // 2) Set current value as the new pBest // 3) Put particle in the ranking array using the fitness value // End // b) For the p best particles in the ranking arrayºº // 1) Find, in the particle neighborhood, the particle with the best fitness // 2) Calculate particle velocity according to the velocity equation (1) // 3) Apply the velocity constriction // 4) Update particle position according to the position equation (2) // 5) Apply the position constriction // c) Inherit // Evaluate // 1) Get the fitness value via evaluation or inheritance. // End for( uint i = 0; i < deme->getSize(); i++ ) { // for each particle IndividualP particle = deme->at(i); //Read "i" particle // the whole point of this section is to compare fitness and pbest FloatingPointP flp = boost::dynamic_pointer_cast<FloatingPoint::FloatingPoint> (particle->getGenotype(3)); double &particlePbestFitness = flp->realValue[0]; double fitness = particle->fitness->getValue(); //There is a problem with the particlePbestFitness initialization in this algorithm. The following lines take care of this. //TODO: Find a way to do this in the ¿initialize fuction?. if(state->getGenerationNo()==1){ //std::cout<<"INCIALIZADOOOOOOOOOOOOO!!!!!!!!!!!!!!!!!"<<std::endl; particlePbestFitness=fitness; } else{ //std::cout<<"FITNESS"<<fitness<<std::endl; flp = boost::dynamic_pointer_cast<FloatingPoint::FloatingPoint> (particle->getGenotype(0)); std::vector< double > &positions = flp->realValue; flp = boost::dynamic_pointer_cast<FloatingPoint::FloatingPoint> (particle->getGenotype(2)); std::vector< double > &pbestx = flp->realValue; // set particle pbestx-es if( /*iter == 0 ||*/ fitness < particlePbestFitness ) { // minimize error particlePbestFitness = fitness; //Update particle personal fitness // set pbestx-es for( uint j = 0;j<pbestx.size();j++ ) { pbestx[j] = positions[j]; } } } // NOTE store best particle index? //std::cout<<"THE PBEST OF THIS PARTICLE IS!!!!!!!!!!!!:"<<particlePbestFitness<<std::endl; } // b) for( uint i = 0; i < deme->getSize(); i++ ) { // for each particle IndividualP particle = deme->at(i); IndividualP bestParticle = selBestOp->select( *deme ); FloatingPointP flp = boost::dynamic_pointer_cast<FloatingPoint::FloatingPoint> (particle->getGenotype(0)); std::vector< double > &positions = flp->realValue; flp = boost::dynamic_pointer_cast<FloatingPoint::FloatingPoint> (particle->getGenotype(1)); std::vector< double > &velocities = flp->realValue; flp = boost::dynamic_pointer_cast<FloatingPoint::FloatingPoint> (particle->getGenotype(2)); std::vector< double > &pbestx = flp->realValue; double R1=rand()/(float)RAND_MAX, R2=rand()/(float)RAND_MAX, vf; int C1=2, C2=2; double weight_up; switch( m_weightType ) { //time variant weight, linear from weight to 0.4 case TIME_VARIANT: weight_up = ( m_weight - 0.4 ) * ( m_maxIter - state->getGenerationNo() ) / m_maxIter + 0.4; break; // constant inertia weight case CONSTANT: default: weight_up = m_weight; break; } // calculate particle velocity according to the velocity equation (1) flp = boost::dynamic_pointer_cast<FloatingPoint::FloatingPoint> (bestParticle->getGenotype(2)); std::vector< double > &bestParticlesPbestx = flp->realValue; for( uint j = 0; j < velocities.size(); j++ ) { double velocity; velocity = weight_up * velocities[j] + 2 * R1 * (pbestx[j] - positions[j]) + 2 * R2 * (bestParticlesPbestx[j] - positions[j]); if( velocity > m_maxV ) velocity = m_maxV; if( velocity < -m_maxV) velocity = -m_maxV; velocities[j] = velocity; positions[j] += velocities[j]; //Updated positions with velocitites X(t+1)=X(t)+velocities(t); // TODO apply position constriction // check for bounds if(bounded_) { if(positions[j] < lbound_) positions[j] = lbound_; if(positions[j] > ubound_) positions[j] = ubound_; } //std::cout<<"LA VELOCIDAD ES::::"<<velocity<<std::endl; } int proportion=55; if(rand()%100>=proportion){ //Initial PSO inheritance algorithm -> 100%inheritance no evaluations. //determine new particle fitness //Particle best personal fitness // flp = boost::dynamic_pointer_cast<FloatingPoint::FloatingPoint> (particle->getGenotype(3)); // double &particlePbestFitness = flp->realValue[0]; //Best particle fitness // flp = boost::dynamic_pointer_cast<FloatingPoint::FloatingPoint> (bestParticle->getGenotype(3)); // double &bestparticlePbestFitness = flp->realValue[0]; // vf=(C1*R1*(particlePbestFitness-particle->fitness->getValue())+C2*R2*(bestparticlePbestFitness-particle->fitness->getValue())) // /(1+C1*R1+C2*R2); // vf=vf+particle->fitness->getValue(); evaluate( particle ); //std::cout<< " Inherited: " << vf<< " -> Evaluated "<< particle->fitness->getValue() <<std::endl ; } else{ //Particle best personal fitness flp = boost::dynamic_pointer_cast<FloatingPoint::FloatingPoint> (particle->getGenotype(3)); double &particlePbestFitness = flp->realValue[0]; //Best particle fitness flp = boost::dynamic_pointer_cast<FloatingPoint::FloatingPoint> (bestParticle->getGenotype(3)); double &bestparticlePbestFitness = flp->realValue[0]; //std::cout<<std::endl<<"The EverPersonalBEST of this particle is:"<<particlePbestFitness<<std::endl; //std::cout<<std::endl<<"THE present LEADER(Allbes) of this particle fitness is:"<<bestparticlePbestFitness<<std::endl; //Inheritance based on flight formula std::cout<<"Particle Fitness"<<particle->fitness->getValue()<<" "<<std::endl; //Fitness inheritance vf=(C1*R1*(particlePbestFitness-particle->fitness->getValue())+C2*R2*(bestparticlePbestFitness-particle->fitness->getValue())) /(1+C1*R1+C2*R2); particle->fitness->setValue(vf+particle->fitness->getValue()); std::cout<< " Inherited: " << particle->fitness->getValue()<< " "<< std::endl ; } } //std::cout<<std::endl<<"THE NUMBER OF THIS GENERATION IS:"<<state->getGenerationNo() <<std::endl; std::cout<<std::endl<<"THE NUMBER OF EVALUATIONS ARE:"<<state->getEvaluations() <<std::endl; std::cout<<std::endl<<"THE TIME TAKEN TO DO THIS IS:"<<state->getElapsedTime() <<std::endl; //*******************FILE OUTPUT FOR DEBUGGING***********************************************// IndividualP bestParticle = selBestOp->select( *deme ); FloatingPointP flp = boost::dynamic_pointer_cast<FloatingPoint::FloatingPoint> (bestParticle->getGenotype(3)); double &bestparticlePbestFitness = flp->realValue[0]; std::ofstream myfile1; myfile1.open("FitnessvsEvaluations.txt", std::ios_base::app); if (myfile1.is_open()){ myfile1<<bestparticlePbestFitness<<" "; myfile1<<state->getEvaluations()<<std::endl; } //*******************************************************************************************// return true; }