Random truncated Poisson variates with minimum value k, generated
    using rejection sampling.
198234
def rtruncated_poisson(mu, k, size=None):
    

    # Calculate m
    try:
        m = max(0, np.floor(k - mu))
    except (TypeError, ValueError):
        # More than one mu
        return np.array([rtruncated_poisson(x, i)
                         for x, i in zip(mu, np.resize(k, np.size(mu)))]).squeeze()
    k -= 1

    # Calculate constant for acceptance probability
    C = np.exp(flib.factln(k + 1) - flib.factln(k + 1 - m))

    # Empty array to hold random variates
    rvs = np.empty(0, int)

    total_size = np.prod(size or 1)

    while(len(rvs) < total_size):

        # Propose values by sampling from untruncated Poisson with mean mu + m
        proposals = np.random.poisson(
            mu + m, (total_size * 4, np.size(m))).squeeze()

        # Acceptance probability
        a = C * np.array([np.exp(flib.factln(y - m) - flib.factln(y))
                          for y in proposals])
        a *= proposals > k

        # Uniform random variates
        u = np.random.random(total_size * 4)

        rvs = np.append(rvs, proposals[u < a])

    return np.reshape(rvs[:total_size], size)
556066
def shot_noise(x, severity=1):
  
  c = [60, 25, 12, 5, 3][severity - 1]
  x = np.array(x) / 255.
  x_clip = np.clip(np.random.poisson(x * c) / float(c), 0, 1) * 255
  return around_and_astype(x_clip)
753850
def _random_stochastic_matrix(m, n, k=None, sparse=False, format='csr',
                              random_state=None):
    
    if k is None:
        k = n
    # m prob vectors of dimension k, shape (m, k)
    probvecs = probvec(m, k, random_state=random_state)

    if k == n:
        P = probvecs
        if sparse:
            return scipy.sparse.coo_matrix(P).asformat(format)
        else:
            return P

    # if k < n:
    rows = np.repeat(np.arange(m), k)
    cols = \
        sample_without_replacement(
            n, k, num_trials=m, random_state=random_state
        ).ravel()
    data = probvecs.ravel()

    if sparse:
        P = scipy.sparse.coo_matrix((data, (rows, cols)), shape=(m, n))
        return P.asformat(format)
    else:
        P = np.zeros((m, n))
        P[rows, cols] = data
        return P
1026230
def noise(matrix):
    

    D = shortest_path_interpolation(matrix, strict=True)
    return np.random.poisson(lam=D)
1019058
public void generateRandom( int nbPoints, float minX, float maxX, float minY, float maxY )
	{
		xs = new ArrayList<Float>();
		ys = new ArrayList<Float>();

		for( int i = 0; i < nbPoints; i++ )
		{
			float r = (float) Math.random();
			r = (float) (((int) (r * 100)) / 100.0);
			xs.add( minX + (i * (maxX - minX) / (nbPoints - 1)) );
			ys.add( minY + r * (maxY - minY) );
		}
	}
1174634
private ApproximationLine approximateLowerHull(ConvexHull convexHull, double[] log_k, double sum_log_k, double sum_log_k2, double[] log_kDist, double sum_log_kDist, double sum_log_k_kDist) {
    // StringBuilder msg = new StringBuilder(1000);
    int[] lowerHull = convexHull.getLowerHull();
    int l = convexHull.getNumberOfPointsInLowerHull();
    int k_0 = settings.kmax - lowerHull.length + 1;

    // linear search on all line segments on the lower convex hull
    // msg.append("lower hull l = ").append(l).append('\n');
    double low_error = Double.MAX_VALUE;
    double low_m = 0.0;
    double low_t = 0.0;

    for(int i = 1; i < l; i++) {
      double cur_m = (log_kDist[lowerHull[i]] - log_kDist[lowerHull[i - 1]]) / (log_k[lowerHull[i]] - log_k[lowerHull[i - 1]]);
      double cur_t = log_kDist[lowerHull[i]] - cur_m * log_k[lowerHull[i]];
      double cur_error = ssqerr(k_0, settings.kmax, log_k, log_kDist, cur_m, cur_t);
      // msg.append(" Segment = ").append(i).append(" m =
      // ").append(cur_m).append(" t = ").append(cur_t).append(" lowerror =
      // ").append(cur_error).append('\n');
      if(cur_error < low_error) {
        low_error = cur_error;
        low_m = cur_m;
        low_t = cur_t;
      }
    }

    // linear search on all points of the lower convex hull
    boolean is_right = true; // NEEDED FOR PROOF CHECK
    for(int i = 0; i < l; i++) {
      double cur_m = optimize(k_0, settings.kmax, sum_log_k, sum_log_k2, log_k[lowerHull[i]], log_kDist[lowerHull[i]], sum_log_k_kDist, sum_log_kDist);
      double cur_t = log_kDist[lowerHull[i]] - cur_m * log_k[lowerHull[i]];
      // only valid if both neighboring points are underneath y=mx+t
      if((i == 0 || log_kDist[lowerHull[i - 1]] >= log_kDist[lowerHull[i]] - cur_m * (log_k[lowerHull[i]] - log_k[lowerHull[i - 1]])) && (i == l - 1 || log_kDist[lowerHull[i + 1]] >= log_kDist[lowerHull[i]] + cur_m * (log_k[lowerHull[i + 1]] - log_k[lowerHull[i]]))) {
        double cur_error = ssqerr(k_0, settings.kmax, log_k, log_kDist, cur_m, cur_t);
        if(cur_error < low_error) {
          low_error = cur_error;
          low_m = cur_m;
          low_t = cur_t;
        }
      }

      // check proof of bisection search
      if(!(i > 0 && log_kDist[lowerHull[i - 1]] < log_kDist[lowerHull[i]] - cur_m * (log_k[lowerHull[i]] - log_k[lowerHull[i - 1]])) && !is_right) {
        LOG.warning("ERROR lower: The bisection search will not work properly!");
        if(!(i < l - 1 && log_kDist[lowerHull[i + 1]] < log_kDist[lowerHull[i]] + cur_m * (log_k[lowerHull[i + 1]] - log_k[lowerHull[i]]))) {
          is_right = false;
        }
      }
    }
    return new ApproximationLine(k_0, low_m, low_t);
  }
763014
def Kdiag(self, X):
        """"""
        ret = np.empty(X.shape[0])
        ret[:] = self.variance
        return ret
1180963
def _sample(rng, arr, k):
  
  selected = numpy.empty(k, dtype="uint32")
  rng.sample(numpy.asarray(arr, dtype="uint32"),
             selected)
  return selected
1035677
def randomise_branch_lengths(
            self,
            i=(1, 1),
            l=(1, 1),
            distribution_func=random.gammavariate,
            inplace=False,
    ):
        

        if not inplace:
            t = self.copy()
        else:
            t = self

        for n in t._tree.preorder_node_iter():
            if n.is_internal():
                n.edge.length = max(0, distribution_func(*i))
            else:
                n.edge.length = max(0, distribution_func(*l))
        t._dirty = True
        return t
1125657
def sample(self, multiplicity):
        

        """
        if self._n is None:
            return self._uniform_phi(multiplicity)

        # Since the flow PDF does not have an analytic inverse CDF, I use a
        # simple accept-reject sampling algorithm.  This is reasonably
        # efficient since for normal-sized vn, the PDF is close to flat.  Now
        # due to the overhead of Python functions, it's desirable to minimize
        # the number of calls to the random number generator.  Therefore I
        # sample numbers in chunks; most of the time only one or two chunks
        # should be needed.  Eventually, I might rewrite this with Cython, but
        # it's fast enough for now.

        N = 0  # number of phi that have been sampled
        phi = np.empty(multiplicity)  # allocate array for phi
        pdf_max = 1 + 2*self._vn.sum()  # sampling efficiency ~ 1/pdf_max

        while N < multiplicity:
            n_remaining = multiplicity - N
            n_to_sample = int(1.03*pdf_max*n_remaining)
            phi_chunk = self._uniform_phi(n_to_sample)
            phi_chunk = phi_chunk[self._pdf(phi_chunk) >
                                  np.random.uniform(0, pdf_max, n_to_sample)]
            K = min(phi_chunk.size, n_remaining)  # number of phi to take
            phi[N:N+K] = phi_chunk[:K]
            N += K

        return phi
624290
def sample_posterior(x,post,nsamples=1):
    
    cdf = post.cumsum()
    cdf /= cdf.max()
    u = rand.random(size=nsamples)
    inds = np.digitize(u,cdf)
    return x[inds]
880466
def poisson_consensus_se(data, k, n_runs=10, **se_params):
    
    clusters = []
    for i in range(n_runs):
        assignments, means  = poisson_cluster(data, k)
        clusters.append(assignments)
    clusterings = np.vstack(clusters)
    consensus = CE.cluster_ensembles(clusterings, verbose=False, N_clusters_max=k)
    init_m, init_w = nmf_init(data, consensus, k, 'basic')
    M, W, ll = poisson_estimate_state(data, k, init_means=init_m, init_weights=init_w, **se_params)
    return M, W, ll
577735
def _backward_sampling_ON(self, M, idx):
        
        nattempts = 0
        for t in reversed(range(self.T - 1)):
            where_rejected = np.arange(M)
            who_rejected = self.X[t + 1][idx[t + 1, :]]
            nrejected = M
            gen = rs.MultinomialQueue(self.wgt[t].W, M=M)
            while nrejected > 0:
                nattempts += nrejected
                nprop = gen.dequeue(nrejected)
                lpr_acc = (self.model.logpt(t + 1, self.X[t][nprop], 
                                            who_rejected)
                           - self.model.upper_bound_trans(t + 1))
                newly_accepted = np.log(random.rand(nrejected)) < lpr_acc
                still_rejected = np.logical_not(newly_accepted)
                idx[t, where_rejected[newly_accepted]] = nprop[newly_accepted]
                where_rejected = where_rejected[still_rejected]
                who_rejected = who_rejected[still_rejected]
                nrejected -= sum(newly_accepted)
        return (M * (self.T - 1)) / nattempts
1295384
def rlmb_base_stochastic_discrete():
  """"""
  hparams = rlmb_base()
  hparams.learning_rate_bump = 1.0
  hparams.grayscale = False
  hparams.generative_model = "next_frame_basic_stochastic_discrete"
  hparams.generative_model_params = "next_frame_basic_stochastic_discrete"
  # The parameters below are the same as base, but repeated for easier reading.
  hparams.ppo_epoch_length = 50
  hparams.simulated_rollout_length = 50
  hparams.simulated_batch_size = 16
  return hparams
470664
def sample_given_context(self, c, c_dims):
        '''
        
        '''
        index = self.discrete_progress.sample_given_context(c, c_dims, self.space)
        return self.space.rand_value(index).flatten()[list(set(range(len(self.space.cardinalities))) - set(c_dims))]
320708
def gen_stochastic_matrix(size, random_state=None):
    
    if not type(size) is tuple:
        size = (1, size)

    assert len(size) == 2

    n = random_state.uniform(size=(size[0], size[1] - 1))
    n = np.concatenate([np.zeros((size[0], 1)), n, np.ones((size[0], 1))], axis=1)

    A = np.diff(np.sort(n))
    return A.squeeze()
220371
def sample_truncated_gaussian(mu=0, sigma=1, lb=-np.Inf, ub=np.Inf):
    
    # Broadcast arrays to be of the same shape
    mu, sigma, lb, ub = np.broadcast_arrays(mu, sigma, lb, ub)
    shp = mu.shape
    if np.allclose(sigma, 0.0):
        return mu

    cdflb = normal_cdf(lb, mu, sigma)
    cdfub = normal_cdf(ub, mu, sigma)

    # Sample uniformly from the CDF
    cdfsamples = cdflb + np.random.rand(*shp) * (cdfub-cdflb)

    # Clip the CDF samples so that we can invert them
    cdfsamples = np.clip(cdfsamples, 1e-15, 1-1e-15)
    zs = -np.sqrt(2) * special.erfcinv(2 * cdfsamples)

    # Transform the standard normal samples
    xs = sigma * zs + mu
    xs = np.clip(xs, lb, ub)

    return xs