void GaTTP::nextGeneration(){ Population* nextPop = new Population; current->GenerateNewPopulation(nextPop); generation++; nextPop->CalcFitness(); if(nextPop->GetBestFitness()>=current->GetBestFitness()) { genNoImprov++; } else{ genNoImprov = 0; } delete current; current = nextPop; //bestIndividual = newPop->GetBestIndividual(); endClock = clock(); }
void WorldGenerator::genPopulation( Population& population, Level& level, PopulationGenerationRanges& ranges, float blockDimension ) { struct OpenBlock{ ushort i; ushort j; }; //Allocate space for open blocks ushort numOpens = 0; OpenBlock* opens = new OpenBlock[ level.getWidth() * level.getDepth() ]; population.clear(); //fill the array with open blocks for(ushort i = 0; i < level.getWidth(); i++){ for(ushort j = 0; j < level.getDepth(); j++){ if( level.getBlock(i, j).getCollidableType() == Level::Block::Collidable::None ){ opens[ numOpens ].i = i; opens[ numOpens ].j = j; numOpens++; } } } float popDensity = ranges.density.gen( mRand ); int popCount = static_cast<int>( static_cast<float>( numOpens ) * popDensity ) + 1; int gennedPop = 0; int attempts = 0; float halfBlockDimension = blockDimension * 0.5f; while( gennedPop < popCount ){ if( attempts > WORLD_GEN_ATTEMPTS ){ break; } //Generate a spot in the list ushort genOpen = mRand.gen( 0, numOpens ); //Spawn an entity 0 to start population.spawn( 0, XMFLOAT4( static_cast<float>( opens[ genOpen ].i ) * blockDimension + halfBlockDimension, 0.32f, static_cast<float>( opens[ genOpen ].j ) * blockDimension + halfBlockDimension, 1.0f ) ); //Remove the spot from the list numOpens--; if( genOpen < numOpens ){ for(ushort i = genOpen; i < numOpens; i++){ opens[i] = opens[i+1]; } } gennedPop++; } delete[] opens; }
Population InitialisePopulation(int populationSize, std::vector<std::vector<int>>& vehicleConfigurationParameters) { Population population; for(int i=0;i<populationSize;i++) { Individual tempInd = GetIndividual(vehicleConfigurationParameters); // Individual = std::vector<float> - vector of floats population.push_back(tempInd); } return population; }
void Merge(const Population& population) { samples.resize(children_start + population.size()); copy(population.begin(), population.end(), samples.begin()+children_start); sort(samples.begin(), samples.end()); samples.resize(capacity()); children_start = capacity(); }
void Crossover::do_crossover(Population& population) { shuffle(population.begin(), population.end(), rng); for (int index = 0; index + 1 < int(population.size()); index += 2) if (decide_to_do_crossover()) { auto crossed = do_crossover(population[index], population[index + 1]); show_crossing(crossed); } }
void Strategies::FullGenerationalReplacement( Population &pop ) { /* All adults die, all children become adults */ pop.SetAdults(pop.GetChildren()); /* Clear children */ pop.GetChildren().clear(); }
void APG::ConstraintSolver::fill_population( Population& population ) { for ( int i = population.size(); quint32(i) < m_populationSize; i++ ) { Meta::TrackList* tl = new Meta::TrackList( sample( m_domain, playlist_size() ) ); double s = m_constraintTreeRoot->satisfaction( (*tl) ); population.insert( tl, s ); } }
int main(int argc, char* argv[]) { try { ostringstream usage; usage << "Usage: simrecomb_aux <function> [args]\n"; usage << endl; usage << "Functions:\n"; usage << " simrecomb_aux txt2pop filename_in filename_out\n"; usage << " simrecomb_aux pop2txt filename_in filename_out\n"; usage << endl; usage << "Darren Kessner\n"; usage << "John Novembre Lab, UCLA\n"; string function = argc>1 ? argv[1] : ""; if (function == "txt2pop") { if (argc < 4) throw runtime_error(usage.str().c_str()); string filename_in = argv[2]; string filename_out = argv[3]; cout << "reading " << filename_in << endl << flush; ifstream is(filename_in.c_str()); if (!is) throw runtime_error(("[simrecomb_aux] Unable to open file " + filename_in).c_str()); Population p; is >> p; cout << "writing " << filename_out << endl << flush; ofstream os(filename_out.c_str(), ios::binary); p.write(os); os.close(); } else if (function == "pop2txt") { if (argc < 4) throw runtime_error(usage.str().c_str()); string filename_in = argv[2]; string filename_out = argv[3]; cout << "reading " << filename_in << endl << flush; ifstream is(filename_in.c_str(), ios::binary); if (!is) throw runtime_error(("[simrecomb_aux] Unable to open file " + filename_in).c_str()); Population p; p.read(is); cout << "writing " << filename_out << endl << flush; ofstream os(filename_out.c_str()); os << p; os.close(); } else { throw runtime_error(usage.str().c_str()); } return 0; }
void Population::removeDependentRelations(){ // std::cout << "Population::removeDependentRelations called on " << (*this); for(auto itRec = m_dependentRelations.begin(); itRec != m_dependentRelations.end(); itRec++ ){ Population* ptrOtherPop = (Population*) (itRec->ptrPopAddr); std::list<Relation>::iterator itOtherRel = itRec->itRelAddr; ptrOtherPop->removeRelation(itOtherRel); } }
void PerPointStopCriterion<TFunction>::update(const Population& population) { for (Population::Iterator it = population.begin(); it != population.end(); ++it) { typename OnePointStopCriterion<TFunction>::Ptr one_point_stop_criterion = stop_criterion_info_->getInfoById(it.point_id()); one_point_stop_criterion->update(it.point()); } }
Population* Population::GenerateRandPopulation( size_t chromosomeCount ) { Population* population = new Population(chromosomeCount); for (size_t i = 0; i < chromosomeCount; ++i) { population->AddChromosome(i, Chromosome::GenerateRandChromosome()); } return population; }
Population make_population(const Mat& oImg, const Mat& pImg, const size_t size) { Population pop; for(size_t i = 0; i < size; ++i) { std::cerr << '\r' << i; pop.push_back(Painter(oImg, pImg)); } std::cerr << std::endl; return pop; }
void Strategies::Elitism( Population &pop ) { unsigned int elitism = pop.GetElitism(); if (elitism > 0) { sort(pop.GetAdults().begin(), pop.GetAdults().end(), IndividualSort); for (unsigned int i = 0; i<elitism; i++) { pop.GetChildren().push_back(pop.GetAdults().at(i)); } } }
void Simulation::printResume(const Population &population) const { _display.basicLine("generation " + std::to_string(_currentGeneration) + "/" + std::to_string(config.simulationNumber)); _display.basicLine("Best: "); _problem->print(population.best()); _display.basicLine("Mid: "); _problem->print(population.at(config.populationSize / 2)); _display.basicLine("Worst: "); _problem->print(population.worst()); _display.newLine(); }
void MainWindow::saveMutationSample(const Population &p) { QPolygonF samples; qint16 size = p.getIndividualNum(); for( qint16 i = 0; i < size; i ++) { samples += QPointF( p.getValueAt( i ), p.getFitnessAt( i ) ); } mutation_operator_indi.append( samples ); }
int main() { srand(time(NULL)); Population population; for (int i = 0; i < POPULATION_COUNT; ++i) { Individual ind; Chromosome chromosome(targetString.size()); chromosome.randomize(); float fitness = evaluate(chromosome); ind.setChromosome(chromosome); ind.setFitness(fitness); population.addIndividual(ind); } population.sortPopulation(); std::string solution = ""; Individual bestInd; int generationCount = 0; int nth = 64; for (int i = 0; i < GENERATION_COUNT; ++i) { generationCount++; evolve(population); population.sortPopulation(); if (bestInd < population[0]) { bestInd = population[0]; } if (i % nth == 0) { std::cout << "Generation: " << generationCount << std::endl; std::cout << "Best individual: " << bestInd << std::endl; } if (bestInd.getFitness() >= 1){ break; } } std::cout << std::endl; std::cout << "Solved on generation " << generationCount << '!' << std::endl; std::cout << bestInd << std::endl << std::endl; std::cout << "Press enter to exit"; std::cin.get(); return 0; }
int RemoteMaster(GeneralGamlConfig& conf, HKYData& data) { debug_mpi("starting RemoteMaster()..."); int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); Parameters params; params.SetParams(conf, data); //the seed has already been set in SetParams above, but we need to //modify it so that all remotes are not the same rnd.set_seed((rank+1) * rnd.init_seed()); LogParams(params); Tree::alpha = params.gammaShapeBrlen; Tree::meanBrlenMuts = params.meanBrlenMuts; int nprocs; MPI_Comm_size(MPI_COMM_WORLD, &nprocs); bool poo=true; // while(poo); Population pop; pop.Setup(params, &conf, nprocs, rank); g_sw=&pop.stopwatch; g_gen = &pop.gen; //DEBUG for now all nodes will be SW debug_mpi("doing remote subtree worker"); RemoteSubtreeWorker(pop, conf); /* if (conf.method == "fde") assert(0); // RemoteFullDuplexExchange(pop, conf); //DJZ changed this 9/10/03 to avoid occasional disparity in the acutal # of sm nodes and the number of shields allocated else if (conf.method == "sm" || (conf.method == "hybrid" && rank <= (int) (conf.hybridp.nt*(nprocs-1)))){ // else if (conf.method == "sm" || (conf.method == "hybrid" && rank < conf.hybridp.nt*nprocs)){ debug_mpi("doing remote shielded migrants"); RemoteShieldedMigrants(pop, conf); } else if (conf.method == "amr" || conf.method == "hybrid") { debug_mpi("doing remote alpha male replication"); RemoteAlphaMaleReplication(pop, conf); } else { debug_mpi("ERROR: unknown method (GamlConfig::General::method): %s", conf.method.c_str()); MPI_Abort(MPI_COMM_WORLD, -1); } */ return 0; }
/* * copy numCopies copies of the n best specimen into the out population */ void GeneticPool::copyNBest(size_t n, const size_t numCopies, Population& in, Population& out) { //add the required amount of copies of the n most fittest to the supplied population while (n--) { for (size_t i = 0; i < numCopies; ++i) { Ship& t = in[(in.size() - 1) - n]; Ship clone = t.clone(); clone.isElite = true; out.push_back(clone); } } }
int main (int argc, char * argv []) { int N = std::stoi (argv [1]); int size = std::stoi (argv [2]); double m_p = std::stod (argv [3]); int alpha = std::stoi (argv [4]); Population pop (N, size, m_p/10, alpha); pop.iterate(10000); pop.saveStats (); return 0; }
void Population::tournamentSelect(Population &lastPop){ int k = 2, i, s1, s2; int size = lastPop.size(); for(i = 0; i < size; i++){ s1 = rand() % size; s2 = rand() % size; // cout << "Tournament:" << s1 << "<-->" << s2 << endl; mMembers.push_back(lastPop.getBetterOne(s1, s2)); //mMembers.push_back(lastPop.getMember(i)); } mMemberSize = size; }
bool Simulation::solve(Population &population) { bool solution = population.checkForWinner(); unsigned int p5 = config.simulationNumber / 100 * 5; for (; _currentGeneration < config.simulationNumber + 1 && solution == false; ++_currentGeneration) { population.reproduce(); solution = population.checkForWinner(); // print information about the current population each 5% of generation if (config.verbose && _currentGeneration % p5 == 0) printResume(population); } return solution; }
virtual void write(Population& population) { // Write population here typename Population::InfectiveIterator it = population.infecBegin(); while(it != population.infecEnd()) { occFile_ << it->getId() << ":" << it->getR() - it->getN() << " "; it++; } occFile_ << "\n"; }
void Run() { if (solved == false) { population3.Update(); static int generation_count = 0; std::cout << "generation" << generation_count++ << ", best answer: " << population3.GetBest() << std::endl; if (population3.best_fitness > 0.98f)solved = true; } }
void APG::ConstraintSolver::run() { if ( !m_readyToRun ) { error() << "DANGER WILL ROBINSON! A ConstraintSolver (serial no:" << m_serialNumber << ") tried to run before its QueryMaker finished!"; m_abortRequested = true; return; } if ( m_domain.empty() ) { debug() << "The QueryMaker returned no tracks"; return; } else { debug() << "Domain has" << m_domain.size() << "tracks"; } debug() << "Running ConstraintSolver" << m_serialNumber; emit totalSteps( m_maxGenerations ); // GENETIC ALGORITHM LOOP Population population; quint32 generation = 0; Meta::TrackList* best = NULL; while ( !m_abortRequested && ( generation < m_maxGenerations ) ) { quint32 s = m_constraintTreeRoot->suggestPlaylistSize(); m_suggestedPlaylistSize = (s > 0) ? s : m_suggestedPlaylistSize; fill_population( population ); best = find_best( population ); if ( population.value( best ) < m_satisfactionThreshold ) { select_population( population, best ); mutate_population( population ); generation++; emit incrementProgress(); } else { break; } } debug() << "solution at" << (void*)(best); m_solvedPlaylist = best->mid( 0 ); m_finalSatisfaction = m_constraintTreeRoot->satisfaction( m_solvedPlaylist ); /* clean up */ Population::iterator it = population.begin(); while ( it != population.end() ) { delete it.key(); it = population.erase( it ); } emit endProgressOperation( this ); }
Population make_population(size_t teamID, PopulationLayout& pl) { Population p; p.layout_ = pl; for(size_t i = 0; i < pl.size_; i++) { Ship t(teamID, pl.sl_); Brain* b = new Brain(); b->initialize(pl.bl_); b->randomize(); t.setBrain(b); p.push_back(t); } return p; }
Population Tournament::do_selection(const Population& population, const vector<float>& fitness) { Population new_population; while (new_population.size() < population.size()) { vector<int> random_indexes = sample_with_repetition(tournament_n, population.size()); float best_index = 0; for (int i = 1; i < int(random_indexes.size()); i++) if (fitness[random_indexes[i]] > fitness[random_indexes[best_index]]) best_index = i; new_population.push_back(population[random_indexes[best_index]]); } return new_population; }
Cmd::ProcessResult ColoniseSquaresCmd::Process(const Input::CmdMessage& msg, CommitSession& session) { auto& m = VerifyCastInput<const Input::CmdColoniseSquares>(msg); Population pop = m.m_moved; VERIFY_INPUT_MSG("no moves specified", !pop.IsEmpty()); VERIFY_INPUT_MSG("not enough ships", pop.GetTotal() <= GetTeam(session.GetGame()).GetUnusedColonyShips()); Moves moves = GetMoves(pop, GetSquareCounts(session.GetGame())); DoRecord(RecordPtr(new ColoniseRecord(m_colour, m_pos, moves)), session); return nullptr; }
//============================================================================== pagmo::population PagmoTypes::convertPopulation( const Population& pop, const ::pagmo::problem& pagmoProb) { pagmo::population pagmoPop(pagmoProb, pop.getSize()); for (std::size_t i = 0u; i < pagmoPop.size(); ++i) { const std::vector<double> pagmoX = convertVector(pop.getDecisionVector(i)); const std::vector<double> pagmoF = convertVector(pop.getFitnessVector(i)); pagmoPop.set_xf(i, pagmoX, pagmoF); } return pagmoPop; }
void GeneticAlgorithm::createOffspring(Population& newPopulation, bool doMutation) { Image& targetImage = *TargetImage::Instance(); Population tmpResult; while (m_population.size() > 1) { m_inputLock.lock(); if (m_population.size() <= 1) { m_inputLock.unlock(); break; } std::pair<Organism*, Organism*> couple = m_pairGenerator.removeRandomPair(m_population); m_inputLock.unlock(); Organism* child = new Organism(*couple.first, *couple.second, doMutation); double score = averagePixelDistance(targetImage, child->getPhenotype()); child->setScore(score); tmpResult.push_back(child); tmpResult.push_back(couple.first); tmpResult.push_back(couple.second); } m_outputLock.lock(); newPopulation.insert(newPopulation.end(), tmpResult.begin(), tmpResult.end()); m_outputLock.unlock(); }
int main(int argc, char* argv[]) { afout.open("out.txt"); wclock = new sf::Clock; bool record = true; bool init_selection = true; if (argc > 1) { if (strcmp(argv[1], "norecord")==0) record = false; else init_selection = false; } if (init_selection) { if (record) DeleteDirectory("arch"); int ngenerations = 100; int ngs = 2; Genome** gs = new Genome*[ngs]; gs[0] = readgenome("shipmind.mind"); gs[1] = readgenome("shipmind2.mind"); Population* pop = new Population(gs, ngs); for (int gen = 0; gen < ngenerations; gen++) { pop->calcfitness(evaluate); pop->printspecies(); if (record) pop->savegeneration(); pop->nextgen(); } return 0; } else { Genome* g1 = readgenome(argv[1]); Genome* g2 = 0; if (argc > 2) g2 = readgenome(argv[2]); else g2 = readgenome("shipmind.mind"); return openwindow(g1, g2); } }