int* crearArreglo(int cant){ int i, j, a, b, aleatorio; int *arreglo = new int[cant]; for(j=0;j<cant;++j) arreglo[j]=-1; /* Conseguimos una semilla */ srand(time(NULL)); /* Usamos la función para obtener números */ for(i=0;i<cant;i++){ aleatorio=alea(0,cant-1); for(j=0;j<cant;++j){ if(arreglo[j] == aleatorio){ aleatorio = alea(0,cant-1); j=-1; } else if(arreglo[j]==-1){ arreglo[j] = aleatorio; break; } } printf("%i\n", arreglo[i]); //getchar(); } return arreglo; }
troisdes lancer (){ troisdes j; j.d1=alea(1,6); j.d2=alea(1,6); j.d3=alea(1,6); return j; }
void step_function (void * W, void * configuration) { annealing_simple_workspace_t * S = W; configuration_t * C = configuration; fitting_step_t * step = S->max_step_value; C->A += alea(S, step->A); C->lambda += alea(S, step->lambda); C->b += alea(S, step->b); }
int main(int argc, char const *argv[]) { int i; int num= atoi(argv[1]); /* Cuantos numeros que queremos obtener */ char ofilename[] = "datos.dat"; FILE *archivo; if((archivo = fopen(ofilename, "w+"))==NULL){ printf("Error en apertura de archivo"); } double alea(int desde, int hasta) { return rand()%(hasta-desde+1)+desde; } srand(time(NULL)); /* Semilla */ for(i=0;i<num;i++) { fprintf(archivo,"%lf,",alea(-1000,1000)); } fclose(archivo); return 0; }
troisdes rejouer(troisdes idk){ troisdes ikn=idk; int x; aff_des(idk); print_newline(); print_newline(); print_text("voulez vous garder "); print_int(ikn.d1); print_text(" [oui/non] [0/1] ?: "); x=read_int(); if(x==1) ikn.d1=alea(1,6); else ikn.d1=ikn.d1; print_text("voulez vous garder "); print_int(ikn.d2); print_text(" [oui/non] [0/1] ?: "); x=read_int(); if(x==1) ikn.d2=alea(1,6); else ikn.d2=ikn.d2; print_text("voulez vous garder "); print_int(ikn.d3); print_text(" [oui/non] [0/1] ?: "); x=read_int(); if(x==1) ikn.d3=alea(1,6); else ikn.d3=ikn.d3; return ikn; }
Requete generationRequete(){ static int numero = 0; Requete r; numero++; r.numero = numero; r.priorite = alea(NbPriorite); return r; }
Tab initialise_tablo(n){ Tab a; int i; a.taille = n; for(i=0;i<a.taille;i++){ a.tab[i] = alea(20); } return a; }
/* Fais appel à la fonction alea pour la tester. */ void testAlea() { int k = 4, n = 42; image img1 = alea(k, n); printf("Voici votre image aleatoire(%d, %d) :\n", k, n); affichage2k(img1, k); printf("\n"); if(img1 != NULL) rendMemoire(img1); }
void alea_tableau_int(int* tab,int lg) { int i; i=0; while(i<lg) { tab[i]=alea(0,100); i++; } }
Tableau initialise(Tableau T) { T.taille = 10; int i; for(i=0; i<T.taille; i++) { T.tab[i] = alea(20); } return T; }
//structure 2 void simulationFile2(){ Fap2 f2 = initialiseFile2(); int compteur = 0; Requete r; while(compteur < Nmax){ if(alea(2) == 0){ //traitement requête avec proba 0.5 f2 = traiteRequete2(f2); } else{ //génération d'une nouvelle requête avec proba 0.5 compteur++; r = generationRequete(); f2 = ajoutFile2(f2, r); } afficheFile2(f2); } libereMemoire2(f2); printf("########################################\n"); }
void aleapermutvec (double *a) { /* permute au hasard les ÚlÚments du vecteur a Manly p. 42 Le vecteur est modifié from Knuth 1981 p. 139*/ int lig, i,j, k; double z; lig = a[0]; for (i=1; i<=lig-1; i++) { j=lig-i+1; k = (int) (j*alea()+1); /*k = (int) (j*genrand()+1);*/ if (k>j) k=j; z = a[j]; a[j]=a[k]; a[k] = z; } }
void testajout() { int a; liste l1 = initialiser(); /*liste l2 = initialiser(); liste l3 = initialiser();*/ do { a = alea(10); l1 = ajoutdebut(l1,a); /*l2 = ajoutfin(l2,a); l3 = ajouttrie(l3,a);*/ } while (a != 0); afficher_liste(l1); //afficher_liste(l2); //afficher_liste(l3); }
void aleapermutmat (double **a) { /* permute au hasard les lignes du tableau a Manly p. 42 le tableau est modifié */ int lig, i,j, col, n, k; double z; lig = a[0][0]; col = a[1][0]; for (i=1; i<=lig-1; i++) { j=lig-i+1; k = (int) (j*alea ()+1); /*k = (int) (j*genrand()+1);*/ if (k>j) k=j; for (n=1; n<=col; n++) { z = a[j][n]; a[j][n]=a[k][n]; a[k][n] = z; } } }
int main(){ int nombreutilisateur,nombreverifie,nombrealeatoire; bool victoire=false; int compteur=0,rejouer; nombrealeatoire = alea(1,10000); while(victoire==false){ nombreutilisateur = demander(); print_newline(); print_newline(); nombreverifie = verifier(nombreutilisateur); victoire = comparer(nombreverifie,nombrealeatoire); compteur = compteur+1;} print_text("Vous avez trouvé la solution en "); print_int(compteur); print_text(" coups"); print_newline(); print_newline(); print_text("Voulez vous rejouer ? : Oui ? tapez(1), Non ? tapez (2) : "); print_newline(); print_newline(); rejouer=read_int(); if(rejouer==1){main();} else{print_text("Au revoir !"); print_newline();print_newline();} return 0;}
int sdtrw; int tdtrw; }; typedef struct mjetded jetded; int alea (int bmin, int bmax) { //creation d'une valeur aléatoire int nombre; //pour le choix du bot entre 1.2.3.4.5 nombre = bmin + rand() % (bmax - bmin + 1); return nombre; } jetded gobelet (); jetded troisjet; troisjet.fttrw=alea(1,6); troisjet.sdtrw=alea(1,6); troisjet.ttrw=alea(1,6); return troisjet; } int sommedesjet(jetded coup){ int resultataddition; resultataddition=coup.fttrw + coup.sdtrw + coup.ttrw; }
void menu(SDL_Surface *ecran, Sprites &sprites, Boutons &boutons, int &modeMenu, int &modeJeu, SourisEvent &sourisEvent, Time &time, Message msgs[], Partie &partie, Chien &chien) { bool sortir = false; int lastKeyPressed; int lastKeyPressedBis; int lastMenu = 1; bool keyPressed = false; bool keyPressedBis = false; bool defilTouche = false; for (int i=0; i<LONGUEUR_MAX_PSEUDO; i++) { partie.pseudoT[i] = 0; } getScore("scoresClassic", partie.highScore); int carActif = 0; Uint8 *keystate = SDL_GetKeyState(NULL); time.currentTime = SDL_GetTicks(); time.timeMenu = time.currentTime; time.timeKey = time.currentTime; time.timeDefKey = time.currentTime; while (!sortir && modeMenu!=0) { if (getEvents(sourisEvent, 1)) { modeMenu = 0; modeJeu = 0; } time.currentTime = SDL_GetTicks(); switch (modeMenu) { case 0: sortir = true; break; case 1 : boutons.bouton[BOUTON_PLAY].position.x = (LARGEUR - boutons.lecture[0].w) / 2; boutons.bouton[BOUTON_PLAY].position.y = 100; boutons.bouton[BOUTON_SCORE].position.x = (LARGEUR - boutons.lecture[0].w) / 2; boutons.bouton[BOUTON_SCORE].position.y = 250; boutons.bouton[BOUTON_OPTIONS].position.x = (LARGEUR - boutons.lecture[0].w) / 2; boutons.bouton[BOUTON_OPTIONS].position.y = 400; boutons.bouton[BOUTON_QUIT].position.x = (LARGEUR - boutons.lecture[0].w) / 2; boutons.bouton[BOUTON_QUIT].position.y = 550; if ((testHoverBouton(sourisEvent.sx, sourisEvent.sy, boutons.bouton[BOUTON_QUIT], boutons.lecture[0]))&&sourisEvent.clicGauche) { modeMenu = 0; modeJeu = 0; } else if ((testHoverBouton(sourisEvent.sx, sourisEvent.sy, boutons.bouton[BOUTON_PLAY], boutons.lecture[0]))&&sourisEvent.clicGauche) { time.currentTime = SDL_GetTicks(); time.timeMenu = time.currentTime; modeJeu = 1; modeMenu = 6; initChien(chien); sprites.canardActifs = 2; for (int i = 0 ; i < sprites.canardActifs ; i++) { sprites.canard[i].type = alea(0, 3); initCanard(sprites.canard[i], partie); } partie.niveau = 0; partie.score = 0; initPartie(partie, sprites.canardActifs); initTableau(partie.tableauChasse, sprites); } else if ((testHoverBouton(sourisEvent.sx, sourisEvent.sy, boutons.bouton[BOUTON_SCORE], boutons.lecture[0]))&&sourisEvent.clicGauche) { modeMenu = 7; } else if ((testHoverBouton(sourisEvent.sx, sourisEvent.sy, boutons.bouton[BOUTON_OPTIONS], boutons.lecture[0]))&&sourisEvent.clicGauche) { modeMenu = 2; } break; case 2: boutons.bouton[BOUTON_RETOUR].position.x = (LARGEUR/2) - (boutons.lecture[0].w/2); boutons.bouton[BOUTON_RETOUR].position.y = 600; boutons.bouton[BOUTON_THEME_CLASSIQUE].position.x = ((LARGEUR/2) - (boutons.lecture[0].w/2))/2; boutons.bouton[BOUTON_THEME_CLASSIQUE].position.y = 200; boutons.bouton[BOUTON_THEME_ISLAND].position.x = (((LARGEUR/2) - (boutons.lecture[0].w/2))/2)+((LARGEUR/2) - (boutons.lecture[0].w/2)); boutons.bouton[BOUTON_THEME_ISLAND].position.y = 200; if ((testHoverBouton(sourisEvent.sx, sourisEvent.sy, boutons.bouton[BOUTON_RETOUR], boutons.lecture[0]))&&sourisEvent.clicGauche) { modeMenu = lastMenu; } else if ((testHoverBouton(sourisEvent.sx, sourisEvent.sy, boutons.bouton[BOUTON_THEME_CLASSIQUE], boutons.lecture[0]))&&sourisEvent.clicGauche) { boutons.bouton[BOUTON_THEME_CLASSIQUE].actif = true; boutons.bouton[BOUTON_THEME_ISLAND].actif = false; libererImages(sprites, chien, boutons); chargerImages(sprites, chien, boutons, "classique"); } else if ((testHoverBouton(sourisEvent.sx, sourisEvent.sy, boutons.bouton[BOUTON_THEME_ISLAND], boutons.lecture[0]))&&sourisEvent.clicGauche) { boutons.bouton[BOUTON_THEME_CLASSIQUE].actif = false; boutons.bouton[BOUTON_THEME_ISLAND].actif = true; libererImages(sprites, chien, boutons); chargerImages(sprites, chien, boutons, "island"); } break; case 5 : boutons.bouton[BOUTON_REPRENDRE].position.x = (LARGEUR/2) - (boutons.lecture[0].w/2); boutons.bouton[BOUTON_REPRENDRE].position.y = 200; boutons.bouton[BOUTON_OPTIONS].position.x = (LARGEUR/2) - (boutons.lecture[0].w/2); boutons.bouton[BOUTON_OPTIONS].position.y = 400; boutons.bouton[BOUTON_QUIT].position.x = (LARGEUR/2) - (boutons.lecture[0].w/2); boutons.bouton[BOUTON_QUIT].position.y = 600; if ((testHoverBouton(sourisEvent.sx, sourisEvent.sy, boutons.bouton[BOUTON_QUIT], boutons.lecture[0]))&&sourisEvent.clicGauche) { modeMenu = 1; lastMenu = 1; } else if ((testHoverBouton(sourisEvent.sx, sourisEvent.sy, boutons.bouton[BOUTON_REPRENDRE], boutons.lecture[0]))&&sourisEvent.clicGauche) { modeMenu = 0; } else if ((testHoverBouton(sourisEvent.sx, sourisEvent.sy, boutons.bouton[BOUTON_OPTIONS], boutons.lecture[0]))&&sourisEvent.clicGauche) { modeMenu = 2; lastMenu = 5; } break; case 6: if (time.currentTime >= time.menuTime + time.timeMenu) { modeMenu = 0; time.timeMenu = time.currentTime; } break; case 7: boutons.bouton[BOUTON_RETOUR].position.x = (LARGEUR/2) - (boutons.lecture[0].w/2); boutons.bouton[BOUTON_RETOUR].position.y = 600; if ((testHoverBouton(sourisEvent.sx, sourisEvent.sy, boutons.bouton[BOUTON_RETOUR], boutons.lecture[0]))&&sourisEvent.clicGauche) { modeMenu = 1; } break; case 8: boutons.bouton[BOUTON_OK].position.x = (LARGEUR/2) - (boutons.lecture[0].w/2); boutons.bouton[BOUTON_OK].position.y = 600; lastKeyPressedBis = lastKeyPressed; keyPressedBis = keyPressed; keyPressed = false; if (carActif < LONGUEUR_MAX_PSEUDO-1) { for (int i=97; i<123; i++) { if (keystate[i]) { lastKeyPressed = i; keyPressed = true; } } } if ((carActif > 0)&&keystate[SDLK_BACKSPACE]) { lastKeyPressed = -1; keyPressed = true; } if ((lastKeyPressedBis !=lastKeyPressed)||(defilTouche&&(time.currentTime >= time.timeDefKey + time.defKeyTime))||(keyPressedBis!=keyPressed)) { if (keyPressedBis!=keyPressed) { defilTouche = false; } if (carActif < LONGUEUR_MAX_PSEUDO-1) { for (int i=97; i<123; i++) { if (keystate[i]) { partie.pseudoT[carActif]=(i-32); carActif++; time.timeKey = time.currentTime; } } } if ((carActif > 0)&&keystate[SDLK_BACKSPACE]) { partie.pseudoT[carActif-1]=0; carActif--; time.timeKey = time.currentTime; } if (defilTouche) { time.timeDefKey = time.currentTime; } } else { if ((time.currentTime >= time.timeKey + time.keyTime)&&keyPressed) { defilTouche = true; } } partie.pseudo = std::string(partie.pseudoT); if ((testHoverBouton(sourisEvent.sx, sourisEvent.sy, boutons.bouton[BOUTON_OK], boutons.lecture[0]))&&sourisEvent.clicGauche) { addScore("scoresClassic", partie.pseudo, partie.score, partie.highScore); modeMenu = 7; } break; case 9: boutons.bouton[BOUTON_RETOUR].position.x = (LARGEUR/2) - (boutons.lecture[0].w/2); boutons.bouton[BOUTON_RETOUR].position.y = 600; if ((testHoverBouton(sourisEvent.sx, sourisEvent.sy, boutons.bouton[BOUTON_RETOUR], boutons.lecture[0]))&&sourisEvent.clicGauche) { modeMenu = 1; } break; default: break; } if (time.currentTime >= time.timeFps + time.fpsTime) { showMenu(ecran, sprites, boutons, modeMenu, msgs, partie, sourisEvent.sx, sourisEvent.sy); time.timeFps = time.currentTime; } SDL_Flip(ecran); } }
void FMDsp64(fmsynth *x, t_object *dsp64,short *count, double samplerate, long maxvectorsize, long flags) { x->sr = samplerate; x->incrementAmp = (1./alea(x->min, x->max)) * kTableLength/ samplerate; object_method(dsp64, gensym("dsp_add64"), x, FMPerform64,0, NULL); }
void FMPerform64 (fmsynth *x, t_object *dsp64, double **ins, long numins, double **outs, long numouts, long sampleframes, long flags, void *userparam) { t_double *out = outs[0]; double increment,increment2,incrementAmp,index,*table, *modtable, calc, index2, mod,modindex, sampleRate, *window, indexAmp, winFlag, env,min,max,freq, minFreq, maxFreq, minModFreq, maxModFreq, modFreq; //Store values locally for suposedly more efficient implementation increment = x->increment; increment2 = x->increment2; index = x->index; index2 = x->index2; table = x->waveTable; modtable = x-> waveTable2; modindex = x->modIndex; sampleRate = x->sr; incrementAmp = x->incrementAmp; indexAmp = x->indexAmp; window = x->window; winFlag = x->winFlag; min = x->min; max = x->max; minFreq = x->minFreq; maxFreq = x->maxFreq; minModFreq = x->minModFreq; maxModFreq = x->maxModFreq; //Aleatoric carrier frequency freq = fabs(alea(minFreq,maxFreq)); //Aleatoric modulator frequency modFreq = fabs(alea(minModFreq,maxModFreq)); while (sampleframes--) { // fill output buffer increment2 = modFreq * kTableLength/sampleRate; //SIMPLE FM increment = fabs(freq + mod) * kTableLength/sampleRate; //CARRIER calc = (table[(int) index]); //Carrier env = window[(int) indexAmp]; //MODULATOR //Option 1: mod = (modtable[(int) index2] * fabs(modFreq * modindex)); //Good results with high freq & depth values (1k or more) and rather slow modulator values /* Option 2: mod = (modtable[(int) index2] * fabs(Freq * modindex)); This will not produce random modulator. Good results with lower frequencies and moderate depth values. */ //APPLY HANNING WINDOW *out++ = (env * calc); //CHECK OF BOUNDARIES index += increment; // increment index index2 += increment2; // increment index2 indexAmp += incrementAmp; //increment window //CONDITIONS while (index >= kTableLength) // check that increment is within bounds index -= kTableLength; while (index2 >= kTableLength) // check that increment is within bounds index2 -= kTableLength; while (indexAmp >= kTableLength) { // Envelope check indexAmp -= kTableLength; winFlag = 1; } } //RESET ENVELOPE if (winFlag) { incrementAmp = (1./alea(min, max)) * kTableLength/ sampleRate; winFlag = 0; } //Save current values in the struct x->increment = increment; x->increment2 = increment2; x->incrementAmp = incrementAmp; x->index = index; x->index2 = index2; x->indexAmp = indexAmp; x->indexAmp = indexAmp; x->min = min; x->max = max; x->minFreq = minFreq; x->maxFreq = maxFreq; x->minModFreq = minModFreq; x->maxModFreq = maxModFreq; }
void remplir (int m){ int i = 0; while (i<t.taille) {t.valeurs[i++] = alea(m);} }
int main() { FILE *f_trace; FILE *f_graph; // File containing the graph FILE *f_run; // To save swarm positions, for each iteration int auto_move_type; struct particle best_hood; // Best particle in the neighbourhood double best_best_f; struct coeff coeff; double eps_max,eps_mean,eps_min; int hamilt; int i; int improv,improv_best; //int iter,iter_min; //struct graph G2; char graph[80]; // Graph file name int j; int k; // int m; //float level; //int loop_auto_move; float max_eval; //int max_iter; double mean_eval; float min_tour; int move4; struct particle new_p; int norm_v; int n_success; //int parallel; int run,run_max; int scanR; int swarm_size; double zzz,zzz2; /*----------------- SOME PARAMETERS -------------- */ #include "param.c" f_trace=fopen("trace.txt","w"); if (save==0) goto graph; /*-------------------------- */ printf("\nChoose the file to save the run, please"); scanR=scanf("%s",graph); f_run=fopen(graph,"w"); /*-------------------------- */ graph: /* Read the valuated graph (Note: value 0 <=> no arc) */ printf("\nFile name for the graph, please: "); scanR=scanf("%s",graph); //printf("\nMultiply all arc values by: "); //scanf("%f",&integer_coeff) ; integer_coeff=1; f_graph=fopen(graph,"r"); G=read_graph(f_graph,trace); //display_graph(G); /* // Save the graph for (i=0;i<G.N;i++) { fprintf(f_trace,"\n"); for (j=0;j<G.N;j++) fprintf(f_trace,"%.0f ",G.v[i][j]); } return EXIT_SUCCESS; */ printf("\n Just looking for Hamilton cycles ? (y/n): "); scanR=scanf("%s",answer); if (answer[0]=='y') { G=TSP_to_Hamilton(G); return EXIT_SUCCESS; } G=graph_min_max(G); /* Compute the max and the min arc values, and the number of edges */ min_tour=G.N*G.l_min; printf("\n Target ? (suggestion %.0f) ",min_tour); scanR=scanf("%f",&target); /*------------------------------ */ //graph_study: hamilt=check_Hamilton_cycle(G); if (hamilt==0) printf("\n\n WARNING. There is NO Hamiltonian cycle. I look for a Hamiltonian path\n"); if(hamilt==1 || hamilt==2)printf("\n\n LUCKY YOU. There IS at least one Hamiltonian cycle. I look for the best one\n"); if (hamilt==3) printf("\n I don't know whether there is a Hamiltonian cycle or not. Let's try"); //parameters: printf("\n\n Default parameters"); //swarm_size=G.N; // Just a rule of thumb //zzz=0; for (i=2;i<G.N;i++) zzz=zzz+log(i); //swarm_size=2.46*zzz-55; // Another rule of thumb (valid only if the result is >0 swarm_size=2*G.N+1; // Another rule of thumb //swarm_size=400; printf("\nSwarm size ......... %i",swarm_size); swarm_size=MAX(1,MIN(swarm_size,Max_size)); sw1.size=swarm_size; // see param.c printf("\n Init option................ %i",init_option); printf("\n Neighbourhood size.. %i ",hood); printf("\nHood_type .............%i",hood_type); printf("\nMove_type ............. %i",move[0]); if(move[0]<=5) { printf("\nKappa value ...... %.2f",kappa) ; printf("\nPhi value ............%.2f",phi); } printf("\nAuto_move_type ....%i",move[1]); printf("\nSplice_around the best %i",move[2]); printf("\nSplice_around more.... %i",move[3]); printf("\nRebuild method .......... %i",move[4]); //same_best_thresh=G.N/(2*hood); //Just a rule of thumb size_max=G.N; // Max size for splice_around. Just a rule of thumb printf("\n Do you want to modify them? (y/n): ") ; scanR=scanf("%s",answer); if (answer[0]=='n') goto end_param; // -----------------------------------Ask for parameters printf("\n Swarm size? (max = %i) ",Max_size); scanR=scanf("%i",&swarm_size); swarm_size=MAX(1,MIN(swarm_size,Max_size)); sw1.size=swarm_size; printf("\n Init option? (suggested 1 or 2): "); scanR=scanf("%i",&init_option); printf("\n Neighbourhood size? (max = %i) ",sw1.size); scanR=scanf("%i",&hood); hood=MAX(1,MIN(hood,sw1.size)); printf("\n Hood type? (0 = social (quick) 1 = physical (long)\n (suggestion: %i): ",hood_type); scanR=scanf(" %i",&hood_type); printf("\n Move type? (1 to 10) (suggestion: %i): ",move[0]); scanR=scanf("%i",&move[0]); if(move[0]<=5) { printf("\n kappa value? (suggestion: %.2f): ",kappa); // Constriction coefficients. See move_towards scanR=scanf("%f",&kappa); printf("\n phi value? (suggestion: %.2f): ",phi); scanR=scanf("%f",&phi); } printf("\n Auto-move type? (0 to 6) (suggestion: %i): ",move[1]); scanR=scanf("%i",&move[1]); printf("\nSplice_around the best?(suggestion %i)",move[2]); scanR=scanf("%i",&move[2]); printf("\nSplice_around more? (suggestion %i)",move[3]); scanR=scanf("%i",&move[3]); printf("\nRebuild method? (suggestion %i)",move[4]); scanR=scanf("%i",&move[4]); end_param: //-------------------------------- Iterations printf("\n Max tour evaluations? (0 => end) "); scanR=scanf("%f",&max_eval); if (max_eval==0) goto the_end; printf("\n Trace level ? (0,1,2,3,4) "); scanR=scanf("%i",&trace); /* ======================================================== HERE IS THE ALGORITHM */ printf("\n How many times? "); scanR=scanf("%i",&run_max); if (run_max==0 ) goto the_end; run=1; n_success=0; eps_min=10000*target; eps_max=0; eps_mean=0; mean_eval=0; if (move[4]>=3) // Initialize the blackboard { for (i=0; i<G.N; i++) for (j=0; j<G.N; j++) for (k=0; k<2; k++) BB[k].v[i][j]=0; } loop_run: printf("\n ___________________________ RUN %i",run); eval_f=0; time=0; // Current time step splice_time=0; // Last time splice_around has been used // Initialize the swarm sw1=init_swarm(swarm_size,G,trace); printf("\nAfter init: eval %.0f value %f for particle %i",eval_f, best_best.best_f,sw1.rank_best); if (best_best.best_f<=target) goto success;// Success if (save!=0) save_swarm(f_run,sw1); /* Save the run as text file */ if(move[0]<=5 && move[0]!=0) coeff=convergence_case(kappa,phi); // Coeffs for non spherical methods moves: time=time+1; printf("\n total velocity %.0f",tot_vel(sw1)); if (move[0]>0) { //----------------------------------------------------------------------------- Normal move printf("\nEval %.0f. Normal move %i",eval_f,move[0]); if (eval_f>=max_eval) goto end_max_eval; best_best_f=best_best.best_f; // Before the move for (i=0; i<sw1.size; i++) { // find the best in the neighbourhood (or the local queen) best_hood=best_neighbour(sw1,sw1.p[i],hood,hood_type,monotony,equiv_v,trace); // M O V E sw1.p[i]=move_towards(sw1.p[i],best_hood,coeff,move[0],explicit_vel,conv_case,equiv_v,trace); if (sw1.p[i].best_f<best_best.best_f)// Check best of the best after the move { best_best=sw1.p[i]; sw1.rank_best=i; printf("\neval %.0f value %f",eval_f, best_best.best_f); display_position(best_best,1); } if (best_best.best_f<=target) goto success;// Success if (best_best.best_f<best_best_f) goto moves; // Loop as soon as there is a global improvement } // next i for normal move } if (move[1]>0) { //------------------------------------------------------------- If no improvement, auto_move printf(" /auto_move %i",move[1]); auto_move_type=move[1]; // auto_move: for (i=0; i<sw1.size; i++) { sw1.p[i]= auto_move(sw1.p[i],auto_move_type,0,0,trace); if (sw1.p[i].best_f<best_best.best_f) { best_best=sw1.p[i]; sw1.rank_best=i; if (best_best.best_f<=target) goto success;// Success printf("\neval %.0f value %f",eval_f, best_best.best_f); display_position(best_best,1); goto moves; } if (eval_f>=max_eval) goto end_max_eval; } // next i for auto_move } if(move[2]>0) { // --------------------------------------------------- If still no improvement, splice_around best particle printf(" /splice_around, best particle"); i= sw1.rank_best; sw1.p[i]= splice_around( sw1, sw1.p[i], hood_type,hood); if (sw1.p[i].best_f<best_best.best_f)// Best of the best after the move { best_best=sw1.p[i]; if (best_best.best_f<=target) goto success;// Success printf("\neval %.0f value %f",eval_f, best_best.best_f); goto moves; } } if(move[3]>0) { // --------------------------------------------------- If still no improvement, splice_around more particles printf(" /splice_around, more, option %i",splice_around_option); improv=0; improv_best=0; splice_time=time; for (i=0; i<sw1.size; i++) // For each particle { zzz= sw1.p[i].f; zzz2= sw1.p[i].best_f; sw1.p[i]= splice_around( sw1, sw1.p[i], hood_type,hood); if (sw1.p[i].f<zzz) improv=improv+1; if (sw1.p[i].best_f<zzz2) improv_best=improv_best+1; if (sw1.p[i].best_f<best_best.best_f)// Best of the best after the move { best_best=sw1.p[i]; sw1.rank_best=i; if (best_best.best_f<=target) goto success;// Success printf("\neval %.0f value %f",eval_f, best_best.best_f); goto moves; } if (eval_f>=max_eval) goto end_max_eval; } // next i for splice_around // if (improv_best>sw1.size/2) goto moves; } if (move[4]==9) move4=alea(1,3); else move4=move[4]; if(move4>0) { //--------------------------------- If still no improvement, rebuild tours if (move4==1) printf(" /rebuild, random"); if (move4==2) printf(" /rebuild, arc_around"); if (move4==3) printf(" /rebuild, blackboard"); for (i=0; i<sw1.size; i++) { switch( move4) { case 1: norm_v=alea(1,G.N); sw1.p[i].v=alea_velocity(norm_v); // random velocity sw1.p[i]=pos_plus_vel(sw1.p[i],sw1.p[i].v,0,0,0); // => random new position break; case 2: new_p=arc_around(sw1,sw1.p[i]); sw1.p[i].v=coeff_pos_minus_pos(new_p,sw1.p[i],monotony,0,equiv_v,trace); sw1.p[i]=new_p; break; case 3: new_p=BB_use(sw1.p[i]); sw1.p[i].v=coeff_pos_minus_pos(new_p,sw1.p[i],monotony,0,equiv_v,trace); sw1.p[i]=new_p; break; } if (sw1.p[i].best_f<best_best.best_f)/* Best of the best after the move */ { best_best=sw1.p[i]; if (best_best.best_f<=target) goto success;// Success printf("\neval %.0f value %f",eval_f, best_best.best_f); goto moves; } if (eval_f>=max_eval) goto end_max_eval; } } // Primitive rehope printf("\n Primitive rehope"); for (i=0; i<sw1.size; i++) { sw1.p[i].v=alea_velocity(G.N); sw1.p[i]= pos_plus_vel(sw1.p[i],sw1.p[i].v,0,0,0); } goto moves; //----------------------------------- // end_move: if (save!=0) save_swarm(f_run,sw1); if (trace>1) display_swarm(sw1); printf("\n Eval %.0f",eval_f); if (trace>0) display_position(best_best,2); goto moves; end_max_eval: printf("\n\n Stop at max eval %.0f",eval_f); goto end; success: n_success=n_success+1; printf("\n SUCCESS"); end: // Give the best position (sequence) found printf("\n Best solution found after %.0f evaluations",eval_f); if (best_best.best_x.s[0]!=0) best_best.best_x=rotate(best_best.best_x,0); display_position(best_best,2); // Check if no error zzz=f(best_best,-1,-1); if (zzz!=best_best.best_f) { printf("\n ERROR. The true f value is in fact %f ",zzz); } zzz=best_best.best_f; if (zzz<eps_min) eps_min= zzz; if (zzz>eps_max) eps_max= zzz; eps_mean=eps_mean+zzz; mean_eval=mean_eval+eval_f; if (save!=0) save_swarm(f_run,sw1); save_swarm(f_trace,sw1); if (trace>1) display_swarm(sw1); run=run+1; if (run<=run_max) goto loop_run; else { printf("\n With swarm size=%i, max eval=%.0f => %i successes/%i. Rate=%.3f ",swarm_size,max_eval,n_success,run_max,(float)n_success/run_max); printf("\n Mean %f [%f, %f]",eps_mean/run_max,eps_min,eps_max); mean_eval=mean_eval/run_max; printf("\n Mean eval %f",mean_eval); goto the_end; } //error_end: printf("\n Sorry, I give up"); the_end: return EXIT_SUCCESS; }
struct result PSO (struct param param, struct problem pb) { int d; double error; double errorPrev; int g; struct position Gr; struct vector GX={0}; int index[param.S]; int initLinks; // Flag to (re)init or not the information links int iter; // Iteration number (time step) int iterBegin; int LINKS[param.S][param.S]; // Information links int m; int noStop; double out; double p; struct vector PX; struct vectorList qRand; struct result R; double rad; int s0, s,s1; struct vector V1,V2; double w1,w2,w3; double xMax,xMin; //struct position XPrev; double zz; PX.size=pb.SS.D; GX.size=pb.SS.D; V1.size=pb.SS.D; V2.size=pb.SS.D; Gr.size=pb.SS.D; // ----------------------------------------------------- // INITIALISATION p=param.p; // Probability threshold for random topology R.SW.S = param.S; // Size of the current swarm // Position and velocity for (s = 0; s < R.SW.S; s++) { R.SW.X[s].size = pb.SS.D; R.SW.V[s].size = pb.SS.D; } switch(param.BW[2]) { default: for (s = 0; s < R.SW.S; s++) { for (d = 0; d < pb.SS.D; d++) { if(pb.SS.normalise==0) { xMin=pb.SS.min[d]; xMax=pb.SS.max[d];} R.SW.X[s].x[d] = alea (xMin,xMax); R.SW.V[s].v[d] = alea( xMin-R.SW.X[s].x[d], xMax-R.SW.X[s].x[d] ); // So that xMin<= x+v <= xMax } } break; case 1: case 2: qRand=quasiRand(pb.SS.D,R.SW.S,param.BW[2]); for (s = 0; s < R.SW.S; s++) { for (d = 0; d < pb.SS.D; d++) { if(pb.SS.normalise==0) { xMin=pb.SS.min[d]; xMax=pb.SS.max[d];} R.SW.X[s].x[d] = xMin+(xMax-xMin)*qRand.V[s].v[d]; R.SW.V[s].v[d] = alea( xMin-R.SW.X[s].x[d], xMax-R.SW.X[s].x[d] ); } } break; } // First evaluations errMax=0; errMin=infinity; for (s = 0; s < R.SW.S; s++) { R.SW.X[s].f = perf_bench (R.SW.X[s], pb.function,pb.objective); R.SW.P[s] = R.SW.X[s]; // Best position = current one } // // If the number max of evaluations is smaller than // the swarm size, just keep evalMax particles, and finish if (R.SW.S>pb.evalMax) R.SW.S=pb.evalMax; R.nEval = R.SW.S; // Find the best R.SW.best = 0; errorPrev =R.SW.P[R.SW.best].f; // "distance" to the wanted f value (objective) for (s = 1; s < R.SW.S; s++) { zz=R.SW.P[s].f; if (zz < errorPrev) { R.SW.best = s; errorPrev=zz; } } // ---------------------------------------------- ITERATIONS noStop = 0; error=errorPrev; iter=0; iterBegin=0; initLinks = 1; // So that information links will be initialized int new_neigh = 0; // Each particle informs itself for (m = 0; m < R.SW.S; m++) LINKS[m][m] = 1; while (noStop == 0) { iter=iter+1; aleaIndex(index, R.SW.S); // Random numbering of the particles if (initLinks==1) // Modify topology { // Who informs who, at random for (s = 0; s < R.SW.S; s++) { for (m = 0; m < R.SW.S; m++) { if(m==s) continue; if (alea (0, 1)<p) { LINKS[m][s] = 1; // Probabilistic method } else LINKS[m][s] = 0; } } } // Loop on particles for (s0 = 0; s0 < R.SW.S; s0++) // For each particle ... { s=index[s0]; // Find the best informant g = 0; for (m = 0; m < R.SW.S; m++) { if (LINKS[m][s] == 1 && R.SW.P[m].f < R.SW.P[g].f) g = m; } //.. compute the new velocity, and move // Exploration tendency for (d = 0; d < pb.SS.D; d++) { R.SW.V[s].v[d]=param.w *R.SW.V[s].v[d]; } // Prepare Exploitation tendency p-x for (d = 0; d < pb.SS.D; d++) { PX.v[d]= R.SW.P[s].x[d] - R.SW.X[s].x[d]; } if(g!=s) // If the particle is not its own local best, prepare g-x { for (d = 0; d < pb.SS.D; d++) GX.v[d]= R.SW.P[g].x[d] - R.SW.X[s].x[d]; } // Gravity centre Gr w1=1; w2=1; w3=1; if(g==s) w3=0; zz=w1+w2+w3; w1=w1/zz; w2=w2/zz; w3=w3/zz; for (d = 0; d < pb.SS.D; d++) { Gr.x[d]=w1*R.SW.X[s].x[d] + w2*(R.SW.X[s].x[d] + param.c*PX.v[d]); if(g!=s) Gr.x[d]=Gr.x[d]+ w3*(R.SW.X[s].x[d] +param.c*GX.v[d]) ; V1.v[d]= Gr.x[d]-R.SW.X[s].x[d]; // Vector X-Gr } // Random point around rad=distanceL(R.SW.X[s],Gr,2); V2=alea_sphere(pb.SS.D,rad,param.distrib, param.mean,param.sigma); // New "velocity" for (d = 0; d < pb.SS.D; d++) R.SW.V[s].v[d]=R.SW.V[s].v[d]+V1.v[d] + V2.v[d]; // New "velocity" // New position for (d = 0; d < pb.SS.D; d++) R.SW.X[s].x[d] = R.SW.X[s].x[d] + R.SW.V[s].v[d]; if (R.nEval >= pb.evalMax) goto end; // Confinement // out=0; for (d = 0; d < pb.SS.D; d++) { xMin=pb.SS.min[d]; xMax=pb.SS.max[d]; if (R.SW.X[s].x[d] < xMin) { R.SW.X[s].x[d] = xMin; R.SW.V[s].v[d] = -0.5*R.SW.V[s].v[d]; //out=1; } else { if (R.SW.X[s].x[d] > xMax) { R.SW.X[s].x[d] = xMax; R.SW.V[s].v[d] = -0.5*R.SW.V[s].v[d]; //out=1; } } } // Evaluation //R.SW.X[s].f =perf(R.SW.X[s],pb.function, pb.SS,pb.objective); R.SW.X[s].f =perf_bench(R.SW.X[s],pb.function, pb.objective); R.nEval = R.nEval + 1; // ... update the best previous position if (R.SW.X[s].f < R.SW.P[s].f) // Improvement { R.SW.P[s] = R.SW.X[s]; // ... update the best of the bests if (R.SW.P[s].f < R.SW.P[R.SW.best].f) { R.SW.best = s; } } } // End of "for (s0=0 ... " // Check if finished error = R.SW.P[R.SW.best].f; if (error < errorPrev) // Improvement of the global best initLinks = 0; else // No global improvement { initLinks = 1; // Information links will be reinitialized new_neigh++; } errorPrev = error; end: if (error > pb.epsilon && R.nEval < pb.evalMax) noStop = 0; // Won't stop else noStop = 1; // Will stop } // End of "while nostop ... // printf( "\n and the winner is ... %i", R.SW.best ); R.error = error; R.new_neigh = new_neigh; return R; }