TEST(Individual, Insert){ Individual mom("07243165"); Individual Child1 = mom; Child1.insert(0, 7); Individual Child2 = mom; Child2.insert(7, 0); Individual Child3 = mom; Child3.insert(2, 5); ASSERT_EQ(Individual("72431650"), Child1); ASSERT_EQ(Individual("50724316"), Child2); ASSERT_EQ(Individual("07431265"), Child3); }
void Population::Init(unsigned int battles, unsigned int soldiers, float rf, float lf, unsigned int children_size, unsigned int adults_size, float mutation_rate, float crossover_rate, void(*selection)(Population&), void(*reproduction)(Population&), unsigned int elitism, float temperature, unsigned int tournament_size ) { /* initialize Population */ m_children_size = children_size; m_adults_size = adults_size; m_temperature = temperature; m_elitism = elitism; m_tournament_size = tournament_size; m_select = selection; m_reproduce = reproduction; m_children = std::vector<Individual>(m_children_size, Individual(battles, soldiers, rf, lf)); srand( time(0) ); m_mutation_rate=mutation_rate; m_crossover_rate=crossover_rate; for( unsigned int i = 0; i < m_children.size(); i++ ) { m_children.at(i).Init(); } }
Individual Individual::copy() { Individual individual = Individual(this->getProblem(), this->getConfig(), this->getDepot(), this->getId()); individual.setProblem(this->getProblem()); individual.setConfig(this->getConfig()); individual.setId(this->getId()); individual.setDepot(this->getDepot()); individual.setChanged(this->isChanged()); individual.setGene(this->getGene()); individual.setRoutes(this->getRoutesConst()); individual.setLocked(this->isLocked()); individual.setNumOperations(this->getNumOperations()); individual.setMutationRatePM(this->getMutationRatePM()); individual.setMutationRatePLS(this->getMutationRatePLS()); individual.setRelaxSplit(this->isRelaxSplit()); individual.setRestartMoves(this->isRestartMoves()); return individual; }
Population::Population(unsigned int children_size, unsigned int adults_size, float mutation_rate, float crossover_rate, void(*selection)(Population&), void(*reproduction)(Population&), unsigned int elitism, float temperature, unsigned int tournament_size ) { /* initialize Population */ m_children_size = children_size; m_adults_size = adults_size; m_temperature = temperature; m_elitism = elitism; m_tournament_size = tournament_size; m_select = selection; m_reproduce = reproduction; m_children = std::vector<Individual>(m_children_size, Individual()); srand( time(0) ); m_mutation_rate=mutation_rate; m_crossover_rate=crossover_rate; for( unsigned int i = 0; i < m_children.size(); i++ ) { m_children.at(i).Init(); } sum_set=false; avg_set=false; stddev_set=false; best_set=false; }
void EvolutionaryAlgorithm::initializePopulation(void) { for (int counter = 0; counter < populationSize; counter++) { currentPopulation.push_back(Individual(typesOfCoins,numberOfGenes)); currentPopulation[counter].evaluateIndividual(targetValue); } }
// [[Rcpp::export]] Rcpp::List dexp(const int& iter, const Eigen::Map<Eigen::VectorXd>& y, const Eigen::MappedSparseMatrix<double>& D, const double& alpha, const double& rho, const int& m, const bool& debug) { Individual b = Individual(y, D, alpha, rho); Individual *btf = &b; bool broken = false; // initialize matrix of posterior draws Eigen::MatrixXd beta_draws = Eigen::MatrixXd::Zero(iter, btf->n); Eigen::MatrixXd omega_draws = Eigen::MatrixXd::Zero(iter, btf->nk); Eigen::VectorXd s2_draws = Eigen::VectorXd::Zero(iter); Eigen::VectorXd lambda_draws = Eigen::VectorXd::Zero(iter); // runs sampler for (int i=0; i<iter; ++i) { if (i % m == 0) { btf->upBeta(); beta_draws.row(i) = btf->beta.transpose(); } btf->upS2(); s2_draws(i) = btf->s2; btf->upLambda2(); lambda_draws(i) = btf->l; btf->upOmega2(); omega_draws.row(i) = btf->o2.transpose(); if ( debug ) { for (int j=0; j<btf->n; ++j) { if (std::isnan(beta_draws(i,j))) { Rcpp::Rcout << "Warning: watch out dexp!, nan @ beta(" << i << "," << j << ")" << std::endl; broken = true; } } for (int j=0; j<btf->nk; ++j) { if (std::isnan(omega_draws(i,j))) { Rcpp::Rcout << "Warning: watch out dexp!, nan @ omega(" << i << "," << j << ")" << std::endl; broken = true; } } if (std::isnan(s2_draws(i)) || std::isnan(lambda_draws(i))) { Rcpp::Rcout << "Warning: watch out dexp!, nan @ s2|lambda(" << i << ")" << std::endl; broken = true; } } if (broken) break; } return Rcpp::List::create(Rcpp::Named("beta") = Rcpp::wrap(beta_draws), Rcpp::Named("s2") = s2_draws, Rcpp::Named("lambda") = lambda_draws, Rcpp::Named("omega") = omega_draws); }
Individual Individual::Reproduce(Individual &mate) { bool *mategeno = mate.GetGenotype(); if (mate.GetReproduced()) { for ( int i=0; i<m_genolength; i++ ) m_mask[i] = mate.GetMask()[i]; mate.SetReproduced(false); } else { bool meh[m_genolength]; bool mah[m_genolength]; int half=0; /* mark the different genotypes */ for ( int i = 0; i < m_genolength; i++ ) { meh[i] = m_genotype[i] && !mategeno[i]; mah[i] = !m_genotype[i] && mategeno[i]; if (meh[i]) half++; } for (int i = 0; i<m_genolength; i++) { m_mask[i]=false; } half/=2; for ( int i = 0; i < m_genolength && half!=0; i++ ) { if ( meh[i] && (rand() % 6 < 4) ) { for ( int j = 0; j < m_genolength && half!=0; j++ ) { if ( mah[j] && (rand() % 6 < 4) && !m_mask[j]) { m_mask[i]=m_mask[j]=true; half--; break; } } } } } bool new_genotype[m_genolength]; for( int i = 0; i < m_genolength; i++ ) { if( m_mask[i] ) { new_genotype[i]=mategeno[i]; } else { new_genotype[i]=m_genotype[i]; } } return Individual(m_battles, m_soldiers, m_rf, m_lf, new_genotype); }
/* ---------------------------------------------------------------------- */ Population::Population(const Individual& ancestor, int size, float timeout) { assert(size>0); assert(ancestor.is_valid()); time_t start=time(NULL); flock.clear(); flock.reserve(size); flock.push_back(ancestor); for(int i=1; i<size && difftime(time(NULL), start)<timeout; i++) flock.push_back(Individual(ancestor, true)); }
std::vector<Individual> Reproduction::Reproduce(Individual father, Individual mother) { std::vector<int> fatherBinary = father.BinaryVector(); std::vector<int> motherBinary = mother.BinaryVector(); int firstCrossOverPoint, secondCrossOverPoint; firstCrossOverPoint = Utility::IntegerBetween(0, fatherBinary.size()); secondCrossOverPoint = Utility::IntegerBetween(firstCrossOverPoint, fatherBinary.size()); std::vector<int> firstSon = CrossoverBetween(fatherBinary, motherBinary, firstCrossOverPoint, secondCrossOverPoint); std::vector<int> secondSon = CrossoverBetween(motherBinary, motherBinary, firstCrossOverPoint, secondCrossOverPoint); std::vector<Individual> descendance; descendance.push_back(Individual(firstSon)); descendance.push_back(Individual(secondSon)); return descendance; }
std::vector < Individual > Individual::cruzaUnPunto (Individual& spouse, size_t p) { std::vector < Individual > result; std::vector < bool > parent1 = getChromosome(); std::vector < bool > parent2 = spouse.getChromosome(); std::vector < bool > child1, child2; size_t size = parent1.size(); size_t genNumber = chromosome.size(); for( size_t i = 0; i < size; i++ ) { if (i < p) { child1.push_back( parent1.at(i) ); child2.push_back( parent2.at(i) ); } else { child1.push_back( parent2.at(i) ); child2.push_back( parent1.at(i) ); } } result.push_back( Individual(child1,genNumber) ); result.push_back( Individual(child2,genNumber) ); return result; }
SolverEvolver::SolverEvolver(int population_size, double combination_probability, double mutation_probability) :population_size_(population_size) , combination_p_(combination_probability) , mutation_p_(mutation_probability) , steps_(0) { std::ifstream file("population.json"); picojson::value v; std::string err; err = picojson::parse(v, file); if (err.empty()) { auto arr = v.get("population").get<picojson::array>(); for (int i = 0; i < population_size && i < arr.size(); ++i) { auto genome = arr[i].get<picojson::array>(); population_.push_back(Individual()); if (genome.size() == population_[i].genome.size()) { for (int j = 0; j < population_[i].genome.size(); ++j) { population_[i].genome[j] = genome[j].get<double>(); } } else { population_[i].genome = random_genome(); } } } for (int i = population_.size(); i < population_size; ++i) { population_.push_back(Individual()); population_[i].genome = random_genome(); } initate_population(); }
// returns a child of the two passed Individuals Individual Genetic_Algorigthm::crossover(Individual father, Individual mother) { char * temp = new char[goalSize]; // if i is even, use father, else, use mother for (int i = 0; i < goalSize; ++i) { if (i % 2 == 0) temp[i] = father.str[i]; else temp[i] = mother.str[i]; } string output = temp; output.resize(goalSize); return Individual(output); }
void Genetic_Algorigthm::initPop() { srand(clock()); for (int i = 0; i < popSize; i++) { char * tempString = new char[goalSize]; for (int j = 0; j < goalSize; j++) { int randPos = rand() % 26; tempString[j] = alphabet[randPos]; //sizeof(alphabet) / sizeof(alphabet[0])]; } string temp = tempString; temp.resize(goalSize); population.push_back(Individual(temp)); previousBest = population[0]; } }
GeneticAlgorithm::GeneticAlgorithm(const int maxGenerations, const int populationSize, double mutationProbability, CryptarithmeticPuzzle cp) : _cp(cp), _maxGenerations(maxGenerations), _populationSize(populationSize), _mutationProbability(mutationProbability) { _averageFit = 0; _worstFit = 0; _bestFit = 0; _generation = 0; for(int i = 0; i < populationSize; ++i) { _population.push_back(Individual(_cp.getLookupTable().size())); } }
std::vector < Individual > Individual::cruzaDosPuntos (Individual& spouse, size_t x, size_t y) { std::vector < Individual > result; std::vector < bool > parent1 = getChromosome(); std::vector < bool > parent2 = spouse.getChromosome(); std::vector < bool > child1, child2; size_t size = parent1.size(); size_t genNumber = chromosome.size(); size_t t = x; x = x<y?x:y; y = y<t?t:y; for( size_t i = 0; i < size; i++ ) { if (i < x || i >= y) { child1.push_back( parent1.at(i) ); child2.push_back( parent2.at(i) ); } else { child1.push_back( parent2.at(i) ); child2.push_back( parent1.at(i) ); } } result.push_back( Individual(child1,genNumber) ); result.push_back( Individual(child2,genNumber) ); return result; }
/* ---------------------------------------------------------------------- */ Population::Population(const Population& ancestors, int size, float timeout) { int ansize=ancestors.get_size(); assert(size>=ansize); assert(ancestors.is_valid()); time_t start=time(NULL); flock.clear(); flock.reserve(size); (*this)=ancestors; for(int i=ansize; i<size && difftime(time(NULL), start)<timeout; ) { if(rand()%10<9 && ansize>1 && i<size-1) {//crossover or mutate if-block int p1=rand()%ansize; int p2; do { p2=rand()%ansize; } while (p1==p2); //p1 and p2 cannot be the same for crossover flock.push_back(Individual()); flock.push_back(Individual()); //Make space for i and i+1 Individual::crossover(ancestors.flock[p1], ancestors.flock[p2], flock[i], flock[i+1]); i+=2; } else { //crossover or mutate if-block flock.push_back(Individual(ancestors.flock[rand()%ansize], true)); i++; } //crossover or mutate if-block } }
/* Genetic Program Functions */ void Population::RampedHalfAndHalf(size_t population_size, size_t depth_min, size_t depth_max) { unsigned gradations = static_cast<unsigned>(depth_max - depth_min + 1); pop_.reserve(population_size); bool full_tree; for (size_t i = 0; i < population_size; ++i) { if (i % 2) { full_tree = true; } else { full_tree = false; } pop_.push_back(Individual(var_count_, const_min_, const_max_, (depth_min + i % gradations), full_tree)); } }
TEST(UX, Crossover){ Individual mom("02134"); Individual dad("41302"); std::vector<int> indices; indices.push_back(1); indices.push_back(3); UX ux(2); Individual child = ux.cross(indices, &dad, &mom); ASSERT_EQ(Individual("31204"), child); ASSERT_EQ(&dad, child.parent(0)); ASSERT_EQ(&mom, child.parent(1)); }
Individual RandomGreedInitialization::create_individual(vector<int> intersections) { vector<bool> chromossome; int chromossome_size = problem->getNintersections(); for(int i = 0; i < chromossome_size; i++) { chromossome.push_back(false); } for(unsigned i = 0; i < intersections.size(); i++) { // cout << intersections[i] << " "; chromossome[intersections[i]] = true; } // cout << endl; Individual individual = Individual(chromossome_size, intersections.size(), chromossome); // cout << "created individual\n"; return individual; }
Individual Population::GetBestIndividual() { if ( m_adults.size() > 0 ) { Individual best=m_adults.at(0); float bestfit=best.GetFitness(); for ( unsigned int i = 1; i < m_adults.size(); i++ ) { if ( bestfit < m_adults.at(i).GetFitness() ) { bestfit = m_adults.at(i).GetFitness(); best = m_adults.at(i); } } return best; } else { return Individual(1,1,1,1); } }
Population::Population(DataStream *ds, int size) :mDStream(ds), mMemberSize(size) { mMembers.assign(mMemberSize, Individual(this, this->mDStream)); }
// constructor Population::Population(int sz, int len, int init): data(sz, Individual(len, init)) { // std::cout << "Population of size " << data.size() << " is being created." << std::endl; }
void ribi::prswt::Simulation::Next() { using Prs = PaperRockScissors; std::map<Prs,double> sum_traits; sum_traits[Prs::paper ] = 0.0; sum_traits[Prs::rock ] = 0.0; sum_traits[Prs::scissors] = 0.0; std::map<Prs,int> tally_popsizes; tally_popsizes[Prs::paper ] = 0; tally_popsizes[Prs::rock ] = 0; tally_popsizes[Prs::scissors] = 0; std::vector<std::vector<Individual>> next(m_grid); const int height{static_cast<int>(m_grid.size())}; const int width{static_cast<int>(m_grid[0].size())}; for (int y=0; y!=height; ++y) { for (int x=0; x!=width; ++x) { int dx{0}; int dy{0}; switch (m_uniform_distribution(m_rng)) { case 0: --dy; break; case 1: ++dx; break; case 2: ++dy; break; case 3: --dx; break; default: assert(!"Should not get here"); } auto& here = m_grid[y][x]; const auto& neighbour = m_grid[(y+dy+height)%height][(x+dx+width)%width]; const auto& winner = DoesBeat(neighbour,here) ? neighbour : here; if (winner == neighbour) { const double new_trait{winner.GetTrait() + m_normal_distribution(m_rng)}; next[y][x] = Individual( winner.GetPrs(), new_trait ) ; ++tally_popsizes[winner.GetPrs()]; sum_traits[winner.GetPrs()] += winner.GetTrait(); } else { const double new_trait{here.GetTrait() + m_normal_distribution(m_rng)}; next[y][x] = Individual( here.GetPrs(), new_trait ) ; sum_traits[here.GetPrs()] += here.GetTrait(); ++tally_popsizes[here.GetPrs()]; } } } { const int n_p{tally_popsizes[Prs::paper]}; const int n_r{tally_popsizes[Prs::rock]}; const int n_s{tally_popsizes[Prs::scissors]}; assert(n_p >= 0); assert(n_r >= 0); assert(n_s >= 0); m_popsizes.push_back(std::make_tuple(n_p,n_r,n_s)); } m_mean_traits.push_back( std::make_tuple( sum_traits[Prs::paper ] / static_cast<double>(tally_popsizes[Prs::paper ]), sum_traits[Prs::rock ] / static_cast<double>(tally_popsizes[Prs::rock ]), sum_traits[Prs::scissors] / static_cast<double>(tally_popsizes[Prs::scissors]) ) ); std::swap(m_grid,next); }
void ribi::prswt::Simulation::SetInitialization(const Initialization initialization) noexcept { using Prs = PaperRockScissors; m_popsizes.clear(); m_mean_traits.clear(); m_grid.clear(); std::map<Prs,int> tally; tally[Prs::paper] = 0; tally[Prs::rock] = 0; tally[Prs::scissors] = 0; m_parameters.SetInitialization(initialization); //Initialize the grid assert(m_grid.empty()); const int height = m_parameters.GetHeight(); const int width = m_parameters.GetWidth(); for (int y=0; y!=height; ++y) { assert(y == static_cast<int>(m_grid.size())); m_grid.push_back(std::vector<Individual>()); assert(y < static_cast<int>(m_grid.size())); for (int x=0; x!=width; ++x) { assert(x == static_cast<int>(m_grid[y].size())); Prs prs = Prs::paper; switch(initialization) { case Initialization::random: { static std::uniform_int_distribution<int> d(0,2); //Inclusive switch (d(m_rng)) { case 0: prs = Prs::paper; break; case 1: prs = Prs::rock; break; case 2: prs = Prs::scissors; break; default: assert(!"Should not get here"); } } break; case Initialization::vertical_bands: { switch ((y / (height / 15)) % 3) { case 0: prs = Prs::paper; break; case 1: prs = Prs::rock; break; case 2: prs = Prs::scissors; break; default: assert(!"Should not get here"); } } break; case Initialization::monomorph: prs = Prs::paper; break; default: assert(!"Should not get here"); } m_grid[y].push_back(Individual(prs,0.0)); ++tally[prs]; } } { const int n_p{tally[Prs::paper]}; const int n_r{tally[Prs::rock]}; const int n_s{tally[Prs::scissors]}; assert(n_p >= 0); assert(n_r >= 0); assert(n_s >= 0); m_popsizes.push_back(std::make_tuple(n_p,n_r,n_s)); } m_mean_traits.push_back( std::make_tuple(0.0,0.0,0.0) ); }
Individual Individual::evolve() { // //If it is locked // if (this->isLocked()) // return Individual(); this->setLocked(true); Individual offspring = this->copy(); if (this->getGene().size() == 0) { printf("Subpop = %d => Ind vazio!\n", this->getDepot()); Individual offspring = Individual(this->getProblem(), this->getConfig(), this->getDepot(), this->getId()); offspring.create(); } //cout << "Offspring = " << offspring.getTotalCost() << endl; bool mutate = false; //printf("Offspring = D: %d - Id: %d => PM: %.2f / PLS: %.2f / RS: %d\n", this->getDepot(), // this->getId(), this->getMutationRatePM(), this->getMutationRatePLS(), this->isRestartMoves()); if (Random::randFloat() <= this->getMutationRatePM()) { offspring.mutate(); offspring.evaluate(true); mutate = true; } else { if (offspring.getRoutes().size() == 0) offspring.evaluate(true); } //offspring.printSolution(); if (Random::randFloat() <= this->getMutationRatePLS()) { //Individual orig = offspring; //offspring.printSolution(true); offspring.localSearch(); offspring.routesToGenes(); //offspring.printSolution(true); if (offspring.getGene().size() == 0) { cout << "Mutate = " << mutate << endl; this->print(); this->print(true); this->printSolution(); offspring.print(); offspring.print(true); offspring.printSolution(); // orig.print(); // orig.print(true); // orig.printSolution(); } } if (this->getRoutes().size() == 0) { //cout << "Wait\n\n"; //cout << "Old: " << this->getTotalCost() << endl; this->evaluate(true); //cout << "New: " << this->getTotalCost() << endl; } if (Util::isBetterSolution(offspring.getTotalCost(), this->getTotalCost())) { //this->setGene(offspring.getGene()); //this->setRoutes(offspring.getRoutesConst()); //this->evaluate(true); this->updateParameters(true); } else { this->updateParameters(false); } //this->print(true); //this->setLocked(false); return offspring; }
#include "../TestRunner/catch.hpp" #include "../../SGAEllipse/Source/Population/Individual.h" #include "../../SGAEllipse/Source/Population/PopulationStatics.h" SCENARIO("Reproduction should") { GIVEN("two individuals and PopulationStatics with 5 bitsAB, 6 bitsXY, 7 bitsTheta") { PopulationStatics::bitsAB = 5; PopulationStatics::bitsXY = 6; PopulationStatics::bitsTheta = 7; Individual father = Individual(); Individual mother = Individual(); THEN("give two sons by Two Point Crossover at bit level") { } } }
Observations ReadData ::ReadObservations(DataSettings &DS) { Observations Obs; std::ifstream IndivID(DS.GetPathToGroup()); std::ifstream TimePointsFile(DS.GetPathToTimepoints()); std::ifstream LandmarksFile(DS.GetPathToLandmarks()); std::ifstream CognitiveScoresFile(DS.GetPathToCognitiveScores()); std::string GroupLine, TimePointsLine, LandmarksLine, CognitiveScoresLine; unsigned int CurrentSubjectID = -1; VectorType TimePoints; std::vector<VectorType> Landmarks; std::vector<VectorType> CognitiveScores; while(getline(IndivID, GroupLine)) { if(CurrentSubjectID == -1) CurrentSubjectID = std::stoi(GroupLine); unsigned int NewSubjectID = std::stoi(GroupLine); getline(TimePointsFile, TimePointsLine); if(DS.LandmarkPresence()) getline(LandmarksFile, LandmarksLine); if(DS.CognitiveScoresPresence()) getline(CognitiveScoresFile, CognitiveScoresLine); /// New subject if(NewSubjectID != CurrentSubjectID) { IndividualObservations Individual(TimePoints); if(DS.LandmarkPresence()) Individual.AddLandmarks(Landmarks); if(DS.CognitiveScoresPresence()) Individual.AddCognitiveScores(CognitiveScores); Obs.AddIndividualData(Individual); CurrentSubjectID = NewSubjectID; TimePoints.clear(); Landmarks.clear(); CognitiveScores.clear(); } TimePoints.push_back(stod(TimePointsLine)); if(DS.LandmarkPresence()) { VectorType NewObs(DS.GetLandmarksDimension()); int i = 0; std::stringstream LineStream(LandmarksLine); std::string cell; while(std::getline(LineStream, cell, ',')) { NewObs(i) = std::stod(cell); ++i; } Landmarks.push_back(NewObs); } if(DS.CognitiveScoresPresence()) { VectorType NewObs(DS.GetCognitiveScoresDimension()); int i = 0; std::stringstream LineStream(CognitiveScoresLine); std::string cell; while(std::getline(LineStream, cell, ',')) { NewObs(i) = std::stod(cell); ++i; } CognitiveScores.push_back(NewObs); } } IndividualObservations Individual(TimePoints); if(DS.LandmarkPresence()) Individual.AddLandmarks(Landmarks); if(DS.CognitiveScoresPresence()) Individual.AddCognitiveScores(CognitiveScores); Obs.AddIndividualData(Individual); return Obs; }
#include "../TestRunner/catch.hpp" #include "../../SGAEllipse/Source/Population/Individual.h" #include "../../SGAEllipse/Source/Population/PopulationStatics.h" TEST_CASE("Individual should") { GIVEN("a PopulationStatics with 5 bitsAB, 6 bitsXY, 7 bitsTheta") { PopulationStatics::bitsAB = 5; PopulationStatics::bitsXY = 6; PopulationStatics::bitsTheta = 7; Individual individual = Individual(); THEN("be initialized with a binary vector of 2 x bitsAB + 2 x bitsXY + bitsTheta number of bits") { int totalBits = PopulationStatics::bitsAB * 2 + PopulationStatics::bitsXY * 2 + PopulationStatics::bitsTheta; CHECK(individual.BinaryVector().size() == totalBits); } THEN("return property A with a binary value of 5 bits") CHECK(individual.A().Binary().size() == 5); THEN("return property B with a binary value of 5 bits") CHECK(individual.B().Binary().size() == 5); THEN("return property X with a binary value of 6 bits") CHECK(individual.XCoord().Binary().size() == 6); THEN("return property Y with a binary value of 6 bits") CHECK(individual.YCoord().Binary().size() == 6);