/* * GAの実行サイクル * * 実行順は * 1. 初期個体生成(init_chrom) * 2. 適合度でソーティング(sort_population) * 3. 子個体を2つ選択(generate_children) * 4. 交叉(crossover) * 5. 突然変異(mutation) * 6. 子個体を適合度の悪い個体と入れ替え(swap_population) * 7. 2~6を繰り返す */ void GA(void) { int gen = 0; // 1. 初期個体生成(init_chrom) init_chrom(); while(gen < MAX_GENERATION) { // 2. 適合度でソーティング(sort_population) sort_population(); printf("%d gen\r\n", gen); print_chrom(0); // 最良個体を表示 // 3. 子個体を2つ選択(generate_children) generate_children(); // 4. 交叉(crossover) crossover(); // 5. 突然変異(mutation) mutation(); // 6. 子個体を適合度の悪い個体と入れ替え(swap_population) swap_population(); gen++; } sort_population(); printf("%d gen\r\n", gen); print_chrom(0); // 最終世代の最良個体を表示 }
void GA::evolve() { //migrate(); // if there is any migration between populations, do it now. for (int i = 0; i < __POPULATIONS__; i++) { //Debug::debugln("EVOLVE"); //Debug::debugln("INITIAL"); //debug_population(i); select_candidates(i); //Debug::debugln("SELECT"); //debug_population(i); //debug_candidates(); mutate_candidates(i); //Debug::debugln("MUTATE"); //debug_population(i); //debug_candidates(); reproduce_candidates(i); //Debug::debugln("REPRODUCE"); //debug_population(i); sort_population(i); //Debug::debugln("SORT"); //debug_population(i); //debug_population__top_organism(i); } //debug_bestfitness(); //Debug::debugln(generation); generation++; }
boolean ga_qsort_test(void) #endif { int i; /* Loop variable */ population *pop=NULL; /* Test population */ pop = ga_population_new(50000, 4, 32); /* Randomly assigned fitnesses */ for (i=0; i<50000; i++) { pop->entity_array[i]->fitness=(double) rand()/RAND_MAX; pop->entity_iarray[i]=pop->entity_array[i]; } pop->size=50000; plog(LOG_NORMAL, "Sorting random list."); sort_population(pop); plog(LOG_NORMAL, "Sorting ordered list."); sort_population(pop); /* Reverse population */ for (i=0; i<50000/2; i++) swap_e(pop->entity_iarray[i],pop->entity_iarray[24999-i]); plog(LOG_NORMAL, "Sorting reverse-ordered list."); sort_population(pop); /* Write list */ /* for (i=0; i<50000; i++) printf("%6d: %f\n", i, pop->entity_iarray[i]->fitness); */ #ifdef GA_QSORT_COMPILE_MAIN exit(EXIT_SUCCESS); #else return TRUE; #endif }
void print_stats(FILE *file){ if (Generation % Params.print_freq != 0) return; sort_population(); double sum = 0.0; for (int i = 0; i < Psize; i++) { sum += Population[i].f; } double mean = sum / Psize; double sq_sum = 0.0; for (int i = 0; i < Psize; i++) { sq_sum += Population[i].f * Population[i].f; } double stdev = sqrt(sq_sum / Psize - mean * mean); fprintf(file, "gen:%d q0:%.2f q1:%.2f q2:%.2f q3:%.2f q4:%.2f\navg:%.2f stdev:%.2f\n", Generation, Population[0].f, Population[Psize/4].f, Population[Psize/2].f, Population[3*Psize/4].f, Population[Psize-1].f, mean, stdev); }
int ga_deterministiccrowding( population *pop, const int max_generations ) { int generation=0; /* Current generation number. */ int *permutation, *ordered; /* Arrays of entities. */ entity *mother, *father; /* Current entities. */ entity *son, *daughter, *entity; /* Current entities. */ int i; /* Loop variable over entities. */ double dist1, dist2; /* Genetic or phenomic distances. */ int rank; /* Rank of entity in population. */ /* Checks. */ if (!pop) die("NULL pointer to population structure passed."); if (!pop->dc_params) die("ga_population_set_deterministiccrowding_params(), or similar, must be used prior to ga_deterministiccrowding()."); if (!pop->evaluate) die("Population's evaluation callback is undefined."); if (!pop->mutate) die("Population's mutation callback is undefined."); if (!pop->crossover) die("Population's crossover callback is undefined."); if (!pop->dc_params->compare) die("Population's comparison callback is undefined."); plog(LOG_VERBOSE, "The evolution by deterministic crowding has begun!"); pop->generation = 0; /* * Score the initial population members. */ if (pop->size < pop->stable_size) gaul_population_fill(pop, pop->stable_size - pop->size); for (i=0; i<pop->size; i++) { if (pop->entity_iarray[i]->fitness == GA_MIN_FITNESS) pop->evaluate(pop, pop->entity_iarray[i]); } sort_population(pop); ga_genocide_by_fitness(pop, GA_MIN_FITNESS); /* * Prepare arrays to store permutations. */ permutation = s_malloc(sizeof(int)*pop->size); ordered = s_malloc(sizeof(int)*pop->size); for (i=0; i<pop->size;i++) ordered[i]=i; plog( LOG_VERBOSE, "Prior to the first generation, population has fitness scores between %f and %f", pop->entity_iarray[0]->fitness, pop->entity_iarray[pop->size-1]->fitness ); /* * Do all the generations: * * Stop when (a) max_generations reached, or * (b) "pop->generation_hook" returns FALSE. */ while ( (pop->generation_hook?pop->generation_hook(generation, pop):TRUE) && generation<max_generations ) { generation++; pop->generation = generation; pop->orig_size = pop->size; plog(LOG_DEBUG, "Population size is %d at start of generation %d", pop->orig_size, generation ); sort_population(pop); random_int_permutation(pop->orig_size, ordered, permutation); for ( i=0; i<pop->orig_size; i++ ) { mother = pop->entity_iarray[i]; father = pop->entity_iarray[permutation[i]]; /* * Crossover step. */ plog(LOG_VERBOSE, "Crossover between %d (rank %d fitness %f) and %d (rank %d fitness %f)", ga_get_entity_id(pop, mother), ga_get_entity_rank(pop, mother), mother->fitness, ga_get_entity_id(pop, father), ga_get_entity_rank(pop, father), father->fitness); son = ga_get_free_entity(pop); daughter = ga_get_free_entity(pop); pop->crossover(pop, mother, father, daughter, son); /* * Mutation step. */ if (random_boolean_prob(pop->mutation_ratio)) { plog(LOG_VERBOSE, "Mutation of %d (rank %d)", ga_get_entity_id(pop, daughter), ga_get_entity_rank(pop, daughter) ); entity = ga_get_free_entity(pop); pop->mutate(pop, daughter, entity); ga_entity_dereference(pop, daughter); daughter = entity; } if (random_boolean_prob(pop->mutation_ratio)) { plog(LOG_VERBOSE, "Mutation of %d (rank %d)", ga_get_entity_id(pop, son), ga_get_entity_rank(pop, son) ); entity = ga_get_free_entity(pop); pop->mutate(pop, son, entity); ga_entity_dereference(pop, son); son = entity; } /* * Apply environmental adaptations, score entities, sort entities, etc. * FIXME: Currently no adaptation. */ pop->evaluate(pop, daughter); pop->evaluate(pop, son); /* * Evaluate similarities. */ dist1 = pop->dc_params->compare(pop, mother, daughter) + pop->dc_params->compare(pop, father, son); dist2 = pop->dc_params->compare(pop, mother, son) + pop->dc_params->compare(pop, father, daughter); /* * Determine which entities will survive, and kill the others. */ if (dist1 < dist2) { rank = ga_get_entity_rank(pop, daughter); if (daughter->fitness < mother->fitness) { entity = pop->entity_iarray[i]; pop->entity_iarray[i] = pop->entity_iarray[rank]; pop->entity_iarray[rank] = entity; } ga_entity_dereference_by_rank(pop, rank); rank = ga_get_entity_rank(pop, son); if (son->fitness < father->fitness) { entity = pop->entity_iarray[permutation[i]]; pop->entity_iarray[permutation[i]] = pop->entity_iarray[rank]; pop->entity_iarray[rank] = entity; } ga_entity_dereference_by_rank(pop, rank); } else { rank = ga_get_entity_rank(pop, son); if (son->fitness < mother->fitness) { entity = pop->entity_iarray[i]; pop->entity_iarray[i] = pop->entity_iarray[rank]; pop->entity_iarray[rank] = entity; } ga_entity_dereference_by_rank(pop, rank); rank = ga_get_entity_rank(pop, daughter); if (daughter->fitness < father->fitness) { entity = pop->entity_iarray[permutation[i]]; pop->entity_iarray[permutation[i]] = pop->entity_iarray[rank]; pop->entity_iarray[rank] = entity; } ga_entity_dereference_by_rank(pop, rank); } } /* * Use callback. */ plog(LOG_VERBOSE, "After generation %d, population has fitness scores between %f and %f", generation, pop->entity_iarray[0]->fitness, pop->entity_iarray[pop->size-1]->fitness ); } /* Generation loop. */ /* * Ensure final ordering of population is correct. */ sort_population(pop); return generation; }
int main(int argc, char *argv[]) { // Need to change to 3. need to remove the logging. if (argc != 4) { printf("Usage: ./maxcut <input data path> <output data path> <log file>\n"); exit(-1); } // Need to remove when submitting. log_file = fopen(argv[3], "w"); fprintf(log_file, "rate, elasped time (s), max val, avg val\n"); start_time = get_seconds(); in = fopen(argv[1], "r"); out = fopen(argv[2], "w"); int i, j, v1, v2, w; // (v1, v2) is the vertex and w is the weight fscanf(in, "%d %d\n", &num_of_vertex, &num_of_edge); int edge[num_of_vertex+1][num_of_vertex+1]; for (i=0; i<=SIZE; i++) for (j=0; j<=SIZE; j++) edge[i][j] = 0; while (fscanf(in, "%d %d %d\n", &v1, &v2, &w) != EOF) { edge[v1][v2] = w; edge[v2][v1] = w; } init_population(); init_offsprings(); init_cost(edge); sort_population(); init_crossover(); int p1, p2; while (!(stop_condition())) { generation++; for (i=1; i<=K; i++) { selection(&p1, &p2); crossover(i, p1, p2); mutation(i); local_optimization(i, edge); } replacement(edge); sort_population(); } for (i=1; i<=SIZE; i++) { if (population[N]->ch[i] == 1) fprintf(out, "%d ", i); } free_population(); fclose(in); fclose(out); printf("N: %d, K: %d, S_RATE: %lf, M_THRE: %lf, P0: %lf, POINTS: %d, K_FIT: %d, T: %lf\n", N, K, S_RATE, M_THRE, P0, POINTS, K_FIT, T); return 0; }
int main() { extern counter; /* test create_population */ population* pop; population_fitness* pop_fit; int x; counter = 0; pop = create_population( 0, &create_individual ); if( pop == 0 ) { printf( "population not created at line: %d\n", __LINE__ ); } else { print_population( pop, 0 ); delete_population( pop ); pop = 0; } counter = 0; pop = create_population( 1, &create_individual ); if( pop == 0 ) { printf( "population not created at line: %d\n", __LINE__ ); } else { print_population( pop, 0 ); delete_population( pop ); pop = 0; } counter = 0; pop = create_population( 10, &create_individual ); if( pop == 0 ) { printf( "population not created at line: %d\n", __LINE__ ); } else { print_population( pop, 0 ); print_population_compact( pop ); delete_population( pop ); pop = 0; } counter = 0; printf( "create_population large test: " ); fflush( stdout ); pop = create_population( INT_MAX / 64, &create_individual ); if( pop == 0 ) { printf( "population not created at line: %d\n", __LINE__ ); } else { delete_population( pop ); pop = 0; } printf( "complete\n" ); /* memory leak test */ printf( "create_population memory test: " ); #ifdef MEMLEAK fflush( stdout ); for( x = 0; x < INT_MAX; x++ ) { counter = 0; pop = create_population( 10, &create_individual ); if( pop == 0 ) { eprintf( "population not created at line: %d\n", __LINE__ ); } else { delete_population( pop ); pop = 0; } } printf( "complete\n" ); # else printf( "skipped\n" ); #endif /* test create_empty_population */ pop = create_empty_population( -1 ); if( pop == 0 ) { printf( "population not created at line: %d\n", __LINE__ ); } else { print_population( pop, 0 ); delete_population( pop ); pop = 0; } pop = create_empty_population( 0 ); if( pop == 0 ) { printf( "population not created at line: %d\n", __LINE__ ); } else { print_population( pop, 0 ); delete_population( pop ); pop = 0; } pop = create_empty_population( 1 ); if( pop == 0 ) { printf( "population not created at line: %d\n", __LINE__ ); } else { print_population( pop, 0 ); delete_population( pop ); pop = 0; } pop = create_empty_population( 10 ); if( pop == 0 ) { printf( "population not created at line: %d\n", __LINE__ ); } else { print_population( pop, 0 ); print_population_compact( pop ); delete_population( pop ); pop = 0; } printf( "create_empty_population large test: " ); fflush( stdout ); pop = create_empty_population( INT_MAX / 64 ); if( pop == 0 ) { printf( "population not created at line: %d\n", __LINE__ ); } else { delete_population( pop ); pop = 0; } printf( "complete\n" ); /* memory leak test */ printf( "create_population memory test: " ); #ifdef MEMLEAK fflush( stdout ); for( x = 0; x < INT_MAX; x++ ) { counter = 0; pop = create_empty_population( 10 ); if( pop == 0 ) { eprintf( "population not created at line: %d\n", __LINE__ ); } else { delete_population( pop ); pop = 0; } } printf( "complete\n" ); #else printf( "skipped\n" ); #endif /* test evaluate_population */ counter = 0; pop = create_empty_population( 1 ); if( pop == 0 ) { printf( "population not created at line: %d\n", __LINE__ ); } else { pop_fit = evaluate_population( pop, &evaluate_individual ); if( pop_fit == 0 ) { printf( "population fitness not created at line: %d\n", __LINE__ ); } else { print_population_fitness( pop_fit, 0 ); print_population_fitness_compact( pop_fit ); delete_population_fitness( pop_fit ); pop_fit = 0; } delete_population( pop ); pop = 0; } pop = create_population( 1, &create_individual ); if( pop == 0 ) { printf( "population not created at line: %d\n", __LINE__ ); } else { pop_fit = evaluate_population( pop, &evaluate_individual ); if( pop_fit == 0 ) { printf( "population fitness not created at line: %d\n", __LINE__ ); } else { print_population_fitness( pop_fit, 0 ); print_population_fitness_compact( pop_fit ); delete_population_fitness( pop_fit ); pop_fit = 0; } delete_population( pop ); pop = 0; } pop = create_population( 10, &create_individual ); if( pop == 0 ) { printf( "population not created at line: %d\n", __LINE__ ); } else { pop_fit = evaluate_population( pop, &evaluate_individual ); if( pop_fit == 0 ) { printf( "population fitness not created at line: %d\n", __LINE__ ); } else { print_population_fitness( pop_fit, 0 ); print_population_fitness_compact( pop_fit ); delete_population_fitness( pop_fit ); pop_fit = 0; } delete_population( pop ); pop = 0; } printf( "evaluate_population large test: " ); fflush( stdout ); pop = create_population( INT_MAX / 64, &create_individual ); if( pop == 0 ) { printf( "population not created at line: %d\n", __LINE__ ); } else { pop_fit = evaluate_population( pop, &evaluate_individual ); if( pop_fit == 0 ) { printf( "population_fitness not created at line: %d\n", __LINE__ ); } else { delete_population_fitness( pop_fit ); pop_fit = 0; } delete_population( pop ); pop = 0; } printf( "complete\n" ); /* memory leak test */ printf( "evaluate_population memory test: " ); #ifdef MEMLEAK fflush( stdout ); counter = 0; pop = create_population( 10, &create_individual ); if( pop == 0 ) { eprintf( "population not created at line: %d\n", __LINE__ ); } else { for( x = 0; x < INT_MAX; x++ ) { pop_fit = evaluate_population( pop, &evaluate_individual ); delete_population_fitness( pop_fit ); pop_fit = 0; } delete_population( pop ); pop = 0; } printf( "complete\n" ); #else printf( "skipped\n" ); #endif /* test sort_population */ counter = 0; pop = create_population( 100, &create_individual ); pop_fit = evaluate_population( pop, &evaluate_individual ); sort_population( pop_fit ); delete_population_fitness( pop_fit ); pop_fit = 0; delete_population( pop ); pop = 0; /* test create_next_generation */ counter = 0; pop = create_population( 100, &create_individual ); pop_fit = evaluate_population( pop, &evaluate_individual ); counter = 0; population* pop_next = create_next_generation( 10, 10, 80, pop, pop_fit, &compare_individuals_fitness ); delete_population_fitness( pop_fit ); pop_fit = 0; delete_population( pop ); pop = 0; delete_population( pop_next ); pop_next = 0; /* test create_population_fitness */ // pop_fit = create_population_fitness( 100 ); /* test delete_population_fitness */ // delete_population_fitness( pop_fit ); /* former tests */ /* srand( time_seed() ); population* pop; population_fitness* pop_fit; population_fitness* pop_fit_sorted; pop = create_population( 3, &create_individual ); print_population( pop, 0 ); pop_fit = evaluate_population( pop, &evaluate_individual ); print_population_fitness( pop_fit, 0 ); delete_population_fitness( pop_fit ); delete_population( pop ); pop = create_population( 4, &create_individual ); individual* ic; individual* im; ic = copy_individual( pop->individuals[0] ); im = mutate_individual( pop->individuals[0], 2 ); delete_individual( pop->individuals[1] ); pop->individuals[1] = ic; delete_individual( pop->individuals[2] ); pop->individuals[2] = im; evaluate_population( pop, &evaluate_individual ); printf( "i1: original, i2: copy, i3 mutant (degree 2)\n" ); print_population( pop, 0 ); delete_population( pop ); pop = create_population( 3, &create_individual ); individual* off; off = mate_individuals( pop->individuals[0], pop->individuals[1], 1 ); delete_individual( pop->individuals[2] ); pop->individuals[2] = off; evaluate_population( pop, &evaluate_individual ); printf( "i1: parent1, i2: parent2, i3 offspring\n" ); print_population( pop, 0 ); delete_population( pop ); */ /* pop = create_population( 100, &create_individual ); pop_fit = evaluate_population( pop, &evaluate_individual ); print_population_fitness( pop_fit, 0 ); pop_fit_sorted = sort_population( pop_fit ); printf( "Original Population Fitness\n" ); print_population_fitness( pop_fit, 0 ); printf( "Sorted Population Fitness\n" ); print_population_fitness( pop_fit_sorted, 0 ); */ }
/** * Principal function of the Genetic Algorithm * \fn shooter_repartition genetic algorithm heuristic for selection of towers **/ void shooter_repartition(const char * input_file_name, const float mutation_prob, const int population_size, const int nb_children, const int nb_iteration, const int dist, float taux_var, bool sim) { vector<tower>* towers = new vector<tower>(); int k, n; tower_parse(input_file_name, *towers, k, n); srand((unsigned int) time(NULL)); if (!is_easy_solution(k, n)) { vector<vector<tower>*>* population = generate_initial_pop(towers, k, dist, taux_var); sort_population(population); vector<vector<tower>*>* children; // population growth until reaching population_size while ((int) population->size() < population_size) { children = reproduction_iteration(nb_children, mutation_prob, population, towers, dist, taux_var); sort_population(children); for (int i = 0; i < (int) children->size(); i++) { if ((int) population->size() < population_size) { //do not oversize the population_size && !find_indiv(population, (*children)[i]) population->push_back((*children)[i]); } else { break; } } } // reordering population sort_population(population); // iteration of genetic algorithm for (int j = 0; j < nb_iteration; j++) { children = reproduction_iteration(nb_children, mutation_prob, population, towers, dist, taux_var); for (int i = 0; i < (int) children->size(); i++) { child_insertion((*children)[i], population); } } // printing the results for (int i = 0; i < 10 ; i++) { cout << i+1 << " : "; print_indiv((*population)[i]); } if(sim) simulate_day(population->front(), towers, dist, taux_var); for (vector<vector<tower>*>::iterator it = population->begin(); it != population->end(); it++){ delete *it; } delete population; } else { // generate all the permutations and verify which is the best; int tmp_eval = 0, best_eval = 0; int nb_perm = binomial_coef(n,k); int t_size = towers->size(); int *perm_indexes = (int*) malloc( k * sizeof(int)); //build index tracker to avoid repeating indivs vector<tower> *tmp_indiv, *best_indiv; tmp_indiv = new vector<tower>(); best_indiv = new vector<tower>(); for(int l = 0; l<k; l++){ perm_indexes[l] = l; tmp_indiv->push_back((*towers)[l]); } // spread var for variance spread_indiv_var(tmp_indiv, towers, taux_var); *best_indiv = *tmp_indiv; best_eval = check_dist(best_indiv, dist) ? eval_indiv(best_indiv) : 0; for (int j = 0; j < nb_perm; j++){ //build and eval permutation for (int i = 0; i < k ; i++){ tmp_indiv->at(i) = towers->at(perm_indexes[i]); } spread_indiv_var(tmp_indiv, towers, taux_var); if(check_dist(tmp_indiv,dist)) { tmp_eval = eval_indiv(tmp_indiv); if (tmp_eval > best_eval) { best_eval = tmp_eval; *best_indiv = *tmp_indiv; } } //update of indexes tracker perm_indexes[k-1]++; for( int m = k-2; m >= 0; m--){ //go to next permutation if (perm_indexes[m+1] > t_size-(k-m-1)){ perm_indexes[m]++; for(int p = m+1; p < k; p++){//correcting overflow perm_indexes[p] = perm_indexes[p-1]+1; } } } } print_indiv(best_indiv); if (sim) simulate_day(best_indiv, towers, dist, taux_var); free(perm_indexes); delete best_indiv; delete tmp_indiv; } delete towers; }
int main() { // Initial population std::vector<grid> population; int largest = 0; for(int i = 0; i < 100; ++i) { grid g; while(g.can_move()) { g.action(rand_action()); } population.emplace_back(g); } for(unsigned int i = 0; i < 100000; ++i) { unsigned int parent_a = tournament_selection(population); unsigned int parent_b = tournament_selection(population); grid child_a; grid child_b; one_point_crossover(population.at(parent_a).actions(), population.at(parent_b).actions(), child_a, child_b); population.emplace_back(child_a); population.emplace_back(child_b); sort_population(population); population.pop_back(); population.pop_back(); if(largest < population.at(0).score()) { largest = population.at(0).score(); std::cout << largest << std::endl; } sort_population_random(population); } sort_population(population); population.at(0).print(); for(auto const& p : population) { std::cout << p.score() << std::endl; } return 0; }