def test_functional_diffgeom_ch3(): x0, y0 = symbols('x0, y0', extended_real=True) x, y, t = symbols('x, y, t', extended_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))
def test_functional_diffgeom_ch3(): x0, y0 = symbols('x0, y0', extended_real=True) x, y, t = symbols('x, y, t', extended_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))
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_ch6(): u0, u1, u2, v0, v1, v2, w0, w1, w2 = symbols('u0:3, v0:3, w0:3', extended_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
def test_functional_diffgeom_ch6(): u0, u1, u2, v0, v1, v2, w0, w1, w2 = symbols('u0:3, v0:3, w0:3', extended_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
def test_functional_diffgeom_ch2(): x0, y0, r0, theta0 = symbols('x0, y0, r0, theta0', extended_real=True) x, y = symbols('x, y', extended_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)
def test_functional_diffgeom_ch2(): x0, y0, r0, theta0 = symbols('x0, y0, r0, theta0', extended_real=True) x, y = symbols('x, y', extended_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)
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 pytest.raises(ValueError, lambda: Assignment(B[i], A)) pytest.raises(ValueError, lambda: Assignment(B[i], mat)) pytest.raises(ValueError, lambda: Assignment(x, mat)) pytest.raises(ValueError, lambda: Assignment(x, A)) pytest.raises(ValueError, lambda: Assignment(A[1, 0], mat)) # Scalar to matrix pytest.raises(ValueError, lambda: Assignment(A, x)) pytest.raises(ValueError, lambda: Assignment(A, 0)) # Non-atomic lhs pytest.raises(TypeError, lambda: Assignment(mat, A)) pytest.raises(TypeError, lambda: Assignment(0, x)) pytest.raises(TypeError, lambda: Assignment(x * x, 1)) pytest.raises(TypeError, lambda: Assignment(A + A, mat)) pytest.raises(TypeError, lambda: Assignment(B, 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 pytest.raises(ValueError, lambda: Assignment(B[i], A)) pytest.raises(ValueError, lambda: Assignment(B[i], mat)) pytest.raises(ValueError, lambda: Assignment(x, mat)) pytest.raises(ValueError, lambda: Assignment(x, A)) pytest.raises(ValueError, lambda: Assignment(A[1, 0], mat)) # Scalar to matrix pytest.raises(ValueError, lambda: Assignment(A, x)) pytest.raises(ValueError, lambda: Assignment(A, 0)) # Non-atomic lhs pytest.raises(TypeError, lambda: Assignment(mat, A)) pytest.raises(TypeError, lambda: Assignment(0, x)) pytest.raises(TypeError, lambda: Assignment(x*x, 1)) pytest.raises(TypeError, lambda: Assignment(A + A, mat)) pytest.raises(TypeError, lambda: Assignment(B, 0))
def test_sympyissue_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) == cbrt((1 + I)**(12*I*f)) assert cbrt((1 + I)**(I*(1 + 7*f))).exp == Rational(1, 3) r = symbols('r', extended_real=True) assert sqrt(r**2) == abs(r) assert cbrt(r**3) != r assert sqrt(Pow(2*I, Rational(5, 2))) != (2*I)**Rational(5, 4) p = symbols('p', positive=True) assert cbrt(p**2) == p**Rational(2, 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)/2) # or 1/sqrt(1 + I) e = 1/(1 - sqrt(2)) assert sqrt(e) == I/sqrt(-1 + sqrt(2)) assert e**Rational(-1, 2) == -I*sqrt(-1 + sqrt(2)) assert sqrt((cos(1)**2 + sin(1)**2 - 1)**(3 + I)).exp == Rational(1, 2) assert sqrt(r**Rational(4, 3)) != r**Rational(2, 3) assert sqrt((p + I)**Rational(4, 3)) == (p + I)**Rational(2, 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**Rational(5, 2) assert sqrt(e**6) == e**3 assert sqrt((1 + I*r)**6) != (1 + I*r)**3
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 range(0, n): numer = [] denom = [] for j in range(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)])
def test_sympyissue_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))**Rational(1, 3) assert (((1 + I)**(I*(1 + 7*f)))**Rational(1, 3)).exp == Rational(1, 3) r = symbols('r', extended_real=True) assert sqrt(r**2) == abs(r) assert cbrt(r**3) != r assert sqrt(Pow(2*I, 5*S.Half)) != (2*I)**(5/Integer(4)) p = symbols('p', positive=True) assert cbrt(p**2) == p**(2/Integer(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)/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/Integer(3))) != r**(2/Integer(3)) assert sqrt((p + I)**(4/Integer(3))) == (p + I)**(2/Integer(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
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, Dict({1: 2})), type(A[1]))
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:])
def test_ccode_user_functions(): x = symbols('x', integer=False) n = symbols('n', integer=True) custom_functions = { "ceiling": "ceil", "Abs": [(lambda x: not x.is_integer, "fabs"), (lambda x: x.is_integer, "abs")], } assert ccode(ceiling(x), user_functions=custom_functions) == "ceil(x)" assert ccode(Abs(x), user_functions=custom_functions) == "fabs(x)" assert ccode(Abs(n), user_functions=custom_functions) == "abs(n)"
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)
def test_Indexed_properties(): i, j = symbols('i j', integer=True) A = Indexed('A', i, j) assert A.rank == 2 assert A.indices == (i, j) assert A.base == IndexedBase('A') assert A.ranges == [None, None] pytest.raises(IndexException, lambda: A.shape) n, m = symbols('n m', integer=True) 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(m, n) pytest.raises(IndexException, lambda: Indexed("A", Idx(i, m), Idx(j)).shape)
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" "}" )
def test_Idx_construction(): i, a, b = symbols('i a b', integer=True) assert Idx(i) != Idx(i, 1) assert Idx(i, a) == Idx(i, (0, a - 1)) assert Idx(i, oo) == Idx(i, (0, oo)) x = symbols('x') pytest.raises(TypeError, lambda: Idx(x)) pytest.raises(TypeError, lambda: Idx(0.5)) pytest.raises(TypeError, lambda: Idx(i, x)) pytest.raises(TypeError, lambda: Idx(i, 0.5)) pytest.raises(TypeError, lambda: Idx(i, (x, 5))) pytest.raises(TypeError, lambda: Idx(i, (2, x))) pytest.raises(TypeError, lambda: Idx(i, (2, 3.5)))
def test_ccode_inline_function(): x = symbols('x') g = implemented_function('g', Lambda(x, 2*x)) assert ccode(g(x)) == "2*x" g = implemented_function('g', Lambda(x, 2*x/Catalan)) assert ccode( g(x)) == "double const Catalan = %s;\n2*x/Catalan" % Catalan.evalf() A = IndexedBase('A') i = Idx('i', symbols('n', integer=True)) g = implemented_function('g', Lambda(x, x*(1 + x)*(2 + x))) assert ccode(g(A[i]), assign_to=A[i]) == ( "for (int i=0; i<n; i++){\n" " A[i] = (A[i] + 1)*(A[i] + 2)*A[i];\n" "}" )
def test_IndexedBase_subs(): i, j, k = symbols('i j k', integer=True) A = IndexedBase(a) B = IndexedBase(b) C = IndexedBase(c) assert A[i] == B[i].subs({b: a}) assert isinstance(C[1].subs({C: Dict({1: 2})}), type(A[1]))
def test_Indexed_constructor(): i, j = symbols('i j', integer=True) A = Indexed('A', i, j) assert A == Indexed(Symbol('A'), i, j) assert A == Indexed(IndexedBase('A'), i, j) pytest.raises(TypeError, lambda: Indexed(A, i, j)) pytest.raises(IndexException, lambda: Indexed("A"))
def test_R2(): x0, y0, r0, theta0 = symbols('x0, y0, r0, theta0', extended_real=True) point_r = R2_r.point([x0, y0]) point_p = R2_p.point([r0, theta0]) # r**2 = x**2 + y**2 assert (R2.r**2 - R2.x**2 - R2.y**2).rcall(point_r) == 0 assert trigsimp((R2.r**2 - R2.x**2 - R2.y**2).rcall(point_p)) == 0 assert trigsimp(R2.e_r(R2.x**2 + R2.y**2).rcall(point_p).doit()) == 2 * r0 # polar->rect->polar == Id a, b = symbols('a b', positive=True) m = Matrix([[a], [b]]) # TODO assert m == R2_r.coord_tuple_transform_to(R2_p, R2_p.coord_tuple_transform_to(R2_r, [a, b])).applyfunc(simplify) assert m == R2_p.coord_tuple_transform_to( R2_r, R2_r.coord_tuple_transform_to(R2_p, m)).applyfunc(simplify)
def test_ccode_loops_multiple_contractions(): from diofant.tensor import IndexedBase, Idx from diofant import symbols 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) s = ('for (int i=0; i<m; i++){\n' ' y[i] = 0;\n' '}\n' 'for (int i=0; i<m; i++){\n' ' for (int j=0; j<n; j++){\n' ' for (int k=0; k<o; k++){\n' ' for (int l=0; l<p; l++){\n' ' y[i] = y[i] + b[%s]*a[%s];\n' % (j * o * p + k * p + l, i * n * o * p + j * o * p + k * p + l) + ' }\n' ' }\n' ' }\n' '}') c = ccode(b[j, k, l] * a[i, j, k, l], assign_to=y[i]) assert c == s
def test_FracElement___add__(): F, x, y = field("x,y", QQ) f, g = 1/x, 1/y assert f + g == g + f == (x + y)/(x*y) z = symbols('z') pytest.raises(TypeError, lambda: x + z) assert x + F.ring.gens[0] == F.ring.gens[0] + x == 2*x F, x, y = field("x,y", ZZ) assert x + 3 == 3 + x assert x + QQ(3, 7) == QQ(3, 7) + x == (7*x + 3)/7 Fuv, u, v = field("u,v", ZZ) Fxyzt, x, y, z, t = field("x,y,z,t", Fuv) f = (u*v + x)/(y + u*v) assert dict(f.numer) == {(1, 0, 0, 0): 1, (0, 0, 0, 0): u*v} assert dict(f.denom) == {(0, 1, 0, 0): 1, (0, 0, 0, 0): u*v} Ruv, u, v = ring("u,v", ZZ) Fxyzt, x, y, z, t = field("x,y,z,t", Ruv) f = (u*v + x)/(y + u*v) assert dict(f.numer) == {(1, 0, 0, 0): 1, (0, 0, 0, 0): u*v} assert dict(f.denom) == {(0, 1, 0, 0): 1, (0, 0, 0, 0): u*v}
def test_MatrixSymbol(): n, m, t = symbols('n,m,t') X = MatrixSymbol('X', n, m) assert X.shape == (n, m) pytest.raises(TypeError, lambda: MatrixSymbol('X', n, m) (t)) # issue sympy/sympy#5855 assert X.doit() == X
def test_PolyElement_from_expr(): x, y, z = symbols("x,y,z") R, X, Y, Z = ring((x, y, z), ZZ) f = R.convert(1) assert f == 1 and isinstance(f, R.dtype) f = R.convert(x) assert f == X and isinstance(f, R.dtype) f = R.convert(x*y*z) assert f == X*Y*Z and isinstance(f, R.dtype) f = R.convert(x*y*z + x*y + x) assert f == X*Y*Z + X*Y + X and isinstance(f, R.dtype) f = R.convert(x**3*y*z + x**2*y**7 + 1) assert f == X**3*Y*Z + X**2*Y**7 + 1 and isinstance(f, R.dtype) pytest.raises(CoercionFailed, lambda: R.convert(1/x)) pytest.raises(CoercionFailed, lambda: R.convert(2**x)) pytest.raises(CoercionFailed, lambda: R.convert(7*x + sqrt(2))) R, X, Y = ring((2**x, y), ZZ) f = R.convert(2**(2*x) + 1) assert f == X**2 + 1
def test_ccode_loops_multiple_contractions(): 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) s = ( 'for (int i=0; i<m; i++){\n' ' y[i] = 0;\n' '}\n' 'for (int i=0; i<m; i++){\n' ' for (int j=0; j<n; j++){\n' ' for (int k=0; k<o; k++){\n' ' for (int l=0; l<p; l++){\n' ' y[i] = y[i] + b[%s]*a[%s];\n' % (j*o*p + k*p + l, i*n*o*p + j*o*p + k*p + l) + ' }\n' ' }\n' ' }\n' '}' ) c = ccode(b[j, k, l]*a[i, j, k, l], assign_to=y[i]) assert c == s
def test_Trace(): assert isinstance(Trace(A), Trace) assert not isinstance(Trace(A), MatrixExpr) pytest.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 assert trace(ZeroMatrix(5, 5)) == 0 assert trace(2 * A * B) == 2 * Trace(A * B) assert trace(A.T) == trace(A) i, j = symbols('i j') F = FunctionMatrix(3, 3, Lambda((i, j), i + j)) assert trace(F) == (0 + 0) + (1 + 1) + (2 + 2) pytest.raises(TypeError, lambda: Trace(S.One)) assert Trace(A).arg is A assert str(trace(A)) == str(Trace(A).doit())
def test_FracElement___add__(): F, x, y = field("x,y", QQ) f, g = 1 / x, 1 / y assert f + g == g + f == (x + y) / (x * y) z = symbols('z') pytest.raises(TypeError, lambda: x + z) assert x + F.ring.gens[0] == F.ring.gens[0] + x == 2 * x F, x, y = field("x,y", ZZ) assert x + 3 == 3 + x assert x + QQ(3, 7) == QQ(3, 7) + x == (7 * x + 3) / 7 Fuv, u, v = field("u,v", ZZ) Fxyzt, x, y, z, t = field("x,y,z,t", Fuv) f = (u * v + x) / (y + u * v) assert dict(f.numer) == {(1, 0, 0, 0): 1, (0, 0, 0, 0): u * v} assert dict(f.denom) == {(0, 1, 0, 0): 1, (0, 0, 0, 0): u * v} Ruv, u, v = ring("u,v", ZZ) Fxyzt, x, y, z, t = field("x,y,z,t", Ruv) f = (u * v + x) / (y + u * v) assert dict(f.numer) == {(1, 0, 0, 0): 1, (0, 0, 0, 0): u * v} assert dict(f.denom) == {(0, 1, 0, 0): 1, (0, 0, 0, 0): u * v}
def test_ccode_loops_matrix_vector(): n, m = symbols('n m', integer=True) A = IndexedBase('A') x = IndexedBase('x') y = IndexedBase('y') i = Idx('i', m) j = Idx('j', n) s = ( 'for (int i=0; i<m; i++){\n' ' y[i] = 0;\n' '}\n' 'for (int i=0; i<m; i++){\n' ' for (int j=0; j<n; j++){\n' ' y[i] = x[j]*A[%s] + y[i];\n' % (i*n + j) + ' }\n' '}' ) c = ccode(A[i, j]*x[j], assign_to=y[i]) assert c == s pytest.raises(ValueError, lambda: ccode(A[i, j]*x[j], assign_to=x[j])) s2 = ('for (int i=0; i<m; i++){\n' ' y[i] = 0;\n' '}\n' 'for (int i=0; i<m; i++){\n' ' for (int i=0; i<m; i++){\n' ' y[i] = y[i] + A[m*i + i];\n' ' }\n}') c = ccode(A[i, i], assign_to=y[i]) assert c == s2
def test_ccode_loops_multiple_terms(): from diofant.tensor import IndexedBase, Idx from diofant import symbols n, m, o, p = symbols('n m o p', integer=True) a = IndexedBase('a') b = IndexedBase('b') c = IndexedBase('c') y = IndexedBase('y') i = Idx('i', m) j = Idx('j', n) k = Idx('k', o) s0 = ('for (int i=0; i<m; i++){\n' ' y[i] = 0;\n' '}\n') s1 = ('for (int i=0; i<m; i++){\n' ' for (int j=0; j<n; j++){\n' ' for (int k=0; k<o; k++){\n' ' y[i] = b[j]*b[k]*c[%s] + y[i];\n' % (i * n * o + j * o + k) + ' }\n' ' }\n' '}\n') s2 = ('for (int i=0; i<m; i++){\n' ' for (int k=0; k<o; k++){\n' ' y[i] = b[k]*a[%s] + y[i];\n' % (i * o + k) + ' }\n' '}\n') s3 = ('for (int i=0; i<m; i++){\n' ' for (int j=0; j<n; j++){\n' ' y[i] = b[j]*a[%s] + y[i];\n' % (i * n + j) + ' }\n' '}\n') c = ccode(b[j] * a[i, j] + b[k] * a[i, k] + b[j] * b[k] * c[i, j, k], assign_to=y[i]) assert (c == s0 + s1 + s2 + s3[:-1] or c == s0 + s1 + s3 + s2[:-1] or c == s0 + s2 + s1 + s3[:-1] or c == s0 + s2 + s3 + s1[:-1] or c == s0 + s3 + s1 + s2[:-1] or c == s0 + s3 + s2 + s1[:-1])
def test_ccode_loops_addfactor(): n, m, o, p = symbols('n m o p', integer=True) a = IndexedBase('a') b = IndexedBase('b') c = IndexedBase('c') y = IndexedBase('y') i = Idx('i', m) j = Idx('j', n) k = Idx('k', o) l = Idx('l', p) s = ( 'for (int i=0; i<m; i++){\n' ' y[i] = 0;\n' '}\n' 'for (int i=0; i<m; i++){\n' ' for (int j=0; j<n; j++){\n' ' for (int k=0; k<o; k++){\n' ' for (int l=0; l<p; l++){\n' ' y[i] = (a[%s] + b[%s])*c[%s] + y[i];\n' % (i*n*o*p + j*o*p + k*p + l, i*n*o*p + j*o*p + k*p + l, j*o*p + k*p + l) + ' }\n' ' }\n' ' }\n' '}' ) c = ccode((a[i, j, k, l] + b[i, j, k, l])*c[j, k, l], assign_to=y[i]) assert c == s
def test_FractionField_methods(): F = ZZ.frac_field("x") assert F.domain_new(2) == ZZ(2) x = symbols("x") assert F.field_new(x**2 + x) == F.x**2 + F.x
def test_Mul(): A, B, C, D = symbols('A B C D', commutative=False) assert mcode(x*y*z) == "x*y*z" assert mcode(x*y*A) == "x*y*A" assert mcode(x*y*A*B) == "x*y*A**B" assert mcode(x*y*A*B*C) == "x*y*A**B**C" assert mcode(x*A*B*(C + D)*A*y) == "x*y*A**B**(C + D)**A"
def test_PolyElement_from_expr(): x, y, z = symbols("x,y,z") R, X, Y, Z = ring((x, y, z), ZZ) f = R.from_expr(1) assert f == 1 and isinstance(f, R.dtype) f = R.from_expr(x) assert f == X and isinstance(f, R.dtype) f = R.from_expr(x * y * z) assert f == X * Y * Z and isinstance(f, R.dtype) f = R.from_expr(x * y * z + x * y + x) assert f == X * Y * Z + X * Y + X and isinstance(f, R.dtype) f = R.from_expr(x**3 * y * z + x**2 * y**7 + 1) assert f == X**3 * Y * Z + X**2 * Y**7 + 1 and isinstance(f, R.dtype) pytest.raises(ValueError, lambda: R.from_expr(1 / x)) pytest.raises(ValueError, lambda: R.from_expr(2**x)) pytest.raises(ValueError, lambda: R.from_expr(7 * x + sqrt(2))) R, X, Y = ring((2**x, y), ZZ) f = R.from_expr(2**(2 * x) + 1) assert f == X**2 + 1
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
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)})
def test_attrs(): a, b = symbols('a, b', cls=Dummy) f = Hyper_Function([2, a], [b]) assert f.ap == Tuple(2, a) assert f.bq == Tuple(b) assert f.args == (Tuple(2, a), Tuple(b)) assert f.sizes == (2, 1)
def test_jscode_loops_addfactor(): from diofant.tensor import IndexedBase, Idx from diofant import symbols n, m, o, p = symbols('n m o p', integer=True) a = IndexedBase('a') b = IndexedBase('b') c = IndexedBase('c') y = IndexedBase('y') i = Idx('i', m) j = Idx('j', n) k = Idx('k', o) l = Idx('l', p) s = ( 'for (var i=0; i<m; i++){\n' ' y[i] = 0;\n' '}\n' 'for (var i=0; i<m; i++){\n' ' for (var j=0; j<n; j++){\n' ' for (var k=0; k<o; k++){\n' ' for (var l=0; l<p; l++){\n' ' y[i] = (a[%s] + b[%s])*c[%s] + y[i];\n' % (i*n*o*p + j*o*p + k*p + l, i*n*o*p + j*o*p + k*p + l, j*o*p + k*p + l) + ' }\n' ' }\n' ' }\n' '}' ) c = jscode((a[i, j, k, l] + b[i, j, k, l])*c[j, k, l], assign_to=y[i]) assert c == s
def test_m_tensor_loops_multiple_contractions(): # see comments in previous test about vectorizing from diofant.tensor import IndexedBase, Idx from diofant import symbols 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
def test_R2(): x0, y0, r0, theta0 = symbols('x0, y0, r0, theta0', extended_real=True) point_r = R2_r.point([x0, y0]) point_p = R2_p.point([r0, theta0]) # r**2 = x**2 + y**2 assert (R2.r**2 - R2.x**2 - R2.y**2).rcall(point_r) == 0 assert trigsimp( (R2.r**2 - R2.x**2 - R2.y**2).rcall(point_p) ) == 0 assert trigsimp(R2.e_r(R2.x**2 + R2.y**2).rcall(point_p).doit()) == 2*r0 # polar->rect->polar == Id a, b = symbols('a b', positive=True) m = Matrix([[a], [b]]) # TODO assert m == R2_r.coord_tuple_transform_to(R2_p, R2_p.coord_tuple_transform_to(R2_r, [a, b])).applyfunc(simplify) assert m == R2_p.coord_tuple_transform_to( R2_r, R2_r.coord_tuple_transform_to(R2_p, m)).applyfunc(simplify)
def test_global_vars_octave(): x, y, z, t = symbols("x y z t") result = codegen(('f', x * y), "Octave", header=False, empty=False, global_vars=(y, )) source = result[0][1] expected = ("function out1 = f(x)\n" " global y\n" " out1 = x.*y;\n" "end\n") assert source == expected result = codegen(('f', x * y + z), "Octave", header=False, empty=False, argument_sequence=(x, y), global_vars=(z, t)) source = result[0][1] expected = ("function out1 = f(x, y)\n" " global t z\n" " out1 = x.*y + z;\n" "end\n") assert source == expected
def test_Trace(): assert isinstance(Trace(A), Trace) assert not isinstance(Trace(A), MatrixExpr) pytest.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 assert trace(ZeroMatrix(5, 5)) == 0 assert trace(2*A*B) == 2*Trace(A*B) assert trace(A.T) == trace(A) i, j = symbols('i j') F = FunctionMatrix(3, 3, Lambda((i, j), i + j)) assert trace(F) == (0 + 0) + (1 + 1) + (2 + 2) pytest.raises(TypeError, lambda: Trace(1)) assert Trace(A).arg is A assert str(trace(A)) == str(Trace(A).doit())
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? from diofant.tensor import IndexedBase, Idx from diofant import symbols 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) })
def test_coords(): r, theta = symbols('r, theta') m = Manifold('M', 2) patch = Patch('P', m) rect = CoordSystem('rect', patch) polar = CoordSystem('polar', patch) polar.connect_to(rect, [r, theta], [r*cos(theta), r*sin(theta)]) polar.coord_tuple_transform_to(rect, [0, 2]) == Matrix([[0], [0]])
def test_Idx_func_args(): i, a, b = symbols('i a b', integer=True) ii = Idx(i) assert ii.func(*ii.args) == ii ii = Idx(i, a) assert ii.func(*ii.args) == ii ii = Idx(i, (a, b)) assert ii.func(*ii.args) == ii
def test_Idx_subs(): i, a, b = symbols('i a b', integer=True) assert Idx(i, a).subs({a: b}) == Idx(i, b) assert Idx(i, a).subs({i: b}) == Idx(b, a) assert Idx(i).subs({i: 2}) == Idx(2) assert Idx(i, a).subs({a: 2}) == Idx(i, 2) assert Idx(i, (a, b)).subs({i: 2}) == Idx(2, (a, b))
def test_IndexedBase_sugar(): i, j = symbols('i j', integer=True) 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:])
def test_PolyElement_almosteq(): R, x, y = ring('x, y', RR) z = symbols('z') assert x.almosteq(y) is False assert x.almosteq(1) is False assert (x + 2*y).almosteq(2) is False assert (x + 2*y).almosteq(2*x + y) is False assert R.one.almosteq(2) is False assert R.one.almosteq(z) is False
def test_minimize_linear(): assert minimize([-2*x - 3*y - 2*z, 2*x + y + z <= 4, x + 2*y + z <= 7, z <= 5, x >= 0, y >= 0, z >= 0], x, y, z) == (-11, {x: 0, y: 3, z: 1}) assert minimize([-2*x - 3*y - 2*z, 2*x + y + z <= 4, x + 2*y + z <= 7, z <= 5, x >= 0, y >= 0, z >= 0], x, y, z) == (-11, {x: 0, y: 3, z: 1}) assert minimize([-2*x - 3*y - 2*z, 2*x + y + z <= 4, x + 2*y + z < 7, z <= 5, x >= 0, y >= 0, z >= 0], x, y, z) is None assert minimize([-2*x - 3*y - 4*z, 3*x + 2*y + z <= 10, 2*x + 5*y + 3*z <= 15, x >= 0, y >= 0, z >= 0], x, y, z) == (-20, {x: 0, y: 0, z: 5}) assert maximize([12*x + 40*y, x + y <= 15, x + 3*y <= 36, x <= 10, x >= 0, y >= 0], x, y) == (480, {x: 0, y: 12}) assert minimize([-2*x - 3*y - 4*z, Eq(3*x + 2*y + z, 10), Eq(2*x + 5*y + 3*z, 15), x >= 0, y >= 0, z >= 0], x, y, z) == (Rational(-130, 7), {x: Rational(15, 7), y: 0, z: Rational(25, 7)}) assert maximize([2*x + y, y - x <= 1, x - 2*y <= 2, x >= 0, y >= 0], x, y) == (oo, {x: nan, y: nan}) assert minimize([2*x + 3*y - z, 1 <= x + y + z, x + y + z <= 2, 1 <= x - y + z, x - y + z <= 2, Eq(x - y - z, 3)], x, y, z) == (3, {x: 2, y: Rational(-1, 2), z: Rational(-1, 2)}) x1, x2, x3, x4, x5 = symbols('x1:6') assert minimize([-2*x1 + 4*x2 + 7*x3 + x4 + 5*x5, Eq(-x1 + x2 + 2*x3 + x4 + 2*x5, 7), Eq(-x1 + 2*x2 + 3*x3 + x4 + x5, 6), Eq(-x1 + x2 + x3 + 2*x4 + x5, 4), x2 >= 0, x3 >= 0, x4 >= 0, x5 >= 0], x1, x2, x3, x4, x5) == (19, {x1: -1, x2: 0, x3: 1, x4: 0, x5: 2}) assert minimize([-x - y, x + 2*y <= 8, 3*x + 2*y <= 12, x + 3*y >= 6, x >= 0, y >= 0], x, y) == (-5, {x: 2, y: 3}) pytest.raises(InfeasibleProblem, lambda: minimize([-x - y, x + 2*y <= 8, 3*x + 2*y <= 12, x + 3*y >= 13, x >= 0, y >= 0], x, y)) pytest.raises(InfeasibleProblem, lambda: minimize([-x - y, x + 2*y <= 8, 3*x + 2*y <= 12, x + 3*y >= 13, x >= 0, y >= 0], x, y)) assert minimize([-x - y, 2*x + y >= 4, Eq(x + 2*y, 6), x >= 0, y >= 0], x, y) == (-6, {x: 6, y: 0}) assert minimize([6*x + 3*y, x + y >= 1, 2*x - y >= 1, 3*y <= 2, x >= 0, y >= 0], x, y) == (5, {x: Rational(2, 3), y: Rational(1, 3)})
def test_check_case_false_positive(): # The upper case/lower case exception should not be triggered by Diofant # 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.) x2 = symbols('x', my_assumption=True) try: codegen(('test', x*x2), 'f95', 'prefix') except CodeGenError as e: if e.args[0].startswith("Fortran ignores case."): raise AssertionError("This exception should not be raised!")
def test_ccode_functions(): assert ccode(sin(x) ** cos(x)) == "pow(sin(x), cos(x))" assert ccode(elliptic_e(x)) == ("// Not supported in C:\n" "// elliptic_e\nelliptic_e(x)") n = symbols('n', integer=True) assert ccode(Abs(n)) == '// Not supported in C:\n// Abs\nAbs(n)' assert ccode(Abs(x)) == 'fabs(x)' pytest.raises(TypeError, lambda: ccode(sin(x), assign_to=1))