Ejemplo n.º 1
0
int lua_random_seed(lua_State *L) {
	RandomLib::Random *s = Glue<RandomLib::Random>::checkto(L, 1);
	if(lua::is<RandomLib::RandomSeed::seed_type>(L, 2)) {
		RandomLib::RandomSeed::seed_type seed = lua::to<RandomLib::RandomSeed::seed_type>(L, 2);
		s->Reseed(seed);
	}
	else {
		luaL_error(L, "Random.seed: invalid arguments");
	}
	return 0;
}
Ejemplo n.º 2
0
int main(int, char**) {
  RandomLib::Random r; r.Reseed();
#if HAVE_LAMBDA
  std::cout << "Illustrate calling STL routines with lambda expressions\n";
#else
  std::cout << "Illustrate calling STL routines without lambda expressions\n";
#endif
  std::cout << "Using " << r.Name() << "\n"
            << "with seed " << r.SeedString() << "\n\n";

  std::vector<unsigned> c(10);  // Fill with unsigned in [0, 2^32)
#if HAVE_LAMBDA
  std::generate(c.begin(), c.end(),
                [&r]() throw() -> unsigned { return r(); });
#else
  std::generate<std::vector<unsigned>::iterator, RandomLib::Random&>
    (c.begin(), c.end(), r);
#endif

  std::vector<double> b(10);    // Fill with normal deviates
#if HAVE_LAMBDA
  RandomLib::NormalDistribution<> nf;
  std::generate(b.begin(), b.end(),
                [&r, &nf]() throw() -> double
                { return nf(r,0.0,2.0); });
#else
  std::generate(b.begin(), b.end(), RandomNormal<>(r,0.0,2.0));
#endif

  std::vector<int> a(20);  // How to shuffle large vectors
#if HAVE_LAMBDA
  int i = 0;
  std::generate(a.begin(), a.end(),
                [&i]() throw() -> int { return i++; });
  std::random_shuffle(a.begin(), a.end(),
                      [&r](unsigned long long n) throw() -> unsigned long long
                      { return r.Integer<unsigned long long>(n); });
#else
  for (size_t i = 0; i < a.size(); ++i) a[i] = int(i);
  RandomInt<unsigned long long> shuffler(r);
  std::random_shuffle(a.begin(), a.end(), shuffler);
#endif

  return 0;
}
Ejemplo n.º 3
0
/**** GLOBAL ****/
void Common::seedRNG() {
    QMutexLocker lock(&rngLock);

    static bool seeded = false;
    if (!seeded) {
        srand(0); // We seed with 0 instead of time(NULL) to have reproducible randomness
        seeded = true;
        g_rand.Reseed(0);
    }
}
Ejemplo n.º 4
0
void NS_move(float* Matrix, float** ptrk, std::vector<Coordinates>& chain, std::vector<Coordinates>& chain_trial, std::vector<int*>& k_array, std::vector<int*>& p_array, std::vector<int>& ruffle, RandomLib::Random& r, Lattice lattice, int chain_length)
{
  int rand, l;
  int intersection = 1;
  bool success = false;
  std::vector<Coordinates>::const_iterator itc;
  
  while (intersection == 1)
    {
      rand = r.Integer(2);
      
      if (rand == 0)
	{
	  success = bondrebridging_2D(ptrk, Matrix, chain, chain_trial, p_array, k_array, r, lattice, chain_length);
	}
      else
	{
	  success = pullmove(Matrix, chain_trial, k_array, ruffle, r, lattice, chain_length);
	}
      
      if(success == false)
	{
	  l = 0;
	  for(itc = chain_trial.begin(); itc != chain_trial.end(); ++itc)
	    {
	      chain_trial[l].reset_coordinates(Matrix, lattice, chain[l].get_x(), chain[l].get_y());
	      ++l;
	    }
	}
      else
	{
	  intersection = 0;
	  l = 0;
	  for(itc = chain.begin(); itc != chain.end(); ++itc)
	    {
	      chain[l].reset_coordinates(Matrix, lattice, chain_trial[l].get_x(), chain_trial[l].get_y());
	      ++l;
	    }
	}
      
      l = 0;
      for(itc = chain.begin(); itc != chain.end(); ++itc)
	{
	  k_array[l] = chain_trial[l].get_ptrk();
	  p_array[l] = chain_trial[l].get_ptrp();
	  l++;
	}
      
    }
}
void potts_NestedSampling_Algorithm_2D(float** ptrMatrix, float* Matrix, std::vector<double>& coordinates, std::vector<double>& likelyhoods, std::vector<double>& postlikelyhoods, Lattice lattice, RandomLib::Random& r, double const J, double const h, double const label_coeff, int const K, int const max, int const mcycle)
{
    int k, p, z, distance, iteration, K_iteration, oldSpin;
    double H_tot, H_in, H_fin, H_tot_constraint, H_tot_trial;

    initialise_likelyhoods(likelyhoods, K);
    initialise_likelyhoods(postlikelyhoods, K);
    initialise_coordinates(coordinates, lattice, K);

    for(int i = 0; i < K; i++)
    {
        potts_generate_random_matrix_2D(Matrix, lattice, r, max);

        H_tot = potts_total_hamiltonian_2D(ptrMatrix,lattice,J,h);

        H_tot = label_likelyhood(H_tot, label_coeff, r);

        likelyhoods.insert(likelyhoods.end(), H_tot);

        add_coordinates(Matrix, coordinates, lattice);
    }

    std::cout<<"END OF INITIALISATION"<<std::endl;
    std::cout<<"likelyhoods.size: "<<likelyhoods.size()<<std::endl;
    std::cout<<"coordinates.size: "<<coordinates.size()<<std::endl;

    bool LOOP = true;
    std::vector<double>::iterator max_likelyhood;

    while(LOOP == true)
    {
        max_likelyhood = std::max_element(likelyhoods.begin(),likelyhoods.end());
        distance = std::distance(likelyhoods.begin(), max_likelyhood);
        H_tot_constraint = likelyhoods.at(distance);
        postlikelyhoods.insert(postlikelyhoods.end(), H_tot_constraint);
        //std::cout<<"H_tot_constraint: "<<H_tot_constraint<<std::endl;

        distance = get_randomlikelyhood_coordinates(Matrix, coordinates, likelyhoods, r, lattice);
        H_tot = likelyhoods.at(distance);
        K_iteration = 0;

        for(z = 0; z < mcycle; z++)
        {
            Matrix_samplepoint_2D(lattice, r, &k, &p);

            H_in = potts_nodal_hamiltonian_2D(ptrMatrix, p, lattice, J, h);

            //flip spin
            oldSpin = Matrix[k];
            Matrix[k] = r.IntegerC(1, max);

            H_fin = potts_nodal_hamiltonian_2D(ptrMatrix, p, lattice, J, h);

            H_tot_trial = H_tot - H_in + H_fin;

            H_tot_trial = label_likelyhood(H_tot_trial, label_coeff, r);

            if (H_tot_trial < H_tot_constraint)
            {
                H_tot = H_tot_trial;
            }
            else
            {
                Matrix[k] = oldSpin;
            }

            if (z == mcycle - 1)
            {
                if (H_tot < H_tot_constraint)
                {
                    replace_maxlikelyhood_coordinates(Matrix, coordinates, likelyhoods, lattice, H_tot);
                    break;
                }
                else
                {
                    //std::cout<<"change"<<std::endl;
                    K_iteration = get_alternativelikelyhood_coordinates_random(Matrix, coordinates, likelyhoods,lattice, r, K, H_tot, K_iteration);
                    z = 0;
                    ++K_iteration;
                }
            }
            else if (K_iteration == K )
            {
                LOOP = false;
                std::cout<<"Algorithm termination condition met"<<std::endl;
                break;
            }
        }
    }
}
void WangLandau_Algorithm_bean_2D(float** ptrMatrix, float* Matrix, std::vector<double>& Histogram, std::vector<double>& Histogram2, std::vector<double>& DOS, Lattice lattice, Bean bean, RandomLib::Random& r, double* ptrf, double const InitialDOS, double const end_f, double const average_frac, double const J, double const h, int const mcycle)
{
  int k, p, z, g, average;
  double H_tot_trial, H_in, H_fin, gE1, gE2;

  int M = lattice.get_M();
  int N = lattice.get_N();
  double H_tot = ising_total_hamiltonian_2D(ptrMatrix,lattice,J,h);
   
  initialiseHistogram_bean(Histogram, DOS);
  initialiseHistogram_bean(Histogram2, DOS);
  
  /*
    std::cout<<"DEBUG3: DOS size: "<<DOS.size()<< std::endl;
    std::cout<<"DEBUG3: Histogram size: "<<Histogram.size()<< std::endl;
  */
  
  while(*ptrf >= end_f)
    {
      bool LOOP = true; 
              
      //std::cout<<"DEBUG Outer while loop"<<std::endl;
       
      while(LOOP == true)
	{
	  //std::cout<<"DEBUG inner while loop"<<std::endl;
	     
	  for(z = 0; z < mcycle; z++)
	    {
	      //the inner loop is necessary for the preconditioning
	      
	      //select random node on the lattice Matrix
	      Matrix_samplepoint_2D(lattice, r, &k, &p);
	      
	      H_in = ising_nodal_hamiltonian_2D(ptrMatrix, p, lattice, J, h);
	      
	      //flip spin
	      Matrix[k] = - Matrix[k];
	      
	      H_fin = ising_nodal_hamiltonian_2D(ptrMatrix, p, lattice, J, h);
	      
	      H_tot_trial = H_tot - H_in + H_fin;
	      gE1 = get_DOS_bean(DOS, bean, H_tot);
	      gE2 = get_DOS_bean(DOS, bean, H_tot_trial);
	      
	      if(gE2 <= gE1)
		{
		  H_tot = H_tot_trial;
		  update_DOS_bean(DOS, Histogram, Histogram2, bean, ptrf, H_tot, InitialDOS);
		  update_EnergyHistogram_bean(Histogram, bean, H_tot);
		}
	      else if (r.Fixed() <= exp( gE1 - gE2 ) ) 
		{
		  H_tot = H_tot_trial;
		  update_DOS_bean(DOS, Histogram, Histogram2, bean, ptrf, H_tot, InitialDOS);
		  update_EnergyHistogram_bean(Histogram, bean, H_tot);
		}
	      else
		{
		  Matrix[k] = - Matrix[k];
		  update_DOS_bean(DOS, Histogram, Histogram2, bean, ptrf, H_tot, InitialDOS);
		  update_EnergyHistogram_bean(Histogram, bean, H_tot);
		}
	    }
	    
	  average = average_EnergyHistogram_bean(Histogram, DOS, InitialDOS, end_f);
	     
	  LOOP = termination_EnergyHistogram_bean(Histogram, DOS, InitialDOS, average, average_frac, end_f);
	}
       
      initialiseHistogram_bean(Histogram, DOS);
      evolve_update_function_sqrt(ptrf);
    }
}
Ejemplo n.º 7
0
template<> RandomLib::Random * Glue<RandomLib::Random>::usr_new(lua_State * L) {
	RandomLib::Random *r = new RandomLib::Random();
	r->Reseed(); 
	return r;
}
Ejemplo n.º 8
0
int lua_random_reset(lua_State *L) {
	RandomLib::Random *s = Glue<RandomLib::Random>::checkto(L, 1);
	s->Reset();
	return 0;
}
Ejemplo n.º 9
0
int lua_random_Float32(lua_State *L) {
	RandomLib::Random *s = Glue<RandomLib::Random>::checkto(L, 1);
	lua::push<double>(L, s->Fixed());
	return 1;
}
Ejemplo n.º 10
0
void sar(char *argv[], unsigned int seed)
{
    RandomLib::Random rng;
    rng.Reseed();

    // List of variables for run conditions:
    const int num_species = 50;
    const int num_patches = 300;
    const int num_step = 5000;
    const int search_radius = 5;

    // Species characteristics:
    const double d = 0.5; // Species mean dispersal distance (shapes dispersal kernel): 1/d
    const double m = 0.1; // Disturbance probability (disturbance kills individual)
    const double niche_min = 0.1; // Competitive strength of empty cells
    const double emi_from_out = 0.001; // Seed bank

    array2Ddouble E;
    array2Dint occupied;
    array2Dint disturbance_counter;

    SetArraySize2d(E, num_patches, num_patches);
    SetArraySize2d(occupied, num_patches, num_patches);
    SetArraySize2d(disturbance_counter, num_patches, num_patches);

    // List of global species characteristic parameters (read in from file or defined in main function):
    double *h = new double[num_species];
    double *u = new double[num_species];
    double *c = new double[num_species];
    double *sigma = new double[num_species];

    // read in species characteristics from file
    char buffer[100];
    sprintf(buffer, "%s_st.txt", argv[1]);
    std::ifstream input_traits(buffer);
    for (int i = 0; i < num_species; ++i)
    {
        input_traits >> sigma[i]; // Niche width
        input_traits >> h[i]; // Performance at niche optimum (height, y at maximum)
        input_traits >> c[i]; // Seed production
        input_traits >> u[i]; // Resource at niche optimum (location, x at maximum)
    }
    input_traits.close();
  
    sprintf(buffer, "%s_species.txt", argv[1]);
    std::ifstream input_species(buffer);
    {
        int i = 0, j = 0;
        while (!input_species.eof())
        {
            input_species >> i;
            input_species >> j;
            input_species >> E[i][j];
            input_species >> occupied[i][j];
            input_species >> disturbance_counter[i][j];
        }
    }
    input_species.close();

    for (int block = 0; block < 1; ++block)
    {
        sprintf(buffer, "%s_dest%d.txt", argv[1], block);
        std::ifstream input_dest(buffer);
		
        for (int i = 0; i < num_patches; ++i)
        {
            for (int j = 0; j < num_patches; ++j)
            {
                disturbance_counter[i][j] = 0;
				//                occupied[i][j] = 0;
            }
        }
		
		// Removed the input_dest as a matrix and replaced by a list (see next loop).
		
		//		for (int i = 0; i < num_patches; ++i)
		//        {
		//            for (int j = 0; j < num_patches; ++j)
		//            {
		//                input_dest >> E[i][j];
		//            }
		//        }
		
		// The input file is now x,y,E with 90000 lines
		
		{										
			int i = 0, j = 0;			
			while (!input_dest.eof())
			{
				input_dest >> i;
				input_dest >> j;
				input_dest >> E[i][j];
			}
		}										
		
        input_dest.close();
		
		//        for (int x = 0; x < num_patches; x++)
		//        {
		//            for (int y = 0; y < num_patches; y++)
		//            {
		//                const int s = (int)(rng.Fixed() * num_species); // Select a species at random
		//                occupied[x][y] = NICHE_F(h[s], u[s], E[x][y], sigma[s]) < niche_min ? EMPTY : s;
		//            }
		//       }
        double all_possible_seeds = 0;

        for (int dx = -search_radius; dx <= search_radius; dx++)
        {
            for (int dy = -search_radius; dy <= search_radius; dy++)
            {
                if ((dx != 0) || (dy != 0))
                {
                    all_possible_seeds += exp(-d * sqrt(dx * dx + dy * dy));
                }
            }
        }
        all_possible_seeds += emi_from_out * num_species;

        for (int t = 0; t < num_step; ++t)
        {
            for (int cell = 0; cell < num_patches * num_patches; cell++)
            {
                const int x = (int)(rng.Fixed() * num_patches);
                const int y = (int)(rng.Fixed() * num_patches);

                if(rng.Fixed() < m)
                {
                    occupied[x][y] = EMPTY;
                    ++disturbance_counter[x][y]; // BR
                }

                double Niche_res = niche_min;
                if (occupied[x][y] != EMPTY)
                {
                    int i = occupied[x][y];
                    Niche_res = NICHE_F(h[i], u[i], E[x][y], sigma[i]);
                }

                std::vector<double> Seed(num_species, 0.0);

                const int dx_min = (x - search_radius < 0) ? -x : -search_radius; 
                const int dx_max = (x + search_radius >= num_patches) ? num_patches - 1 - x : search_radius;
                const int dy_min = (y - search_radius < 0) ? -y : -search_radius;
                const int dy_max = (y + search_radius >= num_patches) ? num_patches - 1 - y : search_radius; 

                assert(x + dx_min >= 0 && x + dx_max < num_patches);
                assert(y + dy_min >= 0 && y + dy_max < num_patches);

                for (int dx = dx_min; dx <= dx_max; ++dx)
                {
                    for (int dy = dy_min; dy <= dy_max; ++dy)
                    {
                        if (((dx != 0) || (dy != 0)) && (occupied[x + dx][y + dy] != EMPTY))
                        {
                            int i = occupied[x + dx][y + dy];
                            if (NICHE_F(h[i], u[i], E[x][y], sigma[i]) > Niche_res)
                            {
                                Seed[i] += c[i] * (exp(-d * sqrt(dx * dx + dy * dy)));
                            }
                        }
                    }
                }
                double all_seeds = 0.0;
                for (int i = 0; i < num_species; ++i)
                {
                    if (NICHE_F(h[i], u[i], E[x][y], sigma[i]) > Niche_res)
                    {
                        Seed[i] += emi_from_out;
                    }
                    all_seeds += Seed[i];
                }

                bool total_colon = false;
                if (all_seeds / all_possible_seeds > rng.Fixed())
                {
                    total_colon = true;
                }

                std::vector<double> Prob_recruit(num_species, 0.0);
                if (total_colon == true)
                {
                    //Prob_recruit[0] = Colon[0]/double(total_colon);
                    Prob_recruit[0] = Seed[0] / all_seeds;
                    for (int i = 1; i < num_species; ++i)
                    {
                        Prob_recruit[i] = Seed[i] / all_seeds + Prob_recruit[i-1];
                    }

                    occupied[x][y] = EMPTY;

                    double randnumb = rng.Fixed();
                    for (int i = 0; i < num_species; i++)
                    {
                        if (randnumb < Prob_recruit[i])
                        {
                            assert(NICHE_F(h[i], u[i], E[x][y], sigma[i]) > niche_min);
                            occupied[x][y] = i;
                            break;
                        }
                    }
                }
            } // ends loop over cells
        } // ends loop t

        sprintf(buffer, "%s_out200_%d.txt", argv[1], block);
        std::ofstream out(buffer);
        for (int x = 0; x < num_patches; ++x)
        {
            for (int y = 0; y < num_patches; ++y)
            {
                out << x << " " << y << " " << E[x][y] << " " << occupied[x][y] << " " << disturbance_counter[x][y] << "\n";
            }
        }
        out.close();
    }
}
Ejemplo n.º 11
0
int main(int, char**) {
  // Create r with a random seed
  RandomLib::Random r; r.Reseed();
  std::cout << "Using " << r.Name() << "\n"
            << "with seed " << r.SeedString() << "\n\n";
  {
    std::cout
      << "Sampling exactly from the normal distribution.  First number is\n"
      << "in binary with ... indicating an infinite sequence of random\n"
      << "bits.  Second number gives the corresponding interval.  Third\n"
      << "number is the result of filling in the missing bits and rounding\n"
      << "exactly to the nearest representable double.\n";
    const int bits = 1;
    RandomLib::ExactNormal<bits> ndist;
    long long num = 20000000ll;
    long long bitcount = 0;
    int numprint = 16;
    for (long long i = 0; i < num; ++i) {
      long long k = r.Count();
      RandomLib::RandomNumber<bits> x = ndist(r); // Sample
      bitcount += r.Count() - k;
      if (i < numprint) {
        std::pair<double, double> z = x.Range();
        std::cout << x << " = "   // Print in binary with ellipsis
                  << "(" << z.first << "," << z.second << ")"; // Print range
        double v = x.Value<double>(r); // Round exactly to nearest double
        std::cout << " = " << v << "\n";
      } else if (i == numprint)
        std::cout << std::flush;
    }
    std::cout
      << "Number of bits needed to obtain the binary representation averaged\n"
      << "over " << num << " samples = " << bitcount/double(num) << "\n\n";
  }
  {
    std::cout
      << "Sampling exactly from exp(-x).  First number is in binary with\n"
      << "... indicating an infinite sequence of random bits.  Second\n"
      << "number gives the corresponding interval.  Third number is the\n"
      << "result of filling in the missing bits and rounding exactly to\n"
      << "the nearest representable double.\n";
    const int bits = 1;
    RandomLib::ExactExponential<bits> edist;
    long long num = 50000000ll;
    long long bitcount = 0;
    int numprint = 16;
    for (long long i = 0; i < num; ++i) {
      long long k = r.Count();
      RandomLib::RandomNumber<bits> x = edist(r); // Sample
      bitcount += r.Count() - k;
      if (i < numprint) {
        std::pair<double, double> z = x.Range();
        std::cout << x << " = "   // Print in binary with ellipsis
                  << "(" << z.first << "," << z.second << ")"; // Print range
        double v = x.Value<double>(r); // Round exactly to nearest double
        std::cout << " = " << v << "\n";
      } else if (i == numprint)
        std::cout << std::flush;
    }
    std::cout
      << "Number of bits needed to obtain the binary representation averaged\n"
      << "over " << num << " samples = " << bitcount/double(num) << "\n\n";
  }
  {
    std::cout
      << "Sampling exactly from the discrete normal distribution with\n"
      << "sigma = 7 and mu = 1/2.\n";
    RandomLib::DiscreteNormal<int> gdist(7,1,1,2);
    long long num = 50000000ll;
    long long count = r.Count();
    int numprint = 16;
    for (long long i = 0; i < num; ++i) {
      int k = gdist(r);         // Sample
      if (i < numprint)
        std::cout << k << " ";
      else if (i == numprint)
        std::cout << std::endl;
    }
    count = r.Count() - count;
    std::cout
      << "Number of random variates needed averaged\n"
      << "over " << num << " samples = " << count/double(num) << "\n\n";
  }
  {
    std::cout
      << "Sampling exactly from the discrete normal distribution with\n"
      << "sigma = 1024 and mu = 1/7.  First result printed is a uniform\n"
      << "range (with covers a power of two).  The second number is the\n"
      << "result of sampling additional bits within that range to obtain\n"
      << "a definite result.\n";
    RandomLib::DiscreteNormalAlt<int,1> gdist(1024,1,1,7);
    long long num = 20000000ll;
    long long count = r.Count();
    long long entropy = 0;
    int numprint = 16;
    for (long long i = 0; i < num; ++i) {
      RandomLib::UniformInteger<int,1> u = gdist(r);
      entropy += u.Entropy();
      if (i < numprint)
        std::cout << u << " = ";
      int k = u(r);
      if (i < numprint)
        std::cout << k << "\n";
      else if (i == numprint)
        std::cout << std::flush;
    }
    count = r.Count() - count;
    std::cout
      << "Number of random bits needed for full result (for range) averaged\n"
      << "over " << num << " samples = " << count/double(num) << " ("
      << (count - entropy)/double(num) << ")\n\n";
  }
  {
    std::cout
      << "Random bits with 1 occurring with probability 1/pi exactly:\n";
    long long num = 100000000ll;
    int numprint = 72;
    RandomLib::InversePiProb pp;
    long long nbits = 0;
    long long k = r.Count();
    for (long long i = 0; i < num; ++i) {
      bool b = pp(r);
      nbits += int(b);
      if (i < numprint) std::cout << int(b);
      else if (i == numprint) std::cout << "..." << std::flush;
    }
    std::cout << "\n";
    std::cout << "Frequency of 1 averaged over " << num << " samples = 1/"
              << double(num)/nbits << "\n"
              << "bits/sample = " << (r.Count() - k)/double(num) << "\n\n";
  }
  {
    std::cout
      << "Random bits with 1 occurring with probability 1/e exactly:\n";
    long long num = 200000000ll;
    int numprint = 72;
    RandomLib::InverseEProb ep;
    long long nbits = 0;
    long long k = r.Count();
    for (long long i = 0; i < num; ++i) {
      bool b = ep(r);
      nbits += int(b);
      if (i < numprint) std::cout << int(b);
      else if (i == numprint) std::cout << "..." << std::flush;
    }
    std::cout << "\n";
    std::cout << "Frequency of 1 averaged over " << num << " samples = 1/"
              << double(num)/nbits << "\n"
              << "bits/sample = " << (r.Count() - k)/double(num) << "\n";
  }
  return 0;
}
Ejemplo n.º 12
0
double Common::randN()
{
    QMutexLocker lock(&rngLock);

    return g_rand.FloatN();
}