Example #1
0
def test_laplace_posterior_cdf():
    # Test the LaplacePosterior cdf vs pdf
    np.random.seed(1)
    y = np.random.randn(15).tolist()

    c = statistics.LaplacePosterior(y)

    num_cdf = lambda t: integrate.quad(c.pdf, -np.inf, t, limit=1000)[0]

    with warnings.catch_warnings():
        warnings.simplefilter("ignore", category=integrate.IntegrationWarning)

        for t in np.linspace(-5, 5, 70):
            x = c.cdf(t)
            assert abs(x - num_cdf(t)) < 1e-5
            assert abs(c.ppf(x) - t) < 1e-5
Example #2
0
def test_laplace_posterior_basic():
    # Test the LaplacePosterior mle/cdf/ppf

    # even
    y = [1, 2, 3, 4, 5, 6][::-1]
    c = statistics.LaplacePosterior(y)
    assert abs(c.mle - 3.5) < 1e-8

    # odd
    y = [1, 2, 3, 4, 5][::-1]
    c = statistics.LaplacePosterior(y)
    assert abs(c.mle - 3) < 1e-8

    # check pdf vs cdf
    sx = 200
    dx = 1.0 / sx
    cdf = 0
    for jx in range(-10 * sx, 10 * sx):
        cdf += c.pdf(dx * jx) * dx
        got = c.cdf(dx * jx)
        assert abs(cdf - got) < 3e-3
    assert abs(cdf - 1.0) < 1e-3

    # large input (must not cause overflows)
    y = list(range(500))
    c = statistics.LaplacePosterior(y)
    assert abs(c.mle - 249.5) < 1e-8
    assert abs(c.cdf(249.5) - 0.5) < 1e-8

    # check cdf sanity
    assert c.cdf(float('inf')) == 1.0
    assert c.cdf(-float('inf')) == 0.0
    assert abs(c.cdf(-1e9) - 0) < 1e-6
    assert abs(c.cdf(1e9) - 1) < 1e-6

    # check ppf
    for p in [0.0, 1e-3, 0.01, 0.1, 0.5, 0.9, 0.99, 0.999, 1.0]:
        assert abs(c.cdf(c.ppf(p)) - p) < 1e-3

    t = c.ppf(1.1)
    assert t != t

    # check zero variance
    y = [1, 1, 1, 1, 1]
    c = statistics.LaplacePosterior(y)
    assert c.mle == 1
    assert c.pdf(1 - 1e-5) == 0
    assert c.pdf(1 + 1e-5) == 0
    assert c.cdf(1 - 1e-5) == 0
    assert c.cdf(1 + 1e-5) == 1.0
    assert c.ppf(1.0) == 1.0

    # one item
    y = [1]
    c = statistics.LaplacePosterior(y)
    assert c.cdf(1 - 1e-5) == 0
    assert c.cdf(1 + 1e-5) == 1.0

    # zero items
    with pytest.raises(ValueError):
        statistics.LaplacePosterior([])
Example #3
0
 def estimator(z, alpha):
     c = statistics.LaplacePosterior(z.tolist())
     a, b = c.ppf(alpha / 2), c.ppf(1 - alpha / 2)
     a = min(c.mle, a)  # force MLE inside CI
     b = max(c.mle, b)
     return c.mle, (a, b)