Python scipy.stats.gamma() Examples

The following are code examples for showing how to use scipy.stats.gamma(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: LaserTOF   Author: kyleuckert   File: test_distributions.py    MIT License 6 votes vote down vote up
def test_erlang_runtimewarning(self):
        # erlang should generate a RuntimeWarning if a non-integer
        # shape parameter is used.
        with warnings.catch_warnings():
            warnings.simplefilter("error", RuntimeWarning)

            # The non-integer shape parameter 1.3 should trigger a
            # RuntimeWarning
            assert_raises(RuntimeWarning,
                          stats.erlang.rvs, 1.3, loc=0, scale=1, size=4)

            # Calling the fit method with `f0` set to an integer should
            # *not* trigger a RuntimeWarning.  It should return the same
            # values as gamma.fit(...).
            data = [0.5, 1.0, 2.0, 4.0]
            result_erlang = stats.erlang.fit(data, f0=1)
            result_gamma = stats.gamma.fit(data, f0=1)
            assert_allclose(result_erlang, result_gamma, rtol=1e-3) 
Example 2
Project: att   Author: Centre-Alt-Rendiment-Esportiu   File: test_distributions.py    GNU General Public License v3.0 6 votes vote down vote up
def test_erlang_runtimewarning(self):
        # erlang should generate a RuntimeWarning if a non-integer
        # shape parameter is used.
        with warnings.catch_warnings():
            warnings.simplefilter("error", RuntimeWarning)

            # The non-integer shape parameter 1.3 should trigger a RuntimeWarning
            assert_raises(RuntimeWarning,
                              stats.erlang.rvs, 1.3, loc=0, scale=1, size=4)

            # Calling the fit method with `f0` set to an integer should
            # *not* trigger a RuntimeWarning.  It should return the same
            # values as gamma.fit(...).
            data = [0.5, 1.0, 2.0, 4.0]
            result_erlang = stats.erlang.fit(data, f0=1)
            result_gamma = stats.gamma.fit(data, f0=1)
            assert_allclose(result_erlang, result_gamma, rtol=1e-3) 
Example 3
Project: revrand   Author: NICTA   File: slm.py    Apache License 2.0 6 votes vote down vote up
def __init__(self,
                 basis=LinearBasis(),
                 var=Parameter(gamma(1.), Positive()),
                 tol=1e-8,
                 maxiter=1000,
                 nstarts=100,
                 random_state=None
                 ):
        """See class docstring."""
        self.basis = basis
        self.var = var
        self.tol = tol
        self.maxiter = maxiter
        self.nstarts = nstarts
        self.random_state = random_state
        self.random_ = check_random_state(random_state) 
Example 4
Project: revrand   Author: NICTA   File: basis_functions.py    Apache License 2.0 6 votes vote down vote up
def __init__(self,
                 nbases,
                 Xdim,
                 mean=Parameter(norm_dist(), Bound()),
                 lenscale=Parameter(gamma(1.), Positive()),
                 regularizer=None,
                 random_state=None
                 ):
        """See this class's docstring."""
        self.random_state = random_state  # for repr
        self._random = check_random_state(random_state)
        self._init_dims(nbases, Xdim)
        self._params = [self._init_param(mean),
                        self._init_param(lenscale)]
        self._init_matrices()
        super(_LengthScaleBasis, self).__init__(regularizer) 
Example 5
Project: revrand   Author: NICTA   File: test_bases.py    Apache License 2.0 6 votes vote down vote up
def test_grad_concat(make_gaus_data):

    X, _, _, _ = make_gaus_data
    N, d = X.shape

    base = bs.LinearBasis(onescol=False) + bs.LinearBasis(onescol=False)

    assert list(base.grad(X)) == []

    base += bs.RadialBasis(centres=X)

    G = base.grad(X, 1.)

    assert list(G)[0].shape == (N, N + 2 * d)

    D = 200
    base += bs.RandomRBF(nbases=D, Xdim=d,
                         lenscale=Parameter(gamma(1), Positive(), shape=(d,)))
    G = base.grad(X, 1., np.ones(d))
    dims = [(N, N + (D + d) * 2), (N, N + (D + d) * 2, d)]

    for g, d in zip(G, dims):
        assert g.shape == d 
Example 6
Project: revrand   Author: NICTA   File: test_optimize.py    Apache License 2.0 6 votes vote down vote up
def test_logstruc_params(make_quadratic, make_random):

    random = make_random
    a, b, c, data, _ = make_quadratic

    w0 = [Parameter(random.gamma(2, size=(2,)), Positive()),
          Parameter(random.randn(), Bound())
          ]

    qobj_struc = lambda w12, w3, data: q_struc(w12, w3, data, qobj)
    assert_opt = lambda Eab, Ec: \
        np.allclose((a, b, c), (Eab[0], Eab[1], Ec), atol=1e-3, rtol=0)

    nmin = structured_minimizer(logtrick_minimizer(minimize))
    res = nmin(qobj_struc, w0, args=(data,), jac=True, method='L-BFGS-B')
    assert_opt(*res.x)

    nsgd = structured_sgd(logtrick_sgd(sgd))
    res = nsgd(qobj_struc, w0, data, eval_obj=True, random_state=make_random)
    assert_opt(*res.x)

    qf_struc = lambda w12, w3, data: q_struc(w12, w3, data, qfun)
    qg_struc = lambda w12, w3, data: q_struc(w12, w3, data, qgrad)
    res = nmin(qf_struc, w0, args=(data,), jac=qg_struc, method='L-BFGS-B')
    assert_opt(*res.x) 
Example 7
Project: ble5-nrf52-mac   Author: tomasero   File: test_distributions.py    MIT License 6 votes vote down vote up
def test_expect(self):
        # smoke test the expect method of the frozen distribution
        # only take a gamma w/loc and scale and poisson with loc specified
        def func(x):
            return x

        gm = stats.gamma(a=2, loc=3, scale=4)
        gm_val = gm.expect(func, lb=1, ub=2, conditional=True)
        gamma_val = stats.gamma.expect(func, args=(2,), loc=3, scale=4,
                                       lb=1, ub=2, conditional=True)
        assert_allclose(gm_val, gamma_val)

        p = stats.poisson(3, loc=4)
        p_val = p.expect(func)
        poisson_val = stats.poisson.expect(func, args=(3,), loc=4)
        assert_allclose(p_val, poisson_val) 
Example 8
Project: ble5-nrf52-mac   Author: tomasero   File: test_distributions.py    MIT License 6 votes vote down vote up
def test_erlang_runtimewarning(self):
        # erlang should generate a RuntimeWarning if a non-integer
        # shape parameter is used.
        with warnings.catch_warnings():
            warnings.simplefilter("error", RuntimeWarning)

            # The non-integer shape parameter 1.3 should trigger a
            # RuntimeWarning
            assert_raises(RuntimeWarning,
                          stats.erlang.rvs, 1.3, loc=0, scale=1, size=4)

            # Calling the fit method with `f0` set to an integer should
            # *not* trigger a RuntimeWarning.  It should return the same
            # values as gamma.fit(...).
            data = [0.5, 1.0, 2.0, 4.0]
            result_erlang = stats.erlang.fit(data, f0=1)
            result_gamma = stats.gamma.fit(data, f0=1)
            assert_allclose(result_erlang, result_gamma, rtol=1e-3) 
Example 9
Project: poker   Author: surgebiswas   File: test_distributions.py    MIT License 6 votes vote down vote up
def test_erlang_runtimewarning(self):
        # erlang should generate a RuntimeWarning if a non-integer
        # shape parameter is used.
        with warnings.catch_warnings():
            warnings.simplefilter("error", RuntimeWarning)

            # The non-integer shape parameter 1.3 should trigger a
            # RuntimeWarning
            assert_raises(RuntimeWarning,
                          stats.erlang.rvs, 1.3, loc=0, scale=1, size=4)

            # Calling the fit method with `f0` set to an integer should
            # *not* trigger a RuntimeWarning.  It should return the same
            # values as gamma.fit(...).
            data = [0.5, 1.0, 2.0, 4.0]
            result_erlang = stats.erlang.fit(data, f0=1)
            result_gamma = stats.gamma.fit(data, f0=1)
            assert_allclose(result_erlang, result_gamma, rtol=1e-3) 
Example 10
Project: P3_image_processing   Author: latedude2   File: test_distributions.py    MIT License 6 votes vote down vote up
def test_expect(self):
        # smoke test the expect method of the frozen distribution
        # only take a gamma w/loc and scale and poisson with loc specified
        def func(x):
            return x

        gm = stats.gamma(a=2, loc=3, scale=4)
        gm_val = gm.expect(func, lb=1, ub=2, conditional=True)
        gamma_val = stats.gamma.expect(func, args=(2,), loc=3, scale=4,
                                       lb=1, ub=2, conditional=True)
        assert_allclose(gm_val, gamma_val)

        p = stats.poisson(3, loc=4)
        p_val = p.expect(func)
        poisson_val = stats.poisson.expect(func, args=(3,), loc=4)
        assert_allclose(p_val, poisson_val) 
Example 11
Project: P3_image_processing   Author: latedude2   File: test_distributions.py    MIT License 6 votes vote down vote up
def test_erlang_runtimewarning(self):
        # erlang should generate a RuntimeWarning if a non-integer
        # shape parameter is used.
        with warnings.catch_warnings():
            warnings.simplefilter("error", RuntimeWarning)

            # The non-integer shape parameter 1.3 should trigger a
            # RuntimeWarning
            assert_raises(RuntimeWarning,
                          stats.erlang.rvs, 1.3, loc=0, scale=1, size=4)

            # Calling the fit method with `f0` set to an integer should
            # *not* trigger a RuntimeWarning.  It should return the same
            # values as gamma.fit(...).
            data = [0.5, 1.0, 2.0, 4.0]
            result_erlang = stats.erlang.fit(data, f0=1)
            result_gamma = stats.gamma.fit(data, f0=1)
            assert_allclose(result_erlang, result_gamma, rtol=1e-3) 
Example 12
Project: chainer   Author: chainer   File: test_gamma.py    MIT License 6 votes vote down vote up
def setUp_configure(self):
        from scipy import stats
        self.dist = distributions.Gamma
        self.scipy_dist = stats.gamma

        self.test_targets = set(
            ['batch_shape', 'entropy', 'event_shape', 'log_prob', 'mean',
             'sample', 'support', 'variance'])

        k = utils.force_array(
            numpy.random.uniform(0, 5, self.shape).astype(numpy.float32))
        theta = utils.force_array(
            numpy.random.uniform(0, 5, self.shape).astype(numpy.float32))
        self.params = {'k': k, 'theta': theta}
        self.scipy_params = {'a': k, 'scale': theta}

        self.support = 'positive' 
Example 13
Project: cprior   Author: guillermo-navas-palencia   File: gamma.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def cdf(self, x):
        """
        Cumulative distribution function of the posterior distribution.

        Parameters
        ----------
        x : array-like
            Quantiles.

        Returns
        -------
        cdf : numpy.ndarray
            Cumulative distribution function evaluated at x.
        """
        return stats.gamma(a=self._shape_posterior, loc=0,
                           scale=1.0 / self._rate_posterior).cdf(x) 
Example 14
Project: cprior   Author: guillermo-navas-palencia   File: gamma.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def ppf(self, q):
        """
        Percent point function (quantile) of the posterior distribution.

        Parameters
        ----------
        x : array-like
            Lower tail probability.

        Returns
        -------
        ppf : numpy.ndarray
            Quantile corresponding to the lower tail probability q.
        """
        return stats.gamma(a=self._shape_posterior, loc=0,
                           scale=1.0 / self._rate_posterior).ppf(q) 
Example 15
Project: cprior   Author: guillermo-navas-palencia   File: gamma.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def rvs(self, size=1, random_state=None):
        """
        Random variates of the posterior distribution.

        Parameters
        ----------
        size : int (default=1)
            Number of random variates.

        random_state : int or None (default=None)
            The seed used by the random number generator.

        Returns
        -------
        rvs : numpy.ndarray or scalar
            Random variates of given size.
        """
        return stats.gamma(a=self._shape_posterior, loc=0,
                           scale=1.0 / self._rate_posterior).rvs(
                           size=size, random_state=random_state) 
Example 16
Project: cprior   Author: guillermo-navas-palencia   File: gamma.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def _expected_value_max_mlhs(self, variants, mlhs_samples):
        """Compute expected value of the maximum of beta random variables."""
        r = np.arange(1, mlhs_samples + 1)
        np.random.shuffle(r)
        v = (r - 0.5) / mlhs_samples
        v = v[..., np.newaxis]

        variant_params = [(self.models[v].shape_posterior,
                          self.models[v].rate_posterior)
                          for v in variants]

        n = len(variant_params)
        aa, bb = map(np.array, zip(*variant_params))
        cc = aa / bb

        xx = stats.gamma(a=aa + 1, loc=0, scale=1.0 / bb).ppf(v)

        return np.sum([cc[i] * np.prod([
                      special.gammainc(aa[j], bb[j] * xx[:, i])
                      for j in range(n) if j != i], axis=0)
                      for i in range(n)], axis=0).mean() 
Example 17
Project: LaserTOF   Author: kyleuckert   File: test_distributions.py    MIT License 5 votes vote down vote up
def test_pdf(self):
        # a few test cases to compare with R
        pdf = stats.gamma.pdf(90, 394, scale=1./5)
        assert_almost_equal(pdf, 0.002312341)

        pdf = stats.gamma.pdf(3, 10, scale=1./5)
        assert_almost_equal(pdf, 0.1620358) 
Example 18
Project: LaserTOF   Author: kyleuckert   File: test_distributions.py    MIT License 5 votes vote down vote up
def test_logpdf(self):
        # Regression test for Ticket #1326: cornercase avoid nan with 0*log(0)
        # situation
        logpdf = stats.gamma.logpdf(0, 1)
        assert_almost_equal(logpdf, 0) 
Example 19
Project: LaserTOF   Author: kyleuckert   File: test_distributions.py    MIT License 5 votes vote down vote up
def test_fix_fit_gamma(self):
        x = np.arange(1, 6)
        meanlog = np.log(x).mean()

        # A basic test of gamma.fit with floc=0.
        floc = 0
        a, loc, scale = stats.gamma.fit(x, floc=floc)
        s = np.log(x.mean()) - meanlog
        assert_almost_equal(np.log(a) - special.digamma(a), s, decimal=5)
        assert_equal(loc, floc)
        assert_almost_equal(scale, x.mean()/a, decimal=8)

        # Regression tests for gh-2514.
        # The problem was that if `floc=0` was given, any other fixed
        # parameters were ignored.
        f0 = 1
        floc = 0
        a, loc, scale = stats.gamma.fit(x, f0=f0, floc=floc)
        assert_equal(a, f0)
        assert_equal(loc, floc)
        assert_almost_equal(scale, x.mean()/a, decimal=8)

        f0 = 2
        floc = 0
        a, loc, scale = stats.gamma.fit(x, f0=f0, floc=floc)
        assert_equal(a, f0)
        assert_equal(loc, floc)
        assert_almost_equal(scale, x.mean()/a, decimal=8)

        # loc and scale fixed.
        floc = 0
        fscale = 2
        a, loc, scale = stats.gamma.fit(x, floc=floc, fscale=fscale)
        assert_equal(loc, floc)
        assert_equal(scale, fscale)
        c = meanlog - np.log(fscale)
        assert_almost_equal(special.digamma(a), c) 
Example 20
Project: LaserTOF   Author: kyleuckert   File: test_distributions.py    MIT License 5 votes vote down vote up
def test_fshapes(self):
        # take a beta distribution, with shapes='a, b', and make sure that
        # fa is equivalent to f0, and fb is equivalent to f1
        a, b = 3., 4.
        x = stats.beta.rvs(a, b, size=100, random_state=1234)
        res_1 = stats.beta.fit(x, f0=3.)
        res_2 = stats.beta.fit(x, fa=3.)
        assert_allclose(res_1, res_2, atol=1e-12, rtol=1e-12)

        res_2 = stats.beta.fit(x, fix_a=3.)
        assert_allclose(res_1, res_2, atol=1e-12, rtol=1e-12)

        res_3 = stats.beta.fit(x, f1=4.)
        res_4 = stats.beta.fit(x, fb=4.)
        assert_allclose(res_3, res_4, atol=1e-12, rtol=1e-12)

        res_4 = stats.beta.fit(x, fix_b=4.)
        assert_allclose(res_3, res_4, atol=1e-12, rtol=1e-12)

        # cannot specify both positional and named args at the same time
        assert_raises(ValueError, stats.beta.fit, x, fa=1, f0=2)

        # check that attempting to fix all parameters raises a ValueError
        assert_raises(ValueError, stats.beta.fit, x, fa=0, f1=1,
                      floc=2, fscale=3)

        # check that specifying floc, fscale and fshapes works for
        # beta and gamma which override the generic fit method
        res_5 = stats.beta.fit(x, fa=3., floc=0, fscale=1)
        aa, bb, ll, ss = res_5
        assert_equal([aa, ll, ss], [3., 0, 1])

        # gamma distribution
        a = 3.
        data = stats.gamma.rvs(a, size=100)
        aa, ll, ss = stats.gamma.fit(data, fa=a)
        assert_equal(aa, a) 
Example 21
Project: LaserTOF   Author: kyleuckert   File: test_distributions.py    MIT License 5 votes vote down vote up
def test_regression_ticket_1316():
    # The following was raising an exception, because _construct_default_doc()
    # did not handle the default keyword extradoc=None.  See ticket #1316.
    g = stats._continuous_distns.gamma_gen(name='gamma') 
Example 22
Project: LaserTOF   Author: kyleuckert   File: test_distributions.py    MIT License 5 votes vote down vote up
def test_distribution_too_many_args():
    # Check that a TypeError is raised when too many args are given to a method
    # Regression test for ticket 1815.
    x = np.linspace(0.1, 0.7, num=5)
    assert_raises(TypeError, stats.gamma.pdf, x, 2, 3, loc=1.0)
    assert_raises(TypeError, stats.gamma.pdf, x, 2, 3, 4, loc=1.0)
    assert_raises(TypeError, stats.gamma.pdf, x, 2, 3, 4, 5)
    assert_raises(TypeError, stats.gamma.pdf, x, 2, 3, loc=1.0, scale=0.5)
    assert_raises(TypeError, stats.gamma.rvs, 2., 3, loc=1.0, scale=0.5)
    assert_raises(TypeError, stats.gamma.cdf, x, 2., 3, loc=1.0, scale=0.5)
    assert_raises(TypeError, stats.gamma.ppf, x, 2., 3, loc=1.0, scale=0.5)
    assert_raises(TypeError, stats.gamma.stats, 2., 3, loc=1.0, scale=0.5)
    assert_raises(TypeError, stats.gamma.entropy, 2., 3, loc=1.0, scale=0.5)
    assert_raises(TypeError, stats.gamma.fit, x, 2., 3, loc=1.0, scale=0.5)

    # These should not give errors
    stats.gamma.pdf(x, 2, 3)  # loc=3
    stats.gamma.pdf(x, 2, 3, 4)  # loc=3, scale=4
    stats.gamma.stats(2., 3)
    stats.gamma.stats(2., 3, 4)
    stats.gamma.stats(2., 3, 4, 'mv')
    stats.gamma.rvs(2., 3, 4, 5)
    stats.gamma.fit(stats.gamma.rvs(2., size=7), 2.)

    # Also for a discrete distribution
    stats.geom.pmf(x, 2, loc=3)  # no error, loc=3
    assert_raises(TypeError, stats.geom.pmf, x, 2, 3, 4)
    assert_raises(TypeError, stats.geom.pmf, x, 2, 3, loc=4)

    # And for distributions with 0, 2 and 3 args respectively
    assert_raises(TypeError, stats.expon.pdf, x, 3, loc=1.0)
    assert_raises(TypeError, stats.exponweib.pdf, x, 3, 4, 5, loc=1.0)
    assert_raises(TypeError, stats.exponweib.pdf, x, 3, 4, 5, 0.1, 0.1)
    assert_raises(TypeError, stats.ncf.pdf, x, 3, 4, 5, 6, loc=1.0)
    assert_raises(TypeError, stats.ncf.pdf, x, 3, 4, 5, 6, 1.0, scale=0.5)
    stats.ncf.pdf(x, 3, 4, 5, 6, 1.0)  # 3 args, plus loc/scale 
Example 23
Project: att   Author: Centre-Alt-Rendiment-Esportiu   File: test_distributions.py    GNU General Public License v3.0 5 votes vote down vote up
def test_pdf(self):
        # a few test cases to compare with R
        pdf = stats.gamma.pdf(90, 394, scale=1./5)
        assert_almost_equal(pdf, 0.002312341)

        pdf = stats.gamma.pdf(3, 10, scale=1./5)
        assert_almost_equal(pdf, 0.1620358) 
Example 24
Project: att   Author: Centre-Alt-Rendiment-Esportiu   File: test_distributions.py    GNU General Public License v3.0 5 votes vote down vote up
def test_logpdf(self):
        # Regression test for Ticket #1326: cornercase avoid nan with 0*log(0)
        # situation
        logpdf = stats.gamma.logpdf(0,1)
        assert_almost_equal(logpdf, 0) 
Example 25
Project: att   Author: Centre-Alt-Rendiment-Esportiu   File: test_distributions.py    GNU General Public License v3.0 5 votes vote down vote up
def test_fix_fit_gamma(self):
        x = np.arange(1, 6)
        meanlog = np.log(x).mean()

        # A basic test of gamma.fit with floc=0.
        floc = 0
        a, loc, scale = stats.gamma.fit(x, floc=floc)
        s = np.log(x.mean()) - meanlog
        assert_almost_equal(np.log(a) - special.digamma(a), s, decimal=5)
        assert_equal(loc, floc)
        assert_almost_equal(scale, x.mean()/a, decimal=8)

        # Regression tests for gh-2514.
        # The problem was that if `floc=0` was given, any other fixed
        # parameters were ignored.
        f0 = 1
        floc = 0
        a, loc, scale = stats.gamma.fit(x, f0=f0, floc=floc)
        assert_equal(a, f0)
        assert_equal(loc, floc)
        assert_almost_equal(scale, x.mean()/a, decimal=8)

        f0 = 2
        floc = 0
        a, loc, scale = stats.gamma.fit(x, f0=f0, floc=floc)
        assert_equal(a, f0)
        assert_equal(loc, floc)
        assert_almost_equal(scale, x.mean()/a, decimal=8)

        # loc and scale fixed.
        floc = 0
        fscale = 2
        a, loc, scale = stats.gamma.fit(x, floc=floc, fscale=fscale)
        assert_equal(loc, floc)
        assert_equal(scale, fscale)
        c = meanlog - np.log(fscale)
        assert_almost_equal(special.digamma(a), c) 
Example 26
Project: att   Author: Centre-Alt-Rendiment-Esportiu   File: test_distributions.py    GNU General Public License v3.0 5 votes vote down vote up
def test_distribution_too_many_args():
    # Check that a TypeError is raised when too many args are given to a method
    # Regression test for ticket 1815.
    x = np.linspace(0.1, 0.7, num=5)
    assert_raises(TypeError, stats.gamma.pdf, x, 2, 3, loc=1.0)
    assert_raises(TypeError, stats.gamma.pdf, x, 2, 3, 4, loc=1.0)
    assert_raises(TypeError, stats.gamma.pdf, x, 2, 3, 4, 5)
    assert_raises(TypeError, stats.gamma.pdf, x, 2, 3, loc=1.0, scale=0.5)
    assert_raises(TypeError, stats.gamma.rvs, 2., 3, loc=1.0, scale=0.5)
    assert_raises(TypeError, stats.gamma.cdf, x, 2., 3, loc=1.0, scale=0.5)
    assert_raises(TypeError, stats.gamma.ppf, x, 2., 3, loc=1.0, scale=0.5)
    assert_raises(TypeError, stats.gamma.stats, 2., 3, loc=1.0, scale=0.5)
    assert_raises(TypeError, stats.gamma.entropy, 2., 3, loc=1.0, scale=0.5)
    assert_raises(TypeError, stats.gamma.fit, x, 2., 3, loc=1.0, scale=0.5)

    # These should not give errors
    stats.gamma.pdf(x, 2, 3)  # loc=3
    stats.gamma.pdf(x, 2, 3, 4)  # loc=3, scale=4
    stats.gamma.stats(2., 3)
    stats.gamma.stats(2., 3, 4)
    stats.gamma.stats(2., 3, 4, 'mv')
    stats.gamma.rvs(2., 3, 4, 5)
    stats.gamma.fit(stats.gamma.rvs(2., size=7), 2.)

    # Also for a discrete distribution
    stats.geom.pmf(x, 2, loc=3)  # no error, loc=3
    assert_raises(TypeError, stats.geom.pmf, x, 2, 3, 4)
    assert_raises(TypeError, stats.geom.pmf, x, 2, 3, loc=4)

    # And for distributions with 0, 2 and 3 args respectively
    assert_raises(TypeError, stats.expon.pdf, x, 3, loc=1.0)
    assert_raises(TypeError, stats.exponweib.pdf, x, 3, 4, 5, loc=1.0)
    assert_raises(TypeError, stats.exponweib.pdf, x, 3, 4, 5, 0.1, 0.1)
    assert_raises(TypeError, stats.ncf.pdf, x, 3, 4, 5, 6, loc=1.0)
    assert_raises(TypeError, stats.ncf.pdf, x, 3, 4, 5, 6, 1.0, scale=0.5)
    stats.ncf.pdf(x, 3, 4, 5, 6, 1.0)  # 3 args, plus loc/scale 
Example 27
Project: revrand   Author: NICTA   File: likelihoods.py    Apache License 2.0 5 votes vote down vote up
def __init__(self, var=Parameter(gamma(1., scale=1), Positive())):
        """See class docstring."""
        self.params = var 
Example 28
Project: revrand   Author: NICTA   File: basis_functions.py    Apache License 2.0 5 votes vote down vote up
def __init__(
            self,
            centres,
            lenscale=Parameter(gamma(1.), Positive()),
            regularizer=None
    ):
        """See this class's docstring."""
        self.M, self.d = centres.shape
        self.C = centres
        self._init_lenscale(lenscale)
        super(_LengthScaleBasis, self).__init__(regularizer) 
Example 29
Project: revrand   Author: NICTA   File: basis_functions.py    Apache License 2.0 5 votes vote down vote up
def __init__(self,
                 nbases,
                 Xdim,
                 lenscale=Parameter(gamma(1.), Positive()),
                 regularizer=None,
                 random_state=None
                 ):
        """See this class's docstring."""
        self.d = Xdim
        self.n = nbases
        self.random_state = random_state  # for repr
        self._random = check_random_state(random_state)
        self.W = self._weightsamples()
        self._init_lenscale(lenscale)
        super(_LengthScaleBasis, self).__init__(regularizer) 
Example 30
Project: revrand   Author: NICTA   File: basis_functions.py    Apache License 2.0 5 votes vote down vote up
def __init__(self,
                 nbases,
                 Xdim,
                 lenscale=Parameter(gamma(1.), Positive()),
                 regularizer=None,
                 random_state=None
                 ):
        """See this class's docstring."""
        self.random_state = random_state  # for repr
        self._random = check_random_state(random_state)
        self._init_dims(nbases, Xdim)
        self._init_lenscale(lenscale)
        self._init_matrices()
        super(_LengthScaleBasis, self).__init__(regularizer) 
Example 31
Project: revrand   Author: NICTA   File: test_btypes.py    Apache License 2.0 5 votes vote down vote up
def test_parameter():

    # Test "Null" parameter
    p = Parameter()
    assert p.shape == (0,)
    assert p.rvs() == []
    assert p.has_value is False
    assert p.is_random is False

    # Test values
    v = 1.
    p = Parameter(v, Positive())
    assert p.value == v
    assert p.bounds.lower > 0
    assert p.bounds.upper is None
    assert p.rvs() == v
    assert p.has_value is True
    assert p.is_random is False

    # Test distributions
    p = Parameter(gamma(1), Positive())
    assert np.shape(p.rvs()) == ()
    assert p.has_value is True
    assert p.is_random is True

    p = Parameter(gamma(1), Positive(), shape=(2,))
    assert np.shape(p.rvs()) == (2,)
    assert Positive().check(p.rvs())

    p = Parameter(gamma(1), Bound(1, 2), shape=(10, 5))
    assert np.shape(p.rvs()) == (10, 5)
    assert Bound(1, 2).check(p.rvs()) 
Example 32
Project: vnpy_crypto   Author: birforce   File: ex_transf2.py    MIT License 5 votes vote down vote up
def test_loggamma():
    #'Results for expgamma'
    loggammaexpg = LogTransf_gen(stats.gamma)
    cdftr = loggammaexpg._cdf(1,10)
    cdfst = stats.loggamma.cdf(1,10)
    assert_almost_equal(cdfst, cdftr, 14)

    cdftr = loggammaexpg._cdf(2,15)
    cdfst = stats.loggamma.cdf(2,15)
    assert_almost_equal(cdfst, cdftr, 14) 
Example 33
Project: vnpy_crypto   Author: birforce   File: ex_transf2.py    MIT License 5 votes vote down vote up
def __init__(self):
        self.dist = LogTransf_gen(stats.gamma)
        self.trargs = (10,)
        self.trkwds = {}
        self.statsdist = stats.loggamma
        self.stargs = (10,)
        self.stkwds = {} 
Example 34
Project: vnpy_crypto   Author: birforce   File: sppatch.py    MIT License 5 votes vote down vote up
def _fitstart(self, x):
    '''example method, method of moment estimator as starting values

    Parameters
    ----------
    x : array
        data for which the parameters are estimated

    Returns
    -------
    est : tuple
        preliminary estimates used as starting value for fitting, not
        necessarily a consistent estimator

    Notes
    -----
    This needs to be written and attached to each individual distribution

    This example was written for the gamma distribution, but not verified
    with literature

    '''
    loc = np.min([x.min(),0])
    a = 4/stats.skew(x)**2
    scale = np.std(x) / np.sqrt(a)
    return (a, loc, scale) 
Example 35
Project: ble5-nrf52-mac   Author: tomasero   File: test_distributions.py    MIT License 5 votes vote down vote up
def test_stats(self):
        a, b = 1, 0.5
        gamma = np.sqrt(a**2 - b**2)
        v_stats = (b / gamma, a**2 / gamma**3, 3.0 * b / (a * np.sqrt(gamma)),
                   3.0 * (1 + 4 * b**2 / a**2) / gamma)
        assert_equal(v_stats, stats.norminvgauss.stats(a, b, moments='mvsk')) 
Example 36
Project: ble5-nrf52-mac   Author: tomasero   File: test_distributions.py    MIT License 5 votes vote down vote up
def test_pdf(self):
        # a few test cases to compare with R
        pdf = stats.gamma.pdf(90, 394, scale=1./5)
        assert_almost_equal(pdf, 0.002312341)

        pdf = stats.gamma.pdf(3, 10, scale=1./5)
        assert_almost_equal(pdf, 0.1620358) 
Example 37
Project: ble5-nrf52-mac   Author: tomasero   File: test_distributions.py    MIT License 5 votes vote down vote up
def test_logpdf(self):
        # Regression test for Ticket #1326: cornercase avoid nan with 0*log(0)
        # situation
        logpdf = stats.gamma.logpdf(0, 1)
        assert_almost_equal(logpdf, 0) 
Example 38
Project: ble5-nrf52-mac   Author: tomasero   File: test_distributions.py    MIT License 5 votes vote down vote up
def test_cdf_nolan_samples(self):
        """ Test cdf values against Nolan's stablec.exe output
            see - http://fs2.american.edu/jpnolan/www/stable/stable.html

            There's a known limitation of Nolan's executable for alpha < 0.2.

            Repeat following with beta = -1, -.5, 0, .5 and 1
                stablec.exe <<
                2 # cdf
                1 # Nolan S equivalent to S0 in scipy
                .25,2,.25 # alpha
                -1,-1,0 # beta
                -10,10,1 # x
                1,0 # gamma, delta
                2 # output file
        """
        data = np.load(os.path.abspath(os.path.join(os.path.dirname(__file__),
                                                 'data/stable-cdf-sample-data.npy')))

        data = np.core.records.fromarrays(data.T, names='x,p,alpha,beta')

        tests = [
            # zolatarev is accurate for all values
            ['zolotarev', None, 8, None],

            # fft accuracy poor, very poor alpha < 1
            ['fft', 0, 2, lambda r: r['alpha'] > 1],
        ]
        for ix, (default_method, fft_min_points, decimal_places, filter_func) in enumerate(tests):
            stats.levy_stable.pdf_default_method = default_method
            stats.levy_stable.pdf_fft_min_points_threshold = fft_min_points
            subdata = data[filter_func(data)] if filter_func is not None else data
            with suppress_warnings() as sup:
                sup.record(RuntimeWarning, 'FFT method is considered ' +
                           'experimental for cumulative distribution ' +
                           'function evaluations.*')
                p = stats.levy_stable.cdf(subdata['x'], subdata['alpha'], subdata['beta'], scale=1, loc=0)
                subdata2 = rec_append_fields(subdata, 'calc', p)
                failures = subdata2[(np.abs(p-subdata['p']) >= 1.5*10.**(-decimal_places)) | np.isnan(p)]
                assert_almost_equal(p, subdata['p'], decimal_places, "cdf test %s failed with method '%s'\n%s" % (ix, default_method, failures), verbose=False) 
Example 39
Project: ble5-nrf52-mac   Author: tomasero   File: test_distributions.py    MIT License 5 votes vote down vote up
def test_fshapes(self):
        # take a beta distribution, with shapes='a, b', and make sure that
        # fa is equivalent to f0, and fb is equivalent to f1
        a, b = 3., 4.
        x = stats.beta.rvs(a, b, size=100, random_state=1234)
        res_1 = stats.beta.fit(x, f0=3.)
        res_2 = stats.beta.fit(x, fa=3.)
        assert_allclose(res_1, res_2, atol=1e-12, rtol=1e-12)

        res_2 = stats.beta.fit(x, fix_a=3.)
        assert_allclose(res_1, res_2, atol=1e-12, rtol=1e-12)

        res_3 = stats.beta.fit(x, f1=4.)
        res_4 = stats.beta.fit(x, fb=4.)
        assert_allclose(res_3, res_4, atol=1e-12, rtol=1e-12)

        res_4 = stats.beta.fit(x, fix_b=4.)
        assert_allclose(res_3, res_4, atol=1e-12, rtol=1e-12)

        # cannot specify both positional and named args at the same time
        assert_raises(ValueError, stats.beta.fit, x, fa=1, f0=2)

        # check that attempting to fix all parameters raises a ValueError
        assert_raises(ValueError, stats.beta.fit, x, fa=0, f1=1,
                      floc=2, fscale=3)

        # check that specifying floc, fscale and fshapes works for
        # beta and gamma which override the generic fit method
        res_5 = stats.beta.fit(x, fa=3., floc=0, fscale=1)
        aa, bb, ll, ss = res_5
        assert_equal([aa, ll, ss], [3., 0, 1])

        # gamma distribution
        a = 3.
        data = stats.gamma.rvs(a, size=100)
        aa, ll, ss = stats.gamma.fit(data, fa=a)
        assert_equal(aa, a) 
Example 40
Project: ble5-nrf52-mac   Author: tomasero   File: test_distributions.py    MIT License 5 votes vote down vote up
def setup_method(self):
        np.random.seed(1234)

    # Test that a frozen distribution gives the same results as the original
    # object.
    #
    # Only tested for the normal distribution (with loc and scale specified)
    # and for the gamma distribution (with a shape parameter specified). 
Example 41
Project: ble5-nrf52-mac   Author: tomasero   File: test_distributions.py    MIT License 5 votes vote down vote up
def test_distribution_too_many_args():
    np.random.seed(1234)

    # Check that a TypeError is raised when too many args are given to a method
    # Regression test for ticket 1815.
    x = np.linspace(0.1, 0.7, num=5)
    assert_raises(TypeError, stats.gamma.pdf, x, 2, 3, loc=1.0)
    assert_raises(TypeError, stats.gamma.pdf, x, 2, 3, 4, loc=1.0)
    assert_raises(TypeError, stats.gamma.pdf, x, 2, 3, 4, 5)
    assert_raises(TypeError, stats.gamma.pdf, x, 2, 3, loc=1.0, scale=0.5)
    assert_raises(TypeError, stats.gamma.rvs, 2., 3, loc=1.0, scale=0.5)
    assert_raises(TypeError, stats.gamma.cdf, x, 2., 3, loc=1.0, scale=0.5)
    assert_raises(TypeError, stats.gamma.ppf, x, 2., 3, loc=1.0, scale=0.5)
    assert_raises(TypeError, stats.gamma.stats, 2., 3, loc=1.0, scale=0.5)
    assert_raises(TypeError, stats.gamma.entropy, 2., 3, loc=1.0, scale=0.5)
    assert_raises(TypeError, stats.gamma.fit, x, 2., 3, loc=1.0, scale=0.5)

    # These should not give errors
    stats.gamma.pdf(x, 2, 3)  # loc=3
    stats.gamma.pdf(x, 2, 3, 4)  # loc=3, scale=4
    stats.gamma.stats(2., 3)
    stats.gamma.stats(2., 3, 4)
    stats.gamma.stats(2., 3, 4, 'mv')
    stats.gamma.rvs(2., 3, 4, 5)
    stats.gamma.fit(stats.gamma.rvs(2., size=7), 2.)

    # Also for a discrete distribution
    stats.geom.pmf(x, 2, loc=3)  # no error, loc=3
    assert_raises(TypeError, stats.geom.pmf, x, 2, 3, 4)
    assert_raises(TypeError, stats.geom.pmf, x, 2, 3, loc=4)

    # And for distributions with 0, 2 and 3 args respectively
    assert_raises(TypeError, stats.expon.pdf, x, 3, loc=1.0)
    assert_raises(TypeError, stats.exponweib.pdf, x, 3, 4, 5, loc=1.0)
    assert_raises(TypeError, stats.exponweib.pdf, x, 3, 4, 5, 0.1, 0.1)
    assert_raises(TypeError, stats.ncf.pdf, x, 3, 4, 5, 6, loc=1.0)
    assert_raises(TypeError, stats.ncf.pdf, x, 3, 4, 5, 6, 1.0, scale=0.5)
    stats.ncf.pdf(x, 3, 4, 5, 6, 1.0)  # 3 args, plus loc/scale 
Example 42
Project: Computable   Author: ktraunmueller   File: test_distributions.py    MIT License 5 votes vote down vote up
def test_pdf(self):
        # a few test cases to compare with R
        pdf = stats.gamma.pdf(90, 394, scale=1./5)
        assert_almost_equal(pdf, 0.002312341)

        pdf = stats.gamma.pdf(3, 10, scale=1./5)
        assert_almost_equal(pdf, 0.1620358) 
Example 43
Project: Computable   Author: ktraunmueller   File: test_distributions.py    MIT License 5 votes vote down vote up
def test_logpdf(self):
        # Regression test for Ticket #1326: cornercase avoid nan with 0*log(0)
        # situation
        logpdf = stats.gamma.logpdf(0,1)
        assert_almost_equal(logpdf, 0) 
Example 44
Project: Computable   Author: ktraunmueller   File: test_distributions.py    MIT License 5 votes vote down vote up
def test_fix_fit_gamma(self):
        x = np.arange(1, 6)
        meanlog = np.log(x).mean()

        # A basic test of gamma.fit with floc=0.
        floc = 0
        a, loc, scale = stats.gamma.fit(x, floc=floc)
        s = np.log(x.mean()) - meanlog
        assert_almost_equal(np.log(a) - special.digamma(a), s, decimal=5)
        assert_equal(loc, floc)
        assert_almost_equal(scale, x.mean()/a, decimal=8)

        # Regression tests for gh-2514.
        # The problem was that if `floc=0` was given, any other fixed
        # parameters were ignored.
        f0 = 1
        floc = 0
        a, loc, scale = stats.gamma.fit(x, f0=f0, floc=floc)
        assert_equal(a, f0)
        assert_equal(loc, floc)
        assert_almost_equal(scale, x.mean()/a, decimal=8)

        f0 = 2
        floc = 0
        a, loc, scale = stats.gamma.fit(x, f0=f0, floc=floc)
        assert_equal(a, f0)
        assert_equal(loc, floc)
        assert_almost_equal(scale, x.mean()/a, decimal=8)

        # loc and scale fixed.
        floc = 0
        fscale = 2
        a, loc, scale = stats.gamma.fit(x, floc=floc, fscale=fscale)
        assert_equal(loc, floc)
        assert_equal(scale, fscale)
        c = meanlog - np.log(fscale)
        assert_almost_equal(special.digamma(a), c) 
Example 45
Project: Computable   Author: ktraunmueller   File: test_distributions.py    MIT License 5 votes vote down vote up
def test_regression_ticket_1316():
    # The following was raising an exception, because _construct_default_doc()
    # did not handle the default keyword extradoc=None.  See ticket #1316.
    g = stats.distributions.gamma_gen(name='gamma') 
Example 46
Project: poker   Author: surgebiswas   File: test_distributions.py    MIT License 5 votes vote down vote up
def test_pdf(self):
        # a few test cases to compare with R
        pdf = stats.gamma.pdf(90, 394, scale=1./5)
        assert_almost_equal(pdf, 0.002312341)

        pdf = stats.gamma.pdf(3, 10, scale=1./5)
        assert_almost_equal(pdf, 0.1620358) 
Example 47
Project: poker   Author: surgebiswas   File: test_distributions.py    MIT License 5 votes vote down vote up
def test_logpdf(self):
        # Regression test for Ticket #1326: cornercase avoid nan with 0*log(0)
        # situation
        logpdf = stats.gamma.logpdf(0, 1)
        assert_almost_equal(logpdf, 0) 
Example 48
Project: poker   Author: surgebiswas   File: test_distributions.py    MIT License 5 votes vote down vote up
def test_fix_fit_gamma(self):
        x = np.arange(1, 6)
        meanlog = np.log(x).mean()

        # A basic test of gamma.fit with floc=0.
        floc = 0
        a, loc, scale = stats.gamma.fit(x, floc=floc)
        s = np.log(x.mean()) - meanlog
        assert_almost_equal(np.log(a) - special.digamma(a), s, decimal=5)
        assert_equal(loc, floc)
        assert_almost_equal(scale, x.mean()/a, decimal=8)

        # Regression tests for gh-2514.
        # The problem was that if `floc=0` was given, any other fixed
        # parameters were ignored.
        f0 = 1
        floc = 0
        a, loc, scale = stats.gamma.fit(x, f0=f0, floc=floc)
        assert_equal(a, f0)
        assert_equal(loc, floc)
        assert_almost_equal(scale, x.mean()/a, decimal=8)

        f0 = 2
        floc = 0
        a, loc, scale = stats.gamma.fit(x, f0=f0, floc=floc)
        assert_equal(a, f0)
        assert_equal(loc, floc)
        assert_almost_equal(scale, x.mean()/a, decimal=8)

        # loc and scale fixed.
        floc = 0
        fscale = 2
        a, loc, scale = stats.gamma.fit(x, floc=floc, fscale=fscale)
        assert_equal(loc, floc)
        assert_equal(scale, fscale)
        c = meanlog - np.log(fscale)
        assert_almost_equal(special.digamma(a), c) 
Example 49
Project: poker   Author: surgebiswas   File: test_distributions.py    MIT License 5 votes vote down vote up
def test_fshapes(self):
        # take a beta distribution, with shapes='a, b', and make sure that
        # fa is equivalent to f0, and fb is equivalent to f1
        a, b = 3., 4.
        x = stats.beta.rvs(a, b, size=100, random_state=1234)
        res_1 = stats.beta.fit(x, f0=3.)
        res_2 = stats.beta.fit(x, fa=3.)
        assert_allclose(res_1, res_2, atol=1e-12, rtol=1e-12)

        res_2 = stats.beta.fit(x, fix_a=3.)
        assert_allclose(res_1, res_2, atol=1e-12, rtol=1e-12)

        res_3 = stats.beta.fit(x, f1=4.)
        res_4 = stats.beta.fit(x, fb=4.)
        assert_allclose(res_3, res_4, atol=1e-12, rtol=1e-12)

        res_4 = stats.beta.fit(x, fix_b=4.)
        assert_allclose(res_3, res_4, atol=1e-12, rtol=1e-12)

        # cannot specify both positional and named args at the same time
        assert_raises(ValueError, stats.beta.fit, x, fa=1, f0=2)

        # check that attempting to fix all parameters raises a ValueError
        assert_raises(ValueError, stats.beta.fit, x, fa=0, f1=1,
                      floc=2, fscale=3)

        # check that specifying floc, fscale and fshapes works for
        # beta and gamma which override the generic fit method
        res_5 = stats.beta.fit(x, fa=3., floc=0, fscale=1)
        aa, bb, ll, ss = res_5
        assert_equal([aa, ll, ss], [3., 0, 1])

        # gamma distribution
        a = 3.
        data = stats.gamma.rvs(a, size=100)
        aa, ll, ss = stats.gamma.fit(data, fa=a)
        assert_equal(aa, a) 
Example 50
Project: poker   Author: surgebiswas   File: test_distributions.py    MIT License 5 votes vote down vote up
def test_regression_ticket_1316():
    # The following was raising an exception, because _construct_default_doc()
    # did not handle the default keyword extradoc=None.  See ticket #1316.
    g = stats._continuous_distns.gamma_gen(name='gamma') 
Example 51
Project: poker   Author: surgebiswas   File: test_distributions.py    MIT License 5 votes vote down vote up
def test_distribution_too_many_args():
    # Check that a TypeError is raised when too many args are given to a method
    # Regression test for ticket 1815.
    x = np.linspace(0.1, 0.7, num=5)
    assert_raises(TypeError, stats.gamma.pdf, x, 2, 3, loc=1.0)
    assert_raises(TypeError, stats.gamma.pdf, x, 2, 3, 4, loc=1.0)
    assert_raises(TypeError, stats.gamma.pdf, x, 2, 3, 4, 5)
    assert_raises(TypeError, stats.gamma.pdf, x, 2, 3, loc=1.0, scale=0.5)
    assert_raises(TypeError, stats.gamma.rvs, 2., 3, loc=1.0, scale=0.5)
    assert_raises(TypeError, stats.gamma.cdf, x, 2., 3, loc=1.0, scale=0.5)
    assert_raises(TypeError, stats.gamma.ppf, x, 2., 3, loc=1.0, scale=0.5)
    assert_raises(TypeError, stats.gamma.stats, 2., 3, loc=1.0, scale=0.5)
    assert_raises(TypeError, stats.gamma.entropy, 2., 3, loc=1.0, scale=0.5)
    assert_raises(TypeError, stats.gamma.fit, x, 2., 3, loc=1.0, scale=0.5)

    # These should not give errors
    stats.gamma.pdf(x, 2, 3)  # loc=3
    stats.gamma.pdf(x, 2, 3, 4)  # loc=3, scale=4
    stats.gamma.stats(2., 3)
    stats.gamma.stats(2., 3, 4)
    stats.gamma.stats(2., 3, 4, 'mv')
    stats.gamma.rvs(2., 3, 4, 5)
    stats.gamma.fit(stats.gamma.rvs(2., size=7), 2.)

    # Also for a discrete distribution
    stats.geom.pmf(x, 2, loc=3)  # no error, loc=3
    assert_raises(TypeError, stats.geom.pmf, x, 2, 3, 4)
    assert_raises(TypeError, stats.geom.pmf, x, 2, 3, loc=4)

    # And for distributions with 0, 2 and 3 args respectively
    assert_raises(TypeError, stats.expon.pdf, x, 3, loc=1.0)
    assert_raises(TypeError, stats.exponweib.pdf, x, 3, 4, 5, loc=1.0)
    assert_raises(TypeError, stats.exponweib.pdf, x, 3, 4, 5, 0.1, 0.1)
    assert_raises(TypeError, stats.ncf.pdf, x, 3, 4, 5, 6, loc=1.0)
    assert_raises(TypeError, stats.ncf.pdf, x, 3, 4, 5, 6, 1.0, scale=0.5)
    stats.ncf.pdf(x, 3, 4, 5, 6, 1.0)  # 3 args, plus loc/scale 
Example 52
Project: distcan   Author: sglyon   File: univariate.py    MIT License 5 votes vote down vote up
def __init__(self, alpha, beta):
        self.alpha = alpha
        self.beta = beta

        # set dist before calling super's __init__
        self.dist = st.gamma(alpha, scale=beta)
        super(Gamma, self).__init__() 
Example 53
Project: distcan   Author: sglyon   File: univariate.py    MIT License 5 votes vote down vote up
def __init__(self, mu, v0, shape, scale):
        self.mu = mu
        self.v0 = v0
        self.shape = shape
        self.scale = scale

        # define docstring arguments
        pdf_tex = r"p(x;\alpha,\beta)=\frac{x^{\alpha-1}e^{-x/\beta}}"
        pdf_tex += r"{\Gamma(\alpha)\beta^{\alpha}}"
        cdf_tex = r"\frac{\gamma(\alpha, \beta x)}{\Gamma(\alpha)}" + "\n\n"
        cdf_tex += r"where :math:`\gamma(\cdot)` is the incomplete"
        cdf_tex += " gamma function"

        self._str = "Normal(mu=%.5f, sigma=%.5f, alpha=%.5f, beta=%.5f)" 
Example 54
Project: distcan   Author: sglyon   File: univariate.py    MIT License 5 votes vote down vote up
def pdf(self, x, sig2):
        m, v, sh, sc = self.mu, self.v0, self.shape, self.scale
        Zinv = sc**sh / gamma(sh) / sqrt(v * 2*pi)
        return (Zinv * 1./(np.sqrt(sig2) * sig2**(sh+1.)) *
                np.exp(-sc/sig2 - 0.5/(sig2*v)*(x-m)**2.0)) 
Example 55
Project: dmipy   Author: AthenaEPI   File: distributions.py    MIT License 5 votes vote down vote up
def __call__(self, **kwargs):
        r"""
        Parameters
        ----------
        diameter : float or array, shape (N)
            cylinder (axon) diameter in meters.

        Returns
        -------
        Pgamma : float or array, shape (N)
            probability of cylinder diameter for given alpha and beta.
        """
        alpha = kwargs.get('alpha', self.alpha)
        beta = kwargs.get('beta', self.beta)

        gamma_dist = stats.gamma(alpha, scale=beta)
        start_point = interpolate.bisplev(alpha, beta, self.start_interpolator)
        end_point = interpolate.bisplev(alpha, beta, self.end_interpolator)
        start_point = max(start_point, 1e-8)
        radii = np.linspace(start_point, end_point, self.Nsteps)
        normalization = self.norm_func(radii)
        radii_pdf = gamma_dist.pdf(radii)
        radii_pdf_area = radii_pdf * normalization
        radii_pdf_normalized = (
            radii_pdf_area /
            np.trapz(x=radii, y=radii_pdf_area)
        )
        return radii, radii_pdf_normalized 
Example 56
Project: P3_image_processing   Author: latedude2   File: test_distributions.py    MIT License 5 votes vote down vote up
def test_stats(self):
        a, b = 1, 0.5
        gamma = np.sqrt(a**2 - b**2)
        v_stats = (b / gamma, a**2 / gamma**3, 3.0 * b / (a * np.sqrt(gamma)),
                   3.0 * (1 + 4 * b**2 / a**2) / gamma)
        assert_equal(v_stats, stats.norminvgauss.stats(a, b, moments='mvsk')) 
Example 57
Project: P3_image_processing   Author: latedude2   File: test_distributions.py    MIT License 5 votes vote down vote up
def test_pdf(self):
        # a few test cases to compare with R
        pdf = stats.gamma.pdf(90, 394, scale=1./5)
        assert_almost_equal(pdf, 0.002312341)

        pdf = stats.gamma.pdf(3, 10, scale=1./5)
        assert_almost_equal(pdf, 0.1620358) 
Example 58
Project: P3_image_processing   Author: latedude2   File: test_distributions.py    MIT License 5 votes vote down vote up
def test_logpdf(self):
        # Regression test for Ticket #1326: cornercase avoid nan with 0*log(0)
        # situation
        logpdf = stats.gamma.logpdf(0, 1)
        assert_almost_equal(logpdf, 0) 
Example 59
Project: P3_image_processing   Author: latedude2   File: test_distributions.py    MIT License 5 votes vote down vote up
def test_cdf_nolan_samples(self):
        """ Test cdf values against Nolan's stablec.exe output
            see - http://fs2.american.edu/jpnolan/www/stable/stable.html

            There's a known limitation of Nolan's executable for alpha < 0.2.

            Repeat following with beta = -1, -.5, 0, .5 and 1
                stablec.exe <<
                2 # cdf
                1 # Nolan S equivalent to S0 in scipy
                .25,2,.25 # alpha
                -1,-1,0 # beta
                -10,10,1 # x
                1,0 # gamma, delta
                2 # output file
        """
        data = np.load(os.path.abspath(os.path.join(os.path.dirname(__file__),
                                                 'data/stable-cdf-sample-data.npy')))

        data = np.core.records.fromarrays(data.T, names='x,p,alpha,beta')

        tests = [
            # zolatarev is accurate for all values
            ['zolotarev', None, 8, None],

            # fft accuracy poor, very poor alpha < 1
            ['fft', 0, 2, lambda r: r['alpha'] > 1],
        ]
        for ix, (default_method, fft_min_points, decimal_places, filter_func) in enumerate(tests):
            stats.levy_stable.pdf_default_method = default_method
            stats.levy_stable.pdf_fft_min_points_threshold = fft_min_points
            subdata = data[filter_func(data)] if filter_func is not None else data
            with suppress_warnings() as sup:
                sup.record(RuntimeWarning, 'FFT method is considered ' +
                           'experimental for cumulative distribution ' +
                           'function evaluations.*')
                p = stats.levy_stable.cdf(subdata['x'], subdata['alpha'], subdata['beta'], scale=1, loc=0)
                subdata2 = rec_append_fields(subdata, 'calc', p)
                failures = subdata2[(np.abs(p-subdata['p']) >= 1.5*10.**(-decimal_places)) | np.isnan(p)]
                assert_almost_equal(p, subdata['p'], decimal_places, "cdf test %s failed with method '%s'\n%s" % (ix, default_method, failures), verbose=False) 
Example 60
Project: P3_image_processing   Author: latedude2   File: test_distributions.py    MIT License 5 votes vote down vote up
def test_fshapes(self):
        # take a beta distribution, with shapes='a, b', and make sure that
        # fa is equivalent to f0, and fb is equivalent to f1
        a, b = 3., 4.
        x = stats.beta.rvs(a, b, size=100, random_state=1234)
        res_1 = stats.beta.fit(x, f0=3.)
        res_2 = stats.beta.fit(x, fa=3.)
        assert_allclose(res_1, res_2, atol=1e-12, rtol=1e-12)

        res_2 = stats.beta.fit(x, fix_a=3.)
        assert_allclose(res_1, res_2, atol=1e-12, rtol=1e-12)

        res_3 = stats.beta.fit(x, f1=4.)
        res_4 = stats.beta.fit(x, fb=4.)
        assert_allclose(res_3, res_4, atol=1e-12, rtol=1e-12)

        res_4 = stats.beta.fit(x, fix_b=4.)
        assert_allclose(res_3, res_4, atol=1e-12, rtol=1e-12)

        # cannot specify both positional and named args at the same time
        assert_raises(ValueError, stats.beta.fit, x, fa=1, f0=2)

        # check that attempting to fix all parameters raises a ValueError
        assert_raises(ValueError, stats.beta.fit, x, fa=0, f1=1,
                      floc=2, fscale=3)

        # check that specifying floc, fscale and fshapes works for
        # beta and gamma which override the generic fit method
        res_5 = stats.beta.fit(x, fa=3., floc=0, fscale=1)
        aa, bb, ll, ss = res_5
        assert_equal([aa, ll, ss], [3., 0, 1])

        # gamma distribution
        a = 3.
        data = stats.gamma.rvs(a, size=100)
        aa, ll, ss = stats.gamma.fit(data, fa=a)
        assert_equal(aa, a) 
Example 61
Project: P3_image_processing   Author: latedude2   File: test_distributions.py    MIT License 5 votes vote down vote up
def setup_method(self):
        np.random.seed(1234)

    # Test that a frozen distribution gives the same results as the original
    # object.
    #
    # Only tested for the normal distribution (with loc and scale specified)
    # and for the gamma distribution (with a shape parameter specified). 
Example 62
Project: P3_image_processing   Author: latedude2   File: test_distributions.py    MIT License 5 votes vote down vote up
def test_distribution_too_many_args():
    np.random.seed(1234)

    # Check that a TypeError is raised when too many args are given to a method
    # Regression test for ticket 1815.
    x = np.linspace(0.1, 0.7, num=5)
    assert_raises(TypeError, stats.gamma.pdf, x, 2, 3, loc=1.0)
    assert_raises(TypeError, stats.gamma.pdf, x, 2, 3, 4, loc=1.0)
    assert_raises(TypeError, stats.gamma.pdf, x, 2, 3, 4, 5)
    assert_raises(TypeError, stats.gamma.pdf, x, 2, 3, loc=1.0, scale=0.5)
    assert_raises(TypeError, stats.gamma.rvs, 2., 3, loc=1.0, scale=0.5)
    assert_raises(TypeError, stats.gamma.cdf, x, 2., 3, loc=1.0, scale=0.5)
    assert_raises(TypeError, stats.gamma.ppf, x, 2., 3, loc=1.0, scale=0.5)
    assert_raises(TypeError, stats.gamma.stats, 2., 3, loc=1.0, scale=0.5)
    assert_raises(TypeError, stats.gamma.entropy, 2., 3, loc=1.0, scale=0.5)
    assert_raises(TypeError, stats.gamma.fit, x, 2., 3, loc=1.0, scale=0.5)

    # These should not give errors
    stats.gamma.pdf(x, 2, 3)  # loc=3
    stats.gamma.pdf(x, 2, 3, 4)  # loc=3, scale=4
    stats.gamma.stats(2., 3)
    stats.gamma.stats(2., 3, 4)
    stats.gamma.stats(2., 3, 4, 'mv')
    stats.gamma.rvs(2., 3, 4, 5)
    stats.gamma.fit(stats.gamma.rvs(2., size=7), 2.)

    # Also for a discrete distribution
    stats.geom.pmf(x, 2, loc=3)  # no error, loc=3
    assert_raises(TypeError, stats.geom.pmf, x, 2, 3, 4)
    assert_raises(TypeError, stats.geom.pmf, x, 2, 3, loc=4)

    # And for distributions with 0, 2 and 3 args respectively
    assert_raises(TypeError, stats.expon.pdf, x, 3, loc=1.0)
    assert_raises(TypeError, stats.exponweib.pdf, x, 3, 4, 5, loc=1.0)
    assert_raises(TypeError, stats.exponweib.pdf, x, 3, 4, 5, 0.1, 0.1)
    assert_raises(TypeError, stats.ncf.pdf, x, 3, 4, 5, 6, loc=1.0)
    assert_raises(TypeError, stats.ncf.pdf, x, 3, 4, 5, 6, 1.0, scale=0.5)
    stats.ncf.pdf(x, 3, 4, 5, 6, 1.0)  # 3 args, plus loc/scale 
Example 63
Project: chainer   Author: chainer   File: test_gamma.py    MIT License 5 votes vote down vote up
def sample_for_test(self):
        smp = numpy.random.gamma(
            shape=5., size=self.sample_shape + self.shape
        ).astype(numpy.float32)
        return smp 
Example 64
Project: cprior   Author: guillermo-navas-palencia   File: gamma.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def func_ppf(x, a0, b0, a1, b1, p):
    """Function CDF ratio of gamma function for root-finding."""
    return special.betainc(a0, a1, x / (x + b1 / b0)) - p 
Example 65
Project: cprior   Author: guillermo-navas-palencia   File: gamma.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def func_mv_ppf(x, variant_params, p):
    """Function CDF of max of gamma random variables for root-finding."""
    cdf = 1.0
    for (a, b) in variant_params:
        cdf *= special.gammainc(a, b * x)
    return cdf - p 
Example 66
Project: cprior   Author: guillermo-navas-palencia   File: gamma.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def mean(self):
        """
        Mean of the posterior distribution.

        Returns
        -------
        mean : float
        """
        return stats.gamma(a=self._shape_posterior, loc=0,
                           scale=1.0 / self._rate_posterior).mean() 
Example 67
Project: cprior   Author: guillermo-navas-palencia   File: gamma.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def var(self):
        """
        Variance of the posterior distribution.

        Returns
        -------
        var : float
        """
        return stats.gamma(a=self._shape_posterior, loc=0,
                           scale=1.0 / self._rate_posterior).var() 
Example 68
Project: cprior   Author: guillermo-navas-palencia   File: gamma.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def std(self):
        """
        Standard deviation of the posterior distribution.

        Returns
        -------
        std : float
        """
        return stats.gamma(a=self._shape_posterior, loc=0,
                           scale=1.0 / self._rate_posterior).std() 
Example 69
Project: GraphicDesignPatternByPython   Author: Relph1119   File: test_distributions.py    MIT License 5 votes vote down vote up
def test_stats(self):
        a, b = 1, 0.5
        gamma = np.sqrt(a**2 - b**2)
        v_stats = (b / gamma, a**2 / gamma**3, 3.0 * b / (a * np.sqrt(gamma)),
                   3.0 * (1 + 4 * b**2 / a**2) / gamma)
        assert_equal(v_stats, stats.norminvgauss.stats(a, b, moments='mvsk')) 
Example 70
Project: LaserTOF   Author: kyleuckert   File: test_distributions.py    MIT License 4 votes vote down vote up
def test_gamma(self):
        a = 2.0
        dist = stats.gamma
        frozen = stats.gamma(a)

        result_f = frozen.pdf(20.0)
        result = dist.pdf(20.0, a)
        assert_equal(result_f, result)

        result_f = frozen.cdf(20.0)
        result = dist.cdf(20.0, a)
        assert_equal(result_f, result)

        result_f = frozen.ppf(0.25)
        result = dist.ppf(0.25, a)
        assert_equal(result_f, result)

        result_f = frozen.isf(0.25)
        result = dist.isf(0.25, a)
        assert_equal(result_f, result)

        result_f = frozen.sf(10.0)
        result = dist.sf(10.0, a)
        assert_equal(result_f, result)

        result_f = frozen.median()
        result = dist.median(a)
        assert_equal(result_f, result)

        result_f = frozen.mean()
        result = dist.mean(a)
        assert_equal(result_f, result)

        result_f = frozen.var()
        result = dist.var(a)
        assert_equal(result_f, result)

        result_f = frozen.std()
        result = dist.std(a)
        assert_equal(result_f, result)

        result_f = frozen.entropy()
        result = dist.entropy(a)
        assert_equal(result_f, result)

        result_f = frozen.moment(2)
        result = dist.moment(2, a)
        assert_equal(result_f, result)

        assert_equal(frozen.a, frozen.dist.a)
        assert_equal(frozen.b, frozen.dist.b) 
Example 71
Project: att   Author: Centre-Alt-Rendiment-Esportiu   File: test_distributions.py    GNU General Public License v3.0 4 votes vote down vote up
def test_gamma(self):
        a = 2.0
        dist = stats.gamma
        frozen = stats.gamma(a)

        result_f = frozen.pdf(20.0)
        result = dist.pdf(20.0, a)
        assert_equal(result_f, result)

        result_f = frozen.cdf(20.0)
        result = dist.cdf(20.0, a)
        assert_equal(result_f, result)

        result_f = frozen.ppf(0.25)
        result = dist.ppf(0.25, a)
        assert_equal(result_f, result)

        result_f = frozen.isf(0.25)
        result = dist.isf(0.25, a)
        assert_equal(result_f, result)

        result_f = frozen.sf(10.0)
        result = dist.sf(10.0, a)
        assert_equal(result_f, result)

        result_f = frozen.median()
        result = dist.median(a)
        assert_equal(result_f, result)

        result_f = frozen.mean()
        result = dist.mean(a)
        assert_equal(result_f, result)

        result_f = frozen.var()
        result = dist.var(a)
        assert_equal(result_f, result)

        result_f = frozen.std()
        result = dist.std(a)
        assert_equal(result_f, result)

        result_f = frozen.entropy()
        result = dist.entropy(a)
        assert_equal(result_f, result)

        result_f = frozen.moment(2)
        result = dist.moment(2, a)
        assert_equal(result_f, result) 
Example 72
Project: revrand   Author: NICTA   File: basis_functions.py    Apache License 2.0 4 votes vote down vote up
def __init__(self, regularizer=None):
        r"""
        Construct this an instance of this class.

        This is also a good place to set non-learnable properties, and bounded
        Parameter types. An example Basis class with parameters may be

        Example
        -------
        >>> def __init__(self, # doctest: +SKIP
        ...              property,
        ...              param=Parameter(1, Bound()),
        ...              regularizer=Parameter(gamma(1.), Positive())
        ...              ):
        ...
        ...     self.property = property
        ...     self._params = param_init
        ...     super().__init__(regularizer)

        All the ``params`` property does is inform algorithms of the intitial
        value and any bounds this basis object has, or it can be used as a
        default value. This will need to correspond to any parameters input
        into the ``transform`` and ``grad`` methods, where it can be used as
        the default value. All basis class objects MUST have a ``params``
        property, which is either:

        - one Parameter object for an optimisable parameter, see btypes.py.
          Parameter objects with ``None`` values are interpreted as having no
          parameters.
        - a list of ``Parameter`` objects, one for each optimisable parameter.

        Also, all basis classes can have a way of setting the
        ``self.regularizer`` property, since this informs the regression
        algorithms of the (initial) values of the weights regularizer
        corresponding to this basis. If it is not set, it will take on a
        default value of ``Parameter(gamma(1.), Positive())``.
        """
        if regularizer is not None:
            if not regularizer.is_scalar:
                raise ValueError("Regularizer parameters have to be scalar!")
            if regularizer.bounds.lower <= 0:
                raise ValueError("Regularizer has to be bounded below by 0!")
            self._regularizer = regularizer 
Example 73
Project: vnpy_crypto   Author: birforce   File: transformed.py    MIT License 4 votes vote down vote up
def examples_transf():
    ##lognormal = ExpTransf(a=0.0, xa=-10.0, name = 'Log transformed normal')
    ##print(lognormal.cdf(1)
    ##print(stats.lognorm.cdf(1,1)
    ##print(lognormal.stats()
    ##print(stats.lognorm.stats(1)
    ##print(lognormal.rvs(size=10)

    print('Results for lognormal')
    lognormalg = ExpTransf_gen(stats.norm, a=0, name = 'Log transformed normal general')
    print(lognormalg.cdf(1))
    print(stats.lognorm.cdf(1,1))
    print(lognormalg.stats())
    print(stats.lognorm.stats(1))
    print(lognormalg.rvs(size=5))

    ##print('Results for loggamma'
    ##loggammag = ExpTransf_gen(stats.gamma)
    ##print(loggammag._cdf(1,10)
    ##print(stats.loggamma.cdf(1,10)

    print('Results for expgamma')
    loggammaexpg = LogTransf_gen(stats.gamma)
    print(loggammaexpg._cdf(1,10))
    print(stats.loggamma.cdf(1,10))
    print(loggammaexpg._cdf(2,15))
    print(stats.loggamma.cdf(2,15))


    # this requires change in scipy.stats.distribution
    #print(loggammaexpg.cdf(1,10)

    print('Results for loglaplace')
    loglaplaceg = LogTransf_gen(stats.laplace)
    print(loglaplaceg._cdf(2,10))
    print(stats.loglaplace.cdf(2,10))
    loglaplaceexpg = ExpTransf_gen(stats.laplace)
    print(loglaplaceexpg._cdf(2,10))




## copied from transformtwo.py 
Example 74
Project: vnpy_crypto   Author: birforce   File: ex_extras.py    MIT License 4 votes vote down vote up
def examples_transf():
    ##lognormal = ExpTransf(a=0.0, xa=-10.0, name = 'Log transformed normal')
    ##print(lognormal.cdf(1))
    ##print(stats.lognorm.cdf(1,1))
    ##print(lognormal.stats())
    ##print(stats.lognorm.stats(1))
    ##print(lognormal.rvs(size=10))

    print('Results for lognormal')
    lognormalg = ExpTransf_gen(stats.norm, a=0, name = 'Log transformed normal general')
    print(lognormalg.cdf(1))
    print(stats.lognorm.cdf(1,1))
    print(lognormalg.stats())
    print(stats.lognorm.stats(1))
    print(lognormalg.rvs(size=5))

    ##print('Results for loggamma')
    ##loggammag = ExpTransf_gen(stats.gamma)
    ##print(loggammag._cdf(1,10))
    ##print(stats.loggamma.cdf(1,10))

    print('Results for expgamma')
    loggammaexpg = LogTransf_gen(stats.gamma)
    print(loggammaexpg._cdf(1,10))
    print(stats.loggamma.cdf(1,10))
    print(loggammaexpg._cdf(2,15))
    print(stats.loggamma.cdf(2,15))


    # this requires change in scipy.stats.distribution
    #print(loggammaexpg.cdf(1,10))

    print('Results for loglaplace')
    loglaplaceg = LogTransf_gen(stats.laplace)
    print(loglaplaceg._cdf(2))
    print(stats.loglaplace.cdf(2,1))
    loglaplaceexpg = ExpTransf_gen(stats.laplace)
    print(loglaplaceexpg._cdf(2))
    stats.loglaplace.cdf(3,3)
    #0.98148148148148151
    loglaplaceexpg._cdf(3,0,1./3)
    #0.98148148148148151 
Example 75
Project: ble5-nrf52-mac   Author: tomasero   File: test_distributions.py    MIT License 4 votes vote down vote up
def test_pdf_nolan_samples(self):
        """ Test pdf values against Nolan's stablec.exe output
            see - http://fs2.american.edu/jpnolan/www/stable/stable.html

            There's a known limitation of Nolan's executable for alpha < 0.2.

            Repeat following with beta = -1, -.5, 0, .5 and 1
                stablec.exe <<
                1 # pdf
                1 # Nolan S equivalent to S0 in scipy
                .25,2,.25 # alpha
                -1,-1,0 # beta
                -10,10,1 # x
                1,0 # gamma, delta
                2 # output file
        """
        data = np.load(os.path.abspath(os.path.join(os.path.dirname(__file__),
                                                 'data/stable-pdf-sample-data.npy')))

        data = np.core.records.fromarrays(data.T, names='x,p,alpha,beta')

        # support numpy 1.8.2 for travis
        npisin = np.isin if hasattr(np, "isin") else np.in1d

        tests = [
            # best selects
            ['best', None, 8, None],

            # quadrature is accurate for most alpha except 0.25; perhaps limitation of Nolan stablec?
            # we reduce size of x to speed up computation as numerical integration slow.
            ['quadrature', None, 8, lambda r: (r['alpha'] > 0.25) & (npisin(r['x'], [-10,-5,0,5,10]))],

            # zolatarev is accurate except at alpha==1, beta != 0
            ['zolotarev', None, 8, lambda r: r['alpha'] != 1],
            ['zolotarev', None, 8, lambda r: (r['alpha'] == 1) & (r['beta'] == 0)],
            ['zolotarev', None, 1, lambda r: (r['alpha'] == 1) & (r['beta'] != 0)],

            # fft accuracy reduces as alpha decreases, fails at low values of alpha and x=0
            ['fft', 0, 4, lambda r: r['alpha'] > 1],
            ['fft', 0, 3, lambda r: (r['alpha'] < 1) & (r['alpha'] > 0.25)],
            ['fft', 0, 1, lambda r: (r['alpha'] == 0.25) & (r['x'] != 0)],  # not useful here
        ]
        for ix, (default_method, fft_min_points, decimal_places, filter_func) in enumerate(tests):
            stats.levy_stable.pdf_default_method = default_method
            stats.levy_stable.pdf_fft_min_points_threshold = fft_min_points
            subdata = data[filter_func(data)] if filter_func is not None else data
            with suppress_warnings() as sup:
                sup.record(RuntimeWarning, "Density calculation unstable for alpha=1 and beta!=0.*")
                sup.record(RuntimeWarning, "Density calculations experimental for FFT method.*")
                p = stats.levy_stable.pdf(subdata['x'], subdata['alpha'], subdata['beta'], scale=1, loc=0)
                subdata2 = rec_append_fields(subdata, 'calc', p)
                failures = subdata2[(np.abs(p-subdata['p']) >= 1.5*10.**(-decimal_places)) | np.isnan(p)]
                assert_almost_equal(p, subdata['p'], decimal_places, "pdf test %s failed with method '%s'\n%s" % (ix, default_method, failures), verbose=False) 
Example 76
Project: ble5-nrf52-mac   Author: tomasero   File: test_distributions.py    MIT License 4 votes vote down vote up
def test_gamma(self):
        a = 2.0
        dist = stats.gamma
        frozen = stats.gamma(a)

        result_f = frozen.pdf(20.0)
        result = dist.pdf(20.0, a)
        assert_equal(result_f, result)

        result_f = frozen.cdf(20.0)
        result = dist.cdf(20.0, a)
        assert_equal(result_f, result)

        result_f = frozen.ppf(0.25)
        result = dist.ppf(0.25, a)
        assert_equal(result_f, result)

        result_f = frozen.isf(0.25)
        result = dist.isf(0.25, a)
        assert_equal(result_f, result)

        result_f = frozen.sf(10.0)
        result = dist.sf(10.0, a)
        assert_equal(result_f, result)

        result_f = frozen.median()
        result = dist.median(a)
        assert_equal(result_f, result)

        result_f = frozen.mean()
        result = dist.mean(a)
        assert_equal(result_f, result)

        result_f = frozen.var()
        result = dist.var(a)
        assert_equal(result_f, result)

        result_f = frozen.std()
        result = dist.std(a)
        assert_equal(result_f, result)

        result_f = frozen.entropy()
        result = dist.entropy(a)
        assert_equal(result_f, result)

        result_f = frozen.moment(2)
        result = dist.moment(2, a)
        assert_equal(result_f, result)

        assert_equal(frozen.a, frozen.dist.a)
        assert_equal(frozen.b, frozen.dist.b) 
Example 77
Project: Computable   Author: ktraunmueller   File: test_distributions.py    MIT License 4 votes vote down vote up
def test_gamma(self):
        a = 2.0
        dist = stats.gamma
        frozen = stats.gamma(a)

        result_f = frozen.pdf(20.0)
        result = dist.pdf(20.0, a)
        assert_equal(result_f, result)

        result_f = frozen.cdf(20.0)
        result = dist.cdf(20.0, a)
        assert_equal(result_f, result)

        result_f = frozen.ppf(0.25)
        result = dist.ppf(0.25, a)
        assert_equal(result_f, result)

        result_f = frozen.isf(0.25)
        result = dist.isf(0.25, a)
        assert_equal(result_f, result)

        result_f = frozen.sf(10.0)
        result = dist.sf(10.0, a)
        assert_equal(result_f, result)

        result_f = frozen.median()
        result = dist.median(a)
        assert_equal(result_f, result)

        result_f = frozen.mean()
        result = dist.mean(a)
        assert_equal(result_f, result)

        result_f = frozen.var()
        result = dist.var(a)
        assert_equal(result_f, result)

        result_f = frozen.std()
        result = dist.std(a)
        assert_equal(result_f, result)

        result_f = frozen.entropy()
        result = dist.entropy(a)
        assert_equal(result_f, result)

        result_f = frozen.moment(2)
        result = dist.moment(2, a)
        assert_equal(result_f, result) 
Example 78
Project: poker   Author: surgebiswas   File: test_distributions.py    MIT License 4 votes vote down vote up
def test_gamma(self):
        a = 2.0
        dist = stats.gamma
        frozen = stats.gamma(a)

        result_f = frozen.pdf(20.0)
        result = dist.pdf(20.0, a)
        assert_equal(result_f, result)

        result_f = frozen.cdf(20.0)
        result = dist.cdf(20.0, a)
        assert_equal(result_f, result)

        result_f = frozen.ppf(0.25)
        result = dist.ppf(0.25, a)
        assert_equal(result_f, result)

        result_f = frozen.isf(0.25)
        result = dist.isf(0.25, a)
        assert_equal(result_f, result)

        result_f = frozen.sf(10.0)
        result = dist.sf(10.0, a)
        assert_equal(result_f, result)

        result_f = frozen.median()
        result = dist.median(a)
        assert_equal(result_f, result)

        result_f = frozen.mean()
        result = dist.mean(a)
        assert_equal(result_f, result)

        result_f = frozen.var()
        result = dist.var(a)
        assert_equal(result_f, result)

        result_f = frozen.std()
        result = dist.std(a)
        assert_equal(result_f, result)

        result_f = frozen.entropy()
        result = dist.entropy(a)
        assert_equal(result_f, result)

        result_f = frozen.moment(2)
        result = dist.moment(2, a)
        assert_equal(result_f, result)

        assert_equal(frozen.a, frozen.dist.a)
        assert_equal(frozen.b, frozen.dist.b) 
Example 79
Project: P3_image_processing   Author: latedude2   File: test_distributions.py    MIT License 4 votes vote down vote up
def test_pdf_nolan_samples(self):
        """ Test pdf values against Nolan's stablec.exe output
            see - http://fs2.american.edu/jpnolan/www/stable/stable.html

            There's a known limitation of Nolan's executable for alpha < 0.2.

            Repeat following with beta = -1, -.5, 0, .5 and 1
                stablec.exe <<
                1 # pdf
                1 # Nolan S equivalent to S0 in scipy
                .25,2,.25 # alpha
                -1,-1,0 # beta
                -10,10,1 # x
                1,0 # gamma, delta
                2 # output file
        """
        data = np.load(os.path.abspath(os.path.join(os.path.dirname(__file__),
                                                 'data/stable-pdf-sample-data.npy')))

        data = np.core.records.fromarrays(data.T, names='x,p,alpha,beta')

        # support numpy 1.8.2 for travis
        npisin = np.isin if hasattr(np, "isin") else np.in1d

        tests = [
            # best selects
            ['best', None, 8, None],

            # quadrature is accurate for most alpha except 0.25; perhaps limitation of Nolan stablec?
            # we reduce size of x to speed up computation as numerical integration slow.
            ['quadrature', None, 8, lambda r: (r['alpha'] > 0.25) & (npisin(r['x'], [-10,-5,0,5,10]))],

            # zolatarev is accurate except at alpha==1, beta != 0
            ['zolotarev', None, 8, lambda r: r['alpha'] != 1],
            ['zolotarev', None, 8, lambda r: (r['alpha'] == 1) & (r['beta'] == 0)],
            ['zolotarev', None, 1, lambda r: (r['alpha'] == 1) & (r['beta'] != 0)],

            # fft accuracy reduces as alpha decreases, fails at low values of alpha and x=0
            ['fft', 0, 4, lambda r: r['alpha'] > 1],
            ['fft', 0, 3, lambda r: (r['alpha'] < 1) & (r['alpha'] > 0.25)],
            ['fft', 0, 1, lambda r: (r['alpha'] == 0.25) & (r['x'] != 0)],  # not useful here
        ]
        for ix, (default_method, fft_min_points, decimal_places, filter_func) in enumerate(tests):
            stats.levy_stable.pdf_default_method = default_method
            stats.levy_stable.pdf_fft_min_points_threshold = fft_min_points
            subdata = data[filter_func(data)] if filter_func is not None else data
            with suppress_warnings() as sup:
                sup.record(RuntimeWarning, "Density calculation unstable for alpha=1 and beta!=0.*")
                sup.record(RuntimeWarning, "Density calculations experimental for FFT method.*")
                p = stats.levy_stable.pdf(subdata['x'], subdata['alpha'], subdata['beta'], scale=1, loc=0)
                subdata2 = rec_append_fields(subdata, 'calc', p)
                failures = subdata2[(np.abs(p-subdata['p']) >= 1.5*10.**(-decimal_places)) | np.isnan(p)]
                assert_almost_equal(p, subdata['p'], decimal_places, "pdf test %s failed with method '%s'\n%s" % (ix, default_method, failures), verbose=False) 
Example 80
Project: P3_image_processing   Author: latedude2   File: test_distributions.py    MIT License 4 votes vote down vote up
def test_gamma(self):
        a = 2.0
        dist = stats.gamma
        frozen = stats.gamma(a)

        result_f = frozen.pdf(20.0)
        result = dist.pdf(20.0, a)
        assert_equal(result_f, result)

        result_f = frozen.cdf(20.0)
        result = dist.cdf(20.0, a)
        assert_equal(result_f, result)

        result_f = frozen.ppf(0.25)
        result = dist.ppf(0.25, a)
        assert_equal(result_f, result)

        result_f = frozen.isf(0.25)
        result = dist.isf(0.25, a)
        assert_equal(result_f, result)

        result_f = frozen.sf(10.0)
        result = dist.sf(10.0, a)
        assert_equal(result_f, result)

        result_f = frozen.median()
        result = dist.median(a)
        assert_equal(result_f, result)

        result_f = frozen.mean()
        result = dist.mean(a)
        assert_equal(result_f, result)

        result_f = frozen.var()
        result = dist.var(a)
        assert_equal(result_f, result)

        result_f = frozen.std()
        result = dist.std(a)
        assert_equal(result_f, result)

        result_f = frozen.entropy()
        result = dist.entropy(a)
        assert_equal(result_f, result)

        result_f = frozen.moment(2)
        result = dist.moment(2, a)
        assert_equal(result_f, result)

        assert_equal(frozen.a, frozen.dist.a)
        assert_equal(frozen.b, frozen.dist.b)