Example #1
1
//generator pseudonahodnych cisiel exponencialneho rozlozenia so stredom v x
double Model::GeneratorExp(double x)
{
	std::mt19937 rng((int)std::time(0) * RandomGenerator());	//ak sa generator zavola v rovnakom strojovom case generuje rovnake hodnoty	
	std::exponential_distribution<double> distrib(1 / x);		//semienko je teda vynasobene nahodnym cislom z intervalu 0 - 100

	return distrib(rng);
}
Example #2
1
//generator pseudonahodnych cisiel, rovnomerne rozlozenie z intervalu
//<a, b>; implicitne hodnoty: a=1, b=100
//pouziva sa pre urcenie pravdepodobnosti
int Model::RandomGenerator(int a, int b)
{
	std::random_device rand;
	std::uniform_int_distribution<int> distrib(a, b);
	std::mt19937 rng(rand());

	return distrib(rng);
}
Example #3
1
extern "C" int main(int ac, char **av)
{
  MPI_CALL(Init(&ac, &av));
  ospcommon::tasking::initTaskingSystem();
  maml::init();

  std::mt19937 rng(std::random_device{}());
  std::uniform_int_distribution<int> distrib(0, 255);

  int numRuns = 1000000;
  int rank = -1;
  int numRanks = 0;
  MPI_CALL(Comm_size(MPI_COMM_WORLD,&numRanks));
  MPI_CALL(Comm_rank(MPI_COMM_WORLD,&rank));

  int numMessages = 100;
  int payloadSize = 100000;

  MyHandler handler;
  maml::registerHandlerFor(MPI_COMM_WORLD,&handler);

  char *payload = (char*)malloc(payloadSize);
  for (int i=0;i<payloadSize;i++)
    payload[i] = distrib(rng);

  for (int run=0;run<numRuns;run++) {
    MPI_CALL(Barrier(MPI_COMM_WORLD));
    double t0 = ospcommon::getSysTime();
    maml::start();

    for (int mID=0;mID<numMessages;mID++) {
      for (int r=0;r<numRanks;r++) {
        maml::sendTo(MPI_COMM_WORLD,r,std::make_shared<maml::Message>(payload,payloadSize));
      }
    }

    while (handler.numReceived != numRanks*numMessages*(run+1)) {
      std::this_thread::sleep_for(std::chrono::milliseconds(10));
    }

    maml::stop();
    double t1 = ospcommon::getSysTime();
    double bytes = numRanks * numMessages * payloadSize / (t1-t0);
    std::string rate = ospcommon::prettyNumber(bytes);
    printf("rank %i: received %i messages in %lf secs; that is %sB/s\n",rank,numRanks*numMessages,t1-t0,
           rate.c_str());
    MPI_CALL(Barrier(MPI_COMM_WORLD));
  }

  maml::shutdown();

  MPI_CALL(Barrier(MPI_COMM_WORLD));
  MPI_Finalize();
}
int main()
{
  KarpShenker ks(0.2);
  
  std::mt19937 seed(getpid());
  std::normal_distribution<double> distrib(500.0, 20.0);

  for (int i = 0; i < 1000; i++)
  {
    uint32_t idx = distrib(seed)/10;
    std::cout << idx << std::endl;
    ks.insert(idx);
  }
  std::cout << ks << std::endl;
}
random_switch_task::random_switch_task(std::shared_ptr<graph_data> graph_data, double mu, size_t step_count, size_t graph_step, const std::string& output_dir) :
  base_task(graph_data, mu, step_count, graph_step, output_dir)
{
  undirected_graph& graph_ = gr_data_->graph_;
  size_t vertices_count = boost::num_vertices(graph_);
  size_t all_edges_count = vertices_count * (vertices_count - 1) / 2;
  size_t non_existing_edges_count = all_edges_count - boost::num_edges(graph_);
  non_existing_edges_.reserve(non_existing_edges_count);
  vertex_iterator v, v_end;
  boost::tie(v, v_end) = boost::vertices(graph_);
  size_t index = 0;
  for(; v != v_end; ++v)
  {
    vertex_iterator v1 = v;
    for(++v1; v1 != v_end; ++v1)
    {
      if(!boost::edge(*v, *v1, graph_).second)
      {
        non_existing_edges_.push_back(std::make_pair(*v, *v1));
      }
    }
  }
  std::uniform_int_distribution<> distrib(0, non_existing_edges_.size() - 1);
  var_generator_ = new boost::variate_generator<random_generator, std::uniform_int_distribution<>>(rand_generator_, distrib);
}
Example #6
0
const Key& CountDictionary<Key>::sample(){

   //put that somewhere else...
   if(!sampling_allowed){
     std::vector<double> w(this->dict.size());
     arg_vec.resize(this->dict.size());
     int idx = 0;
     for(typename std::unordered_map<Key,unsigned>::iterator it = this->dict.begin();it != this->dict.end();++it){
       arg_vec[idx] = it->first;
       w[idx] = it->second;
       ++idx;
     }
     std::discrete_distribution<int> dtmp(w.begin(),w.end());
     distrib.param(dtmp.param()); 
     /*
       std::vector<double> p = distrib.probabilities();
     for(int i = 0; i < p.size();++i){
       std::cout << arg_vec[i] <<  p[i] << endl;
     }
     */

     sampling_allowed = true;
   } 
   //distrib.reset() ?;
   return arg_vec[distrib(rd_generator)];
}
Example #7
0
static
BOOL arith_rel_quasi_eval(Term atom)
{
  /* This is an initial version for testing only. */
  if (SYMNUM(atom) == Eq_sn) {
    BOOL negated = NEGATED(atom);
    Term atom2 = copy_term(atom);
    BOOL val;

    atom2 = distrib(atom2);
    /* printf("after distrib:  "); fwrite_term_nl(stdout, atom2); */
    ac_canonical2(atom2, -1, term_compare_vcp);
    /* printf("after AC canon: "); fwrite_term_nl(stdout, atom2); */

    ARG(atom2,0) = qsimp(ARG(atom2,0));
    ARG(atom2,1) = qsimp(ARG(atom2,1));

    /* printf("after qsimp: "); fwrite_term_nl(stdout, atom2); */

    if (term_ident(ARG(atom2,0), ARG(atom2,1)))
      val = negated ? FALSE : TRUE;
    else
      val = FALSE;

    zap_term(atom2);
    return val;
  }
  else
    return FALSE;
}  /* arith_rel_quasi_eval */
Example #8
0
File: Rand.hpp Project: Agilack/vle
        /**
         * @brief Generate a real using an exponential distribution.
         * @param rate
         * @return a real between 0 and infinite.
         */
        double exponential(double rate)
        {
            boost::exponential_distribution < > distrib(rate);
            boost::variate_generator < boost::mt19937&,
                boost::exponential_distribution < > > gen(m_rand, distrib);

            return gen();
        }
Example #9
0
File: Rand.hpp Project: Agilack/vle
        /**
         * @brief Generate a real using the Log Normal law.
         * @param mean
         * @param sigma
         * @return a real.
         */
        double logNormal(double mean, double sigma)
        {
            boost::lognormal_distribution < > distrib(mean, sigma);
            boost::variate_generator < boost::mt19937&,
                boost::lognormal_distribution < > > gen(m_rand, distrib);

            return gen();
        }
Example #10
0
File: Rand.hpp Project: Agilack/vle
        /**
         * @brief Generate a real from begin to end [begin..end).
         * @param begin The minimum value.
         * @param end The limit (exclude) of the range.
         * @return a random real.
         */
        inline double getDouble(double begin, double end)
        {
            boost::uniform_real < > distrib(begin, end);
            boost::variate_generator < boost::mt19937&,
                boost::uniform_real < > > gen(m_rand, distrib);

            return gen();
        }
Example #11
0
File: Rand.hpp Project: Agilack/vle
        /**
         * @brief Generate a real value [0, 1)
         * @return a random real.
         */
        inline double getDouble()
        {
            boost::uniform_real < > distrib(0.0, 1.0);
            boost::variate_generator < boost::mt19937&,
                boost::uniform_real < > > gen(m_rand, distrib);

            return gen();
        }
Example #12
0
File: Rand.hpp Project: Agilack/vle
        /**
         * @brief Generate an integer from begin to end [begin..end].
         * @param begin The minimum value include.
         * @param end The limit of the range.
         * @return a random integer.
         */
        inline int getInt(int begin, int end)
        {
            boost::uniform_int < > distrib(begin, end);
            boost::variate_generator < boost::mt19937&,
                boost::uniform_int < > > gen(m_rand, distrib);

            return gen();
        }
Example #13
0
void	put_dots(t_dot *dot, t_mlx mlx)
{
	int		ct;

	ct = 0;
	mlx.mlx = mlx_init();
	mlx.win = mlx_new_window(mlx.mlx, 1600, 1600, "lol");
	while (!(dot + ct)->end)
	{
		distrib(*(dot + ct), *(dot + ct + 1), mlx);
		if ((ct / mlx.len) != mlx.line - 1)
			distrib(*(dot + ct), *(dot + ct + mlx.len), mlx);
		ct++;
	}
	mlx_key_hook(mlx.win, ft_quit, NULL);
	mlx_loop(mlx.mlx);
}
Example #14
0
File: Rand.hpp Project: Agilack/vle
        /**
         * @brief Generate a real using the Poisson distribution.
         * @param mean
         * @return a real.
         */
        double poisson(double mean)
        {
            boost::poisson_distribution < > distrib(mean);
            boost::variate_generator < boost::mt19937&,
                boost::poisson_distribution < > > gen(m_rand, distrib);

            return gen();
        }
Example #15
0
File: Rand.hpp Project: Agilack/vle
        /**
         * @brief Generate a real using the Gamma distribution.
         * @param alpha
         * @return a real.
         */
        double gamma(double alpha)
        {
            boost::gamma_distribution < > distrib(alpha);
            boost::variate_generator < boost::mt19937&,
                boost::gamma_distribution < > > gen(m_rand, distrib);

            return gen();
        }
Example #16
0
File: Rand.hpp Project: Agilack/vle
        /**
         * @brief Generate a real using the triangular law.
         * @param a
         * @param b
         * @param c
         * @return a real.
         */
        double triangle(double a, double b, double c)
        {
            boost::triangle_distribution < > distrib(a, b, c);
            boost::variate_generator < boost::mt19937&,
                boost::triangle_distribution < > > gen(m_rand, distrib);

            return gen();
        }
Example #17
0
File: Rand.hpp Project: Agilack/vle
        /**
         * @brief Generate a real using the Cauchy law.
         * @param median
         * @param sigma
         * @return a real.
         */
        double cauchy(double median, double sigma)
        {
            boost::cauchy_distribution < > distrib(median, sigma);
            boost::variate_generator < boost::mt19937&,
                boost::cauchy_distribution < > > gen(m_rand, distrib);

            return gen();
        }
Example #18
0
File: Rand.hpp Project: Agilack/vle
        /**
         * @brief Generate a real using the Geometric distribution.
         * @param p
         * @return a real.
         */
        double geometric(double p)
        {
            boost::geometric_distribution < > distrib(p);
            boost::variate_generator < boost::mt19937&,
                boost::geometric_distribution < > > gen(m_rand, distrib);

            return gen();
        }
Example #19
0
File: Rand.hpp Project: Agilack/vle
        /**
         * @brief Generate a real using the Binomial distribution.
         * @param t
         * @param p
         * @return a real.
         */
        double binomial(int t, double p)
        {
            boost::binomial_distribution < > distrib(t, p);
            boost::variate_generator < boost::mt19937&,
                boost::binomial_distribution < > > gen(m_rand, distrib);

            return gen();
        }
Example #20
0
void	modul(t_precis *nb, t_flag *flag, char *format, int *len)
{
    distrib(nb, flag, format);
    nb->j = double_modulo(nb, format);
    if (nb->min != 0)
        *len += nb->min;
    else
        (*len)++;
}
Example #21
0
    double StdMaterial::lightFreePathLength(const Raycast& ray) const
    {
        double opa = opacity(ray.origin);

        if(opa <= 0.0)
        {
            return Raycast::BACKDROP_LIMIT;
        }
        else if(opa >= 1.0)
        {
            return 0.0;
        }
        else
        {
            double scatterRate = 1 / (1 / (opa) - 1);
            std::exponential_distribution<> distrib(scatterRate);
            return distrib(_randomEngine);
        }
    }
Example #22
0
std::size_t generate_random_number(unsigned min, unsigned max) {

	std::mt19937 typedef generator_t;
	std::random_device generate_seed;
	generator_t gen(generate_seed());
	boost::uniform_int<> distrib(min, max);
	//std::uniform_int<> distrib(min, max);
	std::function<size_t()> uni_random(std::bind(distrib, gen));
	return uni_random();
}
Example #23
0
  void			Population::Mutation(void)
  {
    unsigned int	index;
    std::default_random_engine gen;
    std::uniform_int_distribution<int> distrib('a', 'z');
    std::uniform_real_distribution<double> distrib_d(0,1);
    std::vector<char>	genes;

    for (std::list<Chromosome *>::iterator it = _samples.begin(); it != _samples.end(); ++it)
      {
	if (distrib_d(gen) <= _mutation_rate)
	  {
	    index = RandomInt(0, _gene_size);
	    genes = (*it)->getGenes();
	    genes[index] = (char)distrib(gen);
	    (*it)->setGenes(genes);
	  }
      }
  }
Example #24
0
static
Term distrib(Term t)
{
  if (VARIABLE(t))
    return t;
  else {
    int i;
    for (i = 0; i < ARITY(t); i++)
      ARG(t,i) = distrib(ARG(t,i));

    if (SYMNUM(t) != Prod_sn)
      return t;
    else {
      if (SYMNUM(ARG(t,1)) == Sum_sn) {
	/* a*(b+c) */
	Term a = ARG(t,0);
	Term b = ARG(ARG(t,1),0);
	Term c = ARG(ARG(t,1),1);
	free_term(ARG(t,1));
	free_term(t);
	return build_binary_term(Sum_sn,
				 distrib(build_binary_term(Prod_sn, a, b)),
				 distrib(build_binary_term(Prod_sn, copy_term(a), c)));
      }
      else if (SYMNUM(ARG(t,0)) == Sum_sn) {
	/* (b+c)*a */
	Term a = ARG(t,1);
	Term b = ARG(ARG(t,0),0);
	Term c = ARG(ARG(t,0),1);
	free_term(ARG(t,0));
	free_term(t);
	return build_binary_term(Sum_sn,
				 distrib(build_binary_term(Prod_sn, b, a)),
				 distrib(build_binary_term(Prod_sn, c, copy_term(a))));
      }
      else
	return t;
    }
  }
}  /* distrib */
Example #25
0
 typename graph_traits<Graph>::edge_descriptor
 random_edge(Graph& g, RandomNumGen& gen) {
   if (num_edges(g) > 1) {
     uniform_int<> distrib(0, num_edges(g)-1);
     variate_generator<RandomNumGen&, uniform_int<> > rand_gen(gen, distrib);
     typename graph_traits<Graph>::edges_size_type 
       n = rand_gen();
     typename graph_traits<Graph>::edge_iterator
       i = edges(g).first;
     while (n-- > 0) ++i; // std::advance not VC++ portable
     return *i;
   } else
     return *edges(g).first;
 }
Example #26
0
 typename graph_traits<Graph>::vertex_descriptor
 random_vertex(Graph& g, RandomNumGen& gen)
 {
   if (num_vertices(g) > 1) {
   #if BOOST_WORKAROUND( __BORLANDC__, BOOST_TESTED_AT(0x581))
     std::size_t n = std::random( num_vertices(g) );
   #else
     uniform_int<> distrib(0, num_vertices(g)-1);
     variate_generator<RandomNumGen&, uniform_int<> > rand_gen(gen, distrib);
     std::size_t n = rand_gen();
   #endif
     typename graph_traits<Graph>::vertex_iterator
       i = vertices(g).first;
     return *(boost::next(i, n));
   } else
     return *vertices(g).first;
 }
graph_types::remove_add_edges_pair random_switch_randomizer::get_step()
{
    graph_types::remove_add_edges_pair r_a_p;
    std::uniform_int_distribution<> distrib(0, 
        m_non_existing_edges.size() - 1);
    auto variate_generator = new boost::variate_generator<
        graph_types::random_generator,
        std::uniform_int_distribution<>>(m_random_generator, distrib);
    graph_types::edge e1 = m_graph.random_edge(m_random_generator);
    r_a_p.first.push_back(e1);
    unsigned n_e_e_index = (*variate_generator)();
    auto& e2 = m_non_existing_edges[n_e_e_index];
    assert(!m_graph.edge_exists(e2));
    r_a_p.second.push_back(e2);
    m_non_existing_edges.erase(m_non_existing_edges.begin() + n_e_e_index);
    delete variate_generator;
    return r_a_p;
}
Example #28
0
void		Plazza::start()
{
  draw_menu();
  draw_log();

  char	buff[4096];
  std::string line;

  while (line != "quit")
    {
      printEcrased();
      move(40, 2);
      clrtoeol();
      getstr(buff);
      line.assign(buff);
      parsing(line);
      distrib();
      wclrtoeol(_footer);
    }
}
Example #29
0
static void up_handler(state_t s, event_t e, unmarsh_t abv) {
    endpt_id_t origin ;
    unmarsh_endpt_id(abv, &origin) ;
    if (s->partition) {
	sys_abort() ;
    } else {
	etime_t delay ;
	if (!distrib(s, &delay)) {
	    up_free(e, abv) ;
	} else {
	    etime_t when = time_add(alarm_gettime(s->alarm), delay) ;
	    item_t item = record_create(item_t, item) ;
	    /*eprintf("type=%s\n", event_type_to_string(event_type(e))) ;*/
	    item->type = DROP_UP ;
	    item->u.up.event = e ;
	    item->u.up.abv = abv ;
	    priq_add(s->priq, when, item) ;
	    dnnm(s, event_timer_time(when)) ;
	}
    }
}
Example #30
0
const Distribution1D *SpatialLightDistribution::Lookup(const Point3f &p) const {
    ProfilePhase _(Prof::LightDistribLookup);
    ++nLookups;

    // Compute integer voxel coordinates for the given point |p| with
    // respect to the overall voxel grid.
    Vector3f offset = scene.WorldBound().Offset(p);  // offset in [0,1].
    Point3i pi;
    for (int i = 0; i < 3; ++i) pi[i] = int(offset[i] * nVoxels[i]);

    // Create the per-thread cache of sampling distributions if needed.
    LocalBucketHash *localVoxelDistribution =
        localVoxelDistributions[ThreadIndex].get();
    if (!localVoxelDistribution) {
        LOG(INFO) << "Created per-thread SpatialLightDistribution for thread" <<
            ThreadIndex;
        localVoxelDistribution = new LocalBucketHash;
        localVoxelDistributions[ThreadIndex].reset(localVoxelDistribution);
    }
    else {
        // Otherwise see if we have a sampling distribution for the voxel
        // that |p| is in already available in the local cache.
        auto iter = localVoxelDistribution->find(pi);
        if (iter != localVoxelDistribution->end())
            return iter->second;
    }

    // Now we need to either get the distribution from the shared hash
    // table (if another thread has already created it), or create it
    // ourselves and add it to the shared table.
    ProfilePhase __(Prof::LightDistribLookupL2);

    // First, compute a hash into the first-level hash table.
    size_t hash = std::hash<int>{}(pi[0] + nVoxels[0] * pi[1] +
                                   nVoxels[0] * nVoxels[1] * pi[2]);
    hash &= (nBuckets - 1);

    // Acquire the lock for the corresponding second-level hash table.
    std::lock_guard<std::mutex> lock(mutexes[hash]);
    // See if we can find it.
    auto iter = voxelDistribution[hash].find(pi);
    if (iter != voxelDistribution[hash].end()) {
        // Success. Add the pointer to the thread-specific hash table so
        // that we can look up this distribution more efficiently in the
        // future.
        (*localVoxelDistribution)[pi] = iter->second.get();
        return iter->second.get();
    }

    // We need to compute a new sampling distriibution for this voxel. Note
    // that we're holding the lock for the first-level hash table bucket
    // throughout the following; in general, we'd like to do the following
    // quickly so that other threads don't get held up waiting for that
    // lock (for this or other voxels that share it).
    ProfilePhase ___(Prof::LightDistribCreation);
    ++nCreated;
    ++nDistributions;

    // Compute the world-space bounding box of the voxel.
    Point3f p0(Float(pi[0]) / Float(nVoxels[0]),
               Float(pi[1]) / Float(nVoxels[1]),
               Float(pi[2]) / Float(nVoxels[2]));
    Point3f p1(Float(pi[0] + 1) / Float(nVoxels[0]),
               Float(pi[1] + 1) / Float(nVoxels[1]),
               Float(pi[2] + 1) / Float(nVoxels[2]));
    Bounds3f voxelBounds(scene.WorldBound().Lerp(p0),
                         scene.WorldBound().Lerp(p1));

    // Compute the sampling distribution. Sample a number of points inside
    // voxelBounds using a 3D Halton sequence; at each one, sample each
    // light source and compute a weight based on Li/pdf for the light's
    // sample (ignoring visibility between the point in the voxel and the
    // point on the light source) as an approximation to how much the light
    // is likely to contribute to illumination in the voxel.
    int nSamples = 128;
    std::vector<Float> lightContrib(scene.lights.size(), Float(0));
    for (int i = 0; i < nSamples; ++i) {
        Point3f po = voxelBounds.Lerp(Point3f(
            RadicalInverse(0, i), RadicalInverse(1, i), RadicalInverse(2, i)));
        Interaction intr(po, Normal3f(), Vector3f(), Vector3f(1, 0, 0),
                         0 /* time */, MediumInterface());

        // Use the next two Halton dimensions to sample a point on the
        // light source.
        Point2f u(RadicalInverse(3, i), RadicalInverse(4, i));
        for (size_t j = 0; j < scene.lights.size(); ++j) {
            Float pdf;
            Vector3f wi;
            VisibilityTester vis;
            Spectrum Li = scene.lights[j]->Sample_Li(intr, u, &wi, &pdf, &vis);
            if (pdf > 0) {
                // TODO: look at tracing shadow rays / computing beam
                // transmittance.  Probably shouldn't give those full weight
                // but instead e.g. have an occluded shadow ray scale down
                // the contribution by 10 or something.
                lightContrib[j] += Li.y() / pdf;
            }
        }
    }

    // We don't want to leave any lights with a zero probability; it's
    // possible that a light contributes to points in the voxel even though
    // we didn't find such a point when sampling above.  Therefore, compute
    // a minimum (small) weight and ensure that all lights are given at
    // least the corresponding probability.
    Float sumContrib =
        std::accumulate(lightContrib.begin(), lightContrib.end(), Float(0));
    Float avgContrib = sumContrib / (nSamples * lightContrib.size());
    Float minContrib = (avgContrib > 0) ? .001 * avgContrib : 1;
    for (size_t i = 0; i < lightContrib.size(); ++i) {
        VLOG(2) << "Voxel pi = " << pi << ", light " << i << " contrib = "
                << lightContrib[i];
        lightContrib[i] = std::max(lightContrib[i], minContrib);
    }
    LOG(INFO) << "Initialized light distribution in voxel pi= " <<  pi <<
        ", avgContrib = " << avgContrib;

    // Compute a sampling distribution from the accumulated
    // contributions.
    std::unique_ptr<Distribution1D> distrib(
        new Distribution1D(&lightContrib[0], lightContrib.size()));

    // Store a pointer to it in the per-thread cache for the future.
    (*localVoxelDistribution)[pi] = distrib.get();

    // Store the canonical unique_ptr for it in the global hash table so
    // other threads can use it.
    voxelDistribution[hash][pi] = std::move(distrib);

    return (*localVoxelDistribution)[pi];
}