index_pair selector::ranking(generation& gen) { std::sort(gen.begin(), gen.end(), [](auto& c1, auto& c2) { return c1.fitness < c2.fitness; }); int sum = 0; for (int i = 0; i < gen.size(); ++i) sum += i; std::uniform_int_distribution<> dis_sum(0, sum); auto select = [&](auto& random) { int probability = random(dis_sum); int index = 0; while (probability > 0) { probability -= index + 1; ++index; } return index >= gen.size() ? index - 1 : index; }; return index_pair(select(random), select(random)); }
index_pair selector::roulette(generation& gen) { double sum = std::accumulate(gen.begin(), gen.end(), 0.0, [](double prev, auto& c) { return prev + c.fitness; }); // double sum = 30.0; std::uniform_real_distribution<> dis_sum(0.0, sum); auto select = [&](auto& random) { double probability = random(dis_sum); int index = 0; while (probability > 0) { probability -= gen[index].fitness; ++index; } return index >= gen.size() ? index - 1 : index; }; return index_pair(select(random), select(random)); }
void gen_initialize(generation &geninit, int &spop, int &apop, int &idnumber, const int &aleaspace, const int &n_param, const vector<parameters> ¶ms, const double &lambda) { if(aleaspace==0) { ///Populate the space with equidistant values. First generation int geninit_nindividuals = (int)pow(spop,n_param); geninit.construct(geninit_nindividuals, n_param, idnumber, lambda); ///Determination of parameters_equally_spaced mat samples = doe_uniform(spop, n_param, params); for(int j=0; j<n_param; j++) { for(int i=0; i<geninit.size(); i++) { geninit.pop[i].p(j) = samples(i,j); } } } if(aleaspace==1) { ///Populate the space with equidistant values. First generation int geninit_nindividuals = (int)pow(spop,n_param); geninit.construct(geninit_nindividuals, n_param, idnumber, lambda); ///Determination of parameters_equally_spaced mat samples = doe_uniform_limit(spop, n_param, params); for(int j=0; j<n_param; j++) { for(int i=0; i<geninit.size(); i++) { geninit.pop[i].p(j) = samples(i,j); } } } else if(aleaspace==2) { int geninit_nindividuals=apop; geninit.construct(geninit_nindividuals, n_param, idnumber, lambda); ///Determination of random values ///Determination of parameters_equally_spaced mat samples = doe_random(geninit_nindividuals, n_param, params); for(int j=0; j<n_param; j++) { for(int i=0; i<geninit.size(); i++) { geninit.pop[i].p(j) = samples(i,j); } } } else if(aleaspace==3) { mat samples; read_gen(apop, samples, n_param); int geninit_nindividuals=apop; geninit.construct(geninit_nindividuals, n_param, idnumber, lambda); for(int j=0; j<n_param; j++) { for(int i=0; i<geninit.size(); i++) { geninit.pop[i].p(j) = samples(i,j); } } } }