/* INITIALIZE PARAMETERS */ void init_param(param *par, data *dat, gentime *gen, int *ances, int *init_kappa, double pi_param1, double pi_param2, double phi_param1, double phi_param2, double init_mu1, double init_gamma, double init_spa1, double init_spa2, double spa1_prior, double spa2_prior, double outlier_threshold, int mut_model, int spa_model, int import_method, gsl_rng *rng) { int i, ancesId, T, TmaxLike; /* Tinf */ /* TmaxLike = which_max_vec_double(gen->dens->rows[0]); */ TmaxLike = which_max_vec_double(gen->collTime); for(i=0; i<dat->n; i++) { par->Tinf->values[i] = vec_int_i(dat->dates,i) - TmaxLike; } /* alpha */ for(i=0; i<dat->n; i++) { par->alpha->values[i] = ances[i]; } /* kappa */ /* printf("\nGeneration time data\n");fflush(stdout); */ /* print_gentime(gen); */ for(i=0; i<dat->n; i++) { /* par->kappa->values[i] = 1; */ ancesId = vec_int_i(par->alpha,i); /* printf("\nInitial kappa_%d: %d\n",i,init_kappa[i]);fflush(stdout); */ if(ancesId>-1) { if(init_kappa[i]<1) { /* value < 1 => find ML kappa */ T = vec_int_i(par->Tinf, i) - vec_int_i(par->Tinf, ancesId); par->kappa->values[i] = find_maxLike_kappa_i(T, gen); } else { par->kappa->values[i] = init_kappa[i]; /* otherwise, use specified kappa */ } } else { /* kappa = 1 by convention for imported cases */ par->kappa->values[i] = 1; } /* printf("\nInitialized kappa_%d: %d\n",i,par->kappa->values[i]);fflush(stdout); */ } /* integers */ par->mut_model = mut_model; par->spa_model = spa_model; if(par->mut_model==0) { par->import_method = 2; } else { par->import_method = import_method; } /* doubles*/ par->mu1 = init_mu1; par->mu1_prior = init_mu1; par->gamma = init_gamma; par->pi = gsl_ran_beta(rng,pi_param1,pi_param2); par->pi_param1 = pi_param1; par->pi_param2 = pi_param2; par->spa_param1 = init_spa1; par->spa_param2 = init_spa2; par->spa_param1_prior = spa1_prior; par->spa_param2_prior = spa2_prior; par->outlier_threshold = outlier_threshold; par->phi = gsl_ran_beta(rng,phi_param1,phi_param2); par->phi_param1 = phi_param1; par->phi_param2 = phi_param2; }
/* Samples either one change point or one probability */ void sampleMixed(const gsl_rng *r, parameters* p, int nPar, intparameters *ip, int nIPar) { static int hello=1; double pr=gsl_rng_uniform(r); int moveK=pr<mixingRatio; const int *CDFdata=getData(), nCDFdata=getNdata(); if(hello) fprintf(OUT, "sampleMixed()...\n"), hello=0; /* Set proposed changepoint locations and probabilities to current values.*/ resetProposals(p, nPar, ip, nIPar); /* Assuming there is NO changepoint */ if(nIPar<=0) moveK=0; if(moveK) { double pJump=0.1; /* Which k shall be moved? */ int indK=gsl_rng_uniform_int(r, nIPar); int kDown=(indK-1>=0)?getIntParameter(ip,indK-1):0; int kUp=(indK+1<nIPar)?getIntParameter(ip,indK+1):getNdata(); int kNew; int succ0, succ1; int fail0, fail1; double p0, p1; setIntMin(ip, indK, kDown); setIntMax(ip, indK, kUp); if(gsl_rng_uniform(r)>=pJump) { /*Move only one parameter by width */ proposeIntConstrainedAB(r, ip, indK, 1); } else { proposeIntShiftInterval(r, ip, indK, 1); } /* Update probabilities */ kNew=getIntProposal(ip,indK); succ0=succInterval(CDFdata, kDown, kNew); succ1=succInterval(CDFdata, kNew, kUp); fail0=kNew-kDown-succ0; fail1=kUp-kNew-succ1; p0=gsl_ran_beta(r, succ0, fail0); p1=gsl_ran_beta(r, succ1,fail1); setProposal(p, indK, p0); setProposal(p, indK+1, p1); } else { sampleProbabilities(r, CDFdata, nCDFdata, p, nPar, ip, nIPar); } }
double perfect(long int seed) { /* * The perfect sampling algorithm. */ int t = 100; // starting value of t int increment = 50; // increment t by this number if coalesence fails double Z[MAX_DEPTH+1]; // Grab memory for shocks double U[MAX_DEPTH+1]; // Ditto // Some boilerplate to set up the random number generator const gsl_rng_type * T; gsl_rng * rd; gsl_rng_env_setup(); T = gsl_rng_default; rd = gsl_rng_alloc (T); gsl_rng_set(rd, seed); // Draw the first set of random shocks for i = 0,...,t int i; for (i = 0; i <= t; i++) { U[i] = gsl_ran_beta(rd, alpha1, beta1); Z[i] = gsl_ran_beta(rd, alpha2, beta2); } while (t < MAX_DEPTH - 1) { int sigma = get_sigma(t, U); if (sigma > 0) { double r = compute_singleton(sigma, t, Z, U); if (r >= 0) { gsl_rng_free(rd); return r; } } // Coalescence failed, so lets go round again for (i = t+1; i <= t+increment; i++) { U[i] = gsl_ran_beta(rd, alpha1, beta1); Z[i] = gsl_ran_beta(rd, alpha2, beta2); } t = t + increment; } // If we made it this far then we've hit MAX_DEPTH without success, so // return a warning and a fail value gsl_rng_free(rd); printf("Warning: MAX_DEPTH reached, returning fail value!\n"); printf("If this happens repeatedly, you need to increase MAX_DEPTH.\n"); return -1.0; }
unsigned int gsl_ran_binomial (const gsl_rng * r, double p, unsigned int n) { unsigned int i, a, b, k = 0; while (n > 10) /* This parameter is tunable */ { double X; a = 1 + (n / 2); b = 1 + n - a; X = gsl_ran_beta (r, (double) a, (double) b); if (X >= p) { n = a - 1; p /= X; } else { k += a; n = b - 1; p = (p - X) / (1 - X); } } for (i = 0; i < n; i++) { double u = gsl_rng_uniform (r); if (u < p) k++; } return k; }
int DPMHC_K(struct str_DPMHC *ptr_DPMHC_data) { int i_K = ptr_DPMHC_data->i_K; gsl_vector *v_u = ptr_DPMHC_data->v_u; gsl_vector *v_v = ptr_DPMHC_data->v_v; gsl_vector *v_w = ptr_DPMHC_data->v_w; gsl_matrix *m_DPtheta = ptr_DPMHC_data->m_DPtheta; double d_DPalpha = ptr_DPMHC_data->d_DPalpha; int K_tmp, K_new,j; double a,v_j,w_j,csum,min_u; //gsl_vector_view theta_j; //int k_asset_number = P -> size1; /* number of assets in model */ K_tmp = i_K; min_u = gsl_vector_min ( v_u ); a = 1.0 - min_u; if( a == 1.0 ) printf("**********min_u = %g *************\n",min_u); csum = 0.0; j=0; while ( csum <= a ){ /* check if new v_j,w_j and theta_j should be generated */ if( j >= K_tmp ){ v_j = gsl_ran_beta ( rng , 1.0, d_DPalpha ); vset( v_v, j, v_j); w_j = v_j * (vget( v_w, j-1 )/vget(v_v,j-1))*(1.0-vget(v_v,j-1)); vset( v_w, j, w_j); /* generate new mu, xi, tau from prior G_0 */ mset(m_DPtheta, j, 0, ptr_DPMHC_data->d_m0 + gsl_ran_gaussian_ziggurat(rng, sqrt(ptr_DPMHC_data->d_s2m))); mset(m_DPtheta, j, 1, gsl_ran_gaussian_ziggurat(rng, ptr_DPMHC_data->d_A)); mset(m_DPtheta, j, 2, gsl_ran_gamma(rng, 0.5, 0.5) ); } csum += vget(v_w,j); K_new = j + 1; j++; } ptr_DPMHC_data->i_K = K_new; return 0; }
void librdist_beta(gsl_rng *rng, int argc, void *argv, int bufc, float *buf){ t_atom *av = (t_atom *)argv; if(argc != librdist_getnargs(ps_beta)){ return; } const double a = librdist_atom_getfloat(av); const double b = librdist_atom_getfloat(av + 1); int i; for(i = 0; i < bufc; i++) buf[i] = (float)gsl_ran_beta(rng, a, b); }
int DPMHC_v_smplr(struct str_DPMHC *ptr_DPMHC_data) { gsl_vector *v_v = ptr_DPMHC_data->v_v; gsl_vector *v_w = ptr_DPMHC_data->v_w; gsl_vector_int *vi_S = ptr_DPMHC_data->vi_S; int i_K = ptr_DPMHC_data->i_K; double d_DPalpha = ptr_DPMHC_data->d_DPalpha; size_t i_T = vi_S->size; int i,j,i_si; double d_vj,d_prod; // printf("inside sample_v K=%d\n",K); gsl_vector *v_a = gsl_vector_alloc ( (size_t) i_K ); gsl_vector *v_b = gsl_vector_alloc ( (size_t) i_K ); gsl_vector_set_all ( v_a, 1.0 ); gsl_vector_set_all ( v_b, d_DPalpha); for(i=0;i<i_T;i++){ i_si = vget_int(vi_S,i); (v_a->data[ i_si ]) += 1.0; for(j = 0; j < i_si;j++){ (v_b->data[ j ]) += 1.0; } } /* pvec(a); */ /* pvec(b); */ /* take draws and form w */ for(j=0;j<i_K;j++){ d_vj = gsl_ran_beta ( rng , vget(v_a,j) , vget(v_b,j) ); vset( v_v, j, d_vj ); /* w_j */ if( j == 0 ){ vset(v_w,j, d_vj ); d_prod = (1.0-d_vj); }else{ vset(v_w,j, d_vj*d_prod ); d_prod *= (1.0-d_vj); } } gsl_vector_free (v_a); gsl_vector_free (v_b); return 0; }
inline void CNPLCM_CR_Basic_Freq::sam_lambda(){ int tmp1 = 1, tmp0 = 0; CVariable_Container& lJK = (*par)["lambdaJK"]; CVariable_Container& raux_JK2 = (*par)["aux_JK2"]; this->tabulate_elements(); //accumulate the counts of samples. //add the prior (+1) and sample for(int j = 0; j < data->J; j++){ for(int k = 0; k < par->K; k++){ //add prior and cast and sample! //par->lambdaJK[j][k] = gsl_ran_beta(r, double(1 + par->aux_JK2[j][k][1]), double(1 + par->aux_JK2[j][k][0])); lJK.arr_elem<double>(j,k) = gsl_ran_beta(r, double(1 + raux_JK2.arr_elem<int>(j, k, tmp1)), double(1 + raux_JK2.arr_elem<int>(j, k, tmp0))); } } }
/* Sample probabilities according to successes and failures */ void sampleProbabilities(const gsl_rng *r, const int *CDFdata, int nCDFdata, parameters *p, int nPar, const intparameters *ip, int nIPar) { int k; for(k=0; k<nPar; k++) { int k0=(k<=0)?0:getIntProposal(ip,k-1); int k1=(k<nIPar)?getIntProposal(ip,k):nCDFdata-1; int success=succInterval(CDFdata, k0, k1)/* (k0<=0)?CDFdata[k1-1]:CDFdata[k1-1]-CDFdata[k0-1] */; int failures=k1-k0-success; double estP; double alpha=getAlpha(), beta=getBeta(); estP=gsl_ran_beta(r, success+alpha+1, failures+beta+1); /* fprintf(OUT, "p=%g\n", estP); */ setProposal(p, k, estP); } }
/* Diese Funktion berechnet Nischenwerte für S Spezies. Dabei wird zunächst jeder Spezies eine Zufallszahl zugeordnet, der Nischenwert. Dieser ist gleichverteilt auf ]0,1[. Ausgehend davon wird dann ein Fresszentrum und ein Fressbereich bestimmt. Der Fressbereich wird mit einer Beta-Verteilung erwürfelt. Eine Spezies kann eine andere Spezies fressen, wenn der Nischenwert der Beute im Fressbereich des Räubers liegt. Rückgabewert: 3xS Matrix mit [0][S]: Nischenwert, [1][S]: Fressbereich, [2][S]: Fresszentrum. */ gsl_matrix *SetNicheValues(struct foodweb nicheweb, double C, gsl_rng* rng1, const gsl_rng_type* rng_T){ int S = nicheweb.S; //printf("\nStarte Berechnung der Nischenwerte für %i Spezies\n", S); gsl_matrix *NV = gsl_matrix_calloc(3, nicheweb.S); gsl_vector *nv = gsl_vector_calloc(S); //printf("nischenwert allokation"); double disbeta = (1-2*C)/(2*C); // Für den Fressbereich (Beta-Verteilung) int i = 0; //--Nischenwerte ausrechnen------------------------------------------------------------------------------------------------ for(i= 0; i<S; i++) gsl_vector_set(nv, i, gsl_rng_uniform_pos(rng1)); // Nischenwerte gleichverteilt auf ]0,1[ gsl_sort_vector(nv); // Sortieren für Massenberechnung später for(i = 0; i < S; i++) { double nvi = gsl_vector_get(nv, i); double fri = gsl_ran_beta(rng1, 1, disbeta); double rand = gsl_rng_uniform_pos(rng1); double fci = nvi*fri*rand/2 + nvi*(1-rand); // Zufälliges Fresszentrum in [nv(i)*fr(i)/2, nv(i)] gsl_matrix_set(NV, 0, i, nvi); gsl_matrix_set(NV, 1, i, fri); gsl_matrix_set(NV, 2, i, fci); } //--Zuweisung---------------------------------------------------------------------------------------------------- free(nv); return NV; }//end SetNicheValues
/* Selects changepoint position and adds new changepoint before or after */ void sampleDeath(const gsl_rng *r, parameters* p, int actP, int nPar, intparameters *ip, int actIP, int nIPar) { /* select change point that will be deleted */ int kIndex=gsl_rng_uniform_int(r, actIP); int kDown, kUp; int succ, fail; /* Open probabilities that replaces probabilities 'left' and 'right' of deleted changepoint.*/ double pNew; int i; static int hello=1; const int*CDF=getData(), nCDF=getNdata(); double alpha=getAlpha(), beta=getBeta(); if(hello) fprintf(OUT, "sampleDeath()\n"), hello=0; /*Copy kIndex parameters unchanged */ copyIntOrg2Prop(ip, kIndex); /* Omit kIndex */ for(i=kIndex; i<nIPar-1; i++) { setIntProposal(ip, i, getIntParameter(ip,i+1)); } /*Copy kIndex double parameters unchanged */ copyOrg2Prop(p, kIndex); kDown=(kIndex<=0)?0:getIntParameter(ip, kIndex-1); kUp=(kIndex==actIP)?nCDF-1:getIntParameter(ip,kIndex)-1; succ=succInterval(CDF, kDown, kUp), fail=failInterval(CDF, kDown, kUp); pNew=gsl_ran_beta(r, succ+alpha+1,fail+beta+1); setProposal(p, kIndex, pNew); /* Balance with corresponding birth move */ proposalScale=(double)kUp-kDown; for(i=kIndex+1; i<nPar-1; i++) { setProposal(p, i, getParameter(p,i+1)); } }
void DP_mu_gamma(PARAM *param, PRIOR *prior, DATA *data, const gsl_rng *r) { int i,j; int wsum[_MAX_COMP_]; int wrevsum[_MAX_COMP_]; float gammap[_MAX_COMP_]; for(i=0;i<_MAX_COMP_;i++) { wsum[i] = 0; wrevsum[i] = 0; } for(i=0;i<data->nprey;i++) (wsum[prior->w_mu[i]])++; for(i=_MAX_COMP_-1;i>=0;i--) { for(j=i;j<_MAX_COMP_;j++) wrevsum[i] += wsum[j]; } for(i=0;i<_MAX_COMP_-1;i++) gammap[i] = gsl_ran_beta(r, (1.0 + (double) wsum[i]), ((double) prior->rho_mu) + ((double) wrevsum[i+1])); gammap[_MAX_COMP_-1] = 1.0; prior->gamma_mu[0] = gammap[0]; for(i=1;i<_MAX_COMP_;i++) { prior->gamma_mu[i] = gammap[i]; for(j=0;j<i;j++) prior->gamma_mu[i] *= (1.0 - gammap[j]); } }
int main(int argc, char *argv[]) { clock_t start, stop; // Initiate the GSL random number generator gsl_rng *rng = gsl_rng_alloc(gsl_rng_taus2); gsl_rng_set(rng, time(NULL)); unsigned int S; S = atoi(argv[1]); double C; C = atof(argv[2]); // Pointers to output file FILE *splist; start = clock(); // Let's generate three arrays of n, r, and c double *n = (double*) malloc(S * sizeof(double)); double *r = (double*) malloc(S * sizeof(double)); double *c = (double*) malloc(S * sizeof(double)); int *pop = (int*) malloc(S * sizeof(int)); int *K = (int*) malloc(S * sizeof(int)); // We then generate random values of n for (int sp = 0; sp < S; ++sp) { n[sp] = gsl_ran_flat (rng, 0.0, 1.0); r[sp] = n[sp]*gsl_ran_beta(rng, 1, 1/(2*C)-1); c[sp] = gsl_ran_flat(rng, r[sp]/2, n[sp]); K[sp] = gsl_rng_uniform_int(rng, (int) 500 - 500*n[sp])+100; pop[sp] = gsl_rng_uniform_int(rng, (int) K[sp]-10)+10; } // The species with the smallest n has a r of 0 double min_n = 1000; // We start by getting the min value for (int sp = 0; sp > S; ++sp){ if (n[sp] < min_n){ min_n = n[sp]; } } // Then we update the r value accordingly for (int sp = 0; sp < S; ++sp){ if (n[sp] == min_n){ r[sp] = 0; } } // Finally we write to a file char tfname[FNSIZE]; snprintf(tfname, sizeof(char) * FNSIZE, "splist.txt"); splist = fopen(tfname, "w"); for (int sp = 0; sp < S; ++sp){ fprintf(splist, "%d %.4f %.4f %.4f %d %d\n", sp+1, n[sp], r[sp], c[sp], K[sp], pop[sp]); } fclose(splist); gsl_rng_free(rng); stop = clock(); printf("%d species, expected connectance of %.2f, generated in %.2f seconds\n", S, C, (stop - start) / (float) CLOCKS_PER_SEC); return EXIT_SUCCESS; }
double rbeta(double a, double b) { return gsl_ran_beta(RANDOM_NUMBER, a, b); }
double test_beta (void) { return gsl_ran_beta (r_global, 2.0, 3.0); }
/* Selects changepoint position and adds new changepoint before or after */ void sampleBirth(const gsl_rng *r, parameters* p, int actP, int nPar, intparameters *ip, int actIP, int nIPar) { /* select parameter */ int kIndex=gsl_rng_uniform_int(r, actIP+1); int kDown=(kIndex<=0)?0:getIntParameter(ip,kIndex-1); int kUp=(kIndex==actIP)?getNdata()-1:getIntParameter(ip,kIndex)-1; /*sample new change point*/ int kNew; int i; static int hello=1; const int *CDF=getData(), nCDF=getNdata(); int succ0, succ1, fail0, fail1; double p0, p1; double alpha=getAlpha(), beta=getBeta(); /* Adding the first changepoint */ if(actIP==0) { /* k must be between 1 and nCDF-1*/ int kNew=gsl_rng_uniform_int(r,nCDF-1)+1; /* Successes and failures before and after new changepoint kNew are used for sampling p0 and p1... */ succ0=succInterval(CDF, 0, kNew), fail0=failInterval(CDF, 0, kNew); succ1=succInterval(CDF, kNew, nCDF), fail1=failInterval(CDF, kNew, nCDF); /* ... from beta distributions. */ p0=gsl_ran_beta(r, succ0+1+alpha, fail0+beta+1); p1=gsl_ran_beta(r, succ1+1+alpha, fail1+beta+1); /* Set new proposal */ setIntProposal(ip, 0, kNew); setProposal(p,0,p0); setProposal(p,1,p1); /* Balance with corresponding death move */ proposalScale=1/((double)(nCDF-1)); return; } /* Find kUp and kDown that are more than one data point apart. */ while(kUp-kDown<=1) { kIndex=gsl_rng_uniform_int(r, actIP+1); kDown=(kIndex<=0)?0:getIntParameter(ip,kIndex-1); kUp=(kIndex==actIP)?getNdata()-1:getIntParameter(ip,kIndex)-1; } /* Balance with corresponding death move */ proposalScale=1/((double)(kUp-kDown)); do { kNew=kDown+gsl_rng_uniform_int(r, kUp-kDown); }while (kNew==0); if(hello) fprintf(OUT, "sampleBirth()\n"), hello=0; /*Copy kIndex parameters unchanged */ copyIntOrg2Prop(ip, kIndex); /* Insert new changepoint */ setIntProposal(ip, kIndex, kNew); /* Shift changepoints after inserted changepoint. */ for(i=kIndex+1; i<nIPar; i++) { setIntProposal(ip, i, getIntParameter(ip,i-1)); } /* Now copy kIndex open probabilities. */ if(kIndex-1>0) copyOrg2Prop(p, kIndex); /* Sample open probabilities for the segments 'left' and 'right' of the new changepoint. */ succ0=succInterval(CDF, kDown, kNew), fail0=failInterval(CDF, kDown, kNew); succ1=succInterval(CDF, kNew, kUp), fail1=failInterval(CDF, kNew, kUp); p0=gsl_ran_beta(r, succ0+alpha+1, fail0+beta+1); p1=gsl_ran_beta(r, succ1+alpha+1, fail1+beta+1); setProposal(p, kIndex, p0); setProposal(p, kIndex+1, p1); /* Shift the remaining open probabilities. */ for(i=kIndex+2; i<nPar; i++) { double pI=getParameter(p,i-1); setProposal(p, i, pI); } }
int main() { gsl_rng * r; const gsl_rng_type * T; gsl_rng_env_setup(); T = gsl_rng_default; r = gsl_rng_alloc (T); // printf ("generator type: %s\n", gsl_rng_name (r)); // printf ("seed = %lu\n", gsl_rng_default_seed); // printf ("first value = %lu\n", gsl_rng_get (r)); // Step 1 int k = 3; // k is the # of communities const double alpha = double (1.0) / k; // printf ("k = %d and alpha = %f\n", k, alpha); double eta = 1; // eta is the hidden variable of the Beta distribution double comm_str [k]; for (uint32_t i = 0; i < k; ++i) comm_str[i] = gsl_ran_beta(r, eta, eta); // Step 2 int n = 10; // Number of nodes double theta = 1; // Used for gsl_ran_dirichlet double alpha_array [k]; // Array for gsl_ran_dirichlet for (uint32_t i = 0; i < k; ++i) alpha_array[i] = alpha; double pi [n][k]; // Array to store pi // Populate pi for (uint32_t i = 0; i < n; ++i) gsl_ran_dirichlet(r, k, alpha_array, pi[i]); // // Convert to binary // for (uint32_t i = 0; i < n; ++i){ // for (uint32_t j = 0; j < k ; ++j){ // if (pi[i][j] > 0.5){ // pi[i][j] = 1; // } // else{ // pi[i][j] = 0; // } // } // } // for (uint32_t i = 0; i < n; ++i){ // for (uint32_t j = 0; j < k ; ++j){ // printf("%d, %d, %f\n", i, j ,pi[i][j]); // } // } // Step 4 double mean = 0.0; // Set mean double var = 1; // Set var double prob = 0.5; // Set probability for Bernoulli // Save input values std::ofstream inputs ("inputs.txt"); if (inputs.is_open()){ inputs << "k = " << k << "\n"; inputs << "alpha = " << alpha << "\n"; inputs << "eta = " << eta << "\n"; inputs << "mean = " << mean << "\n"; inputs << "var = " << var << "\n"; inputs << "prob = " << prob << "\n"; inputs << "comm_str = "; for (uint32_t i = 0; i < k; ++i) inputs << comm_str[i] << " "; inputs << "\n" << "n = " << n << "\n" << "pi = " << "\n"; for (uint32_t i = 0; i < n; ++i){ for (uint32_t j = 0; j < k ; ++j){ inputs << pi[i][j] << "\t"; } inputs << "\n"; } inputs.close(); } // Save attribute matrix std::ofstream attributes ("attributes.txt"); if (attributes.is_open()){ for (uint32_t i = 0; i < n; ++i){ attributes << gsl_ran_gaussian(r, var) << "\t"; attributes << gsl_ran_gaussian(r, var) << "\t"; attributes << gsl_ran_bernoulli(r, prob) << "\t"; attributes << gsl_ran_bernoulli(r, prob) << "\t"; attributes << "\n"; } attributes.close(); } // Step 3 int num_edge = 20; // Define number of edges double epsilon = 1e-30; int adj_matrix [n][n]; // Populate adjancency matrix with 0s for (uint32_t i = 0; i < n; ++i) for (uint32_t j = 0; j < n ; ++j) adj_matrix[i][j] = 0; int count = 0; while (count < num_edge){ // printf("count %d\n", count); int a = gsl_rng_uniform_int(r, n); int b = gsl_rng_uniform_int(r, n); // printf("%d, %d\n", a, b); if (a == b){ continue; } double a_probs [k]; double b_probs [k]; for (uint32_t i = 0; i < k; ++i){ a_probs[i] = pi[a][i]; b_probs[i] = pi[b][i]; } int a_val = gsl_ran_discrete(r, gsl_ran_discrete_preproc(k, a_probs)); int b_val = gsl_ran_discrete(r, gsl_ran_discrete_preproc(k, b_probs)); if (a_val == b_val){ // printf("%d, %d\n", a_val, b_val); int x = gsl_ran_bernoulli(r, comm_str[a_val]); if (x == 1){ // printf("x = 1\n"); if (adj_matrix[a][b] == 0){ adj_matrix[a][b] = 1; ++count; } } } else{ int x = gsl_ran_bernoulli(r, epsilon); if (x == 1){ // printf("x = 1\n"); if (adj_matrix[a][b] == 0){ adj_matrix[a][b] = 1; ++count; } } } // for (uint32_t j = 0; j < k ; ++j){ // if (std::pi[a][j] == pi[b][j]){ // int x = gsl_ran_bernoulli(r, comm_str[j]); // // printf("Match 1 %d\n", x); // if (x == 1){ // if (adj_matrix[a][b]) // continue; // else // adj_matrix[a][b] = 1; // run_eps = 0; // ++count; // continue; // } // } // if (run_eps == 1){ // int x = gsl_ran_bernoulli(r, epsilon); // // printf("0 %d\n", x); // if (x == 1){ // if (adj_matrix[a][b]) // continue; // else // adj_matrix[a][b] = 1; // ++count; // continue; // } // } // } } std::ofstream matrix ("matrix.txt"); if (matrix.is_open()){ for (uint32_t i = 0; i < n; ++i){ for (uint32_t j = 0; j < n ; ++j){ if (adj_matrix [i][j]) matrix << i << "\t" << j << '\n'; } } matrix.close(); } }
// -------------------------------------------------- double uqRngGslClass::betaSample(double alpha, double beta) const { return gsl_ran_beta(m_rng,alpha,beta); }
int main (int argc, char *argv[]) { size_t i,j; size_t n = 0; double mu = 0, nu = 0, nu1 = 0, nu2 = 0, sigma = 0, a = 0, b = 0, c = 0; double zeta = 0, sigmax = 0, sigmay = 0, rho = 0; double p = 0; double x = 0, y =0, z=0 ; unsigned int N = 0, t = 0, n1 = 0, n2 = 0 ; unsigned long int seed = 0 ; const char * name ; gsl_rng * r ; if (argc < 4) { printf ( "Usage: gsl-randist seed n DIST param1 param2 ...\n" "Generates n samples from the distribution DIST with parameters param1,\n" "param2, etc. Valid distributions are,\n" "\n" " beta\n" " binomial\n" " bivariate-gaussian\n" " cauchy\n" " chisq\n" " dir-2d\n" " dir-3d\n" " dir-nd\n" " erlang\n" " exponential\n" " exppow\n" " fdist\n" " flat\n" " gamma\n" " gaussian-tail\n" " gaussian\n" " geometric\n" " gumbel1\n" " gumbel2\n" " hypergeometric\n" " laplace\n" " landau\n" " levy\n" " levy-skew\n" " logarithmic\n" " logistic\n" " lognormal\n" " negative-binomial\n" " pareto\n" " pascal\n" " poisson\n" " rayleigh-tail\n" " rayleigh\n" " tdist\n" " ugaussian-tail\n" " ugaussian\n" " weibull\n") ; exit (0); } argv++ ; seed = atol (argv[0]); argc-- ; argv++ ; n = atol (argv[0]); argc-- ; argv++ ; name = argv[0] ; argc-- ; argc-- ; gsl_rng_env_setup() ; if (gsl_rng_default_seed != 0) { fprintf(stderr, "overriding GSL_RNG_SEED with command line value, seed = %ld\n", seed) ; } gsl_rng_default_seed = seed ; r = gsl_rng_alloc(gsl_rng_default) ; #define NAME(x) !strcmp(name,(x)) #define OUTPUT(x) for (i = 0; i < n; i++) { printf("%g\n", (x)) ; } #define OUTPUT1(a,x) for(i = 0; i < n; i++) { a ; printf("%g\n", x) ; } #define OUTPUT2(a,x,y) for(i = 0; i < n; i++) { a ; printf("%g %g\n", x, y) ; } #define OUTPUT3(a,x,y,z) for(i = 0; i < n; i++) { a ; printf("%g %g %g\n", x, y, z) ; } #define INT_OUTPUT(x) for (i = 0; i < n; i++) { printf("%d\n", (x)) ; } #define ARGS(x,y) if (argc != x) error(y) ; #define DBL_ARG(x) if (argc) { x=atof((++argv)[0]);argc--;} else {error( #x);}; #define INT_ARG(x) if (argc) { x=atoi((++argv)[0]);argc--;} else {error( #x);}; if (NAME("bernoulli")) { ARGS(1, "p = probability of success"); DBL_ARG(p) INT_OUTPUT(gsl_ran_bernoulli (r, p)); } else if (NAME("beta")) { ARGS(2, "a,b = shape parameters"); DBL_ARG(a) DBL_ARG(b) OUTPUT(gsl_ran_beta (r, a, b)); } else if (NAME("binomial")) { ARGS(2, "p = probability, N = number of trials"); DBL_ARG(p) INT_ARG(N) INT_OUTPUT(gsl_ran_binomial (r, p, N)); } else if (NAME("cauchy")) { ARGS(1, "a = scale parameter"); DBL_ARG(a) OUTPUT(gsl_ran_cauchy (r, a)); } else if (NAME("chisq")) { ARGS(1, "nu = degrees of freedom"); DBL_ARG(nu) OUTPUT(gsl_ran_chisq (r, nu)); } else if (NAME("erlang")) { ARGS(2, "a = scale parameter, b = order"); DBL_ARG(a) DBL_ARG(b) OUTPUT(gsl_ran_erlang (r, a, b)); } else if (NAME("exponential")) { ARGS(1, "mu = mean value"); DBL_ARG(mu) ; OUTPUT(gsl_ran_exponential (r, mu)); } else if (NAME("exppow")) { ARGS(2, "a = scale parameter, b = power (1=exponential, 2=gaussian)"); DBL_ARG(a) ; DBL_ARG(b) ; OUTPUT(gsl_ran_exppow (r, a, b)); } else if (NAME("fdist")) { ARGS(2, "nu1, nu2 = degrees of freedom parameters"); DBL_ARG(nu1) ; DBL_ARG(nu2) ; OUTPUT(gsl_ran_fdist (r, nu1, nu2)); } else if (NAME("flat")) { ARGS(2, "a = lower limit, b = upper limit"); DBL_ARG(a) ; DBL_ARG(b) ; OUTPUT(gsl_ran_flat (r, a, b)); } else if (NAME("gamma")) { ARGS(2, "a = order, b = scale"); DBL_ARG(a) ; DBL_ARG(b) ; OUTPUT(gsl_ran_gamma (r, a, b)); } else if (NAME("gaussian")) { ARGS(1, "sigma = standard deviation"); DBL_ARG(sigma) ; OUTPUT(gsl_ran_gaussian (r, sigma)); } else if (NAME("gaussian-tail")) { ARGS(2, "a = lower limit, sigma = standard deviation"); DBL_ARG(a) ; DBL_ARG(sigma) ; OUTPUT(gsl_ran_gaussian_tail (r, a, sigma)); } else if (NAME("ugaussian")) { ARGS(0, "unit gaussian, no parameters required"); OUTPUT(gsl_ran_ugaussian (r)); } else if (NAME("ugaussian-tail")) { ARGS(1, "a = lower limit"); DBL_ARG(a) ; OUTPUT(gsl_ran_ugaussian_tail (r, a)); } else if (NAME("bivariate-gaussian")) { ARGS(3, "sigmax = x std.dev., sigmay = y std.dev., rho = correlation"); DBL_ARG(sigmax) ; DBL_ARG(sigmay) ; DBL_ARG(rho) ; OUTPUT2(gsl_ran_bivariate_gaussian (r, sigmax, sigmay, rho, &x, &y), x, y); } else if (NAME("dir-2d")) { OUTPUT2(gsl_ran_dir_2d (r, &x, &y), x, y); } else if (NAME("dir-3d")) { OUTPUT3(gsl_ran_dir_3d (r, &x, &y, &z), x, y, z); } else if (NAME("dir-nd")) { double *xarr; ARGS(1, "n1 = number of dimensions of hypersphere"); INT_ARG(n1) ; xarr = (double *)malloc(n1*sizeof(double)); for(i = 0; i < n; i++) { gsl_ran_dir_nd (r, n1, xarr) ; for (j = 0; j < n1; j++) { if (j) putchar(' '); printf("%g", xarr[j]) ; } putchar('\n'); } ; free(xarr); } else if (NAME("geometric")) { ARGS(1, "p = bernoulli trial probability of success"); DBL_ARG(p) ; INT_OUTPUT(gsl_ran_geometric (r, p)); } else if (NAME("gumbel1")) { ARGS(2, "a = order, b = scale parameter"); DBL_ARG(a) ; DBL_ARG(b) ; OUTPUT(gsl_ran_gumbel1 (r, a, b)); } else if (NAME("gumbel2")) { ARGS(2, "a = order, b = scale parameter"); DBL_ARG(a) ; DBL_ARG(b) ; OUTPUT(gsl_ran_gumbel2 (r, a, b)); } else if (NAME("hypergeometric")) { ARGS(3, "n1 = tagged population, n2 = untagged population, t = number of trials"); INT_ARG(n1) ; INT_ARG(n2) ; INT_ARG(t) ; INT_OUTPUT(gsl_ran_hypergeometric (r, n1, n2, t)); } else if (NAME("laplace")) { ARGS(1, "a = scale parameter"); DBL_ARG(a) ; OUTPUT(gsl_ran_laplace (r, a)); } else if (NAME("landau")) { ARGS(0, "no arguments required"); OUTPUT(gsl_ran_landau (r)); } else if (NAME("levy")) { ARGS(2, "c = scale, a = power (1=cauchy, 2=gaussian)"); DBL_ARG(c) ; DBL_ARG(a) ; OUTPUT(gsl_ran_levy (r, c, a)); } else if (NAME("levy-skew")) { ARGS(3, "c = scale, a = power (1=cauchy, 2=gaussian), b = skew"); DBL_ARG(c) ; DBL_ARG(a) ; DBL_ARG(b) ; OUTPUT(gsl_ran_levy_skew (r, c, a, b)); } else if (NAME("logarithmic")) { ARGS(1, "p = probability"); DBL_ARG(p) ; INT_OUTPUT(gsl_ran_logarithmic (r, p)); } else if (NAME("logistic")) { ARGS(1, "a = scale parameter"); DBL_ARG(a) ; OUTPUT(gsl_ran_logistic (r, a)); } else if (NAME("lognormal")) { ARGS(2, "zeta = location parameter, sigma = scale parameter"); DBL_ARG(zeta) ; DBL_ARG(sigma) ; OUTPUT(gsl_ran_lognormal (r, zeta, sigma)); } else if (NAME("negative-binomial")) { ARGS(2, "p = probability, a = order"); DBL_ARG(p) ; DBL_ARG(a) ; INT_OUTPUT(gsl_ran_negative_binomial (r, p, a)); } else if (NAME("pareto")) { ARGS(2, "a = power, b = scale parameter"); DBL_ARG(a) ; DBL_ARG(b) ; OUTPUT(gsl_ran_pareto (r, a, b)); } else if (NAME("pascal")) { ARGS(2, "p = probability, n = order (integer)"); DBL_ARG(p) ; INT_ARG(N) ; INT_OUTPUT(gsl_ran_pascal (r, p, N)); } else if (NAME("poisson")) { ARGS(1, "mu = scale parameter"); DBL_ARG(mu) ; INT_OUTPUT(gsl_ran_poisson (r, mu)); } else if (NAME("rayleigh")) { ARGS(1, "sigma = scale parameter"); DBL_ARG(sigma) ; OUTPUT(gsl_ran_rayleigh (r, sigma)); } else if (NAME("rayleigh-tail")) { ARGS(2, "a = lower limit, sigma = scale parameter"); DBL_ARG(a) ; DBL_ARG(sigma) ; OUTPUT(gsl_ran_rayleigh_tail (r, a, sigma)); } else if (NAME("tdist")) { ARGS(1, "nu = degrees of freedom"); DBL_ARG(nu) ; OUTPUT(gsl_ran_tdist (r, nu)); } else if (NAME("weibull")) { ARGS(2, "a = scale parameter, b = exponent"); DBL_ARG(a) ; DBL_ARG(b) ; OUTPUT(gsl_ran_weibull (r, a, b)); } else { fprintf(stderr,"Error: unrecognized distribution: %s\n", name) ; } return 0 ; }
int sock_sim(double prior_r,double prior_p,double alpha,double beta,double obs_paired,double obs_odd,double *BigVector,int iter){ int nthreads; //variables, gsl rng initiation int i,j,match_count,n_picked; unsigned int n_socks; double prop_pairs,n_pairs,n_odd,prior_n; double obs_total = obs_paired + obs_odd; prior_n = prior_r - 1; match_count = 0; double temp_paired,temp_odd,temp_pairs; //setup gsl random seed const gsl_rng_type * T; gsl_rng_env_setup(); T = gsl_rng_default; r = gsl_rng_alloc(T); #pragma omp parallel for for(i=0;i<iter;i++){ //sample, get n_pairs and n_odd n_socks = gsl_ran_negative_binomial(r,prior_p,prior_n); prop_pairs = gsl_ran_beta(r,alpha,beta); n_pairs = round(floor(.5*n_socks)*prop_pairs); n_odd = n_socks - 2*n_pairs; //make generated population double *gen_pop = (double *)malloc(sizeof(double)*n_socks); for(j=0;j<n_pairs;j++){ gen_pop[2*j] = (double) j; gen_pop[(2*j)+1] = (double) j; } for(j=2*n_pairs;j<n_socks;j++){ gen_pop[j]= (double) j; } //get generated sample size if(obs_total <= n_socks){ n_picked = (int) obs_total; }else{ n_picked = n_socks; } //get sample vector double *gen_samp = (double *)malloc(sizeof(double)*n_picked); //count pairs //sample from generated population gsl_ran_choose(r,gen_samp,n_picked,gen_pop,n_socks,sizeof(double)); //sort sample gsl_sort(gen_samp,1,n_picked); //count the number of pairs/odd in sample temp_pairs = 0.; temp_odd = 1.; for(j=1;j<n_picked;j++){ if(gen_samp[j] == gen_samp[j-1]){ temp_pairs = temp_pairs + 1; temp_odd = temp_odd - 1; continue; }else{ temp_odd = temp_odd + 1; } } temp_paired = 2*temp_pairs; //allocate big vector BigVector[5*i] = (double) n_socks; BigVector[(5*i) + 1] = n_pairs; BigVector[(5*i) + 2] = n_odd; BigVector[(5*i) + 3] = prop_pairs; //counter if(temp_odd==obs_odd && temp_paired==obs_paired){ match_count = match_count + 1; BigVector[(5*i) + 4] = 1.; continue; } else{ BigVector[(5*i) + 4] = 0.; continue; } //free the temp allocated things free(gen_pop); free(gen_samp); } gsl_rng_free(r); return(match_count); }