Esempio n. 1
0
extern int dist_bernoulli(struct _flow *flow, const double p)
{
#ifdef HAVE_LIBGSL
	gsl_rng * r = flow->r;
	return gsl_ran_bernoulli (r, p);
#else
	return rn_uniform_zero_to_one(flow) <= p;
#endif /* HAVE_LIBGSL */
}
Esempio n. 2
0
void librdist_bernoulli(gsl_rng *rng, int argc, void *argv, int bufc, float *buf){
	t_atom *av = (t_atom *)argv;
	if(argc != librdist_getnargs(ps_bernoulli)){
		return;
	}
	const double p = librdist_atom_getfloat(av);
	int i;
	for(i = 0; i < bufc; i++)
	       	buf[i] = (float)gsl_ran_bernoulli(rng, p);
}
Esempio n. 3
0
rcount nulldist::rand()
{
    if( gsl_ran_bernoulli( rng, a ) ) return 0;

    /* This uses a rejection sampling scheme worked out by Charles Geyer,
     * detailed in his notes "Lower-Truncated Poisson and Negative Binomial
     * Distributions".
     */
    rcount x;
    double accp;
    while( true ) {
        x = gsl_ran_negative_binomial( rng, p, r + 1.0 ) + 1;

        accp = gsl_sf_lnfact( x - 1 ) - gsl_sf_lnfact( x );

        if( gsl_ran_bernoulli( rng, exp( accp ) ) ) break;
    }

    return x;
}
Esempio n. 4
0
int mutate(const  gsl_rng *rand, int genotype){
        int mutated;
        int xi1, xi2;
        if      (genotype==0){
                xi1 = gsl_ran_bernoulli(rand, mut_rate);
                xi2 = gsl_ran_bernoulli(rand, mut_rate);
        }
        else if (genotype==1){
                xi1 = gsl_ran_bernoulli(rand, 1.-mut_rate);
                xi2 = gsl_ran_bernoulli(rand,    mut_rate);
        }
        else if (genotype==2){
                xi1 = gsl_ran_bernoulli(rand, 1.-mut_rate);
                xi2 = gsl_ran_bernoulli(rand, 1.-mut_rate);
        }

        else {
                fprintf(stderr, "ERROR: genotype not 0, 1 or 2\n");
                fflush(stderr);
                abort();
        }

        mutated = xi1 + xi2;
        return mutated;
}
Esempio n. 5
0
/* Erdos-Renyi : G(n,p)
*/
igraph_t *ggen_generate_erdos_gnp(gsl_rng *r, unsigned long n, double p)
{
    igraph_matrix_t m;
    igraph_t *g = NULL;
    int err;
    unsigned long i,j;

    ggen_error_start_stack();
    if(r == NULL)
        GGEN_SET_ERRNO(GGEN_EINVAL);

    if(p < 0.0 || p > 1.0)
        GGEN_SET_ERRNO(GGEN_EINVAL);

    g = malloc(sizeof(igraph_t));
    GGEN_CHECK_ALLOC(g);
    GGEN_FINALLY3(free,g,1);

    if(p == 0.0)
    {
        GGEN_CHECK_IGRAPH(igraph_empty(g,n,1));
        goto end;
    }
    if(p == 1.0)
    {
        GGEN_CHECK_IGRAPH(igraph_full_citation(g,n,1));
        goto end;
    }

    GGEN_CHECK_IGRAPH(igraph_matrix_init(&m,n,n));
    GGEN_FINALLY(igraph_matrix_destroy,&m);

    for(i = 0; i < n; i++)
        for(j = 0; j < n; j++)
            if(i < j)
                // coin flipping to determine if we add an edge or not
                igraph_matrix_set(&m,i,j,gsl_ran_bernoulli(r,p));
            else
                igraph_matrix_set(&m,i,j,0);

    GGEN_CHECK_IGRAPH(igraph_adjacency(g,&m,IGRAPH_ADJ_DIRECTED));
end:
    ggen_error_clean(1);
    return g;
ggen_error_label:
    return NULL;
}
Esempio n. 6
0
int pick_father(const   gsl_rng *rand, 
		int    *ptr_N,
		double *fitness, 
		int     index_mother){
	int picked_father;
	
	/*individuals reproduce by selfing with probability self*/
	if(gsl_ran_bernoulli(rand, self)==1){
		picked_father=index_mother;
	}
			
	/*otherwise the father is picked at random*/
	else{
		picked_father = gsl_rng_uniform_int(rand, *ptr_N);
	}

	return picked_father;
}
Esempio n. 7
0
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 ;
}
Esempio n. 8
0
int GSLRNG_bernoulli(stEval *args, stEval *result, void *i) {
    gsl_rng *r = STPOINTER(&args[0]);
    double p = STDOUBLE(&args[1]);
    STINT(result) = gsl_ran_bernoulli(r,p);
    return EC_OK;
}
Esempio n. 9
0
bool GslRandGen::bernoulli(const double & p)
{
  return (gsl_ran_bernoulli(r, p) == 1);
}
Esempio n. 10
0
void set_Z(PARAM *param, PRIOR *prior, DATA *data, const gsl_rng *r) {
  /* Z and iZ */
  int i,j,id;
  int indiv, total;
  int isCtrl, isReverse;
  float prob, maxl;
  float posi, negi;
  float pos, neg, tmp;
  for(i=0;i<data->nuinter;i++) {
    isCtrl = 0;
    for(j=0;j<data->n_u2a[i];j++) {
      id = data->u2a[i][j];
      if(data->ctrl[data->i2IP[id]] == 1) {
        isCtrl = 1;
        break;
      }
    }
    isReverse = 0;
    for(j=0;j<data->n_u2a[i];j++) {
      id = data->u2a[i][j];
      if(data->d[id] < param->lambda_false[id]) {
        isReverse = 0;
        break;
      }
    }

    if(isCtrl || isReverse) {
      param->Z[i] = 0;
      for(j=0;j<data->n_u2a[i];j++) {
        id = data->u2a[i][j];
        param->iZ[id] = 0;
      }
    }
    else {
      pos = 0.0; neg = 0.0;
      for(j=0;j<data->n_u2a[i];j++) {
        id = data->u2a[i][j];
        tmp = data->d[id];
        posi = log_gaussian(tmp, param->lambda_true[id], param->eta[data->i2p[id]]);
        negi = log_gaussian(tmp, param->lambda_false[id], param->eta0[data->i2p[id]]);
        pos += posi;
        neg += negi;
        maxl = posi > negi ? posi : negi;
        posi -= maxl;
        negi -= maxl;
        prob = param->ptrue * exp(posi) / (param->ptrue * exp(posi) + (1.0-param->ptrue) * exp(negi));
        param->iZ[id] = gsl_ran_flat(r,0.0,1.0) <= prob ? 1 : 0;
      }
      /* Z */
      if(data->n_u2a[i] == 1) {
        id = data->u2a[i][0];
        param->Z[i] = param->iZ[id];	
      }
      else {
        /* maxl = pos > neg ? pos : neg;
        pos -= maxl;
        neg -= maxl;
        prob = param->ptrue * exp(pos) / (param->ptrue * exp(pos) + (1.0-param->ptrue) * exp(neg));
        param->Z[i] = gsl_ran_flat(r,0.0,1.0) <= prob ? 1 : 0; */
        indiv = 0;
        total = data->n_u2a[i];
        for(j=0;j<data->n_u2a[i];j++) {
          id = data->u2a[i][j];
          if(param->iZ[id]) indiv++;
        }
        pos = ((double) indiv) / ((double) total);
        param->Z[i] = gsl_ran_bernoulli(r, pos);
      }
    }
  }
}
Esempio n. 11
0
unsigned int rbernoulli(double p) {
    return gsl_ran_bernoulli(RANDOM_NUMBER, p);
}
Esempio n. 12
0
double
test_bernoulli (void)
{
  return gsl_ran_bernoulli (r_global, 0.3);
}
Esempio n. 13
0
void form_offspring(
		const  gsl_rng *rand, 
		int    k, 
		int    picked_father, 
		int    counter, 
		int  **ptr_matrix_del, 
		int  **ptr_matrix_env, 
		int  **ptr_offspring_matrix_del, 
		int  **ptr_offspring_matrix_env
		){
	
	int i;	
	
	/*I think that this works both for selfing and for sexual reproduction*/	

	for(i=0;i<LOCI_ENV;i++){
		
		ptr_offspring_matrix_env[k][i]=0;


                if(ptr_matrix_env[k][i]+ptr_matrix_env[picked_father][i]==0){
                        ptr_offspring_matrix_env[counter][i]=0;
                }

                if(ptr_matrix_env[k][i]+ptr_matrix_env[picked_father][i]==4){
                        ptr_offspring_matrix_env[counter][i]=2;
                }

                if(ptr_matrix_env[k][i]+ptr_matrix_env[picked_father][i]==1){
                        ptr_offspring_matrix_env[counter][i]=gsl_ran_bernoulli(rand, 0.5);
                }

                if(ptr_matrix_env[k][i]+ptr_matrix_env[picked_father][i]==3){
                        ptr_offspring_matrix_env[counter][i]=1+gsl_ran_bernoulli(rand,0.5);
                }

                if(ptr_matrix_env[k][i]+ptr_matrix_env[picked_father][i]==2){
                        if(ptr_matrix_env[k][i]==0 || ptr_matrix_env[picked_father][i]==0){
                                ptr_offspring_matrix_env[counter][i]=1;
                        }
                        else{
                                ptr_offspring_matrix_env[counter][i]=gsl_ran_binomial(rand,0.5,2);
                        }
                }

	}


	for(i=0;i<LOCI_DEL;i++){
	
		ptr_offspring_matrix_del[k][i]=0;
		

		if(ptr_matrix_del[k][i]+ptr_matrix_del[picked_father][i]==0){
			ptr_offspring_matrix_del[counter][i]=0;
		}

		if(ptr_matrix_del[k][i]+ptr_matrix_del[picked_father][i]==4){
			ptr_offspring_matrix_del[counter][i]=2;
		}

		if(ptr_matrix_del[k][i]+ptr_matrix_del[picked_father][i]==1){
			ptr_offspring_matrix_del[counter][i]=gsl_ran_bernoulli(rand, 0.5);
		}

		if(ptr_matrix_del[k][i]+ptr_matrix_del[picked_father][i]==3){
			ptr_offspring_matrix_del[counter][i]=1+gsl_ran_bernoulli(rand,0.5);
		}

		if(ptr_matrix_del[k][i]+ptr_matrix_del[picked_father][i]==2){
			if(ptr_matrix_del[k][i]==0 || ptr_matrix_del[picked_father][i]==0){
				ptr_offspring_matrix_del[counter][i]=1;
			}
			else{
				ptr_offspring_matrix_del[counter][i]=gsl_ran_binomial(rand,0.5,2);
			}
		}

	}

}
Esempio n. 14
0
/* Fan-in/ Fan-out method
*/
igraph_t *ggen_generate_fifo(gsl_rng *r, unsigned long n, unsigned long od, unsigned long id)
{
    igraph_t *g = NULL;
    igraph_vector_t available_od;
    igraph_vector_t out_degrees;
    igraph_vector_t vertices;
    igraph_vector_t choice;
    igraph_vector_t edges;
    unsigned long max;
    unsigned long i,j,k;
    unsigned long vcount = 1;
    int err;

    ggen_error_start_stack();
    if(r == NULL)
        GGEN_SET_ERRNO(GGEN_EINVAL);

    if(id == 0 || od == 0 || od > n || id > n)
        GGEN_SET_ERRNO(GGEN_EINVAL);

    g = malloc(sizeof(igraph_t));
    GGEN_CHECK_ALLOC(g);
    GGEN_FINALLY3(free,g,1);

    GGEN_CHECK_IGRAPH(igraph_empty(g,1,1));
    GGEN_FINALLY3(igraph_destroy,g,1);

    GGEN_CHECK_IGRAPH(igraph_vector_init(&available_od,n));
    GGEN_FINALLY(igraph_vector_destroy,&available_od);
    GGEN_CHECK_IGRAPH(igraph_vector_init(&out_degrees,n));
    GGEN_FINALLY(igraph_vector_destroy,&out_degrees);
    GGEN_CHECK_IGRAPH(igraph_vector_init(&vertices,n));
    GGEN_FINALLY(igraph_vector_destroy,&vertices);
    GGEN_CHECK_IGRAPH(igraph_vector_init(&choice,n));
    GGEN_FINALLY(igraph_vector_destroy,&choice);
    GGEN_CHECK_IGRAPH(igraph_vector_init(&edges,n*2));
    GGEN_FINALLY(igraph_vector_destroy,&edges);
    while(vcount < n)
    {
        // never trigger errors as it doesn't allocate or free memory
        igraph_vector_resize(&available_od,vcount);
        igraph_vector_resize(&out_degrees,vcount);
        igraph_vector_resize(&vertices,vcount);

        // compute the available out degree of each vertex
        GGEN_CHECK_IGRAPH(igraph_degree(g,&out_degrees,igraph_vss_all(),IGRAPH_OUT,0));

        // fill available with od and substract out_degrees
        igraph_vector_fill(&available_od,od);
        GGEN_CHECK_IGRAPH(igraph_vector_sub(&available_od,&out_degrees));

        if(gsl_ran_bernoulli(r,0.5))     //Fan-out Step
        {
            // find max
            max = igraph_vector_max(&available_od);

            // register all vertices having max as outdegree
            j = 0;
            for (i = 0; i < vcount; i++)
                if(VECTOR(available_od)[i] == max)
                    VECTOR(vertices)[j++] = i;

            // choose randomly a vertex among availables
            GGEN_CHECK_GSL_DO(i = gsl_rng_uniform_int(r,j));

            // how many children ?
            GGEN_CHECK_GSL_DO(j = gsl_rng_uniform_int(r,max));
            j = j+1;

            // create all new nodes and add edges
            GGEN_CHECK_IGRAPH(igraph_add_vertices(g,j,NULL));

            // cannot fail
            igraph_vector_resize(&edges,j*2);

            for(k = 0; k < j; k++)
            {
                VECTOR(edges)[2*k] = i;
                VECTOR(edges)[2*k+1] = vcount + k;
            }
            vcount+=k;
        }
        else	//Fan-In Step
        {
            // register all vertices having an available outdegree
            j = 0;
            for (i = 0; i < vcount; i++)
                if(VECTOR(available_od)[i] > 0)
                    VECTOR(vertices)[j++] = i;

            // we can add at most id vertices
            max =( j > id)? id: j;
            // how many edges to add
            GGEN_CHECK_GSL_DO(k = gsl_rng_uniform_int(r,max));
            k = k+1;

            // choose that many nodes and add edges from them to the new node
            // cannot fail either
            igraph_vector_resize(&choice,k);

            gsl_ran_choose(r,VECTOR(choice),k,
                           VECTOR(vertices),j,sizeof(VECTOR(vertices)[0]));

            // add a vertex to the graph
            GGEN_CHECK_IGRAPH(igraph_add_vertices(g,1,NULL));

            igraph_vector_resize(&edges,k*2);
            // be carefull, vcount is the last ID of vertices not vcount +1
            for(i = 0; i < k; i++)
            {
                VECTOR(edges)[2*i] = VECTOR(choice)[i];
                VECTOR(edges)[2*i+1] = vcount;
            }
            vcount++;

        }
        // in all cases, edges should be added
        GGEN_CHECK_IGRAPH(igraph_add_edges(g,&edges,NULL));
    }
    ggen_error_clean(1);
    return g;
ggen_error_label:
    return NULL;
}
Esempio n. 15
0
igraph_t *ggen_generate_erdos_lbl(gsl_rng *r, unsigned long n, double p, unsigned long nbl)
{
    igraph_t *g = NULL;
    igraph_matrix_t m;
    igraph_vector_t layers;
    unsigned long i,j;
    int err;

    ggen_error_start_stack();
    if(r == NULL)
        GGEN_SET_ERRNO(GGEN_EINVAL);

    if(p < 0.0 || p > 1.0)
        GGEN_SET_ERRNO(GGEN_EINVAL);

    if(nbl > n || nbl == 0)
        GGEN_SET_ERRNO(GGEN_EINVAL);

    g = malloc(sizeof(igraph_t));
    GGEN_CHECK_ALLOC(g);
    GGEN_FINALLY3(free,g,1);

    if(p == 0.0)
    {
        GGEN_CHECK_IGRAPH(igraph_empty(g,n,1));
        goto end;
    }
    if(p == 1.0 && nbl == n)
    {
        GGEN_CHECK_IGRAPH(igraph_full_citation(g,n,1));
        goto end;
    }

    GGEN_CHECK_IGRAPH(igraph_matrix_init(&m,n,n));
    GGEN_FINALLY(igraph_matrix_destroy,&m);

    GGEN_CHECK_IGRAPH(igraph_vector_init(&layers,n));
    GGEN_FINALLY(igraph_vector_destroy,&layers);

    // asign to each vertex a layer
    for(i = 0; i < n; i++)
    {
        GGEN_CHECK_GSL_DO(j = gsl_rng_uniform_int(r,nbl));
        VECTOR(layers)[i] = j;
    }

    // create edges
    for(i = 0; i < n; i++)
        for(j = 0; j < n; j++)
            // if the layer allocation allows the edge, we test for it
            if(VECTOR(layers)[i]<VECTOR(layers)[j])
                igraph_matrix_set(&m,i,j,gsl_ran_bernoulli(r,p));
            else
                igraph_matrix_set(&m,i,j,0);

    //translate the matrix to a graph
    GGEN_CHECK_IGRAPH(igraph_adjacency(g,&m,IGRAPH_ADJ_DIRECTED));
end:
    ggen_error_clean(1);
    return g;
ggen_error_label:
    return NULL;
}
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();
    }
}