Пример #1
0
/*
 * Cruft, but cannoot be removed until we are done
 */
void test_footer(Dtest *dtest,double pvalue,double *pvalues)
{

 /*
  * Display histogram of ks p-values (optional)
  */
 if(hist_flag){
   histogram(pvalues,psamples,0.0,1.0,10,"p-values");
 }

 if(strncmp("file_input",gsl_rng_name(rng),10) == 0){
   printf("# %u rands were used in this test\n",file_input_get_rtot(rng));
   printf("# The file %s was rewound %u times\n",gsl_rng_name(rng),file_input_get_rewind_cnt(rng));
 }

 printf("#                          Results\n");
 printf("# Kuiper KS: p = %8.6f for %s\n",pvalue,dtest->name);
 printf("# Assessment:\n");
 /* Work through some ranges here */
 if(pvalue < 0.0001){
   printf("# FAILED at < 0.01%%.\n");
 } else if(pvalue < 0.01){
   printf("# POOR at < 1%%.\n");
   printf("# Recommendation:  Repeat test to verify failure.\n");
 } else if(pvalue < 0.05){
   printf("# POSSIBLY WEAK at < 5%%.\n");
   printf("# Recommendation:  Repeat test to verify failure.\n");
 } else {
   printf("# PASSED at > 5%%.\n");
 }

}
Пример #2
0
/*
 * Write a standard test header.
 */
void test_header(Dtest *dtest)
{

 /*
  * Show standard test description
  */
 printf("%s",dtest->description);

 /*
  * This is the non-custom part of the header, which should be enough
  * for nearly all tests by design.
  */
 printf("#                        Run Details\n");

 /*
  * Show the generator being tested, handling file_input generators
  * separately.
  */
 if(strncmp("file_input",gsl_rng_name(rng),10) == 0){
   printf("# Random number generator tested: %s\n",gsl_rng_name(rng));
   printf("# File %s contains %u rands of %c type.\n",filename,filecount,filetype);
 } else {
   printf("# Random number generator tested: %s\n",gsl_rng_name(rng));
 }

 /*
  * Now show both current and default values for tsamples and psamples.
  */
 printf("# Samples per test pvalue = %u (test default is %u)\n",tsamples,dtest->tsamples_std);
 printf("# P-values in final KS test = %u (test default is %u)\n",psamples,dtest->psamples_std);

}
Пример #3
0
/*
 * Write a standard test footer.  Arguments include the test
 * variables, the test pvalue, the ks_pvalues, and a test description.
 */
void show_test_results(Dtest *dtest,Test **test)
{

 int i,j,k;

 /*
  * There may be more than one statistic (final p-value) generated by
  * this test; we loop over all of them.
  */
 /* printf("In show_test_results for %s for %u statistics\n",dtest->name,dtest->nkps); */
 for(i=0;i<dtest->nkps;i++){

   /*
    * Display histogram of ks p-values (optional)
    */
   if(hist_flag){
     /*
     for(j=0;j<test[i]->psamples;j++){
       printf("pvalue = %f\n",test[i]->pvalues[j]);
     }*/
     histogram(test[i]->pvalues,test[i]->psamples,0.0,1.0,10,"p-values");
   }

   if(strncmp("file_input",gsl_rng_name(rng),10) == 0){
     printf("# %u rands were used in this test\n",file_input_get_rtot(rng));
     printf("# The file %s was rewound %u times\n",gsl_rng_name(rng),file_input_get_rewind_cnt(rng));
   }

   printf("#                          Results\n");
   if(test[i]->psamples == 1){
     printf("Single test: p = %8.6f\n",test[i]->ks_pvalue);
     printf("Assessment: ");
     /* Work through some ranges here */
     if(test[i]->ks_pvalue < 0.0001 || test[i]->ks_pvalue > 0.9999){
       printf("FAILED at < 0.02%% for %s\n",dtest->name);
     } else if(test[i]->ks_pvalue < 0.01 || test[i] -> ks_pvalue > 0.99){
       printf("POOR at < 2%% for %s\n",dtest->name);
       printf("Recommendation:  Repeat test to verify failure.\n");
     } else {
       printf("PASSED at > 2%% for %s\n",dtest->name);
     }
   } else {
     printf("Kuiper KS: p = %8.6f\n",test[i]->ks_pvalue);
     printf("Assessment: ");
     /* Work through some ranges here */
     if(test[i]->ks_pvalue < 0.0001){
       printf("FAILED at < 0.01%% for %s\n",dtest->name);
     } else if(test[i]->ks_pvalue < 0.01){
       printf("POOR at < 1%% for %s\n",dtest->name);
       printf("Recommendation:  Repeat test to verify failure.\n");
     } else if(test[i]->ks_pvalue < 0.05){
       printf("POSSIBLY WEAK at < 5%% for %s\n",dtest->name);
       printf("Recommendation:  Repeat test to verify failure.\n");
     } else {
       printf("PASSED at > 5%% for %s\n",dtest->name);
     }
   }
 }

}
void run_user_template()
{


 /*
  * Declare the results struct.
  */
 Test **user_template_test;

 /*
  * First we create the test (to set some values displayed in test header
  * correctly).
  */
 user_template_test = create_test(&user_template_dtest,tsamples,psamples,&user_template);

 /*
  * Set any GLOBAL data used by the test.  This is very test specific -- most
  * library tests won't have any but a few do.  The data will usually be input
  * via one of the special command line variables reserved for that purpose,
  * and only can work if the -a(ll) flag is not set -- otherwise test specific
  * defaults are used.
  */
 user_template_lag = (int)x_user;

 /*
  * Show the standard test header for this test.
  */
 show_test_header(&user_template_dtest,user_template_test);

 /*
  * This is where we can output any test-specific information (such as
  * the value of the lag).   In dieharder, I tend to start each output
  * line with an # to make things all pretty.
  */
 printf("# Lag used in %s test: %u\n",user_template_dtest.name,user_template_lag);

 /*
  * Set any GLOBAL data used by the test.  Then call the test itself
  * This fills in the results in the Test struct.
  */
 std_test(&user_template_dtest,user_template_test);

 /*
  * This almost certainly belongs in the show_test_results section,
  * possibly with additional conditionals rejecting test results involving
  * rewinds, period.
  */
 if(strncmp("file_input",gsl_rng_name(rng),10) == 0){
   printf("# %u rands were used in this test\n",file_input_get_rtot(rng));
   printf("# The file %s was rewound %u times\n",gsl_rng_name(rng),file_input_get_rewind_cnt(rng));
 }

 /*
  * Show standard test results, for all statistics generated by a single run.
  */
 show_test_results(&user_template_dtest,user_template_test);

}
void run_diehard_sums()
{


 /*
  * Declare the results struct.
  */
 Test **diehard_sums_test;

 /*
  * First we create the test (to set some values displayed in test header
  * correctly).
  */
 diehard_sums_test = create_test(&diehard_sums_dtest,tsamples,psamples,&diehard_sums);

 /*
  * Set any GLOBAL data used by the test.
  */
 diehard_sums_rand_dbl = (double *)malloc((size_t) diehard_sums_test[0]->tsamples*sizeof(double));

 /*
  * Show the standard test header for this test.
  */
 show_test_header(&diehard_sums_dtest,diehard_sums_test);

 /*
  * This is where we can output any test-specific information.
  */

 /*
  * Set any GLOBAL data used by the test.  Then call the test itself
  * This fills in the results in the Test struct.
  */
 std_test(&diehard_sums_dtest,diehard_sums_test);

 /*
  * This almost certainly belongs in the show_test_results section,
  * possibly with additional conditionals rejecting test results involving
  * rewinds, period.
  */
 if(strncmp("file_input",gsl_rng_name(rng),10) == 0){
   printf("# %u rands were used in this test\n",file_input_get_rtot(rng));
   printf("# The file %s was rewound %u times\n",gsl_rng_name(rng),file_input_get_rewind_cnt(rng));
 }

 /*
  * Show standard test results, for all statistics generated by a single run.
  */
 show_test_results(&diehard_sums_dtest,diehard_sums_test);

 /*
  * Free global memory
  */
 free(diehard_sums_rand_dbl);


}
void run_marsaglia_tsang_gcd()
{


 /*
  * Declare the results struct.
  */
 Test **marsaglia_tsang_gcd_test;

 /*
  * First we create the test (to set some values displayed in test header
  * correctly).
  */
 marsaglia_tsang_gcd_test = create_test(&marsaglia_tsang_gcd_dtest,tsamples,psamples,&marsaglia_tsang_gcd);

 /*
  * Set any GLOBAL data used by the test.
  */

 /*
  * Show the standard test header for this test.
  */
 show_test_header(&marsaglia_tsang_gcd_dtest,marsaglia_tsang_gcd_test);

 /*
  * This is where we can output any test-specific information.
  */

 /*
  * Set any GLOBAL data used by the test.  Then call the test itself
  * This fills in the results in the Test struct.
  */
 std_test(&marsaglia_tsang_gcd_dtest,marsaglia_tsang_gcd_test);

 /*
  * This almost certainly belongs in the show_test_results section,
  * possibly with additional conditionals rejecting test results involving
  * rewinds, period.
  */
 if(strncmp("file_input",gsl_rng_name(rng),10) == 0){
   printf("# %u rands were used in this test\n",file_input_get_rtot(rng));
   printf("# The file %s was rewound %u times\n",gsl_rng_name(rng),file_input_get_rewind_cnt(rng));
 }

 /*
  * Show standard test results, for all statistics generated by a single run.
  */
 show_test_results(&marsaglia_tsang_gcd_dtest,marsaglia_tsang_gcd_test);

}
Пример #7
0
void LargeMatrix::GenerateRandom(std::string a_filename, int a_num_rows, int a_ioflags)
	{
		//std::cout << "Nothing yet implemented for GenerateRandom" << std::endl;
		std::ofstream mtx_file;

		gsl_rng * r;
		const gsl_rng_type * T;
		gsl_rng_env_setup();
		T = gsl_rng_default;
		r = gsl_rng_alloc(T);
		gsl_rng_set(r, 90210);
		std::vector<Real> rand_row(a_num_rows, 0);
		std::cout << "Generator type: " << gsl_rng_name(r) << std::endl;
		
		mtx_file.open(a_filename.c_str());
		for (int i = 0 ; i < a_num_rows ; i++)
			{	
				for (int j = 0 ; j < a_num_rows ; j++)
					{
						rand_row[j] = gsl_rng_uniform(r);
					}
				for (int j = 0 ; j < a_num_rows ; j++)
					{
						mtx_file << rand_row[j] << ",";
					}
				mtx_file << std::endl;
			}
		mtx_file.close();

		gsl_rng_free(r);
	}
Пример #8
0
void
rng_test (const gsl_rng_type * T, unsigned long int seed, unsigned int n,
          unsigned long int result)
{
  gsl_rng *r = gsl_rng_alloc (T);
  unsigned int i;
  unsigned long int k = 0;
  int status;

  if (seed != 0)
    {
      gsl_rng_set (r, seed);
    }

  for (i = 0; i < n; i++)
    {
      k = gsl_rng_get (r);
    }

  status = (k != result);
  printf ( "%s, %u steps (%u observed vs %u expected)",
            gsl_rng_name (r), n, k, result);
/*
  gsl_test (status, "%s, %u steps (%u observed vs %u expected)",
            gsl_rng_name (r), n, k, result);
*/

  gsl_rng_free (r);
}
Пример #9
0
int
random_generator_alloc (void)
{
  gsl_rng_env_setup ();
  random_seed = gsl_rng_default_seed;
  
  if (!gsl_rng_default_seed)
    {
      no_random_seed ();
      rng = NULL;
      return 0;
    }

  rng_type = gsl_rng_default;
  rng = gsl_rng_alloc (rng_type);

  log_to_logfile ("Allocatat generador random (gsl_rng).", 
		  __FILE__, __LINE__);

  char log_gsl_rng_name[100];
  sprintf (log_gsl_rng_name, "gsl_rng_name = %s", gsl_rng_name (rng));
  log_to_logfile (log_gsl_rng_name, __FILE__, __LINE__);

  char log_gsl_seed[100];
  sprintf (log_gsl_seed, "GSL_RNG_SEED = %d", (int) gsl_rng_default_seed);
  log_to_logfile (log_gsl_seed, __FILE__, __LINE__);

  return 0;
}
Пример #10
0
void
generic_rng_test (const gsl_rng_type * T)
{
  gsl_rng *r = gsl_rng_alloc (T);
  const char *name = gsl_rng_name (r);
  unsigned long int kmax = 0, kmin = 1000;
  double sigma = 0;
  const unsigned long int ran_max = gsl_rng_max (r);
  const unsigned long int ran_min = gsl_rng_min (r);

  int status = rng_max_test (r, &kmax, ran_max);

  /*gsl_test (status,*/
            /*"%s, observed vs theoretical maximum (%lu vs %lu)",*/
            /*name, kmax, ran_max);*/

  status = rng_min_test (r, &kmin, ran_min, ran_max);

  /*gsl_test (status,*/
            /*"%s, observed vs theoretical minimum (%lu vs %lu)",*/
            /*name, kmin, ran_min);*/

  status = rng_sum_test (r, &sigma);

  /*gsl_test (status,*/
            /*"%s, sum test within acceptable sigma (observed %.2g
 * sigma)",*/
            /*name, sigma);*/

  status = rng_bin_test (r, &sigma);

  /*gsl_test (status,*/
            /*"%s, bin test within acceptable chisq (observed %.2g
 * sigma)",*/
            /*name, sigma);*/

  gsl_rng_set (r, 1);   /* set seed to 1 */
  status = rng_max_test (r, &kmax, ran_max);

  gsl_rng_set (r, 1);   /* set seed to 1 */
  status |= rng_min_test (r, &kmin, ran_min, ran_max);

  gsl_rng_set (r, 1);   /* set seed to 1 */
  status |= rng_sum_test (r, &sigma);

  gsl_rng_set (r, 12345);       /* set seed to a "typical" value */
  status |= rng_max_test (r, &kmax, ran_max);

  gsl_rng_set (r, 12345);       /* set seed to a "typical" value */
  status |= rng_min_test (r, &kmin, ran_min, ran_max);

  gsl_rng_set (r, 12345);       /* set seed to a "typical" value */
  status |= rng_sum_test (r, &sigma);

  /*gsl_test (status, "%s, maximum and sum tests for non-default seeds",
 * name);*/

  gsl_rng_free (r);
}
Пример #11
0
 void ranran_setup(int s)
 {
   gsl_rng_env_setup();
   T = gsl_rng_default;
   r = gsl_rng_alloc (T);
   std::cerr << gsl_rng_name (r) << "\n";
   gsl_rng_set(r, s);
 }
Пример #12
0
/* gsl rng stuff */
int ggen_rng_init(gsl_rng **r)
{
	const gsl_rng_type *T;
	gsl_rng_env_setup();

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

	info("Using %s as RNG.\n",gsl_rng_name(*r));
	info("Using %lu as RNG seed.\n",gsl_rng_default_seed);
	return 0;
}
Пример #13
0
int main(void) {
	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));

	gsl_rng_free (r);

	return EXIT_SUCCESS;
}
Пример #14
0
void
rng_parallel_state_test (const gsl_rng_type * T)
{
  unsigned long int test_a[N], test_b[N];
  unsigned long int test_c[N], test_d[N];
  double test_e[N], test_f[N];

  int i;

  gsl_rng *r1 = gsl_rng_alloc (T);
  gsl_rng *r2 = gsl_rng_alloc (T);

  for (i = 0; i < N; ++i)
    {
      gsl_rng_get (r1);		/* throw away N iterations */
    }

  gsl_rng_memcpy (r2, r1);		/* save the intermediate state */

  for (i = 0; i < N; ++i)
    {
      /* check that there is no hidden state intermixed between r1 and r2 */
      test_a[i] = gsl_rng_get (r1);	
      test_b[i] = gsl_rng_get (r2);
      test_c[i] = gsl_rng_uniform_int (r1, 1234);	
      test_d[i] = gsl_rng_uniform_int (r2, 1234);
      test_e[i] = gsl_rng_uniform (r1);	
      test_f[i] = gsl_rng_uniform (r2);
    }

  {
    int status = 0;
    for (i = 0; i < N; ++i)
      {
	status |= (test_b[i] != test_a[i]);
	status |= (test_c[i] != test_d[i]);
	status |= (test_e[i] != test_f[i]);
      }
    gsl_test (status, "%s, parallel random number state consistency",
	      gsl_rng_name (r1));
  }

  gsl_rng_free (r1);
  gsl_rng_free (r2);

}
Пример #15
0
int
rng_bin_test (gsl_rng * r, double *sigma)
{
  int count[BINS+EXTRA];
  double chisq = 0;
  int i, status;

  for (i = 0; i < BINS+EXTRA; i++)
      count[i] = 0 ;


  for (i = 0; i < N2; i++)
    {
      int j = gsl_rng_uniform_int (r, BINS);
      count[j]++ ;
    }

  chisq = 0 ;
  for (i = 0; i < BINS; i++)
    {
      double x = (double)N2/(double)BINS ;
      double d = (count[i] - x) ;
      chisq += (d*d) / x;
    }

  *sigma = sqrt(chisq/BINS) ;

  /* more than 3 sigma is an error */
  
  status = (fabs (*sigma) > 3 || fabs(*sigma) < 0.003);

  for (i = BINS; i < BINS+EXTRA; i++)
    {
      if (count[i] != 0)
	{
	  status = 1 ;
	  gsl_test (status, 
		    "%s, wrote outside range in bin test "
		    "(%d observed vs %d expected)",
		    gsl_rng_name(r), i, BINS - 1);
	}
    }

  return status;
}
Пример #16
0
void
rng_state_test (const gsl_rng_type * T)
{
  unsigned long int test_a[N], test_b[N];

  int i;

  gsl_rng *r = gsl_rng_alloc (T);
  gsl_rng *r_save = gsl_rng_alloc (T);

  for (i = 0; i < N; ++i)
    {
      gsl_rng_get (r);	/* throw away N iterations */
    }

  gsl_rng_memcpy (r_save, r);	/* save the intermediate state */

  for (i = 0; i < N; ++i)
    {
      test_a[i] = gsl_rng_get (r);
    }

  gsl_rng_memcpy (r, r_save);	/* restore the intermediate state */
  gsl_rng_free (r_save);

  for (i = 0; i < N; ++i)
    {
      test_b[i] = gsl_rng_get (r);
    }

  {
    int status = 0;
    for (i = 0; i < N; ++i)
      {
	status |= (test_b[i] != test_a[i]);
      }
    gsl_test (status, "%s, random number state consistency",
	      gsl_rng_name (r));
  }

  gsl_rng_free (r);
}
Пример #17
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));
}
Пример #18
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
}
Пример #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 */
}
void run_rgb_timing()
{

 /*
  * Declare the results struct.
  */
 Rgb_Timing timing;
 Test **rgb_timing_test;

 /*
  * First we create the test (to set some values displayed in test header
  * correctly).
  */
 rgb_timing_test = create_test(&rgb_timing_dtest,tsamples,psamples,&rgb_timing);

 /*
  * Set any GLOBAL data used by the test.
  */

 /*
  * Show the standard test header for this test.
  */
 show_test_header(&rgb_timing_dtest,rgb_timing_test);

 /*
  * Call the actual test that fills in the results struct.
  */
 rgb_timing(rgb_timing_test,&timing);

 /*
  * Display the results.
  */
 printf("#========================================================================\n");
 printf("# rgb_timing() test using the %s generator \n",gsl_rng_name(rng));
 printf("# Average time per rand = %e nsec.\n",timing.avg_time_nsec);
 printf("# Rands per second = %e.\n",timing.rands_per_sec);

}
Пример #21
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;
}
Пример #22
0
void
rng_float_test (const gsl_rng_type * T)
{
  gsl_rng *ri = gsl_rng_alloc (T);
  gsl_rng *rf = gsl_rng_alloc (T);

  double u, c ; 
  unsigned int i;
  unsigned long int k = 0;
  int status = 0 ;

  do 
    {
      k = gsl_rng_get (ri);
      u = gsl_rng_get (rf);
    } 
  while (k == 0) ;

  c = k / u ;
  for (i = 0; i < N2; i++)
    {
      k = gsl_rng_get (ri);
      u = gsl_rng_get (rf);
      if (c*k != u)
	{
	  status = 1 ;
	  break ;
	}
    }

  gsl_test (status, "%s, ratio of int to double (%g observed vs %g expected)",
	    gsl_rng_name (ri), c, k/u);

  gsl_rng_free (ri);
  gsl_rng_free (rf);
}
Пример #23
0
int rgb_lmn()
{

 double pks;
 uint ps_save=0,ts_save=0;

 /*
  * Do a standard test if -a(ll) is selected.
  * ALSO use standard values if tsamples or psamples are 0
  */
 if(all == YES){
   ts_save = tsamples;
   tsamples = dtest->tsamples_std;
   ps_save = psamples;
   psamples = dtest->psamples_std;
 }
 if(tsamples == 0){
   tsamples = dtest->tsamples_std;
 }
 if(psamples == 0){
   psamples = dtest->psamples_std;
 }
 
 /*
  * Allocate memory for THIS test's ks_pvalues, etc.  Make sure that
  * any missed prior allocations are freed.
  */
 if(ks_pvalue) nullfree(ks_pvalue);
 ks_pvalue  = (double *)malloc((size_t) psamples*sizeof(double));

 /*
  * Reseed FILE random number generators once per individual test.
  * This correctly resets the rewind counter per test.
  */
 if(strncmp("file_input",gsl_rng_name(rng),10) == 0){
   gsl_rng_set(rng,1);
 }

 /* show_test_header(dtest); */

 /*
  * Any custom test header output lines go here.  They should be
  * used VERY sparingly.
  */

 /*
  * This is the standard test call.
  */
 kspi = 0;  /* Always zero first */
 /* pks = sample((void *)rgb_lmn_test); */

 /*
  * Test Results, standard form.
 show_test_results(dtest,pks,ks_pvalue,"Lagged Sum Test");
  */

 /*
  * Put back tsamples
  */
 if(all == YES){
   tsamples = ts_save;
   psamples = ps_save;
 }

 if(ks_pvalue) nullfree(ks_pvalue);

 return(0);

}
Пример #24
0
/** Initialize Fstat-code: handle user-input and set everything up. */
int
XLALInitCode ( ConfigVariables *cfg, const UserInput_t *uvar )
{
  /* generate log-string for file-output, containing cmdline-options + code VCS version info */
  char *vcs;
  if ( (vcs = XLALGetVersionString(0)) == NULL ) {	  /* short VCS version string */
    XLALPrintError ( "%s: XLALGetVersionString(0) failed with errno=%d.\n", __func__, xlalErrno );
    XLAL_ERROR ( XLAL_EFUNC );
  }
  char *cmdline;
  if ( (cmdline = XLALUserVarGetLog ( UVAR_LOGFMT_CMDLINE )) == NULL ) {
    XLALPrintError ( "%s: XLALUserVarGetLog ( UVAR_LOGFMT_CMDLINE ) failed with errno=%d.\n", __func__, xlalErrno );
    XLAL_ERROR ( XLAL_EFUNC );
  }
  const char fmt[] = "%%%% cmdline: %s\n%%%%\n%s%%%%\n";
  UINT4 len = strlen(vcs) + strlen(cmdline) + strlen(fmt) + 1;
  if ( ( cfg->logString = XLALMalloc ( len  )) == NULL ) {
    XLALPrintError ("%s: XLALMalloc ( %d ) failed.\n", __func__, len );
    XLAL_ERROR ( XLAL_ENOMEM );
  }
  sprintf ( cfg->logString, fmt, cmdline, vcs );
  XLALFree ( cmdline );
  XLALFree ( vcs );

  /* trivial settings from user-input */
  cfg->SignalOnly = uvar->SignalOnly;

  /* ----- parse user-input on signal amplitude-paramters + ranges ----- */
  /* skypos */
  cfg->skypos.longitude = uvar->Alpha;	/* Alpha < 0 indicates 'allsky' */
  cfg->skypos.latitude  = uvar->Delta;
  cfg->skypos.system = COORDINATESYSTEM_EQUATORIAL;

  /* ----- amplitude-params: create prior pdfs reflecting the user-input */
  if ( XLALInitAmplitudePrior ( &cfg->AmpPrior, uvar ) != XLAL_SUCCESS )
    XLAL_ERROR ( XLAL_EFUNC );

  /* ----- initialize random-number generator ----- */
  /* read out environment variables GSL_RNG_xxx
   * GSL_RNG_SEED: use to set random seed: default = 0, override by using --randSeed on cmdline
   * GSL_RNG_TYPE: type of random-number generator to use: default = 'mt19937'
   */
  gsl_rng_env_setup ();
  /* allow overriding the random-seed per command-line */
  if ( XLALUserVarWasSet ( &uvar->randSeed ) )
    gsl_rng_default_seed = uvar->randSeed;
  cfg->rng = gsl_rng_alloc (gsl_rng_default);

  LogPrintf ( LOG_DEBUG, "random-number generator type: %s\n", gsl_rng_name (cfg->rng));
  LogPrintf ( LOG_DEBUG, "seed = %lu\n", gsl_rng_default_seed );

  /* init ephemeris-data */
  EphemerisData *edat = XLALInitBarycenter( uvar->ephemEarth, uvar->ephemSun );
  if ( !edat ) {
    LogPrintf ( LOG_CRITICAL, "%s: XLALInitBarycenter failed: could not load Earth ephemeris '%s' and Sun ephemeris '%s'\n", __func__, uvar->ephemEarth, uvar->ephemSun);
    XLAL_ERROR ( XLAL_EFUNC );
  }

  /* init detector info */
  LALDetector *site;
  if ( (site = XLALGetSiteInfo ( uvar->IFO )) == NULL ) {
    XLALPrintError ("%s: Failed to get site-info for detector '%s'\n", __func__, uvar->IFO );
    XLAL_ERROR ( XLAL_EFUNC );
  }
  MultiLALDetector multiDet;
  multiDet.length = 1;
  multiDet.sites[0] = (*site); 	/* copy! */
  XLALFree ( site );

  /* init timestamps vector covering observation time */
  UINT4 numSteps = (UINT4) ceil ( uvar->dataDuration / uvar->TAtom );
  MultiLIGOTimeGPSVector * multiTS;
  if ( (multiTS = XLALCalloc ( 1, sizeof(*multiTS))) == NULL ) {
    XLAL_ERROR ( XLAL_ENOMEM );
  }
  multiTS->length = 1;
  if ( (multiTS->data = XLALCalloc (1, sizeof(*multiTS->data))) == NULL ) {
    XLAL_ERROR ( XLAL_ENOMEM );
  }
  if ( (multiTS->data[0] = XLALCreateTimestampVector (numSteps)) == NULL ) {
    XLALPrintError ("%s: XLALCreateTimestampVector(%d) failed.\n", __func__, numSteps );
  }
  multiTS->data[0]->deltaT = uvar->TAtom;
  UINT4 i;
  for ( i=0; i < numSteps; i ++ )
    {
      UINT4 ti = uvar->dataStartGPS + i * uvar->TAtom;
      multiTS->data[0]->data[i].gpsSeconds = ti;
      multiTS->data[0]->data[i].gpsNanoSeconds = 0;
    }

  /* get detector states */
  if ( (cfg->multiDetStates = XLALGetMultiDetectorStates ( multiTS, &multiDet, edat, 0.5 * uvar->TAtom )) == NULL ) {
    XLALPrintError ( "%s: XLALGetMultiDetectorStates() failed.\n", __func__ );
    XLAL_ERROR ( XLAL_EFUNC );
  }

  /* get rid of all temporary memory allocated for this step */
  XLALDestroyEphemerisData ( edat );
  XLALDestroyMultiTimestamps ( multiTS );
  multiTS = NULL;


  /* ---------- initialize transient window ranges, for injection ... ---------- */
  transientWindowRange_t XLAL_INIT_DECL(InjectRange);
  int twtype;
  XLAL_CHECK ( (twtype = XLALParseTransientWindowName ( uvar->injectWindow_type )) >= 0, XLAL_EFUNC );
  InjectRange.type = twtype;

  /* make sure user doesn't set window=none but sets window-parameters => indicates she didn't mean 'none' */
  if ( InjectRange.type == TRANSIENT_NONE ) {
    if ( XLALUserVarWasSet ( &uvar->injectWindow_t0Days ) || XLALUserVarWasSet ( &uvar->injectWindow_t0DaysBand ) ||
         XLALUserVarWasSet ( &uvar->injectWindow_tauDays ) || XLALUserVarWasSet ( &uvar->injectWindow_tauDaysBand ) ) {
      XLALPrintError ("%s: ERROR: injectWindow_type == NONE, but window-parameters were set! Use a different window-type!\n", __func__ );
      XLAL_ERROR ( XLAL_EINVAL );
    }
  }

  if ( uvar->injectWindow_t0DaysBand < 0 || uvar->injectWindow_tauDaysBand < 0 ) {
    XLALPrintError ("%s: only positive t0/tau window injection bands allowed (%f, %f)\n", __func__, uvar->injectWindow_t0DaysBand, uvar->injectWindow_tauDaysBand );
    XLAL_ERROR ( XLAL_EINVAL );
  }

  /* apply correct defaults if unset: t0=dataStart, t0Band=dataDuration-3*tauMax */
  InjectRange.t0 = uvar->dataStartGPS + uvar->injectWindow_t0Days * DAY24;

  REAL8 tauMax = ( uvar->injectWindow_tauDays +  uvar->injectWindow_tauDaysBand ) * DAY24;
  if ( XLALUserVarWasSet (&uvar->injectWindow_t0DaysBand ) )
    InjectRange.t0Band  = uvar->injectWindow_t0DaysBand * DAY24;
  else
    InjectRange.t0Band  = fmax ( 0.0, uvar->dataDuration - TRANSIENT_EXP_EFOLDING * tauMax - InjectRange.t0 ); 	/* make sure it's >= 0 */

  InjectRange.tau     = (UINT4) ( uvar->injectWindow_tauDays * DAY24 );
  InjectRange.tauBand = (UINT4) ( uvar->injectWindow_tauDaysBand * DAY24 );

  cfg->transientInjectRange = InjectRange;

  /* ---------- ... and for search -------------------- */
  transientWindowRange_t XLAL_INIT_DECL(SearchRange);
  XLAL_CHECK ( (twtype = XLALParseTransientWindowName ( uvar->searchWindow_type )) >= 0, XLAL_EFUNC );
  SearchRange.type = twtype;

  /* apply correct defaults if unset: use inect window */
  if ( !XLALUserVarWasSet ( &uvar->searchWindow_type ) )
    SearchRange.type    = InjectRange.type;
  if ( !XLALUserVarWasSet ( &uvar->searchWindow_t0Days ) )
    SearchRange.t0      = InjectRange.t0;
  else
    SearchRange.t0      = uvar->dataStartGPS + uvar->searchWindow_t0Days * DAY24;
  if ( !XLALUserVarWasSet ( &uvar->searchWindow_t0DaysBand ) )
    SearchRange.t0Band = InjectRange.t0Band;
  else
    SearchRange.t0Band  = (UINT4) (uvar->searchWindow_t0DaysBand * DAY24);
  if ( !XLALUserVarWasSet ( &uvar->searchWindow_tauDays ) )
    SearchRange.tau = InjectRange.tau;
  else
    SearchRange.tau     = (UINT4) ( uvar->searchWindow_tauDays * DAY24 );
  if ( !XLALUserVarWasSet ( &uvar->searchWindow_tauDaysBand ) )
    SearchRange.tauBand = InjectRange.tauBand;
  else
    SearchRange.tauBand = (UINT4) ( uvar->searchWindow_tauDaysBand * DAY24 );

  if ( XLALUserVarWasSet ( &uvar->searchWindow_dt0 ) )
    SearchRange.dt0 = uvar->searchWindow_dt0;
  else
    SearchRange.dt0 = uvar->TAtom;

  if ( XLALUserVarWasSet ( &uvar->searchWindow_dtau ) )
    SearchRange.dtau = uvar->searchWindow_dtau;
  else
    SearchRange.dtau = uvar->TAtom;

  /* make sure user doesn't set window=none but sets window-parameters => indicates she didn't mean 'none' */
  if ( SearchRange.type == TRANSIENT_NONE )
    if ( XLALUserVarWasSet ( &uvar->searchWindow_t0Days ) || XLALUserVarWasSet ( &uvar->searchWindow_t0DaysBand ) ||
         XLALUserVarWasSet ( &uvar->searchWindow_tauDays ) || XLALUserVarWasSet ( &uvar->searchWindow_tauDaysBand ) ) {
      XLALPrintError ("%s: ERROR: searchWindow_type == NONE, but window-parameters were set! Use a different window-type!\n", __func__ );
      XLAL_ERROR ( XLAL_EINVAL );
    }

  if (   uvar->searchWindow_t0DaysBand < 0 || uvar->searchWindow_tauDaysBand < 0 ) {
    XLALPrintError ("%s: only positive t0/tau window injection bands allowed (%f, %f)\n", __func__, uvar->searchWindow_t0DaysBand, uvar->searchWindow_tauDaysBand );
    XLAL_ERROR ( XLAL_EINVAL );
  }

  cfg->transientSearchRange = SearchRange;

  return XLAL_SUCCESS;

} /* XLALInitCode() */
Пример #25
0
/** Initialize Fstat-code: handle user-input and set everything up. */
int
XLALInitCode ( ConfigVariables *cfg, const UserInput_t *uvar )
{
  /* generate log-string for file-output, containing cmdline-options + code VCS version info */
  char *vcs;
  if ( (vcs = XLALGetVersionString(0)) == NULL ) {	  /* short VCS version string */
    XLALPrintError ( "%s: XLALGetVersionString(0) failed with errno=%d.\n", __func__, xlalErrno );
    XLAL_ERROR ( XLAL_EFUNC );
  }
  char *cmdline;
  if ( (cmdline = XLALUserVarGetLog ( UVAR_LOGFMT_CMDLINE )) == NULL ) {
    XLALPrintError ( "%s: XLALUserVarGetLog ( UVAR_LOGFMT_CMDLINE ) failed with errno=%d.\n", __func__, xlalErrno );
    XLAL_ERROR ( XLAL_EFUNC );
  }
  const char fmt[] = "%%%% cmdline: %s\n%%%%\n%s%%%%\n";
  UINT4 len = strlen(vcs) + strlen(cmdline) + strlen(fmt) + 1;
  if ( ( cfg->logString = XLALMalloc ( len  )) == NULL ) {
    XLALPrintError ("%s: XLALMalloc ( %d ) failed.\n", __func__, len );
    XLAL_ERROR ( XLAL_ENOMEM );
  }
  sprintf ( cfg->logString, fmt, cmdline, vcs );
  XLALFree ( cmdline );
  XLALFree ( vcs );

  /* trivial settings from user-input */
  cfg->SignalOnly = uvar->SignalOnly;

  /* ----- parse user-input on signal amplitude-paramters + ranges ----- */
  /* skypos */
  cfg->skypos.longitude = uvar->Alpha;	/* Alpha < 0 indicates 'allsky' */
  cfg->skypos.latitude  = uvar->Delta;
  cfg->skypos.system = COORDINATESYSTEM_EQUATORIAL;

  /* ----- amplitude-params: create prior pdfs reflecting the user-input */
  if ( XLALInitAmplitudePrior ( &cfg->AmpPrior, uvar ) != XLAL_SUCCESS )
    XLAL_ERROR ( XLAL_EFUNC );

  /* ----- initialize random-number generator ----- */
  /* read out environment variables GSL_RNG_xxx
   * GSL_RNG_SEED: use to set random seed: default = 0, override by using --randSeed on cmdline
   * GSL_RNG_TYPE: type of random-number generator to use: default = 'mt19937'
   */
  gsl_rng_env_setup ();
  /* allow overriding the random-seed per command-line */
  if ( XLALUserVarWasSet ( &uvar->randSeed ) )
    gsl_rng_default_seed = uvar->randSeed;
  cfg->rng = gsl_rng_alloc (gsl_rng_default);

  LogPrintf ( LOG_DEBUG, "random-number generator type: %s\n", gsl_rng_name (cfg->rng));
  LogPrintf ( LOG_DEBUG, "seed = %lu\n", gsl_rng_default_seed );

  /* init ephemeris-data */
  EphemerisData *edat = XLALInitBarycenter( uvar->ephemEarth, uvar->ephemSun );
  if ( !edat ) {
    LogPrintf ( LOG_CRITICAL, "%s: XLALInitBarycenter failed: could not load Earth ephemeris '%s' and Sun ephemeris '%s'\n", __func__, uvar->ephemEarth, uvar->ephemSun);
    XLAL_ERROR ( XLAL_EFUNC );
  }

  UINT4 numDetectors = uvar->IFOs->length;
  MultiLALDetector multiDet;
  XLAL_CHECK ( XLALParseMultiLALDetector ( &multiDet, uvar->IFOs ) == XLAL_SUCCESS, XLAL_EFUNC );

  /* init timestamps vector covering observation time */
  UINT4 numSteps = (UINT4) ceil ( uvar->dataDuration / uvar->TAtom );
  MultiLIGOTimeGPSVector * multiTS;
  if ( (multiTS = XLALCreateMultiLIGOTimeGPSVector (numDetectors)) == NULL ) {
     XLALPrintError ("%s: XLALCreateMultiLIGOTimeGPSVector(%d) failed.\n", __func__, numDetectors );
  }

  for ( UINT4 X=0; X < numDetectors; X++ )    {
    if ( (multiTS->data[X] = XLALCreateTimestampVector (numSteps)) == NULL ) {
      XLALPrintError ("%s: XLALCreateTimestampVector(%d) failed.\n", __func__, numSteps );
    }
    multiTS->data[X]->deltaT = uvar->TAtom;
    UINT4 i;
    for ( i=0; i < numSteps; i ++ )
      {
	UINT4 ti = uvar->dataStartGPS + i * uvar->TAtom;
	multiTS->data[X]->data[i].gpsSeconds = ti;
	multiTS->data[X]->data[i].gpsNanoSeconds = 0;
      }
  }

  /* get detector states */
  if ( (cfg->multiDetStates = XLALGetMultiDetectorStates ( multiTS, &multiDet, edat, 0.5 * uvar->TAtom )) == NULL ) {
    XLALPrintError ( "%s: XLALGetMultiDetectorStates() failed.\n", __func__ );
    XLAL_ERROR ( XLAL_EFUNC );
  }

  if ( uvar->sqrtSX ) { /* translate user-input PSD sqrt(SX) to noise-weights (this actually does not care whether they were normalized or not) */

    /* parse input comma-separated list */
    MultiNoiseFloor multiNoiseFloor;
    XLAL_CHECK ( XLALParseMultiNoiseFloor ( &multiNoiseFloor, uvar->sqrtSX, numDetectors ) == XLAL_SUCCESS, XLAL_EFUNC );

    /* translate to noise weights */
    XLAL_CHECK ( ( cfg->multiNoiseWeights = XLALComputeConstantMultiNoiseWeightsFromNoiseFloor ( &multiNoiseFloor, multiTS, uvar->TAtom ) ) != NULL, XLAL_EFUNC );

  } /* if ( uvar->sqrtSX ) */

  /* get rid of all temporary memory allocated for this step */
  XLALDestroyEphemerisData ( edat );
  XLALDestroyMultiTimestamps ( multiTS );
  multiTS = NULL;

  /* ---------- initialize transient window ranges, for injection ... ---------- */
  cfg->transientInjectRange.type = TRANSIENT_NONE;			/* default: no transient signal window */
  /* apply correct defaults if unset: t0=dataStart, t0Band=dataDuration-3*tauMax */
//   cfg->transientInjectRange.t0 = uvar->dataStartGPS + uvar->injectWindow_t0Days * DAY24;

  cfg->transientSearchRange = cfg->transientInjectRange;
  return XLAL_SUCCESS;

} /* XLALInitCode() */
void run_rgb_persist()
{

 /*
  * Declare the results struct.
  */
 Rgb_Persist persist;
 Test **rgb_persist_test;

 /*
  * First we create the test (to set some values displayed in test header
  * correctly).
  */
 rgb_persist_test = create_test(&rgb_persist_dtest,tsamples,psamples,&rgb_persist);

 /*
  * Set any GLOBAL data used by the test.
  *
  * We arbitrarily choose 256 successive random numbers as enough.
  * This should be plenty -- the probability of any bit slot not
  * changing by CHANCE in 256 tries is 2^-256 or almost 10^-26,
  * so even with 32 bit slots, repeatedly, we aren't horribly likely
  * to see it in our lifetime unless we run this test continuously for
  * months at a time (yes, a dumb idea).
  */
 rgb_persist_rand_uint = (unsigned int*)malloc(256 * sizeof(unsigned int));

 /*
  * Show the standard test header for this test.
  */
 show_test_header(&rgb_persist_dtest,rgb_persist_test);

 /*
  * Call the actual test that fills in the results struct.
  */
 rgb_persist(rgb_persist_test,&persist);

 if(strncmp("file_input",gsl_rng_name(rng),10) == 0){
   printf("# %u rands were used in this test\n",file_input_get_rtot(rng));
   printf("# The file %s was rewound %u times\n",gsl_rng_name(rng),file_input_get_rewind_cnt(rng));
 }
 printf("#==================================================================\n");
 printf("#                          Results\n");
 printf("# Results for %s rng, using its %d valid bits:\n",gsl_rng_name(rng),rmax_bits);
 printf("# (Cumulated mask of zero is good.)\n");
 printf("# cumulated_mask = %10u = ",persist.cumulative_mask);
 dumpbits(&persist.cumulative_mask,persist.nbits);
 printf("\n# randm_mask     = %10u = ",rmax_mask);
 dumpbits(&rmax_mask,persist.nbits);
 printf("\n# random_max     = %10u = ",random_max);
 dumpbits(&random_max,persist.nbits);
 if(persist.cumulative_mask){
   printf("\n# rgb_persist test FAILED (bits repeat)\n");
 } else {
   printf("\n# rgb_persist test PASSED (no bits repeat)\n");
 }
 printf("#==================================================================\n");

 free(rgb_persist_rand_uint);

}
Пример #27
0
//===============================================================
//               MAIN Program
//===============================================================
int main(int argc, char *argv[])
{ 
printf("numbead %d \n",NUMBEAD);

  setbuf(stdout,NULL);

  //===============================================================
  // Declare variables and print to std output for reference
  //===============================================================
  //define the Config sturcts. Example: configOld[n].pos[i][j]
  //where n->Bead i->Particle j->dimension
  //configOld and configCurrent are switched between when doing MD
  config *configOld = calloc(NUMBEAD,sizeof(config));
  config *configCurrent = calloc(NUMBEAD,sizeof(config));
  config *configNew = calloc(NUMBEAD,sizeof(config));

  //Used to save positions for MHMC rejection
  position *savePos = calloc(NUMBEAD,sizeof(position));

  //averages
  averages *tubeAve = calloc(NUMBEAD,sizeof(averages));

  double doubleNUMu=(double)NUMu;
  double doubleNUMl=(double)NUMl;

  //Parameters
  double du=DU;
  double dt=PREDT*DU*DU;
  double h=sqrt(2.0l*dt);

  //Incrimenter Declarations
  int i,j,acc,rej;
  int MDloopi,MCloopi;
  int tau=0;

  //Vectors for doing the L Inverse
  double *vecdg = calloc(NUMl,sizeof(double));;
  double *veci0 = calloc(NUMl,sizeof(double));;
  double *veci1 = calloc(NUMl,sizeof(double));;
  //double veci1[NUMBEAD-2];
  //double veci0[NUMBEAD-2];

  // array to store rand nums in
  double *GaussRandArray = calloc(NUMu,sizeof(double));
  //double GaussRandArray[NUMu];

  // ratio for incrimenting the MH-MC test
  double ratio;

  // storage for brownian bridge
  double *bb = calloc(NUMu,sizeof(double));
  //double bb[NUMBEAD];

  // array plot of the average path
  //int xBinMax=300;
  //int yBinMax=200;
  int arrayPlot[300][200];
  for(i=0;i<300;i++){
    for(j=0;j<200;j++){
      arrayPlot[i][j]=0;
  } }

  //Print parameters for the run in stdout
  printf("=======================================================\n");
  printf("HMC method for 2D potentials \n");
  printf("=======================================================\n");
  printf("TEMPERATURE = %f \n",TEMP);
  printf("=======================================================\n");
  printf("Number of Metropolis Hastings steps: %i\n",NUMMC);
  printf("Number of MD steps: %i \n",NUMMD);
  printf("=======================================================\n");
  printf("Number of Dimensions: %i \n",NUMDIM);
  printf("Number of Beads: %i \n",NUMBEAD);
  printf("Path grid: du = %+.8e \n", DU);
  printf("Sampling Parameters: dt=%f \n",dt);
  printf("=======================================================\n");
  printf("MD step: h=%+.8e \n",h);
  printf("MD time (n*h): %+.8e \n",NUMMD*h);
  printf("=======================================================\n");

  //===============================================================
  // Reading the input configuration file into savepos
  //===============================================================
  //Input file to be read as first command line argument
  if(argv[1]==NULL) { 
    printf("No input file. Exiting!\n");
    exit(-1);
  }
  else {
    printf("Input Configuratrion File: %s\n",argv[1]);
  }
  int lineNum = 0;
  FILE *fptr = fopen(argv[1],"r");
  switch(NUMDIM){
    case 3:  //For 3 Dimensions
      while( EOF != fscanf(fptr,"%lf %lf %lf",
      &(savePos[lineNum].pos[0]),
      &(savePos[lineNum].pos[1]),
      &(savePos[lineNum].pos[2])) ) {
        lineNum++;
      }
      break;
    case 2:   //For 2 Dimensions 
      while( EOF != fscanf(fptr,"%lf %lf",
      &(savePos[lineNum].pos[0]),
      &(savePos[lineNum].pos[1])) ) {
        lineNum++;
      }
      break;
    case 1:  //For 1 Dimension
      while( EOF != fscanf(fptr,"%lf",
      &(savePos[lineNum].pos[0])) ) {
        lineNum++;
      }
      break;
    default:
      printf("ERROR: NUMDIM incorrectly defined. Exiting!\n");
      exit(-1);
  }


  //===============================================================
  // GNU Scientific Library Random Number Setup
  //===============================================================
  // Example shell command$ GSL_RNG_SEED=123 ./a.out
  printf("=======================================================\n");
  const gsl_rng_type * RanNumType;
  gsl_rng *RanNumPointer; 
  gsl_rng_env_setup();
  RanNumType = gsl_rng_default;
  RanNumPointer= gsl_rng_alloc (RanNumType);
  printf("Random Number Generator Type: %s \n", gsl_rng_name(RanNumPointer));
  printf("RNG Seed: %li \n", gsl_rng_default_seed);
  printf("=======================================================\n");

  double randUniform;

  renorm(savePos, DU, doubleNUMu);



  //===============================================================
  //     Start of HMC Loop (loops over Metropolis Hastings - MC steps)
  //===============================================================

  printf("START Hybrid Monte Carlo MAIN LOOP\n");
  printf("=======================================================\n");
  acc=0;
  rej=0;
  zeroAverages(tubeAve,&tau);

  for(MCloopi=1; MCloopi<=NUMMC; MCloopi++)
  {
    //zero ratio for MH MC test
    ratio=0.0l;
    //===============================================================
    //     Perform one SPDE step
    //===============================================================
  
    //store savePos.pos values to configCurrent.pos
    // savePos.pos stores the positions in case of rejection of the MHMC
    savePostoConfig(savePos, configCurrent);
 
    //(calculates potentials in config given the positions)
    #pragma omp parallel for
    for(i=0;i<NUMBEAD;i++) {calcPotentials(configCurrent,i);}
 
    //calculate LinvG for the config
    LInverse(configCurrent, doubleNUMl, du, vecdg, veci1, veci0);

    //do the preconditioned form of the SPDE
    preconditionSPDE(configCurrent, configNew, du, dt, doubleNUMu, bb, GaussRandArray, RanNumPointer);

    //(calculates potentials in config given the positions)
    #pragma omp parallel for
    for(i=0;i<NUMBEAD;i++) {calcPotentials(configNew,i);}

    //calculate LinvG for the config
    LInverse(configNew, doubleNUMl, du, vecdg, veci1, veci0);

    //acc ratio of newconfig
    ProbAccRatio(configCurrent, configNew, dt, du, &ratio);

    //calculate the averages for the tubes estimator
    accumulateAverages(tubeAve,configNew,&tau);
    accumulateArrayPlot(arrayPlot, configNew);

    printf("SPDE ratio: %+0.10f \n",ratio);
    //===============================================================
    //     Start of MD Loop
    //     This loop needs to be focused on for parallelization
    //===============================================================

    for(MDloopi=1;MDloopi<=NUMMD; MDloopi++)
    {
      //rotate the configuration        
      rotateConfig(&configOld, &configCurrent, &configNew);

      //do the MD position update
      MolecularDynamics(configOld, configCurrent, configNew, du, dt);
 
      //(calculates potentials in config given the positions)
      #pragma omp parallel for
      for(i=0;i<NUMBEAD;i++) {calcPotentials(configNew,i);}

      //calculate LinvG for the config
      LInverse(configNew, doubleNUMl, du, vecdg, veci1, veci0);

      //calculate the average distance moved in the step and print to std out
      if(MDloopi%WRITESTDOUT==0){
        printf("MDi: %.5d | MDi*h: %0.5f | MD ratio: %+0.5f | distance: ",MDloopi,MDloopi*sqrt(2*dt),ratio);
        printDistance(configNew, savePos);
      }

      //acc ratio of newconfig
      ProbAccRatio(configCurrent, configNew, dt, du, &ratio);
      //printf("%i  ProbAcc= %+.15e  QV Vel= %0.15e \n", MDloopi, ratio, qvvel);

      //calculate the averages for the tubes estimator
      accumulateAverages(tubeAve,configNew,&tau);
      accumulateArrayPlot(arrayPlot, configNew);
    }
    //===============================================================
    //Metropolis Hastings Monte-Carlo test
    //===============================================================
    randUniform = gsl_rng_uniform(RanNumPointer);
    if( exp(ratio/SIGMA2) > randUniform ){
      acc++;
      saveConfigtoPos(configNew, savePos);
    }
    else{
      rej++;
    }
    printf("rand=%+0.6f  Exp[ratio]=%+0.6f   dt= %+0.5e     acc= %i      rej= %i  \n",randUniform,exp(ratio/SIGMA2),dt,acc,rej);

    // Write the configuration to file
    if(MCloopi % WRITECONFIGS==0){
      normalizeAverages(tubeAve,&tau);
      writeConfig(configNew,tubeAve,MCloopi);
      zeroAverages(tubeAve,&tau);

      writeArrayPlot(arrayPlot, MCloopi);
      for(i=0;i<300;i++){
        for(j=0;j<200;j++){
          arrayPlot[i][j]=0;
      } }
    }

  }
  // GSL random number generator release memory
  gsl_rng_free (RanNumPointer);

  return(0);
}
Пример #28
0
int main(int argc, char **argv)
{
	REAL8TimeSeries *hplus = NULL;
	REAL8TimeSeries *hcross = NULL;
	struct params p;
	int status = 0;
	gsl_rng *rng = NULL;

	XLALSetErrorHandler(XLALAbortErrorHandler);

	p = parseargs(argc, argv);

	if ((int)(p.waveform) < 0 || (int)(p.waveform) >= NumWaveforms) {
		fprintf(stderr, "error: must specify valid waveform\n");
		exit(1);
	}

	if (p.waveform == BLTWNB) { /* set up gsl random number generator */
		gsl_rng_env_setup();
		rng = gsl_rng_alloc(gsl_rng_default);
	}

	if (IS_INVALID_DOUBLE(p.srate) || p.srate <= 0.0) {
		fprintf(stderr, "error: must specify valid sample rate\n");
		status = 1;
	}

	verbose_output("Input parameters:\n");
	verbose_output("%-31s `%s' - %s\n", "waveform:", waveform_names[p.waveform], waveform_long_names[p.waveform]);
	verbose_output("%-31s %g (Hz)\n", "sample rate:", p.srate);

	switch (p.waveform) {

	case BLTWNB:

		/* sanity check relevant parameters */
		if (IS_INVALID_DOUBLE(p.duration) || p.duration < 0.0) {
			fprintf(stderr, "error: must specify valid duration for waveform `%s'\n", waveform_names[p.waveform]);
			status = 1;
		}
		if (IS_INVALID_DOUBLE(p.frequency) || p.frequency < 0.0) {
			fprintf(stderr, "error: must specify valid frequency for waveform `%s'\n", waveform_names[p.waveform]);
			status = 1;
		}
		if (IS_INVALID_DOUBLE(p.bandwidth) || p.bandwidth < 0.0) {
			fprintf(stderr, "error: must specify valid bandwidth for waveform `%s'\n", waveform_names[p.waveform]);
			status = 1;
		}
		if (IS_INVALID_DOUBLE(p.eccentricity) || p.eccentricity < 0.0 || p.eccentricity > 1.0) {
			fprintf(stderr, "error: must specify valid eccentricity in domain [0,1] for waveform `%s'\n", waveform_names[p.waveform]);
			status = 1;
		}
		if (IS_INVALID_DOUBLE(p.fluence) || p.fluence < 0.0) {
			fprintf(stderr, "error: must specify valid fluence for waveform `%s'\n", waveform_names[p.waveform]);
			status = 1;
		}

		/* detect set but ignored parameters */
		if (!IS_INVALID_DOUBLE(p.q))
			fprintf(stderr, "warning: quality-factor parameter is set but ignored for waveform `%s'\n", waveform_names[p.waveform]);
		if (p.phase != DEFAULT_PHASE)
			fprintf(stderr, "warning: phase parameter is set but ignored for waveform `%s'\n", waveform_names[p.waveform]);
		if (!IS_INVALID_DOUBLE(p.amplitude))
			fprintf(stderr, "warning: amplitude parameter is set but ignored for waveform `%s'\n", waveform_names[p.waveform]);
		if (!IS_INVALID_DOUBLE(p.hrss))
			fprintf(stderr, "warning: hrss parameter is set but ignored for waveform `%s'\n", waveform_names[p.waveform]);

		if (!status) {
			double int_hdot_squared_dt;
			int_hdot_squared_dt = p.fluence * LAL_GMSUN_SI * 4 / LAL_C_SI / LAL_PC_SI / LAL_PC_SI;

			verbose_output("%-31s %g (s)\n", "duration:", p.duration);
			verbose_output("%-31s %g (Hz)\n", "frequency:", p.frequency);
			verbose_output("%-31s %g (Hz)\n", "bandwidth:", p.bandwidth);
			verbose_output("%-31s %g\n", "eccentricity:", p.eccentricity);
			verbose_output("%-31s %g (Msun c^2 pc^-2)\n", "fluence:", p.fluence);
			verbose_output("%-31s %g (s^-1)\n", "integral (dh/dt)^2 dt:", int_hdot_squared_dt);
			verbose_output("%-31s GSL_RNG_TYPE=%s\n", "GSL random number generator:", gsl_rng_name(rng));
			verbose_output("%-31s GSL_RNG_SEED=%lu\n", "GSL random number seed:", gsl_rng_default_seed);
			status = XLALGenerateBandAndTimeLimitedWhiteNoiseBurst(&hplus, &hcross, p.duration, p.frequency, p.bandwidth, p.eccentricity, int_hdot_squared_dt, 1.0/p.srate, rng);
		}
		break;

	case StringCusp:

		/* sanity check relevant parameters */
		if (IS_INVALID_DOUBLE(p.amplitude) || p.amplitude < 0.0) {
			fprintf(stderr, "error: must specify valid amplitude for waveform `%s'\n", waveform_names[p.waveform]);
			status = 1;
		}
		if (IS_INVALID_DOUBLE(p.frequency) || p.frequency < 0.0) {
			fprintf(stderr, "error: must specify valid frequency for waveform `%s'\n", waveform_names[p.waveform]);
			status = 1;
		}

		/* detect set but ignored parameters */
		if (!IS_INVALID_DOUBLE(p.duration))
			fprintf(stderr, "warning: duration parameter is set but ignored for waveform `%s'\n", waveform_names[p.waveform]);
		if (!IS_INVALID_DOUBLE(p.bandwidth))
			fprintf(stderr, "warning: bandwidth parameter is set but ignored for waveform `%s'\n", waveform_names[p.waveform]);
		if (!IS_INVALID_DOUBLE(p.q))
			fprintf(stderr, "warning: quality-factor parameter is set but ignored for waveform `%s'\n", waveform_names[p.waveform]);
		if (p.eccentricity != DEFAULT_ECCENTRICITY)
			fprintf(stderr, "warning: eccentricity parameter is set but ignored for waveform `%s'\n", waveform_names[p.waveform]);
		if (p.phase != DEFAULT_PHASE)
			fprintf(stderr, "warning: phase parameter is set but ignored for waveform `%s'\n", waveform_names[p.waveform]);
		if (!IS_INVALID_DOUBLE(p.hrss))
			fprintf(stderr, "warning: hrss parameter is set but ignored for waveform `%s'\n", waveform_names[p.waveform]);
		if (!IS_INVALID_DOUBLE(p.fluence))
			fprintf(stderr, "warning: fluence parameter is set but ignored for waveform `%s'\n", waveform_names[p.waveform]);

		if (!status) {
			verbose_output("%-31s %g (s^-1/3)\n", "amplitude:", p.amplitude);
			verbose_output("%-31s %g (Hz)\n", "frequency:", p.frequency);
			status = XLALGenerateStringCusp(&hplus, &hcross, p.amplitude, p.frequency, 1.0/p.srate);
		}
		break;

	case SineGaussian:

		/* sanity check relevant parameters */
		if (IS_INVALID_DOUBLE(p.q) || p.q < 0.0) {
			fprintf(stderr, "error: must specify valid quality factor for waveform `%s'\n", waveform_names[p.waveform]);
			status = 1;
		}
		if (IS_INVALID_DOUBLE(p.frequency) || p.frequency < 0.0) {
			fprintf(stderr, "error: must specify valid frequency for waveform `%s'\n", waveform_names[p.waveform]);
			status = 1;
		}
		if (IS_INVALID_DOUBLE(p.hrss) || p.hrss < 0.0) {
			fprintf(stderr, "error: must specify valid hrss for waveform `%s\n", waveform_names[p.waveform]);
			status = 1;
		}
		if (IS_INVALID_DOUBLE(p.eccentricity) || p.eccentricity < 0.0 || p.eccentricity > 1.0) {
			fprintf(stderr, "error: must specify valid eccentricity in domain [0,1] for waveform `%s'\n", waveform_names[p.waveform]);
			status = 1;
		}
		if (IS_INVALID_DOUBLE(p.phase)) {
			fprintf(stderr, "error: must specify valid phase for waveform `%s'\n", waveform_names[p.waveform]);
			status = 1;
		}

		/* detect set but ignored parameters */
		if (!IS_INVALID_DOUBLE(p.duration))
			fprintf(stderr, "warning: duration parameter is set but ignored for waveform `%s'\n", waveform_names[p.waveform]);
		if (!IS_INVALID_DOUBLE(p.bandwidth))
			fprintf(stderr, "warning: bandwidth parameter is set but ignored for waveform `%s'\n", waveform_names[p.waveform]);
		if (!IS_INVALID_DOUBLE(p.amplitude))
			fprintf(stderr, "warning: amplitude parameter is set but ignored for waveform `%s'\n", waveform_names[p.waveform]);
		if (!IS_INVALID_DOUBLE(p.fluence))
			fprintf(stderr, "warning: fluence parameter is set but ignored for waveform `%s'\n", waveform_names[p.waveform]);

		if (!status) {
			verbose_output("%-31s %g\n", "quality-factor:", p.q);
			verbose_output("%-31s %g (Hz)\n", "frequency:", p.frequency);
			verbose_output("%-31s %g (Hz^-1/2)\n", "root-sum-squared strain:", p.hrss);
			verbose_output("%-31s %g\n", "eccentricity:", p.eccentricity);
			verbose_output("%-31s %g (degrees)\n", "phase:", p.phase / LAL_PI_180);
			status = XLALSimBurstSineGaussian(&hplus, &hcross, p.q, p.frequency, p.hrss, p.eccentricity, p.phase, 1.0/p.srate);
		}
		break;

	case Gaussian:

		/* sanity check relevant parameters */
		if (IS_INVALID_DOUBLE(p.duration) || p.duration < 0.0) {
			fprintf(stderr, "error: must specify valid duration for waveform `%s'\n", waveform_names[p.waveform]);
			status = 1;
		}
		if (IS_INVALID_DOUBLE(p.hrss) || p.hrss < 0.0) {
			fprintf(stderr, "error: must specify valid hrss for waveform `%s'\n", waveform_names[p.waveform]);
			status = 1;
		}
		/* detect set but ignored parameters */
		if (!IS_INVALID_DOUBLE(p.frequency))
			fprintf(stderr, "warning: frequency parameter is set but ignored for waveform `%s'\n", waveform_names[p.waveform]);
		if (!IS_INVALID_DOUBLE(p.bandwidth))
			fprintf(stderr, "warning: bandwidth parameter is set but ignored for waveform `%s'\n", waveform_names[p.waveform]);
		if (!IS_INVALID_DOUBLE(p.q))
			fprintf(stderr, "warning: quality-factor parameter is set but ignored for waveform `%s'\n", waveform_names[p.waveform]);
		if (p.eccentricity != DEFAULT_ECCENTRICITY)
			fprintf(stderr, "warning: eccentricity parameter is set but ignored for waveform `%s'\n", waveform_names[p.waveform]);
		if (p.phase != DEFAULT_PHASE)
			fprintf(stderr, "warning: phase parameter is set but ignored for waveform `%s'\n", waveform_names[p.waveform]);
		if (!IS_INVALID_DOUBLE(p.amplitude))
			fprintf(stderr, "warning: amplitude parameter is set but ignored for waveform `%s'\n", waveform_names[p.waveform]);
		if (!IS_INVALID_DOUBLE(p.fluence))
			fprintf(stderr, "warning: fluence parameter is set but ignored for waveform `%s'\n", waveform_names[p.waveform]);
		if (!status) {
			verbose_output("%-31s %g (s)\n", "duration:", p.duration);
			verbose_output("%-31s %g (Hz^-1/2)\n", "root-sum-squared strain:", p.hrss);
			status = XLALSimBurstGaussian(&hplus, &hcross, p.duration, p.hrss, 1.0/p.srate);
		}

		break;

	case Impulse:

		/* sanity check relevant parameters */
		if (IS_INVALID_DOUBLE(p.amplitude) || p.amplitude < 0.0) {
			fprintf(stderr, "error: must specify valid amplitude for waveform `%s'\n", waveform_names[p.waveform]);
			status = 1;
		}

		/* detect set but ignored parameters */
		if (!IS_INVALID_DOUBLE(p.duration))
			fprintf(stderr, "warning: duration parameter is set but ignored for waveform `%s'\n", waveform_names[p.waveform]);
		if (!IS_INVALID_DOUBLE(p.frequency))
			fprintf(stderr, "warning: frequency parameter is set but ignored for waveform `%s'\n", waveform_names[p.waveform]);
		if (!IS_INVALID_DOUBLE(p.bandwidth))
			fprintf(stderr, "warning: bandwidth parameter is set but ignored for waveform `%s'\n", waveform_names[p.waveform]);
		if (!IS_INVALID_DOUBLE(p.q))
			fprintf(stderr, "warning: quality-factor parameter is set but ignored for waveform `%s'\n", waveform_names[p.waveform]);
		if (p.eccentricity != DEFAULT_ECCENTRICITY)
			fprintf(stderr, "warning: eccentricity parameter is set but ignored for waveform `%s'\n", waveform_names[p.waveform]);
		if (p.phase != DEFAULT_PHASE)
			fprintf(stderr, "warning: phase parameter is set but ignored for waveform `%s'\n", waveform_names[p.waveform]);
		if (!IS_INVALID_DOUBLE(p.hrss))
			fprintf(stderr, "warning: hrss parameter is set but ignored for waveform `%s'\n", waveform_names[p.waveform]);
		if (!IS_INVALID_DOUBLE(p.fluence))
			fprintf(stderr, "warning: fluence parameter is set but ignored for waveform `%s'\n", waveform_names[p.waveform]);

		if (!status) {
			verbose_output("%-31s %g (dimensionless)\n", "amplitude:", p.amplitude);
			status = XLALGenerateImpulseBurst(&hplus, &hcross, p.amplitude, 1.0/p.srate);
		}
		break;

	default:
		fprintf(stderr, "error: unrecognized waveform\n");
		exit(1);
	};

	if (status)
		exit(1);

	if (verbose) {
		char peak_time[32]; // GPS time string - 31 characters is enough
		LIGOTimeGPS tpeak;
		COMPLEX16 hpeak;
		double hrss;
		double fluence;
		unsigned ipeak;
		hpeak = XLALMeasureHPeak(hplus, hcross, &ipeak);
		tpeak = hplus->epoch;
		XLALGPSAdd(&tpeak, ipeak * hplus->deltaT);
		XLALGPSToStr(peak_time, &tpeak);
		hrss = XLALMeasureHrss(hplus, hcross);
		fluence = XLALMeasureEoverRsquared(hplus, hcross);
		verbose_output("Measured parameters:\n");
		verbose_output("%-31s %s (s)\n", "peak time:", peak_time);
		verbose_output("%-31s (h+, hx) = (%g, %g)\n", "peak strain amplitude:", creal(hpeak), cimag(hpeak));
		verbose_output("%-31s abs(h+, hx) = %g\n", "peak strain amplitude:", cabs(hpeak));
		verbose_output("%-31s arg(h+, hx) = %g (rad)\n", "peak strain amplitude:", carg(hpeak));
		verbose_output("%-31s %g (Hz^-1/2)\n", "root-sum-squared strain:", hrss);
		verbose_output("%-31s %g (J m^-2)\n", "isotropic energy fluence:", fluence);
		verbose_output("%-31s %g (Msun c^2 pc^-2)\n", "isotropic energy fluence:", fluence * LAL_PC_SI * LAL_PC_SI / LAL_MSUN_SI / LAL_C_SI / LAL_C_SI);
	}

	output(hplus, hcross);

	XLALDestroyREAL8TimeSeries(hcross);
	XLALDestroyREAL8TimeSeries(hplus);
	LALCheckMemoryLeaks();
	return 0;
}
Пример #29
0
Файл: rng.c Проект: Fudge/rb-gsl
static VALUE rb_gsl_rng_name(VALUE obj)
{
  gsl_rng *r = NULL;
  Data_Get_Struct(obj, gsl_rng, r);
  return rb_str_new2(gsl_rng_name(r));
}
Пример #30
0
int main(int argc, char ** argv)
{
    fftw_complex *z;
    fftw_plan plan;
    gsl_rng *r;
    const  gsl_rng_type *T;
    struct parms parms;
    double *phi, avg, ran, std;
    double *philocal;
    int Nx, Ny, Nz, size, rank, xnn;
    int i, j, n1, n2, irank, i0, j0;
    char filename[64];
    FILE *file;
    void   initrng(void);
    double uniform(void);
    MPI_Status status;

    Nx = atoi(argv[1]);
    Ny = atoi(argv[2]);
    Nz = atoi(argv[3]);
    avg = atof(argv[4]);
    std = atof(argv[5]);
    parms.Nx = Nx;  parms.Ny = Ny;  parms.Nz = Nz;
    //  MPI
    MPI_Init(&argc, &argv);
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);
    MPI_Comm_size (MPI_COMM_WORLD, &size);
    if (rank == 0){
        //  RNG setup
        gsl_rng_env_setup();
        T = gsl_rng_default;
        r = gsl_rng_alloc (T);
        printf ("r is a '%s' generator\n", gsl_rng_name (r));
        for (i=0; i < 1000000; i++)
            ran = avg + gsl_ran_gaussian(r,std); 
        xnn = Nx*Ny*Nz;
        phi = (double *) calloc(Nx*Ny*Nz, sizeof(double));
        for (i = 0; i < Nx*Ny*Nz; i++){
            ran = avg + gsl_ran_gaussian(r,std);
            phi[i] = (ran);
        }
    }


    parms.Nx = Nx;  parms.Ny = Ny;    parms.Nz = Nz;
    parms.rank = rank-1; parms.size = size-1;        //Slave COMM
    parms = mapping(parms);
    philocal = (double *) calloc(parms.nx*parms.ny, sizeof(double));
    
    if (rank == 0){
        for (irank = 0; irank < parms.size; irank++){
            parms.rank = irank;
            parms = mapping(parms);
            for (i = 0; i < parms.nx; i++)
            for (j = 0; j < parms.ny; j++){
                i0 = parms.x0 + i;        // Global coords
                j0 = parms.y0 + j;
                n1 = i*parms.ny + j;        //Local index
                n2 = i0*parms.Ny + j0;        //Global index
                philocal[n1] = phi[n2];
            }
            n1 = parms.nx*parms.ny;
            MPI_Send(philocal, n1, MPI_DOUBLE, irank+1, 0, MPI_COMM_WORLD);
        }
    }
    else{
        n1 = parms.nx*parms.ny;        //Fill local height
        MPI_Recv(philocal, n1, MPI_DOUBLE, 0, 0, MPI_COMM_WORLD, &status);

        sprintf(filename, "%s.%02d", "phi.dat", parms.rank);
        file = fopen(filename, "w");
        fprintf(file, "%5d %5d %5d %5d %5d    0    0.0\n", parms.Nx, parms.Ny, parms.nx, parms.ny, parms.Nz);
        for (i = 0; i < parms.nx; i++)
        for (j = 0; j < parms.ny; j++){
            fprintf(file, " % .3e", philocal[i*parms.ny+j]);
            if ((i*parms.ny+j+1)%10 == 0) fprintf(file, "\n");
        }
    fclose(file);
    }
    MPI_Finalize();
    return 0;
}