Python scipy.stats.lognorm() Examples

The following are code examples for showing how to use scipy.stats.lognorm(). 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_support():
    """gh-6235"""
    def check_open_support(rvs, args):
        dist = getattr(stats, rvs)

        assert_almost_equal(dist.pdf(dist.a, *args), 0)
        assert_equal(dist.logpdf(dist.a, *args), -np.inf)
        assert_almost_equal(dist.pdf(dist.b, *args), 0)
        assert_equal(dist.logpdf(dist.b, *args), -np.inf)

    dists = ['alpha', 'arcsine', 'betaprime', 'burr', 'burr12',
             'fatiguelife', 'invgamma', 'invgauss', 'invweibull',
             'johnsonsb', 'levy', 'levy_l', 'lognorm', 'gilbrat',
             'powerlognorm', 'rayleigh', 'wald']

    dct = dict(distcont)
    for dist in dists:
        args = dct[dist]
        yield check_open_support, dist, args 
Example 2
Project: LaserTOF   Author: kyleuckert   File: test_distributions.py    MIT License 6 votes vote down vote up
def test_stats_shapes_argcheck():
    # stats method was failing for vector shapes if some of the values
    # were outside of the allowed range, see gh-2678
    mv3 = stats.invgamma.stats([0.0, 0.5, 1.0], 1, 0.5)  # 0 is not a legal `a`
    mv2 = stats.invgamma.stats([0.5, 1.0], 1, 0.5)
    mv2_augmented = tuple(np.r_[np.nan, _] for _ in mv2)
    assert_equal(mv2_augmented, mv3)

    # -1 is not a legal shape parameter
    mv3 = stats.lognorm.stats([2, 2.4, -1])
    mv2 = stats.lognorm.stats([2, 2.4])
    mv2_augmented = tuple(np.r_[_, np.nan] for _ in mv2)
    assert_equal(mv2_augmented, mv3)

    # FIXME: this is only a quick-and-dirty test of a quick-and-dirty bugfix.
    # stats method with multiple shape parameters is not properly vectorized
    # anyway, so some distributions may or may not fail.


# Test subclassing distributions w/ explicit shapes 
Example 3
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_stats_shapes_argcheck():
    # stats method was failing for vector shapes if some of the values
    # were outside of the allowed range, see gh-2678
    mv3 = stats.invgamma.stats([0.0, 0.5, 1.0], 1, 0.5)  # 0 is not a legal `a`
    mv2 = stats.invgamma.stats([0.5, 1.0], 1, 0.5)
    mv2_augmented = tuple(np.r_[np.nan, _] for _ in mv2)
    assert_equal(mv2_augmented, mv3)

    mv3 = stats.lognorm.stats([2, 2.4, -1])  # -1 is not a legal shape parameter
    mv2 = stats.lognorm.stats([2, 2.4])
    mv2_augmented = tuple(np.r_[_, np.nan] for _ in mv2)
    assert_equal(mv2_augmented, mv3)

    # FIXME: this is only a quick-and-dirty test of a quick-and-dirty bugfix.
    # stats method with multiple shape parameters is not properly vectorized
    # anyway, so some distributions may or may not fail.


## Test subclassing distributions w/ explicit shapes 
Example 4
Project: vnpy_crypto   Author: birforce   File: test_transf.py    MIT License 6 votes vote down vote up
def setup_class(cls):
        cls.dist_equivalents = [
            #transf, stats.lognorm(1))
            #The below fails on the SPARC box with scipy 10.1
            #(lognormalg, stats.lognorm(1)),
            #transf2
           (squarenormalg, stats.chi2(1)),
           (absnormalg, stats.halfnorm),
           (absnormalg, stats.foldnorm(1e-5)),  #try frozen
           #(negsquarenormalg, 1-stats.chi2),  # won't work as distribution
           (squaretg(10), stats.f(1, 10))
            ]      #try both frozen

        l,s = 0.0, 1.0
        cls.ppfq = [0.1,0.5,0.9]
        cls.xx = [0.95,1.0,1.1]
        cls.nxx = [-0.95,-1.0,-1.1] 
Example 5
Project: ble5-nrf52-mac   Author: tomasero   File: test_distributions.py    MIT License 6 votes vote down vote up
def test_lognorm_fit(self):
        x = np.array([1.5, 3, 10, 15, 23, 59])
        lnxm1 = np.log(x - 1)

        shape, loc, scale = stats.lognorm.fit(x, floc=1)
        assert_allclose(shape, lnxm1.std(), rtol=1e-12)
        assert_equal(loc, 1)
        assert_allclose(scale, np.exp(lnxm1.mean()), rtol=1e-12)

        shape, loc, scale = stats.lognorm.fit(x, floc=1, fscale=6)
        assert_allclose(shape, np.sqrt(((lnxm1 - np.log(6))**2).mean()),
                        rtol=1e-12)
        assert_equal(loc, 1)
        assert_equal(scale, 6)

        shape, loc, scale = stats.lognorm.fit(x, floc=1, fix_s=0.75)
        assert_equal(shape, 0.75)
        assert_equal(loc, 1)
        assert_allclose(scale, np.exp(lnxm1.mean()), rtol=1e-12) 
Example 6
Project: ble5-nrf52-mac   Author: tomasero   File: test_distributions.py    MIT License 6 votes vote down vote up
def test_stats_shapes_argcheck():
    # stats method was failing for vector shapes if some of the values
    # were outside of the allowed range, see gh-2678
    mv3 = stats.invgamma.stats([0.0, 0.5, 1.0], 1, 0.5)  # 0 is not a legal `a`
    mv2 = stats.invgamma.stats([0.5, 1.0], 1, 0.5)
    mv2_augmented = tuple(np.r_[np.nan, _] for _ in mv2)
    assert_equal(mv2_augmented, mv3)

    # -1 is not a legal shape parameter
    mv3 = stats.lognorm.stats([2, 2.4, -1])
    mv2 = stats.lognorm.stats([2, 2.4])
    mv2_augmented = tuple(np.r_[_, np.nan] for _ in mv2)
    assert_equal(mv2_augmented, mv3)

    # FIXME: this is only a quick-and-dirty test of a quick-and-dirty bugfix.
    # stats method with multiple shape parameters is not properly vectorized
    # anyway, so some distributions may or may not fail.


# Test subclassing distributions w/ explicit shapes 
Example 7
Project: poker   Author: surgebiswas   File: test_distributions.py    MIT License 6 votes vote down vote up
def test_support():
    """gh-6235"""
    def check_open_support(rvs, args):
        dist = getattr(stats, rvs)

        assert_almost_equal(dist.pdf(dist.a, *args), 0)
        assert_equal(dist.logpdf(dist.a, *args), -np.inf)
        assert_almost_equal(dist.pdf(dist.b, *args), 0)
        assert_equal(dist.logpdf(dist.b, *args), -np.inf)

    dists = ['alpha', 'arcsine', 'betaprime', 'burr', 'burr12',
             'fatiguelife', 'invgamma', 'invgauss', 'invweibull',
             'johnsonsb', 'levy', 'levy_l', 'lognorm', 'gilbrat',
             'powerlognorm', 'rayleigh', 'wald']

    dct = dict(distcont)
    for dist in dists:
        args = dct[dist]
        yield check_open_support, dist, args 
Example 8
Project: poker   Author: surgebiswas   File: test_distributions.py    MIT License 6 votes vote down vote up
def test_stats_shapes_argcheck():
    # stats method was failing for vector shapes if some of the values
    # were outside of the allowed range, see gh-2678
    mv3 = stats.invgamma.stats([0.0, 0.5, 1.0], 1, 0.5)  # 0 is not a legal `a`
    mv2 = stats.invgamma.stats([0.5, 1.0], 1, 0.5)
    mv2_augmented = tuple(np.r_[np.nan, _] for _ in mv2)
    assert_equal(mv2_augmented, mv3)

    # -1 is not a legal shape parameter
    mv3 = stats.lognorm.stats([2, 2.4, -1])
    mv2 = stats.lognorm.stats([2, 2.4])
    mv2_augmented = tuple(np.r_[_, np.nan] for _ in mv2)
    assert_equal(mv2_augmented, mv3)

    # FIXME: this is only a quick-and-dirty test of a quick-and-dirty bugfix.
    # stats method with multiple shape parameters is not properly vectorized
    # anyway, so some distributions may or may not fail.


# Test subclassing distributions w/ explicit shapes 
Example 9
Project: P3_image_processing   Author: latedude2   File: test_distributions.py    MIT License 6 votes vote down vote up
def test_lognorm_fit(self):
        x = np.array([1.5, 3, 10, 15, 23, 59])
        lnxm1 = np.log(x - 1)

        shape, loc, scale = stats.lognorm.fit(x, floc=1)
        assert_allclose(shape, lnxm1.std(), rtol=1e-12)
        assert_equal(loc, 1)
        assert_allclose(scale, np.exp(lnxm1.mean()), rtol=1e-12)

        shape, loc, scale = stats.lognorm.fit(x, floc=1, fscale=6)
        assert_allclose(shape, np.sqrt(((lnxm1 - np.log(6))**2).mean()),
                        rtol=1e-12)
        assert_equal(loc, 1)
        assert_equal(scale, 6)

        shape, loc, scale = stats.lognorm.fit(x, floc=1, fix_s=0.75)
        assert_equal(shape, 0.75)
        assert_equal(loc, 1)
        assert_allclose(scale, np.exp(lnxm1.mean()), rtol=1e-12) 
Example 10
Project: P3_image_processing   Author: latedude2   File: test_distributions.py    MIT License 6 votes vote down vote up
def test_stats_shapes_argcheck():
    # stats method was failing for vector shapes if some of the values
    # were outside of the allowed range, see gh-2678
    mv3 = stats.invgamma.stats([0.0, 0.5, 1.0], 1, 0.5)  # 0 is not a legal `a`
    mv2 = stats.invgamma.stats([0.5, 1.0], 1, 0.5)
    mv2_augmented = tuple(np.r_[np.nan, _] for _ in mv2)
    assert_equal(mv2_augmented, mv3)

    # -1 is not a legal shape parameter
    mv3 = stats.lognorm.stats([2, 2.4, -1])
    mv2 = stats.lognorm.stats([2, 2.4])
    mv2_augmented = tuple(np.r_[_, np.nan] for _ in mv2)
    assert_equal(mv2_augmented, mv3)

    # FIXME: this is only a quick-and-dirty test of a quick-and-dirty bugfix.
    # stats method with multiple shape parameters is not properly vectorized
    # anyway, so some distributions may or may not fail.


# Test subclassing distributions w/ explicit shapes 
Example 11
Project: chainer   Author: chainer   File: test_log_normal.py    MIT License 6 votes vote down vote up
def setUp_configure(self):
        from scipy import stats
        self.dist = distributions.LogNormal
        self.scipy_dist = stats.lognorm

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

        mu = utils.force_array(
            numpy.random.uniform(-1, 1, self.shape).astype(numpy.float32))
        sigma = utils.force_array(numpy.exp(numpy.random.uniform(
            -1, 0, self.shape)).astype(numpy.float32))
        self.params = {'mu': mu, 'sigma': sigma}
        self.scipy_params = {'s': sigma, 'scale': numpy.exp(mu)}

        self.support = 'positive' 
Example 12
Project: GraphicDesignPatternByPython   Author: Relph1119   File: test_distributions.py    MIT License 6 votes vote down vote up
def test_lognorm_fit(self):
        x = np.array([1.5, 3, 10, 15, 23, 59])
        lnxm1 = np.log(x - 1)

        shape, loc, scale = stats.lognorm.fit(x, floc=1)
        assert_allclose(shape, lnxm1.std(), rtol=1e-12)
        assert_equal(loc, 1)
        assert_allclose(scale, np.exp(lnxm1.mean()), rtol=1e-12)

        shape, loc, scale = stats.lognorm.fit(x, floc=1, fscale=6)
        assert_allclose(shape, np.sqrt(((lnxm1 - np.log(6))**2).mean()),
                        rtol=1e-12)
        assert_equal(loc, 1)
        assert_equal(scale, 6)

        shape, loc, scale = stats.lognorm.fit(x, floc=1, fix_s=0.75)
        assert_equal(shape, 0.75)
        assert_equal(loc, 1)
        assert_allclose(scale, np.exp(lnxm1.mean()), rtol=1e-12) 
Example 13
Project: GraphicDesignPatternByPython   Author: Relph1119   File: test_distributions.py    MIT License 6 votes vote down vote up
def test_stats_shapes_argcheck():
    # stats method was failing for vector shapes if some of the values
    # were outside of the allowed range, see gh-2678
    mv3 = stats.invgamma.stats([0.0, 0.5, 1.0], 1, 0.5)  # 0 is not a legal `a`
    mv2 = stats.invgamma.stats([0.5, 1.0], 1, 0.5)
    mv2_augmented = tuple(np.r_[np.nan, _] for _ in mv2)
    assert_equal(mv2_augmented, mv3)

    # -1 is not a legal shape parameter
    mv3 = stats.lognorm.stats([2, 2.4, -1])
    mv2 = stats.lognorm.stats([2, 2.4])
    mv2_augmented = tuple(np.r_[_, np.nan] for _ in mv2)
    assert_equal(mv2_augmented, mv3)

    # FIXME: this is only a quick-and-dirty test of a quick-and-dirty bugfix.
    # stats method with multiple shape parameters is not properly vectorized
    # anyway, so some distributions may or may not fail.


# Test subclassing distributions w/ explicit shapes 
Example 14
Project: wine-ml-on-aws-lambda   Author: pierreant   File: test_distributions.py    Apache License 2.0 6 votes vote down vote up
def test_support():
    """gh-6235"""
    def check_open_support(rvs, args):
        dist = getattr(stats, rvs)

        assert_almost_equal(dist.pdf(dist.a, *args), 0)
        assert_equal(dist.logpdf(dist.a, *args), -np.inf)
        assert_almost_equal(dist.pdf(dist.b, *args), 0)
        assert_equal(dist.logpdf(dist.b, *args), -np.inf)

    dists = ['alpha', 'arcsine', 'betaprime', 'burr', 'burr12',
             'fatiguelife', 'invgamma', 'invgauss', 'invweibull',
             'johnsonsb', 'levy', 'levy_l', 'lognorm', 'gilbrat',
             'powerlognorm', 'rayleigh', 'wald']

    dct = dict(distcont)
    for dist in dists:
        args = dct[dist]
        yield check_open_support, dist, args 
Example 15
Project: wine-ml-on-aws-lambda   Author: pierreant   File: test_distributions.py    Apache License 2.0 6 votes vote down vote up
def test_stats_shapes_argcheck():
    # stats method was failing for vector shapes if some of the values
    # were outside of the allowed range, see gh-2678
    mv3 = stats.invgamma.stats([0.0, 0.5, 1.0], 1, 0.5)  # 0 is not a legal `a`
    mv2 = stats.invgamma.stats([0.5, 1.0], 1, 0.5)
    mv2_augmented = tuple(np.r_[np.nan, _] for _ in mv2)
    assert_equal(mv2_augmented, mv3)

    # -1 is not a legal shape parameter
    mv3 = stats.lognorm.stats([2, 2.4, -1])
    mv2 = stats.lognorm.stats([2, 2.4])
    mv2_augmented = tuple(np.r_[_, np.nan] for _ in mv2)
    assert_equal(mv2_augmented, mv3)

    # FIXME: this is only a quick-and-dirty test of a quick-and-dirty bugfix.
    # stats method with multiple shape parameters is not properly vectorized
    # anyway, so some distributions may or may not fail.


# Test subclassing distributions w/ explicit shapes 
Example 16
Project: ngboost   Author: stanfordmlgroup   File: lognormal.py    Apache License 2.0 6 votes vote down vote up
def D_nll(self, Y):
        E = Y['Event'][:,np.newaxis]
        T = Y['Time']
        lT = np.log(T)
        Z = (lT - self.loc) / self.scale

        D_uncens = np.zeros((self.loc.shape[0], 2))
        D_uncens[:, 0] = (self.loc - lT) / (self.scale ** 2)
        D_uncens[:, 1] = 1 - ((self.loc - lT) ** 2) / (self.scale ** 2)

        D_cens = np.zeros((self.loc.shape[0], 2))
        D_cens[:, 0] = -sp.stats.norm.pdf(lT, loc=self.loc, scale=self.scale) / \
                        (1 - self.dist.cdf(T) + self.eps)
        D_cens[:, 1] = -Z * sp.stats.norm.pdf(lT, loc=self.loc, scale=self.scale) / \
                        (1 - self.dist.cdf(T) + self.eps)
        D_cens[:, 0] = -sp.stats.norm.pdf(lT, loc=self.loc, scale=self.scale) / \
                        (1 - self.dist.cdf(T) + self.eps)
        D_cens[:, 1] = -Z * sp.stats.norm.pdf(lT, loc=self.loc, scale=self.scale) / \
                        (1 - self.dist.cdf(T) + self.eps)

        return (1-E) * D_cens + E * D_uncens 
Example 17
Project: LaserTOF   Author: kyleuckert   File: test_distributions.py    MIT License 5 votes vote down vote up
def test_pdf(self):
        # Regression test for Ticket #1471: avoid nan with 0/0 situation
        # Also make sure there are no warnings at x=0, cf gh-5202
        with warnings.catch_warnings():
            warnings.simplefilter('error', RuntimeWarning)
            pdf = stats.lognorm.pdf([0, 0.5, 1], 1)
            assert_array_almost_equal(pdf, [0.0, 0.62749608, 0.39894228]) 
Example 18
Project: LaserTOF   Author: kyleuckert   File: test_distributions.py    MIT License 5 votes vote down vote up
def test_logcdf(self):
        # Regression test for gh-5940: sf et al would underflow too early
        x2, mu, sigma = 201.68, 195, 0.149
        assert_allclose(stats.lognorm.sf(x2-mu, s=sigma),
                        stats.norm.sf(np.log(x2-mu)/sigma))
        assert_allclose(stats.lognorm.logsf(x2-mu, s=sigma),
                        stats.norm.logsf(np.log(x2-mu)/sigma)) 
Example 19
Project: LaserTOF   Author: kyleuckert   File: test_distributions.py    MIT License 5 votes vote down vote up
def test_fix_fit_2args_lognorm(self):
        # Regression test for #1551.
        np.random.seed(12345)
        with np.errstate(all='ignore'):
            x = stats.lognorm.rvs(0.25, 0., 20.0, size=20)
            assert_allclose(np.array(stats.lognorm.fit(x, floc=0, fscale=20)),
                            [0.25888672, 0, 20], atol=1e-5) 
Example 20
Project: LaserTOF   Author: kyleuckert   File: test_distributions.py    MIT License 5 votes vote down vote up
def test_regression_ticket_1293(self):
        # Create a frozen distribution.
        frozen = stats.lognorm(1)
        # Call one of its methods that does not take any keyword arguments.
        m1 = frozen.moment(2)
        # Now call a method that takes a keyword argument.
        frozen.stats(moments='mvsk')
        # Call moment(2) again.
        # After calling stats(), the following was raising an exception.
        # So this test passes if the following does not raise an exception.
        m2 = frozen.moment(2)
        # The following should also be true, of course.  But it is not
        # the focus of this test.
        assert_equal(m1, m2) 
Example 21
Project: Archrisk   Author: UCSBarchlab   File: distributions.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def LogNormalDistribution(mean, std):
        if std == .0:
            return Distribution.ConstantDistribution(mean)
        var = std * std
        mean2 = mean * mean
        mu = np.log(mean) - (var/2)*(1/mean2)
        sigma = np.sqrt(var/mean2)
        dist = UncertainVariable(ss.lognorm(sigma, scale=np.exp(mu)))
        logging.debug('Distribution -- LogNormal: ({}, {})'.format(
            dist.mean, np.sqrt(dist.var)))
        return dist 
Example 22
Project: paramnormal   Author: phobson   File: test_activity.py    MIT License 5 votes vote down vote up
def test_scipy_dist(self):
        assert_dists_are_equivalent(
            activity._check_distro(stats.lognorm(s=2)),
            stats.lognorm(s=2)
        ) 
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):
        # Regression test for Ticket #1471: avoid nan with 0/0 situation
        with np.errstate(divide='ignore'):
            pdf = stats.lognorm.pdf([0, 0.5, 1], 1)
            assert_array_almost_equal(pdf, [0.0, 0.62749608, 0.39894228]) 
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_fix_fit_2args_lognorm(self):
        # Regression test for #1551.
        np.random.seed(12345)
        with np.errstate(all='ignore'):
            x = stats.lognorm.rvs(0.25, 0., 20.0, size=20)
            assert_allclose(np.array(stats.lognorm.fit(x, floc=0, fscale=20)),
                            [0.25888672, 0, 20], atol=1e-5) 
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_regression_ticket_1293(self):
        # Create a frozen distribution.
        frozen = stats.lognorm(1)
        # Call one of its methods that does not take any keyword arguments.
        m1 = frozen.moment(2)
        # Now call a method that takes a keyword argument.
        frozen.stats(moments='mvsk')
        # Call moment(2) again.
        # After calling stats(), the following was raising an exception.
        # So this test passes if the following does not raise an exception.
        m2 = frozen.moment(2)
        # The following should also be true, of course.  But it is not
        # the focus of this test.
        assert_equal(m1, m2) 
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_frozen_fit_ticket_1536():
    np.random.seed(5678)
    true = np.array([0.25, 0., 0.5])
    x = stats.lognorm.rvs(true[0], true[1], true[2], size=100)

    olderr = np.seterr(divide='ignore')
    try:
        params = np.array(stats.lognorm.fit(x, floc=0.))
    finally:
        np.seterr(**olderr)

    assert_almost_equal(params, true, decimal=2)

    params = np.array(stats.lognorm.fit(x, fscale=0.5, loc=0))
    assert_almost_equal(params, true, decimal=2)

    params = np.array(stats.lognorm.fit(x, f0=0.25, loc=0))
    assert_almost_equal(params, true, decimal=2)

    params = np.array(stats.lognorm.fit(x, f0=0.25, floc=0))
    assert_almost_equal(params, true, decimal=2)

    np.random.seed(5678)
    loc = 1
    floc = 0.9
    x = stats.norm.rvs(loc, 2., size=100)
    params = np.array(stats.norm.fit(x, floc=floc))
    expected = np.array([floc, np.sqrt(((x-floc)**2).mean())])
    assert_almost_equal(params, expected, decimal=4) 
Example 27
Project: vnpy_crypto   Author: birforce   File: diffusion.py    MIT License 5 votes vote down vote up
def exactdist(self, xzero, t):
        expnt = np.exp(-self.lambd * t)
        #TODO: check this is still wrong, just guessing
        meant = np.log(xzero) * expnt + self._exactconst(expnt)
        stdt = self._exactstd(expnt)
        return stats.lognorm(loc=meant, scale=stdt) 
Example 28
Project: vnpy_crypto   Author: birforce   File: test_transf.py    MIT License 5 votes vote down vote up
def test_equivalent(self):
        xx, ppfq = self.xx, self.ppfq
        for d1,d2 in self.dist_equivalents:
##            print d1.name
            assert_almost_equal(d1.cdf(xx), d2.cdf(xx), err_msg='cdf'+d1.name)
            assert_almost_equal(d1.pdf(xx), d2.pdf(xx),
                                err_msg='pdf '+d1.name+d2.name)
            assert_almost_equal(d1.sf(xx), d2.sf(xx),
                                err_msg='sf '+d1.name+d2.name)
            assert_almost_equal(d1.ppf(ppfq), d2.ppf(ppfq),
                                err_msg='ppq '+d1.name+d2.name)
            assert_almost_equal(d1.isf(ppfq), d2.isf(ppfq),
                                err_msg='isf '+d1.name+d2.name)
            self.d1 = d1
            self.d2 = d2
##            print d1, d2
##            print d1.moment(3)
##            print d2.moment(3)
            #work around bug#1293
            if hasattr(d2, 'dist'):
                d2mom = d2.dist.moment(3, *d2.args)
            else:
                d2mom = d2.moment(3)
            assert_almost_equal(d1.moment(3), d2mom,
                                DECIMAL,
                                err_msg='moment '+d1.name+d2.name)
            # silence warnings in scipy, works for versions
            # after print changed to warning in scipy
            orig_filter = warnings.filters[:]
            warnings.simplefilter('ignore')
            try:
                s1 = d1.stats(moments='mvsk')
                s2 = d2.stats(moments='mvsk')
            finally:
                warnings.filters = orig_filter
            #stats(moments='k') prints warning for lognormalg
            assert_almost_equal(s1[:2], s2[:2],
                                err_msg='stats '+d1.name+d2.name)
            assert_almost_equal(s1[2:], s2[2:],
                                decimal=2, #lognorm for kurtosis
                                err_msg='stats '+d1.name+d2.name) 
Example 29
Project: ble5-nrf52-mac   Author: tomasero   File: test_distributions.py    MIT License 5 votes vote down vote up
def test_pdf(self):
        # Regression test for Ticket #1471: avoid nan with 0/0 situation
        # Also make sure there are no warnings at x=0, cf gh-5202
        with warnings.catch_warnings():
            warnings.simplefilter('error', RuntimeWarning)
            pdf = stats.lognorm.pdf([0, 0.5, 1], 1)
            assert_array_almost_equal(pdf, [0.0, 0.62749608, 0.39894228]) 
Example 30
Project: ble5-nrf52-mac   Author: tomasero   File: test_distributions.py    MIT License 5 votes vote down vote up
def test_logcdf(self):
        # Regression test for gh-5940: sf et al would underflow too early
        x2, mu, sigma = 201.68, 195, 0.149
        assert_allclose(stats.lognorm.sf(x2-mu, s=sigma),
                        stats.norm.sf(np.log(x2-mu)/sigma))
        assert_allclose(stats.lognorm.logsf(x2-mu, s=sigma),
                        stats.norm.logsf(np.log(x2-mu)/sigma)) 
Example 31
Project: ble5-nrf52-mac   Author: tomasero   File: test_distributions.py    MIT License 5 votes vote down vote up
def test_fix_fit_2args_lognorm(self):
        # Regression test for #1551.
        np.random.seed(12345)
        with np.errstate(all='ignore'):
            x = stats.lognorm.rvs(0.25, 0., 20.0, size=20)
            expected_shape = np.sqrt(((np.log(x) - np.log(20))**2).mean())
            assert_allclose(np.array(stats.lognorm.fit(x, floc=0, fscale=20)),
                            [expected_shape, 0, 20], atol=1e-8) 
Example 32
Project: ble5-nrf52-mac   Author: tomasero   File: test_distributions.py    MIT License 5 votes vote down vote up
def test_regression_ticket_1293(self):
        # Create a frozen distribution.
        frozen = stats.lognorm(1)
        # Call one of its methods that does not take any keyword arguments.
        m1 = frozen.moment(2)
        # Now call a method that takes a keyword argument.
        frozen.stats(moments='mvsk')
        # Call moment(2) again.
        # After calling stats(), the following was raising an exception.
        # So this test passes if the following does not raise an exception.
        m2 = frozen.moment(2)
        # The following should also be true, of course.  But it is not
        # the focus of this test.
        assert_equal(m1, m2) 
Example 33
Project: Computable   Author: ktraunmueller   File: test_distributions.py    MIT License 5 votes vote down vote up
def test_pdf(self):
        # Regression test for Ticket #1471: avoid nan with 0/0 situation
        with np.errstate(divide='ignore'):
            pdf = stats.lognorm.pdf([0, 0.5, 1], 1)
            assert_array_almost_equal(pdf, [0.0, 0.62749608, 0.39894228]) 
Example 34
Project: Computable   Author: ktraunmueller   File: test_distributions.py    MIT License 5 votes vote down vote up
def test_fix_fit_2args_lognorm(self):
        """Regression test for #1551."""
        np.random.seed(12345)
        with np.errstate(all='ignore'):
            x = stats.lognorm.rvs(0.25, 0., 20.0, size=20)
            assert_allclose(np.array(stats.lognorm.fit(x, floc=0, fscale=20)),
                            [0.25888672, 0, 20], atol=1e-5) 
Example 35
Project: Computable   Author: ktraunmueller   File: test_distributions.py    MIT License 5 votes vote down vote up
def test_regression_ticket_1293(self):
        # Create a frozen distribution.
        frozen = stats.lognorm(1)
        # Call one of its methods that does not take any keyword arguments.
        m1 = frozen.moment(2)
        # Now call a method that takes a keyword argument.
        frozen.stats(moments='mvsk')
        # Call moment(2) again.
        # After calling stats(), the following was raising an exception.
        # So this test passes if the following does not raise an exception.
        m2 = frozen.moment(2)
        # The following should also be true, of course.  But it is not
        # the focus of this test.
        assert_equal(m1, m2) 
Example 36
Project: Computable   Author: ktraunmueller   File: test_distributions.py    MIT License 5 votes vote down vote up
def test_frozen_fit_ticket_1536():
    np.random.seed(5678)
    true = np.array([0.25, 0., 0.5])
    x = stats.lognorm.rvs(true[0], true[1], true[2], size=100)

    olderr = np.seterr(divide='ignore')
    try:
        params = np.array(stats.lognorm.fit(x, floc=0.))
    finally:
        np.seterr(**olderr)

    assert_almost_equal(params, true, decimal=2)

    params = np.array(stats.lognorm.fit(x, fscale=0.5, loc=0))
    assert_almost_equal(params, true, decimal=2)

    params = np.array(stats.lognorm.fit(x, f0=0.25, loc=0))
    assert_almost_equal(params, true, decimal=2)

    params = np.array(stats.lognorm.fit(x, f0=0.25, floc=0))
    assert_almost_equal(params, true, decimal=2)

    np.random.seed(5678)
    loc = 1
    floc = 0.9
    x = stats.norm.rvs(loc, 2., size=100)
    params = np.array(stats.norm.fit(x, floc=floc))
    expected = np.array([floc, np.sqrt(((x-floc)**2).mean())])
    assert_almost_equal(params, expected, decimal=4) 
Example 37
Project: poker   Author: surgebiswas   File: test_distributions.py    MIT License 5 votes vote down vote up
def test_pdf(self):
        # Regression test for Ticket #1471: avoid nan with 0/0 situation
        # Also make sure there are no warnings at x=0, cf gh-5202
        with warnings.catch_warnings():
            warnings.simplefilter('error', RuntimeWarning)
            pdf = stats.lognorm.pdf([0, 0.5, 1], 1)
            assert_array_almost_equal(pdf, [0.0, 0.62749608, 0.39894228]) 
Example 38
Project: poker   Author: surgebiswas   File: test_distributions.py    MIT License 5 votes vote down vote up
def test_logcdf(self):
        # Regression test for gh-5940: sf et al would underflow too early
        x2, mu, sigma = 201.68, 195, 0.149
        assert_allclose(stats.lognorm.sf(x2-mu, s=sigma),
                        stats.norm.sf(np.log(x2-mu)/sigma))
        assert_allclose(stats.lognorm.logsf(x2-mu, s=sigma),
                        stats.norm.logsf(np.log(x2-mu)/sigma)) 
Example 39
Project: poker   Author: surgebiswas   File: test_distributions.py    MIT License 5 votes vote down vote up
def test_fix_fit_2args_lognorm(self):
        # Regression test for #1551.
        np.random.seed(12345)
        with np.errstate(all='ignore'):
            x = stats.lognorm.rvs(0.25, 0., 20.0, size=20)
            assert_allclose(np.array(stats.lognorm.fit(x, floc=0, fscale=20)),
                            [0.25888672, 0, 20], atol=1e-5) 
Example 40
Project: poker   Author: surgebiswas   File: test_distributions.py    MIT License 5 votes vote down vote up
def test_regression_ticket_1293(self):
        # Create a frozen distribution.
        frozen = stats.lognorm(1)
        # Call one of its methods that does not take any keyword arguments.
        m1 = frozen.moment(2)
        # Now call a method that takes a keyword argument.
        frozen.stats(moments='mvsk')
        # Call moment(2) again.
        # After calling stats(), the following was raising an exception.
        # So this test passes if the following does not raise an exception.
        m2 = frozen.moment(2)
        # The following should also be true, of course.  But it is not
        # the focus of this test.
        assert_equal(m1, m2) 
Example 41
Project: distcan   Author: sglyon   File: univariate.py    MIT License 5 votes vote down vote up
def __init__(self, mu, sigma):
        self.mu = mu
        self.sigma = sigma

        # set dist before calling super's __init__
        self.dist = st.lognorm(sigma, scale=exp(mu))
        super(LogNormal, self).__init__() 
Example 42
Project: P3_image_processing   Author: latedude2   File: test_distributions.py    MIT License 5 votes vote down vote up
def test_pdf(self):
        # Regression test for Ticket #1471: avoid nan with 0/0 situation
        # Also make sure there are no warnings at x=0, cf gh-5202
        with warnings.catch_warnings():
            warnings.simplefilter('error', RuntimeWarning)
            pdf = stats.lognorm.pdf([0, 0.5, 1], 1)
            assert_array_almost_equal(pdf, [0.0, 0.62749608, 0.39894228]) 
Example 43
Project: P3_image_processing   Author: latedude2   File: test_distributions.py    MIT License 5 votes vote down vote up
def test_logcdf(self):
        # Regression test for gh-5940: sf et al would underflow too early
        x2, mu, sigma = 201.68, 195, 0.149
        assert_allclose(stats.lognorm.sf(x2-mu, s=sigma),
                        stats.norm.sf(np.log(x2-mu)/sigma))
        assert_allclose(stats.lognorm.logsf(x2-mu, s=sigma),
                        stats.norm.logsf(np.log(x2-mu)/sigma)) 
Example 44
Project: P3_image_processing   Author: latedude2   File: test_distributions.py    MIT License 5 votes vote down vote up
def test_fix_fit_2args_lognorm(self):
        # Regression test for #1551.
        np.random.seed(12345)
        with np.errstate(all='ignore'):
            x = stats.lognorm.rvs(0.25, 0., 20.0, size=20)
            expected_shape = np.sqrt(((np.log(x) - np.log(20))**2).mean())
            assert_allclose(np.array(stats.lognorm.fit(x, floc=0, fscale=20)),
                            [expected_shape, 0, 20], atol=1e-8) 
Example 45
Project: P3_image_processing   Author: latedude2   File: test_distributions.py    MIT License 5 votes vote down vote up
def test_regression_ticket_1293(self):
        # Create a frozen distribution.
        frozen = stats.lognorm(1)
        # Call one of its methods that does not take any keyword arguments.
        m1 = frozen.moment(2)
        # Now call a method that takes a keyword argument.
        frozen.stats(moments='mvsk')
        # Call moment(2) again.
        # After calling stats(), the following was raising an exception.
        # So this test passes if the following does not raise an exception.
        m2 = frozen.moment(2)
        # The following should also be true, of course.  But it is not
        # the focus of this test.
        assert_equal(m1, m2) 
Example 46
Project: QuantEcon.lectures.code   Author: QuantEcon   File: lucastree.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self,
                 γ=2,
                 β=0.95,
                 α=0.90,
                 σ=0.1,
                 grid_size=100):

        self.γ, self.β, self.α, self.σ = γ, β, α, σ

        # == Set the grid interval to contain most of the mass of the
        # stationary distribution of the consumption endowment == #
        ssd = self.σ / np.sqrt(1 - self.α**2)
        grid_min, grid_max = np.exp(-4 * ssd), np.exp(4 * ssd)
        self.grid = np.linspace(grid_min, grid_max, grid_size)
        self.grid_size = grid_size

        # == set up distribution for shocks == #
        self.ϕ = lognorm(σ)
        self.draws = self.ϕ.rvs(500)

        # == h(y) = β * int G(y,z)^(1-γ) ϕ(dz) == #
        self.h = np.empty(self.grid_size)
        for i, y in enumerate(self.grid):
            self.h[i] = β * np.mean((y**α * self.draws)**(1 - γ))



## == Now the functions that act on a Lucas Tree == # 
Example 47
Project: GraphicDesignPatternByPython   Author: Relph1119   File: test_distributions.py    MIT License 5 votes vote down vote up
def test_pdf(self):
        # Regression test for Ticket #1471: avoid nan with 0/0 situation
        # Also make sure there are no warnings at x=0, cf gh-5202
        with warnings.catch_warnings():
            warnings.simplefilter('error', RuntimeWarning)
            pdf = stats.lognorm.pdf([0, 0.5, 1], 1)
            assert_array_almost_equal(pdf, [0.0, 0.62749608, 0.39894228]) 
Example 48
Project: GraphicDesignPatternByPython   Author: Relph1119   File: test_distributions.py    MIT License 5 votes vote down vote up
def test_logcdf(self):
        # Regression test for gh-5940: sf et al would underflow too early
        x2, mu, sigma = 201.68, 195, 0.149
        assert_allclose(stats.lognorm.sf(x2-mu, s=sigma),
                        stats.norm.sf(np.log(x2-mu)/sigma))
        assert_allclose(stats.lognorm.logsf(x2-mu, s=sigma),
                        stats.norm.logsf(np.log(x2-mu)/sigma)) 
Example 49
Project: GraphicDesignPatternByPython   Author: Relph1119   File: test_distributions.py    MIT License 5 votes vote down vote up
def test_fix_fit_2args_lognorm(self):
        # Regression test for #1551.
        np.random.seed(12345)
        with np.errstate(all='ignore'):
            x = stats.lognorm.rvs(0.25, 0., 20.0, size=20)
            expected_shape = np.sqrt(((np.log(x) - np.log(20))**2).mean())
            assert_allclose(np.array(stats.lognorm.fit(x, floc=0, fscale=20)),
                            [expected_shape, 0, 20], atol=1e-8) 
Example 50
Project: GraphicDesignPatternByPython   Author: Relph1119   File: test_distributions.py    MIT License 5 votes vote down vote up
def test_regression_ticket_1293(self):
        # Create a frozen distribution.
        frozen = stats.lognorm(1)
        # Call one of its methods that does not take any keyword arguments.
        m1 = frozen.moment(2)
        # Now call a method that takes a keyword argument.
        frozen.stats(moments='mvsk')
        # Call moment(2) again.
        # After calling stats(), the following was raising an exception.
        # So this test passes if the following does not raise an exception.
        m2 = frozen.moment(2)
        # The following should also be true, of course.  But it is not
        # the focus of this test.
        assert_equal(m1, m2) 
Example 51
Project: deep_image_model   Author: tobegit3hub   File: transformed_distribution_test.py    Apache License 2.0 5 votes vote down vote up
def testTransformedDistribution(self):
    g = tf.Graph()
    with g.as_default():
      mu = 3.0
      sigma = 2.0
      # Note: the Jacobian callable only works for this example; more generally
      # you may or may not need a reduce_sum.
      log_normal = distributions.TransformedDistribution(
          distribution=distributions.Normal(mu=mu, sigma=sigma),
          bijector=bijectors.Exp(event_ndims=0))
      sp_dist = stats.lognorm(s=sigma, scale=np.exp(mu))

      # sample
      sample = log_normal.sample(100000, seed=235)
      with self.test_session(graph=g):
        self.assertAllClose(sp_dist.mean(), np.mean(sample.eval()),
                            atol=0.0, rtol=0.05)

      # pdf, log_pdf, cdf, etc...
      # The mean of the lognormal is around 148.
      test_vals = np.linspace(0.1, 1000., num=20).astype(np.float32)
      for func in [
          [log_normal.log_prob, sp_dist.logpdf],
          [log_normal.prob, sp_dist.pdf],
          [log_normal.log_cdf, sp_dist.logcdf],
          [log_normal.cdf, sp_dist.cdf],
          [log_normal.survival_function, sp_dist.sf],
          [log_normal.log_survival_function, sp_dist.logsf]]:
        actual = func[0](test_vals)
        expected = func[1](test_vals)
        with self.test_session(graph=g):
          self.assertAllClose(expected, actual.eval(), atol=0, rtol=0.01) 
Example 52
Project: deep_image_model   Author: tobegit3hub   File: transformed_distribution_test.py    Apache License 2.0 5 votes vote down vote up
def testCachedSamplesWithoutInverse(self):
    with self.test_session() as sess:
      mu = 3.0
      sigma = 0.02
      log_normal = distributions.TransformedDistribution(
          distribution=distributions.Normal(mu=mu, sigma=sigma),
          bijector=bijectors.Exp(event_ndims=0))

      sample = log_normal.sample(1)
      sample_val, log_pdf_val = sess.run([sample, log_normal.log_pdf(sample)])
      self.assertAllClose(
          stats.lognorm.logpdf(sample_val, s=sigma,
                               scale=np.exp(mu)),
          log_pdf_val,
          atol=1e-2) 
Example 53
Project: steam-reviews   Author: woctezuma   File: describe_reviews.py    MIT License 5 votes vote down vote up
def plot_univariate_distribution(data_frame, str_x="votes_up"):
    # Reference: https://seaborn.pydata.org/tutorial/distributions.html

    sns.distplot(data_frame[str_x], kde=False, fit=stats.lognorm)
    plt.show()

    return 
Example 54
Project: wine-ml-on-aws-lambda   Author: pierreant   File: test_distributions.py    Apache License 2.0 5 votes vote down vote up
def test_pdf(self):
        # Regression test for Ticket #1471: avoid nan with 0/0 situation
        # Also make sure there are no warnings at x=0, cf gh-5202
        with warnings.catch_warnings():
            warnings.simplefilter('error', RuntimeWarning)
            pdf = stats.lognorm.pdf([0, 0.5, 1], 1)
            assert_array_almost_equal(pdf, [0.0, 0.62749608, 0.39894228]) 
Example 55
Project: wine-ml-on-aws-lambda   Author: pierreant   File: test_distributions.py    Apache License 2.0 5 votes vote down vote up
def test_logcdf(self):
        # Regression test for gh-5940: sf et al would underflow too early
        x2, mu, sigma = 201.68, 195, 0.149
        assert_allclose(stats.lognorm.sf(x2-mu, s=sigma),
                        stats.norm.sf(np.log(x2-mu)/sigma))
        assert_allclose(stats.lognorm.logsf(x2-mu, s=sigma),
                        stats.norm.logsf(np.log(x2-mu)/sigma)) 
Example 56
Project: wine-ml-on-aws-lambda   Author: pierreant   File: test_distributions.py    Apache License 2.0 5 votes vote down vote up
def test_fix_fit_2args_lognorm(self):
        # Regression test for #1551.
        np.random.seed(12345)
        with np.errstate(all='ignore'):
            x = stats.lognorm.rvs(0.25, 0., 20.0, size=20)
            assert_allclose(np.array(stats.lognorm.fit(x, floc=0, fscale=20)),
                            [0.25888672, 0, 20], atol=1e-5) 
Example 57
Project: wine-ml-on-aws-lambda   Author: pierreant   File: test_distributions.py    Apache License 2.0 5 votes vote down vote up
def test_regression_ticket_1293(self):
        # Create a frozen distribution.
        frozen = stats.lognorm(1)
        # Call one of its methods that does not take any keyword arguments.
        m1 = frozen.moment(2)
        # Now call a method that takes a keyword argument.
        frozen.stats(moments='mvsk')
        # Call moment(2) again.
        # After calling stats(), the following was raising an exception.
        # So this test passes if the following does not raise an exception.
        m2 = frozen.moment(2)
        # The following should also be true, of course.  But it is not
        # the focus of this test.
        assert_equal(m1, m2) 
Example 58
Project: altair-transform   Author: altair-viz   File: vegaexpr.py    MIT License 5 votes vote down vote up
def sampleLogNormal(mean: float = 0, stdev: float = 1) -> float:
    """
    Returns a sample from a univariate log-normal probability distribution with
    specified log mean and log standard deviation stdev. If unspecified, the log
    mean defaults to 0 and the log standard deviation defaults to 1.
    """
    from scipy.stats import lognorm

    return lognorm(s=stdev, scale=np.exp(mean)).rvs() 
Example 59
Project: altair-transform   Author: altair-viz   File: vegaexpr.py    MIT License 5 votes vote down vote up
def cumulativeLogNormal(value: float, mean: float = 0, stdev: float = 1) -> float:
    """
    Returns the value of the cumulative distribution function at the given input
    domain value for a log-normal distribution with specified log mean and log
    standard deviation stdev. If unspecified, the log mean defaults to 0 and the
    log standard deviation defaults to 1.
    """
    from scipy.stats import lognorm

    return lognorm(s=stdev, scale=np.exp(mean)).cdf(value) 
Example 60
Project: altair-transform   Author: altair-viz   File: vegaexpr.py    MIT License 5 votes vote down vote up
def densityLogNormal(value: float, mean: float = 0, stdev: float = 1) -> float:
    """
    Returns the value of the probability density function at the given input domain
    value, for a log-normal distribution with specified log mean and log standard
    deviation stdev. If unspecified, the log mean defaults to 0 and the log standard
    deviation defaults to 1.
    """
    from scipy.stats import lognorm

    return lognorm(s=stdev, scale=np.exp(mean)).pdf(value) 
Example 61
Project: altair-transform   Author: altair-viz   File: vegaexpr.py    MIT License 5 votes vote down vote up
def quantileLogNormal(probability: float, mean: float = 0, stdev: float = 1) -> float:
    """
    Returns the quantile value (the inverse of the cumulative distribution function)
    for the given input probability, for a log-normal distribution with specified log
    mean and log standard deviation stdev. If unspecified, the log mean defaults to 0
    and the log standard deviation defaults to 1.
    """
    from scipy.stats import lognorm

    return lognorm(s=stdev, scale=np.exp(mean)).ppf(probability) 
Example 62
Project: baobab   Author: jiwoncpark   File: distributions.py    MIT License 5 votes vote down vote up
def eval_lognormal_pdf(eval_at, mu, sigma, lower=-np.inf, upper=np.inf):
    """Evaluate the normal pdf, optionally truncated

    See `sample_normal` for parameter definitions.

    """
    dist = stats.lognorm(scale=np.exp(mu), s=sigma, loc=0.0)
    eval_unnormed_pdf = dist.pdf(eval_at)
    accept_norm = dist.cdf(upper) - dist.cdf(lower)
    eval_normed_pdf = eval_unnormed_pdf/accept_norm
    return eval_normed_pdf 
Example 63
Project: baobab   Author: jiwoncpark   File: distributions.py    MIT License 5 votes vote down vote up
def eval_lognormal_logpdf(eval_at, mu, sigma, lower=-np.inf, upper=np.inf):
    """Evaluate the normal pdf, optionally truncated

    See `sample_normal` for parameter definitions.

    """
    dist = stats.lognorm(scale=np.exp(mu), s=sigma, loc=0.0)
    eval_unnormed_logpdf = dist.logpdf(eval_at)
    accept_norm = dist.cdf(upper) - dist.cdf(lower)
    eval_normed_logpdf = eval_unnormed_logpdf - np.log(accept_norm)
    return eval_normed_logpdf 
Example 64
Project: Splunking-Crime   Author: nccgroup   File: diffusion.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def exactdist(self, xzero, t):
        expnt = np.exp(-self.lambd * t)
        #TODO: check this is still wrong, just guessing
        meant = np.log(xzero) * expnt + self._exactconst(expnt)
        stdt = self._exactstd(expnt)
        return stats.lognorm(loc=meant, scale=stdt) 
Example 65
Project: senior-design   Author: james-tate   File: test_distributions.py    GNU General Public License v2.0 5 votes vote down vote up
def test_regression_02(self):
        """Regression test for ticket #1293."""
        # Create a frozen distribution.
        frozen = stats.lognorm(1)
        # Call one of its methods that does not take any keyword arguments.
        m1 = frozen.moment(2)
        # Now call a method that takes a keyword argument.
        s = frozen.stats(moments='mvsk')
        # Call moment(2) again.
        # After calling stats(), the following was raising an exception.
        # So this test passes if the following does not raise an exception.
        m2 = frozen.moment(2)
        # The following should also be true, of course.  But it is not
        # the focus of this test.
        assert_equal(m1, m2) 
Example 66
Project: ngboost   Author: stanfordmlgroup   File: lognormal.py    Apache License 2.0 5 votes vote down vote up
def __init__(self, params):
        self.loc = params[0]
        self.scale = np.exp(params[1])
        self.dist = dist(s=self.scale, scale=np.exp(self.loc))
        self.eps = 1e-5 
Example 67
Project: ngboost   Author: stanfordmlgroup   File: lognormal.py    Apache License 2.0 5 votes vote down vote up
def __getattr__(self, name):
        if name in dir(self.dist):
            return getattr(self.dist, name)
        return None 
Example 68
Project: ngboost   Author: stanfordmlgroup   File: lognormal.py    Apache License 2.0 5 votes vote down vote up
def nll(self, Y):
        E = Y['Event']
        T = Y['Time']
        cens = (1-E) * np.log(1 - self.dist.cdf(T) + self.eps)
        uncens = E * self.dist.logpdf(T)
        return -(cens + uncens) 
Example 69
Project: Charm   Author: UCSBarchlab   File: distributions.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def LogNormalDistribution(mean, std):
        logging.debug('Lognorm -- Target LogN: {}, {}'.format(mean, std))
        if std == .0:
            return Distribution.ConstantDistribution(mean)
        var = std * std
        mean2 = mean * mean
        mu = np.log(mean) - (var/2)*(1/mean2)
        sigma = np.sqrt(var/mean2)
        # Have to construct LogN ourselves, the parameterizaion in mcerp is not correct.
        dist = UncertainVariable(ss.lognorm(sigma, scale=np.exp(mu)))
        logging.debug('Lognorm -- Gen LogN: ({}, {})'.format(dist.mean, np.sqrt(dist.var)))
        #PlotHelper.plot_hist(dist._mcpts)
        return dist 
Example 70
Project: QuantEcon.lectures.code   Author: QuantEcon   File: amflss.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def plot_multiplicative(self, T, npaths=25, show_trend=True):
        """
        Plots for the multiplicative decomposition

        """
        # Pull out right sizes so we know how to increment
        nx, nk, nm = self.nx, self.nk, self.nm
        # Matrices for the multiplicative decomposition
        ν_tilde, H, g = self.multiplicative_decomp()

        # Allocate space (nm is the number of functionals - we want npaths for each)
        mpath_mult = np.empty((nm*npaths, T))
        mbounds_mult = np.empty((nm*2, T))
        spath_mult = np.empty((nm*npaths, T))
        sbounds_mult = np.empty((nm*2, T))
        tpath_mult = np.empty((nm*npaths, T))
        ypath_mult = np.empty((nm*npaths, T))

        # Simulate for as long as we wanted
        moment_generator = self.lss.moment_sequence()
        # Pull out population moments
        for t in range(T):
            tmoms = next(moment_generator)
            ymeans = tmoms[1]
            yvar = tmoms[3]

            # Lower and upper bounds - for each multiplicative functional
            for ii in range(nm):
                li, ui = ii*2, (ii+1)*2
                Mdist = lognorm(np.asscalar(np.sqrt(yvar[nx+nm+ii, nx+nm+ii])), 
                                scale=np.asscalar( np.exp( ymeans[nx+nm+ii]- \
                                                t*(.5)*np.expand_dims(np.diag(H @ H.T),1)[ii])))
                Sdist = lognorm(np.asscalar(np.sqrt(yvar[nx+2*nm+ii, nx+2*nm+ii])),
                                scale = np.asscalar( np.exp(-ymeans[nx+2*nm+ii])))
                mbounds_mult[li:ui, t] = Mdist.ppf([.01, .99])
                sbounds_mult[li:ui, t] = Sdist.ppf([.01, .99])

        # Pull out paths
        for n in range(npaths):
            x, y = self.lss.simulate(T)
            for ii in range(nm):
                ypath_mult[npaths*ii+n, :] = np.exp(y[nx+ii, :])
                mpath_mult[npaths*ii+n, :] = np.exp(y[nx+nm + ii, :] - np.arange(T)*(.5)*np.expand_dims(np.diag(H @ H.T),1)[ii])
                spath_mult[npaths*ii+n, :] = 1/np.exp(-y[nx+2*nm + ii, :])
                tpath_mult[npaths*ii+n, :] = np.exp(y[nx+3*nm + ii, :] + np.arange(T)*(.5)*np.expand_dims(np.diag(H @ H.T),1)[ii])

        mult_figs = []

        for ii in range(nm):
            li, ui = npaths*(ii), npaths*(ii+1)
            LI, UI = 2*(ii), 2*(ii+1)

            mult_figs.append(self.plot_given_paths(T, ypath_mult[li:ui,:], mpath_mult[li:ui,:], 
                                                   spath_mult[li:ui,:], tpath_mult[li:ui,:], 
                                                   mbounds_mult[LI:UI,:], sbounds_mult[LI:UI,:], 1, 
                                                   show_trend=show_trend))
            mult_figs[ii].suptitle(f'Multiplicative decomposition of $y_{ii+1}$', fontsize=14)

        return mult_figs 
Example 71
Project: QuantEcon.lectures.code   Author: QuantEcon   File: amflss.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def plot_martingales(self, T, npaths=25):

        # Pull out right sizes so we know how to increment
        nx, nk, nm = self.nx, self.nk, self.nm
        # Matrices for the multiplicative decomposition
        ν_tilde, H, g = self.multiplicative_decomp()

        # Allocate space (nm is the number of functionals - we want npaths for each)
        mpath_mult = np.empty((nm*npaths, T))
        mbounds_mult = np.empty((nm*2, T))

        # Simulate for as long as we wanted
        moment_generator = self.lss.moment_sequence()
        # Pull out population moments
        for t in range (T):
            tmoms = next(moment_generator)
            ymeans = tmoms[1]
            yvar = tmoms[3]

            # Lower and upper bounds - for each functional
            for ii in range(nm):
                li, ui = ii*2, (ii+1)*2
                Mdist = lognorm(np.asscalar(np.sqrt(yvar[nx+nm+ii, nx+nm+ii])), 
                                scale=np.asscalar( np.exp( ymeans[nx+nm+ii]- \
                                                t*(.5)*np.expand_dims(np.diag(H @ H.T),1)[ii])))
                mbounds_mult[li:ui, t] = Mdist.ppf([.01, .99])

        # Pull out paths
        for n in range(npaths):
            x, y = self.lss.simulate(T)
            for ii in range(nm):
                mpath_mult[npaths*ii+n, :] = np.exp(y[nx+nm + ii, :] - np.arange(T)*(.5)*np.expand_dims(np.diag(H @ H.T),1)[ii])

        mart_figs = []

        for ii in range(nm):
            li, ui = npaths*(ii), npaths*(ii+1)
            LI, UI = 2*(ii), 2*(ii+1)
            mart_figs.append(self.plot_martingale_paths(T, mpath_mult[li:ui, :],
                                                        mbounds_mult[LI:UI, :],
                                                        horline=1))
            mart_figs[ii].suptitle(f'Martingale components for many paths of $y_{ii+1}$', fontsize=14)

        return mart_figs 
Example 72
Project: synthetic_traffic_generator   Author: edumucelli   File: generator.py    GNU General Public License v3.0 4 votes vote down vote up
def choose(self):
        if self.user_class == 'HF':
            self.name = "Log-norm"
            peak_hours_for_iat_hf = [1, 2, 3, 4, 5, 6]
            if self.hour in peak_hours_for_iat_hf:
                lognorm_shape, lognorm_scale, lognorm_location = 4.09174469261446, 1.12850165892419, 4.6875
            else:
                lognorm_shape, lognorm_scale, lognorm_location = 3.93740014906562, 0.982210300411203, 3
            return lognorm(lognorm_shape, loc=lognorm_location, scale=lognorm_scale)
        elif self.user_class == 'HO':
            self.name = "Gamma"
            peak_hours_for_iat_ho = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
            if self.hour in peak_hours_for_iat_ho:
                gamma_shape, gamma_rate, gamma_location = 1.25170029089175, 0.00178381168026473, 0.5
            else:
                gamma_shape, gamma_rate, gamma_location = 1.20448161464647, 0.00177591076721503, 0.5
            return gamma(gamma_shape, loc=gamma_location, scale=1. / gamma_rate)
        elif self.user_class == 'MF':
            self.name = "Gamma"
            peak_hours_for_iat_mf = [1, 2, 3, 4, 5, 6, 7, 22, 23]
            if self.hour in peak_hours_for_iat_mf:
                gamma_shape, gamma_rate, gamma_location = 2.20816848575484, 0.00343216949000565, 1
            else:
                gamma_shape, gamma_rate, gamma_location = 2.03011412986896, 0.00342699308280547, 1
            return gamma(gamma_shape, loc=gamma_location, scale=1. / gamma_rate)
        elif self.user_class == 'MO':
            self.name = "Gamma"
            peak_hours_for_iat_mo = [1, 2, 3, 4, 5, 6]
            if self.hour in peak_hours_for_iat_mo:
                gamma_shape, gamma_rate, gamma_location = 1.29908195595742, 0.00163527376977441, 0.5
            else:
                gamma_shape, gamma_rate, gamma_location = 1.19210494792398, 0.00170354443324898, 0.5
            return gamma(gamma_shape, loc=gamma_location, scale=1. / gamma_rate)
        elif self.user_class == 'LF':
            peak_hours_for_iat_lf = [1, 2, 3, 4, 5, 6, 7]
            if self.hour in peak_hours_for_iat_lf:
                self.name = "Gamma"
                gamma_shape, gamma_rate, gamma_location = 1.79297773527656, 0.00191590321039876, 2
                return gamma(gamma_shape, loc=gamma_location, scale=1. / gamma_rate)
            else:
                self.name = "Weibull"
                weibull_c_shape, weibull_scale, weibull_location = 1.1988117443903, 827.961760834184, 1
                return weibull_min(weibull_c_shape, loc=weibull_location, scale=weibull_scale)
        elif self.user_class == 'LO':
            peak_hours_for_iat_lo = [2, 3, 4, 10, 11, 12, 13, 14, 15, 17, 18, 19, 20]
            if self.hour in peak_hours_for_iat_lo:
                self.name = "Weibull"
                weibull_c_shape, weibull_scale, weibull_location = 0.850890858519732, 548.241539446292, 1
                return weibull_min(weibull_c_shape, loc=weibull_location, scale=weibull_scale)
            else:
                self.name = "Gamma"
                gamma_shape, gamma_rate, gamma_location = 0.707816241615835, 0.00135537879658998, 1
                return gamma(gamma_shape, loc=gamma_location, scale=1. / gamma_rate)
        else:
            raise Exception('The user class %s does not exist' % self.user_class)