int main() { char gene[POOLSIZE][RULESIZE][LOCUSSIZE] ;//遺伝子プール char midgene[POOLSIZE*2][RULESIZE][LOCUSSIZE] ;//増殖中の遺伝子プール char lines[MAXLINES][LINESIZE] ;//キーワードのデータ int lineno ;//キーワードデータの行数 int generation ; srand(65535) ;//乱数の初期化 lineno=readlines(lines) ;//キーワードデータの読み込み initgene(gene) ;//遺伝子プールの初期化 for(generation=0;generation<GMAX;++generation){ printf("第%d世代 平均適応度 %f\n",generation,fave(gene,lines,lineno)) ; printgene(gene,lines,lineno) ;//遺伝子プールの出力 crossover(midgene,gene,lines,lineno) ;//交叉 mutation(midgene) ;//突然変異 selection(gene,midgene,lines,lineno) ;//選択 } printf("第%d世代 平均適応度 %f\n",generation,fave(gene,lines,lineno)) ; printgene(gene,lines,lineno) ;//遺伝子プールの出力 return 0 ; }
Population run_island(Configuration conf, Individual initial_individual){ // Random Number Generation std::default_random_engine eng(std::random_device{}()); std::uniform_real_distribution<> dist(-5, 5); // population generation Population population; population.push_back(initial_individual); // push the initial as it is. for (int i=1; i<conf.pop_size; i++) { Individual indi = mutate(conf, initial_individual); population.push_back(indi); } int generations = conf.num_generations; for (int g=0; g<generations; g++) { // first fitness calculation for (int i=0; i<conf.pop_size; i++) { population[i].score = fitness(population[i]); } // do sorting according to score std::sort(population.begin(), population.end(), compare); if (g != (conf.num_generations - 1)) { // crossover for (int i=0; i<(conf.pop_size / 2); i++) { crossover(conf, population[2*i], population[2*i+1]); } // mutate for (int i=0; i<conf.pop_size; i++) { population[i] = mutate(conf, population[i]); } } } return population; }
void GA::step() { pop_vector children; children.clear(); children.reserve(m_population_size); // elitism unsigned int elite_size = m_population_size * m_elitism_rate; for (unsigned int i=0; i<elite_size; i++) { children.push_back(m_population[i]->copy()); } // crossover while (children.size() < (m_population_size - elite_size)) { // select parents int p1 = roulette(); int p2 = roulette(); // crossover parents crossover(m_population[p1], m_population[p2], children); } // mutation mutate(children); // update population and save last population update(children); // evaluate fitness and sort evaluate_fitness(); // log, save generation log(); save_histograms(); }
static void reproduce_next_generation( network_config *config, individual_t** individuals, int size, int weight_cout, double rate){ int pos = size; int i, j, k; #pragma omp parallel for shared(config, pos,individuals,size,weight_cout,rate) private(i,j,k) for (i = 0; i < size; ++i) { for (j = i + 1; j < size; ++j) { for (k = 0; k < weight_cout; ++k) { double w1 = individuals[i]->weights[k]; double w2 = individuals[j]->weights[k]; crossover(config, w1,w2,individuals[pos]->weights+k,individuals[pos+1]->weights+k); mutation(config, individuals[pos]->weights+k,rate); mutation(config, individuals[pos+1]->weights+k,rate); } #pragma omp atomic pos+=2; } } }
void SolverEvolver::evolve() { sort_by_fitness(); std::vector<Individual> child_population; while (child_population.size() < population_size_) { Individual& c0 = select(); Individual& c1 = select(); if (rand_.NextBool(combination_p_)) { crossover(c0.genome, c1.genome); } mutate(c0.genome); mutate(c1.genome); child_population.push_back(c0); child_population.push_back(c1); } population_ = child_population; initate_population(); }
void main() { int i; int isUnique; Individual best; randomize(); worldInit(); // max 4 unique individuals, 5 and more last long to find while(uniques < 4){ populationInit(); fitness(); for(i = 0; i < maxGenerations; i++){ selection(); crossover(); mutation(); fitness(); best = getBestIndividual(); if(best.fitness == maxFitness){ isUnique = unique(best); if(isUnique){ theBestOf[uniques] = best; uniques++; } break; } } } printAxisOfBest(); }
std::vector<Genome> GenAlg::new_generation(std::vector<Genome> &last_generation) { generation_count++; reset(); std::sort(last_generation.begin(), last_generation.end(), myComparer); calculateStatistics(); std::vector<Genome> new_population; //get elites GetBest(my_params.num_elite, my_params.num_copies_of_elite, last_generation, new_population); //genetic algorithm loop while(new_population.size() < pop_size) { Genome mother = getRandomChromosome(); Genome father = getRandomChromosome(); std::vector<float> child1, child2; crossover(mother.weights, father.weights, child1, child2); mutate(child1); mutate(child2); new_population.push_back(Genome(child1, 0)); new_population.push_back(Genome(child2, 0)); } population = new_population; return population; }
int GAConjProblemForORGroupSolver::reproduction( ) { int pr = ( theIter2<2*numGenes ? 0 : 1 ); switch( roulette( 3 , prob[pr] ) ) { case 0: { int g = selectGene( ); *newGene[0] = *genes[g]; if( newGene[0]->mutation( ) ) return 1; } break; case 1: { int g = selectGene( ); *newGene[0] = *genes[g]; if( newGene[0]->permutation( ) ) return 1; } break; case 2: { int g1 = selectGene( ); int g2; { GACPforORGSolverGene *_tmp = genes[g1]; genes[g1] = 0; g2 = selectGene( ); genes[g1] = _tmp; } *newGene[0] = *genes[g1]; *newGene[1] = *genes[g2]; if( crossover( *newGene[0] , *newGene[1] ) ) return 2; } break; } return 0; }
int main(int argc, char *argv[]) { /*define local variables*/ clock_t start, end, t1, t2, t3, t4; int i,g; //counters //maxrank1; //the larger maxrank between oldpop and matepop //double tot; //sum of no. of inds in a rank in both oldpop and newpop FILE *rep_ptr, *lastit;/*File Pointers*/ if( argc == 2 ) printf("The argument supplied is %s\n", argv[1]); else if( argc > 2 ) printf("Too many arguments supplied.\n"); else printf("One argument expected.\n"); seed = (double)atof(argv[1]); if (seed<=0.0 || seed>=1.0) { printf("\n Entered seed value is wrong, seed value must be in (0,1) \n"); exit(11); } /*open files*/ rep_ptr=fopen ("output.out","w"); lastit = fopen("plot.out","w"); old_pop_ptr=&(oldpop); no_mut1=0; no_mut2=0; no_cross = 0; input(rep_ptr); /*obtain inputs*/ randomize(); /*initialize random no. generator*/ /*initialize population*/ init(old_pop_ptr); //debug /*printf("\n The initial population are:"); printf("\n DV1 DV2 RDV1 RDV2 fit1 fit2 cons1 cons2 Ocons cub_len rank tag eval gen"); for (i=0;i<popsize;i++) { printf("\n %d %d %.4f %.4f %.4f %.4f %.4f %.4f %.4f %.2e %d %d %d %d", old_pop_ptr->ind[i].chrom1[0],old_pop_ptr->ind[i].chrom1[1], old_pop_ptr->ind[i].chrom2[0],old_pop_ptr->ind[i].chrom2[1], old_pop_ptr->ind[i].fit[0],old_pop_ptr->ind[i].fit[1], old_pop_ptr->ind[i].cons[0],old_pop_ptr->ind[i].cons[1], old_pop_ptr->ind[i].overallcons,old_pop_ptr->ind[i].cub_len, old_pop_ptr->ind[i].rank,old_pop_ptr->ind[i].tag, old_pop_ptr->ind[i].eval,old_pop_ptr->ind[i].gen); }*/ /*decode integer chromosomes*/ if (no_intevar>0) { decode(old_pop_ptr); } //debug /*printf("\n The decoded initial population are:"); printf("\n DV1 DV2 D_DV1x D_DV1y D_DV1z D_DV1u D_DV1v D_DV1x D_DV1y D_DV1z D_DV1u D_DV1v"); for (i=0;i<popsize;i++) { printf("\n %d %d %.4f %.4f %.4f %.4f %.4f %.4f %.4f %.4f %.4f %.4f ", old_pop_ptr->ind[i].chrom1[0],old_pop_ptr->ind[i].chrom1[1], old_pop_ptr->ind[i].xchrom1[0],old_pop_ptr->ind[i].ychrom1[0], old_pop_ptr->ind[i].zchrom1[0],old_pop_ptr->ind[i].uchrom1[0], old_pop_ptr->ind[i].vchrom1[0],old_pop_ptr->ind[i].xchrom1[1], old_pop_ptr->ind[i].ychrom1[1],old_pop_ptr->ind[i].zchrom1[1], old_pop_ptr->ind[i].uchrom1[1],old_pop_ptr->ind[i].vchrom1[1]); }*/ /*initialize the rank array having different individuals at a particular rank to zero*/ new_pop_ptr=&(newpop); for (i=0;i<popsize;i++) { old_pop_ptr->rankno[i]=0; new_pop_ptr->rankno[i]=0; old_pop_ptr->ind[i].tag=1; } /*evaluation the objective and constraint functions of the current population*/ noeval=0; //assig generation number to each ind in matepop evaluatepop(old_pop_ptr, -1); for (i=0;i<popsize;i++) { old_pop_ptr->ind[i].tag=0; } //debug /*printf("\n After evaluation the initial oldpop are:"); printf("\n DV1 DV2 RDV1 RDV2 fit1 fit2 cons1 cons2 Ocons cub_len rank tag eval gen"); for (i=0;i<popsize;i++) { printf("\n %d %d %.4f %.4f %.4f %.4f %.4f %.4f %.4f %.2e %d %d %d %d", old_pop_ptr->ind[i].chrom1[0],old_pop_ptr->ind[i].chrom1[1], old_pop_ptr->ind[i].chrom2[0],old_pop_ptr->ind[i].chrom2[1], old_pop_ptr->ind[i].fit[0],old_pop_ptr->ind[i].fit[1], old_pop_ptr->ind[i].cons[0],old_pop_ptr->ind[i].cons[1], old_pop_ptr->ind[i].overallcons,old_pop_ptr->ind[i].cub_len, old_pop_ptr->ind[i].rank,old_pop_ptr->ind[i].tag, old_pop_ptr->ind[i].eval,old_pop_ptr->ind[i].gen); }*/ //rank the oldpop before copy it into midpop and selection if (no_cons==0) { old_pop_ptr->ind_ptr->overallcons=0.0; ranking(old_pop_ptr); } else { rankcon(old_pop_ptr); } //debug /*printf("\n After ranking/rankcon the initial oldpop are:"); printf("\n DV1 DV2 RDV1 RDV2 fit1 fit2 cons1 cons2 Ocons cub_len rank tag eval gen"); for (i=0;i<popsize;i++) { printf("\n %d %d %.4f %.4f %.4f %.4f %.4f %.4f %.4f %.2e %d %d %d %d", old_pop_ptr->ind[i].chrom1[0],old_pop_ptr->ind[i].chrom1[1], old_pop_ptr->ind[i].chrom2[0],old_pop_ptr->ind[i].chrom2[1], old_pop_ptr->ind[i].fit[0],old_pop_ptr->ind[i].fit[1], old_pop_ptr->ind[i].cons[0],old_pop_ptr->ind[i].cons[1], old_pop_ptr->ind[i].overallcons,old_pop_ptr->ind[i].cub_len, old_pop_ptr->ind[i].rank,old_pop_ptr->ind[i].tag, old_pop_ptr->ind[i].eval,old_pop_ptr->ind[i].gen); }*/ /***********************************************************************************/ /****************************GNENRATION LOOP STARTS*********************************/ for (g=0;g<no_gener;g++) { printf("\nGeneration number = %d\n", g+1); start=clock(); //fprintf(rep_ptr,"Population at Generation No. -->%d\n",g+1); //fprintf(rep_ptr,"#Generation No. -->%d\n",g+1); //fprintf(rep_ptr,"#Variable_vector Fitness_vector Constraint_violation Overall_violation\n"); old_pop_ptr=&(oldpop); mid_pop_ptr=&(midpop); mate_pop_ptr=&(matepop); new_pop_ptr=&(newpop); best_pop_ptr=&(bestpop); /**********************Two-member Tournament Selection***************************/ //copy oldpop into midpop-midpop is the exact copy of oldpop copypop(old_pop_ptr, mid_pop_ptr); //debug /*printf("\n ===================Copypop==========================\n"); printf("\n In generation loop:After copypop the initial oldpop are:"); printf("\n DV1 DV2 RDV1 RDV2 fit1 fit2 cons1 cons2 Ocons cub_len rank tag eval gen"); for (i=0;i<popsize;i++) { printf("\n %d %d %.4f %.4f %.4f %.4f %.4f %.4f %.4f %.2e %d %d %d %d", old_pop_ptr->ind[i].chrom1[0],old_pop_ptr->ind[i].chrom1[1], old_pop_ptr->ind[i].chrom2[0],old_pop_ptr->ind[i].chrom2[1], old_pop_ptr->ind[i].fit[0],old_pop_ptr->ind[i].fit[1], old_pop_ptr->ind[i].cons[0],old_pop_ptr->ind[i].cons[1], old_pop_ptr->ind[i].overallcons,old_pop_ptr->ind[i].cub_len, old_pop_ptr->ind[i].rank,old_pop_ptr->ind[i].tag, old_pop_ptr->ind[i].eval,old_pop_ptr->ind[i].gen); } printf("\n In generation loop:After copypop the midpop are:"); printf("\n DV1 DV2 RDV1 RDV2 fit1 fit2 cons1 cons2 Ocons cub_len rank tag eval gen"); for (i=0;i<popsize;i++) { printf("\n %d %d %.4f %.4f %.4f %.4f %.4f %.4f %.4f %.2e %d %d %d %d", mid_pop_ptr->ind[i].chrom1[0],mid_pop_ptr->ind[i].chrom1[1], mid_pop_ptr->ind[i].chrom2[0],mid_pop_ptr->ind[i].chrom2[1], mid_pop_ptr->ind[i].fit[0],mid_pop_ptr->ind[i].fit[1], mid_pop_ptr->ind[i].cons[0],mid_pop_ptr->ind[i].cons[1], mid_pop_ptr->ind[i].overallcons,mid_pop_ptr->ind[i].cub_len, mid_pop_ptr->ind[i].rank,mid_pop_ptr->ind[i].tag, mid_pop_ptr->ind[i].eval,mid_pop_ptr->ind[i].gen); }*/ //shuffle midpop and select from oldpop+midpop to form matepop selectt(old_pop_ptr, mid_pop_ptr, mate_pop_ptr); //debug /*printf("\n===================Select===========================\n"); printf("\n In generation loop:After selection the initial oldpop are:"); printf("\n DV1 DV2 RDV1 RDV2 fit1 fit2 cons1 cons2 Ocons cub_len rank tag eval gen"); for (i=0;i<popsize;i++) { printf("\n %d %d %.4f %.4f %.4f %.4f %.4f %.4f %.4f %.2e %d %d %d %d", old_pop_ptr->ind[i].chrom1[0],old_pop_ptr->ind[i].chrom1[1], old_pop_ptr->ind[i].chrom2[0],old_pop_ptr->ind[i].chrom2[1], old_pop_ptr->ind[i].fit[0],old_pop_ptr->ind[i].fit[1], old_pop_ptr->ind[i].cons[0],old_pop_ptr->ind[i].cons[1], old_pop_ptr->ind[i].overallcons,old_pop_ptr->ind[i].cub_len, old_pop_ptr->ind[i].rank,old_pop_ptr->ind[i].tag, old_pop_ptr->ind[i].eval,old_pop_ptr->ind[i].gen); } printf("\n In generation loop:After selection the midpop are:"); printf("\n DV1 DV2 RDV1 RDV2 fit1 fit2 cons1 cons2 Ocons cub_len rank tag eval gen"); for (i=0;i<popsize;i++) { printf("\n %d %d %.4f %.4f %.4f %.4f %.4f %.4f %.4f %.2e %d %d %d %d", mid_pop_ptr->ind[i].chrom1[0],mid_pop_ptr->ind[i].chrom1[1], mid_pop_ptr->ind[i].chrom2[0],mid_pop_ptr->ind[i].chrom2[1], mid_pop_ptr->ind[i].fit[0],mid_pop_ptr->ind[i].fit[1], mid_pop_ptr->ind[i].cons[0],mid_pop_ptr->ind[i].cons[1], mid_pop_ptr->ind[i].overallcons,mid_pop_ptr->ind[i].cub_len, mid_pop_ptr->ind[i].rank,mid_pop_ptr->ind[i].tag, mid_pop_ptr->ind[i].eval,mid_pop_ptr->ind[i].gen); } printf("\n In generation loop:After selection the matepop are:"); printf("\n DV1 DV2 RDV1 RDV2 fit1 fit2 cons1 cons2 Ocons cub_len rank tag eval gen"); for (i=0;i<popsize;i++) { printf("\n %d %d %.4f %.4f %.4f %.4f %.4f %.4f %.4f %.2e %d %d %d %d", mate_pop_ptr->ind[i].chrom1[0],mate_pop_ptr->ind[i].chrom1[1], mate_pop_ptr->ind[i].chrom2[0],mate_pop_ptr->ind[i].chrom2[1], mate_pop_ptr->ind[i].fit[0],mate_pop_ptr->ind[i].fit[1], mate_pop_ptr->ind[i].cons[0],mate_pop_ptr->ind[i].cons[1], mate_pop_ptr->ind[i].overallcons,mate_pop_ptr->ind[i].cub_len, mate_pop_ptr->ind[i].rank,mate_pop_ptr->ind[i].tag, mate_pop_ptr->ind[i].eval,mate_pop_ptr->ind[i].gen); }*/ /***********************************Crossover************************************/ //one-point crossover for chrom1 and SBX for chrom2 //before crossover and mutation set tag to zero for (i=0;i<popsize;i++) { new_pop_ptr->ind[i].tag=0; } crossover(new_pop_ptr, mate_pop_ptr); //debug /*printf("\n===================Crossover===========================\n"); printf("\n In generation loop:After crossover matepop, the initial oldpop are:"); printf("\n DV1 DV2 RDV1 RDV2 fit1 fit2 cons1 cons2 Ocons cub_len rank tag eval gen"); for (i=0;i<popsize;i++) { printf("\n %d %d %.4f %.4f %.4f %.4f %.4f %.4f %.4f %.2e %d %d %d %d", old_pop_ptr->ind[i].chrom1[0],old_pop_ptr->ind[i].chrom1[1], old_pop_ptr->ind[i].chrom2[0],old_pop_ptr->ind[i].chrom2[1], old_pop_ptr->ind[i].fit[0],old_pop_ptr->ind[i].fit[1], old_pop_ptr->ind[i].cons[0],old_pop_ptr->ind[i].cons[1], old_pop_ptr->ind[i].overallcons,old_pop_ptr->ind[i].cub_len, old_pop_ptr->ind[i].rank,old_pop_ptr->ind[i].tag, old_pop_ptr->ind[i].eval,old_pop_ptr->ind[i].gen); } printf("\n In generation loop:After crossover matepop, the midpop are:"); printf("\n DV1 DV2 RDV1 RDV2 fit1 fit2 cons1 cons2 Ocons cub_len rank tag eval gen"); for (i=0;i<popsize;i++) { printf("\n %d %d %.4f %.4f %.4f %.4f %.4f %.4f %.4f %.2e %d %d %d %d", mid_pop_ptr->ind[i].chrom1[0],mid_pop_ptr->ind[i].chrom1[1], mid_pop_ptr->ind[i].chrom2[0],mid_pop_ptr->ind[i].chrom2[1], mid_pop_ptr->ind[i].fit[0],mid_pop_ptr->ind[i].fit[1], mid_pop_ptr->ind[i].cons[0],mid_pop_ptr->ind[i].cons[1], mid_pop_ptr->ind[i].overallcons,mid_pop_ptr->ind[i].cub_len, mid_pop_ptr->ind[i].rank,mid_pop_ptr->ind[i].tag, mid_pop_ptr->ind[i].eval,mid_pop_ptr->ind[i].gen); } printf("\n In generation loop:After crossover matepop, the matepop are:"); printf("\n DV1 DV2 RDV1 RDV2 fit1 fit2 cons1 cons2 Ocons cub_len rank tag eval gen"); for (i=0;i<popsize;i++) { printf("\n %d %d %.4f %.4f %.4f %.4f %.4f %.4f %.4f %.2e %d %d %d %d", mate_pop_ptr->ind[i].chrom1[0],mate_pop_ptr->ind[i].chrom1[1], mate_pop_ptr->ind[i].chrom2[0],mate_pop_ptr->ind[i].chrom2[1], mate_pop_ptr->ind[i].fit[0],mate_pop_ptr->ind[i].fit[1], mate_pop_ptr->ind[i].cons[0],mate_pop_ptr->ind[i].cons[1], mate_pop_ptr->ind[i].overallcons,mate_pop_ptr->ind[i].cub_len, mate_pop_ptr->ind[i].rank,mate_pop_ptr->ind[i].tag, mate_pop_ptr->ind[i].eval,mate_pop_ptr->ind[i].gen); } printf("\n In generation loop:After crossover matepop, the newpop are:"); printf("\n DV1 DV2 RDV1 RDV2 fit1 fit2 cons1 cons2 Ocons cub_len rank tag eval gen"); for (i=0;i<popsize;i++) { printf("\n %d %d %.4f %.4f %.4f %.4f %.4f %.4f %.4f %.2e %d %d %d %d", new_pop_ptr->ind[i].chrom1[0],new_pop_ptr->ind[i].chrom1[1], new_pop_ptr->ind[i].chrom2[0],new_pop_ptr->ind[i].chrom2[1], new_pop_ptr->ind[i].fit[0],new_pop_ptr->ind[i].fit[1], new_pop_ptr->ind[i].cons[0],new_pop_ptr->ind[i].cons[1], new_pop_ptr->ind[i].overallcons,new_pop_ptr->ind[i].cub_len, new_pop_ptr->ind[i].rank,new_pop_ptr->ind[i].tag, new_pop_ptr->ind[i].eval,new_pop_ptr->ind[i].gen); }*/ /***********************************Mutation************************************/ //adjacent mutation for chrom1 and polynomial mutation for chrom2 //debug to check if tag assigning is working in mutation.c /*for(i=0;i<popsize;i++) { new_pop_ptr->ind[i].tag=0; }*/ mutation(new_pop_ptr); //debug /*printf("\n===================Mutation===========================\n"); printf("\n In generation loop:After mutating newpop, the initial oldpop are:"); printf("\n DV1 DV2 RDV1 RDV2 fit1 fit2 cons1 cons2 Ocons cub_len rank tag eval gen"); for (i=0;i<popsize;i++) { printf("\n %d %d %.4f %.4f %.4f %.4f %.4f %.4f %.4f %.2e %d %d %d %d", old_pop_ptr->ind[i].chrom1[0],old_pop_ptr->ind[i].chrom1[1], old_pop_ptr->ind[i].chrom2[0],old_pop_ptr->ind[i].chrom2[1], old_pop_ptr->ind[i].fit[0],old_pop_ptr->ind[i].fit[1], old_pop_ptr->ind[i].cons[0],old_pop_ptr->ind[i].cons[1], old_pop_ptr->ind[i].overallcons,old_pop_ptr->ind[i].cub_len, old_pop_ptr->ind[i].rank,old_pop_ptr->ind[i].tag, old_pop_ptr->ind[i].eval,old_pop_ptr->ind[i].gen); } printf("\n In generation loop:After mutating newpop, the midpop are:"); printf("\n DV1 DV2 RDV1 RDV2 fit1 fit2 cons1 cons2 Ocons cub_len rank tag eval gen"); for (i=0;i<popsize;i++) { printf("\n %d %d %.4f %.4f %.4f %.4f %.4f %.4f %.4f %.2e %d %d %d %d", mid_pop_ptr->ind[i].chrom1[0],mid_pop_ptr->ind[i].chrom1[1], mid_pop_ptr->ind[i].chrom2[0],mid_pop_ptr->ind[i].chrom2[1], mid_pop_ptr->ind[i].fit[0],mid_pop_ptr->ind[i].fit[1], mid_pop_ptr->ind[i].cons[0],mid_pop_ptr->ind[i].cons[1], mid_pop_ptr->ind[i].overallcons,mid_pop_ptr->ind[i].cub_len, mid_pop_ptr->ind[i].rank,mid_pop_ptr->ind[i].tag, mid_pop_ptr->ind[i].eval,mid_pop_ptr->ind[i].gen); } printf("\n In generation loop:After mutating newpop, the matepop are:"); printf("\n DV1 DV2 RDV1 RDV2 fit1 fit2 cons1 cons2 Ocons cub_len rank tag eval gen"); for (i=0;i<popsize;i++) { printf("\n %d %d %.4f %.4f %.4f %.4f %.4f %.4f %.4f %.2e %d %d %d %d", mate_pop_ptr->ind[i].chrom1[0],mate_pop_ptr->ind[i].chrom1[1], mate_pop_ptr->ind[i].chrom2[0],mate_pop_ptr->ind[i].chrom2[1], mate_pop_ptr->ind[i].fit[0],mate_pop_ptr->ind[i].fit[1], mate_pop_ptr->ind[i].cons[0],mate_pop_ptr->ind[i].cons[1], mate_pop_ptr->ind[i].overallcons,mate_pop_ptr->ind[i].cub_len, mate_pop_ptr->ind[i].rank,mate_pop_ptr->ind[i].tag, mate_pop_ptr->ind[i].eval,mate_pop_ptr->ind[i].gen); } printf("\n In generation loop:After mutating newpop, the newpop are:"); printf("\n DV1 DV2 RDV1 RDV2 fit1 fit2 cons1 cons2 Ocons cub_len rank tag eval gen"); for (i=0;i<popsize;i++) { printf("\n %d %d %.4f %.4f %.4f %.4f %.4f %.4f %.4f %.2e %d %d %d %d", new_pop_ptr->ind[i].chrom1[0],new_pop_ptr->ind[i].chrom1[1], new_pop_ptr->ind[i].chrom2[0],new_pop_ptr->ind[i].chrom2[1], new_pop_ptr->ind[i].fit[0],new_pop_ptr->ind[i].fit[1], new_pop_ptr->ind[i].cons[0],new_pop_ptr->ind[i].cons[1], new_pop_ptr->ind[i].overallcons,new_pop_ptr->ind[i].cub_len, new_pop_ptr->ind[i].rank,new_pop_ptr->ind[i].tag, new_pop_ptr->ind[i].eval,new_pop_ptr->ind[i].gen); }*/ /*************Decode the integer chromosome of the child population*************/ if (no_intevar>0) decode(new_pop_ptr); //debug /*printf("\n The decoded newpop after mutation are:"); printf("\n DV1 DV2 D_DV1x D_DV1y D_DV1z D_DV1u D_DV1v D_DV1x D_DV1y D_DV1z D_DV1u D_DV1v"); for (i=0;i<popsize;i++) { printf("\n %d %d %.4f %.4f %.4f %.4f %.4f %.4f %.4f %.4f %.4f %.4f ", new_pop_ptr->ind[i].chrom1[0],new_pop_ptr->ind[i].chrom1[1], new_pop_ptr->ind[i].xchrom1[0],new_pop_ptr->ind[i].ychrom1[0], new_pop_ptr->ind[i].zchrom1[0],new_pop_ptr->ind[i].uchrom1[0], new_pop_ptr->ind[i].vchrom1[0],new_pop_ptr->ind[i].xchrom1[1], new_pop_ptr->ind[i].ychrom1[1],new_pop_ptr->ind[i].zchrom1[1], new_pop_ptr->ind[i].uchrom1[1],new_pop_ptr->ind[i].vchrom1[1]); } printf("\n In generation loop:After decoding mutated newpop, the newpop are:"); printf("\n DV1 DV2 RDV1 RDV2 fit1 fit2 cons1 cons2 Ocons cub_len rank tag eval gen"); for (i=0;i<popsize;i++) { printf("\n %d %d %.4f %.4f %.4f %.4f %.4f %.4f %.4f %.2e %d %d %d %d", new_pop_ptr->ind[i].chrom1[0],new_pop_ptr->ind[i].chrom1[1], new_pop_ptr->ind[i].chrom2[0],new_pop_ptr->ind[i].chrom2[1], new_pop_ptr->ind[i].fit[0],new_pop_ptr->ind[i].fit[1], new_pop_ptr->ind[i].cons[0],new_pop_ptr->ind[i].cons[1], new_pop_ptr->ind[i].overallcons,new_pop_ptr->ind[i].cub_len, new_pop_ptr->ind[i].rank,new_pop_ptr->ind[i].tag, new_pop_ptr->ind[i].eval,new_pop_ptr->ind[i].gen); }*/ /*Evaluation the objective and constraint functions of the child population*/ t1=clock(); evaluatepop(new_pop_ptr, g); t2=clock(); //debug /*printf("\n================Evaluatepop in generation loop=================\n"); printf("\n In generation loop:After evaluatepop newpop, the newpop are:"); printf("\n DV1 DV2 RDV1 RDV2 fit1 fit2 cons1 cons2 Ocons cub_len rank tag eval gen"); for (i=0;i<popsize;i++) { printf("\n %d %d %.4f %.4f %.4f %.4f %.4f %.4f %.4f %.2e %d %d %d %d", new_pop_ptr->ind[i].chrom1[0],new_pop_ptr->ind[i].chrom1[1], new_pop_ptr->ind[i].chrom2[0],new_pop_ptr->ind[i].chrom2[1], new_pop_ptr->ind[i].fit[0],new_pop_ptr->ind[i].fit[1], new_pop_ptr->ind[i].cons[0],new_pop_ptr->ind[i].cons[1], new_pop_ptr->ind[i].overallcons,new_pop_ptr->ind[i].cub_len, new_pop_ptr->ind[i].rank,new_pop_ptr->ind[i].tag, new_pop_ptr->ind[i].eval,new_pop_ptr->ind[i].gen); }*/ /*if (no_cons==0) { new_pop_ptr->ind_ptr->overallcons=0.0; ranking(new_pop_ptr); } else { rankcon(new_pop_ptr); } printf("\n In generation loop:After ranking/rankcon newpop, the newpop are:"); printf("\n DV1 DV2 RDV1 RDV2 fit1 fit2 cons1 cons2 Ocons cub_len rank tag eval gen"); for (i=0;i<popsize;i++) { printf("\n %d %d %.4f %.4f %.4f %.4f %.4f %.4f %.4f %.2e %d %d %d %d", new_pop_ptr->ind[i].chrom1[0],new_pop_ptr->ind[i].chrom1[1], new_pop_ptr->ind[i].chrom2[0],new_pop_ptr->ind[i].chrom2[1], new_pop_ptr->ind[i].fit[0],new_pop_ptr->ind[i].fit[1], new_pop_ptr->ind[i].cons[0],new_pop_ptr->ind[i].cons[1], new_pop_ptr->ind[i].overallcons,new_pop_ptr->ind[i].cub_len, new_pop_ptr->ind[i].rank,new_pop_ptr->ind[i].tag, new_pop_ptr->ind[i].eval,new_pop_ptr->ind[i].gen); }*/ /************************Selection keeping fronts alive************************/ //Elitism and sharing implementation t3=clock(); keepalive(old_pop_ptr, new_pop_ptr, mate_pop_ptr, g+1); t4=clock(); //debug /*printf("\n\n=====================Keepalive==========================\n"); printf("\n In generation loop:After keepalive, the initial oldpop are:"); printf("\n DV1 DV2 RDV1 RDV2 fit1 fit2 cons1 cons2 Ocons cub_len rank tag eval gen"); for (i=0;i<popsize;i++) { printf("\n %d %d %.4f %.4f %.4f %.4f %.4f %.4f %.4f %.2e %d %d %d %d", old_pop_ptr->ind[i].chrom1[0],old_pop_ptr->ind[i].chrom1[1], old_pop_ptr->ind[i].chrom2[0],old_pop_ptr->ind[i].chrom2[1], old_pop_ptr->ind[i].fit[0],old_pop_ptr->ind[i].fit[1], old_pop_ptr->ind[i].cons[0],old_pop_ptr->ind[i].cons[1], old_pop_ptr->ind[i].overallcons,old_pop_ptr->ind[i].cub_len, old_pop_ptr->ind[i].rank,old_pop_ptr->ind[i].tag, old_pop_ptr->ind[i].eval,old_pop_ptr->ind[i].gen); } printf("\n In generation loop:After keepalive, the newpop are:"); printf("\n DV1 DV2 RDV1 RDV2 fit1 fit2 cons1 cons2 Ocons cub_len rank tag eval gen"); for (i=0;i<popsize;i++) { printf("\n %d %d %.4f %.4f %.4f %.4f %.4f %.4f %.4f %.2e %d %d %d %d", new_pop_ptr->ind[i].chrom1[0],new_pop_ptr->ind[i].chrom1[1], new_pop_ptr->ind[i].chrom2[0],new_pop_ptr->ind[i].chrom2[1], new_pop_ptr->ind[i].fit[0],new_pop_ptr->ind[i].fit[1], new_pop_ptr->ind[i].cons[0],new_pop_ptr->ind[i].cons[1], new_pop_ptr->ind[i].overallcons,new_pop_ptr->ind[i].cub_len, new_pop_ptr->ind[i].rank,new_pop_ptr->ind[i].tag, new_pop_ptr->ind[i].eval,new_pop_ptr->ind[i].gen); } printf("\n In generation loop:After keepalive, the newly formed matepop are:"); printf("\n DV1 DV2 RDV1 RDV2 fit1 fit2 cons1 cons2 Ocons cub_len rank tag eval gen"); for (i=0;i<popsize;i++) { printf("\n %d %d %.4f %.4f %.4f %.4f %.4f %.4f %.4f %.2e %d %d %d %d", mate_pop_ptr->ind[i].chrom1[0],mate_pop_ptr->ind[i].chrom1[1], mate_pop_ptr->ind[i].chrom2[0],mate_pop_ptr->ind[i].chrom2[1], mate_pop_ptr->ind[i].fit[0],mate_pop_ptr->ind[i].fit[1], mate_pop_ptr->ind[i].cons[0],mate_pop_ptr->ind[i].cons[1], mate_pop_ptr->ind[i].overallcons,mate_pop_ptr->ind[i].cub_len, mate_pop_ptr->ind[i].rank,mate_pop_ptr->ind[i].tag, mate_pop_ptr->ind[i].eval,mate_pop_ptr->ind[i].gen); }*/ /*if (no_intevar>0) decode(mate_pop_ptr);*/ //debug /*printf("\n The decoded matepop after keepalive are:"); printf("\n DV1 DV2 D_DV1x D_DV1y D_DV1z D_DV1u D_DV1v D_DV1x D_DV1y D_DV1z D_DV1u D_DV1v"); for (i=0;i<popsize;i++) { printf("\n %d %d %.4f %.4f %.4f %.4f %.4f %.4f %.4f %.4f %.4f %.4f ", mate_pop_ptr->ind[i].chrom1[0],mate_pop_ptr->ind[i].chrom1[1], mate_pop_ptr->ind[i].xchrom1[0],mate_pop_ptr->ind[i].ychrom1[0], mate_pop_ptr->ind[i].zchrom1[0],mate_pop_ptr->ind[i].uchrom1[0], mate_pop_ptr->ind[i].vchrom1[0],mate_pop_ptr->ind[i].xchrom1[1], mate_pop_ptr->ind[i].ychrom1[1],mate_pop_ptr->ind[i].zchrom1[1], mate_pop_ptr->ind[i].uchrom1[1],mate_pop_ptr->ind[i].vchrom1[1]); }*/ /*********************************Report printing*****************************/ //debug /*printf("\n In generation loop:Before selectbest, the old bestpop are:"); printf("\n DV1 DV2 RDV1 RDV2 fit1 fit2 cons1 cons2 Ocons cub_len rank tag eval gen"); for (i=0;i<popsize;i++) { printf("\n %d %d %.4f %.4f %.4f %.4f %.4f %.4f %.4f %.2e %d %d %d %d", best_pop_ptr->ind[i].chrom1[0],best_pop_ptr->ind[i].chrom1[1], best_pop_ptr->ind[i].chrom2[0],best_pop_ptr->ind[i].chrom2[1], best_pop_ptr->ind[i].fit[0],best_pop_ptr->ind[i].fit[1], best_pop_ptr->ind[i].cons[0],best_pop_ptr->ind[i].cons[1], best_pop_ptr->ind[i].overallcons,best_pop_ptr->ind[i].cub_len, best_pop_ptr->ind[i].rank,best_pop_ptr->ind[i].tag, best_pop_ptr->ind[i].eval,best_pop_ptr->ind[i].gen); }*/ //select best pop if (g==0) { //for the first generation form the first bestpop from matepop copypop(mate_pop_ptr, best_pop_ptr); } else { selectbest(mate_pop_ptr, best_pop_ptr, g); } //debug /*printf("\n In generation loop:After selectbest, the matepop are:"); printf("\n DV1 DV2 RDV1 RDV2 fit1 fit2 cons1 cons2 Ocons cub_len rank tag eval gen"); for (i=0;i<popsize;i++) { printf("\n %d %d %.4f %.4f %.4f %.4f %.4f %.4f %.4f %.2e %d %d %d %d", mate_pop_ptr->ind[i].chrom1[0],mate_pop_ptr->ind[i].chrom1[1], mate_pop_ptr->ind[i].chrom2[0],mate_pop_ptr->ind[i].chrom2[1], mate_pop_ptr->ind[i].fit[0],mate_pop_ptr->ind[i].fit[1], mate_pop_ptr->ind[i].cons[0],mate_pop_ptr->ind[i].cons[1], mate_pop_ptr->ind[i].overallcons,mate_pop_ptr->ind[i].cub_len, mate_pop_ptr->ind[i].rank,mate_pop_ptr->ind[i].tag, mate_pop_ptr->ind[i].eval,mate_pop_ptr->ind[i].gen); } printf("\n In generation loop:After selectbest, the bestpop are:"); printf("\n DV1 DV2 RDV1 RDV2 fit1 fit2 cons1 cons2 Ocons cub_len rank tag eval gen"); for (i=0;i<popsize;i++) { printf("\n %d %d %.4f %.4f %.4f %.4f %.4f %.4f %.4f %.2e %d %d %d %d", best_pop_ptr->ind[i].chrom1[0],best_pop_ptr->ind[i].chrom1[1], best_pop_ptr->ind[i].chrom2[0],best_pop_ptr->ind[i].chrom2[1], best_pop_ptr->ind[i].fit[0],best_pop_ptr->ind[i].fit[1], best_pop_ptr->ind[i].cons[0],best_pop_ptr->ind[i].cons[1], best_pop_ptr->ind[i].overallcons,best_pop_ptr->ind[i].cub_len, best_pop_ptr->ind[i].rank,best_pop_ptr->ind[i].tag, best_pop_ptr->ind[i].eval,best_pop_ptr->ind[i].gen); }*/ mogareport(g, best_pop_ptr, mate_pop_ptr, lastit); // output.out, /***************************Copy the newpop to oldpop**************************/ /***Assign oldpop the value of matepop(cross, mutate, keepalive_selection, so the original oldpop is updated***/ copypop(mate_pop_ptr, old_pop_ptr); for (i=0;i<popsize;i++) { old_pop_ptr->ind[i].tag=0; } /***************Print the fitness record for the last generation***************/ /* if (g==no_gener-1) { //for the last generation old_pop_ptr=&(matepop); for (f=0;f<popsize;f++) { //printing loop old_pop_ptr->ind_ptr=&(old_pop_ptr->ind[f]); //for all feasible and non-dominating solutions if ((old_pop_ptr->ind_ptr->overallcons<=0.0) && (old_pop_ptr->ind_ptr->rank==1)) { //if solution is feasible for (l=0;l<no_obj;l++) //for each objective fprintf(end_ptr, "%f\t", old_pop_ptr->ind_ptr->fit[l]); for (l=0;l<no_cons;l++) //for each constraint fprintf(end_ptr, "%f\t", old_pop_ptr->ind_ptr->cons[l]); if (no_cons>0) fprintf(end_ptr, "%f\t", old_pop_ptr->ind_ptr->overallcons); fprintf(end_ptr, "\n"); if (no_realvar>0) { //for real variables for (l=0;l<no_realvar;l++) fprintf(g_var, "%f\t", old_pop_ptr->ind_ptr->chrom2[l]); fprintf(g_var, " "); } //loop over realvar ends if (no_intevar>0) { //for integer variables for (l=0;l<no_intevar;l++) fprintf(g_var, "%d\t", old_pop_ptr->ind_ptr->chrom1[l]); } //loop over integer var ends fprintf(g_var,"\n"); } //feasibility check ends } //loop over f ends (printing) } //end of the last generation */ end=clock(); //printf("\n The time to do evaluatepop of this generation is %f seconds", ((double) t2-t1)/CLOCKS_PER_SEC); //printf("\n The time to doNS of this generation is %f seconds", ((double) t4-t3)/CLOCKS_PER_SEC); //printf("\n The time to do this generation is %f seconds", ((double) end-start)/CLOCKS_PER_SEC); //system(" rm -f en* "); printf("\n The %d th Generation has finished. ", g+1); } /*end of the ith generation*/ /****************************GNENRATION LOOP FINISHES*********************************/ /*************************************************************************************/ fprintf(rep_ptr, "No. OF CROSSOVER = %d\n", no_cross); fprintf(rep_ptr, "NO. OF MUTATION FOR INTEGER CHROMOSOME= %d\n", no_mut1); fprintf(rep_ptr, "NO. OF MUTATION FOR REAL-CODED CHROMOSOME= %d\n", no_mut2); fprintf(rep_ptr, "-----------------------------------------------------------------------\n"); fprintf(rep_ptr, "----------------Now you can look in the ourput files-------------------\n"); //close files fclose(rep_ptr); fclose(lastit); return(0); }
//run the genetic algorithm initialized before with some training parameters: //training location, training algorithm, desired error, max_epochs, epochs_between_reports //see "FeedForwardNNTrainer" class for more details //printtype specifies how much verbose will be the execution (PRINT_ALL,PRINT_MIN,PRINT_OFF) void GAFeedForwardNN::evolve(const int n, const float * params, const int printtype){ if(n<5){printf("TOO FEW PARAMETERS FOR TRAINING\n");exit(1);} int layers[nhidlayers+2]; int functs[nhidlayers+2]; float learningRate; float fitnesses[popsize]; float totfitness=0; float bestFitnessEver=0; FloatChromosome newpop[popsize]; layers[0]=trainingSet->getNumOfInputsPerInstance(); layers[nhidlayers+1]=trainingSet->getNumOfOutputsPerInstance(); //for each generation for(int gen=0;gen<generations;gen++){ float bestFitnessGeneration=0; int bestFitGenIndex=0; totfitness=0; printf("GENERATION NUMBER:\t%d\n\n",gen); //fitness evaluation of each individual for(int i=0;i<popsize;i++){ printf("\nINDIVIDUAL N:\t%d\n",i); //decode the chromosome hidden layers sizes for(int j=0;j<nhidlayers;j++){ layers[j+1]=chromosomes[i].getElement(j); } //decode the chromosome activation functions for each layer for(int j=0;j<nhidlayers+2;j++){ functs[j]=chromosomes[i].getElement(j+nhidlayers); } //decode the chromosome learning rate learningRate=chromosomes[i].getElement(nhidlayers+nhidlayers+2); float medium=0; FeedForwardNN mseT; //do a number of evaluations with different weights and average the results for(int n=0;n<numberofevaluations;n++){ //choose what to print based on user's choice int print=PRINT_ALL; if(printtype==PRINT_MIN){ if(n==0) print=PRINT_MIN; else print=PRINT_OFF; } if(printtype==PRINT_OFF) print=PRINT_OFF; //decode the chromosome into a real network FeedForwardNN net(nhidlayers+2,layers,functs); FeedForwardNNTrainer trainer; trainer.selectTrainingSet(*trainingSet); if(testSet!=NULL){ trainer.selectTestSet(*testSet); } trainer.selectNet(net); trainer.selectBestMSETestNet(mseT); float par[]={params[0],params[1],params[2],params[3],params[4],learningRate,0,SHUFFLE_ON,ERROR_LINEAR}; //do the training of the net and evaluate is MSE error medium+=trainer.train(9,par,print)/float(numberofevaluations); } //the fitness is computed as the inverse of the MSE fitnesses[i]=1.0f/medium; printf("FITNESS:\t%.2f\n\n",fitnesses[i]); //updates the best individual of the generation if(fitnesses[i]>bestFitnessGeneration){bestFitnessGeneration=fitnesses[i];bestFitGenIndex=i;} //if this is the best fitness ever it store the network in bestNet if(bestNet!=NULL) if(fitnesses[i]>bestFitnessEver){*bestNet=mseT;bestFitnessEver=fitnesses[i];} totfitness+=fitnesses[i]; } //the best individual is always carried to the next generation newpop[0]=chromosomes[bestFitGenIndex]; //generate the new population for(int i=1;i<popsize;i++){ //selection int firstmate=0,secondmate=0; //first mate switch(selectionalgorithm){ case ROULETTE_WHEEL: firstmate=rouletteWheel(popsize,fitnesses); break; case TOURNAMENT_SELECTION: firstmate=tournament(popsize,fitnesses,popsize/5+1); break; default: printf("SELECTION ALGORITHM NOT IMPLEMENTED YET\n");exit(1);break; } //second mate do{ switch(selectionalgorithm){ case ROULETTE_WHEEL: secondmate=rouletteWheel(popsize,fitnesses); break; case TOURNAMENT_SELECTION: secondmate=tournament(popsize,fitnesses,popsize/5+1); break; default: printf("SELECTION ALGORITHM NOT IMPLEMENTED YET\n");exit(1);break; } }while(firstmate==secondmate); FloatChromosome child; //do the crossover child=crossover(chromosomes[firstmate],chromosomes[secondmate],pcross); //and the mutation child=mutation(child,pmut,maxdimhiddenlayers,nhidlayers); //and put the child in the new generation newpop[i]=child; } //copy the new generation over the older one, wich is the one we will still use for(int i=0;i<popsize;i++){ chromosomes[i]=newpop[i]; } } }
void createNewPopulation(void) { //double newpop[POP_SIZE][NB_GENES]; _Bool newpop_bin[POP_SIZE][GENOME_LENGTH]; int elitism_counter = round(POP_SIZE*ELITISM_RATIO); double total_fitness = 0; // find minimum fitness to subtract it from sum double min_fitness = sortedfitness[POP_SIZE-1][0]; if (min_fitness<0) min_fitness=0; int i, j; // calculate total of fitness, used for roulette wheel selection for(i=0; i<POP_SIZE; i++) total_fitness+=fitness[i]; total_fitness-=min_fitness*POP_SIZE; //create new population for(i=0; i<POP_SIZE; i++) { //the elitism_counter best individuals are simply copied to the new population if(i<elitism_counter) { for(j=0;j<GENOME_LENGTH;j++) newpop_bin[i][j]=pop_bin[(int)sortedfitness[i][1]][j]; } //the other individuals are generated through the crossover of two parents else { //select non-elitist individual int ind1=0; if (ROULETTE_WHEEL==1) { double r=(double)rand()/(double)RAND_MAX; double fitness_counter=(sortedfitness[ind1][0]-min_fitness)/total_fitness; while( r > fitness_counter) { ind1++; fitness_counter+=(sortedfitness[ind1][0]-min_fitness)/total_fitness; } } else ind1=floor((double)rand()/(double)RAND_MAX*POP_SIZE*REPRODUCTION_RATIO); //if we will do crossover, select a second individual if ((double)rand()/(double)RAND_MAX < CROSSOVER_PROBABILITY) { int ind2=0; if (ROULETTE_WHEEL==1) do { double r=(double)rand()/(double)RAND_MAX; double fitness_counter=(sortedfitness[ind2][0]-min_fitness)/total_fitness; while(( r > fitness_counter) && (ind2 < POP_SIZE)){ ind2++; fitness_counter+=(sortedfitness[ind2][0]-min_fitness)/total_fitness; } } while (ind1==ind2); else do { ind2=floor((double)rand()/(double)RAND_MAX*POP_SIZE*REPRODUCTION_RATIO); } while (ind1==ind2); ind1=(int)sortedfitness[ind1][1]; ind2=(int)sortedfitness[ind2][1]; crossover(ind1, ind2, newpop_bin[i]); } else { //if no crossover was done, just copy selected individual directly for(j=0;j<GENOME_LENGTH;j++) newpop_bin[i][j]=pop_bin[(int)sortedfitness[ind1][1]][j]; } } } //mutate new population and copy back to pop for(i=0; i<POP_SIZE; i++) { if(i<elitism_counter) { //no mutation for elitists for(j=0;j<GENOME_LENGTH;j++) pop_bin[i][j]=newpop_bin[i][j]; } else { //mutate others with probability per gene for(j=0;j<GENOME_LENGTH;j++) if(((double)rand()/(double)RAND_MAX)<MUTATION_PROBABILITY) pop_bin[i][j]=mutate(newpop_bin[i][j]); else pop_bin[i][j]=newpop_bin[i][j]; } //reset fitness fitness[i]=-1; } return; }
void SimpleGA::evolve(Team *T) { Team *oldTeam, *newTeam, *delTeam; QArray<floatbot> botFitness; unsigned int teamSize, breed; int i; Bot *curbot; Bot *newbot1, *newbot2; oldTeam = T; newTeam = new Team; delTeam = new Team; teamSize = oldTeam->size(); botFitness.resize(teamSize); for (i=0; i< (int)teamSize; i++) { curbot = oldTeam->bot(i); botFitness[i].fit = curbot->fitnessFunction(); botFitness[i].bot = i; } botFitness.sort(); // reverse fitness array for (i=0; i<(int)(teamSize/2); i++) { floatbot temp; temp.fit = botFitness[i].fit; temp.bot = botFitness[i].bot; botFitness.at(i).fit = botFitness.at(teamSize-i-1).fit; botFitness.at(i).bot = botFitness.at(teamSize-i-1).bot; botFitness.at(teamSize-i-1).fit = temp.fit; botFitness.at(teamSize-i-1).bot = temp.bot; } // add the good bots to the new team breed = teamSize / 2; // number of bots to breed if ( (breed/2)*2 != breed ) breed--; // make sure its even for (i=0; i<(int)(teamSize - breed); i++) { // number of bots to throw out is the number bred, so keep the number not thrown out curbot = oldTeam->bot(botFitness[i].bot); newTeam->insertBot(curbot); } for (i=(teamSize - breed); i<(int)teamSize; i++) { // put bots to be deleted on a separate team curbot = oldTeam->bot(botFitness[i].bot); delTeam->insertBot(curbot); } while (oldTeam->size() > 0) { // remove bots from oldTeam curbot = oldTeam->removeBot(0); } while (delTeam->size() > 0) { // actually delete bots curbot = delTeam->removeBot(0); delete curbot; } // do the crossover of the best bots for (i=0; i<(int)breed; i+=2) { newbot1 = new Bot(oldTeam); newbot2 = new Bot(oldTeam); crossover(newTeam->bot(i), newTeam->bot(i+1), newbot1, newbot2); newTeam->insertBot(newbot1); newTeam->insertBot(newbot2); } // mutate a bot given the mutation rate for (i=0; i<(int)teamSize; i++) { double rnd = Random::randd(0,1); if (rnd < MutationRate) { curbot = newTeam->bot(i); curbot->mutateBot(); } } // copy bots back into old team while (newTeam->size() > 0) { curbot = newTeam->removeBot(0); oldTeam->insertBot(curbot); } oldTeam->generations(oldTeam->generations() + 1); delete delTeam; delete newTeam; }
main() { /*Some Local variables to this Problem (Counters And some other pointers*/ int i,j,l,f,maxrank1; float *ptr,tot; FILE *rep_ptr, *gen_ptr, *rep2_ptr, *end_ptr, *g_var, *lastit; /*File Pointers*/ rep_ptr = fopen("output.out","w"); gen_ptr =fopen("all_fitness.out","w"); rep2_ptr = fopen("ranks.out","w"); end_ptr = fopen("final_fitness.out","w"); g_var = fopen("final_var.out","w"); lastit = fopen("plot.out","w"); /*Opening the files*/ old_pop_ptr = &(oldpop); nmut = 0; ncross = 0; /*Get the input from the file input.h*/ input(rep_ptr); fprintf(rep_ptr,"Results in a file\n"); fprintf(end_ptr,"# Last generation population (Feasible and non-dominated)\n"); fprintf(end_ptr,"# Fitness_vector (first %d) Constraint_violation (next %d) Overall_penalty\n",nfunc,ncons); fprintf(g_var,"#Feasible Variable_vectors for non-dominated solutions at last generation\n"); fprintf(g_var,"# Real (first %d) Binary (next %d)\n",nvar,nchrom); fprintf(lastit,"# Feasible and Non-dominated Objective Vector\n"); /*Initialize the random no generator*/ warmup_random(seed); /*Binary Initializaton*/ if (nchrom > 0) init(old_pop_ptr); if (nvar > 0) realinit(old_pop_ptr); old_pop_ptr = &(oldpop); // decode binary strings decode(old_pop_ptr); old_pop_ptr = &(oldpop); new_pop_ptr = &(newpop); for(j = 0;j < popsize;j++) { /*Initializing the Rank array having different individuals at a particular rank to zero*/ old_pop_ptr->rankno[j] = 0; new_pop_ptr->rankno[j] = 0; } old_pop_ptr = &(oldpop); func(old_pop_ptr); /*Function Calculaiton*/ fprintf(rep_ptr,"----------------------------------------------------\n"); fprintf(rep_ptr,"Statistics at Generation 0 ->\n"); fprintf(rep_ptr,"--------------------------------------------------\n"); /********************************************************************/ /*----------------------GENERATION STARTS HERE----------------------*/ for (i = 0;i < gener;i++) { printf("Generation = %d\n",i+1); old_pop_ptr = &(oldpop); mate_pop_ptr = &(matepop); fprintf(rep_ptr,"Population at generation no. -->%d\n",i+1); fprintf(gen_ptr,"#Generation No. -->%d\n",i+1); fprintf(gen_ptr,"#Variable_vector Fitness_vector Constraint_violation Overall_penalty\n"); /*--------SELECT----------------*/ nselect(old_pop_ptr ,mate_pop_ptr ); new_pop_ptr = &(newpop); mate_pop_ptr = &(matepop); /*CROSSOVER----------------------------*/ if (nchrom > 0) { if(optype == 1) { crossover(new_pop_ptr ,mate_pop_ptr ); /*Binary Cross-over*/ } if(optype == 2) { unicross(new_pop_ptr ,mate_pop_ptr ); /*Binary Uniform Cross-over*/ } } if (nvar > 0) realcross(new_pop_ptr ,mate_pop_ptr ); /*Real Cross-over*/ /*------MUTATION-------------------*/ new_pop_ptr = &(newpop); if (nchrom > 0) mutate(new_pop_ptr ); /*Binary Mutation */ if (nvar > 0) real_mutate(new_pop_ptr ); /*Real Mutation*/ new_pop_ptr = &(newpop); /*-------DECODING----------*/ if(nchrom > 0) decode(new_pop_ptr ); /*Decoding for binary strings*/ /*----------FUNCTION EVALUATION-----------*/ new_pop_ptr = &(newpop); func(new_pop_ptr ); /*-------------------SELECTION KEEPING FRONTS ALIVE--------------*/ old_pop_ptr = &(oldpop); new_pop_ptr = &(newpop); mate_pop_ptr = &(matepop); /*Elitism And Sharing Implemented*/ keepalive(old_pop_ptr ,new_pop_ptr ,mate_pop_ptr,i+1); mate_pop_ptr = &(matepop); if(nchrom > 0) decode(mate_pop_ptr ); mate_pop_ptr = &(matepop); /*------------------REPORT PRINTING--------------------------------*/ report(i ,old_pop_ptr ,mate_pop_ptr ,rep_ptr ,gen_ptr, lastit ); /*==================================================================*/ /*----------------Rank Ratio Calculation------------------------*/ new_pop_ptr = &(matepop); old_pop_ptr = &(oldpop); /*Finding the greater maxrank among the two populations*/ if(old_pop_ptr->maxrank > new_pop_ptr->maxrank) maxrank1 = old_pop_ptr->maxrank; else maxrank1 = new_pop_ptr->maxrank; fprintf(rep2_ptr,"--------RANK AT GENERATION %d--------------\n",i+1); fprintf(rep2_ptr,"Rank old ranks new ranks rankratio\n"); for(j = 0;j < maxrank1 ; j++) { /*Sum of the no of individuals at any rank in old population and the new populaion*/ tot = (old_pop_ptr->rankno[j])+ (new_pop_ptr->rankno[j]); /*Finding the rank ratio for new population at this rank*/ new_pop_ptr->rankrat[j] = (new_pop_ptr->rankno[j])/tot; /*Printing this rank ratio to a file called ranks.dat*/ fprintf(rep2_ptr," %d\t %d\t\t %d\t %f\n",j+1,old_pop_ptr->rankno[j],new_pop_ptr->rankno[j],new_pop_ptr->rankrat[j]); } fprintf(rep2_ptr,"-----------------Rank Ratio-------------------\n"); /*==================================================================*/ /*=======Copying the new population to old population======*/ old_pop_ptr = &(oldpop); new_pop_ptr = &(matepop); for(j = 0;j < popsize;j++) { old_pop_ptr->ind_ptr = &(old_pop_ptr->ind[j]); new_pop_ptr->ind_ptr = &(new_pop_ptr->ind[j]); if(nchrom > 0) { /*For Binary GA copying of the chromosome*/ for(l = 0;l < chrom;l++) old_pop_ptr->ind_ptr->genes[l]=new_pop_ptr->ind_ptr->genes[l]; for(l = 0;l < nchrom;l++) old_pop_ptr->ind_ptr->xbin[l] = new_pop_ptr->ind_ptr->xbin[l]; } if(nvar > 0) { /*For Real Coded GA copying of the chromosomes*/ for(l = 0;l < nvar;l++) old_pop_ptr->ind_ptr->xreal[l] = new_pop_ptr->ind_ptr->xreal[l]; } /*Copying the fitness vector */ for(l = 0 ; l < nfunc ;l++) old_pop_ptr->ind_ptr->fitness[l] = new_pop_ptr->ind_ptr->fitness[l]; /*Copying the dummy fitness*/ old_pop_ptr->ind_ptr->cub_len = new_pop_ptr->ind_ptr->cub_len; /*Copying the rank of the individuals*/ old_pop_ptr->ind_ptr->rank = new_pop_ptr->ind_ptr->rank; /*Copying the error and constraints of the individual*/ old_pop_ptr->ind_ptr->error = new_pop_ptr->ind_ptr->error; for(l = 0;l < ncons;l++) { old_pop_ptr->ind_ptr->constr[l] = new_pop_ptr->ind_ptr->constr[l]; } /*Copying the flag of the individuals*/ old_pop_ptr->ind_ptr->flag = new_pop_ptr->ind_ptr->flag; } // end of j maxrank1 = new_pop_ptr->maxrank ; /*Copying the array having the record of the individual at different ranks */ for(l = 0;l < popsize;l++) { old_pop_ptr->rankno[l] = new_pop_ptr->rankno[l]; } /*Copying the maxrank */ old_pop_ptr->maxrank = new_pop_ptr->maxrank; /*Printing the fitness record for last generation in a file last*/ if(i == gener-1) { // for the last generation old_pop_ptr = &(matepop); for(f = 0;f < popsize ; f++) // for printing { old_pop_ptr->ind_ptr = &(old_pop_ptr->ind[f]); if ((old_pop_ptr->ind_ptr->error <= 0.0) && (old_pop_ptr->ind_ptr->rank == 1)) // for all feasible solutions and non-dominated solutions { for(l = 0;l < nfunc;l++) fprintf(end_ptr,"%f\t",old_pop_ptr->ind_ptr->fitness[l]); for(l = 0;l < ncons;l++) { fprintf(end_ptr,"%f\t",old_pop_ptr->ind_ptr->constr[l]); } if (ncons > 0) fprintf(end_ptr,"%f\t",old_pop_ptr->ind_ptr->error); fprintf(end_ptr,"\n"); if (nvar > 0) { for(l = 0;l < nvar ;l++) { fprintf(g_var,"%f\t",old_pop_ptr->ind_ptr->xreal[l]); } fprintf(g_var," "); } if(nchrom > 0) { for(l = 0;l < nchrom;l++) { fprintf(g_var,"%f\t",old_pop_ptr->ind_ptr->xbin[l]); } } fprintf(g_var,"\n"); } // feasibility check } // end of f (printing) } // for the last generation } // end of i /* Generation Loop Ends */ /************************************************************************/ fprintf(rep_ptr,"NO. OF CROSSOVER = %d\n",ncross); fprintf(rep_ptr,"NO. OF MUTATION = %d\n",nmut); fprintf(rep_ptr,"------------------------------------------------------------\n"); fprintf(rep_ptr,"---------------------------------Thanks---------------------\n"); fprintf(rep_ptr,"-------------------------------------------------------------\n"); printf("NOW YOU CAN LOOK IN THE FILE OUTPUT2.DAT\n"); /*Closing the files*/ fclose(rep_ptr); fclose(gen_ptr); fclose(rep2_ptr); fclose(end_ptr); fclose(g_var); fclose(lastit); }
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; }
/** * <h3>Algoritmos Genéticos</h3> * <p>A função ga_fo_01 tem como objetivo usar uma implementação simples de GA para * otimizar a função <i>F(x)=x*sin(10*pi*x)+1<i> em um espaço de busca definido.</p> * @file main.c * @version 0.0 * @autor Gill Velleda Gonzales * @param a Início do espaço de busca * @param step Valor de incremento * @param b Fim do espaço de busca * @param otimizacao 0 Minimiza a FO != 0 Maximiza * @pop_size tamanho da população (bug máximo 12 indivíduos) * @return * Valor otimizado de <i><b>fo_01</b></i> no espaço definido por <b>a</b> até <b>b</b> passo <b>step</b> * * @ToDo * * */ long double ga_fo_01(double a, double step, double b, int otimizacao, int pop_size) { //Inicialização int **pop, **pop_mat, //População Intermediaria size_pop = pop_size, //População genes = 12, //Tamanho de Cromossomos (Cadeia de Bits) geracao = 1, i, j, count_ev = 0, //Contador de não-evoluções ou gerações iguais que não evoluirão; nev_max = 10, //Número máximo de populações iguais que não evoluirão, critério de parada *cr_opt; float *v_ap, taxa_cros = 0.9, taxa_mutate = 0.3; printf("\nAlgoritmo Genético Processando"); //Espaço de Busca printf("\nEspaço de busca de %.3f a %.3f incrementado de %.3f", a, b, step); //Gerando a população printf("\nGerando a População ...\nCromossos: 12 genes binários\nPopulação: %d indivíduos", size_pop); pop = gerarPopIni(size_pop, genes, a, step, b); //LOOP do { if (geracao > 1) free(pop_mat); //Liberando memória - Descarta a população de Pais //Avalia População printf("\nAvaliando a população (Geração: %d)", geracao); v_ap = avaliarPop(pop, size_pop, genes, a, b); //Selecionar mais aptos printf("\n Selecionando mais aptos:\n\t-gerando mating-pool\n"); pop_mat = selecaoTorneio(pop, v_ap, size_pop, genes, otimizacao); printf("\n População Original - Geracao %d:\n", geracao); printPop(pop, size_pop, genes); printf("\n\n População Intermediária:\n"); printPop(pop_mat, size_pop, genes); free(pop); //Liberando memória - Descarta a população original //Operações de Crossover e Mutação pop = crossover(pop_mat, taxa_cros, size_pop, genes); printf("\n\n Nova Geração pós-cruzamentos:"); printPop(pop, size_pop, genes); //Mutação pop = mutate(pop, taxa_mutate, size_pop, genes); printf("\n\n Nova Geração pós-mutações:"); printPop(pop, size_pop, genes); //Geração de nova população geracao++; //count_nev = final_ga(pop, v_ap, size_pop, genes, count_nev); count_ev = final_ga(pop_mat, v_ap, size_pop, genes, count_ev); printf("\t-----------CONTADOR %d----------\n", count_ev); printf("\n||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||\n"); if (count_ev == nev_max) { /* aloca espaço para o cromossomo otimo */ cr_opt = (int *) calloc(genes, sizeof (int)); cr_opt = getOtimo(pop_mat, otimizacao, size_pop); } } while (count_ev < nev_max); //&& geracao <= 100); //FIM LOOP printf("\n GA- Finalizado:\n\tPopulação dos mais aptos:\n"); printPop(pop_mat, size_pop, genes); printf("\n GA- Finalizado:\n\tx = %.3f Valor ótimo;\n\t y = %.3f", bitsToFloat(cr_opt), fo_01(bitsToFloat(cr_opt))); printf("\n Tamanho da População: %d", size_pop); printf("\n Genes por Cromossomos: %d", genes); printf("\n Taxa de Cruzamento: %.1f", taxa_cros); printf("\n Taxa de Mutação: %.1f", taxa_mutate); printf("\n Última Geração: %d:\n", geracao); printf("\n\n"); }
int main(int argc, char **argv) { int maxprims, maxfigs, maxpts, state, maxindivs, namelen; int nfigs, nprims, npts, setsize, iters; int ext; struct Individ *indivs, tmp; struct Figure *figs, *figset; char *str; ssize_t chread; size_t n; int i, j, k, m, nindivs; struct NestAttrs attrs; str = NULL; n = 0; maxfigs = 128; namelen = 2048; state = STATE_NEWFIG; nfigs = nprims = npts = 0; figs = (struct Figure*)xmalloc(sizeof(struct Figure) * maxfigs); while ((chread = getline(&str, &n, stdin)) != -1) { double x, y; trim(str); if (state == STATE_NEWFIG) { figs[nfigs].name = (char*)xmalloc(sizeof(char) * namelen); sscanf(str, "%s %d %d\n", figs[nfigs].name, &figs[nfigs].quant, &figs[nfigs].angstep); state = STATE_PRIM; maxpts = 2048; maxprims = 128; figs[nfigs].prims = (struct Primitive*)xmalloc(sizeof(struct Primitive) * maxprims); figs[nfigs].prims[nprims].pts = (struct Point*)xmalloc(sizeof(struct Point) * maxpts); // free(str); str = NULL; continue; } if (strcmp(str, FIG_SEPAR) == 0) { state = STATE_NEWFIG; figs[nfigs].prims[nprims].npts = npts; nprims++; figs[nfigs].id = nfigs; figs[nfigs].nprims = nprims; nfigs++; if (nfigs == maxfigs) { maxfigs *= 2; figs = (struct Figure*)xrealloc(figs, sizeof(struct Figure) * maxfigs); } nprims = 0; npts = 0; // free(str); str = NULL; continue; } if (strcmp(str, PRIM_SEPAR) == 0) { figs[nfigs].prims[nprims].npts = npts; nprims++; if (nprims == maxprims) { maxprims *= 2; figs[nfigs].prims = (struct Primitive*)xrealloc(figs[nfigs].prims, sizeof(struct Primitive) * maxprims); } maxpts = 2048; figs[nfigs].prims[nprims].pts = (struct Point*)xmalloc(sizeof(struct Point) * maxpts); npts = 0; // free(str); str = NULL; continue; } sscanf(str, "%lf %lf\n", &x, &y); figs[nfigs].prims[nprims].pts[npts].x = x; figs[nfigs].prims[nprims].pts[npts].y = y; npts++; if (npts == maxpts) { maxprims *= 2; figs[nfigs].prims[nprims].pts = (struct Point*)xrealloc(figs[nfigs].prims[nprims].pts, sizeof(struct Point) * maxpts); } // free(str); str = NULL; } for (i = 0; i < nfigs; i++) { figinit(&figs[i]); } attrs.width = atof(argv[1]); attrs.height = atof(argv[2]); attrs.type = ROTNEST_DEFAULT; attrs.logfile = fopen("./logfile", "w+"); figset = makeset(figs, nfigs, &setsize); qsort(figset, setsize, sizeof(struct Figure), figcmp); maxindivs = 1024; indivs = (struct Individ*)xmalloc(sizeof(struct Individ) * maxindivs); indivs[0].genom = (int*)xmalloc(sizeof(int) * setsize); indivs[0].gensize = 0; rotnest(figset, setsize, &indivs[0], &attrs); nindivs = 1; ext = 0; iters = atoi(argv[3]); for (i = 0; i < iters && !ext; i++) { int nnew = 0, equal = 0, oldn; printf("nindivs=%d\n", nindivs); for (j = 0; j < 1; j++) { printf("ind=%d height=%lf gensize=%d genom: ", i, indivs[j].height, indivs[j].gensize); for (k = 0; k < indivs[j].gensize; k++) { printf("%d ", indivs[j].genom[k]); } printf("\n"); } printf("\n"); oldn = nindivs; for (j = 0; j < oldn - 1 && nnew < 30; j++) { struct Individ heirs[2]; if (indivs[j].gensize == indivs[j + 1].gensize) { int res; res = crossover(&indivs[j], &indivs[j + 1], &heirs[0], setsize); crossover(&indivs[j + 1], &indivs[j], &heirs[1], setsize); if (res < 0) { break; } } else { break; } for (k = 0; k < 2; k++) { for (m = 0; m < nindivs; m++) { equal = gensequal(&heirs[k], &indivs[m]) || gensequal2(&heirs[k], &indivs[m], figset); if (equal) { break; } } if (!equal) { nnew++; rotnest(figset, setsize, &heirs[k], &attrs); indivs[nindivs] = heirs[k]; nindivs++; if (nindivs == maxindivs) { maxindivs *= 2; indivs = (struct Individ*)xrealloc(indivs, sizeof(struct Individ) * maxindivs); } } else { destrindiv(&heirs[k]); } } } equal = 0; while (nnew == 0) { int res; res = mutate(&indivs[0], &tmp, setsize); if (res < 0) { ext = 1; break; } equal = 0; for (j = 0; j < nindivs; j++) { equal = gensequal(&tmp, &indivs[j]) || gensequal2(&tmp, &indivs[j], figset); if (equal) { break; } } if (!equal) { nnew++; rotnest(figset, setsize, &tmp, &attrs); indivs[nindivs] = tmp; nindivs++; if (nindivs == maxindivs) { maxindivs *= 2; indivs = (struct Individ*)xrealloc(indivs, sizeof(struct Individ) * maxindivs); } } else { destrindiv(&tmp); } } qsort(indivs, nindivs, sizeof(struct Individ), gencmp); } for (i = 0; i < indivs[0].npos; i++) { double a, b, c, d, e, f; a = indivs[0].posits[i].fig.mtx[0][0]; b = indivs[0].posits[i].fig.mtx[1][0]; c = indivs[0].posits[i].fig.mtx[0][1]; d = indivs[0].posits[i].fig.mtx[1][1]; e = indivs[0].posits[i].fig.mtx[0][2]; f = indivs[0].posits[i].fig.mtx[1][2]; printf("%s\n", indivs[0].posits[i].fig.name); printf("matrix(%lf, %lf, %lf, %lf, %lf, %lf)\n:\n", a, b, c, d, e, f); } // ppos2file("./drawposits", indivs[0].posits, indivs[0].npos); return 0; }
/** * Main method of genetic algorithm. * @param config Struct with configuraiton parameters like population size, number of gens, etc... * @see struct Chromosome_configuration */ int genetic_main(Ptr_config config) { #ifdef TRACE printf("---> genetic_main.\n"); fflush(stdout); #endif const int TOTAL_CHROM = config->total_chrom; const int MAX_ITER = config->max_iter; const int MAX_REP_MEJOR = config->max_iter_best; const int CHROMOSOME_LENGTH = config->chrom_length; int rep_best, fin, ale1, ale2, eti1, eti2, iter, i, validos, np; double best; Ptr_Chromosome *List_Chromosome; // Array of chromosmes. Population. rep_best = 10; fin = 0; ale1 = 0; ale2 = 0; eti1 = 0; eti2 = 0; iter = 0; i = 0; validos = 0; /**< Percentage of valid chromosomes */ // Time measurement variables struct timeval *tv; struct timezone *tz; long tf, ti, si, sf; double tiempo, mut; tv = (struct timeval *)malloc(sizeof(struct timeval)); tz = NULL; gettimeofday(tv, tz); si = (tv->tv_sec); ti = (tv->tv_usec); ti = si * 1000000 + ti; srand (time (NULL)); /* * ########################################## * ###### GENERATE INITIAL POPULATION ####### * ########################################## */ List_Chromosome = (Ptr_Chromosome*)malloc(TOTAL_CHROM * sizeof(Ptr_Chromosome)); // Canditate loop to be paralelized with OpenMP for ( i = 0 ; i < TOTAL_CHROM ; i++ ) { List_Chromosome[i] = create_chromosome(i, CHROMOSOME_LENGTH); } rep_best = 0; best = -1.0; //se le da un valor que no tiene ninguno para que no coincida // ######### MAIN LOOP ########## while ( fin == 0 ) { /* * ########################################### * ###### EVALUATION AND CLASSIFICATION ###### * ########################################### */ // Canditate loop to be paralelized with OpenMP for ( i = 0 ; i < TOTAL_CHROM ; i++ ) { if ( ((List_Chromosome[i])->evaluation == BAD_CHROM) && (good_chromosome(List_Chromosome[i], CHROMOSOME_LENGTH) == 1) ) { List_Chromosome[i]->evaluation = evaluate_chromosome(List_Chromosome[i], CHROMOSOME_LENGTH); }; }; classify_chromosome(List_Chromosome, TOTAL_CHROM); best = List_Chromosome[0]->evaluation; /* * ##################################### * ###### CHROMOSOME REPRODUCTION ###### * ##################################### */ #ifdef TRACE printf("Reproduccion de los cromosomas\n"); fflush(stdout); #endif // Canditate loop to be paralelized with OpenMP for ( i = TOTAL_CHROM / 2 ; i < TOTAL_CHROM - 1 ; i = i + 2 ) { // Elimination of the worst half part of the population eti1 = List_Chromosome[i]->id; eti2 = List_Chromosome[i + 1]->id; ale1 = (int)(rand() % (TOTAL_CHROM / 2)); ale2 = (int)(rand() % (TOTAL_CHROM / 2)); free_chromosome(List_Chromosome[i]); free_chromosome(List_Chromosome[i + 1]); List_Chromosome[i] = NULL; List_Chromosome[i + 1] = NULL; crossover(List_Chromosome[ale1], List_Chromosome[ale2], &List_Chromosome[i], &List_Chromosome[i + 1], CHROMOSOME_LENGTH, ONE_POINT_CROSS); List_Chromosome[i]->id = eti1; List_Chromosome[i + 1]->id = eti2; } /* * #################################### * ####### MUTATION ######## * #################################### */ mut = (double)(rand() % (100)); if ( mut < 10 ) //el 10% de que haya mutacion { ale1 = (int)(rand() % (TOTAL_CHROM / 2)); mutate(List_Chromosome[ale1], CHROMOSOME_LENGTH, BIT_STRING_MUTATION); }; iter++; // CHECK END CONDITIONS if ((best == (List_Chromosome[0])->evaluation) && (best != BAD_CHROM)) rep_best++; else { rep_best = 0; best = (List_Chromosome[0])->evaluation; }; if ( (rep_best == MAX_REP_MEJOR) || (iter == MAX_ITER) ) fin = 1; /* * ##################################################################### * ###### EVALUACION Y CLASIFICACION DESPUES DE CRUCE Y MUTACION. ###### * ##################################################################### */ // Canditate loop to be paralelized with OpenMP for ( i = 0 ; i < TOTAL_CHROM ; i++ ) { if ( ((List_Chromosome[i])->evaluation == BAD_CHROM) && (good_chromosome(List_Chromosome[i], CHROMOSOME_LENGTH) == 1) ) { List_Chromosome[i]->evaluation = evaluate_chromosome(List_Chromosome[i], CHROMOSOME_LENGTH); }; }; classify_chromosome(List_Chromosome, TOTAL_CHROM); // PRINT 3 BEST CHROMOSOMES printf("%d ITERATION. 3 BEST CHROMOSOMES:\n", iter); for ( i = 0 ; i < 3 ; i++) { show_chromosome(List_Chromosome[i], CHROMOSOME_LENGTH); } };// ########### END OF MAIN LOOP ########### // TIME MEASUREMENT gettimeofday(tv, tz); sf = (tv->tv_sec); tf = (tv->tv_usec); tf = sf * 1000000 + tf; tiempo = (1.0 * tf - 1.0 * ti) / 1000000.0; printf("\nExecution time T=%lf s.\n", tiempo); fflush(stdout); // CALCULATE PERCENTAGE OF VALID CHROMOSOMES. for ( i = 0 ; i < TOTAL_CHROM ; i++ ) if ( List_Chromosome[i]->evaluation != BAD_CHROM ) validos++; printf("%d%% of valid chromosomes.\n", (validos * 100) / TOTAL_CHROM); // Free memory for ( i = 3 ; i < TOTAL_CHROM ; i++ ) free_chromosome(List_Chromosome[i]); List_Chromosome = realloc(List_Chromosome, 3 * sizeof(struct Chromosome)); }
/* * evolution of the group, including the process of * select parent, crossover and mutation */ void evolve(Group* grp) { select_parent(grp); crossover(grp); mutate(grp); }
SEXP GADEM_Analysis(SEXP sequence,SEXP sizeSeq, SEXP accession, SEXP Rverbose,SEXP RnumWordGroup,SEXP RnumTop3mer,SEXP RnumTop4mer,SEXP RnumTop5mer,SEXP RnumGeneration,SEXP RpopulationSize, SEXP RpValue,SEXP ReValue,SEXP RextTrim,SEXP RminSpaceWidth,SEXP RmaxSpaceWidth,SEXP RuseChIPscore,SEXP RnumEM,SEXP RfEM, SEXP RwidthWt,SEXP RfullScan, SEXP RslideWinPWM,SEXP RstopCriterion,SEXP RnumBackgSets,SEXP RweightType,SEXP RbFileName,SEXP RListPWM,SEXP RminSites,SEXP RmaskR,SEXP Rnmotifs) { char *bFileName; SEXP ResultsGadem; SEXP RSpwm; PROTECT(ResultsGadem=NEW_LIST(100)); int increment=0; double testrand; //Number of sequences int numSeq = INTEGER_VALUE(sizeSeq); // const // char *Fastaheader[size]; int incr=0; int longueur=length(sequence); int IncrementTemp=0; // basic settings/info int maxSeqLen,*seqLen; // sequence info double aveSeqLen; // sequence info char **seq,**rseq; int *geneID; // sequence info char **oseq,**orseq; // copy of the original sequences char **sseq,**rsseq; // simulated seqs. double *bfreq1, *bfreq0=NULL; // base frequencies double *ChIPScore; // chip score int maskR; // mask simple repeats before running the algorithm // pwms double ***pwm; // initial population of PWMs from spaced dyads int *pwmLen; // initial pwm lengths double **opwm2; // EM-derived PWM double ***opwm; // observed PWMs from identified sites double ***epwm; // em-optimized PWMs double **logepwm; // log(em-optimized PWM) int *pwmnewLen; // final motif length after extending to both ends // llr score distr. Pgfs *llrDist; // llr distribution from pgf method int llrDim; // llr distribution dimension int **ipwm; // integer pwm for computing llr score distribution // EM, motif, sites double pvalueCutoff; // user input, used to determine score cutoff based on ipwm int *scoreCutoff; // pwm score cutoff for the corresponding p-value cutoff double logev; // log of E-value of a motif; int useChIPscore; // indicator for using ChIP-seq score for seq. selection for EM int numEM; // number of EM steps double E_valueCutoff; // log E-value cutoff //int nsitesEM; // number of binding sites in sequences subjected to EM int minsitesEM; // minimal number of sites in a motif in EM sequences int *nsites; // number of binding sites in full data int minsites; // minimal number of sites in a motif in full data Sites **site; // binding sites in all sequences int motifCn; // number of motifs sought and found int extTrim; int noMotifFound; // none of the dyads in the population resulted in a motif char **pwmConsensus; // consensus sequences of motifs double pwmDistCutoff; // test statistic for motif pwm similarity char *uniqMotif; // motifs in a population unique or not int numUniq; // number of unique motifs in a population int slideWinPWM; // sliding window for comparing pwm similarity int widthWt; // window width in which nucleotides are given large weights for PWM optimization int fullScan; // scan scan on the original sequences or masked sequences // background int numBackgSets; // weights double **posWeight; // spatial weights int weightType; // four weight types 0, 1, 2, 3, or 4 // words for spaced dyad Words *word; // top-ranked k-mers as the words for spaced dyads int numTop3mer,numTop4mer,numTop5mer; // No. of top-ranked k-mers as words for dyads int maxWordSize; // max of the above three int numWordGroup; // number of non-zero k-mer groups int minSpaceWidth,maxSpaceWidth; // min and max width of spacer of the spaced dyads Chrs **dyad; // initial population of "chromosomes" char **sdyad; // char of spaced dyads // GA int populationSize,numGeneration; // GA parameters double maxpMutationRate; Fitness *fitness; // "chromosome" fitness Wheel *wheel; // roulette-wheel selection // to speed up only select a subset of sequences for EM algorithm double fEM; // percentage of sequences used in EM algorithm int numSeqEM; // number of sequences subject to EM char *Iseq; // Indicator if a sequence is used in EM or not int *emSeqLen; // length of sequences used in EM double *maxpFactor; int numCycle; // number of GADEM cycles int generationNoMotif; // maximal number of GA generations in a GADEM cycle resulted in no motifs // mis. //seed_t seed; // random seed int motifCn2,id,numCycleNoMotif,verbose,minminSites,nmotifs; int startPWMfound,stopCriterion; char *mFileName,*oFileName,*pwmFileName,*tempRbFileName; time_t start; int cn[4],bcn[4],*seqCn,*bseqCn,avebnsites,avebnsiteSeq,totalSitesInput; int i; int ii=0; int jjj=0; /*************/ FILE * output = fopen("output.txt", "w"); /*************/ GetRNGstate(); mFileName=alloc_char(500); mFileName[0]='\0'; oFileName=alloc_char(500); oFileName[0]='\0'; pwmFileName=alloc_char(500); pwmFileName[0]='\0'; bFileName=alloc_char(500); bFileName[0]='\0'; //tempRbFileName=alloc_char(500); tempRbFileName[0]='\0'; seq=NULL; aveSeqLen=0; maxSeqLen=0; //minsites=-1; startPWMfound=0; maxSeqLen=0; for(incr=1;incr<longueur;incr=incr+2) { if (length(STRING_ELT(sequence,(incr)))>maxSeqLen) maxSeqLen=length(STRING_ELT(sequence,(incr))); } // fprintf(output,"maxLength=%d",maxSeqLen); // exit(0); seq=alloc_char_char(numSeq,maxSeqLen+1); for(incr=1;incr<longueur;incr=incr+2) { for (int j=0; j<length(STRING_ELT(sequence,(incr))); j++) { seq[IncrementTemp][j]=CHAR(STRING_ELT(sequence,(incr)))[j]; } IncrementTemp++; } verbose=LOGICAL_VALUE(Rverbose); numWordGroup=INTEGER_VALUE(RnumWordGroup); minsites=INTEGER_VALUE(RminSites); numTop3mer=INTEGER_VALUE(RnumTop3mer); numTop4mer=INTEGER_VALUE(RnumTop4mer); numTop5mer=INTEGER_VALUE(RnumTop5mer); numGeneration=INTEGER_VALUE(RnumGeneration); populationSize=INTEGER_VALUE(RpopulationSize); pvalueCutoff=NUMERIC_VALUE(RpValue); E_valueCutoff=NUMERIC_VALUE(ReValue); extTrim=INTEGER_VALUE(RextTrim); minSpaceWidth=INTEGER_VALUE(RminSpaceWidth); maxSpaceWidth=INTEGER_VALUE(RmaxSpaceWidth); useChIPscore=NUMERIC_VALUE(RuseChIPscore); numEM=INTEGER_VALUE(RnumEM); fEM=NUMERIC_VALUE(RfEM); widthWt=INTEGER_VALUE(RwidthWt); fullScan=INTEGER_VALUE(RfullScan); slideWinPWM=INTEGER_VALUE(RslideWinPWM); numUniq=populationSize; stopCriterion=INTEGER_VALUE(RstopCriterion); numBackgSets=INTEGER_VALUE(RnumBackgSets); weightType=NUMERIC_VALUE(RweightType); //const char *tempRbFileName[1]; tempRbFileName = convertRString2Char(RbFileName); //tempRbFileName[0]=CHAR(STRING_ELT(RbFileName,0)); nmotifs = INTEGER_VALUE(Rnmotifs); maskR = INTEGER_VALUE(RmaskR); if(numSeq>MAX_NUM_SEQ) { error("Error: maximal number of seqences reached!\nPlease reset MAX_NUM_SEQ in gadem.h and rebuild (see installation)\n"); } strcpy(bFileName,tempRbFileName); ChIPScore=alloc_double(MAX_NUM_SEQ); seqLen=alloc_int(MAX_NUM_SEQ); geneID=alloc_int(MAX_NUM_SEQ); // seq=sequences; // numSeq=size; int len; for (i=0; i<numSeq; i++) { len=strlen(seq[i]); seqLen[i]=len; geneID[i]=INTEGER(accession)[i]; } aveSeqLen=0; for (i=0; i<numSeq; i++) aveSeqLen +=seqLen[i]; aveSeqLen /=(double)numSeq; for (i=0; i<numSeq; i++) { if (seqLen[i]>maxSeqLen) maxSeqLen=seqLen[i]; } rseq=alloc_char_char(numSeq,maxSeqLen+1); oseq=alloc_char_char(numSeq,maxSeqLen+1); orseq=alloc_char_char(numSeq,maxSeqLen+1); for (i=0; i<numSeq; i++) { if(seqLen[i]>maxSeqLen) maxSeqLen=seqLen[i]; } reverse_seq(seq,rseq,numSeq,seqLen); // make a copy of the original sequences both strands for (i=0; i<numSeq; i++) { for (int j=0; j<seqLen[i]; j++) { oseq[i][j]=seq[i][j]; orseq[i][j]=rseq[i][j]; } oseq[i][seqLen[i]]='\0'; orseq[i][seqLen[i]]='\0'; } if (strcmp(bFileName,"NULL")!= 0) { bfreq0=alloc_double(5); read_background(bFileName,bfreq0); } if (GET_LENGTH(RListPWM)!= 0) { startPWMfound=1; } else { } // check for input parameters if(numGeneration<1) { error("number of generaton < 1.\n"); } if(populationSize<1) { error("population size < 1.\n"); } if (minSpaceWidth<0) { error("minimal number of unspecified bases in spaced dyads <0.\n"); } if (maxSpaceWidth<0) { error("maximal number of unspecified bases in spaced dyads <0.\n"); } if (minSpaceWidth>maxSpaceWidth) { error("mingap setting must <= to maxgap setting.\n\n"); } if (maxSpaceWidth+12>MAX_PWM_LENGTH) { error("maxgap setting plus word lengths exceed <MAX_PWM_LENGTH>.\n"); } if (numEM<0) { error("number of EM steps is zero.\n"); } if (numEM==0) { error("number of EM steps = 0, no EM optimization is carried out.\n"); } if (fullScan!=0 && fullScan!=1) fullScan=0; maxWordSize=0; if (numTop3mer>maxWordSize) maxWordSize=numTop3mer; if (numTop4mer>maxWordSize) maxWordSize=numTop4mer; if (numTop5mer>maxWordSize) maxWordSize=numTop5mer; // any one, two or three: tetramer, pentamer, hexamer if (numTop3mer==0 && numTop4mer==0 && numTop5mer==0) { error("maxw3, maxw4, and maxw5 all zero - no words for spaced dyads.\n"); } // if (startPWMfound && fEM!=0.5 && fEM!=1.0 & verbose) // { // warning("fEM argument is ignored in a seeded analysis\n"); // } if (startPWMfound) { // if(verbose) // { // if (populationSize!=10 && populationSize!=100) warning("pop argument is ignored in a seeded analysis, -pop is set to 10.\n"); // if (numGeneration!=1 && numGeneration!=5) warning("gen argument is ignored in a seeded analysis, -gen is set to 1.\n"); // } fEM=1.0; populationSize=FIXED_POPULATION; numGeneration=1; } // number of sequences for EM if (fEM>1.0 || fEM<=0.0) { error("The fraction of sequences subject to EM is %3.2f.\n",fEM); } numSeqEM=(int)(fEM*numSeq); // memory callocations Iseq =alloc_char(numSeq+1); opwm2 =alloc_double_double(MAX_PWM_LENGTH,4); ipwm =alloc_int_int(MAX_PWM_LENGTH,4); logepwm=alloc_double_double(MAX_PWM_LENGTH,4); emSeqLen=alloc_int(numSeqEM); scoreCutoff=alloc_int(1000); // scoreCutoff=alloc_int(populationSize); llrDist=alloc_distr(MAX_DIMENSION); posWeight=alloc_double_double(numSeq,maxSeqLen); sseq=alloc_char_char(MAX_NUM_SEQ,maxSeqLen+1); rsseq=alloc_char_char(MAX_NUM_SEQ,maxSeqLen+1); bfreq1=base_frequency(numSeq,seq,seqLen); if (strcmp(bFileName,"NULL") == 0) { bfreq0=alloc_double(5); for (i=0; i<4; i++) { bfreq0[i]=bfreq1[i]; } } // if minN not specified, set the defaults accordingly if (minsites==-1) { minsites =max(2,(int)(numSeq/20)); } minsitesEM=(int)(fEM*minsites); maxpMutationRate=MAXP_MUTATION_RATE; // determine the distribution and critical cut point pwmDistCutoff=vector_similarity(); /*---------- select a subset of sequences for EM only --------------*/ if (useChIPscore==1) { select_high_scoring_seq_for_EM (ChIPScore,numSeq,numSeqEM,Iseq,fEM); } else { sample_without_replacement(Iseq,numSeqEM,numSeq); } /*-------------------- end of selection --------------------------*/ if (maskR==1) mask_repetitive(geneID,seq,numSeq,seqLen,mFileName); if (widthWt<20) { warning("The window width of sequence centered on the nucleotides having large weights in EM for PWM optimization is small\n Motif longer than %d will not be discovered\n",widthWt); } time(&start); // if (weightType==1 || weightType==3) //ffprintf(output,fp,"window width of sequence centered on the nucleotides having large weights for PWM optimization: %d\n",widthWt); //ffprintf(output,fp,"pwm score p-value cutoff for declaring binding site:\t%e\n",pvalueCutoff); if(verbose) { ffprintf(output,output,"==============================================================================================\n"); ffprintf(output,output,"input sequence file: %s\n",mFileName); fprintf(output,"number of sequences and average length:\t\t\t\t%d %5.1f\n",numSeq,aveSeqLen); fprintf(output,"Use pgf method to approximate llr null distribution\n"); fprintf(output,"parameters estimated from sequences in: %s\n\n",mFileName); if (weightType!=0) fprintf(output,"non-uniform weight applies to each sequence - type:\t\t%d\n",weightType); fprintf(output,"number of GA generations & population size:\t\t\t%d %d\n\n",numGeneration,populationSize); fprintf(output,"PWM score p-value cutoff for binding site declaration:\t\t%e\n",pvalueCutoff); fprintf(output,"ln(E-value) cutoff for motif declaration:\t\t\t%f\n\n",E_valueCutoff); // fprintf(output,"number (percentage) of sequences selected for EM:\t\t%d(%4.1f\%)\n",numSeqEM,100.0*(double)numSeqEM/(double)numSeq); fprintf(output,"number of EM steps:\t\t\t\t\t\t%d\n",numEM); fprintf(output,"minimal no. sites considered for a motif:\t\t\t%d\n\n",minsites); fprintf(output,"[a,c,g,t] frequencies in input data:\t\t\t\t%f %f %f %f\n",bfreq1[0],bfreq1[1],bfreq1[2],bfreq1[3]); fprintf(output,"==============================================================================================\n"); } // if (pgf) // { // if (userMarkovOrder!=0 & verbose) // { // warning("The user-specified background Markov order (%d) is ignored when -pgf is set to 1\n",userMarkovOrder); // } // if (bFileName[0]!='\0' & verbose) // { // warning("The user-specified background models: %s are not used when -pgf is set to 1\n",bFileName); // } // } // if (startPWMfound && fEM!=1.0 & verbose) // { // warning("fEM argument is ignored in a seeded analysis\n"); // } // determine seq length by counting only [a,c,g,t], seqLen is used in E-value calculation // determine the distribution and critical cut point pwmDistCutoff=vector_similarity(); if (weightType==0) assign_weight_uniform(seqLen,numSeq,posWeight); else if (weightType==1) assign_weight_triangular(seqLen,numSeq,posWeight); else if (weightType==2) assign_weight_normal(seqLen,numSeq,posWeight); else { error("Motif prior probability type not found - please choose: 0, 1, or 2\n"); // fprintf(output,"Consider: -posWt 1 for strong central enrichment as in ChIP-seq\n"); // fprintf(output," -posWt 0 for others\n\n"); // exit(0); } /* if (startPWMfound) minminSites=minsites; else minminSites=(int)(0.40*minsitesEM);*/ motifCn=0; noMotifFound=0; numCycle=0; numCycleNoMotif=0; int compt=0; int lengthList=GET_LENGTH(RListPWM); /****************************************/ broadcastOnce(maxSeqLen, numEM, startPWMfound, minminSites, maxpFactor, numSeq, numSeqEM, Iseq, bfreq0, posWeight, weightType, pvalueCutoff, emSeqLen, populationSize); /****************************************/ do { if(!startPWMfound) { if(verbose) { fprintf(output,"*** Running an unseeded analysis ***\n"); // fprintf(output,"\n|------------------------------------------------------------------|\n"); // fprintf(output,"| |\n"); // fprintf(output,"| *** Running an unseeded analysis *** |\n"); // fprintf(output,"| |\n"); // fprintf(output,"|------------------------------------------------------------------|\n\n"); } populationSize=INTEGER_VALUE(RpopulationSize); numGeneration=INTEGER_VALUE(RnumGeneration); dyad =alloc_chrs(populationSize,4); wheel =alloc_wheel(populationSize); fitness=alloc_fitness(populationSize); maxpFactor=alloc_double(populationSize); uniqMotif=alloc_char(populationSize+1); opwm =alloc_double_double_double(populationSize,MAX_PWM_LENGTH,4); epwm=alloc_double_double_double(populationSize,MAX_PWM_LENGTH,4); pwmConsensus=alloc_char_char(populationSize,MAX_PWM_LENGTH+1); pwm =alloc_double_double_double(populationSize,MAX_PWM_LENGTH,4); pwmLen=alloc_int(populationSize); sdyad =alloc_char_char(populationSize,MAX_PWM_LENGTH+1); word =alloc_word(numWordGroup,maxWordSize); minminSites=(int)(0.40*minsitesEM); // identify top-ranked k-mers (k=3,4,5) for spaced dyads if(verbose) fprintf(output,"GADEM cycle %2d: enumerate and count k-mers... ",numCycle+1); numWordGroup=word_for_dyad(word,seq,rseq,numSeq,seqLen,bfreq1,&numTop3mer,&numTop4mer,&numTop5mer); if(verbose) fprintf(output,"Done.\n"); // generating a "population" of spaced dyads if(verbose) fprintf(output,"Initializing GA... "); initialisation(dyad,populationSize,numWordGroup,word,minSpaceWidth,maxSpaceWidth,maxpFactor); if(verbose) fprintf(output,"Done.\n"); } else { if(verbose) { fprintf(output,"*** Running an seeded analysis ***\n"); // fprintf(output,"\n|------------------------------------------------------------------|\n"); // fprintf(output,"| |\n"); // fprintf(output,"| *** Running a seeded analysis *** |\n"); // fprintf(output,"| |\n"); // fprintf(output,"|------------------------------------------------------------------|\n\n"); } populationSize=FIXED_POPULATION; dyad =alloc_chrs(populationSize,4); pwm=alloc_double_double_double(populationSize,MAX_PWM_LENGTH,4); pwmLen=alloc_int(populationSize); maxpFactor=alloc_double(populationSize); uniqMotif=alloc_char(populationSize+1); opwm =alloc_double_double_double(populationSize,MAX_PWM_LENGTH,4); epwm=alloc_double_double_double(populationSize,MAX_PWM_LENGTH,4); pwmConsensus=alloc_char_char(populationSize,MAX_PWM_LENGTH+1); sdyad =alloc_char_char(populationSize,MAX_PWM_LENGTH+1); word =alloc_word(numWordGroup,maxWordSize); wheel =alloc_wheel(populationSize); fitness=alloc_fitness(populationSize); minminSites=minsites; int lengthMatrix; lengthMatrix=GET_LENGTH(VECTOR_ELT(RListPWM,compt)); RSpwm=allocMatrix(REALSXP,4,(lengthMatrix/4)); RSpwm=VECTOR_ELT(RListPWM,compt); pwmLen[0]=read_pwm0(RSpwm,pwm[0],lengthMatrix); for(i=1; i<populationSize; i++) { for (int j=0; j<pwmLen[0]; j++) { for (int k=0; k<4; k++) { pwm[i][j][k]=pwm[0][j][k]; } } pwmLen[i]=pwmLen[0]; } for (i=0; i<populationSize; i++) { maxpFactor[i]=FIXED_MAXPF*(i+1); standardize_pwm(pwm[i],pwmLen[i]); consensus_pwm(pwm[i],pwmLen[i],pwmConsensus[i]); strcpy(sdyad[i],pwmConsensus[i]); } } generationNoMotif=0; for (jjj=0; jjj<numGeneration; jjj++) { // convert spaced dyads to letter probability matrix if (!startPWMfound) { dyad_to_pwm(word,populationSize,dyad,pwm,pwmLen); } /* DO_APPLY(populationCalculation(maxSeqLen, numEM, fitness+ii, startPWMfound, minminSites, maxpFactor[ii], numSeq, numSeqEM, seq, rseq, seqLen, Iseq, bfreq0, posWeight, weightType, pvalueCutoff, emSeqLen, pwm[ii], pwmLen[ii], epwm[ii], opwm[ii], pwmConsensus[ii], scoreCutoff+ii, sdyad[ii], ii), populationSize, ii); */ /* Create the structure to send to all the other slaves */ broadcastEveryCycle(Iseq, pwm, pwmLen, pwmConsensus, scoreCutoff, sdyad, populationSize); populationCalculation(maxSeqLen, numEM, fitness+ii, startPWMfound, minminSites, maxpFactor[ii], numSeq, numSeqEM, seq, rseq, seqLen, Iseq, bfreq0, posWeight, weightType, pvalueCutoff, emSeqLen, pwm[ii], pwmLen[ii], epwm[ii], opwm[ii], pwmConsensus[ii], scoreCutoff+ii, sdyad[ii], ii); /* Receive the analyzed data from all the other slaves and compile them */ //getPopCalcResults(...); // for (i=0; i<5; i++) // { // fprintf(output,"fitness.value=%lf\n",fitness[i].value); // fprintf(output,"fitness.index=%d\n",fitness[i].index); // fprintf(output,"maxpfactor=%lf\n",maxpFactor[i]); // fprintf(output,"scoreCutoff=%d\n",scoreCutoff[i]); // fprintf(output," spacedDyad: %s\n",sdyad[i]); // // for (l=0; l<pwmLen[i]; l++) // { // for (m=0; m<4; m++) // { // fprintf(output,"opwm[%d][%d][%d]=%lf ",i,l,m,opwm[i][l][m]); // fprintf(output,"epwm[%d][%d][%d]=%lf ",i,l,m,epwm[i][l][m]); // fprintf(output,"pwm[%d][%d][%d]=%lf ",i,l,m,pwm[i][l][m]); // } // fprintf(output,"\n"); // } // fprintf(output,"\n"); // } // // testrand=runif(0,1); // fprintf(output,"testrand1=%lf\n",testrand); if (populationSize>1) { sort_fitness(fitness,populationSize); } // for (i=0; i<5; i++) // { // fprintf(output,"fitness.value=%lf\n",fitness[i].value); // fprintf(output,"fitness.index=%d\n",fitness[i].index); // } numUniq=check_pwm_uniqueness_dist(opwm, pwmLen, populationSize, fitness, pwmDistCutoff, E_valueCutoff, uniqMotif, slideWinPWM); // for (i=0; i<5; i++) // { // fprintf(output,"fitness.value=%lf\n",fitness[i].value); // fprintf(output,"fitness.index=%d\n",fitness[i].index); // fprintf(output,"maxpfactor=%lf\n",maxpFactor[i]); // fprintf(output,"scoreCutoff=%d\n",scoreCutoff[i]); // fprintf(output," spacedDyad: %s\n",sdyad[i]); // // for (l=0; l<pwmLen[i]; l++) // { // for (m=0; m<4; m++) // { // fprintf(output,"opwm[%d][%d][%d]=%lf",i,l,m,opwm[i][l][m]); // } // fprintf(output,"\n"); // } // fprintf(output,"\n"); // } if(verbose) { fprintf(output,"GADEM cycle[%3d] generation[%3d] number of unique motif: %d\n",numCycle+1,jjj+1,numUniq); for (i=0; i<populationSize; i++) { if (uniqMotif[i]=='1') { fprintf(output," spacedDyad: %s ",sdyad[fitness[i].index]); for (int j=strlen(sdyad[fitness[i].index]); j<maxSpaceWidth+10; j++) fprintf(output," "); fprintf(output,"motifConsensus: %s ",pwmConsensus[fitness[i].index]); for (int j=strlen(sdyad[fitness[i].index]); j<maxSpaceWidth+10; j++) fprintf(output," "); fprintf(output," %3.2f fitness: %7.2f\n",maxpFactor[fitness[i].index],fitness[i].value); } } fprintf(output,"\n"); } if (jjj<numGeneration-1) { // fitness based selection with replacement roulett_wheel_fitness(fitness,populationSize,wheel); // mutation and crossover operations if (populationSize>1) { testrand=runif(0,1); if (testrand>=0.5) { mutation(dyad,numWordGroup,word,minSpaceWidth,maxSpaceWidth,wheel,populationSize,fitness,uniqMotif, maxpFactor,maxpMutationRate); } else { crossover(dyad,numWordGroup,word,minSpaceWidth,maxSpaceWidth,wheel,populationSize,fitness,uniqMotif, maxpFactor,maxpMutationRate); } } else { mutation(dyad,numWordGroup,word,minSpaceWidth,maxSpaceWidth,wheel,populationSize,fitness,uniqMotif, maxpFactor,maxpMutationRate); } } } if((numCycle+1)< lengthList) { compt++; } else { startPWMfound=0; } numCycle++; site=alloc_site_site(numUniq+1,MAX_SITES); nsites=alloc_int(numUniq+1); pwmnewLen=alloc_int(numUniq+1); // after base extension and trimming seqCn=alloc_int(MAX_NUM_SEQ); bseqCn=alloc_int(MAX_NUM_SEQ); // final step user-specified background model is used motifCn2=0; // motifCn per GADEM cycle for (ii=0; ii<populationSize; ii++) { id=fitness[ii].index; if(uniqMotif[ii]=='0') { continue; } // approximate the exact llr distribution using Staden's method // if(verbose) // { // fprintf(output,"Approximate the exact pwm llr score distribution using the pgf method.\n"); // } log_ratio_to_int(epwm[id],ipwm,pwmLen[id],bfreq0); // compute score distribution of the (int)PWM using Staden's method llrDim=pwm_score_dist(ipwm,pwmLen[id],llrDist,bfreq0); //fprintf(output,"Avant ScoreCutoff %d \n",scoreCutoff[id]); scoreCutoff[id]=determine_cutoff(llrDist,llrDim,pvalueCutoff); //fprintf(output,"Apres ScoreCutoff %d \n",scoreCutoff[id]); if(fullScan) { nsites[motifCn2]=scan_llr_pgf(llrDist,llrDim,site[motifCn2],numSeq,oseq,orseq,seqLen,ipwm,pwmLen[id],scoreCutoff[id],bfreq0); } else { nsites[motifCn2]=scan_llr_pgf(llrDist,llrDim,site[motifCn2],numSeq,seq,rseq,seqLen,ipwm,pwmLen[id],scoreCutoff[id],bfreq0); } if (nsites[motifCn2]>=max(2,minsites)) { for (int j=0; j<numSeq; j++) seqCn[j]=0; for (int j=0; j<nsites[motifCn2]; j++) seqCn[site[motifCn2][j].seq]++; for (int j=0; j<4; j++) cn[j]=0; for (int j=0; j<numSeq; j++) { if (seqCn[j]==0) cn[0]++; if (seqCn[j]==1) cn[1]++; if (seqCn[j]==2) cn[2]++; if (seqCn[j]>2) cn[3]++; } totalSitesInput=nsites[motifCn2]; if (extTrim) { if (fullScan) { extend_alignment(site[motifCn2],numSeq,oseq,orseq,seqLen,nsites[motifCn2],pwmLen[id],&(pwmnewLen[motifCn2])); } else { extend_alignment(site[motifCn2],numSeq,seq,rseq,seqLen,nsites[motifCn2],pwmLen[id],&(pwmnewLen[motifCn2])); } } else { pwmnewLen[motifCn2]=pwmLen[id]; } if (fullScan) { align_sites_count(site[motifCn2],oseq,orseq,nsites[motifCn2],pwmnewLen[motifCn2],opwm2); } else { align_sites_count(site[motifCn2],seq,rseq,nsites[motifCn2],pwmnewLen[motifCn2],opwm2); } standardize_pwm(opwm2,pwmnewLen[motifCn2]); logev=E_value(opwm2,nsites[motifCn2],bfreq0,pwmnewLen[motifCn2],numSeq,seqLen); if (logev<=E_valueCutoff) { consensus_pwm(opwm2,pwmnewLen[motifCn2],pwmConsensus[id]); if (fullScan) { SET_VECTOR_ELT(ResultsGadem,increment,print_result_R(site[motifCn2],nsites[motifCn2],numSeq,oseq,orseq,seqLen,logev,opwm2,pwmnewLen[motifCn2],motifCn+1,sdyad[id],pwmConsensus[id],numCycle,pvalueCutoff,maxpFactor[id],geneID)); increment++; print_motif(site[motifCn2],nsites[motifCn2],oseq,orseq,seqLen,pwmnewLen[motifCn2],motifCn+1,opwm2); } else { SET_VECTOR_ELT(ResultsGadem,increment,print_result_R(site[motifCn2],nsites[motifCn2],numSeq,seq,rseq,seqLen,logev,opwm2,pwmnewLen[motifCn2], motifCn+1,sdyad[id],pwmConsensus[id],numCycle,pvalueCutoff,maxpFactor[id],geneID)); increment++; print_motif(site[motifCn2],nsites[motifCn2],seq,rseq,seqLen,pwmnewLen[motifCn2],motifCn+1,opwm2); } mask_sites(nsites[motifCn2],seq,rseq,seqLen,site[motifCn2],pwmnewLen[motifCn2]); /* ----------------------compute the average number of sites in background sequences ----------------------*/ avebnsites=0; avebnsiteSeq=0; for (i=0; i<numBackgSets; i++) { simulate_background_seq(bfreq0,numSeq,seqLen,sseq); reverse_seq(sseq,rsseq,numSeq,seqLen); nsites[motifCn2]=scan_llr_pgf(llrDist,llrDim,site[motifCn2],numSeq,sseq,rsseq,seqLen,ipwm,pwmLen[id],scoreCutoff[id],bfreq0); for (int j=0; j<numSeq; j++) bseqCn[j]=0; for (int j=0; j<nsites[motifCn2]; j++) bseqCn[site[motifCn2][j].seq]++; for (int j=0; j<4; j++) bcn[j]=0; for (int j=0; j<numSeq; j++) { if (bseqCn[j]==0) bcn[0]++; if (bseqCn[j]==1) bcn[1]++; if (bseqCn[j]==2) bcn[2]++; if (bseqCn[j]>2) bcn[3]++; } //ffprintf(output,fq,"background set[%2d] Seqs with 0,1,2,>2 sites: %d %d %d %d\n",i+1,bcn[0],bcn[1],bcn[2],bcn[3]); avebnsites+=nsites[motifCn2]; avebnsiteSeq+=(numSeq-bcn[0]); } avebnsites/=numBackgSets; avebnsiteSeq/=numBackgSets; /* -----------------end compute the average number of sites in background sequences ----------------------*/ motifCn++; motifCn2++; //if((numCycle+1) > lengthList & fixSeeded) // { // numCycleNoMotif=1; // startPWMfound=1; // } else { numCycleNoMotif=0; // } } } } /* for (int i=0; i<motifCn2; i++) { mask_sites(nsites[i],seq,rseq,seqLen,site[i],pwmnewLen[i]); } */ if (site[0]) { free(site[0]); site[0]=NULL; } if (site) { free(site); site=NULL; } if (nsites) { free(nsites); nsites=NULL; } if (pwmnewLen) { free(pwmnewLen); pwmnewLen=NULL; } if (motifCn2==0) numCycleNoMotif++; if (motifCn==nmotifs) { fprintf(output,"Maximal number of motifs (%d) reached\n",nmotifs); break; } if (numCycleNoMotif==stopCriterion) noMotifFound=1; }while (!noMotifFound); // fclose(fp); /*if (!startPWMfound) { if (dyad[0]) { free(dyad[0]); dyad[0]=NULL; } if (dyad) { free(dyad); dyad=NULL; } }*/ if (seqLen) { free(seqLen); seqLen=NULL; } if (pwm[0][0]) { free(pwm[0][0]); pwm[0][0]=NULL; } if (pwm[0]) { free(pwm[0]); pwm[0]=NULL; } if (pwm) { free(pwm); pwm=NULL; } if (opwm2[0]) { free(opwm2[0]); opwm2[0]=NULL; } if (opwm2) { free(opwm2); opwm2=NULL; } if (opwm[0][0]) { free(opwm[0][0]); opwm[0][0]=NULL; } if (opwm[0]) { free(opwm[0]); opwm[0]=NULL; } if (opwm) { free(opwm); opwm=NULL; } if(ipwm[0]) { free(ipwm[0]); ipwm[0]=NULL; } if (ipwm) { free(ipwm); ipwm=NULL; } if (pwmLen) { free(pwmLen); pwmLen=NULL; } if (seq[0]) { free(seq[0]); seq[0]=NULL; } if (seq) { free(seq); seq=NULL; } // if (rseq[0]) { free(rseq[0]); rseq[0]=NULL; } // if (rseq) { free(rseq); rseq=NULL; } // if (oseq[0]) { free(oseq[0]); oseq[0]=NULL; } // if (oseq) { free(oseq); oseq=NULL; } // if (orseq[0]) { free(orseq[0]); orseq[0]=NULL; } // if (orseq) { free(orseq); orseq=NULL; } if (bfreq1) { free(bfreq1); bfreq1=NULL; } if (bfreq0) { free(bfreq0); bfreq0=NULL; } if (wheel) { free(wheel); wheel=NULL; } if (fitness) { free(fitness); fitness=NULL; } if (mFileName) { free(mFileName); mFileName=NULL; } if (oFileName) { free(oFileName); oFileName=NULL; } if (pwmFileName) { free(pwmFileName); pwmFileName=NULL; } if (sdyad[0]) { free(sdyad[0]); sdyad[0]=NULL; } if (sdyad) { free(sdyad); sdyad=NULL; } if (pwmConsensus[0]) { free(pwmConsensus[0]); pwmConsensus[0]=NULL; } if (pwmConsensus) { free(pwmConsensus); pwmConsensus=NULL; } //if (!startPWMfound && word) destroy_word(word,numWordGroup); PutRNGstate(); UNPROTECT(1); return(ResultsGadem); }
//retorna um vetor de indivíduos descendentes da população atual Population nextgeneration() { Population nextgen = &population[POPSIZE]; Individual *p1,*p2,*ind,*ind2; int flag,i,j,r; bestindividual = population[0]; for(i=0;i<NEXTGENSIZE;i+=2) { //escolha dos pais e crossover p1 = selection(); p2 = selection(); ind = crossover(p1,p2); ind2 = c[1]; //garantia de variedade genética if(evaluate(ind)>=bestindividual->fitness) { r = rand()%2; if(r) mutation(ind); else mutation2(ind); } if(evaluate(ind2)>=bestindividual->fitness) { r = rand()%2; if(r) mutation(ind2); else mutation2(ind2); } //mutação r = rand()%100; if(evaluate(ind)>=bestindividual->fitness && r<MUTATIONRATE) { r = rand()%2; if(r) mutation(ind); else mutation2(ind); evaluate(ind); } populationinsert(nextgen,ind,i); r = rand()%100; if(i+1 < NEXTGENSIZE && evaluate(ind2)>=bestindividual->fitness && r<MUTATIONRATE) { r = rand()%2; if(r) mutation(ind2); else mutation2(ind2); evaluate(ind2); } populationinsert(nextgen,ind2,i+1); } qsort(nextgen,NEXTGENSIZE,sizeof(Individual*),compareind); return nextgen; }
ReturnFlag GSTM::run_() { GAPopulation<CodeVInt, GAIndividual<CodeVInt>> subPopul(m_popsize); GAIndividual<CodeVInt> ia, ib; int i, n; double p; int flag, flag1; double bestlen = DBL_MAX; vector<int> arr(m_numDim); dynamic_cast<TermMean*>(m_term.get())->initialize(mean()); while (!ifTerminating()) { /*if(Global::msp_global->mp_problem->getEvaluations()/m_saveFre<m_num){ mean<<diffEdges()<<" "<<Global::msp_global->mp_problem->getEvaluations()<<endl; }*/ #ifdef OFEC_DEMON for (i = 0; i<this->getPopSize(); i++) updateBestArchive(this->m_pop[i]->self()); vector<Algorithm*> vp; vp.push_back(this); msp_buffer->updateBuffer_(&vp); #endif //cout<<Global::msp_global->mp_problem->getEvaluations()<<endl; n = 0; while (n<m_popsize) { flag = 0; flag1 = 0; selection(ia, ib); p = Global::msp_global->mp_uniformAlg->Next(); if (p <= m_PC) { *subPopul.getPop()[n++] = crossover(ia, ib); flag = 1; } if (flag == 0) { if (n<m_popsize - 1) { *subPopul.getPop()[n++] = ia; *subPopul.getPop()[n++] = ib; } else { *subPopul.getPop()[n++] = ia; flag1 = 1; } } p = Global::msp_global->mp_uniformAlg->Next(); if (p <= m_PM) { if (flag == 1 || flag1 == 1) mutation(*subPopul.getPop()[n - 1]); else { mutation(*subPopul.getPop()[n - 2]); mutation(*subPopul.getPop()[n - 1]); } } } for (i = 0; i<m_popsize; i++) subPopul.getPop()[i]->evaluate(); *(static_cast<GAPopulation<CodeVInt, GAIndividual<CodeVInt>>*>(this)) = subPopul; #ifdef OFEC_CONSOLE OptimalEdgeInfo::getOptimalEdgeInfo()->recordEdgeInfo<GAIndividual<CodeVInt>>(Global::msp_global.get(), Solution<CodeVInt>::getBestSolutionSoFar(), m_pop, m_num, m_popsize, m_saveFre); #endif m_iter++; } #ifdef OFEC_CONSOLE OptimalEdgeInfo::getOptimalEdgeInfo()->recordEdgeInfo<GAIndividual<CodeVInt>>(Global::msp_global.get(), Solution<CodeVInt>::getBestSolutionSoFar(), m_pop, m_num, m_popsize, m_saveFre, false); OptimalEdgeInfo::getOptimalEdgeInfo()->recordLastInfo(Global::msp_global->m_runId, Global::msp_global->mp_problem->getEvaluations()); #endif return Return_Terminate; }
void Trainer::breed() { std::sort(agents.begin(), agents.end(), fitness_comparison()); emit agentsChanged(agents); children.clear(); AgentVector selected_agents = selection(); AgentVector selected_agents_one; AgentVector selected_agents_two; for (unsigned int i = 0; i < selected_agents.size(); i++) { if (i % 2) selected_agents_one.push_back(selected_agents[i]); else selected_agents_two.push_back(selected_agents[i]); } unsigned int min_size = (selected_agents_one.size() < selected_agents_two.size()) ? selected_agents_one.size() : selected_agents_two.size(); if (min_size != 0) { Agent *braut = selected_agents.at(0); for (unsigned int i = 0; i < min_size; i++) { Agent *child_one = crossover(*braut, *selected_agents_one[i], rand() % 2); Agent *child_two = crossover(*selected_agents_two[i], *selected_agents_one[i], rand() % 2); // Agent *child_three = crossover(*selected_agents_one[i], *selected_agents_two[i], rand() % 2); // if (child_three) // children.push_back(child_three); if (child_one && braut != selected_agents_one[i]) { if (rand() % 100 < 10) { Genome genome_one = child_one->getGenome(); mutate(genome_one); child_one->setGenome(genome_one); } children.push_back(child_one); } if (child_two) { if (rand() % 100 > 80) { Genome genome_two = child_two->getGenome(); mutate(genome_two); child_two->setGenome(genome_two); } children.push_back(child_two); } } std::sort(children.begin(), children.end(), fitness_comparison()); Agent *b = children.at(0); b->setName("Brautern"); emit childrenChanged(children); } agents.clear(); agents = children; }
int main(){ //printf(" *** Real time multiprocessor allocator***\n"); int i; int maxGen = MAXGEN+1; int nrGen = 0; // Number of generations ga * ga = (struct ga *) malloc(sizeof(struct ga)); FILE * fitnessFile; FILE * chromosomeFile; remove("chromosome0mut0crossElitism.txt"); remove("fitness0mut0crossElitism.txt"); fitnessFile = fopen("fitness0mut0crossElitism.txt", "w"); chromosomeFile = fopen("chromosome0mut0crossElitism.txt", "w"); fprintf(fitnessFile, "%s", "Number of generations, Best Machine, Best fitness, Average fitness \n"); fprintf(chromosomeFile, "%s", "Machine number, TDF, PHYSICAL CORE id, U, Vcore id, Slice, Period, Pcore\n"); srand(time(NULL)); //printf("Initializing GA\n"); initGA(ga); //printf("Evaluating fitness\n"); evaluateFitness(ga); fprintf(fitnessFile, "%d, %d, %f, %f\n", nrGen, ga->bestMachineIndex,ga->bestFitness, ga->avgFitness); fprintf(chromosomeFile, "%s", "Generation 0\n"); for (i = 0; i < ga->populationSize; i++) printChromosome(&(ga->population[i]), chromosomeFile); nrGen++; //for (i = 0; i < ga->populationSize; i++) // printMachineParameters(&(ga->population[i])); //while(nrGen < maxGen && ga->bestFitness<1.0 ){ while(nrGen < maxGen && ga->bestFitness<1.0 ){ printf("Selection for gen %d ...\n", nrGen); selection(ga); printf("Mutation for gen %d ...\n", nrGen); mutation(ga); printf("Crossover for gen %d ...\n", nrGen); crossover(ga); printf("Evaluating fitness for gen %d ...\n", nrGen); evaluateFitness(ga); fprintf(fitnessFile, "%d, %d, %f, %f\n", nrGen, ga->bestMachineIndex, ga->bestFitness, ga->avgFitness); fprintf(chromosomeFile, "Generation %d", nrGen); for (i = 0; i < ga->populationSize; i++) printChromosome(&(ga->population[i]), chromosomeFile); /* printf("Number of generations %d, ", nrGen); printf("Best fitness: %f, ", ga->bestFitness); printf("Average fitness: %f \n", ga->avgFitness); //for (i = 0; i < ga->populationSize; i++) // printMachineParameters(&(ga->population[i])); */ nrGen++; } // end while fclose(chromosomeFile); fclose(fitnessFile); freeGA(ga); return 0; }
int main(int argc, char **argv) { time_t t; /* Intializes random number generator */ srand((unsigned) time(&t)); char **population; //include every parent that is about to have childen int length = LENGTH; int max_population = PSIZE; double mutation_rate = MUTAION_RATE; int i; population = (char **) malloc(max_population * sizeof(char *)); for (i = 0; i < max_population; i++) { population[i] = (char *) malloc(length * sizeof(char)); } // puts("init.."); initp(population); // print_population(population); int total_fitness = totalFitness(population); printf("total fitness: %d\n", total_fitness); double p_crossover = (double) 0.5; //this determines the crossover point in chrom int generation = 0; int limit = LENGTH * max_population; while (total_fitness < limit) { generation++; for (i = 0; i < max_population; i++) { char *child = crossover(population, p_crossover); mutate(child, mutation_rate); //printf("child: %s\n", child); population[i] = child; } printf("after %d generation\n", generation); // print_population(population); total_fitness = totalFitness(population); printf("total fitness: %d\n", total_fitness); } //long long type can represent upto 20 bits of 1 and 0, //chroms longer than 20bits will be splited to array of long long numbers /*char chrom1[] = "10101010001101011"; char chrom2[] = "11010000110010010"; int length = sizeof(chrom1)-1; double crossover = (double)0.5; //this determines the crossover point in chrom //generate mask for crossover char *mask1 = (char *) malloc(length*sizeof(char)); char *mask2 = (char *) malloc(length*sizeof(char)); generate_mask(mask1, mask2, length, crossover); printf("input 1: %15s (%d) 2: %15s (%d) Length: %d\n", chrom1, fitness(chrom1,length), chrom2, fitness(chrom2, length), length); printf("masks 1: %15s 2: %15s\n", mask1, mask2); char *ptr1,*ptr2; //convert the above 4 string values to decimal int following binary rule. long long ret1 = strtoul(chrom1, &ptr1, 2); long long ret2 = strtoul(chrom2, &ptr2, 2); long long m1 = strtoul(mask1, &ptr1, 2); long long m2 = strtoul(mask2, &ptr2, 2); //crossover operation long long ichild1 = (ret1 & m2) ^ (ret2 & m1); long long ichild2 = (ret1 & m1) ^ (ret2 & m2); //convert binary format childern to string, in order to add them to parent pool. char *child1 = (char *)malloc(length * sizeof(char)); char *child2 = (char *)malloc(length * sizeof(char)); sprintf(child1,"%lld",int_to_binary(ichild1)); sprintf(child2,"%lld",int_to_binary(ichild2)); printf("child 1: %18s 2: %s",child1,child2); */ return 0; }
void generation() { individual fuqin1,fuqin2,*pipeiguodu,*pipeichi; int *peiduishuzu;//用来存放产生的随机配对 pipeiguodu=new individual[zhongqunshu1]; pipeichi=new individual[zhongqunshu1]; peiduishuzu=new int[zhongqunshu1]; int member1,member2,j=0,fuzhijishu=0,i=0,temp=0,tt=0; float zhizhen; //随机遍历的实现 for(zhizhen=suijibianli();zhizhen<1;(zhizhen=zhizhen+zhizhenjuli))//设定指针1/66 { pipeichi[fuzhijishu]=nowpop[fuzhi(zhizhen)]; fuzhijishu++; } //交叉与变异的实现 //交叉 for(i=0;i<zhongqunshu1;i++) { peiduishuzu[i]=-1; } for (i=0; i<zhongqunshu1; i++) { temp =rnd(0,zhongqunshu1-1); //产生值在0-zhongqunshu1-1的随机数 while(Exist(temp, i, peiduishuzu))//判断产生的随机数是否已经产生过,如果是,则再产生一个随机数 { temp =rnd(0,zhongqunshu1-1); } //如果没有的话,则把产生的随机数放在peiduishuzu中 *(peiduishuzu+i) = temp; } for(i=0;i<zhongqunshu1-1;i=i+2) { fuqin1=pipeichi[peiduishuzu[i]]; fuqin2=pipeichi[peiduishuzu[i+1]]; crossover(fuqin1,fuqin2,newpop[i],newpop[i+1]); } for(j=0;j<zhongqunshu1;j++) { //if(newpop[j].geti<-1000) //cout<<"个体数值小于下界了"; nowpop[j].geti=newpop[j].geti; } // guanjiancanshujisuan(); //变异的实现 for(j=0;j<zhongqunshu;j++) { bianyi(nowpop[j]); } // guanjiancanshujisuan(); //精英保留的实现 jingyingbaoliu(); // guanjiancanshujisuan(); delete [] peiduishuzu; delete [] pipeichi; delete [] pipeiguodu; }
Sequence::SimData neutral_sample( uniform_generator & uni, uniform01_generator & uni01, exponential_generator & expo, poisson_generator & poiss, const double & theta, const double & rho, const int & nsites, const int & nsam, std::vector<chromosome> * sample, arg * sample_history, unsigned * max_chromosomes = NULL, const unsigned & max_chromosomes_inc = 0) /*! @brief A simple function to generate samples under a neutral equilibrium model. A simple function to generate samples under a neutral equilibrium model with infinite-sites mutation and a constant recombination rate accross the region. \param uni a function/object capable of returning a random double uniformly from [0,k) \param uni01 a function/object capable of returning a random probability uniformly from [0,1) \param expo a function/object capable of returning an exponentially distributed random variable. The function must take a single double as an argument, which is the mean of the exponential distribution \param poiss a function/object capable of returning an poisson distributed random variable. The function must take a single double as an argument, which is the mean of the poisson distribution \param theta 4Nu, the coalescent-scaled mutation rate \param rho 4Nr, the recombination rate for the whole region \param nsites the number of mutational sites to simulate. Recombination is equally likely between any two sites. \param nsites the total sample size. (There is no population structure in this routine) \param sample A pointer to the sample of chromosomes you wish to simulate. This must be properly initialized, for example using the function init_sample in <Sequence/Coalescent/Initialize.hpp> \param sample_history a pointer to the ancestral recombination graph. This must be initialized in the calling enviroment. In general, you can use init_marginal in <Sequence/Coalescent/Initialize.hpp> \param max_chromosomes This is a pointer to an integer in the calling environment which you can use to reserve memory in the array containing the sample of chromosomes. If the size of \a sample ever gets larger than this, max_chromosomes is incremented by \a max_chromosomes_inc \param max_chromosomes_inc the amount by which to increment \a max_chromosomes \note This function does require a bit of work to use, although not much. Please see the example code that comes with the library, in particular ms--.cc \ingroup coalescent */ { int NSAM = nsam; //this is rho = 4Nr/site double littler = rho/(double(nsites-1)); //a chromosome with nsites sites has nsites-1 positions ("links") //at which crossovers can occur, so the total number of //links at the start of the simulation is: int nlinks = nsam*(nsites-1); double t = 0.; while(NSAM>1) { double rcoal = double(NSAM*(NSAM-1)); double rrec = (rho>0.) ? littler*double(nlinks) : 0.; //note--the function calls below scale time in units of 4Ne double tcoal = expo(1./rcoal); double trec = expo(1./rrec); if ( trec < tcoal ) //crossover event { t+=trec; std::pair<int,int> pos_rec = pick_uniform_spot(uni01(), nlinks, sample->begin(),NSAM); assert( pos_rec.second >= 0 ); assert( pos_rec.second >= (sample->begin()+pos_rec.first)->first() ); assert( pos_rec.second <= ((sample->begin()+pos_rec.first)->last() ) ); assert( (sample->begin()+pos_rec.first)->links()>0 ); nlinks -= crossover(NSAM,pos_rec.first,pos_rec.second, sample,sample_history); NSAM++; } else //common ancestor event { t+=tcoal; std::pair<int,int> two = pick2(uni,NSAM); NSAM -= coalesce(t,nsam,NSAM,two.first,two.second,nsites, &nlinks,sample,sample_history); } if (unsigned(NSAM) < sample->size()/5) { sample->erase(sample->begin()+NSAM+1,sample->end()); } } if (max_chromosomes != NULL && sample->size() > *max_chromosomes) *max_chromosomes += max_chromosomes_inc; //As we have scaled time in units of 4Nr generations, we pass theta //to the mutation function. If we had used the following code to //generate times: // double tcoal = expo(2./rcoal); // double trec = expo(2./rrec); //Then time would be scaled in units of 2Ne generations, //and if our simulation considers theta=4Neu, we'd pass theta/2 //to the infinite_sites routine SimData gametes_obj = infinite_sites_sim_data(poiss,uni, nsites,*sample_history,theta); return gametes_obj; }
int main() { // srand(time(0)); // generateInst(CASE); for(CASE = 1; CASE<=10; CASE++) { _mkdir("GAgrid"); strcpy(strdir,"GAgrid//inst"); itoa(CASE,ch,10); strcat(strdir,ch); _mkdir(strdir); strcat(strdir,"//"); readInst(CASE); int i,j; int gen; clock_t start; ////////////////// avg_result_time = 0; ////////////////// for(trialNum = 1; trialNum <= TRIALNUM; trialNum++) { strcpy(str,strdir); strcat(str,"result.txt"); ftotal = fopen(str,"a"); strcpy(str,strdir); itoa(trialNum,ch,10); strcat(str,"resultMnum"); strcat(str,ch); strcat(str,".txt"); fresultgMnum = fopen(str,"w"); strcpy(str,strdir); strcat(str,"runtime"); strcat(str,ch); strcat(str,".txt"); fruntime = fopen(str,"w"); start = clock(); ////////////////// gen = 0; initialize(CASE); evaluate(CASE); keep_the_best(); while(gen < MAXGENS) { select(); //using roulette wheel selection crossover(); mutate(); evaluate(CASE); elitist(); gen++; // printf("%d\t%g\t%g\n",gen,pop[POPSIZE].fitness,pop[POPSIZE].cost); fprintf(fruntime,"%d\t%g\t%g\n",gen,pop[POPSIZE].fitness,pop[POPSIZE].cost); } avg_result_time += clock() - start; ////////////////// printf("%d\t%g\t%g\n",trialNum,pop[POPSIZE].fitness,pop[POPSIZE].cost); fprintf(ftotal,"%d\t%g\t%g\t%g\n",trialNum,pop[POPSIZE].fitness,pop[POPSIZE].cost,(double)avg_result_time/trialNum);////////////////// for(i=0;i<24;i++) { for(j=0;j<MTYPE;j++) { fprintf(fresultgMnum,"%d\t",pop[POPSIZE].gMnum[i][j]); } fprintf(fresultgMnum,"\n"); } // printf("\n"); fprintf(fresultgMnum,"\n"); fclose(fresultgMnum); fclose(ftotal); fclose(fruntime); } } return 0; }
/* slave 进程 */ void worker() { printf("\tProcessor %d at %s begin work..\n", myid, processor_name); MPI_Status status; MPI_Request handle; int recv_flag = 0; int count = 0; int upload = 0; // 非阻塞接收主进程消息 MPI_Irecv(selectedGenes, n, MPI_GENETYPE, 0, MPI_ANY_TAG, MPI_COMM_WORLD, &handle); while(1) { // 独立繁衍count代 count = generations; while(count--) { select(); crossover(); mutate(); evaluate(); prefer(); // 若满足终止条件,则向主进程发送最优路径,并结束进程 if(population[CARDINALITY].fitness <= optimal+margin) { printf("\tProcessor %d at %s Terminated\n", myid, processor_name); MPI_Send(&population[CARDINALITY], 1, MPI_GENETYPE, 0, DONE_TAG, MPI_COMM_WORLD); printf("\tProcessor %d at %s exit\n", myid, processor_name); return; } // 探测是否收到主进程的消息 MPI_Test(&handle, &recv_flag, &status); // 若收到主进程的消息 if(recv_flag) { printf("\tProcessor %d at %s recv %d\n", myid, processor_name, status.MPI_TAG); // 状态重置 recv_flag = 0; // 若接收到DONE_TAG则结束进程 if(status.MPI_TAG == DONE_TAG) { printf("\tProcessor %d at %s exit\n", myid, processor_name); return; } // 否则,将接收到的优良个体替换种群中最差的个体 qsort(population, CARDINALITY, sizeof(GeneType), compare); for(int i=1; i <= n; i++) assign(&population[CARDINALITY-i], &selectedGenes[i-1]); if(selectedGenes[0].fitness < population[CARDINALITY].fitness) assign(&population[CARDINALITY], &selectedGenes[0]); // 非阻塞接收主进程消息 MPI_Irecv(selectedGenes, n, MPI_GENETYPE, 0, MPI_ANY_TAG, MPI_COMM_WORLD, &handle); } } // 繁衍count代后,若没有终止则向主进程发送最优个体 select_N_best(n); MPI_Send(selectedGenes, n, MPI_GENETYPE, 0, PUT_BETTER_TAG, MPI_COMM_WORLD); printf("\tProcessor %d at %s upload %d\n", myid, processor_name, upload++); } }
Genotype::Genotype(const ID_type nID, const std::pair<Genotype*, Genotype*> parents) : ID(nID), decision_chromosome(), link_chromosome(), fitness(parents.first->fitness), value(0.0), generator(nID) { real_type mutation_rate = 0.2, crossover_rate = 0.5; int i, j, ii, jj; //breed new chromosomes from parents, use hardcoded mutation and crossover rates fitness->add(ID, this); //what does crossover rate mean? //generate 2 random numbers for decision_chromosome crossover std::uniform_int_distribution<> random_int(0, decision_chromosome.size() - 1); std::bernoulli_distribution crossover(crossover_rate); if( crossover(generator) ) { i = random_int(generator); //take beginning of chromosome from first parent ... for(ii=i; ii>=0; --ii) decision_chromosome[ii] = parents.first->decision_chromosome[ii]; //... and the rest from the second parent for(ii=decision_chromosome.size()-1; ii>i; --ii) decision_chromosome[ii] = parents.second->decision_chromosome[ii]; } //decide whether to mutate std::bernoulli_distribution mutate(mutation_rate); random_int = std::uniform_int_distribution<>(0, decision_chromosome.size() - 1); if( mutate(generator) ) ~decision_chromosome[random_int(generator)]; //flip a bit //generate 2 random numbers for link_chromosome crossover if( crossover(generator) ) { ii = random_int(generator); //take beginning of chromosome from first parent ... for(i=i; i>=0; --i) //over genetic nodes for(j=link_chromosome[0].size()-1; j>=0; --j) //over each connectivity vector link_chromosome[i][j] = parents.first->link_chromosome[i][j]; //... and the rest from the second parent for(i=decision_chromosome.size()-1; i>ii; --i) for(j=link_chromosome[0].size()-1; j>=0; --j) link_chromosome[i][j] = parents.second->link_chromosome[i][j]; } //decide whether to mutate //mutations must occur in pairs to preserve K=2 connectivity random_int = std::uniform_int_distribution<>(0, link_chromosome.size() - 1); i = random_int(generator); //which bitset random_int = std::uniform_int_distribution<>(0, link_chromosome[0].size() - 1); j = random_int(generator); //which false bit to flip std::bernoulli_distribution random_bit(0.5); bool first = random_bit(generator); //which true bit to flip (there are only 2) ii = link_chromosome[0].size() - 1; if( mutate(generator) ) { for(ii; ii>=0; --ii) { if( link_chromosome[i][ii] ) { //true bit found if(first) { link_chromosome[i][ii] = false; break; } else first = true; //flip next true bit } } while(link_chromosome[i][j]) { //make sure bit is false to start with j = random_int(generator); } //may reflip the same bit, but it doesn't matter; happens rarely link_chromosome[i][j] = true; } //if } //constructor
int main(int argc, char ** argv) { /*OpenMP*/ int thread_count = strtol(argv[1],NULL,10); struct timeval t_begin,t_end; int i; int j; float elapsed[TESTS_TO_DO]; float best = 1000000; float best_var[VAR]; float worst = -1; float worst_var[VAR]; float solution; int generations; population popul; for(i=0;i<TESTS_TO_DO;i++) { ga_init(&popul,VAR); /* Get time */ #ifdef __unix__ gettimeofday(&t_begin, NULL); #else clock_t t = clock(); #endif generations = 0; while(generations < STOP_GENERATIONS) { /* Fitness */ fitness(my_fitness,&popul,thread_count); /* Crossover */ crossover(&popul,thread_count); generations++; } /* Get time */ #ifdef __unix__ gettimeofday(&t_end, NULL); elapsed[i] = ((t_end.tv_sec+t_end.tv_usec/1000000.0)) - \ (t_begin.tv_sec+t_begin.tv_usec/1000000.0); #else t = clock() - t; elapsed[i] = ((float)t)/CLOCKS_PER_SEC; #endif /* Apply fitness to sort */ fitness(my_fitness,&popul,thread_count); solution = my_fitness(popul.chromosomes[popul.size-1]); if(solution < best) { best = solution; for(j=0;j<VAR;j++) { best_var[j] = \ interpret(popul.chromosomes[popul.size-1][j], \ LIMIT_INFERIOR_X1,LIMIT_SUPERIOR_X1); } } else if (solution > worst) { worst = solution; for(j=0;j<VAR;j++) { worst_var[j] = \ interpret(popul.chromosomes[popul.size-1][j], \ LIMIT_INFERIOR_X1,LIMIT_SUPERIOR_X1); } } /* Free memory allocated */ ga_end(&popul); } /* Print results */ float mean = 0.0; for(i=0;i<TESTS_TO_DO;i++) { printf("Elapsed Time %i: %.6fs\n",i,elapsed[i]); mean += elapsed[i]; } printf("Elapsed Time - Mean: %f\n\n",(mean/TESTS_TO_DO)); printf("Worst Result:\t%.8f\n",worst); for(j=0;j<VAR;j++) printf("x%d: %.8f\n",j,worst_var[j]); printf("Best Result:\t%.8f\n",best); for(j=0;j<VAR;j++) printf("x%d: %.8f\n",j,best_var[j]); return 0; }