Ejemplo n.º 1
0
def test__intervals():
    assert Piecewise((x + 2, Eq(x, 3)))._intervals(x) == []
    assert Piecewise(
        (1, x > x + 1),
        (Piecewise((1, x < x + 1)), 2*x < 2*x + 1),
        (1, True))._intervals(x) == [(-oo, oo, 1, 1)]
    assert Piecewise((1, Ne(x, I)), (0, True))._intervals(x) == [
        (-oo, oo, 1, 0)]
    assert Piecewise((-cos(x), sin(x) >= 0), (cos(x), True)
        )._intervals(x) == [(0, pi, -cos(x), 0), (-oo, oo, cos(x), 1)]
    # the following tests that duplicates are removed and that non-Eq
    # generated zero-width intervals are removed
    assert Piecewise((1, Abs(x**(-2)) > 1), (0, True)
        )._intervals(x) == [(-1, 0, 1, 0), (0, 1, 1, 0), (-oo, oo, 0, 1)]
Ejemplo n.º 2
0
def test_reduce_poly_inequalities_complex_relational():
    cond = Eq(im(x), 0)

    assert reduce_poly_inequalities([[Eq(x**2, 0)]], x, relational=True) == And(Eq(re(x), 0), cond)
    assert reduce_poly_inequalities([[Le(x**2, 0)]], x, relational=True) == And(Eq(re(x), 0), cond)
    assert reduce_poly_inequalities([[Lt(x**2, 0)]], x, relational=True) == False
    assert reduce_poly_inequalities([[Ge(x**2, 0)]], x, relational=True) == cond
    assert reduce_poly_inequalities([[Gt(x**2, 0)]], x, relational=True) == And(Or(Lt(re(x), 0), Lt(0, re(x))), cond)
    assert reduce_poly_inequalities([[Ne(x**2, 0)]], x, relational=True) == And(Or(Lt(re(x), 0), Lt(0, re(x))), cond)

    assert reduce_poly_inequalities([[Eq(x**2, 1)]], x, relational=True) == And(Or(Eq(re(x), -1), Eq(re(x), 1)), cond)
    assert reduce_poly_inequalities([[Le(x**2, 1)]], x, relational=True) == And(And(Le(-1, re(x)), Le(re(x), 1)), cond)
    assert reduce_poly_inequalities([[Lt(x**2, 1)]], x, relational=True) == And(And(Lt(-1, re(x)), Lt(re(x), 1)), cond)
    assert reduce_poly_inequalities([[Ge(x**2, 1)]], x, relational=True) == And(Or(Le(re(x), -1), Le(1, re(x))), cond)
    assert reduce_poly_inequalities([[Gt(x**2, 1)]], x, relational=True) == And(Or(Lt(re(x), -1), Lt(1, re(x))), cond)
    assert reduce_poly_inequalities([[Ne(x**2, 1)]], x, relational=True) == And(Or(Lt(re(x), -1), And(Lt(-1, re(x)), Lt(re(x), 1)), Lt(1, re(x))), cond)

    assert reduce_poly_inequalities([[Eq(x**2, 1.0)]], x, relational=True).evalf() == And(Or(Eq(re(x), -1.0), Eq(re(x), 1.0)), cond)
    assert reduce_poly_inequalities([[Le(x**2, 1.0)]], x, relational=True) == And(And(Le(-1.0, re(x)), Le(re(x), 1.0)), cond)
    assert reduce_poly_inequalities([[Lt(x**2, 1.0)]], x, relational=True) == And(And(Lt(-1.0, re(x)), Lt(re(x), 1.0)), cond)
    assert reduce_poly_inequalities([[Ge(x**2, 1.0)]], x, relational=True) == And(Or(Le(re(x), -1.0), Le(1.0, re(x))), cond)
    assert reduce_poly_inequalities([[Gt(x**2, 1.0)]], x, relational=True) == And(Or(Lt(re(x), -1.0), Lt(1.0, re(x))), cond)
    assert reduce_poly_inequalities([[Ne(x**2, 1.0)]], x, relational=True) == And(Or(Lt(re(x), -1.0), And(Lt(-1.0, re(x)), Lt(re(x), 1.0)), Lt(1.0, re(x))), cond)
Ejemplo n.º 3
0
def test_logistic():
    mu = Symbol("mu", real=True)
    s = Symbol("s", positive=True)
    p = Symbol("p", positive=True)

    X = Logistic('x', mu, s)

    #Tests characteristics_function
    assert characteristic_function(X)(x) == \
           (Piecewise((pi*s*x*exp(I*mu*x)/sinh(pi*s*x), Ne(x, 0)), (1, True)))

    assert density(X)(x) == exp((-x + mu)/s)/(s*(exp((-x + mu)/s) + 1)**2)
    assert cdf(X)(x) == 1/(exp((mu - x)/s) + 1)
    assert quantile(X)(p) == mu - s*log(-S.One + 1/p)
Ejemplo n.º 4
0
def test_reduce_poly_inequalities_real_interval():
    global_assumptions.add(x_assume)
    global_assumptions.add(y_assume)

    assert reduce_poly_inequalities([[Eq(x**2, 0)]], x, relational=False) == [Interval(0, 0)]
    assert reduce_poly_inequalities([[Le(x**2, 0)]], x, relational=False) == [Interval(0, 0)]
    assert reduce_poly_inequalities([[Lt(x**2, 0)]], x, relational=False) == []
    assert reduce_poly_inequalities([[Ge(x**2, 0)]], x, relational=False) == [Interval(-oo, oo)]
    assert reduce_poly_inequalities([[Gt(x**2, 0)]], x, relational=False) == [Interval(-oo, 0, right_open=True), Interval(0, oo, left_open=True)]
    assert reduce_poly_inequalities([[Ne(x**2, 0)]], x, relational=False) == [Interval(-oo, 0, right_open=True), Interval(0, oo, left_open=True)]

    assert reduce_poly_inequalities([[Eq(x**2, 1)]], x, relational=False) == [Interval(-1,-1), Interval(1, 1)]
    assert reduce_poly_inequalities([[Le(x**2, 1)]], x, relational=False) == [Interval(-1, 1)]
    assert reduce_poly_inequalities([[Lt(x**2, 1)]], x, relational=False) == [Interval(-1, 1, True, True)]
    assert reduce_poly_inequalities([[Ge(x**2, 1)]], x, relational=False) == [Interval(-oo, -1), Interval(1, oo)]
    assert reduce_poly_inequalities([[Gt(x**2, 1)]], x, relational=False) == [Interval(-oo, -1, right_open=True), Interval(1, oo, left_open=True)]
    assert reduce_poly_inequalities([[Ne(x**2, 1)]], x, relational=False) == [Interval(-oo, -1, right_open=True), Interval(-1, 1, True, True), Interval(1, oo, left_open=True)]

    assert reduce_poly_inequalities([[Eq(x**2, 1.0)]], x, relational=False) == [Interval(-1.0,-1.0), Interval(1.0, 1.0)]
    assert reduce_poly_inequalities([[Le(x**2, 1.0)]], x, relational=False) == [Interval(-1.0, 1.0)]
    assert reduce_poly_inequalities([[Lt(x**2, 1.0)]], x, relational=False) == [Interval(-1.0, 1.0, True, True)]
    assert reduce_poly_inequalities([[Ge(x**2, 1.0)]], x, relational=False) == [Interval(-inf, -1.0), Interval(1.0, inf)]
    assert reduce_poly_inequalities([[Gt(x**2, 1.0)]], x, relational=False) == [Interval(-inf, -1.0, right_open=True), Interval(1.0, inf, left_open=True)]
    assert reduce_poly_inequalities([[Ne(x**2, 1.0)]], x, relational=False) == [Interval(-inf, -1.0, right_open=True), Interval(-1.0, 1.0, True, True), Interval(1.0, inf, left_open=True)]

    s = sqrt(2)

    assert reduce_poly_inequalities([[Lt(x**2 - 1, 0), Gt(x**2 - 1, 0)]], x, relational=False) == []
    assert reduce_poly_inequalities([[Le(x**2 - 1, 0), Ge(x**2 - 1, 0)]], x, relational=False) == [Interval(-1,-1), Interval(1, 1)]
    assert reduce_poly_inequalities([[Le(x**2 - 2, 0), Ge(x**2 - 1, 0)]], x, relational=False) == [Interval(-s, -1, False, False), Interval(1, s, False, False)]
    assert reduce_poly_inequalities([[Le(x**2 - 2, 0), Gt(x**2 - 1, 0)]], x, relational=False) == [Interval(-s, -1, False, True), Interval(1, s, True, False)]
    assert reduce_poly_inequalities([[Lt(x**2 - 2, 0), Ge(x**2 - 1, 0)]], x, relational=False) == [Interval(-s, -1, True, False), Interval(1, s, False, True)]
    assert reduce_poly_inequalities([[Lt(x**2 - 2, 0), Gt(x**2 - 1, 0)]], x, relational=False) == [Interval(-s, -1, True, True), Interval(1, s, True, True)]
    assert reduce_poly_inequalities([[Lt(x**2 - 2, 0), Ne(x**2 - 1, 0)]], x, relational=False) == [Interval(-s, -1, True, True), Interval(-1, 1, True, True), Interval(1, s, True, True)]

    global_assumptions.remove(x_assume)
    global_assumptions.remove(y_assume)
Ejemplo n.º 5
0
def test_issue_11865():
    matplotlib = import_module('matplotlib',
                               min_module_version='1.1.0',
                               catch=(RuntimeError, ))
    if not matplotlib:
        skip("Matplotlib not the default backend")
    k = Symbol('k', integer=True)
    f = Piecewise(
        (-I * exp(I * pi * k) / k + I * exp(-I * pi * k) / k, Ne(k, 0)),
        (2 * pi, True))
    p = plot(f, show=False)
    # Random number of segments, probably more than 100, but we want to see
    # that there are segments generated, as opposed to when the bug was present
    # and that there are no exceptions.
    assert len(p[0].get_segments()) >= 30
Ejemplo n.º 6
0
def test_reduce_poly_inequalities_real_interval():
    global_assumptions.add(Q.real(x))
    global_assumptions.add(Q.real(y))

    assert reduce_poly_inequalities([[Eq(x**2, 0)]], x, relational=False) == FiniteSet(0)
    assert reduce_poly_inequalities([[Le(x**2, 0)]], x, relational=False) == FiniteSet(0)
    assert reduce_poly_inequalities([[Lt(x**2, 0)]], x, relational=False) == S.EmptySet
    assert reduce_poly_inequalities([[Ge(x**2, 0)]], x, relational=False) == Interval(-oo, oo)
    assert reduce_poly_inequalities([[Gt(x**2, 0)]], x, relational=False) == FiniteSet(0).complement
    assert reduce_poly_inequalities([[Ne(x**2, 0)]], x, relational=False) == FiniteSet(0).complement

    assert reduce_poly_inequalities([[Eq(x**2, 1)]], x, relational=False) == FiniteSet(-1, 1)
    assert reduce_poly_inequalities([[Le(x**2, 1)]], x, relational=False) == Interval(-1, 1)
    assert reduce_poly_inequalities([[Lt(x**2, 1)]], x, relational=False) == Interval(-1, 1, True, True)
    assert reduce_poly_inequalities([[Ge(x**2, 1)]], x, relational=False) == Union(Interval(-oo, -1), Interval(1, oo))
    assert reduce_poly_inequalities([[Gt(x**2, 1)]], x, relational=False) == Interval(-1,1).complement
    assert reduce_poly_inequalities([[Ne(x**2, 1)]], x, relational=False) == FiniteSet(-1,1).complement
    assert reduce_poly_inequalities([[Eq(x**2, 1.0)]], x, relational=False) == FiniteSet(-1.0,1.0).evalf()
    assert reduce_poly_inequalities([[Le(x**2, 1.0)]], x, relational=False) == Interval(-1.0, 1.0)
    assert reduce_poly_inequalities([[Lt(x**2, 1.0)]], x, relational=False) == Interval(-1.0, 1.0, True, True)
    assert reduce_poly_inequalities([[Ge(x**2, 1.0)]], x, relational=False) == Union(Interval(-inf, -1.0), Interval(1.0, inf))
    assert reduce_poly_inequalities([[Gt(x**2, 1.0)]], x, relational=False) == Union(Interval(-inf, -1.0, right_open=True), Interval(1.0, inf, left_open=True))
    assert reduce_poly_inequalities([[Ne(x**2, 1.0)]], x, relational=False) == FiniteSet(-1.0, 1.0).complement

    s = sqrt(2)

    assert reduce_poly_inequalities([[Lt(x**2 - 1, 0), Gt(x**2 - 1, 0)]], x, relational=False) == S.EmptySet
    assert reduce_poly_inequalities([[Le(x**2 - 1, 0), Ge(x**2 - 1, 0)]], x, relational=False) == FiniteSet(-1,1)
    assert reduce_poly_inequalities([[Le(x**2 - 2, 0), Ge(x**2 - 1, 0)]], x, relational=False) == Union(Interval(-s, -1, False, False), Interval(1, s, False, False))
    assert reduce_poly_inequalities([[Le(x**2 - 2, 0), Gt(x**2 - 1, 0)]], x, relational=False) == Union(Interval(-s, -1, False, True), Interval(1, s, True, False))
    assert reduce_poly_inequalities([[Lt(x**2 - 2, 0), Ge(x**2 - 1, 0)]], x, relational=False) == Union(Interval(-s, -1, True, False), Interval(1, s, False, True))
    assert reduce_poly_inequalities([[Lt(x**2 - 2, 0), Gt(x**2 - 1, 0)]], x, relational=False) == Union(Interval(-s, -1, True, True), Interval(1, s, True, True))
    assert reduce_poly_inequalities([[Lt(x**2 - 2, 0), Ne(x**2 - 1, 0)]], x, relational=False) == Union(Interval(-s, -1, True, True), Interval(-1, 1, True, True), Interval(1, s, True, True))

    global_assumptions.remove(Q.real(x))
    global_assumptions.remove(Q.real(y))
Ejemplo n.º 7
0
def test__solve_inequality():
    for op in (Gt, Lt, Le, Ge, Eq, Ne):
        assert _solve_inequality(op(x, 1), x).lhs == x
        assert _solve_inequality(op(S.One, x), x).lhs == x
    # don't get tricked by symbol on right: solve it
    assert _solve_inequality(Eq(2 * x - 1, x), x) == Eq(x, 1)
    ie = Eq(S.One, y)
    assert _solve_inequality(ie, x) == ie
    for fx in (x**2, exp(x), sin(x) + cos(x), x * (1 + x)):
        for c in (0, 1):
            e = 2 * fx - c > 0
            assert _solve_inequality(e, x, linear=True) == (fx > c / 2)
    assert _solve_inequality(2 * x**2 + 2 * x - 1 < 0, x,
                             linear=True) == (x * (x + 1) < S.Half)
    assert _solve_inequality(Eq(x * y, 1), x) == Eq(x * y, 1)
    nz = Symbol('nz', nonzero=True)
    assert _solve_inequality(Eq(x * nz, 1), x) == Eq(x, 1 / nz)
    assert _solve_inequality(x * nz < 1, x) == (x * nz < 1)
    a = Symbol('a', positive=True)
    assert _solve_inequality(a / x > 1, x, linear=True) == (1 / x > 1 / a)
    # make sure to include conditions under which solution is valid
    e = Eq(1 - x, x * (1 / x - 1))
    assert _solve_inequality(e, x) == Ne(x, 0)
    assert _solve_inequality(x < x * (1 / x - 1), x) == (x < S.Half) & Ne(x, 0)
Ejemplo n.º 8
0
 def convergence_statement(self):
     """ Return a condition on z under which the series converges. """
     from sympy import And, Or, re, Ne, oo
     R = self.radius_of_convergence
     if R == 0:
         return False
     if R == oo:
         return True
     # The special functions and their approximations, page 44
     e = self.eta
     z = self.argument
     c1 = And(re(e) < 0, abs(z) <= 1)
     c2 = And(0 <= re(e), re(e) < 1, abs(z) <= 1, Ne(z, 1))
     c3 = And(re(e) >= 1, abs(z) < 1)
     return Or(c1, c2, c3)
def test_heurisch_radicals():
    assert heurisch(1/sqrt(x), x) == 2*sqrt(x)
    assert heurisch(1/sqrt(x)**3, x) == -2/sqrt(x)
    assert heurisch(sqrt(x)**3, x) == 2*sqrt(x)**5/5

    assert heurisch(sin(x)*sqrt(cos(x)), x) == -2*sqrt(cos(x))**3/3
    y = Symbol('y')
    assert heurisch(sin(y*sqrt(x)), x) == 2/y**2*sin(y*sqrt(x)) - \
        2*sqrt(x)*cos(y*sqrt(x))/y
    assert heurisch_wrapper(sin(y*sqrt(x)), x) == Piecewise(
        (-2*sqrt(x)*cos(sqrt(x)*y)/y + 2*sin(sqrt(x)*y)/y**2, Ne(y, 0)),
        (0, True))
    y = Symbol('y', positive=True)
    assert heurisch_wrapper(sin(y*sqrt(x)), x) == 2/y**2*sin(y*sqrt(x)) - \
        2*sqrt(x)*cos(y*sqrt(x))/y
Ejemplo n.º 10
0
def test_issue_6746():
    y = Symbol('y')
    n = Symbol('n')
    assert manualintegrate(y**x, x) == Piecewise(
        (y**x / log(y), Ne(log(y), 0)), (x, True))
    assert manualintegrate(y**(n * x), x) == Piecewise((Piecewise(
        (y**(n * x) / log(y), Ne(log(y), 0)), (n * x, True)) / n, Ne(n, 0)),
                                                       (x, True))
    assert manualintegrate(exp(n * x), x) == Piecewise(
        (exp(n * x) / n, Ne(n, 0)), (x, True))

    y = Symbol('y', positive=True)
    assert manualintegrate((y + 1)**x, x) == (y + 1)**x / log(y + 1)
    y = Symbol('y', zero=True)
    assert manualintegrate((y + 1)**x, x) == x
    y = Symbol('y')
    n = Symbol('n', nonzero=True)
    assert manualintegrate(y**(n * x), x) == Piecewise(
        (y**(n * x) / log(y), Ne(log(y), 0)), (n * x, True)) / n
    y = Symbol('y', positive=True)
    assert manualintegrate((y + 1)**(n*x), x) == \
        (y + 1)**(n*x)/(n*log(y + 1))
    a = Symbol('a', negative=True)
    b = Symbol('b')
    assert manualintegrate(1 / (a + b * x**2),
                           x) == atan(x / sqrt(a / b)) / (b * sqrt(a / b))
    b = Symbol('b', negative=True)
    assert manualintegrate(1/(a + b*x**2), x) == \
        atan(x/(sqrt(-a)*sqrt(-1/b)))/(b*sqrt(-a)*sqrt(-1/b))
    assert manualintegrate(1/((x**a + y**b + 4)*sqrt(a*x**2 + 1)), x) == \
        y**(-b)*Integral(x**(-a)/(y**(-b)*sqrt(a*x**2 + 1) +
        x**(-a)*sqrt(a*x**2 + 1) + 4*x**(-a)*y**(-b)*sqrt(a*x**2 + 1)), x)
    assert manualintegrate(1/((x**2 + 4)*sqrt(4*x**2 + 1)), x) == \
        Integral(1/((x**2 + 4)*sqrt(4*x**2 + 1)), x)
    assert manualintegrate(1/(x - a**x + x*b**2), x) == \
        Integral(1/(-a**x + b**2*x + x), x)
Ejemplo n.º 11
0
def test_heurisch_wrapper():
    f = 1 / (y + x)
    assert heurisch_wrapper(f, x) == log(x + y)
    f = 1 / (y - x)
    assert heurisch_wrapper(f, x) == -log(x - y)
    f = 1 / ((y - x) * (y + x))
    assert heurisch_wrapper(f, x) == Piecewise(
        (-log(x - y) / (2 * y) + log(x + y) / (2 * y), Ne(y, 0)), (1 / x, True)
    )
    # issue 6926
    f = sqrt(x ** 2 / ((y - x) * (y + x)))
    assert (
        heurisch_wrapper(f, x)
        == x * sqrt(x ** 2) * sqrt(1 / (-(x ** 2) + y ** 2))
        - y ** 2 * sqrt(x ** 2) * sqrt(1 / (-(x ** 2) + y ** 2)) / x
    )
Ejemplo n.º 12
0
def test_kronecker_delta():
    i, j = symbols('i j')
    k = Symbol('k', nonzero=True)
    assert KroneckerDelta(1, 1) == 1
    assert KroneckerDelta(1, 2) == 0
    assert KroneckerDelta(k, 0) == 0
    assert KroneckerDelta(x, x) == 1
    assert KroneckerDelta(x**2 - y**2, x**2 - y**2) == 1
    assert KroneckerDelta(i, i) == 1
    assert KroneckerDelta(i, i + 1) == 0
    assert KroneckerDelta(0, 0) == 1
    assert KroneckerDelta(0, 1) == 0
    assert KroneckerDelta(i + k, i) == 0
    assert KroneckerDelta(i + k, i + k) == 1
    assert KroneckerDelta(i + k, i + 1 + k) == 0
    assert KroneckerDelta(i, j).subs(dict(i=1, j=0)) == 0
    assert KroneckerDelta(i, j).subs(dict(i=3, j=3)) == 1

    assert KroneckerDelta(i, j)**0 == 1
    for n in range(1, 10):
        assert KroneckerDelta(i, j)**n == KroneckerDelta(i, j)
        assert KroneckerDelta(i, j)**-n == 1 / KroneckerDelta(i, j)

    assert KroneckerDelta(i, j).is_integer is True

    assert adjoint(KroneckerDelta(i, j)) == KroneckerDelta(i, j)
    assert conjugate(KroneckerDelta(i, j)) == KroneckerDelta(i, j)
    assert transpose(KroneckerDelta(i, j)) == KroneckerDelta(i, j)
    # to test if canonical
    assert (KroneckerDelta(i, j) == KroneckerDelta(j, i)) == True

    assert KroneckerDelta(i, j).rewrite(Piecewise) == Piecewise((0, Ne(i, j)),
                                                                (1, True))

    # Tests with range:
    assert KroneckerDelta(i, j, (0, i)).args == (i, j, (0, i))
    assert KroneckerDelta(i, j, (-j, i)).delta_range == (-j, i)

    # If index is out of range, return zero:
    assert KroneckerDelta(i, j, (0, i - 1)) == 0
    assert KroneckerDelta(-1, j, (0, i - 1)) == 0
    assert KroneckerDelta(j, -1, (0, i - 1)) == 0
    assert KroneckerDelta(j, i, (0, i - 1)) == 0
Ejemplo n.º 13
0
def test_presentation_mathml_relational():
    mml_1 = mpp._print(Eq(x, 1))
    assert len(mml_1.childNodes) == 3
    assert mml_1.childNodes[0].nodeName == 'mi'
    assert mml_1.childNodes[0].childNodes[0].nodeValue == 'x'
    assert mml_1.childNodes[1].nodeName == 'mo'
    assert mml_1.childNodes[1].childNodes[0].nodeValue == '='
    assert mml_1.childNodes[2].nodeName == 'mn'
    assert mml_1.childNodes[2].childNodes[0].nodeValue == '1'

    mml_2 = mpp._print(Ne(1, x))
    assert len(mml_2.childNodes) == 3
    assert mml_2.childNodes[0].nodeName == 'mn'
    assert mml_2.childNodes[0].childNodes[0].nodeValue == '1'
    assert mml_2.childNodes[1].nodeName == 'mo'
    assert mml_2.childNodes[1].childNodes[0].nodeValue == '&#x2260;'
    assert mml_2.childNodes[2].nodeName == 'mi'
    assert mml_2.childNodes[2].childNodes[0].nodeValue == 'x'

    mml_3 = mpp._print(Ge(1, x))
    assert len(mml_3.childNodes) == 3
    assert mml_3.childNodes[0].nodeName == 'mn'
    assert mml_3.childNodes[0].childNodes[0].nodeValue == '1'
    assert mml_3.childNodes[1].nodeName == 'mo'
    assert mml_3.childNodes[1].childNodes[0].nodeValue == '&#x2265;'
    assert mml_3.childNodes[2].nodeName == 'mi'
    assert mml_3.childNodes[2].childNodes[0].nodeValue == 'x'

    mml_4 = mpp._print(Lt(1, x))
    assert len(mml_4.childNodes) == 3
    assert mml_4.childNodes[0].nodeName == 'mn'
    assert mml_4.childNodes[0].childNodes[0].nodeValue == '1'
    assert mml_4.childNodes[1].nodeName == 'mo'
    assert mml_4.childNodes[1].childNodes[0].nodeValue == '<'
    assert mml_4.childNodes[2].nodeName == 'mi'
    assert mml_4.childNodes[2].childNodes[0].nodeValue == 'x'
Ejemplo n.º 14
0
def test_issue_12557():
    '''
    # 3200 seconds to compute the fourier part of issue
    import sympy as sym
    x,y,z,t = sym.symbols('x y z t')
    k = sym.symbols("k", integer=True)
    fourier = sym.fourier_series(sym.cos(k*x)*sym.sqrt(x**2),
                                 (x, -sym.pi, sym.pi))
    assert fourier == FourierSeries(
    sqrt(x**2)*cos(k*x), (x, -pi, pi), (Piecewise((pi**2,
    Eq(k, 0)), (2*(-1)**k/k**2 - 2/k**2, True))/(2*pi),
    SeqFormula(Piecewise((pi**2, (Eq(_n, 0) & Eq(k, 0)) | (Eq(_n, 0) &
    Eq(_n, k) & Eq(k, 0)) | (Eq(_n, 0) & Eq(k, 0) & Eq(_n, -k)) | (Eq(_n,
    0) & Eq(_n, k) & Eq(k, 0) & Eq(_n, -k))), (pi**2/2, Eq(_n, k) | Eq(_n,
    -k) | (Eq(_n, 0) & Eq(_n, k)) | (Eq(_n, k) & Eq(k, 0)) | (Eq(_n, 0) &
    Eq(_n, -k)) | (Eq(_n, k) & Eq(_n, -k)) | (Eq(k, 0) & Eq(_n, -k)) |
    (Eq(_n, 0) & Eq(_n, k) & Eq(_n, -k)) | (Eq(_n, k) & Eq(k, 0) & Eq(_n,
    -k))), ((-1)**k*pi**2*_n**3*sin(pi*_n)/(pi*_n**4 - 2*pi*_n**2*k**2 +
    pi*k**4) - (-1)**k*pi**2*_n**3*sin(pi*_n)/(-pi*_n**4 + 2*pi*_n**2*k**2
    - pi*k**4) + (-1)**k*pi*_n**2*cos(pi*_n)/(pi*_n**4 - 2*pi*_n**2*k**2 +
    pi*k**4) - (-1)**k*pi*_n**2*cos(pi*_n)/(-pi*_n**4 + 2*pi*_n**2*k**2 -
    pi*k**4) - (-1)**k*pi**2*_n*k**2*sin(pi*_n)/(pi*_n**4 -
    2*pi*_n**2*k**2 + pi*k**4) +
    (-1)**k*pi**2*_n*k**2*sin(pi*_n)/(-pi*_n**4 + 2*pi*_n**2*k**2 -
    pi*k**4) + (-1)**k*pi*k**2*cos(pi*_n)/(pi*_n**4 - 2*pi*_n**2*k**2 +
    pi*k**4) - (-1)**k*pi*k**2*cos(pi*_n)/(-pi*_n**4 + 2*pi*_n**2*k**2 -
    pi*k**4) - (2*_n**2 + 2*k**2)/(_n**4 - 2*_n**2*k**2 + k**4),
    True))*cos(_n*x)/pi, (_n, 1, oo)), SeqFormula(0, (_k, 1, oo))))
    '''
    x = symbols("x", real=True)
    k = symbols('k', integer=True, finite=True)
    abs2 = lambda x: Piecewise((-x, x <= 0), (x, x > 0))
    assert integrate(abs2(x), (x, -pi, pi)) == pi**2
    func = cos(k * x) * sqrt(x**2)
    assert integrate(func, (x, -pi, pi)) == Piecewise(
        (2 * (-1)**k / k**2 - 2 / k**2, Ne(k, 0)), (pi**2, True))
Ejemplo n.º 15
0
def test_reduce_poly_inequalities_real_interval():
    assert reduce_rational_inequalities([[Eq(x**2, 0)]], x,
                                        relational=False) == FiniteSet(0)
    assert reduce_rational_inequalities([[Le(x**2, 0)]], x,
                                        relational=False) == FiniteSet(0)
    assert reduce_rational_inequalities([[Lt(x**2, 0)]], x,
                                        relational=False) == S.EmptySet
    assert reduce_rational_inequalities(
        [[Ge(x**2, 0)]], x, relational=False) == \
        S.Reals if x.is_real else Interval(-oo, oo)
    assert reduce_rational_inequalities(
        [[Gt(x**2, 0)]], x, relational=False) == \
        FiniteSet(0).complement(S.Reals)
    assert reduce_rational_inequalities(
        [[Ne(x**2, 0)]], x, relational=False) == \
        FiniteSet(0).complement(S.Reals)

    assert reduce_rational_inequalities([[Eq(x**2, 1)]], x,
                                        relational=False) == FiniteSet(-1, 1)
    assert reduce_rational_inequalities([[Le(x**2, 1)]], x,
                                        relational=False) == Interval(-1, 1)
    assert reduce_rational_inequalities([[Lt(x**2, 1)]], x,
                                        relational=False) == Interval(
                                            -1, 1, True, True)
    assert reduce_rational_inequalities(
        [[Ge(x**2, 1)]], x, relational=False) == \
        Union(Interval(-oo, -1), Interval(1, oo))
    assert reduce_rational_inequalities(
        [[Gt(x**2, 1)]], x, relational=False) == \
        Interval(-1, 1).complement(S.Reals)
    assert reduce_rational_inequalities(
        [[Ne(x**2, 1)]], x, relational=False) == \
        FiniteSet(-1, 1).complement(S.Reals)
    assert reduce_rational_inequalities([[Eq(x**2, 1.0)]], x,
                                        relational=False) == FiniteSet(
                                            -1.0, 1.0).evalf()
    assert reduce_rational_inequalities([[Le(x**2, 1.0)]], x,
                                        relational=False) == Interval(
                                            -1.0, 1.0)
    assert reduce_rational_inequalities([[Lt(x**2, 1.0)]], x,
                                        relational=False) == Interval(
                                            -1.0, 1.0, True, True)
    assert reduce_rational_inequalities(
        [[Ge(x**2, 1.0)]], x, relational=False) == \
        Union(Interval(-inf, -1.0), Interval(1.0, inf))
    assert reduce_rational_inequalities(
        [[Gt(x**2, 1.0)]], x, relational=False) == \
        Union(Interval(-inf, -1.0, right_open=True),
        Interval(1.0, inf, left_open=True))
    assert reduce_rational_inequalities([[Ne(
        x**2, 1.0)]], x, relational=False) == \
        FiniteSet(-1.0, 1.0).complement(S.Reals)

    s = sqrt(2)

    assert reduce_rational_inequalities(
        [[Lt(x**2 - 1, 0), Gt(x**2 - 1, 0)]], x,
        relational=False) == S.EmptySet
    assert reduce_rational_inequalities(
        [[Le(x**2 - 1, 0), Ge(x**2 - 1, 0)]], x,
        relational=False) == FiniteSet(-1, 1)
    assert reduce_rational_inequalities(
        [[Le(x**2 - 2, 0), Ge(x**2 - 1, 0)]], x,
        relational=False) == Union(Interval(-s, -1, False, False),
                                   Interval(1, s, False, False))
    assert reduce_rational_inequalities(
        [[Le(x**2 - 2, 0), Gt(x**2 - 1, 0)]], x,
        relational=False) == Union(Interval(-s, -1, False, True),
                                   Interval(1, s, True, False))
    assert reduce_rational_inequalities(
        [[Lt(x**2 - 2, 0), Ge(x**2 - 1, 0)]], x,
        relational=False) == Union(Interval(-s, -1, True, False),
                                   Interval(1, s, False, True))
    assert reduce_rational_inequalities(
        [[Lt(x**2 - 2, 0), Gt(x**2 - 1, 0)]], x,
        relational=False) == Union(Interval(-s, -1, True, True),
                                   Interval(1, s, True, True))
    assert reduce_rational_inequalities(
        [[Lt(x**2 - 2, 0), Ne(x**2 - 1, 0)]], x,
        relational=False) == Union(Interval(-s, -1, True, True),
                                   Interval(-1, 1, True, True),
                                   Interval(1, s, True, True))

    assert reduce_rational_inequalities([[Lt(x**2, -1.)]], x) is S.false
Ejemplo n.º 16
0
def test__solve_inequalities():
    assert reduce_inequalities(x + y < 1, symbols=[x]) == (x < 1 - y)
    assert reduce_inequalities(x + y >= 1,
                               symbols=[x]) == (x < oo) & (x >= -y + 1)
    assert reduce_inequalities(Eq(0, x - y), symbols=[x]) == Eq(x, y)
    assert reduce_inequalities(Ne(0, x - y), symbols=[x]) == Ne(x, y)
Ejemplo n.º 17
0
def test_hacky_inequalities():
    assert reduce_inequalities(x + y < 1, symbols=[x]) == (x < 1 - y)
    assert reduce_inequalities(x + y >= 1, symbols=[x]) == (x >= 1 - y)
    assert reduce_inequalities(Eq(0, x - y), symbols=[x]) == Eq(x, y)
    assert reduce_inequalities(Ne(0, x - y), symbols=[x]) == Ne(x, y)
Ejemplo n.º 18
0
def test_PoissonProcess():
    X = PoissonProcess("X", 3)
    assert X.state_space == S.Naturals0
    assert X.index_set == Interval(0, oo)
    assert X.lamda == 3

    t, d, x, y = symbols('t d x y', positive=True)
    assert isinstance(X(t), RandomIndexedSymbol)
    assert X.distribution(X(t)) == PoissonDistribution(3 * t)
    raises(ValueError, lambda: PoissonProcess("X", -1))
    raises(NotImplementedError, lambda: X[t])
    raises(IndexError, lambda: X(-5))

    assert X.joint_distribution(X(2), X(3)) == JointDistributionHandmade(
        Lambda((X(2), X(3)), 6**X(2) * 9**X(3) * exp(-15) /
               (factorial(X(2)) * factorial(X(3)))))

    assert X.joint_distribution(4, 6) == JointDistributionHandmade(
        Lambda((X(4), X(6)), 12**X(4) * 18**X(6) * exp(-30) /
               (factorial(X(4)) * factorial(X(6)))))

    assert P(X(t) < 1) == exp(-3 * t)
    assert P(Eq(X(t), 0),
             Contains(t, Interval.Lopen(3, 5))) == exp(-6)  # exp(-2*lamda)
    res = P(Eq(X(t), 1), Contains(t, Interval.Lopen(3, 4)))
    assert res == 3 * exp(-3)

    # Equivalent to P(Eq(X(t), 1))**4 because of non-overlapping intervals
    assert P(
        Eq(X(t), 1) & Eq(X(d), 1) & Eq(X(x), 1) & Eq(X(y), 1),
        Contains(t, Interval.Lopen(0, 1))
        & Contains(d, Interval.Lopen(1, 2)) & Contains(x, Interval.Lopen(2, 3))
        & Contains(y, Interval.Lopen(3, 4))) == res**4

    # Return Probability because of overlapping intervals
    assert P(Eq(X(t), 2) & Eq(X(d), 3), Contains(t, Interval.Lopen(0, 2))
    & Contains(d, Interval.Ropen(2, 4))) == \
                Probability(Eq(X(d), 3) & Eq(X(t), 2), Contains(t, Interval.Lopen(0, 2))
                & Contains(d, Interval.Ropen(2, 4)))

    raises(ValueError, lambda: P(
        Eq(X(t), 2) & Eq(X(d), 3),
        Contains(t, Interval.Lopen(0, 4)) & Contains(d, Interval.Lopen(3, oo)))
           )  # no bound on d
    assert P(Eq(X(3), 2)) == 81 * exp(-9) / 2
    assert P(Eq(X(t), 2), Contains(t, Interval.Lopen(0,
                                                     5))) == 225 * exp(-15) / 2

    # Check that probability works correctly by adding it to 1
    res1 = P(X(t) <= 3, Contains(t, Interval.Lopen(0, 5)))
    res2 = P(X(t) > 3, Contains(t, Interval.Lopen(0, 5)))
    assert res1 == 691 * exp(-15)
    assert (res1 + res2).simplify() == 1

    # Check Not and  Or
    assert P(Not(Eq(X(t), 2) & (X(d) > 3)), Contains(t, Interval.Ropen(2, 4)) & \
            Contains(d, Interval.Lopen(7, 8))).simplify() == -18*exp(-6) + 234*exp(-9) + 1
    assert P(Eq(X(t), 2) | Ne(X(t), 4),
             Contains(t, Interval.Ropen(2, 4))) == 1 - 36 * exp(-6)
    raises(ValueError, lambda: P(X(t) > 2, X(t) + X(d)))
    assert E(
        X(t)) == 3 * t  # property of the distribution at a given timestamp
    assert E(
        X(t)**2 + X(d) * 2 + X(y)**3,
        Contains(t, Interval.Lopen(0, 1))
        & Contains(d, Interval.Lopen(1, 2))
        & Contains(y, Interval.Ropen(3, 4))) == 75
    assert E(X(t)**2, Contains(t, Interval.Lopen(0, 1))) == 12
    assert E(x*(X(t) + X(d))*(X(t)**2+X(d)**2), Contains(t, Interval.Lopen(0, 1))
    & Contains(d, Interval.Ropen(1, 2))) == \
            Expectation(x*(X(d) + X(t))*(X(d)**2 + X(t)**2), Contains(t, Interval.Lopen(0, 1))
            & Contains(d, Interval.Ropen(1, 2)))

    # Value Error because of infinite time bound
    raises(ValueError, lambda: E(X(t)**3, Contains(t, Interval.Lopen(1, oo))))

    # Equivalent to E(X(t)**2) - E(X(d)**2) == E(X(1)**2) - E(X(1)**2) == 0
    assert E((X(t) + X(d)) * (X(t) - X(d)),
             Contains(t, Interval.Lopen(0, 1))
             & Contains(d, Interval.Lopen(1, 2))) == 0
    assert E(X(2) + x * E(X(5))) == 15 * x + 6
    assert E(x * X(1) + y) == 3 * x + y
    assert P(Eq(X(1), 2) & Eq(X(t), 3),
             Contains(t, Interval.Lopen(1, 2))) == 81 * exp(-6) / 4
    Y = PoissonProcess("Y", 6)
    Z = X + Y
    assert Z.lamda == X.lamda + Y.lamda == 9
    raises(ValueError,
           lambda: X + 5)  # should be added be only PoissonProcess instance
    N, M = Z.split(4, 5)
    assert N.lamda == 4
    assert M.lamda == 5
    raises(ValueError, lambda: Z.split(3, 2))  # 2+3 != 9

    raises(
        ValueError, lambda: P(Eq(X(t), 0),
                              Contains(t, Interval.Lopen(1, 3)) & Eq(X(1), 0)))
    # check if it handles queries with two random variables in one args
    res1 = P(Eq(N(3), N(5)))
    assert res1 == P(Eq(N(t), 0), Contains(t, Interval(3, 5)))
    res2 = P(N(3) > N(1))
    assert res2 == P((N(t) > 0), Contains(t, Interval(1, 3)))
    assert P(N(3) < N(1)) == 0  # condition is not possible
    res3 = P(N(3) <= N(1))  # holds only for Eq(N(3), N(1))
    assert res3 == P(Eq(N(t), 0), Contains(t, Interval(1, 3)))

    # tests from https://www.probabilitycourse.com/chapter11/11_1_2_basic_concepts_of_the_poisson_process.php
    X = PoissonProcess('X', 10)  # 11.1
    assert P(Eq(X(S(1) / 3), 3)
             & Eq(X(1), 10)) == exp(-10) * Rational(8000000000, 11160261)
    assert P(Eq(X(1), 1), Eq(X(S(1) / 3), 3)) == 0
    assert P(Eq(X(1), 10), Eq(X(S(1) / 3), 3)) == P(Eq(X(S(2) / 3), 7))

    X = PoissonProcess('X', 2)  # 11.2
    assert P(X(S(1) / 2) < 1) == exp(-1)
    assert P(X(3) < 1, Eq(X(1), 0)) == exp(-4)
    assert P(Eq(X(4), 3), Eq(X(2), 3)) == exp(-4)

    X = PoissonProcess('X', 3)
    assert P(Eq(X(2), 5) & Eq(X(1), 2)) == Rational(81, 4) * exp(-6)

    # check few properties
    assert P(
        X(2) <= 3,
        X(1) >= 1) == 3 * P(Eq(X(1), 0)) + 2 * P(Eq(X(1), 1)) + P(Eq(X(1), 2))
    assert P(X(2) <= 3, X(1) > 1) == 2 * P(Eq(X(1), 0)) + 1 * P(Eq(X(1), 1))
    assert P(Eq(X(2), 5) & Eq(X(1), 2)) == P(Eq(X(1), 3)) * P(Eq(X(1), 2))
    assert P(Eq(X(3), 4), Eq(X(1), 3)) == P(Eq(X(2), 1))
Ejemplo n.º 19
0
def test_DiscreteMarkovChain():

    # pass only the name
    X = DiscreteMarkovChain("X")
    assert isinstance(X.state_space, Range)
    assert X.index_set == S.Naturals0
    assert isinstance(X.transition_probabilities, MatrixSymbol)
    t = symbols('t', positive=True, integer=True)
    assert isinstance(X[t], RandomIndexedSymbol)
    assert E(X[0]) == Expectation(X[0])
    raises(TypeError, lambda: DiscreteMarkovChain(1))
    raises(NotImplementedError, lambda: X(t))
    raises(NotImplementedError, lambda: X.communication_classes())
    raises(NotImplementedError, lambda: X.canonical_form())
    raises(NotImplementedError, lambda: X.decompose())

    nz = Symbol('n', integer=True)
    TZ = MatrixSymbol('M', nz, nz)
    SZ = Range(nz)
    YZ = DiscreteMarkovChain('Y', SZ, TZ)
    assert P(Eq(YZ[2], 1), Eq(YZ[1], 0)) == TZ[0, 1]

    raises(ValueError, lambda: sample_stochastic_process(t))
    raises(ValueError, lambda: next(sample_stochastic_process(X)))
    # pass name and state_space
    # any hashable object should be a valid state
    # states should be valid as a tuple/set/list/Tuple/Range
    sym, rainy, cloudy, sunny = symbols('a Rainy Cloudy Sunny', real=True)
    state_spaces = [(1, 2, 3), [Str('Hello'), sym, DiscreteMarkovChain],
                    Tuple(1, exp(sym), Str('World'), sympify=False),
                    Range(-1, 5, 2), [rainy, cloudy, sunny]]
    chains = [
        DiscreteMarkovChain("Y", state_space) for state_space in state_spaces
    ]

    for i, Y in enumerate(chains):
        assert isinstance(Y.transition_probabilities, MatrixSymbol)
        assert Y.state_space == state_spaces[i] or Y.state_space == FiniteSet(
            *state_spaces[i])
        assert Y.number_of_states == 3

        with ignore_warnings(
                UserWarning):  # TODO: Restore tests once warnings are removed
            assert P(Eq(Y[2], 1), Eq(Y[0], 2),
                     evaluate=False) == Probability(Eq(Y[2], 1), Eq(Y[0], 2))
        assert E(Y[0]) == Expectation(Y[0])

        raises(ValueError, lambda: next(sample_stochastic_process(Y)))

    raises(TypeError, lambda: DiscreteMarkovChain("Y", dict((1, 1))))
    Y = DiscreteMarkovChain("Y", Range(1, t, 2))
    assert Y.number_of_states == ceiling((t - 1) / 2)

    # pass name and transition_probabilities
    chains = [
        DiscreteMarkovChain("Y", trans_probs=Matrix([[]])),
        DiscreteMarkovChain("Y", trans_probs=Matrix([[0, 1], [1, 0]])),
        DiscreteMarkovChain("Y",
                            trans_probs=Matrix([[pi, 1 - pi], [sym, 1 - sym]]))
    ]
    for Z in chains:
        assert Z.number_of_states == Z.transition_probabilities.shape[0]
        assert isinstance(Z.transition_probabilities, ImmutableDenseMatrix)

    # pass name, state_space and transition_probabilities
    T = Matrix([[0.5, 0.2, 0.3], [0.2, 0.5, 0.3], [0.2, 0.3, 0.5]])
    TS = MatrixSymbol('T', 3, 3)
    Y = DiscreteMarkovChain("Y", [0, 1, 2], T)
    YS = DiscreteMarkovChain("Y", ['One', 'Two', 3], TS)
    assert YS._transient2transient() == None
    assert YS._transient2absorbing() == None
    assert Y.joint_distribution(1, Y[2],
                                3) == JointDistribution(Y[1], Y[2], Y[3])
    raises(ValueError, lambda: Y.joint_distribution(Y[1].symbol, Y[2].symbol))
    assert P(Eq(Y[3], 2), Eq(Y[1], 1)).round(2) == Float(0.36, 2)
    assert (P(Eq(YS[3], 2), Eq(YS[1], 1)) -
            (TS[0, 2] * TS[1, 0] + TS[1, 1] * TS[1, 2] +
             TS[1, 2] * TS[2, 2])).simplify() == 0
    assert P(Eq(YS[1], 1), Eq(YS[2], 2)) == Probability(Eq(YS[1], 1))
    assert P(Eq(YS[3], 3), Eq(
        YS[1],
        1)) == TS[0, 2] * TS[1, 0] + TS[1, 1] * TS[1, 2] + TS[1, 2] * TS[2, 2]
    TO = Matrix([[0.25, 0.75, 0], [0, 0.25, 0.75], [0.75, 0, 0.25]])
    assert P(Eq(Y[3], 2),
             Eq(Y[1], 1) & TransitionMatrixOf(Y, TO)).round(3) == Float(
                 0.375, 3)
    with ignore_warnings(
            UserWarning):  ### TODO: Restore tests once warnings are removed
        assert E(Y[3], evaluate=False) == Expectation(Y[3])
        assert E(Y[3], Eq(Y[2], 1)).round(2) == Float(1.1, 3)
    TSO = MatrixSymbol('T', 4, 4)
    raises(
        ValueError,
        lambda: str(P(Eq(YS[3], 2),
                      Eq(YS[1], 1) & TransitionMatrixOf(YS, TSO))))
    raises(TypeError,
           lambda: DiscreteMarkovChain("Z", [0, 1, 2], symbols('M')))
    raises(
        ValueError,
        lambda: DiscreteMarkovChain("Z", [0, 1, 2], MatrixSymbol('T', 3, 4)))
    raises(ValueError, lambda: E(Y[3], Eq(Y[2], 6)))
    raises(ValueError, lambda: E(Y[2], Eq(Y[3], 1)))

    # extended tests for probability queries
    TO1 = Matrix([[Rational(1, 4), Rational(3, 4), 0],
                  [Rational(1, 3),
                   Rational(1, 3),
                   Rational(1, 3)], [0, Rational(1, 4),
                                     Rational(3, 4)]])
    assert P(
        And(Eq(Y[2], 1), Eq(Y[1], 1), Eq(Y[0], 0)),
        Eq(Probability(Eq(Y[0], 0)), Rational(1, 4))
        & TransitionMatrixOf(Y, TO1)) == Rational(1, 16)
    assert P(And(Eq(Y[2], 1), Eq(Y[1], 1), Eq(Y[0], 0)), TransitionMatrixOf(Y, TO1)) == \
            Probability(Eq(Y[0], 0))/4
    assert P(
        Lt(X[1], 2) & Gt(X[1], 0),
        Eq(X[0], 2) & StochasticStateSpaceOf(X, [0, 1, 2])
        & TransitionMatrixOf(X, TO1)) == Rational(1, 4)
    assert P(
        Lt(X[1], 2) & Gt(X[1], 0),
        Eq(X[0], 2) & StochasticStateSpaceOf(X, [None, 'None', 1])
        & TransitionMatrixOf(X, TO1)) == Rational(1, 4)
    assert P(
        Ne(X[1], 2) & Ne(X[1], 1),
        Eq(X[0], 2) & StochasticStateSpaceOf(X, [0, 1, 2])
        & TransitionMatrixOf(X, TO1)) is S.Zero
    assert P(
        Ne(X[1], 2) & Ne(X[1], 1),
        Eq(X[0], 2) & StochasticStateSpaceOf(X, [None, 'None', 1])
        & TransitionMatrixOf(X, TO1)) is S.Zero
    assert P(And(Eq(Y[2], 1), Eq(Y[1], 1), Eq(Y[0], 0)),
             Eq(Y[1], 1)) == 0.1 * Probability(Eq(Y[0], 0))

    # testing properties of Markov chain
    TO2 = Matrix([[S.One, 0, 0],
                  [Rational(1, 3),
                   Rational(1, 3),
                   Rational(1, 3)], [0, Rational(1, 4),
                                     Rational(3, 4)]])
    TO3 = Matrix([[Rational(1, 4), Rational(3, 4), 0],
                  [Rational(1, 3),
                   Rational(1, 3),
                   Rational(1, 3)], [0, Rational(1, 4),
                                     Rational(3, 4)]])
    Y2 = DiscreteMarkovChain('Y', trans_probs=TO2)
    Y3 = DiscreteMarkovChain('Y', trans_probs=TO3)
    assert Y3._transient2absorbing() == None
    raises(ValueError, lambda: Y3.fundamental_matrix())
    assert Y2.is_absorbing_chain() == True
    assert Y3.is_absorbing_chain() == False
    assert Y2.canonical_form() == ([0, 1, 2], TO2)
    assert Y3.canonical_form() == ([0, 1, 2], TO3)
    assert Y2.decompose() == ([0, 1,
                               2], TO2[0:1, 0:1], TO2[1:3, 0:1], TO2[1:3, 1:3])
    assert Y3.decompose() == ([0, 1, 2], TO3, Matrix(0, 3,
                                                     []), Matrix(0, 0, []))
    TO4 = Matrix([[Rational(1, 5),
                   Rational(2, 5),
                   Rational(2, 5)], [Rational(1, 10), S.Half,
                                     Rational(2, 5)],
                  [Rational(3, 5),
                   Rational(3, 10),
                   Rational(1, 10)]])
    Y4 = DiscreteMarkovChain('Y', trans_probs=TO4)
    w = ImmutableMatrix([[Rational(11, 39),
                          Rational(16, 39),
                          Rational(4, 13)]])
    assert Y4.limiting_distribution == w
    assert Y4.is_regular() == True
    TS1 = MatrixSymbol('T', 3, 3)
    Y5 = DiscreteMarkovChain('Y', trans_probs=TS1)
    assert Y5.limiting_distribution(w, TO4).doit() == True
    assert Y5.stationary_distribution(condition_set=True).subs(
        TS1, TO4).contains(w).doit() == S.true
    TO6 = Matrix([[S.One, 0, 0, 0, 0], [S.Half, 0, S.Half, 0, 0],
                  [0, S.Half, 0, S.Half, 0], [0, 0, S.Half, 0, S.Half],
                  [0, 0, 0, 0, 1]])
    Y6 = DiscreteMarkovChain('Y', trans_probs=TO6)
    assert Y6._transient2absorbing() == ImmutableMatrix([[S.Half, 0], [0, 0],
                                                         [0, S.Half]])
    assert Y6._transient2transient() == ImmutableMatrix([[0, S.Half, 0],
                                                         [S.Half, 0, S.Half],
                                                         [0, S.Half, 0]])
    assert Y6.fundamental_matrix() == ImmutableMatrix(
        [[Rational(3, 2), S.One, S.Half], [S.One, S(2), S.One],
         [S.Half, S.One, Rational(3, 2)]])
    assert Y6.absorbing_probabilities() == ImmutableMatrix(
        [[Rational(3, 4), Rational(1, 4)], [S.Half, S.Half],
         [Rational(1, 4), Rational(3, 4)]])

    # test for zero-sized matrix functionality
    X = DiscreteMarkovChain('X', trans_probs=Matrix([[]]))
    assert X.number_of_states == 0
    assert X.stationary_distribution() == Matrix([[]])
    assert X.communication_classes() == []
    assert X.canonical_form() == ([], Matrix([[]]))
    assert X.decompose() == ([], Matrix([[]]), Matrix([[]]), Matrix([[]]))

    # test communication_class
    # see https://drive.google.com/drive/folders/1HbxLlwwn2b3U8Lj7eb_ASIUb5vYaNIjg?usp=sharing
    # tutorial 2.pdf
    TO7 = Matrix([[0, 5, 5, 0, 0], [0, 0, 0, 10, 0], [5, 0, 5, 0, 0],
                  [0, 10, 0, 0, 0], [0, 3, 0, 3, 4]]) / 10
    Y7 = DiscreteMarkovChain('Y', trans_probs=TO7)
    tuples = Y7.communication_classes()
    classes, recurrence, periods = list(zip(*tuples))
    assert classes == ([1, 3], [0, 2], [4])
    assert recurrence == (True, False, False)
    assert periods == (2, 1, 1)

    TO8 = Matrix([[0, 0, 0, 10, 0, 0], [5, 0, 5, 0, 0, 0], [0, 4, 0, 0, 0, 6],
                  [10, 0, 0, 0, 0, 0], [0, 10, 0, 0, 0, 0], [0, 0, 0, 5, 5, 0]
                  ]) / 10
    Y8 = DiscreteMarkovChain('Y', trans_probs=TO8)
    tuples = Y8.communication_classes()
    classes, recurrence, periods = list(zip(*tuples))
    assert classes == ([0, 3], [1, 2, 5, 4])
    assert recurrence == (True, False)
    assert periods == (2, 2)

    TO9 = Matrix(
        [[2, 0, 0, 3, 0, 0, 3, 2, 0, 0], [0, 10, 0, 0, 0, 0, 0, 0, 0, 0],
         [0, 2, 2, 0, 0, 0, 0, 0, 3, 3], [0, 0, 0, 3, 0, 0, 6, 1, 0, 0],
         [0, 0, 0, 0, 5, 5, 0, 0, 0, 0], [0, 0, 0, 0, 0, 10, 0, 0, 0, 0],
         [4, 0, 0, 5, 0, 0, 1, 0, 0, 0], [2, 0, 0, 4, 0, 0, 2, 2, 0, 0],
         [3, 0, 1, 0, 0, 0, 0, 0, 4, 2], [0, 0, 4, 0, 0, 0, 0, 0, 3, 3]]) / 10
    Y9 = DiscreteMarkovChain('Y', trans_probs=TO9)
    tuples = Y9.communication_classes()
    classes, recurrence, periods = list(zip(*tuples))
    assert classes == ([0, 3, 6, 7], [1], [2, 8, 9], [5], [4])
    assert recurrence == (True, True, False, True, False)
    assert periods == (1, 1, 1, 1, 1)

    # test canonical form
    # see https://www.dartmouth.edu/~chance/teaching_aids/books_articles/probability_book/Chapter11.pdf
    # example 11.13
    T = Matrix([[1, 0, 0, 0, 0], [S(1) / 2, 0, S(1) / 2, 0, 0],
                [0, S(1) / 2, 0, S(1) / 2, 0], [0, 0,
                                                S(1) / 2, 0,
                                                S(1) / 2], [0, 0, 0, 0,
                                                            S(1)]])
    DW = DiscreteMarkovChain('DW', [0, 1, 2, 3, 4], T)
    states, A, B, C = DW.decompose()
    assert states == [0, 4, 1, 2, 3]
    assert A == Matrix([[1, 0], [0, 1]])
    assert B == Matrix([[S(1) / 2, 0], [0, 0], [0, S(1) / 2]])
    assert C == Matrix([[0, S(1) / 2, 0], [S(1) / 2, 0, S(1) / 2],
                        [0, S(1) / 2, 0]])
    states, new_matrix = DW.canonical_form()
    assert states == [0, 4, 1, 2, 3]
    assert new_matrix == Matrix([[1, 0, 0, 0, 0], [0, 1, 0, 0, 0],
                                 [S(1) / 2, 0, 0, S(1) / 2, 0],
                                 [0, 0, S(1) / 2, 0,
                                  S(1) / 2], [0, S(1) / 2, 0,
                                              S(1) / 2, 0]])

    # test custom state space
    Y10 = DiscreteMarkovChain('Y', [1, 2, 3], TO2)
    tuples = Y10.communication_classes()
    classes, recurrence, periods = list(zip(*tuples))
    assert classes == ([1], [2, 3])
    assert recurrence == (True, False)
    assert periods == (1, 1)
    assert Y10.canonical_form() == ([1, 2, 3], TO2)
    assert Y10.decompose() == ([1, 2, 3], TO2[0:1, 0:1], TO2[1:3,
                                                             0:1], TO2[1:3,
                                                                       1:3])

    # testing miscellaneous queries
    T = Matrix([[S.Half, Rational(1, 4),
                 Rational(1, 4)], [Rational(1, 3), 0,
                                   Rational(2, 3)], [S.Half, S.Half, 0]])
    X = DiscreteMarkovChain('X', [0, 1, 2], T)
    assert P(
        Eq(X[1], 2) & Eq(X[2], 1) & Eq(X[3], 0),
        Eq(P(Eq(X[1], 0)), Rational(1, 4))
        & Eq(P(Eq(X[1], 1)), Rational(1, 4))) == Rational(1, 12)
    assert P(Eq(X[2], 1) | Eq(X[2], 2), Eq(X[1], 1)) == Rational(2, 3)
    assert P(Eq(X[2], 1) & Eq(X[2], 2), Eq(X[1], 1)) is S.Zero
    assert P(Ne(X[2], 2), Eq(X[1], 1)) == Rational(1, 3)
    assert E(X[1]**2, Eq(X[0], 1)) == Rational(8, 3)
    assert variance(X[1], Eq(X[0], 1)) == Rational(8, 9)
    raises(ValueError, lambda: E(X[1], Eq(X[2], 1)))
    raises(ValueError, lambda: DiscreteMarkovChain('X', [0, 1], T))

    # testing miscellaneous queries with different state space
    X = DiscreteMarkovChain('X', ['A', 'B', 'C'], T)
    assert P(
        Eq(X[1], 2) & Eq(X[2], 1) & Eq(X[3], 0),
        Eq(P(Eq(X[1], 0)), Rational(1, 4))
        & Eq(P(Eq(X[1], 1)), Rational(1, 4))) == Rational(1, 12)
    assert P(Eq(X[2], 1) | Eq(X[2], 2), Eq(X[1], 1)) == Rational(2, 3)
    assert P(Eq(X[2], 1) & Eq(X[2], 2), Eq(X[1], 1)) is S.Zero
    assert P(Ne(X[2], 2), Eq(X[1], 1)) == Rational(1, 3)
    a = X.state_space.args[0]
    c = X.state_space.args[2]
    assert (E(X[1]**2, Eq(X[0], 1)) -
            (a**2 / 3 + 2 * c**2 / 3)).simplify() == 0
    assert (variance(X[1], Eq(X[0], 1)) -
            (2 * (-a / 3 + c / 3)**2 / 3 +
             (2 * a / 3 - 2 * c / 3)**2 / 3)).simplify() == 0
    raises(ValueError, lambda: E(X[1], Eq(X[2], 1)))

    #testing queries with multiple RandomIndexedSymbols
    T = Matrix([[Rational(5, 10),
                 Rational(3, 10),
                 Rational(2, 10)],
                [Rational(2, 10),
                 Rational(7, 10),
                 Rational(1, 10)],
                [Rational(3, 10),
                 Rational(3, 10),
                 Rational(4, 10)]])
    Y = DiscreteMarkovChain("Y", [0, 1, 2], T)
    assert P(Eq(Y[7], Y[5]), Eq(Y[2], 0)).round(5) == Float(0.44428, 5)
    assert P(Gt(Y[3], Y[1]), Eq(Y[0], 0)).round(2) == Float(0.36, 2)
    assert P(Le(Y[5], Y[10]), Eq(Y[4], 2)).round(6) == Float(0.739072, 6)
    assert Float(P(Eq(Y[500], Y[240]), Eq(Y[120], 1)),
                 14) == Float(1 - P(Ne(Y[500], Y[240]), Eq(Y[120], 1)), 14)
    assert Float(P(Gt(Y[350], Y[100]), Eq(Y[75], 2)),
                 14) == Float(1 - P(Le(Y[350], Y[100]), Eq(Y[75], 2)), 14)
    assert Float(P(Lt(Y[400], Y[210]), Eq(Y[161], 0)),
                 14) == Float(1 - P(Ge(Y[400], Y[210]), Eq(Y[161], 0)), 14)
Ejemplo n.º 20
0
def test_reduce_poly_inequalities_real_relational():
    x = Symbol('x', real=True)
    y = Symbol('y', real=True)

    assert reduce_rational_inequalities([[Eq(x**2, 0)]], x,
                                        relational=True) == Eq(x, 0)
    assert reduce_rational_inequalities([[Le(x**2, 0)]], x,
                                        relational=True) == Eq(x, 0)
    assert reduce_rational_inequalities([[Lt(x**2, 0)]], x,
                                        relational=True) == False
    assert reduce_rational_inequalities([[Ge(x**2, 0)]], x,
                                        relational=True) == And(
                                            Lt(-oo, x), Lt(x, oo))
    assert reduce_rational_inequalities([[Gt(x**2, 0)]], x,
                                        relational=True) == Or(
                                            And(Lt(-oo, x), Lt(x, 0)),
                                            And(Lt(0, x), Lt(x, oo)))
    assert reduce_rational_inequalities([[Ne(x**2, 0)]], x,
                                        relational=True) == Or(
                                            And(Lt(-oo, x), Lt(x, 0)),
                                            And(Lt(0, x), Lt(x, oo)))

    assert reduce_rational_inequalities([[Eq(x**2, 1)]], x,
                                        relational=True) == Or(
                                            Eq(x, -1), Eq(x, 1))
    assert reduce_rational_inequalities([[Le(x**2, 1)]], x,
                                        relational=True) == And(
                                            Le(-1, x), Le(x, 1))
    assert reduce_rational_inequalities([[Lt(x**2, 1)]], x,
                                        relational=True) == And(
                                            Lt(-1, x), Lt(x, 1))
    assert reduce_rational_inequalities([[Ge(x**2, 1)]], x,
                                        relational=True) == Or(
                                            And(Le(1, x), Lt(x, oo)),
                                            And(Le(x, -1), Lt(-oo, x)))
    assert reduce_rational_inequalities([[Gt(x**2, 1)]], x,
                                        relational=True) == Or(
                                            And(Lt(1, x), Lt(x, oo)),
                                            And(Lt(x, -1), Lt(-oo, x)))
    assert reduce_rational_inequalities([[Ne(x**2, 1)]], x,
                                        relational=True) == Or(
                                            And(Lt(-oo, x), Lt(x, -1)),
                                            And(Lt(-1, x), Lt(x, 1)),
                                            And(Lt(1, x), Lt(x, oo)))

    assert reduce_rational_inequalities([[Le(x**2, 1.0)]], x,
                                        relational=True) == And(
                                            Le(-1.0, x), Le(x, 1.0))
    assert reduce_rational_inequalities([[Lt(x**2, 1.0)]], x,
                                        relational=True) == And(
                                            Lt(-1.0, x), Lt(x, 1.0))
    assert reduce_rational_inequalities([[Ge(x**2, 1.0)]], x,
                                        relational=True) == Or(
                                            And(Lt(Float('-inf'), x),
                                                Le(x, -1.0)),
                                            And(Le(1.0, x),
                                                Lt(x, Float('+inf'))))
    assert reduce_rational_inequalities([[Gt(x**2, 1.0)]], x,
                                        relational=True) == Or(
                                            And(Lt(Float('-inf'), x),
                                                Lt(x, -1.0)),
                                            And(Lt(1.0, x),
                                                Lt(x, Float('+inf'))))
    assert reduce_rational_inequalities([[Ne(x**2, 1.0)]], x, relational=True) == \
            Or(And(Lt(-1.0, x), Lt(x, 1.0)), And(Lt(Float('-inf'), x), Lt(x, -1.0)),
               And(Lt(1.0, x), Lt(x, Float('+inf'))))
Ejemplo n.º 21
0
def test_ContinuousMarkovChain():
    T1 = Matrix([[S(-2), S(2), S.Zero], [S.Zero, S.NegativeOne, S.One],
                 [Rational(3, 2), Rational(3, 2),
                  S(-3)]])
    C1 = ContinuousMarkovChain('C', [0, 1, 2], T1)
    assert C1.limiting_distribution() == ImmutableMatrix(
        [[Rational(3, 19), Rational(12, 19),
          Rational(4, 19)]])

    T2 = Matrix([[-S.One, S.One, S.Zero], [S.One, -S.One, S.Zero],
                 [S.Zero, S.One, -S.One]])
    C2 = ContinuousMarkovChain('C', [0, 1, 2], T2)
    A, t = C2.generator_matrix, symbols('t', positive=True)
    assert C2.transition_probabilities(A)(t) == Matrix(
        [[S.Half + exp(-2 * t) / 2, S.Half - exp(-2 * t) / 2, 0],
         [S.Half - exp(-2 * t) / 2, S.Half + exp(-2 * t) / 2, 0],
         [
             S.Half - exp(-t) + exp(-2 * t) / 2, S.Half - exp(-2 * t) / 2,
             exp(-t)
         ]])
    with ignore_warnings(
            UserWarning):  ### TODO: Restore tests once warnings are removed
        assert P(Eq(C2(1), 1), Eq(C2(0), 1),
                 evaluate=False) == Probability(Eq(C2(1), 1), Eq(C2(0), 1))
    assert P(Eq(C2(1), 1), Eq(C2(0), 1)) == exp(-2) / 2 + S.Half
    assert P(
        Eq(C2(1), 0) & Eq(C2(2), 1) & Eq(C2(3), 1),
        Eq(P(Eq(C2(1), 0)),
           S.Half)) == (Rational(1, 4) - exp(-2) / 4) * (exp(-2) / 2 + S.Half)
    assert P(
        Not(Eq(C2(1), 0) & Eq(C2(2), 1) & Eq(C2(3), 2)) |
        (Eq(C2(1), 0) & Eq(C2(2), 1) & Eq(C2(3), 2)),
        Eq(P(Eq(C2(1), 0)), Rational(1, 4))
        & Eq(P(Eq(C2(1), 1)), Rational(1, 4))) is S.One
    assert E(C2(Rational(3, 2)),
             Eq(C2(0), 2)) == -exp(-3) / 2 + 2 * exp(Rational(-3, 2)) + S.Half
    assert variance(C2(Rational(3, 2)), Eq(
        C2(0),
        1)) == ((S.Half - exp(-3) / 2)**2 * (exp(-3) / 2 + S.Half) +
                (Rational(-1, 2) - exp(-3) / 2)**2 * (S.Half - exp(-3) / 2))
    raises(KeyError, lambda: P(Eq(C2(1), 0), Eq(P(Eq(C2(1), 1)), S.Half)))
    assert P(Eq(C2(1), 0), Eq(P(Eq(C2(5), 1)),
                              S.Half)) == Probability(Eq(C2(1), 0))
    TS1 = MatrixSymbol('G', 3, 3)
    CS1 = ContinuousMarkovChain('C', [0, 1, 2], TS1)
    A = CS1.generator_matrix
    assert CS1.transition_probabilities(A)(t) == exp(t * A)

    C3 = ContinuousMarkovChain(
        'C', [Symbol('0'), Symbol('1'), Symbol('2')], T2)
    assert P(Eq(C3(1), 1), Eq(C3(0), 1)) == exp(-2) / 2 + S.Half
    assert P(Eq(C3(1), Symbol('1')), Eq(C3(0),
                                        Symbol('1'))) == exp(-2) / 2 + S.Half

    #test probability queries
    G = Matrix([[-S(1), Rational(1, 10),
                 Rational(9, 10)], [Rational(2, 5), -S(1),
                                    Rational(3, 5)],
                [Rational(1, 2), Rational(1, 2), -S(1)]])
    C = ContinuousMarkovChain('C', state_space=[0, 1, 2], gen_mat=G)
    assert P(Eq(C(7.385), C(3.19)), Eq(C(0.862),
                                       0)).round(5) == Float(0.35469, 5)
    assert P(Gt(C(98.715), C(19.807)), Eq(C(11.314),
                                          2)).round(5) == Float(0.32452, 5)
    assert P(Le(C(5.9), C(10.112)), Eq(C(4), 1)).round(6) == Float(0.675214, 6)
    assert Float(P(Eq(C(7.32), C(2.91)), Eq(C(2.63), 1)),
                 14) == Float(1 - P(Ne(C(7.32), C(2.91)), Eq(C(2.63), 1)), 14)
    assert Float(P(Gt(C(3.36), C(1.101)), Eq(C(0.8), 2)),
                 14) == Float(1 - P(Le(C(3.36), C(1.101)), Eq(C(0.8), 2)), 14)
    assert Float(P(Lt(C(4.9), C(2.79)), Eq(C(1.61), 0)),
                 14) == Float(1 - P(Ge(C(4.9), C(2.79)), Eq(C(1.61), 0)), 14)
    assert P(Eq(C(5.243), C(10.912)), Eq(C(2.174),
                                         1)) == P(Eq(C(10.912), C(5.243)),
                                                  Eq(C(2.174), 1))
    assert P(Gt(C(2.344), C(9.9)), Eq(C(1.102),
                                      1)) == P(Lt(C(9.9), C(2.344)),
                                               Eq(C(1.102), 1))
    assert P(Ge(C(7.87), C(1.008)), Eq(C(0.153),
                                       1)) == P(Le(C(1.008), C(7.87)),
                                                Eq(C(0.153), 1))

    #test symbolic queries
    a, b, c, d = symbols('a b c d')
    query = P(Eq(C(a), b), Eq(C(c), d))
    assert query.subs({
        a: 3.65,
        b: 2,
        c: 1.78,
        d: 1
    }).evalf().round(10) == P(Eq(C(3.65), 2), Eq(C(1.78), 1)).round(10)
    query_gt = P(Gt(C(a), b), Eq(C(c), d))
    query_le = P(Le(C(a), b), Eq(C(c), d))
    assert query_gt.subs({
        a: 13.2,
        b: 0,
        c: 3.29,
        d: 2
    }).evalf() + query_le.subs({
        a: 13.2,
        b: 0,
        c: 3.29,
        d: 2
    }).evalf() == 1
    query_ge = P(Ge(C(a), b), Eq(C(c), d))
    query_lt = P(Lt(C(a), b), Eq(C(c), d))
    assert query_ge.subs({
        a: 7.43,
        b: 1,
        c: 1.45,
        d: 0
    }).evalf() + query_lt.subs({
        a: 7.43,
        b: 1,
        c: 1.45,
        d: 0
    }).evalf() == 1
Ejemplo n.º 22
0
def test_integrate_returns_piecewise():
    assert integrate(x**y, x) == Piecewise(
        (x**(y + 1)/(y + 1), Ne(y, -1)), (log(x), True))
    assert integrate(x**y, y) == Piecewise(
        (x**y/log(x), Ne(log(x), 0)), (y, True))
    assert integrate(exp(n*x), x) == Piecewise(
        (exp(n*x)/n, Ne(n, 0)), (x, True))
    assert integrate(x*exp(n*x), x) == Piecewise(
        ((n**2*x - n)*exp(n*x)/n**3, Ne(n**3, 0)), (x**2/2, True))
    assert integrate(x**(n*y), x) == Piecewise(
        (x**(n*y + 1)/(n*y + 1), Ne(n*y, -1)), (log(x), True))
    assert integrate(x**(n*y), y) == Piecewise(
        (x**(n*y)/(n*log(x)), Ne(n*log(x), 0)), (y, True))
    assert integrate(cos(n*x), x) == Piecewise(
        (sin(n*x)/n, Ne(n, 0)), (x, True))
    assert integrate(cos(n*x)**2, x) == Piecewise(
        ((n*x/2 + sin(n*x)*cos(n*x)/2)/n, Ne(n, 0)), (x, True))
    assert integrate(x*cos(n*x), x) == Piecewise(
        (x*sin(n*x)/n + cos(n*x)/n**2, Ne(n, 0)), (x**2/2, True))
    assert integrate(sin(n*x), x) == Piecewise(
        (-cos(n*x)/n, Ne(n, 0)), (0, True))
    assert integrate(sin(n*x)**2, x) == Piecewise(
        ((n*x/2 - sin(n*x)*cos(n*x)/2)/n, Ne(n, 0)), (0, True))
    assert integrate(x*sin(n*x), x) == Piecewise(
        (-x*cos(n*x)/n + sin(n*x)/n**2, Ne(n, 0)), (0, True))
    assert integrate(exp(x*y), (x, 0, z)) == Piecewise(
        (exp(y*z)/y - 1/y, (y > -oo) & (y < oo) & Ne(y, 0)), (z, True))
Ejemplo n.º 23
0
def test_DiscreteMarkovChain():

    # pass only the name
    X = DiscreteMarkovChain("X")
    assert X.state_space == S.Reals
    assert X.index_set == S.Naturals0
    assert X.transition_probabilities == None
    t = symbols("t", positive=True, integer=True)
    assert isinstance(X[t], RandomIndexedSymbol)
    assert E(X[0]) == Expectation(X[0])
    raises(TypeError, lambda: DiscreteMarkovChain(1))
    raises(NotImplementedError, lambda: X(t))

    # pass name and state_space
    Y = DiscreteMarkovChain("Y", [1, 2, 3])
    assert Y.transition_probabilities == None
    assert Y.state_space == FiniteSet(1, 2, 3)
    assert P(Eq(Y[2], 1), Eq(Y[0], 2)) == Probability(Eq(Y[2], 1), Eq(Y[0], 2))
    assert E(X[0]) == Expectation(X[0])
    raises(TypeError, lambda: DiscreteMarkovChain("Y", dict((1, 1))))

    # pass name, state_space and transition_probabilities
    T = Matrix([[0.5, 0.2, 0.3], [0.2, 0.5, 0.3], [0.2, 0.3, 0.5]])
    TS = MatrixSymbol("T", 3, 3)
    Y = DiscreteMarkovChain("Y", [0, 1, 2], T)
    YS = DiscreteMarkovChain("Y", [0, 1, 2], TS)
    assert YS._transient2transient() == None
    assert YS._transient2absorbing() == None
    assert Y.joint_distribution(1, Y[2],
                                3) == JointDistribution(Y[1], Y[2], Y[3])
    raises(ValueError, lambda: Y.joint_distribution(Y[1].symbol, Y[2].symbol))
    assert P(Eq(Y[3], 2), Eq(Y[1], 1)).round(2) == Float(0.36, 2)
    assert (str(P(Eq(YS[3], 2), Eq(
        YS[1], 1))) == "T[0, 2]*T[1, 0] + T[1, 1]*T[1, 2] + T[1, 2]*T[2, 2]")
    assert P(Eq(YS[1], 1), Eq(YS[2], 2)) == Probability(Eq(YS[1], 1))
    assert P(Eq(YS[3], 3), Eq(YS[1], 1)) is S.Zero
    TO = Matrix([[0.25, 0.75, 0], [0, 0.25, 0.75], [0.75, 0, 0.25]])
    assert P(Eq(Y[3], 2),
             Eq(Y[1], 1) & TransitionMatrixOf(Y, TO)).round(3) == Float(
                 0.375, 3)
    assert E(Y[3], evaluate=False) == Expectation(Y[3])
    assert E(Y[3], Eq(Y[2], 1)).round(2) == Float(1.1, 3)
    TSO = MatrixSymbol("T", 4, 4)
    raises(
        ValueError,
        lambda: str(P(Eq(YS[3], 2),
                      Eq(YS[1], 1) & TransitionMatrixOf(YS, TSO))),
    )
    raises(TypeError,
           lambda: DiscreteMarkovChain("Z", [0, 1, 2], symbols("M")))
    raises(
        ValueError,
        lambda: DiscreteMarkovChain("Z", [0, 1, 2], MatrixSymbol("T", 3, 4)))
    raises(ValueError, lambda: E(Y[3], Eq(Y[2], 6)))
    raises(ValueError, lambda: E(Y[2], Eq(Y[3], 1)))

    # extended tests for probability queries
    TO1 = Matrix([
        [Rational(1, 4), Rational(3, 4), 0],
        [Rational(1, 3), Rational(1, 3),
         Rational(1, 3)],
        [0, Rational(1, 4), Rational(3, 4)],
    ])
    assert P(
        And(Eq(Y[2], 1), Eq(Y[1], 1), Eq(Y[0], 0)),
        Eq(Probability(Eq(Y[0], 0)), Rational(1, 4))
        & TransitionMatrixOf(Y, TO1),
    ) == Rational(1, 16)
    assert (P(And(Eq(Y[2], 1), Eq(Y[1], 1), Eq(Y[0], 0)),
              TransitionMatrixOf(Y, TO1)) == Probability(Eq(Y[0], 0)) / 4)
    assert P(
        Lt(X[1], 2) & Gt(X[1], 0),
        Eq(X[0], 2) & StochasticStateSpaceOf(X, [0, 1, 2])
        & TransitionMatrixOf(X, TO1),
    ) == Rational(1, 4)
    assert (P(
        Ne(X[1], 2) & Ne(X[1], 1),
        Eq(X[0], 2)
        & StochasticStateSpaceOf(X, [0, 1, 2])
        & TransitionMatrixOf(X, TO1),
    ) is S.Zero)
    assert P(And(Eq(Y[2], 1), Eq(Y[1], 1), Eq(Y[0], 0)),
             Eq(Y[1], 1)) == 0.1 * Probability(Eq(Y[0], 0))

    # testing properties of Markov chain
    TO2 = Matrix([
        [S.One, 0, 0],
        [Rational(1, 3), Rational(1, 3),
         Rational(1, 3)],
        [0, Rational(1, 4), Rational(3, 4)],
    ])
    TO3 = Matrix([
        [Rational(1, 4), Rational(3, 4), 0],
        [Rational(1, 3), Rational(1, 3),
         Rational(1, 3)],
        [0, Rational(1, 4), Rational(3, 4)],
    ])
    Y2 = DiscreteMarkovChain("Y", trans_probs=TO2)
    Y3 = DiscreteMarkovChain("Y", trans_probs=TO3)
    assert Y3._transient2absorbing() == None
    raises(ValueError, lambda: Y3.fundamental_matrix())
    assert Y2.is_absorbing_chain() == True
    assert Y3.is_absorbing_chain() == False
    TO4 = Matrix([
        [Rational(1, 5), Rational(2, 5),
         Rational(2, 5)],
        [Rational(1, 10), S.Half, Rational(2, 5)],
        [Rational(3, 5), Rational(3, 10),
         Rational(1, 10)],
    ])
    Y4 = DiscreteMarkovChain("Y", trans_probs=TO4)
    w = ImmutableMatrix([[Rational(11, 39),
                          Rational(16, 39),
                          Rational(4, 13)]])
    assert Y4.limiting_distribution == w
    assert Y4.is_regular() == True
    TS1 = MatrixSymbol("T", 3, 3)
    Y5 = DiscreteMarkovChain("Y", trans_probs=TS1)
    assert Y5.limiting_distribution(w, TO4).doit() == True
    TO6 = Matrix([
        [S.One, 0, 0, 0, 0],
        [S.Half, 0, S.Half, 0, 0],
        [0, S.Half, 0, S.Half, 0],
        [0, 0, S.Half, 0, S.Half],
        [0, 0, 0, 0, 1],
    ])
    Y6 = DiscreteMarkovChain("Y", trans_probs=TO6)
    assert Y6._transient2absorbing() == ImmutableMatrix([[S.Half, 0], [0, 0],
                                                         [0, S.Half]])
    assert Y6._transient2transient() == ImmutableMatrix([[0, S.Half, 0],
                                                         [S.Half, 0, S.Half],
                                                         [0, S.Half, 0]])
    assert Y6.fundamental_matrix() == ImmutableMatrix([
        [Rational(3, 2), S.One, S.Half],
        [S.One, S(2), S.One],
        [S.Half, S.One, Rational(3, 2)],
    ])
    assert Y6.absorbing_probabilites() == ImmutableMatrix([
        [Rational(3, 4), Rational(1, 4)],
        [S.Half, S.Half],
        [Rational(1, 4), Rational(3, 4)],
    ])

    # testing miscellaneous queries
    T = Matrix([
        [S.Half, Rational(1, 4), Rational(1, 4)],
        [Rational(1, 3), 0, Rational(2, 3)],
        [S.Half, S.Half, 0],
    ])
    X = DiscreteMarkovChain("X", [0, 1, 2], T)
    assert P(
        Eq(X[1], 2) & Eq(X[2], 1) & Eq(X[3], 0),
        Eq(P(Eq(X[1], 0)), Rational(1, 4))
        & Eq(P(Eq(X[1], 1)), Rational(1, 4)),
    ) == Rational(1, 12)
    assert P(Eq(X[2], 1) | Eq(X[2], 2), Eq(X[1], 1)) == Rational(2, 3)
    assert P(Eq(X[2], 1) & Eq(X[2], 2), Eq(X[1], 1)) is S.Zero
    assert P(Ne(X[2], 2), Eq(X[1], 1)) == Rational(1, 3)
    assert E(X[1]**2, Eq(X[0], 1)) == Rational(8, 3)
    assert variance(X[1], Eq(X[0], 1)) == Rational(8, 9)
    raises(ValueError, lambda: E(X[1], Eq(X[2], 1)))
Ejemplo n.º 24
0
def test_issue_12251():
    assert manualintegrate(x**y, x) == Piecewise(
        (x**(y + 1) / (y + 1), Ne(y, -1)), (log(x), True))
Ejemplo n.º 25
0
def test_frac():
    assert isinstance(frac(x), frac)
    assert frac(oo) == AccumBounds(0, 1)
    assert frac(-oo) == AccumBounds(0, 1)
    assert frac(zoo) is nan

    assert frac(n) == 0
    assert frac(nan) is nan
    assert frac(Rational(4, 3)) == Rational(1, 3)
    assert frac(-Rational(4, 3)) == Rational(2, 3)
    assert frac(Rational(-4, 3)) == Rational(2, 3)

    r = Symbol('r', real=True)
    assert frac(I * r) == I * frac(r)
    assert frac(1 + I * r) == I * frac(r)
    assert frac(0.5 + I * r) == 0.5 + I * frac(r)
    assert frac(n + I * r) == I * frac(r)
    assert frac(n + I * k) == 0
    assert unchanged(frac, x + I * x)
    assert frac(x + I * n) == frac(x)

    assert frac(x).rewrite(floor) == x - floor(x)
    assert frac(x).rewrite(ceiling) == x + ceiling(-x)
    assert frac(y).rewrite(floor).subs(y, pi) == frac(pi)
    assert frac(y).rewrite(floor).subs(y, -E) == frac(-E)
    assert frac(y).rewrite(ceiling).subs(y, -pi) == frac(-pi)
    assert frac(y).rewrite(ceiling).subs(y, E) == frac(E)

    assert Eq(frac(y), y - floor(y))
    assert Eq(frac(y), y + ceiling(-y))

    r = Symbol('r', real=True)
    p_i = Symbol('p_i', integer=True, positive=True)
    n_i = Symbol('p_i', integer=True, negative=True)
    np_i = Symbol('np_i', integer=True, nonpositive=True)
    nn_i = Symbol('nn_i', integer=True, nonnegative=True)
    p_r = Symbol('p_r', real=True, positive=True)
    n_r = Symbol('n_r', real=True, negative=True)
    np_r = Symbol('np_r', real=True, nonpositive=True)
    nn_r = Symbol('nn_r', real=True, nonnegative=True)

    # Real frac argument, integer rhs
    assert frac(r) <= p_i
    assert not frac(r) <= n_i
    assert (frac(r) <= np_i).has(Le)
    assert (frac(r) <= nn_i).has(Le)
    assert frac(r) < p_i
    assert not frac(r) < n_i
    assert not frac(r) < np_i
    assert (frac(r) < nn_i).has(Lt)
    assert not frac(r) >= p_i
    assert frac(r) >= n_i
    assert frac(r) >= np_i
    assert (frac(r) >= nn_i).has(Ge)
    assert not frac(r) > p_i
    assert frac(r) > n_i
    assert (frac(r) > np_i).has(Gt)
    assert (frac(r) > nn_i).has(Gt)

    assert not Eq(frac(r), p_i)
    assert not Eq(frac(r), n_i)
    assert Eq(frac(r), np_i).has(Eq)
    assert Eq(frac(r), nn_i).has(Eq)

    assert Ne(frac(r), p_i)
    assert Ne(frac(r), n_i)
    assert Ne(frac(r), np_i).has(Ne)
    assert Ne(frac(r), nn_i).has(Ne)

    # Real frac argument, real rhs
    assert (frac(r) <= p_r).has(Le)
    assert not frac(r) <= n_r
    assert (frac(r) <= np_r).has(Le)
    assert (frac(r) <= nn_r).has(Le)
    assert (frac(r) < p_r).has(Lt)
    assert not frac(r) < n_r
    assert not frac(r) < np_r
    assert (frac(r) < nn_r).has(Lt)
    assert (frac(r) >= p_r).has(Ge)
    assert frac(r) >= n_r
    assert frac(r) >= np_r
    assert (frac(r) >= nn_r).has(Ge)
    assert (frac(r) > p_r).has(Gt)
    assert frac(r) > n_r
    assert (frac(r) > np_r).has(Gt)
    assert (frac(r) > nn_r).has(Gt)

    assert not Eq(frac(r), n_r)
    assert Eq(frac(r), p_r).has(Eq)
    assert Eq(frac(r), np_r).has(Eq)
    assert Eq(frac(r), nn_r).has(Eq)

    assert Ne(frac(r), p_r).has(Ne)
    assert Ne(frac(r), n_r)
    assert Ne(frac(r), np_r).has(Ne)
    assert Ne(frac(r), nn_r).has(Ne)

    # Real frac argument, +/- oo rhs
    assert frac(r) < oo
    assert frac(r) <= oo
    assert not frac(r) > oo
    assert not frac(r) >= oo

    assert not frac(r) < -oo
    assert not frac(r) <= -oo
    assert frac(r) > -oo
    assert frac(r) >= -oo

    assert frac(r) < 1
    assert frac(r) <= 1
    assert not frac(r) > 1
    assert not frac(r) >= 1

    assert not frac(r) < 0
    assert (frac(r) <= 0).has(Le)
    assert (frac(r) > 0).has(Gt)
    assert frac(r) >= 0

    # Some test for numbers
    assert frac(r) <= sqrt(2)
    assert (frac(r) <= sqrt(3) - sqrt(2)).has(Le)
    assert not frac(r) <= sqrt(2) - sqrt(3)
    assert not frac(r) >= sqrt(2)
    assert (frac(r) >= sqrt(3) - sqrt(2)).has(Ge)
    assert frac(r) >= sqrt(2) - sqrt(3)

    assert not Eq(frac(r), sqrt(2))
    assert Eq(frac(r), sqrt(3) - sqrt(2)).has(Eq)
    assert not Eq(frac(r), sqrt(2) - sqrt(3))
    assert Ne(frac(r), sqrt(2))
    assert Ne(frac(r), sqrt(3) - sqrt(2)).has(Ne)
    assert Ne(frac(r), sqrt(2) - sqrt(3))

    assert frac(p_i, evaluate=False).is_zero
    assert frac(p_i, evaluate=False).is_finite
    assert frac(p_i, evaluate=False).is_integer
    assert frac(p_i, evaluate=False).is_real
    assert frac(r).is_finite
    assert frac(r).is_real
    assert frac(r).is_zero is None
    assert frac(r).is_integer is None

    assert frac(oo).is_finite
    assert frac(oo).is_real
Ejemplo n.º 26
0
def test_issue_11045():
    assert integrate(1 / (x * sqrt(x**2 - 1)), (x, 1, 2)) == pi / 3

    # handle And with Or arguments
    assert Piecewise((1, And(Or(x < 1, x > 3), x < 2)), (0, True)).integrate(
        (x, 0, 3)) == 1

    # hidden false
    assert Piecewise((1, x > 1), (2, x > x + 1), (3, True)).integrate(
        (x, 0, 3)) == 5
    # targetcond is Eq
    assert Piecewise((1, x > 1), (2, Eq(1, x)), (3, True)).integrate(
        (x, 0, 4)) == 6
    # And has Relational needing to be solved
    assert Piecewise((1, And(2 * x > x + 1, x < 2)), (0, True)).integrate(
        (x, 0, 3)) == 1
    # Or has Relational needing to be solved
    assert Piecewise((1, Or(2 * x > x + 2, x < 1)), (0, True)).integrate(
        (x, 0, 3)) == 2
    # ignore hidden false (handled in canonicalization)
    assert Piecewise((1, x > 1), (2, x > x + 1), (3, True)).integrate(
        (x, 0, 3)) == 5
    # watch for hidden True Piecewise
    assert Piecewise((2, Eq(1 - x, x * (1 / x - 1))), (0, True)).integrate(
        (x, 0, 3)) == 6

    # overlapping conditions of targetcond are recognized and ignored;
    # the condition x > 3 will be pre-empted by the first condition
    assert Piecewise((1, Or(x < 1, x > 2)), (2, x > 3), (3, True)).integrate(
        (x, 0, 4)) == 6

    # convert Ne to Or
    assert Piecewise((1, Ne(x, 0)), (2, True)).integrate((x, -1, 1)) == 2

    # no default but well defined
    assert Piecewise((x, (x > 1) & (x < 3)), (1, (x < 4))).integrate(
        (x, 1, 4)) == 5

    p = Piecewise((x, (x > 1) & (x < 3)), (1, (x < 4)))
    nan = Undefined
    i = p.integrate((x, 1, y))
    assert i == Piecewise(
        (y - 1, y < 1),
        (Min(3, y)**2 / 2 - Min(3, y) + Min(4, y) - 1 / 2, y <= Min(4, y)),
        (nan, True))
    assert p.integrate((x, 1, -1)) == i.subs(y, -1)
    assert p.integrate((x, 1, 4)) == 5
    assert p.integrate((x, 1, 5)) == nan

    # handle Not
    p = Piecewise((1, x > 1), (2, Not(And(x > 1, x < 3))), (3, True))
    assert p.integrate((x, 0, 3)) == 4

    # handle updating of int_expr when there is overlap
    p = Piecewise((1, And(5 > x, x > 1)), (2, Or(x < 3, x > 7)), (4, x < 8))
    assert p.integrate((x, 0, 10)) == 20

    # And with Eq arg handling
    assert Piecewise((1, x < 1), (2, And(Eq(x, 3), x > 1))).integrate(
        (x, 0, 3)) == S.NaN
    assert Piecewise((1, x < 1), (2, And(Eq(x, 3), x > 1)),
                     (3, True)).integrate((x, 0, 3)) == 7
    assert Piecewise((1, x < 0), (2, And(Eq(x, 3), x < 1)),
                     (3, True)).integrate((x, -1, 1)) == 4
    # middle condition doesn't matter: it's a zero width interval
    assert Piecewise((1, x < 1), (2, Eq(x, 3) & (y < x)), (3, True)).integrate(
        (x, 0, 3)) == 7
Ejemplo n.º 27
0
def test_issue_11045():
    assert integrate(1 / (x * sqrt(x**2 - 1)), (x, 1, 2)) == pi / 3

    # handle And with Or arguments
    assert Piecewise((1, And(Or(x < 1, x > 3), x < 2)), (0, True)).integrate(
        (x, 0, 3)) == 1

    # hidden false
    assert Piecewise((1, x > 1), (2, x > x + 1), (3, True)).integrate(
        (x, 0, 3)) == 5
    # targetcond is Eq
    assert Piecewise((1, x > 1), (2, Eq(1, x)), (3, True)).integrate(
        (x, 0, 4)) == 6
    # And has Relational needing to be solved
    assert Piecewise((1, And(2 * x > x + 1, x < 2)), (0, True)).integrate(
        (x, 0, 3)) == 1
    # Or has Relational needing to be solved
    assert Piecewise((1, Or(2 * x > x + 2, x < 1)), (0, True)).integrate(
        (x, 0, 3)) == 2
    # ignore hidden false (handled in canonicalization)
    assert Piecewise((1, x > 1), (2, x > x + 1), (3, True)).integrate(
        (x, 0, 3)) == 5
    # watch for hidden True Piecewise
    assert Piecewise((2, Eq(1 - x, x * (1 / x - 1))), (0, True)).integrate(
        (x, 0, 3)) == 6

    # overlapping conditions of targetcond are recognized and ignored;
    # the condition x > 3 will be pre-empted by the first condition
    assert Piecewise((1, Or(x < 1, x > 2)), (2, x > 3), (3, True)).integrate(
        (x, 0, 4)) == 6

    # convert Ne to Or
    assert Piecewise((1, Ne(x, 0)), (2, True)).integrate((x, -1, 1)) == 2

    # no default but well defined
    assert Piecewise((x, (x > 1) & (x < 3)), (1, (x < 4))).integrate(
        (x, 1, 4)) == 5

    p = Piecewise((x, (x > 1) & (x < 3)), (1, (x < 4)))
    # with y unknown, this fails because there might be a hole
    # in intervals [Min(1, Max(4, y)), 1] and [Min(4, y), y]. The
    # first one should simplify (i.e. since 1 is less than the
    # minumum value of Max(4, y) that interval should be [1, 1]
    raises(ValueError, lambda: p.integrate((x, 1, y)))
    assert p.integrate((x, 1, 4)) == 5

    # handle Not
    p = Piecewise((1, x > 1), (2, Not(And(x > 1, x < 3))), (3, True))
    assert p.integrate((x, 0, 3)) == 4

    # handle updating of int_expr when there is overlap
    p = Piecewise((1, And(5 > x, x > 1)), (2, Or(x < 3, x > 7)), (4, x < 8))
    assert p.integrate((x, 0, 10)) == 20

    # And with Eq arg handling
    assert Piecewise((1, x < 1), (2, And(Eq(x, 3), x > 1))).integrate(
        (x, 0, 3)) == S.NaN
    assert Piecewise((1, x < 1), (2, And(Eq(x, 3), x > 1)),
                     (3, True)).integrate((x, 0, 3)) == 7
    assert Piecewise((1, x < 0), (2, And(Eq(x, 3), x < 1)),
                     (3, True)).integrate((x, -1, 1)) == 4
    # middle condition doesn't matter: it's a zero width interval
    assert Piecewise((1, x < 1), (2, Eq(x, 3) & (y < x)), (3, True)).integrate(
        (x, 0, 3)) == 7
Ejemplo n.º 28
0
class TestAllGood(object):
    # These latex strings should parse to the corresponding SymPy expression
    GOOD_PAIRS = [
        ("0", Rational(0)),
        ("1", Rational(1)),
        ("-3.14", Rational(-314, 100)),
        ("5-3", _Add(5, _Mul(-1, 3))),
        ("(-7.13)(1.5)", _Mul(Rational('-7.13'), Rational('1.5'))),
        ("\\left(-7.13\\right)\\left(1.5\\right)", _Mul(Rational('-7.13'), Rational('1.5'))),
        ("x", x),
        ("2x", 2 * x),
        ("x^2", x**2),
        ("x^{3 + 1}", x**_Add(3, 1)),
        ("x^{\\left\\{3 + 1\\right\\}}", x**_Add(3, 1)),
        ("-3y + 2x", _Add(_Mul(2, x), Mul(-1, 3, y, evaluate=False))),
        ("-c", -c),
        ("a \\cdot b", a * b),
        ("a / b", a / b),
        ("a \\div b", a / b),
        ("a + b", a + b),
        ("a + b - a", Add(a, b, _Mul(-1, a), evaluate=False)),
        ("a^2 + b^2 = c^2", Eq(a**2 + b**2, c**2)),
        ("a^2 + b^2 != 2c^2", Ne(a**2 + b**2, 2 * c**2)),
        ("a\\mod b", Mod(a, b)),
        ("\\sin \\theta", sin(theta)),
        ("\\sin(\\theta)", sin(theta)),
        ("\\sin\\left(\\theta\\right)", sin(theta)),
        ("\\sin^{-1} a", asin(a)),
        ("\\sin a \\cos b", _Mul(sin(a), cos(b))),
        ("\\sin \\cos \\theta", sin(cos(theta))),
        ("\\sin(\\cos \\theta)", sin(cos(theta))),
        ("\\arcsin(a)", asin(a)),
        ("\\arccos(a)", acos(a)),
        ("\\arctan(a)", atan(a)),
        ("\\sinh(a)", sinh(a)),
        ("\\cosh(a)", cosh(a)),
        ("\\tanh(a)", tanh(a)),
        ("\\sinh^{-1}(a)", asinh(a)),
        ("\\cosh^{-1}(a)", acosh(a)),
        ("\\tanh^{-1}(a)", atanh(a)),
        ("\\arcsinh(a)", asinh(a)),
        ("\\arccosh(a)", acosh(a)),
        ("\\arctanh(a)", atanh(a)),
        ("\\arsinh(a)", asinh(a)),
        ("\\arcosh(a)", acosh(a)),
        ("\\artanh(a)", atanh(a)),
        ("\\operatorname{arcsinh}(a)", asinh(a)),
        ("\\operatorname{arccosh}(a)", acosh(a)),
        ("\\operatorname{arctanh}(a)", atanh(a)),
        ("\\operatorname{arsinh}(a)", asinh(a)),
        ("\\operatorname{arcosh}(a)", acosh(a)),
        ("\\operatorname{artanh}(a)", atanh(a)),
        ("\\operatorname{gcd}(a, b)", UnevaluatedExpr(gcd(a, b))),
        ("\\operatorname{lcm}(a, b)", UnevaluatedExpr(lcm(a, b))),
        ("\\operatorname{gcd}(a,b)", UnevaluatedExpr(gcd(a, b))),
        ("\\operatorname{lcm}(a,b)", UnevaluatedExpr(lcm(a, b))),
        ("\\operatorname{floor}(a)", floor(a)),
        ("\\operatorname{ceil}(b)", ceiling(b)),
        ("\\cos^2(x)", cos(x)**2),
        ("\\cos(x)^2", cos(x)**2),
        ("\\gcd(a, b)", UnevaluatedExpr(gcd(a, b))),
        ("\\lcm(a, b)", UnevaluatedExpr(lcm(a, b))),
        ("\\gcd(a,b)", UnevaluatedExpr(gcd(a, b))),
        ("\\lcm(a,b)", UnevaluatedExpr(lcm(a, b))),
        ("\\floor(a)", floor(a)),
        ("\\ceil(b)", ceiling(b)),
        ("\\max(a, b)", Max(a, b)),
        ("\\min(a, b)", Min(a, b)),
        ("\\frac{a}{b}", a / b),
        ("\\frac{a + b}{c}", _Mul(a + b, _Pow(c, -1))),
        ("\\frac{7}{3}", Rational(7, 3)),
        ("(\\csc x)(\\sec y)", csc(x) * sec(y)),
        ("\\lim_{x \\to 3} a", Limit(a, x, 3)),
        ("\\lim_{x \\rightarrow 3} a", Limit(a, x, 3)),
        ("\\lim_{x \\Rightarrow 3} a", Limit(a, x, 3)),
        ("\\lim_{x \\longrightarrow 3} a", Limit(a, x, 3)),
        ("\\lim_{x \\Longrightarrow 3} a", Limit(a, x, 3)),
        ("\\lim_{x \\to 3^{+}} a", Limit(a, x, 3, dir='+')),
        ("\\lim_{x \\to 3^{-}} a", Limit(a, x, 3, dir='-')),
        ("\\infty", oo),
        ("\\infty\\%", oo),
        ("\\$\\infty", oo),
        ("-\\infty", -oo),
        ("-\\infty\\%", -oo),
        ("-\\$\\infty", -oo),
        ("\\lim_{x \\to \\infty} \\frac{1}{x}", Limit(_Mul(1, _Pow(x, -1)), x, oo)),
        ("\\frac{d}{dx} x", Derivative(x, x)),
        ("\\frac{d}{dt} x", Derivative(x, t)),
        # ("f(x)", f(x)),
        # ("f(x, y)", f(x, y)),
        # ("f(x, y, z)", f(x, y, z)),
        # ("\\frac{d f(x)}{dx}", Derivative(f(x), x)),
        # ("\\frac{d\\theta(x)}{dx}", Derivative(theta(x), x)),
        ("|x|", _Abs(x)),
        ("\\left|x\\right|", _Abs(x)),
        ("||x||", _Abs(_Abs(x))),
        ("|x||y|", _Abs(x) * _Abs(y)),
        ("||x||y||", _Abs(_Abs(x) * _Abs(y))),
        ("\\lfloor x\\rfloor", floor(x)),
        ("\\lceil y\\rceil", ceiling(y)),
        ("\\pi^{|xy|}", pi**_Abs(x * y)),
        ("\\frac{\\pi}{3}", _Mul(pi, _Pow(3, -1))),
        ("\\sin{\\frac{\\pi}{2}}", sin(_Mul(pi, _Pow(2, -1)), evaluate=False)),
        ("a+bI", a + I * b),
        ("e^{I\\pi}", Integer(-1)),
        ("\\int x dx", Integral(x, x)),
        ("\\int x d\\theta", Integral(x, theta)),
        ("\\int (x^2 - y)dx", Integral(x**2 - y, x)),
        ("\\int x + a dx", Integral(_Add(x, a), x)),
        ("\\int da", Integral(1, a)),
        ("\\int_0^7 dx", Integral(1, (x, 0, 7))),
        ("\\int_a^b x dx", Integral(x, (x, a, b))),
        ("\\int^b_a x dx", Integral(x, (x, a, b))),
        ("\\int_{a}^b x dx", Integral(x, (x, a, b))),
        ("\\int^{b}_a x dx", Integral(x, (x, a, b))),
        ("\\int_{a}^{b} x dx", Integral(x, (x, a, b))),
        ("\\int_{  }^{}x dx", Integral(x, x)),
        ("\\int^{  }_{ }x dx", Integral(x, x)),
        ("\\int^{b}_{a} x dx", Integral(x, (x, a, b))),
        # ("\\int_{f(a)}^{f(b)} f(z) dz", Integral(f(z), (z, f(a), f(b)))),
        ("\\int (x+a)", Integral(_Add(x, a), x)),
        ("\\int a + b + c dx", Integral(Add(a, b, c, evaluate=False), x)),
        ("\\int \\frac{dz}{z}", Integral(Pow(z, -1), z)),
        ("\\int \\frac{3 dz}{z}", Integral(3 * Pow(z, -1), z)),
        ("\\int \\frac{1}{x} dx", Integral(Pow(x, -1), x)),
        ("\\int \\frac{1}{a} + \\frac{1}{b} dx", Integral(_Add(_Pow(a, -1), Pow(b, -1)), x)),
        ("\\int \\frac{3 \\cdot d\\theta}{\\theta}", Integral(3 * _Pow(theta, -1), theta)),
        ("\\int \\frac{1}{x} + 1 dx", Integral(_Add(_Pow(x, -1), 1), x)),
        ("x_0", Symbol('x_0', real=True, positive=True)),
        ("x_{1}", Symbol('x_1', real=True, positive=True)),
        ("x_a", Symbol('x_a', real=True, positive=True)),
        ("x_{b}", Symbol('x_b', real=True, positive=True)),
        ("h_\\theta", Symbol('h_{\\theta}', real=True, positive=True)),
        ("h_\\theta ", Symbol('h_{\\theta}', real=True, positive=True)),
        ("h_{\\theta}", Symbol('h_{\\theta}', real=True, positive=True)),
        # ("h_{\\theta}(x_0, x_1)", Symbol('h_{theta}', real=True)(Symbol('x_{0}', real=True), Symbol('x_{1}', real=True))),
        ("x!", _factorial(x)),
        ("100!", _factorial(100)),
        ("\\theta!", _factorial(theta)),
        ("(x + 1)!", _factorial(_Add(x, 1))),
        ("\\left(x + 1\\right)!", _factorial(_Add(x, 1))),
        ("(x!)!", _factorial(_factorial(x))),
        ("x!!!", _factorial(_factorial(_factorial(x)))),
        ("5!7!", _Mul(_factorial(5), _factorial(7))),
        ("\\sqrt{x}", sqrt(x)),
        ("\\sqrt{x + b}", sqrt(_Add(x, b))),
        ("\\sqrt[3]{\\sin x}", root(sin(x), 3)),
        ("\\sqrt[y]{\\sin x}", root(sin(x), y)),
        ("\\sqrt[\\theta]{\\sin x}", root(sin(x), theta)),
        ("x < y", StrictLessThan(x, y)),
        ("x \\leq y", LessThan(x, y)),
        ("x > y", StrictGreaterThan(x, y)),
        ("x \\geq y", GreaterThan(x, y)),
        ("\\sum_{k = 1}^{3} c", Sum(c, (k, 1, 3))),
        ("\\sum_{k = 1}^3 c", Sum(c, (k, 1, 3))),
        ("\\sum^{3}_{k = 1} c", Sum(c, (k, 1, 3))),
        ("\\sum^3_{k = 1} c", Sum(c, (k, 1, 3))),
        ("\\sum_{k = 1}^{10} k^2", Sum(k**2, (k, 1, 10))),
        ("\\sum_{n = 0}^{\\infty} \\frac{1}{n!}", Sum(_Pow(_factorial(n), -1), (n, 0, oo))),
        ("\\prod_{a = b}^{c} x", Product(x, (a, b, c))),
        ("\\prod_{a = b}^c x", Product(x, (a, b, c))),
        ("\\prod^{c}_{a = b} x", Product(x, (a, b, c))),
        ("\\prod^c_{a = b} x", Product(x, (a, b, c))),
        ("\\ln x", _log(x, E)),
        ("\\ln xy", _log(x * y, E)),
        ("\\log x", _log(x, 10)),
        ("\\log xy", _log(x * y, 10)),
        # ("\\log_2 x", _log(x, 2)),
        ("\\log_{2} x", _log(x, 2)),
        # ("\\log_a x", _log(x, a)),
        ("\\log_{a} x", _log(x, a)),
        ("\\log_{11} x", _log(x, 11)),
        ("\\log_{a^2} x", _log(x, _Pow(a, 2))),
        ("[x]", x),
        ("[a + b]", _Add(a, b)),
        ("\\frac{d}{dx} [ \\tan x ]", Derivative(tan(x), x)),
        ("2\\overline{x}", 2 * Symbol('xbar', real=True, positive=True)),
        ("2\\overline{x}_n", 2 * Symbol('xbar_n', real=True, positive=True)),
        ("\\frac{x}{\\overline{x}_n}", x / Symbol('xbar_n', real=True, positive=True)),
        ("\\frac{\\sin(x)}{\\overline{x}_n}", sin(x) / Symbol('xbar_n', real=True, positive=True)),
        ("2\\bar{x}", 2 * Symbol('xbar', real=True, positive=True)),
        ("2\\bar{x}_n", 2 * Symbol('xbar_n', real=True, positive=True)),
        ("\\sin\\left(\\theta\\right) \\cdot4", sin(theta) * 4),
        ("\\ln\\left(\\theta\\right)", _log(theta, E)),
        ("\\ln\\left(x-\\theta\\right)", _log(x - theta, E)),
        ("\\ln\\left(\\left(x-\\theta\\right)\\right)", _log(x - theta, E)),
        ("\\ln\\left(\\left[x-\\theta\\right]\\right)", _log(x - theta, E)),
        ("\\ln\\left(\\left\\{x-\\theta\\right\\}\\right)", _log(x - theta, E)),
        ("\\ln\\left(\\left|x-\\theta\\right|\\right)", _log(_Abs(x - theta), E)),
        ("\\frac{1}{2}xy(x+y)", Mul(Rational(1, 2), x, y, (x + y), evaluate=False)),
        ("\\frac{1}{2}\\theta(x+y)", Mul(Rational(1, 2), theta, (x + y), evaluate=False)),
        ("1-f(x)", 1 - f * x),

        ("\\begin{matrix}1&2\\\\3&4\\end{matrix}", Matrix([[1, 2], [3, 4]])),
        ("\\begin{matrix}x&x^2\\\\\\sqrt{x}&x\\end{matrix}", Matrix([[x, x**2], [_Pow(x, S.Half), x]])),
        ("\\begin{matrix}\\sqrt{x}\\\\\\sin(\\theta)\\end{matrix}", Matrix([_Pow(x, S.Half), sin(theta)])),
        ("\\begin{pmatrix}1&2\\\\3&4\\end{pmatrix}", Matrix([[1, 2], [3, 4]])),
        ("\\begin{bmatrix}1&2\\\\3&4\\end{bmatrix}", Matrix([[1, 2], [3, 4]])),

        # scientific notation
        ("2.5\\times 10^2", Rational(250)),
        ("1,500\\times 10^{-1}", Rational(150)),

        # e notation
        ("2.5E2", Rational(250)),
        ("1,500E-1", Rational(150)),

        # multiplication without cmd
        ("2x2y", Mul(2, x, 2, y, evaluate=False)),
        ("2x2", Mul(2, x, 2, evaluate=False)),
        ("x2", x * 2),

        # lin alg processing
        ("\\theta\\begin{matrix}1&2\\\\3&4\\end{matrix}", MatMul(theta, Matrix([[1, 2], [3, 4]]), evaluate=False)),
        ("\\theta\\begin{matrix}1\\\\3\\end{matrix} - \\begin{matrix}-1\\\\2\\end{matrix}", MatAdd(MatMul(theta, Matrix([[1], [3]]), evaluate=False), MatMul(-1, Matrix([[-1], [2]]), evaluate=False), evaluate=False)),
        ("\\theta\\begin{matrix}1&0\\\\0&1\\end{matrix}*\\begin{matrix}3\\\\-2\\end{matrix}", MatMul(theta, Matrix([[1, 0], [0, 1]]), Matrix([3, -2]), evaluate=False)),
        ("\\frac{1}{9}\\theta\\begin{matrix}1&2\\\\3&4\\end{matrix}", MatMul(Rational(1, 9), theta, Matrix([[1, 2], [3, 4]]), evaluate=False)),
        ("\\begin{pmatrix}1\\\\2\\\\3\\end{pmatrix},\\begin{pmatrix}4\\\\3\\\\1\\end{pmatrix}", [Matrix([1, 2, 3]), Matrix([4, 3, 1])]),
        ("\\begin{pmatrix}1\\\\2\\\\3\\end{pmatrix};\\begin{pmatrix}4\\\\3\\\\1\\end{pmatrix}", [Matrix([1, 2, 3]), Matrix([4, 3, 1])]),
        ("\\left\\{\\begin{pmatrix}1\\\\2\\\\3\\end{pmatrix},\\begin{pmatrix}4\\\\3\\\\1\\end{pmatrix}\\right\\}", [Matrix([1, 2, 3]), Matrix([4, 3, 1])]),
        ("\\left\\{\\begin{pmatrix}1\\\\2\\\\3\\end{pmatrix},\\begin{pmatrix}4\\\\3\\\\1\\end{pmatrix},\\begin{pmatrix}1\\\\1\\\\1\\end{pmatrix}\\right\\}", [Matrix([1, 2, 3]), Matrix([4, 3, 1]), Matrix([1, 1, 1])]),
        ("\\left\\{\\begin{pmatrix}1\\\\2\\\\3\\end{pmatrix}\\right\\}", Matrix([1, 2, 3])),
        ("\\left{\\begin{pmatrix}1\\\\2\\\\3\\end{pmatrix}\\right}", Matrix([1, 2, 3])),
        ("{\\begin{pmatrix}1\\\\2\\\\3\\end{pmatrix}}", Matrix([1, 2, 3])),

        # us dollars
        ("\\$1,000.00", Rational(1000)),
        ("\\$543.21", Rational(54321, 100)),
        ("\\$0.009", Rational(9, 1000)),

        # percentages
        ("100\\%", Rational(1)),
        ("1.5\\%", Rational(15, 1000)),
        ("0.05\\%", Rational(5, 10000)),

        # empty set
        ("\\emptyset", S.EmptySet),

        # divide by zero
        ("\\frac{1}{0}", _Pow(0, -1)),
        ("1+\\frac{5}{0}", _Add(1, _Mul(5, _Pow(0, -1)))),

        # adjacent single char sub sup
        ("4^26^2", _Mul(_Pow(4, 2), _Pow(6, 2))),
        ("x_22^2", _Mul(Symbol('x_2', real=True, positive=True), _Pow(2, 2)))
    ]

    def test_good_pair(self, s, eq):
        assert_equal(s, eq)
Ejemplo n.º 29
0
def test_Relational():
    assert str(Rel(x, y, "<")) == "x < y"
    assert str(Rel(x + y, y, "==")) == "Eq(x + y, y)"
    assert str(Rel(x, y, "!=")) == "Ne(x, y)"
    assert str(Eq(x, 1) | Eq(x, 2)) == "Eq(x, 1) | Eq(x, 2)"
    assert str(Ne(x, 1) & Ne(x, 2)) == "Ne(x, 1) & Ne(x, 2)"
Ejemplo n.º 30
0
def test_pretty_relational():
    expr = Eq(x, y)
    ascii_str = \
"""\
x = y\
"""
    ucode_str = \
u"""\
x = y\
"""
    assert pretty(expr) == ascii_str
    assert upretty(expr) == ucode_str

    expr = Lt(x, y)
    ascii_str = \
"""\
x < y\
"""
    ucode_str = \
u"""\
x < y\
"""
    assert pretty(expr) == ascii_str
    assert upretty(expr) == ucode_str

    expr = Gt(x, y)
    ascii_str = \
"""\
y < x\
"""
    ucode_str = \
u"""\
y < x\
"""
    assert pretty(expr) == ascii_str
    assert upretty(expr) == ucode_str

    expr = Le(x, y)
    ascii_str = \
"""\
x <= y\
"""
    ucode_str = \
u"""\
x ≤ y\
"""
    assert pretty(expr) == ascii_str
    assert upretty(expr) == ucode_str

    expr = Ge(x, y)
    ascii_str = \
"""\
y <= x\
"""
    ucode_str = \
u"""\
y ≤ x\
"""
    assert pretty(expr) == ascii_str
    assert upretty(expr) == ucode_str

    expr = Ne(x / (y + 1), y**2)
    ascii_str_1 = \
"""\
  x       2\n\
----- != y \n\
1 + y      \
"""
    ascii_str_2 = \
"""\
  x       2\n\
----- != y \n\
y + 1      \
"""
    ucode_str_1 = \
u"""\
  x      2\n\
───── ≠ y \n\
1 + y     \
"""
    ucode_str_2 = \
u"""\
  x      2\n\
───── ≠ y \n\
y + 1     \
"""
    assert pretty(expr) in [ascii_str_1, ascii_str_2]
    assert upretty(expr) in [ucode_str_1, ucode_str_2]