コード例 #1
0
void test_multinomial(void){
    double p[SIZE] = { .1, .2, .3, .4 };
    int n[SIZE] = { 0, 0, 0, 0 };
    int numdraws = 100;
    double prob;

    gsl_ran_multinomial(rng, SIZE, numdraws, p, n); 

    printf("gsl_ran_multinomial\t%d\t", numdraws);
    print_double_array(p, SIZE);
    printf("\t");
    print_int_array(n, SIZE);
    printf("\n");

    prob = gsl_ran_multinomial_pdf(SIZE, p, n); 
    printf("gsl_ran_multinomial_pdf\t");
    print_double_array(p, SIZE);
    printf("\t");
    print_int_array(n, SIZE);
    printf("\t%.12f\n", prob);

    prob = gsl_ran_multinomial_lnpdf(SIZE, p, n); 
    printf("gsl_ran_multinomial_lnpdf\t");
    print_double_array(p, SIZE);
    printf("\t");
    print_int_array(n, SIZE);
    printf("\t%.12f\n", prob);
}
コード例 #2
0
ファイル: cgslrandom.cpp プロジェクト: mattjj/gslrandom
void BasicRNG::multinomial(int K,
                           unsigned int N,
                           const double p[],
                           unsigned int n[])
{
    gsl_ran_multinomial(r, K, N, p, n);
}
コード例 #3
0
ファイル: auxiliary.c プロジェクト: rforge/epidemics
/* the sum of all values being N.*/
struct vec_int * sample_int_multinom(int N, int I, double * proba, gsl_rng * rng){
	struct vec_int * out = create_vec_int(I);

	gsl_ran_multinomial (rng, I, N, proba, (unsigned int *) out->values);

	/* free local pointers and return result */
	return out;
}
コード例 #4
0
ファイル: source.cpp プロジェクト: szarma/poprest
void Source::reproduction(const gsl_rng *rand){
        
        assign_fitness();

        gsl_ran_multinomial(rand, pop_size, pop_size, fitness, off_numbers);

        next_generation(rand);
        mutate_population(rand);
}
コード例 #5
0
ファイル: sampling.c プロジェクト: rforge/epidemics
/* the metapopulation. */
struct sample * draw_sample(struct metapopulation *in, int n, struct param *par){
	int i, j, *nIsolatesPerPop, count;
	double *nAvailPerPop;
	struct pathogen *ppat;

	/* create pointer to pathogens */
	struct sample *out=create_sample(n);

	/* escape if no isolate available */
	if(get_total_ninf(in) + get_total_nexp(in) < 1){
		printf("\nMetapopulation without infections - sample will be empty.\n");
		out->n = 0;
		out->pathogens = NULL;
		out->popid = NULL;
		return out;
	}

	/* get nb of isolates available in each population */
	nAvailPerPop = (double *) calloc(get_npop(in), sizeof(double));
	if(nAvailPerPop == NULL){
		fprintf(stderr, "\n[in: population.c->draw_sample]\nNo memory left to isolate available pathogens. Exiting.\n");
		exit(1);
	}

	for(j=0;j<get_npop(in);j++){
		nAvailPerPop[j] = (double) get_nexp(get_populations(in)[j]) + get_ninf(get_populations(in)[j]);
	}

	/* get nb of isolates sampled in each population*/
	nIsolatesPerPop = (int *) calloc(get_npop(in), sizeof(int));
	if(nIsolatesPerPop == NULL){
		fprintf(stderr, "\n[in: population.c->draw_sample]\nNo memory left to isolate available pathogens. Exiting.\n");
		exit(1);
	}

	gsl_ran_multinomial(par->rng, get_npop(in), n, nAvailPerPop, (unsigned int *) nIsolatesPerPop);

	/* fill in the sample pathogens */
	count = 0;
	for(j=0;j<get_npop(in);j++){ /* for each population */
		for(i=0;i<nIsolatesPerPop[j];i++){
			ppat = select_random_pathogen(get_populations(in)[j], par);
			/* free_pathogen(out->pathogens[count]); */
			out->pathogens[count] = reconstruct_genome(ppat);
			out->popid[count++] = j;
		}
	}

	/* free local pointers */
	free(nAvailPerPop);
	free(nIsolatesPerPop);

	return out;
} /* end draw_sample */
コード例 #6
0
double
test_multinomial_large (void)
{
  const unsigned int sum_n = BINS;
  unsigned int n[MULTI_DIM];
  const double p[MULTI_DIM] = { 0.2, 0.20, 0.17, 0.14, 0.12,
                                0.07, 0.05, 0.04, 0.01, 0.00  };

  gsl_ran_multinomial ( r_global, MULTI_DIM, sum_n, p, n);

  return n[0];
}
コード例 #7
0
double
test_multinomial (void)
{
  const size_t K = 3;
  const unsigned int sum_n = BINS;
  unsigned int n[3];
  /* Test use of weights instead of probabilities. */
  const double p[] = { 2., 7., 1.};

  gsl_ran_multinomial ( r_global, K, sum_n, p, n);

  return n[0];
}
コード例 #8
0
ファイル: NPLCM_CR_Basic_Freq.cpp プロジェクト: cran/LCMCR
inline
void CNPLCM_CR_Basic_Freq::sam_z0x0(){
	std::vector<double> table_z(par->K);
	std::vector<unsigned int> counts(par->K);
	for (int k = 0; k < par->K; k++){
		double p = par->nuK[k] ;
		for(int j = 0; j < par->J; j++){
			p *= 1.0 - par->lambdaJK[j][k];
		}
		table_z[k] = p;
	}
	gsl_ran_multinomial(r, par->K, par->n0, &(table_z[0]), (unsigned int*)(par->count0K));
}
コード例 #9
0
ファイル: mlgsl_randist.c プロジェクト: ptrf/LCDE
/* MULTINOMIAL */
CAMLprim value ml_gsl_ran_multinomial(value rng, value n, value p)
{
  const size_t K = Double_array_length(p);
  LOCALARRAY(unsigned int, N, K); 
  value r;
  gsl_ran_multinomial(Rng_val(rng), K, Int_val(n), Double_array_val(p), N);
  {
    register int i;
    r = alloc(K, 0);
    for(i=0; i<K; i++)
      Store_field(r, i, Val_int(N[i]));
  }
  return r;
}
コード例 #10
0
ファイル: sampleCRFDishsMex.c プロジェクト: asaluja/im3f
int sampleDishFull(const uint32_t* examps, const double* resids, const double* mC, const double* muC, const double* muD, const uint32_t* kU, const double* nC, const double* nD, const double betaM, const double c0, const double sigmaSqd, const double invsigmaSqd, const double invsigmaSqd0, const int KM, const int numExamples, const gsl_rng* rng){
  double logmult[KM+1]; //initialize to 0
  for (int kk = 0; kk < KM; kk++ ){
    logmult[kk] = 0; 
    for (int ee_i = 0; ee_i < numExamples; ee_i++ ){
      uint32_t ee = examps[ee_i] - 1;
      double residC = resids[ee] - muD[kU[ee]-1]; 
      double sigmaStarSqd = getSigmaStarSqd(kk, kU[ee]-1, nC, nD, sigmaSqd, invsigmaSqd, invsigmaSqd0); 
      logmult[kk] = logmult[kk] - pow(residC - muC[kk], 2) / (2 * sigmaStarSqd) - log(sigmaStarSqd) / 2; 
    }
  }
  logmult[KM] = 0; 
  for (int ee_i = 0; ee_i < numExamples; ee_i++){
    uint32_t ee = examps[ee_i] - 1;
    double residC = resids[ee] - muD[kU[ee]-1];
    double sigmaDSqd = getSigmaDSqd(kU[ee]-1, nD, invsigmaSqd, invsigmaSqd0);
    //DONGZHEN To do: add sigmaC
    logmult[KM] = logmult[KM] - pow(residC - c0, 2) / (2*(sigmaSqd + sigmaDSqd)) - log(sigmaSqd + sigmaDSqd) / 2;    
  }
  //compute mean, limit max value to counter overflow issues
  double sum = 0; 
  for (int i = 0; i < KM+1; i++ ){ sum += logmult[i]; }
  double average = sum/(KM+1); 
  for (int i = 0; i < KM+1; i++ ){ 
    logmult[i] -= average; //mean shift values
    if (logmult[i] > 30){logmult[i] = 30; } //N.B.: dont hardcode threshold
  }
  double mult[KM+1]; 
  for (int kk = 0; kk < KM; kk++ ){ mult[kk] = mC[kk] * exp(logmult[kk]); }
  mult[KM] = betaM * exp(logmult[KM]); 
  sum = 0; 
  for (int i = 0; i < KM + 1; i++ ){ sum += mult[i]; }
  double multi_norm[KM+1];
  for (int i = 0; i < KM + 1; i++ ){multi_norm[i] = mult[i] / sum; } //need to normalize multinomial
  uint32_t* new_k_sample = (uint32_t*)mxMalloc((KM+1)*sizeof(uint32_t));   //sampling
  gsl_ran_multinomial(rng,(size_t)(KM + 1), 1, multi_norm, new_k_sample); //will return array same length as multi_norm in new_k_sample
  uint32_t new_k = linearSearchInt(new_k_sample, 1, KM+1); 
  if (new_k == -1){ //i.e., we cannot find the sampled idx  
    mexPrintf("Error! Cannot find sampled idx for new dish\n");
    for (int i = 0; i < KM+1; i++ )
      mexPrintf("multi_norm[%d]: %.10f; ", i, multi_norm[i]);
    mexPrintf("\n"); 
  }
  mxFree(new_k_sample); 
  return new_k;
}
コード例 #11
0
ファイル: Colony.cpp プロジェクト: szarma/poprest
void Colony::reproduction(const gsl_rng *rand){
        int k,j,new_pop_size;
        double pop_fitness;
        assign_fitness();

        pop_fitness = 0.;
        for(j=0;j<pop_size;j++)
            {
            pop_fitness += fitness[j];
            }
        pop_fitness = pop_fitness*max_fitness;
        new_pop_size = gsl_ran_poisson(rand,pop_fitness);
//	printf("fitness: %lf\tnew pop size: %i\n", pop_fitness, new_pop_size);

        if (new_pop_size==0)
            {
             printf("extinct\n");
            exit(0);
            }
        if (new_pop_size>limit)
            {
            printf("established\n");
            exit(0);
            }

        gsl_ran_multinomial(rand, pop_size, new_pop_size, fitness, off_numbers);

        next_generation(rand);
        pop_size = new_pop_size;
        mutate_population(rand);

        for(j=pop_size;j<limit;j++)
            {
            for(k=0; k<n_del; k++)
                {
                del_matrix[j][k] = 0;
                }
            for(k=0; k<n_env; k++)
                {
                env_matrix[j][k] = 0;
                }
            }
};
コード例 #12
0
ファイル: libranddist.c プロジェクト: CNMAT/CNMAT-Externs
void librdist_multinomial(gsl_rng *rng, int argc, void *argv, int bufc, float *buf){
	t_atom *av = (t_atom *)argv;
	int i, j;
	size_t K = argc - 1;
	if(K < 1){
		return;
	}
	unsigned int N = librdist_atom_getlong(av);
	double p[K];
	unsigned int n[K];
	for(i = 0; i < K; i++){
		p[i] = atom_getfloat(av + i + 1);
	}

	for(j = 0; j < floor(bufc / K); j++){
		gsl_ran_multinomial(rng, K, N, p, n);
		for(i = 0; i < K; i++)
			buf[i] = (float)n[i];
	}
}
コード例 #13
0
ファイル: NPLCM_CR_Basic_Freq.cpp プロジェクト: cran/LCMCR
inline
void CNPLCM_CR_Basic_Freq::sam_countzIK(){
	double probs[1000];//should have K elements
	double prod = 1.0;
	for (int m = 0; m < data->ncells; m++){
		for (int k = 0; k < par->K; k++){
			prod= par->nuK[k];
			for (int j = 0; j < par->J; j++){
				prod *= data->cells[m][j] == 1 ? par->lambdaJK[j][k] : 	1.0 - par->lambdaJK[j][k];
			}
			probs[k] = prod;
		}
		//sample!
		if (data->freqM[m] > 1){
			gsl_ran_multinomial(r, par->K, data->freqM[m], probs, (unsigned int*)(par->count_zIK[m]));
		} else {
			int z = dan_multinomial_1(r, par->K, probs, false);
			std::fill(par->count_zIK[m], par->count_zIK[m] + par->K, 0);
			par->count_zIK[m][z] = 1;
		}
	}
}
コード例 #14
0
void
test_multinomial_moments (void)
{
  const unsigned int sum_n = 100;

  const double p[MULTI_DIM] ={ 0.2, 0.20, 0.17, 0.14, 0.12,
                               0.07, 0.05, 0.02, 0.02, 0.01 };

  unsigned int  x[MULTI_DIM];
  double x_sum[MULTI_DIM];

  double mean, obs_mean, sd, sigma;
  int status, k, n;

  for (k = 0; k < MULTI_DIM; k++)
    x_sum[k] =0.0;

  for (n = 0; n < N; n++)
    {
      gsl_ran_multinomial (r_global, MULTI_DIM, sum_n, p, x);
      for (k = 0; k < MULTI_DIM; k++)
        x_sum[k] += x[k];
    }

  for (k = 0; k < MULTI_DIM; k++)
    {
      mean = p[k] * sum_n;
      sd = p[k] * (1.-p[k]) * sum_n;

      obs_mean = x_sum[k] / N;
      sigma = sqrt ((double) N) * fabs (mean - obs_mean) / sd;

      status = (sigma > 3.0);

      gsl_test (status,
                "test gsl_ran_multinomial: mean (%g observed vs %g expected)",
                obs_mean, mean);
    }
}
コード例 #15
0
ファイル: BalSelSims.c プロジェクト: MattHartfield/BalSelSims
/* Initialising NEUTRAL allele */
void neutinit(double *geninit, const gsl_rng *r){

	double *probin = calloc(4,sizeof(double));					/* Probability inputs, determine location of neutral allele */
	unsigned int *probout = calloc(4,sizeof(unsigned int));		/* Output from multinomial sampling */
	
	/* Basic idea: g11 at freq p^2; g12 at freq 2pq; g22 at freq q^2.
	So weighted sampling to determine which genotype the neutral allele arises on
	*/
	
	/* Prob definitions */
	*(probin + 0) = *(geninit + 0);
	*(probin + 1) = (*(geninit + 1))/2.0;
	*(probin + 2) = (*(geninit + 1))/2.0;
	*(probin + 3) = *(geninit + 4);
	
	gsl_ran_multinomial(r,4,1,probin,probout);
	
	/* Redefining genotypes depending on outcome */
	if(*(probout + 0) == 1){
		*(geninit + 0) = (*(geninit + 0)) - 1/(1.0*N);
		*(geninit + 2) = (*(geninit + 2)) + 1/(1.0*N);
	}
	else if(*(probout + 1) == 1){
		*(geninit + 1) = (*(geninit + 1)) - 1/(1.0*N);
		*(geninit + 3) = (*(geninit + 3)) + 1/(1.0*N);	
	}
	else if(*(probout + 2) == 1){
		*(geninit + 1) = (*(geninit + 1)) - 1/(1.0*N);
		*(geninit + 5) = (*(geninit + 5)) + 1/(1.0*N);	
	}
	else if(*(probout + 3) == 1){
		*(geninit + 4) = (*(geninit + 4)) - 1/(1.0*N);
		*(geninit + 6) = (*(geninit + 6)) + 1/(1.0*N);	
	}
	
 	free(probout);
	free(probin);
	
}	/* End of gen initiation routine */
コード例 #16
0
ファイル: pidrtpcrsim.cpp プロジェクト: cbg-ethz/PrimerID
std::vector<intType> ran_mult_multinomial(const std::vector<uint64_t>& pop, intType sample_size, const gsl_rng* r, intType min_coverage = 0)
{
    std::vector<intType> sample;
    sample.resize(bins);

    // 1.) first generate N_reads samples, not all of which will satisfy >= min_coverage
    std::vector<double> p_PCR(pop.begin(), pop.end());
    gsl_ran_multinomial(r, bins, sample_size, p_PCR.data(), sample.data());

    uint64_t valid_samples = 0;
    for (const auto& i : sample) {
        if (i >= min_coverage) {
            valid_samples += i;
        }
    }

    // 2.) proceed to add remaining samples
    if (valid_samples < sample_size) {
        gsl_ran_discrete_t* categorical_distrib = gsl_ran_discrete_preproc(bins, p_PCR.data());
        intType ind;

        while (valid_samples < sample_size) {
            ind = gsl_ran_discrete(r, categorical_distrib);
            ++sample[ind];

            if (sample[ind] > min_coverage) {
                ++valid_samples;
            }
            else {
                if (sample[ind] == min_coverage)
                    valid_samples += min_coverage;
            }
        }

        gsl_ran_discrete_free(categorical_distrib);
    }

    return sample;
}
コード例 #17
0
ファイル: BalSelSims.c プロジェクト: MattHartfield/BalSelSims
/* Main program */
int main(int argc, char *argv[]){
	unsigned int g, i; 				/* Counters. Reps counter, geno counter */
	unsigned int reps;				/* Length of simulation (no. of introductions of neutral site) */
	double Bcheck = 0;				/* Frequency of B after each reproduction */
	double Acheck = 0;				/* Frequency of polymorphism */
	double Hsum = 0;				/* Summed heterozygosity over transit time of neutral allele */
	
	/* GSL random number definitions */
	const gsl_rng_type * T; 
	gsl_rng * r;
	
	/* This reads in data from command line. */
	if(argc != 8){
		fprintf(stderr,"Invalid number of input values.\n");
		exit(1);
	}
	N = strtod(argv[1],NULL);
	s = strtod(argv[2],NULL);
	rec = strtod(argv[3],NULL);
	sex = strtod(argv[4],NULL);
	self = strtod(argv[5],NULL);
	gc = strtod(argv[6],NULL);
	reps = strtod(argv[7],NULL);
	
	/* Arrays definition and memory assignment */
	double *genotype = calloc(10,sizeof(double));				/* Genotype frequencies */
	unsigned int *gensamp = calloc(10,sizeof(unsigned int));	/* New population samples */
	  
	/* create a generator chosen by the 
    environment variable GSL_RNG_TYPE */
     
	gsl_rng_env_setup();
	if (!getenv("GSL_RNG_SEED")) gsl_rng_default_seed = time(0);
	T = gsl_rng_default;
	r = gsl_rng_alloc(T);
	
	/* Initialising genotypes */
	geninit(genotype);
    
    /* Run simulation for 2000 generations to create a burn in */
    for(g = 0; g < 2000; g++){

    	/* Selection routine */
    	selection(genotype);
    	
    	/* Reproduction routine */
    	reproduction(genotype);
    	
       	/* Gene conversion routine */
       	gconv(genotype);
       	
       	/* Sampling based on new frequencies */
       	gsl_ran_multinomial(r,10,N,genotype,gensamp);
       	for(i = 0; i < 10; i++){
			*(genotype + i) = (*(gensamp + i))/(1.0*N);
       	}
       	
       	/* Printing out results (for testing) */
		/*
	   	for(i = 0; i < 10; i++){
			printf("%.10lf ", *(genotype + i));
		}
		printf("\n");
		*/
    }
    
	/* Reintroducing neutral genotype, resetting hap sum */	
	neutinit(genotype,r);
    Bcheck = ncheck(genotype);
    Hsum = Bcheck*(1-Bcheck);
    /* printf("%.10lf %.10lf\n",Bcheck,Hsum); */
    
    /* Introduce and track neutral mutations 'reps' times */
    g = 0;
    while(g < reps){

    	/* Selection routine */
    	selection(genotype);
    	
    	/* Reproduction routine */
    	reproduction(genotype);
    	
    	/* Gene conversion routine */
       	gconv(genotype);
       	
    	/* Sampling based on new frequencies */
       	gsl_ran_multinomial(r,10,N,genotype,gensamp);
       	for(i = 0; i < 10; i++){
       		*(genotype + i) = (*(gensamp + i))/(1.0*N);
       	}
       	
       	/* Checking state of haplotypes: if B fixed reset so can start fresh next time */
		Bcheck = ncheck(genotype);
		Hsum += Bcheck*(1-Bcheck);
		/* printf("%.10lf %.10lf\n",Bcheck,Hsum); */
		
		/* If polymorphism fixed then abandon simulation */
       	Acheck = pcheck(genotype);
       	if(Acheck == 0){
       		g = reps;
       	}
       	
       	if(Bcheck == 0 || Bcheck == 1){
       		printf("%.10lf\n",Hsum);
       		g++;
       		/* printf("Rep Number %d\n",g); */
       		
       		if(Bcheck == 1){
       			/* Reset genotypes so B becomes ancestral allele */
       			*(genotype + 0) = *(genotype + 7);
       			*(genotype + 1) = *(genotype + 8);
       			*(genotype + 4) = *(genotype + 9);
       			*(genotype + 7) = 0;
       			*(genotype + 8) = 0;
       			*(genotype + 9) = 0;      			
       		}
     		 
     		/* Reintroducing neutral genotype, resetting hap sum */     		
	    	neutinit(genotype,r);
			Bcheck = ncheck(genotype);
       		Hsum = Bcheck*(1-Bcheck);
       	}
    
	}	/* End of simulation */
	
	
	/* Freeing memory and wrapping up */
 	gsl_rng_free(r);
 	free(gensamp);
	free(genotype);
	/* printf("The End!\n"); */
	return 0;
}
コード例 #18
0
ファイル: pidrtpcrsim.cpp プロジェクト: cbg-ethz/PrimerID
void run_simulation(int thread_id, intVector& rank_abundance, intVector& rank_occurrence)
{
    gsl_rng* r = gsl_rng_alloc(gsl_rng_mt19937);
    gsl_rng_set(r, random_seed());
    std::default_random_engine generator(random_seed());

    // RT
    intVector sample_after_RT(bins);

    // PCR
    uint64_t no_PCR_molecules;
    std::vector<uint64_t> sample_after_PCR(bins);

    // Sequencing sample
    intVector sampler_after_seq(bins);

    for (int i = 1; i <= (N_trials - 1 - thread_id) / number_threads + 1; ++i) {
        if ((thread_id == 0) && (i * number_threads % 10 == 0))
            std::cout << "Trial no.: " << i* number_threads << '\n';

        // 1.) simulate RT
        gsl_ran_multinomial(r, bins, N_RT, prob_RT.data(), sample_after_RT.data());

        // 2.) simulate PCR (branching process)
        no_PCR_molecules = 0;
        for (int j = 0; j < bins; ++j) {
            if (sample_after_RT[j]) {
                sample_after_PCR[j] = sample_after_RT[j];

                // stochastic amplification
                for (int k = 0; k < cycles; ++k) {
                    sample_after_PCR[j] += gsl_ran_binomial(r, p, sample_after_PCR[j]);
                }
                no_PCR_molecules += sample_after_PCR[j];
            }
            else {
                sample_after_PCR[j] = 0;
            }
        }

        if (thread_id == 0) {
            average_PCR_molecules += no_PCR_molecules;
        }

        // 3.) sequencing sample
        if (no_PCR_molecules > 100 * N_reads) {
            // multinomial approximation is good
            std::sort(sample_after_PCR.begin(), sample_after_PCR.end(), std::greater<intType>());
            sampler_after_seq = ran_mult_multinomial(sample_after_PCR, N_reads, r, min_coverage);
            ++used_with_replacement;
        }
        else {
            // multinomial approximation is not good enough!
            sampler_after_seq = ran_mult_hypergeometric(sample_after_PCR, N_reads, r, generator, min_coverage);
            ++used_without_replacement;
        }

        std::sort(sampler_after_seq.begin(), sampler_after_seq.end(), std::greater<intType>());

        // 4.) enter rankings
        for (int j = 0; j < rank_cutoff; ++j) {
            if (sampler_after_seq[j]) {
                rank_abundance[j] += sampler_after_seq[j];
                ++rank_occurrence[j];
            }
        }
    }

    gsl_rng_free(r);
}
コード例 #19
0
void reproduction(int source_colony, 
		  struct pop society,
		  int   *ptr_N,
		  const  gsl_rng *rand){

	int k,j;
	double *fitness;
	double pop_fitness;
	unsigned int N_new;
	unsigned int *tmp;
	int picked_father;
	int counter;
	int **ptr_offspring_matrix_del; /*this is the matrix into which the genotypes of the offspring will be stored*/
	int **ptr_offspring_matrix_env;

	ptr_offspring_matrix_del=make_matrix(society.size_max, LOCI_DEL);
	ptr_offspring_matrix_env=make_matrix(society.size_max, LOCI_ENV);

	fitness = malloc(society.size_max*sizeof(double));
	tmp = malloc(society.size_max*sizeof(double));

	if(fitness==NULL){
		fprintf(stderr, "ERROR: memory allocation did not work\n");
		fflush(stderr);
		abort();
	}

	if(fitness==NULL){
		fprintf(stderr, "ERROR: memory allocation did not work\n");
		fflush(stderr);
		abort();
	}

	for(k=(*ptr_N);k<society.size_max;k++){
                fitness[k]=0;
        }

        pop_fitness=0;

	/*calculate the fitness of individuals*/


	pop_fitness=calculate_fitness(ptr_N, fitness, society);
	
	/*determine the number of individuals in the next generation*/
	
    	if(source_colony == 0){		
		N_new = gsl_ran_poisson(rand, pop_fitness);
	}
	
	else{
	
    		if(source_colony == 1){		
			N_new = *ptr_N;	
		}

		else{
			fprintf(stderr, "ERROR: neither colony nor source\n");
			fflush(stderr);
			abort();
		}
	}



	/*find the mothers: tmp[k] gives the number of offspring of individual k*/
 	gsl_ran_multinomial(rand, society.size_max, N_new, fitness, tmp);
        
        	
	/*now we pick a father for each offspring and determine the genotype of the offspring*/

	counter=0;	
	picked_father=0;

	for(k=0;k<*ptr_N;k++){
		for(j=0;j<tmp[k];j++){
			picked_father = pick_father(rand, ptr_N, fitness, k);	
			form_offspring(rand, k, picked_father, counter, society.ptr_matrix_del, society.ptr_matrix_env, ptr_offspring_matrix_del, ptr_offspring_matrix_env);
			counter=counter+1;
		}
	}


	/*the population size gets updated*/

	*ptr_N=N_new;

	if(N_new > society.size_max){
		fprintf(stderr, "ERROR: population overgrew its limits! \n");
		fflush(stderr);
		abort();
	}
	
	/*the population matrix gets updated by the offspring matrix*/

	/*for(j=0;j<society.size_max;j++){
		for(k=0;k<LOCI_DEL;k++){
			society.ptr_matrix_del[j][k]=ptr_offspring_matrix_del[j][k];
		}
		for(k=0;k<LOCI_ENV;k++){
			society.ptr_matrix_env[j][k]=ptr_offspring_matrix_env[j][k];
		}
	}*/
	
	/*finally, we mutate all the entries in the population matrix*/
	
	for(j=0;j<*ptr_N;j++){
		for(k=0;k<LOCI_DEL;k++){
			society.ptr_matrix_del[j][k] = mutate(rand, ptr_offspring_matrix_del[j][k]);
		}
		for(k=0;k<LOCI_ENV;k++){
			society.ptr_matrix_env[j][k] = mutate(rand, ptr_offspring_matrix_env[j][k]);
		}
	}
	
	for(j=*ptr_N;j<society.size_max;j++){
		for(k=0;k<LOCI_DEL;k++){
			society.ptr_matrix_del[j][k] = 0;
		}
		for(k=0;k<LOCI_ENV;k++){
			society.ptr_matrix_env[j][k] = 0;
		}
	}

	free(ptr_offspring_matrix_del);
	free(ptr_offspring_matrix_env);

}
コード例 #20
0
void Model::simulate(std::vector<double> & model_params, std::vector<std::string> & param_names, Trajectory * traj, int start_dt, int end_dt, double step_size, int total_dt, gsl_rng * rng) {
    if ((traj->get_state(0)+traj->get_state(1)) < 1.0) {
        return;
    }
    double R0_0=1.0;
    double R0_1=1.0;
    double R0_2=1.0;
    double R0_3=1.0;
    double R0_4=1.0;
    double R0_5=1.0;
    double R0_T0=0.0;
    double R0_T1=100000.0;
    double R0_T2=100000.0;
    double R0_T3=100000.0;
    double R0_T4=100000.0;
    double k=1.0;
    double alpha=1.0;
    double scale=1.0;
    // /* For slightly faster implementation, call parameters by index
    for (int i=0; i!=param_names.size(); ++i) {
        if (param_names[i]=="R0_0") R0_0 = model_params[i];
        if (param_names[i]=="R0_1") R0_1 = model_params[i];
        if (param_names[i]=="R0_2") R0_2 = model_params[i];
        if (param_names[i]=="R0_3") R0_0 = model_params[i];
        if (param_names[i]=="R0_4") R0_0 = model_params[i];
        if (param_names[i]=="R0_5") R0_0 = model_params[i];
        if (param_names[i]=="R0_T0") R0_T0 = model_params[i];
        if (param_names[i]=="R0_T1") R0_T1 = model_params[i];
        if (param_names[i]=="R0_T2") R0_T2 = model_params[i];
        if (param_names[i]=="R0_T3") R0_T3 = model_params[i];
        if (param_names[i]=="R0_T4") R0_T4 = model_params[i];
        if (param_names[i]=="k") k = model_params[i];
        if (param_names[i]=="alpha") alpha = model_params[i];
        if (param_names[i]=="scale") scale = model_params[i];
    }
    double R0_now = 0.0;
    double recoveries=0.0;
    double new_infections=0.0;
    double durI = 0.0;
    double ran_unif_num1, ran_unif_num2;
    if (custom_prob.size()==0) set_custom_prob(alpha, scale);
    if (start_dt < step_size) {  // Set initial number of infected
        traj->resize_recoveries(total_dt);
        int init_inf = (int)round(model_params[14]);
        traj->set_state(init_inf, 0);
        for (int i=0; i!=init_inf; ++i) {
//            durI = gsl_ran_gamma(rng, alpha, scale);
            ran_unif_num1 = gsl_ran_flat(rng, 0.0000001, 1);
            ran_unif_num2 = gsl_ran_flat(rng, 0.0000001, 1);
            durI = -log(ran_unif_num1)*scale-log(ran_unif_num2)*scale;
            durI = (int)(durI/365.0/step_size);
            traj->add_recovery_time(durI);
        }
    }
    double num_infected = traj->get_state(0);
    for (int t=start_dt; t<end_dt; ++t) {
        //
        // Transitions
        //
        // Recoveries: I --> R
        recoveries = traj->num_recover_at(t-start_dt);
        if (recoveries > 100000.0) { // If the epidemic is too large, set num_infected to 0, so that likelihood is 0.
            num_infected = 0.0;
            traj->set_traj(0.0, t-start_dt);
        }
        else if (recoveries > 0) {
            traj->set_traj(recoveries, t-start_dt);
            if (t*step_size<(R0_T0)) R0_now = R0_0;
            else if (t*step_size<(R0_T1)) R0_now = R0_1;
            else if (t*step_size<(R0_T2)) R0_now = R0_2;
            else if (t*step_size<(R0_T3)) R0_now = R0_3;
            else if (t*step_size<(R0_T4)) R0_now = R0_4;
            else {
                R0_now = R0_5;
            }
            new_infections = gsl_ran_negative_binomial(rng, k/(k+R0_now), k*recoveries);
            if (new_infections > 1000) {
                std::vector <unsigned int> a (106, 0);
                gsl_ran_multinomial(rng, 106, (unsigned int)new_infections, &custom_prob[0], &a[0]);
                for (int i=0; i!=a.size(); ++i) {
//                    durI = gsl_ran_gamma(rng, alpha, scale);

//                    ran_unif_num1 = gsl_rng_uniform_pos(rng);
//                    ran_unif_num2 = gsl_rng_uniform_pos(rng);
//                    durI = -log(ran_unif_num1)*scale-log(ran_unif_num2)*scale;
//                    durI = (int)(durI/365.0/step_size);
                    
//                    durI = durI_vec[gsl_rng_uniform_int(rng, 1000)];
//                    traj->add_recovery_time(durI+t-start_dt);
                    traj->add_recovery_time(i+t-start_dt, a[i]);
                }
            }
            else if (new_infections > 0) {
                for (int i=0; i!=new_infections; ++i) {
                    ran_unif_num1 = gsl_rng_uniform_pos(rng);
                    ran_unif_num2 = gsl_rng_uniform_pos(rng);
                    durI = -log(ran_unif_num1)*scale-log(ran_unif_num2)*scale;
                    durI = (int)(durI/365.0/step_size);
                    traj->add_recovery_time(durI+t-start_dt);
                }
            }
            num_infected += new_infections - recoveries;
        }
        double curr_coal_rate = 1.0/num_infected;
        // Record 1/N for coalescent rate calculation
        if (num_infected > 0.0) {
            traj->set_traj2(curr_coal_rate*R0_now/(alpha*scale)*(1.0+1.0/k), t-start_dt);
        }
        else {
            traj->set_traj2(0.0, t-start_dt);
            break;
        }
    }
    traj->set_state(num_infected, 0);
    traj->delete_recoveries_before(end_dt-start_dt);
}
コード例 #21
0
ファイル: pvalue.c プロジェクト: lvaruzza/kempbasu
void pvalue(gsl_rng * r,
	    gsl_vector_uint *x,
	    gsl_vector_uint *sums,
	    double *_pvalue,
	    double *_alpha,
	    double *_alpha_score,
	    double *_beta_score,
	    PvalueConfig *config) {

  fprintf(stderr,"pvalue\n");
  assert(x->size == sums->size);

  size_t i;
  size_t dim=x->size;
  unsigned int runs=config->runs;
  unsigned int N=0;
  unsigned int NN=0;

  for(i=0;i<dim;i++) {
    N+=ELT(x,i);
    NN+=ELT(sums,i);
  }
  printf("N=%i\n",N);


  double *p=(double*)malloc(sizeof(double)*dim);

  for(i=0;i<dim;i++) {
    p[i]=ELT(sums,i)*1.0/NN;
  }

  double cutoff = logRV(dim,x,sums,NN);
  fprintf(stderr,"cutoff = %f\n",cutoff);

  double rv;
  unsigned int positives=0;

  //unsigned int *n=(unsigned int*)malloc(sizeof(unsigned int)*dim);

  gsl_vector_uint *n=gsl_vector_uint_alloc(dim);

  for (i = 0; i < runs; i++)  {
    gsl_ran_multinomial (r, dim, N, p, n->data);
    rv=logRV(dim,n,sums,NN);
    if (rv <= cutoff) {
      positives++;
      /*fprintf(multi,"%i %i %i\t%i\n",n->data[0],n->data[1],n->data[2],
	n->data[0]+n->data[1]+n->data[2]);    */
    }
  }

  double pvalue=positives*1.0/runs;

  fprintf(stderr,"%i %i %f",positives,runs,pvalue);

  *_pvalue=pvalue;
  pvalue_alpha_beta(N,4,1,_alpha,_beta_score);
  if (N!=0) {
    *_alpha=0.07/sqrt(N);
  }
  *_alpha_score=1.0-pvalue/(*_alpha);

  fprintf (stderr,"\n");

  free(p);
  //free(n);
  gsl_vector_uint_free(n);
}