How to use the batchflow.sampler.Sampler function in batchflow

To help you get started, we’ve selected a few batchflow examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github analysiscenter / batchflow / batchflow / sampler.py View on Github external
the sampler/weight for multiplication.

        Returns
        -------
        Sampler
            result of the multiplication.
        """
        result = Sampler()

        # case of numeric other
        if isinstance(other, (float, int)):
            result.sample = self.sample
            result.weight *= other

        # when other is a Sampler
        elif isinstance(other, Sampler):
            def concat_sample(size):
                """ Sampling procedure of a product of two samplers.
                """
                _left = self.sample(size)
                _right = other.sample(size)
                return np.concatenate([_left, _right], axis=1)

            result.sample = concat_sample

        return result
github analysiscenter / batchflow / batchflow / sampler.py View on Github external
""" Apply a transformation to the sampler.

        Build new sampler, which sampling function is given by `transform(self.sample(size))``.

        Parameters
        ----------
        transform : callable
            function, that takes ndarray of shape (size, dim_sampler) and produces
            ndarray of shape (size, new_dim_sampler).

        Returns
        -------
        Sampler
            instance of class Sampler with redefined method `sample`.
        """
        result = Sampler()
        result.sample = lambda size: transform(self.sample(size))
        return result
github analysiscenter / batchflow / batchflow / sampler.py View on Github external
The result is the mixture of two samplers. Weights are taken from
        samplers' weight-attributes.

        Parameters
        ----------
        other : Sampler
            the sampler to be added to self.

        Returns
        -------
        Sampler
            resulting mixture of two samplers.
        """
        # init new Sampler
        result = Sampler()

        # calculate probs of samplers in mixture
        _ws = np.array([self.weight, other.weight])
        result.weight = np.sum(_ws)
        _normed = _ws / np.sum(_ws)

        # redefine the sampling procedure of a sampler
        def concat_sample(size):
            """ Sampling procedure of a mixture of two samplers.
            """
            _up_size = np.random.binomial(size, _normed[0])
            _low_size = size - _up_size

            _up = self.sample(size=_up_size)
            _low = other.sample(size=_low_size)
            _sample = np.concatenate([_up, _low])
github analysiscenter / batchflow / batchflow / sampler.py View on Github external
cond &= expr(sample).all(axis=1)

                # check that truncation-prob is not to small
                _share = np.sum(cond) / batch_size
                if _share < SMALL_SHARE and ctr > 0:
                    raise ValueError('Probability of region of interest is too small. Try other truncation bounds')

                # get points from region of interest
                samples.append(sample[cond])
                cumulated += np.sum(cond)
                ctr += 1

            return np.concatenate(samples)[:size]

        # init new Sampler, define its sampling-method
        result = Sampler()
        result.sample = truncated

        return result
github analysiscenter / batchflow / batchflow / sampler.py View on Github external
# get points from region of interest
                samples.append(sample[cond])
                cumulated += np.sum(cond)
                ctr += 1

            return np.concatenate(samples)[:size]

        # init new Sampler, define its sampling-method
        result = Sampler()
        result.sample = truncated

        return result


class ConstantSampler(Sampler):
    """ Sampler of a constant.

    Parameters
    ----------
    constant : int, str, float, list
        constant, associated with the Sampler. Can be multidimensional,
        e.g. list or np.ndarray.

    Attributes
    ----------
    constant : np.array
        vectorized constant, associated with the Sampler.

    """
    def __init__(self, constant, **kwargs):
        self.constant = np.array(constant).reshape(1, -1)
github analysiscenter / batchflow / batchflow / sampler.py View on Github external
Attributes
    ----------
    array : np.array
    """
    def __init__(self, array, **kwargs):
        self.array = np.array(array)
        if self.array.ndim != 1:
            raise ValueError('Array must be 1-dimensional but {}-dimensional were given'.format(self.array.ndim))
        super().__init__(array, **kwargs)

    def sample(self, size):
        sample = np.random.choice(self.array, size=size)
        return sample

class NumpySampler(Sampler):
    """ Sampler based on a distribution from np.random.

    Parameters
    ----------
    name : str
        name of a distribution (method from np.random) or its alias.
    seed : int
        random seed for setting up sampler's state.
    **kwargs
        additional keyword-arguments defining properties of specific
        distribution. E.g., ``loc`` for name='normal'.

    Attributes
    ----------
    name : str
        name of a distribution (method from np.random).
github analysiscenter / batchflow / batchflow / sampler.py View on Github external
The result is the mixture of two samplers. Weights are taken from
        samplers' weight-attributes.

        Parameters
        ----------
        other : Sampler
            the sampler to be added to self.

        Returns
        -------
        Sampler
            resulting mixture of two samplers.
        """
        # init new Sampler
        result = Sampler()

        # calculate probs of samplers in mixture
        _ws = np.array([self.weight, other.weight])
        result.weight = np.sum(_ws)
        _normed = _ws / np.sum(_ws)

        # redefine the sampling procedure of a sampler
        def concat_sample(size):
            """ Sampling procedure of a mixture of two samplers.
            """
            _up_size = np.random.binomial(size, _normed[0])
            _low_size = size - _up_size

            _up = self.sample(size=_up_size)
            _low = other.sample(size=_low_size)
            _sample = np.concatenate([_up, _low])
github analysiscenter / batchflow / batchflow / sampler.py View on Github external
----------
        size : int
            the size of sample to be generated.

        Returns
        -------
        np.ndarray
            array of shape (size, Sampler's dimension).
        """
        sampler = self.distr.rvs
        sample = sampler(size=size, random_state=self.state)
        if len(sample.shape) == 1:
            sample = sample.reshape(-1, 1)
        return sample

class HistoSampler(Sampler):
    """ Sampler based on a histogram, output of `np.histogramdd`.

    Parameters
    ----------
    histo : tuple
        histogram, on which the sampler is based.
        Make sure that it is unnormalized (`normed=False` in `np.histogramdd`).
    edges : list
        list of len=histo_dimension, contains edges of bins along axes.
    seed : int
        random seed for setting up sampler's state.

    Attributes
    ----------
    bins : np.ndarray
        bins of base-histogram (see `np.histogramdd`).