예제 #1
0
def test_ccode_results_named_ordered():
    x, y, z = symbols('x,y,z')
    B, C = symbols('B,C')
    A = MatrixSymbol('A', 1, 3)
    expr1 = Equality(A, Matrix([[1, 2, x]]))
    expr2 = Equality(C, (x + y)*z)
    expr3 = Equality(B, 2*x)
    name_expr = ("test", [expr1, expr2, expr3])
    expected = (
        '#include "test.h"\n'
        '#include <math.h>\n'
        'void test(double x, double *C, double z, double y, double *A, double *B) {\n'
        '   (*C) = z*(x + y);\n'
        '   A[0] = 1;\n'
        '   A[1] = 2;\n'
        '   A[2] = x;\n'
        '   (*B) = 2*x;\n'
        '}\n'
    )
    with warnings.catch_warnings():
        warnings.filterwarnings("ignore", category=SymPyDeprecationWarning)

        result = codegen(name_expr, "c", "test", header=False, empty=False,
                         argument_sequence=(x, C, z, y, A, B))
        source = result[0][1]
        assert source == expected
예제 #2
0
파일: test_GA.py 프로젝트: brombo/sympy
def test_differential_operators():

    xyz_coords = (x, y, z) = symbols('x y z', real=True)
    (o3d, ex, ey, ez) = Ga.build('e', g=[1, 1, 1], coords=xyz_coords)
    f = o3d.mv('f', 'scalar', f=True)
    lap = o3d.grad*o3d.grad

    assert str(lap) == 'D{x}^2 + D{y}^2 + D{z}^2'
    assert str(lap * f) == 'D{x}^2f + D{y}^2f + D{z}^2f'

    sph_coords = (r, th, phi) = symbols('r theta phi', real=True)
    (sp3d, er, eth, ephi) = Ga.build('e', g=[1, r**2, r**2 * sin(th)**2], coords=sph_coords, norm=True)
    f = sp3d.mv('f', 'scalar', f=True)
    lap = sp3d.grad*sp3d.grad
    assert str(lap) == '2/r*D{r} + cos(theta)/(r**2*sin(theta))*D{theta} + D{r}^2 + r**(-2)*D{theta}^2 + 1/(r**2*sin(theta)**2)*D{phi}^2'
    assert str(lap * f) == 'D{r}^2f + 2*D{r}f/r + D{theta}^2f/r**2 + cos(theta)*D{theta}f/(r**2*sin(theta)) + D{phi}^2f/(r**2*sin(theta)**2)'

    A = o3d.mv('A','vector')
    xs = o3d.mv(x)

    assert o3d.grad*A == 0
    assert str(A*o3d.grad) == 'A__x*D{x} + A__y*D{y} + A__z*D{z} + e_x^e_y*(-A__y*D{x} + A__x*D{y}) + e_x^e_z*(-A__z*D{x} + A__x*D{z}) + e_y^e_z*(-A__z*D{y} + A__y*D{z})'
    assert o3d.grad*xs == ex
    assert str(xs*o3d.grad) == 'e_x*x*D{x} + e_y*x*D{y} + e_z*x*D{z}'
    assert str(o3d.grad*(o3d.grad+xs)) == 'D{x}^2 + D{y}^2 + D{z}^2 + e_x*D{}'
    assert str((o3d.grad+xs)*o3d.grad) == 'D{x}^2 + D{y}^2 + D{z}^2 + e_x*x*D{x} + e_y*x*D{y} + e_z*x*D{z}'

    return
예제 #3
0
def test_MatrixElement_with_values():
    x, y, z, w = symbols("x y z w")
    M = Matrix([[x, y], [z, w]])
    i, j = symbols("i, j")
    Mij = M[i, j]
    assert isinstance(Mij, MatrixElement)
    Ms = SparseMatrix([[2, 3], [4, 5]])
    msij = Ms[i, j]
    assert isinstance(msij, MatrixElement)
    for oi, oj in [(0, 0), (0, 1), (1, 0), (1, 1)]:
        assert Mij.subs({i: oi, j: oj}) == M[oi, oj]
        assert msij.subs({i: oi, j: oj}) == Ms[oi, oj]
    A = MatrixSymbol("A", 2, 2)
    assert A[0, 0].subs(A, M) == x
    assert A[i, j].subs(A, M) == M[i, j]
    assert M[i, j].subs(M, A) == A[i, j]

    assert isinstance(M[3*i - 2, j], MatrixElement)
    assert M[3*i - 2, j].subs({i: 1, j: 0}) == M[1, 0]
    assert isinstance(M[i, 0], MatrixElement)
    assert M[i, 0].subs(i, 0) == M[0, 0]
    assert M[0, i].subs(i, 1) == M[0, 1]

    assert M[i, j].diff(x) == Matrix([[1, 0], [0, 0]])[i, j]

    raises(ValueError, lambda: M[i, 2])
    raises(ValueError, lambda: M[i, -1])
    raises(ValueError, lambda: M[2, i])
    raises(ValueError, lambda: M[-1, i])
예제 #4
0
def test_fcode_results_named_ordered():
    x, y, z = symbols('x,y,z')
    B, C = symbols('B,C')
    A = MatrixSymbol('A', 1, 3)
    expr1 = Equality(A, Matrix([[1, 2, x]]))
    expr2 = Equality(C, (x + y)*z)
    expr3 = Equality(B, 2*x)
    name_expr = ("test", [expr1, expr2, expr3])
    result = codegen(name_expr, "f95", "test", header=False, empty=False,
                     argument_sequence=(x, z, y, C, A, B))
    source = result[0][1]
    expected = (
        "subroutine test(x, z, y, C, A, B)\n"
        "implicit none\n"
        "REAL*8, intent(in) :: x\n"
        "REAL*8, intent(in) :: z\n"
        "REAL*8, intent(in) :: y\n"
        "REAL*8, intent(out) :: C\n"
        "REAL*8, intent(out) :: B\n"
        "REAL*8, intent(out), dimension(1:1, 1:3) :: A\n"
        "C = z*(x + y)\n"
        "A(1, 1) = 1\n"
        "A(1, 2) = 2\n"
        "A(1, 3) = x\n"
        "B = 2*x\n"
        "end subroutine\n"
    )
    assert source == expected
예제 #5
0
def test_functional_diffgeom_ch2():
    x0, y0, r0, theta0 = symbols('x0, y0, r0, theta0', real=True)
    x, y = symbols('x, y', real=True)
    f = Function('f')

    assert (R2_p.point_to_coords(R2_r.point([x0, y0])) ==
           Matrix([sqrt(x0**2 + y0**2), atan2(y0, x0)]))
    assert (R2_r.point_to_coords(R2_p.point([r0, theta0])) ==
           Matrix([r0*cos(theta0), r0*sin(theta0)]))

    assert R2_p.jacobian(R2_r, [r0, theta0]) == Matrix(
        [[cos(theta0), -r0*sin(theta0)], [sin(theta0), r0*cos(theta0)]])

    field = f(R2.x, R2.y)
    p1_in_rect = R2_r.point([x0, y0])
    p1_in_polar = R2_p.point([sqrt(x0**2 + y0**2), atan2(y0, x0)])
    assert field.rcall(p1_in_rect) == f(x0, y0)
    assert field.rcall(p1_in_polar) == f(x0, y0)

    p_r = R2_r.point([x0, y0])
    p_p = R2_p.point([r0, theta0])
    assert R2.x(p_r) == x0
    assert R2.x(p_p) == r0*cos(theta0)
    assert R2.r(p_p) == r0
    assert R2.r(p_r) == sqrt(x0**2 + y0**2)
    assert R2.theta(p_r) == atan2(y0, x0)

    h = R2.x*R2.r**2 + R2.y**3
    assert h.rcall(p_r) == x0*(x0**2 + y0**2) + y0**3
    assert h.rcall(p_p) == r0**3*sin(theta0)**3 + r0**3*cos(theta0)
예제 #6
0
def test_Routine_argument_order():
    a, x, y, z = symbols('a x y z')
    expr = (x + y)*z
    raises(CodeGenArgumentListError, lambda: make_routine("test", expr,
           argument_sequence=[z, x]))
    raises(CodeGenArgumentListError, lambda: make_routine("test", Eq(a,
           expr), argument_sequence=[z, x, y]))
    r = make_routine('test', Eq(a, expr), argument_sequence=[z, x, a, y])
    assert [ arg.name for arg in r.arguments ] == [z, x, a, y]
    assert [ type(arg) for arg in r.arguments ] == [
        InputArgument, InputArgument, OutputArgument, InputArgument  ]
    r = make_routine('test', Eq(z, expr), argument_sequence=[z, x, y])
    assert [ type(arg) for arg in r.arguments ] == [
        InOutArgument, InputArgument, InputArgument ]

    from sympy.tensor import IndexedBase, Idx
    A, B = map(IndexedBase, ['A', 'B'])
    m = symbols('m', integer=True)
    i = Idx('i', m)
    r = make_routine('test', Eq(A[i], B[i]), argument_sequence=[B, A, m])
    assert [ arg.name for arg in r.arguments ] == [B.label, A.label, m]

    expr = Integral(x*y*z, (x, 1, 2), (y, 1, 3))
    r = make_routine('test', Eq(a, expr), argument_sequence=[z, x, a, y])
    assert [ arg.name for arg in r.arguments ] == [z, x, a, y]
def test_macaulay_example_two():
    """Tests the Macaulay formulation for example from [Stiller96]_."""

    x, y, z = symbols('x, y, z')
    a_0, a_1, a_2 = symbols('a_0, a_1, a_2')
    b_0, b_1, b_2 = symbols('b_0, b_1, b_2')
    c_0, c_1, c_2, c_3, c_4 = symbols('c_0, c_1, c_2, c_3, c_4')

    f = a_0 * y -  a_1 * x + a_2 * z
    g = b_1 * x ** 2 + b_0 * y ** 2 - b_2 * z ** 2
    h = c_0 * y - c_1 * x ** 3 + c_2 * x ** 2 * z - c_3 * x * z ** 2 + \
        c_4 * z ** 3

    mac = MacaulayResultant([f, g, h], [x, y, z])

    assert mac.degrees == [1, 2, 3]
    assert mac.degree_m == 4
    assert mac.monomials_size == 15
    assert len(mac.get_row_coefficients()) == mac.n

    matrix = mac.get_matrix()
    assert matrix.shape == (mac.monomials_size, mac.monomials_size)
    assert mac.get_submatrix(matrix) == Matrix([[-a_1, a_0, a_2, 0],
                                                [0, -a_1, 0, 0],
                                                [0, 0, -a_1, 0],
                                                [0, 0, 0, -a_1]])
예제 #8
0
def test_complicated_derivative_with_Indexed():
    x, y = symbols("x,y", cls=IndexedBase)
    sigma = symbols("sigma")
    i, j, k = symbols("i,j,k")
    m0,m1,m2,m3,m4,m5 = symbols("m0:6")
    f = Function("f")

    expr = f((x[i] - y[i])**2/sigma)
    _xi_1 = symbols("xi_1", cls=Dummy)
    assert expr.diff(x[m0]).dummy_eq(
        (x[i] - y[i])*KroneckerDelta(i, m0)*\
        2*Subs(
            Derivative(f(_xi_1), _xi_1),
            (_xi_1,),
            ((x[i] - y[i])**2/sigma,)
        )/sigma
    )
    assert expr.diff(x[m0]).diff(x[m1]).dummy_eq(
        2*KroneckerDelta(i, m0)*\
        KroneckerDelta(i, m1)*Subs(
            Derivative(f(_xi_1), _xi_1),
            (_xi_1,),
            ((x[i] - y[i])**2/sigma,)
         )/sigma + \
        4*(x[i] - y[i])**2*KroneckerDelta(i, m0)*KroneckerDelta(i, m1)*\
        Subs(
            Derivative(f(_xi_1), _xi_1, _xi_1),
            (_xi_1,),
            ((x[i] - y[i])**2/sigma,)
        )/sigma**2
    )
예제 #9
0
def test_Subs_with_Indexed():
    A = IndexedBase("A")
    i, j, k = symbols("i,j,k")
    x, y, z = symbols("x,y,z")
    f = Function("f")

    assert Subs(A[i], A[i], A[j]).diff(A[j]) == 1
    assert Subs(A[i], A[i], x).diff(A[i]) == 0
    assert Subs(A[i], A[i], x).diff(A[j]) == 0
    assert Subs(A[i], A[i], x).diff(x) == 1
    assert Subs(A[i], A[i], x).diff(y) == 0
    assert Subs(A[i], A[i], A[j]).diff(A[k]) == KroneckerDelta(j, k)
    assert Subs(x, x, A[i]).diff(A[j]) == KroneckerDelta(i, j)
    assert Subs(f(A[i]), A[i], x).diff(A[j]) == 0
    assert Subs(f(A[i]), A[i], A[k]).diff(A[j]) == Derivative(f(A[k]), A[k])*KroneckerDelta(j, k)
    assert Subs(x, x, A[i]**2).diff(A[j]) == 2*KroneckerDelta(i, j)*A[i]
    assert Subs(A[i], A[i], A[j]**2).diff(A[k]) == 2*KroneckerDelta(j, k)*A[j]

    assert Subs(A[i]*x, x, A[i]).diff(A[i]) == 2*A[i]
    assert Subs(A[i]*x, x, A[i]).diff(A[j]) == 2*A[i]*KroneckerDelta(i, j)
    assert Subs(A[i]*x, x, A[j]).diff(A[i]) == A[j] + A[i]*KroneckerDelta(i, j)
    assert Subs(A[i]*x, x, A[j]).diff(A[j]) == A[i] + A[j]*KroneckerDelta(i, j)
    assert Subs(A[i]*x, x, A[i]).diff(A[k]) == 2*A[i]*KroneckerDelta(i, k)
    assert Subs(A[i]*x, x, A[j]).diff(A[k]) == KroneckerDelta(i, k)*A[j] + KroneckerDelta(j, k)*A[i]

    assert Subs(A[i]*x, A[i], x).diff(A[i]) == 0
    assert Subs(A[i]*x, A[i], x).diff(A[j]) == 0
    assert Subs(A[i]*x, A[j], x).diff(A[i]) == x
    assert Subs(A[i]*x, A[j], x).diff(A[j]) == x*KroneckerDelta(i, j)
    assert Subs(A[i]*x, A[i], x).diff(A[k]) == 0
    assert Subs(A[i]*x, A[j], x).diff(A[k]) == x*KroneckerDelta(i, k)
예제 #10
0
def test_issue_7638():
    f = pi/log(sqrt(2))
    assert ((1 + I)**(I*f/2))**0.3 == (1 + I)**(0.15*I*f)
    # if 1/3 -> 1.0/3 this should fail since it cannot be shown that the
    # sign will be +/-1; for the previous "small arg" case, it didn't matter
    # that this could not be proved
    assert (1 + I)**(4*I*f) == ((1 + I)**(12*I*f))**(S(1)/3)

    assert (((1 + I)**(I*(1 + 7*f)))**(S(1)/3)).exp == S(1)/3
    r = symbols('r', real=True)
    assert sqrt(r**2) == abs(r)
    assert cbrt(r**3) != r
    assert sqrt(Pow(2*I, 5*S.Half)) != (2*I)**(5/S(4))
    p = symbols('p', positive=True)
    assert cbrt(p**2) == p**(2/S(3))
    assert NS(((0.2 + 0.7*I)**(0.7 + 1.0*I))**(0.5 - 0.1*I), 1) == '0.4 + 0.2*I'
    assert sqrt(1/(1 + I)) == sqrt(1 - I)/sqrt(2)  # or 1/sqrt(1 + I)
    e = 1/(1 - sqrt(2))
    assert sqrt(e) == I/sqrt(-1 + sqrt(2))
    assert e**-S.Half == -I*sqrt(-1 + sqrt(2))
    assert sqrt((cos(1)**2 + sin(1)**2 - 1)**(3 + I)).exp == S.Half
    assert sqrt(r**(4/S(3))) != r**(2/S(3))
    assert sqrt((p + I)**(4/S(3))) == (p + I)**(2/S(3))
    assert sqrt((p - p**2*I)**2) == p - p**2*I
    assert sqrt((p + r*I)**2) != p + r*I
    e = (1 + I/5)
    assert sqrt(e**5) == e**(5*S.Half)
    assert sqrt(e**6) == e**3
    assert sqrt((1 + I*r)**6) != (1 + I*r)**3
예제 #11
0
def _test():
    '''runs module unit tests'''

    # Test below - tries every supported subexpression - takes a few seconds
    x = symbols('x')
    eq = sin(x + 0.01)
    #eq = 1*x*x + (0.2-x) / x + sin(x+0.01) + sqrt(x + 1) + cos(x + 0.01) + tan(x + 0.01) - (x+0.1)**(x+0.1)

    print eval_eq(eq, {'x':interval(0.20, 0.21)})

########################################################################
# Test below - makes sure evalEqMulti works as expected
    x = symbols('x')
    eq = x + interval(0.1)
    range1 = {'x':interval(0, 1)}
    range2 = {'x':interval(1, 2)}

    for i in eval_eq_multi(eq, [range1, range2]):
        print i

########################################################################
# Test below - makes sure eval_eq_multi_branch_bound works as expected
    x = symbols('x')
    eq = x*x - 2*x
    range1 = {'x':interval(0, 2)}

    for i in eval_eq_multi_branch_bound(eq, [range1], 0.1):
        print i
예제 #12
0
def test_Assignment():
    x, y = symbols("x, y")
    A = MatrixSymbol('A', 3, 1)
    mat = Matrix([1, 2, 3])
    B = IndexedBase('B')
    n = symbols("n", integer=True)
    i = Idx("i", n)
    # Here we just do things to show they don't error
    Assignment(x, y)
    Assignment(x, 0)
    Assignment(A, mat)
    Assignment(A[1,0], 0)
    Assignment(A[1,0], x)
    Assignment(B[i], x)
    Assignment(B[i], 0)
    # Here we test things to show that they error
    # Matrix to scalar
    raises(ValueError, lambda: Assignment(B[i], A))
    raises(ValueError, lambda: Assignment(B[i], mat))
    raises(ValueError, lambda: Assignment(x, mat))
    raises(ValueError, lambda: Assignment(x, A))
    raises(ValueError, lambda: Assignment(A[1,0], mat))
    # Scalar to matrix
    raises(ValueError, lambda: Assignment(A, x))
    raises(ValueError, lambda: Assignment(A, 0))
    # Non-atomic lhs
    raises(TypeError, lambda: Assignment(mat, A))
    raises(TypeError, lambda: Assignment(0, x))
    raises(TypeError, lambda: Assignment(x*x, 1))
    raises(TypeError, lambda: Assignment(A + A, mat))
    raises(TypeError, lambda: Assignment(B, 0))
예제 #13
0
파일: test_ccode.py 프로젝트: Lenqth/sympy
def test_ccode_Declaration():
    i = symbols('i', integer=True)
    var1 = Variable(i, type=Type.from_expr(i))
    dcl1 = Declaration(var1)
    assert ccode(dcl1) == 'int i'

    var2 = Variable(x, type=float32, attrs={value_const})
    dcl2a = Declaration(var2)
    assert ccode(dcl2a) == 'const float x'
    dcl2b = var2.as_Declaration(value=pi)
    assert ccode(dcl2b) == 'const float x = M_PI'

    var3 = Variable(y, type=Type('bool'))
    dcl3 = Declaration(var3)
    printer = C89CodePrinter()
    assert 'stdbool.h' not in printer.headers
    assert printer.doprint(dcl3) == 'bool y'
    assert 'stdbool.h' in printer.headers

    u = symbols('u', real=True)
    ptr4 = Pointer.deduced(u, attrs={pointer_const, restrict})
    dcl4 = Declaration(ptr4)
    assert ccode(dcl4) == 'double * const restrict u'

    var5 = Variable(x, Type('__float128'), attrs={value_const})
    dcl5a = Declaration(var5)
    assert ccode(dcl5a) == 'const __float128 x'
    var5b = Variable(var5.symbol, var5.type, pi, attrs=var5.attrs)
    dcl5b = Declaration(var5b)
    assert ccode(dcl5b) == 'const __float128 x = M_PI'
예제 #14
0
def interpolating_poly(n, x, X='x', Y='y'):
    """Construct Lagrange interpolating polynomial for ``n`` data points. """
    if isinstance(X, str):
        X = symbols("%s:%s" % (X, n))

    if isinstance(Y, str):
        Y = symbols("%s:%s" % (Y, n))

    coeffs = []

    for i in xrange(0, n):
        numer = []
        denom = []

        for j in xrange(0, n):
            if i == j:
                continue

            numer.append(x - X[j])
            denom.append(X[i] - X[j])

        numer = Mul(*numer)
        denom = Mul(*denom)

        coeffs.append(numer/denom)

    return Add(*[ coeff*y for coeff, y in zip(coeffs, Y) ])
예제 #15
0
def test_Indexed_subs():
    i, j, k = symbols('i j k', integer=True)
    a, b = symbols('a b')
    A = IndexedBase(a)
    B = IndexedBase(b)
    assert A[i, j] == B[i, j].subs(b, a)
    assert A[i, j] == A[i, k].subs(k, j)
def test_functional_diffgeom_ch4():
    x0, y0, theta0 = symbols('x0, y0, theta0', real=True)
    x, y, r, theta = symbols('x, y, r, theta', real=True)
    r0 = symbols('r0', positive=True)
    f = Function('f')
    b1 = Function('b1')
    b2 = Function('b2')
    p_r = R2_r.point([x0, y0])
    p_p = R2_p.point([r0, theta0])

    f_field = b1(R2.x,R2.y)*R2.dx + b2(R2.x,R2.y)*R2.dy
    assert f_field(R2.e_x)(p_r) == b1(x0, y0)
    assert f_field(R2.e_y)(p_r) == b2(x0, y0)

    s_field_r = f(R2.x,R2.y)
    df = Differential(s_field_r)
    assert df(R2.e_x)(p_r).doit() == Derivative(f(x0, y0), x0)
    assert df(R2.e_y)(p_r).doit() == Derivative(f(x0, y0), y0)

    s_field_p = f(R2.r,R2.theta)
    df = Differential(s_field_p)
    assert trigsimp(df(R2.e_x)(p_p).doit()) == cos(theta0)*Derivative(f(r0, theta0), r0) - sin(theta0)*Derivative(f(r0, theta0), theta0)/r0
    assert trigsimp(df(R2.e_y)(p_p).doit()) == sin(theta0)*Derivative(f(r0, theta0), r0) + cos(theta0)*Derivative(f(r0, theta0), theta0)/r0

    assert R2.dx(R2.e_x)(p_r) == 1
    assert R2.dx(R2.e_y)(p_r) == 0

    circ = -R2.y*R2.e_x + R2.x*R2.e_y
    assert R2.dx(circ)(p_r).doit() == -y0
    assert R2.dy(circ)(p_r) == x0
    assert R2.dr(circ)(p_r) == 0
    assert simplify(R2.dtheta(circ)(p_r)) == 1

    assert (circ - R2.e_theta)(s_field_r)(p_r) == 0
예제 #17
0
def test_functional_diffgeom_ch6():
    u0, u1, u2, v0, v1, v2, w0, w1, w2 = symbols('u0:3, v0:3, w0:3', real=True)

    u = u0*R2.e_x + u1*R2.e_y
    v = v0*R2.e_x + v1*R2.e_y
    wp = WedgeProduct(R2.dx, R2.dy)
    assert wp(u, v) == u0*v1 - u1*v0

    u = u0*R3_r.e_x + u1*R3_r.e_y + u2*R3_r.e_z
    v = v0*R3_r.e_x + v1*R3_r.e_y + v2*R3_r.e_z
    w = w0*R3_r.e_x + w1*R3_r.e_y + w2*R3_r.e_z
    wp = WedgeProduct(R3_r.dx, R3_r.dy, R3_r.dz)
    assert wp(
        u, v, w) == Matrix(3, 3, [u0, u1, u2, v0, v1, v2, w0, w1, w2]).det()

    a, b, c = symbols('a, b, c', cls=Function)
    a_f = a(R3_r.x, R3_r.y, R3_r.z)
    b_f = b(R3_r.x, R3_r.y, R3_r.z)
    c_f = c(R3_r.x, R3_r.y, R3_r.z)
    theta = a_f*R3_r.dx + b_f*R3_r.dy + c_f*R3_r.dz
    dtheta = Differential(theta)
    da = Differential(a_f)
    db = Differential(b_f)
    dc = Differential(c_f)
    expr = dtheta - WedgeProduct(
        da, R3_r.dx) - WedgeProduct(db, R3_r.dy) - WedgeProduct(dc, R3_r.dz)
    assert expr.rcall(R3_r.e_x, R3_r.e_y) == 0
예제 #18
0
def test_functional_diffgeom_ch3():
    x0, y0 = symbols('x0, y0', real=True)
    x, y, t = symbols('x, y, t', real=True)
    f = Function('f')
    b1 = Function('b1')
    b2 = Function('b2')
    p_r = R2_r.point([x0, y0])

    s_field = f(R2.x, R2.y)
    v_field = b1(R2.x)*R2.e_x + b2(R2.y)*R2.e_y
    assert v_field.rcall(s_field).rcall(p_r).doit() == b1(
        x0)*Derivative(f(x0, y0), x0) + b2(y0)*Derivative(f(x0, y0), y0)

    assert R2.e_x(R2.r**2).rcall(p_r) == 2*x0
    v = R2.e_x + 2*R2.e_y
    s = R2.r**2 + 3*R2.x
    assert v.rcall(s).rcall(p_r).doit() == 2*x0 + 4*y0 + 3

    circ = -R2.y*R2.e_x + R2.x*R2.e_y
    series = intcurve_series(circ, t, R2_r.point([1, 0]), coeffs=True)
    series_x, series_y = zip(*series)
    assert all(
        [term == cos(t).taylor_term(i, t) for i, term in enumerate(series_x)])
    assert all(
        [term == sin(t).taylor_term(i, t) for i, term in enumerate(series_y)])
예제 #19
0
def test_differentiation():
    from sympy.functions.special.tensor_functions import KroneckerDelta
    i, j, k, l = symbols('i j k l', cls=Idx)
    a = symbols('a')
    m, n = symbols("m, n", integer=True, finite=True)
    assert m.is_real
    h, L = symbols('h L', cls=IndexedBase)
    hi, hj = h[i], h[j]

    expr = hi
    assert expr.diff(hj) == KroneckerDelta(i, j)
    assert expr.diff(hi) == KroneckerDelta(i, i)

    expr = S(2) * hi
    assert expr.diff(hj) == S(2) * KroneckerDelta(i, j)
    assert expr.diff(hi) == S(2) * KroneckerDelta(i, i)
    assert expr.diff(a) == S.Zero

    assert Sum(expr, (i, -oo, oo)).diff(hj) == Sum(2*KroneckerDelta(i, j), (i, -oo, oo))
    assert Sum(expr.diff(hj), (i, -oo, oo)) == Sum(2*KroneckerDelta(i, j), (i, -oo, oo))
    assert Sum(expr, (i, -oo, oo)).diff(hj).doit() == 2

    assert Sum(expr, (i, -oo, oo)).diff(hi) == oo
    assert Sum(expr.diff(hi), (i, -oo, oo)) == Sum(2, (i, -oo, oo))
    assert Sum(expr, (i, -oo, oo)).diff(hi).doit() == oo

    expr = a * hj * hj / S(2)
    assert expr.diff(hi) == a * h[j] * KroneckerDelta(i, j)
    assert expr.diff(a) == hj * hj / S(2)
    assert expr.diff(a, 2) == S.Zero

    assert Sum(expr, (i, -oo, oo)).diff(hi) == Sum(a*KroneckerDelta(i, j)*h[j], (i, -oo, oo))
    assert Sum(expr.diff(hi), (i, -oo, oo)) == Sum(a*KroneckerDelta(i, j)*h[j], (i, -oo, oo))
    assert Sum(expr, (i, -oo, oo)).diff(hi).doit() == a*h[j]

    assert Sum(expr, (j, -oo, oo)).diff(hi) == Sum(a*KroneckerDelta(i, j)*h[j], (j, -oo, oo))
    assert Sum(expr.diff(hi), (j, -oo, oo)) == Sum(a*KroneckerDelta(i, j)*h[j], (j, -oo, oo))
    assert Sum(expr, (j, -oo, oo)).diff(hi).doit() == a*h[i]

    expr = a * sin(hj * hj)
    assert expr.diff(hi) == 2*a*cos(hj * hj) * hj * KroneckerDelta(i, j)
    assert expr.diff(hj) == 2*a*cos(hj * hj) * hj

    expr = a * L[i, j] * h[j]
    assert expr.diff(hi) == a*L[i, j]*KroneckerDelta(i, j)
    assert expr.diff(hj) == a*L[i, j]
    assert expr.diff(L[i, j]) == a*h[j]
    assert expr.diff(L[k, l]) == a*KroneckerDelta(i, k)*KroneckerDelta(j, l)*h[j]
    assert expr.diff(L[i, l]) == a*KroneckerDelta(j, l)*h[j]

    assert Sum(expr, (j, -oo, oo)).diff(L[k, l]) == Sum(a * KroneckerDelta(i, k) * KroneckerDelta(j, l) * h[j], (j, -oo, oo))
    assert Sum(expr, (j, -oo, oo)).diff(L[k, l]).doit() == a * KroneckerDelta(i, k) * h[l]

    assert h[m].diff(h[m]) == 1
    assert h[m].diff(h[n]) == KroneckerDelta(m, n)
    assert Sum(a*h[m], (m, -oo, oo)).diff(h[n]) == Sum(a*KroneckerDelta(m, n), (m, -oo, oo))
    assert Sum(a*h[m], (m, -oo, oo)).diff(h[n]).doit() == a
    assert Sum(a*h[m], (n, -oo, oo)).diff(h[n]) == Sum(a*KroneckerDelta(m, n), (n, -oo, oo))
    assert Sum(a*h[m], (m, -oo, oo)).diff(h[m]) == oo*a
예제 #20
0
def test_IndexedBase_subs():
    i, j, k = symbols('i j k', integer=True)
    a, b, c = symbols('a b c')
    A = IndexedBase(a)
    B = IndexedBase(b)
    C = IndexedBase(c)
    assert A[i] == B[i].subs(b, a)
    assert isinstance(C[1].subs(C, {1: 2}), type(A[1]))
예제 #21
0
def test_IndexedBase_sugar():
    i, j = symbols('i j', integer=True)
    a = symbols('a')
    A1 = Indexed(a, i, j)
    A2 = IndexedBase(a)
    assert A1 == A2[i, j]
    assert A1 == A2[(i, j)]
    assert A1 == A2[[i, j]]
    assert A1 == A2[Tuple(i, j)]
예제 #22
0
def test_extract_facts():
    a, b = symbols('a b', cls=Predicate)
    x, y = symbols('x y')
    assert _extract_facts(a(x), x)  == a
    assert _extract_facts(a(x), y)  == None
    assert _extract_facts(~a(x), x) == ~a
    assert _extract_facts(~a(x), y) == None
    assert _extract_facts(a(x) | b(x), x) == a | b
    assert _extract_facts(a(x) | ~b(x), x) == a | ~b
예제 #23
0
def test_user_functions():
    x = symbols('x', integer=False)
    n = symbols('n', integer=True)
    custom_functions = {
        "ceiling": "ceil",
        "Abs": [(lambda x: not x.is_integer, "fabs", 4), (lambda x: x.is_integer, "abs", 4)],
    }
    assert rust_code(ceiling(x), user_functions=custom_functions) == "x.ceil()"
    assert rust_code(Abs(x), user_functions=custom_functions) == "fabs(x)"
    assert rust_code(Abs(n), user_functions=custom_functions) == "abs(n)"
예제 #24
0
def test_eliminate_assumptions():
    a, b = map(Predicate, symbols('ab'))
    x, y = symbols('xy')
    assert eliminate_assume(Assume(x, a))  == a
    assert eliminate_assume(Assume(x, a), symbol=x)  == a
    assert eliminate_assume(Assume(x, a), symbol=y)  == None
    assert eliminate_assume(Assume(x, a, False)) == ~a
    assert eliminate_assume(Assume(x, a), symbol=y) == None
    assert eliminate_assume(Assume(x, a) | Assume(x, b)) == a | b
    assert eliminate_assume(Assume(x, a) | Assume(x, b, False)) == a | ~b
예제 #25
0
def test_Indexed_shape_precedence():
    i, j = symbols('i j', integer=True)
    o, p = symbols('o p', integer=True)
    n, m = symbols('n m', integer=True)
    a = IndexedBase('a', shape=(o, p))
    assert a.shape == Tuple(o, p)
    assert Indexed(a, Idx(i, m), Idx(j, n)).ranges == [Tuple(0, m - 1), Tuple(0, n - 1)]
    assert Indexed(a, Idx(i, m), Idx(j, n)).shape == Tuple(o, p)
    assert Indexed(a, Idx(i, m), Idx(j)).ranges == [Tuple(0, m - 1), Tuple(None, None)]
    assert Indexed(a, Idx(i, m), Idx(j)).shape == Tuple(o, p)
예제 #26
0
def test_IndexedBase_sugar():
    i, j = symbols('i j', integer=True)
    a = symbols('a')
    A1 = Indexed(a, i, j)
    A2 = IndexedBase(a)
    assert A1 == A2[i, j]
    assert A1 == A2[(i, j)]
    assert A1 == A2[[i, j]]
    assert A1 == A2[Tuple(i, j)]
    assert all(a.is_Integer for a in A2[1, 0].args[1:])
예제 #27
0
파일: test_sho.py 프로젝트: 101man/sympy
def test_sho_R_nl():
    omega, r = symbols('omega r')
    l = symbols('l', integer=True)
    u = Function('u')

    # check that it obeys the Schrodinger equation
    for n in range(5):
        schreq =  ( -diff(u(r), r, 2)/2 + ((l*(l+1))/(2*r**2)
                    + omega**2*r**2/2 - E_nl(n, l, omega))*u(r) )
        result = schreq.subs(u(r), r*R_nl(n, l, omega/2, r))
        assert simplify(result.doit()) == 0
예제 #28
0
def test_jscode_inline_function():
    x = symbols("x")
    g = implemented_function("g", Lambda(x, 2 * x))
    assert jscode(g(x)) == "2*x"
    g = implemented_function("g", Lambda(x, 2 * x / Catalan))
    assert jscode(g(x)) == "var Catalan = %s;\n2*x/Catalan" % Catalan.n()
    A = IndexedBase("A")
    i = Idx("i", symbols("n", integer=True))
    g = implemented_function("g", Lambda(x, x * (1 + x) * (2 + x)))
    assert jscode(g(A[i]), assign_to=A[i]) == (
        "for (var i=0; i<n; i++){\n" "   A[i] = A[i]*(1 + A[i])*(2 + A[i]);\n" "}"
    )
예제 #29
0
def test_check_case_false_positive():
    # The upper case/lower case exception should not be triggered by SymPy
    # objects that differ only because of assumptions.  (It may be useful to
    # have a check for that as well, but here we only want to test against
    # false positives with respect to case checking.)
    x1 = symbols('x')
    x2 = symbols('x', my_assumption=True)
    try:
        codegen(('test', x1*x2), 'f95', 'prefix')
    except CodeGenError as e:
        if e.args[0].startswith("Fortran ignores case."):
            raise AssertionError("This exception should not be raised!")
예제 #30
0
def test_check_case_false_positive():
    # The upper case/lower case exception should not be triggered by Sympy
    # objects that differ only because of assumptions.  (It may be useful to
    # have a check for that as well, but here we only want to test against
    # false positives with respect to case checking.)
    x1 = symbols("x")
    x2 = symbols("x", my_assumption=True)
    try:
        codegen(("test", x1 * x2), "f95", "prefix")
    except CodeGenError, e:
        if e.args[0][0:21] == "Fortran ignores case.":
            raise AssertionError("This exception should not be raised!")
def test_matmul_args_cnc_symbols():
    # Not currently supported
    a, b = symbols('a b', commutative=False)
    assert MatMul(n, a, b, A, A.T).args_cnc() == [[n], [a, b, A, A.T]]
    assert MatMul(n, a, A, b, A.T).args_cnc() == [[n], [a, A, b, A.T]]
예제 #32
0
    besselj,
    bessely,
    besseli,
    besselk,
    hankel1,
    hankel2,
    airyai,
    airybi,
    airyaiprime,
    airybiprime,
)
from sympy.testing.pytest import XFAIL

from sympy import julia_code

x, y, z = symbols("x,y,z")


def test_Integer():
    assert julia_code(Integer(67)) == "67"
    assert julia_code(Integer(-1)) == "-1"


def test_Rational():
    assert julia_code(Rational(3, 7)) == "3/7"
    assert julia_code(Rational(18, 9)) == "2"
    assert julia_code(Rational(3, -7)) == "-3/7"
    assert julia_code(Rational(-3, -7)) == "3/7"
    assert julia_code(x + Rational(3, 7)) == "x + 3/7"
    assert julia_code(Rational(3, 7) * x) == "3*x/7"
예제 #33
0
"""Tests for Dixon's and Macaulay's classes. """

from sympy.matrices.dense import Matrix
from sympy.polys.polytools import factor
from sympy.core import symbols
from sympy.tensor.indexed import IndexedBase

from sympy.polys.multivariate_resultants import (DixonResultant,
                                                 MacaulayResultant)

c, d = symbols("a, b")
x, y = symbols("x, y")

p = c * x + y
q = x + d * y

dixon = DixonResultant(polynomials=[p, q], variables=[x, y])
macaulay = MacaulayResultant(polynomials=[p, q], variables=[x, y])


def test_dixon_resultant_init():
    """Test init method of DixonResultant."""
    a = IndexedBase("alpha")

    assert dixon.polynomials == [p, q]
    assert dixon.variables == [x, y]
    assert dixon.n == 2
    assert dixon.m == 2
    assert dixon.dummy_variables == [a[0], a[1]]

예제 #34
0
def test_intrinsic_math_codegen():
    # not included: log10
    from sympy import (acos, asin, atan, ceiling, cos, cosh, floor, log, ln,
            sin, sinh, sqrt, tan, tanh, N, Abs)
    x = symbols('x')
    name_expr = [
            ("test_abs", Abs(x)),
            ("test_acos", acos(x)),
            ("test_asin", asin(x)),
            ("test_atan", atan(x)),
            # ("test_ceil", ceiling(x)),
            ("test_cos", cos(x)),
            ("test_cosh", cosh(x)),
            # ("test_floor", floor(x)),
            ("test_log", log(x)),
            ("test_ln", ln(x)),
            ("test_sin", sin(x)),
            ("test_sinh", sinh(x)),
            ("test_sqrt", sqrt(x)),
            ("test_tan", tan(x)),
            ("test_tanh", tanh(x)),
            ]
    result = codegen(name_expr, "F95", "file", header=False, empty=False)
    assert result[0][0] == "file.f90"
    expected = (
            'REAL*8 function test_abs(x)\n'
            'implicit none\n'
            'REAL*8, intent(in) :: x\n'
            'test_abs = Abs(x)\n'
            'end function\n'
            'REAL*8 function test_acos(x)\n'
            'implicit none\n'
            'REAL*8, intent(in) :: x\n'
            'test_acos = acos(x)\n'
            'end function\n'
            'REAL*8 function test_asin(x)\n'
            'implicit none\n'
            'REAL*8, intent(in) :: x\n'
            'test_asin = asin(x)\n'
            'end function\n'
            'REAL*8 function test_atan(x)\n'
            'implicit none\n'
            'REAL*8, intent(in) :: x\n'
            'test_atan = atan(x)\n'
            'end function\n'
            'REAL*8 function test_cos(x)\n'
            'implicit none\n'
            'REAL*8, intent(in) :: x\n'
            'test_cos = cos(x)\n'
            'end function\n'
            'REAL*8 function test_cosh(x)\n'
            'implicit none\n'
            'REAL*8, intent(in) :: x\n'
            'test_cosh = cosh(x)\n'
            'end function\n'
            'REAL*8 function test_log(x)\n'
            'implicit none\n'
            'REAL*8, intent(in) :: x\n'
            'test_log = log(x)\n'
            'end function\n'
            'REAL*8 function test_ln(x)\n'
            'implicit none\n'
            'REAL*8, intent(in) :: x\n'
            'test_ln = log(x)\n'
            'end function\n'
            'REAL*8 function test_sin(x)\n'
            'implicit none\n'
            'REAL*8, intent(in) :: x\n'
            'test_sin = sin(x)\n'
            'end function\n'
            'REAL*8 function test_sinh(x)\n'
            'implicit none\n'
            'REAL*8, intent(in) :: x\n'
            'test_sinh = sinh(x)\n'
            'end function\n'
            'REAL*8 function test_sqrt(x)\n'
            'implicit none\n'
            'REAL*8, intent(in) :: x\n'
            'test_sqrt = sqrt(x)\n'
            'end function\n'
            'REAL*8 function test_tan(x)\n'
            'implicit none\n'
            'REAL*8, intent(in) :: x\n'
            'test_tan = tan(x)\n'
            'end function\n'
            'REAL*8 function test_tanh(x)\n'
            'implicit none\n'
            'REAL*8, intent(in) :: x\n'
            'test_tanh = tanh(x)\n'
            'end function\n'
        )
    assert result[0][1] == expected

    assert result[1][0] == "file.h"
    expected =  (
            'interface\n'
            'REAL*8 function test_abs(x)\n'
            'implicit none\n'
            'REAL*8, intent(in) :: x\n'
            'end function\n'
            'end interface\n'
            'interface\n'
            'REAL*8 function test_acos(x)\n'
            'implicit none\n'
            'REAL*8, intent(in) :: x\n'
            'end function\n'
            'end interface\n'
            'interface\n'
            'REAL*8 function test_asin(x)\n'
            'implicit none\n'
            'REAL*8, intent(in) :: x\n'
            'end function\n'
            'end interface\n'
            'interface\n'
            'REAL*8 function test_atan(x)\n'
            'implicit none\n'
            'REAL*8, intent(in) :: x\n'
            'end function\n'
            'end interface\n'
            'interface\n'
            'REAL*8 function test_cos(x)\n'
            'implicit none\n'
            'REAL*8, intent(in) :: x\n'
            'end function\n'
            'end interface\n'
            'interface\n'
            'REAL*8 function test_cosh(x)\n'
            'implicit none\n'
            'REAL*8, intent(in) :: x\n'
            'end function\n'
            'end interface\n'
            'interface\n'
            'REAL*8 function test_log(x)\n'
            'implicit none\n'
            'REAL*8, intent(in) :: x\n'
            'end function\n'
            'end interface\n'
            'interface\n'
            'REAL*8 function test_ln(x)\n'
            'implicit none\n'
            'REAL*8, intent(in) :: x\n'
            'end function\n'
            'end interface\n'
            'interface\n'
            'REAL*8 function test_sin(x)\n'
            'implicit none\n'
            'REAL*8, intent(in) :: x\n'
            'end function\n'
            'end interface\n'
            'interface\n'
            'REAL*8 function test_sinh(x)\n'
            'implicit none\n'
            'REAL*8, intent(in) :: x\n'
            'end function\n'
            'end interface\n'
            'interface\n'
            'REAL*8 function test_sqrt(x)\n'
            'implicit none\n'
            'REAL*8, intent(in) :: x\n'
            'end function\n'
            'end interface\n'
            'interface\n'
            'REAL*8 function test_tan(x)\n'
            'implicit none\n'
            'REAL*8, intent(in) :: x\n'
            'end function\n'
            'end interface\n'
            'interface\n'
            'REAL*8 function test_tanh(x)\n'
            'implicit none\n'
            'REAL*8, intent(in) :: x\n'
            'end function\n'
            'end interface\n'
    )
    assert result[1][1] == expected
예제 #35
0
from sympy.core import (pi, oo, symbols, Rational, Integer, Float, GoldenRatio,
                        EulerGamma, Catalan, Lambda)
from sympy.functions import Piecewise, sin, cos, Abs, exp, ceiling, sqrt, gamma
from sympy.sets.fancysets import Range
from sympy.utilities.pytest import raises
from sympy.utilities.lambdify import implemented_function
from sympy.tensor import IndexedBase, Idx

from pyccel.types.ast import (Assign, AugAssign, For, InArgument, Result,
                              FunctionDef, Return, Import, Declare, Variable)
from pyccel.printers import ccode, CCodePrinter

x, y, z = symbols('x, y, z')
a, b, c = symbols('a, b, c')


def test_printmethod():
    class fabs(Abs):
        def _ccode(self, printer):
            return "fabs(%s)" % printer._print(self.args[0])

    assert ccode(fabs(x)) == "fabs(x)"


def test_ccode_sqrt():
    assert ccode(sqrt(x)) == "sqrt(x)"
    assert ccode(x**0.5) == "sqrt(x)"
    assert ccode(sqrt(Float(10))) == "3.16227766016838"


def test_ccode_Pow():
예제 #36
0
import numpy
import math

#init_printing()

print numpy.arccos(-1)
print math.acos(-1)
print acos(-1)

print acos(0)
print acos(0)

print acos(S.One/2)

x,y,z = symbols('x,y,z')
alpha,beta,gamma = symbols('alpha,beta,gamma')
print x+1
print log(alpha ** beta) + gamma
print sin(x)**2 + cos(x)**2
print simplify(sin(x)**2 + cos(x)**2)

mu,sigma = symbols('mu,sigma')
bell = exp(-(x-mu)**2 / 2*sigma**2)
print bell.diff(x)
print bell.diff(sigma)
print bell.diff(x).diff(x).diff(x)
print simplify(bell.diff(x).diff(x).diff(x))


print (x**2).diff(x)
예제 #37
0
def test_check_case():
    x, X = symbols('xX')
    raises(CodeGenError, "codegen(('test', x*X), 'f95', 'prefix')")
예제 #38
0
#import pythonista
from sympy.matrices.expressions.blockmatrix import (
    block_collapse, bc_matmul, bc_block_plus_ident, BlockDiagMatrix,
    BlockMatrix, bc_dist, bc_matadd, bc_transpose, blockcut, reblock_2x2,
    deblock)
from sympy.matrices.expressions import (MatrixSymbol, Identity, MatMul,
                                        Inverse, trace, Transpose, det)
from sympy.matrices import Matrix, ImmutableMatrix
from sympy.core import Tuple, symbols, Expr
from sympy.functions import transpose

i, j, k, l, m, n, p = symbols('i:n, p', integer=True)
A = MatrixSymbol('A', n, n)
B = MatrixSymbol('B', n, n)
C = MatrixSymbol('C', n, n)
D = MatrixSymbol('D', n, n)
G = MatrixSymbol('G', n, n)
H = MatrixSymbol('H', n, n)
b1 = BlockMatrix([[G, H]])
b2 = BlockMatrix([[G], [H]])


def test_bc_matmul():
    assert bc_matmul(H * b1 * b2 * G) == BlockMatrix([[
        (H * G * G + H * H * H) * G
    ]])


def test_bc_matadd():
    assert bc_matadd(BlockMatrix([[G, H]]) + BlockMatrix([[H, H]])) == \
            BlockMatrix([[G+H, H+H]])
예제 #39
0
def test_ufuncify():
    x, y = symbols('x y')
    f = ufuncify((x, y), x + y, backend='dummy')
    assert f() == "f(_x[_i], y)"
예제 #40
0
from sympy.core import Lambda, S, symbols
from sympy.concrete import Sum
from sympy.functions import adjoint, conjugate, transpose
from sympy.matrices import eye, Matrix, ShapeError, ImmutableMatrix
from sympy.matrices.expressions import (Adjoint, Identity, FunctionMatrix,
                                        MatrixExpr, MatrixSymbol, Trace,
                                        ZeroMatrix, trace, MatPow, MatAdd,
                                        MatMul)
from sympy.utilities.pytest import raises, XFAIL

n = symbols('n', integer=True)
A = MatrixSymbol('A', n, n)
B = MatrixSymbol('B', n, n)
C = MatrixSymbol('C', 3, 4)


def test_Trace():
    assert isinstance(Trace(A), Trace)
    assert not isinstance(Trace(A), MatrixExpr)
    raises(ShapeError, lambda: Trace(C))
    assert trace(eye(3)) == 3
    assert trace(Matrix(3, 3, [1, 2, 3, 4, 5, 6, 7, 8, 9])) == 15

    assert adjoint(Trace(A)) == trace(Adjoint(A))
    assert conjugate(Trace(A)) == trace(Adjoint(A))
    assert transpose(Trace(A)) == Trace(A)

    A / Trace(A)  # Make sure this is possible

    # Some easy simplifications
    assert trace(Identity(5)) == 5
예제 #41
0
def test_trivial_indices():
    x, y = symbols("x y")
    assert get_indices(x) == (set([]), {})
    assert get_indices(x * y) == (set([]), {})
    assert get_indices(x + y) == (set([]), {})
    assert get_indices(x**y) == (set([]), {})
예제 #42
0
from sympy.codegen import Assignment
from sympy.codegen.ast import none
from sympy.codegen.matrix_nodes import MatrixSolve
from sympy.core import Expr, Mod, symbols, Eq, Le, Gt, zoo, oo, Rational
from sympy.core.numbers import pi
from sympy.core.singleton import S
from sympy.functions import acos, Piecewise, sign, sqrt
from sympy.logic import And, Or
from sympy.matrices import SparseMatrix, MatrixSymbol, Identity
from sympy.printing.pycode import (MpmathPrinter, NumPyPrinter,
                                   PythonCodePrinter, pycode, SciPyPrinter,
                                   SymPyPrinter)
from sympy.testing.pytest import raises
from sympy.tensor import IndexedBase

x, y, z = symbols('x y z')
p = IndexedBase("p")


def test_PythonCodePrinter():
    prntr = PythonCodePrinter()

    assert not prntr.module_imports

    assert prntr.doprint(x**y) == 'x**y'
    assert prntr.doprint(Mod(x, 2)) == 'x % 2'
    assert prntr.doprint(And(x, y)) == 'x and y'
    assert prntr.doprint(Or(x, y)) == 'x or y'
    assert not prntr.module_imports

    assert prntr.doprint(pi) == 'math.pi'
예제 #43
0
from sympy.core import symbols, S
from sympy.functions import adjoint, conjugate, transpose
from sympy.matrices.expressions import MatrixSymbol, Adjoint, Trace, Transpose
from sympy.matrices import eye, Matrix

n, m, l, k, p = symbols('n m l k p', integer=True)
A = MatrixSymbol('A', n, m)
B = MatrixSymbol('B', m, l)
C = MatrixSymbol('C', n, n)


def test_adjoint():
    Sq = MatrixSymbol('Sq', n, n)

    assert Adjoint(A).shape == (m, n)
    assert Adjoint(A * B).shape == (l, n)
    assert adjoint(Adjoint(A)) == A
    assert isinstance(Adjoint(Adjoint(A)), Adjoint)

    assert conjugate(Adjoint(A)) == Transpose(A)
    assert transpose(Adjoint(A)) == Adjoint(Transpose(A))

    assert Adjoint(eye(3)).doit() == eye(3)

    assert Adjoint(S(5)).doit() == S(5)

    assert Adjoint(Matrix([[1, 2], [3, 4]])).doit() == Matrix([[1, 3], [2, 4]])

    assert adjoint(Trace(Sq)) == conjugate(Trace(Sq))
    assert Trace(adjoint(Sq)) == conjugate(Trace(Sq))
예제 #44
0
def test_matmul_args_cnc():
    a, b = symbols('a b', commutative=False)
    assert MatMul(n, a, b, A, A.T).args_cnc() == ([n], [a, b, A, A.T])
    assert MatMul(A, A.T).args_cnc() == ([1], [A, A.T])
예제 #45
0
def o_e2():
    x = symbols('x')
    return (S(1)/2*x ** 2+2*x+S(3)/4) ** (S(3)/2)
예제 #46
0
def _trigpats():
    global _trigpat
    a, b, c = symbols('a b c', cls=Wild)
    d = Wild('d', commutative=False)

    # for the simplifications like sinh/cosh -> tanh:
    # DO NOT REORDER THE FIRST 14 since these are assumed to be in this
    # order in _match_div_rewrite.
    matchers_division = (
        (a*sin(b)**c/cos(b)**c, a*tan(b)**c, sin(b), cos(b)),
        (a*tan(b)**c*cos(b)**c, a*sin(b)**c, sin(b), cos(b)),
        (a*cot(b)**c*sin(b)**c, a*cos(b)**c, sin(b), cos(b)),
        (a*tan(b)**c/sin(b)**c, a/cos(b)**c, sin(b), cos(b)),
        (a*cot(b)**c/cos(b)**c, a/sin(b)**c, sin(b), cos(b)),
        (a*cot(b)**c*tan(b)**c, a, sin(b), cos(b)),
        (a*(cos(b) + 1)**c*(cos(b) - 1)**c,
            a*(-sin(b)**2)**c, cos(b) + 1, cos(b) - 1),
        (a*(sin(b) + 1)**c*(sin(b) - 1)**c,
            a*(-cos(b)**2)**c, sin(b) + 1, sin(b) - 1),

        (a*sinh(b)**c/cosh(b)**c, a*tanh(b)**c, S.One, S.One),
        (a*tanh(b)**c*cosh(b)**c, a*sinh(b)**c, S.One, S.One),
        (a*coth(b)**c*sinh(b)**c, a*cosh(b)**c, S.One, S.One),
        (a*tanh(b)**c/sinh(b)**c, a/cosh(b)**c, S.One, S.One),
        (a*coth(b)**c/cosh(b)**c, a/sinh(b)**c, S.One, S.One),
        (a*coth(b)**c*tanh(b)**c, a, S.One, S.One),

        (c*(tanh(a) + tanh(b))/(1 + tanh(a)*tanh(b)),
            tanh(a + b)*c, S.One, S.One),
    )

    matchers_add = (
        (c*sin(a)*cos(b) + c*cos(a)*sin(b) + d, sin(a + b)*c + d),
        (c*cos(a)*cos(b) - c*sin(a)*sin(b) + d, cos(a + b)*c + d),
        (c*sin(a)*cos(b) - c*cos(a)*sin(b) + d, sin(a - b)*c + d),
        (c*cos(a)*cos(b) + c*sin(a)*sin(b) + d, cos(a - b)*c + d),
        (c*sinh(a)*cosh(b) + c*sinh(b)*cosh(a) + d, sinh(a + b)*c + d),
        (c*cosh(a)*cosh(b) + c*sinh(a)*sinh(b) + d, cosh(a + b)*c + d),
    )

    # for cos(x)**2 + sin(x)**2 -> 1
    matchers_identity = (
        (a*sin(b)**2, a - a*cos(b)**2),
        (a*tan(b)**2, a*(1/cos(b))**2 - a),
        (a*cot(b)**2, a*(1/sin(b))**2 - a),
        (a*sin(b + c), a*(sin(b)*cos(c) + sin(c)*cos(b))),
        (a*cos(b + c), a*(cos(b)*cos(c) - sin(b)*sin(c))),
        (a*tan(b + c), a*((tan(b) + tan(c))/(1 - tan(b)*tan(c)))),

        (a*sinh(b)**2, a*cosh(b)**2 - a),
        (a*tanh(b)**2, a - a*(1/cosh(b))**2),
        (a*coth(b)**2, a + a*(1/sinh(b))**2),
        (a*sinh(b + c), a*(sinh(b)*cosh(c) + sinh(c)*cosh(b))),
        (a*cosh(b + c), a*(cosh(b)*cosh(c) + sinh(b)*sinh(c))),
        (a*tanh(b + c), a*((tanh(b) + tanh(c))/(1 + tanh(b)*tanh(c)))),

    )

    # Reduce any lingering artifacts, such as sin(x)**2 changing
    # to 1-cos(x)**2 when sin(x)**2 was "simpler"
    artifacts = (
        (a - a*cos(b)**2 + c, a*sin(b)**2 + c, cos),
        (a - a*(1/cos(b))**2 + c, -a*tan(b)**2 + c, cos),
        (a - a*(1/sin(b))**2 + c, -a*cot(b)**2 + c, sin),

        (a - a*cosh(b)**2 + c, -a*sinh(b)**2 + c, cosh),
        (a - a*(1/cosh(b))**2 + c, a*tanh(b)**2 + c, cosh),
        (a + a*(1/sinh(b))**2 + c, a*coth(b)**2 + c, sinh),

        # same as above but with noncommutative prefactor
        (a*d - a*d*cos(b)**2 + c, a*d*sin(b)**2 + c, cos),
        (a*d - a*d*(1/cos(b))**2 + c, -a*d*tan(b)**2 + c, cos),
        (a*d - a*d*(1/sin(b))**2 + c, -a*d*cot(b)**2 + c, sin),

        (a*d - a*d*cosh(b)**2 + c, -a*d*sinh(b)**2 + c, cosh),
        (a*d - a*d*(1/cosh(b))**2 + c, a*d*tanh(b)**2 + c, cosh),
        (a*d + a*d*(1/sinh(b))**2 + c, a*d*coth(b)**2 + c, sinh),
    )

    _trigpat = (a, b, c, d, matchers_division, matchers_add,
        matchers_identity, artifacts)
    return _trigpat
예제 #47
0
def o_e1():
    x = symbols('x')
    return x**2 + 2*x + S(1)/2
예제 #48
0
    def analyse_gens(gens, hints):
        """
        Analyse the generators ``gens``, using the hints ``hints``.

        The meaning of ``hints`` is described in the main docstring.
        Return a new list of generators, and also the ideal we should
        work with.
        """
        # First parse the hints
        n, funcs, iterables, extragens = parse_hints(hints)
        debug('n=%s' % n, 'funcs:', funcs, 'iterables:',
              iterables, 'extragens:', extragens)

        # We just add the extragens to gens and analyse them as before
        gens = list(gens)
        gens.extend(extragens)

        # remove duplicates
        funcs = list(set(funcs))
        iterables = list(set(iterables))
        gens = list(set(gens))

        # all the functions we can do anything with
        allfuncs = {sin, cos, tan, sinh, cosh, tanh}
        # sin(3*x) -> ((3, x), sin)
        trigterms = [(g.args[0].as_coeff_mul(), g.func) for g in gens
                     if g.func in allfuncs]
        # Our list of new generators - start with anything that we cannot
        # work with (i.e. is not a trigonometric term)
        freegens = [g for g in gens if g.func not in allfuncs]
        newgens = []
        trigdict = {}
        for (coeff, var), fn in trigterms:
            trigdict.setdefault(var, []).append((coeff, fn))
        res = [] # the ideal

        for key, val in trigdict.items():
            # We have now assembeled a dictionary. Its keys are common
            # arguments in trigonometric expressions, and values are lists of
            # pairs (fn, coeff). x0, (fn, coeff) in trigdict means that we
            # need to deal with fn(coeff*x0). We take the rational gcd of the
            # coeffs, call it ``gcd``. We then use x = x0/gcd as "base symbol",
            # all other arguments are integral multiples thereof.
            # We will build an ideal which works with sin(x), cos(x).
            # If hint tan is provided, also work with tan(x). Moreover, if
            # n > 1, also work with sin(k*x) for k <= n, and similarly for cos
            # (and tan if the hint is provided). Finally, any generators which
            # the ideal does not work with but we need to accommodate (either
            # because it was in expr or because it was provided as a hint)
            # we also build into the ideal.
            # This selection process is expressed in the list ``terms``.
            # build_ideal then generates the actual relations in our ideal,
            # from this list.
            fns = [x[1] for x in val]
            val = [x[0] for x in val]
            gcd = reduce(igcd, val)
            terms = [(fn, v/gcd) for (fn, v) in zip(fns, val)]
            fs = set(funcs + fns)
            for c, s, t in ([cos, sin, tan], [cosh, sinh, tanh]):
                if any(x in fs for x in (c, s, t)):
                    fs.add(c)
                    fs.add(s)
            for fn in fs:
                for k in range(1, n + 1):
                    terms.append((fn, k))
            extra = []
            for fn, v in terms:
                if fn == tan:
                    extra.append((sin, v))
                    extra.append((cos, v))
                if fn in [sin, cos] and tan in fs:
                    extra.append((tan, v))
                if fn == tanh:
                    extra.append((sinh, v))
                    extra.append((cosh, v))
                if fn in [sinh, cosh] and tanh in fs:
                    extra.append((tanh, v))
            terms.extend(extra)
            x = gcd*Mul(*key)
            r = build_ideal(x, terms)
            res.extend(r)
            newgens.extend(set(fn(v*x) for fn, v in terms))

        # Add generators for compound expressions from iterables
        for fn, args in iterables:
            if fn == tan:
                # Tan expressions are recovered from sin and cos.
                iterables.extend([(sin, args), (cos, args)])
            elif fn == tanh:
                # Tanh expressions are recovered from sihn and cosh.
                iterables.extend([(sinh, args), (cosh, args)])
            else:
                dummys = symbols('d:%i' % len(args), cls=Dummy)
                expr = fn( Add(*dummys)).expand(trig=True).subs(list(zip(dummys, args)))
                res.append(fn(Add(*args)) - expr)

        if myI in gens:
            res.append(myI**2 + 1)
            freegens.remove(myI)
            newgens.append(myI)

        return res, freegens, newgens
예제 #49
0
def test_binary_function():
    x, y = symbols('x y')
    f = binary_function('f', x + y, backend='dummy')
    assert f._imp_() == str(x + y)
예제 #50
0
def test_pycode_reserved_words():
    s1, s2 = symbols('if else')
    raises(ValueError, lambda: pycode(s1 + s2, error_on_reserved=True))
    py_str = pycode(s1 + s2)
    assert py_str in ('else_ + if_', 'if_ + else_')
예제 #51
0
def gosper_term(f, n):
    """
    Compute Gosper's hypergeometric term for ``f``.

    Suppose ``f`` is a hypergeometric term such that::

    .. math::

        s_n = \sum_{k=0}^{n-1} f_k

    and `f_k` doesn't depend on `n`. Returns a hypergeometric
    term `g_n` such that `g_{n+1} - g_n = f_n`.

    **Examples**

    >>> from sympy.concrete.gosper import gosper_term
    >>> from sympy.functions import factorial
    >>> from sympy.abc import n

    >>> gosper_term((4*n + 1)*factorial(n)/factorial(2*n + 1), n)
    (-n - 1/2)/(n + 1/4)

    """
    r = hypersimp(f, n)

    if r is None:
        return None  # 'f' is *not* a hypergeometric term

    p, q = r.as_numer_denom()

    A, B, C = gosper_normal(p, q, n)
    B = B.shift(-1)

    N = S(A.degree())
    M = S(B.degree())
    K = S(C.degree())

    if (N != M) or (A.LC() != B.LC()):
        D = set([K - max(N, M)])
    elif not N:
        D = set([K - N + 1, S(0)])
    else:
        D = set([K - N + 1, (B.nth(N - 1) - A.nth(N - 1)) / A.LC()])

    for d in set(D):
        if not d.is_Integer or d < 0:
            D.remove(d)

    if not D:
        return None  # 'f(n)' is *not* Gosper-summable

    d = max(D)

    coeffs = symbols('c:%s' % (d + 1), cls=Dummy)
    domain = A.get_domain().inject(*coeffs)

    x = Poly(coeffs, n, domain=domain)
    H = A * x.shift(1) - B * x - C

    solution = solve(H.coeffs(), coeffs)

    if solution is None:
        return None  # 'f(n)' is *not* Gosper-summable

    x = x.as_expr().subs(solution)

    for coeff in coeffs:
        if coeff not in solution:
            x = x.subs(coeff, 0)

    if x is S.Zero:
        return None  # 'f(n)' is *not* Gosper-summable
    else:
        return B.as_expr() * x / C.as_expr()
예제 #52
0
from sympy.core import I, symbols, Basic
from sympy.functions import adjoint, transpose
from sympy.matrices import (Identity, Inverse, Matrix, MatrixSymbol,
                            ZeroMatrix, eye, ImmutableMatrix)
from sympy.matrices.expressions import Adjoint, Transpose, det, MatPow
from sympy.matrices.expressions.matmul import (factor_in_front, remove_ids,
                                               MatMul, xxinv, any_zeros,
                                               unpack, only_squares)
from sympy.strategies import null_safe
from sympy import refine, Q

n, m, l, k = symbols('n m l k', integer=True)
A = MatrixSymbol('A', n, m)
B = MatrixSymbol('B', m, l)
C = MatrixSymbol('C', n, n)
D = MatrixSymbol('D', n, n)
E = MatrixSymbol('E', m, n)


def test_adjoint():
    assert adjoint(A * B) == Adjoint(B) * Adjoint(A)
    assert adjoint(2 * A * B) == 2 * Adjoint(B) * Adjoint(A)
    assert adjoint(2 * I * C) == -2 * I * Adjoint(C)

    M = Matrix(2, 2, [1, 2 + I, 3, 4])
    MA = Matrix(2, 2, [1, 3, 2 - I, 4])
    assert adjoint(M) == MA
    assert adjoint(2 * M) == 2 * MA
    assert adjoint(MatMul(2, M)) == MatMul(2, MA).doit()

예제 #53
0
from sympy.core import symbols, S
from sympy.matrices.expressions import MatrixSymbol, Inverse, MatPow
from sympy.matrices import eye, Identity, ShapeError
from sympy.utilities.pytest import raises
from sympy import refine, Q

n, m, l = symbols('n m l', integer=True)
A = MatrixSymbol('A', n, m)
B = MatrixSymbol('B', m, l)
C = MatrixSymbol('C', n, n)
D = MatrixSymbol('D', n, n)
E = MatrixSymbol('E', m, n)


def test_inverse():
    raises(ShapeError, lambda: Inverse(A))
    raises(ShapeError, lambda: Inverse(A * B))

    assert Inverse(C).args == (C, S.NegativeOne)
    assert Inverse(C).shape == (n, n)
    assert Inverse(A * E).shape == (n, n)
    assert Inverse(E * A).shape == (m, m)
    assert Inverse(C).inverse() == C
    assert isinstance(Inverse(Inverse(C)), Inverse)

    assert Inverse(*Inverse(E * A).args) == Inverse(E * A)

    assert C.inverse().inverse() == C

    assert C.inverse() * C == Identity(C.rows)
def test_point():
    x, y = symbols('x, y')
    p = R2_r.point([x, y])
    #TODO assert p.free_symbols() == set([x, y])
    assert p.coords(R2_r) == p.coords() == Matrix([x, y])
    assert p.coords(R2_p) == Matrix([sqrt(x**2 + y**2), atan2(y, x)])
예제 #55
0
from io import StringIO

from sympy.core import S, symbols, Eq, pi, Catalan, EulerGamma, Function
from sympy.core.relational import Equality
from sympy.functions.elementary.piecewise import Piecewise
from sympy.matrices import Matrix, MatrixSymbol
from sympy.utilities.codegen import JuliaCodeGen, codegen, make_routine
from sympy.testing.pytest import XFAIL
import sympy


x, y, z = symbols('x,y,z')


def test_empty_jl_code():
    code_gen = JuliaCodeGen()
    output = StringIO()
    code_gen.dump_jl([], output, "file", header=False, empty=False)
    source = output.getvalue()
    assert source == ""


def test_jl_simple_code():
    name_expr = ("test", (x + y)*z)
    result, = codegen(name_expr, "Julia", header=False, empty=False)
    assert result[0] == "test.jl"
    source = result[1]
    expected = (
        "function test(x, y, z)\n"
        "    out1 = z.*(x + y)\n"
        "    return out1\n"
예제 #56
0
def test_cyclic_convolution():
    # fft
    a = [1, S(5)/3, sqrt(3), S(7)/5]
    b = [9, 5, 5, 4, 3, 2]

    assert convolution([1, 2, 3], [4, 5, 6], cycle=0) == \
            convolution([1, 2, 3], [4, 5, 6], cycle=5) == \
                convolution([1, 2, 3], [4, 5, 6])

    assert convolution([1, 2, 3], [4, 5, 6], cycle=3) == [31, 31, 28]

    a = [S(1)/3, S(7)/3, S(5)/9, S(2)/7, S(5)/8]
    b = [S(3)/5, S(4)/7, S(7)/8, S(8)/9]

    assert convolution(a, b, cycle=0) == \
            convolution(a, b, cycle=len(a) + len(b) - 1)

    assert convolution(a, b, cycle=4) == [S(87277)/26460, S(30521)/11340,
                            S(11125)/4032, S(3653)/1080]

    assert convolution(a, b, cycle=6) == [S(20177)/20160, S(676)/315, S(47)/24,
                            S(3053)/1080, S(16397)/5292, S(2497)/2268]

    assert convolution(a, b, cycle=9) == \
                convolution(a, b, cycle=0) + [S.Zero]

    # ntt
    a = [2313, 5323532, S(3232), 42142, 42242421]
    b = [S(33456), 56757, 45754, 432423]

    assert convolution(a, b, prime=19*2**10 + 1, cycle=0) == \
            convolution(a, b, prime=19*2**10 + 1, cycle=8) == \
                convolution(a, b, prime=19*2**10 + 1)

    assert convolution(a, b, prime=19*2**10 + 1, cycle=5) == [96, 17146, 2664,
                                                                    15534, 3517]

    assert convolution(a, b, prime=19*2**10 + 1, cycle=7) == [4643, 3458, 1260,
                                                        15534, 3517, 16314, 13688]

    assert convolution(a, b, prime=19*2**10 + 1, cycle=9) == \
            convolution(a, b, prime=19*2**10 + 1) + [0]

    # fwht
    u, v, w, x, y = symbols('u v w x y')
    p, q, r, s, t = symbols('p q r s t')
    c = [u, v, w, x, y]
    d = [p, q, r, s, t]

    assert convolution(a, b, dyadic=True, cycle=3) == \
                        [2499522285783, 19861417974796, 4702176579021]

    assert convolution(a, b, dyadic=True, cycle=5) == [2718149225143,
            2114320852171, 20571217906407, 246166418903, 1413262436976]

    assert convolution(c, d, dyadic=True, cycle=4) == \
            [p*u + p*y + q*v + r*w + s*x + t*u + t*y,
             p*v + q*u + q*y + r*x + s*w + t*v,
             p*w + q*x + r*u + r*y + s*v + t*w,
             p*x + q*w + r*v + s*u + s*y + t*x]

    assert convolution(c, d, dyadic=True, cycle=6) == \
            [p*u + q*v + r*w + r*y + s*x + t*w + t*y,
             p*v + q*u + r*x + s*w + s*y + t*x,
             p*w + q*x + r*u + s*v,
             p*x + q*w + r*v + s*u,
             p*y + t*u,
             q*y + t*v]

    # subset
    assert convolution(a, b, subset=True, cycle=7) == [18266671799811,
                    178235365533, 213958794, 246166418903, 1413262436976,
                    2397553088697, 1932759730434]

    assert convolution(a[1:], b, subset=True, cycle=4) == \
            [178104086592, 302255835516, 244982785880, 3717819845434]

    assert convolution(a, b[:-1], subset=True, cycle=6) == [1932837114162,
            178235365533, 213958794, 245166224504, 1413262436976, 2397553088697]

    assert convolution(c, d, subset=True, cycle=3) == \
            [p*u + p*x + q*w + r*v + r*y + s*u + t*w,
             p*v + p*y + q*u + s*y + t*u + t*x,
             p*w + q*y + r*u + t*v]

    assert convolution(c, d, subset=True, cycle=5) == \
            [p*u + q*y + t*v,
             p*v + q*u + r*y + t*w,
             p*w + r*u + s*y + t*x,
             p*x + q*w + r*v + s*u,
             p*y + t*u]
예제 #57
0
def define_ha():
    '''make the hybrid automaton and return it'''
    # Variable ordering: [x, y, xvel, yvel]

    sym_x, sym_y, sym_xvel, sym_yvel = symbols('x y xvel yvel ')

    ha = HybridAutomaton()

    mode_0_0 = ha.new_mode('mode_0_0')
    mode_0_0.inv = lambda state: state[0] <= 1 and state[1] <= 1
    mode_0_0.inv_sympy = And(sym_x <= 1, sym_y <= 1)
    mode_0_0.der = lambda _, state: [
        state[2], state[3], -1.2 * (state[2] - 1) + 0.1 *
        (state[3] - 0.00000000000000006123233995736766), 0.1 *
        (state[2] - 1) + -1.2 * (state[3] - 0.00000000000000006123233995736766)
    ]
    mode_0_0.der_interval_list = [[0, 0], [0, 0], [-0.1, 0.1], [-0.1, 0.1]]

    mode_1_0 = ha.new_mode('mode_1_0')
    mode_1_0.inv = lambda state: state[0] >= 1 and state[0] <= 2 and state[
        1] <= 1
    mode_1_0.inv_sympy = And(And(sym_x >= 1, sym_x <= 2), sym_y <= 1)
    mode_1_0.der = lambda _, state: [
        state[2], state[3], -1.2 * (state[2] - 1) + 0.1 *
        (state[3] - 0.00000000000000006123233995736766), 0.1 *
        (state[2] - 1) + -1.2 * (state[3] - 0.00000000000000006123233995736766)
    ]
    mode_1_0.der_interval_list = [[0, 0], [0, 0], [-0.1, 0.1], [-0.1, 0.1]]

    mode_2_0 = ha.new_mode('mode_2_0')
    mode_2_0.inv = lambda state: state[0] >= 2 and state[1] <= 1
    mode_2_0.inv_sympy = And(sym_x >= 2, sym_y <= 1)
    mode_2_0.der = lambda _, state: [0, 0, 0, 0]
    mode_2_0.der_interval_list = [[0, 0], [0, 0], [0, 0], [0, 0]]

    mode_0_1 = ha.new_mode('mode_0_1')
    mode_0_1.inv = lambda state: state[0] <= 1 and state[1] >= 1 and state[
        1] <= 2
    mode_0_1.inv_sympy = And(And(sym_x <= 1, sym_y >= 1), sym_y <= 2)
    mode_0_1.der = lambda _, state: [
        state[2], state[3], -1.2 *
        (state[2] - 0.00000000000000012246467991473532) + 0.1 *
        (state[3] - -1), 0.1 *
        (state[2] - 0.00000000000000012246467991473532) + -1.2 *
        (state[3] - -1)
    ]
    mode_0_1.der_interval_list = [[0, 0], [0, 0], [-0.1, 0.1], [-0.1, 0.1]]

    mode_1_1 = ha.new_mode('mode_1_1')
    mode_1_1.inv = lambda state: state[0] >= 1 and state[0] <= 2 and state[
        1] >= 1 and state[1] <= 2
    mode_1_1.inv_sympy = And(And(And(sym_x >= 1, sym_x <= 2), sym_y >= 1),
                             sym_y <= 2)
    mode_1_1.der = lambda _, state: [
        state[2], state[3], -1.2 * (state[2] - 0.7071067811865476) + 0.1 *
        (state[3] - -0.7071067811865475), 0.1 *
        (state[2] - 0.7071067811865476) + -1.2 *
        (state[3] - -0.7071067811865475)
    ]
    mode_1_1.der_interval_list = [[0, 0], [0, 0], [-0.1, 0.1], [-0.1, 0.1]]

    mode_2_1 = ha.new_mode('mode_2_1')
    mode_2_1.inv = lambda state: state[0] >= 2 and state[1] >= 1 and state[
        1] <= 2
    mode_2_1.inv_sympy = And(And(sym_x >= 2, sym_y >= 1), sym_y <= 2)
    mode_2_1.der = lambda _, state: [
        state[2], state[3], -1.2 *
        (state[2] - 0.00000000000000012246467991473532) + 0.1 *
        (state[3] - -1), 0.1 *
        (state[2] - 0.00000000000000012246467991473532) + -1.2 *
        (state[3] - -1)
    ]
    mode_2_1.der_interval_list = [[0, 0], [0, 0], [-0.1, 0.1], [-0.1, 0.1]]

    mode_0_2 = ha.new_mode('mode_0_2')
    mode_0_2.inv = lambda state: state[0] <= 1 and state[1] >= 2
    mode_0_2.inv_sympy = And(sym_x <= 1, sym_y >= 2)
    mode_0_2.der = lambda _, state: [0, 0, 0, 0]
    mode_0_2.der_interval_list = [[0, 0], [0, 0], [0, 0], [0, 0]]

    mode_1_2 = ha.new_mode('mode_1_2')
    mode_1_2.inv = lambda state: state[0] >= 1 and state[0] <= 2 and state[
        1] >= 2
    mode_1_2.inv_sympy = And(And(sym_x >= 1, sym_x <= 2), sym_y >= 2)
    mode_1_2.der = lambda _, state: [
        state[2], state[3], -1.2 * (state[2] - 1) + 0.1 *
        (state[3] - 0.00000000000000006123233995736766), 0.1 *
        (state[2] - 1) + -1.2 * (state[3] - 0.00000000000000006123233995736766)
    ]
    mode_1_2.der_interval_list = [[0, 0], [0, 0], [-0.1, 0.1], [-0.1, 0.1]]

    mode_2_2 = ha.new_mode('mode_2_2')
    mode_2_2.inv = lambda state: state[0] >= 2 and state[1] >= 2
    mode_2_2.inv_sympy = And(sym_x >= 2, sym_y >= 2)
    mode_2_2.der = lambda _, state: [
        state[2], state[3], -1.2 *
        (state[2] - 0.00000000000000012246467991473532) + 0.1 *
        (state[3] - -1), 0.1 *
        (state[2] - 0.00000000000000012246467991473532) + -1.2 *
        (state[3] - -1)
    ]
    mode_2_2.der_interval_list = [[0, 0], [0, 0], [-0.1, 0.1], [-0.1, 0.1]]

    t = ha.new_transition(mode_0_0, mode_1_0)
    t.guard = lambda state: state[0] >= 1
    t.reset = lambda state: [None, None, None, None]
    t.guard_sympy = sym_x >= 1

    t = ha.new_transition(mode_0_0, mode_0_1)
    t.guard = lambda state: state[1] >= 1
    t.reset = lambda state: [None, None, None, None]
    t.guard_sympy = sym_y >= 1

    t = ha.new_transition(mode_1_0, mode_0_0)
    t.guard = lambda state: state[0] <= 1
    t.reset = lambda state: [None, None, None, None]
    t.guard_sympy = sym_x <= 1

    t = ha.new_transition(mode_1_0, mode_2_0)
    t.guard = lambda state: state[0] >= 2
    t.reset = lambda state: [None, None, None, None]
    t.guard_sympy = sym_x >= 2

    t = ha.new_transition(mode_1_0, mode_1_1)
    t.guard = lambda state: state[1] >= 1
    t.reset = lambda state: [None, None, None, None]
    t.guard_sympy = sym_y >= 1

    t = ha.new_transition(mode_2_0, mode_1_0)
    t.guard = lambda state: state[0] <= 2
    t.reset = lambda state: [None, None, None, None]
    t.guard_sympy = sym_x <= 2

    t = ha.new_transition(mode_2_0, mode_2_1)
    t.guard = lambda state: state[1] >= 1
    t.reset = lambda state: [None, None, None, None]
    t.guard_sympy = sym_y >= 1

    t = ha.new_transition(mode_0_1, mode_1_1)
    t.guard = lambda state: state[0] >= 1
    t.reset = lambda state: [None, None, None, None]
    t.guard_sympy = sym_x >= 1

    t = ha.new_transition(mode_0_1, mode_0_0)
    t.guard = lambda state: state[1] <= 1
    t.reset = lambda state: [None, None, None, None]
    t.guard_sympy = sym_y <= 1

    t = ha.new_transition(mode_0_1, mode_0_2)
    t.guard = lambda state: state[1] >= 2
    t.reset = lambda state: [None, None, None, None]
    t.guard_sympy = sym_y >= 2

    t = ha.new_transition(mode_1_1, mode_0_1)
    t.guard = lambda state: state[0] <= 1
    t.reset = lambda state: [None, None, None, None]
    t.guard_sympy = sym_x <= 1

    t = ha.new_transition(mode_1_1, mode_2_1)
    t.guard = lambda state: state[0] >= 2
    t.reset = lambda state: [None, None, None, None]
    t.guard_sympy = sym_x >= 2

    t = ha.new_transition(mode_1_1, mode_1_0)
    t.guard = lambda state: state[1] <= 1
    t.reset = lambda state: [None, None, None, None]
    t.guard_sympy = sym_y <= 1

    t = ha.new_transition(mode_1_1, mode_1_2)
    t.guard = lambda state: state[1] >= 2
    t.reset = lambda state: [None, None, None, None]
    t.guard_sympy = sym_y >= 2

    t = ha.new_transition(mode_2_1, mode_1_1)
    t.guard = lambda state: state[0] <= 2
    t.reset = lambda state: [None, None, None, None]
    t.guard_sympy = sym_x <= 2

    t = ha.new_transition(mode_2_1, mode_2_0)
    t.guard = lambda state: state[1] <= 1
    t.reset = lambda state: [None, None, None, None]
    t.guard_sympy = sym_y <= 1

    t = ha.new_transition(mode_2_1, mode_2_2)
    t.guard = lambda state: state[1] >= 2
    t.reset = lambda state: [None, None, None, None]
    t.guard_sympy = sym_y >= 2

    t = ha.new_transition(mode_0_2, mode_1_2)
    t.guard = lambda state: state[0] >= 1
    t.reset = lambda state: [None, None, None, None]
    t.guard_sympy = sym_x >= 1

    t = ha.new_transition(mode_0_2, mode_0_1)
    t.guard = lambda state: state[1] <= 2
    t.reset = lambda state: [None, None, None, None]
    t.guard_sympy = sym_y <= 2

    t = ha.new_transition(mode_1_2, mode_0_2)
    t.guard = lambda state: state[0] <= 1
    t.reset = lambda state: [None, None, None, None]
    t.guard_sympy = sym_x <= 1

    t = ha.new_transition(mode_1_2, mode_2_2)
    t.guard = lambda state: state[0] >= 2
    t.reset = lambda state: [None, None, None, None]
    t.guard_sympy = sym_x >= 2

    t = ha.new_transition(mode_1_2, mode_1_1)
    t.guard = lambda state: state[1] <= 2
    t.reset = lambda state: [None, None, None, None]
    t.guard_sympy = sym_y <= 2

    t = ha.new_transition(mode_2_2, mode_1_2)
    t.guard = lambda state: state[0] <= 2
    t.reset = lambda state: [None, None, None, None]
    t.guard_sympy = sym_x <= 2

    t = ha.new_transition(mode_2_2, mode_2_1)
    t.guard = lambda state: state[1] <= 2
    t.reset = lambda state: [None, None, None, None]
    t.guard_sympy = sym_y <= 2

    return ha
def test_Idx_properties():
    i, a, b = symbols('i a b', integer=True)
    assert Idx(i).is_integer
    assert Idx(i).name == 'i'
    assert Idx(i + 2).name == 'i + 2'
    assert Idx('foo').name == 'foo'
def test_Indexed_func_args():
    i, j = symbols('i j', integer=True)
    a = symbols('a')
    A = Indexed(a, i, j)
    assert A == A.func(*A.args)
예제 #60
0
from sympy.concrete import Sum
from sympy.concrete.delta import deltaproduct as dp, deltasummation as ds, _extract_delta
from sympy.core import Eq, S, symbols, oo
from sympy.functions import KroneckerDelta as KD, Piecewise, piecewise_fold
from sympy.logic import And
from sympy.utilities.pytest import raises

i, j, k, l, m = symbols("i j k l m", integer=True, finite=True)
x, y = symbols("x y", commutative=False)


def test_deltaproduct_trivial():
    assert dp(x, (j, 1, 0)) == 1
    assert dp(x, (j, 1, 3)) == x**3
    assert dp(x + y, (j, 1, 3)) == (x + y)**3
    assert dp(x * y, (j, 1, 3)) == (x * y)**3
    assert dp(KD(i, j), (k, 1, 3)) == KD(i, j)
    assert dp(x * KD(i, j), (k, 1, 3)) == x**3 * KD(i, j)
    assert dp(x * y * KD(i, j), (k, 1, 3)) == (x * y)**3 * KD(i, j)


def test_deltaproduct_basic():
    assert dp(KD(i, j), (j, 1, 3)) == 0
    assert dp(KD(i, j), (j, 1, 1)) == KD(i, 1)
    assert dp(KD(i, j), (j, 2, 2)) == KD(i, 2)
    assert dp(KD(i, j), (j, 3, 3)) == KD(i, 3)
    assert dp(KD(i, j), (j, 1, k)) == KD(i, 1) * KD(k, 1) + KD(k, 0)
    assert dp(KD(i, j), (j, k, 3)) == KD(i, 3) * KD(k, 3) + KD(k, 4)
    assert dp(KD(i, j), (j, k, l)) == KD(i, l) * KD(k, l) + KD(k, l + 1)