Ejemplo n.º 1
0
def test_Compound_Distribution():
    X = Normal('X', 2, 4)
    N = NormalDistribution(X, 4)
    C = CompoundDistribution(N)
    assert C.is_Continuous
    assert C.set == Interval(-oo, oo)
    assert C.pdf(x,
                 evaluate=True).simplify() == exp(-x**2 / 64 + x / 16 -
                                                  S(1) / 16) / (8 * sqrt(pi))

    assert not isinstance(CompoundDistribution(NormalDistribution(2, 3)),
                          CompoundDistribution)
    M = MultivariateNormalDistribution([1, 2], [[2, 1], [1, 2]])
    raises(NotImplementedError, lambda: CompoundDistribution(M))

    X = Beta('X', 2, 4)
    B = BernoulliDistribution(X, 1, 0)
    C = CompoundDistribution(B)
    assert C.is_Finite
    assert C.set == {0, 1}
    y = symbols('y', negative=False, integer=True)
    assert C.pdf(y, evaluate=True) == Piecewise(
        (S(1) / (30 * beta(2, 4)), Eq(y, 0)),
        (S(1) / (60 * beta(2, 4)), Eq(y, 1)), (0, True))

    k, t, z = symbols('k t z', positive=True, real=True)
    G = Gamma('G', k, t)
    X = PoissonDistribution(G)
    C = CompoundDistribution(X)
    assert C.is_Discrete
    assert C.set == S.Naturals0
    assert C.pdf(z, evaluate=True).simplify() == t**z*(t + 1)**(-k - z)*gamma(k \
                    + z)/(gamma(k)*gamma(z + 1))
Ejemplo n.º 2
0
def test_beta_scipy():
    if not scipy:
        skip("scipy not installed")

    f = beta(x, y)
    F = lambdify((x, y), f, modules='scipy')

    assert abs(beta(1.3, 2.3) - F(1.3, 2.3)) <= 1e-10
Ejemplo n.º 3
0
def apply(m, n=1):
    m = sympify(m)
    n = sympify(n)

    x = Symbol.x(real=True)
    return Equality(Integral[x:0:S.Pi / 2](cos(x)**(m - 1) * sin(x)**(n - 1)),
                    beta(m / 2, n / 2) / 2)
Ejemplo n.º 4
0
def test_yule_simon():
    from sympy.core.singleton import S
    rho = S(3)
    x = YuleSimon('x', rho)
    assert simplify(E(x)) == rho / (rho - 1)
    assert simplify(variance(x)) == rho**2 / ((rho - 1)**2 * (rho - 2))
    assert isinstance(E(x, evaluate=False), Expectation)
    # To test the cdf function
    assert cdf(x)(x) == Piecewise((-beta(floor(x), 4) * floor(x) + 1, x >= 1),
                                  (0, True))
Ejemplo n.º 5
0
def test_beta():
    a, b, x = symbols("a b x", positive=True)
    e = x**(a - 1) * (-x + 1)**(b - 1) / beta(a, b)
    Q = QQ[a, b].get_field()
    h1 = expr_to_holonomic(e, x, domain=Q)

    _, Dx = DifferentialOperators(Q.old_poly_ring(x), 'Dx')
    h2 = HolonomicFunction((a + x * (-a - b + 2) - 1) + (x**2 - x) * Dx, x)

    assert h1 == h2
Ejemplo n.º 6
0
def test_betainc():
    a, b, x1, x2 = symbols('a b x1 x2')

    assert unchanged(betainc, a, b, x1, x2)
    assert unchanged(betainc, a, b, 0, x1)

    assert betainc(1, 2, 0, -5).is_real == True
    assert betainc(1, 2, 0, x2).is_real is None
    assert conjugate(betainc(I, 2, 3 - I, 1 + 4*I)) == betainc(-I, 2, 3 + I, 1 - 4*I)

    assert betainc(a, b, 0, 1).rewrite(Integral).dummy_eq(beta(a, b).rewrite(Integral))
    assert betainc(1, 2, 0, x2).rewrite(hyper) == x2*hyper((1, -1), (2,), x2)

    assert betainc(1, 2, 3, 3).evalf() == 0
Ejemplo n.º 7
0
def test_beta():
    from sympy.functions.special.beta_functions import beta

    expr = beta(x, y)

    prntr = SciPyPrinter()
    assert prntr.doprint(expr) == 'scipy.special.beta(x, y)'

    prntr = NumPyPrinter()
    assert prntr.doprint(expr) == 'math.gamma(x)*math.gamma(y)/math.gamma(x + y)'

    prntr = PythonCodePrinter()
    assert prntr.doprint(expr) == 'math.gamma(x)*math.gamma(y)/math.gamma(x + y)'

    prntr = PythonCodePrinter({'allow_unknown_functions': True})
    assert prntr.doprint(expr) == 'math.gamma(x)*math.gamma(y)/math.gamma(x + y)'

    prntr = MpmathPrinter()
    assert prntr.doprint(expr) ==  'mpmath.beta(x, y)'
Ejemplo n.º 8
0
def test_beta():
    x, y = symbols('x y')
    t = Dummy('t')

    assert unchanged(beta, x, y)

    assert beta(5, -3).is_real == True
    assert beta(3, y).is_real is None

    assert expand_func(beta(x, y)) == gamma(x)*gamma(y)/gamma(x + y)
    assert expand_func(beta(x, y) - beta(y, x)) == 0  # Symmetric
    assert expand_func(beta(x, y)) == expand_func(beta(x, y + 1) + beta(x + 1, y)).simplify()

    assert diff(beta(x, y), x) == beta(x, y)*(polygamma(0, x) - polygamma(0, x + y))
    assert diff(beta(x, y), y) == beta(x, y)*(polygamma(0, y) - polygamma(0, x + y))

    assert conjugate(beta(x, y)) == beta(conjugate(x), conjugate(y))

    raises(ArgumentIndexError, lambda: beta(x, y).fdiff(3))

    assert beta(x, y).rewrite(gamma) == gamma(x)*gamma(y)/gamma(x + y)
    assert beta(x).rewrite(gamma) == gamma(x)**2/gamma(2*x)
    assert beta(x, y).rewrite(Integral).dummy_eq(Integral(t**(x - 1) * (1 - t)**(y - 1), (t, 0, 1)))
Ejemplo n.º 9
0
def test_beta_binomial():
    # verify parameters
    raises(ValueError, lambda: BetaBinomial('b', .2, 1, 2))
    raises(ValueError, lambda: BetaBinomial('b', 2, -1, 2))
    raises(ValueError, lambda: BetaBinomial('b', 2, 1, -2))
    assert BetaBinomial('b', 2, 1, 1)

    # test numeric values
    nvals = range(1, 5)
    alphavals = [Rational(1, 4), S.Half, Rational(3, 4), 1, 10]
    betavals = [Rational(1, 4), S.Half, Rational(3, 4), 1, 10]

    for n in nvals:
        for a in alphavals:
            for b in betavals:
                X = BetaBinomial('X', n, a, b)
                assert E(X) == moment(X, 1)
                assert variance(X) == cmoment(X, 2)

    # test symbolic
    n, a, b = symbols('a b n')
    assert BetaBinomial('x', n, a, b)
    n = 2  # Because we're using for loops, can't do symbolic n
    a, b = symbols('a b', positive=True)
    X = BetaBinomial('X', n, a, b)
    t = Symbol('t')

    assert E(X).expand() == moment(X, 1).expand()
    assert variance(X).expand() == cmoment(X, 2).expand()
    assert skewness(X) == smoment(X, 3)
    assert characteristic_function(X)(t) == exp(2*I*t)*beta(a + 2, b)/beta(a, b) +\
         2*exp(I*t)*beta(a + 1, b + 1)/beta(a, b) + beta(a, b + 2)/beta(a, b)
    assert moment_generating_function(X)(t) == exp(2*t)*beta(a + 2, b)/beta(a, b) +\
         2*exp(t)*beta(a + 1, b + 1)/beta(a, b) + beta(a, b + 2)/beta(a, b)
Ejemplo n.º 10
0
def test_beta_math():
    f = beta(x, y)
    F = lambdify((x, y), f, modules='math')

    assert abs(beta(1.3, 2.3) - F(1.3, 2.3)) <= 1e-10
Ejemplo n.º 11
0
 def _cdf(self, x):
     return Piecewise((1 - floor(x) * beta(floor(x), self.rho + 1), x >= 1),
                      (0, True))
Ejemplo n.º 12
0
 def pdf(self, k):
     rho = self.rho
     return rho * beta(k, rho + 1)
def densi_frac(p_val, c_val, m_val, n_val, pri_val, frac_type):
    """Calculates the prior density of a ratio of beta distributions.\
    Is used in interval calculations.

    Parameters
    ==========

    p_val : Number of exposed in group one
    c_val : Number of exposed in group two
    m_val : Total number in group one
    n_val : Total number in group two
    pri_val : Tuple containing belief parameters for the two beta distributions,\
                B(c_val + pi1, n_val - c_val + pi2) and B(p_val + pi3, m_val - p_val + pi4),\
                given in the order: pi1, pi2, pi3, pi4
    frac_type : Desired ratio - relative risk ("risk") or odds ratio ("odds")

    Returns
    =======

    The denstity function for these inputs

    Raises
    ======

    TypeError
        Count inputs must be integers
    ValueError
        frac_type must be "risk" or "odds"
        C must be larger than pi1
        N - C must be larger than pi2
        P must be larger than pi3
        M - P must be larger than pi4
        One or more counts are negative
        P + N + pi1 + pi2 + pi3 must be positive
        'P + pi3 + 1 must be positive
        C + M + pi1 + pi2 + pi3 must be positive
        C + pi3 + 1 must be positive

    See Also
    =======

    distri_frac : Posterior density

    Examples
    ========

    >>> densi_frac(56, 126, 366, 354, (0, 0, 0, 0), "risk")
    >>> densi_frac(25, 108, 123, 313, (0, 0, 0, 0), "risk")

    """
    if not (isinstance(p_val, int) and isinstance(c_val, int)
            and isinstance(m_val, int) and isinstance(n_val, int)):
        raise TypeError('Count inputs must be integers')
    if c_val <= pri_val[0]:
        raise ValueError('C ({:f}) must be larger than pi1 ({:f})'.format(
            c_val, pri_val[0]))
    elif n_val - c_val <= pri_val[1]:
        raise ValueError('N - C ({:f}) must be larger than pi2 ({:f})'.format(
            n_val - c_val, pri_val[1]))
    elif p_val <= pri_val[2]:
        raise ValueError('P ({:f}) must be larger than pi3 ({:f})'.format(
            p_val, pri_val[2]))
    elif m_val - p_val <= pri_val[3]:
        raise ValueError('M - P ({:f}) must be larger than pi4 ({:f})'.format(
            m_val - p_val, pri_val[3]))
    elif c_val < 0 or p_val < 0 or n_val < 0 or m_val < 0:
        raise ValueError('One or more counts are negative')
    else:
        if frac_type == 'risk':
            dens = Piecewise(
                (beta(alpha + theta, b) /
                 (beta(alpha, b) * beta(theta, phi)) * z**(theta - 1) * hyper(
                     (alpha + theta, 1 - phi),
                     (alpha + theta + b, ), z), z <= 1),
                # this comma needs to be here for hyper to work ^
                (beta(alpha + theta, phi) /
                 (beta(alpha, b) * beta(theta, phi)) * z**(-(1 + alpha)) *
                 hyper((alpha + theta, 1 - b),
                       (alpha + theta + phi, ), 1 / z), z > 1))
        #      this comma needs to be here for hyper to work ^
        elif frac_type == 'odds':
            dens = Piecewise(
                (beta(alpha + theta, b + phi) /
                 (beta(alpha, b) * beta(theta, phi)) * z**(theta - 1) * hyper(
                     (alpha + theta, theta + phi),
                     (alpha + theta + b + phi, ), z), z <= 1),
                (beta(alpha + theta, b + phi) /
                 (beta(alpha, b) * beta(theta, phi)) * z**(-(1 + phi)) * hyper(
                     (phi + theta, phi + b),
                     (alpha + theta + b + phi, ), 1 / z), z > 1))
        else:
            raise ValueError('frac_type must be "risk" or "odds"')
        dens = dens.subs({
            alpha: C + PI_1,
            b: N - C + PI_2,
            theta: P + PI_3,
            phi: M - P + PI_4
        })
        return dens