Exemplo n.º 1
0
def test_euler_interface():
    x = Function('x')
    y = Symbol('y')
    t = Symbol('t')
    pytest.raises(TypeError, lambda: euler())
    pytest.raises(TypeError, lambda: euler(diff(x(t), t)*y(t), [x(t), y]))
    pytest.raises(ValueError, lambda: euler(diff(x(t), t)*x(y), [x(t), x(y)]))
    pytest.raises(TypeError, lambda: euler(diff(x(t), t)**2, x(0)))
    pytest.raises(TypeError, lambda: euler(1, y))
    assert euler(diff(x(t), t)**2/2, {x(t)}) == [Eq(-diff(x(t), t, t), 0)]
    assert euler(diff(x(t), t)**2/2, x(t), {t}) == [Eq(-diff(x(t), t, t), 0)]
Exemplo n.º 2
0
def test_pde_separate_add():
    x, y, z, t = symbols("x,y,z,t")
    F, T, X, Y, Z, u = map(Function, 'FTXYZu')

    eq = Eq(diff(u(x, t), x), diff(u(x, t), t) * exp(u(x, t)))
    res = pde_separate_add(eq, u(x, t), [X(x), T(t)])
    assert res == [diff(X(x), x) * exp(-X(x)), diff(T(t), t) * exp(T(t))]

    eq = Eq(u(x, y).diff(x), -exp(u(x, y).diff(y)))
    res = pde_separate_add(eq, u(x, y), [X(x), Y(y)])
    assert res == [diff(X(x), x), -exp(diff(Y(y), y))]
Exemplo n.º 3
0
def test_dice():
    # TODO: Make iid method!
    X, Y, Z = Die('X', 6), Die('Y', 6), Die('Z', 6)
    a, b = symbols('a b')

    assert E(X) == 3 + Rational(1, 2)
    assert variance(X) == Rational(35, 12)
    assert E(X + Y) == 7
    assert E(X + X) == 7
    assert E(a * X + b) == a * E(X) + b
    assert variance(X + Y) == variance(X) + variance(Y) == cmoment(X + Y, 2)
    assert variance(X + X) == 4 * variance(X) == cmoment(X + X, 2)
    assert cmoment(X, 0) == 1
    assert cmoment(4 * X, 3) == 64 * cmoment(X, 3)
    assert covariance(X, Y) == 0
    assert covariance(X, X + Y) == variance(X)
    assert density(Eq(cos(X * pi), 1))[True] == Rational(1, 2)
    assert correlation(X, Y) == 0
    assert correlation(X, Y) == correlation(Y, X)
    assert smoment(X + Y, 3) == skewness(X + Y)
    assert smoment(X, 0) == 1
    assert P(X > 3) == Rational(1, 2)
    assert P(2 * X > 6) == Rational(1, 2)
    assert P(X > Y) == Rational(5, 12)
    assert P(Eq(X, Y)) == P(Eq(X, 1))

    assert E(X, X > 3) == 5 == moment(X, 1, 0, X > 3)
    assert E(X, Y > 3) == E(X) == moment(X, 1, 0, Y > 3)
    assert E(X + Y, Eq(X, Y)) == E(2 * X)
    assert moment(X, 0) == 1
    assert moment(5 * X, 2) == 25 * moment(X, 2)

    assert P(X > 3, X > 3) == 1
    assert P(X > Y, Eq(Y, 6)) == 0
    assert P(Eq(X + Y, 12)) == Rational(1, 36)
    assert P(Eq(X + Y, 12), Eq(X, 6)) == Rational(1, 6)

    assert density(X + Y) == density(Y + Z) != density(X + X)
    d = density(2 * X + Y**Z)
    assert d[22] == Rational(1, 108) and d[4100] == Rational(
        1, 216) and 3130 not in d

    assert pspace(X).domain.as_boolean() == Or(
        *[Eq(X.symbol, i) for i in [1, 2, 3, 4, 5, 6]])

    assert where(X > 3).set == FiniteSet(4, 5, 6)

    X = Die('X', 2)
    x = X.symbol

    assert X.pspace.compute_cdf(X) == {1: Rational(1, 2), 2: 1}
    assert X.pspace.sorted_cdf(X) == [(1, Rational(1, 2)), (2, 1)]

    assert X.pspace.compute_density(X)(1) == Rational(1, 2)
    assert X.pspace.compute_density(X)(0) == 0
    assert X.pspace.compute_density(X)(8) == 0

    assert X.pspace.density == x
Exemplo n.º 4
0
def test_m_loops():
    # Note: an Octave programmer would probably vectorize this across one or
    # more dimensions.  Also, size(A) would be used rather than passing in m
    # and n.  Perhaps users would expect us to vectorize automatically here?
    # Or is it possible to represent such things using IndexedBase?
    n, m = symbols('n m', integer=True)
    A = IndexedBase('A')
    x = IndexedBase('x')
    y = IndexedBase('y')
    i = Idx('i', m)
    j = Idx('j', n)
    result, = codegen(('mat_vec_mult', Eq(y[i], A[i, j] * x[j])),
                      'Octave',
                      header=False,
                      empty=False)
    source = result[1]
    expected = ('function y = mat_vec_mult(A, m, n, x)\n'
                '  for i = 1:m\n'
                '    y(i) = 0;\n'
                '  end\n'
                '  for i = 1:m\n'
                '    for j = 1:n\n'
                '      y(i) = %(rhs)s + y(i);\n'
                '    end\n'
                '  end\n'
                'end\n')
    assert (source == expected % {
        'rhs': 'A(%s, %s).*x(j)' % (i, j)
    } or source == expected % {
        'rhs': 'x(j).*A(%s, %s)' % (i, j)
    })

    result, = codegen(('mat_vec_mult', Eq(y[i], A[i, j] * x[j])),
                      'Octave',
                      header=False,
                      empty=False,
                      argument_sequence=[x, A, m, n])
    source = result[1]
    expected = ('function y = mat_vec_mult(x, A, m, n)\n'
                '  for i = 1:m\n'
                '    y(i) = 0;\n'
                '  end\n'
                '  for i = 1:m\n'
                '    for j = 1:n\n'
                '      y(i) = %(rhs)s + y(i);\n'
                '    end\n'
                '  end\n'
                'end\n')
    assert (source == expected % {
        'rhs': 'A(%s, %s).*x(j)' % (i, j)
    } or source == expected % {
        'rhs': 'x(j).*A(%s, %s)' % (i, j)
    })
Exemplo n.º 5
0
def test_deltasummation_mul_x_kd():
    assert ds(x*Kd(i, j), (j, 1, 3)) == \
        Piecewise((x, And(Integer(1) <= i, i <= 3)), (0, True))
    assert ds(x * Kd(i, j), (j, 1, 1)) == Piecewise((x, Eq(i, 1)), (0, True))
    assert ds(x * Kd(i, j), (j, 2, 2)) == Piecewise((x, Eq(i, 2)), (0, True))
    assert ds(x * Kd(i, j), (j, 3, 3)) == Piecewise((x, Eq(i, 3)), (0, True))
    assert ds(x*Kd(i, j), (j, 1, k)) == \
        Piecewise((x, And(Integer(1) <= i, i <= k)), (0, True))
    assert ds(x*Kd(i, j), (j, k, 3)) == \
        Piecewise((x, And(k <= i, i <= 3)), (0, True))
    assert ds(x*Kd(i, j), (j, k, l)) == \
        Piecewise((x, And(k <= i, i <= l)), (0, True))
Exemplo n.º 6
0
def test_sho_lagrangian():
    m = Symbol('m')
    k = Symbol('k')
    x = f(t)

    L = m * diff(x, t)**2 / 2 - k * x**2 / 2
    eqna = Eq(diff(L, x), diff(L, diff(x, t), t))
    eqnb = Eq(-k * x, m * diff(x, t, t))
    assert eqna == eqnb

    assert diff(L, x, t) == diff(L, t, x)
    assert diff(L, diff(x, t), t) == m * diff(x, t, 2)
    assert diff(L, t, diff(x, t)) == -k * x + m * diff(x, t, 2)
Exemplo n.º 7
0
def test_parallel_dict_from_expr():
    assert parallel_dict_from_expr([Eq(x, 1), Eq(x**2, 2)]) == ([{
        (0, ):
        -Integer(1),
        (1, ):
        Integer(1)
    }, {
        (0, ):
        -Integer(2),
        (2, ):
        Integer(1)
    }], (x, ))
    pytest.raises(PolynomialError,
                  lambda: parallel_dict_from_expr([A * B - B * A]))
Exemplo n.º 8
0
def test_exceptions():
    cg = OctaveCodeGen()

    r = cg.routine('test',
                   Eq(y, x),
                   argument_sequence=[x, y],
                   global_vars=None)
    bad_r = Routine(r.name,
                    [r.arguments[0], InOutArgument(y, y, y)], r.results,
                    r.local_vars, r.global_vars)
    pytest.raises(CodeGenError, lambda: cg.write([bad_r], 'test'))

    pytest.raises(ValueError, lambda: cg.routine('test', [], None, None))
    pytest.raises(CodeGenError,
                  lambda: cg.routine('test', Eq(sin(y), x), None, None))
Exemplo n.º 9
0
def test_mathml_relational():
    mml_1 = mp._print(Eq(x, 1))
    assert mml_1.nodeName == 'apply'
    assert mml_1.childNodes[0].nodeName == 'eq'
    assert mml_1.childNodes[1].nodeName == 'ci'
    assert mml_1.childNodes[1].childNodes[0].nodeValue == 'x'
    assert mml_1.childNodes[2].nodeName == 'cn'
    assert mml_1.childNodes[2].childNodes[0].nodeValue == '1'

    mml_2 = mp._print(Ne(1, x))
    assert mml_2.nodeName == 'apply'
    assert mml_2.childNodes[0].nodeName == 'neq'
    assert mml_2.childNodes[1].nodeName == 'cn'
    assert mml_2.childNodes[1].childNodes[0].nodeValue == '1'
    assert mml_2.childNodes[2].nodeName == 'ci'
    assert mml_2.childNodes[2].childNodes[0].nodeValue == 'x'

    mml_3 = mp._print(Ge(1, x))
    assert mml_3.nodeName == 'apply'
    assert mml_3.childNodes[0].nodeName == 'geq'
    assert mml_3.childNodes[1].nodeName == 'cn'
    assert mml_3.childNodes[1].childNodes[0].nodeValue == '1'
    assert mml_3.childNodes[2].nodeName == 'ci'
    assert mml_3.childNodes[2].childNodes[0].nodeValue == 'x'

    mml_4 = mp._print(Lt(1, x))
    assert mml_4.nodeName == 'apply'
    assert mml_4.childNodes[0].nodeName == 'lt'
    assert mml_4.childNodes[1].nodeName == 'cn'
    assert mml_4.childNodes[1].childNodes[0].nodeValue == '1'
    assert mml_4.childNodes[2].nodeName == 'ci'
    assert mml_4.childNodes[2].childNodes[0].nodeValue == 'x'
Exemplo n.º 10
0
def test_reduce_piecewise_inequalities():
    e = abs(x - 5) < 3
    ans = (Integer(2) < x) & (x < 8)
    assert reduce_inequalities(e) == ans
    assert reduce_inequalities(e, x) == ans
    assert reduce_inequalities(abs(x - 5)) == Eq(x, 5)
    assert reduce_inequalities(
        abs(2 * x + 3) >= 8) == ((Rational(5, 2) <= x) |
                                 (x <= -Rational(11, 2)))
    assert reduce_inequalities(
        abs(x - 4) + abs(3 * x - 5) < 7) == (Rational(1, 2) < x) & (x < 4)
    assert reduce_inequalities(abs(x - 4) + abs(3*abs(x) - 5) < 7) == \
        ((Integer(-2) < x) & (x < -1)) | ((Rational(1, 2) < x) & (x < 4))

    nr = Symbol('nr', extended_real=False)
    pytest.raises(TypeError, lambda: reduce_inequalities(abs(nr - 5) < 3))

    # sympy/sympy#10198
    assert reduce_inequalities(-1 + 1/abs(1/x - 1) < 0) == \
        ((Integer(0) < x) & (x < Rational(1, 2))) | (x < 0)
    assert reduce_inequalities(-1 + 1/abs(-1/x - 1) < 0) == \
        ((-Rational(1, 2) < x) & (x < 0)) | (Integer(0) < x)

    # sympy/sympy#10255
    assert reduce_inequalities(Piecewise((1, x < 1), (3, True)) > 1) == \
        (Integer(1) <= x)
    assert reduce_inequalities(Piecewise((x**2, x < 0), (2*x, True)) < 1) == \
        (Integer(-1) < x) & (x < Rational(1, 2))
Exemplo n.º 11
0
def test_density():
    x = Symbol('x')
    l = Symbol('l', positive=True)
    rate = Beta(l, 2, 3)
    X = Poisson(x, rate)
    assert isinstance(pspace(X), ProductPSpace)
    assert density(X, Eq(rate, rate.symbol)) == PoissonDistribution(l)
Exemplo n.º 12
0
def test_doit():
    p = Symbol('p', positive=True)
    n = Symbol('n', negative=True)
    np = Symbol('np', nonpositive=True)
    nn = Symbol('nn', nonnegative=True)

    assert Gt(p, 0).doit() is true
    assert Gt(p, 1).doit() == Gt(p, 1)
    assert Ge(p, 0).doit() is true
    assert Le(p, 0).doit() is false
    assert Lt(n, 0).doit() is true
    assert Le(np, 0).doit() is true
    assert Gt(nn, 0).doit() == Gt(nn, 0)
    assert Lt(nn, 0).doit() is false

    assert Eq(x, 0).doit() == Eq(x, 0)
Exemplo n.º 13
0
def test_pde_separate_add():
    x, y, z, t = symbols("x,y,z,t")
    F, T, X, Y, Z, u = map(Function, 'FTXYZu')

    eq = Eq(D(u(x, t), x), D(u(x, t), t) * exp(u(x, t)))
    res = pde_separate_add(eq, u(x, t), [X(x), T(t)])
    assert res == [D(X(x), x) * exp(-X(x)), D(T(t), t) * exp(T(t))]
Exemplo n.º 14
0
def test_pde_classify():
    # When more number of hints are added, add tests for classifying here.
    f, g = symbols('f g', cls=Function)
    u = f(x, y)
    eq1 = a * u + b * u.diff(x) + c * u.diff(y)
    eq2 = 3 * u + 2 * u.diff(x) + u.diff(y)
    eq3 = a * u + b * u.diff(x) + 2 * u.diff(y)
    eq4 = x * u + u.diff(x) + 3 * u.diff(y)
    eq5 = x**2 * u + x * u.diff(x) + x * y * u.diff(y)
    eq6 = y * x**2 * u + y * u.diff(x) + u.diff(y)
    for eq in [eq1, eq2, eq3]:
        assert classify_pde(eq) == ('1st_linear_constant_coeff_homogeneous', )
    for eq in [eq4, eq5, eq6]:
        assert classify_pde(eq) == ('1st_linear_variable_coeff', )

    # coverage tests
    assert classify_pde(eq, u) == ('1st_linear_variable_coeff', )
    assert classify_pde(eq, g(x, y)) == ()
    assert classify_pde(eq, g(x, y), dict=True) == {
        'default': None,
        'order': 0
    }
    assert classify_pde(u.diff(x) + I * u.diff(y) + y) == ()
    assert classify_pde(u.diff(x, y) + x) == ()
    assert classify_pde(x * u.diff(x) + u * u.diff(y) + y) == ()
    assert classify_pde(x * u.diff(x) + u * u.diff(y) + y, dict=True) == {
        'default': None,
        'ordered_hints': (),
        'order': 1
    }
    assert classify_pde(2 * u.diff(x, y, y)) == ()

    eq = Eq(1 + (2 * (u.diff(x) / u)) + (3 * (u.diff(y) / u)), 0)
    assert classify_pde(eq) == ('1st_linear_constant_coeff_homogeneous', )
Exemplo n.º 15
0
def test_reduce_piecewise_inequalities():
    e = abs(x - 5) < 3
    ans = And(Lt(2, x), Lt(x, 8))
    assert reduce_inequalities(e) == ans
    assert reduce_inequalities(e, x) == ans
    assert reduce_inequalities(abs(x - 5)) == Eq(x, 5)
    assert reduce_inequalities(
        abs(2*x + 3) >= 8) == Or(And(Le(Rational(5, 2), x), Lt(x, oo)),
        And(Le(x, -Rational(11, 2)), Lt(-oo, x)))
    assert reduce_inequalities(abs(x - 4) + abs(
        3*x - 5) < 7) == And(Lt(Rational(1, 2), x), Lt(x, 4))
    assert reduce_inequalities(abs(x - 4) + abs(3*abs(x) - 5) < 7) == \
        Or(And(Integer(-2) < x, x < -1), And(Rational(1, 2) < x, x < 4))

    nr = Symbol('nr', extended_real=False)
    pytest.raises(TypeError, lambda: reduce_inequalities(abs(nr - 5) < 3))

    # sympy/sympy#10198
    assert reduce_inequalities(-1 + 1/abs(1/x - 1) < 0) == \
        Or(And(S.Zero < x, x < S.Half), And(-oo < x, x < S.Zero))

    # sympy/sympy#10255
    assert reduce_inequalities(Piecewise((1, x < 1), (3, True)) > 1) == \
        And(S.One <= x, x < oo)
    assert reduce_inequalities(Piecewise((x**2, x < 0), (2*x, x >= 0)) < 1) == \
        And(-S.One < x, x < S.Half)
Exemplo n.º 16
0
def deltaproduct(f, limit):
    """Handle products containing a KroneckerDelta.

    See Also
    ========

    deltasummation
    diofant.functions.special.tensor_functions.KroneckerDelta
    diofant.concrete.products.product
    """
    from diofant.concrete.products import product

    if ((limit[2] - limit[1]) < 0) is S.true:
        return S.One

    if not f.has(KroneckerDelta):
        return product(f, limit)

    if f.is_Add:
        # Identify the term in the Add that has a simple KroneckerDelta
        delta = None
        terms = []
        for arg in sorted(f.args, key=default_sort_key):
            if delta is None and _has_simple_delta(arg, limit[0]):
                delta = arg
            else:
                terms.append(arg)
        newexpr = f.func(*terms)
        k = Dummy("kprime", integer=True)
        if isinstance(limit[1], int) and isinstance(limit[2], int):
            result = deltaproduct(newexpr, limit) + sum(
                deltaproduct(newexpr, (limit[0], limit[1], ik - 1)) *
                delta.subs(limit[0], ik) *
                deltaproduct(newexpr, (limit[0], ik + 1, limit[2]))
                for ik in range(int(limit[1]), int(limit[2] + 1)))
        else:
            result = deltaproduct(newexpr, limit) + deltasummation(
                deltaproduct(newexpr, (limit[0], limit[1], k - 1)) *
                delta.subs(limit[0], k) *
                deltaproduct(newexpr, (limit[0], k + 1, limit[2])),
                (k, limit[1], limit[2]),
                no_piecewise=_has_simple_delta(newexpr, limit[0]))
        return _remove_multiple_delta(result)

    delta, _ = _extract_delta(f, limit[0])

    if not delta:
        g = _expand_delta(f, limit[0])
        if f != g:
            from diofant import factor
            try:
                return factor(deltaproduct(g, limit))
            except AssertionError:
                return deltaproduct(g, limit)
        return product(f, limit)

    from diofant import Eq
    c = Eq(limit[2], limit[1] - 1)
    return _remove_multiple_delta(f.subs(limit[0], limit[1])*KroneckerDelta(limit[2], limit[1])) + \
        S.One*_simplify_delta(KroneckerDelta(limit[2], limit[1] - 1))
Exemplo n.º 17
0
def test_m_tensor_loops_multiple_contractions():
    # see comments in previous test about vectorizing
    n, m, o, p = symbols('n m o p', integer=True)
    A = IndexedBase('A')
    B = IndexedBase('B')
    y = IndexedBase('y')
    i = Idx('i', m)
    j = Idx('j', n)
    k = Idx('k', o)
    l = Idx('l', p)
    result, = codegen(('tensorthing', Eq(y[i], B[j, k, l] * A[i, j, k, l])),
                      'Octave',
                      header=False,
                      empty=False)
    source = result[1]
    expected = ('function y = tensorthing(A, B, m, n, o, p)\n'
                '  for i = 1:m\n'
                '    y(i) = 0;\n'
                '  end\n'
                '  for i = 1:m\n'
                '    for j = 1:n\n'
                '      for k = 1:o\n'
                '        for l = 1:p\n'
                '          y(i) = y(i) + B(j, k, l).*A(i, j, k, l);\n'
                '        end\n'
                '      end\n'
                '    end\n'
                '  end\n'
                'end\n')
    assert source == expected
Exemplo n.º 18
0
def test_deltasummation_mul_x_add_y_kd():
    assert ds(x*(y + Kd(i, j)), (j, 1, 3)) == \
        Piecewise((3*x*y + x, And(Integer(1) <= i, i <= 3)), (3*x*y, True))
    assert ds(x*(y + Kd(i, j)), (j, 1, 1)) == \
        Piecewise((x*y + x, Eq(i, 1)), (x*y, True))
    assert ds(x*(y + Kd(i, j)), (j, 2, 2)) == \
        Piecewise((x*y + x, Eq(i, 2)), (x*y, True))
    assert ds(x*(y + Kd(i, j)), (j, 3, 3)) == \
        Piecewise((x*y + x, Eq(i, 3)), (x*y, True))
    assert ds(x*(y + Kd(i, j)), (j, 1, k)) == \
        Piecewise((k*x*y + x, And(Integer(1) <= i, i <= k)), (k*x*y, True))
    assert ds(x*(y + Kd(i, j)), (j, k, 3)) == \
        Piecewise(((4 - k)*x*y + x, And(k <= i, i <= 3)), ((4 - k)*x*y, True))
    assert ds(x * (y + Kd(i, j)), (j, k, l)) == Piecewise(
        ((l - k + 1) * x * y + x, And(k <= i, i <= l)),
        ((l - k + 1) * x * y, True))
Exemplo n.º 19
0
def test_coins():
    C, D = Coin('C'), Coin('D')
    H, T = symbols('H, T')
    assert P(Eq(C, D)) == Rational(1, 2)
    assert density(Tuple(C, D)) == {(H, H): Rational(1, 4), (H, T): Rational(1, 4),
                                    (T, H): Rational(1, 4), (T, T): Rational(1, 4)}
    assert dict(density(C).items()) == {H: Rational(1, 2), T: Rational(1, 2)}

    F = Coin('F', Rational(1, 10))
    assert P(Eq(F, H)) == Rational(1, 10)

    d = pspace(C).domain

    assert d.as_boolean() == Or(Eq(C.symbol, H), Eq(C.symbol, T))

    pytest.raises(ValueError, lambda: P(C > D))  # Can't intelligently compare H to T
Exemplo n.º 20
0
def test_matplotlib2():
    name = 'test2'

    plot_implicit(And(y > cos(x), Or(y > x, Eq(y, x))),
                  show=False).save(tmp_file(name))

    # Test plots which cannot be rendered using the adaptive algorithm
    # TODO: catch the warning.
    plot_implicit(Eq(y, re(cos(x) + I * sin(x))),
                  show=False).save(tmp_file(name))

    with warnings.catch_warnings(record=True) as w:
        plot_implicit(x**2 - 1, legend='An implicit plot',
                      show=False).save(tmp_file(name))
        assert len(w) == 1
        assert issubclass(w[-1].category, UserWarning)
        assert 'No labelled objects found' in str(w[0].message)
Exemplo n.º 21
0
def test_rewrite():
    x = Symbol('x', extended_real=True)
    assert Heaviside(x).rewrite(Piecewise) == \
        Piecewise((1, x > 0), (Rational(1, 2), Eq(x, 0)), (0, True))
    assert Heaviside(y).rewrite(Piecewise) == Heaviside(y)

    assert Heaviside(x).rewrite(sign) == (sign(x)+1)/2
    assert Heaviside(y).rewrite(sign) == Heaviside(y)
Exemplo n.º 22
0
def test_euler_high_order():
    # an example from hep-th/0309038
    m = Symbol('m')
    k = Symbol('k')
    x = Function('x')
    y = Function('y')
    t = Symbol('t')
    L = (m * D(x(t), t)**2 / 2 + m * D(y(t), t)**2 / 2 -
         k * D(x(t), t) * D(y(t), t, t) + k * D(y(t), t) * D(x(t), t, t))
    assert euler(L, [x(t), y(t)]) == [
        Eq(2 * k * D(y(t), t, t, t) - m * D(x(t), t, t)),
        Eq(-2 * k * D(x(t), t, t, t) - m * D(y(t), t, t))
    ]

    w = Symbol('w')
    L = D(x(t, w), t, w)**2 / 2
    assert euler(L) == [Eq(D(x(t, w), t, t, w, w))]
Exemplo n.º 23
0
def test_euler_sineg():
    psi = Function('psi')
    t = Symbol('t')
    x = Symbol('x')
    L = D(psi(t, x), t)**2 / 2 - D(psi(t, x), x)**2 / 2 + cos(psi(t, x))
    assert euler(L, psi(t, x), [t, x]) == [
        Eq(-sin(psi(t, x)) - D(psi(t, x), t, t) + D(psi(t, x), x, x))
    ]
Exemplo n.º 24
0
def test_relational_bool_output():
    # https://github.com/sympy/sympy/issues/5931
    pytest.raises(TypeError, lambda: bool(x > 3))
    pytest.raises(TypeError, lambda: bool(x >= 3))
    pytest.raises(TypeError, lambda: bool(x < 3))
    pytest.raises(TypeError, lambda: bool(x <= 3))
    pytest.raises(TypeError, lambda: bool(Eq(x, 3)))
    pytest.raises(TypeError, lambda: bool(Ne(x, 3)))
Exemplo n.º 25
0
def test_FiniteRV():
    F = FiniteRV('F', {1: S.Half, 2: S.One/4, 3: S.One/4})

    assert dict(density(F).items()) == {Integer(1): S.Half, Integer(2): S.One/4, Integer(3): S.One/4}
    assert P(F >= 2) == S.Half

    assert pspace(F).domain.as_boolean() == Or(
        *[Eq(F.symbol, i) for i in [1, 2, 3]])
Exemplo n.º 26
0
def test_FiniteRV():
    F = FiniteRV('F', {1: Rational(1, 2), 2: Rational(1, 4), 3: Rational(1, 4)})

    assert dict(density(F).items()) == {1: Rational(1, 2), 2: Rational(1, 4), 3: Rational(1, 4)}
    assert P(F >= 2) == Rational(1, 2)

    assert pspace(F).domain.as_boolean() == Or(
        *[Eq(F.symbol, i) for i in [1, 2, 3]])
Exemplo n.º 27
0
def test_deltasummation_basic_symbolic():
    assert ds(Kd(exp(i), 0), (i, 1, 3)) == 0
    assert ds(Kd(exp(i), 0), (i, -1, 3)) == 0
    assert ds(Kd(exp(i), 1), (i, 0, 3)) == 1
    assert ds(Kd(exp(i), 1), (i, 1, 3)) == 0
    assert ds(Kd(exp(i), 1), (i, -10, 3)) == 1
    assert ds(Kd(i, j), (j, 1, 3)) == \
        Piecewise((1, And(Integer(1) <= i, i <= 3)), (0, True))
    assert ds(Kd(i, j), (j, 1, 1)) == Piecewise((1, Eq(i, 1)), (0, True))
    assert ds(Kd(i, j), (j, 2, 2)) == Piecewise((1, Eq(i, 2)), (0, True))
    assert ds(Kd(i, j), (j, 3, 3)) == Piecewise((1, Eq(i, 3)), (0, True))
    assert ds(Kd(i, j), (j, 1, k)) == \
        Piecewise((1, And(Integer(1) <= i, i <= k)), (0, True))
    assert ds(Kd(i, j), (j, k, 3)) == \
        Piecewise((1, And(k <= i, i <= 3)), (0, True))
    assert ds(Kd(i, j), (j, k, l)) == \
        Piecewise((1, And(k <= i, i <= l)), (0, True))
Exemplo n.º 28
0
def given(expr, condition=None, **kwargs):
    """ Conditional Random Expression
    From a random expression and a condition on that expression creates a new
    probability space from the condition and returns the same expression on that
    conditional probability space.

    Examples
    ========

    >>> from diofant.stats import given, density, Die
    >>> X = Die('X', 6)
    >>> Y = given(X, X > 3)
    >>> density(Y).dict
    {4: 1/3, 5: 1/3, 6: 1/3}

    Following convention, if the condition is a random symbol then that symbol
    is considered fixed.

    >>> from diofant.stats import Normal
    >>> from diofant import pprint
    >>> from diofant.abc import z

    >>> X = Normal('X', 0, 1)
    >>> Y = Normal('Y', 0, 1)
    >>> pprint(density(X + Y, Y)(z), use_unicode=False)
                    2
           -(-Y + z)
           -----------
      ___       2
    \/ 2 *E
    ------------------
             ____
         2*\/ pi
    """

    if not random_symbols(condition) or pspace_independent(expr, condition):
        return expr

    if isinstance(condition, RandomSymbol):
        condition = Eq(condition, condition.symbol)

    condsymbols = random_symbols(condition)
    if (isinstance(condition, Equality) and len(condsymbols) == 1 and
            not isinstance(pspace(expr).domain, ConditionalDomain)):
        rv = tuple(condsymbols)[0]
        results = solve(condition, rv)
        return sum(expr.subs(rv, res) for res in results)

    # Get full probability space of both the expression and the condition
    fullspace = pspace(Tuple(expr, condition))
    # Build new space given the condition
    space = fullspace.conditional_space(condition, **kwargs)
    # Dictionary to swap out RandomSymbols in expr with new RandomSymbols
    # That point to the new conditional space
    swapdict = rs_swap(fullspace.values, space.values)
    # Swap random variables in the expression
    expr = expr.xreplace(swapdict)
    return expr
Exemplo n.º 29
0
def main():
    r, phi, theta = symbols("r,phi,theta")
    Xi = Function('Xi')
    R, Phi, Theta, u = map(Function, ['R', 'Phi', 'Theta', 'u'])
    C1, C2 = symbols('C1,C2')

    pprint(
        "Separation of variables in Laplace equation in spherical coordinates")
    pprint("Laplace equation in spherical coordinates:")
    eq = Eq(
        D(Xi(r, phi, theta), r, 2) + 2 / r * D(Xi(r, phi, theta), r) + 1 /
        (r**2 * sin(phi)**2) * D(Xi(r, phi, theta), theta, 2) + cos(phi) /
        (r**2 * sin(phi)) * D(Xi(r, phi, theta), phi) +
        1 / r**2 * D(Xi(r, phi, theta), phi, 2))
    pprint(eq)

    pprint("We can either separate this equation in regards with variable r:")
    res_r = pde_separate(eq, Xi(r, phi, theta), [R(r), u(phi, theta)])
    pprint(res_r)

    pprint("Or separate it in regards of theta:")
    res_theta = pde_separate(eq, Xi(r, phi, theta), [Theta(theta), u(r, phi)])
    pprint(res_theta)

    res_phi = pde_separate(eq, Xi(r, phi, theta), [Phi(phi), u(r, theta)])
    pprint("But we cannot separate it in regards of variable phi: ")
    pprint("Result: %s" % res_phi)

    pprint("\n\nSo let's make theta dependent part equal with -C1:")
    eq_theta = Eq(res_theta[0], -C1)

    pprint(eq_theta)
    pprint("\nThis also means that second part is also equal to -C1:")
    eq_left = Eq(res_theta[1], -C1)
    pprint(eq_left)

    pprint("\nLets try to separate phi again :)")
    res_theta = pde_separate(eq_left, u(r, phi), [Phi(phi), R(r)])
    pprint("\nThis time it is successful:")
    pprint(res_theta)

    pprint("\n\nSo our final equations with separated variables are:")
    pprint(eq_theta)
    pprint(Eq(res_theta[0], C2))
    pprint(Eq(res_theta[1], C2))
Exemplo n.º 30
0
def test_integrate_hyperexponential_returns_piecewise():
    a, b = symbols('a b')
    DE = DifferentialExtension(a**x, x)
    assert integrate_hyperexponential(DE.fa, DE.fd, DE) == (Piecewise(
        (x, Eq(log(a), 0)), (exp(x * log(a)) / log(a), True)), 0, True)
    DE = DifferentialExtension(a**(b * x), x)
    assert integrate_hyperexponential(DE.fa, DE.fd, DE) == (Piecewise(
        (x, Eq(b * log(a), 0)),
        (exp(b * x * log(a)) / (b * log(a)), True)), 0, True)
    DE = DifferentialExtension(exp(a * x), x)
    assert integrate_hyperexponential(DE.fa, DE.fd, DE) == (Piecewise(
        (x, Eq(a, 0)), (exp(a * x) / a, True)), 0, True)
    DE = DifferentialExtension(x * exp(a * x), x)
    assert integrate_hyperexponential(DE.fa, DE.fd, DE) == (Piecewise(
        (x**2 / 2, Eq(a**3, 0)),
        ((x * a**2 - a) * exp(a * x) / a**3, True)), 0, True)
    DE = DifferentialExtension(x**2 * exp(a * x), x)
    assert integrate_hyperexponential(DE.fa, DE.fd, DE) == (Piecewise(
        (x**3 / 3, Eq(a**6, 0)),
        ((x**2 * a**5 - 2 * x * a**4 + 2 * a**3) * exp(a * x) / a**6, True)),
                                                            0, True)
    DE = DifferentialExtension(x**y + z, y)
    assert integrate_hyperexponential(DE.fa, DE.fd, DE) == (Piecewise(
        (y, Eq(log(x), 0)), (exp(log(x) * y) / log(x), True)), z, True)
    DE = DifferentialExtension(x**y + z + x**(2 * y), y)
    assert integrate_hyperexponential(DE.fa, DE.fd, DE) == (Piecewise(
        (2 * y, Eq(2 * log(x)**2, 0)),
        ((exp(2 * log(x) * y) * log(x) + 2 * exp(log(x) * y) * log(x)) /
         (2 * log(x)**2), True)), z, True)