Draw `nsamples` samples randomly distributed within the unit cube.

        Returns
        -------
        x : `~numpy.ndarray` with shape (nsamples, ndim)
            A collection of coordinates within the unit cube.
975334
def samples(self, nsamples, rstate=None):
        

        if rstate is None:
            rstate = np.random

        xs = np.array([self.sample(rstate=rstate) for i in range(nsamples)])

        return xs
1192538
def sample_within_cc(self, cc_index, nsamples=1):
        
        polygon = self.geometries[cc_index]['polygon']
        samples = []
        while len(samples) < nsamples:
            point = PointSampler.random_point(polygon.envelope.bounds)
            if PointSampler.contains(polygon, point):
                samples.append(point)
        return samples
656216
def visualize(hog, grid=(10, 10), radCircle=None):
    '''
    
    '''
    s0, s1, nang = hog.shape
    angles = np.linspace(0, np.pi, nang + 1)[:-1]
    # center of each sub array:
    cx, cy = s0 // (2 * grid[0]), s1 // (2 * grid[1])
    # max. radius of polynomial around cenetr:
    rx, ry = cx, cy
    # for drawing a position indicator (circle):
    if radCircle is None:
        radCircle = max(1, rx // 10)
    # output array:
    out = np.zeros((s0, s1), dtype=np.uint8)
    # point of polynomial:
    pts = np.empty(shape=(1, 2 * nang, 2), dtype=np.int32)
    # takes grid[0]*grid[1] sample HOG values:
    samplesHOG = subCell2DFnArray(hog, lambda arr: arr[cx, cy], grid)
    mxHOG = samplesHOG.max()
    # sub array slices:
    slices = list(subCell2DSlices(out, grid))
    m = 0
    for m, hhh in enumerate(samplesHOG.reshape(grid[0] * grid[1], nang)):
        hhmax = hhh.max()
        hh = hhh / hhmax
        sout = out[slices[m][2:4]]
        for n, (o, a) in enumerate(zip(hh, angles)):
            pts[0, n, 0] = cx + np.cos(a) * o * rx
            pts[0, n, 1] = cy + np.sin(a) * o * ry
            pts[0, n + nang, 0] = cx + np.cos(a + np.pi) * o * rx
            pts[0, n + nang, 1] = cy + np.sin(a + np.pi) * o * ry

        cv2.fillPoly(sout, pts, int(255 * hhmax / mxHOG))
        cv2.circle(sout, (cx, cy), radCircle, 0, thickness=-1)

    return out
1336549
def random_draw(self, size=None):
        
        return scipy.asarray([scipy.stats.norm.rvs(loc=m, scale=s, size=size) for s, m in zip(self.sigma, self.mu)])
604104
def sample(img, coords):
    
    shape = img.get_shape().as_list()[1:]   # h, w, c
    batch = tf.shape(img)[0]
    shape2 = coords.get_shape().as_list()[1:3]  # h2, w2
    assert None not in shape2, coords.get_shape()
    max_coor = tf.constant([shape[0] - 1, shape[1] - 1], dtype=tf.float32)

    coords = tf.clip_by_value(coords, 0., max_coor)  # borderMode==repeat
    coords = tf.cast(coords, tf.int32)

    batch_index = tf.range(batch, dtype=tf.int32)
    batch_index = tf.reshape(batch_index, [-1, 1, 1, 1])
    batch_index = tf.tile(batch_index, [1, shape2[0], shape2[1], 1])    # bxh2xw2x1
    indices = tf.concat([batch_index, coords], axis=3)  # bxh2xw2x3
    sampled = tf.gather_nd(img, indices)
    return sampled
486726
def randomPairs(n_records, sample_size):
    
    n = int(n_records * (n_records - 1) / 2)

    if sample_size >= n:
        random_pairs = numpy.arange(n, dtype='uint')
    else:
        try:
            random_pairs = numpy.array(random.sample(range(n), sample_size),
                                       dtype='uint')
        except OverflowError:
            return randomPairsWithReplacement(n_records, sample_size)

    b = 1 - 2 * n_records

    root = (-b - 2 * numpy.sqrt(2 * (n - random_pairs) + 0.25)) / 2

    i = numpy.floor(root).astype('uint')
    j = numpy.rint(random_pairs + i * (b + i + 2) / 2 + 1).astype('uint')

    return zip(i, j)
157046
def discrete_random_draw(data, nb=1):
    ''' '''
    data = np.array(data)
    if not data.any():
        data = np.ones_like(data)
    data = data/data.sum()
    xk = np.arange(len(data))
    custm = stats.rv_discrete(name='custm', values=(xk, data))
    return custm.rvs(size=nb)
1032041
def setup_random_indices_local_geometry(self, coordination):
        
        self.icentral_site = 0
        self.indices = list(range(1, coordination + 1))
        np.random.shuffle(self.indices)
146528
def draw(self):
        '''
        
        '''
        sampled_arr = np.empty((self.__batch_size, self.__seq_len, self.__dim))

        for batch in range(self.__batch_size):
            key = np.random.randint(low=0, high=len(self.__midi_df_list))
            midi_df = self.__midi_df_list[key]
            program_arr = midi_df.program.drop_duplicates().values
            key = np.random.randint(low=0, high=program_arr.shape[0])
            program_key = program_arr[key]
            midi_df = midi_df[midi_df.program == program_key]
            if midi_df.shape[0] < self.__seq_len:
                raise ValueError("The length of musical performance (program: " + str(program_key) + " is short.")

            row = np.random.uniform(
                low=midi_df.start.min(), 
                high=midi_df.end.max() - (self.__seq_len * self.__time_fraction)
            )
            for seq in range(self.__seq_len):
                start = row + (seq * self.__time_fraction)
                end = row + ((seq+1) * self.__time_fraction)
                df = midi_df[(start <= midi_df.start) & (midi_df.start <= end)]
                sampled_arr[batch, seq] = self.__convert_into_feature(df)

        return sampled_arr
1250628
def compute_samples(channels, nsamples=None):
    '''
    
    '''
    return islice(izip(*(imap(sum, izip(*channel)) for channel in channels)), nsamples)
735952
def draw(self):
        '''
        
        '''
        observed_arr = self.extract_conditions()
        conv_arr = self.inference(observed_arr)

        if self.__conditon_noise_sampler is not None:
            self.__conditon_noise_sampler.output_shape = conv_arr.shape
            noise_arr = self.__conditon_noise_sampler.generate()
            conv_arr += noise_arr

        deconv_arr = self.__deconvolution_model.inference(conv_arr)
        return np.concatenate((deconv_arr, observed_arr), axis=1)
117289
def draw(self):
        '''
        
        '''
        return np.random.normal(loc=self.__mu, scale=self.__sigma, size=self.__output_shape)
1074591
private BitMatrix sampleGrid(BitMatrix image,
                               ResultPoint topLeft,
                               ResultPoint topRight,
                               ResultPoint bottomRight,
                               ResultPoint bottomLeft) throws NotFoundException {

    GridSampler sampler = GridSampler.getInstance();
    int dimension = getDimension();

    float low = dimension / 2.0f - nbCenterLayers;
    float high = dimension / 2.0f + nbCenterLayers;

    return sampler.sampleGrid(image,
                              dimension,
                              dimension,
                              low, low,   // topleft
                              high, low,  // topright
                              high, high, // bottomright
                              low, high,  // bottomleft
                              topLeft.getX(), topLeft.getY(),
                              topRight.getX(), topRight.getY(),
                              bottomRight.getX(), bottomRight.getY(),
                              bottomLeft.getX(), bottomLeft.getY());
  }
1000127
def random_sample(self, num_samples, df=None, replace=False, weights=None, random_state=100, axis='row'):
    '''
    
    '''

    if df is None:
      df = self.dat_to_df()

    if axis == 'row':
      axis = 0
    if axis == 'col':
      axis = 1

    df = self.export_df()
    df = df.sample(n=num_samples, replace=replace, weights=weights, random_state=random_state,  axis=axis)

    self.load_df(df)
617351
def random(self, shape, tf_fn, kwargs):
    
    # TODO(noam): can we make things better with stateless_random?
    slice_shape = self.slice_shape(shape)
    x = tf_fn(slice_shape, **kwargs)
    # TPU does not have seeds enabled.  Sync up the
    # random choices by zeroing out all but the first core per group of
    # identical slices, then allreducing by group.
    layout = self.tensor_layout(shape)
    # we need to sync across these axes.
    mesh_axes = [i for i in xrange(self.ndims)
                 if i not in layout.tensor_axis_to_mesh_axis]
    multiplier = 1.0
    for axis in mesh_axes:
      multiplier *= tf.cast(
          tf.equal(self.laid_out_pcoord(axis).one_slice, 0), x.dtype)
    x *= multiplier
    x = self.LaidOutTensor([x])
    x = self.allreduce(x, mesh_axes, "SUM")
    return x
52361
def random_samples(self, n):
        
        samples = self.samples
        inds = rand.randint(len(samples),size=int(n))

        newsamples = samples.iloc[inds]
        newsamples.reset_index(inplace=True)
        return newsamples
586598
def embedded_images(X, images, exclusion_radius=None, ax=None, cmap=None,
                    zoom=1, seed=None, frameon=False):
  ''''''
  assert X.shape[0] == images.shape[0], 'Unequal number of points and images'
  assert X.shape[1] == 2, 'X must be 2d'
  if ax is None:
    ax = plt.gca()
  if exclusion_radius is None:
    # TODO: make a smarter default based on image size and axis limits
    exclusion_radius = 1.
  if seed is not None:
    np.random.seed(seed)
  while X.shape[0] > 0:
    i = np.random.choice(X.shape[0])
    im = OffsetImage(images[i], zoom=zoom, cmap=cmap)
    ab = AnnotationBbox(im, X[i], xycoords='data', frameon=frameon)
    ax.add_artist(ab)
    dist = np.sqrt(np.square(X[i] - X).sum(axis=1))
    mask = (dist > exclusion_radius).ravel()
    X = X[mask]
    images = images[mask]
  return plt.show