int main() { int gen = 0; char go = 1; srand(time(NULL)); /* 1. Choose the initial ppopulation */ initial_population(); /* 2. Evaluate the fitness of each individual in the population */ fitness(); /* 3. Repeat */ while((gen++ < MAX_GENS) && go) { /* printf("Find the best fittest\n");*/ /* 1. Select the best-ranking individuals to reproduce */ find_the_best_individuals(); /* Select the reproduce no, dynamicly (Ver. 2) */ reproduce(); /* 2. Breed new generation through crossover and mutation (genetic operations) and give birth to offspring */ /* 3. Evaluate the individual fitnesses of the offspring */ /* 4. Replace worst ranked part of the population with offspring */ fitness(); find_the_best_individuals(); if (population[0].fitness < OK_SNIT) go = 0; } /* 4. Until <terminating condition> */ print_population(); printf("No of gen: %d\n",gen); return 0; }
int main() { srand(time(NULL)); data dat; readfile(dat, "../../data/ks_19_0"); int items = dat[0].value; population *pop, popalpha; initialize_population(popalpha, items); pop = &popalpha; //print(*pop); bat best = get_best(*pop); int iterations = 200; while(iterations > 0){ new_solutions(*pop,dat); calc_fitness(*pop, dat); if(getrand()> 0.5){ best = get_best(*pop); move_bat(best, rand()%5, dat); // amplitude is 2 } if(fitness(best, dat) > fitness((*pop).best, dat)) (*pop).best = best; iterations--; } print(*pop); }
//structured monte carlo //maintains correct blockstructure doesnt work very good void oku_mcblksol(oku_sod* sod, double temp){ int i,j,k,val; int fit1, fit2, num,blk,idx1,idx2,tmp; int size = sod->size; int blkunk[size],cnt[size]; int blkunkidx[size][size]; for(i=0;i<size;i++){ blkunk[i] = 0; for(j=0;j<size;j++) cnt[j] = 0; //find unknowns for every block for(j=0;j<size;j++){ val = get_blk(sod,i,j); if(val == 0){ blkunkidx[i][blkunk[i]++] = j; } else { if(cnt[val-1] == 0){ cnt[val-1] = 1; } else printf("Fehler in oku_mcblocksol: Invalid hint: %d\n",val); } } //fill them k=0; for(j=0;j<size;j++) if(cnt[j] == 0) set_blk(sod,i,blkunkidx[i][k++],j+1); } oku_sod_print(sod); fit1 = fitness(sod); num = 0; while(fit1){ //choose block and two indizes inside blk = rndi() % size; idx1 = rndi() % blkunk[blk]; idx2 = rndi() % blkunk[blk]; //swap tmp = get_blk(sod,blk,idx1); set_blk(sod,blk,idx1,get_blk(sod,blk,idx2)); set_blk(sod,blk,idx2,tmp); fit2 = fitness(sod); if(fit2 > fit1 && exp((fit1 - fit2)/temp) < rndf()){ //swap back tmp = get_blk(sod,blk,idx1); set_blk(sod,blk,idx1,get_blk(sod,blk,idx2)); set_blk(sod,blk,idx2,tmp); } else fit1 = fit2; num++; if(num % 2000 == 0) printf("Step:%d Fitness: %d\n",num,fit1); } }
int torneio (Populacao *pop, void (*fitness)(Populacao *pop, int i1, int i2, int *champion, int *loser, int verb) , int verbose) { Individuo *rind1; Individuo *rind2; int champion1, champion2; int loser1, loser2; int i1 = mysorteiounico(pop->tam, -1,-1,-1); int i2 = mysorteiounico(pop->tam, i1,-1,-1); int i3 = mysorteiounico(pop->tam, i1,i2,-1); int i4 = mysorteiounico(pop->tam, i1,i2,i3); //printf("Sorteados %d %d %d %d\n", i1,i2,i3,i4); fitness(pop, i1, i2,&champion1, &loser1, verbose); fitness(pop, i3, i4,&champion2, &loser2, verbose); crossover(pop->data[champion1], pop->data[champion2], pop->txcross, &rind1, &rind2); mutation(rind1, pop->txmut); mutation(rind2, pop->txmut); freeIndividuo(pop->data[loser1]); freeIndividuo(pop->data[loser2]); pop->data[loser1] = rind1; pop->data[loser2] = rind2; }
void max_fitness(char S[], char bit) { //count++; if (bit == 0) { double maybe_best = fitness(S); if (maybe_best > best) best = maybe_best; S[(int)bit] = 1; maybe_best = fitness(S); S[(int)bit] = 0; if (maybe_best > best) best = maybe_best; return; } max_fitness(S, bit - 1); S[(int)bit] = 1; if (bit < n/2 && upper_bound(S, bit) <= best) { S[(int)bit] = 0; return; } max_fitness(S, bit - 1); S[(int)bit] = 0; }
void main() { int i, test = 0; // set from global variable int generation = m; Individual best; randomize(); worldInit(); populationInit(1); // 100% of population fitness(); // explicit, not in populationInit() best = getBestIndividual(); for(i = 0; i < maxGenerations; i++){ if(test){ printf("#generation: %4d, fitness: %4d\n", i, best.fitness); }else{ printf("#generation: %4d, fitness: %4d\n", i, best.fitness); printAxisOfBest(best); } if(generation == 0){ // a) (K == xAxis) ? K = 1 : K++; // b) //K = random(xAxis); // c) //if(K == 10) K = 25; else K = 10; worldInit(); populationInit(3); // reinicialize 30% of population fitness(); generation = m; }else{ generation--; } selection(); crossover(); mutation(); fitness(); best = getBestIndividual(); } printf("#generation: %4d, fitness: %4d\n", i, best.fitness); if(!test) printAxisOfBest(best); }
void find_gbest(void) { int i; for (i = 0; i < 10; i++) { if (fitness(gbest) > fitness(p[i].current)) { gbest = p[i].current; } } }
int main() { std::cout << "[moeoChebyshevMetric] => "; // objective vectors ObjectiveVector obj0, obj1, obj2, obj3, obj4, obj5, obj6; obj0[0] = 3; obj0[1] = 3; obj1[0] = 2; obj1[1] = 2; obj2[0] = 1; obj2[1] = 1; obj4[0] = 0; obj4[1] = 0; std::vector<double> poids; poids.resize(2); poids[0]=2; poids[1]=3; ObjectiveVector obj_poids(poids); // population eoPop < Solution > pop; pop.resize(3); pop[0].objectiveVector(obj0); pop[1].objectiveVector(obj1); pop[2].objectiveVector(obj2); Solution reference; reference.objectiveVector(obj4); unsigned int rho=2; moeoObjectiveVectorNormalizer<Solution> normalizer(pop,10); moeoAugmentedAchievementScalarizingFunctionMetricFitnessAssignment<Solution> fitness(rho,obj4,obj_poids,normalizer,eval); moeoAugmentedAchievementScalarizingFunctionMetricFitnessAssignment<Solution> fitness1(rho,obj4,obj_poids); moeoAugmentedAchievementScalarizingFunctionMetricFitnessAssignment<Solution> fitness2(rho,obj4,obj_poids,normalizer); moeoAugmentedAchievementScalarizingFunctionMetricFitnessAssignment<Solution> fitness3(rho,obj4,obj_poids,eval); fitness(pop); fitness(reference); assert(pop[0].fitness()<pop[1].fitness()); assert(pop[1].fitness()<pop[2].fitness()); std::cout << "Ok" << std::endl; return EXIT_SUCCESS; }
/** * Check fitness of this tree * @param pos position to check * @param min minimum value * @param max maximum value * @param deepness deepness level * @return fitness of the tree **/ double fitness(int pos, int min=INT_MIN, int max=INT_MAX, double deepness=1) { int lpos = 2*pos+1; int rpos = 2*pos+2; double fit=0; if(values[pos] > max) fit=(fit+1)*deepness; if(values[pos] < min) fit=(fit+1)*deepness; if(lpos < SIZE) fit+=fitness(lpos, min, values[pos], deepness/2); if(rpos < SIZE) fit+=fitness(rpos, values[pos], max, deepness/2); return fit; }
// first monte carlo solver, mildly constraint void oku_mcsol(oku_sod* sod, double temp){ int i,j,num,size = sod->size; int cnt[size+1]; int fit1, fit2, idx1, idx2,tmp,tmp2; //refresh list of unknowns in sod unk_find(sod); //fill sudoku with missing symbols for(i=1;i<size+1;i++) cnt[i] = size; for(i=0;i<size*size;i++) cnt[get_idx(sod,i)]--; j=1; for(i=0;i<get_numunk(sod);i++){ while(cnt[j] < 1 && j <= size+1) j++; cnt[j]--; set_idx(sod,get_unkidx(sod,i),j); } fit1 = fitness(sod); num=0; while(fit1 && num < 200000){ //choose 2 indices idx1 = get_unkidx(sod,rndi() % get_numunk(sod)); idx2 = get_unkidx(sod,rndi() % get_numunk(sod)); //swap tmp = get_idx(sod,idx1); if(tmp == (tmp2 = get_idx(sod,idx2))) continue; set_idx(sod,idx1,tmp2); set_idx(sod,idx2,tmp); fit2 = fitness(sod); if(fit2 > fit1 && exp((fit1 - fit2)/temp) < rndf()){ //swap back tmp = get_idx(sod,idx1); set_idx(sod,idx1,get_idx(sod,idx2)); set_idx(sod,idx2,tmp); } else fit1 = fit2; num++; } printf("Solution found after %d MC Steps\n",num); };
void print_population(char **population) { int i; for (i = 0; i < PSIZE; i++) { printf("population[%02d]: %s (%d)\n", i, population[i], fitness(population[i])); } }
void simu_controller_loop(MBSdataStruct *MBSdata) { double tsim; ControllerStruct *cvs; UserIOStruct *uvs; uvs = MBSdata->user_IO; cvs = uvs->cvs; tsim = MBSdata->tsim; // controller if (tsim >= uvs->last_t_ctrl + PERIOD_CTRL - TIME_EPSILON) { uvs->last_t_ctrl = tsim; controller_inputs(MBSdata); controller_loop(cvs); controller_outputs(MBSdata); } // simulation outputs simu_outputs(MBSdata); // objective function fitness(MBSdata); // stopping the simulation if needed stop_simu(MBSdata); }
/*midgeneプールの適応度の計算*/ void setfvalue(char midgene[POOLSIZE*2][RULESIZE][LOCUSSIZE], int fvalue[],char lines[MAXLINES][LINESIZE],int lineno) { int i ; for(i=0;i<POOLSIZE*2;++i) fvalue[i]=fitness(midgene[i],lines,lineno)+1 ; }
void GeneticAlgorithm<T>::working_thread() { //cout <<"Anzahl: "<<m_populationsize<<endl; Farbe ** buffer = new Farbe*[picsizex]; for(uint i = 0;i<picsizex;i++) buffer[i] = new Farbe[picsizey]; while(1) { number_action.lock(); if(actnum == m_populationsize) { for(uint i = 0;i<picsizex;i++) delete [] buffer[i]; delete [] buffer; number_action.unlock(); ready--; return; } uint arbeit = actnum; actnum++; number_action.unlock(); fitn[arbeit] = fitness(arbeit,buffer,fitnessmode); //cout <<"Fitness von "<<arbeit<<" ist "<<fitn[arbeit]<<endl; } }
int main(int argc, char *argv[]) { int my_rank; double mpi_start_time, mpi_end_time; deme *subpop = (deme*) malloc(sizeof(deme)); MPI_Init(&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD, &my_rank); init_population(subpop, argc, argv); mpi_start_time = MPI_Wtime(); while (!subpop->complete) { migration(subpop); reproduction(subpop); crossover(subpop); mutation(subpop); fitness(subpop); subpop->old_pop = subpop->new_pop; subpop->cur_gen++; check_complete(subpop); sync_complete(subpop); report_all(subpop); } mpi_end_time = MPI_Wtime(); report_fittest(subpop); MPI_Finalize(); printf("[%i] Elapsed time: %f\n", my_rank, mpi_end_time - mpi_start_time); return 1; }
float MinEntropy(GAGenome& g) { GA1DBinaryStringGenome & genome = (GA1DBinaryStringGenome &)g; return fitness(gen2rule(genome)); }
void GQAP::CopyProblem(GQAP & _problem) { // Copy Problem Parameters transportCost = _problem.transportCost; numLocation = _problem.numLocation; numEquip = _problem.numEquip; vectorSpaceCap = _problem.vectorSpaceCap; vectorSpaceReq = _problem.vectorSpaceReq; matrixDist = _problem.matrixDist; matrixFlow = _problem.matrixFlow; matrixInstallCost = _problem.matrixInstallCost; // Copy Current Solution and its Fitness-Value solution = _problem.solution; if (!_problem.invalid()) { fitness(_problem.fitness()); } // Copy Helper Variables numViolatedCapacityUnits = _problem.numViolatedCapacityUnits; numViolatedLocations = _problem.numViolatedLocations; installationPenalty = _problem.installationPenalty; transportationPenalty = _problem.transportationPenalty; UsedCapacity = _problem.UsedCapacity; }
/*Callback function that is called during each GA run*/ int callbackf(int gen, void ** pop, int popsz) { int i,j; double x; void * y; Parameters * p; y = pop[0]; x = fitness(y); if (PRINT_STEPS) { printf("%i %lf\n", gen, x); if (x == 1.0) printf("target reached.\n\n"); } if (x == 1.0) { return (1); } if (gen > 0 && (gen % 20) == 0) { p = 0; for (i=0; i < popsz/2; ++i) { p = (Parameters*)pop[i]; for (j=0; j < p->numVars; ++j) p->alphas[j] *= 2.0 * randnum; for (j=0; j < p->numParams; ++j) p->params[j] *= 2.0 * randnum; normalize (p->alphas , p->numVars); normalize (p->params , p->numParams); } } return (0); }
void selection(char **population, int *x, int *y) { int total_fitness = totalFitness(population); //printf("total fitness: %d\n",total_fitness); //printf("xy: %d %d",*x,*y); // while (*x == *y) { //make sure the two parents are different int random1 = rand() % (total_fitness + 1); int random2 = rand() % (total_fitness + 1); if (random1 > random2) { int temp = 0; temp = random1; random1 = random2; random2 = temp; } //let random 1 < random2 //printf("random 1: %d 2: %d\n", random1, random2); int t = 0; int i; for (i = 0; i < PSIZE; i++) { t += fitness(population[i]); if (t > random1 && *x == 0) *x = i; if (t > random2 && *y == 0) { *y = i; break; } } // } }
void calc_fitness(population &pop, data &dat) { for(int i = 0; i < No_of_Bats; i++) { pop.bats[i].fitness = fitness(pop.bats[i], dat); } }
int main() { std::cout << "[moeoAggregationFitnessAssignment] => "; // objective vectors ObjectiveVector obj0, obj1, obj2, obj3, obj4, obj5, obj6; obj0[0] = 0; obj0[1] = 2; obj1[0] = 2; obj1[1] = 0; obj2[0] = 4; obj2[1] = 2; obj4[0] = 3; obj4[1] = 0; std::vector<double> poids; poids.resize(2); poids[0]=2; poids[1]=1; // population eoPop < Solution > pop; pop.resize(3); pop[0].objectiveVector(obj0); pop[1].objectiveVector(obj1); pop[2].objectiveVector(obj2); moeoObjectiveVectorNormalizer<Solution> normalizer; moeoConstraintFitnessAssignment < Solution > fitness(poids,obj4,1,normalizer); moeoConstraintFitnessAssignment < Solution > fitness2(poids,obj4,1,normalizer,defaultEval); fitness(pop); assert(pop[0].fitness()==-2); assert(pop[1].fitness()==0); assert(pop[2].fitness()==-4); std::cout << "Ok" << std::endl; return EXIT_SUCCESS; }
int totalFitness(char **population) { int total_fitness = 0; int i; for (i = 0; i < PSIZE; i++) { total_fitness += fitness(population[i]); } return total_fitness; }
/*遺伝子プールの世代平均適応度の計算*/ double fave(char gene[POOLSIZE][RULESIZE][LOCUSSIZE],char lines[MAXLINES][LINESIZE],int lineno) { int i ; double fsum=0.0 ; for(i=0;i<POOLSIZE;++i){ fsum+=fitness(gene[i],lines,lineno) ; } return fsum/POOLSIZE ; }
int main() { std::cout << "[moeoAggregationFitnessAssignment] => "; // objective vectors ObjectiveVector obj0, obj1, obj2, obj3; obj0[0] = 2; obj0[1] = 5; obj1[0] = 3; obj1[1] = 3; obj2[0] = 4; obj2[1] = 1; obj3[0] = 5; obj3[1] = 5; std::vector<double> poids; poids.resize(2); poids[0]=2; poids[1]=3; // population eoPop < Solution > pop; pop.resize(4); pop[0].objectiveVector(obj0); pop[1].objectiveVector(obj1); pop[2].objectiveVector(obj2); pop[3].objectiveVector(obj3); moeoAggregationFitnessAssignment < Solution > fitness(poids); fitness(pop); assert(pop[0].fitness() == 19.0); assert(pop[1].fitness() == 15.0); assert(pop[2].fitness() == 11.0); assert(pop[3].fitness() == 25.0); std::cout << "Ok" << std::endl; return EXIT_SUCCESS; }
/** * Mutates the tree **/ void mutate() { if((rand() % 100) <= MUTATION_RATE) { double f0 = fitness(0); mc++; int i = rand() % SIZE; int j = rand() % SIZE; int tmp=values[i]; values[i]=values[j]; values[j]=tmp; } }
// Find the current performance of the swarm. void findPerformance(double swarm[swarmsize][datasize], double perf[swarmsize], double age[swarmsize], char type, int robots, int neighbors[swarmsize][swarmsize]) { double particles[robots][datasize]; double fit[robots]; int i,j,k; // FOR-loop counters for (i = 0; i < swarmsize; i+=robots) { for (j=0;j<robots && i+j<swarmsize;j++) { sprintf(label2,"Particle: %d\n", i+j); wb_supervisor_set_label(1,label2,0.01,0.05,0.05,0xffffff,0); for (k=0;k<datasize;k++) particles[j][k] = swarm[i+j][k]; } // USER MUST IMPLEMENT FITNESS FUNCTION if (type == EVOLVE_AVG) { // Evalute current fitness fitness(particles,fit,neighbors); // TODO : performance as moving average of previous perf and latest fitness // TODO : pay attention to age[] for (j=0;j<robots && i+j<swarmsize;j++) { } } else if (type == EVOLVE) { fitness(particles,fit,neighbors); for (j=0;j<robots && i+j<swarmsize;j++) perf[i+j] = fit[j]; } else if (type == SELECT) { for (j=0;j<robots && i+j<swarmsize;j++) perf[i+j] = 0.0; for (k=0;k<5;k++) { fitness(particles,fit,neighbors); for (j=0;j<robots && i+j<swarmsize;j++) perf[i+j] += fit[j]; } for (j=0;j<robots && i+j<swarmsize;j++) { perf[i+j] /= 5.0; } } } }
void GQAP::operator=(GQAP_Solution& _solution) { if (_solution.solution.size() != solution.size()) { throw std::runtime_error("ERROR: Trying to GQAP_Solution with differen size to a GQAP"); } for (int i = 0; i < solution.size(); i++) { solution[i] = _solution[i]; } fitness(_solution.fitness()); CalculateCapacityViolations(); }
void pso(void) { int i, iter_num; iter_num = 1; while (iter_num < MAX_ITERATIONS) { for (i = 0 ; i < 10; i++) { if (fitness(p[i].current) < fitness(p[i].pbest)) { p[i].pbest = p[i].current; } } find_gbest(); adjust_v(); for (i = 0; i < 10; i++) { p[i].current += v[i]; } iter_num++; } }
// Find the current performance of the swarm. // Lower performance is better void findPerformance(double swarm[swarmsize][datasize], double perf[swarmsize], double age[swarmsize], char type, int robots, int neighbors[swarmsize][swarmsize]) { double particles[robots][datasize]; double fit[robots]; int i,j,k; // FOR-loop counters for (i = 0; i < swarmsize; i+=robots) { for (j=0;j<robots && i+j<swarmsize;j++) { for (k=0;k<datasize;k++) particles[j][k] = swarm[i+j][k]; } // USER MUST IMPLEMENT FITNESS FUNCTION if (type == EVOLVE_AVG) { fitness(particles,fit,neighbors); for (j=0;j<robots && i+j<swarmsize;j++) { perf[i+j] = ((age[i+j]-1.0)*perf[i+j] + fit[j])/age[i+j]; age[i+j]++; } } else if (type == EVOLVE) { fitness(particles,fit,neighbors); for (j=0;j<robots && i+j<swarmsize;j++) perf[i+j] = fit[j]; } else if (type == SELECT) { for (j=0;j<robots && i+j<swarmsize;j++) perf[i+j] = 0.0; for (k=0;k<5;k++) { fitness(particles,fit,neighbors); for (j=0;j<robots && i+j<swarmsize;j++) perf[i+j] += fit[j]; } for (j=0;j<robots && i+j<swarmsize;j++) { perf[i+j] /= 5.0; } } } }
bool Villager::operator >(const Individuo &v) { /* const Villager *ptr = ((const Villager*) &v); if (attack() > ptr->attack())return true; else if (attack() == ptr->attack()){ if (defense() > ptr->defense())return true; else if (defense() == ptr->defense())return blot() < ptr->blot(); } return false; */ return fitness() > v.fitness(); }