Example #1
0
void random_vector(gsl_vector *vec, double parameter , double (* func)(const gsl_rng *, double )){
  //
  const gsl_rng_type * T;
  gsl_rng * r;

  int i;

  gsl_rng_env_setup();
  T = gsl_rng_default;
  r = gsl_rng_alloc (T);
  gsl_rng_set (r, rand());
  for (i = 0; i < vec->size; i++)
    {
      // double u = gsl_rng_uniform (r);
      gsl_vector_set(vec, i, func(r, parameter));
    }

  gsl_rng_free (r);
}
void _simulateSDE(const double * abgth, const int N_spikes, const double dt,
					double * Ss) {
	const double V_THRESH = 1.0;

	double alpha, beta, gamma, theta;
	alpha = abgth[0]; beta= abgth[1]; gamma =abgth[2]; theta = abgth[3];

	int recorded_spikes = 0;

	double v = .0;
	double sqrt_dt = sqrt(dt);

	//RNG stuff:
    const gsl_rng_type * T;
    gsl_rng * G;
    /* create a generator chosen by the environment variable GSL_RNG_TYPE */
    gsl_rng_env_setup();
    T = gsl_rng_default;
    G = gsl_rng_alloc (T);

    struct timeval tv;
    gettimeofday(&tv,NULL);
    srand((tv.tv_sec * 1000) + (tv.tv_usec / 1000));
    unsigned long int S = rand();
//    printf("S=%d\n",S);
    gsl_rng_set (G, S);

    double dB, dv;
    double t = .0;
	while (recorded_spikes < N_spikes){
				dB =  gsl_ran_gaussian_ziggurat(G, sqrt_dt);
	            dv = ( alpha - v + gamma*sin(theta*t) )*dt  + beta*dB;

	            v += dv;
	            t += dt;
	            if (v >= V_THRESH){
	                Ss [recorded_spikes++] = t;
	                v = .0;
	            }
	}

	gsl_rng_free(G);
}
Example #3
0
void unbiasround( double *mat, int *imat, int * imat1, int * rowparity,int *nrow, int *ncol, gsl_rng *r) {
  int i,j,k,k1;
  int  nr,nc;
  static int first_use = 1;
  gsl_rng *rng;
  if (r) rng = r;
  else {
      if (first_use){
          gsl_rng_env_setup();
          first_use=0;
      }
      rng  =  gsl_rng_alloc(gsl_rng_taus2);
  }
  gsl_rng_set(rng, 27);
  /*  Rprintf("Entering unbiasround, nrow = %d , ncol = %d \n",*nrow,*ncol); */

  nr = (*nrow) + 1;
  nc = (*ncol) + 1;

  /* Make an integer array
    Also  add an extra column so there are an even number of 1's in each row */
    for (i=0; i < *nrow; i++) {
      k1 = i + nr * *ncol;
      imat[k1] = 0;
      for (j=0; j < *ncol; j++) {
        imat[i + nr * j] = lrint( mat[i + *nrow * j]*(twobits));
      }
    }
    /* Add an extra row so there will be an even number of 1's in each column */
    for (j=0; j <= *ncol; j++) { //don't forget the lower-right corner.
        k1 = *nrow +j * nr ;
        imat[k1] = 0;
    }  

    for (k1=0; k1< bits; k1++) {
        roundeven(imat,imat1,rowparity,&nr,&nc, rng); 
        for (k=0, i=0; i < nr; i++) {
            for (j=0; j < nc; j++, k++) {
                imat[k] >>= 1;   /* Divide entire matrix by 2 using right shift 1 bit */
            }
        }
    }
}
Example #4
0
void assign_parameters()
{
  extern unsigned long nx0, ny0;
  extern double pi, deg2Rad, rad2Deg, strad2Deg, etaOffSet;
  extern double surveyCenterRA, surveyCenterDEC, node, etaPole;
  const gsl_rng_type *T;

  /* With these base resolutions, we can achieve nearly equal area pixels, with
     nearly square pixels at lambda = 30 degrees.  A resolution factor of 
     4 gives us pixels as wide as a stripe.  The seeing/reddening/sky maps
     are made with resolution=256. 

     YOU MUST CALL assign_parameters() AT THE BEGINNING OF YOUR CODE TO SET
     UP THE REQUIRED GLOBAL VARIABLES.     
  */

  nx0 = 36;
  ny0 = 13;

  pi = 2.0*asin(1.0);
  deg2Rad = pi/180.0;
  rad2Deg = 180.0/pi;
  strad2Deg = 360.0*360.0/(4.0*pi*pi);

  /* These parameters are necessary for translation of LAMBDA-ETA coordinates
     into x-y-z vectors in a way consistant with translations from RA-DEC.  We
     also need etaOffSet to compensate for the fact that the stripes stradle
     the ETA = 0 meridian, rather than being bounded by it. */

  etaOffSet = 91.25;
  surveyCenterRA = 185.0;
  surveyCenterDEC = 32.5;
  node = deg2Rad*(surveyCenterRA - 90.0);
  etaPole = deg2Rad*surveyCenterDEC;

  gsl_rng_env_setup();

  gsl_rng_default_seed = time(NULL);

  T = gsl_rng_default;
  mt19937_rand = gsl_rng_alloc(T);
}
Example #5
0
AlexSim::AlexSim(double tstart,double tend)
{
    qDebug("\n *** ALEX Simulation *** ");
    this->tStart=tstart;
    tDuration=tend-tstart;
    if(tDuration<=0) {
        qFatal("enter times tstart<tend");
    }
    t=0;
    burstDuration=3e-3; // 2ms
    burstDurationVar=18e-7; // variance of burst duration in seconds^2, estimated from data
    rateDemDex=6e4; // 50kHz
    rateAemAex=6e4;
    rateBackground=1e3; // 1kHz
    rateFirst=1e9;
    rateBlinking;
    rateBleaching=4e3; // per second
    lifetimeBleaching=5e-3;
    lifetimeBlinking=10e-6; // triplet state lifetime ca 3 micro seconds
    crosstalk=0.03;
    directExcitation=0.02;

    tDex=100e-6;
    tAex=80e-6;
    tDexBreak=10e-6;
    tAexBreak=10e-6;

     // photonArrivalTimeChannel1.reserve();

    /* create a generator chosen by the environment variable GSL_RNG_TYPE */
    gsl_rng_env_setup();
    rngType = gsl_rng_default;
    r = gsl_rng_alloc(rngType);
    gsl_rng_set(r, 0); // set the seed to 0, i.e. the default value

    // approximate burst size distribution as lognormal
    sigma=sLogNorm(burstDuration,burstDurationVar);
    mu=mLogNorm(burstDuration, burstDurationVar);
    qDebug()<<"lognormal mu="<<mu;
    qDebug()<<"lognormal sigma="<<sigma;

}
Example #6
0
int
main(void)
{
  const gsl_rng_type * T;
  gsl_rng * r;

  double x_initial = 15.5;

  gsl_rng_env_setup();

  T = gsl_rng_default;
  r = gsl_rng_alloc(T);

  gsl_siman_solve(r, &x_initial, E1, S1, M1, P1,
                  NULL, NULL, NULL, 
                  sizeof(double), params);

  gsl_rng_free (r);
  return 0;
}
/* 
 * generating random numbers separately to
 * prevent the side effects on hardware counters.
 *
 * */
void generate_random_numbers(int *sequence) {
  const gsl_rng_type * T;

  gsl_rng_env_setup();

  T = gsl_rng_default;
  r = gsl_rng_alloc (T);

  /* seed */
  gsl_rng_set(r, seed);
  
  /* default generator type is mt19937, which is what we need */
  // printf("generator type: %s\n", gsl_rng_name (r));

  int i;
  for (i = 0; i < SEQUENCE_CNT; i++) {
    sequence[i] = gsl_rng_get(r) % SEQUENCE_CNT; // limit the random numbers to [0, 3999]
    // printf("%u\t", sequence[i]);
  }
}
Example #8
0
int main(void)
{
	// prepare GSL random number generator
	const gsl_rng_type* T;
	gsl_rng* r;
	gsl_rng_env_setup();
	T = gsl_rng_default;
	r = gsl_rng_alloc(T);
	double estim, err;

	fprintf(stdout,"# Volume of n-dim ball:\n");
	fprintf(stdout,"# DIM\tActual Vol.\tADAPT(Estim.)\tADAPT(counts)\tMC(Estim.)\tMC(Counts)\n");
	for(dim=1; dim < 7; dim++)
	{
		fprintf(stdout,"%d\t%g",dim,volume(dim));
		counter = 0;
		estim = adapt_nd_speclim(f,d,u,dim,ACC,EPS,&err);
		fprintf(stdout,"\t%g\t%llu",estim,counter);
		counter = 0;
		estim = monte_carlo_speclim(f,d,u,dim,ACC,EPS,100,&err,r);
		fprintf(stdout,"\t%g\t%llu\n",estim,counter);
	}

	fprintf(stdout,"\n\n# Integral of exp(sum_i x_i) in n-ball\n");
	fprintf(stdout,"# Dim\tADAPT\tMonte Carlo\n");

	for(dim=1; dim < 7; dim++)
	{
		fprintf(stdout,"%d",dim);
		counter = 0;
		estim = adapt_nd_speclim(fexp,d,u,dim,ACC,EPS,&err);
		fprintf(stdout,"\t%llu",counter);
		counter = 0;
		estim = monte_carlo_speclim(fexp,d,u,dim,ACC,EPS,100,&err,r);
		fprintf(stdout,"\t%llu\n",counter);
	}

	gsl_rng_free(r);

	return 0;
}
Example #9
0
File: square.c Project: hwp/fractal
int main(int argc, char** argv) {
  int size = 10000;
  double sx = 1.0;
  double sy = 1.0;

  int opt;
  while ((opt = getopt(argc, argv, "s:x:y:")) != -1) {
    switch (opt) {
      case 's':
        size = atoi(optarg);
        break;
      case 'x':
        sx = atof(optarg);
        break;
      case 'y':
        sy = atof(optarg);
        break;
    }
  }

  gsl_rng_env_setup();
  gsl_rng* rng = gsl_rng_alloc(gsl_rng_default);
 
  double px[4] = {0.0, 0.0, 1.0, 1.0};
  double py[4] = {0.0, 1.0, 0.0, 1.0};

  double x = gsl_rng_uniform(rng);
  double y = gsl_rng_uniform(rng);

  printf("%g %g\n", x, y);

  int i, d;
  for (i = 0; i < size; i++) {
    d = gsl_rng_uniform_int(rng, 4);
    x = (x * sx + px[d]) / (1.0 + sx);
    y = (y * sy + py[d]) / (1.0 + sy);
    printf("%g %g\n", x, y);
  }

  gsl_rng_free(rng);
}
Example #10
0
// [[Rcpp::export]]
Rcpp::List genData() {

    const size_t n = N;
    size_t i;
    double dy;
    gsl_rng *r;
    RcppGSL::vector<double> w(n), x(n), y(n);

    gsl_rng_env_setup();
    r = gsl_rng_alloc(gsl_rng_default);

    //printf("#m=0,S=0\n");
    /* this is the data to be fitted */

    for (i = 0; i < n; ++i) {
        double sigma;
        double xi = (15.0 / (N - 1)) * i;
        double yi = cos(xi) * exp(-0.1 * xi);

        sigma = 0.1 * yi;
        dy = gsl_ran_gaussian(r, sigma);
        yi += dy;

        gsl_vector_set(x, i, xi);
        gsl_vector_set(y, i, yi);
        gsl_vector_set(w, i, 1.0 / (sigma * sigma));
                
        //printf("%f %f\n", xi, yi);
    }

    Rcpp::DataFrame res = Rcpp::DataFrame::create(Rcpp::Named("x") = x,
                                                  Rcpp::Named("y") = y,
                                                  Rcpp::Named("w") = w);

    x.free();
    y.free();
    w.free();
    gsl_rng_free(r);

    return(res);
}
Example #11
0
int main(int argc, char **argv)
{
  int ret;
  params p = {	 	/*<<<	___default___	*/
    4.2,		/*	amp		*/
    4.9, 		/*	omega		*/
    0.0, 		/*	force		*/
    0.9,  		/*	gamma		*/
    0.001, 		/*	Dg		*/
    0.0,		/*	Dp		*/
    0.0,		/*	lambda		*/
    false,		/*	biased		*/
    32,			/*	paths		*/
    10000,		/*	periods		*/
    99,			/*	trans		*/
    200,		/*	spp		*/
    true,		/*	2nd order	*/
  };/*>>>*/	

  tic = clock();
  set_parameters(argc,argv,&p);

  /*<<<      GSL                     */
  const gsl_rng_type * R;
  gsl_rng * rg;
  gsl_rng_env_setup();
  if (!getenv("GSL_RNG_SEED")){
    gsl_rng_default_seed = time(NULL);
    fprintf(stderr,"#seed:%ld\n",gsl_rng_default_seed);
  }
  R = gsl_rng_default;
  rg = gsl_rng_alloc (R);
  /*>>>GSL*/

  dump_params(&p);

  ret = simulate(&p, rg);

  gsl_rng_free(rg);
  return ret;
}
Example #12
0
int main (int argc, char* argv[]){

  int nsteps = 2;
  int g1[WDEFAULT][HDEFAULT], g2[WDEFAULT][HDEFAULT];

  for(int i = 0; i < WDEFAULT; i++)
    for(int j = 0; j < HDEFAULT; j++){
      g1[i][j] = 0;
      g2[i][j] = 0;
    }
  
  const gsl_rng_type *T;
  gsl_rng *rand;

  gsl_rng_env_setup();
  T = gsl_rng_default;
  rand = gsl_rng_alloc(T);

  gsl_rng_set(rand, get_seed_noblock());
  randomInit(g1, 0.55, rand);

  
  printGrid(g1);

  updateGrid(g1,g2);

  printf("# updated \n");
  printGrid(g2);

  for(int i = 0; i < nsteps; i++){
    // blit g2 back into g1
    memcpy(g1, g2, sizeof(int)*WDEFAULT*HDEFAULT);
    // now update g1
    updateGrid(g1,g2);
    printGrid(g2);
  }
  

  gsl_rng_free(rand);
  return EXIT_SUCCESS;
}
Example #13
0
couple::couple (int argc, char *argv[] ) { 
    static const char *optString = "vh";

    static const struct option longOpts[] = {
        { "parameter", required_argument, NULL, 'p' },
        { "verbose", no_argument, NULL, 'v' },
        { "help", no_argument, NULL, 'h' },
        { NULL, no_argument, NULL, 0 }
    };

    d = new data (argc, argv, optString, longOpts);
    string pfile;
    d->get_string ("parameter",pfile,true);
    p = new data (pfile);
    p->print_parameters();
    p->get_int ("debug", io::debug, 0);

	string geno1, snp1, ind1;
    string inputformat = "eigenstrat";
	p->get_string ("genotypename",geno1,true);
	p->get_string ("snpname",snp1,true);
	p->get_string ("indivname",ind1,true);
	p->get_boolean ("isgenotype", isgenotype, false);
    p->get_boolean ("pack", pack, true, false);
    string indivfilterfile = "";
    givenindivfilterfile = p->get_string ("indivfilterfile", indivfilterfile, false);

    g = new genotype (snp1,ind1, geno1, "eigenstrat", isgenotype, indivfilterfile, "", false, pack);

	p->get_int ("seed",seed,1,false);

    nind = g->nind;
    nsnps = g->nsnp;
    nchr = g->nchr;
    gsl_rng_env_setup();
	rng_T = gsl_rng_default;
	rng_r = gsl_rng_alloc (rng_T);
	gsl_rng_set (rng_r, seed);


}
Example #14
0
Random::Random(std::string type)
{
	gsl_rng_env_setup();

	if      (type == "mt19937")	{
		this->randomGeneratorType = gsl_rng_mt19937;}
	else if (type == "taus") {
		this->randomGeneratorType = gsl_rng_taus;}
	else if (type == "ranlxs0") {
		this->randomGeneratorType = gsl_rng_ranlxs0;}
	else {
		this->randomGeneratorType = gsl_rng_ranlxs0;}

	this->randomGeneratorHandle = gsl_rng_alloc(this->randomGeneratorType);
	this->toSeed();
	gsl_rng_set(this->randomGeneratorHandle, this->seed);
	printf(
		"Random number generator of type '%s' "
	    "has been intialized and seeded.\n",
		gsl_rng_name(randomGeneratorHandle));
}
Example #15
0
int main(int argc, char* argv[])
{
    FILE* f_out;
    f_out = fopen("output_ROSSLER.dat","w");

    FILE* f_in;
    f_in = fopen("input_ROSSLER.dat","r");

    double pars[4];
    double Tspan[2];
    Tspan[0] = 0.0;
    double dt;
    int print_step;

    if(!ParseData_ROSSLER(pars,Tspan,&dt,&print_step,f_in)) return 1;
    fclose(f_in);

    double x0[3] = {1.0, 0.0, 0.0};

    // Allocation and Initialization of Random Number Generator
    const gsl_rng_type * T;
    gsl_rng * r;
    gsl_rng * r_lyap;
    gsl_rng_env_setup();
    T = gsl_rng_default;
    r = gsl_rng_alloc(T);
    r_lyap = gsl_rng_alloc(T);

    // Parameters for the Calculation of the Maximum LE
    double tau = 100*dt;
    double alpha = 1e-2;
    double lyapexp = 0;
      
    SdeSolverLyapLog(Stepper_RK4,Update_VF_ROSSLER,Update_Diffusion_ROSSLER,Update_Diffusion_Deriv_ROSSLER,Tspan,x0,3,1,dt,pars,r,r_lyap,tau,alpha,&lyapexp,f_out,print_step,1);

    printf("Computed value of maximum Lyapunov Exponent: %f\n",lyapexp);

    fclose(f_out);
    return 0;
}
Example #16
0
int init_xrandom(string init)
{
#ifdef HAVE_GSL
    char my_gsl_type[64], my_gsl_seed[64], *cp;     /* need two strings, bug in putenv? */
    string *is;
    int nis, iseed;

    is = burststring(init,", ");                      /* parse init as "[seed[,name]]"  */
    nis = xstrlen(is,sizeof(string))-1;
    if (nis > 0) {                                          /* seed is first, but optional */
        iseed = natoi(is[0]);
	if (iseed > 0 || streq(is[0],"+0")) {
	  sprintf(my_gsl_seed,"%s=%s",env_seed,is[0]);
	} else {
	  iseed = set_xrandom(iseed);
	  sprintf(my_gsl_seed,"%s=%u",env_seed,iseed);
	}
	putenv(my_gsl_seed);
	dprintf(1,"putenv: %s\n",my_gsl_seed);
        if (nis > 1) {                                      /* name is second, also optional */
            sprintf(my_gsl_type,"%s=%s",env_type,is[1]);
            putenv(my_gsl_type);
	    dprintf(1,"putenv: %s\n",my_gsl_type);
        }
    }

    gsl_rng_env_setup();                          /* initialize the rng (name/seed) setup */
    my_T = gsl_rng_default;
    my_r = gsl_rng_alloc(my_T);


    dprintf(1,"GSL generator type: %s\n",gsl_rng_name(my_r));
    dprintf(1,"GSL seed = %u\n",gsl_rng_default_seed);
    dprintf(1,"GSL first value = %u\n",gsl_rng_get(my_r));

    return (int) gsl_rng_default_seed;
#else
    return set_xrandom(init? natoi(init) : 0);     /*  18/06/2008: allow for init=0 WD */
#endif
}
void *operateOnTree(void* tArgs)
{
  struct timespec s,e;
  int chooseOperation;
  unsigned long lseed;
  int threadId;
  struct threadArgs* tData = (struct threadArgs*) tArgs;
  threadId = tData->threadId;
  lseed = tData->lseed;
  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,lseed);
  while(!start)
  {
  }

  clock_gettime(CLOCK_REALTIME,&s);
  for(int i=0;i< (int)iterations;i++)
  {
    chooseOperation = gsl_rng_uniform(r)*100;
    if(chooseOperation < findPercent)
    {
      lookup(tData,gsl_rng_get(r)%keyRange + 1);
    }
    else if (chooseOperation < insertPercent)
    {
      insert(tData,gsl_rng_get(r)%keyRange + 1);
    }
    else
    {
      remove(tData,gsl_rng_get(r)%keyRange + 1);
    }
  }
  clock_gettime(CLOCK_REALTIME,&e);
  timeArray[threadId] = (double) (diff(s,e).tv_sec * 1000000000 + diff(s,e).tv_nsec)/1000;
  return NULL;
}
Example #18
0
void TrainLINE() {
  long a;
  pthread_t *pt = (pthread_t *)malloc(num_threads * sizeof(pthread_t));

  if (order != 1 && order != 2)
  {
    printf("Error: order should be eighther 1 or 2!\n");
    exit(1);
  }
  printf("--------------------------------\n");
  printf("Order: %d\n", order);
  printf("Samples: %lldM\n", total_samples / 1000000);
  printf("Negative: %d\n", num_negative);
  printf("Dimension: %d\n", dim);
  printf("Initial rho: %lf\n", init_rho);
  printf("--------------------------------\n");

  InitHashTable();
  ReadData();
  InitAliasTable();
  InitVector();
  InitNegTable();
  InitSigmoidTable();

  gsl_rng_env_setup();
  gsl_T = gsl_rng_rand48;
  gsl_r = gsl_rng_alloc(gsl_T);
  gsl_rng_set(gsl_r, 314159265);

  clock_t start = clock();
  printf("--------------------------------\n");
  for (a = 0; a < num_threads; a++) pthread_create(&pt[a], NULL, TrainLINEThread, (void *)a);
  for (a = 0; a < num_threads; a++) pthread_join(pt[a], NULL);
  printf("\n");
  clock_t finish = clock();
  double duration = (double)(finish - start) / CLOCKS_PER_SEC;
  printf("Total CPU time: %lf, real time %.2lf (s)\n", duration, duration / num_threads);

  Output();
}
Example #19
0
extern void init_math_functions (struct _flow *flow, unsigned long seed)
{
	int rc;
#ifndef HAVE_LIBGSL
	UNUSED_ARGUMENT(flow);
#endif /* HAVE_LIBGSL */
	/* set rounding */
	fesetround(FE_TONEAREST);

	/* initalize rng */
#ifdef HAVE_LIBGSL
	const gsl_rng_type * T;
	gsl_rng_env_setup();
	T = gsl_rng_default;
	flow->r = gsl_rng_alloc (T);
#endif /* HAVE_LIBGSL */

	if (!seed) {
	/* if no seed supplied use urandom */
		DEBUG_MSG(LOG_WARNING, "client did not supply random seed "
			  "value");
		int data = open("/dev/urandom", O_RDONLY);
		rc = read(data, &seed, sizeof (long) );
		close(data);
		if(rc == -1)
			crit("read /dev/urandom failed");
	}

#ifdef HAVE_LIBGSL
	gsl_rng_set (flow->r, seed);
	DEBUG_MSG(LOG_WARNING, "initalized local libgsl random functions for "
		  "flow %d with seed %lu, gsl generator is: %s",
		  flow->id,seed,gsl_rng_name (flow->r));
#else
	srand((unsigned int)seed);
	DEBUG_MSG(LOG_WARNING, "initalized posix random functions with seed "
		  "%u", (unsigned int)seed);
#endif /* HAVE_LIBGSL */
}
Example #20
0
int main(){
	int i;
	const int M = 5e7;
	time_t t1, t2, t;
	double mu= 1e-7;
	int L=3e6, T, N;

	/* INIT GSL RNG*/
	t = time(NULL); // time in seconds, used to change the seed of the random generator
	gsl_rng * rng;
 	const gsl_rng_type *typ;
	gsl_rng_env_setup();
	typ=gsl_rng_default;
	rng=gsl_rng_alloc(typ);
	gsl_rng_set(rng,t); // changes the seed of the random generator


	printf("\n - performing %d computations of Bernoulli prob mass fct - ", M);
	time(&t1);
	for(i=0;i<M;i++){
		T=gsl_rng_uniform_int(rng,100); /* time */
		N=gsl_rng_uniform_int(rng, 20); /* nb of mutations*/
		gsl_ran_binomial_pdf((unsigned int) N, mu, T*L);
	}
	time(&t2);
	printf("\nTime ellapsed: %d ", (int) (t2-t1));


	printf("\n - performing %d computations of Poisson prob mass fct- ", M);
	time(&t1);
	for(i=0;i<M;i++){
		T=gsl_rng_uniform_int(rng,100); /* time */
		N=gsl_rng_uniform_int(rng, 20); /* nb of mutations*/
		gsl_ran_poisson_pdf((unsigned int) N, mu*T*L);
	}
	time(&t2);
	printf("\nTime ellapsed: %d \n", (int) (t2-t1));

}
Example #21
0
void
init_rng( long unsigned int Seed )
{
  gsl_rng_env_setup( ) ;
  
  const gsl_rng_type *type = gsl_rng_default ;
  r = gsl_rng_alloc (type) ;

  if( Seed == 0 ) {
    FILE *urandom = fopen( "/dev/urandom" , "r" ) ;
    if( urandom == NULL ) exit( 1 ) ;
    if( fread( &Seed , sizeof( Seed ) , 1 , urandom ) != 1 ) exit(1) ;
    fclose( urandom ) ;
  }

  SEED = Seed ;
  printf( "USING GSL seed %lu \n" , SEED ) ;

  gsl_rng_set( r , Seed ) ;

  return ;
}
Example #22
0
gsl_rng *ini_gsl_rng(Args *args) {
    const gsl_rng_type *t;
    gsl_rng *r;
    int idum;
    FILE *fp;

    gsl_rng_env_setup();
    t = gsl_rng_default;
    r = gsl_rng_alloc(t);
    /* seed for random number generation */
    if(args->s != 0) {
        idum = args->s;
    } else if((fp = fopen("randomSeed.dat","r")) != NULL) {
        if(!fscanf(fp,"%d",&idum))
            printf("WARNING[gsl_rng]: Something went wrong when trying to read the the seed for the random number generator from randomSeed.dat.\n");
        fclose(fp);
    } else
        idum = -time(NULL);
    gsl_rng_set(r,idum);

    return r;
}
Example #23
0
	/**
	 * @brief           Construct
	 *
	 * @param  k        K-Space points
	 * @param  maxit    Max search iterations
	 * @param  st       Start temperature
	 * @param  ft       Final temperature
	 * @param  cr       Cooling rate 
	 * @param  verb     Verbosity
	 * @param  accworse Accept worse solutions with a certain probability
	 */
	SimulatedAnnealing (const Matrix<double>& k, const size_t& maxit = 1000, const double& st = 300.0, 
						const double& ft = 0.0, const double& cr = 0.95, const bool& verb = true, 
						const bool& accworse = false) {
		
		m_maxit = maxit;
		m_st    = st;
		m_ft    = ft;
		m_cr    = cr;
		m_verb  = verb;
		m_accworse = accworse;
		m_k     = k;

		gsl_rng_env_setup();
		m_rng = gsl_rng_alloc (gsl_rng_taus2);
		gsl_rng_set (m_rng, time(0));

		Initialise ();
		m_ct = m_st;

		printf ("Simulated annealing set up\n");

	}
Example #24
0
int
main (void)
   {
    double res, err;
    double a= 0.;
    double b= 2.;
    int dim=9;
    double xl[9] = { a,a,a,a,a,a,a,a,a};
    double xu[9] = { b,b,b,b,b,b,b,b,b};
    gsl_monte_function G = { &f, dim, 0 };
    size_t calls =1e6*dim;

    gsl_rng_env_setup ();
    gsl_rng *r = gsl_rng_alloc (gsl_rng_taus2);
    gsl_rng_set (r, 30776);
    
    gsl_monte_vegas_state *s = gsl_monte_vegas_alloc (dim);

    gsl_monte_vegas_integrate (&G, xl, xu, dim, 1e4, r, s,
			    &res, &err);
    //display_results ("vegas warm-up", res, err,0);

    //printf ("converging...\n");
    int i=0;
    do
    {
      gsl_monte_vegas_integrate (&G, xl, xu, dim, calls/5, r, s,
				&res, &err);
      //printf ("result = % .6f sigma = % .6f chisq/dof = %.1f\n",
      //	    res, err, gsl_monte_vegas_chisq (s));
      i=i+1;
    }
    while (fabs (gsl_monte_vegas_chisq (s) - 1.0) > 0.5);

    display_results ("vegas final", res, err, i);

    gsl_monte_vegas_free (s);
    return 0;
    }
Example #25
0
int main(int argc, char *argv[])
{
	//Make stack size unlimited
	system("ulimit -s unlimited");

	int ii;
	const long N = 1000;
	double x[N],y[N],dx ,dy;

	const gsl_rng_type * T;
	gsl_rng *r;
	FILE *fp1;

	gsl_rng_env_setup();
	T = gsl_rng_default;
	r = gsl_rng_alloc(T);

	x[0] = 0;
	y[0] = 0;
	
	fp1 = fopen("./data/random_walk.dat","w");
	
	for (ii = 1; ii < N; ii++)
	{
		gsl_ran_dir_2d(r,&dx,&dy);	
		x[ii] = x[ii-1]+dx;
		y[ii] = y[ii-1]+dy;
		//printf("%f\n",dx);
		//printf("%f\n",dy);
		fprintf(fp1,"%f %f\n",x[ii],y[ii]);		
	}

	gsl_rng_free(r);
	fclose(fp1);

	//Call gnuplot
	system("gnuplot random_walk.plt");
	return 0;
}
Example #26
0
int main(int argc, char* argv[])
{
    /* initialize the CUnit test registry */
    if (CUE_SUCCESS != CU_initialize_registry()) {
        return CU_get_error();
    }

#ifdef HAVE_LIBGSL
    gsl_rng_env_setup();
#endif

    registerUtilsTests();
    registerPopulationTests();
    registerEnvironmentTests();
    
    /* Run all tests using the CUnit Basic interface */
    CU_basic_set_mode(CU_BRM_VERBOSE);
    CU_basic_run_tests();
    CU_cleanup_registry();
   
    return CU_get_error();
}
/* Estimate the coefficient on the independent variable in an AR(1) model */
double ar1_ols_est (double * params, int n, unsigned long int seed){
    double beta = params[0];
    double alpha = params[1];
    double s = params[2];
    /* Create a generator chosen by the environment variable GSL_RNG_TYPE */
    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, seed);
    
    // Generate the sample path
    int i;
    double x[n+1]; // Create an array of size n+1 for the data
    x[0] = beta / (1 - alpha); // Start at mean of stationary dist
    for (i = 1; i <= n; i++) {
        x[i] = beta + alpha * x[i-1] + gsl_ran_gaussian(r,s);
    }
    gsl_rng_free (r); // Setting the random number generator free

    // Compute auxiliary variables for estimators
    double sum_x = 0;
    double sum_y = 0;
    double sum_xy = 0;
    double sum_xx = 0;
    for (i = 1; i <= n; i++) {
        sum_x += x[i-1];
        sum_y += x[i];
        sum_xy += x[i-1] * x[i];
        sum_xx += x[i-1] * x[i-1];
    }

    // Compute the OLS estimate for alpha
    double alpha_ols =  (sum_xy - ( sum_x * sum_y)/n) / (sum_xx - (sum_x *
    sum_x)/n);
    return alpha_ols;
}
Example #28
0
/* gsl rng stuff */
int ggen_rng_init(gsl_rng **r)
{
	const gsl_rng_type *T;
	char *seedenv;
	unsigned long seedval;
	FILE *file;

	gsl_rng_env_setup();

	T = gsl_rng_default;
	*r = gsl_rng_alloc(T);

	info("Using %s as RNG.\n",gsl_rng_name(*r));

	/* if the user didn't provide a seed, we try to seed the generator
	 * using something sensible.
	 * THIS IS NOT INTENDED TO BE USED IN REAL EXPERIMENTS.
	 * USERS SHOULD BE CAREFUL ABOUT THEIR RNG INIT.
	 */
	seedenv = getenv("GSL_RNG_SEED");
	if(seedenv == NULL)
	{
		warning("RNG seed not provided by user, will attempt to use /dev/urandom.\n");

		file = fopen("/dev/urandom","r");
		if(file == NULL)
			error("Cannot open /dev/urandom: %s\n",strerror(errno));
		if(fread(&seedval,sizeof(seedval),1,file) != 1)
			error("Cannot read /dev/urandom: %s\n",
					strerror(ferror(file)));
		fclose(file);
		gsl_rng_set(*r,seedval);
		info("Using %lu as RNG seed (provided by urandom).\n", seedval);
	}
	else
		info("Using %lu as RNG seed.\n",gsl_rng_default_seed);
	return 0;
}
Example #29
0
void test_0(const int n) {
    gsl_rng_env_setup();
    gsl_rng *r = gsl_rng_alloc(gsl_rng_default);
    
    double *a = gsl_runorm(r, n);
    double *b = gsl_runorm(r, n);

    gsl_rng_free(r);

    double *c = malloc(n * sizeof(double));

    clock_t begin = clock();
    #pragma omp parallel for schedule(static), num_threads(2) 
    for (int i = 0; i < n; i++) {        
        c[i] = a[i] + b[i];
        c[i] = c[i] * (a[i] + b[i]);
        c[i] = c[i] * (a[i] / 2.0);
        c[i] = exp(c[i]);
        c[i] = log(c[i]);
    }
    clock_t end = clock();
    printf("Time elapsed: %e s\n", (end - begin) / ((double) CLOCKS_PER_SEC));
}
Example #30
0
void gauss_xdat(Search_settings *sett, double amplitude, double sigma, int i){

  gsl_rng * r;
  int j;
  unsigned long mySeed;
  mySeed = random_seed();

  const gsl_rng_type * T;
  
  gsl_rng_env_setup();

  T = gsl_rng_default;
  r = gsl_rng_alloc (T);
  gsl_rng_set(r, mySeed);
  // Generate normal distribution (around 0, 
  // with amplitude and sigma as parameters)
  for(j = 0; j < sett->N; j++) 
    ifo[i].sig.xDat[j] = amplitude*gsl_ran_gaussian_ziggurat(r, sigma);
 
  gsl_rng_free(r); 


}