/* Perform all the work involved with the creation of a new generation of chromosomes */ void generation() { int mate1, mate2, jcross1, jcross2, j; /* perform any preselection actions necessary before generation */ preselect(); /* select, crossover, and mutation */ j = 0; do { /* pick a pair of mates */ mate1 = selectt(); mate2 = selectt(); /* Crossover and mutation */ crossover(oldpop[mate1].chrom, oldpop[mate2].chrom, newpop[j].chrom, newpop[j + 1].chrom, &jcross1, &jcross2); mutation(&(newpop[j])); mutation(&(newpop[j + 1])); objfunc(&(newpop[j])); newpop[j].parent[0] = mate1 + 1; newpop[j].xsite1 = jcross1; newpop[j].xsite2 = jcross2; newpop[j].parent[1] = mate2 + 1; objfunc(&(newpop[j + 1])); newpop[j + 1].parent[0] = mate1 + 1; newpop[j + 1].xsite1 = jcross1; newpop[j + 1].xsite2 = jcross2; newpop[j + 1].parent[1] = mate2 + 1; /* Increment population index */ j = j + 2; } while (j < (popsize - 1)); }
void trocaVizinhancaPRNS(pVNS *vns, int i, int *t, int *best_aval, int *best_index, double *bestfo, double *y, double *fy, pVNS **x){/*{{{*/ //etapa de avaliacao e troca de vizinhanca *fy = objfunc(y,&vns->FUNCTION,&vns->DIM,t); if(*fy < x[i]->bestfo){ memcpy(x[i]->best,y,sizeof(double) * vns->DIM); /* x[i]->best = y; */ x[i]->bestfo = *fy; x[i]->know = 0; if(x[i]->bestfo < *bestfo){ *bestfo = x[i]->bestfo; *best_aval = *t; *best_index = i; } }else{ if(x[i]->know <= vns->KMAX -1){ x[i]->know += 1; }else{ x[i]->know = 0; //reinicia k } } }/*}}}*/
/* Define randomly the population for generation # 0 */ void initialize_pop() { int j, k, bc, rbit; for (j = 0; j < popsize; j++) { for (k = 0; k < CODESIZE; k++) { bits[k] = k; oldpop[j].parent[0] = 0; /* Initialize parent info */ oldpop[j].parent[1] = 0; oldpop[j].xsite1 = 0; /* Initialize crossover sites */ oldpop[j].xsite2 = 0; oldpop[j].placemut = 0; /* Initialize mutation place */ oldpop[j].mutation = 0; /* Initialize mutation indicator */ } for (bc = CODESIZE; bc > CODESIZE/2; bc--) { // We need a balanced bin string rbit = rnd(0, bc-1); oldpop[j].chrom[ bits[rbit] ] = 1; for (k = rbit; k < bc-1; k++) // Shift the array bits[k] = bits[k+1]; bc--; } objfunc(&(oldpop[j])); // Set the fitness } }
void neighborhoodChange(double* x, double* y, double *fx, const int DIM, int *k, const int FUNCTION, int *best_aval, int *aval, double *fy, int lb, int ub){ /*{{{*/ checkisLbUb(y,DIM,lb,ub); *fy = objfunc(y,&FUNCTION,&DIM,aval); if( *fy < *fx){ *best_aval = *aval; memcpy(x,y,DIM*sizeof(double));//set as start value *fx = *fy; *k = 1; }else{ *k += 1; } }/*}}}*/
void *PRVNS(void *arg){//Populational Reduced VNS/*{{{*/ pVNS *vns = arg; int i,j, t=0,iter=0; int r1,r2,p, best_aval, best_index; double *y = malloc(sizeof(double) * vns->DIM); double fy; double bestfo; //GRAFICOS //INICIO Grafico Convergencia inicializacao #ifdef GRAFICO char *vns_plot_k; /* char *vns_plot_best; */ double sum=0; char file_name[100]; if(GRAFICO == 1){ /* vns_plot_best = (char *) malloc(sizeof(char) * vns->TMAX * 1000); */ sprintf(file_name,"Convergencia/VNS_%d_%d_%d_%d",vns->METHOD,vns->DIM,vns->FUNCTION,vns->RUN); }else if(GRAFICO == 2){ vns_plot_k = (char *) malloc(sizeof(char) * vns->TMAX * 1000); sprintf(file_name,"Convergencia/VNS_K_%d_%d_%d_%d",vns->METHOD,vns->DIM,vns->FUNCTION,vns->RUN); } #endif //FIM Grafico Convergencia inicializacao //definir raio vns->r = malloc(sizeof(double) * vns->KMAX); vns->r[0] = 0.1f; vns->r[1] = 0.3f; vns->r[2] = 0.5f; vns->r[3] = 0.7f; vns->r[4] = 0.9f; //inicializar populacao pVNS **x = malloc (sizeof (pVNS*) * (vns->VNS_POP +1) ); //faz o primeira antes para pegar o melhor x[0] = malloc (sizeof (pVNS)); x[0]->know = 0; x[0]->best = malloc(sizeof(double) * vns->DIM); //the start point for (j=0; j<vns->DIM;j++) //each dimension { x[0]->best[j] = randon(vns->LB,vns->UB); } //avaliar individuo x[0]->bestfo = objfunc(x[0]->best,&vns->FUNCTION,&vns->DIM,&t); //inicializa o melhor bestfo = x[0]->bestfo; best_aval = t; best_index = 0; for(i=1;i<vns->VNS_POP;i++){ x[i] = malloc (sizeof (pVNS)); x[i]->know = 0; x[i]->best = malloc(sizeof(double) * vns->DIM); //the start point for (j=0; j<vns->DIM;j++) //each dimension { x[i]->best[j] = randon(vns->LB,vns->UB); } //evaluate indivi x[i]->bestfo = objfunc(x[i]->best,&vns->FUNCTION,&vns->DIM,&t); if(x[i]->bestfo < bestfo){ bestfo = x[i]->bestfo; best_aval = t; best_index = i; } } #ifdef DEBUG if(DEBUG == 2){ printf("\nGeracao=> %d\n",iter); for(i=0;i<vns->VNS_POP;i++){ printf("x[%d]=> [",i); for(j=0;j<vns->DIM;j++){ printf(" %f",x[i]->best[j]); if(j < vns->DIM -1) printf(","); } printf("] FO=> %f", x[i]->bestfo); if(best_index == i){ printf("*\n"); }else{ printf("\n"); } } } #endif //GRAFICOS #ifdef GRAFICO if(GRAFICO == 1){ geracao = 0; //melhor fo bestfo_geracoes[execucao][geracao] = bestfo; /* //calcular a media para gerar grafico */ fo_geracoes[execucao][geracao] = 0.0f; for (j=0; j<vns->VNS_POP; j++) { fo_geracoes[execucao][geracao] += x[j]->bestfo; } fo_geracoes[execucao][geracao] = fo_geracoes[execucao][geracao]/(double)vns->VNS_POP; if(DEBUG){ printf("\nMedia Geracao[%d] =>%f\n",geracao,fo_geracoes[execucao][geracao]); printf("\nMelhor[%d] =>%f\n",geracao,bestfo_geracoes[execucao][geracao]); } }else if(GRAFICO == 2){ //calcular a media de K para gerar grafico sum = 0; for(j=0;j<vns->VNS_POP;j++){ sum += x[j]->know + 1; } sprintf(vns_plot_k, "%s %d %lf\n ",vns_plot_k,iter,(double)sum/vns->VNS_POP); } #endif time (&(vns->solv.stime)); while((iter + 1 < vns->G_MAX) && ((t + vns->VNS_POP) <= vns->TMAX)){ #ifdef GRAFICO if(GRAFICO){ geracao++; } #endif //etapa populacional for(i =0; i < vns->VNS_POP;i++){ //usar os whiles separados para tentar melhorar o tempo //seleciona um por vez pode ser melhor que selecionar todos //e testar no mesmo while do{ r1 = randon(0,vns->VNS_POP); }while(r1 == i); do{ r2 = randon(0,vns->VNS_POP); }while( r1 == r2 || r2 == i ); //pos na dim para sempre perturbar p = randon(0,vns->DIM); #ifdef DEBUG if(DEBUG == 2){ printf("r1=> %d r2=> %d p=> %d\n",r1,r2,p); } #endif //etapa da evolucao diferencial for(j=0;j<vns->DIM;j++){ if( (j == p) || (randon(0,1) < vns->PC)){ y[j] = x[r2]->best[j] + ( randon(-1.0f * vns->r[x[i]->know], vns->r[x[i]->know]) * x[r1]->best[j] ); /* y[j] = x[i]->best[j] + ( randon(-1.0f * vns->r[x[i]->know], vns->r[x[i]->know]) * x[r1]->best[j] ); */ }else{ y[j] = x[i]->best[j]; } //trata se esta no intervalo permitido da FO if(vns->UB < y[j]){ y[j] = vns->UB; }else if(vns->LB > y[j]){ y[j] = vns->LB; } } //etapa de avaliacao e troca de vizinhanca fy = objfunc(y,&vns->FUNCTION,&vns->DIM,&t); #ifdef DEBUG if(DEBUG == 2){ printf("Depois:\n"); printf("x[%d]=> [",i); for(j=0;j<vns->DIM;j++){ printf(" %f",y[j]); if(j < vns->DIM -1) printf(","); } printf("] FO=> %f", fy); if(best_index == i){ printf("*\n"); }else{ printf("\n"); } } #endif if(fy < x[i]->bestfo){ memcpy(x[i]->best,y,sizeof(double) * vns->DIM); /* x[i]->best = y; */ x[i]->bestfo = fy; x[i]->know = 0; if(x[i]->bestfo < bestfo){ bestfo = x[i]->bestfo; best_aval = t; best_index = i; } }else{ if(x[i]->know <= vns->KMAX -1){ x[i]->know += 1; }else{ x[i]->know = 0; //reinicia k } } } iter++; #ifdef DEBUG if(DEBUG == 2){ printf("\nGeracao=> %d\n",iter); for(i=0;i<vns->VNS_POP;i++){ printf("x[%d]=> [",i); for(j=0;j<vns->DIM;j++){ printf(" %f",x[i]->best[j]); if(j < vns->DIM -1) printf(","); } printf("] FO=> %f", x[i]->bestfo); if(best_index == i){ printf("*\n"); }else{ printf("\n"); } } } #endif #ifdef GRAFICO //GRAFICOS if(GRAFICO == 1){ //melhor fo bestfo_geracoes[execucao][geracao] = bestfo; /* //calcular a media para gerar grafico */ fo_geracoes[execucao][geracao] = 0.0f; for (j=0; j<vns->VNS_POP; j++) { fo_geracoes[execucao][geracao] += x[j]->bestfo; } fo_geracoes[execucao][geracao] = fo_geracoes[execucao][geracao]/(double)vns->VNS_POP; if(DEBUG){ printf("\nMedia Geracao[%d] =>%f\n",geracao,fo_geracoes[execucao][geracao]); printf("\nMelhor Geracao[%d] =>%f\n",geracao,bestfo_geracoes[execucao][geracao]); } }else if(GRAFICO == 2){ //calcular a media de K para gerar grafico sum = 0; for(j=0;j<vns->VNS_POP;j++){ sum += x[j]->know + 1; } sprintf(vns_plot_k, "%s %d %lf\n ",vns_plot_k,iter,(double)sum/vns->VNS_POP); } #endif } time (&(vns->solv.etime)); vns->solv.t_total = difftime(vns->solv.etime,vns->solv.stime); printf("\n==RUN: %d\n",vns->RUN); /* printf("VNS total number of avaliations : %d\n",vns_cont); */ /* printf("Hooke total number of avaliations: %d\n",hooke_geral_cont); */ printf("Total number of avaliation: %d\n",t); printf("Best solution found == %g\n",bestfo); printf("Time: == %.0f seconds\n",vns->solv.t_total); vns->solv.c_aval=t; vns->solv.c_aval_best=best_aval; vns->solv.bestfo=bestfo; printf("\n"); /* free(f_name); */ /* free(vns_plot); */ /* free(x); */ /* free(y); */ /* free(r); */ #ifdef GRAFICO if(GRAFICO == 2){ grafico_linhas_x_y(vns_plot_k,"Geracoes","K","PRVNS","K",file_name); } /* grafico_linhas_x_y(vns_plot_best,"Geracoes","FO","PRVNS","PRVNS",file_name); */ #endif //when return, return the best of the best return (void*)arg; }/*}}}*/
void *PPRVNS_Master(void *arg){//Populational Reduced VNS/*{{{*/ /* typedef struct _VNS_ISLAND { int id; int neighborhood_id; double **sol_migration; //sol_migration[MIGRATION_PERCENT] double **pop; //pop[POP_SIZE + MIGRATION_PERCENT] double *pop_fo; //pop[POP_SIZE + MIGRATION_PERCENT] double *best; int best_index; double bestfo; }pVNS_ISLAND; */ pVNS *vns = arg; int i,j,t,rc; int MIGRATION_INTERVAL = 1; int MIGRATION_PERCENT=5; int ISLANDS = 3; pthread_t islands_thread[ISLANDS]; void *status; vns->MIGRATION_SIZE = (vns->MIGRATION_PERCENT * 100)/vns->VNS_POP +1;//round up vns->islands_mutex = (pthread_mutex_t *) malloc (sizeof (pthread_mutex_t)*(vns->ISLANDS); vns->islands = (pVNS **) malloc (sizeof (pVNS*)*vns->ISLANDS); pVNS islands_sol[ISLANDS];// = (pVNS **) malloc (sizeof (pVNS*)*ISLANDS); //definir raio vns->r = malloc(sizeof(double) * vns->KMAX); vns->r[0] = 0.1f; vns->r[1] = 0.3f; vns->r[2] = 0.5f; vns->r[3] = 0.7f; vns->r[4] = 0.9f; vns->know = 0; //TODO randon start on thread for(t=0; t<ISLANDS; t++){ islands_sol[t] = (pVNS *) malloc (sizeof (pVNS)); islands_sol[t].vns_params = (pVNS *) malloc (sizeof (pVNS)); memccpy(vns->islands[t].vns_params,vns,sizeof(pVNS)); islands_sol[t].id = t; islands_sol[t].neighborhood_id = t+1; islands_sol[t].sol_migration = (double **) malloc (sizeof (double*)*vns->MIGRATION_SIZE); for(i=0; i<vns->MIGRATION_SIZE; i++){ islands_sol[t].sol_migration[i] = (double *) malloc (sizeof (double)*vns->DIM); } islands_sol[t].pop = (pVNS **) malloc (sizeof (pVNS*)*vns->VNS_POP); for(i=0; i<vns->VNS_POP; i++){ islands_sol[t].pop[i] = malloc (sizeof (pVNS)); } islands_sol[t].pop[i]->best = malloc(sizeof(double) * vns->DIM); //the start point for (j=0; j<vns->DIM;j++) //each dimension {//TODO continue from her, adjust to pop[i] islands_sol[t].pop[i]->best[j] = randon(vns->LB,vns->UB); } //avaliar individuo islands_sol[t].bestfo = objfunc(islands_sol[t].best,&vns->FUNCTION,&vns->DIM,&t); islands_sol[t].best_index = 0; for (j=1; j<vns->VNS_POP;j++) //each dimension { for(i=0;i<vns->DIM;i++){ islands_sol[t].pop[j][i] = randon(vns->LB,vns->UB); } //evaluate indivi islands_sol[t].pop_fo[j] = objfunc(islands_sol[t].pop[j],&vns->FUNCTION,&vns->DIM,&t); if(islands_sol[t].pop_fo[j] < bestfo){ islands_sol[t].bestfo = islands_sol[t].pop_fo[j]; islands_sol[t].best_index = j; } } } islands_sol[ISLANDS-1].neighborhood_id = 0;//the last points to first /* for(i=0;i<MIGRATION_INTERVAL;i++){ */ for(t=0; t<ISLANDS; t++){ printf("In PPRVNS_Master: creating thread %d\n", t); rc = pthread_create(&islands_thread[t], NULL, PPRVNS_Island, (void *)&islands_sol[t]); if (rc){ printf("ERROR; return code from pthread_create() is %d\n", rc); exit(-1); } } for(t=0; t<ISLANDS; t++) { printf("joining tread %d\n",t); rc = pthread_join(islands_thread[t], NULL); if (rc) { printf("ERROR; return code from pthread_join() is %d\n", rc); exit(-1); } printf("Main: completed join with thread %d having a best of %g\n",t, islands_sol[t].solv.bestfo); } /* } */ //TODO return only the best return vns; }/*}}}*/
void *RVNS(void *arg){//Reduced VNS pVNS *vns = arg; int t = 0,k=1,j; int best_aval = 0; int shake_one = 1; bool stop = false; int avalmax_aux=0; int shake_cont =0; int vns_cont = 0; double *x,*x2,*y,*r; double fx,fy; int run=vns->RUN; int p = vns->P; x = malloc (vns->DIM * sizeof(double)); x2 = malloc (vns->DIM * sizeof(double)); y = malloc (vns->DIM * sizeof(double)); //GRAFICOS //INICIO Grafico Convergencia inicializacao #ifdef GRAFICO char *vns_plot_k; /* char *vns_plot_best; */ char file_name[100]; if(GRAFICO == 1){ /* vns_plot_best = (char *) malloc(sizeof(char) * vns->TMAX * 1000); */ sprintf(file_name,"Convergencia/VNS_%d_%d_%d_%d",vns->METHOD,vns->DIM,vns->FUNCTION,vns->RUN); }else if(GRAFICO == 2){ vns_plot_k = (char *) malloc(sizeof(char) * vns->TMAX * 1000); sprintf(file_name,"Convergencia/VNS_K_%d_%d_%d_%d",vns->METHOD,vns->DIM,vns->FUNCTION,vns->RUN); } #endif //FIM Grafico Convergencia inicializacao r = (double*)malloc ( (vns->KMAX+1) *sizeof(double)); if(vns->r == NULL) vns->r = (double*)malloc ( (vns->KMAX+1) *sizeof(double)); //set wich radii value r[0] = 0.0f; for(j=1;j<=vns->KMAX;j++){ r[j] = vns->RADII; vns->r[j] = r[j]; vns->RADII*=vns->Q; } /* memcpy(vns->r,r,sizeof(double)* (vns->KMAX + 1)); */ run = vns->RUN+1; t=0; k=1; vns_cont=0; avalmax_aux=0; shake_cont=0; stop=false; memcpy(x,vns->best,sizeof(double)*vns->DIM); memcpy(x2,x,vns->DIM*sizeof(double));//set as start value, just for initialize memcpy(y,x,vns->DIM*sizeof(double));//set as start value, just for initialize fx = objfunc(x,&vns->FUNCTION,&vns->DIM,&t);//initialize fx avalmax_aux = vns->AVAL_MAX; //GRAFICOS #ifdef GRAFICO if(GRAFICO == 1){ geracao = 0; //melhor fo bestfo_geracoes[execucao][geracao] = fx; if(DEBUG){ printf("\nMelhor[%d] =>%f\n",geracao,bestfo_geracoes[execucao][geracao]); } }else if(GRAFICO == 2){ //calcular a media de K para gerar grafico sprintf(vns_plot_k, "%s %d %lf\n ",vns_plot_k,vns_cont,(double)k); } #endif time (&(vns->solv.stime)); while(t < vns->TMAX && !stop){ k=1; while(k<=vns->KMAX && t< vns->TMAX && !stop){ /* t++; */ vns_cont++; //do shake */ /* shake_one(x, y, r, k,vns->KMAX,vns->DIM,vns->LB,vns->UB,&shake_cont,vns->RADII_T_FLAG,p); */ shake(x, y, r, k,vns->DIM,vns->LB,vns->UB,&shake_cont,vns->RADII_T_FLAG,p,shake_one,0.5f); if( (vns->TMAX - t) < avalmax_aux){ avalmax_aux = vns->TMAX -t; } //change neighborhood, x<= receive the best or the same neighborhoodChange(x,y,&fx,vns->DIM,&k,vns->FUNCTION,&best_aval,&t,&fy,vns->LB,vns->UB); /* if(fx == 0.0f){ */ /* if(vns->FUNCTION == 8){ */ /* if(-418.0 > fx){ */ /* printf("Find the best solution before finis2h!\n"); */ /* stop = true; */ /* }else{ */ /* continue; */ /* } */ /* }else if(fx < (1E-10)){ */ /* printf("Find the best solution before finish!\n"); */ /* stop = true; */ /* } */ //GRAFICOS #ifdef GRAFICO if(GRAFICO == 1 && t%50 ==0){ geracao++; //melhor fo memcpy(&bestfo_geracoes[execucao][geracao],&fx,sizeof(double)); if(DEBUG){ printf("\nMelhor[%d][%d] =>%f\n",execucao,geracao,bestfo_geracoes[execucao][geracao]); } }else if(GRAFICO == 2){ //calcular a media de K para gerar grafico /* sprintf(vns_plot_k, "%s %d %lf\n ",vns_plot_k,vns_cont,(double)k); */ } #endif } } time (&(vns->solv.etime)); vns->solv.t_total = difftime(vns->solv.etime,vns->solv.stime); printf("\n==RUN: %d\n",run); printf("Total number of avaliation: %d\n",t); printf("Best solution found == %.10f\n",fx); printf("Time: == %.0f seconds\n",vns->solv.t_total); vns->solv.c_aval=t; vns->solv.c_aval_best=best_aval; vns->solv.bestfo=fx; free(x); free(y); free(r); return (void*)arg; }
void *BVNS_NM(void *arg){//VNSM com NM pVNS *vns = arg; int t = 0,k=1,i,j; int best_aval = 0; bool stop = false; int shake_cont =0; int vns_cont = 0; double *x,*x2,*y,*r; double fx,fy; int run=vns->RUN; int p=vns->P; int nelmin_cont = 0; double *simplex; int shake_one = 1; int avalmax_aux=0; int num_restart = 0; int ifault = 0; simplex = (double*) malloc ((vns->DIM +1) * sizeof(double)); x = (double*) malloc (vns->DIM * sizeof(double)); x2 = (double*) malloc (vns->DIM * sizeof(double)); y = (double*)malloc (vns->DIM * sizeof(double)); r = (double*)malloc ( (vns->KMAX+1) *sizeof(double)); //set wich radii value r[0] = 0.0f; for(j=vns->KMAX;j>=1;j--){ r[j] = vns->RADII; vns->RADII*=vns->Q; } run = vns->RUN+1; t=0; k=1; vns_cont=0; int vns_geral_cont=0; shake_cont=0; stop=false; for (i=0; i<vns->DIM;i++) //each dimension { x[i] = randon(vns->LB,vns->UB); } memcpy(x2,x,vns->DIM*sizeof(double));//set as start value, just for initialize memcpy(y,x,vns->DIM*sizeof(double));//set as start value, just for initialize fx = objfunc(x,&vns->FUNCTION,&vns->DIM,&t);//initialize fx time (&(vns->solv.stime)); while(t < vns->TMAX && !stop){ k=1; while(k<=vns->KMAX && t< vns->TMAX && !stop){ //do shake */ shake(x, y, r, k,vns->DIM,vns->LB,vns->UB,&shake_cont,vns->RADII_T_FLAG,p,shake_one,1.0f); for(i=0;i<vns->DIM;i++){ simplex[i] = x[i]; //inicializa o simplex com indice igual, menos o final } simplex[vns->DIM] = randon(vns->LB,vns->UB); //o ultimo faz aleatorio if( (vns->TMAX - t) < avalmax_aux){ avalmax_aux = vns->TMAX -t; } nelmin(vns->DIM, x, x, &fx, vns->EPSILON , simplex,avalmax_aux, &nelmin_cont, &num_restart, &ifault, vns->FUNCTION ); avalmax_aux = vns->AVAL_MAX; /* printf("nelmin_cont => %d valor => %.2f\n",nelmin_cont,fx); */ t+=nelmin_cont; nelmin_cont = 0; if(checkisLbUb(x,vns->DIM,vns->LB,vns->UB)){ fx = objfunc(x,&vns->FUNCTION,&vns->DIM,&t); //<= fx vem do nelmin, so atualiza se mudar pelo checkisLBUL } //change neighborhood, x<= receive the best or the same neighborhoodChange(x,x2,&fx,vns->DIM,&k,vns->FUNCTION,&best_aval,&vns_cont,&fy,vns->LB,vns->UB); t+=vns_cont; vns_geral_cont+=vns_cont; vns_cont=0; /* if(vns->FUNCTION == 8){ */ /* if(-418.0 > fx){ */ /* printf("Find the best solution before finis2h!\n"); */ /* stop = true; */ /* }else{ */ /* continue; */ /* } */ /* }else if(fx < (1E-10)){ */ /* printf("Find the best solution before finish!\n"); */ /* stop = true; */ /* } */ /* if(fx == fy){ */ /* printf("Improved with %d avaliation and %.20f value \n",t,fx); */ /* } */ } } t--; time (&(vns->solv.etime)); vns->solv.t_total = difftime(vns->solv.etime,vns->solv.stime); printf("\n==RUN: %d\n",run); /* printf("VNS total number of avaliations : %d\n",vns_geral_cont); */ /* printf("NM total number of avaliations: %d\n",nm_geral_cont); */ printf("Total number of avaliation: %d\n",t); printf("Best solution found == %.10f\n",fx); printf("Time: == %.0f seconds\n",vns->solv.t_total); vns->solv.c_aval=t; vns->solv.c_aval_best=best_aval; vns->solv.bestfo=fx; printf("\n"); free(x); free(x2); free(y); free(r); return (void*)arg; }
void *NM(void *arg){//Only Nelder Mead pVNS *vns = arg; int t = 0,i; bool stop = false; double *x; int nelmin_cont = 0; double *simplex; int num_restart = 0; double stop_condition = 1E-20; int ifault = 0; double fx = 0; int run=vns->RUN; x = (double*) malloc (vns->DIM * sizeof(double)); simplex = (double*) malloc ((vns->DIM +1) * sizeof(double)); run = vns->RUN+1; t=0; nelmin_cont=0; stop=false; for (i=0; i<vns->DIM;i++) //each dimension { x[i] = randon(vns->LB,vns->UB); } time (&(vns->solv.stime)); while(t < vns->TMAX && !stop){ /* t++; */ for(i=0;i<vns->DIM;i++){ simplex[i] = x[i]; //inicializa o simplex com indice igual, menos o final } simplex[vns->DIM] = randon(vns->LB,vns->UB); //o ultimo faz aleatorio nelmin(vns->DIM, x, x, &fx, stop_condition , simplex,vns->TMAX - t, &nelmin_cont, &num_restart, &ifault, vns->FUNCTION ); t+=nelmin_cont; nelmin_cont = 0; if(checkisLbUb(x,vns->DIM,vns->LB,vns->UB)){ fx = objfunc(x,&vns->FUNCTION,&vns->DIM,&t); //<= fx vem do nelmin, so atualiza se mudar pelo checkisLBUL } /* t = t + nelmin_cont; */ /* if(fx == 0.0f){ */ /* if(vns->FUNCTION == 8){ */ /* if(-418.0 > fx){ */ /* printf("Find the best solution before finis2h!\n"); */ /* stop = true; */ /* }else{ */ /* continue; */ /* } */ /* }else if(fx < (1E-10)){ */ /* printf("Find the best solution before finish!\n"); */ /* stop = true; */ /* } */ /* printf("Improved with %d avaliation and %.20f value\n",t,fx); */ } time (&(vns->solv.etime)); vns->solv.t_total = difftime(vns->solv.etime,vns->solv.stime); printf("\n==RUN: %d\n",run); printf("Total number of avaliation with NM: %d\n",t); printf("Best solution found == %.10f\n",fx); vns->solv.c_aval=t; vns->solv.c_aval_best=t; vns->solv.bestfo=fx; printf("\n"); free(x); free(simplex); return (void*)arg; }
void *HJ(void *arg){//Only Hooke and Jaevees pVNS *vns = arg; int t = 0,i; bool stop = false; int avalmax_aux=0; double *x; double fx; int run=vns->RUN; x = (double*) malloc (vns->DIM * sizeof(double)); run = vns->RUN+1; t=0; avalmax_aux=0; stop=false; for (i=0; i<vns->DIM;i++) //each dimension { x[i] = randon(vns->LB,vns->UB); } fx = objfunc(x,&vns->FUNCTION,&vns->DIM,&t);//initialize fx avalmax_aux = vns->AVAL_MAX; time (&(vns->solv.stime)); while(t < vns->TMAX && !stop){ /* t++; */ if( (vns->TMAX - t) < avalmax_aux){ avalmax_aux = vns->TMAX -t; } hooke(vns->DIM, x, x, vns->RHO, vns->EPSILON, avalmax_aux, vns->FUNCTION,&t); checkisLbUb(x,vns->DIM,vns->LB,vns->UB); /* t = t + hooke_cont; */ //change neighborhood, x<= receive the best or the same fx = objfunc(x,&vns->FUNCTION,&vns->DIM,&t); /* if(fx == 0.0f){ */ /* if(vns->FUNCTION == 8){ */ /* if(-418.0 > fx){ */ /* printf("Find the best solution before finis2h!\n"); */ /* stop = true; */ /* }else{ */ /* continue; */ /* } */ /* }else if(fx < (1E-10)){ */ /* printf("Find the best solution before finish!\n"); */ /* stop = true; */ /* } */ /* printf("Improved with %d avaliation and %.20f value\n",t,fx); */ } time (&(vns->solv.etime)); printf("\n==RUN: %d\n",run); printf("Total number of avaliation with HJ: %d\n",t); printf("Best solution found == %.10f\n",fx); vns->solv.c_aval=t; vns->solv.c_aval_best=t; vns->solv.bestfo=fx; printf("\n"); free(x); vns->solv.t_total = difftime(vns->solv.etime,vns->solv.stime); return (void*)arg; }
void *BVNS(void *arg){//VNS com HJ pVNS *vns = arg; int t = 0,k=1,j; int best_aval = 0; int hooke_cont = 0; bool stop = false; int avalmax_aux=0; int shake_cont =0; int hooke_geral_cont = 0; int vns_cont = 0; double *x,*x2,*y,*r; double fx,fy; int run=vns->RUN; int p = vns->P; x = (double*) malloc (vns->DIM * sizeof(double)); x2 = (double*) malloc (vns->DIM * sizeof(double)); y = (double*)malloc (vns->DIM * sizeof(double)); r = (double*)malloc ( (vns->KMAX+1) *sizeof(double)); vns->r = (double*)malloc ( (vns->KMAX+1) *sizeof(double)); //set wich radii value r[0] = 0.0f; for(j=1;j<=vns->KMAX;j++){ r[j] = vns->RADII; vns->RADII*=vns->Q; } memcpy(vns->r,r,sizeof(double)*vns->KMAX+1); run = vns->RUN+1; t=0; k=1; vns_cont=0; hooke_cont=0; hooke_geral_cont=0; avalmax_aux=0; shake_cont=0; stop=false; memcpy(x,vns->best,sizeof(double)*vns->DIM); memcpy(x2,x,vns->DIM*sizeof(double));//set as start value, just for initialize memcpy(y,x,vns->DIM*sizeof(double));//set as start value, just for initialize fx = objfunc(x,&vns->FUNCTION,&vns->DIM,&t);//initialize fx avalmax_aux = vns->AVAL_MAX; time (&(vns->solv.stime)); while(t < vns->TMAX -1 && !stop){ k=1; while(k<=vns->KMAX && t< vns->TMAX && !stop){ /* t++; */ vns_cont++; //do shake */ shake_one(x, y, r, k,vns->DIM,vns->LB,vns->UB,&shake_cont,vns->RADII_T_FLAG,p); if( (vns->TMAX - t) < avalmax_aux){ avalmax_aux = vns->TMAX -t; } shake_cont = hooke(vns->DIM, y, x2, vns->RHO, vns->EPSILON, avalmax_aux, vns->FUNCTION,&hooke_cont); /* checkisLbUb(x2,vns->DIM,vns->LB,vns->UB); */ t += hooke_cont; hooke_geral_cont+=hooke_cont; hooke_cont=0; avalmax_aux = vns->AVAL_MAX; //change neighborhood, x<= receive the best or the same neighborhoodChange(x,x2,&fx,vns->DIM,&k,vns->FUNCTION,&best_aval,&t,&fy,vns->LB,vns->UB); /* if(vns->FUNCTION == 8){ */ /* if(-418.0 > fx){ */ /* printf("Find the best solution before finis2h!\n"); */ /* stop = true; */ /* }else{ */ /* continue; */ /* } */ /* }else if(fx < (1E-10)){ */ /* printf("Find the best solution before finish!\n"); */ /* stop = true; */ /* } */ } } time (&(vns->solv.etime)); vns->solv.t_total = difftime(vns->solv.etime,vns->solv.stime); printf("\n==RUN: %d\n",run); printf("VNS total number of avaliations : %d\n",vns_cont); printf("Hooke total number of avaliations: %d\n",hooke_geral_cont); printf("Total number of avaliation: %d\n",t); printf("Best solution found == %.10f\n",fx); printf("Time: == %.0f seconds\n",vns->solv.t_total); vns->solv.c_aval=t; vns->solv.c_aval_best=best_aval; vns->solv.bestfo=fx; printf("\n"); free(x); free(x2); free(y); free(r); return (void*)arg; }
void UntangleWrapper::run_wrapper( MeshDomainAssoc* mesh_and_domain, ParallelMesh* pmesh, Settings* settings, QualityAssessor* qa, MsqError& err ) { Instruction::initialize_vertex_byte( mesh_and_domain, settings, err ); MSQ_ERRRTN(err); Mesh* mesh = mesh_and_domain->get_mesh(); // get some global mesh properties SimpleStats edge_len, lambda; std::auto_ptr<MeshUtil> tool(new MeshUtil( mesh, settings )); tool->edge_length_distribution( edge_len, err ); MSQ_ERRRTN(err); tool->lambda_distribution( lambda, err ); MSQ_ERRRTN(err); tool.reset(0); // get target metrics from user perferences TSizeNB1 mu_size; TShapeSize2DNB1 mu_shape_2d; TShapeSize3DNB1 mu_shape_3d; TMixed mu_shape( &mu_shape_2d, &mu_shape_3d ); std::auto_ptr<TMetric> mu; if (qualityMetric == BETA) { double beta = metricConstant; if (beta < 0) beta = (lambda.average()*lambda.average())/20; //std::cout << "beta= " << beta << std::endl; mu.reset(new TUntangleBeta( beta )); } else { TMetric* sub = 0; if (qualityMetric == SIZE) sub = &mu_size; else sub = &mu_shape; if (metricConstant >= 0) mu.reset(new TUntangleMu( sub, metricConstant )); else mu.reset(new TUntangleMu( sub )); } // define objective function IdealShapeTarget base_target; LambdaConstant target( lambda.average(), &base_target ); TQualityMetric metric_0(&target, mu.get()); ElementPMeanP metric( 1.0, &metric_0 ); PMeanPTemplate objfunc( 1.0, &metric ); // define termination criterion double eps = movementFactor * (edge_len.average() - edge_len.standard_deviation()); TerminationCriterion inner("<type:untangle_inner>", TerminationCriterion::TYPE_INNER), outer("<type:untangle_outer>", TerminationCriterion::TYPE_OUTER); outer.add_untangled_mesh(); if (doCulling) inner.cull_on_absolute_vertex_movement( eps ); else outer.add_absolute_vertex_movement( eps ); if (maxTime > 0.0) outer.add_cpu_time( maxTime ); inner.add_iteration_limit( NUM_INNER_ITERATIONS ); if (maxIterations > 0) outer.add_iteration_limit(maxIterations); // construct solver SteepestDescent solver( &objfunc ); solver.use_element_on_vertex_patch(); solver.set_inner_termination_criterion( &inner ); solver.set_outer_termination_criterion( &outer ); if (doJacobi) solver.do_jacobi_optimization(); else solver.do_gauss_optimization(); // Run qa->add_quality_assessment( &metric ); InstructionQueue q; q.add_quality_assessor( qa, err ); MSQ_ERRRTN(err); q.set_master_quality_improver( &solver, err ); MSQ_ERRRTN(err); q.add_quality_assessor( qa, err ); MSQ_ERRRTN(err); q.run_common( mesh_and_domain, pmesh, settings, err ); MSQ_ERRRTN(err); }
double simplex(double (*objfunc)(double[], void *extra), double start[],int n, double EPSILON, double scale, void (*constrain)(double[],int n), void *extra) { int vs; /* vertex with smallest value */ int vh; /* vertex with next smallest value */ int vg; /* vertex with largest value */ int i,j,m,row; int k; /* track the number of function evaluations */ int itr; /* track the number of iterations */ double **v; /* holds vertices of simplex */ double pn,qn; /* values used to create initial simplex */ double *f; /* value of function at each vertex */ double fr; /* value of function at reflection point */ double fe; /* value of function at expansion point */ double fc; /* value of function at contraction point */ double *vr; /* reflection - coordinates */ double *ve; /* expansion - coordinates */ double *vc; /* contraction - coordinates */ double *vm; /* centroid - coordinates */ double min; double fsum,favg,s,cent; /* dynamically allocate arrays */ /* allocate the rows of the arrays */ v = (double **) malloc ((n+1) * sizeof(double *)); f = (double *) malloc ((n+1) * sizeof(double)); vr = (double *) malloc (n * sizeof(double)); ve = (double *) malloc (n * sizeof(double)); vc = (double *) malloc (n * sizeof(double)); vm = (double *) malloc (n * sizeof(double)); /* allocate the columns of the arrays */ for (i=0;i<=n;i++) { v[i] = (double *) malloc (n * sizeof(double)); } /* create the initial simplex */ /* assume one of the vertices is 0,0 */ pn = scale*(sqrt(n+1)-1+n)/(n*sqrt(2)); qn = scale*(sqrt(n+1)-1)/(n*sqrt(2)); for (i=0;i<n;i++) { v[0][i] = start[i]; } for (i=1;i<=n;i++) { for (j=0;j<n;j++) { if (i-1 == j) { v[i][j] = pn + start[j]; } else { v[i][j] = qn + start[j]; } } } if (constrain != NULL) { constrain(v[j],n); } /* find the initial function values */ for (j=0;j<=n;j++) { f[j] = objfunc(v[j], extra); } k = n+1; /* print out the initial values */ /* printf("Initial Values\n"); for (j=0;j<=n;j++) { for (i=0;i<n;i++) { printf("%f %f\n",v[j][i],f[j]); } } */ /* begin the main loop of the minimization */ for (itr=1;itr<=MAX_IT;itr++) { /* find the index of the largest value */ vg=0; for (j=0;j<=n;j++) { if (f[j] > f[vg]) { vg = j; } } /* find the index of the smallest value */ vs=0; for (j=0;j<=n;j++) { if (f[j] < f[vs]) { vs = j; } } /* find the index of the second largest value */ vh=vs; for (j=0;j<=n;j++) { if (f[j] > f[vh] && f[j] < f[vg]) { vh = j; } } /* calculate the centroid */ for (j=0;j<=n-1;j++) { cent=0.0; for (m=0;m<=n;m++) { if (m!=vg) { cent += v[m][j]; } } vm[j] = cent/n; } /* reflect vg to new vertex vr */ for (j=0;j<=n-1;j++) { /*vr[j] = (1+ALPHA)*vm[j] - ALPHA*v[vg][j];*/ vr[j] = vm[j]+ALPHA*(vm[j]-v[vg][j]); } if (constrain != NULL) { constrain(vr,n); } fr = objfunc(vr, extra); k++; if (fr < f[vh] && fr >= f[vs]) { for (j=0;j<=n-1;j++) { v[vg][j] = vr[j]; } f[vg] = fr; } /* investigate a step further in this direction */ if ( fr < f[vs]) { for (j=0;j<=n-1;j++) { /*ve[j] = GAMMA*vr[j] + (1-GAMMA)*vm[j];*/ ve[j] = vm[j]+GAMMA*(vr[j]-vm[j]); } if (constrain != NULL) { constrain(ve,n); } fe = objfunc(ve, extra); k++; /* by making fe < fr as opposed to fe < f[vs], Rosenbrocks function takes 63 iterations as opposed to 64 when using double variables. */ if (fe < fr) { for (j=0;j<=n-1;j++) { v[vg][j] = ve[j]; } f[vg] = fe; } else { for (j=0;j<=n-1;j++) { v[vg][j] = vr[j]; } f[vg] = fr; } } /* check to see if a contraction is necessary */ if (fr >= f[vh]) { if (fr < f[vg] && fr >= f[vh]) { /* perform outside contraction */ for (j=0;j<=n-1;j++) { /*vc[j] = BETA*v[vg][j] + (1-BETA)*vm[j];*/ vc[j] = vm[j]+BETA*(vr[j]-vm[j]); } if (constrain != NULL) { constrain(vc,n); } fc = objfunc(vc, extra); k++; } else { /* perform inside contraction */ for (j=0;j<=n-1;j++) { /*vc[j] = BETA*v[vg][j] + (1-BETA)*vm[j];*/ vc[j] = vm[j]-BETA*(vm[j]-v[vg][j]); } if (constrain != NULL) { constrain(vc,n); } fc = objfunc(vc, extra); k++; } if (fc < f[vg]) { for (j=0;j<=n-1;j++) { v[vg][j] = vc[j]; } f[vg] = fc; } /* at this point the contraction is not successful, we must halve the distance from vs to all the vertices of the simplex and then continue. 10/31/97 - modified to account for ALL vertices. */ else { for (row=0;row<=n;row++) { if (row != vs) { for (j=0;j<=n-1;j++) { v[row][j] = v[vs][j]+(v[row][j]-v[vs][j])/2.0; } } } if (constrain != NULL) { constrain(v[vg],n); } f[vg] = objfunc(v[vg], extra); k++; if (constrain != NULL) { constrain(v[vh],n); } f[vh] = objfunc(v[vh], extra); k++; } } /* print out the value at each iteration */ /* printf("Iteration %d\n",itr); for (j=0;j<=n;j++) { for (i=0;i<n;i++) { printf("%f %f\n",v[j][i],f[j]); } } */ /* test for convergence */ fsum = 0.0; for (j=0;j<=n;j++) { fsum += f[j]; } favg = fsum/(n+1); s = 0.0; for (j=0;j<=n;j++) { s += pow((f[j]-favg),2.0)/(n); } s = sqrt(s); if (s < EPSILON) break; } /* end main loop of the minimization */ /* find the index of the smallest value */ vs=0; for (j=0;j<=n;j++) { if (f[j] < f[vs]) { vs = j; } } // printf("The minimum was found at\n"); for (j=0;j<n;j++) { // printf("%e\n",v[vs][j]); start[j] = v[vs][j]; } min=objfunc(v[vs], extra); k++; // printf("%d Function Evaluations\n",k); // printf("%d Iterations through program\n",itr); free(f); free(vr); free(ve); free(vc); free(vm); for (i=0;i<=n;i++) { free (v[i]); } free(v); return min; }