// contribute to lsnfe bool Chromosome::tryFlipping(int index) { int oldNFE = nfe; double oldF = getFitness(); flip(index); if (getFitness() <= oldF) { flip(index); evaluated = true; fitness = oldF; lsnfe += nfe - oldNFE; nfe = oldNFE; return false; } else { lsnfe += nfe - oldNFE; nfe = oldNFE; return true; } }
void MainWindow::ais(void){ TotalFitness = 0; ais_population.clear(); for(int i = 0; i < COUNT; i++){ float x = randomRange(MINX, MAXX); float y = randomRange(MINY, MAXY); this->ais_population.push_back({x, y, getFitness(x, y, false)}); //cout << this->population[i].fitness << endl; } //sort by fitness sort(this->ais_population.begin(), this->ais_population.end(), by_fitness()); int j = 0; while(j < COUNT){ //clone half of population vector<data> ais_newpopulation(this->ais_population.begin(),(this->ais_population.begin()+(COUNT/2))); //mutation for(int i = 0; i < (COUNT/2); i++){ float mutate = randomRange(-0.05, 0.05); if(mutate < 0) ais_newpopulation[i].fitness = ais_newpopulation[i].fitness + ((1/ais_newpopulation[i].fitness) * mutate); else ais_newpopulation[i].fitness = ais_newpopulation[i].fitness + ((1/ais_newpopulation[i].fitness) * mutate); // this->ais_population.push_back({x, y, getFitness(x, y, false)}); } for(int i = 0; i < 3; i++){ float x = randomRange(MINX, MAXX); float y = randomRange(MINY, MAXY); ais_newpopulation.push_back({x, y, getFitness(x, y, false)}); //cout << this->population[i].fitness << endl; } //merge new with old population ais_population.insert(ais_population.end(), ais_newpopulation.begin(), ais_newpopulation.end()); //sort by fitness sort(ais_population.begin(), ais_population.end(), by_fitness()); // erase unecessary elements/population: ais_population.erase(ais_population.begin()+COUNT,ais_population.end()); //best ais_best.push_back(ais_population[0].fitness); //best ais_avg.push_back(ais_population[COUNT/2].fitness); j++; TotalFitness = 0; } }
float calcolateP(Bees bees, int i) { float fitnessSummation = 0.0; int y; for (y=0; y<NUMBER_OF_EMPLOYED; y++) fitnessSummation = fitnessSummation + getFitness(bees, i); return getFitness(bees, i) / fitnessSummation; }
int rouletteWheelEmployedSelection(Bees bees) { float totalFitness = getFitness(bees, 0); int y; for (y=1; y<NUMBER_OF_EMPLOYED; y++) { totalFitness = totalFitness + getFitness(bees, y); if (chooseRandomValueBetweenRange(0.0f, 1.0f) < getFitness(bees, y) / totalFitness) return y; } return 0; }
shared_ptr<ILegalMove> FitnessBasedCheckersAI::getBestMove(const shared_ptr<const CheckersModel>& checkersModel) { auto originalLegalMoves = checkersModel->getLegalMoves(); CheckersModel simulation(*checkersModel); auto legalMoves = simulation.getLegalMoves(); vector<pair<shared_ptr<ILegalMove>, float>> legalMoveFitnessPairs; for (auto it = legalMoves.begin(); it != legalMoves.end(); it++) { pair<shared_ptr<ILegalMove>, float> currentPair; currentPair.first = *it; currentPair.second = getFitness(simulation, *it); legalMoveFitnessPairs.push_back(currentPair); } sort(legalMoveFitnessPairs.begin(), legalMoveFitnessPairs.end(), sortByFitness); auto selectedlegalMove = legalMoveFitnessPairs[0].first; for (auto it = originalLegalMoves.begin(); it != originalLegalMoves.end(); it++) { if ((*it)->getPosition() == selectedlegalMove->getPosition()) { return *it; } } return originalLegalMoves[0]; }
void Creature::toXml(QDomDocument& xml, QDomElement * parent) const { QDomElement creature = xml.createElement("Creature"); // creature.setAttribute("id", getId()); creature.setAttribute("name", QString(getName().c_str())); // creature.setAttribute("type", QString::number(getType())); creature.setAttribute("body-parts", getNumberOfBodyParts()); creature.setAttribute("constraints", getNumberOfConstraints()); creature.setAttribute("hidden-layers", getNeuralNetwork().getNumberOfLayers() - 2); creature.setAttribute("neurons-per-layer", getNeuralNetwork().getLayer(1).getNumberOfNeurons()); creature.setAttribute("initial-position", QString(( TO_STRING(getInitialPosition().x()) + " ; " + TO_STRING(getInitialPosition().y()) + " ; " + TO_STRING(getInitialPosition().z())).c_str())); creature.setAttribute("final-position", QString(( TO_STRING(getFinalPosition().x()) + " ; " + TO_STRING(getFinalPosition().y()) + " ; " + TO_STRING(getFinalPosition().z())).c_str())); creature.setAttribute("fitness", getFitness()); for (int i = 0; i < getNumberOfBodyParts(); ++i) { getBodyPart(i).toXml(xml, &creature); } for (int i = 0; i < getNumberOfConstraints(); ++i) { getConstraint(i).toXml(xml, &creature); } getNeuralNetwork().toXml(xml, &creature); if (parent) { parent->appendChild(creature); } else { xml.appendChild(creature); } }
Individual* createIndividual() { int i; Individual* ind = (Individual*) malloc(sizeof(Individual)); if (!ind) { printf("Memory allocation failed.\n"); return NULL; } ind->solution = (int *) malloc(sizeof(int) * nQueens); if (!ind->solution) { printf("Memory allocation failed.\n"); free(ind); return NULL; } for (i = 0; i < nQueens; ++i) ind->solution[i] = rand() % nQueens; getFitness(ind); return ind; }
Individual *crossover(Individual *ind1, Individual *ind2) { int i; const int crossPoint = 1 + rand() % (nQueens - 2); Individual* indTemp; indTemp = (Individual*) malloc(sizeof(Individual*)); if (!indTemp) { printf("Memory allocation failed.\n"); return NULL; } indTemp->solution = (int *) malloc(sizeof(int) * nQueens); if (!indTemp->solution) { printf("Memory allocation failed.\n"); free(indTemp); return NULL; } indTemp->fitness = 0; for (i = 0; i < nQueens; ++i) indTemp->solution[i] = ind1->solution[i]; for (i = crossPoint; i < nQueens; ++i) indTemp->solution[i] = ind2->solution[i]; getFitness(indTemp); return indTemp; }
void PsoSolver::initFitness() { #pragma omp parallel for for (int i = 0; i < particleNum; i++) { Particle &p = particles[i]; p.fitness = getFitness(p, obj); p.pBestFitness = p.fitness; } }
std::string TreeOfNodes::toString() const { std::string result = "Tree={f=" + TO_STRING(getFitness()) + ";"; if (getRoot()) { result += getRoot()->toString(); } result += "}"; return result; }
TreeOfNodes* TreeOfNodes::clone() const { TreeOfNodes* result = new TreeOfNodes(); result->setFitness(getFitness()); if (getRoot()) { result->setRoot(getRoot()->clone()); } return result; }
// get new copy of this // sub classes return their class with own values IIndividual *CBotGAValues :: copy () { IIndividual *individual = new CBotGAValues (m_theValues); individual->setFitness(getFitness()); return individual; }
void MainWindow::generatePopulations(bool isRBS){ for(int i = 0; i < COUNT; i++){ float x = randomRange(MINX, MAXX); float y = randomRange(MINY, MAXY); this->population.push_back({x, y, getFitness(x, y, isRBS)}); //cout << this->population[i].fitness << endl; } }
void TreeOfNodes::toXml(QDomDocument& xml, QDomElement* parent) { QDomElement tree = xml.createElement("TreeOfNodes"); tree.setAttribute("fitness", getFitness()); if (getRoot()) { getRoot()->toXml(xml, &tree); } if (parent) { parent->appendChild(tree); } else { xml.appendChild(tree); } }
/****************************************************************************** Function evolutionStep - controls one evolution step, is called for each generation, manages the deffirences between CGP and coevolution Takes parameters: @input - pointer to an array of all training vectors @geneticP - pointer to a struct of all CGP params @geneticArray - pointer to a vector of whole population @functions - pointer to an array of available functions @test - pointer to the test - in variant without coevolution is NULL ******************************************************************************/ void evolutionStep(TData* input, TCgpProperties* geneticP, vector<TIndividual>* geneticArray, TFuncAvailable* functions, TTest* test){ #ifdef COEVOLUTION //copy test vector from shared memory TCoevIndividual* testVect = NULL; testVect = (TCoevIndividual*)malloc(sizeof(struct test)); pthread_mutex_lock(&test->test_sem); testVect->value = new vector<int>(*test->test.value); pthread_mutex_unlock(&test->test_sem); #endif getActiveNodes(geneticArray, geneticP); for(int ind = 0; ind < geneticP->individCount; ind++){ resetFitness(&geneticArray->at(ind)); #ifdef COEVOLUTION for(int i = 0; i < geneticP->testSize; i++){ getValue(&geneticArray->at(ind), geneticP, input->data[testVect->value->at(i)]); getFitness(&geneticArray->at(ind), geneticP, input->data[testVect->value->at(i)]); }//for all tests #else for(int i = 0; i < input->dataCount; i++){ getValue(&geneticArray->at(ind), geneticP, input->data[i]); getFitness(&geneticArray->at(ind), geneticP, input->data[i]); }//for all inputs #endif }//for all individuals #ifdef COEVOLUTION //tidy up the test vector delete(testVect->value); free(testVect); #endif getParents(geneticArray, geneticP); createChildren(geneticArray, geneticP, functions); }
void PsoSolver::updateFitness() { #pragma omp parallel for for (int i = 0; i < particleNum; i++) { Particle &p = particles[i]; p.fitness = getFitness(p, obj); // update pBest if (p.fitness < p.pBestFitness) { p.pBestFitness = p.fitness; for (int d = 0; d < p.dim; d++) { p.pBest[d] = p.pos[d]; } } } // end of update particles }
Creature * Creature::clone() const { Creature* result = new Creature(getNumberOfBodyParts(), getNumberOfConstraints(), getNeuralNetwork()); for (int i = 0; i < result->getNumberOfBodyParts(); ++i) { result->setBodyPart(i, getBodyPart(i).clone()); } for (int i = 0; i < result->getNumberOfConstraints(); ++i) { result->setConstraint(i, getConstraint(i).clone()); } result->setFinalPosition(getFinalPosition()); result->setInitialPosition(getInitialPosition()); result->setFitness(getFitness()); result->setName(getName()); return result; }
void CMA_ES_Population::debugOutput() { std::fstream log; log.open(std::string(File::getBHDir()) + "/Config/Logs/CMA-ES.csv", std::fstream::app); if(log.is_open()) { auto t = std::time(nullptr); auto tm = *std::localtime(&t); log << std::put_time(&tm, "%H:%M") << ","; log << std::to_string(getFitness(0)) << ","; for(float v : configuration.initialization) log << v << ","; log << "begin_covariance,"; for(int i = 0; i < C.rows(); i++) log << C(i, i) << ","; log << std::endl; log.close(); } }
void CUDAANNMP::generation(bool print = false){ p2.copy(p); int r1,r2,r3; double ran; double nnMSE; int i,j,k; int v; #pragma omp parallel for private(v,r1,r2,r3,ran,nnMSE,i,j,k) for( v = 0 ; v < maxPopulation ; v++){ do{ r1 = unifRandInt (0,maxPopulation-1); r2 = unifRandInt (0,maxPopulation-1); r3 = unifRandInt (0,maxPopulation-1); }while(r1 == r2 || r1 == r3 || r2 == r3 || r1 == v || r2 == v || r3 == v); for( i = 1 ; i < nbLayers ; i++){ for( j = 0 ; j < neuronPerLayer[i] ; j++){ for( k = 0 ; k < neuronPerLayer[i-1]+1 ; k++){ ran = unifRand(); if(ran < crossRate){ p.pop[v]->W[i][j][k] = p2.pop[r1]->W[i][j][k] + (mutRate * (p2.pop[r3]->W[i][j][k] - p2.pop[r2]->W[i][j][k])); }else{ p.pop[v]->W[i][j][k] = p2.pop[v]->W[i][j][k]; } } } } p.pop[v]->MSE( getFitness (p.pop[v]) ); if(p.pop[v]->MSE() > p2.pop[v]->MSE() ){ for( i = 1 ; i < nbLayers ; i++){ for( j = 0 ; j < neuronPerLayer[i] ; j++){ for( k = 0 ; k < neuronPerLayer[i-1]+1 ; k++){ p.pop[v]->W[i][j][k] = p2.pop[v]->W[i][j][k]; } } } p.pop[v]->MSE(p2.pop[v]->MSE()); }//if(fitnessTrialIndividual < p.pop[v]->MSE() ) }//End for(int i = 0 ; i < maxPopulation ; i++) s.stat(p); if(print==true){ if(printBestChromosome==true){ p.pop[0]->print(); //nn[0].print(); } } vectorFitness.push_back (p.pop[0]->MSE()); }//end for
bool Solution::operator<(const Solution& rhs) const { if ((getFitness() - rhs.getFitness()) <= 0) return false; else return true; }
// Starts the algorithm with the required parameters void startGenerations(int targetNumber, uint maxGenerations, uint geneCountMin, uint geneCountMax, uint logThreshold) { bool solutionFound = false; int generation = 0; Chromosome *fittestChromosome = NULL; float bestFitness = 0; // Run the simulation until a solution has been found or the maximum number of generations has been reached for (unsigned int i = 0; !solutionFound && (maxGenerations == 0 || i < maxGenerations); ++i) { bool writeLog = logThreshold && (generation % logThreshold == 0); if (writeLog) std::cout << "Generation " << generation << '\n'; Chromosome *newChromosome = NULL; if (fittestChromosome) newChromosome = new Chromosome(*fittestChromosome); else newChromosome = new Chromosome(geneCountMin, geneCountMax); int result = 0; eval_expr(newChromosome->getSanitized(), result); if (writeLog) std::cout << "Chromosome result: " << result << '\n'; if (result != targetNumber) // Solution not yet found { float fitness = getFitness(result, targetNumber); if (writeLog) std::cout << "Chromosome fitness: " << fitness; if (fitness > bestFitness) { if (writeLog) std::cout << " -> selected\n"; if (fittestChromosome) delete fittestChromosome; fittestChromosome = newChromosome; bestFitness = fitness; } else { if (writeLog) std::cout << " -> rejected\n"; delete newChromosome; } } else // Solution found { if (fittestChromosome) delete fittestChromosome; fittestChromosome = newChromosome; solutionFound = true; } if (writeLog) std::cout << std::endl; ++generation; } std::cout << "Target number: " << targetNumber << '\n' << "Solution " << (solutionFound ? "" : "not ") << "found after " << generation << " generations" << std::endl; if (fittestChromosome) { if (solutionFound) fittestChromosome->displayInfo(); delete fittestChromosome; } }
void mutation(Individual *ind) { const int max = nQueens - 1; ind->solution[rand() % max] = rand() % max; getFitness(ind); }
//http://www.mnemstudio.org/particle-swarm-introduction.htm //http://www.swarmintelligence.org/tutorials.php void MainWindow::pso(void){ //initialize particles this->gbest = {{0, 0}, 0}; for(int i = 0; i < COUNT; i++){ float x = randomRange(MINX, MAXX); float y = randomRange(MINY, MAXY); this->particle.push_back({{x, y}, NULL}); this->lbest.push_back({{0, 0}, 0}); this->present.push_back({{0, 0}, 0}); //cout << "particle x:" << this->v[i].x << "particle y:" << this->v[i].y << endl; } // While maximum iterations or minimum error criteria is not attained int k = 0; while(k < COUNT){ for(int i = 0; i < COUNT; i++){ // Calculate Data fitness value this->present[i].fitness = getFitness(this->present[i].v.x, this->present[i].v.y, false); // If the fitness value is better than pBest // { // Set pBest = current fitness value // } if(this->present[i].fitness > lbest[i].fitness){ // cout << "change in lbest" << endl; lbest[i] = this->present[i]; } // If pBest is better than gBest // { // Set gBest = pBest // } if(lbest[i].fitness > gbest.fitness){ // cout << "change in gbest" << endl; gbest = lbest[i]; } } cout << "gbest" << gbest.fitness << endl; pso_best.push_back(gbest.fitness); //problem values obtaining is bigger than limit for(int i = 0; i < COUNT; i++){ // Calculate particle Velocity // cout << "old v.x" << v[i].x << endl; particle[i].v.x = particle[i].v.x + C1 * randomRange(0, 1) * (gbest.v.x - present[i].v.x) + C2 * randomRange(0, 1) * (lbest[i].v.x - present[i].v.x); particle[i].v.y = particle[i].v.y + C1 * randomRange(0, 1) * (gbest.v.y - present[i].v.y) + C2 * randomRange(0, 1) * (lbest[i].v.y - present[i].v.y); if(particle[i].v.x < MINX) particle[i].v.x = MINX; else if(particle[i].v.x > MAXX) particle[i].v.x = MAXX; if(particle[i].v.y < MINY) particle[i].v.y = MINY; else if(particle[i].v.y > MAXY) particle[i].v.y = MAXY; // cout << "new particle.v.x" << particle[i].v.x << "new particle.v.y" << particle[i].v.x << endl; // Use gBest and Velocity to update particle Data present[i].v.x = present[i].v.x + particle[i].v.x; present[i].v.y = present[i].v.y + particle[i].v.y; if(present[i].v.x < MINX) present[i].v.x = MINX; else if(present[i].v.x > MAXX) present[i].v.x = MAXX; if(present[i].v.y < MINY) present[i].v.y = MINY; else if(present[i].v.y > MAXY) present[i].v.y = MAXY; } k++; } }
void MainWindow::mutation(float x1, float y2, float x2, float y1, bool isRBS){ float val, fit1, fit2; fit1 = getFitness(x1, y2, isRBS); fit2 = getFitness(x2, y1, isRBS); //for x1 if(x1 > 0.2){ // val = randomRange(0, 1); // if(val > 0.2){ val = randomRange(-0.5, 0.5); if(val+x1 > MAXX) x1 = MAXX; else if(val+x1 < MINX) x1 = MINX; else x1 = val+x1; } //for y2 if(y2 > 0.2){ // val = randomRange(0, 1); // if(val > 0.2){ val = randomRange(-0.5, 0.5); if(val+y2 > MAXY) y2 = MAXY; else if(val+y2 < MINY) y2 = MINY; else y2 = val+y2; } //for x2 if(x2 > 0.2){ // val = randomRange(0, 1); // if(val > 0.2){ val = randomRange(-0.5, 0.5); if(val+x2 > MAXX) x2 = MAXX; else if(val+x2 < MINX) x2 = MINX; else x2 = val+x2; } //for y1 if(y1 > 0.2){ // val = randomRange(0, 1); // if(val > 0.2){ val = randomRange(-0.5, 0.5); if(val+y1 > MAXY) y1 = MAXY; else if(val+y1 < MINY) y1 = MINY; else y1 = val+y1; } // newpopulation.push_back({x1, y2, fit1}); // newpopulation.push_back({x2, y1, fit2}); newpopulation.push_back({x1, y2, getFitness(x1, y2, isRBS)}); newpopulation.push_back({x2, y1, getFitness(x2, y1, isRBS)}); }
double Population::getBestFitness() const { return getFitness(0); }
cinder::Surface ColorAlgoGen::operator()(const cinder::Surface& realImage) { std::vector<SurfaceWrapper> nextGenPopulation; nextGenPopulation.reserve(m_popSize); std::for_each(m_population.begin(), m_population.end(), [this, &realImage](SurfaceWrapper& s) { s.fitness = getFitness(realImage, s.image); }); std::sort(m_population.begin(), m_population.end(), [](const SurfaceWrapper& s1, const SurfaceWrapper& s2) { return s1.fitness < s2.fitness; }); unsigned int copyRatio = tools::clamp<int>( static_cast<int>(getPercent(COPY) * m_popSize), 0, m_popSize ); if (copyRatio > 0) { std::transform(m_population.begin(), m_population.begin() + copyRatio, std::back_inserter(nextGenPopulation), [&realImage, this](const SurfaceWrapper& sw) { return sw; }); } unsigned int mutateRatio = tools::clamp<int>( static_cast<int>(getPercent(MUTATE) * m_popSize), 0, m_popSize - copyRatio ); if (mutateRatio > 0) { std::transform(m_population.begin(), m_population.begin() + mutateRatio, std::back_inserter(nextGenPopulation), [&realImage, this](const SurfaceWrapper& sw) { cinder::Surface s = mutate(sw.image); return SurfaceWrapper(s, getFitness(realImage, s)); }); } unsigned int crossOverRatio = tools::clamp<int>( static_cast<int>(getPercent(CROSSOVER) * m_popSize), 0, m_popSize - copyRatio - mutateRatio ); if (crossOverRatio > 0) { std::transform(m_population.begin(), m_population.begin() + crossOverRatio, std::back_inserter(nextGenPopulation), [&realImage, this](const SurfaceWrapper& sw) { auto& pop = getPop(); cinder::Surface s = crossOver(sw.image, pop[RANDOMIZER.nextUint(pop.size())].image); return SurfaceWrapper(s, getFitness(realImage, s)); }); } unsigned int randomRatio = tools::clamp<int>( static_cast<int>(getPercent(RANDOM) * m_popSize), 0, m_popSize - copyRatio - mutateRatio - crossOverRatio ); if (nextGenPopulation.size() + randomRatio < m_popSize) { randomRatio = m_popSize - nextGenPopulation.size(); } if (randomRatio > 0) { std::transform(m_population.begin(), m_population.begin() + randomRatio, std::back_inserter(nextGenPopulation), [&realImage, this](const SurfaceWrapper& sw) { cinder::Surface s = getRandomSurface(sw.image.getWidth(), sw.image.getHeight()); return SurfaceWrapper(s, getFitness(realImage, s)); }); } std::sort(nextGenPopulation.begin(), nextGenPopulation.end(), [](const SurfaceWrapper& s1, const SurfaceWrapper& s2) { return s1.fitness < s2.fitness; }); m_population = nextGenPopulation; return m_population.front().image; }
BOOL isPerturbedFitnessBetter(Bees bees, int i, float perturbedFitness) { return getFitness(bees, i) < perturbedFitness; }
void moveOnlookerInPosition(Bees bees, int i, int selectedEmployed) { setPosition(bees, i, getPosition(bees, selectedEmployed)); setFitness(bees, i, getFitness(bees, selectedEmployed)); }