Exemplo n.º 1
0
/// Initialize \ref sim_poisson 
void sim_poisson_init(void)
{	// just pick on generator and do not worry about seed
	rng_  = gsl_rng_alloc(gsl_rng_taus);
	assert( rng_ != NULL );	
}
Exemplo n.º 2
0
int main(int argc, char ** argv){
  gsl_rng * r = gsl_rng_alloc (gsl_rng_taus2);
  //  gsl_rng_set(r,time(NULL));
  FILE * log = fopen("recover_shanon.log","w");

#ifdef MPI
  MPI_Init(&argc, &argv);
#endif

  int n_samples = 500;
  if(argc != 2 && argc != 3 && argc != 4 ){
    printf("recover_shanon <input_image> [total n photons scattered] [n samples]\n");
    printf("The defaults are n photons = n pixels and n samples = 500\n");
    exit(0);
  }
  if(argc >= 4){
    n_samples = atoi(argv[3]);
  }
  Image * a = sp_image_read(argv[1],0);
  double image_photons = 0;
  for(int i = 0;i<sp_image_size(a);i++){
    image_photons += sp_real(a->image->data[i]);
  }
  int n_photons = sp_image_size(a);
  if(argc >= 3){
    n_photons = atoi(argv[2]);
  }
  sp_image_scale(a,n_photons/image_photons);

  image_photons = 0;
  for(int i = 0;i<sp_image_size(a);i++){
    image_photons += sp_real(a->image->data[i]);
  }
  printf("Total photons %f\n",image_photons);
  printf("Average photon count %f\n",image_photons/sp_image_size(a));

  printf("Creating rotated samples...");
  fflush(stdout);
  Image * avg_samples = sp_image_alloc(sp_image_x(a),sp_image_y(a),sp_image_z(a));
  sp_matrix ** random_orient_samples = get_rotated_samples(a,n_samples,r,avg_samples);

  //  Image ** orient_samples = get_orient_samples(a,n_samples,r);
  printf("done\n");

  image_photons = 0;
  for(int i = 0;i<sp_image_size(a);i++){
    image_photons += random_orient_samples[0]->data[i];
  }
  printf("Total photons in sample 1 - %f\n",image_photons);


  //  Image * avg_samples = get_image_avg(orient_samples,n_samples);
  /*  printf("Rotating samples...");
  fflush(stdout);
  sp_matrix ** random_orient_samples = get_random_orient_samples(orient_samples,n_samples,r);
  printf("done\n");*/

  //  sp_image_write(random_orient_samples[1],"sample.png",COLOR_GRAYSCALE);
  /*  for(int i = 0;i<n_samples;i++){
    sp_image_free(orient_samples[i]);
  }
  free(orient_samples);*/

  Image * avg_random_samples = sp_image_alloc(sp_image_x(a),sp_image_y(a),sp_image_z(a));
  for(int i = 0;i<n_samples;i++){
    for(int k = 0;k<sp_image_size(avg_random_samples);k++){
      sp_real(avg_random_samples->image->data[k]) += random_orient_samples[i]->data[k];
    }
  }
  
  /* Create rotation list */
  /*  printf("Creating rotation list...");
  fflush(stdout);
  sp_matrix *** rotated_random_orient_samples = get_rotation_list(random_orient_samples,  n_samples);
  printf("done\n");*/


  /* Initialize with uniform distribution in [0,1) */
  Image * restore = sp_image_alloc(sp_image_x(a),sp_image_y(a),sp_image_z(a));
  Image * after = sp_image_alloc(sp_image_x(a),sp_image_y(a),sp_image_z(a));
  for(int i = 0;i<sp_image_size(a);i++){
    restore->image->data[i] = sp_cinit(gsl_rng_uniform(r),0);
  }
  image_normalize(restore);

  sp_image_write(a,"orig.png",COLOR_GRAYSCALE);
  sp_image_write(avg_samples,"avg_sample.png",COLOR_GRAYSCALE);
  sp_image_write(avg_random_samples,"avg_random_sample.png",COLOR_GRAYSCALE);
  for(int iter = 0;;iter++){
    tomas_iteration(restore,after,random_orient_samples,n_samples);
    Image * tmp = restore;
    restore = after;
    after = tmp;

    for(int i = 0;i<sp_image_size(a);i++){
      sp_real(after->image->data[i]) = 0;
    }
    
    output_result(a,restore,log,iter);
  }
  return 0;
}
Exemplo n.º 3
0
int main(int argc, char **argv)
{
    gsl_rng_env_setup();

    T = gsl_rng_default;
    r = gsl_rng_alloc (T);
    gsl_rng_set(r, time(NULL));

    Graph *g = new Graph();
	g->addVertex(Vertex(1, "v1", 0, 0, 0, 1.0, 1.0, 1.0));
	g->addVertex(Vertex(2, "v2", 0, 0, 0, 1.0, 0.2, 0.2));
	g->addVertex(Vertex(3, "v3", 0, 0, 0, 0.2, 1.0, 0.2));
	g->addVertex(Vertex(4, "v4", 0, 0, 0, 0.2, 0.2, 1.0));

	g->addEdge(1, 2);
	g->addEdge(1, 3);
	g->addEdge(3, 4);

	ptr population(new std::vector<Graph>(4, *g));
	/*
	std::cout << "Population" << std::endl;
	printgraph(population);

	ptr reproduced = reproduce(population);
	std::cout << "Reproduced" << std::endl;
	printgraph(reproduced);

	ptr offsprings = genetic(reproduced);
	std::cout << "Offsprings" << std::endl;
	printgraph(offsprings);

	population = succession(population, offsprings);
	std::cout << "After one iteration" << std::endl;
	printgraph(population);
	*/

	int iterationcount = 0;
	double bestv = best(population);
	double bestvold = bestv * 2;

	std::cout << "best " << bestv << "; bestvold " << bestvold << std::endl;
	while (fabs(bestvold - bestv)/bestvold > 0.00000001)
	{
		++iterationcount;
		ptr offsprings = genetic(reproduce(population));
		population = succession(population, offsprings);
		bestvold = bestv;
		bestv = best(population);
	}

	std::cout << "Possible result found after " << iterationcount << "iterations: " << std::endl;
	printgraph(population);

	const Graph *bestgraph = bestg(population);
	for (Graph::vertices_const_iterator i = bestgraph->vertices.begin(); i != bestgraph->vertices.end(); ++i)
	{
		const Vertex &v = i->second;
		std::cout << "\"" << v.name << "\"";
		std::cout << "\t@" << v.x << " " << v.y << " " << v.z;
		std::cout << "\tcolor" << v.r << " " << v.g << " " << v.b;
		std::cout << "\tfrozen light size 1.0" << std::endl;
	}

    gsl_rng_free (r);
	return 0;
}
Exemplo n.º 4
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);
}
Exemplo n.º 5
0
int main(void)
{
  double x_min = 1.36312999455315182 ;
  double x ;

  gsl_rng * r = gsl_rng_alloc (gsl_rng_env_setup()) ;

  gsl_ieee_env_setup ();

  /* The function tested here has multiple mimima. 
     The global minimum is at    x = 1.36312999, (f = -0.87287)
     There is a local minimum at x = 0.60146196, (f = -0.84893) */

  x = -10.0 ;
  gsl_siman_solve(r, &x, E1, S1, M1, NULL, NULL, NULL, NULL,
		  sizeof(double), params);
  gsl_test_rel(x, x_min, 1e-3, "f(x)= exp(-(x-1)^2) sin(8x), x0=-10") ;

  x = +10.0 ;
  gsl_siman_solve(r, &x, E1, S1, M1, NULL, NULL, NULL, NULL,
		  sizeof(double), params);
  gsl_test_rel(x, x_min, 1e-3, "f(x)= exp(-(x-1)^2) sin(8x), x0=10") ;

  /* Start at the false minimum */

  x = +0.6 ; 
  gsl_siman_solve(r, &x, E1, S1, M1, NULL, NULL, NULL, NULL,
		  sizeof(double), params);
  gsl_test_rel(x, x_min, 1e-3, "f(x)= exp(-(x-1)^2) sin(8x), x0=0.6") ;

  x = +0.5 ; 
  gsl_siman_solve(r, &x, E1, S1, M1, NULL, NULL, NULL, NULL,
		  sizeof(double), params);
  gsl_test_rel(x, x_min, 1e-3, "f(x)= exp(-(x-1)^2) sin(8x), x0=0.5") ;

  x = +0.4 ; 
  gsl_siman_solve(r, &x, E1, S1, M1, NULL, NULL, NULL, NULL,
		  sizeof(double), params);
  gsl_test_rel(x, x_min, 1e-3, "f(x)= exp(-(x-1)^2) sin(8x), x0=0.4") ;

  exit (gsl_test_summary ());

#ifdef JUNK 
  x0.D1 = 12.0;
  printf("#one dimensional problem, x0 = %f\n", x0.D1);
  gsl_siman_Usolve(r, &x0, test_E_1D, test_step_1D, distance_1D,
		   print_pos_1D, params);


  x0.D2[0] = 12.0;
  x0.D2[1] = 5.5;
  printf("#two dimensional problem, (x0,y0) = (%f,%f)\n",
	 x0.D2[0], x0.D2[1]);
  gsl_siman_Usolve(r, &x0, test_E_2D, test_step_2D, distance_2D,
		   print_pos_2D, params); 

  x0.D3[0] = 12.2;
  x0.D3[1] = 5.5;
  x0.D3[2] = -15.5;
  printf("#three dimensional problem, (x0,y0,z0) = (%f,%f,%f)\n",
	 x0.D3[0], x0.D3[1], x0.D3[2]);
  gsl_siman_Usolve(r, &x0, test_E_3D, test_step_3D, distance_3D, 
		   print_pos_3D, params); 

  x0.D2[0] = 12.2;
  x0.D2[1] = 5.5;

  gsl_siman_solve(r, &x0, test_E_2D, test_step_2D, distance_2D, print_pos_2D, params);
  
  x0.D3[0] = 12.2;
  x0.D3[1] = 5.5;
  x0.D3[2] = -15.5;

  gsl_siman_solve(r, &x0, test_E_3D, test_step_3D, distance_3D, print_pos_3D, params);

  return 0;
#endif
}
Exemplo n.º 6
0
double
thermo_sa(double temp_init, double temp_end, double temp_sig, double initstate,
          double bm_sigma, double k, FILE * log)
{
   double  energy, energy_new, energy_delta, energy_variation;
   int    *path;
   double  temp, temp_old;
   double  prob;
   double  rot_old, best_rot;
   double  entropy_variation;
   double  energy_best;
   gsl_rng *acpt_rng;
   unsigned long time = 0;
   double  BM;

   /*
    * Initialize the random number generators. 
    */
   _bm_rng = gsl_rng_alloc(gsl_rng_taus);
   acpt_rng = gsl_rng_alloc(gsl_rng_taus);

   temp = temp_init;
   rotation = initstate;

   /*
    * Compute the first path. 
    */
   path = renormalize();
   energy = route_length(path, tsp->dimension);
	free(path);
   energy_best = energy;

   entropy_variation = 0;
   energy_variation = 0;

   /*
    * Print the log headers. 
    */
   if (log != NULL)
      (void) fprintf(log, "time T E_n E_d E_v E_b S_v rb r rv bm\n");

   do {
      temp_old = temp;
      rot_old = rotation;
      if (log != NULL)
         (void) fprintf(log, "%lu ", time);

      BM = neighbour_rot(temp, temp_end, temp_init, bm_sigma);

      if(fpclassify(rotation) == FP_NAN)
          errx(EX_DATAERR, "Rotation can not be NaN");
      path = renormalize();
      energy_new = route_length(path, tsp->dimension);
		free(path);
      energy_delta = energy_new - energy;

      prob = exp(-energy_delta / temp);

      if (log != NULL)
			(void)fprintf(log, "%lf %lf %lf %lf %lf %lf %lf %lf %lf %lf\n",
							temp, energy_new, energy_delta, energy_variation,
							energy_best, entropy_variation, best_rot, rotation,
                     (rotation - rot_old), BM);

      if (gsl_rng_uniform(acpt_rng) < prob) {
         if (energy_best > energy) {
            energy_best = energy;
            best_rot = rot_old;
         }
         energy = energy_new;
         energy_variation += energy_delta;
      } else
         rotation = rot_old;

      if (energy_delta > 0)
         entropy_variation -= energy_delta / temp;

      if ((energy_variation >= 0) || fabs(entropy_variation) < 0.000001)
         temp = temp_init;
      else {
         temp = k * (energy_variation / entropy_variation);
         //rotation = best_rot;
      }
      time++;
   } while ((temp > temp_end) || (fabs(temp - temp_old) > temp_sig));

   gsl_rng_free(acpt_rng);
   gsl_rng_free(_bm_rng);

   return energy_best;
}
void test(int max, int size) {
  
  std::vector<double> a;
  std::vector<int> b;
  double d[size];

  for(int i = 0; i<size; i++) {
    a.push_back(1.0/size);
    b.push_back(1);
    d[i] = rand();;
  }
  
  //s += std::to_string(max);
  //s += "\t";
  s += std::to_string(size);
  s += "\t";
  
  int sum = 0;
  
  std::cout << std::endl << "Max: " << max << ";\t Size: " << size << std::endl << std::endl;
    
  boost::mt19937 gen;
  
  
  const gsl_rng_type * T;
  gsl_rng * r;

  gsl_rng_env_setup();

  T = gsl_rng_default;
  r = gsl_rng_alloc(T);
  
  RandomLib::Random r2; 
  
  sum = 0;
  clock_t startTime = clock(); 
  
  
  
  //RandomLib
  
  sum = 0;
  startTime = clock();
  RandomLib::RandomSelect<int> sel(b.begin(), b.end());
  s += std::to_string(clock() - startTime);
  s += "\t";
  std::cout << "\t RandomLib: " << std::endl << "\t\t Initiate: " << clock() - startTime << std::endl;
  startTime = clock();  
  for(int i = 0; i < max; i++) {
    sum += sel(r2);
  }
  s += std::to_string(clock() - startTime);
  s += "\t";
  std::cout << "\t\t Generate: " << clock() - startTime << std::endl << "\t\t Sum: " << sum << std::endl;
  
  
  //gnu science
  
  sum = 0;
  startTime = clock();
  gsl_ran_discrete_t * table = gsl_ran_discrete_preproc(size, d);
  s += std::to_string(clock() - startTime);
  s += "\t";
  std::cout << "\t Gnu Science: " << std::endl << "\t\t Initiate: " << clock() - startTime << std::endl;
  startTime = clock();  
  for(int i = 0; i < max; i++) {
    sum += gsl_ran_discrete(r, table);
  }
  s += std::to_string(clock() - startTime);
  s += "\t";
  std::cout << "\t\t Generate: " << clock() - startTime << std::endl << "\t\t Sum: " << sum << std::endl;
  
  gsl_rng_free(r);

  
  //boost
  
  sum = 0;
  startTime = clock();
  boost::random::discrete_distribution<> dist(a.begin(), a.end());
  //boost::random::discrete_distribution<> dist(b, b+size);
  s += std::to_string(clock() - startTime);
  s += "\t";
  std::cout << "\t Boost: " << std::endl << "\t\t Initiate: " << clock() - startTime << std::endl;
  startTime = clock();  
  for(int i = 0; i < max; i++) {
    sum += dist(gen);
  }
  s += std::to_string(clock() - startTime);
  s += "\t";
  std::cout << "\t\t Generate: " << clock() - startTime << std::endl << "\t\t Sum: " << sum << std::endl;
  
  
  //std::dsicrete_distribution
  
  sum = 0;
  startTime = clock();
  std::discrete_distribution<int> std_dist(b.begin(), b.end());
  s += std::to_string(clock() - startTime);
  s += "\t";
  std::cout << "\t std::discrete_distribution: " << std::endl << "\t\t Initiate: " << clock() - startTime << std::endl;
  startTime = clock();  
  for(int i = 0; i < max; i++) {
    sum += std_dist(gen);
  }
  s += std::to_string(clock() - startTime);
  s += "\t";
  std::cout << "\t\t Generate: " << clock() - startTime << std::endl << "\t\t Sum: " << sum << std::endl;
  
  /*
  //table-lookup
  
  sum = 0;
  startTime = clock();
  random_distribution q(a);
  s += std::to_string(clock() - startTime);
  s += "\t";
  std::cout << "\t Method 1: " << std::endl << "\t\t Initiate: " << clock() - startTime << std::endl;
  startTime = clock();  
  for(int i = 0; i < max; i++) {
    sum += q.dist();
  }
  s += std::to_string(clock() - startTime);
  s += "\t";
  std::cout << "\t\t Generate: " << clock() - startTime << std::endl << "\t\t Sum: " << sum << std::endl;
  //std::cout << "\t\t i0: " << q.i0 << "\t i1: " << q.i1 <<  "\t i2: " << q.i2 <<  "\t i3: " << q.i3 << std::endl;

  
  //table-lookup + histogram
  
  sum = 0;
  startTime = clock();
  random_distribution q2(a,2);
  s += std::to_string(clock() - startTime);
  s += "\t";
  std::cout << "\t Method 2: " << std::endl << "\t\t Initiate: " << clock() - startTime << std::endl;
  startTime = clock();  
  for(int i = 0; i < max; i++) {
    sum += q2.dist2();
  }
  s += std::to_string(clock() - startTime);
  s += "\t";
  std::cout << "\t\t Generate: " << clock() - startTime << std::endl << "\t\t Sum: " << sum << std::endl;
    
  
  //binary search
  
  sum = 0;
  startTime = clock();
  random_distribution q3(a,3);
  s += std::to_string(clock() - startTime);
  s += "\t";
  std::cout << "\t Method 3: " << std::endl << "\t\t Initiate: " << clock() - startTime << std::endl;
  startTime = clock();  
  for(int i = 0; i < max; i++) {
    sum += q3.dist3();
  }
  s += std::to_string(clock() - startTime);
  s += "\t";
  std::cout << "\t\t Generate: " << clock() - startTime << std::endl << "\t\t Sum: " << sum << std::endl;  
  */
  s += "\n";
}
Exemplo n.º 8
0
int
main (void)
{
  const gsl_multifit_fdfsolver_type *T;
  gsl_multifit_fdfsolver *s;
  int status;
  unsigned int i, iter = 0;
  const size_t n = N;
  const size_t p = 3;

  gsl_matrix *covar = gsl_matrix_alloc (p, p);
  double y[N], sigma[N];
  struct data d = { n, y, sigma};
  gsl_multifit_function_fdf f;
  double x_init[3] = { 1.0, 0.0, 0.0 };
  gsl_vector_view x = gsl_vector_view_array (x_init, p);
  const gsl_rng_type * type;
  gsl_rng * r;

  gsl_rng_env_setup();

  type = gsl_rng_default;
  r = gsl_rng_alloc (type);

  f.f = &expb_f;
  f.df = &expb_df;
  f.fdf = &expb_fdf;
  f.n = n;
  f.p = p;
  f.params = &d;

  /* This is the data to be fitted */

  for (i = 0; i < n; i++)
    {
      double t = i;
      y[i] = 1.0 + 5 * exp (-0.1 * t) 
                 + gsl_ran_gaussian (r, 0.1);
      sigma[i] = 0.1;
      printf ("data: %u %g %g\n", i, y[i], sigma[i]);
    };

  T = gsl_multifit_fdfsolver_lmsder;
  s = gsl_multifit_fdfsolver_alloc (T, n, p);
  gsl_multifit_fdfsolver_set (s, &f, &x.vector);

  print_state (iter, s);

  do
    {
      iter++;
      status = gsl_multifit_fdfsolver_iterate (s);

      printf ("status = %s\n", gsl_strerror (status));

      print_state (iter, s);

      if (status)
        break;

      status = gsl_multifit_test_delta (s->dx, s->x,
                                        1e-4, 1e-4);
    }
  while (status == GSL_CONTINUE && iter < 500);

  gsl_multifit_covar (s->J, 0.0, covar);

#define FIT(i) gsl_vector_get(s->x, i)
#define ERR(i) sqrt(gsl_matrix_get(covar,i,i))

  { 
    double chi = gsl_blas_dnrm2(s->f);
    double dof = n - p;
    double c = GSL_MAX_DBL(1, chi / sqrt(dof)); 

    printf("chisq/dof = %g\n",  pow(chi, 2.0) / dof);

    printf ("A      = %.5f +/- %.5f\n", FIT(0), c*ERR(0));
    printf ("lambda = %.5f +/- %.5f\n", FIT(1), c*ERR(1));
    printf ("b      = %.5f +/- %.5f\n", FIT(2), c*ERR(2));
  }

  printf ("status = %s\n", gsl_strerror (status));

  gsl_multifit_fdfsolver_free (s);
  gsl_matrix_free (covar);
  gsl_rng_free (r);
  return 0;
}
Exemplo n.º 9
0
/**
 * @brief Main principal
 * @param argc El número de argumentos del programa
 * @param argv Cadenas de argumentos del programa
 * @return Nada si es correcto o algún número negativo si es incorrecto
 */
int main( int argc, char** argv ) {
	
	if( argc < 4 )
		return -1;

	// Declaración de variables
	gsl_rng *rng;
	IplImage *frame, *hsv_frame;
	float **ref_histos, histo_aux[1][HTAM];
	CvCapture *video;
	particle **particles, **aux, **nuevas_particulas;
	CvScalar color_rojo = CV_RGB(255,0,0), color_azul = CV_RGB(0,0,255);
	float factor = 1.0 / 255.0, sum = 0.0f;
	CvRect *regions;
	int num_objects = 0;
	int MAX_OBJECTS = atoi(argv[3]), PARTICLES = atoi(argv[2]);
	FILE *datos;
	char name[45], num[3], *p1, *p2;
	clock_t t_ini, t_fin;
	double ms;
	
	video = cvCaptureFromFile( argv[1] );
	if( !video ) {
		printf("No se pudo abrir el fichero de video %s\n", argv[1]);
		exit(-1);
	}

	int nFrames = (int) cvGetCaptureProperty( video , CV_CAP_PROP_FRAME_COUNT );
	first_frame = cvQueryFrame( video );
	num_objects = get_regions( &regions,  MAX_OBJECTS, argv[1] );
	if( num_objects == 0 )
		exit(-1);

	t_ini = clock();
	// Inicializamos el generador de números aleatorios
	gsl_rng_env_setup();
	rng = gsl_rng_alloc( gsl_rng_mt19937 );
	gsl_rng_set(rng, (unsigned long) time(NULL));

	hsv_frame = bgr2hsv( first_frame );
	nuevas_particulas = (particle**) malloc( num_objects * sizeof( particle* ) );
	for( int j = 0; j < num_objects; ++j )
		nuevas_particulas[j] = (particle*) malloc( PARTICLES * sizeof( particle ) );
	
	// Computamos los histogramas de referencia y distribuimos las partículas iniciales
	ref_histos = compute_ref_histos( hsv_frame, regions, num_objects );
	particles = init_distribution( regions, num_objects, PARTICLES );

	// Mostramos el tracking
	if( show_tracking ) {

		// Mostramos todas las partículas
		if( show_all )
			for( int k = 0; k < num_objects; ++k )
				for( int j = 0; j < PARTICLES; ++j )
					display_particle( first_frame, particles[k][j], color_azul );

		// Dibujamos la partícula más prometedora de cada objeto
		for( int k = 0; k < num_objects; ++k )
			display_particle( first_frame, particles[k][0], color_rojo );

		cvNamedWindow( "RGB", 1 );
		cvShowImage( "RGB", first_frame );
		cvWaitKey( 5 );
	}

	// Exportamos los histogramas de referencia y los frames
	if( exportar ) {
		export_ref_histos( ref_histos, num_objects );
		export_frame( first_frame, 1 );

		for( int k = 0; k < num_objects; ++k ) {
			sprintf( num, "%02d", k );
			strcpy( name, REGION_BASE);
			p1 = strrchr( argv[1], '/' );
			p2 = strrchr( argv[1], '.' );
			strncat( name, (++p1), p2-p1 );
			strcat( name, num );
			strcat( name, ".txt" );
			datos = fopen( name, "a+" );
			if( ! datos ) {
				printf("Error creando fichero para datos\n");
				exit(-1);;
			}
			fprintf( datos, "%d\t%f\t%f\n", 0, particles[k][0].x, particles[k][0].y );
			fclose( datos );
		}
	}

	
	// Bucle principal!!
	for(int i = 1; i < nFrames; ++i) {

		// Recordar que frame no se puede liberar debido al cvQueryFrame
		frame = cvQueryFrame( video );
		for( int f = 0 ; f < hsv_frame->height; ++f ) {
			float *ptrHSV = (float*) ( hsv_frame->imageData + hsv_frame->widthStep*f );
			unsigned char *ptrRGB = (unsigned char*) ( frame->imageData + frame->widthStep*f );
			float h;
			for( int col = 0, despH = 0; col < hsv_frame->width; ++col, despH+=3 ) {
				int despS = despH+1;
				int despV = despH+2;
				float b = ptrRGB[despH] * factor;
				float g = ptrRGB[despS] * factor;
				float r = ptrRGB[despV] * factor;
				float min = MIN(MIN(b, g), r);
				float max = MAX(MAX(b, g), r);
				ptrHSV[despV] = max; // v
				if( max != min ) {
					float delta = max - min;
					ptrHSV[despS] = delta / max; // s = (max - min) / max = 1.0 - (min / max)
					if( r == max )
						h = ( g - b ) / delta;
					else if( g == max )
						h = 2.0f + (( b - r ) / delta);
					else
						h = 4.0f + (( r - g ) / delta);
					h *= 60.0f;
					if(h < 0.0f)
						h += 360.0f;
					ptrHSV[despH] = h; // h
				}
				else {
					ptrHSV[despH] = 0.0f; // h
					ptrHSV[despS] = 0.0f; // s
				}
			}
		}

		// Realizamos la predicción y medición de probabilidad para cada partícula
		for( int k = 0; k < num_objects; ++k ) {

			sum = 0.0f;
			for( int j = 0; j < PARTICLES; ++j ) {
				transition( &particles[k][j], frame->width, frame->height, rng );
				particles[k][j].w = likelihood( hsv_frame, &particles[k][j], ref_histos[k], histo_aux[0] );
				sum += particles[k][j].w;
			}
		
			// Normalizamos los pesos y remuestreamos un conjunto de partículas no ponderadas
			for( int j = 0; j < PARTICLES; ++j )
				particles[k][j].w /= sum;
		}

		// Remuestreamos un conjunto de partículas no ponderadas
		for (int k = 0; k < num_objects; ++k )
			resample( particles[k], PARTICLES, nuevas_particulas[k] );

		aux = particles;
		particles = nuevas_particulas;
		nuevas_particulas = aux;

		// Mostramos el tracking
		if( show_tracking ) {

			// Mostramos todas las partículas
			if( show_all )
				for( int k = 0; k < num_objects; ++k )
					for( int j = 0; j < PARTICLES; ++j )
						display_particle( frame, particles[k][j], color_azul );

			// Dibujamos la partícula más prometedora de cada objeto
			for( int k = 0; k < num_objects; ++k )
				display_particle( frame, particles[k][0], color_rojo );
			cvNamedWindow( "RGB", 1 );
			cvShowImage( "RGB", frame );
			cvWaitKey( 5 );
		}

		// Exportamos los histogramas de referencia y los frames
		if( exportar ) {
			export_frame( frame, i+1 );

			for( int k = 0; k < num_objects; ++k ) {
				sprintf( num, "%02d", k );
				strcpy( name, REGION_BASE);
				p1 = strrchr( argv[1], '/' );
				p2 = strrchr( argv[1], '.' );
				strncat( name, (++p1), p2-p1 );
				strcat( name, num );
				strcat( name, ".txt" );
				datos = fopen( name, "a+" );
				if( ! datos ) {
					printf("Error abriendo fichero para datos\n");
					exit(-1);
				}
				fprintf( datos, "%d\t%f\t%f\n", i, particles[k][0].x, particles[k][0].y );
				fclose( datos );
			}
		}
	}
	
	// Liberamos todos los recursos usados (mallocs, gsl y frames)
	cvReleaseImage( &hsv_frame );
	cvReleaseCapture( &video );
	gsl_rng_free( rng );
	free( regions );

	for( int i = 0; i < num_objects; ++i ) {
		free( ref_histos[i] );
		free( particles[i] );
		free( nuevas_particulas[i] );
	}

	free( particles );
	free( nuevas_particulas );

	t_fin = clock();
	ms = ((double)(t_fin - t_ini) / CLOCKS_PER_SEC) * 1000.0;
	printf("%d\t%d\t%.10g\n", PARTICLES, num_objects, ms);
}
Exemplo n.º 10
0
int main(int argc, char** argv)
{
    if (argc < 2 || !strcmp(argv[1], "-help") || !strcmp(argv[1], "--help") ||
            !strcmp(argv[1], "-h") || !strcmp(argv[1], "--usage"))
    {
        print_usage_and_exit();
    }

    double gamma_a = 1.0, gamma_b = 1.0, alpha_a = 1.0, alpha_b = 1.0, eta = 0.5;
    int max_iter = 1000, save_lag = 100, init_topics = 0;
    bool sample_hyperparameter = false;

    bool split_merge = false;
    int num_restricted_scan = 5;

    time_t t;
    time(&t);
    long seed = (long) t;

    char* directory = NULL;;
    char* algorithm = NULL;;
    char* data_path = NULL;
    char* model_path = NULL;

    for (int i = 1; i < argc; i++)
    {
        if (!strcmp(argv[i], "--algorithm"))        algorithm = argv[++i];
        else if (!strcmp(argv[i], "--data"))        data_path = argv[++i];
        else if (!strcmp(argv[i], "--max_iter"))    max_iter = atoi(argv[++i]);
        else if (!strcmp(argv[i], "--save_lag"))    save_lag = atoi(argv[++i]);
        else if (!strcmp(argv[i], "--init_topics")) init_topics = atoi(argv[++i]);
        else if (!strcmp(argv[i], "--directory"))   directory = argv[++i];
        else if (!strcmp(argv[i], "--random_seed")) seed = atoi(argv[++i]);
        else if (!strcmp(argv[i], "--gamma_a"))     gamma_a = atof(argv[++i]);
        else if (!strcmp(argv[i], "--gamma_b"))     gamma_b = atof(argv[++i]);
        else if (!strcmp(argv[i], "--alpha_a"))     alpha_a = atof(argv[++i]);
        else if (!strcmp(argv[i], "--alpha_b"))     alpha_b = atof(argv[++i]);
        else if (!strcmp(argv[i], "--eta"))         eta = atof(argv[++i]);
        else if (!strcmp(argv[i], "--restrict_scan")) num_restricted_scan = atoi(argv[++i]);
        else if (!strcmp(argv[i], "--saved_model")) model_path = argv[++i];
        else if (!strcmp(argv[i], "--split_merge"))
        {
           ++i;
            if (!strcmp(argv[i], "yes") ||  !strcmp(argv[i], "YES"))
                split_merge = true;
        }
        else if (!strcmp(argv[i], "--sample_hyper"))
        {
           ++i;
            if (!strcmp(argv[i], "yes") ||  !strcmp(argv[i], "YES"))
                sample_hyperparameter = true;
        }
        else
        {
            printf("%s, unknown parameters, exit\n", argv[i]);
            exit(0);
        }
    }

    if (algorithm == NULL || directory == NULL || data_path == NULL)
    {
        printf("Note that algorithm, directory and data are not optional!\n");
        exit(0);
    }

    if (VERBOSE && !strcmp(algorithm, "train"))
    {
        printf("\nProgram starts with following parameters:\n");

        printf("algorithm:          = %s\n", algorithm);
        printf("data_path:          = %s\n", data_path);
        printf("directory:          = %s\n", directory);

        printf("max_iter            = %d\n", max_iter);
        printf("save_lag            = %d\n", save_lag);
        printf("init_topics         = %d\n", init_topics);
        printf("random_seed         = %d\n", seed);
        printf("gamma_a             = %.2f\n", gamma_a);
        printf("gamma_b             = %.2f\n", gamma_b);
        printf("alpha_a             = %.2f\n", alpha_a);
        printf("alpha_b             = %.2f\n", alpha_b);
        printf("eta                 = %.2f\n", eta);
        printf("#restricted_scans   = %d\n", num_restricted_scan);
        if (model_path != NULL)
        printf("saved model_path    = %s\n", model_path);
        if (split_merge)
        printf("split-merge         = yes\n");
        else
        printf("split-merge         = no\n");
        if (sample_hyperparameter)
        printf("sampling hyperparam = yes\n");
        else
        printf("sampling hyperparam = no\n");
    }

    if (!dir_exists(directory))
        mkdir(directory, S_IRUSR | S_IWUSR | S_IXUSR);

    // allocate the random number structure
    RANDOM_NUMBER = gsl_rng_alloc(gsl_rng_taus);
    gsl_rng_set(RANDOM_NUMBER, (long) seed); // init the seed

    if (!strcmp(algorithm, "train"))
    {
        // read data
        corpus * c = new corpus();
        c->read_data(data_path);

        // read hyperparameters

        hdp_hyperparameter * hdp_hyperparam = new hdp_hyperparameter();
        hdp_hyperparam->setup_parameters(gamma_a, gamma_b,
                                         alpha_a, alpha_b,
                                         max_iter, save_lag,
                                         num_restricted_scan,
                                         sample_hyperparameter,
                                         split_merge);

        hdp * hdp_instance = new hdp();

        hdp_instance->setup_state(c, eta, init_topics,
                                  hdp_hyperparam);

        hdp_instance->run(directory);

        // free resources
        delete hdp_instance;
        delete c;
        delete hdp_hyperparam;
    }

    if (!strcmp(algorithm, "test"))
    {
        corpus* c = new corpus();
        c->read_data(data_path);

        hdp_hyperparameter * hdp_hyperparam = new hdp_hyperparameter();
        hdp_hyperparam->setup_parameters(gamma_a, gamma_b,
                                         alpha_a, alpha_b,
                                         max_iter, save_lag,
                                         num_restricted_scan,
                                         sample_hyperparameter,
                                         split_merge);

        hdp * hdp_instance = new hdp();
        hdp_instance->load(model_path);
        hdp_instance->setup_state(c, hdp_hyperparam);
        hdp_instance->run_test(directory);

        delete hdp_hyperparam;
        delete hdp_instance;
        delete c;
    }
    gsl_rng_free(RANDOM_NUMBER);
}
Exemplo n.º 11
0
int main(int argc, char *argv[])
{
	struct options options;
	INT8 tinj, jitter;
	gsl_rng *rng;
	ProcessTable *process_table_head = NULL, *process;
	ProcessParamsTable *process_params_table_head = NULL;
	SearchSummaryTable *search_summary_table_head = NULL, *search_summary;
	TimeSlide *time_slide_table_head = NULL;
	SimBurst *sim_burst_table_head = NULL;
	SimBurst **sim_burst = &sim_burst_table_head;


	/*
	 * Initialize debug handler
	 */


	lal_errhandler = LAL_ERR_EXIT;


	/*
	 * Process table
	 */


	process_table_head = process = XLALCreateProcessTableRow();
	if(XLALPopulateProcessTable(process, PROGRAM_NAME, lalAppsVCSIdentId, lalAppsVCSIdentStatus, lalAppsVCSIdentDate, 0))
		exit(1);
	XLALGPSTimeNow(&process->start_time);


	/*
	 * Command line and process params table.
	 */


	options = parse_command_line(&argc, &argv, process, &process_params_table_head);
	if(options.user_tag)
		snprintf(process->comment, sizeof(process->comment), "%s", options.user_tag);


	/*
	 * Search summary table
	 */


	search_summary_table_head = search_summary = XLALCreateSearchSummaryTableRow(process);
	if(options.user_tag)
		snprintf(search_summary->comment, sizeof(search_summary->comment), "%s", options.user_tag);
	search_summary->nnodes = 1;
	search_summary->out_start_time = *XLALINT8NSToGPS(&search_summary->in_start_time, options.gps_start_time);
	search_summary->out_end_time = *XLALINT8NSToGPS(&search_summary->in_end_time, options.gps_end_time);


	/*
	 * Initialize random number generator
	 */


	rng = gsl_rng_alloc(gsl_rng_mt19937);
	if(options.seed)
		gsl_rng_set(rng, options.seed);


	/*
	 * Main loop
	 */


	for(tinj = options.gps_start_time; tinj <= options.gps_end_time; tinj += options.time_step * 1e9) {
		/*
		 * Progress bar.
		 */

		XLALPrintInfo("%s: ", argv[0]);
		XLALPrintProgressBar((tinj - options.gps_start_time) / (double) (options.gps_end_time - options.gps_start_time));
		XLALPrintInfo(" complete\n");

		/*
		 * Create an injection
		 */

		switch(options.population) {
		case POPULATION_TARGETED:
			*sim_burst = random_directed_btlwnb(options.ra, options.dec, gsl_ran_flat(rng, 0, LAL_TWOPI), options.minf, options.maxf, options.minbandwidth, options.maxbandwidth, options.minduration, options.maxduration, options.minEoverr2, options.maxEoverr2, rng);
			break;

		case POPULATION_ALL_SKY_SINEGAUSSIAN:
			*sim_burst = random_all_sky_sineGaussian(options.minf, options.maxf, options.q, options.minhrss, options.maxhrss, rng);
			break;

		case POPULATION_ALL_SKY_BTLWNB:
			*sim_burst = random_all_sky_btlwnb(options.minf, options.maxf, options.minbandwidth, options.maxbandwidth, options.minduration, options.maxduration, options.minEoverr2, options.maxEoverr2, rng);
			break;

		case POPULATION_STRING_CUSP:
			*sim_burst = random_string_cusp(options.minf, options.maxf, options.minA, options.maxA, rng);
			break;

		default:
			/* shouldn't get here, command line parsing code
			 * should prevent it */
			XLALPrintError("internal error\n");
			exit(1);
		}

		if(!*sim_burst) {
			XLALPrintError("can't make injection\n");
			exit(1);
		}

		/*
		 * Peak time at geocentre in GPS seconds
		 */

		/* Add "jitter" to the injection if user requests it */
		if(options.jitter > 0) {
			jitter = gsl_ran_flat(rng, -options.jitter/2, options.jitter/2)*1e9;
		} else {
			jitter = 0;
		}

		XLALINT8NSToGPS(&(*sim_burst)->time_geocent_gps, tinj + jitter);

		/*
		 * Peak time at geocentre in GMST radians
		 */

		(*sim_burst)->time_geocent_gmst = XLALGreenwichMeanSiderealTime(&(*sim_burst)->time_geocent_gps);

		/*
		 * Move to next injection
		 */

		sim_burst = &(*sim_burst)->next;
	}

	XLALPrintInfo("%s: ", argv[0]);
	XLALPrintProgressBar(1.0);
	XLALPrintInfo(" complete\n");

	/* load time slide document and merge our table rows with its */

	if(load_tisl_file_and_merge(options.time_slide_file, &process_table_head, &process_params_table_head, &time_slide_table_head, &search_summary_table_head, &sim_burst_table_head))
		exit(1);
	if(set_instruments(process, time_slide_table_head))
		exit(1);
	snprintf(search_summary->ifos, sizeof(search_summary->ifos), "%s", process->ifos);

	/* output */

	XLALGPSTimeNow(&process->end_time);
	search_summary->nevents = XLALSimBurstAssignIDs(sim_burst_table_head, process->process_id, time_slide_table_head->time_slide_id, 0);
	write_xml(options.output, process_table_head, process_params_table_head, search_summary_table_head, time_slide_table_head, sim_burst_table_head);

	/* done */

	gsl_rng_free(rng);
	XLALDestroyProcessTable(process_table_head);
	XLALDestroyProcessParamsTable(process_params_table_head);
	XLALDestroyTimeSlideTable(time_slide_table_head);
	XLALDestroySearchSummaryTable(search_summary_table_head);
	XLALDestroySimBurstTable(sim_burst_table_head);
	exit(0);
}
Exemplo n.º 12
0
int main(int argc, char *argv[]) {
   if (argc != 2) {
      cout << "Usage: setup outfilename" << endl;
      return(-1);
   }
   string filename = argv[1];

   vector<Cparticle> ps;
   Cparticle p;
   cout << "Creating box with sides: rmax = ["<<RMAX[0]<<" "<<RMAX[1]<<"] rmin = ["<<RMIN[0]<<" "<<RMIN[1]<<"]"<<endl;
   cout << "Reynolds Number = "<<REYNOLDS_NUMBER<<endl;
   cout << "Density = "<<DENS<<endl;
   cout << "number of particles on side = "<<NX<<endl;
   cout << "alpha = "<<ALPHA<<endl;
   cout << "viscosity = "<<VISCOSITY<<endl;
   cout << "maxtime = "<<MAXTIME<<endl;
 
   double tsc = Nsph::courantCondition(H,2*SPSOUND);
   double tsv = Nsph::viscDiffusionCondition(H,VISCOSITY);
   cout <<"simulation will take "<<int((MAXTIME/tsc)+1)<<" steps according to Courant condition, "<<int((MAXTIME/tsv)+1)<<" steps according to visc diffusion condition"<<endl;


   gsl_rng *rng = gsl_rng_alloc(gsl_rng_ranlxd1);
   gsl_rng_set(rng,1);
   //gsl_rng_set(rng,time(NULL));
   for (int i=0;i<NX;i++) {
         cout << "\rParticle ("<<i<<","<<"0"<<"). Generation "<<((i+2)*(NY+4))/double((NX+4)*(NY+4))*100<<"\% complete"<<flush;
      for (int j=0;j<NY;j++) {
         p.tag = ps.size()+1;
         p.r = (i+0.5)*PSEP+RMIN[0],(j+0.5)*PSEP+RMIN[1];
         p.dens = DENS;
         p.mass = PSEP*PSEP*DENS;
         p.h = H;
         p.v = -VREF*cos(2.0*PI*p.r[0])*sin(2.0*PI*p.r[1]),VREF*sin(2.0*PI*p.r[0])*cos(2.0*PI*p.r[1]);
         p.v[0] += gsl_ran_gaussian(rng,VREF/20);
         p.v[1] += gsl_ran_gaussian(rng,VREF/20);
         p.v[2] += gsl_ran_gaussian(rng,VREF/20);
         p.vhat = p.v;
         p.iam = sph;
         ps.push_back(p);
      }
   }


   cout << "Total number of particles = " << ps.size() << endl;

   CglobalVars globals;


   vector<vector<double> > vprocDomain(globals.mpiSize);
   vector<Array<int,NDIM> > vprocNeighbrs(globals.mpiSize);
   vector<particleContainer > vps;
   vectInt split;
   split = 1,1;
   particleContainer pps;
   for (int i=0;i<ps.size();i++) {
      pps.push_back(ps[i]);
   }
   Nmisc::splitDomain(pps,split,vps,vprocDomain,vprocNeighbrs);
   cout << "Opening files for writing..."<<endl;

   Cio_data_vtk ioFile(filename.c_str(),&globals);

   cout << "Writing Restart data to file..."<<endl;
   int nProc = product(split);
   for (int i=0;i<nProc;i++) {
      globals.mpiRank = i;
      for (int j=0;j<NDIM*2;j++)
         globals.procDomain[j] = vprocDomain[i][j];
      globals.procNeighbrs = vprocNeighbrs[i];
      ioFile.setFilename(filename.c_str(),&globals);
      ioFile.writeGlobals(0,&globals);
      ioFile.writeRestart(0,vps[i],&globals);
      ioFile.writeDomain(0,&globals);
      globals.mpiRank = 0;
   }


}
Exemplo n.º 13
0
int
main()
{
  // setup random number generator
  gRandomGenerator = gsl_rng_alloc(gsl_rng_taus);
  gsl_rng_set (gRandomGenerator, 0.0);

  // created a rapidity cut named "eta", which returns true if the passed track has a
  //  pseudo-rapidity greater than 0.1
  Cut c0("eta", new eta_greator(0.1));

  // add some other cuts acting on different ranges
  c0.AddCut("zab>2", new eta_greator(2.0))(new eta_greator(5.0))(new eta_greator(8.0));

  // Create a pt cut
  Cut pt_cut("pt>3", new pt_greator(3.0));

  // Create a pt cut
  Cut pt_cut("pt>3.0", new pt_greator(3.0));

  // add some more cuts to the pt-cut group
  //  (Cut::AddCut returns an inserter with operator() which
  //   continues to insert if given a name + function pair)
  pt_cut.AddCut("pt>4.0", new pt_greator(4.0))
               ("pt>6.0", new pt_greator(6.0))
               ("pt>2.0", new pt_greator(2.0))
               ("pt>1.0", new pt_greator(1.0));

  // create a cutlist
  CutList cuts;
  cuts.AddCut(pt_cut);

//  cuts.AddAction("eta", add_to_histogram_eta_1);
//  cuts.AddAction("pt>3 zab>2", add_to_histogram_1);
//  cuts.AddAction("pt>3 eta", add_to_histogram_4);

  cuts.AddAction("pt>3.0", action_pt_3_0);
  cuts.AddAction("pt>4.0", action_pt_4_0);
  cuts.AddAction("pt>1.0", action_pt_1_0);
  cuts.AddAction("pt>2.0", action_pt_2_0);
  cuts.AddAction("pt>6.0", action_pt_6_0);

  cuts.AddAction("pt>4.0 pt>2.0", action_pt_4_AND_2);

//  cuts.Print();

  // generate a random cut
  Track track = Generate();
  track.print();
  std::cout << "Testing Random : " << cuts.Run(track) << std::endl;
  for (int i = 0; i < 50; i++) {
    Track t = Generate();
//    std::cout << "Mass : " << t.m << std::endl;
    cuts.Run(t);
  }
  // std::cout << c0.Run(1.0f) << ' ' << c0.Run(9.0f) << std::endl;
  puts("");

std::cout << "Pt > 1.0 Count : " << pt_1_count << std::endl
          << "Pt > 2.0 Count : " << pt_2_count << std::endl
          << "Pt > 3.0 Count : " << pt_3_count << std::endl
          << "Pt > 4.0 Count : " << pt_4_count << std::endl
          << "Pt > 6.0 Count : " << pt_6_count << std::endl;



  std::cout << "It works!" << std::endl;
  return 0;
}
Exemplo n.º 14
0
Arquivo: test.c Projeto: gaponenko/gsl
int
main()
{
  gsl_rng *r = gsl_rng_alloc(gsl_rng_default);
  const double tol1 = 1.0e-8;
  const double tol2 = 1.0e-3;

  gsl_ieee_env_setup();

  {
    const size_t N = 2000000;
    double *data = random_data(N, r);
    double data2[] = { 4.0, 7.0, 13.0, 16.0 };
    size_t i;

    test_basic(2, data, tol1);
    test_basic(100, data, tol1);
    test_basic(1000, data, tol1);
    test_basic(10000, data, tol1);
    test_basic(50000, data, tol1);
    test_basic(80000, data, tol1);
    test_basic(1500000, data, tol1);
    test_basic(2000000, data, tol1);

    for (i = 0; i < 4; ++i)
      data2[i] += 1.0e9;

    test_basic(4, data2, tol1);

    free(data);
  }

  {
    /* dataset from Jain and Chlamtac paper */
    const size_t n_jain = 20;
    const double data_jain[] = {  0.02,  0.15,  0.74,  3.39,  0.83,
                                  22.37, 10.15, 15.43, 38.62, 15.92,
                                  34.60, 10.28,  1.47,  0.40,  0.05,
                                  11.39,  0.27,  0.42,  0.09, 11.37 };
    double expected_jain = 4.44063435326;
  
    test_quantile(0.5, data_jain, n_jain, expected_jain, tol1, "jain");
  }

  {
    size_t n = 1000000;
    double *data = malloc(n * sizeof(double));
    double *sorted_data = malloc(n * sizeof(double));
    gsl_rstat_workspace *rstat_workspace_p = gsl_rstat_alloc();
    double p;
    size_t i;

    for (i = 0; i < n; ++i)
      {
        data[i] = gsl_ran_gaussian_tail(r, 1.3, 1.0);
        gsl_rstat_add(data[i], rstat_workspace_p);
      }

    memcpy(sorted_data, data, n * sizeof(double));
    gsl_sort(sorted_data, 1, n);

    /* test quantile calculation */
    for (p = 0.1; p <= 0.9; p += 0.1)
      {
        double expected = gsl_stats_quantile_from_sorted_data(sorted_data, 1, n, p);
        test_quantile(p, data, n, expected, tol2, "gauss");
      }

    /* test mean, variance */
    {
      const double expected_mean = gsl_stats_mean(data, 1, n);
      const double expected_var = gsl_stats_variance(data, 1, n);
      const double expected_sd = gsl_stats_sd(data, 1, n);
      const double expected_skew = gsl_stats_skew(data, 1, n);
      const double expected_kurtosis = gsl_stats_kurtosis(data, 1, n);
      const double expected_median = gsl_stats_quantile_from_sorted_data(sorted_data, 1, n, 0.5);

      const double mean = gsl_rstat_mean(rstat_workspace_p);
      const double var = gsl_rstat_variance(rstat_workspace_p);
      const double sd = gsl_rstat_sd(rstat_workspace_p);
      const double skew = gsl_rstat_skew(rstat_workspace_p);
      const double kurtosis = gsl_rstat_kurtosis(rstat_workspace_p);
      const double median = gsl_rstat_median(rstat_workspace_p);

      gsl_test_rel(mean, expected_mean, tol1, "mean");
      gsl_test_rel(var, expected_var, tol1, "variance");
      gsl_test_rel(sd, expected_sd, tol1, "stddev");
      gsl_test_rel(skew, expected_skew, tol1, "skew");
      gsl_test_rel(kurtosis, expected_kurtosis, tol1, "kurtosis");
      gsl_test_abs(median, expected_median, tol2, "median");
    }

    free(data);
    free(sorted_data);
    gsl_rstat_free(rstat_workspace_p);
  }

  gsl_rng_free(r);

  exit (gsl_test_summary());
}
Exemplo n.º 15
0
int main (int argc, char *argv[])
{
    double ratio,ns;
    
    // neutron stars, pulsar to bulge
    double res_x,err_x;

    //double xl_x[4]={3.0,0.0,-1200.0,-1200.0};
    //double xu_x[4]={13.0,13.0,1200.0,1200.0};
    //double xl_x[10]={4.5,0.0,-2000.0,-2000.0,-2000.0,-550.0,-450.0,-350.0,-3.1415926, -5.0*3.1415926/180.0};
    double xl_x[10]={4.5,0.0,-2000.0,-2000.0,-2000.0,-550.0,-450.0,-350.0,0.0001, -5.0*3.1415926/180.0};
    double xu_x[10]={11.5,8.0,2000.0,2000.0,2000.0,550.0,450.0,350.0,3.1415926, 5.0*3.1415926/180.0};

    const gsl_rng_type *T_x;
    gsl_rng *r_x;

    gsl_monte_function G_x={&g_psr,10,0};

    size_t calls_x=50000000;

    gsl_rng_env_setup ();

    T_x=gsl_rng_default;

    // neutron stars, pulsar to disk 
    double res_xd,err_xd;

    //double xl_x[4]={3.0,0.0,-2000.0,-2000.0};
    //double xu_x[4]={13.0,13.0,2000.0,2000.0};
    //double xl_xd[10]={0.0,0.0,-2000.0,-2000.0,-2000.0,-100.0,-150.0,-100.0,-3.1415926, -5.0*3.1415926/180.0};
    double xl_xd[10]={0.0,0.0,-2000.0,-2000.0,-2000.0,-100.0,-150.0,-100.0,0.0001, -5.0*3.1415926/180.0};
    double xu_xd[10]={11.5,8.0,2000.0,2000.0,2000.0,100.0,150.0,100.0,3.1415926, 5.0*3.1415926/180.0};

    const gsl_rng_type *T_xd;
    gsl_rng *r_xd;

    gsl_monte_function G_xd={&g_psr_disk,10,0};

    size_t calls_xd=50000000;

    T_xd=gsl_rng_default;
    
    ////////////////////////////////////////////////////////////////////////////////////////////
    //////////////////////////////////////////////////////////////////////////////////////////////////////

    // source bulge
    double res_s,err_s;

    double xl_s[3]={4.5,-3.1415926, -5.0*3.1415926/180.0};
    double xu_s[3]={11.5,3.1415926, 5.0*3.1415926/180.0};

    const gsl_rng_type *T_s;
    gsl_rng *r_s;

    gsl_monte_function G_s={&source,3,0};

    size_t calls_s=50000000;

    T_s=gsl_rng_default;

    r_s = gsl_rng_alloc (T_s);

    gsl_monte_vegas_state *s_s = gsl_monte_vegas_alloc (3);
    gsl_monte_vegas_integrate (&G_s, xl_s, xu_s, 3, 10000, r_s, s_s, &res_s, &err_s);

    do
    {
        gsl_monte_vegas_integrate (&G_s, xl_s, xu_s, 3, calls_s/5, r_s, s_s, &res_s, &err_s);
    }
    while (fabs (gsl_monte_vegas_chisq (s_s) - 1.0) > 0.5);

    gsl_monte_vegas_free (s_s);

    gsl_rng_free (r_s);
    
    //////////////////////////////////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////////////////////////////////////

    // source disk
    double res_sd,err_sd;

    double xl_sd[3]={0.0,-3.1415926, -5.0*3.1415926/180.0};
    double xu_sd[3]={11.5,3.1415926, 5.0*3.1415926/180.0};

    const gsl_rng_type *T_sd;
    gsl_rng *r_sd;

    gsl_monte_function G_sd={&source_d,3,0};

    size_t calls_sd=50000000;

    T_sd=gsl_rng_default;

    r_sd = gsl_rng_alloc (T_sd);

    gsl_monte_vegas_state *s_sd = gsl_monte_vegas_alloc (3);
    gsl_monte_vegas_integrate (&G_sd, xl_sd, xu_sd, 3, 10000, r_sd, s_sd, &res_sd, &err_sd);

    do
    {
        gsl_monte_vegas_integrate (&G_sd, xl_sd, xu_sd, 3, calls_sd/5, r_sd, s_sd, &res_sd, &err_sd);
    }
    while (fabs (gsl_monte_vegas_chisq (s_sd) - 1.0) > 0.5);

    gsl_monte_vegas_free (s_sd);

    gsl_rng_free (r_sd);
    
    //////////////////////////////////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////////////////////////////////////


    r_x=gsl_rng_alloc(T_x);

    gsl_monte_vegas_state *s_x = gsl_monte_vegas_alloc (10);

    r_xd=gsl_rng_alloc(T_xd);
        
    gsl_monte_vegas_state *s_xd = gsl_monte_vegas_alloc (10);

    // calculation
    
        gsl_monte_vegas_integrate (&G_x, xl_x, xu_x, 10, 10000, r_x, s_x,&res_x, &err_x);

        do
        {
            gsl_monte_vegas_integrate (&G_x, xl_x, xu_x, 10, calls_x/5, r_x, s_x,&res_x, &err_x);
        }
        while (fabs (gsl_monte_vegas_chisq (s_x) - 1.0) > 0.5);

    /////////////////////////////////////////////////////////////////////////////////////////////
    //////////////////////////////////////////////////////////////////////////////////////////////

        gsl_monte_vegas_integrate (&G_xd, xl_xd, xu_xd, 10, 10000, r_xd, s_xd, &res_xd, &err_xd);

        do
        {
            gsl_monte_vegas_integrate (&G_xd, xl_xd, xu_xd, 10, calls_xd/5, r_xd, s_xd, &res_xd, &err_xd);
        }
        while (fabs (gsl_monte_vegas_chisq (s_xd) - 1.0) > 0.5);

        //////////////////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////

        ns = res_x+res_xd;
        ratio = ns/(res_s+res_sd);
        printf ("%e\n", ratio);

    gsl_monte_vegas_free (s_x);

    gsl_rng_free (r_x);

    gsl_monte_vegas_free (s_xd);

    gsl_rng_free (r_xd);

    return 0;
}
Exemplo n.º 16
0
int main (int argc, char *argv[])
{
    double ns;
    int i;
    int id;  //  process rank
    int p;   //  number of processes

    MPI_Init (&argc, &argv);
    MPI_Comm_rank (MPI_COMM_WORLD, &id);
    MPI_Comm_size (MPI_COMM_WORLD, &p);
    
    // neutron stars, pulsar to bulge
    double res_x,err_x;

    //double xl_x[4]={3.0,0.0,-1200.0,-1200.0};
    //double xu_x[4]={13.0,13.0,1200.0,1200.0};
    double xl_x[8]={3.0,0.0,-2000.0,-2000.0,-2000.0,-550.0,-450.0,-350.0};
    double xu_x[8]={13.0,13.0,2000.0,2000.0,2000.0,550.0,450.0,350.0};

    const gsl_rng_type *T_x;
    gsl_rng *r_x;

    gsl_monte_function G_x={&g_psr,8,0};

    size_t calls_x=500000000;

    T_x=gsl_rng_default;

    // neutron stars, pulsar to disk 
    double res_xd,err_xd;

    //double xl_x[4]={3.0,0.0,-2000.0,-2000.0};
    //double xu_x[4]={13.0,13.0,2000.0,2000.0};
    double xl_xd[8]={0.0,0.0,-2000.0,-2000.0,-2000.0,-100.0,-150.0,-100.0};
    double xu_xd[8]={13.0,13.0,2000.0,2000.0,2000.0,100.0,150.0,100.0};

    const gsl_rng_type *T_xd;
    gsl_rng *r_xd;

    gsl_monte_function G_xd={&g_psr_disk,8,0};

    size_t calls_xd=500000000;

    T_xd=gsl_rng_default;
    
    ////////////////////////////////////////////////////////////////////////////////////////////
    // source
    double res_s,err_s;

    double xl_s[1]={3.0};
    double xu_s[1]={13.0};

    const gsl_rng_type *T_s;
    gsl_rng *r_s;

    gsl_monte_function G_s={&source,1,0};

    size_t calls_s=500000000;

    T_s=gsl_rng_default;

    r_s = gsl_rng_alloc (T_s);

    gsl_monte_vegas_state *s_s = gsl_monte_vegas_alloc (1);
    gsl_monte_vegas_integrate (&G_s, xl_s, xu_s, 1, 10000, r_s, s_s, &res_s, &err_s);

    do
    {
        gsl_monte_vegas_integrate (&G_s, xl_s, xu_s, 1, calls_s/5, r_s, s_s, &res_s, &err_s);
    }
    while (fabs (gsl_monte_vegas_chisq (s_s) - 1.0) > 0.5);

    gsl_monte_vegas_free (s_s);

    gsl_rng_free (r_s);
    
    //////////////////////////////////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////////////////////////////////////

    // source disk
    double res_sd,err_sd;

    double xl_sd[1]={0.0};
    double xu_sd[1]={13.0};

    const gsl_rng_type *T_sd;
    gsl_rng *r_sd;

    gsl_monte_function G_sd={&source_disk,1,0};

    size_t calls_sd=500000000;

    T_sd=gsl_rng_default;

    r_sd = gsl_rng_alloc (T_sd);

    gsl_monte_vegas_state *s_sd = gsl_monte_vegas_alloc (1);
    gsl_monte_vegas_integrate (&G_sd, xl_sd, xu_sd, 1, 10000, r_sd, s_sd, &res_sd, &err_sd);

    do
    {
        gsl_monte_vegas_integrate (&G_sd, xl_sd, xu_sd, 1, calls_sd/5, r_sd, s_sd, &res_sd, &err_sd);
    }
    while (fabs (gsl_monte_vegas_chisq (s_sd) - 1.0) > 0.5);

    gsl_monte_vegas_free (s_sd);

    gsl_rng_free (r_sd);
    

    //////////////////////////////////////////////////////////////////////////////////////////////////////

    r_x=gsl_rng_alloc(T_x);
        
    gsl_monte_vegas_state *s_x = gsl_monte_vegas_alloc (8);

    r_xd=gsl_rng_alloc(T_xd);
        
    gsl_monte_vegas_state *s_xd = gsl_monte_vegas_alloc (8);

    // calculation
    for (i=id;i<=200;i+=p)
    {
        //t=pow(10.0,0.015*i);    
        t=-0.5+0.0175*i; 
    
        gsl_monte_vegas_integrate (&G_x, xl_x, xu_x, 8, 10000, r_x, s_x,&res_x, &err_x);

        do
        {
            gsl_monte_vegas_integrate (&G_x, xl_x, xu_x, 8, calls_x/5, r_x, s_x,&res_x, &err_x);
        }
        while (fabs (gsl_monte_vegas_chisq (s_x) - 1.0) > 0.5);

    /////////////////////////////////////////////////////////////////////////////////////////////
    //////////////////////////////////////////////////////////////////////////////////////////////

        gsl_monte_vegas_integrate (&G_xd, xl_xd, xu_xd, 8, 10000, r_xd, s_xd, &res_xd, &err_xd);

        // display_results ("vegas warm-up", res, err);
        // printf ("converging...\n");
        do
        {
            gsl_monte_vegas_integrate (&G_xd, xl_xd, xu_xd, 8, calls_xd/5, r_xd, s_xd, &res_xd, &err_xd);
          //printf ("result = % .6ef sigma = % .6ef chisq/dof = %.1f\n", res, err, gsl_monte_vegas_chisq (s));
        }
        while (fabs (gsl_monte_vegas_chisq (s_xd) - 1.0) > 0.5);
        // display_results ("vegas final", res, err);

        //////////////////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////

        ns = (fabs(res_x)+fabs(res_xd))/(fabs(res_s)+fabs(res_sd));
        printf ("%e %e\n", t, ns);
        fflush(stdout);        

    }

    gsl_monte_vegas_free (s_x);

    gsl_rng_free (r_x);

    gsl_monte_vegas_free (s_xd);

    gsl_rng_free (r_xd);

    fflush (stdout);
    MPI_Finalize ();
    return 0;
}
Exemplo n.º 17
0
	void cpuoptical_(int *gpusize)				
	{    

		// command line arguments
		float xdetector, ydetector, radius, height, n_C, n_IC, top_absfrac, bulk_abscoeff, beta, d_min, lbound_x, lbound_y, ubound_x, ubound_y, d_max, yield, sensorRefl;
		int pixelsize, num_primary, min_optphotons, max_optphotons, num_bins;

		float dcos[3]={0}; 		// directional cosines
		float normal[3]={0}; 		// normal to surface in case of TIR
		float pos[3] = {0}; 		// intersecting point coordinates
		float old_pos[3] = {0};  	// source coordinates
	
		int nbytes = (optical_.myctropt - (*gpusize))*sizeof(struct start_info);
		struct start_info *structa;
		structa = (struct start_info*) malloc(nbytes);
		if( structa == NULL )
			printf("\n Struct start_info array CANNOT BE ALLOCATED - %d !!", (optical_.myctropt-(*gpusize)));

		// get cpu time
		clock_t start, end;
		float num_sec;

		// get current time stamp to initialize seed input for RNG
		time_t seconds;
		seconds = time (NULL);
		struct timeval tv;
		gettimeofday(&tv,NULL);

		float rr=0.0f, theta=0.0f;	
		float r=0.0f;			// random number
		float norm=0.0f;
		int jj=0;
		int my_index=0;
		int penindex = 0;		// equal to *gpusize
		int result_algo = 0;
		unsigned long long int *num_rebound;

		// initialize random number generator (RANECU)
		int seed_input = 271828182 ; 		// ranecu seed input
		int seed[2];

		// GNU scientific library (gsl) variables
		const gsl_rng_type * Tgsl;
		gsl_rng * rgsl;
		double mu_gsl;	
				
		// output image variables
		int xdim = 0;
		int ydim = 0;
		int indexi=0, indexj=0;

		// copy to local variables from PENELOPE buffers
		xdetector = inputargs_.detx;		// x dimension of detector (in um). x in (0,xdetector)
		ydetector = inputargs_.dety;		// y dimension of detector (in um). y in (0,ydetector)
		height = inputargs_.detheight;		// height of column and thickness of detector (in um). z in range (-H/2, H/2)
		radius = inputargs_.detradius;		// radius of column (in um).
		n_C = inputargs_.detnC;			// refractive index of columns
		n_IC = inputargs_.detnIC;		// refractive index of intercolumnar material
		top_absfrac = inputargs_.dettop;	// column's top surface absorption fraction (0.0, 0.5, 0.98)
		bulk_abscoeff = inputargs_.detbulk;	// column's bulk absorption coefficient (in um^-1) (0.001, 0.1 cm^-1) 
		beta = inputargs_.detbeta;		// roughness coefficient of column walls
		d_min = inputargs_.detdmin;		// minimum distance a photon can travel when transmitted from a column
		d_max = inputargs_.detdmax;
		lbound_x = inputargs_.detlboundx;	// x lower bound of region of interest of output image (in um)
		lbound_y = inputargs_.detlboundy;	// y lower bound (in um)
		ubound_x = inputargs_.detuboundx;	// x upper bound (in um) 
		ubound_y = inputargs_.detuboundy;	// y upper bound (in um)
		yield = inputargs_.detyield;		// yield (/eV)
		pixelsize = inputargs_.detpixel;	// 1 pixel = pixelsize microns (in um)
		sensorRefl = inputargs_.detsensorRefl;	// Non-Ideal sensor reflectivity (%)
		num_primary = inputargs_.mynumhist;	// total number of primaries to be simulated
		min_optphotons = inputargs_.minphotons;	// minimum number of optical photons detected to be included in PHS
		max_optphotons = inputargs_.maxphotons;	// maximum number of optical photons detected to be included in PHS
		num_bins = inputargs_.mynumbins;	// number of bins for genrating PHS

	      	// create a generator chosen by the environment variable GSL_RNG_TYPE
	       	gsl_rng_env_setup();	     
	       	Tgsl = gsl_rng_default;
	       	rgsl = gsl_rng_alloc (Tgsl);
	       	
	       	// dimensions of PRF image
		xdim = ceil((ubound_x - lbound_x)/pixelsize);
		ydim = ceil((ubound_y - lbound_y)/pixelsize);
		unsigned long long int myimage[xdim][ydim];
		
		//initialize the output image 2D array
		for(indexi = 0; indexi < xdim; indexi++)
		{ 
		 for(indexj = 0; indexj < ydim; indexj++)
		 {
		  myimage[indexi][indexj] = 0;
		 }
		}
	
		// memory for storing histogram of # photons detected/primary
		int *h_num_detected_prim = 0;		
		h_num_detected_prim = (int*)malloc(sizeof(int)*num_primary);
			
		for(indexj=0; indexj < num_primary; indexj++)
		  h_num_detected_prim[indexj] = 0;
		  	
		// memory for storing histogram of # photons detected/primary
		int *h_histogram = 0;		
		h_histogram = (int*)malloc(sizeof(int)*num_bins);
			
		for(indexj=0; indexj < num_bins; indexj++)
		  h_histogram[indexj] = 0;

	penindex = *gpusize;
	
	for(my_index = 0; my_index < (optical_.myctropt-(*gpusize)); my_index++)		// iterate over x-rays
	{

		// reset the global counters
		num_generated = 0;
		num_detect=0;
		num_abs_top=0;	
		num_abs_bulk=0;	
		num_lost=0;
		num_outofcol=0;
		num_theta1=0;
		photon_distance=0.0f;

		//re-initialize the output image 2D array
		for(indexi = 0; indexi < xdim; indexi++)
		 for(indexj = 0; indexj < ydim; indexj++)
		   myimage[indexi][indexj] = 0;

		// copying PENELOPE buffer into *structa

		// units in the penelope output file are in cm. Convert them to microns.
		structa[my_index].str_x = optical_.xbufopt[penindex+my_index] * 10000.0f;	// x-coordinate of interaction event
		structa[my_index].str_y = optical_.ybufopt[penindex+my_index] * 10000.0f;	// y-coordinate
		structa[my_index].str_z = optical_.zbufopt[penindex+my_index] * 10000.0f;	// z-coordinate
		structa[my_index].str_E = optical_.debufopt[penindex+my_index];			// energy deposited
		structa[my_index].str_histnum = optical_.nbufopt[penindex+my_index];		// x-ray history

		// sample # optical photons based on light yield and energy deposited for this interaction event (using Poisson distribution)
		mu_gsl = (double)structa[my_index].str_E * yield;
		structa[my_index].str_N = gsl_ran_poisson(rgsl,mu_gsl);

		if(structa[my_index].str_N > max_photon_per_EDE)
		{
			printf("\n\n str_n exceeds max photons. program is exiting - %d !! \n\n",structa[my_index].str_N);
			exit(0);
		}


		num_rebound = (unsigned long long int*) malloc(structa[my_index].str_N*sizeof(unsigned long long int));
		if(num_rebound == NULL)
		printf("\n Error allocating num_rebound memory !\n");

		// start the clock
		start = clock();

		// initialize the RANECU generator in a position far away from the previous history:
		seed_input = (int)(seconds/3600+tv.tv_usec);			// seed input=seconds passed since 1970+current time in micro secs
		init_PRNG(my_index, 50000, seed_input, seed);      		// intialize RNG

		for(jj=0; jj<structa[my_index].str_N; jj++)
			num_rebound[jj] = 0;

		// reset the directional cosine and normal vectors
		dcos[0]=0.0f; dcos[1]=0.0f; dcos[2]=0.0f;
		normal[0]=0.0f; normal[1]=0.0f; normal[2]=0.0f;

		// re-initialize myimage
		for(indexi = 0; indexi < xdim; indexi++)
		 for(indexj = 0; indexj < ydim; indexj++)
			  myimage[indexi][indexj] = 0;
		
		// set starting location of photon
		pos[0] = structa[my_index].str_x; pos[1] = structa[my_index].str_y; pos[2] = structa[my_index].str_z;	
		old_pos[0] = structa[my_index].str_x; old_pos[1] = structa[my_index].str_y; old_pos[2] = structa[my_index].str_z;

		// initializing the direction cosines for the first particle in each core
		r = (ranecu(seed) * 2.0f) - 1.0f; 	// random number between (-1,1)
		 	
		while(fabs(r) <= 0.01f)	
		 {
		   	r = (ranecu(seed) * 2.0f) - 1.0f;  	
		 }

		dcos[2] = r;		// random number between (-1,1)
		rr = sqrt(1.0f-r*r);
		theta=ranecu(seed)*twopipen;
		dcos[0]=rr*cos(theta);
		dcos[1]=rr*sin(theta);

		norm = sqrt(dcos[0]*dcos[0] + dcos[1]*dcos[1] + dcos[2]*dcos[2]);

		if ((norm < (1.0f - epsilon)) || (norm > (1.0f + epsilon)))	// normalize
		 {
			dcos[0] = dcos[0]/norm;
			dcos[1] = dcos[1]/norm;
			dcos[2] = dcos[2]/norm;
		 }


		local_counter=0;	// total number of photons terminated (either detected at sensor, absorbed at the top or in the bulk) [global variable]
		while(local_counter < structa[my_index].str_N)		// until all the optical photons are not transported
		 { 
			
			absorbed = 0;
			detect = 0;
			bulk_abs = 0;

			// set starting location of photon
			pos[0] = structa[my_index].str_x; pos[1] = structa[my_index].str_y; pos[2] = structa[my_index].str_z;	
			old_pos[0] = structa[my_index].str_x; old_pos[1] = structa[my_index].str_y; old_pos[2] = structa[my_index].str_z;
			num_generated++;
			result_algo = 0;

			while(result_algo == 0)
			 {
			  	result_algo = algo(normal, old_pos, pos, dcos, num_rebound, seed, structa[my_index], &myimage[0][0], xdetector, ydetector, radius, height, n_C, n_IC, top_absfrac, bulk_abscoeff, beta, d_min, pixelsize, lbound_x, lbound_y, ubound_x, ubound_y, sensorRefl, d_max, ydim, h_num_detected_prim);      
			 }

		 }	


		// end the clock		
		end = clock();

		num_sec = (((float)end - start)/CLOCKS_PER_SEC);

			
		 // type cast unsigned long long int to double
		 double cast_num_generated;
		 double cast_num_detect;
		 double cast_num_abs_top;
		 double cast_num_abs_bulk;
		 double cast_num_lost;
		 double cast_num_outofcol;
		 double cast_num_theta1;
		 double cast_gputime;

		 cast_num_generated = (double)num_generated;
		 cast_num_detect    = (double)num_detect;
		 cast_num_abs_top   = (double)num_abs_top;
		 cast_num_abs_bulk  = (double)num_abs_bulk;
		 cast_num_lost      = (double)num_lost;
		 cast_num_outofcol  = (double)num_outofcol;
		 cast_num_theta1    = (double)num_theta1;
		 cast_gputime	    = (double)(num_sec*1000.0);		// convert in millisecond

		 // save to global counters
		 optstats_.glgen      = optstats_.glgen      + cast_num_generated;
		 optstats_.gldetect   = optstats_.gldetect   + cast_num_detect;
		 optstats_.glabstop   = optstats_.glabstop   + cast_num_abs_top;
		 optstats_.glabsbulk  = optstats_.glabsbulk  + cast_num_abs_bulk;
		 optstats_.gllost     = optstats_.gllost     + cast_num_lost;
		 optstats_.gloutofcol = optstats_.gloutofcol + cast_num_outofcol;
		 optstats_.gltheta1   = optstats_.gltheta1   + cast_num_theta1;
		 optstats_.glgputime  = optstats_.glgputime  + cast_gputime;

		// release resources
		free(num_rebound);
	
	}	// my_index loop ends
	
	// make histogram of number of detected photons/primary for num_bins
	int binsize=0, newbin=0;
	int bincorr=0;
							
	binsize = floor((max_optphotons-min_optphotons)/num_bins);	// calculate size of each bin. Assuming equally spaced bins.
	bincorr = floor(min_optphotons/binsize);			// correction in bin number if min_optphotons > 0.
			
	for(indexi = 0; indexi < num_primary; indexi++)
	 {
	 	newbin = floor(h_num_detected_prim[indexi]/binsize) - bincorr;	// find bin #
		 	
	 	if(h_num_detected_prim[indexi] > 0)	// store only non-zero bins
	 	{
		 	if(h_num_detected_prim[indexi] <= min_optphotons)	// # detected < minimum photons given by user, add to the first bin
		 		h_histogram[0]++;
		 	else if(h_num_detected_prim[indexi] >= max_optphotons)	// # detected > maximum photons given by user, then add to the last bin
		 		h_histogram[num_bins-1]++;
		 	else
		 		h_histogram[newbin]++; 
		}
	 }
			
	// add num_detected_primary to gldetprimary array in PENELOPE
	for(indexi = 0; indexi < num_bins; indexi++)
		outputdetprim_.gldetprimary[indexi] = outputdetprim_.gldetprimary[indexi] + h_histogram[indexi];
		
	// release resources
	free(structa);
	free(h_num_detected_prim);
	free(h_histogram);

		return;
	}	// C main() ends
Exemplo n.º 18
0
int main(int argc, char *argv[]) {
  clock_t start, stop;
  // Initiate the GSL random number generator
  gsl_rng *rng = gsl_rng_alloc(gsl_rng_taus2);
  gsl_rng_set(rng, time(NULL));

  unsigned int S;
  S = atoi(argv[1]);
  double C;
  C = atof(argv[2]);

  // Pointers to output file
  FILE *splist;

  start = clock();
  // Let's generate three arrays of n, r, and c
  double *n = (double*) malloc(S * sizeof(double));
  double *r = (double*) malloc(S * sizeof(double));
  double *c = (double*) malloc(S * sizeof(double));
  int *pop = (int*) malloc(S * sizeof(int));
  int *K = (int*) malloc(S * sizeof(int));

  // We then generate random values of n
  for (int sp = 0; sp < S; ++sp) {
      n[sp] = gsl_ran_flat (rng, 0.0, 1.0);
      r[sp] = n[sp]*gsl_ran_beta(rng, 1, 1/(2*C)-1);
      c[sp] = gsl_ran_flat(rng, r[sp]/2, n[sp]);
      K[sp] =  gsl_rng_uniform_int(rng, (int) 500 - 500*n[sp])+100;
      pop[sp] =  gsl_rng_uniform_int(rng, (int) K[sp]-10)+10;
  }

  // The species with the smallest n has a r of 0
  double min_n = 1000;
  // We start by getting the min value
  for (int sp = 0; sp > S; ++sp){
      if (n[sp] < min_n){
          min_n = n[sp];
      }
  }

  // Then we update the r value accordingly
  for (int sp = 0; sp < S; ++sp){
      if (n[sp] == min_n){
          r[sp] = 0;
      }
  }

  // Finally we write to a file
  char tfname[FNSIZE];
  snprintf(tfname, sizeof(char) * FNSIZE, "splist.txt");
  splist = fopen(tfname, "w");
  for (int sp = 0; sp < S; ++sp){
      fprintf(splist, "%d %.4f %.4f %.4f %d %d\n", sp+1, n[sp], r[sp], c[sp], K[sp], pop[sp]);
  }
  fclose(splist);

  gsl_rng_free(rng);

  stop = clock();
  printf("%d species, expected connectance of %.2f, generated in %.2f seconds\n", S, C, (stop - start) / (float) CLOCKS_PER_SEC);

  return EXIT_SUCCESS;
}
Exemplo n.º 19
0
void MAIAllocator::Setup() {

//////// initialization of dynamic data structures

  Hmat = gsl_matrix_complex_alloc(N(),M());
  Hchan = gsl_vector_complex_alloc(N());
  Hperm = gsl_matrix_uint_alloc(N(),M());
  p = gsl_permutation_alloc(N());
  huserabs = gsl_vector_alloc(N());
  nextcarr = gsl_vector_uint_alloc(M());
  usedcarr = gsl_vector_uint_alloc(N());
  errs = gsl_vector_uint_alloc(M());
  habs = gsl_matrix_alloc(N(),M());
  huu = gsl_matrix_complex_alloc(N(),M());

  framecount = 0;
  ericount = 0;
  csicount = 0;
  noDecisions = 0;
  ostringstream cmd;

  //
  // time
  //
  time(&reporttime);

  //
  // Random Generator
  //
  ran = gsl_rng_alloc( gsl_rng_default );

  // SIGNATURE FREQUENCIES INITIAL SETUP

  signature_frequencies = gsl_matrix_uint_alloc(M(),J());
  signature_frequencies_init = gsl_matrix_uint_alloc(M(),J());
  signature_powers = gsl_matrix_alloc(M(),J());


  for (int i=0; i<M(); i++)
    for (int j=0; j<J(); j++)
      gsl_matrix_uint_set(signature_frequencies_init,i,j,(j*M()+i) % N());

  //
  // INITIAL ALLOCATION
  //
  gsl_matrix_uint_memcpy(signature_frequencies,
			 signature_frequencies_init);

  // maximum initial powers for all carriers
  gsl_matrix_set_all(signature_powers,INIT_CARR_POWER); 

  gsl_vector_uint_set_zero(errs);


  //
  //
  //  FFT Transform Matrix
  //  
  // 
  transform_mat = gsl_matrix_complex_calloc(N(),N());
  double fftarg=-2.0*double(M_PI/N());
  double fftamp=1.0/sqrt(double(N()));

  for (int i=0; i<N(); i++)
    for (int j=0; j<N(); j++)
      gsl_matrix_complex_set(transform_mat,i,j,
			     gsl_complex_polar(fftamp,fftarg*i*j) );



  switch (Mode()) {
  case 0:
    cout << BlockName << " - Allocator type FIXED_ALLOCATION selected" << endl;
    break;
  case 1:
    cout << BlockName << " - Allocator type GIVE_BEST_CARR selected" << endl;
    break;
  case 2:
    cout << BlockName << " - Allocator type SWAP_BAD_GOOD selected" << endl;
    break;
  case 3:
    cout << BlockName << " - Allocator type BEST_OVERLAP selected" << endl;
    break;
  case 4:
    cout << BlockName << " - Allocator type SOAR_AI selected" << endl;

    //
    // SOAR INITIALIZATION
    //
    max_errors = MAX_ERROR_RATE * ERROR_REPORT_INTERVAL * Nb() * K();
    cout << BlockName << " - Max errors tuned to " << max_errors << " errors/frame." << endl;

    //
    // first we initialize the vectors and matrices
    // in the order of appearance in the header file.
    //
    umapUserVec =  vector < Identifier * > (M());
    umapUserUidVec = vector < IntElement * > (M());
    umapUserErrsVec = vector < IntElement * > (M());
    umapUserPowerVec = vector < FloatElement * > (M());
    umapUserCarrMat  = vector < Identifier * > (M()*J());
    umapUserCarrCidMat = vector < IntElement * > (M()*J());
    umapUserCarrPowerMat = vector < FloatElement * > (M()*J());
    
    chansCoeffMat = vector < Identifier * > (M()*N());
    chansCoeffUserMat = vector < IntElement * > (M()*N());
    chansCoeffCarrMat = vector < IntElement * > (M()*N());
    chansCoeffValueMat = vector < FloatElement * > (M()*N());
    
    carmapCarrVec = vector < Identifier * >  (N());
    carmapCarrCidVec = vector < IntElement * >   (N());
    

    //
    // then we create an instance of the Soar kernel in our process
    //

    pKernel = Kernel::CreateKernelInNewThread() ;
    //pKernel = Kernel::CreateRemoteConnection() ;
    
    // Check that nothing went wrong.  We will always get back a kernel object
    // even if something went wrong and we have to abort.
    if (pKernel->HadError())
      {
	cerr << BlockName << ".SOAR - " 
	     << pKernel->GetLastErrorDescription() << endl ;
	exit(1);
      }
    
    // We check if an agent has been prevoiusly created, otherwise we create it 
    // NOTE: We don't delete the agent pointer.  It's owned by the kernel
    pAgent = pKernel->GetAgent("AIAllocator") ;
    if (! pKernel->IsAgentValid(pAgent)) {
      pAgent = pKernel->CreateAgent("AIAllocator") ;
    }
    
    
    // Check that nothing went wrong
    // NOTE: No agent gets created if there's a problem, so we have to check for
    // errors through the kernel object.
    if (pKernel->HadError())
      {
	cerr << BlockName << ".SOAR - " << pKernel->GetLastErrorDescription() << endl ;
	exit(1);
      }
    
    //
    // load productions
    //
    pAgent->LoadProductions(SoarFn());

    // spawn debugger
#ifdef SPAWN_DEBUGGER
    pAgent->SpawnDebugger();
#endif
    
    // Check that nothing went wrong
    // NOTE: No agent gets created if there's a problem, so we have to check for
    // errors through the kernel object.
    if (pKernel->HadError())
      {
	cerr << BlockName << ".SOAR - " 
	     << pKernel->GetLastErrorDescription() << endl ;
	exit(1);
      }

    // keypress 
    //cout << "pause maillocator:203 ... (press ENTER key)" << endl;
    //cin.ignore();

    //
    // we can now generate initial input link structure
    //

    // NO MORE adjust max-nil-output-cycle
    //cmd << "max-nil-output-cycles " << 120;
    //pAgent->ExecuteCommandLine(cmd.str().c_str());

    // the input-link
    pInputLink = pAgent->GetInputLink();

    // input-time
    input_time = 0;
    inputTime = pAgent->CreateIntWME(pInputLink,"input-time",input_time);

    // the usrmap structure (common wmes)
    umap = pAgent->CreateIdWME(pInputLink,"usrmap");

    // BITS_PER_REPORT = ERROR_REPORT_INTERVAL * Nb() * K()
    // MAX_ERRORS = MAX_ERROR_RATE * BITS_PER_REPORT
    umapMaxerr = pAgent->CreateIntWME(umap,"maxerr",max_errors);
    umapPstep = pAgent->CreateFloatWME(umap,"pstep",POWER_STEP);
    umapPmax = pAgent->CreateFloatWME(umap,"pmax",MAX_POWER);
    // the channels
    chans = pAgent->CreateIdWME(pInputLink,"channels");
    // the carmap
    carmap = pAgent->CreateIdWME(pInputLink,"carmap");
 
    // the usrmap structure (users substructure)
    for (int i=0;i<M();i++) { // user loop
      umapUserVec[i] = pAgent->CreateIdWME(umap,"user");
      umapUserUidVec[i] = pAgent->CreateIntWME(umapUserVec[i],"uid",i);
      umapUserErrsVec[i] = pAgent->CreateIntWME(umapUserVec[i],"errs",int(0));
      umapUserPowerVec[i] = pAgent->CreateFloatWME(umapUserVec[i],"power",J());
      // update the current allocation 
      for (int j=0;j<J();j++) { // allocated carriers loop
	unsigned int usedcarr = gsl_matrix_uint_get(signature_frequencies,i,j);
	double usedpow = gsl_matrix_get(signature_powers,i,j);
	umapUserCarrMat[i*J()+j] = pAgent->CreateIdWME(umapUserVec[i],"carr");
	umapUserCarrCidMat[i*J()+j] = 
	  pAgent->CreateIntWME(umapUserCarrMat[i*J()+j],"cid",usedcarr);
	umapUserCarrPowerMat[i*J()+j] = 
	  pAgent->CreateFloatWME(umapUserCarrMat[i*J()+j],"power",usedpow);
      } // allocated carriers loop
      // the channels
      for (int j=0;j<N();j++) { // all channels loop
	chansCoeffMat[i*N()+j] = pAgent->CreateIdWME(chans,"coeff");
	chansCoeffUserMat[i*N()+j] = pAgent->CreateIntWME(chansCoeffMat[i*N()+j],"user",i);
	chansCoeffCarrMat[i*N()+j] = pAgent->CreateIntWME(chansCoeffMat[i*N()+j],"carr",j);
	chansCoeffValueMat[i*N()+j] = pAgent->CreateFloatWME(chansCoeffMat[i*N()+j],"value",0.0);	
      } // all channels loop
    } // user loop

    // the carmap structure
    for (int j=0;j<N();j++) { // all carriers loop
	carmapCarrVec[j] = pAgent->CreateIdWME(carmap,"carr");
	carmapCarrCidVec[j] = pAgent->CreateIntWME(carmapCarrVec[j],"cid",j);
      } // all carriers loop
     
    //
    // END OF SOAR INITIALIZAZION
    //
   
    break;  
  default:
    cerr << BlockName << " - Unhandled allocator type !" << endl;
    exit(1);
  }
  

  //////// rate declaration for ports


}
Exemplo n.º 20
0
double fit_n(set_const* Init, double n0){
		const gsl_multifit_fdfsolver_type *T;
		gsl_multifit_fdfsolver *s;
		int status;
		unsigned int i, iter = 0;
		const size_t n = 11;
		const size_t p = 5;
		double k = n0/0.16;
		gsl_matrix *covar = gsl_matrix_alloc (p, p);
		double y[11] = {4.45, 6.45 , 9.65, 13.29, 17.94, 22.92, 27.49, 38.82, 54.95, 75.13, 99.75}; 
		double t[11] = {k*0.02,k*0.04, k*0.08,k*0.12,k*0.16,k*0.2,k*0.24, k*0.32, k*0.4,k*0.48, k*0.56};
		struct data d = { n, y, t, Init};
		gsl_multifit_function_fdf f;
		double x_init[5] = {Init->C_s,Init->C_o, Init->b,Init->c, Init->C_r};

		//double x_init[6]  = {11.56279437,7.49931859,0.00871711,0.00267620,0.86859184,0.5};
		//double x_init[4] = { sqrt(130.746),sqrt(120.7244),1.0,10.0};
		gsl_vector_view x = gsl_vector_view_array (x_init, p);
		const gsl_rng_type * type;
		gsl_rng * r;

		gsl_rng_env_setup();

		type = gsl_rng_default;
		r = gsl_rng_alloc (type);

		f.f = &func_fit_n;
		f.df = NULL;
		f.fdf = NULL;
		f.n = n;
		f.p = p;
		f.params = &d;

		/* This is the data to be fitted */

		/*for (i = 0; i < n; i++)
		{
			double t = i;
			y[i] = 1.0 + 5 * exp (-0.1 * t) 
				+ gsl_ran_gaussian (r, 0.1);
			sigma[i] = 0.1;
			printf ("data: %u %g %g\n", i, y[i], sigma[i]);
		};*/

		T = gsl_multifit_fdfsolver_lmsder;
		
		s = gsl_multifit_fdfsolver_alloc (T, n, p);

		gsl_multifit_fdfsolver_set (s, &f, &x.vector);
	
		print_state (iter, s);

		do
		{
			iter++;
			status = gsl_multifit_fdfsolver_iterate (s);

			//printf ("status = %s\n", gsl_strerror (status));

			print_state (iter, s);

			if (status)
				break;

			status = gsl_multifit_test_delta (s->dx, s->x,
				1e-15, 0.0);
		}
		while (status == GSL_CONTINUE && iter < 2000);

		gsl_multifit_covar (s->J, 0.0, covar);

#define FIT(i) gsl_vector_get(s->x, i)
#define ERR(i) sqrt(gsl_matrix_get(covar,i,i))


		cond(Init, FIT(0), FIT(1), FIT(2), FIT(3), FIT(4));

		{ 
			double chi = gsl_blas_dnrm2(s->f);
			double dof = n - p;
			double c = GSL_MAX_DBL(1, chi / sqrt(dof)); 
			//double c = 1.0;
			/*printf("chisq/dof = %g\n",  pow(chi, 2.0) / dof);

			printf ("Cs      = %.5f +/- %.5f\n", Init->C_s, c*ERR(0));
			printf ("Co = %.5f +/- %.5f\n", Init->C_o, c*ERR(1));
			printf ("b      = %.5f +/- %.5f\n", Init->c, c*ERR(2));
			printf ("c      = %.5f +/- %.5f\n", Init->b, c*ERR(3));
			printf ("Cr      = %.5f +/- %.5f\n", Init->C_r, c*ERR(4));*/
		}
		
	//	printf ("status = %s\n", gsl_strerror (status));
		double z = 0.65;

		
		gsl_matrix_free (covar);
		gsl_rng_free (r);

		double yi = 0;
		/*for (int i = 0; i < 11; i++){
		double yi = EoS::t_E(t[i],0, Init)/(D*t[i]) - m_n ;
		printf("n = %.3f, %.3f  %.3f  %.3f \n",
		t[i],
		yi,
		y[i],
		yi-y[i]);

		}*/
	
		/*return *(new set_const("APR_fit return constant set",FIT(0), FIT(1), 10.0, FIT(2),abs(FIT(3)), z, 
			[](double f){return (1-f);},
			[](double f){return 1.0;},
			[=](double f){return eta_o(f);},
			[](double f){return 1.0;}));*/
		double rr = gsl_blas_dnrm2(s->x);
		gsl_multifit_fdfsolver_free (s);
		return rr;
	}
int initialize() {
  int i;
  
  if(read_from_file) {
    if(noise == 0) {
        read_popdens(1);
        flat_constraint(1.);
    }
    if(noise == 1) {
        read_popdens(1);
        flat_constraint(populationsize);
    }
    if(noise == 2) {
        read_constraint(1);
        read_popdens(0);
    }
    if(noise == 3) {
        read_popdens(1);
        flat_constraint(1.);
        read_timetrace();
    }
  }else{
    if(noise == 0)flat_constraint(1.);
    if(noise == 1)flat_constraint(populationsize);
    if(noise == 2)read_constraint(1);
    if(noise == 3) {
        flat_constraint(1.);
        read_timetrace();
    }
    nn = (double*)calloc(space,sizeof(double));
    initialize_with_gaussian_popdens();
  }
  tmp = (double*)malloc(space*sizeof(double));

  gsl_rng_env_setup();
  T = gsl_rng_default;
  rg = gsl_rng_alloc(T);
  gsl_rng_set(rg, randseed);

  twoepssqrt = sqrt(2.*epsilon);
  speedprefactor = wavespeed/dx*epsilon;
  
  x = (double*)malloc(space*sizeof(double));
  for(i=0;i<space;i++)x[i] = (i-space0)*dx;
  mutation_diff2dx = epsilon*mutationrate/(dx*dx);
  
  if(quiet<2) {
    printf("###############################################################################\n");
    printf("# stochastic simulation of adapting population with diffusion mutation kernel #\n");
    printf("###############################################################################\n");
    printf("#    mutationrate     = %e\n",mutationrate);
    if(noise==0) {
      printf("#    constraint       = deterministic\n");
    }
    if(noise==1) {
      printf("#    constraint       = fixedN\n");
      printf("#    populationsize   = %e\n",populationsize);
    }
    if(noise==2) {
      printf("#    constraint       = ustar\n");
      printf("#    ufile            = %s\n",u_infile);
      printf("#    wavespeed        = %e\n",wavespeed);
    }
    if(noise==3) {
      printf("#    constraint       = fluctN\n");
      printf("#    N trajectory file= %s\n",timetrace_filename);
    }    
    printf("#    (lattice) space  = %d\n",space);
    printf("#    (lattice) space0 = %d\n",space0);
    printf("#    (lattice) dx     = %e\n",dx);
    printf("#    randseed         = %d\n",randseed);
  }

}
Exemplo n.º 22
0
/* Random Number Generation */
void FC_FUNC_(oct_ran_init, OCT_RAN_INIT)
     (gsl_rng **r)
{
  gsl_rng_env_setup();
  *r = gsl_rng_alloc(gsl_rng_default);
}
Exemplo n.º 23
0
int main(void) {
  gsl_matrix *TS; /* the training set of real waveforms */
  gsl_matrix_complex *cTS; /* the training set of complex waveforms */

  size_t TSsize;  /* the size of the training set (number of waveforms) */
  size_t wl;      /* the length of each waveform */
  size_t k = 0, j = 0, i = 0, nbases = 0, cnbases = 0;

  REAL8 *RB = NULL;        /* the real reduced basis set */
  COMPLEX16 *cRB = NULL;   /* the complex reduced basis set */
  LALInferenceREALROQInterpolant *interp = NULL;
  LALInferenceCOMPLEXROQInterpolant *cinterp = NULL;

  gsl_vector *freqs;

  double tolerance = TOLERANCE; /* tolerance for reduced basis generation loop */

  TSsize = TSSIZE;
  wl = WL;

  /* allocate memory for training set */
  TS = gsl_matrix_calloc(TSsize, wl);
  cTS = gsl_matrix_complex_calloc(TSsize, wl);

  /* the waveform model is just a simple chirp so set up chirp mass range for training set */
  double fmin0 = 48, fmax0 = 256, f0 = 0., m0 = 0.;
  double df = (fmax0-fmin0)/(wl-1.); /* model time steps */
  freqs = gsl_vector_alloc(wl); /* times at which to calculate the model */
  double Mcmax = 2., Mcmin = 1.5, Mc = 0.;

  gsl_vector_view fweights = gsl_vector_view_array(&df, 1);

  /* set up training sets (one real and one complex) */
  for ( k=0; k < TSsize; k++ ){
    Mc = pow(pow(Mcmin, 5./3.) + (double)k*(pow(Mcmax, 5./3.)-pow(Mcmin, 5./3.))/((double)TSsize-1), 3./5.);

    for ( j=0; j < wl; j++ ){
      f0 = fmin0 + (double)j*(fmax0-fmin0)/((double)wl-1.);

      gsl_complex gctmp;
      COMPLEX16 ctmp;
      m0 = real_model(f0, Mc);
      ctmp = imag_model(f0, Mc);
      GSL_SET_COMPLEX(&gctmp, creal(ctmp), cimag(ctmp));
      gsl_vector_set(freqs, j, f0);
      gsl_matrix_set(TS, k, j, m0);
      gsl_matrix_complex_set(cTS, k, j, gctmp);
    }
  }

  /* create reduced orthonormal basis from training set */
  if ( (RB = LALInferenceGenerateREAL8OrthonormalBasis(&fweights.vector, tolerance, TS, &nbases)) == NULL){
    fprintf(stderr, "Error... problem producing basis\n");
    return 1;
  }

  if ( (cRB = LALInferenceGenerateCOMPLEX16OrthonormalBasis(&fweights.vector, tolerance, cTS, &cnbases)) == NULL){
    fprintf(stderr, "Error... problem producing basis\n");
    return 1;
  }

  /* free the training set */
  gsl_matrix_free(TS);
  gsl_matrix_complex_free(cTS);

  gsl_matrix_view RBview = gsl_matrix_view_array(RB, nbases, wl);
  gsl_matrix_complex_view cRBview = gsl_matrix_complex_view_array((double*)cRB, cnbases, wl);

  fprintf(stderr, "No. nodes (real)  = %zu, %zu x %zu\n", nbases, RBview.matrix.size1, RBview.matrix.size2);
  fprintf(stderr, "No. nodes (complex)  = %zu, %zu x %zu\n", cnbases, cRBview.matrix.size1, cRBview.matrix.size2);

  /* get the interpolant */
  interp = LALInferenceGenerateREALROQInterpolant(&RBview.matrix);
  cinterp = LALInferenceGenerateCOMPLEXROQInterpolant(&cRBview.matrix);

  /* free the reduced basis */
  XLALFree(RB);
  XLALFree(cRB);

  /* now get the terms for the likelihood with and without the reduced order quadrature
   * and do some timing tests */

  /* create the model dot model weights */
  REAL8 varval = 1.;
  gsl_vector_view vars = gsl_vector_view_array(&varval, 1);

  gsl_matrix *mmw = LALInferenceGenerateREALModelModelWeights(interp->B, &vars.vector);
  gsl_matrix_complex *cmmw = LALInferenceGenerateCOMPLEXModelModelWeights(cinterp->B, &vars.vector);

  /* let's create some Gaussian random data */
  const gsl_rng_type *T;
  gsl_rng *r;

  gsl_rng_env_setup();

  T = gsl_rng_default;
  r = gsl_rng_alloc(T);

  REAL8 *data = XLALCalloc(wl, sizeof(REAL8));
  COMPLEX16 *cdata = XLALCalloc(wl, sizeof(COMPLEX16));
  for ( i=0; i<wl; i++ ){
    data[i] = gsl_ran_gaussian(r, 1.0);                               /* real data */
    cdata[i] = gsl_ran_gaussian(r, 1.0) + I*gsl_ran_gaussian(r, 1.0); /* complex data */
  }

  /* create the data dot model weights */
  gsl_vector_view dataview = gsl_vector_view_array(data, wl);
  gsl_vector *dmw = LALInferenceGenerateREAL8DataModelWeights(interp->B, &dataview.vector, &vars.vector);

  gsl_vector_complex_view cdataview = gsl_vector_complex_view_array((double*)cdata, wl);
  gsl_vector_complex *cdmw = LALInferenceGenerateCOMPLEX16DataModelWeights(cinterp->B, &cdataview.vector, &vars.vector);

  /* pick a chirp mass and generate a model to compare likelihoods */
  double randMc = 1.873; /* a random frequency to create a model */

  gsl_vector *modelfull = gsl_vector_alloc(wl);
  gsl_vector *modelreduced = gsl_vector_alloc(nbases);
  gsl_vector_complex *cmodelfull = gsl_vector_complex_alloc(wl);
  gsl_vector_complex *cmodelreduced = gsl_vector_complex_alloc(cnbases);

  /* create models */
  for ( i=0; i<wl; i++ ){
    /* models at all frequencies */
    gsl_vector_set(modelfull, i, real_model(gsl_vector_get(freqs, i), randMc));

    COMPLEX16 cval = imag_model(gsl_vector_get(freqs, i), randMc);
    gsl_complex gcval;
    GSL_SET_COMPLEX(&gcval, creal(cval), cimag(cval));
    gsl_vector_complex_set(cmodelfull, i, gcval);
  }

  /* models at interpolant nodes */
  for ( i=0; i<nbases; i++ ){ /* real model */
    gsl_vector_set(modelreduced, i, real_model(gsl_vector_get(freqs, interp->nodes[i]), randMc));
  }
  for ( i=0; i<cnbases; i++ ){ /* complex model */
    COMPLEX16 cval = imag_model(gsl_vector_get(freqs, cinterp->nodes[i]), randMc);
    gsl_complex gcval;
    GSL_SET_COMPLEX(&gcval, creal(cval), cimag(cval));
    gsl_vector_complex_set(cmodelreduced, i, gcval);
  }

  /* timing variables */
  struct timeval t1, t2, t3, t4;
  double dt1, dt2;

  /* start with the real model */
  /* get the model model term with the full model */
  REAL8 mmfull, mmred;
  gettimeofday(&t1, NULL);
  XLAL_CALLGSL( gsl_blas_ddot(modelfull, modelfull, &mmfull) );        /* real model */
  gettimeofday(&t2, NULL);

  /* now get it with the reduced order quadrature */
  gettimeofday(&t3, NULL);
  mmred = LALInferenceROQREAL8ModelDotModel(mmw, modelreduced);
  gettimeofday(&t4, NULL);

  dt1 = (double)((t2.tv_sec + t2.tv_usec*1.e-6) - (t1.tv_sec + t1.tv_usec*1.e-6));
  dt2 = (double)((t4.tv_sec + t4.tv_usec*1.e-6) - (t3.tv_sec + t3.tv_usec*1.e-6));
  fprintf(stderr, "Real Signal:\n - M dot M (full) = %le [%.9lf s], M dot M (reduced) = %le [%.9lf s], time ratio = %lf\n", mmfull, dt1, mmred, dt2, dt1/dt2);

  /* get the data model term with the full model */
  REAL8 dmfull, dmred;
  gettimeofday(&t1, NULL);
  XLAL_CALLGSL( gsl_blas_ddot(&dataview.vector, modelfull, &dmfull) );
  gettimeofday(&t2, NULL);

  /* now get it with the reduced order quadrature */
  gettimeofday(&t3, NULL);
  dmred = LALInferenceROQREAL8DataDotModel(dmw, modelreduced);
  gettimeofday(&t4, NULL);

  dt1 = (double)((t2.tv_sec + t2.tv_usec*1.e-6) - (t1.tv_sec + t1.tv_usec*1.e-6));
  dt2 = (double)((t4.tv_sec + t4.tv_usec*1.e-6) - (t3.tv_sec + t3.tv_usec*1.e-6));
  fprintf(stderr, " - D dot M (full) = %le [%.9lf s], D dot M (reduced) = %le [%.9lf s], time ratio = %lf\n", dmfull, dt1, dmred, dt2, dt1/dt2);

  /* check difference in log likelihoods */
  double Lfull, Lred, Lfrac;

  Lfull = mmfull - 2.*dmfull;
  Lred = mmred - 2.*dmred;
  Lfrac = 100.*fabs(Lfull-Lred)/fabs(Lfull); /* fractional log likelihood difference (in %) */

  fprintf(stderr, " - Fractional difference in log likelihoods = %lf%%\n", Lfrac);

  XLALFree(data);
  gsl_vector_free(modelfull);
  gsl_vector_free(modelreduced);
  gsl_matrix_free(mmw);
  gsl_vector_free(dmw);

  /* check log likelihood difference is within tolerance */
  if ( Lfrac > LTOL ) { return 1; }

  /* now do the same with the complex model */
  /* get the model model term with the full model */
  COMPLEX16 cmmred, cmmfull;
  gsl_complex cmmfulltmp;
  gettimeofday(&t1, NULL);
  XLAL_CALLGSL( gsl_blas_zdotc(cmodelfull, cmodelfull, &cmmfulltmp) ); /* complex model */
  cmmfull = GSL_REAL(cmmfulltmp) + I*GSL_IMAG(cmmfulltmp);
  gettimeofday(&t2, NULL);

  gettimeofday(&t3, NULL);
  cmmred = LALInferenceROQCOMPLEX16ModelDotModel(cmmw, cmodelreduced);
  gettimeofday(&t4, NULL);

  dt1 = (double)((t2.tv_sec + t2.tv_usec*1.e-6) - (t1.tv_sec + t1.tv_usec*1.e-6));
  dt2 = (double)((t4.tv_sec + t4.tv_usec*1.e-6) - (t3.tv_sec + t3.tv_usec*1.e-6));
  fprintf(stderr, "Complex Signal:\n - M dot M (full) = %le [%.9lf s], M dot M (reduced) = %le [%.9lf s], time ratio = %lf\n", creal(cmmfull), dt1, creal(cmmred), dt2, dt1/dt2);

  COMPLEX16 cdmfull, cdmred;
  gsl_complex cdmfulltmp;
  gettimeofday(&t1, NULL);
  XLAL_CALLGSL( gsl_blas_zdotc(&cdataview.vector, cmodelfull, &cdmfulltmp) );
  cdmfull = GSL_REAL(cdmfulltmp) + I*GSL_IMAG(cdmfulltmp);
  gettimeofday(&t2, NULL);

  gettimeofday(&t3, NULL);
  cdmred = LALInferenceROQCOMPLEX16DataDotModel(cdmw, cmodelreduced);
  gettimeofday(&t4, NULL);

  dt1 = (double)((t2.tv_sec + t2.tv_usec*1.e-6) - (t1.tv_sec + t1.tv_usec*1.e-6));
  dt2 = (double)((t4.tv_sec + t4.tv_usec*1.e-6) - (t3.tv_sec + t3.tv_usec*1.e-6));
  fprintf(stderr, " - D dot M (full) = %le [%.9lf s], D dot M (reduced) = %le [%.9lf s], time ratio = %lf\n", creal(cdmfull), dt1, creal(cdmred), dt2, dt1/dt2);

  /* check difference in log likelihoods */
  Lfull = creal(cmmfull) - 2.*creal(cdmfull);
  Lred = creal(cmmred) - 2.*creal(cdmred);
  Lfrac = 100.*fabs(Lfull-Lred)/fabs(Lfull); /* fractional log likelihood difference (in %) */

  fprintf(stderr, " - Fractional difference in log likelihoods = %lf%%\n", Lfrac);

  XLALFree(cdata);
  gsl_vector_complex_free(cmodelfull);
  gsl_vector_complex_free(cmodelreduced);
  gsl_matrix_complex_free(cmmw);
  gsl_vector_complex_free(cdmw);
  LALInferenceRemoveREALROQInterpolant( interp );
  LALInferenceRemoveCOMPLEXROQInterpolant( cinterp );

  /* check log likelihood difference is within tolerance */
  if ( Lfrac > LTOL ) { return 1; }

  return 0;
}
Exemplo n.º 24
0
static void uvag_set (void *vstate, unsigned long int s) {

 /* Initialize automaton using specified seed. */
 uvag_state_t *state = (uvag_state_t *) vstate;
 
 uint i, array_len = 255 + WORD, tot, seed_seed, tmp8;
 unsigned char key[256], *kp, temp;
 gsl_rng *seed_rng;    /* random number generator used to seed uvag */

 /*
  * Preload the array with 1-byte integers
  */
 for (i=0; i<array_len; i++){
   svec[i]=i;
 }

 /*
  * OK, here we have to modify Alex's algorithm.  The GSL requires a
  * single seed, unsigned long int in type.  Alex requires a key string
  * 256 characters long (that is, 64 uints long).  We therefore have to
  * bootstrap off of an existing, deterministic GSL RNG to fill the seed
  * string from a single permitted seed.  Note that type 12 is the
  * mt19937_1999 generator, basically one of the best in the world -- not
  * that it matters.
  */
 seed_rng = gsl_rng_alloc(dh_rng_types[14]);
 seed_seed = s;
 gsl_rng_set(seed_rng,seed_seed);
 random_max = gsl_rng_max(seed_rng);
 rmax = random_max;
 rmax_bits = 0;
 rmax_mask = 0;
 while(rmax){
   rmax >>= 1;
   rmax_mask = rmax_mask << 1;
   rmax_mask++;
   rmax_bits++;
 }
 for(i=0;i<256;i++){
   /* if(i%32 == 0) printf("\n"); */
   get_rand_bits(&tmp8,sizeof(uint),8,seed_rng);
   if(i!=255){
     key[i] = tmp8;
   } else {
     key[i] = 0;
   }
   /* printf("%02x",key[i]); */
 }
 /* printf("\n"); */

 kp = key;
 tot = 0;
 for(i=0; i<array_len; i++) {        /* shuffle seeds */
   tot += *kp++;
   tot%=array_len;
   temp = svec[tot];
   svec[tot] = svec[i];
   svec[i] = temp;
   /* wrap around key[] */
   if(*kp == '\0') {
     kp = key;
   }
 }
/* For debugging of the original load'n'shuffle
 printf("svec = ");
 for(i=0;i<256;i++){
   if(i%32 == 0) printf("\n");
   printf("%02x|",svec[i]);
 }
 printf("\n");
 */

 sindex = 0;
 rndint = 0;

}
/*Numero de objetos sin leer en el subcatalogo:  N*/
int LAE_catalog_generator(int model,int N_laes,double mass[],double x[],double y[],double z[],double *mass_min,double halo_m_dev,int *N,int *T,double *mass_max,double *duty_cycle,double x_cat[],double y_cat[],double z_cat[],int *catalog)
{
   //1-DECLARA
   const gsl_rng_type *tipo;
  gsl_rng *generador;
  
  //2-ALOCA E INICIALIZA
  tipo=gsl_rng_mt19937;
  generador=gsl_rng_alloc(tipo);
  gsl_rng_set(generador,time(NULL));   
  int rand;
  int k,l;
  double exp_mass_min;
  double mass1;
  l=1;
  while( mass[*N-l]<=*mass_min)
    {
      l++;
    }
  
  *mass_min=mass[*N-l];
  exp_mass_min=pow(10,*mass_min);
  *N=*N-l;

  *T=*N;		
  //printf("N=%d \n",*N);
  if(*N-N_laes>0)
    { 
      // printf("N-N_LAES>0, m_min=%lf m_max=%lf \n",*mass_min,*mass_max);
      *catalog=1;
      if(model==0)
	{
	  printf("model=0 \n");
	  if( ( pow(10,mass[*N-N_laes]) - exp_mass_min  ) <= halo_m_dev )
	    {	  
	      *mass_max=log10( exp_mass_min + halo_m_dev );	  
	    }
	  else
	    {
	      *mass_max=mass[*N-N_laes]; 
	    }
	  l=1;			  
	  
	  while( mass[*T-l]<=(*mass_max) )
	    {
	      l++;
	    }
	  
	  for(k=0;k<N_laes;k++)
	    {
	      rand=gsl_rng_uniform_int(generador, l );
	      x_cat[k]=x[*N-rand];
	      y_cat[k]=y[*N-rand];
	      z_cat[k]=z[*N-rand];
	    }
	  
	  *duty_cycle=((double)N_laes)/((double)l);
	}
      if(model==1)
	{
	  //printf("model=1 \n");
	  l=1;
	  *duty_cycle=2;	
	  //k=0;
	  while( mass[*T-l]<=(*mass_max) )
	    {
	      l++;
	    }
	  
	  *duty_cycle=((double)N_laes)/((double)l);	  
	  if(*duty_cycle>1.0) *catalog=0;
	  //*mass_max+=k*0.1;
	  //k++;
	}
      //printf("l=%d \n",l);
      
      for(k=0;k<N_laes;k++)
	    {
	      rand=gsl_rng_uniform_int(generador, l );
	      //printf("x[N-rand]=%lf y[N-rand]=%lf z[N-rand]=%lf \n",x[*N-rand],y[*N-rand],z[*N-rand]);
	      //printf("rand=%d \n",rand);
	      x_cat[k]=x[*N-rand];
	      //printf("x[N-l]=%lf  \n",x[*N-rand]);
	      y_cat[k]=y[*N-rand];
	      //printf("y[N-l]=%lf  \n",y[*N-rand]);
	      z_cat[k]=z[*N-rand];
	      //printf("x[N-l]=%lf y[N-l]=%lf z[N-l]=%lf \n",x[*N-rand],y[*N-rand],z[*N-rand]);
	    }
      // printf("x[N-l]=%lf y[N-l]=%lf z[N-l]=%lf \n",x[*N-l],y[*N-l],z[*N-l]);
      *duty_cycle=((double)N_laes)/((double)l);	  
	  //printf("duty_cycle=%lf \n",*duty_cycle);
    
    }else{*catalog=0;}
  //  printf("saliendo \n");
  return 0;
}
Exemplo n.º 26
0
void  smf_fillgaps( ThrWorkForce *wf, smfData *data,
                    smf_qual_t mask, int *status ) {

/* Local Variables */
  const gsl_rng_type *type;     /* GSL random number generator type */
  dim_t bpt;                    /* Number of bolos per thread */
  dim_t i;                      /* Bolometer index */
  dim_t nbolo;                  /* Number of bolos */
  dim_t ntslice;                /* Number of time slices */
  double *dat=NULL;             /* Pointer to bolo data */
  int fillpad;                  /* Fill PAD samples? */
  size_t bstride;               /* bolo stride */
  size_t pend;                  /* Last non-PAD sample */
  size_t pstart;                /* First non-PAD sample */
  size_t tstride;               /* time slice stride */
  smfFillGapsData *job_data;    /* Structures holding data for worker threads */
  smfFillGapsData *pdata;       /* Pointer to data for next worker thread */
  smf_qual_t *qua=NULL;         /* Pointer to quality array */

/* Main routine */
  if (*status != SAI__OK) return;

/* Check we have double precision data floating point data. */
  if (!smf_dtype_check_fatal( data, NULL, SMF__DOUBLE, status )) return;

/* Pointers to data and quality */
  dat = data->pntr[0];
  qua = smf_select_qualpntr( data, NULL, status );

  if( !qua ) {
    *status = SAI__ERROR;
    errRep( "", FUNC_NAME ": No valid QUALITY array was provided", status );
    return;
  }

  if( !dat ) {
    *status = SAI__ERROR;
    errRep( "", FUNC_NAME ": smfData does not contain a DATA component",status);
    return;
  }

 /* obtain data dimensions */
  smf_get_dims( data,  NULL, NULL, &nbolo, &ntslice, NULL, &bstride, &tstride,
                status );

  /* Determine how many bolometers to process in each thread, and create
     the structures used to pass data to the threads. */
  if( wf ) {
     bpt = nbolo/wf->nworker;
     if( wf->nworker*bpt < nbolo ) bpt++;
     job_data = astMalloc( sizeof( smfFillGapsData )*wf->nworker );
  } else {
     bpt = nbolo;
     job_data = astMalloc( sizeof( smfFillGapsData ) );
  }

  /* Find the indices of the first and last non-PAD sample. */
  smf_get_goodrange( qua, ntslice, tstride, SMF__Q_PAD, &pstart, &pend,
                     status );

  /* Report an error if it is too short. */
  if( pend - pstart <= 2*BOX && *status == SAI__OK ) {
    *status = SAI__ERROR;
    errRepf( "", FUNC_NAME ": length of data (%d samples) is too small "
             "to fill gaps. Must have at least %d samples per bolometer.",
             status, (int) ( pend - pstart ), 2*BOX + 1 );
  }

  /* If the supplied "mask" value includes SMF__Q_PAD, then we will be
  replacing the zero-padded region at the start and end of each time series
  with artificial noisey data that connects the first and last data values
  smoothly. Remove SMF__Q_PAD from the mask. */
  if( mask & SMF__Q_PAD ) {
     mask &= ~SMF__Q_PAD;
     fillpad = 1;
  } else {
     fillpad = 0;
  }

  /* Get the default GSL randim number generator type. A separate random
     number generator is used for each worker thread so that the gap filling
     process does not depend on the the order in which threads are
     executed. */
  type = gsl_rng_default;

  /* Begin a job context. */
  thrBeginJobContext( wf, status );

  /* Loop over bolometer in groups of "bpt". */
  pdata = job_data;
  for( i = 0; i < nbolo; i += bpt, pdata++ ) {

    /* Store information for this group in the  next smfFillGapsData
       structure. */
    pdata->ntslice = ntslice;
    pdata->dat = dat;
    pdata->r = gsl_rng_alloc( type );
    pdata->b1 = i;
    pdata->b2 = i + bpt - 1;
    pdata->pend = pend;
    pdata->fillpad = fillpad;
    pdata->pstart = pstart;
    if( pdata->b2 >= nbolo ) pdata->b2 = nbolo - 1;
    pdata->bstride = bstride;
    pdata->tstride = tstride;
    pdata->qua = qua;
    pdata->mask = mask;

    /* Submit a job to the workforce to process this group of bolometers. */
    (void) thrAddJob( wf, 0, pdata, smfFillGapsParallel, 0, NULL, status );
  }

  /* Wait until all jobs in the current job context have completed, and
     then end the job context. */
  thrWait( wf, status );
  thrEndJobContext( wf, status );

  /* Free resources. */
  if( job_data ) {
    pdata = job_data;
    for( i = 0; i < nbolo; i += bpt, pdata++ ) {
      if( pdata->r ) gsl_rng_free( pdata->r );
    }
    job_data = astFree( job_data );
  }
}
Exemplo n.º 27
0
int main(int argc, char* argv[]) {
	// Initialisation
	argp_parse(&argp, argc, argv, 0, 0, 0);
	
	init_globals();
	
	if(! wsinit() ) {
		fprintf(stderr, "Could not allocate grammar workspace\n");
		return 1;
	}
	
	gsl_rng* rng = gsl_rng_alloc( gsl_rng_env_setup() );
	if(!rng) {
		fprintf(stderr, "Could not create rng\n");
		return 1;
	}

	// Create a set of grammars according to desired initial condition
	grammar_t grammars[agents];
	for(unsigned a=0; a<agents; a++) {
		if(! (grammars[a] = ginit()) ) {
			fprintf(stderr, "Could not create grammar\n");
		}
		switch(initial_condition) {
		case ic_random:
	 		randomise_associations(grammars[a], rng);
	 		break;
	 	case ic_identity:
			identity_associations(grammars[a]);
			break;
		case ic_rook:
			rook_associations(grammars[a], rng);
			break;
		default:
			fprintf(stderr, "Unknown initial condition\n");
			return 1;
		}
		renew_pseudo_associations(grammars[a]);
	}
	
	// Print out initial coherence matrix
	printf("coherence agents=%u round=0\n", agents);
	for(unsigned a1=0; a1<agents; a1++) {
		for(unsigned a2=0; a2<agents; a2++) {
			printf("%g ", coherence(grammars[a1], grammars[a2]));
		}
		printf("\n");
	}
	printf("\n");

	unsigned interactions_per_round = agents * meanings * signals;
	
	for(unsigned t=0;t<rounds*interactions_per_round;t++) {

		// Update loop starts here

		// 1. Choose a pair of speakers
		unsigned a1 = gsl_rng_uniform_int(rng, agents);
		unsigned a2 = gsl_rng_uniform_int(rng, agents-1);
		if (a2 >= a1) a2++;
		
		// 2. Speaker selects a topic
		meaning_t m1 = sample_meaning(grammars[a1], rng);
		
		// 3. Speaker produces a signal for m
		signal_t s = produce_signal(grammars[a1], m1, rng);
		
		// 4. Listener infers a meaning
		meaning_t m2 = infer_meaning(grammars[a2], s, rng);
		
		// 5. Obtain feedback
		double fb = feedback > 0.0 ? stochastic_feedback(m1,m2,rng) : deterministic_feedback(m1,m2);
				
		// 6. Update grammars
		vary_association(grammars[a1], m1, s, fb*stepsize );
		vary_association(grammars[a2], m2, s, fb*stepsize );
	
		renew_pseudo_associations(grammars[a1]);
		renew_pseudo_associations(grammars[a2]);

		// Update loop ends here
		
		// Print out the coherence matrix at the end of each rounds		
		if((t+1) % interactions_per_round == 0) {
			printf("coherence agents=%u round=%u\n", agents, (t+1)/interactions_per_round);
			for(unsigned a1=0; a1<agents; a1++) {
				for(unsigned a2=0; a2<agents; a2++) {
					printf("%g ", coherence(grammars[a1], grammars[a2]));
				}
				printf("\n");
			}
			printf("\n");
		}
	}
	
	// Print out grammars at the end
	for(unsigned a=0; a<agents; a++) {
		printf("grammar agent=%u meanings=%u signals=%u round=%u\n", a, meanings, signals, rounds);
		for(meaning_t m=0; m<meanings; m++) {
			for(signal_t s=0;s<signals; s++) {
				printf("%g ", get_association(grammars[a], m, s));
			}
			printf("\n");
		}
		printf("\n");
	}

	// Print out pseudo grammars at the end
	for(unsigned a=0; a<agents; a++) {
		printf("pseudo agent=%u meanings=%u signals=%u round=%u\n", a, meanings, signals, rounds);
		for(meaning_t m=0; m<meanings; m++) {
			for(signal_t s=0;s<signals; s++) {
				printf("%g ", get_pseudo_association(grammars[a], m, s));
			}
			printf("\n");
		}
		printf("\n");
	}

	
	return 0;
}
Exemplo n.º 28
0
int main()
{
  // ----------------------------------------------------------------
  // Initialize the random number generator
  // ----------------------------------------------------------------
  gsl_rng *rand_gen;
  rand_gen = gsl_rng_alloc(gsl_rng_mt19937);
  gsl_rng_set(rand_gen, seed);

  // ----------------------------------------------------------------
  // Build the network---only use giant component
  // ----------------------------------------------------------------
  struct node_gra *total_net = NULL;
  struct node_gra *net = NULL;
  FILE *infile;

  infile = fopen("test.dat", "r");
  total_net = FBuildNetwork(infile, 0, 0, 0, 1);
  fclose(infile);
  net = GetLargestStronglyConnectedSet(total_net, 100000);

  // ----------------------------------------------------------------
  // Initialize the coclassification matrix
  // ----------------------------------------------------------------
  int i, j;
  int **coclas;
  int S = CountNodes(net);
  coclas = allocate_i_mat(S, S);
  for (i=0; i<S; i++)
    for (j=0; j<S; j++)
      coclas[i][j] = 0;

  // ----------------------------------------------------------------
  // Find the modules rep times and calculate coclassification matrix
  // ----------------------------------------------------------------
  struct group *part = NULL;
  struct node_gra *p1 = NULL;
  struct node_gra *p2 = NULL;
  for (i=0; i<rep; i++) {
    fprintf(stderr, "Repetition %d\n", i+1);
    part = SACommunityIdent(net,
			    0.0, -1.0, 0.0,
			    0.10,
			    S,         // #modules
			    'r',       // r=random initial conf
			    1,         // 0=No collective moves
			    'n',       // n=no output
			    rand_gen);
   
    // Update coclas matrix
    // --------------------------------------------------------------
    p1 = net;
    while ((p1 = p1->next) != NULL) {
      p2 = net;
      while ((p2 = p2->next) != NULL) {
	if (p1->inGroup == p2->inGroup)
	  coclas[p1->num][p2->num] += 1;
      }
    }

    // Remove the partition
    // --------------------------------------------------------------
    RemovePartition(part);
    part = NULL;
  }

  // ----------------------------------------------------------------
  // Output results
  // ----------------------------------------------------------------
  p1 = net;
  while ((p1 = p1->next) != NULL) {
    p2 = net;
    while ((p2 = p2->next) != NULL) {
      fprintf(stdout, "%s %s -1 -1 -1 -1 %lf\n",
	      p1->label, p2->label,
	      (double)coclas[p1->num][p2->num] / (double)rep);
    }
  }

  // ----------------------------------------------------------------
  // Free memory
  // ----------------------------------------------------------------
  RemoveGraph(total_net);
  RemoveGraph(net);
  free_i_mat(coclas,S);
  gsl_rng_free(rand_gen);

  return 0;
}
Exemplo n.º 29
0
    GammaDistributionFitter::GammaDistributionFitResult GammaDistributionFitter::fit(vector<DPosition<2> > & input)
    {
      const gsl_multifit_fdfsolver_type * T = NULL;
      gsl_multifit_fdfsolver * s = NULL;

      int status = 0;
      size_t iter = 0;

      const size_t p = 2;

      gsl_multifit_function_fdf f;
      double x_init[2] = { init_param_.b, init_param_.p };
      gsl_vector_view x = gsl_vector_view_array(x_init, p);
      const gsl_rng_type * type = NULL;
      gsl_rng * r = NULL;

      gsl_rng_env_setup();

      type = gsl_rng_default;
      r = gsl_rng_alloc(type);

      f.f = &gammaDistributionFitterf_;
      f.df = &gammaDistributionFitterdf_;
      f.fdf = &gammaDistributionFitterfdf_;
      f.n = input.size();
      f.p = p;
      f.params = &input;

      T = gsl_multifit_fdfsolver_lmsder;
      s = gsl_multifit_fdfsolver_alloc(T, input.size(), p);
      gsl_multifit_fdfsolver_set(s, &f, &x.vector);

#ifdef GAMMA_DISTRIBUTION_FITTER_VERBOSE
      printState_(iter, s);
#endif

      do
      {
        ++iter;
        status = gsl_multifit_fdfsolver_iterate(s);

#ifdef GAMMA_DISTRIBUTION_FITTER_VERBOSE
        printf("status = %s\n", gsl_strerror(status));
        printState_(iter, s);
#endif

        if (status)
        {
          break;
        }

        status = gsl_multifit_test_delta(s->dx, s->x, 1e-4, 1e-4);
#ifdef GAMMA_DISTRIBUTION_FITTER_VERBOSE
        printf("Status = '%s'\n", gsl_strerror(status));
#endif
      }
      while (status == GSL_CONTINUE && iter < 1000);

#ifdef GAMMA_DISTRIBUTION_FITTER_VERBOSE
      printf("Final status = '%s'\n", gsl_strerror(status));
#endif

      if (status != GSL_SUCCESS)
      {
        gsl_rng_free(r);
        gsl_multifit_fdfsolver_free(s);

        throw Exception::UnableToFit(__FILE__, __LINE__, __PRETTY_FUNCTION__, "UnableToFit-GammaDistributionFitter", "Could not fit the gamma distribution to the data");
      }

      // write the result in a GammaDistributionFitResult struct
      GammaDistributionFitResult result;
      result.b = gsl_vector_get(s->x, 0);
      result.p = gsl_vector_get(s->x, 1);

      // build a formula with the fitted parameters for gnuplot
      stringstream formula;
      formula << "f(x)=" << "(" << result.b << " ** " << result.p << ") / gamma(" << result.p << ") * x ** (" << result.p << " - 1) * exp(- " << result.b << " * x)";
      gnuplot_formula_ = formula.str();

#ifdef GAMMA_DISTRIBUTION_FITTER_VERBOSE
      cout << gnuplot_formula_ << endl;
#endif

      gsl_rng_free(r);
      gsl_multifit_fdfsolver_free(s);

      return result;
    }
Exemplo n.º 30
0
npRandom::npRandom(unsigned long int seed) {
	  ran = gsl_rng_alloc(gsl_rng_mt19937);
	  gsl_rng_set(ran, seed);
}