void bootstrap(double x[], double y[], double* result, int* b, int* B, int *n, int* d) { static gsl_rng *restrict r = NULL; if(r == NULL) { // First call to this function, setup RNG gsl_rng_env_setup(); r = gsl_rng_alloc(gsl_rng_mt19937); gsl_rng_set(r, time(NULL)); } //a stores the sampled indices int a[ *n ]; //allocate memory for the regression step gsl_matrix * pred = gsl_matrix_alloc ( *n, *d ); gsl_vector * resp = gsl_vector_alloc( *n ); gsl_multifit_linear_workspace * work = gsl_multifit_linear_alloc ( *n, *d ); gsl_vector* coef = gsl_vector_alloc ( *d ); gsl_matrix* cov = gsl_matrix_alloc ( *d, *d ); gsl_matrix * T_boot = gsl_matrix_alloc ( *B, *d ); double chisq; //create bootstrap samples for ( int i = 0; i < *B; i++ ) { //sample the indices samp_k_from_n( n, b, a, r); printf("dfdfdfd"); //transfer x to a matrix pred and y to a vector resp for ( int i = 0; i < *n; i++ ) { gsl_vector_set (resp, i, y[ a[i] ]); for (int j = 0; j < *d; j++) gsl_matrix_set (pred, i, j, x[ j + ( a[ i ] * (*d) ) ]); } //linera regression gsl_multifit_linear ( pred, resp, coef, cov, &chisq, work ); //pass the elements of coef to the ith row of T_boot gsl_matrix_set_row ( T_boot, i, coef ); } //compute the standard deviation of each coefficient accros the bootstrap repetitions for ( int j = 0; j < *d; j++){ result[ j ] = sqrt( gsl_stats_variance( gsl_matrix_ptr ( T_boot, 0, j ), 1, *B ) ); } //free the memory gsl_matrix_free (pred); gsl_vector_free(resp); gsl_multifit_linear_free ( work); gsl_vector_free (coef); //gsl_vector_free (w); gsl_matrix_free (cov); printf("\nI AM DONE\n\n"); }
/*! This function performs the initial set-up of the simulation. First, the * parameterfile is set, then routines for setting units, reading * ICs/restart-files are called, auxialiary memory is allocated, etc. */ void begrun(void) { struct global_data_all_processes all; if(ThisTask == 0) { printf("\nThis is Gadget, version `%s'.\n", GADGETVERSION); printf("\nRunning on %d processors.\n", NTask); } read_parameter_file(ParameterFile); /* ... read in parameters for this run */ allocate_commbuffers(); /* ... allocate buffer-memory for particle exchange during force computation */ set_units(); #if defined(PERIODIC) && (!defined(PMGRID) || defined(FORCETEST)) ewald_init(); #endif open_outputfiles(); random_generator = gsl_rng_alloc(gsl_rng_ranlxd1); gsl_rng_set(random_generator, 42); /* start-up seed */ #ifdef PMGRID long_range_init(); #endif All.TimeLastRestartFile = CPUThisRun; if(RestartFlag == 0 || RestartFlag == 2) { set_random_numbers(); init(); /* ... read in initial model */ } else { all = All; /* save global variables. (will be read from restart file) */ restart(RestartFlag); /* ... read restart file. Note: This also resets all variables in the struct `All'. However, during the run, some variables in the parameter file are allowed to be changed, if desired. These need to copied in the way below. Note: All.PartAllocFactor is treated in restart() separately. */ All.MinSizeTimestep = all.MinSizeTimestep; All.MaxSizeTimestep = all.MaxSizeTimestep; All.BufferSize = all.BufferSize; All.BunchSizeForce = all.BunchSizeForce; All.BunchSizeDensity = all.BunchSizeDensity; All.BunchSizeHydro = all.BunchSizeHydro; All.BunchSizeDomain = all.BunchSizeDomain; All.TimeLimitCPU = all.TimeLimitCPU; All.ResubmitOn = all.ResubmitOn; All.TimeBetSnapshot = all.TimeBetSnapshot; All.TimeBetStatistics = all.TimeBetStatistics; All.CpuTimeBetRestartFile = all.CpuTimeBetRestartFile; All.ErrTolIntAccuracy = all.ErrTolIntAccuracy; All.MaxRMSDisplacementFac = all.MaxRMSDisplacementFac; All.ErrTolForceAcc = all.ErrTolForceAcc; All.TypeOfTimestepCriterion = all.TypeOfTimestepCriterion; All.TypeOfOpeningCriterion = all.TypeOfOpeningCriterion; All.NumFilesWrittenInParallel = all.NumFilesWrittenInParallel; All.TreeDomainUpdateFrequency = all.TreeDomainUpdateFrequency; All.SnapFormat = all.SnapFormat; All.NumFilesPerSnapshot = all.NumFilesPerSnapshot; All.MaxNumNgbDeviation = all.MaxNumNgbDeviation; All.ArtBulkViscConst = all.ArtBulkViscConst; All.OutputListOn = all.OutputListOn; All.CourantFac = all.CourantFac; All.OutputListLength = all.OutputListLength; memcpy(All.OutputListTimes, all.OutputListTimes, sizeof(double) * All.OutputListLength); strcpy(All.ResubmitCommand, all.ResubmitCommand); strcpy(All.OutputListFilename, all.OutputListFilename); strcpy(All.OutputDir, all.OutputDir); strcpy(All.RestartFile, all.RestartFile); strcpy(All.EnergyFile, all.EnergyFile); strcpy(All.InfoFile, all.InfoFile); strcpy(All.CpuFile, all.CpuFile); strcpy(All.TimingsFile, all.TimingsFile); strcpy(All.SnapshotFileBase, all.SnapshotFileBase); if(All.TimeMax != all.TimeMax) readjust_timebase(All.TimeMax, all.TimeMax); } #ifdef PMGRID long_range_init_regionsize(); #endif if(All.ComovingIntegrationOn) init_drift_table(); if(RestartFlag == 2) All.Ti_nextoutput = find_next_outputtime(All.Ti_Current + 1); else All.Ti_nextoutput = find_next_outputtime(All.Ti_Current); All.TimeLastRestartFile = CPUThisRun; }
int main(int argc, char **argv) { char *netF; FILE *infile=NULL; FILE *outfileAND=NULL, *outfileOR=NULL; struct node_gra *net=NULL; gsl_rng *rand_gen; double **newA_OR; struct node_gra *p1, *p2; long int seed; char outFileNameOR[200]; /* --------------------------------------------------------------------------- Command line parameters --------------------------------------------------------------------------- */ if (argc < 2) { printf("\nUse: reliability_links_mb_OR net_file seed\n\n"); return -1; } netF = argv[1]; seed = atoi(argv[2]); rand_gen = gsl_rng_alloc(gsl_rng_mt19937); gsl_rng_set(rand_gen, seed); /* --------------------------------------------------------------------------- Build the network --------------------------------------------------------------------------- */ infile = fopen(netF, "r"); net = FBuildNetwork(infile, 0, 0, 0, 1); fclose(infile); /* --------------------------------------------------------------------------- Get link reliabilities --------------------------------------------------------------------------- */ newA_OR = ORLinkScoreMB(net, 0.0, 10000, rand_gen, 'q'); /* --------------------------------------------------------------------------- Output --------------------------------------------------------------------------- */ strcpy(outFileNameOR, netF); strcat(outFileNameOR, ".OR_scores"); outfileOR = fopen(outFileNameOR, "w"); p1 = net; while ((p1 = p1->next) != NULL) { p2 = p1; while ((p2 = p2->next) != NULL) { fprintf(outfileOR, "%g %s %s\n", newA_OR[p1->num][p2->num], p1->label, p2->label); } } fclose(outfileOR); /* --------------------------------------------------------------------------- Finish --------------------------------------------------------------------------- */ RemoveGraph(net); gsl_rng_free(rand_gen); return 0; }
int main(void) { int i; /* loop counter */ int eeglelap; /* elapsed time for eegl */ int mtelap; /* elapsed time for mt19937 */ int ranlxelap; /* elapsed time for ranlxd2 */ unsigned int dttk; /* combined date, time #ticks */ double tot; /* total points within a circle */ double bot; /* 1 million */ double ratio; /* estimated 2 / pi */ time_t now; /* current date and time */ clock_t clk; /* current number of ticks */ clock_t eeglstart; /* start time for eegl */ clock_t eeglfin; /* end time for eegl */ clock_t mtstart; /* start time for mt19937 */ clock_t mtfin; /* end time for mt19937 */ clock_t ranlxstart; /* start time for ranlxd2 */ clock_t ranlxfin; /* end time for ranlxd2 */ struct tms t; /* structure used by times() */ gsl_rng *r; /* GSL RNG structure */ eefmt *ee; /* eegl structure */ ee = (eefmt *) eeglinit(); /* initialize the eegl structure */ bot = 1000000.0; /* set to 1 million */ /************************************************************/ tot = 0.0; /* initialize total */ i = (int) bot; /* set loop counter */ /* get clock ticks since boot */ eeglstart = times(&t); /* start time for eegl */ while (i--) /* loop 1 million times */ { double x; /* horizontal coordinate */ double y; /* vertical coordinate */ double wyy; /* y = sin(x) */ x = eeglunif(ee) * M_PI; /* uniform number 0-pi */ y = eeglunif(ee); /* uniform number 0-1 */ wyy = sin(x); /* the sine curve */ if (y < wyy) tot += 1.0; /* if y is under the curve, tally */ } /* for each point above or below a sine curve */ ratio = M_PI * (tot / bot); /* calculate est. 2.0 */ eeglfin = times(&t); /* finish time for eegl */ printf("Monte Carlo Definite Integral of sin(x)\n"); printf(" From zero to Pi\n"); printf(" Expected error is 1/1000\n"); printf(" n = 1 million\n"); printf(" eegl %18.15f\n", ratio); /************************************************************/ /* allocate the mt19937 random number generator */ r = (gsl_rng *) gsl_rng_alloc(gsl_rng_mt19937); /* get clock ticks since boot */ clk = times(&t); /* get date & time */ time(&now); /* combine date, time, and ticks into a single UINT */ dttk = (unsigned int) (now ^ clk); /* initialize the GSL Mersenne Twister */ /* random number generator to date,time,#ticks */ gsl_rng_set(r, dttk); /* initialize mt19937 seed */ tot = 0.0; /* initialize total */ i = (int) bot; /* set loop counter */ /* get clock ticks since boot */ mtstart = times(&t); /* start time for GSL mt19937 */ while (i--) /* loop 1 million times */ { double x; /* horizontal coordinate */ double y; /* vertical coordinate */ double wyy; /* y = sin(x) */ /* use the mt19937 random number generator this time */ x = gsl_rng_uniform(r) * M_PI; /* uniform number 0-pi */ y = gsl_rng_uniform(r); /* uniform number 0-1 */ wyy = sin(x); /* the sine curve */ if (y < wyy) tot += 1.0; /* if under the curve, tally */ } /* for each point above or below a sine curve */ ratio = M_PI * tot / bot; /* calculate est. 2.0 */ mtfin = times(&t); /* finish time for GSL mt19937 */ printf("GSL mt19937 %18.15f\n", ratio); gsl_rng_free(r); /************************************************************/ /* allocate the ranlxd2 random number generator */ r = (gsl_rng *) gsl_rng_alloc(gsl_rng_ranlxd2); /* get clock ticks since boot */ clk = times(&t); /* get date & time */ time(&now); /* combine date, time, and ticks into a single UINT */ dttk = (unsigned int) (now ^ clk); /* initialize the GSL ranlxd2 random number generator */ /* to date,time,#ticks */ gsl_rng_set(r, dttk); /* initialize ranlxd2 seed */ tot = 0.0; /* initialize total */ i = (int) bot; /* set loop counter */ /* get clock ticks since boot */ ranlxstart = times(&t); /* start time for GSL ranlxd2 */ while (i--) /* loop 1 million times */ { double x; /* horizontal coordinate */ double y; /* vertical coordinate */ double wyy; /* y = sin(x) */ /* use the ranlxd2 random number generator this time */ x = gsl_rng_uniform(r) * M_PI; /* uniform number 0-pi */ y = gsl_rng_uniform(r); /* uniform number 0-1 */ wyy = sin(x); /* the sine curve */ if (y < wyy) tot += 1.0; /* if under the curve, tally */ } /* for each point above or below a sine curve */ ratio = M_PI * (tot / bot); /* calculate est. 2.0 */ ranlxfin = times(&t); /* finish time for GSL ranlxd2 */ printf("GSL ranlxd2 %18.15f\n", ratio); printf(" Actual %18.15f\n", 2.0); eeglelap = eeglfin - eeglstart; mtelap = mtfin - mtstart; ranlxelap = ranlxfin - ranlxstart; printf(" eegl ticks %6d\n", eeglelap); printf("GSL mt19937 ticks %6d\n", mtelap); printf("GSL ranlxd2 ticks %6d\n", ranlxelap); gsl_rng_free(r); free(ee->state); free(ee); return(0); } /* main */
void predefinedGrid(inputPars *par, struct grid *g){ FILE *fp; int i; double x,y,z,scale; gsl_rng *ran = gsl_rng_alloc(gsl_rng_ranlxs2); #ifdef TEST gsl_rng_set(ran,6611304); #else gsl_rng_set(ran,time(0)); #endif fp=fopen(par->pregrid,"r"); par->ncell=par->pIntensity+par->sinkPoints; for(i=0;i<par->pIntensity;i++){ // fscanf(fp,"%d %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf\n", &g[i].id, &g[i].x[0], &g[i].x[1], &g[i].x[2], &g[i].dens[0], &g[i].t[0], &abun, &g[i].dopb, &g[i].vel[0], &g[i].vel[1], &g[i].vel[2]); // fscanf(fp,"%d %lf %lf %lf %lf %lf %lf %lf\n", &g[i].id, &g[i].x[0], &g[i].x[1], &g[i].x[2], &g[i].dens[0], &g[i].t[0], &abun, &g[i].dopb); int nRead = fscanf(fp,"%d %lf %lf %lf %lf %lf %lf %lf %lf\n", &g[i].id, &g[i].x[0], &g[i].x[1], &g[i].x[2], &g[i].dens[0], &g[i].t[0], &g[i].vel[0], &g[i].vel[1], &g[i].vel[2]); if( nRead != 9 || g[i].id < 0 || g[i].id > par->ncell) { if(!silent) bail_out("Reading Grid File error"); exit(0); } g[i].dopb=200; g[i].abun[0]=1e-9; g[i].sink=0; g[i].t[1]=g[i].t[0]; g[i].nmol[0]=g[i].abun[0]*g[i].dens[0]; /* This next step needs to be done, even though it looks stupid */ g[i].dir=malloc(sizeof(point)*1); g[i].ds =malloc(sizeof(double)*1); g[i].neigh =malloc(sizeof(struct grid *)*1); if(!silent) progressbar((double) i/((double)par->pIntensity-1), 4); } for(i=par->pIntensity;i<par->ncell;i++){ x=2*gsl_rng_uniform(ran)-1.; y=2*gsl_rng_uniform(ran)-1.; z=2*gsl_rng_uniform(ran)-1.; if(x*x+y*y+z*z<1){ scale=par->radius*sqrt(1/(x*x+y*y+z*z)); g[i].id=i; g[i].x[0]=scale*x; g[i].x[1]=scale*y; g[i].x[2]=scale*z; g[i].sink=1; g[i].abun[0]=0; g[i].dens[0]=1e-30; g[i].t[0]=par->tcmb; g[i].t[1]=par->tcmb; g[i].dopb=0.; } else i--; } fclose(fp); qhull(par,g); distCalc(par,g); // getArea(par,g, ran); // getMass(par,g, ran); getVelosplines_lin(par,g); if(par->gridfile) write_VTK_unstructured_Points(par, g); gsl_rng_free(ran); }
void studyPop::addMutation(vector<int>& parent1, vector<int>& parent2, int currentRound) { // These variables save the average number of mutations on each chromosome double avgDelMutations; double avgBenMutations; double P_ben; P_ben = PROB_BEN; avgDelMutations = (0.5)*MUTATIONRATE*(1-P_ben); // multiplied by half to get # for each chromosome avgBenMutations = (0.5)*MUTATIONRATE*P_ben; // multiplied by half to get # for each chromosome // Pick number of mutation loci on each gamete in the next several lines int parent1DelMutationsNum, parent1BenMutationsNum, parent2DelMutationsNum, parent2BenMutationsNum; // GSL objects to generate random numbers const gsl_rng_type * T; gsl_rng * r; gsl_rng_default_seed += time(NULL); T = gsl_rng_default; r = gsl_rng_alloc (T); gsl_rng_set(r, gsl_rng_default_seed); parent1DelMutationsNum = gsl_ran_poisson(r,avgDelMutations); // Get a new seed for more randomization gsl_rng_default_seed += time(NULL); gsl_rng_set(r, gsl_rng_default_seed); parent1BenMutationsNum = gsl_ran_poisson(r,avgBenMutations); gsl_rng_default_seed += time(NULL); gsl_rng_set(r, gsl_rng_default_seed); parent2DelMutationsNum = gsl_ran_poisson(r,avgDelMutations); gsl_rng_default_seed += time(NULL); gsl_rng_set(r, gsl_rng_default_seed); parent2BenMutationsNum = gsl_ran_poisson(r,avgBenMutations); gsl_rng_default_seed += time(NULL); gsl_rng_set(r, gsl_rng_default_seed); // Pick exact loci of mutation on each chromosome & then put them on the chromosome vector<int> allMutationsOnGamete1, benMutationsOnGamete1, delMutationsOnGamete1; vector<int> allMutationsOnGamete2, benMutationsOnGamete2, delMutationsOnGamete2; // Gamete from parent1 for(int i=0; i<parent1DelMutationsNum ; i++) { gsl_rng_default_seed += time(NULL)^i; gsl_rng_set(r, gsl_rng_default_seed); delMutationsOnGamete1.push_back(floor(gsl_ran_flat(r, 0.5, L+0.4999) + 0.5)); } // Find beneficial mutations loci for(int i=0; i<parent1BenMutationsNum ;) { gsl_rng_default_seed += time(NULL)^i; gsl_rng_set(r, gsl_rng_default_seed); int tempMutation = floor(gsl_ran_flat(r, 0.5, L+0.4999) + 0.5); int q=0; for(; q<delMutationsOnGamete1.size() ; q++) { if(delMutationsOnGamete1.at(q) == tempMutation) break; } if(q==delMutationsOnGamete1.size()) { benMutationsOnGamete1.push_back(tempMutation); i++; } } // put the beneficial and del mutations in a same vector & sort allMutationsOnGamete1.insert(allMutationsOnGamete1.end(), delMutationsOnGamete1.begin(), delMutationsOnGamete1.end()); allMutationsOnGamete1.insert(allMutationsOnGamete1.end(), benMutationsOnGamete1.begin(), benMutationsOnGamete1.end()); sort(allMutationsOnGamete1.begin(), allMutationsOnGamete1.end()); // make the beneficial mutations negative (and leave the the del mutations positive integers) for(int p=0; p<allMutationsOnGamete1.size() ; p++) { for(int q=0; q<benMutationsOnGamete1.size() ; q++) { if(allMutationsOnGamete1.at(p) == benMutationsOnGamete1.at(q)) { allMutationsOnGamete1.at(p) *= -1; } } } //Merge the sorted mutations with the unmutated chromosome int placeOnChromosome = 0; if(parent1.size() > 0) { for(int i=0; i<allMutationsOnGamete1.size();) { if(abs(allMutationsOnGamete1.at(i)) < abs(parent1.at(placeOnChromosome))) { parent1.insert(parent1.begin() + placeOnChromosome, allMutationsOnGamete1.at(i)); i++; placeOnChromosome++; } else if(abs(allMutationsOnGamete1.at(i)) > abs(parent1.at(placeOnChromosome))) { if(placeOnChromosome < parent1.size()-1) { placeOnChromosome++; } else { parent1.insert(parent1.begin() + placeOnChromosome + 1, allMutationsOnGamete1.begin() + i, allMutationsOnGamete1.end()); break; } } // This else is for when the mutation already exists on the chromosome. else { if(allMutationsOnGamete1.at(i) == parent1.at(placeOnChromosome)) i++; else { // replace beneficial/deleterious with each other allMutationsOnGamete1.at(i) *= -1; i++; } } } } // this else is executed when original parent chromosome has no mutations at all else parent1 = allMutationsOnGamete1; // Gamete from parent2 for(int i=0; i<parent2DelMutationsNum ; i++) { gsl_rng_default_seed += time(NULL)^i; gsl_rng_set(r, gsl_rng_default_seed); delMutationsOnGamete2.push_back(floor(gsl_ran_flat(r, 0.5, L+0.4999) + 0.5)); } // Find beneficial mutations loci for(int i=0; i<parent2BenMutationsNum ;) { gsl_rng_default_seed += time(NULL)^i; gsl_rng_set(r, gsl_rng_default_seed); int tempMutation = floor(gsl_ran_flat(r, 0.5, L+0.4999) + 0.5); int q=0; for(; q<delMutationsOnGamete2.size() ; q++) { if(delMutationsOnGamete2.at(q) == tempMutation) break; } if(q==delMutationsOnGamete2.size()) { benMutationsOnGamete2.push_back(tempMutation); i++; } } // put all the mutations in a same vector and sort allMutationsOnGamete2.insert(allMutationsOnGamete2.end(), delMutationsOnGamete2.begin(), delMutationsOnGamete2.end()); allMutationsOnGamete2.insert(allMutationsOnGamete2.end(), benMutationsOnGamete2.begin(), benMutationsOnGamete2.end()); sort(allMutationsOnGamete2.begin(), allMutationsOnGamete2.end()); // make the ben mutations negative for(int p=0; p<allMutationsOnGamete2.size() ; p++) { for(int q=0; q<benMutationsOnGamete2.size() ; q++) { if(allMutationsOnGamete2.at(p) == benMutationsOnGamete2.at(q)) { allMutationsOnGamete2.at(p) *= -1; } } } //Merge the sorted mutations with the unmutated chromosome placeOnChromosome = 0; if(parent2.size() > 0) { for(int i=0; i<allMutationsOnGamete2.size();) { if(abs(allMutationsOnGamete2.at(i)) < abs(parent2.at(placeOnChromosome))) { parent2.insert(parent2.begin() + placeOnChromosome, allMutationsOnGamete2.at(i)); i++; placeOnChromosome++; } else if(abs(allMutationsOnGamete2.at(i)) > abs(parent2.at(placeOnChromosome))) { if(placeOnChromosome < parent2.size()-1) { placeOnChromosome++; } else { parent2.insert(parent2.begin() + placeOnChromosome + 1, allMutationsOnGamete2.begin() + i, allMutationsOnGamete2.end()); break; } } // This else is for when the mutation already exists on the chromosome. else { if(allMutationsOnGamete2.at(i) == parent2.at(placeOnChromosome)) i++; else { // replace beneficial/deleterious with each other allMutationsOnGamete2.at(i) *= -1; i++; } } } } // this else is executed when original parent chromosome has no mutations at all else { parent2 = allMutationsOnGamete2; } // free up the memory taken by the random number generator gsl_rng_free(r); }
int main ( int argc, char * argv[] ) { double * rx, * ry, * rz; double * vx, * vy, * vz; double * fx, * fy, * fz; int * ix, * iy, * iz; int N=216,c,a; double L=0.0; double rho=0.5, Tb = 1.0, gamma=1.0, rc2 = 2.5; double vir, vir_sum, pcor, V; double PE, KE, TE, ecor, ecut, T0=0.0, TE0; double rr3,dt=0.001, dt2, gfric, noise; int i,j,s; int nSteps = 10, fSamp=100; int short_out=0; int use_e_corr=0; int unfold = 0; char fn[20]; FILE * out; char * wrt_code_str = "w"; char * init_cfg_file = NULL; gsl_rng * r = gsl_rng_alloc(gsl_rng_mt19937); unsigned long int Seed = 23410981; /* Here we parse the command line arguments; If you add an option, document it in the usage() function! */ for (i=1;i<argc;i++) { if (!strcmp(argv[i],"-N")) N=atoi(argv[++i]); else if (!strcmp(argv[i],"-rho")) rho=atof(argv[++i]); else if (!strcmp(argv[i],"-gam")) gamma=atof(argv[++i]); else if (!strcmp(argv[i],"-dt")) dt=atof(argv[++i]); else if (!strcmp(argv[i],"-rc")) rc2=atof(argv[++i]); else if (!strcmp(argv[i],"-ns")) nSteps = atoi(argv[++i]); else if (!strcmp(argv[i],"-so")) short_out=1; else if (!strcmp(argv[i],"-T0")) T0=atof(argv[++i]); else if (!strcmp(argv[i],"-Tb")) Tb=atof(argv[++i]); else if (!strcmp(argv[i],"-fs")) fSamp=atoi(argv[++i]); else if (!strcmp(argv[i],"-sf")) wrt_code_str = argv[++i]; else if (!strcmp(argv[i],"-icf")) init_cfg_file = argv[++i]; else if (!strcmp(argv[i],"-ecorr")) use_e_corr = 1; else if (!strcmp(argv[i],"-seed")) Seed = (unsigned long)atoi(argv[++i]); else if (!strcmp(argv[i],"-uf")) unfold = 1; else if (!strcmp(argv[i],"-h")) { usage(); exit(0); } else { fprintf(stderr,"Error: Command-line argument '%s' not recognized.\n", argv[i]); exit(-1); } } /* Compute the side-length */ L = pow((V=N/rho),0.3333333); /* Compute the tail-corrections; assumes sigma and epsilon are both 1 */ rr3 = 1.0/(rc2*rc2*rc2); ecor = use_e_corr?8*M_PI*rho*(rr3*rr3*rr3/9.0-rr3/3.0):0.0; pcor = use_e_corr?16.0/3.0*M_PI*rho*rho*(2./3.*rr3*rr3*rr3-rr3):0.0; ecut = 4*(rr3*rr3*rr3*rr3-rr3*rr3); /* Compute the *squared* cutoff, reusing the variable rc2 */ rc2*=rc2; /* compute the squared time step */ dt2=dt*dt; /* Compute gfric */ gfric = 1.0-gamma*dt/2.0; /* Compute noise */ noise = sqrt(6.0*gamma*Tb/dt); /* Output some initial information */ fprintf(stdout,"# Langevin-Thermostat MD Simulation" " of a Lennard-Jones fluid\n"); fprintf(stdout,"# L = %.5lf; rho = %.5lf; N = %i; rc = %.5lf\n", L,rho,N,sqrt(rc2)); fprintf(stdout,"# nSteps %i, seed %d, dt %.5lf, T0 %.5lf, gamma %.5lf\n", nSteps,Seed,dt,T0,gamma); fprintf(stdout,"# gfric %.5lf noise %.5lf\n",gfric,noise); /* Seed the random number generator */ gsl_rng_set(r,Seed); /* Allocate the position arrays */ rx = (double*)malloc(N*sizeof(double)); ry = (double*)malloc(N*sizeof(double)); rz = (double*)malloc(N*sizeof(double)); /* Allocate the boundary crossing counter arrays */ ix = (int*)malloc(N*sizeof(int)); iy = (int*)malloc(N*sizeof(int)); iz = (int*)malloc(N*sizeof(int)); /* Allocate the velocity arrays */ vx = (double*)malloc(N*sizeof(double)); vy = (double*)malloc(N*sizeof(double)); vz = (double*)malloc(N*sizeof(double)); /* Allocate the force arrays */ fx = (double*)malloc(N*sizeof(double)); fy = (double*)malloc(N*sizeof(double)); fz = (double*)malloc(N*sizeof(double)); /* Generate initial positions on a cubic grid, and measure initial energy */ init(rx,ry,rz,vx,vy,vz,ix,iy,iz,N,L,r,T0,&KE,init_cfg_file); sprintf(fn,"%i.xyz",0); out=fopen(fn,"w"); xyz_out(out,rx,ry,rz,vx,vy,vz,ix,iy,iz,L,N,16,1,unfold); fclose(out); PE = total_e(rx,ry,rz,fx,fy,fz,N,L,rc2,ecor,ecut,&vir); TE0=PE+KE; fprintf(stdout,"# step time PE KE TE drift T P\n"); for (s=0;s<nSteps;s++) { /* First integration half-step */ for (i=0;i<N;i++) { rx[i] += vx[i]*dt+0.5*dt2*fx[i]; ry[i] += vy[i]*dt+0.5*dt2*fy[i]; rz[i] += vz[i]*dt+0.5*dt2*fz[i]; vx[i] = vx[i]*gfric + 0.5*dt*fx[i]; vy[i] = vy[i]*gfric + 0.5*dt*fy[i]; vz[i] = vz[i]*gfric + 0.5*dt*fz[i]; /* Apply periodic boundary conditions */ if (rx[i]<0.0) { rx[i]+=L; ix[i]--; } if (rx[i]>L) { rx[i]-=L; ix[i]++; } if (ry[i]<0.0) { ry[i]+=L; iy[i]--; } if (ry[i]>L) { ry[i]-=L; iy[i]++; } if (rz[i]<0.0) { rz[i]+=L; iz[i]--; } if (rz[i]>L) { rz[i]-=L; iz[i]++; } } /* Calculate forces */ /* Initialize forces */ for (i=0;i<N;i++) { fx[i] = 2*noise*(gsl_rng_uniform(r)-0.5); fy[i] = 2*noise*(gsl_rng_uniform(r)-0.5); fz[i] = 2*noise*(gsl_rng_uniform(r)-0.5); } PE = total_e(rx,ry,rz,fx,fy,fz,N,L,rc2,ecor,ecut,&vir); /* Second integration half-step */ KE = 0.0; for (i=0;i<N;i++) { vx[i] = vx[i]*gfric + 0.5*dt*fx[i]; vy[i] = vy[i]*gfric + 0.5*dt*fy[i]; vz[i] = vz[i]*gfric + 0.5*dt*fz[i]; KE+=vx[i]*vx[i]+vy[i]*vy[i]+vz[i]*vz[i]; } KE*=0.5; TE=PE+KE; fprintf(stdout,"%i %.5lf %.5lf %.5lf %.5lf %.5le %.5lf %.5lf\n", s,s*dt,PE,KE,TE,(TE-TE0)/TE0,KE*2/3./N,rho*KE*2./3./N+vir/3.0/V); if (!(s%fSamp)) { sprintf(fn,"%i.xyz",!strcmp(wrt_code_str,"a")?0:s); out=fopen(fn,wrt_code_str); xyz_out(out,rx,ry,rz,vx,vy,vz,ix,iy,iz,L,N,16,1,unfold); fclose(out); } } }
int main(int argc, char **argv) { /* program variables */ unsigned int i,j,k,m,m_x,m_y; /* variables to iterate over */ double x,y,z; double scanxy = 15e-6; /* the boundary of the region */ double lambda_light = 632.8e-9; /* wavelength of light */ int NSCAT = 65; /*the scatterer number*/ int NSA = 50000; /* the simulation iteration for the angle for each scatter*/ int var_x = 10; int var_y = 10; /*number of sets of the positions*/ camera_t cam = {0.20,0.20,512,512}; /*initialize the cam struct*/ double z0 = 0.13; /* the camera distance from the orginal plane*/ field_t(*field)[NSCAT] = malloc((sizeof *field)*NSA); assert(field!=NULL); /* seed the scatterers */ scatterer_t *scatts = malloc(NSCAT*sizeof(scatterer_t)); assert(scatts!=NULL); /* the locations */ scatterer_t *locations = malloc(NSCAT*sizeof(scatterer_t)); assert(locations!=NULL); /*free path array*/ double *free_path = malloc(NSA*NSCAT*sizeof(double)); /* the radiation counting for NSCATS */ int *visting_array = malloc(NSCAT*sizeof(int)); bzero(visting_array,NSCAT*sizeof(int)); /* To read the scatterers positions from the file into the scatterer array*/ FILE *fp = fopen("Scatterers.txt","r"); if (fp == 0) { fprintf(stderr, "failed to open the file"); exit(1); } for (i = 0; i < NSCAT-1; ++i) { fscanf(fp,"%lf %lf %lf",&scatts[i].x,&scatts[i].y,&scatts[i].z); fscanf(fp,"\n"); //printf("%12.12f %12.12f %12.12f\n",scatts[i].x,scatts[i].y,scatts[i].z); } fclose(fp); FILE *fp_counting = fopen("visting_counter_moving.txt","w"); if (fp_counting == 0) { fprintf(stderr, "failed to open the file"); exit(1); } FILE *fp_x = fopen("Scatterers_x_moving.txt","w"); if (fp_x == 0) { fprintf(stderr, "failed to open the file"); exit(1); } FILE *fp_y = fopen("Scatterers_y_moving.txt","w"); if (fp_y == 0) { fprintf(stderr, "failed to open the file"); exit(1); } index_bounds (*Matrix)[NSCAT-1] = malloc((sizeof *Matrix)*NSCAT); index_bounds *matrix; for(m = 0; m < var_x*var_y; ++m) { bzero(visting_array,NSCAT*sizeof(int)); m_x = m/var_x; m_y = m%var_y; scatts[NSCAT-1].x = m_x*scanxy/var_x - scanxy/2.0; scatts[NSCAT-1].y = m_y*scanxy/var_y - scanxy/2.0; scatts[NSCAT-1].z = 500e-9; for (i = 0; i < NSCAT; ++i) { fprintf(fp_x,"%-12.12f ",scatts[i].x); } fprintf(fp_x,"\n"); for (i = 0; i < NSCAT; ++i) { fprintf(fp_y,"%-12.12f ",scatts[i].y); } fprintf(fp_y,"\n"); for (i = 0; i < NSCAT; ++i) { matrix = Matrix[i]; conduc_matrix(NSCAT, scatts, i, matrix); for (k = 0; k < NSCAT-1; ++k) { printf("%12.12f %d %12.12f || ",Matrix[i][k].lower_bound,Matrix[i][k].index,Matrix[i][k].upper_bound); } printf("%d\n",i); } printf("%s\n","conductive matrix finished"); //scatts[500].x = 5.0e-6; //scatts[500].y = 4.0e-6; //scatts[500].z = 0.2e-6; /* initialize the random number generator */ int rseed = (int)time(NULL); const gsl_rng_type *T; gsl_rng *r; gsl_rng_env_setup(); T = gsl_rng_default; r = gsl_rng_alloc(T); gsl_rng_set(r,rseed); /* *Create the path length array */ for(i=0; i<NSA; ++i) { for (j = 0; j < NSCAT; ++j) { matrix = Matrix[j]; field[i][j] = single_field_spp(j, scatts, NSCAT, r, free_path,(i*NSCAT + j),matrix); ++visting_array[field[i][j].scatterer_index]; } } /** * Write the tmp array as a way to do the cross-correlation function. */ //char *file_names = malloc(10*sizeof(char)); //sprintf(file_names,"visting_counter_%d _ %d",NSCAT,m); for (i = 0; i < NSCAT; ++i) { fprintf(fp_counting,"%d ",visting_array[i]); } fprintf(fp_counting,"\n"); } free(Matrix); fclose(fp_counting); fclose(fp_x); fclose(fp_y); free(scatts); free(locations); printf("%s","finished"); return 0; }
void *gendyn_new(t_symbol *msg, short argc, t_atom *argv){ t_gendyn *x; x = (t_gendyn *)newobject(gendyn_class); // create a new instance of this object dsp_setup((t_pxobject *)x, 1); outlet_new((t_pxobject *)x, "signal"); if(argc == 0){ error("you must specify the gendy type [1-3]"); return NULL; } x->g_type = argv[0].a_w.w_long; x->g_whichamp = 1; x->g_whichdur = 1; x->g_aamp = 1.f; x->g_adur = 1.f; x->g_minfreq = 440.f; x->g_maxfreq = 660.f; x->g_scaleamp = 0.5f; x->g_scaledur = 0.5f; if(argc > 1) x->g_whichamp = argv[1].a_w.w_long; if(argc > 2) x->g_whichdur = argv[2].a_w.w_long; if(argc > 3){ if(argv[3].a_type == A_LONG) x->g_aamp = argv[3].a_w.w_long; else x->g_aamp = (float)argv[3].a_w.w_float; } if(argc > 4){ if(argv[4].a_type == A_LONG) x->g_adur = argv[4].a_w.w_long; else x->g_adur = (float)argv[4].a_w.w_float; } if(argc > 5){ if(argv[5].a_type == A_LONG) x->g_minfreq = argv[5].a_w.w_long; else x->g_minfreq = (float)argv[5].a_w.w_float; } if(argc > 6){ if(argv[6].a_type == A_LONG) x->g_maxfreq = argv[6].a_w.w_long; else x->g_maxfreq = (float)argv[6].a_w.w_float; } if(argc > 7){ if(argv[7].a_type == A_LONG) x->g_scaleamp = argv[7].a_w.w_long; else x->g_scaleamp = (float)argv[7].a_w.w_float; } if(argc > 8){ if(argv[8].a_type == A_LONG) x->g_scaledur = argv[8].a_w.w_long; else x->g_scaledur = (float)argv[8].a_w.w_float; } gsl_rng_env_setup(); x->g_rng = gsl_rng_alloc((const gsl_rng_type *)gsl_rng_default); // systime_ms() is a really bad idea since it'll be the same or very close if a bunch // are instantiated when the patch opens. //gsl_rng_set(x->r_rng, systime_ms()); // makeseed() is from the PD code in x_misc.c gsl_rng_set(x->g_rng, makeseed()); switch(x->g_type){ case 1: gendy1_constructor(x); break; case 2: gendy2_constructor(x); break; case 3: gendy3_constructor(x); break; } return(x); }
int main(int argc, char *argv[]) { int write_pops(hgt_pop **ps, hgt_params *params, int rank, int numprocs); int pxy_calc(hgt_stat_mean ***means, hgt_stat_variance ***vars, double *pxy, double *d1, double *d2,hgt_pop **ps, hgt_params *params, int rank, int numprocs, hgt_cov_sample_func sample_func, gsl_rng *r); int cov_calc(hgt_stat_mean ***means, hgt_stat_variance ***vars, hgt_pop **ps, hgt_params *params, int rank, int numprocs, gsl_rng *rng); int write_pxy(FILE * fp, unsigned maxl, hgt_stat_mean ***means, hgt_stat_variance ***vars, unsigned long gen); int write_cov(FILE * fp, unsigned maxl, hgt_stat_mean ***means, hgt_stat_variance ***vars, unsigned long gen); int write_ks(FILE * fp, unsigned maxl, hgt_stat_mean ***means, hgt_stat_variance ***vars, unsigned long gen); int t2_calc(hgt_stat_mean *** t2means, hgt_stat_variance *** t2vars, hgt_params * params, hgt_pop ** ps, hgt_pop_calc_most_recent_coal_func coal_time_func, int rank, int numprocs, const gsl_rng * rng); int write_t2(FILE *fp, hgt_stat_mean ***means, hgt_stat_variance ***vars, int dim, int size, unsigned long gen); int numprocs, rank, exit_code; MPI_Init(&argc, &argv); MPI_Comm_size(MPI_COMM_WORLD, &numprocs); MPI_Comm_rank(MPI_COMM_WORLD, &rank); hgt_params *params = hgt_params_alloc(); exit_code = hgt_params_parse(params, argc, argv, "hgt_mpi_moran_const"); if (exit_code == EXIT_FAILURE) { goto exit; } if (rank == 0) { hgt_params_printf(params, stdout); } const gsl_rng_type *T; gsl_rng_env_setup(); T = gsl_rng_default; long int seed = (long int) time(NULL) + rank; gsl_rng *rng = gsl_rng_alloc(T); gsl_rng_set(rng, seed); hgt_pop **ps = hgt_utils_alloc_populations(params, rank, rng); hgt_stat_mean ***p2means; hgt_stat_mean ***p3means; hgt_stat_mean ***p4means; hgt_stat_variance ***p2vars; hgt_stat_variance ***p3vars; hgt_stat_variance ***p4vars; hgt_stat_mean ***covmeans; hgt_stat_variance ***covvars; hgt_stat_mean ***t2means; hgt_stat_variance ***t2vars; hgt_stat_mean ***q2means; hgt_stat_variance ***q2vars; int linkage_dim = params->linkage_size + 1; if (rank == 0) { if (params->save_pxy == 1) { p2means = hgt_utils_alloc_stat_means(params->maxl, 4); p2vars = hgt_utils_alloc_stat_variance(params->maxl, 4); p3means = hgt_utils_alloc_stat_means(params->maxl, 4); p3vars = hgt_utils_alloc_stat_variance(params->maxl, 4); p4means = hgt_utils_alloc_stat_means(params->maxl, 4); p4vars = hgt_utils_alloc_stat_variance(params->maxl, 4); } covmeans = hgt_utils_alloc_stat_means(params->maxl+1, 4); covvars = hgt_utils_alloc_stat_variance(params->maxl+1, 4); t2means = hgt_utils_alloc_stat_means(linkage_dim, 3); t2vars = hgt_utils_alloc_stat_variance(linkage_dim, 3); q2means = hgt_utils_alloc_stat_means(linkage_dim, 3); q2vars = hgt_utils_alloc_stat_variance(linkage_dim, 3); } file_container *fc; if (rank == 0) { fc = create_file_container(params->prefix); file_container_write_headers(fc); } double *pxy = malloc(params->maxl*4*params->sample_size*sizeof(double)); double *d1 = malloc(params->seq_len*sizeof(double)); double *d2 = malloc(params->seq_len*sizeof(double)); unsigned i; time_t start, end; hgt_pop_sample_func sample_f; hgt_pop_frag_func frag_f; switch (params->frag_type) { case 1: frag_f = hgt_pop_frag_exp; break; case 2: frag_f = hgt_pop_frag_geom; break; default: frag_f = hgt_pop_frag_constant; break; } switch (params->reprodution) { case 1: sample_f = hgt_pop_sample_wf; break; case 2: sample_f = hgt_pop_sample_linear_selection; break; case 3: sample_f = hgt_pop_sample_bsc; if (rank == 0) { printf("using BSC model\n"); } break; default: sample_f = hgt_pop_sample_moran; break; } for (i = 0; i < params->sample_time; i++) { unsigned long current_generation; current_generation = (i + 1) * params->generations; start = clock(); hgt_utils_batch_evolve(ps, params->replicates, params, sample_f, frag_f, rng); end = clock(); if (rank == 0) { printf("%d, evolve using time = %ld sec\n", i, (end - start)/CLOCKS_PER_SEC); } start = clock(); if (params->save_pxy > 0) { pxy_calc(p2means, p2vars, pxy, d1, d2, ps, params, rank, numprocs, hgt_cov_sample_p2, rng); pxy_calc(p3means, p3vars, pxy, d1, d2, ps, params, rank, numprocs, hgt_cov_sample_p3, rng); pxy_calc(p4means, p4vars, pxy, d1, d2, ps, params, rank, numprocs, hgt_cov_sample_p4, rng); } cov_calc(covmeans, covvars, ps, params, rank, numprocs, rng); t2_calc(t2means, t2vars, params, ps, hgt_pop_calc_most_recent_ancestor_time, rank, numprocs, rng); t2_calc(q2means, q2vars, params, ps, hgt_pop_calc_most_recent_coal_time, rank, numprocs, rng); if (rank == 0) { if (params->save_pxy > 0) { write_pxy(fc->p2, params->maxl, p2means, p2vars, current_generation); write_pxy(fc->p3, params->maxl, p3means, p3vars, current_generation); write_pxy(fc->p4, params->maxl, p4means, p4vars, current_generation); } write_cov(fc->cov, params->maxl, covmeans, covvars, current_generation); write_ks(fc->ks, params->maxl, covmeans, covvars, current_generation); write_t2(fc->t2, t2means, t2vars, linkage_dim, 3, current_generation); write_t2(fc->q2, q2means, q2vars, linkage_dim, 3, current_generation); file_container_flush(fc); if (params->save_pxy > 0) { hgt_utils_clean_stat_means(p2means, params->maxl, 4); hgt_utils_clean_stat_means(p3means, params->maxl, 4); hgt_utils_clean_stat_means(p4means, params->maxl, 4); hgt_utils_clean_stat_variances(p2vars, params->maxl, 4); hgt_utils_clean_stat_variances(p3vars, params->maxl, 4); hgt_utils_clean_stat_variances(p4vars, params->maxl, 4); } hgt_utils_clean_stat_means(covmeans, params->maxl+1, 3); hgt_utils_clean_stat_variances(covvars, params->maxl+1, 3); hgt_utils_clean_stat_means(t2means, linkage_dim, 3); hgt_utils_clean_stat_variances(t2vars, linkage_dim, 3); hgt_utils_clean_stat_means(q2means, linkage_dim, 3); hgt_utils_clean_stat_variances(q2vars, linkage_dim, 3); } end = clock(); if (rank == 0) { printf("%d, calculation using time = %ld sec\n", i, (end - start)/CLOCKS_PER_SEC); } } if (params->save_pop > 0) { write_pops(ps, params, rank, numprocs); } if (rank == 0) { if (params->save_pxy > 0) { hgt_utils_free_stat_means(p2means, params->maxl, 4); hgt_utils_free_stat_means(p3means, params->maxl, 4); hgt_utils_free_stat_means(p4means, params->maxl, 4); hgt_utils_free_stat_variances(p2vars, params->maxl, 4); hgt_utils_free_stat_variances(p3vars, params->maxl, 4); hgt_utils_free_stat_variances(p4vars, params->maxl, 4); } hgt_utils_free_stat_means(covmeans, params->maxl+1, 4); hgt_utils_free_stat_variances(covvars, params->maxl+1, 4); hgt_utils_free_stat_means(t2means, linkage_dim, 3); hgt_utils_free_stat_variances(t2vars, linkage_dim, 3); hgt_utils_free_stat_means(q2means, linkage_dim, 3); hgt_utils_free_stat_variances(q2vars, linkage_dim, 3); file_container_close(fc); file_container_destroy(fc); } free(pxy); free(d1); free(d2); hgt_utils_free_populations(ps, params->replicates); gsl_rng_free(rng); hgt_params_free(params); exit: MPI_Finalize(); return EXIT_SUCCESS; }
int main(int argc, char *argv[]) { if (argc != 2) { cout << "Usage: setup outfilename" << endl; return(-1); } string filename = argv[1]; vector<Cparticle> ps; Cparticle p; cout << "Creating length with sides: rmax = ["<<RMAX[0]<<"] rmin = ["<<RMIN[0]<<"]"<<endl; cout << "Reynolds Number = "<<REYNOLDS_NUMBER<<endl; cout << "Density = "<<DENS<<endl; cout << "number of particles on side = "<<NX<<endl; cout << "alpha = "<<ALPHA<<endl; cout << "viscosity = "<<VISCOSITY<<endl; cout << "maxtime = "<<MAXTIME<<endl; double tsc = Nsph::courantCondition(H,2*SPSOUND); double tsv = Nsph::viscDiffusionCondition(H,VISCOSITY); cout <<"simulation will take "<<int((MAXTIME/tsc)+1)<<" steps according to Courant condition, "<<int((MAXTIME/tsv)+1)<<" steps according to visc diffusion condition"<<endl; gsl_rng *rng = gsl_rng_alloc(gsl_rng_ranlxd1); gsl_rng_set(rng,1); int numBound1,numBound2; if (PERIODIC[0]) { numBound1 = 1; numBound2 = 0; } else { numBound1 = 4; numBound2 = 4; } for (int i=1-numBound1;i<=NX+numBound2-1;i++) { cout << "\rParticle ("<<i<<","<<"0"<<"). Generation "<<((i+2)*(NY+4))/double((NX+4)*(NY+4))*100<<"\% complete"<<flush; p.tag = ps.size()+1; if (PERIODIC[0]) { p.r[0] = (i+0.5)*PSEP+RMIN[0]; } else { p.r[0] = i*PSEP+RMIN[0]; } p.dens = DENS; p.mass = PSEP*DENS; p.mass += gsl_ran_gaussian(rng,0.2*p.mass); p.h = H; p.v = 0,0; //p.v = -p.r[1]*BOX_GLOB_ANGVEL,p.r[0]*BOX_GLOB_ANGVEL; //const vect middle = (RMAX[0]-RMIN[0])/2.0 + RMIN[0]; //const vect size = (RMAX[0]-RMIN[0])/7.0; //const double sigma = (RMAX[0]-RMIN[0])/14.0; //if (all(p.r>=middle)&&all(p.r<=middle+size)) { // p.v = sin(2.0*PI*(1.0/size)*(p.r-middle)); //} else { // p.v = 0; //} //if (all(p.r>RMIN[0])&&all(p.r<RMAX[0])) { // p.v = 0.1*exp(-len2(p.r-middle)/(2.0*pow(sigma,2))); //p.v = 0.1*sin(2.0*PI*3.0*p.r); //} else { // p.v = 0.0; //} if ((i<=0)&&(!PERIODIC[0])) { p.iam = sphBoundary; p.norm1[0] = -i*PSEP; p.norm1[1] = 0; p.dist = len(p.norm1); if (p.dist==0) { p.norm1[0] = 1.0; } else { p.norm1 = p.norm1/p.dist; } } else if ((i>=NX)&&(!PERIODIC[0])) { p.iam = sphBoundary; p.norm1[0] = (NX-i)*PSEP; p.norm1[1] = 0; p.dist = len(p.norm1); if (p.dist==0) { p.norm1[0] = -1.0; } else { p.norm1 = p.norm1/p.dist; } } else { p.iam = sph; p.v[0] = 0.1*sin(PI*p.r[0]/PSEP); p.v[0] += 0.1*sin(10.0*PI*p.r[0]/(RMAX[0]-RMIN[0])); cout << "p.v = "<<p.v<<endl; } p.alpha = ALPHA; ps.push_back(p); } cout << "Total number of particles = " << ps.size() << endl; CglobalVars globals; vector<vector<double> > vprocDomain(globals.mpiSize); vector<Array<int,NDIM> > vprocNeighbrs(globals.mpiSize); vector<particleContainer > vps; vectInt split; split = 1; particleContainer pps; for (int i=0;i<ps.size();i++) { pps.push_back(ps[i]); } Nmisc::splitDomain(pps,split,vps,vprocDomain,vprocNeighbrs); //CdataLL *data = new CdataLL(ps,globals); //CsphIncompress sph(data); //CcustomOutput customOutput(data); //CcustomSim customSim(data,globals.time); cout << "Opening files for writing..."<<endl; Cio_data_vtk ioFile(filename.c_str(),&globals); cout << "Calculating Output stuff.."<<endl; //sph.calcOutputVars(); //customOutput.calcOutput(0,&customSim,&ioFile); cout << "Writing Restart data to file..."<<endl; int nProc = product(split); for (int i=0;i<nProc;i++) { globals.mpiRank = i; ioFile.setFilename(filename.c_str(),&globals); ioFile.writeGlobals(0,&globals); ioFile.writeRestart(0,vps[i],&globals); globals.mpiRank = 0; } cout << "Writing Global data to file..."<<endl; //ioFile.writeGlobals(0,&globals); ioFile.writeDomain(0,vprocDomain,vprocNeighbrs); //Write restart file for John /*ofstream fo("restartJohn.dat"); fo <<"h = "<<H<<" mass = "<<ps[0].mass<<" dens = "<<ps[0].dens<<" psep = "<<PSEP<<" Re = "<<REYNOLDS_NUMBER<<" kinematic viscosity = "<<VISCOSITY<<" n = "<<ps.size()<<endl; fo <<"r_x r_y v_x v_y flag(0=fluid,1=boundary)"<<endl; for (int i=0;i<ps.size();i++) { fo << ps[i].r[0]<<' '<<ps[i].r[1]<<' '<<ps[i].v[0]<<' '<<ps[i].v[1]<<' '<<ps[i].iam<<endl; }*/ }
SCCResults run_scc( const GlobalSettings& settings, const int& id ) { // ----- INITIALIZATION ----- SCCResults results; // define short names for the most used settings: int const& s = settings.s; fptype const& t = settings.t; fptype const& t_prime = settings.t_prime; fptype const& U = settings.U; fptype const& m_prec = settings.m_prec; // create a new random number generator gsl_rng* rng; rng = gsl_rng_alloc( gsl_rng_mt19937 ); gsl_rng_set( rng, rand() ); // initialize mean field parameter <n_i,sigma> Array<fptype, Dynamic, 1> n_up( s * s, 1 ); Array<fptype, Dynamic, 1> n_down( s * s, 1 ); if ( settings.init == 0 ) { for ( int i = 0; i < s * s; ++i ) { n_up( i ) = gsl_rng_uniform_pos( rng ); n_down( i ) = gsl_rng_uniform_pos( rng ); } } else if ( settings.init == 1 ) { for ( int i = 0; i < s * s; ++i ) { n_up( i ) = ( ( i + i / s ) % 2 == 0 ? 1.0 : 0.0 ); n_down( i ) = ( ( i + i / s ) % 2 == 1 ? 1.0 : 0.0 ); } } else if ( settings.init == 2 ) { n_up = Array<fptype, Dynamic, 1>::Constant( s * s, 1, 0.5 ); n_down = Array<fptype, Dynamic, 1>::Constant( s * s, 1, 0.5 ); } else { #pragma omp critical (output) { cerr << id << ": ERROR -> unknown initialization!" << endl; } gsl_rng_free( rng ); return results; } // construct the tight-binding part of H_sigma // (it doesn't change with the iterations, so // we only need to calculate its matrix once) Matrix<fptype, Dynamic, Dynamic> H_tb = Matrix<fptype, Dynamic, Dynamic>::Zero( s * s, s * s ); for ( int i = 0; i < s * s; ++i ) { // calculate the position of atom i in the lattice const int x = idx2x( i, s ); const int y = idx2y( i, s ); // nearest neighbour hopping H_tb( i, xy2idx( x - 1, y, s ) ) -= t; H_tb( i, xy2idx( x + 1, y, s ) ) -= t; H_tb( i, xy2idx( x, y - 1, s ) ) -= t; H_tb( i, xy2idx( x, y + 1, s ) ) -= t; // diagonal hopping H_tb( i, xy2idx( x - 1, y + 1, s ) ) -= t_prime; H_tb( i, xy2idx( x + 1, y - 1, s ) ) -= t_prime; } // save the old mean field parameters Array<fptype, Dynamic, 1> n_up_old = n_up; Array<fptype, Dynamic, 1> n_down_old = n_down; #ifdef _VERBOSE cout << endl << "Starting self consistency cycle ..." << endl; cout << "Iteration 0: " << endl; cout << n_up.transpose().head( 5 ) << endl; cout << n_down.transpose().head( 5 ) << endl; #endif // ----- SELF CONSISTENCY CYCLE ----- // forward declare variables needed in the SCC Matrix<fptype, Dynamic, Dynamic> H_up; Matrix<fptype, Dynamic, Dynamic> H_down; SelfAdjointEigenSolver< Matrix<fptype, Dynamic, Dynamic> > solver_H_up; SelfAdjointEigenSolver< Matrix<fptype, Dynamic, Dynamic> > solver_H_down; // iteration counter int iter = 0; do { ++iter; // construct H_up and H_down from the mean field parameters <n_i,sigma> H_up = H_tb; H_up += ( U * n_down ).matrix().asDiagonal(); H_down = H_tb; H_down += ( U * n_up ).matrix().asDiagonal(); // diagonalize H_up and H_down solver_H_up.compute( H_up ); solver_H_down.compute( H_down ); if ( solver_H_up.info() == NoConvergence || solver_H_down.info() == NoConvergence ) { #pragma omp critical (output) { cerr << id << ": ERROR -> diagonalization did not converge!" << endl; } gsl_rng_free( rng ); return results; } // save old mean field parameters n_up_old = n_up; n_down_old = n_down; if ( iter == 1 && settings.init == 2 ) { // calculate the fermi energy fptype E_fermi = 0.5 * ( solver_H_up.eigenvalues()( ( s * s / 2 ) - 1 ) + solver_H_down.eigenvalues()( ( s * s / 2 ) - 1 ) ); // create arrays to store which states are occupied vector<bool> occupied_up( s * s, false ); vector<bool> occupied_down( s * s, false ); // find occupied states according to the fermi distribution while ( ( int ) count( occupied_up.begin(), occupied_up.end(), true ) != s * s / 2 ) { for ( int i = 0; i < s * s; ++i ) { fptype fdi_up = fermifunc( solver_H_up.eigenvalues()( i ), E_fermi, settings.kT ); occupied_up[i] = ( fdi_up == 1.0 || gsl_rng_uniform( rng ) < fdi_up ); } } while ( ( int ) count( occupied_down.begin(), occupied_down.end(), true ) != s * s / 2 ) { for ( int i = 0; i < s * s; ++i ) { fptype fdi_down = fermifunc( solver_H_up.eigenvalues()( i ), E_fermi, settings.kT ); occupied_down[i] = ( fdi_down == 1.0 || gsl_rng_uniform( rng ) < fdi_down ); } } #ifdef _VERBOSE cout << "Initial occupied states according to FD-statistics:" << endl; for ( int i = 0; i < s * s; ++i ) { occupied_up[i] ? cout << '1' : cout << '0'; } cout << endl; for ( int i = 0; i < s * s; ++i ) { occupied_down[i] ? cout << '1' : cout << '0'; } cout << endl << endl; #endif // reset mean field parameters to zero n_up = Array<fptype, Dynamic, 1>::Constant( s * s, 1, 0.0 ); n_down = Array<fptype, Dynamic, 1>::Constant( s * s, 1, 0.0 ); // add the contributions of the individual eigenstates for ( int alpha = 0; alpha < s * s; ++alpha ) { if ( occupied_up[alpha] ) { n_up += solver_H_up.eigenvectors().col( alpha ).array().square(); } if ( occupied_down[alpha] ) { n_down += solver_H_down.eigenvectors().col( alpha ).array().square(); } } } else { // update mean field parameters with mixing fptype mix = 0.5 * gsl_rng_uniform_pos( rng ); n_up = ( 0.25 + mix ) * solver_H_up.eigenvectors() .array().block( 0, 0, s * s, s * s / 2 ).square().rowwise().sum() + ( 0.75 - mix ) * n_up; n_down = ( 0.25 + mix ) * solver_H_down.eigenvectors() .array().block( 0, 0, s * s, s * s / 2 ).square().rowwise().sum() + ( 0.75 - mix ) * n_down; } #ifdef _VERBOSE cout << "Iteration " << iter << ": " << ( n_up - n_up_old ).square().sum() << ' ' << ( n_down - n_down_old ).square().sum() << ' ' << ( solver_H_up.eigenvalues() + solver_H_down.eigenvalues() ) .head( s * s / 2 ).sum() << endl; cout << n_up.transpose().head( 5 ) << endl; cout << n_down.transpose().head( 5 ) << endl; cout << endl; cout.flush(); #endif } while ( ( ( n_up - n_up_old ).array().abs().maxCoeff() > m_prec || ( n_down - n_down_old ).array().abs().maxCoeff() > m_prec ) && iter < settings.max_iterations ); // delete random number generator gsl_rng_free( rng ); #ifdef _VERBOSE cout << "Converged after " << iter << " iterations!" << endl << endl; #endif // ----- RESULT OUTPUT ----- results.converged = ( n_up - n_up_old ).array().abs().maxCoeff() < m_prec && ( n_down - n_down_old ).array().abs().maxCoeff() < m_prec; results.iterations_to_convergence = iter; results.Delta_n_up = ( n_up - n_up_old ).array().abs().maxCoeff(); results.Delta_n_down = ( n_down - n_down_old ).array().abs().maxCoeff(); results.energy = ( solver_H_up.eigenvalues() + solver_H_down.eigenvalues() ) .head( s * s / 2 ).sum(); results.gap = min( solver_H_up.eigenvalues()( ( s * s / 2 ) + 1 ) - solver_H_up.eigenvalues()( s * s / 2 ), solver_H_down.eigenvalues()( ( s * s / 2 ) + 1 ) - solver_H_down.eigenvalues()( s * s / 2 ) ); results.m_z = n_up.sum() - n_down.sum(); results.filling = ( n_up.sum() + n_down.sum() ) / static_cast<fptype>( s * s * 2 ); results.n_up = n_up; results.n_down = n_down; results.epsilon_up = solver_H_up.eigenvalues(); results.epsilon_down = solver_H_down.eigenvalues(); results.Q_up = solver_H_up.eigenvectors(); results.Q_down = solver_H_down.eigenvectors(); results.exit_code = 0; return results; }
int main (int argc, char ** argv) { annealing_multibest_workspace_t S; annealing_configuration_t array[4]; double configurations[2+4]; /* new, current and 4 best */ double max_step = 10.0; int verbose_mode = 0; { int c; while ((c = getopt(argc, argv, "hv")) != -1) switch (c) { case 'h': fprintf(stderr, "usage: test_multi_sinc [-v] [-h]\n"); exit(EXIT_SUCCESS); case 'v': verbose_mode = 1; break; default: fprintf(stderr, "test_multi_sinc error: unknown option %c\n", c); exit(EXIT_FAILURE); } } printf("\n------------------------------------------------------------\n"); printf("test_multi_sinc: multi-best sinc minimisation with simulated annealing\n"); S.number_of_iterations_at_fixed_temperature = 10; S.max_step_value = &max_step; S.minimum_acceptance_distance = 2.0; S.temperature = 10.0; S.minimum_temperature = 1.0e-6; S.boltzmann_constant = 1.0; S.damping_factor = 1.005; S.energy_function = energy_function; S.step_function = step_function; S.copy_function = copy_function; S.log_function = (verbose_mode)? log_function : NULL; S.metric_function = metric_function; S.cooling_function = NULL; S.numbers_generator = gsl_rng_alloc(gsl_rng_rand); gsl_rng_set(S.numbers_generator, 15); S.max_number_of_best_configurations = 4; S.current_configuration.data = &(configurations[0]); S.new_configuration.data = &(configurations[1]); S.best_configurations = array; array[0].data = &(configurations[2]); array[1].data = &(configurations[3]); array[2].data = &(configurations[4]); array[3].data = &(configurations[5]); configurations[0] = 100.0; annealing_multibest_solve(&S); printf("test_multi_sinc: found %u best solutions:", S.best_configurations_count); for (size_t i=0; i<S.best_configurations_count; ++i) { double * value = array[i].data; printf(" %.5f", *value); } printf("\n------------------------------------------------------------\n\n"); gsl_rng_free(S.numbers_generator); exit(EXIT_SUCCESS); }
int main(int argc, char** argv){ int seed = getpid(); int c; int option_index = 0; int league_id; int num_players; struct argp_option options[] = { {"seed",'s', "int", 0, 0}, {"league-id", 'l', "int", 0, 0}, {"players", 'n', "int", 0, 0}, {"hitter-mean",'h', "double", 0, 0}, {"hitter-sd", 'i', "double", 0, 0}, {"pitcher-mean", 'p', "double", 0, 0}, {"pitcher-sd", 'r', "double", 0, 0}, {0} }; struct arguments args = {&seed, &league_id, &num_players, &HITTER_MEAN, &HITTER_SD, &PITCHER_MEAN, &PITCHER_SD}; struct argp argp = {options, arg_parser, 0, 0, global_child}; argp_parse(&argp, argc, argv, 0, 0, &args); #ifdef _USEGSL_ gsl_rng_env_setup(); const gsl_rng_type *type = gsl_rng_default; rng = gsl_rng_alloc(type); gsl_rng_set(rng,seed); #else srand(seed); #endif Db_Object db = db_connect(CONFIG_FILE); db->begin_transaction(db->conn); fprintf(stderr,"Seed: %d\n",seed); Array_List first_names = Array_List_create(sizeof(char*)); Array_List last_names = Array_List_create(sizeof(char*)); select_names(db,first_names,last_names); int i; struct player new_player; struct hitter_skill hitter_skill; struct pitcher_skill pitcher_skill; struct fielder_skill fielder_skill; for(i=0;i<num_players;i++){ int power= random_normal(HITTER_MEAN,HITTER_SD,MIN_SKILL,MAX_SKILL); int contact = random_normal(HITTER_MEAN,HITTER_SD,MIN_SKILL,MAX_SKILL); int fielding = random_normal(HITTER_MEAN,HITTER_SD,MIN_SKILL,MAX_SKILL); int speed = random_normal(HITTER_MEAN,HITTER_SD,MIN_SKILL,MAX_SKILL); int intelligence = random_normal(HITTER_MEAN,HITTER_SD,MIN_SKILL,MAX_SKILL); int control = random_normal(PITCHER_MEAN,PITCHER_SD,MIN_SKILL,MAX_SKILL); int movement = random_normal(PITCHER_MEAN,PITCHER_SD,MIN_SKILL,MAX_SKILL); int velocity = random_normal(PITCHER_MEAN,PITCHER_SD,MIN_SKILL,MAX_SKILL); int endurance = 0; int bats = (rand()%100)+1; int throws = (rand()%100)+1; int position = rand()%18; /*TODO: Make the choosing of names random.*/ int first_name = 8 * (power + contact + fielding + speed + bats) % first_names->length; int last_name = 8 * (first_name + speed + intelligence + control + movement + velocity + bats + throws + control + movement + position) % last_names->length; if(throws <= PERCENT_THROW_RIGHT){ new_player.throws = RIGHT; } else{ new_player.throws = LEFT; } if(bats<= PERCENT_HIT_SAME){ new_player.bats = new_player.throws; } else if(bats<PERCENT_HIT_SAME+PERCENT_HIT_DIFFERENT){ if(new_player.throws == RIGHT){ new_player.bats = LEFT; } else{ new_player.bats = RIGHT; } } else{ new_player.bats = SWITCH; } if(position <= 9 && position > 1){ new_player. position = position; pitcher_skill.end = random_normal(30.0,PITCHER_SD*SD_TWEAK,0,49); } else if(position>=15 || position == 1){ new_player.position =1; pitcher_skill.end = random_normal(80.0,PITCHER_SD*SD_TWEAK,50,100); } else{ new_player.position = 0; pitcher_skill.end = random_normal(30.0,PITCHER_SD*SD_TWEAK,0,49); } int vs_right_mod = 5; int vs_left_mod = 5; if(new_player.bats == RIGHT){ vs_right_mod = -5; } if(new_player.bats ==LEFT){ vs_left_mod = -5; } new_player.first_name = gget(first_names,first_name); new_player.last_name = gget(last_names,last_name); hitter_skill.cvr = calc_skill(contact+vs_right_mod,HITTER_SD); hitter_skill.pvr = calc_skill(power+vs_right_mod,HITTER_SD); hitter_skill.cvl = calc_skill(contact+vs_left_mod,HITTER_SD); hitter_skill.pvl = calc_skill(power+vs_left_mod,HITTER_SD); hitter_skill.spd = speed; fielder_skill.range = calc_skill(fielding,HITTER_SD); fielder_skill.arm = calc_skill(fielding,HITTER_SD); fielder_skill.field = calc_skill(fielding,HITTER_SD); new_player.intelligence = intelligence; pitcher_skill.mov = calc_skill(movement,PITCHER_SD); pitcher_skill.vel = calc_skill(velocity,PITCHER_SD); pitcher_skill.ctrl = calc_skill(control,PITCHER_SD); insert_player(db,&new_player,&hitter_skill,&pitcher_skill,&fielder_skill,league_id); } db->commit(db->conn); db->close_connection(db->conn); #ifdef _USEGSL_ gsl_rng_free(rng); #endif return 0; }
// Constructor: When an object of type "studyPop" is created, it automatically creates its first generation studyPop::studyPop(int currentRound) { if(PARASITES_EXIST) { /*** Initialize parasiteInfectionTables ***/ // perform this part if parasite host model being used is GFG if(strcmp("GFG", MODEL_OF_PARASITE_INFECTION) == 0) { if(PARASITE_PLOIDY == 1) { // Fitness tables based on Agrawal 2009 for(int i=0; i<9 ; i++) { hostFitnessTable[i][2] = 0; parasiteFitnessTable[i][2] = 0; hostFitnessTable[i][5] = 0; parasiteFitnessTable[i][5] = 0; hostFitnessTable[i][6] = 0; parasiteFitnessTable[i][6] = 0; hostFitnessTable[i][7] = 0; parasiteFitnessTable[i][7] = 0; hostFitnessTable[i][8] = 0; parasiteFitnessTable[i][8] = 0; } // Host Fitness based on Agrawal 2009 hostFitnessTable[0][0]=hostFitnessTable[0][1]=hostFitnessTable[0][3] = pow((1-PLEIOTROPIC_COST_FOR_HOST), 2.0); hostFitnessTable[0][4] = pow((1-PLEIOTROPIC_COST_FOR_HOST), 2.0) * (1-V); hostFitnessTable[1][0]=hostFitnessTable[1][1]=hostFitnessTable[1][3] = (1-PLEIOTROPIC_COST_FOR_HOST)* (1-PLEIOTROPIC_COST_FOR_HOST*D1); hostFitnessTable[1][4] = (1-PLEIOTROPIC_COST_FOR_HOST)* (1-PLEIOTROPIC_COST_FOR_HOST*D1) * (1-V); hostFitnessTable[2][0]=hostFitnessTable[2][1] = (1-PLEIOTROPIC_COST_FOR_HOST); hostFitnessTable[2][3]=hostFitnessTable[2][4] = (1-PLEIOTROPIC_COST_FOR_HOST)* (1-V); hostFitnessTable[3][0]=hostFitnessTable[3][1]=hostFitnessTable[3][3] = (1-PLEIOTROPIC_COST_FOR_HOST)* (1-PLEIOTROPIC_COST_FOR_HOST*D1); hostFitnessTable[3][4] = (1-PLEIOTROPIC_COST_FOR_HOST)* (1-PLEIOTROPIC_COST_FOR_HOST*D1) * (1-V); hostFitnessTable[4][0]=hostFitnessTable[4][1]=hostFitnessTable[4][3] = pow((1-PLEIOTROPIC_COST_FOR_HOST*D1), 2.0); hostFitnessTable[4][4] = pow((1-PLEIOTROPIC_COST_FOR_HOST*D1), 2.0) * (1-V); hostFitnessTable[5][0]=hostFitnessTable[5][1] = (1-PLEIOTROPIC_COST_FOR_HOST*D1); hostFitnessTable[5][3]=hostFitnessTable[5][4] = (1-PLEIOTROPIC_COST_FOR_HOST*D1)* (1-V); hostFitnessTable[6][0]=hostFitnessTable[6][3] = (1-PLEIOTROPIC_COST_FOR_HOST); hostFitnessTable[6][1]=hostFitnessTable[6][4] = (1-PLEIOTROPIC_COST_FOR_HOST)* (1-V); hostFitnessTable[7][0]=hostFitnessTable[7][3] = (1-PLEIOTROPIC_COST_FOR_HOST*D1); hostFitnessTable[7][1]=hostFitnessTable[7][4] = (1-PLEIOTROPIC_COST_FOR_HOST*D1)* (1-V); hostFitnessTable[8][0]=hostFitnessTable[8][1]=hostFitnessTable[8][3]=hostFitnessTable[8][4] = 1-V; // Parasite Fitness based on Agrawal 2009 for(int i=0; i<8 ; i++) parasiteFitnessTable[i][0] = 1-T_COST; parasiteFitnessTable[8][0] = 1; for(int i=0; i<6 ; i++) parasiteFitnessTable[i][1] = (1-PLEIOTROPIC_COST_FOR_PARASITE)*(1-T_COST); parasiteFitnessTable[6][1] = (1-PLEIOTROPIC_COST_FOR_PARASITE); parasiteFitnessTable[7][1] = (1-PLEIOTROPIC_COST_FOR_PARASITE); parasiteFitnessTable[8][1] = (1-PLEIOTROPIC_COST_FOR_PARASITE); for(int i=0; i<8 ; i++) { if(i != 2 && i != 5) { parasiteFitnessTable[i][3] = (1-PLEIOTROPIC_COST_FOR_PARASITE)*(1-T_COST); } } parasiteFitnessTable[2][3] = (1-PLEIOTROPIC_COST_FOR_PARASITE); parasiteFitnessTable[5][3] = (1-PLEIOTROPIC_COST_FOR_PARASITE); parasiteFitnessTable[8][3] = (1-PLEIOTROPIC_COST_FOR_PARASITE); for(int i=0; i<9 ; i++) parasiteFitnessTable[i][4] = pow((1-PLEIOTROPIC_COST_FOR_PARASITE), 2.0); } } // perform this part if parasite host model being used is MA else if(strcmp("MA", MODEL_OF_PARASITE_INFECTION) == 0) { if(PARASITE_PLOIDY == 1) { for(int i=0; i<9 ; i++) { hostFitnessTable[i][2] = 0; parasiteFitnessTable[i][2] = 0; hostFitnessTable[i][5] = 0; parasiteFitnessTable[i][5] = 0; hostFitnessTable[i][6] = 0; parasiteFitnessTable[i][6] = 0; hostFitnessTable[i][7] = 0; parasiteFitnessTable[i][7] = 0; hostFitnessTable[i][8] = 0; parasiteFitnessTable[i][8] = 0; } // find values for host & parasite fitness tables based on Agrawal 2009 for(int i=0; i<9 ; i++) { for(int j=0; j<5 ; j++) { hostFitnessTable[i][j] = 1; parasiteFitnessTable[i][j] = 1-T_COST; } } hostFitnessTable[0][0]=hostFitnessTable[2][1]=hostFitnessTable[6][3]=hostFitnessTable[8][4] = 1-V; hostFitnessTable[1][0]=hostFitnessTable[3][0]=hostFitnessTable[1][1]=hostFitnessTable[5][1]=hostFitnessTable[3][3]=hostFitnessTable[7][3]=hostFitnessTable[5][4]=hostFitnessTable[7][4] = 1 - (D1 + (1-D1)*D2)*V; hostFitnessTable[4][0]=hostFitnessTable[4][1]=hostFitnessTable[4][3]=hostFitnessTable[4][4]= 1 - pow(D1 + (1-D1)*D2, 2.0)*V; parasiteFitnessTable[0][0]=parasiteFitnessTable[2][1]=parasiteFitnessTable[6][3]=parasiteFitnessTable[8][4] = 1; parasiteFitnessTable[1][0]=parasiteFitnessTable[3][0]=parasiteFitnessTable[1][1]=parasiteFitnessTable[5][1]=parasiteFitnessTable[3][3]=parasiteFitnessTable[7][3]=parasiteFitnessTable[5][4]=parasiteFitnessTable[7][4] = 1 - (1 - D1+(1-D1)*D2)*T_COST; parasiteFitnessTable[4][0]=parasiteFitnessTable[4][1]=parasiteFitnessTable[4][3]=parasiteFitnessTable[4][4] = 1 - (1 - pow(D1 + (1-D1)*D2, 2.0))*T_COST; } } // perform this part if parasite host model being used is IMA else if(strcmp("IMA", MODEL_OF_PARASITE_INFECTION) == 0) { if(PARASITE_PLOIDY == 1) { for(int i=0; i<9 ; i++) { hostFitnessTable[i][2] = 0; parasiteFitnessTable[i][2] = 0; hostFitnessTable[i][5] = 0; parasiteFitnessTable[i][5] = 0; hostFitnessTable[i][6] = 0; parasiteFitnessTable[i][6] = 0; hostFitnessTable[i][7] = 0; parasiteFitnessTable[i][7] = 0; hostFitnessTable[i][8] = 0; parasiteFitnessTable[i][8] = 0; } // find values for host & parasite fitness tables based on Agrawal 2009 for(int i=0; i<9 ; i++) { for(int j=0; j<5 ; j++) { if(j==2) continue; hostFitnessTable[i][j] = 1-V; parasiteFitnessTable[i][j] = 1; } } hostFitnessTable[0][0]=hostFitnessTable[2][1]=hostFitnessTable[6][3]=hostFitnessTable[8][4] = 1; hostFitnessTable[1][0]=hostFitnessTable[3][0]=hostFitnessTable[1][1]=hostFitnessTable[5][1]=hostFitnessTable[3][3]=hostFitnessTable[7][3]=hostFitnessTable[5][4]=hostFitnessTable[7][4] = 1 - V - (D1 + (1-D1)*D2)*V; hostFitnessTable[4][0]=hostFitnessTable[4][1]=hostFitnessTable[4][3]=hostFitnessTable[4][4]= 1 - V - pow(D1 + (1-D1)*D2, 2.0)*V; parasiteFitnessTable[0][0]=parasiteFitnessTable[2][1]=parasiteFitnessTable[6][3]=parasiteFitnessTable[8][4] = 1 - T_COST; parasiteFitnessTable[1][0]=parasiteFitnessTable[3][0]=parasiteFitnessTable[1][1]=parasiteFitnessTable[5][1]=parasiteFitnessTable[3][3]=parasiteFitnessTable[7][3]=parasiteFitnessTable[5][4]=parasiteFitnessTable[7][4] = 1 - (D1+(1-D1)*D2)*T_COST; parasiteFitnessTable[4][0]=parasiteFitnessTable[4][1]=parasiteFitnessTable[4][3]=parasiteFitnessTable[4][4] = 1 - pow(D1 + (1-D1)*D2, 2.0)*T_COST; } } // In the following parts we initialize Parasite frequencies // use GSL library random num geberator to generate random frequencies const gsl_rng_type * T; gsl_rng * r; // Initialize the random number generator T = gsl_rng_taus; r = gsl_rng_alloc (T); gsl_rng_set (r, gsl_rng_default_seed); double freqA = gsl_ran_flat(r, 0.1, 0.9); double freq_a = 1-freqA; gsl_rng_default_seed += time(NULL); gsl_rng_set (r, gsl_rng_default_seed); double freqB = gsl_ran_flat(r, 0.1, 0.9); double freq_b = 1-freqB; gsl_rng_default_seed += time(NULL); gsl_rng_set (r, gsl_rng_default_seed); // free up the memory taken by the random num generator gsl_rng_free(r); for(int i=0; i<9 ; i++) { parasites[i] = 0; } if(PARASITE_PLOIDY == 1) { parasites[0] = freqA * freqB; parasites[1] = freqA * freq_b; parasites[3] = freq_a * freqB; parasites[4] = freq_a * freq_b; } else if(PARASITE_PLOIDY == 2) { for(int i=0; i<9 ; i++) { parasites[i] = 1; for(int j=0; j<(int)(i/3) ; j++) { parasites[i] *= freq_a; } for(int j=0; j<2-(int)(i/3) ; j++) { parasites[i] *= freqA; } for(int j=0; j<i-((int)(i/3)*3) ; j++) { parasites[i] *= freq_b; } for(int j=0; j<2-i+((int)(i/3)*3) ; j++) { parasites[i] *= freqB; } } } } // initialize tempHostfreq. The values for immunityGenotypeFreq is calculated later in the code for(int i=0; i<9 ; i++) { immunityGenotypeFreq[i] = tempHostFreq[i] = 0; } for(int i=0; i<POPULATION; i++) { gsl_rng_default_seed += time(NULL)^i; indiv newIndiv(currentRound); immunityGenotypeFreq[(int)((newIndiv.immunityGeneA[0]+newIndiv.immunityGeneA[1])*3 + newIndiv.immunityGeneB[0]+newIndiv.immunityGeneB[1])] += 1; thePop.push_back(newIndiv); } for(int i=0; i<9 ; i++) { immunityGenotypeFreq[i] /= POPULATION; } // initialize other variables highestNewW=0; highestNewDadW = 0; meanRecombination = 1; newMeanRecombination = 0; selfedChildren[0] = 0.0; selfedChildren[1] = 0.0; outcrossedChildren[0] = 0.0; outcrossedChildren[1] = 0.0; population = POPULATION; }
int main(int argc, char *argv[]) { double mean = atof(argv[1]); double sigma = atof(argv[2]); //for cell 1 double g_Na1 = atof(argv[3]); //uS/nF double g_CaT1 = atof(argv[4])-0.5; double g_CaS1 = atof(argv[5])-0.5; double g_A1 = atof(argv[6]); double g_KCa1 = atof(argv[7])+1000.0; double g_K1 = atof(argv[8]); double g_H1 = atof(argv[9]); double g_L1 = atof(argv[10]);; //uS/nF //for cell 2 double g_Na2 = atof(argv[11]); //uS/nF double g_CaT2 = atof(argv[12])-0.5; double g_CaS2 = atof(argv[13])-0.5; double g_A2 = atof(argv[14]); double g_KCa2 = atof(argv[15])+1000.0; double g_K2 = atof(argv[16]); double g_H2 = atof(argv[17]); double g_L2 = atof(argv[18]);; //uS/nF //synaptic double g_syn1 = atof(argv[19]); double g_syn2 = atof(argv[20]); // double corr_coef = atof(argv[21]); //correlation coefficient of the input double tau_c = atof(argv[22]); //correlation time const int num_run = atof(argv[23]); //don't use, use voltage derivative double V_th = -15; //mV, threshold for detecting spikes /*open files where spikes will be recorded*/ char sp_file1 [999]; sprintf (sp_file1, "spikes1_mean_%g_sig_%g_gNa_%g_gCaT_%g_gCaS_%g_gA_%g_gKCa_%g_gK_%g_gH_%g_gL_%g_gsyn_%g_%g_corr_%g_tc_%g_dt_%g_num_%d.dat", mean, sigma, g_Na1, g_CaT1, g_CaS1, g_A1, g_KCa1, g_K1, g_H1, g_L1, g_syn1, g_syn2, corr_coef,tau_c, dt, num_run); FILE *spfile1; spfile1 = fopen(sp_file1,"w"); // char sp_file2 [999]; sprintf (sp_file2, "spikes2_mean_%g_sig_%g_gNa_%g_gCaT_%g_gCaS_%g_gA_%g_gKCa_%g_gK_%g_gH_%g_gL_%g_gsyn_%g_%g_corr_%g_tc_%g_dt_%g_num_%d.dat", mean, sigma, g_Na2, g_CaT2, g_CaS2, g_A2, g_KCa2, g_K2, g_H2, g_L2, g_syn1, g_syn2, corr_coef,tau_c, dt, num_run); FILE *spfile2; spfile2 = fopen(sp_file2,"w"); /* char V_file1 [999]; sprintf (V_file1, "V1_mean_%g_sig_%g_gNa_%g_gCaT_%g_gCaS_%g_gA_%g_gKCa_%g_gK_%g_gH_%g_gL_%g_gsyn_%g_%g_corr_%g_tc_%g_dt_%g_num_%d.dat", mean, sigma, g_Na1, g_CaT1, g_CaS1, g_A1, g_KCa1, g_K1, g_H1, g_L1, g_syn1, g_syn2, corr_coef,tau_c, dt, num_run); FILE *Vfile1; Vfile1 = fopen(V_file1,"w"); // char V_file2 [999]; sprintf (V_file2, "V2_mean_%g_sig_%g_gNa_%g_gCaT_%g_gCaS_%g_gA_%g_gKCa_%g_gK_%g_gH_%g_gL_%g_gsyn_%g_%g_corr_%g_tc_%g_dt_%g_num_%d.dat", mean, sigma, g_Na2, g_CaT2, g_CaS2, g_A2, g_KCa2, g_K2, g_H2, g_L2, g_syn1, g_syn2, corr_coef,tau_c, dt, num_run); FILE *Vfile2; Vfile2 = fopen(V_file2,"w"); */ /*For random number generation:*/ gsl_rng * r; r = gsl_rng_alloc (gsl_rng_default); gsl_rng_set(r, time(NULL)); /*done*/ int ii, jj, nn; /* Defining the model gate = [ m h ][4] gating variables for the four conductances g = [ g_Na g_CaT g_CaS g_A g_KCa g_K g_H g_leak ] maximal conductances E = [ E_Na E_CaT E_CaS E_A E_KCa E_K E_H E_leak ] Nernst (reversal) potentials gmh = [ conductances as a function of time ] */ //reversal potentials double E_Na = 50; //mV or 30? double E_A = -80; //mV double E_K = -80; //mV double E_H = -20; //mV double E_Ca[2]; E_Ca[0] = 120; E_Ca[1] = 120; //mV default, but will vary double E_L = -50; //mV double C = 1; //nF double tau_Ca = 20; //ms double I_Ca[2]; I_Ca[0] = 0; I_Ca[1] = 0; //synaptic double E_syn = -80; //mV double tau_syn = 100; //ms double V_half = -45; //mV double V_slope = 5; //mV /*Initial conditions*/ double V[2]; V[0] = -46.8; //mV V[1] = -50; double Ca[2]; Ca[0] = 0.2; Ca[1] = 0.2; double Ca_inf[2]; Ca_inf[0] = 0.2; Ca_inf[1] = 0.2; double g[7][2]; double gate[2][7][2]; double tau[2][7][2]; double gate_inf[2][7][2]; double E[7][2]; int p[7]; double gnmh[7][2]; for (nn=0;nn<2;nn++) { for (ii=0;ii<7;ii++) { gate[0][ii][nn] = 0.02; //m gate[1][ii][nn] = 0.7; //h gnmh[ii][nn] = 0.0; } } E[0][0] = E_Na; E[0][1] = E_Na; E[1][0] = E_Ca[0]; E[1][1] = E_Ca[1]; E[2][0] = E_Ca[0]; E[2][1] = E_Ca[1]; E[3][0] = E_A; E[3][1] = E_A; E[4][0] = E_K; E[4][1] = E_K; E[5][0] = E_K; E[5][1] = E_K; E[6][0] = E_H; E[6][1] = E_H; // p[0] = p_Na; p[1] = p_CaT; p[2] = p_CaS; p[3] = p_A; p[4] = p_KCa; p[5] = p_K; p[6] = p_H; g[0][0] = g_Na1; g[0][1] = g_Na2; g[1][0] = g_CaT1; g[1][1] = g_CaT2; g[2][0] = g_CaS1; g[2][1] = g_CaS2; g[3][0] = g_A1; g[3][1] = g_A2; g[4][0] = g_KCa1; g[4][1] = g_KCa2; g[5][0] = g_K1; g[5][1] = g_K2; g[6][0] = g_H1; g[6][1] = g_H2; double g_L[2]; g_L[0] = g_L1; g_L[1] = g_L2; double current_time = 0.0; double s_c = mean; double s_1 = mean; double s_2 = mean; double s[2]; double Svar[2]; Svar[0] = 0; Svar[1] = 0; double S_inf[2]; S_inf[0] = 0; S_inf[1] = 0; double g_syn[2]; g_syn[0] = g_syn1; g_syn[1] = g_syn2; int counter = 0; int voltage_high1 = 0; double spike1 = 0.0; //to impose an absolute refractory period when reading spikes int voltage_high2 = 0; double spike2 = 0.0; //to impose an absolute refractory period when reading spikes double rand_g1 = 0.0; double rand_g2 = 0.0; double rand_g3 = 0.0; double ds = 0.0; // double I_ion[2]; I_ion[0] = 0.0; I_ion[1] = 0.0; double sum_g[2], sum_Eg[2], tau_V[2], V_inf[2]; while (current_time < total_time) { current_time += dt; counter ++; //s = mean + sigma/sqrt(dt)*rand_g; //if white noise //common input rand_g1 = gsl_ran_gaussian (r,1.0); //if correlated noise with correlation time constant tau_c ds = (mean-s_c)*(1-exp(-dt/tau_c)) + sigma*sqrt(1-exp(-2*dt/tau_c))*rand_g1; s_c += ds; //independent input cell 1 rand_g2 = gsl_ran_gaussian (r,1.0); ds = (mean-s_1)*(1-exp(-dt/tau_c)) + sigma*sqrt(1-exp(-2*dt/tau_c))*rand_g2; s_1 += ds; //independent input cell 2 rand_g3 = gsl_ran_gaussian (r,1.0); ds = (mean-s_2)*(1-exp(-dt/tau_c)) + sigma*sqrt(1-exp(-2*dt/tau_c))*rand_g3; s_2 += ds; s[0] = s_1*(1-corr_coef) + s_c*corr_coef; //input to cell 1 s[1] = s_2*(1-corr_coef) + s_c*corr_coef; //input to cell 2 /* Model equations: C dv/dt = s - I_ion I_ion = sum( gate.*(V-E) ) d gate/dt = -1/tau(v).*(gate-gate_0(v)) */ for (nn=0;nn<2;nn++) { E_Ca[nn] = 500.0*R_F*(T + 273.15)*log(3000.0/Ca[nn]); E[1][nn] = E_Ca[nn]; E[2][nn] = E_Ca[nn]; Ca_inf[nn] = 0.05 + 0.94*I_Ca[nn]; // integrate Ca dynamics Ca[nn] = Ca[nn] + (1-exp(-dt/tau_Ca))*(Ca_inf[nn] - Ca[nn]); tau[0][0][nn] = 1.32 - 1.26/(1.0+exp((V[nn]+120.0)/(-25.0))); //m, Na tau[1][0][nn] = 0.67/(1+exp((V[nn]+62.9)/(-10.0)))*(1.5+1.0/(1.0+exp((V[nn]+34.9)/3.6))); //h, Na tau[0][1][nn] = 21.7 - 21.3/(1.0 + exp((V[nn]+68.1)/(-20.5))); //m, CaT tau[1][1][nn] = 105.0 - 89.8/(1.0 + exp((V[nn]+55.0)/(-16.9))); //h, CaT tau[0][2][nn] = 1.4 + 7.0/(exp((V[nn]+27.0)/10.0) + exp((V[nn]+70.0)/(-13.0))); //m, CaS tau[1][2][nn] = 60.0 + 150.0/(exp((V[nn]+55.0)/9.0) + exp((V[nn]+65.0)/(-16.0))); //h, CaS tau[0][3][nn] = 11.6 - 10.4/(1.0+exp((V[nn]+32.9)/(-15.2))); //m, A tau[1][3][nn] = 38.6 - 29.2/(1.0+exp((V[nn]+38.9)/(-26.5))); //h, A tau[0][4][nn] = 90.3 - 75.1/(1.0+exp((V[nn]+46.0)/(-22.7))); //m, KCa tau[1][4][nn] = 0.0; //h, kCa tau[0][5][nn] = 7.2 - 6.4/(1+exp((V[nn]+28.3)/(-19.2))); //m, Kd tau[1][5][nn] = 0.0; //h, Kd tau[0][6][nn] = 272.0 + 1499.0/(1.0+exp((V[nn]+42.2)/(-8.73))); //m, H tau[1][6][nn] = 0.0; //h, H gate_inf[0][0][nn] = 1.0/(1.0+exp((V[nn]+25.5)/(-5.29))); //m, Na gate_inf[1][0][nn] = 1.0/(1.0+exp((V[nn]+48.9)/5.18)); //h, Na gate_inf[0][1][nn] = 1.0/(1.0 + exp((V[nn]+27.1)/(-7.2))); //m, CaT gate_inf[1][1][nn] = 1.0/(1.0 + exp((V[nn]+32.1)/5.5)); //h, CaT gate_inf[0][2][nn] = 1.0/(1.0+exp((V[nn]+33.0)/-8.1)); //m, CaS gate_inf[1][2][nn] = 1.0/(1.0+exp((V[nn]+60.0)/6.2)); //h, CaT gate_inf[0][3][nn] = 1.0/(1.0+exp((V[nn]+27.2)/(-8.7))); //m, A gate_inf[1][3][nn] = 1.0/(1.0+exp((V[nn]+56.9)/4.9)); //h, A gate_inf[0][4][nn] = (Ca[nn]/(Ca[nn]+3.0))/(1.0+exp((V[nn]+28.3)/-12.6)); //m, kCa gate_inf[1][4][nn] = 0.0; //h, kCa gate_inf[0][5][nn] = 1.0/(1.0+exp((V[nn]+12.3)/(-11.8))); //m, Kd gate_inf[1][5][nn] = 0.0; //h, Kd gate_inf[0][6][nn] = 1.0/(1.0+exp((V[nn]+70.0)/6.0)); //m, H gate_inf[1][6][nn] = 0.0; //h, H } //V_pre = V[0] if (V[0]>V_half) { S_inf[1] = tanh((V[0]-V_half)/V_slope); } else { S_inf[1] = 0; } //V_pre = V[1] if (V[1]>V_half) { S_inf[0] = tanh((V[1]-V_half)/V_slope); } else { S_inf[0] = 0; } for (nn=0;nn<2;nn++) { //evolve Svar Svar[nn] = Svar[nn] + (1-exp(-dt/(tau_syn*(1-S_inf[nn]))))*(S_inf[nn] - Svar[nn]); //evolve the conductances, first order Euler for (ii=0;ii<7;ii++) { gate[0][ii][nn] = gate[0][ii][nn] + (1-exp(-dt/tau[0][ii][nn]))*(gate_inf[0][ii][nn] - gate[0][ii][nn]); gate[1][ii][nn] = gate[1][ii][nn] + (1-exp(-dt/tau[1][ii][nn]))*(gate_inf[1][ii][nn] - gate[1][ii][nn]); } //reset gate[1][4][nn] = 1.0; //h, KCa gate[1][5][nn] = 1.0; //h, Kd gate[1][6][nn] = 1.0; //h, H sum_g[nn] = g_L[nn] + g_syn[nn]*Svar[nn]; sum_Eg[nn] = g_L[nn]*E_L + g_syn[nn]*Svar[nn]*E_syn; for (ii=0;ii<7;ii++) { gnmh[ii][nn] = g[ii][nn]*get_power(gate[0][ii][nn],p[ii])*gate[1][ii][nn]; sum_g[nn] += gnmh[ii][nn]; sum_Eg[nn] += gnmh[ii][nn]*E[ii][nn]; } I_Ca[nn] = (gnmh[1][nn] + gnmh[2][nn])*(E_Ca[nn]-V[nn]); /* I_ion[nn] = g_L*(V[nn]-E_L); //sum of all ionic currents for (ii=0;ii<4; ii++) { I_ion[nn] += gnmh[ii][nn]*(V[nn]-E[ii]); } */ tau_V[nn] = C/sum_g[nn]; //Membrane time constant. // V_inf is steady-state voltage. V_inf[nn] = (sum_Eg[nn] + s[nn])*tau_V[nn]; //evolve the voltage using exponential Euler V[nn] = V_inf[nn] + (V[nn]-V_inf[nn])*exp(-dt/tau_V[nn]); } /* if (fmod(current_time,0.1)<dt) { //printf("%g \n",current_time); fprintf(Vfile1,"%f \n", V[0]); fprintf(Vfile2,"%f \n", V[1]); } */ //find out if there's a spike and record it if (V[0] > V_th & current_time>5000) { //if a high threshold was detected, record the spike if (voltage_high1 == 0 && current_time-spike1>5) //5 is tau_abs { fprintf(spfile1,"%f \n", current_time); spike1 = current_time; } //if the high threshold was continuous (after spike has occured) //then wait for it to cross the threshold again before recording voltage_high1 ++; } else { if (voltage_high1 > 0) { voltage_high1 = 0; //reset } } //same for cell 2 if (V[1] > V_th & current_time>5000) { //if a high threshold was detected, record the spike if (voltage_high2 == 0 && current_time-spike2>5) //5 is tau_abs { fprintf(spfile2,"%f \n", current_time); spike2 = current_time; } //if the high threshold was continuous (after spike has occured) //then wait for it to cross the threshold again before recording voltage_high2 ++; } else { if (voltage_high2 > 0) { voltage_high2 = 0; //reset } } } fclose(spfile1); fclose(spfile2); //fclose(Vfile1); //fclose(Vfile2); return 0; }
// make a child with given parents (in case of selfing, both parents are the same indiv) // MH NOTE: I've yet to update this section to account for asex: but if it is only used // when testing ID, then I suspect accounting for asex is not needed...? indiv* studyPop::makeForcedIndiv(int mom, int dad, int currentRound) { vector<int> *momChromosome, *dadChromosome; // variables to save R,S,N,immuneA and immuneB inherited from parents double momS, momR, dadS, dadR, momN, dadN; int momA, momB, dadA, dadB; // Initialize the random number generator const gsl_rng_type * T; gsl_rng * r; T = gsl_rng_default; r = gsl_rng_alloc (T); gsl_rng_default_seed += time(NULL); gsl_rng_set (r, gsl_rng_default_seed); // Get the chromosomes from mom and dad momChromosome = thePop.at(mom).makeGamete(this->meanRecombination,0,0); dadChromosome = thePop.at(dad).makeGamete(this->meanRecombination,0,1); // renew the seed for more randomization gsl_rng_default_seed += time(NULL); gsl_rng_set (r, gsl_rng_default_seed); // A variable to store the mutation amount of Selfing, recomb and neutral genes (R,S,N) double geneMutation; momN = *(thePop.at(mom).neutralGene + momChromosome->at(momChromosome->size()-5)); // After mutation check, add mutation to inherited neutral gene double randomMutationChecker; randomMutationChecker = gsl_ran_flat(r, 0, 1); gsl_rng_default_seed += time(NULL); gsl_rng_set (r, gsl_rng_default_seed); if(randomMutationChecker<NEUTRALMUTATIONRATE) { geneMutation = gsl_ran_gaussian(r, SIGMAN); momN = momN + geneMutation; gsl_rng_default_seed += time(NULL)^(mom); gsl_rng_set (r, gsl_rng_default_seed); } momS = *(thePop.at(mom).selfingGene + momChromosome->at(momChromosome->size()-4)); // After mutation check, add mutation to inherited selfing gene and keep it in [0,1] randomMutationChecker = gsl_ran_flat(r, 0, 1); gsl_rng_default_seed += time(NULL); gsl_rng_set (r, gsl_rng_default_seed); if(randomMutationChecker<SELFINGMUTATIONRATE) { geneMutation = gsl_ran_gaussian(r, SIGMAS); momS = ((momS + geneMutation) > 0 ? ((momS + geneMutation) < 1 ? (momS + geneMutation) : 1) : 0); gsl_rng_default_seed += time(NULL)^((int)floor(gsl_ran_flat(r, -0.5, 1.4999) + 0.5)+1); gsl_rng_set (r, gsl_rng_default_seed); } momR = *(thePop.at(mom).recombinationGene + momChromosome->at(momChromosome->size()-3)); // After mutation check, add mutations to inherited recombination gene and keep it >0 randomMutationChecker = gsl_ran_flat(r, 0, 1); gsl_rng_default_seed += time(NULL); gsl_rng_set (r, gsl_rng_default_seed); if(randomMutationChecker<RECOMBMUTATIONRATE) { geneMutation = gsl_ran_gaussian(r, SIGMAR); momR = (momR + geneMutation)>0 ? (momR + geneMutation) : 0; gsl_rng_default_seed += time(NULL)^((int)floor(gsl_ran_flat(r, -0.5, 1.4999) + 0.5)+1); gsl_rng_set (r, gsl_rng_default_seed); } // mutation is not added here, it is added later, after a generation is made momA = *(thePop.at(mom).immunityGeneA + momChromosome->at(momChromosome->size()-2)); momB = *(thePop.at(mom).immunityGeneB + momChromosome->at(momChromosome->size()-1)); dadN = *(thePop.at(dad).neutralGene + dadChromosome->at(dadChromosome->size()-5)); // After mutation check, add mutation to inherited neutral gene randomMutationChecker = gsl_ran_flat(r, 0, 1); gsl_rng_default_seed += time(NULL); gsl_rng_set (r, gsl_rng_default_seed); if(randomMutationChecker<NEUTRALMUTATIONRATE) { geneMutation = gsl_ran_gaussian(r, SIGMAN); dadN = dadN + geneMutation; gsl_rng_default_seed += time(NULL)^(dad); gsl_rng_set (r, gsl_rng_default_seed); } dadS = *(thePop.at(dad).selfingGene + dadChromosome->at(dadChromosome->size()-4)); // add mutation to inherited selfing gene and keep it in [0,1] randomMutationChecker = gsl_ran_flat(r, 0, 1); gsl_rng_default_seed += time(NULL); gsl_rng_set (r, gsl_rng_default_seed); if(randomMutationChecker<SELFINGMUTATIONRATE) { geneMutation = gsl_ran_gaussian(r, SIGMAS); dadS = ((dadS + geneMutation) > 0 ? ((dadS + geneMutation) < 1 ? (dadS + geneMutation) : 1) : 0); gsl_rng_default_seed += time(NULL)^((int)floor(gsl_ran_flat(r, -0.5, 1.4999) + 0.5)+1); gsl_rng_set (r, gsl_rng_default_seed); } dadR = *(thePop.at(dad).recombinationGene + dadChromosome->at(dadChromosome->size()-3)); // add mutations to inherited recombination gene and keep it >0 randomMutationChecker = gsl_ran_flat(r, 0, 1); gsl_rng_default_seed += time(NULL); gsl_rng_set (r, gsl_rng_default_seed); if(randomMutationChecker<RECOMBMUTATIONRATE) { geneMutation = gsl_ran_gaussian(r, SIGMAR); dadR = (dadR + geneMutation)>0 ? (dadR + geneMutation) : 0; gsl_rng_default_seed += time(NULL)^((int)floor(gsl_ran_flat(r, -0.5, 1.4999) + 0.5)+1); gsl_rng_set (r, gsl_rng_default_seed); } // mutation for the immunity alleles are added after a generation is made dadA = *(thePop.at(dad).immunityGeneA + dadChromosome->at(dadChromosome->size()-2)); dadB = *(thePop.at(dad).immunityGeneB + dadChromosome->at(dadChromosome->size()-1)); // removing the last three elements which were just indices of inherited recomb & selfing & neutral genes momChromosome->pop_back(); momChromosome->pop_back(); momChromosome->pop_back(); momChromosome->pop_back(); momChromosome->pop_back(); dadChromosome->pop_back(); dadChromosome->pop_back(); dadChromosome->pop_back(); dadChromosome->pop_back(); dadChromosome->pop_back(); // Add mutations to the chromosomes inherited from parents addMutation(*momChromosome, *dadChromosome, currentRound); // create the child with the given info indiv* theChild = new indiv(*momChromosome, *dadChromosome, momS, dadS, momR, dadR, momN, dadN, momA, dadA, momB, dadB); // use delete because we used new in "makeGamete" method delete momChromosome; delete dadChromosome; // free up the memory taken by the random number generator gsl_rng_free(r); return theChild; }
int main(int argc, const char ** argv) { sm_set_program_name(argv[0]); struct ld_exp_tro1_params p; options_banner(banner); struct option* ops = options_allocate(10); options_double(ops, "max_xy_error", &p.max_xy_error, 10.0, "Maximum error for x,y (m)"); options_double(ops, "max_theta_error_deg", &p.max_theta_error_deg, 10.0, "Maximum error for orientation (deg)"); options_int (ops, "seed", &p.seed, 0, "Seed for random number generator (if 0, use GSL_RNG_SEED env. variable)."); options_int(ops, "num_per_scan", &p.num_per_scan, 10, "Number of trials for each scan."); options_string(ops, "in", &p.file_input, "stdin", "Input file "); options_string(ops, "out1", &p.file_output1, "stdout", "Output file for first scan"); options_string(ops, "out2", &p.file_output2, "stdout", "Output file for second scan"); options_int(ops, "debug", &p.debug, 0, "Shows debug information"); if(!options_parse_args(ops, argc, argv)) { options_print_help(ops, stderr); return -1; } sm_debug_write(p.debug); gsl_rng_env_setup(); gsl_rng * rng = gsl_rng_alloc (gsl_rng_ranlxs0); if(p.seed != 0) gsl_rng_set(rng, (unsigned int) p.seed); /* Open the two output files (possibly the same one) */ FILE * in = open_file_for_reading(p.file_input); if(!in) return -3; FILE * out1 = open_file_for_writing(p.file_output1); if(!out1) return -2; FILE * out2; if(!strcmp(p.file_output1, p.file_output2)) { out1 = out2; } else { out2 = open_file_for_writing(p.file_output2); if(!out2) return -2; } /* Read laser data from input file */ LDP ld; int count=0; while( (ld = ld_read_smart(in))) { count++; if(!ld_valid_fields(ld)) { sm_error("Invalid laser data (#%d in file)\n", count); continue; } for(int n=0; n < p.num_per_scan; n++) { ld->true_pose[0] = 0; ld->true_pose[1] = 0; ld->true_pose[2] = 0; ld->odometry[0] = 0; ld->odometry[1] = 0; ld->odometry[2] = 0; ld_write_as_json(ld, out1); ld->odometry[0] = 2*(gsl_rng_uniform(rng)-0.5) * p.max_xy_error; ld->odometry[1] = 2*(gsl_rng_uniform(rng)-0.5) * p.max_xy_error; ld->odometry[2] = 2*(gsl_rng_uniform(rng)-0.5) * deg2rad(p.max_theta_error_deg); ld_write_as_json(ld, out2); } ld_free(ld); } return 0; }
int generateBinnedData(WIMPpars *W, detector *det, int nbins, int b, int simSeed) { double Er_min, Er_max; const gsl_rng_type * T; gsl_rng * r; gsl_rng_env_setup(); T=gsl_rng_default; r=gsl_rng_alloc(T); gsl_rng_set(r, simSeed + SEED++); //total signal and background, for setting bin size double signal = intWIMPrate( det->ErL, det->ErU, W, det) * det->exposure; double background = b * intBgRate(*det, det->ErL, det->ErU) * det->exposure; det->nbins = nbins; det->binW = ( det->ErU - det->ErL ) / ( (double) det->nbins); try { det->binnedData = new double[det->nbins]; } catch (std::bad_alloc& ba) { std::cerr << "bad_alloc caught: " << ba.what() << std::endl << "you requested: " << det->nbins << " doubles" <<std::endl; return 1; } char filename[100]; std::ofstream datfile; FILE* data; char *ret; char temp[100]; sprintf(filename,"%s_events.dat",det->name); if ( W->asimov == 2 ) data = fopen(filename,"r"); else datfile.open(filename,ios::out); for(int i=0; i<det->nbins; i++) { Er_min = (double)i*det->binW+det->ErL; Er_max = (double)(i+1)*det->binW+det->ErL; background = b * intBgRate(*det, Er_min, Er_max) * det->exposure; signal = intWIMPrate( Er_min, Er_max, W, det) * det->exposure; if ( W->asimov == 2 ) { ret = fgets(temp,100,data); sscanf(temp,"%*lf %*lf %lf",&(det->binnedData[i])); } else if( W->asimov == 1) { det->binnedData[i] = gsl_ran_poisson(r,signal+background); datfile << Er_min << " " << Er_max << " " << det->binnedData[i] << std::endl; } else { det->binnedData[i] = signal + background; datfile << Er_min << " " << Er_max << " " << det->binnedData[i] << std::endl; } det->nEvents += det->binnedData[i]; } datfile.close(); gsl_rng_free(r); return 0; }
/* Calculates a best-fit image transform from image feature correspondences using RANSAC. For more information refer to: Fischler, M. A. and Bolles, R. C. Random sample consensus: a paradigm for model fitting with applications to image analysis and automated cartography. <EM>Communications of the ACM, 24</EM>, 6 (1981), pp. 381--395. @param features an array of features; only features with a non-NULL match of type mtype are used in homography computation @param n number of features in feat @param mtype determines which of each feature's match fields to use for model computation; should be one of FEATURE_FWD_MATCH, FEATURE_BCK_MATCH, or FEATURE_MDL_MATCH; if this is FEATURE_MDL_MATCH, correspondences are assumed to be between a feature's img_pt field and its match's mdl_pt field, otherwise correspondences are assumed to be between the the feature's img_pt field and its match's img_pt field @param xform_fn pointer to the function used to compute the desired transformation from feature correspondences @param m minimum number of correspondences necessary to instantiate the model computed by xform_fn @param p_badxform desired probability that the final transformation returned by RANSAC is corrupted by outliers (i.e. the probability that no samples of all inliers were drawn) @param err_fn pointer to the function used to compute a measure of error between putative correspondences and a computed model @param err_tol correspondences within this distance of a computed model are considered as inliers @param inliers if not NULL, output as an array of pointers to the final set of inliers @param n_in if not NULL and \a inliers is not NULL, output as the final number of inliers @return Returns a transformation matrix computed using RANSAC or NULL on error or if an acceptable transform could not be computed. */ CvMat* ransac_xform( struct feature* features, int n, int mtype, ransac_xform_fn xform_fn, int m, double p_badxform, ransac_err_fn err_fn, double err_tol, struct feature*** inliers, int* n_in ) { struct feature** matched, ** sample, ** consensus, ** consensus_max = NULL; struct ransac_data* rdata; CvPoint2D64f* pts, * mpts; CvMat* M = NULL; gsl_rng* rng; double p, in_frac = RANSAC_INLIER_FRAC_EST; int i, nm, in, in_min, in_max = 0, k = 0; nm = get_matched_features( features, n, mtype, &matched ); if( nm < m ) { fprintf( stderr, "Warning: not enough matches to compute xform, %s" \ " line %d\n", __FILE__, __LINE__ ); goto end; } /* initialize random number generator */ rng = gsl_rng_alloc( gsl_rng_mt19937 ); gsl_rng_set( rng, time(NULL) ); in_min = calc_min_inliers( nm, m, RANSAC_PROB_BAD_SUPP, p_badxform ); p = pow( 1.0 - pow( in_frac, m ), k ); i = 0; while( p > p_badxform ) { sample = draw_ransac_sample( matched, nm, m, rng ); extract_corresp_pts( sample, m, mtype, &pts, &mpts ); M = xform_fn( pts, mpts, m ); if( ! M ) goto iteration_end; in = find_consensus( matched, nm, mtype, M, err_fn, err_tol, &consensus); if( in > in_max ) { if( consensus_max ) free( consensus_max ); consensus_max = consensus; in_max = in; in_frac = (double)in_max / nm; } else free( consensus ); cvReleaseMat( &M ); iteration_end: release_mem( pts, mpts, sample ); p = pow( 1.0 - pow( in_frac, m ), ++k ); } /* calculate final transform based on best consensus set */ if( in_max >= in_min ) { extract_corresp_pts( consensus_max, in_max, mtype, &pts, &mpts ); M = xform_fn( pts, mpts, in_max ); in = find_consensus( matched, nm, mtype, M, err_fn, err_tol, &consensus); cvReleaseMat( &M ); release_mem( pts, mpts, consensus_max ); extract_corresp_pts( consensus, in, mtype, &pts, &mpts ); M = xform_fn( pts, mpts, in ); if( inliers ) { *inliers = consensus; consensus = NULL; } if( n_in ) *n_in = in; release_mem( pts, mpts, consensus ); } else if( consensus_max ) { if( inliers ) *inliers = NULL; if( n_in ) *n_in = 0; free( consensus_max ); } gsl_rng_free( rng ); end: for( i = 0; i < nm; i++ ) { rdata = feat_ransac_data( matched[i] ); matched[i]->feature_data = rdata->orig_feat_data; free( rdata ); } free( matched ); return M; }
void simulation(float mu, float koff){ /*set up variables for RNG, generate seed that's time-dependent, * seed RNG with that value - guarantees that MPI instances will * actually be different from each other*/ const gsl_rng_type * T; gsl_rng_env_setup(); T = gsl_rng_default; gsl_rng *r; r = gsl_rng_alloc (T); unsigned long int seed; seed=gen_seed(); gsl_rng_set(r,seed); /*old legacy stuff //memset(lanes,0,NLANES*L*sizeof(int)); //lanes[8][48]=22; //FILE *fp;*/ /*define total time of simulation (in units of polymerizing events)*/ int totaltime=500; /*define number of ends in the system, necessary for depol * calculation and rates. Also, define a toggle for the first pol * event to reset*/ int ends=0; int newends=0; int first=1; /*just declare a bunch of stuff that we will use*/ float domega,kon; int accepted=0; int filaments,noconsts; int int_i; int j,k,size,currfils,currlen,gap,l,m; float i,p,coverage; int type=0; /*declare two matrices for the filaments per lane, one for the * "permanent" stuff and one for temporary testing in the * Metropolis scheme*/ int lanes[NLANES][L]={{0}}; int newlanes[NLANES][L]={{0}}; /*two floats to store the time of the next polymerization and depol * events, that will be initialized later*/ float nexton=0; float nextoff=VERYBIG; /*declare three GMP arbitrary precision values: one for storing the * current number of microstates, one for the new number when testing * in the Metropolis scheme and one to store the difference*/ mpz_t states; mpz_t newstates; mpz_t deltastates; mpz_init(states); mpz_init(newstates); mpz_init(deltastates); /*sets up: the value of the chemical potential of a monomer, the * on-rate (we're always taking it to be one), the off-rate * (defined in relation to the on-rate) and the average size of * a new polymer*/ kon=1; //float kon=1.0; //float koff=0.1; //try based on ends //printf("%f %f\n",kon,koff); int avg_size=3; p=1.0/avg_size; float inv_sites=1.0/(NLANES*(L-1)); clock_t t1 = clock(); /*sets up the I/O to a file - filename is dependent on MPI * instance number to avoid conflicts*/ char* filename[40]; //int my_rank=0; int my_rank; MPI_Comm_rank(MPI_COMM_WORLD,&my_rank); sprintf(filename,"outputs_%1.1f_%1.1f/run%d.txt",mu,koff,my_rank); FILE *fp = fopen(filename, "w"); //strcat(filename,threadnum); //strcat(filename,".txt"); /*sets up the time for the first on event (first off only calculated * after we have filaments!)*/ nexton=gsl_ran_exponential(r,1.0/kon); //nextoff=gsl_ran_exponential(r,1.0/koff); //printf("nexton=%f nexoff=%f, avg on=%f avg off=%f thread=%d\n",nexton,nextoff,1.0/kon,1.0/koff,omp_get_thread_num()); /*start of the main loop*/ for (i=0;i<totaltime;i=i+0.01){ clock_t t2 = clock(); //printf("thread=%d i=%f\n",omp_get_thread_num(),i); /*before anything else, make a copy of the current lanes into * the matrix newlanes*/ memcpy(newlanes,lanes,sizeof(lanes)); newends=ends; /*calculate the current coverage (sites occupied divided by the * total number of sites) and output to file the current "time" * and coverage*/ coverage=0; for (k=0;k<NLANES;k++){ for (j=1;j<lanes[k][0]+1;j++){ coverage=coverage+lanes[k][j]; } } //printf("total length=%f\n",coverage); coverage=coverage*inv_sites; //printf("coverage=%f\n",coverage); fprintf(fp, "%f %f %f\n", i,coverage,ends,(double)(t2-t1)/CLOCKS_PER_SEC); //printf("%f %f\n",i,coverage); //printf("i=%f nexton=%f nextoff=%f type=%d\n",i,nexton,nextoff,type); /*tests for events, with priority for polymerizing - if both * are due, it will polymerize first and only depol in the next * timestep*/ if (i>=nextoff){ type=2;} if (i>=nexton){ type=1; } /*we will now calculate the number of filaments and constraints * in the system, going over each lane - relatively * straightforward!*/ filaments=0; noconsts=0; for (k=0;k<NLANES;k++){ //printf("according to main, %d filaments in lane %d\n",newlanes[k][0],k); filaments=filaments+newlanes[k][0]; noconsts=noconsts+2*newlanes[k][0]; if (newlanes[k][0]>1){ noconsts=noconsts+newlanes[k][0]; } } /*polymerization event!*/ if (type==1){ /*big legacy stuff - leave it alone!*/ //printf("lanes at beginning: filaments=%d noconsts=%d\n",filaments,noconsts); //for (k=0;k<NLANES;k++){ //printf("lane %d: ",k); //for (j=1;j<lanes[k][0]+1;j++){ //printf("%d ",lanes[k][j]); //} //printf("\n"); //} //if (i>0) count(states,argc, argv, lanes, filaments, noconsts); //gmp_printf("%Zd\n",states); /*sample exponential to get the size of the filament to be * added (integer exponential is geometric!)*/ size=gsl_ran_geometric(r,p); /*pick a lane at random to add the new filament*/ /*parentheses: in the system without stickers, as long as * this step of random sampling doesn't change, we're fine - * order inside lane doesn't really matter!*/ j=gsl_rng_uniform_int(r,NLANES); /*calculate the current number of filaments and occupied * length in the chosen lane*/ currfils=lanes[j][0]; currlen=0; for (k=1;k<currfils+1;k++){ currlen=currlen+lanes[j][k]; } //printf("currlen %d currfils %d\n",currlen,currfils); /*test if there's enough space to insert the new filament*/ if (currlen+currfils+size+2>L) continue; /*if there is, pick a "gap" to insert the filament in * (i.e. the place in the order of filaments of that lane)*/ else{ gap=1+gsl_rng_uniform_int(r,currfils+1); /*if it's not at the end of the order, need to move the other * ones in the lanes matrix to open space for the new one*/ if (gap!=currfils+1){ for (k=currfils;k>gap-1;k--){ newlanes[j][k+1]=newlanes[j][k]; } } /*insert new filament...*/ newlanes[j][gap]=size; /*...and update the number of filaments in the lane*/ newlanes[j][0]++; } /*calculate number of filaments and constraints for the * newlanes matrix - seems like a waste of a for loop, eh?*/ filaments=0; noconsts=0; for (k=0;k<NLANES;k++){ //printf("according to lanes, %d filaments in lane %d\n",newlanes[k][0],k); filaments=filaments+newlanes[k][0]; noconsts=noconsts+2*newlanes[k][0]; if (newlanes[k][0]>1){ noconsts=noconsts+newlanes[k][0]; } } //printf("lanes after adding: filaments=%d noconsts=%d\n",filaments,noconsts); //printf("proposed change:\n"); //for (k=0;k<NLANES;k++){ //printf("lane %d: ",k); //for (j=1;j<newlanes[k][0]+1;j++){ //printf("%d ",newlanes[k][j]); //} //printf("\n"); //} /*count microstates after addition!*/ count_new(&newstates, newlanes, filaments, noconsts); //fprintf(fp,"count="); //value_print(fp, P_VALUE_FMT, newstates); //fprintf(fp,"\n"); //gmp_printf("states=%Zd\n",states); //gmp_printf("newstates=%Zd\n",newstates); /*calculate delta omega for the addition - chemical potential * plus entropy difference - this should always work since we * set states to 0 in the very first iteration*/ domega=-mu*size-mpzln(newstates)+mpzln(states); //printf("delta omega: %f log10newstates=%f log10states=%f\n",domega, mpzln(newstates),mpzln(states)); /*metropolis test - if delta omega is negative, we accept * the addition*/ if (domega<0){ memcpy(lanes,newlanes,sizeof(lanes)); mpz_set(states,newstates); if (size==1){ ends=ends+1; }else if (size>1){ ends=ends+2; } if (first==1){ first=0; nextoff=gsl_ran_exponential(r,1.0/(koff*ends)); }else{ nextoff=i+gsl_ran_exponential(r,1.0/(koff*ends)); } } /*if it's positive, we calculate the probability of acceptance * and test for it*/ else{ double prob=exp(-1.0*domega); double fromthehat=gsl_rng_uniform(r); //printf("metropolising: rng=%f, prob=%f\n",fromthehat,prob); if (fromthehat<prob){ memcpy(lanes,newlanes,sizeof(lanes)); mpz_set(states,newstates); if (size==1){ ends=ends+1; }else if (size>1){ ends=ends+2; } if (first==1){ first=0; nextoff=gsl_ran_exponential(r,1.0/(koff*ends)); }else{ nextoff=i+gsl_ran_exponential(r,1.0/(koff*ends)); } //printf("accepted anyway!\n"); } } //printf("final result:\n"); //for (k=0;k<NLANES;k++){ //printf("lane %d: ",k); //for (j=1;j<lanes[k][0]+1;j++){ //printf("%d ",lanes[k][j]); //} //printf("\n"); //} /*calculate time of next polymerization event and reset type*/ nexton=nexton+gsl_ran_exponential(r,1.0/kon); //printf("nexton: %f\n",nexton); type=0; } /*Depol event! We need to check for number of filaments here * (note that "filaments" here is the one calculated at the * beginning of the for loop) because if there are no filaments * we just need to recalculate nextoff and keep going*/ if (type==2 && filaments>0){ //printf("entered depol\n"); //printf("filaments: %d\n",filaments); /*this is one of those conditions that shouldn't be necessary, * but I needed to add this at some point and now I'm afraid * to take it out and break the whole thing, so there you go*/ if (i>0 && filaments>0 ) { //count(states,argc, argv, lanes, filaments, noconsts); //gmp_printf("%Zd\n",states); /*pick a filament to decrease size - this will be changed * soon!*/ //j=gsl_rng_uniform_int(r,filaments)+1; //printf("j=%d\n",j); j=gsl_rng_uniform_int(r,ends)+1; //fprintf(fp,"j=%d out of %d\n",j,ends); /*need to replicate the routine below, but with more * intelligence to track ends - maybe create small * test program to try it in isolation?*/ /*go through lanes until you find the filament to be * decreased in size. Then, decrease size by one, check * whether the filament disappeared (in which case following * filaments need to be shifted left and number of filaments * in lane decreased). Finally, break from the for loop*/ int end_counter=0; int doneit=0; for (k=0;k<NLANES;k++){ //fprintf(fp,"k=%d nd_counter=%d, lane has %d filaments\n",k,end_counter,lanes[k][0]); for (l=1;l<lanes[k][0]+1;l++){ if (lanes[k][l]==1){ end_counter=end_counter+1; }else{ end_counter=end_counter+2; } if (j<=end_counter){ //fprintf(fp,"filaments=%d k=%d end_counter=%d thing to change=%d\n",filaments,k,end_counter,newlanes[k][l]); newlanes[k][l]=newlanes[k][l]-1; if (newlanes[k][l]==1){ newends=newends-1; } if (newlanes[k][l]==0){ for (m=l;m<newlanes[k][0];m++){ newlanes[k][m]=newlanes[k][m+1]; } newlanes[k][0]--; newends=newends-1; } doneit=1; break; } } if (doneit==1){ break; } } } //printf("nextoff=%f\n",nextoff); type=0; filaments=0; noconsts=0; for (k=0;k<NLANES;k++){ //printf("according to lanes, %d filaments in lane %d\n",newlanes[k][0],k); filaments=filaments+newlanes[k][0]; noconsts=noconsts+2*newlanes[k][0]; if (newlanes[k][0]>1){ noconsts=noconsts+newlanes[k][0]; } } //printf("rank %d is dumping previous lanes:\n",my_rank); //dump_lanes(lanes); //printf("rank %d is dumping its %d filaments and noconsts %d\n",my_rank,filaments,noconsts); //dump_lanes(newlanes); /*metropolis test should go in here*/ count_new(&newstates, newlanes, filaments, noconsts); //<-segfault is here! //fprintf(fp,"count="); //value_print(fp, P_VALUE_FMT, newstates); //fprintf(fp,"\n"); //gmp_printf("states=%Zd\n",states); //gmp_printf("newstates=%Zd\n",newstates); /*calculate delta omega for the addition - chemical potential * plus entropy difference - this should always work since we * set states to 0 in the very first iteration*/ domega=mu-mpzln(newstates)+mpzln(states); //fprintf(fp,"depol domega=%f, diff in mpzln=%f\n",domega,domega-1); if (domega<0){ memcpy(lanes,newlanes,sizeof(lanes)); mpz_set(states,newstates); ends=newends; } /*if it's positive, we calculate the probability of acceptance * and test for it*/ else{ double prob=exp(-1.0*domega); double fromthehat=gsl_rng_uniform(r); //printf("metropolising: rng=%f, prob=%f\n",fromthehat,prob); if (fromthehat<prob){ memcpy(lanes,newlanes,sizeof(lanes)); mpz_set(states,newstates); } } if (ends>0){ /*recalculate nextoff and reset type*/ nextoff=nextoff+gsl_ran_exponential(r,1.0/(koff*ends)); }else{ nextoff=VERYBIG; //first=1; } /*recalculate the number of filaments and constraints (could * be done more efficiently, but whatever)*/ filaments=0; noconsts=0; for (k=0;k<NLANES;k++){ //printf("according to lanes, %d filaments in lane %d\n",newlanes[k][0],k); filaments=filaments+lanes[k][0]; noconsts=noconsts+2*lanes[k][0]; if (lanes[k][0]>1){ noconsts=noconsts+lanes[k][0]; } //printf("before counting: filaments=%d noconsts=%d\n",filaments,noconsts); } /*recalculate total number of states - this will probably be * part of the Metropolis test further up when this is done*/ count_new(&states, lanes, filaments, noconsts); //fprintf(fp,"count="); //value_print(fp, P_VALUE_FMT, states); //fprintf(fp,"\n"); } /*in case there's nothing to depolimerize, we set nextoff as a big * float and reset the first flag*/ if (type==2 && filaments==0){ nextoff=VERYBIG; //first=1; type=0; } /*also, in any situation where there's no filament in the system, * we set states to zero just to be on the safe side*/ if (filaments==0){ mpz_set_si(states,0);} //else{ ////printf("pass/ng to count: %d %d \n",filaments, noconsts); //count_new(&states,lanes, filaments, noconsts);} ////for (k=0;k<NLANES;k++){ //////printf("lane %d: ",k); ////for (j=1;j<lanes[k][0]+1;j++){ //////printf("%d ",lanes[k][j]); ////} ////printf("\n"); //} //printf("%d %d\n",size,j); //printf("%d %f\n",omp_get_thread_num(),coverage); } /*clearing up - deallocating the arbitrary precision stuff, closing * the I/O file and returning!*/ mpz_clear(states); mpz_clear(newstates); mpz_clear(deltastates); gsl_rng_free (r); fclose(fp); return coverage; }
void allocate_rng() { free_rng(); rand_gen = gsl_rng_alloc(gsl_rng_ranlux); gsl_rng_set(rand_gen, time(NULL)); }
void cosmo_init_particles( unsigned seed ) { fftwf_real *data = new fftwf_real[ nres * (nres+2) ]; fftwf_complex *cdata = reinterpret_cast<fftwf_complex*>(data); fftwf_real *data2 = new fftwf_real[ nres * (nres+2) ]; fftwf_complex *cdata2 = reinterpret_cast<fftwf_complex*>(data2); gsl_rng *RNG = gsl_rng_alloc( gsl_rng_mt19937 ); gsl_rng_set( RNG, seed ); fftwf_plan plan, iplan, plan2, iplan2; plan = fftwf_plan_dft_r2c_2d( nres, nres, data, cdata, FFTW_MEASURE ), iplan = fftwf_plan_dft_c2r_2d( nres, nres, cdata, data, FFTW_MEASURE ); plan2 = fftwf_plan_dft_r2c_2d( nres, nres, data2, cdata2, FFTW_MEASURE ), iplan2 = fftwf_plan_dft_c2r_2d( nres, nres, cdata2, data2, FFTW_MEASURE ); ///////////////////////////////// int nresp = nres/2+1; float kfac = 2.0*M_PI/boxlength; float gaussran1, gaussran2; float fftnorm = 1.0f / (float)nres * (2.0f*M_PI/boxlength); for( int i=0; i<nres; ++i ) for( int j=0; j<nres; ++j ) { int idx = i*(nres+2)+j; data[idx] = gsl_ran_ugaussian_ratio_method( RNG ) / nres; } fftwf_execute( plan ); ///////////////////////////////// for( int i=0; i<nres; ++i ) for( int j=0; j<nresp; ++j ) { float kx = i>=nresp? (float)(i-nres)*kfac : (float)i*kfac; float ky = (float)j*kfac; float kk = sqrtf(kx*kx+ky*ky); int idx = i*nresp+j; float ampk = cosmo_get_amp_k( kk ); //*sqrtf(kk); if( kk >= nresp*kfac ) ampk = 0.0; cdata[idx][0] *= ampk * fftnorm; cdata[idx][1] *= ampk * fftnorm; } // insert code to make random numbers independent of resolution (have rectangle outliens) float dx = boxlength / nres; float vfact = ComputeVFact( 1.0f/(1.0f+g_zstart)); ///////////////////////////////// // generate x-component for( int i=0; i<nres; ++i ) for( int j=0; j<nresp; ++j ) { float kx = i>=nresp? (float)(i-nres)*kfac : (float)i*kfac; float ky = (float)j*kfac; float kk = sqrtf(kx*kx+ky*ky); int idx = i*nresp+j; // (a+ib) * ik = iak -bk cdata2[idx][0] = kx/kk/kk * cdata[idx][1]; cdata2[idx][1] = -kx/kk/kk * cdata[idx][0]; } cdata2[0][0] = 0.0f; cdata2[0][1] = 0.0f; fftwf_execute( iplan2 ); for( int i=0; i<nres; ++i ) for( int j=0; j<nres; ++j ) { int idx = i*(nres+2)+j; int ii = i*nres+j; P[ii].x = (float)i*dx + data2[idx]; P[ii].vx = data2[idx] * vfact; P[ii].id = ii; P[ii].acc[0] = 0.0f; } ///////////////////////////////// // generate y-component for( int i=0; i<nres; ++i ) for( int j=0; j<nresp; ++j ) { float kx = i>=nresp? (float)(i-nres)*kfac : (float)i*kfac; float ky = (float)j*kfac; float kk = sqrtf(kx*kx+ky*ky); int idx = i*nresp+j; cdata2[idx][0] = ky/kk/kk * cdata[idx][1]; cdata2[idx][1] = -ky/kk/kk * cdata[idx][0]; } cdata2[0][0] = 0.0f; cdata2[0][1] = 0.0f; fftwf_execute( iplan2 ); for( int i=0; i<nres; ++i ) for( int j=0; j<nres; ++j ) { int idx = i*(nres+2)+j; int ii = i*nres+j; P[ii].y = (float)j*dx + data2[idx]; P[ii].vy = data2[idx] * vfact; P[ii].acc[1] = 0.0f; } ///////////////////////////////// delete[] data; delete[] data2; fftwf_destroy_plan(plan); fftwf_destroy_plan(iplan); fftwf_destroy_plan(plan2); fftwf_destroy_plan(iplan2); gsl_rng_free( RNG ); }
/** main simulation loop */ int main() { // init own parameters. initDerivedParams(); // init random generator gsl_rng_env_setup(); r = gsl_rng_alloc(gsl_rng_default); gsl_rng_set(r, SEED_MAIN); // file handle for xxx file FILE *postF = fopen(FILENAME_POST, FILEPOST_FLAG); // file handle for xxx file FILE *preF = fopen(FILENAME_PRE, "wb"); // set up vectors: // to hold post synaptic potentials [unused??] gsl_vector *psp = gsl_vector_alloc(NPRE); // to hold post synaptic potentials 1st filtered gsl_vector *pspS = gsl_vector_alloc(NPRE); // to hold "excitatory" part of psp for Euler integration gsl_vector *sue = gsl_vector_alloc(NPRE); // to hold "inhibitory" part of psp for Euler integration gsl_vector *sui = gsl_vector_alloc(NPRE); // to hold psp 2nd filter gsl_vector *pspTilde = gsl_vector_alloc(NPRE); // to hold weights gsl_vector *w = gsl_vector_alloc(NPRE); // to hold xxx gsl_vector *pres = gsl_vector_alloc(NPRE); // ?? ou XXX \todo #ifdef PREDICT_OU gsl_vector *ou = gsl_vector_alloc(N_OU); gsl_vector *preU = gsl_vector_calloc(NPRE); gsl_vector *wInput = gsl_vector_alloc(N_OU); gsl_matrix *wPre = gsl_matrix_calloc(NPRE, N_OU); double *preUP = gsl_vector_ptr(preU,0); double *ouP = gsl_vector_ptr(ou,0); double *wInputP = gsl_vector_ptr(wInput,0); double *wPreP = gsl_matrix_ptr(wPre,0,0); #endif // get pointers to array within the gsl_vector data structures above. double *pspP = gsl_vector_ptr(psp,0); double *pspSP = gsl_vector_ptr(pspS,0); double *sueP = gsl_vector_ptr(sue,0); double *suiP = gsl_vector_ptr(sui,0); double *pspTildeP = gsl_vector_ptr(pspTilde,0); double *wP = gsl_vector_ptr(w,0); double *presP = gsl_vector_ptr(pres,0); for(int i=0; i<NPRE; i++) { // init pspP etc to zero *(pspP+i) = 0; *(sueP+i) = 0; *(suiP+i) = 0; #ifdef RANDI_WEIGHTS // Gaussian weights *(wP+i) = gsl_ran_gaussian(r, .1); #else *(wP+i) = 0; #endif } //! OU \todo what for? #ifdef PREDICT_OU for(int j=0; j < N_OU; j++) { *(ouP + j) = gsl_ran_gaussian(r, 1) + M_OU; *(wInputP + j) = gsl_ran_lognormal(r, 0., 2.)/N_OU/exp(2.)/2.; for(int i=0; i < NPRE; i++) *(wPreP + j*NPRE + i) = gsl_ran_lognormal(r, 0., 2.)/N_OU/exp(2.)/2.; } #endif // temp variables for the simulation yyyy double u = 0, // soma potential. uV = 0, // some potential from dendrite only (ie discounted // dendrite potential rU = 0, // instantneou rate rV = 0, // rate on dendritic potential only uI = 0, // soma potential only from somatic inputs rI = 0, // rate on somatic potential only uInput = 0; // for OU? // run simulatio TRAININGCYCLES number of times for( int s = 0; s < TRAININGCYCLES; s++) { // for all TIMEBINS for( int t = 0; t < TIMEBINS; t++) { #ifdef PREDICT_OU for(int i = 0; i < N_OU; i++) { *(ouP+i) = runOU(*(ouP+i), M_OU, GAMMA_OU, S_OU); } gsl_blas_dgemv(CblasNoTrans, 1., wPre, ou, 0., preU); #endif // update PSP of our neurons for inputs from all presynaptic neurons for( int i = 0; i < NPRE; i++) { #ifdef RAMPUPRATE /** just read in the PRE_ACT and generate a spike and store it in presP -- so PRE_ACT has inpretation of potential */ updatePre(sueP+i, suiP+i, pspP + i, pspSP + i, pspTildeP + i, *(presP + i) = spiking(PRE_ACT[t*NPRE + i], gsl_rng_uniform(r))); #elif defined PREDICT_OU //*(ouP+i) = runOU(*(ouP+i), M_OU, GAMMA_OU, S_OU); // why commented out? updatePre(sueP+i, suiP+i, pspP + i, pspSP + i, pspTildeP + i, *(presP + i) = DT * phi(*(preUP+i)));//spiking(DT * phi(*(preUP+i)), gsl_rng_uniform(r))); // why commented out? #else // PRE_ACT intepreated as spikes updatePre(sueP+i, suiP+i, pspP + i, pspSP + i, pspTildeP + i, *(presP + i) = PRE_ACT[t*NPRE + i]); #endif } // endfor NPRE #ifdef PREDICT_OU gsl_blas_ddot(wInput, ou, &uInput); GE[t] = DT * phi(uInput); #endif // now update the membrane potential. updateMembrane(&u, &uV, &uI, w, psp, GE[t], GI[t]); // now calculate rates from from potentials. #ifdef POSTSPIKING // usually switch off as learning is faster when // learning from U // with low-pass filtering of soma potential from actual // generation of spikes (back propgating dentric spikes? rU = GAMMA_POSTS*rU + (1-GAMMA_POSTS)*spiking(DT * phi(u), gsl_rng_uniform(r))/DT; #else // simpler -- direct. rU = phi(u); #endif rV = phi(uV); rI = phi(uI); // now update weights based on rU, RV, the 2nd filtered PSP and // the pspSP for(int i = 0; i < NPRE; i++) { updateWeight(wP + i, rU, *(pspTildeP+i), rV, *(pspSP+i)); } #ifdef TAUEFF /** write rU to postF, but only for the last run of the simulation and then only before the STIM_ONSET time -- ie it is the trained output without somatic drive. */ if(s == TRAININGCYCLES - 1 && t < STIM_ONSET/DT) { fwrite(&rU, sizeof(double), 1, postF); } #else /** for every 10th training cycle write all variables below to postF in order: */ if(s%(TRAININGCYCLES/10)==0) { fwrite(&rU, sizeof(double), 1, postF); fwrite(GE+t, sizeof(double), 1, postF); fwrite(&rV, sizeof(double), 1, postF); fwrite(&rI, sizeof(double), 1, postF); fwrite(&u, sizeof(double), 1, postF); } if(s == TRAININGCYCLES - 1) { #ifdef RECORD_PREACT // for the last cycle also record the activity of the // presynaptic neurons fwrite(PRE_ACT + t * NPRE, sizeof(double), 20, preF); //fwrite(ouP, sizeof(double), 20, preF); fwrite(presP, sizeof(double), 20, preF); #else // and the 1st and 2nd filtered PSP fwrite(pspSP, sizeof(double), 1, preF); fwrite(pspTildeP, sizeof(double), 1, preF); #endif } #endif } } fclose(preF); fclose(postF); return 0; }
void FC_FUNC_(oct_printrecipe, OCT_PRINTRECIPE) (STR_F_TYPE _dir, STR_F_TYPE filename STR_ARG2) { #if defined(HAVE_SCANDIR) && defined(HAVE_ALPHASORT) char *lang, *tmp, dir[512]; struct dirent **namelist; int ii, nn; gsl_rng *rng; /* get language */ lang = getenv("LANG"); if(lang == NULL) lang = "en"; /* convert directory from Fortran to C string */ TO_C_STR1(_dir, tmp); strcpy(dir, tmp); free(tmp); strcat(dir, "/recipes"); /* check out if lang dir exists */ nn = scandir(dir, &namelist, 0, alphasort); if (nn < 0){ printf("Directory does not exist: %s", dir); return; } for(ii=0; ii<nn; ii++) if(strncmp(lang, namelist[ii]->d_name, 2) == 0){ strcat(dir, "/"); strcat(dir, namelist[ii]->d_name); break; } if(ii == nn) strcat(dir, "/en"); /* default */ /* clean up */ for(ii=0; ii<nn; ii++) free(namelist[ii]); free(namelist); /* now we read the recipes */ nn = scandir(dir, &namelist, 0, alphasort); /* initialize random numbers */ gsl_rng_env_setup(); rng = gsl_rng_alloc(gsl_rng_default); gsl_rng_set(rng, random_seed()); ii = gsl_rng_uniform_int(rng, nn - 2); gsl_rng_free(rng); strcat(dir, "/"); strcat(dir, namelist[ii+2]->d_name); /* skip ./ and ../ */ /* clean up again */ for(ii=0; ii<nn; ii++) free(namelist[ii]); free(namelist); TO_F_STR2(dir, filename); #else printf("Sorry, recipes cannot be printed unless scandir and alphasort are available with your C compiler.\n"); #endif }
/** * Function to open and perform a optimization. */ void optimize_open () { GTimeZone *tz; GDateTime *t0, *t; unsigned int i, j; #if DEBUG_OPTIMIZE char *buffer; fprintf (stderr, "optimize_open: start\n"); #endif // Getting initial time #if DEBUG_OPTIMIZE fprintf (stderr, "optimize_open: getting initial time\n"); #endif tz = g_time_zone_new_utc (); t0 = g_date_time_new_now (tz); // Obtaining and initing the pseudo-random numbers generator seed #if DEBUG_OPTIMIZE fprintf (stderr, "optimize_open: getting initial seed\n"); #endif if (optimize->seed == DEFAULT_RANDOM_SEED) optimize->seed = input->seed; gsl_rng_set (optimize->rng, optimize->seed); // Replacing the working directory #if DEBUG_OPTIMIZE fprintf (stderr, "optimize_open: replacing the working directory\n"); #endif g_chdir (input->directory); // Getting results file names optimize->result = input->result; optimize->variables = input->variables; // Obtaining the simulator file optimize->simulator = input->simulator; // Obtaining the evaluator file optimize->evaluator = input->evaluator; // Reading the algorithm optimize->algorithm = input->algorithm; switch (optimize->algorithm) { case ALGORITHM_MONTE_CARLO: optimize_algorithm = optimize_MonteCarlo; break; case ALGORITHM_SWEEP: optimize_algorithm = optimize_sweep; break; case ALGORITHM_ORTHOGONAL: optimize_algorithm = optimize_orthogonal; break; default: optimize_algorithm = optimize_genetic; optimize->mutation_ratio = input->mutation_ratio; optimize->reproduction_ratio = input->reproduction_ratio; optimize->adaptation_ratio = input->adaptation_ratio; } optimize->nvariables = input->nvariables; optimize->nsimulations = input->nsimulations; optimize->niterations = input->niterations; optimize->nbest = input->nbest; optimize->tolerance = input->tolerance; optimize->nsteps = input->nsteps; optimize->nestimates = 0; optimize->threshold = input->threshold; optimize->stop = 0; if (input->nsteps) { optimize->relaxation = input->relaxation; switch (input->climbing) { case CLIMBING_METHOD_COORDINATES: optimize->nestimates = 2 * optimize->nvariables; optimize_estimate_climbing = optimize_estimate_climbing_coordinates; break; default: optimize->nestimates = input->nestimates; optimize_estimate_climbing = optimize_estimate_climbing_random; } } #if DEBUG_OPTIMIZE fprintf (stderr, "optimize_open: nbest=%u\n", optimize->nbest); #endif optimize->simulation_best = (unsigned int *) alloca (optimize->nbest * sizeof (unsigned int)); optimize->error_best = (double *) alloca (optimize->nbest * sizeof (double)); // Reading the experimental data #if DEBUG_OPTIMIZE buffer = g_get_current_dir (); fprintf (stderr, "optimize_open: current directory=%s\n", buffer); g_free (buffer); #endif optimize->nexperiments = input->nexperiments; optimize->ninputs = input->experiment->ninputs; optimize->experiment = (char **) alloca (input->nexperiments * sizeof (char *)); optimize->weight = (double *) alloca (input->nexperiments * sizeof (double)); for (i = 0; i < input->experiment->ninputs; ++i) optimize->file[i] = (GMappedFile **) g_malloc (input->nexperiments * sizeof (GMappedFile *)); for (i = 0; i < input->nexperiments; ++i) { #if DEBUG_OPTIMIZE fprintf (stderr, "optimize_open: i=%u\n", i); #endif optimize->experiment[i] = input->experiment[i].name; optimize->weight[i] = input->experiment[i].weight; #if DEBUG_OPTIMIZE fprintf (stderr, "optimize_open: experiment=%s weight=%lg\n", optimize->experiment[i], optimize->weight[i]); #endif for (j = 0; j < input->experiment->ninputs; ++j) { #if DEBUG_OPTIMIZE fprintf (stderr, "optimize_open: stencil%u\n", j + 1); #endif optimize->file[j][i] = g_mapped_file_new (input->experiment[i].stencil[j], 0, NULL); } } // Reading the variables data #if DEBUG_OPTIMIZE fprintf (stderr, "optimize_open: reading variables\n"); #endif optimize->label = (char **) alloca (input->nvariables * sizeof (char *)); j = input->nvariables * sizeof (double); optimize->rangemin = (double *) alloca (j); optimize->rangeminabs = (double *) alloca (j); optimize->rangemax = (double *) alloca (j); optimize->rangemaxabs = (double *) alloca (j); optimize->step = (double *) alloca (j); j = input->nvariables * sizeof (unsigned int); optimize->precision = (unsigned int *) alloca (j); optimize->nsweeps = (unsigned int *) alloca (j); optimize->nbits = (unsigned int *) alloca (j); for (i = 0; i < input->nvariables; ++i) { optimize->label[i] = input->variable[i].name; optimize->rangemin[i] = input->variable[i].rangemin; optimize->rangeminabs[i] = input->variable[i].rangeminabs; optimize->rangemax[i] = input->variable[i].rangemax; optimize->rangemaxabs[i] = input->variable[i].rangemaxabs; optimize->precision[i] = input->variable[i].precision; optimize->step[i] = input->variable[i].step; optimize->nsweeps[i] = input->variable[i].nsweeps; optimize->nbits[i] = input->variable[i].nbits; } if (input->algorithm == ALGORITHM_SWEEP || input->algorithm == ALGORITHM_ORTHOGONAL) { optimize->nsimulations = 1; for (i = 0; i < input->nvariables; ++i) { optimize->nsimulations *= optimize->nsweeps[i]; #if DEBUG_OPTIMIZE fprintf (stderr, "optimize_open: nsweeps=%u nsimulations=%u\n", optimize->nsweeps[i], optimize->nsimulations); #endif } } if (optimize->nsteps) optimize->climbing = (double *) alloca (optimize->nvariables * sizeof (double)); // Setting error norm switch (input->norm) { case ERROR_NORM_EUCLIDIAN: optimize_norm = optimize_norm_euclidian; break; case ERROR_NORM_MAXIMUM: optimize_norm = optimize_norm_maximum; break; case ERROR_NORM_P: optimize_norm = optimize_norm_p; optimize->p = input->p; break; default: optimize_norm = optimize_norm_taxicab; } // Allocating values #if DEBUG_OPTIMIZE fprintf (stderr, "optimize_open: allocating variables\n"); fprintf (stderr, "optimize_open: nvariables=%u algorithm=%u\n", optimize->nvariables, optimize->algorithm); #endif optimize->genetic_variable = NULL; if (optimize->algorithm == ALGORITHM_GENETIC) { optimize->genetic_variable = (GeneticVariable *) g_malloc (optimize->nvariables * sizeof (GeneticVariable)); for (i = 0; i < optimize->nvariables; ++i) { #if DEBUG_OPTIMIZE fprintf (stderr, "optimize_open: i=%u min=%lg max=%lg nbits=%u\n", i, optimize->rangemin[i], optimize->rangemax[i], optimize->nbits[i]); #endif optimize->genetic_variable[i].minimum = optimize->rangemin[i]; optimize->genetic_variable[i].maximum = optimize->rangemax[i]; optimize->genetic_variable[i].nbits = optimize->nbits[i]; } } #if DEBUG_OPTIMIZE fprintf (stderr, "optimize_open: nvariables=%u nsimulations=%u\n", optimize->nvariables, optimize->nsimulations); #endif optimize->value = (double *) g_malloc ((optimize->nsimulations + optimize->nestimates * optimize->nsteps) * optimize->nvariables * sizeof (double)); // Calculating simulations to perform for each task #if HAVE_MPI #if DEBUG_OPTIMIZE fprintf (stderr, "optimize_open: rank=%u ntasks=%u\n", optimize->mpi_rank, ntasks); #endif optimize->nstart = optimize->mpi_rank * optimize->nsimulations / ntasks; optimize->nend = (1 + optimize->mpi_rank) * optimize->nsimulations / ntasks; if (optimize->nsteps) { optimize->nstart_climbing = optimize->mpi_rank * optimize->nestimates / ntasks; optimize->nend_climbing = (1 + optimize->mpi_rank) * optimize->nestimates / ntasks; } #else optimize->nstart = 0; optimize->nend = optimize->nsimulations; if (optimize->nsteps) { optimize->nstart_climbing = 0; optimize->nend_climbing = optimize->nestimates; } #endif #if DEBUG_OPTIMIZE fprintf (stderr, "optimize_open: nstart=%u nend=%u\n", optimize->nstart, optimize->nend); #endif // Calculating simulations to perform for each thread optimize->thread = (unsigned int *) alloca ((1 + nthreads) * sizeof (unsigned int)); for (i = 0; i <= nthreads; ++i) { optimize->thread[i] = optimize->nstart + i * (optimize->nend - optimize->nstart) / nthreads; #if DEBUG_OPTIMIZE fprintf (stderr, "optimize_open: i=%u thread=%u\n", i, optimize->thread[i]); #endif } if (optimize->nsteps) optimize->thread_climbing = (unsigned int *) alloca ((1 + nthreads_climbing) * sizeof (unsigned int)); // Opening result files optimize->file_result = g_fopen (optimize->result, "w"); optimize->file_variables = g_fopen (optimize->variables, "w"); // Performing the algorithm switch (optimize->algorithm) { // Genetic algorithm case ALGORITHM_GENETIC: optimize_genetic (); break; // Iterative algorithm default: optimize_iterate (); } // Getting calculation time t = g_date_time_new_now (tz); optimize->calculation_time = 0.000001 * g_date_time_difference (t, t0); g_date_time_unref (t); g_date_time_unref (t0); g_time_zone_unref (tz); printf ("%s = %.6lg s\n", _("Calculation time"), optimize->calculation_time); fprintf (optimize->file_result, "%s = %.6lg s\n", _("Calculation time"), optimize->calculation_time); // Closing result files fclose (optimize->file_variables); fclose (optimize->file_result); #if DEBUG_OPTIMIZE fprintf (stderr, "optimize_open: end\n"); #endif }
int main(int argc, char **argv) { unsigned int i,j,m,n; /* variables to iterate over */ int iter_num = 0; /* * To avoid the memory limitation, here we use a LOW_NI and UP_NI to get enough iteration times. * The total iteration times should be LOW_NI*UP_NI. */ unsigned long LOW_NI = 10000; /* lower iteration times for each scatterer*/ unsigned long UP_NI = 20000; /*Upper iteration times for each scatterer*/ camera_t cam = {0.20,0.20,512,512}; /* initialize the cam struct*/ field_t field; /* seed the scatterers */ scatterer_t *scatts = NULL; scatts = malloc(NSCAT*sizeof(scatterer_t)); check_mem(scatts); /* the locations */ scatterer_t location; /* the radiation counting for NSCATS */ int *visiting_array = NULL; visiting_array = calloc(NSCAT,sizeof(int)); check_mem(visiting_array); double *distance_array = NULL; distance_array = calloc(UP_NI*LOW_NI,sizeof(double)); check_mem(distance_array); complex double *ccd_all = NULL; ccd_all = calloc(cam.cam_sx*cam.cam_sy,sizeof(complex double)); check_mem(ccd_all); /* check memory, should probably */ //long page_size = sysconf(_SC_PAGE_SIZE); //long pages_avail = sysconf(_SC_AVPHYS_PAGES); //long pages_tot = sysconf(_SC_PHYS_PAGES); //if(pages_tot*page_size<8*cam.cam_sx*cam.cam_sy*2*sizeof(complex double)){ // error("Size of output arrays exceed avaliable memory."); //} unsigned long *gaussian_beam = calloc(NSCAT,sizeof(unsigned long)); check_mem(gaussian_beam); /* To read the scatterers positions from the file into the scatterer array*/ char filename[FILENAME_MAX]; bzero(filename,FILENAME_MAX*sizeof(char)); sprintf(filename,"%s","Scatterers.txt"); log_info("Reading from %s.",filename); /* use tsvread to get list of scatterers */ tsv_t *tsv = tsv_fread(filename); for(i=0;i<NSCAT;++i){ memcpy(scatts,*tsv->data,sizeof(scatterer_t)); tsv->data++; scatts++; } tsv->data-=i; scatts-=i; tsv_free(tsv); index_bounds **Matrix = NULL; Matrix = (index_bounds**)malloc(NSCAT*sizeof(index_bounds*)); check_mem(Matrix); for(i=0;i<NSCAT;++i){ Matrix[i] = (index_bounds*)malloc(NSCAT*sizeof(index_bounds)); check_mem(Matrix[i]); conduc_matrix(NSCAT, scatts, i, Matrix[i]); } log_info("Conductance matrix finished"); /* initialize the random number generator */ int rseed = (int)time(NULL); const gsl_rng_type *T; gsl_rng *r; gsl_rng_env_setup(); T = gsl_rng_default; r = gsl_rng_alloc(T); srand(rseed); gsl_rng_set(r,rseed); int gaussian_sum = 0; j = 0; n = 1; gaussian_profile_creator(scatts,waist, UP_NI*LOW_NI,NSCAT,gaussian_beam); for (m = 0; m < UP_NI; ++m) { for (i = 0; i < LOW_NI; ++i) { if (gaussian_sum < gaussian_beam[j]) { ++gaussian_sum; if((m*UP_NI+i+1)%100==0) { ++iter_num; } field = single_field_spp(j, scatts, NSCAT,r,Matrix[j],iter_num, distance_array); ++visiting_array[field.scatterer_index]; location = fst_transfer(field,z0,scatts[field.scatterer_index]); field_on_ccd(z0,location,scatts[field.scatterer_index],field,cam,ccd_all); } else { ++j; gaussian_sum = 0; if (j == (int)(0.1*n*NSCAT)) { log_info("Process %d0 percent done.",n); ++n; } } } } log_info("iter_num is %d", iter_num); log_info("Field generated."); bzero(filename,FILENAME_MAX*sizeof(char)); sprintf(filename,"%s","distance_1000.txt"); FILE *fp_dis = fopen(filename,"w"); check(fp_dis, "Failed to open %s for writing.", filename); log_info("Writing to %s.",filename); for (i = 0; i < iter_num; ++i) { fprintf(fp_dis,"%-12.12f\n",distance_array[i]); } fclose(fp_dis); double *tmp = NULL; tmp = malloc(cam.cam_sx*cam.cam_sy*sizeof(double)); check_mem(tmp); /* normalize tmp, first by finding max */ double max = 0; for(i=0;i<cam.cam_sx*cam.cam_sy;++i){ tmp[i]=cabs(ccd_all[i])*cabs(ccd_all[i]); if(tmp[i]>max){ max=tmp[i]; } } /* then dividing by max */ for(i=0;i<cam.cam_sx*cam.cam_sy;++i){ tmp[i]/=max; //printf("%d",tmp[i]); } /** * Write the tmp array as a way to do the * cross-correlation function. */ bzero(filename,FILENAME_MAX*sizeof(char)); sprintf(filename,"%s","tmp.txt"); FILE *fp_tmp = fopen(filename,"w"); check(fp_tmp, "Failed to open %s for writing.", filename); log_info("Writing to %s.",filename); for (i = 0; i < cam.cam_sx*cam.cam_sy; ++i) { fprintf(fp_tmp,"%-12.12f\n",tmp[i]); } fclose(fp_tmp); /* output file */ hid_t file,dataset,dataspace; herr_t status = 0; hsize_t dims[2]; /* dimensionality of the set */ dims[0]=cam.cam_sx; dims[1]=cam.cam_sy; dataspace = H5Screate_simple(2,dims,NULL); bzero(filename,FILENAME_MAX*sizeof(char)); sprintf(filename,"%s","out_s300_w50_5000_10000_20n.h5"); file = H5Fcreate(filename,H5F_ACC_TRUNC,H5P_DEFAULT,H5P_DEFAULT); dataset = H5Dcreate1(file,"/e2",H5T_NATIVE_DOUBLE,dataspace,H5P_DEFAULT); log_info("Writing to HDF5 file %s.",filename); status = H5Dwrite(dataset, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, tmp); check(status>=0,"Can't write dataset /e2 to %s",filename); /* write the real and imaginary parts as well */ dataset = H5Dcreate1(file,"/er",H5T_NATIVE_DOUBLE,dataspace,H5P_DEFAULT); for(i=0;i<cam.cam_sx*cam.cam_sy;++i){ tmp[i]=creal(ccd_all[i]); } status = H5Dwrite(dataset, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, tmp); check(status>=0,"Can't write dataset /er to %s",filename); dataset = H5Dcreate1(file,"/ei",H5T_NATIVE_DOUBLE,dataspace,H5P_DEFAULT); for(i=0;i<cam.cam_sx*cam.cam_sy;++i){ tmp[i]=cimag(ccd_all[i]); } status = H5Dwrite(dataset, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, tmp); check(status>=0,"Can't write dataset /ei to %s",filename); /* clean up */ log_info("Cleaning up."); free(tmp); status = H5Dclose(dataset); status = H5Sclose(dataspace); status = H5Fclose(file); gsl_rng_free(r); free(scatts); //free(free_path); free(visiting_array); free(ccd_all); for(i=0;i<NSCAT;++i){ free(Matrix[i]); } free(Matrix); log_info("Program finished."); return 0; error: return 1; }
void studyPop::makeIndiv(int currentGen, int currentRound) { int mom, dad; vector<int> *momChromosome, *dadChromosome; // variables to save R,S,N, immuneA & immuneB alleles inherited from parents double momS, momR, dadS, dadR, momN, dadN; int momA, momB, dadA, dadB; // MH: Variable to determine if gamete is asexually-produced int isasex = 0; // pick the mom for the new indiv mom = pickAMom(); // check if the mom selfs or outcrosses MH OR ASEXUAL const gsl_rng_type * T; gsl_rng * r; // Initialize the random number generator T = gsl_rng_default; r = gsl_rng_alloc (T); gsl_rng_default_seed += time(NULL)^mom; gsl_rng_set (r, gsl_rng_default_seed); double outCrossCheck = gsl_ran_flat(r, 0, 1); double AsexCheck = gsl_ran_flat(r, 0, 1); /* printf("\n"); printf("Asex Check is %f\n",AsexCheck); */ if(AsexCheck < ASEXP) { // In this case, offspring is clonal dad = mom; isasex = 1; } else { if(outCrossCheck > thePop.at(mom).calcSelfingRate()) { // in this case mom would outcross dad = pickADad(mom); } else { // in this case mom will self dad = mom; } } /* printf("IsAsex is %d\n",isasex); printf("Dad is %d, Mom is %d\n",dad,mom); */ // Get the chromosomes from mom and dad // The last five elements are not mutations (check makeHamete function in individual.cpp to find out) /* printf("Creating Mom chromosome\n"); */ momChromosome = thePop.at(mom).makeGamete(this->meanRecombination,isasex,0); /* printf("Creating Dad chromosome\n"); */ dadChromosome = thePop.at(dad).makeGamete(this->meanRecombination,isasex,1); // renew the seed gsl_rng_default_seed += time(NULL)*(momChromosome->size() + dadChromosome->size()); gsl_rng_set (r, gsl_rng_default_seed); // A variable to store the mutation amount of Selfing, recomb and neutral genes double geneMutation; momN = *(thePop.at(mom).neutralGene + momChromosome->at(momChromosome->size()-5)); // After mutation check, add mutation to inherited neutral gene double randomMutationChecker; randomMutationChecker = gsl_ran_flat(r, 0, 1); gsl_rng_default_seed += time(NULL); gsl_rng_set (r, gsl_rng_default_seed); if(randomMutationChecker<NEUTRALMUTATIONRATE) { geneMutation = gsl_ran_gaussian(r, SIGMAN); momN = momN + geneMutation; gsl_rng_default_seed += time(NULL)^(mom); gsl_rng_set (r, gsl_rng_default_seed); } momS = *(thePop.at(mom).selfingGene + momChromosome->at(momChromosome->size()-4)); // After mutation check, add mutation to inherited selfing gene and keep it in [0,1] // MH: I've altered this to remove the dependence on time, so no selfing arises if not defined randomMutationChecker = gsl_ran_flat(r, 0, 1); /*if(currentGen <= 2000) randomMutationChecker = 1;*/ gsl_rng_default_seed += time(NULL); gsl_rng_set (r, gsl_rng_default_seed); if(randomMutationChecker<SELFINGMUTATIONRATE) { geneMutation = gsl_ran_gaussian(r, SIGMAS); momS = ((momS + geneMutation) > 0 ? ((momS + geneMutation) < 1 ? (momS + geneMutation) : 1) : 0); gsl_rng_default_seed += time(NULL)^((int)floor(gsl_ran_flat(r, -0.5, 1.4999) + 0.5)+1); gsl_rng_set (r, gsl_rng_default_seed); } momR = *(thePop.at(mom).recombinationGene + momChromosome->at(momChromosome->size()-3)); // After mutation check, add mutations to inherited recombination gene and keep it >0 randomMutationChecker = gsl_ran_flat(r, 0, 1); gsl_rng_default_seed += time(NULL); gsl_rng_set (r, gsl_rng_default_seed); if(randomMutationChecker<RECOMBMUTATIONRATE) { geneMutation = gsl_ran_gaussian(r, SIGMAR); momR = (momR + geneMutation)>0 ? (momR + geneMutation) : 0; gsl_rng_default_seed += time(NULL)^((int)floor(gsl_ran_flat(r, -0.5, 1.4999) + 0.5)+1); gsl_rng_set (r, gsl_rng_default_seed); } // mutation is not added here, it is added after a generation is made momA = *(thePop.at(mom).immunityGeneA + momChromosome->at(momChromosome->size()-2)); momB = *(thePop.at(mom).immunityGeneB + momChromosome->at(momChromosome->size()-1)); dadN = *(thePop.at(dad).neutralGene + dadChromosome->at(dadChromosome->size()-5)); // After mutation check, add mutation to inherited neutral gene randomMutationChecker = gsl_ran_flat(r, 0, 1); gsl_rng_default_seed += time(NULL); gsl_rng_set (r, gsl_rng_default_seed); if(randomMutationChecker<NEUTRALMUTATIONRATE) { geneMutation = gsl_ran_gaussian(r, SIGMAN); dadN = dadN + geneMutation; gsl_rng_default_seed += time(NULL)^(dad); gsl_rng_set (r, gsl_rng_default_seed); } dadS = *(thePop.at(dad).selfingGene + dadChromosome->at(dadChromosome->size()-4)); // add mutation to inherited selfing gene and keep it in [0,1] // MH: I've altered this to remove the dependence on time, so no selfing arises if not defined randomMutationChecker = gsl_ran_flat(r, 0, 1); gsl_rng_default_seed += time(NULL); gsl_rng_set (r, gsl_rng_default_seed); if(randomMutationChecker<SELFINGMUTATIONRATE) { geneMutation = gsl_ran_gaussian(r,SIGMAS); dadS = ((dadS + geneMutation) > 0 ? ((dadS + geneMutation) < 1 ? (dadS + geneMutation) : 1) : 0); gsl_rng_default_seed += time(NULL)^((int)floor(gsl_ran_flat(r, -0.5, 1.4999) + 0.5)+1); gsl_rng_set (r, gsl_rng_default_seed); } dadR = *(thePop.at(dad).recombinationGene + dadChromosome->at(dadChromosome->size()-3)); // add mutations to inherited recombination gene and keep it >0 randomMutationChecker = gsl_ran_flat(r, 0, 1); gsl_rng_default_seed += time(NULL); gsl_rng_set (r, gsl_rng_default_seed); if(randomMutationChecker<RECOMBMUTATIONRATE) { geneMutation = gsl_ran_gaussian(r, SIGMAR); dadR = (dadR + geneMutation)>0 ? (dadR + geneMutation) : 0; gsl_rng_default_seed += time(NULL)^((int)floor(gsl_ran_flat(r, -0.5, 1.4999) + 0.5)+1); gsl_rng_set (r, gsl_rng_default_seed); } // mutation for these alleles are added after a generation is made dadA = *(thePop.at(dad).immunityGeneA + dadChromosome->at(dadChromosome->size()-2)); dadB = *(thePop.at(dad).immunityGeneB + dadChromosome->at(dadChromosome->size()-1)); // removing the last five elements which were just indices of inherited R,S,N,immuneA,immuneB momChromosome->pop_back(); momChromosome->pop_back(); momChromosome->pop_back(); momChromosome->pop_back(); momChromosome->pop_back(); dadChromosome->pop_back(); dadChromosome->pop_back(); dadChromosome->pop_back(); dadChromosome->pop_back(); dadChromosome->pop_back(); // Add deleterious and beneficial mutations to the chromosomes inherited from parents addMutation(*momChromosome, *dadChromosome, currentRound); // create the new indiv with the given info indiv theChild(*momChromosome, *dadChromosome, momS, dadS, momR, dadR, momN, dadN, momA, dadA, momB, dadB); tempHostFreq[(int)((theChild.immunityGeneA[0]+theChild.immunityGeneA[1])*3 + theChild.immunityGeneB[0]+theChild.immunityGeneB[1])] += 1; // save whether this child is a result of selfing or outcrossing // these values will later be used to calculate inbreeding dep if "EXPERIMENTAL_INBREEDING_DEP" is zero // NOTE: in our simulations "EXPERIMENTAL_INBREEDING_DEP" was 1 if(mom == dad && isasex == 0) { selfedChildren[0] += 1.0; selfedChildren[1] += theChild.get_fitness(); } else { outcrossedChildren[0] += 1.0; outcrossedChildren[1] += theChild.get_fitness(); } newMeanRecombination += momR + dadR; // use delete because we used new in "makeGamete" method delete momChromosome; delete dadChromosome; newGen.push_back(theChild); // free up the space taken by the random number generator gsl_rng_free(r); // one indiv was added to the new population (new generation) population++; }
/////////////////////////////////////////// // The simulation // /////////////////////////////////////////// void *sim(void *parameters) { const Params P = *((Params*)parameters); const int k_gen = P.k_gen; const int kernel = P.kernel; const int communities = P.communities; const int j_per_c = P.j_per_c; const int init_species = P.init_species; const int init_pop_size = j_per_c / init_species; const double mu = P.mu; const double s = P.s; const double eta = P.eta; const double width = P.width; const double width2 = width * width; const double sigma = P.var; const double sigma2 = sigma * sigma; // GSL's Taus generator: gsl_rng *rng = gsl_rng_alloc(gsl_rng_taus2); // Initialize the GSL generator with /dev/urandom: const unsigned int seed = devurandom_get_uint(); gsl_rng_set(rng, seed); // Seed with time printf(" <seed>%u</seed>\n", seed); // Used to name the output file: char *buffer = (char*)malloc(100); // Nme of the file: sprintf(buffer, "%s%u.xml", P.ofilename, seed); // Open the output file: FILE *restrict out = fopen(buffer, "w"); // Store the total num. of species/1000 generations: int *restrict total_species = (int*)malloc(k_gen * sizeof(int)); // Number of speciation events/1000 generations: int *restrict speciation_events = (int*)malloc(k_gen * sizeof(int)); // Number of extinctions/1000 generations: int *restrict extinction_events = (int*)malloc(k_gen * sizeof(int)); // Number of speciation events/vertex: int *restrict speciation_per_c = (int*)malloc(communities * sizeof(int)); // Number of local extinction events/vertex: int *restrict extinction_per_c = (int*)malloc(communities * sizeof(int)); // Store the lifespan of the extinct species: ivector lifespan; ivector_init0(&lifespan); // Store the population size at speciation event: ivector pop_size; ivector_init0(&pop_size); // (x, y) coordinates for the spatial graph: double *restrict x = (double*)malloc(communities * sizeof(double)); double *restrict y = (double*)malloc(communities * sizeof(double)); for (int i = 0; i < communities; ++i) { speciation_per_c[i] = 0; extinction_per_c[i] = 0; } // Initialize an empty list of species: species_list *restrict list = species_list_init(); // Initialize the metacommunity and fill them with the initial species evenly: for (int i = 0; i < init_species; ++i) { // Intialize the species and add it to the list: species_list_add(list, species_init(communities, 0, 3)); } // To iterate the list; slnode *it = list->head; // Fill the communities: while (it != NULL) { for (int i = 0; i < communities; ++i) { it->sp->n[i] = init_pop_size; it->sp->genotypes[0][i] = init_pop_size; } it = it->next; } // To iterate the list; const int remainder = j_per_c - (init_species * init_pop_size); for (int i = 0; i < communities; ++i) { it = list->head; for (int j = 0; j < remainder; ++j, it = it->next) { ++(it->sp->n[i]); ++(it->sp->genotypes[0][i]); } } int sum = 0; it = list->head; while (it != NULL) { sum += species_total(it->sp); it = it->next; } assert(sum == j_per_c * communities); #ifdef NOTTOOCLOSE { int count_c = 0; while (count_c < communities) { bool within = false; const double xx = gsl_rng_uniform(rng); const double yy = gsl_rng_uniform(rng); for (int i = 0; i < count_c; ++i) { if (hypot(x[i] - xx, y[i] - yy) < MINDIST) { within = true; // oh nooo, an evil goto! break; } } if (within == false) { x[count_c] = xx; y[count_c] = yy; ++count_c; } } } #else for (int i = 0; i < communities; ++i) { x[i] = gsl_rng_uniform(rng); y[i] = gsl_rng_uniform(rng); } #endif double **m = (double**)malloc(communities * sizeof(double*)); for (int i = 0; i < communities; ++i) { m[i] = (double*)malloc(communities * sizeof(double)); } for (int i = 0; i < communities; ++i) { for (int j = 0; j < communities; ++j) { const double a = x[i] - x[j]; const double b = y[i] - y[j]; const double x = hypot(a, b); assert(distance >= 0.0); if (kernel == gaussian_k) { m[i][j] = (1.0 / sqrt(2 * M_PI * sigma2)) * exp((-x * x) / (2 * sigma2)); } else { m[i][j] = -(eta + 2)/(2 * M_PI * width2) * pow(1 + (x * x) / width2, eta / 2); } } } // Setup the array for migration: double **cmig = setup_cmig(m, communities); fprintf(out, "<?xml version=\"1.0\"?>\n"); fprintf(out, "<simulation>\n"); if (kernel == gaussian_k) { fprintf(out, " <model>Gaussian</model>\n"); } else { fprintf(out, " <model>Fat-tailed</model>\n"); } fprintf(out, " <seed>%u</seed>\n", seed); fprintf(out, " <metacom_size>%d</metacom_size>\n", j_per_c * communities); fprintf(out, " <k_gen>%d</k_gen>\n", k_gen); fprintf(out, " <num_comm>%d</num_comm>\n", communities); fprintf(out, " <individuals_per_comm>%d</individuals_per_comm>\n", j_per_c); fprintf(out, " <initial_num_species>%d</initial_num_species>\n", init_species); fprintf(out, " <mutation_rate>%.2e</mutation_rate>\n", mu); if (kernel == gaussian_k) { fprintf(out, " <variance>%.8e</variance>\n", sigma); } else { fprintf(out, " <width>%.8e</width>\n", width); fprintf(out, " <eta>%.8e</eta>\n", eta); } // To select the species and genotypes to pick and replace: slnode *s0 = list->head; // species0 slnode *s1 = list->head; // species1 int g0 = 0; int g1 = 0; int v1 = 0; // Vertex of the individual 1 ///////////////////////////////////////////// // Groups of 1 000 generations // ///////////////////////////////////////////// for (int k = 0; k < k_gen; ++k) { extinction_events[k] = 0; speciation_events[k] = 0; ///////////////////////////////////////////// // 1 000 generations // ///////////////////////////////////////////// for (int gen = 0; gen < 1000; ++gen) { const int current_date = (k * 1000) + gen; ///////////////////////////////////////////// // A single generation // ///////////////////////////////////////////// for (int t = 0; t < j_per_c; ++t) { ///////////////////////////////////////////// // A single time step (for each community) // ///////////////////////////////////////////// for (int c = 0; c < communities; ++c) { // Select the species and genotype of the individual to be replaced int position = (int)(gsl_rng_uniform(rng) * j_per_c); s0 = list->head; int index = s0->sp->n[c]; while (index <= position) { s0 = s0->next; index += s0->sp->n[c]; } position = (int)(gsl_rng_uniform(rng) * s0->sp->n[c]); if (position < s0->sp->genotypes[0][c]) { g0 = 0; } else if (position < (s0->sp->genotypes[0][c] + s0->sp->genotypes[1][c])) { g0 = 1; } else { g0 = 2; } // Choose the vertex for the individual const double r_v1 = gsl_rng_uniform(rng); v1 = 0; while (r_v1 > cmig[c][v1]) { ++v1; } // species of the new individual position = (int)(gsl_rng_uniform(rng) * j_per_c); s1 = list->head; index = s1->sp->n[v1]; while (index <= position) { s1 = s1->next; index += s1->sp->n[v1]; } if (v1 == c) // local remplacement { const double r = gsl_rng_uniform(rng); const int aa = s1->sp->genotypes[0][v1]; const int Ab = s1->sp->genotypes[1][v1]; const int AB = s1->sp->genotypes[2][v1]; // The total fitness of the population 'W': const double w = aa + Ab * (1.0 + s) + AB * (1.0 + s) * (1.0 + s); if (r < aa / w) { g1 = gsl_rng_uniform(rng) < mu ? 1 : 0; } else { if (AB == 0 || r < (aa + Ab * (1.0 + s)) / w) { g1 = gsl_rng_uniform(rng) < mu ? 2 : 1; } else { g1 = 2; } } } else { // Migration event g1 = 0; } // Apply the changes s0->sp->n[c]--; s0->sp->genotypes[g0][c]--; s1->sp->n[c]++; s1->sp->genotypes[g1][c]++; //////////////////////////////////////////// // Check for local extinction // //////////////////////////////////////////// if (s0->sp->n[c] == 0) { extinction_per_c[c]++; } //////////////////////////////////////////// // Check for speciation // //////////////////////////////////////////// else if (s0->sp->genotypes[2][c] > 0 && s0->sp->genotypes[0][c] == 0 && s0->sp->genotypes[1][c] == 0) { species_list_add(list, species_init(communities, current_date, 3)); // Add the new species const int pop = s0->sp->n[c]; list->tail->sp->n[c] = pop; list->tail->sp->genotypes[0][c] = pop; s0->sp->n[c] = 0; s0->sp->genotypes[2][c] = 0; // To keep info on patterns of speciation... ivector_add(&pop_size, pop); ++speciation_events[k]; ++speciation_per_c[c]; } } // End 'c' } // End 't' // Remove extinct species from the list and store the number of extinctions. extinction_events[k] += species_list_rmv_extinct2(list, &lifespan, current_date); } // End 'g' total_species[k] = list->size; } // End 'k' ////////////////////////////////////////////////// // PRINT THE FINAL RESULTS // ////////////////////////////////////////////////// fprintf(out, " <global>\n"); fprintf(out, " <avr_lifespan>%.4f</avr_lifespan>\n", imean(lifespan.array, lifespan.size)); fprintf(out, " <median_lifespan>%.4f</median_lifespan>\n", imedian(lifespan.array, lifespan.size)); fprintf(out, " <avr_pop_size_speciation>%.4f</avr_pop_size_speciation>\n", imean(pop_size.array, pop_size.size)); fprintf(out, " <median_pop_size_speciation>%.4f</median_pop_size_speciation>\n", imedian(pop_size.array, pop_size.size)); fprintf(out, " <speciation_per_k_gen>"); int i = 0; for (; i < k_gen - 1; ++i) { fprintf(out, "%d ", speciation_events[i]); } fprintf(out, "%d</speciation_per_k_gen>\n", speciation_events[i]); fprintf(out, " <extinctions_per_k_gen>"); for (i = 0; i < k_gen - 1; ++i) { fprintf(out, "%d ", extinction_events[i]); } fprintf(out, "%d</extinctions_per_k_gen>\n", extinction_events[i]); fprintf(out, " <extant_species_per_k_gen>"); for (i = 0; i < k_gen - 1; ++i) { fprintf(out, "%d ", total_species[i]); } fprintf(out, "%d</extant_species_per_k_gen>\n", total_species[i]); // Print global distribution fprintf(out, " <species_distribution>"); ivector species_distribution; ivector_init1(&species_distribution, 128); it = list->head; while (it != NULL) { ivector_add(&species_distribution, species_total(it->sp)); it = it->next; } ivector_sort_asc(&species_distribution); ivector_print(&species_distribution, out); fprintf(out, "</species_distribution>\n"); double *octaves; int oct_num = biodiversity_octaves(species_distribution.array, species_distribution.size, &octaves); fprintf(out, " <octaves>"); for (i = 0; i < oct_num; ++i) { fprintf(out, "%.2f ", octaves[i]); } fprintf(out, "%.2f</octaves>\n", octaves[i]); fprintf(out, " </global>\n"); // Print info on all vertices double *restrict ric_per_c = (double*)malloc(communities * sizeof(double)); for (int c = 0; c < communities; ++c) { fprintf(out, " <vertex>\n"); fprintf(out, " <id>%d</id>\n", c); fprintf(out, " <xcoor>%.4f</xcoor>\n", x[c]); fprintf(out, " <ycoor>%.4f</ycoor>\n", y[c]); fprintf(out, " <total_mig_rate>%.8f</total_mig_rate>\n", 1.0 - ((c==0)?cmig[0][0]:cmig[c][c]-cmig[c][c-1])); fprintf(out, " <speciation_events>%d</speciation_events>\n", speciation_per_c[c]); fprintf(out, " <extinction_events>%d</extinction_events>\n", extinction_per_c[c]); int vertex_richess = 0; ivector_rmvall(&species_distribution); it = list->head; while (it != NULL) { ivector_add(&species_distribution, it->sp->n[c]); it = it->next; } // Sort the species distribution and remove the 0s ivector_sort_asc(&species_distribution); ivector_trim_small(&species_distribution, 1); ric_per_c[c] = (double)species_distribution.size; fprintf(out, " <species_richess>%d</species_richess>\n", species_distribution.size); fprintf(out, " <species_distribution>"); ivector_print(&species_distribution, out); fprintf(out, "</species_distribution>\n"); // Print octaves free(octaves); oct_num = biodiversity_octaves(species_distribution.array, species_distribution.size, &octaves); fprintf(out, " <octaves>"); for (i = 0; i < oct_num - 1; ++i) { fprintf(out, "%.2f ", octaves[i]); } fprintf(out, "%.2f</octaves>\n", octaves[i]); fprintf(out, " </vertex>\n"); } fprintf(out, "</simulation>\n"); sprintf(buffer, "%s%u-bc.xml", P.ofilename, seed); FILE *restrict obc = fopen(buffer, "w"); fprintf(obc, "<dissimilarity>\n"); for (int i = 0; i < communities; ++i) { for (int j = 0; j < communities - i; ++j) { const double a = x[i] - x[j]; const double b = y[i] - y[j]; int sum = 0; s0 = list->head; while (s0 != NULL) { const int n_a = s0->sp->n[i]; const int n_b = s0->sp->n[j]; if (n_a > 0 && n_b > 0) { sum += MIN(n_a, n_b); } s0 = s0->next; } const double bray_curtis = ((double)sum) / j_per_c; fprintf(obc, " <pair><distance>%.8f</distance><bc>%.8f</bc></pair>\n", hypot(a, b), bray_curtis); } } fprintf(obc, "</dissimilarity>\n"); ////////////////////////////////////////////////// // EPILOGUE... // ////////////////////////////////////////////////// // Close files; fclose(out); fclose(obc); // Free arrays; free(x); free(y); free(ric_per_c); //free(spe_per_c); free(buffer); free(total_species); free(octaves); free(speciation_per_c); free(extinction_per_c); free(speciation_events); free(extinction_events); // Free structs; species_list_free(list); ivector_free(&species_distribution); ivector_free(&lifespan); ivector_free(&pop_size); gsl_rng_free(rng); return NULL; }
int run_huge_exepriment(string experimentData, int argc, char * argv[]) { mpi::environment env(argc, argv); mpi::communicator world; print_current_memory_consumption(world); // Create Optimization settings DistributedSettings settings; settings.verbose = true; settings.bulkIterations = true; settings.showLastObjectiveValue = true; settings.partitioning = BlockedPartitioning; //Set partitioning method // Create Optimization stats distributed_statistics stat("generated", &world, settings); gsl_rng_env_setup(); const gsl_rng_type * T; gsl_rng * rr; T = gsl_rng_default; rr = gsl_rng_alloc(T); const int MAXIMUM_THREADS = 32; std::vector<gsl_rng *> rs(MAXIMUM_THREADS); for (int i = 0; i < MAXIMUM_THREADS; i++) { rs[i] = gsl_rng_alloc(T); unsigned long seed = i + MAXIMUM_THREADS * world.rank() * world.size(); gsl_rng_set(rs[i], seed); } randomNumberUtil::init_omp_random_seeds(world.rank()); randomNumberUtil::init_random_seeds(rs, MAXIMUM_THREADS * world.rank() * world.size()); srand(world.rank()); // ================================LOAD DATA======================= ProblemData<L, D> part; D optimalValue = 0; loadDistributedSparseSVMRowData(experimentData, world.rank(), world.size(), part, false); vreduce(world, &part.n, &part.total_n, 1, 0); vbroadcast(world, &part.total_n, 1, 0); // obatining \omega int omega = 0; for (int sample = 0; sample < part.A_csr_row_ptr.size() - 1; sample++) { int rowOmega = part.A_csr_row_ptr[sample + 1] - part.A_csr_row_ptr[sample]; if (rowOmega > omega) { omega = rowOmega; } } int totalOmega; vreduce(world, &omega, &totalOmega, 1, 0); vbroadcast(world, &totalOmega, 1, 0); cout << "omega : " << omega << " " << "total Omega " << totalOmega << endl; part.lambda = 1 / (0.0 + part.total_n); part.lambda = 0.01; L totalFeatures; vreduce_max(world, &part.m, &totalFeatures, 1, 0); vbroadcast(world, &totalFeatures, 1, 0); part.m = totalFeatures; ProblemData<L, D> part_local; part_local.n = part.n; part_local.m = 0; part_local.A_csr_row_ptr.resize(part.n + 1, 0); // normalize ROWS!!! // for (L sample = 0; sample < part.n; sample++) { // D norm = 0; // for (L tmp = part.A_csr_row_ptr[sample]; // tmp < part.A_csr_row_ptr[sample + 1]; tmp++) { // norm += part.A_csr_values[tmp] * part.A_csr_values[tmp]; // } // if (norm > 0) { // norm = 1 / sqrt(norm); // for (L tmp = part.A_csr_row_ptr[sample]; // tmp < part.A_csr_row_ptr[sample + 1]; tmp++) { // part.A_csr_values[tmp] = part.A_csr_values[tmp] * norm; // } // } // // } stat.generated_optimal_value = optimalValue; long long totalN = part.total_n; settings.totalThreads = 8; settings.iterationsPerThread = 20; // settings.totalThreads = 2; // settings.iterationsPerThread = 1; settings.iters_communicate_count = //20 +totalN / (world.size() * settings.iterationsPerThread * settings.totalThreads + 0.0); // settings.iters_bulkIterations_count = 5; settings.iters_communicate_count = settings.iters_communicate_count * 5; settings.iters_communicate_count = 50; settings.iters_bulkIterations_count = 100; // settings.iters_communicate_count=1; // settings.iters_bulkIterations_count = 1; cout << "Solver settings " << settings.iterationsPerThread << " communica " << settings.iters_communicate_count << " recompute " << settings.iters_bulkIterations_count << endl; settings.showInitialObjectiveValue = true; // settings.iters_communicate_count = 1; // settings.iters_bulkIterations_count = 1; // part.sigma = 8 // + ((part.n * p * world.size() / (part.m + 0.0) - 1.0) // * (settings.iterationsPerThread // * settings.totalThreads * world.size() - 1.0)) // / (part.n * world.size() - 1.0) ; //FIXME compute true SIGMA!!! // cout << "SIGMA IS " << part.sigma << " " << part.n << " " // << part.m << endl; // part.sigma = 1; world.barrier(); data_distributor<L, D> dataDistributor; settings.broadcast_treshold = 2; settings.showIntermediateObjectiveValue = true; omp_set_num_threads(settings.totalThreads); randomNumberUtil::init_random_seeds(rs, settings.totalThreads * world.rank() * world.size()); int test_case = 0; stat.reset(); settings.iterationsPerThread =settings.iterationsPerThread /6; // part.sigma = 2*2*2*2*2*2*2*2; double increment = 2; for (int ex = 0; ex < 10; ex++) { settings.iterationsPerThread = settings.iterationsPerThread * increment; // increment = increment * 2; double tt = settings.totalThreads * settings.iterationsPerThread; // totalOmega=totalOmega; part.sigma = 1; if (part.n > 1 && tt > 1) { part.sigma += (totalOmega - 1) * (tt - 1) / (part.n - 1.0) + totalOmega * (world.size() - 1) / (world.size() + 0.0) * (tt / (part.n + 0.0) - (tt - 1) / (part.n - 1.0)); } part_local.sigma = part.sigma; settings.distributed = SynchronousReduce; // settings.distributed = AsynchronousStreamlinedOptimized; // switch (ex) { // case 0: // part.sigma = 1.1; // break; // case 1: // part.sigma = 2; // break; // case 2: // part.sigma = 3; // break; // // default: // break; // } cout << "SIGMA IS " << part.sigma << " " << part.n << " " << part.m << endl; distributed_solver_from_multiple_sources_structured_hybrid_barrier<D, L, LT>(env, world, settings, stat, part_local, part, dataDistributor, rs); if (world.rank() == 0) { std::cout << "TEST " << test_case++ << " (" << settings.distributed << ")" << std::endl << ": Objective " << stat.last_obj_value << ": error " << stat.last_obj_value - optimalValue << " Runtime " << boost::timer::format(stat.time_nonstop.elapsed(), 6, "%w") << "\n" << " " << part.sigma << std::endl; get_additional_times(stat); } } // // distributed_solver_from_multiple_sources<D, L, LT>(env, world, settings, // stat, part, dataDistributor); // if (world.rank() == 0) { // std::cout << "TEST " << test_case++ << " (" << settings.distributed // << ")" << std::endl << ": Objective " << stat.last_obj_value // << " Runtime " // << boost::timer::format(stat.time_nonstop.elapsed(), 6, "%w") // << "\n" << std::endl; // get_additional_times(stat); // } // stat.reset(); /* part.sigma = 1; create_distribution_schema_for_multiple_sources(world, inst, part, dataDistributor, settings, stat); if (world.rank() == 0) { cout << "Hypergraph cut: " << stat.hypergraph_cut << endl; } world.barrier(); int test_case = 0; // Solver should solve using only PART! (INST can we used for other purposes settings.distributed = AsynchronousStreamlined; distributed_solver_from_multiple_sources<D, L, LT>(env, world, settings, stat, part, dataDistributor); if (world.rank() == 0) { std::cout << "TEST " << test_case++ << " (" << settings.distributed << ")" << std::endl << ": Objective " << stat.last_obj_value << " Runtime " << boost::timer::format(stat.time_nonstop.elapsed(), 6, "%w") << "\n" << std::endl; get_additional_times(stat); } stat.reset(); // NOTE: on 4 computers, width 2 does not work settings.torus_width = 2; settings.distributed = AsynchronousTorus; distributed_solver_from_multiple_sources<D, L, LT>(env, world, settings, stat, part, dataDistributor); if (world.rank() == 0) { std::cout << "TEST " << test_case++ << " (" << settings.distributed << ")" << std::endl << ": Objective " << stat.last_obj_value << " Runtime " << boost::timer::format(stat.time_nonstop.elapsed(), 6, "%w") << "\n" << std::endl; get_additional_times(stat); } stat.reset(); // NOTE: on 4 computers, width 2 does not work settings.torus_width = 2; settings.distributed = AsynchronousTorusOpt; distributed_solver_from_multiple_sources<D, L, LT>(env, world, settings, stat, part, dataDistributor); if (world.rank() == 0) { std::cout << "TEST " << test_case++ << " (" << settings.distributed << ")" << std::endl << ": Objective " << stat.last_obj_value << " Runtime " << boost::timer::format(stat.time_nonstop.elapsed(), 6, "%w") << "\n" << std::endl; get_additional_times(stat); } stat.reset(); // NOTE: on 4 computers, width 2 does not work settings.torus_width = 2; settings.distributed = AsynchronousTorusOptCollectives; distributed_solver_from_multiple_sources<D, L, LT>(env, world, settings, stat, part, dataDistributor); if (world.rank() == 0) { std::cout << "TEST " << test_case++ << " (" << settings.distributed << ")" << std::endl << ": Objective " << stat.last_obj_value << " Runtime " << boost::timer::format(stat.time_nonstop.elapsed(), 6, "%w") << "\n" << std::endl; get_additional_times(stat); } stat.reset(); */ if (world.rank() == 0) cout << "Optimal value should be " << optimalValue << endl; print_current_memory_consumption(world); return 0; }