hash
stringlengths
64
64
content
stringlengths
0
1.51M
c8d0f7473f3ccb377320e5e2a0f956e8a5ef6d048d1eb746b7d18d52df8fa99e
from sympy import ( adjoint, And, Basic, conjugate, diff, expand, Eq, Function, I, ITE, Integral, integrate, Interval, KroneckerDelta, lambdify, log, Max, Min, oo, Or, pi, Piecewise, piecewise_fold, Rational, solve, symbols, transpose, cos, sin, exp, Abs, Ne, Not, Symbol, S, sqrt, Sum, Tuple, zoo, Float, DiracDelta, Heaviside, Add, Mul, factorial, Ge, Contains) from sympy.core.expr import unchanged from sympy.functions.elementary.piecewise import Undefined, ExprCondPair from sympy.printing import srepr from sympy.testing.pytest import raises, slow a, b, c, d, x, y = symbols('a:d, x, y') z = symbols('z', nonzero=True) def test_piecewise1(): # Test canonicalization assert unchanged(Piecewise, ExprCondPair(x, x < 1), ExprCondPair(0, True)) assert Piecewise((x, x < 1), (0, True)) == Piecewise(ExprCondPair(x, x < 1), ExprCondPair(0, True)) assert Piecewise((x, x < 1), (0, True), (1, True)) == \ Piecewise((x, x < 1), (0, True)) assert Piecewise((x, x < 1), (0, False), (-1, 1 > 2)) == \ Piecewise((x, x < 1)) assert Piecewise((x, x < 1), (0, x < 1), (0, True)) == \ Piecewise((x, x < 1), (0, True)) assert Piecewise((x, x < 1), (0, x < 2), (0, True)) == \ Piecewise((x, x < 1), (0, True)) assert Piecewise((x, x < 1), (x, x < 2), (0, True)) == \ Piecewise((x, Or(x < 1, x < 2)), (0, True)) assert Piecewise((x, x < 1), (x, x < 2), (x, True)) == x assert Piecewise((x, True)) == x # Explicitly constructed empty Piecewise not accepted raises(TypeError, lambda: Piecewise()) # False condition is never retained assert Piecewise((2*x, x < 0), (x, False)) == \ Piecewise((2*x, x < 0), (x, False), evaluate=False) == \ Piecewise((2*x, x < 0)) assert Piecewise((x, False)) == Undefined raises(TypeError, lambda: Piecewise(x)) assert Piecewise((x, 1)) == x # 1 and 0 are accepted as True/False raises(TypeError, lambda: Piecewise((x, 2))) raises(TypeError, lambda: Piecewise((x, x**2))) raises(TypeError, lambda: Piecewise(([1], True))) assert Piecewise(((1, 2), True)) == Tuple(1, 2) cond = (Piecewise((1, x < 0), (2, True)) < y) assert Piecewise((1, cond) ) == Piecewise((1, ITE(x < 0, y > 1, y > 2))) assert Piecewise((1, x > 0), (2, And(x <= 0, x > -1)) ) == Piecewise((1, x > 0), (2, x > -1)) # test for supporting Contains in Piecewise pwise = Piecewise( (1, And(x <= 6, x > 1, Contains(x, S.Integers))), (0, True)) assert pwise.subs(x, pi) == 0 assert pwise.subs(x, 2) == 1 assert pwise.subs(x, 7) == 0 # Test subs p = Piecewise((-1, x < -1), (x**2, x < 0), (log(x), x >= 0)) p_x2 = Piecewise((-1, x**2 < -1), (x**4, x**2 < 0), (log(x**2), x**2 >= 0)) assert p.subs(x, x**2) == p_x2 assert p.subs(x, -5) == -1 assert p.subs(x, -1) == 1 assert p.subs(x, 1) == log(1) # More subs tests p2 = Piecewise((1, x < pi), (-1, x < 2*pi), (0, x > 2*pi)) p3 = Piecewise((1, Eq(x, 0)), (1/x, True)) p4 = Piecewise((1, Eq(x, 0)), (2, 1/x>2)) assert p2.subs(x, 2) == 1 assert p2.subs(x, 4) == -1 assert p2.subs(x, 10) == 0 assert p3.subs(x, 0.0) == 1 assert p4.subs(x, 0.0) == 1 f, g, h = symbols('f,g,h', cls=Function) pf = Piecewise((f(x), x < -1), (f(x) + h(x) + 2, x <= 1)) pg = Piecewise((g(x), x < -1), (g(x) + h(x) + 2, x <= 1)) assert pg.subs(g, f) == pf assert Piecewise((1, Eq(x, 0)), (0, True)).subs(x, 0) == 1 assert Piecewise((1, Eq(x, 0)), (0, True)).subs(x, 1) == 0 assert Piecewise((1, Eq(x, y)), (0, True)).subs(x, y) == 1 assert Piecewise((1, Eq(x, z)), (0, True)).subs(x, z) == 1 assert Piecewise((1, Eq(exp(x), cos(z))), (0, True)).subs(x, z) == \ Piecewise((1, Eq(exp(z), cos(z))), (0, True)) p5 = Piecewise( (0, Eq(cos(x) + y, 0)), (1, True)) assert p5.subs(y, 0) == Piecewise( (0, Eq(cos(x), 0)), (1, True)) assert Piecewise((-1, y < 1), (0, x < 0), (1, Eq(x, 0)), (2, True) ).subs(x, 1) == Piecewise((-1, y < 1), (2, True)) assert Piecewise((1, Eq(x**2, -1)), (2, x < 0)).subs(x, I) == 1 p6 = Piecewise((x, x > 0)) n = symbols('n', negative=True) assert p6.subs(x, n) == Undefined # Test evalf assert p.evalf() == p assert p.evalf(subs={x: -2}) == -1 assert p.evalf(subs={x: -1}) == 1 assert p.evalf(subs={x: 1}) == log(1) assert p6.evalf(subs={x: -5}) == Undefined # Test doit f_int = Piecewise((Integral(x, (x, 0, 1)), x < 1)) assert f_int.doit() == Piecewise( (S.Half, x < 1) ) # Test differentiation f = x fp = x*p dp = Piecewise((0, x < -1), (2*x, x < 0), (1/x, x >= 0)) fp_dx = x*dp + p assert diff(p, x) == dp assert diff(f*p, x) == fp_dx # Test simple arithmetic assert x*p == fp assert x*p + p == p + x*p assert p + f == f + p assert p + dp == dp + p assert p - dp == -(dp - p) # Test power dp2 = Piecewise((0, x < -1), (4*x**2, x < 0), (1/x**2, x >= 0)) assert dp**2 == dp2 # Test _eval_interval f1 = x*y + 2 f2 = x*y**2 + 3 peval = Piecewise((f1, x < 0), (f2, x > 0)) peval_interval = f1.subs( x, 0) - f1.subs(x, -1) + f2.subs(x, 1) - f2.subs(x, 0) assert peval._eval_interval(x, 0, 0) == 0 assert peval._eval_interval(x, -1, 1) == peval_interval peval2 = Piecewise((f1, x < 0), (f2, True)) assert peval2._eval_interval(x, 0, 0) == 0 assert peval2._eval_interval(x, 1, -1) == -peval_interval assert peval2._eval_interval(x, -1, -2) == f1.subs(x, -2) - f1.subs(x, -1) assert peval2._eval_interval(x, -1, 1) == peval_interval assert peval2._eval_interval(x, None, 0) == peval2.subs(x, 0) assert peval2._eval_interval(x, -1, None) == -peval2.subs(x, -1) # Test integration assert p.integrate() == Piecewise( (-x, x < -1), (x**3/3 + Rational(4, 3), x < 0), (x*log(x) - x + Rational(4, 3), True)) p = Piecewise((x, x < 1), (x**2, -1 <= x), (x, 3 < x)) assert integrate(p, (x, -2, 2)) == Rational(5, 6) assert integrate(p, (x, 2, -2)) == Rational(-5, 6) p = Piecewise((0, x < 0), (1, x < 1), (0, x < 2), (1, x < 3), (0, True)) assert integrate(p, (x, -oo, oo)) == 2 p = Piecewise((x, x < -10), (x**2, x <= -1), (x, 1 < x)) assert integrate(p, (x, -2, 2)) == Undefined # Test commutativity assert isinstance(p, Piecewise) and p.is_commutative is True def test_piecewise_free_symbols(): f = Piecewise((x, a < 0), (y, True)) assert f.free_symbols == {x, y, a} def test_piecewise_integrate1(): x, y = symbols('x y', real=True, finite=True) f = Piecewise(((x - 2)**2, x >= 0), (1, True)) assert integrate(f, (x, -2, 2)) == Rational(14, 3) g = Piecewise(((x - 5)**5, x >= 4), (f, True)) assert integrate(g, (x, -2, 2)) == Rational(14, 3) assert integrate(g, (x, -2, 5)) == Rational(43, 6) assert g == Piecewise(((x - 5)**5, x >= 4), (f, x < 4)) g = Piecewise(((x - 5)**5, 2 <= x), (f, x < 2)) assert integrate(g, (x, -2, 2)) == Rational(14, 3) assert integrate(g, (x, -2, 5)) == Rational(-701, 6) assert g == Piecewise(((x - 5)**5, 2 <= x), (f, True)) g = Piecewise(((x - 5)**5, 2 <= x), (2*f, True)) assert integrate(g, (x, -2, 2)) == Rational(28, 3) assert integrate(g, (x, -2, 5)) == Rational(-673, 6) def test_piecewise_integrate1b(): g = Piecewise((1, x > 0), (0, Eq(x, 0)), (-1, x < 0)) assert integrate(g, (x, -1, 1)) == 0 g = Piecewise((1, x - y < 0), (0, True)) assert integrate(g, (y, -oo, 0)) == -Min(0, x) assert g.subs(x, -3).integrate((y, -oo, 0)) == 3 assert integrate(g, (y, 0, -oo)) == Min(0, x) assert integrate(g, (y, 0, oo)) == -Max(0, x) + oo assert integrate(g, (y, -oo, 42)) == -Min(42, x) + 42 assert integrate(g, (y, -oo, oo)) == -x + oo g = Piecewise((0, x < 0), (x, x <= 1), (1, True)) gy1 = g.integrate((x, y, 1)) g1y = g.integrate((x, 1, y)) for yy in (-1, S.Half, 2): assert g.integrate((x, yy, 1)) == gy1.subs(y, yy) assert g.integrate((x, 1, yy)) == g1y.subs(y, yy) assert gy1 == Piecewise( (-Min(1, Max(0, y))**2/2 + S.Half, y < 1), (-y + 1, True)) assert g1y == Piecewise( (Min(1, Max(0, y))**2/2 - S.Half, y < 1), (y - 1, True)) @slow def test_piecewise_integrate1ca(): y = symbols('y', real=True) g = Piecewise( (1 - x, Interval(0, 1).contains(x)), (1 + x, Interval(-1, 0).contains(x)), (0, True) ) gy1 = g.integrate((x, y, 1)) g1y = g.integrate((x, 1, y)) assert g.integrate((x, -2, 1)) == gy1.subs(y, -2) assert g.integrate((x, 1, -2)) == g1y.subs(y, -2) assert g.integrate((x, 0, 1)) == gy1.subs(y, 0) assert g.integrate((x, 1, 0)) == g1y.subs(y, 0) # XXX Make test pass without simplify assert g.integrate((x, 2, 1)) == gy1.subs(y, 2).simplify() assert g.integrate((x, 1, 2)) == g1y.subs(y, 2).simplify() assert piecewise_fold(gy1.rewrite(Piecewise)) == \ Piecewise( (1, y <= -1), (-y**2/2 - y + S.Half, y <= 0), (y**2/2 - y + S.Half, y < 1), (0, True)) assert piecewise_fold(g1y.rewrite(Piecewise)) == \ Piecewise( (-1, y <= -1), (y**2/2 + y - S.Half, y <= 0), (-y**2/2 + y - S.Half, y < 1), (0, True)) # g1y and gy1 should simplify if the condition that y < 1 # is applied, e.g. Min(1, Max(-1, y)) --> Max(-1, y) # XXX Make test pass without simplify assert gy1.simplify() == Piecewise( ( -Min(1, Max(-1, y))**2/2 - Min(1, Max(-1, y)) + Min(1, Max(0, y))**2 + S.Half, y < 1), (0, True) ) assert g1y.simplify() == Piecewise( ( Min(1, Max(-1, y))**2/2 + Min(1, Max(-1, y)) - Min(1, Max(0, y))**2 - S.Half, y < 1), (0, True)) @slow def test_piecewise_integrate1cb(): y = symbols('y', real=True) g = Piecewise( (0, Or(x <= -1, x >= 1)), (1 - x, x > 0), (1 + x, True) ) gy1 = g.integrate((x, y, 1)) g1y = g.integrate((x, 1, y)) assert g.integrate((x, -2, 1)) == gy1.subs(y, -2) assert g.integrate((x, 1, -2)) == g1y.subs(y, -2) assert g.integrate((x, 0, 1)) == gy1.subs(y, 0) assert g.integrate((x, 1, 0)) == g1y.subs(y, 0) assert g.integrate((x, 2, 1)) == gy1.subs(y, 2) assert g.integrate((x, 1, 2)) == g1y.subs(y, 2) assert piecewise_fold(gy1.rewrite(Piecewise)) == \ Piecewise( (1, y <= -1), (-y**2/2 - y + S.Half, y <= 0), (y**2/2 - y + S.Half, y < 1), (0, True)) assert piecewise_fold(g1y.rewrite(Piecewise)) == \ Piecewise( (-1, y <= -1), (y**2/2 + y - S.Half, y <= 0), (-y**2/2 + y - S.Half, y < 1), (0, True)) # g1y and gy1 should simplify if the condition that y < 1 # is applied, e.g. Min(1, Max(-1, y)) --> Max(-1, y) assert gy1 == Piecewise( ( -Min(1, Max(-1, y))**2/2 - Min(1, Max(-1, y)) + Min(1, Max(0, y))**2 + S.Half, y < 1), (0, True) ) assert g1y == Piecewise( ( Min(1, Max(-1, y))**2/2 + Min(1, Max(-1, y)) - Min(1, Max(0, y))**2 - S.Half, y < 1), (0, True)) def test_piecewise_integrate2(): from itertools import permutations lim = Tuple(x, c, d) p = Piecewise((1, x < a), (2, x > b), (3, True)) q = p.integrate(lim) assert q == Piecewise( (-c + 2*d - 2*Min(d, Max(a, c)) + Min(d, Max(a, b, c)), c < d), (-2*c + d + 2*Min(c, Max(a, d)) - Min(c, Max(a, b, d)), True)) for v in permutations((1, 2, 3, 4)): r = dict(zip((a, b, c, d), v)) assert p.subs(r).integrate(lim.subs(r)) == q.subs(r) def test_meijer_bypass(): # totally bypass meijerg machinery when dealing # with Piecewise in integrate assert Piecewise((1, x < 4), (0, True)).integrate((x, oo, 1)) == -3 def test_piecewise_integrate3_inequality_conditions(): from sympy.utilities.iterables import cartes lim = (x, 0, 5) # set below includes two pts below range, 2 pts in range, # 2 pts above range, and the boundaries N = (-2, -1, 0, 1, 2, 5, 6, 7) p = Piecewise((1, x > a), (2, x > b), (0, True)) ans = p.integrate(lim) for i, j in cartes(N, repeat=2): reps = dict(zip((a, b), (i, j))) assert ans.subs(reps) == p.subs(reps).integrate(lim) assert ans.subs(a, 4).subs(b, 1) == 0 + 2*3 + 1 p = Piecewise((1, x > a), (2, x < b), (0, True)) ans = p.integrate(lim) for i, j in cartes(N, repeat=2): reps = dict(zip((a, b), (i, j))) assert ans.subs(reps) == p.subs(reps).integrate(lim) # delete old tests that involved c1 and c2 since those # reduce to the above except that a value of 0 was used # for two expressions whereas the above uses 3 different # values @slow def test_piecewise_integrate4_symbolic_conditions(): a = Symbol('a', real=True, finite=True) b = Symbol('b', real=True, finite=True) x = Symbol('x', real=True, finite=True) y = Symbol('y', real=True, finite=True) p0 = Piecewise((0, Or(x < a, x > b)), (1, True)) p1 = Piecewise((0, x < a), (0, x > b), (1, True)) p2 = Piecewise((0, x > b), (0, x < a), (1, True)) p3 = Piecewise((0, x < a), (1, x < b), (0, True)) p4 = Piecewise((0, x > b), (1, x > a), (0, True)) p5 = Piecewise((1, And(a < x, x < b)), (0, True)) # check values of a=1, b=3 (and reversed) with values # of y of 0, 1, 2, 3, 4 lim = Tuple(x, -oo, y) for p in (p0, p1, p2, p3, p4, p5): ans = p.integrate(lim) for i in range(5): reps = {a:1, b:3, y:i} assert ans.subs(reps) == p.subs(reps).integrate(lim.subs(reps)) reps = {a: 3, b:1, y:i} assert ans.subs(reps) == p.subs(reps).integrate(lim.subs(reps)) lim = Tuple(x, y, oo) for p in (p0, p1, p2, p3, p4, p5): ans = p.integrate(lim) for i in range(5): reps = {a:1, b:3, y:i} assert ans.subs(reps) == p.subs(reps).integrate(lim.subs(reps)) reps = {a:3, b:1, y:i} assert ans.subs(reps) == p.subs(reps).integrate(lim.subs(reps)) ans = Piecewise( (0, x <= Min(a, b)), (x - Min(a, b), x <= b), (b - Min(a, b), True)) for i in (p0, p1, p2, p4): assert i.integrate(x) == ans assert p3.integrate(x) == Piecewise( (0, x < a), (-a + x, x <= Max(a, b)), (-a + Max(a, b), True)) assert p5.integrate(x) == Piecewise( (0, x <= a), (-a + x, x <= Max(a, b)), (-a + Max(a, b), True)) p1 = Piecewise((0, x < a), (0.5, x > b), (1, True)) p2 = Piecewise((0.5, x > b), (0, x < a), (1, True)) p3 = Piecewise((0, x < a), (1, x < b), (0.5, True)) p4 = Piecewise((0.5, x > b), (1, x > a), (0, True)) p5 = Piecewise((1, And(a < x, x < b)), (0.5, x > b), (0, True)) # check values of a=1, b=3 (and reversed) with values # of y of 0, 1, 2, 3, 4 lim = Tuple(x, -oo, y) for p in (p1, p2, p3, p4, p5): ans = p.integrate(lim) for i in range(5): reps = {a:1, b:3, y:i} assert ans.subs(reps) == p.subs(reps).integrate(lim.subs(reps)) reps = {a: 3, b:1, y:i} assert ans.subs(reps) == p.subs(reps).integrate(lim.subs(reps)) def test_piecewise_integrate5_independent_conditions(): p = Piecewise((0, Eq(y, 0)), (x*y, True)) assert integrate(p, (x, 1, 3)) == Piecewise((0, Eq(y, 0)), (4*y, True)) def test_piecewise_simplify(): p = Piecewise(((x**2 + 1)/x**2, Eq(x*(1 + x) - x**2, 0)), ((-1)**x*(-1), True)) assert p.simplify() == \ Piecewise((zoo, Eq(x, 0)), ((-1)**(x + 1), True)) # simplify when there are Eq in conditions assert Piecewise( (a, And(Eq(a, 0), Eq(a + b, 0))), (1, True)).simplify( ) == Piecewise( (0, And(Eq(a, 0), Eq(b, 0))), (1, True)) assert Piecewise((2*x*factorial(a)/(factorial(y)*factorial(-y + a)), Eq(y, 0) & Eq(-y + a, 0)), (2*factorial(a)/(factorial(y)*factorial(-y + a)), Eq(y, 0) & Eq(-y + a, 1)), (0, True)).simplify( ) == Piecewise( (2*x, And(Eq(a, 0), Eq(y, 0))), (2, And(Eq(a, 1), Eq(y, 0))), (0, True)) args = (2, And(Eq(x, 2), Ge(y ,0))), (x, True) assert Piecewise(*args).simplify() == Piecewise(*args) args = (1, Eq(x, 0)), (sin(x)/x, True) assert Piecewise(*args).simplify() == Piecewise(*args) assert Piecewise((2 + y, And(Eq(x, 2), Eq(y, 0))), (x, True) ).simplify() == x # check that x or f(x) are recognized as being Symbol-like for lhs args = Tuple((1, Eq(x, 0)), (sin(x) + 1 + x, True)) ans = x + sin(x) + 1 f = Function('f') assert Piecewise(*args).simplify() == ans assert Piecewise(*args.subs(x, f(x))).simplify() == ans.subs(x, f(x)) # issue 18634 d = Symbol("d", integer=True) n = Symbol("n", integer=True) t = Symbol("t", real=True, positive=True) expr = Piecewise((-d + 2*n, Eq(1/t, 1)), (t**(1 - 4*n)*t**(4*n - 1)*(-d + 2*n), True)) assert expr.simplify() == -d + 2*n def test_piecewise_solve(): abs2 = Piecewise((-x, x <= 0), (x, x > 0)) f = abs2.subs(x, x - 2) assert solve(f, x) == [2] assert solve(f - 1, x) == [1, 3] f = Piecewise(((x - 2)**2, x >= 0), (1, True)) assert solve(f, x) == [2] g = Piecewise(((x - 5)**5, x >= 4), (f, True)) assert solve(g, x) == [2, 5] g = Piecewise(((x - 5)**5, x >= 4), (f, x < 4)) assert solve(g, x) == [2, 5] g = Piecewise(((x - 5)**5, x >= 2), (f, x < 2)) assert solve(g, x) == [5] g = Piecewise(((x - 5)**5, x >= 2), (f, True)) assert solve(g, x) == [5] g = Piecewise(((x - 5)**5, x >= 2), (f, True), (10, False)) assert solve(g, x) == [5] g = Piecewise(((x - 5)**5, x >= 2), (-x + 2, x - 2 <= 0), (x - 2, x - 2 > 0)) assert solve(g, x) == [5] # if no symbol is given the piecewise detection must still work assert solve(Piecewise((x - 2, x > 2), (2 - x, True)) - 3) == [-1, 5] f = Piecewise(((x - 2)**2, x >= 0), (0, True)) raises(NotImplementedError, lambda: solve(f, x)) def nona(ans): return list(filter(lambda x: x is not S.NaN, ans)) p = Piecewise((x**2 - 4, x < y), (x - 2, True)) ans = solve(p, x) assert nona([i.subs(y, -2) for i in ans]) == [2] assert nona([i.subs(y, 2) for i in ans]) == [-2, 2] assert nona([i.subs(y, 3) for i in ans]) == [-2, 2] assert ans == [ Piecewise((-2, y > -2), (S.NaN, True)), Piecewise((2, y <= 2), (S.NaN, True)), Piecewise((2, y > 2), (S.NaN, True))] # issue 6060 absxm3 = Piecewise( (x - 3, 0 <= x - 3), (3 - x, 0 > x - 3) ) assert solve(absxm3 - y, x) == [ Piecewise((-y + 3, -y < 0), (S.NaN, True)), Piecewise((y + 3, y >= 0), (S.NaN, True))] p = Symbol('p', positive=True) assert solve(absxm3 - p, x) == [-p + 3, p + 3] # issue 6989 f = Function('f') assert solve(Eq(-f(x), Piecewise((1, x > 0), (0, True))), f(x)) == \ [Piecewise((-1, x > 0), (0, True))] # issue 8587 f = Piecewise((2*x**2, And(0 < x, x < 1)), (2, True)) assert solve(f - 1) == [1/sqrt(2)] def test_piecewise_fold(): p = Piecewise((x, x < 1), (1, 1 <= x)) assert piecewise_fold(x*p) == Piecewise((x**2, x < 1), (x, 1 <= x)) assert piecewise_fold(p + p) == Piecewise((2*x, x < 1), (2, 1 <= x)) assert piecewise_fold(Piecewise((1, x < 0), (2, True)) + Piecewise((10, x < 0), (-10, True))) == \ Piecewise((11, x < 0), (-8, True)) p1 = Piecewise((0, x < 0), (x, x <= 1), (0, True)) p2 = Piecewise((0, x < 0), (1 - x, x <= 1), (0, True)) p = 4*p1 + 2*p2 assert integrate( piecewise_fold(p), (x, -oo, oo)) == integrate(2*x + 2, (x, 0, 1)) assert piecewise_fold( Piecewise((1, y <= 0), (-Piecewise((2, y >= 0)), True) )) == Piecewise((1, y <= 0), (-2, y >= 0)) assert piecewise_fold(Piecewise((x, ITE(x > 0, y < 1, y > 1))) ) == Piecewise((x, ((x <= 0) | (y < 1)) & ((x > 0) | (y > 1)))) a, b = (Piecewise((2, Eq(x, 0)), (0, True)), Piecewise((x, Eq(-x + y, 0)), (1, Eq(-x + y, 1)), (0, True))) assert piecewise_fold(Mul(a, b, evaluate=False) ) == piecewise_fold(Mul(b, a, evaluate=False)) def test_piecewise_fold_piecewise_in_cond(): p1 = Piecewise((cos(x), x < 0), (0, True)) p2 = Piecewise((0, Eq(p1, 0)), (p1 / Abs(p1), True)) assert p2.subs(x, -pi/2) == 0 assert p2.subs(x, 1) == 0 assert p2.subs(x, -pi/4) == 1 p4 = Piecewise((0, Eq(p1, 0)), (1,True)) ans = piecewise_fold(p4) for i in range(-1, 1): assert ans.subs(x, i) == p4.subs(x, i) r1 = 1 < Piecewise((1, x < 1), (3, True)) ans = piecewise_fold(r1) for i in range(2): assert ans.subs(x, i) == r1.subs(x, i) p5 = Piecewise((1, x < 0), (3, True)) p6 = Piecewise((1, x < 1), (3, True)) p7 = Piecewise((1, p5 < p6), (0, True)) ans = piecewise_fold(p7) for i in range(-1, 2): assert ans.subs(x, i) == p7.subs(x, i) def test_piecewise_fold_piecewise_in_cond_2(): p1 = Piecewise((cos(x), x < 0), (0, True)) p2 = Piecewise((0, Eq(p1, 0)), (1 / p1, True)) p3 = Piecewise( (0, (x >= 0) | Eq(cos(x), 0)), (1/cos(x), x < 0), (zoo, True)) # redundant b/c all x are already covered assert(piecewise_fold(p2) == p3) def test_piecewise_fold_expand(): p1 = Piecewise((1, Interval(0, 1, False, True).contains(x)), (0, True)) p2 = piecewise_fold(expand((1 - x)*p1)) assert p2 == Piecewise((1 - x, (x >= 0) & (x < 1)), (0, True)) assert p2 == expand(piecewise_fold((1 - x)*p1)) def test_piecewise_duplicate(): p = Piecewise((x, x < -10), (x**2, x <= -1), (x, 1 < x)) assert p == Piecewise(*p.args) def test_doit(): p1 = Piecewise((x, x < 1), (x**2, -1 <= x), (x, 3 < x)) p2 = Piecewise((x, x < 1), (Integral(2 * x), -1 <= x), (x, 3 < x)) assert p2.doit() == p1 assert p2.doit(deep=False) == p2 # issue 17165 p1 = Sum(y**x, (x, -1, oo)).doit() assert p1.doit() == p1 def test_piecewise_interval(): p1 = Piecewise((x, Interval(0, 1).contains(x)), (0, True)) assert p1.subs(x, -0.5) == 0 assert p1.subs(x, 0.5) == 0.5 assert p1.diff(x) == Piecewise((1, Interval(0, 1).contains(x)), (0, True)) assert integrate(p1, x) == Piecewise( (0, x <= 0), (x**2/2, x <= 1), (S.Half, True)) def test_piecewise_collapse(): assert Piecewise((x, True)) == x a = x < 1 assert Piecewise((x, a), (x + 1, a)) == Piecewise((x, a)) assert Piecewise((x, a), (x + 1, a.reversed)) == Piecewise((x, a)) b = x < 5 def canonical(i): if isinstance(i, Piecewise): return Piecewise(*i.args) return i for args in [ ((1, a), (Piecewise((2, a), (3, b)), b)), ((1, a), (Piecewise((2, a), (3, b.reversed)), b)), ((1, a), (Piecewise((2, a), (3, b)), b), (4, True)), ((1, a), (Piecewise((2, a), (3, b), (4, True)), b)), ((1, a), (Piecewise((2, a), (3, b), (4, True)), b), (5, True))]: for i in (0, 2, 10): assert canonical( Piecewise(*args, evaluate=False).subs(x, i) ) == canonical(Piecewise(*args).subs(x, i)) r1, r2, r3, r4 = symbols('r1:5') a = x < r1 b = x < r2 c = x < r3 d = x < r4 assert Piecewise((1, a), (Piecewise( (2, a), (3, b), (4, c)), b), (5, c) ) == Piecewise((1, a), (3, b), (5, c)) assert Piecewise((1, a), (Piecewise( (2, a), (3, b), (4, c), (6, True)), c), (5, d) ) == Piecewise((1, a), (Piecewise( (3, b), (4, c)), c), (5, d)) assert Piecewise((1, Or(a, d)), (Piecewise( (2, d), (3, b), (4, c)), b), (5, c) ) == Piecewise((1, Or(a, d)), (Piecewise( (2, d), (3, b)), b), (5, c)) assert Piecewise((1, c), (2, ~c), (3, S.true) ) == Piecewise((1, c), (2, S.true)) assert Piecewise((1, c), (2, And(~c, b)), (3,True) ) == Piecewise((1, c), (2, b), (3, True)) assert Piecewise((1, c), (2, Or(~c, b)), (3,True) ).subs(dict(zip((r1, r2, r3, r4, x), (1, 2, 3, 4, 3.5)))) == 2 assert Piecewise((1, c), (2, ~c)) == Piecewise((1, c), (2, True)) def test_piecewise_lambdify(): p = Piecewise( (x**2, x < 0), (x, Interval(0, 1, False, True).contains(x)), (2 - x, x >= 1), (0, True) ) f = lambdify(x, p) assert f(-2.0) == 4.0 assert f(0.0) == 0.0 assert f(0.5) == 0.5 assert f(2.0) == 0.0 def test_piecewise_series(): from sympy import sin, cos, O p1 = Piecewise((sin(x), x < 0), (cos(x), x > 0)) p2 = Piecewise((x + O(x**2), x < 0), (1 + O(x**2), x > 0)) assert p1.nseries(x, n=2) == p2 def test_piecewise_as_leading_term(): p1 = Piecewise((1/x, x > 1), (0, True)) p2 = Piecewise((x, x > 1), (0, True)) p3 = Piecewise((1/x, x > 1), (x, True)) p4 = Piecewise((x, x > 1), (1/x, True)) p5 = Piecewise((1/x, x > 1), (x, True)) p6 = Piecewise((1/x, x < 1), (x, True)) p7 = Piecewise((x, x < 1), (1/x, True)) p8 = Piecewise((x, x > 1), (1/x, True)) assert p1.as_leading_term(x) == 0 assert p2.as_leading_term(x) == 0 assert p3.as_leading_term(x) == x assert p4.as_leading_term(x) == 1/x assert p5.as_leading_term(x) == x assert p6.as_leading_term(x) == 1/x assert p7.as_leading_term(x) == x assert p8.as_leading_term(x) == 1/x def test_piecewise_complex(): p1 = Piecewise((2, x < 0), (1, 0 <= x)) p2 = Piecewise((2*I, x < 0), (I, 0 <= x)) p3 = Piecewise((I*x, x > 1), (1 + I, True)) p4 = Piecewise((-I*conjugate(x), x > 1), (1 - I, True)) assert conjugate(p1) == p1 assert conjugate(p2) == piecewise_fold(-p2) assert conjugate(p3) == p4 assert p1.is_imaginary is False assert p1.is_real is True assert p2.is_imaginary is True assert p2.is_real is False assert p3.is_imaginary is None assert p3.is_real is None assert p1.as_real_imag() == (p1, 0) assert p2.as_real_imag() == (0, -I*p2) def test_conjugate_transpose(): A, B = symbols("A B", commutative=False) p = Piecewise((A*B**2, x > 0), (A**2*B, True)) assert p.adjoint() == \ Piecewise((adjoint(A*B**2), x > 0), (adjoint(A**2*B), True)) assert p.conjugate() == \ Piecewise((conjugate(A*B**2), x > 0), (conjugate(A**2*B), True)) assert p.transpose() == \ Piecewise((transpose(A*B**2), x > 0), (transpose(A**2*B), True)) def test_piecewise_evaluate(): assert Piecewise((x, True)) == x assert Piecewise((x, True), evaluate=True) == x p = Piecewise((x, True), evaluate=False) assert p != x assert p.is_Piecewise assert all(isinstance(i, Basic) for i in p.args) assert Piecewise((1, Eq(1, x))).args == ((1, Eq(x, 1)),) assert Piecewise((1, Eq(1, x)), evaluate=False).args == ( (1, Eq(1, x)),) def test_as_expr_set_pairs(): assert Piecewise((x, x > 0), (-x, x <= 0)).as_expr_set_pairs() == \ [(x, Interval(0, oo, True, True)), (-x, Interval(-oo, 0))] assert Piecewise(((x - 2)**2, x >= 0), (0, True)).as_expr_set_pairs() == \ [((x - 2)**2, Interval(0, oo)), (0, Interval(-oo, 0, True, True))] def test_S_srepr_is_identity(): p = Piecewise((10, Eq(x, 0)), (12, True)) q = S(srepr(p)) assert p == q def test_issue_12587(): # sort holes into intervals p = Piecewise((1, x > 4), (2, Not((x <= 3) & (x > -1))), (3, True)) assert p.integrate((x, -5, 5)) == 23 p = Piecewise((1, x > 1), (2, x < y), (3, True)) lim = x, -3, 3 ans = p.integrate(lim) for i in range(-1, 3): assert ans.subs(y, i) == p.subs(y, i).integrate(lim) def test_issue_11045(): assert integrate(1/(x*sqrt(x**2 - 1)), (x, 1, 2)) == pi/3 # handle And with Or arguments assert Piecewise((1, And(Or(x < 1, x > 3), x < 2)), (0, True) ).integrate((x, 0, 3)) == 1 # hidden false assert Piecewise((1, x > 1), (2, x > x + 1), (3, True) ).integrate((x, 0, 3)) == 5 # targetcond is Eq assert Piecewise((1, x > 1), (2, Eq(1, x)), (3, True) ).integrate((x, 0, 4)) == 6 # And has Relational needing to be solved assert Piecewise((1, And(2*x > x + 1, x < 2)), (0, True) ).integrate((x, 0, 3)) == 1 # Or has Relational needing to be solved assert Piecewise((1, Or(2*x > x + 2, x < 1)), (0, True) ).integrate((x, 0, 3)) == 2 # ignore hidden false (handled in canonicalization) assert Piecewise((1, x > 1), (2, x > x + 1), (3, True) ).integrate((x, 0, 3)) == 5 # watch for hidden True Piecewise assert Piecewise((2, Eq(1 - x, x*(1/x - 1))), (0, True) ).integrate((x, 0, 3)) == 6 # overlapping conditions of targetcond are recognized and ignored; # the condition x > 3 will be pre-empted by the first condition assert Piecewise((1, Or(x < 1, x > 2)), (2, x > 3), (3, True) ).integrate((x, 0, 4)) == 6 # convert Ne to Or assert Piecewise((1, Ne(x, 0)), (2, True) ).integrate((x, -1, 1)) == 2 # no default but well defined assert Piecewise((x, (x > 1) & (x < 3)), (1, (x < 4)) ).integrate((x, 1, 4)) == 5 p = Piecewise((x, (x > 1) & (x < 3)), (1, (x < 4))) nan = Undefined i = p.integrate((x, 1, y)) assert i == Piecewise( (y - 1, y < 1), (Min(3, y)**2/2 - Min(3, y) + Min(4, y) - S.Half, y <= Min(4, y)), (nan, True)) assert p.integrate((x, 1, -1)) == i.subs(y, -1) assert p.integrate((x, 1, 4)) == 5 assert p.integrate((x, 1, 5)) is nan # handle Not p = Piecewise((1, x > 1), (2, Not(And(x > 1, x< 3))), (3, True)) assert p.integrate((x, 0, 3)) == 4 # handle updating of int_expr when there is overlap p = Piecewise( (1, And(5 > x, x > 1)), (2, Or(x < 3, x > 7)), (4, x < 8)) assert p.integrate((x, 0, 10)) == 20 # And with Eq arg handling assert Piecewise((1, x < 1), (2, And(Eq(x, 3), x > 1)) ).integrate((x, 0, 3)) is S.NaN assert Piecewise((1, x < 1), (2, And(Eq(x, 3), x > 1)), (3, True) ).integrate((x, 0, 3)) == 7 assert Piecewise((1, x < 0), (2, And(Eq(x, 3), x < 1)), (3, True) ).integrate((x, -1, 1)) == 4 # middle condition doesn't matter: it's a zero width interval assert Piecewise((1, x < 1), (2, Eq(x, 3) & (y < x)), (3, True) ).integrate((x, 0, 3)) == 7 def test_holes(): nan = Undefined assert Piecewise((1, x < 2)).integrate(x) == Piecewise( (x, x < 2), (nan, True)) assert Piecewise((1, And(x > 1, x < 2))).integrate(x) == Piecewise( (nan, x < 1), (x - 1, x < 2), (nan, True)) assert Piecewise((1, And(x > 1, x < 2))).integrate((x, 0, 3)) is nan assert Piecewise((1, And(x > 0, x < 4))).integrate((x, 1, 3)) == 2 # this also tests that the integrate method is used on non-Piecwise # arguments in _eval_integral A, B = symbols("A B") a, b = symbols('a b', real=True) assert Piecewise((A, And(x < 0, a < 1)), (B, Or(x < 1, a > 2)) ).integrate(x) == Piecewise( (B*x, (a > 2)), (Piecewise((A*x, x < 0), (B*x, x < 1), (nan, True)), a < 1), (Piecewise((B*x, x < 1), (nan, True)), True)) def test_issue_11922(): def f(x): return Piecewise((0, x < -1), (1 - x**2, x < 1), (0, True)) autocorr = lambda k: ( f(x) * f(x + k)).integrate((x, -1, 1)) assert autocorr(1.9) > 0 k = symbols('k') good_autocorr = lambda k: ( (1 - x**2) * f(x + k)).integrate((x, -1, 1)) a = good_autocorr(k) assert a.subs(k, 3) == 0 k = symbols('k', positive=True) a = good_autocorr(k) assert a.subs(k, 3) == 0 assert Piecewise((0, x < 1), (10, (x >= 1)) ).integrate() == Piecewise((0, x < 1), (10*x - 10, True)) def test_issue_5227(): f = 0.0032513612725229*Piecewise((0, x < -80.8461538461539), (-0.0160799238820171*x + 1.33215984776403, x < 2), (Piecewise((0.3, x > 123), (0.7, True)) + Piecewise((0.4, x > 2), (0.6, True)), x <= 123), (-0.00817409766454352*x + 2.10541401273885, x < 380.571428571429), (0, True)) i = integrate(f, (x, -oo, oo)) assert i == Integral(f, (x, -oo, oo)).doit() assert str(i) == '1.00195081676351' assert Piecewise((1, x - y < 0), (0, True) ).integrate(y) == Piecewise((0, y <= x), (-x + y, True)) def test_issue_10137(): a = Symbol('a', real=True, finite=True) b = Symbol('b', real=True, finite=True) x = Symbol('x', real=True, finite=True) y = Symbol('y', real=True, finite=True) p0 = Piecewise((0, Or(x < a, x > b)), (1, True)) p1 = Piecewise((0, Or(a > x, b < x)), (1, True)) assert integrate(p0, (x, y, oo)) == integrate(p1, (x, y, oo)) p3 = Piecewise((1, And(0 < x, x < a)), (0, True)) p4 = Piecewise((1, And(a > x, x > 0)), (0, True)) ip3 = integrate(p3, x) assert ip3 == Piecewise( (0, x <= 0), (x, x <= Max(0, a)), (Max(0, a), True)) ip4 = integrate(p4, x) assert ip4 == ip3 assert p3.integrate((x, 2, 4)) == Min(4, Max(2, a)) - 2 assert p4.integrate((x, 2, 4)) == Min(4, Max(2, a)) - 2 def test_stackoverflow_43852159(): f = lambda x: Piecewise((1 , (x >= -1) & (x <= 1)) , (0, True)) Conv = lambda x: integrate(f(x - y)*f(y), (y, -oo, +oo)) cx = Conv(x) assert cx.subs(x, -1.5) == cx.subs(x, 1.5) assert cx.subs(x, 3) == 0 assert piecewise_fold(f(x - y)*f(y)) == Piecewise( (1, (y >= -1) & (y <= 1) & (x - y >= -1) & (x - y <= 1)), (0, True)) def test_issue_12557(): ''' # 3200 seconds to compute the fourier part of issue import sympy as sym x,y,z,t = sym.symbols('x y z t') k = sym.symbols("k", integer=True) fourier = sym.fourier_series(sym.cos(k*x)*sym.sqrt(x**2), (x, -sym.pi, sym.pi)) assert fourier == FourierSeries( sqrt(x**2)*cos(k*x), (x, -pi, pi), (Piecewise((pi**2, Eq(k, 0)), (2*(-1)**k/k**2 - 2/k**2, True))/(2*pi), SeqFormula(Piecewise((pi**2, (Eq(_n, 0) & Eq(k, 0)) | (Eq(_n, 0) & Eq(_n, k) & Eq(k, 0)) | (Eq(_n, 0) & Eq(k, 0) & Eq(_n, -k)) | (Eq(_n, 0) & Eq(_n, k) & Eq(k, 0) & Eq(_n, -k))), (pi**2/2, Eq(_n, k) | Eq(_n, -k) | (Eq(_n, 0) & Eq(_n, k)) | (Eq(_n, k) & Eq(k, 0)) | (Eq(_n, 0) & Eq(_n, -k)) | (Eq(_n, k) & Eq(_n, -k)) | (Eq(k, 0) & Eq(_n, -k)) | (Eq(_n, 0) & Eq(_n, k) & Eq(_n, -k)) | (Eq(_n, k) & Eq(k, 0) & Eq(_n, -k))), ((-1)**k*pi**2*_n**3*sin(pi*_n)/(pi*_n**4 - 2*pi*_n**2*k**2 + pi*k**4) - (-1)**k*pi**2*_n**3*sin(pi*_n)/(-pi*_n**4 + 2*pi*_n**2*k**2 - pi*k**4) + (-1)**k*pi*_n**2*cos(pi*_n)/(pi*_n**4 - 2*pi*_n**2*k**2 + pi*k**4) - (-1)**k*pi*_n**2*cos(pi*_n)/(-pi*_n**4 + 2*pi*_n**2*k**2 - pi*k**4) - (-1)**k*pi**2*_n*k**2*sin(pi*_n)/(pi*_n**4 - 2*pi*_n**2*k**2 + pi*k**4) + (-1)**k*pi**2*_n*k**2*sin(pi*_n)/(-pi*_n**4 + 2*pi*_n**2*k**2 - pi*k**4) + (-1)**k*pi*k**2*cos(pi*_n)/(pi*_n**4 - 2*pi*_n**2*k**2 + pi*k**4) - (-1)**k*pi*k**2*cos(pi*_n)/(-pi*_n**4 + 2*pi*_n**2*k**2 - pi*k**4) - (2*_n**2 + 2*k**2)/(_n**4 - 2*_n**2*k**2 + k**4), True))*cos(_n*x)/pi, (_n, 1, oo)), SeqFormula(0, (_k, 1, oo)))) ''' x = symbols("x", real=True) k = symbols('k', integer=True, finite=True) abs2 = lambda x: Piecewise((-x, x <= 0), (x, x > 0)) assert integrate(abs2(x), (x, -pi, pi)) == pi**2 func = cos(k*x)*sqrt(x**2) assert integrate(func, (x, -pi, pi)) == Piecewise( (2*(-1)**k/k**2 - 2/k**2, Ne(k, 0)), (pi**2, True)) def test_issue_6900(): from itertools import permutations t0, t1, T, t = symbols('t0, t1 T t') f = Piecewise((0, t < t0), (x, And(t0 <= t, t < t1)), (0, t >= t1)) g = f.integrate(t) assert g == Piecewise( (0, t <= t0), (t*x - t0*x, t <= Max(t0, t1)), (-t0*x + x*Max(t0, t1), True)) for i in permutations(range(2)): reps = dict(zip((t0,t1), i)) for tt in range(-1,3): assert (g.xreplace(reps).subs(t,tt) == f.xreplace(reps).integrate(t).subs(t,tt)) lim = Tuple(t, t0, T) g = f.integrate(lim) ans = Piecewise( (-t0*x + x*Min(T, Max(t0, t1)), T > t0), (0, True)) for i in permutations(range(3)): reps = dict(zip((t0,t1,T), i)) tru = f.xreplace(reps).integrate(lim.xreplace(reps)) assert tru == ans.xreplace(reps) assert g == ans def test_issue_10122(): assert solve(abs(x) + abs(x - 1) - 1 > 0, x ) == Or(And(-oo < x, x < S.Zero), And(S.One < x, x < oo)) def test_issue_4313(): u = Piecewise((0, x <= 0), (1, x >= a), (x/a, True)) e = (u - u.subs(x, y))**2/(x - y)**2 M = Max(0, a) assert integrate(e, x).expand() == Piecewise( (Piecewise( (0, x <= 0), (-y**2/(a**2*x - a**2*y) + x/a**2 - 2*y*log(-y)/a**2 + 2*y*log(x - y)/a**2 - y/a**2, x <= M), (-y**2/(-a**2*y + a**2*M) + 1/(-y + M) - 1/(x - y) - 2*y*log(-y)/a**2 + 2*y*log(-y + M)/a**2 - y/a**2 + M/a**2, True)), ((a <= y) & (y <= 0)) | ((y <= 0) & (y > -oo))), (Piecewise( (-1/(x - y), x <= 0), (-a**2/(a**2*x - a**2*y) + 2*a*y/(a**2*x - a**2*y) - y**2/(a**2*x - a**2*y) + 2*log(-y)/a - 2*log(x - y)/a + 2/a + x/a**2 - 2*y*log(-y)/a**2 + 2*y*log(x - y)/a**2 - y/a**2, x <= M), (-a**2/(-a**2*y + a**2*M) + 2*a*y/(-a**2*y + a**2*M) - y**2/(-a**2*y + a**2*M) + 2*log(-y)/a - 2*log(-y + M)/a + 2/a - 2*y*log(-y)/a**2 + 2*y*log(-y + M)/a**2 - y/a**2 + M/a**2, True)), a <= y), (Piecewise( (-y**2/(a**2*x - a**2*y), x <= 0), (x/a**2 + y/a**2, x <= M), (a**2/(-a**2*y + a**2*M) - a**2/(a**2*x - a**2*y) - 2*a*y/(-a**2*y + a**2*M) + 2*a*y/(a**2*x - a**2*y) + y**2/(-a**2*y + a**2*M) - y**2/(a**2*x - a**2*y) + y/a**2 + M/a**2, True)), True)) def test__intervals(): assert Piecewise((x + 2, Eq(x, 3)))._intervals(x) == [] assert Piecewise( (1, x > x + 1), (Piecewise((1, x < x + 1)), 2*x < 2*x + 1), (1, True))._intervals(x) == [(-oo, oo, 1, 1)] assert Piecewise((1, Ne(x, I)), (0, True))._intervals(x) == [ (-oo, oo, 1, 0)] assert Piecewise((-cos(x), sin(x) >= 0), (cos(x), True) )._intervals(x) == [(0, pi, -cos(x), 0), (-oo, oo, cos(x), 1)] # the following tests that duplicates are removed and that non-Eq # generated zero-width intervals are removed assert Piecewise((1, Abs(x**(-2)) > 1), (0, True) )._intervals(x) == [(-1, 0, 1, 0), (0, 1, 1, 0), (-oo, oo, 0, 1)] def test_containment(): a, b, c, d, e = [1, 2, 3, 4, 5] p = (Piecewise((d, x > 1), (e, True))* Piecewise((a, Abs(x - 1) < 1), (b, Abs(x - 2) < 2), (c, True))) assert p.integrate(x).diff(x) == Piecewise( (c*e, x <= 0), (a*e, x <= 1), (a*d, x < 2), # this is what we want to get right (b*d, x < 4), (c*d, True)) def test_piecewise_with_DiracDelta(): d1 = DiracDelta(x - 1) assert integrate(d1, (x, -oo, oo)) == 1 assert integrate(d1, (x, 0, 2)) == 1 assert Piecewise((d1, Eq(x, 2)), (0, True)).integrate(x) == 0 assert Piecewise((d1, x < 2), (0, True)).integrate(x) == Piecewise( (Heaviside(x - 1), x < 2), (1, True)) # TODO raise error if function is discontinuous at limit of # integration, e.g. integrate(d1, (x, -2, 1)) or Piecewise( # (d1, Eq(x ,1) def test_issue_10258(): assert Piecewise((0, x < 1), (1, True)).is_zero is None assert Piecewise((-1, x < 1), (1, True)).is_zero is False a = Symbol('a', zero=True) assert Piecewise((0, x < 1), (a, True)).is_zero assert Piecewise((1, x < 1), (a, x < 3)).is_zero is None a = Symbol('a') assert Piecewise((0, x < 1), (a, True)).is_zero is None assert Piecewise((0, x < 1), (1, True)).is_nonzero is None assert Piecewise((1, x < 1), (2, True)).is_nonzero assert Piecewise((0, x < 1), (oo, True)).is_finite is None assert Piecewise((0, x < 1), (1, True)).is_finite b = Basic() assert Piecewise((b, x < 1)).is_finite is None # 10258 c = Piecewise((1, x < 0), (2, True)) < 3 assert c != True assert piecewise_fold(c) == True def test_issue_10087(): a, b = Piecewise((x, x > 1), (2, True)), Piecewise((x, x > 3), (3, True)) m = a*b f = piecewise_fold(m) for i in (0, 2, 4): assert m.subs(x, i) == f.subs(x, i) m = a + b f = piecewise_fold(m) for i in (0, 2, 4): assert m.subs(x, i) == f.subs(x, i) def test_issue_8919(): c = symbols('c:5') x = symbols("x") f1 = Piecewise((c[1], x < 1), (c[2], True)) f2 = Piecewise((c[3], x < Rational(1, 3)), (c[4], True)) assert integrate(f1*f2, (x, 0, 2) ) == c[1]*c[3]/3 + 2*c[1]*c[4]/3 + c[2]*c[4] f1 = Piecewise((0, x < 1), (2, True)) f2 = Piecewise((3, x < 2), (0, True)) assert integrate(f1*f2, (x, 0, 3)) == 6 y = symbols("y", positive=True) a, b, c, x, z = symbols("a,b,c,x,z", real=True) I = Integral(Piecewise( (0, (x >= y) | (x < 0) | (b > c)), (a, True)), (x, 0, z)) ans = I.doit() assert ans == Piecewise((0, b > c), (a*Min(y, z) - a*Min(0, z), True)) for cond in (True, False): for yy in range(1, 3): for zz in range(-yy, 0, yy): reps = [(b > c, cond), (y, yy), (z, zz)] assert ans.subs(reps) == I.subs(reps).doit() def test_unevaluated_integrals(): f = Function('f') p = Piecewise((1, Eq(f(x) - 1, 0)), (2, x - 10 < 0), (0, True)) assert p.integrate(x) == Integral(p, x) assert p.integrate((x, 0, 5)) == Integral(p, (x, 0, 5)) # test it by replacing f(x) with x%2 which will not # affect the answer: the integrand is essentially 2 over # the domain of integration assert Integral(p, (x, 0, 5)).subs(f(x), x%2).n() == 10 # this is a test of using _solve_inequality when # solve_univariate_inequality fails assert p.integrate(y) == Piecewise( (y, Eq(f(x), 1) | ((x < 10) & Eq(f(x), 1))), (2*y, (x >= -oo) & (x < 10)), (0, True)) def test_conditions_as_alternate_booleans(): a, b, c = symbols('a:c') assert Piecewise((x, Piecewise((y < 1, x > 0), (y > 1, True))) ) == Piecewise((x, ITE(x > 0, y < 1, y > 1))) def test_Piecewise_rewrite_as_ITE(): a, b, c, d = symbols('a:d') def _ITE(*args): return Piecewise(*args).rewrite(ITE) assert _ITE((a, x < 1), (b, x >= 1)) == ITE(x < 1, a, b) assert _ITE((a, x < 1), (b, x < oo)) == ITE(x < 1, a, b) assert _ITE((a, x < 1), (b, Or(y < 1, x < oo)), (c, y > 0) ) == ITE(x < 1, a, b) assert _ITE((a, x < 1), (b, True)) == ITE(x < 1, a, b) assert _ITE((a, x < 1), (b, x < 2), (c, True) ) == ITE(x < 1, a, ITE(x < 2, b, c)) assert _ITE((a, x < 1), (b, y < 2), (c, True) ) == ITE(x < 1, a, ITE(y < 2, b, c)) assert _ITE((a, x < 1), (b, x < oo), (c, y < 1) ) == ITE(x < 1, a, b) assert _ITE((a, x < 1), (c, y < 1), (b, x < oo), (d, True) ) == ITE(x < 1, a, ITE(y < 1, c, b)) assert _ITE((a, x < 0), (b, Or(x < oo, y < 1)) ) == ITE(x < 0, a, b) raises(TypeError, lambda: _ITE((x + 1, x < 1), (x, True))) # if `a` in the following were replaced with y then the coverage # is complete but something other than as_set would need to be # used to detect this raises(NotImplementedError, lambda: _ITE((x, x < y), (y, x >= a))) raises(ValueError, lambda: _ITE((a, x < 2), (b, x > 3))) def test_issue_14052(): assert integrate(abs(sin(x)), (x, 0, 2*pi)) == 4 def test_issue_14240(): assert piecewise_fold( Piecewise((1, a), (2, b), (4, True)) + Piecewise((8, a), (16, True)) ) == Piecewise((9, a), (18, b), (20, True)) assert piecewise_fold( Piecewise((2, a), (3, b), (5, True)) * Piecewise((7, a), (11, True)) ) == Piecewise((14, a), (33, b), (55, True)) # these will hang if naive folding is used assert piecewise_fold(Add(*[ Piecewise((i, a), (0, True)) for i in range(40)]) ) == Piecewise((780, a), (0, True)) assert piecewise_fold(Mul(*[ Piecewise((i, a), (0, True)) for i in range(1, 41)]) ) == Piecewise((factorial(40), a), (0, True)) def test_issue_14787(): x = Symbol('x') f = Piecewise((x, x < 1), ((S(58) / 7), True)) assert str(f.evalf()) == "Piecewise((x, x < 1), (8.28571428571429, True))" def test_issue_8458(): x, y = symbols('x y') # Original issue p1 = Piecewise((0, Eq(x, 0)), (sin(x), True)) assert p1.simplify() == sin(x) # Slightly larger variant p2 = Piecewise((x, Eq(x, 0)), (4*x + (y-2)**4, Eq(x, 0) & Eq(x+y, 2)), (sin(x), True)) assert p2.simplify() == sin(x) # Test for problem highlighted during review p3 = Piecewise((x+1, Eq(x, -1)), (4*x + (y-2)**4, Eq(x, 0) & Eq(x+y, 2)), (sin(x), True)) assert p3.simplify() == Piecewise((0, Eq(x, -1)), (sin(x), True)) def test_issue_16417(): from sympy import im, re, Gt z = Symbol('z') assert unchanged(Piecewise, (1, Or(Eq(im(z), 0), Gt(re(z), 0))), (2, True)) x = Symbol('x') assert unchanged(Piecewise, (S.Pi, re(x) < 0), (0, Or(re(x) > 0, Ne(im(x), 0))), (S.NaN, True)) r = Symbol('r', real=True) p = Piecewise((S.Pi, re(r) < 0), (0, Or(re(r) > 0, Ne(im(r), 0))), (S.NaN, True)) assert p == Piecewise((S.Pi, r < 0), (0, r > 0), (S.NaN, True), evaluate=False) # Does not work since imaginary != 0... #i = Symbol('i', imaginary=True) #p = Piecewise((S.Pi, re(i) < 0), # (0, Or(re(i) > 0, Ne(im(i), 0))), # (S.NaN, True)) #assert p == Piecewise((0, Ne(im(i), 0)), # (S.NaN, True), evaluate=False) i = I*r p = Piecewise((S.Pi, re(i) < 0), (0, Or(re(i) > 0, Ne(im(i), 0))), (S.NaN, True)) assert p == Piecewise((0, Ne(im(i), 0)), (S.NaN, True), evaluate=False) assert p == Piecewise((0, Ne(r, 0)), (S.NaN, True), evaluate=False) def test_eval_rewrite_as_KroneckerDelta(): x, y, z, n, t, m = symbols('x y z n t m') K = KroneckerDelta f = lambda p: expand(p.rewrite(K)) p1 = Piecewise((0, Eq(x, y)), (1, True)) assert f(p1) == 1 - K(x, y) p2 = Piecewise((x, Eq(y,0)), (z, Eq(t,0)), (n, True)) assert f(p2) == n*K(0, t)*K(0, y) - n*K(0, t) - n*K(0, y) + n + \ x*K(0, y) - z*K(0, t)*K(0, y) + z*K(0, t) p3 = Piecewise((1, Ne(x, y)), (0, True)) assert f(p3) == 1 - K(x, y) p4 = Piecewise((1, Eq(x, 3)), (4, True), (5, True)) assert f(p4) == 4 - 3*K(3, x) p5 = Piecewise((3, Ne(x, 2)), (4, Eq(y, 2)), (5, True)) assert f(p5) == -K(2, x)*K(2, y) + 2*K(2, x) + 3 p6 = Piecewise((0, Ne(x, 1) & Ne(y, 4)), (1, True)) assert f(p6) == -K(1, x)*K(4, y) + K(1, x) + K(4, y) p7 = Piecewise((2, Eq(y, 3) & Ne(x, 2)), (1, True)) assert f(p7) == -K(2, x)*K(3, y) + K(3, y) + 1 p8 = Piecewise((4, Eq(x, 3) & Ne(y, 2)), (1, True)) assert f(p8) == -3*K(2, y)*K(3, x) + 3*K(3, x) + 1 p9 = Piecewise((6, Eq(x, 4) & Eq(y, 1)), (1, True)) assert f(p9) == 5 * K(1, y) * K(4, x) + 1 p10 = Piecewise((4, Ne(x, -4) | Ne(y, 1)), (1, True)) assert f(p10) == -3 * K(-4, x) * K(1, y) + 4 p11 = Piecewise((1, Eq(y, 2) | Ne(x, -3)), (2, True)) assert f(p11) == -K(-3, x)*K(2, y) + K(-3, x) + 1 p12 = Piecewise((-1, Eq(x, 1) | Ne(y, 3)), (1, True)) assert f(p12) == -2*K(1, x)*K(3, y) + 2*K(3, y) - 1 p13 = Piecewise((3, Eq(x, 2) | Eq(y, 4)), (1, True)) assert f(p13) == -2*K(2, x)*K(4, y) + 2*K(2, x) + 2*K(4, y) + 1 p14 = Piecewise((1, Ne(x, 0) | Ne(y, 1)), (3, True)) assert f(p14) == 2 * K(0, x) * K(1, y) + 1 p15 = Piecewise((2, Eq(x, 3) | Ne(y, 2)), (3, Eq(x, 4) & Eq(y, 5)), (1, True)) assert f(p15) == -2*K(2, y)*K(3, x)*K(4, x)*K(5, y) + K(2, y)*K(3, x) + \ 2*K(2, y)*K(4, x)*K(5, y) - K(2, y) + 2 p16 = Piecewise((0, Ne(m, n)), (1, True))*Piecewise((0, Ne(n, t)), (1, True))\ *Piecewise((0, Ne(n, x)), (1, True)) - Piecewise((0, Ne(t, x)), (1, True)) assert f(p16) == K(m, n)*K(n, t)*K(n, x) - K(t, x) p17 = Piecewise((0, Ne(t, x) & (Ne(m, n) | Ne(n, t) | Ne(n, x))), (1, Ne(t, x)), (-1, Ne(m, n) | Ne(n, t) | Ne(n, x)), (0, True)) assert f(p17) == K(m, n)*K(n, t)*K(n, x) - K(t, x) p18 = Piecewise((-4, Eq(y, 1) | (Eq(x, -5) & Eq(x, z))), (4, True)) assert f(p18) == 8*K(-5, x)*K(1, y)*K(x, z) - 8*K(-5, x)*K(x, z) - 8*K(1, y) + 4 p19 = Piecewise((0, x > 2), (1, True)) assert f(p19) == p19 p20 = Piecewise((0, And(x < 2, x > -5)), (1, True)) assert f(p20) == p20 p21 = Piecewise((0, Or(x > 1, x < 0)), (1, True)) assert f(p21) == p21 p22 = Piecewise((0, ~((Eq(y, -1) | Ne(x, 0)) & (Ne(x, 1) | Ne(y, -1)))), (1, True)) assert f(p22) == K(-1, y)*K(0, x) - K(-1, y)*K(1, x) - K(0, x) + 1 @slow def test_identical_conds_issue(): from sympy.stats import Uniform, density u1 = Uniform('u1', 0, 1) u2 = Uniform('u2', 0, 1) # Result is quite big, so not really important here (and should ideally be # simpler). Should not give an exception though. density(u1 + u2) def test_issue_7370(): f = Piecewise((1, x <= 2400)) v = integrate(f, (x, 0, Float("252.4", 30))) assert str(v) == '252.400000000000000000000000000' def test_issue_16715(): raises(NotImplementedError, lambda: Piecewise((x, x<0), (0, y>1)).as_expr_set_pairs())
d29b4637b09796c6cafb856a56b0f02e49b158afe5d076251b1307b6373e5b13
import itertools as it from sympy.core.expr import unchanged from sympy.core.function import Function from sympy.core.numbers import I, oo, Rational from sympy.core.power import Pow from sympy.core.singleton import S from sympy.core.symbol import Symbol from sympy.external import import_module from sympy.functions.elementary.exponential import log from sympy.functions.elementary.integers import floor, ceiling from sympy.functions.elementary.miscellaneous import (sqrt, cbrt, root, Min, Max, real_root) from sympy.functions.elementary.trigonometric import cos, sin from sympy.functions.special.delta_functions import Heaviside from sympy.utilities.lambdify import lambdify from sympy.testing.pytest import raises, skip, ignore_warnings def test_Min(): from sympy.abc import x, y, z n = Symbol('n', negative=True) n_ = Symbol('n_', negative=True) nn = Symbol('nn', nonnegative=True) nn_ = Symbol('nn_', nonnegative=True) p = Symbol('p', positive=True) p_ = Symbol('p_', positive=True) np = Symbol('np', nonpositive=True) np_ = Symbol('np_', nonpositive=True) r = Symbol('r', real=True) assert Min(5, 4) == 4 assert Min(-oo, -oo) is -oo assert Min(-oo, n) is -oo assert Min(n, -oo) is -oo assert Min(-oo, np) is -oo assert Min(np, -oo) is -oo assert Min(-oo, 0) is -oo assert Min(0, -oo) is -oo assert Min(-oo, nn) is -oo assert Min(nn, -oo) is -oo assert Min(-oo, p) is -oo assert Min(p, -oo) is -oo assert Min(-oo, oo) is -oo assert Min(oo, -oo) is -oo assert Min(n, n) == n assert unchanged(Min, n, np) assert Min(np, n) == Min(n, np) assert Min(n, 0) == n assert Min(0, n) == n assert Min(n, nn) == n assert Min(nn, n) == n assert Min(n, p) == n assert Min(p, n) == n assert Min(n, oo) == n assert Min(oo, n) == n assert Min(np, np) == np assert Min(np, 0) == np assert Min(0, np) == np assert Min(np, nn) == np assert Min(nn, np) == np assert Min(np, p) == np assert Min(p, np) == np assert Min(np, oo) == np assert Min(oo, np) == np assert Min(0, 0) == 0 assert Min(0, nn) == 0 assert Min(nn, 0) == 0 assert Min(0, p) == 0 assert Min(p, 0) == 0 assert Min(0, oo) == 0 assert Min(oo, 0) == 0 assert Min(nn, nn) == nn assert unchanged(Min, nn, p) assert Min(p, nn) == Min(nn, p) assert Min(nn, oo) == nn assert Min(oo, nn) == nn assert Min(p, p) == p assert Min(p, oo) == p assert Min(oo, p) == p assert Min(oo, oo) is oo assert Min(n, n_).func is Min assert Min(nn, nn_).func is Min assert Min(np, np_).func is Min assert Min(p, p_).func is Min # lists assert Min() is S.Infinity assert Min(x) == x assert Min(x, y) == Min(y, x) assert Min(x, y, z) == Min(z, y, x) assert Min(x, Min(y, z)) == Min(z, y, x) assert Min(x, Max(y, -oo)) == Min(x, y) assert Min(p, oo, n, p, p, p_) == n assert Min(p_, n_, p) == n_ assert Min(n, oo, -7, p, p, 2) == Min(n, -7) assert Min(2, x, p, n, oo, n_, p, 2, -2, -2) == Min(-2, x, n, n_) assert Min(0, x, 1, y) == Min(0, x, y) assert Min(1000, 100, -100, x, p, n) == Min(n, x, -100) assert unchanged(Min, sin(x), cos(x)) assert Min(sin(x), cos(x)) == Min(cos(x), sin(x)) assert Min(cos(x), sin(x)).subs(x, 1) == cos(1) assert Min(cos(x), sin(x)).subs(x, S.Half) == sin(S.Half) raises(ValueError, lambda: Min(cos(x), sin(x)).subs(x, I)) raises(ValueError, lambda: Min(I)) raises(ValueError, lambda: Min(I, x)) raises(ValueError, lambda: Min(S.ComplexInfinity, x)) assert Min(1, x).diff(x) == Heaviside(1 - x) assert Min(x, 1).diff(x) == Heaviside(1 - x) assert Min(0, -x, 1 - 2*x).diff(x) == -Heaviside(x + Min(0, -2*x + 1)) \ - 2*Heaviside(2*x + Min(0, -x) - 1) # issue 7619 f = Function('f') assert Min(1, 2*Min(f(1), 2)) # doesn't fail # issue 7233 e = Min(0, x) assert e.n().args == (0, x) # issue 8643 m = Min(n, p_, n_, r) assert m.is_positive is False assert m.is_nonnegative is False assert m.is_negative is True m = Min(p, p_) assert m.is_positive is True assert m.is_nonnegative is True assert m.is_negative is False m = Min(p, nn_, p_) assert m.is_positive is None assert m.is_nonnegative is True assert m.is_negative is False m = Min(nn, p, r) assert m.is_positive is None assert m.is_nonnegative is None assert m.is_negative is None def test_Max(): from sympy.abc import x, y, z n = Symbol('n', negative=True) n_ = Symbol('n_', negative=True) nn = Symbol('nn', nonnegative=True) p = Symbol('p', positive=True) p_ = Symbol('p_', positive=True) r = Symbol('r', real=True) assert Max(5, 4) == 5 # lists assert Max() is S.NegativeInfinity assert Max(x) == x assert Max(x, y) == Max(y, x) assert Max(x, y, z) == Max(z, y, x) assert Max(x, Max(y, z)) == Max(z, y, x) assert Max(x, Min(y, oo)) == Max(x, y) assert Max(n, -oo, n_, p, 2) == Max(p, 2) assert Max(n, -oo, n_, p) == p assert Max(2, x, p, n, -oo, S.NegativeInfinity, n_, p, 2) == Max(2, x, p) assert Max(0, x, 1, y) == Max(1, x, y) assert Max(r, r + 1, r - 1) == 1 + r assert Max(1000, 100, -100, x, p, n) == Max(p, x, 1000) assert Max(cos(x), sin(x)) == Max(sin(x), cos(x)) assert Max(cos(x), sin(x)).subs(x, 1) == sin(1) assert Max(cos(x), sin(x)).subs(x, S.Half) == cos(S.Half) raises(ValueError, lambda: Max(cos(x), sin(x)).subs(x, I)) raises(ValueError, lambda: Max(I)) raises(ValueError, lambda: Max(I, x)) raises(ValueError, lambda: Max(S.ComplexInfinity, 1)) assert Max(n, -oo, n_, p, 2) == Max(p, 2) assert Max(n, -oo, n_, p, 1000) == Max(p, 1000) assert Max(1, x).diff(x) == Heaviside(x - 1) assert Max(x, 1).diff(x) == Heaviside(x - 1) assert Max(x**2, 1 + x, 1).diff(x) == \ 2*x*Heaviside(x**2 - Max(1, x + 1)) \ + Heaviside(x - Max(1, x**2) + 1) e = Max(0, x) assert e.n().args == (0, x) # issue 8643 m = Max(p, p_, n, r) assert m.is_positive is True assert m.is_nonnegative is True assert m.is_negative is False m = Max(n, n_) assert m.is_positive is False assert m.is_nonnegative is False assert m.is_negative is True m = Max(n, n_, r) assert m.is_positive is None assert m.is_nonnegative is None assert m.is_negative is None m = Max(n, nn, r) assert m.is_positive is None assert m.is_nonnegative is True assert m.is_negative is False def test_minmax_assumptions(): r = Symbol('r', real=True) a = Symbol('a', real=True, algebraic=True) t = Symbol('t', real=True, transcendental=True) q = Symbol('q', rational=True) p = Symbol('p', irrational=True) n = Symbol('n', rational=True, integer=False) i = Symbol('i', integer=True) o = Symbol('o', odd=True) e = Symbol('e', even=True) k = Symbol('k', prime=True) reals = [r, a, t, q, p, n, i, o, e, k] for ext in (Max, Min): for x, y in it.product(reals, repeat=2): # Must be real assert ext(x, y).is_real # Algebraic? if x.is_algebraic and y.is_algebraic: assert ext(x, y).is_algebraic elif x.is_transcendental and y.is_transcendental: assert ext(x, y).is_transcendental else: assert ext(x, y).is_algebraic is None # Rational? if x.is_rational and y.is_rational: assert ext(x, y).is_rational elif x.is_irrational and y.is_irrational: assert ext(x, y).is_irrational else: assert ext(x, y).is_rational is None # Integer? if x.is_integer and y.is_integer: assert ext(x, y).is_integer elif x.is_noninteger and y.is_noninteger: assert ext(x, y).is_noninteger else: assert ext(x, y).is_integer is None # Odd? if x.is_odd and y.is_odd: assert ext(x, y).is_odd elif x.is_odd is False and y.is_odd is False: assert ext(x, y).is_odd is False else: assert ext(x, y).is_odd is None # Even? if x.is_even and y.is_even: assert ext(x, y).is_even elif x.is_even is False and y.is_even is False: assert ext(x, y).is_even is False else: assert ext(x, y).is_even is None # Prime? if x.is_prime and y.is_prime: assert ext(x, y).is_prime elif x.is_prime is False and y.is_prime is False: assert ext(x, y).is_prime is False else: assert ext(x, y).is_prime is None def test_issue_8413(): x = Symbol('x', real=True) # we can't evaluate in general because non-reals are not # comparable: Min(floor(3.2 + I), 3.2 + I) -> ValueError assert Min(floor(x), x) == floor(x) assert Min(ceiling(x), x) == x assert Max(floor(x), x) == x assert Max(ceiling(x), x) == ceiling(x) def test_root(): from sympy.abc import x n = Symbol('n', integer=True) k = Symbol('k', integer=True) assert root(2, 2) == sqrt(2) assert root(2, 1) == 2 assert root(2, 3) == 2**Rational(1, 3) assert root(2, 3) == cbrt(2) assert root(2, -5) == 2**Rational(4, 5)/2 assert root(-2, 1) == -2 assert root(-2, 2) == sqrt(2)*I assert root(-2, 1) == -2 assert root(x, 2) == sqrt(x) assert root(x, 1) == x assert root(x, 3) == x**Rational(1, 3) assert root(x, 3) == cbrt(x) assert root(x, -5) == x**Rational(-1, 5) assert root(x, n) == x**(1/n) assert root(x, -n) == x**(-1/n) assert root(x, n, k) == (-1)**(2*k/n)*x**(1/n) def test_real_root(): assert real_root(-8, 3) == -2 assert real_root(-16, 4) == root(-16, 4) r = root(-7, 4) assert real_root(r) == r r1 = root(-1, 3) r2 = r1**2 r3 = root(-1, 4) assert real_root(r1 + r2 + r3) == -1 + r2 + r3 assert real_root(root(-2, 3)) == -root(2, 3) assert real_root(-8., 3) == -2 x = Symbol('x') n = Symbol('n') g = real_root(x, n) assert g.subs(dict(x=-8, n=3)) == -2 assert g.subs(dict(x=8, n=3)) == 2 # give principle root if there is no real root -- if this is not desired # then maybe a Root class is needed to raise an error instead assert g.subs(dict(x=I, n=3)) == cbrt(I) assert g.subs(dict(x=-8, n=2)) == sqrt(-8) assert g.subs(dict(x=I, n=2)) == sqrt(I) def test_issue_11463(): numpy = import_module('numpy') if not numpy: skip("numpy not installed.") x = Symbol('x') f = lambdify(x, real_root((log(x/(x-2))), 3), 'numpy') # numpy.select evaluates all options before considering conditions, # so it raises a warning about root of negative number which does # not affect the outcome. This warning is suppressed here with ignore_warnings(RuntimeWarning): assert f(numpy.array(-1)) < -1 def test_rewrite_MaxMin_as_Heaviside(): from sympy.abc import x assert Max(0, x).rewrite(Heaviside) == x*Heaviside(x) assert Max(3, x).rewrite(Heaviside) == x*Heaviside(x - 3) + \ 3*Heaviside(-x + 3) assert Max(0, x+2, 2*x).rewrite(Heaviside) == \ 2*x*Heaviside(2*x)*Heaviside(x - 2) + \ (x + 2)*Heaviside(-x + 2)*Heaviside(x + 2) assert Min(0, x).rewrite(Heaviside) == x*Heaviside(-x) assert Min(3, x).rewrite(Heaviside) == x*Heaviside(-x + 3) + \ 3*Heaviside(x - 3) assert Min(x, -x, -2).rewrite(Heaviside) == \ x*Heaviside(-2*x)*Heaviside(-x - 2) - \ x*Heaviside(2*x)*Heaviside(x - 2) \ - 2*Heaviside(-x + 2)*Heaviside(x + 2) def test_rewrite_MaxMin_as_Piecewise(): from sympy import symbols, Piecewise x, y, z, a, b = symbols('x y z a b', real=True) vx, vy, va = symbols('vx vy va') assert Max(a, b).rewrite(Piecewise) == Piecewise((a, a >= b), (b, True)) assert Max(x, y, z).rewrite(Piecewise) == Piecewise((x, (x >= y) & (x >= z)), (y, y >= z), (z, True)) assert Max(x, y, a, b).rewrite(Piecewise) == Piecewise((a, (a >= b) & (a >= x) & (a >= y)), (b, (b >= x) & (b >= y)), (x, x >= y), (y, True)) assert Min(a, b).rewrite(Piecewise) == Piecewise((a, a <= b), (b, True)) assert Min(x, y, z).rewrite(Piecewise) == Piecewise((x, (x <= y) & (x <= z)), (y, y <= z), (z, True)) assert Min(x, y, a, b).rewrite(Piecewise) == Piecewise((a, (a <= b) & (a <= x) & (a <= y)), (b, (b <= x) & (b <= y)), (x, x <= y), (y, True)) # Piecewise rewriting of Min/Max does also takes place for not explicitly real arguments assert Max(vx, vy).rewrite(Piecewise) == Piecewise((vx, vx >= vy), (vy, True)) assert Min(va, vx, vy).rewrite(Piecewise) == Piecewise((va, (va <= vx) & (va <= vy)), (vx, vx <= vy), (vy, True)) def test_issue_11099(): from sympy.abc import x, y # some fixed value tests fixed_test_data = {x: -2, y: 3} assert Min(x, y).evalf(subs=fixed_test_data) == \ Min(x, y).subs(fixed_test_data).evalf() assert Max(x, y).evalf(subs=fixed_test_data) == \ Max(x, y).subs(fixed_test_data).evalf() # randomly generate some test data from random import randint for i in range(20): random_test_data = {x: randint(-100, 100), y: randint(-100, 100)} assert Min(x, y).evalf(subs=random_test_data) == \ Min(x, y).subs(random_test_data).evalf() assert Max(x, y).evalf(subs=random_test_data) == \ Max(x, y).subs(random_test_data).evalf() def test_issue_12638(): from sympy.abc import a, b, c assert Min(a, b, c, Max(a, b)) == Min(a, b, c) assert Min(a, b, Max(a, b, c)) == Min(a, b) assert Min(a, b, Max(a, c)) == Min(a, b) def test_instantiation_evaluation(): from sympy.abc import v, w, x, y, z assert Min(1, Max(2, x)) == 1 assert Max(3, Min(2, x)) == 3 assert Min(Max(x, y), Max(x, z)) == Max(x, Min(y, z)) assert set(Min(Max(w, x), Max(y, z)).args) == set( [Max(w, x), Max(y, z)]) assert Min(Max(x, y), Max(x, z), w) == Min( w, Max(x, Min(y, z))) A, B = Min, Max for i in range(2): assert A(x, B(x, y)) == x assert A(x, B(y, A(x, w, z))) == A(x, B(y, A(w, z))) A, B = B, A assert Min(w, Max(x, y), Max(v, x, z)) == Min( w, Max(x, Min(y, Max(v, z)))) def test_rewrite_as_Abs(): from itertools import permutations from sympy.functions.elementary.complexes import Abs from sympy.abc import x, y, z, w def test(e): free = e.free_symbols a = e.rewrite(Abs) assert not a.has(Min, Max) for i in permutations(range(len(free))): reps = dict(zip(free, i)) assert a.xreplace(reps) == e.xreplace(reps) test(Min(x, y)) test(Max(x, y)) test(Min(x, y, z)) test(Min(Max(w, x), Max(y, z))) def test_issue_14000(): assert isinstance(sqrt(4, evaluate=False), Pow) == True assert isinstance(cbrt(3.5, evaluate=False), Pow) == True assert isinstance(root(16, 4, evaluate=False), Pow) == True assert sqrt(4, evaluate=False) == Pow(4, S.Half, evaluate=False) assert cbrt(3.5, evaluate=False) == Pow(3.5, Rational(1, 3), evaluate=False) assert root(4, 2, evaluate=False) == Pow(4, S.Half, evaluate=False) assert root(16, 4, 2, evaluate=False).has(Pow) == True assert real_root(-8, 3, evaluate=False).has(Pow) == True
d8363852a8d74e0cf6f86ea3ca706b2ac17fd3571d3754d58375484fcee1bb76
from sympy import (symbols, Symbol, sinh, nan, oo, zoo, pi, asinh, acosh, log, sqrt, coth, I, cot, E, tanh, tan, cosh, cos, S, sin, Rational, atanh, acoth, Integer, O, exp, sech, sec, csch, asech, acsch, acos, asin, expand_mul, AccumBounds, im, re) from sympy.core.expr import unchanged from sympy.core.function import ArgumentIndexError from sympy.testing.pytest import raises def test_sinh(): x, y = symbols('x,y') k = Symbol('k', integer=True) assert sinh(nan) is nan assert sinh(zoo) is nan assert sinh(oo) is oo assert sinh(-oo) is -oo assert sinh(0) == 0 assert unchanged(sinh, 1) assert sinh(-1) == -sinh(1) assert unchanged(sinh, x) assert sinh(-x) == -sinh(x) assert unchanged(sinh, pi) assert sinh(-pi) == -sinh(pi) assert unchanged(sinh, 2**1024 * E) assert sinh(-2**1024 * E) == -sinh(2**1024 * E) assert sinh(pi*I) == 0 assert sinh(-pi*I) == 0 assert sinh(2*pi*I) == 0 assert sinh(-2*pi*I) == 0 assert sinh(-3*10**73*pi*I) == 0 assert sinh(7*10**103*pi*I) == 0 assert sinh(pi*I/2) == I assert sinh(-pi*I/2) == -I assert sinh(pi*I*Rational(5, 2)) == I assert sinh(pi*I*Rational(7, 2)) == -I assert sinh(pi*I/3) == S.Half*sqrt(3)*I assert sinh(pi*I*Rational(-2, 3)) == Rational(-1, 2)*sqrt(3)*I assert sinh(pi*I/4) == S.Half*sqrt(2)*I assert sinh(-pi*I/4) == Rational(-1, 2)*sqrt(2)*I assert sinh(pi*I*Rational(17, 4)) == S.Half*sqrt(2)*I assert sinh(pi*I*Rational(-3, 4)) == Rational(-1, 2)*sqrt(2)*I assert sinh(pi*I/6) == S.Half*I assert sinh(-pi*I/6) == Rational(-1, 2)*I assert sinh(pi*I*Rational(7, 6)) == Rational(-1, 2)*I assert sinh(pi*I*Rational(-5, 6)) == Rational(-1, 2)*I assert sinh(pi*I/105) == sin(pi/105)*I assert sinh(-pi*I/105) == -sin(pi/105)*I assert unchanged(sinh, 2 + 3*I) assert sinh(x*I) == sin(x)*I assert sinh(k*pi*I) == 0 assert sinh(17*k*pi*I) == 0 assert sinh(k*pi*I/2) == sin(k*pi/2)*I assert sinh(x).as_real_imag(deep=False) == (cos(im(x))*sinh(re(x)), sin(im(x))*cosh(re(x))) x = Symbol('x', extended_real=True) assert sinh(x).as_real_imag(deep=False) == (sinh(x), 0) x = Symbol('x', real=True) assert sinh(I*x).is_finite is True assert sinh(x).is_real is True assert sinh(I).is_real is False def test_sinh_series(): x = Symbol('x') assert sinh(x).series(x, 0, 10) == \ x + x**3/6 + x**5/120 + x**7/5040 + x**9/362880 + O(x**10) def test_sinh_fdiff(): x = Symbol('x') raises(ArgumentIndexError, lambda: sinh(x).fdiff(2)) def test_cosh(): x, y = symbols('x,y') k = Symbol('k', integer=True) assert cosh(nan) is nan assert cosh(zoo) is nan assert cosh(oo) is oo assert cosh(-oo) is oo assert cosh(0) == 1 assert unchanged(cosh, 1) assert cosh(-1) == cosh(1) assert unchanged(cosh, x) assert cosh(-x) == cosh(x) assert cosh(pi*I) == cos(pi) assert cosh(-pi*I) == cos(pi) assert unchanged(cosh, 2**1024 * E) assert cosh(-2**1024 * E) == cosh(2**1024 * E) assert cosh(pi*I/2) == 0 assert cosh(-pi*I/2) == 0 assert cosh((-3*10**73 + 1)*pi*I/2) == 0 assert cosh((7*10**103 + 1)*pi*I/2) == 0 assert cosh(pi*I) == -1 assert cosh(-pi*I) == -1 assert cosh(5*pi*I) == -1 assert cosh(8*pi*I) == 1 assert cosh(pi*I/3) == S.Half assert cosh(pi*I*Rational(-2, 3)) == Rational(-1, 2) assert cosh(pi*I/4) == S.Half*sqrt(2) assert cosh(-pi*I/4) == S.Half*sqrt(2) assert cosh(pi*I*Rational(11, 4)) == Rational(-1, 2)*sqrt(2) assert cosh(pi*I*Rational(-3, 4)) == Rational(-1, 2)*sqrt(2) assert cosh(pi*I/6) == S.Half*sqrt(3) assert cosh(-pi*I/6) == S.Half*sqrt(3) assert cosh(pi*I*Rational(7, 6)) == Rational(-1, 2)*sqrt(3) assert cosh(pi*I*Rational(-5, 6)) == Rational(-1, 2)*sqrt(3) assert cosh(pi*I/105) == cos(pi/105) assert cosh(-pi*I/105) == cos(pi/105) assert unchanged(cosh, 2 + 3*I) assert cosh(x*I) == cos(x) assert cosh(k*pi*I) == cos(k*pi) assert cosh(17*k*pi*I) == cos(17*k*pi) assert unchanged(cosh, k*pi) assert cosh(x).as_real_imag(deep=False) == (cos(im(x))*cosh(re(x)), sin(im(x))*sinh(re(x))) x = Symbol('x', extended_real=True) assert cosh(x).as_real_imag(deep=False) == (cosh(x), 0) x = Symbol('x', real=True) assert cosh(I*x).is_finite is True assert cosh(I*x).is_real is True assert cosh(I*2 + 1).is_real is False def test_cosh_series(): x = Symbol('x') assert cosh(x).series(x, 0, 10) == \ 1 + x**2/2 + x**4/24 + x**6/720 + x**8/40320 + O(x**10) def test_cosh_fdiff(): x = Symbol('x') raises(ArgumentIndexError, lambda: cosh(x).fdiff(2)) def test_tanh(): x, y = symbols('x,y') k = Symbol('k', integer=True) assert tanh(nan) is nan assert tanh(zoo) is nan assert tanh(oo) == 1 assert tanh(-oo) == -1 assert tanh(0) == 0 assert unchanged(tanh, 1) assert tanh(-1) == -tanh(1) assert unchanged(tanh, x) assert tanh(-x) == -tanh(x) assert unchanged(tanh, pi) assert tanh(-pi) == -tanh(pi) assert unchanged(tanh, 2**1024 * E) assert tanh(-2**1024 * E) == -tanh(2**1024 * E) assert tanh(pi*I) == 0 assert tanh(-pi*I) == 0 assert tanh(2*pi*I) == 0 assert tanh(-2*pi*I) == 0 assert tanh(-3*10**73*pi*I) == 0 assert tanh(7*10**103*pi*I) == 0 assert tanh(pi*I/2) is zoo assert tanh(-pi*I/2) is zoo assert tanh(pi*I*Rational(5, 2)) is zoo assert tanh(pi*I*Rational(7, 2)) is zoo assert tanh(pi*I/3) == sqrt(3)*I assert tanh(pi*I*Rational(-2, 3)) == sqrt(3)*I assert tanh(pi*I/4) == I assert tanh(-pi*I/4) == -I assert tanh(pi*I*Rational(17, 4)) == I assert tanh(pi*I*Rational(-3, 4)) == I assert tanh(pi*I/6) == I/sqrt(3) assert tanh(-pi*I/6) == -I/sqrt(3) assert tanh(pi*I*Rational(7, 6)) == I/sqrt(3) assert tanh(pi*I*Rational(-5, 6)) == I/sqrt(3) assert tanh(pi*I/105) == tan(pi/105)*I assert tanh(-pi*I/105) == -tan(pi/105)*I assert unchanged(tanh, 2 + 3*I) assert tanh(x*I) == tan(x)*I assert tanh(k*pi*I) == 0 assert tanh(17*k*pi*I) == 0 assert tanh(k*pi*I/2) == tan(k*pi/2)*I assert tanh(x).as_real_imag(deep=False) == (sinh(re(x))*cosh(re(x))/(cos(im(x))**2 + sinh(re(x))**2), sin(im(x))*cos(im(x))/(cos(im(x))**2 + sinh(re(x))**2)) x = Symbol('x', extended_real=True) assert tanh(x).as_real_imag(deep=False) == (tanh(x), 0) assert tanh(I*pi/3 + 1).is_real is False assert tanh(x).is_real is True assert tanh(I*pi*x/2).is_real is None def test_tanh_series(): x = Symbol('x') assert tanh(x).series(x, 0, 10) == \ x - x**3/3 + 2*x**5/15 - 17*x**7/315 + 62*x**9/2835 + O(x**10) def test_tanh_fdiff(): x = Symbol('x') raises(ArgumentIndexError, lambda: tanh(x).fdiff(2)) def test_coth(): x, y = symbols('x,y') k = Symbol('k', integer=True) assert coth(nan) is nan assert coth(zoo) is nan assert coth(oo) == 1 assert coth(-oo) == -1 assert coth(0) is zoo assert unchanged(coth, 1) assert coth(-1) == -coth(1) assert unchanged(coth, x) assert coth(-x) == -coth(x) assert coth(pi*I) == -I*cot(pi) assert coth(-pi*I) == cot(pi)*I assert unchanged(coth, 2**1024 * E) assert coth(-2**1024 * E) == -coth(2**1024 * E) assert coth(pi*I) == -I*cot(pi) assert coth(-pi*I) == I*cot(pi) assert coth(2*pi*I) == -I*cot(2*pi) assert coth(-2*pi*I) == I*cot(2*pi) assert coth(-3*10**73*pi*I) == I*cot(3*10**73*pi) assert coth(7*10**103*pi*I) == -I*cot(7*10**103*pi) assert coth(pi*I/2) == 0 assert coth(-pi*I/2) == 0 assert coth(pi*I*Rational(5, 2)) == 0 assert coth(pi*I*Rational(7, 2)) == 0 assert coth(pi*I/3) == -I/sqrt(3) assert coth(pi*I*Rational(-2, 3)) == -I/sqrt(3) assert coth(pi*I/4) == -I assert coth(-pi*I/4) == I assert coth(pi*I*Rational(17, 4)) == -I assert coth(pi*I*Rational(-3, 4)) == -I assert coth(pi*I/6) == -sqrt(3)*I assert coth(-pi*I/6) == sqrt(3)*I assert coth(pi*I*Rational(7, 6)) == -sqrt(3)*I assert coth(pi*I*Rational(-5, 6)) == -sqrt(3)*I assert coth(pi*I/105) == -cot(pi/105)*I assert coth(-pi*I/105) == cot(pi/105)*I assert unchanged(coth, 2 + 3*I) assert coth(x*I) == -cot(x)*I assert coth(k*pi*I) == -cot(k*pi)*I assert coth(17*k*pi*I) == -cot(17*k*pi)*I assert coth(k*pi*I) == -cot(k*pi)*I assert coth(log(tan(2))) == coth(log(-tan(2))) assert coth(1 + I*pi/2) == tanh(1) assert coth(x).as_real_imag(deep=False) == (sinh(re(x))*cosh(re(x))/(sin(im(x))**2 + sinh(re(x))**2), -sin(im(x))*cos(im(x))/(sin(im(x))**2 + sinh(re(x))**2)) x = Symbol('x', extended_real=True) assert coth(x).as_real_imag(deep=False) == (coth(x), 0) def test_coth_series(): x = Symbol('x') assert coth(x).series(x, 0, 8) == \ 1/x + x/3 - x**3/45 + 2*x**5/945 - x**7/4725 + O(x**8) def test_coth_fdiff(): x = Symbol('x') raises(ArgumentIndexError, lambda: coth(x).fdiff(2)) def test_csch(): x, y = symbols('x,y') k = Symbol('k', integer=True) n = Symbol('n', positive=True) assert csch(nan) is nan assert csch(zoo) is nan assert csch(oo) == 0 assert csch(-oo) == 0 assert csch(0) is zoo assert csch(-1) == -csch(1) assert csch(-x) == -csch(x) assert csch(-pi) == -csch(pi) assert csch(-2**1024 * E) == -csch(2**1024 * E) assert csch(pi*I) is zoo assert csch(-pi*I) is zoo assert csch(2*pi*I) is zoo assert csch(-2*pi*I) is zoo assert csch(-3*10**73*pi*I) is zoo assert csch(7*10**103*pi*I) is zoo assert csch(pi*I/2) == -I assert csch(-pi*I/2) == I assert csch(pi*I*Rational(5, 2)) == -I assert csch(pi*I*Rational(7, 2)) == I assert csch(pi*I/3) == -2/sqrt(3)*I assert csch(pi*I*Rational(-2, 3)) == 2/sqrt(3)*I assert csch(pi*I/4) == -sqrt(2)*I assert csch(-pi*I/4) == sqrt(2)*I assert csch(pi*I*Rational(7, 4)) == sqrt(2)*I assert csch(pi*I*Rational(-3, 4)) == sqrt(2)*I assert csch(pi*I/6) == -2*I assert csch(-pi*I/6) == 2*I assert csch(pi*I*Rational(7, 6)) == 2*I assert csch(pi*I*Rational(-7, 6)) == -2*I assert csch(pi*I*Rational(-5, 6)) == 2*I assert csch(pi*I/105) == -1/sin(pi/105)*I assert csch(-pi*I/105) == 1/sin(pi/105)*I assert csch(x*I) == -1/sin(x)*I assert csch(k*pi*I) is zoo assert csch(17*k*pi*I) is zoo assert csch(k*pi*I/2) == -1/sin(k*pi/2)*I assert csch(n).is_real is True def test_csch_series(): x = Symbol('x') assert csch(x).series(x, 0, 10) == \ 1/ x - x/6 + 7*x**3/360 - 31*x**5/15120 + 127*x**7/604800 \ - 73*x**9/3421440 + O(x**10) def test_csch_fdiff(): x = Symbol('x') raises(ArgumentIndexError, lambda: csch(x).fdiff(2)) def test_sech(): x, y = symbols('x, y') k = Symbol('k', integer=True) n = Symbol('n', positive=True) assert sech(nan) is nan assert sech(zoo) is nan assert sech(oo) == 0 assert sech(-oo) == 0 assert sech(0) == 1 assert sech(-1) == sech(1) assert sech(-x) == sech(x) assert sech(pi*I) == sec(pi) assert sech(-pi*I) == sec(pi) assert sech(-2**1024 * E) == sech(2**1024 * E) assert sech(pi*I/2) is zoo assert sech(-pi*I/2) is zoo assert sech((-3*10**73 + 1)*pi*I/2) is zoo assert sech((7*10**103 + 1)*pi*I/2) is zoo assert sech(pi*I) == -1 assert sech(-pi*I) == -1 assert sech(5*pi*I) == -1 assert sech(8*pi*I) == 1 assert sech(pi*I/3) == 2 assert sech(pi*I*Rational(-2, 3)) == -2 assert sech(pi*I/4) == sqrt(2) assert sech(-pi*I/4) == sqrt(2) assert sech(pi*I*Rational(5, 4)) == -sqrt(2) assert sech(pi*I*Rational(-5, 4)) == -sqrt(2) assert sech(pi*I/6) == 2/sqrt(3) assert sech(-pi*I/6) == 2/sqrt(3) assert sech(pi*I*Rational(7, 6)) == -2/sqrt(3) assert sech(pi*I*Rational(-5, 6)) == -2/sqrt(3) assert sech(pi*I/105) == 1/cos(pi/105) assert sech(-pi*I/105) == 1/cos(pi/105) assert sech(x*I) == 1/cos(x) assert sech(k*pi*I) == 1/cos(k*pi) assert sech(17*k*pi*I) == 1/cos(17*k*pi) assert sech(n).is_real is True def test_sech_series(): x = Symbol('x') assert sech(x).series(x, 0, 10) == \ 1 - x**2/2 + 5*x**4/24 - 61*x**6/720 + 277*x**8/8064 + O(x**10) def test_sech_fdiff(): x = Symbol('x') raises(ArgumentIndexError, lambda: sech(x).fdiff(2)) def test_asinh(): x, y = symbols('x,y') assert unchanged(asinh, x) assert asinh(-x) == -asinh(x) #at specific points assert asinh(nan) is nan assert asinh( 0) == 0 assert asinh(+1) == log(sqrt(2) + 1) assert asinh(-1) == log(sqrt(2) - 1) assert asinh(I) == pi*I/2 assert asinh(-I) == -pi*I/2 assert asinh(I/2) == pi*I/6 assert asinh(-I/2) == -pi*I/6 # at infinites assert asinh(oo) is oo assert asinh(-oo) is -oo assert asinh(I*oo) is oo assert asinh(-I *oo) is -oo assert asinh(zoo) is zoo #properties assert asinh(I *(sqrt(3) - 1)/(2**Rational(3, 2))) == pi*I/12 assert asinh(-I *(sqrt(3) - 1)/(2**Rational(3, 2))) == -pi*I/12 assert asinh(I*(sqrt(5) - 1)/4) == pi*I/10 assert asinh(-I*(sqrt(5) - 1)/4) == -pi*I/10 assert asinh(I*(sqrt(5) + 1)/4) == pi*I*Rational(3, 10) assert asinh(-I*(sqrt(5) + 1)/4) == pi*I*Rational(-3, 10) # Symmetry assert asinh(Rational(-1, 2)) == -asinh(S.Half) # inverse composition assert unchanged(asinh, sinh(Symbol('v1'))) assert asinh(sinh(0, evaluate=False)) == 0 assert asinh(sinh(-3, evaluate=False)) == -3 assert asinh(sinh(2, evaluate=False)) == 2 assert asinh(sinh(I, evaluate=False)) == I assert asinh(sinh(-I, evaluate=False)) == -I assert asinh(sinh(5*I, evaluate=False)) == -2*I*pi + 5*I assert asinh(sinh(15 + 11*I)) == 15 - 4*I*pi + 11*I assert asinh(sinh(-73 + 97*I)) == 73 - 97*I + 31*I*pi assert asinh(sinh(-7 - 23*I)) == 7 - 7*I*pi + 23*I assert asinh(sinh(13 - 3*I)) == -13 - I*pi + 3*I def test_asinh_rewrite(): x = Symbol('x') assert asinh(x).rewrite(log) == log(x + sqrt(x**2 + 1)) def test_asinh_series(): x = Symbol('x') assert asinh(x).series(x, 0, 8) == \ x - x**3/6 + 3*x**5/40 - 5*x**7/112 + O(x**8) t5 = asinh(x).taylor_term(5, x) assert t5 == 3*x**5/40 assert asinh(x).taylor_term(7, x, t5, 0) == -5*x**7/112 def test_asinh_fdiff(): x = Symbol('x') raises(ArgumentIndexError, lambda: asinh(x).fdiff(2)) def test_acosh(): x = Symbol('x') assert unchanged(acosh, -x) #at specific points assert acosh(1) == 0 assert acosh(-1) == pi*I assert acosh(0) == I*pi/2 assert acosh(S.Half) == I*pi/3 assert acosh(Rational(-1, 2)) == pi*I*Rational(2, 3) assert acosh(nan) is nan # at infinites assert acosh(oo) is oo assert acosh(-oo) is oo assert acosh(I*oo) == oo + I*pi/2 assert acosh(-I*oo) == oo - I*pi/2 assert acosh(zoo) is zoo assert acosh(I) == log(I*(1 + sqrt(2))) assert acosh(-I) == log(-I*(1 + sqrt(2))) assert acosh((sqrt(3) - 1)/(2*sqrt(2))) == pi*I*Rational(5, 12) assert acosh(-(sqrt(3) - 1)/(2*sqrt(2))) == pi*I*Rational(7, 12) assert acosh(sqrt(2)/2) == I*pi/4 assert acosh(-sqrt(2)/2) == I*pi*Rational(3, 4) assert acosh(sqrt(3)/2) == I*pi/6 assert acosh(-sqrt(3)/2) == I*pi*Rational(5, 6) assert acosh(sqrt(2 + sqrt(2))/2) == I*pi/8 assert acosh(-sqrt(2 + sqrt(2))/2) == I*pi*Rational(7, 8) assert acosh(sqrt(2 - sqrt(2))/2) == I*pi*Rational(3, 8) assert acosh(-sqrt(2 - sqrt(2))/2) == I*pi*Rational(5, 8) assert acosh((1 + sqrt(3))/(2*sqrt(2))) == I*pi/12 assert acosh(-(1 + sqrt(3))/(2*sqrt(2))) == I*pi*Rational(11, 12) assert acosh((sqrt(5) + 1)/4) == I*pi/5 assert acosh(-(sqrt(5) + 1)/4) == I*pi*Rational(4, 5) assert str(acosh(5*I).n(6)) == '2.31244 + 1.5708*I' assert str(acosh(-5*I).n(6)) == '2.31244 - 1.5708*I' # inverse composition assert unchanged(acosh, Symbol('v1')) assert acosh(cosh(-3, evaluate=False)) == 3 assert acosh(cosh(3, evaluate=False)) == 3 assert acosh(cosh(0, evaluate=False)) == 0 assert acosh(cosh(I, evaluate=False)) == I assert acosh(cosh(-I, evaluate=False)) == I assert acosh(cosh(7*I, evaluate=False)) == -2*I*pi + 7*I assert acosh(cosh(1 + I)) == 1 + I assert acosh(cosh(3 - 3*I)) == 3 - 3*I assert acosh(cosh(-3 + 2*I)) == 3 - 2*I assert acosh(cosh(-5 - 17*I)) == 5 - 6*I*pi + 17*I assert acosh(cosh(-21 + 11*I)) == 21 - 11*I + 4*I*pi assert acosh(cosh(cosh(1) + I)) == cosh(1) + I def test_acosh_rewrite(): x = Symbol('x') assert acosh(x).rewrite(log) == log(x + sqrt(x - 1)*sqrt(x + 1)) def test_acosh_series(): x = Symbol('x') assert acosh(x).series(x, 0, 8) == \ -I*x + pi*I/2 - I*x**3/6 - 3*I*x**5/40 - 5*I*x**7/112 + O(x**8) t5 = acosh(x).taylor_term(5, x) assert t5 == - 3*I*x**5/40 assert acosh(x).taylor_term(7, x, t5, 0) == - 5*I*x**7/112 def test_acosh_fdiff(): x = Symbol('x') raises(ArgumentIndexError, lambda: acosh(x).fdiff(2)) def test_asech(): x = Symbol('x') assert unchanged(asech, -x) # values at fixed points assert asech(1) == 0 assert asech(-1) == pi*I assert asech(0) is oo assert asech(2) == I*pi/3 assert asech(-2) == 2*I*pi / 3 assert asech(nan) is nan # at infinites assert asech(oo) == I*pi/2 assert asech(-oo) == I*pi/2 assert asech(zoo) == I*AccumBounds(-pi/2, pi/2) assert asech(I) == log(1 + sqrt(2)) - I*pi/2 assert asech(-I) == log(1 + sqrt(2)) + I*pi/2 assert asech(sqrt(2) - sqrt(6)) == 11*I*pi / 12 assert asech(sqrt(2 - 2/sqrt(5))) == I*pi / 10 assert asech(-sqrt(2 - 2/sqrt(5))) == 9*I*pi / 10 assert asech(2 / sqrt(2 + sqrt(2))) == I*pi / 8 assert asech(-2 / sqrt(2 + sqrt(2))) == 7*I*pi / 8 assert asech(sqrt(5) - 1) == I*pi / 5 assert asech(1 - sqrt(5)) == 4*I*pi / 5 assert asech(-sqrt(2*(2 + sqrt(2)))) == 5*I*pi / 8 # properties # asech(x) == acosh(1/x) assert asech(sqrt(2)) == acosh(1/sqrt(2)) assert asech(2/sqrt(3)) == acosh(sqrt(3)/2) assert asech(2/sqrt(2 + sqrt(2))) == acosh(sqrt(2 + sqrt(2))/2) assert asech(2) == acosh(S.Half) # asech(x) == I*acos(1/x) # (Note: the exact formula is asech(x) == +/- I*acos(1/x)) assert asech(-sqrt(2)) == I*acos(-1/sqrt(2)) assert asech(-2/sqrt(3)) == I*acos(-sqrt(3)/2) assert asech(-S(2)) == I*acos(Rational(-1, 2)) assert asech(-2/sqrt(2)) == I*acos(-sqrt(2)/2) # sech(asech(x)) / x == 1 assert expand_mul(sech(asech(sqrt(6) - sqrt(2))) / (sqrt(6) - sqrt(2))) == 1 assert expand_mul(sech(asech(sqrt(6) + sqrt(2))) / (sqrt(6) + sqrt(2))) == 1 assert (sech(asech(sqrt(2 + 2/sqrt(5)))) / (sqrt(2 + 2/sqrt(5)))).simplify() == 1 assert (sech(asech(-sqrt(2 + 2/sqrt(5)))) / (-sqrt(2 + 2/sqrt(5)))).simplify() == 1 assert (sech(asech(sqrt(2*(2 + sqrt(2))))) / (sqrt(2*(2 + sqrt(2))))).simplify() == 1 assert expand_mul(sech(asech((1 + sqrt(5)))) / ((1 + sqrt(5)))) == 1 assert expand_mul(sech(asech((-1 - sqrt(5)))) / ((-1 - sqrt(5)))) == 1 assert expand_mul(sech(asech((-sqrt(6) - sqrt(2)))) / ((-sqrt(6) - sqrt(2)))) == 1 # numerical evaluation assert str(asech(5*I).n(6)) == '0.19869 - 1.5708*I' assert str(asech(-5*I).n(6)) == '0.19869 + 1.5708*I' def test_asech_series(): x = Symbol('x') t6 = asech(x).expansion_term(6, x) assert t6 == -5*x**6/96 assert asech(x).expansion_term(8, x, t6, 0) == -35*x**8/1024 def test_asech_rewrite(): x = Symbol('x') assert asech(x).rewrite(log) == log(1/x + sqrt(1/x - 1) * sqrt(1/x + 1)) def test_asech_fdiff(): x = Symbol('x') raises(ArgumentIndexError, lambda: asech(x).fdiff(2)) def test_acsch(): x = Symbol('x') assert unchanged(acsch, x) assert acsch(-x) == -acsch(x) # values at fixed points assert acsch(1) == log(1 + sqrt(2)) assert acsch(-1) == - log(1 + sqrt(2)) assert acsch(0) is zoo assert acsch(2) == log((1+sqrt(5))/2) assert acsch(-2) == - log((1+sqrt(5))/2) assert acsch(I) == - I*pi/2 assert acsch(-I) == I*pi/2 assert acsch(-I*(sqrt(6) + sqrt(2))) == I*pi / 12 assert acsch(I*(sqrt(2) + sqrt(6))) == -I*pi / 12 assert acsch(-I*(1 + sqrt(5))) == I*pi / 10 assert acsch(I*(1 + sqrt(5))) == -I*pi / 10 assert acsch(-I*2 / sqrt(2 - sqrt(2))) == I*pi / 8 assert acsch(I*2 / sqrt(2 - sqrt(2))) == -I*pi / 8 assert acsch(-I*2) == I*pi / 6 assert acsch(I*2) == -I*pi / 6 assert acsch(-I*sqrt(2 + 2/sqrt(5))) == I*pi / 5 assert acsch(I*sqrt(2 + 2/sqrt(5))) == -I*pi / 5 assert acsch(-I*sqrt(2)) == I*pi / 4 assert acsch(I*sqrt(2)) == -I*pi / 4 assert acsch(-I*(sqrt(5)-1)) == 3*I*pi / 10 assert acsch(I*(sqrt(5)-1)) == -3*I*pi / 10 assert acsch(-I*2 / sqrt(3)) == I*pi / 3 assert acsch(I*2 / sqrt(3)) == -I*pi / 3 assert acsch(-I*2 / sqrt(2 + sqrt(2))) == 3*I*pi / 8 assert acsch(I*2 / sqrt(2 + sqrt(2))) == -3*I*pi / 8 assert acsch(-I*sqrt(2 - 2/sqrt(5))) == 2*I*pi / 5 assert acsch(I*sqrt(2 - 2/sqrt(5))) == -2*I*pi / 5 assert acsch(-I*(sqrt(6) - sqrt(2))) == 5*I*pi / 12 assert acsch(I*(sqrt(6) - sqrt(2))) == -5*I*pi / 12 assert acsch(nan) is nan # properties # acsch(x) == asinh(1/x) assert acsch(-I*sqrt(2)) == asinh(I/sqrt(2)) assert acsch(-I*2 / sqrt(3)) == asinh(I*sqrt(3) / 2) # acsch(x) == -I*asin(I/x) assert acsch(-I*sqrt(2)) == -I*asin(-1/sqrt(2)) assert acsch(-I*2 / sqrt(3)) == -I*asin(-sqrt(3)/2) # csch(acsch(x)) / x == 1 assert expand_mul(csch(acsch(-I*(sqrt(6) + sqrt(2)))) / (-I*(sqrt(6) + sqrt(2)))) == 1 assert expand_mul(csch(acsch(I*(1 + sqrt(5)))) / ((I*(1 + sqrt(5))))) == 1 assert (csch(acsch(I*sqrt(2 - 2/sqrt(5)))) / (I*sqrt(2 - 2/sqrt(5)))).simplify() == 1 assert (csch(acsch(-I*sqrt(2 - 2/sqrt(5)))) / (-I*sqrt(2 - 2/sqrt(5)))).simplify() == 1 # numerical evaluation assert str(acsch(5*I+1).n(6)) == '0.0391819 - 0.193363*I' assert str(acsch(-5*I+1).n(6)) == '0.0391819 + 0.193363*I' def test_acsch_infinities(): assert acsch(oo) == 0 assert acsch(-oo) == 0 assert acsch(zoo) == 0 def test_acsch_rewrite(): x = Symbol('x') assert acsch(x).rewrite(log) == log(1/x + sqrt(1/x**2 + 1)) def test_acsch_fdiff(): x = Symbol('x') raises(ArgumentIndexError, lambda: acsch(x).fdiff(2)) def test_atanh(): x = Symbol('x') #at specific points assert atanh(0) == 0 assert atanh(I) == I*pi/4 assert atanh(-I) == -I*pi/4 assert atanh(1) is oo assert atanh(-1) is -oo assert atanh(nan) is nan # at infinites assert atanh(oo) == -I*pi/2 assert atanh(-oo) == I*pi/2 assert atanh(I*oo) == I*pi/2 assert atanh(-I*oo) == -I*pi/2 assert atanh(zoo) == I*AccumBounds(-pi/2, pi/2) #properties assert atanh(-x) == -atanh(x) assert atanh(I/sqrt(3)) == I*pi/6 assert atanh(-I/sqrt(3)) == -I*pi/6 assert atanh(I*sqrt(3)) == I*pi/3 assert atanh(-I*sqrt(3)) == -I*pi/3 assert atanh(I*(1 + sqrt(2))) == pi*I*Rational(3, 8) assert atanh(I*(sqrt(2) - 1)) == pi*I/8 assert atanh(I*(1 - sqrt(2))) == -pi*I/8 assert atanh(-I*(1 + sqrt(2))) == pi*I*Rational(-3, 8) assert atanh(I*sqrt(5 + 2*sqrt(5))) == I*pi*Rational(2, 5) assert atanh(-I*sqrt(5 + 2*sqrt(5))) == I*pi*Rational(-2, 5) assert atanh(I*(2 - sqrt(3))) == pi*I/12 assert atanh(I*(sqrt(3) - 2)) == -pi*I/12 assert atanh(oo) == -I*pi/2 # Symmetry assert atanh(Rational(-1, 2)) == -atanh(S.Half) # inverse composition assert unchanged(atanh, tanh(Symbol('v1'))) assert atanh(tanh(-5, evaluate=False)) == -5 assert atanh(tanh(0, evaluate=False)) == 0 assert atanh(tanh(7, evaluate=False)) == 7 assert atanh(tanh(I, evaluate=False)) == I assert atanh(tanh(-I, evaluate=False)) == -I assert atanh(tanh(-11*I, evaluate=False)) == -11*I + 4*I*pi assert atanh(tanh(3 + I)) == 3 + I assert atanh(tanh(4 + 5*I)) == 4 - 2*I*pi + 5*I assert atanh(tanh(pi/2)) == pi/2 assert atanh(tanh(pi)) == pi assert atanh(tanh(-3 + 7*I)) == -3 - 2*I*pi + 7*I assert atanh(tanh(9 - I*Rational(2, 3))) == 9 - I*Rational(2, 3) assert atanh(tanh(-32 - 123*I)) == -32 - 123*I + 39*I*pi def test_atanh_rewrite(): x = Symbol('x') assert atanh(x).rewrite(log) == (log(1 + x) - log(1 - x)) / 2 def test_atanh_series(): x = Symbol('x') assert atanh(x).series(x, 0, 10) == \ x + x**3/3 + x**5/5 + x**7/7 + x**9/9 + O(x**10) def test_atanh_fdiff(): x = Symbol('x') raises(ArgumentIndexError, lambda: atanh(x).fdiff(2)) def test_acoth(): x = Symbol('x') #at specific points assert acoth(0) == I*pi/2 assert acoth(I) == -I*pi/4 assert acoth(-I) == I*pi/4 assert acoth(1) is oo assert acoth(-1) is -oo assert acoth(nan) is nan # at infinites assert acoth(oo) == 0 assert acoth(-oo) == 0 assert acoth(I*oo) == 0 assert acoth(-I*oo) == 0 assert acoth(zoo) == 0 #properties assert acoth(-x) == -acoth(x) assert acoth(I/sqrt(3)) == -I*pi/3 assert acoth(-I/sqrt(3)) == I*pi/3 assert acoth(I*sqrt(3)) == -I*pi/6 assert acoth(-I*sqrt(3)) == I*pi/6 assert acoth(I*(1 + sqrt(2))) == -pi*I/8 assert acoth(-I*(sqrt(2) + 1)) == pi*I/8 assert acoth(I*(1 - sqrt(2))) == pi*I*Rational(3, 8) assert acoth(I*(sqrt(2) - 1)) == pi*I*Rational(-3, 8) assert acoth(I*sqrt(5 + 2*sqrt(5))) == -I*pi/10 assert acoth(-I*sqrt(5 + 2*sqrt(5))) == I*pi/10 assert acoth(I*(2 + sqrt(3))) == -pi*I/12 assert acoth(-I*(2 + sqrt(3))) == pi*I/12 assert acoth(I*(2 - sqrt(3))) == pi*I*Rational(-5, 12) assert acoth(I*(sqrt(3) - 2)) == pi*I*Rational(5, 12) # Symmetry assert acoth(Rational(-1, 2)) == -acoth(S.Half) def test_acoth_rewrite(): x = Symbol('x') assert acoth(x).rewrite(log) == (log(1 + 1/x) - log(1 - 1/x)) / 2 def test_acoth_series(): x = Symbol('x') assert acoth(x).series(x, 0, 10) == \ I*pi/2 + x + x**3/3 + x**5/5 + x**7/7 + x**9/9 + O(x**10) def test_acoth_fdiff(): x = Symbol('x') raises(ArgumentIndexError, lambda: acoth(x).fdiff(2)) def test_inverses(): x = Symbol('x') assert sinh(x).inverse() == asinh raises(AttributeError, lambda: cosh(x).inverse()) assert tanh(x).inverse() == atanh assert coth(x).inverse() == acoth assert asinh(x).inverse() == sinh assert acosh(x).inverse() == cosh assert atanh(x).inverse() == tanh assert acoth(x).inverse() == coth assert asech(x).inverse() == sech assert acsch(x).inverse() == csch def test_leading_term(): x = Symbol('x') assert cosh(x).as_leading_term(x) == 1 assert coth(x).as_leading_term(x) == 1/x assert acosh(x).as_leading_term(x) == I*pi/2 assert acoth(x).as_leading_term(x) == I*pi/2 for func in [sinh, tanh, asinh, atanh]: assert func(x).as_leading_term(x) == x for func in [sinh, cosh, tanh, coth, asinh, acosh, atanh, acoth]: for arg in (1/x, S.Half): eq = func(arg) assert eq.as_leading_term(x) == eq for func in [csch, sech]: eq = func(S.Half) assert eq.as_leading_term(x) == eq def test_complex(): a, b = symbols('a,b', real=True) z = a + b*I for func in [sinh, cosh, tanh, coth, sech, csch]: assert func(z).conjugate() == func(a - b*I) for deep in [True, False]: assert sinh(z).expand( complex=True, deep=deep) == sinh(a)*cos(b) + I*cosh(a)*sin(b) assert cosh(z).expand( complex=True, deep=deep) == cosh(a)*cos(b) + I*sinh(a)*sin(b) assert tanh(z).expand(complex=True, deep=deep) == sinh(a)*cosh( a)/(cos(b)**2 + sinh(a)**2) + I*sin(b)*cos(b)/(cos(b)**2 + sinh(a)**2) assert coth(z).expand(complex=True, deep=deep) == sinh(a)*cosh( a)/(sin(b)**2 + sinh(a)**2) - I*sin(b)*cos(b)/(sin(b)**2 + sinh(a)**2) assert csch(z).expand(complex=True, deep=deep) == cos(b) * sinh(a) / (sin(b)**2\ *cosh(a)**2 + cos(b)**2 * sinh(a)**2) - I*sin(b) * cosh(a) / (sin(b)**2\ *cosh(a)**2 + cos(b)**2 * sinh(a)**2) assert sech(z).expand(complex=True, deep=deep) == cos(b) * cosh(a) / (sin(b)**2\ *sinh(a)**2 + cos(b)**2 * cosh(a)**2) - I*sin(b) * sinh(a) / (sin(b)**2\ *sinh(a)**2 + cos(b)**2 * cosh(a)**2) def test_complex_2899(): a, b = symbols('a,b', real=True) for deep in [True, False]: for func in [sinh, cosh, tanh, coth]: assert func(a).expand(complex=True, deep=deep) == func(a) def test_simplifications(): x = Symbol('x') assert sinh(asinh(x)) == x assert sinh(acosh(x)) == sqrt(x - 1) * sqrt(x + 1) assert sinh(atanh(x)) == x/sqrt(1 - x**2) assert sinh(acoth(x)) == 1/(sqrt(x - 1) * sqrt(x + 1)) assert cosh(asinh(x)) == sqrt(1 + x**2) assert cosh(acosh(x)) == x assert cosh(atanh(x)) == 1/sqrt(1 - x**2) assert cosh(acoth(x)) == x/(sqrt(x - 1) * sqrt(x + 1)) assert tanh(asinh(x)) == x/sqrt(1 + x**2) assert tanh(acosh(x)) == sqrt(x - 1) * sqrt(x + 1) / x assert tanh(atanh(x)) == x assert tanh(acoth(x)) == 1/x assert coth(asinh(x)) == sqrt(1 + x**2)/x assert coth(acosh(x)) == x/(sqrt(x - 1) * sqrt(x + 1)) assert coth(atanh(x)) == 1/x assert coth(acoth(x)) == x assert csch(asinh(x)) == 1/x assert csch(acosh(x)) == 1/(sqrt(x - 1) * sqrt(x + 1)) assert csch(atanh(x)) == sqrt(1 - x**2)/x assert csch(acoth(x)) == sqrt(x - 1) * sqrt(x + 1) assert sech(asinh(x)) == 1/sqrt(1 + x**2) assert sech(acosh(x)) == 1/x assert sech(atanh(x)) == sqrt(1 - x**2) assert sech(acoth(x)) == sqrt(x - 1) * sqrt(x + 1)/x def test_issue_4136(): assert cosh(asinh(Integer(3)/2)) == sqrt(Integer(13)/4) def test_sinh_rewrite(): x = Symbol('x') assert sinh(x).rewrite(exp) == (exp(x) - exp(-x))/2 \ == sinh(x).rewrite('tractable') assert sinh(x).rewrite(cosh) == -I*cosh(x + I*pi/2) tanh_half = tanh(S.Half*x) assert sinh(x).rewrite(tanh) == 2*tanh_half/(1 - tanh_half**2) coth_half = coth(S.Half*x) assert sinh(x).rewrite(coth) == 2*coth_half/(coth_half**2 - 1) def test_cosh_rewrite(): x = Symbol('x') assert cosh(x).rewrite(exp) == (exp(x) + exp(-x))/2 \ == cosh(x).rewrite('tractable') assert cosh(x).rewrite(sinh) == -I*sinh(x + I*pi/2) tanh_half = tanh(S.Half*x)**2 assert cosh(x).rewrite(tanh) == (1 + tanh_half)/(1 - tanh_half) coth_half = coth(S.Half*x)**2 assert cosh(x).rewrite(coth) == (coth_half + 1)/(coth_half - 1) def test_tanh_rewrite(): x = Symbol('x') assert tanh(x).rewrite(exp) == (exp(x) - exp(-x))/(exp(x) + exp(-x)) \ == tanh(x).rewrite('tractable') assert tanh(x).rewrite(sinh) == I*sinh(x)/sinh(I*pi/2 - x) assert tanh(x).rewrite(cosh) == I*cosh(I*pi/2 - x)/cosh(x) assert tanh(x).rewrite(coth) == 1/coth(x) def test_coth_rewrite(): x = Symbol('x') assert coth(x).rewrite(exp) == (exp(x) + exp(-x))/(exp(x) - exp(-x)) \ == coth(x).rewrite('tractable') assert coth(x).rewrite(sinh) == -I*sinh(I*pi/2 - x)/sinh(x) assert coth(x).rewrite(cosh) == -I*cosh(x)/cosh(I*pi/2 - x) assert coth(x).rewrite(tanh) == 1/tanh(x) def test_csch_rewrite(): x = Symbol('x') assert csch(x).rewrite(exp) == 1 / (exp(x)/2 - exp(-x)/2) \ == csch(x).rewrite('tractable') assert csch(x).rewrite(cosh) == I/cosh(x + I*pi/2) tanh_half = tanh(S.Half*x) assert csch(x).rewrite(tanh) == (1 - tanh_half**2)/(2*tanh_half) coth_half = coth(S.Half*x) assert csch(x).rewrite(coth) == (coth_half**2 - 1)/(2*coth_half) def test_sech_rewrite(): x = Symbol('x') assert sech(x).rewrite(exp) == 1 / (exp(x)/2 + exp(-x)/2) \ == sech(x).rewrite('tractable') assert sech(x).rewrite(sinh) == I/sinh(x + I*pi/2) tanh_half = tanh(S.Half*x)**2 assert sech(x).rewrite(tanh) == (1 - tanh_half)/(1 + tanh_half) coth_half = coth(S.Half*x)**2 assert sech(x).rewrite(coth) == (coth_half - 1)/(coth_half + 1) def test_derivs(): x = Symbol('x') assert coth(x).diff(x) == -sinh(x)**(-2) assert sinh(x).diff(x) == cosh(x) assert cosh(x).diff(x) == sinh(x) assert tanh(x).diff(x) == -tanh(x)**2 + 1 assert csch(x).diff(x) == -coth(x)*csch(x) assert sech(x).diff(x) == -tanh(x)*sech(x) assert acoth(x).diff(x) == 1/(-x**2 + 1) assert asinh(x).diff(x) == 1/sqrt(x**2 + 1) assert acosh(x).diff(x) == 1/sqrt(x**2 - 1) assert atanh(x).diff(x) == 1/(-x**2 + 1) assert asech(x).diff(x) == -1/(x*sqrt(1 - x**2)) assert acsch(x).diff(x) == -1/(x**2*sqrt(1 + x**(-2))) def test_sinh_expansion(): x, y = symbols('x,y') assert sinh(x+y).expand(trig=True) == sinh(x)*cosh(y) + cosh(x)*sinh(y) assert sinh(2*x).expand(trig=True) == 2*sinh(x)*cosh(x) assert sinh(3*x).expand(trig=True).expand() == \ sinh(x)**3 + 3*sinh(x)*cosh(x)**2 def test_cosh_expansion(): x, y = symbols('x,y') assert cosh(x+y).expand(trig=True) == cosh(x)*cosh(y) + sinh(x)*sinh(y) assert cosh(2*x).expand(trig=True) == cosh(x)**2 + sinh(x)**2 assert cosh(3*x).expand(trig=True).expand() == \ 3*sinh(x)**2*cosh(x) + cosh(x)**3 def test_cosh_positive(): # See issue 11721 # cosh(x) is positive for real values of x k = symbols('k', real=True) n = symbols('n', integer=True) assert cosh(k, evaluate=False).is_positive is True assert cosh(k + 2*n*pi*I, evaluate=False).is_positive is True assert cosh(I*pi/4, evaluate=False).is_positive is True assert cosh(3*I*pi/4, evaluate=False).is_positive is False def test_cosh_nonnegative(): k = symbols('k', real=True) n = symbols('n', integer=True) assert cosh(k, evaluate=False).is_nonnegative is True assert cosh(k + 2*n*pi*I, evaluate=False).is_nonnegative is True assert cosh(I*pi/4, evaluate=False).is_nonnegative is True assert cosh(3*I*pi/4, evaluate=False).is_nonnegative is False assert cosh(S.Zero, evaluate=False).is_nonnegative is True def test_real_assumptions(): z = Symbol('z', real=False) assert sinh(z).is_real is None assert cosh(z).is_real is None assert tanh(z).is_real is None assert sech(z).is_real is None assert csch(z).is_real is None assert coth(z).is_real is None def test_sign_assumptions(): p = Symbol('p', positive=True) n = Symbol('n', negative=True) assert sinh(n).is_negative is True assert sinh(p).is_positive is True assert cosh(n).is_positive is True assert cosh(p).is_positive is True assert tanh(n).is_negative is True assert tanh(p).is_positive is True assert csch(n).is_negative is True assert csch(p).is_positive is True assert sech(n).is_positive is True assert sech(p).is_positive is True assert coth(n).is_negative is True assert coth(p).is_positive is True
863434ac70f330cefe545fb050029af1588824591a7a62f0c121a589422a79ac
from sympy import ( adjoint, conjugate, Dummy, Eijk, KroneckerDelta, LeviCivita, Symbol, symbols, transpose, Piecewise, Ne ) from sympy.physics.secondquant import evaluate_deltas, F x, y = symbols('x y') def test_levicivita(): assert Eijk(1, 2, 3) == LeviCivita(1, 2, 3) assert LeviCivita(1, 2, 3) == 1 assert LeviCivita(int(1), int(2), int(3)) == 1 assert LeviCivita(1, 3, 2) == -1 assert LeviCivita(1, 2, 2) == 0 i, j, k = symbols('i j k') assert LeviCivita(i, j, k) == LeviCivita(i, j, k, evaluate=False) assert LeviCivita(i, j, i) == 0 assert LeviCivita(1, i, i) == 0 assert LeviCivita(i, j, k).doit() == (j - i)*(k - i)*(k - j)/2 assert LeviCivita(1, 2, 3, 1) == 0 assert LeviCivita(4, 5, 1, 2, 3) == 1 assert LeviCivita(4, 5, 2, 1, 3) == -1 assert LeviCivita(i, j, k).is_integer is True assert adjoint(LeviCivita(i, j, k)) == LeviCivita(i, j, k) assert conjugate(LeviCivita(i, j, k)) == LeviCivita(i, j, k) assert transpose(LeviCivita(i, j, k)) == LeviCivita(i, j, k) def test_kronecker_delta(): i, j = symbols('i j') k = Symbol('k', nonzero=True) assert KroneckerDelta(1, 1) == 1 assert KroneckerDelta(1, 2) == 0 assert KroneckerDelta(k, 0) == 0 assert KroneckerDelta(x, x) == 1 assert KroneckerDelta(x**2 - y**2, x**2 - y**2) == 1 assert KroneckerDelta(i, i) == 1 assert KroneckerDelta(i, i + 1) == 0 assert KroneckerDelta(0, 0) == 1 assert KroneckerDelta(0, 1) == 0 assert KroneckerDelta(i + k, i) == 0 assert KroneckerDelta(i + k, i + k) == 1 assert KroneckerDelta(i + k, i + 1 + k) == 0 assert KroneckerDelta(i, j).subs(dict(i=1, j=0)) == 0 assert KroneckerDelta(i, j).subs(dict(i=3, j=3)) == 1 assert KroneckerDelta(i, j)**0 == 1 for n in range(1, 10): assert KroneckerDelta(i, j)**n == KroneckerDelta(i, j) assert KroneckerDelta(i, j)**-n == 1/KroneckerDelta(i, j) assert KroneckerDelta(i, j).is_integer is True assert adjoint(KroneckerDelta(i, j)) == KroneckerDelta(i, j) assert conjugate(KroneckerDelta(i, j)) == KroneckerDelta(i, j) assert transpose(KroneckerDelta(i, j)) == KroneckerDelta(i, j) # to test if canonical assert (KroneckerDelta(i, j) == KroneckerDelta(j, i)) == True assert KroneckerDelta(i, j).rewrite(Piecewise) == Piecewise((0, Ne(i, j)), (1, True)) # Tests with range: assert KroneckerDelta(i, j, (0, i)).args == (i, j, (0, i)) assert KroneckerDelta(i, j, (-j, i)).delta_range == (-j, i) # If index is out of range, return zero: assert KroneckerDelta(i, j, (0, i-1)) == 0 assert KroneckerDelta(-1, j, (0, i-1)) == 0 assert KroneckerDelta(j, -1, (0, i-1)) == 0 assert KroneckerDelta(j, i, (0, i-1)) == 0 def test_kronecker_delta_secondquant(): """secondquant-specific methods""" D = KroneckerDelta i, j, v, w = symbols('i j v w', below_fermi=True, cls=Dummy) a, b, t, u = symbols('a b t u', above_fermi=True, cls=Dummy) p, q, r, s = symbols('p q r s', cls=Dummy) assert D(i, a) == 0 assert D(i, t) == 0 assert D(i, j).is_above_fermi is False assert D(a, b).is_above_fermi is True assert D(p, q).is_above_fermi is True assert D(i, q).is_above_fermi is False assert D(q, i).is_above_fermi is False assert D(q, v).is_above_fermi is False assert D(a, q).is_above_fermi is True assert D(i, j).is_below_fermi is True assert D(a, b).is_below_fermi is False assert D(p, q).is_below_fermi is True assert D(p, j).is_below_fermi is True assert D(q, b).is_below_fermi is False assert D(i, j).is_only_above_fermi is False assert D(a, b).is_only_above_fermi is True assert D(p, q).is_only_above_fermi is False assert D(i, q).is_only_above_fermi is False assert D(q, i).is_only_above_fermi is False assert D(a, q).is_only_above_fermi is True assert D(i, j).is_only_below_fermi is True assert D(a, b).is_only_below_fermi is False assert D(p, q).is_only_below_fermi is False assert D(p, j).is_only_below_fermi is True assert D(q, b).is_only_below_fermi is False assert not D(i, q).indices_contain_equal_information assert not D(a, q).indices_contain_equal_information assert D(p, q).indices_contain_equal_information assert D(a, b).indices_contain_equal_information assert D(i, j).indices_contain_equal_information assert D(q, b).preferred_index == b assert D(q, b).killable_index == q assert D(q, t).preferred_index == t assert D(q, t).killable_index == q assert D(q, i).preferred_index == i assert D(q, i).killable_index == q assert D(q, v).preferred_index == v assert D(q, v).killable_index == q assert D(q, p).preferred_index == p assert D(q, p).killable_index == q EV = evaluate_deltas assert EV(D(a, q)*F(q)) == F(a) assert EV(D(i, q)*F(q)) == F(i) assert EV(D(a, q)*F(a)) == D(a, q)*F(a) assert EV(D(i, q)*F(i)) == D(i, q)*F(i) assert EV(D(a, b)*F(a)) == F(b) assert EV(D(a, b)*F(b)) == F(a) assert EV(D(i, j)*F(i)) == F(j) assert EV(D(i, j)*F(j)) == F(i) assert EV(D(p, q)*F(q)) == F(p) assert EV(D(p, q)*F(p)) == F(q) assert EV(D(p, j)*D(p, i)*F(i)) == F(j) assert EV(D(p, j)*D(p, i)*F(j)) == F(i) assert EV(D(p, q)*D(p, i))*F(i) == D(q, i)*F(i)
81cb0a3c9cd6a54a832e2c5cb4ee314e9f8dcfe014200c6c7f6d0d707c7979f1
from sympy.functions import bspline_basis_set, interpolating_spline from sympy import Piecewise, Interval, And from sympy import symbols, Rational, S from sympy.testing.pytest import slow x, y = symbols('x,y') def test_basic_degree_0(): d = 0 knots = range(5) splines = bspline_basis_set(d, knots, x) for i in range(len(splines)): assert splines[i] == Piecewise((1, Interval(i, i + 1).contains(x)), (0, True)) def test_basic_degree_1(): d = 1 knots = range(5) splines = bspline_basis_set(d, knots, x) assert splines[0] == Piecewise((x, Interval(0, 1).contains(x)), (2 - x, Interval(1, 2).contains(x)), (0, True)) assert splines[1] == Piecewise((-1 + x, Interval(1, 2).contains(x)), (3 - x, Interval(2, 3).contains(x)), (0, True)) assert splines[2] == Piecewise((-2 + x, Interval(2, 3).contains(x)), (4 - x, Interval(3, 4).contains(x)), (0, True)) def test_basic_degree_2(): d = 2 knots = range(5) splines = bspline_basis_set(d, knots, x) b0 = Piecewise((x**2/2, Interval(0, 1).contains(x)), (Rational(-3, 2) + 3*x - x**2, Interval(1, 2).contains(x)), (Rational(9, 2) - 3*x + x**2/2, Interval(2, 3).contains(x)), (0, True)) b1 = Piecewise((S.Half - x + x**2/2, Interval(1, 2).contains(x)), (Rational(-11, 2) + 5*x - x**2, Interval(2, 3).contains(x)), (8 - 4*x + x**2/2, Interval(3, 4).contains(x)), (0, True)) assert splines[0] == b0 assert splines[1] == b1 def test_basic_degree_3(): d = 3 knots = range(5) splines = bspline_basis_set(d, knots, x) b0 = Piecewise( (x**3/6, Interval(0, 1).contains(x)), (Rational(2, 3) - 2*x + 2*x**2 - x**3/2, Interval(1, 2).contains(x)), (Rational(-22, 3) + 10*x - 4*x**2 + x**3/2, Interval(2, 3).contains(x)), (Rational(32, 3) - 8*x + 2*x**2 - x**3/6, Interval(3, 4).contains(x)), (0, True) ) assert splines[0] == b0 def test_repeated_degree_1(): d = 1 knots = [0, 0, 1, 2, 2, 3, 4, 4] splines = bspline_basis_set(d, knots, x) assert splines[0] == Piecewise((1 - x, Interval(0, 1).contains(x)), (0, True)) assert splines[1] == Piecewise((x, Interval(0, 1).contains(x)), (2 - x, Interval(1, 2).contains(x)), (0, True)) assert splines[2] == Piecewise((-1 + x, Interval(1, 2).contains(x)), (0, True)) assert splines[3] == Piecewise((3 - x, Interval(2, 3).contains(x)), (0, True)) assert splines[4] == Piecewise((-2 + x, Interval(2, 3).contains(x)), (4 - x, Interval(3, 4).contains(x)), (0, True)) assert splines[5] == Piecewise((-3 + x, Interval(3, 4).contains(x)), (0, True)) def test_repeated_degree_2(): d = 2 knots = [0, 0, 1, 2, 2, 3, 4, 4] splines = bspline_basis_set(d, knots, x) assert splines[0] == Piecewise(((-3*x**2/2 + 2*x), And(x <= 1, x >= 0)), (x**2/2 - 2*x + 2, And(x <= 2, x >= 1)), (0, True)) assert splines[1] == Piecewise((x**2/2, And(x <= 1, x >= 0)), (-3*x**2/2 + 4*x - 2, And(x <= 2, x >= 1)), (0, True)) assert splines[2] == Piecewise((x**2 - 2*x + 1, And(x <= 2, x >= 1)), (x**2 - 6*x + 9, And(x <= 3, x >= 2)), (0, True)) assert splines[3] == Piecewise((-3*x**2/2 + 8*x - 10, And(x <= 3, x >= 2)), (x**2/2 - 4*x + 8, And(x <= 4, x >= 3)), (0, True)) assert splines[4] == Piecewise((x**2/2 - 2*x + 2, And(x <= 3, x >= 2)), (-3*x**2/2 + 10*x - 16, And(x <= 4, x >= 3)), (0, True)) # Tests for interpolating_spline def test_10_points_degree_1(): d = 1 X = [-5, 2, 3, 4, 7, 9, 10, 30, 31, 34] Y = [-10, -2, 2, 4, 7, 6, 20, 45, 19, 25] spline = interpolating_spline(d, x, X, Y) assert spline == Piecewise((x*Rational(8, 7) - Rational(30, 7), (x >= -5) & (x <= 2)), (4*x - 10, (x >= 2) & (x <= 3)), (2*x - 4, (x >= 3) & (x <= 4)), (x, (x >= 4) & (x <= 7)), (-x/2 + Rational(21, 2), (x >= 7) & (x <= 9)), (14*x - 120, (x >= 9) & (x <= 10)), (x*Rational(5, 4) + Rational(15, 2), (x >= 10) & (x <= 30)), (-26*x + 825, (x >= 30) & (x <= 31)), (2*x - 43, (x >= 31) & (x <= 34))) def test_3_points_degree_2(): d = 2 X = [-3, 10, 19] Y = [3, -4, 30] spline = interpolating_spline(d, x, X, Y) assert spline == Piecewise((505*x**2/2574 - x*Rational(4921, 2574) - Rational(1931, 429), (x >= -3) & (x <= 19))) def test_5_points_degree_2(): d = 2 X = [-3, 2, 4, 5, 10] Y = [-1, 2, 5, 10, 14] spline = interpolating_spline(d, x, X, Y) assert spline == Piecewise((4*x**2/329 + x*Rational(1007, 1645) + Rational(1196, 1645), (x >= -3) & (x <= 3)), (2701*x**2/1645 - x*Rational(15079, 1645) + Rational(5065, 329), (x >= 3) & (x <= Rational(9, 2))), (-1319*x**2/1645 + x*Rational(21101, 1645) - Rational(11216, 329), (x >= Rational(9, 2)) & (x <= 10))) @slow def test_6_points_degree_3(): d = 3 X = [-1, 0, 2, 3, 9, 12] Y = [-4, 3, 3, 7, 9, 20] spline = interpolating_spline(d, x, X, Y) assert spline == Piecewise((6058*x**3/5301 - 18427*x**2/5301 + x*Rational(12622, 5301) + 3, (x >= -1) & (x <= 2)), (-8327*x**3/5301 + 67883*x**2/5301 - x*Rational(159998, 5301) + Rational(43661, 1767), (x >= 2) & (x <= 3)), (5414*x**3/47709 - 1386*x**2/589 + x*Rational(4267, 279) - Rational(12232, 589), (x >= 3) & (x <= 12)))
1fdec0b6010d59489d9fecb7f7821d42823ae930de6bee58435c85350f05e18f
from sympy import (hyper, meijerg, S, Tuple, pi, I, exp, log, Rational, cos, sqrt, symbols, oo, Derivative, gamma, O, appellf1) from sympy.abc import x, z, k from sympy.series.limits import limit from sympy.testing.pytest import raises, slow from sympy.testing.randtest import ( random_complex_number as randcplx, verify_numerically as tn, test_derivative_numerically as td) def test_TupleParametersBase(): # test that our implementation of the chain rule works p = hyper((), (), z**2) assert p.diff(z) == p*2*z def test_hyper(): raises(TypeError, lambda: hyper(1, 2, z)) assert hyper((1, 2), (1,), z) == hyper(Tuple(1, 2), Tuple(1), z) h = hyper((1, 2), (3, 4, 5), z) assert h.ap == Tuple(1, 2) assert h.bq == Tuple(3, 4, 5) assert h.argument == z assert h.is_commutative is True # just a few checks to make sure that all arguments go where they should assert tn(hyper(Tuple(), Tuple(), z), exp(z), z) assert tn(z*hyper((1, 1), Tuple(2), -z), log(1 + z), z) # differentiation h = hyper( (randcplx(), randcplx(), randcplx()), (randcplx(), randcplx()), z) assert td(h, z) a1, a2, b1, b2, b3 = symbols('a1:3, b1:4') assert hyper((a1, a2), (b1, b2, b3), z).diff(z) == \ a1*a2/(b1*b2*b3) * hyper((a1 + 1, a2 + 1), (b1 + 1, b2 + 1, b3 + 1), z) # differentiation wrt parameters is not supported assert hyper([z], [], z).diff(z) == Derivative(hyper([z], [], z), z) # hyper is unbranched wrt parameters from sympy import polar_lift assert hyper([polar_lift(z)], [polar_lift(k)], polar_lift(x)) == \ hyper([z], [k], polar_lift(x)) # hyper does not automatically evaluate anyway, but the test is to make # sure that the evaluate keyword is accepted assert hyper((1, 2), (1,), z, evaluate=False).func is hyper def test_expand_func(): # evaluation at 1 of Gauss' hypergeometric function: from sympy.abc import a, b, c from sympy import gamma, expand_func a1, b1, c1 = randcplx(), randcplx(), randcplx() + 5 assert expand_func(hyper([a, b], [c], 1)) == \ gamma(c)*gamma(-a - b + c)/(gamma(-a + c)*gamma(-b + c)) assert abs(expand_func(hyper([a1, b1], [c1], 1)).n() - hyper([a1, b1], [c1], 1).n()) < 1e-10 # hyperexpand wrapper for hyper: assert expand_func(hyper([], [], z)) == exp(z) assert expand_func(hyper([1, 2, 3], [], z)) == hyper([1, 2, 3], [], z) assert expand_func(meijerg([[1, 1], []], [[1], [0]], z)) == log(z + 1) assert expand_func(meijerg([[1, 1], []], [[], []], z)) == \ meijerg([[1, 1], []], [[], []], z) def replace_dummy(expr, sym): from sympy import Dummy dum = expr.atoms(Dummy) if not dum: return expr assert len(dum) == 1 return expr.xreplace({dum.pop(): sym}) def test_hyper_rewrite_sum(): from sympy import RisingFactorial, factorial, Dummy, Sum _k = Dummy("k") assert replace_dummy(hyper((1, 2), (1, 3), x).rewrite(Sum), _k) == \ Sum(x**_k / factorial(_k) * RisingFactorial(2, _k) / RisingFactorial(3, _k), (_k, 0, oo)) assert hyper((1, 2, 3), (-1, 3), z).rewrite(Sum) == \ hyper((1, 2, 3), (-1, 3), z) def test_radius_of_convergence(): assert hyper((1, 2), [3], z).radius_of_convergence == 1 assert hyper((1, 2), [3, 4], z).radius_of_convergence is oo assert hyper((1, 2, 3), [4], z).radius_of_convergence == 0 assert hyper((0, 1, 2), [4], z).radius_of_convergence is oo assert hyper((-1, 1, 2), [-4], z).radius_of_convergence == 0 assert hyper((-1, -2, 2), [-1], z).radius_of_convergence is oo assert hyper((-1, 2), [-1, -2], z).radius_of_convergence == 0 assert hyper([-1, 1, 3], [-2, 2], z).radius_of_convergence == 1 assert hyper([-1, 1], [-2, 2], z).radius_of_convergence is oo assert hyper([-1, 1, 3], [-2], z).radius_of_convergence == 0 assert hyper((-1, 2, 3, 4), [], z).radius_of_convergence is oo assert hyper([1, 1], [3], 1).convergence_statement == True assert hyper([1, 1], [2], 1).convergence_statement == False assert hyper([1, 1], [2], -1).convergence_statement == True assert hyper([1, 1], [1], -1).convergence_statement == False def test_meijer(): raises(TypeError, lambda: meijerg(1, z)) raises(TypeError, lambda: meijerg(((1,), (2,)), (3,), (4,), z)) assert meijerg(((1, 2), (3,)), ((4,), (5,)), z) == \ meijerg(Tuple(1, 2), Tuple(3), Tuple(4), Tuple(5), z) g = meijerg((1, 2), (3, 4, 5), (6, 7, 8, 9), (10, 11, 12, 13, 14), z) assert g.an == Tuple(1, 2) assert g.ap == Tuple(1, 2, 3, 4, 5) assert g.aother == Tuple(3, 4, 5) assert g.bm == Tuple(6, 7, 8, 9) assert g.bq == Tuple(6, 7, 8, 9, 10, 11, 12, 13, 14) assert g.bother == Tuple(10, 11, 12, 13, 14) assert g.argument == z assert g.nu == 75 assert g.delta == -1 assert g.is_commutative is True assert g.is_number is False #issue 13071 assert meijerg([[],[]], [[S.Half],[0]], 1).is_number is True assert meijerg([1, 2], [3], [4], [5], z).delta == S.Half # just a few checks to make sure that all arguments go where they should assert tn(meijerg(Tuple(), Tuple(), Tuple(0), Tuple(), -z), exp(z), z) assert tn(sqrt(pi)*meijerg(Tuple(), Tuple(), Tuple(0), Tuple(S.Half), z**2/4), cos(z), z) assert tn(meijerg(Tuple(1, 1), Tuple(), Tuple(1), Tuple(0), z), log(1 + z), z) # test exceptions raises(ValueError, lambda: meijerg(((3, 1), (2,)), ((oo,), (2, 0)), x)) raises(ValueError, lambda: meijerg(((3, 1), (2,)), ((1,), (2, 0)), x)) # differentiation g = meijerg((randcplx(),), (randcplx() + 2*I,), Tuple(), (randcplx(), randcplx()), z) assert td(g, z) g = meijerg(Tuple(), (randcplx(),), Tuple(), (randcplx(), randcplx()), z) assert td(g, z) g = meijerg(Tuple(), Tuple(), Tuple(randcplx()), Tuple(randcplx(), randcplx()), z) assert td(g, z) a1, a2, b1, b2, c1, c2, d1, d2 = symbols('a1:3, b1:3, c1:3, d1:3') assert meijerg((a1, a2), (b1, b2), (c1, c2), (d1, d2), z).diff(z) == \ (meijerg((a1 - 1, a2), (b1, b2), (c1, c2), (d1, d2), z) + (a1 - 1)*meijerg((a1, a2), (b1, b2), (c1, c2), (d1, d2), z))/z assert meijerg([z, z], [], [], [], z).diff(z) == \ Derivative(meijerg([z, z], [], [], [], z), z) # meijerg is unbranched wrt parameters from sympy import polar_lift as pl assert meijerg([pl(a1)], [pl(a2)], [pl(b1)], [pl(b2)], pl(z)) == \ meijerg([a1], [a2], [b1], [b2], pl(z)) # integrand from sympy.abc import a, b, c, d, s assert meijerg([a], [b], [c], [d], z).integrand(s) == \ z**s*gamma(c - s)*gamma(-a + s + 1)/(gamma(b - s)*gamma(-d + s + 1)) def test_meijerg_derivative(): assert meijerg([], [1, 1], [0, 0, x], [], z).diff(x) == \ log(z)*meijerg([], [1, 1], [0, 0, x], [], z) \ + 2*meijerg([], [1, 1, 1], [0, 0, x, 0], [], z) y = randcplx() a = 5 # mpmath chokes with non-real numbers, and Mod1 with floats assert td(meijerg([x], [], [], [], y), x) assert td(meijerg([x**2], [], [], [], y), x) assert td(meijerg([], [x], [], [], y), x) assert td(meijerg([], [], [x], [], y), x) assert td(meijerg([], [], [], [x], y), x) assert td(meijerg([x], [a], [a + 1], [], y), x) assert td(meijerg([x], [a + 1], [a], [], y), x) assert td(meijerg([x, a], [], [], [a + 1], y), x) assert td(meijerg([x, a + 1], [], [], [a], y), x) b = Rational(3, 2) assert td(meijerg([a + 2], [b], [b - 3, x], [a], y), x) def test_meijerg_period(): assert meijerg([], [1], [0], [], x).get_period() == 2*pi assert meijerg([1], [], [], [0], x).get_period() == 2*pi assert meijerg([], [], [0], [], x).get_period() == 2*pi # exp(x) assert meijerg( [], [], [0], [S.Half], x).get_period() == 2*pi # cos(sqrt(x)) assert meijerg( [], [], [S.Half], [0], x).get_period() == 4*pi # sin(sqrt(x)) assert meijerg([1, 1], [], [1], [0], x).get_period() is oo # log(1 + x) def test_hyper_unpolarify(): from sympy import exp_polar a = exp_polar(2*pi*I)*x b = x assert hyper([], [], a).argument == b assert hyper([0], [], a).argument == a assert hyper([0], [0], a).argument == b assert hyper([0, 1], [0], a).argument == a assert hyper([0, 1], [0], exp_polar(2*pi*I)).argument == 1 @slow def test_hyperrep(): from sympy.functions.special.hyper import (HyperRep, HyperRep_atanh, HyperRep_power1, HyperRep_power2, HyperRep_log1, HyperRep_asin1, HyperRep_asin2, HyperRep_sqrts1, HyperRep_sqrts2, HyperRep_log2, HyperRep_cosasin, HyperRep_sinasin) # First test the base class works. from sympy import Piecewise, exp_polar a, b, c, d, z = symbols('a b c d z') class myrep(HyperRep): @classmethod def _expr_small(cls, x): return a @classmethod def _expr_small_minus(cls, x): return b @classmethod def _expr_big(cls, x, n): return c*n @classmethod def _expr_big_minus(cls, x, n): return d*n assert myrep(z).rewrite('nonrep') == Piecewise((0, abs(z) > 1), (a, True)) assert myrep(exp_polar(I*pi)*z).rewrite('nonrep') == \ Piecewise((0, abs(z) > 1), (b, True)) assert myrep(exp_polar(2*I*pi)*z).rewrite('nonrep') == \ Piecewise((c, abs(z) > 1), (a, True)) assert myrep(exp_polar(3*I*pi)*z).rewrite('nonrep') == \ Piecewise((d, abs(z) > 1), (b, True)) assert myrep(exp_polar(4*I*pi)*z).rewrite('nonrep') == \ Piecewise((2*c, abs(z) > 1), (a, True)) assert myrep(exp_polar(5*I*pi)*z).rewrite('nonrep') == \ Piecewise((2*d, abs(z) > 1), (b, True)) assert myrep(z).rewrite('nonrepsmall') == a assert myrep(exp_polar(I*pi)*z).rewrite('nonrepsmall') == b def t(func, hyp, z): """ Test that func is a valid representation of hyp. """ # First test that func agrees with hyp for small z if not tn(func.rewrite('nonrepsmall'), hyp, z, a=Rational(-1, 2), b=Rational(-1, 2), c=S.Half, d=S.Half): return False # Next check that the two small representations agree. if not tn( func.rewrite('nonrepsmall').subs( z, exp_polar(I*pi)*z).replace(exp_polar, exp), func.subs(z, exp_polar(I*pi)*z).rewrite('nonrepsmall'), z, a=Rational(-1, 2), b=Rational(-1, 2), c=S.Half, d=S.Half): return False # Next check continuity along exp_polar(I*pi)*t expr = func.subs(z, exp_polar(I*pi)*z).rewrite('nonrep') if abs(expr.subs(z, 1 + 1e-15).n() - expr.subs(z, 1 - 1e-15).n()) > 1e-10: return False # Finally check continuity of the big reps. def dosubs(func, a, b): rv = func.subs(z, exp_polar(a)*z).rewrite('nonrep') return rv.subs(z, exp_polar(b)*z).replace(exp_polar, exp) for n in [0, 1, 2, 3, 4, -1, -2, -3, -4]: expr1 = dosubs(func, 2*I*pi*n, I*pi/2) expr2 = dosubs(func, 2*I*pi*n + I*pi, -I*pi/2) if not tn(expr1, expr2, z): return False expr1 = dosubs(func, 2*I*pi*(n + 1), -I*pi/2) expr2 = dosubs(func, 2*I*pi*n + I*pi, I*pi/2) if not tn(expr1, expr2, z): return False return True # Now test the various representatives. a = Rational(1, 3) assert t(HyperRep_atanh(z), hyper([S.Half, 1], [Rational(3, 2)], z), z) assert t(HyperRep_power1(a, z), hyper([-a], [], z), z) assert t(HyperRep_power2(a, z), hyper([a, a - S.Half], [2*a], z), z) assert t(HyperRep_log1(z), -z*hyper([1, 1], [2], z), z) assert t(HyperRep_asin1(z), hyper([S.Half, S.Half], [Rational(3, 2)], z), z) assert t(HyperRep_asin2(z), hyper([1, 1], [Rational(3, 2)], z), z) assert t(HyperRep_sqrts1(a, z), hyper([-a, S.Half - a], [S.Half], z), z) assert t(HyperRep_sqrts2(a, z), -2*z/(2*a + 1)*hyper([-a - S.Half, -a], [S.Half], z).diff(z), z) assert t(HyperRep_log2(z), -z/4*hyper([Rational(3, 2), 1, 1], [2, 2], z), z) assert t(HyperRep_cosasin(a, z), hyper([-a, a], [S.Half], z), z) assert t(HyperRep_sinasin(a, z), 2*a*z*hyper([1 - a, 1 + a], [Rational(3, 2)], z), z) @slow def test_meijerg_eval(): from sympy import besseli, exp_polar from sympy.abc import l a = randcplx() arg = x*exp_polar(k*pi*I) expr1 = pi*meijerg([[], [(a + 1)/2]], [[a/2], [-a/2, (a + 1)/2]], arg**2/4) expr2 = besseli(a, arg) # Test that the two expressions agree for all arguments. for x_ in [0.5, 1.5]: for k_ in [0.0, 0.1, 0.3, 0.5, 0.8, 1, 5.751, 15.3]: assert abs((expr1 - expr2).n(subs={x: x_, k: k_})) < 1e-10 assert abs((expr1 - expr2).n(subs={x: x_, k: -k_})) < 1e-10 # Test continuity independently eps = 1e-13 expr2 = expr1.subs(k, l) for x_ in [0.5, 1.5]: for k_ in [0.5, Rational(1, 3), 0.25, 0.75, Rational(2, 3), 1.0, 1.5]: assert abs((expr1 - expr2).n( subs={x: x_, k: k_ + eps, l: k_ - eps})) < 1e-10 assert abs((expr1 - expr2).n( subs={x: x_, k: -k_ + eps, l: -k_ - eps})) < 1e-10 expr = (meijerg(((0.5,), ()), ((0.5, 0, 0.5), ()), exp_polar(-I*pi)/4) + meijerg(((0.5,), ()), ((0.5, 0, 0.5), ()), exp_polar(I*pi)/4)) \ /(2*sqrt(pi)) assert (expr - pi/exp(1)).n(chop=True) == 0 def test_limits(): k, x = symbols('k, x') assert hyper((1,), (Rational(4, 3), Rational(5, 3)), k**2).series(k) == \ 1 + 9*k**2/20 + 81*k**4/1120 + O(k**6) # issue 6350 assert limit(meijerg((), (), (1,), (0,), -x), x, 0) == \ meijerg(((), ()), ((1,), (0,)), 0) # issue 6052 def test_appellf1(): a, b1, b2, c, x, y = symbols('a b1 b2 c x y') assert appellf1(a, b2, b1, c, y, x) == appellf1(a, b1, b2, c, x, y) assert appellf1(a, b1, b1, c, y, x) == appellf1(a, b1, b1, c, x, y) assert appellf1(a, b1, b2, c, S.Zero, S.Zero) is S.One f = appellf1(a, b1, b2, c, S.Zero, S.Zero, evaluate=False) assert f.func is appellf1 assert f.doit() is S.One def test_derivative_appellf1(): from sympy import diff a, b1, b2, c, x, y, z = symbols('a b1 b2 c x y z') assert diff(appellf1(a, b1, b2, c, x, y), x) == a*b1*appellf1(a + 1, b2, b1 + 1, c + 1, y, x)/c assert diff(appellf1(a, b1, b2, c, x, y), y) == a*b2*appellf1(a + 1, b1, b2 + 1, c + 1, x, y)/c assert diff(appellf1(a, b1, b2, c, x, y), z) == 0 assert diff(appellf1(a, b1, b2, c, x, y), a) == Derivative(appellf1(a, b1, b2, c, x, y), a) def test_eval_nseries(): a1, b1, a2, b2 = symbols('a1 b1 a2 b2') assert hyper((1,2), (1,2,3), x**2)._eval_nseries(x, 7, None) == 1 + x**2/3 + x**4/24 + x**6/360 + O(x**7) assert exp(x)._eval_nseries(x,7,None) == hyper((a1, b1), (a1, b1), x)._eval_nseries(x, 7, None) assert hyper((a1, a2), (b1, b2), x)._eval_nseries(z, 7, None) == hyper((a1, a2), (b1, b2), x) + O(z**7)
e9a6376d64741e4b56d8720ce2ae784df4e77567a5551c64c4a1f3341f9403be
from sympy import ( adjoint, conjugate, DiracDelta, Heaviside, nan, pi, sign, sqrt, symbols, transpose, Symbol, Piecewise, I, S, Eq, Ne, oo, SingularityFunction, signsimp ) from sympy.testing.pytest import raises, warns_deprecated_sympy from sympy.core.function import ArgumentIndexError x, y = symbols('x y') i = symbols('t', nonzero=True) j = symbols('j', positive=True) k = symbols('k', negative=True) def test_DiracDelta(): assert DiracDelta(1) == 0 assert DiracDelta(5.1) == 0 assert DiracDelta(-pi) == 0 assert DiracDelta(5, 7) == 0 assert DiracDelta(i) == 0 assert DiracDelta(j) == 0 assert DiracDelta(k) == 0 assert DiracDelta(nan) is nan assert DiracDelta(0).func is DiracDelta assert DiracDelta(x).func is DiracDelta # FIXME: this is generally undefined @ x=0 # But then limit(Delta(c)*Heaviside(x),x,-oo) # need's to be implemented. # assert 0*DiracDelta(x) == 0 assert adjoint(DiracDelta(x)) == DiracDelta(x) assert adjoint(DiracDelta(x - y)) == DiracDelta(x - y) assert conjugate(DiracDelta(x)) == DiracDelta(x) assert conjugate(DiracDelta(x - y)) == DiracDelta(x - y) assert transpose(DiracDelta(x)) == DiracDelta(x) assert transpose(DiracDelta(x - y)) == DiracDelta(x - y) assert DiracDelta(x).diff(x) == DiracDelta(x, 1) assert DiracDelta(x, 1).diff(x) == DiracDelta(x, 2) assert DiracDelta(x).is_simple(x) is True assert DiracDelta(3*x).is_simple(x) is True assert DiracDelta(x**2).is_simple(x) is False assert DiracDelta(sqrt(x)).is_simple(x) is False assert DiracDelta(x).is_simple(y) is False assert DiracDelta(x*y).expand(diracdelta=True, wrt=x) == DiracDelta(x)/abs(y) assert DiracDelta(x*y).expand(diracdelta=True, wrt=y) == DiracDelta(y)/abs(x) assert DiracDelta(x**2*y).expand(diracdelta=True, wrt=x) == DiracDelta(x**2*y) assert DiracDelta(y).expand(diracdelta=True, wrt=x) == DiracDelta(y) assert DiracDelta((x - 1)*(x - 2)*(x - 3)).expand(diracdelta=True, wrt=x) == ( DiracDelta(x - 3)/2 + DiracDelta(x - 2) + DiracDelta(x - 1)/2) assert DiracDelta(2*x) != DiracDelta(x) # scaling property assert DiracDelta(x) == DiracDelta(-x) # even function assert DiracDelta(-x, 2) == DiracDelta(x, 2) assert DiracDelta(-x, 1) == -DiracDelta(x, 1) # odd deriv is odd assert DiracDelta(-oo*x) == DiracDelta(oo*x) assert DiracDelta(x - y) != DiracDelta(y - x) assert signsimp(DiracDelta(x - y) - DiracDelta(y - x)) == 0 with warns_deprecated_sympy(): assert DiracDelta(x*y).simplify(x) == DiracDelta(x)/abs(y) with warns_deprecated_sympy(): assert DiracDelta(x*y).simplify(y) == DiracDelta(y)/abs(x) with warns_deprecated_sympy(): assert DiracDelta(x**2*y).simplify(x) == DiracDelta(x**2*y) with warns_deprecated_sympy(): assert DiracDelta(y).simplify(x) == DiracDelta(y) with warns_deprecated_sympy(): assert DiracDelta((x - 1)*(x - 2)*(x - 3)).simplify(x) == ( DiracDelta(x - 3)/2 + DiracDelta(x - 2) + DiracDelta(x - 1)/2) raises(ArgumentIndexError, lambda: DiracDelta(x).fdiff(2)) raises(ValueError, lambda: DiracDelta(x, -1)) raises(ValueError, lambda: DiracDelta(I)) raises(ValueError, lambda: DiracDelta(2 + 3*I)) def test_heaviside(): assert Heaviside(0).func == Heaviside assert Heaviside(-5) == 0 assert Heaviside(1) == 1 assert Heaviside(nan) is nan assert Heaviside(0, x) == x assert Heaviside(0, nan) is nan assert Heaviside(x, None) == Heaviside(x) assert Heaviside(0, None) == Heaviside(0) # we do not want None and Heaviside(0) in the args: assert Heaviside(x, H0=None).args == (x,) assert Heaviside(x, H0=Heaviside(0)).args == (x,) assert adjoint(Heaviside(x)) == Heaviside(x) assert adjoint(Heaviside(x - y)) == Heaviside(x - y) assert conjugate(Heaviside(x)) == Heaviside(x) assert conjugate(Heaviside(x - y)) == Heaviside(x - y) assert transpose(Heaviside(x)) == Heaviside(x) assert transpose(Heaviside(x - y)) == Heaviside(x - y) assert Heaviside(x).diff(x) == DiracDelta(x) assert Heaviside(x + I).is_Function is True assert Heaviside(I*x).is_Function is True raises(ArgumentIndexError, lambda: Heaviside(x).fdiff(2)) raises(ValueError, lambda: Heaviside(I)) raises(ValueError, lambda: Heaviside(2 + 3*I)) def test_rewrite(): x, y = Symbol('x', real=True), Symbol('y') assert Heaviside(x).rewrite(Piecewise) == ( Piecewise((0, x < 0), (Heaviside(0), Eq(x, 0)), (1, x > 0))) assert Heaviside(y).rewrite(Piecewise) == ( Piecewise((0, y < 0), (Heaviside(0), Eq(y, 0)), (1, y > 0))) assert Heaviside(x, y).rewrite(Piecewise) == ( Piecewise((0, x < 0), (y, Eq(x, 0)), (1, x > 0))) assert Heaviside(x, 0).rewrite(Piecewise) == ( Piecewise((0, x <= 0), (1, x > 0))) assert Heaviside(x, 1).rewrite(Piecewise) == ( Piecewise((0, x < 0), (1, x >= 0))) assert Heaviside(x).rewrite(sign) == \ Heaviside(x, H0=Heaviside(0)).rewrite(sign) == \ Piecewise( (sign(x)/2 + S(1)/2, Eq(Heaviside(0), S(1)/2)), (Piecewise( (sign(x)/2 + S(1)/2, Ne(x, 0)), (Heaviside(0), True)), True) ) assert Heaviside(y).rewrite(sign) == Heaviside(y) assert Heaviside(x, S.Half).rewrite(sign) == (sign(x)+1)/2 assert Heaviside(x, y).rewrite(sign) == \ Piecewise( (sign(x)/2 + S(1)/2, Eq(y, S(1)/2)), (Piecewise( (sign(x)/2 + S(1)/2, Ne(x, 0)), (y, True)), True) ) assert DiracDelta(y).rewrite(Piecewise) == Piecewise((DiracDelta(0), Eq(y, 0)), (0, True)) assert DiracDelta(y, 1).rewrite(Piecewise) == DiracDelta(y, 1) assert DiracDelta(x - 5).rewrite(Piecewise) == ( Piecewise((DiracDelta(0), Eq(x - 5, 0)), (0, True))) assert (x*DiracDelta(x - 10)).rewrite(SingularityFunction) == x*SingularityFunction(x, 10, -1) assert 5*x*y*DiracDelta(y, 1).rewrite(SingularityFunction) == 5*x*y*SingularityFunction(y, 0, -2) assert DiracDelta(0).rewrite(SingularityFunction) == SingularityFunction(0, 0, -1) assert DiracDelta(0, 1).rewrite(SingularityFunction) == SingularityFunction(0, 0, -2) assert Heaviside(x).rewrite(SingularityFunction) == SingularityFunction(x, 0, 0) assert 5*x*y*Heaviside(y + 1).rewrite(SingularityFunction) == 5*x*y*SingularityFunction(y, -1, 0) assert ((x - 3)**3*Heaviside(x - 3)).rewrite(SingularityFunction) == (x - 3)**3*SingularityFunction(x, 3, 0) assert Heaviside(0).rewrite(SingularityFunction) == SingularityFunction(0, 0, 0) def test_issue_15923(): x = Symbol('x', real=True) assert Heaviside(x).rewrite(Piecewise, H0=0) == ( Piecewise((0, x <= 0), (1, True))) assert Heaviside(x).rewrite(Piecewise, H0=1) == ( Piecewise((0, x < 0), (1, True))) assert Heaviside(x).rewrite(Piecewise, H0=S.Half) == ( Piecewise((0, x < 0), (S.Half, Eq(x, 0)), (1, x > 0)))
4a0f5397f97b8ff282579da9e6ae8cc8a93f411366a6f9de6df9253f4d036b18
from sympy import (Symbol, gamma, expand_func, beta, diff, conjugate) from sympy.functions.special.gamma_functions import polygamma from sympy.core.function import ArgumentIndexError from sympy.testing.pytest import raises def test_beta(): x, y = Symbol('x'), Symbol('y') assert isinstance(beta(x, y), beta) assert expand_func(beta(x, y)) == gamma(x)*gamma(y)/gamma(x + y) assert expand_func(beta(x, y) - beta(y, x)) == 0 # Symmetric assert expand_func(beta(x, y)) == expand_func(beta(x, y + 1) + beta(x + 1, y)).simplify() assert diff(beta(x, y), x) == beta(x, y)*(polygamma(0, x) - polygamma(0, x + y)) assert diff(beta(x, y), y) == beta(x, y)*(polygamma(0, y) - polygamma(0, x + y)) assert conjugate(beta(x, y)) == beta(conjugate(x), conjugate(y)) raises(ArgumentIndexError, lambda: beta(x, y).fdiff(3)) assert beta(x, y).rewrite(gamma) == gamma(x)*gamma(y)/gamma(x + y)
77397ee07625f6ae2c8614a3893baff2aa879fa4d077c5fd1affd23d75fce0db
from sympy import (Symbol, zeta, nan, Rational, Float, pi, dirichlet_eta, log, zoo, expand_func, polylog, lerchphi, S, exp, sqrt, I, exp_polar, polar_lift, O, stieltjes, Abs, Sum, oo) from sympy.core.function import ArgumentIndexError from sympy.functions.combinatorial.numbers import bernoulli, factorial from sympy.testing.pytest import raises from sympy.testing.randtest import (test_derivative_numerically as td, random_complex_number as randcplx, verify_numerically as tn) x = Symbol('x') a = Symbol('a') b = Symbol('b', negative=True) z = Symbol('z') s = Symbol('s') def test_zeta_eval(): assert zeta(nan) is nan assert zeta(x, nan) is nan assert zeta(0) == Rational(-1, 2) assert zeta(0, x) == S.Half - x assert zeta(0, b) == S.Half - b assert zeta(1) is zoo assert zeta(1, 2) is zoo assert zeta(1, -7) is zoo assert zeta(1, x) is zoo assert zeta(2, 1) == pi**2/6 assert zeta(2) == pi**2/6 assert zeta(4) == pi**4/90 assert zeta(6) == pi**6/945 assert zeta(2, 2) == pi**2/6 - 1 assert zeta(4, 3) == pi**4/90 - Rational(17, 16) assert zeta(6, 4) == pi**6/945 - Rational(47449, 46656) assert zeta(2, -2) == pi**2/6 + Rational(5, 4) assert zeta(4, -3) == pi**4/90 + Rational(1393, 1296) assert zeta(6, -4) == pi**6/945 + Rational(3037465, 2985984) assert zeta(oo) == 1 assert zeta(-1) == Rational(-1, 12) assert zeta(-2) == 0 assert zeta(-3) == Rational(1, 120) assert zeta(-4) == 0 assert zeta(-5) == Rational(-1, 252) assert zeta(-1, 3) == Rational(-37, 12) assert zeta(-1, 7) == Rational(-253, 12) assert zeta(-1, -4) == Rational(119, 12) assert zeta(-1, -9) == Rational(539, 12) assert zeta(-4, 3) == -17 assert zeta(-4, -8) == 8772 assert zeta(0, 1) == Rational(-1, 2) assert zeta(0, -1) == Rational(3, 2) assert zeta(0, 2) == Rational(-3, 2) assert zeta(0, -2) == Rational(5, 2) assert zeta( 3).evalf(20).epsilon_eq(Float("1.2020569031595942854", 20), 1e-19) def test_zeta_series(): assert zeta(x, a).series(a, 0, 2) == \ zeta(x, 0) - x*a*zeta(x + 1, 0) + O(a**2) def test_dirichlet_eta_eval(): assert dirichlet_eta(0) == S.Half assert dirichlet_eta(-1) == Rational(1, 4) assert dirichlet_eta(1) == log(2) assert dirichlet_eta(2) == pi**2/12 assert dirichlet_eta(4) == pi**4*Rational(7, 720) def test_rewriting(): assert dirichlet_eta(x).rewrite(zeta) == (1 - 2**(1 - x))*zeta(x) assert zeta(x).rewrite(dirichlet_eta) == dirichlet_eta(x)/(1 - 2**(1 - x)) assert zeta(x).rewrite(dirichlet_eta, a=2) == zeta(x) assert tn(dirichlet_eta(x), dirichlet_eta(x).rewrite(zeta), x) assert tn(zeta(x), zeta(x).rewrite(dirichlet_eta), x) assert zeta(x, a).rewrite(lerchphi) == lerchphi(1, x, a) assert polylog(s, z).rewrite(lerchphi) == lerchphi(z, s, 1)*z assert lerchphi(1, x, a).rewrite(zeta) == zeta(x, a) assert z*lerchphi(z, s, 1).rewrite(polylog) == polylog(s, z) def test_derivatives(): from sympy import Derivative assert zeta(x, a).diff(x) == Derivative(zeta(x, a), x) assert zeta(x, a).diff(a) == -x*zeta(x + 1, a) assert lerchphi( z, s, a).diff(z) == (lerchphi(z, s - 1, a) - a*lerchphi(z, s, a))/z assert lerchphi(z, s, a).diff(a) == -s*lerchphi(z, s + 1, a) assert polylog(s, z).diff(z) == polylog(s - 1, z)/z b = randcplx() c = randcplx() assert td(zeta(b, x), x) assert td(polylog(b, z), z) assert td(lerchphi(c, b, x), x) assert td(lerchphi(x, b, c), x) raises(ArgumentIndexError, lambda: lerchphi(c, b, x).fdiff(2)) raises(ArgumentIndexError, lambda: lerchphi(c, b, x).fdiff(4)) raises(ArgumentIndexError, lambda: polylog(b, z).fdiff(1)) raises(ArgumentIndexError, lambda: polylog(b, z).fdiff(3)) def myexpand(func, target): expanded = expand_func(func) if target is not None: return expanded == target if expanded == func: # it didn't expand return False # check to see that the expanded and original evaluate to the same value subs = {} for a in func.free_symbols: subs[a] = randcplx() return abs(func.subs(subs).n() - expanded.replace(exp_polar, exp).subs(subs).n()) < 1e-10 def test_polylog_expansion(): from sympy import log assert polylog(s, 0) == 0 assert polylog(s, 1) == zeta(s) assert polylog(s, -1) == -dirichlet_eta(s) assert polylog(s, exp_polar(I*pi*Rational(4, 3))) == polylog(s, exp(I*pi*Rational(4, 3))) assert polylog(s, exp_polar(I*pi)/3) == polylog(s, exp(I*pi)/3) assert myexpand(polylog(1, z), -log(1 - z)) assert myexpand(polylog(0, z), z/(1 - z)) assert myexpand(polylog(-1, z), z/(1 - z)**2) assert ((1-z)**3 * expand_func(polylog(-2, z))).simplify() == z*(1 + z) assert myexpand(polylog(-5, z), None) def test_issue_8404(): i = Symbol('i', integer=True) assert Abs(Sum(1/(3*i + 1)**2, (i, 0, S.Infinity)).doit().n(4) - 1.122) < 0.001 def test_polylog_values(): from sympy.testing.randtest import verify_numerically as tn assert polylog(2, 2) == pi**2/4 - I*pi*log(2) assert polylog(2, S.Half) == pi**2/12 - log(2)**2/2 for z in [S.Half, 2, (sqrt(5)-1)/2, -(sqrt(5)-1)/2, -(sqrt(5)+1)/2, (3-sqrt(5))/2]: assert Abs(polylog(2, z).evalf() - polylog(2, z, evaluate=False).evalf()) < 1e-15 z = Symbol("z") for s in [-1, 0]: for _ in range(10): assert tn(polylog(s, z), polylog(s, z, evaluate=False), z, a=-3, b=-2, c=S.Half, d=2) assert tn(polylog(s, z), polylog(s, z, evaluate=False), z, a=2, b=-2, c=5, d=2) from sympy import Integral assert polylog(0, Integral(1, (x, 0, 1))) == -S.Half def test_lerchphi_expansion(): assert myexpand(lerchphi(1, s, a), zeta(s, a)) assert myexpand(lerchphi(z, s, 1), polylog(s, z)/z) # direct summation assert myexpand(lerchphi(z, -1, a), a/(1 - z) + z/(1 - z)**2) assert myexpand(lerchphi(z, -3, a), None) # polylog reduction assert myexpand(lerchphi(z, s, S.Half), 2**(s - 1)*(polylog(s, sqrt(z))/sqrt(z) - polylog(s, polar_lift(-1)*sqrt(z))/sqrt(z))) assert myexpand(lerchphi(z, s, 2), -1/z + polylog(s, z)/z**2) assert myexpand(lerchphi(z, s, Rational(3, 2)), None) assert myexpand(lerchphi(z, s, Rational(7, 3)), None) assert myexpand(lerchphi(z, s, Rational(-1, 3)), None) assert myexpand(lerchphi(z, s, Rational(-5, 2)), None) # hurwitz zeta reduction assert myexpand(lerchphi(-1, s, a), 2**(-s)*zeta(s, a/2) - 2**(-s)*zeta(s, (a + 1)/2)) assert myexpand(lerchphi(I, s, a), None) assert myexpand(lerchphi(-I, s, a), None) assert myexpand(lerchphi(exp(I*pi*Rational(2, 5)), s, a), None) def test_stieltjes(): assert isinstance(stieltjes(x), stieltjes) assert isinstance(stieltjes(x, a), stieltjes) # Zero'th constant EulerGamma assert stieltjes(0) == S.EulerGamma assert stieltjes(0, 1) == S.EulerGamma # Not defined assert stieltjes(nan) is nan assert stieltjes(0, nan) is nan assert stieltjes(-1) is S.ComplexInfinity assert stieltjes(1.5) is S.ComplexInfinity assert stieltjes(z, 0) is S.ComplexInfinity assert stieltjes(z, -1) is S.ComplexInfinity def test_stieltjes_evalf(): assert abs(stieltjes(0).evalf() - 0.577215664) < 1E-9 assert abs(stieltjes(0, 0.5).evalf() - 1.963510026) < 1E-9 assert abs(stieltjes(1, 2).evalf() + 0.072815845 ) < 1E-9 def test_issue_10475(): a = Symbol('a', extended_real=True) b = Symbol('b', extended_positive=True) s = Symbol('s', zero=False) assert zeta(2 + I).is_finite assert zeta(1).is_finite is False assert zeta(x).is_finite is None assert zeta(x + I).is_finite is None assert zeta(a).is_finite is None assert zeta(b).is_finite is None assert zeta(-b).is_finite is True assert zeta(b**2 - 2*b + 1).is_finite is None assert zeta(a + I).is_finite is True assert zeta(b + 1).is_finite is True assert zeta(s + 1).is_finite is True def test_issue_14177(): n = Symbol('n', positive=True, integer=True) assert zeta(2*n) == (-1)**(n + 1)*2**(2*n - 1)*pi**(2*n)*bernoulli(2*n)/factorial(2*n) assert zeta(-n) == (-1)**(-n)*bernoulli(n + 1)/(n + 1) n = Symbol('n') assert zeta(2*n) == zeta(2*n) # As sign of z (= 2*n) is not determined
79fda134fd6e316a04cab746df9afa0b8f0dc33839c783086f40261c78d38494
from itertools import product from sympy import (jn, yn, symbols, Symbol, sin, cos, pi, S, jn_zeros, besselj, bessely, besseli, besselk, hankel1, hankel2, hn1, hn2, expand_func, sqrt, sinh, cosh, diff, series, gamma, hyper, I, O, oo, conjugate, uppergamma, exp, Integral, Sum, Rational) from sympy.functions.special.bessel import fn from sympy.functions.special.bessel import (airyai, airybi, airyaiprime, airybiprime, marcumq) from sympy.testing.randtest import (random_complex_number as randcplx, verify_numerically as tn, test_derivative_numerically as td, _randint) from sympy.testing.pytest import raises from sympy.abc import z, n, k, x randint = _randint() def test_bessel_rand(): for f in [besselj, bessely, besseli, besselk, hankel1, hankel2]: assert td(f(randcplx(), z), z) for f in [jn, yn, hn1, hn2]: assert td(f(randint(-10, 10), z), z) def test_bessel_twoinputs(): for f in [besselj, bessely, besseli, besselk, hankel1, hankel2, jn, yn]: raises(TypeError, lambda: f(1)) raises(TypeError, lambda: f(1, 2, 3)) def test_diff(): assert besselj(n, z).diff(z) == besselj(n - 1, z)/2 - besselj(n + 1, z)/2 assert bessely(n, z).diff(z) == bessely(n - 1, z)/2 - bessely(n + 1, z)/2 assert besseli(n, z).diff(z) == besseli(n - 1, z)/2 + besseli(n + 1, z)/2 assert besselk(n, z).diff(z) == -besselk(n - 1, z)/2 - besselk(n + 1, z)/2 assert hankel1(n, z).diff(z) == hankel1(n - 1, z)/2 - hankel1(n + 1, z)/2 assert hankel2(n, z).diff(z) == hankel2(n - 1, z)/2 - hankel2(n + 1, z)/2 def test_rewrite(): from sympy import polar_lift, exp, I assert besselj(n, z).rewrite(jn) == sqrt(2*z/pi)*jn(n - S.Half, z) assert bessely(n, z).rewrite(yn) == sqrt(2*z/pi)*yn(n - S.Half, z) assert besseli(n, z).rewrite(besselj) == \ exp(-I*n*pi/2)*besselj(n, polar_lift(I)*z) assert besselj(n, z).rewrite(besseli) == \ exp(I*n*pi/2)*besseli(n, polar_lift(-I)*z) nu = randcplx() assert tn(besselj(nu, z), besselj(nu, z).rewrite(besseli), z) assert tn(besselj(nu, z), besselj(nu, z).rewrite(bessely), z) assert tn(besseli(nu, z), besseli(nu, z).rewrite(besselj), z) assert tn(besseli(nu, z), besseli(nu, z).rewrite(bessely), z) assert tn(bessely(nu, z), bessely(nu, z).rewrite(besselj), z) assert tn(bessely(nu, z), bessely(nu, z).rewrite(besseli), z) assert tn(besselk(nu, z), besselk(nu, z).rewrite(besselj), z) assert tn(besselk(nu, z), besselk(nu, z).rewrite(besseli), z) assert tn(besselk(nu, z), besselk(nu, z).rewrite(bessely), z) # check that a rewrite was triggered, when the order is set to a generic # symbol 'nu' assert yn(nu, z) != yn(nu, z).rewrite(jn) assert hn1(nu, z) != hn1(nu, z).rewrite(jn) assert hn2(nu, z) != hn2(nu, z).rewrite(jn) assert jn(nu, z) != jn(nu, z).rewrite(yn) assert hn1(nu, z) != hn1(nu, z).rewrite(yn) assert hn2(nu, z) != hn2(nu, z).rewrite(yn) # rewriting spherical bessel functions (SBFs) w.r.t. besselj, bessely is # not allowed if a generic symbol 'nu' is used as the order of the SBFs # to avoid inconsistencies (the order of bessel[jy] is allowed to be # complex-valued, whereas SBFs are defined only for integer orders) order = nu for f in (besselj, bessely): assert hn1(order, z) == hn1(order, z).rewrite(f) assert hn2(order, z) == hn2(order, z).rewrite(f) assert jn(order, z).rewrite(besselj) == sqrt(2)*sqrt(pi)*sqrt(1/z)*besselj(order + S.Half, z)/2 assert jn(order, z).rewrite(bessely) == (-1)**nu*sqrt(2)*sqrt(pi)*sqrt(1/z)*bessely(-order - S.Half, z)/2 # for integral orders rewriting SBFs w.r.t bessel[jy] is allowed N = Symbol('n', integer=True) ri = randint(-11, 10) for order in (ri, N): for f in (besselj, bessely): assert yn(order, z) != yn(order, z).rewrite(f) assert jn(order, z) != jn(order, z).rewrite(f) assert hn1(order, z) != hn1(order, z).rewrite(f) assert hn2(order, z) != hn2(order, z).rewrite(f) for func, refunc in product((yn, jn, hn1, hn2), (jn, yn, besselj, bessely)): assert tn(func(ri, z), func(ri, z).rewrite(refunc), z) def test_expand(): from sympy import besselsimp, Symbol, exp, exp_polar, I assert expand_func(besselj(S.Half, z).rewrite(jn)) == \ sqrt(2)*sin(z)/(sqrt(pi)*sqrt(z)) assert expand_func(bessely(S.Half, z).rewrite(yn)) == \ -sqrt(2)*cos(z)/(sqrt(pi)*sqrt(z)) # XXX: teach sin/cos to work around arguments like # x*exp_polar(I*pi*n/2). Then change besselsimp -> expand_func assert besselsimp(besselj(S.Half, z)) == sqrt(2)*sin(z)/(sqrt(pi)*sqrt(z)) assert besselsimp(besselj(Rational(-1, 2), z)) == sqrt(2)*cos(z)/(sqrt(pi)*sqrt(z)) assert besselsimp(besselj(Rational(5, 2), z)) == \ -sqrt(2)*(z**2*sin(z) + 3*z*cos(z) - 3*sin(z))/(sqrt(pi)*z**Rational(5, 2)) assert besselsimp(besselj(Rational(-5, 2), z)) == \ -sqrt(2)*(z**2*cos(z) - 3*z*sin(z) - 3*cos(z))/(sqrt(pi)*z**Rational(5, 2)) assert besselsimp(bessely(S.Half, z)) == \ -(sqrt(2)*cos(z))/(sqrt(pi)*sqrt(z)) assert besselsimp(bessely(Rational(-1, 2), z)) == sqrt(2)*sin(z)/(sqrt(pi)*sqrt(z)) assert besselsimp(bessely(Rational(5, 2), z)) == \ sqrt(2)*(z**2*cos(z) - 3*z*sin(z) - 3*cos(z))/(sqrt(pi)*z**Rational(5, 2)) assert besselsimp(bessely(Rational(-5, 2), z)) == \ -sqrt(2)*(z**2*sin(z) + 3*z*cos(z) - 3*sin(z))/(sqrt(pi)*z**Rational(5, 2)) assert besselsimp(besseli(S.Half, z)) == sqrt(2)*sinh(z)/(sqrt(pi)*sqrt(z)) assert besselsimp(besseli(Rational(-1, 2), z)) == \ sqrt(2)*cosh(z)/(sqrt(pi)*sqrt(z)) assert besselsimp(besseli(Rational(5, 2), z)) == \ sqrt(2)*(z**2*sinh(z) - 3*z*cosh(z) + 3*sinh(z))/(sqrt(pi)*z**Rational(5, 2)) assert besselsimp(besseli(Rational(-5, 2), z)) == \ sqrt(2)*(z**2*cosh(z) - 3*z*sinh(z) + 3*cosh(z))/(sqrt(pi)*z**Rational(5, 2)) assert besselsimp(besselk(S.Half, z)) == \ besselsimp(besselk(Rational(-1, 2), z)) == sqrt(pi)*exp(-z)/(sqrt(2)*sqrt(z)) assert besselsimp(besselk(Rational(5, 2), z)) == \ besselsimp(besselk(Rational(-5, 2), z)) == \ sqrt(2)*sqrt(pi)*(z**2 + 3*z + 3)*exp(-z)/(2*z**Rational(5, 2)) def check(eq, ans): return tn(eq, ans) and eq == ans rn = randcplx(a=1, b=0, d=0, c=2) for besselx in [besselj, bessely, besseli, besselk]: ri = S(2*randint(-11, 10) + 1) / 2 # half integer in [-21/2, 21/2] assert tn(besselsimp(besselx(ri, z)), besselx(ri, z)) assert check(expand_func(besseli(rn, x)), besseli(rn - 2, x) - 2*(rn - 1)*besseli(rn - 1, x)/x) assert check(expand_func(besseli(-rn, x)), besseli(-rn + 2, x) + 2*(-rn + 1)*besseli(-rn + 1, x)/x) assert check(expand_func(besselj(rn, x)), -besselj(rn - 2, x) + 2*(rn - 1)*besselj(rn - 1, x)/x) assert check(expand_func(besselj(-rn, x)), -besselj(-rn + 2, x) + 2*(-rn + 1)*besselj(-rn + 1, x)/x) assert check(expand_func(besselk(rn, x)), besselk(rn - 2, x) + 2*(rn - 1)*besselk(rn - 1, x)/x) assert check(expand_func(besselk(-rn, x)), besselk(-rn + 2, x) - 2*(-rn + 1)*besselk(-rn + 1, x)/x) assert check(expand_func(bessely(rn, x)), -bessely(rn - 2, x) + 2*(rn - 1)*bessely(rn - 1, x)/x) assert check(expand_func(bessely(-rn, x)), -bessely(-rn + 2, x) + 2*(-rn + 1)*bessely(-rn + 1, x)/x) n = Symbol('n', integer=True, positive=True) assert expand_func(besseli(n + 2, z)) == \ besseli(n, z) + (-2*n - 2)*(-2*n*besseli(n, z)/z + besseli(n - 1, z))/z assert expand_func(besselj(n + 2, z)) == \ -besselj(n, z) + (2*n + 2)*(2*n*besselj(n, z)/z - besselj(n - 1, z))/z assert expand_func(besselk(n + 2, z)) == \ besselk(n, z) + (2*n + 2)*(2*n*besselk(n, z)/z + besselk(n - 1, z))/z assert expand_func(bessely(n + 2, z)) == \ -bessely(n, z) + (2*n + 2)*(2*n*bessely(n, z)/z - bessely(n - 1, z))/z assert expand_func(besseli(n + S.Half, z).rewrite(jn)) == \ (sqrt(2)*sqrt(z)*exp(-I*pi*(n + S.Half)/2) * exp_polar(I*pi/4)*jn(n, z*exp_polar(I*pi/2))/sqrt(pi)) assert expand_func(besselj(n + S.Half, z).rewrite(jn)) == \ sqrt(2)*sqrt(z)*jn(n, z)/sqrt(pi) r = Symbol('r', real=True) p = Symbol('p', positive=True) i = Symbol('i', integer=True) for besselx in [besselj, bessely, besseli, besselk]: assert besselx(i, p).is_extended_real is True assert besselx(i, x).is_extended_real is None assert besselx(x, z).is_extended_real is None for besselx in [besselj, besseli]: assert besselx(i, r).is_extended_real is True for besselx in [bessely, besselk]: assert besselx(i, r).is_extended_real is None def test_fn(): x, z = symbols("x z") assert fn(1, z) == 1/z**2 assert fn(2, z) == -1/z + 3/z**3 assert fn(3, z) == -6/z**2 + 15/z**4 assert fn(4, z) == 1/z - 45/z**3 + 105/z**5 def mjn(n, z): return expand_func(jn(n, z)) def myn(n, z): return expand_func(yn(n, z)) def test_jn(): z = symbols("z") assert jn(0, 0) == 1 assert jn(1, 0) == 0 assert jn(-1, 0) == S.ComplexInfinity assert jn(z, 0) == jn(z, 0, evaluate=False) assert jn(0, oo) == 0 assert jn(0, -oo) == 0 assert mjn(0, z) == sin(z)/z assert mjn(1, z) == sin(z)/z**2 - cos(z)/z assert mjn(2, z) == (3/z**3 - 1/z)*sin(z) - (3/z**2) * cos(z) assert mjn(3, z) == (15/z**4 - 6/z**2)*sin(z) + (1/z - 15/z**3)*cos(z) assert mjn(4, z) == (1/z + 105/z**5 - 45/z**3)*sin(z) + \ (-105/z**4 + 10/z**2)*cos(z) assert mjn(5, z) == (945/z**6 - 420/z**4 + 15/z**2)*sin(z) + \ (-1/z - 945/z**5 + 105/z**3)*cos(z) assert mjn(6, z) == (-1/z + 10395/z**7 - 4725/z**5 + 210/z**3)*sin(z) + \ (-10395/z**6 + 1260/z**4 - 21/z**2)*cos(z) assert expand_func(jn(n, z)) == jn(n, z) # SBFs not defined for complex-valued orders assert jn(2+3j, 5.2+0.3j).evalf() == jn(2+3j, 5.2+0.3j) assert eq([jn(2, 5.2+0.3j).evalf(10)], [0.09941975672 - 0.05452508024*I]) def test_yn(): z = symbols("z") assert myn(0, z) == -cos(z)/z assert myn(1, z) == -cos(z)/z**2 - sin(z)/z assert myn(2, z) == -((3/z**3 - 1/z)*cos(z) + (3/z**2)*sin(z)) assert expand_func(yn(n, z)) == yn(n, z) # SBFs not defined for complex-valued orders assert yn(2+3j, 5.2+0.3j).evalf() == yn(2+3j, 5.2+0.3j) assert eq([yn(2, 5.2+0.3j).evalf(10)], [0.185250342 + 0.01489557397*I]) def test_sympify_yn(): assert S(15) in myn(3, pi).atoms() assert myn(3, pi) == 15/pi**4 - 6/pi**2 def eq(a, b, tol=1e-6): for u, v in zip(a, b): if not (abs(u - v) < tol): return False return True def test_jn_zeros(): assert eq(jn_zeros(0, 4), [3.141592, 6.283185, 9.424777, 12.566370]) assert eq(jn_zeros(1, 4), [4.493409, 7.725251, 10.904121, 14.066193]) assert eq(jn_zeros(2, 4), [5.763459, 9.095011, 12.322940, 15.514603]) assert eq(jn_zeros(3, 4), [6.987932, 10.417118, 13.698023, 16.923621]) assert eq(jn_zeros(4, 4), [8.182561, 11.704907, 15.039664, 18.301255]) def test_bessel_eval(): from sympy import I, Symbol n, m, k = Symbol('n', integer=True), Symbol('m'), Symbol('k', integer=True, zero=False) for f in [besselj, besseli]: assert f(0, 0) is S.One assert f(2.1, 0) is S.Zero assert f(-3, 0) is S.Zero assert f(-10.2, 0) is S.ComplexInfinity assert f(1 + 3*I, 0) is S.Zero assert f(-3 + I, 0) is S.ComplexInfinity assert f(-2*I, 0) is S.NaN assert f(n, 0) != S.One and f(n, 0) != S.Zero assert f(m, 0) != S.One and f(m, 0) != S.Zero assert f(k, 0) is S.Zero assert bessely(0, 0) is S.NegativeInfinity assert besselk(0, 0) is S.Infinity for f in [bessely, besselk]: assert f(1 + I, 0) is S.ComplexInfinity assert f(I, 0) is S.NaN for f in [besselj, bessely]: assert f(m, S.Infinity) is S.Zero assert f(m, S.NegativeInfinity) is S.Zero for f in [besseli, besselk]: assert f(m, I*S.Infinity) is S.Zero assert f(m, I*S.NegativeInfinity) is S.Zero for f in [besseli, besselk]: assert f(-4, z) == f(4, z) assert f(-3, z) == f(3, z) assert f(-n, z) == f(n, z) assert f(-m, z) != f(m, z) for f in [besselj, bessely]: assert f(-4, z) == f(4, z) assert f(-3, z) == -f(3, z) assert f(-n, z) == (-1)**n*f(n, z) assert f(-m, z) != (-1)**m*f(m, z) for f in [besselj, besseli]: assert f(m, -z) == (-z)**m*z**(-m)*f(m, z) assert besseli(2, -z) == besseli(2, z) assert besseli(3, -z) == -besseli(3, z) assert besselj(0, -z) == besselj(0, z) assert besselj(1, -z) == -besselj(1, z) assert besseli(0, I*z) == besselj(0, z) assert besseli(1, I*z) == I*besselj(1, z) assert besselj(3, I*z) == -I*besseli(3, z) def test_bessel_nan(): # FIXME: could have these return NaN; for now just fix infinite recursion for f in [besselj, bessely, besseli, besselk, hankel1, hankel2, yn, jn]: assert f(1, S.NaN) == f(1, S.NaN, evaluate=False) def test_conjugate(): from sympy import conjugate, I, Symbol n = Symbol('n') z = Symbol('z', extended_real=False) x = Symbol('x', extended_real=True) y = Symbol('y', real=True, positive=True) t = Symbol('t', negative=True) for f in [besseli, besselj, besselk, bessely, hankel1, hankel2]: assert f(n, -1).conjugate() != f(conjugate(n), -1) assert f(n, x).conjugate() != f(conjugate(n), x) assert f(n, t).conjugate() != f(conjugate(n), t) rz = randcplx(b=0.5) for f in [besseli, besselj, besselk, bessely]: assert f(n, 1 + I).conjugate() == f(conjugate(n), 1 - I) assert f(n, 0).conjugate() == f(conjugate(n), 0) assert f(n, 1).conjugate() == f(conjugate(n), 1) assert f(n, z).conjugate() == f(conjugate(n), conjugate(z)) assert f(n, y).conjugate() == f(conjugate(n), y) assert tn(f(n, rz).conjugate(), f(conjugate(n), conjugate(rz))) assert hankel1(n, 1 + I).conjugate() == hankel2(conjugate(n), 1 - I) assert hankel1(n, 0).conjugate() == hankel2(conjugate(n), 0) assert hankel1(n, 1).conjugate() == hankel2(conjugate(n), 1) assert hankel1(n, y).conjugate() == hankel2(conjugate(n), y) assert hankel1(n, z).conjugate() == hankel2(conjugate(n), conjugate(z)) assert tn(hankel1(n, rz).conjugate(), hankel2(conjugate(n), conjugate(rz))) assert hankel2(n, 1 + I).conjugate() == hankel1(conjugate(n), 1 - I) assert hankel2(n, 0).conjugate() == hankel1(conjugate(n), 0) assert hankel2(n, 1).conjugate() == hankel1(conjugate(n), 1) assert hankel2(n, y).conjugate() == hankel1(conjugate(n), y) assert hankel2(n, z).conjugate() == hankel1(conjugate(n), conjugate(z)) assert tn(hankel2(n, rz).conjugate(), hankel1(conjugate(n), conjugate(rz))) def test_branching(): from sympy import exp_polar, polar_lift, Symbol, I, exp assert besselj(polar_lift(k), x) == besselj(k, x) assert besseli(polar_lift(k), x) == besseli(k, x) n = Symbol('n', integer=True) assert besselj(n, exp_polar(2*pi*I)*x) == besselj(n, x) assert besselj(n, polar_lift(x)) == besselj(n, x) assert besseli(n, exp_polar(2*pi*I)*x) == besseli(n, x) assert besseli(n, polar_lift(x)) == besseli(n, x) def tn(func, s): from random import uniform c = uniform(1, 5) expr = func(s, c*exp_polar(I*pi)) - func(s, c*exp_polar(-I*pi)) eps = 1e-15 expr2 = func(s + eps, -c + eps*I) - func(s + eps, -c - eps*I) return abs(expr.n() - expr2.n()).n() < 1e-10 nu = Symbol('nu') assert besselj(nu, exp_polar(2*pi*I)*x) == exp(2*pi*I*nu)*besselj(nu, x) assert besseli(nu, exp_polar(2*pi*I)*x) == exp(2*pi*I*nu)*besseli(nu, x) assert tn(besselj, 2) assert tn(besselj, pi) assert tn(besselj, I) assert tn(besseli, 2) assert tn(besseli, pi) assert tn(besseli, I) def test_airy_base(): z = Symbol('z') x = Symbol('x', real=True) y = Symbol('y', real=True) assert conjugate(airyai(z)) == airyai(conjugate(z)) assert airyai(x).is_extended_real assert airyai(x+I*y).as_real_imag() == ( airyai(x - I*y)/2 + airyai(x + I*y)/2, I*(airyai(x - I*y) - airyai(x + I*y))/2) def test_airyai(): z = Symbol('z', real=False) t = Symbol('t', negative=True) p = Symbol('p', positive=True) assert isinstance(airyai(z), airyai) assert airyai(0) == 3**Rational(1, 3)/(3*gamma(Rational(2, 3))) assert airyai(oo) == 0 assert airyai(-oo) == 0 assert diff(airyai(z), z) == airyaiprime(z) assert series(airyai(z), z, 0, 3) == ( 3**Rational(5, 6)*gamma(Rational(1, 3))/(6*pi) - 3**Rational(1, 6)*z*gamma(Rational(2, 3))/(2*pi) + O(z**3)) assert airyai(z).rewrite(hyper) == ( -3**Rational(2, 3)*z*hyper((), (Rational(4, 3),), z**3/9)/(3*gamma(Rational(1, 3))) + 3**Rational(1, 3)*hyper((), (Rational(2, 3),), z**3/9)/(3*gamma(Rational(2, 3)))) assert isinstance(airyai(z).rewrite(besselj), airyai) assert airyai(t).rewrite(besselj) == ( sqrt(-t)*(besselj(Rational(-1, 3), 2*(-t)**Rational(3, 2)/3) + besselj(Rational(1, 3), 2*(-t)**Rational(3, 2)/3))/3) assert airyai(z).rewrite(besseli) == ( -z*besseli(Rational(1, 3), 2*z**Rational(3, 2)/3)/(3*(z**Rational(3, 2))**Rational(1, 3)) + (z**Rational(3, 2))**Rational(1, 3)*besseli(Rational(-1, 3), 2*z**Rational(3, 2)/3)/3) assert airyai(p).rewrite(besseli) == ( sqrt(p)*(besseli(Rational(-1, 3), 2*p**Rational(3, 2)/3) - besseli(Rational(1, 3), 2*p**Rational(3, 2)/3))/3) assert expand_func(airyai(2*(3*z**5)**Rational(1, 3))) == ( -sqrt(3)*(-1 + (z**5)**Rational(1, 3)/z**Rational(5, 3))*airybi(2*3**Rational(1, 3)*z**Rational(5, 3))/6 + (1 + (z**5)**Rational(1, 3)/z**Rational(5, 3))*airyai(2*3**Rational(1, 3)*z**Rational(5, 3))/2) def test_airybi(): z = Symbol('z', real=False) t = Symbol('t', negative=True) p = Symbol('p', positive=True) assert isinstance(airybi(z), airybi) assert airybi(0) == 3**Rational(5, 6)/(3*gamma(Rational(2, 3))) assert airybi(oo) is oo assert airybi(-oo) == 0 assert diff(airybi(z), z) == airybiprime(z) assert series(airybi(z), z, 0, 3) == ( 3**Rational(1, 3)*gamma(Rational(1, 3))/(2*pi) + 3**Rational(2, 3)*z*gamma(Rational(2, 3))/(2*pi) + O(z**3)) assert airybi(z).rewrite(hyper) == ( 3**Rational(1, 6)*z*hyper((), (Rational(4, 3),), z**3/9)/gamma(Rational(1, 3)) + 3**Rational(5, 6)*hyper((), (Rational(2, 3),), z**3/9)/(3*gamma(Rational(2, 3)))) assert isinstance(airybi(z).rewrite(besselj), airybi) assert airyai(t).rewrite(besselj) == ( sqrt(-t)*(besselj(Rational(-1, 3), 2*(-t)**Rational(3, 2)/3) + besselj(Rational(1, 3), 2*(-t)**Rational(3, 2)/3))/3) assert airybi(z).rewrite(besseli) == ( sqrt(3)*(z*besseli(Rational(1, 3), 2*z**Rational(3, 2)/3)/(z**Rational(3, 2))**Rational(1, 3) + (z**Rational(3, 2))**Rational(1, 3)*besseli(Rational(-1, 3), 2*z**Rational(3, 2)/3))/3) assert airybi(p).rewrite(besseli) == ( sqrt(3)*sqrt(p)*(besseli(Rational(-1, 3), 2*p**Rational(3, 2)/3) + besseli(Rational(1, 3), 2*p**Rational(3, 2)/3))/3) assert expand_func(airybi(2*(3*z**5)**Rational(1, 3))) == ( sqrt(3)*(1 - (z**5)**Rational(1, 3)/z**Rational(5, 3))*airyai(2*3**Rational(1, 3)*z**Rational(5, 3))/2 + (1 + (z**5)**Rational(1, 3)/z**Rational(5, 3))*airybi(2*3**Rational(1, 3)*z**Rational(5, 3))/2) def test_airyaiprime(): z = Symbol('z', real=False) t = Symbol('t', negative=True) p = Symbol('p', positive=True) assert isinstance(airyaiprime(z), airyaiprime) assert airyaiprime(0) == -3**Rational(2, 3)/(3*gamma(Rational(1, 3))) assert airyaiprime(oo) == 0 assert diff(airyaiprime(z), z) == z*airyai(z) assert series(airyaiprime(z), z, 0, 3) == ( -3**Rational(2, 3)/(3*gamma(Rational(1, 3))) + 3**Rational(1, 3)*z**2/(6*gamma(Rational(2, 3))) + O(z**3)) assert airyaiprime(z).rewrite(hyper) == ( 3**Rational(1, 3)*z**2*hyper((), (Rational(5, 3),), z**3/9)/(6*gamma(Rational(2, 3))) - 3**Rational(2, 3)*hyper((), (Rational(1, 3),), z**3/9)/(3*gamma(Rational(1, 3)))) assert isinstance(airyaiprime(z).rewrite(besselj), airyaiprime) assert airyai(t).rewrite(besselj) == ( sqrt(-t)*(besselj(Rational(-1, 3), 2*(-t)**Rational(3, 2)/3) + besselj(Rational(1, 3), 2*(-t)**Rational(3, 2)/3))/3) assert airyaiprime(z).rewrite(besseli) == ( z**2*besseli(Rational(2, 3), 2*z**Rational(3, 2)/3)/(3*(z**Rational(3, 2))**Rational(2, 3)) - (z**Rational(3, 2))**Rational(2, 3)*besseli(Rational(-1, 3), 2*z**Rational(3, 2)/3)/3) assert airyaiprime(p).rewrite(besseli) == ( p*(-besseli(Rational(-2, 3), 2*p**Rational(3, 2)/3) + besseli(Rational(2, 3), 2*p**Rational(3, 2)/3))/3) assert expand_func(airyaiprime(2*(3*z**5)**Rational(1, 3))) == ( sqrt(3)*(z**Rational(5, 3)/(z**5)**Rational(1, 3) - 1)*airybiprime(2*3**Rational(1, 3)*z**Rational(5, 3))/6 + (z**Rational(5, 3)/(z**5)**Rational(1, 3) + 1)*airyaiprime(2*3**Rational(1, 3)*z**Rational(5, 3))/2) def test_airybiprime(): z = Symbol('z', real=False) t = Symbol('t', negative=True) p = Symbol('p', positive=True) assert isinstance(airybiprime(z), airybiprime) assert airybiprime(0) == 3**Rational(1, 6)/gamma(Rational(1, 3)) assert airybiprime(oo) is oo assert airybiprime(-oo) == 0 assert diff(airybiprime(z), z) == z*airybi(z) assert series(airybiprime(z), z, 0, 3) == ( 3**Rational(1, 6)/gamma(Rational(1, 3)) + 3**Rational(5, 6)*z**2/(6*gamma(Rational(2, 3))) + O(z**3)) assert airybiprime(z).rewrite(hyper) == ( 3**Rational(5, 6)*z**2*hyper((), (Rational(5, 3),), z**3/9)/(6*gamma(Rational(2, 3))) + 3**Rational(1, 6)*hyper((), (Rational(1, 3),), z**3/9)/gamma(Rational(1, 3))) assert isinstance(airybiprime(z).rewrite(besselj), airybiprime) assert airyai(t).rewrite(besselj) == ( sqrt(-t)*(besselj(Rational(-1, 3), 2*(-t)**Rational(3, 2)/3) + besselj(Rational(1, 3), 2*(-t)**Rational(3, 2)/3))/3) assert airybiprime(z).rewrite(besseli) == ( sqrt(3)*(z**2*besseli(Rational(2, 3), 2*z**Rational(3, 2)/3)/(z**Rational(3, 2))**Rational(2, 3) + (z**Rational(3, 2))**Rational(2, 3)*besseli(Rational(-2, 3), 2*z**Rational(3, 2)/3))/3) assert airybiprime(p).rewrite(besseli) == ( sqrt(3)*p*(besseli(Rational(-2, 3), 2*p**Rational(3, 2)/3) + besseli(Rational(2, 3), 2*p**Rational(3, 2)/3))/3) assert expand_func(airybiprime(2*(3*z**5)**Rational(1, 3))) == ( sqrt(3)*(z**Rational(5, 3)/(z**5)**Rational(1, 3) - 1)*airyaiprime(2*3**Rational(1, 3)*z**Rational(5, 3))/2 + (z**Rational(5, 3)/(z**5)**Rational(1, 3) + 1)*airybiprime(2*3**Rational(1, 3)*z**Rational(5, 3))/2) def test_marcumq(): m = Symbol('m') a = Symbol('a') b = Symbol('b') assert marcumq(0, 0, 0) == 0 assert marcumq(m, 0, b) == uppergamma(m, b**2/2)/gamma(m) assert marcumq(2, 0, 5) == 27*exp(Rational(-25, 2))/2 assert marcumq(0, a, 0) == 1 - exp(-a**2/2) assert marcumq(0, pi, 0) == 1 - exp(-pi**2/2) assert marcumq(1, a, a) == S.Half + exp(-a**2)*besseli(0, a**2)/2 assert marcumq(2, a, a) == S.Half + exp(-a**2)*besseli(0, a**2)/2 + exp(-a**2)*besseli(1, a**2) assert diff(marcumq(1, a, 3), a) == a*(-marcumq(1, a, 3) + marcumq(2, a, 3)) assert diff(marcumq(2, 3, b), b) == -b**2*exp(-b**2/2 - Rational(9, 2))*besseli(1, 3*b)/3 x = Symbol('x') assert marcumq(2, 3, 4).rewrite(Integral, x=x) == \ Integral(x**2*exp(-x**2/2 - Rational(9, 2))*besseli(1, 3*x), (x, 4, oo))/3 assert eq([marcumq(5, -2, 3).rewrite(Integral).evalf(10)], [0.7905769565]) k = Symbol('k') assert marcumq(-3, -5, -7).rewrite(Sum, k=k) == \ exp(-37)*Sum((Rational(5, 7))**k*besseli(k, 35), (k, 4, oo)) assert eq([marcumq(1, 3, 1).rewrite(Sum).evalf(10)], [0.9891705502]) assert marcumq(1, a, a, evaluate=False).rewrite(besseli) == S.Half + exp(-a**2)*besseli(0, a**2)/2 assert marcumq(2, a, a, evaluate=False).rewrite(besseli) == S.Half + exp(-a**2)*besseli(0, a**2)/2 + \ exp(-a**2)*besseli(1, a**2) assert marcumq(3, a, a).rewrite(besseli) == (besseli(1, a**2) + besseli(2, a**2))*exp(-a**2) + \ S.Half + exp(-a**2)*besseli(0, a**2)/2 assert marcumq(5, 8, 8).rewrite(besseli) == exp(-64)*besseli(0, 64)/2 + \ (besseli(4, 64) + besseli(3, 64) + besseli(2, 64) + besseli(1, 64))*exp(-64) + S.Half assert marcumq(m, a, a).rewrite(besseli) == marcumq(m, a, a) x = Symbol('x', integer=True) assert marcumq(x, a, a).rewrite(besseli) == marcumq(x, a, a)
d7dfe81f86cd312707b2292bb3a0084696eb82a985935a1fc87937539e234264
from sympy import ( nan, pi, symbols, DiracDelta, Symbol, diff, Piecewise, I, Eq, Derivative, oo, SingularityFunction, Heaviside, Float ) from sympy.core.expr import unchanged from sympy.core.function import ArgumentIndexError from sympy.testing.pytest import raises x, y, a, n = symbols('x y a n') def test_fdiff(): assert SingularityFunction(x, 4, 5).fdiff() == 5*SingularityFunction(x, 4, 4) assert SingularityFunction(x, 4, -1).fdiff() == SingularityFunction(x, 4, -2) assert SingularityFunction(x, 4, 0).fdiff() == SingularityFunction(x, 4, -1) assert SingularityFunction(y, 6, 2).diff(y) == 2*SingularityFunction(y, 6, 1) assert SingularityFunction(y, -4, -1).diff(y) == SingularityFunction(y, -4, -2) assert SingularityFunction(y, 4, 0).diff(y) == SingularityFunction(y, 4, -1) assert SingularityFunction(y, 4, 0).diff(y, 2) == SingularityFunction(y, 4, -2) n = Symbol('n', positive=True) assert SingularityFunction(x, a, n).fdiff() == n*SingularityFunction(x, a, n - 1) assert SingularityFunction(y, a, n).diff(y) == n*SingularityFunction(y, a, n - 1) expr_in = 4*SingularityFunction(x, a, n) + 3*SingularityFunction(x, a, -1) + -10*SingularityFunction(x, a, 0) expr_out = n*4*SingularityFunction(x, a, n - 1) + 3*SingularityFunction(x, a, -2) - 10*SingularityFunction(x, a, -1) assert diff(expr_in, x) == expr_out assert SingularityFunction(x, -10, 5).diff(evaluate=False) == ( Derivative(SingularityFunction(x, -10, 5), x)) raises(ArgumentIndexError, lambda: SingularityFunction(x, 4, 5).fdiff(2)) def test_eval(): assert SingularityFunction(x, a, n).func == SingularityFunction assert unchanged(SingularityFunction, x, 5, n) assert SingularityFunction(5, 3, 2) == 4 assert SingularityFunction(3, 5, 1) == 0 assert SingularityFunction(3, 3, 0) == 1 assert SingularityFunction(4, 4, -1) is oo assert SingularityFunction(4, 2, -1) == 0 assert SingularityFunction(4, 7, -1) == 0 assert SingularityFunction(5, 6, -2) == 0 assert SingularityFunction(4, 2, -2) == 0 assert SingularityFunction(4, 4, -2) is oo assert (SingularityFunction(6.1, 4, 5)).evalf(5) == Float('40.841', '5') assert SingularityFunction(6.1, pi, 2) == (-pi + 6.1)**2 assert SingularityFunction(x, a, nan) is nan assert SingularityFunction(x, nan, 1) is nan assert SingularityFunction(nan, a, n) is nan raises(ValueError, lambda: SingularityFunction(x, a, I)) raises(ValueError, lambda: SingularityFunction(2*I, I, n)) raises(ValueError, lambda: SingularityFunction(x, a, -3)) def test_rewrite(): assert SingularityFunction(x, 4, 5).rewrite(Piecewise) == ( Piecewise(((x - 4)**5, x - 4 > 0), (0, True))) assert SingularityFunction(x, -10, 0).rewrite(Piecewise) == ( Piecewise((1, x + 10 > 0), (0, True))) assert SingularityFunction(x, 2, -1).rewrite(Piecewise) == ( Piecewise((oo, Eq(x - 2, 0)), (0, True))) assert SingularityFunction(x, 0, -2).rewrite(Piecewise) == ( Piecewise((oo, Eq(x, 0)), (0, True))) n = Symbol('n', nonnegative=True) assert SingularityFunction(x, a, n).rewrite(Piecewise) == ( Piecewise(((x - a)**n, x - a > 0), (0, True))) expr_in = SingularityFunction(x, 4, 5) + SingularityFunction(x, -3, -1) - SingularityFunction(x, 0, -2) expr_out = (x - 4)**5*Heaviside(x - 4) + DiracDelta(x + 3) - DiracDelta(x, 1) assert expr_in.rewrite(Heaviside) == expr_out assert expr_in.rewrite(DiracDelta) == expr_out assert expr_in.rewrite('HeavisideDiracDelta') == expr_out expr_in = SingularityFunction(x, a, n) + SingularityFunction(x, a, -1) - SingularityFunction(x, a, -2) expr_out = (x - a)**n*Heaviside(x - a) + DiracDelta(x - a) + DiracDelta(a - x, 1) assert expr_in.rewrite(Heaviside) == expr_out assert expr_in.rewrite(DiracDelta) == expr_out assert expr_in.rewrite('HeavisideDiracDelta') == expr_out
249fd9e5260d59de9f9b26d60e11ac9f621441c7d16c00cc09a8b61c331825ff
from sympy import (S, Symbol, pi, I, oo, zoo, sin, sqrt, tan, gamma, atanh, hyper, meijerg, O, Dummy, Integral, Rational) from sympy.functions.special.elliptic_integrals import (elliptic_k as K, elliptic_f as F, elliptic_e as E, elliptic_pi as P) from sympy.testing.randtest import (test_derivative_numerically as td, random_complex_number as randcplx, verify_numerically as tn) from sympy.abc import z, m, n i = Symbol('i', integer=True) j = Symbol('k', integer=True, positive=True) t = Dummy('t') def test_K(): assert K(0) == pi/2 assert K(S.Half) == 8*pi**Rational(3, 2)/gamma(Rational(-1, 4))**2 assert K(1) is zoo assert K(-1) == gamma(Rational(1, 4))**2/(4*sqrt(2*pi)) assert K(oo) == 0 assert K(-oo) == 0 assert K(I*oo) == 0 assert K(-I*oo) == 0 assert K(zoo) == 0 assert K(z).diff(z) == (E(z) - (1 - z)*K(z))/(2*z*(1 - z)) assert td(K(z), z) zi = Symbol('z', real=False) assert K(zi).conjugate() == K(zi.conjugate()) zr = Symbol('z', real=True, negative=True) assert K(zr).conjugate() == K(zr) assert K(z).rewrite(hyper) == \ (pi/2)*hyper((S.Half, S.Half), (S.One,), z) assert tn(K(z), (pi/2)*hyper((S.Half, S.Half), (S.One,), z)) assert K(z).rewrite(meijerg) == \ meijerg(((S.Half, S.Half), []), ((S.Zero,), (S.Zero,)), -z)/2 assert tn(K(z), meijerg(((S.Half, S.Half), []), ((S.Zero,), (S.Zero,)), -z)/2) assert K(z).series(z) == pi/2 + pi*z/8 + 9*pi*z**2/128 + \ 25*pi*z**3/512 + 1225*pi*z**4/32768 + 3969*pi*z**5/131072 + O(z**6) assert K(m).rewrite(Integral).dummy_eq( Integral(1/sqrt(1 - m*sin(t)**2), (t, 0, pi/2))) def test_F(): assert F(z, 0) == z assert F(0, m) == 0 assert F(pi*i/2, m) == i*K(m) assert F(z, oo) == 0 assert F(z, -oo) == 0 assert F(-z, m) == -F(z, m) assert F(z, m).diff(z) == 1/sqrt(1 - m*sin(z)**2) assert F(z, m).diff(m) == E(z, m)/(2*m*(1 - m)) - F(z, m)/(2*m) - \ sin(2*z)/(4*(1 - m)*sqrt(1 - m*sin(z)**2)) r = randcplx() assert td(F(z, r), z) assert td(F(r, m), m) mi = Symbol('m', real=False) assert F(z, mi).conjugate() == F(z.conjugate(), mi.conjugate()) mr = Symbol('m', real=True, negative=True) assert F(z, mr).conjugate() == F(z.conjugate(), mr) assert F(z, m).series(z) == \ z + z**5*(3*m**2/40 - m/30) + m*z**3/6 + O(z**6) assert F(z, m).rewrite(Integral).dummy_eq( Integral(1/sqrt(1 - m*sin(t)**2), (t, 0, z))) def test_E(): assert E(z, 0) == z assert E(0, m) == 0 assert E(i*pi/2, m) == i*E(m) assert E(z, oo) is zoo assert E(z, -oo) is zoo assert E(0) == pi/2 assert E(1) == 1 assert E(oo) == I*oo assert E(-oo) is oo assert E(zoo) is zoo assert E(-z, m) == -E(z, m) assert E(z, m).diff(z) == sqrt(1 - m*sin(z)**2) assert E(z, m).diff(m) == (E(z, m) - F(z, m))/(2*m) assert E(z).diff(z) == (E(z) - K(z))/(2*z) r = randcplx() assert td(E(r, m), m) assert td(E(z, r), z) assert td(E(z), z) mi = Symbol('m', real=False) assert E(z, mi).conjugate() == E(z.conjugate(), mi.conjugate()) assert E(mi).conjugate() == E(mi.conjugate()) mr = Symbol('m', real=True, negative=True) assert E(z, mr).conjugate() == E(z.conjugate(), mr) assert E(mr).conjugate() == E(mr) assert E(z).rewrite(hyper) == (pi/2)*hyper((Rational(-1, 2), S.Half), (S.One,), z) assert tn(E(z), (pi/2)*hyper((Rational(-1, 2), S.Half), (S.One,), z)) assert E(z).rewrite(meijerg) == \ -meijerg(((S.Half, Rational(3, 2)), []), ((S.Zero,), (S.Zero,)), -z)/4 assert tn(E(z), -meijerg(((S.Half, Rational(3, 2)), []), ((S.Zero,), (S.Zero,)), -z)/4) assert E(z, m).series(z) == \ z + z**5*(-m**2/40 + m/30) - m*z**3/6 + O(z**6) assert E(z).series(z) == pi/2 - pi*z/8 - 3*pi*z**2/128 - \ 5*pi*z**3/512 - 175*pi*z**4/32768 - 441*pi*z**5/131072 + O(z**6) assert E(z, m).rewrite(Integral).dummy_eq( Integral(sqrt(1 - m*sin(t)**2), (t, 0, z))) assert E(m).rewrite(Integral).dummy_eq( Integral(sqrt(1 - m*sin(t)**2), (t, 0, pi/2))) def test_P(): assert P(0, z, m) == F(z, m) assert P(1, z, m) == F(z, m) + \ (sqrt(1 - m*sin(z)**2)*tan(z) - E(z, m))/(1 - m) assert P(n, i*pi/2, m) == i*P(n, m) assert P(n, z, 0) == atanh(sqrt(n - 1)*tan(z))/sqrt(n - 1) assert P(n, z, n) == F(z, n) - P(1, z, n) + tan(z)/sqrt(1 - n*sin(z)**2) assert P(oo, z, m) == 0 assert P(-oo, z, m) == 0 assert P(n, z, oo) == 0 assert P(n, z, -oo) == 0 assert P(0, m) == K(m) assert P(1, m) is zoo assert P(n, 0) == pi/(2*sqrt(1 - n)) assert P(2, 1) is -oo assert P(-1, 1) is oo assert P(n, n) == E(n)/(1 - n) assert P(n, -z, m) == -P(n, z, m) ni, mi = Symbol('n', real=False), Symbol('m', real=False) assert P(ni, z, mi).conjugate() == \ P(ni.conjugate(), z.conjugate(), mi.conjugate()) nr, mr = Symbol('n', real=True, negative=True), \ Symbol('m', real=True, negative=True) assert P(nr, z, mr).conjugate() == P(nr, z.conjugate(), mr) assert P(n, m).conjugate() == P(n.conjugate(), m.conjugate()) assert P(n, z, m).diff(n) == (E(z, m) + (m - n)*F(z, m)/n + (n**2 - m)*P(n, z, m)/n - n*sqrt(1 - m*sin(z)**2)*sin(2*z)/(2*(1 - n*sin(z)**2)))/(2*(m - n)*(n - 1)) assert P(n, z, m).diff(z) == 1/(sqrt(1 - m*sin(z)**2)*(1 - n*sin(z)**2)) assert P(n, z, m).diff(m) == (E(z, m)/(m - 1) + P(n, z, m) - m*sin(2*z)/(2*(m - 1)*sqrt(1 - m*sin(z)**2)))/(2*(n - m)) assert P(n, m).diff(n) == (E(m) + (m - n)*K(m)/n + (n**2 - m)*P(n, m)/n)/(2*(m - n)*(n - 1)) assert P(n, m).diff(m) == (E(m)/(m - 1) + P(n, m))/(2*(n - m)) rx, ry = randcplx(), randcplx() assert td(P(n, rx, ry), n) assert td(P(rx, z, ry), z) assert td(P(rx, ry, m), m) assert P(n, z, m).series(z) == z + z**3*(m/6 + n/3) + \ z**5*(3*m**2/40 + m*n/10 - m/30 + n**2/5 - n/15) + O(z**6) assert P(n, z, m).rewrite(Integral).dummy_eq( Integral(1/((1 - n*sin(t)**2)*sqrt(1 - m*sin(t)**2)), (t, 0, z))) assert P(n, m).rewrite(Integral).dummy_eq( Integral(1/((1 - n*sin(t)**2)*sqrt(1 - m*sin(t)**2)), (t, 0, pi/2)))
8fdd1cf22fefb6392223c461a58ae39fbff3b19da45d851d07bb8c10fd815752
from sympy import ( Symbol, Dummy, diff, Derivative, Rational, roots, S, sqrt, hyper, cos, gamma, conjugate, factorial, pi, oo, zoo, binomial, RisingFactorial, legendre, assoc_legendre, chebyshevu, chebyshevt, chebyshevt_root, chebyshevu_root, laguerre, assoc_laguerre, laguerre_poly, hermite, gegenbauer, jacobi, jacobi_normalized, Sum, floor, exp) from sympy.core.expr import unchanged from sympy.core.function import ArgumentIndexError from sympy.testing.pytest import raises x = Symbol('x') def test_jacobi(): n = Symbol("n") a = Symbol("a") b = Symbol("b") assert jacobi(0, a, b, x) == 1 assert jacobi(1, a, b, x) == a/2 - b/2 + x*(a/2 + b/2 + 1) assert jacobi(n, a, a, x) == RisingFactorial( a + 1, n)*gegenbauer(n, a + S.Half, x)/RisingFactorial(2*a + 1, n) assert jacobi(n, a, -a, x) == ((-1)**a*(-x + 1)**(-a/2)*(x + 1)**(a/2)*assoc_legendre(n, a, x)* factorial(-a + n)*gamma(a + n + 1)/(factorial(a + n)*gamma(n + 1))) assert jacobi(n, -b, b, x) == ((-x + 1)**(b/2)*(x + 1)**(-b/2)*assoc_legendre(n, b, x)* gamma(-b + n + 1)/gamma(n + 1)) assert jacobi(n, 0, 0, x) == legendre(n, x) assert jacobi(n, S.Half, S.Half, x) == RisingFactorial( Rational(3, 2), n)*chebyshevu(n, x)/factorial(n + 1) assert jacobi(n, Rational(-1, 2), Rational(-1, 2), x) == RisingFactorial( S.Half, n)*chebyshevt(n, x)/factorial(n) X = jacobi(n, a, b, x) assert isinstance(X, jacobi) assert jacobi(n, a, b, -x) == (-1)**n*jacobi(n, b, a, x) assert jacobi(n, a, b, 0) == 2**(-n)*gamma(a + n + 1)*hyper( (-b - n, -n), (a + 1,), -1)/(factorial(n)*gamma(a + 1)) assert jacobi(n, a, b, 1) == RisingFactorial(a + 1, n)/factorial(n) m = Symbol("m", positive=True) assert jacobi(m, a, b, oo) == oo*RisingFactorial(a + b + m + 1, m) assert unchanged(jacobi, n, a, b, oo) assert conjugate(jacobi(m, a, b, x)) == \ jacobi(m, conjugate(a), conjugate(b), conjugate(x)) _k = Dummy('k') assert diff(jacobi(n, a, b, x), n) == Derivative(jacobi(n, a, b, x), n) assert diff(jacobi(n, a, b, x), a).dummy_eq(Sum((jacobi(n, a, b, x) + (2*_k + a + b + 1)*RisingFactorial(_k + b + 1, -_k + n)*jacobi(_k, a, b, x)/((-_k + n)*RisingFactorial(_k + a + b + 1, -_k + n)))/(_k + a + b + n + 1), (_k, 0, n - 1))) assert diff(jacobi(n, a, b, x), b).dummy_eq(Sum(((-1)**(-_k + n)*(2*_k + a + b + 1)*RisingFactorial(_k + a + 1, -_k + n)*jacobi(_k, a, b, x)/ ((-_k + n)*RisingFactorial(_k + a + b + 1, -_k + n)) + jacobi(n, a, b, x))/(_k + a + b + n + 1), (_k, 0, n - 1))) assert diff(jacobi(n, a, b, x), x) == \ (a/2 + b/2 + n/2 + S.Half)*jacobi(n - 1, a + 1, b + 1, x) assert jacobi_normalized(n, a, b, x) == \ (jacobi(n, a, b, x)/sqrt(2**(a + b + 1)*gamma(a + n + 1)*gamma(b + n + 1) /((a + b + 2*n + 1)*factorial(n)*gamma(a + b + n + 1)))) raises(ValueError, lambda: jacobi(-2.1, a, b, x)) raises(ValueError, lambda: jacobi(Dummy(positive=True, integer=True), 1, 2, oo)) assert jacobi(n, a, b, x).rewrite("polynomial").dummy_eq(Sum((S.Half - x/2) **_k*RisingFactorial(-n, _k)*RisingFactorial(_k + a + 1, -_k + n)* RisingFactorial(a + b + n + 1, _k)/factorial(_k), (_k, 0, n))/factorial(n)) raises(ArgumentIndexError, lambda: jacobi(n, a, b, x).fdiff(5)) def test_gegenbauer(): n = Symbol("n") a = Symbol("a") assert gegenbauer(0, a, x) == 1 assert gegenbauer(1, a, x) == 2*a*x assert gegenbauer(2, a, x) == -a + x**2*(2*a**2 + 2*a) assert gegenbauer(3, a, x) == \ x**3*(4*a**3/3 + 4*a**2 + a*Rational(8, 3)) + x*(-2*a**2 - 2*a) assert gegenbauer(-1, a, x) == 0 assert gegenbauer(n, S.Half, x) == legendre(n, x) assert gegenbauer(n, 1, x) == chebyshevu(n, x) assert gegenbauer(n, -1, x) == 0 X = gegenbauer(n, a, x) assert isinstance(X, gegenbauer) assert gegenbauer(n, a, -x) == (-1)**n*gegenbauer(n, a, x) assert gegenbauer(n, a, 0) == 2**n*sqrt(pi) * \ gamma(a + n/2)/(gamma(a)*gamma(-n/2 + S.Half)*gamma(n + 1)) assert gegenbauer(n, a, 1) == gamma(2*a + n)/(gamma(2*a)*gamma(n + 1)) assert gegenbauer(n, Rational(3, 4), -1) is zoo assert gegenbauer(n, Rational(1, 4), -1) == (sqrt(2)*cos(pi*(n + S.One/4))* gamma(n + S.Half)/(sqrt(pi)*gamma(n + 1))) m = Symbol("m", positive=True) assert gegenbauer(m, a, oo) == oo*RisingFactorial(a, m) assert unchanged(gegenbauer, n, a, oo) assert conjugate(gegenbauer(n, a, x)) == gegenbauer(n, conjugate(a), conjugate(x)) _k = Dummy('k') assert diff(gegenbauer(n, a, x), n) == Derivative(gegenbauer(n, a, x), n) assert diff(gegenbauer(n, a, x), a).dummy_eq(Sum((2*(-1)**(-_k + n) + 2)* (_k + a)*gegenbauer(_k, a, x)/((-_k + n)*(_k + 2*a + n)) + ((2*_k + 2)/((_k + 2*a)*(2*_k + 2*a + 1)) + 2/(_k + 2*a + n))*gegenbauer(n, a , x), (_k, 0, n - 1))) assert diff(gegenbauer(n, a, x), x) == 2*a*gegenbauer(n - 1, a + 1, x) assert gegenbauer(n, a, x).rewrite('polynomial').dummy_eq( Sum((-1)**_k*(2*x)**(-2*_k + n)*RisingFactorial(a, -_k + n) /(factorial(_k)*factorial(-2*_k + n)), (_k, 0, floor(n/2)))) raises(ArgumentIndexError, lambda: gegenbauer(n, a, x).fdiff(4)) def test_legendre(): assert legendre(0, x) == 1 assert legendre(1, x) == x assert legendre(2, x) == ((3*x**2 - 1)/2).expand() assert legendre(3, x) == ((5*x**3 - 3*x)/2).expand() assert legendre(4, x) == ((35*x**4 - 30*x**2 + 3)/8).expand() assert legendre(5, x) == ((63*x**5 - 70*x**3 + 15*x)/8).expand() assert legendre(6, x) == ((231*x**6 - 315*x**4 + 105*x**2 - 5)/16).expand() assert legendre(10, -1) == 1 assert legendre(11, -1) == -1 assert legendre(10, 1) == 1 assert legendre(11, 1) == 1 assert legendre(10, 0) != 0 assert legendre(11, 0) == 0 assert legendre(-1, x) == 1 k = Symbol('k') assert legendre(5 - k, x).subs(k, 2) == ((5*x**3 - 3*x)/2).expand() assert roots(legendre(4, x), x) == { sqrt(Rational(3, 7) - Rational(2, 35)*sqrt(30)): 1, -sqrt(Rational(3, 7) - Rational(2, 35)*sqrt(30)): 1, sqrt(Rational(3, 7) + Rational(2, 35)*sqrt(30)): 1, -sqrt(Rational(3, 7) + Rational(2, 35)*sqrt(30)): 1, } n = Symbol("n") X = legendre(n, x) assert isinstance(X, legendre) assert unchanged(legendre, n, x) assert legendre(n, 0) == sqrt(pi)/(gamma(S.Half - n/2)*gamma(n/2 + 1)) assert legendre(n, 1) == 1 assert legendre(n, oo) is oo assert legendre(-n, x) == legendre(n - 1, x) assert legendre(n, -x) == (-1)**n*legendre(n, x) assert unchanged(legendre, -n + k, x) assert conjugate(legendre(n, x)) == legendre(n, conjugate(x)) assert diff(legendre(n, x), x) == \ n*(x*legendre(n, x) - legendre(n - 1, x))/(x**2 - 1) assert diff(legendre(n, x), n) == Derivative(legendre(n, x), n) _k = Dummy('k') assert legendre(n, x).rewrite("polynomial").dummy_eq(Sum((-1)**_k*(S.Half - x/2)**_k*(x/2 + S.Half)**(-_k + n)*binomial(n, _k)**2, (_k, 0, n))) raises(ArgumentIndexError, lambda: legendre(n, x).fdiff(1)) raises(ArgumentIndexError, lambda: legendre(n, x).fdiff(3)) def test_assoc_legendre(): Plm = assoc_legendre Q = sqrt(1 - x**2) assert Plm(0, 0, x) == 1 assert Plm(1, 0, x) == x assert Plm(1, 1, x) == -Q assert Plm(2, 0, x) == (3*x**2 - 1)/2 assert Plm(2, 1, x) == -3*x*Q assert Plm(2, 2, x) == 3*Q**2 assert Plm(3, 0, x) == (5*x**3 - 3*x)/2 assert Plm(3, 1, x).expand() == (( 3*(1 - 5*x**2)/2 ).expand() * Q).expand() assert Plm(3, 2, x) == 15*x * Q**2 assert Plm(3, 3, x) == -15 * Q**3 # negative m assert Plm(1, -1, x) == -Plm(1, 1, x)/2 assert Plm(2, -2, x) == Plm(2, 2, x)/24 assert Plm(2, -1, x) == -Plm(2, 1, x)/6 assert Plm(3, -3, x) == -Plm(3, 3, x)/720 assert Plm(3, -2, x) == Plm(3, 2, x)/120 assert Plm(3, -1, x) == -Plm(3, 1, x)/12 n = Symbol("n") m = Symbol("m") X = Plm(n, m, x) assert isinstance(X, assoc_legendre) assert Plm(n, 0, x) == legendre(n, x) assert Plm(n, m, 0) == 2**m*sqrt(pi)/(gamma(-m/2 - n/2 + S.Half)*gamma(-m/2 + n/2 + 1)) assert diff(Plm(m, n, x), x) == (m*x*assoc_legendre(m, n, x) - (m + n)*assoc_legendre(m - 1, n, x))/(x**2 - 1) _k = Dummy('k') assert Plm(m, n, x).rewrite("polynomial").dummy_eq( (1 - x**2)**(n/2)*Sum((-1)**_k*2**(-m)*x**(-2*_k + m - n)*factorial (-2*_k + 2*m)/(factorial(_k)*factorial(-_k + m)*factorial(-2*_k + m - n)), (_k, 0, floor(m/2 - n/2)))) assert conjugate(assoc_legendre(n, m, x)) == \ assoc_legendre(n, conjugate(m), conjugate(x)) raises(ValueError, lambda: Plm(0, 1, x)) raises(ValueError, lambda: Plm(-1, 1, x)) raises(ArgumentIndexError, lambda: Plm(n, m, x).fdiff(1)) raises(ArgumentIndexError, lambda: Plm(n, m, x).fdiff(2)) raises(ArgumentIndexError, lambda: Plm(n, m, x).fdiff(4)) def test_chebyshev(): assert chebyshevt(0, x) == 1 assert chebyshevt(1, x) == x assert chebyshevt(2, x) == 2*x**2 - 1 assert chebyshevt(3, x) == 4*x**3 - 3*x for n in range(1, 4): for k in range(n): z = chebyshevt_root(n, k) assert chebyshevt(n, z) == 0 raises(ValueError, lambda: chebyshevt_root(n, n)) for n in range(1, 4): for k in range(n): z = chebyshevu_root(n, k) assert chebyshevu(n, z) == 0 raises(ValueError, lambda: chebyshevu_root(n, n)) n = Symbol("n") X = chebyshevt(n, x) assert isinstance(X, chebyshevt) assert unchanged(chebyshevt, n, x) assert chebyshevt(n, -x) == (-1)**n*chebyshevt(n, x) assert chebyshevt(-n, x) == chebyshevt(n, x) assert chebyshevt(n, 0) == cos(pi*n/2) assert chebyshevt(n, 1) == 1 assert chebyshevt(n, oo) is oo assert conjugate(chebyshevt(n, x)) == chebyshevt(n, conjugate(x)) assert diff(chebyshevt(n, x), x) == n*chebyshevu(n - 1, x) X = chebyshevu(n, x) assert isinstance(X, chebyshevu) y = Symbol('y') assert chebyshevu(n, -x) == (-1)**n*chebyshevu(n, x) assert chebyshevu(-n, x) == -chebyshevu(n - 2, x) assert unchanged(chebyshevu, -n + y, x) assert chebyshevu(n, 0) == cos(pi*n/2) assert chebyshevu(n, 1) == n + 1 assert chebyshevu(n, oo) is oo assert conjugate(chebyshevu(n, x)) == chebyshevu(n, conjugate(x)) assert diff(chebyshevu(n, x), x) == \ (-x*chebyshevu(n, x) + (n + 1)*chebyshevt(n + 1, x))/(x**2 - 1) _k = Dummy('k') assert chebyshevt(n, x).rewrite("polynomial").dummy_eq(Sum(x**(-2*_k + n) *(x**2 - 1)**_k*binomial(n, 2*_k), (_k, 0, floor(n/2)))) assert chebyshevu(n, x).rewrite("polynomial").dummy_eq(Sum((-1)**_k*(2*x) **(-2*_k + n)*factorial(-_k + n)/(factorial(_k)* factorial(-2*_k + n)), (_k, 0, floor(n/2)))) raises(ArgumentIndexError, lambda: chebyshevt(n, x).fdiff(1)) raises(ArgumentIndexError, lambda: chebyshevt(n, x).fdiff(3)) raises(ArgumentIndexError, lambda: chebyshevu(n, x).fdiff(1)) raises(ArgumentIndexError, lambda: chebyshevu(n, x).fdiff(3)) def test_hermite(): assert hermite(0, x) == 1 assert hermite(1, x) == 2*x assert hermite(2, x) == 4*x**2 - 2 assert hermite(3, x) == 8*x**3 - 12*x assert hermite(4, x) == 16*x**4 - 48*x**2 + 12 assert hermite(6, x) == 64*x**6 - 480*x**4 + 720*x**2 - 120 n = Symbol("n") assert unchanged(hermite, n, x) assert hermite(n, -x) == (-1)**n*hermite(n, x) assert unchanged(hermite, -n, x) assert hermite(n, 0) == 2**n*sqrt(pi)/gamma(S.Half - n/2) assert hermite(n, oo) is oo assert conjugate(hermite(n, x)) == hermite(n, conjugate(x)) _k = Dummy('k') assert hermite(n, x).rewrite("polynomial").dummy_eq(factorial(n)*Sum((-1) **_k*(2*x)**(-2*_k + n)/(factorial(_k)*factorial(-2*_k + n)), (_k, 0, floor(n/2)))) assert diff(hermite(n, x), x) == 2*n*hermite(n - 1, x) assert diff(hermite(n, x), n) == Derivative(hermite(n, x), n) raises(ArgumentIndexError, lambda: hermite(n, x).fdiff(3)) def test_laguerre(): n = Symbol("n") m = Symbol("m", negative=True) # Laguerre polynomials: assert laguerre(0, x) == 1 assert laguerre(1, x) == -x + 1 assert laguerre(2, x) == x**2/2 - 2*x + 1 assert laguerre(3, x) == -x**3/6 + 3*x**2/2 - 3*x + 1 assert laguerre(-2, x) == (x + 1)*exp(x) X = laguerre(n, x) assert isinstance(X, laguerre) assert laguerre(n, 0) == 1 assert laguerre(n, oo) == (-1)**n*oo assert laguerre(n, -oo) is oo assert conjugate(laguerre(n, x)) == laguerre(n, conjugate(x)) _k = Dummy('k') assert laguerre(n, x).rewrite("polynomial").dummy_eq( Sum(x**_k*RisingFactorial(-n, _k)/factorial(_k)**2, (_k, 0, n))) assert laguerre(m, x).rewrite("polynomial").dummy_eq( exp(x)*Sum((-x)**_k*RisingFactorial(m + 1, _k)/factorial(_k)**2, (_k, 0, -m - 1))) assert diff(laguerre(n, x), x) == -assoc_laguerre(n - 1, 1, x) k = Symbol('k') assert laguerre(-n, x) == exp(x)*laguerre(n - 1, -x) assert laguerre(-3, x) == exp(x)*laguerre(2, -x) assert unchanged(laguerre, -n + k, x) raises(ValueError, lambda: laguerre(-2.1, x)) raises(ValueError, lambda: laguerre(Rational(5, 2), x)) raises(ArgumentIndexError, lambda: laguerre(n, x).fdiff(1)) raises(ArgumentIndexError, lambda: laguerre(n, x).fdiff(3)) def test_assoc_laguerre(): n = Symbol("n") m = Symbol("m") alpha = Symbol("alpha") # generalized Laguerre polynomials: assert assoc_laguerre(0, alpha, x) == 1 assert assoc_laguerre(1, alpha, x) == -x + alpha + 1 assert assoc_laguerre(2, alpha, x).expand() == \ (x**2/2 - (alpha + 2)*x + (alpha + 2)*(alpha + 1)/2).expand() assert assoc_laguerre(3, alpha, x).expand() == \ (-x**3/6 + (alpha + 3)*x**2/2 - (alpha + 2)*(alpha + 3)*x/2 + (alpha + 1)*(alpha + 2)*(alpha + 3)/6).expand() # Test the lowest 10 polynomials with laguerre_poly, to make sure it works: for i in range(10): assert assoc_laguerre(i, 0, x).expand() == laguerre_poly(i, x) X = assoc_laguerre(n, m, x) assert isinstance(X, assoc_laguerre) assert assoc_laguerre(n, 0, x) == laguerre(n, x) assert assoc_laguerre(n, alpha, 0) == binomial(alpha + n, alpha) p = Symbol("p", positive=True) assert assoc_laguerre(p, alpha, oo) == (-1)**p*oo assert assoc_laguerre(p, alpha, -oo) is oo assert diff(assoc_laguerre(n, alpha, x), x) == \ -assoc_laguerre(n - 1, alpha + 1, x) _k = Dummy('k') assert diff(assoc_laguerre(n, alpha, x), alpha).dummy_eq( Sum(assoc_laguerre(_k, alpha, x)/(-alpha + n), (_k, 0, n - 1))) assert conjugate(assoc_laguerre(n, alpha, x)) == \ assoc_laguerre(n, conjugate(alpha), conjugate(x)) assert assoc_laguerre(n, alpha, x).rewrite('polynomial').dummy_eq( gamma(alpha + n + 1)*Sum(x**_k*RisingFactorial(-n, _k)/ (factorial(_k)*gamma(_k + alpha + 1)), (_k, 0, n))/factorial(n)) raises(ValueError, lambda: assoc_laguerre(-2.1, alpha, x)) raises(ArgumentIndexError, lambda: assoc_laguerre(n, alpha, x).fdiff(1)) raises(ArgumentIndexError, lambda: assoc_laguerre(n, alpha, x).fdiff(4))
f63c38f8988320853c109c05af1183efdd416b87e935ee02b597f0d9c96ac70d
from sympy import ( Symbol, Dummy, gamma, I, oo, nan, zoo, factorial, sqrt, Rational, multigamma, log, polygamma, digamma, trigamma, EulerGamma, pi, uppergamma, S, expand_func, loggamma, sin, cos, O, lowergamma, exp, erf, erfc, exp_polar, harmonic, zeta, conjugate, Ei, im, re, tanh, Abs) from sympy.core.expr import unchanged from sympy.core.function import ArgumentIndexError from sympy.testing.pytest import raises from sympy.testing.randtest import (test_derivative_numerically as td, random_complex_number as randcplx, verify_numerically as tn) x = Symbol('x') y = Symbol('y') n = Symbol('n', integer=True) w = Symbol('w', real=True) def test_gamma(): assert gamma(nan) is nan assert gamma(oo) is oo assert gamma(-100) is zoo assert gamma(0) is zoo assert gamma(-100.0) is zoo assert gamma(1) == 1 assert gamma(2) == 1 assert gamma(3) == 2 assert gamma(102) == factorial(101) assert gamma(S.Half) == sqrt(pi) assert gamma(Rational(3, 2)) == sqrt(pi)*S.Half assert gamma(Rational(5, 2)) == sqrt(pi)*Rational(3, 4) assert gamma(Rational(7, 2)) == sqrt(pi)*Rational(15, 8) assert gamma(Rational(-1, 2)) == -2*sqrt(pi) assert gamma(Rational(-3, 2)) == sqrt(pi)*Rational(4, 3) assert gamma(Rational(-5, 2)) == sqrt(pi)*Rational(-8, 15) assert gamma(Rational(-15, 2)) == sqrt(pi)*Rational(256, 2027025) assert gamma(Rational( -11, 8)).expand(func=True) == Rational(64, 33)*gamma(Rational(5, 8)) assert gamma(Rational( -10, 3)).expand(func=True) == Rational(81, 280)*gamma(Rational(2, 3)) assert gamma(Rational( 14, 3)).expand(func=True) == Rational(880, 81)*gamma(Rational(2, 3)) assert gamma(Rational( 17, 7)).expand(func=True) == Rational(30, 49)*gamma(Rational(3, 7)) assert gamma(Rational( 19, 8)).expand(func=True) == Rational(33, 64)*gamma(Rational(3, 8)) assert gamma(x).diff(x) == gamma(x)*polygamma(0, x) assert gamma(x - 1).expand(func=True) == gamma(x)/(x - 1) assert gamma(x + 2).expand(func=True, mul=False) == x*(x + 1)*gamma(x) assert conjugate(gamma(x)) == gamma(conjugate(x)) assert expand_func(gamma(x + Rational(3, 2))) == \ (x + S.Half)*gamma(x + S.Half) assert expand_func(gamma(x - S.Half)) == \ gamma(S.Half + x)/(x - S.Half) # Test a bug: assert expand_func(gamma(x + Rational(3, 4))) == gamma(x + Rational(3, 4)) # XXX: Not sure about these tests. I can fix them by defining e.g. # exp_polar.is_integer but I'm not sure if that makes sense. assert gamma(3*exp_polar(I*pi)/4).is_nonnegative is False assert gamma(3*exp_polar(I*pi)/4).is_extended_nonpositive is True y = Symbol('y', nonpositive=True, integer=True) assert gamma(y).is_real == False y = Symbol('y', positive=True, noninteger=True) assert gamma(y).is_real == True assert gamma(-1.0, evaluate=False).is_real == False assert gamma(0, evaluate=False).is_real == False assert gamma(-2, evaluate=False).is_real == False def test_gamma_rewrite(): assert gamma(n).rewrite(factorial) == factorial(n - 1) def test_gamma_series(): assert gamma(x + 1).series(x, 0, 3) == \ 1 - EulerGamma*x + x**2*(EulerGamma**2/2 + pi**2/12) + O(x**3) assert gamma(x).series(x, -1, 3) == \ -1/(x + 1) + EulerGamma - 1 + (x + 1)*(-1 - pi**2/12 - EulerGamma**2/2 + \ EulerGamma) + (x + 1)**2*(-1 - pi**2/12 - EulerGamma**2/2 + EulerGamma**3/6 - \ polygamma(2, 1)/6 + EulerGamma*pi**2/12 + EulerGamma) + O((x + 1)**3, (x, -1)) def tn_branch(s, func): from sympy import I, pi, exp_polar from random import uniform c = uniform(1, 5) expr = func(s, c*exp_polar(I*pi)) - func(s, c*exp_polar(-I*pi)) eps = 1e-15 expr2 = func(s + eps, -c + eps*I) - func(s + eps, -c - eps*I) return abs(expr.n() - expr2.n()).n() < 1e-10 def test_lowergamma(): from sympy import meijerg, exp_polar, I, expint assert lowergamma(x, 0) == 0 assert lowergamma(x, y).diff(y) == y**(x - 1)*exp(-y) assert td(lowergamma(randcplx(), y), y) assert td(lowergamma(x, randcplx()), x) assert lowergamma(x, y).diff(x) == \ gamma(x)*digamma(x) - uppergamma(x, y)*log(y) \ - meijerg([], [1, 1], [0, 0, x], [], y) assert lowergamma(S.Half, x) == sqrt(pi)*erf(sqrt(x)) assert not lowergamma(S.Half - 3, x).has(lowergamma) assert not lowergamma(S.Half + 3, x).has(lowergamma) assert lowergamma(S.Half, x, evaluate=False).has(lowergamma) assert tn(lowergamma(S.Half + 3, x, evaluate=False), lowergamma(S.Half + 3, x), x) assert tn(lowergamma(S.Half - 3, x, evaluate=False), lowergamma(S.Half - 3, x), x) assert tn_branch(-3, lowergamma) assert tn_branch(-4, lowergamma) assert tn_branch(Rational(1, 3), lowergamma) assert tn_branch(pi, lowergamma) assert lowergamma(3, exp_polar(4*pi*I)*x) == lowergamma(3, x) assert lowergamma(y, exp_polar(5*pi*I)*x) == \ exp(4*I*pi*y)*lowergamma(y, x*exp_polar(pi*I)) assert lowergamma(-2, exp_polar(5*pi*I)*x) == \ lowergamma(-2, x*exp_polar(I*pi)) + 2*pi*I assert conjugate(lowergamma(x, y)) == lowergamma(conjugate(x), conjugate(y)) assert conjugate(lowergamma(x, 0)) == 0 assert unchanged(conjugate, lowergamma(x, -oo)) assert lowergamma( x, y).rewrite(expint) == -y**x*expint(-x + 1, y) + gamma(x) k = Symbol('k', integer=True) assert lowergamma( k, y).rewrite(expint) == -y**k*expint(-k + 1, y) + gamma(k) k = Symbol('k', integer=True, positive=False) assert lowergamma(k, y).rewrite(expint) == lowergamma(k, y) assert lowergamma(x, y).rewrite(uppergamma) == gamma(x) - uppergamma(x, y) assert lowergamma(70, 6) == factorial(69) - 69035724522603011058660187038367026272747334489677105069435923032634389419656200387949342530805432320 * exp(-6) assert (lowergamma(S(77) / 2, 6) - lowergamma(S(77) / 2, 6, evaluate=False)).evalf() < 1e-16 assert (lowergamma(-S(77) / 2, 6) - lowergamma(-S(77) / 2, 6, evaluate=False)).evalf() < 1e-16 def test_uppergamma(): from sympy import meijerg, exp_polar, I, expint assert uppergamma(4, 0) == 6 assert uppergamma(x, y).diff(y) == -y**(x - 1)*exp(-y) assert td(uppergamma(randcplx(), y), y) assert uppergamma(x, y).diff(x) == \ uppergamma(x, y)*log(y) + meijerg([], [1, 1], [0, 0, x], [], y) assert td(uppergamma(x, randcplx()), x) p = Symbol('p', positive=True) assert uppergamma(0, p) == -Ei(-p) assert uppergamma(p, 0) == gamma(p) assert uppergamma(S.Half, x) == sqrt(pi)*erfc(sqrt(x)) assert not uppergamma(S.Half - 3, x).has(uppergamma) assert not uppergamma(S.Half + 3, x).has(uppergamma) assert uppergamma(S.Half, x, evaluate=False).has(uppergamma) assert tn(uppergamma(S.Half + 3, x, evaluate=False), uppergamma(S.Half + 3, x), x) assert tn(uppergamma(S.Half - 3, x, evaluate=False), uppergamma(S.Half - 3, x), x) assert unchanged(uppergamma, x, -oo) assert unchanged(uppergamma, x, 0) assert tn_branch(-3, uppergamma) assert tn_branch(-4, uppergamma) assert tn_branch(Rational(1, 3), uppergamma) assert tn_branch(pi, uppergamma) assert uppergamma(3, exp_polar(4*pi*I)*x) == uppergamma(3, x) assert uppergamma(y, exp_polar(5*pi*I)*x) == \ exp(4*I*pi*y)*uppergamma(y, x*exp_polar(pi*I)) + \ gamma(y)*(1 - exp(4*pi*I*y)) assert uppergamma(-2, exp_polar(5*pi*I)*x) == \ uppergamma(-2, x*exp_polar(I*pi)) - 2*pi*I assert uppergamma(-2, x) == expint(3, x)/x**2 assert conjugate(uppergamma(x, y)) == uppergamma(conjugate(x), conjugate(y)) assert unchanged(conjugate, uppergamma(x, -oo)) assert uppergamma(x, y).rewrite(expint) == y**x*expint(-x + 1, y) assert uppergamma(x, y).rewrite(lowergamma) == gamma(x) - lowergamma(x, y) assert uppergamma(70, 6) == 69035724522603011058660187038367026272747334489677105069435923032634389419656200387949342530805432320*exp(-6) assert (uppergamma(S(77) / 2, 6) - uppergamma(S(77) / 2, 6, evaluate=False)).evalf() < 1e-16 assert (uppergamma(-S(77) / 2, 6) - uppergamma(-S(77) / 2, 6, evaluate=False)).evalf() < 1e-16 def test_polygamma(): from sympy import I assert polygamma(n, nan) is nan assert polygamma(0, oo) is oo assert polygamma(0, -oo) is oo assert polygamma(0, I*oo) is oo assert polygamma(0, -I*oo) is oo assert polygamma(1, oo) == 0 assert polygamma(5, oo) == 0 assert polygamma(0, -9) is zoo assert polygamma(0, -9) is zoo assert polygamma(0, -1) is zoo assert polygamma(0, 0) is zoo assert polygamma(0, 1) == -EulerGamma assert polygamma(0, 7) == Rational(49, 20) - EulerGamma assert polygamma(1, 1) == pi**2/6 assert polygamma(1, 2) == pi**2/6 - 1 assert polygamma(1, 3) == pi**2/6 - Rational(5, 4) assert polygamma(3, 1) == pi**4 / 15 assert polygamma(3, 5) == 6*(Rational(-22369, 20736) + pi**4/90) assert polygamma(5, 1) == 8 * pi**6 / 63 assert polygamma(1, S.Half) == pi**2 / 2 assert polygamma(2, S.Half) == -14*zeta(3) assert polygamma(11, S.Half) == 176896*pi**12 def t(m, n): x = S(m)/n r = polygamma(0, x) if r.has(polygamma): return False return abs(polygamma(0, x.n()).n() - r.n()).n() < 1e-10 assert t(1, 2) assert t(3, 2) assert t(-1, 2) assert t(1, 4) assert t(-3, 4) assert t(1, 3) assert t(4, 3) assert t(3, 4) assert t(2, 3) assert t(123, 5) assert polygamma(0, x).rewrite(zeta) == polygamma(0, x) assert polygamma(1, x).rewrite(zeta) == zeta(2, x) assert polygamma(2, x).rewrite(zeta) == -2*zeta(3, x) assert polygamma(I, 2).rewrite(zeta) == polygamma(I, 2) n1 = Symbol('n1') n2 = Symbol('n2', real=True) n3 = Symbol('n3', integer=True) n4 = Symbol('n4', positive=True) n5 = Symbol('n5', positive=True, integer=True) assert polygamma(n1, x).rewrite(zeta) == polygamma(n1, x) assert polygamma(n2, x).rewrite(zeta) == polygamma(n2, x) assert polygamma(n3, x).rewrite(zeta) == polygamma(n3, x) assert polygamma(n4, x).rewrite(zeta) == polygamma(n4, x) assert polygamma(n5, x).rewrite(zeta) == (-1)**(n5 + 1) * factorial(n5) * zeta(n5 + 1, x) assert polygamma(3, 7*x).diff(x) == 7*polygamma(4, 7*x) assert polygamma(0, x).rewrite(harmonic) == harmonic(x - 1) - EulerGamma assert polygamma(2, x).rewrite(harmonic) == 2*harmonic(x - 1, 3) - 2*zeta(3) ni = Symbol("n", integer=True) assert polygamma(ni, x).rewrite(harmonic) == (-1)**(ni + 1)*(-harmonic(x - 1, ni + 1) + zeta(ni + 1))*factorial(ni) # Polygamma of non-negative integer order is unbranched: from sympy import exp_polar k = Symbol('n', integer=True, nonnegative=True) assert polygamma(k, exp_polar(2*I*pi)*x) == polygamma(k, x) # but negative integers are branched! k = Symbol('n', integer=True) assert polygamma(k, exp_polar(2*I*pi)*x).args == (k, exp_polar(2*I*pi)*x) # Polygamma of order -1 is loggamma: assert polygamma(-1, x) == loggamma(x) # But smaller orders are iterated integrals and don't have a special name assert polygamma(-2, x).func is polygamma # Test a bug assert polygamma(0, -x).expand(func=True) == polygamma(0, -x) assert polygamma(2, 2.5).is_positive == False assert polygamma(2, -2.5).is_positive == False assert polygamma(3, 2.5).is_positive == True assert polygamma(3, -2.5).is_positive is True assert polygamma(-2, -2.5).is_positive is None assert polygamma(-3, -2.5).is_positive is None assert polygamma(2, 2.5).is_negative == True assert polygamma(3, 2.5).is_negative == False assert polygamma(3, -2.5).is_negative == False assert polygamma(2, -2.5).is_negative is True assert polygamma(-2, -2.5).is_negative is None assert polygamma(-3, -2.5).is_negative is None assert polygamma(I, 2).is_positive is None assert polygamma(I, 3).is_negative is None # issue 17350 assert polygamma(pi, 3).evalf() == polygamma(pi, 3) assert (I*polygamma(I, pi)).as_real_imag() == \ (-im(polygamma(I, pi)), re(polygamma(I, pi))) assert (tanh(polygamma(I, 1))).rewrite(exp) == \ (exp(polygamma(I, 1)) - exp(-polygamma(I, 1)))/(exp(polygamma(I, 1)) + exp(-polygamma(I, 1))) assert (I / polygamma(I, 4)).rewrite(exp) == \ I*sqrt(re(polygamma(I, 4))**2 + im(polygamma(I, 4))**2)\ /((re(polygamma(I, 4)) + I*im(polygamma(I, 4)))*Abs(polygamma(I, 4))) assert unchanged(polygamma, 2.3, 1.0) # issue 12569 assert unchanged(im, polygamma(0, I)) assert polygamma(Symbol('a', positive=True), Symbol('b', positive=True)).is_real is True assert polygamma(0, I).is_real is None def test_polygamma_expand_func(): assert polygamma(0, x).expand(func=True) == polygamma(0, x) assert polygamma(0, 2*x).expand(func=True) == \ polygamma(0, x)/2 + polygamma(0, S.Half + x)/2 + log(2) assert polygamma(1, 2*x).expand(func=True) == \ polygamma(1, x)/4 + polygamma(1, S.Half + x)/4 assert polygamma(2, x).expand(func=True) == \ polygamma(2, x) assert polygamma(0, -1 + x).expand(func=True) == \ polygamma(0, x) - 1/(x - 1) assert polygamma(0, 1 + x).expand(func=True) == \ 1/x + polygamma(0, x ) assert polygamma(0, 2 + x).expand(func=True) == \ 1/x + 1/(1 + x) + polygamma(0, x) assert polygamma(0, 3 + x).expand(func=True) == \ polygamma(0, x) + 1/x + 1/(1 + x) + 1/(2 + x) assert polygamma(0, 4 + x).expand(func=True) == \ polygamma(0, x) + 1/x + 1/(1 + x) + 1/(2 + x) + 1/(3 + x) assert polygamma(1, 1 + x).expand(func=True) == \ polygamma(1, x) - 1/x**2 assert polygamma(1, 2 + x).expand(func=True, multinomial=False) == \ polygamma(1, x) - 1/x**2 - 1/(1 + x)**2 assert polygamma(1, 3 + x).expand(func=True, multinomial=False) == \ polygamma(1, x) - 1/x**2 - 1/(1 + x)**2 - 1/(2 + x)**2 assert polygamma(1, 4 + x).expand(func=True, multinomial=False) == \ polygamma(1, x) - 1/x**2 - 1/(1 + x)**2 - \ 1/(2 + x)**2 - 1/(3 + x)**2 assert polygamma(0, x + y).expand(func=True) == \ polygamma(0, x + y) assert polygamma(1, x + y).expand(func=True) == \ polygamma(1, x + y) assert polygamma(1, 3 + 4*x + y).expand(func=True, multinomial=False) == \ polygamma(1, y + 4*x) - 1/(y + 4*x)**2 - \ 1/(1 + y + 4*x)**2 - 1/(2 + y + 4*x)**2 assert polygamma(3, 3 + 4*x + y).expand(func=True, multinomial=False) == \ polygamma(3, y + 4*x) - 6/(y + 4*x)**4 - \ 6/(1 + y + 4*x)**4 - 6/(2 + y + 4*x)**4 assert polygamma(3, 4*x + y + 1).expand(func=True, multinomial=False) == \ polygamma(3, y + 4*x) - 6/(y + 4*x)**4 e = polygamma(3, 4*x + y + Rational(3, 2)) assert e.expand(func=True) == e e = polygamma(3, x + y + Rational(3, 4)) assert e.expand(func=True, basic=False) == e def test_digamma(): from sympy import I assert digamma(nan) == nan assert digamma(oo) == oo assert digamma(-oo) == oo assert digamma(I*oo) == oo assert digamma(-I*oo) == oo assert digamma(-9) == zoo assert digamma(-9) == zoo assert digamma(-1) == zoo assert digamma(0) == zoo assert digamma(1) == -EulerGamma assert digamma(7) == Rational(49, 20) - EulerGamma def t(m, n): x = S(m)/n r = digamma(x) if r.has(digamma): return False return abs(digamma(x.n()).n() - r.n()).n() < 1e-10 assert t(1, 2) assert t(3, 2) assert t(-1, 2) assert t(1, 4) assert t(-3, 4) assert t(1, 3) assert t(4, 3) assert t(3, 4) assert t(2, 3) assert t(123, 5) assert digamma(x).rewrite(zeta) == polygamma(0, x) assert digamma(x).rewrite(harmonic) == harmonic(x - 1) - EulerGamma assert digamma(I).is_real is None assert digamma(x,evaluate=False).fdiff() == polygamma(1, x) assert digamma(x,evaluate=False).is_real is None assert digamma(x,evaluate=False).is_positive is None assert digamma(x,evaluate=False).is_negative is None assert digamma(x,evaluate=False).rewrite(polygamma) == polygamma(0, x) def test_digamma_expand_func(): assert digamma(x).expand(func=True) == polygamma(0, x) assert digamma(2*x).expand(func=True) == \ polygamma(0, x)/2 + polygamma(0, Rational(1, 2) + x)/2 + log(2) assert digamma(-1 + x).expand(func=True) == \ polygamma(0, x) - 1/(x - 1) assert digamma(1 + x).expand(func=True) == \ 1/x + polygamma(0, x ) assert digamma(2 + x).expand(func=True) == \ 1/x + 1/(1 + x) + polygamma(0, x) assert digamma(3 + x).expand(func=True) == \ polygamma(0, x) + 1/x + 1/(1 + x) + 1/(2 + x) assert digamma(4 + x).expand(func=True) == \ polygamma(0, x) + 1/x + 1/(1 + x) + 1/(2 + x) + 1/(3 + x) assert digamma(x + y).expand(func=True) == \ polygamma(0, x + y) def test_trigamma(): assert trigamma(nan) == nan assert trigamma(oo) == 0 assert trigamma(1) == pi**2/6 assert trigamma(2) == pi**2/6 - 1 assert trigamma(3) == pi**2/6 - Rational(5, 4) assert trigamma(x, evaluate=False).rewrite(zeta) == zeta(2, x) assert trigamma(x, evaluate=False).rewrite(harmonic) == \ trigamma(x).rewrite(polygamma).rewrite(harmonic) assert trigamma(x,evaluate=False).fdiff() == polygamma(2, x) assert trigamma(x,evaluate=False).is_real is None assert trigamma(x,evaluate=False).is_positive is None assert trigamma(x,evaluate=False).is_negative is None assert trigamma(x,evaluate=False).rewrite(polygamma) == polygamma(1, x) def test_trigamma_expand_func(): assert trigamma(2*x).expand(func=True) == \ polygamma(1, x)/4 + polygamma(1, Rational(1, 2) + x)/4 assert trigamma(1 + x).expand(func=True) == \ polygamma(1, x) - 1/x**2 assert trigamma(2 + x).expand(func=True, multinomial=False) == \ polygamma(1, x) - 1/x**2 - 1/(1 + x)**2 assert trigamma(3 + x).expand(func=True, multinomial=False) == \ polygamma(1, x) - 1/x**2 - 1/(1 + x)**2 - 1/(2 + x)**2 assert trigamma(4 + x).expand(func=True, multinomial=False) == \ polygamma(1, x) - 1/x**2 - 1/(1 + x)**2 - \ 1/(2 + x)**2 - 1/(3 + x)**2 assert trigamma(x + y).expand(func=True) == \ polygamma(1, x + y) assert trigamma(3 + 4*x + y).expand(func=True, multinomial=False) == \ polygamma(1, y + 4*x) - 1/(y + 4*x)**2 - \ 1/(1 + y + 4*x)**2 - 1/(2 + y + 4*x)**2 def test_loggamma(): raises(TypeError, lambda: loggamma(2, 3)) raises(ArgumentIndexError, lambda: loggamma(x).fdiff(2)) assert loggamma(-1) is oo assert loggamma(-2) is oo assert loggamma(0) is oo assert loggamma(1) == 0 assert loggamma(2) == 0 assert loggamma(3) == log(2) assert loggamma(4) == log(6) n = Symbol("n", integer=True, positive=True) assert loggamma(n) == log(gamma(n)) assert loggamma(-n) is oo assert loggamma(n/2) == log(2**(-n + 1)*sqrt(pi)*gamma(n)/gamma(n/2 + S.Half)) from sympy import I assert loggamma(oo) is oo assert loggamma(-oo) is zoo assert loggamma(I*oo) is zoo assert loggamma(-I*oo) is zoo assert loggamma(zoo) is zoo assert loggamma(nan) is nan L = loggamma(Rational(16, 3)) E = -5*log(3) + loggamma(Rational(1, 3)) + log(4) + log(7) + log(10) + log(13) assert expand_func(L).doit() == E assert L.n() == E.n() L = loggamma(Rational(19, 4)) E = -4*log(4) + loggamma(Rational(3, 4)) + log(3) + log(7) + log(11) + log(15) assert expand_func(L).doit() == E assert L.n() == E.n() L = loggamma(Rational(23, 7)) E = -3*log(7) + log(2) + loggamma(Rational(2, 7)) + log(9) + log(16) assert expand_func(L).doit() == E assert L.n() == E.n() L = loggamma(Rational(19, 4) - 7) E = -log(9) - log(5) + loggamma(Rational(3, 4)) + 3*log(4) - 3*I*pi assert expand_func(L).doit() == E assert L.n() == E.n() L = loggamma(Rational(23, 7) - 6) E = -log(19) - log(12) - log(5) + loggamma(Rational(2, 7)) + 3*log(7) - 3*I*pi assert expand_func(L).doit() == E assert L.n() == E.n() assert loggamma(x).diff(x) == polygamma(0, x) s1 = loggamma(1/(x + sin(x)) + cos(x)).nseries(x, n=4) s2 = (-log(2*x) - 1)/(2*x) - log(x/pi)/2 + (4 - log(2*x))*x/24 + O(x**2) + \ log(x)*x**2/2 assert (s1 - s2).expand(force=True).removeO() == 0 s1 = loggamma(1/x).series(x) s2 = (1/x - S.Half)*log(1/x) - 1/x + log(2*pi)/2 + \ x/12 - x**3/360 + x**5/1260 + O(x**7) assert ((s1 - s2).expand(force=True)).removeO() == 0 assert loggamma(x).rewrite('intractable') == log(gamma(x)) s1 = loggamma(x).series(x) assert s1 == -log(x) - EulerGamma*x + pi**2*x**2/12 + x**3*polygamma(2, 1)/6 + \ pi**4*x**4/360 + x**5*polygamma(4, 1)/120 + O(x**6) assert s1 == loggamma(x).rewrite('intractable').series(x) assert conjugate(loggamma(x)) == loggamma(conjugate(x)) assert conjugate(loggamma(0)) is oo assert conjugate(loggamma(1)) == loggamma(conjugate(1)) assert conjugate(loggamma(-oo)) == conjugate(zoo) assert loggamma(Symbol('v', positive=True)).is_real is True assert loggamma(Symbol('v', zero=True)).is_real is False assert loggamma(Symbol('v', negative=True)).is_real is False assert loggamma(Symbol('v', nonpositive=True)).is_real is False assert loggamma(Symbol('v', nonnegative=True)).is_real is None assert loggamma(Symbol('v', imaginary=True)).is_real is None assert loggamma(Symbol('v', real=True)).is_real is None assert loggamma(Symbol('v')).is_real is None assert loggamma(S.Half).is_real is True assert loggamma(0).is_real is False assert loggamma(Rational(-1, 2)).is_real is False assert loggamma(I).is_real is None assert loggamma(2 + 3*I).is_real is None def tN(N, M): assert loggamma(1/x)._eval_nseries(x, n=N).getn() == M tN(0, 0) tN(1, 1) tN(2, 3) tN(3, 3) tN(4, 5) tN(5, 5) def test_polygamma_expansion(): # A. & S., pa. 259 and 260 assert polygamma(0, 1/x).nseries(x, n=3) == \ -log(x) - x/2 - x**2/12 + O(x**4) assert polygamma(1, 1/x).series(x, n=5) == \ x + x**2/2 + x**3/6 + O(x**5) assert polygamma(3, 1/x).nseries(x, n=11) == \ 2*x**3 + 3*x**4 + 2*x**5 - x**7 + 4*x**9/3 + O(x**11) def test_issue_8657(): n = Symbol('n', negative=True, integer=True) m = Symbol('m', integer=True) o = Symbol('o', positive=True) p = Symbol('p', negative=True, integer=False) assert gamma(n).is_real is False assert gamma(m).is_real is None assert gamma(o).is_real is True assert gamma(p).is_real is True assert gamma(w).is_real is None def test_issue_8524(): x = Symbol('x', positive=True) y = Symbol('y', negative=True) z = Symbol('z', positive=False) p = Symbol('p', negative=False) q = Symbol('q', integer=True) r = Symbol('r', integer=False) e = Symbol('e', even=True, negative=True) assert gamma(x).is_positive is True assert gamma(y).is_positive is None assert gamma(z).is_positive is None assert gamma(p).is_positive is None assert gamma(q).is_positive is None assert gamma(r).is_positive is None assert gamma(e + S.Half).is_positive is True assert gamma(e - S.Half).is_positive is False def test_issue_14450(): assert uppergamma(Rational(3, 8), x).evalf() == uppergamma(Rational(3, 8), x) assert lowergamma(x, Rational(3, 8)).evalf() == lowergamma(x, Rational(3, 8)) # some values from Wolfram Alpha for comparison assert abs(uppergamma(Rational(3, 8), 2).evalf() - 0.07105675881) < 1e-9 assert abs(lowergamma(Rational(3, 8), 2).evalf() - 2.2993794256) < 1e-9 def test_issue_14528(): k = Symbol('k', integer=True, nonpositive=True) assert isinstance(gamma(k), gamma) def test_multigamma(): from sympy import Product p = Symbol('p') _k = Dummy('_k') assert multigamma(x, p).dummy_eq(pi**(p*(p - 1)/4)*\ Product(gamma(x + (1 - _k)/2), (_k, 1, p))) assert conjugate(multigamma(x, p)).dummy_eq(pi**((conjugate(p) - 1)*\ conjugate(p)/4)*Product(gamma(conjugate(x) + (1-conjugate(_k))/2), (_k, 1, p))) assert conjugate(multigamma(x, 1)) == gamma(conjugate(x)) p = Symbol('p', positive=True) assert conjugate(multigamma(x, p)).dummy_eq(pi**((p - 1)*p/4)*\ Product(gamma(conjugate(x) + (1-conjugate(_k))/2), (_k, 1, p))) assert multigamma(nan, 1) is nan assert multigamma(oo, 1).doit() is oo assert multigamma(1, 1) == 1 assert multigamma(2, 1) == 1 assert multigamma(3, 1) == 2 assert multigamma(102, 1) == factorial(101) assert multigamma(S.Half, 1) == sqrt(pi) assert multigamma(1, 2) == pi assert multigamma(2, 2) == pi/2 assert multigamma(1, 3) is zoo assert multigamma(2, 3) == pi**2/2 assert multigamma(3, 3) == 3*pi**2/2 assert multigamma(x, 1).diff(x) == gamma(x)*polygamma(0, x) assert multigamma(x, 2).diff(x) == sqrt(pi)*gamma(x)*gamma(x - S.Half)*\ polygamma(0, x) + sqrt(pi)*gamma(x)*gamma(x - S.Half)*polygamma(0, x - S.Half) assert multigamma(x - 1, 1).expand(func=True) == gamma(x)/(x - 1) assert multigamma(x + 2, 1).expand(func=True, mul=False) == x*(x + 1)*\ gamma(x) assert multigamma(x - 1, 2).expand(func=True) == sqrt(pi)*gamma(x)*\ gamma(x + S.Half)/(x**3 - 3*x**2 + x*Rational(11, 4) - Rational(3, 4)) assert multigamma(x - 1, 3).expand(func=True) == pi**Rational(3, 2)*gamma(x)**2*\ gamma(x + S.Half)/(x**5 - 6*x**4 + 55*x**3/4 - 15*x**2 + x*Rational(31, 4) - Rational(3, 2)) assert multigamma(n, 1).rewrite(factorial) == factorial(n - 1) assert multigamma(n, 2).rewrite(factorial) == sqrt(pi)*\ factorial(n - Rational(3, 2))*factorial(n - 1) assert multigamma(n, 3).rewrite(factorial) == pi**Rational(3, 2)*\ factorial(n - 2)*factorial(n - Rational(3, 2))*factorial(n - 1) assert multigamma(Rational(-1, 2), 3, evaluate=False).is_real == False assert multigamma(S.Half, 3, evaluate=False).is_real == False assert multigamma(0, 1, evaluate=False).is_real == False assert multigamma(1, 3, evaluate=False).is_real == False assert multigamma(-1.0, 3, evaluate=False).is_real == False assert multigamma(0.7, 3, evaluate=False).is_real == True assert multigamma(3, 3, evaluate=False).is_real == True def test_gamma_as_leading_term(): assert gamma(x).as_leading_term(x) == 1/x assert gamma(2 + x).as_leading_term(x) == S(1) assert gamma(cos(x)).as_leading_term(x) == S(1) assert gamma(sin(x)).as_leading_term(x) == 1/x
27349dfb7527b0625db9bd22b8ccbb29b0923f95b9c9d7833f8a710c85b9b0cb
from sympy import ( symbols, expand, expand_func, nan, oo, Float, conjugate, diff, re, im, O, exp_polar, polar_lift, gruntz, limit, Symbol, I, integrate, Integral, S, sqrt, sin, cos, sinc, sinh, cosh, exp, log, pi, EulerGamma, erf, erfc, erfi, erf2, erfinv, erfcinv, erf2inv, gamma, uppergamma, Ei, expint, E1, li, Li, Si, Ci, Shi, Chi, fresnels, fresnelc, hyper, meijerg, E, Rational) from sympy.core.expr import unchanged from sympy.core.function import ArgumentIndexError from sympy.functions.special.error_functions import _erfs, _eis from sympy.testing.pytest import raises, slow x, y, z = symbols('x,y,z') w = Symbol("w", real=True) n = Symbol("n", integer=True) def test_erf(): assert erf(nan) is nan assert erf(oo) == 1 assert erf(-oo) == -1 assert erf(0) == 0 assert erf(I*oo) == oo*I assert erf(-I*oo) == -oo*I assert erf(-2) == -erf(2) assert erf(-x*y) == -erf(x*y) assert erf(-x - y) == -erf(x + y) assert erf(erfinv(x)) == x assert erf(erfcinv(x)) == 1 - x assert erf(erf2inv(0, x)) == x assert erf(erf2inv(0, x, evaluate=False)) == x # To cover code in erf assert erf(erf2inv(0, erf(erfcinv(1 - erf(erfinv(x)))))) == x assert erf(I).is_real is False assert erf(0).is_real is True assert conjugate(erf(z)) == erf(conjugate(z)) assert erf(x).as_leading_term(x) == 2*x/sqrt(pi) assert erf(1/x).as_leading_term(x) == erf(1/x) assert erf(z).rewrite('uppergamma') == sqrt(z**2)*(1 - erfc(sqrt(z**2)))/z assert erf(z).rewrite('erfc') == S.One - erfc(z) assert erf(z).rewrite('erfi') == -I*erfi(I*z) assert erf(z).rewrite('fresnels') == (1 + I)*(fresnelc(z*(1 - I)/sqrt(pi)) - I*fresnels(z*(1 - I)/sqrt(pi))) assert erf(z).rewrite('fresnelc') == (1 + I)*(fresnelc(z*(1 - I)/sqrt(pi)) - I*fresnels(z*(1 - I)/sqrt(pi))) assert erf(z).rewrite('hyper') == 2*z*hyper([S.Half], [3*S.Half], -z**2)/sqrt(pi) assert erf(z).rewrite('meijerg') == z*meijerg([S.Half], [], [0], [Rational(-1, 2)], z**2)/sqrt(pi) assert erf(z).rewrite('expint') == sqrt(z**2)/z - z*expint(S.Half, z**2)/sqrt(S.Pi) assert limit(exp(x)*exp(x**2)*(erf(x + 1/exp(x)) - erf(x)), x, oo) == \ 2/sqrt(pi) assert limit((1 - erf(z))*exp(z**2)*z, z, oo) == 1/sqrt(pi) assert limit((1 - erf(x))*exp(x**2)*sqrt(pi)*x, x, oo) == 1 assert limit(((1 - erf(x))*exp(x**2)*sqrt(pi)*x - 1)*2*x**2, x, oo) == -1 assert erf(x).as_real_imag() == \ (erf(re(x) - I*im(x))/2 + erf(re(x) + I*im(x))/2, -I*(-erf(re(x) - I*im(x)) + erf(re(x) + I*im(x)))/2) assert erf(x).as_real_imag(deep=False) == \ (erf(re(x) - I*im(x))/2 + erf(re(x) + I*im(x))/2, -I*(-erf(re(x) - I*im(x)) + erf(re(x) + I*im(x)))/2) assert erf(w).as_real_imag() == (erf(w), 0) assert erf(w).as_real_imag(deep=False) == (erf(w), 0) # issue 13575 assert erf(I).as_real_imag() == (0, -I*erf(I)) raises(ArgumentIndexError, lambda: erf(x).fdiff(2)) assert erf(x).inverse() == erfinv def test_erf_series(): assert erf(x).series(x, 0, 7) == 2*x/sqrt(pi) - \ 2*x**3/3/sqrt(pi) + x**5/5/sqrt(pi) + O(x**7) def test_erf_evalf(): assert abs( erf(Float(2.0)) - 0.995322265 ) < 1E-8 # XXX def test__erfs(): assert _erfs(z).diff(z) == -2/sqrt(S.Pi) + 2*z*_erfs(z) assert _erfs(1/z).series(z) == \ z/sqrt(pi) - z**3/(2*sqrt(pi)) + 3*z**5/(4*sqrt(pi)) + O(z**6) assert expand(erf(z).rewrite('tractable').diff(z).rewrite('intractable')) \ == erf(z).diff(z) assert _erfs(z).rewrite("intractable") == (-erf(z) + 1)*exp(z**2) raises(ArgumentIndexError, lambda: _erfs(z).fdiff(2)) def test_erfc(): assert erfc(nan) is nan assert erfc(oo) == 0 assert erfc(-oo) == 2 assert erfc(0) == 1 assert erfc(I*oo) == -oo*I assert erfc(-I*oo) == oo*I assert erfc(-x) == S(2) - erfc(x) assert erfc(erfcinv(x)) == x assert erfc(I).is_real is False assert erfc(0).is_real is True assert erfc(erfinv(x)) == 1 - x assert conjugate(erfc(z)) == erfc(conjugate(z)) assert erfc(x).as_leading_term(x) is S.One assert erfc(1/x).as_leading_term(x) == erfc(1/x) assert erfc(z).rewrite('erf') == 1 - erf(z) assert erfc(z).rewrite('erfi') == 1 + I*erfi(I*z) assert erfc(z).rewrite('fresnels') == 1 - (1 + I)*(fresnelc(z*(1 - I)/sqrt(pi)) - I*fresnels(z*(1 - I)/sqrt(pi))) assert erfc(z).rewrite('fresnelc') == 1 - (1 + I)*(fresnelc(z*(1 - I)/sqrt(pi)) - I*fresnels(z*(1 - I)/sqrt(pi))) assert erfc(z).rewrite('hyper') == 1 - 2*z*hyper([S.Half], [3*S.Half], -z**2)/sqrt(pi) assert erfc(z).rewrite('meijerg') == 1 - z*meijerg([S.Half], [], [0], [Rational(-1, 2)], z**2)/sqrt(pi) assert erfc(z).rewrite('uppergamma') == 1 - sqrt(z**2)*(1 - erfc(sqrt(z**2)))/z assert erfc(z).rewrite('expint') == S.One - sqrt(z**2)/z + z*expint(S.Half, z**2)/sqrt(S.Pi) assert erfc(z).rewrite('tractable') == _erfs(z)*exp(-z**2) assert expand_func(erf(x) + erfc(x)) is S.One assert erfc(x).as_real_imag() == \ (erfc(re(x) - I*im(x))/2 + erfc(re(x) + I*im(x))/2, -I*(-erfc(re(x) - I*im(x)) + erfc(re(x) + I*im(x)))/2) assert erfc(x).as_real_imag(deep=False) == \ (erfc(re(x) - I*im(x))/2 + erfc(re(x) + I*im(x))/2, -I*(-erfc(re(x) - I*im(x)) + erfc(re(x) + I*im(x)))/2) assert erfc(w).as_real_imag() == (erfc(w), 0) assert erfc(w).as_real_imag(deep=False) == (erfc(w), 0) raises(ArgumentIndexError, lambda: erfc(x).fdiff(2)) assert erfc(x).inverse() == erfcinv def test_erfc_series(): assert erfc(x).series(x, 0, 7) == 1 - 2*x/sqrt(pi) + \ 2*x**3/3/sqrt(pi) - x**5/5/sqrt(pi) + O(x**7) def test_erfc_evalf(): assert abs( erfc(Float(2.0)) - 0.00467773 ) < 1E-8 # XXX def test_erfi(): assert erfi(nan) is nan assert erfi(oo) is S.Infinity assert erfi(-oo) is S.NegativeInfinity assert erfi(0) is S.Zero assert erfi(I*oo) == I assert erfi(-I*oo) == -I assert erfi(-x) == -erfi(x) assert erfi(I*erfinv(x)) == I*x assert erfi(I*erfcinv(x)) == I*(1 - x) assert erfi(I*erf2inv(0, x)) == I*x assert erfi(I*erf2inv(0, x, evaluate=False)) == I*x # To cover code in erfi assert erfi(I).is_real is False assert erfi(0).is_real is True assert conjugate(erfi(z)) == erfi(conjugate(z)) assert erfi(z).rewrite('erf') == -I*erf(I*z) assert erfi(z).rewrite('erfc') == I*erfc(I*z) - I assert erfi(z).rewrite('fresnels') == (1 - I)*(fresnelc(z*(1 + I)/sqrt(pi)) - I*fresnels(z*(1 + I)/sqrt(pi))) assert erfi(z).rewrite('fresnelc') == (1 - I)*(fresnelc(z*(1 + I)/sqrt(pi)) - I*fresnels(z*(1 + I)/sqrt(pi))) assert erfi(z).rewrite('hyper') == 2*z*hyper([S.Half], [3*S.Half], z**2)/sqrt(pi) assert erfi(z).rewrite('meijerg') == z*meijerg([S.Half], [], [0], [Rational(-1, 2)], -z**2)/sqrt(pi) assert erfi(z).rewrite('uppergamma') == (sqrt(-z**2)/z*(uppergamma(S.Half, -z**2)/sqrt(S.Pi) - S.One)) assert erfi(z).rewrite('expint') == sqrt(-z**2)/z - z*expint(S.Half, -z**2)/sqrt(S.Pi) assert erfi(z).rewrite('tractable') == -I*(-_erfs(I*z)*exp(z**2) + 1) assert expand_func(erfi(I*z)) == I*erf(z) assert erfi(x).as_real_imag() == \ (erfi(re(x) - I*im(x))/2 + erfi(re(x) + I*im(x))/2, -I*(-erfi(re(x) - I*im(x)) + erfi(re(x) + I*im(x)))/2) assert erfi(x).as_real_imag(deep=False) == \ (erfi(re(x) - I*im(x))/2 + erfi(re(x) + I*im(x))/2, -I*(-erfi(re(x) - I*im(x)) + erfi(re(x) + I*im(x)))/2) assert erfi(w).as_real_imag() == (erfi(w), 0) assert erfi(w).as_real_imag(deep=False) == (erfi(w), 0) raises(ArgumentIndexError, lambda: erfi(x).fdiff(2)) def test_erfi_series(): assert erfi(x).series(x, 0, 7) == 2*x/sqrt(pi) + \ 2*x**3/3/sqrt(pi) + x**5/5/sqrt(pi) + O(x**7) def test_erfi_evalf(): assert abs( erfi(Float(2.0)) - 18.5648024145756 ) < 1E-13 # XXX def test_erf2(): assert erf2(0, 0) is S.Zero assert erf2(x, x) is S.Zero assert erf2(nan, 0) is nan assert erf2(-oo, y) == erf(y) + 1 assert erf2( oo, y) == erf(y) - 1 assert erf2( x, oo) == 1 - erf(x) assert erf2( x,-oo) == -1 - erf(x) assert erf2(x, erf2inv(x, y)) == y assert erf2(-x, -y) == -erf2(x,y) assert erf2(-x, y) == erf(y) + erf(x) assert erf2( x, -y) == -erf(y) - erf(x) assert erf2(x, y).rewrite('fresnels') == erf(y).rewrite(fresnels)-erf(x).rewrite(fresnels) assert erf2(x, y).rewrite('fresnelc') == erf(y).rewrite(fresnelc)-erf(x).rewrite(fresnelc) assert erf2(x, y).rewrite('hyper') == erf(y).rewrite(hyper)-erf(x).rewrite(hyper) assert erf2(x, y).rewrite('meijerg') == erf(y).rewrite(meijerg)-erf(x).rewrite(meijerg) assert erf2(x, y).rewrite('uppergamma') == erf(y).rewrite(uppergamma) - erf(x).rewrite(uppergamma) assert erf2(x, y).rewrite('expint') == erf(y).rewrite(expint)-erf(x).rewrite(expint) assert erf2(I, 0).is_real is False assert erf2(0, 0).is_real is True assert expand_func(erf(x) + erf2(x, y)) == erf(y) assert conjugate(erf2(x, y)) == erf2(conjugate(x), conjugate(y)) assert erf2(x, y).rewrite('erf') == erf(y) - erf(x) assert erf2(x, y).rewrite('erfc') == erfc(x) - erfc(y) assert erf2(x, y).rewrite('erfi') == I*(erfi(I*x) - erfi(I*y)) assert erf2(x, y).diff(x) == erf2(x, y).fdiff(1) assert erf2(x, y).diff(y) == erf2(x, y).fdiff(2) assert erf2(x, y).diff(x) == -2*exp(-x**2)/sqrt(pi) assert erf2(x, y).diff(y) == 2*exp(-y**2)/sqrt(pi) raises(ArgumentIndexError, lambda: erf2(x, y).fdiff(3)) assert erf2(x, y).is_extended_real is None xr, yr = symbols('xr yr', extended_real=True) assert erf2(xr, yr).is_extended_real is True def test_erfinv(): assert erfinv(0) == 0 assert erfinv(1) is S.Infinity assert erfinv(nan) is S.NaN assert erfinv(-1) is S.NegativeInfinity assert erfinv(erf(w)) == w assert erfinv(erf(-w)) == -w assert erfinv(x).diff() == sqrt(pi)*exp(erfinv(x)**2)/2 raises(ArgumentIndexError, lambda: erfinv(x).fdiff(2)) assert erfinv(z).rewrite('erfcinv') == erfcinv(1-z) assert erfinv(z).inverse() == erf def test_erfinv_evalf(): assert abs( erfinv(Float(0.2)) - 0.179143454621292 ) < 1E-13 def test_erfcinv(): assert erfcinv(1) == 0 assert erfcinv(0) is S.Infinity assert erfcinv(nan) is S.NaN assert erfcinv(x).diff() == -sqrt(pi)*exp(erfcinv(x)**2)/2 raises(ArgumentIndexError, lambda: erfcinv(x).fdiff(2)) assert erfcinv(z).rewrite('erfinv') == erfinv(1-z) assert erfcinv(z).inverse() == erfc def test_erf2inv(): assert erf2inv(0, 0) is S.Zero assert erf2inv(0, 1) is S.Infinity assert erf2inv(1, 0) is S.One assert erf2inv(0, y) == erfinv(y) assert erf2inv(oo, y) == erfcinv(-y) assert erf2inv(x, 0) == x assert erf2inv(x, oo) == erfinv(x) assert erf2inv(nan, 0) is nan assert erf2inv(0, nan) is nan assert erf2inv(x, y).diff(x) == exp(-x**2 + erf2inv(x, y)**2) assert erf2inv(x, y).diff(y) == sqrt(pi)*exp(erf2inv(x, y)**2)/2 raises(ArgumentIndexError, lambda: erf2inv(x, y).fdiff(3)) # NOTE we multiply by exp_polar(I*pi) and need this to be on the principal # branch, hence take x in the lower half plane (d=0). def mytn(expr1, expr2, expr3, x, d=0): from sympy.testing.randtest import verify_numerically, random_complex_number subs = {} for a in expr1.free_symbols: if a != x: subs[a] = random_complex_number() return expr2 == expr3 and verify_numerically(expr1.subs(subs), expr2.subs(subs), x, d=d) def mytd(expr1, expr2, x): from sympy.testing.randtest import test_derivative_numerically, \ random_complex_number subs = {} for a in expr1.free_symbols: if a != x: subs[a] = random_complex_number() return expr1.diff(x) == expr2 and test_derivative_numerically(expr1.subs(subs), x) def tn_branch(func, s=None): from sympy import I, pi, exp_polar from random import uniform def fn(x): if s is None: return func(x) return func(s, x) c = uniform(1, 5) expr = fn(c*exp_polar(I*pi)) - fn(c*exp_polar(-I*pi)) eps = 1e-15 expr2 = fn(-c + eps*I) - fn(-c - eps*I) return abs(expr.n() - expr2.n()).n() < 1e-10 def test_ei(): assert Ei(0) is S.NegativeInfinity assert Ei(oo) is S.Infinity assert Ei(-oo) is S.Zero assert tn_branch(Ei) assert mytd(Ei(x), exp(x)/x, x) assert mytn(Ei(x), Ei(x).rewrite(uppergamma), -uppergamma(0, x*polar_lift(-1)) - I*pi, x) assert mytn(Ei(x), Ei(x).rewrite(expint), -expint(1, x*polar_lift(-1)) - I*pi, x) assert Ei(x).rewrite(expint).rewrite(Ei) == Ei(x) assert Ei(x*exp_polar(2*I*pi)) == Ei(x) + 2*I*pi assert Ei(x*exp_polar(-2*I*pi)) == Ei(x) - 2*I*pi assert mytn(Ei(x), Ei(x).rewrite(Shi), Chi(x) + Shi(x), x) assert mytn(Ei(x*polar_lift(I)), Ei(x*polar_lift(I)).rewrite(Si), Ci(x) + I*Si(x) + I*pi/2, x) assert Ei(log(x)).rewrite(li) == li(x) assert Ei(2*log(x)).rewrite(li) == li(x**2) assert gruntz(Ei(x+exp(-x))*exp(-x)*x, x, oo) == 1 assert Ei(x).series(x) == EulerGamma + log(x) + x + x**2/4 + \ x**3/18 + x**4/96 + x**5/600 + O(x**6) assert Ei(x).series(x, 1, 3) == Ei(1) + E*(x - 1) + O((x - 1)**3, (x, 1)) assert str(Ei(cos(2)).evalf(n=10)) == '-0.6760647401' raises(ArgumentIndexError, lambda: Ei(x).fdiff(2)) def test_expint(): assert mytn(expint(x, y), expint(x, y).rewrite(uppergamma), y**(x - 1)*uppergamma(1 - x, y), x) assert mytd( expint(x, y), -y**(x - 1)*meijerg([], [1, 1], [0, 0, 1 - x], [], y), x) assert mytd(expint(x, y), -expint(x - 1, y), y) assert mytn(expint(1, x), expint(1, x).rewrite(Ei), -Ei(x*polar_lift(-1)) + I*pi, x) assert expint(-4, x) == exp(-x)/x + 4*exp(-x)/x**2 + 12*exp(-x)/x**3 \ + 24*exp(-x)/x**4 + 24*exp(-x)/x**5 assert expint(Rational(-3, 2), x) == \ exp(-x)/x + 3*exp(-x)/(2*x**2) + 3*sqrt(pi)*erfc(sqrt(x))/(4*x**S('5/2')) assert tn_branch(expint, 1) assert tn_branch(expint, 2) assert tn_branch(expint, 3) assert tn_branch(expint, 1.7) assert tn_branch(expint, pi) assert expint(y, x*exp_polar(2*I*pi)) == \ x**(y - 1)*(exp(2*I*pi*y) - 1)*gamma(-y + 1) + expint(y, x) assert expint(y, x*exp_polar(-2*I*pi)) == \ x**(y - 1)*(exp(-2*I*pi*y) - 1)*gamma(-y + 1) + expint(y, x) assert expint(2, x*exp_polar(2*I*pi)) == 2*I*pi*x + expint(2, x) assert expint(2, x*exp_polar(-2*I*pi)) == -2*I*pi*x + expint(2, x) assert expint(1, x).rewrite(Ei).rewrite(expint) == expint(1, x) assert expint(x, y).rewrite(Ei) == expint(x, y) assert expint(x, y).rewrite(Ci) == expint(x, y) assert mytn(E1(x), E1(x).rewrite(Shi), Shi(x) - Chi(x), x) assert mytn(E1(polar_lift(I)*x), E1(polar_lift(I)*x).rewrite(Si), -Ci(x) + I*Si(x) - I*pi/2, x) assert mytn(expint(2, x), expint(2, x).rewrite(Ei).rewrite(expint), -x*E1(x) + exp(-x), x) assert mytn(expint(3, x), expint(3, x).rewrite(Ei).rewrite(expint), x**2*E1(x)/2 + (1 - x)*exp(-x)/2, x) assert expint(Rational(3, 2), z).nseries(z) == \ 2 + 2*z - z**2/3 + z**3/15 - z**4/84 + z**5/540 - \ 2*sqrt(pi)*sqrt(z) + O(z**6) assert E1(z).series(z) == -EulerGamma - log(z) + z - \ z**2/4 + z**3/18 - z**4/96 + z**5/600 + O(z**6) assert expint(4, z).series(z) == Rational(1, 3) - z/2 + z**2/2 + \ z**3*(log(z)/6 - Rational(11, 36) + EulerGamma/6 - I*pi/6) - z**4/24 + \ z**5/240 + O(z**6) assert expint(z, y).series(z, 0, 2) == exp(-y)/y - z*meijerg(((), (1, 1)), ((0, 0, 1), ()), y)/y + O(z**2) raises(ArgumentIndexError, lambda: expint(x, y).fdiff(3)) neg = Symbol('neg', negative=True) assert Ei(neg).rewrite(Si) == Shi(neg) + Chi(neg) - I*pi def test__eis(): assert _eis(z).diff(z) == -_eis(z) + 1/z assert _eis(1/z).series(z) == \ z + z**2 + 2*z**3 + 6*z**4 + 24*z**5 + O(z**6) assert Ei(z).rewrite('tractable') == exp(z)*_eis(z) assert li(z).rewrite('tractable') == z*_eis(log(z)) assert _eis(z).rewrite('intractable') == exp(-z)*Ei(z) assert expand(li(z).rewrite('tractable').diff(z).rewrite('intractable')) \ == li(z).diff(z) assert expand(Ei(z).rewrite('tractable').diff(z).rewrite('intractable')) \ == Ei(z).diff(z) assert _eis(z).series(z, n=3) == EulerGamma + log(z) + z*(-log(z) - \ EulerGamma + 1) + z**2*(log(z)/2 - Rational(3, 4) + EulerGamma/2) + O(z**3*log(z)) raises(ArgumentIndexError, lambda: _eis(z).fdiff(2)) def tn_arg(func): def test(arg, e1, e2): from random import uniform v = uniform(1, 5) v1 = func(arg*x).subs(x, v).n() v2 = func(e1*v + e2*1e-15).n() return abs(v1 - v2).n() < 1e-10 return test(exp_polar(I*pi/2), I, 1) and \ test(exp_polar(-I*pi/2), -I, 1) and \ test(exp_polar(I*pi), -1, I) and \ test(exp_polar(-I*pi), -1, -I) def test_li(): z = Symbol("z") zr = Symbol("z", real=True) zp = Symbol("z", positive=True) zn = Symbol("z", negative=True) assert li(0) == 0 assert li(1) is -oo assert li(oo) is oo assert isinstance(li(z), li) assert unchanged(li, -zp) assert unchanged(li, zn) assert diff(li(z), z) == 1/log(z) assert conjugate(li(z)) == li(conjugate(z)) assert conjugate(li(-zr)) == li(-zr) assert unchanged(conjugate, li(-zp)) assert unchanged(conjugate, li(zn)) assert li(z).rewrite(Li) == Li(z) + li(2) assert li(z).rewrite(Ei) == Ei(log(z)) assert li(z).rewrite(uppergamma) == (-log(1/log(z))/2 - log(-log(z)) + log(log(z))/2 - expint(1, -log(z))) assert li(z).rewrite(Si) == (-log(I*log(z)) - log(1/log(z))/2 + log(log(z))/2 + Ci(I*log(z)) + Shi(log(z))) assert li(z).rewrite(Ci) == (-log(I*log(z)) - log(1/log(z))/2 + log(log(z))/2 + Ci(I*log(z)) + Shi(log(z))) assert li(z).rewrite(Shi) == (-log(1/log(z))/2 + log(log(z))/2 + Chi(log(z)) - Shi(log(z))) assert li(z).rewrite(Chi) == (-log(1/log(z))/2 + log(log(z))/2 + Chi(log(z)) - Shi(log(z))) assert li(z).rewrite(hyper) ==(log(z)*hyper((1, 1), (2, 2), log(z)) - log(1/log(z))/2 + log(log(z))/2 + EulerGamma) assert li(z).rewrite(meijerg) == (-log(1/log(z))/2 - log(-log(z)) + log(log(z))/2 - meijerg(((), (1,)), ((0, 0), ()), -log(z))) assert gruntz(1/li(z), z, oo) == 0 raises(ArgumentIndexError, lambda: li(z).fdiff(2)) def test_Li(): assert Li(2) == 0 assert Li(oo) is oo assert isinstance(Li(z), Li) assert diff(Li(z), z) == 1/log(z) assert gruntz(1/Li(z), z, oo) == 0 assert Li(z).rewrite(li) == li(z) - li(2) raises(ArgumentIndexError, lambda: Li(z).fdiff(2)) def test_si(): assert Si(I*x) == I*Shi(x) assert Shi(I*x) == I*Si(x) assert Si(-I*x) == -I*Shi(x) assert Shi(-I*x) == -I*Si(x) assert Si(-x) == -Si(x) assert Shi(-x) == -Shi(x) assert Si(exp_polar(2*pi*I)*x) == Si(x) assert Si(exp_polar(-2*pi*I)*x) == Si(x) assert Shi(exp_polar(2*pi*I)*x) == Shi(x) assert Shi(exp_polar(-2*pi*I)*x) == Shi(x) assert Si(oo) == pi/2 assert Si(-oo) == -pi/2 assert Shi(oo) is oo assert Shi(-oo) is -oo assert mytd(Si(x), sin(x)/x, x) assert mytd(Shi(x), sinh(x)/x, x) assert mytn(Si(x), Si(x).rewrite(Ei), -I*(-Ei(x*exp_polar(-I*pi/2))/2 + Ei(x*exp_polar(I*pi/2))/2 - I*pi) + pi/2, x) assert mytn(Si(x), Si(x).rewrite(expint), -I*(-expint(1, x*exp_polar(-I*pi/2))/2 + expint(1, x*exp_polar(I*pi/2))/2) + pi/2, x) assert mytn(Shi(x), Shi(x).rewrite(Ei), Ei(x)/2 - Ei(x*exp_polar(I*pi))/2 + I*pi/2, x) assert mytn(Shi(x), Shi(x).rewrite(expint), expint(1, x)/2 - expint(1, x*exp_polar(I*pi))/2 - I*pi/2, x) assert tn_arg(Si) assert tn_arg(Shi) assert Si(x).nseries(x, n=8) == \ x - x**3/18 + x**5/600 - x**7/35280 + O(x**9) assert Shi(x).nseries(x, n=8) == \ x + x**3/18 + x**5/600 + x**7/35280 + O(x**9) assert Si(sin(x)).nseries(x, n=5) == x - 2*x**3/9 + 17*x**5/450 + O(x**6) assert Si(x).nseries(x, 1, n=3) == \ Si(1) + (x - 1)*sin(1) + (x - 1)**2*(-sin(1)/2 + cos(1)/2) + O((x - 1)**3, (x, 1)) t = Symbol('t', Dummy=True) assert Si(x).rewrite(sinc) == Integral(sinc(t), (t, 0, x)) def test_ci(): m1 = exp_polar(I*pi) m1_ = exp_polar(-I*pi) pI = exp_polar(I*pi/2) mI = exp_polar(-I*pi/2) assert Ci(m1*x) == Ci(x) + I*pi assert Ci(m1_*x) == Ci(x) - I*pi assert Ci(pI*x) == Chi(x) + I*pi/2 assert Ci(mI*x) == Chi(x) - I*pi/2 assert Chi(m1*x) == Chi(x) + I*pi assert Chi(m1_*x) == Chi(x) - I*pi assert Chi(pI*x) == Ci(x) + I*pi/2 assert Chi(mI*x) == Ci(x) - I*pi/2 assert Ci(exp_polar(2*I*pi)*x) == Ci(x) + 2*I*pi assert Chi(exp_polar(-2*I*pi)*x) == Chi(x) - 2*I*pi assert Chi(exp_polar(2*I*pi)*x) == Chi(x) + 2*I*pi assert Ci(exp_polar(-2*I*pi)*x) == Ci(x) - 2*I*pi assert Ci(oo) == 0 assert Ci(-oo) == I*pi assert Chi(oo) is oo assert Chi(-oo) is oo assert mytd(Ci(x), cos(x)/x, x) assert mytd(Chi(x), cosh(x)/x, x) assert mytn(Ci(x), Ci(x).rewrite(Ei), Ei(x*exp_polar(-I*pi/2))/2 + Ei(x*exp_polar(I*pi/2))/2, x) assert mytn(Chi(x), Chi(x).rewrite(Ei), Ei(x)/2 + Ei(x*exp_polar(I*pi))/2 - I*pi/2, x) assert tn_arg(Ci) assert tn_arg(Chi) from sympy import O, EulerGamma, log, limit assert Ci(x).nseries(x, n=4) == \ EulerGamma + log(x) - x**2/4 + x**4/96 + O(x**5) assert Chi(x).nseries(x, n=4) == \ EulerGamma + log(x) + x**2/4 + x**4/96 + O(x**5) assert limit(log(x) - Ci(2*x), x, 0) == -log(2) - EulerGamma assert Ci(x).rewrite(uppergamma) == -expint(1, x*exp_polar(-I*pi/2))/2 -\ expint(1, x*exp_polar(I*pi/2))/2 assert Ci(x).rewrite(expint) == -expint(1, x*exp_polar(-I*pi/2))/2 -\ expint(1, x*exp_polar(I*pi/2))/2 raises(ArgumentIndexError, lambda: Ci(x).fdiff(2)) def test_fresnel(): assert fresnels(0) == 0 assert fresnels(oo) == S.Half assert fresnels(-oo) == Rational(-1, 2) assert fresnels(I*oo) == -I*S.Half assert unchanged(fresnels, z) assert fresnels(-z) == -fresnels(z) assert fresnels(I*z) == -I*fresnels(z) assert fresnels(-I*z) == I*fresnels(z) assert conjugate(fresnels(z)) == fresnels(conjugate(z)) assert fresnels(z).diff(z) == sin(pi*z**2/2) assert fresnels(z).rewrite(erf) == (S.One + I)/4 * ( erf((S.One + I)/2*sqrt(pi)*z) - I*erf((S.One - I)/2*sqrt(pi)*z)) assert fresnels(z).rewrite(hyper) == \ pi*z**3/6 * hyper([Rational(3, 4)], [Rational(3, 2), Rational(7, 4)], -pi**2*z**4/16) assert fresnels(z).series(z, n=15) == \ pi*z**3/6 - pi**3*z**7/336 + pi**5*z**11/42240 + O(z**15) assert fresnels(w).is_extended_real is True assert fresnels(w).is_finite is True assert fresnels(z).is_extended_real is None assert fresnels(z).is_finite is None assert fresnels(z).as_real_imag() == (fresnels(re(z) - I*im(z))/2 + fresnels(re(z) + I*im(z))/2, -I*(-fresnels(re(z) - I*im(z)) + fresnels(re(z) + I*im(z)))/2) assert fresnels(z).as_real_imag(deep=False) == (fresnels(re(z) - I*im(z))/2 + fresnels(re(z) + I*im(z))/2, -I*(-fresnels(re(z) - I*im(z)) + fresnels(re(z) + I*im(z)))/2) assert fresnels(w).as_real_imag() == (fresnels(w), 0) assert fresnels(w).as_real_imag(deep=True) == (fresnels(w), 0) assert fresnels(2 + 3*I).as_real_imag() == ( fresnels(2 + 3*I)/2 + fresnels(2 - 3*I)/2, -I*(fresnels(2 + 3*I) - fresnels(2 - 3*I))/2 ) assert expand_func(integrate(fresnels(z), z)) == \ z*fresnels(z) + cos(pi*z**2/2)/pi assert fresnels(z).rewrite(meijerg) == sqrt(2)*pi*z**Rational(9, 4) * \ meijerg(((), (1,)), ((Rational(3, 4),), (Rational(1, 4), 0)), -pi**2*z**4/16)/(2*(-z)**Rational(3, 4)*(z**2)**Rational(3, 4)) assert fresnelc(0) == 0 assert fresnelc(oo) == S.Half assert fresnelc(-oo) == Rational(-1, 2) assert fresnelc(I*oo) == I*S.Half assert unchanged(fresnelc, z) assert fresnelc(-z) == -fresnelc(z) assert fresnelc(I*z) == I*fresnelc(z) assert fresnelc(-I*z) == -I*fresnelc(z) assert conjugate(fresnelc(z)) == fresnelc(conjugate(z)) assert fresnelc(z).diff(z) == cos(pi*z**2/2) assert fresnelc(z).rewrite(erf) == (S.One - I)/4 * ( erf((S.One + I)/2*sqrt(pi)*z) + I*erf((S.One - I)/2*sqrt(pi)*z)) assert fresnelc(z).rewrite(hyper) == \ z * hyper([Rational(1, 4)], [S.Half, Rational(5, 4)], -pi**2*z**4/16) assert fresnelc(w).is_extended_real is True assert fresnelc(z).as_real_imag() == \ (fresnelc(re(z) - I*im(z))/2 + fresnelc(re(z) + I*im(z))/2, -I*(-fresnelc(re(z) - I*im(z)) + fresnelc(re(z) + I*im(z)))/2) assert fresnelc(z).as_real_imag(deep=False) == \ (fresnelc(re(z) - I*im(z))/2 + fresnelc(re(z) + I*im(z))/2, -I*(-fresnelc(re(z) - I*im(z)) + fresnelc(re(z) + I*im(z)))/2) assert fresnelc(2 + 3*I).as_real_imag() == ( fresnelc(2 - 3*I)/2 + fresnelc(2 + 3*I)/2, -I*(fresnelc(2 + 3*I) - fresnelc(2 - 3*I))/2 ) assert expand_func(integrate(fresnelc(z), z)) == \ z*fresnelc(z) - sin(pi*z**2/2)/pi assert fresnelc(z).rewrite(meijerg) == sqrt(2)*pi*z**Rational(3, 4) * \ meijerg(((), (1,)), ((Rational(1, 4),), (Rational(3, 4), 0)), -pi**2*z**4/16)/(2*(-z)**Rational(1, 4)*(z**2)**Rational(1, 4)) from sympy.testing.randtest import verify_numerically verify_numerically(re(fresnels(z)), fresnels(z).as_real_imag()[0], z) verify_numerically(im(fresnels(z)), fresnels(z).as_real_imag()[1], z) verify_numerically(fresnels(z), fresnels(z).rewrite(hyper), z) verify_numerically(fresnels(z), fresnels(z).rewrite(meijerg), z) verify_numerically(re(fresnelc(z)), fresnelc(z).as_real_imag()[0], z) verify_numerically(im(fresnelc(z)), fresnelc(z).as_real_imag()[1], z) verify_numerically(fresnelc(z), fresnelc(z).rewrite(hyper), z) verify_numerically(fresnelc(z), fresnelc(z).rewrite(meijerg), z) raises(ArgumentIndexError, lambda: fresnels(z).fdiff(2)) raises(ArgumentIndexError, lambda: fresnelc(z).fdiff(2)) assert fresnels(x).taylor_term(-1, x) is S.Zero assert fresnelc(x).taylor_term(-1, x) is S.Zero assert fresnelc(x).taylor_term(1, x) == -pi**2*x**5/40 @slow def test_fresnel_series(): assert fresnelc(z).series(z, n=15) == \ z - pi**2*z**5/40 + pi**4*z**9/3456 - pi**6*z**13/599040 + O(z**15) # issues 6510, 10102 fs = (S.Half - sin(pi*z**2/2)/(pi**2*z**3) + (-1/(pi*z) + 3/(pi**3*z**5))*cos(pi*z**2/2)) fc = (S.Half - cos(pi*z**2/2)/(pi**2*z**3) + (1/(pi*z) - 3/(pi**3*z**5))*sin(pi*z**2/2)) assert fresnels(z).series(z, oo) == fs + O(z**(-6), (z, oo)) assert fresnelc(z).series(z, oo) == fc + O(z**(-6), (z, oo)) assert (fresnels(z).series(z, -oo) + fs.subs(z, -z)).expand().is_Order assert (fresnelc(z).series(z, -oo) + fc.subs(z, -z)).expand().is_Order assert (fresnels(1/z).series(z) - fs.subs(z, 1/z)).expand().is_Order assert (fresnelc(1/z).series(z) - fc.subs(z, 1/z)).expand().is_Order assert ((2*fresnels(3*z)).series(z, oo) - 2*fs.subs(z, 3*z)).expand().is_Order assert ((3*fresnelc(2*z)).series(z, oo) - 3*fc.subs(z, 2*z)).expand().is_Order
6d29da93ae00a3db1ac8fa899f42ae256610bfd831cad2a3dcfef1189bfcff93
from __future__ import print_function, division from sympy import zeros, eye, Symbol, solve_linear_system N = 8 M = zeros(N, N + 1) M[:, :N] = eye(N) S = [Symbol('A%i' % i) for i in range(N)] def timeit_linsolve_trivial(): solve_linear_system(M, *S)
0d74975b455e3f90cf72c9cc2d41e4f33f2a33cd77d2ab2f6d8a8058f6df02a6
from .diophantine import diophantine, classify_diop __all__ = [ 'diophantine', 'classify_diop' ]
3041ff056148a8e9f7e941b825f252df4755b6769757172a18759c1f55594410
from __future__ import print_function, division from sympy.core.add import Add from sympy.core.compatibility import as_int, is_sequence from sympy.core.exprtools import factor_terms from sympy.core.function import _mexpand from sympy.core.mul import Mul from sympy.core.numbers import Rational from sympy.core.numbers import igcdex, ilcm, igcd from sympy.core.power import integer_nthroot, isqrt from sympy.core.relational import Eq from sympy.core.singleton import S from sympy.core.symbol import Symbol, symbols from sympy.core.sympify import _sympify from sympy.functions.elementary.complexes import sign from sympy.functions.elementary.integers import floor from sympy.functions.elementary.miscellaneous import sqrt from sympy.matrices.dense import MutableDenseMatrix as Matrix from sympy.ntheory.factor_ import ( divisors, factorint, multiplicity, perfect_power) from sympy.ntheory.generate import nextprime from sympy.ntheory.primetest import is_square, isprime from sympy.ntheory.residue_ntheory import sqrt_mod from sympy.polys.polyerrors import GeneratorsNeeded from sympy.polys.polytools import Poly, factor_list from sympy.simplify.simplify import signsimp from sympy.solvers.solvers import check_assumptions from sympy.solvers.solveset import solveset_real from sympy.utilities import default_sort_key, numbered_symbols from sympy.utilities.misc import filldedent # these are imported with 'from sympy.solvers.diophantine import * __all__ = ['diophantine', 'classify_diop'] # these types are known (but not necessarily handled) diop_known = { "binary_quadratic", "cubic_thue", "general_pythagorean", "general_sum_of_even_powers", "general_sum_of_squares", "homogeneous_general_quadratic", "homogeneous_ternary_quadratic", "homogeneous_ternary_quadratic_normal", "inhomogeneous_general_quadratic", "inhomogeneous_ternary_quadratic", "linear", "univariate"} def _is_int(i): try: as_int(i) return True except ValueError: pass def _sorted_tuple(*i): return tuple(sorted(i)) def _remove_gcd(*x): try: g = igcd(*x) except ValueError: fx = list(filter(None, x)) if len(fx) < 2: return x g = igcd(*[i.as_content_primitive()[0] for i in fx]) except TypeError: raise TypeError('_remove_gcd(a,b,c) or _remove_gcd(*container)') if g == 1: return x return tuple([i//g for i in x]) def _rational_pq(a, b): # return `(numer, denom)` for a/b; sign in numer and gcd removed return _remove_gcd(sign(b)*a, abs(b)) def _nint_or_floor(p, q): # return nearest int to p/q; in case of tie return floor(p/q) w, r = divmod(p, q) if abs(r) <= abs(q)//2: return w return w + 1 def _odd(i): return i % 2 != 0 def _even(i): return i % 2 == 0 def diophantine(eq, param=symbols("t", integer=True), syms=None, permute=False): """ Simplify the solution procedure of diophantine equation ``eq`` by converting it into a product of terms which should equal zero. For example, when solving, `x^2 - y^2 = 0` this is treated as `(x + y)(x - y) = 0` and `x + y = 0` and `x - y = 0` are solved independently and combined. Each term is solved by calling ``diop_solve()``. (Although it is possible to call ``diop_solve()`` directly, one must be careful to pass an equation in the correct form and to interpret the output correctly; ``diophantine()`` is the public-facing function to use in general.) Output of ``diophantine()`` is a set of tuples. The elements of the tuple are the solutions for each variable in the equation and are arranged according to the alphabetic ordering of the variables. e.g. For an equation with two variables, `a` and `b`, the first element of the tuple is the solution for `a` and the second for `b`. Usage ===== ``diophantine(eq, t, syms)``: Solve the diophantine equation ``eq``. ``t`` is the optional parameter to be used by ``diop_solve()``. ``syms`` is an optional list of symbols which determines the order of the elements in the returned tuple. By default, only the base solution is returned. If ``permute`` is set to True then permutations of the base solution and/or permutations of the signs of the values will be returned when applicable. >>> from sympy.solvers.diophantine import diophantine >>> from sympy.abc import a, b >>> eq = a**4 + b**4 - (2**4 + 3**4) >>> diophantine(eq) {(2, 3)} >>> diophantine(eq, permute=True) {(-3, -2), (-3, 2), (-2, -3), (-2, 3), (2, -3), (2, 3), (3, -2), (3, 2)} Details ======= ``eq`` should be an expression which is assumed to be zero. ``t`` is the parameter to be used in the solution. Examples ======== >>> from sympy.abc import x, y, z >>> diophantine(x**2 - y**2) {(t_0, -t_0), (t_0, t_0)} >>> diophantine(x*(2*x + 3*y - z)) {(0, n1, n2), (t_0, t_1, 2*t_0 + 3*t_1)} >>> diophantine(x**2 + 3*x*y + 4*x) {(0, n1), (3*t_0 - 4, -t_0)} See Also ======== diop_solve() sympy.utilities.iterables.permute_signs sympy.utilities.iterables.signed_permutations """ from sympy.utilities.iterables import ( subsets, permute_signs, signed_permutations) eq = _sympify(eq) if isinstance(eq, Eq): eq = eq.lhs - eq.rhs try: var = list(eq.expand(force=True).free_symbols) var.sort(key=default_sort_key) if syms: if not is_sequence(syms): raise TypeError( 'syms should be given as a sequence, e.g. a list') syms = [i for i in syms if i in var] if syms != var: dict_sym_index = dict(zip(syms, range(len(syms)))) return {tuple([t[dict_sym_index[i]] for i in var]) for t in diophantine(eq, param, permute=permute)} n, d = eq.as_numer_denom() if n.is_number: return set() if not d.is_number: dsol = diophantine(d) good = diophantine(n) - dsol return {s for s in good if _mexpand(d.subs(zip(var, s)))} else: eq = n eq = factor_terms(eq) assert not eq.is_number eq = eq.as_independent(*var, as_Add=False)[1] p = Poly(eq) assert not any(g.is_number for g in p.gens) eq = p.as_expr() assert eq.is_polynomial() except (GeneratorsNeeded, AssertionError): raise TypeError(filldedent(''' Equation should be a polynomial with Rational coefficients.''')) # permute only sign do_permute_signs = False # permute sign and values do_permute_signs_var = False # permute few signs permute_few_signs = False try: # if we know that factoring should not be attempted, skip # the factoring step v, c, t = classify_diop(eq) # check for permute sign if permute: len_var = len(v) permute_signs_for = [ 'general_sum_of_squares', 'general_sum_of_even_powers'] permute_signs_check = [ 'homogeneous_ternary_quadratic', 'homogeneous_ternary_quadratic_normal', 'binary_quadratic'] if t in permute_signs_for: do_permute_signs_var = True elif t in permute_signs_check: # if all the variables in eq have even powers # then do_permute_sign = True if len_var == 3: var_mul = list(subsets(v, 2)) # here var_mul is like [(x, y), (x, z), (y, z)] xy_coeff = True x_coeff = True var1_mul_var2 = map(lambda a: a[0]*a[1], var_mul) # if coeff(y*z), coeff(y*x), coeff(x*z) is not 0 then # `xy_coeff` => True and do_permute_sign => False. # Means no permuted solution. for v1_mul_v2 in var1_mul_var2: try: coeff = c[v1_mul_v2] except KeyError: coeff = 0 xy_coeff = bool(xy_coeff) and bool(coeff) var_mul = list(subsets(v, 1)) # here var_mul is like [(x,), (y, )] for v1 in var_mul: try: coeff = c[v1[0]] except KeyError: coeff = 0 x_coeff = bool(x_coeff) and bool(coeff) if not any([xy_coeff, x_coeff]): # means only x**2, y**2, z**2, const is present do_permute_signs = True elif not x_coeff: permute_few_signs = True elif len_var == 2: var_mul = list(subsets(v, 2)) # here var_mul is like [(x, y)] xy_coeff = True x_coeff = True var1_mul_var2 = map(lambda x: x[0]*x[1], var_mul) for v1_mul_v2 in var1_mul_var2: try: coeff = c[v1_mul_v2] except KeyError: coeff = 0 xy_coeff = bool(xy_coeff) and bool(coeff) var_mul = list(subsets(v, 1)) # here var_mul is like [(x,), (y, )] for v1 in var_mul: try: coeff = c[v1[0]] except KeyError: coeff = 0 x_coeff = bool(x_coeff) and bool(coeff) if not any([xy_coeff, x_coeff]): # means only x**2, y**2 and const is present # so we can get more soln by permuting this soln. do_permute_signs = True elif not x_coeff: # when coeff(x), coeff(y) is not present then signs of # x, y can be permuted such that their sign are same # as sign of x*y. # e.g 1. (x_val,y_val)=> (x_val,y_val), (-x_val,-y_val) # 2. (-x_vall, y_val)=> (-x_val,y_val), (x_val,-y_val) permute_few_signs = True if t == 'general_sum_of_squares': # trying to factor such expressions will sometimes hang terms = [(eq, 1)] else: raise TypeError except (TypeError, NotImplementedError): fl = factor_list(eq) if fl[0].is_Rational and fl[0] != 1: return diophantine(eq/fl[0], param=param, syms=syms, permute=permute) terms = fl[1] sols = set([]) for term in terms: base, _ = term var_t, _, eq_type = classify_diop(base, _dict=False) _, base = signsimp(base, evaluate=False).as_coeff_Mul() solution = diop_solve(base, param) if eq_type in [ "linear", "homogeneous_ternary_quadratic", "homogeneous_ternary_quadratic_normal", "general_pythagorean"]: sols.add(merge_solution(var, var_t, solution)) elif eq_type in [ "binary_quadratic", "general_sum_of_squares", "general_sum_of_even_powers", "univariate"]: for sol in solution: sols.add(merge_solution(var, var_t, sol)) else: raise NotImplementedError('unhandled type: %s' % eq_type) # remove null merge results if () in sols: sols.remove(()) null = tuple([0]*len(var)) # if there is no solution, return trivial solution if not sols and eq.subs(zip(var, null)).is_zero: sols.add(null) final_soln = set([]) for sol in sols: if all(_is_int(s) for s in sol): if do_permute_signs: permuted_sign = set(permute_signs(sol)) final_soln.update(permuted_sign) elif permute_few_signs: lst = list(permute_signs(sol)) lst = list(filter(lambda x: x[0]*x[1] == sol[1]*sol[0], lst)) permuted_sign = set(lst) final_soln.update(permuted_sign) elif do_permute_signs_var: permuted_sign_var = set(signed_permutations(sol)) final_soln.update(permuted_sign_var) else: final_soln.add(sol) else: final_soln.add(sol) return final_soln def merge_solution(var, var_t, solution): """ This is used to construct the full solution from the solutions of sub equations. For example when solving the equation `(x - y)(x^2 + y^2 - z^2) = 0`, solutions for each of the equations `x - y = 0` and `x^2 + y^2 - z^2` are found independently. Solutions for `x - y = 0` are `(x, y) = (t, t)`. But we should introduce a value for z when we output the solution for the original equation. This function converts `(t, t)` into `(t, t, n_{1})` where `n_{1}` is an integer parameter. """ sol = [] if None in solution: return () solution = iter(solution) params = numbered_symbols("n", integer=True, start=1) for v in var: if v in var_t: sol.append(next(solution)) else: sol.append(next(params)) for val, symb in zip(sol, var): if check_assumptions(val, **symb.assumptions0) is False: return tuple() return tuple(sol) def diop_solve(eq, param=symbols("t", integer=True)): """ Solves the diophantine equation ``eq``. Unlike ``diophantine()``, factoring of ``eq`` is not attempted. Uses ``classify_diop()`` to determine the type of the equation and calls the appropriate solver function. Use of ``diophantine()`` is recommended over other helper functions. ``diop_solve()`` can return either a set or a tuple depending on the nature of the equation. Usage ===== ``diop_solve(eq, t)``: Solve diophantine equation, ``eq`` using ``t`` as a parameter if needed. Details ======= ``eq`` should be an expression which is assumed to be zero. ``t`` is a parameter to be used in the solution. Examples ======== >>> from sympy.solvers.diophantine.diophantine import diop_solve >>> from sympy.abc import x, y, z, w >>> diop_solve(2*x + 3*y - 5) (3*t_0 - 5, 5 - 2*t_0) >>> diop_solve(4*x + 3*y - 4*z + 5) (t_0, 8*t_0 + 4*t_1 + 5, 7*t_0 + 3*t_1 + 5) >>> diop_solve(x + 3*y - 4*z + w - 6) (t_0, t_0 + t_1, 6*t_0 + 5*t_1 + 4*t_2 - 6, 5*t_0 + 4*t_1 + 3*t_2 - 6) >>> diop_solve(x**2 + y**2 - 5) {(-2, -1), (-2, 1), (-1, -2), (-1, 2), (1, -2), (1, 2), (2, -1), (2, 1)} See Also ======== diophantine() """ var, coeff, eq_type = classify_diop(eq, _dict=False) if eq_type == "linear": return _diop_linear(var, coeff, param) elif eq_type == "binary_quadratic": return _diop_quadratic(var, coeff, param) elif eq_type == "homogeneous_ternary_quadratic": x_0, y_0, z_0 = _diop_ternary_quadratic(var, coeff) return _parametrize_ternary_quadratic( (x_0, y_0, z_0), var, coeff) elif eq_type == "homogeneous_ternary_quadratic_normal": x_0, y_0, z_0 = _diop_ternary_quadratic_normal(var, coeff) return _parametrize_ternary_quadratic( (x_0, y_0, z_0), var, coeff) elif eq_type == "general_pythagorean": return _diop_general_pythagorean(var, coeff, param) elif eq_type == "univariate": return set([(int(i),) for i in solveset_real( eq, var[0]).intersect(S.Integers)]) elif eq_type == "general_sum_of_squares": return _diop_general_sum_of_squares(var, -int(coeff[1]), limit=S.Infinity) elif eq_type == "general_sum_of_even_powers": for k in coeff.keys(): if k.is_Pow and coeff[k]: p = k.exp return _diop_general_sum_of_even_powers(var, p, -int(coeff[1]), limit=S.Infinity) if eq_type is not None and eq_type not in diop_known: raise ValueError(filldedent(''' Alhough this type of equation was identified, it is not yet handled. It should, however, be listed in `diop_known` at the top of this file. Developers should see comments at the end of `classify_diop`. ''')) # pragma: no cover else: raise NotImplementedError( 'No solver has been written for %s.' % eq_type) def classify_diop(eq, _dict=True): # docstring supplied externally try: var = list(eq.free_symbols) assert var except (AttributeError, AssertionError): raise ValueError('equation should have 1 or more free symbols') var.sort(key=default_sort_key) eq = eq.expand(force=True) coeff = eq.as_coefficients_dict() if not all(_is_int(c) for c in coeff.values()): raise TypeError("Coefficients should be Integers") diop_type = None total_degree = Poly(eq).total_degree() homogeneous = 1 not in coeff if total_degree == 1: diop_type = "linear" elif len(var) == 1: diop_type = "univariate" elif total_degree == 2 and len(var) == 2: diop_type = "binary_quadratic" elif total_degree == 2 and len(var) == 3 and homogeneous: if set(coeff) & set(var): diop_type = "inhomogeneous_ternary_quadratic" else: nonzero = [k for k in coeff if coeff[k]] if len(nonzero) == 3 and all(i**2 in nonzero for i in var): diop_type = "homogeneous_ternary_quadratic_normal" else: diop_type = "homogeneous_ternary_quadratic" elif total_degree == 2 and len(var) >= 3: if set(coeff) & set(var): diop_type = "inhomogeneous_general_quadratic" else: # there may be Pow keys like x**2 or Mul keys like x*y if any(k.is_Mul for k in coeff): # cross terms if not homogeneous: diop_type = "inhomogeneous_general_quadratic" else: diop_type = "homogeneous_general_quadratic" else: # all squares: x**2 + y**2 + ... + constant if all(coeff[k] == 1 for k in coeff if k != 1): diop_type = "general_sum_of_squares" elif all(is_square(abs(coeff[k])) for k in coeff): if abs(sum(sign(coeff[k]) for k in coeff)) == \ len(var) - 2: # all but one has the same sign # e.g. 4*x**2 + y**2 - 4*z**2 diop_type = "general_pythagorean" elif total_degree == 3 and len(var) == 2: diop_type = "cubic_thue" elif (total_degree > 3 and total_degree % 2 == 0 and all(k.is_Pow and k.exp == total_degree for k in coeff if k != 1)): if all(coeff[k] == 1 for k in coeff if k != 1): diop_type = 'general_sum_of_even_powers' if diop_type is not None: return var, dict(coeff) if _dict else coeff, diop_type # new diop type instructions # -------------------------- # if this error raises and the equation *can* be classified, # * it should be identified in the if-block above # * the type should be added to the diop_known # if a solver can be written for it, # * a dedicated handler should be written (e.g. diop_linear) # * it should be passed to that handler in diop_solve raise NotImplementedError(filldedent(''' This equation is not yet recognized or else has not been simplified sufficiently to put it in a form recognized by diop_classify().''')) classify_diop.func_doc = ( # type: ignore ''' Helper routine used by diop_solve() to find information about ``eq``. Returns a tuple containing the type of the diophantine equation along with the variables (free symbols) and their coefficients. Variables are returned as a list and coefficients are returned as a dict with the key being the respective term and the constant term is keyed to 1. The type is one of the following: * %s Usage ===== ``classify_diop(eq)``: Return variables, coefficients and type of the ``eq``. Details ======= ``eq`` should be an expression which is assumed to be zero. ``_dict`` is for internal use: when True (default) a dict is returned, otherwise a defaultdict which supplies 0 for missing keys is returned. Examples ======== >>> from sympy.solvers.diophantine import classify_diop >>> from sympy.abc import x, y, z, w, t >>> classify_diop(4*x + 6*y - 4) ([x, y], {1: -4, x: 4, y: 6}, 'linear') >>> classify_diop(x + 3*y -4*z + 5) ([x, y, z], {1: 5, x: 1, y: 3, z: -4}, 'linear') >>> classify_diop(x**2 + y**2 - x*y + x + 5) ([x, y], {1: 5, x: 1, x**2: 1, y**2: 1, x*y: -1}, 'binary_quadratic') ''' % ('\n * '.join(sorted(diop_known)))) def diop_linear(eq, param=symbols("t", integer=True)): """ Solves linear diophantine equations. A linear diophantine equation is an equation of the form `a_{1}x_{1} + a_{2}x_{2} + .. + a_{n}x_{n} = 0` where `a_{1}, a_{2}, ..a_{n}` are integer constants and `x_{1}, x_{2}, ..x_{n}` are integer variables. Usage ===== ``diop_linear(eq)``: Returns a tuple containing solutions to the diophantine equation ``eq``. Values in the tuple is arranged in the same order as the sorted variables. Details ======= ``eq`` is a linear diophantine equation which is assumed to be zero. ``param`` is the parameter to be used in the solution. Examples ======== >>> from sympy.solvers.diophantine.diophantine import diop_linear >>> from sympy.abc import x, y, z, t >>> diop_linear(2*x - 3*y - 5) # solves equation 2*x - 3*y - 5 == 0 (3*t_0 - 5, 2*t_0 - 5) Here x = -3*t_0 - 5 and y = -2*t_0 - 5 >>> diop_linear(2*x - 3*y - 4*z -3) (t_0, 2*t_0 + 4*t_1 + 3, -t_0 - 3*t_1 - 3) See Also ======== diop_quadratic(), diop_ternary_quadratic(), diop_general_pythagorean(), diop_general_sum_of_squares() """ var, coeff, diop_type = classify_diop(eq, _dict=False) if diop_type == "linear": return _diop_linear(var, coeff, param) def _diop_linear(var, coeff, param): """ Solves diophantine equations of the form: a_0*x_0 + a_1*x_1 + ... + a_n*x_n == c Note that no solution exists if gcd(a_0, ..., a_n) doesn't divide c. """ if 1 in coeff: # negate coeff[] because input is of the form: ax + by + c == 0 # but is used as: ax + by == -c c = -coeff[1] else: c = 0 # Some solutions will have multiple free variables in their solutions. if param is None: params = [symbols('t')]*len(var) else: temp = str(param) + "_%i" params = [symbols(temp % i, integer=True) for i in range(len(var))] if len(var) == 1: q, r = divmod(c, coeff[var[0]]) if not r: return (q,) else: return (None,) ''' base_solution_linear() can solve diophantine equations of the form: a*x + b*y == c We break down multivariate linear diophantine equations into a series of bivariate linear diophantine equations which can then be solved individually by base_solution_linear(). Consider the following: a_0*x_0 + a_1*x_1 + a_2*x_2 == c which can be re-written as: a_0*x_0 + g_0*y_0 == c where g_0 == gcd(a_1, a_2) and y == (a_1*x_1)/g_0 + (a_2*x_2)/g_0 This leaves us with two binary linear diophantine equations. For the first equation: a == a_0 b == g_0 c == c For the second: a == a_1/g_0 b == a_2/g_0 c == the solution we find for y_0 in the first equation. The arrays A and B are the arrays of integers used for 'a' and 'b' in each of the n-1 bivariate equations we solve. ''' A = [coeff[v] for v in var] B = [] if len(var) > 2: B.append(igcd(A[-2], A[-1])) A[-2] = A[-2] // B[0] A[-1] = A[-1] // B[0] for i in range(len(A) - 3, 0, -1): gcd = igcd(B[0], A[i]) B[0] = B[0] // gcd A[i] = A[i] // gcd B.insert(0, gcd) B.append(A[-1]) ''' Consider the trivariate linear equation: 4*x_0 + 6*x_1 + 3*x_2 == 2 This can be re-written as: 4*x_0 + 3*y_0 == 2 where y_0 == 2*x_1 + x_2 (Note that gcd(3, 6) == 3) The complete integral solution to this equation is: x_0 == 2 + 3*t_0 y_0 == -2 - 4*t_0 where 't_0' is any integer. Now that we have a solution for 'x_0', find 'x_1' and 'x_2': 2*x_1 + x_2 == -2 - 4*t_0 We can then solve for '-2' and '-4' independently, and combine the results: 2*x_1a + x_2a == -2 x_1a == 0 + t_0 x_2a == -2 - 2*t_0 2*x_1b + x_2b == -4*t_0 x_1b == 0*t_0 + t_1 x_2b == -4*t_0 - 2*t_1 ==> x_1 == t_0 + t_1 x_2 == -2 - 6*t_0 - 2*t_1 where 't_0' and 't_1' are any integers. Note that: 4*(2 + 3*t_0) + 6*(t_0 + t_1) + 3*(-2 - 6*t_0 - 2*t_1) == 2 for any integral values of 't_0', 't_1'; as required. This method is generalised for many variables, below. ''' solutions = [] for i in range(len(B)): tot_x, tot_y = [], [] for j, arg in enumerate(Add.make_args(c)): if arg.is_Integer: # example: 5 -> k = 5 k, p = arg, S.One pnew = params[0] else: # arg is a Mul or Symbol # example: 3*t_1 -> k = 3 # example: t_0 -> k = 1 k, p = arg.as_coeff_Mul() pnew = params[params.index(p) + 1] sol = sol_x, sol_y = base_solution_linear(k, A[i], B[i], pnew) if p is S.One: if None in sol: return tuple([None]*len(var)) else: # convert a + b*pnew -> a*p + b*pnew if isinstance(sol_x, Add): sol_x = sol_x.args[0]*p + sol_x.args[1] if isinstance(sol_y, Add): sol_y = sol_y.args[0]*p + sol_y.args[1] tot_x.append(sol_x) tot_y.append(sol_y) solutions.append(Add(*tot_x)) c = Add(*tot_y) solutions.append(c) if param is None: # just keep the additive constant (i.e. replace t with 0) solutions = [i.as_coeff_Add()[0] for i in solutions] return tuple(solutions) def base_solution_linear(c, a, b, t=None): """ Return the base solution for the linear equation, `ax + by = c`. Used by ``diop_linear()`` to find the base solution of a linear Diophantine equation. If ``t`` is given then the parametrized solution is returned. Usage ===== ``base_solution_linear(c, a, b, t)``: ``a``, ``b``, ``c`` are coefficients in `ax + by = c` and ``t`` is the parameter to be used in the solution. Examples ======== >>> from sympy.solvers.diophantine.diophantine import base_solution_linear >>> from sympy.abc import t >>> base_solution_linear(5, 2, 3) # equation 2*x + 3*y = 5 (-5, 5) >>> base_solution_linear(0, 5, 7) # equation 5*x + 7*y = 0 (0, 0) >>> base_solution_linear(5, 2, 3, t) # equation 2*x + 3*y = 5 (3*t - 5, 5 - 2*t) >>> base_solution_linear(0, 5, 7, t) # equation 5*x + 7*y = 0 (7*t, -5*t) """ a, b, c = _remove_gcd(a, b, c) if c == 0: if t is not None: if b < 0: t = -t return (b*t , -a*t) else: return (0, 0) else: x0, y0, d = igcdex(abs(a), abs(b)) x0 *= sign(a) y0 *= sign(b) if divisible(c, d): if t is not None: if b < 0: t = -t return (c*x0 + b*t, c*y0 - a*t) else: return (c*x0, c*y0) else: return (None, None) def divisible(a, b): """ Returns `True` if ``a`` is divisible by ``b`` and `False` otherwise. """ return not a % b def diop_quadratic(eq, param=symbols("t", integer=True)): """ Solves quadratic diophantine equations. i.e. equations of the form `Ax^2 + Bxy + Cy^2 + Dx + Ey + F = 0`. Returns a set containing the tuples `(x, y)` which contains the solutions. If there are no solutions then `(None, None)` is returned. Usage ===== ``diop_quadratic(eq, param)``: ``eq`` is a quadratic binary diophantine equation. ``param`` is used to indicate the parameter to be used in the solution. Details ======= ``eq`` should be an expression which is assumed to be zero. ``param`` is a parameter to be used in the solution. Examples ======== >>> from sympy.abc import x, y, t >>> from sympy.solvers.diophantine.diophantine import diop_quadratic >>> diop_quadratic(x**2 + y**2 + 2*x + 2*y + 2, t) {(-1, -1)} References ========== .. [1] Methods to solve Ax^2 + Bxy + Cy^2 + Dx + Ey + F = 0, [online], Available: http://www.alpertron.com.ar/METHODS.HTM .. [2] Solving the equation ax^2+ bxy + cy^2 + dx + ey + f= 0, [online], Available: http://www.jpr2718.org/ax2p.pdf See Also ======== diop_linear(), diop_ternary_quadratic(), diop_general_sum_of_squares(), diop_general_pythagorean() """ var, coeff, diop_type = classify_diop(eq, _dict=False) if diop_type == "binary_quadratic": return _diop_quadratic(var, coeff, param) def _diop_quadratic(var, coeff, t): x, y = var A = coeff[x**2] B = coeff[x*y] C = coeff[y**2] D = coeff[x] E = coeff[y] F = coeff[S.One] A, B, C, D, E, F = [as_int(i) for i in _remove_gcd(A, B, C, D, E, F)] # (1) Simple-Hyperbolic case: A = C = 0, B != 0 # In this case equation can be converted to (Bx + E)(By + D) = DE - BF # We consider two cases; DE - BF = 0 and DE - BF != 0 # More details, http://www.alpertron.com.ar/METHODS.HTM#SHyperb sol = set([]) discr = B**2 - 4*A*C if A == 0 and C == 0 and B != 0: if D*E - B*F == 0: q, r = divmod(E, B) if not r: sol.add((-q, t)) q, r = divmod(D, B) if not r: sol.add((t, -q)) else: div = divisors(D*E - B*F) div = div + [-term for term in div] for d in div: x0, r = divmod(d - E, B) if not r: q, r = divmod(D*E - B*F, d) if not r: y0, r = divmod(q - D, B) if not r: sol.add((x0, y0)) # (2) Parabolic case: B**2 - 4*A*C = 0 # There are two subcases to be considered in this case. # sqrt(c)D - sqrt(a)E = 0 and sqrt(c)D - sqrt(a)E != 0 # More Details, http://www.alpertron.com.ar/METHODS.HTM#Parabol elif discr == 0: if A == 0: s = _diop_quadratic([y, x], coeff, t) for soln in s: sol.add((soln[1], soln[0])) else: g = sign(A)*igcd(A, C) a = A // g c = C // g e = sign(B/A) sqa = isqrt(a) sqc = isqrt(c) _c = e*sqc*D - sqa*E if not _c: z = symbols("z", real=True) eq = sqa*g*z**2 + D*z + sqa*F roots = solveset_real(eq, z).intersect(S.Integers) for root in roots: ans = diop_solve(sqa*x + e*sqc*y - root) sol.add((ans[0], ans[1])) elif _is_int(c): solve_x = lambda u: -e*sqc*g*_c*t**2 - (E + 2*e*sqc*g*u)*t\ - (e*sqc*g*u**2 + E*u + e*sqc*F) // _c solve_y = lambda u: sqa*g*_c*t**2 + (D + 2*sqa*g*u)*t \ + (sqa*g*u**2 + D*u + sqa*F) // _c for z0 in range(0, abs(_c)): # Check if the coefficients of y and x obtained are integers or not if (divisible(sqa*g*z0**2 + D*z0 + sqa*F, _c) and divisible(e*sqc*g*z0**2 + E*z0 + e*sqc*F, _c)): sol.add((solve_x(z0), solve_y(z0))) # (3) Method used when B**2 - 4*A*C is a square, is described in p. 6 of the below paper # by John P. Robertson. # http://www.jpr2718.org/ax2p.pdf elif is_square(discr): if A != 0: r = sqrt(discr) u, v = symbols("u, v", integer=True) eq = _mexpand( 4*A*r*u*v + 4*A*D*(B*v + r*u + r*v - B*u) + 2*A*4*A*E*(u - v) + 4*A*r*4*A*F) solution = diop_solve(eq, t) for s0, t0 in solution: num = B*t0 + r*s0 + r*t0 - B*s0 x_0 = S(num)/(4*A*r) y_0 = S(s0 - t0)/(2*r) if isinstance(s0, Symbol) or isinstance(t0, Symbol): if check_param(x_0, y_0, 4*A*r, t) != (None, None): ans = check_param(x_0, y_0, 4*A*r, t) sol.add((ans[0], ans[1])) elif x_0.is_Integer and y_0.is_Integer: if is_solution_quad(var, coeff, x_0, y_0): sol.add((x_0, y_0)) else: s = _diop_quadratic(var[::-1], coeff, t) # Interchange x and y while s: # | sol.add(s.pop()[::-1]) # and solution <--------+ # (4) B**2 - 4*A*C > 0 and B**2 - 4*A*C not a square or B**2 - 4*A*C < 0 else: P, Q = _transformation_to_DN(var, coeff) D, N = _find_DN(var, coeff) solns_pell = diop_DN(D, N) if D < 0: for x0, y0 in solns_pell: for x in [-x0, x0]: for y in [-y0, y0]: s = P*Matrix([x, y]) + Q try: sol.add(tuple([as_int(_) for _ in s])) except ValueError: pass else: # In this case equation can be transformed into a Pell equation solns_pell = set(solns_pell) for X, Y in list(solns_pell): solns_pell.add((-X, -Y)) a = diop_DN(D, 1) T = a[0][0] U = a[0][1] if all(_is_int(_) for _ in P[:4] + Q[:2]): for r, s in solns_pell: _a = (r + s*sqrt(D))*(T + U*sqrt(D))**t _b = (r - s*sqrt(D))*(T - U*sqrt(D))**t x_n = _mexpand(S(_a + _b)/2) y_n = _mexpand(S(_a - _b)/(2*sqrt(D))) s = P*Matrix([x_n, y_n]) + Q sol.add(tuple(s)) else: L = ilcm(*[_.q for _ in P[:4] + Q[:2]]) k = 1 T_k = T U_k = U while (T_k - 1) % L != 0 or U_k % L != 0: T_k, U_k = T_k*T + D*U_k*U, T_k*U + U_k*T k += 1 for X, Y in solns_pell: for i in range(k): if all(_is_int(_) for _ in P*Matrix([X, Y]) + Q): _a = (X + sqrt(D)*Y)*(T_k + sqrt(D)*U_k)**t _b = (X - sqrt(D)*Y)*(T_k - sqrt(D)*U_k)**t Xt = S(_a + _b)/2 Yt = S(_a - _b)/(2*sqrt(D)) s = P*Matrix([Xt, Yt]) + Q sol.add(tuple(s)) X, Y = X*T + D*U*Y, X*U + Y*T return sol def is_solution_quad(var, coeff, u, v): """ Check whether `(u, v)` is solution to the quadratic binary diophantine equation with the variable list ``var`` and coefficient dictionary ``coeff``. Not intended for use by normal users. """ reps = dict(zip(var, (u, v))) eq = Add(*[j*i.xreplace(reps) for i, j in coeff.items()]) return _mexpand(eq) == 0 def diop_DN(D, N, t=symbols("t", integer=True)): """ Solves the equation `x^2 - Dy^2 = N`. Mainly concerned with the case `D > 0, D` is not a perfect square, which is the same as the generalized Pell equation. The LMM algorithm [1]_ is used to solve this equation. Returns one solution tuple, (`x, y)` for each class of the solutions. Other solutions of the class can be constructed according to the values of ``D`` and ``N``. Usage ===== ``diop_DN(D, N, t)``: D and N are integers as in `x^2 - Dy^2 = N` and ``t`` is the parameter to be used in the solutions. Details ======= ``D`` and ``N`` correspond to D and N in the equation. ``t`` is the parameter to be used in the solutions. Examples ======== >>> from sympy.solvers.diophantine.diophantine import diop_DN >>> diop_DN(13, -4) # Solves equation x**2 - 13*y**2 = -4 [(3, 1), (393, 109), (36, 10)] The output can be interpreted as follows: There are three fundamental solutions to the equation `x^2 - 13y^2 = -4` given by (3, 1), (393, 109) and (36, 10). Each tuple is in the form (x, y), i.e. solution (3, 1) means that `x = 3` and `y = 1`. >>> diop_DN(986, 1) # Solves equation x**2 - 986*y**2 = 1 [(49299, 1570)] See Also ======== find_DN(), diop_bf_DN() References ========== .. [1] Solving the generalized Pell equation x**2 - D*y**2 = N, John P. Robertson, July 31, 2004, Pages 16 - 17. [online], Available: http://www.jpr2718.org/pell.pdf """ if D < 0: if N == 0: return [(0, 0)] elif N < 0: return [] elif N > 0: sol = [] for d in divisors(square_factor(N)): sols = cornacchia(1, -D, N // d**2) if sols: for x, y in sols: sol.append((d*x, d*y)) if D == -1: sol.append((d*y, d*x)) return sol elif D == 0: if N < 0: return [] if N == 0: return [(0, t)] sN, _exact = integer_nthroot(N, 2) if _exact: return [(sN, t)] else: return [] else: # D > 0 sD, _exact = integer_nthroot(D, 2) if _exact: if N == 0: return [(sD*t, t)] else: sol = [] for y in range(floor(sign(N)*(N - 1)/(2*sD)) + 1): try: sq, _exact = integer_nthroot(D*y**2 + N, 2) except ValueError: _exact = False if _exact: sol.append((sq, y)) return sol elif 1 < N**2 < D: # It is much faster to call `_special_diop_DN`. return _special_diop_DN(D, N) else: if N == 0: return [(0, 0)] elif abs(N) == 1: pqa = PQa(0, 1, D) j = 0 G = [] B = [] for i in pqa: a = i[2] G.append(i[5]) B.append(i[4]) if j != 0 and a == 2*sD: break j = j + 1 if _odd(j): if N == -1: x = G[j - 1] y = B[j - 1] else: count = j while count < 2*j - 1: i = next(pqa) G.append(i[5]) B.append(i[4]) count += 1 x = G[count] y = B[count] else: if N == 1: x = G[j - 1] y = B[j - 1] else: return [] return [(x, y)] else: fs = [] sol = [] div = divisors(N) for d in div: if divisible(N, d**2): fs.append(d) for f in fs: m = N // f**2 zs = sqrt_mod(D, abs(m), all_roots=True) zs = [i for i in zs if i <= abs(m) // 2 ] if abs(m) != 2: zs = zs + [-i for i in zs if i] # omit dupl 0 for z in zs: pqa = PQa(z, abs(m), D) j = 0 G = [] B = [] for i in pqa: G.append(i[5]) B.append(i[4]) if j != 0 and abs(i[1]) == 1: r = G[j-1] s = B[j-1] if r**2 - D*s**2 == m: sol.append((f*r, f*s)) elif diop_DN(D, -1) != []: a = diop_DN(D, -1) sol.append((f*(r*a[0][0] + a[0][1]*s*D), f*(r*a[0][1] + s*a[0][0]))) break j = j + 1 if j == length(z, abs(m), D): break return sol def _special_diop_DN(D, N): """ Solves the equation `x^2 - Dy^2 = N` for the special case where `1 < N**2 < D` and `D` is not a perfect square. It is better to call `diop_DN` rather than this function, as the former checks the condition `1 < N**2 < D`, and calls the latter only if appropriate. Usage ===== WARNING: Internal method. Do not call directly! ``_special_diop_DN(D, N)``: D and N are integers as in `x^2 - Dy^2 = N`. Details ======= ``D`` and ``N`` correspond to D and N in the equation. Examples ======== >>> from sympy.solvers.diophantine.diophantine import _special_diop_DN >>> _special_diop_DN(13, -3) # Solves equation x**2 - 13*y**2 = -3 [(7, 2), (137, 38)] The output can be interpreted as follows: There are two fundamental solutions to the equation `x^2 - 13y^2 = -3` given by (7, 2) and (137, 38). Each tuple is in the form (x, y), i.e. solution (7, 2) means that `x = 7` and `y = 2`. >>> _special_diop_DN(2445, -20) # Solves equation x**2 - 2445*y**2 = -20 [(445, 9), (17625560, 356454), (698095554475, 14118073569)] See Also ======== diop_DN() References ========== .. [1] Section 4.4.4 of the following book: Quadratic Diophantine Equations, T. Andreescu and D. Andrica, Springer, 2015. """ # The following assertion was removed for efficiency, with the understanding # that this method is not called directly. The parent method, `diop_DN` # is responsible for performing the appropriate checks. # # assert (1 < N**2 < D) and (not integer_nthroot(D, 2)[1]) sqrt_D = sqrt(D) F = [(N, 1)] f = 2 while True: f2 = f**2 if f2 > abs(N): break n, r = divmod(N, f2) if r == 0: F.append((n, f)) f += 1 P = 0 Q = 1 G0, G1 = 0, 1 B0, B1 = 1, 0 solutions = [] i = 0 while True: a = floor((P + sqrt_D) / Q) P = a*Q - P Q = (D - P**2) // Q G2 = a*G1 + G0 B2 = a*B1 + B0 for n, f in F: if G2**2 - D*B2**2 == n: solutions.append((f*G2, f*B2)) i += 1 if Q == 1 and i % 2 == 0: break G0, G1 = G1, G2 B0, B1 = B1, B2 return solutions def cornacchia(a, b, m): r""" Solves `ax^2 + by^2 = m` where `\gcd(a, b) = 1 = gcd(a, m)` and `a, b > 0`. Uses the algorithm due to Cornacchia. The method only finds primitive solutions, i.e. ones with `\gcd(x, y) = 1`. So this method can't be used to find the solutions of `x^2 + y^2 = 20` since the only solution to former is `(x, y) = (4, 2)` and it is not primitive. When `a = b`, only the solutions with `x \leq y` are found. For more details, see the References. Examples ======== >>> from sympy.solvers.diophantine.diophantine import cornacchia >>> cornacchia(2, 3, 35) # equation 2x**2 + 3y**2 = 35 {(2, 3), (4, 1)} >>> cornacchia(1, 1, 25) # equation x**2 + y**2 = 25 {(4, 3)} References =========== .. [1] A. Nitaj, "L'algorithme de Cornacchia" .. [2] Solving the diophantine equation ax**2 + by**2 = m by Cornacchia's method, [online], Available: http://www.numbertheory.org/php/cornacchia.html See Also ======== sympy.utilities.iterables.signed_permutations """ sols = set() a1 = igcdex(a, m)[0] v = sqrt_mod(-b*a1, m, all_roots=True) if not v: return None for t in v: if t < m // 2: continue u, r = t, m while True: u, r = r, u % r if a*r**2 < m: break m1 = m - a*r**2 if m1 % b == 0: m1 = m1 // b s, _exact = integer_nthroot(m1, 2) if _exact: if a == b and r < s: r, s = s, r sols.add((int(r), int(s))) return sols def PQa(P_0, Q_0, D): r""" Returns useful information needed to solve the Pell equation. There are six sequences of integers defined related to the continued fraction representation of `\\frac{P + \sqrt{D}}{Q}`, namely {`P_{i}`}, {`Q_{i}`}, {`a_{i}`},{`A_{i}`}, {`B_{i}`}, {`G_{i}`}. ``PQa()`` Returns these values as a 6-tuple in the same order as mentioned above. Refer [1]_ for more detailed information. Usage ===== ``PQa(P_0, Q_0, D)``: ``P_0``, ``Q_0`` and ``D`` are integers corresponding to `P_{0}`, `Q_{0}` and `D` in the continued fraction `\\frac{P_{0} + \sqrt{D}}{Q_{0}}`. Also it's assumed that `P_{0}^2 == D mod(|Q_{0}|)` and `D` is square free. Examples ======== >>> from sympy.solvers.diophantine.diophantine import PQa >>> pqa = PQa(13, 4, 5) # (13 + sqrt(5))/4 >>> next(pqa) # (P_0, Q_0, a_0, A_0, B_0, G_0) (13, 4, 3, 3, 1, -1) >>> next(pqa) # (P_1, Q_1, a_1, A_1, B_1, G_1) (-1, 1, 1, 4, 1, 3) References ========== .. [1] Solving the generalized Pell equation x^2 - Dy^2 = N, John P. Robertson, July 31, 2004, Pages 4 - 8. http://www.jpr2718.org/pell.pdf """ A_i_2 = B_i_1 = 0 A_i_1 = B_i_2 = 1 G_i_2 = -P_0 G_i_1 = Q_0 P_i = P_0 Q_i = Q_0 while True: a_i = floor((P_i + sqrt(D))/Q_i) A_i = a_i*A_i_1 + A_i_2 B_i = a_i*B_i_1 + B_i_2 G_i = a_i*G_i_1 + G_i_2 yield P_i, Q_i, a_i, A_i, B_i, G_i A_i_1, A_i_2 = A_i, A_i_1 B_i_1, B_i_2 = B_i, B_i_1 G_i_1, G_i_2 = G_i, G_i_1 P_i = a_i*Q_i - P_i Q_i = (D - P_i**2)/Q_i def diop_bf_DN(D, N, t=symbols("t", integer=True)): r""" Uses brute force to solve the equation, `x^2 - Dy^2 = N`. Mainly concerned with the generalized Pell equation which is the case when `D > 0, D` is not a perfect square. For more information on the case refer [1]_. Let `(t, u)` be the minimal positive solution of the equation `x^2 - Dy^2 = 1`. Then this method requires `\sqrt{\\frac{\mid N \mid (t \pm 1)}{2D}}` to be small. Usage ===== ``diop_bf_DN(D, N, t)``: ``D`` and ``N`` are coefficients in `x^2 - Dy^2 = N` and ``t`` is the parameter to be used in the solutions. Details ======= ``D`` and ``N`` correspond to D and N in the equation. ``t`` is the parameter to be used in the solutions. Examples ======== >>> from sympy.solvers.diophantine.diophantine import diop_bf_DN >>> diop_bf_DN(13, -4) [(3, 1), (-3, 1), (36, 10)] >>> diop_bf_DN(986, 1) [(49299, 1570)] See Also ======== diop_DN() References ========== .. [1] Solving the generalized Pell equation x**2 - D*y**2 = N, John P. Robertson, July 31, 2004, Page 15. http://www.jpr2718.org/pell.pdf """ D = as_int(D) N = as_int(N) sol = [] a = diop_DN(D, 1) u = a[0][0] if abs(N) == 1: return diop_DN(D, N) elif N > 1: L1 = 0 L2 = integer_nthroot(int(N*(u - 1)/(2*D)), 2)[0] + 1 elif N < -1: L1, _exact = integer_nthroot(-int(N/D), 2) if not _exact: L1 += 1 L2 = integer_nthroot(-int(N*(u + 1)/(2*D)), 2)[0] + 1 else: # N = 0 if D < 0: return [(0, 0)] elif D == 0: return [(0, t)] else: sD, _exact = integer_nthroot(D, 2) if _exact: return [(sD*t, t), (-sD*t, t)] else: return [(0, 0)] for y in range(L1, L2): try: x, _exact = integer_nthroot(N + D*y**2, 2) except ValueError: _exact = False if _exact: sol.append((x, y)) if not equivalent(x, y, -x, y, D, N): sol.append((-x, y)) return sol def equivalent(u, v, r, s, D, N): """ Returns True if two solutions `(u, v)` and `(r, s)` of `x^2 - Dy^2 = N` belongs to the same equivalence class and False otherwise. Two solutions `(u, v)` and `(r, s)` to the above equation fall to the same equivalence class iff both `(ur - Dvs)` and `(us - vr)` are divisible by `N`. See reference [1]_. No test is performed to test whether `(u, v)` and `(r, s)` are actually solutions to the equation. User should take care of this. Usage ===== ``equivalent(u, v, r, s, D, N)``: `(u, v)` and `(r, s)` are two solutions of the equation `x^2 - Dy^2 = N` and all parameters involved are integers. Examples ======== >>> from sympy.solvers.diophantine.diophantine import equivalent >>> equivalent(18, 5, -18, -5, 13, -1) True >>> equivalent(3, 1, -18, 393, 109, -4) False References ========== .. [1] Solving the generalized Pell equation x**2 - D*y**2 = N, John P. Robertson, July 31, 2004, Page 12. http://www.jpr2718.org/pell.pdf """ return divisible(u*r - D*v*s, N) and divisible(u*s - v*r, N) def length(P, Q, D): r""" Returns the (length of aperiodic part + length of periodic part) of continued fraction representation of `\\frac{P + \sqrt{D}}{Q}`. It is important to remember that this does NOT return the length of the periodic part but the sum of the lengths of the two parts as mentioned above. Usage ===== ``length(P, Q, D)``: ``P``, ``Q`` and ``D`` are integers corresponding to the continued fraction `\\frac{P + \sqrt{D}}{Q}`. Details ======= ``P``, ``D`` and ``Q`` corresponds to P, D and Q in the continued fraction, `\\frac{P + \sqrt{D}}{Q}`. Examples ======== >>> from sympy.solvers.diophantine.diophantine import length >>> length(-2 , 4, 5) # (-2 + sqrt(5))/4 3 >>> length(-5, 4, 17) # (-5 + sqrt(17))/4 4 See Also ======== sympy.ntheory.continued_fraction.continued_fraction_periodic """ from sympy.ntheory.continued_fraction import continued_fraction_periodic v = continued_fraction_periodic(P, Q, D) if type(v[-1]) is list: rpt = len(v[-1]) nonrpt = len(v) - 1 else: rpt = 0 nonrpt = len(v) return rpt + nonrpt def transformation_to_DN(eq): """ This function transforms general quadratic, `ax^2 + bxy + cy^2 + dx + ey + f = 0` to more easy to deal with `X^2 - DY^2 = N` form. This is used to solve the general quadratic equation by transforming it to the latter form. Refer [1]_ for more detailed information on the transformation. This function returns a tuple (A, B) where A is a 2 X 2 matrix and B is a 2 X 1 matrix such that, Transpose([x y]) = A * Transpose([X Y]) + B Usage ===== ``transformation_to_DN(eq)``: where ``eq`` is the quadratic to be transformed. Examples ======== >>> from sympy.abc import x, y >>> from sympy.solvers.diophantine.diophantine import transformation_to_DN >>> from sympy.solvers.diophantine import classify_diop >>> A, B = transformation_to_DN(x**2 - 3*x*y - y**2 - 2*y + 1) >>> A Matrix([ [1/26, 3/26], [ 0, 1/13]]) >>> B Matrix([ [-6/13], [-4/13]]) A, B returned are such that Transpose((x y)) = A * Transpose((X Y)) + B. Substituting these values for `x` and `y` and a bit of simplifying work will give an equation of the form `x^2 - Dy^2 = N`. >>> from sympy.abc import X, Y >>> from sympy import Matrix, simplify >>> u = (A*Matrix([X, Y]) + B)[0] # Transformation for x >>> u X/26 + 3*Y/26 - 6/13 >>> v = (A*Matrix([X, Y]) + B)[1] # Transformation for y >>> v Y/13 - 4/13 Next we will substitute these formulas for `x` and `y` and do ``simplify()``. >>> eq = simplify((x**2 - 3*x*y - y**2 - 2*y + 1).subs(zip((x, y), (u, v)))) >>> eq X**2/676 - Y**2/52 + 17/13 By multiplying the denominator appropriately, we can get a Pell equation in the standard form. >>> eq * 676 X**2 - 13*Y**2 + 884 If only the final equation is needed, ``find_DN()`` can be used. See Also ======== find_DN() References ========== .. [1] Solving the equation ax^2 + bxy + cy^2 + dx + ey + f = 0, John P.Robertson, May 8, 2003, Page 7 - 11. http://www.jpr2718.org/ax2p.pdf """ var, coeff, diop_type = classify_diop(eq, _dict=False) if diop_type == "binary_quadratic": return _transformation_to_DN(var, coeff) def _transformation_to_DN(var, coeff): x, y = var a = coeff[x**2] b = coeff[x*y] c = coeff[y**2] d = coeff[x] e = coeff[y] f = coeff[1] a, b, c, d, e, f = [as_int(i) for i in _remove_gcd(a, b, c, d, e, f)] X, Y = symbols("X, Y", integer=True) if b: B, C = _rational_pq(2*a, b) A, T = _rational_pq(a, B**2) # eq_1 = A*B*X**2 + B*(c*T - A*C**2)*Y**2 + d*T*X + (B*e*T - d*T*C)*Y + f*T*B coeff = {X**2: A*B, X*Y: 0, Y**2: B*(c*T - A*C**2), X: d*T, Y: B*e*T - d*T*C, 1: f*T*B} A_0, B_0 = _transformation_to_DN([X, Y], coeff) return Matrix(2, 2, [S.One/B, -S(C)/B, 0, 1])*A_0, Matrix(2, 2, [S.One/B, -S(C)/B, 0, 1])*B_0 else: if d: B, C = _rational_pq(2*a, d) A, T = _rational_pq(a, B**2) # eq_2 = A*X**2 + c*T*Y**2 + e*T*Y + f*T - A*C**2 coeff = {X**2: A, X*Y: 0, Y**2: c*T, X: 0, Y: e*T, 1: f*T - A*C**2} A_0, B_0 = _transformation_to_DN([X, Y], coeff) return Matrix(2, 2, [S.One/B, 0, 0, 1])*A_0, Matrix(2, 2, [S.One/B, 0, 0, 1])*B_0 + Matrix([-S(C)/B, 0]) else: if e: B, C = _rational_pq(2*c, e) A, T = _rational_pq(c, B**2) # eq_3 = a*T*X**2 + A*Y**2 + f*T - A*C**2 coeff = {X**2: a*T, X*Y: 0, Y**2: A, X: 0, Y: 0, 1: f*T - A*C**2} A_0, B_0 = _transformation_to_DN([X, Y], coeff) return Matrix(2, 2, [1, 0, 0, S.One/B])*A_0, Matrix(2, 2, [1, 0, 0, S.One/B])*B_0 + Matrix([0, -S(C)/B]) else: # TODO: pre-simplification: Not necessary but may simplify # the equation. return Matrix(2, 2, [S.One/a, 0, 0, 1]), Matrix([0, 0]) def find_DN(eq): """ This function returns a tuple, `(D, N)` of the simplified form, `x^2 - Dy^2 = N`, corresponding to the general quadratic, `ax^2 + bxy + cy^2 + dx + ey + f = 0`. Solving the general quadratic is then equivalent to solving the equation `X^2 - DY^2 = N` and transforming the solutions by using the transformation matrices returned by ``transformation_to_DN()``. Usage ===== ``find_DN(eq)``: where ``eq`` is the quadratic to be transformed. Examples ======== >>> from sympy.abc import x, y >>> from sympy.solvers.diophantine.diophantine import find_DN >>> find_DN(x**2 - 3*x*y - y**2 - 2*y + 1) (13, -884) Interpretation of the output is that we get `X^2 -13Y^2 = -884` after transforming `x^2 - 3xy - y^2 - 2y + 1` using the transformation returned by ``transformation_to_DN()``. See Also ======== transformation_to_DN() References ========== .. [1] Solving the equation ax^2 + bxy + cy^2 + dx + ey + f = 0, John P.Robertson, May 8, 2003, Page 7 - 11. http://www.jpr2718.org/ax2p.pdf """ var, coeff, diop_type = classify_diop(eq, _dict=False) if diop_type == "binary_quadratic": return _find_DN(var, coeff) def _find_DN(var, coeff): x, y = var X, Y = symbols("X, Y", integer=True) A, B = _transformation_to_DN(var, coeff) u = (A*Matrix([X, Y]) + B)[0] v = (A*Matrix([X, Y]) + B)[1] eq = x**2*coeff[x**2] + x*y*coeff[x*y] + y**2*coeff[y**2] + x*coeff[x] + y*coeff[y] + coeff[1] simplified = _mexpand(eq.subs(zip((x, y), (u, v)))) coeff = simplified.as_coefficients_dict() return -coeff[Y**2]/coeff[X**2], -coeff[1]/coeff[X**2] def check_param(x, y, a, t): """ If there is a number modulo ``a`` such that ``x`` and ``y`` are both integers, then return a parametric representation for ``x`` and ``y`` else return (None, None). Here ``x`` and ``y`` are functions of ``t``. """ from sympy.simplify.simplify import clear_coefficients if x.is_number and not x.is_Integer: return (None, None) if y.is_number and not y.is_Integer: return (None, None) m, n = symbols("m, n", integer=True) c, p = (m*x + n*y).as_content_primitive() if a % c.q: return (None, None) # clear_coefficients(mx + b, R)[1] -> (R - b)/m eq = clear_coefficients(x, m)[1] - clear_coefficients(y, n)[1] junk, eq = eq.as_content_primitive() return diop_solve(eq, t) def diop_ternary_quadratic(eq): """ Solves the general quadratic ternary form, `ax^2 + by^2 + cz^2 + fxy + gyz + hxz = 0`. Returns a tuple `(x, y, z)` which is a base solution for the above equation. If there are no solutions, `(None, None, None)` is returned. Usage ===== ``diop_ternary_quadratic(eq)``: Return a tuple containing a basic solution to ``eq``. Details ======= ``eq`` should be an homogeneous expression of degree two in three variables and it is assumed to be zero. Examples ======== >>> from sympy.abc import x, y, z >>> from sympy.solvers.diophantine.diophantine import diop_ternary_quadratic >>> diop_ternary_quadratic(x**2 + 3*y**2 - z**2) (1, 0, 1) >>> diop_ternary_quadratic(4*x**2 + 5*y**2 - z**2) (1, 0, 2) >>> diop_ternary_quadratic(45*x**2 - 7*y**2 - 8*x*y - z**2) (28, 45, 105) >>> diop_ternary_quadratic(x**2 - 49*y**2 - z**2 + 13*z*y -8*x*y) (9, 1, 5) """ var, coeff, diop_type = classify_diop(eq, _dict=False) if diop_type in ( "homogeneous_ternary_quadratic", "homogeneous_ternary_quadratic_normal"): return _diop_ternary_quadratic(var, coeff) def _diop_ternary_quadratic(_var, coeff): x, y, z = _var var = [x, y, z] # Equations of the form B*x*y + C*z*x + E*y*z = 0 and At least two of the # coefficients A, B, C are non-zero. # There are infinitely many solutions for the equation. # Ex: (0, 0, t), (0, t, 0), (t, 0, 0) # Equation can be re-written as y*(B*x + E*z) = -C*x*z and we can find rather # unobvious solutions. Set y = -C and B*x + E*z = x*z. The latter can be solved by # using methods for binary quadratic diophantine equations. Let's select the # solution which minimizes |x| + |z| if not any(coeff[i**2] for i in var): if coeff[x*z]: sols = diophantine(coeff[x*y]*x + coeff[y*z]*z - x*z) s = sols.pop() min_sum = abs(s[0]) + abs(s[1]) for r in sols: m = abs(r[0]) + abs(r[1]) if m < min_sum: s = r min_sum = m x_0, y_0, z_0 = _remove_gcd(s[0], -coeff[x*z], s[1]) else: var[0], var[1] = _var[1], _var[0] y_0, x_0, z_0 = _diop_ternary_quadratic(var, coeff) return x_0, y_0, z_0 if coeff[x**2] == 0: # If the coefficient of x is zero change the variables if coeff[y**2] == 0: var[0], var[2] = _var[2], _var[0] z_0, y_0, x_0 = _diop_ternary_quadratic(var, coeff) else: var[0], var[1] = _var[1], _var[0] y_0, x_0, z_0 = _diop_ternary_quadratic(var, coeff) else: if coeff[x*y] or coeff[x*z]: # Apply the transformation x --> X - (B*y + C*z)/(2*A) A = coeff[x**2] B = coeff[x*y] C = coeff[x*z] D = coeff[y**2] E = coeff[y*z] F = coeff[z**2] _coeff = dict() _coeff[x**2] = 4*A**2 _coeff[y**2] = 4*A*D - B**2 _coeff[z**2] = 4*A*F - C**2 _coeff[y*z] = 4*A*E - 2*B*C _coeff[x*y] = 0 _coeff[x*z] = 0 x_0, y_0, z_0 = _diop_ternary_quadratic(var, _coeff) if x_0 is None: return (None, None, None) p, q = _rational_pq(B*y_0 + C*z_0, 2*A) x_0, y_0, z_0 = x_0*q - p, y_0*q, z_0*q elif coeff[z*y] != 0: if coeff[y**2] == 0: if coeff[z**2] == 0: # Equations of the form A*x**2 + E*yz = 0. A = coeff[x**2] E = coeff[y*z] b, a = _rational_pq(-E, A) x_0, y_0, z_0 = b, a, b else: # Ax**2 + E*y*z + F*z**2 = 0 var[0], var[2] = _var[2], _var[0] z_0, y_0, x_0 = _diop_ternary_quadratic(var, coeff) else: # A*x**2 + D*y**2 + E*y*z + F*z**2 = 0, C may be zero var[0], var[1] = _var[1], _var[0] y_0, x_0, z_0 = _diop_ternary_quadratic(var, coeff) else: # Ax**2 + D*y**2 + F*z**2 = 0, C may be zero x_0, y_0, z_0 = _diop_ternary_quadratic_normal(var, coeff) return _remove_gcd(x_0, y_0, z_0) def transformation_to_normal(eq): """ Returns the transformation Matrix that converts a general ternary quadratic equation ``eq`` (`ax^2 + by^2 + cz^2 + dxy + eyz + fxz`) to a form without cross terms: `ax^2 + by^2 + cz^2 = 0`. This is not used in solving ternary quadratics; it is only implemented for the sake of completeness. """ var, coeff, diop_type = classify_diop(eq, _dict=False) if diop_type in ( "homogeneous_ternary_quadratic", "homogeneous_ternary_quadratic_normal"): return _transformation_to_normal(var, coeff) def _transformation_to_normal(var, coeff): _var = list(var) # copy x, y, z = var if not any(coeff[i**2] for i in var): # https://math.stackexchange.com/questions/448051/transform-quadratic-ternary-form-to-normal-form/448065#448065 a = coeff[x*y] b = coeff[y*z] c = coeff[x*z] swap = False if not a: # b can't be 0 or else there aren't 3 vars swap = True a, b = b, a T = Matrix(((1, 1, -b/a), (1, -1, -c/a), (0, 0, 1))) if swap: T.row_swap(0, 1) T.col_swap(0, 1) return T if coeff[x**2] == 0: # If the coefficient of x is zero change the variables if coeff[y**2] == 0: _var[0], _var[2] = var[2], var[0] T = _transformation_to_normal(_var, coeff) T.row_swap(0, 2) T.col_swap(0, 2) return T else: _var[0], _var[1] = var[1], var[0] T = _transformation_to_normal(_var, coeff) T.row_swap(0, 1) T.col_swap(0, 1) return T # Apply the transformation x --> X - (B*Y + C*Z)/(2*A) if coeff[x*y] != 0 or coeff[x*z] != 0: A = coeff[x**2] B = coeff[x*y] C = coeff[x*z] D = coeff[y**2] E = coeff[y*z] F = coeff[z**2] _coeff = dict() _coeff[x**2] = 4*A**2 _coeff[y**2] = 4*A*D - B**2 _coeff[z**2] = 4*A*F - C**2 _coeff[y*z] = 4*A*E - 2*B*C _coeff[x*y] = 0 _coeff[x*z] = 0 T_0 = _transformation_to_normal(_var, _coeff) return Matrix(3, 3, [1, S(-B)/(2*A), S(-C)/(2*A), 0, 1, 0, 0, 0, 1])*T_0 elif coeff[y*z] != 0: if coeff[y**2] == 0: if coeff[z**2] == 0: # Equations of the form A*x**2 + E*yz = 0. # Apply transformation y -> Y + Z ans z -> Y - Z return Matrix(3, 3, [1, 0, 0, 0, 1, 1, 0, 1, -1]) else: # Ax**2 + E*y*z + F*z**2 = 0 _var[0], _var[2] = var[2], var[0] T = _transformation_to_normal(_var, coeff) T.row_swap(0, 2) T.col_swap(0, 2) return T else: # A*x**2 + D*y**2 + E*y*z + F*z**2 = 0, F may be zero _var[0], _var[1] = var[1], var[0] T = _transformation_to_normal(_var, coeff) T.row_swap(0, 1) T.col_swap(0, 1) return T else: return Matrix.eye(3) def parametrize_ternary_quadratic(eq): """ Returns the parametrized general solution for the ternary quadratic equation ``eq`` which has the form `ax^2 + by^2 + cz^2 + fxy + gyz + hxz = 0`. Examples ======== >>> from sympy import Tuple, ordered >>> from sympy.abc import x, y, z >>> from sympy.solvers.diophantine.diophantine import parametrize_ternary_quadratic The parametrized solution may be returned with three parameters: >>> parametrize_ternary_quadratic(2*x**2 + y**2 - 2*z**2) (p**2 - 2*q**2, -2*p**2 + 4*p*q - 4*p*r - 4*q**2, p**2 - 4*p*q + 2*q**2 - 4*q*r) There might also be only two parameters: >>> parametrize_ternary_quadratic(4*x**2 + 2*y**2 - 3*z**2) (2*p**2 - 3*q**2, -4*p**2 + 12*p*q - 6*q**2, 4*p**2 - 8*p*q + 6*q**2) Notes ===== Consider ``p`` and ``q`` in the previous 2-parameter solution and observe that more than one solution can be represented by a given pair of parameters. If `p` and ``q`` are not coprime, this is trivially true since the common factor will also be a common factor of the solution values. But it may also be true even when ``p`` and ``q`` are coprime: >>> sol = Tuple(*_) >>> p, q = ordered(sol.free_symbols) >>> sol.subs([(p, 3), (q, 2)]) (6, 12, 12) >>> sol.subs([(q, 1), (p, 1)]) (-1, 2, 2) >>> sol.subs([(q, 0), (p, 1)]) (2, -4, 4) >>> sol.subs([(q, 1), (p, 0)]) (-3, -6, 6) Except for sign and a common factor, these are equivalent to the solution of (1, 2, 2). References ========== .. [1] The algorithmic resolution of Diophantine equations, Nigel P. Smart, London Mathematical Society Student Texts 41, Cambridge University Press, Cambridge, 1998. """ var, coeff, diop_type = classify_diop(eq, _dict=False) if diop_type in ( "homogeneous_ternary_quadratic", "homogeneous_ternary_quadratic_normal"): x_0, y_0, z_0 = _diop_ternary_quadratic(var, coeff) return _parametrize_ternary_quadratic( (x_0, y_0, z_0), var, coeff) def _parametrize_ternary_quadratic(solution, _var, coeff): # called for a*x**2 + b*y**2 + c*z**2 + d*x*y + e*y*z + f*x*z = 0 assert 1 not in coeff x_0, y_0, z_0 = solution v = list(_var) # copy if x_0 is None: return (None, None, None) if solution.count(0) >= 2: # if there are 2 zeros the equation reduces # to k*X**2 == 0 where X is x, y, or z so X must # be zero, too. So there is only the trivial # solution. return (None, None, None) if x_0 == 0: v[0], v[1] = v[1], v[0] y_p, x_p, z_p = _parametrize_ternary_quadratic( (y_0, x_0, z_0), v, coeff) return x_p, y_p, z_p x, y, z = v r, p, q = symbols("r, p, q", integer=True) eq = sum(k*v for k, v in coeff.items()) eq_1 = _mexpand(eq.subs(zip( (x, y, z), (r*x_0, r*y_0 + p, r*z_0 + q)))) A, B = eq_1.as_independent(r, as_Add=True) x = A*x_0 y = (A*y_0 - _mexpand(B/r*p)) z = (A*z_0 - _mexpand(B/r*q)) return _remove_gcd(x, y, z) def diop_ternary_quadratic_normal(eq): """ Solves the quadratic ternary diophantine equation, `ax^2 + by^2 + cz^2 = 0`. Here the coefficients `a`, `b`, and `c` should be non zero. Otherwise the equation will be a quadratic binary or univariate equation. If solvable, returns a tuple `(x, y, z)` that satisfies the given equation. If the equation does not have integer solutions, `(None, None, None)` is returned. Usage ===== ``diop_ternary_quadratic_normal(eq)``: where ``eq`` is an equation of the form `ax^2 + by^2 + cz^2 = 0`. Examples ======== >>> from sympy.abc import x, y, z >>> from sympy.solvers.diophantine.diophantine import diop_ternary_quadratic_normal >>> diop_ternary_quadratic_normal(x**2 + 3*y**2 - z**2) (1, 0, 1) >>> diop_ternary_quadratic_normal(4*x**2 + 5*y**2 - z**2) (1, 0, 2) >>> diop_ternary_quadratic_normal(34*x**2 - 3*y**2 - 301*z**2) (4, 9, 1) """ var, coeff, diop_type = classify_diop(eq, _dict=False) if diop_type == "homogeneous_ternary_quadratic_normal": return _diop_ternary_quadratic_normal(var, coeff) def _diop_ternary_quadratic_normal(var, coeff): x, y, z = var a = coeff[x**2] b = coeff[y**2] c = coeff[z**2] try: assert len([k for k in coeff if coeff[k]]) == 3 assert all(coeff[i**2] for i in var) except AssertionError: raise ValueError(filldedent(''' coeff dict is not consistent with assumption of this routine: coefficients should be those of an expression in the form a*x**2 + b*y**2 + c*z**2 where a*b*c != 0.''')) (sqf_of_a, sqf_of_b, sqf_of_c), (a_1, b_1, c_1), (a_2, b_2, c_2) = \ sqf_normal(a, b, c, steps=True) A = -a_2*c_2 B = -b_2*c_2 # If following two conditions are satisfied then there are no solutions if A < 0 and B < 0: return (None, None, None) if ( sqrt_mod(-b_2*c_2, a_2) is None or sqrt_mod(-c_2*a_2, b_2) is None or sqrt_mod(-a_2*b_2, c_2) is None): return (None, None, None) z_0, x_0, y_0 = descent(A, B) z_0, q = _rational_pq(z_0, abs(c_2)) x_0 *= q y_0 *= q x_0, y_0, z_0 = _remove_gcd(x_0, y_0, z_0) # Holzer reduction if sign(a) == sign(b): x_0, y_0, z_0 = holzer(x_0, y_0, z_0, abs(a_2), abs(b_2), abs(c_2)) elif sign(a) == sign(c): x_0, z_0, y_0 = holzer(x_0, z_0, y_0, abs(a_2), abs(c_2), abs(b_2)) else: y_0, z_0, x_0 = holzer(y_0, z_0, x_0, abs(b_2), abs(c_2), abs(a_2)) x_0 = reconstruct(b_1, c_1, x_0) y_0 = reconstruct(a_1, c_1, y_0) z_0 = reconstruct(a_1, b_1, z_0) sq_lcm = ilcm(sqf_of_a, sqf_of_b, sqf_of_c) x_0 = abs(x_0*sq_lcm//sqf_of_a) y_0 = abs(y_0*sq_lcm//sqf_of_b) z_0 = abs(z_0*sq_lcm//sqf_of_c) return _remove_gcd(x_0, y_0, z_0) def sqf_normal(a, b, c, steps=False): """ Return `a', b', c'`, the coefficients of the square-free normal form of `ax^2 + by^2 + cz^2 = 0`, where `a', b', c'` are pairwise prime. If `steps` is True then also return three tuples: `sq`, `sqf`, and `(a', b', c')` where `sq` contains the square factors of `a`, `b` and `c` after removing the `gcd(a, b, c)`; `sqf` contains the values of `a`, `b` and `c` after removing both the `gcd(a, b, c)` and the square factors. The solutions for `ax^2 + by^2 + cz^2 = 0` can be recovered from the solutions of `a'x^2 + b'y^2 + c'z^2 = 0`. Examples ======== >>> from sympy.solvers.diophantine.diophantine import sqf_normal >>> sqf_normal(2 * 3**2 * 5, 2 * 5 * 11, 2 * 7**2 * 11) (11, 1, 5) >>> sqf_normal(2 * 3**2 * 5, 2 * 5 * 11, 2 * 7**2 * 11, True) ((3, 1, 7), (5, 55, 11), (11, 1, 5)) References ========== .. [1] Legendre's Theorem, Legrange's Descent, http://public.csusm.edu/aitken_html/notes/legendre.pdf See Also ======== reconstruct() """ ABC = _remove_gcd(a, b, c) sq = tuple(square_factor(i) for i in ABC) sqf = A, B, C = tuple([i//j**2 for i,j in zip(ABC, sq)]) pc = igcd(A, B) A /= pc B /= pc pa = igcd(B, C) B /= pa C /= pa pb = igcd(A, C) A /= pb B /= pb A *= pa B *= pb C *= pc if steps: return (sq, sqf, (A, B, C)) else: return A, B, C def square_factor(a): r""" Returns an integer `c` s.t. `a = c^2k, \ c,k \in Z`. Here `k` is square free. `a` can be given as an integer or a dictionary of factors. Examples ======== >>> from sympy.solvers.diophantine.diophantine import square_factor >>> square_factor(24) 2 >>> square_factor(-36*3) 6 >>> square_factor(1) 1 >>> square_factor({3: 2, 2: 1, -1: 1}) # -18 3 See Also ======== sympy.ntheory.factor_.core """ f = a if isinstance(a, dict) else factorint(a) return Mul(*[p**(e//2) for p, e in f.items()]) def reconstruct(A, B, z): """ Reconstruct the `z` value of an equivalent solution of `ax^2 + by^2 + cz^2` from the `z` value of a solution of the square-free normal form of the equation, `a'*x^2 + b'*y^2 + c'*z^2`, where `a'`, `b'` and `c'` are square free and `gcd(a', b', c') == 1`. """ f = factorint(igcd(A, B)) for p, e in f.items(): if e != 1: raise ValueError('a and b should be square-free') z *= p return z def ldescent(A, B): """ Return a non-trivial solution to `w^2 = Ax^2 + By^2` using Lagrange's method; return None if there is no such solution. . Here, `A \\neq 0` and `B \\neq 0` and `A` and `B` are square free. Output a tuple `(w_0, x_0, y_0)` which is a solution to the above equation. Examples ======== >>> from sympy.solvers.diophantine.diophantine import ldescent >>> ldescent(1, 1) # w^2 = x^2 + y^2 (1, 1, 0) >>> ldescent(4, -7) # w^2 = 4x^2 - 7y^2 (2, -1, 0) This means that `x = -1, y = 0` and `w = 2` is a solution to the equation `w^2 = 4x^2 - 7y^2` >>> ldescent(5, -1) # w^2 = 5x^2 - y^2 (2, 1, -1) References ========== .. [1] The algorithmic resolution of Diophantine equations, Nigel P. Smart, London Mathematical Society Student Texts 41, Cambridge University Press, Cambridge, 1998. .. [2] Efficient Solution of Rational Conices, J. E. Cremona and D. Rusin, [online], Available: http://eprints.nottingham.ac.uk/60/1/kvxefz87.pdf """ if abs(A) > abs(B): w, y, x = ldescent(B, A) return w, x, y if A == 1: return (1, 1, 0) if B == 1: return (1, 0, 1) if B == -1: # and A == -1 return r = sqrt_mod(A, B) Q = (r**2 - A) // B if Q == 0: B_0 = 1 d = 0 else: div = divisors(Q) B_0 = None for i in div: sQ, _exact = integer_nthroot(abs(Q) // i, 2) if _exact: B_0, d = sign(Q)*i, sQ break if B_0 is not None: W, X, Y = ldescent(A, B_0) return _remove_gcd((-A*X + r*W), (r*X - W), Y*(B_0*d)) def descent(A, B): """ Returns a non-trivial solution, (x, y, z), to `x^2 = Ay^2 + Bz^2` using Lagrange's descent method with lattice-reduction. `A` and `B` are assumed to be valid for such a solution to exist. This is faster than the normal Lagrange's descent algorithm because the Gaussian reduction is used. Examples ======== >>> from sympy.solvers.diophantine.diophantine import descent >>> descent(3, 1) # x**2 = 3*y**2 + z**2 (1, 0, 1) `(x, y, z) = (1, 0, 1)` is a solution to the above equation. >>> descent(41, -113) (-16, -3, 1) References ========== .. [1] Efficient Solution of Rational Conices, J. E. Cremona and D. Rusin, Mathematics of Computation, Volume 00, Number 0. """ if abs(A) > abs(B): x, y, z = descent(B, A) return x, z, y if B == 1: return (1, 0, 1) if A == 1: return (1, 1, 0) if B == -A: return (0, 1, 1) if B == A: x, z, y = descent(-1, A) return (A*y, z, x) w = sqrt_mod(A, B) x_0, z_0 = gaussian_reduce(w, A, B) t = (x_0**2 - A*z_0**2) // B t_2 = square_factor(t) t_1 = t // t_2**2 x_1, z_1, y_1 = descent(A, t_1) return _remove_gcd(x_0*x_1 + A*z_0*z_1, z_0*x_1 + x_0*z_1, t_1*t_2*y_1) def gaussian_reduce(w, a, b): r""" Returns a reduced solution `(x, z)` to the congruence `X^2 - aZ^2 \equiv 0 \ (mod \ b)` so that `x^2 + |a|z^2` is minimal. Details ======= Here ``w`` is a solution of the congruence `x^2 \equiv a \ (mod \ b)` References ========== .. [1] Gaussian lattice Reduction [online]. Available: http://home.ie.cuhk.edu.hk/~wkshum/wordpress/?p=404 .. [2] Efficient Solution of Rational Conices, J. E. Cremona and D. Rusin, Mathematics of Computation, Volume 00, Number 0. """ u = (0, 1) v = (1, 0) if dot(u, v, w, a, b) < 0: v = (-v[0], -v[1]) if norm(u, w, a, b) < norm(v, w, a, b): u, v = v, u while norm(u, w, a, b) > norm(v, w, a, b): k = dot(u, v, w, a, b) // dot(v, v, w, a, b) u, v = v, (u[0]- k*v[0], u[1]- k*v[1]) u, v = v, u if dot(u, v, w, a, b) < dot(v, v, w, a, b)/2 or norm((u[0]-v[0], u[1]-v[1]), w, a, b) > norm(v, w, a, b): c = v else: c = (u[0] - v[0], u[1] - v[1]) return c[0]*w + b*c[1], c[0] def dot(u, v, w, a, b): r""" Returns a special dot product of the vectors `u = (u_{1}, u_{2})` and `v = (v_{1}, v_{2})` which is defined in order to reduce solution of the congruence equation `X^2 - aZ^2 \equiv 0 \ (mod \ b)`. """ u_1, u_2 = u v_1, v_2 = v return (w*u_1 + b*u_2)*(w*v_1 + b*v_2) + abs(a)*u_1*v_1 def norm(u, w, a, b): r""" Returns the norm of the vector `u = (u_{1}, u_{2})` under the dot product defined by `u \cdot v = (wu_{1} + bu_{2})(w*v_{1} + bv_{2}) + |a|*u_{1}*v_{1}` where `u = (u_{1}, u_{2})` and `v = (v_{1}, v_{2})`. """ u_1, u_2 = u return sqrt(dot((u_1, u_2), (u_1, u_2), w, a, b)) def holzer(x, y, z, a, b, c): r""" Simplify the solution `(x, y, z)` of the equation `ax^2 + by^2 = cz^2` with `a, b, c > 0` and `z^2 \geq \mid ab \mid` to a new reduced solution `(x', y', z')` such that `z'^2 \leq \mid ab \mid`. The algorithm is an interpretation of Mordell's reduction as described on page 8 of Cremona and Rusin's paper [1]_ and the work of Mordell in reference [2]_. References ========== .. [1] Efficient Solution of Rational Conices, J. E. Cremona and D. Rusin, Mathematics of Computation, Volume 00, Number 0. .. [2] Diophantine Equations, L. J. Mordell, page 48. """ if _odd(c): k = 2*c else: k = c//2 small = a*b*c step = 0 while True: t1, t2, t3 = a*x**2, b*y**2, c*z**2 # check that it's a solution if t1 + t2 != t3: if step == 0: raise ValueError('bad starting solution') break x_0, y_0, z_0 = x, y, z if max(t1, t2, t3) <= small: # Holzer condition break uv = u, v = base_solution_linear(k, y_0, -x_0) if None in uv: break p, q = -(a*u*x_0 + b*v*y_0), c*z_0 r = Rational(p, q) if _even(c): w = _nint_or_floor(p, q) assert abs(w - r) <= S.Half else: w = p//q # floor if _odd(a*u + b*v + c*w): w += 1 assert abs(w - r) <= S.One A = (a*u**2 + b*v**2 + c*w**2) B = (a*u*x_0 + b*v*y_0 + c*w*z_0) x = Rational(x_0*A - 2*u*B, k) y = Rational(y_0*A - 2*v*B, k) z = Rational(z_0*A - 2*w*B, k) assert all(i.is_Integer for i in (x, y, z)) step += 1 return tuple([int(i) for i in (x_0, y_0, z_0)]) def diop_general_pythagorean(eq, param=symbols("m", integer=True)): """ Solves the general pythagorean equation, `a_{1}^2x_{1}^2 + a_{2}^2x_{2}^2 + . . . + a_{n}^2x_{n}^2 - a_{n + 1}^2x_{n + 1}^2 = 0`. Returns a tuple which contains a parametrized solution to the equation, sorted in the same order as the input variables. Usage ===== ``diop_general_pythagorean(eq, param)``: where ``eq`` is a general pythagorean equation which is assumed to be zero and ``param`` is the base parameter used to construct other parameters by subscripting. Examples ======== >>> from sympy.solvers.diophantine.diophantine import diop_general_pythagorean >>> from sympy.abc import a, b, c, d, e >>> diop_general_pythagorean(a**2 + b**2 + c**2 - d**2) (m1**2 + m2**2 - m3**2, 2*m1*m3, 2*m2*m3, m1**2 + m2**2 + m3**2) >>> diop_general_pythagorean(9*a**2 - 4*b**2 + 16*c**2 + 25*d**2 + e**2) (10*m1**2 + 10*m2**2 + 10*m3**2 - 10*m4**2, 15*m1**2 + 15*m2**2 + 15*m3**2 + 15*m4**2, 15*m1*m4, 12*m2*m4, 60*m3*m4) """ var, coeff, diop_type = classify_diop(eq, _dict=False) if diop_type == "general_pythagorean": return _diop_general_pythagorean(var, coeff, param) def _diop_general_pythagorean(var, coeff, t): if sign(coeff[var[0]**2]) + sign(coeff[var[1]**2]) + sign(coeff[var[2]**2]) < 0: for key in coeff.keys(): coeff[key] = -coeff[key] n = len(var) index = 0 for i, v in enumerate(var): if sign(coeff[v**2]) == -1: index = i m = symbols('%s1:%i' % (t, n), integer=True) ith = sum(m_i**2 for m_i in m) L = [ith - 2*m[n - 2]**2] L.extend([2*m[i]*m[n-2] for i in range(n - 2)]) sol = L[:index] + [ith] + L[index:] lcm = 1 for i, v in enumerate(var): if i == index or (index > 0 and i == 0) or (index == 0 and i == 1): lcm = ilcm(lcm, sqrt(abs(coeff[v**2]))) else: s = sqrt(coeff[v**2]) lcm = ilcm(lcm, s if _odd(s) else s//2) for i, v in enumerate(var): sol[i] = (lcm*sol[i]) / sqrt(abs(coeff[v**2])) return tuple(sol) def diop_general_sum_of_squares(eq, limit=1): r""" Solves the equation `x_{1}^2 + x_{2}^2 + . . . + x_{n}^2 - k = 0`. Returns at most ``limit`` number of solutions. Usage ===== ``general_sum_of_squares(eq, limit)`` : Here ``eq`` is an expression which is assumed to be zero. Also, ``eq`` should be in the form, `x_{1}^2 + x_{2}^2 + . . . + x_{n}^2 - k = 0`. Details ======= When `n = 3` if `k = 4^a(8m + 7)` for some `a, m \in Z` then there will be no solutions. Refer [1]_ for more details. Examples ======== >>> from sympy.solvers.diophantine.diophantine import diop_general_sum_of_squares >>> from sympy.abc import a, b, c, d, e, f >>> diop_general_sum_of_squares(a**2 + b**2 + c**2 + d**2 + e**2 - 2345) {(15, 22, 22, 24, 24)} Reference ========= .. [1] Representing an integer as a sum of three squares, [online], Available: http://www.proofwiki.org/wiki/Integer_as_Sum_of_Three_Squares """ var, coeff, diop_type = classify_diop(eq, _dict=False) if diop_type == "general_sum_of_squares": return _diop_general_sum_of_squares(var, -coeff[1], limit) def _diop_general_sum_of_squares(var, k, limit=1): # solves Eq(sum(i**2 for i in var), k) n = len(var) if n < 3: raise ValueError('n must be greater than 2') s = set() if k < 0 or limit < 1: return s sign = [-1 if x.is_nonpositive else 1 for x in var] negs = sign.count(-1) != 0 took = 0 for t in sum_of_squares(k, n, zeros=True): if negs: s.add(tuple([sign[i]*j for i, j in enumerate(t)])) else: s.add(t) took += 1 if took == limit: break return s def diop_general_sum_of_even_powers(eq, limit=1): """ Solves the equation `x_{1}^e + x_{2}^e + . . . + x_{n}^e - k = 0` where `e` is an even, integer power. Returns at most ``limit`` number of solutions. Usage ===== ``general_sum_of_even_powers(eq, limit)`` : Here ``eq`` is an expression which is assumed to be zero. Also, ``eq`` should be in the form, `x_{1}^e + x_{2}^e + . . . + x_{n}^e - k = 0`. Examples ======== >>> from sympy.solvers.diophantine.diophantine import diop_general_sum_of_even_powers >>> from sympy.abc import a, b >>> diop_general_sum_of_even_powers(a**4 + b**4 - (2**4 + 3**4)) {(2, 3)} See Also ======== power_representation """ var, coeff, diop_type = classify_diop(eq, _dict=False) if diop_type == "general_sum_of_even_powers": for k in coeff.keys(): if k.is_Pow and coeff[k]: p = k.exp return _diop_general_sum_of_even_powers(var, p, -coeff[1], limit) def _diop_general_sum_of_even_powers(var, p, n, limit=1): # solves Eq(sum(i**2 for i in var), n) k = len(var) s = set() if n < 0 or limit < 1: return s sign = [-1 if x.is_nonpositive else 1 for x in var] negs = sign.count(-1) != 0 took = 0 for t in power_representation(n, p, k): if negs: s.add(tuple([sign[i]*j for i, j in enumerate(t)])) else: s.add(t) took += 1 if took == limit: break return s ## Functions below this comment can be more suitably grouped under ## an Additive number theory module rather than the Diophantine ## equation module. def partition(n, k=None, zeros=False): """ Returns a generator that can be used to generate partitions of an integer `n`. A partition of `n` is a set of positive integers which add up to `n`. For example, partitions of 3 are 3, 1 + 2, 1 + 1 + 1. A partition is returned as a tuple. If ``k`` equals None, then all possible partitions are returned irrespective of their size, otherwise only the partitions of size ``k`` are returned. If the ``zero`` parameter is set to True then a suitable number of zeros are added at the end of every partition of size less than ``k``. ``zero`` parameter is considered only if ``k`` is not None. When the partitions are over, the last `next()` call throws the ``StopIteration`` exception, so this function should always be used inside a try - except block. Details ======= ``partition(n, k)``: Here ``n`` is a positive integer and ``k`` is the size of the partition which is also positive integer. Examples ======== >>> from sympy.solvers.diophantine.diophantine import partition >>> f = partition(5) >>> next(f) (1, 1, 1, 1, 1) >>> next(f) (1, 1, 1, 2) >>> g = partition(5, 3) >>> next(g) (1, 1, 3) >>> next(g) (1, 2, 2) >>> g = partition(5, 3, zeros=True) >>> next(g) (0, 0, 5) """ from sympy.utilities.iterables import ordered_partitions if not zeros or k is None: for i in ordered_partitions(n, k): yield tuple(i) else: for m in range(1, k + 1): for i in ordered_partitions(n, m): i = tuple(i) yield (0,)*(k - len(i)) + i def prime_as_sum_of_two_squares(p): """ Represent a prime `p` as a unique sum of two squares; this can only be done if the prime is congruent to 1 mod 4. Examples ======== >>> from sympy.solvers.diophantine.diophantine import prime_as_sum_of_two_squares >>> prime_as_sum_of_two_squares(7) # can't be done >>> prime_as_sum_of_two_squares(5) (1, 2) Reference ========= .. [1] Representing a number as a sum of four squares, [online], Available: http://schorn.ch/lagrange.html See Also ======== sum_of_squares() """ if not p % 4 == 1: return if p % 8 == 5: b = 2 else: b = 3 while pow(b, (p - 1) // 2, p) == 1: b = nextprime(b) b = pow(b, (p - 1) // 4, p) a = p while b**2 > p: a, b = b, a % b return (int(a % b), int(b)) # convert from long def sum_of_three_squares(n): r""" Returns a 3-tuple `(a, b, c)` such that `a^2 + b^2 + c^2 = n` and `a, b, c \geq 0`. Returns None if `n = 4^a(8m + 7)` for some `a, m \in Z`. See [1]_ for more details. Usage ===== ``sum_of_three_squares(n)``: Here ``n`` is a non-negative integer. Examples ======== >>> from sympy.solvers.diophantine.diophantine import sum_of_three_squares >>> sum_of_three_squares(44542) (18, 37, 207) References ========== .. [1] Representing a number as a sum of three squares, [online], Available: http://schorn.ch/lagrange.html See Also ======== sum_of_squares() """ special = {1:(1, 0, 0), 2:(1, 1, 0), 3:(1, 1, 1), 10: (1, 3, 0), 34: (3, 3, 4), 58:(3, 7, 0), 85:(6, 7, 0), 130:(3, 11, 0), 214:(3, 6, 13), 226:(8, 9, 9), 370:(8, 9, 15), 526:(6, 7, 21), 706:(15, 15, 16), 730:(1, 27, 0), 1414:(6, 17, 33), 1906:(13, 21, 36), 2986: (21, 32, 39), 9634: (56, 57, 57)} v = 0 if n == 0: return (0, 0, 0) v = multiplicity(4, n) n //= 4**v if n % 8 == 7: return if n in special.keys(): x, y, z = special[n] return _sorted_tuple(2**v*x, 2**v*y, 2**v*z) s, _exact = integer_nthroot(n, 2) if _exact: return (2**v*s, 0, 0) x = None if n % 8 == 3: s = s if _odd(s) else s - 1 for x in range(s, -1, -2): N = (n - x**2) // 2 if isprime(N): y, z = prime_as_sum_of_two_squares(N) return _sorted_tuple(2**v*x, 2**v*(y + z), 2**v*abs(y - z)) return if n % 8 == 2 or n % 8 == 6: s = s if _odd(s) else s - 1 else: s = s - 1 if _odd(s) else s for x in range(s, -1, -2): N = n - x**2 if isprime(N): y, z = prime_as_sum_of_two_squares(N) return _sorted_tuple(2**v*x, 2**v*y, 2**v*z) def sum_of_four_squares(n): r""" Returns a 4-tuple `(a, b, c, d)` such that `a^2 + b^2 + c^2 + d^2 = n`. Here `a, b, c, d \geq 0`. Usage ===== ``sum_of_four_squares(n)``: Here ``n`` is a non-negative integer. Examples ======== >>> from sympy.solvers.diophantine.diophantine import sum_of_four_squares >>> sum_of_four_squares(3456) (8, 8, 32, 48) >>> sum_of_four_squares(1294585930293) (0, 1234, 2161, 1137796) References ========== .. [1] Representing a number as a sum of four squares, [online], Available: http://schorn.ch/lagrange.html See Also ======== sum_of_squares() """ if n == 0: return (0, 0, 0, 0) v = multiplicity(4, n) n //= 4**v if n % 8 == 7: d = 2 n = n - 4 elif n % 8 == 6 or n % 8 == 2: d = 1 n = n - 1 else: d = 0 x, y, z = sum_of_three_squares(n) return _sorted_tuple(2**v*d, 2**v*x, 2**v*y, 2**v*z) def power_representation(n, p, k, zeros=False): r""" Returns a generator for finding k-tuples of integers, `(n_{1}, n_{2}, . . . n_{k})`, such that `n = n_{1}^p + n_{2}^p + . . . n_{k}^p`. Usage ===== ``power_representation(n, p, k, zeros)``: Represent non-negative number ``n`` as a sum of ``k`` ``p``\ th powers. If ``zeros`` is true, then the solutions is allowed to contain zeros. Examples ======== >>> from sympy.solvers.diophantine.diophantine import power_representation Represent 1729 as a sum of two cubes: >>> f = power_representation(1729, 3, 2) >>> next(f) (9, 10) >>> next(f) (1, 12) If the flag `zeros` is True, the solution may contain tuples with zeros; any such solutions will be generated after the solutions without zeros: >>> list(power_representation(125, 2, 3, zeros=True)) [(5, 6, 8), (3, 4, 10), (0, 5, 10), (0, 2, 11)] For even `p` the `permute_sign` function can be used to get all signed values: >>> from sympy.utilities.iterables import permute_signs >>> list(permute_signs((1, 12))) [(1, 12), (-1, 12), (1, -12), (-1, -12)] All possible signed permutations can also be obtained: >>> from sympy.utilities.iterables import signed_permutations >>> list(signed_permutations((1, 12))) [(1, 12), (-1, 12), (1, -12), (-1, -12), (12, 1), (-12, 1), (12, -1), (-12, -1)] """ n, p, k = [as_int(i) for i in (n, p, k)] if n < 0: if p % 2: for t in power_representation(-n, p, k, zeros): yield tuple(-i for i in t) return if p < 1 or k < 1: raise ValueError(filldedent(''' Expecting positive integers for `(p, k)`, but got `(%s, %s)`''' % (p, k))) if n == 0: if zeros: yield (0,)*k return if k == 1: if p == 1: yield (n,) else: be = perfect_power(n) if be: b, e = be d, r = divmod(e, p) if not r: yield (b**d,) return if p == 1: for t in partition(n, k, zeros=zeros): yield t return if p == 2: feasible = _can_do_sum_of_squares(n, k) if not feasible: return if not zeros and n > 33 and k >= 5 and k <= n and n - k in ( 13, 10, 7, 5, 4, 2, 1): '''Todd G. Will, "When Is n^2 a Sum of k Squares?", [online]. Available: https://www.maa.org/sites/default/files/Will-MMz-201037918.pdf''' return if feasible is not True: # it's prime and k == 2 yield prime_as_sum_of_two_squares(n) return if k == 2 and p > 2: be = perfect_power(n) if be and be[1] % p == 0: return # Fermat: a**n + b**n = c**n has no solution for n > 2 if n >= k: a = integer_nthroot(n - (k - 1), p)[0] for t in pow_rep_recursive(a, k, n, [], p): yield tuple(reversed(t)) if zeros: a = integer_nthroot(n, p)[0] for i in range(1, k): for t in pow_rep_recursive(a, i, n, [], p): yield tuple(reversed(t + (0,) * (k - i))) sum_of_powers = power_representation def pow_rep_recursive(n_i, k, n_remaining, terms, p): if k == 0 and n_remaining == 0: yield tuple(terms) else: if n_i >= 1 and k > 0: for t in pow_rep_recursive(n_i - 1, k, n_remaining, terms, p): yield t residual = n_remaining - pow(n_i, p) if residual >= 0: for t in pow_rep_recursive(n_i, k - 1, residual, terms + [n_i], p): yield t def sum_of_squares(n, k, zeros=False): """Return a generator that yields the k-tuples of nonnegative values, the squares of which sum to n. If zeros is False (default) then the solution will not contain zeros. The nonnegative elements of a tuple are sorted. * If k == 1 and n is square, (n,) is returned. * If k == 2 then n can only be written as a sum of squares if every prime in the factorization of n that has the form 4*k + 3 has an even multiplicity. If n is prime then it can only be written as a sum of two squares if it is in the form 4*k + 1. * if k == 3 then n can be written as a sum of squares if it does not have the form 4**m*(8*k + 7). * all integers can be written as the sum of 4 squares. * if k > 4 then n can be partitioned and each partition can be written as a sum of 4 squares; if n is not evenly divisible by 4 then n can be written as a sum of squares only if the an additional partition can be written as sum of squares. For example, if k = 6 then n is partitioned into two parts, the first being written as a sum of 4 squares and the second being written as a sum of 2 squares -- which can only be done if the condition above for k = 2 can be met, so this will automatically reject certain partitions of n. Examples ======== >>> from sympy.solvers.diophantine.diophantine import sum_of_squares >>> list(sum_of_squares(25, 2)) [(3, 4)] >>> list(sum_of_squares(25, 2, True)) [(3, 4), (0, 5)] >>> list(sum_of_squares(25, 4)) [(1, 2, 2, 4)] See Also ======== sympy.utilities.iterables.signed_permutations """ for t in power_representation(n, 2, k, zeros): yield t def _can_do_sum_of_squares(n, k): """Return True if n can be written as the sum of k squares, False if it can't, or 1 if k == 2 and n is prime (in which case it *can* be written as a sum of two squares). A False is returned only if it can't be written as k-squares, even if 0s are allowed. """ if k < 1: return False if n < 0: return False if n == 0: return True if k == 1: return is_square(n) if k == 2: if n in (1, 2): return True if isprime(n): if n % 4 == 1: return 1 # signal that it was prime return False else: f = factorint(n) for p, m in f.items(): # we can proceed iff no prime factor in the form 4*k + 3 # has an odd multiplicity if (p % 4 == 3) and m % 2: return False return True if k == 3: if (n//4**multiplicity(4, n)) % 8 == 7: return False # every number can be written as a sum of 4 squares; for k > 4 partitions # can be 0 return True
8c090876a2eb58cc6eb545e12888b3837870aada36875565729196c1d62a7935
r""" This module contains :py:meth:`~sympy.solvers.ode.dsolve` and different helper functions that it uses. :py:meth:`~sympy.solvers.ode.dsolve` solves ordinary differential equations. See the docstring on the various functions for their uses. Note that partial differential equations support is in ``pde.py``. Note that hint functions have docstrings describing their various methods, but they are intended for internal use. Use ``dsolve(ode, func, hint=hint)`` to solve an ODE using a specific hint. See also the docstring on :py:meth:`~sympy.solvers.ode.dsolve`. **Functions in this module** These are the user functions in this module: - :py:meth:`~sympy.solvers.ode.dsolve` - Solves ODEs. - :py:meth:`~sympy.solvers.ode.classify_ode` - Classifies ODEs into possible hints for :py:meth:`~sympy.solvers.ode.dsolve`. - :py:meth:`~sympy.solvers.ode.checkodesol` - Checks if an equation is the solution to an ODE. - :py:meth:`~sympy.solvers.ode.homogeneous_order` - Returns the homogeneous order of an expression. - :py:meth:`~sympy.solvers.ode.infinitesimals` - Returns the infinitesimals of the Lie group of point transformations of an ODE, such that it is invariant. - :py:meth:`~sympy.solvers.ode.checkinfsol` - Checks if the given infinitesimals are the actual infinitesimals of a first order ODE. These are the non-solver helper functions that are for internal use. The user should use the various options to :py:meth:`~sympy.solvers.ode.dsolve` to obtain the functionality provided by these functions: - :py:meth:`~sympy.solvers.ode.ode.odesimp` - Does all forms of ODE simplification. - :py:meth:`~sympy.solvers.ode.ode.ode_sol_simplicity` - A key function for comparing solutions by simplicity. - :py:meth:`~sympy.solvers.ode.constantsimp` - Simplifies arbitrary constants. - :py:meth:`~sympy.solvers.ode.ode.constant_renumber` - Renumber arbitrary constants. - :py:meth:`~sympy.solvers.ode.ode._handle_Integral` - Evaluate unevaluated Integrals. See also the docstrings of these functions. **Currently implemented solver methods** The following methods are implemented for solving ordinary differential equations. See the docstrings of the various hint functions for more information on each (run ``help(ode)``): - 1st order separable differential equations. - 1st order differential equations whose coefficients or `dx` and `dy` are functions homogeneous of the same order. - 1st order exact differential equations. - 1st order linear differential equations. - 1st order Bernoulli differential equations. - Power series solutions for first order differential equations. - Lie Group method of solving first order differential equations. - 2nd order Liouville differential equations. - Power series solutions for second order differential equations at ordinary and regular singular points. - `n`\th order differential equation that can be solved with algebraic rearrangement and integration. - `n`\th order linear homogeneous differential equation with constant coefficients. - `n`\th order linear inhomogeneous differential equation with constant coefficients using the method of undetermined coefficients. - `n`\th order linear inhomogeneous differential equation with constant coefficients using the method of variation of parameters. **Philosophy behind this module** This module is designed to make it easy to add new ODE solving methods without having to mess with the solving code for other methods. The idea is that there is a :py:meth:`~sympy.solvers.ode.classify_ode` function, which takes in an ODE and tells you what hints, if any, will solve the ODE. It does this without attempting to solve the ODE, so it is fast. Each solving method is a hint, and it has its own function, named ``ode_<hint>``. That function takes in the ODE and any match expression gathered by :py:meth:`~sympy.solvers.ode.classify_ode` and returns a solved result. If this result has any integrals in it, the hint function will return an unevaluated :py:class:`~sympy.integrals.integrals.Integral` class. :py:meth:`~sympy.solvers.ode.dsolve`, which is the user wrapper function around all of this, will then call :py:meth:`~sympy.solvers.ode.ode.odesimp` on the result, which, among other things, will attempt to solve the equation for the dependent variable (the function we are solving for), simplify the arbitrary constants in the expression, and evaluate any integrals, if the hint allows it. **How to add new solution methods** If you have an ODE that you want :py:meth:`~sympy.solvers.ode.dsolve` to be able to solve, try to avoid adding special case code here. Instead, try finding a general method that will solve your ODE, as well as others. This way, the :py:mod:`~sympy.solvers.ode` module will become more robust, and unhindered by special case hacks. WolphramAlpha and Maple's DETools[odeadvisor] function are two resources you can use to classify a specific ODE. It is also better for a method to work with an `n`\th order ODE instead of only with specific orders, if possible. To add a new method, there are a few things that you need to do. First, you need a hint name for your method. Try to name your hint so that it is unambiguous with all other methods, including ones that may not be implemented yet. If your method uses integrals, also include a ``hint_Integral`` hint. If there is more than one way to solve ODEs with your method, include a hint for each one, as well as a ``<hint>_best`` hint. Your ``ode_<hint>_best()`` function should choose the best using min with ``ode_sol_simplicity`` as the key argument. See :py:meth:`~sympy.solvers.ode.ode.ode_1st_homogeneous_coeff_best`, for example. The function that uses your method will be called ``ode_<hint>()``, so the hint must only use characters that are allowed in a Python function name (alphanumeric characters and the underscore '``_``' character). Include a function for every hint, except for ``_Integral`` hints (:py:meth:`~sympy.solvers.ode.dsolve` takes care of those automatically). Hint names should be all lowercase, unless a word is commonly capitalized (such as Integral or Bernoulli). If you have a hint that you do not want to run with ``all_Integral`` that doesn't have an ``_Integral`` counterpart (such as a best hint that would defeat the purpose of ``all_Integral``), you will need to remove it manually in the :py:meth:`~sympy.solvers.ode.dsolve` code. See also the :py:meth:`~sympy.solvers.ode.classify_ode` docstring for guidelines on writing a hint name. Determine *in general* how the solutions returned by your method compare with other methods that can potentially solve the same ODEs. Then, put your hints in the :py:data:`~sympy.solvers.ode.allhints` tuple in the order that they should be called. The ordering of this tuple determines which hints are default. Note that exceptions are ok, because it is easy for the user to choose individual hints with :py:meth:`~sympy.solvers.ode.dsolve`. In general, ``_Integral`` variants should go at the end of the list, and ``_best`` variants should go before the various hints they apply to. For example, the ``undetermined_coefficients`` hint comes before the ``variation_of_parameters`` hint because, even though variation of parameters is more general than undetermined coefficients, undetermined coefficients generally returns cleaner results for the ODEs that it can solve than variation of parameters does, and it does not require integration, so it is much faster. Next, you need to have a match expression or a function that matches the type of the ODE, which you should put in :py:meth:`~sympy.solvers.ode.classify_ode` (if the match function is more than just a few lines, like :py:meth:`~sympy.solvers.ode.ode._undetermined_coefficients_match`, it should go outside of :py:meth:`~sympy.solvers.ode.classify_ode`). It should match the ODE without solving for it as much as possible, so that :py:meth:`~sympy.solvers.ode.classify_ode` remains fast and is not hindered by bugs in solving code. Be sure to consider corner cases. For example, if your solution method involves dividing by something, make sure you exclude the case where that division will be 0. In most cases, the matching of the ODE will also give you the various parts that you need to solve it. You should put that in a dictionary (``.match()`` will do this for you), and add that as ``matching_hints['hint'] = matchdict`` in the relevant part of :py:meth:`~sympy.solvers.ode.classify_ode`. :py:meth:`~sympy.solvers.ode.classify_ode` will then send this to :py:meth:`~sympy.solvers.ode.dsolve`, which will send it to your function as the ``match`` argument. Your function should be named ``ode_<hint>(eq, func, order, match)`. If you need to send more information, put it in the ``match`` dictionary. For example, if you had to substitute in a dummy variable in :py:meth:`~sympy.solvers.ode.classify_ode` to match the ODE, you will need to pass it to your function using the `match` dict to access it. You can access the independent variable using ``func.args[0]``, and the dependent variable (the function you are trying to solve for) as ``func.func``. If, while trying to solve the ODE, you find that you cannot, raise ``NotImplementedError``. :py:meth:`~sympy.solvers.ode.dsolve` will catch this error with the ``all`` meta-hint, rather than causing the whole routine to fail. Add a docstring to your function that describes the method employed. Like with anything else in SymPy, you will need to add a doctest to the docstring, in addition to real tests in ``test_ode.py``. Try to maintain consistency with the other hint functions' docstrings. Add your method to the list at the top of this docstring. Also, add your method to ``ode.rst`` in the ``docs/src`` directory, so that the Sphinx docs will pull its docstring into the main SymPy documentation. Be sure to make the Sphinx documentation by running ``make html`` from within the doc directory to verify that the docstring formats correctly. If your solution method involves integrating, use :py:obj:`~.Integral` instead of :py:meth:`~sympy.core.expr.Expr.integrate`. This allows the user to bypass hard/slow integration by using the ``_Integral`` variant of your hint. In most cases, calling :py:meth:`sympy.core.basic.Basic.doit` will integrate your solution. If this is not the case, you will need to write special code in :py:meth:`~sympy.solvers.ode.ode._handle_Integral`. Arbitrary constants should be symbols named ``C1``, ``C2``, and so on. All solution methods should return an equality instance. If you need an arbitrary number of arbitrary constants, you can use ``constants = numbered_symbols(prefix='C', cls=Symbol, start=1)``. If it is possible to solve for the dependent function in a general way, do so. Otherwise, do as best as you can, but do not call solve in your ``ode_<hint>()`` function. :py:meth:`~sympy.solvers.ode.ode.odesimp` will attempt to solve the solution for you, so you do not need to do that. Lastly, if your ODE has a common simplification that can be applied to your solutions, you can add a special case in :py:meth:`~sympy.solvers.ode.ode.odesimp` for it. For example, solutions returned from the ``1st_homogeneous_coeff`` hints often have many :obj:`~sympy.functions.elementary.exponential.log` terms, so :py:meth:`~sympy.solvers.ode.ode.odesimp` calls :py:meth:`~sympy.simplify.simplify.logcombine` on them (it also helps to write the arbitrary constant as ``log(C1)`` instead of ``C1`` in this case). Also consider common ways that you can rearrange your solution to have :py:meth:`~sympy.solvers.ode.constantsimp` take better advantage of it. It is better to put simplification in :py:meth:`~sympy.solvers.ode.ode.odesimp` than in your method, because it can then be turned off with the simplify flag in :py:meth:`~sympy.solvers.ode.dsolve`. If you have any extraneous simplification in your function, be sure to only run it using ``if match.get('simplify', True):``, especially if it can be slow or if it can reduce the domain of the solution. Finally, as with every contribution to SymPy, your method will need to be tested. Add a test for each method in ``test_ode.py``. Follow the conventions there, i.e., test the solver using ``dsolve(eq, f(x), hint=your_hint)``, and also test the solution using :py:meth:`~sympy.solvers.ode.checkodesol` (you can put these in a separate tests and skip/XFAIL if it runs too slow/doesn't work). Be sure to call your hint specifically in :py:meth:`~sympy.solvers.ode.dsolve`, that way the test won't be broken simply by the introduction of another matching hint. If your method works for higher order (>1) ODEs, you will need to run ``sol = constant_renumber(sol, 'C', 1, order)`` for each solution, where ``order`` is the order of the ODE. This is because ``constant_renumber`` renumbers the arbitrary constants by printing order, which is platform dependent. Try to test every corner case of your solver, including a range of orders if it is a `n`\th order solver, but if your solver is slow, such as if it involves hard integration, try to keep the test run time down. Feel free to refactor existing hints to avoid duplicating code or creating inconsistencies. If you can show that your method exactly duplicates an existing method, including in the simplicity and speed of obtaining the solutions, then you can remove the old, less general method. The existing code is tested extensively in ``test_ode.py``, so if anything is broken, one of those tests will surely fail. """ from __future__ import print_function, division from typing import Dict, Type from collections import defaultdict from itertools import islice from sympy.functions import hyper from sympy.core import Add, S, Mul, Pow, oo, Rational from sympy.core.compatibility import ordered, iterable from sympy.core.containers import Tuple from sympy.core.exprtools import factor_terms from sympy.core.expr import AtomicExpr, Expr from sympy.core.function import (Function, Derivative, AppliedUndef, diff, expand, expand_mul, Subs, _mexpand) from sympy.core.multidimensional import vectorize from sympy.core.numbers import NaN, zoo, I, Number from sympy.core.relational import Equality, Eq from sympy.core.symbol import Symbol, Wild, Dummy, symbols from sympy.core.sympify import sympify from sympy.logic.boolalg import (BooleanAtom, And, Not, BooleanTrue, BooleanFalse) from sympy.functions import cos, cosh, exp, im, log, re, sin, sinh, tan, sqrt, \ atan2, conjugate, Piecewise, cbrt, besselj, bessely, airyai, airybi from sympy.functions.combinatorial.factorials import factorial from sympy.integrals.integrals import Integral, integrate from sympy.matrices import wronskian, Matrix, eye, zeros from sympy.polys import (Poly, RootOf, rootof, terms_gcd, PolynomialError, lcm, roots, gcd) from sympy.polys.polyroots import roots_quartic from sympy.polys.polytools import cancel, degree, div from sympy.series import Order from sympy.series.series import series from sympy.simplify import (collect, logcombine, powsimp, # type: ignore separatevars, simplify, trigsimp, posify, cse) from sympy.simplify.powsimp import powdenest from sympy.simplify.radsimp import collect_const, fraction from sympy.solvers import checksol, solve from sympy.solvers.pde import pdsolve from sympy.utilities import numbered_symbols, default_sort_key, sift from sympy.solvers.deutils import _preprocess, ode_order, _desolve from .subscheck import sub_func_doit #: This is a list of hints in the order that they should be preferred by #: :py:meth:`~sympy.solvers.ode.classify_ode`. In general, hints earlier in the #: list should produce simpler solutions than those later in the list (for #: ODEs that fit both). For now, the order of this list is based on empirical #: observations by the developers of SymPy. #: #: The hint used by :py:meth:`~sympy.solvers.ode.dsolve` for a specific ODE #: can be overridden (see the docstring). #: #: In general, ``_Integral`` hints are grouped at the end of the list, unless #: there is a method that returns an unevaluable integral most of the time #: (which go near the end of the list anyway). ``default``, ``all``, #: ``best``, and ``all_Integral`` meta-hints should not be included in this #: list, but ``_best`` and ``_Integral`` hints should be included. allhints = ( "factorable", "nth_algebraic", "separable", "1st_exact", "1st_linear", "Bernoulli", "Riccati_special_minus2", "1st_homogeneous_coeff_best", "1st_homogeneous_coeff_subs_indep_div_dep", "1st_homogeneous_coeff_subs_dep_div_indep", "almost_linear", "linear_coefficients", "separable_reduced", "1st_power_series", "lie_group", "nth_linear_constant_coeff_homogeneous", "nth_linear_euler_eq_homogeneous", "nth_linear_constant_coeff_undetermined_coefficients", "nth_linear_euler_eq_nonhomogeneous_undetermined_coefficients", "nth_linear_constant_coeff_variation_of_parameters", "nth_linear_euler_eq_nonhomogeneous_variation_of_parameters", "Liouville", "2nd_linear_airy", "2nd_linear_bessel", "2nd_hypergeometric", "2nd_hypergeometric_Integral", "nth_order_reducible", "2nd_power_series_ordinary", "2nd_power_series_regular", "nth_algebraic_Integral", "separable_Integral", "1st_exact_Integral", "1st_linear_Integral", "Bernoulli_Integral", "1st_homogeneous_coeff_subs_indep_div_dep_Integral", "1st_homogeneous_coeff_subs_dep_div_indep_Integral", "almost_linear_Integral", "linear_coefficients_Integral", "separable_reduced_Integral", "nth_linear_constant_coeff_variation_of_parameters_Integral", "nth_linear_euler_eq_nonhomogeneous_variation_of_parameters_Integral", "Liouville_Integral", ) lie_heuristics = ( "abaco1_simple", "abaco1_product", "abaco2_similar", "abaco2_unique_unknown", "abaco2_unique_general", "linear", "function_sum", "bivariate", "chi" ) def get_numbered_constants(eq, num=1, start=1, prefix='C'): """ Returns a list of constants that do not occur in eq already. """ ncs = iter_numbered_constants(eq, start, prefix) Cs = [next(ncs) for i in range(num)] return (Cs[0] if num == 1 else tuple(Cs)) def iter_numbered_constants(eq, start=1, prefix='C'): """ Returns an iterator of constants that do not occur in eq already. """ if isinstance(eq, (Expr, Eq)): eq = [eq] elif not iterable(eq): raise ValueError("Expected Expr or iterable but got %s" % eq) atom_set = set().union(*[i.free_symbols for i in eq]) func_set = set().union(*[i.atoms(Function) for i in eq]) if func_set: atom_set |= {Symbol(str(f.func)) for f in func_set} return numbered_symbols(start=start, prefix=prefix, exclude=atom_set) def dsolve(eq, func=None, hint="default", simplify=True, ics= None, xi=None, eta=None, x0=0, n=6, **kwargs): r""" Solves any (supported) kind of ordinary differential equation and system of ordinary differential equations. For single ordinary differential equation ========================================= It is classified under this when number of equation in ``eq`` is one. **Usage** ``dsolve(eq, f(x), hint)`` -> Solve ordinary differential equation ``eq`` for function ``f(x)``, using method ``hint``. **Details** ``eq`` can be any supported ordinary differential equation (see the :py:mod:`~sympy.solvers.ode` docstring for supported methods). This can either be an :py:class:`~sympy.core.relational.Equality`, or an expression, which is assumed to be equal to ``0``. ``f(x)`` is a function of one variable whose derivatives in that variable make up the ordinary differential equation ``eq``. In many cases it is not necessary to provide this; it will be autodetected (and an error raised if it couldn't be detected). ``hint`` is the solving method that you want dsolve to use. Use ``classify_ode(eq, f(x))`` to get all of the possible hints for an ODE. The default hint, ``default``, will use whatever hint is returned first by :py:meth:`~sympy.solvers.ode.classify_ode`. See Hints below for more options that you can use for hint. ``simplify`` enables simplification by :py:meth:`~sympy.solvers.ode.ode.odesimp`. See its docstring for more information. Turn this off, for example, to disable solving of solutions for ``func`` or simplification of arbitrary constants. It will still integrate with this hint. Note that the solution may contain more arbitrary constants than the order of the ODE with this option enabled. ``xi`` and ``eta`` are the infinitesimal functions of an ordinary differential equation. They are the infinitesimals of the Lie group of point transformations for which the differential equation is invariant. The user can specify values for the infinitesimals. If nothing is specified, ``xi`` and ``eta`` are calculated using :py:meth:`~sympy.solvers.ode.infinitesimals` with the help of various heuristics. ``ics`` is the set of initial/boundary conditions for the differential equation. It should be given in the form of ``{f(x0): x1, f(x).diff(x).subs(x, x2): x3}`` and so on. For power series solutions, if no initial conditions are specified ``f(0)`` is assumed to be ``C0`` and the power series solution is calculated about 0. ``x0`` is the point about which the power series solution of a differential equation is to be evaluated. ``n`` gives the exponent of the dependent variable up to which the power series solution of a differential equation is to be evaluated. **Hints** Aside from the various solving methods, there are also some meta-hints that you can pass to :py:meth:`~sympy.solvers.ode.dsolve`: ``default``: This uses whatever hint is returned first by :py:meth:`~sympy.solvers.ode.classify_ode`. This is the default argument to :py:meth:`~sympy.solvers.ode.dsolve`. ``all``: To make :py:meth:`~sympy.solvers.ode.dsolve` apply all relevant classification hints, use ``dsolve(ODE, func, hint="all")``. This will return a dictionary of ``hint:solution`` terms. If a hint causes dsolve to raise the ``NotImplementedError``, value of that hint's key will be the exception object raised. The dictionary will also include some special keys: - ``order``: The order of the ODE. See also :py:meth:`~sympy.solvers.deutils.ode_order` in ``deutils.py``. - ``best``: The simplest hint; what would be returned by ``best`` below. - ``best_hint``: The hint that would produce the solution given by ``best``. If more than one hint produces the best solution, the first one in the tuple returned by :py:meth:`~sympy.solvers.ode.classify_ode` is chosen. - ``default``: The solution that would be returned by default. This is the one produced by the hint that appears first in the tuple returned by :py:meth:`~sympy.solvers.ode.classify_ode`. ``all_Integral``: This is the same as ``all``, except if a hint also has a corresponding ``_Integral`` hint, it only returns the ``_Integral`` hint. This is useful if ``all`` causes :py:meth:`~sympy.solvers.ode.dsolve` to hang because of a difficult or impossible integral. This meta-hint will also be much faster than ``all``, because :py:meth:`~sympy.core.expr.Expr.integrate` is an expensive routine. ``best``: To have :py:meth:`~sympy.solvers.ode.dsolve` try all methods and return the simplest one. This takes into account whether the solution is solvable in the function, whether it contains any Integral classes (i.e. unevaluatable integrals), and which one is the shortest in size. See also the :py:meth:`~sympy.solvers.ode.classify_ode` docstring for more info on hints, and the :py:mod:`~sympy.solvers.ode` docstring for a list of all supported hints. **Tips** - You can declare the derivative of an unknown function this way: >>> from sympy import Function, Derivative >>> from sympy.abc import x # x is the independent variable >>> f = Function("f")(x) # f is a function of x >>> # f_ will be the derivative of f with respect to x >>> f_ = Derivative(f, x) - See ``test_ode.py`` for many tests, which serves also as a set of examples for how to use :py:meth:`~sympy.solvers.ode.dsolve`. - :py:meth:`~sympy.solvers.ode.dsolve` always returns an :py:class:`~sympy.core.relational.Equality` class (except for the case when the hint is ``all`` or ``all_Integral``). If possible, it solves the solution explicitly for the function being solved for. Otherwise, it returns an implicit solution. - Arbitrary constants are symbols named ``C1``, ``C2``, and so on. - Because all solutions should be mathematically equivalent, some hints may return the exact same result for an ODE. Often, though, two different hints will return the same solution formatted differently. The two should be equivalent. Also note that sometimes the values of the arbitrary constants in two different solutions may not be the same, because one constant may have "absorbed" other constants into it. - Do ``help(ode.ode_<hintname>)`` to get help more information on a specific hint, where ``<hintname>`` is the name of a hint without ``_Integral``. For system of ordinary differential equations ============================================= **Usage** ``dsolve(eq, func)`` -> Solve a system of ordinary differential equations ``eq`` for ``func`` being list of functions including `x(t)`, `y(t)`, `z(t)` where number of functions in the list depends upon the number of equations provided in ``eq``. **Details** ``eq`` can be any supported system of ordinary differential equations This can either be an :py:class:`~sympy.core.relational.Equality`, or an expression, which is assumed to be equal to ``0``. ``func`` holds ``x(t)`` and ``y(t)`` being functions of one variable which together with some of their derivatives make up the system of ordinary differential equation ``eq``. It is not necessary to provide this; it will be autodetected (and an error raised if it couldn't be detected). **Hints** The hints are formed by parameters returned by classify_sysode, combining them give hints name used later for forming method name. Examples ======== >>> from sympy import Function, dsolve, Eq, Derivative, sin, cos, symbols >>> from sympy.abc import x >>> f = Function('f') >>> dsolve(Derivative(f(x), x, x) + 9*f(x), f(x)) Eq(f(x), C1*sin(3*x) + C2*cos(3*x)) >>> eq = sin(x)*cos(f(x)) + cos(x)*sin(f(x))*f(x).diff(x) >>> dsolve(eq, hint='1st_exact') [Eq(f(x), -acos(C1/cos(x)) + 2*pi), Eq(f(x), acos(C1/cos(x)))] >>> dsolve(eq, hint='almost_linear') [Eq(f(x), -acos(C1/cos(x)) + 2*pi), Eq(f(x), acos(C1/cos(x)))] >>> t = symbols('t') >>> x, y = symbols('x, y', cls=Function) >>> eq = (Eq(Derivative(x(t),t), 12*t*x(t) + 8*y(t)), Eq(Derivative(y(t),t), 21*x(t) + 7*t*y(t))) >>> dsolve(eq) [Eq(x(t), C1*x0(t) + C2*x0(t)*Integral(8*exp(Integral(7*t, t))*exp(Integral(12*t, t))/x0(t)**2, t)), Eq(y(t), C1*y0(t) + C2*(y0(t)*Integral(8*exp(Integral(7*t, t))*exp(Integral(12*t, t))/x0(t)**2, t) + exp(Integral(7*t, t))*exp(Integral(12*t, t))/x0(t)))] >>> eq = (Eq(Derivative(x(t),t),x(t)*y(t)*sin(t)), Eq(Derivative(y(t),t),y(t)**2*sin(t))) >>> dsolve(eq) {Eq(x(t), -exp(C1)/(C2*exp(C1) - cos(t))), Eq(y(t), -1/(C1 - cos(t)))} """ if iterable(eq): match = classify_sysode(eq, func) eq = match['eq'] order = match['order'] func = match['func'] t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0] # keep highest order term coefficient positive for i in range(len(eq)): for func_ in func: if isinstance(func_, list): pass else: if eq[i].coeff(diff(func[i],t,ode_order(eq[i], func[i]))).is_negative: eq[i] = -eq[i] match['eq'] = eq if len(set(order.values()))!=1: raise ValueError("It solves only those systems of equations whose orders are equal") match['order'] = list(order.values())[0] def recur_len(l): return sum(recur_len(item) if isinstance(item,list) else 1 for item in l) if recur_len(func) != len(eq): raise ValueError("dsolve() and classify_sysode() work with " "number of functions being equal to number of equations") if match['type_of_equation'] is None: raise NotImplementedError else: if match['is_linear'] == True: if match['no_of_equation'] > 3: solvefunc = globals()['sysode_linear_neq_order%(order)s' % match] else: solvefunc = globals()['sysode_linear_%(no_of_equation)seq_order%(order)s' % match] else: solvefunc = globals()['sysode_nonlinear_%(no_of_equation)seq_order%(order)s' % match] sols = solvefunc(match) if ics: constants = Tuple(*sols).free_symbols - Tuple(*eq).free_symbols solved_constants = solve_ics(sols, func, constants, ics) return [sol.subs(solved_constants) for sol in sols] return sols else: given_hint = hint # hint given by the user # See the docstring of _desolve for more details. hints = _desolve(eq, func=func, hint=hint, simplify=True, xi=xi, eta=eta, type='ode', ics=ics, x0=x0, n=n, **kwargs) eq = hints.pop('eq', eq) all_ = hints.pop('all', False) if all_: retdict = {} failed_hints = {} gethints = classify_ode(eq, dict=True) orderedhints = gethints['ordered_hints'] for hint in hints: try: rv = _helper_simplify(eq, hint, hints[hint], simplify) except NotImplementedError as detail: failed_hints[hint] = detail else: retdict[hint] = rv func = hints[hint]['func'] retdict['best'] = min(list(retdict.values()), key=lambda x: ode_sol_simplicity(x, func, trysolving=not simplify)) if given_hint == 'best': return retdict['best'] for i in orderedhints: if retdict['best'] == retdict.get(i, None): retdict['best_hint'] = i break retdict['default'] = gethints['default'] retdict['order'] = gethints['order'] retdict.update(failed_hints) return retdict else: # The key 'hint' stores the hint needed to be solved for. hint = hints['hint'] return _helper_simplify(eq, hint, hints, simplify, ics=ics) def _helper_simplify(eq, hint, match, simplify=True, ics=None, **kwargs): r""" Helper function of dsolve that calls the respective :py:mod:`~sympy.solvers.ode` functions to solve for the ordinary differential equations. This minimizes the computation in calling :py:meth:`~sympy.solvers.deutils._desolve` multiple times. """ r = match if hint.endswith('_Integral'): solvefunc = globals()['ode_' + hint[:-len('_Integral')]] else: solvefunc = globals()['ode_' + hint] func = r['func'] order = r['order'] match = r[hint] free = eq.free_symbols cons = lambda s: s.free_symbols.difference(free) if simplify: # odesimp() will attempt to integrate, if necessary, apply constantsimp(), # attempt to solve for func, and apply any other hint specific # simplifications sols = solvefunc(eq, func, order, match) if iterable(sols): rv = [odesimp(eq, s, func, hint) for s in sols] else: rv = odesimp(eq, sols, func, hint) else: # We still want to integrate (you can disable it separately with the hint) match['simplify'] = False # Some hints can take advantage of this option exprs = solvefunc(eq, func, order, match) if isinstance(exprs, list): rv = [_handle_Integral(expr, func, hint) for expr in exprs] else: rv = _handle_Integral(exprs, func, hint) if isinstance(rv, list): rv = _remove_redundant_solutions(eq, rv, order, func.args[0]) if len(rv) == 1: rv = rv[0] if ics and not 'power_series' in hint: if isinstance(rv, (Expr, Eq)): solved_constants = solve_ics([rv], [r['func']], cons(rv), ics) rv = rv.subs(solved_constants) else: rv1 = [] for s in rv: try: solved_constants = solve_ics([s], [r['func']], cons(s), ics) except ValueError: continue rv1.append(s.subs(solved_constants)) if len(rv1) == 1: return rv1[0] rv = rv1 return rv def solve_ics(sols, funcs, constants, ics): """ Solve for the constants given initial conditions ``sols`` is a list of solutions. ``funcs`` is a list of functions. ``constants`` is a list of constants. ``ics`` is the set of initial/boundary conditions for the differential equation. It should be given in the form of ``{f(x0): x1, f(x).diff(x).subs(x, x2): x3}`` and so on. Returns a dictionary mapping constants to values. ``solution.subs(constants)`` will replace the constants in ``solution``. Example ======= >>> # From dsolve(f(x).diff(x) - f(x), f(x)) >>> from sympy import symbols, Eq, exp, Function >>> from sympy.solvers.ode.ode import solve_ics >>> f = Function('f') >>> x, C1 = symbols('x C1') >>> sols = [Eq(f(x), C1*exp(x))] >>> funcs = [f(x)] >>> constants = [C1] >>> ics = {f(0): 2} >>> solved_constants = solve_ics(sols, funcs, constants, ics) >>> solved_constants {C1: 2} >>> sols[0].subs(solved_constants) Eq(f(x), 2*exp(x)) """ # Assume ics are of the form f(x0): value or Subs(diff(f(x), x, n), (x, # x0)): value (currently checked by classify_ode). To solve, replace x # with x0, f(x0) with value, then solve for constants. For f^(n)(x0), # differentiate the solution n times, so that f^(n)(x) appears. x = funcs[0].args[0] diff_sols = [] subs_sols = [] diff_variables = set() for funcarg, value in ics.items(): if isinstance(funcarg, AppliedUndef): x0 = funcarg.args[0] matching_func = [f for f in funcs if f.func == funcarg.func][0] S = sols elif isinstance(funcarg, (Subs, Derivative)): if isinstance(funcarg, Subs): # Make sure it stays a subs. Otherwise subs below will produce # a different looking term. funcarg = funcarg.doit() if isinstance(funcarg, Subs): deriv = funcarg.expr x0 = funcarg.point[0] variables = funcarg.expr.variables matching_func = deriv elif isinstance(funcarg, Derivative): deriv = funcarg x0 = funcarg.variables[0] variables = (x,)*len(funcarg.variables) matching_func = deriv.subs(x0, x) if variables not in diff_variables: for sol in sols: if sol.has(deriv.expr.func): diff_sols.append(Eq(sol.lhs.diff(*variables), sol.rhs.diff(*variables))) diff_variables.add(variables) S = diff_sols else: raise NotImplementedError("Unrecognized initial condition") for sol in S: if sol.has(matching_func): sol2 = sol sol2 = sol2.subs(x, x0) sol2 = sol2.subs(funcarg, value) # This check is necessary because of issue #15724 if not isinstance(sol2, BooleanAtom) or not subs_sols: subs_sols = [s for s in subs_sols if not isinstance(s, BooleanAtom)] subs_sols.append(sol2) # TODO: Use solveset here try: solved_constants = solve(subs_sols, constants, dict=True) except NotImplementedError: solved_constants = [] # XXX: We can't differentiate between the solution not existing because of # invalid initial conditions, and not existing because solve is not smart # enough. If we could use solveset, this might be improvable, but for now, # we use NotImplementedError in this case. if not solved_constants: raise ValueError("Couldn't solve for initial conditions") if solved_constants == True: raise ValueError("Initial conditions did not produce any solutions for constants. Perhaps they are degenerate.") if len(solved_constants) > 1: raise NotImplementedError("Initial conditions produced too many solutions for constants") return solved_constants[0] def classify_ode(eq, func=None, dict=False, ics=None, **kwargs): r""" Returns a tuple of possible :py:meth:`~sympy.solvers.ode.dsolve` classifications for an ODE. The tuple is ordered so that first item is the classification that :py:meth:`~sympy.solvers.ode.dsolve` uses to solve the ODE by default. In general, classifications at the near the beginning of the list will produce better solutions faster than those near the end, thought there are always exceptions. To make :py:meth:`~sympy.solvers.ode.dsolve` use a different classification, use ``dsolve(ODE, func, hint=<classification>)``. See also the :py:meth:`~sympy.solvers.ode.dsolve` docstring for different meta-hints you can use. If ``dict`` is true, :py:meth:`~sympy.solvers.ode.classify_ode` will return a dictionary of ``hint:match`` expression terms. This is intended for internal use by :py:meth:`~sympy.solvers.ode.dsolve`. Note that because dictionaries are ordered arbitrarily, this will most likely not be in the same order as the tuple. You can get help on different hints by executing ``help(ode.ode_hintname)``, where ``hintname`` is the name of the hint without ``_Integral``. See :py:data:`~sympy.solvers.ode.allhints` or the :py:mod:`~sympy.solvers.ode` docstring for a list of all supported hints that can be returned from :py:meth:`~sympy.solvers.ode.classify_ode`. Notes ===== These are remarks on hint names. ``_Integral`` If a classification has ``_Integral`` at the end, it will return the expression with an unevaluated :py:class:`~.Integral` class in it. Note that a hint may do this anyway if :py:meth:`~sympy.core.expr.Expr.integrate` cannot do the integral, though just using an ``_Integral`` will do so much faster. Indeed, an ``_Integral`` hint will always be faster than its corresponding hint without ``_Integral`` because :py:meth:`~sympy.core.expr.Expr.integrate` is an expensive routine. If :py:meth:`~sympy.solvers.ode.dsolve` hangs, it is probably because :py:meth:`~sympy.core.expr.Expr.integrate` is hanging on a tough or impossible integral. Try using an ``_Integral`` hint or ``all_Integral`` to get it return something. Note that some hints do not have ``_Integral`` counterparts. This is because :py:func:`~sympy.integrals.integrals.integrate` is not used in solving the ODE for those method. For example, `n`\th order linear homogeneous ODEs with constant coefficients do not require integration to solve, so there is no ``nth_linear_homogeneous_constant_coeff_Integrate`` hint. You can easily evaluate any unevaluated :py:class:`~sympy.integrals.integrals.Integral`\s in an expression by doing ``expr.doit()``. Ordinals Some hints contain an ordinal such as ``1st_linear``. This is to help differentiate them from other hints, as well as from other methods that may not be implemented yet. If a hint has ``nth`` in it, such as the ``nth_linear`` hints, this means that the method used to applies to ODEs of any order. ``indep`` and ``dep`` Some hints contain the words ``indep`` or ``dep``. These reference the independent variable and the dependent function, respectively. For example, if an ODE is in terms of `f(x)`, then ``indep`` will refer to `x` and ``dep`` will refer to `f`. ``subs`` If a hints has the word ``subs`` in it, it means the the ODE is solved by substituting the expression given after the word ``subs`` for a single dummy variable. This is usually in terms of ``indep`` and ``dep`` as above. The substituted expression will be written only in characters allowed for names of Python objects, meaning operators will be spelled out. For example, ``indep``/``dep`` will be written as ``indep_div_dep``. ``coeff`` The word ``coeff`` in a hint refers to the coefficients of something in the ODE, usually of the derivative terms. See the docstring for the individual methods for more info (``help(ode)``). This is contrast to ``coefficients``, as in ``undetermined_coefficients``, which refers to the common name of a method. ``_best`` Methods that have more than one fundamental way to solve will have a hint for each sub-method and a ``_best`` meta-classification. This will evaluate all hints and return the best, using the same considerations as the normal ``best`` meta-hint. Examples ======== >>> from sympy import Function, classify_ode, Eq >>> from sympy.abc import x >>> f = Function('f') >>> classify_ode(Eq(f(x).diff(x), 0), f(x)) ('nth_algebraic', 'separable', '1st_linear', '1st_homogeneous_coeff_best', '1st_homogeneous_coeff_subs_indep_div_dep', '1st_homogeneous_coeff_subs_dep_div_indep', '1st_power_series', 'lie_group', 'nth_linear_constant_coeff_homogeneous', 'nth_linear_euler_eq_homogeneous', 'nth_algebraic_Integral', 'separable_Integral', '1st_linear_Integral', '1st_homogeneous_coeff_subs_indep_div_dep_Integral', '1st_homogeneous_coeff_subs_dep_div_indep_Integral') >>> classify_ode(f(x).diff(x, 2) + 3*f(x).diff(x) + 2*f(x) - 4) ('nth_linear_constant_coeff_undetermined_coefficients', 'nth_linear_constant_coeff_variation_of_parameters', 'nth_linear_constant_coeff_variation_of_parameters_Integral') """ ics = sympify(ics) prep = kwargs.pop('prep', True) if func and len(func.args) != 1: raise ValueError("dsolve() and classify_ode() only " "work with functions of one variable, not %s" % func) # Some methods want the unprocessed equation eq_orig = eq if prep or func is None: eq, func_ = _preprocess(eq, func) if func is None: func = func_ x = func.args[0] f = func.func y = Dummy('y') xi = kwargs.get('xi') eta = kwargs.get('eta') terms = kwargs.get('n') if isinstance(eq, Equality): if eq.rhs != 0: return classify_ode(eq.lhs - eq.rhs, func, dict=dict, ics=ics, xi=xi, n=terms, eta=eta, prep=False) eq = eq.lhs order = ode_order(eq, f(x)) # hint:matchdict or hint:(tuple of matchdicts) # Also will contain "default":<default hint> and "order":order items. matching_hints = {"order": order} df = f(x).diff(x) a = Wild('a', exclude=[f(x)]) b = Wild('b', exclude=[f(x)]) c = Wild('c', exclude=[f(x)]) d = Wild('d', exclude=[df, f(x).diff(x, 2)]) e = Wild('e', exclude=[df]) k = Wild('k', exclude=[df]) n = Wild('n', exclude=[x, f(x), df]) c1 = Wild('c1', exclude=[x]) a2 = Wild('a2', exclude=[x, f(x), df]) b2 = Wild('b2', exclude=[x, f(x), df]) c2 = Wild('c2', exclude=[x, f(x), df]) d2 = Wild('d2', exclude=[x, f(x), df]) a3 = Wild('a3', exclude=[f(x), df, f(x).diff(x, 2)]) b3 = Wild('b3', exclude=[f(x), df, f(x).diff(x, 2)]) c3 = Wild('c3', exclude=[f(x), df, f(x).diff(x, 2)]) r3 = {'xi': xi, 'eta': eta} # Used for the lie_group hint boundary = {} # Used to extract initial conditions C1 = Symbol("C1") # Preprocessing to get the initial conditions out if ics is not None: for funcarg in ics: # Separating derivatives if isinstance(funcarg, (Subs, Derivative)): # f(x).diff(x).subs(x, 0) is a Subs, but f(x).diff(x).subs(x, # y) is a Derivative if isinstance(funcarg, Subs): deriv = funcarg.expr old = funcarg.variables[0] new = funcarg.point[0] elif isinstance(funcarg, Derivative): deriv = funcarg # No information on this. Just assume it was x old = x new = funcarg.variables[0] if (isinstance(deriv, Derivative) and isinstance(deriv.args[0], AppliedUndef) and deriv.args[0].func == f and len(deriv.args[0].args) == 1 and old == x and not new.has(x) and all(i == deriv.variables[0] for i in deriv.variables) and not ics[funcarg].has(f)): dorder = ode_order(deriv, x) temp = 'f' + str(dorder) boundary.update({temp: new, temp + 'val': ics[funcarg]}) else: raise ValueError("Enter valid boundary conditions for Derivatives") # Separating functions elif isinstance(funcarg, AppliedUndef): if (funcarg.func == f and len(funcarg.args) == 1 and not funcarg.args[0].has(x) and not ics[funcarg].has(f)): boundary.update({'f0': funcarg.args[0], 'f0val': ics[funcarg]}) else: raise ValueError("Enter valid boundary conditions for Function") else: raise ValueError("Enter boundary conditions of the form ics={f(point}: value, f(x).diff(x, order).subs(x, point): value}") # Factorable method r = _ode_factorable_match(eq, func, kwargs.get('x0', 0)) if r: matching_hints['factorable'] = r # Any ODE that can be solved with a combination of algebra and # integrals e.g.: # d^3/dx^3(x y) = F(x) r = _nth_algebraic_match(eq_orig, func) if r['solutions']: matching_hints['nth_algebraic'] = r matching_hints['nth_algebraic_Integral'] = r eq = expand(eq) # Precondition to try remove f(x) from highest order derivative reduced_eq = None if eq.is_Add: deriv_coef = eq.coeff(f(x).diff(x, order)) if deriv_coef not in (1, 0): r = deriv_coef.match(a*f(x)**c1) if r and r[c1]: den = f(x)**r[c1] reduced_eq = Add(*[arg/den for arg in eq.args]) if not reduced_eq: reduced_eq = eq if order == 1: ## Linear case: a(x)*y'+b(x)*y+c(x) == 0 if eq.is_Add: ind, dep = reduced_eq.as_independent(f) else: u = Dummy('u') ind, dep = (reduced_eq + u).as_independent(f) ind, dep = [tmp.subs(u, 0) for tmp in [ind, dep]] r = {a: dep.coeff(df), b: dep.coeff(f(x)), c: ind} # double check f[a] since the preconditioning may have failed if not r[a].has(f) and not r[b].has(f) and ( r[a]*df + r[b]*f(x) + r[c]).expand() - reduced_eq == 0: r['a'] = a r['b'] = b r['c'] = c matching_hints["1st_linear"] = r matching_hints["1st_linear_Integral"] = r ## Bernoulli case: a(x)*y'+b(x)*y+c(x)*y**n == 0 r = collect( reduced_eq, f(x), exact=True).match(a*df + b*f(x) + c*f(x)**n) if r and r[c] != 0 and r[n] != 1: # See issue 4676 r['a'] = a r['b'] = b r['c'] = c r['n'] = n matching_hints["Bernoulli"] = r matching_hints["Bernoulli_Integral"] = r ## Riccati special n == -2 case: a2*y'+b2*y**2+c2*y/x+d2/x**2 == 0 r = collect(reduced_eq, f(x), exact=True).match(a2*df + b2*f(x)**2 + c2*f(x)/x + d2/x**2) if r and r[b2] != 0 and (r[c2] != 0 or r[d2] != 0): r['a2'] = a2 r['b2'] = b2 r['c2'] = c2 r['d2'] = d2 matching_hints["Riccati_special_minus2"] = r # NON-REDUCED FORM OF EQUATION matches r = collect(eq, df, exact=True).match(d + e * df) if r: r['d'] = d r['e'] = e r['y'] = y r[d] = r[d].subs(f(x), y) r[e] = r[e].subs(f(x), y) # FIRST ORDER POWER SERIES WHICH NEEDS INITIAL CONDITIONS # TODO: Hint first order series should match only if d/e is analytic. # For now, only d/e and (d/e).diff(arg) is checked for existence at # at a given point. # This is currently done internally in ode_1st_power_series. point = boundary.get('f0', 0) value = boundary.get('f0val', C1) check = cancel(r[d]/r[e]) check1 = check.subs({x: point, y: value}) if not check1.has(oo) and not check1.has(zoo) and \ not check1.has(NaN) and not check1.has(-oo): check2 = (check1.diff(x)).subs({x: point, y: value}) if not check2.has(oo) and not check2.has(zoo) and \ not check2.has(NaN) and not check2.has(-oo): rseries = r.copy() rseries.update({'terms': terms, 'f0': point, 'f0val': value}) matching_hints["1st_power_series"] = rseries r3.update(r) ## Exact Differential Equation: P(x, y) + Q(x, y)*y' = 0 where # dP/dy == dQ/dx try: if r[d] != 0: numerator = simplify(r[d].diff(y) - r[e].diff(x)) # The following few conditions try to convert a non-exact # differential equation into an exact one. # References : Differential equations with applications # and historical notes - George E. Simmons if numerator: # If (dP/dy - dQ/dx) / Q = f(x) # then exp(integral(f(x))*equation becomes exact factor = simplify(numerator/r[e]) variables = factor.free_symbols if len(variables) == 1 and x == variables.pop(): factor = exp(Integral(factor).doit()) r[d] *= factor r[e] *= factor matching_hints["1st_exact"] = r matching_hints["1st_exact_Integral"] = r else: # If (dP/dy - dQ/dx) / -P = f(y) # then exp(integral(f(y))*equation becomes exact factor = simplify(-numerator/r[d]) variables = factor.free_symbols if len(variables) == 1 and y == variables.pop(): factor = exp(Integral(factor).doit()) r[d] *= factor r[e] *= factor matching_hints["1st_exact"] = r matching_hints["1st_exact_Integral"] = r else: matching_hints["1st_exact"] = r matching_hints["1st_exact_Integral"] = r except NotImplementedError: # Differentiating the coefficients might fail because of things # like f(2*x).diff(x). See issue 4624 and issue 4719. pass # Any first order ODE can be ideally solved by the Lie Group # method matching_hints["lie_group"] = r3 # This match is used for several cases below; we now collect on # f(x) so the matching works. r = collect(reduced_eq, df, exact=True).match(d + e*df) if r is None and 'factorable' not in matching_hints: roots = solve(reduced_eq, df) if roots: meq = Mul(*[(df - i) for i in roots])*Dummy() m = _ode_factorable_match(meq, func, kwargs.get('x0', 0)) matching_hints['factorable'] = m if r: # Using r[d] and r[e] without any modification for hints # linear-coefficients and separable-reduced. num, den = r[d], r[e] # ODE = d/e + df r['d'] = d r['e'] = e r['y'] = y r[d] = num.subs(f(x), y) r[e] = den.subs(f(x), y) ## Separable Case: y' == P(y)*Q(x) r[d] = separatevars(r[d]) r[e] = separatevars(r[e]) # m1[coeff]*m1[x]*m1[y] + m2[coeff]*m2[x]*m2[y]*y' m1 = separatevars(r[d], dict=True, symbols=(x, y)) m2 = separatevars(r[e], dict=True, symbols=(x, y)) if m1 and m2: r1 = {'m1': m1, 'm2': m2, 'y': y} matching_hints["separable"] = r1 matching_hints["separable_Integral"] = r1 ## First order equation with homogeneous coefficients: # dy/dx == F(y/x) or dy/dx == F(x/y) ordera = homogeneous_order(r[d], x, y) if ordera is not None: orderb = homogeneous_order(r[e], x, y) if ordera == orderb: # u1=y/x and u2=x/y u1 = Dummy('u1') u2 = Dummy('u2') s = "1st_homogeneous_coeff_subs" s1 = s + "_dep_div_indep" s2 = s + "_indep_div_dep" if simplify((r[d] + u1*r[e]).subs({x: 1, y: u1})) != 0: matching_hints[s1] = r matching_hints[s1 + "_Integral"] = r if simplify((r[e] + u2*r[d]).subs({x: u2, y: 1})) != 0: matching_hints[s2] = r matching_hints[s2 + "_Integral"] = r if s1 in matching_hints and s2 in matching_hints: matching_hints["1st_homogeneous_coeff_best"] = r ## Linear coefficients of the form # y'+ F((a*x + b*y + c)/(a'*x + b'y + c')) = 0 # that can be reduced to homogeneous form. F = num/den params = _linear_coeff_match(F, func) if params: xarg, yarg = params u = Dummy('u') t = Dummy('t') # Dummy substitution for df and f(x). dummy_eq = reduced_eq.subs(((df, t), (f(x), u))) reps = ((x, x + xarg), (u, u + yarg), (t, df), (u, f(x))) dummy_eq = simplify(dummy_eq.subs(reps)) # get the re-cast values for e and d r2 = collect(expand(dummy_eq), [df, f(x)]).match(e*df + d) if r2: orderd = homogeneous_order(r2[d], x, f(x)) if orderd is not None: ordere = homogeneous_order(r2[e], x, f(x)) if orderd == ordere: # Match arguments are passed in such a way that it # is coherent with the already existing homogeneous # functions. r2[d] = r2[d].subs(f(x), y) r2[e] = r2[e].subs(f(x), y) r2.update({'xarg': xarg, 'yarg': yarg, 'd': d, 'e': e, 'y': y}) matching_hints["linear_coefficients"] = r2 matching_hints["linear_coefficients_Integral"] = r2 ## Equation of the form y' + (y/x)*H(x^n*y) = 0 # that can be reduced to separable form factor = simplify(x/f(x)*num/den) # Try representing factor in terms of x^n*y # where n is lowest power of x in factor; # first remove terms like sqrt(2)*3 from factor.atoms(Mul) u = None for mul in ordered(factor.atoms(Mul)): if mul.has(x): _, u = mul.as_independent(x, f(x)) break if u and u.has(f(x)): h = x**(degree(Poly(u.subs(f(x), y), gen=x)))*f(x) p = Wild('p') if (u/h == 1) or ((u/h).simplify().match(x**p)): t = Dummy('t') r2 = {'t': t} xpart, ypart = u.as_independent(f(x)) test = factor.subs(((u, t), (1/u, 1/t))) free = test.free_symbols if len(free) == 1 and free.pop() == t: r2.update({'power': xpart.as_base_exp()[1], 'u': test}) matching_hints["separable_reduced"] = r2 matching_hints["separable_reduced_Integral"] = r2 ## Almost-linear equation of the form f(x)*g(y)*y' + k(x)*l(y) + m(x) = 0 r = collect(eq, [df, f(x)]).match(e*df + d) if r: r2 = r.copy() r2[c] = S.Zero if r2[d].is_Add: # Separate the terms having f(x) to r[d] and # remaining to r[c] no_f, r2[d] = r2[d].as_independent(f(x)) r2[c] += no_f factor = simplify(r2[d].diff(f(x))/r[e]) if factor and not factor.has(f(x)): r2[d] = factor_terms(r2[d]) u = r2[d].as_independent(f(x), as_Add=False)[1] r2.update({'a': e, 'b': d, 'c': c, 'u': u}) r2[d] /= u r2[e] /= u.diff(f(x)) matching_hints["almost_linear"] = r2 matching_hints["almost_linear_Integral"] = r2 elif order == 2: # Liouville ODE in the form # f(x).diff(x, 2) + g(f(x))*(f(x).diff(x))**2 + h(x)*f(x).diff(x) # See Goldstein and Braun, "Advanced Methods for the Solution of # Differential Equations", pg. 98 s = d*f(x).diff(x, 2) + e*df**2 + k*df r = reduced_eq.match(s) if r and r[d] != 0: y = Dummy('y') g = simplify(r[e]/r[d]).subs(f(x), y) h = simplify(r[k]/r[d]).subs(f(x), y) if y in h.free_symbols or x in g.free_symbols: pass else: r = {'g': g, 'h': h, 'y': y} matching_hints["Liouville"] = r matching_hints["Liouville_Integral"] = r # Homogeneous second order differential equation of the form # a3*f(x).diff(x, 2) + b3*f(x).diff(x) + c3 # It has a definite power series solution at point x0 if, b3/a3 and c3/a3 # are analytic at x0. deq = a3*(f(x).diff(x, 2)) + b3*df + c3*f(x) r = collect(reduced_eq, [f(x).diff(x, 2), f(x).diff(x), f(x)]).match(deq) ordinary = False if r: if not all([r[key].is_polynomial() for key in r]): n, d = reduced_eq.as_numer_denom() reduced_eq = expand(n) r = collect(reduced_eq, [f(x).diff(x, 2), f(x).diff(x), f(x)]).match(deq) if r and r[a3] != 0: p = cancel(r[b3]/r[a3]) # Used below q = cancel(r[c3]/r[a3]) # Used below point = kwargs.get('x0', 0) check = p.subs(x, point) if not check.has(oo, NaN, zoo, -oo): check = q.subs(x, point) if not check.has(oo, NaN, zoo, -oo): ordinary = True r.update({'a3': a3, 'b3': b3, 'c3': c3, 'x0': point, 'terms': terms}) matching_hints["2nd_power_series_ordinary"] = r # Checking if the differential equation has a regular singular point # at x0. It has a regular singular point at x0, if (b3/a3)*(x - x0) # and (c3/a3)*((x - x0)**2) are analytic at x0. if not ordinary: p = cancel((x - point)*p) check = p.subs(x, point) if not check.has(oo, NaN, zoo, -oo): q = cancel(((x - point)**2)*q) check = q.subs(x, point) if not check.has(oo, NaN, zoo, -oo): coeff_dict = {'p': p, 'q': q, 'x0': point, 'terms': terms} matching_hints["2nd_power_series_regular"] = coeff_dict # For Hypergeometric solutions. _r = {} _r.update(r) rn = match_2nd_hypergeometric(_r, func) if rn: matching_hints["2nd_hypergeometric"] = rn matching_hints["2nd_hypergeometric_Integral"] = rn # If the ODE has regular singular point at x0 and is of the form # Eq((x)**2*Derivative(y(x), x, x) + x*Derivative(y(x), x) + # (a4**2*x**(2*p)-n**2)*y(x) thus Bessel's equation rn = match_2nd_linear_bessel(r, f(x)) if rn: matching_hints["2nd_linear_bessel"] = rn # If the ODE is ordinary and is of the form of Airy's Equation # Eq(x**2*Derivative(y(x),x,x)-(ax+b)*y(x)) if p.is_zero: a4 = Wild('a4', exclude=[x,f(x),df]) b4 = Wild('b4', exclude=[x,f(x),df]) rn = q.match(a4+b4*x) if rn and rn[b4] != 0: rn = {'b':rn[a4],'m':rn[b4]} matching_hints["2nd_linear_airy"] = rn if order > 0: # Any ODE that can be solved with a substitution and # repeated integration e.g.: # `d^2/dx^2(y) + x*d/dx(y) = constant #f'(x) must be finite for this to work r = _nth_order_reducible_match(reduced_eq, func) if r: matching_hints['nth_order_reducible'] = r # nth order linear ODE # a_n(x)y^(n) + ... + a_1(x)y' + a_0(x)y = F(x) = b r = _nth_linear_match(reduced_eq, func, order) # Constant coefficient case (a_i is constant for all i) if r and not any(r[i].has(x) for i in r if i >= 0): # Inhomogeneous case: F(x) is not identically 0 if r[-1]: eq_homogeneous = Add(eq,-r[-1]) undetcoeff = _undetermined_coefficients_match(r[-1], x, func, eq_homogeneous) s = "nth_linear_constant_coeff_variation_of_parameters" matching_hints[s] = r matching_hints[s + "_Integral"] = r if undetcoeff['test']: r['trialset'] = undetcoeff['trialset'] matching_hints[ "nth_linear_constant_coeff_undetermined_coefficients" ] = r # Homogeneous case: F(x) is identically 0 else: matching_hints["nth_linear_constant_coeff_homogeneous"] = r # nth order Euler equation a_n*x**n*y^(n) + ... + a_1*x*y' + a_0*y = F(x) #In case of Homogeneous euler equation F(x) = 0 def _test_term(coeff, order): r""" Linear Euler ODEs have the form K*x**order*diff(y(x),x,order) = F(x), where K is independent of x and y(x), order>= 0. So we need to check that for each term, coeff == K*x**order from some K. We have a few cases, since coeff may have several different types. """ if order < 0: raise ValueError("order should be greater than 0") if coeff == 0: return True if order == 0: if x in coeff.free_symbols: return False return True if coeff.is_Mul: if coeff.has(f(x)): return False return x**order in coeff.args elif coeff.is_Pow: return coeff.as_base_exp() == (x, order) elif order == 1: return x == coeff return False # Find coefficient for highest derivative, multiply coefficients to # bring the equation into Euler form if possible r_rescaled = None if r is not None: coeff = r[order] factor = x**order / coeff r_rescaled = {i: factor*r[i] for i in r if i != 'trialset'} # XXX: Mixing up the trialset with the coefficients is error-prone. # These should be separated as something like r['coeffs'] and # r['trialset'] if r_rescaled and not any(not _test_term(r_rescaled[i], i) for i in r_rescaled if i != 'trialset' and i >= 0): if not r_rescaled[-1]: matching_hints["nth_linear_euler_eq_homogeneous"] = r_rescaled else: matching_hints["nth_linear_euler_eq_nonhomogeneous_variation_of_parameters"] = r_rescaled matching_hints["nth_linear_euler_eq_nonhomogeneous_variation_of_parameters_Integral"] = r_rescaled e, re = posify(r_rescaled[-1].subs(x, exp(x))) undetcoeff = _undetermined_coefficients_match(e.subs(re), x) if undetcoeff['test']: r_rescaled['trialset'] = undetcoeff['trialset'] matching_hints["nth_linear_euler_eq_nonhomogeneous_undetermined_coefficients"] = r_rescaled # Order keys based on allhints. retlist = [i for i in allhints if i in matching_hints] if dict: # Dictionaries are ordered arbitrarily, so make note of which # hint would come first for dsolve(). Use an ordered dict in Py 3. matching_hints["default"] = retlist[0] if retlist else None matching_hints["ordered_hints"] = tuple(retlist) return matching_hints else: return tuple(retlist) def equivalence(max_num_pow, dem_pow): # this function is made for checking the equivalence with 2F1 type of equation. # max_num_pow is the value of maximum power of x in numerator # and dem_pow is list of powers of different factor of form (a*x b). # reference from table 1 in paper - "Non-Liouvillian solutions for second order # linear ODEs" by L. Chan, E.S. Cheb-Terrab. # We can extend it for 1F1 and 0F1 type also. if max_num_pow == 2: if dem_pow in [[2, 2], [2, 2, 2]]: return "2F1" elif max_num_pow == 1: if dem_pow in [[1, 2, 2], [2, 2, 2], [1, 2], [2, 2]]: return "2F1" elif max_num_pow == 0: if dem_pow in [[1, 1, 2], [2, 2], [1 ,2, 2], [1, 1], [2], [1, 2], [2, 2]]: return "2F1" return None def equivalence_hypergeometric(A, B, func): from sympy import factor # This method for finding the equivalence is only for 2F1 type. # We can extend it for 1F1 and 0F1 type also. x = func.args[0] # making given equation in normal form I1 = factor(cancel(A.diff(x)/2 + A**2/4 - B)) # computing shifted invariant(J1) of the equation J1 = factor(cancel(x**2*I1 + S(1)/4)) num, dem = J1.as_numer_denom() num = powdenest(expand(num)) dem = powdenest(expand(dem)) pow_num = set() pow_dem = set() # this function will compute the different powers of variable(x) in J1. # then it will help in finding value of k. k is power of x such that we can express # J1 = x**k * J0(x**k) then all the powers in J0 become integers. def _power_counting(num): _pow = {0} for val in num: if val.has(x): if isinstance(val, Pow) and val.as_base_exp()[0] == x: _pow.add(val.as_base_exp()[1]) elif val == x: _pow.add(val.as_base_exp()[1]) else: _pow.update(_power_counting(val.args)) return _pow pow_num = _power_counting((num, )) pow_dem = _power_counting((dem, )) pow_dem.update(pow_num) _pow = pow_dem k = gcd(_pow) # computing I0 of the given equation I0 = powdenest(simplify(factor(((J1/k**2) - S(1)/4)/((x**k)**2))), force=True) I0 = factor(cancel(powdenest(I0.subs(x, x**(S(1)/k)), force=True))) num, dem = I0.as_numer_denom() max_num_pow = max(_power_counting((num, ))) dem_args = dem.args sing_point = [] dem_pow = [] # calculating singular point of I0. for arg in dem_args: if arg.has(x): if isinstance(arg, Pow): # (x-a)**n dem_pow.append(arg.as_base_exp()[1]) sing_point.append(list(roots(arg.as_base_exp()[0], x).keys())[0]) else: # (x-a) type dem_pow.append(arg.as_base_exp()[1]) sing_point.append(list(roots(arg, x).keys())[0]) dem_pow.sort() # checking if equivalence is exists or not. if equivalence(max_num_pow, dem_pow) == "2F1": return {'I0':I0, 'k':k, 'sing_point':sing_point, 'type':"2F1"} else: return None def ode_2nd_hypergeometric(eq, func, order, match): from sympy.simplify.hyperexpand import hyperexpand from sympy import factor x = func.args[0] C0, C1 = get_numbered_constants(eq, num=2) a = match['a'] b = match['b'] c = match['c'] A = match['A'] # B = match['B'] sol = None if match['type'] == "2F1": if c.is_integer == False: sol = C0*hyper([a, b], [c], x) + C1*hyper([a-c+1, b-c+1], [2-c], x)*x**(1-c) elif c == 1: y2 = Integral(exp(Integral((-(a+b+1)*x + c)/(x**2-x), x))/(hyperexpand(hyper([a, b], [c], x))**2), x)*hyper([a, b], [c], x) sol = C0*hyper([a, b], [c], x) + C1*y2 elif (c-a-b).is_integer == False: sol = C0*hyper([a, b], [1+a+b-c], 1-x) + C1*hyper([c-a, c-b], [1+c-a-b], 1-x)*(1-x)**(c-a-b) if sol is None: raise NotImplementedError("The given ODE " + str(eq) + " cannot be solved by" + " the hypergeometric method") # applying transformation in the solution subs = match['mobius'] dtdx = simplify(1/(subs.diff(x))) _B = ((a + b + 1)*x - c).subs(x, subs)*dtdx _B = factor(_B + ((x**2 -x).subs(x, subs))*(dtdx.diff(x)*dtdx)) _A = factor((x**2 - x).subs(x, subs)*(dtdx**2)) e = exp(logcombine(Integral(cancel(_B/(2*_A)), x), force=True)) sol = sol.subs(x, match['mobius']) sol = sol.subs(x, x**match['k']) e = e.subs(x, x**match['k']) if not A.is_zero: e1 = Integral(A/2, x) e1 = exp(logcombine(e1, force=True)) sol = cancel((e/e1)*x**((-match['k']+1)/2))*sol sol = Eq(func, sol) return sol sol = cancel((e)*x**((-match['k']+1)/2))*sol sol = Eq(func, sol) return sol def match_2nd_2F1_hypergeometric(I, k, sing_point, func): from sympy import factor x = func.args[0] a = Wild("a") b = Wild("b") c = Wild("c") t = Wild("t") s = Wild("s") r = Wild("r") alpha = Wild("alpha") beta = Wild("beta") gamma = Wild("gamma") delta = Wild("delta") rn = {'type':None} # I0 of the standerd 2F1 equation. I0 = ((a-b+1)*(a-b-1)*x**2 + 2*((1-a-b)*c + 2*a*b)*x + c*(c-2))/(4*x**2*(x-1)**2) if sing_point != [0, 1]: # If singular point is [0, 1] then we have standerd equation. eqs = [] sing_eqs = [-beta/alpha, -delta/gamma, (delta-beta)/(alpha-gamma)] # making equations for the finding the mobius transformation for i in range(3): if i<len(sing_point): eqs.append(Eq(sing_eqs[i], sing_point[i])) else: eqs.append(Eq(1/sing_eqs[i], 0)) # solving above equations for the mobius transformation _beta = -alpha*sing_point[0] _delta = -gamma*sing_point[1] _gamma = alpha if len(sing_point) == 3: _gamma = (_beta + sing_point[2]*alpha)/(sing_point[2] - sing_point[1]) mob = (alpha*x + beta)/(gamma*x + delta) mob = mob.subs(beta, _beta) mob = mob.subs(delta, _delta) mob = mob.subs(gamma, _gamma) mob = cancel(mob) t = (beta - delta*x)/(gamma*x - alpha) t = cancel(((t.subs(beta, _beta)).subs(delta, _delta)).subs(gamma, _gamma)) else: mob = x t = x # applying mobius transformation in I to make it into I0. I = I.subs(x, t) I = I*(t.diff(x))**2 I = factor(I) dict_I = {x**2:0, x:0, 1:0} I0_num, I0_dem = I0.as_numer_denom() # collecting coeff of (x**2, x), of the standerd equation. # substituting (a-b) = s, (a+b) = r dict_I0 = {x**2:s**2 - 1, x:(2*(1-r)*c + (r+s)*(r-s)), 1:c*(c-2)} # collecting coeff of (x**2, x) from I0 of the given equation. dict_I.update(collect(expand(cancel(I*I0_dem)), [x**2, x], evaluate=False)) eqs = [] # We are comparing the coeff of powers of different x, for finding the values of # parameters of standerd equation. for key in [x**2, x, 1]: eqs.append(Eq(dict_I[key], dict_I0[key])) # We can have many possible roots for the equation. # I am selecting the root on the basis that when we have # standard equation eq = x*(x-1)*f(x).diff(x, 2) + ((a+b+1)*x-c)*f(x).diff(x) + a*b*f(x) # then root should be a, b, c. _c = 1 - factor(sqrt(1+eqs[2].lhs)) if not _c.has(Symbol): _c = min(list(roots(eqs[2], c))) _s = factor(sqrt(eqs[0].lhs + 1)) _r = _c - factor(sqrt(_c**2 + _s**2 + eqs[1].lhs - 2*_c)) _a = (_r + _s)/2 _b = (_r - _s)/2 rn = {'a':simplify(_a), 'b':simplify(_b), 'c':simplify(_c), 'k':k, 'mobius':mob, 'type':"2F1"} return rn def match_2nd_hypergeometric(r, func): x = func.args[0] a3 = Wild('a3', exclude=[func, func.diff(x), func.diff(x, 2)]) b3 = Wild('b3', exclude=[func, func.diff(x), func.diff(x, 2)]) c3 = Wild('c3', exclude=[func, func.diff(x), func.diff(x, 2)]) A = cancel(r[b3]/r[a3]) B = cancel(r[c3]/r[a3]) d = equivalence_hypergeometric(A, B, func) rn = None if d: if d['type'] == "2F1": rn = match_2nd_2F1_hypergeometric(d['I0'], d['k'], d['sing_point'], func) if rn is not None: rn.update({'A':A, 'B':B}) # We can extend it for 1F1 and 0F1 type also. return rn def match_2nd_linear_bessel(r, func): from sympy.polys.polytools import factor # eq = a3*f(x).diff(x, 2) + b3*f(x).diff(x) + c3*f(x) f = func x = func.args[0] df = f.diff(x) a = Wild('a', exclude=[f,df]) b = Wild('b', exclude=[x, f,df]) a4 = Wild('a4', exclude=[x,f,df]) b4 = Wild('b4', exclude=[x,f,df]) c4 = Wild('c4', exclude=[x,f,df]) d4 = Wild('d4', exclude=[x,f,df]) a3 = Wild('a3', exclude=[f, df, f.diff(x, 2)]) b3 = Wild('b3', exclude=[f, df, f.diff(x, 2)]) c3 = Wild('c3', exclude=[f, df, f.diff(x, 2)]) # leading coeff of f(x).diff(x, 2) coeff = factor(r[a3]).match(a4*(x-b)**b4) if coeff: # if coeff[b4] = 0 means constant coefficient if coeff[b4] == 0: return None point = coeff[b] else: return None if point: r[a3] = simplify(r[a3].subs(x, x+point)) r[b3] = simplify(r[b3].subs(x, x+point)) r[c3] = simplify(r[c3].subs(x, x+point)) # making a3 in the form of x**2 r[a3] = cancel(r[a3]/(coeff[a4]*(x)**(-2+coeff[b4]))) r[b3] = cancel(r[b3]/(coeff[a4]*(x)**(-2+coeff[b4]))) r[c3] = cancel(r[c3]/(coeff[a4]*(x)**(-2+coeff[b4]))) # checking if b3 is of form c*(x-b) coeff1 = factor(r[b3]).match(a4*(x)) if coeff1 is None: return None # c3 maybe of very complex form so I am simply checking (a - b) form # if yes later I will match with the standerd form of bessel in a and b # a, b are wild variable defined above. _coeff2 = r[c3].match(a - b) if _coeff2 is None: return None # matching with standerd form for c3 coeff2 = factor(_coeff2[a]).match(c4**2*(x)**(2*a4)) if coeff2 is None: return None if _coeff2[b] == 0: coeff2[d4] = 0 else: coeff2[d4] = factor(_coeff2[b]).match(d4**2)[d4] rn = {'n':coeff2[d4], 'a4':coeff2[c4], 'd4':coeff2[a4]} rn['c4'] = coeff1[a4] rn['b4'] = point return rn def classify_sysode(eq, funcs=None, **kwargs): r""" Returns a dictionary of parameter names and values that define the system of ordinary differential equations in ``eq``. The parameters are further used in :py:meth:`~sympy.solvers.ode.dsolve` for solving that system. The parameter names and values are: 'is_linear' (boolean), which tells whether the given system is linear. Note that "linear" here refers to the operator: terms such as ``x*diff(x,t)`` are nonlinear, whereas terms like ``sin(t)*diff(x,t)`` are still linear operators. 'func' (list) contains the :py:class:`~sympy.core.function.Function`s that appear with a derivative in the ODE, i.e. those that we are trying to solve the ODE for. 'order' (dict) with the maximum derivative for each element of the 'func' parameter. 'func_coeff' (dict) with the coefficient for each triple ``(equation number, function, order)```. The coefficients are those subexpressions that do not appear in 'func', and hence can be considered constant for purposes of ODE solving. 'eq' (list) with the equations from ``eq``, sympified and transformed into expressions (we are solving for these expressions to be zero). 'no_of_equations' (int) is the number of equations (same as ``len(eq)``). 'type_of_equation' (string) is an internal classification of the type of ODE. References ========== -http://eqworld.ipmnet.ru/en/solutions/sysode/sode-toc1.htm -A. D. Polyanin and A. V. Manzhirov, Handbook of Mathematics for Engineers and Scientists Examples ======== >>> from sympy import Function, Eq, symbols, diff >>> from sympy.solvers.ode.ode import classify_sysode >>> from sympy.abc import t >>> f, x, y = symbols('f, x, y', cls=Function) >>> k, l, m, n = symbols('k, l, m, n', Integer=True) >>> x1 = diff(x(t), t) ; y1 = diff(y(t), t) >>> x2 = diff(x(t), t, t) ; y2 = diff(y(t), t, t) >>> eq = (Eq(5*x1, 12*x(t) - 6*y(t)), Eq(2*y1, 11*x(t) + 3*y(t))) >>> classify_sysode(eq) {'eq': [-12*x(t) + 6*y(t) + 5*Derivative(x(t), t), -11*x(t) - 3*y(t) + 2*Derivative(y(t), t)], 'func': [x(t), y(t)], 'func_coeff': {(0, x(t), 0): -12, (0, x(t), 1): 5, (0, y(t), 0): 6, (0, y(t), 1): 0, (1, x(t), 0): -11, (1, x(t), 1): 0, (1, y(t), 0): -3, (1, y(t), 1): 2}, 'is_linear': True, 'no_of_equation': 2, 'order': {x(t): 1, y(t): 1}, 'type_of_equation': 'type1'} >>> eq = (Eq(diff(x(t),t), 5*t*x(t) + t**2*y(t)), Eq(diff(y(t),t), -t**2*x(t) + 5*t*y(t))) >>> classify_sysode(eq) {'eq': [-t**2*y(t) - 5*t*x(t) + Derivative(x(t), t), t**2*x(t) - 5*t*y(t) + Derivative(y(t), t)], 'func': [x(t), y(t)], 'func_coeff': {(0, x(t), 0): -5*t, (0, x(t), 1): 1, (0, y(t), 0): -t**2, (0, y(t), 1): 0, (1, x(t), 0): t**2, (1, x(t), 1): 0, (1, y(t), 0): -5*t, (1, y(t), 1): 1}, 'is_linear': True, 'no_of_equation': 2, 'order': {x(t): 1, y(t): 1}, 'type_of_equation': 'type4'} """ # Sympify equations and convert iterables of equations into # a list of equations def _sympify(eq): return list(map(sympify, eq if iterable(eq) else [eq])) eq, funcs = (_sympify(w) for w in [eq, funcs]) if len(eq) == 0: raise ValueError("classify_sysode() works for systems of ODEs. " "For scalar ODEs, classify_ode should be used") for i, fi in enumerate(eq): if isinstance(fi, Equality): eq[i] = fi.lhs - fi.rhs matching_hints = {"no_of_equation":i+1} matching_hints['eq'] = eq t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0] # find all the functions if not given order = dict() if funcs==[None]: funcs = [] for eqs in eq: derivs = eqs.atoms(Derivative) func = set().union(*[d.atoms(AppliedUndef) for d in derivs]) for func_ in func: funcs.append(func_) funcs = list(set(funcs)) if len(funcs) != len(eq): raise ValueError("Number of functions given is not equal to the number of equations %s" % funcs) func_dict = dict() for func in funcs: if not order.get(func, False): max_order = 0 for i, eqs_ in enumerate(eq): order_ = ode_order(eqs_,func) if max_order < order_: max_order = order_ eq_no = i if eq_no in func_dict: list_func = [] list_func.append(func_dict[eq_no]) list_func.append(func) func_dict[eq_no] = list_func else: func_dict[eq_no] = func order[func] = max_order funcs = [func_dict[i] for i in range(len(func_dict))] matching_hints['func'] = funcs for func in funcs: if isinstance(func, list): for func_elem in func: if len(func_elem.args) != 1: raise ValueError("dsolve() and classify_sysode() work with " "functions of one variable only, not %s" % func) else: if func and len(func.args) != 1: raise ValueError("dsolve() and classify_sysode() work with " "functions of one variable only, not %s" % func) # find the order of all equation in system of odes matching_hints["order"] = order # find coefficients of terms f(t), diff(f(t),t) and higher derivatives # and similarly for other functions g(t), diff(g(t),t) in all equations. # Here j denotes the equation number, funcs[l] denotes the function about # which we are talking about and k denotes the order of function funcs[l] # whose coefficient we are calculating. def linearity_check(eqs, j, func, is_linear_): for k in range(order[func] + 1): func_coef[j, func, k] = collect(eqs.expand(), [diff(func, t, k)]).coeff(diff(func, t, k)) if is_linear_ == True: if func_coef[j, func, k] == 0: if k == 0: coef = eqs.as_independent(func, as_Add=True)[1] for xr in range(1, ode_order(eqs,func) + 1): coef -= eqs.as_independent(diff(func, t, xr), as_Add=True)[1] if coef != 0: is_linear_ = False else: if eqs.as_independent(diff(func, t, k), as_Add=True)[1]: is_linear_ = False else: for func_ in funcs: if isinstance(func_, list): for elem_func_ in func_: dep = func_coef[j, func, k].as_independent(elem_func_, as_Add=True)[1] if dep != 0: is_linear_ = False else: dep = func_coef[j, func, k].as_independent(func_, as_Add=True)[1] if dep != 0: is_linear_ = False return is_linear_ func_coef = {} is_linear = True for j, eqs in enumerate(eq): for func in funcs: if isinstance(func, list): for func_elem in func: is_linear = linearity_check(eqs, j, func_elem, is_linear) else: is_linear = linearity_check(eqs, j, func, is_linear) matching_hints['func_coeff'] = func_coef matching_hints['is_linear'] = is_linear if len(set(order.values())) == 1: order_eq = list(matching_hints['order'].values())[0] if matching_hints['is_linear'] == True: if matching_hints['no_of_equation'] == 2: if order_eq == 1: type_of_equation = check_linear_2eq_order1(eq, funcs, func_coef) elif order_eq == 2: type_of_equation = check_linear_2eq_order2(eq, funcs, func_coef) else: type_of_equation = None elif matching_hints['no_of_equation'] == 3: if order_eq == 1: type_of_equation = check_linear_3eq_order1(eq, funcs, func_coef) if type_of_equation is None: type_of_equation = check_linear_neq_order1(eq, funcs, func_coef) else: type_of_equation = None else: if order_eq == 1: type_of_equation = check_linear_neq_order1(eq, funcs, func_coef) else: type_of_equation = None else: if matching_hints['no_of_equation'] == 2: if order_eq == 1: type_of_equation = check_nonlinear_2eq_order1(eq, funcs, func_coef) else: type_of_equation = None elif matching_hints['no_of_equation'] == 3: if order_eq == 1: type_of_equation = check_nonlinear_3eq_order1(eq, funcs, func_coef) else: type_of_equation = None else: type_of_equation = None else: type_of_equation = None matching_hints['type_of_equation'] = type_of_equation return matching_hints def check_linear_2eq_order1(eq, func, func_coef): x = func[0].func y = func[1].func fc = func_coef t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0] r = dict() # for equations Eq(a1*diff(x(t),t), b1*x(t) + c1*y(t) + d1) # and Eq(a2*diff(y(t),t), b2*x(t) + c2*y(t) + d2) r['a1'] = fc[0,x(t),1] ; r['a2'] = fc[1,y(t),1] r['b1'] = -fc[0,x(t),0]/fc[0,x(t),1] ; r['b2'] = -fc[1,x(t),0]/fc[1,y(t),1] r['c1'] = -fc[0,y(t),0]/fc[0,x(t),1] ; r['c2'] = -fc[1,y(t),0]/fc[1,y(t),1] forcing = [S.Zero,S.Zero] for i in range(2): for j in Add.make_args(eq[i]): if not j.has(x(t), y(t)): forcing[i] += j if not (forcing[0].has(t) or forcing[1].has(t)): # We can handle homogeneous case and simple constant forcings r['d1'] = forcing[0] r['d2'] = forcing[1] else: # Issue #9244: nonhomogeneous linear systems are not supported return None # Conditions to check for type 6 whose equations are Eq(diff(x(t),t), f(t)*x(t) + g(t)*y(t)) and # Eq(diff(y(t),t), a*[f(t) + a*h(t)]x(t) + a*[g(t) - h(t)]*y(t)) p = 0 q = 0 p1 = cancel(r['b2']/(cancel(r['b2']/r['c2']).as_numer_denom()[0])) p2 = cancel(r['b1']/(cancel(r['b1']/r['c1']).as_numer_denom()[0])) for n, i in enumerate([p1, p2]): for j in Mul.make_args(collect_const(i)): if not j.has(t): q = j if q and n==0: if ((r['b2']/j - r['b1'])/(r['c1'] - r['c2']/j)) == j: p = 1 elif q and n==1: if ((r['b1']/j - r['b2'])/(r['c2'] - r['c1']/j)) == j: p = 2 # End of condition for type 6 if r['d1']!=0 or r['d2']!=0: if not r['d1'].has(t) and not r['d2'].has(t): if all(not r[k].has(t) for k in 'a1 a2 b1 b2 c1 c2'.split()): # Equations for type 2 are Eq(a1*diff(x(t),t),b1*x(t)+c1*y(t)+d1) and Eq(a2*diff(y(t),t),b2*x(t)+c2*y(t)+d2) return "type2" else: return None else: if all(not r[k].has(t) for k in 'a1 a2 b1 b2 c1 c2'.split()): # Equations for type 1 are Eq(a1*diff(x(t),t),b1*x(t)+c1*y(t)) and Eq(a2*diff(y(t),t),b2*x(t)+c2*y(t)) return "type1" else: r['b1'] = r['b1']/r['a1'] ; r['b2'] = r['b2']/r['a2'] r['c1'] = r['c1']/r['a1'] ; r['c2'] = r['c2']/r['a2'] if (r['b1'] == r['c2']) and (r['c1'] == r['b2']): # Equation for type 3 are Eq(diff(x(t),t), f(t)*x(t) + g(t)*y(t)) and Eq(diff(y(t),t), g(t)*x(t) + f(t)*y(t)) return "type3" elif (r['b1'] == r['c2']) and (r['c1'] == -r['b2']) or (r['b1'] == -r['c2']) and (r['c1'] == r['b2']): # Equation for type 4 are Eq(diff(x(t),t), f(t)*x(t) + g(t)*y(t)) and Eq(diff(y(t),t), -g(t)*x(t) + f(t)*y(t)) return "type4" elif (not cancel(r['b2']/r['c1']).has(t) and not cancel((r['c2']-r['b1'])/r['c1']).has(t)) \ or (not cancel(r['b1']/r['c2']).has(t) and not cancel((r['c1']-r['b2'])/r['c2']).has(t)): # Equations for type 5 are Eq(diff(x(t),t), f(t)*x(t) + g(t)*y(t)) and Eq(diff(y(t),t), a*g(t)*x(t) + [f(t) + b*g(t)]*y(t) return "type5" elif p: return "type6" else: # Equations for type 7 are Eq(diff(x(t),t), f(t)*x(t) + g(t)*y(t)) and Eq(diff(y(t),t), h(t)*x(t) + p(t)*y(t)) return "type7" def check_linear_2eq_order2(eq, func, func_coef): x = func[0].func y = func[1].func fc = func_coef t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0] r = dict() a = Wild('a', exclude=[1/t]) b = Wild('b', exclude=[1/t**2]) u = Wild('u', exclude=[t, t**2]) v = Wild('v', exclude=[t, t**2]) w = Wild('w', exclude=[t, t**2]) p = Wild('p', exclude=[t, t**2]) r['a1'] = fc[0,x(t),2] ; r['a2'] = fc[1,y(t),2] r['b1'] = fc[0,x(t),1] ; r['b2'] = fc[1,x(t),1] r['c1'] = fc[0,y(t),1] ; r['c2'] = fc[1,y(t),1] r['d1'] = fc[0,x(t),0] ; r['d2'] = fc[1,x(t),0] r['e1'] = fc[0,y(t),0] ; r['e2'] = fc[1,y(t),0] const = [S.Zero, S.Zero] for i in range(2): for j in Add.make_args(eq[i]): if not (j.has(x(t)) or j.has(y(t))): const[i] += j r['f1'] = const[0] r['f2'] = const[1] if r['f1']!=0 or r['f2']!=0: if all(not r[k].has(t) for k in 'a1 a2 d1 d2 e1 e2 f1 f2'.split()) \ and r['b1']==r['c1']==r['b2']==r['c2']==0: return "type2" elif all(not r[k].has(t) for k in 'a1 a2 b1 b2 c1 c2 d1 d2 e1 e1'.split()): p = [S.Zero, S.Zero] ; q = [S.Zero, S.Zero] for n, e in enumerate([r['f1'], r['f2']]): if e.has(t): tpart = e.as_independent(t, Mul)[1] for i in Mul.make_args(tpart): if i.has(exp): b, e = i.as_base_exp() co = e.coeff(t) if co and not co.has(t) and co.has(I): p[n] = 1 else: q[n] = 1 else: q[n] = 1 else: q[n] = 1 if p[0]==1 and p[1]==1 and q[0]==0 and q[1]==0: return "type4" else: return None else: return None else: if r['b1']==r['b2']==r['c1']==r['c2']==0 and all(not r[k].has(t) \ for k in 'a1 a2 d1 d2 e1 e2'.split()): return "type1" elif r['b1']==r['e1']==r['c2']==r['d2']==0 and all(not r[k].has(t) \ for k in 'a1 a2 b2 c1 d1 e2'.split()) and r['c1'] == -r['b2'] and \ r['d1'] == r['e2']: return "type3" elif cancel(-r['b2']/r['d2'])==t and cancel(-r['c1']/r['e1'])==t and not \ (r['d2']/r['a2']).has(t) and not (r['e1']/r['a1']).has(t) and \ r['b1']==r['d1']==r['c2']==r['e2']==0: return "type5" elif ((r['a1']/r['d1']).expand()).match((p*(u*t**2+v*t+w)**2).expand()) and not \ (cancel(r['a1']*r['d2']/(r['a2']*r['d1']))).has(t) and not (r['d1']/r['e1']).has(t) and not \ (r['d2']/r['e2']).has(t) and r['b1'] == r['b2'] == r['c1'] == r['c2'] == 0: return "type10" elif not cancel(r['d1']/r['e1']).has(t) and not cancel(r['d2']/r['e2']).has(t) and not \ cancel(r['d1']*r['a2']/(r['d2']*r['a1'])).has(t) and r['b1']==r['b2']==r['c1']==r['c2']==0: return "type6" elif not cancel(r['b1']/r['c1']).has(t) and not cancel(r['b2']/r['c2']).has(t) and not \ cancel(r['b1']*r['a2']/(r['b2']*r['a1'])).has(t) and r['d1']==r['d2']==r['e1']==r['e2']==0: return "type7" elif cancel(-r['b2']/r['d2'])==t and cancel(-r['c1']/r['e1'])==t and not \ cancel(r['e1']*r['a2']/(r['d2']*r['a1'])).has(t) and r['e1'].has(t) \ and r['b1']==r['d1']==r['c2']==r['e2']==0: return "type8" elif (r['b1']/r['a1']).match(a/t) and (r['b2']/r['a2']).match(a/t) and not \ (r['b1']/r['c1']).has(t) and not (r['b2']/r['c2']).has(t) and \ (r['d1']/r['a1']).match(b/t**2) and (r['d2']/r['a2']).match(b/t**2) \ and not (r['d1']/r['e1']).has(t) and not (r['d2']/r['e2']).has(t): return "type9" elif -r['b1']/r['d1']==-r['c1']/r['e1']==-r['b2']/r['d2']==-r['c2']/r['e2']==t: return "type11" else: return None def check_linear_3eq_order1(eq, func, func_coef): x = func[0].func y = func[1].func z = func[2].func fc = func_coef t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0] r = dict() r['a1'] = fc[0,x(t),1]; r['a2'] = fc[1,y(t),1]; r['a3'] = fc[2,z(t),1] r['b1'] = fc[0,x(t),0]; r['b2'] = fc[1,x(t),0]; r['b3'] = fc[2,x(t),0] r['c1'] = fc[0,y(t),0]; r['c2'] = fc[1,y(t),0]; r['c3'] = fc[2,y(t),0] r['d1'] = fc[0,z(t),0]; r['d2'] = fc[1,z(t),0]; r['d3'] = fc[2,z(t),0] forcing = [S.Zero, S.Zero, S.Zero] for i in range(3): for j in Add.make_args(eq[i]): if not j.has(x(t), y(t), z(t)): forcing[i] += j if forcing[0].has(t) or forcing[1].has(t) or forcing[2].has(t): # We can handle homogeneous case and simple constant forcings. # Issue #9244: nonhomogeneous linear systems are not supported return None if all(not r[k].has(t) for k in 'a1 a2 a3 b1 b2 b3 c1 c2 c3 d1 d2 d3'.split()): if r['c1']==r['d1']==r['d2']==0: return 'type1' elif r['c1'] == -r['b2'] and r['d1'] == -r['b3'] and r['d2'] == -r['c3'] \ and r['b1'] == r['c2'] == r['d3'] == 0: return 'type2' elif r['b1'] == r['c2'] == r['d3'] == 0 and r['c1']/r['a1'] == -r['d1']/r['a1'] \ and r['d2']/r['a2'] == -r['b2']/r['a2'] and r['b3']/r['a3'] == -r['c3']/r['a3']: return 'type3' else: return None else: for k1 in 'c1 d1 b2 d2 b3 c3'.split(): if r[k1] == 0: continue else: if all(not cancel(r[k1]/r[k]).has(t) for k in 'd1 b2 d2 b3 c3'.split() if r[k]!=0) \ and all(not cancel(r[k1]/(r['b1'] - r[k])).has(t) for k in 'b1 c2 d3'.split() if r['b1']!=r[k]): return 'type4' else: break return None def check_linear_neq_order1(eq, func, func_coef): fc = func_coef t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0] n = len(eq) for i in range(n): for j in range(n): if (fc[i, func[j], 0]/fc[i, func[i], 1]).has(t): return None if len(eq) == 3: return 'type6' return 'type1' def check_nonlinear_2eq_order1(eq, func, func_coef): t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0] f = Wild('f') g = Wild('g') u, v = symbols('u, v', cls=Dummy) def check_type(x, y): r1 = eq[0].match(t*diff(x(t),t) - x(t) + f) r2 = eq[1].match(t*diff(y(t),t) - y(t) + g) if not (r1 and r2): r1 = eq[0].match(diff(x(t),t) - x(t)/t + f/t) r2 = eq[1].match(diff(y(t),t) - y(t)/t + g/t) if not (r1 and r2): r1 = (-eq[0]).match(t*diff(x(t),t) - x(t) + f) r2 = (-eq[1]).match(t*diff(y(t),t) - y(t) + g) if not (r1 and r2): r1 = (-eq[0]).match(diff(x(t),t) - x(t)/t + f/t) r2 = (-eq[1]).match(diff(y(t),t) - y(t)/t + g/t) if r1 and r2 and not (r1[f].subs(diff(x(t),t),u).subs(diff(y(t),t),v).has(t) \ or r2[g].subs(diff(x(t),t),u).subs(diff(y(t),t),v).has(t)): return 'type5' else: return None for func_ in func: if isinstance(func_, list): x = func[0][0].func y = func[0][1].func eq_type = check_type(x, y) if not eq_type: eq_type = check_type(y, x) return eq_type x = func[0].func y = func[1].func fc = func_coef n = Wild('n', exclude=[x(t),y(t)]) f1 = Wild('f1', exclude=[v,t]) f2 = Wild('f2', exclude=[v,t]) g1 = Wild('g1', exclude=[u,t]) g2 = Wild('g2', exclude=[u,t]) for i in range(2): eqs = 0 for terms in Add.make_args(eq[i]): eqs += terms/fc[i,func[i],1] eq[i] = eqs r = eq[0].match(diff(x(t),t) - x(t)**n*f) if r: g = (diff(y(t),t) - eq[1])/r[f] if r and not (g.has(x(t)) or g.subs(y(t),v).has(t) or r[f].subs(x(t),u).subs(y(t),v).has(t)): return 'type1' r = eq[0].match(diff(x(t),t) - exp(n*x(t))*f) if r: g = (diff(y(t),t) - eq[1])/r[f] if r and not (g.has(x(t)) or g.subs(y(t),v).has(t) or r[f].subs(x(t),u).subs(y(t),v).has(t)): return 'type2' g = Wild('g') r1 = eq[0].match(diff(x(t),t) - f) r2 = eq[1].match(diff(y(t),t) - g) if r1 and r2 and not (r1[f].subs(x(t),u).subs(y(t),v).has(t) or \ r2[g].subs(x(t),u).subs(y(t),v).has(t)): return 'type3' r1 = eq[0].match(diff(x(t),t) - f) r2 = eq[1].match(diff(y(t),t) - g) num, den = ( (r1[f].subs(x(t),u).subs(y(t),v))/ (r2[g].subs(x(t),u).subs(y(t),v))).as_numer_denom() R1 = num.match(f1*g1) R2 = den.match(f2*g2) # phi = (r1[f].subs(x(t),u).subs(y(t),v))/num if R1 and R2: return 'type4' return None def check_nonlinear_2eq_order2(eq, func, func_coef): return None def check_nonlinear_3eq_order1(eq, func, func_coef): x = func[0].func y = func[1].func z = func[2].func fc = func_coef t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0] u, v, w = symbols('u, v, w', cls=Dummy) a = Wild('a', exclude=[x(t), y(t), z(t), t]) b = Wild('b', exclude=[x(t), y(t), z(t), t]) c = Wild('c', exclude=[x(t), y(t), z(t), t]) f = Wild('f') F1 = Wild('F1') F2 = Wild('F2') F3 = Wild('F3') for i in range(3): eqs = 0 for terms in Add.make_args(eq[i]): eqs += terms/fc[i,func[i],1] eq[i] = eqs r1 = eq[0].match(diff(x(t),t) - a*y(t)*z(t)) r2 = eq[1].match(diff(y(t),t) - b*z(t)*x(t)) r3 = eq[2].match(diff(z(t),t) - c*x(t)*y(t)) if r1 and r2 and r3: num1, den1 = r1[a].as_numer_denom() num2, den2 = r2[b].as_numer_denom() num3, den3 = r3[c].as_numer_denom() if solve([num1*u-den1*(v-w), num2*v-den2*(w-u), num3*w-den3*(u-v)],[u, v]): return 'type1' r = eq[0].match(diff(x(t),t) - y(t)*z(t)*f) if r: r1 = collect_const(r[f]).match(a*f) r2 = ((diff(y(t),t) - eq[1])/r1[f]).match(b*z(t)*x(t)) r3 = ((diff(z(t),t) - eq[2])/r1[f]).match(c*x(t)*y(t)) if r1 and r2 and r3: num1, den1 = r1[a].as_numer_denom() num2, den2 = r2[b].as_numer_denom() num3, den3 = r3[c].as_numer_denom() if solve([num1*u-den1*(v-w), num2*v-den2*(w-u), num3*w-den3*(u-v)],[u, v]): return 'type2' r = eq[0].match(diff(x(t),t) - (F2-F3)) if r: r1 = collect_const(r[F2]).match(c*F2) r1.update(collect_const(r[F3]).match(b*F3)) if r1: if eq[1].has(r1[F2]) and not eq[1].has(r1[F3]): r1[F2], r1[F3] = r1[F3], r1[F2] r1[c], r1[b] = -r1[b], -r1[c] r2 = eq[1].match(diff(y(t),t) - a*r1[F3] + r1[c]*F1) if r2: r3 = (eq[2] == diff(z(t),t) - r1[b]*r2[F1] + r2[a]*r1[F2]) if r1 and r2 and r3: return 'type3' r = eq[0].match(diff(x(t),t) - z(t)*F2 + y(t)*F3) if r: r1 = collect_const(r[F2]).match(c*F2) r1.update(collect_const(r[F3]).match(b*F3)) if r1: if eq[1].has(r1[F2]) and not eq[1].has(r1[F3]): r1[F2], r1[F3] = r1[F3], r1[F2] r1[c], r1[b] = -r1[b], -r1[c] r2 = (diff(y(t),t) - eq[1]).match(a*x(t)*r1[F3] - r1[c]*z(t)*F1) if r2: r3 = (diff(z(t),t) - eq[2] == r1[b]*y(t)*r2[F1] - r2[a]*x(t)*r1[F2]) if r1 and r2 and r3: return 'type4' r = (diff(x(t),t) - eq[0]).match(x(t)*(F2 - F3)) if r: r1 = collect_const(r[F2]).match(c*F2) r1.update(collect_const(r[F3]).match(b*F3)) if r1: if eq[1].has(r1[F2]) and not eq[1].has(r1[F3]): r1[F2], r1[F3] = r1[F3], r1[F2] r1[c], r1[b] = -r1[b], -r1[c] r2 = (diff(y(t),t) - eq[1]).match(y(t)*(a*r1[F3] - r1[c]*F1)) if r2: r3 = (diff(z(t),t) - eq[2] == z(t)*(r1[b]*r2[F1] - r2[a]*r1[F2])) if r1 and r2 and r3: return 'type5' return None def check_nonlinear_3eq_order2(eq, func, func_coef): return None @vectorize(0) def odesimp(ode, eq, func, hint): r""" Simplifies solutions of ODEs, including trying to solve for ``func`` and running :py:meth:`~sympy.solvers.ode.constantsimp`. It may use knowledge of the type of solution that the hint returns to apply additional simplifications. It also attempts to integrate any :py:class:`~sympy.integrals.integrals.Integral`\s in the expression, if the hint is not an ``_Integral`` hint. This function should have no effect on expressions returned by :py:meth:`~sympy.solvers.ode.dsolve`, as :py:meth:`~sympy.solvers.ode.dsolve` already calls :py:meth:`~sympy.solvers.ode.ode.odesimp`, but the individual hint functions do not call :py:meth:`~sympy.solvers.ode.ode.odesimp` (because the :py:meth:`~sympy.solvers.ode.dsolve` wrapper does). Therefore, this function is designed for mainly internal use. Examples ======== >>> from sympy import sin, symbols, dsolve, pprint, Function >>> from sympy.solvers.ode.ode import odesimp >>> x , u2, C1= symbols('x,u2,C1') >>> f = Function('f') >>> eq = dsolve(x*f(x).diff(x) - f(x) - x*sin(f(x)/x), f(x), ... hint='1st_homogeneous_coeff_subs_indep_div_dep_Integral', ... simplify=False) >>> pprint(eq, wrap_line=False) x ---- f(x) / | | / 1 \ | -|u2 + -------| | | /1 \| | | sin|--|| | \ \u2// log(f(x)) = log(C1) + | ---------------- d(u2) | 2 | u2 | / >>> pprint(odesimp(eq, f(x), 1, {C1}, ... hint='1st_homogeneous_coeff_subs_indep_div_dep' ... )) #doctest: +SKIP x --------- = C1 /f(x)\ tan|----| \2*x / """ x = func.args[0] f = func.func C1 = get_numbered_constants(eq, num=1) constants = eq.free_symbols - ode.free_symbols # First, integrate if the hint allows it. eq = _handle_Integral(eq, func, hint) if hint.startswith("nth_linear_euler_eq_nonhomogeneous"): eq = simplify(eq) if not isinstance(eq, Equality): raise TypeError("eq should be an instance of Equality") # Second, clean up the arbitrary constants. # Right now, nth linear hints can put as many as 2*order constants in an # expression. If that number grows with another hint, the third argument # here should be raised accordingly, or constantsimp() rewritten to handle # an arbitrary number of constants. eq = constantsimp(eq, constants) # Lastly, now that we have cleaned up the expression, try solving for func. # When CRootOf is implemented in solve(), we will want to return a CRootOf # every time instead of an Equality. # Get the f(x) on the left if possible. if eq.rhs == func and not eq.lhs.has(func): eq = [Eq(eq.rhs, eq.lhs)] # make sure we are working with lists of solutions in simplified form. if eq.lhs == func and not eq.rhs.has(func): # The solution is already solved eq = [eq] # special simplification of the rhs if hint.startswith("nth_linear_constant_coeff"): # Collect terms to make the solution look nice. # This is also necessary for constantsimp to remove unnecessary # terms from the particular solution from variation of parameters # # Collect is not behaving reliably here. The results for # some linear constant-coefficient equations with repeated # roots do not properly simplify all constants sometimes. # 'collectterms' gives different orders sometimes, and results # differ in collect based on that order. The # sort-reverse trick fixes things, but may fail in the # future. In addition, collect is splitting exponentials with # rational powers for no reason. We have to do a match # to fix this using Wilds. # # XXX: This global collectterms hack should be removed. global collectterms collectterms.sort(key=default_sort_key) collectterms.reverse() assert len(eq) == 1 and eq[0].lhs == f(x) sol = eq[0].rhs sol = expand_mul(sol) for i, reroot, imroot in collectterms: sol = collect(sol, x**i*exp(reroot*x)*sin(abs(imroot)*x)) sol = collect(sol, x**i*exp(reroot*x)*cos(imroot*x)) for i, reroot, imroot in collectterms: sol = collect(sol, x**i*exp(reroot*x)) del collectterms # Collect is splitting exponentials with rational powers for # no reason. We call powsimp to fix. sol = powsimp(sol) eq[0] = Eq(f(x), sol) else: # The solution is not solved, so try to solve it try: floats = any(i.is_Float for i in eq.atoms(Number)) eqsol = solve(eq, func, force=True, rational=False if floats else None) if not eqsol: raise NotImplementedError except (NotImplementedError, PolynomialError): eq = [eq] else: def _expand(expr): numer, denom = expr.as_numer_denom() if denom.is_Add: return expr else: return powsimp(expr.expand(), combine='exp', deep=True) # XXX: the rest of odesimp() expects each ``t`` to be in a # specific normal form: rational expression with numerator # expanded, but with combined exponential functions (at # least in this setup all tests pass). eq = [Eq(f(x), _expand(t)) for t in eqsol] # special simplification of the lhs. if hint.startswith("1st_homogeneous_coeff"): for j, eqi in enumerate(eq): newi = logcombine(eqi, force=True) if isinstance(newi.lhs, log) and newi.rhs == 0: newi = Eq(newi.lhs.args[0]/C1, C1) eq[j] = newi # We cleaned up the constants before solving to help the solve engine with # a simpler expression, but the solved expression could have introduced # things like -C1, so rerun constantsimp() one last time before returning. for i, eqi in enumerate(eq): eq[i] = constantsimp(eqi, constants) eq[i] = constant_renumber(eq[i], ode.free_symbols) # If there is only 1 solution, return it; # otherwise return the list of solutions. if len(eq) == 1: eq = eq[0] return eq def ode_sol_simplicity(sol, func, trysolving=True): r""" Returns an extended integer representing how simple a solution to an ODE is. The following things are considered, in order from most simple to least: - ``sol`` is solved for ``func``. - ``sol`` is not solved for ``func``, but can be if passed to solve (e.g., a solution returned by ``dsolve(ode, func, simplify=False``). - If ``sol`` is not solved for ``func``, then base the result on the length of ``sol``, as computed by ``len(str(sol))``. - If ``sol`` has any unevaluated :py:class:`~sympy.integrals.integrals.Integral`\s, this will automatically be considered less simple than any of the above. This function returns an integer such that if solution A is simpler than solution B by above metric, then ``ode_sol_simplicity(sola, func) < ode_sol_simplicity(solb, func)``. Currently, the following are the numbers returned, but if the heuristic is ever improved, this may change. Only the ordering is guaranteed. +----------------------------------------------+-------------------+ | Simplicity | Return | +==============================================+===================+ | ``sol`` solved for ``func`` | ``-2`` | +----------------------------------------------+-------------------+ | ``sol`` not solved for ``func`` but can be | ``-1`` | +----------------------------------------------+-------------------+ | ``sol`` is not solved nor solvable for | ``len(str(sol))`` | | ``func`` | | +----------------------------------------------+-------------------+ | ``sol`` contains an | ``oo`` | | :obj:`~sympy.integrals.integrals.Integral` | | +----------------------------------------------+-------------------+ ``oo`` here means the SymPy infinity, which should compare greater than any integer. If you already know :py:meth:`~sympy.solvers.solvers.solve` cannot solve ``sol``, you can use ``trysolving=False`` to skip that step, which is the only potentially slow step. For example, :py:meth:`~sympy.solvers.ode.dsolve` with the ``simplify=False`` flag should do this. If ``sol`` is a list of solutions, if the worst solution in the list returns ``oo`` it returns that, otherwise it returns ``len(str(sol))``, that is, the length of the string representation of the whole list. Examples ======== This function is designed to be passed to ``min`` as the key argument, such as ``min(listofsolutions, key=lambda i: ode_sol_simplicity(i, f(x)))``. >>> from sympy import symbols, Function, Eq, tan, cos, sqrt, Integral >>> from sympy.solvers.ode.ode import ode_sol_simplicity >>> x, C1, C2 = symbols('x, C1, C2') >>> f = Function('f') >>> ode_sol_simplicity(Eq(f(x), C1*x**2), f(x)) -2 >>> ode_sol_simplicity(Eq(x**2 + f(x), C1), f(x)) -1 >>> ode_sol_simplicity(Eq(f(x), C1*Integral(2*x, x)), f(x)) oo >>> eq1 = Eq(f(x)/tan(f(x)/(2*x)), C1) >>> eq2 = Eq(f(x)/tan(f(x)/(2*x) + f(x)), C2) >>> [ode_sol_simplicity(eq, f(x)) for eq in [eq1, eq2]] [28, 35] >>> min([eq1, eq2], key=lambda i: ode_sol_simplicity(i, f(x))) Eq(f(x)/tan(f(x)/(2*x)), C1) """ # TODO: if two solutions are solved for f(x), we still want to be # able to get the simpler of the two # See the docstring for the coercion rules. We check easier (faster) # things here first, to save time. if iterable(sol): # See if there are Integrals for i in sol: if ode_sol_simplicity(i, func, trysolving=trysolving) == oo: return oo return len(str(sol)) if sol.has(Integral): return oo # Next, try to solve for func. This code will change slightly when CRootOf # is implemented in solve(). Probably a CRootOf solution should fall # somewhere between a normal solution and an unsolvable expression. # First, see if they are already solved if sol.lhs == func and not sol.rhs.has(func) or \ sol.rhs == func and not sol.lhs.has(func): return -2 # We are not so lucky, try solving manually if trysolving: try: sols = solve(sol, func) if not sols: raise NotImplementedError except NotImplementedError: pass else: return -1 # Finally, a naive computation based on the length of the string version # of the expression. This may favor combined fractions because they # will not have duplicate denominators, and may slightly favor expressions # with fewer additions and subtractions, as those are separated by spaces # by the printer. # Additional ideas for simplicity heuristics are welcome, like maybe # checking if a equation has a larger domain, or if constantsimp has # introduced arbitrary constants numbered higher than the order of a # given ODE that sol is a solution of. return len(str(sol)) def _get_constant_subexpressions(expr, Cs): Cs = set(Cs) Ces = [] def _recursive_walk(expr): expr_syms = expr.free_symbols if expr_syms and expr_syms.issubset(Cs): Ces.append(expr) else: if expr.func == exp: expr = expr.expand(mul=True) if expr.func in (Add, Mul): d = sift(expr.args, lambda i : i.free_symbols.issubset(Cs)) if len(d[True]) > 1: x = expr.func(*d[True]) if not x.is_number: Ces.append(x) elif isinstance(expr, Integral): if expr.free_symbols.issubset(Cs) and \ all(len(x) == 3 for x in expr.limits): Ces.append(expr) for i in expr.args: _recursive_walk(i) return _recursive_walk(expr) return Ces def __remove_linear_redundancies(expr, Cs): cnts = {i: expr.count(i) for i in Cs} Cs = [i for i in Cs if cnts[i] > 0] def _linear(expr): if isinstance(expr, Add): xs = [i for i in Cs if expr.count(i)==cnts[i] \ and 0 == expr.diff(i, 2)] d = {} for x in xs: y = expr.diff(x) if y not in d: d[y]=[] d[y].append(x) for y in d: if len(d[y]) > 1: d[y].sort(key=str) for x in d[y][1:]: expr = expr.subs(x, 0) return expr def _recursive_walk(expr): if len(expr.args) != 0: expr = expr.func(*[_recursive_walk(i) for i in expr.args]) expr = _linear(expr) return expr if isinstance(expr, Equality): lhs, rhs = [_recursive_walk(i) for i in expr.args] f = lambda i: isinstance(i, Number) or i in Cs if isinstance(lhs, Symbol) and lhs in Cs: rhs, lhs = lhs, rhs if lhs.func in (Add, Symbol) and rhs.func in (Add, Symbol): dlhs = sift([lhs] if isinstance(lhs, AtomicExpr) else lhs.args, f) drhs = sift([rhs] if isinstance(rhs, AtomicExpr) else rhs.args, f) for i in [True, False]: for hs in [dlhs, drhs]: if i not in hs: hs[i] = [0] # this calculation can be simplified lhs = Add(*dlhs[False]) - Add(*drhs[False]) rhs = Add(*drhs[True]) - Add(*dlhs[True]) elif lhs.func in (Mul, Symbol) and rhs.func in (Mul, Symbol): dlhs = sift([lhs] if isinstance(lhs, AtomicExpr) else lhs.args, f) if True in dlhs: if False not in dlhs: dlhs[False] = [1] lhs = Mul(*dlhs[False]) rhs = rhs/Mul(*dlhs[True]) return Eq(lhs, rhs) else: return _recursive_walk(expr) @vectorize(0) def constantsimp(expr, constants): r""" Simplifies an expression with arbitrary constants in it. This function is written specifically to work with :py:meth:`~sympy.solvers.ode.dsolve`, and is not intended for general use. Simplification is done by "absorbing" the arbitrary constants into other arbitrary constants, numbers, and symbols that they are not independent of. The symbols must all have the same name with numbers after it, for example, ``C1``, ``C2``, ``C3``. The ``symbolname`` here would be '``C``', the ``startnumber`` would be 1, and the ``endnumber`` would be 3. If the arbitrary constants are independent of the variable ``x``, then the independent symbol would be ``x``. There is no need to specify the dependent function, such as ``f(x)``, because it already has the independent symbol, ``x``, in it. Because terms are "absorbed" into arbitrary constants and because constants are renumbered after simplifying, the arbitrary constants in expr are not necessarily equal to the ones of the same name in the returned result. If two or more arbitrary constants are added, multiplied, or raised to the power of each other, they are first absorbed together into a single arbitrary constant. Then the new constant is combined into other terms if necessary. Absorption of constants is done with limited assistance: 1. terms of :py:class:`~sympy.core.add.Add`\s are collected to try join constants so `e^x (C_1 \cos(x) + C_2 \cos(x))` will simplify to `e^x C_1 \cos(x)`; 2. powers with exponents that are :py:class:`~sympy.core.add.Add`\s are expanded so `e^{C_1 + x}` will be simplified to `C_1 e^x`. Use :py:meth:`~sympy.solvers.ode.ode.constant_renumber` to renumber constants after simplification or else arbitrary numbers on constants may appear, e.g. `C_1 + C_3 x`. In rare cases, a single constant can be "simplified" into two constants. Every differential equation solution should have as many arbitrary constants as the order of the differential equation. The result here will be technically correct, but it may, for example, have `C_1` and `C_2` in an expression, when `C_1` is actually equal to `C_2`. Use your discretion in such situations, and also take advantage of the ability to use hints in :py:meth:`~sympy.solvers.ode.dsolve`. Examples ======== >>> from sympy import symbols >>> from sympy.solvers.ode.ode import constantsimp >>> C1, C2, C3, x, y = symbols('C1, C2, C3, x, y') >>> constantsimp(2*C1*x, {C1, C2, C3}) C1*x >>> constantsimp(C1 + 2 + x, {C1, C2, C3}) C1 + x >>> constantsimp(C1*C2 + 2 + C2 + C3*x, {C1, C2, C3}) C1 + C3*x """ # This function works recursively. The idea is that, for Mul, # Add, Pow, and Function, if the class has a constant in it, then # we can simplify it, which we do by recursing down and # simplifying up. Otherwise, we can skip that part of the # expression. Cs = constants orig_expr = expr constant_subexprs = _get_constant_subexpressions(expr, Cs) for xe in constant_subexprs: xes = list(xe.free_symbols) if not xes: continue if all([expr.count(c) == xe.count(c) for c in xes]): xes.sort(key=str) expr = expr.subs(xe, xes[0]) # try to perform common sub-expression elimination of constant terms try: commons, rexpr = cse(expr) commons.reverse() rexpr = rexpr[0] for s in commons: cs = list(s[1].atoms(Symbol)) if len(cs) == 1 and cs[0] in Cs and \ cs[0] not in rexpr.atoms(Symbol) and \ not any(cs[0] in ex for ex in commons if ex != s): rexpr = rexpr.subs(s[0], cs[0]) else: rexpr = rexpr.subs(*s) expr = rexpr except IndexError: pass expr = __remove_linear_redundancies(expr, Cs) def _conditional_term_factoring(expr): new_expr = terms_gcd(expr, clear=False, deep=True, expand=False) # we do not want to factor exponentials, so handle this separately if new_expr.is_Mul: infac = False asfac = False for m in new_expr.args: if isinstance(m, exp): asfac = True elif m.is_Add: infac = any(isinstance(fi, exp) for t in m.args for fi in Mul.make_args(t)) if asfac and infac: new_expr = expr break return new_expr expr = _conditional_term_factoring(expr) # call recursively if more simplification is possible if orig_expr != expr: return constantsimp(expr, Cs) return expr def constant_renumber(expr, variables=None, newconstants=None): r""" Renumber arbitrary constants in ``expr`` to use the symbol names as given in ``newconstants``. In the process, this reorders expression terms in a standard way. If ``newconstants`` is not provided then the new constant names will be ``C1``, ``C2`` etc. Otherwise ``newconstants`` should be an iterable giving the new symbols to use for the constants in order. The ``variables`` argument is a list of non-constant symbols. All other free symbols found in ``expr`` are assumed to be constants and will be renumbered. If ``variables`` is not given then any numbered symbol beginning with ``C`` (e.g. ``C1``) is assumed to be a constant. Symbols are renumbered based on ``.sort_key()``, so they should be numbered roughly in the order that they appear in the final, printed expression. Note that this ordering is based in part on hashes, so it can produce different results on different machines. The structure of this function is very similar to that of :py:meth:`~sympy.solvers.ode.constantsimp`. Examples ======== >>> from sympy import symbols, Eq, pprint >>> from sympy.solvers.ode.ode import constant_renumber >>> x, C1, C2, C3 = symbols('x,C1:4') >>> expr = C3 + C2*x + C1*x**2 >>> expr C1*x**2 + C2*x + C3 >>> constant_renumber(expr) C1 + C2*x + C3*x**2 The ``variables`` argument specifies which are constants so that the other symbols will not be renumbered: >>> constant_renumber(expr, [C1, x]) C1*x**2 + C2 + C3*x The ``newconstants`` argument is used to specify what symbols to use when replacing the constants: >>> constant_renumber(expr, [x], newconstants=symbols('E1:4')) E1 + E2*x + E3*x**2 """ if type(expr) in (set, list, tuple): renumbered = [constant_renumber(e, variables, newconstants) for e in expr] return type(expr)(renumbered) # Symbols in solution but not ODE are constants if variables is not None: variables = set(variables) constantsymbols = list(expr.free_symbols - variables) # Any Cn is a constant... else: variables = set() isconstant = lambda s: s.startswith('C') and s[1:].isdigit() constantsymbols = [sym for sym in expr.free_symbols if isconstant(sym.name)] # Find new constants checking that they aren't already in the ODE if newconstants is None: iter_constants = numbered_symbols(start=1, prefix='C', exclude=variables) else: iter_constants = (sym for sym in newconstants if sym not in variables) # XXX: This global newstartnumber hack should be removed global newstartnumber newstartnumber = 1 endnumber = len(constantsymbols) constants_found = [None]*(endnumber + 2) # make a mapping to send all constantsymbols to S.One and use # that to make sure that term ordering is not dependent on # the indexed value of C C_1 = [(ci, S.One) for ci in constantsymbols] sort_key=lambda arg: default_sort_key(arg.subs(C_1)) def _constant_renumber(expr): r""" We need to have an internal recursive function so that newstartnumber maintains its values throughout recursive calls. """ # FIXME: Use nonlocal here when support for Py2 is dropped: global newstartnumber if isinstance(expr, Equality): return Eq( _constant_renumber(expr.lhs), _constant_renumber(expr.rhs)) if type(expr) not in (Mul, Add, Pow) and not expr.is_Function and \ not expr.has(*constantsymbols): # Base case, as above. Hope there aren't constants inside # of some other class, because they won't be renumbered. return expr elif expr.is_Piecewise: return expr elif expr in constantsymbols: if expr not in constants_found: constants_found[newstartnumber] = expr newstartnumber += 1 return expr elif expr.is_Function or expr.is_Pow or isinstance(expr, Tuple): return expr.func( *[_constant_renumber(x) for x in expr.args]) else: sortedargs = list(expr.args) sortedargs.sort(key=sort_key) return expr.func(*[_constant_renumber(x) for x in sortedargs]) expr = _constant_renumber(expr) # Don't renumber symbols present in the ODE. constants_found = [c for c in constants_found if c not in variables] # Renumbering happens here expr = expr.subs(zip(constants_found[1:], iter_constants), simultaneous=True) return expr def _handle_Integral(expr, func, hint): r""" Converts a solution with Integrals in it into an actual solution. For most hints, this simply runs ``expr.doit()``. """ # XXX: This global y hack should be removed global y x = func.args[0] f = func.func if hint == "1st_exact": sol = (expr.doit()).subs(y, f(x)) del y elif hint == "1st_exact_Integral": sol = Eq(Subs(expr.lhs, y, f(x)), expr.rhs) del y elif hint == "nth_linear_constant_coeff_homogeneous": sol = expr elif not hint.endswith("_Integral"): sol = expr.doit() else: sol = expr return sol def _ode_factorable_match(eq, func, x0): from sympy.polys.polytools import factor eqs = factor(eq) eqs = fraction(eqs)[0] # p/q =0, So we need to solve only p=0 eqns = [] r = None if isinstance(eqs, Pow): # if f(x)**p=0 then f(x)=0 (p>0) if eqs.exp.is_positive: eq = eqs.base if isinstance(eq, Pow): return None else: r = _ode_factorable_match(eq, func, x0) if r is None: r = {'eqns' : [eq], 'x0': x0} return r if isinstance(eqs, Mul): fac = eqs.args for i in fac: if i.has(func): eqns.append(i) if len(eqns)>0: r = {'eqns' : eqns, 'x0' : x0} return r # FIXME: replace the general solution in the docstring with # dsolve(equation, hint='1st_exact_Integral'). You will need to be able # to have assumptions on P and Q that dP/dy = dQ/dx. def ode_1st_exact(eq, func, order, match): r""" Solves 1st order exact ordinary differential equations. A 1st order differential equation is called exact if it is the total differential of a function. That is, the differential equation .. math:: P(x, y) \,\partial{}x + Q(x, y) \,\partial{}y = 0 is exact if there is some function `F(x, y)` such that `P(x, y) = \partial{}F/\partial{}x` and `Q(x, y) = \partial{}F/\partial{}y`. It can be shown that a necessary and sufficient condition for a first order ODE to be exact is that `\partial{}P/\partial{}y = \partial{}Q/\partial{}x`. Then, the solution will be as given below:: >>> from sympy import Function, Eq, Integral, symbols, pprint >>> x, y, t, x0, y0, C1= symbols('x,y,t,x0,y0,C1') >>> P, Q, F= map(Function, ['P', 'Q', 'F']) >>> pprint(Eq(Eq(F(x, y), Integral(P(t, y), (t, x0, x)) + ... Integral(Q(x0, t), (t, y0, y))), C1)) x y / / | | F(x, y) = | P(t, y) dt + | Q(x0, t) dt = C1 | | / / x0 y0 Where the first partials of `P` and `Q` exist and are continuous in a simply connected region. A note: SymPy currently has no way to represent inert substitution on an expression, so the hint ``1st_exact_Integral`` will return an integral with `dy`. This is supposed to represent the function that you are solving for. Examples ======== >>> from sympy import Function, dsolve, cos, sin >>> from sympy.abc import x >>> f = Function('f') >>> dsolve(cos(f(x)) - (x*sin(f(x)) - f(x)**2)*f(x).diff(x), ... f(x), hint='1st_exact') Eq(x*cos(f(x)) + f(x)**3/3, C1) References ========== - https://en.wikipedia.org/wiki/Exact_differential_equation - M. Tenenbaum & H. Pollard, "Ordinary Differential Equations", Dover 1963, pp. 73 # indirect doctest """ x = func.args[0] r = match # d+e*diff(f(x),x) e = r[r['e']] d = r[r['d']] # XXX: This global y hack should be removed global y # This is the only way to pass dummy y to _handle_Integral y = r['y'] C1 = get_numbered_constants(eq, num=1) # Refer Joel Moses, "Symbolic Integration - The Stormy Decade", # Communications of the ACM, Volume 14, Number 8, August 1971, pp. 558 # which gives the method to solve an exact differential equation. sol = Integral(d, x) + Integral((e - (Integral(d, x).diff(y))), y) return Eq(sol, C1) def ode_1st_homogeneous_coeff_best(eq, func, order, match): r""" Returns the best solution to an ODE from the two hints ``1st_homogeneous_coeff_subs_dep_div_indep`` and ``1st_homogeneous_coeff_subs_indep_div_dep``. This is as determined by :py:meth:`~sympy.solvers.ode.ode.ode_sol_simplicity`. See the :py:meth:`~sympy.solvers.ode.ode.ode_1st_homogeneous_coeff_subs_indep_div_dep` and :py:meth:`~sympy.solvers.ode.ode.ode_1st_homogeneous_coeff_subs_dep_div_indep` docstrings for more information on these hints. Note that there is no ``ode_1st_homogeneous_coeff_best_Integral`` hint. Examples ======== >>> from sympy import Function, dsolve, pprint >>> from sympy.abc import x >>> f = Function('f') >>> pprint(dsolve(2*x*f(x) + (x**2 + f(x)**2)*f(x).diff(x), f(x), ... hint='1st_homogeneous_coeff_best', simplify=False)) / 2 \ | 3*x | log|----- + 1| | 2 | \f (x) / log(f(x)) = log(C1) - -------------- 3 References ========== - https://en.wikipedia.org/wiki/Homogeneous_differential_equation - M. Tenenbaum & H. Pollard, "Ordinary Differential Equations", Dover 1963, pp. 59 # indirect doctest """ # There are two substitutions that solve the equation, u1=y/x and u2=x/y # They produce different integrals, so try them both and see which # one is easier. sol1 = ode_1st_homogeneous_coeff_subs_indep_div_dep(eq, func, order, match) sol2 = ode_1st_homogeneous_coeff_subs_dep_div_indep(eq, func, order, match) simplify = match.get('simplify', True) if simplify: # why is odesimp called here? Should it be at the usual spot? sol1 = odesimp(eq, sol1, func, "1st_homogeneous_coeff_subs_indep_div_dep") sol2 = odesimp(eq, sol2, func, "1st_homogeneous_coeff_subs_dep_div_indep") return min([sol1, sol2], key=lambda x: ode_sol_simplicity(x, func, trysolving=not simplify)) def ode_1st_homogeneous_coeff_subs_dep_div_indep(eq, func, order, match): r""" Solves a 1st order differential equation with homogeneous coefficients using the substitution `u_1 = \frac{\text{<dependent variable>}}{\text{<independent variable>}}`. This is a differential equation .. math:: P(x, y) + Q(x, y) dy/dx = 0 such that `P` and `Q` are homogeneous and of the same order. A function `F(x, y)` is homogeneous of order `n` if `F(x t, y t) = t^n F(x, y)`. Equivalently, `F(x, y)` can be rewritten as `G(y/x)` or `H(x/y)`. See also the docstring of :py:meth:`~sympy.solvers.ode.homogeneous_order`. If the coefficients `P` and `Q` in the differential equation above are homogeneous functions of the same order, then it can be shown that the substitution `y = u_1 x` (i.e. `u_1 = y/x`) will turn the differential equation into an equation separable in the variables `x` and `u`. If `h(u_1)` is the function that results from making the substitution `u_1 = f(x)/x` on `P(x, f(x))` and `g(u_2)` is the function that results from the substitution on `Q(x, f(x))` in the differential equation `P(x, f(x)) + Q(x, f(x)) f'(x) = 0`, then the general solution is:: >>> from sympy import Function, dsolve, pprint >>> from sympy.abc import x >>> f, g, h = map(Function, ['f', 'g', 'h']) >>> genform = g(f(x)/x) + h(f(x)/x)*f(x).diff(x) >>> pprint(genform) /f(x)\ /f(x)\ d g|----| + h|----|*--(f(x)) \ x / \ x / dx >>> pprint(dsolve(genform, f(x), ... hint='1st_homogeneous_coeff_subs_dep_div_indep_Integral')) f(x) ---- x / | | -h(u1) log(x) = C1 + | ---------------- d(u1) | u1*h(u1) + g(u1) | / Where `u_1 h(u_1) + g(u_1) \ne 0` and `x \ne 0`. See also the docstrings of :py:meth:`~sympy.solvers.ode.ode.ode_1st_homogeneous_coeff_best` and :py:meth:`~sympy.solvers.ode.ode.ode_1st_homogeneous_coeff_subs_indep_div_dep`. Examples ======== >>> from sympy import Function, dsolve >>> from sympy.abc import x >>> f = Function('f') >>> pprint(dsolve(2*x*f(x) + (x**2 + f(x)**2)*f(x).diff(x), f(x), ... hint='1st_homogeneous_coeff_subs_dep_div_indep', simplify=False)) / 3 \ |3*f(x) f (x)| log|------ + -----| | x 3 | \ x / log(x) = log(C1) - ------------------- 3 References ========== - https://en.wikipedia.org/wiki/Homogeneous_differential_equation - M. Tenenbaum & H. Pollard, "Ordinary Differential Equations", Dover 1963, pp. 59 # indirect doctest """ x = func.args[0] f = func.func u = Dummy('u') u1 = Dummy('u1') # u1 == f(x)/x r = match # d+e*diff(f(x),x) C1 = get_numbered_constants(eq, num=1) xarg = match.get('xarg', 0) yarg = match.get('yarg', 0) int = Integral( (-r[r['e']]/(r[r['d']] + u1*r[r['e']])).subs({x: 1, r['y']: u1}), (u1, None, f(x)/x)) sol = logcombine(Eq(log(x), int + log(C1)), force=True) sol = sol.subs(f(x), u).subs(((u, u - yarg), (x, x - xarg), (u, f(x)))) return sol def ode_1st_homogeneous_coeff_subs_indep_div_dep(eq, func, order, match): r""" Solves a 1st order differential equation with homogeneous coefficients using the substitution `u_2 = \frac{\text{<independent variable>}}{\text{<dependent variable>}}`. This is a differential equation .. math:: P(x, y) + Q(x, y) dy/dx = 0 such that `P` and `Q` are homogeneous and of the same order. A function `F(x, y)` is homogeneous of order `n` if `F(x t, y t) = t^n F(x, y)`. Equivalently, `F(x, y)` can be rewritten as `G(y/x)` or `H(x/y)`. See also the docstring of :py:meth:`~sympy.solvers.ode.homogeneous_order`. If the coefficients `P` and `Q` in the differential equation above are homogeneous functions of the same order, then it can be shown that the substitution `x = u_2 y` (i.e. `u_2 = x/y`) will turn the differential equation into an equation separable in the variables `y` and `u_2`. If `h(u_2)` is the function that results from making the substitution `u_2 = x/f(x)` on `P(x, f(x))` and `g(u_2)` is the function that results from the substitution on `Q(x, f(x))` in the differential equation `P(x, f(x)) + Q(x, f(x)) f'(x) = 0`, then the general solution is: >>> from sympy import Function, dsolve, pprint >>> from sympy.abc import x >>> f, g, h = map(Function, ['f', 'g', 'h']) >>> genform = g(x/f(x)) + h(x/f(x))*f(x).diff(x) >>> pprint(genform) / x \ / x \ d g|----| + h|----|*--(f(x)) \f(x)/ \f(x)/ dx >>> pprint(dsolve(genform, f(x), ... hint='1st_homogeneous_coeff_subs_indep_div_dep_Integral')) x ---- f(x) / | | -g(u2) | ---------------- d(u2) | u2*g(u2) + h(u2) | / <BLANKLINE> f(x) = C1*e Where `u_2 g(u_2) + h(u_2) \ne 0` and `f(x) \ne 0`. See also the docstrings of :py:meth:`~sympy.solvers.ode.ode.ode_1st_homogeneous_coeff_best` and :py:meth:`~sympy.solvers.ode.ode.ode_1st_homogeneous_coeff_subs_dep_div_indep`. Examples ======== >>> from sympy import Function, pprint, dsolve >>> from sympy.abc import x >>> f = Function('f') >>> pprint(dsolve(2*x*f(x) + (x**2 + f(x)**2)*f(x).diff(x), f(x), ... hint='1st_homogeneous_coeff_subs_indep_div_dep', ... simplify=False)) / 2 \ | 3*x | log|----- + 1| | 2 | \f (x) / log(f(x)) = log(C1) - -------------- 3 References ========== - https://en.wikipedia.org/wiki/Homogeneous_differential_equation - M. Tenenbaum & H. Pollard, "Ordinary Differential Equations", Dover 1963, pp. 59 # indirect doctest """ x = func.args[0] f = func.func u = Dummy('u') u2 = Dummy('u2') # u2 == x/f(x) r = match # d+e*diff(f(x),x) C1 = get_numbered_constants(eq, num=1) xarg = match.get('xarg', 0) # If xarg present take xarg, else zero yarg = match.get('yarg', 0) # If yarg present take yarg, else zero int = Integral( simplify( (-r[r['d']]/(r[r['e']] + u2*r[r['d']])).subs({x: u2, r['y']: 1})), (u2, None, x/f(x))) sol = logcombine(Eq(log(f(x)), int + log(C1)), force=True) sol = sol.subs(f(x), u).subs(((u, u - yarg), (x, x - xarg), (u, f(x)))) return sol # XXX: Should this function maybe go somewhere else? def homogeneous_order(eq, *symbols): r""" Returns the order `n` if `g` is homogeneous and ``None`` if it is not homogeneous. Determines if a function is homogeneous and if so of what order. A function `f(x, y, \cdots)` is homogeneous of order `n` if `f(t x, t y, \cdots) = t^n f(x, y, \cdots)`. If the function is of two variables, `F(x, y)`, then `f` being homogeneous of any order is equivalent to being able to rewrite `F(x, y)` as `G(x/y)` or `H(y/x)`. This fact is used to solve 1st order ordinary differential equations whose coefficients are homogeneous of the same order (see the docstrings of :py:meth:`~sympy.solvers.ode.ode.ode_1st_homogeneous_coeff_subs_dep_div_indep` and :py:meth:`~sympy.solvers.ode.ode.ode_1st_homogeneous_coeff_subs_indep_div_dep`). Symbols can be functions, but every argument of the function must be a symbol, and the arguments of the function that appear in the expression must match those given in the list of symbols. If a declared function appears with different arguments than given in the list of symbols, ``None`` is returned. Examples ======== >>> from sympy import Function, homogeneous_order, sqrt >>> from sympy.abc import x, y >>> f = Function('f') >>> homogeneous_order(f(x), f(x)) is None True >>> homogeneous_order(f(x,y), f(y, x), x, y) is None True >>> homogeneous_order(f(x), f(x), x) 1 >>> homogeneous_order(x**2*f(x)/sqrt(x**2+f(x)**2), x, f(x)) 2 >>> homogeneous_order(x**2+f(x), x, f(x)) is None True """ if not symbols: raise ValueError("homogeneous_order: no symbols were given.") symset = set(symbols) eq = sympify(eq) # The following are not supported if eq.has(Order, Derivative): return None # These are all constants if (eq.is_Number or eq.is_NumberSymbol or eq.is_number ): return S.Zero # Replace all functions with dummy variables dum = numbered_symbols(prefix='d', cls=Dummy) newsyms = set() for i in [j for j in symset if getattr(j, 'is_Function')]: iargs = set(i.args) if iargs.difference(symset): return None else: dummyvar = next(dum) eq = eq.subs(i, dummyvar) symset.remove(i) newsyms.add(dummyvar) symset.update(newsyms) if not eq.free_symbols & symset: return None # assuming order of a nested function can only be equal to zero if isinstance(eq, Function): return None if homogeneous_order( eq.args[0], *tuple(symset)) != 0 else S.Zero # make the replacement of x with x*t and see if t can be factored out t = Dummy('t', positive=True) # It is sufficient that t > 0 eqs = separatevars(eq.subs([(i, t*i) for i in symset]), [t], dict=True)[t] if eqs is S.One: return S.Zero # there was no term with only t i, d = eqs.as_independent(t, as_Add=False) b, e = d.as_base_exp() if b == t: return e def ode_1st_linear(eq, func, order, match): r""" Solves 1st order linear differential equations. These are differential equations of the form .. math:: dy/dx + P(x) y = Q(x)\text{.} These kinds of differential equations can be solved in a general way. The integrating factor `e^{\int P(x) \,dx}` will turn the equation into a separable equation. The general solution is:: >>> from sympy import Function, dsolve, Eq, pprint, diff, sin >>> from sympy.abc import x >>> f, P, Q = map(Function, ['f', 'P', 'Q']) >>> genform = Eq(f(x).diff(x) + P(x)*f(x), Q(x)) >>> pprint(genform) d P(x)*f(x) + --(f(x)) = Q(x) dx >>> pprint(dsolve(genform, f(x), hint='1st_linear_Integral')) / / \ | | | | | / | / | | | | | | | | P(x) dx | - | P(x) dx | | | | | | | / | / f(x) = |C1 + | Q(x)*e dx|*e | | | \ / / Examples ======== >>> f = Function('f') >>> pprint(dsolve(Eq(x*diff(f(x), x) - f(x), x**2*sin(x)), ... f(x), '1st_linear')) f(x) = x*(C1 - cos(x)) References ========== - https://en.wikipedia.org/wiki/Linear_differential_equation#First_order_equation - M. Tenenbaum & H. Pollard, "Ordinary Differential Equations", Dover 1963, pp. 92 # indirect doctest """ x = func.args[0] f = func.func r = match # a*diff(f(x),x) + b*f(x) + c C1 = get_numbered_constants(eq, num=1) t = exp(Integral(r[r['b']]/r[r['a']], x)) tt = Integral(t*(-r[r['c']]/r[r['a']]), x) f = match.get('u', f(x)) # take almost-linear u if present, else f(x) return Eq(f, (tt + C1)/t) def ode_Bernoulli(eq, func, order, match): r""" Solves Bernoulli differential equations. These are equations of the form .. math:: dy/dx + P(x) y = Q(x) y^n\text{, }n \ne 1`\text{.} The substitution `w = 1/y^{1-n}` will transform an equation of this form into one that is linear (see the docstring of :py:meth:`~sympy.solvers.ode.ode.ode_1st_linear`). The general solution is:: >>> from sympy import Function, dsolve, Eq, pprint >>> from sympy.abc import x, n >>> f, P, Q = map(Function, ['f', 'P', 'Q']) >>> genform = Eq(f(x).diff(x) + P(x)*f(x), Q(x)*f(x)**n) >>> pprint(genform) d n P(x)*f(x) + --(f(x)) = Q(x)*f (x) dx >>> pprint(dsolve(genform, f(x), hint='Bernoulli_Integral'), num_columns=100) 1 ----- 1 - n // / \ \ || | | | || | / | / | || | | | | | || | (1 - n)* | P(x) dx | -(1 - n)* | P(x) dx| || | | | | | || | / | / | f(x) = ||C1 + (n - 1)* | -Q(x)*e dx|*e | || | | | \\ / / / Note that the equation is separable when `n = 1` (see the docstring of :py:meth:`~sympy.solvers.ode.ode.ode_separable`). >>> pprint(dsolve(Eq(f(x).diff(x) + P(x)*f(x), Q(x)*f(x)), f(x), ... hint='separable_Integral')) f(x) / | / | 1 | | - dy = C1 + | (-P(x) + Q(x)) dx | y | | / / Examples ======== >>> from sympy import Function, dsolve, Eq, pprint, log >>> from sympy.abc import x >>> f = Function('f') >>> pprint(dsolve(Eq(x*f(x).diff(x) + f(x), log(x)*f(x)**2), ... f(x), hint='Bernoulli')) 1 f(x) = ------------------- / log(x) 1\ x*|C1 + ------ + -| \ x x/ References ========== - https://en.wikipedia.org/wiki/Bernoulli_differential_equation - M. Tenenbaum & H. Pollard, "Ordinary Differential Equations", Dover 1963, pp. 95 # indirect doctest """ x = func.args[0] f = func.func r = match # a*diff(f(x),x) + b*f(x) + c*f(x)**n, n != 1 C1 = get_numbered_constants(eq, num=1) t = exp((1 - r[r['n']])*Integral(r[r['b']]/r[r['a']], x)) tt = (r[r['n']] - 1)*Integral(t*r[r['c']]/r[r['a']], x) return Eq(f(x), ((tt + C1)/t)**(1/(1 - r[r['n']]))) def ode_Riccati_special_minus2(eq, func, order, match): r""" The general Riccati equation has the form .. math:: dy/dx = f(x) y^2 + g(x) y + h(x)\text{.} While it does not have a general solution [1], the "special" form, `dy/dx = a y^2 - b x^c`, does have solutions in many cases [2]. This routine returns a solution for `a(dy/dx) = b y^2 + c y/x + d/x^2` that is obtained by using a suitable change of variables to reduce it to the special form and is valid when neither `a` nor `b` are zero and either `c` or `d` is zero. >>> from sympy.abc import x, y, a, b, c, d >>> from sympy.solvers.ode import dsolve, checkodesol >>> from sympy import pprint, Function >>> f = Function('f') >>> y = f(x) >>> genform = a*y.diff(x) - (b*y**2 + c*y/x + d/x**2) >>> sol = dsolve(genform, y) >>> pprint(sol, wrap_line=False) / / __________________ \\ | __________________ | / 2 || | / 2 | \/ 4*b*d - (a + c) *log(x)|| -|a + c - \/ 4*b*d - (a + c) *tan|C1 + ----------------------------|| \ \ 2*a // f(x) = ------------------------------------------------------------------------ 2*b*x >>> checkodesol(genform, sol, order=1)[0] True References ========== 1. http://www.maplesoft.com/support/help/Maple/view.aspx?path=odeadvisor/Riccati 2. http://eqworld.ipmnet.ru/en/solutions/ode/ode0106.pdf - http://eqworld.ipmnet.ru/en/solutions/ode/ode0123.pdf """ x = func.args[0] f = func.func r = match # a2*diff(f(x),x) + b2*f(x) + c2*f(x)/x + d2/x**2 a2, b2, c2, d2 = [r[r[s]] for s in 'a2 b2 c2 d2'.split()] C1 = get_numbered_constants(eq, num=1) mu = sqrt(4*d2*b2 - (a2 - c2)**2) return Eq(f(x), (a2 - c2 - mu*tan(mu/(2*a2)*log(x) + C1))/(2*b2*x)) def ode_Liouville(eq, func, order, match): r""" Solves 2nd order Liouville differential equations. The general form of a Liouville ODE is .. math:: \frac{d^2 y}{dx^2} + g(y) \left(\! \frac{dy}{dx}\!\right)^2 + h(x) \frac{dy}{dx}\text{.} The general solution is: >>> from sympy import Function, dsolve, Eq, pprint, diff >>> from sympy.abc import x >>> f, g, h = map(Function, ['f', 'g', 'h']) >>> genform = Eq(diff(f(x),x,x) + g(f(x))*diff(f(x),x)**2 + ... h(x)*diff(f(x),x), 0) >>> pprint(genform) 2 2 /d \ d d g(f(x))*|--(f(x))| + h(x)*--(f(x)) + ---(f(x)) = 0 \dx / dx 2 dx >>> pprint(dsolve(genform, f(x), hint='Liouville_Integral')) f(x) / / | | | / | / | | | | | - | h(x) dx | | g(y) dy | | | | | / | / C1 + C2* | e dx + | e dy = 0 | | / / Examples ======== >>> from sympy import Function, dsolve, Eq, pprint >>> from sympy.abc import x >>> f = Function('f') >>> pprint(dsolve(diff(f(x), x, x) + diff(f(x), x)**2/f(x) + ... diff(f(x), x)/x, f(x), hint='Liouville')) ________________ ________________ [f(x) = -\/ C1 + C2*log(x) , f(x) = \/ C1 + C2*log(x) ] References ========== - Goldstein and Braun, "Advanced Methods for the Solution of Differential Equations", pp. 98 - http://www.maplesoft.com/support/help/Maple/view.aspx?path=odeadvisor/Liouville # indirect doctest """ # Liouville ODE: # f(x).diff(x, 2) + g(f(x))*(f(x).diff(x, 2))**2 + h(x)*f(x).diff(x) # See Goldstein and Braun, "Advanced Methods for the Solution of # Differential Equations", pg. 98, as well as # http://www.maplesoft.com/support/help/view.aspx?path=odeadvisor/Liouville x = func.args[0] f = func.func r = match # f(x).diff(x, 2) + g*f(x).diff(x)**2 + h*f(x).diff(x) y = r['y'] C1, C2 = get_numbered_constants(eq, num=2) int = Integral(exp(Integral(r['g'], y)), (y, None, f(x))) sol = Eq(int + C1*Integral(exp(-Integral(r['h'], x)), x) + C2, 0) return sol def ode_2nd_power_series_ordinary(eq, func, order, match): r""" Gives a power series solution to a second order homogeneous differential equation with polynomial coefficients at an ordinary point. A homogeneous differential equation is of the form .. math :: P(x)\frac{d^2y}{dx^2} + Q(x)\frac{dy}{dx} + R(x) = 0 For simplicity it is assumed that `P(x)`, `Q(x)` and `R(x)` are polynomials, it is sufficient that `\frac{Q(x)}{P(x)}` and `\frac{R(x)}{P(x)}` exists at `x_{0}`. A recurrence relation is obtained by substituting `y` as `\sum_{n=0}^\infty a_{n}x^{n}`, in the differential equation, and equating the nth term. Using this relation various terms can be generated. Examples ======== >>> from sympy import dsolve, Function, pprint >>> from sympy.abc import x, y >>> f = Function("f") >>> eq = f(x).diff(x, 2) + f(x) >>> pprint(dsolve(eq, hint='2nd_power_series_ordinary')) / 4 2 \ / 2\ |x x | | x | / 6\ f(x) = C2*|-- - -- + 1| + C1*x*|1 - --| + O\x / \24 2 / \ 6 / References ========== - http://tutorial.math.lamar.edu/Classes/DE/SeriesSolutions.aspx - George E. Simmons, "Differential Equations with Applications and Historical Notes", p.p 176 - 184 """ x = func.args[0] f = func.func C0, C1 = get_numbered_constants(eq, num=2) n = Dummy("n", integer=True) s = Wild("s") k = Wild("k", exclude=[x]) x0 = match.get('x0') terms = match.get('terms', 5) p = match[match['a3']] q = match[match['b3']] r = match[match['c3']] seriesdict = {} recurr = Function("r") # Generating the recurrence relation which works this way: # for the second order term the summation begins at n = 2. The coefficients # p is multiplied with an*(n - 1)*(n - 2)*x**n-2 and a substitution is made such that # the exponent of x becomes n. # For example, if p is x, then the second degree recurrence term is # an*(n - 1)*(n - 2)*x**n-1, substituting (n - 1) as n, it transforms to # an+1*n*(n - 1)*x**n. # A similar process is done with the first order and zeroth order term. coefflist = [(recurr(n), r), (n*recurr(n), q), (n*(n - 1)*recurr(n), p)] for index, coeff in enumerate(coefflist): if coeff[1]: f2 = powsimp(expand((coeff[1]*(x - x0)**(n - index)).subs(x, x + x0))) if f2.is_Add: addargs = f2.args else: addargs = [f2] for arg in addargs: powm = arg.match(s*x**k) term = coeff[0]*powm[s] if not powm[k].is_Symbol: term = term.subs(n, n - powm[k].as_independent(n)[0]) startind = powm[k].subs(n, index) # Seeing if the startterm can be reduced further. # If it vanishes for n lesser than startind, it is # equal to summation from n. if startind: for i in reversed(range(startind)): if not term.subs(n, i): seriesdict[term] = i else: seriesdict[term] = i + 1 break else: seriesdict[term] = S.Zero # Stripping of terms so that the sum starts with the same number. teq = S.Zero suminit = seriesdict.values() rkeys = seriesdict.keys() req = Add(*rkeys) if any(suminit): maxval = max(suminit) for term in seriesdict: val = seriesdict[term] if val != maxval: for i in range(val, maxval): teq += term.subs(n, val) finaldict = {} if teq: fargs = teq.atoms(AppliedUndef) if len(fargs) == 1: finaldict[fargs.pop()] = 0 else: maxf = max(fargs, key = lambda x: x.args[0]) sol = solve(teq, maxf) if isinstance(sol, list): sol = sol[0] finaldict[maxf] = sol # Finding the recurrence relation in terms of the largest term. fargs = req.atoms(AppliedUndef) maxf = max(fargs, key = lambda x: x.args[0]) minf = min(fargs, key = lambda x: x.args[0]) if minf.args[0].is_Symbol: startiter = 0 else: startiter = -minf.args[0].as_independent(n)[0] lhs = maxf rhs = solve(req, maxf) if isinstance(rhs, list): rhs = rhs[0] # Checking how many values are already present tcounter = len([t for t in finaldict.values() if t]) for _ in range(tcounter, terms - 3): # Assuming c0 and c1 to be arbitrary check = rhs.subs(n, startiter) nlhs = lhs.subs(n, startiter) nrhs = check.subs(finaldict) finaldict[nlhs] = nrhs startiter += 1 # Post processing series = C0 + C1*(x - x0) for term in finaldict: if finaldict[term]: fact = term.args[0] series += (finaldict[term].subs([(recurr(0), C0), (recurr(1), C1)])*( x - x0)**fact) series = collect(expand_mul(series), [C0, C1]) + Order(x**terms) return Eq(f(x), series) def ode_2nd_linear_airy(eq, func, order, match): r""" Gives solution of the Airy differential equation .. math :: \frac{d^2y}{dx^2} + (a + b x) y(x) = 0 in terms of Airy special functions airyai and airybi. Examples ======== >>> from sympy import dsolve, Function, pprint >>> from sympy.abc import x >>> f = Function("f") >>> eq = f(x).diff(x, 2) - x*f(x) >>> dsolve(eq) Eq(f(x), C1*airyai(x) + C2*airybi(x)) """ x = func.args[0] f = func.func C0, C1 = get_numbered_constants(eq, num=2) b = match['b'] m = match['m'] if m.is_positive: arg = - b/cbrt(m)**2 - cbrt(m)*x elif m.is_negative: arg = - b/cbrt(-m)**2 + cbrt(-m)*x else: arg = - b/cbrt(-m)**2 + cbrt(-m)*x return Eq(f(x), C0*airyai(arg) + C1*airybi(arg)) def ode_2nd_power_series_regular(eq, func, order, match): r""" Gives a power series solution to a second order homogeneous differential equation with polynomial coefficients at a regular point. A second order homogeneous differential equation is of the form .. math :: P(x)\frac{d^2y}{dx^2} + Q(x)\frac{dy}{dx} + R(x) = 0 A point is said to regular singular at `x0` if `x - x0\frac{Q(x)}{P(x)}` and `(x - x0)^{2}\frac{R(x)}{P(x)}` are analytic at `x0`. For simplicity `P(x)`, `Q(x)` and `R(x)` are assumed to be polynomials. The algorithm for finding the power series solutions is: 1. Try expressing `(x - x0)P(x)` and `((x - x0)^{2})Q(x)` as power series solutions about x0. Find `p0` and `q0` which are the constants of the power series expansions. 2. Solve the indicial equation `f(m) = m(m - 1) + m*p0 + q0`, to obtain the roots `m1` and `m2` of the indicial equation. 3. If `m1 - m2` is a non integer there exists two series solutions. If `m1 = m2`, there exists only one solution. If `m1 - m2` is an integer, then the existence of one solution is confirmed. The other solution may or may not exist. The power series solution is of the form `x^{m}\sum_{n=0}^\infty a_{n}x^{n}`. The coefficients are determined by the following recurrence relation. `a_{n} = -\frac{\sum_{k=0}^{n-1} q_{n-k} + (m + k)p_{n-k}}{f(m + n)}`. For the case in which `m1 - m2` is an integer, it can be seen from the recurrence relation that for the lower root `m`, when `n` equals the difference of both the roots, the denominator becomes zero. So if the numerator is not equal to zero, a second series solution exists. Examples ======== >>> from sympy import dsolve, Function, pprint >>> from sympy.abc import x, y >>> f = Function("f") >>> eq = x*(f(x).diff(x, 2)) + 2*(f(x).diff(x)) + x*f(x) >>> pprint(dsolve(eq, hint='2nd_power_series_regular')) / 6 4 2 \ | x x x | / 4 2 \ C1*|- --- + -- - -- + 1| | x x | \ 720 24 2 / / 6\ f(x) = C2*|--- - -- + 1| + ------------------------ + O\x / \120 6 / x References ========== - George E. Simmons, "Differential Equations with Applications and Historical Notes", p.p 176 - 184 """ x = func.args[0] f = func.func C0, C1 = get_numbered_constants(eq, num=2) m = Dummy("m") # for solving the indicial equation x0 = match.get('x0') terms = match.get('terms', 5) p = match['p'] q = match['q'] # Generating the indicial equation indicial = [] for term in [p, q]: if not term.has(x): indicial.append(term) else: term = series(term, n=1, x0=x0) if isinstance(term, Order): indicial.append(S.Zero) else: for arg in term.args: if not arg.has(x): indicial.append(arg) break p0, q0 = indicial sollist = solve(m*(m - 1) + m*p0 + q0, m) if sollist and isinstance(sollist, list) and all( [sol.is_real for sol in sollist]): serdict1 = {} serdict2 = {} if len(sollist) == 1: # Only one series solution exists in this case. m1 = m2 = sollist.pop() if terms-m1-1 <= 0: return Eq(f(x), Order(terms)) serdict1 = _frobenius(terms-m1-1, m1, p0, q0, p, q, x0, x, C0) else: m1 = sollist[0] m2 = sollist[1] if m1 < m2: m1, m2 = m2, m1 # Irrespective of whether m1 - m2 is an integer or not, one # Frobenius series solution exists. serdict1 = _frobenius(terms-m1-1, m1, p0, q0, p, q, x0, x, C0) if not (m1 - m2).is_integer: # Second frobenius series solution exists. serdict2 = _frobenius(terms-m2-1, m2, p0, q0, p, q, x0, x, C1) else: # Check if second frobenius series solution exists. serdict2 = _frobenius(terms-m2-1, m2, p0, q0, p, q, x0, x, C1, check=m1) if serdict1: finalseries1 = C0 for key in serdict1: power = int(key.name[1:]) finalseries1 += serdict1[key]*(x - x0)**power finalseries1 = (x - x0)**m1*finalseries1 finalseries2 = S.Zero if serdict2: for key in serdict2: power = int(key.name[1:]) finalseries2 += serdict2[key]*(x - x0)**power finalseries2 += C1 finalseries2 = (x - x0)**m2*finalseries2 return Eq(f(x), collect(finalseries1 + finalseries2, [C0, C1]) + Order(x**terms)) def ode_2nd_linear_bessel(eq, func, order, match): r""" Gives solution of the Bessel differential equation .. math :: x^2 \frac{d^2y}{dx^2} + x \frac{dy}{dx} y(x) + (x^2-n^2) y(x) if n is integer then the solution is of the form Eq(f(x), C0 besselj(n,x) + C1 bessely(n,x)) as both the solutions are linearly independent else if n is a fraction then the solution is of the form Eq(f(x), C0 besselj(n,x) + C1 besselj(-n,x)) which can also transform into Eq(f(x), C0 besselj(n,x) + C1 bessely(n,x)). Examples ======== >>> from sympy.abc import x, y, a >>> from sympy import Symbol >>> v = Symbol('v', positive=True) >>> from sympy.solvers.ode import dsolve, checkodesol >>> from sympy import pprint, Function >>> f = Function('f') >>> y = f(x) >>> genform = x**2*y.diff(x, 2) + x*y.diff(x) + (x**2 - v**2)*y >>> dsolve(genform) Eq(f(x), C1*besselj(v, x) + C2*bessely(v, x)) References ========== https://www.math24.net/bessel-differential-equation/ """ x = func.args[0] f = func.func C0, C1 = get_numbered_constants(eq, num=2) n = match['n'] a4 = match['a4'] c4 = match['c4'] d4 = match['d4'] b4 = match['b4'] n = sqrt(n**2 + Rational(1, 4)*(c4 - 1)**2) return Eq(f(x), ((x**(Rational(1-c4,2)))*(C0*besselj(n/d4,a4*x**d4/d4) + C1*bessely(n/d4,a4*x**d4/d4))).subs(x, x-b4)) def _frobenius(n, m, p0, q0, p, q, x0, x, c, check=None): r""" Returns a dict with keys as coefficients and values as their values in terms of C0 """ n = int(n) # In cases where m1 - m2 is not an integer m2 = check d = Dummy("d") numsyms = numbered_symbols("C", start=0) numsyms = [next(numsyms) for i in range(n + 1)] serlist = [] for ser in [p, q]: # Order term not present if ser.is_polynomial(x) and Poly(ser, x).degree() <= n: if x0: ser = ser.subs(x, x + x0) dict_ = Poly(ser, x).as_dict() # Order term present else: tseries = series(ser, x=x0, n=n+1) # Removing order dict_ = Poly(list(ordered(tseries.args))[: -1], x).as_dict() # Fill in with zeros, if coefficients are zero. for i in range(n + 1): if (i,) not in dict_: dict_[(i,)] = S.Zero serlist.append(dict_) pseries = serlist[0] qseries = serlist[1] indicial = d*(d - 1) + d*p0 + q0 frobdict = {} for i in range(1, n + 1): num = c*(m*pseries[(i,)] + qseries[(i,)]) for j in range(1, i): sym = Symbol("C" + str(j)) num += frobdict[sym]*((m + j)*pseries[(i - j,)] + qseries[(i - j,)]) # Checking for cases when m1 - m2 is an integer. If num equals zero # then a second Frobenius series solution cannot be found. If num is not zero # then set constant as zero and proceed. if m2 is not None and i == m2 - m: if num: return False else: frobdict[numsyms[i]] = S.Zero else: frobdict[numsyms[i]] = -num/(indicial.subs(d, m+i)) return frobdict def _nth_order_reducible_match(eq, func): r""" Matches any differential equation that can be rewritten with a smaller order. Only derivatives of ``func`` alone, wrt a single variable, are considered, and only in them should ``func`` appear. """ # ODE only handles functions of 1 variable so this affirms that state assert len(func.args) == 1 x = func.args[0] vc = [d.variable_count[0] for d in eq.atoms(Derivative) if d.expr == func and len(d.variable_count) == 1] ords = [c for v, c in vc if v == x] if len(ords) < 2: return smallest = min(ords) # make sure func does not appear outside of derivatives D = Dummy() if eq.subs(func.diff(x, smallest), D).has(func): return return {'n': smallest} def ode_nth_order_reducible(eq, func, order, match): r""" Solves ODEs that only involve derivatives of the dependent variable using a substitution of the form `f^n(x) = g(x)`. For example any second order ODE of the form `f''(x) = h(f'(x), x)` can be transformed into a pair of 1st order ODEs `g'(x) = h(g(x), x)` and `f'(x) = g(x)`. Usually the 1st order ODE for `g` is easier to solve. If that gives an explicit solution for `g` then `f` is found simply by integration. Examples ======== >>> from sympy import Function, dsolve, Eq >>> from sympy.abc import x >>> f = Function('f') >>> eq = Eq(x*f(x).diff(x)**2 + f(x).diff(x, 2), 0) >>> dsolve(eq, f(x), hint='nth_order_reducible') ... # doctest: +NORMALIZE_WHITESPACE Eq(f(x), C1 - sqrt(-1/C2)*log(-C2*sqrt(-1/C2) + x) + sqrt(-1/C2)*log(C2*sqrt(-1/C2) + x)) """ x = func.args[0] f = func.func n = match['n'] # get a unique function name for g names = [a.name for a in eq.atoms(AppliedUndef)] while True: name = Dummy().name if name not in names: g = Function(name) break w = f(x).diff(x, n) geq = eq.subs(w, g(x)) gsol = dsolve(geq, g(x)) if not isinstance(gsol, list): gsol = [gsol] # Might be multiple solutions to the reduced ODE: fsol = [] for gsoli in gsol: fsoli = dsolve(gsoli.subs(g(x), w), f(x)) # or do integration n times fsol.append(fsoli) if len(fsol) == 1: fsol = fsol[0] return fsol # This needs to produce an invertible function but the inverse depends # which variable we are integrating with respect to. Since the class can # be stored in cached results we need to ensure that we always get the # same class back for each particular integration variable so we store these # classes in a global dict: _nth_algebraic_diffx_stored = {} # type: Dict[Symbol, Type[Function]] def _nth_algebraic_diffx(var): cls = _nth_algebraic_diffx_stored.get(var, None) if cls is None: # A class that behaves like Derivative wrt var but is "invertible". class diffx(Function): def inverse(self): # don't use integrate here because fx has been replaced by _t # in the equation; integrals will not be correct while solve # is at work. return lambda expr: Integral(expr, var) + Dummy('C') cls = _nth_algebraic_diffx_stored.setdefault(var, diffx) return cls def _nth_algebraic_match(eq, func): r""" Matches any differential equation that nth_algebraic can solve. Uses `sympy.solve` but teaches it how to integrate derivatives. This involves calling `sympy.solve` and does most of the work of finding a solution (apart from evaluating the integrals). """ # The independent variable var = func.args[0] # Derivative that solve can handle: diffx = _nth_algebraic_diffx(var) # Replace derivatives wrt the independent variable with diffx def replace(eq, var): def expand_diffx(*args): differand, diffs = args[0], args[1:] toreplace = differand for v, n in diffs: for _ in range(n): if v == var: toreplace = diffx(toreplace) else: toreplace = Derivative(toreplace, v) return toreplace return eq.replace(Derivative, expand_diffx) # Restore derivatives in solution afterwards def unreplace(eq, var): return eq.replace(diffx, lambda e: Derivative(e, var)) subs_eqn = replace(eq, var) try: # turn off simplification to protect Integrals that have # _t instead of fx in them and would otherwise factor # as t_*Integral(1, x) solns = solve(subs_eqn, func, simplify=False) except NotImplementedError: solns = [] solns = [simplify(unreplace(soln, var)) for soln in solns] solns = [Equality(func, soln) for soln in solns] return {'var':var, 'solutions':solns} def ode_nth_algebraic(eq, func, order, match): r""" Solves an `n`\th order ordinary differential equation using algebra and integrals. There is no general form for the kind of equation that this can solve. The the equation is solved algebraically treating differentiation as an invertible algebraic function. Examples ======== >>> from sympy import Function, dsolve, Eq >>> from sympy.abc import x >>> f = Function('f') >>> eq = Eq(f(x) * (f(x).diff(x)**2 - 1), 0) >>> dsolve(eq, f(x), hint='nth_algebraic') ... # doctest: +NORMALIZE_WHITESPACE [Eq(f(x), 0), Eq(f(x), C1 - x), Eq(f(x), C1 + x)] Note that this solver can return algebraic solutions that do not have any integration constants (f(x) = 0 in the above example). # indirect doctest """ return match['solutions'] def _remove_redundant_solutions(eq, solns, order, var): r""" Remove redundant solutions from the set of solutions. This function is needed because otherwise dsolve can return redundant solutions. As an example consider: eq = Eq((f(x).diff(x, 2))*f(x).diff(x), 0) There are two ways to find solutions to eq. The first is to solve f(x).diff(x, 2) = 0 leading to solution f(x)=C1 + C2*x. The second is to solve the equation f(x).diff(x) = 0 leading to the solution f(x) = C1. In this particular case we then see that the second solution is a special case of the first and we don't want to return it. This does not always happen. If we have eq = Eq((f(x)**2-4)*(f(x).diff(x)-4), 0) then we get the algebraic solution f(x) = [-2, 2] and the integral solution f(x) = x + C1 and in this case the two solutions are not equivalent wrt initial conditions so both should be returned. """ def is_special_case_of(soln1, soln2): return _is_special_case_of(soln1, soln2, eq, order, var) unique_solns = [] for soln1 in solns: for soln2 in unique_solns[:]: if is_special_case_of(soln1, soln2): break elif is_special_case_of(soln2, soln1): unique_solns.remove(soln2) else: unique_solns.append(soln1) return unique_solns def _is_special_case_of(soln1, soln2, eq, order, var): r""" True if soln1 is found to be a special case of soln2 wrt some value of the constants that appear in soln2. False otherwise. """ # The solutions returned by dsolve may be given explicitly or implicitly. # We will equate the sol1=(soln1.rhs - soln1.lhs), sol2=(soln2.rhs - soln2.lhs) # of the two solutions. # # Since this is supposed to hold for all x it also holds for derivatives. # For an order n ode we should be able to differentiate # each solution n times to get n+1 equations. # # We then try to solve those n+1 equations for the integrations constants # in sol2. If we can find a solution that doesn't depend on x then it # means that some value of the constants in sol1 is a special case of # sol2 corresponding to a particular choice of the integration constants. # In case the solution is in implicit form we subtract the sides soln1 = soln1.rhs - soln1.lhs soln2 = soln2.rhs - soln2.lhs # Work for the series solution if soln1.has(Order) and soln2.has(Order): if soln1.getO() == soln2.getO(): soln1 = soln1.removeO() soln2 = soln2.removeO() else: return False elif soln1.has(Order) or soln2.has(Order): return False constants1 = soln1.free_symbols.difference(eq.free_symbols) constants2 = soln2.free_symbols.difference(eq.free_symbols) constants1_new = get_numbered_constants(Tuple(soln1, soln2), len(constants1)) if len(constants1) == 1: constants1_new = {constants1_new} for c_old, c_new in zip(constants1, constants1_new): soln1 = soln1.subs(c_old, c_new) # n equations for sol1 = sol2, sol1'=sol2', ... lhs = soln1 rhs = soln2 eqns = [Eq(lhs, rhs)] for n in range(1, order): lhs = lhs.diff(var) rhs = rhs.diff(var) eq = Eq(lhs, rhs) eqns.append(eq) # BooleanTrue/False awkwardly show up for trivial equations if any(isinstance(eq, BooleanFalse) for eq in eqns): return False eqns = [eq for eq in eqns if not isinstance(eq, BooleanTrue)] try: constant_solns = solve(eqns, constants2) except NotImplementedError: return False # Sometimes returns a dict and sometimes a list of dicts if isinstance(constant_solns, dict): constant_solns = [constant_solns] # after solving the issue 17418, maybe we don't need the following checksol code. for constant_soln in constant_solns: for eq in eqns: eq=eq.rhs-eq.lhs if checksol(eq, constant_soln) is not True: return False # If any solution gives all constants as expressions that don't depend on # x then there exists constants for soln2 that give soln1 for constant_soln in constant_solns: if not any(c.has(var) for c in constant_soln.values()): return True return False def _nth_linear_match(eq, func, order): r""" Matches a differential equation to the linear form: .. math:: a_n(x) y^{(n)} + \cdots + a_1(x)y' + a_0(x) y + B(x) = 0 Returns a dict of order:coeff terms, where order is the order of the derivative on each term, and coeff is the coefficient of that derivative. The key ``-1`` holds the function `B(x)`. Returns ``None`` if the ODE is not linear. This function assumes that ``func`` has already been checked to be good. Examples ======== >>> from sympy import Function, cos, sin >>> from sympy.abc import x >>> from sympy.solvers.ode.ode import _nth_linear_match >>> f = Function('f') >>> _nth_linear_match(f(x).diff(x, 3) + 2*f(x).diff(x) + ... x*f(x).diff(x, 2) + cos(x)*f(x).diff(x) + x - f(x) - ... sin(x), f(x), 3) {-1: x - sin(x), 0: -1, 1: cos(x) + 2, 2: x, 3: 1} >>> _nth_linear_match(f(x).diff(x, 3) + 2*f(x).diff(x) + ... x*f(x).diff(x, 2) + cos(x)*f(x).diff(x) + x - f(x) - ... sin(f(x)), f(x), 3) == None True """ x = func.args[0] one_x = {x} terms = {i: S.Zero for i in range(-1, order + 1)} for i in Add.make_args(eq): if not i.has(func): terms[-1] += i else: c, f = i.as_independent(func) if (isinstance(f, Derivative) and set(f.variables) == one_x and f.args[0] == func): terms[f.derivative_count] += c elif f == func: terms[len(f.args[1:])] += c else: return None return terms def ode_nth_linear_euler_eq_homogeneous(eq, func, order, match, returns='sol'): r""" Solves an `n`\th order linear homogeneous variable-coefficient Cauchy-Euler equidimensional ordinary differential equation. This is an equation with form `0 = a_0 f(x) + a_1 x f'(x) + a_2 x^2 f''(x) \cdots`. These equations can be solved in a general manner, by substituting solutions of the form `f(x) = x^r`, and deriving a characteristic equation for `r`. When there are repeated roots, we include extra terms of the form `C_{r k} \ln^k(x) x^r`, where `C_{r k}` is an arbitrary integration constant, `r` is a root of the characteristic equation, and `k` ranges over the multiplicity of `r`. In the cases where the roots are complex, solutions of the form `C_1 x^a \sin(b \log(x)) + C_2 x^a \cos(b \log(x))` are returned, based on expansions with Euler's formula. The general solution is the sum of the terms found. If SymPy cannot find exact roots to the characteristic equation, a :py:obj:`~.ComplexRootOf` instance will be returned instead. >>> from sympy import Function, dsolve, Eq >>> from sympy.abc import x >>> f = Function('f') >>> dsolve(4*x**2*f(x).diff(x, 2) + f(x), f(x), ... hint='nth_linear_euler_eq_homogeneous') ... # doctest: +NORMALIZE_WHITESPACE Eq(f(x), sqrt(x)*(C1 + C2*log(x))) Note that because this method does not involve integration, there is no ``nth_linear_euler_eq_homogeneous_Integral`` hint. The following is for internal use: - ``returns = 'sol'`` returns the solution to the ODE. - ``returns = 'list'`` returns a list of linearly independent solutions, corresponding to the fundamental solution set, for use with non homogeneous solution methods like variation of parameters and undetermined coefficients. Note that, though the solutions should be linearly independent, this function does not explicitly check that. You can do ``assert simplify(wronskian(sollist)) != 0`` to check for linear independence. Also, ``assert len(sollist) == order`` will need to pass. - ``returns = 'both'``, return a dictionary ``{'sol': <solution to ODE>, 'list': <list of linearly independent solutions>}``. Examples ======== >>> from sympy import Function, dsolve, pprint >>> from sympy.abc import x >>> f = Function('f') >>> eq = f(x).diff(x, 2)*x**2 - 4*f(x).diff(x)*x + 6*f(x) >>> pprint(dsolve(eq, f(x), ... hint='nth_linear_euler_eq_homogeneous')) 2 f(x) = x *(C1 + C2*x) References ========== - https://en.wikipedia.org/wiki/Cauchy%E2%80%93Euler_equation - C. Bender & S. Orszag, "Advanced Mathematical Methods for Scientists and Engineers", Springer 1999, pp. 12 # indirect doctest """ # XXX: This global collectterms hack should be removed. global collectterms collectterms = [] x = func.args[0] f = func.func r = match # First, set up characteristic equation. chareq, symbol = S.Zero, Dummy('x') for i in r.keys(): if not isinstance(i, str) and i >= 0: chareq += (r[i]*diff(x**symbol, x, i)*x**-symbol).expand() chareq = Poly(chareq, symbol) chareqroots = [rootof(chareq, k) for k in range(chareq.degree())] # A generator of constants constants = list(get_numbered_constants(eq, num=chareq.degree()*2)) constants.reverse() # Create a dict root: multiplicity or charroots charroots = defaultdict(int) for root in chareqroots: charroots[root] += 1 gsol = S.Zero # We need keep track of terms so we can run collect() at the end. # This is necessary for constantsimp to work properly. ln = log for root, multiplicity in charroots.items(): for i in range(multiplicity): if isinstance(root, RootOf): gsol += (x**root) * constants.pop() if multiplicity != 1: raise ValueError("Value should be 1") collectterms = [(0, root, 0)] + collectterms elif root.is_real: gsol += ln(x)**i*(x**root) * constants.pop() collectterms = [(i, root, 0)] + collectterms else: reroot = re(root) imroot = im(root) gsol += ln(x)**i * (x**reroot) * ( constants.pop() * sin(abs(imroot)*ln(x)) + constants.pop() * cos(imroot*ln(x))) # Preserve ordering (multiplicity, real part, imaginary part) # It will be assumed implicitly when constructing # fundamental solution sets. collectterms = [(i, reroot, imroot)] + collectterms if returns == 'sol': return Eq(f(x), gsol) elif returns in ('list' 'both'): # HOW TO TEST THIS CODE? (dsolve does not pass 'returns' through) # Create a list of (hopefully) linearly independent solutions gensols = [] # Keep track of when to use sin or cos for nonzero imroot for i, reroot, imroot in collectterms: if imroot == 0: gensols.append(ln(x)**i*x**reroot) else: sin_form = ln(x)**i*x**reroot*sin(abs(imroot)*ln(x)) if sin_form in gensols: cos_form = ln(x)**i*x**reroot*cos(imroot*ln(x)) gensols.append(cos_form) else: gensols.append(sin_form) if returns == 'list': return gensols else: return {'sol': Eq(f(x), gsol), 'list': gensols} else: raise ValueError('Unknown value for key "returns".') def ode_nth_linear_euler_eq_nonhomogeneous_undetermined_coefficients(eq, func, order, match, returns='sol'): r""" Solves an `n`\th order linear non homogeneous Cauchy-Euler equidimensional ordinary differential equation using undetermined coefficients. This is an equation with form `g(x) = a_0 f(x) + a_1 x f'(x) + a_2 x^2 f''(x) \cdots`. These equations can be solved in a general manner, by substituting solutions of the form `x = exp(t)`, and deriving a characteristic equation of form `g(exp(t)) = b_0 f(t) + b_1 f'(t) + b_2 f''(t) \cdots` which can be then solved by nth_linear_constant_coeff_undetermined_coefficients if g(exp(t)) has finite number of linearly independent derivatives. Functions that fit this requirement are finite sums functions of the form `a x^i e^{b x} \sin(c x + d)` or `a x^i e^{b x} \cos(c x + d)`, where `i` is a non-negative integer and `a`, `b`, `c`, and `d` are constants. For example any polynomial in `x`, functions like `x^2 e^{2 x}`, `x \sin(x)`, and `e^x \cos(x)` can all be used. Products of `\sin`'s and `\cos`'s have a finite number of derivatives, because they can be expanded into `\sin(a x)` and `\cos(b x)` terms. However, SymPy currently cannot do that expansion, so you will need to manually rewrite the expression in terms of the above to use this method. So, for example, you will need to manually convert `\sin^2(x)` into `(1 + \cos(2 x))/2` to properly apply the method of undetermined coefficients on it. After replacement of x by exp(t), this method works by creating a trial function from the expression and all of its linear independent derivatives and substituting them into the original ODE. The coefficients for each term will be a system of linear equations, which are be solved for and substituted, giving the solution. If any of the trial functions are linearly dependent on the solution to the homogeneous equation, they are multiplied by sufficient `x` to make them linearly independent. Examples ======== >>> from sympy import dsolve, Function, Derivative, log >>> from sympy.abc import x >>> f = Function('f') >>> eq = x**2*Derivative(f(x), x, x) - 2*x*Derivative(f(x), x) + 2*f(x) - log(x) >>> dsolve(eq, f(x), ... hint='nth_linear_euler_eq_nonhomogeneous_undetermined_coefficients').expand() Eq(f(x), C1*x + C2*x**2 + log(x)/2 + 3/4) """ x = func.args[0] f = func.func r = match chareq, eq, symbol = S.Zero, S.Zero, Dummy('x') for i in r.keys(): if not isinstance(i, str) and i >= 0: chareq += (r[i]*diff(x**symbol, x, i)*x**-symbol).expand() for i in range(1,degree(Poly(chareq, symbol))+1): eq += chareq.coeff(symbol**i)*diff(f(x), x, i) if chareq.as_coeff_add(symbol)[0]: eq += chareq.as_coeff_add(symbol)[0]*f(x) e, re = posify(r[-1].subs(x, exp(x))) eq += e.subs(re) match = _nth_linear_match(eq, f(x), ode_order(eq, f(x))) eq_homogeneous = Add(eq,-match[-1]) match['trialset'] = _undetermined_coefficients_match(match[-1], x, func, eq_homogeneous)['trialset'] return ode_nth_linear_constant_coeff_undetermined_coefficients(eq, func, order, match).subs(x, log(x)).subs(f(log(x)), f(x)).expand() def ode_nth_linear_euler_eq_nonhomogeneous_variation_of_parameters(eq, func, order, match, returns='sol'): r""" Solves an `n`\th order linear non homogeneous Cauchy-Euler equidimensional ordinary differential equation using variation of parameters. This is an equation with form `g(x) = a_0 f(x) + a_1 x f'(x) + a_2 x^2 f''(x) \cdots`. This method works by assuming that the particular solution takes the form .. math:: \sum_{x=1}^{n} c_i(x) y_i(x) {a_n} {x^n} \text{,} where `y_i` is the `i`\th solution to the homogeneous equation. The solution is then solved using Wronskian's and Cramer's Rule. The particular solution is given by multiplying eq given below with `a_n x^{n}` .. math:: \sum_{x=1}^n \left( \int \frac{W_i(x)}{W(x)} \,dx \right) y_i(x) \text{,} where `W(x)` is the Wronskian of the fundamental system (the system of `n` linearly independent solutions to the homogeneous equation), and `W_i(x)` is the Wronskian of the fundamental system with the `i`\th column replaced with `[0, 0, \cdots, 0, \frac{x^{- n}}{a_n} g{\left(x \right)}]`. This method is general enough to solve any `n`\th order inhomogeneous linear differential equation, but sometimes SymPy cannot simplify the Wronskian well enough to integrate it. If this method hangs, try using the ``nth_linear_constant_coeff_variation_of_parameters_Integral`` hint and simplifying the integrals manually. Also, prefer using ``nth_linear_constant_coeff_undetermined_coefficients`` when it applies, because it doesn't use integration, making it faster and more reliable. Warning, using simplify=False with 'nth_linear_constant_coeff_variation_of_parameters' in :py:meth:`~sympy.solvers.ode.dsolve` may cause it to hang, because it will not attempt to simplify the Wronskian before integrating. It is recommended that you only use simplify=False with 'nth_linear_constant_coeff_variation_of_parameters_Integral' for this method, especially if the solution to the homogeneous equation has trigonometric functions in it. Examples ======== >>> from sympy import Function, dsolve, Derivative >>> from sympy.abc import x >>> f = Function('f') >>> eq = x**2*Derivative(f(x), x, x) - 2*x*Derivative(f(x), x) + 2*f(x) - x**4 >>> dsolve(eq, f(x), ... hint='nth_linear_euler_eq_nonhomogeneous_variation_of_parameters').expand() Eq(f(x), C1*x + C2*x**2 + x**4/6) """ x = func.args[0] f = func.func r = match gensol = ode_nth_linear_euler_eq_homogeneous(eq, func, order, match, returns='both') match.update(gensol) r[-1] = r[-1]/r[ode_order(eq, f(x))] sol = _solve_variation_of_parameters(eq, func, order, match) return Eq(f(x), r['sol'].rhs + (sol.rhs - r['sol'].rhs)*r[ode_order(eq, f(x))]) def ode_almost_linear(eq, func, order, match): r""" Solves an almost-linear differential equation. The general form of an almost linear differential equation is .. math:: f(x) g(y) y + k(x) l(y) + m(x) = 0 \text{where} l'(y) = g(y)\text{.} This can be solved by substituting `l(y) = u(y)`. Making the given substitution reduces it to a linear differential equation of the form `u' + P(x) u + Q(x) = 0`. The general solution is >>> from sympy import Function, dsolve, Eq, pprint >>> from sympy.abc import x, y, n >>> f, g, k, l = map(Function, ['f', 'g', 'k', 'l']) >>> genform = Eq(f(x)*(l(y).diff(y)) + k(x)*l(y) + g(x), 0) >>> pprint(genform) d f(x)*--(l(y)) + g(x) + k(x)*l(y) = 0 dy >>> pprint(dsolve(genform, hint = 'almost_linear')) / // y*k(x) \\ | || ------ || | || f(x) || -y*k(x) | ||-g(x)*e || -------- | ||-------------- for k(x) != 0|| f(x) l(y) = |C1 + |< k(x) ||*e | || || | || -y*g(x) || | || -------- otherwise || | || f(x) || \ \\ // See Also ======== :meth:`sympy.solvers.ode.ode.ode_1st_linear` Examples ======== >>> from sympy import Function, Derivative, pprint >>> from sympy.solvers.ode import dsolve, classify_ode >>> from sympy.abc import x >>> f = Function('f') >>> d = f(x).diff(x) >>> eq = x*d + x*f(x) + 1 >>> dsolve(eq, f(x), hint='almost_linear') Eq(f(x), (C1 - Ei(x))*exp(-x)) >>> pprint(dsolve(eq, f(x), hint='almost_linear')) -x f(x) = (C1 - Ei(x))*e References ========== - Joel Moses, "Symbolic Integration - The Stormy Decade", Communications of the ACM, Volume 14, Number 8, August 1971, pp. 558 """ # Since ode_1st_linear has already been implemented, and the # coefficients have been modified to the required form in # classify_ode, just passing eq, func, order and match to # ode_1st_linear will give the required output. return ode_1st_linear(eq, func, order, match) def _linear_coeff_match(expr, func): r""" Helper function to match hint ``linear_coefficients``. Matches the expression to the form `(a_1 x + b_1 f(x) + c_1)/(a_2 x + b_2 f(x) + c_2)` where the following conditions hold: 1. `a_1`, `b_1`, `c_1`, `a_2`, `b_2`, `c_2` are Rationals; 2. `c_1` or `c_2` are not equal to zero; 3. `a_2 b_1 - a_1 b_2` is not equal to zero. Return ``xarg``, ``yarg`` where 1. ``xarg`` = `(b_2 c_1 - b_1 c_2)/(a_2 b_1 - a_1 b_2)` 2. ``yarg`` = `(a_1 c_2 - a_2 c_1)/(a_2 b_1 - a_1 b_2)` Examples ======== >>> from sympy import Function >>> from sympy.abc import x >>> from sympy.solvers.ode.ode import _linear_coeff_match >>> from sympy.functions.elementary.trigonometric import sin >>> f = Function('f') >>> _linear_coeff_match(( ... (-25*f(x) - 8*x + 62)/(4*f(x) + 11*x - 11)), f(x)) (1/9, 22/9) >>> _linear_coeff_match( ... sin((-5*f(x) - 8*x + 6)/(4*f(x) + x - 1)), f(x)) (19/27, 2/27) >>> _linear_coeff_match(sin(f(x)/x), f(x)) """ f = func.func x = func.args[0] def abc(eq): r''' Internal function of _linear_coeff_match that returns Rationals a, b, c if eq is a*x + b*f(x) + c, else None. ''' eq = _mexpand(eq) c = eq.as_independent(x, f(x), as_Add=True)[0] if not c.is_Rational: return a = eq.coeff(x) if not a.is_Rational: return b = eq.coeff(f(x)) if not b.is_Rational: return if eq == a*x + b*f(x) + c: return a, b, c def match(arg): r''' Internal function of _linear_coeff_match that returns Rationals a1, b1, c1, a2, b2, c2 and a2*b1 - a1*b2 of the expression (a1*x + b1*f(x) + c1)/(a2*x + b2*f(x) + c2) if one of c1 or c2 and a2*b1 - a1*b2 is non-zero, else None. ''' n, d = arg.together().as_numer_denom() m = abc(n) if m is not None: a1, b1, c1 = m m = abc(d) if m is not None: a2, b2, c2 = m d = a2*b1 - a1*b2 if (c1 or c2) and d: return a1, b1, c1, a2, b2, c2, d m = [fi.args[0] for fi in expr.atoms(Function) if fi.func != f and len(fi.args) == 1 and not fi.args[0].is_Function] or {expr} m1 = match(m.pop()) if m1 and all(match(mi) == m1 for mi in m): a1, b1, c1, a2, b2, c2, denom = m1 return (b2*c1 - b1*c2)/denom, (a1*c2 - a2*c1)/denom def ode_linear_coefficients(eq, func, order, match): r""" Solves a differential equation with linear coefficients. The general form of a differential equation with linear coefficients is .. math:: y' + F\left(\!\frac{a_1 x + b_1 y + c_1}{a_2 x + b_2 y + c_2}\!\right) = 0\text{,} where `a_1`, `b_1`, `c_1`, `a_2`, `b_2`, `c_2` are constants and `a_1 b_2 - a_2 b_1 \ne 0`. This can be solved by substituting: .. math:: x = x' + \frac{b_2 c_1 - b_1 c_2}{a_2 b_1 - a_1 b_2} y = y' + \frac{a_1 c_2 - a_2 c_1}{a_2 b_1 - a_1 b_2}\text{.} This substitution reduces the equation to a homogeneous differential equation. See Also ======== :meth:`sympy.solvers.ode.ode.ode_1st_homogeneous_coeff_best` :meth:`sympy.solvers.ode.ode.ode_1st_homogeneous_coeff_subs_indep_div_dep` :meth:`sympy.solvers.ode.ode.ode_1st_homogeneous_coeff_subs_dep_div_indep` Examples ======== >>> from sympy import Function, Derivative, pprint >>> from sympy.solvers.ode import dsolve, classify_ode >>> from sympy.abc import x >>> f = Function('f') >>> df = f(x).diff(x) >>> eq = (x + f(x) + 1)*df + (f(x) - 6*x + 1) >>> dsolve(eq, hint='linear_coefficients') [Eq(f(x), -x - sqrt(C1 + 7*x**2) - 1), Eq(f(x), -x + sqrt(C1 + 7*x**2) - 1)] >>> pprint(dsolve(eq, hint='linear_coefficients')) ___________ ___________ / 2 / 2 [f(x) = -x - \/ C1 + 7*x - 1, f(x) = -x + \/ C1 + 7*x - 1] References ========== - Joel Moses, "Symbolic Integration - The Stormy Decade", Communications of the ACM, Volume 14, Number 8, August 1971, pp. 558 """ return ode_1st_homogeneous_coeff_best(eq, func, order, match) def ode_separable_reduced(eq, func, order, match): r""" Solves a differential equation that can be reduced to the separable form. The general form of this equation is .. math:: y' + (y/x) H(x^n y) = 0\text{}. This can be solved by substituting `u(y) = x^n y`. The equation then reduces to the separable form `\frac{u'}{u (\mathrm{power} - H(u))} - \frac{1}{x} = 0`. The general solution is: >>> from sympy import Function, dsolve, Eq, pprint >>> from sympy.abc import x, n >>> f, g = map(Function, ['f', 'g']) >>> genform = f(x).diff(x) + (f(x)/x)*g(x**n*f(x)) >>> pprint(genform) / n \ d f(x)*g\x *f(x)/ --(f(x)) + --------------- dx x >>> pprint(dsolve(genform, hint='separable_reduced')) n x *f(x) / | | 1 | ------------ dy = C1 + log(x) | y*(n - g(y)) | / See Also ======== :meth:`sympy.solvers.ode.ode.ode_separable` Examples ======== >>> from sympy import Function, Derivative, pprint >>> from sympy.solvers.ode import dsolve, classify_ode >>> from sympy.abc import x >>> f = Function('f') >>> d = f(x).diff(x) >>> eq = (x - x**2*f(x))*d - f(x) >>> dsolve(eq, hint='separable_reduced') [Eq(f(x), (1 - sqrt(C1*x**2 + 1))/x), Eq(f(x), (sqrt(C1*x**2 + 1) + 1)/x)] >>> pprint(dsolve(eq, hint='separable_reduced')) ___________ ___________ / 2 / 2 1 - \/ C1*x + 1 \/ C1*x + 1 + 1 [f(x) = ------------------, f(x) = ------------------] x x References ========== - Joel Moses, "Symbolic Integration - The Stormy Decade", Communications of the ACM, Volume 14, Number 8, August 1971, pp. 558 """ # Arguments are passed in a way so that they are coherent with the # ode_separable function x = func.args[0] f = func.func y = Dummy('y') u = match['u'].subs(match['t'], y) ycoeff = 1/(y*(match['power'] - u)) m1 = {y: 1, x: -1/x, 'coeff': 1} m2 = {y: ycoeff, x: 1, 'coeff': 1} r = {'m1': m1, 'm2': m2, 'y': y, 'hint': x**match['power']*f(x)} return ode_separable(eq, func, order, r) def ode_1st_power_series(eq, func, order, match): r""" The power series solution is a method which gives the Taylor series expansion to the solution of a differential equation. For a first order differential equation `\frac{dy}{dx} = h(x, y)`, a power series solution exists at a point `x = x_{0}` if `h(x, y)` is analytic at `x_{0}`. The solution is given by .. math:: y(x) = y(x_{0}) + \sum_{n = 1}^{\infty} \frac{F_{n}(x_{0},b)(x - x_{0})^n}{n!}, where `y(x_{0}) = b` is the value of y at the initial value of `x_{0}`. To compute the values of the `F_{n}(x_{0},b)` the following algorithm is followed, until the required number of terms are generated. 1. `F_1 = h(x_{0}, b)` 2. `F_{n+1} = \frac{\partial F_{n}}{\partial x} + \frac{\partial F_{n}}{\partial y}F_{1}` Examples ======== >>> from sympy import Function, Derivative, pprint, exp >>> from sympy.solvers.ode import dsolve >>> from sympy.abc import x >>> f = Function('f') >>> eq = exp(x)*(f(x).diff(x)) - f(x) >>> pprint(dsolve(eq, hint='1st_power_series')) 3 4 5 C1*x C1*x C1*x / 6\ f(x) = C1 + C1*x - ----- + ----- + ----- + O\x / 6 24 60 References ========== - Travis W. Walker, Analytic power series technique for solving first-order differential equations, p.p 17, 18 """ x = func.args[0] y = match['y'] f = func.func h = -match[match['d']]/match[match['e']] point = match.get('f0') value = match.get('f0val') terms = match.get('terms') # First term F = h if not h: return Eq(f(x), value) # Initialization series = value if terms > 1: hc = h.subs({x: point, y: value}) if hc.has(oo) or hc.has(NaN) or hc.has(zoo): # Derivative does not exist, not analytic return Eq(f(x), oo) elif hc: series += hc*(x - point) for factcount in range(2, terms): Fnew = F.diff(x) + F.diff(y)*h Fnewc = Fnew.subs({x: point, y: value}) # Same logic as above if Fnewc.has(oo) or Fnewc.has(NaN) or Fnewc.has(-oo) or Fnewc.has(zoo): return Eq(f(x), oo) series += Fnewc*((x - point)**factcount)/factorial(factcount) F = Fnew series += Order(x**terms) return Eq(f(x), series) def ode_nth_linear_constant_coeff_homogeneous(eq, func, order, match, returns='sol'): r""" Solves an `n`\th order linear homogeneous differential equation with constant coefficients. This is an equation of the form .. math:: a_n f^{(n)}(x) + a_{n-1} f^{(n-1)}(x) + \cdots + a_1 f'(x) + a_0 f(x) = 0\text{.} These equations can be solved in a general manner, by taking the roots of the characteristic equation `a_n m^n + a_{n-1} m^{n-1} + \cdots + a_1 m + a_0 = 0`. The solution will then be the sum of `C_n x^i e^{r x}` terms, for each where `C_n` is an arbitrary constant, `r` is a root of the characteristic equation and `i` is one of each from 0 to the multiplicity of the root - 1 (for example, a root 3 of multiplicity 2 would create the terms `C_1 e^{3 x} + C_2 x e^{3 x}`). The exponential is usually expanded for complex roots using Euler's equation `e^{I x} = \cos(x) + I \sin(x)`. Complex roots always come in conjugate pairs in polynomials with real coefficients, so the two roots will be represented (after simplifying the constants) as `e^{a x} \left(C_1 \cos(b x) + C_2 \sin(b x)\right)`. If SymPy cannot find exact roots to the characteristic equation, a :py:class:`~sympy.polys.rootoftools.ComplexRootOf` instance will be return instead. >>> from sympy import Function, dsolve, Eq >>> from sympy.abc import x >>> f = Function('f') >>> dsolve(f(x).diff(x, 5) + 10*f(x).diff(x) - 2*f(x), f(x), ... hint='nth_linear_constant_coeff_homogeneous') ... # doctest: +NORMALIZE_WHITESPACE Eq(f(x), C5*exp(x*CRootOf(_x**5 + 10*_x - 2, 0)) + (C1*sin(x*im(CRootOf(_x**5 + 10*_x - 2, 1))) + C2*cos(x*im(CRootOf(_x**5 + 10*_x - 2, 1))))*exp(x*re(CRootOf(_x**5 + 10*_x - 2, 1))) + (C3*sin(x*im(CRootOf(_x**5 + 10*_x - 2, 3))) + C4*cos(x*im(CRootOf(_x**5 + 10*_x - 2, 3))))*exp(x*re(CRootOf(_x**5 + 10*_x - 2, 3)))) Note that because this method does not involve integration, there is no ``nth_linear_constant_coeff_homogeneous_Integral`` hint. The following is for internal use: - ``returns = 'sol'`` returns the solution to the ODE. - ``returns = 'list'`` returns a list of linearly independent solutions, for use with non homogeneous solution methods like variation of parameters and undetermined coefficients. Note that, though the solutions should be linearly independent, this function does not explicitly check that. You can do ``assert simplify(wronskian(sollist)) != 0`` to check for linear independence. Also, ``assert len(sollist) == order`` will need to pass. - ``returns = 'both'``, return a dictionary ``{'sol': <solution to ODE>, 'list': <list of linearly independent solutions>}``. Examples ======== >>> from sympy import Function, dsolve, pprint >>> from sympy.abc import x >>> f = Function('f') >>> pprint(dsolve(f(x).diff(x, 4) + 2*f(x).diff(x, 3) - ... 2*f(x).diff(x, 2) - 6*f(x).diff(x) + 5*f(x), f(x), ... hint='nth_linear_constant_coeff_homogeneous')) x -2*x f(x) = (C1 + C2*x)*e + (C3*sin(x) + C4*cos(x))*e References ========== - https://en.wikipedia.org/wiki/Linear_differential_equation section: Nonhomogeneous_equation_with_constant_coefficients - M. Tenenbaum & H. Pollard, "Ordinary Differential Equations", Dover 1963, pp. 211 # indirect doctest """ x = func.args[0] f = func.func r = match # First, set up characteristic equation. chareq, symbol = S.Zero, Dummy('x') for i in r.keys(): if type(i) == str or i < 0: pass else: chareq += r[i]*symbol**i chareq = Poly(chareq, symbol) # Can't just call roots because it doesn't return rootof for unsolveable # polynomials. chareqroots = roots(chareq, multiple=True) if len(chareqroots) != order: chareqroots = [rootof(chareq, k) for k in range(chareq.degree())] chareq_is_complex = not all([i.is_real for i in chareq.all_coeffs()]) # A generator of constants constants = list(get_numbered_constants(eq, num=chareq.degree()*2)) # Create a dict root: multiplicity or charroots charroots = defaultdict(int) for root in chareqroots: charroots[root] += 1 # We need to keep track of terms so we can run collect() at the end. # This is necessary for constantsimp to work properly. # # XXX: This global collectterms hack should be removed. global collectterms collectterms = [] gensols = [] conjugate_roots = [] # used to prevent double-use of conjugate roots # Loop over roots in theorder provided by roots/rootof... for root in chareqroots: # but don't repoeat multiple roots. if root not in charroots: continue multiplicity = charroots.pop(root) for i in range(multiplicity): if chareq_is_complex: gensols.append(x**i*exp(root*x)) collectterms = [(i, root, 0)] + collectterms continue reroot = re(root) imroot = im(root) if imroot.has(atan2) and reroot.has(atan2): # Remove this condition when re and im stop returning # circular atan2 usages. gensols.append(x**i*exp(root*x)) collectterms = [(i, root, 0)] + collectterms else: if root in conjugate_roots: collectterms = [(i, reroot, imroot)] + collectterms continue if imroot == 0: gensols.append(x**i*exp(reroot*x)) collectterms = [(i, reroot, 0)] + collectterms continue conjugate_roots.append(conjugate(root)) gensols.append(x**i*exp(reroot*x) * sin(abs(imroot) * x)) gensols.append(x**i*exp(reroot*x) * cos( imroot * x)) # This ordering is important collectterms = [(i, reroot, imroot)] + collectterms if returns == 'list': return gensols elif returns in ('sol' 'both'): gsol = Add(*[i*j for (i, j) in zip(constants, gensols)]) if returns == 'sol': return Eq(f(x), gsol) else: return {'sol': Eq(f(x), gsol), 'list': gensols} else: raise ValueError('Unknown value for key "returns".') def ode_nth_linear_constant_coeff_undetermined_coefficients(eq, func, order, match): r""" Solves an `n`\th order linear differential equation with constant coefficients using the method of undetermined coefficients. This method works on differential equations of the form .. math:: a_n f^{(n)}(x) + a_{n-1} f^{(n-1)}(x) + \cdots + a_1 f'(x) + a_0 f(x) = P(x)\text{,} where `P(x)` is a function that has a finite number of linearly independent derivatives. Functions that fit this requirement are finite sums functions of the form `a x^i e^{b x} \sin(c x + d)` or `a x^i e^{b x} \cos(c x + d)`, where `i` is a non-negative integer and `a`, `b`, `c`, and `d` are constants. For example any polynomial in `x`, functions like `x^2 e^{2 x}`, `x \sin(x)`, and `e^x \cos(x)` can all be used. Products of `\sin`'s and `\cos`'s have a finite number of derivatives, because they can be expanded into `\sin(a x)` and `\cos(b x)` terms. However, SymPy currently cannot do that expansion, so you will need to manually rewrite the expression in terms of the above to use this method. So, for example, you will need to manually convert `\sin^2(x)` into `(1 + \cos(2 x))/2` to properly apply the method of undetermined coefficients on it. This method works by creating a trial function from the expression and all of its linear independent derivatives and substituting them into the original ODE. The coefficients for each term will be a system of linear equations, which are be solved for and substituted, giving the solution. If any of the trial functions are linearly dependent on the solution to the homogeneous equation, they are multiplied by sufficient `x` to make them linearly independent. Examples ======== >>> from sympy import Function, dsolve, pprint, exp, cos >>> from sympy.abc import x >>> f = Function('f') >>> pprint(dsolve(f(x).diff(x, 2) + 2*f(x).diff(x) + f(x) - ... 4*exp(-x)*x**2 + cos(2*x), f(x), ... hint='nth_linear_constant_coeff_undetermined_coefficients')) / 4\ | x | -x 4*sin(2*x) 3*cos(2*x) f(x) = |C1 + C2*x + --|*e - ---------- + ---------- \ 3 / 25 25 References ========== - https://en.wikipedia.org/wiki/Method_of_undetermined_coefficients - M. Tenenbaum & H. Pollard, "Ordinary Differential Equations", Dover 1963, pp. 221 # indirect doctest """ gensol = ode_nth_linear_constant_coeff_homogeneous(eq, func, order, match, returns='both') match.update(gensol) return _solve_undetermined_coefficients(eq, func, order, match) def _solve_undetermined_coefficients(eq, func, order, match): r""" Helper function for the method of undetermined coefficients. See the :py:meth:`~sympy.solvers.ode.ode.ode_nth_linear_constant_coeff_undetermined_coefficients` docstring for more information on this method. The parameter ``match`` should be a dictionary that has the following keys: ``list`` A list of solutions to the homogeneous equation, such as the list returned by ``ode_nth_linear_constant_coeff_homogeneous(returns='list')``. ``sol`` The general solution, such as the solution returned by ``ode_nth_linear_constant_coeff_homogeneous(returns='sol')``. ``trialset`` The set of trial functions as returned by ``_undetermined_coefficients_match()['trialset']``. """ x = func.args[0] f = func.func r = match coeffs = numbered_symbols('a', cls=Dummy) coefflist = [] gensols = r['list'] gsol = r['sol'] trialset = r['trialset'] if len(gensols) != order: raise NotImplementedError("Cannot find " + str(order) + " solutions to the homogeneous equation necessary to apply" + " undetermined coefficients to " + str(eq) + " (number of terms != order)") trialfunc = 0 for i in trialset: c = next(coeffs) coefflist.append(c) trialfunc += c*i eqs = sub_func_doit(eq, f(x), trialfunc) coeffsdict = dict(list(zip(trialset, [0]*(len(trialset) + 1)))) eqs = _mexpand(eqs) for i in Add.make_args(eqs): s = separatevars(i, dict=True, symbols=[x]) if coeffsdict.get(s[x]): coeffsdict[s[x]] += s['coeff'] else: coeffsdict[s[x]] = s['coeff'] coeffvals = solve(list(coeffsdict.values()), coefflist) if not coeffvals: raise NotImplementedError( "Could not solve `%s` using the " "method of undetermined coefficients " "(unable to solve for coefficients)." % eq) psol = trialfunc.subs(coeffvals) return Eq(f(x), gsol.rhs + psol) def _undetermined_coefficients_match(expr, x, func=None, eq_homogeneous=S.Zero): r""" Returns a trial function match if undetermined coefficients can be applied to ``expr``, and ``None`` otherwise. A trial expression can be found for an expression for use with the method of undetermined coefficients if the expression is an additive/multiplicative combination of constants, polynomials in `x` (the independent variable of expr), `\sin(a x + b)`, `\cos(a x + b)`, and `e^{a x}` terms (in other words, it has a finite number of linearly independent derivatives). Note that you may still need to multiply each term returned here by sufficient `x` to make it linearly independent with the solutions to the homogeneous equation. This is intended for internal use by ``undetermined_coefficients`` hints. SymPy currently has no way to convert `\sin^n(x) \cos^m(y)` into a sum of only `\sin(a x)` and `\cos(b x)` terms, so these are not implemented. So, for example, you will need to manually convert `\sin^2(x)` into `[1 + \cos(2 x)]/2` to properly apply the method of undetermined coefficients on it. Examples ======== >>> from sympy import log, exp >>> from sympy.solvers.ode.ode import _undetermined_coefficients_match >>> from sympy.abc import x >>> _undetermined_coefficients_match(9*x*exp(x) + exp(-x), x) {'test': True, 'trialset': {x*exp(x), exp(-x), exp(x)}} >>> _undetermined_coefficients_match(log(x), x) {'test': False} """ a = Wild('a', exclude=[x]) b = Wild('b', exclude=[x]) expr = powsimp(expr, combine='exp') # exp(x)*exp(2*x + 1) => exp(3*x + 1) retdict = {} def _test_term(expr, x): r""" Test if ``expr`` fits the proper form for undetermined coefficients. """ if not expr.has(x): return True elif expr.is_Add: return all(_test_term(i, x) for i in expr.args) elif expr.is_Mul: if expr.has(sin, cos): foundtrig = False # Make sure that there is only one trig function in the args. # See the docstring. for i in expr.args: if i.has(sin, cos): if foundtrig: return False else: foundtrig = True return all(_test_term(i, x) for i in expr.args) elif expr.is_Function: if expr.func in (sin, cos, exp, sinh, cosh): if expr.args[0].match(a*x + b): return True else: return False else: return False elif expr.is_Pow and expr.base.is_Symbol and expr.exp.is_Integer and \ expr.exp >= 0: return True elif expr.is_Pow and expr.base.is_number: if expr.exp.match(a*x + b): return True else: return False elif expr.is_Symbol or expr.is_number: return True else: return False def _get_trial_set(expr, x, exprs=set([])): r""" Returns a set of trial terms for undetermined coefficients. The idea behind undetermined coefficients is that the terms expression repeat themselves after a finite number of derivatives, except for the coefficients (they are linearly dependent). So if we collect these, we should have the terms of our trial function. """ def _remove_coefficient(expr, x): r""" Returns the expression without a coefficient. Similar to expr.as_independent(x)[1], except it only works multiplicatively. """ term = S.One if expr.is_Mul: for i in expr.args: if i.has(x): term *= i elif expr.has(x): term = expr return term expr = expand_mul(expr) if expr.is_Add: for term in expr.args: if _remove_coefficient(term, x) in exprs: pass else: exprs.add(_remove_coefficient(term, x)) exprs = exprs.union(_get_trial_set(term, x, exprs)) else: term = _remove_coefficient(expr, x) tmpset = exprs.union({term}) oldset = set([]) while tmpset != oldset: # If you get stuck in this loop, then _test_term is probably # broken oldset = tmpset.copy() expr = expr.diff(x) term = _remove_coefficient(expr, x) if term.is_Add: tmpset = tmpset.union(_get_trial_set(term, x, tmpset)) else: tmpset.add(term) exprs = tmpset return exprs def is_homogeneous_solution(term): r""" This function checks whether the given trialset contains any root of homogenous equation""" return expand(sub_func_doit(eq_homogeneous, func, term)).is_zero retdict['test'] = _test_term(expr, x) if retdict['test']: # Try to generate a list of trial solutions that will have the # undetermined coefficients. Note that if any of these are not linearly # independent with any of the solutions to the homogeneous equation, # then they will need to be multiplied by sufficient x to make them so. # This function DOES NOT do that (it doesn't even look at the # homogeneous equation). temp_set = set([]) for i in Add.make_args(expr): act = _get_trial_set(i,x) if eq_homogeneous is not S.Zero: while any(is_homogeneous_solution(ts) for ts in act): act = {x*ts for ts in act} temp_set = temp_set.union(act) retdict['trialset'] = temp_set return retdict def ode_nth_linear_constant_coeff_variation_of_parameters(eq, func, order, match): r""" Solves an `n`\th order linear differential equation with constant coefficients using the method of variation of parameters. This method works on any differential equations of the form .. math:: f^{(n)}(x) + a_{n-1} f^{(n-1)}(x) + \cdots + a_1 f'(x) + a_0 f(x) = P(x)\text{.} This method works by assuming that the particular solution takes the form .. math:: \sum_{x=1}^{n} c_i(x) y_i(x)\text{,} where `y_i` is the `i`\th solution to the homogeneous equation. The solution is then solved using Wronskian's and Cramer's Rule. The particular solution is given by .. math:: \sum_{x=1}^n \left( \int \frac{W_i(x)}{W(x)} \,dx \right) y_i(x) \text{,} where `W(x)` is the Wronskian of the fundamental system (the system of `n` linearly independent solutions to the homogeneous equation), and `W_i(x)` is the Wronskian of the fundamental system with the `i`\th column replaced with `[0, 0, \cdots, 0, P(x)]`. This method is general enough to solve any `n`\th order inhomogeneous linear differential equation with constant coefficients, but sometimes SymPy cannot simplify the Wronskian well enough to integrate it. If this method hangs, try using the ``nth_linear_constant_coeff_variation_of_parameters_Integral`` hint and simplifying the integrals manually. Also, prefer using ``nth_linear_constant_coeff_undetermined_coefficients`` when it applies, because it doesn't use integration, making it faster and more reliable. Warning, using simplify=False with 'nth_linear_constant_coeff_variation_of_parameters' in :py:meth:`~sympy.solvers.ode.dsolve` may cause it to hang, because it will not attempt to simplify the Wronskian before integrating. It is recommended that you only use simplify=False with 'nth_linear_constant_coeff_variation_of_parameters_Integral' for this method, especially if the solution to the homogeneous equation has trigonometric functions in it. Examples ======== >>> from sympy import Function, dsolve, pprint, exp, log >>> from sympy.abc import x >>> f = Function('f') >>> pprint(dsolve(f(x).diff(x, 3) - 3*f(x).diff(x, 2) + ... 3*f(x).diff(x) - f(x) - exp(x)*log(x), f(x), ... hint='nth_linear_constant_coeff_variation_of_parameters')) / 3 \ | 2 x *(6*log(x) - 11)| x f(x) = |C1 + C2*x + C3*x + ------------------|*e \ 36 / References ========== - https://en.wikipedia.org/wiki/Variation_of_parameters - http://planetmath.org/VariationOfParameters - M. Tenenbaum & H. Pollard, "Ordinary Differential Equations", Dover 1963, pp. 233 # indirect doctest """ gensol = ode_nth_linear_constant_coeff_homogeneous(eq, func, order, match, returns='both') match.update(gensol) return _solve_variation_of_parameters(eq, func, order, match) def _solve_variation_of_parameters(eq, func, order, match): r""" Helper function for the method of variation of parameters and nonhomogeneous euler eq. See the :py:meth:`~sympy.solvers.ode.ode.ode_nth_linear_constant_coeff_variation_of_parameters` docstring for more information on this method. The parameter ``match`` should be a dictionary that has the following keys: ``list`` A list of solutions to the homogeneous equation, such as the list returned by ``ode_nth_linear_constant_coeff_homogeneous(returns='list')``. ``sol`` The general solution, such as the solution returned by ``ode_nth_linear_constant_coeff_homogeneous(returns='sol')``. """ x = func.args[0] f = func.func r = match psol = 0 gensols = r['list'] gsol = r['sol'] wr = wronskian(gensols, x) if r.get('simplify', True): wr = simplify(wr) # We need much better simplification for # some ODEs. See issue 4662, for example. # To reduce commonly occurring sin(x)**2 + cos(x)**2 to 1 wr = trigsimp(wr, deep=True, recursive=True) if not wr: # The wronskian will be 0 iff the solutions are not linearly # independent. raise NotImplementedError("Cannot find " + str(order) + " solutions to the homogeneous equation necessary to apply " + "variation of parameters to " + str(eq) + " (Wronskian == 0)") if len(gensols) != order: raise NotImplementedError("Cannot find " + str(order) + " solutions to the homogeneous equation necessary to apply " + "variation of parameters to " + str(eq) + " (number of terms != order)") negoneterm = (-1)**(order) for i in gensols: psol += negoneterm*Integral(wronskian([sol for sol in gensols if sol != i], x)*r[-1]/wr, x)*i/r[order] negoneterm *= -1 if r.get('simplify', True): psol = simplify(psol) psol = trigsimp(psol, deep=True) return Eq(f(x), gsol.rhs + psol) def ode_factorable(eq, func, order, match): r""" Solves equations having a solvable factor. This function is used to solve the equation having factors. Factors may be of type algebraic or ode. It will try to solve each factor independently. Factors will be solved by calling dsolve. We will return the list of solutions. Examples ======== >>> from sympy import Function, dsolve, Eq, pprint, Derivative >>> from sympy.abc import x >>> f = Function('f') >>> eq = (f(x)**2-4)*(f(x).diff(x)+f(x)) >>> pprint(dsolve(eq, f(x))) -x [f(x) = 2, f(x) = -2, f(x) = C1*e ] """ eqns = match['eqns'] x0 = match['x0'] sols = [] for eq in eqns: try: sol = dsolve(eq, func, x0=x0) except NotImplementedError: continue else: if isinstance(sol, list): sols.extend(sol) else: sols.append(sol) if sols == []: raise NotImplementedError("The given ODE " + str(eq) + " cannot be solved by" + " the factorable group method") return sols def ode_separable(eq, func, order, match): r""" Solves separable 1st order differential equations. This is any differential equation that can be written as `P(y) \tfrac{dy}{dx} = Q(x)`. The solution can then just be found by rearranging terms and integrating: `\int P(y) \,dy = \int Q(x) \,dx`. This hint uses :py:meth:`sympy.simplify.simplify.separatevars` as its back end, so if a separable equation is not caught by this solver, it is most likely the fault of that function. :py:meth:`~sympy.simplify.simplify.separatevars` is smart enough to do most expansion and factoring necessary to convert a separable equation `F(x, y)` into the proper form `P(x)\cdot{}Q(y)`. The general solution is:: >>> from sympy import Function, dsolve, Eq, pprint >>> from sympy.abc import x >>> a, b, c, d, f = map(Function, ['a', 'b', 'c', 'd', 'f']) >>> genform = Eq(a(x)*b(f(x))*f(x).diff(x), c(x)*d(f(x))) >>> pprint(genform) d a(x)*b(f(x))*--(f(x)) = c(x)*d(f(x)) dx >>> pprint(dsolve(genform, f(x), hint='separable_Integral')) f(x) / / | | | b(y) | c(x) | ---- dy = C1 + | ---- dx | d(y) | a(x) | | / / Examples ======== >>> from sympy import Function, dsolve, Eq >>> from sympy.abc import x >>> f = Function('f') >>> pprint(dsolve(Eq(f(x)*f(x).diff(x) + x, 3*x*f(x)**2), f(x), ... hint='separable', simplify=False)) / 2 \ 2 log\3*f (x) - 1/ x ---------------- = C1 + -- 6 2 References ========== - M. Tenenbaum & H. Pollard, "Ordinary Differential Equations", Dover 1963, pp. 52 # indirect doctest """ x = func.args[0] f = func.func C1 = get_numbered_constants(eq, num=1) r = match # {'m1':m1, 'm2':m2, 'y':y} u = r.get('hint', f(x)) # get u from separable_reduced else get f(x) return Eq(Integral(r['m2']['coeff']*r['m2'][r['y']]/r['m1'][r['y']], (r['y'], None, u)), Integral(-r['m1']['coeff']*r['m1'][x]/ r['m2'][x], x) + C1) def checkinfsol(eq, infinitesimals, func=None, order=None): r""" This function is used to check if the given infinitesimals are the actual infinitesimals of the given first order differential equation. This method is specific to the Lie Group Solver of ODEs. As of now, it simply checks, by substituting the infinitesimals in the partial differential equation. .. math:: \frac{\partial \eta}{\partial x} + \left(\frac{\partial \eta}{\partial y} - \frac{\partial \xi}{\partial x}\right)*h - \frac{\partial \xi}{\partial y}*h^{2} - \xi\frac{\partial h}{\partial x} - \eta\frac{\partial h}{\partial y} = 0 where `\eta`, and `\xi` are the infinitesimals and `h(x,y) = \frac{dy}{dx}` The infinitesimals should be given in the form of a list of dicts ``[{xi(x, y): inf, eta(x, y): inf}]``, corresponding to the output of the function infinitesimals. It returns a list of values of the form ``[(True/False, sol)]`` where ``sol`` is the value obtained after substituting the infinitesimals in the PDE. If it is ``True``, then ``sol`` would be 0. """ if isinstance(eq, Equality): eq = eq.lhs - eq.rhs if not func: eq, func = _preprocess(eq) variables = func.args if len(variables) != 1: raise ValueError("ODE's have only one independent variable") else: x = variables[0] if not order: order = ode_order(eq, func) if order != 1: raise NotImplementedError("Lie groups solver has been implemented " "only for first order differential equations") else: df = func.diff(x) a = Wild('a', exclude = [df]) b = Wild('b', exclude = [df]) match = collect(expand(eq), df).match(a*df + b) if match: h = -simplify(match[b]/match[a]) else: try: sol = solve(eq, df) except NotImplementedError: raise NotImplementedError("Infinitesimals for the " "first order ODE could not be found") else: h = sol[0] # Find infinitesimals for one solution y = Dummy('y') h = h.subs(func, y) xi = Function('xi')(x, y) eta = Function('eta')(x, y) dxi = Function('xi')(x, func) deta = Function('eta')(x, func) pde = (eta.diff(x) + (eta.diff(y) - xi.diff(x))*h - (xi.diff(y))*h**2 - xi*(h.diff(x)) - eta*(h.diff(y))) soltup = [] for sol in infinitesimals: tsol = {xi: S(sol[dxi]).subs(func, y), eta: S(sol[deta]).subs(func, y)} sol = simplify(pde.subs(tsol).doit()) if sol: soltup.append((False, sol.subs(y, func))) else: soltup.append((True, 0)) return soltup def _ode_lie_group_try_heuristic(eq, heuristic, func, match, inf): xi = Function("xi") eta = Function("eta") f = func.func x = func.args[0] y = match['y'] h = match['h'] tempsol = [] if not inf: try: inf = infinitesimals(eq, hint=heuristic, func=func, order=1, match=match) except ValueError: return None for infsim in inf: xiinf = (infsim[xi(x, func)]).subs(func, y) etainf = (infsim[eta(x, func)]).subs(func, y) # This condition creates recursion while using pdsolve. # Since the first step while solving a PDE of form # a*(f(x, y).diff(x)) + b*(f(x, y).diff(y)) + c = 0 # is to solve the ODE dy/dx = b/a if simplify(etainf/xiinf) == h: continue rpde = f(x, y).diff(x)*xiinf + f(x, y).diff(y)*etainf r = pdsolve(rpde, func=f(x, y)).rhs s = pdsolve(rpde - 1, func=f(x, y)).rhs newcoord = [_lie_group_remove(coord) for coord in [r, s]] r = Dummy("r") s = Dummy("s") C1 = Symbol("C1") rcoord = newcoord[0] scoord = newcoord[-1] try: sol = solve([r - rcoord, s - scoord], x, y, dict=True) if sol == []: continue except NotImplementedError: continue else: sol = sol[0] xsub = sol[x] ysub = sol[y] num = simplify(scoord.diff(x) + scoord.diff(y)*h) denom = simplify(rcoord.diff(x) + rcoord.diff(y)*h) if num and denom: diffeq = simplify((num/denom).subs([(x, xsub), (y, ysub)])) sep = separatevars(diffeq, symbols=[r, s], dict=True) if sep: # Trying to separate, r and s coordinates deq = integrate((1/sep[s]), s) + C1 - integrate(sep['coeff']*sep[r], r) # Substituting and reverting back to original coordinates deq = deq.subs([(r, rcoord), (s, scoord)]) try: sdeq = solve(deq, y) except NotImplementedError: tempsol.append(deq) else: return [Eq(f(x), sol) for sol in sdeq] elif denom: # (ds/dr) is zero which means s is constant return [Eq(f(x), solve(scoord - C1, y)[0])] elif num: # (dr/ds) is zero which means r is constant return [Eq(f(x), solve(rcoord - C1, y)[0])] # If nothing works, return solution as it is, without solving for y if tempsol: return [Eq(sol.subs(y, f(x)), 0) for sol in tempsol] return None def _ode_lie_group( s, func, order, match): heuristics = lie_heuristics inf = {} f = func.func x = func.args[0] df = func.diff(x) xi = Function("xi") eta = Function("eta") xis = match['xi'] etas = match['eta'] y = match.pop('y', None) if y: h = -simplify(match[match['d']]/match[match['e']]) y = y else: y = Dummy("y") h = s.subs(func, y) if xis is not None and etas is not None: inf = [{xi(x, f(x)): S(xis), eta(x, f(x)): S(etas)}] if checkinfsol(Eq(df, s), inf, func=f(x), order=1)[0][0]: heuristics = ["user_defined"] + list(heuristics) match = {'h': h, 'y': y} # This is done so that if any heuristic raises a ValueError # another heuristic can be used. sol = None for heuristic in heuristics: sol = _ode_lie_group_try_heuristic(Eq(df, s), heuristic, func, match, inf) if sol: return sol return sol def ode_lie_group(eq, func, order, match): r""" This hint implements the Lie group method of solving first order differential equations. The aim is to convert the given differential equation from the given coordinate system into another coordinate system where it becomes invariant under the one-parameter Lie group of translations. The converted ODE can be easily solved by quadrature. It makes use of the :py:meth:`sympy.solvers.ode.infinitesimals` function which returns the infinitesimals of the transformation. The coordinates `r` and `s` can be found by solving the following Partial Differential Equations. .. math :: \xi\frac{\partial r}{\partial x} + \eta\frac{\partial r}{\partial y} = 0 .. math :: \xi\frac{\partial s}{\partial x} + \eta\frac{\partial s}{\partial y} = 1 The differential equation becomes separable in the new coordinate system .. math :: \frac{ds}{dr} = \frac{\frac{\partial s}{\partial x} + h(x, y)\frac{\partial s}{\partial y}}{ \frac{\partial r}{\partial x} + h(x, y)\frac{\partial r}{\partial y}} After finding the solution by integration, it is then converted back to the original coordinate system by substituting `r` and `s` in terms of `x` and `y` again. Examples ======== >>> from sympy import Function, dsolve, Eq, exp, pprint >>> from sympy.abc import x >>> f = Function('f') >>> pprint(dsolve(f(x).diff(x) + 2*x*f(x) - x*exp(-x**2), f(x), ... hint='lie_group')) / 2\ 2 | x | -x f(x) = |C1 + --|*e \ 2 / References ========== - Solving differential equations by Symmetry Groups, John Starrett, pp. 1 - pp. 14 """ x = func.args[0] df = func.diff(x) try: eqsol = solve(eq, df) except NotImplementedError: eqsol = [] desols = [] for s in eqsol: sol = _ode_lie_group(s, func, order, match=match) if sol: desols.extend(sol) if desols == []: raise NotImplementedError("The given ODE " + str(eq) + " cannot be solved by" + " the lie group method") return desols def _lie_group_remove(coords): r""" This function is strictly meant for internal use by the Lie group ODE solving method. It replaces arbitrary functions returned by pdsolve as follows: 1] If coords is an arbitrary function, then its argument is returned. 2] An arbitrary function in an Add object is replaced by zero. 3] An arbitrary function in a Mul object is replaced by one. 4] If there is no arbitrary function coords is returned unchanged. Examples ======== >>> from sympy.solvers.ode.ode import _lie_group_remove >>> from sympy import Function >>> from sympy.abc import x, y >>> F = Function("F") >>> eq = x**2*y >>> _lie_group_remove(eq) x**2*y >>> eq = F(x**2*y) >>> _lie_group_remove(eq) x**2*y >>> eq = x*y**2 + F(x**3) >>> _lie_group_remove(eq) x*y**2 >>> eq = (F(x**3) + y)*x**4 >>> _lie_group_remove(eq) x**4*y """ if isinstance(coords, AppliedUndef): return coords.args[0] elif coords.is_Add: subfunc = coords.atoms(AppliedUndef) if subfunc: for func in subfunc: coords = coords.subs(func, 0) return coords elif coords.is_Pow: base, expr = coords.as_base_exp() base = _lie_group_remove(base) expr = _lie_group_remove(expr) return base**expr elif coords.is_Mul: mulargs = [] coordargs = coords.args for arg in coordargs: if not isinstance(coords, AppliedUndef): mulargs.append(_lie_group_remove(arg)) return Mul(*mulargs) return coords def infinitesimals(eq, func=None, order=None, hint='default', match=None): r""" The infinitesimal functions of an ordinary differential equation, `\xi(x,y)` and `\eta(x,y)`, are the infinitesimals of the Lie group of point transformations for which the differential equation is invariant. So, the ODE `y'=f(x,y)` would admit a Lie group `x^*=X(x,y;\varepsilon)=x+\varepsilon\xi(x,y)`, `y^*=Y(x,y;\varepsilon)=y+\varepsilon\eta(x,y)` such that `(y^*)'=f(x^*, y^*)`. A change of coordinates, to `r(x,y)` and `s(x,y)`, can be performed so this Lie group becomes the translation group, `r^*=r` and `s^*=s+\varepsilon`. They are tangents to the coordinate curves of the new system. Consider the transformation `(x, y) \to (X, Y)` such that the differential equation remains invariant. `\xi` and `\eta` are the tangents to the transformed coordinates `X` and `Y`, at `\varepsilon=0`. .. math:: \left(\frac{\partial X(x,y;\varepsilon)}{\partial\varepsilon }\right)|_{\varepsilon=0} = \xi, \left(\frac{\partial Y(x,y;\varepsilon)}{\partial\varepsilon }\right)|_{\varepsilon=0} = \eta, The infinitesimals can be found by solving the following PDE: >>> from sympy import Function, diff, Eq, pprint >>> from sympy.abc import x, y >>> xi, eta, h = map(Function, ['xi', 'eta', 'h']) >>> h = h(x, y) # dy/dx = h >>> eta = eta(x, y) >>> xi = xi(x, y) >>> genform = Eq(eta.diff(x) + (eta.diff(y) - xi.diff(x))*h ... - (xi.diff(y))*h**2 - xi*(h.diff(x)) - eta*(h.diff(y)), 0) >>> pprint(genform) /d d \ d 2 d |--(eta(x, y)) - --(xi(x, y))|*h(x, y) - eta(x, y)*--(h(x, y)) - h (x, y)*--(x \dy dx / dy dy <BLANKLINE> d d i(x, y)) - xi(x, y)*--(h(x, y)) + --(eta(x, y)) = 0 dx dx Solving the above mentioned PDE is not trivial, and can be solved only by making intelligent assumptions for `\xi` and `\eta` (heuristics). Once an infinitesimal is found, the attempt to find more heuristics stops. This is done to optimise the speed of solving the differential equation. If a list of all the infinitesimals is needed, ``hint`` should be flagged as ``all``, which gives the complete list of infinitesimals. If the infinitesimals for a particular heuristic needs to be found, it can be passed as a flag to ``hint``. Examples ======== >>> from sympy import Function, diff >>> from sympy.solvers.ode import infinitesimals >>> from sympy.abc import x >>> f = Function('f') >>> eq = f(x).diff(x) - x**2*f(x) >>> infinitesimals(eq) [{eta(x, f(x)): exp(x**3/3), xi(x, f(x)): 0}] References ========== - Solving differential equations by Symmetry Groups, John Starrett, pp. 1 - pp. 14 """ if isinstance(eq, Equality): eq = eq.lhs - eq.rhs if not func: eq, func = _preprocess(eq) variables = func.args if len(variables) != 1: raise ValueError("ODE's have only one independent variable") else: x = variables[0] if not order: order = ode_order(eq, func) if order != 1: raise NotImplementedError("Infinitesimals for only " "first order ODE's have been implemented") else: df = func.diff(x) # Matching differential equation of the form a*df + b a = Wild('a', exclude = [df]) b = Wild('b', exclude = [df]) if match: # Used by lie_group hint h = match['h'] y = match['y'] else: match = collect(expand(eq), df).match(a*df + b) if match: h = -simplify(match[b]/match[a]) else: try: sol = solve(eq, df) except NotImplementedError: raise NotImplementedError("Infinitesimals for the " "first order ODE could not be found") else: h = sol[0] # Find infinitesimals for one solution y = Dummy("y") h = h.subs(func, y) u = Dummy("u") hx = h.diff(x) hy = h.diff(y) hinv = ((1/h).subs([(x, u), (y, x)])).subs(u, y) # Inverse ODE match = {'h': h, 'func': func, 'hx': hx, 'hy': hy, 'y': y, 'hinv': hinv} if hint == 'all': xieta = [] for heuristic in lie_heuristics: function = globals()['lie_heuristic_' + heuristic] inflist = function(match, comp=True) if inflist: xieta.extend([inf for inf in inflist if inf not in xieta]) if xieta: return xieta else: raise NotImplementedError("Infinitesimals could not be found for " "the given ODE") elif hint == 'default': for heuristic in lie_heuristics: function = globals()['lie_heuristic_' + heuristic] xieta = function(match, comp=False) if xieta: return xieta raise NotImplementedError("Infinitesimals could not be found for" " the given ODE") elif hint not in lie_heuristics: raise ValueError("Heuristic not recognized: " + hint) else: function = globals()['lie_heuristic_' + hint] xieta = function(match, comp=True) if xieta: return xieta else: raise ValueError("Infinitesimals could not be found using the" " given heuristic") def lie_heuristic_abaco1_simple(match, comp=False): r""" The first heuristic uses the following four sets of assumptions on `\xi` and `\eta` .. math:: \xi = 0, \eta = f(x) .. math:: \xi = 0, \eta = f(y) .. math:: \xi = f(x), \eta = 0 .. math:: \xi = f(y), \eta = 0 The success of this heuristic is determined by algebraic factorisation. For the first assumption `\xi = 0` and `\eta` to be a function of `x`, the PDE .. math:: \frac{\partial \eta}{\partial x} + (\frac{\partial \eta}{\partial y} - \frac{\partial \xi}{\partial x})*h - \frac{\partial \xi}{\partial y}*h^{2} - \xi*\frac{\partial h}{\partial x} - \eta*\frac{\partial h}{\partial y} = 0 reduces to `f'(x) - f\frac{\partial h}{\partial y} = 0` If `\frac{\partial h}{\partial y}` is a function of `x`, then this can usually be integrated easily. A similar idea is applied to the other 3 assumptions as well. References ========== - E.S Cheb-Terrab, L.G.S Duarte and L.A,C.P da Mota, Computer Algebra Solving of First Order ODEs Using Symmetry Methods, pp. 8 """ xieta = [] y = match['y'] h = match['h'] func = match['func'] x = func.args[0] hx = match['hx'] hy = match['hy'] xi = Function('xi')(x, func) eta = Function('eta')(x, func) hysym = hy.free_symbols if y not in hysym: try: fx = exp(integrate(hy, x)) except NotImplementedError: pass else: inf = {xi: S.Zero, eta: fx} if not comp: return [inf] if comp and inf not in xieta: xieta.append(inf) factor = hy/h facsym = factor.free_symbols if x not in facsym: try: fy = exp(integrate(factor, y)) except NotImplementedError: pass else: inf = {xi: S.Zero, eta: fy.subs(y, func)} if not comp: return [inf] if comp and inf not in xieta: xieta.append(inf) factor = -hx/h facsym = factor.free_symbols if y not in facsym: try: fx = exp(integrate(factor, x)) except NotImplementedError: pass else: inf = {xi: fx, eta: S.Zero} if not comp: return [inf] if comp and inf not in xieta: xieta.append(inf) factor = -hx/(h**2) facsym = factor.free_symbols if x not in facsym: try: fy = exp(integrate(factor, y)) except NotImplementedError: pass else: inf = {xi: fy.subs(y, func), eta: S.Zero} if not comp: return [inf] if comp and inf not in xieta: xieta.append(inf) if xieta: return xieta def lie_heuristic_abaco1_product(match, comp=False): r""" The second heuristic uses the following two assumptions on `\xi` and `\eta` .. math:: \eta = 0, \xi = f(x)*g(y) .. math:: \eta = f(x)*g(y), \xi = 0 The first assumption of this heuristic holds good if `\frac{1}{h^{2}}\frac{\partial^2}{\partial x \partial y}\log(h)` is separable in `x` and `y`, then the separated factors containing `x` is `f(x)`, and `g(y)` is obtained by .. math:: e^{\int f\frac{\partial}{\partial x}\left(\frac{1}{f*h}\right)\,dy} provided `f\frac{\partial}{\partial x}\left(\frac{1}{f*h}\right)` is a function of `y` only. The second assumption holds good if `\frac{dy}{dx} = h(x, y)` is rewritten as `\frac{dy}{dx} = \frac{1}{h(y, x)}` and the same properties of the first assumption satisfies. After obtaining `f(x)` and `g(y)`, the coordinates are again interchanged, to get `\eta` as `f(x)*g(y)` References ========== - E.S. Cheb-Terrab, A.D. Roche, Symmetries and First Order ODE Patterns, pp. 7 - pp. 8 """ xieta = [] y = match['y'] h = match['h'] hinv = match['hinv'] func = match['func'] x = func.args[0] xi = Function('xi')(x, func) eta = Function('eta')(x, func) inf = separatevars(((log(h).diff(y)).diff(x))/h**2, dict=True, symbols=[x, y]) if inf and inf['coeff']: fx = inf[x] gy = simplify(fx*((1/(fx*h)).diff(x))) gysyms = gy.free_symbols if x not in gysyms: gy = exp(integrate(gy, y)) inf = {eta: S.Zero, xi: (fx*gy).subs(y, func)} if not comp: return [inf] if comp and inf not in xieta: xieta.append(inf) u1 = Dummy("u1") inf = separatevars(((log(hinv).diff(y)).diff(x))/hinv**2, dict=True, symbols=[x, y]) if inf and inf['coeff']: fx = inf[x] gy = simplify(fx*((1/(fx*hinv)).diff(x))) gysyms = gy.free_symbols if x not in gysyms: gy = exp(integrate(gy, y)) etaval = fx*gy etaval = (etaval.subs([(x, u1), (y, x)])).subs(u1, y) inf = {eta: etaval.subs(y, func), xi: S.Zero} if not comp: return [inf] if comp and inf not in xieta: xieta.append(inf) if xieta: return xieta def lie_heuristic_bivariate(match, comp=False): r""" The third heuristic assumes the infinitesimals `\xi` and `\eta` to be bi-variate polynomials in `x` and `y`. The assumption made here for the logic below is that `h` is a rational function in `x` and `y` though that may not be necessary for the infinitesimals to be bivariate polynomials. The coefficients of the infinitesimals are found out by substituting them in the PDE and grouping similar terms that are polynomials and since they form a linear system, solve and check for non trivial solutions. The degree of the assumed bivariates are increased till a certain maximum value. References ========== - Lie Groups and Differential Equations pp. 327 - pp. 329 """ h = match['h'] hx = match['hx'] hy = match['hy'] func = match['func'] x = func.args[0] y = match['y'] xi = Function('xi')(x, func) eta = Function('eta')(x, func) if h.is_rational_function(): # The maximum degree that the infinitesimals can take is # calculated by this technique. etax, etay, etad, xix, xiy, xid = symbols("etax etay etad xix xiy xid") ipde = etax + (etay - xix)*h - xiy*h**2 - xid*hx - etad*hy num, denom = cancel(ipde).as_numer_denom() deg = Poly(num, x, y).total_degree() deta = Function('deta')(x, y) dxi = Function('dxi')(x, y) ipde = (deta.diff(x) + (deta.diff(y) - dxi.diff(x))*h - (dxi.diff(y))*h**2 - dxi*hx - deta*hy) xieq = Symbol("xi0") etaeq = Symbol("eta0") for i in range(deg + 1): if i: xieq += Add(*[ Symbol("xi_" + str(power) + "_" + str(i - power))*x**power*y**(i - power) for power in range(i + 1)]) etaeq += Add(*[ Symbol("eta_" + str(power) + "_" + str(i - power))*x**power*y**(i - power) for power in range(i + 1)]) pden, denom = (ipde.subs({dxi: xieq, deta: etaeq}).doit()).as_numer_denom() pden = expand(pden) # If the individual terms are monomials, the coefficients # are grouped if pden.is_polynomial(x, y) and pden.is_Add: polyy = Poly(pden, x, y).as_dict() if polyy: symset = xieq.free_symbols.union(etaeq.free_symbols) - {x, y} soldict = solve(polyy.values(), *symset) if isinstance(soldict, list): soldict = soldict[0] if any(soldict.values()): xired = xieq.subs(soldict) etared = etaeq.subs(soldict) # Scaling is done by substituting one for the parameters # This can be any number except zero. dict_ = dict((sym, 1) for sym in symset) inf = {eta: etared.subs(dict_).subs(y, func), xi: xired.subs(dict_).subs(y, func)} return [inf] def lie_heuristic_chi(match, comp=False): r""" The aim of the fourth heuristic is to find the function `\chi(x, y)` that satisfies the PDE `\frac{d\chi}{dx} + h\frac{d\chi}{dx} - \frac{\partial h}{\partial y}\chi = 0`. This assumes `\chi` to be a bivariate polynomial in `x` and `y`. By intuition, `h` should be a rational function in `x` and `y`. The method used here is to substitute a general binomial for `\chi` up to a certain maximum degree is reached. The coefficients of the polynomials, are calculated by by collecting terms of the same order in `x` and `y`. After finding `\chi`, the next step is to use `\eta = \xi*h + \chi`, to determine `\xi` and `\eta`. This can be done by dividing `\chi` by `h` which would give `-\xi` as the quotient and `\eta` as the remainder. References ========== - E.S Cheb-Terrab, L.G.S Duarte and L.A,C.P da Mota, Computer Algebra Solving of First Order ODEs Using Symmetry Methods, pp. 8 """ h = match['h'] hy = match['hy'] func = match['func'] x = func.args[0] y = match['y'] xi = Function('xi')(x, func) eta = Function('eta')(x, func) if h.is_rational_function(): schi, schix, schiy = symbols("schi, schix, schiy") cpde = schix + h*schiy - hy*schi num, denom = cancel(cpde).as_numer_denom() deg = Poly(num, x, y).total_degree() chi = Function('chi')(x, y) chix = chi.diff(x) chiy = chi.diff(y) cpde = chix + h*chiy - hy*chi chieq = Symbol("chi") for i in range(1, deg + 1): chieq += Add(*[ Symbol("chi_" + str(power) + "_" + str(i - power))*x**power*y**(i - power) for power in range(i + 1)]) cnum, cden = cancel(cpde.subs({chi : chieq}).doit()).as_numer_denom() cnum = expand(cnum) if cnum.is_polynomial(x, y) and cnum.is_Add: cpoly = Poly(cnum, x, y).as_dict() if cpoly: solsyms = chieq.free_symbols - {x, y} soldict = solve(cpoly.values(), *solsyms) if isinstance(soldict, list): soldict = soldict[0] if any(soldict.values()): chieq = chieq.subs(soldict) dict_ = dict((sym, 1) for sym in solsyms) chieq = chieq.subs(dict_) # After finding chi, the main aim is to find out # eta, xi by the equation eta = xi*h + chi # One method to set xi, would be rearranging it to # (eta/h) - xi = (chi/h). This would mean dividing # chi by h would give -xi as the quotient and eta # as the remainder. Thanks to Sean Vig for suggesting # this method. xic, etac = div(chieq, h) inf = {eta: etac.subs(y, func), xi: -xic.subs(y, func)} return [inf] def lie_heuristic_function_sum(match, comp=False): r""" This heuristic uses the following two assumptions on `\xi` and `\eta` .. math:: \eta = 0, \xi = f(x) + g(y) .. math:: \eta = f(x) + g(y), \xi = 0 The first assumption of this heuristic holds good if .. math:: \frac{\partial}{\partial y}[(h\frac{\partial^{2}}{ \partial x^{2}}(h^{-1}))^{-1}] is separable in `x` and `y`, 1. The separated factors containing `y` is `\frac{\partial g}{\partial y}`. From this `g(y)` can be determined. 2. The separated factors containing `x` is `f''(x)`. 3. `h\frac{\partial^{2}}{\partial x^{2}}(h^{-1})` equals `\frac{f''(x)}{f(x) + g(y)}`. From this `f(x)` can be determined. The second assumption holds good if `\frac{dy}{dx} = h(x, y)` is rewritten as `\frac{dy}{dx} = \frac{1}{h(y, x)}` and the same properties of the first assumption satisfies. After obtaining `f(x)` and `g(y)`, the coordinates are again interchanged, to get `\eta` as `f(x) + g(y)`. For both assumptions, the constant factors are separated among `g(y)` and `f''(x)`, such that `f''(x)` obtained from 3] is the same as that obtained from 2]. If not possible, then this heuristic fails. References ========== - E.S. Cheb-Terrab, A.D. Roche, Symmetries and First Order ODE Patterns, pp. 7 - pp. 8 """ xieta = [] h = match['h'] func = match['func'] hinv = match['hinv'] x = func.args[0] y = match['y'] xi = Function('xi')(x, func) eta = Function('eta')(x, func) for odefac in [h, hinv]: factor = odefac*((1/odefac).diff(x, 2)) sep = separatevars((1/factor).diff(y), dict=True, symbols=[x, y]) if sep and sep['coeff'] and sep[x].has(x) and sep[y].has(y): k = Dummy("k") try: gy = k*integrate(sep[y], y) except NotImplementedError: pass else: fdd = 1/(k*sep[x]*sep['coeff']) fx = simplify(fdd/factor - gy) check = simplify(fx.diff(x, 2) - fdd) if fx: if not check: fx = fx.subs(k, 1) gy = (gy/k) else: sol = solve(check, k) if sol: sol = sol[0] fx = fx.subs(k, sol) gy = (gy/k)*sol else: continue if odefac == hinv: # Inverse ODE fx = fx.subs(x, y) gy = gy.subs(y, x) etaval = factor_terms(fx + gy) if etaval.is_Mul: etaval = Mul(*[arg for arg in etaval.args if arg.has(x, y)]) if odefac == hinv: # Inverse ODE inf = {eta: etaval.subs(y, func), xi : S.Zero} else: inf = {xi: etaval.subs(y, func), eta : S.Zero} if not comp: return [inf] else: xieta.append(inf) if xieta: return xieta def lie_heuristic_abaco2_similar(match, comp=False): r""" This heuristic uses the following two assumptions on `\xi` and `\eta` .. math:: \eta = g(x), \xi = f(x) .. math:: \eta = f(y), \xi = g(y) For the first assumption, 1. First `\frac{\frac{\partial h}{\partial y}}{\frac{\partial^{2} h}{ \partial yy}}` is calculated. Let us say this value is A 2. If this is constant, then `h` is matched to the form `A(x) + B(x)e^{ \frac{y}{C}}` then, `\frac{e^{\int \frac{A(x)}{C} \,dx}}{B(x)}` gives `f(x)` and `A(x)*f(x)` gives `g(x)` 3. Otherwise `\frac{\frac{\partial A}{\partial X}}{\frac{\partial A}{ \partial Y}} = \gamma` is calculated. If a] `\gamma` is a function of `x` alone b] `\frac{\gamma\frac{\partial h}{\partial y} - \gamma'(x) - \frac{ \partial h}{\partial x}}{h + \gamma} = G` is a function of `x` alone. then, `e^{\int G \,dx}` gives `f(x)` and `-\gamma*f(x)` gives `g(x)` The second assumption holds good if `\frac{dy}{dx} = h(x, y)` is rewritten as `\frac{dy}{dx} = \frac{1}{h(y, x)}` and the same properties of the first assumption satisfies. After obtaining `f(x)` and `g(x)`, the coordinates are again interchanged, to get `\xi` as `f(x^*)` and `\eta` as `g(y^*)` References ========== - E.S. Cheb-Terrab, A.D. Roche, Symmetries and First Order ODE Patterns, pp. 10 - pp. 12 """ h = match['h'] hx = match['hx'] hy = match['hy'] func = match['func'] hinv = match['hinv'] x = func.args[0] y = match['y'] xi = Function('xi')(x, func) eta = Function('eta')(x, func) factor = cancel(h.diff(y)/h.diff(y, 2)) factorx = factor.diff(x) factory = factor.diff(y) if not factor.has(x) and not factor.has(y): A = Wild('A', exclude=[y]) B = Wild('B', exclude=[y]) C = Wild('C', exclude=[x, y]) match = h.match(A + B*exp(y/C)) try: tau = exp(-integrate(match[A]/match[C]), x)/match[B] except NotImplementedError: pass else: gx = match[A]*tau return [{xi: tau, eta: gx}] else: gamma = cancel(factorx/factory) if not gamma.has(y): tauint = cancel((gamma*hy - gamma.diff(x) - hx)/(h + gamma)) if not tauint.has(y): try: tau = exp(integrate(tauint, x)) except NotImplementedError: pass else: gx = -tau*gamma return [{xi: tau, eta: gx}] factor = cancel(hinv.diff(y)/hinv.diff(y, 2)) factorx = factor.diff(x) factory = factor.diff(y) if not factor.has(x) and not factor.has(y): A = Wild('A', exclude=[y]) B = Wild('B', exclude=[y]) C = Wild('C', exclude=[x, y]) match = h.match(A + B*exp(y/C)) try: tau = exp(-integrate(match[A]/match[C]), x)/match[B] except NotImplementedError: pass else: gx = match[A]*tau return [{eta: tau.subs(x, func), xi: gx.subs(x, func)}] else: gamma = cancel(factorx/factory) if not gamma.has(y): tauint = cancel((gamma*hinv.diff(y) - gamma.diff(x) - hinv.diff(x))/( hinv + gamma)) if not tauint.has(y): try: tau = exp(integrate(tauint, x)) except NotImplementedError: pass else: gx = -tau*gamma return [{eta: tau.subs(x, func), xi: gx.subs(x, func)}] def lie_heuristic_abaco2_unique_unknown(match, comp=False): r""" This heuristic assumes the presence of unknown functions or known functions with non-integer powers. 1. A list of all functions and non-integer powers containing x and y 2. Loop over each element `f` in the list, find `\frac{\frac{\partial f}{\partial x}}{ \frac{\partial f}{\partial x}} = R` If it is separable in `x` and `y`, let `X` be the factors containing `x`. Then a] Check if `\xi = X` and `\eta = -\frac{X}{R}` satisfy the PDE. If yes, then return `\xi` and `\eta` b] Check if `\xi = \frac{-R}{X}` and `\eta = -\frac{1}{X}` satisfy the PDE. If yes, then return `\xi` and `\eta` If not, then check if a] :math:`\xi = -R,\eta = 1` b] :math:`\xi = 1, \eta = -\frac{1}{R}` are solutions. References ========== - E.S. Cheb-Terrab, A.D. Roche, Symmetries and First Order ODE Patterns, pp. 10 - pp. 12 """ h = match['h'] hx = match['hx'] hy = match['hy'] func = match['func'] x = func.args[0] y = match['y'] xi = Function('xi')(x, func) eta = Function('eta')(x, func) funclist = [] for atom in h.atoms(Pow): base, exp = atom.as_base_exp() if base.has(x) and base.has(y): if not exp.is_Integer: funclist.append(atom) for function in h.atoms(AppliedUndef): syms = function.free_symbols if x in syms and y in syms: funclist.append(function) for f in funclist: frac = cancel(f.diff(y)/f.diff(x)) sep = separatevars(frac, dict=True, symbols=[x, y]) if sep and sep['coeff']: xitry1 = sep[x] etatry1 = -1/(sep[y]*sep['coeff']) pde1 = etatry1.diff(y)*h - xitry1.diff(x)*h - xitry1*hx - etatry1*hy if not simplify(pde1): return [{xi: xitry1, eta: etatry1.subs(y, func)}] xitry2 = 1/etatry1 etatry2 = 1/xitry1 pde2 = etatry2.diff(x) - (xitry2.diff(y))*h**2 - xitry2*hx - etatry2*hy if not simplify(expand(pde2)): return [{xi: xitry2.subs(y, func), eta: etatry2}] else: etatry = -1/frac pde = etatry.diff(x) + etatry.diff(y)*h - hx - etatry*hy if not simplify(pde): return [{xi: S.One, eta: etatry.subs(y, func)}] xitry = -frac pde = -xitry.diff(x)*h -xitry.diff(y)*h**2 - xitry*hx -hy if not simplify(expand(pde)): return [{xi: xitry.subs(y, func), eta: S.One}] def lie_heuristic_abaco2_unique_general(match, comp=False): r""" This heuristic finds if infinitesimals of the form `\eta = f(x)`, `\xi = g(y)` without making any assumptions on `h`. The complete sequence of steps is given in the paper mentioned below. References ========== - E.S. Cheb-Terrab, A.D. Roche, Symmetries and First Order ODE Patterns, pp. 10 - pp. 12 """ hx = match['hx'] hy = match['hy'] func = match['func'] x = func.args[0] y = match['y'] xi = Function('xi')(x, func) eta = Function('eta')(x, func) A = hx.diff(y) B = hy.diff(y) + hy**2 C = hx.diff(x) - hx**2 if not (A and B and C): return Ax = A.diff(x) Ay = A.diff(y) Axy = Ax.diff(y) Axx = Ax.diff(x) Ayy = Ay.diff(y) D = simplify(2*Axy + hx*Ay - Ax*hy + (hx*hy + 2*A)*A)*A - 3*Ax*Ay if not D: E1 = simplify(3*Ax**2 + ((hx**2 + 2*C)*A - 2*Axx)*A) if E1: E2 = simplify((2*Ayy + (2*B - hy**2)*A)*A - 3*Ay**2) if not E2: E3 = simplify( E1*((28*Ax + 4*hx*A)*A**3 - E1*(hy*A + Ay)) - E1.diff(x)*8*A**4) if not E3: etaval = cancel((4*A**3*(Ax - hx*A) + E1*(hy*A - Ay))/(S(2)*A*E1)) if x not in etaval: try: etaval = exp(integrate(etaval, y)) except NotImplementedError: pass else: xival = -4*A**3*etaval/E1 if y not in xival: return [{xi: xival, eta: etaval.subs(y, func)}] else: E1 = simplify((2*Ayy + (2*B - hy**2)*A)*A - 3*Ay**2) if E1: E2 = simplify( 4*A**3*D - D**2 + E1*((2*Axx - (hx**2 + 2*C)*A)*A - 3*Ax**2)) if not E2: E3 = simplify( -(A*D)*E1.diff(y) + ((E1.diff(x) - hy*D)*A + 3*Ay*D + (A*hx - 3*Ax)*E1)*E1) if not E3: etaval = cancel(((A*hx - Ax)*E1 - (Ay + A*hy)*D)/(S(2)*A*D)) if x not in etaval: try: etaval = exp(integrate(etaval, y)) except NotImplementedError: pass else: xival = -E1*etaval/D if y not in xival: return [{xi: xival, eta: etaval.subs(y, func)}] def lie_heuristic_linear(match, comp=False): r""" This heuristic assumes 1. `\xi = ax + by + c` and 2. `\eta = fx + gy + h` After substituting the following assumptions in the determining PDE, it reduces to .. math:: f + (g - a)h - bh^{2} - (ax + by + c)\frac{\partial h}{\partial x} - (fx + gy + c)\frac{\partial h}{\partial y} Solving the reduced PDE obtained, using the method of characteristics, becomes impractical. The method followed is grouping similar terms and solving the system of linear equations obtained. The difference between the bivariate heuristic is that `h` need not be a rational function in this case. References ========== - E.S. Cheb-Terrab, A.D. Roche, Symmetries and First Order ODE Patterns, pp. 10 - pp. 12 """ h = match['h'] hx = match['hx'] hy = match['hy'] func = match['func'] x = func.args[0] y = match['y'] xi = Function('xi')(x, func) eta = Function('eta')(x, func) coeffdict = {} symbols = numbered_symbols("c", cls=Dummy) symlist = [next(symbols) for _ in islice(symbols, 6)] C0, C1, C2, C3, C4, C5 = symlist pde = C3 + (C4 - C0)*h - (C0*x + C1*y + C2)*hx - (C3*x + C4*y + C5)*hy - C1*h**2 pde, denom = pde.as_numer_denom() pde = powsimp(expand(pde)) if pde.is_Add: terms = pde.args for term in terms: if term.is_Mul: rem = Mul(*[m for m in term.args if not m.has(x, y)]) xypart = term/rem if xypart not in coeffdict: coeffdict[xypart] = rem else: coeffdict[xypart] += rem else: if term not in coeffdict: coeffdict[term] = S.One else: coeffdict[term] += S.One sollist = coeffdict.values() soldict = solve(sollist, symlist) if soldict: if isinstance(soldict, list): soldict = soldict[0] subval = soldict.values() if any(t for t in subval): onedict = dict(zip(symlist, [1]*6)) xival = C0*x + C1*func + C2 etaval = C3*x + C4*func + C5 xival = xival.subs(soldict) etaval = etaval.subs(soldict) xival = xival.subs(onedict) etaval = etaval.subs(onedict) return [{xi: xival, eta: etaval}] def sysode_linear_2eq_order1(match_): x = match_['func'][0].func y = match_['func'][1].func func = match_['func'] fc = match_['func_coeff'] eq = match_['eq'] r = dict() t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0] for i in range(2): eqs = 0 for terms in Add.make_args(eq[i]): eqs += terms/fc[i,func[i],1] eq[i] = eqs # for equations Eq(a1*diff(x(t),t), a*x(t) + b*y(t) + k1) # and Eq(a2*diff(x(t),t), c*x(t) + d*y(t) + k2) r['a'] = -fc[0,x(t),0]/fc[0,x(t),1] r['c'] = -fc[1,x(t),0]/fc[1,y(t),1] r['b'] = -fc[0,y(t),0]/fc[0,x(t),1] r['d'] = -fc[1,y(t),0]/fc[1,y(t),1] forcing = [S.Zero,S.Zero] for i in range(2): for j in Add.make_args(eq[i]): if not j.has(x(t), y(t)): forcing[i] += j if not (forcing[0].has(t) or forcing[1].has(t)): r['k1'] = forcing[0] r['k2'] = forcing[1] else: raise NotImplementedError("Only homogeneous problems are supported" + " (and constant inhomogeneity)") if match_['type_of_equation'] == 'type1': sol = _linear_2eq_order1_type1(x, y, t, r, eq) if match_['type_of_equation'] == 'type2': gsol = _linear_2eq_order1_type1(x, y, t, r, eq) psol = _linear_2eq_order1_type2(x, y, t, r, eq) sol = [Eq(x(t), gsol[0].rhs+psol[0]), Eq(y(t), gsol[1].rhs+psol[1])] if match_['type_of_equation'] == 'type3': sol = _linear_2eq_order1_type3(x, y, t, r, eq) if match_['type_of_equation'] == 'type4': sol = _linear_2eq_order1_type4(x, y, t, r, eq) if match_['type_of_equation'] == 'type5': sol = _linear_2eq_order1_type5(x, y, t, r, eq) if match_['type_of_equation'] == 'type6': sol = _linear_2eq_order1_type6(x, y, t, r, eq) if match_['type_of_equation'] == 'type7': sol = _linear_2eq_order1_type7(x, y, t, r, eq) return sol def _linear_2eq_order1_type1(x, y, t, r, eq): r""" It is classified under system of two linear homogeneous first-order constant-coefficient ordinary differential equations. The equations which come under this type are .. math:: x' = ax + by, .. math:: y' = cx + dy The characteristics equation is written as .. math:: \lambda^{2} + (a+d) \lambda + ad - bc = 0 and its discriminant is `D = (a-d)^{2} + 4bc`. There are several cases 1. Case when `ad - bc \neq 0`. The origin of coordinates, `x = y = 0`, is the only stationary point; it is - a node if `D = 0` - a node if `D > 0` and `ad - bc > 0` - a saddle if `D > 0` and `ad - bc < 0` - a focus if `D < 0` and `a + d \neq 0` - a centre if `D < 0` and `a + d \neq 0`. 1.1. If `D > 0`. The characteristic equation has two distinct real roots `\lambda_1` and `\lambda_ 2` . The general solution of the system in question is expressed as .. math:: x = C_1 b e^{\lambda_1 t} + C_2 b e^{\lambda_2 t} .. math:: y = C_1 (\lambda_1 - a) e^{\lambda_1 t} + C_2 (\lambda_2 - a) e^{\lambda_2 t} where `C_1` and `C_2` being arbitrary constants 1.2. If `D < 0`. The characteristics equation has two conjugate roots, `\lambda_1 = \sigma + i \beta` and `\lambda_2 = \sigma - i \beta`. The general solution of the system is given by .. math:: x = b e^{\sigma t} (C_1 \sin(\beta t) + C_2 \cos(\beta t)) .. math:: y = e^{\sigma t} ([(\sigma - a) C_1 - \beta C_2] \sin(\beta t) + [\beta C_1 + (\sigma - a) C_2 \cos(\beta t)]) 1.3. If `D = 0` and `a \neq d`. The characteristic equation has two equal roots, `\lambda_1 = \lambda_2`. The general solution of the system is written as .. math:: x = 2b (C_1 + \frac{C_2}{a-d} + C_2 t) e^{\frac{a+d}{2} t} .. math:: y = [(d - a) C_1 + C_2 + (d - a) C_2 t] e^{\frac{a+d}{2} t} 1.4. If `D = 0` and `a = d \neq 0` and `b = 0` .. math:: x = C_1 e^{a t} , y = (c C_1 t + C_2) e^{a t} 1.5. If `D = 0` and `a = d \neq 0` and `c = 0` .. math:: x = (b C_1 t + C_2) e^{a t} , y = C_1 e^{a t} 2. Case when `ad - bc = 0` and `a^{2} + b^{2} > 0`. The whole straight line `ax + by = 0` consists of singular points. The original system of differential equations can be rewritten as .. math:: x' = ax + by , y' = k (ax + by) 2.1 If `a + bk \neq 0`, solution will be .. math:: x = b C_1 + C_2 e^{(a + bk) t} , y = -a C_1 + k C_2 e^{(a + bk) t} 2.2 If `a + bk = 0`, solution will be .. math:: x = C_1 (bk t - 1) + b C_2 t , y = k^{2} b C_1 t + (b k^{2} t + 1) C_2 """ C1, C2 = get_numbered_constants(eq, num=2) a, b, c, d = r['a'], r['b'], r['c'], r['d'] real_coeff = all(v.is_real for v in (a, b, c, d)) D = (a - d)**2 + 4*b*c l1 = (a + d + sqrt(D))/2 l2 = (a + d - sqrt(D))/2 equal_roots = Eq(D, 0).expand() gsol1, gsol2 = [], [] # Solutions have exponential form if either D > 0 with real coefficients # or D != 0 with complex coefficients. Eigenvalues are distinct. # For each eigenvalue lam, pick an eigenvector, making sure we don't get (0, 0) # The candidates are (b, lam-a) and (lam-d, c). exponential_form = D > 0 if real_coeff else Not(equal_roots) bad_ab_vector1 = And(Eq(b, 0), Eq(l1, a)) bad_ab_vector2 = And(Eq(b, 0), Eq(l2, a)) vector1 = Matrix((Piecewise((l1 - d, bad_ab_vector1), (b, True)), Piecewise((c, bad_ab_vector1), (l1 - a, True)))) vector2 = Matrix((Piecewise((l2 - d, bad_ab_vector2), (b, True)), Piecewise((c, bad_ab_vector2), (l2 - a, True)))) sol_vector = C1*exp(l1*t)*vector1 + C2*exp(l2*t)*vector2 gsol1.append((sol_vector[0], exponential_form)) gsol2.append((sol_vector[1], exponential_form)) # Solutions have trigonometric form for real coefficients with D < 0 # Both b and c are nonzero in this case, so (b, lam-a) is an eigenvector # It splits into real/imag parts as (b, sigma-a) and (0, beta). Then # multiply it by C1(cos(beta*t) + I*C2*sin(beta*t)) and separate real/imag trigonometric_form = D < 0 if real_coeff else False sigma = re(l1) if im(l1).is_positive: beta = im(l1) else: beta = im(l2) vector1 = Matrix((b, sigma - a)) vector2 = Matrix((0, beta)) sol_vector = exp(sigma*t) * (C1*(cos(beta*t)*vector1 - sin(beta*t)*vector2) + \ C2*(sin(beta*t)*vector1 + cos(beta*t)*vector2)) gsol1.append((sol_vector[0], trigonometric_form)) gsol2.append((sol_vector[1], trigonometric_form)) # Final case is D == 0, a single eigenvalue. If the eigenspace is 2-dimensional # then we have a scalar matrix, deal with this case first. scalar_matrix = And(Eq(a, d), Eq(b, 0), Eq(c, 0)) vector1 = Matrix((S.One, S.Zero)) vector2 = Matrix((S.Zero, S.One)) sol_vector = exp(l1*t) * (C1*vector1 + C2*vector2) gsol1.append((sol_vector[0], scalar_matrix)) gsol2.append((sol_vector[1], scalar_matrix)) # Have one eigenvector. Get a generalized eigenvector from (A-lam)*vector2 = vector1 vector1 = Matrix((Piecewise((l1 - d, bad_ab_vector1), (b, True)), Piecewise((c, bad_ab_vector1), (l1 - a, True)))) vector2 = Matrix((Piecewise((S.One, bad_ab_vector1), (S.Zero, Eq(a, l1)), (b/(a - l1), True)), Piecewise((S.Zero, bad_ab_vector1), (S.One, Eq(a, l1)), (S.Zero, True)))) sol_vector = exp(l1*t) * (C1*vector1 + C2*(vector2 + t*vector1)) gsol1.append((sol_vector[0], equal_roots)) gsol2.append((sol_vector[1], equal_roots)) return [Eq(x(t), Piecewise(*gsol1)), Eq(y(t), Piecewise(*gsol2))] def _linear_2eq_order1_type2(x, y, t, r, eq): r""" The equations of this type are .. math:: x' = ax + by + k1 , y' = cx + dy + k2 The general solution of this system is given by sum of its particular solution and the general solution of the corresponding homogeneous system is obtained from type1. 1. When `ad - bc \neq 0`. The particular solution will be `x = x_0` and `y = y_0` where `x_0` and `y_0` are determined by solving linear system of equations .. math:: a x_0 + b y_0 + k1 = 0 , c x_0 + d y_0 + k2 = 0 2. When `ad - bc = 0` and `a^{2} + b^{2} > 0`. In this case, the system of equation becomes .. math:: x' = ax + by + k_1 , y' = k (ax + by) + k_2 2.1 If `\sigma = a + bk \neq 0`, particular solution is given by .. math:: x = b \sigma^{-1} (c_1 k - c_2) t - \sigma^{-2} (a c_1 + b c_2) .. math:: y = kx + (c_2 - c_1 k) t 2.2 If `\sigma = a + bk = 0`, particular solution is given by .. math:: x = \frac{1}{2} b (c_2 - c_1 k) t^{2} + c_1 t .. math:: y = kx + (c_2 - c_1 k) t """ r['k1'] = -r['k1']; r['k2'] = -r['k2'] if (r['a']*r['d'] - r['b']*r['c']) != 0: x0, y0 = symbols('x0, y0', cls=Dummy) sol = solve((r['a']*x0+r['b']*y0+r['k1'], r['c']*x0+r['d']*y0+r['k2']), x0, y0) psol = [sol[x0], sol[y0]] elif (r['a']*r['d'] - r['b']*r['c']) == 0 and (r['a']**2+r['b']**2) > 0: k = r['c']/r['a'] sigma = r['a'] + r['b']*k if sigma != 0: sol1 = r['b']*sigma**-1*(r['k1']*k-r['k2'])*t - sigma**-2*(r['a']*r['k1']+r['b']*r['k2']) sol2 = k*sol1 + (r['k2']-r['k1']*k)*t else: # FIXME: a previous typo fix shows this is not covered by tests sol1 = r['b']*(r['k2']-r['k1']*k)*t**2 + r['k1']*t sol2 = k*sol1 + (r['k2']-r['k1']*k)*t psol = [sol1, sol2] return psol def _linear_2eq_order1_type3(x, y, t, r, eq): r""" The equations of this type of ode are .. math:: x' = f(t) x + g(t) y .. math:: y' = g(t) x + f(t) y The solution of such equations is given by .. math:: x = e^{F} (C_1 e^{G} + C_2 e^{-G}) , y = e^{F} (C_1 e^{G} - C_2 e^{-G}) where `C_1` and `C_2` are arbitrary constants, and .. math:: F = \int f(t) \,dt , G = \int g(t) \,dt """ C1, C2, C3, C4 = get_numbered_constants(eq, num=4) F = Integral(r['a'], t) G = Integral(r['b'], t) sol1 = exp(F)*(C1*exp(G) + C2*exp(-G)) sol2 = exp(F)*(C1*exp(G) - C2*exp(-G)) return [Eq(x(t), sol1), Eq(y(t), sol2)] def _linear_2eq_order1_type4(x, y, t, r, eq): r""" The equations of this type of ode are . .. math:: x' = f(t) x + g(t) y .. math:: y' = -g(t) x + f(t) y The solution is given by .. math:: x = F (C_1 \cos(G) + C_2 \sin(G)), y = F (-C_1 \sin(G) + C_2 \cos(G)) where `C_1` and `C_2` are arbitrary constants, and .. math:: F = \int f(t) \,dt , G = \int g(t) \,dt """ C1, C2, C3, C4 = get_numbered_constants(eq, num=4) if r['b'] == -r['c']: F = exp(Integral(r['a'], t)) G = Integral(r['b'], t) sol1 = F*(C1*cos(G) + C2*sin(G)) sol2 = F*(-C1*sin(G) + C2*cos(G)) # FIXME: the case below doesn't seem correct, is only XFAIL tested and doesn't # match the description in the docstring above. It can be triggered with: # dsolve([Eq(f(x).diff(x), f(x) + x*g(x)), Eq(g(x).diff(x), x*f(x) - g(x))]) elif r['d'] == -r['a']: F = exp(Integral(r['b'], t)) G = Integral(r['d'], t) sol1 = F*(-C1*sin(G) + C2*cos(G)) sol2 = F*(C1*cos(G) + C2*sin(G)) return [Eq(x(t), sol1), Eq(y(t), sol2)] def _linear_2eq_order1_type5(x, y, t, r, eq): r""" The equations of this type of ode are . .. math:: x' = f(t) x + g(t) y .. math:: y' = a g(t) x + [f(t) + b g(t)] y The transformation of .. math:: x = e^{\int f(t) \,dt} u , y = e^{\int f(t) \,dt} v , T = \int g(t) \,dt leads to a system of constant coefficient linear differential equations .. math:: u'(T) = v , v'(T) = au + bv """ u, v = symbols('u, v', cls=Function) T = Symbol('T') if not cancel(r['c']/r['b']).has(t): p = cancel(r['c']/r['b']) q = cancel((r['d']-r['a'])/r['b']) eq = (Eq(diff(u(T),T), v(T)), Eq(diff(v(T),T), p*u(T)+q*v(T))) sol = dsolve(eq) sol1 = exp(Integral(r['a'], t))*sol[0].rhs.subs(T, Integral(r['b'], t)) sol2 = exp(Integral(r['a'], t))*sol[1].rhs.subs(T, Integral(r['b'], t)) # The case below isn't tested and doesn't match the description in the # docstring above. Perhaps this should be removed... if not cancel(r['a']/r['d']).has(t): p = cancel(r['a']/r['d']) q = cancel((r['b']-r['c'])/r['d']) sol = dsolve(Eq(diff(u(T),T), v(T)), Eq(diff(v(T),T), p*u(T)+q*v(T))) sol1 = exp(Integral(r['c'], t))*sol[1].rhs.subs(T, Integral(r['d'], t)) sol2 = exp(Integral(r['c'], t))*sol[0].rhs.subs(T, Integral(r['d'], t)) return [Eq(x(t), sol1), Eq(y(t), sol2)] def _linear_2eq_order1_type6(x, y, t, r, eq): r""" The equations of this type of ode are . .. math:: x' = f(t) x + g(t) y .. math:: y' = a [f(t) + a h(t)] x + a [g(t) - h(t)] y This is solved by first multiplying the first equation by `-a` and adding it to the second equation to obtain .. math:: y' - a x' = -a h(t) (y - a x) Setting `U = y - ax` and integrating the equation we arrive at .. math:: y - ax = C_1 e^{-a \int h(t) \,dt} and on substituting the value of y in first equation give rise to first order ODEs. After solving for `x`, we can obtain `y` by substituting the value of `x` in second equation. """ C1, C2, C3, C4 = get_numbered_constants(eq, num=4) p = 0 q = 0 p1 = cancel(r['c']/cancel(r['c']/r['d']).as_numer_denom()[0]) p2 = cancel(r['a']/cancel(r['a']/r['b']).as_numer_denom()[0]) for n, i in enumerate([p1, p2]): for j in Mul.make_args(collect_const(i)): if not j.has(t): q = j if q!=0 and n==0: if ((r['c']/j - r['a'])/(r['b'] - r['d']/j)) == j: p = 1 s = j break if q!=0 and n==1: if ((r['a']/j - r['c'])/(r['d'] - r['b']/j)) == j: p = 2 s = j break if p == 1: equ = diff(x(t),t) - r['a']*x(t) - r['b']*(s*x(t) + C1*exp(-s*Integral(r['b'] - r['d']/s, t))) hint1 = classify_ode(equ)[1] sol1 = dsolve(equ, hint=hint1+'_Integral').rhs sol2 = s*sol1 + C1*exp(-s*Integral(r['b'] - r['d']/s, t)) elif p ==2: equ = diff(y(t),t) - r['c']*y(t) - r['d']*s*y(t) + C1*exp(-s*Integral(r['d'] - r['b']/s, t)) hint1 = classify_ode(equ)[1] sol2 = dsolve(equ, hint=hint1+'_Integral').rhs sol1 = s*sol2 + C1*exp(-s*Integral(r['d'] - r['b']/s, t)) return [Eq(x(t), sol1), Eq(y(t), sol2)] def _linear_2eq_order1_type7(x, y, t, r, eq): r""" The equations of this type of ode are . .. math:: x' = f(t) x + g(t) y .. math:: y' = h(t) x + p(t) y Differentiating the first equation and substituting the value of `y` from second equation will give a second-order linear equation .. math:: g x'' - (fg + gp + g') x' + (fgp - g^{2} h + f g' - f' g) x = 0 This above equation can be easily integrated if following conditions are satisfied. 1. `fgp - g^{2} h + f g' - f' g = 0` 2. `fgp - g^{2} h + f g' - f' g = ag, fg + gp + g' = bg` If first condition is satisfied then it is solved by current dsolve solver and in second case it becomes a constant coefficient differential equation which is also solved by current solver. Otherwise if the above condition fails then, a particular solution is assumed as `x = x_0(t)` and `y = y_0(t)` Then the general solution is expressed as .. math:: x = C_1 x_0(t) + C_2 x_0(t) \int \frac{g(t) F(t) P(t)}{x_0^{2}(t)} \,dt .. math:: y = C_1 y_0(t) + C_2 [\frac{F(t) P(t)}{x_0(t)} + y_0(t) \int \frac{g(t) F(t) P(t)}{x_0^{2}(t)} \,dt] where C1 and C2 are arbitrary constants and .. math:: F(t) = e^{\int f(t) \,dt} , P(t) = e^{\int p(t) \,dt} """ C1, C2, C3, C4 = get_numbered_constants(eq, num=4) e1 = r['a']*r['b']*r['c'] - r['b']**2*r['c'] + r['a']*diff(r['b'],t) - diff(r['a'],t)*r['b'] e2 = r['a']*r['c']*r['d'] - r['b']*r['c']**2 + diff(r['c'],t)*r['d'] - r['c']*diff(r['d'],t) m1 = r['a']*r['b'] + r['b']*r['d'] + diff(r['b'],t) m2 = r['a']*r['c'] + r['c']*r['d'] + diff(r['c'],t) if e1 == 0: sol1 = dsolve(r['b']*diff(x(t),t,t) - m1*diff(x(t),t)).rhs sol2 = dsolve(diff(y(t),t) - r['c']*sol1 - r['d']*y(t)).rhs elif e2 == 0: sol2 = dsolve(r['c']*diff(y(t),t,t) - m2*diff(y(t),t)).rhs sol1 = dsolve(diff(x(t),t) - r['a']*x(t) - r['b']*sol2).rhs elif not (e1/r['b']).has(t) and not (m1/r['b']).has(t): sol1 = dsolve(diff(x(t),t,t) - (m1/r['b'])*diff(x(t),t) - (e1/r['b'])*x(t)).rhs sol2 = dsolve(diff(y(t),t) - r['c']*sol1 - r['d']*y(t)).rhs elif not (e2/r['c']).has(t) and not (m2/r['c']).has(t): sol2 = dsolve(diff(y(t),t,t) - (m2/r['c'])*diff(y(t),t) - (e2/r['c'])*y(t)).rhs sol1 = dsolve(diff(x(t),t) - r['a']*x(t) - r['b']*sol2).rhs else: x0 = Function('x0')(t) # x0 and y0 being particular solutions y0 = Function('y0')(t) F = exp(Integral(r['a'],t)) P = exp(Integral(r['d'],t)) sol1 = C1*x0 + C2*x0*Integral(r['b']*F*P/x0**2, t) sol2 = C1*y0 + C2*(F*P/x0 + y0*Integral(r['b']*F*P/x0**2, t)) return [Eq(x(t), sol1), Eq(y(t), sol2)] def sysode_linear_2eq_order2(match_): x = match_['func'][0].func y = match_['func'][1].func func = match_['func'] fc = match_['func_coeff'] eq = match_['eq'] r = dict() t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0] for i in range(2): eqs = [] for terms in Add.make_args(eq[i]): eqs.append(terms/fc[i,func[i],2]) eq[i] = Add(*eqs) # for equations Eq(diff(x(t),t,t), a1*diff(x(t),t)+b1*diff(y(t),t)+c1*x(t)+d1*y(t)+e1) # and Eq(a2*diff(y(t),t,t), a2*diff(x(t),t)+b2*diff(y(t),t)+c2*x(t)+d2*y(t)+e2) r['a1'] = -fc[0,x(t),1]/fc[0,x(t),2] ; r['a2'] = -fc[1,x(t),1]/fc[1,y(t),2] r['b1'] = -fc[0,y(t),1]/fc[0,x(t),2] ; r['b2'] = -fc[1,y(t),1]/fc[1,y(t),2] r['c1'] = -fc[0,x(t),0]/fc[0,x(t),2] ; r['c2'] = -fc[1,x(t),0]/fc[1,y(t),2] r['d1'] = -fc[0,y(t),0]/fc[0,x(t),2] ; r['d2'] = -fc[1,y(t),0]/fc[1,y(t),2] const = [S.Zero, S.Zero] for i in range(2): for j in Add.make_args(eq[i]): if not (j.has(x(t)) or j.has(y(t))): const[i] += j r['e1'] = -const[0] r['e2'] = -const[1] if match_['type_of_equation'] == 'type1': sol = _linear_2eq_order2_type1(x, y, t, r, eq) elif match_['type_of_equation'] == 'type2': gsol = _linear_2eq_order2_type1(x, y, t, r, eq) psol = _linear_2eq_order2_type2(x, y, t, r, eq) sol = [Eq(x(t), gsol[0].rhs+psol[0]), Eq(y(t), gsol[1].rhs+psol[1])] elif match_['type_of_equation'] == 'type3': sol = _linear_2eq_order2_type3(x, y, t, r, eq) elif match_['type_of_equation'] == 'type4': sol = _linear_2eq_order2_type4(x, y, t, r, eq) elif match_['type_of_equation'] == 'type5': sol = _linear_2eq_order2_type5(x, y, t, r, eq) elif match_['type_of_equation'] == 'type6': sol = _linear_2eq_order2_type6(x, y, t, r, eq) elif match_['type_of_equation'] == 'type7': sol = _linear_2eq_order2_type7(x, y, t, r, eq) elif match_['type_of_equation'] == 'type8': sol = _linear_2eq_order2_type8(x, y, t, r, eq) elif match_['type_of_equation'] == 'type9': sol = _linear_2eq_order2_type9(x, y, t, r, eq) elif match_['type_of_equation'] == 'type10': sol = _linear_2eq_order2_type10(x, y, t, r, eq) elif match_['type_of_equation'] == 'type11': sol = _linear_2eq_order2_type11(x, y, t, r, eq) return sol def _linear_2eq_order2_type1(x, y, t, r, eq): r""" System of two constant-coefficient second-order linear homogeneous differential equations .. math:: x'' = ax + by .. math:: y'' = cx + dy The characteristic equation for above equations .. math:: \lambda^4 - (a + d) \lambda^2 + ad - bc = 0 whose discriminant is `D = (a - d)^2 + 4bc \neq 0` 1. When `ad - bc \neq 0` 1.1. If `D \neq 0`. The characteristic equation has four distinct roots, `\lambda_1, \lambda_2, \lambda_3, \lambda_4`. The general solution of the system is .. math:: x = C_1 b e^{\lambda_1 t} + C_2 b e^{\lambda_2 t} + C_3 b e^{\lambda_3 t} + C_4 b e^{\lambda_4 t} .. math:: y = C_1 (\lambda_1^{2} - a) e^{\lambda_1 t} + C_2 (\lambda_2^{2} - a) e^{\lambda_2 t} + C_3 (\lambda_3^{2} - a) e^{\lambda_3 t} + C_4 (\lambda_4^{2} - a) e^{\lambda_4 t} where `C_1,..., C_4` are arbitrary constants. 1.2. If `D = 0` and `a \neq d`: .. math:: x = 2 C_1 (bt + \frac{2bk}{a - d}) e^{\frac{kt}{2}} + 2 C_2 (bt + \frac{2bk}{a - d}) e^{\frac{-kt}{2}} + 2b C_3 t e^{\frac{kt}{2}} + 2b C_4 t e^{\frac{-kt}{2}} .. math:: y = C_1 (d - a) t e^{\frac{kt}{2}} + C_2 (d - a) t e^{\frac{-kt}{2}} + C_3 [(d - a) t + 2k] e^{\frac{kt}{2}} + C_4 [(d - a) t - 2k] e^{\frac{-kt}{2}} where `C_1,..., C_4` are arbitrary constants and `k = \sqrt{2 (a + d)}` 1.3. If `D = 0` and `a = d \neq 0` and `b = 0`: .. math:: x = 2 \sqrt{a} C_1 e^{\sqrt{a} t} + 2 \sqrt{a} C_2 e^{-\sqrt{a} t} .. math:: y = c C_1 t e^{\sqrt{a} t} - c C_2 t e^{-\sqrt{a} t} + C_3 e^{\sqrt{a} t} + C_4 e^{-\sqrt{a} t} 1.4. If `D = 0` and `a = d \neq 0` and `c = 0`: .. math:: x = b C_1 t e^{\sqrt{a} t} - b C_2 t e^{-\sqrt{a} t} + C_3 e^{\sqrt{a} t} + C_4 e^{-\sqrt{a} t} .. math:: y = 2 \sqrt{a} C_1 e^{\sqrt{a} t} + 2 \sqrt{a} C_2 e^{-\sqrt{a} t} 2. When `ad - bc = 0` and `a^2 + b^2 > 0`. Then the original system becomes .. math:: x'' = ax + by .. math:: y'' = k (ax + by) 2.1. If `a + bk \neq 0`: .. math:: x = C_1 e^{t \sqrt{a + bk}} + C_2 e^{-t \sqrt{a + bk}} + C_3 bt + C_4 b .. math:: y = C_1 k e^{t \sqrt{a + bk}} + C_2 k e^{-t \sqrt{a + bk}} - C_3 at - C_4 a 2.2. If `a + bk = 0`: .. math:: x = C_1 b t^3 + C_2 b t^2 + C_3 t + C_4 .. math:: y = kx + 6 C_1 t + 2 C_2 """ r['a'] = r['c1'] r['b'] = r['d1'] r['c'] = r['c2'] r['d'] = r['d2'] l = Symbol('l') C1, C2, C3, C4 = get_numbered_constants(eq, num=4) chara_eq = l**4 - (r['a']+r['d'])*l**2 + r['a']*r['d'] - r['b']*r['c'] l1 = rootof(chara_eq, 0) l2 = rootof(chara_eq, 1) l3 = rootof(chara_eq, 2) l4 = rootof(chara_eq, 3) D = (r['a'] - r['d'])**2 + 4*r['b']*r['c'] if (r['a']*r['d'] - r['b']*r['c']) != 0: if D != 0: gsol1 = C1*r['b']*exp(l1*t) + C2*r['b']*exp(l2*t) + C3*r['b']*exp(l3*t) \ + C4*r['b']*exp(l4*t) gsol2 = C1*(l1**2-r['a'])*exp(l1*t) + C2*(l2**2-r['a'])*exp(l2*t) + \ C3*(l3**2-r['a'])*exp(l3*t) + C4*(l4**2-r['a'])*exp(l4*t) else: if r['a'] != r['d']: k = sqrt(2*(r['a']+r['d'])) mid = r['b']*t+2*r['b']*k/(r['a']-r['d']) gsol1 = 2*C1*mid*exp(k*t/2) + 2*C2*mid*exp(-k*t/2) + \ 2*r['b']*C3*t*exp(k*t/2) + 2*r['b']*C4*t*exp(-k*t/2) gsol2 = C1*(r['d']-r['a'])*t*exp(k*t/2) + C2*(r['d']-r['a'])*t*exp(-k*t/2) + \ C3*((r['d']-r['a'])*t+2*k)*exp(k*t/2) + C4*((r['d']-r['a'])*t-2*k)*exp(-k*t/2) elif r['a'] == r['d'] != 0 and r['b'] == 0: sa = sqrt(r['a']) gsol1 = 2*sa*C1*exp(sa*t) + 2*sa*C2*exp(-sa*t) gsol2 = r['c']*C1*t*exp(sa*t)-r['c']*C2*t*exp(-sa*t)+C3*exp(sa*t)+C4*exp(-sa*t) elif r['a'] == r['d'] != 0 and r['c'] == 0: sa = sqrt(r['a']) gsol1 = r['b']*C1*t*exp(sa*t)-r['b']*C2*t*exp(-sa*t)+C3*exp(sa*t)+C4*exp(-sa*t) gsol2 = 2*sa*C1*exp(sa*t) + 2*sa*C2*exp(-sa*t) elif (r['a']*r['d'] - r['b']*r['c']) == 0 and (r['a']**2 + r['b']**2) > 0: k = r['c']/r['a'] if r['a'] + r['b']*k != 0: mid = sqrt(r['a'] + r['b']*k) gsol1 = C1*exp(mid*t) + C2*exp(-mid*t) + C3*r['b']*t + C4*r['b'] gsol2 = C1*k*exp(mid*t) + C2*k*exp(-mid*t) - C3*r['a']*t - C4*r['a'] else: gsol1 = C1*r['b']*t**3 + C2*r['b']*t**2 + C3*t + C4 gsol2 = k*gsol1 + 6*C1*t + 2*C2 return [Eq(x(t), gsol1), Eq(y(t), gsol2)] def _linear_2eq_order2_type2(x, y, t, r, eq): r""" The equations in this type are .. math:: x'' = a_1 x + b_1 y + c_1 .. math:: y'' = a_2 x + b_2 y + c_2 The general solution of this system is given by the sum of its particular solution and the general solution of the homogeneous system. The general solution is given by the linear system of 2 equation of order 2 and type 1 1. If `a_1 b_2 - a_2 b_1 \neq 0`. A particular solution will be `x = x_0` and `y = y_0` where the constants `x_0` and `y_0` are determined by solving the linear algebraic system .. math:: a_1 x_0 + b_1 y_0 + c_1 = 0, a_2 x_0 + b_2 y_0 + c_2 = 0 2. If `a_1 b_2 - a_2 b_1 = 0` and `a_1^2 + b_1^2 > 0`. In this case, the system in question becomes .. math:: x'' = ax + by + c_1, y'' = k (ax + by) + c_2 2.1. If `\sigma = a + bk \neq 0`, the particular solution will be .. math:: x = \frac{1}{2} b \sigma^{-1} (c_1 k - c_2) t^2 - \sigma^{-2} (a c_1 + b c_2) .. math:: y = kx + \frac{1}{2} (c_2 - c_1 k) t^2 2.2. If `\sigma = a + bk = 0`, the particular solution will be .. math:: x = \frac{1}{24} b (c_2 - c_1 k) t^4 + \frac{1}{2} c_1 t^2 .. math:: y = kx + \frac{1}{2} (c_2 - c_1 k) t^2 """ x0, y0 = symbols('x0, y0') if r['c1']*r['d2'] - r['c2']*r['d1'] != 0: sol = solve((r['c1']*x0+r['d1']*y0+r['e1'], r['c2']*x0+r['d2']*y0+r['e2']), x0, y0) psol = [sol[x0], sol[y0]] elif r['c1']*r['d2'] - r['c2']*r['d1'] == 0 and (r['c1']**2 + r['d1']**2) > 0: k = r['c2']/r['c1'] sig = r['c1'] + r['d1']*k if sig != 0: psol1 = r['d1']*sig**-1*(r['e1']*k-r['e2'])*t**2/2 - \ sig**-2*(r['c1']*r['e1']+r['d1']*r['e2']) psol2 = k*psol1 + (r['e2'] - r['e1']*k)*t**2/2 psol = [psol1, psol2] else: psol1 = r['d1']*(r['e2']-r['e1']*k)*t**4/24 + r['e1']*t**2/2 psol2 = k*psol1 + (r['e2']-r['e1']*k)*t**2/2 psol = [psol1, psol2] return psol def _linear_2eq_order2_type3(x, y, t, r, eq): r""" These type of equation is used for describing the horizontal motion of a pendulum taking into account the Earth rotation. The solution is given with `a^2 + 4b > 0`: .. math:: x = C_1 \cos(\alpha t) + C_2 \sin(\alpha t) + C_3 \cos(\beta t) + C_4 \sin(\beta t) .. math:: y = -C_1 \sin(\alpha t) + C_2 \cos(\alpha t) - C_3 \sin(\beta t) + C_4 \cos(\beta t) where `C_1,...,C_4` and .. math:: \alpha = \frac{1}{2} a + \frac{1}{2} \sqrt{a^2 + 4b}, \beta = \frac{1}{2} a - \frac{1}{2} \sqrt{a^2 + 4b} """ C1, C2, C3, C4 = get_numbered_constants(eq, num=4) if r['b1']**2 - 4*r['c1'] > 0: r['a'] = r['b1'] ; r['b'] = -r['c1'] alpha = r['a']/2 + sqrt(r['a']**2 + 4*r['b'])/2 beta = r['a']/2 - sqrt(r['a']**2 + 4*r['b'])/2 sol1 = C1*cos(alpha*t) + C2*sin(alpha*t) + C3*cos(beta*t) + C4*sin(beta*t) sol2 = -C1*sin(alpha*t) + C2*cos(alpha*t) - C3*sin(beta*t) + C4*cos(beta*t) return [Eq(x(t), sol1), Eq(y(t), sol2)] def _linear_2eq_order2_type4(x, y, t, r, eq): r""" These equations are found in the theory of oscillations .. math:: x'' + a_1 x' + b_1 y' + c_1 x + d_1 y = k_1 e^{i \omega t} .. math:: y'' + a_2 x' + b_2 y' + c_2 x + d_2 y = k_2 e^{i \omega t} The general solution of this linear nonhomogeneous system of constant-coefficient differential equations is given by the sum of its particular solution and the general solution of the corresponding homogeneous system (with `k_1 = k_2 = 0`) 1. A particular solution is obtained by the method of undetermined coefficients: .. math:: x = A_* e^{i \omega t}, y = B_* e^{i \omega t} On substituting these expressions into the original system of differential equations, one arrive at a linear nonhomogeneous system of algebraic equations for the coefficients `A` and `B`. 2. The general solution of the homogeneous system of differential equations is determined by a linear combination of linearly independent particular solutions determined by the method of undetermined coefficients in the form of exponentials: .. math:: x = A e^{\lambda t}, y = B e^{\lambda t} On substituting these expressions into the original system and collecting the coefficients of the unknown `A` and `B`, one obtains .. math:: (\lambda^{2} + a_1 \lambda + c_1) A + (b_1 \lambda + d_1) B = 0 .. math:: (a_2 \lambda + c_2) A + (\lambda^{2} + b_2 \lambda + d_2) B = 0 The determinant of this system must vanish for nontrivial solutions A, B to exist. This requirement results in the following characteristic equation for `\lambda` .. math:: (\lambda^2 + a_1 \lambda + c_1) (\lambda^2 + b_2 \lambda + d_2) - (b_1 \lambda + d_1) (a_2 \lambda + c_2) = 0 If all roots `k_1,...,k_4` of this equation are distinct, the general solution of the original system of the differential equations has the form .. math:: x = C_1 (b_1 \lambda_1 + d_1) e^{\lambda_1 t} - C_2 (b_1 \lambda_2 + d_1) e^{\lambda_2 t} - C_3 (b_1 \lambda_3 + d_1) e^{\lambda_3 t} - C_4 (b_1 \lambda_4 + d_1) e^{\lambda_4 t} .. math:: y = C_1 (\lambda_1^{2} + a_1 \lambda_1 + c_1) e^{\lambda_1 t} + C_2 (\lambda_2^{2} + a_1 \lambda_2 + c_1) e^{\lambda_2 t} + C_3 (\lambda_3^{2} + a_1 \lambda_3 + c_1) e^{\lambda_3 t} + C_4 (\lambda_4^{2} + a_1 \lambda_4 + c_1) e^{\lambda_4 t} """ C1, C2, C3, C4 = get_numbered_constants(eq, num=4) k = Symbol('k') Ra, Ca, Rb, Cb = symbols('Ra, Ca, Rb, Cb') a1 = r['a1'] ; a2 = r['a2'] b1 = r['b1'] ; b2 = r['b2'] c1 = r['c1'] ; c2 = r['c2'] d1 = r['d1'] ; d2 = r['d2'] k1 = r['e1'].expand().as_independent(t)[0] k2 = r['e2'].expand().as_independent(t)[0] ew1 = r['e1'].expand().as_independent(t)[1] ew2 = powdenest(ew1).as_base_exp()[1] ew3 = collect(ew2, t).coeff(t) w = cancel(ew3/I) # The particular solution is assumed to be (Ra+I*Ca)*exp(I*w*t) and # (Rb+I*Cb)*exp(I*w*t) for x(t) and y(t) respectively # peq1, peq2, peq3, peq4 unused # peq1 = (-w**2+c1)*Ra - a1*w*Ca + d1*Rb - b1*w*Cb - k1 # peq2 = a1*w*Ra + (-w**2+c1)*Ca + b1*w*Rb + d1*Cb # peq3 = c2*Ra - a2*w*Ca + (-w**2+d2)*Rb - b2*w*Cb - k2 # peq4 = a2*w*Ra + c2*Ca + b2*w*Rb + (-w**2+d2)*Cb # FIXME: solve for what in what? Ra, Rb, etc I guess # but then psol not used for anything? # psol = solve([peq1, peq2, peq3, peq4]) chareq = (k**2+a1*k+c1)*(k**2+b2*k+d2) - (b1*k+d1)*(a2*k+c2) [k1, k2, k3, k4] = roots_quartic(Poly(chareq)) sol1 = -C1*(b1*k1+d1)*exp(k1*t) - C2*(b1*k2+d1)*exp(k2*t) - \ C3*(b1*k3+d1)*exp(k3*t) - C4*(b1*k4+d1)*exp(k4*t) + (Ra+I*Ca)*exp(I*w*t) a1_ = (a1-1) sol2 = C1*(k1**2+a1_*k1+c1)*exp(k1*t) + C2*(k2**2+a1_*k2+c1)*exp(k2*t) + \ C3*(k3**2+a1_*k3+c1)*exp(k3*t) + C4*(k4**2+a1_*k4+c1)*exp(k4*t) + (Rb+I*Cb)*exp(I*w*t) return [Eq(x(t), sol1), Eq(y(t), sol2)] def _linear_2eq_order2_type5(x, y, t, r, eq): r""" The equation which come under this category are .. math:: x'' = a (t y' - y) .. math:: y'' = b (t x' - x) The transformation .. math:: u = t x' - x, b = t y' - y leads to the first-order system .. math:: u' = atv, v' = btu The general solution of this system is given by If `ab > 0`: .. math:: u = C_1 a e^{\frac{1}{2} \sqrt{ab} t^2} + C_2 a e^{-\frac{1}{2} \sqrt{ab} t^2} .. math:: v = C_1 \sqrt{ab} e^{\frac{1}{2} \sqrt{ab} t^2} - C_2 \sqrt{ab} e^{-\frac{1}{2} \sqrt{ab} t^2} If `ab < 0`: .. math:: u = C_1 a \cos(\frac{1}{2} \sqrt{\left|ab\right|} t^2) + C_2 a \sin(-\frac{1}{2} \sqrt{\left|ab\right|} t^2) .. math:: v = C_1 \sqrt{\left|ab\right|} \sin(\frac{1}{2} \sqrt{\left|ab\right|} t^2) + C_2 \sqrt{\left|ab\right|} \cos(-\frac{1}{2} \sqrt{\left|ab\right|} t^2) where `C_1` and `C_2` are arbitrary constants. On substituting the value of `u` and `v` in above equations and integrating the resulting expressions, the general solution will become .. math:: x = C_3 t + t \int \frac{u}{t^2} \,dt, y = C_4 t + t \int \frac{u}{t^2} \,dt where `C_3` and `C_4` are arbitrary constants. """ C1, C2, C3, C4 = get_numbered_constants(eq, num=4) r['a'] = -r['d1'] ; r['b'] = -r['c2'] mul = sqrt(abs(r['a']*r['b'])) if r['a']*r['b'] > 0: u = C1*r['a']*exp(mul*t**2/2) + C2*r['a']*exp(-mul*t**2/2) v = C1*mul*exp(mul*t**2/2) - C2*mul*exp(-mul*t**2/2) else: u = C1*r['a']*cos(mul*t**2/2) + C2*r['a']*sin(mul*t**2/2) v = -C1*mul*sin(mul*t**2/2) + C2*mul*cos(mul*t**2/2) sol1 = C3*t + t*Integral(u/t**2, t) sol2 = C4*t + t*Integral(v/t**2, t) return [Eq(x(t), sol1), Eq(y(t), sol2)] def _linear_2eq_order2_type6(x, y, t, r, eq): r""" The equations are .. math:: x'' = f(t) (a_1 x + b_1 y) .. math:: y'' = f(t) (a_2 x + b_2 y) If `k_1` and `k_2` are roots of the quadratic equation .. math:: k^2 - (a_1 + b_2) k + a_1 b_2 - a_2 b_1 = 0 Then by multiplying appropriate constants and adding together original equations we obtain two independent equations: .. math:: z_1'' = k_1 f(t) z_1, z_1 = a_2 x + (k_1 - a_1) y .. math:: z_2'' = k_2 f(t) z_2, z_2 = a_2 x + (k_2 - a_1) y Solving the equations will give the values of `x` and `y` after obtaining the value of `z_1` and `z_2` by solving the differential equation and substituting the result. """ k = Symbol('k') z = Function('z') num, den = cancel( (r['c1']*x(t) + r['d1']*y(t))/ (r['c2']*x(t) + r['d2']*y(t))).as_numer_denom() f = r['c1']/num.coeff(x(t)) a1 = num.coeff(x(t)) b1 = num.coeff(y(t)) a2 = den.coeff(x(t)) b2 = den.coeff(y(t)) chareq = k**2 - (a1 + b2)*k + a1*b2 - a2*b1 k1, k2 = [rootof(chareq, k) for k in range(Poly(chareq).degree())] z1 = dsolve(diff(z(t),t,t) - k1*f*z(t)).rhs z2 = dsolve(diff(z(t),t,t) - k2*f*z(t)).rhs sol1 = (k1*z2 - k2*z1 + a1*(z1 - z2))/(a2*(k1-k2)) sol2 = (z1 - z2)/(k1 - k2) return [Eq(x(t), sol1), Eq(y(t), sol2)] def _linear_2eq_order2_type7(x, y, t, r, eq): r""" The equations are given as .. math:: x'' = f(t) (a_1 x' + b_1 y') .. math:: y'' = f(t) (a_2 x' + b_2 y') If `k_1` and 'k_2` are roots of the quadratic equation .. math:: k^2 - (a_1 + b_2) k + a_1 b_2 - a_2 b_1 = 0 Then the system can be reduced by adding together the two equations multiplied by appropriate constants give following two independent equations: .. math:: z_1'' = k_1 f(t) z_1', z_1 = a_2 x + (k_1 - a_1) y .. math:: z_2'' = k_2 f(t) z_2', z_2 = a_2 x + (k_2 - a_1) y Integrating these and returning to the original variables, one arrives at a linear algebraic system for the unknowns `x` and `y`: .. math:: a_2 x + (k_1 - a_1) y = C_1 \int e^{k_1 F(t)} \,dt + C_2 .. math:: a_2 x + (k_2 - a_1) y = C_3 \int e^{k_2 F(t)} \,dt + C_4 where `C_1,...,C_4` are arbitrary constants and `F(t) = \int f(t) \,dt` """ C1, C2, C3, C4 = get_numbered_constants(eq, num=4) k = Symbol('k') num, den = cancel( (r['a1']*x(t) + r['b1']*y(t))/ (r['a2']*x(t) + r['b2']*y(t))).as_numer_denom() f = r['a1']/num.coeff(x(t)) a1 = num.coeff(x(t)) b1 = num.coeff(y(t)) a2 = den.coeff(x(t)) b2 = den.coeff(y(t)) chareq = k**2 - (a1 + b2)*k + a1*b2 - a2*b1 [k1, k2] = [rootof(chareq, k) for k in range(Poly(chareq).degree())] F = Integral(f, t) z1 = C1*Integral(exp(k1*F), t) + C2 z2 = C3*Integral(exp(k2*F), t) + C4 sol1 = (k1*z2 - k2*z1 + a1*(z1 - z2))/(a2*(k1-k2)) sol2 = (z1 - z2)/(k1 - k2) return [Eq(x(t), sol1), Eq(y(t), sol2)] def _linear_2eq_order2_type8(x, y, t, r, eq): r""" The equation of this category are .. math:: x'' = a f(t) (t y' - y) .. math:: y'' = b f(t) (t x' - x) The transformation .. math:: u = t x' - x, v = t y' - y leads to the system of first-order equations .. math:: u' = a t f(t) v, v' = b t f(t) u The general solution of this system has the form If `ab > 0`: .. math:: u = C_1 a e^{\sqrt{ab} \int t f(t) \,dt} + C_2 a e^{-\sqrt{ab} \int t f(t) \,dt} .. math:: v = C_1 \sqrt{ab} e^{\sqrt{ab} \int t f(t) \,dt} - C_2 \sqrt{ab} e^{-\sqrt{ab} \int t f(t) \,dt} If `ab < 0`: .. math:: u = C_1 a \cos(\sqrt{\left|ab\right|} \int t f(t) \,dt) + C_2 a \sin(-\sqrt{\left|ab\right|} \int t f(t) \,dt) .. math:: v = C_1 \sqrt{\left|ab\right|} \sin(\sqrt{\left|ab\right|} \int t f(t) \,dt) + C_2 \sqrt{\left|ab\right|} \cos(-\sqrt{\left|ab\right|} \int t f(t) \,dt) where `C_1` and `C_2` are arbitrary constants. On substituting the value of `u` and `v` in above equations and integrating the resulting expressions, the general solution will become .. math:: x = C_3 t + t \int \frac{u}{t^2} \,dt, y = C_4 t + t \int \frac{u}{t^2} \,dt where `C_3` and `C_4` are arbitrary constants. """ C1, C2, C3, C4 = get_numbered_constants(eq, num=4) num, den = cancel(r['d1']/r['c2']).as_numer_denom() f = -r['d1']/num a = num b = den mul = sqrt(abs(a*b)) Igral = Integral(t*f, t) if a*b > 0: u = C1*a*exp(mul*Igral) + C2*a*exp(-mul*Igral) v = C1*mul*exp(mul*Igral) - C2*mul*exp(-mul*Igral) else: u = C1*a*cos(mul*Igral) + C2*a*sin(mul*Igral) v = -C1*mul*sin(mul*Igral) + C2*mul*cos(mul*Igral) sol1 = C3*t + t*Integral(u/t**2, t) sol2 = C4*t + t*Integral(v/t**2, t) return [Eq(x(t), sol1), Eq(y(t), sol2)] def _linear_2eq_order2_type9(x, y, t, r, eq): r""" .. math:: t^2 x'' + a_1 t x' + b_1 t y' + c_1 x + d_1 y = 0 .. math:: t^2 y'' + a_2 t x' + b_2 t y' + c_2 x + d_2 y = 0 These system of equations are euler type. The substitution of `t = \sigma e^{\tau} (\sigma \neq 0)` leads to the system of constant coefficient linear differential equations .. math:: x'' + (a_1 - 1) x' + b_1 y' + c_1 x + d_1 y = 0 .. math:: y'' + a_2 x' + (b_2 - 1) y' + c_2 x + d_2 y = 0 The general solution of the homogeneous system of differential equations is determined by a linear combination of linearly independent particular solutions determined by the method of undetermined coefficients in the form of exponentials .. math:: x = A e^{\lambda t}, y = B e^{\lambda t} On substituting these expressions into the original system and collecting the coefficients of the unknown `A` and `B`, one obtains .. math:: (\lambda^{2} + (a_1 - 1) \lambda + c_1) A + (b_1 \lambda + d_1) B = 0 .. math:: (a_2 \lambda + c_2) A + (\lambda^{2} + (b_2 - 1) \lambda + d_2) B = 0 The determinant of this system must vanish for nontrivial solutions A, B to exist. This requirement results in the following characteristic equation for `\lambda` .. math:: (\lambda^2 + (a_1 - 1) \lambda + c_1) (\lambda^2 + (b_2 - 1) \lambda + d_2) - (b_1 \lambda + d_1) (a_2 \lambda + c_2) = 0 If all roots `k_1,...,k_4` of this equation are distinct, the general solution of the original system of the differential equations has the form .. math:: x = C_1 (b_1 \lambda_1 + d_1) e^{\lambda_1 t} - C_2 (b_1 \lambda_2 + d_1) e^{\lambda_2 t} - C_3 (b_1 \lambda_3 + d_1) e^{\lambda_3 t} - C_4 (b_1 \lambda_4 + d_1) e^{\lambda_4 t} .. math:: y = C_1 (\lambda_1^{2} + (a_1 - 1) \lambda_1 + c_1) e^{\lambda_1 t} + C_2 (\lambda_2^{2} + (a_1 - 1) \lambda_2 + c_1) e^{\lambda_2 t} + C_3 (\lambda_3^{2} + (a_1 - 1) \lambda_3 + c_1) e^{\lambda_3 t} + C_4 (\lambda_4^{2} + (a_1 - 1) \lambda_4 + c_1) e^{\lambda_4 t} """ C1, C2, C3, C4 = get_numbered_constants(eq, num=4) k = Symbol('k') a1 = -r['a1']*t; a2 = -r['a2']*t b1 = -r['b1']*t; b2 = -r['b2']*t c1 = -r['c1']*t**2; c2 = -r['c2']*t**2 d1 = -r['d1']*t**2; d2 = -r['d2']*t**2 eq = (k**2+(a1-1)*k+c1)*(k**2+(b2-1)*k+d2)-(b1*k+d1)*(a2*k+c2) [k1, k2, k3, k4] = roots_quartic(Poly(eq)) sol1 = -C1*(b1*k1+d1)*exp(k1*log(t)) - C2*(b1*k2+d1)*exp(k2*log(t)) - \ C3*(b1*k3+d1)*exp(k3*log(t)) - C4*(b1*k4+d1)*exp(k4*log(t)) a1_ = (a1-1) sol2 = C1*(k1**2+a1_*k1+c1)*exp(k1*log(t)) + C2*(k2**2+a1_*k2+c1)*exp(k2*log(t)) \ + C3*(k3**2+a1_*k3+c1)*exp(k3*log(t)) + C4*(k4**2+a1_*k4+c1)*exp(k4*log(t)) return [Eq(x(t), sol1), Eq(y(t), sol2)] def _linear_2eq_order2_type10(x, y, t, r, eq): r""" The equation of this category are .. math:: (\alpha t^2 + \beta t + \gamma)^{2} x'' = ax + by .. math:: (\alpha t^2 + \beta t + \gamma)^{2} y'' = cx + dy The transformation .. math:: \tau = \int \frac{1}{\alpha t^2 + \beta t + \gamma} \,dt , u = \frac{x}{\sqrt{\left|\alpha t^2 + \beta t + \gamma\right|}} , v = \frac{y}{\sqrt{\left|\alpha t^2 + \beta t + \gamma\right|}} leads to a constant coefficient linear system of equations .. math:: u'' = (a - \alpha \gamma + \frac{1}{4} \beta^{2}) u + b v .. math:: v'' = c u + (d - \alpha \gamma + \frac{1}{4} \beta^{2}) v These system of equations obtained can be solved by type1 of System of two constant-coefficient second-order linear homogeneous differential equations. """ # FIXME: This function is equivalent to type6 (and broken). Should be removed... C1, C2, C3, C4 = get_numbered_constants(eq, num=4) u, v = symbols('u, v', cls=Function) assert False p = Wild('p', exclude=[t, t**2]) q = Wild('q', exclude=[t, t**2]) s = Wild('s', exclude=[t, t**2]) n = Wild('n', exclude=[t, t**2]) num, den = r['c1'].as_numer_denom() dic = den.match((n*(p*t**2+q*t+s)**2).expand()) eqz = dic[p]*t**2 + dic[q]*t + dic[s] a = num/dic[n] b = cancel(r['d1']*eqz**2) c = cancel(r['c2']*eqz**2) d = cancel(r['d2']*eqz**2) [msol1, msol2] = dsolve([Eq(diff(u(t), t, t), (a - dic[p]*dic[s] + dic[q]**2/4)*u(t) \ + b*v(t)), Eq(diff(v(t),t,t), c*u(t) + (d - dic[p]*dic[s] + dic[q]**2/4)*v(t))]) sol1 = (msol1.rhs*sqrt(abs(eqz))).subs(t, Integral(1/eqz, t)) sol2 = (msol2.rhs*sqrt(abs(eqz))).subs(t, Integral(1/eqz, t)) return [Eq(x(t), sol1), Eq(y(t), sol2)] def _linear_2eq_order2_type11(x, y, t, r, eq): r""" The equations which comes under this type are .. math:: x'' = f(t) (t x' - x) + g(t) (t y' - y) .. math:: y'' = h(t) (t x' - x) + p(t) (t y' - y) The transformation .. math:: u = t x' - x, v = t y' - y leads to the linear system of first-order equations .. math:: u' = t f(t) u + t g(t) v, v' = t h(t) u + t p(t) v On substituting the value of `u` and `v` in transformed equation gives value of `x` and `y` as .. math:: x = C_3 t + t \int \frac{u}{t^2} \,dt , y = C_4 t + t \int \frac{v}{t^2} \,dt. where `C_3` and `C_4` are arbitrary constants. """ C1, C2, C3, C4 = get_numbered_constants(eq, num=4) u, v = symbols('u, v', cls=Function) f = -r['c1'] ; g = -r['d1'] h = -r['c2'] ; p = -r['d2'] [msol1, msol2] = dsolve([Eq(diff(u(t),t), t*f*u(t) + t*g*v(t)), Eq(diff(v(t),t), t*h*u(t) + t*p*v(t))]) sol1 = C3*t + t*Integral(msol1.rhs/t**2, t) sol2 = C4*t + t*Integral(msol2.rhs/t**2, t) return [Eq(x(t), sol1), Eq(y(t), sol2)] def sysode_linear_3eq_order1(match_): x = match_['func'][0].func y = match_['func'][1].func z = match_['func'][2].func func = match_['func'] fc = match_['func_coeff'] eq = match_['eq'] r = dict() t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0] for i in range(3): eqs = 0 for terms in Add.make_args(eq[i]): eqs += terms/fc[i,func[i],1] eq[i] = eqs # for equations: # Eq(g1*diff(x(t),t), a1*x(t)+b1*y(t)+c1*z(t)+d1), # Eq(g2*diff(y(t),t), a2*x(t)+b2*y(t)+c2*z(t)+d2), and # Eq(g3*diff(z(t),t), a3*x(t)+b3*y(t)+c3*z(t)+d3) r['a1'] = fc[0,x(t),0]/fc[0,x(t),1]; r['a2'] = fc[1,x(t),0]/fc[1,y(t),1]; r['a3'] = fc[2,x(t),0]/fc[2,z(t),1] r['b1'] = fc[0,y(t),0]/fc[0,x(t),1]; r['b2'] = fc[1,y(t),0]/fc[1,y(t),1]; r['b3'] = fc[2,y(t),0]/fc[2,z(t),1] r['c1'] = fc[0,z(t),0]/fc[0,x(t),1]; r['c2'] = fc[1,z(t),0]/fc[1,y(t),1]; r['c3'] = fc[2,z(t),0]/fc[2,z(t),1] for i in range(3): for j in Add.make_args(eq[i]): if not j.has(x(t), y(t), z(t)): raise NotImplementedError("Only homogeneous problems are supported, non-homogeneous are not supported currently.") if match_['type_of_equation'] == 'type1': sol = _linear_3eq_order1_type1(x, y, z, t, r, eq) if match_['type_of_equation'] == 'type2': sol = _linear_3eq_order1_type2(x, y, z, t, r, eq) if match_['type_of_equation'] == 'type3': sol = _linear_3eq_order1_type3(x, y, z, t, r, eq) if match_['type_of_equation'] == 'type4': sol = _linear_3eq_order1_type4(x, y, z, t, r, eq) if match_['type_of_equation'] == 'type6': sol = _linear_neq_order1_type1(match_) return sol def _linear_3eq_order1_type1(x, y, z, t, r, eq): r""" .. math:: x' = ax .. math:: y' = bx + cy .. math:: z' = dx + ky + pz Solution of such equations are forward substitution. Solving first equations gives the value of `x`, substituting it in second and third equation and solving second equation gives `y` and similarly substituting `y` in third equation give `z`. .. math:: x = C_1 e^{at} .. math:: y = \frac{b C_1}{a - c} e^{at} + C_2 e^{ct} .. math:: z = \frac{C_1}{a - p} (d + \frac{bk}{a - c}) e^{at} + \frac{k C_2}{c - p} e^{ct} + C_3 e^{pt} where `C_1, C_2` and `C_3` are arbitrary constants. """ C1, C2, C3, C4 = get_numbered_constants(eq, num=4) a = -r['a1']; b = -r['a2']; c = -r['b2'] d = -r['a3']; k = -r['b3']; p = -r['c3'] sol1 = C1*exp(a*t) sol2 = b*C1*exp(a*t)/(a-c) + C2*exp(c*t) sol3 = C1*(d+b*k/(a-c))*exp(a*t)/(a-p) + k*C2*exp(c*t)/(c-p) + C3*exp(p*t) return [Eq(x(t), sol1), Eq(y(t), sol2), Eq(z(t), sol3)] def _linear_3eq_order1_type2(x, y, z, t, r, eq): r""" The equations of this type are .. math:: x' = cy - bz .. math:: y' = az - cx .. math:: z' = bx - ay 1. First integral: .. math:: ax + by + cz = A \qquad - (1) .. math:: x^2 + y^2 + z^2 = B^2 \qquad - (2) where `A` and `B` are arbitrary constants. It follows from these integrals that the integral lines are circles formed by the intersection of the planes `(1)` and sphere `(2)` 2. Solution: .. math:: x = a C_0 + k C_1 \cos(kt) + (c C_2 - b C_3) \sin(kt) .. math:: y = b C_0 + k C_2 \cos(kt) + (a C_2 - c C_3) \sin(kt) .. math:: z = c C_0 + k C_3 \cos(kt) + (b C_2 - a C_3) \sin(kt) where `k = \sqrt{a^2 + b^2 + c^2}` and the four constants of integration, `C_1,...,C_4` are constrained by a single relation, .. math:: a C_1 + b C_2 + c C_3 = 0 """ C0, C1, C2, C3 = get_numbered_constants(eq, num=4, start=0) a = -r['c2']; b = -r['a3']; c = -r['b1'] k = sqrt(a**2 + b**2 + c**2) C3 = (-a*C1 - b*C2)/c sol1 = a*C0 + k*C1*cos(k*t) + (c*C2-b*C3)*sin(k*t) sol2 = b*C0 + k*C2*cos(k*t) + (a*C3-c*C1)*sin(k*t) sol3 = c*C0 + k*C3*cos(k*t) + (b*C1-a*C2)*sin(k*t) return [Eq(x(t), sol1), Eq(y(t), sol2), Eq(z(t), sol3)] def _linear_3eq_order1_type3(x, y, z, t, r, eq): r""" Equations of this system of ODEs .. math:: a x' = bc (y - z) .. math:: b y' = ac (z - x) .. math:: c z' = ab (x - y) 1. First integral: .. math:: a^2 x + b^2 y + c^2 z = A where A is an arbitrary constant. It follows that the integral lines are plane curves. 2. Solution: .. math:: x = C_0 + k C_1 \cos(kt) + a^{-1} bc (C_2 - C_3) \sin(kt) .. math:: y = C_0 + k C_2 \cos(kt) + a b^{-1} c (C_3 - C_1) \sin(kt) .. math:: z = C_0 + k C_3 \cos(kt) + ab c^{-1} (C_1 - C_2) \sin(kt) where `k = \sqrt{a^2 + b^2 + c^2}` and the four constants of integration, `C_1,...,C_4` are constrained by a single relation .. math:: a^2 C_1 + b^2 C_2 + c^2 C_3 = 0 """ C0, C1, C2, C3 = get_numbered_constants(eq, num=4, start=0) c = sqrt(r['b1']*r['c2']) b = sqrt(r['b1']*r['a3']) a = sqrt(r['c2']*r['a3']) C3 = (-a**2*C1-b**2*C2)/c**2 k = sqrt(a**2 + b**2 + c**2) sol1 = C0 + k*C1*cos(k*t) + a**-1*b*c*(C2-C3)*sin(k*t) sol2 = C0 + k*C2*cos(k*t) + a*b**-1*c*(C3-C1)*sin(k*t) sol3 = C0 + k*C3*cos(k*t) + a*b*c**-1*(C1-C2)*sin(k*t) return [Eq(x(t), sol1), Eq(y(t), sol2), Eq(z(t), sol3)] def _linear_3eq_order1_type4(x, y, z, t, r, eq): r""" Equations: .. math:: x' = (a_1 f(t) + g(t)) x + a_2 f(t) y + a_3 f(t) z .. math:: y' = b_1 f(t) x + (b_2 f(t) + g(t)) y + b_3 f(t) z .. math:: z' = c_1 f(t) x + c_2 f(t) y + (c_3 f(t) + g(t)) z The transformation .. math:: x = e^{\int g(t) \,dt} u, y = e^{\int g(t) \,dt} v, z = e^{\int g(t) \,dt} w, \tau = \int f(t) \,dt leads to the system of constant coefficient linear differential equations .. math:: u' = a_1 u + a_2 v + a_3 w .. math:: v' = b_1 u + b_2 v + b_3 w .. math:: w' = c_1 u + c_2 v + c_3 w These system of equations are solved by homogeneous linear system of constant coefficients of `n` equations of first order. Then substituting the value of `u, v` and `w` in transformed equation gives value of `x, y` and `z`. """ u, v, w = symbols('u, v, w', cls=Function) a2, a3 = cancel(r['b1']/r['c1']).as_numer_denom() f = cancel(r['b1']/a2) b1 = cancel(r['a2']/f); b3 = cancel(r['c2']/f) c1 = cancel(r['a3']/f); c2 = cancel(r['b3']/f) a1, g = div(r['a1'],f) b2 = div(r['b2'],f)[0] c3 = div(r['c3'],f)[0] trans_eq = (diff(u(t),t)-a1*u(t)-a2*v(t)-a3*w(t), diff(v(t),t)-b1*u(t)-\ b2*v(t)-b3*w(t), diff(w(t),t)-c1*u(t)-c2*v(t)-c3*w(t)) sol = dsolve(trans_eq) sol1 = exp(Integral(g,t))*((sol[0].rhs).subs(t, Integral(f,t))) sol2 = exp(Integral(g,t))*((sol[1].rhs).subs(t, Integral(f,t))) sol3 = exp(Integral(g,t))*((sol[2].rhs).subs(t, Integral(f,t))) return [Eq(x(t), sol1), Eq(y(t), sol2), Eq(z(t), sol3)] def sysode_linear_neq_order1(match_): sol = _linear_neq_order1_type1(match_) return sol def _linear_neq_order1_type1(match_): r""" System of n first-order constant-coefficient linear nonhomogeneous differential equation .. math:: y'_k = a_{k1} y_1 + a_{k2} y_2 +...+ a_{kn} y_n; k = 1,2,...,n or that can be written as `\vec{y'} = A . \vec{y}` where `\vec{y}` is matrix of `y_k` for `k = 1,2,...n` and `A` is a `n \times n` matrix. Since these equations are equivalent to a first order homogeneous linear differential equation. So the general solution will contain `n` linearly independent parts and solution will consist some type of exponential functions. Assuming `y = \vec{v} e^{rt}` is a solution of the system where `\vec{v}` is a vector of coefficients of `y_1,...,y_n`. Substituting `y` and `y' = r v e^{r t}` into the equation `\vec{y'} = A . \vec{y}`, we get .. math:: r \vec{v} e^{rt} = A \vec{v} e^{rt} .. math:: r \vec{v} = A \vec{v} where `r` comes out to be eigenvalue of `A` and vector `\vec{v}` is the eigenvector of `A` corresponding to `r`. There are three possibilities of eigenvalues of `A` - `n` distinct real eigenvalues - complex conjugate eigenvalues - eigenvalues with multiplicity `k` 1. When all eigenvalues `r_1,..,r_n` are distinct with `n` different eigenvectors `v_1,...v_n` then the solution is given by .. math:: \vec{y} = C_1 e^{r_1 t} \vec{v_1} + C_2 e^{r_2 t} \vec{v_2} +...+ C_n e^{r_n t} \vec{v_n} where `C_1,C_2,...,C_n` are arbitrary constants. 2. When some eigenvalues are complex then in order to make the solution real, we take a linear combination: if `r = a + bi` has an eigenvector `\vec{v} = \vec{w_1} + i \vec{w_2}` then to obtain real-valued solutions to the system, replace the complex-valued solutions `e^{rx} \vec{v}` with real-valued solution `e^{ax} (\vec{w_1} \cos(bx) - \vec{w_2} \sin(bx))` and for `r = a - bi` replace the solution `e^{-r x} \vec{v}` with `e^{ax} (\vec{w_1} \sin(bx) + \vec{w_2} \cos(bx))` 3. If some eigenvalues are repeated. Then we get fewer than `n` linearly independent eigenvectors, we miss some of the solutions and need to construct the missing ones. We do this via generalized eigenvectors, vectors which are not eigenvectors but are close enough that we can use to write down the remaining solutions. For a eigenvalue `r` with eigenvector `\vec{w}` we obtain `\vec{w_2},...,\vec{w_k}` using .. math:: (A - r I) . \vec{w_2} = \vec{w} .. math:: (A - r I) . \vec{w_3} = \vec{w_2} .. math:: \vdots .. math:: (A - r I) . \vec{w_k} = \vec{w_{k-1}} Then the solutions to the system for the eigenspace are `e^{rt} [\vec{w}], e^{rt} [t \vec{w} + \vec{w_2}], e^{rt} [\frac{t^2}{2} \vec{w} + t \vec{w_2} + \vec{w_3}], ...,e^{rt} [\frac{t^{k-1}}{(k-1)!} \vec{w} + \frac{t^{k-2}}{(k-2)!} \vec{w_2} +...+ t \vec{w_{k-1}} + \vec{w_k}]` So, If `\vec{y_1},...,\vec{y_n}` are `n` solution of obtained from three categories of `A`, then general solution to the system `\vec{y'} = A . \vec{y}` .. math:: \vec{y} = C_1 \vec{y_1} + C_2 \vec{y_2} + \cdots + C_n \vec{y_n} """ eq = match_['eq'] func = match_['func'] fc = match_['func_coeff'] n = len(eq) t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0] constants = numbered_symbols(prefix='C', cls=Symbol, start=1) M = Matrix(n,n,lambda i,j:-fc[i,func[j],0]) evector = M.eigenvects(simplify=True) def is_complex(mat, root): return Matrix(n, 1, lambda i,j: re(mat[i])*cos(im(root)*t) - im(mat[i])*sin(im(root)*t)) def is_complex_conjugate(mat, root): return Matrix(n, 1, lambda i,j: re(mat[i])*sin(abs(im(root))*t) + im(mat[i])*cos(im(root)*t)*abs(im(root))/im(root)) conjugate_root = [] e_vector = zeros(n,1) for evects in evector: if evects[0] not in conjugate_root: # If number of column of an eigenvector is not equal to the multiplicity # of its eigenvalue then the legt eigenvectors are calculated if len(evects[2])!=evects[1]: var_mat = Matrix(n, 1, lambda i,j: Symbol('x'+str(i))) Mnew = (M - evects[0]*eye(evects[2][-1].rows))*var_mat w = [0 for i in range(evects[1])] w[0] = evects[2][-1] for r in range(1, evects[1]): w_ = Mnew - w[r-1] sol_dict = solve(list(w_), var_mat[1:]) sol_dict[var_mat[0]] = var_mat[0] for key, value in sol_dict.items(): sol_dict[key] = value.subs(var_mat[0],1) w[r] = Matrix(n, 1, lambda i,j: sol_dict[var_mat[i]]) evects[2].append(w[r]) for i in range(evects[1]): C = next(constants) for j in range(i+1): if evects[0].has(I): evects[2][j] = simplify(evects[2][j]) e_vector += C*is_complex(evects[2][j], evects[0])*t**(i-j)*exp(re(evects[0])*t)/factorial(i-j) C = next(constants) e_vector += C*is_complex_conjugate(evects[2][j], evects[0])*t**(i-j)*exp(re(evects[0])*t)/factorial(i-j) else: e_vector += C*evects[2][j]*t**(i-j)*exp(evects[0]*t)/factorial(i-j) if evects[0].has(I): conjugate_root.append(conjugate(evects[0])) sol = [] for i in range(len(eq)): sol.append(Eq(func[i],e_vector[i])) return sol def sysode_nonlinear_2eq_order1(match_): func = match_['func'] eq = match_['eq'] fc = match_['func_coeff'] t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0] if match_['type_of_equation'] == 'type5': sol = _nonlinear_2eq_order1_type5(func, t, eq) return sol x = func[0].func y = func[1].func for i in range(2): eqs = 0 for terms in Add.make_args(eq[i]): eqs += terms/fc[i,func[i],1] eq[i] = eqs if match_['type_of_equation'] == 'type1': sol = _nonlinear_2eq_order1_type1(x, y, t, eq) elif match_['type_of_equation'] == 'type2': sol = _nonlinear_2eq_order1_type2(x, y, t, eq) elif match_['type_of_equation'] == 'type3': sol = _nonlinear_2eq_order1_type3(x, y, t, eq) elif match_['type_of_equation'] == 'type4': sol = _nonlinear_2eq_order1_type4(x, y, t, eq) return sol def _nonlinear_2eq_order1_type1(x, y, t, eq): r""" Equations: .. math:: x' = x^n F(x,y) .. math:: y' = g(y) F(x,y) Solution: .. math:: x = \varphi(y), \int \frac{1}{g(y) F(\varphi(y),y)} \,dy = t + C_2 where if `n \neq 1` .. math:: \varphi = [C_1 + (1-n) \int \frac{1}{g(y)} \,dy]^{\frac{1}{1-n}} if `n = 1` .. math:: \varphi = C_1 e^{\int \frac{1}{g(y)} \,dy} where `C_1` and `C_2` are arbitrary constants. """ C1, C2 = get_numbered_constants(eq, num=2) n = Wild('n', exclude=[x(t),y(t)]) f = Wild('f') u, v = symbols('u, v') r = eq[0].match(diff(x(t),t) - x(t)**n*f) g = ((diff(y(t),t) - eq[1])/r[f]).subs(y(t),v) F = r[f].subs(x(t),u).subs(y(t),v) n = r[n] if n!=1: phi = (C1 + (1-n)*Integral(1/g, v))**(1/(1-n)) else: phi = C1*exp(Integral(1/g, v)) phi = phi.doit() sol2 = solve(Integral(1/(g*F.subs(u,phi)), v).doit() - t - C2, v) sol = [] for sols in sol2: sol.append(Eq(x(t),phi.subs(v, sols))) sol.append(Eq(y(t), sols)) return sol def _nonlinear_2eq_order1_type2(x, y, t, eq): r""" Equations: .. math:: x' = e^{\lambda x} F(x,y) .. math:: y' = g(y) F(x,y) Solution: .. math:: x = \varphi(y), \int \frac{1}{g(y) F(\varphi(y),y)} \,dy = t + C_2 where if `\lambda \neq 0` .. math:: \varphi = -\frac{1}{\lambda} log(C_1 - \lambda \int \frac{1}{g(y)} \,dy) if `\lambda = 0` .. math:: \varphi = C_1 + \int \frac{1}{g(y)} \,dy where `C_1` and `C_2` are arbitrary constants. """ C1, C2 = get_numbered_constants(eq, num=2) n = Wild('n', exclude=[x(t),y(t)]) f = Wild('f') u, v = symbols('u, v') r = eq[0].match(diff(x(t),t) - exp(n*x(t))*f) g = ((diff(y(t),t) - eq[1])/r[f]).subs(y(t),v) F = r[f].subs(x(t),u).subs(y(t),v) n = r[n] if n: phi = -1/n*log(C1 - n*Integral(1/g, v)) else: phi = C1 + Integral(1/g, v) phi = phi.doit() sol2 = solve(Integral(1/(g*F.subs(u,phi)), v).doit() - t - C2, v) sol = [] for sols in sol2: sol.append(Eq(x(t),phi.subs(v, sols))) sol.append(Eq(y(t), sols)) return sol def _nonlinear_2eq_order1_type3(x, y, t, eq): r""" Autonomous system of general form .. math:: x' = F(x,y) .. math:: y' = G(x,y) Assuming `y = y(x, C_1)` where `C_1` is an arbitrary constant is the general solution of the first-order equation .. math:: F(x,y) y'_x = G(x,y) Then the general solution of the original system of equations has the form .. math:: \int \frac{1}{F(x,y(x,C_1))} \,dx = t + C_1 """ C1, C2, C3, C4 = get_numbered_constants(eq, num=4) v = Function('v') u = Symbol('u') f = Wild('f') g = Wild('g') r1 = eq[0].match(diff(x(t),t) - f) r2 = eq[1].match(diff(y(t),t) - g) F = r1[f].subs(x(t), u).subs(y(t), v(u)) G = r2[g].subs(x(t), u).subs(y(t), v(u)) sol2r = dsolve(Eq(diff(v(u), u), G/F)) if isinstance(sol2r, Expr): sol2r = [sol2r] for sol2s in sol2r: sol1 = solve(Integral(1/F.subs(v(u), sol2s.rhs), u).doit() - t - C2, u) sol = [] for sols in sol1: sol.append(Eq(x(t), sols)) sol.append(Eq(y(t), (sol2s.rhs).subs(u, sols))) return sol def _nonlinear_2eq_order1_type4(x, y, t, eq): r""" Equation: .. math:: x' = f_1(x) g_1(y) \phi(x,y,t) .. math:: y' = f_2(x) g_2(y) \phi(x,y,t) First integral: .. math:: \int \frac{f_2(x)}{f_1(x)} \,dx - \int \frac{g_1(y)}{g_2(y)} \,dy = C where `C` is an arbitrary constant. On solving the first integral for `x` (resp., `y` ) and on substituting the resulting expression into either equation of the original solution, one arrives at a first-order equation for determining `y` (resp., `x` ). """ C1, C2 = get_numbered_constants(eq, num=2) u, v = symbols('u, v') U, V = symbols('U, V', cls=Function) f = Wild('f') g = Wild('g') f1 = Wild('f1', exclude=[v,t]) f2 = Wild('f2', exclude=[v,t]) g1 = Wild('g1', exclude=[u,t]) g2 = Wild('g2', exclude=[u,t]) r1 = eq[0].match(diff(x(t),t) - f) r2 = eq[1].match(diff(y(t),t) - g) num, den = ( (r1[f].subs(x(t),u).subs(y(t),v))/ (r2[g].subs(x(t),u).subs(y(t),v))).as_numer_denom() R1 = num.match(f1*g1) R2 = den.match(f2*g2) phi = (r1[f].subs(x(t),u).subs(y(t),v))/num F1 = R1[f1]; F2 = R2[f2] G1 = R1[g1]; G2 = R2[g2] sol1r = solve(Integral(F2/F1, u).doit() - Integral(G1/G2,v).doit() - C1, u) sol2r = solve(Integral(F2/F1, u).doit() - Integral(G1/G2,v).doit() - C1, v) sol = [] for sols in sol1r: sol.append(Eq(y(t), dsolve(diff(V(t),t) - F2.subs(u,sols).subs(v,V(t))*G2.subs(v,V(t))*phi.subs(u,sols).subs(v,V(t))).rhs)) for sols in sol2r: sol.append(Eq(x(t), dsolve(diff(U(t),t) - F1.subs(u,U(t))*G1.subs(v,sols).subs(u,U(t))*phi.subs(v,sols).subs(u,U(t))).rhs)) return set(sol) def _nonlinear_2eq_order1_type5(func, t, eq): r""" Clairaut system of ODEs .. math:: x = t x' + F(x',y') .. math:: y = t y' + G(x',y') The following are solutions of the system `(i)` straight lines: .. math:: x = C_1 t + F(C_1, C_2), y = C_2 t + G(C_1, C_2) where `C_1` and `C_2` are arbitrary constants; `(ii)` envelopes of the above lines; `(iii)` continuously differentiable lines made up from segments of the lines `(i)` and `(ii)`. """ C1, C2 = get_numbered_constants(eq, num=2) f = Wild('f') g = Wild('g') def check_type(x, y): r1 = eq[0].match(t*diff(x(t),t) - x(t) + f) r2 = eq[1].match(t*diff(y(t),t) - y(t) + g) if not (r1 and r2): r1 = eq[0].match(diff(x(t),t) - x(t)/t + f/t) r2 = eq[1].match(diff(y(t),t) - y(t)/t + g/t) if not (r1 and r2): r1 = (-eq[0]).match(t*diff(x(t),t) - x(t) + f) r2 = (-eq[1]).match(t*diff(y(t),t) - y(t) + g) if not (r1 and r2): r1 = (-eq[0]).match(diff(x(t),t) - x(t)/t + f/t) r2 = (-eq[1]).match(diff(y(t),t) - y(t)/t + g/t) return [r1, r2] for func_ in func: if isinstance(func_, list): x = func[0][0].func y = func[0][1].func [r1, r2] = check_type(x, y) if not (r1 and r2): [r1, r2] = check_type(y, x) x, y = y, x x1 = diff(x(t),t); y1 = diff(y(t),t) return {Eq(x(t), C1*t + r1[f].subs(x1,C1).subs(y1,C2)), Eq(y(t), C2*t + r2[g].subs(x1,C1).subs(y1,C2))} def sysode_nonlinear_3eq_order1(match_): x = match_['func'][0].func y = match_['func'][1].func z = match_['func'][2].func eq = match_['eq'] t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0] if match_['type_of_equation'] == 'type1': sol = _nonlinear_3eq_order1_type1(x, y, z, t, eq) if match_['type_of_equation'] == 'type2': sol = _nonlinear_3eq_order1_type2(x, y, z, t, eq) if match_['type_of_equation'] == 'type3': sol = _nonlinear_3eq_order1_type3(x, y, z, t, eq) if match_['type_of_equation'] == 'type4': sol = _nonlinear_3eq_order1_type4(x, y, z, t, eq) if match_['type_of_equation'] == 'type5': sol = _nonlinear_3eq_order1_type5(x, y, z, t, eq) return sol def _nonlinear_3eq_order1_type1(x, y, z, t, eq): r""" Equations: .. math:: a x' = (b - c) y z, \enspace b y' = (c - a) z x, \enspace c z' = (a - b) x y First Integrals: .. math:: a x^{2} + b y^{2} + c z^{2} = C_1 .. math:: a^{2} x^{2} + b^{2} y^{2} + c^{2} z^{2} = C_2 where `C_1` and `C_2` are arbitrary constants. On solving the integrals for `y` and `z` and on substituting the resulting expressions into the first equation of the system, we arrives at a separable first-order equation on `x`. Similarly doing that for other two equations, we will arrive at first order equation on `y` and `z` too. References ========== -http://eqworld.ipmnet.ru/en/solutions/sysode/sode0401.pdf """ C1, C2 = get_numbered_constants(eq, num=2) u, v, w = symbols('u, v, w') p = Wild('p', exclude=[x(t), y(t), z(t), t]) q = Wild('q', exclude=[x(t), y(t), z(t), t]) s = Wild('s', exclude=[x(t), y(t), z(t), t]) r = (diff(x(t),t) - eq[0]).match(p*y(t)*z(t)) r.update((diff(y(t),t) - eq[1]).match(q*z(t)*x(t))) r.update((diff(z(t),t) - eq[2]).match(s*x(t)*y(t))) n1, d1 = r[p].as_numer_denom() n2, d2 = r[q].as_numer_denom() n3, d3 = r[s].as_numer_denom() val = solve([n1*u-d1*v+d1*w, d2*u+n2*v-d2*w, d3*u-d3*v-n3*w],[u,v]) vals = [val[v], val[u]] c = lcm(vals[0].as_numer_denom()[1], vals[1].as_numer_denom()[1]) b = vals[0].subs(w, c) a = vals[1].subs(w, c) y_x = sqrt(((c*C1-C2) - a*(c-a)*x(t)**2)/(b*(c-b))) z_x = sqrt(((b*C1-C2) - a*(b-a)*x(t)**2)/(c*(b-c))) z_y = sqrt(((a*C1-C2) - b*(a-b)*y(t)**2)/(c*(a-c))) x_y = sqrt(((c*C1-C2) - b*(c-b)*y(t)**2)/(a*(c-a))) x_z = sqrt(((b*C1-C2) - c*(b-c)*z(t)**2)/(a*(b-a))) y_z = sqrt(((a*C1-C2) - c*(a-c)*z(t)**2)/(b*(a-b))) sol1 = dsolve(a*diff(x(t),t) - (b-c)*y_x*z_x) sol2 = dsolve(b*diff(y(t),t) - (c-a)*z_y*x_y) sol3 = dsolve(c*diff(z(t),t) - (a-b)*x_z*y_z) return [sol1, sol2, sol3] def _nonlinear_3eq_order1_type2(x, y, z, t, eq): r""" Equations: .. math:: a x' = (b - c) y z f(x, y, z, t) .. math:: b y' = (c - a) z x f(x, y, z, t) .. math:: c z' = (a - b) x y f(x, y, z, t) First Integrals: .. math:: a x^{2} + b y^{2} + c z^{2} = C_1 .. math:: a^{2} x^{2} + b^{2} y^{2} + c^{2} z^{2} = C_2 where `C_1` and `C_2` are arbitrary constants. On solving the integrals for `y` and `z` and on substituting the resulting expressions into the first equation of the system, we arrives at a first-order differential equations on `x`. Similarly doing that for other two equations we will arrive at first order equation on `y` and `z`. References ========== -http://eqworld.ipmnet.ru/en/solutions/sysode/sode0402.pdf """ C1, C2 = get_numbered_constants(eq, num=2) u, v, w = symbols('u, v, w') p = Wild('p', exclude=[x(t), y(t), z(t), t]) q = Wild('q', exclude=[x(t), y(t), z(t), t]) s = Wild('s', exclude=[x(t), y(t), z(t), t]) f = Wild('f') r1 = (diff(x(t),t) - eq[0]).match(y(t)*z(t)*f) r = collect_const(r1[f]).match(p*f) r.update(((diff(y(t),t) - eq[1])/r[f]).match(q*z(t)*x(t))) r.update(((diff(z(t),t) - eq[2])/r[f]).match(s*x(t)*y(t))) n1, d1 = r[p].as_numer_denom() n2, d2 = r[q].as_numer_denom() n3, d3 = r[s].as_numer_denom() val = solve([n1*u-d1*v+d1*w, d2*u+n2*v-d2*w, -d3*u+d3*v+n3*w],[u,v]) vals = [val[v], val[u]] c = lcm(vals[0].as_numer_denom()[1], vals[1].as_numer_denom()[1]) a = vals[0].subs(w, c) b = vals[1].subs(w, c) y_x = sqrt(((c*C1-C2) - a*(c-a)*x(t)**2)/(b*(c-b))) z_x = sqrt(((b*C1-C2) - a*(b-a)*x(t)**2)/(c*(b-c))) z_y = sqrt(((a*C1-C2) - b*(a-b)*y(t)**2)/(c*(a-c))) x_y = sqrt(((c*C1-C2) - b*(c-b)*y(t)**2)/(a*(c-a))) x_z = sqrt(((b*C1-C2) - c*(b-c)*z(t)**2)/(a*(b-a))) y_z = sqrt(((a*C1-C2) - c*(a-c)*z(t)**2)/(b*(a-b))) sol1 = dsolve(a*diff(x(t),t) - (b-c)*y_x*z_x*r[f]) sol2 = dsolve(b*diff(y(t),t) - (c-a)*z_y*x_y*r[f]) sol3 = dsolve(c*diff(z(t),t) - (a-b)*x_z*y_z*r[f]) return [sol1, sol2, sol3] def _nonlinear_3eq_order1_type3(x, y, z, t, eq): r""" Equations: .. math:: x' = c F_2 - b F_3, \enspace y' = a F_3 - c F_1, \enspace z' = b F_1 - a F_2 where `F_n = F_n(x, y, z, t)`. 1. First Integral: .. math:: a x + b y + c z = C_1, where C is an arbitrary constant. 2. If we assume function `F_n` to be independent of `t`,i.e, `F_n` = `F_n (x, y, z)` Then, on eliminating `t` and `z` from the first two equation of the system, one arrives at the first-order equation .. math:: \frac{dy}{dx} = \frac{a F_3 (x, y, z) - c F_1 (x, y, z)}{c F_2 (x, y, z) - b F_3 (x, y, z)} where `z = \frac{1}{c} (C_1 - a x - b y)` References ========== -http://eqworld.ipmnet.ru/en/solutions/sysode/sode0404.pdf """ C1 = get_numbered_constants(eq, num=1) u, v, w = symbols('u, v, w') fu, fv, fw = symbols('u, v, w', cls=Function) p = Wild('p', exclude=[x(t), y(t), z(t), t]) q = Wild('q', exclude=[x(t), y(t), z(t), t]) s = Wild('s', exclude=[x(t), y(t), z(t), t]) F1, F2, F3 = symbols('F1, F2, F3', cls=Wild) r1 = (diff(x(t), t) - eq[0]).match(F2-F3) r = collect_const(r1[F2]).match(s*F2) r.update(collect_const(r1[F3]).match(q*F3)) if eq[1].has(r[F2]) and not eq[1].has(r[F3]): r[F2], r[F3] = r[F3], r[F2] r[s], r[q] = -r[q], -r[s] r.update((diff(y(t), t) - eq[1]).match(p*r[F3] - r[s]*F1)) a = r[p]; b = r[q]; c = r[s] F1 = r[F1].subs(x(t), u).subs(y(t),v).subs(z(t), w) F2 = r[F2].subs(x(t), u).subs(y(t),v).subs(z(t), w) F3 = r[F3].subs(x(t), u).subs(y(t),v).subs(z(t), w) z_xy = (C1-a*u-b*v)/c y_zx = (C1-a*u-c*w)/b x_yz = (C1-b*v-c*w)/a y_x = dsolve(diff(fv(u),u) - ((a*F3-c*F1)/(c*F2-b*F3)).subs(w,z_xy).subs(v,fv(u))).rhs z_x = dsolve(diff(fw(u),u) - ((b*F1-a*F2)/(c*F2-b*F3)).subs(v,y_zx).subs(w,fw(u))).rhs z_y = dsolve(diff(fw(v),v) - ((b*F1-a*F2)/(a*F3-c*F1)).subs(u,x_yz).subs(w,fw(v))).rhs x_y = dsolve(diff(fu(v),v) - ((c*F2-b*F3)/(a*F3-c*F1)).subs(w,z_xy).subs(u,fu(v))).rhs y_z = dsolve(diff(fv(w),w) - ((a*F3-c*F1)/(b*F1-a*F2)).subs(u,x_yz).subs(v,fv(w))).rhs x_z = dsolve(diff(fu(w),w) - ((c*F2-b*F3)/(b*F1-a*F2)).subs(v,y_zx).subs(u,fu(w))).rhs sol1 = dsolve(diff(fu(t),t) - (c*F2 - b*F3).subs(v,y_x).subs(w,z_x).subs(u,fu(t))).rhs sol2 = dsolve(diff(fv(t),t) - (a*F3 - c*F1).subs(u,x_y).subs(w,z_y).subs(v,fv(t))).rhs sol3 = dsolve(diff(fw(t),t) - (b*F1 - a*F2).subs(u,x_z).subs(v,y_z).subs(w,fw(t))).rhs return [sol1, sol2, sol3] def _nonlinear_3eq_order1_type4(x, y, z, t, eq): r""" Equations: .. math:: x' = c z F_2 - b y F_3, \enspace y' = a x F_3 - c z F_1, \enspace z' = b y F_1 - a x F_2 where `F_n = F_n (x, y, z, t)` 1. First integral: .. math:: a x^{2} + b y^{2} + c z^{2} = C_1 where `C` is an arbitrary constant. 2. Assuming the function `F_n` is independent of `t`: `F_n = F_n (x, y, z)`. Then on eliminating `t` and `z` from the first two equations of the system, one arrives at the first-order equation .. math:: \frac{dy}{dx} = \frac{a x F_3 (x, y, z) - c z F_1 (x, y, z)} {c z F_2 (x, y, z) - b y F_3 (x, y, z)} where `z = \pm \sqrt{\frac{1}{c} (C_1 - a x^{2} - b y^{2})}` References ========== -http://eqworld.ipmnet.ru/en/solutions/sysode/sode0405.pdf """ C1 = get_numbered_constants(eq, num=1) u, v, w = symbols('u, v, w') p = Wild('p', exclude=[x(t), y(t), z(t), t]) q = Wild('q', exclude=[x(t), y(t), z(t), t]) s = Wild('s', exclude=[x(t), y(t), z(t), t]) F1, F2, F3 = symbols('F1, F2, F3', cls=Wild) r1 = eq[0].match(diff(x(t),t) - z(t)*F2 + y(t)*F3) r = collect_const(r1[F2]).match(s*F2) r.update(collect_const(r1[F3]).match(q*F3)) if eq[1].has(r[F2]) and not eq[1].has(r[F3]): r[F2], r[F3] = r[F3], r[F2] r[s], r[q] = -r[q], -r[s] r.update((diff(y(t),t) - eq[1]).match(p*x(t)*r[F3] - r[s]*z(t)*F1)) a = r[p]; b = r[q]; c = r[s] F1 = r[F1].subs(x(t),u).subs(y(t),v).subs(z(t),w) F2 = r[F2].subs(x(t),u).subs(y(t),v).subs(z(t),w) F3 = r[F3].subs(x(t),u).subs(y(t),v).subs(z(t),w) x_yz = sqrt((C1 - b*v**2 - c*w**2)/a) y_zx = sqrt((C1 - c*w**2 - a*u**2)/b) z_xy = sqrt((C1 - a*u**2 - b*v**2)/c) y_x = dsolve(diff(v(u),u) - ((a*u*F3-c*w*F1)/(c*w*F2-b*v*F3)).subs(w,z_xy).subs(v,v(u))).rhs z_x = dsolve(diff(w(u),u) - ((b*v*F1-a*u*F2)/(c*w*F2-b*v*F3)).subs(v,y_zx).subs(w,w(u))).rhs z_y = dsolve(diff(w(v),v) - ((b*v*F1-a*u*F2)/(a*u*F3-c*w*F1)).subs(u,x_yz).subs(w,w(v))).rhs x_y = dsolve(diff(u(v),v) - ((c*w*F2-b*v*F3)/(a*u*F3-c*w*F1)).subs(w,z_xy).subs(u,u(v))).rhs y_z = dsolve(diff(v(w),w) - ((a*u*F3-c*w*F1)/(b*v*F1-a*u*F2)).subs(u,x_yz).subs(v,v(w))).rhs x_z = dsolve(diff(u(w),w) - ((c*w*F2-b*v*F3)/(b*v*F1-a*u*F2)).subs(v,y_zx).subs(u,u(w))).rhs sol1 = dsolve(diff(u(t),t) - (c*w*F2 - b*v*F3).subs(v,y_x).subs(w,z_x).subs(u,u(t))).rhs sol2 = dsolve(diff(v(t),t) - (a*u*F3 - c*w*F1).subs(u,x_y).subs(w,z_y).subs(v,v(t))).rhs sol3 = dsolve(diff(w(t),t) - (b*v*F1 - a*u*F2).subs(u,x_z).subs(v,y_z).subs(w,w(t))).rhs return [sol1, sol2, sol3] def _nonlinear_3eq_order1_type5(x, y, z, t, eq): r""" .. math:: x' = x (c F_2 - b F_3), \enspace y' = y (a F_3 - c F_1), \enspace z' = z (b F_1 - a F_2) where `F_n = F_n (x, y, z, t)` and are arbitrary functions. First Integral: .. math:: \left|x\right|^{a} \left|y\right|^{b} \left|z\right|^{c} = C_1 where `C` is an arbitrary constant. If the function `F_n` is independent of `t`, then, by eliminating `t` and `z` from the first two equations of the system, one arrives at a first-order equation. References ========== -http://eqworld.ipmnet.ru/en/solutions/sysode/sode0406.pdf """ C1 = get_numbered_constants(eq, num=1) u, v, w = symbols('u, v, w') fu, fv, fw = symbols('u, v, w', cls=Function) p = Wild('p', exclude=[x(t), y(t), z(t), t]) q = Wild('q', exclude=[x(t), y(t), z(t), t]) s = Wild('s', exclude=[x(t), y(t), z(t), t]) F1, F2, F3 = symbols('F1, F2, F3', cls=Wild) r1 = eq[0].match(diff(x(t), t) - x(t)*F2 + x(t)*F3) r = collect_const(r1[F2]).match(s*F2) r.update(collect_const(r1[F3]).match(q*F3)) if eq[1].has(r[F2]) and not eq[1].has(r[F3]): r[F2], r[F3] = r[F3], r[F2] r[s], r[q] = -r[q], -r[s] r.update((diff(y(t), t) - eq[1]).match(y(t)*(p*r[F3] - r[s]*F1))) a = r[p]; b = r[q]; c = r[s] F1 = r[F1].subs(x(t), u).subs(y(t), v).subs(z(t), w) F2 = r[F2].subs(x(t), u).subs(y(t), v).subs(z(t), w) F3 = r[F3].subs(x(t), u).subs(y(t), v).subs(z(t), w) x_yz = (C1*v**-b*w**-c)**-a y_zx = (C1*w**-c*u**-a)**-b z_xy = (C1*u**-a*v**-b)**-c y_x = dsolve(diff(fv(u), u) - ((v*(a*F3 - c*F1))/(u*(c*F2 - b*F3))).subs(w, z_xy).subs(v, fv(u))).rhs z_x = dsolve(diff(fw(u), u) - ((w*(b*F1 - a*F2))/(u*(c*F2 - b*F3))).subs(v, y_zx).subs(w, fw(u))).rhs z_y = dsolve(diff(fw(v), v) - ((w*(b*F1 - a*F2))/(v*(a*F3 - c*F1))).subs(u, x_yz).subs(w, fw(v))).rhs x_y = dsolve(diff(fu(v), v) - ((u*(c*F2 - b*F3))/(v*(a*F3 - c*F1))).subs(w, z_xy).subs(u, fu(v))).rhs y_z = dsolve(diff(fv(w), w) - ((v*(a*F3 - c*F1))/(w*(b*F1 - a*F2))).subs(u, x_yz).subs(v, fv(w))).rhs x_z = dsolve(diff(fu(w), w) - ((u*(c*F2 - b*F3))/(w*(b*F1 - a*F2))).subs(v, y_zx).subs(u, fu(w))).rhs sol1 = dsolve(diff(fu(t), t) - (u*(c*F2 - b*F3)).subs(v, y_x).subs(w, z_x).subs(u, fu(t))).rhs sol2 = dsolve(diff(fv(t), t) - (v*(a*F3 - c*F1)).subs(u, x_y).subs(w, z_y).subs(v, fv(t))).rhs sol3 = dsolve(diff(fw(t), t) - (w*(b*F1 - a*F2)).subs(u, x_z).subs(v, y_z).subs(w, fw(t))).rhs return [sol1, sol2, sol3]
143b320ae9ca52f73e1ae87820fa325f4af5ca7e0e56dbbfe9109d81d8dd71f8
from .ode import (allhints, checkinfsol, classify_ode, constantsimp, dsolve, homogeneous_order, infinitesimals) from .subscheck import checkodesol __all__ = [ 'allhints', 'checkinfsol', 'checkodesol', 'classify_ode', 'constantsimp', 'dsolve', 'homogeneous_order', 'infinitesimals', ]
2eb21b4c938c597ebf13a9801538ecae2dbb6f088a8697b4fd5c9342abdeb440
from sympy.core import S, Pow from sympy.core.compatibility import iterable, is_sequence from sympy.core.function import (Derivative, AppliedUndef, diff) from sympy.core.relational import Equality, Eq from sympy.core.symbol import Dummy from sympy.core.sympify import sympify from sympy.logic.boolalg import BooleanAtom from sympy.functions import exp from sympy.series import Order from sympy.simplify import (simplify, trigsimp, posify, besselsimp) # type: ignore from sympy.solvers import solve from sympy.solvers.deutils import _preprocess, ode_order def sub_func_doit(eq, func, new): r""" When replacing the func with something else, we usually want the derivative evaluated, so this function helps in making that happen. Examples ======== >>> from sympy import Derivative, symbols, Function >>> from sympy.solvers.ode.ode import sub_func_doit >>> x, z = symbols('x, z') >>> y = Function('y') >>> sub_func_doit(3*Derivative(y(x), x) - 1, y(x), x) 2 >>> sub_func_doit(x*Derivative(y(x), x) - y(x)**2 + y(x), y(x), ... 1/(x*(z + 1/x))) x*(-1/(x**2*(z + 1/x)) + 1/(x**3*(z + 1/x)**2)) + 1/(x*(z + 1/x)) ...- 1/(x**2*(z + 1/x)**2) """ reps= {func: new} for d in eq.atoms(Derivative): if d.expr == func: reps[d] = new.diff(*d.variable_count) else: reps[d] = d.xreplace({func: new}).doit(deep=False) return eq.xreplace(reps) def checkodesol(ode, sol, func=None, order='auto', solve_for_func=True): r""" Substitutes ``sol`` into ``ode`` and checks that the result is ``0``. This only works when ``func`` is one function, like `f(x)`. ``sol`` can be a single solution or a list of solutions. Each solution may be an :py:class:`~sympy.core.relational.Equality` that the solution satisfies, e.g. ``Eq(f(x), C1), Eq(f(x) + C1, 0)``; or simply an :py:class:`~sympy.core.expr.Expr`, e.g. ``f(x) - C1``. In most cases it will not be necessary to explicitly identify the function, but if the function cannot be inferred from the original equation it can be supplied through the ``func`` argument. If a sequence of solutions is passed, the same sort of container will be used to return the result for each solution. It tries the following methods, in order, until it finds zero equivalence: 1. Substitute the solution for `f` in the original equation. This only works if ``ode`` is solved for `f`. It will attempt to solve it first unless ``solve_for_func == False``. 2. Take `n` derivatives of the solution, where `n` is the order of ``ode``, and check to see if that is equal to the solution. This only works on exact ODEs. 3. Take the 1st, 2nd, ..., `n`\th derivatives of the solution, each time solving for the derivative of `f` of that order (this will always be possible because `f` is a linear operator). Then back substitute each derivative into ``ode`` in reverse order. This function returns a tuple. The first item in the tuple is ``True`` if the substitution results in ``0``, and ``False`` otherwise. The second item in the tuple is what the substitution results in. It should always be ``0`` if the first item is ``True``. Sometimes this function will return ``False`` even when an expression is identically equal to ``0``. This happens when :py:meth:`~sympy.simplify.simplify.simplify` does not reduce the expression to ``0``. If an expression returned by this function vanishes identically, then ``sol`` really is a solution to the ``ode``. If this function seems to hang, it is probably because of a hard simplification. To use this function to test, test the first item of the tuple. Examples ======== >>> from sympy import Eq, Function, checkodesol, symbols >>> x, C1 = symbols('x,C1') >>> f = Function('f') >>> checkodesol(f(x).diff(x), Eq(f(x), C1)) (True, 0) >>> assert checkodesol(f(x).diff(x), C1)[0] >>> assert not checkodesol(f(x).diff(x), x)[0] >>> checkodesol(f(x).diff(x, 2), x**2) (False, 2) """ if not isinstance(ode, Equality): ode = Eq(ode, 0) if func is None: try: _, func = _preprocess(ode.lhs) except ValueError: funcs = [s.atoms(AppliedUndef) for s in ( sol if is_sequence(sol, set) else [sol])] funcs = set().union(*funcs) if len(funcs) != 1: raise ValueError( 'must pass func arg to checkodesol for this case.') func = funcs.pop() if not isinstance(func, AppliedUndef) or len(func.args) != 1: raise ValueError( "func must be a function of one variable, not %s" % func) if is_sequence(sol, set): return type(sol)([checkodesol(ode, i, order=order, solve_for_func=solve_for_func) for i in sol]) if not isinstance(sol, Equality): sol = Eq(func, sol) elif sol.rhs == func: sol = sol.reversed if order == 'auto': order = ode_order(ode, func) solved = sol.lhs == func and not sol.rhs.has(func) if solve_for_func and not solved: rhs = solve(sol, func) if rhs: eqs = [Eq(func, t) for t in rhs] if len(rhs) == 1: eqs = eqs[0] return checkodesol(ode, eqs, order=order, solve_for_func=False) x = func.args[0] # Handle series solutions here if sol.has(Order): assert sol.lhs == func Oterm = sol.rhs.getO() solrhs = sol.rhs.removeO() Oexpr = Oterm.expr assert isinstance(Oexpr, Pow) sorder = Oexpr.exp assert Oterm == Order(x**sorder) odesubs = (ode.lhs-ode.rhs).subs(func, solrhs).doit().expand() neworder = Order(x**(sorder - order)) odesubs = odesubs + neworder assert odesubs.getO() == neworder residual = odesubs.removeO() return (residual == 0, residual) s = True testnum = 0 while s: if testnum == 0: # First pass, try substituting a solved solution directly into the # ODE. This has the highest chance of succeeding. ode_diff = ode.lhs - ode.rhs if sol.lhs == func: s = sub_func_doit(ode_diff, func, sol.rhs) s = besselsimp(s) else: testnum += 1 continue ss = simplify(s.rewrite(exp)) if ss: # with the new numer_denom in power.py, if we do a simple # expansion then testnum == 0 verifies all solutions. s = ss.expand(force=True) else: s = 0 testnum += 1 elif testnum == 1: # Second pass. If we cannot substitute f, try seeing if the nth # derivative is equal, this will only work for odes that are exact, # by definition. s = simplify( trigsimp(diff(sol.lhs, x, order) - diff(sol.rhs, x, order)) - trigsimp(ode.lhs) + trigsimp(ode.rhs)) # s2 = simplify( # diff(sol.lhs, x, order) - diff(sol.rhs, x, order) - \ # ode.lhs + ode.rhs) testnum += 1 elif testnum == 2: # Third pass. Try solving for df/dx and substituting that into the # ODE. Thanks to Chris Smith for suggesting this method. Many of # the comments below are his, too. # The method: # - Take each of 1..n derivatives of the solution. # - Solve each nth derivative for d^(n)f/dx^(n) # (the differential of that order) # - Back substitute into the ODE in decreasing order # (i.e., n, n-1, ...) # - Check the result for zero equivalence if sol.lhs == func and not sol.rhs.has(func): diffsols = {0: sol.rhs} elif sol.rhs == func and not sol.lhs.has(func): diffsols = {0: sol.lhs} else: diffsols = {} sol = sol.lhs - sol.rhs for i in range(1, order + 1): # Differentiation is a linear operator, so there should always # be 1 solution. Nonetheless, we test just to make sure. # We only need to solve once. After that, we automatically # have the solution to the differential in the order we want. if i == 1: ds = sol.diff(x) try: sdf = solve(ds, func.diff(x, i)) if not sdf: raise NotImplementedError except NotImplementedError: testnum += 1 break else: diffsols[i] = sdf[0] else: # This is what the solution says df/dx should be. diffsols[i] = diffsols[i - 1].diff(x) # Make sure the above didn't fail. if testnum > 2: continue else: # Substitute it into ODE to check for self consistency. lhs, rhs = ode.lhs, ode.rhs for i in range(order, -1, -1): if i == 0 and 0 not in diffsols: # We can only substitute f(x) if the solution was # solved for f(x). break lhs = sub_func_doit(lhs, func.diff(x, i), diffsols[i]) rhs = sub_func_doit(rhs, func.diff(x, i), diffsols[i]) ode_or_bool = Eq(lhs, rhs) ode_or_bool = simplify(ode_or_bool) if isinstance(ode_or_bool, (bool, BooleanAtom)): if ode_or_bool: lhs = rhs = S.Zero else: lhs = ode_or_bool.lhs rhs = ode_or_bool.rhs # No sense in overworking simplify -- just prove that the # numerator goes to zero num = trigsimp((lhs - rhs).as_numer_denom()[0]) # since solutions are obtained using force=True we test # using the same level of assumptions ## replace function with dummy so assumptions will work _func = Dummy('func') num = num.subs(func, _func) ## posify the expression num, reps = posify(num) s = simplify(num).xreplace(reps).xreplace({_func: func}) testnum += 1 else: break if not s: return (True, s) elif s is True: # The code above never was able to change s raise NotImplementedError("Unable to test if " + str(sol) + " is a solution to " + str(ode) + ".") else: return (False, s) def checksysodesol(eqs, sols, func=None): r""" Substitutes corresponding ``sols`` for each functions into each ``eqs`` and checks that the result of substitutions for each equation is ``0``. The equations and solutions passed can be any iterable. This only works when each ``sols`` have one function only, like `x(t)` or `y(t)`. For each function, ``sols`` can have a single solution or a list of solutions. In most cases it will not be necessary to explicitly identify the function, but if the function cannot be inferred from the original equation it can be supplied through the ``func`` argument. When a sequence of equations is passed, the same sequence is used to return the result for each equation with each function substituted with corresponding solutions. It tries the following method to find zero equivalence for each equation: Substitute the solutions for functions, like `x(t)` and `y(t)` into the original equations containing those functions. This function returns a tuple. The first item in the tuple is ``True`` if the substitution results for each equation is ``0``, and ``False`` otherwise. The second item in the tuple is what the substitution results in. Each element of the ``list`` should always be ``0`` corresponding to each equation if the first item is ``True``. Note that sometimes this function may return ``False``, but with an expression that is identically equal to ``0``, instead of returning ``True``. This is because :py:meth:`~sympy.simplify.simplify.simplify` cannot reduce the expression to ``0``. If an expression returned by each function vanishes identically, then ``sols`` really is a solution to ``eqs``. If this function seems to hang, it is probably because of a difficult simplification. Examples ======== >>> from sympy import Eq, diff, symbols, sin, cos, exp, sqrt, S, Function >>> from sympy.solvers.ode.subscheck import checksysodesol >>> C1, C2 = symbols('C1:3') >>> t = symbols('t') >>> x, y = symbols('x, y', cls=Function) >>> eq = (Eq(diff(x(t),t), x(t) + y(t) + 17), Eq(diff(y(t),t), -2*x(t) + y(t) + 12)) >>> sol = [Eq(x(t), (C1*sin(sqrt(2)*t) + C2*cos(sqrt(2)*t))*exp(t) - S(5)/3), ... Eq(y(t), (sqrt(2)*C1*cos(sqrt(2)*t) - sqrt(2)*C2*sin(sqrt(2)*t))*exp(t) - S(46)/3)] >>> checksysodesol(eq, sol) (True, [0, 0]) >>> eq = (Eq(diff(x(t),t),x(t)*y(t)**4), Eq(diff(y(t),t),y(t)**3)) >>> sol = [Eq(x(t), C1*exp(-1/(4*(C2 + t)))), Eq(y(t), -sqrt(2)*sqrt(-1/(C2 + t))/2), ... Eq(x(t), C1*exp(-1/(4*(C2 + t)))), Eq(y(t), sqrt(2)*sqrt(-1/(C2 + t))/2)] >>> checksysodesol(eq, sol) (True, [0, 0]) """ def _sympify(eq): return list(map(sympify, eq if iterable(eq) else [eq])) eqs = _sympify(eqs) for i in range(len(eqs)): if isinstance(eqs[i], Equality): eqs[i] = eqs[i].lhs - eqs[i].rhs if func is None: funcs = [] for eq in eqs: derivs = eq.atoms(Derivative) func = set().union(*[d.atoms(AppliedUndef) for d in derivs]) for func_ in func: funcs.append(func_) funcs = list(set(funcs)) if not all(isinstance(func, AppliedUndef) and len(func.args) == 1 for func in funcs)\ and len({func.args for func in funcs})!=1: raise ValueError("func must be a function of one variable, not %s" % func) for sol in sols: if len(sol.atoms(AppliedUndef)) != 1: raise ValueError("solutions should have one function only") if len(funcs) != len({sol.lhs for sol in sols}): raise ValueError("number of solutions provided does not match the number of equations") dictsol = dict() for sol in sols: func = list(sol.atoms(AppliedUndef))[0] if sol.rhs == func: sol = sol.reversed solved = sol.lhs == func and not sol.rhs.has(func) if not solved: rhs = solve(sol, func) if not rhs: raise NotImplementedError else: rhs = sol.rhs dictsol[func] = rhs checkeq = [] for eq in eqs: for func in funcs: eq = sub_func_doit(eq, func, dictsol[func]) ss = simplify(eq) if ss != 0: eq = ss.expand(force=True) else: eq = 0 checkeq.append(eq) if len(set(checkeq)) == 1 and list(set(checkeq))[0] == 0: return (True, checkeq) else: return (False, checkeq)
ce148659a4cb64ddc7ab6966095b79594f9a2b1b40e66702355a11083d94c8b6
from sympy.core.containers import Tuple from sympy.core.function import (Function, Lambda, nfloat, diff) from sympy.core.mod import Mod from sympy.core.numbers import (E, I, Rational, oo, pi) from sympy.core.relational import (Eq, Gt, Ne) from sympy.core.singleton import S from sympy.core.symbol import (Dummy, Symbol, symbols) from sympy.functions.elementary.complexes import (Abs, arg, im, re, sign) from sympy.functions.elementary.exponential import (LambertW, exp, log) from sympy.functions.elementary.hyperbolic import (HyperbolicFunction, sinh, tanh, cosh, sech, coth) from sympy.functions.elementary.miscellaneous import sqrt, Min, Max from sympy.functions.elementary.piecewise import Piecewise from sympy.functions.elementary.trigonometric import ( TrigonometricFunction, acos, acot, acsc, asec, asin, atan, atan2, cos, cot, csc, sec, sin, tan) from sympy.functions.special.error_functions import (erf, erfc, erfcinv, erfinv) from sympy.logic.boolalg import And from sympy.matrices.dense import MutableDenseMatrix as Matrix from sympy.matrices.immutable import ImmutableDenseMatrix from sympy.polys.polytools import Poly from sympy.polys.rootoftools import CRootOf from sympy.sets.contains import Contains from sympy.sets.conditionset import ConditionSet from sympy.sets.fancysets import ImageSet from sympy.sets.sets import (Complement, EmptySet, FiniteSet, Intersection, Interval, Union, imageset, ProductSet) from sympy.tensor.indexed import Indexed from sympy.utilities.iterables import numbered_symbols from sympy.testing.pytest import (XFAIL, raises, skip, slow, SKIP, nocache_fail) from sympy.testing.randtest import verify_numerically as tn from sympy.physics.units import cm from sympy.solvers.solveset import ( solveset_real, domain_check, solveset_complex, linear_eq_to_matrix, linsolve, _is_function_class_equation, invert_real, invert_complex, solveset, solve_decomposition, substitution, nonlinsolve, solvify, _is_finite_with_finite_vars, _transolve, _is_exponential, _solve_exponential, _is_logarithmic, _solve_logarithm, _term_factors, _is_modular) a = Symbol('a', real=True) b = Symbol('b', real=True) c = Symbol('c', real=True) x = Symbol('x', real=True) y = Symbol('y', real=True) z = Symbol('z', real=True) q = Symbol('q', real=True) m = Symbol('m', real=True) n = Symbol('n', real=True) def test_invert_real(): x = Symbol('x', real=True) y = Symbol('y') n = Symbol('n') def ireal(x, s=S.Reals): return Intersection(s, x) # issue 14223 assert invert_real(x, 0, x, Interval(1, 2)) == (x, S.EmptySet) assert invert_real(exp(x), y, x) == (x, ireal(FiniteSet(log(y)))) y = Symbol('y', positive=True) n = Symbol('n', real=True) assert invert_real(x + 3, y, x) == (x, FiniteSet(y - 3)) assert invert_real(x*3, y, x) == (x, FiniteSet(y / 3)) assert invert_real(exp(x), y, x) == (x, FiniteSet(log(y))) assert invert_real(exp(3*x), y, x) == (x, FiniteSet(log(y) / 3)) assert invert_real(exp(x + 3), y, x) == (x, FiniteSet(log(y) - 3)) assert invert_real(exp(x) + 3, y, x) == (x, ireal(FiniteSet(log(y - 3)))) assert invert_real(exp(x)*3, y, x) == (x, FiniteSet(log(y / 3))) assert invert_real(log(x), y, x) == (x, FiniteSet(exp(y))) assert invert_real(log(3*x), y, x) == (x, FiniteSet(exp(y) / 3)) assert invert_real(log(x + 3), y, x) == (x, FiniteSet(exp(y) - 3)) assert invert_real(Abs(x), y, x) == (x, FiniteSet(y, -y)) assert invert_real(2**x, y, x) == (x, FiniteSet(log(y)/log(2))) assert invert_real(2**exp(x), y, x) == (x, ireal(FiniteSet(log(log(y)/log(2))))) assert invert_real(x**2, y, x) == (x, FiniteSet(sqrt(y), -sqrt(y))) assert invert_real(x**S.Half, y, x) == (x, FiniteSet(y**2)) raises(ValueError, lambda: invert_real(x, x, x)) raises(ValueError, lambda: invert_real(x**pi, y, x)) raises(ValueError, lambda: invert_real(S.One, y, x)) assert invert_real(x**31 + x, y, x) == (x**31 + x, FiniteSet(y)) lhs = x**31 + x base_values = FiniteSet(y - 1, -y - 1) assert invert_real(Abs(x**31 + x + 1), y, x) == (lhs, base_values) assert invert_real(sin(x), y, x) == \ (x, imageset(Lambda(n, n*pi + (-1)**n*asin(y)), S.Integers)) assert invert_real(sin(exp(x)), y, x) == \ (x, imageset(Lambda(n, log((-1)**n*asin(y) + n*pi)), S.Integers)) assert invert_real(csc(x), y, x) == \ (x, imageset(Lambda(n, n*pi + (-1)**n*acsc(y)), S.Integers)) assert invert_real(csc(exp(x)), y, x) == \ (x, imageset(Lambda(n, log((-1)**n*acsc(y) + n*pi)), S.Integers)) assert invert_real(cos(x), y, x) == \ (x, Union(imageset(Lambda(n, 2*n*pi + acos(y)), S.Integers), \ imageset(Lambda(n, 2*n*pi - acos(y)), S.Integers))) assert invert_real(cos(exp(x)), y, x) == \ (x, Union(imageset(Lambda(n, log(2*n*pi + acos(y))), S.Integers), \ imageset(Lambda(n, log(2*n*pi - acos(y))), S.Integers))) assert invert_real(sec(x), y, x) == \ (x, Union(imageset(Lambda(n, 2*n*pi + asec(y)), S.Integers), \ imageset(Lambda(n, 2*n*pi - asec(y)), S.Integers))) assert invert_real(sec(exp(x)), y, x) == \ (x, Union(imageset(Lambda(n, log(2*n*pi + asec(y))), S.Integers), \ imageset(Lambda(n, log(2*n*pi - asec(y))), S.Integers))) assert invert_real(tan(x), y, x) == \ (x, imageset(Lambda(n, n*pi + atan(y)), S.Integers)) assert invert_real(tan(exp(x)), y, x) == \ (x, imageset(Lambda(n, log(n*pi + atan(y))), S.Integers)) assert invert_real(cot(x), y, x) == \ (x, imageset(Lambda(n, n*pi + acot(y)), S.Integers)) assert invert_real(cot(exp(x)), y, x) == \ (x, imageset(Lambda(n, log(n*pi + acot(y))), S.Integers)) assert invert_real(tan(tan(x)), y, x) == \ (tan(x), imageset(Lambda(n, n*pi + atan(y)), S.Integers)) x = Symbol('x', positive=True) assert invert_real(x**pi, y, x) == (x, FiniteSet(y**(1/pi))) def test_invert_complex(): assert invert_complex(x + 3, y, x) == (x, FiniteSet(y - 3)) assert invert_complex(x*3, y, x) == (x, FiniteSet(y / 3)) assert invert_complex(exp(x), y, x) == \ (x, imageset(Lambda(n, I*(2*pi*n + arg(y)) + log(Abs(y))), S.Integers)) assert invert_complex(log(x), y, x) == (x, FiniteSet(exp(y))) raises(ValueError, lambda: invert_real(1, y, x)) raises(ValueError, lambda: invert_complex(x, x, x)) raises(ValueError, lambda: invert_complex(x, x, 1)) # https://github.com/skirpichev/omg/issues/16 assert invert_complex(sinh(x), 0, x) != (x, FiniteSet(0)) def test_domain_check(): assert domain_check(1/(1 + (1/(x+1))**2), x, -1) is False assert domain_check(x**2, x, 0) is True assert domain_check(x, x, oo) is False assert domain_check(0, x, oo) is False def test_issue_11536(): assert solveset(0**x - 100, x, S.Reals) == S.EmptySet assert solveset(0**x - 1, x, S.Reals) == FiniteSet(0) def test_issue_17479(): x, y, z = symbols("x, y, z") f = (x**2 + y**2)**2 + (x**2 + z**2)**2 - 2*(2*x**2 + y**2 + z**2) fx = diff(f, x) fy = diff(f, y) fz = diff(f, z) sol = nonlinsolve([fx, fy, fz], [x, y, z]) assert len(sol) >= 4 and len(sol) <= 20 # nonlinsolve has been giving a varying number of solutions # (originally 18, then 20, now 19) due to various internal changes. # Unfortunately not all the solutions are actually valid and some are # redundant. Since the original issue was that an exception was raised, # this first test only checks that nonlinsolve returns a "plausible" # solution set. The next test checks the result for correctness. @XFAIL def test_issue_18449(): x, y, z = symbols("x, y, z") f = (x**2 + y**2)**2 + (x**2 + z**2)**2 - 2*(2*x**2 + y**2 + z**2) fx = diff(f, x) fy = diff(f, y) fz = diff(f, z) sol = nonlinsolve([fx, fy, fz], [x, y, z]) for (xs, ys, zs) in sol: d = {x: xs, y: ys, z: zs} assert tuple(_.subs(d).simplify() for _ in (fx, fy, fz)) == (0, 0, 0) # After simplification and removal of duplicate elements, there should # only be 4 parametric solutions left: # simplifiedsolutions = FiniteSet((sqrt(1 - z**2), z, z), # (-sqrt(1 - z**2), z, z), # (sqrt(1 - z**2), -z, z), # (-sqrt(1 - z**2), -z, z)) # TODO: Is the above solution set definitely complete? def test_is_function_class_equation(): from sympy.abc import x, a assert _is_function_class_equation(TrigonometricFunction, tan(x), x) is True assert _is_function_class_equation(TrigonometricFunction, tan(x) - 1, x) is True assert _is_function_class_equation(TrigonometricFunction, tan(x) + sin(x), x) is True assert _is_function_class_equation(TrigonometricFunction, tan(x) + sin(x) - a, x) is True assert _is_function_class_equation(TrigonometricFunction, sin(x)*tan(x) + sin(x), x) is True assert _is_function_class_equation(TrigonometricFunction, sin(x)*tan(x + a) + sin(x), x) is True assert _is_function_class_equation(TrigonometricFunction, sin(x)*tan(x*a) + sin(x), x) is True assert _is_function_class_equation(TrigonometricFunction, a*tan(x) - 1, x) is True assert _is_function_class_equation(TrigonometricFunction, tan(x)**2 + sin(x) - 1, x) is True assert _is_function_class_equation(TrigonometricFunction, tan(x) + x, x) is False assert _is_function_class_equation(TrigonometricFunction, tan(x**2), x) is False assert _is_function_class_equation(TrigonometricFunction, tan(x**2) + sin(x), x) is False assert _is_function_class_equation(TrigonometricFunction, tan(x)**sin(x), x) is False assert _is_function_class_equation(TrigonometricFunction, tan(sin(x)) + sin(x), x) is False assert _is_function_class_equation(HyperbolicFunction, tanh(x), x) is True assert _is_function_class_equation(HyperbolicFunction, tanh(x) - 1, x) is True assert _is_function_class_equation(HyperbolicFunction, tanh(x) + sinh(x), x) is True assert _is_function_class_equation(HyperbolicFunction, tanh(x) + sinh(x) - a, x) is True assert _is_function_class_equation(HyperbolicFunction, sinh(x)*tanh(x) + sinh(x), x) is True assert _is_function_class_equation(HyperbolicFunction, sinh(x)*tanh(x + a) + sinh(x), x) is True assert _is_function_class_equation(HyperbolicFunction, sinh(x)*tanh(x*a) + sinh(x), x) is True assert _is_function_class_equation(HyperbolicFunction, a*tanh(x) - 1, x) is True assert _is_function_class_equation(HyperbolicFunction, tanh(x)**2 + sinh(x) - 1, x) is True assert _is_function_class_equation(HyperbolicFunction, tanh(x) + x, x) is False assert _is_function_class_equation(HyperbolicFunction, tanh(x**2), x) is False assert _is_function_class_equation(HyperbolicFunction, tanh(x**2) + sinh(x), x) is False assert _is_function_class_equation(HyperbolicFunction, tanh(x)**sinh(x), x) is False assert _is_function_class_equation(HyperbolicFunction, tanh(sinh(x)) + sinh(x), x) is False def test_garbage_input(): raises(ValueError, lambda: solveset_real([x], x)) assert solveset_real(x, 1) == S.EmptySet assert solveset_real(x - 1, 1) == FiniteSet(x) assert solveset_real(x, pi) == S.EmptySet assert solveset_real(x, x**2) == S.EmptySet raises(ValueError, lambda: solveset_complex([x], x)) assert solveset_complex(x, pi) == S.EmptySet raises(ValueError, lambda: solveset((x, y), x)) raises(ValueError, lambda: solveset(x + 1, S.Reals)) raises(ValueError, lambda: solveset(x + 1, x, 2)) def test_solve_mul(): assert solveset_real((a*x + b)*(exp(x) - 3), x) == \ Union({log(3)}, Intersection({-b/a}, S.Reals)) anz = Symbol('anz', nonzero=True) assert solveset_real((anz*x + b)*(exp(x) - 3), x) == \ FiniteSet(-b/anz, log(3)) assert solveset_real((2*x + 8)*(8 + exp(x)), x) == FiniteSet(S(-4)) assert solveset_real(x/log(x), x) == EmptySet() def test_solve_invert(): assert solveset_real(exp(x) - 3, x) == FiniteSet(log(3)) assert solveset_real(log(x) - 3, x) == FiniteSet(exp(3)) assert solveset_real(3**(x + 2), x) == FiniteSet() assert solveset_real(3**(2 - x), x) == FiniteSet() assert solveset_real(y - b*exp(a/x), x) == Intersection( S.Reals, FiniteSet(a/log(y/b))) # issue 4504 assert solveset_real(2**x - 10, x) == FiniteSet(1 + log(5)/log(2)) def test_errorinverses(): assert solveset_real(erf(x) - S.Half, x) == \ FiniteSet(erfinv(S.Half)) assert solveset_real(erfinv(x) - 2, x) == \ FiniteSet(erf(2)) assert solveset_real(erfc(x) - S.One, x) == \ FiniteSet(erfcinv(S.One)) assert solveset_real(erfcinv(x) - 2, x) == FiniteSet(erfc(2)) def test_solve_polynomial(): assert solveset_real(3*x - 2, x) == FiniteSet(Rational(2, 3)) assert solveset_real(x**2 - 1, x) == FiniteSet(-S.One, S.One) assert solveset_real(x - y**3, x) == FiniteSet(y ** 3) a11, a12, a21, a22, b1, b2 = symbols('a11, a12, a21, a22, b1, b2') assert solveset_real(x**3 - 15*x - 4, x) == FiniteSet( -2 + 3 ** S.Half, S(4), -2 - 3 ** S.Half) assert solveset_real(sqrt(x) - 1, x) == FiniteSet(1) assert solveset_real(sqrt(x) - 2, x) == FiniteSet(4) assert solveset_real(x**Rational(1, 4) - 2, x) == FiniteSet(16) assert solveset_real(x**Rational(1, 3) - 3, x) == FiniteSet(27) assert len(solveset_real(x**5 + x**3 + 1, x)) == 1 assert len(solveset_real(-2*x**3 + 4*x**2 - 2*x + 6, x)) > 0 assert solveset_real(x**6 + x**4 + I, x) == ConditionSet(x, Eq(x**6 + x**4 + I, 0), S.Reals) def test_return_root_of(): f = x**5 - 15*x**3 - 5*x**2 + 10*x + 20 s = list(solveset_complex(f, x)) for root in s: assert root.func == CRootOf # if one uses solve to get the roots of a polynomial that has a CRootOf # solution, make sure that the use of nfloat during the solve process # doesn't fail. Note: if you want numerical solutions to a polynomial # it is *much* faster to use nroots to get them than to solve the # equation only to get CRootOf solutions which are then numerically # evaluated. So for eq = x**5 + 3*x + 7 do Poly(eq).nroots() rather # than [i.n() for i in solve(eq)] to get the numerical roots of eq. assert nfloat(list(solveset_complex(x**5 + 3*x**3 + 7, x))[0], exponent=False) == CRootOf(x**5 + 3*x**3 + 7, 0).n() sol = list(solveset_complex(x**6 - 2*x + 2, x)) assert all(isinstance(i, CRootOf) for i in sol) and len(sol) == 6 f = x**5 - 15*x**3 - 5*x**2 + 10*x + 20 s = list(solveset_complex(f, x)) for root in s: assert root.func == CRootOf s = x**5 + 4*x**3 + 3*x**2 + Rational(7, 4) assert solveset_complex(s, x) == \ FiniteSet(*Poly(s*4, domain='ZZ').all_roots()) # Refer issue #7876 eq = x*(x - 1)**2*(x + 1)*(x**6 - x + 1) assert solveset_complex(eq, x) == \ FiniteSet(-1, 0, 1, CRootOf(x**6 - x + 1, 0), CRootOf(x**6 - x + 1, 1), CRootOf(x**6 - x + 1, 2), CRootOf(x**6 - x + 1, 3), CRootOf(x**6 - x + 1, 4), CRootOf(x**6 - x + 1, 5)) def test__has_rational_power(): from sympy.solvers.solveset import _has_rational_power assert _has_rational_power(sqrt(2), x)[0] is False assert _has_rational_power(x*sqrt(2), x)[0] is False assert _has_rational_power(x**2*sqrt(x), x) == (True, 2) assert _has_rational_power(sqrt(2)*x**Rational(1, 3), x) == (True, 3) assert _has_rational_power(sqrt(x)*x**Rational(1, 3), x) == (True, 6) def test_solveset_sqrt_1(): assert solveset_real(sqrt(5*x + 6) - 2 - x, x) == \ FiniteSet(-S.One, S(2)) assert solveset_real(sqrt(x - 1) - x + 7, x) == FiniteSet(10) assert solveset_real(sqrt(x - 2) - 5, x) == FiniteSet(27) assert solveset_real(sqrt(x) - 2 - 5, x) == FiniteSet(49) assert solveset_real(sqrt(x**3), x) == FiniteSet(0) assert solveset_real(sqrt(x - 1), x) == FiniteSet(1) def test_solveset_sqrt_2(): # http://tutorial.math.lamar.edu/Classes/Alg/SolveRadicalEqns.aspx#Solve_Rad_Ex2_a assert solveset_real(sqrt(2*x - 1) - sqrt(x - 4) - 2, x) == \ FiniteSet(S(5), S(13)) assert solveset_real(sqrt(x + 7) + 2 - sqrt(3 - x), x) == \ FiniteSet(-6) # http://www.purplemath.com/modules/solverad.htm assert solveset_real(sqrt(17*x - sqrt(x**2 - 5)) - 7, x) == \ FiniteSet(3) eq = x + 1 - (x**4 + 4*x**3 - x)**Rational(1, 4) assert solveset_real(eq, x) == FiniteSet(Rational(-1, 2), Rational(-1, 3)) eq = sqrt(2*x + 9) - sqrt(x + 1) - sqrt(x + 4) assert solveset_real(eq, x) == FiniteSet(0) eq = sqrt(x + 4) + sqrt(2*x - 1) - 3*sqrt(x - 1) assert solveset_real(eq, x) == FiniteSet(5) eq = sqrt(x)*sqrt(x - 7) - 12 assert solveset_real(eq, x) == FiniteSet(16) eq = sqrt(x - 3) + sqrt(x) - 3 assert solveset_real(eq, x) == FiniteSet(4) eq = sqrt(2*x**2 - 7) - (3 - x) assert solveset_real(eq, x) == FiniteSet(-S(8), S(2)) # others eq = sqrt(9*x**2 + 4) - (3*x + 2) assert solveset_real(eq, x) == FiniteSet(0) assert solveset_real(sqrt(x - 3) - sqrt(x) - 3, x) == FiniteSet() eq = (2*x - 5)**Rational(1, 3) - 3 assert solveset_real(eq, x) == FiniteSet(16) assert solveset_real(sqrt(x) + sqrt(sqrt(x)) - 4, x) == \ FiniteSet((Rational(-1, 2) + sqrt(17)/2)**4) eq = sqrt(x) - sqrt(x - 1) + sqrt(sqrt(x)) assert solveset_real(eq, x) == FiniteSet() eq = (sqrt(x) + sqrt(x + 1) + sqrt(1 - x) - 6*sqrt(5)/5) ans = solveset_real(eq, x) ra = S('''-1484/375 - 4*(-1/2 + sqrt(3)*I/2)*(-12459439/52734375 + 114*sqrt(12657)/78125)**(1/3) - 172564/(140625*(-1/2 + sqrt(3)*I/2)*(-12459439/52734375 + 114*sqrt(12657)/78125)**(1/3))''') rb = Rational(4, 5) assert all(abs(eq.subs(x, i).n()) < 1e-10 for i in (ra, rb)) and \ len(ans) == 2 and \ set([i.n(chop=True) for i in ans]) == \ set([i.n(chop=True) for i in (ra, rb)]) assert solveset_real(sqrt(x) + x**Rational(1, 3) + x**Rational(1, 4), x) == FiniteSet(0) assert solveset_real(x/sqrt(x**2 + 1), x) == FiniteSet(0) eq = (x - y**3)/((y**2)*sqrt(1 - y**2)) assert solveset_real(eq, x) == FiniteSet(y**3) # issue 4497 assert solveset_real(1/(5 + x)**Rational(1, 5) - 9, x) == \ FiniteSet(Rational(-295244, 59049)) @XFAIL def test_solve_sqrt_fail(): # this only works if we check real_root(eq.subs(x, Rational(1, 3))) # but checksol doesn't work like that eq = (x**3 - 3*x**2)**Rational(1, 3) + 1 - x assert solveset_real(eq, x) == FiniteSet(Rational(1, 3)) @slow def test_solve_sqrt_3(): R = Symbol('R') eq = sqrt(2)*R*sqrt(1/(R + 1)) + (R + 1)*(sqrt(2)*sqrt(1/(R + 1)) - 1) sol = solveset_complex(eq, R) fset = [Rational(5, 3) + 4*sqrt(10)*cos(atan(3*sqrt(111)/251)/3)/3, -sqrt(10)*cos(atan(3*sqrt(111)/251)/3)/3 + 40*re(1/((Rational(-1, 2) - sqrt(3)*I/2)*(Rational(251, 27) + sqrt(111)*I/9)**Rational(1, 3)))/9 + sqrt(30)*sin(atan(3*sqrt(111)/251)/3)/3 + Rational(5, 3) + I*(-sqrt(30)*cos(atan(3*sqrt(111)/251)/3)/3 - sqrt(10)*sin(atan(3*sqrt(111)/251)/3)/3 + 40*im(1/((Rational(-1, 2) - sqrt(3)*I/2)*(Rational(251, 27) + sqrt(111)*I/9)**Rational(1, 3)))/9)] cset = [40*re(1/((Rational(-1, 2) + sqrt(3)*I/2)*(Rational(251, 27) + sqrt(111)*I/9)**Rational(1, 3)))/9 - sqrt(10)*cos(atan(3*sqrt(111)/251)/3)/3 - sqrt(30)*sin(atan(3*sqrt(111)/251)/3)/3 + Rational(5, 3) + I*(40*im(1/((Rational(-1, 2) + sqrt(3)*I/2)*(Rational(251, 27) + sqrt(111)*I/9)**Rational(1, 3)))/9 - sqrt(10)*sin(atan(3*sqrt(111)/251)/3)/3 + sqrt(30)*cos(atan(3*sqrt(111)/251)/3)/3)] assert sol._args[0] == FiniteSet(*fset) assert sol._args[1] == ConditionSet( R, Eq(sqrt(2)*R*sqrt(1/(R + 1)) + (R + 1)*(sqrt(2)*sqrt(1/(R + 1)) - 1), 0), FiniteSet(*cset)) # the number of real roots will depend on the value of m: for m=1 there are 4 # and for m=-1 there are none. eq = -sqrt((m - q)**2 + (-m/(2*q) + S.Half)**2) + sqrt((-m**2/2 - sqrt( 4*m**4 - 4*m**2 + 8*m + 1)/4 - Rational(1, 4))**2 + (m**2/2 - m - sqrt( 4*m**4 - 4*m**2 + 8*m + 1)/4 - Rational(1, 4))**2) unsolved_object = ConditionSet(q, Eq(sqrt((m - q)**2 + (-m/(2*q) + S.Half)**2) - sqrt((-m**2/2 - sqrt(4*m**4 - 4*m**2 + 8*m + 1)/4 - Rational(1, 4))**2 + (m**2/2 - m - sqrt(4*m**4 - 4*m**2 + 8*m + 1)/4 - Rational(1, 4))**2), 0), S.Reals) assert solveset_real(eq, q) == unsolved_object def test_solve_polynomial_symbolic_param(): assert solveset_complex((x**2 - 1)**2 - a, x) == \ FiniteSet(sqrt(1 + sqrt(a)), -sqrt(1 + sqrt(a)), sqrt(1 - sqrt(a)), -sqrt(1 - sqrt(a))) # issue 4507 assert solveset_complex(y - b/(1 + a*x), x) == \ FiniteSet((b/y - 1)/a) - FiniteSet(-1/a) # issue 4508 assert solveset_complex(y - b*x/(a + x), x) == \ FiniteSet(-a*y/(y - b)) - FiniteSet(-a) def test_solve_rational(): assert solveset_real(1/x + 1, x) == FiniteSet(-S.One) assert solveset_real(1/exp(x) - 1, x) == FiniteSet(0) assert solveset_real(x*(1 - 5/x), x) == FiniteSet(5) assert solveset_real(2*x/(x + 2) - 1, x) == FiniteSet(2) assert solveset_real((x**2/(7 - x)).diff(x), x) == \ FiniteSet(S.Zero, S(14)) def test_solveset_real_gen_is_pow(): assert solveset_real(sqrt(1) + 1, x) == EmptySet() def test_no_sol(): assert solveset(1 - oo*x) == EmptySet() assert solveset(oo*x, x) == EmptySet() assert solveset(oo*x - oo, x) == EmptySet() assert solveset_real(4, x) == EmptySet() assert solveset_real(exp(x), x) == EmptySet() assert solveset_real(x**2 + 1, x) == EmptySet() assert solveset_real(-3*a/sqrt(x), x) == EmptySet() assert solveset_real(1/x, x) == EmptySet() assert solveset_real(-(1 + x)/(2 + x)**2 + 1/(2 + x), x) == \ EmptySet() def test_sol_zero_real(): assert solveset_real(0, x) == S.Reals assert solveset(0, x, Interval(1, 2)) == Interval(1, 2) assert solveset_real(-x**2 - 2*x + (x + 1)**2 - 1, x) == S.Reals def test_no_sol_rational_extragenous(): assert solveset_real((x/(x + 1) + 3)**(-2), x) == EmptySet() assert solveset_real((x - 1)/(1 + 1/(x - 1)), x) == EmptySet() def test_solve_polynomial_cv_1a(): """ Test for solving on equations that can be converted to a polynomial equation using the change of variable y -> x**Rational(p, q) """ assert solveset_real(sqrt(x) - 1, x) == FiniteSet(1) assert solveset_real(sqrt(x) - 2, x) == FiniteSet(4) assert solveset_real(x**Rational(1, 4) - 2, x) == FiniteSet(16) assert solveset_real(x**Rational(1, 3) - 3, x) == FiniteSet(27) assert solveset_real(x*(x**(S.One / 3) - 3), x) == \ FiniteSet(S.Zero, S(27)) def test_solveset_real_rational(): """Test solveset_real for rational functions""" assert solveset_real((x - y**3) / ((y**2)*sqrt(1 - y**2)), x) \ == FiniteSet(y**3) # issue 4486 assert solveset_real(2*x/(x + 2) - 1, x) == FiniteSet(2) def test_solveset_real_log(): assert solveset_real(log((x-1)*(x+1)), x) == \ FiniteSet(sqrt(2), -sqrt(2)) def test_poly_gens(): assert solveset_real(4**(2*(x**2) + 2*x) - 8, x) == \ FiniteSet(Rational(-3, 2), S.Half) def test_solve_abs(): x = Symbol('x') n = Dummy('n') raises(ValueError, lambda: solveset(Abs(x) - 1, x)) assert solveset(Abs(x) - n, x, S.Reals) == ConditionSet(x, Contains(n, Interval(0, oo)), {-n, n}) assert solveset_real(Abs(x) - 2, x) == FiniteSet(-2, 2) assert solveset_real(Abs(x) + 2, x) is S.EmptySet assert solveset_real(Abs(x + 3) - 2*Abs(x - 3), x) == \ FiniteSet(1, 9) assert solveset_real(2*Abs(x) - Abs(x - 1), x) == \ FiniteSet(-1, Rational(1, 3)) sol = ConditionSet( x, And( Contains(b, Interval(0, oo)), Contains(a + b, Interval(0, oo)), Contains(a - b, Interval(0, oo))), FiniteSet(-a - b - 3, -a + b - 3, a - b - 3, a + b - 3)) eq = Abs(Abs(x + 3) - a) - b assert invert_real(eq, 0, x)[1] == sol reps = {a: 3, b: 1} eqab = eq.subs(reps) for i in sol.subs(reps): assert not eqab.subs(x, i) assert solveset(Eq(sin(Abs(x)), 1), x, domain=S.Reals) == Union( Intersection(Interval(0, oo), ImageSet(Lambda(n, (-1)**n*pi/2 + n*pi), S.Integers)), Intersection(Interval(-oo, 0), ImageSet(Lambda(n, n*pi - (-1)**(-n)*pi/2), S.Integers))) def test_issue_9824(): assert solveset(sin(x)**2 - 2*sin(x) + 1, x) == ImageSet(Lambda(n, 2*n*pi + pi/2), S.Integers) assert solveset(cos(x)**2 - 2*cos(x) + 1, x) == ImageSet(Lambda(n, 2*n*pi), S.Integers) def test_issue_9565(): assert solveset_real(Abs((x - 1)/(x - 5)) <= Rational(1, 3), x) == Interval(-1, 2) def test_issue_10069(): eq = abs(1/(x - 1)) - 1 > 0 u = Union(Interval.open(0, 1), Interval.open(1, 2)) assert solveset_real(eq, x) == u def test_real_imag_splitting(): a, b = symbols('a b', real=True) assert solveset_real(sqrt(a**2 - b**2) - 3, a) == \ FiniteSet(-sqrt(b**2 + 9), sqrt(b**2 + 9)) assert solveset_real(sqrt(a**2 + b**2) - 3, a) != \ S.EmptySet def test_units(): assert solveset_real(1/x - 1/(2*cm), x) == FiniteSet(2*cm) def test_solve_only_exp_1(): y = Symbol('y', positive=True) assert solveset_real(exp(x) - y, x) == FiniteSet(log(y)) assert solveset_real(exp(x) + exp(-x) - 4, x) == \ FiniteSet(log(-sqrt(3) + 2), log(sqrt(3) + 2)) assert solveset_real(exp(x) + exp(-x) - y, x) != S.EmptySet def test_atan2(): # The .inverse() method on atan2 works only if x.is_real is True and the # second argument is a real constant assert solveset_real(atan2(x, 2) - pi/3, x) == FiniteSet(2*sqrt(3)) def test_piecewise_solveset(): eq = Piecewise((x - 2, Gt(x, 2)), (2 - x, True)) - 3 assert set(solveset_real(eq, x)) == set(FiniteSet(-1, 5)) absxm3 = Piecewise( (x - 3, 0 <= x - 3), (3 - x, 0 > x - 3)) y = Symbol('y', positive=True) assert solveset_real(absxm3 - y, x) == FiniteSet(-y + 3, y + 3) f = Piecewise(((x - 2)**2, x >= 0), (0, True)) assert solveset(f, x, domain=S.Reals) == Union(FiniteSet(2), Interval(-oo, 0, True, True)) assert solveset( Piecewise((x + 1, x > 0), (I, True)) - I, x, S.Reals ) == Interval(-oo, 0) assert solveset(Piecewise((x - 1, Ne(x, I)), (x, True)), x) == FiniteSet(1) def test_solveset_complex_polynomial(): from sympy.abc import x, a, b, c assert solveset_complex(a*x**2 + b*x + c, x) == \ FiniteSet(-b/(2*a) - sqrt(-4*a*c + b**2)/(2*a), -b/(2*a) + sqrt(-4*a*c + b**2)/(2*a)) assert solveset_complex(x - y**3, y) == FiniteSet( (-x**Rational(1, 3))/2 + I*sqrt(3)*x**Rational(1, 3)/2, x**Rational(1, 3), (-x**Rational(1, 3))/2 - I*sqrt(3)*x**Rational(1, 3)/2) assert solveset_complex(x + 1/x - 1, x) == \ FiniteSet(S.Half + I*sqrt(3)/2, S.Half - I*sqrt(3)/2) def test_sol_zero_complex(): assert solveset_complex(0, x) == S.Complexes def test_solveset_complex_rational(): assert solveset_complex((x - 1)*(x - I)/(x - 3), x) == \ FiniteSet(1, I) assert solveset_complex((x - y**3)/((y**2)*sqrt(1 - y**2)), x) == \ FiniteSet(y**3) assert solveset_complex(-x**2 - I, x) == \ FiniteSet(-sqrt(2)/2 + sqrt(2)*I/2, sqrt(2)/2 - sqrt(2)*I/2) def test_solve_quintics(): skip("This test is too slow") f = x**5 - 110*x**3 - 55*x**2 + 2310*x + 979 s = solveset_complex(f, x) for root in s: res = f.subs(x, root.n()).n() assert tn(res, 0) f = x**5 + 15*x + 12 s = solveset_complex(f, x) for root in s: res = f.subs(x, root.n()).n() assert tn(res, 0) def test_solveset_complex_exp(): from sympy.abc import x, n assert solveset_complex(exp(x) - 1, x) == \ imageset(Lambda(n, I*2*n*pi), S.Integers) assert solveset_complex(exp(x) - I, x) == \ imageset(Lambda(n, I*(2*n*pi + pi/2)), S.Integers) assert solveset_complex(1/exp(x), x) == S.EmptySet assert solveset_complex(sinh(x).rewrite(exp), x) == \ imageset(Lambda(n, n*pi*I), S.Integers) def test_solveset_real_exp(): from sympy.abc import x, y assert solveset(Eq((-2)**x, 4), x, S.Reals) == FiniteSet(2) assert solveset(Eq(-2**x, 4), x, S.Reals) == S.EmptySet assert solveset(Eq((-3)**x, 27), x, S.Reals) == S.EmptySet assert solveset(Eq((-5)**(x+1), 625), x, S.Reals) == FiniteSet(3) assert solveset(Eq(2**(x-3), -16), x, S.Reals) == S.EmptySet assert solveset(Eq((-3)**(x - 3), -3**39), x, S.Reals) == FiniteSet(42) assert solveset(Eq(2**x, y), x, S.Reals) == Intersection(S.Reals, FiniteSet(log(y)/log(2))) assert invert_real((-2)**(2*x) - 16, 0, x) == (x, FiniteSet(2)) def test_solve_complex_log(): assert solveset_complex(log(x), x) == FiniteSet(1) assert solveset_complex(1 - log(a + 4*x**2), x) == \ FiniteSet(-sqrt(-a + E)/2, sqrt(-a + E)/2) def test_solve_complex_sqrt(): assert solveset_complex(sqrt(5*x + 6) - 2 - x, x) == \ FiniteSet(-S.One, S(2)) assert solveset_complex(sqrt(5*x + 6) - (2 + 2*I) - x, x) == \ FiniteSet(-S(2), 3 - 4*I) assert solveset_complex(4*x*(1 - a * sqrt(x)), x) == \ FiniteSet(S.Zero, 1 / a ** 2) def test_solveset_complex_tan(): s = solveset_complex(tan(x).rewrite(exp), x) assert s == imageset(Lambda(n, pi*n), S.Integers) - \ imageset(Lambda(n, pi*n + pi/2), S.Integers) @nocache_fail def test_solve_trig(): from sympy.abc import n assert solveset_real(sin(x), x) == \ Union(imageset(Lambda(n, 2*pi*n), S.Integers), imageset(Lambda(n, 2*pi*n + pi), S.Integers)) assert solveset_real(sin(x) - 1, x) == \ imageset(Lambda(n, 2*pi*n + pi/2), S.Integers) assert solveset_real(cos(x), x) == \ Union(imageset(Lambda(n, 2*pi*n + pi/2), S.Integers), imageset(Lambda(n, 2*pi*n + pi*Rational(3, 2)), S.Integers)) assert solveset_real(sin(x) + cos(x), x) == \ Union(imageset(Lambda(n, 2*n*pi + pi*Rational(3, 4)), S.Integers), imageset(Lambda(n, 2*n*pi + pi*Rational(7, 4)), S.Integers)) assert solveset_real(sin(x)**2 + cos(x)**2, x) == S.EmptySet # This fails when running with the cache off: assert solveset_complex(cos(x) - S.Half, x) == \ Union(imageset(Lambda(n, 2*n*pi + pi*Rational(5, 3)), S.Integers), imageset(Lambda(n, 2*n*pi + pi/3), S.Integers)) y, a = symbols('y,a') assert solveset(sin(y + a) - sin(y), a, domain=S.Reals) == \ Union(ImageSet(Lambda(n, 2*n*pi), S.Integers), Intersection(ImageSet(Lambda(n, -I*(I*( 2*n*pi + arg(-exp(-2*I*y))) + 2*im(y))), S.Integers), S.Reals)) assert solveset_real(sin(2*x)*cos(x) + cos(2*x)*sin(x)-1, x) == \ ImageSet(Lambda(n, n*pi*Rational(2, 3) + pi/6), S.Integers) # Tests for _solve_trig2() function assert solveset_real(2*cos(x)*cos(2*x) - 1, x) == \ Union(ImageSet(Lambda(n, 2*n*pi + 2*atan(sqrt(-2*2**Rational(1, 3)*(67 + 9*sqrt(57))**Rational(2, 3) + 8*2**Rational(2, 3) + 11*(67 + 9*sqrt(57))**Rational(1, 3))/(3*(67 + 9*sqrt(57))**Rational(1, 6)))), S.Integers), ImageSet(Lambda(n, 2*n*pi - 2*atan(sqrt(-2*2**Rational(1, 3)*(67 + 9*sqrt(57))**Rational(2, 3) + 8*2**Rational(2, 3) + 11*(67 + 9*sqrt(57))**Rational(1, 3))/(3*(67 + 9*sqrt(57))**Rational(1, 6))) + 2*pi), S.Integers)) assert solveset_real(2*tan(x)*sin(x) + 1, x) == Union( ImageSet(Lambda(n, 2*n*pi + atan(sqrt(2)*sqrt(-1 +sqrt(17))/ (1 - sqrt(17))) + pi), S.Integers), ImageSet(Lambda(n, 2*n*pi - atan(sqrt(2)*sqrt(-1 + sqrt(17))/ (1 - sqrt(17))) + pi), S.Integers)) assert solveset_real(cos(2*x)*cos(4*x) - 1, x) == \ ImageSet(Lambda(n, n*pi), S.Integers) def test_solve_hyperbolic(): # actual solver: _solve_trig1 n = Dummy('n') assert solveset(sinh(x) + cosh(x), x) == S.EmptySet assert solveset(sinh(x) + cos(x), x) == ConditionSet(x, Eq(cos(x) + sinh(x), 0), S.Complexes) assert solveset_real(sinh(x) + sech(x), x) == FiniteSet( log(sqrt(sqrt(5) - 2))) assert solveset_real(3*cosh(2*x) - 5, x) == FiniteSet( log(sqrt(3)/3), log(sqrt(3))) assert solveset_real(sinh(x - 3) - 2, x) == FiniteSet( log((2 + sqrt(5))*exp(3))) assert solveset_real(cosh(2*x) + 2*sinh(x) - 5, x) == FiniteSet( log(-2 + sqrt(5)), log(1 + sqrt(2))) assert solveset_real((coth(x) + sinh(2*x))/cosh(x) - 3, x) == FiniteSet( log(S.Half + sqrt(5)/2), log(1 + sqrt(2))) assert solveset_real(cosh(x)*sinh(x) - 2, x) == FiniteSet( log(sqrt(4 + sqrt(17)))) assert solveset_real(sinh(x) + tanh(x) - 1, x) == FiniteSet( log(sqrt(2)/2 + sqrt(-S(1)/2 + sqrt(2)))) assert solveset_complex(sinh(x) - I/2, x) == Union( ImageSet(Lambda(n, I*(2*n*pi + 5*pi/6)), S.Integers), ImageSet(Lambda(n, I*(2*n*pi + pi/6)), S.Integers)) assert solveset_complex(sinh(x) + sech(x), x) == Union( ImageSet(Lambda(n, 2*n*I*pi + log(sqrt(-2 + sqrt(5)))), S.Integers), ImageSet(Lambda(n, I*(2*n*pi + pi/2) + log(sqrt(2 + sqrt(5)))), S.Integers), ImageSet(Lambda(n, I*(2*n*pi + pi) + log(sqrt(-2 + sqrt(5)))), S.Integers), ImageSet(Lambda(n, I*(2*n*pi - pi/2) + log(sqrt(2 + sqrt(5)))), S.Integers)) # issues #9606 / #9531: assert solveset(sinh(x), x, S.Reals) == FiniteSet(0) assert solveset(sinh(x), x, S.Complexes) == Union( ImageSet(Lambda(n, I*(2*n*pi + pi)), S.Integers), ImageSet(Lambda(n, 2*n*I*pi), S.Integers)) def test_solve_invalid_sol(): assert 0 not in solveset_real(sin(x)/x, x) assert 0 not in solveset_complex((exp(x) - 1)/x, x) @XFAIL def test_solve_trig_simplified(): from sympy.abc import n assert solveset_real(sin(x), x) == \ imageset(Lambda(n, n*pi), S.Integers) assert solveset_real(cos(x), x) == \ imageset(Lambda(n, n*pi + pi/2), S.Integers) assert solveset_real(cos(x) + sin(x), x) == \ imageset(Lambda(n, n*pi - pi/4), S.Integers) @XFAIL def test_solve_lambert(): assert solveset_real(x*exp(x) - 1, x) == FiniteSet(LambertW(1)) assert solveset_real(exp(x) + x, x) == FiniteSet(-LambertW(1)) assert solveset_real(x + 2**x, x) == \ FiniteSet(-LambertW(log(2))/log(2)) # issue 4739 ans = solveset_real(3*x + 5 + 2**(-5*x + 3), x) assert ans == FiniteSet(Rational(-5, 3) + LambertW(-10240*2**Rational(1, 3)*log(2)/3)/(5*log(2))) eq = 2*(3*x + 4)**5 - 6*7**(3*x + 9) result = solveset_real(eq, x) ans = FiniteSet((log(2401) + 5*LambertW(-log(7**(7*3**Rational(1, 5)/5))))/(3*log(7))/-1) assert result == ans assert solveset_real(eq.expand(), x) == result assert solveset_real(5*x - 1 + 3*exp(2 - 7*x), x) == \ FiniteSet(Rational(1, 5) + LambertW(-21*exp(Rational(3, 5))/5)/7) assert solveset_real(2*x + 5 + log(3*x - 2), x) == \ FiniteSet(Rational(2, 3) + LambertW(2*exp(Rational(-19, 3))/3)/2) assert solveset_real(3*x + log(4*x), x) == \ FiniteSet(LambertW(Rational(3, 4))/3) assert solveset_real(x**x - 2) == FiniteSet(exp(LambertW(log(2)))) a = Symbol('a') assert solveset_real(-a*x + 2*x*log(x), x) == FiniteSet(exp(a/2)) a = Symbol('a', real=True) assert solveset_real(a/x + exp(x/2), x) == \ FiniteSet(2*LambertW(-a/2)) assert solveset_real((a/x + exp(x/2)).diff(x), x) == \ FiniteSet(4*LambertW(sqrt(2)*sqrt(a)/4)) # coverage test assert solveset_real(tanh(x + 3)*tanh(x - 3) - 1, x) == EmptySet() assert solveset_real((x**2 - 2*x + 1).subs(x, log(x) + 3*x), x) == \ FiniteSet(LambertW(3*S.Exp1)/3) assert solveset_real((x**2 - 2*x + 1).subs(x, (log(x) + 3*x)**2 - 1), x) == \ FiniteSet(LambertW(3*exp(-sqrt(2)))/3, LambertW(3*exp(sqrt(2)))/3) assert solveset_real((x**2 - 2*x - 2).subs(x, log(x) + 3*x), x) == \ FiniteSet(LambertW(3*exp(1 + sqrt(3)))/3, LambertW(3*exp(-sqrt(3) + 1))/3) assert solveset_real(x*log(x) + 3*x + 1, x) == \ FiniteSet(exp(-3 + LambertW(-exp(3)))) eq = (x*exp(x) - 3).subs(x, x*exp(x)) assert solveset_real(eq, x) == \ FiniteSet(LambertW(3*exp(-LambertW(3)))) assert solveset_real(3*log(a**(3*x + 5)) + a**(3*x + 5), x) == \ FiniteSet(-((log(a**5) + LambertW(Rational(1, 3)))/(3*log(a)))) p = symbols('p', positive=True) assert solveset_real(3*log(p**(3*x + 5)) + p**(3*x + 5), x) == \ FiniteSet( log((-3**Rational(1, 3) - 3**Rational(5, 6)*I)*LambertW(Rational(1, 3))**Rational(1, 3)/(2*p**Rational(5, 3)))/log(p), log((-3**Rational(1, 3) + 3**Rational(5, 6)*I)*LambertW(Rational(1, 3))**Rational(1, 3)/(2*p**Rational(5, 3)))/log(p), log((3*LambertW(Rational(1, 3))/p**5)**(1/(3*log(p)))),) # checked numerically # check collection b = Symbol('b') eq = 3*log(a**(3*x + 5)) + b*log(a**(3*x + 5)) + a**(3*x + 5) assert solveset_real(eq, x) == FiniteSet( -((log(a**5) + LambertW(1/(b + 3)))/(3*log(a)))) # issue 4271 assert solveset_real((a/x + exp(x/2)).diff(x, 2), x) == FiniteSet( 6*LambertW((-1)**Rational(1, 3)*a**Rational(1, 3)/3)) assert solveset_real(x**3 - 3**x, x) == \ FiniteSet(-3/log(3)*LambertW(-log(3)/3)) assert solveset_real(3**cos(x) - cos(x)**3) == FiniteSet( acos(-3*LambertW(-log(3)/3)/log(3))) assert solveset_real(x**2 - 2**x, x) == \ solveset_real(-x**2 + 2**x, x) assert solveset_real(3*log(x) - x*log(3)) == FiniteSet( -3*LambertW(-log(3)/3)/log(3), -3*LambertW(-log(3)/3, -1)/log(3)) assert solveset_real(LambertW(2*x) - y) == FiniteSet( y*exp(y)/2) @XFAIL def test_other_lambert(): a = Rational(6, 5) assert solveset_real(x**a - a**x, x) == FiniteSet( a, -a*LambertW(-log(a)/a)/log(a)) def test_solveset(): x = Symbol('x') f = Function('f') raises(ValueError, lambda: solveset(x + y)) assert solveset(x, 1) == S.EmptySet assert solveset(f(1)**2 + y + 1, f(1) ) == FiniteSet(-sqrt(-y - 1), sqrt(-y - 1)) assert solveset(f(1)**2 - 1, f(1), S.Reals) == FiniteSet(-1, 1) assert solveset(f(1)**2 + 1, f(1)) == FiniteSet(-I, I) assert solveset(x - 1, 1) == FiniteSet(x) assert solveset(sin(x) - cos(x), sin(x)) == FiniteSet(cos(x)) assert solveset(0, domain=S.Reals) == S.Reals assert solveset(1) == S.EmptySet assert solveset(True, domain=S.Reals) == S.Reals # issue 10197 assert solveset(False, domain=S.Reals) == S.EmptySet assert solveset(exp(x) - 1, domain=S.Reals) == FiniteSet(0) assert solveset(exp(x) - 1, x, S.Reals) == FiniteSet(0) assert solveset(Eq(exp(x), 1), x, S.Reals) == FiniteSet(0) assert solveset(exp(x) - 1, exp(x), S.Reals) == FiniteSet(1) A = Indexed('A', x) assert solveset(A - 1, A, S.Reals) == FiniteSet(1) assert solveset(x - 1 >= 0, x, S.Reals) == Interval(1, oo) assert solveset(exp(x) - 1 >= 0, x, S.Reals) == Interval(0, oo) assert solveset(exp(x) - 1, x) == imageset(Lambda(n, 2*I*pi*n), S.Integers) assert solveset(Eq(exp(x), 1), x) == imageset(Lambda(n, 2*I*pi*n), S.Integers) # issue 13825 assert solveset(x**2 + f(0) + 1, x) == {-sqrt(-f(0) - 1), sqrt(-f(0) - 1)} def test__solveset_multi(): from sympy.solvers.solveset import _solveset_multi from sympy import Reals # Basic univariate case: from sympy.abc import x assert _solveset_multi([x**2-1], [x], [S.Reals]) == FiniteSet((1,), (-1,)) # Linear systems of two equations from sympy.abc import x, y assert _solveset_multi([x+y, x+1], [x, y], [Reals, Reals]) == FiniteSet((-1, 1)) assert _solveset_multi([x+y, x+1], [y, x], [Reals, Reals]) == FiniteSet((1, -1)) assert _solveset_multi([x+y, x-y-1], [x, y], [Reals, Reals]) == FiniteSet((S(1)/2, -S(1)/2)) assert _solveset_multi([x-1, y-2], [x, y], [Reals, Reals]) == FiniteSet((1, 2)) #assert _solveset_multi([x+y], [x, y], [Reals, Reals]) == ImageSet(Lambda(x, (x, -x)), Reals) assert _solveset_multi([x+y], [x, y], [Reals, Reals]) == Union( ImageSet(Lambda(((x,),), (x, -x)), ProductSet(Reals)), ImageSet(Lambda(((y,),), (-y, y)), ProductSet(Reals))) assert _solveset_multi([x+y, x+y+1], [x, y], [Reals, Reals]) == S.EmptySet assert _solveset_multi([x+y, x-y, x-1], [x, y], [Reals, Reals]) == S.EmptySet assert _solveset_multi([x+y, x-y, x-1], [y, x], [Reals, Reals]) == S.EmptySet # Systems of three equations: from sympy.abc import x, y, z assert _solveset_multi([x+y+z-1, x+y-z-2, x-y-z-3], [x, y, z], [Reals, Reals, Reals]) == FiniteSet((2, -S.Half, -S.Half)) # Nonlinear systems: from sympy.abc import r, theta, z, x, y assert _solveset_multi([x**2+y**2-2, x+y], [x, y], [Reals, Reals]) == FiniteSet((-1, 1), (1, -1)) assert _solveset_multi([x**2-1, y], [x, y], [Reals, Reals]) == FiniteSet((1, 0), (-1, 0)) #assert _solveset_multi([x**2-y**2], [x, y], [Reals, Reals]) == Union( # ImageSet(Lambda(x, (x, -x)), Reals), ImageSet(Lambda(x, (x, x)), Reals)) assert _solveset_multi([x**2-y**2], [x, y], [Reals, Reals]) == Union( ImageSet(Lambda(((x,),), (x, -Abs(x))), ProductSet(Reals)), ImageSet(Lambda(((x,),), (x, Abs(x))), ProductSet(Reals)), ImageSet(Lambda(((y,),), (-Abs(y), y)), ProductSet(Reals)), ImageSet(Lambda(((y,),), (Abs(y), y)), ProductSet(Reals))) assert _solveset_multi([r*cos(theta)-1, r*sin(theta)], [theta, r], [Interval(0, pi), Interval(-1, 1)]) == FiniteSet((0, 1), (pi, -1)) assert _solveset_multi([r*cos(theta)-1, r*sin(theta)], [r, theta], [Interval(0, 1), Interval(0, pi)]) == FiniteSet((1, 0)) #assert _solveset_multi([r*cos(theta)-r, r*sin(theta)], [r, theta], # [Interval(0, 1), Interval(0, pi)]) == ? assert _solveset_multi([r*cos(theta)-r, r*sin(theta)], [r, theta], [Interval(0, 1), Interval(0, pi)]) == Union( ImageSet(Lambda(((r,),), (r, 0)), ImageSet(Lambda(r, (r,)), Interval(0, 1))), ImageSet(Lambda(((theta,),), (0, theta)), ImageSet(Lambda(theta, (theta,)), Interval(0, pi)))) def test_conditionset(): assert solveset(Eq(sin(x)**2 + cos(x)**2, 1), x, domain=S.Reals) == \ ConditionSet(x, True, S.Reals) assert solveset(Eq(x**2 + x*sin(x), 1), x, domain=S.Reals ) == ConditionSet(x, Eq(x**2 + x*sin(x) - 1, 0), S.Reals) assert solveset(Eq(-I*(exp(I*x) - exp(-I*x))/2, 1), x ) == imageset(Lambda(n, 2*n*pi + pi/2), S.Integers) assert solveset(x + sin(x) > 1, x, domain=S.Reals ) == ConditionSet(x, x + sin(x) > 1, S.Reals) assert solveset(Eq(sin(Abs(x)), x), x, domain=S.Reals ) == ConditionSet(x, Eq(-x + sin(Abs(x)), 0), S.Reals) assert solveset(y**x-z, x, S.Reals) == \ ConditionSet(x, Eq(y**x - z, 0), S.Reals) @XFAIL def test_conditionset_equality(): ''' Checking equality of different representations of ConditionSet''' assert solveset(Eq(tan(x), y), x) == ConditionSet(x, Eq(tan(x), y), S.Complexes) def test_solveset_domain(): x = Symbol('x') assert solveset(x**2 - x - 6, x, Interval(0, oo)) == FiniteSet(3) assert solveset(x**2 - 1, x, Interval(0, oo)) == FiniteSet(1) assert solveset(x**4 - 16, x, Interval(0, 10)) == FiniteSet(2) def test_improve_coverage(): from sympy.solvers.solveset import _has_rational_power x = Symbol('x') solution = solveset(exp(x) + sin(x), x, S.Reals) unsolved_object = ConditionSet(x, Eq(exp(x) + sin(x), 0), S.Reals) assert solution == unsolved_object assert _has_rational_power(sin(x)*exp(x) + 1, x) == (False, S.One) assert _has_rational_power((sin(x)**2)*(exp(x) + 1)**3, x) == (False, S.One) def test_issue_9522(): x = Symbol('x') expr1 = Eq(1/(x**2 - 4) + x, 1/(x**2 - 4) + 2) expr2 = Eq(1/x + x, 1/x) assert solveset(expr1, x, S.Reals) == EmptySet() assert solveset(expr2, x, S.Reals) == EmptySet() def test_solvify(): x = Symbol('x') assert solvify(x**2 + 10, x, S.Reals) == [] assert solvify(x**3 + 1, x, S.Complexes) == [-1, S.Half - sqrt(3)*I/2, S.Half + sqrt(3)*I/2] assert solvify(log(x), x, S.Reals) == [1] assert solvify(cos(x), x, S.Reals) == [pi/2, pi*Rational(3, 2)] assert solvify(sin(x) + 1, x, S.Reals) == [pi*Rational(3, 2)] raises(NotImplementedError, lambda: solvify(sin(exp(x)), x, S.Complexes)) def test_abs_invert_solvify(): assert solvify(sin(Abs(x)), x, S.Reals) is None def test_linear_eq_to_matrix(): x, y, z = symbols('x, y, z') a, b, c, d, e, f, g, h, i, j, k, l = symbols('a:l') eqns1 = [2*x + y - 2*z - 3, x - y - z, x + y + 3*z - 12] eqns2 = [Eq(3*x + 2*y - z, 1), Eq(2*x - 2*y + 4*z, -2), -2*x + y - 2*z] A, B = linear_eq_to_matrix(eqns1, x, y, z) assert A == Matrix([[2, 1, -2], [1, -1, -1], [1, 1, 3]]) assert B == Matrix([[3], [0], [12]]) A, B = linear_eq_to_matrix(eqns2, x, y, z) assert A == Matrix([[3, 2, -1], [2, -2, 4], [-2, 1, -2]]) assert B == Matrix([[1], [-2], [0]]) # Pure symbolic coefficients eqns3 = [a*b*x + b*y + c*z - d, e*x + d*x + f*y + g*z - h, i*x + j*y + k*z - l] A, B = linear_eq_to_matrix(eqns3, x, y, z) assert A == Matrix([[a*b, b, c], [d + e, f, g], [i, j, k]]) assert B == Matrix([[d], [h], [l]]) # raise ValueError if # 1) no symbols are given raises(ValueError, lambda: linear_eq_to_matrix(eqns3)) # 2) there are duplicates raises(ValueError, lambda: linear_eq_to_matrix(eqns3, [x, x, y])) # 3) there are non-symbols raises(ValueError, lambda: linear_eq_to_matrix(eqns3, [x, 1/a, y])) # 4) a nonlinear term is detected in the original expression raises(ValueError, lambda: linear_eq_to_matrix(Eq(1/x + x, 1/x))) assert linear_eq_to_matrix(1, x) == (Matrix([[0]]), Matrix([[-1]])) # issue 15195 assert linear_eq_to_matrix(x + y*(z*(3*x + 2) + 3), x) == ( Matrix([[3*y*z + 1]]), Matrix([[-y*(2*z + 3)]])) assert linear_eq_to_matrix(Matrix( [[a*x + b*y - 7], [5*x + 6*y - c]]), x, y) == ( Matrix([[a, b], [5, 6]]), Matrix([[7], [c]])) # issue 15312 assert linear_eq_to_matrix(Eq(x + 2, 1), x) == ( Matrix([[1]]), Matrix([[-1]])) def test_issue_16577(): assert linear_eq_to_matrix(Eq(a*(2*x + 3*y) + 4*y, 5), x, y) == ( Matrix([[2*a, 3*a + 4]]), Matrix([[5]])) def test_linsolve(): x, y, z, u, v, w = symbols("x, y, z, u, v, w") x1, x2, x3, x4 = symbols('x1, x2, x3, x4') # Test for different input forms M = Matrix([[1, 2, 1, 1, 7], [1, 2, 2, -1, 12], [2, 4, 0, 6, 4]]) system1 = A, b = M[:, :-1], M[:, -1] Eqns = [x1 + 2*x2 + x3 + x4 - 7, x1 + 2*x2 + 2*x3 - x4 - 12, 2*x1 + 4*x2 + 6*x4 - 4] sol = FiniteSet((-2*x2 - 3*x4 + 2, x2, 2*x4 + 5, x4)) assert linsolve(Eqns, (x1, x2, x3, x4)) == sol assert linsolve(Eqns, *(x1, x2, x3, x4)) == sol assert linsolve(system1, (x1, x2, x3, x4)) == sol assert linsolve(system1, *(x1, x2, x3, x4)) == sol # issue 9667 - symbols can be Dummy symbols x1, x2, x3, x4 = symbols('x:4', cls=Dummy) assert linsolve(system1, x1, x2, x3, x4) == FiniteSet( (-2*x2 - 3*x4 + 2, x2, 2*x4 + 5, x4)) # raise ValueError for garbage value raises(ValueError, lambda: linsolve(Eqns)) raises(ValueError, lambda: linsolve(x1)) raises(ValueError, lambda: linsolve(x1, x2)) raises(ValueError, lambda: linsolve((A,), x1, x2)) raises(ValueError, lambda: linsolve(A, b, x1, x2)) #raise ValueError if equations are non-linear in given variables raises(ValueError, lambda: linsolve([x + y - 1, x ** 2 + y - 3], [x, y])) raises(ValueError, lambda: linsolve([cos(x) + y, x + y], [x, y])) assert linsolve([x + z - 1, x ** 2 + y - 3], [z, y]) == {(-x + 1, -x**2 + 3)} # Fully symbolic test a, b, c, d, e, f = symbols('a, b, c, d, e, f') A = Matrix([[a, b], [c, d]]) B = Matrix([[e], [f]]) system2 = (A, B) sol = FiniteSet(((-b*f + d*e)/(a*d - b*c), (a*f - c*e)/(a*d - b*c))) assert linsolve(system2, [x, y]) == sol # No solution A = Matrix([[1, 2, 3], [2, 4, 6], [3, 6, 9]]) b = Matrix([0, 0, 1]) assert linsolve((A, b), (x, y, z)) == EmptySet() # Issue #10056 A, B, J1, J2 = symbols('A B J1 J2') Augmatrix = Matrix([ [2*I*J1, 2*I*J2, -2/J1], [-2*I*J2, -2*I*J1, 2/J2], [0, 2, 2*I/(J1*J2)], [2, 0, 0], ]) assert linsolve(Augmatrix, A, B) == FiniteSet((0, I/(J1*J2))) # Issue #10121 - Assignment of free variables a, b, c, d, e = symbols('a, b, c, d, e') Augmatrix = Matrix([[0, 1, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0]]) assert linsolve(Augmatrix, a, b, c, d, e) == FiniteSet((a, 0, c, 0, e)) raises(IndexError, lambda: linsolve(Augmatrix, a, b, c)) x0, x1, x2, _x0 = symbols('tau0 tau1 tau2 _tau0') assert linsolve(Matrix([[0, 1, 0, 0, 0, 0], [0, 0, 0, 1, 0, _x0]]) ) == FiniteSet((x0, 0, x1, _x0, x2)) x0, x1, x2, _x0 = symbols('_tau0 _tau1 _tau2 tau0') assert linsolve(Matrix([[0, 1, 0, 0, 0, 0], [0, 0, 0, 1, 0, _x0]]) ) == FiniteSet((x0, 0, x1, _x0, x2)) x0, x1, x2, _x0 = symbols('_tau0 _tau1 _tau2 tau1') assert linsolve(Matrix([[0, 1, 0, 0, 0, 0], [0, 0, 0, 1, 0, _x0]]) ) == FiniteSet((x0, 0, x1, _x0, x2)) # symbols can be given as generators x0, x2, x4 = symbols('x0, x2, x4') assert linsolve(Augmatrix, numbered_symbols('x') ) == FiniteSet((x0, 0, x2, 0, x4)) Augmatrix[-1, -1] = x0 # use Dummy to avoid clash; the names may clash but the symbols # will not Augmatrix[-1, -1] = symbols('_x0') assert len(linsolve( Augmatrix, numbered_symbols('x', cls=Dummy)).free_symbols) == 4 # Issue #12604 f = Function('f') assert linsolve([f(x) - 5], f(x)) == FiniteSet((5,)) # Issue #14860 from sympy.physics.units import meter, newton, kilo Eqns = [8*kilo*newton + x + y, 28*kilo*newton*meter + 3*x*meter] assert linsolve(Eqns, x, y) == {(newton*Rational(-28000, 3), newton*Rational(4000, 3))} # linsolve fully expands expressions, so removable singularities # and other nonlinearity does not raise an error assert linsolve([Eq(x, x + y)], [x, y]) == {(x, 0)} assert linsolve([Eq(1/x, 1/x + y)], [x, y]) == {(x, 0)} assert linsolve([Eq(y/x, y/x + y)], [x, y]) == {(x, 0)} assert linsolve([Eq(x*(x + 1), x**2 + y)], [x, y]) == {(y, y)} def test_linsolve_immutable(): A = ImmutableDenseMatrix([[1, 1, 2], [0, 1, 2], [0, 0, 1]]) B = ImmutableDenseMatrix([2, 1, -1]) c = symbols('c1 c2 c3') assert linsolve([A, B], c) == FiniteSet((1, 3, -1)) A = ImmutableDenseMatrix([[1, 1, 7], [1, -1, 3]]) assert linsolve(A) == FiniteSet((5, 2)) def test_solve_decomposition(): x = Symbol('x') n = Dummy('n') f1 = exp(3*x) - 6*exp(2*x) + 11*exp(x) - 6 f2 = sin(x)**2 - 2*sin(x) + 1 f3 = sin(x)**2 - sin(x) f4 = sin(x + 1) f5 = exp(x + 2) - 1 f6 = 1/log(x) f7 = 1/x s1 = ImageSet(Lambda(n, 2*n*pi), S.Integers) s2 = ImageSet(Lambda(n, 2*n*pi + pi), S.Integers) s3 = ImageSet(Lambda(n, 2*n*pi + pi/2), S.Integers) s4 = ImageSet(Lambda(n, 2*n*pi - 1), S.Integers) s5 = ImageSet(Lambda(n, 2*n*pi - 1 + pi), S.Integers) assert solve_decomposition(f1, x, S.Reals) == FiniteSet(0, log(2), log(3)) assert solve_decomposition(f2, x, S.Reals) == s3 assert solve_decomposition(f3, x, S.Reals) == Union(s1, s2, s3) assert solve_decomposition(f4, x, S.Reals) == Union(s4, s5) assert solve_decomposition(f5, x, S.Reals) == FiniteSet(-2) assert solve_decomposition(f6, x, S.Reals) == S.EmptySet assert solve_decomposition(f7, x, S.Reals) == S.EmptySet assert solve_decomposition(x, x, Interval(1, 2)) == S.EmptySet # nonlinsolve testcases def test_nonlinsolve_basic(): assert nonlinsolve([],[]) == S.EmptySet assert nonlinsolve([],[x, y]) == S.EmptySet system = [x, y - x - 5] assert nonlinsolve([x],[x, y]) == FiniteSet((0, y)) assert nonlinsolve(system, [y]) == FiniteSet((x + 5,)) soln = (ImageSet(Lambda(n, 2*n*pi + pi/2), S.Integers),) assert nonlinsolve([sin(x) - 1], [x]) == FiniteSet(tuple(soln)) assert nonlinsolve([x**2 - 1], [x]) == FiniteSet((-1,), (1,)) soln = FiniteSet((y, y)) assert nonlinsolve([x - y, 0], x, y) == soln assert nonlinsolve([0, x - y], x, y) == soln assert nonlinsolve([x - y, x - y], x, y) == soln assert nonlinsolve([x, 0], x, y) == FiniteSet((0, y)) f = Function('f') assert nonlinsolve([f(x), 0], f(x), y) == FiniteSet((0, y)) assert nonlinsolve([f(x), 0], f(x), f(y)) == FiniteSet((0, f(y))) A = Indexed('A', x) assert nonlinsolve([A, 0], A, y) == FiniteSet((0, y)) assert nonlinsolve([x**2 -1], [sin(x)]) == FiniteSet((S.EmptySet,)) assert nonlinsolve([x**2 -1], sin(x)) == FiniteSet((S.EmptySet,)) assert nonlinsolve([x**2 -1], 1) == FiniteSet((x**2,)) assert nonlinsolve([x**2 -1], x + y) == FiniteSet((S.EmptySet,)) def test_nonlinsolve_abs(): soln = FiniteSet((x, Abs(x))) assert nonlinsolve([Abs(x) - y], x, y) == soln def test_raise_exception_nonlinsolve(): raises(IndexError, lambda: nonlinsolve([x**2 -1], [])) raises(ValueError, lambda: nonlinsolve([x**2 -1])) raises(NotImplementedError, lambda: nonlinsolve([(x+y)**2 - 9, x**2 - y**2 - 0.75], (x, y))) def test_trig_system(): # TODO: add more simple testcases when solveset returns # simplified soln for Trig eq assert nonlinsolve([sin(x) - 1, cos(x) -1 ], x) == S.EmptySet soln1 = (ImageSet(Lambda(n, 2*n*pi + pi/2), S.Integers),) soln = FiniteSet(soln1) assert nonlinsolve([sin(x) - 1, cos(x)], x) == soln @XFAIL def test_trig_system_fail(): # fails because solveset trig solver is not much smart. sys = [x + y - pi/2, sin(x) + sin(y) - 1] # solveset returns conditionset for sin(x) + sin(y) - 1 soln_1 = (ImageSet(Lambda(n, n*pi + pi/2), S.Integers), ImageSet(Lambda(n, n*pi)), S.Integers) soln_1 = FiniteSet(soln_1) soln_2 = (ImageSet(Lambda(n, n*pi), S.Integers), ImageSet(Lambda(n, n*pi+ pi/2), S.Integers)) soln_2 = FiniteSet(soln_2) soln = soln_1 + soln_2 assert nonlinsolve(sys, [x, y]) == soln # Add more cases from here # http://www.vitutor.com/geometry/trigonometry/equations_systems.html#uno sys = [sin(x) + sin(y) - (sqrt(3)+1)/2, sin(x) - sin(y) - (sqrt(3) - 1)/2] soln_x = Union(ImageSet(Lambda(n, 2*n*pi + pi/3), S.Integers), ImageSet(Lambda(n, 2*n*pi + pi*Rational(2, 3)), S.Integers)) soln_y = Union(ImageSet(Lambda(n, 2*n*pi + pi/6), S.Integers), ImageSet(Lambda(n, 2*n*pi + pi*Rational(5, 6)), S.Integers)) assert nonlinsolve(sys, [x, y]) ==FiniteSet((soln_x, soln_y)) def test_nonlinsolve_positive_dimensional(): x, y, z, a, b, c, d = symbols('x, y, z, a, b, c, d', extended_real = True) assert nonlinsolve([x*y, x*y - x], [x, y]) == FiniteSet((0, y)) system = [a**2 + a*c, a - b] assert nonlinsolve(system, [a, b]) == FiniteSet((0, 0), (-c, -c)) # here (a= 0, b = 0) is independent soln so both is printed. # if symbols = [a, b, c] then only {a : -c ,b : -c} eq1 = a + b + c + d eq2 = a*b + b*c + c*d + d*a eq3 = a*b*c + b*c*d + c*d*a + d*a*b eq4 = a*b*c*d - 1 system = [eq1, eq2, eq3, eq4] sol1 = (-1/d, -d, 1/d, FiniteSet(d) - FiniteSet(0)) sol2 = (1/d, -d, -1/d, FiniteSet(d) - FiniteSet(0)) soln = FiniteSet(sol1, sol2) assert nonlinsolve(system, [a, b, c, d]) == soln def test_nonlinsolve_polysys(): x, y, z = symbols('x, y, z', real = True) assert nonlinsolve([x**2 + y - 2, x**2 + y], [x, y]) == S.EmptySet s = (-y + 2, y) assert nonlinsolve([(x + y)**2 - 4, x + y - 2], [x, y]) == FiniteSet(s) system = [x**2 - y**2] soln_real = FiniteSet((-y, y), (y, y)) soln_complex = FiniteSet((-Abs(y), y), (Abs(y), y)) soln =soln_real + soln_complex assert nonlinsolve(system, [x, y]) == soln system = [x**2 - y**2] soln_real= FiniteSet((y, -y), (y, y)) soln_complex = FiniteSet((y, -Abs(y)), (y, Abs(y))) soln = soln_real + soln_complex assert nonlinsolve(system, [y, x]) == soln system = [x**2 + y - 3, x - y - 4] assert nonlinsolve(system, (x, y)) != nonlinsolve(system, (y, x)) def test_nonlinsolve_using_substitution(): x, y, z, n = symbols('x, y, z, n', real = True) system = [(x + y)*n - y**2 + 2] s_x = (n*y - y**2 + 2)/n soln = (-s_x, y) assert nonlinsolve(system, [x, y]) == FiniteSet(soln) system = [z**2*x**2 - z**2*y**2/exp(x)] soln_real_1 = (y, x, 0) soln_real_2 = (-exp(x/2)*Abs(x), x, z) soln_real_3 = (exp(x/2)*Abs(x), x, z) soln_complex_1 = (-x*exp(x/2), x, z) soln_complex_2 = (x*exp(x/2), x, z) syms = [y, x, z] soln = FiniteSet(soln_real_1, soln_complex_1, soln_complex_2,\ soln_real_2, soln_real_3) assert nonlinsolve(system,syms) == soln def test_nonlinsolve_complex(): x, y, z = symbols('x, y, z') n = Dummy('n') assert nonlinsolve([exp(x) - sin(y), 1/y - 3], [x, y]) == { (ImageSet(Lambda(n, 2*n*I*pi + log(sin(Rational(1, 3)))), S.Integers), Rational(1, 3))} system = [exp(x) - sin(y), 1/exp(y) - 3] assert nonlinsolve(system, [x, y]) == { (ImageSet(Lambda(n, I*(2*n*pi + pi) + log(sin(log(3)))), S.Integers), -log(3)), (ImageSet(Lambda(n, I*(2*n*pi + arg(sin(2*n*I*pi - log(3)))) + log(Abs(sin(2*n*I*pi - log(3))))), S.Integers), ImageSet(Lambda(n, 2*n*I*pi - log(3)), S.Integers))} system = [exp(x) - sin(y), y**2 - 4] assert nonlinsolve(system, [x, y]) == { (ImageSet(Lambda(n, I*(2*n*pi + pi) + log(sin(2))), S.Integers), -2), (ImageSet(Lambda(n, 2*n*I*pi + log(sin(2))), S.Integers), 2)} @XFAIL def test_solve_nonlinear_trans(): # After the transcendental equation solver these will work x, y, z = symbols('x, y, z', real=True) soln1 = FiniteSet((2*LambertW(y/2), y)) soln2 = FiniteSet((-x*sqrt(exp(x)), y), (x*sqrt(exp(x)), y)) soln3 = FiniteSet((x*exp(x/2), x)) soln4 = FiniteSet(2*LambertW(y/2), y) assert nonlinsolve([x**2 - y**2/exp(x)], [x, y]) == soln1 assert nonlinsolve([x**2 - y**2/exp(x)], [y, x]) == soln2 assert nonlinsolve([x**2 - y**2/exp(x)], [y, x]) == soln3 assert nonlinsolve([x**2 - y**2/exp(x)], [x, y]) == soln4 def test_issue_5132_1(): system = [sqrt(x**2 + y**2) - sqrt(10), x + y - 4] assert nonlinsolve(system, [x, y]) == FiniteSet((1, 3), (3, 1)) n = Dummy('n') eqs = [exp(x)**2 - sin(y) + z**2, 1/exp(y) - 3] s_real_y = -log(3) s_real_z = sqrt(-exp(2*x) - sin(log(3))) soln_real = FiniteSet((s_real_y, s_real_z), (s_real_y, -s_real_z)) lam = Lambda(n, 2*n*I*pi + -log(3)) s_complex_y = ImageSet(lam, S.Integers) lam = Lambda(n, sqrt(-exp(2*x) + sin(2*n*I*pi + -log(3)))) s_complex_z_1 = ImageSet(lam, S.Integers) lam = Lambda(n, -sqrt(-exp(2*x) + sin(2*n*I*pi + -log(3)))) s_complex_z_2 = ImageSet(lam, S.Integers) soln_complex = FiniteSet( (s_complex_y, s_complex_z_1), (s_complex_y, s_complex_z_2) ) soln = soln_real + soln_complex assert nonlinsolve(eqs, [y, z]) == soln def test_issue_5132_2(): x, y = symbols('x, y', real=True) eqs = [exp(x)**2 - sin(y) + z**2, 1/exp(y) - 3] n = Dummy('n') soln_real = (log(-z**2 + sin(y))/2, z) lam = Lambda( n, I*(2*n*pi + arg(-z**2 + sin(y)))/2 + log(Abs(z**2 - sin(y)))/2) img = ImageSet(lam, S.Integers) # not sure about the complex soln. But it looks correct. soln_complex = (img, z) soln = FiniteSet(soln_real, soln_complex) assert nonlinsolve(eqs, [x, z]) == soln r, t = symbols('r, t') system = [r - x**2 - y**2, tan(t) - y/x] s_x = sqrt(r/(tan(t)**2 + 1)) s_y = sqrt(r/(tan(t)**2 + 1))*tan(t) soln = FiniteSet((s_x, s_y), (-s_x, -s_y)) assert nonlinsolve(system, [x, y]) == soln def test_issue_6752(): a,b,c,d = symbols('a, b, c, d', real=True) assert nonlinsolve([a**2 + a, a - b], [a, b]) == {(-1, -1), (0, 0)} @SKIP("slow") def test_issue_5114_solveset(): # slow testcase a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r = symbols('a:r') # there is no 'a' in the equation set but this is how the # problem was originally posed syms = [a, b, c, f, h, k, n] eqs = [b + r/d - c/d, c*(1/d + 1/e + 1/g) - f/g - r/d, f*(1/g + 1/i + 1/j) - c/g - h/i, h*(1/i + 1/l + 1/m) - f/i - k/m, k*(1/m + 1/o + 1/p) - h/m - n/p, n*(1/p + 1/q) - k/p] assert len(nonlinsolve(eqs, syms)) == 1 @SKIP("Hangs") def _test_issue_5335(): # Not able to check zero dimensional system. # is_zero_dimensional Hangs lam, a0, conc = symbols('lam a0 conc') eqs = [lam + 2*y - a0*(1 - x/2)*x - 0.005*x/2*x, a0*(1 - x/2)*x - 1*y - 0.743436700916726*y, x + y - conc] sym = [x, y, a0] # there are 4 solutions but only two are valid assert len(nonlinsolve(eqs, sym)) == 2 # float lam, a0, conc = symbols('lam a0 conc') eqs = [lam + 2*y - a0*(1 - x/2)*x - 0.005*x/2*x, a0*(1 - x/2)*x - 1*y - 0.743436700916726*y, x + y - conc] sym = [x, y, a0] assert len(nonlinsolve(eqs, sym)) == 2 def test_issue_2777(): # the equations represent two circles x, y = symbols('x y', real=True) e1, e2 = sqrt(x**2 + y**2) - 10, sqrt(y**2 + (-x + 10)**2) - 3 a, b = Rational(191, 20), 3*sqrt(391)/20 ans = {(a, -b), (a, b)} assert nonlinsolve((e1, e2), (x, y)) == ans assert nonlinsolve((e1, e2/(x - a)), (x, y)) == S.EmptySet # make the 2nd circle's radius be -3 e2 += 6 assert nonlinsolve((e1, e2), (x, y)) == S.EmptySet def test_issue_8828(): x1 = 0 y1 = -620 r1 = 920 x2 = 126 y2 = 276 x3 = 51 y3 = 205 r3 = 104 v = [x, y, z] f1 = (x - x1)**2 + (y - y1)**2 - (r1 - z)**2 f2 = (x2 - x)**2 + (y2 - y)**2 - z**2 f3 = (x - x3)**2 + (y - y3)**2 - (r3 - z)**2 F = [f1, f2, f3] g1 = sqrt((x - x1)**2 + (y - y1)**2) + z - r1 g2 = f2 g3 = sqrt((x - x3)**2 + (y - y3)**2) + z - r3 G = [g1, g2, g3] # both soln same A = nonlinsolve(F, v) B = nonlinsolve(G, v) assert A == B def test_nonlinsolve_conditionset(): # when solveset failed to solve all the eq # return conditionset f = Function('f') f1 = f(x) - pi/2 f2 = f(y) - pi*Rational(3, 2) intermediate_system = Eq(2*f(x) - pi, 0) & Eq(2*f(y) - 3*pi, 0) symbols = Tuple(x, y) soln = ConditionSet( symbols, intermediate_system, S.Complexes**2) assert nonlinsolve([f1, f2], [x, y]) == soln def test_substitution_basic(): assert substitution([], [x, y]) == S.EmptySet assert substitution([], []) == S.EmptySet system = [2*x**2 + 3*y**2 - 30, 3*x**2 - 2*y**2 - 19] soln = FiniteSet((-3, -2), (-3, 2), (3, -2), (3, 2)) assert substitution(system, [x, y]) == soln soln = FiniteSet((-1, 1)) assert substitution([x + y], [x], [{y: 1}], [y], set([]), [x, y]) == soln assert substitution( [x + y], [x], [{y: 1}], [y], set([x + 1]), [y, x]) == S.EmptySet def test_issue_5132_substitution(): x, y, z, r, t = symbols('x, y, z, r, t', real=True) system = [r - x**2 - y**2, tan(t) - y/x] s_x_1 = Complement(FiniteSet(-sqrt(r/(tan(t)**2 + 1))), FiniteSet(0)) s_x_2 = Complement(FiniteSet(sqrt(r/(tan(t)**2 + 1))), FiniteSet(0)) s_y = sqrt(r/(tan(t)**2 + 1))*tan(t) soln = FiniteSet((s_x_2, s_y)) + FiniteSet((s_x_1, -s_y)) assert substitution(system, [x, y]) == soln n = Dummy('n') eqs = [exp(x)**2 - sin(y) + z**2, 1/exp(y) - 3] s_real_y = -log(3) s_real_z = sqrt(-exp(2*x) - sin(log(3))) soln_real = FiniteSet((s_real_y, s_real_z), (s_real_y, -s_real_z)) lam = Lambda(n, 2*n*I*pi + -log(3)) s_complex_y = ImageSet(lam, S.Integers) lam = Lambda(n, sqrt(-exp(2*x) + sin(2*n*I*pi + -log(3)))) s_complex_z_1 = ImageSet(lam, S.Integers) lam = Lambda(n, -sqrt(-exp(2*x) + sin(2*n*I*pi + -log(3)))) s_complex_z_2 = ImageSet(lam, S.Integers) soln_complex = FiniteSet( (s_complex_y, s_complex_z_1), (s_complex_y, s_complex_z_2)) soln = soln_real + soln_complex assert substitution(eqs, [y, z]) == soln def test_raises_substitution(): raises(ValueError, lambda: substitution([x**2 -1], [])) raises(TypeError, lambda: substitution([x**2 -1])) raises(ValueError, lambda: substitution([x**2 -1], [sin(x)])) raises(TypeError, lambda: substitution([x**2 -1], x)) raises(TypeError, lambda: substitution([x**2 -1], 1)) # end of tests for nonlinsolve def test_issue_9556(): x = Symbol('x') b = Symbol('b', positive=True) assert solveset(Abs(x) + 1, x, S.Reals) == EmptySet() assert solveset(Abs(x) + b, x, S.Reals) == EmptySet() assert solveset(Eq(b, -1), b, S.Reals) == EmptySet() def test_issue_9611(): x = Symbol('x') a = Symbol('a') y = Symbol('y') assert solveset(Eq(x - x + a, a), x, S.Reals) == S.Reals assert solveset(Eq(y - y + a, a), y) == S.Complexes def test_issue_9557(): x = Symbol('x') a = Symbol('a') assert solveset(x**2 + a, x, S.Reals) == Intersection(S.Reals, FiniteSet(-sqrt(-a), sqrt(-a))) def test_issue_9778(): assert solveset(x**3 + 1, x, S.Reals) == FiniteSet(-1) assert solveset(x**Rational(3, 5) + 1, x, S.Reals) == S.EmptySet assert solveset(x**3 + y, x, S.Reals) == \ FiniteSet(-Abs(y)**Rational(1, 3)*sign(y)) def test_issue_10214(): assert solveset(x**Rational(3, 2) + 4, x, S.Reals) == S.EmptySet assert solveset(x**(Rational(-3, 2)) + 4, x, S.Reals) == S.EmptySet ans = FiniteSet(-2**Rational(2, 3)) assert solveset(x**(S(3)) + 4, x, S.Reals) == ans assert (x**(S(3)) + 4).subs(x,list(ans)[0]) == 0 # substituting ans and verifying the result. assert (x**(S(3)) + 4).subs(x,-(-2)**Rational(2, 3)) == 0 def test_issue_9849(): assert solveset(Abs(sin(x)) + 1, x, S.Reals) == S.EmptySet def test_issue_9953(): assert linsolve([ ], x) == S.EmptySet def test_issue_9913(): assert solveset(2*x + 1/(x - 10)**2, x, S.Reals) == \ FiniteSet(-(3*sqrt(24081)/4 + Rational(4027, 4))**Rational(1, 3)/3 - 100/ (3*(3*sqrt(24081)/4 + Rational(4027, 4))**Rational(1, 3)) + Rational(20, 3)) def test_issue_10397(): assert solveset(sqrt(x), x, S.Complexes) == FiniteSet(0) def test_issue_14987(): raises(ValueError, lambda: linear_eq_to_matrix( [x**2], x)) raises(ValueError, lambda: linear_eq_to_matrix( [x*(-3/x + 1) + 2*y - a], [x, y])) raises(ValueError, lambda: linear_eq_to_matrix( [(x**2 - 3*x)/(x - 3) - 3], x)) raises(ValueError, lambda: linear_eq_to_matrix( [(x + 1)**3 - x**3 - 3*x**2 + 7], x)) raises(ValueError, lambda: linear_eq_to_matrix( [x*(1/x + 1) + y], [x, y])) raises(ValueError, lambda: linear_eq_to_matrix( [(x + 1)*y], [x, y])) raises(ValueError, lambda: linear_eq_to_matrix( [Eq(1/x, 1/x + y)], [x, y])) raises(ValueError, lambda: linear_eq_to_matrix( [Eq(y/x, y/x + y)], [x, y])) raises(ValueError, lambda: linear_eq_to_matrix( [Eq(x*(x + 1), x**2 + y)], [x, y])) def test_simplification(): eq = x + (a - b)/(-2*a + 2*b) assert solveset(eq, x) == FiniteSet(S.Half) assert solveset(eq, x, S.Reals) == Intersection({-((a - b)/(-2*a + 2*b))}, S.Reals) # So that ap - bn is not zero: ap = Symbol('ap', positive=True) bn = Symbol('bn', negative=True) eq = x + (ap - bn)/(-2*ap + 2*bn) assert solveset(eq, x) == FiniteSet(S.Half) assert solveset(eq, x, S.Reals) == FiniteSet(S.Half) def test_issue_10555(): f = Function('f') g = Function('g') assert solveset(f(x) - pi/2, x, S.Reals) == \ ConditionSet(x, Eq(f(x) - pi/2, 0), S.Reals) assert solveset(f(g(x)) - pi/2, g(x), S.Reals) == \ ConditionSet(g(x), Eq(f(g(x)) - pi/2, 0), S.Reals) def test_issue_8715(): eq = x + 1/x > -2 + 1/x assert solveset(eq, x, S.Reals) == \ (Interval.open(-2, oo) - FiniteSet(0)) assert solveset(eq.subs(x,log(x)), x, S.Reals) == \ Interval.open(exp(-2), oo) - FiniteSet(1) def test_issue_11174(): r, t = symbols('r t') eq = z**2 + exp(2*x) - sin(y) soln = Intersection(S.Reals, FiniteSet(log(-z**2 + sin(y))/2)) assert solveset(eq, x, S.Reals) == soln eq = sqrt(r)*Abs(tan(t))/sqrt(tan(t)**2 + 1) + x*tan(t) s = -sqrt(r)*Abs(tan(t))/(sqrt(tan(t)**2 + 1)*tan(t)) soln = Intersection(S.Reals, FiniteSet(s)) assert solveset(eq, x, S.Reals) == soln def test_issue_11534(): # eq and eq2 should give the same solution as a Complement eq = -y + x/sqrt(-x**2 + 1) eq2 = -y**2 + x**2/(-x**2 + 1) soln = Complement(FiniteSet(-y/sqrt(y**2 + 1), y/sqrt(y**2 + 1)), FiniteSet(-1, 1)) assert solveset(eq, x, S.Reals) == soln assert solveset(eq2, x, S.Reals) == soln def test_issue_10477(): assert solveset((x**2 + 4*x - 3)/x < 2, x, S.Reals) == \ Union(Interval.open(-oo, -3), Interval.open(0, 1)) def test_issue_10671(): assert solveset(sin(y), y, Interval(0, pi)) == FiniteSet(0, pi) i = Interval(1, 10) assert solveset((1/x).diff(x) < 0, x, i) == i def test_issue_11064(): eq = x + sqrt(x**2 - 5) assert solveset(eq > 0, x, S.Reals) == \ Interval(sqrt(5), oo) assert solveset(eq < 0, x, S.Reals) == \ Interval(-oo, -sqrt(5)) assert solveset(eq > sqrt(5), x, S.Reals) == \ Interval.Lopen(sqrt(5), oo) def test_issue_12478(): eq = sqrt(x - 2) + 2 soln = solveset_real(eq, x) assert soln is S.EmptySet assert solveset(eq < 0, x, S.Reals) is S.EmptySet assert solveset(eq > 0, x, S.Reals) == Interval(2, oo) def test_issue_12429(): eq = solveset(log(x)/x <= 0, x, S.Reals) sol = Interval.Lopen(0, 1) assert eq == sol def test_solveset_arg(): assert solveset(arg(x), x, S.Reals) == Interval.open(0, oo) assert solveset(arg(4*x -3), x) == Interval.open(Rational(3, 4), oo) def test__is_finite_with_finite_vars(): f = _is_finite_with_finite_vars # issue 12482 assert all(f(1/x) is None for x in ( Dummy(), Dummy(real=True), Dummy(complex=True))) assert f(1/Dummy(real=False)) is True # b/c it's finite but not 0 def test_issue_13550(): assert solveset(x**2 - 2*x - 15, symbol = x, domain = Interval(-oo, 0)) == FiniteSet(-3) def test_issue_13849(): t = symbols('t') assert nonlinsolve((t*(sqrt(5) + sqrt(2)) - sqrt(2), t), t) == EmptySet() def test_issue_14223(): x = Symbol('x') assert solveset((Abs(x + Min(x, 2)) - 2).rewrite(Piecewise), x, S.Reals) == FiniteSet(-1, 1) assert solveset((Abs(x + Min(x, 2)) - 2).rewrite(Piecewise), x, Interval(0, 2)) == FiniteSet(1) def test_issue_10158(): x = Symbol('x') dom = S.Reals assert solveset(x*Max(x, 15) - 10, x, dom) == FiniteSet(Rational(2, 3)) assert solveset(x*Min(x, 15) - 10, x, dom) == FiniteSet(-sqrt(10), sqrt(10)) assert solveset(Max(Abs(x - 3) - 1, x + 2) - 3, x, dom) == FiniteSet(-1, 1) assert solveset(Abs(x - 1) - Abs(y), x, dom) == FiniteSet(-Abs(y) + 1, Abs(y) + 1) assert solveset(Abs(x + 4*Abs(x + 1)), x, dom) == FiniteSet(Rational(-4, 3), Rational(-4, 5)) assert solveset(2*Abs(x + Abs(x + Max(3, x))) - 2, x, S.Reals) == FiniteSet(-1, -2) dom = S.Complexes raises(ValueError, lambda: solveset(x*Max(x, 15) - 10, x, dom)) raises(ValueError, lambda: solveset(x*Min(x, 15) - 10, x, dom)) raises(ValueError, lambda: solveset(Max(Abs(x - 3) - 1, x + 2) - 3, x, dom)) raises(ValueError, lambda: solveset(Abs(x - 1) - Abs(y), x, dom)) raises(ValueError, lambda: solveset(Abs(x + 4*Abs(x + 1)), x, dom)) def test_issue_14300(): x, y, n = symbols('x y n') f = 1 - exp(-18000000*x) - y a1 = FiniteSet(-log(-y + 1)/18000000) assert solveset(f, x, S.Reals) == \ Intersection(S.Reals, a1) assert solveset(f, x) == \ ImageSet(Lambda(n, -I*(2*n*pi + arg(-y + 1))/18000000 - log(Abs(y - 1))/18000000), S.Integers) def test_issue_14454(): x = Symbol('x') number = CRootOf(x**4 + x - 1, 2) raises(ValueError, lambda: invert_real(number, 0, x, S.Reals)) assert invert_real(x**2, number, x, S.Reals) # no error def test_issue_17882(): assert solveset(-8*x**2/(9*(x**2 - 1)**(S(4)/3)) + 4/(3*(x**2 - 1)**(S(1)/3)), x, S.Complexes) == \ FiniteSet(sqrt(3), -sqrt(3)) def test_term_factors(): assert list(_term_factors(3**x - 2)) == [-2, 3**x] expr = 4**(x + 1) + 4**(x + 2) + 4**(x - 1) - 3**(x + 2) - 3**(x + 3) assert set(_term_factors(expr)) == set([ 3**(x + 2), 4**(x + 2), 3**(x + 3), 4**(x - 1), -1, 4**(x + 1)]) #################### tests for transolve and its helpers ############### def test_transolve(): assert _transolve(3**x, x, S.Reals) == S.EmptySet assert _transolve(3**x - 9**(x + 5), x, S.Reals) == FiniteSet(-10) # exponential tests def test_exponential_real(): from sympy.abc import x, y, z e1 = 3**(2*x) - 2**(x + 3) e2 = 4**(5 - 9*x) - 8**(2 - x) e3 = 2**x + 4**x e4 = exp(log(5)*x) - 2**x e5 = exp(x/y)*exp(-z/y) - 2 e6 = 5**(x/2) - 2**(x/3) e7 = 4**(x + 1) + 4**(x + 2) + 4**(x - 1) - 3**(x + 2) - 3**(x + 3) e8 = -9*exp(-2*x + 5) + 4*exp(3*x + 1) e9 = 2**x + 4**x + 8**x - 84 assert solveset(e1, x, S.Reals) == FiniteSet( -3*log(2)/(-2*log(3) + log(2))) assert solveset(e2, x, S.Reals) == FiniteSet(Rational(4, 15)) assert solveset(e3, x, S.Reals) == S.EmptySet assert solveset(e4, x, S.Reals) == FiniteSet(0) assert solveset(e5, x, S.Reals) == Intersection( S.Reals, FiniteSet(y*log(2*exp(z/y)))) assert solveset(e6, x, S.Reals) == FiniteSet(0) assert solveset(e7, x, S.Reals) == FiniteSet(2) assert solveset(e8, x, S.Reals) == FiniteSet(-2*log(2)/5 + 2*log(3)/5 + Rational(4, 5)) assert solveset(e9, x, S.Reals) == FiniteSet(2) assert solveset_real(-9*exp(-2*x + 5) + 2**(x + 1), x) == FiniteSet( -((-5 - 2*log(3) + log(2))/(log(2) + 2))) assert solveset_real(4**(x/2) - 2**(x/3), x) == FiniteSet(0) b = sqrt(6)*sqrt(log(2))/sqrt(log(5)) assert solveset_real(5**(x/2) - 2**(3/x), x) == FiniteSet(-b, b) # coverage test C1, C2 = symbols('C1 C2') f = Function('f') assert solveset_real(C1 + C2/x**2 - exp(-f(x)), f(x)) == Intersection( S.Reals, FiniteSet(-log(C1 + C2/x**2))) y = symbols('y', positive=True) assert solveset_real(x**2 - y**2/exp(x), y) == Intersection( S.Reals, FiniteSet(-sqrt(x**2*exp(x)), sqrt(x**2*exp(x)))) p = Symbol('p', positive=True) assert solveset_real((1/p + 1)**(p + 1), p) == EmptySet() @XFAIL def test_exponential_complex(): from sympy.abc import x from sympy import Dummy n = Dummy('n') assert solveset_complex(2**x + 4**x, x) == imageset( Lambda(n, I*(2*n*pi + pi)/log(2)), S.Integers) assert solveset_complex(x**z*y**z - 2, z) == FiniteSet( log(2)/(log(x) + log(y))) assert solveset_complex(4**(x/2) - 2**(x/3), x) == imageset( Lambda(n, 3*n*I*pi/log(2)), S.Integers) assert solveset(2**x + 32, x) == imageset( Lambda(n, (I*(2*n*pi + pi) + 5*log(2))/log(2)), S.Integers) eq = (2**exp(y**2/x) + 2)/(x**2 + 15) a = sqrt(x)*sqrt(-log(log(2)) + log(log(2) + 2*n*I*pi)) assert solveset_complex(eq, y) == FiniteSet(-a, a) union1 = imageset(Lambda(n, I*(2*n*pi - pi*Rational(2, 3))/log(2)), S.Integers) union2 = imageset(Lambda(n, I*(2*n*pi + pi*Rational(2, 3))/log(2)), S.Integers) assert solveset(2**x + 4**x + 8**x, x) == Union(union1, union2) eq = 4**(x + 1) + 4**(x + 2) + 4**(x - 1) - 3**(x + 2) - 3**(x + 3) res = solveset(eq, x) num = 2*n*I*pi - 4*log(2) + 2*log(3) den = -2*log(2) + log(3) ans = imageset(Lambda(n, num/den), S.Integers) assert res == ans def test_expo_conditionset(): from sympy.abc import x, y f1 = (exp(x) + 1)**x - 2 f2 = (x + 2)**y*x - 3 f3 = 2**x - exp(x) - 3 f4 = log(x) - exp(x) f5 = 2**x + 3**x - 5**x assert solveset(f1, x, S.Reals) == ConditionSet( x, Eq((exp(x) + 1)**x - 2, 0), S.Reals) assert solveset(f2, x, S.Reals) == ConditionSet( x, Eq(x*(x + 2)**y - 3, 0), S.Reals) assert solveset(f3, x, S.Reals) == ConditionSet( x, Eq(2**x - exp(x) - 3, 0), S.Reals) assert solveset(f4, x, S.Reals) == ConditionSet( x, Eq(-exp(x) + log(x), 0), S.Reals) assert solveset(f5, x, S.Reals) == ConditionSet( x, Eq(2**x + 3**x - 5**x, 0), S.Reals) def test_exponential_symbols(): x, y, z = symbols('x y z', positive=True) assert solveset(z**x - y, x, S.Reals) == Intersection( S.Reals, FiniteSet(log(y)/log(z))) w = symbols('w') f1 = 2*x**w - 4*y**w f2 = (x/y)**w - 2 sol1 = Intersection({log(2)/(log(x) - log(y))}, S.Reals) sol2 = Intersection({log(2)/log(x/y)}, S.Reals) assert solveset(f1, w, S.Reals) == sol1 assert solveset(f2, w, S.Reals) == sol2 assert solveset(x**x, x, S.Reals) == S.EmptySet assert solveset(x**y - 1, y, S.Reals) == FiniteSet(0) assert solveset(exp(x/y)*exp(-z/y) - 2, y, S.Reals) == FiniteSet( (x - z)/log(2)) - FiniteSet(0) a, b, x, y = symbols('a b x y') assert solveset_real(a**x - b**x, x) == ConditionSet( x, (a > 0) & (b > 0), FiniteSet(0)) assert solveset(a**x - b**x, x) == ConditionSet( x, Ne(a, 0) & Ne(b, 0), FiniteSet(0)) @XFAIL def test_issue_10864(): assert solveset(x**(y*z) - x, x, S.Reals) == FiniteSet(1) @XFAIL def test_solve_only_exp_2(): assert solveset_real(sqrt(exp(x)) + sqrt(exp(-x)) - 4, x) == \ FiniteSet(2*log(-sqrt(3) + 2), 2*log(sqrt(3) + 2)) def test_is_exponential(): x, y, z = symbols('x y z') assert _is_exponential(y, x) is False assert _is_exponential(3**x - 2, x) is True assert _is_exponential(5**x - 7**(2 - x), x) is True assert _is_exponential(sin(2**x) - 4*x, x) is False assert _is_exponential(x**y - z, y) is True assert _is_exponential(x**y - z, x) is False assert _is_exponential(2**x + 4**x - 1, x) is True assert _is_exponential(x**(y*z) - x, x) is False assert _is_exponential(x**(2*x) - 3**x, x) is False assert _is_exponential(x**y - y*z, y) is False assert _is_exponential(x**y - x*z, y) is True def test_solve_exponential(): assert _solve_exponential(3**(2*x) - 2**(x + 3), 0, x, S.Reals) == \ FiniteSet(-3*log(2)/(-2*log(3) + log(2))) assert _solve_exponential(2**y + 4**y, 1, y, S.Reals) == \ FiniteSet(log(Rational(-1, 2) + sqrt(5)/2)/log(2)) assert _solve_exponential(2**y + 4**y, 0, y, S.Reals) == \ S.EmptySet assert _solve_exponential(2**x + 3**x - 5**x, 0, x, S.Reals) == \ ConditionSet(x, Eq(2**x + 3**x - 5**x, 0), S.Reals) # end of exponential tests # logarithmic tests def test_logarithmic(): assert solveset_real(log(x - 3) + log(x + 3), x) == FiniteSet( -sqrt(10), sqrt(10)) assert solveset_real(log(x + 1) - log(2*x - 1), x) == FiniteSet(2) assert solveset_real(log(x + 3) + log(1 + 3/x) - 3, x) == FiniteSet( -3 + sqrt(-12 + exp(3))*exp(Rational(3, 2))/2 + exp(3)/2, -sqrt(-12 + exp(3))*exp(Rational(3, 2))/2 - 3 + exp(3)/2) eq = z - log(x) + log(y/(x*(-1 + y**2/x**2))) assert solveset_real(eq, x) == \ Intersection(S.Reals, FiniteSet(-sqrt(y**2 - y*exp(z)), sqrt(y**2 - y*exp(z)))) - \ Intersection(S.Reals, FiniteSet(-sqrt(y**2), sqrt(y**2))) assert solveset_real( log(3*x) - log(-x + 1) - log(4*x + 1), x) == FiniteSet(Rational(-1, 2), S.Half) assert solveset(log(x**y) - y*log(x), x, S.Reals) == S.Reals @XFAIL def test_uselogcombine_2(): eq = log(exp(2*x) + 1) + log(-tanh(x) + 1) - log(2) assert solveset_real(eq, x) == EmptySet() eq = log(8*x) - log(sqrt(x) + 1) - 2 assert solveset_real(eq, x) == EmptySet() def test_is_logarithmic(): assert _is_logarithmic(y, x) is False assert _is_logarithmic(log(x), x) is True assert _is_logarithmic(log(x) - 3, x) is True assert _is_logarithmic(log(x)*log(y), x) is True assert _is_logarithmic(log(x)**2, x) is False assert _is_logarithmic(log(x - 3) + log(x + 3), x) is True assert _is_logarithmic(log(x**y) - y*log(x), x) is True assert _is_logarithmic(sin(log(x)), x) is False assert _is_logarithmic(x + y, x) is False assert _is_logarithmic(log(3*x) - log(1 - x) + 4, x) is True assert _is_logarithmic(log(x) + log(y) + x, x) is False assert _is_logarithmic(log(log(x - 3)) + log(x - 3), x) is True assert _is_logarithmic(log(log(3) + x) + log(x), x) is True assert _is_logarithmic(log(x)*(y + 3) + log(x), y) is False def test_solve_logarithm(): y = Symbol('y') assert _solve_logarithm(log(x**y) - y*log(x), 0, x, S.Reals) == S.Reals y = Symbol('y', positive=True) assert _solve_logarithm(log(x)*log(y), 0, x, S.Reals) == FiniteSet(1) # end of logarithmic tests def test_linear_coeffs(): from sympy.solvers.solveset import linear_coeffs assert linear_coeffs(0, x) == [0, 0] assert all(i is S.Zero for i in linear_coeffs(0, x)) assert linear_coeffs(x + 2*y + 3, x, y) == [1, 2, 3] assert linear_coeffs(x + 2*y + 3, y, x) == [2, 1, 3] assert linear_coeffs(x + 2*x**2 + 3, x, x**2) == [1, 2, 3] raises(ValueError, lambda: linear_coeffs(x + 2*x**2 + x**3, x, x**2)) raises(ValueError, lambda: linear_coeffs(1/x*(x - 1) + 1/x, x)) assert linear_coeffs(a*(x + y), x, y) == [a, a, 0] assert linear_coeffs(1.0, x, y) == [0, 0, 1.0] # modular tests def test_is_modular(): x, y = symbols('x y') assert _is_modular(y, x) is False assert _is_modular(Mod(x, 3) - 1, x) is True assert _is_modular(Mod(x**3 - 3*x**2 - x + 1, 3) - 1, x) is True assert _is_modular(Mod(exp(x + y), 3) - 2, x) is True assert _is_modular(Mod(exp(x + y), 3) - log(x), x) is True assert _is_modular(Mod(x, 3) - 1, y) is False assert _is_modular(Mod(x, 3)**2 - 5, x) is False assert _is_modular(Mod(x, 3)**2 - y, x) is False assert _is_modular(exp(Mod(x, 3)) - 1, x) is False assert _is_modular(Mod(3, y) - 1, y) is False def test_invert_modular(): x, y = symbols('x y') n = Dummy('n', integer=True) from sympy.solvers.solveset import _invert_modular as invert_modular # non invertible cases assert invert_modular(Mod(sin(x), 7), S(5), n, x) == (Mod(sin(x), 7), 5) assert invert_modular(Mod(exp(x), 7), S(5), n, x) == (Mod(exp(x), 7), 5) assert invert_modular(Mod(log(x), 7), S(5), n, x) == (Mod(log(x), 7), 5) # a is symbol assert invert_modular(Mod(x, 7), S(5), n, x) == \ (x, ImageSet(Lambda(n, 7*n + 5), S.Integers)) # a.is_Add assert invert_modular(Mod(x + 8, 7), S(5), n, x) == \ (x, ImageSet(Lambda(n, 7*n + 4), S.Integers)) assert invert_modular(Mod(x**2 + x, 7), S(5), n, x) == \ (Mod(x**2 + x, 7), 5) # a.is_Mul assert invert_modular(Mod(3*x, 7), S(5), n, x) == \ (x, ImageSet(Lambda(n, 7*n + 4), S.Integers)) assert invert_modular(Mod((x + 1)*(x + 2), 7), S(5), n, x) == \ (Mod((x + 1)*(x + 2), 7), 5) # a.is_Pow assert invert_modular(Mod(x**4, 7), S(5), n, x) == \ (x, EmptySet()) assert invert_modular(Mod(3**x, 4), S(3), n, x) == \ (x, ImageSet(Lambda(n, 2*n + 1), S.Naturals0)) assert invert_modular(Mod(2**(x**2 + x + 1), 7), S(2), n, x) == \ (x**2 + x + 1, ImageSet(Lambda(n, 3*n + 1), S.Naturals0)) assert invert_modular(Mod(sin(x)**4, 7), S(5), n, x) == (x, EmptySet()) def test_solve_modular(): x = Symbol('x') n = Dummy('n', integer=True) # if rhs has symbol (need to be implemented in future). assert solveset(Mod(x, 4) - x, x, S.Integers) == \ ConditionSet(x, Eq(-x + Mod(x, 4), 0), \ S.Integers) # when _invert_modular fails to invert assert solveset(3 - Mod(sin(x), 7), x, S.Integers) == \ ConditionSet(x, Eq(Mod(sin(x), 7) - 3, 0), S.Integers) assert solveset(3 - Mod(log(x), 7), x, S.Integers) == \ ConditionSet(x, Eq(Mod(log(x), 7) - 3, 0), S.Integers) assert solveset(3 - Mod(exp(x), 7), x, S.Integers) == \ ConditionSet(x, Eq(Mod(exp(x), 7) - 3, 0), S.Integers) # EmptySet solution definitely assert solveset(7 - Mod(x, 5), x, S.Integers) == EmptySet() assert solveset(5 - Mod(x, 5), x, S.Integers) == EmptySet() # Negative m assert solveset(2 + Mod(x, -3), x, S.Integers) == \ ImageSet(Lambda(n, -3*n - 2), S.Integers) assert solveset(4 + Mod(x, -3), x, S.Integers) == EmptySet() # linear expression in Mod assert solveset(3 - Mod(x, 5), x, S.Integers) == ImageSet(Lambda(n, 5*n + 3), S.Integers) assert solveset(3 - Mod(5*x - 8, 7), x, S.Integers) == \ ImageSet(Lambda(n, 7*n + 5), S.Integers) assert solveset(3 - Mod(5*x, 7), x, S.Integers) == \ ImageSet(Lambda(n, 7*n + 2), S.Integers) # higher degree expression in Mod assert solveset(Mod(x**2, 160) - 9, x, S.Integers) == \ Union(ImageSet(Lambda(n, 160*n + 3), S.Integers), ImageSet(Lambda(n, 160*n + 13), S.Integers), ImageSet(Lambda(n, 160*n + 67), S.Integers), ImageSet(Lambda(n, 160*n + 77), S.Integers), ImageSet(Lambda(n, 160*n + 83), S.Integers), ImageSet(Lambda(n, 160*n + 93), S.Integers), ImageSet(Lambda(n, 160*n + 147), S.Integers), ImageSet(Lambda(n, 160*n + 157), S.Integers)) assert solveset(3 - Mod(x**4, 7), x, S.Integers) == EmptySet() assert solveset(Mod(x**4, 17) - 13, x, S.Integers) == \ Union(ImageSet(Lambda(n, 17*n + 3), S.Integers), ImageSet(Lambda(n, 17*n + 5), S.Integers), ImageSet(Lambda(n, 17*n + 12), S.Integers), ImageSet(Lambda(n, 17*n + 14), S.Integers)) # a.is_Pow tests assert solveset(Mod(7**x, 41) - 15, x, S.Integers) == \ ImageSet(Lambda(n, 40*n + 3), S.Naturals0) assert solveset(Mod(12**x, 21) - 18, x, S.Integers) == \ ImageSet(Lambda(n, 6*n + 2), S.Naturals0) assert solveset(Mod(3**x, 4) - 3, x, S.Integers) == \ ImageSet(Lambda(n, 2*n + 1), S.Naturals0) assert solveset(Mod(2**x, 7) - 2 , x, S.Integers) == \ ImageSet(Lambda(n, 3*n + 1), S.Naturals0) assert solveset(Mod(3**(3**x), 4) - 3, x, S.Integers) == \ Intersection(ImageSet(Lambda(n, Intersection({log(2*n + 1)/log(3)}, S.Integers)), S.Naturals0), S.Integers) # Implemented for m without primitive root assert solveset(Mod(x**3, 7) - 2, x, S.Integers) == EmptySet() assert solveset(Mod(x**3, 8) - 1, x, S.Integers) == \ ImageSet(Lambda(n, 8*n + 1), S.Integers) assert solveset(Mod(x**4, 9) - 4, x, S.Integers) == \ Union(ImageSet(Lambda(n, 9*n + 4), S.Integers), ImageSet(Lambda(n, 9*n + 5), S.Integers)) # domain intersection assert solveset(3 - Mod(5*x - 8, 7), x, S.Naturals0) == \ Intersection(ImageSet(Lambda(n, 7*n + 5), S.Integers), S.Naturals0) # Complex args assert solveset(Mod(x, 3) - I, x, S.Integers) == \ EmptySet() assert solveset(Mod(I*x, 3) - 2, x, S.Integers) == \ ConditionSet(x, Eq(Mod(I*x, 3) - 2, 0), S.Integers) assert solveset(Mod(I + x, 3) - 2, x, S.Integers) == \ ConditionSet(x, Eq(Mod(x + I, 3) - 2, 0), S.Integers) # issue 13178 n = symbols('n', integer=True) a = 742938285 z = 1898888478 m = 2**31 - 1 x = 20170816 assert solveset(x - Mod(a**n*z, m), n, S.Integers) == \ ImageSet(Lambda(n, 2147483646*n + 100), S.Naturals0) assert solveset(x - Mod(a**n*z, m), n, S.Naturals0) == \ Intersection(ImageSet(Lambda(n, 2147483646*n + 100), S.Naturals0), S.Naturals0) assert solveset(x - Mod(a**(2*n)*z, m), n, S.Integers) == \ Intersection(ImageSet(Lambda(n, 1073741823*n + 50), S.Naturals0), S.Integers) assert solveset(x - Mod(a**(2*n + 7)*z, m), n, S.Integers) == EmptySet() assert solveset(x - Mod(a**(n - 4)*z, m), n, S.Integers) == \ Intersection(ImageSet(Lambda(n, 2147483646*n + 104), S.Naturals0), S.Integers) @XFAIL def test_solve_modular_fail(): # issue 17373 (https://github.com/sympy/sympy/issues/17373) assert solveset(Mod(x**4, 14) - 11, x, S.Integers) == \ Union(ImageSet(Lambda(n, 14*n + 3), S.Integers), ImageSet(Lambda(n, 14*n + 11), S.Integers)) assert solveset(Mod(x**31, 74) - 43, x, S.Integers) == \ ImageSet(Lambda(n, 74*n + 31), S.Integers) # end of modular tests
e45434786ef872d6509262d2cbb8ca1dd51f6f87aee7f99bc69b4a40a43a9615
from sympy import ( Abs, And, Derivative, Dummy, Eq, Float, Function, Gt, I, Integral, LambertW, Lt, Matrix, Or, Poly, Q, Rational, S, Symbol, Ne, Wild, acos, asin, atan, atanh, cos, cosh, diff, erf, erfinv, erfc, erfcinv, exp, im, log, pi, re, sec, sin, sinh, solve, solve_linear, sqrt, sstr, symbols, sympify, tan, tanh, root, atan2, arg, Mul, SparseMatrix, ask, Tuple, nsolve, oo, E, cbrt, denom, Add, Piecewise, GoldenRatio, TribonacciConstant) from sympy.core.function import nfloat from sympy.solvers import solve_linear_system, solve_linear_system_LU, \ solve_undetermined_coeffs from sympy.solvers.bivariate import _filtered_gens, _solve_lambert, _lambert from sympy.solvers.solvers import _invert, unrad, checksol, posify, _ispow, \ det_quick, det_perm, det_minor, _simple_dens, check_assumptions, denoms, \ failing_assumptions from sympy.physics.units import cm from sympy.polys.rootoftools import CRootOf from sympy.testing.pytest import slow, XFAIL, SKIP, raises from sympy.testing.randtest import verify_numerically as tn from sympy.abc import a, b, c, d, k, h, p, x, y, z, t, q, m def NS(e, n=15, **options): return sstr(sympify(e).evalf(n, **options), full_prec=True) def test_swap_back(): f, g = map(Function, 'fg') fx, gx = f(x), g(x) assert solve([fx + y - 2, fx - gx - 5], fx, y, gx) == \ {fx: gx + 5, y: -gx - 3} assert solve(fx + gx*x - 2, [fx, gx], dict=True)[0] == {fx: 2, gx: 0} assert solve(fx + gx**2*x - y, [fx, gx], dict=True) == [{fx: y - gx**2*x}] assert solve([f(1) - 2, x + 2], dict=True) == [{x: -2, f(1): 2}] def guess_solve_strategy(eq, symbol): try: solve(eq, symbol) return True except (TypeError, NotImplementedError): return False def test_guess_poly(): # polynomial equations assert guess_solve_strategy( S(4), x ) # == GS_POLY assert guess_solve_strategy( x, x ) # == GS_POLY assert guess_solve_strategy( x + a, x ) # == GS_POLY assert guess_solve_strategy( 2*x, x ) # == GS_POLY assert guess_solve_strategy( x + sqrt(2), x) # == GS_POLY assert guess_solve_strategy( x + 2**Rational(1, 4), x) # == GS_POLY assert guess_solve_strategy( x**2 + 1, x ) # == GS_POLY assert guess_solve_strategy( x**2 - 1, x ) # == GS_POLY assert guess_solve_strategy( x*y + y, x ) # == GS_POLY assert guess_solve_strategy( x*exp(y) + y, x) # == GS_POLY assert guess_solve_strategy( (x - y**3)/(y**2*sqrt(1 - y**2)), x) # == GS_POLY def test_guess_poly_cv(): # polynomial equations via a change of variable assert guess_solve_strategy( sqrt(x) + 1, x ) # == GS_POLY_CV_1 assert guess_solve_strategy( x**Rational(1, 3) + sqrt(x) + 1, x ) # == GS_POLY_CV_1 assert guess_solve_strategy( 4*x*(1 - sqrt(x)), x ) # == GS_POLY_CV_1 # polynomial equation multiplying both sides by x**n assert guess_solve_strategy( x + 1/x + y, x ) # == GS_POLY_CV_2 def test_guess_rational_cv(): # rational functions assert guess_solve_strategy( (x + 1)/(x**2 + 2), x) # == GS_RATIONAL assert guess_solve_strategy( (x - y**3)/(y**2*sqrt(1 - y**2)), y) # == GS_RATIONAL_CV_1 # rational functions via the change of variable y -> x**n assert guess_solve_strategy( (sqrt(x) + 1)/(x**Rational(1, 3) + sqrt(x) + 1), x ) \ #== GS_RATIONAL_CV_1 def test_guess_transcendental(): #transcendental functions assert guess_solve_strategy( exp(x) + 1, x ) # == GS_TRANSCENDENTAL assert guess_solve_strategy( 2*cos(x) - y, x ) # == GS_TRANSCENDENTAL assert guess_solve_strategy( exp(x) + exp(-x) - y, x ) # == GS_TRANSCENDENTAL assert guess_solve_strategy(3**x - 10, x) # == GS_TRANSCENDENTAL assert guess_solve_strategy(-3**x + 10, x) # == GS_TRANSCENDENTAL assert guess_solve_strategy(a*x**b - y, x) # == GS_TRANSCENDENTAL def test_solve_args(): # equation container, issue 5113 ans = {x: -3, y: 1} eqs = (x + 5*y - 2, -3*x + 6*y - 15) assert all(solve(container(eqs), x, y) == ans for container in (tuple, list, set, frozenset)) assert solve(Tuple(*eqs), x, y) == ans # implicit symbol to solve for assert set(solve(x**2 - 4)) == set([S(2), -S(2)]) assert solve([x + y - 3, x - y - 5]) == {x: 4, y: -1} assert solve(x - exp(x), x, implicit=True) == [exp(x)] # no symbol to solve for assert solve(42) == solve(42, x) == [] assert solve([1, 2]) == [] # duplicate symbols removed assert solve((x - 3, y + 2), x, y, x) == {x: 3, y: -2} # unordered symbols # only 1 assert solve(y - 3, set([y])) == [3] # more than 1 assert solve(y - 3, set([x, y])) == [{y: 3}] # multiple symbols: take the first linear solution+ # - return as tuple with values for all requested symbols assert solve(x + y - 3, [x, y]) == [(3 - y, y)] # - unless dict is True assert solve(x + y - 3, [x, y], dict=True) == [{x: 3 - y}] # - or no symbols are given assert solve(x + y - 3) == [{x: 3 - y}] # multiple symbols might represent an undetermined coefficients system assert solve(a + b*x - 2, [a, b]) == {a: 2, b: 0} args = (a + b)*x - b**2 + 2, a, b assert solve(*args) == \ [(-sqrt(2), sqrt(2)), (sqrt(2), -sqrt(2))] assert solve(*args, set=True) == \ ([a, b], set([(-sqrt(2), sqrt(2)), (sqrt(2), -sqrt(2))])) assert solve(*args, dict=True) == \ [{b: sqrt(2), a: -sqrt(2)}, {b: -sqrt(2), a: sqrt(2)}] eq = a*x**2 + b*x + c - ((x - h)**2 + 4*p*k)/4/p flags = dict(dict=True) assert solve(eq, [h, p, k], exclude=[a, b, c], **flags) == \ [{k: c - b**2/(4*a), h: -b/(2*a), p: 1/(4*a)}] flags.update(dict(simplify=False)) assert solve(eq, [h, p, k], exclude=[a, b, c], **flags) == \ [{k: (4*a*c - b**2)/(4*a), h: -b/(2*a), p: 1/(4*a)}] # failing undetermined system assert solve(a*x + b**2/(x + 4) - 3*x - 4/x, a, b, dict=True) == \ [{a: (-b**2*x + 3*x**3 + 12*x**2 + 4*x + 16)/(x**2*(x + 4))}] # failed single equation assert solve(1/(1/x - y + exp(y))) == [] raises( NotImplementedError, lambda: solve(exp(x) + sin(x) + exp(y) + sin(y))) # failed system # -- when no symbols given, 1 fails assert solve([y, exp(x) + x]) == [{x: -LambertW(1), y: 0}] # both fail assert solve( (exp(x) - x, exp(y) - y)) == [{x: -LambertW(-1), y: -LambertW(-1)}] # -- when symbols given solve([y, exp(x) + x], x, y) == [(-LambertW(1), 0)] # symbol is a number assert solve(x**2 - pi, pi) == [x**2] # no equations assert solve([], [x]) == [] # overdetermined system # - nonlinear assert solve([(x + y)**2 - 4, x + y - 2]) == [{x: -y + 2}] # - linear assert solve((x + y - 2, 2*x + 2*y - 4)) == {x: -y + 2} # When one or more args are Boolean assert solve([True, Eq(x, 0)], [x], dict=True) == [{x: 0}] assert solve([Eq(x, x), Eq(x, 0), Eq(x, x+1)], [x], dict=True) == [] assert not solve([Eq(x, x+1), x < 2], x) assert solve([Eq(x, 0), x+1<2]) == Eq(x, 0) assert solve([Eq(x, x), Eq(x, x+1)], x) == [] assert solve(True, x) == [] assert solve([x-1, False], [x], set=True) == ([], set()) def test_solve_polynomial1(): assert solve(3*x - 2, x) == [Rational(2, 3)] assert solve(Eq(3*x, 2), x) == [Rational(2, 3)] assert set(solve(x**2 - 1, x)) == set([-S.One, S.One]) assert set(solve(Eq(x**2, 1), x)) == set([-S.One, S.One]) assert solve(x - y**3, x) == [y**3] rx = root(x, 3) assert solve(x - y**3, y) == [ rx, -rx/2 - sqrt(3)*I*rx/2, -rx/2 + sqrt(3)*I*rx/2] a11, a12, a21, a22, b1, b2 = symbols('a11,a12,a21,a22,b1,b2') assert solve([a11*x + a12*y - b1, a21*x + a22*y - b2], x, y) == \ { x: (a22*b1 - a12*b2)/(a11*a22 - a12*a21), y: (a11*b2 - a21*b1)/(a11*a22 - a12*a21), } solution = {y: S.Zero, x: S.Zero} assert solve((x - y, x + y), x, y ) == solution assert solve((x - y, x + y), (x, y)) == solution assert solve((x - y, x + y), [x, y]) == solution assert set(solve(x**3 - 15*x - 4, x)) == set([ -2 + 3**S.Half, S(4), -2 - 3**S.Half ]) assert set(solve((x**2 - 1)**2 - a, x)) == \ set([sqrt(1 + sqrt(a)), -sqrt(1 + sqrt(a)), sqrt(1 - sqrt(a)), -sqrt(1 - sqrt(a))]) def test_solve_polynomial2(): assert solve(4, x) == [] def test_solve_polynomial_cv_1a(): """ Test for solving on equations that can be converted to a polynomial equation using the change of variable y -> x**Rational(p, q) """ assert solve( sqrt(x) - 1, x) == [1] assert solve( sqrt(x) - 2, x) == [4] assert solve( x**Rational(1, 4) - 2, x) == [16] assert solve( x**Rational(1, 3) - 3, x) == [27] assert solve(sqrt(x) + x**Rational(1, 3) + x**Rational(1, 4), x) == [0] def test_solve_polynomial_cv_1b(): assert set(solve(4*x*(1 - a*sqrt(x)), x)) == set([S.Zero, 1/a**2]) assert set(solve(x*(root(x, 3) - 3), x)) == set([S.Zero, S(27)]) def test_solve_polynomial_cv_2(): """ Test for solving on equations that can be converted to a polynomial equation multiplying both sides of the equation by x**m """ assert solve(x + 1/x - 1, x) in \ [[ S.Half + I*sqrt(3)/2, S.Half - I*sqrt(3)/2], [ S.Half - I*sqrt(3)/2, S.Half + I*sqrt(3)/2]] def test_quintics_1(): f = x**5 - 110*x**3 - 55*x**2 + 2310*x + 979 s = solve(f, check=False) for r in s: res = f.subs(x, r.n()).n() assert tn(res, 0) f = x**5 - 15*x**3 - 5*x**2 + 10*x + 20 s = solve(f) for r in s: assert r.func == CRootOf # if one uses solve to get the roots of a polynomial that has a CRootOf # solution, make sure that the use of nfloat during the solve process # doesn't fail. Note: if you want numerical solutions to a polynomial # it is *much* faster to use nroots to get them than to solve the # equation only to get RootOf solutions which are then numerically # evaluated. So for eq = x**5 + 3*x + 7 do Poly(eq).nroots() rather # than [i.n() for i in solve(eq)] to get the numerical roots of eq. assert nfloat(solve(x**5 + 3*x**3 + 7)[0], exponent=False) == \ CRootOf(x**5 + 3*x**3 + 7, 0).n() def test_highorder_poly(): # just testing that the uniq generator is unpacked sol = solve(x**6 - 2*x + 2) assert all(isinstance(i, CRootOf) for i in sol) and len(sol) == 6 def test_quintics_2(): f = x**5 + 15*x + 12 s = solve(f, check=False) for r in s: res = f.subs(x, r.n()).n() assert tn(res, 0) f = x**5 - 15*x**3 - 5*x**2 + 10*x + 20 s = solve(f) for r in s: assert r.func == CRootOf def test_solve_rational(): """Test solve for rational functions""" assert solve( ( x - y**3 )/( (y**2)*sqrt(1 - y**2) ), x) == [y**3] def test_solve_nonlinear(): assert solve(x**2 - y**2, x, y, dict=True) == [{x: -y}, {x: y}] assert solve(x**2 - y**2/exp(x), y, x, dict=True) == [{y: -x*sqrt(exp(x))}, {y: x*sqrt(exp(x))}] def test_issue_8666(): x = symbols('x') assert solve(Eq(x**2 - 1/(x**2 - 4), 4 - 1/(x**2 - 4)), x) == [] assert solve(Eq(x + 1/x, 1/x), x) == [] def test_issue_7228(): assert solve(4**(2*(x**2) + 2*x) - 8, x) == [Rational(-3, 2), S.Half] def test_issue_7190(): assert solve(log(x-3) + log(x+3), x) == [sqrt(10)] def test_linear_system(): x, y, z, t, n = symbols('x, y, z, t, n') assert solve([x - 1, x - y, x - 2*y, y - 1], [x, y]) == [] assert solve([x - 1, x - y, x - 2*y, x - 1], [x, y]) == [] assert solve([x - 1, x - 1, x - y, x - 2*y], [x, y]) == [] assert solve([x + 5*y - 2, -3*x + 6*y - 15], x, y) == {x: -3, y: 1} M = Matrix([[0, 0, n*(n + 1), (n + 1)**2, 0], [n + 1, n + 1, -2*n - 1, -(n + 1), 0], [-1, 0, 1, 0, 0]]) assert solve_linear_system(M, x, y, z, t) == \ {x: -t - t/n, z: -t - t/n, y: 0} assert solve([x + y + z + t, -z - t], x, y, z, t) == {x: -y, z: -t} def test_linear_system_function(): a = Function('a') assert solve([a(0, 0) + a(0, 1) + a(1, 0) + a(1, 1), -a(1, 0) - a(1, 1)], a(0, 0), a(0, 1), a(1, 0), a(1, 1)) == {a(1, 0): -a(1, 1), a(0, 0): -a(0, 1)} def test_linear_systemLU(): n = Symbol('n') M = Matrix([[1, 2, 0, 1], [1, 3, 2*n, 1], [4, -1, n**2, 1]]) assert solve_linear_system_LU(M, [x, y, z]) == {z: -3/(n**2 + 18*n), x: 1 - 12*n/(n**2 + 18*n), y: 6*n/(n**2 + 18*n)} # Note: multiple solutions exist for some of these equations, so the tests # should be expected to break if the implementation of the solver changes # in such a way that a different branch is chosen @slow def test_solve_transcendental(): from sympy.abc import a, b assert solve(exp(x) - 3, x) == [log(3)] assert set(solve((a*x + b)*(exp(x) - 3), x)) == set([-b/a, log(3)]) assert solve(cos(x) - y, x) == [-acos(y) + 2*pi, acos(y)] assert solve(2*cos(x) - y, x) == [-acos(y/2) + 2*pi, acos(y/2)] assert solve(Eq(cos(x), sin(x)), x) == [pi*Rational(-3, 4), pi/4] assert set(solve(exp(x) + exp(-x) - y, x)) in [set([ log(y/2 - sqrt(y**2 - 4)/2), log(y/2 + sqrt(y**2 - 4)/2), ]), set([ log(y - sqrt(y**2 - 4)) - log(2), log(y + sqrt(y**2 - 4)) - log(2)]), set([ log(y/2 - sqrt((y - 2)*(y + 2))/2), log(y/2 + sqrt((y - 2)*(y + 2))/2)])] assert solve(exp(x) - 3, x) == [log(3)] assert solve(Eq(exp(x), 3), x) == [log(3)] assert solve(log(x) - 3, x) == [exp(3)] assert solve(sqrt(3*x) - 4, x) == [Rational(16, 3)] assert solve(3**(x + 2), x) == [] assert solve(3**(2 - x), x) == [] assert solve(x + 2**x, x) == [-LambertW(log(2))/log(2)] assert solve(2*x + 5 + log(3*x - 2), x) == \ [Rational(2, 3) + LambertW(2*exp(Rational(-19, 3))/3)/2] assert solve(3*x + log(4*x), x) == [LambertW(Rational(3, 4))/3] assert set(solve((2*x + 8)*(8 + exp(x)), x)) == set([S(-4), log(8) + pi*I]) eq = 2*exp(3*x + 4) - 3 ans = solve(eq, x) # this generated a failure in flatten assert len(ans) == 3 and all(eq.subs(x, a).n(chop=True) == 0 for a in ans) assert solve(2*log(3*x + 4) - 3, x) == [(exp(Rational(3, 2)) - 4)/3] assert solve(exp(x) + 1, x) == [pi*I] eq = 2*(3*x + 4)**5 - 6*7**(3*x + 9) result = solve(eq, x) ans = [(log(2401) + 5*LambertW((-1 + sqrt(5) + sqrt(2)*I*sqrt(sqrt(5) + \ 5))*log(7**(7*3**Rational(1, 5)/20))* -1))/(-3*log(7)), \ (log(2401) + 5*LambertW((1 + sqrt(5) - sqrt(2)*I*sqrt(5 - \ sqrt(5)))*log(7**(7*3**Rational(1, 5)/20))))/(-3*log(7)), \ (log(2401) + 5*LambertW((1 + sqrt(5) + sqrt(2)*I*sqrt(5 - \ sqrt(5)))*log(7**(7*3**Rational(1, 5)/20))))/(-3*log(7)), \ (log(2401) + 5*LambertW((-sqrt(5) + 1 + sqrt(2)*I*sqrt(sqrt(5) + \ 5))*log(7**(7*3**Rational(1, 5)/20))))/(-3*log(7)), \ (log(2401) + 5*LambertW(-log(7**(7*3**Rational(1, 5)/5))))/(-3*log(7))] assert result == ans # it works if expanded, too assert solve(eq.expand(), x) == result assert solve(z*cos(x) - y, x) == [-acos(y/z) + 2*pi, acos(y/z)] assert solve(z*cos(2*x) - y, x) == [-acos(y/z)/2 + pi, acos(y/z)/2] assert solve(z*cos(sin(x)) - y, x) == [ pi - asin(acos(y/z)), asin(acos(y/z) - 2*pi) + pi, -asin(acos(y/z) - 2*pi), asin(acos(y/z))] assert solve(z*cos(x), x) == [pi/2, pi*Rational(3, 2)] # issue 4508 assert solve(y - b*x/(a + x), x) in [[-a*y/(y - b)], [a*y/(b - y)]] assert solve(y - b*exp(a/x), x) == [a/log(y/b)] # issue 4507 assert solve(y - b/(1 + a*x), x) in [[(b - y)/(a*y)], [-((y - b)/(a*y))]] # issue 4506 assert solve(y - a*x**b, x) == [(y/a)**(1/b)] # issue 4505 assert solve(z**x - y, x) == [log(y)/log(z)] # issue 4504 assert solve(2**x - 10, x) == [log(10)/log(2)] # issue 6744 assert solve(x*y) == [{x: 0}, {y: 0}] assert solve([x*y]) == [{x: 0}, {y: 0}] assert solve(x**y - 1) == [{x: 1}, {y: 0}] assert solve([x**y - 1]) == [{x: 1}, {y: 0}] assert solve(x*y*(x**2 - y**2)) == [{x: 0}, {x: -y}, {x: y}, {y: 0}] assert solve([x*y*(x**2 - y**2)]) == [{x: 0}, {x: -y}, {x: y}, {y: 0}] # issue 4739 assert solve(exp(log(5)*x) - 2**x, x) == [0] # issue 14791 assert solve(exp(log(5)*x) - exp(log(2)*x), x) == [0] f = Function('f') assert solve(y*f(log(5)*x) - y*f(log(2)*x), x) == [0] assert solve(f(x) - f(0), x) == [0] assert solve(f(x) - f(2 - x), x) == [1] raises(NotImplementedError, lambda: solve(f(x, y) - f(1, 2), x)) raises(NotImplementedError, lambda: solve(f(x, y) - f(2 - x, 2), x)) raises(ValueError, lambda: solve(f(x, y) - f(1 - x), x)) raises(ValueError, lambda: solve(f(x, y) - f(1), x)) # misc # make sure that the right variables is picked up in tsolve # shouldn't generate a GeneratorsNeeded error in _tsolve when the NaN is generated # for eq_down. Actual answers, as determined numerically are approx. +/- 0.83 raises(NotImplementedError, lambda: solve(sinh(x)*sinh(sinh(x)) + cosh(x)*cosh(sinh(x)) - 3)) # watch out for recursive loop in tsolve raises(NotImplementedError, lambda: solve((x + 2)**y*x - 3, x)) # issue 7245 assert solve(sin(sqrt(x))) == [0, pi**2] # issue 7602 a, b = symbols('a, b', real=True, negative=False) assert str(solve(Eq(a, 0.5 - cos(pi*b)/2), b)) == \ '[2.0 - 0.318309886183791*acos(1.0 - 2.0*a), 0.318309886183791*acos(1.0 - 2.0*a)]' # issue 15325 assert solve(y**(1/x) - z, x) == [log(y)/log(z)] def test_solve_for_functions_derivatives(): t = Symbol('t') x = Function('x')(t) y = Function('y')(t) a11, a12, a21, a22, b1, b2 = symbols('a11,a12,a21,a22,b1,b2') soln = solve([a11*x + a12*y - b1, a21*x + a22*y - b2], x, y) assert soln == { x: (a22*b1 - a12*b2)/(a11*a22 - a12*a21), y: (a11*b2 - a21*b1)/(a11*a22 - a12*a21), } assert solve(x - 1, x) == [1] assert solve(3*x - 2, x) == [Rational(2, 3)] soln = solve([a11*x.diff(t) + a12*y.diff(t) - b1, a21*x.diff(t) + a22*y.diff(t) - b2], x.diff(t), y.diff(t)) assert soln == { y.diff(t): (a11*b2 - a21*b1)/(a11*a22 - a12*a21), x.diff(t): (a22*b1 - a12*b2)/(a11*a22 - a12*a21) } assert solve(x.diff(t) - 1, x.diff(t)) == [1] assert solve(3*x.diff(t) - 2, x.diff(t)) == [Rational(2, 3)] eqns = set((3*x - 1, 2*y - 4)) assert solve(eqns, set((x, y))) == { x: Rational(1, 3), y: 2 } x = Symbol('x') f = Function('f') F = x**2 + f(x)**2 - 4*x - 1 assert solve(F.diff(x), diff(f(x), x)) == [(-x + 2)/f(x)] # Mixed cased with a Symbol and a Function x = Symbol('x') y = Function('y')(t) soln = solve([a11*x + a12*y.diff(t) - b1, a21*x + a22*y.diff(t) - b2], x, y.diff(t)) assert soln == { y.diff(t): (a11*b2 - a21*b1)/(a11*a22 - a12*a21), x: (a22*b1 - a12*b2)/(a11*a22 - a12*a21) } def test_issue_3725(): f = Function('f') F = x**2 + f(x)**2 - 4*x - 1 e = F.diff(x) assert solve(e, f(x).diff(x)) in [[(2 - x)/f(x)], [-((x - 2)/f(x))]] def test_issue_3870(): a, b, c, d = symbols('a b c d') A = Matrix(2, 2, [a, b, c, d]) B = Matrix(2, 2, [0, 2, -3, 0]) C = Matrix(2, 2, [1, 2, 3, 4]) assert solve(A*B - C, [a, b, c, d]) == {a: 1, b: Rational(-1, 3), c: 2, d: -1} assert solve([A*B - C], [a, b, c, d]) == {a: 1, b: Rational(-1, 3), c: 2, d: -1} assert solve(Eq(A*B, C), [a, b, c, d]) == {a: 1, b: Rational(-1, 3), c: 2, d: -1} assert solve([A*B - B*A], [a, b, c, d]) == {a: d, b: Rational(-2, 3)*c} assert solve([A*C - C*A], [a, b, c, d]) == {a: d - c, b: Rational(2, 3)*c} assert solve([A*B - B*A, A*C - C*A], [a, b, c, d]) == {a: d, b: 0, c: 0} assert solve([Eq(A*B, B*A)], [a, b, c, d]) == {a: d, b: Rational(-2, 3)*c} assert solve([Eq(A*C, C*A)], [a, b, c, d]) == {a: d - c, b: Rational(2, 3)*c} assert solve([Eq(A*B, B*A), Eq(A*C, C*A)], [a, b, c, d]) == {a: d, b: 0, c: 0} def test_solve_linear(): w = Wild('w') assert solve_linear(x, x) == (0, 1) assert solve_linear(x, exclude=[x]) == (0, 1) assert solve_linear(x, symbols=[w]) == (0, 1) assert solve_linear(x, y - 2*x) in [(x, y/3), (y, 3*x)] assert solve_linear(x, y - 2*x, exclude=[x]) == (y, 3*x) assert solve_linear(3*x - y, 0) in [(x, y/3), (y, 3*x)] assert solve_linear(3*x - y, 0, [x]) == (x, y/3) assert solve_linear(3*x - y, 0, [y]) == (y, 3*x) assert solve_linear(x**2/y, 1) == (y, x**2) assert solve_linear(w, x) in [(w, x), (x, w)] assert solve_linear(cos(x)**2 + sin(x)**2 + 2 + y) == \ (y, -2 - cos(x)**2 - sin(x)**2) assert solve_linear(cos(x)**2 + sin(x)**2 + 2 + y, symbols=[x]) == (0, 1) assert solve_linear(Eq(x, 3)) == (x, 3) assert solve_linear(1/(1/x - 2)) == (0, 0) assert solve_linear((x + 1)*exp(-x), symbols=[x]) == (x, -1) assert solve_linear((x + 1)*exp(x), symbols=[x]) == ((x + 1)*exp(x), 1) assert solve_linear(x*exp(-x**2), symbols=[x]) == (x, 0) assert solve_linear(0**x - 1) == (0**x - 1, 1) assert solve_linear(1 + 1/(x - 1)) == (x, 0) eq = y*cos(x)**2 + y*sin(x)**2 - y # = y*(1 - 1) = 0 assert solve_linear(eq) == (0, 1) eq = cos(x)**2 + sin(x)**2 # = 1 assert solve_linear(eq) == (0, 1) raises(ValueError, lambda: solve_linear(Eq(x, 3), 3)) def test_solve_undetermined_coeffs(): assert solve_undetermined_coeffs(a*x**2 + b*x**2 + b*x + 2*c*x + c + 1, [a, b, c], x) == \ {a: -2, b: 2, c: -1} # Test that rational functions work assert solve_undetermined_coeffs(a/x + b/(x + 1) - (2*x + 1)/(x**2 + x), [a, b], x) == \ {a: 1, b: 1} # Test cancellation in rational functions assert solve_undetermined_coeffs(((c + 1)*a*x**2 + (c + 1)*b*x**2 + (c + 1)*b*x + (c + 1)*2*c*x + (c + 1)**2)/(c + 1), [a, b, c], x) == \ {a: -2, b: 2, c: -1} def test_solve_inequalities(): x = Symbol('x') sol = And(S.Zero < x, x < oo) assert solve(x + 1 > 1) == sol assert solve([x + 1 > 1]) == sol assert solve([x + 1 > 1], x) == sol assert solve([x + 1 > 1], [x]) == sol system = [Lt(x**2 - 2, 0), Gt(x**2 - 1, 0)] assert solve(system) == \ And(Or(And(Lt(-sqrt(2), x), Lt(x, -1)), And(Lt(1, x), Lt(x, sqrt(2)))), Eq(0, 0)) x = Symbol('x', real=True) system = [Lt(x**2 - 2, 0), Gt(x**2 - 1, 0)] assert solve(system) == \ Or(And(Lt(-sqrt(2), x), Lt(x, -1)), And(Lt(1, x), Lt(x, sqrt(2)))) # issues 6627, 3448 assert solve((x - 3)/(x - 2) < 0, x) == And(Lt(2, x), Lt(x, 3)) assert solve(x/(x + 1) > 1, x) == And(Lt(-oo, x), Lt(x, -1)) assert solve(sin(x) > S.Half) == And(pi/6 < x, x < pi*Rational(5, 6)) assert solve(Eq(False, x < 1)) == (S.One <= x) & (x < oo) assert solve(Eq(True, x < 1)) == (-oo < x) & (x < 1) assert solve(Eq(x < 1, False)) == (S.One <= x) & (x < oo) assert solve(Eq(x < 1, True)) == (-oo < x) & (x < 1) assert solve(Eq(False, x)) == False assert solve(Eq(True, x)) == True assert solve(Eq(False, ~x)) == True assert solve(Eq(True, ~x)) == False assert solve(Ne(True, x)) == False def test_issue_4793(): assert solve(1/x) == [] assert solve(x*(1 - 5/x)) == [5] assert solve(x + sqrt(x) - 2) == [1] assert solve(-(1 + x)/(2 + x)**2 + 1/(2 + x)) == [] assert solve(-x**2 - 2*x + (x + 1)**2 - 1) == [] assert solve((x/(x + 1) + 3)**(-2)) == [] assert solve(x/sqrt(x**2 + 1), x) == [0] assert solve(exp(x) - y, x) == [log(y)] assert solve(exp(x)) == [] assert solve(x**2 + x + sin(y)**2 + cos(y)**2 - 1, x) in [[0, -1], [-1, 0]] eq = 4*3**(5*x + 2) - 7 ans = solve(eq, x) assert len(ans) == 5 and all(eq.subs(x, a).n(chop=True) == 0 for a in ans) assert solve(log(x**2) - y**2/exp(x), x, y, set=True) == ( [x, y], {(x, sqrt(exp(x) * log(x ** 2))), (x, -sqrt(exp(x) * log(x ** 2)))}) assert solve(x**2*z**2 - z**2*y**2) == [{x: -y}, {x: y}, {z: 0}] assert solve((x - 1)/(1 + 1/(x - 1))) == [] assert solve(x**(y*z) - x, x) == [1] raises(NotImplementedError, lambda: solve(log(x) - exp(x), x)) raises(NotImplementedError, lambda: solve(2**x - exp(x) - 3)) def test_PR1964(): # issue 5171 assert solve(sqrt(x)) == solve(sqrt(x**3)) == [0] assert solve(sqrt(x - 1)) == [1] # issue 4462 a = Symbol('a') assert solve(-3*a/sqrt(x), x) == [] # issue 4486 assert solve(2*x/(x + 2) - 1, x) == [2] # issue 4496 assert set(solve((x**2/(7 - x)).diff(x))) == set([S.Zero, S(14)]) # issue 4695 f = Function('f') assert solve((3 - 5*x/f(x))*f(x), f(x)) == [x*Rational(5, 3)] # issue 4497 assert solve(1/root(5 + x, 5) - 9, x) == [Rational(-295244, 59049)] assert solve(sqrt(x) + sqrt(sqrt(x)) - 4) == [(Rational(-1, 2) + sqrt(17)/2)**4] assert set(solve(Poly(sqrt(exp(x)) + sqrt(exp(-x)) - 4))) in \ [ set([log((-sqrt(3) + 2)**2), log((sqrt(3) + 2)**2)]), set([2*log(-sqrt(3) + 2), 2*log(sqrt(3) + 2)]), set([log(-4*sqrt(3) + 7), log(4*sqrt(3) + 7)]), ] assert set(solve(Poly(exp(x) + exp(-x) - 4))) == \ set([log(-sqrt(3) + 2), log(sqrt(3) + 2)]) assert set(solve(x**y + x**(2*y) - 1, x)) == \ set([(Rational(-1, 2) + sqrt(5)/2)**(1/y), (Rational(-1, 2) - sqrt(5)/2)**(1/y)]) assert solve(exp(x/y)*exp(-z/y) - 2, y) == [(x - z)/log(2)] assert solve( x**z*y**z - 2, z) in [[log(2)/(log(x) + log(y))], [log(2)/(log(x*y))]] # if you do inversion too soon then multiple roots (as for the following) # will be missed, e.g. if exp(3*x) = exp(3) -> 3*x = 3 E = S.Exp1 assert solve(exp(3*x) - exp(3), x) in [ [1, log(E*(Rational(-1, 2) - sqrt(3)*I/2)), log(E*(Rational(-1, 2) + sqrt(3)*I/2))], [1, log(-E/2 - sqrt(3)*E*I/2), log(-E/2 + sqrt(3)*E*I/2)], ] # coverage test p = Symbol('p', positive=True) assert solve((1/p + 1)**(p + 1)) == [] def test_issue_5197(): x = Symbol('x', real=True) assert solve(x**2 + 1, x) == [] n = Symbol('n', integer=True, positive=True) assert solve((n - 1)*(n + 2)*(2*n - 1), n) == [1] x = Symbol('x', positive=True) y = Symbol('y') assert solve([x + 5*y - 2, -3*x + 6*y - 15], x, y) == [] # not {x: -3, y: 1} b/c x is positive # The solution following should not contain (-sqrt(2), sqrt(2)) assert solve((x + y)*n - y**2 + 2, x, y) == [(sqrt(2), -sqrt(2))] y = Symbol('y', positive=True) # The solution following should not contain {y: -x*exp(x/2)} assert solve(x**2 - y**2/exp(x), y, x, dict=True) == [{y: x*exp(x/2)}] x, y, z = symbols('x y z', positive=True) assert solve(z**2*x**2 - z**2*y**2/exp(x), y, x, z, dict=True) == [{y: x*exp(x/2)}] def test_checking(): assert set( solve(x*(x - y/x), x, check=False)) == set([sqrt(y), S.Zero, -sqrt(y)]) assert set(solve(x*(x - y/x), x, check=True)) == set([sqrt(y), -sqrt(y)]) # {x: 0, y: 4} sets denominator to 0 in the following so system should return None assert solve((1/(1/x + 2), 1/(y - 3) - 1)) == [] # 0 sets denominator of 1/x to zero so None is returned assert solve(1/(1/x + 2)) == [] def test_issue_4671_4463_4467(): assert solve((sqrt(x**2 - 1) - 2)) in ([sqrt(5), -sqrt(5)], [-sqrt(5), sqrt(5)]) assert solve((2**exp(y**2/x) + 2)/(x**2 + 15), y) == [ -sqrt(x*log(1 + I*pi/log(2))), sqrt(x*log(1 + I*pi/log(2)))] C1, C2 = symbols('C1 C2') f = Function('f') assert solve(C1 + C2/x**2 - exp(-f(x)), f(x)) == [log(x**2/(C1*x**2 + C2))] a = Symbol('a') E = S.Exp1 assert solve(1 - log(a + 4*x**2), x) in ( [-sqrt(-a + E)/2, sqrt(-a + E)/2], [sqrt(-a + E)/2, -sqrt(-a + E)/2] ) assert solve(log(a**(-3) - x**2)/a, x) in ( [-sqrt(-1 + a**(-3)), sqrt(-1 + a**(-3))], [sqrt(-1 + a**(-3)), -sqrt(-1 + a**(-3))],) assert solve(1 - log(a + 4*x**2), x) in ( [-sqrt(-a + E)/2, sqrt(-a + E)/2], [sqrt(-a + E)/2, -sqrt(-a + E)/2],) assert set(solve(( a**2 + 1) * (sin(a*x) + cos(a*x)), x)) == set([-pi/(4*a), 3*pi/(4*a)]) assert solve(3 - (sinh(a*x) + cosh(a*x)), x) == [log(3)/a] assert set(solve(3 - (sinh(a*x) + cosh(a*x)**2), x)) == \ set([log(-2 + sqrt(5))/a, log(-sqrt(2) + 1)/a, log(-sqrt(5) - 2)/a, log(1 + sqrt(2))/a]) assert solve(atan(x) - 1) == [tan(1)] def test_issue_5132(): r, t = symbols('r,t') assert set(solve([r - x**2 - y**2, tan(t) - y/x], [x, y])) == \ set([( -sqrt(r*cos(t)**2), -1*sqrt(r*cos(t)**2)*tan(t)), (sqrt(r*cos(t)**2), sqrt(r*cos(t)**2)*tan(t))]) assert solve([exp(x) - sin(y), 1/y - 3], [x, y]) == \ [(log(sin(Rational(1, 3))), Rational(1, 3))] assert solve([exp(x) - sin(y), 1/exp(y) - 3], [x, y]) == \ [(log(-sin(log(3))), -log(3))] assert set(solve([exp(x) - sin(y), y**2 - 4], [x, y])) == \ set([(log(-sin(2)), -S(2)), (log(sin(2)), S(2))]) eqs = [exp(x)**2 - sin(y) + z**2, 1/exp(y) - 3] assert solve(eqs, set=True) == \ ([x, y], set([ (log(-sqrt(-z**2 - sin(log(3)))), -log(3)), (log(-z**2 - sin(log(3)))/2, -log(3))])) assert solve(eqs, x, z, set=True) == ( [x, z], {(log(-z**2 + sin(y))/2, z), (log(-sqrt(-z**2 + sin(y))), z)}) assert set(solve(eqs, x, y)) == \ set([ (log(-sqrt(-z**2 - sin(log(3)))), -log(3)), (log(-z**2 - sin(log(3)))/2, -log(3))]) assert set(solve(eqs, y, z)) == \ set([ (-log(3), -sqrt(-exp(2*x) - sin(log(3)))), (-log(3), sqrt(-exp(2*x) - sin(log(3))))]) eqs = [exp(x)**2 - sin(y) + z, 1/exp(y) - 3] assert solve(eqs, set=True) == ([x, y], set( [ (log(-sqrt(-z - sin(log(3)))), -log(3)), (log(-z - sin(log(3)))/2, -log(3))])) assert solve(eqs, x, z, set=True) == ( [x, z], {(log(-sqrt(-z + sin(y))), z), (log(-z + sin(y))/2, z)}) assert set(solve(eqs, x, y)) == set( [ (log(-sqrt(-z - sin(log(3)))), -log(3)), (log(-z - sin(log(3)))/2, -log(3))]) assert solve(eqs, z, y) == \ [(-exp(2*x) - sin(log(3)), -log(3))] assert solve((sqrt(x**2 + y**2) - sqrt(10), x + y - 4), set=True) == ( [x, y], set([(S.One, S(3)), (S(3), S.One)])) assert set(solve((sqrt(x**2 + y**2) - sqrt(10), x + y - 4), x, y)) == \ set([(S.One, S(3)), (S(3), S.One)]) def test_issue_5335(): lam, a0, conc = symbols('lam a0 conc') a = 0.005 b = 0.743436700916726 eqs = [lam + 2*y - a0*(1 - x/2)*x - a*x/2*x, a0*(1 - x/2)*x - 1*y - b*y, x + y - conc] sym = [x, y, a0] # there are 4 solutions obtained manually but only two are valid assert len(solve(eqs, sym, manual=True, minimal=True)) == 2 assert len(solve(eqs, sym)) == 2 # cf below with rational=False @SKIP("Hangs") def _test_issue_5335_float(): # gives ZeroDivisionError: polynomial division lam, a0, conc = symbols('lam a0 conc') a = 0.005 b = 0.743436700916726 eqs = [lam + 2*y - a0*(1 - x/2)*x - a*x/2*x, a0*(1 - x/2)*x - 1*y - b*y, x + y - conc] sym = [x, y, a0] assert len(solve(eqs, sym, rational=False)) == 2 def test_issue_5767(): assert set(solve([x**2 + y + 4], [x])) == \ set([(-sqrt(-y - 4),), (sqrt(-y - 4),)]) def test_polysys(): assert set(solve([x**2 + 2/y - 2, x + y - 3], [x, y])) == \ set([(S.One, S(2)), (1 + sqrt(5), 2 - sqrt(5)), (1 - sqrt(5), 2 + sqrt(5))]) assert solve([x**2 + y - 2, x**2 + y]) == [] # the ordering should be whatever the user requested assert solve([x**2 + y - 3, x - y - 4], (x, y)) != solve([x**2 + y - 3, x - y - 4], (y, x)) @slow def test_unrad1(): raises(NotImplementedError, lambda: unrad(sqrt(x) + sqrt(x + 1) + sqrt(1 - sqrt(x)) + 3)) raises(NotImplementedError, lambda: unrad(sqrt(x) + (x + 1)**Rational(1, 3) + 2*sqrt(y))) s = symbols('s', cls=Dummy) # checkers to deal with possibility of answer coming # back with a sign change (cf issue 5203) def check(rv, ans): assert bool(rv[1]) == bool(ans[1]) if ans[1]: return s_check(rv, ans) e = rv[0].expand() a = ans[0].expand() return e in [a, -a] and rv[1] == ans[1] def s_check(rv, ans): # get the dummy rv = list(rv) d = rv[0].atoms(Dummy) reps = list(zip(d, [s]*len(d))) # replace s with this dummy rv = (rv[0].subs(reps).expand(), [rv[1][0].subs(reps), rv[1][1].subs(reps)]) ans = (ans[0].subs(reps).expand(), [ans[1][0].subs(reps), ans[1][1].subs(reps)]) return str(rv[0]) in [str(ans[0]), str(-ans[0])] and \ str(rv[1]) == str(ans[1]) assert check(unrad(sqrt(x)), (x, [])) assert check(unrad(sqrt(x) + 1), (x - 1, [])) assert check(unrad(sqrt(x) + root(x, 3) + 2), (s**3 + s**2 + 2, [s, s**6 - x])) assert check(unrad(sqrt(x)*root(x, 3) + 2), (x**5 - 64, [])) assert check(unrad(sqrt(x) + (x + 1)**Rational(1, 3)), (x**3 - (x + 1)**2, [])) assert check(unrad(sqrt(x) + sqrt(x + 1) + sqrt(2*x)), (-2*sqrt(2)*x - 2*x + 1, [])) assert check(unrad(sqrt(x) + sqrt(x + 1) + 2), (16*x - 9, [])) assert check(unrad(sqrt(x) + sqrt(x + 1) + sqrt(1 - x)), (5*x**2 - 4*x, [])) assert check(unrad(a*sqrt(x) + b*sqrt(x) + c*sqrt(y) + d*sqrt(y)), ((a*sqrt(x) + b*sqrt(x))**2 - (c*sqrt(y) + d*sqrt(y))**2, [])) assert check(unrad(sqrt(x) + sqrt(1 - x)), (2*x - 1, [])) assert check(unrad(sqrt(x) + sqrt(1 - x) - 3), (x**2 - x + 16, [])) assert check(unrad(sqrt(x) + sqrt(1 - x) + sqrt(2 + x)), (5*x**2 - 2*x + 1, [])) assert unrad(sqrt(x) + sqrt(1 - x) + sqrt(2 + x) - 3) in [ (25*x**4 + 376*x**3 + 1256*x**2 - 2272*x + 784, []), (25*x**8 - 476*x**6 + 2534*x**4 - 1468*x**2 + 169, [])] assert unrad(sqrt(x) + sqrt(1 - x) + sqrt(2 + x) - sqrt(1 - 2*x)) == \ (41*x**4 + 40*x**3 + 232*x**2 - 160*x + 16, []) # orig root at 0.487 assert check(unrad(sqrt(x) + sqrt(x + 1)), (S.One, [])) eq = sqrt(x) + sqrt(x + 1) + sqrt(1 - sqrt(x)) assert check(unrad(eq), (16*x**2 - 9*x, [])) assert set(solve(eq, check=False)) == set([S.Zero, Rational(9, 16)]) assert solve(eq) == [] # but this one really does have those solutions assert set(solve(sqrt(x) - sqrt(x + 1) + sqrt(1 - sqrt(x)))) == \ set([S.Zero, Rational(9, 16)]) assert check(unrad(sqrt(x) + root(x + 1, 3) + 2*sqrt(y), y), (S('2*sqrt(x)*(x + 1)**(1/3) + x - 4*y + (x + 1)**(2/3)'), [])) assert check(unrad(sqrt(x/(1 - x)) + (x + 1)**Rational(1, 3)), (x**5 - x**4 - x**3 + 2*x**2 + x - 1, [])) assert check(unrad(sqrt(x/(1 - x)) + 2*sqrt(y), y), (4*x*y + x - 4*y, [])) assert check(unrad(sqrt(x)*sqrt(1 - x) + 2, x), (x**2 - x + 4, [])) # http://tutorial.math.lamar.edu/ # Classes/Alg/SolveRadicalEqns.aspx#Solve_Rad_Ex2_a assert solve(Eq(x, sqrt(x + 6))) == [3] assert solve(Eq(x + sqrt(x - 4), 4)) == [4] assert solve(Eq(1, x + sqrt(2*x - 3))) == [] assert set(solve(Eq(sqrt(5*x + 6) - 2, x))) == set([-S.One, S(2)]) assert set(solve(Eq(sqrt(2*x - 1) - sqrt(x - 4), 2))) == set([S(5), S(13)]) assert solve(Eq(sqrt(x + 7) + 2, sqrt(3 - x))) == [-6] # http://www.purplemath.com/modules/solverad.htm assert solve((2*x - 5)**Rational(1, 3) - 3) == [16] assert set(solve(x + 1 - root(x**4 + 4*x**3 - x, 4))) == \ set([Rational(-1, 2), Rational(-1, 3)]) assert set(solve(sqrt(2*x**2 - 7) - (3 - x))) == set([-S(8), S(2)]) assert solve(sqrt(2*x + 9) - sqrt(x + 1) - sqrt(x + 4)) == [0] assert solve(sqrt(x + 4) + sqrt(2*x - 1) - 3*sqrt(x - 1)) == [5] assert solve(sqrt(x)*sqrt(x - 7) - 12) == [16] assert solve(sqrt(x - 3) + sqrt(x) - 3) == [4] assert solve(sqrt(9*x**2 + 4) - (3*x + 2)) == [0] assert solve(sqrt(x) - 2 - 5) == [49] assert solve(sqrt(x - 3) - sqrt(x) - 3) == [] assert solve(sqrt(x - 1) - x + 7) == [10] assert solve(sqrt(x - 2) - 5) == [27] assert solve(sqrt(17*x - sqrt(x**2 - 5)) - 7) == [3] assert solve(sqrt(x) - sqrt(x - 1) + sqrt(sqrt(x))) == [] # don't posify the expression in unrad and do use _mexpand z = sqrt(2*x + 1)/sqrt(x) - sqrt(2 + 1/x) p = posify(z)[0] assert solve(p) == [] assert solve(z) == [] assert solve(z + 6*I) == [Rational(-1, 11)] assert solve(p + 6*I) == [] # issue 8622 assert unrad((root(x + 1, 5) - root(x, 3))) == ( x**5 - x**3 - 3*x**2 - 3*x - 1, []) # issue #8679 assert check(unrad(x + root(x, 3) + root(x, 3)**2 + sqrt(y), x), (s**3 + s**2 + s + sqrt(y), [s, s**3 - x])) # for coverage assert check(unrad(sqrt(x) + root(x, 3) + y), (s**3 + s**2 + y, [s, s**6 - x])) assert solve(sqrt(x) + root(x, 3) - 2) == [1] raises(NotImplementedError, lambda: solve(sqrt(x) + root(x, 3) + root(x + 1, 5) - 2)) # fails through a different code path raises(NotImplementedError, lambda: solve(-sqrt(2) + cosh(x)/x)) # unrad some assert solve(sqrt(x + root(x, 3))+root(x - y, 5), y) == [ x + (x**Rational(1, 3) + x)**Rational(5, 2)] assert check(unrad(sqrt(x) - root(x + 1, 3)*sqrt(x + 2) + 2), (s**10 + 8*s**8 + 24*s**6 - 12*s**5 - 22*s**4 - 160*s**3 - 212*s**2 - 192*s - 56, [s, s**2 - x])) e = root(x + 1, 3) + root(x, 3) assert unrad(e) == (2*x + 1, []) eq = (sqrt(x) + sqrt(x + 1) + sqrt(1 - x) - 6*sqrt(5)/5) assert check(unrad(eq), (15625*x**4 + 173000*x**3 + 355600*x**2 - 817920*x + 331776, [])) assert check(unrad(root(x, 4) + root(x, 4)**3 - 1), (s**3 + s - 1, [s, s**4 - x])) assert check(unrad(root(x, 2) + root(x, 2)**3 - 1), (x**3 + 2*x**2 + x - 1, [])) assert unrad(x**0.5) is None assert check(unrad(t + root(x + y, 5) + root(x + y, 5)**3), (s**3 + s + t, [s, s**5 - x - y])) assert check(unrad(x + root(x + y, 5) + root(x + y, 5)**3, y), (s**3 + s + x, [s, s**5 - x - y])) assert check(unrad(x + root(x + y, 5) + root(x + y, 5)**3, x), (s**5 + s**3 + s - y, [s, s**5 - x - y])) assert check(unrad(root(x - 1, 3) + root(x + 1, 5) + root(2, 5)), (s**5 + 5*2**Rational(1, 5)*s**4 + s**3 + 10*2**Rational(2, 5)*s**3 + 10*2**Rational(3, 5)*s**2 + 5*2**Rational(4, 5)*s + 4, [s, s**3 - x + 1])) raises(NotImplementedError, lambda: unrad((root(x, 2) + root(x, 3) + root(x, 4)).subs(x, x**5 - x + 1))) # the simplify flag should be reset to False for unrad results; # if it's not then this next test will take a long time assert solve(root(x, 3) + root(x, 5) - 2) == [1] eq = (sqrt(x) + sqrt(x + 1) + sqrt(1 - x) - 6*sqrt(5)/5) assert check(unrad(eq), ((5*x - 4)*(3125*x**3 + 37100*x**2 + 100800*x - 82944), [])) ans = S(''' [4/5, -1484/375 + 172564/(140625*(114*sqrt(12657)/78125 + 12459439/52734375)**(1/3)) + 4*(114*sqrt(12657)/78125 + 12459439/52734375)**(1/3)]''') assert solve(eq) == ans # duplicate radical handling assert check(unrad(sqrt(x + root(x + 1, 3)) - root(x + 1, 3) - 2), (s**3 - s**2 - 3*s - 5, [s, s**3 - x - 1])) # cov post-processing e = root(x**2 + 1, 3) - root(x**2 - 1, 5) - 2 assert check(unrad(e), (s**5 - 10*s**4 + 39*s**3 - 80*s**2 + 80*s - 30, [s, s**3 - x**2 - 1])) e = sqrt(x + root(x + 1, 2)) - root(x + 1, 3) - 2 assert check(unrad(e), (s**6 - 2*s**5 - 7*s**4 - 3*s**3 + 26*s**2 + 40*s + 25, [s, s**3 - x - 1])) assert check(unrad(e, _reverse=True), (s**6 - 14*s**5 + 73*s**4 - 187*s**3 + 276*s**2 - 228*s + 89, [s, s**2 - x - sqrt(x + 1)])) # this one needs r0, r1 reversal to work assert check(unrad(sqrt(x + sqrt(root(x, 3) - 1)) - root(x, 6) - 2), (s**12 - 2*s**8 - 8*s**7 - 8*s**6 + s**4 + 8*s**3 + 23*s**2 + 32*s + 17, [s, s**6 - x])) # is this needed? #assert unrad(root(cosh(x), 3)/x*root(x + 1, 5) - 1) == ( # x**15 - x**3*cosh(x)**5 - 3*x**2*cosh(x)**5 - 3*x*cosh(x)**5 - cosh(x)**5, []) raises(NotImplementedError, lambda: unrad(sqrt(cosh(x)/x) + root(x + 1,3)*sqrt(x) - 1)) assert unrad(S('(x+y)**(2*y/3) + (x+y)**(1/3) + 1')) is None assert check(unrad(S('(x+y)**(2*y/3) + (x+y)**(1/3) + 1'), x), (s**(2*y) + s + 1, [s, s**3 - x - y])) # This tests two things: that if full unrad is attempted and fails # the solution should still be found; also it tests that the use of # composite assert len(solve(sqrt(y)*x + x**3 - 1, x)) == 3 assert len(solve(-512*y**3 + 1344*(x + 2)**Rational(1, 3)*y**2 - 1176*(x + 2)**Rational(2, 3)*y - 169*x + 686, y, _unrad=False)) == 3 # watch out for when the cov doesn't involve the symbol of interest eq = S('-x + (7*y/8 - (27*x/2 + 27*sqrt(x**2)/2)**(1/3)/3)**3 - 1') assert solve(eq, y) == [ 4*2**Rational(2, 3)*(27*x + 27*sqrt(x**2))**Rational(1, 3)/21 - (Rational(-1, 2) - sqrt(3)*I/2)*(x*Rational(-6912, 343) + sqrt((x*Rational(-13824, 343) - Rational(13824, 343))**2)/2 - Rational(6912, 343))**Rational(1, 3)/3, 4*2**Rational(2, 3)*(27*x + 27*sqrt(x**2))**Rational(1, 3)/21 - (Rational(-1, 2) + sqrt(3)*I/2)*(x*Rational(-6912, 343) + sqrt((x*Rational(-13824, 343) - Rational(13824, 343))**2)/2 - Rational(6912, 343))**Rational(1, 3)/3, 4*2**Rational(2, 3)*(27*x + 27*sqrt(x**2))**Rational(1, 3)/21 - (x*Rational(-6912, 343) + sqrt((x*Rational(-13824, 343) - Rational(13824, 343))**2)/2 - Rational(6912, 343))**Rational(1, 3)/3] eq = root(x + 1, 3) - (root(x, 3) + root(x, 5)) assert check(unrad(eq), (3*s**13 + 3*s**11 + s**9 - 1, [s, s**15 - x])) assert check(unrad(eq - 2), (3*s**13 + 3*s**11 + 6*s**10 + s**9 + 12*s**8 + 6*s**6 + 12*s**5 + 12*s**3 + 7, [s, s**15 - x])) assert check(unrad(root(x, 3) - root(x + 1, 4)/2 + root(x + 2, 3)), (4096*s**13 + 960*s**12 + 48*s**11 - s**10 - 1728*s**4, [s, s**4 - x - 1])) # orig expr has two real roots: -1, -.389 assert check(unrad(root(x, 3) + root(x + 1, 4) - root(x + 2, 3)/2), (343*s**13 + 2904*s**12 + 1344*s**11 + 512*s**10 - 1323*s**9 - 3024*s**8 - 1728*s**7 + 1701*s**5 + 216*s**4 - 729*s, [s, s**4 - x - 1])) # orig expr has one real root: -0.048 assert check(unrad(root(x, 3)/2 - root(x + 1, 4) + root(x + 2, 3)), (729*s**13 - 216*s**12 + 1728*s**11 - 512*s**10 + 1701*s**9 - 3024*s**8 + 1344*s**7 + 1323*s**5 - 2904*s**4 + 343*s, [s, s**4 - x - 1])) # orig expr has 2 real roots: -0.91, -0.15 assert check(unrad(root(x, 3)/2 - root(x + 1, 4) + root(x + 2, 3) - 2), (729*s**13 + 1242*s**12 + 18496*s**10 + 129701*s**9 + 388602*s**8 + 453312*s**7 - 612864*s**6 - 3337173*s**5 - 6332418*s**4 - 7134912*s**3 - 5064768*s**2 - 2111913*s - 398034, [s, s**4 - x - 1])) # orig expr has 1 real root: 19.53 ans = solve(sqrt(x) + sqrt(x + 1) - sqrt(1 - x) - sqrt(2 + x)) assert len(ans) == 1 and NS(ans[0])[:4] == '0.73' # the fence optimization problem # https://github.com/sympy/sympy/issues/4793#issuecomment-36994519 F = Symbol('F') eq = F - (2*x + 2*y + sqrt(x**2 + y**2)) ans = F*Rational(2, 7) - sqrt(2)*F/14 X = solve(eq, x, check=False) for xi in reversed(X): # reverse since currently, ans is the 2nd one Y = solve((x*y).subs(x, xi).diff(y), y, simplify=False, check=False) if any((a - ans).expand().is_zero for a in Y): break else: assert None # no answer was found assert solve(sqrt(x + 1) + root(x, 3) - 2) == S(''' [(-11/(9*(47/54 + sqrt(93)/6)**(1/3)) + 1/3 + (47/54 + sqrt(93)/6)**(1/3))**3]''') assert solve(sqrt(sqrt(x + 1)) + x**Rational(1, 3) - 2) == S(''' [(-sqrt(-2*(-1/16 + sqrt(6913)/16)**(1/3) + 6/(-1/16 + sqrt(6913)/16)**(1/3) + 17/2 + 121/(4*sqrt(-6/(-1/16 + sqrt(6913)/16)**(1/3) + 2*(-1/16 + sqrt(6913)/16)**(1/3) + 17/4)))/2 + sqrt(-6/(-1/16 + sqrt(6913)/16)**(1/3) + 2*(-1/16 + sqrt(6913)/16)**(1/3) + 17/4)/2 + 9/4)**3]''') assert solve(sqrt(x) + root(sqrt(x) + 1, 3) - 2) == S(''' [(-(81/2 + 3*sqrt(741)/2)**(1/3)/3 + (81/2 + 3*sqrt(741)/2)**(-1/3) + 2)**2]''') eq = S(''' -x + (1/2 - sqrt(3)*I/2)*(3*x**3/2 - x*(3*x**2 - 34)/2 + sqrt((-3*x**3 + x*(3*x**2 - 34) + 90)**2/4 - 39304/27) - 45)**(1/3) + 34/(3*(1/2 - sqrt(3)*I/2)*(3*x**3/2 - x*(3*x**2 - 34)/2 + sqrt((-3*x**3 + x*(3*x**2 - 34) + 90)**2/4 - 39304/27) - 45)**(1/3))''') assert check(unrad(eq), (-s*(-s**6 + sqrt(3)*s**6*I - 153*2**Rational(2, 3)*3**Rational(1, 3)*s**4 + 51*12**Rational(1, 3)*s**4 - 102*2**Rational(2, 3)*3**Rational(5, 6)*s**4*I - 1620*s**3 + 1620*sqrt(3)*s**3*I + 13872*18**Rational(1, 3)*s**2 - 471648 + 471648*sqrt(3)*I), [s, s**3 - 306*x - sqrt(3)*sqrt(31212*x**2 - 165240*x + 61484) + 810])) assert solve(eq) == [] # not other code errors eq = root(x, 3) - root(y, 3) + root(x, 5) assert check(unrad(eq), (s**15 + 3*s**13 + 3*s**11 + s**9 - y, [s, s**15 - x])) eq = root(x, 3) + root(y, 3) + root(x*y, 4) assert check(unrad(eq), (s*y*(-s**12 - 3*s**11*y - 3*s**10*y**2 - s**9*y**3 - 3*s**8*y**2 + 21*s**7*y**3 - 3*s**6*y**4 - 3*s**4*y**4 - 3*s**3*y**5 - y**6), [s, s**4 - x*y])) raises(NotImplementedError, lambda: unrad(root(x, 3) + root(y, 3) + root(x*y, 5))) # Test unrad with an Equality eq = Eq(-x**(S(1)/5) + x**(S(1)/3), -3**(S(1)/3) - (-1)**(S(3)/5)*3**(S(1)/5)) assert check(unrad(eq), (-s**5 + s**3 - 3**(S(1)/3) - (-1)**(S(3)/5)*3**(S(1)/5), [s, s**15 - x])) @slow def test_unrad_slow(): # this has roots with multiplicity > 1; there should be no # repeats in roots obtained, however eq = (sqrt(1 + sqrt(1 - 4*x**2)) - x*((1 + sqrt(1 + 2*sqrt(1 - 4*x**2))))) assert solve(eq) == [S.Half] @XFAIL def test_unrad_fail(): # this only works if we check real_root(eq.subs(x, Rational(1, 3))) # but checksol doesn't work like that assert solve(root(x**3 - 3*x**2, 3) + 1 - x) == [Rational(1, 3)] assert solve(root(x + 1, 3) + root(x**2 - 2, 5) + 1) == [ -1, -1 + CRootOf(x**5 + x**4 + 5*x**3 + 8*x**2 + 10*x + 5, 0)**3] def test_checksol(): x, y, r, t = symbols('x, y, r, t') eq = r - x**2 - y**2 dict_var_soln = {y: - sqrt(r) / sqrt(tan(t)**2 + 1), x: -sqrt(r)*tan(t)/sqrt(tan(t)**2 + 1)} assert checksol(eq, dict_var_soln) == True assert checksol(Eq(x, False), {x: False}) is True assert checksol(Ne(x, False), {x: False}) is False assert checksol(Eq(x < 1, True), {x: 0}) is True assert checksol(Eq(x < 1, True), {x: 1}) is False assert checksol(Eq(x < 1, False), {x: 1}) is True assert checksol(Eq(x < 1, False), {x: 0}) is False assert checksol(Eq(x + 1, x**2 + 1), {x: 1}) is True assert checksol([x - 1, x**2 - 1], x, 1) is True assert checksol([x - 1, x**2 - 2], x, 1) is False assert checksol(Poly(x**2 - 1), x, 1) is True raises(ValueError, lambda: checksol(x, 1)) raises(ValueError, lambda: checksol([], x, 1)) def test__invert(): assert _invert(x - 2) == (2, x) assert _invert(2) == (2, 0) assert _invert(exp(1/x) - 3, x) == (1/log(3), x) assert _invert(exp(1/x + a/x) - 3, x) == ((a + 1)/log(3), x) assert _invert(a, x) == (a, 0) def test_issue_4463(): assert solve(-a*x + 2*x*log(x), x) == [exp(a/2)] assert solve(x**x) == [] assert solve(x**x - 2) == [exp(LambertW(log(2)))] assert solve(((x - 3)*(x - 2))**((x - 3)*(x - 4))) == [2] @slow def test_issue_5114_solvers(): a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r = symbols('a:r') # there is no 'a' in the equation set but this is how the # problem was originally posed syms = a, b, c, f, h, k, n eqs = [b + r/d - c/d, c*(1/d + 1/e + 1/g) - f/g - r/d, f*(1/g + 1/i + 1/j) - c/g - h/i, h*(1/i + 1/l + 1/m) - f/i - k/m, k*(1/m + 1/o + 1/p) - h/m - n/p, n*(1/p + 1/q) - k/p] assert len(solve(eqs, syms, manual=True, check=False, simplify=False)) == 1 def test_issue_5849(): I1, I2, I3, I4, I5, I6 = symbols('I1:7') dI1, dI4, dQ2, dQ4, Q2, Q4 = symbols('dI1,dI4,dQ2,dQ4,Q2,Q4') e = ( I1 - I2 - I3, I3 - I4 - I5, I4 + I5 - I6, -I1 + I2 + I6, -2*I1 - 2*I3 - 2*I5 - 3*I6 - dI1/2 + 12, -I4 + dQ4, -I2 + dQ2, 2*I3 + 2*I5 + 3*I6 - Q2, I4 - 2*I5 + 2*Q4 + dI4 ) ans = [{ dQ4: I3 - I5, dI1: -4*I2 - 8*I3 - 4*I5 - 6*I6 + 24, I4: I3 - I5, dQ2: I2, Q2: 2*I3 + 2*I5 + 3*I6, I1: I2 + I3, Q4: -I3/2 + 3*I5/2 - dI4/2}] v = I1, I4, Q2, Q4, dI1, dI4, dQ2, dQ4 assert solve(e, *v, manual=True, check=False, dict=True) == ans assert solve(e, *v, manual=True) == [] # the matrix solver (tested below) doesn't like this because it produces # a zero row in the matrix. Is this related to issue 4551? assert [ei.subs( ans[0]) for ei in e] == [0, 0, I3 - I6, -I3 + I6, 0, 0, 0, 0, 0] def test_issue_5849_matrix(): '''Same as test_2750 but solved with the matrix solver.''' I1, I2, I3, I4, I5, I6 = symbols('I1:7') dI1, dI4, dQ2, dQ4, Q2, Q4 = symbols('dI1,dI4,dQ2,dQ4,Q2,Q4') e = ( I1 - I2 - I3, I3 - I4 - I5, I4 + I5 - I6, -I1 + I2 + I6, -2*I1 - 2*I3 - 2*I5 - 3*I6 - dI1/2 + 12, -I4 + dQ4, -I2 + dQ2, 2*I3 + 2*I5 + 3*I6 - Q2, I4 - 2*I5 + 2*Q4 + dI4 ) assert solve(e, I1, I4, Q2, Q4, dI1, dI4, dQ2, dQ4) == { dI4: -I3 + 3*I5 - 2*Q4, dI1: -4*I2 - 8*I3 - 4*I5 - 6*I6 + 24, dQ2: I2, I1: I2 + I3, Q2: 2*I3 + 2*I5 + 3*I6, dQ4: I3 - I5, I4: I3 - I5} def test_issue_5901(): f, g, h = map(Function, 'fgh') a = Symbol('a') D = Derivative(f(x), x) G = Derivative(g(a), a) assert solve(f(x) + f(x).diff(x), f(x)) == \ [-D] assert solve(f(x) - 3, f(x)) == \ [3] assert solve(f(x) - 3*f(x).diff(x), f(x)) == \ [3*D] assert solve([f(x) - 3*f(x).diff(x)], f(x)) == \ {f(x): 3*D} assert solve([f(x) - 3*f(x).diff(x), f(x)**2 - y + 4], f(x), y) == \ [{f(x): 3*D, y: 9*D**2 + 4}] assert solve(-f(a)**2*g(a)**2 + f(a)**2*h(a)**2 + g(a).diff(a), h(a), g(a), set=True) == \ ([g(a)], set([ (-sqrt(h(a)**2*f(a)**2 + G)/f(a),), (sqrt(h(a)**2*f(a)**2+ G)/f(a),)])) args = [f(x).diff(x, 2)*(f(x) + g(x)) - g(x)**2 + 2, f(x), g(x)] assert set(solve(*args)) == \ set([(-sqrt(2), sqrt(2)), (sqrt(2), -sqrt(2))]) eqs = [f(x)**2 + g(x) - 2*f(x).diff(x), g(x)**2 - 4] assert solve(eqs, f(x), g(x), set=True) == \ ([f(x), g(x)], set([ (-sqrt(2*D - 2), S(2)), (sqrt(2*D - 2), S(2)), (-sqrt(2*D + 2), -S(2)), (sqrt(2*D + 2), -S(2))])) # the underlying problem was in solve_linear that was not masking off # anything but a Mul or Add; it now raises an error if it gets anything # but a symbol and solve handles the substitutions necessary so solve_linear # won't make this error raises( ValueError, lambda: solve_linear(f(x) + f(x).diff(x), symbols=[f(x)])) assert solve_linear(f(x) + f(x).diff(x), symbols=[x]) == \ (f(x) + Derivative(f(x), x), 1) assert solve_linear(f(x) + Integral(x, (x, y)), symbols=[x]) == \ (f(x) + Integral(x, (x, y)), 1) assert solve_linear(f(x) + Integral(x, (x, y)) + x, symbols=[x]) == \ (x + f(x) + Integral(x, (x, y)), 1) assert solve_linear(f(y) + Integral(x, (x, y)) + x, symbols=[x]) == \ (x, -f(y) - Integral(x, (x, y))) assert solve_linear(x - f(x)/a + (f(x) - 1)/a, symbols=[x]) == \ (x, 1/a) assert solve_linear(x + Derivative(2*x, x)) == \ (x, -2) assert solve_linear(x + Integral(x, y), symbols=[x]) == \ (x, 0) assert solve_linear(x + Integral(x, y) - 2, symbols=[x]) == \ (x, 2/(y + 1)) assert set(solve(x + exp(x)**2, exp(x))) == \ set([-sqrt(-x), sqrt(-x)]) assert solve(x + exp(x), x, implicit=True) == \ [-exp(x)] assert solve(cos(x) - sin(x), x, implicit=True) == [] assert solve(x - sin(x), x, implicit=True) == \ [sin(x)] assert solve(x**2 + x - 3, x, implicit=True) == \ [-x**2 + 3] assert solve(x**2 + x - 3, x**2, implicit=True) == \ [-x + 3] def test_issue_5912(): assert set(solve(x**2 - x - 0.1, rational=True)) == \ set([S.Half + sqrt(35)/10, -sqrt(35)/10 + S.Half]) ans = solve(x**2 - x - 0.1, rational=False) assert len(ans) == 2 and all(a.is_Number for a in ans) ans = solve(x**2 - x - 0.1) assert len(ans) == 2 and all(a.is_Number for a in ans) def test_float_handling(): def test(e1, e2): return len(e1.atoms(Float)) == len(e2.atoms(Float)) assert solve(x - 0.5, rational=True)[0].is_Rational assert solve(x - 0.5, rational=False)[0].is_Float assert solve(x - S.Half, rational=False)[0].is_Rational assert solve(x - 0.5, rational=None)[0].is_Float assert solve(x - S.Half, rational=None)[0].is_Rational assert test(nfloat(1 + 2*x), 1.0 + 2.0*x) for contain in [list, tuple, set]: ans = nfloat(contain([1 + 2*x])) assert type(ans) is contain and test(list(ans)[0], 1.0 + 2.0*x) k, v = list(nfloat({2*x: [1 + 2*x]}).items())[0] assert test(k, 2*x) and test(v[0], 1.0 + 2.0*x) assert test(nfloat(cos(2*x)), cos(2.0*x)) assert test(nfloat(3*x**2), 3.0*x**2) assert test(nfloat(3*x**2, exponent=True), 3.0*x**2.0) assert test(nfloat(exp(2*x)), exp(2.0*x)) assert test(nfloat(x/3), x/3.0) assert test(nfloat(x**4 + 2*x + cos(Rational(1, 3)) + 1), x**4 + 2.0*x + 1.94495694631474) # don't call nfloat if there is no solution tot = 100 + c + z + t assert solve(((.7 + c)/tot - .6, (.2 + z)/tot - .3, t/tot - .1)) == [] def test_check_assumptions(): x = symbols('x', positive=True) assert solve(x**2 - 1) == [1] assert check_assumptions(1, x) == True raises(AssertionError, lambda: check_assumptions(2*x, x, positive=True)) raises(TypeError, lambda: check_assumptions(1, 1)) def test_failing_assumptions(): x = Symbol('x', real=True, positive=True) y = Symbol('y') assert failing_assumptions(6*x + y, **x.assumptions0) == \ {'real': None, 'imaginary': None, 'complex': None, 'hermitian': None, 'positive': None, 'nonpositive': None, 'nonnegative': None, 'nonzero': None, 'negative': None, 'zero': None, 'extended_real': None, 'finite': None, 'infinite': None, 'extended_negative': None, 'extended_nonnegative': None, 'extended_nonpositive': None, 'extended_nonzero': None, 'extended_positive': None } def test_issue_6056(): assert solve(tanh(x + 3)*tanh(x - 3) - 1) == [] assert solve(tanh(x - 1)*tanh(x + 1) + 1) == \ [I*pi*Rational(-3, 4), -I*pi/4, I*pi/4, I*pi*Rational(3, 4)] assert solve((tanh(x + 3)*tanh(x - 3) + 1)**2) == \ [I*pi*Rational(-3, 4), -I*pi/4, I*pi/4, I*pi*Rational(3, 4)] def test_issue_5673(): eq = -x + exp(exp(LambertW(log(x)))*LambertW(log(x))) assert checksol(eq, x, 2) is True assert checksol(eq, x, 2, numerical=False) is None def test_exclude(): R, C, Ri, Vout, V1, Vminus, Vplus, s = \ symbols('R, C, Ri, Vout, V1, Vminus, Vplus, s') Rf = symbols('Rf', positive=True) # to eliminate Rf = 0 soln eqs = [C*V1*s + Vplus*(-2*C*s - 1/R), Vminus*(-1/Ri - 1/Rf) + Vout/Rf, C*Vplus*s + V1*(-C*s - 1/R) + Vout/R, -Vminus + Vplus] assert solve(eqs, exclude=s*C*R) == [ { Rf: Ri*(C*R*s + 1)**2/(C*R*s), Vminus: Vplus, V1: 2*Vplus + Vplus/(C*R*s), Vout: C*R*Vplus*s + 3*Vplus + Vplus/(C*R*s)}, { Vplus: 0, Vminus: 0, V1: 0, Vout: 0}, ] # TODO: Investigate why currently solution [0] is preferred over [1]. assert solve(eqs, exclude=[Vplus, s, C]) in [[{ Vminus: Vplus, V1: Vout/2 + Vplus/2 + sqrt((Vout - 5*Vplus)*(Vout - Vplus))/2, R: (Vout - 3*Vplus - sqrt(Vout**2 - 6*Vout*Vplus + 5*Vplus**2))/(2*C*Vplus*s), Rf: Ri*(Vout - Vplus)/Vplus, }, { Vminus: Vplus, V1: Vout/2 + Vplus/2 - sqrt((Vout - 5*Vplus)*(Vout - Vplus))/2, R: (Vout - 3*Vplus + sqrt(Vout**2 - 6*Vout*Vplus + 5*Vplus**2))/(2*C*Vplus*s), Rf: Ri*(Vout - Vplus)/Vplus, }], [{ Vminus: Vplus, Vout: (V1**2 - V1*Vplus - Vplus**2)/(V1 - 2*Vplus), Rf: Ri*(V1 - Vplus)**2/(Vplus*(V1 - 2*Vplus)), R: Vplus/(C*s*(V1 - 2*Vplus)), }]] def test_high_order_roots(): s = x**5 + 4*x**3 + 3*x**2 + Rational(7, 4) assert set(solve(s)) == set(Poly(s*4, domain='ZZ').all_roots()) def test_minsolve_linear_system(): def count(dic): return len([x for x in dic.values() if x == 0]) assert count(solve([x + y + z, y + z + a + t], particular=True, quick=True)) \ == 3 assert count(solve([x + y + z, y + z + a + t], particular=True, quick=False)) \ == 3 assert count(solve([x + y + z, y + z + a], particular=True, quick=True)) == 1 assert count(solve([x + y + z, y + z + a], particular=True, quick=False)) == 2 def test_real_roots(): # cf. issue 6650 x = Symbol('x', real=True) assert len(solve(x**5 + x**3 + 1)) == 1 def test_issue_6528(): eqs = [ 327600995*x**2 - 37869137*x + 1809975124*y**2 - 9998905626, 895613949*x**2 - 273830224*x*y + 530506983*y**2 - 10000000000] # two expressions encountered are > 1400 ops long so if this hangs # it is likely because simplification is being done assert len(solve(eqs, y, x, check=False)) == 4 def test_overdetermined(): x = symbols('x', real=True) eqs = [Abs(4*x - 7) - 5, Abs(3 - 8*x) - 1] assert solve(eqs, x) == [(S.Half,)] assert solve(eqs, x, manual=True) == [(S.Half,)] assert solve(eqs, x, manual=True, check=False) == [(S.Half,), (S(3),)] def test_issue_6605(): x = symbols('x') assert solve(4**(x/2) - 2**(x/3)) == [0, 3*I*pi/log(2)] # while the first one passed, this one failed x = symbols('x', real=True) assert solve(5**(x/2) - 2**(x/3)) == [0] b = sqrt(6)*sqrt(log(2))/sqrt(log(5)) assert solve(5**(x/2) - 2**(3/x)) == [-b, b] def test__ispow(): assert _ispow(x**2) assert not _ispow(x) assert not _ispow(True) def test_issue_6644(): eq = -sqrt((m - q)**2 + (-m/(2*q) + S.Half)**2) + sqrt((-m**2/2 - sqrt( 4*m**4 - 4*m**2 + 8*m + 1)/4 - Rational(1, 4))**2 + (m**2/2 - m - sqrt( 4*m**4 - 4*m**2 + 8*m + 1)/4 - Rational(1, 4))**2) sol = solve(eq, q, simplify=False, check=False) assert len(sol) == 5 def test_issue_6752(): assert solve([a**2 + a, a - b], [a, b]) == [(-1, -1), (0, 0)] assert solve([a**2 + a*c, a - b], [a, b]) == [(0, 0), (-c, -c)] def test_issue_6792(): assert solve(x*(x - 1)**2*(x + 1)*(x**6 - x + 1)) == [ -1, 0, 1, CRootOf(x**6 - x + 1, 0), CRootOf(x**6 - x + 1, 1), CRootOf(x**6 - x + 1, 2), CRootOf(x**6 - x + 1, 3), CRootOf(x**6 - x + 1, 4), CRootOf(x**6 - x + 1, 5)] def test_issues_6819_6820_6821_6248_8692(): # issue 6821 x, y = symbols('x y', real=True) assert solve(abs(x + 3) - 2*abs(x - 3)) == [1, 9] assert solve([abs(x) - 2, arg(x) - pi], x) == [(-2,), (2,)] assert set(solve(abs(x - 7) - 8)) == set([-S.One, S(15)]) # issue 8692 assert solve(Eq(Abs(x + 1) + Abs(x**2 - 7), 9), x) == [ Rational(-1, 2) + sqrt(61)/2, -sqrt(69)/2 + S.Half] # issue 7145 assert solve(2*abs(x) - abs(x - 1)) == [-1, Rational(1, 3)] x = symbols('x') assert solve([re(x) - 1, im(x) - 2], x) == [ {re(x): 1, x: 1 + 2*I, im(x): 2}] # check for 'dict' handling of solution eq = sqrt(re(x)**2 + im(x)**2) - 3 assert solve(eq) == solve(eq, x) i = symbols('i', imaginary=True) assert solve(abs(i) - 3) == [-3*I, 3*I] raises(NotImplementedError, lambda: solve(abs(x) - 3)) w = symbols('w', integer=True) assert solve(2*x**w - 4*y**w, w) == solve((x/y)**w - 2, w) x, y = symbols('x y', real=True) assert solve(x + y*I + 3) == {y: 0, x: -3} # issue 2642 assert solve(x*(1 + I)) == [0] x, y = symbols('x y', imaginary=True) assert solve(x + y*I + 3 + 2*I) == {x: -2*I, y: 3*I} x = symbols('x', real=True) assert solve(x + y + 3 + 2*I) == {x: -3, y: -2*I} # issue 6248 f = Function('f') assert solve(f(x + 1) - f(2*x - 1)) == [2] assert solve(log(x + 1) - log(2*x - 1)) == [2] x = symbols('x') assert solve(2**x + 4**x) == [I*pi/log(2)] def test_issue_14607(): # issue 14607 s, tau_c, tau_1, tau_2, phi, K = symbols( 's, tau_c, tau_1, tau_2, phi, K') target = (s**2*tau_1*tau_2 + s*tau_1 + s*tau_2 + 1)/(K*s*(-phi + tau_c)) K_C, tau_I, tau_D = symbols('K_C, tau_I, tau_D', positive=True, nonzero=True) PID = K_C*(1 + 1/(tau_I*s) + tau_D*s) eq = (target - PID).together() eq *= denom(eq).simplify() eq = Poly(eq, s) c = eq.coeffs() vars = [K_C, tau_I, tau_D] s = solve(c, vars, dict=True) assert len(s) == 1 knownsolution = {K_C: -(tau_1 + tau_2)/(K*(phi - tau_c)), tau_I: tau_1 + tau_2, tau_D: tau_1*tau_2/(tau_1 + tau_2)} for var in vars: assert s[0][var].simplify() == knownsolution[var].simplify() def test_lambert_multivariate(): from sympy.abc import x, y assert _filtered_gens(Poly(x + 1/x + exp(x) + y), x) == set([x, exp(x)]) assert _lambert(x, x) == [] assert solve((x**2 - 2*x + 1).subs(x, log(x) + 3*x)) == [LambertW(3*S.Exp1)/3] assert solve((x**2 - 2*x + 1).subs(x, (log(x) + 3*x)**2 - 1)) == \ [LambertW(3*exp(-sqrt(2)))/3, LambertW(3*exp(sqrt(2)))/3] assert solve((x**2 - 2*x - 2).subs(x, log(x) + 3*x)) == \ [LambertW(3*exp(1 - sqrt(3)))/3, LambertW(3*exp(1 + sqrt(3)))/3] eq = (x*exp(x) - 3).subs(x, x*exp(x)) assert solve(eq) == [LambertW(3*exp(-LambertW(3)))] # coverage test raises(NotImplementedError, lambda: solve(x - sin(x)*log(y - x), x)) ans = [3, -3*LambertW(-log(3)/3)/log(3)] # 3 and 2.478... assert solve(x**3 - 3**x, x) == ans assert set(solve(3*log(x) - x*log(3))) == set(ans) assert solve(LambertW(2*x) - y, x) == [y*exp(y)/2] @XFAIL def test_other_lambert(): assert solve(3*sin(x) - x*sin(3), x) == [3] assert set(solve(x**a - a**x), x) == set( [a, -a*LambertW(-log(a)/a)/log(a)]) @slow def test_lambert_bivariate(): # tests passing current implementation assert solve((x**2 + x)*exp((x**2 + x)) - 1) == [ Rational(-1, 2) + sqrt(1 + 4*LambertW(1))/2, Rational(-1, 2) - sqrt(1 + 4*LambertW(1))/2] assert solve((x**2 + x)*exp((x**2 + x)*2) - 1) == [ Rational(-1, 2) + sqrt(1 + 2*LambertW(2))/2, Rational(-1, 2) - sqrt(1 + 2*LambertW(2))/2] assert solve(a/x + exp(x/2), x) == [2*LambertW(-a/2)] assert solve((a/x + exp(x/2)).diff(x), x) == \ [4*LambertW(-sqrt(2)*sqrt(a)/4), 4*LambertW(sqrt(2)*sqrt(a)/4)] assert solve((1/x + exp(x/2)).diff(x), x) == \ [4*LambertW(-sqrt(2)/4), 4*LambertW(sqrt(2)/4), # nsimplifies as 2*2**(141/299)*3**(206/299)*5**(205/299)*7**(37/299)/21 4*LambertW(-sqrt(2)/4, -1)] assert solve(x*log(x) + 3*x + 1, x) == \ [exp(-3 + LambertW(-exp(3)))] assert solve(-x**2 + 2**x, x) == [2, 4, -2*LambertW(log(2)/2)/log(2)] assert solve(x**2 - 2**x, x) == [2, 4, -2*LambertW(log(2)/2)/log(2)] ans = solve(3*x + 5 + 2**(-5*x + 3), x) assert len(ans) == 1 and ans[0].expand() == \ Rational(-5, 3) + LambertW(-10240*root(2, 3)*log(2)/3)/(5*log(2)) assert solve(5*x - 1 + 3*exp(2 - 7*x), x) == \ [Rational(1, 5) + LambertW(-21*exp(Rational(3, 5))/5)/7] assert solve((log(x) + x).subs(x, x**2 + 1)) == [ -I*sqrt(-LambertW(1) + 1), sqrt(-1 + LambertW(1))] # check collection ax = a**(3*x + 5) ans = solve(3*log(ax) + b*log(ax) + ax, x) x0 = 1/log(a) x1 = sqrt(3)*I x2 = b + 3 x3 = x2*LambertW(1/x2)/a**5 x4 = x3**Rational(1, 3)/2 assert ans == [ x0*log(x4*(x1 - 1)), x0*log(-x4*(x1 + 1)), x0*log(x3)/3] x1 = LambertW(Rational(1, 3)) x2 = a**(-5) x3 = 3**Rational(1, 3) x4 = 3**Rational(5, 6)*I x5 = x1**Rational(1, 3)*x2**Rational(1, 3)/2 ans = solve(3*log(ax) + ax, x) assert ans == [ x0*log(3*x1*x2)/3, x0*log(x5*(-x3 + x4)), x0*log(-x5*(x3 + x4))] # coverage p = symbols('p', positive=True) eq = 4*2**(2*p + 3) - 2*p - 3 assert _solve_lambert(eq, p, _filtered_gens(Poly(eq), p)) == [ Rational(-3, 2) - LambertW(-4*log(2))/(2*log(2))] assert set(solve(3**cos(x) - cos(x)**3)) == set( [acos(3), acos(-3*LambertW(-log(3)/3)/log(3))]) # should give only one solution after using `uniq` assert solve(2*log(x) - 2*log(z) + log(z + log(x) + log(z)), x) == [ exp(-z + LambertW(2*z**4*exp(2*z))/2)/z] # cases when p != S.One # issue 4271 ans = solve((a/x + exp(x/2)).diff(x, 2), x) x0 = (-a)**Rational(1, 3) x1 = sqrt(3)*I x2 = x0/6 assert ans == [ 6*LambertW(x0/3), 6*LambertW(x2*(x1 - 1)), 6*LambertW(-x2*(x1 + 1))] assert solve((1/x + exp(x/2)).diff(x, 2), x) == \ [6*LambertW(Rational(-1, 3)), 6*LambertW(Rational(1, 6) - sqrt(3)*I/6), \ 6*LambertW(Rational(1, 6) + sqrt(3)*I/6), 6*LambertW(Rational(-1, 3), -1)] assert solve(x**2 - y**2/exp(x), x, y, dict=True) == \ [{x: 2*LambertW(-y/2)}, {x: 2*LambertW(y/2)}] # this is slow but not exceedingly slow assert solve((x**3)**(x/2) + pi/2, x) == [ exp(LambertW(-2*log(2)/3 + 2*log(pi)/3 + I*pi*Rational(2, 3)))] def test_rewrite_trig(): assert solve(sin(x) + tan(x)) == [0, -pi, pi, 2*pi] assert solve(sin(x) + sec(x)) == [ -2*atan(Rational(-1, 2) + sqrt(2)*sqrt(1 - sqrt(3)*I)/2 + sqrt(3)*I/2), 2*atan(S.Half - sqrt(2)*sqrt(1 + sqrt(3)*I)/2 + sqrt(3)*I/2), 2*atan(S.Half + sqrt(2)*sqrt(1 + sqrt(3)*I)/2 + sqrt(3)*I/2), 2*atan(S.Half - sqrt(3)*I/2 + sqrt(2)*sqrt(1 - sqrt(3)*I)/2)] assert solve(sinh(x) + tanh(x)) == [0, I*pi] # issue 6157 assert solve(2*sin(x) - cos(x), x) == [-2*atan(2 - sqrt(5)), -2*atan(2 + sqrt(5))] @XFAIL def test_rewrite_trigh(): # if this import passes then the test below should also pass from sympy import sech assert solve(sinh(x) + sech(x)) == [ 2*atanh(Rational(-1, 2) + sqrt(5)/2 - sqrt(-2*sqrt(5) + 2)/2), 2*atanh(Rational(-1, 2) + sqrt(5)/2 + sqrt(-2*sqrt(5) + 2)/2), 2*atanh(-sqrt(5)/2 - S.Half + sqrt(2 + 2*sqrt(5))/2), 2*atanh(-sqrt(2 + 2*sqrt(5))/2 - sqrt(5)/2 - S.Half)] def test_uselogcombine(): eq = z - log(x) + log(y/(x*(-1 + y**2/x**2))) assert solve(eq, x, force=True) == [-sqrt(y*(y - exp(z))), sqrt(y*(y - exp(z)))] assert solve(log(x + 3) + log(1 + 3/x) - 3) in [ [-3 + sqrt(-12 + exp(3))*exp(Rational(3, 2))/2 + exp(3)/2, -sqrt(-12 + exp(3))*exp(Rational(3, 2))/2 - 3 + exp(3)/2], [-3 + sqrt(-36 + (-exp(3) + 6)**2)/2 + exp(3)/2, -3 - sqrt(-36 + (-exp(3) + 6)**2)/2 + exp(3)/2], ] assert solve(log(exp(2*x) + 1) + log(-tanh(x) + 1) - log(2)) == [] def test_atan2(): assert solve(atan2(x, 2) - pi/3, x) == [2*sqrt(3)] def test_errorinverses(): assert solve(erf(x) - y, x) == [erfinv(y)] assert solve(erfinv(x) - y, x) == [erf(y)] assert solve(erfc(x) - y, x) == [erfcinv(y)] assert solve(erfcinv(x) - y, x) == [erfc(y)] def test_issue_2725(): R = Symbol('R') eq = sqrt(2)*R*sqrt(1/(R + 1)) + (R + 1)*(sqrt(2)*sqrt(1/(R + 1)) - 1) sol = solve(eq, R, set=True)[1] assert sol == set([(Rational(5, 3) + (Rational(-1, 2) - sqrt(3)*I/2)*(Rational(251, 27) + sqrt(111)*I/9)**Rational(1, 3) + 40/(9*((Rational(-1, 2) - sqrt(3)*I/2)*(Rational(251, 27) + sqrt(111)*I/9)**Rational(1, 3))),), (Rational(5, 3) + 40/(9*(Rational(251, 27) + sqrt(111)*I/9)**Rational(1, 3)) + (Rational(251, 27) + sqrt(111)*I/9)**Rational(1, 3),)]) def test_issue_5114_6611(): # See that it doesn't hang; this solves in about 2 seconds. # Also check that the solution is relatively small. # Note: the system in issue 6611 solves in about 5 seconds and has # an op-count of 138336 (with simplify=False). b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r = symbols('b:r') eqs = Matrix([ [b - c/d + r/d], [c*(1/g + 1/e + 1/d) - f/g - r/d], [-c/g + f*(1/j + 1/i + 1/g) - h/i], [-f/i + h*(1/m + 1/l + 1/i) - k/m], [-h/m + k*(1/p + 1/o + 1/m) - n/p], [-k/p + n*(1/q + 1/p)]]) v = Matrix([f, h, k, n, b, c]) ans = solve(list(eqs), list(v), simplify=False) # If time is taken to simplify then then 2617 below becomes # 1168 and the time is about 50 seconds instead of 2. assert sum([s.count_ops() for s in ans.values()]) <= 2617 def test_det_quick(): m = Matrix(3, 3, symbols('a:9')) assert m.det() == det_quick(m) # calls det_perm m[0, 0] = 1 assert m.det() == det_quick(m) # calls det_minor m = Matrix(3, 3, list(range(9))) assert m.det() == det_quick(m) # defaults to .det() # make sure they work with Sparse s = SparseMatrix(2, 2, (1, 2, 1, 4)) assert det_perm(s) == det_minor(s) == s.det() def test_real_imag_splitting(): a, b = symbols('a b', real=True) assert solve(sqrt(a**2 + b**2) - 3, a) == \ [-sqrt(-b**2 + 9), sqrt(-b**2 + 9)] a, b = symbols('a b', imaginary=True) assert solve(sqrt(a**2 + b**2) - 3, a) == [] def test_issue_7110(): y = -2*x**3 + 4*x**2 - 2*x + 5 assert any(ask(Q.real(i)) for i in solve(y)) def test_units(): assert solve(1/x - 1/(2*cm)) == [2*cm] def test_issue_7547(): A, B, V = symbols('A,B,V') eq1 = Eq(630.26*(V - 39.0)*V*(V + 39) - A + B, 0) eq2 = Eq(B, 1.36*10**8*(V - 39)) eq3 = Eq(A, 5.75*10**5*V*(V + 39.0)) sol = Matrix(nsolve(Tuple(eq1, eq2, eq3), [A, B, V], (0, 0, 0))) assert str(sol) == str(Matrix( [['4442890172.68209'], ['4289299466.1432'], ['70.5389666628177']])) def test_issue_7895(): r = symbols('r', real=True) assert solve(sqrt(r) - 2) == [4] def test_issue_2777(): # the equations represent two circles x, y = symbols('x y', real=True) e1, e2 = sqrt(x**2 + y**2) - 10, sqrt(y**2 + (-x + 10)**2) - 3 a, b = Rational(191, 20), 3*sqrt(391)/20 ans = [(a, -b), (a, b)] assert solve((e1, e2), (x, y)) == ans assert solve((e1, e2/(x - a)), (x, y)) == [] # make the 2nd circle's radius be -3 e2 += 6 assert solve((e1, e2), (x, y)) == [] assert solve((e1, e2), (x, y), check=False) == ans def test_issue_7322(): number = 5.62527e-35 assert solve(x - number, x)[0] == number def test_nsolve(): raises(ValueError, lambda: nsolve(x, (-1, 1), method='bisect')) raises(TypeError, lambda: nsolve((x - y + 3,x + y,z - y),(x,y,z),(-50,50))) raises(TypeError, lambda: nsolve((x + y, x - y), (0, 1))) @slow def test_high_order_multivariate(): assert len(solve(a*x**3 - x + 1, x)) == 3 assert len(solve(a*x**4 - x + 1, x)) == 4 assert solve(a*x**5 - x + 1, x) == [] # incomplete solution allowed raises(NotImplementedError, lambda: solve(a*x**5 - x + 1, x, incomplete=False)) # result checking must always consider the denominator and CRootOf # must be checked, too d = x**5 - x + 1 assert solve(d*(1 + 1/d)) == [CRootOf(d + 1, i) for i in range(5)] d = x - 1 assert solve(d*(2 + 1/d)) == [S.Half] def test_base_0_exp_0(): assert solve(0**x - 1) == [0] assert solve(0**(x - 2) - 1) == [2] assert solve(S('x*(1/x**0 - x)', evaluate=False)) == \ [0, 1] def test__simple_dens(): assert _simple_dens(1/x**0, [x]) == set() assert _simple_dens(1/x**y, [x]) == set([x**y]) assert _simple_dens(1/root(x, 3), [x]) == set([x]) def test_issue_8755(): # This tests two things: that if full unrad is attempted and fails # the solution should still be found; also it tests the use of # keyword `composite`. assert len(solve(sqrt(y)*x + x**3 - 1, x)) == 3 assert len(solve(-512*y**3 + 1344*(x + 2)**Rational(1, 3)*y**2 - 1176*(x + 2)**Rational(2, 3)*y - 169*x + 686, y, _unrad=False)) == 3 @slow def test_issue_8828(): x1 = 0 y1 = -620 r1 = 920 x2 = 126 y2 = 276 x3 = 51 y3 = 205 r3 = 104 v = x, y, z f1 = (x - x1)**2 + (y - y1)**2 - (r1 - z)**2 f2 = (x2 - x)**2 + (y2 - y)**2 - z**2 f3 = (x - x3)**2 + (y - y3)**2 - (r3 - z)**2 F = f1,f2,f3 g1 = sqrt((x - x1)**2 + (y - y1)**2) + z - r1 g2 = f2 g3 = sqrt((x - x3)**2 + (y - y3)**2) + z - r3 G = g1,g2,g3 A = solve(F, v) B = solve(G, v) C = solve(G, v, manual=True) p, q, r = [set([tuple(i.evalf(2) for i in j) for j in R]) for R in [A, B, C]] assert p == q == r @slow def test_issue_2840_8155(): assert solve(sin(3*x) + sin(6*x)) == [ 0, pi*Rational(-5, 3), pi*Rational(-4, 3), -pi, pi*Rational(-2, 3), pi*Rational(-4, 9), -pi/3, pi*Rational(-2, 9), pi*Rational(2, 9), pi/3, pi*Rational(4, 9), pi*Rational(2, 3), pi, pi*Rational(4, 3), pi*Rational(14, 9), pi*Rational(5, 3), pi*Rational(16, 9), 2*pi, -2*I*log(-(-1)**Rational(1, 9)), -2*I*log(-(-1)**Rational(2, 9)), -2*I*log(-sin(pi/18) - I*cos(pi/18)), -2*I*log(-sin(pi/18) + I*cos(pi/18)), -2*I*log(sin(pi/18) - I*cos(pi/18)), -2*I*log(sin(pi/18) + I*cos(pi/18))] assert solve(2*sin(x) - 2*sin(2*x)) == [ 0, pi*Rational(-5, 3), -pi, -pi/3, pi/3, pi, pi*Rational(5, 3)] def test_issue_9567(): assert solve(1 + 1/(x - 1)) == [0] def test_issue_11538(): assert solve(x + E) == [-E] assert solve(x**2 + E) == [-I*sqrt(E), I*sqrt(E)] assert solve(x**3 + 2*E) == [ -cbrt(2 * E), cbrt(2)*cbrt(E)/2 - cbrt(2)*sqrt(3)*I*cbrt(E)/2, cbrt(2)*cbrt(E)/2 + cbrt(2)*sqrt(3)*I*cbrt(E)/2] assert solve([x + 4, y + E], x, y) == {x: -4, y: -E} assert solve([x**2 + 4, y + E], x, y) == [ (-2*I, -E), (2*I, -E)] e1 = x - y**3 + 4 e2 = x + y + 4 + 4 * E assert len(solve([e1, e2], x, y)) == 3 @slow def test_issue_12114(): a, b, c, d, e, f, g = symbols('a,b,c,d,e,f,g') terms = [1 + a*b + d*e, 1 + a*c + d*f, 1 + b*c + e*f, g - a**2 - d**2, g - b**2 - e**2, g - c**2 - f**2] s = solve(terms, [a, b, c, d, e, f, g], dict=True) assert s == [{a: -sqrt(-f**2 - 1), b: -sqrt(-f**2 - 1), c: -sqrt(-f**2 - 1), d: f, e: f, g: -1}, {a: sqrt(-f**2 - 1), b: sqrt(-f**2 - 1), c: sqrt(-f**2 - 1), d: f, e: f, g: -1}, {a: -sqrt(3)*f/2 - sqrt(-f**2 + 2)/2, b: sqrt(3)*f/2 - sqrt(-f**2 + 2)/2, c: sqrt(-f**2 + 2), d: -f/2 + sqrt(-3*f**2 + 6)/2, e: -f/2 - sqrt(3)*sqrt(-f**2 + 2)/2, g: 2}, {a: -sqrt(3)*f/2 + sqrt(-f**2 + 2)/2, b: sqrt(3)*f/2 + sqrt(-f**2 + 2)/2, c: -sqrt(-f**2 + 2), d: -f/2 - sqrt(-3*f**2 + 6)/2, e: -f/2 + sqrt(3)*sqrt(-f**2 + 2)/2, g: 2}, {a: sqrt(3)*f/2 - sqrt(-f**2 + 2)/2, b: -sqrt(3)*f/2 - sqrt(-f**2 + 2)/2, c: sqrt(-f**2 + 2), d: -f/2 - sqrt(-3*f**2 + 6)/2, e: -f/2 + sqrt(3)*sqrt(-f**2 + 2)/2, g: 2}, {a: sqrt(3)*f/2 + sqrt(-f**2 + 2)/2, b: -sqrt(3)*f/2 + sqrt(-f**2 + 2)/2, c: -sqrt(-f**2 + 2), d: -f/2 + sqrt(-3*f**2 + 6)/2, e: -f/2 - sqrt(3)*sqrt(-f**2 + 2)/2, g: 2}] def test_inf(): assert solve(1 - oo*x) == [] assert solve(oo*x, x) == [] assert solve(oo*x - oo, x) == [] def test_issue_12448(): f = Function('f') fun = [f(i) for i in range(15)] sym = symbols('x:15') reps = dict(zip(fun, sym)) (x, y, z), c = sym[:3], sym[3:] ssym = solve([c[4*i]*x + c[4*i + 1]*y + c[4*i + 2]*z + c[4*i + 3] for i in range(3)], (x, y, z)) (x, y, z), c = fun[:3], fun[3:] sfun = solve([c[4*i]*x + c[4*i + 1]*y + c[4*i + 2]*z + c[4*i + 3] for i in range(3)], (x, y, z)) assert sfun[fun[0]].xreplace(reps).count_ops() == \ ssym[sym[0]].count_ops() def test_denoms(): assert denoms(x/2 + 1/y) == set([2, y]) assert denoms(x/2 + 1/y, y) == set([y]) assert denoms(x/2 + 1/y, [y]) == set([y]) assert denoms(1/x + 1/y + 1/z, [x, y]) == set([x, y]) assert denoms(1/x + 1/y + 1/z, x, y) == set([x, y]) assert denoms(1/x + 1/y + 1/z, set([x, y])) == set([x, y]) def test_issue_12476(): x0, x1, x2, x3, x4, x5 = symbols('x0 x1 x2 x3 x4 x5') eqns = [x0**2 - x0, x0*x1 - x1, x0*x2 - x2, x0*x3 - x3, x0*x4 - x4, x0*x5 - x5, x0*x1 - x1, -x0/3 + x1**2 - 2*x2/3, x1*x2 - x1/3 - x2/3 - x3/3, x1*x3 - x2/3 - x3/3 - x4/3, x1*x4 - 2*x3/3 - x5/3, x1*x5 - x4, x0*x2 - x2, x1*x2 - x1/3 - x2/3 - x3/3, -x0/6 - x1/6 + x2**2 - x2/6 - x3/3 - x4/6, -x1/6 + x2*x3 - x2/3 - x3/6 - x4/6 - x5/6, x2*x4 - x2/3 - x3/3 - x4/3, x2*x5 - x3, x0*x3 - x3, x1*x3 - x2/3 - x3/3 - x4/3, -x1/6 + x2*x3 - x2/3 - x3/6 - x4/6 - x5/6, -x0/6 - x1/6 - x2/6 + x3**2 - x3/3 - x4/6, -x1/3 - x2/3 + x3*x4 - x3/3, -x2 + x3*x5, x0*x4 - x4, x1*x4 - 2*x3/3 - x5/3, x2*x4 - x2/3 - x3/3 - x4/3, -x1/3 - x2/3 + x3*x4 - x3/3, -x0/3 - 2*x2/3 + x4**2, -x1 + x4*x5, x0*x5 - x5, x1*x5 - x4, x2*x5 - x3, -x2 + x3*x5, -x1 + x4*x5, -x0 + x5**2, x0 - 1] sols = [{x0: 1, x3: Rational(1, 6), x2: Rational(1, 6), x4: Rational(-2, 3), x1: Rational(-2, 3), x5: 1}, {x0: 1, x3: S.Half, x2: Rational(-1, 2), x4: 0, x1: 0, x5: -1}, {x0: 1, x3: Rational(-1, 3), x2: Rational(-1, 3), x4: Rational(1, 3), x1: Rational(1, 3), x5: 1}, {x0: 1, x3: 1, x2: 1, x4: 1, x1: 1, x5: 1}, {x0: 1, x3: Rational(-1, 3), x2: Rational(1, 3), x4: sqrt(5)/3, x1: -sqrt(5)/3, x5: -1}, {x0: 1, x3: Rational(-1, 3), x2: Rational(1, 3), x4: -sqrt(5)/3, x1: sqrt(5)/3, x5: -1}] assert solve(eqns) == sols def test_issue_13849(): t = symbols('t') assert solve((t*(sqrt(5) + sqrt(2)) - sqrt(2), t), t) == [] def test_issue_14860(): from sympy.physics.units import newton, kilo assert solve(8*kilo*newton + x + y, x) == [-8000*newton - y] def test_issue_14721(): k, h, a, b = symbols(':4') assert solve([ -1 + (-k + 1)**2/b**2 + (-h - 1)**2/a**2, -1 + (-k + 1)**2/b**2 + (-h + 1)**2/a**2, h, k + 2], h, k, a, b) == [ (0, -2, -b*sqrt(1/(b**2 - 9)), b), (0, -2, b*sqrt(1/(b**2 - 9)), b)] assert solve([ h, h/a + 1/b**2 - 2, -h/2 + 1/b**2 - 2], a, h, b) == [ (a, 0, -sqrt(2)/2), (a, 0, sqrt(2)/2)] assert solve((a + b**2 - 1, a + b**2 - 2)) == [] def test_issue_14779(): x = symbols('x', real=True) assert solve(sqrt(x**4 - 130*x**2 + 1089) + sqrt(x**4 - 130*x**2 + 3969) - 96*Abs(x)/x,x) == [sqrt(130)] def test_issue_15307(): assert solve((y - 2, Mul(x + 3,x - 2, evaluate=False))) == \ [{x: -3, y: 2}, {x: 2, y: 2}] assert solve((y - 2, Mul(3, x - 2, evaluate=False))) == \ {x: 2, y: 2} assert solve((y - 2, Add(x + 4, x - 2, evaluate=False))) == \ {x: -1, y: 2} eq1 = Eq(12513*x + 2*y - 219093, -5726*x - y) eq2 = Eq(-2*x + 8, 2*x - 40) assert solve([eq1, eq2]) == {x:12, y:75} def test_issue_15415(): assert solve(x - 3, x) == [3] assert solve([x - 3], x) == {x:3} assert solve(Eq(y + 3*x**2/2, y + 3*x), y) == [] assert solve([Eq(y + 3*x**2/2, y + 3*x)], y) == [] assert solve([Eq(y + 3*x**2/2, y + 3*x), Eq(x, 1)], y) == [] @slow def test_issue_15731(): # f(x)**g(x)=c assert solve(Eq((x**2 - 7*x + 11)**(x**2 - 13*x + 42), 1)) == [2, 3, 4, 5, 6, 7] assert solve((x)**(x + 4) - 4) == [-2] assert solve((-x)**(-x + 4) - 4) == [2] assert solve((x**2 - 6)**(x**2 - 2) - 4) == [-2, 2] assert solve((x**2 - 2*x - 1)**(x**2 - 3) - 1/(1 - 2*sqrt(2))) == [sqrt(2)] assert solve(x**(x + S.Half) - 4*sqrt(2)) == [S(2)] assert solve((x**2 + 1)**x - 25) == [2] assert solve(x**(2/x) - 2) == [2, 4] assert solve((x/2)**(2/x) - sqrt(2)) == [4, 8] assert solve(x**(x + S.Half) - Rational(9, 4)) == [Rational(3, 2)] # a**g(x)=c assert solve((-sqrt(sqrt(2)))**x - 2) == [4, log(2)/(log(2**Rational(1, 4)) + I*pi)] assert solve((sqrt(2))**x - sqrt(sqrt(2))) == [S.Half] assert solve((-sqrt(2))**x + 2*(sqrt(2))) == [3, (3*log(2)**2 + 4*pi**2 - 4*I*pi*log(2))/(log(2)**2 + 4*pi**2)] assert solve((sqrt(2))**x - 2*(sqrt(2))) == [3] assert solve(I**x + 1) == [2] assert solve((1 + I)**x - 2*I) == [2] assert solve((sqrt(2) + sqrt(3))**x - (2*sqrt(6) + 5)**Rational(1, 3)) == [Rational(2, 3)] # bases of both sides are equal b = Symbol('b') assert solve(b**x - b**2, x) == [2] assert solve(b**x - 1/b, x) == [-1] assert solve(b**x - b, x) == [1] b = Symbol('b', positive=True) assert solve(b**x - b**2, x) == [2] assert solve(b**x - 1/b, x) == [-1] def test_issue_10933(): assert solve(x**4 + y*(x + 0.1), x) # doesn't fail assert solve(I*x**4 + x**3 + x**2 + 1.) # doesn't fail def test_Abs_handling(): x = symbols('x', real=True) assert solve(abs(x/y), x) == [0] def test_issue_7982(): x = Symbol('x') # Test that no exception happens assert solve([2*x**2 + 5*x + 20 <= 0, x >= 1.5], x) is S.false # From #8040 assert solve([x**3 - 8.08*x**2 - 56.48*x/5 - 106 >= 0, x - 1 <= 0], [x]) is S.false def test_issue_14645(): x, y = symbols('x y') assert solve([x*y - x - y, x*y - x - y], [x, y]) == [(y/(y - 1), y)] def test_issue_12024(): x, y = symbols('x y') assert solve(Piecewise((0.0, x < 0.1), (x, x >= 0.1)) - y) == \ [{y: Piecewise((0.0, x < 0.1), (x, True))}] def test_issue_17452(): assert solve((7**x)**x + pi, x) == [-sqrt(log(pi) + I*pi)/sqrt(log(7)), sqrt(log(pi) + I*pi)/sqrt(log(7))] assert solve(x**(x/11) + pi/11, x) == [exp(LambertW(-11*log(11) + 11*log(pi) + 11*I*pi))] def test_issue_17799(): assert solve(-erf(x**(S(1)/3))**pi + I, x) == [] def test_issue_17650(): x = Symbol('x', real=True) assert solve(abs((abs(x**2 - 1) - x)) - x) == [1, -1 + sqrt(2), 1 + sqrt(2)] def test_issue_17882(): eq = -8*x**2/(9*(x**2 - 1)**(S(4)/3)) + 4/(3*(x**2 - 1)**(S(1)/3)) assert unrad(eq) == (4*x**2 - 12, []) def test_issue_17949(): assert solve(exp(+x+x**2), x) == [] assert solve(exp(-x+x**2), x) == [] assert solve(exp(+x-x**2), x) == [] assert solve(exp(-x-x**2), x) == [] def test_issue_11553(): eq1 = x + y + 1 eq2 = x + GoldenRatio assert solve([eq1, eq2], x, y) == {x: -GoldenRatio, y: -1 + GoldenRatio} eq3 = x + 2 + TribonacciConstant assert solve([eq1, eq3], x, y) == {x: -2 - TribonacciConstant, y: 1 + TribonacciConstant}
963a223a17fc8d34050c5f412b0d45e742bc964a48f42bd994740d7dbebff5ce
"""Tests for solvers of systems of polynomial equations. """ from sympy import (flatten, I, Integer, Poly, QQ, Rational, S, sqrt, solve, symbols) from sympy.abc import x, y, z from sympy.polys import PolynomialError from sympy.solvers.polysys import (solve_poly_system, solve_triangulated, solve_biquadratic, SolveFailed) from sympy.polys.polytools import parallel_poly_from_expr from sympy.testing.pytest import raises def test_solve_poly_system(): assert solve_poly_system([x - 1], x) == [(S.One,)] assert solve_poly_system([y - x, y - x - 1], x, y) is None assert solve_poly_system([y - x**2, y + x**2], x, y) == [(S.Zero, S.Zero)] assert solve_poly_system([2*x - 3, y*Rational(3, 2) - 2*x, z - 5*y], x, y, z) == \ [(Rational(3, 2), Integer(2), Integer(10))] assert solve_poly_system([x*y - 2*y, 2*y**2 - x**2], x, y) == \ [(0, 0), (2, -sqrt(2)), (2, sqrt(2))] assert solve_poly_system([y - x**2, y + x**2 + 1], x, y) == \ [(-I*sqrt(S.Half), Rational(-1, 2)), (I*sqrt(S.Half), Rational(-1, 2))] f_1 = x**2 + y + z - 1 f_2 = x + y**2 + z - 1 f_3 = x + y + z**2 - 1 a, b = sqrt(2) - 1, -sqrt(2) - 1 assert solve_poly_system([f_1, f_2, f_3], x, y, z) == \ [(0, 0, 1), (0, 1, 0), (1, 0, 0), (a, a, a), (b, b, b)] solution = [(1, -1), (1, 1)] assert solve_poly_system([Poly(x**2 - y**2), Poly(x - 1)]) == solution assert solve_poly_system([x**2 - y**2, x - 1], x, y) == solution assert solve_poly_system([x**2 - y**2, x - 1]) == solution assert solve_poly_system( [x + x*y - 3, y + x*y - 4], x, y) == [(-3, -2), (1, 2)] raises(NotImplementedError, lambda: solve_poly_system([x**3 - y**3], x, y)) raises(NotImplementedError, lambda: solve_poly_system( [z, -2*x*y**2 + x + y**2*z, y**2*(-z - 4) + 2])) raises(PolynomialError, lambda: solve_poly_system([1/x], x)) def test_solve_biquadratic(): x0, y0, x1, y1, r = symbols('x0 y0 x1 y1 r') f_1 = (x - 1)**2 + (y - 1)**2 - r**2 f_2 = (x - 2)**2 + (y - 2)**2 - r**2 s = sqrt(2*r**2 - 1) a = (3 - s)/2 b = (3 + s)/2 assert solve_poly_system([f_1, f_2], x, y) == [(a, b), (b, a)] f_1 = (x - 1)**2 + (y - 2)**2 - r**2 f_2 = (x - 1)**2 + (y - 1)**2 - r**2 assert solve_poly_system([f_1, f_2], x, y) == \ [(1 - sqrt(((2*r - 1)*(2*r + 1)))/2, Rational(3, 2)), (1 + sqrt(((2*r - 1)*(2*r + 1)))/2, Rational(3, 2))] query = lambda expr: expr.is_Pow and expr.exp is S.Half f_1 = (x - 1 )**2 + (y - 2)**2 - r**2 f_2 = (x - x1)**2 + (y - 1)**2 - r**2 result = solve_poly_system([f_1, f_2], x, y) assert len(result) == 2 and all(len(r) == 2 for r in result) assert all(r.count(query) == 1 for r in flatten(result)) f_1 = (x - x0)**2 + (y - y0)**2 - r**2 f_2 = (x - x1)**2 + (y - y1)**2 - r**2 result = solve_poly_system([f_1, f_2], x, y) assert len(result) == 2 and all(len(r) == 2 for r in result) assert all(len(r.find(query)) == 1 for r in flatten(result)) s1 = (x*y - y, x**2 - x) assert solve(s1) == [{x: 1}, {x: 0, y: 0}] s2 = (x*y - x, y**2 - y) assert solve(s2) == [{y: 1}, {x: 0, y: 0}] gens = (x, y) for seq in (s1, s2): (f, g), opt = parallel_poly_from_expr(seq, *gens) raises(SolveFailed, lambda: solve_biquadratic(f, g, opt)) seq = (x**2 + y**2 - 2, y**2 - 1) (f, g), opt = parallel_poly_from_expr(seq, *gens) assert solve_biquadratic(f, g, opt) == [ (-1, -1), (-1, 1), (1, -1), (1, 1)] ans = [(0, -1), (0, 1)] seq = (x**2 + y**2 - 1, y**2 - 1) (f, g), opt = parallel_poly_from_expr(seq, *gens) assert solve_biquadratic(f, g, opt) == ans seq = (x**2 + y**2 - 1, x**2 - x + y**2 - 1) (f, g), opt = parallel_poly_from_expr(seq, *gens) assert solve_biquadratic(f, g, opt) == ans def test_solve_triangulated(): f_1 = x**2 + y + z - 1 f_2 = x + y**2 + z - 1 f_3 = x + y + z**2 - 1 a, b = sqrt(2) - 1, -sqrt(2) - 1 assert solve_triangulated([f_1, f_2, f_3], x, y, z) == \ [(0, 0, 1), (0, 1, 0), (1, 0, 0)] dom = QQ.algebraic_field(sqrt(2)) assert solve_triangulated([f_1, f_2, f_3], x, y, z, domain=dom) == \ [(0, 0, 1), (0, 1, 0), (1, 0, 0), (a, a, a), (b, b, b)] def test_solve_issue_3686(): roots = solve_poly_system([((x - 5)**2/250000 + (y - Rational(5, 10))**2/250000) - 1, x], x, y) assert roots == [(0, S.Half - 15*sqrt(1111)), (0, S.Half + 15*sqrt(1111))] roots = solve_poly_system([((x - 5)**2/250000 + (y - 5.0/10)**2/250000) - 1, x], x, y) # TODO: does this really have to be so complicated?! assert len(roots) == 2 assert roots[0][0] == 0 assert roots[0][1].epsilon_eq(-499.474999374969, 1e12) assert roots[1][0] == 0 assert roots[1][1].epsilon_eq(500.474999374969, 1e12)
bc1d4f766fde241f466ef8e039146a61848e120a95c1bb874c05da86fd8117e7
"""Tests for tools for solving inequalities and systems of inequalities. """ from sympy import (And, Eq, FiniteSet, Ge, Gt, Interval, Le, Lt, Ne, oo, I, Or, S, sin, cos, tan, sqrt, Symbol, Union, Integral, Sum, Function, Poly, PurePoly, pi, root, log, exp, Dummy, Abs, Piecewise, Rational) from sympy.solvers.inequalities import (reduce_inequalities, solve_poly_inequality as psolve, reduce_rational_inequalities, solve_univariate_inequality as isolve, reduce_abs_inequality, _solve_inequality) from sympy.polys.rootoftools import rootof from sympy.solvers.solvers import solve from sympy.solvers.solveset import solveset from sympy.abc import x, y from sympy.testing.pytest import raises, XFAIL inf = oo.evalf() def test_solve_poly_inequality(): assert psolve(Poly(0, x), '==') == [S.Reals] assert psolve(Poly(1, x), '==') == [S.EmptySet] assert psolve(PurePoly(x + 1, x), ">") == [Interval(-1, oo, True, False)] def test_reduce_poly_inequalities_real_interval(): assert reduce_rational_inequalities( [[Eq(x**2, 0)]], x, relational=False) == FiniteSet(0) assert reduce_rational_inequalities( [[Le(x**2, 0)]], x, relational=False) == FiniteSet(0) assert reduce_rational_inequalities( [[Lt(x**2, 0)]], x, relational=False) == S.EmptySet assert reduce_rational_inequalities( [[Ge(x**2, 0)]], x, relational=False) == \ S.Reals if x.is_real else Interval(-oo, oo) assert reduce_rational_inequalities( [[Gt(x**2, 0)]], x, relational=False) == \ FiniteSet(0).complement(S.Reals) assert reduce_rational_inequalities( [[Ne(x**2, 0)]], x, relational=False) == \ FiniteSet(0).complement(S.Reals) assert reduce_rational_inequalities( [[Eq(x**2, 1)]], x, relational=False) == FiniteSet(-1, 1) assert reduce_rational_inequalities( [[Le(x**2, 1)]], x, relational=False) == Interval(-1, 1) assert reduce_rational_inequalities( [[Lt(x**2, 1)]], x, relational=False) == Interval(-1, 1, True, True) assert reduce_rational_inequalities( [[Ge(x**2, 1)]], x, relational=False) == \ Union(Interval(-oo, -1), Interval(1, oo)) assert reduce_rational_inequalities( [[Gt(x**2, 1)]], x, relational=False) == \ Interval(-1, 1).complement(S.Reals) assert reduce_rational_inequalities( [[Ne(x**2, 1)]], x, relational=False) == \ FiniteSet(-1, 1).complement(S.Reals) assert reduce_rational_inequalities([[Eq( x**2, 1.0)]], x, relational=False) == FiniteSet(-1.0, 1.0).evalf() assert reduce_rational_inequalities( [[Le(x**2, 1.0)]], x, relational=False) == Interval(-1.0, 1.0) assert reduce_rational_inequalities([[Lt( x**2, 1.0)]], x, relational=False) == Interval(-1.0, 1.0, True, True) assert reduce_rational_inequalities( [[Ge(x**2, 1.0)]], x, relational=False) == \ Union(Interval(-inf, -1.0), Interval(1.0, inf)) assert reduce_rational_inequalities( [[Gt(x**2, 1.0)]], x, relational=False) == \ Union(Interval(-inf, -1.0, right_open=True), Interval(1.0, inf, left_open=True)) assert reduce_rational_inequalities([[Ne( x**2, 1.0)]], x, relational=False) == \ FiniteSet(-1.0, 1.0).complement(S.Reals) s = sqrt(2) assert reduce_rational_inequalities([[Lt( x**2 - 1, 0), Gt(x**2 - 1, 0)]], x, relational=False) == S.EmptySet assert reduce_rational_inequalities([[Le(x**2 - 1, 0), Ge( x**2 - 1, 0)]], x, relational=False) == FiniteSet(-1, 1) assert reduce_rational_inequalities( [[Le(x**2 - 2, 0), Ge(x**2 - 1, 0)]], x, relational=False ) == Union(Interval(-s, -1, False, False), Interval(1, s, False, False)) assert reduce_rational_inequalities( [[Le(x**2 - 2, 0), Gt(x**2 - 1, 0)]], x, relational=False ) == Union(Interval(-s, -1, False, True), Interval(1, s, True, False)) assert reduce_rational_inequalities( [[Lt(x**2 - 2, 0), Ge(x**2 - 1, 0)]], x, relational=False ) == Union(Interval(-s, -1, True, False), Interval(1, s, False, True)) assert reduce_rational_inequalities( [[Lt(x**2 - 2, 0), Gt(x**2 - 1, 0)]], x, relational=False ) == Union(Interval(-s, -1, True, True), Interval(1, s, True, True)) assert reduce_rational_inequalities( [[Lt(x**2 - 2, 0), Ne(x**2 - 1, 0)]], x, relational=False ) == Union(Interval(-s, -1, True, True), Interval(-1, 1, True, True), Interval(1, s, True, True)) assert reduce_rational_inequalities([[Lt(x**2, -1.)]], x) is S.false def test_reduce_poly_inequalities_complex_relational(): assert reduce_rational_inequalities( [[Eq(x**2, 0)]], x, relational=True) == Eq(x, 0) assert reduce_rational_inequalities( [[Le(x**2, 0)]], x, relational=True) == Eq(x, 0) assert reduce_rational_inequalities( [[Lt(x**2, 0)]], x, relational=True) == False assert reduce_rational_inequalities( [[Ge(x**2, 0)]], x, relational=True) == And(Lt(-oo, x), Lt(x, oo)) assert reduce_rational_inequalities( [[Gt(x**2, 0)]], x, relational=True) == \ And(Gt(x, -oo), Lt(x, oo), Ne(x, 0)) assert reduce_rational_inequalities( [[Ne(x**2, 0)]], x, relational=True) == \ And(Gt(x, -oo), Lt(x, oo), Ne(x, 0)) for one in (S.One, S(1.0)): inf = one*oo assert reduce_rational_inequalities( [[Eq(x**2, one)]], x, relational=True) == \ Or(Eq(x, -one), Eq(x, one)) assert reduce_rational_inequalities( [[Le(x**2, one)]], x, relational=True) == \ And(And(Le(-one, x), Le(x, one))) assert reduce_rational_inequalities( [[Lt(x**2, one)]], x, relational=True) == \ And(And(Lt(-one, x), Lt(x, one))) assert reduce_rational_inequalities( [[Ge(x**2, one)]], x, relational=True) == \ And(Or(And(Le(one, x), Lt(x, inf)), And(Le(x, -one), Lt(-inf, x)))) assert reduce_rational_inequalities( [[Gt(x**2, one)]], x, relational=True) == \ And(Or(And(Lt(-inf, x), Lt(x, -one)), And(Lt(one, x), Lt(x, inf)))) assert reduce_rational_inequalities( [[Ne(x**2, one)]], x, relational=True) == \ Or(And(Lt(-inf, x), Lt(x, -one)), And(Lt(-one, x), Lt(x, one)), And(Lt(one, x), Lt(x, inf))) def test_reduce_rational_inequalities_real_relational(): assert reduce_rational_inequalities([], x) == False assert reduce_rational_inequalities( [[(x**2 + 3*x + 2)/(x**2 - 16) >= 0]], x, relational=False) == \ Union(Interval.open(-oo, -4), Interval(-2, -1), Interval.open(4, oo)) assert reduce_rational_inequalities( [[((-2*x - 10)*(3 - x))/((x**2 + 5)*(x - 2)**2) < 0]], x, relational=False) == \ Union(Interval.open(-5, 2), Interval.open(2, 3)) assert reduce_rational_inequalities([[(x + 1)/(x - 5) <= 0]], x, relational=False) == \ Interval.Ropen(-1, 5) assert reduce_rational_inequalities([[(x**2 + 4*x + 3)/(x - 1) > 0]], x, relational=False) == \ Union(Interval.open(-3, -1), Interval.open(1, oo)) assert reduce_rational_inequalities([[(x**2 - 16)/(x - 1)**2 < 0]], x, relational=False) == \ Union(Interval.open(-4, 1), Interval.open(1, 4)) assert reduce_rational_inequalities([[(3*x + 1)/(x + 4) >= 1]], x, relational=False) == \ Union(Interval.open(-oo, -4), Interval.Ropen(Rational(3, 2), oo)) assert reduce_rational_inequalities([[(x - 8)/x <= 3 - x]], x, relational=False) == \ Union(Interval.Lopen(-oo, -2), Interval.Lopen(0, 4)) # issue sympy/sympy#10237 assert reduce_rational_inequalities( [[x < oo, x >= 0, -oo < x]], x, relational=False) == Interval(0, oo) def test_reduce_abs_inequalities(): e = abs(x - 5) < 3 ans = And(Lt(2, x), Lt(x, 8)) assert reduce_inequalities(e) == ans assert reduce_inequalities(e, x) == ans assert reduce_inequalities(abs(x - 5)) == Eq(x, 5) assert reduce_inequalities( abs(2*x + 3) >= 8) == Or(And(Le(Rational(5, 2), x), Lt(x, oo)), And(Le(x, Rational(-11, 2)), Lt(-oo, x))) assert reduce_inequalities(abs(x - 4) + abs( 3*x - 5) < 7) == And(Lt(S.Half, x), Lt(x, 4)) assert reduce_inequalities(abs(x - 4) + abs(3*abs(x) - 5) < 7) == \ Or(And(S(-2) < x, x < -1), And(S.Half < x, x < 4)) nr = Symbol('nr', extended_real=False) raises(TypeError, lambda: reduce_inequalities(abs(nr - 5) < 3)) assert reduce_inequalities(x < 3, symbols=[x, nr]) == And(-oo < x, x < 3) def test_reduce_inequalities_general(): assert reduce_inequalities(Ge(sqrt(2)*x, 1)) == And(sqrt(2)/2 <= x, x < oo) assert reduce_inequalities(x + 1 > 0) == And(S.NegativeOne < x, x < oo) def test_reduce_inequalities_boolean(): assert reduce_inequalities( [Eq(x**2, 0), True]) == Eq(x, 0) assert reduce_inequalities([Eq(x**2, 0), False]) == False assert reduce_inequalities(x**2 >= 0) is S.true # issue 10196 def test_reduce_inequalities_multivariate(): assert reduce_inequalities([Ge(x**2, 1), Ge(y**2, 1)]) == And( Or(And(Le(S.One, x), Lt(x, oo)), And(Le(x, -1), Lt(-oo, x))), Or(And(Le(S.One, y), Lt(y, oo)), And(Le(y, -1), Lt(-oo, y)))) def test_reduce_inequalities_errors(): raises(NotImplementedError, lambda: reduce_inequalities(Ge(sin(x) + x, 1))) raises(NotImplementedError, lambda: reduce_inequalities(Ge(x**2*y + y, 1))) def test__solve_inequalities(): assert reduce_inequalities(x + y < 1, symbols=[x]) == (x < 1 - y) assert reduce_inequalities(x + y >= 1, symbols=[x]) == (x < oo) & (x >= -y + 1) assert reduce_inequalities(Eq(0, x - y), symbols=[x]) == Eq(x, y) assert reduce_inequalities(Ne(0, x - y), symbols=[x]) == Ne(x, y) def test_issue_6343(): eq = -3*x**2/2 - x*Rational(45, 4) + Rational(33, 2) > 0 assert reduce_inequalities(eq) == \ And(x < Rational(-15, 4) + sqrt(401)/4, -sqrt(401)/4 - Rational(15, 4) < x) def test_issue_8235(): assert reduce_inequalities(x**2 - 1 < 0) == \ And(S.NegativeOne < x, x < 1) assert reduce_inequalities(x**2 - 1 <= 0) == \ And(S.NegativeOne <= x, x <= 1) assert reduce_inequalities(x**2 - 1 > 0) == \ Or(And(-oo < x, x < -1), And(x < oo, S.One < x)) assert reduce_inequalities(x**2 - 1 >= 0) == \ Or(And(-oo < x, x <= -1), And(S.One <= x, x < oo)) eq = x**8 + x - 9 # we want CRootOf solns here sol = solve(eq >= 0) tru = Or(And(rootof(eq, 1) <= x, x < oo), And(-oo < x, x <= rootof(eq, 0))) assert sol == tru # recast vanilla as real assert solve(sqrt((-x + 1)**2) < 1) == And(S.Zero < x, x < 2) def test_issue_5526(): assert reduce_inequalities(0 <= x + Integral(y**2, (y, 1, 3)) - 1, [x]) == \ (x >= -Integral(y**2, (y, 1, 3)) + 1) f = Function('f') e = Sum(f(x), (x, 1, 3)) assert reduce_inequalities(0 <= x + e + y**2, [x]) == \ (x >= -y**2 - Sum(f(x), (x, 1, 3))) def test_solve_univariate_inequality(): assert isolve(x**2 >= 4, x, relational=False) == Union(Interval(-oo, -2), Interval(2, oo)) assert isolve(x**2 >= 4, x) == Or(And(Le(2, x), Lt(x, oo)), And(Le(x, -2), Lt(-oo, x))) assert isolve((x - 1)*(x - 2)*(x - 3) >= 0, x, relational=False) == \ Union(Interval(1, 2), Interval(3, oo)) assert isolve((x - 1)*(x - 2)*(x - 3) >= 0, x) == \ Or(And(Le(1, x), Le(x, 2)), And(Le(3, x), Lt(x, oo))) assert isolve((x - 1)*(x - 2)*(x - 4) < 0, x, domain = FiniteSet(0, 3)) == \ Or(Eq(x, 0), Eq(x, 3)) # issue 2785: assert isolve(x**3 - 2*x - 1 > 0, x, relational=False) == \ Union(Interval(-1, -sqrt(5)/2 + S.Half, True, True), Interval(S.Half + sqrt(5)/2, oo, True, True)) # issue 2794: assert isolve(x**3 - x**2 + x - 1 > 0, x, relational=False) == \ Interval(1, oo, True) #issue 13105 assert isolve((x + I)*(x + 2*I) < 0, x) == Eq(x, 0) assert isolve(((x - 1)*(x - 2) + I)*((x - 1)*(x - 2) + 2*I) < 0, x) == Or(Eq(x, 1), Eq(x, 2)) assert isolve((((x - 1)*(x - 2) + I)*((x - 1)*(x - 2) + 2*I))/(x - 2) > 0, x) == Eq(x, 1) raises (ValueError, lambda: isolve((x**2 - 3*x*I + 2)/x < 0, x)) # numerical testing in valid() is needed assert isolve(x**7 - x - 2 > 0, x) == \ And(rootof(x**7 - x - 2, 0) < x, x < oo) # handle numerator and denominator; although these would be handled as # rational inequalities, these test confirm that the right thing is done # when the domain is EX (e.g. when 2 is replaced with sqrt(2)) assert isolve(1/(x - 2) > 0, x) == And(S(2) < x, x < oo) den = ((x - 1)*(x - 2)).expand() assert isolve((x - 1)/den <= 0, x) == \ Or(And(-oo < x, x < 1), And(S.One < x, x < 2)) n = Dummy('n') raises(NotImplementedError, lambda: isolve(Abs(x) <= n, x, relational=False)) c1 = Dummy("c1", positive=True) raises(NotImplementedError, lambda: isolve(n/c1 < 0, c1)) n = Dummy('n', negative=True) assert isolve(n/c1 > -2, c1) == (-n/2 < c1) assert isolve(n/c1 < 0, c1) == True assert isolve(n/c1 > 0, c1) == False zero = cos(1)**2 + sin(1)**2 - 1 raises(NotImplementedError, lambda: isolve(x**2 < zero, x)) raises(NotImplementedError, lambda: isolve( x**2 < zero*I, x)) raises(NotImplementedError, lambda: isolve(1/(x - y) < 2, x)) raises(NotImplementedError, lambda: isolve(1/(x - y) < 0, x)) raises(TypeError, lambda: isolve(x - I < 0, x)) zero = x**2 + x - x*(x + 1) assert isolve(zero < 0, x, relational=False) is S.EmptySet assert isolve(zero <= 0, x, relational=False) is S.Reals # make sure iter_solutions gets a default value raises(NotImplementedError, lambda: isolve( Eq(cos(x)**2 + sin(x)**2, 1), x)) def test_trig_inequalities(): # all the inequalities are solved in a periodic interval. assert isolve(sin(x) < S.Half, x, relational=False) == \ Union(Interval(0, pi/6, False, True), Interval(pi*Rational(5, 6), 2*pi, True, False)) assert isolve(sin(x) > S.Half, x, relational=False) == \ Interval(pi/6, pi*Rational(5, 6), True, True) assert isolve(cos(x) < S.Zero, x, relational=False) == \ Interval(pi/2, pi*Rational(3, 2), True, True) assert isolve(cos(x) >= S.Zero, x, relational=False) == \ Union(Interval(0, pi/2), Interval(pi*Rational(3, 2), 2*pi)) assert isolve(tan(x) < S.One, x, relational=False) == \ Union(Interval.Ropen(0, pi/4), Interval.Lopen(pi/2, pi)) assert isolve(sin(x) <= S.Zero, x, relational=False) == \ Union(FiniteSet(S.Zero), Interval(pi, 2*pi)) assert isolve(sin(x) <= S.One, x, relational=False) == S.Reals assert isolve(cos(x) < S(-2), x, relational=False) == S.EmptySet assert isolve(sin(x) >= S.NegativeOne, x, relational=False) == S.Reals assert isolve(cos(x) > S.One, x, relational=False) == S.EmptySet def test_issue_9954(): assert isolve(x**2 >= 0, x, relational=False) == S.Reals assert isolve(x**2 >= 0, x, relational=True) == S.Reals.as_relational(x) assert isolve(x**2 < 0, x, relational=False) == S.EmptySet assert isolve(x**2 < 0, x, relational=True) == S.EmptySet.as_relational(x) @XFAIL def test_slow_general_univariate(): r = rootof(x**5 - x**2 + 1, 0) assert solve(sqrt(x) + 1/root(x, 3) > 1) == \ Or(And(0 < x, x < r**6), And(r**6 < x, x < oo)) def test_issue_8545(): eq = 1 - x - abs(1 - x) ans = And(Lt(1, x), Lt(x, oo)) assert reduce_abs_inequality(eq, '<', x) == ans eq = 1 - x - sqrt((1 - x)**2) assert reduce_inequalities(eq < 0) == ans def test_issue_8974(): assert isolve(-oo < x, x) == And(-oo < x, x < oo) assert isolve(oo > x, x) == And(-oo < x, x < oo) def test_issue_10198(): assert reduce_inequalities( -1 + 1/abs(1/x - 1) < 0) == Or( And(-oo < x, x < 0), And(S.Zero < x, x < S.Half) ) assert reduce_inequalities(abs(1/sqrt(x)) - 1, x) == Eq(x, 1) assert reduce_abs_inequality(-3 + 1/abs(1 - 1/x), '<', x) == \ Or(And(-oo < x, x < 0), And(S.Zero < x, x < Rational(3, 4)), And(Rational(3, 2) < x, x < oo)) raises(ValueError,lambda: reduce_abs_inequality(-3 + 1/abs( 1 - 1/sqrt(x)), '<', x)) def test_issue_10047(): # issue 10047: this must remain an inequality, not True, since if x # is not real the inequality is invalid # assert solve(sin(x) < 2) == (x <= oo) # with PR 16956, (x <= oo) autoevaluates when x is extended_real # which is assumed in the current implementation of inequality solvers assert solve(sin(x) < 2) == True assert solveset(sin(x) < 2, domain=S.Reals) == S.Reals def test_issue_10268(): assert solve(log(x) < 1000) == And(S.Zero < x, x < exp(1000)) @XFAIL def test_isolve_Sets(): n = Dummy('n') assert isolve(Abs(x) <= n, x, relational=False) == \ Piecewise((S.EmptySet, n < 0), (Interval(-n, n), True)) def test_issue_10671_12466(): assert solveset(sin(y), y, Interval(0, pi)) == FiniteSet(0, pi) i = Interval(1, 10) assert solveset((1/x).diff(x) < 0, x, i) == i assert solveset((log(x - 6)/x) <= 0, x, S.Reals) == \ Interval.Lopen(6, 7) def test__solve_inequality(): for op in (Gt, Lt, Le, Ge, Eq, Ne): assert _solve_inequality(op(x, 1), x).lhs == x assert _solve_inequality(op(S.One, x), x).lhs == x # don't get tricked by symbol on right: solve it assert _solve_inequality(Eq(2*x - 1, x), x) == Eq(x, 1) ie = Eq(S.One, y) assert _solve_inequality(ie, x) == ie for fx in (x**2, exp(x), sin(x) + cos(x), x*(1 + x)): for c in (0, 1): e = 2*fx - c > 0 assert _solve_inequality(e, x, linear=True) == ( fx > c/S(2)) assert _solve_inequality(2*x**2 + 2*x - 1 < 0, x, linear=True) == ( x*(x + 1) < S.Half) assert _solve_inequality(Eq(x*y, 1), x) == Eq(x*y, 1) nz = Symbol('nz', nonzero=True) assert _solve_inequality(Eq(x*nz, 1), x) == Eq(x, 1/nz) assert _solve_inequality(x*nz < 1, x) == (x*nz < 1) a = Symbol('a', positive=True) assert _solve_inequality(a/x > 1, x) == (S.Zero < x) & (x < a) assert _solve_inequality(a/x > 1, x, linear=True) == (1/x > 1/a) # make sure to include conditions under which solution is valid e = Eq(1 - x, x*(1/x - 1)) assert _solve_inequality(e, x) == Ne(x, 0) assert _solve_inequality(x < x*(1/x - 1), x) == (x < S.Half) & Ne(x, 0) def test__pt(): from sympy.solvers.inequalities import _pt assert _pt(-oo, oo) == 0 assert _pt(S.One, S(3)) == 2 assert _pt(S.One, oo) == _pt(oo, S.One) == 2 assert _pt(S.One, -oo) == _pt(-oo, S.One) == S.Half assert _pt(S.NegativeOne, oo) == _pt(oo, S.NegativeOne) == Rational(-1, 2) assert _pt(S.NegativeOne, -oo) == _pt(-oo, S.NegativeOne) == -2 assert _pt(x, oo) == _pt(oo, x) == x + 1 assert _pt(x, -oo) == _pt(-oo, x) == x - 1 raises(ValueError, lambda: _pt(Dummy('i', infinite=True), S.One))
0e87a740e3aa6b3485f8276b10e0fadb89009bb59779328d99bd5a679c6fc3fb
from sympy.solvers.decompogen import decompogen, compogen from sympy import sin, cos, sqrt, Abs, exp, symbols from sympy.testing.pytest import XFAIL, raises x, y = symbols('x y') def test_decompogen(): assert decompogen(sin(cos(x)), x) == [sin(x), cos(x)] assert decompogen(sin(x)**2 + sin(x) + 1, x) == [x**2 + x + 1, sin(x)] assert decompogen(sqrt(6*x**2 - 5), x) == [sqrt(x), 6*x**2 - 5] assert decompogen(sin(sqrt(cos(x**2 + 1))), x) == [sin(x), sqrt(x), cos(x), x**2 + 1] assert decompogen(Abs(cos(x)**2 + 3*cos(x) - 4), x) == [Abs(x), x**2 + 3*x - 4, cos(x)] assert decompogen(sin(x)**2 + sin(x) - sqrt(3)/2, x) == [x**2 + x - sqrt(3)/2, sin(x)] assert decompogen(Abs(cos(y)**2 + 3*cos(x) - 4), x) == [Abs(x), 3*x + cos(y)**2 - 4, cos(x)] assert decompogen(x, y) == [x] assert decompogen(1, x) == [1] raises(TypeError, lambda: decompogen(x < 5, x)) def test_decompogen_poly(): assert decompogen(x**4 + 2*x**2 + 1, x) == [x**2 + 2*x + 1, x**2] assert decompogen(x**4 + 2*x**3 - x - 1, x) == [x**2 - x - 1, x**2 + x] @XFAIL def test_decompogen_fails(): A = lambda x: x**2 + 2*x + 3 B = lambda x: 4*x**2 + 5*x + 6 assert decompogen(A(x*exp(x)), x) == [x**2 + 2*x + 3, x*exp(x)] assert decompogen(A(B(x)), x) == [x**2 + 2*x + 3, 4*x**2 + 5*x + 6] assert decompogen(A(1/x + 1/x**2), x) == [x**2 + 2*x + 3, 1/x + 1/x**2] assert decompogen(A(1/x + 2/(x + 1)), x) == [x**2 + 2*x + 3, 1/x + 2/(x + 1)] def test_compogen(): assert compogen([sin(x), cos(x)], x) == sin(cos(x)) assert compogen([x**2 + x + 1, sin(x)], x) == sin(x)**2 + sin(x) + 1 assert compogen([sqrt(x), 6*x**2 - 5], x) == sqrt(6*x**2 - 5) assert compogen([sin(x), sqrt(x), cos(x), x**2 + 1], x) == sin(sqrt( cos(x**2 + 1))) assert compogen([Abs(x), x**2 + 3*x - 4, cos(x)], x) == Abs(cos(x)**2 + 3*cos(x) - 4) assert compogen([x**2 + x - sqrt(3)/2, sin(x)], x) == (sin(x)**2 + sin(x) - sqrt(3)/2) assert compogen([Abs(x), 3*x + cos(y)**2 - 4, cos(x)], x) == \ Abs(3*cos(x) + cos(y)**2 - 4) assert compogen([x**2 + 2*x + 1, x**2], x) == x**4 + 2*x**2 + 1 # the result is in unsimplified form assert compogen([x**2 - x - 1, x**2 + x], x) == -x**2 - x + (x**2 + x)**2 - 1
e4ba72ca74a4736088348acf9a240c862c1a72caea53498b40456e39b232666d
from sympy import (Eq, Matrix, pi, sin, sqrt, Symbol, Integral, Piecewise, symbols, Float, I, Rational) from mpmath import mnorm, mpf from sympy.solvers import nsolve from sympy.utilities.lambdify import lambdify from sympy.testing.pytest import raises, XFAIL from sympy.utilities.decorator import conserve_mpmath_dps @XFAIL def test_nsolve_fail(): x = symbols('x') # Sometimes it is better to use the numerator (issue 4829) # but sometimes it is not (issue 11768) so leave this to # the discretion of the user ans = nsolve(x**2/(1 - x)/(1 - 2*x)**2 - 100, x, 0) assert ans > 0.46 and ans < 0.47 def test_nsolve_denominator(): x = symbols('x') # Test that nsolve uses the full expression (numerator and denominator). ans = nsolve((x**2 + 3*x + 2)/(x + 2), -2.1) # The root -2 was divided out, so make sure we don't find it. assert ans == -1.0 def test_nsolve(): # onedimensional x = Symbol('x') assert nsolve(sin(x), 2) - pi.evalf() < 1e-15 assert nsolve(Eq(2*x, 2), x, -10) == nsolve(2*x - 2, -10) # Testing checks on number of inputs raises(TypeError, lambda: nsolve(Eq(2*x, 2))) raises(TypeError, lambda: nsolve(Eq(2*x, 2), x, 1, 2)) # multidimensional x1 = Symbol('x1') x2 = Symbol('x2') f1 = 3 * x1**2 - 2 * x2**2 - 1 f2 = x1**2 - 2 * x1 + x2**2 + 2 * x2 - 8 f = Matrix((f1, f2)).T F = lambdify((x1, x2), f.T, modules='mpmath') for x0 in [(-1, 1), (1, -2), (4, 4), (-4, -4)]: x = nsolve(f, (x1, x2), x0, tol=1.e-8) assert mnorm(F(*x), 1) <= 1.e-10 # The Chinese mathematician Zhu Shijie was the very first to solve this # nonlinear system 700 years ago (z was added to make it 3-dimensional) x = Symbol('x') y = Symbol('y') z = Symbol('z') f1 = -x + 2*y f2 = (x**2 + x*(y**2 - 2) - 4*y) / (x + 4) f3 = sqrt(x**2 + y**2)*z f = Matrix((f1, f2, f3)).T F = lambdify((x, y, z), f.T, modules='mpmath') def getroot(x0): root = nsolve(f, (x, y, z), x0) assert mnorm(F(*root), 1) <= 1.e-8 return root assert list(map(round, getroot((1, 1, 1)))) == [2.0, 1.0, 0.0] assert nsolve([Eq( f1, 0), Eq(f2, 0), Eq(f3, 0)], [x, y, z], (1, 1, 1)) # just see that it works a = Symbol('a') assert abs(nsolve(1/(0.001 + a)**3 - 6/(0.9 - a)**3, a, 0.3) - mpf('0.31883011387318591')) < 1e-15 def test_issue_6408(): x = Symbol('x') assert nsolve(Piecewise((x, x < 1), (x**2, True)), x, 2) == 0.0 @XFAIL def test_issue_6408_fail(): x, y = symbols('x y') assert nsolve(Integral(x*y, (x, 0, 5)), y, 2) == 0.0 @conserve_mpmath_dps def test_increased_dps(): # Issue 8564 import mpmath mpmath.mp.dps = 128 x = Symbol('x') e1 = x**2 - pi q = nsolve(e1, x, 3.0) assert abs(sqrt(pi).evalf(128) - q) < 1e-128 def test_nsolve_precision(): x, y = symbols('x y') sol = nsolve(x**2 - pi, x, 3, prec=128) assert abs(sqrt(pi).evalf(128) - sol) < 1e-128 assert isinstance(sol, Float) sols = nsolve((y**2 - x, x**2 - pi), (x, y), (3, 3), prec=128) assert isinstance(sols, Matrix) assert sols.shape == (2, 1) assert abs(sqrt(pi).evalf(128) - sols[0]) < 1e-128 assert abs(sqrt(sqrt(pi)).evalf(128) - sols[1]) < 1e-128 assert all(isinstance(i, Float) for i in sols) def test_nsolve_complex(): x, y = symbols('x y') assert nsolve(x**2 + 2, 1j) == sqrt(2.)*I assert nsolve(x**2 + 2, I) == sqrt(2.)*I assert nsolve([x**2 + 2, y**2 + 2], [x, y], [I, I]) == Matrix([sqrt(2.)*I, sqrt(2.)*I]) assert nsolve([x**2 + 2, y**2 + 2], [x, y], [I, I]) == Matrix([sqrt(2.)*I, sqrt(2.)*I]) def test_nsolve_dict_kwarg(): x, y = symbols('x y') # one variable assert nsolve(x**2 - 2, 1, dict = True) == \ [{x: sqrt(2.)}] # one variable with complex solution assert nsolve(x**2 + 2, I, dict = True) == \ [{x: sqrt(2.)*I}] # two variables assert nsolve([x**2 + y**2 - 5, x**2 - y**2 + 1], [x, y], [1, 1], dict = True) == \ [{x: sqrt(2.), y: sqrt(3.)}] def test_nsolve_rational(): x = symbols('x') assert nsolve(x - Rational(1, 3), 0, prec=100) == Rational(1, 3).evalf(100) def test_issue_14950(): x = Matrix(symbols('t s')) x0 = Matrix([17, 23]) eqn = x + x0 assert nsolve(eqn, x, x0) == -x0 assert nsolve(eqn.T, x.T, x0.T) == -x0
079b65bc2cb0799ee96c08a2a45f7c3de6e5096386d2b55652e1cca41ad97e72
from sympy import (Derivative as D, Eq, exp, sin, Function, Symbol, symbols, cos, log) from sympy.core import S from sympy.solvers.pde import (pde_separate, pde_separate_add, pde_separate_mul, pdsolve, classify_pde, checkpdesol) from sympy.testing.pytest import raises a, b, c, x, y = symbols('a b c x y') def test_pde_separate_add(): x, y, z, t = symbols("x,y,z,t") F, T, X, Y, Z, u = map(Function, 'FTXYZu') eq = Eq(D(u(x, t), x), D(u(x, t), t)*exp(u(x, t))) res = pde_separate_add(eq, u(x, t), [X(x), T(t)]) assert res == [D(X(x), x)*exp(-X(x)), D(T(t), t)*exp(T(t))] def test_pde_separate(): x, y, z, t = symbols("x,y,z,t") F, T, X, Y, Z, u = map(Function, 'FTXYZu') eq = Eq(D(u(x, t), x), D(u(x, t), t)*exp(u(x, t))) raises(ValueError, lambda: pde_separate(eq, u(x, t), [X(x), T(t)], 'div')) def test_pde_separate_mul(): x, y, z, t = symbols("x,y,z,t") c = Symbol("C", real=True) Phi = Function('Phi') F, R, T, X, Y, Z, u = map(Function, 'FRTXYZu') r, theta, z = symbols('r,theta,z') # Something simple :) eq = Eq(D(F(x, y, z), x) + D(F(x, y, z), y) + D(F(x, y, z), z), 0) # Duplicate arguments in functions raises( ValueError, lambda: pde_separate_mul(eq, F(x, y, z), [X(x), u(z, z)])) # Wrong number of arguments raises(ValueError, lambda: pde_separate_mul(eq, F(x, y, z), [X(x), Y(y)])) # Wrong variables: [x, y] -> [x, z] raises( ValueError, lambda: pde_separate_mul(eq, F(x, y, z), [X(t), Y(x, y)])) assert pde_separate_mul(eq, F(x, y, z), [Y(y), u(x, z)]) == \ [D(Y(y), y)/Y(y), -D(u(x, z), x)/u(x, z) - D(u(x, z), z)/u(x, z)] assert pde_separate_mul(eq, F(x, y, z), [X(x), Y(y), Z(z)]) == \ [D(X(x), x)/X(x), -D(Z(z), z)/Z(z) - D(Y(y), y)/Y(y)] # wave equation wave = Eq(D(u(x, t), t, t), c**2*D(u(x, t), x, x)) res = pde_separate_mul(wave, u(x, t), [X(x), T(t)]) assert res == [D(X(x), x, x)/X(x), D(T(t), t, t)/(c**2*T(t))] # Laplace equation in cylindrical coords eq = Eq(1/r * D(Phi(r, theta, z), r) + D(Phi(r, theta, z), r, 2) + 1/r**2 * D(Phi(r, theta, z), theta, 2) + D(Phi(r, theta, z), z, 2), 0) # Separate z res = pde_separate_mul(eq, Phi(r, theta, z), [Z(z), u(theta, r)]) assert res == [D(Z(z), z, z)/Z(z), -D(u(theta, r), r, r)/u(theta, r) - D(u(theta, r), r)/(r*u(theta, r)) - D(u(theta, r), theta, theta)/(r**2*u(theta, r))] # Lets use the result to create a new equation... eq = Eq(res[1], c) # ...and separate theta... res = pde_separate_mul(eq, u(theta, r), [T(theta), R(r)]) assert res == [D(T(theta), theta, theta)/T(theta), -r*D(R(r), r)/R(r) - r**2*D(R(r), r, r)/R(r) - c*r**2] # ...or r... res = pde_separate_mul(eq, u(theta, r), [R(r), T(theta)]) assert res == [r*D(R(r), r)/R(r) + r**2*D(R(r), r, r)/R(r) + c*r**2, -D(T(theta), theta, theta)/T(theta)] def test_issue_11726(): x, t = symbols("x t") f = symbols("f", cls=Function) X, T = symbols("X T", cls=Function) u = f(x, t) eq = u.diff(x, 2) - u.diff(t, 2) res = pde_separate(eq, u, [T(x), X(t)]) assert res == [D(T(x), x, x)/T(x),D(X(t), t, t)/X(t)] def test_pde_classify(): # When more number of hints are added, add tests for classifying here. f = Function('f') eq1 = a*f(x,y) + b*f(x,y).diff(x) + c*f(x,y).diff(y) eq2 = 3*f(x,y) + 2*f(x,y).diff(x) + f(x,y).diff(y) eq3 = a*f(x,y) + b*f(x,y).diff(x) + 2*f(x,y).diff(y) eq4 = x*f(x,y) + f(x,y).diff(x) + 3*f(x,y).diff(y) eq5 = x**2*f(x,y) + x*f(x,y).diff(x) + x*y*f(x,y).diff(y) eq6 = y*x**2*f(x,y) + y*f(x,y).diff(x) + f(x,y).diff(y) for eq in [eq1, eq2, eq3]: assert classify_pde(eq) == ('1st_linear_constant_coeff_homogeneous',) for eq in [eq4, eq5, eq6]: assert classify_pde(eq) == ('1st_linear_variable_coeff',) def test_checkpdesol(): f, F = map(Function, ['f', 'F']) eq1 = a*f(x,y) + b*f(x,y).diff(x) + c*f(x,y).diff(y) eq2 = 3*f(x,y) + 2*f(x,y).diff(x) + f(x,y).diff(y) eq3 = a*f(x,y) + b*f(x,y).diff(x) + 2*f(x,y).diff(y) for eq in [eq1, eq2, eq3]: assert checkpdesol(eq, pdsolve(eq))[0] eq4 = x*f(x,y) + f(x,y).diff(x) + 3*f(x,y).diff(y) eq5 = 2*f(x,y) + 1*f(x,y).diff(x) + 3*f(x,y).diff(y) eq6 = f(x,y) + 1*f(x,y).diff(x) + 3*f(x,y).diff(y) assert checkpdesol(eq4, [pdsolve(eq5), pdsolve(eq6)]) == [ (False, (x - 2)*F(3*x - y)*exp(-x/S(5) - 3*y/S(5))), (False, (x - 1)*F(3*x - y)*exp(-x/S(10) - 3*y/S(10)))] for eq in [eq4, eq5, eq6]: assert checkpdesol(eq, pdsolve(eq))[0] sol = pdsolve(eq4) sol4 = Eq(sol.lhs - sol.rhs, 0) raises(NotImplementedError, lambda: checkpdesol(eq4, sol4, solve_for_func=False)) def test_solvefun(): f, F, G, H = map(Function, ['f', 'F', 'G', 'H']) eq1 = f(x,y) + f(x,y).diff(x) + f(x,y).diff(y) assert pdsolve(eq1) == Eq(f(x, y), F(x - y)*exp(-x/2 - y/2)) assert pdsolve(eq1, solvefun=G) == Eq(f(x, y), G(x - y)*exp(-x/2 - y/2)) assert pdsolve(eq1, solvefun=H) == Eq(f(x, y), H(x - y)*exp(-x/2 - y/2)) def test_pde_1st_linear_constant_coeff_homogeneous(): f, F = map(Function, ['f', 'F']) u = f(x, y) eq = 2*u + u.diff(x) + u.diff(y) assert classify_pde(eq) == ('1st_linear_constant_coeff_homogeneous',) sol = pdsolve(eq) assert sol == Eq(u, F(x - y)*exp(-x - y)) assert checkpdesol(eq, sol)[0] eq = 4 + (3*u.diff(x)/u) + (2*u.diff(y)/u) assert classify_pde(eq) == ('1st_linear_constant_coeff_homogeneous',) sol = pdsolve(eq) assert sol == Eq(u, F(2*x - 3*y)*exp(-S(12)*x/13 - S(8)*y/13)) assert checkpdesol(eq, sol)[0] eq = u + (6*u.diff(x)) + (7*u.diff(y)) assert classify_pde(eq) == ('1st_linear_constant_coeff_homogeneous',) sol = pdsolve(eq) assert sol == Eq(u, F(7*x - 6*y)*exp(-6*x/S(85) - 7*y/S(85))) assert checkpdesol(eq, sol)[0] eq = a*u + b*u.diff(x) + c*u.diff(y) sol = pdsolve(eq) assert checkpdesol(eq, sol)[0] def test_pde_1st_linear_constant_coeff(): f, F = map(Function, ['f', 'F']) u = f(x,y) eq = -2*u.diff(x) + 4*u.diff(y) + 5*u - exp(x + 3*y) sol = pdsolve(eq) assert sol == Eq(f(x,y), (F(4*x + 2*y) + exp(x/S(2) + 4*y)/S(15))*exp(x/S(2) - y)) assert classify_pde(eq) == ('1st_linear_constant_coeff', '1st_linear_constant_coeff_Integral') assert checkpdesol(eq, sol)[0] eq = (u.diff(x)/u) + (u.diff(y)/u) + 1 - (exp(x + y)/u) sol = pdsolve(eq) assert sol == Eq(f(x, y), F(x - y)*exp(-x/2 - y/2) + exp(x + y)/S(3)) assert classify_pde(eq) == ('1st_linear_constant_coeff', '1st_linear_constant_coeff_Integral') assert checkpdesol(eq, sol)[0] eq = 2*u + -u.diff(x) + 3*u.diff(y) + sin(x) sol = pdsolve(eq) assert sol == Eq(f(x, y), F(3*x + y)*exp(x/S(5) - 3*y/S(5)) - 2*sin(x)/S(5) - cos(x)/S(5)) assert classify_pde(eq) == ('1st_linear_constant_coeff', '1st_linear_constant_coeff_Integral') assert checkpdesol(eq, sol)[0] eq = u + u.diff(x) + u.diff(y) + x*y sol = pdsolve(eq) assert sol == Eq(f(x, y), -x*y + x + y + F(x - y)*exp(-x/S(2) - y/S(2)) - 2) assert classify_pde(eq) == ('1st_linear_constant_coeff', '1st_linear_constant_coeff_Integral') assert checkpdesol(eq, sol)[0] eq = u + u.diff(x) + u.diff(y) + log(x) assert classify_pde(eq) == ('1st_linear_constant_coeff', '1st_linear_constant_coeff_Integral') def test_pdsolve_all(): f, F = map(Function, ['f', 'F']) u = f(x,y) eq = u + u.diff(x) + u.diff(y) + x**2*y sol = pdsolve(eq, hint = 'all') keys = ['1st_linear_constant_coeff', '1st_linear_constant_coeff_Integral', 'default', 'order'] assert sorted(sol.keys()) == keys assert sol['order'] == 1 assert sol['default'] == '1st_linear_constant_coeff' assert sol['1st_linear_constant_coeff'] == Eq(f(x, y), -x**2*y + x**2 + 2*x*y - 4*x - 2*y + F(x - y)*exp(-x/S(2) - y/S(2)) + 6) def test_pdsolve_variable_coeff(): f, F = map(Function, ['f', 'F']) u = f(x, y) eq = x*(u.diff(x)) - y*(u.diff(y)) + y**2*u - y**2 sol = pdsolve(eq, hint="1st_linear_variable_coeff") assert sol == Eq(u, F(x*y)*exp(y**2/2) + 1) assert checkpdesol(eq, sol)[0] eq = x**2*u + x*u.diff(x) + x*y*u.diff(y) sol = pdsolve(eq, hint='1st_linear_variable_coeff') assert sol == Eq(u, F(y*exp(-x))*exp(-x**2/2)) assert checkpdesol(eq, sol)[0] eq = y*x**2*u + y*u.diff(x) + u.diff(y) sol = pdsolve(eq, hint='1st_linear_variable_coeff') assert sol == Eq(u, F(-2*x + y**2)*exp(-x**3/3)) assert checkpdesol(eq, sol)[0] eq = exp(x)**2*(u.diff(x)) + y sol = pdsolve(eq, hint='1st_linear_variable_coeff') assert sol == Eq(u, y*exp(-2*x)/2 + F(y)) assert checkpdesol(eq, sol)[0] eq = exp(2*x)*(u.diff(y)) + y*u - u sol = pdsolve(eq, hint='1st_linear_variable_coeff') assert sol == Eq(u, exp((-y**2 + 2*y + 2*F(x))*exp(-2*x)/2))
e13506cf670776db797180c8683b5fe268cab6ccefcb4f77fd8ffd8addecbf0c
from sympy import Eq, factorial, Function, Lambda, rf, S, sqrt, symbols, I, \ expand_func, binomial, gamma, Rational from sympy.solvers.recurr import rsolve, rsolve_hyper, rsolve_poly, rsolve_ratio from sympy.testing.pytest import raises, slow from sympy.abc import a, b y = Function('y') n, k = symbols('n,k', integer=True) C0, C1, C2 = symbols('C0,C1,C2') def test_rsolve_poly(): assert rsolve_poly([-1, -1, 1], 0, n) == 0 assert rsolve_poly([-1, -1, 1], 1, n) == -1 assert rsolve_poly([-1, n + 1], n, n) == 1 assert rsolve_poly([-1, 1], n, n) == C0 + (n**2 - n)/2 assert rsolve_poly([-n - 1, n], 1, n) == C1*n - 1 assert rsolve_poly([-4*n - 2, 1], 4*n + 1, n) == -1 assert rsolve_poly([-1, 1], n**5 + n**3, n) == \ C0 - n**3 / 2 - n**5 / 2 + n**2 / 6 + n**6 / 6 + 2*n**4 / 3 def test_rsolve_ratio(): solution = rsolve_ratio([-2*n**3 + n**2 + 2*n - 1, 2*n**3 + n**2 - 6*n, -2*n**3 - 11*n**2 - 18*n - 9, 2*n**3 + 13*n**2 + 22*n + 8], 0, n) assert solution in [ C1*((-2*n + 3)/(n**2 - 1))/3, (S.Half)*(C1*(-3 + 2*n)/(-1 + n**2)), (S.Half)*(C1*( 3 - 2*n)/( 1 - n**2)), (S.Half)*(C2*(-3 + 2*n)/(-1 + n**2)), (S.Half)*(C2*( 3 - 2*n)/( 1 - n**2)), ] def test_rsolve_hyper(): assert rsolve_hyper([-1, -1, 1], 0, n) in [ C0*(S.Half - S.Half*sqrt(5))**n + C1*(S.Half + S.Half*sqrt(5))**n, C1*(S.Half - S.Half*sqrt(5))**n + C0*(S.Half + S.Half*sqrt(5))**n, ] assert rsolve_hyper([n**2 - 2, -2*n - 1, 1], 0, n) in [ C0*rf(sqrt(2), n) + C1*rf(-sqrt(2), n), C1*rf(sqrt(2), n) + C0*rf(-sqrt(2), n), ] assert rsolve_hyper([n**2 - k, -2*n - 1, 1], 0, n) in [ C0*rf(sqrt(k), n) + C1*rf(-sqrt(k), n), C1*rf(sqrt(k), n) + C0*rf(-sqrt(k), n), ] assert rsolve_hyper( [2*n*(n + 1), -n**2 - 3*n + 2, n - 1], 0, n) == C1*factorial(n) + C0*2**n assert rsolve_hyper( [n + 2, -(2*n + 3)*(17*n**2 + 51*n + 39), n + 1], 0, n) == None assert rsolve_hyper([-n - 1, -1, 1], 0, n) == None assert rsolve_hyper([-1, 1], n, n).expand() == C0 + n**2/2 - n/2 assert rsolve_hyper([-1, 1], 1 + n, n).expand() == C0 + n**2/2 + n/2 assert rsolve_hyper([-1, 1], 3*(n + n**2), n).expand() == C0 + n**3 - n assert rsolve_hyper([-a, 1],0,n).expand() == C0*a**n assert rsolve_hyper([-a, 0, 1], 0, n).expand() == (-1)**n*C1*a**(n/2) + C0*a**(n/2) assert rsolve_hyper([1, 1, 1], 0, n).expand() == \ C0*(Rational(-1, 2) - sqrt(3)*I/2)**n + C1*(Rational(-1, 2) + sqrt(3)*I/2)**n assert rsolve_hyper([1, -2*n/a - 2/a, 1], 0, n) is None def recurrence_term(c, f): """Compute RHS of recurrence in f(n) with coefficients in c.""" return sum(c[i]*f.subs(n, n + i) for i in range(len(c))) def test_rsolve_bulk(): """Some bulk-generated tests.""" funcs = [ n, n + 1, n**2, n**3, n**4, n + n**2, 27*n + 52*n**2 - 3* n**3 + 12*n**4 - 52*n**5 ] coeffs = [ [-2, 1], [-2, -1, 1], [-1, 1, 1, -1, 1], [-n, 1], [n**2 - n + 12, 1] ] for p in funcs: # compute difference for c in coeffs: q = recurrence_term(c, p) if p.is_polynomial(n): assert rsolve_poly(c, q, n) == p # See issue 3956: #if p.is_hypergeometric(n): # assert rsolve_hyper(c, q, n) == p def test_rsolve(): f = y(n + 2) - y(n + 1) - y(n) h = sqrt(5)*(S.Half + S.Half*sqrt(5))**n \ - sqrt(5)*(S.Half - S.Half*sqrt(5))**n assert rsolve(f, y(n)) in [ C0*(S.Half - S.Half*sqrt(5))**n + C1*(S.Half + S.Half*sqrt(5))**n, C1*(S.Half - S.Half*sqrt(5))**n + C0*(S.Half + S.Half*sqrt(5))**n, ] assert rsolve(f, y(n), [0, 5]) == h assert rsolve(f, y(n), {0: 0, 1: 5}) == h assert rsolve(f, y(n), {y(0): 0, y(1): 5}) == h assert rsolve(y(n) - y(n - 1) - y(n - 2), y(n), [0, 5]) == h assert rsolve(Eq(y(n), y(n - 1) + y(n - 2)), y(n), [0, 5]) == h assert f.subs(y, Lambda(k, rsolve(f, y(n)).subs(n, k))).simplify() == 0 f = (n - 1)*y(n + 2) - (n**2 + 3*n - 2)*y(n + 1) + 2*n*(n + 1)*y(n) g = C1*factorial(n) + C0*2**n h = -3*factorial(n) + 3*2**n assert rsolve(f, y(n)) == g assert rsolve(f, y(n), []) == g assert rsolve(f, y(n), {}) == g assert rsolve(f, y(n), [0, 3]) == h assert rsolve(f, y(n), {0: 0, 1: 3}) == h assert rsolve(f, y(n), {y(0): 0, y(1): 3}) == h assert f.subs(y, Lambda(k, rsolve(f, y(n)).subs(n, k))).simplify() == 0 f = y(n) - y(n - 1) - 2 assert rsolve(f, y(n), {y(0): 0}) == 2*n assert rsolve(f, y(n), {y(0): 1}) == 2*n + 1 assert rsolve(f, y(n), {y(0): 0, y(1): 1}) is None assert f.subs(y, Lambda(k, rsolve(f, y(n)).subs(n, k))).simplify() == 0 f = 3*y(n - 1) - y(n) - 1 assert rsolve(f, y(n), {y(0): 0}) == -3**n/2 + S.Half assert rsolve(f, y(n), {y(0): 1}) == 3**n/2 + S.Half assert rsolve(f, y(n), {y(0): 2}) == 3*3**n/2 + S.Half assert f.subs(y, Lambda(k, rsolve(f, y(n)).subs(n, k))).simplify() == 0 f = y(n) - 1/n*y(n - 1) assert rsolve(f, y(n)) == C0/factorial(n) assert f.subs(y, Lambda(k, rsolve(f, y(n)).subs(n, k))).simplify() == 0 f = y(n) - 1/n*y(n - 1) - 1 assert rsolve(f, y(n)) is None f = 2*y(n - 1) + (1 - n)*y(n)/n assert rsolve(f, y(n), {y(1): 1}) == 2**(n - 1)*n assert rsolve(f, y(n), {y(1): 2}) == 2**(n - 1)*n*2 assert rsolve(f, y(n), {y(1): 3}) == 2**(n - 1)*n*3 assert f.subs(y, Lambda(k, rsolve(f, y(n)).subs(n, k))).simplify() == 0 f = (n - 1)*(n - 2)*y(n + 2) - (n + 1)*(n + 2)*y(n) assert rsolve(f, y(n), {y(3): 6, y(4): 24}) == n*(n - 1)*(n - 2) assert rsolve( f, y(n), {y(3): 6, y(4): -24}) == -n*(n - 1)*(n - 2)*(-1)**(n) assert f.subs(y, Lambda(k, rsolve(f, y(n)).subs(n, k))).simplify() == 0 assert rsolve(Eq(y(n + 1), a*y(n)), y(n), {y(1): a}).simplify() == a**n assert rsolve(y(n) - a*y(n-2),y(n), \ {y(1): sqrt(a)*(a + b), y(2): a*(a - b)}).simplify() == \ a**(n/2)*(-(-1)**n*b + a) f = (-16*n**2 + 32*n - 12)*y(n - 1) + (4*n**2 - 12*n + 9)*y(n) assert expand_func(rsolve(f, y(n), \ {y(1): binomial(2*n + 1, 3)}).rewrite(gamma)).simplify() == \ 2**(2*n)*n*(2*n - 1)*(4*n**2 - 1)/12 assert (rsolve(y(n) + a*(y(n + 1) + y(n - 1))/2, y(n)) - (C0*((sqrt(-a**2 + 1) - 1)/a)**n + C1*((-sqrt(-a**2 + 1) - 1)/a)**n)).simplify() == 0 assert rsolve((k + 1)*y(k), y(k)) is None assert (rsolve((k + 1)*y(k) + (k + 3)*y(k + 1) + (k + 5)*y(k + 2), y(k)) is None) def test_rsolve_raises(): x = Function('x') raises(ValueError, lambda: rsolve(y(n) - y(k + 1), y(n))) raises(ValueError, lambda: rsolve(y(n) - y(n + 1), x(n))) raises(ValueError, lambda: rsolve(y(n) - x(n + 1), y(n))) raises(ValueError, lambda: rsolve(y(n) - sqrt(n)*y(n + 1), y(n))) raises(ValueError, lambda: rsolve(y(n) - y(n + 1), y(n), {x(0): 0})) def test_issue_6844(): f = y(n + 2) - y(n + 1) + y(n)/4 assert rsolve(f, y(n)) == 2**(-n)*(C0 + C1*n) assert rsolve(f, y(n), {y(0): 0, y(1): 1}) == 2*2**(-n)*n @slow def test_issue_15751(): f = y(n) + 21*y(n + 1) - 273*y(n + 2) - 1092*y(n + 3) + 1820*y(n + 4) + 1092*y(n + 5) - 273*y(n + 6) - 21*y(n + 7) + y(n + 8) assert rsolve(f, y(n)) is not None
b1575c402b3ae8ce7b76984daae46efd230be9f04b8aa0fe099e777579eece2a
""" If the arbitrary constant class from issue 4435 is ever implemented, this should serve as a set of test cases. """ from sympy import (acos, cos, cosh, Eq, exp, Function, I, Integral, log, Pow, S, sin, sinh, sqrt, Symbol) from sympy.solvers.ode.ode import constantsimp, constant_renumber from sympy.testing.pytest import XFAIL x = Symbol('x') y = Symbol('y') z = Symbol('z') u2 = Symbol('u2') _a = Symbol('_a') C1 = Symbol('C1') C2 = Symbol('C2') C3 = Symbol('C3') f = Function('f') def test_constant_mul(): # We want C1 (Constant) below to absorb the y's, but not the x's assert constant_renumber(constantsimp(y*C1, [C1])) == C1*y assert constant_renumber(constantsimp(C1*y, [C1])) == C1*y assert constant_renumber(constantsimp(x*C1, [C1])) == x*C1 assert constant_renumber(constantsimp(C1*x, [C1])) == x*C1 assert constant_renumber(constantsimp(2*C1, [C1])) == C1 assert constant_renumber(constantsimp(C1*2, [C1])) == C1 assert constant_renumber(constantsimp(y*C1*x, [C1, y])) == C1*x assert constant_renumber(constantsimp(x*y*C1, [C1, y])) == x*C1 assert constant_renumber(constantsimp(y*x*C1, [C1, y])) == x*C1 assert constant_renumber(constantsimp(C1*x*y, [C1, y])) == C1*x assert constant_renumber(constantsimp(x*C1*y, [C1, y])) == x*C1 assert constant_renumber(constantsimp(C1*y*(y + 1), [C1])) == C1*y*(y+1) assert constant_renumber(constantsimp(y*C1*(y + 1), [C1])) == C1*y*(y+1) assert constant_renumber(constantsimp(x*(y*C1), [C1])) == x*y*C1 assert constant_renumber(constantsimp(x*(C1*y), [C1])) == x*y*C1 assert constant_renumber(constantsimp(C1*(x*y), [C1, y])) == C1*x assert constant_renumber(constantsimp((x*y)*C1, [C1, y])) == x*C1 assert constant_renumber(constantsimp((y*x)*C1, [C1, y])) == x*C1 assert constant_renumber(constantsimp(y*(y + 1)*C1, [C1, y])) == C1 assert constant_renumber(constantsimp((C1*x)*y, [C1, y])) == C1*x assert constant_renumber(constantsimp(y*(x*C1), [C1, y])) == x*C1 assert constant_renumber(constantsimp((x*C1)*y, [C1, y])) == x*C1 assert constant_renumber(constantsimp(C1*x*y*x*y*2, [C1, y])) == C1*x**2 assert constant_renumber(constantsimp(C1*x*y*z, [C1, y, z])) == C1*x assert constant_renumber(constantsimp(C1*x*y**2*sin(z), [C1, y, z])) == C1*x assert constant_renumber(constantsimp(C1*C1, [C1])) == C1 assert constant_renumber(constantsimp(C1*C2, [C1, C2])) == C1 assert constant_renumber(constantsimp(C2*C2, [C1, C2])) == C1 assert constant_renumber(constantsimp(C1*C1*C2, [C1, C2])) == C1 assert constant_renumber(constantsimp(C1*x*2**x, [C1])) == C1*x*2**x def test_constant_add(): assert constant_renumber(constantsimp(C1 + C1, [C1])) == C1 assert constant_renumber(constantsimp(C1 + 2, [C1])) == C1 assert constant_renumber(constantsimp(2 + C1, [C1])) == C1 assert constant_renumber(constantsimp(C1 + y, [C1, y])) == C1 assert constant_renumber(constantsimp(C1 + x, [C1])) == C1 + x assert constant_renumber(constantsimp(C1 + C1, [C1])) == C1 assert constant_renumber(constantsimp(C1 + C2, [C1, C2])) == C1 assert constant_renumber(constantsimp(C2 + C1, [C1, C2])) == C1 assert constant_renumber(constantsimp(C1 + C2 + C1, [C1, C2])) == C1 def test_constant_power_as_base(): assert constant_renumber(constantsimp(C1**C1, [C1])) == C1 assert constant_renumber(constantsimp(Pow(C1, C1), [C1])) == C1 assert constant_renumber(constantsimp(C1**C1, [C1])) == C1 assert constant_renumber(constantsimp(C1**C2, [C1, C2])) == C1 assert constant_renumber(constantsimp(C2**C1, [C1, C2])) == C1 assert constant_renumber(constantsimp(C2**C2, [C1, C2])) == C1 assert constant_renumber(constantsimp(C1**y, [C1, y])) == C1 assert constant_renumber(constantsimp(C1**x, [C1])) == C1**x assert constant_renumber(constantsimp(C1**2, [C1])) == C1 assert constant_renumber( constantsimp(C1**(x*y), [C1])) == C1**(x*y) def test_constant_power_as_exp(): assert constant_renumber(constantsimp(x**C1, [C1])) == x**C1 assert constant_renumber(constantsimp(y**C1, [C1, y])) == C1 assert constant_renumber(constantsimp(x**y**C1, [C1, y])) == x**C1 assert constant_renumber( constantsimp((x**y)**C1, [C1])) == (x**y)**C1 assert constant_renumber( constantsimp(x**(y**C1), [C1, y])) == x**C1 assert constant_renumber(constantsimp(x**C1**y, [C1, y])) == x**C1 assert constant_renumber( constantsimp(x**(C1**y), [C1, y])) == x**C1 assert constant_renumber( constantsimp((x**C1)**y, [C1])) == (x**C1)**y assert constant_renumber(constantsimp(2**C1, [C1])) == C1 assert constant_renumber(constantsimp(S(2)**C1, [C1])) == C1 assert constant_renumber(constantsimp(exp(C1), [C1])) == C1 assert constant_renumber( constantsimp(exp(C1 + x), [C1])) == C1*exp(x) assert constant_renumber(constantsimp(Pow(2, C1), [C1])) == C1 def test_constant_function(): assert constant_renumber(constantsimp(sin(C1), [C1])) == C1 assert constant_renumber(constantsimp(f(C1), [C1])) == C1 assert constant_renumber(constantsimp(f(C1, C1), [C1])) == C1 assert constant_renumber(constantsimp(f(C1, C2), [C1, C2])) == C1 assert constant_renumber(constantsimp(f(C2, C1), [C1, C2])) == C1 assert constant_renumber(constantsimp(f(C2, C2), [C1, C2])) == C1 assert constant_renumber( constantsimp(f(C1, x), [C1])) == f(C1, x) assert constant_renumber(constantsimp(f(C1, y), [C1, y])) == C1 assert constant_renumber(constantsimp(f(y, C1), [C1, y])) == C1 assert constant_renumber(constantsimp(f(C1, y, C2), [C1, C2, y])) == C1 def test_constant_function_multiple(): # The rules to not renumber in this case would be too complicated, and # dsolve is not likely to ever encounter anything remotely like this. assert constant_renumber( constantsimp(f(C1, C1, x), [C1])) == f(C1, C1, x) def test_constant_multiple(): assert constant_renumber(constantsimp(C1*2 + 2, [C1])) == C1 assert constant_renumber(constantsimp(x*2/C1, [C1])) == C1*x assert constant_renumber(constantsimp(C1**2*2 + 2, [C1])) == C1 assert constant_renumber( constantsimp(sin(2*C1) + x + sqrt(2), [C1])) == C1 + x assert constant_renumber(constantsimp(2*C1 + C2, [C1, C2])) == C1 def test_constant_repeated(): assert C1 + C1*x == constant_renumber( C1 + C1*x) def test_ode_solutions(): # only a few examples here, the rest will be tested in the actual dsolve tests assert constant_renumber(constantsimp(C1*exp(2*x) + exp(x)*(C2 + C3), [C1, C2, C3])) == \ constant_renumber((C1*exp(x) + C2*exp(2*x))) assert constant_renumber( constantsimp(Eq(f(x), I*C1*sinh(x/3) + C2*cosh(x/3)), [C1, C2]) ) == constant_renumber(Eq(f(x), C1*sinh(x/3) + C2*cosh(x/3))) assert constant_renumber(constantsimp(Eq(f(x), acos((-C1)/cos(x))), [C1])) == \ Eq(f(x), acos(C1/cos(x))) assert constant_renumber( constantsimp(Eq(log(f(x)/C1) + 2*exp(x/f(x)), 0), [C1]) ) == Eq(log(C1*f(x)) + 2*exp(x/f(x)), 0) assert constant_renumber(constantsimp(Eq(log(x*sqrt(2)*sqrt(1/x)*sqrt(f(x)) /C1) + x**2/(2*f(x)**2), 0), [C1])) == \ Eq(log(C1*sqrt(x)*sqrt(f(x))) + x**2/(2*f(x)**2), 0) assert constant_renumber(constantsimp(Eq(-exp(-f(x)/x)*sin(f(x)/x)/2 + log(x/C1) - cos(f(x)/x)*exp(-f(x)/x)/2, 0), [C1])) == \ Eq(-exp(-f(x)/x)*sin(f(x)/x)/2 + log(C1*x) - cos(f(x)/x)* exp(-f(x)/x)/2, 0) assert constant_renumber(constantsimp(Eq(-Integral(-1/(sqrt(1 - u2**2)*u2), (u2, _a, x/f(x))) + log(f(x)/C1), 0), [C1])) == \ Eq(-Integral(-1/(u2*sqrt(1 - u2**2)), (u2, _a, x/f(x))) + log(C1*f(x)), 0) assert [constantsimp(i, [C1]) for i in [Eq(f(x), sqrt(-C1*x + x**2)), Eq(f(x), -sqrt(-C1*x + x**2))]] == \ [Eq(f(x), sqrt(x*(C1 + x))), Eq(f(x), -sqrt(x*(C1 + x)))] @XFAIL def test_nonlocal_simplification(): assert constantsimp(C1 + C2+x*C2, [C1, C2]) == C1 + C2*x def test_constant_Eq(): # C1 on the rhs is well-tested, but the lhs is only tested here assert constantsimp(Eq(C1, 3 + f(x)*x), [C1]) == Eq(x*f(x), C1) assert constantsimp(Eq(C1, 3 * f(x)*x), [C1]) == Eq(f(x)*x, C1)
3dd81a10d781f60c38ccf87c0e9b013e8491220e359163f99fe342f81ff246fd
from sympy import (Add, Matrix, Mul, S, symbols, Eq, pi, factorint, oo, powsimp, Rational) from sympy.core.function import _mexpand from sympy.core.compatibility import ordered from sympy.functions.elementary.trigonometric import sin from sympy.solvers.diophantine import diophantine from sympy.solvers.diophantine.diophantine import (diop_DN, diop_solve, diop_ternary_quadratic_normal, diop_general_pythagorean, diop_ternary_quadratic, diop_linear, diop_quadratic, diop_general_sum_of_squares, diop_general_sum_of_even_powers, descent, diop_bf_DN, divisible, equivalent, find_DN, ldescent, length, reconstruct, partition, power_representation, prime_as_sum_of_two_squares, square_factor, sum_of_four_squares, sum_of_three_squares, transformation_to_DN, transformation_to_normal, classify_diop, base_solution_linear, cornacchia, sqf_normal, gaussian_reduce, holzer, check_param, parametrize_ternary_quadratic, sum_of_powers, sum_of_squares, _diop_ternary_quadratic_normal, _diop_general_sum_of_squares, _nint_or_floor, _odd, _even, _remove_gcd, _can_do_sum_of_squares) from sympy.utilities import default_sort_key from sympy.testing.pytest import slow, raises, XFAIL from sympy.utilities.iterables import ( signed_permutations) a, b, c, d, p, q, x, y, z, w, t, u, v, X, Y, Z = symbols( "a, b, c, d, p, q, x, y, z, w, t, u, v, X, Y, Z", integer=True) t_0, t_1, t_2, t_3, t_4, t_5, t_6 = symbols("t_:7", integer=True) m1, m2, m3 = symbols('m1:4', integer=True) n1 = symbols('n1', integer=True) def diop_simplify(eq): return _mexpand(powsimp(_mexpand(eq))) def test_input_format(): raises(TypeError, lambda: diophantine(sin(x))) raises(TypeError, lambda: diophantine(x/pi - 3)) def test_nosols(): # diophantine should sympify eq so that these are equivalent assert diophantine(3) == set() assert diophantine(S(3)) == set() def test_univariate(): assert diop_solve((x - 1)*(x - 2)**2) == {(1,), (2,)} assert diop_solve((x - 1)*(x - 2)) == {(1,), (2,)} def test_classify_diop(): raises(TypeError, lambda: classify_diop(x**2/3 - 1)) raises(ValueError, lambda: classify_diop(1)) raises(NotImplementedError, lambda: classify_diop(w*x*y*z - 1)) raises(NotImplementedError, lambda: classify_diop(x**3 + y**3 + z**4 - 90)) assert classify_diop(14*x**2 + 15*x - 42) == ( [x], {1: -42, x: 15, x**2: 14}, 'univariate') assert classify_diop(x*y + z) == ( [x, y, z], {x*y: 1, z: 1}, 'inhomogeneous_ternary_quadratic') assert classify_diop(x*y + z + w + x**2) == ( [w, x, y, z], {x*y: 1, w: 1, x**2: 1, z: 1}, 'inhomogeneous_general_quadratic') assert classify_diop(x*y + x*z + x**2 + 1) == ( [x, y, z], {x*y: 1, x*z: 1, x**2: 1, 1: 1}, 'inhomogeneous_general_quadratic') assert classify_diop(x*y + z + w + 42) == ( [w, x, y, z], {x*y: 1, w: 1, 1: 42, z: 1}, 'inhomogeneous_general_quadratic') assert classify_diop(x*y + z*w) == ( [w, x, y, z], {x*y: 1, w*z: 1}, 'homogeneous_general_quadratic') assert classify_diop(x*y**2 + 1) == ( [x, y], {x*y**2: 1, 1: 1}, 'cubic_thue') assert classify_diop(x**4 + y**4 + z**4 - (1 + 16 + 81)) == ( [x, y, z], {1: -98, x**4: 1, z**4: 1, y**4: 1}, 'general_sum_of_even_powers') def test_linear(): assert diop_solve(x) == (0,) assert diop_solve(1*x) == (0,) assert diop_solve(3*x) == (0,) assert diop_solve(x + 1) == (-1,) assert diop_solve(2*x + 1) == (None,) assert diop_solve(2*x + 4) == (-2,) assert diop_solve(y + x) == (t_0, -t_0) assert diop_solve(y + x + 0) == (t_0, -t_0) assert diop_solve(y + x - 0) == (t_0, -t_0) assert diop_solve(0*x - y - 5) == (-5,) assert diop_solve(3*y + 2*x - 5) == (3*t_0 - 5, -2*t_0 + 5) assert diop_solve(2*x - 3*y - 5) == (3*t_0 - 5, 2*t_0 - 5) assert diop_solve(-2*x - 3*y - 5) == (3*t_0 + 5, -2*t_0 - 5) assert diop_solve(7*x + 5*y) == (5*t_0, -7*t_0) assert diop_solve(2*x + 4*y) == (2*t_0, -t_0) assert diop_solve(4*x + 6*y - 4) == (3*t_0 - 2, -2*t_0 + 2) assert diop_solve(4*x + 6*y - 3) == (None, None) assert diop_solve(0*x + 3*y - 4*z + 5) == (4*t_0 + 5, 3*t_0 + 5) assert diop_solve(4*x + 3*y - 4*z + 5) == (t_0, 8*t_0 + 4*t_1 + 5, 7*t_0 + 3*t_1 + 5) assert diop_solve(4*x + 3*y - 4*z + 5, None) == (0, 5, 5) assert diop_solve(4*x + 2*y + 8*z - 5) == (None, None, None) assert diop_solve(5*x + 7*y - 2*z - 6) == (t_0, -3*t_0 + 2*t_1 + 6, -8*t_0 + 7*t_1 + 18) assert diop_solve(3*x - 6*y + 12*z - 9) == (2*t_0 + 3, t_0 + 2*t_1, t_1) assert diop_solve(6*w + 9*x + 20*y - z) == (t_0, t_1, t_1 + t_2, 6*t_0 + 29*t_1 + 20*t_2) # to ignore constant factors, use diophantine raises(TypeError, lambda: diop_solve(x/2)) def test_quadratic_simple_hyperbolic_case(): # Simple Hyperbolic case: A = C = 0 and B != 0 assert diop_solve(3*x*y + 34*x - 12*y + 1) == \ {(-133, -11), (5, -57)} assert diop_solve(6*x*y + 2*x + 3*y + 1) == set([]) assert diop_solve(-13*x*y + 2*x - 4*y - 54) == {(27, 0)} assert diop_solve(-27*x*y - 30*x - 12*y - 54) == {(-14, -1)} assert diop_solve(2*x*y + 5*x + 56*y + 7) == {(-161, -3), (-47, -6), (-35, -12), (-29, -69), (-27, 64), (-21, 7), (-9, 1), (105, -2)} assert diop_solve(6*x*y + 9*x + 2*y + 3) == set([]) assert diop_solve(x*y + x + y + 1) == {(-1, t), (t, -1)} assert diophantine(48*x*y) def test_quadratic_elliptical_case(): # Elliptical case: B**2 - 4AC < 0 assert diop_solve(42*x**2 + 8*x*y + 15*y**2 + 23*x + 17*y - 4915) == {(-11, -1)} assert diop_solve(4*x**2 + 3*y**2 + 5*x - 11*y + 12) == set([]) assert diop_solve(x**2 + y**2 + 2*x + 2*y + 2) == {(-1, -1)} assert diop_solve(15*x**2 - 9*x*y + 14*y**2 - 23*x - 14*y - 4950) == {(-15, 6)} assert diop_solve(10*x**2 + 12*x*y + 12*y**2 - 34) == \ {(-1, -1), (-1, 2), (1, -2), (1, 1)} def test_quadratic_parabolic_case(): # Parabolic case: B**2 - 4AC = 0 assert check_solutions(8*x**2 - 24*x*y + 18*y**2 + 5*x + 7*y + 16) assert check_solutions(8*x**2 - 24*x*y + 18*y**2 + 6*x + 12*y - 6) assert check_solutions(8*x**2 + 24*x*y + 18*y**2 + 4*x + 6*y - 7) assert check_solutions(-4*x**2 + 4*x*y - y**2 + 2*x - 3) assert check_solutions(x**2 + 2*x*y + y**2 + 2*x + 2*y + 1) assert check_solutions(x**2 - 2*x*y + y**2 + 2*x + 2*y + 1) assert check_solutions(y**2 - 41*x + 40) def test_quadratic_perfect_square(): # B**2 - 4*A*C > 0 # B**2 - 4*A*C is a perfect square assert check_solutions(48*x*y) assert check_solutions(4*x**2 - 5*x*y + y**2 + 2) assert check_solutions(-2*x**2 - 3*x*y + 2*y**2 -2*x - 17*y + 25) assert check_solutions(12*x**2 + 13*x*y + 3*y**2 - 2*x + 3*y - 12) assert check_solutions(8*x**2 + 10*x*y + 2*y**2 - 32*x - 13*y - 23) assert check_solutions(4*x**2 - 4*x*y - 3*y- 8*x - 3) assert check_solutions(- 4*x*y - 4*y**2 - 3*y- 5*x - 10) assert check_solutions(x**2 - y**2 - 2*x - 2*y) assert check_solutions(x**2 - 9*y**2 - 2*x - 6*y) assert check_solutions(4*x**2 - 9*y**2 - 4*x - 12*y - 3) def test_quadratic_non_perfect_square(): # B**2 - 4*A*C is not a perfect square # Used check_solutions() since the solutions are complex expressions involving # square roots and exponents assert check_solutions(x**2 - 2*x - 5*y**2) assert check_solutions(3*x**2 - 2*y**2 - 2*x - 2*y) assert check_solutions(x**2 - x*y - y**2 - 3*y) assert check_solutions(x**2 - 9*y**2 - 2*x - 6*y) def test_issue_9106(): eq = -48 - 2*x*(3*x - 1) + y*(3*y - 1) v = (x, y) for sol in diophantine(eq): assert not diop_simplify(eq.xreplace(dict(zip(v, sol)))) def test_issue_18138(): eq = x**2 - x - y**2 v = (x, y) for sol in diophantine(eq): assert not diop_simplify(eq.xreplace(dict(zip(v, sol)))) @slow def test_quadratic_non_perfect_slow(): assert check_solutions(8*x**2 + 10*x*y - 2*y**2 - 32*x - 13*y - 23) # This leads to very large numbers. # assert check_solutions(5*x**2 - 13*x*y + y**2 - 4*x - 4*y - 15) assert check_solutions(-3*x**2 - 2*x*y + 7*y**2 - 5*x - 7) assert check_solutions(-4 - x + 4*x**2 - y - 3*x*y - 4*y**2) assert check_solutions(1 + 2*x + 2*x**2 + 2*y + x*y - 2*y**2) def test_DN(): # Most of the test cases were adapted from, # Solving the generalized Pell equation x**2 - D*y**2 = N, John P. Robertson, July 31, 2004. # http://www.jpr2718.org/pell.pdf # others are verified using Wolfram Alpha. # Covers cases where D <= 0 or D > 0 and D is a square or N = 0 # Solutions are straightforward in these cases. assert diop_DN(3, 0) == [(0, 0)] assert diop_DN(-17, -5) == [] assert diop_DN(-19, 23) == [(2, 1)] assert diop_DN(-13, 17) == [(2, 1)] assert diop_DN(-15, 13) == [] assert diop_DN(0, 5) == [] assert diop_DN(0, 9) == [(3, t)] assert diop_DN(9, 0) == [(3*t, t)] assert diop_DN(16, 24) == [] assert diop_DN(9, 180) == [(18, 4)] assert diop_DN(9, -180) == [(12, 6)] assert diop_DN(7, 0) == [(0, 0)] # When equation is x**2 + y**2 = N # Solutions are interchangeable assert diop_DN(-1, 5) == [(2, 1), (1, 2)] assert diop_DN(-1, 169) == [(12, 5), (5, 12), (13, 0), (0, 13)] # D > 0 and D is not a square # N = 1 assert diop_DN(13, 1) == [(649, 180)] assert diop_DN(980, 1) == [(51841, 1656)] assert diop_DN(981, 1) == [(158070671986249, 5046808151700)] assert diop_DN(986, 1) == [(49299, 1570)] assert diop_DN(991, 1) == [(379516400906811930638014896080, 12055735790331359447442538767)] assert diop_DN(17, 1) == [(33, 8)] assert diop_DN(19, 1) == [(170, 39)] # N = -1 assert diop_DN(13, -1) == [(18, 5)] assert diop_DN(991, -1) == [] assert diop_DN(41, -1) == [(32, 5)] assert diop_DN(290, -1) == [(17, 1)] assert diop_DN(21257, -1) == [(13913102721304, 95427381109)] assert diop_DN(32, -1) == [] # |N| > 1 # Some tests were created using calculator at # http://www.numbertheory.org/php/patz.html assert diop_DN(13, -4) == [(3, 1), (393, 109), (36, 10)] # Source I referred returned (3, 1), (393, 109) and (-3, 1) as fundamental solutions # So (-3, 1) and (393, 109) should be in the same equivalent class assert equivalent(-3, 1, 393, 109, 13, -4) == True assert diop_DN(13, 27) == [(220, 61), (40, 11), (768, 213), (12, 3)] assert set(diop_DN(157, 12)) == {(13, 1), (10663, 851), (579160, 46222), (483790960, 38610722), (26277068347, 2097138361), (21950079635497, 1751807067011)} assert diop_DN(13, 25) == [(3245, 900)] assert diop_DN(192, 18) == [] assert diop_DN(23, 13) == [(-6, 1), (6, 1)] assert diop_DN(167, 2) == [(13, 1)] assert diop_DN(167, -2) == [] assert diop_DN(123, -2) == [(11, 1)] # One calculator returned [(11, 1), (-11, 1)] but both of these are in # the same equivalence class assert equivalent(11, 1, -11, 1, 123, -2) assert diop_DN(123, -23) == [(-10, 1), (10, 1)] assert diop_DN(0, 0, t) == [(0, t)] assert diop_DN(0, -1, t) == [] def test_bf_pell(): assert diop_bf_DN(13, -4) == [(3, 1), (-3, 1), (36, 10)] assert diop_bf_DN(13, 27) == [(12, 3), (-12, 3), (40, 11), (-40, 11)] assert diop_bf_DN(167, -2) == [] assert diop_bf_DN(1729, 1) == [(44611924489705, 1072885712316)] assert diop_bf_DN(89, -8) == [(9, 1), (-9, 1)] assert diop_bf_DN(21257, -1) == [(13913102721304, 95427381109)] assert diop_bf_DN(340, -4) == [(756, 41)] assert diop_bf_DN(-1, 0, t) == [(0, 0)] assert diop_bf_DN(0, 0, t) == [(0, t)] assert diop_bf_DN(4, 0, t) == [(2*t, t), (-2*t, t)] assert diop_bf_DN(3, 0, t) == [(0, 0)] assert diop_bf_DN(1, -2, t) == [] def test_length(): assert length(2, 1, 0) == 1 assert length(-2, 4, 5) == 3 assert length(-5, 4, 17) == 4 assert length(0, 4, 13) == 6 assert length(7, 13, 11) == 23 assert length(1, 6, 4) == 2 def is_pell_transformation_ok(eq): """ Test whether X*Y, X, or Y terms are present in the equation after transforming the equation using the transformation returned by transformation_to_pell(). If they are not present we are good. Moreover, coefficient of X**2 should be a divisor of coefficient of Y**2 and the constant term. """ A, B = transformation_to_DN(eq) u = (A*Matrix([X, Y]) + B)[0] v = (A*Matrix([X, Y]) + B)[1] simplified = diop_simplify(eq.subs(zip((x, y), (u, v)))) coeff = dict([reversed(t.as_independent(*[X, Y])) for t in simplified.args]) for term in [X*Y, X, Y]: if term in coeff.keys(): return False for term in [X**2, Y**2, 1]: if term not in coeff.keys(): coeff[term] = 0 if coeff[X**2] != 0: return divisible(coeff[Y**2], coeff[X**2]) and \ divisible(coeff[1], coeff[X**2]) return True def test_transformation_to_pell(): assert is_pell_transformation_ok(-13*x**2 - 7*x*y + y**2 + 2*x - 2*y - 14) assert is_pell_transformation_ok(-17*x**2 + 19*x*y - 7*y**2 - 5*x - 13*y - 23) assert is_pell_transformation_ok(x**2 - y**2 + 17) assert is_pell_transformation_ok(-x**2 + 7*y**2 - 23) assert is_pell_transformation_ok(25*x**2 - 45*x*y + 5*y**2 - 5*x - 10*y + 5) assert is_pell_transformation_ok(190*x**2 + 30*x*y + y**2 - 3*y - 170*x - 130) assert is_pell_transformation_ok(x**2 - 2*x*y -190*y**2 - 7*y - 23*x - 89) assert is_pell_transformation_ok(15*x**2 - 9*x*y + 14*y**2 - 23*x - 14*y - 4950) def test_find_DN(): assert find_DN(x**2 - 2*x - y**2) == (1, 1) assert find_DN(x**2 - 3*y**2 - 5) == (3, 5) assert find_DN(x**2 - 2*x*y - 4*y**2 - 7) == (5, 7) assert find_DN(4*x**2 - 8*x*y - y**2 - 9) == (20, 36) assert find_DN(7*x**2 - 2*x*y - y**2 - 12) == (8, 84) assert find_DN(-3*x**2 + 4*x*y -y**2) == (1, 0) assert find_DN(-13*x**2 - 7*x*y + y**2 + 2*x - 2*y -14) == (101, -7825480) def test_ldescent(): # Equations which have solutions u = ([(13, 23), (3, -11), (41, -113), (4, -7), (-7, 4), (91, -3), (1, 1), (1, -1), (4, 32), (17, 13), (123689, 1), (19, -570)]) for a, b in u: w, x, y = ldescent(a, b) assert a*x**2 + b*y**2 == w**2 assert ldescent(-1, -1) is None def test_diop_ternary_quadratic_normal(): assert check_solutions(234*x**2 - 65601*y**2 - z**2) assert check_solutions(23*x**2 + 616*y**2 - z**2) assert check_solutions(5*x**2 + 4*y**2 - z**2) assert check_solutions(3*x**2 + 6*y**2 - 3*z**2) assert check_solutions(x**2 + 3*y**2 - z**2) assert check_solutions(4*x**2 + 5*y**2 - z**2) assert check_solutions(x**2 + y**2 - z**2) assert check_solutions(16*x**2 + y**2 - 25*z**2) assert check_solutions(6*x**2 - y**2 + 10*z**2) assert check_solutions(213*x**2 + 12*y**2 - 9*z**2) assert check_solutions(34*x**2 - 3*y**2 - 301*z**2) assert check_solutions(124*x**2 - 30*y**2 - 7729*z**2) def is_normal_transformation_ok(eq): A = transformation_to_normal(eq) X, Y, Z = A*Matrix([x, y, z]) simplified = diop_simplify(eq.subs(zip((x, y, z), (X, Y, Z)))) coeff = dict([reversed(t.as_independent(*[X, Y, Z])) for t in simplified.args]) for term in [X*Y, Y*Z, X*Z]: if term in coeff.keys(): return False return True def test_transformation_to_normal(): assert is_normal_transformation_ok(x**2 + 3*y**2 + z**2 - 13*x*y - 16*y*z + 12*x*z) assert is_normal_transformation_ok(x**2 + 3*y**2 - 100*z**2) assert is_normal_transformation_ok(x**2 + 23*y*z) assert is_normal_transformation_ok(3*y**2 - 100*z**2 - 12*x*y) assert is_normal_transformation_ok(x**2 + 23*x*y - 34*y*z + 12*x*z) assert is_normal_transformation_ok(z**2 + 34*x*y - 23*y*z + x*z) assert is_normal_transformation_ok(x**2 + y**2 + z**2 - x*y - y*z - x*z) assert is_normal_transformation_ok(x**2 + 2*y*z + 3*z**2) assert is_normal_transformation_ok(x*y + 2*x*z + 3*y*z) assert is_normal_transformation_ok(2*x*z + 3*y*z) def test_diop_ternary_quadratic(): assert check_solutions(2*x**2 + z**2 + y**2 - 4*x*y) assert check_solutions(x**2 - y**2 - z**2 - x*y - y*z) assert check_solutions(3*x**2 - x*y - y*z - x*z) assert check_solutions(x**2 - y*z - x*z) assert check_solutions(5*x**2 - 3*x*y - x*z) assert check_solutions(4*x**2 - 5*y**2 - x*z) assert check_solutions(3*x**2 + 2*y**2 - z**2 - 2*x*y + 5*y*z - 7*y*z) assert check_solutions(8*x**2 - 12*y*z) assert check_solutions(45*x**2 - 7*y**2 - 8*x*y - z**2) assert check_solutions(x**2 - 49*y**2 - z**2 + 13*z*y -8*x*y) assert check_solutions(90*x**2 + 3*y**2 + 5*x*y + 2*z*y + 5*x*z) assert check_solutions(x**2 + 3*y**2 + z**2 - x*y - 17*y*z) assert check_solutions(x**2 + 3*y**2 + z**2 - x*y - 16*y*z + 12*x*z) assert check_solutions(x**2 + 3*y**2 + z**2 - 13*x*y - 16*y*z + 12*x*z) assert check_solutions(x*y - 7*y*z + 13*x*z) assert diop_ternary_quadratic_normal(x**2 + y**2 + z**2) == (None, None, None) assert diop_ternary_quadratic_normal(x**2 + y**2) is None raises(ValueError, lambda: _diop_ternary_quadratic_normal((x, y, z), {x*y: 1, x**2: 2, y**2: 3, z**2: 0})) eq = -2*x*y - 6*x*z + 7*y**2 - 3*y*z + 4*z**2 assert diop_ternary_quadratic(eq) == (7, 2, 0) assert diop_ternary_quadratic_normal(4*x**2 + 5*y**2 - z**2) == \ (1, 0, 2) assert diop_ternary_quadratic(x*y + 2*y*z) == \ (-2, 0, n1) eq = -5*x*y - 8*x*z - 3*y*z + 8*z**2 assert parametrize_ternary_quadratic(eq) == \ (8*p**2 - 3*p*q, -8*p*q + 8*q**2, 5*p*q) # this cannot be tested with diophantine because it will # factor into a product assert diop_solve(x*y + 2*y*z) == (-2*p*q, -n1*p**2 + p**2, p*q) def test_square_factor(): assert square_factor(1) == square_factor(-1) == 1 assert square_factor(0) == 1 assert square_factor(5) == square_factor(-5) == 1 assert square_factor(4) == square_factor(-4) == 2 assert square_factor(12) == square_factor(-12) == 2 assert square_factor(6) == 1 assert square_factor(18) == 3 assert square_factor(52) == 2 assert square_factor(49) == 7 assert square_factor(392) == 14 assert square_factor(factorint(-12)) == 2 def test_parametrize_ternary_quadratic(): assert check_solutions(x**2 + y**2 - z**2) assert check_solutions(x**2 + 2*x*y + z**2) assert check_solutions(234*x**2 - 65601*y**2 - z**2) assert check_solutions(3*x**2 + 2*y**2 - z**2 - 2*x*y + 5*y*z - 7*y*z) assert check_solutions(x**2 - y**2 - z**2) assert check_solutions(x**2 - 49*y**2 - z**2 + 13*z*y - 8*x*y) assert check_solutions(8*x*y + z**2) assert check_solutions(124*x**2 - 30*y**2 - 7729*z**2) assert check_solutions(236*x**2 - 225*y**2 - 11*x*y - 13*y*z - 17*x*z) assert check_solutions(90*x**2 + 3*y**2 + 5*x*y + 2*z*y + 5*x*z) assert check_solutions(124*x**2 - 30*y**2 - 7729*z**2) def test_no_square_ternary_quadratic(): assert check_solutions(2*x*y + y*z - 3*x*z) assert check_solutions(189*x*y - 345*y*z - 12*x*z) assert check_solutions(23*x*y + 34*y*z) assert check_solutions(x*y + y*z + z*x) assert check_solutions(23*x*y + 23*y*z + 23*x*z) def test_descent(): u = ([(13, 23), (3, -11), (41, -113), (91, -3), (1, 1), (1, -1), (17, 13), (123689, 1), (19, -570)]) for a, b in u: w, x, y = descent(a, b) assert a*x**2 + b*y**2 == w**2 # the docstring warns against bad input, so these are expected results # - can't both be negative raises(TypeError, lambda: descent(-1, -3)) # A can't be zero unless B != 1 raises(ZeroDivisionError, lambda: descent(0, 3)) # supposed to be square-free raises(TypeError, lambda: descent(4, 3)) def test_diophantine(): assert check_solutions((x - y)*(y - z)*(z - x)) assert check_solutions((x - y)*(x**2 + y**2 - z**2)) assert check_solutions((x - 3*y + 7*z)*(x**2 + y**2 - z**2)) assert check_solutions((x**2 - 3*y**2 - 1)) assert check_solutions(y**2 + 7*x*y) assert check_solutions(x**2 - 3*x*y + y**2) assert check_solutions(z*(x**2 - y**2 - 15)) assert check_solutions(x*(2*y - 2*z + 5)) assert check_solutions((x**2 - 3*y**2 - 1)*(x**2 - y**2 - 15)) assert check_solutions((x**2 - 3*y**2 - 1)*(y - 7*z)) assert check_solutions((x**2 + y**2 - z**2)*(x - 7*y - 3*z + 4*w)) # Following test case caused problems in parametric representation # But this can be solved by factoring out y. # No need to use methods for ternary quadratic equations. assert check_solutions(y**2 - 7*x*y + 4*y*z) assert check_solutions(x**2 - 2*x + 1) assert diophantine(x - y) == diophantine(Eq(x, y)) # 18196 eq = x**4 + y**4 - 97 assert diophantine(eq, permute=True) == diophantine(-eq, permute=True) assert diophantine(3*x*pi - 2*y*pi) == {(2*t_0, 3*t_0)} eq = x**2 + y**2 + z**2 - 14 base_sol = {(1, 2, 3)} assert diophantine(eq) == base_sol complete_soln = set(signed_permutations(base_sol.pop())) assert diophantine(eq, permute=True) == complete_soln assert diophantine(x**2 + x*Rational(15, 14) - 3) == set() # test issue 11049 eq = 92*x**2 - 99*y**2 - z**2 coeff = eq.as_coefficients_dict() assert _diop_ternary_quadratic_normal((x, y, z), coeff) == \ (9, 7, 51) assert diophantine(eq) == {( 891*p**2 + 9*q**2, -693*p**2 - 102*p*q + 7*q**2, 5049*p**2 - 1386*p*q - 51*q**2)} eq = 2*x**2 + 2*y**2 - z**2 coeff = eq.as_coefficients_dict() assert _diop_ternary_quadratic_normal((x, y, z), coeff) == \ (1, 1, 2) assert diophantine(eq) == {( 2*p**2 - q**2, -2*p**2 + 4*p*q - q**2, 4*p**2 - 4*p*q + 2*q**2)} eq = 411*x**2+57*y**2-221*z**2 coeff = eq.as_coefficients_dict() assert _diop_ternary_quadratic_normal((x, y, z), coeff) == \ (2021, 2645, 3066) assert diophantine(eq) == \ {(115197*p**2 - 446641*q**2, -150765*p**2 + 1355172*p*q - 584545*q**2, 174762*p**2 - 301530*p*q + 677586*q**2)} eq = 573*x**2+267*y**2-984*z**2 coeff = eq.as_coefficients_dict() assert _diop_ternary_quadratic_normal((x, y, z), coeff) == \ (49, 233, 127) assert diophantine(eq) == \ {(4361*p**2 - 16072*q**2, -20737*p**2 + 83312*p*q - 76424*q**2, 11303*p**2 - 41474*p*q + 41656*q**2)} # this produces factors during reconstruction eq = x**2 + 3*y**2 - 12*z**2 coeff = eq.as_coefficients_dict() assert _diop_ternary_quadratic_normal((x, y, z), coeff) == \ (0, 2, 1) assert diophantine(eq) == \ {(24*p*q, 2*p**2 - 24*q**2, p**2 + 12*q**2)} # solvers have not been written for every type raises(NotImplementedError, lambda: diophantine(x*y**2 + 1)) # rational expressions assert diophantine(1/x) == set() assert diophantine(1/x + 1/y - S.Half) == {(6, 3), (-2, 1), (4, 4), (1, -2), (3, 6)} assert diophantine(x**2 + y**2 +3*x- 5, permute=True) == \ {(-1, 1), (-4, -1), (1, -1), (1, 1), (-4, 1), (-1, -1), (4, 1), (4, -1)} #test issue 18186 assert diophantine(y**4 + x**4 - 2**4 - 3**4, syms=(x, y), permute=True) == \ {(-3, -2), (-3, 2), (-2, -3), (-2, 3), (2, -3), (2, 3), (3, -2), (3, 2)} assert diophantine(y**4 + x**4 - 2**4 - 3**4, syms=(y, x), permute=True) == \ {(-3, -2), (-3, 2), (-2, -3), (-2, 3), (2, -3), (2, 3), (3, -2), (3, 2)} # issue 18122 assert check_solutions(x**2-y) assert check_solutions(y**2-x) assert diophantine((x**2-y), t) == {(t, t**2)} assert diophantine((y**2-x), t) == {(t**2, -t)} def test_general_pythagorean(): from sympy.abc import a, b, c, d, e assert check_solutions(a**2 + b**2 + c**2 - d**2) assert check_solutions(a**2 + 4*b**2 + 4*c**2 - d**2) assert check_solutions(9*a**2 + 4*b**2 + 4*c**2 - d**2) assert check_solutions(9*a**2 + 4*b**2 - 25*d**2 + 4*c**2 ) assert check_solutions(9*a**2 - 16*d**2 + 4*b**2 + 4*c**2) assert check_solutions(-e**2 + 9*a**2 + 4*b**2 + 4*c**2 + 25*d**2) assert check_solutions(16*a**2 - b**2 + 9*c**2 + d**2 + 25*e**2) def test_diop_general_sum_of_squares_quick(): for i in range(3, 10): assert check_solutions(sum(i**2 for i in symbols(':%i' % i)) - i) raises(ValueError, lambda: _diop_general_sum_of_squares((x, y), 2)) assert _diop_general_sum_of_squares((x, y, z), -2) == set() eq = x**2 + y**2 + z**2 - (1 + 4 + 9) assert diop_general_sum_of_squares(eq) == \ {(1, 2, 3)} eq = u**2 + v**2 + x**2 + y**2 + z**2 - 1313 assert len(diop_general_sum_of_squares(eq, 3)) == 3 # issue 11016 var = symbols(':5') + (symbols('6', negative=True),) eq = Add(*[i**2 for i in var]) - 112 base_soln = {(0, 1, 1, 5, 6, -7), (1, 1, 1, 3, 6, -8), (2, 3, 3, 4, 5, -7), (0, 1, 1, 1, 3, -10), (0, 0, 4, 4, 4, -8), (1, 2, 3, 3, 5, -8), (0, 1, 2, 3, 7, -7), (2, 2, 4, 4, 6, -6), (1, 1, 3, 4, 6, -7), (0, 2, 3, 3, 3, -9), (0, 0, 2, 2, 2, -10), (1, 1, 2, 3, 4, -9), (0, 1, 1, 2, 5, -9), (0, 0, 2, 6, 6, -6), (1, 3, 4, 5, 5, -6), (0, 2, 2, 2, 6, -8), (0, 3, 3, 3, 6, -7), (0, 2, 3, 5, 5, -7), (0, 1, 5, 5, 5, -6)} assert diophantine(eq) == base_soln assert len(diophantine(eq, permute=True)) == 196800 # handle negated squares with signsimp assert diophantine(12 - x**2 - y**2 - z**2) == {(2, 2, 2)} # diophantine handles simplification, so classify_diop should # not have to look for additional patterns that are removed # by diophantine eq = a**2 + b**2 + c**2 + d**2 - 4 raises(NotImplementedError, lambda: classify_diop(-eq)) def test_diop_partition(): for n in [8, 10]: for k in range(1, 8): for p in partition(n, k): assert len(p) == k assert [p for p in partition(3, 5)] == [] assert [list(p) for p in partition(3, 5, 1)] == [ [0, 0, 0, 0, 3], [0, 0, 0, 1, 2], [0, 0, 1, 1, 1]] assert list(partition(0)) == [()] assert list(partition(1, 0)) == [()] assert [list(i) for i in partition(3)] == [[1, 1, 1], [1, 2], [3]] def test_prime_as_sum_of_two_squares(): for i in [5, 13, 17, 29, 37, 41, 2341, 3557, 34841, 64601]: a, b = prime_as_sum_of_two_squares(i) assert a**2 + b**2 == i assert prime_as_sum_of_two_squares(7) is None ans = prime_as_sum_of_two_squares(800029) assert ans == (450, 773) and type(ans[0]) is int def test_sum_of_three_squares(): for i in [0, 1, 2, 34, 123, 34304595905, 34304595905394941, 343045959052344, 800, 801, 802, 803, 804, 805, 806]: a, b, c = sum_of_three_squares(i) assert a**2 + b**2 + c**2 == i assert sum_of_three_squares(7) is None assert sum_of_three_squares((4**5)*15) is None assert sum_of_three_squares(25) == (5, 0, 0) assert sum_of_three_squares(4) == (0, 0, 2) def test_sum_of_four_squares(): from random import randint # this should never fail n = randint(1, 100000000000000) assert sum(i**2 for i in sum_of_four_squares(n)) == n assert sum_of_four_squares(0) == (0, 0, 0, 0) assert sum_of_four_squares(14) == (0, 1, 2, 3) assert sum_of_four_squares(15) == (1, 1, 2, 3) assert sum_of_four_squares(18) == (1, 2, 2, 3) assert sum_of_four_squares(19) == (0, 1, 3, 3) assert sum_of_four_squares(48) == (0, 4, 4, 4) def test_power_representation(): tests = [(1729, 3, 2), (234, 2, 4), (2, 1, 2), (3, 1, 3), (5, 2, 2), (12352, 2, 4), (32760, 2, 3)] for test in tests: n, p, k = test f = power_representation(n, p, k) while True: try: l = next(f) assert len(l) == k chk_sum = 0 for l_i in l: chk_sum = chk_sum + l_i**p assert chk_sum == n except StopIteration: break assert list(power_representation(20, 2, 4, True)) == \ [(1, 1, 3, 3), (0, 0, 2, 4)] raises(ValueError, lambda: list(power_representation(1.2, 2, 2))) raises(ValueError, lambda: list(power_representation(2, 0, 2))) raises(ValueError, lambda: list(power_representation(2, 2, 0))) assert list(power_representation(-1, 2, 2)) == [] assert list(power_representation(1, 1, 1)) == [(1,)] assert list(power_representation(3, 2, 1)) == [] assert list(power_representation(4, 2, 1)) == [(2,)] assert list(power_representation(3**4, 4, 6, zeros=True)) == \ [(1, 2, 2, 2, 2, 2), (0, 0, 0, 0, 0, 3)] assert list(power_representation(3**4, 4, 5, zeros=False)) == [] assert list(power_representation(-2, 3, 2)) == [(-1, -1)] assert list(power_representation(-2, 4, 2)) == [] assert list(power_representation(0, 3, 2, True)) == [(0, 0)] assert list(power_representation(0, 3, 2, False)) == [] # when we are dealing with squares, do feasibility checks assert len(list(power_representation(4**10*(8*10 + 7), 2, 3))) == 0 # there will be a recursion error if these aren't recognized big = 2**30 for i in [13, 10, 7, 5, 4, 2, 1]: assert list(sum_of_powers(big, 2, big - i)) == [] def test_assumptions(): """ Test whether diophantine respects the assumptions. """ #Test case taken from the below so question regarding assumptions in diophantine module #https://stackoverflow.com/questions/23301941/how-can-i-declare-natural-symbols-with-sympy m, n = symbols('m n', integer=True, positive=True) diof = diophantine(n**2 + m*n - 500) assert diof == {(5, 20), (40, 10), (95, 5), (121, 4), (248, 2), (499, 1)} a, b = symbols('a b', integer=True, positive=False) diof = diophantine(a*b + 2*a + 3*b - 6) assert diof == {(-15, -3), (-9, -4), (-7, -5), (-6, -6), (-5, -8), (-4, -14)} def check_solutions(eq): """ Determines whether solutions returned by diophantine() satisfy the original equation. Hope to generalize this so we can remove functions like check_ternay_quadratic, check_solutions_normal, check_solutions() """ s = diophantine(eq) factors = Mul.make_args(eq) var = list(eq.free_symbols) var.sort(key=default_sort_key) while s: solution = s.pop() for f in factors: if diop_simplify(f.subs(zip(var, solution))) == 0: break else: return False return True def test_diopcoverage(): eq = (2*x + y + 1)**2 assert diop_solve(eq) == {(t_0, -2*t_0 - 1)} eq = 2*x**2 + 6*x*y + 12*x + 4*y**2 + 18*y + 18 assert diop_solve(eq) == {(t_0, -t_0 - 3), (2*t_0 - 3, -t_0)} assert diop_quadratic(x + y**2 - 3) == {(-t**2 + 3, -t)} assert diop_linear(x + y - 3) == (t_0, 3 - t_0) assert base_solution_linear(0, 1, 2, t=None) == (0, 0) ans = (3*t - 1, -2*t + 1) assert base_solution_linear(4, 8, 12, t) == ans assert base_solution_linear(4, 8, 12, t=None) == tuple(_.subs(t, 0) for _ in ans) assert cornacchia(1, 1, 20) is None assert cornacchia(1, 1, 5) == {(2, 1)} assert cornacchia(1, 2, 17) == {(3, 2)} raises(ValueError, lambda: reconstruct(4, 20, 1)) assert gaussian_reduce(4, 1, 3) == (1, 1) eq = -w**2 - x**2 - y**2 + z**2 assert diop_general_pythagorean(eq) == \ diop_general_pythagorean(-eq) == \ (m1**2 + m2**2 - m3**2, 2*m1*m3, 2*m2*m3, m1**2 + m2**2 + m3**2) assert check_param(S(3) + x/3, S(4) + x/2, S(2), x) == (None, None) assert check_param(Rational(3, 2), S(4) + x, S(2), x) == (None, None) assert check_param(S(4) + x, Rational(3, 2), S(2), x) == (None, None) assert _nint_or_floor(16, 10) == 2 assert _odd(1) == (not _even(1)) == True assert _odd(0) == (not _even(0)) == False assert _remove_gcd(2, 4, 6) == (1, 2, 3) raises(TypeError, lambda: _remove_gcd((2, 4, 6))) assert sqf_normal(2*3**2*5, 2*5*11, 2*7**2*11) == \ (11, 1, 5) # it's ok if these pass some day when the solvers are implemented raises(NotImplementedError, lambda: diophantine(x**2 + y**2 + x*y + 2*y*z - 12)) raises(NotImplementedError, lambda: diophantine(x**3 + y**2)) assert diop_quadratic(x**2 + y**2 - 1**2 - 3**4) == \ {(-9, -1), (-9, 1), (-1, -9), (-1, 9), (1, -9), (1, 9), (9, -1), (9, 1)} def test_holzer(): # if the input is good, don't let it diverge in holzer() # (but see test_fail_holzer below) assert holzer(2, 7, 13, 4, 79, 23) == (2, 7, 13) # None in uv condition met; solution is not Holzer reduced # so this will hopefully change but is here for coverage assert holzer(2, 6, 2, 1, 1, 10) == (2, 6, 2) raises(ValueError, lambda: holzer(2, 7, 14, 4, 79, 23)) @XFAIL def test_fail_holzer(): eq = lambda x, y, z: a*x**2 + b*y**2 - c*z**2 a, b, c = 4, 79, 23 x, y, z = xyz = 26, 1, 11 X, Y, Z = ans = 2, 7, 13 assert eq(*xyz) == 0 assert eq(*ans) == 0 assert max(a*x**2, b*y**2, c*z**2) <= a*b*c assert max(a*X**2, b*Y**2, c*Z**2) <= a*b*c h = holzer(x, y, z, a, b, c) assert h == ans # it would be nice to get the smaller soln def test_issue_9539(): assert diophantine(6*w + 9*y + 20*x - z) == \ {(t_0, t_1, t_1 + t_2, 6*t_0 + 29*t_1 + 9*t_2)} def test_issue_8943(): assert diophantine( (3*(x**2 + y**2 + z**2) - 14*(x*y + y*z + z*x))) == \ {(0, 0, 0)} def test_diop_sum_of_even_powers(): eq = x**4 + y**4 + z**4 - 2673 assert diop_solve(eq) == {(3, 6, 6), (2, 4, 7)} assert diop_general_sum_of_even_powers(eq, 2) == {(3, 6, 6), (2, 4, 7)} raises(NotImplementedError, lambda: diop_general_sum_of_even_powers(-eq, 2)) neg = symbols('neg', negative=True) eq = x**4 + y**4 + neg**4 - 2673 assert diop_general_sum_of_even_powers(eq) == {(-3, 6, 6)} assert diophantine(x**4 + y**4 + 2) == set() assert diop_general_sum_of_even_powers(x**4 + y**4 - 2, limit=0) == set() def test_sum_of_squares_powers(): tru = {(0, 0, 1, 1, 11), (0, 0, 5, 7, 7), (0, 1, 3, 7, 8), (0, 1, 4, 5, 9), (0, 3, 4, 7, 7), (0, 3, 5, 5, 8), (1, 1, 2, 6, 9), (1, 1, 6, 6, 7), (1, 2, 3, 3, 10), (1, 3, 4, 4, 9), (1, 5, 5, 6, 6), (2, 2, 3, 5, 9), (2, 3, 5, 6, 7), (3, 3, 4, 5, 8)} eq = u**2 + v**2 + x**2 + y**2 + z**2 - 123 ans = diop_general_sum_of_squares(eq, oo) # allow oo to be used assert len(ans) == 14 assert ans == tru raises(ValueError, lambda: list(sum_of_squares(10, -1))) assert list(sum_of_squares(-10, 2)) == [] assert list(sum_of_squares(2, 3)) == [] assert list(sum_of_squares(0, 3, True)) == [(0, 0, 0)] assert list(sum_of_squares(0, 3)) == [] assert list(sum_of_squares(4, 1)) == [(2,)] assert list(sum_of_squares(5, 1)) == [] assert list(sum_of_squares(50, 2)) == [(5, 5), (1, 7)] assert list(sum_of_squares(11, 5, True)) == [ (1, 1, 1, 2, 2), (0, 0, 1, 1, 3)] assert list(sum_of_squares(8, 8)) == [(1, 1, 1, 1, 1, 1, 1, 1)] assert [len(list(sum_of_squares(i, 5, True))) for i in range(30)] == [ 1, 1, 1, 1, 2, 2, 1, 1, 2, 2, 2, 2, 2, 3, 2, 1, 3, 3, 3, 3, 4, 3, 3, 2, 2, 4, 4, 4, 4, 5] assert [len(list(sum_of_squares(i, 5))) for i in range(30)] == [ 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 3] for i in range(30): s1 = set(sum_of_squares(i, 5, True)) assert not s1 or all(sum(j**2 for j in t) == i for t in s1) s2 = set(sum_of_squares(i, 5)) assert all(sum(j**2 for j in t) == i for t in s2) raises(ValueError, lambda: list(sum_of_powers(2, -1, 1))) raises(ValueError, lambda: list(sum_of_powers(2, 1, -1))) assert list(sum_of_powers(-2, 3, 2)) == [(-1, -1)] assert list(sum_of_powers(-2, 4, 2)) == [] assert list(sum_of_powers(2, 1, 1)) == [(2,)] assert list(sum_of_powers(2, 1, 3, True)) == [(0, 0, 2), (0, 1, 1)] assert list(sum_of_powers(5, 1, 2, True)) == [(0, 5), (1, 4), (2, 3)] assert list(sum_of_powers(6, 2, 2)) == [] assert list(sum_of_powers(3**5, 3, 1)) == [] assert list(sum_of_powers(3**6, 3, 1)) == [(9,)] and (9**3 == 3**6) assert list(sum_of_powers(2**1000, 5, 2)) == [] def test__can_do_sum_of_squares(): assert _can_do_sum_of_squares(3, -1) is False assert _can_do_sum_of_squares(-3, 1) is False assert _can_do_sum_of_squares(0, 1) assert _can_do_sum_of_squares(4, 1) assert _can_do_sum_of_squares(1, 2) assert _can_do_sum_of_squares(2, 2) assert _can_do_sum_of_squares(3, 2) is False def test_diophantine_permute_sign(): from sympy.abc import a, b, c, d, e eq = a**4 + b**4 - (2**4 + 3**4) base_sol = {(2, 3)} assert diophantine(eq) == base_sol complete_soln = set(signed_permutations(base_sol.pop())) assert diophantine(eq, permute=True) == complete_soln eq = a**2 + b**2 + c**2 + d**2 + e**2 - 234 assert len(diophantine(eq)) == 35 assert len(diophantine(eq, permute=True)) == 62000 soln = {(-1, -1), (-1, 2), (1, -2), (1, 1)} assert diophantine(10*x**2 + 12*x*y + 12*y**2 - 34, permute=True) == soln @XFAIL def test_not_implemented(): eq = x**2 + y**4 - 1**2 - 3**4 assert diophantine(eq, syms=[x, y]) == {(9, 1), (1, 3)} def test_issue_9538(): eq = x - 3*y + 2 assert diophantine(eq, syms=[y,x]) == {(t_0, 3*t_0 - 2)} raises(TypeError, lambda: diophantine(eq, syms={y, x})) def test_ternary_quadratic(): # solution with 3 parameters s = diophantine(2*x**2 + y**2 - 2*z**2) p, q, r = ordered(S(s).free_symbols) assert s == {( p**2 - 2*q**2, -2*p**2 + 4*p*q - 4*p*r - 4*q**2, p**2 - 4*p*q + 2*q**2 - 4*q*r)} # solution with Mul in solution s = diophantine(x**2 + 2*y**2 - 2*z**2) assert s == {(4*p*q, p**2 - 2*q**2, p**2 + 2*q**2)} # solution with no Mul in solution s = diophantine(2*x**2 + 2*y**2 - z**2) assert s == {(2*p**2 - q**2, -2*p**2 + 4*p*q - q**2, 4*p**2 - 4*p*q + 2*q**2)} # reduced form when parametrized s = diophantine(3*x**2 + 72*y**2 - 27*z**2) assert s == {(24*p**2 - 9*q**2, 6*p*q, 8*p**2 + 3*q**2)} assert parametrize_ternary_quadratic( 3*x**2 + 2*y**2 - z**2 - 2*x*y + 5*y*z - 7*y*z) == ( 2*p**2 - 2*p*q - q**2, 2*p**2 + 2*p*q - q**2, 2*p**2 - 2*p*q + 3*q**2) assert parametrize_ternary_quadratic( 124*x**2 - 30*y**2 - 7729*z**2) == ( -1410*p**2 - 363263*q**2, 2700*p**2 + 30916*p*q - 695610*q**2, -60*p**2 + 5400*p*q + 15458*q**2)
2c9e7d5dcaf994c96eb0049ee6ed74f8e3fcad487f0a45c05c1e472605602f18
from sympy import (acos, acosh, asinh, atan, cos, Derivative, diff, Dummy, Eq, Ne, erfi, exp, Function, I, Integral, LambertW, log, O, pi, Rational, rootof, S, sin, sqrt, Subs, Symbol, tan, asin, sinh, Piecewise, symbols, Poly, sec, Ei, re, im, atan2, collect, hyper, simplify) from sympy.solvers.ode import (classify_ode, homogeneous_order, infinitesimals, checkinfsol, dsolve) from sympy.solvers.ode.subscheck import checkodesol, checksysodesol from sympy.solvers.ode.ode import (_linear_coeff_match, _ode_factorable_match, _remove_redundant_solutions, _undetermined_coefficients_match, classify_sysode, constant_renumber, constantsimp, get_numbered_constants, solve_ics) from sympy.functions import airyai, airybi, besselj, bessely from sympy.solvers.deutils import ode_order from sympy.testing.pytest import XFAIL, skip, raises, slow, ON_TRAVIS, SKIP from sympy.utilities.misc import filldedent C0, C1, C2, C3, C4, C5, C6, C7, C8, C9, C10 = symbols('C0:11') u, x, y, z = symbols('u,x:z', real=True) f = Function('f') g = Function('g') h = Function('h') # Note: the tests below may fail (but still be correct) if ODE solver, # the integral engine, solve(), or even simplify() changes. Also, in # differently formatted solutions, the arbitrary constants might not be # equal. Using specific hints in tests can help to avoid this. # Tests of order higher than 1 should run the solutions through # constant_renumber because it will normalize it (constant_renumber causes # dsolve() to return different results on different machines) def test_get_numbered_constants(): with raises(ValueError): get_numbered_constants(None) def test_dsolve_system(): eqs = [-f(x).diff(x), g(x).diff(x)] sols = {Eq(f(x), C1), Eq(g(x), C2)} assert set(dsolve(eqs)) == sols eqs = [f(x).diff(x, 2), g(x).diff(x)] with raises(ValueError): dsolve(eqs) # NotImplementedError would be better eqs = [f(x).diff(x) - x, f(x).diff(x) + x] with raises(ValueError): # Could also be NotImplementedError. f(x)=0 is a solution... dsolve(eqs) eqs = [f(x, y).diff(x)] with raises(ValueError): dsolve(eqs) eqs = [f(x, y).diff(x)+g(x).diff(x), g(x).diff(x)] with raises(ValueError): dsolve(eqs) def test_dsolve_all_hint(): eq = f(x).diff(x) output = dsolve(eq, hint='all') # Match the Dummy variables: sol1 = output['separable_Integral'] _y = sol1.lhs.args[1][0] sol1 = output['1st_homogeneous_coeff_subs_dep_div_indep_Integral'] _u1 = sol1.rhs.args[1].args[1][0] expected = { '1st_homogeneous_coeff_subs_indep_div_dep_Integral': Eq(f(x), C1), 'separable_Integral': Eq(Integral(1, (_y, f(x))), C1 + Integral(0, x)), 'separable': Eq(f(x), C1), 'lie_group': Eq(f(x), C1), 'nth_linear_constant_coeff_homogeneous': Eq(f(x), C1), 'nth_algebraic_Integral': Eq(f(x), C1), '1st_power_series': Eq(f(x), C1), '1st_homogeneous_coeff_subs_indep_div_dep': Eq(f(x), C1), '1st_linear': Eq(f(x), C1), '1st_homogeneous_coeff_subs_dep_div_indep': Eq(f(x), C1), '1st_homogeneous_coeff_subs_dep_div_indep_Integral': Eq(log(x), C1 + Integral(-1/_u1, (_u1, f(x)/x))), '1st_homogeneous_coeff_best': Eq(f(x), C1), 'nth_linear_euler_eq_homogeneous': Eq(f(x), C1), 'nth_algebraic': Eq(f(x), C1), '1st_linear_Integral': Eq(f(x), C1 + Integral(0, x)), 'best': Eq(f(x), C1), 'best_hint': 'nth_algebraic', 'default': 'nth_algebraic', 'order': 1 } assert output == expected assert dsolve(eq, hint='best') == Eq(f(x), C1) def test_dsolve_ics(): # Maybe this should just use one of the solutions instead of raising... with raises(NotImplementedError): dsolve(f(x).diff(x) - sqrt(f(x)), ics={f(1):1}) @XFAIL @slow def test_nonlinear_3eq_order1_type1(): if ON_TRAVIS: skip("Too slow for travis.") a, b, c = symbols('a b c') eqs = [ a * f(x).diff(x) - (b - c) * g(x) * h(x), b * g(x).diff(x) - (c - a) * h(x) * f(x), c * h(x).diff(x) - (a - b) * f(x) * g(x), ] assert dsolve(eqs) # NotImplementedError def test_dsolve_euler_rootof(): eq = x**6 * f(x).diff(x, 6) - x*f(x).diff(x) + f(x) sol = Eq(f(x), C1*x + C2*x**rootof(x**5 - 14*x**4 + 71*x**3 - 154*x**2 + 120*x - 1, 0) + C3*x**rootof(x**5 - 14*x**4 + 71*x**3 - 154*x**2 + 120*x - 1, 1) + C4*x**rootof(x**5 - 14*x**4 + 71*x**3 - 154*x**2 + 120*x - 1, 2) + C5*x**rootof(x**5 - 14*x**4 + 71*x**3 - 154*x**2 + 120*x - 1, 3) + C6*x**rootof(x**5 - 14*x**4 + 71*x**3 - 154*x**2 + 120*x - 1, 4) ) assert dsolve(eq) == sol def test_linear_2eq_order1_type2_noninvertible(): # a*d - b*c == 0 eqs = [Eq(diff(f(x), x), f(x) + g(x) + 5), Eq(diff(g(x), x), f(x) + g(x) + 7)] sol = [Eq(f(x), C1*exp(2*x) + C2 - x - 3), Eq(g(x), C1*exp(2*x) - C2 + x - 3)] assert dsolve(eqs) == sol assert checksysodesol(eqs, sol) == (True, [0, 0]) @XFAIL def test_linear_2eq_order1_type2_fixme(): # There is a FIXME comment about this in the code that handles this case. # The answer returned is currently incorrect as reported by checksysodesol # below... # a*d - b*c == 0 and a + b*c/a = 0 eqs = [Eq(diff(f(x), x), f(x) + g(x) + 5), Eq(diff(g(x), x), -f(x) - g(x) + 7)] sol = [Eq(f(x), C1 + C2*(x + 1) + 12*x**2 + 5*x), Eq(g(x), -C1 - C2*x - 12*x**2 + 7*x)] assert dsolve(eqs) == sol assert checksysodesol(eqs, sol) == (True, [0, 0]) def test_linear_2eq_order1_type4(): eqs = [Eq(diff(f(x), x), f(x) + x*g(x)), Eq(diff(g(x), x),-x*f(x) + g(x))] sol = [Eq(f(x), (C1*cos(x**2/2) + C2*sin(x**2/2))*exp(x)), Eq(g(x), (-C1*sin(x**2/2) + C2*cos(x**2/2))*exp(x))] # FIXME: This should probably be fixed so that this happens in the solver: dsolve_sol = dsolve(eqs) dsolve_sol = [s.doit() for s in sol] assert dsolve_sol == sol assert checksysodesol(eqs, sol) == (True, [0, 0]) @XFAIL def test_linear_2eq_order1_type4_broken(): eqs = [Eq(f(x).diff(x), f(x) + x*g(x)), Eq(g(x).diff(x), x*f(x) - g(x))] # FIXME: This is not the correct solution: sol = [Eq(f(x), (C1*sin(x) + C2*cos(x))*exp(x**2/2)), Eq(g(x), (C1*cos(x) - C2*sin(x))*exp(x**2/2))] dsolve_sol = dsolve(eqs) dsolve_sol = [s.doit() for s in sol] assert dsolve_sol == sol assert checksysodesol(eqs, sol) == (True, [0, 0]) def test_linear_2eq_order1_type5(): eqs = [Eq(diff(f(x), x), x*f(x) + x**2*g(x)), Eq(diff(g(x), x), 2*x**2*f(x) + (x + 3*x**2)*g(x))] sol = [ Eq(f(x), (C1*exp(x**3*(S(3)/2 + sqrt(17)/2)/3) + C2*exp(x**3*(-sqrt(17)/2 + S(3)/2)/3))*exp(x**2/2)), Eq(g(x), (C1*(S(3)/2 + sqrt(17)/2)*exp(x**3*(S(3)/2 + sqrt(17)/2)/3) + C2*(-sqrt(17)/2 + S(3)/2)*exp(x**3*(-sqrt(17)/2 + S(3)/2)/3))*exp(x**2/2)) ] dsolve_sol = dsolve(eqs) # FIXME: This should probably be fixed so that this happens in the solver: dsolve_sol = [s.doit() for s in sol] assert dsolve_sol == sol assert checksysodesol(eqs, sol) == (True, [0, 0]) @XFAIL def test_linear_2eq_order1_type6_path1(): eqs = [Eq(diff(f(x), x), f(x) + x*g(x)), Eq(diff(g(x), x), 2*(1 + 2/x)*f(x) + 2*(x - 1/x) * g(x))] # This solution is currently returned but is incorrect: sol = [ Eq(f(x), (C1 + Integral(C2*x*exp(-2*Integral(1/x, x))*exp(Integral(-2*x - 1, x)), x))*exp(-Integral(-2*x - 1, x))), Eq(g(x), C1*exp(-2*Integral(1/x, x)) + 2*(C1 + Integral(C2*x*exp(-2*Integral(1/x, x))*exp(Integral(-2*x - 1, x)), x))*exp(-Integral(-2*x - 1, x))) ] dsolve_sol = dsolve(eqs) # Comparing solutions with == doesn't work in this case... assert [ds.lhs for ds in dsolve_sol] == [f(x), g(x)] assert [ds.rhs.equals(ss.rhs) for ds, ss in zip(dsolve_sol, sol)] assert checksysodesol(eqs, sol) == (True, [0, 0]) # XFAIL @XFAIL def test_linear_2eq_order1_type6_path2(): # This is the reverse of the equations above and should also be handled by # type6. eqs = [Eq(diff(g(x), x), 2*(1 + 2/x)*g(x) + 2*(x - 1/x) * f(x)), Eq(diff(f(x), x), g(x) + x*f(x))] # This solution is currently returned but is incorrect: sol = [ Eq(g(x), C1*exp(-2*Integral(1/x, x)) + 2*(C1 + Integral(-C2*exp(-2*Integral(1/x, x))*exp(Integral(-2*x - 1, x)), x))*exp(-Integral(-2*x - 1, x))), Eq(f(x), (C1 + Integral(-C2*exp(-2*Integral(1/x, x))*exp(Integral(-2*x - 1, x)), x))*exp(-Integral(-2*x - 1, x))) ] dsolve_sol = dsolve(eqs) # Comparing solutions with == doesn't work in this case... assert [ds.lhs for ds in dsolve_sol] == [g(x), f(x)] assert [ds.rhs.equals(ss.rhs) for ds, ss in zip(dsolve_sol, sol)] assert checksysodesol(eqs, sol) == (True, [0, 0]) # XFAIL def test_nth_euler_imroot(): eq = x**2 * f(x).diff(x, 2) + x * f(x).diff(x) + 4 * f(x) - 1/x sol = Eq(f(x), C1*sin(2*log(x)) + C2*cos(2*log(x)) + 1/(5*x)) dsolve_sol = dsolve(eq, hint='nth_linear_euler_eq_nonhomogeneous_variation_of_parameters') assert dsolve_sol == sol assert checkodesol(eq, sol, order=2, solve_for_func=False)[0] def test_constant_coeff_circular_atan2(): eq = f(x).diff(x, x) + y*f(x) sol = Eq(f(x), C1*exp(-x*sqrt(-y)) + C2*exp(x*sqrt(-y))) assert dsolve(eq) == sol assert checkodesol(eq, sol, order=2, solve_for_func=False)[0] @XFAIL def test_linear_2eq_order2_type1_fail1(): eqs = [Eq(f(x).diff(x, 2), 2*f(x) + g(x)), Eq(g(x).diff(x, 2), -f(x))] # This is the returned solution but it isn't correct: sol = [ Eq(f(x), 2*C1*(x + 2)*exp(x) + 2*C2*(x + 2)*exp(-x) + 2*C3*x*exp(x) + 2*C4*x*exp(-x)), Eq(g(x), -2*C1*x*exp(x) - 2*C2*x*exp(-x) + C3*(-2*x + 4)*exp(x) + C4*(-2*x - 4)*exp(-x)) ] assert dsolve(eqs) == sol assert checksysodesol(eqs, sol) == (True, [0, 0]) @XFAIL def test_linear_2eq_order2_type1_fail2(): eqs = [Eq(f(x).diff(x, 2), 0), Eq(g(x).diff(x, 2), f(x))] sol = [ Eq(f(x), C1 + C2*x), Eq(g(x), C4 + C3*x + C2*x**3/6 + C1*x**2/2) ] assert dsolve(eqs) == sol # UnboundLocalError assert checksysodesol(eqs, sol) == (True, [0, 0]) def test_linear_2eq_order2_type1(): eqs = [Eq(f(x).diff(x, 2), 2*f(x)), Eq(g(x).diff(x, 2), -f(x) + 2*g(x))] sol = [ Eq(f(x), 2*sqrt(2)*C1*exp(sqrt(2)*x) + 2*sqrt(2)*C2*exp(-sqrt(2)*x)), Eq(g(x), -C1*x*exp(sqrt(2)*x) + C2*x*exp(-sqrt(2)*x) + C3*exp(sqrt(2)*x) + C4*exp(-sqrt(2)*x)) ] assert dsolve(eqs) == sol assert checksysodesol(eqs, sol) == (True, [0, 0]) eqs = [Eq(f(x).diff(x, 2), 2*f(x) + g(x)), Eq(g(x).diff(x, 2), + 2*g(x))] sol = [ Eq(f(x), C1*x*exp(sqrt(2)*x) - C2*x*exp(-sqrt(2)*x) + C3*exp(sqrt(2)*x) + C4*exp(-sqrt(2)*x)), Eq(g(x), 2*sqrt(2)*C1*exp(sqrt(2)*x) + 2*sqrt(2)*C2*exp(-sqrt(2)*x)) ] assert dsolve(eqs) == sol assert checksysodesol(eqs, sol) == (True, [0, 0]) eqs = [Eq(f(x).diff(x, 2), f(x)), Eq(g(x).diff(x, 2), f(x))] sol = [Eq(f(x), C1*exp(x) + C2*exp(-x)), Eq(g(x), C1*exp(x) + C2*exp(-x) - C3*x - C4)] assert dsolve(eqs) == sol assert checksysodesol(eqs, sol) == (True, [0, 0]) eqs = [Eq(f(x).diff(x, 2), f(x) + g(x)), Eq(g(x).diff(x, 2), -f(x) - g(x))] sol = [Eq(f(x), C1*x**3 + C2*x**2 + C3*x + C4), Eq(g(x), -C1*x**3 + 6*C1*x - C2*x**2 + 2*C2 - C3*x - C4)] assert dsolve(eqs) == sol assert checksysodesol(eqs, sol) == (True, [0, 0]) def test_linear_2eq_order2_type2(): eqs = [Eq(f(x).diff(x, 2), f(x) + g(x) + 1), Eq(g(x).diff(x, 2), f(x) + g(x) + 1)] sol = [Eq(f(x), C1*exp(sqrt(2)*x) + C2*exp(-sqrt(2)*x) + C3*x + C4 - S.Half), Eq(g(x), C1*exp(sqrt(2)*x) + C2*exp(-sqrt(2)*x) - C3*x - C4 - S.Half)] assert dsolve(eqs) == sol assert checksysodesol(eqs, sol) == (True, [0, 0]) eqs = [Eq(f(x).diff(x, 2), f(x) + g(x) + 1), Eq(g(x).diff(x, 2), -f(x) - g(x) + 1)] sol = [Eq(f(x), C1*x**3 + C2*x**2 + C3*x + C4 + x**4/12 + x**2/2), Eq(g(x), -C1*x**3 + 6*C1*x - C2*x**2 + 2*C2 - C3*x - C4 - x**4/12 + x**2/2)] assert dsolve(eqs) == sol assert checksysodesol(eqs, sol) == (True, [0, 0]) @XFAIL def test_linear_2eq_order2_type4(): Ca, Cb, Ra, Rb = symbols('Ca, Cb, Ra, Rb') eq = [f(x).diff(x, 2) + 2*f(x).diff(x) + f(x) + g(x) - 2*exp(I*x), g(x).diff(x, 2) + 2*g(x).diff(x) + f(x) + g(x) - 2*exp(I*x)] dsolve_sol = dsolve(eq) # Solution returned with Ca, Ra etc symbols is clearly incorrect: sol = [ Eq(f(x), C1 + C2*exp(2*x) + C3*exp(x*(1 + sqrt(3))) + C4*exp(x*(-sqrt(3) + 1)) + (I*Ca + Ra)*exp(I*x)), Eq(g(x), -C1 - 3*C2*exp(2*x) + C3*(-3*sqrt(3) - 4 + (1 + sqrt(3))**2)*exp(x*(1 + sqrt(3))) + C4*(-4 + (-sqrt(3) + 1)**2 + 3*sqrt(3))*exp(x*(-sqrt(3) + 1)) + (I*Cb + Rb)*exp(I*x)) ] assert dsolve_sol == sol assert checksysodesol(eq, sol) == (True, [0, 0]) # Fails here def test_linear_2eq_order2_type5(): eqs = [Eq(f(x).diff(x, 2), 2*(x*g(x).diff(x) - g(x))), Eq(g(x).diff(x, 2),-2*(x*f(x).diff(x) - f(x)))] sol = [Eq(f(x), C3*x + x*Integral((2*C1*cos(x**2) + 2*C2*sin(x**2))/x**2, x)), Eq(g(x), C4*x + x*Integral((-2*C1*sin(x**2) + 2*C2*cos(x**2))/x**2, x))] assert dsolve(eqs) == sol # FIXME: checksysodesol not working: #assert checksysodesol(eqs, sol) == (True, [0, 0]) def test_linear_2eq_order2_type8(): eqs = [Eq(f(x).diff(x, 2), 2/x *(x*g(x).diff(x) - g(x))), Eq(g(x).diff(x, 2),-2/x *(x*f(x).diff(x) - f(x)))] # FIXME: This is what is returned but it does not seem correct: sol = [Eq(f(x), C3*x + x*Integral((-C1*cos(Integral(-2, x)) - C2*sin(Integral(-2, x)))/x**2, x)), Eq(g(x), C4*x + x*Integral((-C1*sin(Integral(-2, x)) + C2*cos(Integral(-2, x)))/x**2, x))] assert dsolve(eqs) == sol assert checksysodesol(eqs, sol) == (True, [0, 0]) # Fails here def test_linear_3eq_order1_type2(): eqs = [ Eq(f(x).diff(x), 2*g(x) - 3*h(x)), Eq(g(x).diff(x), 4*h(x) - 2*f(x)), Eq(h(x).diff(x), 3*f(x) - 4*g(x)), ] sol = [ Eq(f(x), 4*C0 + sqrt(29)*C1*cos(sqrt(29)*x) + (6*C1 + 13*C2/2)*sin(sqrt(29)*x)), Eq(g(x), 3*C0 + sqrt(29)*C2*cos(sqrt(29)*x) + (-10*C1 - 6*C2)*sin(sqrt(29)*x)), Eq(h(x), 2*C0 + sqrt(29)*(-2*C1 - 3*C2/2)*cos(sqrt(29)*x) + (3*C1 - 4*C2)*sin(sqrt(29)*x)) ] assert dsolve(eqs) == sol assert checksysodesol(eqs, sol) == (True, [0, 0, 0]) def test_linear_3eq_order1_type3(): eqs = [ Eq(2*f(x).diff(x), 3*4*(g(x) - h(x))), Eq(3*g(x).diff(x), 2*4*(h(x) - f(x))), Eq(4*h(x).diff(x), 2*3*(f(x) - g(x))), ] sol = [ Eq(f(x), C0 + sqrt(29)*C1*cos(sqrt(29)*x) + (3*C1/2 + 75*C2/8)*sin(sqrt(29)*x)), Eq(g(x), C0 + sqrt(29)*C2*cos(sqrt(29)*x) + (-10*C1/3 - 3*C2/2)*sin(sqrt(29)*x)), Eq(h(x), C0 + sqrt(29)*(-C1/4 - 9*C2/16)*cos(sqrt(29)*x) + (3*C1/2 - 3*C2/2)*sin(sqrt(29)*x)) ] assert dsolve(eqs) == sol assert checksysodesol(eqs, sol) == (True, [0, 0, 0]) @XFAIL def test_nonlinear_3eq_order1_type4(): eqs = [ Eq(f(x).diff(x), (2*h(x)*g(x) - 3*g(x)*h(x))), Eq(g(x).diff(x), (4*f(x)*h(x) - 2*h(x)*f(x))), Eq(h(x).diff(x), (3*g(x)*f(x) - 4*f(x)*g(x))), ] dsolve_sol = dsolve(eqs) # KeyError when matching # sol = ? # assert dsolve_sol == sol assert checksysodesol(eqs, dsolve_sol) == (True, [0, 0, 0]) @slow @XFAIL def test_nonlinear_3eq_order1_type3(): if ON_TRAVIS: skip("Too slow for travis.") eqs = [ Eq(f(x).diff(x), (2*f(x)**2 - 3 )), Eq(g(x).diff(x), (4 - 2*h(x) )), Eq(h(x).diff(x), (3*h(x) - 4*f(x)**2)), ] dsolve_sol = dsolve(eqs) # Not sure if this finishes... # sol = ? # assert dsolve_sol == sol assert checksysodesol(eqs, dsolve_sol) == (True, [0, 0, 0]) @XFAIL def test_nonlinear_3eq_order1_type5(): eqs = [ Eq(f(x).diff(x), f(x)*(2*f(x) - 3*g(x))), Eq(g(x).diff(x), g(x)*(4*g(x) - 2*h(x))), Eq(h(x).diff(x), h(x)*(3*h(x) - 4*f(x))), ] dsolve_sol = dsolve(eqs) # KeyError # sol = ? # assert dsolve_sol == sol assert checksysodesol(eqs, dsolve_sol) == (True, [0, 0, 0]) def test_linear_2eq_order1(): x, y, z = symbols('x, y, z', cls=Function) k, l, m, n = symbols('k, l, m, n', Integer=True) t = Symbol('t') x0, y0 = symbols('x0, y0', cls=Function) eq1 = (Eq(diff(x(t),t), 9*y(t)), Eq(diff(y(t),t), 12*x(t))) sol1 = [Eq(x(t), 9*C1*exp(6*sqrt(3)*t) + 9*C2*exp(-6*sqrt(3)*t)), \ Eq(y(t), 6*sqrt(3)*C1*exp(6*sqrt(3)*t) - 6*sqrt(3)*C2*exp(-6*sqrt(3)*t))] assert checksysodesol(eq1, sol1) == (True, [0, 0]) eq2 = (Eq(diff(x(t),t), 2*x(t) + 4*y(t)), Eq(diff(y(t),t), 12*x(t) + 41*y(t))) sol2 = [Eq(x(t), 4*C1*exp(t*(sqrt(1713)/2 + Rational(43, 2))) + 4*C2*exp(t*(-sqrt(1713)/2 + Rational(43, 2)))), \ Eq(y(t), C1*(Rational(39, 2) + sqrt(1713)/2)*exp(t*(sqrt(1713)/2 + Rational(43, 2))) + \ C2*(-sqrt(1713)/2 + Rational(39, 2))*exp(t*(-sqrt(1713)/2 + Rational(43, 2))))] assert checksysodesol(eq2, sol2) == (True, [0, 0]) eq3 = (Eq(diff(x(t),t), x(t) + y(t)), Eq(diff(y(t),t), -2*x(t) + 2*y(t))) sol3 = [Eq(x(t), (C1*cos(sqrt(7)*t/2) + C2*sin(sqrt(7)*t/2))*exp(t*Rational(3, 2))), \ Eq(y(t), (C1*(-sqrt(7)*sin(sqrt(7)*t/2)/2 + cos(sqrt(7)*t/2)/2) + \ C2*(sin(sqrt(7)*t/2)/2 + sqrt(7)*cos(sqrt(7)*t/2)/2))*exp(t*Rational(3, 2)))] assert checksysodesol(eq3, sol3) == (True, [0, 0]) eq4 = (Eq(diff(x(t),t), x(t) + y(t) + 9), Eq(diff(y(t),t), 2*x(t) + 5*y(t) + 23)) sol4 = [Eq(x(t), C1*exp(t*(sqrt(6) + 3)) + C2*exp(t*(-sqrt(6) + 3)) - Rational(22, 3)), \ Eq(y(t), C1*(2 + sqrt(6))*exp(t*(sqrt(6) + 3)) + C2*(-sqrt(6) + 2)*exp(t*(-sqrt(6) + 3)) - Rational(5, 3))] assert checksysodesol(eq4, sol4) == (True, [0, 0]) eq5 = (Eq(diff(x(t),t), x(t) + y(t) + 81), Eq(diff(y(t),t), -2*x(t) + y(t) + 23)) sol5 = [Eq(x(t), (C1*cos(sqrt(2)*t) + C2*sin(sqrt(2)*t))*exp(t) - Rational(58, 3)), \ Eq(y(t), (-sqrt(2)*C1*sin(sqrt(2)*t) + sqrt(2)*C2*cos(sqrt(2)*t))*exp(t) - Rational(185, 3))] assert checksysodesol(eq5, sol5) == (True, [0, 0]) eq6 = (Eq(diff(x(t),t), 5*t*x(t) + 2*y(t)), Eq(diff(y(t),t), 2*x(t) + 5*t*y(t))) sol6 = [Eq(x(t), (C1*exp(2*t) + C2*exp(-2*t))*exp(Rational(5, 2)*t**2)), \ Eq(y(t), (C1*exp(2*t) - C2*exp(-2*t))*exp(Rational(5, 2)*t**2))] s = dsolve(eq6) assert checksysodesol(eq6, sol6) == (True, [0, 0]) eq7 = (Eq(diff(x(t),t), 5*t*x(t) + t**2*y(t)), Eq(diff(y(t),t), -t**2*x(t) + 5*t*y(t))) sol7 = [Eq(x(t), (C1*cos((t**3)/3) + C2*sin((t**3)/3))*exp(Rational(5, 2)*t**2)), \ Eq(y(t), (-C1*sin((t**3)/3) + C2*cos((t**3)/3))*exp(Rational(5, 2)*t**2))] assert checksysodesol(eq7, sol7) == (True, [0, 0]) eq8 = (Eq(diff(x(t),t), 5*t*x(t) + t**2*y(t)), Eq(diff(y(t),t), -t**2*x(t) + (5*t+9*t**2)*y(t))) sol8 = [Eq(x(t), (C1*exp((sqrt(77)/2 + Rational(9, 2))*(t**3)/3) + \ C2*exp((-sqrt(77)/2 + Rational(9, 2))*(t**3)/3))*exp(Rational(5, 2)*t**2)), \ Eq(y(t), (C1*(sqrt(77)/2 + Rational(9, 2))*exp((sqrt(77)/2 + Rational(9, 2))*(t**3)/3) + \ C2*(-sqrt(77)/2 + Rational(9, 2))*exp((-sqrt(77)/2 + Rational(9, 2))*(t**3)/3))*exp(Rational(5, 2)*t**2))] assert checksysodesol(eq8, sol8) == (True, [0, 0]) eq10 = (Eq(diff(x(t),t), 5*t*x(t) + t**2*y(t)), Eq(diff(y(t),t), (1-t**2)*x(t) + (5*t+9*t**2)*y(t))) sol10 = [Eq(x(t), C1*x0(t) + C2*x0(t)*Integral(t**2*exp(Integral(5*t, t))*exp(Integral(9*t**2 + 5*t, t))/x0(t)**2, t)), \ Eq(y(t), C1*y0(t) + C2*(y0(t)*Integral(t**2*exp(Integral(5*t, t))*exp(Integral(9*t**2 + 5*t, t))/x0(t)**2, t) + \ exp(Integral(5*t, t))*exp(Integral(9*t**2 + 5*t, t))/x0(t)))] s = dsolve(eq10) assert s == sol10 # too complicated to test with subs and simplify # assert checksysodesol(eq10, sol10) == (True, [0, 0]) # this one fails def test_linear_2eq_order1_nonhomog_linear(): e = [Eq(diff(f(x), x), f(x) + g(x) + 5*x), Eq(diff(g(x), x), f(x) - g(x))] raises(NotImplementedError, lambda: dsolve(e)) def test_linear_2eq_order1_nonhomog(): # Note: once implemented, add some tests esp. with resonance e = [Eq(diff(f(x), x), f(x) + exp(x)), Eq(diff(g(x), x), f(x) + g(x) + x*exp(x))] raises(NotImplementedError, lambda: dsolve(e)) def test_linear_2eq_order1_type2_degen(): e = [Eq(diff(f(x), x), f(x) + 5), Eq(diff(g(x), x), f(x) + 7)] s1 = [Eq(f(x), C1*exp(x) - 5), Eq(g(x), C1*exp(x) - C2 + 2*x - 5)] assert checksysodesol(e, s1) == (True, [0, 0]) def test_dsolve_linear_2eq_order1_diag_triangular(): e = [Eq(diff(f(x), x), f(x)), Eq(diff(g(x), x), g(x))] s1 = [Eq(f(x), C1*exp(x)), Eq(g(x), C2*exp(x))] assert checksysodesol(e, s1) == (True, [0, 0]) e = [Eq(diff(f(x), x), 2*f(x)), Eq(diff(g(x), x), 3*f(x) + 7*g(x))] s1 = [Eq(f(x), -5*C2*exp(2*x)), Eq(g(x), 5*C1*exp(7*x) + 3*C2*exp(2*x))] assert checksysodesol(e, s1) == (True, [0, 0]) def test_sysode_linear_2eq_order1_type1_D_lt_0(): e = [Eq(diff(f(x), x), -9*I*f(x) - 4*g(x)), Eq(diff(g(x), x), -4*I*g(x))] s1 = [Eq(f(x), -4*C1*exp(-4*I*x) - 4*C2*exp(-9*I*x)), \ Eq(g(x), 5*I*C1*exp(-4*I*x))] assert checksysodesol(e, s1) == (True, [0, 0]) def test_sysode_linear_2eq_order1_type1_D_lt_0_b_eq_0(): e = [Eq(diff(f(x), x), -9*I*f(x)), Eq(diff(g(x), x), -4*I*g(x))] s1 = [Eq(f(x), -5*I*C2*exp(-9*I*x)), Eq(g(x), 5*I*C1*exp(-4*I*x))] assert checksysodesol(e, s1) == (True, [0, 0]) def test_sysode_linear_2eq_order1_many_zeros(): t = Symbol('t') corner_cases = [(0, 0, 0, 0), (1, 0, 0, 0), (0, 1, 0, 0), (0, 0, 1, 0), (0, 0, 0, 1), (1, 0, 0, I), (I, 0, 0, -I), (0, I, 0, 0), (0, I, I, 0)] s1 = [[Eq(f(t), C1), Eq(g(t), C2)], [Eq(f(t), C1*exp(t)), Eq(g(t), -C2)], [Eq(f(t), C1 + C2*t), Eq(g(t), C2)], [Eq(f(t), C2), Eq(g(t), C1 + C2*t)], [Eq(f(t), -C2), Eq(g(t), C1*exp(t))], [Eq(f(t), C1*(1 - I)*exp(t)), Eq(g(t), C2*(-1 + I)*exp(I*t))], [Eq(f(t), 2*I*C1*exp(I*t)), Eq(g(t), -2*I*C2*exp(-I*t))], [Eq(f(t), I*C1 + I*C2*t), Eq(g(t), C2)], [Eq(f(t), I*C1*exp(I*t) + I*C2*exp(-I*t)), \ Eq(g(t), I*C1*exp(I*t) - I*C2*exp(-I*t))] ] for r, sol in zip(corner_cases, s1): eq = [Eq(diff(f(t), t), r[0]*f(t) + r[1]*g(t)), Eq(diff(g(t), t), r[2]*f(t) + r[3]*g(t))] assert checksysodesol(eq, sol) == (True, [0, 0]) def test_dsolve_linsystem_symbol_piecewise(): u = Symbol('u') # XXX it's more complicated with real u eq = (Eq(diff(f(x), x), 2*f(x) + g(x)), Eq(diff(g(x), x), u*f(x))) s1 = [Eq(f(x), Piecewise((C1*exp(x*(sqrt(4*u + 4)/2 + 1)) + C2*exp(x*(-sqrt(4*u + 4)/2 + 1)), Ne(4*u + 4, 0)), ((C1 + C2*(x + Piecewise((0, Eq(sqrt(4*u + 4)/2 + 1, 2)), (1/(-sqrt(4*u + 4)/2 + 1), True))))*exp(x*(sqrt(4*u + 4)/2 + 1)), True))), Eq(g(x), Piecewise((C1*(sqrt(4*u + 4)/2 - 1)*exp(x*(sqrt(4*u + 4)/2 + 1)) + C2*(-sqrt(4*u + 4)/2 - 1)*exp(x*(-sqrt(4*u + 4)/2 + 1)), Ne(4*u + 4, 0)), ((C1*(sqrt(4*u + 4)/2 - 1) + C2*(x*(sqrt(4*u + 4)/2 - 1) + Piecewise((1, Eq(sqrt(4*u + 4)/2 + 1, 2)), (0, True))))*exp(x*(sqrt(4*u + 4)/2 + 1)), True)))] assert dsolve(eq) == s1 # FIXME: assert checksysodesol(eq, s) == (True, [0, 0]) # Remove lines below when checksysodesol works s = [(l.lhs, l.rhs) for l in s1] for v in [0, 7, -42, 5*I, 3 + 4*I]: assert eq[0].subs(s).subs(u, v).doit().simplify() assert eq[1].subs(s).subs(u, v).doit().simplify() # example from https://groups.google.com/d/msg/sympy/xmzoqW6tWaE/sf0bgQrlCgAJ i, r1, c1, r2, c2, t = symbols('i, r1, c1, r2, c2, t') x1 = Function('x1') x2 = Function('x2') eq1 = r1*c1*Derivative(x1(t), t) + x1(t) - x2(t) - r1*i eq2 = r2*c1*Derivative(x1(t), t) + r2*c2*Derivative(x2(t), t) + x2(t) - r2*i sol = dsolve((eq1, eq2)) # FIXME: assert checksysodesol(eq, sol) == (True, [0, 0]) # Remove line below when checksysodesol works assert all(s.has(Piecewise) for s in sol) @slow def test_linear_2eq_order2(): x, y, z = symbols('x, y, z', cls=Function) k, l, m, n = symbols('k, l, m, n', Integer=True) t, l = symbols('t, l') x0, y0 = symbols('x0, y0', cls=Function) eq1 = (Eq(diff(x(t),t,t), 5*x(t) + 43*y(t)), Eq(diff(y(t),t,t), x(t) + 9*y(t))) sol1 = [Eq(x(t), 43*C1*exp(t*rootof(l**4 - 14*l**2 + 2, 0)) + 43*C2*exp(t*rootof(l**4 - 14*l**2 + 2, 1)) + \ 43*C3*exp(t*rootof(l**4 - 14*l**2 + 2, 2)) + 43*C4*exp(t*rootof(l**4 - 14*l**2 + 2, 3))), \ Eq(y(t), C1*(rootof(l**4 - 14*l**2 + 2, 0)**2 - 5)*exp(t*rootof(l**4 - 14*l**2 + 2, 0)) + \ C2*(rootof(l**4 - 14*l**2 + 2, 1)**2 - 5)*exp(t*rootof(l**4 - 14*l**2 + 2, 1)) + \ C3*(rootof(l**4 - 14*l**2 + 2, 2)**2 - 5)*exp(t*rootof(l**4 - 14*l**2 + 2, 2)) + \ C4*(rootof(l**4 - 14*l**2 + 2, 3)**2 - 5)*exp(t*rootof(l**4 - 14*l**2 + 2, 3)))] assert dsolve(eq1) == sol1 # FIXME: assert checksysodesol(eq1, sol1) == (True, [0, 0]) # this one fails eq2 = (Eq(diff(x(t),t,t), 8*x(t)+3*y(t)+31), Eq(diff(y(t),t,t), 9*x(t)+7*y(t)+12)) sol2 = [Eq(x(t), 3*C1*exp(t*rootof(l**4 - 15*l**2 + 29, 0)) + 3*C2*exp(t*rootof(l**4 - 15*l**2 + 29, 1)) + \ 3*C3*exp(t*rootof(l**4 - 15*l**2 + 29, 2)) + 3*C4*exp(t*rootof(l**4 - 15*l**2 + 29, 3)) - Rational(181, 29)), \ Eq(y(t), C1*(rootof(l**4 - 15*l**2 + 29, 0)**2 - 8)*exp(t*rootof(l**4 - 15*l**2 + 29, 0)) + \ C2*(rootof(l**4 - 15*l**2 + 29, 1)**2 - 8)*exp(t*rootof(l**4 - 15*l**2 + 29, 1)) + \ C3*(rootof(l**4 - 15*l**2 + 29, 2)**2 - 8)*exp(t*rootof(l**4 - 15*l**2 + 29, 2)) + \ C4*(rootof(l**4 - 15*l**2 + 29, 3)**2 - 8)*exp(t*rootof(l**4 - 15*l**2 + 29, 3)) + Rational(183, 29))] assert dsolve(eq2) == sol2 # FIXME: assert checksysodesol(eq2, sol2) == (True, [0, 0]) # this one fails eq3 = (Eq(diff(x(t),t,t) - 9*diff(y(t),t) + 7*x(t),0), Eq(diff(y(t),t,t) + 9*diff(x(t),t) + 7*y(t),0)) sol3 = [Eq(x(t), C1*cos(t*(Rational(9, 2) + sqrt(109)/2)) + C2*sin(t*(Rational(9, 2) + sqrt(109)/2)) + C3*cos(t*(-sqrt(109)/2 + Rational(9, 2))) + \ C4*sin(t*(-sqrt(109)/2 + Rational(9, 2)))), Eq(y(t), -C1*sin(t*(Rational(9, 2) + sqrt(109)/2)) + C2*cos(t*(Rational(9, 2) + sqrt(109)/2)) - \ C3*sin(t*(-sqrt(109)/2 + Rational(9, 2))) + C4*cos(t*(-sqrt(109)/2 + Rational(9, 2))))] assert dsolve(eq3) == sol3 assert checksysodesol(eq3, sol3) == (True, [0, 0]) eq4 = (Eq(diff(x(t),t,t), 9*t*diff(y(t),t)-9*y(t)), Eq(diff(y(t),t,t),7*t*diff(x(t),t)-7*x(t))) sol4 = [Eq(x(t), C3*t + t*Integral((9*C1*exp(3*sqrt(7)*t**2/2) + 9*C2*exp(-3*sqrt(7)*t**2/2))/t**2, t)), \ Eq(y(t), C4*t + t*Integral((3*sqrt(7)*C1*exp(3*sqrt(7)*t**2/2) - 3*sqrt(7)*C2*exp(-3*sqrt(7)*t**2/2))/t**2, t))] assert dsolve(eq4) == sol4 assert checksysodesol(eq4, sol4) == (True, [0, 0]) eq5 = (Eq(diff(x(t),t,t), (log(t)+t**2)*diff(x(t),t)+(log(t)+t**2)*3*diff(y(t),t)), Eq(diff(y(t),t,t), \ (log(t)+t**2)*2*diff(x(t),t)+(log(t)+t**2)*9*diff(y(t),t))) sol5 = [Eq(x(t), -sqrt(22)*(C1*Integral(exp((-sqrt(22) + 5)*Integral(t**2 + log(t), t)), t) + C2 - \ C3*Integral(exp((sqrt(22) + 5)*Integral(t**2 + log(t), t)), t) - C4 - \ (sqrt(22) + 5)*(C1*Integral(exp((-sqrt(22) + 5)*Integral(t**2 + log(t), t)), t) + C2) + \ (-sqrt(22) + 5)*(C3*Integral(exp((sqrt(22) + 5)*Integral(t**2 + log(t), t)), t) + C4))/88), \ Eq(y(t), -sqrt(22)*(C1*Integral(exp((-sqrt(22) + 5)*Integral(t**2 + log(t), t)), t) + \ C2 - C3*Integral(exp((sqrt(22) + 5)*Integral(t**2 + log(t), t)), t) - C4)/44)] assert dsolve(eq5) == sol5 assert checksysodesol(eq5, sol5) == (True, [0, 0]) eq6 = (Eq(diff(x(t),t,t), log(t)*t*diff(y(t),t) - log(t)*y(t)), Eq(diff(y(t),t,t), log(t)*t*diff(x(t),t) - log(t)*x(t))) sol6 = [Eq(x(t), C3*t + t*Integral((C1*exp(Integral(t*log(t), t)) + \ C2*exp(-Integral(t*log(t), t)))/t**2, t)), Eq(y(t), C4*t + t*Integral((C1*exp(Integral(t*log(t), t)) - \ C2*exp(-Integral(t*log(t), t)))/t**2, t))] assert dsolve(eq6) == sol6 assert checksysodesol(eq6, sol6) == (True, [0, 0]) eq7 = (Eq(diff(x(t),t,t), log(t)*(t*diff(x(t),t) - x(t)) + exp(t)*(t*diff(y(t),t) - y(t))), \ Eq(diff(y(t),t,t), (t**2)*(t*diff(x(t),t) - x(t)) + (t)*(t*diff(y(t),t) - y(t)))) sol7 = [Eq(x(t), C3*t + t*Integral((C1*x0(t) + C2*x0(t)*Integral(t*exp(t)*exp(Integral(t**2, t))*\ exp(Integral(t*log(t), t))/x0(t)**2, t))/t**2, t)), Eq(y(t), C4*t + t*Integral((C1*y0(t) + \ C2*(y0(t)*Integral(t*exp(t)*exp(Integral(t**2, t))*exp(Integral(t*log(t), t))/x0(t)**2, t) + \ exp(Integral(t**2, t))*exp(Integral(t*log(t), t))/x0(t)))/t**2, t))] assert dsolve(eq7) == sol7 # FIXME: assert checksysodesol(eq7, sol7) == (True, [0, 0]) eq8 = (Eq(diff(x(t),t,t), t*(4*x(t) + 9*y(t))), Eq(diff(y(t),t,t), t*(12*x(t) - 6*y(t)))) sol8 = [Eq(x(t), -sqrt(133)*(-4*C1*airyai(t*(-1 + sqrt(133))**(S(1)/3)) + 4*C1*airyai(-t*(1 + \ sqrt(133))**(S(1)/3)) - 4*C2*airybi(t*(-1 + sqrt(133))**(S(1)/3)) + 4*C2*airybi(-t*(1 + sqrt(133))**(S(1)/3)) +\ (-sqrt(133) - 1)*(C1*airyai(t*(-1 + sqrt(133))**(S(1)/3)) + C2*airybi(t*(-1 + sqrt(133))**(S(1)/3))) - (-1 +\ sqrt(133))*(C1*airyai(-t*(1 + sqrt(133))**(S(1)/3)) + C2*airybi(-t*(1 + sqrt(133))**(S(1)/3))))/3192), \ Eq(y(t), -sqrt(133)*(-C1*airyai(t*(-1 + sqrt(133))**(S(1)/3)) + C1*airyai(-t*(1 + sqrt(133))**(S(1)/3)) -\ C2*airybi(t*(-1 + sqrt(133))**(S(1)/3)) + C2*airybi(-t*(1 + sqrt(133))**(S(1)/3)))/266)] assert dsolve(eq8) == sol8 assert checksysodesol(eq8, sol8) == (True, [0, 0]) assert filldedent(dsolve(eq8)) == filldedent(''' [Eq(x(t), -sqrt(133)*(-4*C1*airyai(t*(-1 + sqrt(133))**(1/3)) + 4*C1*airyai(-t*(1 + sqrt(133))**(1/3)) - 4*C2*airybi(t*(-1 + sqrt(133))**(1/3)) + 4*C2*airybi(-t*(1 + sqrt(133))**(1/3)) + (-sqrt(133) - 1)*(C1*airyai(t*(-1 + sqrt(133))**(1/3)) + C2*airybi(t*(-1 + sqrt(133))**(1/3))) - (-1 + sqrt(133))*(C1*airyai(-t*(1 + sqrt(133))**(1/3)) + C2*airybi(-t*(1 + sqrt(133))**(1/3))))/3192), Eq(y(t), -sqrt(133)*(-C1*airyai(t*(-1 + sqrt(133))**(1/3)) + C1*airyai(-t*(1 + sqrt(133))**(1/3)) - C2*airybi(t*(-1 + sqrt(133))**(1/3)) + C2*airybi(-t*(1 + sqrt(133))**(1/3)))/266)]''') assert checksysodesol(eq8, sol8) == (True, [0, 0]) eq9 = (Eq(diff(x(t),t,t), t*(4*diff(x(t),t) + 9*diff(y(t),t))), Eq(diff(y(t),t,t), t*(12*diff(x(t),t) - 6*diff(y(t),t)))) sol9 = [Eq(x(t), -sqrt(133)*(4*C1*Integral(exp((-sqrt(133) - 1)*Integral(t, t)), t) + 4*C2 - \ 4*C3*Integral(exp((-1 + sqrt(133))*Integral(t, t)), t) - 4*C4 - (-1 + sqrt(133))*(C1*Integral(exp((-sqrt(133) - \ 1)*Integral(t, t)), t) + C2) + (-sqrt(133) - 1)*(C3*Integral(exp((-1 + sqrt(133))*Integral(t, t)), t) + \ C4))/3192), Eq(y(t), -sqrt(133)*(C1*Integral(exp((-sqrt(133) - 1)*Integral(t, t)), t) + C2 - \ C3*Integral(exp((-1 + sqrt(133))*Integral(t, t)), t) - C4)/266)] assert dsolve(eq9) == sol9 assert checksysodesol(eq9, sol9) == (True, [0, 0]) eq10 = (t**2*diff(x(t),t,t) + 3*t*diff(x(t),t) + 4*t*diff(y(t),t) + 12*x(t) + 9*y(t), \ t**2*diff(y(t),t,t) + 2*t*diff(x(t),t) - 5*t*diff(y(t),t) + 15*x(t) + 8*y(t)) sol10 = [Eq(x(t), -C1*(-2*sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + 2*(Rational(4333, 4) + \ 5*sqrt(70771857)/36)**Rational(1, 3)) + 13 + 2*sqrt(-284/sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + \ 4 + 2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) - 2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3) + 8 + \ 346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3))))*exp((-sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + \ 4 + 2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3))/2 + 1 + sqrt(-284/sqrt(-346/(3*(Rational(4333, 4) + \ 5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + 2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) - 2*(Rational(4333, 4) + \ 5*sqrt(70771857)/36)**Rational(1, 3) + 8 + 346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)))/2)*log(t)) - \ C2*(-2*sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + 2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + \ 13 - 2*sqrt(-284/sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + 2*(Rational(4333, 4) + \ 5*sqrt(70771857)/36)**Rational(1, 3)) - 2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3) + 8 + 346/(3*(Rational(4333, 4) + \ 5*sqrt(70771857)/36)**Rational(1, 3))))*exp((-sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + \ 2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3))/2 + 1 - sqrt(-284/sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + \ 4 + 2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) - 2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3) + 8 + 346/(3*(Rational(4333, 4) + \ 5*sqrt(70771857)/36)**Rational(1, 3)))/2)*log(t)) - C3*t**(1 + sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + \ 2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3))/2 + sqrt(-2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3) + 8 + 346/(3*(Rational(4333, 4) + \ 5*sqrt(70771857)/36)**Rational(1, 3)) + 284/sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + 2*(Rational(4333, 4) + \ 5*sqrt(70771857)/36)**Rational(1, 3)))/2)*(2*sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + 2*(Rational(4333, 4) + \ 5*sqrt(70771857)/36)**Rational(1, 3)) + 13 + 2*sqrt(-2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3) + 8 + 346/(3*(Rational(4333, 4) + \ 5*sqrt(70771857)/36)**Rational(1, 3)) + 284/sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + 2*(Rational(4333, 4) + \ 5*sqrt(70771857)/36)**Rational(1, 3)))) - C4*t**(-sqrt(-2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3) + 8 + 346/(3*(Rational(4333, 4) + \ 5*sqrt(70771857)/36)**Rational(1, 3)) + 284/sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + 2*(Rational(4333, 4) + \ 5*sqrt(70771857)/36)**Rational(1, 3)))/2 + 1 + sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + 2*(Rational(4333, 4) + \ 5*sqrt(70771857)/36)**Rational(1, 3))/2)*(-2*sqrt(-2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3) + 8 + 346/(3*(Rational(4333, 4) + \ 5*sqrt(70771857)/36)**Rational(1, 3)) + 284/sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + 2*(Rational(4333, 4) + \ 5*sqrt(70771857)/36)**Rational(1, 3))) + 2*sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + 2*(Rational(4333, 4) + \ 5*sqrt(70771857)/36)**Rational(1, 3)) + 13)), Eq(y(t), C1*(-sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + \ 2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 14 + (-sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + \ 2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3))/2 + 1 + sqrt(-284/sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + \ 4 + 2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) - 2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3) + 8 + 346/(3*(Rational(4333, 4) + \ 5*sqrt(70771857)/36)**Rational(1, 3)))/2)**2 + sqrt(-284/sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + \ 2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) - 2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3) + 8 + 346/(3*(Rational(4333, 4) + \ 5*sqrt(70771857)/36)**Rational(1, 3))))*exp((-sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + 2*(Rational(4333, 4) + \ 5*sqrt(70771857)/36)**Rational(1, 3))/2 + 1 + sqrt(-284/sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + \ 2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) - 2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3) + 8 + 346/(3*(Rational(4333, 4) + \ 5*sqrt(70771857)/36)**Rational(1, 3)))/2)*log(t)) + C2*(-sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + \ 2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 14 - sqrt(-284/sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + \ 4 + 2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) - 2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3) + 8 + 346/(3*(Rational(4333, 4) + \ 5*sqrt(70771857)/36)**Rational(1, 3))) + (-sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + 2*(Rational(4333, 4) + \ 5*sqrt(70771857)/36)**Rational(1, 3))/2 + 1 - sqrt(-284/sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + \ 2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) - 2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3) + 8 + 346/(3*(Rational(4333, 4) + \ 5*sqrt(70771857)/36)**Rational(1, 3)))/2)**2)*exp((-sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + 2*(Rational(4333, 4) + \ 5*sqrt(70771857)/36)**Rational(1, 3))/2 + 1 - sqrt(-284/sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + \ 2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) - 2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3) + 8 + 346/(3*(Rational(4333, 4) + \ 5*sqrt(70771857)/36)**Rational(1, 3)))/2)*log(t)) + C3*t**(1 + sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + \ 2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3))/2 + sqrt(-2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3) + 8 + 346/(3*(Rational(4333, 4) + \ 5*sqrt(70771857)/36)**Rational(1, 3)) + 284/sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + 2*(Rational(4333, 4) + \ 5*sqrt(70771857)/36)**Rational(1, 3)))/2)*(sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + 2*(Rational(4333, 4) + \ 5*sqrt(70771857)/36)**Rational(1, 3)) + sqrt(-2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3) + 8 + 346/(3*(Rational(4333, 4) + \ 5*sqrt(70771857)/36)**Rational(1, 3)) + 284/sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + 2*(Rational(4333, 4) + \ 5*sqrt(70771857)/36)**Rational(1, 3))) + 14 + (1 + sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + 2*(Rational(4333, 4) + \ 5*sqrt(70771857)/36)**Rational(1, 3))/2 + sqrt(-2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3) + 8 + 346/(3*(Rational(4333, 4) + \ 5*sqrt(70771857)/36)**Rational(1, 3)) + 284/sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + 2*(Rational(4333, 4) + \ 5*sqrt(70771857)/36)**Rational(1, 3)))/2)**2) + C4*t**(-sqrt(-2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3) + 8 + \ 346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 284/sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + \ 4 + 2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)))/2 + 1 + sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + \ 4 + 2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3))/2)*(-sqrt(-2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3) + \ 8 + 346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 284/sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + \ 4 + 2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3))) + (-sqrt(-2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3) + 8 + \ 346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 284/sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + \ 4 + 2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)))/2 + 1 + sqrt(-346/(3*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + \ 4 + 2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3))/2)**2 + sqrt(-346/(3*(Rational(4333, 4) + \ 5*sqrt(70771857)/36)**Rational(1, 3)) + 4 + 2*(Rational(4333, 4) + 5*sqrt(70771857)/36)**Rational(1, 3)) + 14))] assert dsolve(eq10) == sol10 # FIXME: assert checksysodesol(eq10, sol10) == (True, [0, 0]) # this hangs or at least takes a while... def test_linear_3eq_order1(): x, y, z = symbols('x, y, z', cls=Function) t = Symbol('t') eq1 = (Eq(diff(x(t),t), 21*x(t)), Eq(diff(y(t),t), 17*x(t)+3*y(t)), Eq(diff(z(t),t), 5*x(t)+7*y(t)+9*z(t))) sol1 = [Eq(x(t), C1*exp(21*t)), Eq(y(t), 17*C1*exp(21*t)/18 + C2*exp(3*t)), \ Eq(z(t), 209*C1*exp(21*t)/216 - 7*C2*exp(3*t)/6 + C3*exp(9*t))] assert checksysodesol(eq1, sol1) == (True, [0, 0, 0]) eq2 = (Eq(diff(x(t),t),3*y(t)-11*z(t)),Eq(diff(y(t),t),7*z(t)-3*x(t)),Eq(diff(z(t),t),11*x(t)-7*y(t))) sol2 = [Eq(x(t), 7*C0 + sqrt(179)*C1*cos(sqrt(179)*t) + (77*C1/3 + 130*C2/3)*sin(sqrt(179)*t)), \ Eq(y(t), 11*C0 + sqrt(179)*C2*cos(sqrt(179)*t) + (-58*C1/3 - 77*C2/3)*sin(sqrt(179)*t)), \ Eq(z(t), 3*C0 + sqrt(179)*(-7*C1/3 - 11*C2/3)*cos(sqrt(179)*t) + (11*C1 - 7*C2)*sin(sqrt(179)*t))] assert checksysodesol(eq2, sol2) == (True, [0, 0, 0]) eq3 = (Eq(3*diff(x(t),t),4*5*(y(t)-z(t))),Eq(4*diff(y(t),t),3*5*(z(t)-x(t))),Eq(5*diff(z(t),t),3*4*(x(t)-y(t)))) sol3 = [Eq(x(t), C0 + 5*sqrt(2)*C1*cos(5*sqrt(2)*t) + (12*C1/5 + 164*C2/15)*sin(5*sqrt(2)*t)), \ Eq(y(t), C0 + 5*sqrt(2)*C2*cos(5*sqrt(2)*t) + (-51*C1/10 - 12*C2/5)*sin(5*sqrt(2)*t)), \ Eq(z(t), C0 + 5*sqrt(2)*(-9*C1/25 - 16*C2/25)*cos(5*sqrt(2)*t) + (12*C1/5 - 12*C2/5)*sin(5*sqrt(2)*t))] assert checksysodesol(eq3, sol3) == (True, [0, 0, 0]) f = t**3 + log(t) g = t**2 + sin(t) eq4 = (Eq(diff(x(t),t),(4*f+g)*x(t)-f*y(t)-2*f*z(t)), Eq(diff(y(t),t),2*f*x(t)+(f+g)*y(t)-2*f*z(t)), Eq(diff(z(t),t),5*f*x(t)+f*y(t)+(-3*f+g)*z(t))) sol4 = [Eq(x(t), (C1*exp(-2*Integral(t**3 + log(t), t)) + C2*(sqrt(3)*sin(sqrt(3)*Integral(t**3 + log(t), t))/6 \ + cos(sqrt(3)*Integral(t**3 + log(t), t))/2) + C3*(sin(sqrt(3)*Integral(t**3 + log(t), t))/2 - \ sqrt(3)*cos(sqrt(3)*Integral(t**3 + log(t), t))/6))*exp(Integral(-t**2 - sin(t), t))), Eq(y(t), \ (C2*(sqrt(3)*sin(sqrt(3)*Integral(t**3 + log(t), t))/6 + cos(sqrt(3)*Integral(t**3 + log(t), t))/2) + \ C3*(sin(sqrt(3)*Integral(t**3 + log(t), t))/2 - sqrt(3)*cos(sqrt(3)*Integral(t**3 + log(t), t))/6))*\ exp(Integral(-t**2 - sin(t), t))), Eq(z(t), (C1*exp(-2*Integral(t**3 + log(t), t)) + C2*cos(sqrt(3)*\ Integral(t**3 + log(t), t)) + C3*sin(sqrt(3)*Integral(t**3 + log(t), t)))*exp(Integral(-t**2 - sin(t), t)))] assert dsolve(eq4) == sol4 # FIXME: assert checksysodesol(eq4, sol4) == (True, [0, 0, 0]) # this one fails eq5 = (Eq(diff(x(t),t),4*x(t) - z(t)),Eq(diff(y(t),t),2*x(t)+2*y(t)-z(t)),Eq(diff(z(t),t),3*x(t)+y(t))) sol5 = [Eq(x(t), C1*exp(2*t) + C2*t*exp(2*t) + C2*exp(2*t) + C3*t**2*exp(2*t)/2 + C3*t*exp(2*t) + C3*exp(2*t)), \ Eq(y(t), C1*exp(2*t) + C2*t*exp(2*t) + C2*exp(2*t) + C3*t**2*exp(2*t)/2 + C3*t*exp(2*t)), \ Eq(z(t), 2*C1*exp(2*t) + 2*C2*t*exp(2*t) + C2*exp(2*t) + C3*t**2*exp(2*t) + C3*t*exp(2*t) + C3*exp(2*t))] assert checksysodesol(eq5, sol5) == (True, [0, 0, 0]) eq6 = (Eq(diff(x(t),t),4*x(t) - y(t) - 2*z(t)),Eq(diff(y(t),t),2*x(t) + y(t)- 2*z(t)),Eq(diff(z(t),t),5*x(t)-3*z(t))) sol6 = [Eq(x(t), C1*exp(2*t) + C2*(-sin(t)/5 + 3*cos(t)/5) + C3*(3*sin(t)/5 + cos(t)/5)), Eq(y(t), C2*(-sin(t)/5 + 3*cos(t)/5) + C3*(3*sin(t)/5 + cos(t)/5)), Eq(z(t), C1*exp(2*t) + C2*cos(t) + C3*sin(t))] assert checksysodesol(eq6, sol6) == (True, [0, 0, 0]) def test_linear_3eq_order1_nonhomog(): e = [Eq(diff(f(x), x), -9*f(x) - 4*g(x)), Eq(diff(g(x), x), -4*g(x)), Eq(diff(h(x), x), h(x) + exp(x))] raises(NotImplementedError, lambda: dsolve(e)) @XFAIL def test_linear_3eq_order1_diagonal(): # code makes assumptions about coefficients being nonzero, breaks when assumptions are not true e = [Eq(diff(f(x), x), f(x)), Eq(diff(g(x), x), g(x)), Eq(diff(h(x), x), h(x))] s1 = [Eq(f(x), C1*exp(x)), Eq(g(x), C2*exp(x)), Eq(h(x), C3*exp(x))] s = dsolve(e) assert s == s1 assert checksysodesol(e, s1) == (True, [0, 0, 0]) def test_nonlinear_2eq_order1(): x, y, z = symbols('x, y, z', cls=Function) t = Symbol('t') eq1 = (Eq(diff(x(t),t),x(t)*y(t)**3), Eq(diff(y(t),t),y(t)**5)) sol1 = [ Eq(x(t), C1*exp((-1/(4*C2 + 4*t))**(Rational(-1, 4)))), Eq(y(t), -(-1/(4*C2 + 4*t))**Rational(1, 4)), Eq(x(t), C1*exp(-1/(-1/(4*C2 + 4*t))**Rational(1, 4))), Eq(y(t), (-1/(4*C2 + 4*t))**Rational(1, 4)), Eq(x(t), C1*exp(-I/(-1/(4*C2 + 4*t))**Rational(1, 4))), Eq(y(t), -I*(-1/(4*C2 + 4*t))**Rational(1, 4)), Eq(x(t), C1*exp(I/(-1/(4*C2 + 4*t))**Rational(1, 4))), Eq(y(t), I*(-1/(4*C2 + 4*t))**Rational(1, 4))] assert dsolve(eq1) == sol1 assert checksysodesol(eq1, sol1) == (True, [0, 0]) eq2 = (Eq(diff(x(t),t), exp(3*x(t))*y(t)**3),Eq(diff(y(t),t), y(t)**5)) sol2 = [ Eq(x(t), -log(C1 - 3/(-1/(4*C2 + 4*t))**Rational(1, 4))/3), Eq(y(t), -(-1/(4*C2 + 4*t))**Rational(1, 4)), Eq(x(t), -log(C1 + 3/(-1/(4*C2 + 4*t))**Rational(1, 4))/3), Eq(y(t), (-1/(4*C2 + 4*t))**Rational(1, 4)), Eq(x(t), -log(C1 + 3*I/(-1/(4*C2 + 4*t))**Rational(1, 4))/3), Eq(y(t), -I*(-1/(4*C2 + 4*t))**Rational(1, 4)), Eq(x(t), -log(C1 - 3*I/(-1/(4*C2 + 4*t))**Rational(1, 4))/3), Eq(y(t), I*(-1/(4*C2 + 4*t))**Rational(1, 4))] assert dsolve(eq2) == sol2 assert checksysodesol(eq2, sol2) == (True, [0, 0]) eq3 = (Eq(diff(x(t),t), y(t)*x(t)), Eq(diff(y(t),t), x(t)**3)) tt = Rational(2, 3) sol3 = [ Eq(x(t), 6**tt/(6*(-sinh(sqrt(C1)*(C2 + t)/2)/sqrt(C1))**tt)), Eq(y(t), sqrt(C1 + C1/sinh(sqrt(C1)*(C2 + t)/2)**2)/3)] assert dsolve(eq3) == sol3 # FIXME: assert checksysodesol(eq3, sol3) == (True, [0, 0]) eq4 = (Eq(diff(x(t),t),x(t)*y(t)*sin(t)**2), Eq(diff(y(t),t),y(t)**2*sin(t)**2)) sol4 = set([Eq(x(t), -2*exp(C1)/(C2*exp(C1) + t - sin(2*t)/2)), Eq(y(t), -2/(C1 + t - sin(2*t)/2))]) assert dsolve(eq4) == sol4 # FIXME: assert checksysodesol(eq4, sol4) == (True, [0, 0]) eq5 = (Eq(x(t),t*diff(x(t),t)+diff(x(t),t)*diff(y(t),t)), Eq(y(t),t*diff(y(t),t)+diff(y(t),t)**2)) sol5 = set([Eq(x(t), C1*C2 + C1*t), Eq(y(t), C2**2 + C2*t)]) assert dsolve(eq5) == sol5 assert checksysodesol(eq5, sol5) == (True, [0, 0]) eq6 = (Eq(diff(x(t),t),x(t)**2*y(t)**3), Eq(diff(y(t),t),y(t)**5)) sol6 = [ Eq(x(t), 1/(C1 - 1/(-1/(4*C2 + 4*t))**Rational(1, 4))), Eq(y(t), -(-1/(4*C2 + 4*t))**Rational(1, 4)), Eq(x(t), 1/(C1 + (-1/(4*C2 + 4*t))**(Rational(-1, 4)))), Eq(y(t), (-1/(4*C2 + 4*t))**Rational(1, 4)), Eq(x(t), 1/(C1 + I/(-1/(4*C2 + 4*t))**Rational(1, 4))), Eq(y(t), -I*(-1/(4*C2 + 4*t))**Rational(1, 4)), Eq(x(t), 1/(C1 - I/(-1/(4*C2 + 4*t))**Rational(1, 4))), Eq(y(t), I*(-1/(4*C2 + 4*t))**Rational(1, 4))] assert dsolve(eq6) == sol6 assert checksysodesol(eq6, sol6) == (True, [0, 0]) @slow def test_nonlinear_3eq_order1(): x, y, z = symbols('x, y, z', cls=Function) t, u = symbols('t u') eq1 = (4*diff(x(t),t) + 2*y(t)*z(t), 3*diff(y(t),t) - z(t)*x(t), 5*diff(z(t),t) - x(t)*y(t)) sol1 = [Eq(4*Integral(1/(sqrt(-4*u**2 - 3*C1 + C2)*sqrt(-4*u**2 + 5*C1 - C2)), (u, x(t))), C3 - sqrt(15)*t/15), Eq(3*Integral(1/(sqrt(-6*u**2 - C1 + 5*C2)*sqrt(3*u**2 + C1 - 4*C2)), (u, y(t))), C3 + sqrt(5)*t/10), Eq(5*Integral(1/(sqrt(-10*u**2 - 3*C1 + C2)* sqrt(5*u**2 + 4*C1 - C2)), (u, z(t))), C3 + sqrt(3)*t/6)] assert [i.dummy_eq(j) for i, j in zip(dsolve(eq1), sol1)] # FIXME: assert checksysodesol(eq1, sol1) == (True, [0, 0, 0]) eq2 = (4*diff(x(t),t) + 2*y(t)*z(t)*sin(t), 3*diff(y(t),t) - z(t)*x(t)*sin(t), 5*diff(z(t),t) - x(t)*y(t)*sin(t)) sol2 = [Eq(3*Integral(1/(sqrt(-6*u**2 - C1 + 5*C2)*sqrt(3*u**2 + C1 - 4*C2)), (u, x(t))), C3 + sqrt(5)*cos(t)/10), Eq(4*Integral(1/(sqrt(-4*u**2 - 3*C1 + C2)*sqrt(-4*u**2 + 5*C1 - C2)), (u, y(t))), C3 - sqrt(15)*cos(t)/15), Eq(5*Integral(1/(sqrt(-10*u**2 - 3*C1 + C2)* sqrt(5*u**2 + 4*C1 - C2)), (u, z(t))), C3 + sqrt(3)*cos(t)/6)] assert [i.dummy_eq(j) for i, j in zip(dsolve(eq2), sol2)] # FIXME: assert checksysodesol(eq2, sol2) == (True, [0, 0, 0]) @slow def test_dsolve_options(): eq = x*f(x).diff(x) + f(x) a = dsolve(eq, hint='all') b = dsolve(eq, hint='all', simplify=False) c = dsolve(eq, hint='all_Integral') keys = ['1st_exact', '1st_exact_Integral', '1st_homogeneous_coeff_best', '1st_homogeneous_coeff_subs_dep_div_indep', '1st_homogeneous_coeff_subs_dep_div_indep_Integral', '1st_homogeneous_coeff_subs_indep_div_dep', '1st_homogeneous_coeff_subs_indep_div_dep_Integral', '1st_linear', '1st_linear_Integral', 'almost_linear', 'almost_linear_Integral', 'best', 'best_hint', 'default', 'lie_group', 'nth_linear_euler_eq_homogeneous', 'order', 'separable', 'separable_Integral'] Integral_keys = ['1st_exact_Integral', '1st_homogeneous_coeff_subs_dep_div_indep_Integral', '1st_homogeneous_coeff_subs_indep_div_dep_Integral', '1st_linear_Integral', 'almost_linear_Integral', 'best', 'best_hint', 'default', 'nth_linear_euler_eq_homogeneous', 'order', 'separable_Integral'] assert sorted(a.keys()) == keys assert a['order'] == ode_order(eq, f(x)) assert a['best'] == Eq(f(x), C1/x) assert dsolve(eq, hint='best') == Eq(f(x), C1/x) assert a['default'] == 'separable' assert a['best_hint'] == 'separable' assert not a['1st_exact'].has(Integral) assert not a['separable'].has(Integral) assert not a['1st_homogeneous_coeff_best'].has(Integral) assert not a['1st_homogeneous_coeff_subs_dep_div_indep'].has(Integral) assert not a['1st_homogeneous_coeff_subs_indep_div_dep'].has(Integral) assert not a['1st_linear'].has(Integral) assert a['1st_linear_Integral'].has(Integral) assert a['1st_exact_Integral'].has(Integral) assert a['1st_homogeneous_coeff_subs_dep_div_indep_Integral'].has(Integral) assert a['1st_homogeneous_coeff_subs_indep_div_dep_Integral'].has(Integral) assert a['separable_Integral'].has(Integral) assert sorted(b.keys()) == keys assert b['order'] == ode_order(eq, f(x)) assert b['best'] == Eq(f(x), C1/x) assert dsolve(eq, hint='best', simplify=False) == Eq(f(x), C1/x) assert b['default'] == 'separable' assert b['best_hint'] == '1st_linear' assert a['separable'] != b['separable'] assert a['1st_homogeneous_coeff_subs_dep_div_indep'] != \ b['1st_homogeneous_coeff_subs_dep_div_indep'] assert a['1st_homogeneous_coeff_subs_indep_div_dep'] != \ b['1st_homogeneous_coeff_subs_indep_div_dep'] assert not b['1st_exact'].has(Integral) assert not b['separable'].has(Integral) assert not b['1st_homogeneous_coeff_best'].has(Integral) assert not b['1st_homogeneous_coeff_subs_dep_div_indep'].has(Integral) assert not b['1st_homogeneous_coeff_subs_indep_div_dep'].has(Integral) assert not b['1st_linear'].has(Integral) assert b['1st_linear_Integral'].has(Integral) assert b['1st_exact_Integral'].has(Integral) assert b['1st_homogeneous_coeff_subs_dep_div_indep_Integral'].has(Integral) assert b['1st_homogeneous_coeff_subs_indep_div_dep_Integral'].has(Integral) assert b['separable_Integral'].has(Integral) assert sorted(c.keys()) == Integral_keys raises(ValueError, lambda: dsolve(eq, hint='notarealhint')) raises(ValueError, lambda: dsolve(eq, hint='Liouville')) assert dsolve(f(x).diff(x) - 1/f(x)**2, hint='all')['best'] == \ dsolve(f(x).diff(x) - 1/f(x)**2, hint='best') assert dsolve(f(x) + f(x).diff(x) + sin(x).diff(x) + 1, f(x), hint="1st_linear_Integral") == \ Eq(f(x), (C1 + Integral((-sin(x).diff(x) - 1)* exp(Integral(1, x)), x))*exp(-Integral(1, x))) def test_classify_ode(): assert classify_ode(f(x).diff(x, 2), f(x)) == \ ( 'nth_algebraic', 'nth_linear_constant_coeff_homogeneous', 'nth_linear_euler_eq_homogeneous', 'Liouville', '2nd_power_series_ordinary', 'nth_algebraic_Integral', 'Liouville_Integral', ) assert classify_ode(f(x), f(x)) == ('nth_algebraic', 'nth_algebraic_Integral') assert classify_ode(Eq(f(x).diff(x), 0), f(x)) == ( 'nth_algebraic', 'separable', '1st_linear', '1st_homogeneous_coeff_best', '1st_homogeneous_coeff_subs_indep_div_dep', '1st_homogeneous_coeff_subs_dep_div_indep', '1st_power_series', 'lie_group', 'nth_linear_constant_coeff_homogeneous', 'nth_linear_euler_eq_homogeneous', 'nth_algebraic_Integral', 'separable_Integral', '1st_linear_Integral', '1st_homogeneous_coeff_subs_indep_div_dep_Integral', '1st_homogeneous_coeff_subs_dep_div_indep_Integral') assert classify_ode(f(x).diff(x)**2, f(x)) == ('nth_algebraic', 'separable', '1st_linear', '1st_homogeneous_coeff_best', '1st_homogeneous_coeff_subs_indep_div_dep', '1st_homogeneous_coeff_subs_dep_div_indep', '1st_power_series', 'lie_group', 'nth_linear_constant_coeff_homogeneous', 'nth_linear_euler_eq_homogeneous', 'nth_algebraic_Integral', 'separable_Integral', '1st_linear_Integral', '1st_homogeneous_coeff_subs_indep_div_dep_Integral', '1st_homogeneous_coeff_subs_dep_div_indep_Integral') # issue 4749: f(x) should be cleared from highest derivative before classifying a = classify_ode(Eq(f(x).diff(x) + f(x), x), f(x)) b = classify_ode(f(x).diff(x)*f(x) + f(x)*f(x) - x*f(x), f(x)) c = classify_ode(f(x).diff(x)/f(x) + f(x)/f(x) - x/f(x), f(x)) assert a == ('1st_linear', 'Bernoulli', 'almost_linear', '1st_power_series', "lie_group", 'nth_linear_constant_coeff_undetermined_coefficients', 'nth_linear_constant_coeff_variation_of_parameters', '1st_linear_Integral', 'Bernoulli_Integral', 'almost_linear_Integral', 'nth_linear_constant_coeff_variation_of_parameters_Integral') assert b == ('factorable', '1st_linear', 'Bernoulli', '1st_power_series', 'lie_group', 'nth_linear_constant_coeff_undetermined_coefficients', 'nth_linear_constant_coeff_variation_of_parameters', '1st_linear_Integral', 'Bernoulli_Integral', 'nth_linear_constant_coeff_variation_of_parameters_Integral') assert c == ('1st_linear', 'Bernoulli', '1st_power_series', 'lie_group', 'nth_linear_constant_coeff_undetermined_coefficients', 'nth_linear_constant_coeff_variation_of_parameters', '1st_linear_Integral', 'Bernoulli_Integral', 'nth_linear_constant_coeff_variation_of_parameters_Integral') assert classify_ode( 2*x*f(x)*f(x).diff(x) + (1 + x)*f(x)**2 - exp(x), f(x) ) == ('Bernoulli', 'almost_linear', 'lie_group', 'Bernoulli_Integral', 'almost_linear_Integral') assert 'Riccati_special_minus2' in \ classify_ode(2*f(x).diff(x) + f(x)**2 - f(x)/x + 3*x**(-2), f(x)) raises(ValueError, lambda: classify_ode(x + f(x, y).diff(x).diff( y), f(x, y))) # issue 5176 k = Symbol('k') assert classify_ode(f(x).diff(x)/(k*f(x) + k*x*f(x)) + 2*f(x)/(k*f(x) + k*x*f(x)) + x*f(x).diff(x)/(k*f(x) + k*x*f(x)) + z, f(x)) == \ ('separable', '1st_exact', '1st_power_series', 'lie_group', 'separable_Integral', '1st_exact_Integral') # preprocessing ans = ('nth_algebraic', 'separable', '1st_exact', '1st_linear', 'Bernoulli', '1st_homogeneous_coeff_best', '1st_homogeneous_coeff_subs_indep_div_dep', '1st_homogeneous_coeff_subs_dep_div_indep', '1st_power_series', 'lie_group', 'nth_linear_constant_coeff_undetermined_coefficients', 'nth_linear_euler_eq_nonhomogeneous_undetermined_coefficients', 'nth_linear_constant_coeff_variation_of_parameters', 'nth_linear_euler_eq_nonhomogeneous_variation_of_parameters', 'nth_algebraic_Integral', 'separable_Integral', '1st_exact_Integral', '1st_linear_Integral', 'Bernoulli_Integral', '1st_homogeneous_coeff_subs_indep_div_dep_Integral', '1st_homogeneous_coeff_subs_dep_div_indep_Integral', 'nth_linear_constant_coeff_variation_of_parameters_Integral', 'nth_linear_euler_eq_nonhomogeneous_variation_of_parameters_Integral') # w/o f(x) given assert classify_ode(diff(f(x) + x, x) + diff(f(x), x)) == ans # w/ f(x) and prep=True assert classify_ode(diff(f(x) + x, x) + diff(f(x), x), f(x), prep=True) == ans assert classify_ode(Eq(2*x**3*f(x).diff(x), 0), f(x)) == \ ('factorable', 'nth_algebraic', 'separable', '1st_linear', '1st_power_series', 'lie_group', 'nth_linear_euler_eq_homogeneous', 'nth_algebraic_Integral', 'separable_Integral', '1st_linear_Integral') assert classify_ode(Eq(2*f(x)**3*f(x).diff(x), 0), f(x)) == \ ('factorable', 'nth_algebraic', 'separable', '1st_power_series', 'lie_group', 'nth_algebraic_Integral', 'separable_Integral') # test issue 13864 assert classify_ode(Eq(diff(f(x), x) - f(x)**x, 0), f(x)) == \ ('1st_power_series', 'lie_group') assert isinstance(classify_ode(Eq(f(x), 5), f(x), dict=True), dict) def test_classify_ode_ics(): # Dummy eq = f(x).diff(x, x) - f(x) # Not f(0) or f'(0) ics = {x: 1} raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics)) ############################ # f(0) type (AppliedUndef) # ############################ # Wrong function ics = {g(0): 1} raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics)) # Contains x ics = {f(x): 1} raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics)) # Too many args ics = {f(0, 0): 1} raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics)) # point contains f # XXX: Should be NotImplementedError ics = {f(0): f(1)} raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics)) # Does not raise ics = {f(0): 1} classify_ode(eq, f(x), ics=ics) ##################### # f'(0) type (Subs) # ##################### # Wrong function ics = {g(x).diff(x).subs(x, 0): 1} raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics)) # Contains x ics = {f(y).diff(y).subs(y, x): 1} raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics)) # Wrong variable ics = {f(y).diff(y).subs(y, 0): 1} raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics)) # Too many args ics = {f(x, y).diff(x).subs(x, 0): 1} raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics)) # Derivative wrt wrong vars ics = {Derivative(f(x), x, y).subs(x, 0): 1} raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics)) # point contains f # XXX: Should be NotImplementedError ics = {f(x).diff(x).subs(x, 0): f(0)} raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics)) # Does not raise ics = {f(x).diff(x).subs(x, 0): 1} classify_ode(eq, f(x), ics=ics) ########################### # f'(y) type (Derivative) # ########################### # Wrong function ics = {g(x).diff(x).subs(x, y): 1} raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics)) # Contains x ics = {f(y).diff(y).subs(y, x): 1} raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics)) # Too many args ics = {f(x, y).diff(x).subs(x, y): 1} raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics)) # Derivative wrt wrong vars ics = {Derivative(f(x), x, z).subs(x, y): 1} raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics)) # point contains f # XXX: Should be NotImplementedError ics = {f(x).diff(x).subs(x, y): f(0)} raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics)) # Does not raise ics = {f(x).diff(x).subs(x, y): 1} classify_ode(eq, f(x), ics=ics) def test_classify_sysode(): # Here x is assumed to be x(t) and y as y(t) for simplicity. # Similarly diff(x,t) and diff(y,y) is assumed to be x1 and y1 respectively. k, l, m, n = symbols('k, l, m, n', Integer=True) k1, k2, k3, l1, l2, l3, m1, m2, m3 = symbols('k1, k2, k3, l1, l2, l3, m1, m2, m3', Integer=True) P, Q, R, p, q, r = symbols('P, Q, R, p, q, r', cls=Function) P1, P2, P3, Q1, Q2, R1, R2 = symbols('P1, P2, P3, Q1, Q2, R1, R2', cls=Function) x, y, z = symbols('x, y, z', cls=Function) t = symbols('t') x1 = diff(x(t),t) ; y1 = diff(y(t),t) ; z1 = diff(z(t),t) x2 = diff(x(t),t,t) ; y2 = diff(y(t),t,t) eq1 = (Eq(diff(x(t),t), 5*t*x(t) + 2*y(t)), Eq(diff(y(t),t), 2*x(t) + 5*t*y(t))) sol1 = {'no_of_equation': 2, 'func_coeff': {(0, x(t), 0): -5*t, (1, x(t), 1): 0, (0, x(t), 1): 1, \ (1, y(t), 0): -5*t, (1, x(t), 0): -2, (0, y(t), 1): 0, (0, y(t), 0): -2, (1, y(t), 1): 1}, \ 'type_of_equation': 'type3', 'func': [x(t), y(t)], 'is_linear': True, 'eq': [-5*t*x(t) - 2*y(t) + \ Derivative(x(t), t), -5*t*y(t) - 2*x(t) + Derivative(y(t), t)], 'order': {y(t): 1, x(t): 1}} assert classify_sysode(eq1) == sol1 eq2 = (Eq(x2, k*x(t) - l*y1), Eq(y2, l*x1 + k*y(t))) sol2 = {'order': {y(t): 2, x(t): 2}, 'type_of_equation': 'type3', 'is_linear': True, 'eq': \ [-k*x(t) + l*Derivative(y(t), t) + Derivative(x(t), t, t), -k*y(t) - l*Derivative(x(t), t) + \ Derivative(y(t), t, t)], 'no_of_equation': 2, 'func_coeff': {(0, y(t), 0): 0, (0, x(t), 2): 1, \ (1, y(t), 1): 0, (1, y(t), 2): 1, (1, x(t), 2): 0, (0, y(t), 2): 0, (0, x(t), 0): -k, (1, x(t), 1): \ -l, (0, x(t), 1): 0, (0, y(t), 1): l, (1, x(t), 0): 0, (1, y(t), 0): -k}, 'func': [x(t), y(t)]} assert classify_sysode(eq2) == sol2 eq3 = (Eq(x2+4*x1+3*y1+9*x(t)+7*y(t), 11*exp(I*t)), Eq(y2+5*x1+8*y1+3*x(t)+12*y(t), 2*exp(I*t))) sol3 = {'no_of_equation': 2, 'func_coeff': {(1, x(t), 2): 0, (0, y(t), 2): 0, (0, x(t), 0): 9, \ (1, x(t), 1): 5, (0, x(t), 1): 4, (0, y(t), 1): 3, (1, x(t), 0): 3, (1, y(t), 0): 12, (0, y(t), 0): 7, \ (0, x(t), 2): 1, (1, y(t), 2): 1, (1, y(t), 1): 8}, 'type_of_equation': 'type4', 'func': [x(t), y(t)], \ 'is_linear': True, 'eq': [9*x(t) + 7*y(t) - 11*exp(I*t) + 4*Derivative(x(t), t) + 3*Derivative(y(t), t) + \ Derivative(x(t), t, t), 3*x(t) + 12*y(t) - 2*exp(I*t) + 5*Derivative(x(t), t) + 8*Derivative(y(t), t) + \ Derivative(y(t), t, t)], 'order': {y(t): 2, x(t): 2}} assert classify_sysode(eq3) == sol3 eq4 = (Eq((4*t**2 + 7*t + 1)**2*x2, 5*x(t) + 35*y(t)), Eq((4*t**2 + 7*t + 1)**2*y2, x(t) + 9*y(t))) sol4 = {'no_of_equation': 2, 'func_coeff': {(1, x(t), 2): 0, (0, y(t), 2): 0, (0, x(t), 0): -5, \ (1, x(t), 1): 0, (0, x(t), 1): 0, (0, y(t), 1): 0, (1, x(t), 0): -1, (1, y(t), 0): -9, (0, y(t), 0): -35, \ (0, x(t), 2): 16*t**4 + 56*t**3 + 57*t**2 + 14*t + 1, (1, y(t), 2): 16*t**4 + 56*t**3 + 57*t**2 + 14*t + 1, \ (1, y(t), 1): 0}, 'type_of_equation': 'type10', 'func': [x(t), y(t)], 'is_linear': True, \ 'eq': [(4*t**2 + 7*t + 1)**2*Derivative(x(t), t, t) - 5*x(t) - 35*y(t), (4*t**2 + 7*t + 1)**2*Derivative(y(t), t, t)\ - x(t) - 9*y(t)], 'order': {y(t): 2, x(t): 2}} assert classify_sysode(eq4) == sol4 eq5 = (Eq(diff(x(t),t), x(t) + y(t) + 9), Eq(diff(y(t),t), 2*x(t) + 5*y(t) + 23)) sol5 = {'no_of_equation': 2, 'func_coeff': {(0, x(t), 0): -1, (1, x(t), 1): 0, (0, x(t), 1): 1, (1, y(t), 0): -5, \ (1, x(t), 0): -2, (0, y(t), 1): 0, (0, y(t), 0): -1, (1, y(t), 1): 1}, 'type_of_equation': 'type2', \ 'func': [x(t), y(t)], 'is_linear': True, 'eq': [-x(t) - y(t) + Derivative(x(t), t) - 9, -2*x(t) - 5*y(t) + \ Derivative(y(t), t) - 23], 'order': {y(t): 1, x(t): 1}} assert classify_sysode(eq5) == sol5 eq6 = (Eq(x1, exp(k*x(t))*P(x(t),y(t))), Eq(y1,r(y(t))*P(x(t),y(t)))) sol6 = {'no_of_equation': 2, 'func_coeff': {(0, x(t), 0): 0, (1, x(t), 1): 0, (0, x(t), 1): 1, (1, y(t), 0): 0, \ (1, x(t), 0): 0, (0, y(t), 1): 0, (0, y(t), 0): 0, (1, y(t), 1): 1}, 'type_of_equation': 'type2', 'func': \ [x(t), y(t)], 'is_linear': False, 'eq': [-P(x(t), y(t))*exp(k*x(t)) + Derivative(x(t), t), -P(x(t), \ y(t))*r(y(t)) + Derivative(y(t), t)], 'order': {y(t): 1, x(t): 1}} assert classify_sysode(eq6) == sol6 eq7 = (Eq(x1, x(t)**2+y(t)/x(t)), Eq(y1, x(t)/y(t))) sol7 = {'no_of_equation': 2, 'func_coeff': {(0, x(t), 0): 0, (1, x(t), 1): 0, (0, x(t), 1): 1, (1, y(t), 0): 0, \ (1, x(t), 0): -1/y(t), (0, y(t), 1): 0, (0, y(t), 0): -1/x(t), (1, y(t), 1): 1}, 'type_of_equation': 'type3', \ 'func': [x(t), y(t)], 'is_linear': False, 'eq': [-x(t)**2 + Derivative(x(t), t) - y(t)/x(t), -x(t)/y(t) + \ Derivative(y(t), t)], 'order': {y(t): 1, x(t): 1}} assert classify_sysode(eq7) == sol7 eq8 = (Eq(x1, P1(x(t))*Q1(y(t))*R(x(t),y(t),t)), Eq(y1, P1(x(t))*Q1(y(t))*R(x(t),y(t),t))) sol8 = {'func': [x(t), y(t)], 'is_linear': False, 'type_of_equation': 'type4', 'eq': \ [-P1(x(t))*Q1(y(t))*R(x(t), y(t), t) + Derivative(x(t), t), -P1(x(t))*Q1(y(t))*R(x(t), y(t), t) + \ Derivative(y(t), t)], 'func_coeff': {(0, y(t), 1): 0, (1, y(t), 1): 1, (1, x(t), 1): 0, (0, y(t), 0): 0, \ (1, x(t), 0): 0, (0, x(t), 0): 0, (1, y(t), 0): 0, (0, x(t), 1): 1}, 'order': {y(t): 1, x(t): 1}, 'no_of_equation': 2} assert classify_sysode(eq8) == sol8 eq9 = (Eq(x1,3*y(t)-11*z(t)),Eq(y1,7*z(t)-3*x(t)),Eq(z1,11*x(t)-7*y(t))) sol9 = {'no_of_equation': 3, 'func_coeff': {(1, y(t), 0): 0, (2, y(t), 1): 0, (2, z(t), 1): 1, \ (0, x(t), 0): 0, (2, x(t), 1): 0, (1, x(t), 1): 0, (2, y(t), 0): 7, (0, x(t), 1): 1, (1, z(t), 1): 0, \ (0, y(t), 1): 0, (1, x(t), 0): 3, (0, z(t), 0): 11, (0, y(t), 0): -3, (1, z(t), 0): -7, (0, z(t), 1): 0, \ (2, x(t), 0): -11, (2, z(t), 0): 0, (1, y(t), 1): 1}, 'type_of_equation': 'type2', 'func': [x(t), y(t), z(t)], \ 'is_linear': True, 'eq': [-3*y(t) + 11*z(t) + Derivative(x(t), t), 3*x(t) - 7*z(t) + Derivative(y(t), t), \ -11*x(t) + 7*y(t) + Derivative(z(t), t)], 'order': {z(t): 1, y(t): 1, x(t): 1}} assert classify_sysode(eq9) == sol9 eq10 = (x2 + log(t)*(t*x1 - x(t)) + exp(t)*(t*y1 - y(t)), y2 + (t**2)*(t*x1 - x(t)) + (t)*(t*y1 - y(t))) sol10 = {'no_of_equation': 2, 'func_coeff': {(1, x(t), 2): 0, (0, y(t), 2): 0, (0, x(t), 0): -log(t), \ (1, x(t), 1): t**3, (0, x(t), 1): t*log(t), (0, y(t), 1): t*exp(t), (1, x(t), 0): -t**2, (1, y(t), 0): -t, \ (0, y(t), 0): -exp(t), (0, x(t), 2): 1, (1, y(t), 2): 1, (1, y(t), 1): t**2}, 'type_of_equation': 'type11', \ 'func': [x(t), y(t)], 'is_linear': True, 'eq': [(t*Derivative(x(t), t) - x(t))*log(t) + (t*Derivative(y(t), t) - \ y(t))*exp(t) + Derivative(x(t), t, t), t**2*(t*Derivative(x(t), t) - x(t)) + t*(t*Derivative(y(t), t) - y(t)) \ + Derivative(y(t), t, t)], 'order': {y(t): 2, x(t): 2}} assert classify_sysode(eq10) == sol10 eq11 = (Eq(x1,x(t)*y(t)**3), Eq(y1,y(t)**5)) sol11 = {'no_of_equation': 2, 'func_coeff': {(0, x(t), 0): -y(t)**3, (1, x(t), 1): 0, (0, x(t), 1): 1, \ (1, y(t), 0): 0, (1, x(t), 0): 0, (0, y(t), 1): 0, (0, y(t), 0): 0, (1, y(t), 1): 1}, 'type_of_equation': \ 'type1', 'func': [x(t), y(t)], 'is_linear': False, 'eq': [-x(t)*y(t)**3 + Derivative(x(t), t), \ -y(t)**5 + Derivative(y(t), t)], 'order': {y(t): 1, x(t): 1}} assert classify_sysode(eq11) == sol11 eq12 = (Eq(x1, y(t)), Eq(y1, x(t))) sol12 = {'no_of_equation': 2, 'func_coeff': {(0, x(t), 0): 0, (1, x(t), 1): 0, (0, x(t), 1): 1, (1, y(t), 0): 0, \ (1, x(t), 0): -1, (0, y(t), 1): 0, (0, y(t), 0): -1, (1, y(t), 1): 1}, 'type_of_equation': 'type1', 'func': \ [x(t), y(t)], 'is_linear': True, 'eq': [-y(t) + Derivative(x(t), t), -x(t) + Derivative(y(t), t)], 'order': {y(t): 1, x(t): 1}} assert classify_sysode(eq12) == sol12 eq13 = (Eq(x1,x(t)*y(t)*sin(t)**2), Eq(y1,y(t)**2*sin(t)**2)) sol13 = {'no_of_equation': 2, 'func_coeff': {(0, x(t), 0): -y(t)*sin(t)**2, (1, x(t), 1): 0, (0, x(t), 1): 1, \ (1, y(t), 0): 0, (1, x(t), 0): 0, (0, y(t), 1): 0, (0, y(t), 0): -x(t)*sin(t)**2, (1, y(t), 1): 1}, \ 'type_of_equation': 'type4', 'func': [x(t), y(t)], 'is_linear': False, 'eq': [-x(t)*y(t)*sin(t)**2 + \ Derivative(x(t), t), -y(t)**2*sin(t)**2 + Derivative(y(t), t)], 'order': {y(t): 1, x(t): 1}} assert classify_sysode(eq13) == sol13 eq14 = (Eq(x1, 21*x(t)), Eq(y1, 17*x(t)+3*y(t)), Eq(z1, 5*x(t)+7*y(t)+9*z(t))) sol14 = {'no_of_equation': 3, 'func_coeff': {(1, y(t), 0): -3, (2, y(t), 1): 0, (2, z(t), 1): 1, \ (0, x(t), 0): -21, (2, x(t), 1): 0, (1, x(t), 1): 0, (2, y(t), 0): -7, (0, x(t), 1): 1, (1, z(t), 1): 0, \ (0, y(t), 1): 0, (1, x(t), 0): -17, (0, z(t), 0): 0, (0, y(t), 0): 0, (1, z(t), 0): 0, (0, z(t), 1): 0, \ (2, x(t), 0): -5, (2, z(t), 0): -9, (1, y(t), 1): 1}, 'type_of_equation': 'type1', 'func': [x(t), y(t), z(t)], \ 'is_linear': True, 'eq': [-21*x(t) + Derivative(x(t), t), -17*x(t) - 3*y(t) + Derivative(y(t), t), -5*x(t) - \ 7*y(t) - 9*z(t) + Derivative(z(t), t)], 'order': {z(t): 1, y(t): 1, x(t): 1}} assert classify_sysode(eq14) == sol14 eq15 = (Eq(x1,4*x(t)+5*y(t)+2*z(t)),Eq(y1,x(t)+13*y(t)+9*z(t)),Eq(z1,32*x(t)+41*y(t)+11*z(t))) sol15 = {'no_of_equation': 3, 'func_coeff': {(1, y(t), 0): -13, (2, y(t), 1): 0, (2, z(t), 1): 1, \ (0, x(t), 0): -4, (2, x(t), 1): 0, (1, x(t), 1): 0, (2, y(t), 0): -41, (0, x(t), 1): 1, (1, z(t), 1): 0, \ (0, y(t), 1): 0, (1, x(t), 0): -1, (0, z(t), 0): -2, (0, y(t), 0): -5, (1, z(t), 0): -9, (0, z(t), 1): 0, \ (2, x(t), 0): -32, (2, z(t), 0): -11, (1, y(t), 1): 1}, 'type_of_equation': 'type6', 'func': \ [x(t), y(t), z(t)], 'is_linear': True, 'eq': [-4*x(t) - 5*y(t) - 2*z(t) + Derivative(x(t), t), -x(t) - 13*y(t) - \ 9*z(t) + Derivative(y(t), t), -32*x(t) - 41*y(t) - 11*z(t) + Derivative(z(t), t)], 'order': {z(t): 1, y(t): 1, x(t): 1}} assert classify_sysode(eq15) == sol15 eq16 = (Eq(3*x1,4*5*(y(t)-z(t))),Eq(4*y1,3*5*(z(t)-x(t))),Eq(5*z1,3*4*(x(t)-y(t)))) sol16 = {'no_of_equation': 3, 'func_coeff': {(1, y(t), 0): 0, (2, y(t), 1): 0, (2, z(t), 1): 5, \ (0, x(t), 0): 0, (2, x(t), 1): 0, (1, x(t), 1): 0, (2, y(t), 0): 12, (0, x(t), 1): 3, (1, z(t), 1): 0, \ (0, y(t), 1): 0, (1, x(t), 0): 15, (0, z(t), 0): 20, (0, y(t), 0): -20, (1, z(t), 0): -15, (0, z(t), 1): 0, \ (2, x(t), 0): -12, (2, z(t), 0): 0, (1, y(t), 1): 4}, 'type_of_equation': 'type3', 'func': [x(t), y(t), z(t)], \ 'is_linear': True, 'eq': [-20*y(t) + 20*z(t) + 3*Derivative(x(t), t), 15*x(t) - 15*z(t) + 4*Derivative(y(t), t), \ -12*x(t) + 12*y(t) + 5*Derivative(z(t), t)], 'order': {z(t): 1, y(t): 1, x(t): 1}} assert classify_sysode(eq16) == sol16 # issue 8193: funcs parameter for classify_sysode has to actually work assert classify_sysode(eq1, funcs=[x(t), y(t)]) == sol1 def test_solve_ics(): # Basic tests that things work from dsolve. assert dsolve(f(x).diff(x) - 1/f(x), f(x), ics={f(1): 2}) == \ Eq(f(x), sqrt(2 * x + 2)) assert dsolve(f(x).diff(x) - f(x), f(x), ics={f(0): 1}) == Eq(f(x), exp(x)) assert dsolve(f(x).diff(x) - f(x), f(x), ics={f(x).diff(x).subs(x, 0): 1}) == Eq(f(x), exp(x)) assert dsolve(f(x).diff(x, x) + f(x), f(x), ics={f(0): 1, f(x).diff(x).subs(x, 0): 1}) == Eq(f(x), sin(x) + cos(x)) assert dsolve([f(x).diff(x) - f(x) + g(x), g(x).diff(x) - g(x) - f(x)], [f(x), g(x)], ics={f(0): 1, g(0): 0}) == [Eq(f(x), exp(x)*cos(x)), Eq(g(x), exp(x)*sin(x))] # Test cases where dsolve returns two solutions. eq = (x**2*f(x)**2 - x).diff(x) assert dsolve(eq, f(x), ics={f(1): 0}) == [Eq(f(x), -sqrt(x - 1)/x), Eq(f(x), sqrt(x - 1)/x)] assert dsolve(eq, f(x), ics={f(x).diff(x).subs(x, 1): 0}) == [Eq(f(x), -sqrt(x - S.Half)/x), Eq(f(x), sqrt(x - S.Half)/x)] eq = cos(f(x)) - (x*sin(f(x)) - f(x)**2)*f(x).diff(x) assert dsolve(eq, f(x), ics={f(0):1}, hint='1st_exact', simplify=False) == Eq(x*cos(f(x)) + f(x)**3/3, Rational(1, 3)) assert dsolve(eq, f(x), ics={f(0):1}, hint='1st_exact', simplify=True) == Eq(x*cos(f(x)) + f(x)**3/3, Rational(1, 3)) assert solve_ics([Eq(f(x), C1*exp(x))], [f(x)], [C1], {f(0): 1}) == {C1: 1} assert solve_ics([Eq(f(x), C1*sin(x) + C2*cos(x))], [f(x)], [C1, C2], {f(0): 1, f(pi/2): 1}) == {C1: 1, C2: 1} assert solve_ics([Eq(f(x), C1*sin(x) + C2*cos(x))], [f(x)], [C1, C2], {f(0): 1, f(x).diff(x).subs(x, 0): 1}) == {C1: 1, C2: 1} assert solve_ics([Eq(f(x), C1*sin(x) + C2*cos(x))], [f(x)], [C1, C2], {f(0): 1}) == \ {C2: 1} # Some more complicated tests Refer to PR #16098 assert set(dsolve(f(x).diff(x)*(f(x).diff(x, 2)-x), ics={f(0):0, f(x).diff(x).subs(x, 1):0})) == \ {Eq(f(x), 0), Eq(f(x), x ** 3 / 6 - x / 2)} assert set(dsolve(f(x).diff(x)*(f(x).diff(x, 2)-x), ics={f(0):0})) == \ {Eq(f(x), 0), Eq(f(x), C2*x + x**3/6)} K, r, f0 = symbols('K r f0') sol = Eq(f(x), K*f0*exp(r*x)/((-K + f0)*(f0*exp(r*x)/(-K + f0) - 1))) assert (dsolve(Eq(f(x).diff(x), r * f(x) * (1 - f(x) / K)), f(x), ics={f(0): f0})) == sol #Order dependent issues Refer to PR #16098 assert set(dsolve(f(x).diff(x)*(f(x).diff(x, 2)-x), ics={f(x).diff(x).subs(x,0):0, f(0):0})) == \ {Eq(f(x), 0), Eq(f(x), x ** 3 / 6)} assert set(dsolve(f(x).diff(x)*(f(x).diff(x, 2)-x), ics={f(0):0, f(x).diff(x).subs(x,0):0})) == \ {Eq(f(x), 0), Eq(f(x), x ** 3 / 6)} # XXX: Ought to be ValueError raises(ValueError, lambda: solve_ics([Eq(f(x), C1*sin(x) + C2*cos(x))], [f(x)], [C1, C2], {f(0): 1, f(pi): 1})) # Degenerate case. f'(0) is identically 0. raises(ValueError, lambda: solve_ics([Eq(f(x), sqrt(C1 - x**2))], [f(x)], [C1], {f(x).diff(x).subs(x, 0): 0})) EI, q, L = symbols('EI q L') # eq = Eq(EI*diff(f(x), x, 4), q) sols = [Eq(f(x), C1 + C2*x + C3*x**2 + C4*x**3 + q*x**4/(24*EI))] funcs = [f(x)] constants = [C1, C2, C3, C4] # Test both cases, Derivative (the default from f(x).diff(x).subs(x, L)), # and Subs ics1 = {f(0): 0, f(x).diff(x).subs(x, 0): 0, f(L).diff(L, 2): 0, f(L).diff(L, 3): 0} ics2 = {f(0): 0, f(x).diff(x).subs(x, 0): 0, Subs(f(x).diff(x, 2), x, L): 0, Subs(f(x).diff(x, 3), x, L): 0} solved_constants1 = solve_ics(sols, funcs, constants, ics1) solved_constants2 = solve_ics(sols, funcs, constants, ics2) assert solved_constants1 == solved_constants2 == { C1: 0, C2: 0, C3: L**2*q/(4*EI), C4: -L*q/(6*EI)} def test_ode_order(): f = Function('f') g = Function('g') x = Symbol('x') assert ode_order(3*x*exp(f(x)), f(x)) == 0 assert ode_order(x*diff(f(x), x) + 3*x*f(x) - sin(x)/x, f(x)) == 1 assert ode_order(x**2*f(x).diff(x, x) + x*diff(f(x), x) - f(x), f(x)) == 2 assert ode_order(diff(x*exp(f(x)), x, x), f(x)) == 2 assert ode_order(diff(x*diff(x*exp(f(x)), x, x), x), f(x)) == 3 assert ode_order(diff(f(x), x, x), g(x)) == 0 assert ode_order(diff(f(x), x, x)*diff(g(x), x), f(x)) == 2 assert ode_order(diff(f(x), x, x)*diff(g(x), x), g(x)) == 1 assert ode_order(diff(x*diff(x*exp(f(x)), x, x), x), g(x)) == 0 # issue 5835: ode_order has to also work for unevaluated derivatives # (ie, without using doit()). assert ode_order(Derivative(x*f(x), x), f(x)) == 1 assert ode_order(x*sin(Derivative(x*f(x)**2, x, x)), f(x)) == 2 assert ode_order(Derivative(x*Derivative(x*exp(f(x)), x, x), x), g(x)) == 0 assert ode_order(Derivative(f(x), x, x), g(x)) == 0 assert ode_order(Derivative(x*exp(f(x)), x, x), f(x)) == 2 assert ode_order(Derivative(f(x), x, x)*Derivative(g(x), x), g(x)) == 1 assert ode_order(Derivative(x*Derivative(f(x), x, x), x), f(x)) == 3 assert ode_order( x*sin(Derivative(x*Derivative(f(x), x)**2, x, x)), f(x)) == 3 # In all tests below, checkodesol has the order option set to prevent # superfluous calls to ode_order(), and the solve_for_func flag set to False # because dsolve() already tries to solve for the function, unless the # simplify=False option is set. def test_old_ode_tests(): # These are simple tests from the old ode module eq1 = Eq(f(x).diff(x), 0) eq2 = Eq(3*f(x).diff(x) - 5, 0) eq3 = Eq(3*f(x).diff(x), 5) eq4 = Eq(9*f(x).diff(x, x) + f(x), 0) eq5 = Eq(9*f(x).diff(x, x), f(x)) # Type: a(x)f'(x)+b(x)*f(x)+c(x)=0 eq6 = Eq(x**2*f(x).diff(x) + 3*x*f(x) - sin(x)/x, 0) eq7 = Eq(f(x).diff(x, x) - 3*diff(f(x), x) + 2*f(x), 0) # Type: 2nd order, constant coefficients (two real different roots) eq8 = Eq(f(x).diff(x, x) - 4*diff(f(x), x) + 4*f(x), 0) # Type: 2nd order, constant coefficients (two real equal roots) eq9 = Eq(f(x).diff(x, x) + 2*diff(f(x), x) + 3*f(x), 0) # Type: 2nd order, constant coefficients (two complex roots) eq10 = Eq(3*f(x).diff(x) - 1, 0) eq11 = Eq(x*f(x).diff(x) - 1, 0) sol1 = Eq(f(x), C1) sol2 = Eq(f(x), C1 + x*Rational(5, 3)) sol3 = Eq(f(x), C1 + x*Rational(5, 3)) sol4 = Eq(f(x), C1*sin(x/3) + C2*cos(x/3)) sol5 = Eq(f(x), C1*exp(-x/3) + C2*exp(x/3)) sol6 = Eq(f(x), (C1 - cos(x))/x**3) sol7 = Eq(f(x), (C1 + C2*exp(x))*exp(x)) sol8 = Eq(f(x), (C1 + C2*x)*exp(2*x)) sol9 = Eq(f(x), (C1*sin(x*sqrt(2)) + C2*cos(x*sqrt(2)))*exp(-x)) sol10 = Eq(f(x), C1 + x/3) sol11 = Eq(f(x), C1 + log(x)) assert dsolve(eq1) == sol1 assert dsolve(eq1.lhs) == sol1 assert dsolve(eq2) == sol2 assert dsolve(eq3) == sol3 assert dsolve(eq4) == sol4 assert dsolve(eq5) == sol5 assert dsolve(eq6) == sol6 assert dsolve(eq7) == sol7 assert dsolve(eq8) == sol8 assert dsolve(eq9) == sol9 assert dsolve(eq10) == sol10 assert dsolve(eq11) == sol11 assert checkodesol(eq1, sol1, order=1, solve_for_func=False)[0] assert checkodesol(eq2, sol2, order=1, solve_for_func=False)[0] assert checkodesol(eq3, sol3, order=1, solve_for_func=False)[0] assert checkodesol(eq4, sol4, order=2, solve_for_func=False)[0] assert checkodesol(eq5, sol5, order=2, solve_for_func=False)[0] assert checkodesol(eq6, sol6, order=1, solve_for_func=False)[0] assert checkodesol(eq7, sol7, order=2, solve_for_func=False)[0] assert checkodesol(eq8, sol8, order=2, solve_for_func=False)[0] assert checkodesol(eq9, sol9, order=2, solve_for_func=False)[0] assert checkodesol(eq10, sol10, order=1, solve_for_func=False)[0] assert checkodesol(eq11, sol11, order=1, solve_for_func=False)[0] def test_1st_linear(): # Type: first order linear form f'(x)+p(x)f(x)=q(x) eq = Eq(f(x).diff(x) + x*f(x), x**2) sol = Eq(f(x), (C1 + x*exp(x**2/2) - sqrt(2)*sqrt(pi)*erfi(sqrt(2)*x/2)/2)*exp(-x**2/2)) assert dsolve(eq, hint='1st_linear') == sol assert checkodesol(eq, sol, order=1, solve_for_func=False)[0] def test_Bernoulli(): # Type: Bernoulli, f'(x) + p(x)*f(x) == q(x)*f(x)**n eq = Eq(x*f(x).diff(x) + f(x) - f(x)**2, 0) sol = dsolve(eq, f(x), hint='Bernoulli') assert sol == Eq(f(x), 1/(x*(C1 + 1/x))) assert checkodesol(eq, sol, order=1, solve_for_func=False)[0] def test_Riccati_special_minus2(): # Type: Riccati special alpha = -2, a*dy/dx + b*y**2 + c*y/x +d/x**2 eq = 2*f(x).diff(x) + f(x)**2 - f(x)/x + 3*x**(-2) sol = dsolve(eq, f(x), hint='Riccati_special_minus2') assert checkodesol(eq, sol, order=1, solve_for_func=False)[0] @slow def test_1st_exact1(): # Type: Exact differential equation, p(x,f) + q(x,f)*f' == 0, # where dp/df == dq/dx eq1 = sin(x)*cos(f(x)) + cos(x)*sin(f(x))*f(x).diff(x) eq2 = (2*x*f(x) + 1)/f(x) + (f(x) - x)/f(x)**2*f(x).diff(x) eq3 = 2*x + f(x)*cos(x) + (2*f(x) + sin(x) - sin(f(x)))*f(x).diff(x) eq4 = cos(f(x)) - (x*sin(f(x)) - f(x)**2)*f(x).diff(x) eq5 = 2*x*f(x) + (x**2 + f(x)**2)*f(x).diff(x) sol1 = [Eq(f(x), -acos(C1/cos(x)) + 2*pi), Eq(f(x), acos(C1/cos(x)))] sol2 = Eq(f(x), exp(C1 - x**2 + LambertW(-x*exp(-C1 + x**2)))) sol2b = Eq(log(f(x)) + x/f(x) + x**2, C1) sol3 = Eq(f(x)*sin(x) + cos(f(x)) + x**2 + f(x)**2, C1) sol4 = Eq(x*cos(f(x)) + f(x)**3/3, C1) sol5 = Eq(x**2*f(x) + f(x)**3/3, C1) assert dsolve(eq1, f(x), hint='1st_exact') == sol1 assert dsolve(eq2, f(x), hint='1st_exact') == sol2 assert dsolve(eq3, f(x), hint='1st_exact') == sol3 assert dsolve(eq4, hint='1st_exact') == sol4 assert dsolve(eq5, hint='1st_exact', simplify=False) == sol5 assert checkodesol(eq1, sol1, order=1, solve_for_func=False)[0] # issue 5080 blocks the testing of this solution # FIXME: assert checkodesol(eq2, sol2, order=1, solve_for_func=False)[0] assert checkodesol(eq2, sol2b, order=1, solve_for_func=False)[0] assert checkodesol(eq3, sol3, order=1, solve_for_func=False)[0] assert checkodesol(eq4, sol4, order=1, solve_for_func=False)[0] assert checkodesol(eq5, sol5, order=1, solve_for_func=False)[0] @slow @XFAIL def test_1st_exact2(): """ This is an exact equation that fails under the exact engine. It is caught by first order homogeneous albeit with a much contorted solution. The exact engine fails because of a poorly simplified integral of q(0,y)dy, where q is the function multiplying f'. The solutions should be Eq(sqrt(x**2+f(x)**2)**3+y**3, C1). The equation below is equivalent, but it is so complex that checkodesol fails, and takes a long time to do so. """ if ON_TRAVIS: skip("Too slow for travis.") eq = (x*sqrt(x**2 + f(x)**2) - (x**2*f(x)/(f(x) - sqrt(x**2 + f(x)**2)))*f(x).diff(x)) sol = dsolve(eq) assert sol == Eq(log(x), C1 - 9*sqrt(1 + f(x)**2/x**2)*asinh(f(x)/x)/(-27*f(x)/x + 27*sqrt(1 + f(x)**2/x**2)) - 9*sqrt(1 + f(x)**2/x**2)* log(1 - sqrt(1 + f(x)**2/x**2)*f(x)/x + 2*f(x)**2/x**2)/ (-27*f(x)/x + 27*sqrt(1 + f(x)**2/x**2)) + 9*asinh(f(x)/x)*f(x)/(x*(-27*f(x)/x + 27*sqrt(1 + f(x)**2/x**2))) + 9*f(x)*log(1 - sqrt(1 + f(x)**2/x**2)*f(x)/x + 2*f(x)**2/x**2)/ (x*(-27*f(x)/x + 27*sqrt(1 + f(x)**2/x**2)))) assert checkodesol(eq, sol, order=1, solve_for_func=False)[0] def test_separable1(): # test_separable1-5 are from Ordinary Differential Equations, Tenenbaum and # Pollard, pg. 55 eq1 = f(x).diff(x) - f(x) eq2 = x*f(x).diff(x) - f(x) eq3 = f(x).diff(x) + sin(x) eq4 = f(x)**2 + 1 - (x**2 + 1)*f(x).diff(x) eq5 = f(x).diff(x)/tan(x) - f(x) - 2 eq6 = f(x).diff(x) * (1 - sin(f(x))) - 1 sol1 = Eq(f(x), C1*exp(x)) sol2 = Eq(f(x), C1*x) sol3 = Eq(f(x), C1 + cos(x)) sol4 = Eq(f(x), tan(C1 + atan(x))) sol5 = Eq(f(x), C1/cos(x) - 2) sol6 = Eq(-x + f(x) + cos(f(x)), C1) assert dsolve(eq1, hint='separable') == sol1 assert dsolve(eq2, hint='separable') == sol2 assert dsolve(eq3, hint='separable') == sol3 assert dsolve(eq4, hint='separable') == sol4 assert dsolve(eq5, hint='separable') == sol5 assert dsolve(eq6, hint='separable') == sol6 assert checkodesol(eq1, sol1, order=1, solve_for_func=False)[0] assert checkodesol(eq2, sol2, order=1, solve_for_func=False)[0] assert checkodesol(eq3, sol3, order=1, solve_for_func=False)[0] assert checkodesol(eq4, sol4, order=1, solve_for_func=False)[0] assert checkodesol(eq5, sol5, order=1, solve_for_func=False)[0] assert checkodesol(eq6, sol6, order=1, solve_for_func=False)[0] @slow def test_separable2(): a = Symbol('a') eq6 = f(x)*x**2*f(x).diff(x) - f(x)**3 - 2*x**2*f(x).diff(x) eq7 = f(x)**2 - 1 - (2*f(x) + x*f(x))*f(x).diff(x) eq8 = x*log(x)*f(x).diff(x) + sqrt(1 + f(x)**2) eq9 = exp(x + 1)*tan(f(x)) + cos(f(x))*f(x).diff(x) eq10 = (x*cos(f(x)) + x**2*sin(f(x))*f(x).diff(x) - a**2*sin(f(x))*f(x).diff(x)) sol6 = Eq(Integral((u - 2)/u**3, (u, f(x))), C1 + Integral(x**(-2), x)) sol7 = Eq(-log(-1 + f(x)**2)/2, C1 - log(2 + x)) sol8 = Eq(asinh(f(x)), C1 - log(log(x))) # integrate cannot handle the integral on the lhs (cos/tan) sol9 = Eq(Integral(cos(u)/tan(u), (u, f(x))), C1 + Integral(-exp(1)*exp(x), x)) sol10 = Eq(-log(cos(f(x))), C1 - log(- a**2 + x**2)/2) assert dsolve(eq6, hint='separable_Integral').dummy_eq(sol6) assert dsolve(eq7, hint='separable', simplify=False) == sol7 assert dsolve(eq8, hint='separable', simplify=False) == sol8 assert dsolve(eq9, hint='separable_Integral').dummy_eq(sol9) assert dsolve(eq10, hint='separable', simplify=False) == sol10 assert checkodesol(eq6, sol6, order=1, solve_for_func=False)[0] assert checkodesol(eq7, sol7, order=1, solve_for_func=False)[0] assert checkodesol(eq8, sol8, order=1, solve_for_func=False)[0] assert checkodesol(eq9, sol9, order=1, solve_for_func=False)[0] assert checkodesol(eq10, sol10, order=1, solve_for_func=False)[0] def test_separable3(): eq11 = f(x).diff(x) - f(x)*tan(x) eq12 = (x - 1)*cos(f(x))*f(x).diff(x) - 2*x*sin(f(x)) eq13 = f(x).diff(x) - f(x)*log(f(x))/tan(x) sol11 = Eq(f(x), C1/cos(x)) sol12 = Eq(log(sin(f(x))), C1 + 2*x + 2*log(x - 1)) sol13 = Eq(log(log(f(x))), C1 + log(sin(x))) assert dsolve(eq11, hint='separable') == sol11 assert dsolve(eq12, hint='separable', simplify=False) == sol12 assert dsolve(eq13, hint='separable', simplify=False) == sol13 assert checkodesol(eq11, sol11, order=1, solve_for_func=False)[0] assert checkodesol(eq12, sol12, order=1, solve_for_func=False)[0] assert checkodesol(eq13, sol13, order=1, solve_for_func=False)[0] def test_separable4(): # This has a slow integral (1/((1 + y**2)*atan(y))), so we isolate it. eq14 = x*f(x).diff(x) + (1 + f(x)**2)*atan(f(x)) sol14 = Eq(log(atan(f(x))), C1 - log(x)) assert dsolve(eq14, hint='separable', simplify=False) == sol14 assert checkodesol(eq14, sol14, order=1, solve_for_func=False)[0] def test_separable5(): eq15 = f(x).diff(x) + x*(f(x) + 1) eq16 = exp(f(x)**2)*(x**2 + 2*x + 1) + (x*f(x) + f(x))*f(x).diff(x) eq17 = f(x).diff(x) + f(x) eq18 = sin(x)*cos(2*f(x)) + cos(x)*sin(2*f(x))*f(x).diff(x) eq19 = (1 - x)*f(x).diff(x) - x*(f(x) + 1) eq20 = f(x)*diff(f(x), x) + x - 3*x*f(x)**2 eq21 = f(x).diff(x) - exp(x + f(x)) sol15 = Eq(f(x), -1 + C1*exp(-x**2/2)) sol16 = Eq(-exp(-f(x)**2)/2, C1 - x - x**2/2) sol17 = Eq(f(x), C1*exp(-x)) sol18 = Eq(-log(cos(2*f(x)))/2, C1 + log(cos(x))) sol19 = Eq(f(x), (C1*exp(-x) - x + 1)/(x - 1)) sol20 = Eq(log(-1 + 3*f(x)**2)/6, C1 + x**2/2) sol21 = Eq(-exp(-f(x)), C1 + exp(x)) assert dsolve(eq15, hint='separable') == sol15 assert dsolve(eq16, hint='separable', simplify=False) == sol16 assert dsolve(eq17, hint='separable') == sol17 assert dsolve(eq18, hint='separable', simplify=False) == sol18 assert dsolve(eq19, hint='separable') == sol19 assert dsolve(eq20, hint='separable', simplify=False) == sol20 assert dsolve(eq21, hint='separable', simplify=False) == sol21 assert checkodesol(eq15, sol15, order=1, solve_for_func=False)[0] assert checkodesol(eq16, sol16, order=1, solve_for_func=False)[0] assert checkodesol(eq17, sol17, order=1, solve_for_func=False)[0] assert checkodesol(eq18, sol18, order=1, solve_for_func=False)[0] assert checkodesol(eq19, sol19, order=1, solve_for_func=False)[0] assert checkodesol(eq20, sol20, order=1, solve_for_func=False)[0] assert checkodesol(eq21, sol21, order=1, solve_for_func=False)[0] def test_separable_1_5_checkodesol(): eq12 = (x - 1)*cos(f(x))*f(x).diff(x) - 2*x*sin(f(x)) sol12 = Eq(-log(1 - cos(f(x))**2)/2, C1 - 2*x - 2*log(1 - x)) assert checkodesol(eq12, sol12, order=1, solve_for_func=False)[0] def test_homogeneous_order(): assert homogeneous_order(exp(y/x) + tan(y/x), x, y) == 0 assert homogeneous_order(x**2 + sin(x)*cos(y), x, y) is None assert homogeneous_order(x - y - x*sin(y/x), x, y) == 1 assert homogeneous_order((x*y + sqrt(x**4 + y**4) + x**2*(log(x) - log(y)))/ (pi*x**Rational(2, 3)*sqrt(y)**3), x, y) == Rational(-1, 6) assert homogeneous_order(y/x*cos(y/x) - x/y*sin(y/x) + cos(y/x), x, y) == 0 assert homogeneous_order(f(x), x, f(x)) == 1 assert homogeneous_order(f(x)**2, x, f(x)) == 2 assert homogeneous_order(x*y*z, x, y) == 2 assert homogeneous_order(x*y*z, x, y, z) == 3 assert homogeneous_order(x**2*f(x)/sqrt(x**2 + f(x)**2), f(x)) is None assert homogeneous_order(f(x, y)**2, x, f(x, y), y) == 2 assert homogeneous_order(f(x, y)**2, x, f(x), y) is None assert homogeneous_order(f(x, y)**2, x, f(x, y)) is None assert homogeneous_order(f(y, x)**2, x, y, f(x, y)) is None assert homogeneous_order(f(y), f(x), x) is None assert homogeneous_order(-f(x)/x + 1/sin(f(x)/ x), f(x), x) == 0 assert homogeneous_order(log(1/y) + log(x**2), x, y) is None assert homogeneous_order(log(1/y) + log(x), x, y) == 0 assert homogeneous_order(log(x/y), x, y) == 0 assert homogeneous_order(2*log(1/y) + 2*log(x), x, y) == 0 a = Symbol('a') assert homogeneous_order(a*log(1/y) + a*log(x), x, y) == 0 assert homogeneous_order(f(x).diff(x), x, y) is None assert homogeneous_order(-f(x).diff(x) + x, x, y) is None assert homogeneous_order(O(x), x, y) is None assert homogeneous_order(x + O(x**2), x, y) is None assert homogeneous_order(x**pi, x) == pi assert homogeneous_order(x**x, x) is None raises(ValueError, lambda: homogeneous_order(x*y)) @slow def test_1st_homogeneous_coeff_ode(): # Type: First order homogeneous, y'=f(y/x) eq1 = f(x)/x*cos(f(x)/x) - (x/f(x)*sin(f(x)/x) + cos(f(x)/x))*f(x).diff(x) eq2 = x*f(x).diff(x) - f(x) - x*sin(f(x)/x) eq3 = f(x) + (x*log(f(x)/x) - 2*x)*diff(f(x), x) eq4 = 2*f(x)*exp(x/f(x)) + f(x)*f(x).diff(x) - 2*x*exp(x/f(x))*f(x).diff(x) eq5 = 2*x**2*f(x) + f(x)**3 + (x*f(x)**2 - 2*x**3)*f(x).diff(x) eq6 = x*exp(f(x)/x) - f(x)*sin(f(x)/x) + x*sin(f(x)/x)*f(x).diff(x) eq7 = (x + sqrt(f(x)**2 - x*f(x)))*f(x).diff(x) - f(x) eq8 = x + f(x) - (x - f(x))*f(x).diff(x) sol1 = Eq(log(x), C1 - log(f(x)*sin(f(x)/x)/x)) sol2 = Eq(log(x), log(C1) + log(cos(f(x)/x) - 1)/2 - log(cos(f(x)/x) + 1)/2) sol3 = Eq(f(x), -exp(C1)*LambertW(-x*exp(-C1 + 1))) sol4 = Eq(log(f(x)), C1 - 2*exp(x/f(x))) sol5 = Eq(f(x), exp(2*C1 + LambertW(-2*x**4*exp(-4*C1))/2)/x) sol6 = Eq(log(x), C1 + exp(-f(x)/x)*sin(f(x)/x)/2 + exp(-f(x)/x)*cos(f(x)/x)/2) sol7 = Eq(log(f(x)), C1 - 2*sqrt(-x/f(x) + 1)) sol8 = Eq(log(x), C1 - log(sqrt(1 + f(x)**2/x**2)) + atan(f(x)/x)) # indep_div_dep actually has a simpler solution for eq2, # but it runs too slow assert dsolve(eq1, hint='1st_homogeneous_coeff_subs_dep_div_indep') == sol1 assert dsolve(eq2, hint='1st_homogeneous_coeff_subs_dep_div_indep', simplify=False) == sol2 assert dsolve(eq3, hint='1st_homogeneous_coeff_best') == sol3 assert dsolve(eq4, hint='1st_homogeneous_coeff_best') == sol4 assert dsolve(eq5, hint='1st_homogeneous_coeff_best') == sol5 assert dsolve(eq6, hint='1st_homogeneous_coeff_subs_dep_div_indep') == sol6 assert dsolve(eq7, hint='1st_homogeneous_coeff_best') == sol7 assert dsolve(eq8, hint='1st_homogeneous_coeff_best') == sol8 # FIXME: sol3 and sol5 don't work with checkodesol (because of LambertW?) # previous code was testing with these other solutions: sol3b = Eq(-f(x)/(1 + log(x/f(x))), C1) sol5b = Eq(log(C1*x*sqrt(1/x)*sqrt(f(x))) + x**2/(2*f(x)**2), 0) assert checkodesol(eq1, sol1, order=1, solve_for_func=False)[0] assert checkodesol(eq2, sol2, order=1, solve_for_func=False)[0] assert checkodesol(eq3, sol3b, order=1, solve_for_func=False)[0] assert checkodesol(eq4, sol4, order=1, solve_for_func=False)[0] assert checkodesol(eq5, sol5b, order=1, solve_for_func=False)[0] assert checkodesol(eq6, sol6, order=1, solve_for_func=False)[0] assert checkodesol(eq8, sol8, order=1, solve_for_func=False)[0] def test_1st_homogeneous_coeff_ode_check2(): eq2 = x*f(x).diff(x) - f(x) - x*sin(f(x)/x) sol2 = Eq(x/tan(f(x)/(2*x)), C1) assert checkodesol(eq2, sol2, order=1, solve_for_func=False)[0] @XFAIL def test_1st_homogeneous_coeff_ode_check3(): skip('This is a known issue.') # checker cannot determine that the following expression is zero: # (False, # x*(log(exp(-LambertW(C1*x))) + # LambertW(C1*x))*exp(-LambertW(C1*x) + 1)) # This is blocked by issue 5080. eq3 = f(x) + (x*log(f(x)/x) - 2*x)*diff(f(x), x) sol3a = Eq(f(x), x*exp(1 - LambertW(C1*x))) assert checkodesol(eq3, sol3a, solve_for_func=True)[0] # Checker can't verify this form either # (False, # C1*(log(C1*LambertW(C2*x)/x) + LambertW(C2*x) - 1)*LambertW(C2*x)) # It is because a = W(a)*exp(W(a)), so log(a) == log(W(a)) + W(a) and C2 = # -E/C1 (which can be verified by solving with simplify=False). sol3b = Eq(f(x), C1*LambertW(C2*x)) assert checkodesol(eq3, sol3b, solve_for_func=True)[0] def test_1st_homogeneous_coeff_ode_check7(): eq7 = (x + sqrt(f(x)**2 - x*f(x)))*f(x).diff(x) - f(x) sol7 = Eq(log(C1*f(x)) + 2*sqrt(1 - x/f(x)), 0) assert checkodesol(eq7, sol7, order=1, solve_for_func=False)[0] def test_1st_homogeneous_coeff_ode2(): eq1 = f(x).diff(x) - f(x)/x + 1/sin(f(x)/x) eq2 = x**2 + f(x)**2 - 2*x*f(x)*f(x).diff(x) eq3 = x*exp(f(x)/x) + f(x) - x*f(x).diff(x) sol1 = [Eq(f(x), x*(-acos(C1 + log(x)) + 2*pi)), Eq(f(x), x*acos(C1 + log(x)))] sol2 = Eq(log(f(x)), log(C1) + log(x/f(x)) - log(x**2/f(x)**2 - 1)) sol3 = Eq(f(x), log((1/(C1 - log(x)))**x)) # specific hints are applied for speed reasons assert dsolve(eq1, hint='1st_homogeneous_coeff_subs_dep_div_indep') == sol1 assert dsolve(eq2, hint='1st_homogeneous_coeff_best', simplify=False) == sol2 assert dsolve(eq3, hint='1st_homogeneous_coeff_subs_dep_div_indep') == sol3 # FIXME: sol3 doesn't work with checkodesol (because of **x?) # previous code was testing with this other solution: sol3b = Eq(f(x), log(log(C1/x)**(-x))) assert checkodesol(eq1, sol1, order=1, solve_for_func=False)[0] assert checkodesol(eq2, sol2, order=1, solve_for_func=False)[0] assert checkodesol(eq3, sol3b, order=1, solve_for_func=False)[0] def test_1st_homogeneous_coeff_ode_check9(): _u2 = Dummy('u2') __a = Dummy('a') eq9 = f(x)**2 + (x*sqrt(f(x)**2 - x**2) - x*f(x))*f(x).diff(x) sol9 = Eq(-Integral(-1/(-(1 - sqrt(1 - _u2**2))*_u2 + _u2), (_u2, __a, x/f(x))) + log(C1*f(x)), 0) assert checkodesol(eq9, sol9, order=1, solve_for_func=False)[0] def test_1st_homogeneous_coeff_ode3(): # The standard integration engine cannot handle one of the integrals # involved (see issue 4551). meijerg code comes up with an answer, but in # unconventional form. # checkodesol fails for this equation, so its test is in # test_1st_homogeneous_coeff_ode_check9 above. It has to compare string # expressions because u2 is a dummy variable. eq = f(x)**2 + (x*sqrt(f(x)**2 - x**2) - x*f(x))*f(x).diff(x) sol = Eq(log(f(x)), C1 + Piecewise( (acosh(f(x)/x), abs(f(x)**2)/x**2 > 1), (-I*asin(f(x)/x), True))) assert dsolve(eq, hint='1st_homogeneous_coeff_subs_indep_div_dep') == sol def test_1st_homogeneous_coeff_corner_case(): eq1 = f(x).diff(x) - f(x)/x c1 = classify_ode(eq1, f(x)) eq2 = x*f(x).diff(x) - f(x) c2 = classify_ode(eq2, f(x)) sdi = "1st_homogeneous_coeff_subs_dep_div_indep" sid = "1st_homogeneous_coeff_subs_indep_div_dep" assert sid not in c1 and sdi not in c1 assert sid not in c2 and sdi not in c2 @slow def test_nth_linear_constant_coeff_homogeneous(): # From Exercise 20, in Ordinary Differential Equations, # Tenenbaum and Pollard, pg. 220 a = Symbol('a', positive=True) k = Symbol('k', real=True) eq1 = f(x).diff(x, 2) + 2*f(x).diff(x) eq2 = f(x).diff(x, 2) - 3*f(x).diff(x) + 2*f(x) eq3 = f(x).diff(x, 2) - f(x) eq4 = f(x).diff(x, 3) + f(x).diff(x, 2) - 6*f(x).diff(x) eq5 = 6*f(x).diff(x, 2) - 11*f(x).diff(x) + 4*f(x) eq6 = Eq(f(x).diff(x, 2) + 2*f(x).diff(x) - f(x), 0) eq7 = diff(f(x), x, 3) + diff(f(x), x, 2) - 10*diff(f(x), x) - 6*f(x) eq8 = f(x).diff(x, 4) - f(x).diff(x, 3) - 4*f(x).diff(x, 2) + \ 4*f(x).diff(x) eq9 = f(x).diff(x, 4) + 4*f(x).diff(x, 3) + f(x).diff(x, 2) - \ 4*f(x).diff(x) - 2*f(x) eq10 = f(x).diff(x, 4) - a**2*f(x) eq11 = f(x).diff(x, 2) - 2*k*f(x).diff(x) - 2*f(x) eq12 = f(x).diff(x, 2) + 4*k*f(x).diff(x) - 12*k**2*f(x) eq13 = f(x).diff(x, 4) eq14 = f(x).diff(x, 2) + 4*f(x).diff(x) + 4*f(x) eq15 = 3*f(x).diff(x, 3) + 5*f(x).diff(x, 2) + f(x).diff(x) - f(x) eq16 = f(x).diff(x, 3) - 6*f(x).diff(x, 2) + 12*f(x).diff(x) - 8*f(x) eq17 = f(x).diff(x, 2) - 2*a*f(x).diff(x) + a**2*f(x) eq18 = f(x).diff(x, 4) + 3*f(x).diff(x, 3) eq19 = f(x).diff(x, 4) - 2*f(x).diff(x, 2) eq20 = f(x).diff(x, 4) + 2*f(x).diff(x, 3) - 11*f(x).diff(x, 2) - \ 12*f(x).diff(x) + 36*f(x) eq21 = 36*f(x).diff(x, 4) - 37*f(x).diff(x, 2) + 4*f(x).diff(x) + 5*f(x) eq22 = f(x).diff(x, 4) - 8*f(x).diff(x, 2) + 16*f(x) eq23 = f(x).diff(x, 2) - 2*f(x).diff(x) + 5*f(x) eq24 = f(x).diff(x, 2) - f(x).diff(x) + f(x) eq25 = f(x).diff(x, 4) + 5*f(x).diff(x, 2) + 6*f(x) eq26 = f(x).diff(x, 2) - 4*f(x).diff(x) + 20*f(x) eq27 = f(x).diff(x, 4) + 4*f(x).diff(x, 2) + 4*f(x) eq28 = f(x).diff(x, 3) + 8*f(x) eq29 = f(x).diff(x, 4) + 4*f(x).diff(x, 2) eq30 = f(x).diff(x, 5) + 2*f(x).diff(x, 3) + f(x).diff(x) eq31 = f(x).diff(x, 4) + f(x).diff(x, 2) + f(x) eq32 = f(x).diff(x, 4) + 4*f(x).diff(x, 2) + f(x) sol1 = Eq(f(x), C1 + C2*exp(-2*x)) sol2 = Eq(f(x), (C1 + C2*exp(x))*exp(x)) sol3 = Eq(f(x), C1*exp(x) + C2*exp(-x)) sol4 = Eq(f(x), C1 + C2*exp(-3*x) + C3*exp(2*x)) sol5 = Eq(f(x), C1*exp(x/2) + C2*exp(x*Rational(4, 3))) sol6 = Eq(f(x), C1*exp(x*(-1 + sqrt(2))) + C2*exp(x*(-sqrt(2) - 1))) sol7 = Eq(f(x), C1*exp(3*x) + C2*exp(x*(-2 - sqrt(2))) + C3*exp(x*(-2 + sqrt(2)))) sol8 = Eq(f(x), C1 + C2*exp(x) + C3*exp(-2*x) + C4*exp(2*x)) sol9 = Eq(f(x), C1*exp(x) + C2*exp(-x) + C3*exp(x*(-2 + sqrt(2))) + C4*exp(x*(-2 - sqrt(2)))) sol10 = Eq(f(x), C1*sin(x*sqrt(a)) + C2*cos(x*sqrt(a)) + C3*exp(x*sqrt(a)) + C4*exp(-x*sqrt(a))) sol11 = Eq(f(x), C1*exp(x*(k - sqrt(k**2 + 2))) + C2*exp(x*(k + sqrt(k**2 + 2)))) sol12 = Eq(f(x), C1*exp(-6*k*x) + C2*exp(2*k*x)) sol13 = Eq(f(x), C1 + C2*x + C3*x**2 + C4*x**3) sol14 = Eq(f(x), (C1 + C2*x)*exp(-2*x)) sol15 = Eq(f(x), (C1 + C2*x)*exp(-x) + C3*exp(x/3)) sol16 = Eq(f(x), (C1 + C2*x + C3*x**2)*exp(2*x)) sol17 = Eq(f(x), (C1 + C2*x)*exp(a*x)) sol18 = Eq(f(x), C1 + C2*x + C3*x**2 + C4*exp(-3*x)) sol19 = Eq(f(x), C1 + C2*x + C3*exp(x*sqrt(2)) + C4*exp(-x*sqrt(2))) sol20 = Eq(f(x), (C1 + C2*x)*exp(-3*x) + (C3 + C4*x)*exp(2*x)) sol21 = Eq(f(x), C1*exp(x/2) + C2*exp(-x) + C3*exp(-x/3) + C4*exp(x*Rational(5, 6))) sol22 = Eq(f(x), (C1 + C2*x)*exp(-2*x) + (C3 + C4*x)*exp(2*x)) sol23 = Eq(f(x), (C1*sin(2*x) + C2*cos(2*x))*exp(x)) sol24 = Eq(f(x), (C1*sin(x*sqrt(3)/2) + C2*cos(x*sqrt(3)/2))*exp(x/2)) sol25 = Eq(f(x), C1*cos(x*sqrt(3)) + C2*sin(x*sqrt(3)) + C3*sin(x*sqrt(2)) + C4*cos(x*sqrt(2))) sol26 = Eq(f(x), (C1*sin(4*x) + C2*cos(4*x))*exp(2*x)) sol27 = Eq(f(x), (C1 + C2*x)*sin(x*sqrt(2)) + (C3 + C4*x)*cos(x*sqrt(2))) sol28 = Eq(f(x), (C1*sin(x*sqrt(3)) + C2*cos(x*sqrt(3)))*exp(x) + C3*exp(-2*x)) sol29 = Eq(f(x), C1 + C2*sin(2*x) + C3*cos(2*x) + C4*x) sol30 = Eq(f(x), C1 + (C2 + C3*x)*sin(x) + (C4 + C5*x)*cos(x)) sol31 = Eq(f(x), (C1*sin(sqrt(3)*x/2) + C2*cos(sqrt(3)*x/2))/sqrt(exp(x)) + (C3*sin(sqrt(3)*x/2) + C4*cos(sqrt(3)*x/2))*sqrt(exp(x))) sol32 = Eq(f(x), C1*sin(x*sqrt(-sqrt(3) + 2)) + C2*sin(x*sqrt(sqrt(3) + 2)) + C3*cos(x*sqrt(-sqrt(3) + 2)) + C4*cos(x*sqrt(sqrt(3) + 2))) sol1s = constant_renumber(sol1) sol2s = constant_renumber(sol2) sol3s = constant_renumber(sol3) sol4s = constant_renumber(sol4) sol5s = constant_renumber(sol5) sol6s = constant_renumber(sol6) sol7s = constant_renumber(sol7) sol8s = constant_renumber(sol8) sol9s = constant_renumber(sol9) sol10s = constant_renumber(sol10) sol11s = constant_renumber(sol11) sol12s = constant_renumber(sol12) sol13s = constant_renumber(sol13) sol14s = constant_renumber(sol14) sol15s = constant_renumber(sol15) sol16s = constant_renumber(sol16) sol17s = constant_renumber(sol17) sol18s = constant_renumber(sol18) sol19s = constant_renumber(sol19) sol20s = constant_renumber(sol20) sol21s = constant_renumber(sol21) sol22s = constant_renumber(sol22) sol23s = constant_renumber(sol23) sol24s = constant_renumber(sol24) sol25s = constant_renumber(sol25) sol26s = constant_renumber(sol26) sol27s = constant_renumber(sol27) sol28s = constant_renumber(sol28) sol29s = constant_renumber(sol29) sol30s = constant_renumber(sol30) assert dsolve(eq1) in (sol1, sol1s) assert dsolve(eq2) in (sol2, sol2s) assert dsolve(eq3) in (sol3, sol3s) assert dsolve(eq4) in (sol4, sol4s) assert dsolve(eq5) in (sol5, sol5s) assert dsolve(eq6) in (sol6, sol6s) assert dsolve(eq7) in (sol7, sol7s) assert dsolve(eq8) in (sol8, sol8s) assert dsolve(eq9) in (sol9, sol9s) assert dsolve(eq10) in (sol10, sol10s) assert dsolve(eq11) in (sol11, sol11s) assert dsolve(eq12) in (sol12, sol12s) assert dsolve(eq13) in (sol13, sol13s) assert dsolve(eq14) in (sol14, sol14s) assert dsolve(eq15) in (sol15, sol15s) assert dsolve(eq16) in (sol16, sol16s) assert dsolve(eq17) in (sol17, sol17s) assert dsolve(eq18) in (sol18, sol18s) assert dsolve(eq19) in (sol19, sol19s) assert dsolve(eq20) in (sol20, sol20s) assert dsolve(eq21) in (sol21, sol21s) assert dsolve(eq22) in (sol22, sol22s) assert dsolve(eq23) in (sol23, sol23s) assert dsolve(eq24) in (sol24, sol24s) assert dsolve(eq25) in (sol25, sol25s) assert dsolve(eq26) in (sol26, sol26s) assert dsolve(eq27) in (sol27, sol27s) assert dsolve(eq28) in (sol28, sol28s) assert dsolve(eq29) in (sol29, sol29s) assert dsolve(eq30) in (sol30, sol30s) assert dsolve(eq31) in (sol31,) assert dsolve(eq32) in (sol32,) assert checkodesol(eq1, sol1, order=2, solve_for_func=False)[0] assert checkodesol(eq2, sol2, order=2, solve_for_func=False)[0] assert checkodesol(eq3, sol3, order=2, solve_for_func=False)[0] assert checkodesol(eq4, sol4, order=3, solve_for_func=False)[0] assert checkodesol(eq5, sol5, order=2, solve_for_func=False)[0] assert checkodesol(eq6, sol6, order=2, solve_for_func=False)[0] assert checkodesol(eq7, sol7, order=3, solve_for_func=False)[0] assert checkodesol(eq8, sol8, order=4, solve_for_func=False)[0] assert checkodesol(eq9, sol9, order=4, solve_for_func=False)[0] assert checkodesol(eq10, sol10, order=4, solve_for_func=False)[0] assert checkodesol(eq11, sol11, order=2, solve_for_func=False)[0] assert checkodesol(eq12, sol12, order=2, solve_for_func=False)[0] assert checkodesol(eq13, sol13, order=4, solve_for_func=False)[0] assert checkodesol(eq14, sol14, order=2, solve_for_func=False)[0] assert checkodesol(eq15, sol15, order=3, solve_for_func=False)[0] assert checkodesol(eq16, sol16, order=3, solve_for_func=False)[0] assert checkodesol(eq17, sol17, order=2, solve_for_func=False)[0] assert checkodesol(eq18, sol18, order=4, solve_for_func=False)[0] assert checkodesol(eq19, sol19, order=4, solve_for_func=False)[0] assert checkodesol(eq20, sol20, order=4, solve_for_func=False)[0] assert checkodesol(eq21, sol21, order=4, solve_for_func=False)[0] assert checkodesol(eq22, sol22, order=4, solve_for_func=False)[0] assert checkodesol(eq23, sol23, order=2, solve_for_func=False)[0] assert checkodesol(eq24, sol24, order=2, solve_for_func=False)[0] assert checkodesol(eq25, sol25, order=4, solve_for_func=False)[0] assert checkodesol(eq26, sol26, order=2, solve_for_func=False)[0] assert checkodesol(eq27, sol27, order=4, solve_for_func=False)[0] assert checkodesol(eq28, sol28, order=3, solve_for_func=False)[0] assert checkodesol(eq29, sol29, order=4, solve_for_func=False)[0] assert checkodesol(eq30, sol30, order=5, solve_for_func=False)[0] assert checkodesol(eq31, sol31, order=4, solve_for_func=False)[0] assert checkodesol(eq32, sol32, order=4, solve_for_func=False)[0] # Issue #15237 eqn = Derivative(x*f(x), x, x, x) hint = 'nth_linear_constant_coeff_homogeneous' raises(ValueError, lambda: dsolve(eqn, f(x), hint, prep=True)) raises(ValueError, lambda: dsolve(eqn, f(x), hint, prep=False)) def test_nth_linear_constant_coeff_homogeneous_rootof(): # One real root, two complex conjugate pairs eq = f(x).diff(x, 5) + 11*f(x).diff(x) - 2*f(x) r1, r2, r3, r4, r5 = [rootof(x**5 + 11*x - 2, n) for n in range(5)] sol = Eq(f(x), C5*exp(r1*x) + exp(re(r2)*x) * (C1*sin(im(r2)*x) + C2*cos(im(r2)*x)) + exp(re(r4)*x) * (C3*sin(im(r4)*x) + C4*cos(im(r4)*x)) ) assert dsolve(eq) == sol # FIXME: assert checkodesol(eq, sol) == (True, [0]) # Hangs... # Three real roots, one complex conjugate pair eq = f(x).diff(x,5) - 3*f(x).diff(x) + f(x) r1, r2, r3, r4, r5 = [rootof(x**5 - 3*x + 1, n) for n in range(5)] sol = Eq(f(x), C3*exp(r1*x) + C4*exp(r2*x) + C5*exp(r3*x) + exp(re(r4)*x) * (C1*sin(im(r4)*x) + C2*cos(im(r4)*x)) ) assert dsolve(eq) == sol # FIXME: assert checkodesol(eq, sol) == (True, [0]) # Hangs... # Five distinct real roots eq = f(x).diff(x,5) - 100*f(x).diff(x,3) + 1000*f(x).diff(x) + f(x) r1, r2, r3, r4, r5 = [rootof(x**5 - 100*x**3 + 1000*x + 1, n) for n in range(5)] sol = Eq(f(x), C1*exp(r1*x) + C2*exp(r2*x) + C3*exp(r3*x) + C4*exp(r4*x) + C5*exp(r5*x)) assert dsolve(eq) == sol # FIXME: assert checkodesol(eq, sol) == (True, [0]) # Hangs... # Rational root and unsolvable quintic eq = f(x).diff(x, 6) - 6*f(x).diff(x, 5) + 5*f(x).diff(x, 4) + 10*f(x).diff(x) - 50 * f(x) r2, r3, r4, r5, r6 = [rootof(x**5 - x**4 + 10, n) for n in range(5)] sol = Eq(f(x), C5*exp(5*x) + C6*exp(x*r2) + exp(re(r3)*x) * (C1*sin(im(r3)*x) + C2*cos(im(r3)*x)) + exp(re(r5)*x) * (C3*sin(im(r5)*x) + C4*cos(im(r5)*x)) ) assert dsolve(eq) == sol # FIXME: assert checkodesol(eq, sol) == (True, [0]) # Hangs... # Five double roots (this is (x**5 - x + 1)**2) eq = f(x).diff(x, 10) - 2*f(x).diff(x, 6) + 2*f(x).diff(x, 5) + f(x).diff(x, 2) - 2*f(x).diff(x, 1) + f(x) r1, r2, r3, r4, r5 = [rootof(x**5 - x + 1, n) for n in range(5)] sol = Eq(f(x), (C1 + C2 *x)*exp(r1*x) + exp(re(r2)*x) * ((C3 + C4*x)*sin(im(r2)*x) + (C5 + C6 *x)*cos(im(r2)*x)) + exp(re(r4)*x) * ((C7 + C8*x)*sin(im(r4)*x) + (C9 + C10*x)*cos(im(r4)*x)) ) assert dsolve(eq) == sol # FIXME: assert checkodesol(eq, sol) == (True, [0]) # Hangs... def test_nth_linear_constant_coeff_homogeneous_irrational(): our_hint='nth_linear_constant_coeff_homogeneous' eq = Eq(sqrt(2) * f(x).diff(x,x,x) + f(x).diff(x), 0) sol = Eq(f(x), C1 + C2*sin(2**Rational(3, 4)*x/2) + C3*cos(2**Rational(3, 4)*x/2)) assert our_hint in classify_ode(eq) assert dsolve(eq, f(x), hint=our_hint) == sol assert dsolve(eq, f(x)) == sol assert checkodesol(eq, sol, order=3, solve_for_func=False)[0] E = exp(1) eq = Eq(E * f(x).diff(x,x,x) + f(x).diff(x), 0) sol = Eq(f(x), C1 + C2*sin(x/sqrt(E)) + C3*cos(x/sqrt(E))) assert our_hint in classify_ode(eq) assert dsolve(eq, f(x), hint=our_hint) == sol assert dsolve(eq, f(x)) == sol assert checkodesol(eq, sol, order=3, solve_for_func=False)[0] eq = Eq(pi * f(x).diff(x,x,x) + f(x).diff(x), 0) sol = Eq(f(x), C1 + C2*sin(x/sqrt(pi)) + C3*cos(x/sqrt(pi))) assert our_hint in classify_ode(eq) assert dsolve(eq, f(x), hint=our_hint) == sol assert dsolve(eq, f(x)) == sol assert checkodesol(eq, sol, order=3, solve_for_func=False)[0] eq = Eq(I * f(x).diff(x,x,x) + f(x).diff(x), 0) sol = Eq(f(x), C1 + C2*exp(-sqrt(I)*x) + C3*exp(sqrt(I)*x)) assert our_hint in classify_ode(eq) assert dsolve(eq, f(x), hint=our_hint) == sol assert dsolve(eq, f(x)) == sol assert checkodesol(eq, sol, order=3, solve_for_func=False)[0] @XFAIL @slow def test_nth_linear_constant_coeff_homogeneous_rootof_sol(): if ON_TRAVIS: skip("Too slow for travis.") eq = f(x).diff(x, 5) + 11*f(x).diff(x) - 2*f(x) sol = Eq(f(x), C1*exp(x*rootof(x**5 + 11*x - 2, 0)) + C2*exp(x*rootof(x**5 + 11*x - 2, 1)) + C3*exp(x*rootof(x**5 + 11*x - 2, 2)) + C4*exp(x*rootof(x**5 + 11*x - 2, 3)) + C5*exp(x*rootof(x**5 + 11*x - 2, 4))) assert checkodesol(eq, sol, order=5, solve_for_func=False)[0] @XFAIL def test_noncircularized_real_imaginary_parts(): # If this passes, lines numbered 3878-3882 (at the time of this commit) # of sympy/solvers/ode.py for nth_linear_constant_coeff_homogeneous # should be removed. y = sqrt(1+x) i, r = im(y), re(y) assert not (i.has(atan2) and r.has(atan2)) def test_collect_respecting_exponentials(): # If this test passes, lines 1306-1311 (at the time of this commit) # of sympy/solvers/ode.py should be removed. sol = 1 + exp(x/2) assert sol == collect( sol, exp(x/3)) def test_undetermined_coefficients_match(): assert _undetermined_coefficients_match(g(x), x) == {'test': False} assert _undetermined_coefficients_match(sin(2*x + sqrt(5)), x) == \ {'test': True, 'trialset': set([cos(2*x + sqrt(5)), sin(2*x + sqrt(5))])} assert _undetermined_coefficients_match(sin(x)*cos(x), x) == \ {'test': False} s = set([cos(x), x*cos(x), x**2*cos(x), x**2*sin(x), x*sin(x), sin(x)]) assert _undetermined_coefficients_match(sin(x)*(x**2 + x + 1), x) == \ {'test': True, 'trialset': s} assert _undetermined_coefficients_match( sin(x)*x**2 + sin(x)*x + sin(x), x) == {'test': True, 'trialset': s} assert _undetermined_coefficients_match( exp(2*x)*sin(x)*(x**2 + x + 1), x ) == { 'test': True, 'trialset': set([exp(2*x)*sin(x), x**2*exp(2*x)*sin(x), cos(x)*exp(2*x), x**2*cos(x)*exp(2*x), x*cos(x)*exp(2*x), x*exp(2*x)*sin(x)])} assert _undetermined_coefficients_match(1/sin(x), x) == {'test': False} assert _undetermined_coefficients_match(log(x), x) == {'test': False} assert _undetermined_coefficients_match(2**(x)*(x**2 + x + 1), x) == \ {'test': True, 'trialset': set([2**x, x*2**x, x**2*2**x])} assert _undetermined_coefficients_match(x**y, x) == {'test': False} assert _undetermined_coefficients_match(exp(x)*exp(2*x + 1), x) == \ {'test': True, 'trialset': set([exp(1 + 3*x)])} assert _undetermined_coefficients_match(sin(x)*(x**2 + x + 1), x) == \ {'test': True, 'trialset': set([x*cos(x), x*sin(x), x**2*cos(x), x**2*sin(x), cos(x), sin(x)])} assert _undetermined_coefficients_match(sin(x)*(x + sin(x)), x) == \ {'test': False} assert _undetermined_coefficients_match(sin(x)*(x + sin(2*x)), x) == \ {'test': False} assert _undetermined_coefficients_match(sin(x)*tan(x), x) == \ {'test': False} assert _undetermined_coefficients_match( x**2*sin(x)*exp(x) + x*sin(x) + x, x ) == { 'test': True, 'trialset': set([x**2*cos(x)*exp(x), x, cos(x), S.One, exp(x)*sin(x), sin(x), x*exp(x)*sin(x), x*cos(x), x*cos(x)*exp(x), x*sin(x), cos(x)*exp(x), x**2*exp(x)*sin(x)])} assert _undetermined_coefficients_match(4*x*sin(x - 2), x) == { 'trialset': set([x*cos(x - 2), x*sin(x - 2), cos(x - 2), sin(x - 2)]), 'test': True, } assert _undetermined_coefficients_match(2**x*x, x) == \ {'test': True, 'trialset': set([2**x, x*2**x])} assert _undetermined_coefficients_match(2**x*exp(2*x), x) == \ {'test': True, 'trialset': set([2**x*exp(2*x)])} assert _undetermined_coefficients_match(exp(-x)/x, x) == \ {'test': False} # Below are from Ordinary Differential Equations, # Tenenbaum and Pollard, pg. 231 assert _undetermined_coefficients_match(S(4), x) == \ {'test': True, 'trialset': set([S.One])} assert _undetermined_coefficients_match(12*exp(x), x) == \ {'test': True, 'trialset': set([exp(x)])} assert _undetermined_coefficients_match(exp(I*x), x) == \ {'test': True, 'trialset': set([exp(I*x)])} assert _undetermined_coefficients_match(sin(x), x) == \ {'test': True, 'trialset': set([cos(x), sin(x)])} assert _undetermined_coefficients_match(cos(x), x) == \ {'test': True, 'trialset': set([cos(x), sin(x)])} assert _undetermined_coefficients_match(8 + 6*exp(x) + 2*sin(x), x) == \ {'test': True, 'trialset': set([S.One, cos(x), sin(x), exp(x)])} assert _undetermined_coefficients_match(x**2, x) == \ {'test': True, 'trialset': set([S.One, x, x**2])} assert _undetermined_coefficients_match(9*x*exp(x) + exp(-x), x) == \ {'test': True, 'trialset': set([x*exp(x), exp(x), exp(-x)])} assert _undetermined_coefficients_match(2*exp(2*x)*sin(x), x) == \ {'test': True, 'trialset': set([exp(2*x)*sin(x), cos(x)*exp(2*x)])} assert _undetermined_coefficients_match(x - sin(x), x) == \ {'test': True, 'trialset': set([S.One, x, cos(x), sin(x)])} assert _undetermined_coefficients_match(x**2 + 2*x, x) == \ {'test': True, 'trialset': set([S.One, x, x**2])} assert _undetermined_coefficients_match(4*x*sin(x), x) == \ {'test': True, 'trialset': set([x*cos(x), x*sin(x), cos(x), sin(x)])} assert _undetermined_coefficients_match(x*sin(2*x), x) == \ {'test': True, 'trialset': set([x*cos(2*x), x*sin(2*x), cos(2*x), sin(2*x)])} assert _undetermined_coefficients_match(x**2*exp(-x), x) == \ {'test': True, 'trialset': set([x*exp(-x), x**2*exp(-x), exp(-x)])} assert _undetermined_coefficients_match(2*exp(-x) - x**2*exp(-x), x) == \ {'test': True, 'trialset': set([x*exp(-x), x**2*exp(-x), exp(-x)])} assert _undetermined_coefficients_match(exp(-2*x) + x**2, x) == \ {'test': True, 'trialset': set([S.One, x, x**2, exp(-2*x)])} assert _undetermined_coefficients_match(x*exp(-x), x) == \ {'test': True, 'trialset': set([x*exp(-x), exp(-x)])} assert _undetermined_coefficients_match(x + exp(2*x), x) == \ {'test': True, 'trialset': set([S.One, x, exp(2*x)])} assert _undetermined_coefficients_match(sin(x) + exp(-x), x) == \ {'test': True, 'trialset': set([cos(x), sin(x), exp(-x)])} assert _undetermined_coefficients_match(exp(x), x) == \ {'test': True, 'trialset': set([exp(x)])} # converted from sin(x)**2 assert _undetermined_coefficients_match(S.Half - cos(2*x)/2, x) == \ {'test': True, 'trialset': set([S.One, cos(2*x), sin(2*x)])} # converted from exp(2*x)*sin(x)**2 assert _undetermined_coefficients_match( exp(2*x)*(S.Half + cos(2*x)/2), x ) == { 'test': True, 'trialset': set([exp(2*x)*sin(2*x), cos(2*x)*exp(2*x), exp(2*x)])} assert _undetermined_coefficients_match(2*x + sin(x) + cos(x), x) == \ {'test': True, 'trialset': set([S.One, x, cos(x), sin(x)])} # converted from sin(2*x)*sin(x) assert _undetermined_coefficients_match(cos(x)/2 - cos(3*x)/2, x) == \ {'test': True, 'trialset': set([cos(x), cos(3*x), sin(x), sin(3*x)])} assert _undetermined_coefficients_match(cos(x**2), x) == {'test': False} assert _undetermined_coefficients_match(2**(x**2), x) == {'test': False} @slow def test_nth_linear_constant_coeff_undetermined_coefficients(): hint = 'nth_linear_constant_coeff_undetermined_coefficients' g = exp(-x) f2 = f(x).diff(x, 2) c = 3*f(x).diff(x, 3) + 5*f2 + f(x).diff(x) - f(x) - x eq1 = c - x*g eq2 = c - g # 3-27 below are from Ordinary Differential Equations, # Tenenbaum and Pollard, pg. 231 eq3 = f2 + 3*f(x).diff(x) + 2*f(x) - 4 eq4 = f2 + 3*f(x).diff(x) + 2*f(x) - 12*exp(x) eq5 = f2 + 3*f(x).diff(x) + 2*f(x) - exp(I*x) eq6 = f2 + 3*f(x).diff(x) + 2*f(x) - sin(x) eq7 = f2 + 3*f(x).diff(x) + 2*f(x) - cos(x) eq8 = f2 + 3*f(x).diff(x) + 2*f(x) - (8 + 6*exp(x) + 2*sin(x)) eq9 = f2 + f(x).diff(x) + f(x) - x**2 eq10 = f2 - 2*f(x).diff(x) - 8*f(x) - 9*x*exp(x) - 10*exp(-x) eq11 = f2 - 3*f(x).diff(x) - 2*exp(2*x)*sin(x) eq12 = f(x).diff(x, 4) - 2*f2 + f(x) - x + sin(x) eq13 = f2 + f(x).diff(x) - x**2 - 2*x eq14 = f2 + f(x).diff(x) - x - sin(2*x) eq15 = f2 + f(x) - 4*x*sin(x) eq16 = f2 + 4*f(x) - x*sin(2*x) eq17 = f2 + 2*f(x).diff(x) + f(x) - x**2*exp(-x) eq18 = f(x).diff(x, 3) + 3*f2 + 3*f(x).diff(x) + f(x) - 2*exp(-x) + \ x**2*exp(-x) eq19 = f2 + 3*f(x).diff(x) + 2*f(x) - exp(-2*x) - x**2 eq20 = f2 - 3*f(x).diff(x) + 2*f(x) - x*exp(-x) eq21 = f2 + f(x).diff(x) - 6*f(x) - x - exp(2*x) eq22 = f2 + f(x) - sin(x) - exp(-x) eq23 = f(x).diff(x, 3) - 3*f2 + 3*f(x).diff(x) - f(x) - exp(x) # sin(x)**2 eq24 = f2 + f(x) - S.Half - cos(2*x)/2 # exp(2*x)*sin(x)**2 eq25 = f(x).diff(x, 3) - f(x).diff(x) - exp(2*x)*(S.Half - cos(2*x)/2) eq26 = (f(x).diff(x, 5) + 2*f(x).diff(x, 3) + f(x).diff(x) - 2*x - sin(x) - cos(x)) # sin(2*x)*sin(x), skip 3127 for now, match bug eq27 = f2 + f(x) - cos(x)/2 + cos(3*x)/2 eq28 = f(x).diff(x) - 1 sol1 = Eq(f(x), -1 - x + (C1 + C2*x - 3*x**2/32 - x**3/24)*exp(-x) + C3*exp(x/3)) sol2 = Eq(f(x), -1 - x + (C1 + C2*x - x**2/8)*exp(-x) + C3*exp(x/3)) sol3 = Eq(f(x), 2 + C1*exp(-x) + C2*exp(-2*x)) sol4 = Eq(f(x), 2*exp(x) + C1*exp(-x) + C2*exp(-2*x)) sol5 = Eq(f(x), C1*exp(-2*x) + C2*exp(-x) + exp(I*x)/10 - 3*I*exp(I*x)/10) sol6 = Eq(f(x), -3*cos(x)/10 + sin(x)/10 + C1*exp(-x) + C2*exp(-2*x)) sol7 = Eq(f(x), cos(x)/10 + 3*sin(x)/10 + C1*exp(-x) + C2*exp(-2*x)) sol8 = Eq(f(x), 4 - 3*cos(x)/5 + sin(x)/5 + exp(x) + C1*exp(-x) + C2*exp(-2*x)) sol9 = Eq(f(x), -2*x + x**2 + (C1*sin(x*sqrt(3)/2) + C2*cos(x*sqrt(3)/2))*exp(-x/2)) sol10 = Eq(f(x), -x*exp(x) - 2*exp(-x) + C1*exp(-2*x) + C2*exp(4*x)) sol11 = Eq(f(x), C1 + C2*exp(3*x) + (-3*sin(x) - cos(x))*exp(2*x)/5) sol12 = Eq(f(x), x - sin(x)/4 + (C1 + C2*x)*exp(-x) + (C3 + C4*x)*exp(x)) sol13 = Eq(f(x), C1 + x**3/3 + C2*exp(-x)) sol14 = Eq(f(x), C1 - x - sin(2*x)/5 - cos(2*x)/10 + x**2/2 + C2*exp(-x)) sol15 = Eq(f(x), (C1 + x)*sin(x) + (C2 - x**2)*cos(x)) sol16 = Eq(f(x), (C1 + x/16)*sin(2*x) + (C2 - x**2/8)*cos(2*x)) sol17 = Eq(f(x), (C1 + C2*x + x**4/12)*exp(-x)) sol18 = Eq(f(x), (C1 + C2*x + C3*x**2 - x**5/60 + x**3/3)*exp(-x)) sol19 = Eq(f(x), Rational(7, 4) - x*Rational(3, 2) + x**2/2 + C1*exp(-x) + (C2 - x)*exp(-2*x)) sol20 = Eq(f(x), C1*exp(x) + C2*exp(2*x) + (6*x + 5)*exp(-x)/36) sol21 = Eq(f(x), Rational(-1, 36) - x/6 + C1*exp(-3*x) + (C2 + x/5)*exp(2*x)) sol22 = Eq(f(x), C1*sin(x) + (C2 - x/2)*cos(x) + exp(-x)/2) sol23 = Eq(f(x), (C1 + C2*x + C3*x**2 + x**3/6)*exp(x)) sol24 = Eq(f(x), S.Half - cos(2*x)/6 + C1*sin(x) + C2*cos(x)) sol25 = Eq(f(x), C1 + C2*exp(-x) + C3*exp(x) + (-21*sin(2*x) + 27*cos(2*x) + 130)*exp(2*x)/1560) sol26 = Eq(f(x), C1 + (C2 + C3*x - x**2/8)*sin(x) + (C4 + C5*x + x**2/8)*cos(x) + x**2) sol27 = Eq(f(x), cos(3*x)/16 + C1*cos(x) + (C2 + x/4)*sin(x)) sol28 = Eq(f(x), C1 + x) sol1s = constant_renumber(sol1) sol2s = constant_renumber(sol2) sol3s = constant_renumber(sol3) sol4s = constant_renumber(sol4) sol5s = constant_renumber(sol5) sol6s = constant_renumber(sol6) sol7s = constant_renumber(sol7) sol8s = constant_renumber(sol8) sol9s = constant_renumber(sol9) sol10s = constant_renumber(sol10) sol11s = constant_renumber(sol11) sol12s = constant_renumber(sol12) sol13s = constant_renumber(sol13) sol14s = constant_renumber(sol14) sol15s = constant_renumber(sol15) sol16s = constant_renumber(sol16) sol17s = constant_renumber(sol17) sol18s = constant_renumber(sol18) sol19s = constant_renumber(sol19) sol20s = constant_renumber(sol20) sol21s = constant_renumber(sol21) sol22s = constant_renumber(sol22) sol23s = constant_renumber(sol23) sol24s = constant_renumber(sol24) sol25s = constant_renumber(sol25) sol26s = constant_renumber(sol26) sol27s = constant_renumber(sol27) assert dsolve(eq1, hint=hint) in (sol1, sol1s) assert dsolve(eq2, hint=hint) in (sol2, sol2s) assert dsolve(eq3, hint=hint) in (sol3, sol3s) assert dsolve(eq4, hint=hint) in (sol4, sol4s) assert dsolve(eq5, hint=hint) in (sol5, sol5s) assert dsolve(eq6, hint=hint) in (sol6, sol6s) assert dsolve(eq7, hint=hint) in (sol7, sol7s) assert dsolve(eq8, hint=hint) in (sol8, sol8s) assert dsolve(eq9, hint=hint) in (sol9, sol9s) assert dsolve(eq10, hint=hint) in (sol10, sol10s) assert dsolve(eq11, hint=hint) in (sol11, sol11s) assert dsolve(eq12, hint=hint) in (sol12, sol12s) assert dsolve(eq13, hint=hint) in (sol13, sol13s) assert dsolve(eq14, hint=hint) in (sol14, sol14s) assert dsolve(eq15, hint=hint) in (sol15, sol15s) assert dsolve(eq16, hint=hint) in (sol16, sol16s) assert dsolve(eq17, hint=hint) in (sol17, sol17s) assert dsolve(eq18, hint=hint) in (sol18, sol18s) assert dsolve(eq19, hint=hint) in (sol19, sol19s) assert dsolve(eq20, hint=hint) in (sol20, sol20s) assert dsolve(eq21, hint=hint) in (sol21, sol21s) assert dsolve(eq22, hint=hint) in (sol22, sol22s) assert dsolve(eq23, hint=hint) in (sol23, sol23s) assert dsolve(eq24, hint=hint) in (sol24, sol24s) assert dsolve(eq25, hint=hint) in (sol25, sol25s) assert dsolve(eq26, hint=hint) in (sol26, sol26s) assert dsolve(eq27, hint=hint) in (sol27, sol27s) assert dsolve(eq28, hint=hint) == sol28 assert checkodesol(eq1, sol1, order=3, solve_for_func=False)[0] assert checkodesol(eq2, sol2, order=3, solve_for_func=False)[0] assert checkodesol(eq3, sol3, order=2, solve_for_func=False)[0] assert checkodesol(eq4, sol4, order=2, solve_for_func=False)[0] assert checkodesol(eq5, sol5, order=2, solve_for_func=False)[0] assert checkodesol(eq6, sol6, order=2, solve_for_func=False)[0] assert checkodesol(eq7, sol7, order=2, solve_for_func=False)[0] assert checkodesol(eq8, sol8, order=2, solve_for_func=False)[0] assert checkodesol(eq9, sol9, order=2, solve_for_func=False)[0] assert checkodesol(eq10, sol10, order=2, solve_for_func=False)[0] assert checkodesol(eq11, sol11, order=2, solve_for_func=False)[0] assert checkodesol(eq12, sol12, order=4, solve_for_func=False)[0] assert checkodesol(eq13, sol13, order=2, solve_for_func=False)[0] assert checkodesol(eq14, sol14, order=2, solve_for_func=False)[0] assert checkodesol(eq15, sol15, order=2, solve_for_func=False)[0] assert checkodesol(eq16, sol16, order=2, solve_for_func=False)[0] assert checkodesol(eq17, sol17, order=2, solve_for_func=False)[0] assert checkodesol(eq18, sol18, order=3, solve_for_func=False)[0] assert checkodesol(eq19, sol19, order=2, solve_for_func=False)[0] assert checkodesol(eq20, sol20, order=2, solve_for_func=False)[0] assert checkodesol(eq21, sol21, order=2, solve_for_func=False)[0] assert checkodesol(eq22, sol22, order=2, solve_for_func=False)[0] assert checkodesol(eq23, sol23, order=3, solve_for_func=False)[0] assert checkodesol(eq24, sol24, order=2, solve_for_func=False)[0] assert checkodesol(eq25, sol25, order=3, solve_for_func=False)[0] assert checkodesol(eq26, sol26, order=5, solve_for_func=False)[0] assert checkodesol(eq27, sol27, order=2, solve_for_func=False)[0] assert checkodesol(eq28, sol28, order=1, solve_for_func=False)[0] def test_issue_5787(): # This test case is to show the classification of imaginary constants under # nth_linear_constant_coeff_undetermined_coefficients eq = Eq(diff(f(x), x), I*f(x) + S.Half - I) our_hint = 'nth_linear_constant_coeff_undetermined_coefficients' assert our_hint in classify_ode(eq) @XFAIL def test_nth_linear_constant_coeff_undetermined_coefficients_imaginary_exp(): # Equivalent to eq26 in # test_nth_linear_constant_coeff_undetermined_coefficients above. # This fails because the algorithm for undetermined coefficients # doesn't know to multiply exp(I*x) by sufficient x because it is linearly # dependent on sin(x) and cos(x). hint = 'nth_linear_constant_coeff_undetermined_coefficients' eq26a = f(x).diff(x, 5) + 2*f(x).diff(x, 3) + f(x).diff(x) - 2*x - exp(I*x) sol26 = Eq(f(x), C1 + (C2 + C3*x - x**2/8)*sin(x) + (C4 + C5*x + x**2/8)*cos(x) + x**2) assert dsolve(eq26a, hint=hint) == sol26 assert checkodesol(eq26a, sol26, order=5, solve_for_func=False)[0] @slow def test_nth_linear_constant_coeff_variation_of_parameters(): hint = 'nth_linear_constant_coeff_variation_of_parameters' g = exp(-x) f2 = f(x).diff(x, 2) c = 3*f(x).diff(x, 3) + 5*f2 + f(x).diff(x) - f(x) - x eq1 = c - x*g eq2 = c - g eq3 = f(x).diff(x) - 1 eq4 = f2 + 3*f(x).diff(x) + 2*f(x) - 4 eq5 = f2 + 3*f(x).diff(x) + 2*f(x) - 12*exp(x) eq6 = f2 - 2*f(x).diff(x) - 8*f(x) - 9*x*exp(x) - 10*exp(-x) eq7 = f2 + 2*f(x).diff(x) + f(x) - x**2*exp(-x) eq8 = f2 - 3*f(x).diff(x) + 2*f(x) - x*exp(-x) eq9 = f(x).diff(x, 3) - 3*f2 + 3*f(x).diff(x) - f(x) - exp(x) eq10 = f2 + 2*f(x).diff(x) + f(x) - exp(-x)/x eq11 = f2 + f(x) - 1/sin(x)*1/cos(x) eq12 = f(x).diff(x, 4) - 1/x sol1 = Eq(f(x), -1 - x + (C1 + C2*x - 3*x**2/32 - x**3/24)*exp(-x) + C3*exp(x/3)) sol2 = Eq(f(x), -1 - x + (C1 + C2*x - x**2/8)*exp(-x) + C3*exp(x/3)) sol3 = Eq(f(x), C1 + x) sol4 = Eq(f(x), 2 + C1*exp(-x) + C2*exp(-2*x)) sol5 = Eq(f(x), 2*exp(x) + C1*exp(-x) + C2*exp(-2*x)) sol6 = Eq(f(x), -x*exp(x) - 2*exp(-x) + C1*exp(-2*x) + C2*exp(4*x)) sol7 = Eq(f(x), (C1 + C2*x + x**4/12)*exp(-x)) sol8 = Eq(f(x), C1*exp(x) + C2*exp(2*x) + (6*x + 5)*exp(-x)/36) sol9 = Eq(f(x), (C1 + C2*x + C3*x**2 + x**3/6)*exp(x)) sol10 = Eq(f(x), (C1 + x*(C2 + log(x)))*exp(-x)) sol11 = Eq(f(x), (C1 + log(sin(x) - 1)/2 - log(sin(x) + 1)/2 )*cos(x) + (C2 + log(cos(x) - 1)/2 - log(cos(x) + 1)/2)*sin(x)) sol12 = Eq(f(x), C1 + C2*x + x**3*(C3 + log(x)/6) + C4*x**2) sol1s = constant_renumber(sol1) sol2s = constant_renumber(sol2) sol3s = constant_renumber(sol3) sol4s = constant_renumber(sol4) sol5s = constant_renumber(sol5) sol6s = constant_renumber(sol6) sol7s = constant_renumber(sol7) sol8s = constant_renumber(sol8) sol9s = constant_renumber(sol9) sol10s = constant_renumber(sol10) sol11s = constant_renumber(sol11) sol12s = constant_renumber(sol12) assert dsolve(eq1, hint=hint) in (sol1, sol1s) assert dsolve(eq2, hint=hint) in (sol2, sol2s) assert dsolve(eq3, hint=hint) in (sol3, sol3s) assert dsolve(eq4, hint=hint) in (sol4, sol4s) assert dsolve(eq5, hint=hint) in (sol5, sol5s) assert dsolve(eq6, hint=hint) in (sol6, sol6s) assert dsolve(eq7, hint=hint) in (sol7, sol7s) assert dsolve(eq8, hint=hint) in (sol8, sol8s) assert dsolve(eq9, hint=hint) in (sol9, sol9s) assert dsolve(eq10, hint=hint) in (sol10, sol10s) assert dsolve(eq11, hint=hint + '_Integral').doit() in (sol11, sol11s) assert dsolve(eq12, hint=hint) in (sol12, sol12s) assert checkodesol(eq1, sol1, order=3, solve_for_func=False)[0] assert checkodesol(eq2, sol2, order=3, solve_for_func=False)[0] assert checkodesol(eq3, sol3, order=1, solve_for_func=False)[0] assert checkodesol(eq4, sol4, order=2, solve_for_func=False)[0] assert checkodesol(eq5, sol5, order=2, solve_for_func=False)[0] assert checkodesol(eq6, sol6, order=2, solve_for_func=False)[0] assert checkodesol(eq7, sol7, order=2, solve_for_func=False)[0] assert checkodesol(eq8, sol8, order=2, solve_for_func=False)[0] assert checkodesol(eq9, sol9, order=3, solve_for_func=False)[0] assert checkodesol(eq10, sol10, order=2, solve_for_func=False)[0] assert checkodesol(eq12, sol12, order=4, solve_for_func=False)[0] @slow def test_nth_linear_constant_coeff_variation_of_parameters_simplify_False(): # solve_variation_of_parameters shouldn't attempt to simplify the # Wronskian if simplify=False. If wronskian() ever gets good enough # to simplify the result itself, this test might fail. our_hint = 'nth_linear_constant_coeff_variation_of_parameters_Integral' eq = f(x).diff(x, 5) + 2*f(x).diff(x, 3) + f(x).diff(x) - 2*x - exp(I*x) sol_simp = dsolve(eq, f(x), hint=our_hint, simplify=True) sol_nsimp = dsolve(eq, f(x), hint=our_hint, simplify=False) assert sol_simp != sol_nsimp assert checkodesol(eq, sol_simp, order=5, solve_for_func=False) == (True, 0) assert checkodesol(eq, sol_simp, order=5, solve_for_func=False) == (True, 0) def test_Liouville_ODE(): hint = 'Liouville' # The first part here used to be test_ODE_1() from test_solvers.py eq1 = diff(f(x), x)/x + diff(f(x), x, x)/2 - diff(f(x), x)**2/2 eq1a = diff(x*exp(-f(x)), x, x) # compare to test_unexpanded_Liouville_ODE() below eq2 = (eq1*exp(-f(x))/exp(f(x))).expand() eq3 = diff(f(x), x, x) + 1/f(x)*(diff(f(x), x))**2 + 1/x*diff(f(x), x) eq4 = x*diff(f(x), x, x) + x/f(x)*diff(f(x), x)**2 + x*diff(f(x), x) eq5 = Eq((x*exp(f(x))).diff(x, x), 0) sol1 = Eq(f(x), log(x/(C1 + C2*x))) sol1a = Eq(C1 + C2/x - exp(-f(x)), 0) sol2 = sol1 sol3 = set( [Eq(f(x), -sqrt(C1 + C2*log(x))), Eq(f(x), sqrt(C1 + C2*log(x)))]) sol4 = set([Eq(f(x), sqrt(C1 + C2*exp(x))*exp(-x/2)), Eq(f(x), -sqrt(C1 + C2*exp(x))*exp(-x/2))]) sol5 = Eq(f(x), log(C1 + C2/x)) sol1s = constant_renumber(sol1) sol2s = constant_renumber(sol2) sol3s = constant_renumber(sol3) sol4s = constant_renumber(sol4) sol5s = constant_renumber(sol5) assert dsolve(eq1, hint=hint) in (sol1, sol1s) assert dsolve(eq1a, hint=hint) in (sol1, sol1s) assert dsolve(eq2, hint=hint) in (sol2, sol2s) assert set(dsolve(eq3, hint=hint)) in (sol3, sol3s) assert set(dsolve(eq4, hint=hint)) in (sol4, sol4s) assert dsolve(eq5, hint=hint) in (sol5, sol5s) assert checkodesol(eq1, sol1, order=2, solve_for_func=False)[0] assert checkodesol(eq1a, sol1a, order=2, solve_for_func=False)[0] assert checkodesol(eq2, sol2, order=2, solve_for_func=False)[0] assert checkodesol(eq3, sol3, order=2, solve_for_func=False) == {(True, 0)} assert checkodesol(eq4, sol4, order=2, solve_for_func=False) == {(True, 0)} assert checkodesol(eq5, sol5, order=2, solve_for_func=False)[0] not_Liouville1 = classify_ode(diff(f(x), x)/x + f(x)*diff(f(x), x, x)/2 - diff(f(x), x)**2/2, f(x)) not_Liouville2 = classify_ode(diff(f(x), x)/x + diff(f(x), x, x)/2 - x*diff(f(x), x)**2/2, f(x)) assert hint not in not_Liouville1 assert hint not in not_Liouville2 assert hint + '_Integral' not in not_Liouville1 assert hint + '_Integral' not in not_Liouville2 def test_unexpanded_Liouville_ODE(): # This is the same as eq1 from test_Liouville_ODE() above. eq1 = diff(f(x), x)/x + diff(f(x), x, x)/2 - diff(f(x), x)**2/2 eq2 = eq1*exp(-f(x))/exp(f(x)) sol2 = Eq(f(x), log(x/(C1 + C2*x))) sol2s = constant_renumber(sol2) assert dsolve(eq2) in (sol2, sol2s) assert checkodesol(eq2, sol2, order=2, solve_for_func=False)[0] def test_issue_4785(): from sympy.abc import A eq = x + A*(x + diff(f(x), x) + f(x)) + diff(f(x), x) + f(x) + 2 assert classify_ode(eq, f(x)) == ('1st_linear', 'almost_linear', '1st_power_series', 'lie_group', 'nth_linear_constant_coeff_undetermined_coefficients', 'nth_linear_constant_coeff_variation_of_parameters', '1st_linear_Integral', 'almost_linear_Integral', 'nth_linear_constant_coeff_variation_of_parameters_Integral') # issue 4864 eq = (x**2 + f(x)**2)*f(x).diff(x) - 2*x*f(x) assert classify_ode(eq, f(x)) == ('1st_exact', '1st_homogeneous_coeff_best', '1st_homogeneous_coeff_subs_indep_div_dep', '1st_homogeneous_coeff_subs_dep_div_indep', '1st_power_series', 'lie_group', '1st_exact_Integral', '1st_homogeneous_coeff_subs_indep_div_dep_Integral', '1st_homogeneous_coeff_subs_dep_div_indep_Integral') def test_issue_4825(): raises(ValueError, lambda: dsolve(f(x, y).diff(x) - y*f(x, y), f(x))) assert classify_ode(f(x, y).diff(x) - y*f(x, y), f(x), dict=True) == \ {'order': 0, 'default': None, 'ordered_hints': ()} # See also issue 3793, test Z13. raises(ValueError, lambda: dsolve(f(x).diff(x), f(y))) assert classify_ode(f(x).diff(x), f(y), dict=True) == \ {'order': 0, 'default': None, 'ordered_hints': ()} def test_constant_renumber_order_issue_5308(): from sympy.utilities.iterables import variations assert constant_renumber(C1*x + C2*y) == \ constant_renumber(C1*y + C2*x) == \ C1*x + C2*y e = C1*(C2 + x)*(C3 + y) for a, b, c in variations([C1, C2, C3], 3): assert constant_renumber(a*(b + x)*(c + y)) == e def test_issue_5770(): k = Symbol("k", real=True) t = Symbol('t') w = Function('w') sol = dsolve(w(t).diff(t, 6) - k**6*w(t), w(t)) assert len([s for s in sol.free_symbols if s.name.startswith('C')]) == 6 assert constantsimp((C1*cos(x) + C2*cos(x))*exp(x), set([C1, C2])) == \ C1*cos(x)*exp(x) assert constantsimp(C1*cos(x) + C2*cos(x) + C3*sin(x), set([C1, C2, C3])) == \ C1*cos(x) + C3*sin(x) assert constantsimp(exp(C1 + x), set([C1])) == C1*exp(x) assert constantsimp(x + C1 + y, set([C1, y])) == C1 + x assert constantsimp(x + C1 + Integral(x, (x, 1, 2)), set([C1])) == C1 + x def test_issue_5112_5430(): assert homogeneous_order(-log(x) + acosh(x), x) is None assert homogeneous_order(y - log(x), x, y) is None def test_nth_order_linear_euler_eq_homogeneous(): x, t, a, b, c = symbols('x t a b c') y = Function('y') our_hint = "nth_linear_euler_eq_homogeneous" eq = diff(f(t), t, 4)*t**4 - 13*diff(f(t), t, 2)*t**2 + 36*f(t) assert our_hint in classify_ode(eq) eq = a*y(t) + b*t*diff(y(t), t) + c*t**2*diff(y(t), t, 2) assert our_hint in classify_ode(eq) eq = Eq(-3*diff(f(x), x)*x + 2*x**2*diff(f(x), x, x), 0) sol = C1 + C2*x**Rational(5, 2) sols = constant_renumber(sol) assert our_hint in classify_ode(eq) assert dsolve(eq, f(x), hint=our_hint).rhs in (sol, sols) assert checkodesol(eq, sol, order=2, solve_for_func=False)[0] eq = Eq(3*f(x) - 5*diff(f(x), x)*x + 2*x**2*diff(f(x), x, x), 0) sol = C1*sqrt(x) + C2*x**3 sols = constant_renumber(sol) assert our_hint in classify_ode(eq) assert dsolve(eq, f(x), hint=our_hint).rhs in (sol, sols) assert checkodesol(eq, sol, order=2, solve_for_func=False)[0] eq = Eq(4*f(x) + 5*diff(f(x), x)*x + x**2*diff(f(x), x, x), 0) sol = (C1 + C2*log(x))/x**2 sols = constant_renumber(sol) assert our_hint in classify_ode(eq) assert dsolve(eq, f(x), hint=our_hint).rhs in (sol, sols) assert checkodesol(eq, sol, order=2, solve_for_func=False)[0] eq = Eq(6*f(x) - 6*diff(f(x), x)*x + 1*x**2*diff(f(x), x, x) + x**3*diff(f(x), x, x, x), 0) sol = dsolve(eq, f(x), hint=our_hint) sol = C1/x**2 + C2*x + C3*x**3 sols = constant_renumber(sol) assert our_hint in classify_ode(eq) assert dsolve(eq, f(x), hint=our_hint).rhs in (sol, sols) assert checkodesol(eq, sol, order=2, solve_for_func=False)[0] eq = Eq(-125*f(x) + 61*diff(f(x), x)*x - 12*x**2*diff(f(x), x, x) + x**3*diff(f(x), x, x, x), 0) sol = x**5*(C1 + C2*log(x) + C3*log(x)**2) sols = [sol, constant_renumber(sol)] sols += [sols[-1].expand()] assert our_hint in classify_ode(eq) assert dsolve(eq, f(x), hint=our_hint).rhs in sols assert checkodesol(eq, sol, order=2, solve_for_func=False)[0] eq = t**2*diff(y(t), t, 2) + t*diff(y(t), t) - 9*y(t) sol = C1*t**3 + C2*t**-3 sols = constant_renumber(sol) assert our_hint in classify_ode(eq) assert dsolve(eq, y(t), hint=our_hint).rhs in (sol, sols) assert checkodesol(eq, sol, order=2, solve_for_func=False)[0] eq = sin(x)*x**2*f(x).diff(x, 2) + sin(x)*x*f(x).diff(x) + sin(x)*f(x) sol = C1*sin(log(x)) + C2*cos(log(x)) sols = constant_renumber(sol) assert our_hint in classify_ode(eq) assert dsolve(eq, f(x), hint=our_hint).rhs in (sol, sols) assert checkodesol(eq, sol, order=2, solve_for_func=False)[0] def test_nth_order_linear_euler_eq_nonhomogeneous_undetermined_coefficients(): x, t = symbols('x t') a, b, c, d = symbols('a b c d', integer=True) our_hint = "nth_linear_euler_eq_nonhomogeneous_undetermined_coefficients" eq = x**4*diff(f(x), x, 4) - 13*x**2*diff(f(x), x, 2) + 36*f(x) + x assert our_hint in classify_ode(eq, f(x)) eq = a*x**2*diff(f(x), x, 2) + b*x*diff(f(x), x) + c*f(x) + d*log(x) assert our_hint in classify_ode(eq, f(x)) eq = Eq(x**2*diff(f(x), x, x) + x*diff(f(x), x), 1) sol = C1 + C2*log(x) + log(x)**2/2 sols = constant_renumber(sol) assert our_hint in classify_ode(eq, f(x)) assert dsolve(eq, f(x), hint=our_hint).rhs in (sol, sols) assert checkodesol(eq, sol, order=2, solve_for_func=False)[0] eq = Eq(x**2*diff(f(x), x, x) - 2*x*diff(f(x), x) + 2*f(x), x**3) sol = x*(C1 + C2*x + Rational(1, 2)*x**2) sols = constant_renumber(sol) assert our_hint in classify_ode(eq, f(x)) assert dsolve(eq, f(x), hint=our_hint).rhs in (sol, sols) assert checkodesol(eq, sol, order=2, solve_for_func=False)[0] eq = Eq(x**2*diff(f(x), x, x) - x*diff(f(x), x) - 3*f(x), log(x)/x) sol = C1/x + C2*x**3 - Rational(1, 16)*log(x)/x - Rational(1, 8)*log(x)**2/x sols = constant_renumber(sol) assert our_hint in classify_ode(eq, f(x)) assert dsolve(eq, f(x), hint=our_hint).rhs.expand() in (sol, sols) assert checkodesol(eq, sol, order=2, solve_for_func=False)[0] eq = Eq(x**2*diff(f(x), x, x) + 3*x*diff(f(x), x) - 8*f(x), log(x)**3 - log(x)) sol = C1/x**4 + C2*x**2 - Rational(1,8)*log(x)**3 - Rational(3,32)*log(x)**2 - Rational(1,64)*log(x) - Rational(7, 256) sols = constant_renumber(sol) assert our_hint in classify_ode(eq) assert dsolve(eq, f(x), hint=our_hint).rhs.expand() in (sol, sols) assert checkodesol(eq, sol, order=2, solve_for_func=False)[0] eq = Eq(x**3*diff(f(x), x, x, x) - 3*x**2*diff(f(x), x, x) + 6*x*diff(f(x), x) - 6*f(x), log(x)) sol = C1*x + C2*x**2 + C3*x**3 - Rational(1, 6)*log(x) - Rational(11, 36) sols = constant_renumber(sol) assert our_hint in classify_ode(eq) assert dsolve(eq, f(x), hint=our_hint).rhs.expand() in (sol, sols) assert checkodesol(eq, sol, order=2, solve_for_func=False)[0] def test_nth_order_linear_euler_eq_nonhomogeneous_variation_of_parameters(): x, t = symbols('x, t') a, b, c, d = symbols('a, b, c, d', integer=True) our_hint = "nth_linear_euler_eq_nonhomogeneous_variation_of_parameters" eq = Eq(x**2*diff(f(x),x,2) - 8*x*diff(f(x),x) + 12*f(x), x**2) assert our_hint in classify_ode(eq, f(x)) eq = Eq(a*x**3*diff(f(x),x,3) + b*x**2*diff(f(x),x,2) + c*x*diff(f(x),x) + d*f(x), x*log(x)) assert our_hint in classify_ode(eq, f(x)) eq = Eq(x**2*Derivative(f(x), x, x) - 2*x*Derivative(f(x), x) + 2*f(x), x**4) sol = C1*x + C2*x**2 + x**4/6 sols = constant_renumber(sol) assert our_hint in classify_ode(eq) assert dsolve(eq, f(x), hint=our_hint).rhs.expand() in (sol, sols) assert checkodesol(eq, sol, order=2, solve_for_func=False)[0] eq = Eq(3*x**2*diff(f(x), x, x) + 6*x*diff(f(x), x) - 6*f(x), x**3*exp(x)) sol = C1/x**2 + C2*x + x*exp(x)/3 - 4*exp(x)/3 + 8*exp(x)/(3*x) - 8*exp(x)/(3*x**2) sols = constant_renumber(sol) assert our_hint in classify_ode(eq) assert dsolve(eq, f(x), hint=our_hint).rhs.expand() in (sol, sols) assert checkodesol(eq, sol, order=2, solve_for_func=False)[0] eq = Eq(x**2*Derivative(f(x), x, x) - 2*x*Derivative(f(x), x) + 2*f(x), x**4*exp(x)) sol = C1*x + C2*x**2 + x**2*exp(x) - 2*x*exp(x) sols = constant_renumber(sol) assert our_hint in classify_ode(eq) assert dsolve(eq, f(x), hint=our_hint).rhs.expand() in (sol, sols) assert checkodesol(eq, sol, order=2, solve_for_func=False)[0] eq = x**2*Derivative(f(x), x, x) - 2*x*Derivative(f(x), x) + 2*f(x) - log(x) sol = C1*x + C2*x**2 + log(x)/2 + Rational(3, 4) sols = constant_renumber(sol) assert our_hint in classify_ode(eq) assert dsolve(eq, f(x), hint=our_hint).rhs in (sol, sols) assert checkodesol(eq, sol, order=2, solve_for_func=False)[0] eq = -exp(x) + (x*Derivative(f(x), (x, 2)) + Derivative(f(x), x))/x sol = Eq(f(x), C1 + C2*log(x) + exp(x) - Ei(x)) assert our_hint in classify_ode(eq) assert dsolve(eq, f(x), hint=our_hint) == sol assert checkodesol(eq, sol, order=2, solve_for_func=False)[0] def test_issue_5095(): f = Function('f') raises(ValueError, lambda: dsolve(f(x).diff(x)**2, f(x), 'fdsjf')) def test_almost_linear(): from sympy import Ei A = Symbol('A', positive=True) our_hint = 'almost_linear' f = Function('f') d = f(x).diff(x) eq = x**2*f(x)**2*d + f(x)**3 + 1 sol = dsolve(eq, f(x), hint = 'almost_linear') assert sol[0].rhs == (C1*exp(3/x) - 1)**Rational(1, 3) assert checkodesol(eq, sol, order=1, solve_for_func=False)[0] eq = x*f(x)*d + 2*x*f(x)**2 + 1 sol = [ Eq(f(x), -sqrt((C1 - 2*Ei(4*x))*exp(-4*x))), Eq(f(x), sqrt((C1 - 2*Ei(4*x))*exp(-4*x))) ] assert set(dsolve(eq, f(x), hint = 'almost_linear')) == set(sol) assert checkodesol(eq, sol, order=1, solve_for_func=False)[0] eq = x*d + x*f(x) + 1 sol = dsolve(eq, f(x), hint = 'almost_linear') assert sol.rhs == (C1 - Ei(x))*exp(-x) assert checkodesol(eq, sol, order=1, solve_for_func=False)[0] assert our_hint in classify_ode(eq, f(x)) eq = x*exp(f(x))*d + exp(f(x)) + 3*x sol = dsolve(eq, f(x), hint = 'almost_linear') assert sol.rhs == log(C1/x - x*Rational(3, 2)) assert checkodesol(eq, sol, order=1, solve_for_func=False)[0] eq = x + A*(x + diff(f(x), x) + f(x)) + diff(f(x), x) + f(x) + 2 sol = dsolve(eq, f(x), hint = 'almost_linear') assert sol.rhs == (C1 + Piecewise( (x, Eq(A + 1, 0)), ((-A*x + A - x - 1)*exp(x)/(A + 1), True)))*exp(-x) assert checkodesol(eq, sol, order=1, solve_for_func=False)[0] def test_exact_enhancement(): f = Function('f')(x) df = Derivative(f, x) eq = f/x**2 + ((f*x - 1)/x)*df sol = [Eq(f, (i*sqrt(C1*x**2 + 1) + 1)/x) for i in (-1, 1)] assert set(dsolve(eq, f)) == set(sol) assert checkodesol(eq, sol, order=1, solve_for_func=False) == [(True, 0), (True, 0)] eq = (x*f - 1) + df*(x**2 - x*f) sol = [Eq(f, x - sqrt(C1 + x**2 - 2*log(x))), Eq(f, x + sqrt(C1 + x**2 - 2*log(x)))] assert set(dsolve(eq, f)) == set(sol) assert checkodesol(eq, sol, order=1, solve_for_func=False) == [(True, 0), (True, 0)] eq = (x + 2)*sin(f) + df*x*cos(f) sol = [Eq(f, -asin(C1*exp(-x)/x**2) + pi), Eq(f, asin(C1*exp(-x)/x**2))] assert set(dsolve(eq, f)) == set(sol) assert checkodesol(eq, sol, order=1, solve_for_func=False) == [(True, 0), (True, 0)] @slow def test_separable_reduced(): f = Function('f') x = Symbol('x') df = f(x).diff(x) eq = (x / f(x))*df + tan(x**2*f(x) / (x**2*f(x) - 1)) assert classify_ode(eq) == ('separable_reduced', 'lie_group', 'separable_reduced_Integral') eq = x* df + f(x)* (1 / (x**2*f(x) - 1)) assert classify_ode(eq) == ('separable_reduced', 'lie_group', 'separable_reduced_Integral') sol = dsolve(eq, hint = 'separable_reduced', simplify=False) assert sol.lhs == log(x**2*f(x))/3 + log(x**2*f(x) - Rational(3, 2))/6 assert sol.rhs == C1 + log(x) assert checkodesol(eq, sol, order=1, solve_for_func=False)[0] eq = f(x).diff(x) + (f(x) / (x**4*f(x) - x)) assert classify_ode(eq) == ('separable_reduced', 'lie_group', 'separable_reduced_Integral') sol = dsolve(eq, hint = 'separable_reduced') # FIXME: This one hangs #assert checkodesol(eq, sol, order=1, solve_for_func=False) == [(True, 0)] * 4 assert len(sol) == 4 eq = x*df + f(x)*(x**2*f(x)) sol = dsolve(eq, hint = 'separable_reduced', simplify=False) assert sol == Eq(log(x**2*f(x))/2 - log(x**2*f(x) - 2)/2, C1 + log(x)) assert checkodesol(eq, sol, order=1, solve_for_func=False)[0] def test_homogeneous_function(): f = Function('f') eq1 = tan(x + f(x)) eq2 = sin((3*x)/(4*f(x))) eq3 = cos(x*f(x)*Rational(3, 4)) eq4 = log((3*x + 4*f(x))/(5*f(x) + 7*x)) eq5 = exp((2*x**2)/(3*f(x)**2)) eq6 = log((3*x + 4*f(x))/(5*f(x) + 7*x) + exp((2*x**2)/(3*f(x)**2))) eq7 = sin((3*x)/(5*f(x) + x**2)) assert homogeneous_order(eq1, x, f(x)) == None assert homogeneous_order(eq2, x, f(x)) == 0 assert homogeneous_order(eq3, x, f(x)) == None assert homogeneous_order(eq4, x, f(x)) == 0 assert homogeneous_order(eq5, x, f(x)) == 0 assert homogeneous_order(eq6, x, f(x)) == 0 assert homogeneous_order(eq7, x, f(x)) == None def test_linear_coeff_match(): n, d = z*(2*x + 3*f(x) + 5), z*(7*x + 9*f(x) + 11) rat = n/d eq1 = sin(rat) + cos(rat.expand()) eq2 = rat eq3 = log(sin(rat)) ans = (4, Rational(-13, 3)) assert _linear_coeff_match(eq1, f(x)) == ans assert _linear_coeff_match(eq2, f(x)) == ans assert _linear_coeff_match(eq3, f(x)) == ans # no c eq4 = (3*x)/f(x) # not x and f(x) eq5 = (3*x + 2)/x # denom will be zero eq6 = (3*x + 2*f(x) + 1)/(3*x + 2*f(x) + 5) # not rational coefficient eq7 = (3*x + 2*f(x) + sqrt(2))/(3*x + 2*f(x) + 5) assert _linear_coeff_match(eq4, f(x)) is None assert _linear_coeff_match(eq5, f(x)) is None assert _linear_coeff_match(eq6, f(x)) is None assert _linear_coeff_match(eq7, f(x)) is None def test_linear_coefficients(): f = Function('f') sol = Eq(f(x), C1/(x**2 + 6*x + 9) - Rational(3, 2)) eq = f(x).diff(x) + (3 + 2*f(x))/(x + 3) assert dsolve(eq, hint='linear_coefficients') == sol assert checkodesol(eq, sol, order=1, solve_for_func=False)[0] def test_constantsimp_take_problem(): c = exp(C1) + 2 assert len(Poly(constantsimp(exp(C1) + c + c*x, [C1])).gens) == 2 def test_issue_6879(): f = Function('f') eq = Eq(Derivative(f(x), x, 2) - 2*Derivative(f(x), x) + f(x), sin(x)) sol = (C1 + C2*x)*exp(x) + cos(x)/2 assert dsolve(eq).rhs == sol assert checkodesol(eq, sol, order=1, solve_for_func=False)[0] def test_issue_6989(): f = Function('f') k = Symbol('k') eq = f(x).diff(x) - x*exp(-k*x) csol = Eq(f(x), C1 + Piecewise( ((-k*x - 1)*exp(-k*x)/k**2, Ne(k**2, 0)), (x**2/2, True) )) sol = dsolve(eq, f(x)) assert sol == csol assert checkodesol(eq, sol, order=1, solve_for_func=False)[0] eq = -f(x).diff(x) + x*exp(-k*x) csol = Eq(f(x), C1 + Piecewise( ((-k*x - 1)*exp(-k*x)/k**2, Ne(k**2, 0)), (x**2/2, True) )) sol = dsolve(eq, f(x)) assert sol == csol assert checkodesol(eq, sol, order=1, solve_for_func=False)[0] def test_heuristic1(): y, a, b, c, a4, a3, a2, a1, a0 = symbols("y a b c a4 a3 a2 a1 a0") f = Function('f') xi = Function('xi') eta = Function('eta') df = f(x).diff(x) eq = Eq(df, x**2*f(x)) eq1 = f(x).diff(x) + a*f(x) - c*exp(b*x) eq2 = f(x).diff(x) + 2*x*f(x) - x*exp(-x**2) eq3 = (1 + 2*x)*df + 2 - 4*exp(-f(x)) eq4 = f(x).diff(x) - (a4*x**4 + a3*x**3 + a2*x**2 + a1*x + a0)**Rational(-1, 2) eq5 = x**2*df - f(x) + x**2*exp(x - (1/x)) eqlist = [eq, eq1, eq2, eq3, eq4, eq5] i = infinitesimals(eq, hint='abaco1_simple') assert i == [{eta(x, f(x)): exp(x**3/3), xi(x, f(x)): 0}, {eta(x, f(x)): f(x), xi(x, f(x)): 0}, {eta(x, f(x)): 0, xi(x, f(x)): x**(-2)}] i1 = infinitesimals(eq1, hint='abaco1_simple') assert i1 == [{eta(x, f(x)): exp(-a*x), xi(x, f(x)): 0}] i2 = infinitesimals(eq2, hint='abaco1_simple') assert i2 == [{eta(x, f(x)): exp(-x**2), xi(x, f(x)): 0}] i3 = infinitesimals(eq3, hint='abaco1_simple') assert i3 == [{eta(x, f(x)): 0, xi(x, f(x)): 2*x + 1}, {eta(x, f(x)): 0, xi(x, f(x)): 1/(exp(f(x)) - 2)}] i4 = infinitesimals(eq4, hint='abaco1_simple') assert i4 == [{eta(x, f(x)): 1, xi(x, f(x)): 0}, {eta(x, f(x)): 0, xi(x, f(x)): sqrt(a0 + a1*x + a2*x**2 + a3*x**3 + a4*x**4)}] i5 = infinitesimals(eq5, hint='abaco1_simple') assert i5 == [{xi(x, f(x)): 0, eta(x, f(x)): exp(-1/x)}] ilist = [i, i1, i2, i3, i4, i5] for eq, i in (zip(eqlist, ilist)): check = checkinfsol(eq, i) assert check[0] def test_issue_6247(): eq = x**2*f(x)**2 + x*Derivative(f(x), x) sol = Eq(f(x), 2*C1/(C1*x**2 - 1)) assert dsolve(eq, hint = 'separable_reduced') == sol assert checkodesol(eq, sol, order=1)[0] eq = f(x).diff(x, x) + 4*f(x) sol = Eq(f(x), C1*sin(2*x) + C2*cos(2*x)) assert dsolve(eq) == sol assert checkodesol(eq, sol, order=1)[0] def test_heuristic2(): xi = Function('xi') eta = Function('eta') df = f(x).diff(x) # This ODE can be solved by the Lie Group method, when there are # better assumptions eq = df - (f(x)/x)*(x*log(x**2/f(x)) + 2) i = infinitesimals(eq, hint='abaco1_product') assert i == [{eta(x, f(x)): f(x)*exp(-x), xi(x, f(x)): 0}] assert checkinfsol(eq, i)[0] @slow def test_heuristic3(): xi = Function('xi') eta = Function('eta') a, b = symbols("a b") df = f(x).diff(x) eq = x**2*df + x*f(x) + f(x)**2 + x**2 i = infinitesimals(eq, hint='bivariate') assert i == [{eta(x, f(x)): f(x), xi(x, f(x)): x}] assert checkinfsol(eq, i)[0] eq = x**2*(-f(x)**2 + df)- a*x**2*f(x) + 2 - a*x i = infinitesimals(eq, hint='bivariate') assert checkinfsol(eq, i)[0] def test_heuristic_4(): y, a = symbols("y a") eq = x*(f(x).diff(x)) + 1 - f(x)**2 i = infinitesimals(eq, hint='chi') assert checkinfsol(eq, i)[0] def test_heuristic_function_sum(): xi = Function('xi') eta = Function('eta') eq = f(x).diff(x) - (3*(1 + x**2/f(x)**2)*atan(f(x)/x) + (1 - 2*f(x))/x + (1 - 3*f(x))*(x/f(x)**2)) i = infinitesimals(eq, hint='function_sum') assert i == [{eta(x, f(x)): f(x)**(-2) + x**(-2), xi(x, f(x)): 0}] assert checkinfsol(eq, i)[0] def test_heuristic_abaco2_similar(): xi = Function('xi') eta = Function('eta') F = Function('F') a, b = symbols("a b") eq = f(x).diff(x) - F(a*x + b*f(x)) i = infinitesimals(eq, hint='abaco2_similar') assert i == [{eta(x, f(x)): -a/b, xi(x, f(x)): 1}] assert checkinfsol(eq, i)[0] eq = f(x).diff(x) - (f(x)**2 / (sin(f(x) - x) - x**2 + 2*x*f(x))) i = infinitesimals(eq, hint='abaco2_similar') assert i == [{eta(x, f(x)): f(x)**2, xi(x, f(x)): f(x)**2}] assert checkinfsol(eq, i)[0] def test_heuristic_abaco2_unique_unknown(): xi = Function('xi') eta = Function('eta') F = Function('F') a, b = symbols("a b") x = Symbol("x", positive=True) eq = f(x).diff(x) - x**(a - 1)*(f(x)**(1 - b))*F(x**a/a + f(x)**b/b) i = infinitesimals(eq, hint='abaco2_unique_unknown') assert i == [{eta(x, f(x)): -f(x)*f(x)**(-b), xi(x, f(x)): x*x**(-a)}] assert checkinfsol(eq, i)[0] eq = f(x).diff(x) + tan(F(x**2 + f(x)**2) + atan(x/f(x))) i = infinitesimals(eq, hint='abaco2_unique_unknown') assert i == [{eta(x, f(x)): x, xi(x, f(x)): -f(x)}] assert checkinfsol(eq, i)[0] eq = (x*f(x).diff(x) + f(x) + 2*x)**2 -4*x*f(x) -4*x**2 -4*a i = infinitesimals(eq, hint='abaco2_unique_unknown') assert checkinfsol(eq, i)[0] def test_heuristic_linear(): a, b, m, n = symbols("a b m n") eq = x**(n*(m + 1) - m)*(f(x).diff(x)) - a*f(x)**n -b*x**(n*(m + 1)) i = infinitesimals(eq, hint='linear') assert checkinfsol(eq, i)[0] @XFAIL def test_kamke(): a, b, alpha, c = symbols("a b alpha c") eq = x**2*(a*f(x)**2+(f(x).diff(x))) + b*x**alpha + c i = infinitesimals(eq, hint='sum_function') assert checkinfsol(eq, i)[0] def test_series(): C1 = Symbol("C1") eq = f(x).diff(x) - f(x) sol = Eq(f(x), C1 + C1*x + C1*x**2/2 + C1*x**3/6 + C1*x**4/24 + C1*x**5/120 + O(x**6)) assert dsolve(eq, hint='1st_power_series') == sol assert checkodesol(eq, sol, order=1)[0] eq = f(x).diff(x) - x*f(x) sol = Eq(f(x), C1*x**4/8 + C1*x**2/2 + C1 + O(x**6)) assert dsolve(eq, hint='1st_power_series') == sol assert checkodesol(eq, sol, order=1)[0] eq = f(x).diff(x) - sin(x*f(x)) sol = Eq(f(x), (x - 2)**2*(1+ sin(4))*cos(4) + (x - 2)*sin(4) + 2 + O(x**3)) assert dsolve(eq, hint='1st_power_series', ics={f(2): 2}, n=3) == sol # FIXME: The solution here should be O((x-2)**3) so is incorrect #assert checkodesol(eq, sol, order=1)[0] @XFAIL @SKIP def test_lie_group_issue17322(): eq=x*f(x).diff(x)*(f(x)+4) + (f(x)**2) -2*f(x)-2*x sol = dsolve(eq, f(x)) assert checkodesol(eq, sol) == (True, 0) eq=x*f(x).diff(x)*(f(x)+4) + (f(x)**2) -2*f(x)-2*x sol = dsolve(eq) assert checkodesol(eq, sol) == (True, 0) eq=Eq(x**7*Derivative(f(x), x) + 5*x**3*f(x)**2 - (2*x**2 + 2)*f(x)**3, 0) sol = dsolve(eq) assert checkodesol(eq, sol) == (True, 0) eq=f(x).diff(x) - (f(x) - x*log(x))**2/x**2 + log(x) sol = dsolve(eq) assert checkodesol(eq, sol) == (True, 0) @slow def test_lie_group(): C1 = Symbol("C1") x = Symbol("x") # assuming x is real generates an error! a, b, c = symbols("a b c") eq = f(x).diff(x)**2 sol = dsolve(eq, f(x), hint='lie_group') assert checkodesol(eq, sol) == (True, 0) eq = Eq(f(x).diff(x), x**2*f(x)) sol = dsolve(eq, f(x), hint='lie_group') assert sol == Eq(f(x), C1*exp(x**3)**Rational(1, 3)) assert checkodesol(eq, sol) == (True, 0) eq = f(x).diff(x) + a*f(x) - c*exp(b*x) sol = dsolve(eq, f(x), hint='lie_group') assert checkodesol(eq, sol) == (True, 0) eq = f(x).diff(x) + 2*x*f(x) - x*exp(-x**2) sol = dsolve(eq, f(x), hint='lie_group') actual_sol = Eq(f(x), (C1 + x**2/2)*exp(-x**2)) errstr = str(eq)+' : '+str(sol)+' == '+str(actual_sol) assert sol == actual_sol, errstr assert checkodesol(eq, sol) == (True, 0) eq = (1 + 2*x)*(f(x).diff(x)) + 2 - 4*exp(-f(x)) sol = dsolve(eq, f(x), hint='lie_group') assert sol == Eq(f(x), log(C1/(2*x + 1) + 2)) assert checkodesol(eq, sol) == (True, 0) eq = x**2*(f(x).diff(x)) - f(x) + x**2*exp(x - (1/x)) sol = dsolve(eq, f(x), hint='lie_group') assert checkodesol(eq, sol)[0] eq = x**2*f(x)**2 + x*Derivative(f(x), x) sol = dsolve(eq, f(x), hint='lie_group') assert sol == Eq(f(x), 2/(C1 + x**2)) assert checkodesol(eq, sol) == (True, 0) eq=diff(f(x),x) + 2*x*f(x) - x*exp(-x**2) sol = Eq(f(x), exp(-x**2)*(C1 + x**2/2)) assert sol == dsolve(eq, hint='lie_group') assert checkodesol(eq, sol) == (True, 0) eq = diff(f(x),x) + f(x)*cos(x) - exp(2*x) sol = Eq(f(x), exp(-sin(x))*(C1 + Integral(exp(2*x)*exp(sin(x)), x))) assert sol == dsolve(eq, hint='lie_group') assert checkodesol(eq, sol) == (True, 0) eq = diff(f(x),x) + f(x)*cos(x) - sin(2*x)/2 sol = Eq(f(x), C1*exp(-sin(x)) + sin(x) - 1) assert sol == dsolve(eq, hint='lie_group') assert checkodesol(eq, sol) == (True, 0) eq = x*diff(f(x),x) + f(x) - x*sin(x) sol = Eq(f(x), (C1 - x*cos(x) + sin(x))/x) assert sol == dsolve(eq, hint='lie_group') assert checkodesol(eq, sol) == (True, 0) eq = x*diff(f(x),x) - f(x) - x/log(x) sol = Eq(f(x), x*(C1 + log(log(x)))) assert sol == dsolve(eq, hint='lie_group') assert checkodesol(eq, sol) == (True, 0) eq = (f(x).diff(x)-f(x)) * (f(x).diff(x)+f(x)) sol = [Eq(f(x), C1*exp(x)), Eq(f(x), C1*exp(-x))] assert set(sol) == set(dsolve(eq, hint='lie_group')) assert checkodesol(eq, sol[0]) == (True, 0) assert checkodesol(eq, sol[1]) == (True, 0) eq = f(x).diff(x) * (f(x).diff(x) - f(x)) sol = [Eq(f(x), C1*exp(x)), Eq(f(x), C1)] assert set(sol) == set(dsolve(eq, hint='lie_group')) assert checkodesol(eq, sol[0]) == (True, 0) assert checkodesol(eq, sol[1]) == (True, 0) @XFAIL def test_lie_group_issue15219(): eqn = exp(f(x).diff(x)-f(x)) assert 'lie_group' not in classify_ode(eqn, f(x)) def test_user_infinitesimals(): x = Symbol("x") # assuming x is real generates an error eq = x*(f(x).diff(x)) + 1 - f(x)**2 sol = Eq(f(x), (C1 + x**2)/(C1 - x**2)) infinitesimals = {'xi':sqrt(f(x) - 1)/sqrt(f(x) + 1), 'eta':0} assert dsolve(eq, hint='lie_group', **infinitesimals) == sol assert checkodesol(eq, sol) == (True, 0) def test_issue_7081(): eq = x*(f(x).diff(x)) + 1 - f(x)**2 s = Eq(f(x), -1/(-C1 + x**2)*(C1 + x**2)) assert dsolve(eq) == s assert checkodesol(eq, s) == (True, 0) @slow def test_2nd_power_series_ordinary(): C1, C2 = symbols("C1 C2") eq = f(x).diff(x, 2) - x*f(x) assert classify_ode(eq) == ('2nd_linear_airy', '2nd_power_series_ordinary') sol = Eq(f(x), C2*(x**3/6 + 1) + C1*x*(x**3/12 + 1) + O(x**6)) assert dsolve(eq, hint='2nd_power_series_ordinary') == sol assert checkodesol(eq, sol) == (True, 0) sol = Eq(f(x), C2*((x + 2)**4/6 + (x + 2)**3/6 - (x + 2)**2 + 1) + C1*(x + (x + 2)**4/12 - (x + 2)**3/3 + S(2)) + O(x**6)) assert dsolve(eq, hint='2nd_power_series_ordinary', x0=-2) == sol # FIXME: Solution should be O((x+2)**6) # assert checkodesol(eq, sol) == (True, 0) sol = Eq(f(x), C2*x + C1 + O(x**2)) assert dsolve(eq, hint='2nd_power_series_ordinary', n=2) == sol assert checkodesol(eq, sol) == (True, 0) eq = (1 + x**2)*(f(x).diff(x, 2)) + 2*x*(f(x).diff(x)) -2*f(x) assert classify_ode(eq) == ('2nd_power_series_ordinary',) sol = Eq(f(x), C2*(-x**4/3 + x**2 + 1) + C1*x + O(x**6)) assert dsolve(eq) == sol assert checkodesol(eq, sol) == (True, 0) eq = f(x).diff(x, 2) + x*(f(x).diff(x)) + f(x) assert classify_ode(eq) == ('2nd_power_series_ordinary',) sol = Eq(f(x), C2*(x**4/8 - x**2/2 + 1) + C1*x*(-x**2/3 + 1) + O(x**6)) assert dsolve(eq) == sol # FIXME: checkodesol fails for this solution... # assert checkodesol(eq, sol) == (True, 0) eq = f(x).diff(x, 2) + f(x).diff(x) - x*f(x) assert classify_ode(eq) == ('2nd_power_series_ordinary',) sol = Eq(f(x), C2*(-x**4/24 + x**3/6 + 1) + C1*x*(x**3/24 + x**2/6 - x/2 + 1) + O(x**6)) assert dsolve(eq) == sol # FIXME: checkodesol fails for this solution... # assert checkodesol(eq, sol) == (True, 0) eq = f(x).diff(x, 2) + x*f(x) assert classify_ode(eq) == ('2nd_linear_airy', '2nd_power_series_ordinary') sol = Eq(f(x), C2*(x**6/180 - x**3/6 + 1) + C1*x*(-x**3/12 + 1) + O(x**7)) assert dsolve(eq, hint='2nd_power_series_ordinary', n=7) == sol assert checkodesol(eq, sol) == (True, 0) def test_Airy_equation(): eq = f(x).diff(x, 2) - x*f(x) sol = Eq(f(x), C1*airyai(x) + C2*airybi(x)) sols = constant_renumber(sol) assert classify_ode(eq) == ("2nd_linear_airy",'2nd_power_series_ordinary') assert checkodesol(eq, sol) == (True, 0) assert dsolve(eq, f(x)) in (sol, sols) assert dsolve(eq, f(x), hint='2nd_linear_airy') in (sol, sols) eq = f(x).diff(x, 2) + 2*x*f(x) sol = Eq(f(x), C1*airyai(-2**(S(1)/3)*x) + C2*airybi(-2**(S(1)/3)*x)) sols = constant_renumber(sol) assert classify_ode(eq) == ("2nd_linear_airy",'2nd_power_series_ordinary') assert checkodesol(eq, sol) == (True, 0) assert dsolve(eq, f(x)) in (sol, sols) assert dsolve(eq, f(x), hint='2nd_linear_airy') in (sol, sols) def test_2nd_power_series_regular(): C1, C2 = symbols("C1 C2") eq = x**2*(f(x).diff(x, 2)) - 3*x*(f(x).diff(x)) + (4*x + 4)*f(x) sol = Eq(f(x), C1*x**2*(-16*x**3/9 + 4*x**2 - 4*x + 1) + O(x**6)) assert dsolve(eq, hint='2nd_power_series_regular') == sol assert checkodesol(eq, sol) == (True, 0) eq = 4*x**2*(f(x).diff(x, 2)) -8*x**2*(f(x).diff(x)) + (4*x**2 + 1)*f(x) sol = Eq(f(x), C1*sqrt(x)*(x**4/24 + x**3/6 + x**2/2 + x + 1) + O(x**6)) assert dsolve(eq, hint='2nd_power_series_regular') == sol assert checkodesol(eq, sol) == (True, 0) eq = x**2*(f(x).diff(x, 2)) - x**2*(f(x).diff(x)) + ( x**2 - 2)*f(x) sol = Eq(f(x), C1*(-x**6/720 - 3*x**5/80 - x**4/8 + x**2/2 + x/2 + 1)/x + C2*x**2*(-x**3/60 + x**2/20 + x/2 + 1) + O(x**6)) assert dsolve(eq) == sol assert checkodesol(eq, sol) == (True, 0) eq = x**2*(f(x).diff(x, 2)) + x*(f(x).diff(x)) + (x**2 - Rational(1, 4))*f(x) sol = Eq(f(x), C1*(x**4/24 - x**2/2 + 1)/sqrt(x) + C2*sqrt(x)*(x**4/120 - x**2/6 + 1) + O(x**6)) assert dsolve(eq, hint='2nd_power_series_regular') == sol assert checkodesol(eq, sol) == (True, 0) def test_2nd_linear_bessel_equation(): eq = x**2*(f(x).diff(x, 2)) + x*(f(x).diff(x)) + (x**2 - 4)*f(x) sol = Eq(f(x), C1*besselj(2, x) + C2*bessely(2, x)) sols = constant_renumber(sol) assert dsolve(eq, f(x)) in (sol, sols) assert dsolve(eq, f(x), hint='2nd_linear_bessel') in (sol, sols) assert checkodesol(eq, sol, order=2, solve_for_func=False) == (True, 0) eq = x**2*(f(x).diff(x, 2)) + x*(f(x).diff(x)) + (x**2 +25)*f(x) sol = Eq(f(x), C1*besselj(5*I, x) + C2*bessely(5*I, x)) sols = constant_renumber(sol) assert dsolve(eq, f(x)) in (sol, sols) assert dsolve(eq, f(x), hint='2nd_linear_bessel') in (sol, sols) checkodesol(eq, sol, order=2, solve_for_func=False) == (True, 0) eq = x**2*(f(x).diff(x, 2)) + x*(f(x).diff(x)) + (x**2)*f(x) sol = Eq(f(x), C1*besselj(0, x) + C2*bessely(0, x)) sols = constant_renumber(sol) assert dsolve(eq, f(x)) in (sol, sols) assert dsolve(eq, f(x), hint='2nd_linear_bessel') in (sol, sols) assert checkodesol(eq, sol, order=2, solve_for_func=False) == (True, 0) eq = x**2*(f(x).diff(x, 2)) + x*(f(x).diff(x)) + (81*x**2 -S(1)/9)*f(x) sol = Eq(f(x), C1*besselj(S(1)/3, 9*x) + C2*bessely(S(1)/3, 9*x)) sols = constant_renumber(sol) assert dsolve(eq, f(x)) in (sol, sols) assert dsolve(eq, f(x), hint='2nd_linear_bessel') in (sol, sols) checkodesol(eq, sol, order=2, solve_for_func=False) == (True, 0) eq = x**2*(f(x).diff(x, 2)) + x*(f(x).diff(x)) + (x**4 - 4)*f(x) sol = Eq(f(x), C1*besselj(1, x**2/2) + C2*bessely(1, x**2/2)) sols = constant_renumber(sol) assert dsolve(eq, f(x)) in (sol, sols) assert dsolve(eq, f(x), hint='2nd_linear_bessel') in (sol, sols) assert checkodesol(eq, sol, order=2, solve_for_func=False) == (True, 0) eq = x**2*(f(x).diff(x, 2)) + 2*x*(f(x).diff(x)) + (x**4 - 4)*f(x) sol = Eq(f(x), (C1*besselj(sqrt(17)/4, x**2/2) + C2*bessely(sqrt(17)/4, x**2/2))/sqrt(x)) sols = constant_renumber(sol) assert dsolve(eq, f(x)) in (sol, sols) assert dsolve(eq, f(x), hint='2nd_linear_bessel') in (sol, sols) assert checkodesol(eq, sol, order=2, solve_for_func=False) == (True, 0) eq = x**2*(f(x).diff(x, 2)) + x*(f(x).diff(x)) + (x**2 - S(1)/4)*f(x) sol = Eq(f(x), C1*besselj(S(1)/2, x) + C2*bessely(S(1)/2, x)) sols = constant_renumber(sol) assert dsolve(eq, f(x)) in (sol, sols) assert dsolve(eq, f(x), hint='2nd_linear_bessel') in (sol, sols) assert checkodesol(eq, sol, order=2, solve_for_func=False) == (True, 0) eq = x**2*(f(x).diff(x, 2)) - 3*x*(f(x).diff(x)) + (4*x + 4)*f(x) sol = Eq(f(x), x**2*(C1*besselj(0, 4*sqrt(x)) + C2*bessely(0, 4*sqrt(x)))) sols = constant_renumber(sol) assert dsolve(eq, f(x)) in (sol, sols) assert dsolve(eq, f(x), hint='2nd_linear_bessel') in (sol, sols) assert checkodesol(eq, sol, order=2, solve_for_func=False) == (True, 0) eq = x*(f(x).diff(x, 2)) - f(x).diff(x) + 4*x**3*f(x) sol = Eq(f(x), x*(C1*besselj(S(1)/2, x**2) + C2*bessely(S(1)/2, x**2))) sols = constant_renumber(sol) assert dsolve(eq, f(x)) in (sol, sols) assert dsolve(eq, f(x), hint='2nd_linear_bessel') in (sol, sols) assert checkodesol(eq, sol, order=2, solve_for_func=False) == (True, 0) eq = (x-2)**2*(f(x).diff(x, 2)) - (x-2)*f(x).diff(x) + 4*(x-2)**2*f(x) sol = Eq(f(x), (x - 2)*(C1*besselj(1, 2*x - 4) + C2*bessely(1, 2*x - 4))) sols = constant_renumber(sol) assert dsolve(eq, f(x)) in (sol, sols) assert dsolve(eq, f(x), hint='2nd_linear_bessel') in (sol, sols) assert checkodesol(eq, sol, order=2, solve_for_func=False) == (True, 0) def test_issue_7093(): x = Symbol("x") # assuming x is real leads to an error sol = [Eq(f(x), C1 - 2*x*sqrt(x**3)/5), Eq(f(x), C1 + 2*x*sqrt(x**3)/5)] eq = Derivative(f(x), x)**2 - x**3 assert set(dsolve(eq)) == set(sol) assert checkodesol(eq, sol) == [(True, 0)] * 2 def test_dsolve_linsystem_symbol(): eps = Symbol('epsilon', positive=True) eq1 = (Eq(diff(f(x), x), -eps*g(x)), Eq(diff(g(x), x), eps*f(x))) sol1 = [Eq(f(x), -C1*eps*cos(eps*x) - C2*eps*sin(eps*x)), Eq(g(x), -C1*eps*sin(eps*x) + C2*eps*cos(eps*x))] assert checksysodesol(eq1, sol1) == (True, [0, 0]) def test_C1_function_9239(): t = Symbol('t') C1 = Function('C1') C2 = Function('C2') C3 = Symbol('C3') C4 = Symbol('C4') eq = (Eq(diff(C1(t), t), 9*C2(t)), Eq(diff(C2(t), t), 12*C1(t))) sol = [Eq(C1(t), 9*C3*exp(6*sqrt(3)*t) + 9*C4*exp(-6*sqrt(3)*t)), Eq(C2(t), 6*sqrt(3)*C3*exp(6*sqrt(3)*t) - 6*sqrt(3)*C4*exp(-6*sqrt(3)*t))] assert checksysodesol(eq, sol) == (True, [0, 0]) def test_issue_15056(): t = Symbol('t') C3 = Symbol('C3') assert get_numbered_constants(Symbol('C1') * Function('C2')(t)) == C3 def test_issue_10379(): t,y = symbols('t,y') eq = f(t).diff(t)-(1-51.05*y*f(t)) sol = Eq(f(t), (0.019588638589618*exp(y*(C1 - 51.05*t)) + 0.019588638589618)/y) dsolve_sol = dsolve(eq, rational=False) assert str(dsolve_sol) == str(sol) assert checkodesol(eq, dsolve_sol)[0] def test_issue_10867(): x = Symbol('x') eq = Eq(g(x).diff(x).diff(x), (x-2)**2 + (x-3)**3) sol = Eq(g(x), C1 + C2*x + x**5/20 - 2*x**4/3 + 23*x**3/6 - 23*x**2/2) assert dsolve(eq, g(x)) == sol assert checkodesol(eq, sol, order=2, solve_for_func=False) == (True, 0) def test_issue_11290(): eq = cos(f(x)) - (x*sin(f(x)) - f(x)**2)*f(x).diff(x) sol_1 = dsolve(eq, f(x), simplify=False, hint='1st_exact_Integral') sol_0 = dsolve(eq, f(x), simplify=False, hint='1st_exact') assert sol_1.dummy_eq(Eq(Subs( Integral(u**2 - x*sin(u) - Integral(-sin(u), x), u) + Integral(cos(u), x), u, f(x)), C1)) assert sol_1.doit() == sol_0 assert checkodesol(eq, sol_0, order=1, solve_for_func=False) assert checkodesol(eq, sol_1, order=1, solve_for_func=False) def test_issue_4838(): # Issue #15999 eq = f(x).diff(x) - C1*f(x) sol = Eq(f(x), C2*exp(C1*x)) assert dsolve(eq, f(x)) == sol assert checkodesol(eq, sol, order=1, solve_for_func=False) == (True, 0) # Issue #13691 eq = f(x).diff(x) - C1*g(x).diff(x) sol = Eq(f(x), C2 + C1*g(x)) assert dsolve(eq, f(x)) == sol assert checkodesol(eq, sol, f(x), order=1, solve_for_func=False) == (True, 0) # Issue #4838 eq = f(x).diff(x) - 3*C1 - 3*x**2 sol = Eq(f(x), C2 + 3*C1*x + x**3) assert dsolve(eq, f(x)) == sol assert checkodesol(eq, sol, order=1, solve_for_func=False) == (True, 0) @slow def test_issue_14395(): eq = Derivative(f(x), x, x) + 9*f(x) - sec(x) sol = Eq(f(x), (C1 - x/3 + sin(2*x)/3)*sin(3*x) + (C2 + log(cos(x)) - 2*log(cos(x)**2)/3 + 2*cos(x)**2/3)*cos(3*x)) assert dsolve(eq, f(x)) == sol # FIXME: assert checkodesol(eq, sol, order=2, solve_for_func=False) == (True, 0) def test_sysode_linear_neq_order1(): from sympy.abc import t Z0 = Function('Z0') Z1 = Function('Z1') Z2 = Function('Z2') Z3 = Function('Z3') k01, k10, k20, k21, k23, k30 = symbols('k01 k10 k20 k21 k23 k30') eq = (Eq(Derivative(Z0(t), t), -k01*Z0(t) + k10*Z1(t) + k20*Z2(t) + k30*Z3(t)), Eq(Derivative(Z1(t), t), k01*Z0(t) - k10*Z1(t) + k21*Z2(t)), Eq(Derivative(Z2(t), t), -(k20 + k21 + k23)*Z2(t)), Eq(Derivative(Z3(t), t), k23*Z2(t) - k30*Z3(t))) sols_eq = [Eq(Z0(t), C1*k10/k01 + C2*(-k10 + k30)*exp(-k30*t)/(k01 + k10 - k30) - C3*exp(t*(- k01 - k10)) + C4*(k10*k20 + k10*k21 - k10*k30 - k20**2 - k20*k21 - k20*k23 + k20*k30 + k23*k30)*exp(t*(-k20 - k21 - k23))/(k23*(k01 + k10 - k20 - k21 - k23))), Eq(Z1(t), C1 - C2*k01*exp(-k30*t)/(k01 + k10 - k30) + C3*exp(t*(-k01 - k10)) + C4*(k01*k20 + k01*k21 - k01*k30 - k20*k21 - k21**2 - k21*k23 + k21*k30)*exp(t*(-k20 - k21 - k23))/(k23*(k01 + k10 - k20 - k21 - k23))), Eq(Z2(t), C4*(-k20 - k21 - k23 + k30)*exp(t*(-k20 - k21 - k23))/k23), Eq(Z3(t), C2*exp(-k30*t) + C4*exp(t*(-k20 - k21 - k23)))] # assert dsolve(eq, simplify=False) == sols_eq dsolved = dsolve(eq, simplify=False) assert all(ds.args[0] == seq.args[0] for ds, seq in zip (dsolved, sols_eq)) assert all(simplify(ds.args[1] - seq.args[1]) == 0 for ds, seq in zip (dsolved, sols_eq)) assert checksysodesol(eq, sols_eq) == (True, [0, 0, 0, 0]) @slow def test_nth_order_reducible(): from sympy.solvers.ode.ode import _nth_order_reducible_match eqn = Eq(x*Derivative(f(x), x)**2 + Derivative(f(x), x, 2), 0) sol = Eq(f(x), C1 - sqrt(-1/C2)*log(-C2*sqrt(-1/C2) + x) + sqrt(-1/C2)*log(C2*sqrt(-1/C2) + x)) assert checkodesol(eqn, sol, order=2, solve_for_func=False) == (True, 0) assert sol == dsolve(eqn, f(x), hint='nth_order_reducible') assert sol == dsolve(eqn, f(x)) F = lambda eq: _nth_order_reducible_match(eq, f(x)) D = Derivative assert F(D(y*f(x), x, y) + D(f(x), x)) is None assert F(D(y*f(y), y, y) + D(f(y), y)) is None assert F(f(x)*D(f(x), x) + D(f(x), x, 2)) is None assert F(D(x*f(y), y, 2) + D(u*y*f(x), x, 3)) is None # no simplification by design assert F(D(f(y), y, 2) + D(f(y), y, 3) + D(f(x), x, 4)) is None assert F(D(f(x), x, 2) + D(f(x), x, 3)) == dict(n=2) eqn = -exp(x) + (x*Derivative(f(x), (x, 2)) + Derivative(f(x), x))/x sol = Eq(f(x), C1 + C2*log(x) + exp(x) - Ei(x)) assert checkodesol(eqn, sol, order=2, solve_for_func=False) == (True, 0) assert sol == dsolve(eqn, f(x)) assert sol == dsolve(eqn, f(x), hint='nth_order_reducible') eqn = Eq(sqrt(2) * f(x).diff(x,x,x) + f(x).diff(x), 0) sol = Eq(f(x), C1 + C2*sin(2**Rational(3, 4)*x/2) + C3*cos(2**Rational(3, 4)*x/2)) assert checkodesol(eqn, sol, order=2, solve_for_func=False) == (True, 0) assert sol == dsolve(eqn, f(x)) assert sol == dsolve(eqn, f(x), hint='nth_order_reducible') eqn = f(x).diff(x, 2) + 2*f(x).diff(x) sol = Eq(f(x), C1 + C2*exp(-2*x)) sols = constant_renumber(sol) assert checkodesol(eqn, sol, order=2, solve_for_func=False) == (True, 0) assert dsolve(eqn, f(x)) in (sol, sols) assert dsolve(eqn, f(x), hint='nth_order_reducible') in (sol, sols) eqn = f(x).diff(x, 3) + f(x).diff(x, 2) - 6*f(x).diff(x) sol = Eq(f(x), C1 + C2*exp(-3*x) + C3*exp(2*x)) sols = constant_renumber(sol) assert checkodesol(eqn, sol, order=2, solve_for_func=False) == (True, 0) assert dsolve(eqn, f(x)) in (sol, sols) assert dsolve(eqn, f(x), hint='nth_order_reducible') in (sol, sols) eqn = f(x).diff(x, 4) - f(x).diff(x, 3) - 4*f(x).diff(x, 2) + \ 4*f(x).diff(x) sol = Eq(f(x), C1 + C2*exp(x) + C3*exp(-2*x) + C4*exp(2*x)) sols = constant_renumber(sol) assert checkodesol(eqn, sol, order=2, solve_for_func=False) == (True, 0) assert dsolve(eqn, f(x)) in (sol, sols) assert dsolve(eqn, f(x), hint='nth_order_reducible') in (sol, sols) eqn = f(x).diff(x, 4) + 3*f(x).diff(x, 3) sol = Eq(f(x), C1 + C2*x + C3*x**2 + C4*exp(-3*x)) sols = constant_renumber(sol) assert checkodesol(eqn, sol, order=2, solve_for_func=False) == (True, 0) assert dsolve(eqn, f(x)) in (sol, sols) assert dsolve(eqn, f(x), hint='nth_order_reducible') in (sol, sols) eqn = f(x).diff(x, 4) - 2*f(x).diff(x, 2) sol = Eq(f(x), C1 + C2*x + C3*exp(x*sqrt(2)) + C4*exp(-x*sqrt(2))) sols = constant_renumber(sol) assert checkodesol(eqn, sol, order=2, solve_for_func=False) == (True, 0) assert dsolve(eqn, f(x)) in (sol, sols) assert dsolve(eqn, f(x), hint='nth_order_reducible') in (sol, sols) eqn = f(x).diff(x, 4) + 4*f(x).diff(x, 2) sol = Eq(f(x), C1 + C2*sin(2*x) + C3*cos(2*x) + C4*x) sols = constant_renumber(sol) assert checkodesol(eqn, sol, order=2, solve_for_func=False) == (True, 0) assert dsolve(eqn, f(x)) in (sol, sols) assert dsolve(eqn, f(x), hint='nth_order_reducible') in (sol, sols) eqn = f(x).diff(x, 5) + 2*f(x).diff(x, 3) + f(x).diff(x) # These are equivalent: sol1 = Eq(f(x), C1 + (C2 + C3*x)*sin(x) + (C4 + C5*x)*cos(x)) sol2 = Eq(f(x), C1 + C2*(x*sin(x) + cos(x)) + C3*(-x*cos(x) + sin(x)) + C4*sin(x) + C5*cos(x)) sol1s = constant_renumber(sol1) sol2s = constant_renumber(sol2) assert checkodesol(eqn, sol1, order=2, solve_for_func=False) == (True, 0) assert checkodesol(eqn, sol2, order=2, solve_for_func=False) == (True, 0) assert dsolve(eqn, f(x)) in (sol1, sol1s) assert dsolve(eqn, f(x), hint='nth_order_reducible') in (sol2, sol2s) # In this case the reduced ODE has two distinct solutions eqn = f(x).diff(x, 2) - f(x).diff(x)**3 sol = [Eq(f(x), C2 - sqrt(2)*I*(C1 + x)*sqrt(1/(C1 + x))), Eq(f(x), C2 + sqrt(2)*I*(C1 + x)*sqrt(1/(C1 + x)))] sols = constant_renumber(sol) assert checkodesol(eqn, sol, order=2, solve_for_func=False) == [(True, 0), (True, 0)] assert dsolve(eqn, f(x)) in (sol, sols) assert dsolve(eqn, f(x), hint='nth_order_reducible') in (sol, sols) def test_nth_algebraic(): eqn = Eq(Derivative(f(x), x), Derivative(g(x), x)) sol = Eq(f(x), C1 + g(x)) assert checkodesol(eqn, sol, order=1, solve_for_func=False)[0] assert sol == dsolve(eqn, f(x), hint='nth_algebraic'), dsolve(eqn, f(x), hint='nth_algebraic') assert sol == dsolve(eqn, f(x)) eqn = (diff(f(x)) - x)*(diff(f(x)) + x) sol = [Eq(f(x), C1 - x**2/2), Eq(f(x), C1 + x**2/2)] assert checkodesol(eqn, sol, order=1, solve_for_func=False)[0] assert set(sol) == set(dsolve(eqn, f(x), hint='nth_algebraic')) assert set(sol) == set(dsolve(eqn, f(x))) eqn = (1 - sin(f(x))) * f(x).diff(x) sol = Eq(f(x), C1) assert checkodesol(eqn, sol, order=1, solve_for_func=False)[0] assert sol == dsolve(eqn, f(x), hint='nth_algebraic') assert sol == dsolve(eqn, f(x)) M, m, r, t = symbols('M m r t') phi = Function('phi') eqn = Eq(-M * phi(t).diff(t), Rational(3, 2) * m * r**2 * phi(t).diff(t) * phi(t).diff(t,t)) solns = [Eq(phi(t), C1), Eq(phi(t), C1 + C2*t - M*t**2/(3*m*r**2))] assert checkodesol(eqn, solns[0], order=2, solve_for_func=False)[0] assert checkodesol(eqn, solns[1], order=2, solve_for_func=False)[0] assert set(solns) == set(dsolve(eqn, phi(t), hint='nth_algebraic')) assert set(solns) == set(dsolve(eqn, phi(t))) eqn = f(x) * f(x).diff(x) * f(x).diff(x, x) sol = Eq(f(x), C1 + C2*x) assert checkodesol(eqn, sol, order=1, solve_for_func=False)[0] assert sol == dsolve(eqn, f(x), hint='nth_algebraic') assert sol == dsolve(eqn, f(x)) eqn = f(x) * f(x).diff(x) * f(x).diff(x, x) * (f(x) - 1) sol = Eq(f(x), C1 + C2*x) assert checkodesol(eqn, sol, order=1, solve_for_func=False)[0] assert sol == dsolve(eqn, f(x), hint='nth_algebraic') assert sol == dsolve(eqn, f(x)) eqn = f(x) * f(x).diff(x) * f(x).diff(x, x) * (f(x) - 1) * (f(x).diff(x) - x) solns = [Eq(f(x), C1 + x**2/2), Eq(f(x), C1 + C2*x)] assert checkodesol(eqn, solns[0], order=2, solve_for_func=False)[0] assert checkodesol(eqn, solns[1], order=2, solve_for_func=False)[0] assert set(solns) == set(dsolve(eqn, f(x), hint='nth_algebraic')) assert set(solns) == set(dsolve(eqn, f(x))) def test_nth_algebraic_issue15999(): eqn = f(x).diff(x) - C1 sol = Eq(f(x), C1*x + C2) # Correct solution assert checkodesol(eqn, sol, order=1, solve_for_func=False) == (True, 0) assert dsolve(eqn, f(x), hint='nth_algebraic') == sol assert dsolve(eqn, f(x)) == sol def test_nth_algebraic_redundant_solutions(): # This one has a redundant solution that should be removed eqn = f(x)*f(x).diff(x) soln = Eq(f(x), C1) assert checkodesol(eqn, soln, order=1, solve_for_func=False)[0] assert soln == dsolve(eqn, f(x), hint='nth_algebraic') assert soln == dsolve(eqn, f(x)) # This has two integral solutions and no algebraic solutions eqn = (diff(f(x)) - x)*(diff(f(x)) + x) sol = [Eq(f(x), C1 - x**2/2), Eq(f(x), C1 + x**2/2)] assert all(c[0] for c in checkodesol(eqn, sol, order=1, solve_for_func=False)) assert set(sol) == set(dsolve(eqn, f(x), hint='nth_algebraic')) assert set(sol) == set(dsolve(eqn, f(x))) eqn = f(x) + f(x)*f(x).diff(x) solns = [Eq(f(x), 0), Eq(f(x), C1 - x)] assert all(c[0] for c in checkodesol(eqn, solns, order=1, solve_for_func=False)) assert set(solns) == set(dsolve(eqn, f(x))) solns = [Eq(f(x), exp(x)), Eq(f(x), C1*exp(C2*x))] solns_final = _remove_redundant_solutions(eqn, solns, 2, x) assert solns_final == [Eq(f(x), C1*exp(C2*x))] # This one needs a substitution f' = g. eqn = -exp(x) + (x*Derivative(f(x), (x, 2)) + Derivative(f(x), x))/x sol = Eq(f(x), C1 + C2*log(x) + exp(x) - Ei(x)) assert checkodesol(eqn, sol, order=2, solve_for_func=False)[0] assert sol == dsolve(eqn, f(x)) # # These tests can be combined with the above test if they get fixed # so that dsolve actually works in all these cases. # # prep = True breaks this def test_nth_algebraic_noprep1(): eqn = Derivative(x*f(x), x, x, x) sol = Eq(f(x), (C1 + C2*x + C3*x**2) / x) assert checkodesol(eqn, sol, order=3, solve_for_func=False)[0] assert sol == dsolve(eqn, f(x), prep=False, hint='nth_algebraic') @XFAIL def test_nth_algebraic_prep1(): eqn = Derivative(x*f(x), x, x, x) sol = Eq(f(x), (C1 + C2*x + C3*x**2) / x) assert checkodesol(eqn, sol, order=3, solve_for_func=False)[0] assert sol == dsolve(eqn, f(x), prep=True, hint='nth_algebraic') assert sol == dsolve(eqn, f(x)) # prep = True breaks this def test_nth_algebraic_noprep2(): eqn = Eq(Derivative(x*Derivative(f(x), x), x)/x, exp(x)) sol = Eq(f(x), C1 + C2*log(x) + exp(x) - Ei(x)) assert checkodesol(eqn, sol, order=2, solve_for_func=False)[0] assert sol == dsolve(eqn, f(x), prep=False, hint='nth_algebraic') @XFAIL def test_nth_algebraic_prep2(): eqn = Eq(Derivative(x*Derivative(f(x), x), x)/x, exp(x)) sol = Eq(f(x), C1 + C2*log(x) + exp(x) - Ei(x)) assert checkodesol(eqn, sol, order=2, solve_for_func=False)[0] assert sol == dsolve(eqn, f(x), prep=True, hint='nth_algebraic') assert sol == dsolve(eqn, f(x)) # Needs to be a way to know how to combine derivatives in the expression def test_factoring_ode(): from sympy import Mul eqn = Derivative(x*f(x), x, x, x) + Derivative(f(x), x, x, x) # 2-arg Mul! soln = Eq(f(x), C1 + C2*x + C3/Mul(2, (x + 1), evaluate=False)) assert checkodesol(eqn, soln, order=2, solve_for_func=False)[0] assert soln == dsolve(eqn, f(x)) def test_issue_11542(): m = 96 g = 9.8 k = .2 f1 = g * m t = Symbol('t') v = Function('v') v_equation = dsolve(f1 - k * (v(t) ** 2) - m * Derivative(v(t)), 0) assert str(v_equation) == \ 'Eq(v(t), -68.585712797929/tanh(C1 - 0.142886901662352*t))' def test_issue_15913(): eq = -C1/x - 2*x*f(x) - f(x) + Derivative(f(x), x) sol = C2*exp(x**2 + x) + exp(x**2 + x)*Integral(C1*exp(-x**2 - x)/x, x) assert checkodesol(eq, sol) == (True, 0) sol = C1 + C2*exp(-x*y) eq = Derivative(y*f(x), x) + f(x).diff(x, 2) assert checkodesol(eq, sol, f(x)) == (True, 0) def test_issue_16146(): raises(ValueError, lambda: dsolve([f(x).diff(x), g(x).diff(x)], [f(x), g(x), h(x)])) raises(ValueError, lambda: dsolve([f(x).diff(x), g(x).diff(x)], [f(x)])) def test_dsolve_remove_redundant_solutions(): eq = (f(x)-2)*f(x).diff(x) sol = Eq(f(x), C1) assert dsolve(eq) == sol eq = (f(x)-sin(x))*(f(x).diff(x, 2)) sol = {Eq(f(x), C1 + C2*x), Eq(f(x), sin(x))} assert set(dsolve(eq)) == sol eq = (f(x)**2-2*f(x)+1)*f(x).diff(x, 3) sol = Eq(f(x), C1 + C2*x + C3*x**2) assert dsolve(eq) == sol def test_factorable(): # Unable to get coverage on this without explicit testing because _desolve # already handles Pow before we get there but that should be disabled in # future so that factorable gets the raw ODE. eq = f(x).diff(x)-1 assert _ode_factorable_match(eq**3, f(x), 1) == {'eqns':[eq], 'x0': 1} eq = f(x) + f(x)*f(x).diff(x) sols = [Eq(f(x), C1 - x), Eq(f(x), 0)] assert set(sols) == set(dsolve(eq, f(x), hint='factorable')) assert checkodesol(eq, sols) == 2*[(True, 0)] eq = f(x)*(f(x).diff(x)+f(x)*x+2) sols = [Eq(f(x), (C1 - sqrt(2)*sqrt(pi)*erfi(sqrt(2)*x/2)) *exp(-x**2/2)), Eq(f(x), 0)] assert set(sols) == set(dsolve(eq, f(x), hint='factorable')) assert checkodesol(eq, sols) == 2*[(True, 0)] eq = (f(x).diff(x)+f(x)*x**2)*(f(x).diff(x, 2) + x*f(x)) sols = [Eq(f(x), C1*airyai(-x) + C2*airybi(-x)), Eq(f(x), C1*exp(-x**3/3))] assert set(sols) == set(dsolve(eq, f(x), hint='factorable')) assert checkodesol(eq, sols[1]) == (True, 0) eq = (f(x).diff(x)+f(x)*x**2)*(f(x).diff(x, 2) + f(x)) sols = [Eq(f(x), C1*exp(-x**3/3)), Eq(f(x), C1*sin(x) + C2*cos(x))] assert set(sols) == set(dsolve(eq, f(x), hint='factorable')) assert checkodesol(eq, sols) == 2*[(True, 0)] eq = (f(x).diff(x)**2-1)*(f(x).diff(x)**2-4) sols = [Eq(f(x), C1 - x), Eq(f(x), C1 + x), Eq(f(x), C1 + 2*x), Eq(f(x), C1 - 2*x)] assert set(sols) == set(dsolve(eq, f(x), hint='factorable')) assert checkodesol(eq, sols) == 4*[(True, 0)] eq = (f(x).diff(x, 2)-exp(f(x)))*f(x).diff(x) sol = Eq(f(x), C1) assert sol == dsolve(eq, f(x), hint='factorable') assert checkodesol(eq, sol) == (True, 0) eq = (f(x).diff(x)**2-1)*(f(x)*f(x).diff(x)-1) sol = [Eq(f(x), C1 - x), Eq(f(x), -sqrt(C1 + 2*x)), Eq(f(x), sqrt(C1 + 2*x)), Eq(f(x), C1 + x)] assert set(sol) == set(dsolve(eq, f(x), hint='factorable')) assert checkodesol(eq, sol) == 4*[(True, 0)] eq = Derivative(f(x), x)**4 - 2*Derivative(f(x), x)**2 + 1 sol = [Eq(f(x), C1 - x), Eq(f(x), C1 + x)] assert set(sol) == set(dsolve(eq, f(x), hint='factorable')) assert checkodesol(eq, sol) == 2*[(True, 0)] eq = f(x)**2*Derivative(f(x), x)**6 - 2*f(x)**2*Derivative(f(x), x)**4 + f(x)**2*Derivative(f(x), x)**2 - 2*f(x)*Derivative(f(x), x)**5 + 4*f(x)*Derivative(f(x), x)**3 - 2*f(x)*Derivative(f(x), x) + Derivative(f(x), x)**4 - 2*Derivative(f(x), x)**2 + 1 sol = [Eq(f(x), C1 - x), Eq(f(x), -sqrt(C1 + 2*x)), Eq(f(x), sqrt(C1 + 2*x)), Eq(f(x), C1 + x)] assert set(sol) == set(dsolve(eq, f(x), hint='factorable')) assert checkodesol(eq, sol) == 4*[(True, 0)] eq = (f(x).diff(x, 2)-exp(f(x)))*(f(x).diff(x, 2)+exp(f(x))) raises(NotImplementedError, lambda: dsolve(eq, hint = 'factorable')) eq = x**4*f(x)**2 + 2*x**4*f(x)*Derivative(f(x), (x, 2)) + x**4*Derivative(f(x), (x, 2))**2 + 2*x**3*f(x)*Derivative(f(x), x) + 2*x**3*Derivative(f(x), x)*Derivative(f(x), (x, 2)) - 7*x**2*f(x)**2 - 7*x**2*f(x)*Derivative(f(x), (x, 2)) + x**2*Derivative(f(x), x)**2 - 7*x*f(x)*Derivative(f(x), x) + 12*f(x)**2 sol = [Eq(f(x), C1*besselj(2, x) + C2*bessely(2, x)), Eq(f(x), C1*besselj(sqrt(3), x) + C2*bessely(sqrt(3), x))] assert set(sol) == set(dsolve(eq, f(x), hint='factorable')) assert checkodesol(eq, sol) == 2*[(True, 0)] def test_issue_17322(): eq = (f(x).diff(x)-f(x)) * (f(x).diff(x)+f(x)) sol = [Eq(f(x), C1*exp(-x)), Eq(f(x), C1*exp(x))] assert set(sol) == set(dsolve(eq, hint='lie_group')) assert checkodesol(eq, sol) == 2*[(True, 0)] eq = f(x).diff(x)*(f(x).diff(x)+f(x)) sol = [Eq(f(x), C1), Eq(f(x), C1*exp(-x))] assert set(sol) == set(dsolve(eq, hint='lie_group')) assert checkodesol(eq, sol) == 2*[(True, 0)] def test_2nd_2F1_hypergeometric(): eq = x*(x-1)*f(x).diff(x, 2) + (S(3)/2 -2*x)*f(x).diff(x) + 2*f(x) sol = Eq(f(x), C1*x**(S(5)/2)*hyper((S(3)/2, S(1)/2), (S(7)/2,), x) + C2*hyper((-1, -2), (-S(3)/2,), x)) assert sol == dsolve(eq, hint='2nd_hypergeometric') assert checkodesol(eq, sol) == (True, 0) eq = x*(x-1)*f(x).diff(x, 2) + (S(7)/2*x)*f(x).diff(x) + f(x) sol = Eq(f(x), (C1*(1 - x)**(S(5)/2)*hyper((S(1)/2, 2), (S(7)/2,), 1 - x) + C2*hyper((-S(1)/2, -2), (-S(3)/2,), 1 - x))/(x - 1)**(S(5)/2)) assert sol == dsolve(eq, hint='2nd_hypergeometric') assert checkodesol(eq, sol) == (True, 0) eq = x*(x-1)*f(x).diff(x, 2) + (S(3)+ S(7)/2*x)*f(x).diff(x) + f(x) sol = Eq(f(x), (C1*(1 - x)**(S(11)/2)*hyper((S(1)/2, 2), (S(13)/2,), 1 - x) + C2*hyper((-S(7)/2, -5), (-S(9)/2,), 1 - x))/(x - 1)**(S(11)/2)) assert sol == dsolve(eq, hint='2nd_hypergeometric') assert checkodesol(eq, sol) == (True, 0) eq = x*(x-1)*f(x).diff(x, 2) + (-1+ S(7)/2*x)*f(x).diff(x) + f(x) sol = Eq(f(x), (C1 + C2*Integral(exp(Integral((1 - x/2)/(x*(x - 1)), x))/(1 - x/2)**2, x))*exp(Integral(1/(x - 1), x)/4)*exp(-Integral(7/(x - 1), x)/4)*hyper((S(1)/2, -1), (1,), x)) assert sol == dsolve(eq, hint='2nd_hypergeometric_Integral') assert checkodesol(eq, sol) == (True, 0) eq = -x**(S(5)/7)*(-416*x**(S(9)/7)/9 - 2385*x**(S(5)/7)/49 + S(298)*x/3)*f(x)/(196*(-x**(S(6)/7) + x)**2*(x**(S(6)/7) + x)**2) + Derivative(f(x), (x, 2)) sol = Eq(f(x), x**(S(45)/98)*(C1*x**(S(4)/49)*hyper((S(1)/3, -S(1)/2), (S(9)/7,), x**(S(2)/7)) + C2*hyper((S(1)/21, -S(11)/14), (S(5)/7,), x**(S(2)/7)))/(x**(S(2)/7) - 1)**(S(19)/84)) assert sol == dsolve(eq, hint='2nd_hypergeometric') # assert checkodesol(eq, sol) == (True, 0) #issue-https://github.com/sympy/sympy/issues/17702 def test_issue_15889(): eq = exp(f(x).diff(x))-f(x)**2 sol = Eq(Integral(1/log(y**2), (y, f(x))), C1 + x) assert str(sol.as_dummy()) == str(dsolve(eq).as_dummy()) assert checkodesol(eq, sol) == (True, 0) eq = f(x).diff(x)**2 - f(x)**3 sol = Eq(f(x), 4/(C1**2 - 2*C1*x + x**2)) assert sol == dsolve(eq) assert checkodesol(eq, sol) == (True, 0) eq = f(x).diff(x)**2 - f(x) sol = Eq(f(x), C1**2/4 - C1*x/2 + x**2/4) assert sol == dsolve(eq) assert checkodesol(eq, sol) == (True, 0) eq = f(x).diff(x)**2 - f(x)**2 sol = [Eq(f(x), C1*exp(x)), Eq(f(x), C1*exp(-x))] assert sol == dsolve(eq) assert checkodesol(eq, sol) == 2*[(True, 0)] eq = f(x).diff(x)**2 - f(x)**3 sol = Eq(f(x), 4/(C1**2 + 2*C1*x + x**2)) assert sol == dsolve(eq, hint='lie_group') assert checkodesol(eq, sol) == (True, 0) def test_issue_5096(): eq = f(x).diff(x, x) + f(x) - x*sin(x - 2) sol = Eq(f(x), C1*sin(x) + C2*cos(x) - x**2*cos(x - 2)/4 + x*sin(x - 2)/4) assert sol == dsolve(eq, hint='nth_linear_constant_coeff_undetermined_coefficients') assert checkodesol(eq, sol) == (True, 0) eq = f(x).diff(x, 2) + f(x) - x**4*sin(x-1) sol = Eq(f(x), C1*sin(x) + C2*cos(x) - x**5*cos(x - 1)/10 + x**4*sin(x - 1)/4 + x**3*cos(x - 1)/2 - 3*x**2*sin(x - 1)/4 - 3*x*cos(x - 1)/4) assert sol == dsolve(eq, hint='nth_linear_constant_coeff_undetermined_coefficients') assert checkodesol(eq, sol) == (True, 0) eq = f(x).diff(x, 2) - f(x) - exp(x - 1) sol = Eq(f(x), C1*exp(-x) + C2*exp(x) + x*exp(x - 1)/2) assert sol == dsolve(eq, hint='nth_linear_constant_coeff_undetermined_coefficients') assert checkodesol(eq, sol) == (True, 0) eq = f(x).diff(x, 2)+f(x)-(sin(x-2)+1) sol = Eq(f(x), C1*sin(x) + C2*cos(x) - x*cos(x - 2)/2 + 1) assert sol == dsolve(eq, hint='nth_linear_constant_coeff_undetermined_coefficients') assert checkodesol(eq, sol) == (True, 0) eq = 2*x**2*f(x).diff(x, 2) + f(x) + sqrt(2*x)*sin(log(2*x)/2) sol = Eq(f(x), sqrt(x)*(C1*sin(log(x)/2) + C2*cos(log(x)/2) + sqrt(2)*log(x)*cos(log(2*x)/2)/2)) assert sol == dsolve(eq, hint='nth_linear_euler_eq_nonhomogeneous_undetermined_coefficients') assert checkodesol(eq, sol) == (True, 0) eq = 2*x**2*f(x).diff(x, 2) + f(x) + sin(log(2*x)/2) sol = Eq(f(x), C1*sqrt(x)*sin(log(x)/2) + C2*sqrt(x)*cos(log(x)/2) - 2*sin(log(2*x)/2)/5 - 4*cos(log(2*x)/2)/5) assert sol == dsolve(eq, hint='nth_linear_euler_eq_nonhomogeneous_undetermined_coefficients') assert checkodesol(eq, sol) == (True, 0) def test_issue_15996(): eq = f(x).diff(x, 5) + 2*f(x).diff(x, 3) + f(x).diff(x) - 2*x - exp(I*x) sol = Eq(f(x), C1 + x**2 + (C2 - x**2/8 + x*(C3 + 3*exp(I*x)/2 + 3*exp(-I*x)/2) + 5*exp(2*I*x)/16 + 2*I*exp(I*x) - 2*I*exp(-I*x))*sin(x) + (C4 + I*x**2/8 + x*(C5 + 3*I*exp(I*x)/2 - 3*I*exp(-I*x)/2) + 5*I*exp(2*I*x)/16 - 2*exp(I*x) - 2*exp(-I*x))*cos(x) - I*exp(I*x)) assert sol == dsolve(eq, hint='nth_linear_constant_coeff_variation_of_parameters') assert checkodesol(eq, sol) == (True, 0) eq = f(x).diff(x, 5) + 2*f(x).diff(x, 3) + f(x).diff(x) - exp(I*x) sol = Eq(f(x), C1 + (C2 + C3*x - x**2/8 + 5*exp(2*I*x)/16)*sin(x) + (C4 + C5*x + I*x**2/8 + 5*I*exp(2*I*x)/16)*cos(x) - I*exp(I*x)) assert sol == dsolve(eq, hint='nth_linear_constant_coeff_variation_of_parameters') assert checkodesol(eq, sol) == (True, 0) def test_issue_18408(): eq = f(x).diff(x, 3) - f(x).diff(x) - sinh(x) sol = Eq(f(x), C1 + C2*exp(-x) + C3*exp(x) + x*sinh(x)/2) assert sol == dsolve(eq, hint='nth_linear_constant_coeff_undetermined_coefficients') assert checkodesol(eq, sol) == (True, 0) eq = f(x).diff(x, 2) - 49*f(x) - sinh(3*x) sol = Eq(f(x), C1*exp(-7*x) + C2*exp(7*x) - sinh(3*x)/40) assert sol == dsolve(eq, hint='nth_linear_constant_coeff_undetermined_coefficients') assert checkodesol(eq, sol) == (True, 0) eq = f(x).diff(x, 3) - f(x).diff(x) - sinh(x) - exp(x) sol = Eq(f(x), C1 + C3*exp(-x) + x*sinh(x)/2 + (C2 + x/2)*exp(x)) assert sol == dsolve(eq, hint='nth_linear_constant_coeff_undetermined_coefficients') assert checkodesol(eq, sol) == (True, 0)
8c80aaeb4632a60129460e93316aa590ebb4cfe51df379f6fe1f5cf203a55b92
from sympy import (cos, Derivative, diff, Eq, erf, erfi, exp, Function, I, Integral, log, pi, Rational, sin, sqrt, Symbol, symbols, Ei) from sympy.solvers.ode.subscheck import checkodesol, checksysodesol from sympy.functions import besselj, bessely from sympy.testing.pytest import raises, slow C0, C1, C2, C3, C4 = symbols('C0:5') u, x, y, z = symbols('u,x:z', real=True) f = Function('f') g = Function('g') h = Function('h') @slow def test_checkodesol(): # For the most part, checkodesol is well tested in the tests below. # These tests only handle cases not checked below. raises(ValueError, lambda: checkodesol(f(x, y).diff(x), Eq(f(x, y), x))) raises(ValueError, lambda: checkodesol(f(x).diff(x), Eq(f(x, y), x), f(x, y))) assert checkodesol(f(x).diff(x), Eq(f(x, y), x)) == \ (False, -f(x).diff(x) + f(x, y).diff(x) - 1) assert checkodesol(f(x).diff(x), Eq(f(x), x)) is not True assert checkodesol(f(x).diff(x), Eq(f(x), x)) == (False, 1) sol1 = Eq(f(x)**5 + 11*f(x) - 2*f(x) + x, 0) assert checkodesol(diff(sol1.lhs, x), sol1) == (True, 0) assert checkodesol(diff(sol1.lhs, x)*exp(f(x)), sol1) == (True, 0) assert checkodesol(diff(sol1.lhs, x, 2), sol1) == (True, 0) assert checkodesol(diff(sol1.lhs, x, 2)*exp(f(x)), sol1) == (True, 0) assert checkodesol(diff(sol1.lhs, x, 3), sol1) == (True, 0) assert checkodesol(diff(sol1.lhs, x, 3)*exp(f(x)), sol1) == (True, 0) assert checkodesol(diff(sol1.lhs, x, 3), Eq(f(x), x*log(x))) == \ (False, 60*x**4*((log(x) + 1)**2 + log(x))*( log(x) + 1)*log(x)**2 - 5*x**4*log(x)**4 - 9) assert checkodesol(diff(exp(f(x)) + x, x)*x, Eq(exp(f(x)) + x, 0)) == \ (True, 0) assert checkodesol(diff(exp(f(x)) + x, x)*x, Eq(exp(f(x)) + x, 0), solve_for_func=False) == (True, 0) assert checkodesol(f(x).diff(x, 2), [Eq(f(x), C1 + C2*x), Eq(f(x), C2 + C1*x), Eq(f(x), C1*x + C2*x**2)]) == \ [(True, 0), (True, 0), (False, C2)] assert checkodesol(f(x).diff(x, 2), set([Eq(f(x), C1 + C2*x), Eq(f(x), C2 + C1*x), Eq(f(x), C1*x + C2*x**2)])) == \ set([(True, 0), (True, 0), (False, C2)]) assert checkodesol(f(x).diff(x) - 1/f(x)/2, Eq(f(x)**2, x)) == \ [(True, 0), (True, 0)] assert checkodesol(f(x).diff(x) - f(x), Eq(C1*exp(x), f(x))) == (True, 0) # Based on test_1st_homogeneous_coeff_ode2_eq3sol. Make sure that # checkodesol tries back substituting f(x) when it can. eq3 = x*exp(f(x)/x) + f(x) - x*f(x).diff(x) sol3 = Eq(f(x), log(log(C1/x)**(-x))) assert not checkodesol(eq3, sol3)[1].has(f(x)) # This case was failing intermittently depending on hash-seed: eqn = Eq(Derivative(x*Derivative(f(x), x), x)/x, exp(x)) sol = Eq(f(x), C1 + C2*log(x) + exp(x) - Ei(x)) assert checkodesol(eqn, sol, order=2, solve_for_func=False)[0] eq = x**2*(f(x).diff(x, 2)) + x*(f(x).diff(x)) + (2*x**2 +25)*f(x) sol = Eq(f(x), C1*besselj(5*I, sqrt(2)*x) + C2*bessely(5*I, sqrt(2)*x)) assert checkodesol(eq, sol) == (True, 0) def test_checksysodesol(): x, y, z = symbols('x, y, z', cls=Function) t = Symbol('t') eq = (Eq(diff(x(t),t), 9*y(t)), Eq(diff(y(t),t), 12*x(t))) sol = [Eq(x(t), 9*C1*exp(-6*sqrt(3)*t) + 9*C2*exp(6*sqrt(3)*t)), \ Eq(y(t), -6*sqrt(3)*C1*exp(-6*sqrt(3)*t) + 6*sqrt(3)*C2*exp(6*sqrt(3)*t))] assert checksysodesol(eq, sol) == (True, [0, 0]) eq = (Eq(diff(x(t),t), 2*x(t) + 4*y(t)), Eq(diff(y(t),t), 12*x(t) + 41*y(t))) sol = [Eq(x(t), 4*C1*exp(t*(-sqrt(1713)/2 + Rational(43, 2))) + 4*C2*exp(t*(sqrt(1713)/2 + \ Rational(43, 2)))), Eq(y(t), C1*(-sqrt(1713)/2 + Rational(39, 2))*exp(t*(-sqrt(1713)/2 + \ Rational(43, 2))) + C2*(Rational(39, 2) + sqrt(1713)/2)*exp(t*(sqrt(1713)/2 + Rational(43, 2))))] assert checksysodesol(eq, sol) == (True, [0, 0]) eq = (Eq(diff(x(t),t), x(t) + y(t)), Eq(diff(y(t),t), -2*x(t) + 2*y(t))) sol = [Eq(x(t), (C1*sin(sqrt(7)*t/2) + C2*cos(sqrt(7)*t/2))*exp(t*Rational(3, 2))), \ Eq(y(t), ((C1/2 - sqrt(7)*C2/2)*sin(sqrt(7)*t/2) + (sqrt(7)*C1/2 + \ C2/2)*cos(sqrt(7)*t/2))*exp(t*Rational(3, 2)))] assert checksysodesol(eq, sol) == (True, [0, 0]) eq = (Eq(diff(x(t),t), x(t) + y(t) + 9), Eq(diff(y(t),t), 2*x(t) + 5*y(t) + 23)) sol = [Eq(x(t), C1*exp(t*(-sqrt(6) + 3)) + C2*exp(t*(sqrt(6) + 3)) - \ Rational(22, 3)), Eq(y(t), C1*(-sqrt(6) + 2)*exp(t*(-sqrt(6) + 3)) + C2*(2 + \ sqrt(6))*exp(t*(sqrt(6) + 3)) - Rational(5, 3))] assert checksysodesol(eq, sol) == (True, [0, 0]) eq = (Eq(diff(x(t),t), x(t) + y(t) + 81), Eq(diff(y(t),t), -2*x(t) + y(t) + 23)) sol = [Eq(x(t), (C1*sin(sqrt(2)*t) + C2*cos(sqrt(2)*t))*exp(t) - Rational(58, 3)), \ Eq(y(t), (sqrt(2)*C1*cos(sqrt(2)*t) - sqrt(2)*C2*sin(sqrt(2)*t))*exp(t) - Rational(185, 3))] assert checksysodesol(eq, sol) == (True, [0, 0]) eq = (Eq(diff(x(t),t), 5*t*x(t) + 2*y(t)), Eq(diff(y(t),t), 2*x(t) + 5*t*y(t))) sol = [Eq(x(t), (C1*exp((Integral(2, t).doit())) + C2*exp(-(Integral(2, t)).doit()))*\ exp((Integral(5*t, t)).doit())), Eq(y(t), (C1*exp((Integral(2, t)).doit()) - \ C2*exp(-(Integral(2, t)).doit()))*exp((Integral(5*t, t)).doit()))] assert checksysodesol(eq, sol) == (True, [0, 0]) eq = (Eq(diff(x(t),t), 5*t*x(t) + t**2*y(t)), Eq(diff(y(t),t), -t**2*x(t) + 5*t*y(t))) sol = [Eq(x(t), (C1*cos((Integral(t**2, t)).doit()) + C2*sin((Integral(t**2, t)).doit()))*\ exp((Integral(5*t, t)).doit())), Eq(y(t), (-C1*sin((Integral(t**2, t)).doit()) + \ C2*cos((Integral(t**2, t)).doit()))*exp((Integral(5*t, t)).doit()))] assert checksysodesol(eq, sol) == (True, [0, 0]) eq = (Eq(diff(x(t),t), 5*t*x(t) + t**2*y(t)), Eq(diff(y(t),t), -t**2*x(t) + (5*t+9*t**2)*y(t))) sol = [Eq(x(t), (C1*exp((-sqrt(77)/2 + Rational(9, 2))*(Integral(t**2, t)).doit()) + \ C2*exp((sqrt(77)/2 + Rational(9, 2))*(Integral(t**2, t)).doit()))*exp((Integral(5*t, t)).doit())), \ Eq(y(t), (C1*(-sqrt(77)/2 + Rational(9, 2))*exp((-sqrt(77)/2 + Rational(9, 2))*(Integral(t**2, t)).doit()) + \ C2*(sqrt(77)/2 + Rational(9, 2))*exp((sqrt(77)/2 + Rational(9, 2))*(Integral(t**2, t)).doit()))*exp((Integral(5*t, t)).doit()))] assert checksysodesol(eq, sol) == (True, [0, 0]) eq = (Eq(diff(x(t),t,t), 5*x(t) + 43*y(t)), Eq(diff(y(t),t,t), x(t) + 9*y(t))) root0 = -sqrt(-sqrt(47) + 7) root1 = sqrt(-sqrt(47) + 7) root2 = -sqrt(sqrt(47) + 7) root3 = sqrt(sqrt(47) + 7) sol = [Eq(x(t), 43*C1*exp(t*root0) + 43*C2*exp(t*root1) + 43*C3*exp(t*root2) + 43*C4*exp(t*root3)), \ Eq(y(t), C1*(root0**2 - 5)*exp(t*root0) + C2*(root1**2 - 5)*exp(t*root1) + \ C3*(root2**2 - 5)*exp(t*root2) + C4*(root3**2 - 5)*exp(t*root3))] assert checksysodesol(eq, sol) == (True, [0, 0]) eq = (Eq(diff(x(t),t,t), 8*x(t)+3*y(t)+31), Eq(diff(y(t),t,t), 9*x(t)+7*y(t)+12)) root0 = -sqrt(-sqrt(109)/2 + Rational(15, 2)) root1 = sqrt(-sqrt(109)/2 + Rational(15, 2)) root2 = -sqrt(sqrt(109)/2 + Rational(15, 2)) root3 = sqrt(sqrt(109)/2 + Rational(15, 2)) sol = [Eq(x(t), 3*C1*exp(t*root0) + 3*C2*exp(t*root1) + 3*C3*exp(t*root2) + 3*C4*exp(t*root3) - Rational(181, 29)), \ Eq(y(t), C1*(root0**2 - 8)*exp(t*root0) + C2*(root1**2 - 8)*exp(t*root1) + \ C3*(root2**2 - 8)*exp(t*root2) + C4*(root3**2 - 8)*exp(t*root3) + Rational(183, 29))] assert checksysodesol(eq, sol) == (True, [0, 0]) eq = (Eq(diff(x(t),t,t) - 9*diff(y(t),t) + 7*x(t),0), Eq(diff(y(t),t,t) + 9*diff(x(t),t) + 7*y(t),0)) sol = [Eq(x(t), C1*cos(t*(Rational(9, 2) + sqrt(109)/2)) + C2*sin(t*(Rational(9, 2) + sqrt(109)/2)) + \ C3*cos(t*(-sqrt(109)/2 + Rational(9, 2))) + C4*sin(t*(-sqrt(109)/2 + Rational(9, 2)))), Eq(y(t), -C1*sin(t*(Rational(9, 2) + sqrt(109)/2)) \ + C2*cos(t*(Rational(9, 2) + sqrt(109)/2)) - C3*sin(t*(-sqrt(109)/2 + Rational(9, 2))) + C4*cos(t*(-sqrt(109)/2 + Rational(9, 2))))] assert checksysodesol(eq, sol) == (True, [0, 0]) eq = (Eq(diff(x(t),t,t), 9*t*diff(y(t),t)-9*y(t)), Eq(diff(y(t),t,t),7*t*diff(x(t),t)-7*x(t))) I1 = sqrt(6)*7**Rational(1, 4)*sqrt(pi)*erfi(sqrt(6)*7**Rational(1, 4)*t/2)/2 - exp(3*sqrt(7)*t**2/2)/t I2 = -sqrt(6)*7**Rational(1, 4)*sqrt(pi)*erf(sqrt(6)*7**Rational(1, 4)*t/2)/2 - exp(-3*sqrt(7)*t**2/2)/t sol = [Eq(x(t), C3*t + t*(9*C1*I1 + 9*C2*I2)), Eq(y(t), C4*t + t*(3*sqrt(7)*C1*I1 - 3*sqrt(7)*C2*I2))] assert checksysodesol(eq, sol) == (True, [0, 0]) eq = (Eq(diff(x(t),t), 21*x(t)), Eq(diff(y(t),t), 17*x(t)+3*y(t)), Eq(diff(z(t),t), 5*x(t)+7*y(t)+9*z(t))) sol = [Eq(x(t), C1*exp(21*t)), Eq(y(t), 17*C1*exp(21*t)/18 + C2*exp(3*t)), \ Eq(z(t), 209*C1*exp(21*t)/216 - 7*C2*exp(3*t)/6 + C3*exp(9*t))] assert checksysodesol(eq, sol) == (True, [0, 0, 0]) eq = (Eq(diff(x(t),t),3*y(t)-11*z(t)),Eq(diff(y(t),t),7*z(t)-3*x(t)),Eq(diff(z(t),t),11*x(t)-7*y(t))) sol = [Eq(x(t), 7*C0 + sqrt(179)*C1*cos(sqrt(179)*t) + (77*C1/3 + 130*C2/3)*sin(sqrt(179)*t)), \ Eq(y(t), 11*C0 + sqrt(179)*C2*cos(sqrt(179)*t) + (-58*C1/3 - 77*C2/3)*sin(sqrt(179)*t)), \ Eq(z(t), 3*C0 + sqrt(179)*(-7*C1/3 - 11*C2/3)*cos(sqrt(179)*t) + (11*C1 - 7*C2)*sin(sqrt(179)*t))] assert checksysodesol(eq, sol) == (True, [0, 0, 0]) eq = (Eq(3*diff(x(t),t),4*5*(y(t)-z(t))),Eq(4*diff(y(t),t),3*5*(z(t)-x(t))),Eq(5*diff(z(t),t),3*4*(x(t)-y(t)))) sol = [Eq(x(t), C0 + 5*sqrt(2)*C1*cos(5*sqrt(2)*t) + (12*C1/5 + 164*C2/15)*sin(5*sqrt(2)*t)), \ Eq(y(t), C0 + 5*sqrt(2)*C2*cos(5*sqrt(2)*t) + (-51*C1/10 - 12*C2/5)*sin(5*sqrt(2)*t)), \ Eq(z(t), C0 + 5*sqrt(2)*(-9*C1/25 - 16*C2/25)*cos(5*sqrt(2)*t) + (12*C1/5 - 12*C2/5)*sin(5*sqrt(2)*t))] assert checksysodesol(eq, sol) == (True, [0, 0, 0]) eq = (Eq(diff(x(t),t),4*x(t) - z(t)),Eq(diff(y(t),t),2*x(t)+2*y(t)-z(t)),Eq(diff(z(t),t),3*x(t)+y(t))) sol = [Eq(x(t), C1*exp(2*t) + C2*t*exp(2*t) + C2*exp(2*t) + C3*t**2*exp(2*t)/2 + C3*t*exp(2*t) + C3*exp(2*t)), \ Eq(y(t), C1*exp(2*t) + C2*t*exp(2*t) + C2*exp(2*t) + C3*t**2*exp(2*t)/2 + C3*t*exp(2*t)), \ Eq(z(t), 2*C1*exp(2*t) + 2*C2*t*exp(2*t) + C2*exp(2*t) + C3*t**2*exp(2*t) + C3*t*exp(2*t) + C3*exp(2*t))] assert checksysodesol(eq, sol) == (True, [0, 0, 0]) eq = (Eq(diff(x(t),t),4*x(t) - y(t) - 2*z(t)),Eq(diff(y(t),t),2*x(t) + y(t)- 2*z(t)),Eq(diff(z(t),t),5*x(t)-3*z(t))) sol = [Eq(x(t), C1*exp(2*t) + C2*(-sin(t) + 3*cos(t)) + C3*(3*sin(t) + cos(t))), \ Eq(y(t), C2*(-sin(t) + 3*cos(t)) + C3*(3*sin(t) + cos(t))), Eq(z(t), C1*exp(2*t) + 5*C2*cos(t) + 5*C3*sin(t))] assert checksysodesol(eq, sol) == (True, [0, 0, 0]) eq = (Eq(diff(x(t),t),x(t)*y(t)**3), Eq(diff(y(t),t),y(t)**5)) sol = [Eq(x(t), C1*exp((-1/(4*C2 + 4*t))**(Rational(-1, 4)))), Eq(y(t), -(-1/(4*C2 + 4*t))**Rational(1, 4)), \ Eq(x(t), C1*exp(-1/(-1/(4*C2 + 4*t))**Rational(1, 4))), Eq(y(t), (-1/(4*C2 + 4*t))**Rational(1, 4)), \ Eq(x(t), C1*exp(-I/(-1/(4*C2 + 4*t))**Rational(1, 4))), Eq(y(t), -I*(-1/(4*C2 + 4*t))**Rational(1, 4)), \ Eq(x(t), C1*exp(I/(-1/(4*C2 + 4*t))**Rational(1, 4))), Eq(y(t), I*(-1/(4*C2 + 4*t))**Rational(1, 4))] assert checksysodesol(eq, sol) == (True, [0, 0]) eq = (Eq(diff(x(t),t), exp(3*x(t))*y(t)**3),Eq(diff(y(t),t), y(t)**5)) sol = [Eq(x(t), -log(C1 - 3/(-1/(4*C2 + 4*t))**Rational(1, 4))/3), Eq(y(t), -(-1/(4*C2 + 4*t))**Rational(1, 4)), \ Eq(x(t), -log(C1 + 3/(-1/(4*C2 + 4*t))**Rational(1, 4))/3), Eq(y(t), (-1/(4*C2 + 4*t))**Rational(1, 4)), \ Eq(x(t), -log(C1 + 3*I/(-1/(4*C2 + 4*t))**Rational(1, 4))/3), Eq(y(t), -I*(-1/(4*C2 + 4*t))**Rational(1, 4)), \ Eq(x(t), -log(C1 - 3*I/(-1/(4*C2 + 4*t))**Rational(1, 4))/3), Eq(y(t), I*(-1/(4*C2 + 4*t))**Rational(1, 4))] assert checksysodesol(eq, sol) == (True, [0, 0]) eq = (Eq(x(t),t*diff(x(t),t)+diff(x(t),t)*diff(y(t),t)), Eq(y(t),t*diff(y(t),t)+diff(y(t),t)**2)) sol = set([Eq(x(t), C1*C2 + C1*t), Eq(y(t), C2**2 + C2*t)]) assert checksysodesol(eq, sol) == (True, [0, 0])
f16ae8c1e2bc802f432ab32d31f19e84814fc57d5609331e05c02fd97e10efe0
from sympy import sqrt, pi, E, exp, Rational from sympy.core import S, symbols, I from sympy.discrete.convolutions import ( convolution, convolution_fft, convolution_ntt, convolution_fwht, convolution_subset, covering_product, intersecting_product) from sympy.testing.pytest import raises from sympy.abc import x, y def test_convolution(): # fft a = [1, Rational(5, 3), sqrt(3), Rational(7, 5)] b = [9, 5, 5, 4, 3, 2] c = [3, 5, 3, 7, 8] d = [1422, 6572, 3213, 5552] assert convolution(a, b) == convolution_fft(a, b) assert convolution(a, b, dps=9) == convolution_fft(a, b, dps=9) assert convolution(a, d, dps=7) == convolution_fft(d, a, dps=7) assert convolution(a, d[1:], dps=3) == convolution_fft(d[1:], a, dps=3) # prime moduli of the form (m*2**k + 1), sequence length # should be a divisor of 2**k p = 7*17*2**23 + 1 q = 19*2**10 + 1 # ntt assert convolution(d, b, prime=q) == convolution_ntt(b, d, prime=q) assert convolution(c, b, prime=p) == convolution_ntt(b, c, prime=p) assert convolution(d, c, prime=p) == convolution_ntt(c, d, prime=p) raises(TypeError, lambda: convolution(b, d, dps=5, prime=q)) raises(TypeError, lambda: convolution(b, d, dps=6, prime=q)) # fwht assert convolution(a, b, dyadic=True) == convolution_fwht(a, b) assert convolution(a, b, dyadic=False) == convolution(a, b) raises(TypeError, lambda: convolution(b, d, dps=2, dyadic=True)) raises(TypeError, lambda: convolution(b, d, prime=p, dyadic=True)) raises(TypeError, lambda: convolution(a, b, dps=2, dyadic=True)) raises(TypeError, lambda: convolution(b, c, prime=p, dyadic=True)) # subset assert convolution(a, b, subset=True) == convolution_subset(a, b) == \ convolution(a, b, subset=True, dyadic=False) == \ convolution(a, b, subset=True) assert convolution(a, b, subset=False) == convolution(a, b) raises(TypeError, lambda: convolution(a, b, subset=True, dyadic=True)) raises(TypeError, lambda: convolution(c, d, subset=True, dps=6)) raises(TypeError, lambda: convolution(a, c, subset=True, prime=q)) def test_cyclic_convolution(): # fft a = [1, Rational(5, 3), sqrt(3), Rational(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 = [Rational(1, 3), Rational(7, 3), Rational(5, 9), Rational(2, 7), Rational(5, 8)] b = [Rational(3, 5), Rational(4, 7), Rational(7, 8), Rational(8, 9)] assert convolution(a, b, cycle=0) == \ convolution(a, b, cycle=len(a) + len(b) - 1) assert convolution(a, b, cycle=4) == [Rational(87277, 26460), Rational(30521, 11340), Rational(11125, 4032), Rational(3653, 1080)] assert convolution(a, b, cycle=6) == [Rational(20177, 20160), Rational(676, 315), Rational(47, 24), Rational(3053, 1080), Rational(16397, 5292), Rational(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] raises(ValueError, lambda: convolution([1, 2, 3], [4, 5, 6], cycle=-1)) def test_convolution_fft(): assert all(convolution_fft([], x, dps=y) == [] for x in ([], [1]) for y in (None, 3)) assert convolution_fft([1, 2, 3], [4, 5, 6]) == [4, 13, 28, 27, 18] assert convolution_fft([1], [5, 6, 7]) == [5, 6, 7] assert convolution_fft([1, 3], [5, 6, 7]) == [5, 21, 25, 21] assert convolution_fft([1 + 2*I], [2 + 3*I]) == [-4 + 7*I] assert convolution_fft([1 + 2*I, 3 + 4*I, 5 + Rational(3, 5)*I], [Rational(2, 5) + Rational(4, 7)*I]) == \ [Rational(-26, 35) + I*Rational(48, 35), Rational(-38, 35) + I*Rational(116, 35), Rational(58, 35) + I*Rational(542, 175)] assert convolution_fft([Rational(3, 4), Rational(5, 6)], [Rational(7, 8), Rational(1, 3), Rational(2, 5)]) == \ [Rational(21, 32), Rational(47, 48), Rational(26, 45), Rational(1, 3)] assert convolution_fft([Rational(1, 9), Rational(2, 3), Rational(3, 5)], [Rational(2, 5), Rational(3, 7), Rational(4, 9)]) == \ [Rational(2, 45), Rational(11, 35), Rational(8152, 14175), Rational(523, 945), Rational(4, 15)] assert convolution_fft([pi, E, sqrt(2)], [sqrt(3), 1/pi, 1/E]) == \ [sqrt(3)*pi, 1 + sqrt(3)*E, E/pi + pi*exp(-1) + sqrt(6), sqrt(2)/pi + 1, sqrt(2)*exp(-1)] assert convolution_fft([2321, 33123], [5321, 6321, 71323]) == \ [12350041, 190918524, 374911166, 2362431729] assert convolution_fft([312313, 31278232], [32139631, 319631]) == \ [10037624576503, 1005370659728895, 9997492572392] raises(TypeError, lambda: convolution_fft(x, y)) raises(ValueError, lambda: convolution_fft([x, y], [y, x])) def test_convolution_ntt(): # prime moduli of the form (m*2**k + 1), sequence length # should be a divisor of 2**k p = 7*17*2**23 + 1 q = 19*2**10 + 1 r = 2*500000003 + 1 # only for sequences of length 1 or 2 # s = 2*3*5*7 # composite modulus assert all(convolution_ntt([], x, prime=y) == [] for x in ([], [1]) for y in (p, q, r)) assert convolution_ntt([2], [3], r) == [6] assert convolution_ntt([2, 3], [4], r) == [8, 12] assert convolution_ntt([32121, 42144, 4214, 4241], [32132, 3232, 87242], p) == [33867619, 459741727, 79180879, 831885249, 381344700, 369993322] assert convolution_ntt([121913, 3171831, 31888131, 12], [17882, 21292, 29921, 312], q) == \ [8158, 3065, 3682, 7090, 1239, 2232, 3744] assert convolution_ntt([12, 19, 21, 98, 67], [2, 6, 7, 8, 9], p) == \ convolution_ntt([12, 19, 21, 98, 67], [2, 6, 7, 8, 9], q) assert convolution_ntt([12, 19, 21, 98, 67], [21, 76, 17, 78, 69], p) == \ convolution_ntt([12, 19, 21, 98, 67], [21, 76, 17, 78, 69], q) raises(ValueError, lambda: convolution_ntt([2, 3], [4, 5], r)) raises(ValueError, lambda: convolution_ntt([x, y], [y, x], q)) raises(TypeError, lambda: convolution_ntt(x, y, p)) def test_convolution_fwht(): assert convolution_fwht([], []) == [] assert convolution_fwht([], [1]) == [] assert convolution_fwht([1, 2, 3], [4, 5, 6]) == [32, 13, 18, 27] assert convolution_fwht([Rational(5, 7), Rational(6, 8), Rational(7, 3)], [2, 4, Rational(6, 7)]) == \ [Rational(45, 7), Rational(61, 14), Rational(776, 147), Rational(419, 42)] a = [1, Rational(5, 3), sqrt(3), Rational(7, 5), 4 + 5*I] b = [94, 51, 53, 45, 31, 27, 13] c = [3 + 4*I, 5 + 7*I, 3, Rational(7, 6), 8] assert convolution_fwht(a, b) == [53*sqrt(3) + 366 + 155*I, 45*sqrt(3) + Rational(5848, 15) + 135*I, 94*sqrt(3) + Rational(1257, 5) + 65*I, 51*sqrt(3) + Rational(3974, 15), 13*sqrt(3) + 452 + 470*I, Rational(4513, 15) + 255*I, 31*sqrt(3) + Rational(1314, 5) + 265*I, 27*sqrt(3) + Rational(3676, 15) + 225*I] assert convolution_fwht(b, c) == [Rational(1993, 2) + 733*I, Rational(6215, 6) + 862*I, Rational(1659, 2) + 527*I, Rational(1988, 3) + 551*I, 1019 + 313*I, Rational(3955, 6) + 325*I, Rational(1175, 2) + 52*I, Rational(3253, 6) + 91*I] assert convolution_fwht(a[3:], c) == [Rational(-54, 5) + I*Rational(293, 5), -1 + I*Rational(204, 5), Rational(133, 15) + I*Rational(35, 6), Rational(409, 30) + 15*I, Rational(56, 5), 32 + 40*I, 0, 0] u, v, w, x, y, z = symbols('u v w x y z') assert convolution_fwht([u, v], [x, y]) == [u*x + v*y, u*y + v*x] assert convolution_fwht([u, v, w], [x, y]) == \ [u*x + v*y, u*y + v*x, w*x, w*y] assert convolution_fwht([u, v, w], [x, y, z]) == \ [u*x + v*y + w*z, u*y + v*x, u*z + w*x, v*z + w*y] raises(TypeError, lambda: convolution_fwht(x, y)) raises(TypeError, lambda: convolution_fwht(x*y, u + v)) def test_convolution_subset(): assert convolution_subset([], []) == [] assert convolution_subset([], [Rational(1, 3)]) == [] assert convolution_subset([6 + I*Rational(3, 7)], [Rational(2, 3)]) == [4 + I*Rational(2, 7)] a = [1, Rational(5, 3), sqrt(3), 4 + 5*I] b = [64, 71, 55, 47, 33, 29, 15] c = [3 + I*Rational(2, 3), 5 + 7*I, 7, Rational(7, 5), 9] assert convolution_subset(a, b) == [64, Rational(533, 3), 55 + 64*sqrt(3), 71*sqrt(3) + Rational(1184, 3) + 320*I, 33, 84, 15 + 33*sqrt(3), 29*sqrt(3) + 157 + 165*I] assert convolution_subset(b, c) == [192 + I*Rational(128, 3), 533 + I*Rational(1486, 3), 613 + I*Rational(110, 3), Rational(5013, 5) + I*Rational(1249, 3), 675 + 22*I, 891 + I*Rational(751, 3), 771 + 10*I, Rational(3736, 5) + 105*I] assert convolution_subset(a, c) == convolution_subset(c, a) assert convolution_subset(a[:2], b) == \ [64, Rational(533, 3), 55, Rational(416, 3), 33, 84, 15, 25] assert convolution_subset(a[:2], c) == \ [3 + I*Rational(2, 3), 10 + I*Rational(73, 9), 7, Rational(196, 15), 9, 15, 0, 0] u, v, w, x, y, z = symbols('u v w x y z') assert convolution_subset([u, v, w], [x, y]) == [u*x, u*y + v*x, w*x, w*y] assert convolution_subset([u, v, w, x], [y, z]) == \ [u*y, u*z + v*y, w*y, w*z + x*y] assert convolution_subset([u, v], [x, y, z]) == \ convolution_subset([x, y, z], [u, v]) raises(TypeError, lambda: convolution_subset(x, z)) raises(TypeError, lambda: convolution_subset(Rational(7, 3), u)) def test_covering_product(): assert covering_product([], []) == [] assert covering_product([], [Rational(1, 3)]) == [] assert covering_product([6 + I*Rational(3, 7)], [Rational(2, 3)]) == [4 + I*Rational(2, 7)] a = [1, Rational(5, 8), sqrt(7), 4 + 9*I] b = [66, 81, 95, 49, 37, 89, 17] c = [3 + I*Rational(2, 3), 51 + 72*I, 7, Rational(7, 15), 91] assert covering_product(a, b) == [66, Rational(1383, 8), 95 + 161*sqrt(7), 130*sqrt(7) + 1303 + 2619*I, 37, Rational(671, 4), 17 + 54*sqrt(7), 89*sqrt(7) + Rational(4661, 8) + 1287*I] assert covering_product(b, c) == [198 + 44*I, 7740 + 10638*I, 1412 + I*Rational(190, 3), Rational(42684, 5) + I*Rational(31202, 3), 9484 + I*Rational(74, 3), 22163 + I*Rational(27394, 3), 10621 + I*Rational(34, 3), Rational(90236, 15) + 1224*I] assert covering_product(a, c) == covering_product(c, a) assert covering_product(b, c[:-1]) == [198 + 44*I, 7740 + 10638*I, 1412 + I*Rational(190, 3), Rational(42684, 5) + I*Rational(31202, 3), 111 + I*Rational(74, 3), 6693 + I*Rational(27394, 3), 429 + I*Rational(34, 3), Rational(23351, 15) + 1224*I] assert covering_product(a, c[:-1]) == [3 + I*Rational(2, 3), Rational(339, 4) + I*Rational(1409, 12), 7 + 10*sqrt(7) + 2*sqrt(7)*I/3, -403 + 772*sqrt(7)/15 + 72*sqrt(7)*I + I*Rational(12658, 15)] u, v, w, x, y, z = symbols('u v w x y z') assert covering_product([u, v, w], [x, y]) == \ [u*x, u*y + v*x + v*y, w*x, w*y] assert covering_product([u, v, w, x], [y, z]) == \ [u*y, u*z + v*y + v*z, w*y, w*z + x*y + x*z] assert covering_product([u, v], [x, y, z]) == \ covering_product([x, y, z], [u, v]) raises(TypeError, lambda: covering_product(x, z)) raises(TypeError, lambda: covering_product(Rational(7, 3), u)) def test_intersecting_product(): assert intersecting_product([], []) == [] assert intersecting_product([], [Rational(1, 3)]) == [] assert intersecting_product([6 + I*Rational(3, 7)], [Rational(2, 3)]) == [4 + I*Rational(2, 7)] a = [1, sqrt(5), Rational(3, 8) + 5*I, 4 + 7*I] b = [67, 51, 65, 48, 36, 79, 27] c = [3 + I*Rational(2, 5), 5 + 9*I, 7, Rational(7, 19), 13] assert intersecting_product(a, b) == [195*sqrt(5) + Rational(6979, 8) + 1886*I, 178*sqrt(5) + 520 + 910*I, Rational(841, 2) + 1344*I, 192 + 336*I, 0, 0, 0, 0] assert intersecting_product(b, c) == [Rational(128553, 19) + I*Rational(9521, 5), Rational(17820, 19) + 1602*I, Rational(19264, 19), Rational(336, 19), 1846, 0, 0, 0] assert intersecting_product(a, c) == intersecting_product(c, a) assert intersecting_product(b[1:], c[:-1]) == [Rational(64788, 19) + I*Rational(8622, 5), Rational(12804, 19) + 1152*I, Rational(11508, 19), Rational(252, 19), 0, 0, 0, 0] assert intersecting_product(a, c[:-2]) == \ [Rational(-99, 5) + 10*sqrt(5) + 2*sqrt(5)*I/5 + I*Rational(3021, 40), -43 + 5*sqrt(5) + 9*sqrt(5)*I + 71*I, Rational(245, 8) + 84*I, 0] u, v, w, x, y, z = symbols('u v w x y z') assert intersecting_product([u, v, w], [x, y]) == \ [u*x + u*y + v*x + w*x + w*y, v*y, 0, 0] assert intersecting_product([u, v, w, x], [y, z]) == \ [u*y + u*z + v*y + w*y + w*z + x*y, v*z + x*z, 0, 0] assert intersecting_product([u, v], [x, y, z]) == \ intersecting_product([x, y, z], [u, v]) raises(TypeError, lambda: intersecting_product(x, z)) raises(TypeError, lambda: intersecting_product(u, Rational(8, 3)))
84118bce900a0f61fea353a1493f5d785c78a59f030199179cadfa4e9da7bc35
from sympy import Rational, fibonacci from sympy.core import S, symbols from sympy.testing.pytest import raises from sympy.discrete.recurrences import linrec def test_linrec(): assert linrec(coeffs=[1, 1], init=[1, 1], n=20) == 10946 assert linrec(coeffs=[1, 2, 3, 4, 5], init=[1, 1, 0, 2], n=10) == 1040 assert linrec(coeffs=[0, 0, 11, 13], init=[23, 27], n=25) == 59628567384 assert linrec(coeffs=[0, 0, 1, 1, 2], init=[1, 5, 3], n=15) == 165 assert linrec(coeffs=[11, 13, 15, 17], init=[1, 2, 3, 4], n=70) == \ 56889923441670659718376223533331214868804815612050381493741233489928913241 assert linrec(coeffs=[0]*55 + [1, 1, 2, 3], init=[0]*50 + [1, 2, 3], n=4000) == \ 702633573874937994980598979769135096432444135301118916539 assert linrec(coeffs=[11, 13, 15, 17], init=[1, 2, 3, 4], n=10**4) assert linrec(coeffs=[11, 13, 15, 17], init=[1, 2, 3, 4], n=10**5) assert all(linrec(coeffs=[1, 1], init=[0, 1], n=n) == fibonacci(n) for n in range(95, 115)) assert all(linrec(coeffs=[1, 1], init=[1, 1], n=n) == fibonacci(n + 1) for n in range(595, 615)) a = [S.Half, Rational(3, 4), Rational(5, 6), 7, Rational(8, 9), Rational(3, 5)] b = [1, 2, 8, Rational(5, 7), Rational(3, 7), Rational(2, 9), 6] x, y, z = symbols('x y z') assert linrec(coeffs=a[:5], init=b[:4], n=80) == \ Rational(1726244235456268979436592226626304376013002142588105090705187189, 1960143456748895967474334873705475211264) assert linrec(coeffs=a[:4], init=b[:4], n=50) == \ Rational(368949940033050147080268092104304441, 504857282956046106624) assert linrec(coeffs=a[3:], init=b[:3], n=35) == \ Rational(97409272177295731943657945116791049305244422833125109, 814315512679031689453125) assert linrec(coeffs=[0]*60 + [Rational(2, 3), Rational(4, 5)], init=b, n=3000) == \ Rational(26777668739896791448594650497024, 48084516708184142230517578125) raises(TypeError, lambda: linrec(coeffs=[11, 13, 15, 17], init=[1, 2, 3, 4, 5], n=1)) raises(TypeError, lambda: linrec(coeffs=a[:4], init=b[:5], n=10000)) raises(ValueError, lambda: linrec(coeffs=a[:4], init=b[:4], n=-10000)) raises(TypeError, lambda: linrec(x, b, n=10000)) raises(TypeError, lambda: linrec(a, y, n=10000)) assert linrec(coeffs=[x, y, z], init=[1, 1, 1], n=4) == \ x**2 + x*y + x*z + y + z assert linrec(coeffs=[1, 2, 1], init=[x, y, z], n=20) == \ 269542*x + 664575*y + 578949*z assert linrec(coeffs=[0, 3, 1, 2], init=[x, y], n=30) == \ 58516436*x + 56372788*y assert linrec(coeffs=[0]*50 + [1, 2, 3], init=[x, y, z], n=1000) == \ 11477135884896*x + 25999077948732*y + 41975630244216*z assert linrec(coeffs=[], init=[1, 1], n=20) == 0
66b3342ae863da93afa5d8c9ac2db81a03841dc81d45ae1d5751e495e2f0f5de
from sympy import sqrt from sympy.core import S, Symbol, symbols, I, Rational from sympy.discrete import (fft, ifft, ntt, intt, fwht, ifwht, mobius_transform, inverse_mobius_transform) from sympy.testing.pytest import raises def test_fft_ifft(): assert all(tf(ls) == ls for tf in (fft, ifft) for ls in ([], [Rational(5, 3)])) ls = list(range(6)) fls = [15, -7*sqrt(2)/2 - 4 - sqrt(2)*I/2 + 2*I, 2 + 3*I, -4 + 7*sqrt(2)/2 - 2*I - sqrt(2)*I/2, -3, -4 + 7*sqrt(2)/2 + sqrt(2)*I/2 + 2*I, 2 - 3*I, -7*sqrt(2)/2 - 4 - 2*I + sqrt(2)*I/2] assert fft(ls) == fls assert ifft(fls) == ls + [S.Zero]*2 ls = [1 + 2*I, 3 + 4*I, 5 + 6*I] ifls = [Rational(9, 4) + 3*I, I*Rational(-7, 4), Rational(3, 4) + I, -2 - I/4] assert ifft(ls) == ifls assert fft(ifls) == ls + [S.Zero] x = Symbol('x', real=True) raises(TypeError, lambda: fft(x)) raises(ValueError, lambda: ifft([x, 2*x, 3*x**2, 4*x**3])) def test_ntt_intt(): # prime moduli of the form (m*2**k + 1), sequence length # should be a divisor of 2**k p = 7*17*2**23 + 1 q = 2*500000003 + 1 # only for sequences of length 1 or 2 r = 2*3*5*7 # composite modulus assert all(tf(ls, p) == ls for tf in (ntt, intt) for ls in ([], [5])) ls = list(range(6)) nls = [15, 801133602, 738493201, 334102277, 998244350, 849020224, 259751156, 12232587] assert ntt(ls, p) == nls assert intt(nls, p) == ls + [0]*2 ls = [1 + 2*I, 3 + 4*I, 5 + 6*I] x = Symbol('x', integer=True) raises(TypeError, lambda: ntt(x, p)) raises(ValueError, lambda: intt([x, 2*x, 3*x**2, 4*x**3], p)) raises(ValueError, lambda: intt(ls, p)) raises(ValueError, lambda: ntt([1.2, 2.1, 3.5], p)) raises(ValueError, lambda: ntt([3, 5, 6], q)) raises(ValueError, lambda: ntt([4, 5, 7], r)) raises(ValueError, lambda: ntt([1.0, 2.0, 3.0], p)) def test_fwht_ifwht(): assert all(tf(ls) == ls for tf in (fwht, ifwht) \ for ls in ([], [Rational(7, 4)])) ls = [213, 321, 43235, 5325, 312, 53] fls = [49459, 38061, -47661, -37759, 48729, 37543, -48391, -38277] assert fwht(ls) == fls assert ifwht(fls) == ls + [S.Zero]*2 ls = [S.Half + 2*I, Rational(3, 7) + 4*I, Rational(5, 6) + 6*I, Rational(7, 3), Rational(9, 4)] ifls = [Rational(533, 672) + I*Rational(3, 2), Rational(23, 224) + I/2, Rational(1, 672), Rational(107, 224) - I, Rational(155, 672) + I*Rational(3, 2), Rational(-103, 224) + I/2, Rational(-377, 672), Rational(-19, 224) - I] assert ifwht(ls) == ifls assert fwht(ifls) == ls + [S.Zero]*3 x, y = symbols('x y') raises(TypeError, lambda: fwht(x)) ls = [x, 2*x, 3*x**2, 4*x**3] ifls = [x**3 + 3*x**2/4 + x*Rational(3, 4), -x**3 + 3*x**2/4 - x/4, -x**3 - 3*x**2/4 + x*Rational(3, 4), x**3 - 3*x**2/4 - x/4] assert ifwht(ls) == ifls assert fwht(ifls) == ls ls = [x, y, x**2, y**2, x*y] fls = [x**2 + x*y + x + y**2 + y, x**2 + x*y + x - y**2 - y, -x**2 + x*y + x - y**2 + y, -x**2 + x*y + x + y**2 - y, x**2 - x*y + x + y**2 + y, x**2 - x*y + x - y**2 - y, -x**2 - x*y + x - y**2 + y, -x**2 - x*y + x + y**2 - y] assert fwht(ls) == fls assert ifwht(fls) == ls + [S.Zero]*3 ls = list(range(6)) assert fwht(ls) == [x*8 for x in ifwht(ls)] def test_mobius_transform(): assert all(tf(ls, subset=subset) == ls for ls in ([], [Rational(7, 4)]) for subset in (True, False) for tf in (mobius_transform, inverse_mobius_transform)) w, x, y, z = symbols('w x y z') assert mobius_transform([x, y]) == [x, x + y] assert inverse_mobius_transform([x, x + y]) == [x, y] assert mobius_transform([x, y], subset=False) == [x + y, y] assert inverse_mobius_transform([x + y, y], subset=False) == [x, y] assert mobius_transform([w, x, y, z]) == [w, w + x, w + y, w + x + y + z] assert inverse_mobius_transform([w, w + x, w + y, w + x + y + z]) == \ [w, x, y, z] assert mobius_transform([w, x, y, z], subset=False) == \ [w + x + y + z, x + z, y + z, z] assert inverse_mobius_transform([w + x + y + z, x + z, y + z, z], subset=False) == \ [w, x, y, z] ls = [Rational(2, 3), Rational(6, 7), Rational(5, 8), 9, Rational(5, 3) + 7*I] mls = [Rational(2, 3), Rational(32, 21), Rational(31, 24), Rational(1873, 168), Rational(7, 3) + 7*I, Rational(67, 21) + 7*I, Rational(71, 24) + 7*I, Rational(2153, 168) + 7*I] assert mobius_transform(ls) == mls assert inverse_mobius_transform(mls) == ls + [S.Zero]*3 mls = [Rational(2153, 168) + 7*I, Rational(69, 7), Rational(77, 8), 9, Rational(5, 3) + 7*I, 0, 0, 0] assert mobius_transform(ls, subset=False) == mls assert inverse_mobius_transform(mls, subset=False) == ls + [S.Zero]*3 ls = ls[:-1] mls = [Rational(2, 3), Rational(32, 21), Rational(31, 24), Rational(1873, 168)] assert mobius_transform(ls) == mls assert inverse_mobius_transform(mls) == ls mls = [Rational(1873, 168), Rational(69, 7), Rational(77, 8), 9] assert mobius_transform(ls, subset=False) == mls assert inverse_mobius_transform(mls, subset=False) == ls raises(TypeError, lambda: mobius_transform(x, subset=True)) raises(TypeError, lambda: inverse_mobius_transform(y, subset=False))
b2e1ba0da67647be28be726b63a186ca2bbd03a163524a2e44d5053e711ccea9
from sympy.liealgebras.cartan_type import CartanType from sympy.matrices import Matrix def test_type_E(): c = CartanType("E6") m = Matrix(6, 6, [2, 0, -1, 0, 0, 0, 0, 2, 0, -1, 0, 0, -1, 0, 2, -1, 0, 0, 0, -1, -1, 2, -1, 0, 0, 0, 0, -1, 2, -1, 0, 0, 0, 0, -1, 2]) assert c.cartan_matrix() == m assert c.dimension() == 8 assert c.simple_root(6) == [0, 0, 0, -1, 1, 0, 0, 0] assert c.roots() == 72 assert c.basis() == 78 diag = " "*8 + "2\n" + " "*8 + "0\n" + " "*8 + "|\n" + " "*8 + "|\n" diag += "---".join("0" for i in range(1, 6))+"\n" diag += "1 " + " ".join(str(i) for i in range(3, 7)) assert c.dynkin_diagram() == diag posroots = c.positive_roots() assert posroots[8] == [1, 0, 0, 0, 1, 0, 0, 0]
c94409ecbcd37a6bf809dd575bf76bdf1eca108d3b05a86c580c897d72d2d5e0
from sympy.liealgebras.cartan_type import CartanType from sympy.matrices import Matrix from sympy.core.backend import S def test_type_F(): c = CartanType("F4") m = Matrix(4, 4, [2, -1, 0, 0, -1, 2, -2, 0, 0, -1, 2, -1, 0, 0, -1, 2]) assert c.cartan_matrix() == m assert c.dimension() == 4 assert c.simple_root(1) == [1, -1, 0, 0] assert c.simple_root(2) == [0, 1, -1, 0] assert c.simple_root(3) == [0, 0, 0, 1] assert c.simple_root(4) == [-S.Half, -S.Half, -S.Half, -S.Half] assert c.roots() == 48 assert c.basis() == 52 diag = "0---0=>=0---0\n" + " ".join(str(i) for i in range(1, 5)) assert c.dynkin_diagram() == diag assert c.positive_roots() == {1: [1, -1, 0, 0], 2: [1, 1, 0, 0], 3: [1, 0, -1, 0], 4: [1, 0, 1, 0], 5: [1, 0, 0, -1], 6: [1, 0, 0, 1], 7: [0, 1, -1, 0], 8: [0, 1, 1, 0], 9: [0, 1, 0, -1], 10: [0, 1, 0, 1], 11: [0, 0, 1, -1], 12: [0, 0, 1, 1], 13: [1, 0, 0, 0], 14: [0, 1, 0, 0], 15: [0, 0, 1, 0], 16: [0, 0, 0, 1], 17: [S.Half, S.Half, S.Half, S.Half], 18: [S.Half, -S.Half, S.Half, S.Half], 19: [S.Half, S.Half, -S.Half, S.Half], 20: [S.Half, S.Half, S.Half, -S.Half], 21: [S.Half, S.Half, -S.Half, -S.Half], 22: [S.Half, -S.Half, S.Half, -S.Half], 23: [S.Half, -S.Half, -S.Half, S.Half], 24: [S.Half, -S.Half, -S.Half, -S.Half]}
b77384cb72555cff9d2810da766c80e64a38d80206a54c059fe75b648ec52d8b
from sympy import Symbol, Function, Derivative as D, Eq, cos, sin from sympy.testing.pytest import raises from sympy.calculus.euler import euler_equations as euler def test_euler_interface(): x = Function('x') y = Symbol('y') t = Symbol('t') raises(TypeError, lambda: euler()) raises(TypeError, lambda: euler(D(x(t), t)*y(t), [x(t), y])) raises(ValueError, lambda: euler(D(x(t), t)*x(y), [x(t), x(y)])) raises(TypeError, lambda: euler(D(x(t), t)**2, x(0))) raises(TypeError, lambda: euler(D(x(t), t)*y(t), [t])) assert euler(D(x(t), t)**2/2, {x(t)}) == [Eq(-D(x(t), t, t), 0)] assert euler(D(x(t), t)**2/2, x(t), {t}) == [Eq(-D(x(t), t, t), 0)] def test_euler_pendulum(): x = Function('x') t = Symbol('t') L = D(x(t), t)**2/2 + cos(x(t)) assert euler(L, x(t), t) == [Eq(-sin(x(t)) - D(x(t), t, t), 0)] def test_euler_henonheiles(): x = Function('x') y = Function('y') t = Symbol('t') L = sum(D(z(t), t)**2/2 - z(t)**2/2 for z in [x, y]) L += -x(t)**2*y(t) + y(t)**3/3 assert euler(L, [x(t), y(t)], t) == [Eq(-2*x(t)*y(t) - x(t) - D(x(t), t, t), 0), Eq(-x(t)**2 + y(t)**2 - y(t) - D(y(t), t, t), 0)] def test_euler_sineg(): psi = Function('psi') t = Symbol('t') x = Symbol('x') L = D(psi(t, x), t)**2/2 - D(psi(t, x), x)**2/2 + cos(psi(t, x)) assert euler(L, psi(t, x), [t, x]) == [Eq(-sin(psi(t, x)) - D(psi(t, x), t, t) + D(psi(t, x), x, x), 0)] def test_euler_high_order(): # an example from hep-th/0309038 m = Symbol('m') k = Symbol('k') x = Function('x') y = Function('y') t = Symbol('t') L = (m*D(x(t), t)**2/2 + m*D(y(t), t)**2/2 - k*D(x(t), t)*D(y(t), t, t) + k*D(y(t), t)*D(x(t), t, t)) assert euler(L, [x(t), y(t)]) == [Eq(2*k*D(y(t), t, t, t) - m*D(x(t), t, t), 0), Eq(-2*k*D(x(t), t, t, t) - m*D(y(t), t, t), 0)] w = Symbol('w') L = D(x(t, w), t, w)**2/2 assert euler(L) == [Eq(D(x(t, w), t, t, w, w), 0)]
2959df51afc691c2c937669f5bbd0eeb59ad19b5d08d7bb0763b873b9568a419
from sympy import Symbol, exp, log, oo, S, I, sqrt, Rational from sympy.calculus.singularities import ( singularities, is_increasing, is_strictly_increasing, is_decreasing, is_strictly_decreasing, is_monotonic ) from sympy.sets import Interval, FiniteSet from sympy.testing.pytest import XFAIL, raises from sympy.abc import x, y def test_singularities(): x = Symbol('x') assert singularities(x**2, x) == S.EmptySet assert singularities(x/(x**2 + 3*x + 2), x) == FiniteSet(-2, -1) assert singularities(1/(x**2 + 1), x) == FiniteSet(I, -I) assert singularities(x/(x**3 + 1), x) == \ FiniteSet(-1, (1 - sqrt(3) * I) / 2, (1 + sqrt(3) * I) / 2) assert singularities(1/(y**2 + 2*I*y + 1), y) == \ FiniteSet(-I + sqrt(2)*I, -I - sqrt(2)*I) x = Symbol('x', real=True) assert singularities(1/(x**2 + 1), x) == S.EmptySet @XFAIL def test_singularities_non_rational(): x = Symbol('x', real=True) assert singularities(exp(1/x), x) == FiniteSet(0) assert singularities(log((x - 2)**2), x) == FiniteSet(2) def test_is_increasing(): """Test whether is_increasing returns correct value.""" a = Symbol('a', negative=True) assert is_increasing(x**3 - 3*x**2 + 4*x, S.Reals) assert is_increasing(-x**2, Interval(-oo, 0)) assert not is_increasing(-x**2, Interval(0, oo)) assert not is_increasing(4*x**3 - 6*x**2 - 72*x + 30, Interval(-2, 3)) assert is_increasing(x**2 + y, Interval(1, oo), x) assert is_increasing(-x**2*a, Interval(1, oo), x) assert is_increasing(1) assert is_increasing(4*x**3 - 6*x**2 - 72*x + 30, Interval(-2, 3)) is False def test_is_strictly_increasing(): """Test whether is_strictly_increasing returns correct value.""" assert is_strictly_increasing( 4*x**3 - 6*x**2 - 72*x + 30, Interval.Ropen(-oo, -2)) assert is_strictly_increasing( 4*x**3 - 6*x**2 - 72*x + 30, Interval.Lopen(3, oo)) assert not is_strictly_increasing( 4*x**3 - 6*x**2 - 72*x + 30, Interval.open(-2, 3)) assert not is_strictly_increasing(-x**2, Interval(0, oo)) assert not is_strictly_decreasing(1) assert is_strictly_increasing(4*x**3 - 6*x**2 - 72*x + 30, Interval.open(-2, 3)) is False def test_is_decreasing(): """Test whether is_decreasing returns correct value.""" b = Symbol('b', positive=True) assert is_decreasing(1/(x**2 - 3*x), Interval.open(1.5, 3)) assert is_decreasing(1/(x**2 - 3*x), Interval.Lopen(3, oo)) assert not is_decreasing(1/(x**2 - 3*x), Interval.Ropen(-oo, Rational(3, 2))) assert not is_decreasing(-x**2, Interval(-oo, 0)) assert not is_decreasing(-x**2*b, Interval(-oo, 0), x) def test_is_strictly_decreasing(): """Test whether is_strictly_decreasing returns correct value.""" assert is_strictly_decreasing(1/(x**2 - 3*x), Interval.Lopen(3, oo)) assert not is_strictly_decreasing( 1/(x**2 - 3*x), Interval.Ropen(-oo, Rational(3, 2))) assert not is_strictly_decreasing(-x**2, Interval(-oo, 0)) assert not is_strictly_decreasing(1) assert is_strictly_decreasing(1/(x**2 - 3*x), Interval.open(1.5, 3)) def test_is_monotonic(): """Test whether is_monotonic returns correct value.""" assert is_monotonic(1/(x**2 - 3*x), Interval.open(1.5, 3)) assert is_monotonic(1/(x**2 - 3*x), Interval.Lopen(3, oo)) assert is_monotonic(x**3 - 3*x**2 + 4*x, S.Reals) assert not is_monotonic(-x**2, S.Reals) assert is_monotonic(x**2 + y + 1, Interval(1, 2), x) raises(NotImplementedError, lambda: is_monotonic(x**2 + y + 1))
7f91eb7d35b2da1adf444791ea332fde3a5dee52c4201d73665bfd94785b1eb0
from sympy import (Symbol, S, exp, log, sqrt, oo, E, zoo, pi, tan, sin, cos, cot, sec, csc, Abs, symbols, I, re, simplify, expint, Rational) from sympy.calculus.util import (function_range, continuous_domain, not_empty_in, periodicity, lcim, AccumBounds, is_convex, stationary_points, minimum, maximum) from sympy.core import Add, Mul, Pow from sympy.sets.sets import (Interval, FiniteSet, EmptySet, Complement, Union) from sympy.testing.pytest import raises from sympy.abc import x a = Symbol('a', real=True) def test_function_range(): x, y, a, b = symbols('x y a b') assert function_range(sin(x), x, Interval(-pi/2, pi/2) ) == Interval(-1, 1) assert function_range(sin(x), x, Interval(0, pi) ) == Interval(0, 1) assert function_range(tan(x), x, Interval(0, pi) ) == Interval(-oo, oo) assert function_range(tan(x), x, Interval(pi/2, pi) ) == Interval(-oo, 0) assert function_range((x + 3)/(x - 2), x, Interval(-5, 5) ) == Union(Interval(-oo, Rational(2, 7)), Interval(Rational(8, 3), oo)) assert function_range(1/(x**2), x, Interval(-1, 1) ) == Interval(1, oo) assert function_range(exp(x), x, Interval(-1, 1) ) == Interval(exp(-1), exp(1)) assert function_range(log(x) - x, x, S.Reals ) == Interval(-oo, -1) assert function_range(sqrt(3*x - 1), x, Interval(0, 2) ) == Interval(0, sqrt(5)) assert function_range(x*(x - 1) - (x**2 - x), x, S.Reals ) == FiniteSet(0) assert function_range(x*(x - 1) - (x**2 - x) + y, x, S.Reals ) == FiniteSet(y) assert function_range(sin(x), x, Union(Interval(-5, -3), FiniteSet(4)) ) == Union(Interval(-sin(3), 1), FiniteSet(sin(4))) assert function_range(cos(x), x, Interval(-oo, -4) ) == Interval(-1, 1) assert function_range(cos(x), x, S.EmptySet) == S.EmptySet raises(NotImplementedError, lambda : function_range( exp(x)*(sin(x) - cos(x))/2 - x, x, S.Reals)) raises(NotImplementedError, lambda : function_range( sin(x) + x, x, S.Reals)) # issue 13273 raises(NotImplementedError, lambda : function_range( log(x), x, S.Integers)) raises(NotImplementedError, lambda : function_range( sin(x)/2, x, S.Naturals)) def test_continuous_domain(): x = Symbol('x') assert continuous_domain(sin(x), x, Interval(0, 2*pi)) == Interval(0, 2*pi) assert continuous_domain(tan(x), x, Interval(0, 2*pi)) == \ Union(Interval(0, pi/2, False, True), Interval(pi/2, pi*Rational(3, 2), True, True), Interval(pi*Rational(3, 2), 2*pi, True, False)) assert continuous_domain((x - 1)/((x - 1)**2), x, S.Reals) == \ Union(Interval(-oo, 1, True, True), Interval(1, oo, True, True)) assert continuous_domain(log(x) + log(4*x - 1), x, S.Reals) == \ Interval(Rational(1, 4), oo, True, True) assert continuous_domain(1/sqrt(x - 3), x, S.Reals) == Interval(3, oo, True, True) assert continuous_domain(1/x - 2, x, S.Reals) == \ Union(Interval.open(-oo, 0), Interval.open(0, oo)) assert continuous_domain(1/(x**2 - 4) + 2, x, S.Reals) == \ Union(Interval.open(-oo, -2), Interval.open(-2, 2), Interval.open(2, oo)) def test_not_empty_in(): assert not_empty_in(FiniteSet(x, 2*x).intersect(Interval(1, 2, True, False)), x) == \ Interval(S.Half, 2, True, False) assert not_empty_in(FiniteSet(x, x**2).intersect(Interval(1, 2)), x) == \ Union(Interval(-sqrt(2), -1), Interval(1, 2)) assert not_empty_in(FiniteSet(x**2 + x, x).intersect(Interval(2, 4)), x) == \ Union(Interval(-sqrt(17)/2 - S.Half, -2), Interval(1, Rational(-1, 2) + sqrt(17)/2), Interval(2, 4)) assert not_empty_in(FiniteSet(x/(x - 1)).intersect(S.Reals), x) == \ Complement(S.Reals, FiniteSet(1)) assert not_empty_in(FiniteSet(a/(a - 1)).intersect(S.Reals), a) == \ Complement(S.Reals, FiniteSet(1)) assert not_empty_in(FiniteSet((x**2 - 3*x + 2)/(x - 1)).intersect(S.Reals), x) == \ Complement(S.Reals, FiniteSet(1)) assert not_empty_in(FiniteSet(3, 4, x/(x - 1)).intersect(Interval(2, 3)), x) == \ Interval(-oo, oo) assert not_empty_in(FiniteSet(4, x/(x - 1)).intersect(Interval(2, 3)), x) == \ Interval(S(3)/2, 2) assert not_empty_in(FiniteSet(x/(x**2 - 1)).intersect(S.Reals), x) == \ Complement(S.Reals, FiniteSet(-1, 1)) assert not_empty_in(FiniteSet(x, x**2).intersect(Union(Interval(1, 3, True, True), Interval(4, 5))), x) == \ Union(Interval(-sqrt(5), -2), Interval(-sqrt(3), -1, True, True), Interval(1, 3, True, True), Interval(4, 5)) assert not_empty_in(FiniteSet(1).intersect(Interval(3, 4)), x) == S.EmptySet assert not_empty_in(FiniteSet(x**2/(x + 2)).intersect(Interval(1, oo)), x) == \ Union(Interval(-2, -1, True, False), Interval(2, oo)) raises(ValueError, lambda: not_empty_in(x)) raises(ValueError, lambda: not_empty_in(Interval(0, 1), x)) raises(NotImplementedError, lambda: not_empty_in(FiniteSet(x).intersect(S.Reals), x, a)) def test_periodicity(): x = Symbol('x') y = Symbol('y') z = Symbol('z', real=True) assert periodicity(sin(2*x), x) == pi assert periodicity((-2)*tan(4*x), x) == pi/4 assert periodicity(sin(x)**2, x) == 2*pi assert periodicity(3**tan(3*x), x) == pi/3 assert periodicity(tan(x)*cos(x), x) == 2*pi assert periodicity(sin(x)**(tan(x)), x) == 2*pi assert periodicity(tan(x)*sec(x), x) == 2*pi assert periodicity(sin(2*x)*cos(2*x) - y, x) == pi/2 assert periodicity(tan(x) + cot(x), x) == pi assert periodicity(sin(x) - cos(2*x), x) == 2*pi assert periodicity(sin(x) - 1, x) == 2*pi assert periodicity(sin(4*x) + sin(x)*cos(x), x) == pi assert periodicity(exp(sin(x)), x) == 2*pi assert periodicity(log(cot(2*x)) - sin(cos(2*x)), x) == pi assert periodicity(sin(2*x)*exp(tan(x) - csc(2*x)), x) == pi assert periodicity(cos(sec(x) - csc(2*x)), x) == 2*pi assert periodicity(tan(sin(2*x)), x) == pi assert periodicity(2*tan(x)**2, x) == pi assert periodicity(sin(x%4), x) == 4 assert periodicity(sin(x)%4, x) == 2*pi assert periodicity(tan((3*x-2)%4), x) == Rational(4, 3) assert periodicity((sqrt(2)*(x+1)+x) % 3, x) == 3 / (sqrt(2)+1) assert periodicity((x**2+1) % x, x) is None assert periodicity(sin(re(x)), x) == 2*pi assert periodicity(sin(x)**2 + cos(x)**2, x) is S.Zero assert periodicity(tan(x), y) is S.Zero assert periodicity(sin(x) + I*cos(x), x) == 2*pi assert periodicity(x - sin(2*y), y) == pi assert periodicity(exp(x), x) is None assert periodicity(exp(I*x), x) == 2*pi assert periodicity(exp(I*z), z) == 2*pi assert periodicity(exp(z), z) is None assert periodicity(exp(log(sin(z) + I*cos(2*z)), evaluate=False), z) == 2*pi assert periodicity(exp(log(sin(2*z) + I*cos(z)), evaluate=False), z) == 2*pi assert periodicity(exp(sin(z)), z) == 2*pi assert periodicity(exp(2*I*z), z) == pi assert periodicity(exp(z + I*sin(z)), z) is None assert periodicity(exp(cos(z/2) + sin(z)), z) == 4*pi assert periodicity(log(x), x) is None assert periodicity(exp(x)**sin(x), x) is None assert periodicity(sin(x)**y, y) is None assert periodicity(Abs(sin(Abs(sin(x)))), x) == pi assert all(periodicity(Abs(f(x)), x) == pi for f in ( cos, sin, sec, csc, tan, cot)) assert periodicity(Abs(sin(tan(x))), x) == pi assert periodicity(Abs(sin(sin(x) + tan(x))), x) == 2*pi assert periodicity(sin(x) > S.Half, x) == 2*pi assert periodicity(x > 2, x) is None assert periodicity(x**3 - x**2 + 1, x) is None assert periodicity(Abs(x), x) is None assert periodicity(Abs(x**2 - 1), x) is None assert periodicity((x**2 + 4)%2, x) is None assert periodicity((E**x)%3, x) is None assert periodicity(sin(expint(1, x))/expint(1, x), x) is None def test_periodicity_check(): x = Symbol('x') y = Symbol('y') assert periodicity(tan(x), x, check=True) == pi assert periodicity(sin(x) + cos(x), x, check=True) == 2*pi assert periodicity(sec(x), x) == 2*pi assert periodicity(sin(x*y), x) == 2*pi/abs(y) assert periodicity(Abs(sec(sec(x))), x) == pi def test_lcim(): from sympy import pi assert lcim([S.Half, S(2), S(3)]) == 6 assert lcim([pi/2, pi/4, pi]) == pi assert lcim([2*pi, pi/2]) == 2*pi assert lcim([S.One, 2*pi]) is None assert lcim([S(2) + 2*E, E/3 + Rational(1, 3), S.One + E]) == S(2) + 2*E def test_is_convex(): assert is_convex(1/x, x, domain=Interval(0, oo)) == True assert is_convex(1/x, x, domain=Interval(-oo, 0)) == False assert is_convex(x**2, x, domain=Interval(0, oo)) == True assert is_convex(log(x), x) == False raises(NotImplementedError, lambda: is_convex(log(x), x, a)) def test_stationary_points(): x, y = symbols('x y') assert stationary_points(sin(x), x, Interval(-pi/2, pi/2) ) == {-pi/2, pi/2} assert stationary_points(sin(x), x, Interval.Ropen(0, pi/4) ) == EmptySet() assert stationary_points(tan(x), x, ) == EmptySet() assert stationary_points(sin(x)*cos(x), x, Interval(0, pi) ) == {pi/4, pi*Rational(3, 4)} assert stationary_points(sec(x), x, Interval(0, pi) ) == {0, pi} assert stationary_points((x+3)*(x-2), x ) == FiniteSet(Rational(-1, 2)) assert stationary_points((x + 3)/(x - 2), x, Interval(-5, 5) ) == EmptySet() assert stationary_points((x**2+3)/(x-2), x ) == {2 - sqrt(7), 2 + sqrt(7)} assert stationary_points((x**2+3)/(x-2), x, Interval(0, 5) ) == {2 + sqrt(7)} assert stationary_points(x**4 + x**3 - 5*x**2, x, S.Reals ) == FiniteSet(-2, 0, Rational(5, 4)) assert stationary_points(exp(x), x ) == EmptySet() assert stationary_points(log(x) - x, x, S.Reals ) == {1} assert stationary_points(cos(x), x, Union(Interval(0, 5), Interval(-6, -3)) ) == {0, -pi, pi} assert stationary_points(y, x, S.Reals ) == S.Reals assert stationary_points(y, x, S.EmptySet) == S.EmptySet def test_maximum(): x, y = symbols('x y') assert maximum(sin(x), x) is S.One assert maximum(sin(x), x, Interval(0, 1)) == sin(1) assert maximum(tan(x), x) is oo assert maximum(tan(x), x, Interval(-pi/4, pi/4)) is S.One assert maximum(sin(x)*cos(x), x, S.Reals) == S.Half assert simplify(maximum(sin(x)*cos(x), x, Interval(pi*Rational(3, 8), pi*Rational(5, 8))) ) == sqrt(2)/4 assert maximum((x+3)*(x-2), x) is oo assert maximum((x+3)*(x-2), x, Interval(-5, 0)) == S(14) assert maximum((x+3)/(x-2), x, Interval(-5, 0)) == Rational(2, 7) assert simplify(maximum(-x**4-x**3+x**2+10, x) ) == 41*sqrt(41)/512 + Rational(5419, 512) assert maximum(exp(x), x, Interval(-oo, 2)) == exp(2) assert maximum(log(x) - x, x, S.Reals) is S.NegativeOne assert maximum(cos(x), x, Union(Interval(0, 5), Interval(-6, -3)) ) is S.One assert maximum(cos(x)-sin(x), x, S.Reals) == sqrt(2) assert maximum(y, x, S.Reals) == y raises(ValueError, lambda : maximum(sin(x), x, S.EmptySet)) raises(ValueError, lambda : maximum(log(cos(x)), x, S.EmptySet)) raises(ValueError, lambda : maximum(1/(x**2 + y**2 + 1), x, S.EmptySet)) raises(ValueError, lambda : maximum(sin(x), sin(x))) raises(ValueError, lambda : maximum(sin(x), x*y, S.EmptySet)) raises(ValueError, lambda : maximum(sin(x), S.One)) def test_minimum(): x, y = symbols('x y') assert minimum(sin(x), x) is S.NegativeOne assert minimum(sin(x), x, Interval(1, 4)) == sin(4) assert minimum(tan(x), x) is -oo assert minimum(tan(x), x, Interval(-pi/4, pi/4)) is S.NegativeOne assert minimum(sin(x)*cos(x), x, S.Reals) == Rational(-1, 2) assert simplify(minimum(sin(x)*cos(x), x, Interval(pi*Rational(3, 8), pi*Rational(5, 8))) ) == -sqrt(2)/4 assert minimum((x+3)*(x-2), x) == Rational(-25, 4) assert minimum((x+3)/(x-2), x, Interval(-5, 0)) == Rational(-3, 2) assert minimum(x**4-x**3+x**2+10, x) == S(10) assert minimum(exp(x), x, Interval(-2, oo)) == exp(-2) assert minimum(log(x) - x, x, S.Reals) is -oo assert minimum(cos(x), x, Union(Interval(0, 5), Interval(-6, -3)) ) is S.NegativeOne assert minimum(cos(x)-sin(x), x, S.Reals) == -sqrt(2) assert minimum(y, x, S.Reals) == y raises(ValueError, lambda : minimum(sin(x), x, S.EmptySet)) raises(ValueError, lambda : minimum(log(cos(x)), x, S.EmptySet)) raises(ValueError, lambda : minimum(1/(x**2 + y**2 + 1), x, S.EmptySet)) raises(ValueError, lambda : minimum(sin(x), sin(x))) raises(ValueError, lambda : minimum(sin(x), x*y, S.EmptySet)) raises(ValueError, lambda : minimum(sin(x), S.One)) def test_AccumBounds(): assert AccumBounds(1, 2).args == (1, 2) assert AccumBounds(1, 2).delta is S.One assert AccumBounds(1, 2).mid == Rational(3, 2) assert AccumBounds(1, 3).is_real == True assert AccumBounds(1, 1) is S.One assert AccumBounds(1, 2) + 1 == AccumBounds(2, 3) assert 1 + AccumBounds(1, 2) == AccumBounds(2, 3) assert AccumBounds(1, 2) + AccumBounds(2, 3) == AccumBounds(3, 5) assert -AccumBounds(1, 2) == AccumBounds(-2, -1) assert AccumBounds(1, 2) - 1 == AccumBounds(0, 1) assert 1 - AccumBounds(1, 2) == AccumBounds(-1, 0) assert AccumBounds(2, 3) - AccumBounds(1, 2) == AccumBounds(0, 2) assert x + AccumBounds(1, 2) == Add(AccumBounds(1, 2), x) assert a + AccumBounds(1, 2) == AccumBounds(1 + a, 2 + a) assert AccumBounds(1, 2) - x == Add(AccumBounds(1, 2), -x) assert AccumBounds(-oo, 1) + oo == AccumBounds(-oo, oo) assert AccumBounds(1, oo) + oo is oo assert AccumBounds(1, oo) - oo == AccumBounds(-oo, oo) assert (-oo - AccumBounds(-1, oo)) is -oo assert AccumBounds(-oo, 1) - oo is -oo assert AccumBounds(1, oo) - oo == AccumBounds(-oo, oo) assert AccumBounds(-oo, 1) - (-oo) == AccumBounds(-oo, oo) assert (oo - AccumBounds(1, oo)) == AccumBounds(-oo, oo) assert (-oo - AccumBounds(1, oo)) is -oo assert AccumBounds(1, 2)/2 == AccumBounds(S.Half, 1) assert 2/AccumBounds(2, 3) == AccumBounds(Rational(2, 3), 1) assert 1/AccumBounds(-1, 1) == AccumBounds(-oo, oo) assert abs(AccumBounds(1, 2)) == AccumBounds(1, 2) assert abs(AccumBounds(-2, -1)) == AccumBounds(1, 2) assert abs(AccumBounds(-2, 1)) == AccumBounds(0, 2) assert abs(AccumBounds(-1, 2)) == AccumBounds(0, 2) c = Symbol('c') raises(ValueError, lambda: AccumBounds(0, c)) raises(ValueError, lambda: AccumBounds(1, -1)) def test_AccumBounds_mul(): assert AccumBounds(1, 2)*2 == AccumBounds(2, 4) assert 2*AccumBounds(1, 2) == AccumBounds(2, 4) assert AccumBounds(1, 2)*AccumBounds(2, 3) == AccumBounds(2, 6) assert AccumBounds(1, 2)*0 == 0 assert AccumBounds(1, oo)*0 == AccumBounds(0, oo) assert AccumBounds(-oo, 1)*0 == AccumBounds(-oo, 0) assert AccumBounds(-oo, oo)*0 == AccumBounds(-oo, oo) assert AccumBounds(1, 2)*x == Mul(AccumBounds(1, 2), x, evaluate=False) assert AccumBounds(0, 2)*oo == AccumBounds(0, oo) assert AccumBounds(-2, 0)*oo == AccumBounds(-oo, 0) assert AccumBounds(0, 2)*(-oo) == AccumBounds(-oo, 0) assert AccumBounds(-2, 0)*(-oo) == AccumBounds(0, oo) assert AccumBounds(-1, 1)*oo == AccumBounds(-oo, oo) assert AccumBounds(-1, 1)*(-oo) == AccumBounds(-oo, oo) assert AccumBounds(-oo, oo)*oo == AccumBounds(-oo, oo) def test_AccumBounds_div(): assert AccumBounds(-1, 3)/AccumBounds(3, 4) == AccumBounds(Rational(-1, 3), 1) assert AccumBounds(-2, 4)/AccumBounds(-3, 4) == AccumBounds(-oo, oo) assert AccumBounds(-3, -2)/AccumBounds(-4, 0) == AccumBounds(S.Half, oo) # these two tests can have a better answer # after Union of AccumBounds is improved assert AccumBounds(-3, -2)/AccumBounds(-2, 1) == AccumBounds(-oo, oo) assert AccumBounds(2, 3)/AccumBounds(-2, 2) == AccumBounds(-oo, oo) assert AccumBounds(-3, -2)/AccumBounds(0, 4) == AccumBounds(-oo, Rational(-1, 2)) assert AccumBounds(2, 4)/AccumBounds(-3, 0) == AccumBounds(-oo, Rational(-2, 3)) assert AccumBounds(2, 4)/AccumBounds(0, 3) == AccumBounds(Rational(2, 3), oo) assert AccumBounds(0, 1)/AccumBounds(0, 1) == AccumBounds(0, oo) assert AccumBounds(-1, 0)/AccumBounds(0, 1) == AccumBounds(-oo, 0) assert AccumBounds(-1, 2)/AccumBounds(-2, 2) == AccumBounds(-oo, oo) assert 1/AccumBounds(-1, 2) == AccumBounds(-oo, oo) assert 1/AccumBounds(0, 2) == AccumBounds(S.Half, oo) assert (-1)/AccumBounds(0, 2) == AccumBounds(-oo, Rational(-1, 2)) assert 1/AccumBounds(-oo, 0) == AccumBounds(-oo, 0) assert 1/AccumBounds(-1, 0) == AccumBounds(-oo, -1) assert (-2)/AccumBounds(-oo, 0) == AccumBounds(0, oo) assert 1/AccumBounds(-oo, -1) == AccumBounds(-1, 0) assert AccumBounds(1, 2)/a == Mul(AccumBounds(1, 2), 1/a, evaluate=False) assert AccumBounds(1, 2)/0 == AccumBounds(1, 2)*zoo assert AccumBounds(1, oo)/oo == AccumBounds(0, oo) assert AccumBounds(1, oo)/(-oo) == AccumBounds(-oo, 0) assert AccumBounds(-oo, -1)/oo == AccumBounds(-oo, 0) assert AccumBounds(-oo, -1)/(-oo) == AccumBounds(0, oo) assert AccumBounds(-oo, oo)/oo == AccumBounds(-oo, oo) assert AccumBounds(-oo, oo)/(-oo) == AccumBounds(-oo, oo) assert AccumBounds(-1, oo)/oo == AccumBounds(0, oo) assert AccumBounds(-1, oo)/(-oo) == AccumBounds(-oo, 0) assert AccumBounds(-oo, 1)/oo == AccumBounds(-oo, 0) assert AccumBounds(-oo, 1)/(-oo) == AccumBounds(0, oo) def test_AccumBounds_func(): assert (x**2 + 2*x + 1).subs(x, AccumBounds(-1, 1)) == AccumBounds(-1, 4) assert exp(AccumBounds(0, 1)) == AccumBounds(1, E) assert exp(AccumBounds(-oo, oo)) == AccumBounds(0, oo) assert log(AccumBounds(3, 6)) == AccumBounds(log(3), log(6)) def test_AccumBounds_pow(): assert AccumBounds(0, 2)**2 == AccumBounds(0, 4) assert AccumBounds(-1, 1)**2 == AccumBounds(0, 1) assert AccumBounds(1, 2)**2 == AccumBounds(1, 4) assert AccumBounds(-1, 2)**3 == AccumBounds(-1, 8) assert AccumBounds(-1, 1)**0 == 1 assert AccumBounds(1, 2)**Rational(5, 2) == AccumBounds(1, 4*sqrt(2)) assert AccumBounds(-1, 2)**Rational(1, 3) == AccumBounds(-1, 2**Rational(1, 3)) assert AccumBounds(0, 2)**S.Half == AccumBounds(0, sqrt(2)) assert AccumBounds(-4, 2)**Rational(2, 3) == AccumBounds(0, 2*2**Rational(1, 3)) assert AccumBounds(-1, 5)**S.Half == AccumBounds(0, sqrt(5)) assert AccumBounds(-oo, 2)**S.Half == AccumBounds(0, sqrt(2)) assert AccumBounds(-2, 3)**Rational(-1, 4) == AccumBounds(0, oo) assert AccumBounds(1, 5)**(-2) == AccumBounds(Rational(1, 25), 1) assert AccumBounds(-1, 3)**(-2) == AccumBounds(0, oo) assert AccumBounds(0, 2)**(-2) == AccumBounds(Rational(1, 4), oo) assert AccumBounds(-1, 2)**(-3) == AccumBounds(-oo, oo) assert AccumBounds(-3, -2)**(-3) == AccumBounds(Rational(-1, 8), Rational(-1, 27)) assert AccumBounds(-3, -2)**(-2) == AccumBounds(Rational(1, 9), Rational(1, 4)) assert AccumBounds(0, oo)**S.Half == AccumBounds(0, oo) assert AccumBounds(-oo, -1)**Rational(1, 3) == AccumBounds(-oo, -1) assert AccumBounds(-2, 3)**(Rational(-1, 3)) == AccumBounds(-oo, oo) assert AccumBounds(-oo, 0)**(-2) == AccumBounds(0, oo) assert AccumBounds(-2, 0)**(-2) == AccumBounds(Rational(1, 4), oo) assert AccumBounds(Rational(1, 3), S.Half)**oo is S.Zero assert AccumBounds(0, S.Half)**oo is S.Zero assert AccumBounds(S.Half, 1)**oo == AccumBounds(0, oo) assert AccumBounds(0, 1)**oo == AccumBounds(0, oo) assert AccumBounds(2, 3)**oo is oo assert AccumBounds(1, 2)**oo == AccumBounds(0, oo) assert AccumBounds(S.Half, 3)**oo == AccumBounds(0, oo) assert AccumBounds(Rational(-1, 3), Rational(-1, 4))**oo is S.Zero assert AccumBounds(-1, Rational(-1, 2))**oo == AccumBounds(-oo, oo) assert AccumBounds(-3, -2)**oo == FiniteSet(-oo, oo) assert AccumBounds(-2, -1)**oo == AccumBounds(-oo, oo) assert AccumBounds(-2, Rational(-1, 2))**oo == AccumBounds(-oo, oo) assert AccumBounds(Rational(-1, 2), S.Half)**oo is S.Zero assert AccumBounds(Rational(-1, 2), 1)**oo == AccumBounds(0, oo) assert AccumBounds(Rational(-2, 3), 2)**oo == AccumBounds(0, oo) assert AccumBounds(-1, 1)**oo == AccumBounds(-oo, oo) assert AccumBounds(-1, S.Half)**oo == AccumBounds(-oo, oo) assert AccumBounds(-1, 2)**oo == AccumBounds(-oo, oo) assert AccumBounds(-2, S.Half)**oo == AccumBounds(-oo, oo) assert AccumBounds(1, 2)**x == Pow(AccumBounds(1, 2), x) assert AccumBounds(2, 3)**(-oo) is S.Zero assert AccumBounds(0, 2)**(-oo) == AccumBounds(0, oo) assert AccumBounds(-1, 2)**(-oo) == AccumBounds(-oo, oo) assert (tan(x)**sin(2*x)).subs(x, AccumBounds(0, pi/2)) == \ Pow(AccumBounds(-oo, oo), AccumBounds(0, 1)) def test_comparison_AccumBounds(): assert (AccumBounds(1, 3) < 4) == S.true assert (AccumBounds(1, 3) < -1) == S.false assert (AccumBounds(1, 3) < 2).rel_op == '<' assert (AccumBounds(1, 3) <= 2).rel_op == '<=' assert (AccumBounds(1, 3) > 4) == S.false assert (AccumBounds(1, 3) > -1) == S.true assert (AccumBounds(1, 3) > 2).rel_op == '>' assert (AccumBounds(1, 3) >= 2).rel_op == '>=' assert (AccumBounds(1, 3) < AccumBounds(4, 6)) == S.true assert (AccumBounds(1, 3) < AccumBounds(2, 4)).rel_op == '<' assert (AccumBounds(1, 3) < AccumBounds(-2, 0)) == S.false assert (AccumBounds(1, 3) <= AccumBounds(4, 6)) == S.true assert (AccumBounds(1, 3) <= AccumBounds(-2, 0)) == S.false assert (AccumBounds(1, 3) > AccumBounds(4, 6)) == S.false assert (AccumBounds(1, 3) > AccumBounds(-2, 0)) == S.true assert (AccumBounds(1, 3) >= AccumBounds(4, 6)) == S.false assert (AccumBounds(1, 3) >= AccumBounds(-2, 0)) == S.true # issue 13499 assert (cos(x) > 0).subs(x, oo) == (AccumBounds(-1, 1) > 0) c = Symbol('c') raises(TypeError, lambda: (AccumBounds(0, 1) < c)) raises(TypeError, lambda: (AccumBounds(0, 1) <= c)) raises(TypeError, lambda: (AccumBounds(0, 1) > c)) raises(TypeError, lambda: (AccumBounds(0, 1) >= c)) def test_contains_AccumBounds(): assert (1 in AccumBounds(1, 2)) == S.true raises(TypeError, lambda: a in AccumBounds(1, 2)) assert 0 in AccumBounds(-1, 0) raises(TypeError, lambda: (cos(1)**2 + sin(1)**2 - 1) in AccumBounds(-1, 0)) assert (-oo in AccumBounds(1, oo)) == S.true assert (oo in AccumBounds(-oo, 0)) == S.true # issue 13159 assert Mul(0, AccumBounds(-1, 1)) == Mul(AccumBounds(-1, 1), 0) == 0 import itertools for perm in itertools.permutations([0, AccumBounds(-1, 1), x]): assert Mul(*perm) == 0 def test_intersection_AccumBounds(): assert AccumBounds(0, 3).intersection(AccumBounds(1, 2)) == AccumBounds(1, 2) assert AccumBounds(0, 3).intersection(AccumBounds(1, 4)) == AccumBounds(1, 3) assert AccumBounds(0, 3).intersection(AccumBounds(-1, 2)) == AccumBounds(0, 2) assert AccumBounds(0, 3).intersection(AccumBounds(-1, 4)) == AccumBounds(0, 3) assert AccumBounds(0, 1).intersection(AccumBounds(2, 3)) == S.EmptySet raises(TypeError, lambda: AccumBounds(0, 3).intersection(1)) def test_union_AccumBounds(): assert AccumBounds(0, 3).union(AccumBounds(1, 2)) == AccumBounds(0, 3) assert AccumBounds(0, 3).union(AccumBounds(1, 4)) == AccumBounds(0, 4) assert AccumBounds(0, 3).union(AccumBounds(-1, 2)) == AccumBounds(-1, 3) assert AccumBounds(0, 3).union(AccumBounds(-1, 4)) == AccumBounds(-1, 4) raises(TypeError, lambda: AccumBounds(0, 3).union(1)) def test_issue_16469(): x = Symbol("x", real=True) f = abs(x) assert function_range(f, x, S.Reals) == Interval(0, oo, False, True)
8e206b9f7fc381abaf78c65a2780d51feed293d3e2849f49ca7c9b0ad7ca1b56
from itertools import product from sympy import S, symbols, Function, exp, diff, Rational from sympy.calculus.finite_diff import ( apply_finite_diff, differentiate_finite, finite_diff_weights, as_finite_diff ) from sympy.testing.pytest import raises, warns_deprecated_sympy, ignore_warnings from sympy.utilities.exceptions import SymPyDeprecationWarning def test_apply_finite_diff(): x, h = symbols('x h') f = Function('f') assert (apply_finite_diff(1, [x-h, x+h], [f(x-h), f(x+h)], x) - (f(x+h)-f(x-h))/(2*h)).simplify() == 0 assert (apply_finite_diff(1, [5, 6, 7], [f(5), f(6), f(7)], 5) - (Rational(-3, 2)*f(5) + 2*f(6) - S.Half*f(7))).simplify() == 0 raises(ValueError, lambda: apply_finite_diff(1, [x, h], [f(x)])) def test_finite_diff_weights(): d = finite_diff_weights(1, [5, 6, 7], 5) assert d[1][2] == [Rational(-3, 2), 2, Rational(-1, 2)] # Table 1, p. 702 in doi:10.1090/S0025-5718-1988-0935077-0 # -------------------------------------------------------- xl = [0, 1, -1, 2, -2, 3, -3, 4, -4] # d holds all coefficients d = finite_diff_weights(4, xl, S.Zero) # Zeroeth derivative for i in range(5): assert d[0][i] == [S.One] + [S.Zero]*8 # First derivative assert d[1][0] == [S.Zero]*9 assert d[1][2] == [S.Zero, S.Half, Rational(-1, 2)] + [S.Zero]*6 assert d[1][4] == [S.Zero, Rational(2, 3), Rational(-2, 3), Rational(-1, 12), Rational(1, 12)] + [S.Zero]*4 assert d[1][6] == [S.Zero, Rational(3, 4), Rational(-3, 4), Rational(-3, 20), Rational(3, 20), Rational(1, 60), Rational(-1, 60)] + [S.Zero]*2 assert d[1][8] == [S.Zero, Rational(4, 5), Rational(-4, 5), Rational(-1, 5), Rational(1, 5), Rational(4, 105), Rational(-4, 105), Rational(-1, 280), Rational(1, 280)] # Second derivative for i in range(2): assert d[2][i] == [S.Zero]*9 assert d[2][2] == [-S(2), S.One, S.One] + [S.Zero]*6 assert d[2][4] == [Rational(-5, 2), Rational(4, 3), Rational(4, 3), Rational(-1, 12), Rational(-1, 12)] + [S.Zero]*4 assert d[2][6] == [Rational(-49, 18), Rational(3, 2), Rational(3, 2), Rational(-3, 20), Rational(-3, 20), Rational(1, 90), Rational(1, 90)] + [S.Zero]*2 assert d[2][8] == [Rational(-205, 72), Rational(8, 5), Rational(8, 5), Rational(-1, 5), Rational(-1, 5), Rational(8, 315), Rational(8, 315), Rational(-1, 560), Rational(-1, 560)] # Third derivative for i in range(3): assert d[3][i] == [S.Zero]*9 assert d[3][4] == [S.Zero, -S.One, S.One, S.Half, Rational(-1, 2)] + [S.Zero]*4 assert d[3][6] == [S.Zero, Rational(-13, 8), Rational(13, 8), S.One, -S.One, Rational(-1, 8), Rational(1, 8)] + [S.Zero]*2 assert d[3][8] == [S.Zero, Rational(-61, 30), Rational(61, 30), Rational(169, 120), Rational(-169, 120), Rational(-3, 10), Rational(3, 10), Rational(7, 240), Rational(-7, 240)] # Fourth derivative for i in range(4): assert d[4][i] == [S.Zero]*9 assert d[4][4] == [S(6), -S(4), -S(4), S.One, S.One] + [S.Zero]*4 assert d[4][6] == [Rational(28, 3), Rational(-13, 2), Rational(-13, 2), S(2), S(2), Rational(-1, 6), Rational(-1, 6)] + [S.Zero]*2 assert d[4][8] == [Rational(91, 8), Rational(-122, 15), Rational(-122, 15), Rational(169, 60), Rational(169, 60), Rational(-2, 5), Rational(-2, 5), Rational(7, 240), Rational(7, 240)] # Table 2, p. 703 in doi:10.1090/S0025-5718-1988-0935077-0 # -------------------------------------------------------- xl = [[j/S(2) for j in list(range(-i*2+1, 0, 2))+list(range(1, i*2+1, 2))] for i in range(1, 5)] # d holds all coefficients d = [finite_diff_weights({0: 1, 1: 2, 2: 4, 3: 4}[i], xl[i], 0) for i in range(4)] # Zeroth derivative assert d[0][0][1] == [S.Half, S.Half] assert d[1][0][3] == [Rational(-1, 16), Rational(9, 16), Rational(9, 16), Rational(-1, 16)] assert d[2][0][5] == [Rational(3, 256), Rational(-25, 256), Rational(75, 128), Rational(75, 128), Rational(-25, 256), Rational(3, 256)] assert d[3][0][7] == [Rational(-5, 2048), Rational(49, 2048), Rational(-245, 2048), Rational(1225, 2048), Rational(1225, 2048), Rational(-245, 2048), Rational(49, 2048), Rational(-5, 2048)] # First derivative assert d[0][1][1] == [-S.One, S.One] assert d[1][1][3] == [Rational(1, 24), Rational(-9, 8), Rational(9, 8), Rational(-1, 24)] assert d[2][1][5] == [Rational(-3, 640), Rational(25, 384), Rational(-75, 64), Rational(75, 64), Rational(-25, 384), Rational(3, 640)] assert d[3][1][7] == [Rational(5, 7168), Rational(-49, 5120), Rational(245, 3072), Rational(-1225, 1024), Rational(1225, 1024), Rational(-245, 3072), Rational(49, 5120), Rational(-5, 7168)] # Reasonably the rest of the table is also correct... (testing of that # deemed excessive at the moment) raises(ValueError, lambda: finite_diff_weights(-1, [1, 2])) raises(ValueError, lambda: finite_diff_weights(1.2, [1, 2])) x = symbols('x') raises(ValueError, lambda: finite_diff_weights(x, [1, 2])) def test_as_finite_diff(): x = symbols('x') f = Function('f') dx = Function('dx') with warns_deprecated_sympy(): as_finite_diff(f(x).diff(x), [x-2, x-1, x, x+1, x+2]) # Use of undefined functions in ``points`` df_true = -f(x+dx(x)/2-dx(x+dx(x)/2)/2) / dx(x+dx(x)/2) \ + f(x+dx(x)/2+dx(x+dx(x)/2)/2) / dx(x+dx(x)/2) df_test = diff(f(x), x).as_finite_difference(points=dx(x), x0=x+dx(x)/2) assert (df_test - df_true).simplify() == 0 def test_differentiate_finite(): x, y, h = symbols('x y h') f = Function('f') with ignore_warnings(SymPyDeprecationWarning): res0 = differentiate_finite(f(x, y) + exp(42), x, y, evaluate=True) xm, xp, ym, yp = [v + sign*S.Half for v, sign in product([x, y], [-1, 1])] ref0 = f(xm, ym) + f(xp, yp) - f(xm, yp) - f(xp, ym) assert (res0 - ref0).simplify() == 0 g = Function('g') with ignore_warnings(SymPyDeprecationWarning): res1 = differentiate_finite(f(x)*g(x) + 42, x, evaluate=True) ref1 = (-f(x - S.Half) + f(x + S.Half))*g(x) + \ (-g(x - S.Half) + g(x + S.Half))*f(x) assert (res1 - ref1).simplify() == 0 res2 = differentiate_finite(f(x) + x**3 + 42, x, points=[x-1, x+1]) ref2 = (f(x + 1) + (x + 1)**3 - f(x - 1) - (x - 1)**3)/2 assert (res2 - ref2).simplify() == 0 raises(ValueError, lambda: differentiate_finite(f(x)*g(x), x, pints=[x-1, x+1])) res3 = differentiate_finite(f(x)*g(x).diff(x), x) ref3 = (-g(x) + g(x + 1))*f(x + S.Half) - (g(x) - g(x - 1))*f(x - S.Half) assert res3 == ref3 res4 = differentiate_finite(f(x)*g(x).diff(x).diff(x), x) ref4 = -((g(x - Rational(3, 2)) - 2*g(x - S.Half) + g(x + S.Half))*f(x - S.Half)) \ + (g(x - S.Half) - 2*g(x + S.Half) + g(x + Rational(3, 2)))*f(x + S.Half) assert res4 == ref4 res5_expr = f(x).diff(x)*g(x).diff(x) res5 = differentiate_finite(res5_expr, points=[x-h, x, x+h]) ref5 = (-2*f(x)/h + f(-h + x)/(2*h) + 3*f(h + x)/(2*h))*(-2*g(x)/h + g(-h + x)/(2*h) \ + 3*g(h + x)/(2*h))/(2*h) - (2*f(x)/h - 3*f(-h + x)/(2*h) - \ f(h + x)/(2*h))*(2*g(x)/h - 3*g(-h + x)/(2*h) - g(h + x)/(2*h))/(2*h) assert res5 == ref5 res6 = res5.limit(h, 0).doit() ref6 = diff(res5_expr, x) assert res6 == ref6
d4c8d6805c20485a7beef65fcb06b23748bccc0e9134359c87391a23a07ab8d9
from sympy import S from sympy.strategies.rl import (rm_id, glom, flatten, unpack, sort, distribute, subs, rebuild) from sympy import Basic def test_rm_id(): rmzeros = rm_id(lambda x: x == 0) assert rmzeros(Basic(0, 1)) == Basic(1) assert rmzeros(Basic(0, 0)) == Basic(0) assert rmzeros(Basic(2, 1)) == Basic(2, 1) def test_glom(): from sympy import Add from sympy.abc import x key = lambda x: x.as_coeff_Mul()[1] count = lambda x: x.as_coeff_Mul()[0] newargs = lambda cnt, arg: cnt * arg rl = glom(key, count, newargs) result = rl(Add(x, -x, 3*x, 2, 3, evaluate=False)) expected = Add(3*x, 5) assert set(result.args) == set(expected.args) def test_flatten(): assert flatten(Basic(1, 2, Basic(3, 4))) == Basic(1, 2, 3, 4) def test_unpack(): assert unpack(Basic(2)) == 2 assert unpack(Basic(2, 3)) == Basic(2, 3) def test_sort(): assert sort(str)(Basic(3,1,2)) == Basic(1,2,3) def test_distribute(): class T1(Basic): pass class T2(Basic): pass distribute_t12 = distribute(T1, T2) assert distribute_t12(T1(1, 2, T2(3, 4), 5)) == \ T2(T1(1, 2, 3, 5), T1(1, 2, 4, 5)) assert distribute_t12(T1(1, 2, 3)) == T1(1, 2, 3) def test_distribute_add_mul(): from sympy import Add, Mul, symbols x, y = symbols('x, y') expr = Mul(2, Add(x, y), evaluate=False) expected = Add(Mul(2, x), Mul(2, y)) distribute_mul = distribute(Mul, Add) assert distribute_mul(expr) == expected def test_subs(): rl = subs(1, 2) assert rl(1) == 2 assert rl(3) == 3 def test_rebuild(): from sympy import Add expr = Basic.__new__(Add, S(1), S(2)) assert rebuild(expr) == 3
43c87f55092f84e25e95725b9d6b44e309ddc31fb1e5acf79ddda0b23222f79c
from sympy.strategies.traverse import (top_down, bottom_up, sall, top_down_once, bottom_up_once, basic_fns) from sympy.strategies.rl import rebuild from sympy.strategies.util import expr_fns from sympy import Add, Basic, Symbol, S from sympy.abc import x, y, z def zero_symbols(expression): return S.Zero if isinstance(expression, Symbol) else expression def test_sall(): zero_onelevel = sall(zero_symbols) assert zero_onelevel(Basic(x, y, Basic(x, z))) == Basic(0, 0, Basic(x, z)) def test_bottom_up(): _test_global_traversal(bottom_up) _test_stop_on_non_basics(bottom_up) def test_top_down(): _test_global_traversal(top_down) _test_stop_on_non_basics(top_down) def _test_global_traversal(trav): zero_all_symbols = trav(zero_symbols) assert zero_all_symbols(Basic(x, y, Basic(x, z))) == \ Basic(0, 0, Basic(0, 0)) def _test_stop_on_non_basics(trav): def add_one_if_can(expr): try: return expr + 1 except TypeError: return expr expr = Basic(1, 'a', Basic(2, 'b')) expected = Basic(2, 'a', Basic(3, 'b')) rl = trav(add_one_if_can) assert rl(expr) == expected class Basic2(Basic): pass rl = lambda x: Basic2(*x.args) if isinstance(x, Basic) else x def test_top_down_once(): top_rl = top_down_once(rl) assert top_rl(Basic(1, 2, Basic(3, 4))) == Basic2(1, 2, Basic(3, 4)) def test_bottom_up_once(): bottom_rl = bottom_up_once(rl) assert bottom_rl(Basic(1, 2, Basic(3, 4))) == Basic(1, 2, Basic2(3, 4)) def test_expr_fns(): expr = x + y**3 e = bottom_up(lambda v: v + 1, expr_fns)(expr) b = bottom_up(lambda v: Basic.__new__(Add, v, S(1)), basic_fns)(expr) assert rebuild(b) == e
62a5574f68335da8bd83d53d217828d248653f93fcd17f306ac8d0e7c8b7a945
from sympy import S from sympy.strategies.core import (null_safe, exhaust, memoize, condition, chain, tryit, do_one, debug, switch, minimize) from sympy.core.compatibility import get_function_name def test_null_safe(): def rl(expr): if expr == 1: return 2 safe_rl = null_safe(rl) assert rl(1) == safe_rl(1) assert rl(3) == None assert safe_rl(3) == 3 def posdec(x): if x > 0: return x-1 else: return x def test_exhaust(): sink = exhaust(posdec) assert sink(5) == 0 assert sink(10) == 0 def test_memoize(): rl = memoize(posdec) assert rl(5) == posdec(5) assert rl(5) == posdec(5) assert rl(-2) == posdec(-2) def test_condition(): rl = condition(lambda x: x%2 == 0, posdec) assert rl(5) == 5 assert rl(4) == 3 def test_chain(): rl = chain(posdec, posdec) assert rl(5) == 3 assert rl(1) == 0 def test_tryit(): def rl(expr): assert False safe_rl = tryit(rl, AssertionError) assert safe_rl(S(1)) == 1 def test_do_one(): rl = do_one(posdec, posdec) assert rl(5) == 4 rl1 = lambda x: 2 if x == 1 else x rl2 = lambda x: 3 if x == 2 else x rule = do_one(rl1, rl2) assert rule(1) == 2 assert rule(rule(1)) == 3 def test_debug(): from sympy.core.compatibility import StringIO file = StringIO() rl = debug(posdec, file) rl(5) log = file.getvalue() file.close() assert get_function_name(posdec) in log assert '5' in log assert '4' in log def test_switch(): inc = lambda x: x + 1 dec = lambda x: x - 1 key = lambda x: x % 3 rl = switch(key, {0: inc, 1: dec}) assert rl(3) == 4 assert rl(4) == 3 assert rl(5) == 5 def test_minimize(): inc = lambda x: x + 1 dec = lambda x: x - 1 rl = minimize(inc, dec) assert rl(4) == 3 rl = minimize(inc, dec, objective=lambda x: -x) assert rl(4) == 5
4caaf29e17ce80f5ae119defc97a1299719b4808f66fb3099a138065096f28b3
from sympy.strategies.branch.core import (exhaust, debug, multiplex, condition, notempty, chain, onaction, sfilter, yieldify, do_one, identity) from sympy.core.compatibility import get_function_name def posdec(x): if x > 0: yield x-1 else: yield x def branch5(x): if 0 < x < 5: yield x-1 elif 5 < x < 10: yield x+1 elif x == 5: yield x+1 yield x-1 else: yield x even = lambda x: x%2 == 0 def inc(x): yield x + 1 def one_to_n(n): for i in range(n): yield i def test_exhaust(): brl = exhaust(branch5) assert set(brl(3)) == {0} assert set(brl(7)) == {10} assert set(brl(5)) == {0, 10} def test_debug(): from sympy.core.compatibility import StringIO file = StringIO() rl = debug(posdec, file) list(rl(5)) log = file.getvalue() file.close() assert get_function_name(posdec) in log assert '5' in log assert '4' in log def test_multiplex(): brl = multiplex(posdec, branch5) assert set(brl(3)) == {2} assert set(brl(7)) == {6, 8} assert set(brl(5)) == {4, 6} def test_condition(): brl = condition(even, branch5) assert set(brl(4)) == set(branch5(4)) assert set(brl(5)) == set([]) def test_sfilter(): brl = sfilter(even, one_to_n) assert set(brl(10)) == {0, 2, 4, 6, 8} def test_notempty(): def ident_if_even(x): if even(x): yield x brl = notempty(ident_if_even) assert set(brl(4)) == {4} assert set(brl(5)) == {5} def test_chain(): assert list(chain()(2)) == [2] # identity assert list(chain(inc, inc)(2)) == [4] assert list(chain(branch5, inc)(4)) == [4] assert set(chain(branch5, inc)(5)) == {5, 7} assert list(chain(inc, branch5)(5)) == [7] def test_onaction(): L = [] def record(fn, input, output): L.append((input, output)) list(onaction(inc, record)(2)) assert L == [(2, 3)] list(onaction(identity, record)(2)) assert L == [(2, 3)] def test_yieldify(): inc = lambda x: x + 1 yinc = yieldify(inc) assert list(yinc(3)) == [4] def test_do_one(): def bad(expr): raise ValueError() yield False assert list(do_one(inc)(3)) == [4] assert list(do_one(inc, bad)(3)) == [4] assert list(do_one(inc, posdec)(3)) == [4]
feeccc858ff347d422fcf0c16b2c8444463d4aac4bb274d33d4c7146820574a9
from __future__ import (absolute_import, division, print_function) import glob import os import shutil import subprocess import sys import tempfile import warnings from distutils.errors import CompileError from distutils.sysconfig import get_config_var from .runners import ( CCompilerRunner, CppCompilerRunner, FortranCompilerRunner ) from .util import ( get_abspath, make_dirs, copy, Glob, ArbitraryDepthGlob, glob_at_depth, import_module_from_file, pyx_is_cplus, sha256_of_string, sha256_of_file ) sharedext = get_config_var('EXT_SUFFIX' if sys.version_info >= (3, 3) else 'SO') if os.name == 'posix': objext = '.o' elif os.name == 'nt': objext = '.obj' else: warnings.warn("Unknown os.name: {}".format(os.name)) objext = '.o' def compile_sources(files, Runner=None, destdir=None, cwd=None, keep_dir_struct=False, per_file_kwargs=None, **kwargs): """ Compile source code files to object files. Parameters ========== files : iterable of str Paths to source files, if ``cwd`` is given, the paths are taken as relative. Runner: CompilerRunner subclass (optional) Could be e.g. ``FortranCompilerRunner``. Will be inferred from filename extensions if missing. destdir: str Output directory, if cwd is given, the path is taken as relative. cwd: str Working directory. Specify to have compiler run in other directory. also used as root of relative paths. keep_dir_struct: bool Reproduce directory structure in `destdir`. default: ``False`` per_file_kwargs: dict Dict mapping instances in ``files`` to keyword arguments. \\*\\*kwargs: dict Default keyword arguments to pass to ``Runner``. """ _per_file_kwargs = {} if per_file_kwargs is not None: for k, v in per_file_kwargs.items(): if isinstance(k, Glob): for path in glob.glob(k.pathname): _per_file_kwargs[path] = v elif isinstance(k, ArbitraryDepthGlob): for path in glob_at_depth(k.filename, cwd): _per_file_kwargs[path] = v else: _per_file_kwargs[k] = v # Set up destination directory destdir = destdir or '.' if not os.path.isdir(destdir): if os.path.exists(destdir): raise IOError("{} is not a directory".format(destdir)) else: make_dirs(destdir) if cwd is None: cwd = '.' for f in files: copy(f, destdir, only_update=True, dest_is_dir=True) # Compile files and return list of paths to the objects dstpaths = [] for f in files: if keep_dir_struct: name, ext = os.path.splitext(f) else: name, ext = os.path.splitext(os.path.basename(f)) file_kwargs = kwargs.copy() file_kwargs.update(_per_file_kwargs.get(f, {})) dstpaths.append(src2obj(f, Runner, cwd=cwd, **file_kwargs)) return dstpaths def get_mixed_fort_c_linker(vendor=None, cplus=False, cwd=None): vendor = vendor or os.environ.get('SYMPY_COMPILER_VENDOR', 'gnu') if vendor.lower() == 'intel': if cplus: return (FortranCompilerRunner, {'flags': ['-nofor_main', '-cxxlib']}, vendor) else: return (FortranCompilerRunner, {'flags': ['-nofor_main']}, vendor) elif vendor.lower() == 'gnu' or 'llvm': if cplus: return (CppCompilerRunner, {'lib_options': ['fortran']}, vendor) else: return (FortranCompilerRunner, {}, vendor) else: raise ValueError("No vendor found.") def link(obj_files, out_file=None, shared=False, Runner=None, cwd=None, cplus=False, fort=False, **kwargs): """ Link object files. Parameters ========== obj_files: iterable of str Paths to object files. out_file: str (optional) Path to executable/shared library, if ``None`` it will be deduced from the last item in obj_files. shared: bool Generate a shared library? Runner: CompilerRunner subclass (optional) If not given the ``cplus`` and ``fort`` flags will be inspected (fallback is the C compiler). cwd: str Path to the root of relative paths and working directory for compiler. cplus: bool C++ objects? default: ``False``. fort: bool Fortran objects? default: ``False``. \\*\\*kwargs: dict Keyword arguments passed to ``Runner``. Returns ======= The absolute path to the generated shared object / executable. """ if out_file is None: out_file, ext = os.path.splitext(os.path.basename(obj_files[-1])) if shared: out_file += sharedext if not Runner: if fort: Runner, extra_kwargs, vendor = \ get_mixed_fort_c_linker( vendor=kwargs.get('vendor', None), cplus=cplus, cwd=cwd, ) for k, v in extra_kwargs.items(): if k in kwargs: kwargs[k].expand(v) else: kwargs[k] = v else: if cplus: Runner = CppCompilerRunner else: Runner = CCompilerRunner flags = kwargs.pop('flags', []) if shared: if '-shared' not in flags: flags.append('-shared') run_linker = kwargs.pop('run_linker', True) if not run_linker: raise ValueError("run_linker was set to False (nonsensical).") out_file = get_abspath(out_file, cwd=cwd) runner = Runner(obj_files, out_file, flags, cwd=cwd, **kwargs) runner.run() return out_file def link_py_so(obj_files, so_file=None, cwd=None, libraries=None, cplus=False, fort=False, **kwargs): """ Link python extension module (shared object) for importing Parameters ========== obj_files: iterable of str Paths to object files to be linked. so_file: str Name (path) of shared object file to create. If not specified it will have the basname of the last object file in `obj_files` but with the extension '.so' (Unix). cwd: path string Root of relative paths and working directory of linker. libraries: iterable of strings Libraries to link against, e.g. ['m']. cplus: bool Any C++ objects? default: ``False``. fort: bool Any Fortran objects? default: ``False``. kwargs**: dict Keyword arguments passed to ``link(...)``. Returns ======= Absolute path to the generate shared object. """ libraries = libraries or [] include_dirs = kwargs.pop('include_dirs', []) library_dirs = kwargs.pop('library_dirs', []) # from distutils/command/build_ext.py: if sys.platform == "win32": warnings.warn("Windows not yet supported.") elif sys.platform == 'darwin': # Don't use the default code below pass elif sys.platform[:3] == 'aix': # Don't use the default code below pass else: from distutils import sysconfig if sysconfig.get_config_var('Py_ENABLE_SHARED'): ABIFLAGS = sysconfig.get_config_var('ABIFLAGS') pythonlib = 'python{}.{}{}'.format( sys.hexversion >> 24, (sys.hexversion >> 16) & 0xff, ABIFLAGS or '') libraries += [pythonlib] else: pass flags = kwargs.pop('flags', []) needed_flags = ('-pthread',) for flag in needed_flags: if flag not in flags: flags.append(flag) return link(obj_files, shared=True, flags=flags, cwd=cwd, cplus=cplus, fort=fort, include_dirs=include_dirs, libraries=libraries, library_dirs=library_dirs, **kwargs) def simple_cythonize(src, destdir=None, cwd=None, **cy_kwargs): """ Generates a C file from a Cython source file. Parameters ========== src: str Path to Cython source. destdir: str (optional) Path to output directory (default: '.'). cwd: path string (optional) Root of relative paths (default: '.'). **cy_kwargs: Second argument passed to cy_compile. Generates a .cpp file if ``cplus=True`` in ``cy_kwargs``, else a .c file. """ from Cython.Compiler.Main import ( default_options, CompilationOptions ) from Cython.Compiler.Main import compile as cy_compile assert src.lower().endswith('.pyx') or src.lower().endswith('.py') cwd = cwd or '.' destdir = destdir or '.' ext = '.cpp' if cy_kwargs.get('cplus', False) else '.c' c_name = os.path.splitext(os.path.basename(src))[0] + ext dstfile = os.path.join(destdir, c_name) if cwd: ori_dir = os.getcwd() else: ori_dir = '.' os.chdir(cwd) try: cy_options = CompilationOptions(default_options) cy_options.__dict__.update(cy_kwargs) cy_result = cy_compile([src], cy_options) if cy_result.num_errors > 0: raise ValueError("Cython compilation failed.") if os.path.abspath(os.path.dirname(src)) != os.path.abspath(destdir): if os.path.exists(dstfile): os.unlink(dstfile) shutil.move(os.path.join(os.path.dirname(src), c_name), destdir) finally: os.chdir(ori_dir) return dstfile extension_mapping = { '.c': (CCompilerRunner, None), '.cpp': (CppCompilerRunner, None), '.cxx': (CppCompilerRunner, None), '.f': (FortranCompilerRunner, None), '.for': (FortranCompilerRunner, None), '.ftn': (FortranCompilerRunner, None), '.f90': (FortranCompilerRunner, None), # ifort only knows about .f90 '.f95': (FortranCompilerRunner, 'f95'), '.f03': (FortranCompilerRunner, 'f2003'), '.f08': (FortranCompilerRunner, 'f2008'), } def src2obj(srcpath, Runner=None, objpath=None, cwd=None, inc_py=False, **kwargs): """ Compiles a source code file to an object file. Files ending with '.pyx' assumed to be cython files and are dispatched to pyx2obj. Parameters ========== srcpath: str Path to source file. Runner: CompilerRunner subclass (optional) If ``None``: deduced from extension of srcpath. objpath : str (optional) Path to generated object. If ``None``: deduced from ``srcpath``. cwd: str (optional) Working directory and root of relative paths. If ``None``: current dir. inc_py: bool Add Python include path to kwarg "include_dirs". Default: False \\*\\*kwargs: dict keyword arguments passed to Runner or pyx2obj """ name, ext = os.path.splitext(os.path.basename(srcpath)) if objpath is None: if os.path.isabs(srcpath): objpath = '.' else: objpath = os.path.dirname(srcpath) objpath = objpath or '.' # avoid objpath == '' if os.path.isdir(objpath): objpath = os.path.join(objpath, name + objext) include_dirs = kwargs.pop('include_dirs', []) if inc_py: from distutils.sysconfig import get_python_inc py_inc_dir = get_python_inc() if py_inc_dir not in include_dirs: include_dirs.append(py_inc_dir) if ext.lower() == '.pyx': return pyx2obj(srcpath, objpath=objpath, include_dirs=include_dirs, cwd=cwd, **kwargs) if Runner is None: Runner, std = extension_mapping[ext.lower()] if 'std' not in kwargs: kwargs['std'] = std flags = kwargs.pop('flags', []) needed_flags = ('-fPIC',) for flag in needed_flags: if flag not in flags: flags.append(flag) # src2obj implies not running the linker... run_linker = kwargs.pop('run_linker', False) if run_linker: raise CompileError("src2obj called with run_linker=True") runner = Runner([srcpath], objpath, include_dirs=include_dirs, run_linker=run_linker, cwd=cwd, flags=flags, **kwargs) runner.run() return objpath def pyx2obj(pyxpath, objpath=None, destdir=None, cwd=None, include_dirs=None, cy_kwargs=None, cplus=None, **kwargs): """ Convenience function If cwd is specified, pyxpath and dst are taken to be relative If only_update is set to `True` the modification time is checked and compilation is only run if the source is newer than the destination Parameters ========== pyxpath: str Path to Cython source file. objpath: str (optional) Path to object file to generate. destdir: str (optional) Directory to put generated C file. When ``None``: directory of ``objpath``. cwd: str (optional) Working directory and root of relative paths. include_dirs: iterable of path strings (optional) Passed onto src2obj and via cy_kwargs['include_path'] to simple_cythonize. cy_kwargs: dict (optional) Keyword arguments passed onto `simple_cythonize` cplus: bool (optional) Indicate whether C++ is used. default: auto-detect using ``.util.pyx_is_cplus``. compile_kwargs: dict keyword arguments passed onto src2obj Returns ======= Absolute path of generated object file. """ assert pyxpath.endswith('.pyx') cwd = cwd or '.' objpath = objpath or '.' destdir = destdir or os.path.dirname(objpath) abs_objpath = get_abspath(objpath, cwd=cwd) if os.path.isdir(abs_objpath): pyx_fname = os.path.basename(pyxpath) name, ext = os.path.splitext(pyx_fname) objpath = os.path.join(objpath, name + objext) cy_kwargs = cy_kwargs or {} cy_kwargs['output_dir'] = cwd if cplus is None: cplus = pyx_is_cplus(pyxpath) cy_kwargs['cplus'] = cplus interm_c_file = simple_cythonize(pyxpath, destdir=destdir, cwd=cwd, **cy_kwargs) include_dirs = include_dirs or [] flags = kwargs.pop('flags', []) needed_flags = ('-fwrapv', '-pthread', '-fPIC') for flag in needed_flags: if flag not in flags: flags.append(flag) options = kwargs.pop('options', []) if kwargs.pop('strict_aliasing', False): raise CompileError("Cython requires strict aliasing to be disabled.") # Let's be explicit about standard if cplus: std = kwargs.pop('std', 'c++98') else: std = kwargs.pop('std', 'c99') return src2obj(interm_c_file, objpath=objpath, cwd=cwd, include_dirs=include_dirs, flags=flags, std=std, options=options, inc_py=True, strict_aliasing=False, **kwargs) def _any_X(srcs, cls): for src in srcs: name, ext = os.path.splitext(src) key = ext.lower() if key in extension_mapping: if extension_mapping[key][0] == cls: return True return False def any_fortran_src(srcs): return _any_X(srcs, FortranCompilerRunner) def any_cplus_src(srcs): return _any_X(srcs, CppCompilerRunner) def compile_link_import_py_ext(sources, extname=None, build_dir='.', compile_kwargs=None, link_kwargs=None): """ Compiles sources to a shared object (python extension) and imports it Sources in ``sources`` which is imported. If shared object is newer than the sources, they are not recompiled but instead it is imported. Parameters ========== sources : string List of paths to sources. extname : string Name of extension (default: ``None``). If ``None``: taken from the last file in ``sources`` without extension. build_dir: str Path to directory in which objects files etc. are generated. compile_kwargs: dict keyword arguments passed to ``compile_sources`` link_kwargs: dict keyword arguments passed to ``link_py_so`` Returns ======= The imported module from of the python extension. Examples ======== >>> mod = compile_link_import_py_ext(['fft.f90', 'conv.cpp', '_fft.pyx']) # doctest: +SKIP >>> Aprim = mod.fft(A) # doctest: +SKIP """ if extname is None: extname = os.path.splitext(os.path.basename(sources[-1]))[0] compile_kwargs = compile_kwargs or {} link_kwargs = link_kwargs or {} try: mod = import_module_from_file(os.path.join(build_dir, extname), sources) except ImportError: objs = compile_sources(list(map(get_abspath, sources)), destdir=build_dir, cwd=build_dir, **compile_kwargs) so = link_py_so(objs, cwd=build_dir, fort=any_fortran_src(sources), cplus=any_cplus_src(sources), **link_kwargs) mod = import_module_from_file(so) return mod def _write_sources_to_build_dir(sources, build_dir): build_dir = build_dir or tempfile.mkdtemp() if not os.path.isdir(build_dir): raise OSError("Non-existent directory: ", build_dir) source_files = [] for name, src in sources: dest = os.path.join(build_dir, name) differs = True sha256_in_mem = sha256_of_string(src.encode('utf-8')).hexdigest() if os.path.exists(dest): if os.path.exists(dest + '.sha256'): sha256_on_disk = open(dest + '.sha256', 'rt').read() else: sha256_on_disk = sha256_of_file(dest).hexdigest() differs = sha256_on_disk != sha256_in_mem if differs: with open(dest, 'wt') as fh: fh.write(src) open(dest + '.sha256', 'wt').write(sha256_in_mem) source_files.append(dest) return source_files, build_dir def compile_link_import_strings(sources, build_dir=None, **kwargs): """ Compiles, links and imports extension module from source. Parameters ========== sources : iterable of name/source pair tuples build_dir : string (default: None) Path. ``None`` implies use a temporary directory. **kwargs: Keyword arguments passed onto `compile_link_import_py_ext`. Returns ======= mod : module The compiled and imported extension module. info : dict Containing ``build_dir`` as 'build_dir'. """ source_files, build_dir = _write_sources_to_build_dir(sources, build_dir) mod = compile_link_import_py_ext(source_files, build_dir=build_dir, **kwargs) info = dict(build_dir=build_dir) return mod, info def compile_run_strings(sources, build_dir=None, clean=False, compile_kwargs=None, link_kwargs=None): """ Compiles, links and runs a program built from sources. Parameters ========== sources : iterable of name/source pair tuples build_dir : string (default: None) Path. ``None`` implies use a temporary directory. clean : bool Whether to remove build_dir after use. This will only have an effect if ``build_dir`` is ``None`` (which creates a temporary directory). Passing ``clean == True`` and ``build_dir != None`` raises a ``ValueError``. This will also set ``build_dir`` in returned info dictionary to ``None``. compile_kwargs: dict Keyword arguments passed onto ``compile_sources`` link_kwargs: dict Keyword arguments passed onto ``link`` Returns ======= (stdout, stderr): pair of strings info: dict Containing exit status as 'exit_status' and ``build_dir`` as 'build_dir' """ if clean and build_dir is not None: raise ValueError("Automatic removal of build_dir is only available for temporary directory.") try: source_files, build_dir = _write_sources_to_build_dir(sources, build_dir) objs = compile_sources(list(map(get_abspath, source_files)), destdir=build_dir, cwd=build_dir, **(compile_kwargs or {})) prog = link(objs, cwd=build_dir, fort=any_fortran_src(source_files), cplus=any_cplus_src(source_files), **(link_kwargs or {})) p = subprocess.Popen([prog], stdout=subprocess.PIPE, stderr=subprocess.PIPE) exit_status = p.wait() stdout, stderr = [txt.decode('utf-8') for txt in p.communicate()] finally: if clean and os.path.isdir(build_dir): shutil.rmtree(build_dir) build_dir = None info = dict(exit_status=exit_status, build_dir=build_dir) return (stdout, stderr), info
4d557b28b15edd43c3e54f641fe3af7041165c00ed0b93a5c340de82fe117ef7
from __future__ import print_function, division, absolute_import from typing import Callable, Dict, Optional, Tuple, Union from collections import OrderedDict from distutils.errors import CompileError import os import re import subprocess import sys from .util import ( find_binary_of_command, unique_list ) class CompilerRunner(object): """ CompilerRunner base class. Parameters ========== sources : list of str Paths to sources. out : str flags : iterable of str Compiler flags. run_linker : bool compiler_name_exe : (str, str) tuple Tuple of compiler name & command to call. cwd : str Path of root of relative paths. include_dirs : list of str Include directories. libraries : list of str Libraries to link against. library_dirs : list of str Paths to search for shared libraries. std : str Standard string, e.g. ``'c++11'``, ``'c99'``, ``'f2003'``. define: iterable of strings macros to define undef : iterable of strings macros to undefine preferred_vendor : string name of preferred vendor e.g. 'gnu' or 'intel' Methods ======= run(): Invoke compilation as a subprocess. """ # Subclass to vendor/binary dict compiler_dict = None # type: Dict[str, str] # Standards should be a tuple of supported standards # (first one will be the default) standards = None # type: Tuple[Union[None, str], ...] # Subclass to dict of binary/formater-callback std_formater = None # type: Dict[str, Callable[[Optional[str]], str]] # subclass to be e.g. {'gcc': 'gnu', ...} compiler_name_vendor_mapping = None # type: Dict[str, str] def __init__(self, sources, out, flags=None, run_linker=True, compiler=None, cwd='.', include_dirs=None, libraries=None, library_dirs=None, std=None, define=None, undef=None, strict_aliasing=None, preferred_vendor=None, **kwargs): if isinstance(sources, str): raise ValueError("Expected argument sources to be a list of strings.") self.sources = list(sources) self.out = out self.flags = flags or [] self.cwd = cwd if compiler: self.compiler_name, self.compiler_binary = compiler else: # Find a compiler if preferred_vendor is None: preferred_vendor = os.environ.get('SYMPY_COMPILER_VENDOR', None) self.compiler_name, self.compiler_binary, self.compiler_vendor = self.find_compiler(preferred_vendor) if self.compiler_binary is None: raise ValueError("No compiler found (searched: {0})".format(', '.join(self.compiler_dict.values()))) self.define = define or [] self.undef = undef or [] self.include_dirs = include_dirs or [] self.libraries = libraries or [] self.library_dirs = library_dirs or [] self.std = std or self.standards[0] self.run_linker = run_linker if self.run_linker: # both gnu and intel compilers use '-c' for disabling linker self.flags = list(filter(lambda x: x != '-c', self.flags)) else: if '-c' not in self.flags: self.flags.append('-c') if self.std: self.flags.append(self.std_formater[ self.compiler_name](self.std)) self.linkline = [] if strict_aliasing is not None: nsa_re = re.compile("no-strict-aliasing$") sa_re = re.compile("strict-aliasing$") if strict_aliasing is True: if any(map(nsa_re.match, flags)): raise CompileError("Strict aliasing cannot be both enforced and disabled") elif any(map(sa_re.match, flags)): pass # already enforced else: flags.append('-fstrict-aliasing') elif strict_aliasing is False: if any(map(nsa_re.match, flags)): pass # already disabled else: if any(map(sa_re.match, flags)): raise CompileError("Strict aliasing cannot be both enforced and disabled") else: flags.append('-fno-strict-aliasing') else: msg = "Expected argument strict_aliasing to be True/False, got {}" raise ValueError(msg.format(strict_aliasing)) @classmethod def find_compiler(cls, preferred_vendor=None): """ Identify a suitable C/fortran/other compiler. """ candidates = list(cls.compiler_dict.keys()) if preferred_vendor: if preferred_vendor in candidates: candidates = [preferred_vendor]+candidates else: raise ValueError("Unknown vendor {}".format(preferred_vendor)) name, path = find_binary_of_command([cls.compiler_dict[x] for x in candidates]) return name, path, cls.compiler_name_vendor_mapping[name] def cmd(self): """ List of arguments (str) to be passed to e.g. ``subprocess.Popen``. """ cmd = ( [self.compiler_binary] + self.flags + ['-U'+x for x in self.undef] + ['-D'+x for x in self.define] + ['-I'+x for x in self.include_dirs] + self.sources ) if self.run_linker: cmd += (['-L'+x for x in self.library_dirs] + ['-l'+x for x in self.libraries] + self.linkline) counted = [] for envvar in re.findall(r'\$\{(\w+)\}', ' '.join(cmd)): if os.getenv(envvar) is None: if envvar not in counted: counted.append(envvar) msg = "Environment variable '{}' undefined.".format(envvar) raise CompileError(msg) return cmd def run(self): self.flags = unique_list(self.flags) # Append output flag and name to tail of flags self.flags.extend(['-o', self.out]) env = os.environ.copy() env['PWD'] = self.cwd # NOTE: intel compilers seems to need shell=True p = subprocess.Popen(' '.join(self.cmd()), shell=True, cwd=self.cwd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env=env) comm = p.communicate() if sys.version_info[0] == 2: self.cmd_outerr = comm[0] else: try: self.cmd_outerr = comm[0].decode('utf-8') except UnicodeDecodeError: self.cmd_outerr = comm[0].decode('iso-8859-1') # win32 self.cmd_returncode = p.returncode # Error handling if self.cmd_returncode != 0: msg = "Error executing '{0}' in {1} (exited status {2}):\n {3}\n".format( ' '.join(self.cmd()), self.cwd, str(self.cmd_returncode), self.cmd_outerr ) raise CompileError(msg) return self.cmd_outerr, self.cmd_returncode class CCompilerRunner(CompilerRunner): compiler_dict = OrderedDict([ ('gnu', 'gcc'), ('intel', 'icc'), ('llvm', 'clang'), ]) standards = ('c89', 'c90', 'c99', 'c11') # First is default std_formater = { 'gcc': '-std={}'.format, 'icc': '-std={}'.format, 'clang': '-std={}'.format, } compiler_name_vendor_mapping = { 'gcc': 'gnu', 'icc': 'intel', 'clang': 'llvm' } def _mk_flag_filter(cmplr_name): # helper for class initialization not_welcome = {'g++': ("Wimplicit-interface",)} # "Wstrict-prototypes",)} if cmplr_name in not_welcome: def fltr(x): for nw in not_welcome[cmplr_name]: if nw in x: return False return True else: def fltr(x): return True return fltr class CppCompilerRunner(CompilerRunner): compiler_dict = OrderedDict([ ('gnu', 'g++'), ('intel', 'icpc'), ('llvm', 'clang++'), ]) # First is the default, c++0x == c++11 standards = ('c++98', 'c++0x') std_formater = { 'g++': '-std={}'.format, 'icpc': '-std={}'.format, 'clang++': '-std={}'.format, } compiler_name_vendor_mapping = { 'g++': 'gnu', 'icpc': 'intel', 'clang++': 'llvm' } class FortranCompilerRunner(CompilerRunner): standards = (None, 'f77', 'f95', 'f2003', 'f2008') std_formater = { 'gfortran': lambda x: '-std=gnu' if x is None else '-std=legacy' if x == 'f77' else '-std={}'.format(x), 'ifort': lambda x: '-stand f08' if x is None else '-stand f{}'.format(x[-2:]), # f2008 => f08 } compiler_dict = OrderedDict([ ('gnu', 'gfortran'), ('intel', 'ifort'), ]) compiler_name_vendor_mapping = { 'gfortran': 'gnu', 'ifort': 'intel', }
4c181a17d08c7385ebc4dbe70b28ac4161ed721b31f700ed45ddd82b80de9268
from __future__ import (absolute_import, division, print_function) from collections import namedtuple from hashlib import sha256 import os import shutil import sys import tempfile import fnmatch from sympy.testing.pytest import XFAIL def may_xfail(func): if sys.platform.lower() == 'darwin' or os.name == 'nt': # sympy.utilities._compilation needs more testing on Windows and macOS # once those two platforms are reliably supported this xfail decorator # may be removed. return XFAIL(func) else: return func if sys.version_info[0] == 2: class FileNotFoundError(IOError): pass class TemporaryDirectory(object): def __init__(self): self.path = tempfile.mkdtemp() def __enter__(self): return self.path def __exit__(self, exc, value, tb): shutil.rmtree(self.path) else: FileNotFoundError = FileNotFoundError TemporaryDirectory = tempfile.TemporaryDirectory class CompilerNotFoundError(FileNotFoundError): pass def get_abspath(path, cwd='.'): """ Returns the aboslute path. Parameters ========== path : str (relative) path. cwd : str Path to root of relative path. """ if os.path.isabs(path): return path else: if not os.path.isabs(cwd): cwd = os.path.abspath(cwd) return os.path.abspath( os.path.join(cwd, path) ) def make_dirs(path): """ Create directories (equivalent of ``mkdir -p``). """ if path[-1] == '/': parent = os.path.dirname(path[:-1]) else: parent = os.path.dirname(path) if len(parent) > 0: if not os.path.exists(parent): make_dirs(parent) if not os.path.exists(path): os.mkdir(path, 0o777) else: assert os.path.isdir(path) def copy(src, dst, only_update=False, copystat=True, cwd=None, dest_is_dir=False, create_dest_dirs=False): """ Variation of ``shutil.copy`` with extra options. Parameters ========== src : str Path to source file. dst : str Path to destination. only_update : bool Only copy if source is newer than destination (returns None if it was newer), default: ``False``. copystat : bool See ``shutil.copystat``. default: ``True``. cwd : str Path to working directory (root of relative paths). dest_is_dir : bool Ensures that dst is treated as a directory. default: ``False`` create_dest_dirs : bool Creates directories if needed. Returns ======= Path to the copied file. """ if cwd: # Handle working directory if not os.path.isabs(src): src = os.path.join(cwd, src) if not os.path.isabs(dst): dst = os.path.join(cwd, dst) if not os.path.exists(src): # Make sure source file extists raise FileNotFoundError("Source: `{}` does not exist".format(src)) # We accept both (re)naming destination file _or_ # passing a (possible non-existent) destination directory if dest_is_dir: if not dst[-1] == '/': dst = dst+'/' else: if os.path.exists(dst) and os.path.isdir(dst): dest_is_dir = True if dest_is_dir: dest_dir = dst dest_fname = os.path.basename(src) dst = os.path.join(dest_dir, dest_fname) else: dest_dir = os.path.dirname(dst) dest_fname = os.path.basename(dst) if not os.path.exists(dest_dir): if create_dest_dirs: make_dirs(dest_dir) else: raise FileNotFoundError("You must create directory first.") if only_update: # This function is not defined: # XXX: This branch is clearly not tested! if not missing_or_other_newer(dst, src): # noqa return if os.path.islink(dst): dst = os.path.abspath(os.path.realpath(dst), cwd=cwd) shutil.copy(src, dst) if copystat: shutil.copystat(src, dst) return dst Glob = namedtuple('Glob', 'pathname') ArbitraryDepthGlob = namedtuple('ArbitraryDepthGlob', 'filename') def glob_at_depth(filename_glob, cwd=None): if cwd is not None: cwd = '.' globbed = [] for root, dirs, filenames in os.walk(cwd): for fn in filenames: # This is not tested: if fnmatch.fnmatch(fn, filename_glob): globbed.append(os.path.join(root, fn)) return globbed def sha256_of_file(path, nblocks=128): """ Computes the SHA256 hash of a file. Parameters ========== path : string Path to file to compute hash of. nblocks : int Number of blocks to read per iteration. Returns ======= hashlib sha256 hash object. Use ``.digest()`` or ``.hexdigest()`` on returned object to get binary or hex encoded string. """ sh = sha256() with open(path, 'rb') as f: for chunk in iter(lambda: f.read(nblocks*sh.block_size), b''): sh.update(chunk) return sh def sha256_of_string(string): """ Computes the SHA256 hash of a string. """ sh = sha256() sh.update(string) return sh def pyx_is_cplus(path): """ Inspect a Cython source file (.pyx) and look for comment line like: # distutils: language = c++ Returns True if such a file is present in the file, else False. """ for line in open(path, 'rt'): if line.startswith('#') and '=' in line: splitted = line.split('=') if len(splitted) != 2: continue lhs, rhs = splitted if lhs.strip().split()[-1].lower() == 'language' and \ rhs.strip().split()[0].lower() == 'c++': return True return False def import_module_from_file(filename, only_if_newer_than=None): """ Imports python extension (from shared object file) Provide a list of paths in `only_if_newer_than` to check timestamps of dependencies. import_ raises an ImportError if any is newer. Word of warning: The OS may cache shared objects which makes reimporting same path of an shared object file very problematic. It will not detect the new time stamp, nor new checksum, but will instead silently use old module. Use unique names for this reason. Parameters ========== filename : str Path to shared object. only_if_newer_than : iterable of strings Paths to dependencies of the shared object. Raises ====== ``ImportError`` if any of the files specified in ``only_if_newer_than`` are newer than the file given by filename. """ path, name = os.path.split(filename) name, ext = os.path.splitext(name) name = name.split('.')[0] if sys.version_info[0] == 2: from imp import find_module, load_module fobj, filename, data = find_module(name, [path]) if only_if_newer_than: for dep in only_if_newer_than: if os.path.getmtime(filename) < os.path.getmtime(dep): raise ImportError("{} is newer than {}".format(dep, filename)) mod = load_module(name, fobj, filename, data) else: import importlib.util spec = importlib.util.spec_from_file_location(name, filename) if spec is None: raise ImportError("Failed to import: '%s'" % filename) mod = importlib.util.module_from_spec(spec) spec.loader.exec_module(mod) return mod def find_binary_of_command(candidates): """ Finds binary first matching name among candidates. Calls `find_executable` from distuils for provided candidates and returns first hit. Parameters ========== candidates : iterable of str Names of candidate commands Raises ====== CompilerNotFoundError if no candidates match. """ from distutils.spawn import find_executable for c in candidates: binary_path = find_executable(c) if c and binary_path: return c, binary_path raise CompilerNotFoundError('No binary located for candidates: {}'.format(candidates)) def unique_list(l): """ Uniquify a list (skip duplicate items). """ result = [] for x in l: if x not in result: result.append(x) return result
15bbae0f5f160629979cbac173b5d15b52760ce07b72c0c94cbab0c44b2c6b95
# Tests that require installed backends go into # sympy/test_external/test_autowrap import os import tempfile import shutil from sympy.core import symbols, Eq from sympy.core.compatibility import StringIO from sympy.utilities.autowrap import (autowrap, binary_function, CythonCodeWrapper, UfuncifyCodeWrapper, CodeWrapper) from sympy.utilities.codegen import ( CCodeGen, C99CodeGen, CodeGenArgumentListError, make_routine ) from sympy.testing.pytest import raises from sympy.testing.tmpfiles import TmpFileManager def get_string(dump_fn, routines, prefix="file", **kwargs): """Wrapper for dump_fn. dump_fn writes its results to a stream object and this wrapper returns the contents of that stream as a string. This auxiliary function is used by many tests below. The header and the empty lines are not generator to facilitate the testing of the output. """ output = StringIO() dump_fn(routines, output, prefix, **kwargs) source = output.getvalue() output.close() return source def test_cython_wrapper_scalar_function(): x, y, z = symbols('x,y,z') expr = (x + y)*z routine = make_routine("test", expr) code_gen = CythonCodeWrapper(CCodeGen()) source = get_string(code_gen.dump_pyx, [routine]) expected = ( "cdef extern from 'file.h':\n" " double test(double x, double y, double z)\n" "\n" "def test_c(double x, double y, double z):\n" "\n" " return test(x, y, z)") assert source == expected def test_cython_wrapper_outarg(): from sympy import Equality x, y, z = symbols('x,y,z') code_gen = CythonCodeWrapper(C99CodeGen()) routine = make_routine("test", Equality(z, x + y)) source = get_string(code_gen.dump_pyx, [routine]) expected = ( "cdef extern from 'file.h':\n" " void test(double x, double y, double *z)\n" "\n" "def test_c(double x, double y):\n" "\n" " cdef double z = 0\n" " test(x, y, &z)\n" " return z") assert source == expected def test_cython_wrapper_inoutarg(): from sympy import Equality x, y, z = symbols('x,y,z') code_gen = CythonCodeWrapper(C99CodeGen()) routine = make_routine("test", Equality(z, x + y + z)) source = get_string(code_gen.dump_pyx, [routine]) expected = ( "cdef extern from 'file.h':\n" " void test(double x, double y, double *z)\n" "\n" "def test_c(double x, double y, double z):\n" "\n" " test(x, y, &z)\n" " return z") assert source == expected def test_cython_wrapper_compile_flags(): from sympy import Equality x, y, z = symbols('x,y,z') routine = make_routine("test", Equality(z, x + y)) code_gen = CythonCodeWrapper(CCodeGen()) expected = """\ try: from setuptools import setup from setuptools import Extension except ImportError: from distutils.core import setup from distutils.extension import Extension from Cython.Build import cythonize cy_opts = {} ext_mods = [Extension( 'wrapper_module_%(num)s', ['wrapper_module_%(num)s.pyx', 'wrapped_code_%(num)s.c'], include_dirs=[], library_dirs=[], libraries=[], extra_compile_args=['-std=c99'], extra_link_args=[] )] setup(ext_modules=cythonize(ext_mods, **cy_opts)) """ % {'num': CodeWrapper._module_counter} temp_dir = tempfile.mkdtemp() TmpFileManager.tmp_folder(temp_dir) setup_file_path = os.path.join(temp_dir, 'setup.py') code_gen._prepare_files(routine, build_dir=temp_dir) with open(setup_file_path) as f: setup_text = f.read() assert setup_text == expected code_gen = CythonCodeWrapper(CCodeGen(), include_dirs=['/usr/local/include', '/opt/booger/include'], library_dirs=['/user/local/lib'], libraries=['thelib', 'nilib'], extra_compile_args=['-slow-math'], extra_link_args=['-lswamp', '-ltrident'], cythonize_options={'compiler_directives': {'boundscheck': False}} ) expected = """\ try: from setuptools import setup from setuptools import Extension except ImportError: from distutils.core import setup from distutils.extension import Extension from Cython.Build import cythonize cy_opts = {'compiler_directives': {'boundscheck': False}} ext_mods = [Extension( 'wrapper_module_%(num)s', ['wrapper_module_%(num)s.pyx', 'wrapped_code_%(num)s.c'], include_dirs=['/usr/local/include', '/opt/booger/include'], library_dirs=['/user/local/lib'], libraries=['thelib', 'nilib'], extra_compile_args=['-slow-math', '-std=c99'], extra_link_args=['-lswamp', '-ltrident'] )] setup(ext_modules=cythonize(ext_mods, **cy_opts)) """ % {'num': CodeWrapper._module_counter} code_gen._prepare_files(routine, build_dir=temp_dir) with open(setup_file_path) as f: setup_text = f.read() assert setup_text == expected expected = """\ try: from setuptools import setup from setuptools import Extension except ImportError: from distutils.core import setup from distutils.extension import Extension from Cython.Build import cythonize cy_opts = {'compiler_directives': {'boundscheck': False}} import numpy as np ext_mods = [Extension( 'wrapper_module_%(num)s', ['wrapper_module_%(num)s.pyx', 'wrapped_code_%(num)s.c'], include_dirs=['/usr/local/include', '/opt/booger/include', np.get_include()], library_dirs=['/user/local/lib'], libraries=['thelib', 'nilib'], extra_compile_args=['-slow-math', '-std=c99'], extra_link_args=['-lswamp', '-ltrident'] )] setup(ext_modules=cythonize(ext_mods, **cy_opts)) """ % {'num': CodeWrapper._module_counter} code_gen._need_numpy = True code_gen._prepare_files(routine, build_dir=temp_dir) with open(setup_file_path) as f: setup_text = f.read() assert setup_text == expected TmpFileManager.cleanup() def test_cython_wrapper_unique_dummyvars(): from sympy import Dummy, Equality x, y, z = Dummy('x'), Dummy('y'), Dummy('z') x_id, y_id, z_id = [str(d.dummy_index) for d in [x, y, z]] expr = Equality(z, x + y) routine = make_routine("test", expr) code_gen = CythonCodeWrapper(CCodeGen()) source = get_string(code_gen.dump_pyx, [routine]) expected_template = ( "cdef extern from 'file.h':\n" " void test(double x_{x_id}, double y_{y_id}, double *z_{z_id})\n" "\n" "def test_c(double x_{x_id}, double y_{y_id}):\n" "\n" " cdef double z_{z_id} = 0\n" " test(x_{x_id}, y_{y_id}, &z_{z_id})\n" " return z_{z_id}") expected = expected_template.format(x_id=x_id, y_id=y_id, z_id=z_id) assert source == expected def test_autowrap_dummy(): x, y, z = symbols('x y z') # Uses DummyWrapper to test that codegen works as expected f = autowrap(x + y, backend='dummy') assert f() == str(x + y) assert f.args == "x, y" assert f.returns == "nameless" f = autowrap(Eq(z, x + y), backend='dummy') assert f() == str(x + y) assert f.args == "x, y" assert f.returns == "z" f = autowrap(Eq(z, x + y + z), backend='dummy') assert f() == str(x + y + z) assert f.args == "x, y, z" assert f.returns == "z" def test_autowrap_args(): x, y, z = symbols('x y z') raises(CodeGenArgumentListError, lambda: autowrap(Eq(z, x + y), backend='dummy', args=[x])) f = autowrap(Eq(z, x + y), backend='dummy', args=[y, x]) assert f() == str(x + y) assert f.args == "y, x" assert f.returns == "z" raises(CodeGenArgumentListError, lambda: autowrap(Eq(z, x + y + z), backend='dummy', args=[x, y])) f = autowrap(Eq(z, x + y + z), backend='dummy', args=[y, x, z]) assert f() == str(x + y + z) assert f.args == "y, x, z" assert f.returns == "z" f = autowrap(Eq(z, x + y + z), backend='dummy', args=(y, x, z)) assert f() == str(x + y + z) assert f.args == "y, x, z" assert f.returns == "z" def test_autowrap_store_files(): x, y = symbols('x y') tmp = tempfile.mkdtemp() TmpFileManager.tmp_folder(tmp) f = autowrap(x + y, backend='dummy', tempdir=tmp) assert f() == str(x + y) assert os.access(tmp, os.F_OK) TmpFileManager.cleanup() def test_autowrap_store_files_issue_gh12939(): x, y = symbols('x y') tmp = './tmp' try: f = autowrap(x + y, backend='dummy', tempdir=tmp) assert f() == str(x + y) assert os.access(tmp, os.F_OK) finally: shutil.rmtree(tmp) def test_binary_function(): x, y = symbols('x y') f = binary_function('f', x + y, backend='dummy') assert f._imp_() == str(x + y) def test_ufuncify_source(): x, y, z = symbols('x,y,z') code_wrapper = UfuncifyCodeWrapper(C99CodeGen("ufuncify")) routine = make_routine("test", x + y + z) source = get_string(code_wrapper.dump_c, [routine]) expected = """\ #include "Python.h" #include "math.h" #include "numpy/ndarraytypes.h" #include "numpy/ufuncobject.h" #include "numpy/halffloat.h" #include "file.h" static PyMethodDef wrapper_module_%(num)sMethods[] = { {NULL, NULL, 0, NULL} }; static void test_ufunc(char **args, npy_intp *dimensions, npy_intp* steps, void* data) { npy_intp i; npy_intp n = dimensions[0]; char *in0 = args[0]; char *in1 = args[1]; char *in2 = args[2]; char *out0 = args[3]; npy_intp in0_step = steps[0]; npy_intp in1_step = steps[1]; npy_intp in2_step = steps[2]; npy_intp out0_step = steps[3]; for (i = 0; i < n; i++) { *((double *)out0) = test(*(double *)in0, *(double *)in1, *(double *)in2); in0 += in0_step; in1 += in1_step; in2 += in2_step; out0 += out0_step; } } PyUFuncGenericFunction test_funcs[1] = {&test_ufunc}; static char test_types[4] = {NPY_DOUBLE, NPY_DOUBLE, NPY_DOUBLE, NPY_DOUBLE}; static void *test_data[1] = {NULL}; #if PY_VERSION_HEX >= 0x03000000 static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "wrapper_module_%(num)s", NULL, -1, wrapper_module_%(num)sMethods, NULL, NULL, NULL, NULL }; PyMODINIT_FUNC PyInit_wrapper_module_%(num)s(void) { PyObject *m, *d; PyObject *ufunc0; m = PyModule_Create(&moduledef); if (!m) { return NULL; } import_array(); import_umath(); d = PyModule_GetDict(m); ufunc0 = PyUFunc_FromFuncAndData(test_funcs, test_data, test_types, 1, 3, 1, PyUFunc_None, "wrapper_module_%(num)s", "Created in SymPy with Ufuncify", 0); PyDict_SetItemString(d, "test", ufunc0); Py_DECREF(ufunc0); return m; } #else PyMODINIT_FUNC initwrapper_module_%(num)s(void) { PyObject *m, *d; PyObject *ufunc0; m = Py_InitModule("wrapper_module_%(num)s", wrapper_module_%(num)sMethods); if (m == NULL) { return; } import_array(); import_umath(); d = PyModule_GetDict(m); ufunc0 = PyUFunc_FromFuncAndData(test_funcs, test_data, test_types, 1, 3, 1, PyUFunc_None, "wrapper_module_%(num)s", "Created in SymPy with Ufuncify", 0); PyDict_SetItemString(d, "test", ufunc0); Py_DECREF(ufunc0); } #endif""" % {'num': CodeWrapper._module_counter} assert source == expected def test_ufuncify_source_multioutput(): x, y, z = symbols('x,y,z') var_symbols = (x, y, z) expr = x + y**3 + 10*z**2 code_wrapper = UfuncifyCodeWrapper(C99CodeGen("ufuncify")) routines = [make_routine("func{}".format(i), expr.diff(var_symbols[i]), var_symbols) for i in range(len(var_symbols))] source = get_string(code_wrapper.dump_c, routines, funcname='multitest') expected = """\ #include "Python.h" #include "math.h" #include "numpy/ndarraytypes.h" #include "numpy/ufuncobject.h" #include "numpy/halffloat.h" #include "file.h" static PyMethodDef wrapper_module_%(num)sMethods[] = { {NULL, NULL, 0, NULL} }; static void multitest_ufunc(char **args, npy_intp *dimensions, npy_intp* steps, void* data) { npy_intp i; npy_intp n = dimensions[0]; char *in0 = args[0]; char *in1 = args[1]; char *in2 = args[2]; char *out0 = args[3]; char *out1 = args[4]; char *out2 = args[5]; npy_intp in0_step = steps[0]; npy_intp in1_step = steps[1]; npy_intp in2_step = steps[2]; npy_intp out0_step = steps[3]; npy_intp out1_step = steps[4]; npy_intp out2_step = steps[5]; for (i = 0; i < n; i++) { *((double *)out0) = func0(*(double *)in0, *(double *)in1, *(double *)in2); *((double *)out1) = func1(*(double *)in0, *(double *)in1, *(double *)in2); *((double *)out2) = func2(*(double *)in0, *(double *)in1, *(double *)in2); in0 += in0_step; in1 += in1_step; in2 += in2_step; out0 += out0_step; out1 += out1_step; out2 += out2_step; } } PyUFuncGenericFunction multitest_funcs[1] = {&multitest_ufunc}; static char multitest_types[6] = {NPY_DOUBLE, NPY_DOUBLE, NPY_DOUBLE, NPY_DOUBLE, NPY_DOUBLE, NPY_DOUBLE}; static void *multitest_data[1] = {NULL}; #if PY_VERSION_HEX >= 0x03000000 static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "wrapper_module_%(num)s", NULL, -1, wrapper_module_%(num)sMethods, NULL, NULL, NULL, NULL }; PyMODINIT_FUNC PyInit_wrapper_module_%(num)s(void) { PyObject *m, *d; PyObject *ufunc0; m = PyModule_Create(&moduledef); if (!m) { return NULL; } import_array(); import_umath(); d = PyModule_GetDict(m); ufunc0 = PyUFunc_FromFuncAndData(multitest_funcs, multitest_data, multitest_types, 1, 3, 3, PyUFunc_None, "wrapper_module_%(num)s", "Created in SymPy with Ufuncify", 0); PyDict_SetItemString(d, "multitest", ufunc0); Py_DECREF(ufunc0); return m; } #else PyMODINIT_FUNC initwrapper_module_%(num)s(void) { PyObject *m, *d; PyObject *ufunc0; m = Py_InitModule("wrapper_module_%(num)s", wrapper_module_%(num)sMethods); if (m == NULL) { return; } import_array(); import_umath(); d = PyModule_GetDict(m); ufunc0 = PyUFunc_FromFuncAndData(multitest_funcs, multitest_data, multitest_types, 1, 3, 3, PyUFunc_None, "wrapper_module_%(num)s", "Created in SymPy with Ufuncify", 0); PyDict_SetItemString(d, "multitest", ufunc0); Py_DECREF(ufunc0); } #endif""" % {'num': CodeWrapper._module_counter} assert source == expected
d0bf0fb587e4b1ba682ee5665aded500d7815ad0ba1f4fb597c41f19aff829b1
from textwrap import dedent import sys from subprocess import Popen, PIPE import os from sympy.utilities.misc import translate, replace, ordinal, rawlines, strlines def test_translate(): abc = 'abc' translate(abc, None, 'a') == 'bc' translate(abc, None, '') == 'abc' translate(abc, {'a': 'x'}, 'c') == 'xb' assert translate(abc, {'a': 'bc'}, 'c') == 'bcb' assert translate(abc, {'ab': 'x'}, 'c') == 'x' assert translate(abc, {'ab': ''}, 'c') == '' assert translate(abc, {'bc': 'x'}, 'c') == 'ab' assert translate(abc, {'abc': 'x', 'a': 'y'}) == 'x' u = chr(4096) assert translate(abc, 'a', 'x', u) == 'xbc' assert (u in translate(abc, 'a', u, u)) is True def test_replace(): assert replace('abc', ('a', 'b')) == 'bbc' assert replace('abc', {'a': 'Aa'}) == 'Aabc' assert replace('abc', ('a', 'b'), ('c', 'C')) == 'bbC' def test_ordinal(): assert ordinal(-1) == '-1st' assert ordinal(0) == '0th' assert ordinal(1) == '1st' assert ordinal(2) == '2nd' assert ordinal(3) == '3rd' assert all(ordinal(i).endswith('th') for i in range(4, 21)) assert ordinal(100) == '100th' assert ordinal(101) == '101st' assert ordinal(102) == '102nd' assert ordinal(103) == '103rd' assert ordinal(104) == '104th' assert ordinal(200) == '200th' assert all(ordinal(i) == str(i) + 'th' for i in range(-220, -203)) def test_rawlines(): assert rawlines('a a\na') == "dedent('''\\\n a a\n a''')" assert rawlines('a a') == "'a a'" assert rawlines(strlines('\\le"ft')) == ( '(\n' " '(\\n'\n" ' \'r\\\'\\\\le"ft\\\'\\n\'\n' " ')'\n" ')') def test_strlines(): q = 'this quote (") is in the middle' # the following assert rhs was prepared with # print(rawlines(strlines(q, 10))) assert strlines(q, 10) == dedent('''\ ( 'this quo' 'te (") i' 's in the' ' middle' )''') assert q == ( 'this quo' 'te (") i' 's in the' ' middle' ) q = "this quote (') is in the middle" assert strlines(q, 20) == dedent('''\ ( "this quote (') is " "in the middle" )''') assert strlines('\\left') == ( '(\n' "r'\\left'\n" ')') assert strlines('\\left', short=True) == r"r'\left'" assert strlines('\\le"ft') == ( '(\n' 'r\'\\le"ft\'\n' ')') q = 'this\nother line' assert strlines(q) == rawlines(q) def test_translate_args(): try: translate(None, None, None, 'not_none') except ValueError: pass # Exception raised successfully else: assert False assert translate('s', None, None, None) == 's' try: translate('s', 'a', 'bc') except ValueError: pass # Exception raised successfully else: assert False def test_debug_output(): env = os.environ.copy() env['SYMPY_DEBUG'] = 'True' cmd = 'from sympy import *; x = Symbol("x"); print(integrate((1-cos(x))/x, x))' cmdline = [sys.executable, '-c', cmd] proc = Popen(cmdline, env=env, stdout=PIPE, stderr=PIPE) out, err = proc.communicate() out = out.decode('ascii') # utf-8? err = err.decode('ascii') expected = 'substituted: -x*(cos(x) - 1), u: 1/x, u_var: _u' assert expected in err, err
4fe16957be17812a38c6d5de922c46619e2b3e5c952fc0e389ec6faa51e5682b
from sympy.core import S, symbols, Eq, pi, Catalan, EulerGamma, Function from sympy.core.compatibility import StringIO from sympy import Piecewise from sympy import Equality from sympy.matrices import Matrix, MatrixSymbol from sympy.utilities.codegen import OctaveCodeGen, codegen, make_routine from sympy.testing.pytest import raises from sympy.testing.pytest import XFAIL import sympy x, y, z = symbols('x,y,z') def test_empty_m_code(): code_gen = OctaveCodeGen() output = StringIO() code_gen.dump_m([], output, "file", header=False, empty=False) source = output.getvalue() assert source == "" def test_m_simple_code(): name_expr = ("test", (x + y)*z) result, = codegen(name_expr, "Octave", header=False, empty=False) assert result[0] == "test.m" source = result[1] expected = ( "function out1 = test(x, y, z)\n" " out1 = z.*(x + y);\n" "end\n" ) assert source == expected def test_m_simple_code_with_header(): name_expr = ("test", (x + y)*z) result, = codegen(name_expr, "Octave", header=True, empty=False) assert result[0] == "test.m" source = result[1] expected = ( "function out1 = test(x, y, z)\n" " %TEST Autogenerated by sympy\n" " % Code generated with sympy " + sympy.__version__ + "\n" " %\n" " % See http://www.sympy.org/ for more information.\n" " %\n" " % This file is part of 'project'\n" " out1 = z.*(x + y);\n" "end\n" ) assert source == expected def test_m_simple_code_nameout(): expr = Equality(z, (x + y)) name_expr = ("test", expr) result, = codegen(name_expr, "Octave", header=False, empty=False) source = result[1] expected = ( "function z = test(x, y)\n" " z = x + y;\n" "end\n" ) assert source == expected def test_m_numbersymbol(): name_expr = ("test", pi**Catalan) result, = codegen(name_expr, "Octave", header=False, empty=False) source = result[1] expected = ( "function out1 = test()\n" " out1 = pi^%s;\n" "end\n" ) % Catalan.evalf(17) assert source == expected @XFAIL def test_m_numbersymbol_no_inline(): # FIXME: how to pass inline=False to the OctaveCodePrinter? name_expr = ("test", [pi**Catalan, EulerGamma]) result, = codegen(name_expr, "Octave", header=False, empty=False, inline=False) source = result[1] expected = ( "function [out1, out2] = test()\n" " Catalan = 0.915965594177219; % constant\n" " EulerGamma = 0.5772156649015329; % constant\n" " out1 = pi^Catalan;\n" " out2 = EulerGamma;\n" "end\n" ) assert source == expected def test_m_code_argument_order(): expr = x + y routine = make_routine("test", expr, argument_sequence=[z, x, y], language="octave") code_gen = OctaveCodeGen() output = StringIO() code_gen.dump_m([routine], output, "test", header=False, empty=False) source = output.getvalue() expected = ( "function out1 = test(z, x, y)\n" " out1 = x + y;\n" "end\n" ) assert source == expected def test_multiple_results_m(): # Here the output order is the input order expr1 = (x + y)*z expr2 = (x - y)*z name_expr = ("test", [expr1, expr2]) result, = codegen(name_expr, "Octave", header=False, empty=False) source = result[1] expected = ( "function [out1, out2] = test(x, y, z)\n" " out1 = z.*(x + y);\n" " out2 = z.*(x - y);\n" "end\n" ) assert source == expected def test_results_named_unordered(): # Here output order is based on name_expr A, B, C = symbols('A,B,C') expr1 = Equality(C, (x + y)*z) expr2 = Equality(A, (x - y)*z) expr3 = Equality(B, 2*x) name_expr = ("test", [expr1, expr2, expr3]) result, = codegen(name_expr, "Octave", header=False, empty=False) source = result[1] expected = ( "function [C, A, B] = test(x, y, z)\n" " C = z.*(x + y);\n" " A = z.*(x - y);\n" " B = 2*x;\n" "end\n" ) assert source == expected def test_results_named_ordered(): A, B, C = symbols('A,B,C') expr1 = Equality(C, (x + y)*z) expr2 = Equality(A, (x - y)*z) expr3 = Equality(B, 2*x) name_expr = ("test", [expr1, expr2, expr3]) result = codegen(name_expr, "Octave", header=False, empty=False, argument_sequence=(x, z, y)) assert result[0][0] == "test.m" source = result[0][1] expected = ( "function [C, A, B] = test(x, z, y)\n" " C = z.*(x + y);\n" " A = z.*(x - y);\n" " B = 2*x;\n" "end\n" ) assert source == expected def test_complicated_m_codegen(): from sympy import sin, cos, tan name_expr = ("testlong", [ ((sin(x) + cos(y) + tan(z))**3).expand(), cos(cos(cos(cos(cos(cos(cos(cos(x + y + z)))))))) ]) result = codegen(name_expr, "Octave", header=False, empty=False) assert result[0][0] == "testlong.m" source = result[0][1] expected = ( "function [out1, out2] = testlong(x, y, z)\n" " out1 = sin(x).^3 + 3*sin(x).^2.*cos(y) + 3*sin(x).^2.*tan(z)" " + 3*sin(x).*cos(y).^2 + 6*sin(x).*cos(y).*tan(z) + 3*sin(x).*tan(z).^2" " + cos(y).^3 + 3*cos(y).^2.*tan(z) + 3*cos(y).*tan(z).^2 + tan(z).^3;\n" " out2 = cos(cos(cos(cos(cos(cos(cos(cos(x + y + z))))))));\n" "end\n" ) assert source == expected def test_m_output_arg_mixed_unordered(): # named outputs are alphabetical, unnamed output appear in the given order from sympy import sin, cos a = symbols("a") name_expr = ("foo", [cos(2*x), Equality(y, sin(x)), cos(x), Equality(a, sin(2*x))]) result, = codegen(name_expr, "Octave", header=False, empty=False) assert result[0] == "foo.m" source = result[1]; expected = ( 'function [out1, y, out3, a] = foo(x)\n' ' out1 = cos(2*x);\n' ' y = sin(x);\n' ' out3 = cos(x);\n' ' a = sin(2*x);\n' 'end\n' ) assert source == expected def test_m_piecewise_(): pw = Piecewise((0, x < -1), (x**2, x <= 1), (-x+2, x > 1), (1, True), evaluate=False) name_expr = ("pwtest", pw) result, = codegen(name_expr, "Octave", header=False, empty=False) source = result[1] expected = ( "function out1 = pwtest(x)\n" " out1 = ((x < -1).*(0) + (~(x < -1)).*( ...\n" " (x <= 1).*(x.^2) + (~(x <= 1)).*( ...\n" " (x > 1).*(2 - x) + (~(x > 1)).*(1))));\n" "end\n" ) assert source == expected @XFAIL def test_m_piecewise_no_inline(): # FIXME: how to pass inline=False to the OctaveCodePrinter? pw = Piecewise((0, x < -1), (x**2, x <= 1), (-x+2, x > 1), (1, True)) name_expr = ("pwtest", pw) result, = codegen(name_expr, "Octave", header=False, empty=False, inline=False) source = result[1] expected = ( "function out1 = pwtest(x)\n" " if (x < -1)\n" " out1 = 0;\n" " elseif (x <= 1)\n" " out1 = x.^2;\n" " elseif (x > 1)\n" " out1 = -x + 2;\n" " else\n" " out1 = 1;\n" " end\n" "end\n" ) assert source == expected def test_m_multifcns_per_file(): name_expr = [ ("foo", [2*x, 3*y]), ("bar", [y**2, 4*y]) ] result = codegen(name_expr, "Octave", header=False, empty=False) assert result[0][0] == "foo.m" source = result[0][1]; expected = ( "function [out1, out2] = foo(x, y)\n" " out1 = 2*x;\n" " out2 = 3*y;\n" "end\n" "function [out1, out2] = bar(y)\n" " out1 = y.^2;\n" " out2 = 4*y;\n" "end\n" ) assert source == expected def test_m_multifcns_per_file_w_header(): name_expr = [ ("foo", [2*x, 3*y]), ("bar", [y**2, 4*y]) ] result = codegen(name_expr, "Octave", header=True, empty=False) assert result[0][0] == "foo.m" source = result[0][1]; expected = ( "function [out1, out2] = foo(x, y)\n" " %FOO Autogenerated by sympy\n" " % Code generated with sympy " + sympy.__version__ + "\n" " %\n" " % See http://www.sympy.org/ for more information.\n" " %\n" " % This file is part of 'project'\n" " out1 = 2*x;\n" " out2 = 3*y;\n" "end\n" "function [out1, out2] = bar(y)\n" " out1 = y.^2;\n" " out2 = 4*y;\n" "end\n" ) assert source == expected def test_m_filename_match_first_fcn(): name_expr = [ ("foo", [2*x, 3*y]), ("bar", [y**2, 4*y]) ] raises(ValueError, lambda: codegen(name_expr, "Octave", prefix="bar", header=False, empty=False)) def test_m_matrix_named(): e2 = Matrix([[x, 2*y, pi*z]]) name_expr = ("test", Equality(MatrixSymbol('myout1', 1, 3), e2)) result = codegen(name_expr, "Octave", header=False, empty=False) assert result[0][0] == "test.m" source = result[0][1] expected = ( "function myout1 = test(x, y, z)\n" " myout1 = [x 2*y pi*z];\n" "end\n" ) assert source == expected def test_m_matrix_named_matsym(): myout1 = MatrixSymbol('myout1', 1, 3) e2 = Matrix([[x, 2*y, pi*z]]) name_expr = ("test", Equality(myout1, e2, evaluate=False)) result, = codegen(name_expr, "Octave", header=False, empty=False) source = result[1] expected = ( "function myout1 = test(x, y, z)\n" " myout1 = [x 2*y pi*z];\n" "end\n" ) assert source == expected def test_m_matrix_output_autoname(): expr = Matrix([[x, x+y, 3]]) name_expr = ("test", expr) result, = codegen(name_expr, "Octave", header=False, empty=False) source = result[1] expected = ( "function out1 = test(x, y)\n" " out1 = [x x + y 3];\n" "end\n" ) assert source == expected def test_m_matrix_output_autoname_2(): e1 = (x + y) e2 = Matrix([[2*x, 2*y, 2*z]]) e3 = Matrix([[x], [y], [z]]) e4 = Matrix([[x, y], [z, 16]]) name_expr = ("test", (e1, e2, e3, e4)) result, = codegen(name_expr, "Octave", header=False, empty=False) source = result[1] expected = ( "function [out1, out2, out3, out4] = test(x, y, z)\n" " out1 = x + y;\n" " out2 = [2*x 2*y 2*z];\n" " out3 = [x; y; z];\n" " out4 = [x y; z 16];\n" "end\n" ) assert source == expected def test_m_results_matrix_named_ordered(): B, C = symbols('B,C') A = MatrixSymbol('A', 1, 3) expr1 = Equality(C, (x + y)*z) expr2 = Equality(A, Matrix([[1, 2, x]])) expr3 = Equality(B, 2*x) name_expr = ("test", [expr1, expr2, expr3]) result, = codegen(name_expr, "Octave", header=False, empty=False, argument_sequence=(x, z, y)) source = result[1] expected = ( "function [C, A, B] = test(x, z, y)\n" " C = z.*(x + y);\n" " A = [1 2 x];\n" " B = 2*x;\n" "end\n" ) assert source == expected def test_m_matrixsymbol_slice(): A = MatrixSymbol('A', 2, 3) B = MatrixSymbol('B', 1, 3) C = MatrixSymbol('C', 1, 3) D = MatrixSymbol('D', 2, 1) name_expr = ("test", [Equality(B, A[0, :]), Equality(C, A[1, :]), Equality(D, A[:, 2])]) result, = codegen(name_expr, "Octave", header=False, empty=False) source = result[1] expected = ( "function [B, C, D] = test(A)\n" " B = A(1, :);\n" " C = A(2, :);\n" " D = A(:, 3);\n" "end\n" ) assert source == expected def test_m_matrixsymbol_slice2(): A = MatrixSymbol('A', 3, 4) B = MatrixSymbol('B', 2, 2) C = MatrixSymbol('C', 2, 2) name_expr = ("test", [Equality(B, A[0:2, 0:2]), Equality(C, A[0:2, 1:3])]) result, = codegen(name_expr, "Octave", header=False, empty=False) source = result[1] expected = ( "function [B, C] = test(A)\n" " B = A(1:2, 1:2);\n" " C = A(1:2, 2:3);\n" "end\n" ) assert source == expected def test_m_matrixsymbol_slice3(): A = MatrixSymbol('A', 8, 7) B = MatrixSymbol('B', 2, 2) C = MatrixSymbol('C', 4, 2) name_expr = ("test", [Equality(B, A[6:, 1::3]), Equality(C, A[::2, ::3])]) result, = codegen(name_expr, "Octave", header=False, empty=False) source = result[1] expected = ( "function [B, C] = test(A)\n" " B = A(7:end, 2:3:end);\n" " C = A(1:2:end, 1:3:end);\n" "end\n" ) assert source == expected def test_m_matrixsymbol_slice_autoname(): A = MatrixSymbol('A', 2, 3) B = MatrixSymbol('B', 1, 3) name_expr = ("test", [Equality(B, A[0,:]), A[1,:], A[:,0], A[:,1]]) result, = codegen(name_expr, "Octave", header=False, empty=False) source = result[1] expected = ( "function [B, out2, out3, out4] = test(A)\n" " B = A(1, :);\n" " out2 = A(2, :);\n" " out3 = A(:, 1);\n" " out4 = A(:, 2);\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? from sympy.tensor import IndexedBase, Idx from sympy 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_m_tensor_loops_multiple_contractions(): # see comments in previous test about vectorizing from sympy.tensor import IndexedBase, Idx from sympy 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) = A(i, j, k, l).*B(j, k, l) + y(i);\n' ' end\n' ' end\n' ' end\n' ' end\n' 'end\n' ) assert source == expected def test_m_InOutArgument(): expr = Equality(x, x**2) name_expr = ("mysqr", expr) result, = codegen(name_expr, "Octave", header=False, empty=False) source = result[1] expected = ( "function x = mysqr(x)\n" " x = x.^2;\n" "end\n" ) assert source == expected def test_m_InOutArgument_order(): # can specify the order as (x, y) expr = Equality(x, x**2 + y) name_expr = ("test", expr) result, = codegen(name_expr, "Octave", header=False, empty=False, argument_sequence=(x,y)) source = result[1] expected = ( "function x = test(x, y)\n" " x = x.^2 + y;\n" "end\n" ) assert source == expected # make sure it gives (x, y) not (y, x) expr = Equality(x, x**2 + y) name_expr = ("test", expr) result, = codegen(name_expr, "Octave", header=False, empty=False) source = result[1] expected = ( "function x = test(x, y)\n" " x = x.^2 + y;\n" "end\n" ) assert source == expected def test_m_not_supported(): f = Function('f') name_expr = ("test", [f(x).diff(x), S.ComplexInfinity]) result, = codegen(name_expr, "Octave", header=False, empty=False) source = result[1] expected = ( "function [out1, out2] = test(x)\n" " % unsupported: Derivative(f(x), x)\n" " % unsupported: zoo\n" " out1 = Derivative(f(x), x);\n" " out2 = zoo;\n" "end\n" ) assert source == expected 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
1531799362794b3791280897164811bbb23df42efd13050c57ff8914c290e175
import sys import inspect import copy import pickle from sympy.physics.units import meter from sympy.testing.pytest import XFAIL from sympy.core.basic import Atom, Basic from sympy.core.core import BasicMeta from sympy.core.singleton import SingletonRegistry from sympy.core.symbol import Dummy, Symbol, Wild from sympy.core.numbers import (E, I, pi, oo, zoo, nan, Integer, Rational, Float) from sympy.core.relational import (Equality, GreaterThan, LessThan, Relational, StrictGreaterThan, StrictLessThan, Unequality) from sympy.core.add import Add from sympy.core.mul import Mul from sympy.core.power import Pow from sympy.core.function import Derivative, Function, FunctionClass, Lambda, \ WildFunction from sympy.sets.sets import Interval from sympy.core.multidimensional import vectorize from sympy.core.compatibility import HAS_GMPY from sympy.utilities.exceptions import SymPyDeprecationWarning from sympy import symbols, S from sympy.external import import_module cloudpickle = import_module('cloudpickle') excluded_attrs = set([ '_assumptions', # This is a local cache that isn't automatically filled on creation '_mhash', # Cached after __hash__ is called but set to None after creation 'message', # This is an exception attribute that is present but deprecated in Py2 (can be removed when Py2 support is dropped 'is_EmptySet', # Deprecated from SymPy 1.5. This can be removed when is_EmptySet is removed. ]) def check(a, exclude=[], check_attr=True): """ Check that pickling and copying round-trips. """ protocols = [0, 1, 2, copy.copy, copy.deepcopy] # Python 2.x doesn't support the third pickling protocol if sys.version_info >= (3,): protocols.extend([3, 4]) if cloudpickle: protocols.extend([cloudpickle]) for protocol in protocols: if protocol in exclude: continue if callable(protocol): if isinstance(a, BasicMeta): # Classes can't be copied, but that's okay. continue b = protocol(a) elif inspect.ismodule(protocol): b = protocol.loads(protocol.dumps(a)) else: b = pickle.loads(pickle.dumps(a, protocol)) d1 = dir(a) d2 = dir(b) assert set(d1) == set(d2) if not check_attr: continue def c(a, b, d): for i in d: if i in excluded_attrs: continue if not hasattr(a, i): continue attr = getattr(a, i) if not hasattr(attr, "__call__"): assert hasattr(b, i), i assert getattr(b, i) == attr, "%s != %s, protocol: %s" % (getattr(b, i), attr, protocol) c(a, b, d1) c(b, a, d2) #================== core ========================= def test_core_basic(): for c in (Atom, Atom(), Basic, Basic(), # XXX: dynamically created types are not picklable # BasicMeta, BasicMeta("test", (), {}), SingletonRegistry, S): check(c) def test_core_symbol(): # make the Symbol a unique name that doesn't class with any other # testing variable in this file since after this test the symbol # having the same name will be cached as noncommutative for c in (Dummy, Dummy("x", commutative=False), Symbol, Symbol("_issue_3130", commutative=False), Wild, Wild("x")): check(c) def test_core_numbers(): for c in (Integer(2), Rational(2, 3), Float("1.2")): check(c) def test_core_float_copy(): # See gh-7457 y = Symbol("x") + 1.0 check(y) # does not raise TypeError ("argument is not an mpz") def test_core_relational(): x = Symbol("x") y = Symbol("y") for c in (Equality, Equality(x, y), GreaterThan, GreaterThan(x, y), LessThan, LessThan(x, y), Relational, Relational(x, y), StrictGreaterThan, StrictGreaterThan(x, y), StrictLessThan, StrictLessThan(x, y), Unequality, Unequality(x, y)): check(c) def test_core_add(): x = Symbol("x") for c in (Add, Add(x, 4)): check(c) def test_core_mul(): x = Symbol("x") for c in (Mul, Mul(x, 4)): check(c) def test_core_power(): x = Symbol("x") for c in (Pow, Pow(x, 4)): check(c) def test_core_function(): x = Symbol("x") for f in (Derivative, Derivative(x), Function, FunctionClass, Lambda, WildFunction): check(f) def test_core_undefinedfunctions(): f = Function("f") # Full XFAILed test below exclude = list(range(5)) # https://github.com/cloudpipe/cloudpickle/issues/65 # https://github.com/cloudpipe/cloudpickle/issues/190 exclude.append(cloudpickle) check(f, exclude=exclude) @XFAIL def test_core_undefinedfunctions_fail(): # This fails because f is assumed to be a class at sympy.basic.function.f f = Function("f") check(f) def test_core_interval(): for c in (Interval, Interval(0, 2)): check(c) def test_core_multidimensional(): for c in (vectorize, vectorize(0)): check(c) def test_Singletons(): protocols = [0, 1, 2] if sys.version_info >= (3,): protocols.extend([3, 4]) copiers = [copy.copy, copy.deepcopy] copiers += [lambda x: pickle.loads(pickle.dumps(x, proto)) for proto in protocols] if cloudpickle: copiers += [lambda x: cloudpickle.loads(cloudpickle.dumps(x))] for obj in (Integer(-1), Integer(0), Integer(1), Rational(1, 2), pi, E, I, oo, -oo, zoo, nan, S.GoldenRatio, S.TribonacciConstant, S.EulerGamma, S.Catalan, S.EmptySet, S.IdentityFunction): for func in copiers: assert func(obj) is obj #================== functions =================== from sympy.functions import (Piecewise, lowergamma, acosh, chebyshevu, chebyshevt, ln, chebyshevt_root, legendre, Heaviside, bernoulli, coth, tanh, assoc_legendre, sign, arg, asin, DiracDelta, re, rf, Abs, uppergamma, binomial, sinh, cos, cot, acos, acot, gamma, bell, hermite, harmonic, LambertW, zeta, log, factorial, asinh, acoth, cosh, dirichlet_eta, Eijk, loggamma, erf, ceiling, im, fibonacci, tribonacci, conjugate, tan, chebyshevu_root, floor, atanh, sqrt, sin, atan, ff, lucas, atan2, polygamma, exp) def test_functions(): one_var = (acosh, ln, Heaviside, factorial, bernoulli, coth, tanh, sign, arg, asin, DiracDelta, re, Abs, sinh, cos, cot, acos, acot, gamma, bell, harmonic, LambertW, zeta, log, factorial, asinh, acoth, cosh, dirichlet_eta, loggamma, erf, ceiling, im, fibonacci, tribonacci, conjugate, tan, floor, atanh, sin, atan, lucas, exp) two_var = (rf, ff, lowergamma, chebyshevu, chebyshevt, binomial, atan2, polygamma, hermite, legendre, uppergamma) x, y, z = symbols("x,y,z") others = (chebyshevt_root, chebyshevu_root, Eijk(x, y, z), Piecewise( (0, x < -1), (x**2, x <= 1), (x**3, True)), assoc_legendre) for cls in one_var: check(cls) c = cls(x) check(c) for cls in two_var: check(cls) c = cls(x, y) check(c) for cls in others: check(cls) #================== geometry ==================== from sympy.geometry.entity import GeometryEntity from sympy.geometry.point import Point from sympy.geometry.ellipse import Circle, Ellipse from sympy.geometry.line import Line, LinearEntity, Ray, Segment from sympy.geometry.polygon import Polygon, RegularPolygon, Triangle def test_geometry(): p1 = Point(1, 2) p2 = Point(2, 3) p3 = Point(0, 0) p4 = Point(0, 1) for c in ( GeometryEntity, GeometryEntity(), Point, p1, Circle, Circle(p1, 2), Ellipse, Ellipse(p1, 3, 4), Line, Line(p1, p2), LinearEntity, LinearEntity(p1, p2), Ray, Ray(p1, p2), Segment, Segment(p1, p2), Polygon, Polygon(p1, p2, p3, p4), RegularPolygon, RegularPolygon(p1, 4, 5), Triangle, Triangle(p1, p2, p3)): check(c, check_attr=False) #================== integrals ==================== from sympy.integrals.integrals import Integral def test_integrals(): x = Symbol("x") for c in (Integral, Integral(x)): check(c) #==================== logic ===================== from sympy.core.logic import Logic def test_logic(): for c in (Logic, Logic(1)): check(c) #================== matrices ==================== from sympy.matrices import Matrix, SparseMatrix def test_matrices(): for c in (Matrix, Matrix([1, 2, 3]), SparseMatrix, SparseMatrix([[1, 2], [3, 4]])): check(c) #================== ntheory ===================== from sympy.ntheory.generate import Sieve def test_ntheory(): for c in (Sieve, Sieve()): check(c) #================== physics ===================== from sympy.physics.paulialgebra import Pauli from sympy.physics.units import Unit def test_physics(): for c in (Unit, meter, Pauli, Pauli(1)): check(c) #================== plotting ==================== # XXX: These tests are not complete, so XFAIL them @XFAIL def test_plotting(): from sympy.plotting.pygletplot.color_scheme import ColorGradient, ColorScheme from sympy.plotting.pygletplot.managed_window import ManagedWindow from sympy.plotting.plot import Plot, ScreenShot from sympy.plotting.pygletplot.plot_axes import PlotAxes, PlotAxesBase, PlotAxesFrame, PlotAxesOrdinate from sympy.plotting.pygletplot.plot_camera import PlotCamera from sympy.plotting.pygletplot.plot_controller import PlotController from sympy.plotting.pygletplot.plot_curve import PlotCurve from sympy.plotting.pygletplot.plot_interval import PlotInterval from sympy.plotting.pygletplot.plot_mode import PlotMode from sympy.plotting.pygletplot.plot_modes import Cartesian2D, Cartesian3D, Cylindrical, \ ParametricCurve2D, ParametricCurve3D, ParametricSurface, Polar, Spherical from sympy.plotting.pygletplot.plot_object import PlotObject from sympy.plotting.pygletplot.plot_surface import PlotSurface from sympy.plotting.pygletplot.plot_window import PlotWindow for c in ( ColorGradient, ColorGradient(0.2, 0.4), ColorScheme, ManagedWindow, ManagedWindow, Plot, ScreenShot, PlotAxes, PlotAxesBase, PlotAxesFrame, PlotAxesOrdinate, PlotCamera, PlotController, PlotCurve, PlotInterval, PlotMode, Cartesian2D, Cartesian3D, Cylindrical, ParametricCurve2D, ParametricCurve3D, ParametricSurface, Polar, Spherical, PlotObject, PlotSurface, PlotWindow): check(c) @XFAIL def test_plotting2(): #from sympy.plotting.color_scheme import ColorGradient from sympy.plotting.pygletplot.color_scheme import ColorScheme #from sympy.plotting.managed_window import ManagedWindow from sympy.plotting.plot import Plot #from sympy.plotting.plot import ScreenShot from sympy.plotting.pygletplot.plot_axes import PlotAxes #from sympy.plotting.plot_axes import PlotAxesBase, PlotAxesFrame, PlotAxesOrdinate #from sympy.plotting.plot_camera import PlotCamera #from sympy.plotting.plot_controller import PlotController #from sympy.plotting.plot_curve import PlotCurve #from sympy.plotting.plot_interval import PlotInterval #from sympy.plotting.plot_mode import PlotMode #from sympy.plotting.plot_modes import Cartesian2D, Cartesian3D, Cylindrical, \ # ParametricCurve2D, ParametricCurve3D, ParametricSurface, Polar, Spherical #from sympy.plotting.plot_object import PlotObject #from sympy.plotting.plot_surface import PlotSurface # from sympy.plotting.plot_window import PlotWindow check(ColorScheme("rainbow")) check(Plot(1, visible=False)) check(PlotAxes()) #================== polys ======================= from sympy import Poly, ZZ, QQ, lex def test_pickling_polys_polytools(): from sympy.polys.polytools import PurePoly # from sympy.polys.polytools import GroebnerBasis x = Symbol('x') for c in (Poly, Poly(x, x)): check(c) for c in (PurePoly, PurePoly(x)): check(c) # TODO: fix pickling of Options class (see GroebnerBasis._options) # for c in (GroebnerBasis, GroebnerBasis([x**2 - 1], x, order=lex)): # check(c) def test_pickling_polys_polyclasses(): from sympy.polys.polyclasses import DMP, DMF, ANP for c in (DMP, DMP([[ZZ(1)], [ZZ(2)], [ZZ(3)]], ZZ)): check(c) for c in (DMF, DMF(([ZZ(1), ZZ(2)], [ZZ(1), ZZ(3)]), ZZ)): check(c) for c in (ANP, ANP([QQ(1), QQ(2)], [QQ(1), QQ(2), QQ(3)], QQ)): check(c) @XFAIL def test_pickling_polys_rings(): # NOTE: can't use protocols < 2 because we have to execute __new__ to # make sure caching of rings works properly. from sympy.polys.rings import PolyRing ring = PolyRing("x,y,z", ZZ, lex) for c in (PolyRing, ring): check(c, exclude=[0, 1]) for c in (ring.dtype, ring.one): check(c, exclude=[0, 1], check_attr=False) # TODO: Py3k def test_pickling_polys_fields(): pass # NOTE: can't use protocols < 2 because we have to execute __new__ to # make sure caching of fields works properly. # from sympy.polys.fields import FracField # field = FracField("x,y,z", ZZ, lex) # TODO: AssertionError: assert id(obj) not in self.memo # for c in (FracField, field): # check(c, exclude=[0, 1]) # TODO: AssertionError: assert id(obj) not in self.memo # for c in (field.dtype, field.one): # check(c, exclude=[0, 1]) def test_pickling_polys_elements(): from sympy.polys.domains.pythonrational import PythonRational #from sympy.polys.domains.pythonfinitefield import PythonFiniteField #from sympy.polys.domains.mpelements import MPContext for c in (PythonRational, PythonRational(1, 7)): check(c) #gf = PythonFiniteField(17) # TODO: fix pickling of ModularInteger # for c in (gf.dtype, gf(5)): # check(c) #mp = MPContext() # TODO: fix pickling of RealElement # for c in (mp.mpf, mp.mpf(1.0)): # check(c) # TODO: fix pickling of ComplexElement # for c in (mp.mpc, mp.mpc(1.0, -1.5)): # check(c) def test_pickling_polys_domains(): # from sympy.polys.domains.pythonfinitefield import PythonFiniteField from sympy.polys.domains.pythonintegerring import PythonIntegerRing from sympy.polys.domains.pythonrationalfield import PythonRationalField # TODO: fix pickling of ModularInteger # for c in (PythonFiniteField, PythonFiniteField(17)): # check(c) for c in (PythonIntegerRing, PythonIntegerRing()): check(c, check_attr=False) for c in (PythonRationalField, PythonRationalField()): check(c, check_attr=False) if HAS_GMPY: # from sympy.polys.domains.gmpyfinitefield import GMPYFiniteField from sympy.polys.domains.gmpyintegerring import GMPYIntegerRing from sympy.polys.domains.gmpyrationalfield import GMPYRationalField # TODO: fix pickling of ModularInteger # for c in (GMPYFiniteField, GMPYFiniteField(17)): # check(c) for c in (GMPYIntegerRing, GMPYIntegerRing()): check(c, check_attr=False) for c in (GMPYRationalField, GMPYRationalField()): check(c, check_attr=False) #from sympy.polys.domains.realfield import RealField #from sympy.polys.domains.complexfield import ComplexField from sympy.polys.domains.algebraicfield import AlgebraicField #from sympy.polys.domains.polynomialring import PolynomialRing #from sympy.polys.domains.fractionfield import FractionField from sympy.polys.domains.expressiondomain import ExpressionDomain # TODO: fix pickling of RealElement # for c in (RealField, RealField(100)): # check(c) # TODO: fix pickling of ComplexElement # for c in (ComplexField, ComplexField(100)): # check(c) for c in (AlgebraicField, AlgebraicField(QQ, sqrt(3))): check(c, check_attr=False) # TODO: AssertionError # for c in (PolynomialRing, PolynomialRing(ZZ, "x,y,z")): # check(c) # TODO: AttributeError: 'PolyElement' object has no attribute 'ring' # for c in (FractionField, FractionField(ZZ, "x,y,z")): # check(c) for c in (ExpressionDomain, ExpressionDomain()): check(c, check_attr=False) def test_pickling_polys_numberfields(): from sympy.polys.numberfields import AlgebraicNumber for c in (AlgebraicNumber, AlgebraicNumber(sqrt(3))): check(c, check_attr=False) def test_pickling_polys_orderings(): from sympy.polys.orderings import (LexOrder, GradedLexOrder, ReversedGradedLexOrder, InverseOrder) # from sympy.polys.orderings import ProductOrder for c in (LexOrder, LexOrder()): check(c) for c in (GradedLexOrder, GradedLexOrder()): check(c) for c in (ReversedGradedLexOrder, ReversedGradedLexOrder()): check(c) # TODO: Argh, Python is so naive. No lambdas nor inner function support in # pickling module. Maybe someone could figure out what to do with this. # # for c in (ProductOrder, ProductOrder((LexOrder(), lambda m: m[:2]), # (GradedLexOrder(), lambda m: m[2:]))): # check(c) for c in (InverseOrder, InverseOrder(LexOrder())): check(c) def test_pickling_polys_monomials(): from sympy.polys.monomials import MonomialOps, Monomial x, y, z = symbols("x,y,z") for c in (MonomialOps, MonomialOps(3)): check(c) for c in (Monomial, Monomial((1, 2, 3), (x, y, z))): check(c) def test_pickling_polys_errors(): from sympy.polys.polyerrors import (HeuristicGCDFailed, HomomorphismFailed, IsomorphismFailed, ExtraneousFactors, EvaluationFailed, RefinementFailed, CoercionFailed, NotInvertible, NotReversible, NotAlgebraic, DomainError, PolynomialError, UnificationFailed, GeneratorsError, GeneratorsNeeded, UnivariatePolynomialError, MultivariatePolynomialError, OptionError, FlagError) # from sympy.polys.polyerrors import (ExactQuotientFailed, # OperationNotSupported, ComputationFailed, PolificationFailed) # x = Symbol('x') # TODO: TypeError: __init__() takes at least 3 arguments (1 given) # for c in (ExactQuotientFailed, ExactQuotientFailed(x, 3*x, ZZ)): # check(c) # TODO: TypeError: can't pickle instancemethod objects # for c in (OperationNotSupported, OperationNotSupported(Poly(x), Poly.gcd)): # check(c) for c in (HeuristicGCDFailed, HeuristicGCDFailed()): check(c) for c in (HomomorphismFailed, HomomorphismFailed()): check(c) for c in (IsomorphismFailed, IsomorphismFailed()): check(c) for c in (ExtraneousFactors, ExtraneousFactors()): check(c) for c in (EvaluationFailed, EvaluationFailed()): check(c) for c in (RefinementFailed, RefinementFailed()): check(c) for c in (CoercionFailed, CoercionFailed()): check(c) for c in (NotInvertible, NotInvertible()): check(c) for c in (NotReversible, NotReversible()): check(c) for c in (NotAlgebraic, NotAlgebraic()): check(c) for c in (DomainError, DomainError()): check(c) for c in (PolynomialError, PolynomialError()): check(c) for c in (UnificationFailed, UnificationFailed()): check(c) for c in (GeneratorsError, GeneratorsError()): check(c) for c in (GeneratorsNeeded, GeneratorsNeeded()): check(c) # TODO: PicklingError: Can't pickle <function <lambda> at 0x38578c0>: it's not found as __main__.<lambda> # for c in (ComputationFailed, ComputationFailed(lambda t: t, 3, None)): # check(c) for c in (UnivariatePolynomialError, UnivariatePolynomialError()): check(c) for c in (MultivariatePolynomialError, MultivariatePolynomialError()): check(c) # TODO: TypeError: __init__() takes at least 3 arguments (1 given) # for c in (PolificationFailed, PolificationFailed({}, x, x, False)): # check(c) for c in (OptionError, OptionError()): check(c) for c in (FlagError, FlagError()): check(c) #def test_pickling_polys_options(): #from sympy.polys.polyoptions import Options # TODO: fix pickling of `symbols' flag # for c in (Options, Options((), dict(domain='ZZ', polys=False))): # check(c) # TODO: def test_pickling_polys_rootisolation(): # RealInterval # ComplexInterval def test_pickling_polys_rootoftools(): from sympy.polys.rootoftools import CRootOf, RootSum x = Symbol('x') f = x**3 + x + 3 for c in (CRootOf, CRootOf(f, 0)): check(c) for c in (RootSum, RootSum(f, exp)): check(c) #================== printing ==================== from sympy.printing.latex import LatexPrinter from sympy.printing.mathml import MathMLContentPrinter, MathMLPresentationPrinter from sympy.printing.pretty.pretty import PrettyPrinter from sympy.printing.pretty.stringpict import prettyForm, stringPict from sympy.printing.printer import Printer from sympy.printing.python import PythonPrinter def test_printing(): for c in (LatexPrinter, LatexPrinter(), MathMLContentPrinter, MathMLPresentationPrinter, PrettyPrinter, prettyForm, stringPict, stringPict("a"), Printer, Printer(), PythonPrinter, PythonPrinter()): check(c) @XFAIL def test_printing1(): check(MathMLContentPrinter()) @XFAIL def test_printing2(): check(MathMLPresentationPrinter()) @XFAIL def test_printing3(): check(PrettyPrinter()) #================== series ====================== from sympy.series.limits import Limit from sympy.series.order import Order def test_series(): e = Symbol("e") x = Symbol("x") for c in (Limit, Limit(e, x, 1), Order, Order(e)): check(c) #================== concrete ================== from sympy.concrete.products import Product from sympy.concrete.summations import Sum def test_concrete(): x = Symbol("x") for c in (Product, Product(x, (x, 2, 4)), Sum, Sum(x, (x, 2, 4))): check(c) def test_deprecation_warning(): w = SymPyDeprecationWarning('value', 'feature', issue=12345, deprecated_since_version='1.0') check(w)
782f6eb21a1d579c99f1d8e1bb652607cefac1c017fdcdd7bc7c1d715a8f6809
from sympy.core import S, symbols, pi, Catalan, EulerGamma, Function from sympy.core.compatibility import StringIO from sympy import Piecewise from sympy import Equality from sympy.utilities.codegen import RustCodeGen, codegen, make_routine from sympy.testing.pytest import XFAIL import sympy x, y, z = symbols('x,y,z') def test_empty_rust_code(): code_gen = RustCodeGen() output = StringIO() code_gen.dump_rs([], output, "file", header=False, empty=False) source = output.getvalue() assert source == "" def test_simple_rust_code(): name_expr = ("test", (x + y)*z) result, = codegen(name_expr, "Rust", header=False, empty=False) assert result[0] == "test.rs" source = result[1] expected = ( "fn test(x: f64, y: f64, z: f64) -> f64 {\n" " let out1 = z*(x + y);\n" " out1\n" "}\n" ) assert source == expected def test_simple_code_with_header(): name_expr = ("test", (x + y)*z) result, = codegen(name_expr, "Rust", header=True, empty=False) assert result[0] == "test.rs" source = result[1] version_str = "Code generated with sympy %s" % sympy.__version__ version_line = version_str.center(76).rstrip() expected = ( "/*\n" " *%(version_line)s\n" " *\n" " * See http://www.sympy.org/ for more information.\n" " *\n" " * This file is part of 'project'\n" " */\n" "fn test(x: f64, y: f64, z: f64) -> f64 {\n" " let out1 = z*(x + y);\n" " out1\n" "}\n" ) % {'version_line': version_line} assert source == expected def test_simple_code_nameout(): expr = Equality(z, (x + y)) name_expr = ("test", expr) result, = codegen(name_expr, "Rust", header=False, empty=False) source = result[1] expected = ( "fn test(x: f64, y: f64) -> f64 {\n" " let z = x + y;\n" " z\n" "}\n" ) assert source == expected def test_numbersymbol(): name_expr = ("test", pi**Catalan) result, = codegen(name_expr, "Rust", header=False, empty=False) source = result[1] expected = ( "fn test() -> f64 {\n" " const Catalan: f64 = %s;\n" " let out1 = PI.powf(Catalan);\n" " out1\n" "}\n" ) % Catalan.evalf(17) assert source == expected @XFAIL def test_numbersymbol_inline(): # FIXME: how to pass inline to the RustCodePrinter? name_expr = ("test", [pi**Catalan, EulerGamma]) result, = codegen(name_expr, "Rust", header=False, empty=False, inline=True) source = result[1] expected = ( "fn test() -> (f64, f64) {\n" " const Catalan: f64 = %s;\n" " const EulerGamma: f64 = %s;\n" " let out1 = PI.powf(Catalan);\n" " let out2 = EulerGamma);\n" " (out1, out2)\n" "}\n" ) % (Catalan.evalf(17), EulerGamma.evalf(17)) assert source == expected def test_argument_order(): expr = x + y routine = make_routine("test", expr, argument_sequence=[z, x, y], language="rust") code_gen = RustCodeGen() output = StringIO() code_gen.dump_rs([routine], output, "test", header=False, empty=False) source = output.getvalue() expected = ( "fn test(z: f64, x: f64, y: f64) -> f64 {\n" " let out1 = x + y;\n" " out1\n" "}\n" ) assert source == expected def test_multiple_results_rust(): # Here the output order is the input order expr1 = (x + y)*z expr2 = (x - y)*z name_expr = ("test", [expr1, expr2]) result, = codegen(name_expr, "Rust", header=False, empty=False) source = result[1] expected = ( "fn test(x: f64, y: f64, z: f64) -> (f64, f64) {\n" " let out1 = z*(x + y);\n" " let out2 = z*(x - y);\n" " (out1, out2)\n" "}\n" ) assert source == expected def test_results_named_unordered(): # Here output order is based on name_expr A, B, C = symbols('A,B,C') expr1 = Equality(C, (x + y)*z) expr2 = Equality(A, (x - y)*z) expr3 = Equality(B, 2*x) name_expr = ("test", [expr1, expr2, expr3]) result, = codegen(name_expr, "Rust", header=False, empty=False) source = result[1] expected = ( "fn test(x: f64, y: f64, z: f64) -> (f64, f64, f64) {\n" " let C = z*(x + y);\n" " let A = z*(x - y);\n" " let B = 2*x;\n" " (C, A, B)\n" "}\n" ) assert source == expected def test_results_named_ordered(): A, B, C = symbols('A,B,C') expr1 = Equality(C, (x + y)*z) expr2 = Equality(A, (x - y)*z) expr3 = Equality(B, 2*x) name_expr = ("test", [expr1, expr2, expr3]) result = codegen(name_expr, "Rust", header=False, empty=False, argument_sequence=(x, z, y)) assert result[0][0] == "test.rs" source = result[0][1] expected = ( "fn test(x: f64, z: f64, y: f64) -> (f64, f64, f64) {\n" " let C = z*(x + y);\n" " let A = z*(x - y);\n" " let B = 2*x;\n" " (C, A, B)\n" "}\n" ) assert source == expected def test_complicated_rs_codegen(): from sympy import sin, cos, tan name_expr = ("testlong", [ ((sin(x) + cos(y) + tan(z))**3).expand(), cos(cos(cos(cos(cos(cos(cos(cos(x + y + z)))))))) ]) result = codegen(name_expr, "Rust", header=False, empty=False) assert result[0][0] == "testlong.rs" source = result[0][1] expected = ( "fn testlong(x: f64, y: f64, z: f64) -> (f64, f64) {\n" " let out1 = x.sin().powi(3) + 3*x.sin().powi(2)*y.cos()" " + 3*x.sin().powi(2)*z.tan() + 3*x.sin()*y.cos().powi(2)" " + 6*x.sin()*y.cos()*z.tan() + 3*x.sin()*z.tan().powi(2)" " + y.cos().powi(3) + 3*y.cos().powi(2)*z.tan()" " + 3*y.cos()*z.tan().powi(2) + z.tan().powi(3);\n" " let out2 = (x + y + z).cos().cos().cos().cos()" ".cos().cos().cos().cos();\n" " (out1, out2)\n" "}\n" ) assert source == expected def test_output_arg_mixed_unordered(): # named outputs are alphabetical, unnamed output appear in the given order from sympy import sin, cos a = symbols("a") name_expr = ("foo", [cos(2*x), Equality(y, sin(x)), cos(x), Equality(a, sin(2*x))]) result, = codegen(name_expr, "Rust", header=False, empty=False) assert result[0] == "foo.rs" source = result[1]; expected = ( "fn foo(x: f64) -> (f64, f64, f64, f64) {\n" " let out1 = (2*x).cos();\n" " let y = x.sin();\n" " let out3 = x.cos();\n" " let a = (2*x).sin();\n" " (out1, y, out3, a)\n" "}\n" ) assert source == expected def test_piecewise_(): pw = Piecewise((0, x < -1), (x**2, x <= 1), (-x+2, x > 1), (1, True), evaluate=False) name_expr = ("pwtest", pw) result, = codegen(name_expr, "Rust", header=False, empty=False) source = result[1] expected = ( "fn pwtest(x: f64) -> f64 {\n" " let out1 = if (x < -1) {\n" " 0\n" " } else if (x <= 1) {\n" " x.powi(2)\n" " } else if (x > 1) {\n" " 2 - x\n" " } else {\n" " 1\n" " };\n" " out1\n" "}\n" ) assert source == expected @XFAIL def test_piecewise_inline(): # FIXME: how to pass inline to the RustCodePrinter? pw = Piecewise((0, x < -1), (x**2, x <= 1), (-x+2, x > 1), (1, True)) name_expr = ("pwtest", pw) result, = codegen(name_expr, "Rust", header=False, empty=False, inline=True) source = result[1] expected = ( "fn pwtest(x: f64) -> f64 {\n" " let out1 = if (x < -1) { 0 } else if (x <= 1) { x.powi(2) }" " else if (x > 1) { -x + 2 } else { 1 };\n" " out1\n" "}\n" ) assert source == expected def test_multifcns_per_file(): name_expr = [ ("foo", [2*x, 3*y]), ("bar", [y**2, 4*y]) ] result = codegen(name_expr, "Rust", header=False, empty=False) assert result[0][0] == "foo.rs" source = result[0][1]; expected = ( "fn foo(x: f64, y: f64) -> (f64, f64) {\n" " let out1 = 2*x;\n" " let out2 = 3*y;\n" " (out1, out2)\n" "}\n" "fn bar(y: f64) -> (f64, f64) {\n" " let out1 = y.powi(2);\n" " let out2 = 4*y;\n" " (out1, out2)\n" "}\n" ) assert source == expected def test_multifcns_per_file_w_header(): name_expr = [ ("foo", [2*x, 3*y]), ("bar", [y**2, 4*y]) ] result = codegen(name_expr, "Rust", header=True, empty=False) assert result[0][0] == "foo.rs" source = result[0][1]; version_str = "Code generated with sympy %s" % sympy.__version__ version_line = version_str.center(76).rstrip() expected = ( "/*\n" " *%(version_line)s\n" " *\n" " * See http://www.sympy.org/ for more information.\n" " *\n" " * This file is part of 'project'\n" " */\n" "fn foo(x: f64, y: f64) -> (f64, f64) {\n" " let out1 = 2*x;\n" " let out2 = 3*y;\n" " (out1, out2)\n" "}\n" "fn bar(y: f64) -> (f64, f64) {\n" " let out1 = y.powi(2);\n" " let out2 = 4*y;\n" " (out1, out2)\n" "}\n" ) % {'version_line': version_line} assert source == expected def test_filename_match_prefix(): name_expr = [ ("foo", [2*x, 3*y]), ("bar", [y**2, 4*y]) ] result, = codegen(name_expr, "Rust", prefix="baz", header=False, empty=False) assert result[0] == "baz.rs" def test_InOutArgument(): expr = Equality(x, x**2) name_expr = ("mysqr", expr) result, = codegen(name_expr, "Rust", header=False, empty=False) source = result[1] expected = ( "fn mysqr(x: f64) -> f64 {\n" " let x = x.powi(2);\n" " x\n" "}\n" ) assert source == expected def test_InOutArgument_order(): # can specify the order as (x, y) expr = Equality(x, x**2 + y) name_expr = ("test", expr) result, = codegen(name_expr, "Rust", header=False, empty=False, argument_sequence=(x,y)) source = result[1] expected = ( "fn test(x: f64, y: f64) -> f64 {\n" " let x = x.powi(2) + y;\n" " x\n" "}\n" ) assert source == expected # make sure it gives (x, y) not (y, x) expr = Equality(x, x**2 + y) name_expr = ("test", expr) result, = codegen(name_expr, "Rust", header=False, empty=False) source = result[1] expected = ( "fn test(x: f64, y: f64) -> f64 {\n" " let x = x.powi(2) + y;\n" " x\n" "}\n" ) assert source == expected def test_not_supported(): f = Function('f') name_expr = ("test", [f(x).diff(x), S.ComplexInfinity]) result, = codegen(name_expr, "Rust", header=False, empty=False) source = result[1] expected = ( "fn test(x: f64) -> (f64, f64) {\n" " // unsupported: Derivative(f(x), x)\n" " // unsupported: zoo\n" " let out1 = Derivative(f(x), x);\n" " let out2 = zoo;\n" " (out1, out2)\n" "}\n" ) assert source == expected def test_global_vars_rust(): x, y, z, t = symbols("x y z t") result = codegen(('f', x*y), "Rust", header=False, empty=False, global_vars=(y,)) source = result[0][1] expected = ( "fn f(x: f64) -> f64 {\n" " let out1 = x*y;\n" " out1\n" "}\n" ) assert source == expected result = codegen(('f', x*y+z), "Rust", header=False, empty=False, argument_sequence=(x, y), global_vars=(z, t)) source = result[0][1] expected = ( "fn f(x: f64, y: f64) -> f64 {\n" " let out1 = x*y + z;\n" " out1\n" "}\n" ) assert source == expected
ff37cbc6daf09d3053cf43dd143b957b54c8ad09c8a2db0c39abda8e9e22ccdf
from itertools import zip_longest from sympy.utilities.enumerative import ( list_visitor, MultisetPartitionTraverser, multiset_partitions_taocp ) from sympy.utilities.iterables import _set_partitions # first some functions only useful as test scaffolding - these provide # straightforward, but slow reference implementations against which to # compare the real versions, and also a comparison to verify that # different versions are giving identical results. def part_range_filter(partition_iterator, lb, ub): """ Filters (on the number of parts) a multiset partition enumeration Arguments ========= lb, and ub are a range (in the python slice sense) on the lpart variable returned from a multiset partition enumeration. Recall that lpart is 0-based (it points to the topmost part on the part stack), so if you want to return parts of sizes 2,3,4,5 you would use lb=1 and ub=5. """ for state in partition_iterator: f, lpart, pstack = state if lpart >= lb and lpart < ub: yield state def multiset_partitions_baseline(multiplicities, components): """Enumerates partitions of a multiset Parameters ========== multiplicities list of integer multiplicities of the components of the multiset. components the components (elements) themselves Returns ======= Set of partitions. Each partition is tuple of parts, and each part is a tuple of components (with repeats to indicate multiplicity) Notes ===== Multiset partitions can be created as equivalence classes of set partitions, and this function does just that. This approach is slow and memory intensive compared to the more advanced algorithms available, but the code is simple and easy to understand. Hence this routine is strictly for testing -- to provide a straightforward baseline against which to regress the production versions. (This code is a simplified version of an earlier production implementation.) """ canon = [] # list of components with repeats for ct, elem in zip(multiplicities, components): canon.extend([elem]*ct) # accumulate the multiset partitions in a set to eliminate dups cache = set() n = len(canon) for nc, q in _set_partitions(n): rv = [[] for i in range(nc)] for i in range(n): rv[q[i]].append(canon[i]) canonical = tuple( sorted([tuple(p) for p in rv])) cache.add(canonical) return cache def compare_multiset_w_baseline(multiplicities): """ Enumerates the partitions of multiset with AOCP algorithm and baseline implementation, and compare the results. """ letters = "abcdefghijklmnopqrstuvwxyz" bl_partitions = multiset_partitions_baseline(multiplicities, letters) # The partitions returned by the different algorithms may have # their parts in different orders. Also, they generate partitions # in different orders. Hence the sorting, and set comparison. aocp_partitions = set() for state in multiset_partitions_taocp(multiplicities): p1 = tuple(sorted( [tuple(p) for p in list_visitor(state, letters)])) aocp_partitions.add(p1) assert bl_partitions == aocp_partitions def compare_multiset_states(s1, s2): """compare for equality two instances of multiset partition states This is useful for comparing different versions of the algorithm to verify correctness.""" # Comparison is physical, the only use of semantics is to ignore # trash off the top of the stack. f1, lpart1, pstack1 = s1 f2, lpart2, pstack2 = s2 if (lpart1 == lpart2) and (f1[0:lpart1+1] == f2[0:lpart2+1]): if pstack1[0:f1[lpart1+1]] == pstack2[0:f2[lpart2+1]]: return True return False def test_multiset_partitions_taocp(): """Compares the output of multiset_partitions_taocp with a baseline (set partition based) implementation.""" # Test cases should not be too large, since the baseline # implementation is fairly slow. multiplicities = [2,2] compare_multiset_w_baseline(multiplicities) multiplicities = [4,3,1] compare_multiset_w_baseline(multiplicities) def test_multiset_partitions_versions(): """Compares Knuth-based versions of multiset_partitions""" multiplicities = [5,2,2,1] m = MultisetPartitionTraverser() for s1, s2 in zip_longest(m.enum_all(multiplicities), multiset_partitions_taocp(multiplicities)): assert compare_multiset_states(s1, s2) def subrange_exercise(mult, lb, ub): """Compare filter-based and more optimized subrange implementations Helper for tests, called with both small and larger multisets. """ m = MultisetPartitionTraverser() assert m.count_partitions(mult) == \ m.count_partitions_slow(mult) # Note - multiple traversals from the same # MultisetPartitionTraverser object cannot execute at the same # time, hence make several instances here. ma = MultisetPartitionTraverser() mc = MultisetPartitionTraverser() md = MultisetPartitionTraverser() # Several paths to compute just the size two partitions a_it = ma.enum_range(mult, lb, ub) b_it = part_range_filter(multiset_partitions_taocp(mult), lb, ub) c_it = part_range_filter(mc.enum_small(mult, ub), lb, sum(mult)) d_it = part_range_filter(md.enum_large(mult, lb), 0, ub) for sa, sb, sc, sd in zip_longest(a_it, b_it, c_it, d_it): assert compare_multiset_states(sa, sb) assert compare_multiset_states(sa, sc) assert compare_multiset_states(sa, sd) def test_subrange(): # Quick, but doesn't hit some of the corner cases mult = [4,4,2,1] # mississippi lb = 1 ub = 2 subrange_exercise(mult, lb, ub) def test_subrange_large(): # takes a second or so, depending on cpu, Python version, etc. mult = [6,3,2,1] lb = 4 ub = 7 subrange_exercise(mult, lb, ub)
11707b8e54709b40c7247c4cb663925ef7dcc96b9bab068f5c8bca381efd3948
from sympy.testing.pytest import warns_deprecated_sympy, XFAIL # See https://github.com/sympy/sympy/pull/18095 def test_deprecated_utilities(): with warns_deprecated_sympy(): import sympy.utilities.pytest # noqa:F401 with warns_deprecated_sympy(): import sympy.utilities.runtests # noqa:F401 with warns_deprecated_sympy(): import sympy.utilities.randtest # noqa:F401 with warns_deprecated_sympy(): import sympy.utilities.tmpfiles # noqa:F401 with warns_deprecated_sympy(): import sympy.utilities.quality_unicode # noqa:F401 # This fails because benchmarking isn't importable... @XFAIL def test_deprecated_benchmarking(): with warns_deprecated_sympy(): import sympy.utilities.benchmarking # noqa:F401
d1ad571a8815a1998e78ebfd0b6e6e470b00a1b88fe233997a1305533922eb60
from itertools import product import math import inspect import mpmath from sympy.testing.pytest import raises from sympy import ( symbols, lambdify, sqrt, sin, cos, tan, pi, acos, acosh, Rational, Float, Matrix, Lambda, Piecewise, exp, E, Integral, oo, I, Abs, Function, true, false, And, Or, Not, ITE, Min, Max, floor, diff, IndexedBase, Sum, DotProduct, Eq, Dummy, sinc, erf, erfc, factorial, gamma, loggamma, digamma, RisingFactorial, besselj, bessely, besseli, besselk, S, beta, MatrixSymbol, fresnelc, fresnels) from sympy.functions.elementary.complexes import re, im, arg from sympy.functions.special.polynomials import \ chebyshevt, chebyshevu, legendre, hermite, laguerre, gegenbauer, \ assoc_legendre, assoc_laguerre, jacobi from sympy.printing.lambdarepr import LambdaPrinter from sympy.printing.pycode import NumPyPrinter from sympy.utilities.lambdify import implemented_function, lambdastr from sympy.testing.pytest import skip from sympy.utilities.decorator import conserve_mpmath_dps from sympy.external import import_module from sympy.functions.special.gamma_functions import uppergamma, lowergamma import sympy MutableDenseMatrix = Matrix numpy = import_module('numpy') scipy = import_module('scipy') numexpr = import_module('numexpr') tensorflow = import_module('tensorflow') if tensorflow: # Hide Tensorflow warnings import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' w, x, y, z = symbols('w,x,y,z') #================== Test different arguments ======================= def test_no_args(): f = lambdify([], 1) raises(TypeError, lambda: f(-1)) assert f() == 1 def test_single_arg(): f = lambdify(x, 2*x) assert f(1) == 2 def test_list_args(): f = lambdify([x, y], x + y) assert f(1, 2) == 3 def test_nested_args(): f1 = lambdify([[w, x]], [w, x]) assert f1([91, 2]) == [91, 2] raises(TypeError, lambda: f1(1, 2)) f2 = lambdify([(w, x), (y, z)], [w, x, y, z]) assert f2((18, 12), (73, 4)) == [18, 12, 73, 4] raises(TypeError, lambda: f2(3, 4)) f3 = lambdify([w, [[[x]], y], z], [w, x, y, z]) assert f3(10, [[[52]], 31], 44) == [10, 52, 31, 44] def test_str_args(): f = lambdify('x,y,z', 'z,y,x') assert f(3, 2, 1) == (1, 2, 3) assert f(1.0, 2.0, 3.0) == (3.0, 2.0, 1.0) # make sure correct number of args required raises(TypeError, lambda: f(0)) def test_own_namespace_1(): myfunc = lambda x: 1 f = lambdify(x, sin(x), {"sin": myfunc}) assert f(0.1) == 1 assert f(100) == 1 def test_own_namespace_2(): def myfunc(x): return 1 f = lambdify(x, sin(x), {'sin': myfunc}) assert f(0.1) == 1 assert f(100) == 1 def test_own_module(): f = lambdify(x, sin(x), math) assert f(0) == 0.0 def test_bad_args(): # no vargs given raises(TypeError, lambda: lambdify(1)) # same with vector exprs raises(TypeError, lambda: lambdify([1, 2])) def test_atoms(): # Non-Symbol atoms should not be pulled out from the expression namespace f = lambdify(x, pi + x, {"pi": 3.14}) assert f(0) == 3.14 f = lambdify(x, I + x, {"I": 1j}) assert f(1) == 1 + 1j #================== Test different modules ========================= # high precision output of sin(0.2*pi) is used to detect if precision is lost unwanted @conserve_mpmath_dps def test_sympy_lambda(): mpmath.mp.dps = 50 sin02 = mpmath.mpf("0.19866933079506121545941262711838975037020672954020") f = lambdify(x, sin(x), "sympy") assert f(x) == sin(x) prec = 1e-15 assert -prec < f(Rational(1, 5)).evalf() - Float(str(sin02)) < prec # arctan is in numpy module and should not be available # The arctan below gives NameError. What is this supposed to test? # raises(NameError, lambda: lambdify(x, arctan(x), "sympy")) @conserve_mpmath_dps def test_math_lambda(): mpmath.mp.dps = 50 sin02 = mpmath.mpf("0.19866933079506121545941262711838975037020672954020") f = lambdify(x, sin(x), "math") prec = 1e-15 assert -prec < f(0.2) - sin02 < prec raises(TypeError, lambda: f(x)) # if this succeeds, it can't be a python math function @conserve_mpmath_dps def test_mpmath_lambda(): mpmath.mp.dps = 50 sin02 = mpmath.mpf("0.19866933079506121545941262711838975037020672954020") f = lambdify(x, sin(x), "mpmath") prec = 1e-49 # mpmath precision is around 50 decimal places assert -prec < f(mpmath.mpf("0.2")) - sin02 < prec raises(TypeError, lambda: f(x)) # if this succeeds, it can't be a mpmath function @conserve_mpmath_dps def test_number_precision(): mpmath.mp.dps = 50 sin02 = mpmath.mpf("0.19866933079506121545941262711838975037020672954020") f = lambdify(x, sin02, "mpmath") prec = 1e-49 # mpmath precision is around 50 decimal places assert -prec < f(0) - sin02 < prec @conserve_mpmath_dps def test_mpmath_precision(): mpmath.mp.dps = 100 assert str(lambdify((), pi.evalf(100), 'mpmath')()) == str(pi.evalf(100)) #================== Test Translations ============================== # We can only check if all translated functions are valid. It has to be checked # by hand if they are complete. def test_math_transl(): from sympy.utilities.lambdify import MATH_TRANSLATIONS for sym, mat in MATH_TRANSLATIONS.items(): assert sym in sympy.__dict__ assert mat in math.__dict__ def test_mpmath_transl(): from sympy.utilities.lambdify import MPMATH_TRANSLATIONS for sym, mat in MPMATH_TRANSLATIONS.items(): assert sym in sympy.__dict__ or sym == 'Matrix' assert mat in mpmath.__dict__ def test_numpy_transl(): if not numpy: skip("numpy not installed.") from sympy.utilities.lambdify import NUMPY_TRANSLATIONS for sym, nump in NUMPY_TRANSLATIONS.items(): assert sym in sympy.__dict__ assert nump in numpy.__dict__ def test_scipy_transl(): if not scipy: skip("scipy not installed.") from sympy.utilities.lambdify import SCIPY_TRANSLATIONS for sym, scip in SCIPY_TRANSLATIONS.items(): assert sym in sympy.__dict__ assert scip in scipy.__dict__ or scip in scipy.special.__dict__ def test_numpy_translation_abs(): if not numpy: skip("numpy not installed.") f = lambdify(x, Abs(x), "numpy") assert f(-1) == 1 assert f(1) == 1 def test_numexpr_printer(): if not numexpr: skip("numexpr not installed.") # if translation/printing is done incorrectly then evaluating # a lambdified numexpr expression will throw an exception from sympy.printing.lambdarepr import NumExprPrinter blacklist = ('where', 'complex', 'contains') arg_tuple = (x, y, z) # some functions take more than one argument for sym in NumExprPrinter._numexpr_functions.keys(): if sym in blacklist: continue ssym = S(sym) if hasattr(ssym, '_nargs'): nargs = ssym._nargs[0] else: nargs = 1 args = arg_tuple[:nargs] f = lambdify(args, ssym(*args), modules='numexpr') assert f(*(1, )*nargs) is not None def test_issue_9334(): if not numexpr: skip("numexpr not installed.") if not numpy: skip("numpy not installed.") expr = S('b*a - sqrt(a**2)') a, b = sorted(expr.free_symbols, key=lambda s: s.name) func_numexpr = lambdify((a,b), expr, modules=[numexpr], dummify=False) foo, bar = numpy.random.random((2, 4)) func_numexpr(foo, bar) def test_issue_12984(): import warnings if not numexpr: skip("numexpr not installed.") func_numexpr = lambdify((x,y,z), Piecewise((y, x >= 0), (z, x > -1)), numexpr) assert func_numexpr(1, 24, 42) == 24 with warnings.catch_warnings(): warnings.simplefilter("ignore", RuntimeWarning) assert str(func_numexpr(-1, 24, 42)) == 'nan' #================== Test some functions ============================ def test_exponentiation(): f = lambdify(x, x**2) assert f(-1) == 1 assert f(0) == 0 assert f(1) == 1 assert f(-2) == 4 assert f(2) == 4 assert f(2.5) == 6.25 def test_sqrt(): f = lambdify(x, sqrt(x)) assert f(0) == 0.0 assert f(1) == 1.0 assert f(4) == 2.0 assert abs(f(2) - 1.414) < 0.001 assert f(6.25) == 2.5 def test_trig(): f = lambdify([x], [cos(x), sin(x)], 'math') d = f(pi) prec = 1e-11 assert -prec < d[0] + 1 < prec assert -prec < d[1] < prec d = f(3.14159) prec = 1e-5 assert -prec < d[0] + 1 < prec assert -prec < d[1] < prec #================== Test vectors =================================== def test_vector_simple(): f = lambdify((x, y, z), (z, y, x)) assert f(3, 2, 1) == (1, 2, 3) assert f(1.0, 2.0, 3.0) == (3.0, 2.0, 1.0) # make sure correct number of args required raises(TypeError, lambda: f(0)) def test_vector_discontinuous(): f = lambdify(x, (-1/x, 1/x)) raises(ZeroDivisionError, lambda: f(0)) assert f(1) == (-1.0, 1.0) assert f(2) == (-0.5, 0.5) assert f(-2) == (0.5, -0.5) def test_trig_symbolic(): f = lambdify([x], [cos(x), sin(x)], 'math') d = f(pi) assert abs(d[0] + 1) < 0.0001 assert abs(d[1] - 0) < 0.0001 def test_trig_float(): f = lambdify([x], [cos(x), sin(x)]) d = f(3.14159) assert abs(d[0] + 1) < 0.0001 assert abs(d[1] - 0) < 0.0001 def test_docs(): f = lambdify(x, x**2) assert f(2) == 4 f = lambdify([x, y, z], [z, y, x]) assert f(1, 2, 3) == [3, 2, 1] f = lambdify(x, sqrt(x)) assert f(4) == 2.0 f = lambdify((x, y), sin(x*y)**2) assert f(0, 5) == 0 def test_math(): f = lambdify((x, y), sin(x), modules="math") assert f(0, 5) == 0 def test_sin(): f = lambdify(x, sin(x)**2) assert isinstance(f(2), float) f = lambdify(x, sin(x)**2, modules="math") assert isinstance(f(2), float) def test_matrix(): A = Matrix([[x, x*y], [sin(z) + 4, x**z]]) sol = Matrix([[1, 2], [sin(3) + 4, 1]]) f = lambdify((x, y, z), A, modules="sympy") assert f(1, 2, 3) == sol f = lambdify((x, y, z), (A, [A]), modules="sympy") assert f(1, 2, 3) == (sol, [sol]) J = Matrix((x, x + y)).jacobian((x, y)) v = Matrix((x, y)) sol = Matrix([[1, 0], [1, 1]]) assert lambdify(v, J, modules='sympy')(1, 2) == sol assert lambdify(v.T, J, modules='sympy')(1, 2) == sol def test_numpy_matrix(): if not numpy: skip("numpy not installed.") A = Matrix([[x, x*y], [sin(z) + 4, x**z]]) sol_arr = numpy.array([[1, 2], [numpy.sin(3) + 4, 1]]) #Lambdify array first, to ensure return to array as default f = lambdify((x, y, z), A, ['numpy']) numpy.testing.assert_allclose(f(1, 2, 3), sol_arr) #Check that the types are arrays and matrices assert isinstance(f(1, 2, 3), numpy.ndarray) # gh-15071 class dot(Function): pass x_dot_mtx = dot(x, Matrix([[2], [1], [0]])) f_dot1 = lambdify(x, x_dot_mtx) inp = numpy.zeros((17, 3)) assert numpy.all(f_dot1(inp) == 0) strict_kw = dict(allow_unknown_functions=False, inline=True, fully_qualified_modules=False) p2 = NumPyPrinter(dict(user_functions={'dot': 'dot'}, **strict_kw)) f_dot2 = lambdify(x, x_dot_mtx, printer=p2) assert numpy.all(f_dot2(inp) == 0) p3 = NumPyPrinter(strict_kw) # The line below should probably fail upon construction (before calling with "(inp)"): raises(Exception, lambda: lambdify(x, x_dot_mtx, printer=p3)(inp)) def test_numpy_transpose(): if not numpy: skip("numpy not installed.") A = Matrix([[1, x], [0, 1]]) f = lambdify((x), A.T, modules="numpy") numpy.testing.assert_array_equal(f(2), numpy.array([[1, 0], [2, 1]])) def test_numpy_dotproduct(): if not numpy: skip("numpy not installed") A = Matrix([x, y, z]) f1 = lambdify([x, y, z], DotProduct(A, A), modules='numpy') f2 = lambdify([x, y, z], DotProduct(A, A.T), modules='numpy') f3 = lambdify([x, y, z], DotProduct(A.T, A), modules='numpy') f4 = lambdify([x, y, z], DotProduct(A, A.T), modules='numpy') assert f1(1, 2, 3) == \ f2(1, 2, 3) == \ f3(1, 2, 3) == \ f4(1, 2, 3) == \ numpy.array([14]) def test_numpy_inverse(): if not numpy: skip("numpy not installed.") A = Matrix([[1, x], [0, 1]]) f = lambdify((x), A**-1, modules="numpy") numpy.testing.assert_array_equal(f(2), numpy.array([[1, -2], [0, 1]])) def test_numpy_old_matrix(): if not numpy: skip("numpy not installed.") A = Matrix([[x, x*y], [sin(z) + 4, x**z]]) sol_arr = numpy.array([[1, 2], [numpy.sin(3) + 4, 1]]) f = lambdify((x, y, z), A, [{'ImmutableDenseMatrix': numpy.matrix}, 'numpy']) numpy.testing.assert_allclose(f(1, 2, 3), sol_arr) assert isinstance(f(1, 2, 3), numpy.matrix) def test_python_div_zero_issue_11306(): if not numpy: skip("numpy not installed.") p = Piecewise((1 / x, y < -1), (x, y < 1), (1 / x, True)) f = lambdify([x, y], p, modules='numpy') numpy.seterr(divide='ignore') assert float(f(numpy.array([0]),numpy.array([0.5]))) == 0 assert str(float(f(numpy.array([0]),numpy.array([1])))) == 'inf' numpy.seterr(divide='warn') def test_issue9474(): mods = [None, 'math'] if numpy: mods.append('numpy') if mpmath: mods.append('mpmath') for mod in mods: f = lambdify(x, S.One/x, modules=mod) assert f(2) == 0.5 f = lambdify(x, floor(S.One/x), modules=mod) assert f(2) == 0 for absfunc, modules in product([Abs, abs], mods): f = lambdify(x, absfunc(x), modules=modules) assert f(-1) == 1 assert f(1) == 1 assert f(3+4j) == 5 def test_issue_9871(): if not numexpr: skip("numexpr not installed.") if not numpy: skip("numpy not installed.") r = sqrt(x**2 + y**2) expr = diff(1/r, x) xn = yn = numpy.linspace(1, 10, 16) # expr(xn, xn) = -xn/(sqrt(2)*xn)^3 fv_exact = -numpy.sqrt(2.)**-3 * xn**-2 fv_numpy = lambdify((x, y), expr, modules='numpy')(xn, yn) fv_numexpr = lambdify((x, y), expr, modules='numexpr')(xn, yn) numpy.testing.assert_allclose(fv_numpy, fv_exact, rtol=1e-10) numpy.testing.assert_allclose(fv_numexpr, fv_exact, rtol=1e-10) def test_numpy_piecewise(): if not numpy: skip("numpy not installed.") pieces = Piecewise((x, x < 3), (x**2, x > 5), (0, True)) f = lambdify(x, pieces, modules="numpy") numpy.testing.assert_array_equal(f(numpy.arange(10)), numpy.array([0, 1, 2, 0, 0, 0, 36, 49, 64, 81])) # If we evaluate somewhere all conditions are False, we should get back NaN nodef_func = lambdify(x, Piecewise((x, x > 0), (-x, x < 0))) numpy.testing.assert_array_equal(nodef_func(numpy.array([-1, 0, 1])), numpy.array([1, numpy.nan, 1])) def test_numpy_logical_ops(): if not numpy: skip("numpy not installed.") and_func = lambdify((x, y), And(x, y), modules="numpy") and_func_3 = lambdify((x, y, z), And(x, y, z), modules="numpy") or_func = lambdify((x, y), Or(x, y), modules="numpy") or_func_3 = lambdify((x, y, z), Or(x, y, z), modules="numpy") not_func = lambdify((x), Not(x), modules="numpy") arr1 = numpy.array([True, True]) arr2 = numpy.array([False, True]) arr3 = numpy.array([True, False]) numpy.testing.assert_array_equal(and_func(arr1, arr2), numpy.array([False, True])) numpy.testing.assert_array_equal(and_func_3(arr1, arr2, arr3), numpy.array([False, False])) numpy.testing.assert_array_equal(or_func(arr1, arr2), numpy.array([True, True])) numpy.testing.assert_array_equal(or_func_3(arr1, arr2, arr3), numpy.array([True, True])) numpy.testing.assert_array_equal(not_func(arr2), numpy.array([True, False])) def test_numpy_matmul(): if not numpy: skip("numpy not installed.") xmat = Matrix([[x, y], [z, 1+z]]) ymat = Matrix([[x**2], [Abs(x)]]) mat_func = lambdify((x, y, z), xmat*ymat, modules="numpy") numpy.testing.assert_array_equal(mat_func(0.5, 3, 4), numpy.array([[1.625], [3.5]])) numpy.testing.assert_array_equal(mat_func(-0.5, 3, 4), numpy.array([[1.375], [3.5]])) # Multiple matrices chained together in multiplication f = lambdify((x, y, z), xmat*xmat*xmat, modules="numpy") numpy.testing.assert_array_equal(f(0.5, 3, 4), numpy.array([[72.125, 119.25], [159, 251]])) def test_numpy_numexpr(): if not numpy: skip("numpy not installed.") if not numexpr: skip("numexpr not installed.") a, b, c = numpy.random.randn(3, 128, 128) # ensure that numpy and numexpr return same value for complicated expression expr = sin(x) + cos(y) + tan(z)**2 + Abs(z-y)*acos(sin(y*z)) + \ Abs(y-z)*acosh(2+exp(y-x))- sqrt(x**2+I*y**2) npfunc = lambdify((x, y, z), expr, modules='numpy') nefunc = lambdify((x, y, z), expr, modules='numexpr') assert numpy.allclose(npfunc(a, b, c), nefunc(a, b, c)) def test_numexpr_userfunctions(): if not numpy: skip("numpy not installed.") if not numexpr: skip("numexpr not installed.") a, b = numpy.random.randn(2, 10) uf = type('uf', (Function, ), {'eval' : classmethod(lambda x, y : y**2+1)}) func = lambdify(x, 1-uf(x), modules='numexpr') assert numpy.allclose(func(a), -(a**2)) uf = implemented_function(Function('uf'), lambda x, y : 2*x*y+1) func = lambdify((x, y), uf(x, y), modules='numexpr') assert numpy.allclose(func(a, b), 2*a*b+1) def test_tensorflow_basic_math(): if not tensorflow: skip("tensorflow not installed.") expr = Max(sin(x), Abs(1/(x+2))) func = lambdify(x, expr, modules="tensorflow") with tensorflow.compat.v1.Session() as s: a = tensorflow.constant(0, dtype=tensorflow.float32) assert func(a).eval(session=s) == 0.5 def test_tensorflow_placeholders(): if not tensorflow: skip("tensorflow not installed.") expr = Max(sin(x), Abs(1/(x+2))) func = lambdify(x, expr, modules="tensorflow") with tensorflow.compat.v1.Session() as s: a = tensorflow.compat.v1.placeholder(dtype=tensorflow.float32) assert func(a).eval(session=s, feed_dict={a: 0}) == 0.5 def test_tensorflow_variables(): if not tensorflow: skip("tensorflow not installed.") expr = Max(sin(x), Abs(1/(x+2))) func = lambdify(x, expr, modules="tensorflow") with tensorflow.compat.v1.Session() as s: a = tensorflow.Variable(0, dtype=tensorflow.float32) s.run(a.initializer) assert func(a).eval(session=s, feed_dict={a: 0}) == 0.5 def test_tensorflow_logical_operations(): if not tensorflow: skip("tensorflow not installed.") expr = Not(And(Or(x, y), y)) func = lambdify([x, y], expr, modules="tensorflow") with tensorflow.compat.v1.Session() as s: assert func(False, True).eval(session=s) == False def test_tensorflow_piecewise(): if not tensorflow: skip("tensorflow not installed.") expr = Piecewise((0, Eq(x,0)), (-1, x < 0), (1, x > 0)) func = lambdify(x, expr, modules="tensorflow") with tensorflow.compat.v1.Session() as s: assert func(-1).eval(session=s) == -1 assert func(0).eval(session=s) == 0 assert func(1).eval(session=s) == 1 def test_tensorflow_multi_max(): if not tensorflow: skip("tensorflow not installed.") expr = Max(x, -x, x**2) func = lambdify(x, expr, modules="tensorflow") with tensorflow.compat.v1.Session() as s: assert func(-2).eval(session=s) == 4 def test_tensorflow_multi_min(): if not tensorflow: skip("tensorflow not installed.") expr = Min(x, -x, x**2) func = lambdify(x, expr, modules="tensorflow") with tensorflow.compat.v1.Session() as s: assert func(-2).eval(session=s) == -2 def test_tensorflow_relational(): if not tensorflow: skip("tensorflow not installed.") expr = x >= 0 func = lambdify(x, expr, modules="tensorflow") with tensorflow.compat.v1.Session() as s: assert func(1).eval(session=s) == True def test_tensorflow_complexes(): if not tensorflow: skip("tensorflow not installed") func1 = lambdify(x, re(x), modules="tensorflow") func2 = lambdify(x, im(x), modules="tensorflow") func3 = lambdify(x, Abs(x), modules="tensorflow") func4 = lambdify(x, arg(x), modules="tensorflow") with tensorflow.compat.v1.Session() as s: # For versions before # https://github.com/tensorflow/tensorflow/issues/30029 # resolved, using python numeric types may not work a = tensorflow.constant(1+2j) assert func1(a).eval(session=s) == 1 assert func2(a).eval(session=s) == 2 tensorflow_result = func3(a).eval(session=s) sympy_result = Abs(1 + 2j).evalf() assert abs(tensorflow_result-sympy_result) < 10**-6 tensorflow_result = func4(a).eval(session=s) sympy_result = arg(1 + 2j).evalf() assert abs(tensorflow_result-sympy_result) < 10**-6 def test_tensorflow_array_arg(): # Test for issue 14655 (tensorflow part) if not tensorflow: skip("tensorflow not installed.") f = lambdify([[x, y]], x*x + y, 'tensorflow') with tensorflow.compat.v1.Session() as s: fcall = f(tensorflow.constant([2.0, 1.0])) assert fcall.eval(session=s) == 5.0 #================== Test symbolic ================================== def test_integral(): f = Lambda(x, exp(-x**2)) l = lambdify(x, Integral(f(x), (x, -oo, oo)), modules="sympy") assert l(x) == Integral(exp(-x**2), (x, -oo, oo)) def test_sym_single_arg(): f = lambdify(x, x * y) assert f(z) == z * y def test_sym_list_args(): f = lambdify([x, y], x + y + z) assert f(1, 2) == 3 + z def test_sym_integral(): f = Lambda(x, exp(-x**2)) l = lambdify(x, Integral(f(x), (x, -oo, oo)), modules="sympy") assert l(y).doit() == sqrt(pi) def test_namespace_order(): # lambdify had a bug, such that module dictionaries or cached module # dictionaries would pull earlier namespaces into themselves. # Because the module dictionaries form the namespace of the # generated lambda, this meant that the behavior of a previously # generated lambda function could change as a result of later calls # to lambdify. n1 = {'f': lambda x: 'first f'} n2 = {'f': lambda x: 'second f', 'g': lambda x: 'function g'} f = sympy.Function('f') g = sympy.Function('g') if1 = lambdify(x, f(x), modules=(n1, "sympy")) assert if1(1) == 'first f' if2 = lambdify(x, g(x), modules=(n2, "sympy")) # previously gave 'second f' assert if1(1) == 'first f' assert if2(1) == 'function g' def test_namespace_type(): # lambdify had a bug where it would reject modules of type unicode # on Python 2. x = sympy.Symbol('x') lambdify(x, x, modules=u'math') def test_imps(): # Here we check if the default returned functions are anonymous - in # the sense that we can have more than one function with the same name f = implemented_function('f', lambda x: 2*x) g = implemented_function('f', lambda x: math.sqrt(x)) l1 = lambdify(x, f(x)) l2 = lambdify(x, g(x)) assert str(f(x)) == str(g(x)) assert l1(3) == 6 assert l2(3) == math.sqrt(3) # check that we can pass in a Function as input func = sympy.Function('myfunc') assert not hasattr(func, '_imp_') my_f = implemented_function(func, lambda x: 2*x) assert hasattr(my_f, '_imp_') # Error for functions with same name and different implementation f2 = implemented_function("f", lambda x: x + 101) raises(ValueError, lambda: lambdify(x, f(f2(x)))) def test_imps_errors(): # Test errors that implemented functions can return, and still be able to # form expressions. # See: https://github.com/sympy/sympy/issues/10810 # # XXX: Removed AttributeError here. This test was added due to issue 10810 # but that issue was about ValueError. It doesn't seem reasonable to # "support" catching AttributeError in the same context... for val, error_class in product((0, 0., 2, 2.0), (TypeError, ValueError)): def myfunc(a): if a == 0: raise error_class return 1 f = implemented_function('f', myfunc) expr = f(val) assert expr == f(val) def test_imps_wrong_args(): raises(ValueError, lambda: implemented_function(sin, lambda x: x)) def test_lambdify_imps(): # Test lambdify with implemented functions # first test basic (sympy) lambdify f = sympy.cos assert lambdify(x, f(x))(0) == 1 assert lambdify(x, 1 + f(x))(0) == 2 assert lambdify((x, y), y + f(x))(0, 1) == 2 # make an implemented function and test f = implemented_function("f", lambda x: x + 100) assert lambdify(x, f(x))(0) == 100 assert lambdify(x, 1 + f(x))(0) == 101 assert lambdify((x, y), y + f(x))(0, 1) == 101 # Can also handle tuples, lists, dicts as expressions lam = lambdify(x, (f(x), x)) assert lam(3) == (103, 3) lam = lambdify(x, [f(x), x]) assert lam(3) == [103, 3] lam = lambdify(x, [f(x), (f(x), x)]) assert lam(3) == [103, (103, 3)] lam = lambdify(x, {f(x): x}) assert lam(3) == {103: 3} lam = lambdify(x, {f(x): x}) assert lam(3) == {103: 3} lam = lambdify(x, {x: f(x)}) assert lam(3) == {3: 103} # Check that imp preferred to other namespaces by default d = {'f': lambda x: x + 99} lam = lambdify(x, f(x), d) assert lam(3) == 103 # Unless flag passed lam = lambdify(x, f(x), d, use_imps=False) assert lam(3) == 102 def test_dummification(): t = symbols('t') F = Function('F') G = Function('G') #"\alpha" is not a valid python variable name #lambdify should sub in a dummy for it, and return #without a syntax error alpha = symbols(r'\alpha') some_expr = 2 * F(t)**2 / G(t) lam = lambdify((F(t), G(t)), some_expr) assert lam(3, 9) == 2 lam = lambdify(sin(t), 2 * sin(t)**2) assert lam(F(t)) == 2 * F(t)**2 #Test that \alpha was properly dummified lam = lambdify((alpha, t), 2*alpha + t) assert lam(2, 1) == 5 raises(SyntaxError, lambda: lambdify(F(t) * G(t), F(t) * G(t) + 5)) raises(SyntaxError, lambda: lambdify(2 * F(t), 2 * F(t) + 5)) raises(SyntaxError, lambda: lambdify(2 * F(t), 4 * F(t) + 5)) def test_curly_matrix_symbol(): # Issue #15009 curlyv = sympy.MatrixSymbol("{v}", 2, 1) lam = lambdify(curlyv, curlyv) assert lam(1)==1 lam = lambdify(curlyv, curlyv, dummify=True) assert lam(1)==1 def test_python_keywords(): # Test for issue 7452. The automatic dummification should ensure use of # Python reserved keywords as symbol names will create valid lambda # functions. This is an additional regression test. python_if = symbols('if') expr = python_if / 2 f = lambdify(python_if, expr) assert f(4.0) == 2.0 def test_lambdify_docstring(): func = lambdify((w, x, y, z), w + x + y + z) ref = ( "Created with lambdify. Signature:\n\n" "func(w, x, y, z)\n\n" "Expression:\n\n" "w + x + y + z" ).splitlines() assert func.__doc__.splitlines()[:len(ref)] == ref syms = symbols('a1:26') func = lambdify(syms, sum(syms)) ref = ( "Created with lambdify. Signature:\n\n" "func(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15,\n" " a16, a17, a18, a19, a20, a21, a22, a23, a24, a25)\n\n" "Expression:\n\n" "a1 + a10 + a11 + a12 + a13 + a14 + a15 + a16 + a17 + a18 + a19 + a2 + a20 +..." ).splitlines() assert func.__doc__.splitlines()[:len(ref)] == ref #================== Test special printers ========================== def test_special_printers(): from sympy.polys.numberfields import IntervalPrinter def intervalrepr(expr): return IntervalPrinter().doprint(expr) expr = sqrt(sqrt(2) + sqrt(3)) + S.Half func0 = lambdify((), expr, modules="mpmath", printer=intervalrepr) func1 = lambdify((), expr, modules="mpmath", printer=IntervalPrinter) func2 = lambdify((), expr, modules="mpmath", printer=IntervalPrinter()) mpi = type(mpmath.mpi(1, 2)) assert isinstance(func0(), mpi) assert isinstance(func1(), mpi) assert isinstance(func2(), mpi) def test_true_false(): # We want exact is comparison here, not just == assert lambdify([], true)() is True assert lambdify([], false)() is False def test_issue_2790(): assert lambdify((x, (y, z)), x + y)(1, (2, 4)) == 3 assert lambdify((x, (y, (w, z))), w + x + y + z)(1, (2, (3, 4))) == 10 assert lambdify(x, x + 1, dummify=False)(1) == 2 def test_issue_12092(): f = implemented_function('f', lambda x: x**2) assert f(f(2)).evalf() == Float(16) def test_issue_14911(): class Variable(sympy.Symbol): def _sympystr(self, printer): return printer.doprint(self.name) _lambdacode = _sympystr _numpycode = _sympystr x = Variable('x') y = 2 * x code = LambdaPrinter().doprint(y) assert code.replace(' ', '') == '2*x' def test_ITE(): assert lambdify((x, y, z), ITE(x, y, z))(True, 5, 3) == 5 assert lambdify((x, y, z), ITE(x, y, z))(False, 5, 3) == 3 def test_Min_Max(): # see gh-10375 assert lambdify((x, y, z), Min(x, y, z))(1, 2, 3) == 1 assert lambdify((x, y, z), Max(x, y, z))(1, 2, 3) == 3 def test_Indexed(): # Issue #10934 if not numpy: skip("numpy not installed") a = IndexedBase('a') i, j = symbols('i j') b = numpy.array([[1, 2], [3, 4]]) assert lambdify(a, Sum(a[x, y], (x, 0, 1), (y, 0, 1)))(b) == 10 def test_issue_12173(): #test for issue 12173 exp1 = lambdify((x, y), uppergamma(x, y),"mpmath")(1, 2) exp2 = lambdify((x, y), lowergamma(x, y),"mpmath")(1, 2) assert exp1 == uppergamma(1, 2).evalf() assert exp2 == lowergamma(1, 2).evalf() def test_issue_13642(): if not numpy: skip("numpy not installed") f = lambdify(x, sinc(x)) assert Abs(f(1) - sinc(1)).n() < 1e-15 def test_sinc_mpmath(): f = lambdify(x, sinc(x), "mpmath") assert Abs(f(1) - sinc(1)).n() < 1e-15 def test_lambdify_dummy_arg(): d1 = Dummy() f1 = lambdify(d1, d1 + 1, dummify=False) assert f1(2) == 3 f1b = lambdify(d1, d1 + 1) assert f1b(2) == 3 d2 = Dummy('x') f2 = lambdify(d2, d2 + 1) assert f2(2) == 3 f3 = lambdify([[d2]], d2 + 1) assert f3([2]) == 3 def test_lambdify_mixed_symbol_dummy_args(): d = Dummy() # Contrived example of name clash dsym = symbols(str(d)) f = lambdify([d, dsym], d - dsym) assert f(4, 1) == 3 def test_numpy_array_arg(): # Test for issue 14655 (numpy part) if not numpy: skip("numpy not installed") f = lambdify([[x, y]], x*x + y, 'numpy') assert f(numpy.array([2.0, 1.0])) == 5 def test_scipy_fns(): if not scipy: skip("scipy not installed") single_arg_sympy_fns = [erf, erfc, factorial, gamma, loggamma, digamma] single_arg_scipy_fns = [scipy.special.erf, scipy.special.erfc, scipy.special.factorial, scipy.special.gamma, scipy.special.gammaln, scipy.special.psi] numpy.random.seed(0) for (sympy_fn, scipy_fn) in zip(single_arg_sympy_fns, single_arg_scipy_fns): f = lambdify(x, sympy_fn(x), modules="scipy") for i in range(20): tv = numpy.random.uniform(-10, 10) + 1j*numpy.random.uniform(-5, 5) # SciPy thinks that factorial(z) is 0 when re(z) < 0 and # does not support complex numbers. # SymPy does not think so. if sympy_fn == factorial: tv = numpy.abs(tv) # SciPy supports gammaln for real arguments only, # and there is also a branch cut along the negative real axis if sympy_fn == loggamma: tv = numpy.abs(tv) # SymPy's digamma evaluates as polygamma(0, z) # which SciPy supports for real arguments only if sympy_fn == digamma: tv = numpy.real(tv) sympy_result = sympy_fn(tv).evalf() assert abs(f(tv) - sympy_result) < 1e-13*(1 + abs(sympy_result)) assert abs(f(tv) - scipy_fn(tv)) < 1e-13*(1 + abs(sympy_result)) double_arg_sympy_fns = [RisingFactorial, besselj, bessely, besseli, besselk] double_arg_scipy_fns = [scipy.special.poch, scipy.special.jv, scipy.special.yv, scipy.special.iv, scipy.special.kv] for (sympy_fn, scipy_fn) in zip(double_arg_sympy_fns, double_arg_scipy_fns): f = lambdify((x, y), sympy_fn(x, y), modules="scipy") for i in range(20): # SciPy supports only real orders of Bessel functions tv1 = numpy.random.uniform(-10, 10) tv2 = numpy.random.uniform(-10, 10) + 1j*numpy.random.uniform(-5, 5) # SciPy supports poch for real arguments only if sympy_fn == RisingFactorial: tv2 = numpy.real(tv2) sympy_result = sympy_fn(tv1, tv2).evalf() assert abs(f(tv1, tv2) - sympy_result) < 1e-13*(1 + abs(sympy_result)) assert abs(f(tv1, tv2) - scipy_fn(tv1, tv2)) < 1e-13*(1 + abs(sympy_result)) def test_scipy_polys(): if not scipy: skip("scipy not installed") numpy.random.seed(0) params = symbols('n k a b') # list polynomials with the number of parameters polys = [ (chebyshevt, 1), (chebyshevu, 1), (legendre, 1), (hermite, 1), (laguerre, 1), (gegenbauer, 2), (assoc_legendre, 2), (assoc_laguerre, 2), (jacobi, 3) ] msg = \ "The random test of the function {func} with the arguments " \ "{args} had failed because the SymPy result {sympy_result} " \ "and SciPy result {scipy_result} had failed to converge " \ "within the tolerance {tol} " \ "(Actual absolute difference : {diff})" for sympy_fn, num_params in polys: args = params[:num_params] + (x,) f = lambdify(args, sympy_fn(*args)) for _ in range(10): tn = numpy.random.randint(3, 10) tparams = tuple(numpy.random.uniform(0, 5, size=num_params-1)) tv = numpy.random.uniform(-10, 10) + 1j*numpy.random.uniform(-5, 5) # SciPy supports hermite for real arguments only if sympy_fn == hermite: tv = numpy.real(tv) # assoc_legendre needs x in (-1, 1) and integer param at most n if sympy_fn == assoc_legendre: tv = numpy.random.uniform(-1, 1) tparams = tuple(numpy.random.randint(1, tn, size=1)) vals = (tn,) + tparams + (tv,) scipy_result = f(*vals) sympy_result = sympy_fn(*vals).evalf() atol = 1e-9*(1 + abs(sympy_result)) diff = abs(scipy_result - sympy_result) try: assert diff < atol except TypeError: raise AssertionError( msg.format( func=repr(sympy_fn), args=repr(vals), sympy_result=repr(sympy_result), scipy_result=repr(scipy_result), diff=diff, tol=atol) ) def test_lambdify_inspect(): f = lambdify(x, x**2) # Test that inspect.getsource works but don't hard-code implementation # details assert 'x**2' in inspect.getsource(f) def test_issue_14941(): x, y = Dummy(), Dummy() # test dict f1 = lambdify([x, y], {x: 3, y: 3}, 'sympy') assert f1(2, 3) == {2: 3, 3: 3} # test tuple f2 = lambdify([x, y], (y, x), 'sympy') assert f2(2, 3) == (3, 2) # test list f3 = lambdify([x, y], [y, x], 'sympy') assert f3(2, 3) == [3, 2] def test_lambdify_Derivative_arg_issue_16468(): f = Function('f')(x) fx = f.diff() assert lambdify((f, fx), f + fx)(10, 5) == 15 assert eval(lambdastr((f, fx), f/fx))(10, 5) == 2 raises(SyntaxError, lambda: eval(lambdastr((f, fx), f/fx, dummify=False))) assert eval(lambdastr((f, fx), f/fx, dummify=True))(10, 5) == 2 assert eval(lambdastr((fx, f), f/fx, dummify=True))(S(10), 5) == S.Half assert lambdify(fx, 1 + fx)(41) == 42 assert eval(lambdastr(fx, 1 + fx, dummify=True))(41) == 42 def test_imag_real(): f_re = lambdify([z], sympy.re(z)) val = 3+2j assert f_re(val) == val.real f_im = lambdify([z], sympy.im(z)) # see #15400 assert f_im(val) == val.imag def test_MatrixSymbol_issue_15578(): if not numpy: skip("numpy not installed") A = MatrixSymbol('A', 2, 2) A0 = numpy.array([[1, 2], [3, 4]]) f = lambdify(A, A**(-1)) assert numpy.allclose(f(A0), numpy.array([[-2., 1.], [1.5, -0.5]])) g = lambdify(A, A**3) assert numpy.allclose(g(A0), numpy.array([[37, 54], [81, 118]])) def test_issue_15654(): if not scipy: skip("scipy not installed") from sympy.abc import n, l, r, Z from sympy.physics import hydrogen nv, lv, rv, Zv = 1, 0, 3, 1 sympy_value = hydrogen.R_nl(nv, lv, rv, Zv).evalf() f = lambdify((n, l, r, Z), hydrogen.R_nl(n, l, r, Z)) scipy_value = f(nv, lv, rv, Zv) assert abs(sympy_value - scipy_value) < 1e-15 def test_issue_15827(): if not numpy: skip("numpy not installed") A = MatrixSymbol("A", 3, 3) B = MatrixSymbol("B", 2, 3) C = MatrixSymbol("C", 3, 4) D = MatrixSymbol("D", 4, 5) k=symbols("k") f = lambdify(A, (2*k)*A) g = lambdify(A, (2+k)*A) h = lambdify(A, 2*A) i = lambdify((B, C, D), 2*B*C*D) assert numpy.array_equal(f(numpy.array([[1, 2, 3], [1, 2, 3], [1, 2, 3]])), \ numpy.array([[2*k, 4*k, 6*k], [2*k, 4*k, 6*k], [2*k, 4*k, 6*k]], dtype=object)) assert numpy.array_equal(g(numpy.array([[1, 2, 3], [1, 2, 3], [1, 2, 3]])), \ numpy.array([[k + 2, 2*k + 4, 3*k + 6], [k + 2, 2*k + 4, 3*k + 6], \ [k + 2, 2*k + 4, 3*k + 6]], dtype=object)) assert numpy.array_equal(h(numpy.array([[1, 2, 3], [1, 2, 3], [1, 2, 3]])), \ numpy.array([[2, 4, 6], [2, 4, 6], [2, 4, 6]])) assert numpy.array_equal(i(numpy.array([[1, 2, 3], [1, 2, 3]]), numpy.array([[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]), \ numpy.array([[1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5]])), numpy.array([[ 120, 240, 360, 480, 600], \ [ 120, 240, 360, 480, 600]])) def test_issue_16930(): if not scipy: skip("scipy not installed") x = symbols("x") f = lambda x: S.GoldenRatio * x**2 f_ = lambdify(x, f(x), modules='scipy') assert f_(1) == scipy.constants.golden_ratio def test_issue_17898(): if not scipy: skip("scipy not installed") x = symbols("x") f_ = lambdify([x], sympy.LambertW(x,-1), modules='scipy') assert f_(0.1) == mpmath.lambertw(0.1, -1) def test_single_e(): f = lambdify(x, E) assert f(23) == exp(1.0) def test_issue_16536(): if not scipy: skip("scipy not installed") a = symbols('a') f1 = lowergamma(a, x) F = lambdify((a, x), f1, modules='scipy') assert abs(lowergamma(1, 3) - F(1, 3)) <= 1e-10 f2 = uppergamma(a, x) F = lambdify((a, x), f2, modules='scipy') assert abs(uppergamma(1, 3) - F(1, 3)) <= 1e-10 def test_fresnel_integrals_scipy(): if not scipy: skip("scipy not installed") f1 = fresnelc(x) f2 = fresnels(x) F1 = lambdify(x, f1, modules='scipy') F2 = lambdify(x, f2, modules='scipy') assert abs(fresnelc(1.3) - F1(1.3)) <= 1e-10 assert abs(fresnels(1.3) - F2(1.3)) <= 1e-10 def test_beta_scipy(): if not scipy: skip("scipy not installed") f = beta(x, y) F = lambdify((x, y), f, modules='scipy') assert abs(beta(1.3, 2.3) - F(1.3, 2.3)) <= 1e-10 def test_beta_math(): f = beta(x, y) F = lambdify((x, y), f, modules='math') assert abs(beta(1.3, 2.3) - F(1.3, 2.3)) <= 1e-10
bb43e17fa86652f4deebc1cef61ab58a79ac5089a67055483125cb1778890368
""" Tests from Michael Wester's 1999 paper "Review of CAS mathematical capabilities". http://www.math.unm.edu/~wester/cas/book/Wester.pdf See also http://math.unm.edu/~wester/cas_review.html for detailed output of each tested system. """ from sympy import (Rational, symbols, Dummy, factorial, sqrt, log, exp, oo, zoo, product, binomial, rf, pi, gamma, igcd, factorint, radsimp, combsimp, npartitions, totient, primerange, factor, simplify, gcd, resultant, expand, I, trigsimp, tan, sin, cos, cot, diff, nan, limit, EulerGamma, polygamma, bernoulli, hyper, hyperexpand, besselj, asin, assoc_legendre, Function, re, im, DiracDelta, chebyshevt, legendre_poly, polylog, series, O, atan, sinh, cosh, tanh, floor, ceiling, solve, asinh, acot, csc, sec, LambertW, N, apart, sqrtdenest, factorial2, powdenest, Mul, S, ZZ, Poly, expand_func, E, Q, And, Lt, Min, ask, refine, AlgebraicNumber, continued_fraction_iterator as cf_i, continued_fraction_periodic as cf_p, continued_fraction_convergents as cf_c, continued_fraction_reduce as cf_r, FiniteSet, elliptic_e, elliptic_f, powsimp, hessian, wronskian, fibonacci, sign, Lambda, Piecewise, Subs, residue, Derivative, logcombine, Symbol, Intersection, Union, EmptySet, Interval, idiff, ImageSet, acos, Max, MatMul, conjugate) import mpmath from sympy.functions.combinatorial.numbers import stirling from sympy.functions.special.delta_functions import Heaviside from sympy.functions.special.error_functions import Ci, Si, erf from sympy.functions.special.zeta_functions import zeta from sympy.testing.pytest import (XFAIL, slow, SKIP, skip, ON_TRAVIS, raises, nocache_fail) from sympy.utilities.iterables import partitions from mpmath import mpi, mpc from sympy.matrices import Matrix, GramSchmidt, eye from sympy.matrices.expressions.blockmatrix import BlockMatrix, block_collapse from sympy.matrices.expressions import MatrixSymbol, ZeroMatrix from sympy.physics.quantum import Commutator from sympy.assumptions import assuming from sympy.polys.rings import PolyRing from sympy.polys.fields import FracField from sympy.polys.solvers import solve_lin_sys from sympy.concrete import Sum from sympy.concrete.products import Product from sympy.integrals import integrate from sympy.integrals.transforms import laplace_transform,\ inverse_laplace_transform, LaplaceTransform, fourier_transform,\ mellin_transform from sympy.solvers.recurr import rsolve from sympy.solvers.solveset import solveset, solveset_real, linsolve from sympy.solvers.ode import dsolve from sympy.core.relational import Equality from itertools import islice, takewhile from sympy.series.formal import fps from sympy.series.fourier import fourier_series from sympy.calculus.util import minimum R = Rational x, y, z = symbols('x y z') i, j, k, l, m, n = symbols('i j k l m n', integer=True) f = Function('f') g = Function('g') # A. Boolean Logic and Quantifier Elimination # Not implemented. # B. Set Theory def test_B1(): assert (FiniteSet(i, j, j, k, k, k) | FiniteSet(l, k, j) | FiniteSet(j, m, j)) == FiniteSet(i, j, k, l, m) def test_B2(): assert (FiniteSet(i, j, j, k, k, k) & FiniteSet(l, k, j) & FiniteSet(j, m, j)) == Intersection({j, m}, {i, j, k}, {j, k, l}) # Previous output below. Not sure why that should be the expected output. # There should probably be a way to rewrite Intersections that way but I # don't see why an Intersection should evaluate like that: # # == Union({j}, Intersection({m}, Union({j, k}, Intersection({i}, {l})))) def test_B3(): assert (FiniteSet(i, j, k, l, m) - FiniteSet(j) == FiniteSet(i, k, l, m)) def test_B4(): assert (FiniteSet(*(FiniteSet(i, j)*FiniteSet(k, l))) == FiniteSet((i, k), (i, l), (j, k), (j, l))) # C. Numbers def test_C1(): assert (factorial(50) == 30414093201713378043612608166064768844377641568960512000000000000) def test_C2(): assert (factorint(factorial(50)) == {2: 47, 3: 22, 5: 12, 7: 8, 11: 4, 13: 3, 17: 2, 19: 2, 23: 2, 29: 1, 31: 1, 37: 1, 41: 1, 43: 1, 47: 1}) def test_C3(): assert (factorial2(10), factorial2(9)) == (3840, 945) # Base conversions; not really implemented by sympy # Whatever. Take credit! def test_C4(): assert 0xABC == 2748 def test_C5(): assert 123 == int('234', 7) def test_C6(): assert int('677', 8) == int('1BF', 16) == 447 def test_C7(): assert log(32768, 8) == 5 def test_C8(): # Modular multiplicative inverse. Would be nice if divmod could do this. assert ZZ.invert(5, 7) == 3 assert ZZ.invert(5, 6) == 5 def test_C9(): assert igcd(igcd(1776, 1554), 5698) == 74 def test_C10(): x = 0 for n in range(2, 11): x += R(1, n) assert x == R(4861, 2520) def test_C11(): assert R(1, 7) == S('0.[142857]') def test_C12(): assert R(7, 11) * R(22, 7) == 2 def test_C13(): test = R(10, 7) * (1 + R(29, 1000)) ** R(1, 3) good = 3 ** R(1, 3) assert test == good def test_C14(): assert sqrtdenest(sqrt(2*sqrt(3) + 4)) == 1 + sqrt(3) def test_C15(): test = sqrtdenest(sqrt(14 + 3*sqrt(3 + 2*sqrt(5 - 12*sqrt(3 - 2*sqrt(2)))))) good = sqrt(2) + 3 assert test == good def test_C16(): test = sqrtdenest(sqrt(10 + 2*sqrt(6) + 2*sqrt(10) + 2*sqrt(15))) good = sqrt(2) + sqrt(3) + sqrt(5) assert test == good def test_C17(): test = radsimp((sqrt(3) + sqrt(2)) / (sqrt(3) - sqrt(2))) good = 5 + 2*sqrt(6) assert test == good def test_C18(): assert simplify((sqrt(-2 + sqrt(-5)) * sqrt(-2 - sqrt(-5))).expand(complex=True)) == 3 @XFAIL def test_C19(): assert radsimp(simplify((90 + 34*sqrt(7)) ** R(1, 3))) == 3 + sqrt(7) def test_C20(): inside = (135 + 78*sqrt(3)) test = AlgebraicNumber((inside**R(2, 3) + 3) * sqrt(3) / inside**R(1, 3)) assert simplify(test) == AlgebraicNumber(12) def test_C21(): assert simplify(AlgebraicNumber((41 + 29*sqrt(2)) ** R(1, 5))) == \ AlgebraicNumber(1 + sqrt(2)) @XFAIL def test_C22(): test = simplify(((6 - 4*sqrt(2))*log(3 - 2*sqrt(2)) + (3 - 2*sqrt(2))*log(17 - 12*sqrt(2)) + 32 - 24*sqrt(2)) / (48*sqrt(2) - 72)) good = sqrt(2)/3 - log(sqrt(2) - 1)/3 assert test == good def test_C23(): assert 2 * oo - 3 is oo @XFAIL def test_C24(): raise NotImplementedError("2**aleph_null == aleph_1") # D. Numerical Analysis def test_D1(): assert 0.0 / sqrt(2) == 0.0 def test_D2(): assert str(exp(-1000000).evalf()) == '3.29683147808856e-434295' def test_D3(): assert exp(pi*sqrt(163)).evalf(50).num.ae(262537412640768744) def test_D4(): assert floor(R(-5, 3)) == -2 assert ceiling(R(-5, 3)) == -1 @XFAIL def test_D5(): raise NotImplementedError("cubic_spline([1, 2, 4, 5], [1, 4, 2, 3], x)(3) == 27/8") @XFAIL def test_D6(): raise NotImplementedError("translate sum(a[i]*x**i, (i,1,n)) to FORTRAN") @XFAIL def test_D7(): raise NotImplementedError("translate sum(a[i]*x**i, (i,1,n)) to C") @XFAIL def test_D8(): # One way is to cheat by converting the sum to a string, # and replacing the '[' and ']' with ''. # E.g., horner(S(str(_).replace('[','').replace(']',''))) raise NotImplementedError("apply Horner's rule to sum(a[i]*x**i, (i,1,5))") @XFAIL def test_D9(): raise NotImplementedError("translate D8 to FORTRAN") @XFAIL def test_D10(): raise NotImplementedError("translate D8 to C") @XFAIL def test_D11(): #Is there a way to use count_ops? raise NotImplementedError("flops(sum(product(f[i][k], (i,1,k)), (k,1,n)))") @XFAIL def test_D12(): assert (mpi(-4, 2) * x + mpi(1, 3)) ** 2 == mpi(-8, 16)*x**2 + mpi(-24, 12)*x + mpi(1, 9) @XFAIL def test_D13(): raise NotImplementedError("discretize a PDE: diff(f(x,t),t) == diff(diff(f(x,t),x),x)") # E. Statistics # See scipy; all of this is numerical. # F. Combinatorial Theory. def test_F1(): assert rf(x, 3) == x*(1 + x)*(2 + x) def test_F2(): assert expand_func(binomial(n, 3)) == n*(n - 1)*(n - 2)/6 @XFAIL def test_F3(): assert combsimp(2**n * factorial(n) * factorial2(2*n - 1)) == factorial(2*n) @XFAIL def test_F4(): assert combsimp((2**n * factorial(n) * product(2*k - 1, (k, 1, n)))) == factorial(2*n) @XFAIL def test_F5(): assert gamma(n + R(1, 2)) / sqrt(pi) / factorial(n) == factorial(2*n)/2**(2*n)/factorial(n)**2 def test_F6(): partTest = [p.copy() for p in partitions(4)] partDesired = [{4: 1}, {1: 1, 3: 1}, {2: 2}, {1: 2, 2:1}, {1: 4}] assert partTest == partDesired def test_F7(): assert npartitions(4) == 5 def test_F8(): assert stirling(5, 2, signed=True) == -50 # if signed, then kind=1 def test_F9(): assert totient(1776) == 576 # G. Number Theory def test_G1(): assert list(primerange(999983, 1000004)) == [999983, 1000003] @XFAIL def test_G2(): raise NotImplementedError("find the primitive root of 191 == 19") @XFAIL def test_G3(): raise NotImplementedError("(a+b)**p mod p == a**p + b**p mod p; p prime") # ... G14 Modular equations are not implemented. def test_G15(): assert Rational(sqrt(3).evalf()).limit_denominator(15) == R(26, 15) assert list(takewhile(lambda x: x.q <= 15, cf_c(cf_i(sqrt(3)))))[-1] == \ R(26, 15) def test_G16(): assert list(islice(cf_i(pi),10)) == [3, 7, 15, 1, 292, 1, 1, 1, 2, 1] def test_G17(): assert cf_p(0, 1, 23) == [4, [1, 3, 1, 8]] def test_G18(): assert cf_p(1, 2, 5) == [[1]] assert cf_r([[1]]).expand() == S.Half + sqrt(5)/2 @XFAIL def test_G19(): s = symbols('s', integer=True, positive=True) it = cf_i((exp(1/s) - 1)/(exp(1/s) + 1)) assert list(islice(it, 5)) == [0, 2*s, 6*s, 10*s, 14*s] def test_G20(): s = symbols('s', integer=True, positive=True) # Wester erroneously has this as -s + sqrt(s**2 + 1) assert cf_r([[2*s]]) == s + sqrt(s**2 + 1) @XFAIL def test_G20b(): s = symbols('s', integer=True, positive=True) assert cf_p(s, 1, s**2 + 1) == [[2*s]] # H. Algebra def test_H1(): assert simplify(2*2**n) == simplify(2**(n + 1)) assert powdenest(2*2**n) == simplify(2**(n + 1)) def test_H2(): assert powsimp(4 * 2**n) == 2**(n + 2) def test_H3(): assert (-1)**(n*(n + 1)) == 1 def test_H4(): expr = factor(6*x - 10) assert type(expr) is Mul assert expr.args[0] == 2 assert expr.args[1] == 3*x - 5 p1 = 64*x**34 - 21*x**47 - 126*x**8 - 46*x**5 - 16*x**60 - 81 p2 = 72*x**60 - 25*x**25 - 19*x**23 - 22*x**39 - 83*x**52 + 54*x**10 + 81 q = 34*x**19 - 25*x**16 + 70*x**7 + 20*x**3 - 91*x - 86 def test_H5(): assert gcd(p1, p2, x) == 1 def test_H6(): assert gcd(expand(p1 * q), expand(p2 * q)) == q def test_H7(): p1 = 24*x*y**19*z**8 - 47*x**17*y**5*z**8 + 6*x**15*y**9*z**2 - 3*x**22 + 5 p2 = 34*x**5*y**8*z**13 + 20*x**7*y**7*z**7 + 12*x**9*y**16*z**4 + 80*y**14*z assert gcd(p1, p2, x, y, z) == 1 def test_H8(): p1 = 24*x*y**19*z**8 - 47*x**17*y**5*z**8 + 6*x**15*y**9*z**2 - 3*x**22 + 5 p2 = 34*x**5*y**8*z**13 + 20*x**7*y**7*z**7 + 12*x**9*y**16*z**4 + 80*y**14*z q = 11*x**12*y**7*z**13 - 23*x**2*y**8*z**10 + 47*x**17*y**5*z**8 assert gcd(p1 * q, p2 * q, x, y, z) == q def test_H9(): p1 = 2*x**(n + 4) - x**(n + 2) p2 = 4*x**(n + 1) + 3*x**n assert gcd(p1, p2) == x**n def test_H10(): p1 = 3*x**4 + 3*x**3 + x**2 - x - 2 p2 = x**3 - 3*x**2 + x + 5 assert resultant(p1, p2, x) == 0 def test_H11(): assert resultant(p1 * q, p2 * q, x) == 0 def test_H12(): num = x**2 - 4 den = x**2 + 4*x + 4 assert simplify(num/den) == (x - 2)/(x + 2) @XFAIL def test_H13(): assert simplify((exp(x) - 1) / (exp(x/2) + 1)) == exp(x/2) - 1 def test_H14(): p = (x + 1) ** 20 ep = expand(p) assert ep == (1 + 20*x + 190*x**2 + 1140*x**3 + 4845*x**4 + 15504*x**5 + 38760*x**6 + 77520*x**7 + 125970*x**8 + 167960*x**9 + 184756*x**10 + 167960*x**11 + 125970*x**12 + 77520*x**13 + 38760*x**14 + 15504*x**15 + 4845*x**16 + 1140*x**17 + 190*x**18 + 20*x**19 + x**20) dep = diff(ep, x) assert dep == (20 + 380*x + 3420*x**2 + 19380*x**3 + 77520*x**4 + 232560*x**5 + 542640*x**6 + 1007760*x**7 + 1511640*x**8 + 1847560*x**9 + 1847560*x**10 + 1511640*x**11 + 1007760*x**12 + 542640*x**13 + 232560*x**14 + 77520*x**15 + 19380*x**16 + 3420*x**17 + 380*x**18 + 20*x**19) assert factor(dep) == 20*(1 + x)**19 def test_H15(): assert simplify((Mul(*[x - r for r in solveset(x**3 + x**2 - 7)]))) == x**3 + x**2 - 7 def test_H16(): assert factor(x**100 - 1) == ((x - 1)*(x + 1)*(x**2 + 1)*(x**4 - x**3 + x**2 - x + 1)*(x**4 + x**3 + x**2 + x + 1)*(x**8 - x**6 + x**4 - x**2 + 1)*(x**20 - x**15 + x**10 - x**5 + 1)*(x**20 + x**15 + x**10 + x**5 + 1)*(x**40 - x**30 + x**20 - x**10 + 1)) def test_H17(): assert simplify(factor(expand(p1 * p2)) - p1*p2) == 0 @XFAIL def test_H18(): # Factor over complex rationals. test = factor(4*x**4 + 8*x**3 + 77*x**2 + 18*x + 153) good = (2*x + 3*I)*(2*x - 3*I)*(x + 1 - 4*I)*(x + 1 + 4*I) assert test == good def test_H19(): a = symbols('a') # The idea is to let a**2 == 2, then solve 1/(a-1). Answer is a+1") assert Poly(a - 1).invert(Poly(a**2 - 2)) == a + 1 @XFAIL def test_H20(): raise NotImplementedError("let a**2==2; (x**3 + (a-2)*x**2 - " + "(2*a+3)*x - 3*a) / (x**2-2) = (x**2 - 2*x - 3) / (x-a)") @XFAIL def test_H21(): raise NotImplementedError("evaluate (b+c)**4 assuming b**3==2, c**2==3. \ Answer is 2*b + 8*c + 18*b**2 + 12*b*c + 9") def test_H22(): assert factor(x**4 - 3*x**2 + 1, modulus=5) == (x - 2)**2 * (x + 2)**2 def test_H23(): f = x**11 + x + 1 g = (x**2 + x + 1) * (x**9 - x**8 + x**6 - x**5 + x**3 - x**2 + 1) assert factor(f, modulus=65537) == g def test_H24(): phi = AlgebraicNumber(S.GoldenRatio.expand(func=True), alias='phi') assert factor(x**4 - 3*x**2 + 1, extension=phi) == \ (x - phi)*(x + 1 - phi)*(x - 1 + phi)*(x + phi) def test_H25(): e = (x - 2*y**2 + 3*z**3) ** 20 assert factor(expand(e)) == e def test_H26(): g = expand((sin(x) - 2*cos(y)**2 + 3*tan(z)**3)**20) assert factor(g, expand=False) == (-sin(x) + 2*cos(y)**2 - 3*tan(z)**3)**20 def test_H27(): f = 24*x*y**19*z**8 - 47*x**17*y**5*z**8 + 6*x**15*y**9*z**2 - 3*x**22 + 5 g = 34*x**5*y**8*z**13 + 20*x**7*y**7*z**7 + 12*x**9*y**16*z**4 + 80*y**14*z h = -2*z*y**7 \ *(6*x**9*y**9*z**3 + 10*x**7*z**6 + 17*y*x**5*z**12 + 40*y**7) \ *(3*x**22 + 47*x**17*y**5*z**8 - 6*x**15*y**9*z**2 - 24*x*y**19*z**8 - 5) assert factor(expand(f*g)) == h @XFAIL def test_H28(): raise NotImplementedError("expand ((1 - c**2)**5 * (1 - s**2)**5 * " + "(c**2 + s**2)**10) with c**2 + s**2 = 1. Answer is c**10*s**10.") @XFAIL def test_H29(): assert factor(4*x**2 - 21*x*y + 20*y**2, modulus=3) == (x + y)*(x - y) def test_H30(): test = factor(x**3 + y**3, extension=sqrt(-3)) answer = (x + y)*(x + y*(-R(1, 2) - sqrt(3)/2*I))*(x + y*(-R(1, 2) + sqrt(3)/2*I)) assert answer == test def test_H31(): f = (x**2 + 2*x + 3)/(x**3 + 4*x**2 + 5*x + 2) g = 2 / (x + 1)**2 - 2 / (x + 1) + 3 / (x + 2) assert apart(f) == g @XFAIL def test_H32(): # issue 6558 raise NotImplementedError("[A*B*C - (A*B*C)**(-1)]*A*C*B (product \ of a non-commuting product and its inverse)") def test_H33(): A, B, C = symbols('A, B, C', commutative=False) assert (Commutator(A, Commutator(B, C)) + Commutator(B, Commutator(C, A)) + Commutator(C, Commutator(A, B))).doit().expand() == 0 # I. Trigonometry def test_I1(): assert tan(pi*R(7, 10)) == -sqrt(1 + 2/sqrt(5)) @XFAIL def test_I2(): assert sqrt((1 + cos(6))/2) == -cos(3) def test_I3(): assert cos(n*pi) + sin((4*n - 1)*pi/2) == (-1)**n - 1 def test_I4(): assert refine(cos(pi*cos(n*pi)) + sin(pi/2*cos(n*pi)), Q.integer(n)) == (-1)**n - 1 @XFAIL def test_I5(): assert sin((n**5/5 + n**4/2 + n**3/3 - n/30) * pi) == 0 @XFAIL def test_I6(): raise NotImplementedError("assuming -3*pi<x<-5*pi/2, abs(cos(x)) == -cos(x), abs(sin(x)) == -sin(x)") @XFAIL def test_I7(): assert cos(3*x)/cos(x) == cos(x)**2 - 3*sin(x)**2 @XFAIL def test_I8(): assert cos(3*x)/cos(x) == 2*cos(2*x) - 1 @XFAIL def test_I9(): # Supposed to do this with rewrite rules. assert cos(3*x)/cos(x) == cos(x)**2 - 3*sin(x)**2 def test_I10(): assert trigsimp((tan(x)**2 + 1 - cos(x)**-2) / (sin(x)**2 + cos(x)**2 - 1)) is nan @SKIP("hangs") @XFAIL def test_I11(): assert limit((tan(x)**2 + 1 - cos(x)**-2) / (sin(x)**2 + cos(x)**2 - 1), x, 0) != 0 @XFAIL def test_I12(): # This should fail or return nan or something. res = diff((tan(x)**2 + 1 - cos(x)**-2) / (sin(x)**2 + cos(x)**2 - 1), x) assert res is nan # trigsimp(res) gives nan # J. Special functions. def test_J1(): assert bernoulli(16) == R(-3617, 510) def test_J2(): assert diff(elliptic_e(x, y**2), y) == (elliptic_e(x, y**2) - elliptic_f(x, y**2))/y @XFAIL def test_J3(): raise NotImplementedError("Jacobi elliptic functions: diff(dn(u,k), u) == -k**2*sn(u,k)*cn(u,k)") def test_J4(): assert gamma(R(-1, 2)) == -2*sqrt(pi) def test_J5(): assert polygamma(0, R(1, 3)) == -log(3) - sqrt(3)*pi/6 - EulerGamma - log(sqrt(3)) def test_J6(): assert mpmath.besselj(2, 1 + 1j).ae(mpc('0.04157988694396212', '0.24739764151330632')) def test_J7(): assert simplify(besselj(R(-5,2), pi/2)) == 12/(pi**2) def test_J8(): p = besselj(R(3,2), z) q = (sin(z)/z - cos(z))/sqrt(pi*z/2) assert simplify(expand_func(p) -q) == 0 def test_J9(): assert besselj(0, z).diff(z) == - besselj(1, z) def test_J10(): mu, nu = symbols('mu, nu', integer=True) assert assoc_legendre(nu, mu, 0) == 2**mu*sqrt(pi)/gamma((nu - mu)/2 + 1)/gamma((-nu - mu + 1)/2) def test_J11(): assert simplify(assoc_legendre(3, 1, x)) == simplify(-R(3, 2)*sqrt(1 - x**2)*(5*x**2 - 1)) @slow def test_J12(): assert simplify(chebyshevt(1008, x) - 2*x*chebyshevt(1007, x) + chebyshevt(1006, x)) == 0 def test_J13(): a = symbols('a', integer=True, negative=False) assert chebyshevt(a, -1) == (-1)**a def test_J14(): p = hyper([S.Half, S.Half], [R(3, 2)], z**2) assert hyperexpand(p) == asin(z)/z @XFAIL def test_J15(): raise NotImplementedError("F((n+2)/2,-(n-2)/2,R(3,2),sin(z)**2) == sin(n*z)/(n*sin(z)*cos(z)); F(.) is hypergeometric function") @XFAIL def test_J16(): raise NotImplementedError("diff(zeta(x), x) @ x=0 == -log(2*pi)/2") def test_J17(): assert integrate(f((x + 2)/5)*DiracDelta((x - 2)/3) - g(x)*diff(DiracDelta(x - 1), x), (x, 0, 3)) == 3*f(R(4, 5)) + Subs(Derivative(g(x), x), x, 1) @XFAIL def test_J18(): raise NotImplementedError("define an antisymmetric function") # K. The Complex Domain def test_K1(): z1, z2 = symbols('z1, z2', complex=True) assert re(z1 + I*z2) == -im(z2) + re(z1) assert im(z1 + I*z2) == im(z1) + re(z2) def test_K2(): assert abs(3 - sqrt(7) + I*sqrt(6*sqrt(7) - 15)) == 1 @XFAIL def test_K3(): a, b = symbols('a, b', real=True) assert simplify(abs(1/(a + I/a + I*b))) == 1/sqrt(a**2 + (I/a + b)**2) def test_K4(): assert log(3 + 4*I).expand(complex=True) == log(5) + I*atan(R(4, 3)) def test_K5(): x, y = symbols('x, y', real=True) assert tan(x + I*y).expand(complex=True) == (sin(2*x)/(cos(2*x) + cosh(2*y)) + I*sinh(2*y)/(cos(2*x) + cosh(2*y))) def test_K6(): assert sqrt(x*y*abs(z)**2)/(sqrt(x)*abs(z)) == sqrt(x*y)/sqrt(x) assert sqrt(x*y*abs(z)**2)/(sqrt(x)*abs(z)) != sqrt(y) def test_K7(): y = symbols('y', real=True, negative=False) expr = sqrt(x*y*abs(z)**2)/(sqrt(x)*abs(z)) sexpr = simplify(expr) assert sexpr == sqrt(y) @XFAIL def test_K8(): z = symbols('z', complex=True) assert simplify(sqrt(1/z) - 1/sqrt(z)) != 0 # Passes z = symbols('z', complex=True, negative=False) assert simplify(sqrt(1/z) - 1/sqrt(z)) == 0 # Fails def test_K9(): z = symbols('z', real=True, positive=True) assert simplify(sqrt(1/z) - 1/sqrt(z)) == 0 def test_K10(): z = symbols('z', real=True, negative=True) assert simplify(sqrt(1/z) + 1/sqrt(z)) == 0 # This goes up to K25 # L. Determining Zero Equivalence def test_L1(): assert sqrt(997) - (997**3)**R(1, 6) == 0 def test_L2(): assert sqrt(999983) - (999983**3)**R(1, 6) == 0 def test_L3(): assert simplify((2**R(1, 3) + 4**R(1, 3))**3 - 6*(2**R(1, 3) + 4**R(1, 3)) - 6) == 0 def test_L4(): assert trigsimp(cos(x)**3 + cos(x)*sin(x)**2 - cos(x)) == 0 @XFAIL def test_L5(): assert log(tan(R(1, 2)*x + pi/4)) - asinh(tan(x)) == 0 def test_L6(): assert (log(tan(x/2 + pi/4)) - asinh(tan(x))).diff(x).subs({x: 0}) == 0 @XFAIL def test_L7(): assert simplify(log((2*sqrt(x) + 1)/(sqrt(4*x + 4*sqrt(x) + 1)))) == 0 @XFAIL def test_L8(): assert simplify((4*x + 4*sqrt(x) + 1)**(sqrt(x)/(2*sqrt(x) + 1)) \ *(2*sqrt(x) + 1)**(1/(2*sqrt(x) + 1)) - 2*sqrt(x) - 1) == 0 @XFAIL def test_L9(): z = symbols('z', complex=True) assert simplify(2**(1 - z)*gamma(z)*zeta(z)*cos(z*pi/2) - pi**2*zeta(1 - z)) == 0 # M. Equations @XFAIL def test_M1(): assert Equality(x, 2)/2 + Equality(1, 1) == Equality(x/2 + 1, 2) def test_M2(): # The roots of this equation should all be real. Note that this # doesn't test that they are correct. sol = solveset(3*x**3 - 18*x**2 + 33*x - 19, x) assert all(s.expand(complex=True).is_real for s in sol) @XFAIL def test_M5(): assert solveset(x**6 - 9*x**4 - 4*x**3 + 27*x**2 - 36*x - 23, x) == FiniteSet(2**(1/3) + sqrt(3), 2**(1/3) - sqrt(3), +sqrt(3) - 1/2**(2/3) + I*sqrt(3)/2**(2/3), +sqrt(3) - 1/2**(2/3) - I*sqrt(3)/2**(2/3), -sqrt(3) - 1/2**(2/3) + I*sqrt(3)/2**(2/3), -sqrt(3) - 1/2**(2/3) - I*sqrt(3)/2**(2/3)) def test_M6(): assert set(solveset(x**7 - 1, x)) == \ {cos(n*pi*R(2, 7)) + I*sin(n*pi*R(2, 7)) for n in range(0, 7)} # The paper asks for exp terms, but sin's and cos's may be acceptable; # if the results are simplified, exp terms appear for all but # -sin(pi/14) - I*cos(pi/14) and -sin(pi/14) + I*cos(pi/14) which # will simplify if you apply the transformation foo.rewrite(exp).expand() def test_M7(): # TODO: Replace solve with solveset, as of now test fails for solveset sol = solve(x**8 - 8*x**7 + 34*x**6 - 92*x**5 + 175*x**4 - 236*x**3 + 226*x**2 - 140*x + 46, x) assert [s.simplify() for s in sol] == [ 1 - sqrt(-6 - 2*I*sqrt(3 + 4*sqrt(3)))/2, 1 + sqrt(-6 - 2*I*sqrt(3 + 4*sqrt(3)))/2, 1 - sqrt(-6 + 2*I*sqrt(3 + 4*sqrt(3)))/2, 1 + sqrt(-6 + 2*I*sqrt(3 + 4*sqrt (3)))/2, 1 - sqrt(-6 + 2*sqrt(-3 + 4*sqrt(3)))/2, 1 + sqrt(-6 + 2*sqrt(-3 + 4*sqrt(3)))/2, 1 - sqrt(-6 - 2*sqrt(-3 + 4*sqrt(3)))/2, 1 + sqrt(-6 - 2*sqrt(-3 + 4*sqrt(3)))/2] @XFAIL # There are an infinite number of solutions. def test_M8(): x = Symbol('x') z = symbols('z', complex=True) assert solveset(exp(2*x) + 2*exp(x) + 1 - z, x, S.Reals) == \ FiniteSet(log(1 + z - 2*sqrt(z))/2, log(1 + z + 2*sqrt(z))/2) # This one could be simplified better (the 1/2 could be pulled into the log # as a sqrt, and the function inside the log can be factored as a square, # giving [log(sqrt(z) - 1), log(sqrt(z) + 1)]). Also, there should be an # infinite number of solutions. # x = {log(sqrt(z) - 1), log(sqrt(z) + 1) + i pi} [+ n 2 pi i, + n 2 pi i] # where n is an arbitrary integer. See url of detailed output above. @XFAIL def test_M9(): # x = symbols('x') raise NotImplementedError("solveset(exp(2-x**2)-exp(-x),x) has complex solutions.") def test_M10(): # TODO: Replace solve with solveset, as of now test fails for solveset assert solve(exp(x) - x, x) == [-LambertW(-1)] @XFAIL def test_M11(): assert solveset(x**x - x, x) == FiniteSet(-1, 1) def test_M12(): # TODO: x = [-1, 2*(+/-asinh(1)*I + n*pi}, 3*(pi/6 + n*pi/3)] # TODO: Replace solve with solveset, as of now test fails for solveset assert solve((x + 1)*(sin(x)**2 + 1)**2*cos(3*x)**3, x) == [ -1, pi/6, pi/2, - I*log(1 + sqrt(2)), I*log(1 + sqrt(2)), pi - I*log(1 + sqrt(2)), pi + I*log(1 + sqrt(2)), ] @XFAIL def test_M13(): n = Dummy('n') assert solveset_real(sin(x) - cos(x), x) == ImageSet(Lambda(n, n*pi - pi*R(7, 4)), S.Integers) @XFAIL def test_M14(): n = Dummy('n') assert solveset_real(tan(x) - 1, x) == ImageSet(Lambda(n, n*pi + pi/4), S.Integers) @nocache_fail def test_M15(): n = Dummy('n') # This test fails when running with the cache off: assert solveset(sin(x) - S.Half) in (Union(ImageSet(Lambda(n, 2*n*pi + pi/6), S.Integers), ImageSet(Lambda(n, 2*n*pi + pi*R(5, 6)), S.Integers)), Union(ImageSet(Lambda(n, 2*n*pi + pi*R(5, 6)), S.Integers), ImageSet(Lambda(n, 2*n*pi + pi/6), S.Integers))) @XFAIL def test_M16(): n = Dummy('n') assert solveset(sin(x) - tan(x), x) == ImageSet(Lambda(n, n*pi), S.Integers) @XFAIL def test_M17(): assert solveset_real(asin(x) - atan(x), x) == FiniteSet(0) @XFAIL def test_M18(): assert solveset_real(acos(x) - atan(x), x) == FiniteSet(sqrt((sqrt(5) - 1)/2)) def test_M19(): # TODO: Replace solve with solveset, as of now test fails for solveset assert solve((x - 2)/x**R(1, 3), x) == [2] def test_M20(): assert solveset(sqrt(x**2 + 1) - x + 2, x) == EmptySet def test_M21(): assert solveset(x + sqrt(x) - 2) == FiniteSet(1) def test_M22(): assert solveset(2*sqrt(x) + 3*x**R(1, 4) - 2) == FiniteSet(R(1, 16)) def test_M23(): x = symbols('x', complex=True) # TODO: Replace solve with solveset, as of now test fails for solveset assert solve(x - 1/sqrt(1 + x**2)) == [ -I*sqrt(S.Half + sqrt(5)/2), sqrt(Rational(-1, 2) + sqrt(5)/2)] def test_M24(): # TODO: Replace solve with solveset, as of now test fails for solveset solution = solve(1 - binomial(m, 2)*2**k, k) answer = log(2/(m*(m - 1)), 2) assert solution[0].expand() == answer.expand() def test_M25(): a, b, c, d = symbols(':d', positive=True) x = symbols('x') # TODO: Replace solve with solveset, as of now test fails for solveset assert solve(a*b**x - c*d**x, x)[0].expand() == (log(c/a)/log(b/d)).expand() def test_M26(): # TODO: Replace solve with solveset, as of now test fails for solveset assert solve(sqrt(log(x)) - log(sqrt(x))) == [1, exp(4)] def test_M27(): x = symbols('x', real=True) b = symbols('b', real=True) with assuming(Q.is_true(sin(cos(1/E**2) + 1) + b > 0)): # TODO: Replace solve with solveset solve(log(acos(asin(x**R(2, 3) - b) - 1)) + 2, x) == [-b - sin(1 + cos(1/E**2))**R(3/2), b + sin(1 + cos(1/E**2))**R(3/2)] @XFAIL def test_M28(): assert solveset_real(5*x + exp((x - 5)/2) - 8*x**3, x, assume=Q.real(x)) == [-0.784966, -0.016291, 0.802557] def test_M29(): x = symbols('x') assert solveset(abs(x - 1) - 2, domain=S.Reals) == FiniteSet(-1, 3) def test_M30(): # TODO: Replace solve with solveset, as of now # solveset doesn't supports assumptions # assert solve(abs(2*x + 5) - abs(x - 2),x, assume=Q.real(x)) == [-1, -7] assert solveset_real(abs(2*x + 5) - abs(x - 2), x) == FiniteSet(-1, -7) def test_M31(): # TODO: Replace solve with solveset, as of now # solveset doesn't supports assumptions # assert solve(1 - abs(x) - max(-x - 2, x - 2),x, assume=Q.real(x)) == [-3/2, 3/2] assert solveset_real(1 - abs(x) - Max(-x - 2, x - 2), x) == FiniteSet(R(-3, 2), R(3, 2)) @XFAIL def test_M32(): # TODO: Replace solve with solveset, as of now # solveset doesn't supports assumptions assert solveset_real(Max(2 - x**2, x)- Max(-x, (x**3)/9), x) == FiniteSet(-1, 3) @XFAIL def test_M33(): # TODO: Replace solve with solveset, as of now # solveset doesn't supports assumptions # Second answer can be written in another form. The second answer is the root of x**3 + 9*x**2 - 18 = 0 in the interval (-2, -1). assert solveset_real(Max(2 - x**2, x) - x**3/9, x) == FiniteSet(-3, -1.554894, 3) @XFAIL def test_M34(): z = symbols('z', complex=True) assert solveset((1 + I) * z + (2 - I) * conjugate(z) + 3*I, z) == FiniteSet(2 + 3*I) def test_M35(): x, y = symbols('x y', real=True) assert linsolve((3*x - 2*y - I*y + 3*I).as_real_imag(), y, x) == FiniteSet((3, 2)) def test_M36(): # TODO: Replace solve with solveset, as of now # solveset doesn't supports solving for function # assert solve(f**2 + f - 2, x) == [Eq(f(x), 1), Eq(f(x), -2)] assert solveset(f(x)**2 + f(x) - 2, f(x)) == FiniteSet(-2, 1) def test_M37(): assert linsolve([x + y + z - 6, 2*x + y + 2*z - 10, x + 3*y + z - 10 ], x, y, z) == \ FiniteSet((-z + 4, 2, z)) def test_M38(): a, b, c = symbols('a, b, c') domain = FracField([a, b, c], ZZ).to_domain() ring = PolyRing('k1:50', domain) (k1, k2, k3, k4, k5, k6, k7, k8, k9, k10, k11, k12, k13, k14, k15, k16, k17, k18, k19, k20, k21, k22, k23, k24, k25, k26, k27, k28, k29, k30, k31, k32, k33, k34, k35, k36, k37, k38, k39, k40, k41, k42, k43, k44, k45, k46, k47, k48, k49) = ring.gens system = [ -b*k8/a + c*k8/a, -b*k11/a + c*k11/a, -b*k10/a + c*k10/a + k2, -k3 - b*k9/a + c*k9/a, -b*k14/a + c*k14/a, -b*k15/a + c*k15/a, -b*k18/a + c*k18/a - k2, -b*k17/a + c*k17/a, -b*k16/a + c*k16/a + k4, -b*k13/a + c*k13/a - b*k21/a + c*k21/a + b*k5/a - c*k5/a, b*k44/a - c*k44/a, -b*k45/a + c*k45/a, -b*k20/a + c*k20/a, -b*k44/a + c*k44/a, b*k46/a - c*k46/a, b**2*k47/a**2 - 2*b*c*k47/a**2 + c**2*k47/a**2, k3, -k4, -b*k12/a + c*k12/a - a*k6/b + c*k6/b, -b*k19/a + c*k19/a + a*k7/c - b*k7/c, b*k45/a - c*k45/a, -b*k46/a + c*k46/a, -k48 + c*k48/a + c*k48/b - c**2*k48/(a*b), -k49 + b*k49/a + b*k49/c - b**2*k49/(a*c), a*k1/b - c*k1/b, a*k4/b - c*k4/b, a*k3/b - c*k3/b + k9, -k10 + a*k2/b - c*k2/b, a*k7/b - c*k7/b, -k9, k11, b*k12/a - c*k12/a + a*k6/b - c*k6/b, a*k15/b - c*k15/b, k10 + a*k18/b - c*k18/b, -k11 + a*k17/b - c*k17/b, a*k16/b - c*k16/b, -a*k13/b + c*k13/b + a*k21/b - c*k21/b + a*k5/b - c*k5/b, -a*k44/b + c*k44/b, a*k45/b - c*k45/b, a*k14/c - b*k14/c + a*k20/b - c*k20/b, a*k44/b - c*k44/b, -a*k46/b + c*k46/b, -k47 + c*k47/a + c*k47/b - c**2*k47/(a*b), a*k19/b - c*k19/b, -a*k45/b + c*k45/b, a*k46/b - c*k46/b, a**2*k48/b**2 - 2*a*c*k48/b**2 + c**2*k48/b**2, -k49 + a*k49/b + a*k49/c - a**2*k49/(b*c), k16, -k17, -a*k1/c + b*k1/c, -k16 - a*k4/c + b*k4/c, -a*k3/c + b*k3/c, k18 - a*k2/c + b*k2/c, b*k19/a - c*k19/a - a*k7/c + b*k7/c, -a*k6/c + b*k6/c, -a*k8/c + b*k8/c, -a*k11/c + b*k11/c + k17, -a*k10/c + b*k10/c - k18, -a*k9/c + b*k9/c, -a*k14/c + b*k14/c - a*k20/b + c*k20/b, -a*k13/c + b*k13/c + a*k21/c - b*k21/c - a*k5/c + b*k5/c, a*k44/c - b*k44/c, -a*k45/c + b*k45/c, -a*k44/c + b*k44/c, a*k46/c - b*k46/c, -k47 + b*k47/a + b*k47/c - b**2*k47/(a*c), -a*k12/c + b*k12/c, a*k45/c - b*k45/c, -a*k46/c + b*k46/c, -k48 + a*k48/b + a*k48/c - a**2*k48/(b*c), a**2*k49/c**2 - 2*a*b*k49/c**2 + b**2*k49/c**2, k8, k11, -k15, k10 - k18, -k17, k9, -k16, -k29, k14 - k32, -k21 + k23 - k31, -k24 - k30, -k35, k44, -k45, k36, k13 - k23 + k39, -k20 + k38, k25 + k37, b*k26/a - c*k26/a - k34 + k42, -2*k44, k45, k46, b*k47/a - c*k47/a, k41, k44, -k46, -b*k47/a + c*k47/a, k12 + k24, -k19 - k25, -a*k27/b + c*k27/b - k33, k45, -k46, -a*k48/b + c*k48/b, a*k28/c - b*k28/c + k40, -k45, k46, a*k48/b - c*k48/b, a*k49/c - b*k49/c, -a*k49/c + b*k49/c, -k1, -k4, -k3, k15, k18 - k2, k17, k16, k22, k25 - k7, k24 + k30, k21 + k23 - k31, k28, -k44, k45, -k30 - k6, k20 + k32, k27 + b*k33/a - c*k33/a, k44, -k46, -b*k47/a + c*k47/a, -k36, k31 - k39 - k5, -k32 - k38, k19 - k37, k26 - a*k34/b + c*k34/b - k42, k44, -2*k45, k46, a*k48/b - c*k48/b, a*k35/c - b*k35/c - k41, -k44, k46, b*k47/a - c*k47/a, -a*k49/c + b*k49/c, -k40, k45, -k46, -a*k48/b + c*k48/b, a*k49/c - b*k49/c, k1, k4, k3, -k8, -k11, -k10 + k2, -k9, k37 + k7, -k14 - k38, -k22, -k25 - k37, -k24 + k6, -k13 - k23 + k39, -k28 + b*k40/a - c*k40/a, k44, -k45, -k27, -k44, k46, b*k47/a - c*k47/a, k29, k32 + k38, k31 - k39 + k5, -k12 + k30, k35 - a*k41/b + c*k41/b, -k44, k45, -k26 + k34 + a*k42/c - b*k42/c, k44, k45, -2*k46, -b*k47/a + c*k47/a, -a*k48/b + c*k48/b, a*k49/c - b*k49/c, k33, -k45, k46, a*k48/b - c*k48/b, -a*k49/c + b*k49/c ] solution = { k49: 0, k48: 0, k47: 0, k46: 0, k45: 0, k44: 0, k41: 0, k40: 0, k38: 0, k37: 0, k36: 0, k35: 0, k33: 0, k32: 0, k30: 0, k29: 0, k28: 0, k27: 0, k25: 0, k24: 0, k22: 0, k21: 0, k20: 0, k19: 0, k18: 0, k17: 0, k16: 0, k15: 0, k14: 0, k13: 0, k12: 0, k11: 0, k10: 0, k9: 0, k8: 0, k7: 0, k6: 0, k5: 0, k4: 0, k3: 0, k2: 0, k1: 0, k34: b/c*k42, k31: k39, k26: a/c*k42, k23: k39 } assert solve_lin_sys(system, ring) == solution def test_M39(): x, y, z = symbols('x y z', complex=True) # TODO: Replace solve with solveset, as of now # solveset doesn't supports non-linear multivariate assert solve([x**2*y + 3*y*z - 4, -3*x**2*z + 2*y**2 + 1, 2*y*z**2 - z**2 - 1 ]) ==\ [{y: 1, z: 1, x: -1}, {y: 1, z: 1, x: 1},\ {y: sqrt(2)*I, z: R(1,3) - sqrt(2)*I/3, x: -sqrt(-1 - sqrt(2)*I)},\ {y: sqrt(2)*I, z: R(1,3) - sqrt(2)*I/3, x: sqrt(-1 - sqrt(2)*I)},\ {y: -sqrt(2)*I, z: R(1,3) + sqrt(2)*I/3, x: -sqrt(-1 + sqrt(2)*I)},\ {y: -sqrt(2)*I, z: R(1,3) + sqrt(2)*I/3, x: sqrt(-1 + sqrt(2)*I)}] # N. Inequalities def test_N1(): assert ask(Q.is_true(E**pi > pi**E)) @XFAIL def test_N2(): x = symbols('x', real=True) assert ask(Q.is_true(x**4 - x + 1 > 0)) is True assert ask(Q.is_true(x**4 - x + 1 > 1)) is False @XFAIL def test_N3(): x = symbols('x', real=True) assert ask(Q.is_true(And(Lt(-1, x), Lt(x, 1))), Q.is_true(abs(x) < 1 )) @XFAIL def test_N4(): x, y = symbols('x y', real=True) assert ask(Q.is_true(2*x**2 > 2*y**2), Q.is_true((x > y) & (y > 0))) is True @XFAIL def test_N5(): x, y, k = symbols('x y k', real=True) assert ask(Q.is_true(k*x**2 > k*y**2), Q.is_true((x > y) & (y > 0) & (k > 0))) is True @XFAIL def test_N6(): x, y, k, n = symbols('x y k n', real=True) assert ask(Q.is_true(k*x**n > k*y**n), Q.is_true((x > y) & (y > 0) & (k > 0) & (n > 0))) is True @XFAIL def test_N7(): x, y = symbols('x y', real=True) assert ask(Q.is_true(y > 0), Q.is_true((x > 1) & (y >= x - 1))) is True @XFAIL def test_N8(): x, y, z = symbols('x y z', real=True) assert ask(Q.is_true((x == y) & (y == z)), Q.is_true((x >= y) & (y >= z) & (z >= x))) def test_N9(): x = Symbol('x') assert solveset(abs(x - 1) > 2, domain=S.Reals) == Union(Interval(-oo, -1, False, True), Interval(3, oo, True)) def test_N10(): x = Symbol('x') p = (x - 1)*(x - 2)*(x - 3)*(x - 4)*(x - 5) assert solveset(expand(p) < 0, domain=S.Reals) == Union(Interval(-oo, 1, True, True), Interval(2, 3, True, True), Interval(4, 5, True, True)) def test_N11(): x = Symbol('x') assert solveset(6/(x - 3) <= 3, domain=S.Reals) == Union(Interval(-oo, 3, True, True), Interval(5, oo)) def test_N12(): x = Symbol('x') assert solveset(sqrt(x) < 2, domain=S.Reals) == Interval(0, 4, False, True) def test_N13(): x = Symbol('x') assert solveset(sin(x) < 2, domain=S.Reals) == S.Reals @XFAIL def test_N14(): x = Symbol('x') # Gives 'Union(Interval(Integer(0), Mul(Rational(1, 2), pi), false, true), # Interval(Mul(Rational(1, 2), pi), Mul(Integer(2), pi), true, false))' # which is not the correct answer, but the provided also seems wrong. assert solveset(sin(x) < 1, x, domain=S.Reals) == Union(Interval(-oo, pi/2, True, True), Interval(pi/2, oo, True, True)) def test_N15(): r, t = symbols('r t') # raises NotImplementedError: only univariate inequalities are supported solveset(abs(2*r*(cos(t) - 1) + 1) <= 1, r, S.Reals) def test_N16(): r, t = symbols('r t') solveset((r**2)*((cos(t) - 4)**2)*sin(t)**2 < 9, r, S.Reals) @XFAIL def test_N17(): # currently only univariate inequalities are supported assert solveset((x + y > 0, x - y < 0), (x, y)) == (abs(x) < y) def test_O1(): M = Matrix((1 + I, -2, 3*I)) assert sqrt(expand(M.dot(M.H))) == sqrt(15) def test_O2(): assert Matrix((2, 2, -3)).cross(Matrix((1, 3, 1))) == Matrix([[11], [-5], [4]]) # The vector module has no way of representing vectors symbolically (without # respect to a basis) @XFAIL def test_O3(): # assert (va ^ vb) | (vc ^ vd) == -(va | vc)*(vb | vd) + (va | vd)*(vb | vc) raise NotImplementedError("""The vector module has no way of representing vectors symbolically (without respect to a basis)""") def test_O4(): from sympy.vector import CoordSys3D, Del N = CoordSys3D("N") delop = Del() i, j, k = N.base_vectors() x, y, z = N.base_scalars() F = i*(x*y*z) + j*((x*y*z)**2) + k*((y**2)*(z**3)) assert delop.cross(F).doit() == (-2*x**2*y**2*z + 2*y*z**3)*i + x*y*j + (2*x*y**2*z**2 - x*z)*k @XFAIL def test_O5(): #assert grad|(f^g)-g|(grad^f)+f|(grad^g) == 0 raise NotImplementedError("""The vector module has no way of representing vectors symbolically (without respect to a basis)""") #testO8-O9 MISSING!! def test_O10(): L = [Matrix([2, 3, 5]), Matrix([3, 6, 2]), Matrix([8, 3, 6])] assert GramSchmidt(L) == [Matrix([ [2], [3], [5]]), Matrix([ [R(23, 19)], [R(63, 19)], [R(-47, 19)]]), Matrix([ [R(1692, 353)], [R(-1551, 706)], [R(-423, 706)]])] def test_P1(): assert Matrix(3, 3, lambda i, j: j - i).diagonal(-1) == Matrix( 1, 2, [-1, -1]) def test_P2(): M = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) M.row_del(1) M.col_del(2) assert M == Matrix([[1, 2], [7, 8]]) def test_P3(): A = Matrix([ [11, 12, 13, 14], [21, 22, 23, 24], [31, 32, 33, 34], [41, 42, 43, 44]]) A11 = A[0:3, 1:4] A12 = A[(0, 1, 3), (2, 0, 3)] A21 = A A221 = -A[0:2, 2:4] A222 = -A[(3, 0), (2, 1)] A22 = BlockMatrix([[A221, A222]]).T rows = [[-A11, A12], [A21, A22]] raises(ValueError, lambda: BlockMatrix(rows)) B = Matrix(rows) assert B == Matrix([ [-12, -13, -14, 13, 11, 14], [-22, -23, -24, 23, 21, 24], [-32, -33, -34, 43, 41, 44], [11, 12, 13, 14, -13, -23], [21, 22, 23, 24, -14, -24], [31, 32, 33, 34, -43, -13], [41, 42, 43, 44, -42, -12]]) @XFAIL def test_P4(): raise NotImplementedError("Block matrix diagonalization not supported") def test_P5(): M = Matrix([[7, 11], [3, 8]]) assert M % 2 == Matrix([[1, 1], [1, 0]]) def test_P6(): M = Matrix([[cos(x), sin(x)], [-sin(x), cos(x)]]) assert M.diff(x, 2) == Matrix([[-cos(x), -sin(x)], [sin(x), -cos(x)]]) def test_P7(): M = Matrix([[x, y]])*( z*Matrix([[1, 3, 5], [2, 4, 6]]) + Matrix([[7, -9, 11], [-8, 10, -12]])) assert M == Matrix([[x*(z + 7) + y*(2*z - 8), x*(3*z - 9) + y*(4*z + 10), x*(5*z + 11) + y*(6*z - 12)]]) def test_P8(): M = Matrix([[1, -2*I], [-3*I, 4]]) assert M.norm(ord=S.Infinity) == 7 def test_P9(): a, b, c = symbols('a b c', nonzero=True) M = Matrix([[a/(b*c), 1/c, 1/b], [1/c, b/(a*c), 1/a], [1/b, 1/a, c/(a*b)]]) assert factor(M.norm('fro')) == (a**2 + b**2 + c**2)/(abs(a)*abs(b)*abs(c)) @XFAIL def test_P10(): M = Matrix([[1, 2 + 3*I], [f(4 - 5*I), 6]]) # conjugate(f(4 - 5*i)) is not simplified to f(4+5*I) assert M.H == Matrix([[1, f(4 + 5*I)], [2 + 3*I, 6]]) @XFAIL def test_P11(): # raises NotImplementedError("Matrix([[x,y],[1,x*y]]).inv() # not simplifying to extract common factor") assert Matrix([[x, y], [1, x*y]]).inv() == (1/(x**2 - 1))*Matrix([[x, -1], [-1/y, x/y]]) def test_P11_workaround(): # This test was changed to inverse method ADJ because it depended on the # specific form of inverse returned from the 'GE' method which has changed. M = Matrix([[x, y], [1, x*y]]).inv('ADJ') c = gcd(tuple(M)) assert MatMul(c, M/c, evaluate=False) == MatMul(c, Matrix([ [x*y, -y], [ -1, x]]), evaluate=False) def test_P12(): A11 = MatrixSymbol('A11', n, n) A12 = MatrixSymbol('A12', n, n) A22 = MatrixSymbol('A22', n, n) B = BlockMatrix([[A11, A12], [ZeroMatrix(n, n), A22]]) assert block_collapse(B.I) == BlockMatrix([[A11.I, (-1)*A11.I*A12*A22.I], [ZeroMatrix(n, n), A22.I]]) def test_P13(): M = Matrix([[1, x - 2, x - 3], [x - 1, x**2 - 3*x + 6, x**2 - 3*x - 2], [x - 2, x**2 - 8, 2*(x**2) - 12*x + 14]]) L, U, _ = M.LUdecomposition() assert simplify(L) == Matrix([[1, 0, 0], [x - 1, 1, 0], [x - 2, x - 3, 1]]) assert simplify(U) == Matrix([[1, x - 2, x - 3], [0, 4, x - 5], [0, 0, x - 7]]) def test_P14(): M = Matrix([[1, 2, 3, 1, 3], [3, 2, 1, 1, 7], [0, 2, 4, 1, 1], [1, 1, 1, 1, 4]]) R, _ = M.rref() assert R == Matrix([[1, 0, -1, 0, 2], [0, 1, 2, 0, -1], [0, 0, 0, 1, 3], [0, 0, 0, 0, 0]]) def test_P15(): M = Matrix([[-1, 3, 7, -5], [4, -2, 1, 3], [2, 4, 15, -7]]) assert M.rank() == 2 def test_P16(): M = Matrix([[2*sqrt(2), 8], [6*sqrt(6), 24*sqrt(3)]]) assert M.rank() == 1 def test_P17(): t = symbols('t', real=True) M=Matrix([ [sin(2*t), cos(2*t)], [2*(1 - (cos(t)**2))*cos(t), (1 - 2*(sin(t)**2))*sin(t)]]) assert M.rank() == 1 def test_P18(): M = Matrix([[1, 0, -2, 0], [-2, 1, 0, 3], [-1, 2, -6, 6]]) assert M.nullspace() == [Matrix([[2], [4], [1], [0]]), Matrix([[0], [-3], [0], [1]])] def test_P19(): w = symbols('w') M = Matrix([[1, 1, 1, 1], [w, x, y, z], [w**2, x**2, y**2, z**2], [w**3, x**3, y**3, z**3]]) assert M.det() == (w**3*x**2*y - w**3*x**2*z - w**3*x*y**2 + w**3*x*z**2 + w**3*y**2*z - w**3*y*z**2 - w**2*x**3*y + w**2*x**3*z + w**2*x*y**3 - w**2*x*z**3 - w**2*y**3*z + w**2*y*z**3 + w*x**3*y**2 - w*x**3*z**2 - w*x**2*y**3 + w*x**2*z**3 + w*y**3*z**2 - w*y**2*z**3 - x**3*y**2*z + x**3*y*z**2 + x**2*y**3*z - x**2*y*z**3 - x*y**3*z**2 + x*y**2*z**3 ) @XFAIL def test_P20(): raise NotImplementedError("Matrix minimal polynomial not supported") def test_P21(): M = Matrix([[5, -3, -7], [-2, 1, 2], [2, -3, -4]]) assert M.charpoly(x).as_expr() == x**3 - 2*x**2 - 5*x + 6 def test_P22(): d = 100 M = (2 - x)*eye(d) assert M.eigenvals() == {-x + 2: d} def test_P23(): M = Matrix([ [2, 1, 0, 0, 0], [1, 2, 1, 0, 0], [0, 1, 2, 1, 0], [0, 0, 1, 2, 1], [0, 0, 0, 1, 2]]) assert M.eigenvals() == { S('1'): 1, S('2'): 1, S('3'): 1, S('sqrt(3) + 2'): 1, S('-sqrt(3) + 2'): 1} def test_P24(): M = Matrix([[611, 196, -192, 407, -8, -52, -49, 29], [196, 899, 113, -192, -71, -43, -8, -44], [-192, 113, 899, 196, 61, 49, 8, 52], [ 407, -192, 196, 611, 8, 44, 59, -23], [ -8, -71, 61, 8, 411, -599, 208, 208], [ -52, -43, 49, 44, -599, 411, 208, 208], [ -49, -8, 8, 59, 208, 208, 99, -911], [ 29, -44, 52, -23, 208, 208, -911, 99]]) assert M.eigenvals() == { S('0'): 1, S('10*sqrt(10405)'): 1, S('100*sqrt(26) + 510'): 1, S('1000'): 2, S('-100*sqrt(26) + 510'): 1, S('-10*sqrt(10405)'): 1, S('1020'): 1} def test_P25(): MF = N(Matrix([[ 611, 196, -192, 407, -8, -52, -49, 29], [ 196, 899, 113, -192, -71, -43, -8, -44], [-192, 113, 899, 196, 61, 49, 8, 52], [ 407, -192, 196, 611, 8, 44, 59, -23], [ -8, -71, 61, 8, 411, -599, 208, 208], [ -52, -43, 49, 44, -599, 411, 208, 208], [ -49, -8, 8, 59, 208, 208, 99, -911], [ 29, -44, 52, -23, 208, 208, -911, 99]])) assert (Matrix(sorted(MF.eigenvals())) - Matrix( [-1020.0490184299969, 0.0, 0.09804864072151699, 1000.0, 1019.9019513592784, 1020.0, 1020.0490184299969])).norm() < 1e-13 def test_P26(): a0, a1, a2, a3, a4 = symbols('a0 a1 a2 a3 a4') M = Matrix([[-a4, -a3, -a2, -a1, -a0, 0, 0, 0, 0], [ 1, 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 1, 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 1, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 1, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, -1, -1, 0, 0], [ 0, 0, 0, 0, 0, 1, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 1, -1, -1], [ 0, 0, 0, 0, 0, 0, 0, 1, 0]]) assert M.eigenvals(error_when_incomplete=False) == { S('-1/2 - sqrt(3)*I/2'): 2, S('-1/2 + sqrt(3)*I/2'): 2} def test_P27(): a = symbols('a') M = Matrix([[a, 0, 0, 0, 0], [0, 0, 0, 0, 1], [0, 0, a, 0, 0], [0, 0, 0, a, 0], [0, -2, 0, 0, 2]]) assert M.eigenvects() == [(a, 3, [Matrix([[1], [0], [0], [0], [0]]), Matrix([[0], [0], [1], [0], [0]]), Matrix([[0], [0], [0], [1], [0]])]), (1 - I, 1, [Matrix([[ 0], [S(1)/2 + I/2], [ 0], [ 0], [ 1]])]), (1 + I, 1, [Matrix([[ 0], [S(1)/2 - I/2], [ 0], [ 0], [ 1]])])] @XFAIL def test_P28(): raise NotImplementedError("Generalized eigenvectors not supported \ https://github.com/sympy/sympy/issues/5293") @XFAIL def test_P29(): raise NotImplementedError("Generalized eigenvectors not supported \ https://github.com/sympy/sympy/issues/5293") def test_P30(): M = Matrix([[1, 0, 0, 1, -1], [0, 1, -2, 3, -3], [0, 0, -1, 2, -2], [1, -1, 1, 0, 1], [1, -1, 1, -1, 2]]) _, J = M.jordan_form() assert J == Matrix([[-1, 0, 0, 0, 0], [0, 1, 1, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 1, 1], [0, 0, 0, 0, 1]]) @XFAIL def test_P31(): raise NotImplementedError("Smith normal form not implemented") def test_P32(): M = Matrix([[1, -2], [2, 1]]) assert exp(M).rewrite(cos).simplify() == Matrix([[E*cos(2), -E*sin(2)], [E*sin(2), E*cos(2)]]) def test_P33(): w, t = symbols('w t') M = Matrix([[0, 1, 0, 0], [0, 0, 0, 2*w], [0, 0, 0, 1], [0, -2*w, 3*w**2, 0]]) assert exp(M*t).rewrite(cos).expand() == Matrix([ [1, -3*t + 4*sin(t*w)/w, 6*t*w - 6*sin(t*w), -2*cos(t*w)/w + 2/w], [0, 4*cos(t*w) - 3, -6*w*cos(t*w) + 6*w, 2*sin(t*w)], [0, 2*cos(t*w)/w - 2/w, -3*cos(t*w) + 4, sin(t*w)/w], [0, -2*sin(t*w), 3*w*sin(t*w), cos(t*w)]]) @XFAIL def test_P34(): a, b, c = symbols('a b c', real=True) M = Matrix([[a, 1, 0, 0, 0, 0], [0, a, 0, 0, 0, 0], [0, 0, b, 0, 0, 0], [0, 0, 0, c, 1, 0], [0, 0, 0, 0, c, 1], [0, 0, 0, 0, 0, c]]) # raises exception, sin(M) not supported. exp(M*I) also not supported # https://github.com/sympy/sympy/issues/6218 assert sin(M) == Matrix([[sin(a), cos(a), 0, 0, 0, 0], [0, sin(a), 0, 0, 0, 0], [0, 0, sin(b), 0, 0, 0], [0, 0, 0, sin(c), cos(c), -sin(c)/2], [0, 0, 0, 0, sin(c), cos(c)], [0, 0, 0, 0, 0, sin(c)]]) @XFAIL def test_P35(): M = pi/2*Matrix([[2, 1, 1], [2, 3, 2], [1, 1, 2]]) # raises exception, sin(M) not supported. exp(M*I) also not supported # https://github.com/sympy/sympy/issues/6218 assert sin(M) == eye(3) @XFAIL def test_P36(): M = Matrix([[10, 7], [7, 17]]) assert sqrt(M) == Matrix([[3, 1], [1, 4]]) def test_P37(): M = Matrix([[1, 1, 0], [0, 1, 0], [0, 0, 1]]) assert M**S.Half == Matrix([[1, R(1, 2), 0], [0, 1, 0], [0, 0, 1]]) @XFAIL def test_P38(): M=Matrix([[0, 1, 0], [0, 0, 0], [0, 0, 0]]) #raises ValueError: Matrix det == 0; not invertible M**S.Half @XFAIL def test_P39(): """ M=Matrix([ [1, 1], [2, 2], [3, 3]]) M.SVD() """ raise NotImplementedError("Singular value decomposition not implemented") def test_P40(): r, t = symbols('r t', real=True) M = Matrix([r*cos(t), r*sin(t)]) assert M.jacobian(Matrix([r, t])) == Matrix([[cos(t), -r*sin(t)], [sin(t), r*cos(t)]]) def test_P41(): r, t = symbols('r t', real=True) assert hessian(r**2*sin(t),(r,t)) == Matrix([[ 2*sin(t), 2*r*cos(t)], [2*r*cos(t), -r**2*sin(t)]]) def test_P42(): assert wronskian([cos(x), sin(x)], x).simplify() == 1 def test_P43(): def __my_jacobian(M, Y): return Matrix([M.diff(v).T for v in Y]).T r, t = symbols('r t', real=True) M = Matrix([r*cos(t), r*sin(t)]) assert __my_jacobian(M,[r,t]) == Matrix([[cos(t), -r*sin(t)], [sin(t), r*cos(t)]]) def test_P44(): def __my_hessian(f, Y): V = Matrix([diff(f, v) for v in Y]) return Matrix([V.T.diff(v) for v in Y]) r, t = symbols('r t', real=True) assert __my_hessian(r**2*sin(t), (r, t)) == Matrix([ [ 2*sin(t), 2*r*cos(t)], [2*r*cos(t), -r**2*sin(t)]]) def test_P45(): def __my_wronskian(Y, v): M = Matrix([Matrix(Y).T.diff(x, n) for n in range(0, len(Y))]) return M.det() assert __my_wronskian([cos(x), sin(x)], x).simplify() == 1 # Q1-Q6 Tensor tests missing @XFAIL def test_R1(): i, j, n = symbols('i j n', integer=True, positive=True) xn = MatrixSymbol('xn', n, 1) Sm = Sum((xn[i, 0] - Sum(xn[j, 0], (j, 0, n - 1))/n)**2, (i, 0, n - 1)) # sum does not calculate # Unknown result Sm.doit() raise NotImplementedError('Unknown result') @XFAIL def test_R2(): m, b = symbols('m b') i, n = symbols('i n', integer=True, positive=True) xn = MatrixSymbol('xn', n, 1) yn = MatrixSymbol('yn', n, 1) f = Sum((yn[i, 0] - m*xn[i, 0] - b)**2, (i, 0, n - 1)) f1 = diff(f, m) f2 = diff(f, b) # raises TypeError: solveset() takes at most 2 arguments (3 given) solveset((f1, f2), (m, b), domain=S.Reals) @XFAIL def test_R3(): n, k = symbols('n k', integer=True, positive=True) sk = ((-1)**k) * (binomial(2*n, k))**2 Sm = Sum(sk, (k, 1, oo)) T = Sm.doit() T2 = T.combsimp() # returns -((-1)**n*factorial(2*n) # - (factorial(n))**2)*exp_polar(-I*pi)/(factorial(n))**2 assert T2 == (-1)**n*binomial(2*n, n) @XFAIL def test_R4(): # Macsyma indefinite sum test case: #(c15) /* Check whether the full Gosper algorithm is implemented # => 1/2^(n + 1) binomial(n, k - 1) */ #closedform(indefsum(binomial(n, k)/2^n - binomial(n + 1, k)/2^(n + 1), k)); #Time= 2690 msecs # (- n + k - 1) binomial(n + 1, k) #(d15) - -------------------------------- # n # 2 2 (n + 1) # #(c16) factcomb(makefact(%)); #Time= 220 msecs # n! #(d16) ---------------- # n # 2 k! 2 (n - k)! # Might be possible after fixing https://github.com/sympy/sympy/pull/1879 raise NotImplementedError("Indefinite sum not supported") @XFAIL def test_R5(): a, b, c, n, k = symbols('a b c n k', integer=True, positive=True) sk = ((-1)**k)*(binomial(a + b, a + k) *binomial(b + c, b + k)*binomial(c + a, c + k)) Sm = Sum(sk, (k, 1, oo)) T = Sm.doit() # hypergeometric series not calculated assert T == factorial(a+b+c)/(factorial(a)*factorial(b)*factorial(c)) def test_R6(): n, k = symbols('n k', integer=True, positive=True) gn = MatrixSymbol('gn', n + 2, 1) Sm = Sum(gn[k, 0] - gn[k - 1, 0], (k, 1, n + 1)) assert Sm.doit() == -gn[0, 0] + gn[n + 1, 0] def test_R7(): n, k = symbols('n k', integer=True, positive=True) T = Sum(k**3,(k,1,n)).doit() assert T.factor() == n**2*(n + 1)**2/4 @XFAIL def test_R8(): n, k = symbols('n k', integer=True, positive=True) Sm = Sum(k**2*binomial(n, k), (k, 1, n)) T = Sm.doit() #returns Piecewise function assert T.combsimp() == n*(n + 1)*2**(n - 2) def test_R9(): n, k = symbols('n k', integer=True, positive=True) Sm = Sum(binomial(n, k - 1)/k, (k, 1, n + 1)) assert Sm.doit().simplify() == (2**(n + 1) - 1)/(n + 1) @XFAIL def test_R10(): n, m, r, k = symbols('n m r k', integer=True, positive=True) Sm = Sum(binomial(n, k)*binomial(m, r - k), (k, 0, r)) T = Sm.doit() T2 = T.combsimp().rewrite(factorial) assert T2 == factorial(m + n)/(factorial(r)*factorial(m + n - r)) assert T2 == binomial(m + n, r).rewrite(factorial) # rewrite(binomial) is not working. # https://github.com/sympy/sympy/issues/7135 T3 = T2.rewrite(binomial) assert T3 == binomial(m + n, r) @XFAIL def test_R11(): n, k = symbols('n k', integer=True, positive=True) sk = binomial(n, k)*fibonacci(k) Sm = Sum(sk, (k, 0, n)) T = Sm.doit() # Fibonacci simplification not implemented # https://github.com/sympy/sympy/issues/7134 assert T == fibonacci(2*n) @XFAIL def test_R12(): n, k = symbols('n k', integer=True, positive=True) Sm = Sum(fibonacci(k)**2, (k, 0, n)) T = Sm.doit() assert T == fibonacci(n)*fibonacci(n + 1) @XFAIL def test_R13(): n, k = symbols('n k', integer=True, positive=True) Sm = Sum(sin(k*x), (k, 1, n)) T = Sm.doit() # Sum is not calculated assert T.simplify() == cot(x/2)/2 - cos(x*(2*n + 1)/2)/(2*sin(x/2)) @XFAIL def test_R14(): n, k = symbols('n k', integer=True, positive=True) Sm = Sum(sin((2*k - 1)*x), (k, 1, n)) T = Sm.doit() # Sum is not calculated assert T.simplify() == sin(n*x)**2/sin(x) @XFAIL def test_R15(): n, k = symbols('n k', integer=True, positive=True) Sm = Sum(binomial(n - k, k), (k, 0, floor(n/2))) T = Sm.doit() # Sum is not calculated assert T.simplify() == fibonacci(n + 1) def test_R16(): k = symbols('k', integer=True, positive=True) Sm = Sum(1/k**2 + 1/k**3, (k, 1, oo)) assert Sm.doit() == zeta(3) + pi**2/6 def test_R17(): k = symbols('k', integer=True, positive=True) assert abs(float(Sum(1/k**2 + 1/k**3, (k, 1, oo))) - 2.8469909700078206) < 1e-15 def test_R18(): k = symbols('k', integer=True, positive=True) Sm = Sum(1/(2**k*k**2), (k, 1, oo)) T = Sm.doit() assert T.simplify() == -log(2)**2/2 + pi**2/12 @slow @XFAIL def test_R19(): k = symbols('k', integer=True, positive=True) Sm = Sum(1/((3*k + 1)*(3*k + 2)*(3*k + 3)), (k, 0, oo)) T = Sm.doit() # assert fails, T not simplified assert T.simplify() == -log(3)/4 + sqrt(3)*pi/12 @XFAIL def test_R20(): n, k = symbols('n k', integer=True, positive=True) Sm = Sum(binomial(n, 4*k), (k, 0, oo)) T = Sm.doit() # assert fails, T not simplified assert T.simplify() == 2**(n/2)*cos(pi*n/4)/2 + 2**(n - 1)/2 @XFAIL def test_R21(): k = symbols('k', integer=True, positive=True) Sm = Sum(1/(sqrt(k*(k + 1)) * (sqrt(k) + sqrt(k + 1))), (k, 1, oo)) T = Sm.doit() # Sum not calculated assert T.simplify() == 1 # test_R22 answer not available in Wester samples # Sum(Sum(binomial(n, k)*binomial(n - k, n - 2*k)*x**n*y**(n - 2*k), # (k, 0, floor(n/2))), (n, 0, oo)) with abs(x*y)<1? @XFAIL def test_R23(): n, k = symbols('n k', integer=True, positive=True) Sm = Sum(Sum((factorial(n)/(factorial(k)**2*factorial(n - 2*k)))* (x/y)**k*(x*y)**(n - k), (n, 2*k, oo)), (k, 0, oo)) # Missing how to express constraint abs(x*y)<1? T = Sm.doit() # Sum not calculated assert T == -1/sqrt(x**2*y**2 - 4*x**2 - 2*x*y + 1) def test_R24(): m, k = symbols('m k', integer=True, positive=True) Sm = Sum(Product(k/(2*k - 1), (k, 1, m)), (m, 2, oo)) assert Sm.doit() == pi/2 def test_S1(): k = symbols('k', integer=True, positive=True) Pr = Product(gamma(k/3), (k, 1, 8)) assert Pr.doit().simplify() == 640*sqrt(3)*pi**3/6561 def test_S2(): n, k = symbols('n k', integer=True, positive=True) assert Product(k, (k, 1, n)).doit() == factorial(n) def test_S3(): n, k = symbols('n k', integer=True, positive=True) assert Product(x**k, (k, 1, n)).doit().simplify() == x**(n*(n + 1)/2) def test_S4(): n, k = symbols('n k', integer=True, positive=True) assert Product(1 + 1/k, (k, 1, n -1)).doit().simplify() == n def test_S5(): n, k = symbols('n k', integer=True, positive=True) assert (Product((2*k - 1)/(2*k), (k, 1, n)).doit().gammasimp() == gamma(n + S.Half)/(sqrt(pi)*gamma(n + 1))) @XFAIL def test_S6(): n, k = symbols('n k', integer=True, positive=True) # Product does not evaluate assert (Product(x**2 -2*x*cos(k*pi/n) + 1, (k, 1, n - 1)).doit().simplify() == (x**(2*n) - 1)/(x**2 - 1)) @XFAIL def test_S7(): k = symbols('k', integer=True, positive=True) Pr = Product((k**3 - 1)/(k**3 + 1), (k, 2, oo)) T = Pr.doit() # Product does not evaluate assert T.simplify() == R(2, 3) @XFAIL def test_S8(): k = symbols('k', integer=True, positive=True) Pr = Product(1 - 1/(2*k)**2, (k, 1, oo)) T = Pr.doit() # Product does not evaluate assert T.simplify() == 2/pi @XFAIL def test_S9(): k = symbols('k', integer=True, positive=True) Pr = Product(1 + (-1)**(k + 1)/(2*k - 1), (k, 1, oo)) T = Pr.doit() # Product produces 0 # https://github.com/sympy/sympy/issues/7133 assert T.simplify() == sqrt(2) @XFAIL def test_S10(): k = symbols('k', integer=True, positive=True) Pr = Product((k*(k + 1) + 1 + I)/(k*(k + 1) + 1 - I), (k, 0, oo)) T = Pr.doit() # Product does not evaluate assert T.simplify() == -1 def test_T1(): assert limit((1 + 1/n)**n, n, oo) == E assert limit((1 - cos(x))/x**2, x, 0) == S.Half def test_T2(): assert limit((3**x + 5**x)**(1/x), x, oo) == 5 def test_T3(): assert limit(log(x)/(log(x) + sin(x)), x, oo) == 1 def test_T4(): assert limit((exp(x*exp(-x)/(exp(-x) + exp(-2*x**2/(x + 1)))) - exp(x))/x, x, oo) == -exp(2) def test_T5(): assert limit(x*log(x)*log(x*exp(x) - x**2)**2/log(log(x**2 + 2*exp(exp(3*x**3*log(x))))), x, oo) == R(1, 3) def test_T6(): assert limit(1/n * factorial(n)**(1/n), n, oo) == exp(-1) def test_T7(): limit(1/n * gamma(n + 1)**(1/n), n, oo) def test_T8(): a, z = symbols('a z', real=True, positive=True) assert limit(gamma(z + a)/gamma(z)*exp(-a*log(z)), z, oo) == 1 @XFAIL def test_T9(): z, k = symbols('z k', real=True, positive=True) # raises NotImplementedError: # Don't know how to calculate the mrv of '(1, k)' assert limit(hyper((1, k), (1,), z/k), k, oo) == exp(z) @XFAIL def test_T10(): # No longer raises PoleError, but should return euler-mascheroni constant assert limit(zeta(x) - 1/(x - 1), x, 1) == integrate(-1/x + 1/floor(x), (x, 1, oo)) @XFAIL def test_T11(): n, k = symbols('n k', integer=True, positive=True) # evaluates to 0 assert limit(n**x/(x*product((1 + x/k), (k, 1, n))), n, oo) == gamma(x) @XFAIL def test_T12(): x, t = symbols('x t', real=True) # Does not evaluate the limit but returns an expression with erf assert limit(x * integrate(exp(-t**2), (t, 0, x))/(1 - exp(-x**2)), x, 0) == 1 def test_T13(): x = symbols('x', real=True) assert [limit(x/abs(x), x, 0, dir='-'), limit(x/abs(x), x, 0, dir='+')] == [-1, 1] def test_T14(): x = symbols('x', real=True) assert limit(atan(-log(x)), x, 0, dir='+') == pi/2 def test_U1(): x = symbols('x', real=True) assert diff(abs(x), x) == sign(x) def test_U2(): f = Lambda(x, Piecewise((-x, x < 0), (x, x >= 0))) assert diff(f(x), x) == Piecewise((-1, x < 0), (1, x >= 0)) def test_U3(): f = Lambda(x, Piecewise((x**2 - 1, x == 1), (x**3, x != 1))) f1 = Lambda(x, diff(f(x), x)) assert f1(x) == 3*x**2 assert f1(1) == 3 @XFAIL def test_U4(): n = symbols('n', integer=True, positive=True) x = symbols('x', real=True) d = diff(x**n, x, n) assert d.rewrite(factorial) == factorial(n) def test_U5(): # issue 6681 t = symbols('t') ans = ( Derivative(f(g(t)), g(t))*Derivative(g(t), (t, 2)) + Derivative(f(g(t)), (g(t), 2))*Derivative(g(t), t)**2) assert f(g(t)).diff(t, 2) == ans assert ans.doit() == ans def test_U6(): h = Function('h') T = integrate(f(y), (y, h(x), g(x))) assert T.diff(x) == ( f(g(x))*Derivative(g(x), x) - f(h(x))*Derivative(h(x), x)) @XFAIL def test_U7(): p, t = symbols('p t', real=True) # Exact differential => d(V(P, T)) => dV/dP DP + dV/dT DT # raises ValueError: Since there is more than one variable in the # expression, the variable(s) of differentiation must be supplied to # differentiate f(p,t) diff(f(p, t)) def test_U8(): x, y = symbols('x y', real=True) eq = cos(x*y) + x # If SymPy had implicit_diff() function this hack could be avoided # TODO: Replace solve with solveset, current test fails for solveset assert idiff(y - eq, y, x) == (-y*sin(x*y) + 1)/(x*sin(x*y) + 1) def test_U9(): # Wester sample case for Maple: # O29 := diff(f(x, y), x) + diff(f(x, y), y); # /d \ /d \ # |-- f(x, y)| + |-- f(x, y)| # \dx / \dy / # # O30 := factor(subs(f(x, y) = g(x^2 + y^2), %)); # 2 2 # 2 D(g)(x + y ) (x + y) x, y = symbols('x y', real=True) su = diff(f(x, y), x) + diff(f(x, y), y) s2 = su.subs(f(x, y), g(x**2 + y**2)) s3 = s2.doit().factor() # Subs not performed, s3 = 2*(x + y)*Subs(Derivative( # g(_xi_1), _xi_1), _xi_1, x**2 + y**2) # Derivative(g(x*2 + y**2), x**2 + y**2) is not valid in SymPy, # and probably will remain that way. You can take derivatives with respect # to other expressions only if they are atomic, like a symbol or a # function. # D operator should be added to SymPy # See https://github.com/sympy/sympy/issues/4719. assert s3 == (x + y)*Subs(Derivative(g(x), x), x, x**2 + y**2)*2 def test_U10(): # see issue 2519: assert residue((z**3 + 5)/((z**4 - 1)*(z + 1)), z, -1) == R(-9, 4) @XFAIL def test_U11(): # assert (2*dx + dz) ^ (3*dx + dy + dz) ^ (dx + dy + 4*dz) == 8*dx ^ dy ^dz raise NotImplementedError @XFAIL def test_U12(): # Wester sample case: # (c41) /* d(3 x^5 dy /\ dz + 5 x y^2 dz /\ dx + 8 z dx /\ dy) # => (15 x^4 + 10 x y + 8) dx /\ dy /\ dz */ # factor(ext_diff(3*x^5 * dy ~ dz + 5*x*y^2 * dz ~ dx + 8*z * dx ~ dy)); # 4 # (d41) (10 x y + 15 x + 8) dx dy dz raise NotImplementedError( "External diff of differential form not supported") def test_U13(): assert minimum(x**4 - x + 1, x) == -3*2**R(1,3)/8 + 1 @XFAIL def test_U14(): #f = 1/(x**2 + y**2 + 1) #assert [minimize(f), maximize(f)] == [0,1] raise NotImplementedError("minimize(), maximize() not supported") @XFAIL def test_U15(): raise NotImplementedError("minimize() not supported and also solve does \ not support multivariate inequalities") @XFAIL def test_U16(): raise NotImplementedError("minimize() not supported in SymPy and also \ solve does not support multivariate inequalities") @XFAIL def test_U17(): raise NotImplementedError("Linear programming, symbolic simplex not \ supported in SymPy") def test_V1(): x = symbols('x', real=True) assert integrate(abs(x), x) == Piecewise((-x**2/2, x <= 0), (x**2/2, True)) def test_V2(): assert integrate(Piecewise((-x, x < 0), (x, x >= 0)), x ) == Piecewise((-x**2/2, x < 0), (x**2/2, True)) def test_V3(): assert integrate(1/(x**3 + 2),x).diff().simplify() == 1/(x**3 + 2) def test_V4(): assert integrate(2**x/sqrt(1 + 4**x), x) == asinh(2**x)/log(2) @XFAIL def test_V5(): # Returns (-45*x**2 + 80*x - 41)/(5*sqrt(2*x - 1)*(4*x**2 - 4*x + 1)) assert (integrate((3*x - 5)**2/(2*x - 1)**R(7, 2), x).simplify() == (-41 + 80*x - 45*x**2)/(5*(2*x - 1)**R(5, 2))) @XFAIL def test_V6(): # returns RootSum(40*_z**2 - 1, Lambda(_i, _i*log(-4*_i + exp(-m*x))))/m assert (integrate(1/(2*exp(m*x) - 5*exp(-m*x)), x) == sqrt(10)*( log(2*exp(m*x) - sqrt(10)) - log(2*exp(m*x) + sqrt(10)))/(20*m)) def test_V7(): r1 = integrate(sinh(x)**4/cosh(x)**2) assert r1.simplify() == x*R(-3, 2) + sinh(x)**3/(2*cosh(x)) + 3*tanh(x)/2 @XFAIL def test_V8_V9(): #Macsyma test case: #(c27) /* This example involves several symbolic parameters # => 1/sqrt(b^2 - a^2) log([sqrt(b^2 - a^2) tan(x/2) + a + b]/ # [sqrt(b^2 - a^2) tan(x/2) - a - b]) (a^2 < b^2) # [Gradshteyn and Ryzhik 2.553(3)] */ #assume(b^2 > a^2)$ #(c28) integrate(1/(a + b*cos(x)), x); #(c29) trigsimp(ratsimp(diff(%, x))); # 1 #(d29) ------------ # b cos(x) + a raise NotImplementedError( "Integrate with assumption not supported") def test_V10(): assert integrate(1/(3 + 3*cos(x) + 4*sin(x)), x) == log(tan(x/2) + R(3, 4))/4 def test_V11(): r1 = integrate(1/(4 + 3*cos(x) + 4*sin(x)), x) r2 = factor(r1) assert (logcombine(r2, force=True) == log(((tan(x/2) + 1)/(tan(x/2) + 7))**R(1, 3))) @XFAIL def test_V12(): r1 = integrate(1/(5 + 3*cos(x) + 4*sin(x)), x) # Correct result in python2.7.4, wrong result in python3.5 # https://github.com/sympy/sympy/issues/7157 assert r1 == -1/(tan(x/2) + 2) @XFAIL def test_V13(): r1 = integrate(1/(6 + 3*cos(x) + 4*sin(x)), x) # expression not simplified, returns: -sqrt(11)*I*log(tan(x/2) + 4/3 # - sqrt(11)*I/3)/11 + sqrt(11)*I*log(tan(x/2) + 4/3 + sqrt(11)*I/3)/11 assert r1.simplify() == 2*sqrt(11)*atan(sqrt(11)*(3*tan(x/2) + 4)/11)/11 @slow @XFAIL def test_V14(): r1 = integrate(log(abs(x**2 - y**2)), x) # Piecewise result does not simplify to the desired result. assert (r1.simplify() == x*log(abs(x**2 - y**2)) + y*log(x + y) - y*log(x - y) - 2*x) def test_V15(): r1 = integrate(x*acot(x/y), x) assert simplify(r1 - (x*y + (x**2 + y**2)*acot(x/y))/2) == 0 @XFAIL def test_V16(): # Integral not calculated assert integrate(cos(5*x)*Ci(2*x), x) == Ci(2*x)*sin(5*x)/5 - (Si(3*x) + Si(7*x))/10 @XFAIL def test_V17(): r1 = integrate((diff(f(x), x)*g(x) - f(x)*diff(g(x), x))/(f(x)**2 - g(x)**2), x) # integral not calculated assert simplify(r1 - (f(x) - g(x))/(f(x) + g(x))/2) == 0 @XFAIL def test_W1(): # The function has a pole at y. # The integral has a Cauchy principal value of zero but SymPy returns -I*pi # https://github.com/sympy/sympy/issues/7159 assert integrate(1/(x - y), (x, y - 1, y + 1)) == 0 @XFAIL def test_W2(): # The function has a pole at y. # The integral is divergent but SymPy returns -2 # https://github.com/sympy/sympy/issues/7160 # Test case in Macsyma: # (c6) errcatch(integrate(1/(x - a)^2, x, a - 1, a + 1)); # Integral is divergent assert integrate(1/(x - y)**2, (x, y - 1, y + 1)) is zoo @XFAIL @slow def test_W3(): # integral is not calculated # https://github.com/sympy/sympy/issues/7161 assert integrate(sqrt(x + 1/x - 2), (x, 0, 1)) == R(4, 3) @XFAIL @slow def test_W4(): # integral is not calculated assert integrate(sqrt(x + 1/x - 2), (x, 1, 2)) == -2*sqrt(2)/3 + R(4, 3) @XFAIL @slow def test_W5(): # integral is not calculated assert integrate(sqrt(x + 1/x - 2), (x, 0, 2)) == -2*sqrt(2)/3 + R(8, 3) @XFAIL @slow def test_W6(): # integral is not calculated assert integrate(sqrt(2 - 2*cos(2*x))/2, (x, pi*R(-3, 4), -pi/4)) == sqrt(2) def test_W7(): a = symbols('a', real=True, positive=True) r1 = integrate(cos(x)/(x**2 + a**2), (x, -oo, oo)) assert r1.simplify() == pi*exp(-a)/a @XFAIL def test_W8(): # Test case in Mathematica: # In[19]:= Integrate[t^(a - 1)/(1 + t), {t, 0, Infinity}, # Assumptions -> 0 < a < 1] # Out[19]= Pi Csc[a Pi] raise NotImplementedError( "Integrate with assumption 0 < a < 1 not supported") @XFAIL def test_W9(): # Integrand with a residue at infinity => -2 pi [sin(pi/5) + sin(2pi/5)] # (principal value) [Levinson and Redheffer, p. 234] *) r1 = integrate(5*x**3/(1 + x + x**2 + x**3 + x**4), (x, -oo, oo)) r2 = r1.doit() assert r2 == -2*pi*(sqrt(-sqrt(5)/8 + 5/8) + sqrt(sqrt(5)/8 + 5/8)) @XFAIL def test_W10(): # integrate(1/[1 + x + x^2 + ... + x^(2 n)], x = -infinity..infinity) = # 2 pi/(2 n + 1) [1 + cos(pi/[2 n + 1])] csc(2 pi/[2 n + 1]) # [Levinson and Redheffer, p. 255] => 2 pi/5 [1 + cos(pi/5)] csc(2 pi/5) */ r1 = integrate(x/(1 + x + x**2 + x**4), (x, -oo, oo)) r2 = r1.doit() assert r2 == 2*pi*(sqrt(5)/4 + 5/4)*csc(pi*R(2, 5))/5 @XFAIL def test_W11(): # integral not calculated assert (integrate(sqrt(1 - x**2)/(1 + x**2), (x, -1, 1)) == pi*(-1 + sqrt(2))) def test_W12(): p = symbols('p', real=True, positive=True) q = symbols('q', real=True) r1 = integrate(x*exp(-p*x**2 + 2*q*x), (x, -oo, oo)) assert r1.simplify() == sqrt(pi)*q*exp(q**2/p)/p**R(3, 2) @XFAIL def test_W13(): # Integral not calculated. Expected result is 2*(Euler_mascheroni_constant) r1 = integrate(1/log(x) + 1/(1 - x) - log(log(1/x)), (x, 0, 1)) assert r1 == 2*EulerGamma def test_W14(): assert integrate(sin(x)/x*exp(2*I*x), (x, -oo, oo)) == 0 @XFAIL def test_W15(): # integral not calculated assert integrate(log(gamma(x))*cos(6*pi*x), (x, 0, 1)) == R(1, 12) def test_W16(): assert integrate((1 + x)**3*legendre_poly(1, x)*legendre_poly(2, x), (x, -1, 1)) == R(36, 35) def test_W17(): a, b = symbols('a b', real=True, positive=True) assert integrate(exp(-a*x)*besselj(0, b*x), (x, 0, oo)) == 1/(b*sqrt(a**2/b**2 + 1)) def test_W18(): assert integrate((besselj(1, x)/x)**2, (x, 0, oo)) == 4/(3*pi) @XFAIL def test_W19(): # Integral not calculated # Expected result is (cos 7 - 1)/7 [Gradshteyn and Ryzhik 6.782(3)] assert integrate(Ci(x)*besselj(0, 2*sqrt(7*x)), (x, 0, oo)) == (cos(7) - 1)/7 @XFAIL def test_W20(): # integral not calculated assert (integrate(x**2*polylog(3, 1/(x + 1)), (x, 0, 1)) == -pi**2/36 - R(17, 108) + zeta(3)/4 + (-pi**2/2 - 4*log(2) + log(2)**2 + 35/3)*log(2)/9) def test_W21(): assert abs(N(integrate(x**2*polylog(3, 1/(x + 1)), (x, 0, 1))) - 0.210882859565594) < 1e-15 def test_W22(): t, u = symbols('t u', real=True) s = Lambda(x, Piecewise((1, And(x >= 1, x <= 2)), (0, True))) assert integrate(s(t)*cos(t), (t, 0, u)) == Piecewise( (0, u < 0), (-sin(Min(1, u)) + sin(Min(2, u)), True)) @slow def test_W23(): a, b = symbols('a b', real=True, positive=True) r1 = integrate(integrate(x/(x**2 + y**2), (x, a, b)), (y, -oo, oo)) assert r1.collect(pi) == pi*(-a + b) def test_W23b(): # like W23 but limits are reversed a, b = symbols('a b', real=True, positive=True) r2 = integrate(integrate(x/(x**2 + y**2), (y, -oo, oo)), (x, a, b)) assert r2.collect(pi) == pi*(-a + b) @XFAIL @slow def test_W24(): if ON_TRAVIS: skip("Too slow for travis.") # Not that slow, but does not fully evaluate so simplify is slow. # Maybe also require doit() x, y = symbols('x y', real=True) r1 = integrate(integrate(sqrt(x**2 + y**2), (x, 0, 1)), (y, 0, 1)) assert (r1 - (sqrt(2) + asinh(1))/3).simplify() == 0 @XFAIL @slow def test_W25(): if ON_TRAVIS: skip("Too slow for travis.") a, x, y = symbols('a x y', real=True) i1 = integrate( sin(a)*sin(y)/sqrt(1 - sin(a)**2*sin(x)**2*sin(y)**2), (x, 0, pi/2)) i2 = integrate(i1, (y, 0, pi/2)) assert (i2 - pi*a/2).simplify() == 0 def test_W26(): x, y = symbols('x y', real=True) assert integrate(integrate(abs(y - x**2), (y, 0, 2)), (x, -1, 1)) == R(46, 15) def test_W27(): a, b, c = symbols('a b c') assert integrate(integrate(integrate(1, (z, 0, c*(1 - x/a - y/b))), (y, 0, b*(1 - x/a))), (x, 0, a)) == a*b*c/6 def test_X1(): v, c = symbols('v c', real=True) assert (series(1/sqrt(1 - (v/c)**2), v, x0=0, n=8) == 5*v**6/(16*c**6) + 3*v**4/(8*c**4) + v**2/(2*c**2) + 1 + O(v**8)) def test_X2(): v, c = symbols('v c', real=True) s1 = series(1/sqrt(1 - (v/c)**2), v, x0=0, n=8) assert (1/s1**2).series(v, x0=0, n=8) == -v**2/c**2 + 1 + O(v**8) def test_X3(): s1 = (sin(x).series()/cos(x).series()).series() s2 = tan(x).series() assert s2 == x + x**3/3 + 2*x**5/15 + O(x**6) assert s1 == s2 def test_X4(): s1 = log(sin(x)/x).series() assert s1 == -x**2/6 - x**4/180 + O(x**6) assert log(series(sin(x)/x)).series() == s1 @XFAIL def test_X5(): # test case in Mathematica syntax: # In[21]:= (* => [a f'(a d) + g(b d) + integrate(h(c y), y = 0..d)] # + [a^2 f''(a d) + b g'(b d) + h(c d)] (x - d) *) # In[22]:= D[f[a*x], x] + g[b*x] + Integrate[h[c*y], {y, 0, x}] # Out[22]= g[b x] + Integrate[h[c y], {y, 0, x}] + a f'[a x] # In[23]:= Series[%, {x, d, 1}] # Out[23]= (g[b d] + Integrate[h[c y], {y, 0, d}] + a f'[a d]) + # 2 2 # (h[c d] + b g'[b d] + a f''[a d]) (-d + x) + O[-d + x] h = Function('h') a, b, c, d = symbols('a b c d', real=True) # series() raises NotImplementedError: # The _eval_nseries method should be added to <class # 'sympy.core.function.Subs'> to give terms up to O(x**n) at x=0 series(diff(f(a*x), x) + g(b*x) + integrate(h(c*y), (y, 0, x)), x, x0=d, n=2) # assert missing, until exception is removed def test_X6(): # Taylor series of nonscalar objects (noncommutative multiplication) # expected result => (B A - A B) t^2/2 + O(t^3) [Stanly Steinberg] a, b = symbols('a b', commutative=False, scalar=False) assert (series(exp((a + b)*x) - exp(a*x) * exp(b*x), x, x0=0, n=3) == x**2*(-a*b/2 + b*a/2) + O(x**3)) def test_X7(): # => sum( Bernoulli[k]/k! x^(k - 2), k = 1..infinity ) # = 1/x^2 - 1/(2 x) + 1/12 - x^2/720 + x^4/30240 + O(x^6) # [Levinson and Redheffer, p. 173] assert (series(1/(x*(exp(x) - 1)), x, 0, 7) == x**(-2) - 1/(2*x) + R(1, 12) - x**2/720 + x**4/30240 - x**6/1209600 + O(x**7)) def test_X8(): # Puiseux series (terms with fractional degree): # => 1/sqrt(x - 3/2 pi) + (x - 3/2 pi)^(3/2) / 12 + O([x - 3/2 pi]^(7/2)) # see issue 7167: x = symbols('x', real=True) assert (series(sqrt(sec(x)), x, x0=pi*3/2, n=4) == 1/sqrt(x - pi*R(3, 2)) + (x - pi*R(3, 2))**R(3, 2)/12 + (x - pi*R(3, 2))**R(7, 2)/160 + O((x - pi*R(3, 2))**4, (x, pi*R(3, 2)))) def test_X9(): assert (series(x**x, x, x0=0, n=4) == 1 + x*log(x) + x**2*log(x)**2/2 + x**3*log(x)**3/6 + O(x**4*log(x)**4)) def test_X10(): z, w = symbols('z w') assert (series(log(sinh(z)) + log(cosh(z + w)), z, x0=0, n=2) == log(cosh(w)) + log(z) + z*sinh(w)/cosh(w) + O(z**2)) def test_X11(): z, w = symbols('z w') assert (series(log(sinh(z) * cosh(z + w)), z, x0=0, n=2) == log(cosh(w)) + log(z) + z*sinh(w)/cosh(w) + O(z**2)) @XFAIL def test_X12(): # Look at the generalized Taylor series around x = 1 # Result => (x - 1)^a/e^b [1 - (a + 2 b) (x - 1) / 2 + O((x - 1)^2)] a, b, x = symbols('a b x', real=True) # series returns O(log(x-1)**2) # https://github.com/sympy/sympy/issues/7168 assert (series(log(x)**a*exp(-b*x), x, x0=1, n=2) == (x - 1)**a/exp(b)*(1 - (a + 2*b)*(x - 1)/2 + O((x - 1)**2))) def test_X13(): assert series(sqrt(2*x**2 + 1), x, x0=oo, n=1) == sqrt(2)*x + O(1/x, (x, oo)) @XFAIL def test_X14(): # Wallis' product => 1/sqrt(pi n) + ... [Knopp, p. 385] assert series(1/2**(2*n)*binomial(2*n, n), n, x==oo, n=1) == 1/(sqrt(pi)*sqrt(n)) + O(1/x, (x, oo)) @SKIP("https://github.com/sympy/sympy/issues/7164") def test_X15(): # => 0!/x - 1!/x^2 + 2!/x^3 - 3!/x^4 + O(1/x^5) [Knopp, p. 544] x, t = symbols('x t', real=True) # raises RuntimeError: maximum recursion depth exceeded # https://github.com/sympy/sympy/issues/7164 # 2019-02-17: Raises # PoleError: # Asymptotic expansion of Ei around [-oo] is not implemented. e1 = integrate(exp(-t)/t, (t, x, oo)) assert (series(e1, x, x0=oo, n=5) == 6/x**4 + 2/x**3 - 1/x**2 + 1/x + O(x**(-5), (x, oo))) def test_X16(): # Multivariate Taylor series expansion => 1 - (x^2 + 2 x y + y^2)/2 + O(x^4) assert (series(cos(x + y), x + y, x0=0, n=4) == 1 - (x + y)**2/2 + O(x**4 + x**3*y + x**2*y**2 + x*y**3 + y**4, x, y)) @XFAIL def test_X17(): # Power series (compute the general formula) # (c41) powerseries(log(sin(x)/x), x, 0); # /aquarius/data2/opt/local/macsyma_422/library1/trgred.so being loaded. # inf # ==== i1 2 i1 2 i1 # \ (- 1) 2 bern(2 i1) x # (d41) > ------------------------------ # / 2 i1 (2 i1)! # ==== # i1 = 1 # fps does not calculate assert fps(log(sin(x)/x)) == \ Sum((-1)**k*2**(2*k - 1)*bernoulli(2*k)*x**(2*k)/(k*factorial(2*k)), (k, 1, oo)) @XFAIL def test_X18(): # Power series (compute the general formula). Maple FPS: # > FormalPowerSeries(exp(-x)*sin(x), x = 0); # infinity # ----- (1/2 k) k # \ 2 sin(3/4 k Pi) x # ) ------------------------- # / k! # ----- # # Now, sympy returns # oo # _____ # \ ` # \ / k k\ # \ k |I*(-1 - I) I*(-1 + I) | # \ x *|----------- - -----------| # / \ 2 2 / # / ------------------------------ # / k! # /____, # k = 0 k = Dummy('k') assert fps(exp(-x)*sin(x)) == \ Sum(2**(S.Half*k)*sin(R(3, 4)*k*pi)*x**k/factorial(k), (k, 0, oo)) @XFAIL def test_X19(): # (c45) /* Derive an explicit Taylor series solution of y as a function of # x from the following implicit relation: # y = x - 1 + (x - 1)^2/2 + 2/3 (x - 1)^3 + (x - 1)^4 + # 17/10 (x - 1)^5 + ... # */ # x = sin(y) + cos(y); # Time= 0 msecs # (d45) x = sin(y) + cos(y) # # (c46) taylor_revert(%, y, 7); raise NotImplementedError("Solve using series not supported. \ Inverse Taylor series expansion also not supported") @XFAIL def test_X20(): # Pade (rational function) approximation => (2 - x)/(2 + x) # > numapprox[pade](exp(-x), x = 0, [1, 1]); # bytes used=9019816, alloc=3669344, time=13.12 # 1 - 1/2 x # --------- # 1 + 1/2 x # mpmath support numeric Pade approximant but there is # no symbolic implementation in SymPy # https://en.wikipedia.org/wiki/Pad%C3%A9_approximant raise NotImplementedError("Symbolic Pade approximant not supported") def test_X21(): """ Test whether `fourier_series` of x periodical on the [-p, p] interval equals `- (2 p / pi) sum( (-1)^n / n sin(n pi x / p), n = 1..infinity )`. """ p = symbols('p', positive=True) n = symbols('n', positive=True, integer=True) s = fourier_series(x, (x, -p, p)) # All cosine coefficients are equal to 0 assert s.an.formula == 0 # Check for sine coefficients assert s.bn.formula.subs(s.bn.variables[0], 0) == 0 assert s.bn.formula.subs(s.bn.variables[0], n) == \ -2*p/pi * (-1)**n / n * sin(n*pi*x/p) @XFAIL def test_X22(): # (c52) /* => p / 2 # - (2 p / pi^2) sum( [1 - (-1)^n] cos(n pi x / p) / n^2, # n = 1..infinity ) */ # fourier_series(abs(x), x, p); # p # (e52) a = - # 0 2 # # %nn # (2 (- 1) - 2) p # (e53) a = ------------------ # %nn 2 2 # %pi %nn # # (e54) b = 0 # %nn # # Time= 5290 msecs # inf %nn %pi %nn x # ==== (2 (- 1) - 2) cos(---------) # \ p # p > ------------------------------- # / 2 # ==== %nn # %nn = 1 p # (d54) ----------------------------------------- + - # 2 2 # %pi raise NotImplementedError("Fourier series not supported") def test_Y1(): t = symbols('t', real=True, positive=True) w = symbols('w', real=True) s = symbols('s') F, _, _ = laplace_transform(cos((w - 1)*t), t, s) assert F == s/(s**2 + (w - 1)**2) def test_Y2(): t = symbols('t', real=True, positive=True) w = symbols('w', real=True) s = symbols('s') f = inverse_laplace_transform(s/(s**2 + (w - 1)**2), s, t) assert f == cos(t*w - t) def test_Y3(): t = symbols('t', real=True, positive=True) w = symbols('w', real=True) s = symbols('s') F, _, _ = laplace_transform(sinh(w*t)*cosh(w*t), t, s) assert F == w/(s**2 - 4*w**2) def test_Y4(): t = symbols('t', real=True, positive=True) s = symbols('s') F, _, _ = laplace_transform(erf(3/sqrt(t)), t, s) assert F == (1 - exp(-6*sqrt(s)))/s @XFAIL def test_Y5_Y6(): # Solve y'' + y = 4 [H(t - 1) - H(t - 2)], y(0) = 1, y'(0) = 0 where H is the # Heaviside (unit step) function (the RHS describes a pulse of magnitude 4 and # duration 1). See David A. Sanchez, Richard C. Allen, Jr. and Walter T. # Kyner, _Differential Equations: An Introduction_, Addison-Wesley Publishing # Company, 1983, p. 211. First, take the Laplace transform of the ODE # => s^2 Y(s) - s + Y(s) = 4/s [e^(-s) - e^(-2 s)] # where Y(s) is the Laplace transform of y(t) t = symbols('t', real=True, positive=True) s = symbols('s') y = Function('y') F, _, _ = laplace_transform(diff(y(t), t, 2) + y(t) - 4*(Heaviside(t - 1) - Heaviside(t - 2)), t, s) # Laplace transform for diff() not calculated # https://github.com/sympy/sympy/issues/7176 assert (F == s**2*LaplaceTransform(y(t), t, s) - s + LaplaceTransform(y(t), t, s) - 4*exp(-s)/s + 4*exp(-2*s)/s) # TODO implement second part of test case # Now, solve for Y(s) and then take the inverse Laplace transform # => Y(s) = s/(s^2 + 1) + 4 [1/s - s/(s^2 + 1)] [e^(-s) - e^(-2 s)] # => y(t) = cos t + 4 {[1 - cos(t - 1)] H(t - 1) - [1 - cos(t - 2)] H(t - 2)} @XFAIL def test_Y7(): # What is the Laplace transform of an infinite square wave? # => 1/s + 2 sum( (-1)^n e^(- s n a)/s, n = 1..infinity ) # [Sanchez, Allen and Kyner, p. 213] t = symbols('t', real=True, positive=True) a = symbols('a', real=True) s = symbols('s') F, _, _ = laplace_transform(1 + 2*Sum((-1)**n*Heaviside(t - n*a), (n, 1, oo)), t, s) # returns 2*LaplaceTransform(Sum((-1)**n*Heaviside(-a*n + t), # (n, 1, oo)), t, s) + 1/s # https://github.com/sympy/sympy/issues/7177 assert F == 2*Sum((-1)**n*exp(-a*n*s)/s, (n, 1, oo)) + 1/s @XFAIL def test_Y8(): assert fourier_transform(1, x, z) == DiracDelta(z) def test_Y9(): assert (fourier_transform(exp(-9*x**2), x, z) == sqrt(pi)*exp(-pi**2*z**2/9)/3) def test_Y10(): assert (fourier_transform(abs(x)*exp(-3*abs(x)), x, z) == (-8*pi**2*z**2 + 18)/(16*pi**4*z**4 + 72*pi**2*z**2 + 81)) @SKIP("https://github.com/sympy/sympy/issues/7181") @slow def test_Y11(): # => pi cot(pi s) (0 < Re s < 1) [Gradshteyn and Ryzhik 17.43(5)] x, s = symbols('x s') # raises RuntimeError: maximum recursion depth exceeded # https://github.com/sympy/sympy/issues/7181 # Update 2019-02-17 raises: # TypeError: cannot unpack non-iterable MellinTransform object F, _, _ = mellin_transform(1/(1 - x), x, s) assert F == pi*cot(pi*s) @XFAIL def test_Y12(): # => 2^(s - 4) gamma(s/2)/gamma(4 - s/2) (0 < Re s < 1) # [Gradshteyn and Ryzhik 17.43(16)] x, s = symbols('x s') # returns Wrong value -2**(s - 4)*gamma(s/2 - 3)/gamma(-s/2 + 1) # https://github.com/sympy/sympy/issues/7182 F, _, _ = mellin_transform(besselj(3, x)/x**3, x, s) assert F == -2**(s - 4)*gamma(s/2)/gamma(-s/2 + 4) @XFAIL def test_Y13(): # Z[H(t - m T)] => z/[z^m (z - 1)] (H is the Heaviside (unit step) function) z raise NotImplementedError("z-transform not supported") @XFAIL def test_Y14(): # Z[H(t - m T)] => z/[z^m (z - 1)] (H is the Heaviside (unit step) function) raise NotImplementedError("z-transform not supported") def test_Z1(): r = Function('r') assert (rsolve(r(n + 2) - 2*r(n + 1) + r(n) - 2, r(n), {r(0): 1, r(1): m}).simplify() == n**2 + n*(m - 2) + 1) def test_Z2(): r = Function('r') assert (rsolve(r(n) - (5*r(n - 1) - 6*r(n - 2)), r(n), {r(0): 0, r(1): 1}) == -2**n + 3**n) def test_Z3(): # => r(n) = Fibonacci[n + 1] [Cohen, p. 83] r = Function('r') # recurrence solution is correct, Wester expects it to be simplified to # fibonacci(n+1), but that is quite hard assert (rsolve(r(n) - (r(n - 1) + r(n - 2)), r(n), {r(1): 1, r(2): 2}).simplify() == 2**(-n)*((1 + sqrt(5))**n*(sqrt(5) + 5) + (-sqrt(5) + 1)**n*(-sqrt(5) + 5))/10) @XFAIL def test_Z4(): # => [c^(n+1) [c^(n+1) - 2 c - 2] + (n+1) c^2 + 2 c - n] / [(c-1)^3 (c+1)] # [Joan Z. Yu and Robert Israel in sci.math.symbolic] r = Function('r') c = symbols('c') # raises ValueError: Polynomial or rational function expected, # got '(c**2 - c**n)/(c - c**n) s = rsolve(r(n) - ((1 + c - c**(n-1) - c**(n+1))/(1 - c**n)*r(n - 1) - c*(1 - c**(n-2))/(1 - c**(n-1))*r(n - 2) + 1), r(n), {r(1): 1, r(2): (2 + 2*c + c**2)/(1 + c)}) assert (s - (c*(n + 1)*(c*(n + 1) - 2*c - 2) + (n + 1)*c**2 + 2*c - n)/((c-1)**3*(c+1)) == 0) @XFAIL def test_Z5(): # Second order ODE with initial conditions---solve directly # transform: f(t) = sin(2 t)/8 - t cos(2 t)/4 C1, C2 = symbols('C1 C2') # initial conditions not supported, this is a manual workaround # https://github.com/sympy/sympy/issues/4720 eq = Derivative(f(x), x, 2) + 4*f(x) - sin(2*x) sol = dsolve(eq, f(x)) f0 = Lambda(x, sol.rhs) assert f0(x) == C2*sin(2*x) + (C1 - x/4)*cos(2*x) f1 = Lambda(x, diff(f0(x), x)) # TODO: Replace solve with solveset, when it works for solveset const_dict = solve((f0(0), f1(0))) result = f0(x).subs(C1, const_dict[C1]).subs(C2, const_dict[C2]) assert result == -x*cos(2*x)/4 + sin(2*x)/8 # Result is OK, but ODE solving with initial conditions should be # supported without all this manual work raise NotImplementedError('ODE solving with initial conditions \ not supported') @XFAIL def test_Z6(): # Second order ODE with initial conditions---solve using Laplace # transform: f(t) = sin(2 t)/8 - t cos(2 t)/4 t = symbols('t', real=True, positive=True) s = symbols('s') eq = Derivative(f(t), t, 2) + 4*f(t) - sin(2*t) F, _, _ = laplace_transform(eq, t, s) # Laplace transform for diff() not calculated # https://github.com/sympy/sympy/issues/7176 assert (F == s**2*LaplaceTransform(f(t), t, s) + 4*LaplaceTransform(f(t), t, s) - 2/(s**2 + 4)) # rest of test case not implemented
8d277264359d74873f334bed2e042e7678a812b848eac6fc2537ef4fc24e5f9f
from __future__ import print_function from textwrap import dedent from itertools import islice, product from sympy import ( symbols, Integer, Integral, Tuple, Dummy, Basic, default_sort_key, Matrix, factorial, true) from sympy.combinatorics import RGS_enum, RGS_unrank, Permutation from sympy.core.compatibility import iterable from sympy.utilities.iterables import ( _partition, _set_partitions, binary_partitions, bracelets, capture, cartes, common_prefix, common_suffix, connected_components, dict_merge, filter_symbols, flatten, generate_bell, generate_derangements, generate_involutions, generate_oriented_forest, group, has_dups, ibin, iproduct, kbins, minlex, multiset, multiset_combinations, multiset_partitions, multiset_permutations, necklaces, numbered_symbols, ordered, partitions, permutations, postfixes, postorder_traversal, prefixes, reshape, rotate_left, rotate_right, runs, sift, strongly_connected_components, subsets, take, topological_sort, unflatten, uniq, variations, ordered_partitions, rotations) from sympy.utilities.enumerative import ( factoring_visitor, multiset_partitions_taocp ) from sympy.core.singleton import S from sympy.functions.elementary.piecewise import Piecewise, ExprCondPair from sympy.testing.pytest import raises w, x, y, z = symbols('w,x,y,z') def test_postorder_traversal(): expr = z + w*(x + y) expected = [z, w, x, y, x + y, w*(x + y), w*(x + y) + z] assert list(postorder_traversal(expr, keys=default_sort_key)) == expected assert list(postorder_traversal(expr, keys=True)) == expected expr = Piecewise((x, x < 1), (x**2, True)) expected = [ x, 1, x, x < 1, ExprCondPair(x, x < 1), 2, x, x**2, true, ExprCondPair(x**2, True), Piecewise((x, x < 1), (x**2, True)) ] assert list(postorder_traversal(expr, keys=default_sort_key)) == expected assert list(postorder_traversal( [expr], keys=default_sort_key)) == expected + [[expr]] assert list(postorder_traversal(Integral(x**2, (x, 0, 1)), keys=default_sort_key)) == [ 2, x, x**2, 0, 1, x, Tuple(x, 0, 1), Integral(x**2, Tuple(x, 0, 1)) ] assert list(postorder_traversal(('abc', ('d', 'ef')))) == [ 'abc', 'd', 'ef', ('d', 'ef'), ('abc', ('d', 'ef'))] def test_flatten(): assert flatten((1, (1,))) == [1, 1] assert flatten((x, (x,))) == [x, x] ls = [[(-2, -1), (1, 2)], [(0, 0)]] assert flatten(ls, levels=0) == ls assert flatten(ls, levels=1) == [(-2, -1), (1, 2), (0, 0)] assert flatten(ls, levels=2) == [-2, -1, 1, 2, 0, 0] assert flatten(ls, levels=3) == [-2, -1, 1, 2, 0, 0] raises(ValueError, lambda: flatten(ls, levels=-1)) class MyOp(Basic): pass assert flatten([MyOp(x, y), z]) == [MyOp(x, y), z] assert flatten([MyOp(x, y), z], cls=MyOp) == [x, y, z] assert flatten({1, 11, 2}) == list({1, 11, 2}) def test_iproduct(): assert list(iproduct()) == [()] assert list(iproduct([])) == [] assert list(iproduct([1,2,3])) == [(1,),(2,),(3,)] assert sorted(iproduct([1, 2], [3, 4, 5])) == [ (1,3),(1,4),(1,5),(2,3),(2,4),(2,5)] assert sorted(iproduct([0,1],[0,1],[0,1])) == [ (0,0,0),(0,0,1),(0,1,0),(0,1,1),(1,0,0),(1,0,1),(1,1,0),(1,1,1)] assert iterable(iproduct(S.Integers)) is True assert iterable(iproduct(S.Integers, S.Integers)) is True assert (3,) in iproduct(S.Integers) assert (4, 5) in iproduct(S.Integers, S.Integers) assert (1, 2, 3) in iproduct(S.Integers, S.Integers, S.Integers) triples = set(islice(iproduct(S.Integers, S.Integers, S.Integers), 1000)) for n1, n2, n3 in triples: assert isinstance(n1, Integer) assert isinstance(n2, Integer) assert isinstance(n3, Integer) for t in set(product(*([range(-2, 3)]*3))): assert t in iproduct(S.Integers, S.Integers, S.Integers) def test_group(): assert group([]) == [] assert group([], multiple=False) == [] assert group([1]) == [[1]] assert group([1], multiple=False) == [(1, 1)] assert group([1, 1]) == [[1, 1]] assert group([1, 1], multiple=False) == [(1, 2)] assert group([1, 1, 1]) == [[1, 1, 1]] assert group([1, 1, 1], multiple=False) == [(1, 3)] assert group([1, 2, 1]) == [[1], [2], [1]] assert group([1, 2, 1], multiple=False) == [(1, 1), (2, 1), (1, 1)] assert group([1, 1, 2, 2, 2, 1, 3, 3]) == [[1, 1], [2, 2, 2], [1], [3, 3]] assert group([1, 1, 2, 2, 2, 1, 3, 3], multiple=False) == [(1, 2), (2, 3), (1, 1), (3, 2)] def test_subsets(): # combinations assert list(subsets([1, 2, 3], 0)) == [()] assert list(subsets([1, 2, 3], 1)) == [(1,), (2,), (3,)] assert list(subsets([1, 2, 3], 2)) == [(1, 2), (1, 3), (2, 3)] assert list(subsets([1, 2, 3], 3)) == [(1, 2, 3)] l = list(range(4)) assert list(subsets(l, 0, repetition=True)) == [()] assert list(subsets(l, 1, repetition=True)) == [(0,), (1,), (2,), (3,)] assert list(subsets(l, 2, repetition=True)) == [(0, 0), (0, 1), (0, 2), (0, 3), (1, 1), (1, 2), (1, 3), (2, 2), (2, 3), (3, 3)] assert list(subsets(l, 3, repetition=True)) == [(0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 0, 3), (0, 1, 1), (0, 1, 2), (0, 1, 3), (0, 2, 2), (0, 2, 3), (0, 3, 3), (1, 1, 1), (1, 1, 2), (1, 1, 3), (1, 2, 2), (1, 2, 3), (1, 3, 3), (2, 2, 2), (2, 2, 3), (2, 3, 3), (3, 3, 3)] assert len(list(subsets(l, 4, repetition=True))) == 35 assert list(subsets(l[:2], 3, repetition=False)) == [] assert list(subsets(l[:2], 3, repetition=True)) == [(0, 0, 0), (0, 0, 1), (0, 1, 1), (1, 1, 1)] assert list(subsets([1, 2], repetition=True)) == \ [(), (1,), (2,), (1, 1), (1, 2), (2, 2)] assert list(subsets([1, 2], repetition=False)) == \ [(), (1,), (2,), (1, 2)] assert list(subsets([1, 2, 3], 2)) == \ [(1, 2), (1, 3), (2, 3)] assert list(subsets([1, 2, 3], 2, repetition=True)) == \ [(1, 1), (1, 2), (1, 3), (2, 2), (2, 3), (3, 3)] def test_variations(): # permutations l = list(range(4)) assert list(variations(l, 0, repetition=False)) == [()] assert list(variations(l, 1, repetition=False)) == [(0,), (1,), (2,), (3,)] assert list(variations(l, 2, repetition=False)) == [(0, 1), (0, 2), (0, 3), (1, 0), (1, 2), (1, 3), (2, 0), (2, 1), (2, 3), (3, 0), (3, 1), (3, 2)] assert list(variations(l, 3, repetition=False)) == [(0, 1, 2), (0, 1, 3), (0, 2, 1), (0, 2, 3), (0, 3, 1), (0, 3, 2), (1, 0, 2), (1, 0, 3), (1, 2, 0), (1, 2, 3), (1, 3, 0), (1, 3, 2), (2, 0, 1), (2, 0, 3), (2, 1, 0), (2, 1, 3), (2, 3, 0), (2, 3, 1), (3, 0, 1), (3, 0, 2), (3, 1, 0), (3, 1, 2), (3, 2, 0), (3, 2, 1)] assert list(variations(l, 0, repetition=True)) == [()] assert list(variations(l, 1, repetition=True)) == [(0,), (1,), (2,), (3,)] assert list(variations(l, 2, repetition=True)) == [(0, 0), (0, 1), (0, 2), (0, 3), (1, 0), (1, 1), (1, 2), (1, 3), (2, 0), (2, 1), (2, 2), (2, 3), (3, 0), (3, 1), (3, 2), (3, 3)] assert len(list(variations(l, 3, repetition=True))) == 64 assert len(list(variations(l, 4, repetition=True))) == 256 assert list(variations(l[:2], 3, repetition=False)) == [] assert list(variations(l[:2], 3, repetition=True)) == [ (0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1) ] def test_cartes(): assert list(cartes([1, 2], [3, 4, 5])) == \ [(1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5)] assert list(cartes()) == [()] assert list(cartes('a')) == [('a',)] assert list(cartes('a', repeat=2)) == [('a', 'a')] assert list(cartes(list(range(2)))) == [(0,), (1,)] def test_filter_symbols(): s = numbered_symbols() filtered = filter_symbols(s, symbols("x0 x2 x3")) assert take(filtered, 3) == list(symbols("x1 x4 x5")) def test_numbered_symbols(): s = numbered_symbols(cls=Dummy) assert isinstance(next(s), Dummy) assert next(numbered_symbols('C', start=1, exclude=[symbols('C1')])) == \ symbols('C2') def test_sift(): assert sift(list(range(5)), lambda _: _ % 2) == {1: [1, 3], 0: [0, 2, 4]} assert sift([x, y], lambda _: _.has(x)) == {False: [y], True: [x]} assert sift([S.One], lambda _: _.has(x)) == {False: [1]} assert sift([0, 1, 2, 3], lambda x: x % 2, binary=True) == ( [1, 3], [0, 2]) assert sift([0, 1, 2, 3], lambda x: x % 3 == 1, binary=True) == ( [1], [0, 2, 3]) raises(ValueError, lambda: sift([0, 1, 2, 3], lambda x: x % 3, binary=True)) def test_take(): X = numbered_symbols() assert take(X, 5) == list(symbols('x0:5')) assert take(X, 5) == list(symbols('x5:10')) assert take([1, 2, 3, 4, 5], 5) == [1, 2, 3, 4, 5] def test_dict_merge(): assert dict_merge({}, {1: x, y: z}) == {1: x, y: z} assert dict_merge({1: x, y: z}, {}) == {1: x, y: z} assert dict_merge({2: z}, {1: x, y: z}) == {1: x, 2: z, y: z} assert dict_merge({1: x, y: z}, {2: z}) == {1: x, 2: z, y: z} assert dict_merge({1: y, 2: z}, {1: x, y: z}) == {1: x, 2: z, y: z} assert dict_merge({1: x, y: z}, {1: y, 2: z}) == {1: y, 2: z, y: z} def test_prefixes(): assert list(prefixes([])) == [] assert list(prefixes([1])) == [[1]] assert list(prefixes([1, 2])) == [[1], [1, 2]] assert list(prefixes([1, 2, 3, 4, 5])) == \ [[1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5]] def test_postfixes(): assert list(postfixes([])) == [] assert list(postfixes([1])) == [[1]] assert list(postfixes([1, 2])) == [[2], [1, 2]] assert list(postfixes([1, 2, 3, 4, 5])) == \ [[5], [4, 5], [3, 4, 5], [2, 3, 4, 5], [1, 2, 3, 4, 5]] def test_topological_sort(): V = [2, 3, 5, 7, 8, 9, 10, 11] E = [(7, 11), (7, 8), (5, 11), (3, 8), (3, 10), (11, 2), (11, 9), (11, 10), (8, 9)] assert topological_sort((V, E)) == [3, 5, 7, 8, 11, 2, 9, 10] assert topological_sort((V, E), key=lambda v: -v) == \ [7, 5, 11, 3, 10, 8, 9, 2] raises(ValueError, lambda: topological_sort((V, E + [(10, 7)]))) def test_strongly_connected_components(): assert strongly_connected_components(([], [])) == [] assert strongly_connected_components(([1, 2, 3], [])) == [[1], [2], [3]] V = [1, 2, 3] E = [(1, 2), (1, 3), (2, 1), (2, 3), (3, 1)] assert strongly_connected_components((V, E)) == [[1, 2, 3]] V = [1, 2, 3, 4] E = [(1, 2), (2, 3), (3, 2), (3, 4)] assert strongly_connected_components((V, E)) == [[4], [2, 3], [1]] V = [1, 2, 3, 4] E = [(1, 2), (2, 1), (3, 4), (4, 3)] assert strongly_connected_components((V, E)) == [[1, 2], [3, 4]] def test_connected_components(): assert connected_components(([], [])) == [] assert connected_components(([1, 2, 3], [])) == [[1], [2], [3]] V = [1, 2, 3] E = [(1, 2), (1, 3), (2, 1), (2, 3), (3, 1)] assert connected_components((V, E)) == [[1, 2, 3]] V = [1, 2, 3, 4] E = [(1, 2), (2, 3), (3, 2), (3, 4)] assert connected_components((V, E)) == [[1, 2, 3, 4]] V = [1, 2, 3, 4] E = [(1, 2), (3, 4)] assert connected_components((V, E)) == [[1, 2], [3, 4]] def test_rotate(): A = [0, 1, 2, 3, 4] assert rotate_left(A, 2) == [2, 3, 4, 0, 1] assert rotate_right(A, 1) == [4, 0, 1, 2, 3] A = [] B = rotate_right(A, 1) assert B == [] B.append(1) assert A == [] B = rotate_left(A, 1) assert B == [] B.append(1) assert A == [] def test_multiset_partitions(): A = [0, 1, 2, 3, 4] assert list(multiset_partitions(A, 5)) == [[[0], [1], [2], [3], [4]]] assert len(list(multiset_partitions(A, 4))) == 10 assert len(list(multiset_partitions(A, 3))) == 25 assert list(multiset_partitions([1, 1, 1, 2, 2], 2)) == [ [[1, 1, 1, 2], [2]], [[1, 1, 1], [2, 2]], [[1, 1, 2, 2], [1]], [[1, 1, 2], [1, 2]], [[1, 1], [1, 2, 2]]] assert list(multiset_partitions([1, 1, 2, 2], 2)) == [ [[1, 1, 2], [2]], [[1, 1], [2, 2]], [[1, 2, 2], [1]], [[1, 2], [1, 2]]] assert list(multiset_partitions([1, 2, 3, 4], 2)) == [ [[1, 2, 3], [4]], [[1, 2, 4], [3]], [[1, 2], [3, 4]], [[1, 3, 4], [2]], [[1, 3], [2, 4]], [[1, 4], [2, 3]], [[1], [2, 3, 4]]] assert list(multiset_partitions([1, 2, 2], 2)) == [ [[1, 2], [2]], [[1], [2, 2]]] assert list(multiset_partitions(3)) == [ [[0, 1, 2]], [[0, 1], [2]], [[0, 2], [1]], [[0], [1, 2]], [[0], [1], [2]]] assert list(multiset_partitions(3, 2)) == [ [[0, 1], [2]], [[0, 2], [1]], [[0], [1, 2]]] assert list(multiset_partitions([1] * 3, 2)) == [[[1], [1, 1]]] assert list(multiset_partitions([1] * 3)) == [ [[1, 1, 1]], [[1], [1, 1]], [[1], [1], [1]]] a = [3, 2, 1] assert list(multiset_partitions(a)) == \ list(multiset_partitions(sorted(a))) assert list(multiset_partitions(a, 5)) == [] assert list(multiset_partitions(a, 1)) == [[[1, 2, 3]]] assert list(multiset_partitions(a + [4], 5)) == [] assert list(multiset_partitions(a + [4], 1)) == [[[1, 2, 3, 4]]] assert list(multiset_partitions(2, 5)) == [] assert list(multiset_partitions(2, 1)) == [[[0, 1]]] assert list(multiset_partitions('a')) == [[['a']]] assert list(multiset_partitions('a', 2)) == [] assert list(multiset_partitions('ab')) == [[['a', 'b']], [['a'], ['b']]] assert list(multiset_partitions('ab', 1)) == [[['a', 'b']]] assert list(multiset_partitions('aaa', 1)) == [['aaa']] assert list(multiset_partitions([1, 1], 1)) == [[[1, 1]]] ans = [('mpsyy',), ('mpsy', 'y'), ('mps', 'yy'), ('mps', 'y', 'y'), ('mpyy', 's'), ('mpy', 'sy'), ('mpy', 's', 'y'), ('mp', 'syy'), ('mp', 'sy', 'y'), ('mp', 's', 'yy'), ('mp', 's', 'y', 'y'), ('msyy', 'p'), ('msy', 'py'), ('msy', 'p', 'y'), ('ms', 'pyy'), ('ms', 'py', 'y'), ('ms', 'p', 'yy'), ('ms', 'p', 'y', 'y'), ('myy', 'ps'), ('myy', 'p', 's'), ('my', 'psy'), ('my', 'ps', 'y'), ('my', 'py', 's'), ('my', 'p', 'sy'), ('my', 'p', 's', 'y'), ('m', 'psyy'), ('m', 'psy', 'y'), ('m', 'ps', 'yy'), ('m', 'ps', 'y', 'y'), ('m', 'pyy', 's'), ('m', 'py', 'sy'), ('m', 'py', 's', 'y'), ('m', 'p', 'syy'), ('m', 'p', 'sy', 'y'), ('m', 'p', 's', 'yy'), ('m', 'p', 's', 'y', 'y')] assert list(tuple("".join(part) for part in p) for p in multiset_partitions('sympy')) == ans factorings = [[24], [8, 3], [12, 2], [4, 6], [4, 2, 3], [6, 2, 2], [2, 2, 2, 3]] assert list(factoring_visitor(p, [2,3]) for p in multiset_partitions_taocp([3, 1])) == factorings def test_multiset_combinations(): ans = ['iii', 'iim', 'iip', 'iis', 'imp', 'ims', 'ipp', 'ips', 'iss', 'mpp', 'mps', 'mss', 'pps', 'pss', 'sss'] assert [''.join(i) for i in list(multiset_combinations('mississippi', 3))] == ans M = multiset('mississippi') assert [''.join(i) for i in list(multiset_combinations(M, 3))] == ans assert [''.join(i) for i in multiset_combinations(M, 30)] == [] assert list(multiset_combinations([[1], [2, 3]], 2)) == [[[1], [2, 3]]] assert len(list(multiset_combinations('a', 3))) == 0 assert len(list(multiset_combinations('a', 0))) == 1 assert list(multiset_combinations('abc', 1)) == [['a'], ['b'], ['c']] def test_multiset_permutations(): ans = ['abby', 'abyb', 'aybb', 'baby', 'bayb', 'bbay', 'bbya', 'byab', 'byba', 'yabb', 'ybab', 'ybba'] assert [''.join(i) for i in multiset_permutations('baby')] == ans assert [''.join(i) for i in multiset_permutations(multiset('baby'))] == ans assert list(multiset_permutations([0, 0, 0], 2)) == [[0, 0]] assert list(multiset_permutations([0, 2, 1], 2)) == [ [0, 1], [0, 2], [1, 0], [1, 2], [2, 0], [2, 1]] assert len(list(multiset_permutations('a', 0))) == 1 assert len(list(multiset_permutations('a', 3))) == 0 def test(): for i in range(1, 7): print(i) for p in multiset_permutations([0, 0, 1, 0, 1], i): print(p) assert capture(lambda: test()) == dedent('''\ 1 [0] [1] 2 [0, 0] [0, 1] [1, 0] [1, 1] 3 [0, 0, 0] [0, 0, 1] [0, 1, 0] [0, 1, 1] [1, 0, 0] [1, 0, 1] [1, 1, 0] 4 [0, 0, 0, 1] [0, 0, 1, 0] [0, 0, 1, 1] [0, 1, 0, 0] [0, 1, 0, 1] [0, 1, 1, 0] [1, 0, 0, 0] [1, 0, 0, 1] [1, 0, 1, 0] [1, 1, 0, 0] 5 [0, 0, 0, 1, 1] [0, 0, 1, 0, 1] [0, 0, 1, 1, 0] [0, 1, 0, 0, 1] [0, 1, 0, 1, 0] [0, 1, 1, 0, 0] [1, 0, 0, 0, 1] [1, 0, 0, 1, 0] [1, 0, 1, 0, 0] [1, 1, 0, 0, 0] 6\n''') def test_partitions(): ans = [[{}], [(0, {})]] for i in range(2): assert list(partitions(0, size=i)) == ans[i] assert list(partitions(1, 0, size=i)) == ans[i] assert list(partitions(6, 2, 2, size=i)) == ans[i] assert list(partitions(6, 2, None, size=i)) != ans[i] assert list(partitions(6, None, 2, size=i)) != ans[i] assert list(partitions(6, 2, 0, size=i)) == ans[i] assert [p.copy() for p in partitions(6, k=2)] == [ {2: 3}, {1: 2, 2: 2}, {1: 4, 2: 1}, {1: 6}] assert [p.copy() for p in partitions(6, k=3)] == [ {3: 2}, {1: 1, 2: 1, 3: 1}, {1: 3, 3: 1}, {2: 3}, {1: 2, 2: 2}, {1: 4, 2: 1}, {1: 6}] assert [p.copy() for p in partitions(8, k=4, m=3)] == [ {4: 2}, {1: 1, 3: 1, 4: 1}, {2: 2, 4: 1}, {2: 1, 3: 2}] == [ i.copy() for i in partitions(8, k=4, m=3) if all(k <= 4 for k in i) and sum(i.values()) <=3] assert [p.copy() for p in partitions(S(3), m=2)] == [ {3: 1}, {1: 1, 2: 1}] assert [i.copy() for i in partitions(4, k=3)] == [ {1: 1, 3: 1}, {2: 2}, {1: 2, 2: 1}, {1: 4}] == [ i.copy() for i in partitions(4) if all(k <= 3 for k in i)] # Consistency check on output of _partitions and RGS_unrank. # This provides a sanity test on both routines. Also verifies that # the total number of partitions is the same in each case. # (from pkrathmann2) for n in range(2, 6): i = 0 for m, q in _set_partitions(n): assert q == RGS_unrank(i, n) i += 1 assert i == RGS_enum(n) def test_binary_partitions(): assert [i[:] for i in binary_partitions(10)] == [[8, 2], [8, 1, 1], [4, 4, 2], [4, 4, 1, 1], [4, 2, 2, 2], [4, 2, 2, 1, 1], [4, 2, 1, 1, 1, 1], [4, 1, 1, 1, 1, 1, 1], [2, 2, 2, 2, 2], [2, 2, 2, 2, 1, 1], [2, 2, 2, 1, 1, 1, 1], [2, 2, 1, 1, 1, 1, 1, 1], [2, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] assert len([j[:] for j in binary_partitions(16)]) == 36 def test_bell_perm(): assert [len(set(generate_bell(i))) for i in range(1, 7)] == [ factorial(i) for i in range(1, 7)] assert list(generate_bell(3)) == [ (0, 1, 2), (0, 2, 1), (2, 0, 1), (2, 1, 0), (1, 2, 0), (1, 0, 2)] # generate_bell and trotterjohnson are advertised to return the same # permutations; this is not technically necessary so this test could # be removed for n in range(1, 5): p = Permutation(range(n)) b = generate_bell(n) for bi in b: assert bi == tuple(p.array_form) p = p.next_trotterjohnson() raises(ValueError, lambda: list(generate_bell(0))) # XXX is this consistent with other permutation algorithms? def test_involutions(): lengths = [1, 2, 4, 10, 26, 76] for n, N in enumerate(lengths): i = list(generate_involutions(n + 1)) assert len(i) == N assert len({Permutation(j)**2 for j in i}) == 1 def test_derangements(): assert len(list(generate_derangements(list(range(6))))) == 265 assert ''.join(''.join(i) for i in generate_derangements('abcde')) == ( 'badecbaecdbcaedbcdeabceadbdaecbdeacbdecabeacdbedacbedcacabedcadebcaebd' 'cdaebcdbeacdeabcdebaceabdcebadcedabcedbadabecdaebcdaecbdcaebdcbeadceab' 'dcebadeabcdeacbdebacdebcaeabcdeadbceadcbecabdecbadecdabecdbaedabcedacb' 'edbacedbca') assert list(generate_derangements([0, 1, 2, 3])) == [ [1, 0, 3, 2], [1, 2, 3, 0], [1, 3, 0, 2], [2, 0, 3, 1], [2, 3, 0, 1], [2, 3, 1, 0], [3, 0, 1, 2], [3, 2, 0, 1], [3, 2, 1, 0]] assert list(generate_derangements([0, 1, 2, 2])) == [ [2, 2, 0, 1], [2, 2, 1, 0]] def test_necklaces(): def count(n, k, f): return len(list(necklaces(n, k, f))) m = [] for i in range(1, 8): m.append(( i, count(i, 2, 0), count(i, 2, 1), count(i, 3, 1))) assert Matrix(m) == Matrix([ [1, 2, 2, 3], [2, 3, 3, 6], [3, 4, 4, 10], [4, 6, 6, 21], [5, 8, 8, 39], [6, 14, 13, 92], [7, 20, 18, 198]]) def test_bracelets(): bc = [i for i in bracelets(2, 4)] assert Matrix(bc) == Matrix([ [0, 0], [0, 1], [0, 2], [0, 3], [1, 1], [1, 2], [1, 3], [2, 2], [2, 3], [3, 3] ]) bc = [i for i in bracelets(4, 2)] assert Matrix(bc) == Matrix([ [0, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 1], [0, 1, 0, 1], [0, 1, 1, 1], [1, 1, 1, 1] ]) def test_generate_oriented_forest(): assert list(generate_oriented_forest(5)) == [[0, 1, 2, 3, 4], [0, 1, 2, 3, 3], [0, 1, 2, 3, 2], [0, 1, 2, 3, 1], [0, 1, 2, 3, 0], [0, 1, 2, 2, 2], [0, 1, 2, 2, 1], [0, 1, 2, 2, 0], [0, 1, 2, 1, 2], [0, 1, 2, 1, 1], [0, 1, 2, 1, 0], [0, 1, 2, 0, 1], [0, 1, 2, 0, 0], [0, 1, 1, 1, 1], [0, 1, 1, 1, 0], [0, 1, 1, 0, 1], [0, 1, 1, 0, 0], [0, 1, 0, 1, 0], [0, 1, 0, 0, 0], [0, 0, 0, 0, 0]] assert len(list(generate_oriented_forest(10))) == 1842 def test_unflatten(): r = list(range(10)) assert unflatten(r) == list(zip(r[::2], r[1::2])) assert unflatten(r, 5) == [tuple(r[:5]), tuple(r[5:])] raises(ValueError, lambda: unflatten(list(range(10)), 3)) raises(ValueError, lambda: unflatten(list(range(10)), -2)) def test_common_prefix_suffix(): assert common_prefix([], [1]) == [] assert common_prefix(list(range(3))) == [0, 1, 2] assert common_prefix(list(range(3)), list(range(4))) == [0, 1, 2] assert common_prefix([1, 2, 3], [1, 2, 5]) == [1, 2] assert common_prefix([1, 2, 3], [1, 3, 5]) == [1] assert common_suffix([], [1]) == [] assert common_suffix(list(range(3))) == [0, 1, 2] assert common_suffix(list(range(3)), list(range(3))) == [0, 1, 2] assert common_suffix(list(range(3)), list(range(4))) == [] assert common_suffix([1, 2, 3], [9, 2, 3]) == [2, 3] assert common_suffix([1, 2, 3], [9, 7, 3]) == [3] def test_minlex(): assert minlex([1, 2, 0]) == (0, 1, 2) assert minlex((1, 2, 0)) == (0, 1, 2) assert minlex((1, 0, 2)) == (0, 2, 1) assert minlex((1, 0, 2), directed=False) == (0, 1, 2) assert minlex('aba') == 'aab' def test_ordered(): assert list(ordered((x, y), hash, default=False)) in [[x, y], [y, x]] assert list(ordered((x, y), hash, default=False)) == \ list(ordered((y, x), hash, default=False)) assert list(ordered((x, y))) == [x, y] seq, keys = [[[1, 2, 1], [0, 3, 1], [1, 1, 3], [2], [1]], (lambda x: len(x), lambda x: sum(x))] assert list(ordered(seq, keys, default=False, warn=False)) == \ [[1], [2], [1, 2, 1], [0, 3, 1], [1, 1, 3]] raises(ValueError, lambda: list(ordered(seq, keys, default=False, warn=True))) def test_runs(): assert runs([]) == [] assert runs([1]) == [[1]] assert runs([1, 1]) == [[1], [1]] assert runs([1, 1, 2]) == [[1], [1, 2]] assert runs([1, 2, 1]) == [[1, 2], [1]] assert runs([2, 1, 1]) == [[2], [1], [1]] from operator import lt assert runs([2, 1, 1], lt) == [[2, 1], [1]] def test_reshape(): seq = list(range(1, 9)) assert reshape(seq, [4]) == \ [[1, 2, 3, 4], [5, 6, 7, 8]] assert reshape(seq, (4,)) == \ [(1, 2, 3, 4), (5, 6, 7, 8)] assert reshape(seq, (2, 2)) == \ [(1, 2, 3, 4), (5, 6, 7, 8)] assert reshape(seq, (2, [2])) == \ [(1, 2, [3, 4]), (5, 6, [7, 8])] assert reshape(seq, ((2,), [2])) == \ [((1, 2), [3, 4]), ((5, 6), [7, 8])] assert reshape(seq, (1, [2], 1)) == \ [(1, [2, 3], 4), (5, [6, 7], 8)] assert reshape(tuple(seq), ([[1], 1, (2,)],)) == \ (([[1], 2, (3, 4)],), ([[5], 6, (7, 8)],)) assert reshape(tuple(seq), ([1], 1, (2,))) == \ (([1], 2, (3, 4)), ([5], 6, (7, 8))) assert reshape(list(range(12)), [2, [3], {2}, (1, (3,), 1)]) == \ [[0, 1, [2, 3, 4], {5, 6}, (7, (8, 9, 10), 11)]] raises(ValueError, lambda: reshape([0, 1], [-1])) raises(ValueError, lambda: reshape([0, 1], [3])) def test_uniq(): assert list(uniq(p.copy() for p in partitions(4))) == \ [{4: 1}, {1: 1, 3: 1}, {2: 2}, {1: 2, 2: 1}, {1: 4}] assert list(uniq(x % 2 for x in range(5))) == [0, 1] assert list(uniq('a')) == ['a'] assert list(uniq('ababc')) == list('abc') assert list(uniq([[1], [2, 1], [1]])) == [[1], [2, 1]] assert list(uniq(permutations(i for i in [[1], 2, 2]))) == \ [([1], 2, 2), (2, [1], 2), (2, 2, [1])] assert list(uniq([2, 3, 2, 4, [2], [1], [2], [3], [1]])) == \ [2, 3, 4, [2], [1], [3]] def test_kbins(): assert len(list(kbins('1123', 2, ordered=1))) == 24 assert len(list(kbins('1123', 2, ordered=11))) == 36 assert len(list(kbins('1123', 2, ordered=10))) == 10 assert len(list(kbins('1123', 2, ordered=0))) == 5 assert len(list(kbins('1123', 2, ordered=None))) == 3 def test1(): for orderedval in [None, 0, 1, 10, 11]: print('ordered =', orderedval) for p in kbins([0, 0, 1], 2, ordered=orderedval): print(' ', p) assert capture(lambda : test1()) == dedent('''\ ordered = None [[0], [0, 1]] [[0, 0], [1]] ordered = 0 [[0, 0], [1]] [[0, 1], [0]] ordered = 1 [[0], [0, 1]] [[0], [1, 0]] [[1], [0, 0]] ordered = 10 [[0, 0], [1]] [[1], [0, 0]] [[0, 1], [0]] [[0], [0, 1]] ordered = 11 [[0], [0, 1]] [[0, 0], [1]] [[0], [1, 0]] [[0, 1], [0]] [[1], [0, 0]] [[1, 0], [0]]\n''') def test2(): for orderedval in [None, 0, 1, 10, 11]: print('ordered =', orderedval) for p in kbins(list(range(3)), 2, ordered=orderedval): print(' ', p) assert capture(lambda : test2()) == dedent('''\ ordered = None [[0], [1, 2]] [[0, 1], [2]] ordered = 0 [[0, 1], [2]] [[0, 2], [1]] [[0], [1, 2]] ordered = 1 [[0], [1, 2]] [[0], [2, 1]] [[1], [0, 2]] [[1], [2, 0]] [[2], [0, 1]] [[2], [1, 0]] ordered = 10 [[0, 1], [2]] [[2], [0, 1]] [[0, 2], [1]] [[1], [0, 2]] [[0], [1, 2]] [[1, 2], [0]] ordered = 11 [[0], [1, 2]] [[0, 1], [2]] [[0], [2, 1]] [[0, 2], [1]] [[1], [0, 2]] [[1, 0], [2]] [[1], [2, 0]] [[1, 2], [0]] [[2], [0, 1]] [[2, 0], [1]] [[2], [1, 0]] [[2, 1], [0]]\n''') def test_has_dups(): assert has_dups(set()) is False assert has_dups(list(range(3))) is False assert has_dups([1, 2, 1]) is True def test__partition(): assert _partition('abcde', [1, 0, 1, 2, 0]) == [ ['b', 'e'], ['a', 'c'], ['d']] assert _partition('abcde', [1, 0, 1, 2, 0], 3) == [ ['b', 'e'], ['a', 'c'], ['d']] output = (3, [1, 0, 1, 2, 0]) assert _partition('abcde', *output) == [['b', 'e'], ['a', 'c'], ['d']] def test_ordered_partitions(): from sympy.functions.combinatorial.numbers import nT f = ordered_partitions assert list(f(0, 1)) == [[]] assert list(f(1, 0)) == [[]] for i in range(1, 7): for j in [None] + list(range(1, i)): assert ( sum(1 for p in f(i, j, 1)) == sum(1 for p in f(i, j, 0)) == nT(i, j)) def test_rotations(): assert list(rotations('ab')) == [['a', 'b'], ['b', 'a']] assert list(rotations(range(3))) == [[0, 1, 2], [1, 2, 0], [2, 0, 1]] assert list(rotations(range(3), dir=-1)) == [[0, 1, 2], [2, 0, 1], [1, 2, 0]] def test_ibin(): assert ibin(3) == [1, 1] assert ibin(3, 3) == [0, 1, 1] assert ibin(3, str=True) == '11' assert ibin(3, 3, str=True) == '011' assert list(ibin(2, 'all')) == [(0, 0), (0, 1), (1, 0), (1, 1)] assert list(ibin(2, 'all', str=True)) == ['00', '01', '10', '11']
6e417f7f5c983f448be8dffaee62b78b23620f16a7145c05ad813b70c8b25e30
import sys from sympy.utilities.source import get_mod_func, get_class, source from sympy.testing.pytest import warns_deprecated_sympy from sympy.geometry import point def test_source(): # Dummy stdout class StdOut(object): def write(self, x): pass # Test SymPyDeprecationWarning from source() with warns_deprecated_sympy(): # Redirect stdout temporarily so print out is not seen stdout = sys.stdout try: sys.stdout = StdOut() source(point) finally: sys.stdout = stdout def test_get_mod_func(): assert get_mod_func( 'sympy.core.basic.Basic') == ('sympy.core.basic', 'Basic') def test_get_class(): _basic = get_class('sympy.core.basic.Basic') assert _basic.__name__ == 'Basic'
7a9b7407bbce05c16c485b5b10fe2b5bd92c0422a79909a3fe3b8789560444ec
from sympy.core import S, symbols, Eq, pi, Catalan, EulerGamma, Function from sympy.core.compatibility import StringIO from sympy import Piecewise from sympy import Equality 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" "end\n" ) assert source == expected def test_jl_simple_code_with_header(): name_expr = ("test", (x + y)*z) result, = codegen(name_expr, "Julia", header=True, empty=False) assert result[0] == "test.jl" source = result[1] expected = ( "# Code generated with sympy " + sympy.__version__ + "\n" "#\n" "# See http://www.sympy.org/ for more information.\n" "#\n" "# This file is part of 'project'\n" "function test(x, y, z)\n" " out1 = z.*(x + y)\n" " return out1\n" "end\n" ) assert source == expected def test_jl_simple_code_nameout(): expr = Equality(z, (x + y)) name_expr = ("test", expr) result, = codegen(name_expr, "Julia", header=False, empty=False) source = result[1] expected = ( "function test(x, y)\n" " z = x + y\n" " return z\n" "end\n" ) assert source == expected def test_jl_numbersymbol(): name_expr = ("test", pi**Catalan) result, = codegen(name_expr, "Julia", header=False, empty=False) source = result[1] expected = ( "function test()\n" " out1 = pi^catalan\n" " return out1\n" "end\n" ) assert source == expected @XFAIL def test_jl_numbersymbol_no_inline(): # FIXME: how to pass inline=False to the JuliaCodePrinter? name_expr = ("test", [pi**Catalan, EulerGamma]) result, = codegen(name_expr, "Julia", header=False, empty=False, inline=False) source = result[1] expected = ( "function test()\n" " Catalan = 0.915965594177219\n" " EulerGamma = 0.5772156649015329\n" " out1 = pi^Catalan\n" " out2 = EulerGamma\n" " return out1, out2\n" "end\n" ) assert source == expected def test_jl_code_argument_order(): expr = x + y routine = make_routine("test", expr, argument_sequence=[z, x, y], language="julia") code_gen = JuliaCodeGen() output = StringIO() code_gen.dump_jl([routine], output, "test", header=False, empty=False) source = output.getvalue() expected = ( "function test(z, x, y)\n" " out1 = x + y\n" " return out1\n" "end\n" ) assert source == expected def test_multiple_results_m(): # Here the output order is the input order expr1 = (x + y)*z expr2 = (x - y)*z name_expr = ("test", [expr1, expr2]) result, = codegen(name_expr, "Julia", header=False, empty=False) source = result[1] expected = ( "function test(x, y, z)\n" " out1 = z.*(x + y)\n" " out2 = z.*(x - y)\n" " return out1, out2\n" "end\n" ) assert source == expected def test_results_named_unordered(): # Here output order is based on name_expr A, B, C = symbols('A,B,C') expr1 = Equality(C, (x + y)*z) expr2 = Equality(A, (x - y)*z) expr3 = Equality(B, 2*x) name_expr = ("test", [expr1, expr2, expr3]) result, = codegen(name_expr, "Julia", header=False, empty=False) source = result[1] expected = ( "function test(x, y, z)\n" " C = z.*(x + y)\n" " A = z.*(x - y)\n" " B = 2*x\n" " return C, A, B\n" "end\n" ) assert source == expected def test_results_named_ordered(): A, B, C = symbols('A,B,C') expr1 = Equality(C, (x + y)*z) expr2 = Equality(A, (x - y)*z) expr3 = Equality(B, 2*x) name_expr = ("test", [expr1, expr2, expr3]) result = codegen(name_expr, "Julia", header=False, empty=False, argument_sequence=(x, z, y)) assert result[0][0] == "test.jl" source = result[0][1] expected = ( "function test(x, z, y)\n" " C = z.*(x + y)\n" " A = z.*(x - y)\n" " B = 2*x\n" " return C, A, B\n" "end\n" ) assert source == expected def test_complicated_jl_codegen(): from sympy import sin, cos, tan name_expr = ("testlong", [ ((sin(x) + cos(y) + tan(z))**3).expand(), cos(cos(cos(cos(cos(cos(cos(cos(x + y + z)))))))) ]) result = codegen(name_expr, "Julia", header=False, empty=False) assert result[0][0] == "testlong.jl" source = result[0][1] expected = ( "function testlong(x, y, z)\n" " out1 = sin(x).^3 + 3*sin(x).^2.*cos(y) + 3*sin(x).^2.*tan(z)" " + 3*sin(x).*cos(y).^2 + 6*sin(x).*cos(y).*tan(z) + 3*sin(x).*tan(z).^2" " + cos(y).^3 + 3*cos(y).^2.*tan(z) + 3*cos(y).*tan(z).^2 + tan(z).^3\n" " out2 = cos(cos(cos(cos(cos(cos(cos(cos(x + y + z))))))))\n" " return out1, out2\n" "end\n" ) assert source == expected def test_jl_output_arg_mixed_unordered(): # named outputs are alphabetical, unnamed output appear in the given order from sympy import sin, cos a = symbols("a") name_expr = ("foo", [cos(2*x), Equality(y, sin(x)), cos(x), Equality(a, sin(2*x))]) result, = codegen(name_expr, "Julia", header=False, empty=False) assert result[0] == "foo.jl" source = result[1]; expected = ( 'function foo(x)\n' ' out1 = cos(2*x)\n' ' y = sin(x)\n' ' out3 = cos(x)\n' ' a = sin(2*x)\n' ' return out1, y, out3, a\n' 'end\n' ) assert source == expected def test_jl_piecewise_(): pw = Piecewise((0, x < -1), (x**2, x <= 1), (-x+2, x > 1), (1, True), evaluate=False) name_expr = ("pwtest", pw) result, = codegen(name_expr, "Julia", header=False, empty=False) source = result[1] expected = ( "function pwtest(x)\n" " out1 = ((x < -1) ? (0) :\n" " (x <= 1) ? (x.^2) :\n" " (x > 1) ? (2 - x) : (1))\n" " return out1\n" "end\n" ) assert source == expected @XFAIL def test_jl_piecewise_no_inline(): # FIXME: how to pass inline=False to the JuliaCodePrinter? pw = Piecewise((0, x < -1), (x**2, x <= 1), (-x+2, x > 1), (1, True)) name_expr = ("pwtest", pw) result, = codegen(name_expr, "Julia", header=False, empty=False, inline=False) source = result[1] expected = ( "function pwtest(x)\n" " if (x < -1)\n" " out1 = 0\n" " elseif (x <= 1)\n" " out1 = x.^2\n" " elseif (x > 1)\n" " out1 = -x + 2\n" " else\n" " out1 = 1\n" " end\n" " return out1\n" "end\n" ) assert source == expected def test_jl_multifcns_per_file(): name_expr = [ ("foo", [2*x, 3*y]), ("bar", [y**2, 4*y]) ] result = codegen(name_expr, "Julia", header=False, empty=False) assert result[0][0] == "foo.jl" source = result[0][1]; expected = ( "function foo(x, y)\n" " out1 = 2*x\n" " out2 = 3*y\n" " return out1, out2\n" "end\n" "function bar(y)\n" " out1 = y.^2\n" " out2 = 4*y\n" " return out1, out2\n" "end\n" ) assert source == expected def test_jl_multifcns_per_file_w_header(): name_expr = [ ("foo", [2*x, 3*y]), ("bar", [y**2, 4*y]) ] result = codegen(name_expr, "Julia", header=True, empty=False) assert result[0][0] == "foo.jl" source = result[0][1]; expected = ( "# Code generated with sympy " + sympy.__version__ + "\n" "#\n" "# See http://www.sympy.org/ for more information.\n" "#\n" "# This file is part of 'project'\n" "function foo(x, y)\n" " out1 = 2*x\n" " out2 = 3*y\n" " return out1, out2\n" "end\n" "function bar(y)\n" " out1 = y.^2\n" " out2 = 4*y\n" " return out1, out2\n" "end\n" ) assert source == expected def test_jl_filename_match_prefix(): name_expr = [ ("foo", [2*x, 3*y]), ("bar", [y**2, 4*y]) ] result, = codegen(name_expr, "Julia", prefix="baz", header=False, empty=False) assert result[0] == "baz.jl" def test_jl_matrix_named(): e2 = Matrix([[x, 2*y, pi*z]]) name_expr = ("test", Equality(MatrixSymbol('myout1', 1, 3), e2)) result = codegen(name_expr, "Julia", header=False, empty=False) assert result[0][0] == "test.jl" source = result[0][1] expected = ( "function test(x, y, z)\n" " myout1 = [x 2*y pi*z]\n" " return myout1\n" "end\n" ) assert source == expected def test_jl_matrix_named_matsym(): myout1 = MatrixSymbol('myout1', 1, 3) e2 = Matrix([[x, 2*y, pi*z]]) name_expr = ("test", Equality(myout1, e2, evaluate=False)) result, = codegen(name_expr, "Julia", header=False, empty=False) source = result[1] expected = ( "function test(x, y, z)\n" " myout1 = [x 2*y pi*z]\n" " return myout1\n" "end\n" ) assert source == expected def test_jl_matrix_output_autoname(): expr = Matrix([[x, x+y, 3]]) name_expr = ("test", expr) result, = codegen(name_expr, "Julia", header=False, empty=False) source = result[1] expected = ( "function test(x, y)\n" " out1 = [x x + y 3]\n" " return out1\n" "end\n" ) assert source == expected def test_jl_matrix_output_autoname_2(): e1 = (x + y) e2 = Matrix([[2*x, 2*y, 2*z]]) e3 = Matrix([[x], [y], [z]]) e4 = Matrix([[x, y], [z, 16]]) name_expr = ("test", (e1, e2, e3, e4)) result, = codegen(name_expr, "Julia", header=False, empty=False) source = result[1] expected = ( "function test(x, y, z)\n" " out1 = x + y\n" " out2 = [2*x 2*y 2*z]\n" " out3 = [x, y, z]\n" " out4 = [x y;\n" " z 16]\n" " return out1, out2, out3, out4\n" "end\n" ) assert source == expected def test_jl_results_matrix_named_ordered(): B, C = symbols('B,C') A = MatrixSymbol('A', 1, 3) expr1 = Equality(C, (x + y)*z) expr2 = Equality(A, Matrix([[1, 2, x]])) expr3 = Equality(B, 2*x) name_expr = ("test", [expr1, expr2, expr3]) result, = codegen(name_expr, "Julia", header=False, empty=False, argument_sequence=(x, z, y)) source = result[1] expected = ( "function test(x, z, y)\n" " C = z.*(x + y)\n" " A = [1 2 x]\n" " B = 2*x\n" " return C, A, B\n" "end\n" ) assert source == expected def test_jl_matrixsymbol_slice(): A = MatrixSymbol('A', 2, 3) B = MatrixSymbol('B', 1, 3) C = MatrixSymbol('C', 1, 3) D = MatrixSymbol('D', 2, 1) name_expr = ("test", [Equality(B, A[0, :]), Equality(C, A[1, :]), Equality(D, A[:, 2])]) result, = codegen(name_expr, "Julia", header=False, empty=False) source = result[1] expected = ( "function test(A)\n" " B = A[1,:]\n" " C = A[2,:]\n" " D = A[:,3]\n" " return B, C, D\n" "end\n" ) assert source == expected def test_jl_matrixsymbol_slice2(): A = MatrixSymbol('A', 3, 4) B = MatrixSymbol('B', 2, 2) C = MatrixSymbol('C', 2, 2) name_expr = ("test", [Equality(B, A[0:2, 0:2]), Equality(C, A[0:2, 1:3])]) result, = codegen(name_expr, "Julia", header=False, empty=False) source = result[1] expected = ( "function test(A)\n" " B = A[1:2,1:2]\n" " C = A[1:2,2:3]\n" " return B, C\n" "end\n" ) assert source == expected def test_jl_matrixsymbol_slice3(): A = MatrixSymbol('A', 8, 7) B = MatrixSymbol('B', 2, 2) C = MatrixSymbol('C', 4, 2) name_expr = ("test", [Equality(B, A[6:, 1::3]), Equality(C, A[::2, ::3])]) result, = codegen(name_expr, "Julia", header=False, empty=False) source = result[1] expected = ( "function test(A)\n" " B = A[7:end,2:3:end]\n" " C = A[1:2:end,1:3:end]\n" " return B, C\n" "end\n" ) assert source == expected def test_jl_matrixsymbol_slice_autoname(): A = MatrixSymbol('A', 2, 3) B = MatrixSymbol('B', 1, 3) name_expr = ("test", [Equality(B, A[0,:]), A[1,:], A[:,0], A[:,1]]) result, = codegen(name_expr, "Julia", header=False, empty=False) source = result[1] expected = ( "function test(A)\n" " B = A[1,:]\n" " out2 = A[2,:]\n" " out3 = A[:,1]\n" " out4 = A[:,2]\n" " return B, out2, out3, out4\n" "end\n" ) assert source == expected def test_jl_loops(): # Note: an Julia 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 sympy.tensor import IndexedBase, Idx from sympy 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])), "Julia", header=False, empty=False) source = result[1] expected = ( 'function mat_vec_mult(y, 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' ' return y\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_jl_tensor_loops_multiple_contractions(): # see comments in previous test about vectorizing from sympy.tensor import IndexedBase, Idx from sympy 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])), "Julia", header=False, empty=False) source = result[1] expected = ( 'function tensorthing(y, 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] = A[i,j,k,l].*B[j,k,l] + y[i]\n' ' end\n' ' end\n' ' end\n' ' end\n' ' return y\n' 'end\n' ) assert source == expected def test_jl_InOutArgument(): expr = Equality(x, x**2) name_expr = ("mysqr", expr) result, = codegen(name_expr, "Julia", header=False, empty=False) source = result[1] expected = ( "function mysqr(x)\n" " x = x.^2\n" " return x\n" "end\n" ) assert source == expected def test_jl_InOutArgument_order(): # can specify the order as (x, y) expr = Equality(x, x**2 + y) name_expr = ("test", expr) result, = codegen(name_expr, "Julia", header=False, empty=False, argument_sequence=(x,y)) source = result[1] expected = ( "function test(x, y)\n" " x = x.^2 + y\n" " return x\n" "end\n" ) assert source == expected # make sure it gives (x, y) not (y, x) expr = Equality(x, x**2 + y) name_expr = ("test", expr) result, = codegen(name_expr, "Julia", header=False, empty=False) source = result[1] expected = ( "function test(x, y)\n" " x = x.^2 + y\n" " return x\n" "end\n" ) assert source == expected def test_jl_not_supported(): f = Function('f') name_expr = ("test", [f(x).diff(x), S.ComplexInfinity]) result, = codegen(name_expr, "Julia", header=False, empty=False) source = result[1] expected = ( "function test(x)\n" " # unsupported: Derivative(f(x), x)\n" " # unsupported: zoo\n" " out1 = Derivative(f(x), x)\n" " out2 = zoo\n" " return out1, out2\n" "end\n" ) assert source == expected def test_global_vars_octave(): x, y, z, t = symbols("x y z t") result = codegen(('f', x*y), "Julia", header=False, empty=False, global_vars=(y,)) source = result[0][1] expected = ( "function f(x)\n" " out1 = x.*y\n" " return out1\n" "end\n" ) assert source == expected result = codegen(('f', x*y+z), "Julia", header=False, empty=False, argument_sequence=(x, y), global_vars=(z, t)) source = result[0][1] expected = ( "function f(x, y)\n" " out1 = x.*y + z\n" " return out1\n" "end\n" ) assert source == expected
49946731b4713aba86a46668ee391ece9ba27fdd8f927e9210d2e9df69253c19
from sympy.core import symbols, Eq, pi, Catalan, Lambda, Dummy from sympy.core.compatibility import StringIO from sympy import erf, Integral, Symbol from sympy import Equality from sympy.matrices import Matrix, MatrixSymbol from sympy.utilities.codegen import ( codegen, make_routine, CCodeGen, C89CodeGen, C99CodeGen, InputArgument, CodeGenError, FCodeGen, CodeGenArgumentListError, OutputArgument, InOutArgument) from sympy.testing.pytest import raises from sympy.utilities.lambdify import implemented_function #FIXME: Fails due to circular import in with core # from sympy import codegen def get_string(dump_fn, routines, prefix="file", header=False, empty=False): """Wrapper for dump_fn. dump_fn writes its results to a stream object and this wrapper returns the contents of that stream as a string. This auxiliary function is used by many tests below. The header and the empty lines are not generated to facilitate the testing of the output. """ output = StringIO() dump_fn(routines, output, prefix, header, empty) source = output.getvalue() output.close() return source 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_empty_c_code(): code_gen = C89CodeGen() source = get_string(code_gen.dump_c, []) assert source == "#include \"file.h\"\n#include <math.h>\n" def test_empty_c_code_with_comment(): code_gen = C89CodeGen() source = get_string(code_gen.dump_c, [], header=True) assert source[:82] == ( "/******************************************************************************\n *" ) # " Code generated with sympy 0.7.2-git " assert source[158:] == ( "*\n" " * *\n" " * See http://www.sympy.org/ for more information. *\n" " * *\n" " * This file is part of 'project' *\n" " ******************************************************************************/\n" "#include \"file.h\"\n" "#include <math.h>\n" ) def test_empty_c_header(): code_gen = C99CodeGen() source = get_string(code_gen.dump_h, []) assert source == "#ifndef PROJECT__FILE__H\n#define PROJECT__FILE__H\n#endif\n" def test_simple_c_code(): x, y, z = symbols('x,y,z') expr = (x + y)*z routine = make_routine("test", expr) code_gen = C89CodeGen() source = get_string(code_gen.dump_c, [routine]) expected = ( "#include \"file.h\"\n" "#include <math.h>\n" "double test(double x, double y, double z) {\n" " double test_result;\n" " test_result = z*(x + y);\n" " return test_result;\n" "}\n" ) assert source == expected def test_c_code_reserved_words(): x, y, z = symbols('if, typedef, while') expr = (x + y) * z routine = make_routine("test", expr) code_gen = C99CodeGen() source = get_string(code_gen.dump_c, [routine]) expected = ( "#include \"file.h\"\n" "#include <math.h>\n" "double test(double if_, double typedef_, double while_) {\n" " double test_result;\n" " test_result = while_*(if_ + typedef_);\n" " return test_result;\n" "}\n" ) assert source == expected def test_numbersymbol_c_code(): routine = make_routine("test", pi**Catalan) code_gen = C89CodeGen() source = get_string(code_gen.dump_c, [routine]) expected = ( "#include \"file.h\"\n" "#include <math.h>\n" "double test() {\n" " double test_result;\n" " double const Catalan = %s;\n" " test_result = pow(M_PI, Catalan);\n" " return test_result;\n" "}\n" ) % Catalan.evalf(17) assert source == expected def test_c_code_argument_order(): x, y, z = symbols('x,y,z') expr = x + y routine = make_routine("test", expr, argument_sequence=[z, x, y]) code_gen = C89CodeGen() source = get_string(code_gen.dump_c, [routine]) expected = ( "#include \"file.h\"\n" "#include <math.h>\n" "double test(double z, double x, double y) {\n" " double test_result;\n" " test_result = x + y;\n" " return test_result;\n" "}\n" ) assert source == expected def test_simple_c_header(): x, y, z = symbols('x,y,z') expr = (x + y)*z routine = make_routine("test", expr) code_gen = C89CodeGen() source = get_string(code_gen.dump_h, [routine]) expected = ( "#ifndef PROJECT__FILE__H\n" "#define PROJECT__FILE__H\n" "double test(double x, double y, double z);\n" "#endif\n" ) assert source == expected def test_simple_c_codegen(): x, y, z = symbols('x,y,z') expr = (x + y)*z expected = [ ("file.c", "#include \"file.h\"\n" "#include <math.h>\n" "double test(double x, double y, double z) {\n" " double test_result;\n" " test_result = z*(x + y);\n" " return test_result;\n" "}\n"), ("file.h", "#ifndef PROJECT__FILE__H\n" "#define PROJECT__FILE__H\n" "double test(double x, double y, double z);\n" "#endif\n") ] result = codegen(("test", expr), "C", "file", header=False, empty=False) assert result == expected def test_multiple_results_c(): x, y, z = symbols('x,y,z') expr1 = (x + y)*z expr2 = (x - y)*z routine = make_routine( "test", [expr1, expr2] ) code_gen = C99CodeGen() raises(CodeGenError, lambda: get_string(code_gen.dump_h, [routine])) def test_no_results_c(): raises(ValueError, lambda: make_routine("test", [])) def test_ansi_math1_codegen(): # not included: log10 from sympy import (acos, asin, atan, ceiling, cos, cosh, floor, log, ln, sin, sinh, sqrt, tan, tanh, Abs) x = symbols('x') name_expr = [ ("test_fabs", 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, "C89", "file", header=False, empty=False) assert result[0][0] == "file.c" assert result[0][1] == ( '#include "file.h"\n#include <math.h>\n' 'double test_fabs(double x) {\n double test_fabs_result;\n test_fabs_result = fabs(x);\n return test_fabs_result;\n}\n' 'double test_acos(double x) {\n double test_acos_result;\n test_acos_result = acos(x);\n return test_acos_result;\n}\n' 'double test_asin(double x) {\n double test_asin_result;\n test_asin_result = asin(x);\n return test_asin_result;\n}\n' 'double test_atan(double x) {\n double test_atan_result;\n test_atan_result = atan(x);\n return test_atan_result;\n}\n' 'double test_ceil(double x) {\n double test_ceil_result;\n test_ceil_result = ceil(x);\n return test_ceil_result;\n}\n' 'double test_cos(double x) {\n double test_cos_result;\n test_cos_result = cos(x);\n return test_cos_result;\n}\n' 'double test_cosh(double x) {\n double test_cosh_result;\n test_cosh_result = cosh(x);\n return test_cosh_result;\n}\n' 'double test_floor(double x) {\n double test_floor_result;\n test_floor_result = floor(x);\n return test_floor_result;\n}\n' 'double test_log(double x) {\n double test_log_result;\n test_log_result = log(x);\n return test_log_result;\n}\n' 'double test_ln(double x) {\n double test_ln_result;\n test_ln_result = log(x);\n return test_ln_result;\n}\n' 'double test_sin(double x) {\n double test_sin_result;\n test_sin_result = sin(x);\n return test_sin_result;\n}\n' 'double test_sinh(double x) {\n double test_sinh_result;\n test_sinh_result = sinh(x);\n return test_sinh_result;\n}\n' 'double test_sqrt(double x) {\n double test_sqrt_result;\n test_sqrt_result = sqrt(x);\n return test_sqrt_result;\n}\n' 'double test_tan(double x) {\n double test_tan_result;\n test_tan_result = tan(x);\n return test_tan_result;\n}\n' 'double test_tanh(double x) {\n double test_tanh_result;\n test_tanh_result = tanh(x);\n return test_tanh_result;\n}\n' ) assert result[1][0] == "file.h" assert result[1][1] == ( '#ifndef PROJECT__FILE__H\n#define PROJECT__FILE__H\n' 'double test_fabs(double x);\ndouble test_acos(double x);\n' 'double test_asin(double x);\ndouble test_atan(double x);\n' 'double test_ceil(double x);\ndouble test_cos(double x);\n' 'double test_cosh(double x);\ndouble test_floor(double x);\n' 'double test_log(double x);\ndouble test_ln(double x);\n' 'double test_sin(double x);\ndouble test_sinh(double x);\n' 'double test_sqrt(double x);\ndouble test_tan(double x);\n' 'double test_tanh(double x);\n#endif\n' ) def test_ansi_math2_codegen(): # not included: frexp, ldexp, modf, fmod from sympy import atan2 x, y = symbols('x,y') name_expr = [ ("test_atan2", atan2(x, y)), ("test_pow", x**y), ] result = codegen(name_expr, "C89", "file", header=False, empty=False) assert result[0][0] == "file.c" assert result[0][1] == ( '#include "file.h"\n#include <math.h>\n' 'double test_atan2(double x, double y) {\n double test_atan2_result;\n test_atan2_result = atan2(x, y);\n return test_atan2_result;\n}\n' 'double test_pow(double x, double y) {\n double test_pow_result;\n test_pow_result = pow(x, y);\n return test_pow_result;\n}\n' ) assert result[1][0] == "file.h" assert result[1][1] == ( '#ifndef PROJECT__FILE__H\n#define PROJECT__FILE__H\n' 'double test_atan2(double x, double y);\n' 'double test_pow(double x, double y);\n' '#endif\n' ) def test_complicated_codegen(): from sympy import sin, cos, tan x, y, z = symbols('x,y,z') name_expr = [ ("test1", ((sin(x) + cos(y) + tan(z))**7).expand()), ("test2", cos(cos(cos(cos(cos(cos(cos(cos(x + y + z))))))))), ] result = codegen(name_expr, "C89", "file", header=False, empty=False) assert result[0][0] == "file.c" assert result[0][1] == ( '#include "file.h"\n#include <math.h>\n' 'double test1(double x, double y, double z) {\n' ' double test1_result;\n' ' test1_result = ' 'pow(sin(x), 7) + ' '7*pow(sin(x), 6)*cos(y) + ' '7*pow(sin(x), 6)*tan(z) + ' '21*pow(sin(x), 5)*pow(cos(y), 2) + ' '42*pow(sin(x), 5)*cos(y)*tan(z) + ' '21*pow(sin(x), 5)*pow(tan(z), 2) + ' '35*pow(sin(x), 4)*pow(cos(y), 3) + ' '105*pow(sin(x), 4)*pow(cos(y), 2)*tan(z) + ' '105*pow(sin(x), 4)*cos(y)*pow(tan(z), 2) + ' '35*pow(sin(x), 4)*pow(tan(z), 3) + ' '35*pow(sin(x), 3)*pow(cos(y), 4) + ' '140*pow(sin(x), 3)*pow(cos(y), 3)*tan(z) + ' '210*pow(sin(x), 3)*pow(cos(y), 2)*pow(tan(z), 2) + ' '140*pow(sin(x), 3)*cos(y)*pow(tan(z), 3) + ' '35*pow(sin(x), 3)*pow(tan(z), 4) + ' '21*pow(sin(x), 2)*pow(cos(y), 5) + ' '105*pow(sin(x), 2)*pow(cos(y), 4)*tan(z) + ' '210*pow(sin(x), 2)*pow(cos(y), 3)*pow(tan(z), 2) + ' '210*pow(sin(x), 2)*pow(cos(y), 2)*pow(tan(z), 3) + ' '105*pow(sin(x), 2)*cos(y)*pow(tan(z), 4) + ' '21*pow(sin(x), 2)*pow(tan(z), 5) + ' '7*sin(x)*pow(cos(y), 6) + ' '42*sin(x)*pow(cos(y), 5)*tan(z) + ' '105*sin(x)*pow(cos(y), 4)*pow(tan(z), 2) + ' '140*sin(x)*pow(cos(y), 3)*pow(tan(z), 3) + ' '105*sin(x)*pow(cos(y), 2)*pow(tan(z), 4) + ' '42*sin(x)*cos(y)*pow(tan(z), 5) + ' '7*sin(x)*pow(tan(z), 6) + ' 'pow(cos(y), 7) + ' '7*pow(cos(y), 6)*tan(z) + ' '21*pow(cos(y), 5)*pow(tan(z), 2) + ' '35*pow(cos(y), 4)*pow(tan(z), 3) + ' '35*pow(cos(y), 3)*pow(tan(z), 4) + ' '21*pow(cos(y), 2)*pow(tan(z), 5) + ' '7*cos(y)*pow(tan(z), 6) + ' 'pow(tan(z), 7);\n' ' return test1_result;\n' '}\n' 'double test2(double x, double y, double z) {\n' ' double test2_result;\n' ' test2_result = cos(cos(cos(cos(cos(cos(cos(cos(x + y + z))))))));\n' ' return test2_result;\n' '}\n' ) assert result[1][0] == "file.h" assert result[1][1] == ( '#ifndef PROJECT__FILE__H\n' '#define PROJECT__FILE__H\n' 'double test1(double x, double y, double z);\n' 'double test2(double x, double y, double z);\n' '#endif\n' ) def test_loops_c(): from sympy.tensor import IndexedBase, Idx from sympy 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) (f1, code), (f2, interface) = codegen( ('matrix_vector', Eq(y[i], A[i, j]*x[j])), "C99", "file", header=False, empty=False) assert f1 == 'file.c' expected = ( '#include "file.h"\n' '#include <math.h>\n' 'void matrix_vector(double *A, int m, int n, double *x, double *y) {\n' ' 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] = %(rhs)s + y[i];\n' ' }\n' ' }\n' '}\n' ) assert (code == expected % {'rhs': 'A[%s]*x[j]' % (i*n + j)} or code == expected % {'rhs': 'A[%s]*x[j]' % (j + i*n)} or code == expected % {'rhs': 'x[j]*A[%s]' % (i*n + j)} or code == expected % {'rhs': 'x[j]*A[%s]' % (j + i*n)}) assert f2 == 'file.h' assert interface == ( '#ifndef PROJECT__FILE__H\n' '#define PROJECT__FILE__H\n' 'void matrix_vector(double *A, int m, int n, double *x, double *y);\n' '#endif\n' ) def test_dummy_loops_c(): from sympy.tensor import IndexedBase, Idx i, m = symbols('i m', integer=True, cls=Dummy) x = IndexedBase('x') y = IndexedBase('y') i = Idx(i, m) expected = ( '#include "file.h"\n' '#include <math.h>\n' 'void test_dummies(int m_%(mno)i, double *x, double *y) {\n' ' for (int i_%(ino)i=0; i_%(ino)i<m_%(mno)i; i_%(ino)i++){\n' ' y[i_%(ino)i] = x[i_%(ino)i];\n' ' }\n' '}\n' ) % {'ino': i.label.dummy_index, 'mno': m.dummy_index} r = make_routine('test_dummies', Eq(y[i], x[i])) c89 = C89CodeGen() c99 = C99CodeGen() code = get_string(c99.dump_c, [r]) assert code == expected with raises(NotImplementedError): get_string(c89.dump_c, [r]) def test_partial_loops_c(): # check that loop boundaries are determined by Idx, and array strides # determined by shape of IndexedBase object. from sympy.tensor import IndexedBase, Idx from sympy import symbols n, m, o, p = symbols('n m o p', integer=True) A = IndexedBase('A', shape=(m, p)) x = IndexedBase('x') y = IndexedBase('y') i = Idx('i', (o, m - 5)) # Note: bounds are inclusive j = Idx('j', n) # dimension n corresponds to bounds (0, n - 1) (f1, code), (f2, interface) = codegen( ('matrix_vector', Eq(y[i], A[i, j]*x[j])), "C99", "file", header=False, empty=False) assert f1 == 'file.c' expected = ( '#include "file.h"\n' '#include <math.h>\n' 'void matrix_vector(double *A, int m, int n, int o, int p, double *x, double *y) {\n' ' for (int i=o; i<%(upperi)s; i++){\n' ' y[i] = 0;\n' ' }\n' ' for (int i=o; i<%(upperi)s; i++){\n' ' for (int j=0; j<n; j++){\n' ' y[i] = %(rhs)s + y[i];\n' ' }\n' ' }\n' '}\n' ) % {'upperi': m - 4, 'rhs': '%(rhs)s'} assert (code == expected % {'rhs': 'A[%s]*x[j]' % (i*p + j)} or code == expected % {'rhs': 'A[%s]*x[j]' % (j + i*p)} or code == expected % {'rhs': 'x[j]*A[%s]' % (i*p + j)} or code == expected % {'rhs': 'x[j]*A[%s]' % (j + i*p)}) assert f2 == 'file.h' assert interface == ( '#ifndef PROJECT__FILE__H\n' '#define PROJECT__FILE__H\n' 'void matrix_vector(double *A, int m, int n, int o, int p, double *x, double *y);\n' '#endif\n' ) def test_output_arg_c(): from sympy import sin, cos, Equality x, y, z = symbols("x,y,z") r = make_routine("foo", [Equality(y, sin(x)), cos(x)]) c = C89CodeGen() result = c.write([r], "test", header=False, empty=False) assert result[0][0] == "test.c" expected = ( '#include "test.h"\n' '#include <math.h>\n' 'double foo(double x, double *y) {\n' ' (*y) = sin(x);\n' ' double foo_result;\n' ' foo_result = cos(x);\n' ' return foo_result;\n' '}\n' ) assert result[0][1] == expected def test_output_arg_c_reserved_words(): from sympy import sin, cos, Equality x, y, z = symbols("if, while, z") r = make_routine("foo", [Equality(y, sin(x)), cos(x)]) c = C89CodeGen() result = c.write([r], "test", header=False, empty=False) assert result[0][0] == "test.c" expected = ( '#include "test.h"\n' '#include <math.h>\n' 'double foo(double if_, double *while_) {\n' ' (*while_) = sin(if_);\n' ' double foo_result;\n' ' foo_result = cos(if_);\n' ' return foo_result;\n' '}\n' ) assert result[0][1] == expected 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' ) 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 def test_ccode_matrixsymbol_slice(): A = MatrixSymbol('A', 5, 3) B = MatrixSymbol('B', 1, 3) C = MatrixSymbol('C', 1, 3) D = MatrixSymbol('D', 5, 1) name_expr = ("test", [Equality(B, A[0, :]), Equality(C, A[1, :]), Equality(D, A[:, 2])]) result = codegen(name_expr, "c99", "test", header=False, empty=False) source = result[0][1] expected = ( '#include "test.h"\n' '#include <math.h>\n' 'void test(double *A, double *B, double *C, double *D) {\n' ' B[0] = A[0];\n' ' B[1] = A[1];\n' ' B[2] = A[2];\n' ' C[0] = A[3];\n' ' C[1] = A[4];\n' ' C[2] = A[5];\n' ' D[0] = A[2];\n' ' D[1] = A[5];\n' ' D[2] = A[8];\n' ' D[3] = A[11];\n' ' D[4] = A[14];\n' '}\n' ) assert source == expected def test_ccode_cse(): a, b, c, d = symbols('a b c d') e = MatrixSymbol('e', 3, 1) name_expr = ("test", [Equality(e, Matrix([[a*b], [a*b + c*d], [a*b*c*d]]))]) generator = CCodeGen(cse=True) result = codegen(name_expr, code_gen=generator, header=False, empty=False) source = result[0][1] expected = ( '#include "test.h"\n' '#include <math.h>\n' 'void test(double a, double b, double c, double d, double *e) {\n' ' const double x0 = a*b;\n' ' const double x1 = c*d;\n' ' e[0] = x0;\n' ' e[1] = x0 + x1;\n' ' e[2] = x0*x1;\n' '}\n' ) assert source == expected def test_ccode_unused_array_arg(): x = MatrixSymbol('x', 2, 1) # x does not appear in output name_expr = ("test", 1.0) generator = CCodeGen() result = codegen(name_expr, code_gen=generator, header=False, empty=False, argument_sequence=(x,)) source = result[0][1] # note: x should appear as (double *) expected = ( '#include "test.h"\n' '#include <math.h>\n' 'double test(double *x) {\n' ' double test_result;\n' ' test_result = 1.0;\n' ' return test_result;\n' '}\n' ) assert source == expected def test_empty_f_code(): code_gen = FCodeGen() source = get_string(code_gen.dump_f95, []) assert source == "" def test_empty_f_code_with_header(): code_gen = FCodeGen() source = get_string(code_gen.dump_f95, [], header=True) assert source[:82] == ( "!******************************************************************************\n!*" ) # " Code generated with sympy 0.7.2-git " assert source[158:] == ( "*\n" "!* *\n" "!* See http://www.sympy.org/ for more information. *\n" "!* *\n" "!* This file is part of 'project' *\n" "!******************************************************************************\n" ) def test_empty_f_header(): code_gen = FCodeGen() source = get_string(code_gen.dump_h, []) assert source == "" def test_simple_f_code(): x, y, z = symbols('x,y,z') expr = (x + y)*z routine = make_routine("test", expr) code_gen = FCodeGen() source = get_string(code_gen.dump_f95, [routine]) expected = ( "REAL*8 function test(x, y, z)\n" "implicit none\n" "REAL*8, intent(in) :: x\n" "REAL*8, intent(in) :: y\n" "REAL*8, intent(in) :: z\n" "test = z*(x + y)\n" "end function\n" ) assert source == expected def test_numbersymbol_f_code(): routine = make_routine("test", pi**Catalan) code_gen = FCodeGen() source = get_string(code_gen.dump_f95, [routine]) expected = ( "REAL*8 function test()\n" "implicit none\n" "REAL*8, parameter :: Catalan = %sd0\n" "REAL*8, parameter :: pi = %sd0\n" "test = pi**Catalan\n" "end function\n" ) % (Catalan.evalf(17), pi.evalf(17)) assert source == expected def test_erf_f_code(): x = symbols('x') routine = make_routine("test", erf(x) - erf(-2 * x)) code_gen = FCodeGen() source = get_string(code_gen.dump_f95, [routine]) expected = ( "REAL*8 function test(x)\n" "implicit none\n" "REAL*8, intent(in) :: x\n" "test = erf(x) + erf(2.0d0*x)\n" "end function\n" ) assert source == expected, source def test_f_code_argument_order(): x, y, z = symbols('x,y,z') expr = x + y routine = make_routine("test", expr, argument_sequence=[z, x, y]) code_gen = FCodeGen() source = get_string(code_gen.dump_f95, [routine]) expected = ( "REAL*8 function test(z, x, y)\n" "implicit none\n" "REAL*8, intent(in) :: z\n" "REAL*8, intent(in) :: x\n" "REAL*8, intent(in) :: y\n" "test = x + y\n" "end function\n" ) assert source == expected def test_simple_f_header(): x, y, z = symbols('x,y,z') expr = (x + y)*z routine = make_routine("test", expr) code_gen = FCodeGen() source = get_string(code_gen.dump_h, [routine]) expected = ( "interface\n" "REAL*8 function test(x, y, z)\n" "implicit none\n" "REAL*8, intent(in) :: x\n" "REAL*8, intent(in) :: y\n" "REAL*8, intent(in) :: z\n" "end function\n" "end interface\n" ) assert source == expected def test_simple_f_codegen(): x, y, z = symbols('x,y,z') expr = (x + y)*z result = codegen( ("test", expr), "F95", "file", header=False, empty=False) expected = [ ("file.f90", "REAL*8 function test(x, y, z)\n" "implicit none\n" "REAL*8, intent(in) :: x\n" "REAL*8, intent(in) :: y\n" "REAL*8, intent(in) :: z\n" "test = z*(x + y)\n" "end function\n"), ("file.h", "interface\n" "REAL*8 function test(x, y, z)\n" "implicit none\n" "REAL*8, intent(in) :: x\n" "REAL*8, intent(in) :: y\n" "REAL*8, intent(in) :: z\n" "end function\n" "end interface\n") ] assert result == expected def test_multiple_results_f(): x, y, z = symbols('x,y,z') expr1 = (x + y)*z expr2 = (x - y)*z routine = make_routine( "test", [expr1, expr2] ) code_gen = FCodeGen() raises(CodeGenError, lambda: get_string(code_gen.dump_h, [routine])) def test_no_results_f(): raises(ValueError, lambda: make_routine("test", [])) def test_intrinsic_math_codegen(): # not included: log10 from sympy import (acos, asin, atan, cos, cosh, log, ln, sin, sinh, sqrt, tan, tanh, Abs) x = symbols('x') name_expr = [ ("test_abs", Abs(x)), ("test_acos", acos(x)), ("test_asin", asin(x)), ("test_atan", atan(x)), ("test_cos", cos(x)), ("test_cosh", cosh(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 def test_intrinsic_math2_codegen(): # not included: frexp, ldexp, modf, fmod from sympy import atan2 x, y = symbols('x,y') name_expr = [ ("test_atan2", atan2(x, y)), ("test_pow", x**y), ] result = codegen(name_expr, "F95", "file", header=False, empty=False) assert result[0][0] == "file.f90" expected = ( 'REAL*8 function test_atan2(x, y)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'REAL*8, intent(in) :: y\n' 'test_atan2 = atan2(x, y)\n' 'end function\n' 'REAL*8 function test_pow(x, y)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'REAL*8, intent(in) :: y\n' 'test_pow = x**y\n' 'end function\n' ) assert result[0][1] == expected assert result[1][0] == "file.h" expected = ( 'interface\n' 'REAL*8 function test_atan2(x, y)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'REAL*8, intent(in) :: y\n' 'end function\n' 'end interface\n' 'interface\n' 'REAL*8 function test_pow(x, y)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'REAL*8, intent(in) :: y\n' 'end function\n' 'end interface\n' ) assert result[1][1] == expected def test_complicated_codegen_f95(): from sympy import sin, cos, tan x, y, z = symbols('x,y,z') name_expr = [ ("test1", ((sin(x) + cos(y) + tan(z))**7).expand()), ("test2", cos(cos(cos(cos(cos(cos(cos(cos(x + y + z))))))))), ] result = codegen(name_expr, "F95", "file", header=False, empty=False) assert result[0][0] == "file.f90" expected = ( 'REAL*8 function test1(x, y, z)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'REAL*8, intent(in) :: y\n' 'REAL*8, intent(in) :: z\n' 'test1 = sin(x)**7 + 7*sin(x)**6*cos(y) + 7*sin(x)**6*tan(z) + 21*sin(x) &\n' ' **5*cos(y)**2 + 42*sin(x)**5*cos(y)*tan(z) + 21*sin(x)**5*tan(z) &\n' ' **2 + 35*sin(x)**4*cos(y)**3 + 105*sin(x)**4*cos(y)**2*tan(z) + &\n' ' 105*sin(x)**4*cos(y)*tan(z)**2 + 35*sin(x)**4*tan(z)**3 + 35*sin( &\n' ' x)**3*cos(y)**4 + 140*sin(x)**3*cos(y)**3*tan(z) + 210*sin(x)**3* &\n' ' cos(y)**2*tan(z)**2 + 140*sin(x)**3*cos(y)*tan(z)**3 + 35*sin(x) &\n' ' **3*tan(z)**4 + 21*sin(x)**2*cos(y)**5 + 105*sin(x)**2*cos(y)**4* &\n' ' tan(z) + 210*sin(x)**2*cos(y)**3*tan(z)**2 + 210*sin(x)**2*cos(y) &\n' ' **2*tan(z)**3 + 105*sin(x)**2*cos(y)*tan(z)**4 + 21*sin(x)**2*tan &\n' ' (z)**5 + 7*sin(x)*cos(y)**6 + 42*sin(x)*cos(y)**5*tan(z) + 105* &\n' ' sin(x)*cos(y)**4*tan(z)**2 + 140*sin(x)*cos(y)**3*tan(z)**3 + 105 &\n' ' *sin(x)*cos(y)**2*tan(z)**4 + 42*sin(x)*cos(y)*tan(z)**5 + 7*sin( &\n' ' x)*tan(z)**6 + cos(y)**7 + 7*cos(y)**6*tan(z) + 21*cos(y)**5*tan( &\n' ' z)**2 + 35*cos(y)**4*tan(z)**3 + 35*cos(y)**3*tan(z)**4 + 21*cos( &\n' ' y)**2*tan(z)**5 + 7*cos(y)*tan(z)**6 + tan(z)**7\n' 'end function\n' 'REAL*8 function test2(x, y, z)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'REAL*8, intent(in) :: y\n' 'REAL*8, intent(in) :: z\n' 'test2 = cos(cos(cos(cos(cos(cos(cos(cos(x + y + z))))))))\n' 'end function\n' ) assert result[0][1] == expected assert result[1][0] == "file.h" expected = ( 'interface\n' 'REAL*8 function test1(x, y, z)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'REAL*8, intent(in) :: y\n' 'REAL*8, intent(in) :: z\n' 'end function\n' 'end interface\n' 'interface\n' 'REAL*8 function test2(x, y, z)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'REAL*8, intent(in) :: y\n' 'REAL*8, intent(in) :: z\n' 'end function\n' 'end interface\n' ) assert result[1][1] == expected def test_loops(): from sympy.tensor import IndexedBase, Idx from sympy import symbols n, m = symbols('n,m', integer=True) A, x, y = map(IndexedBase, 'Axy') i = Idx('i', m) j = Idx('j', n) (f1, code), (f2, interface) = codegen( ('matrix_vector', Eq(y[i], A[i, j]*x[j])), "F95", "file", header=False, empty=False) assert f1 == 'file.f90' expected = ( 'subroutine matrix_vector(A, m, n, x, y)\n' 'implicit none\n' 'INTEGER*4, intent(in) :: m\n' 'INTEGER*4, intent(in) :: n\n' 'REAL*8, intent(in), dimension(1:m, 1:n) :: A\n' 'REAL*8, intent(in), dimension(1:n) :: x\n' 'REAL*8, intent(out), dimension(1:m) :: y\n' 'INTEGER*4 :: i\n' 'INTEGER*4 :: j\n' 'do i = 1, m\n' ' y(i) = 0\n' 'end do\n' 'do i = 1, m\n' ' do j = 1, n\n' ' y(i) = %(rhs)s + y(i)\n' ' end do\n' 'end do\n' 'end subroutine\n' ) assert code == expected % {'rhs': 'A(i, j)*x(j)'} or\ code == expected % {'rhs': 'x(j)*A(i, j)'} assert f2 == 'file.h' assert interface == ( 'interface\n' 'subroutine matrix_vector(A, m, n, x, y)\n' 'implicit none\n' 'INTEGER*4, intent(in) :: m\n' 'INTEGER*4, intent(in) :: n\n' 'REAL*8, intent(in), dimension(1:m, 1:n) :: A\n' 'REAL*8, intent(in), dimension(1:n) :: x\n' 'REAL*8, intent(out), dimension(1:m) :: y\n' 'end subroutine\n' 'end interface\n' ) def test_dummy_loops_f95(): from sympy.tensor import IndexedBase, Idx i, m = symbols('i m', integer=True, cls=Dummy) x = IndexedBase('x') y = IndexedBase('y') i = Idx(i, m) expected = ( 'subroutine test_dummies(m_%(mcount)i, x, y)\n' 'implicit none\n' 'INTEGER*4, intent(in) :: m_%(mcount)i\n' 'REAL*8, intent(in), dimension(1:m_%(mcount)i) :: x\n' 'REAL*8, intent(out), dimension(1:m_%(mcount)i) :: y\n' 'INTEGER*4 :: i_%(icount)i\n' 'do i_%(icount)i = 1, m_%(mcount)i\n' ' y(i_%(icount)i) = x(i_%(icount)i)\n' 'end do\n' 'end subroutine\n' ) % {'icount': i.label.dummy_index, 'mcount': m.dummy_index} r = make_routine('test_dummies', Eq(y[i], x[i])) c = FCodeGen() code = get_string(c.dump_f95, [r]) assert code == expected def test_loops_InOut(): from sympy.tensor import IndexedBase, Idx from sympy import symbols i, j, n, m = symbols('i,j,n,m', integer=True) A, x, y = symbols('A,x,y') A = IndexedBase(A)[Idx(i, m), Idx(j, n)] x = IndexedBase(x)[Idx(j, n)] y = IndexedBase(y)[Idx(i, m)] (f1, code), (f2, interface) = codegen( ('matrix_vector', Eq(y, y + A*x)), "F95", "file", header=False, empty=False) assert f1 == 'file.f90' expected = ( 'subroutine matrix_vector(A, m, n, x, y)\n' 'implicit none\n' 'INTEGER*4, intent(in) :: m\n' 'INTEGER*4, intent(in) :: n\n' 'REAL*8, intent(in), dimension(1:m, 1:n) :: A\n' 'REAL*8, intent(in), dimension(1:n) :: x\n' 'REAL*8, intent(inout), dimension(1:m) :: y\n' 'INTEGER*4 :: i\n' 'INTEGER*4 :: j\n' 'do i = 1, m\n' ' do j = 1, n\n' ' y(i) = %(rhs)s + y(i)\n' ' end do\n' 'end do\n' 'end subroutine\n' ) assert (code == expected % {'rhs': 'A(i, j)*x(j)'} or code == expected % {'rhs': 'x(j)*A(i, j)'}) assert f2 == 'file.h' assert interface == ( 'interface\n' 'subroutine matrix_vector(A, m, n, x, y)\n' 'implicit none\n' 'INTEGER*4, intent(in) :: m\n' 'INTEGER*4, intent(in) :: n\n' 'REAL*8, intent(in), dimension(1:m, 1:n) :: A\n' 'REAL*8, intent(in), dimension(1:n) :: x\n' 'REAL*8, intent(inout), dimension(1:m) :: y\n' 'end subroutine\n' 'end interface\n' ) def test_partial_loops_f(): # check that loop boundaries are determined by Idx, and array strides # determined by shape of IndexedBase object. from sympy.tensor import IndexedBase, Idx from sympy import symbols n, m, o, p = symbols('n m o p', integer=True) A = IndexedBase('A', shape=(m, p)) x = IndexedBase('x') y = IndexedBase('y') i = Idx('i', (o, m - 5)) # Note: bounds are inclusive j = Idx('j', n) # dimension n corresponds to bounds (0, n - 1) (f1, code), (f2, interface) = codegen( ('matrix_vector', Eq(y[i], A[i, j]*x[j])), "F95", "file", header=False, empty=False) expected = ( 'subroutine matrix_vector(A, m, n, o, p, x, y)\n' 'implicit none\n' 'INTEGER*4, intent(in) :: m\n' 'INTEGER*4, intent(in) :: n\n' 'INTEGER*4, intent(in) :: o\n' 'INTEGER*4, intent(in) :: p\n' 'REAL*8, intent(in), dimension(1:m, 1:p) :: A\n' 'REAL*8, intent(in), dimension(1:n) :: x\n' 'REAL*8, intent(out), dimension(1:%(iup-ilow)s) :: y\n' 'INTEGER*4 :: i\n' 'INTEGER*4 :: j\n' 'do i = %(ilow)s, %(iup)s\n' ' y(i) = 0\n' 'end do\n' 'do i = %(ilow)s, %(iup)s\n' ' do j = 1, n\n' ' y(i) = %(rhs)s + y(i)\n' ' end do\n' 'end do\n' 'end subroutine\n' ) % { 'rhs': '%(rhs)s', 'iup': str(m - 4), 'ilow': str(1 + o), 'iup-ilow': str(m - 4 - o) } assert code == expected % {'rhs': 'A(i, j)*x(j)'} or\ code == expected % {'rhs': 'x(j)*A(i, j)'} def test_output_arg_f(): from sympy import sin, cos, Equality x, y, z = symbols("x,y,z") r = make_routine("foo", [Equality(y, sin(x)), cos(x)]) c = FCodeGen() result = c.write([r], "test", header=False, empty=False) assert result[0][0] == "test.f90" assert result[0][1] == ( 'REAL*8 function foo(x, y)\n' 'implicit none\n' 'REAL*8, intent(in) :: x\n' 'REAL*8, intent(out) :: y\n' 'y = sin(x)\n' 'foo = cos(x)\n' 'end function\n' ) def test_inline_function(): from sympy.tensor import IndexedBase, Idx from sympy import symbols n, m = symbols('n m', integer=True) A, x, y = map(IndexedBase, 'Axy') i = Idx('i', m) p = FCodeGen() func = implemented_function('func', Lambda(n, n*(n + 1))) routine = make_routine('test_inline', Eq(y[i], func(x[i]))) code = get_string(p.dump_f95, [routine]) expected = ( 'subroutine test_inline(m, x, y)\n' 'implicit none\n' 'INTEGER*4, intent(in) :: m\n' 'REAL*8, intent(in), dimension(1:m) :: x\n' 'REAL*8, intent(out), dimension(1:m) :: y\n' 'INTEGER*4 :: i\n' 'do i = 1, m\n' ' y(i) = %s*%s\n' 'end do\n' 'end subroutine\n' ) args = ('x(i)', '(x(i) + 1)') assert code == expected % args or\ code == expected % args[::-1] def test_f_code_call_signature_wrap(): # Issue #7934 x = symbols('x:20') expr = 0 for sym in x: expr += sym routine = make_routine("test", expr) code_gen = FCodeGen() source = get_string(code_gen.dump_f95, [routine]) expected = """\ REAL*8 function test(x0, x1, x10, x11, x12, x13, x14, x15, x16, x17, x18, & x19, x2, x3, x4, x5, x6, x7, x8, x9) implicit none REAL*8, intent(in) :: x0 REAL*8, intent(in) :: x1 REAL*8, intent(in) :: x10 REAL*8, intent(in) :: x11 REAL*8, intent(in) :: x12 REAL*8, intent(in) :: x13 REAL*8, intent(in) :: x14 REAL*8, intent(in) :: x15 REAL*8, intent(in) :: x16 REAL*8, intent(in) :: x17 REAL*8, intent(in) :: x18 REAL*8, intent(in) :: x19 REAL*8, intent(in) :: x2 REAL*8, intent(in) :: x3 REAL*8, intent(in) :: x4 REAL*8, intent(in) :: x5 REAL*8, intent(in) :: x6 REAL*8, intent(in) :: x7 REAL*8, intent(in) :: x8 REAL*8, intent(in) :: x9 test = x0 + x1 + x10 + x11 + x12 + x13 + x14 + x15 + x16 + x17 + x18 + & x19 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9 end function """ assert source == expected def test_check_case(): x, X = symbols('x,X') raises(CodeGenError, lambda: codegen(('test', x*X), 'f95', 'prefix')) 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!") def test_c_fortran_omit_routine_name(): x, y = symbols("x,y") name_expr = [("foo", 2*x)] result = codegen(name_expr, "F95", header=False, empty=False) expresult = codegen(name_expr, "F95", "foo", header=False, empty=False) assert result[0][1] == expresult[0][1] name_expr = ("foo", x*y) result = codegen(name_expr, "F95", header=False, empty=False) expresult = codegen(name_expr, "F95", "foo", header=False, empty=False) assert result[0][1] == expresult[0][1] name_expr = ("foo", Matrix([[x, y], [x+y, x-y]])) result = codegen(name_expr, "C89", header=False, empty=False) expresult = codegen(name_expr, "C89", "foo", header=False, empty=False) assert result[0][1] == expresult[0][1] def test_fcode_matrix_output(): x, y, z = symbols('x,y,z') e1 = x + y e2 = Matrix([[x, y], [z, 16]]) name_expr = ("test", (e1, e2)) result = codegen(name_expr, "f95", "test", header=False, empty=False) source = result[0][1] expected = ( "REAL*8 function test(x, y, z, out_%(hash)s)\n" "implicit none\n" "REAL*8, intent(in) :: x\n" "REAL*8, intent(in) :: y\n" "REAL*8, intent(in) :: z\n" "REAL*8, intent(out), dimension(1:2, 1:2) :: out_%(hash)s\n" "out_%(hash)s(1, 1) = x\n" "out_%(hash)s(2, 1) = z\n" "out_%(hash)s(1, 2) = y\n" "out_%(hash)s(2, 2) = 16\n" "test = x + y\n" "end function\n" ) # look for the magic number a = source.splitlines()[5] b = a.split('_') out = b[1] expected = expected % {'hash': out} assert source == expected 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 def test_fcode_matrixsymbol_slice(): A = MatrixSymbol('A', 2, 3) B = MatrixSymbol('B', 1, 3) C = MatrixSymbol('C', 1, 3) D = MatrixSymbol('D', 2, 1) name_expr = ("test", [Equality(B, A[0, :]), Equality(C, A[1, :]), Equality(D, A[:, 2])]) result = codegen(name_expr, "f95", "test", header=False, empty=False) source = result[0][1] expected = ( "subroutine test(A, B, C, D)\n" "implicit none\n" "REAL*8, intent(in), dimension(1:2, 1:3) :: A\n" "REAL*8, intent(out), dimension(1:1, 1:3) :: B\n" "REAL*8, intent(out), dimension(1:1, 1:3) :: C\n" "REAL*8, intent(out), dimension(1:2, 1:1) :: D\n" "B(1, 1) = A(1, 1)\n" "B(1, 2) = A(1, 2)\n" "B(1, 3) = A(1, 3)\n" "C(1, 1) = A(2, 1)\n" "C(1, 2) = A(2, 2)\n" "C(1, 3) = A(2, 3)\n" "D(1, 1) = A(1, 3)\n" "D(2, 1) = A(2, 3)\n" "end subroutine\n" ) assert source == expected def test_fcode_matrixsymbol_slice_autoname(): # see issue #8093 A = MatrixSymbol('A', 2, 3) name_expr = ("test", A[:, 1]) result = codegen(name_expr, "f95", "test", header=False, empty=False) source = result[0][1] expected = ( "subroutine test(A, out_%(hash)s)\n" "implicit none\n" "REAL*8, intent(in), dimension(1:2, 1:3) :: A\n" "REAL*8, intent(out), dimension(1:2, 1:1) :: out_%(hash)s\n" "out_%(hash)s(1, 1) = A(1, 2)\n" "out_%(hash)s(2, 1) = A(2, 2)\n" "end subroutine\n" ) # look for the magic number a = source.splitlines()[3] b = a.split('_') out = b[1] expected = expected % {'hash': out} assert source == expected def test_global_vars(): x, y, z, t = symbols("x y z t") result = codegen(('f', x*y), "F95", header=False, empty=False, global_vars=(y,)) source = result[0][1] expected = ( "REAL*8 function f(x)\n" "implicit none\n" "REAL*8, intent(in) :: x\n" "f = x*y\n" "end function\n" ) assert source == expected expected = ( '#include "f.h"\n' '#include <math.h>\n' 'double f(double x, double y) {\n' ' double f_result;\n' ' f_result = x*y + z;\n' ' return f_result;\n' '}\n' ) result = codegen(('f', x*y+z), "C", header=False, empty=False, global_vars=(z, t)) source = result[0][1] assert source == expected def test_custom_codegen(): from sympy.printing.ccode import C99CodePrinter from sympy.functions.elementary.exponential import exp printer = C99CodePrinter(settings={'user_functions': {'exp': 'fastexp'}}) x, y = symbols('x y') expr = exp(x + y) # replace math.h with a different header gen = C99CodeGen(printer=printer, preprocessor_statements=['#include "fastexp.h"']) expected = ( '#include "expr.h"\n' '#include "fastexp.h"\n' 'double expr(double x, double y) {\n' ' double expr_result;\n' ' expr_result = fastexp(x + y);\n' ' return expr_result;\n' '}\n' ) result = codegen(('expr', expr), header=False, empty=False, code_gen=gen) source = result[0][1] assert source == expected # use both math.h and an external header gen = C99CodeGen(printer=printer) gen.preprocessor_statements.append('#include "fastexp.h"') expected = ( '#include "expr.h"\n' '#include <math.h>\n' '#include "fastexp.h"\n' 'double expr(double x, double y) {\n' ' double expr_result;\n' ' expr_result = fastexp(x + y);\n' ' return expr_result;\n' '}\n' ) result = codegen(('expr', expr), header=False, empty=False, code_gen=gen) source = result[0][1] assert source == expected def test_c_with_printer(): #issue 13586 from sympy.printing.ccode import C99CodePrinter class CustomPrinter(C99CodePrinter): def _print_Pow(self, expr): return "fastpow({}, {})".format(self._print(expr.base), self._print(expr.exp)) x = symbols('x') expr = x**3 expected =[ ("file.c", "#include \"file.h\"\n" "#include <math.h>\n" "double test(double x) {\n" " double test_result;\n" " test_result = fastpow(x, 3);\n" " return test_result;\n" "}\n"), ("file.h", "#ifndef PROJECT__FILE__H\n" "#define PROJECT__FILE__H\n" "double test(double x);\n" "#endif\n") ] result = codegen(("test", expr), "C","file", header=False, empty=False, printer = CustomPrinter()) assert result == expected def test_fcode_complex(): import sympy.utilities.codegen sympy.utilities.codegen.COMPLEX_ALLOWED = True x = Symbol('x', real=True) y = Symbol('y',real=True) result = codegen(('test',x+y), 'f95', 'test', header=False, empty=False) source = (result[0][1]) expected = ( "REAL*8 function test(x, y)\n" "implicit none\n" "REAL*8, intent(in) :: x\n" "REAL*8, intent(in) :: y\n" "test = x + y\n" "end function\n") assert source == expected x = Symbol('x') y = Symbol('y',real=True) result = codegen(('test',x+y), 'f95', 'test', header=False, empty=False) source = (result[0][1]) expected = ( "COMPLEX*16 function test(x, y)\n" "implicit none\n" "COMPLEX*16, intent(in) :: x\n" "REAL*8, intent(in) :: y\n" "test = x + y\n" "end function\n" ) assert source==expected sympy.utilities.codegen.COMPLEX_ALLOWED = False
f27d9edc09964f9519a5354d437e31c55c1e7866bbebb2e8f9b3b0b0519375b4
from __future__ import absolute_import import shutil from sympy.external import import_module from sympy.testing.pytest import skip from sympy.utilities._compilation.compilation import compile_link_import_strings numpy = import_module('numpy') cython = import_module('cython') _sources1 = [ ('sigmoid.c', r""" #include <math.h> void sigmoid(int n, const double * const restrict in, double * const restrict out, double lim){ for (int i=0; i<n; ++i){ const double x = in[i]; out[i] = x*pow(pow(x/lim, 8)+1, -1./8.); } } """), ('_sigmoid.pyx', r""" import numpy as np cimport numpy as cnp cdef extern void c_sigmoid "sigmoid" (int, const double * const, double * const, double) def sigmoid(double [:] inp, double lim=350.0): cdef cnp.ndarray[cnp.float64_t, ndim=1] out = np.empty( inp.size, dtype=np.float64) c_sigmoid(inp.size, &inp[0], &out[0], lim) return out """) ] def npy(data, lim=350.0): return data/((data/lim)**8+1)**(1/8.) def test_compile_link_import_strings(): if not numpy: skip("numpy not installed.") if not cython: skip("cython not installed.") from sympy.utilities._compilation import has_c if not has_c(): skip("No C compiler found.") compile_kw = dict(std='c99', include_dirs=[numpy.get_include()]) info = None try: mod, info = compile_link_import_strings(_sources1, compile_kwargs=compile_kw) data = numpy.random.random(1024*1024*8) # 64 MB of RAM needed.. res_mod = mod.sigmoid(data) res_npy = npy(data) assert numpy.allclose(res_mod, res_npy) finally: if info and info['build_dir']: shutil.rmtree(info['build_dir'])
3c8b0e7aa0d1313b0ae6fe77ac2d86a4c4266cd6ceead95abb6709906d37ac8f
from __future__ import print_function, division import itertools from sympy.core import S from sympy.core.containers import Tuple from sympy.core.function import _coeff_isneg from sympy.core.mul import Mul from sympy.core.numbers import Rational from sympy.core.power import Pow from sympy.core.symbol import Symbol from sympy.core.sympify import SympifyError from sympy.printing.conventions import requires_partial from sympy.printing.precedence import PRECEDENCE, precedence, precedence_traditional from sympy.printing.printer import Printer from sympy.printing.str import sstr from sympy.utilities import default_sort_key from sympy.utilities.iterables import has_variety from sympy.utilities.exceptions import SymPyDeprecationWarning from sympy.printing.pretty.stringpict import prettyForm, stringPict from sympy.printing.pretty.pretty_symbology import xstr, hobj, vobj, xobj, \ xsym, pretty_symbol, pretty_atom, pretty_use_unicode, greek_unicode, U, \ pretty_try_use_unicode, annotated # rename for usage from outside pprint_use_unicode = pretty_use_unicode pprint_try_use_unicode = pretty_try_use_unicode class PrettyPrinter(Printer): """Printer, which converts an expression into 2D ASCII-art figure.""" printmethod = "_pretty" _default_settings = { "order": None, "full_prec": "auto", "use_unicode": None, "wrap_line": True, "num_columns": None, "use_unicode_sqrt_char": True, "root_notation": True, "mat_symbol_style": "plain", "imaginary_unit": "i", "perm_cyclic": True } def __init__(self, settings=None): Printer.__init__(self, settings) if not isinstance(self._settings['imaginary_unit'], str): raise TypeError("'imaginary_unit' must a string, not {}".format(self._settings['imaginary_unit'])) elif self._settings['imaginary_unit'] not in ["i", "j"]: raise ValueError("'imaginary_unit' must be either 'i' or 'j', not '{}'".format(self._settings['imaginary_unit'])) self.emptyPrinter = lambda x: prettyForm(xstr(x)) @property def _use_unicode(self): if self._settings['use_unicode']: return True else: return pretty_use_unicode() def doprint(self, expr): return self._print(expr).render(**self._settings) # empty op so _print(stringPict) returns the same def _print_stringPict(self, e): return e def _print_basestring(self, e): return prettyForm(e) def _print_atan2(self, e): pform = prettyForm(*self._print_seq(e.args).parens()) pform = prettyForm(*pform.left('atan2')) return pform def _print_Symbol(self, e, bold_name=False): symb = pretty_symbol(e.name, bold_name) return prettyForm(symb) _print_RandomSymbol = _print_Symbol def _print_MatrixSymbol(self, e): return self._print_Symbol(e, self._settings['mat_symbol_style'] == "bold") def _print_Float(self, e): # we will use StrPrinter's Float printer, but we need to handle the # full_prec ourselves, according to the self._print_level full_prec = self._settings["full_prec"] if full_prec == "auto": full_prec = self._print_level == 1 return prettyForm(sstr(e, full_prec=full_prec)) def _print_Cross(self, e): vec1 = e._expr1 vec2 = e._expr2 pform = self._print(vec2) pform = prettyForm(*pform.left('(')) pform = prettyForm(*pform.right(')')) pform = prettyForm(*pform.left(self._print(U('MULTIPLICATION SIGN')))) pform = prettyForm(*pform.left(')')) pform = prettyForm(*pform.left(self._print(vec1))) pform = prettyForm(*pform.left('(')) return pform def _print_Curl(self, e): vec = e._expr pform = self._print(vec) pform = prettyForm(*pform.left('(')) pform = prettyForm(*pform.right(')')) pform = prettyForm(*pform.left(self._print(U('MULTIPLICATION SIGN')))) pform = prettyForm(*pform.left(self._print(U('NABLA')))) return pform def _print_Divergence(self, e): vec = e._expr pform = self._print(vec) pform = prettyForm(*pform.left('(')) pform = prettyForm(*pform.right(')')) pform = prettyForm(*pform.left(self._print(U('DOT OPERATOR')))) pform = prettyForm(*pform.left(self._print(U('NABLA')))) return pform def _print_Dot(self, e): vec1 = e._expr1 vec2 = e._expr2 pform = self._print(vec2) pform = prettyForm(*pform.left('(')) pform = prettyForm(*pform.right(')')) pform = prettyForm(*pform.left(self._print(U('DOT OPERATOR')))) pform = prettyForm(*pform.left(')')) pform = prettyForm(*pform.left(self._print(vec1))) pform = prettyForm(*pform.left('(')) return pform def _print_Gradient(self, e): func = e._expr pform = self._print(func) pform = prettyForm(*pform.left('(')) pform = prettyForm(*pform.right(')')) pform = prettyForm(*pform.left(self._print(U('NABLA')))) return pform def _print_Laplacian(self, e): func = e._expr pform = self._print(func) pform = prettyForm(*pform.left('(')) pform = prettyForm(*pform.right(')')) pform = prettyForm(*pform.left(self._print(U('INCREMENT')))) return pform def _print_Atom(self, e): try: # print atoms like Exp1 or Pi return prettyForm(pretty_atom(e.__class__.__name__, printer=self)) except KeyError: return self.emptyPrinter(e) # Infinity inherits from Number, so we have to override _print_XXX order _print_Infinity = _print_Atom _print_NegativeInfinity = _print_Atom _print_EmptySet = _print_Atom _print_Naturals = _print_Atom _print_Naturals0 = _print_Atom _print_Integers = _print_Atom _print_Rationals = _print_Atom _print_Complexes = _print_Atom _print_EmptySequence = _print_Atom def _print_Reals(self, e): if self._use_unicode: return self._print_Atom(e) else: inf_list = ['-oo', 'oo'] return self._print_seq(inf_list, '(', ')') def _print_subfactorial(self, e): x = e.args[0] pform = self._print(x) # Add parentheses if needed if not ((x.is_Integer and x.is_nonnegative) or x.is_Symbol): pform = prettyForm(*pform.parens()) pform = prettyForm(*pform.left('!')) return pform def _print_factorial(self, e): x = e.args[0] pform = self._print(x) # Add parentheses if needed if not ((x.is_Integer and x.is_nonnegative) or x.is_Symbol): pform = prettyForm(*pform.parens()) pform = prettyForm(*pform.right('!')) return pform def _print_factorial2(self, e): x = e.args[0] pform = self._print(x) # Add parentheses if needed if not ((x.is_Integer and x.is_nonnegative) or x.is_Symbol): pform = prettyForm(*pform.parens()) pform = prettyForm(*pform.right('!!')) return pform def _print_binomial(self, e): n, k = e.args n_pform = self._print(n) k_pform = self._print(k) bar = ' '*max(n_pform.width(), k_pform.width()) pform = prettyForm(*k_pform.above(bar)) pform = prettyForm(*pform.above(n_pform)) pform = prettyForm(*pform.parens('(', ')')) pform.baseline = (pform.baseline + 1)//2 return pform def _print_Relational(self, e): op = prettyForm(' ' + xsym(e.rel_op) + ' ') l = self._print(e.lhs) r = self._print(e.rhs) pform = prettyForm(*stringPict.next(l, op, r)) return pform def _print_Not(self, e): from sympy import Equivalent, Implies if self._use_unicode: arg = e.args[0] pform = self._print(arg) if isinstance(arg, Equivalent): return self._print_Equivalent(arg, altchar=u"\N{LEFT RIGHT DOUBLE ARROW WITH STROKE}") if isinstance(arg, Implies): return self._print_Implies(arg, altchar=u"\N{RIGHTWARDS ARROW WITH STROKE}") if arg.is_Boolean and not arg.is_Not: pform = prettyForm(*pform.parens()) return prettyForm(*pform.left(u"\N{NOT SIGN}")) else: return self._print_Function(e) def __print_Boolean(self, e, char, sort=True): args = e.args if sort: args = sorted(e.args, key=default_sort_key) arg = args[0] pform = self._print(arg) if arg.is_Boolean and not arg.is_Not: pform = prettyForm(*pform.parens()) for arg in args[1:]: pform_arg = self._print(arg) if arg.is_Boolean and not arg.is_Not: pform_arg = prettyForm(*pform_arg.parens()) pform = prettyForm(*pform.right(u' %s ' % char)) pform = prettyForm(*pform.right(pform_arg)) return pform def _print_And(self, e): if self._use_unicode: return self.__print_Boolean(e, u"\N{LOGICAL AND}") else: return self._print_Function(e, sort=True) def _print_Or(self, e): if self._use_unicode: return self.__print_Boolean(e, u"\N{LOGICAL OR}") else: return self._print_Function(e, sort=True) def _print_Xor(self, e): if self._use_unicode: return self.__print_Boolean(e, u"\N{XOR}") else: return self._print_Function(e, sort=True) def _print_Nand(self, e): if self._use_unicode: return self.__print_Boolean(e, u"\N{NAND}") else: return self._print_Function(e, sort=True) def _print_Nor(self, e): if self._use_unicode: return self.__print_Boolean(e, u"\N{NOR}") else: return self._print_Function(e, sort=True) def _print_Implies(self, e, altchar=None): if self._use_unicode: return self.__print_Boolean(e, altchar or u"\N{RIGHTWARDS ARROW}", sort=False) else: return self._print_Function(e) def _print_Equivalent(self, e, altchar=None): if self._use_unicode: return self.__print_Boolean(e, altchar or u"\N{LEFT RIGHT DOUBLE ARROW}") else: return self._print_Function(e, sort=True) def _print_conjugate(self, e): pform = self._print(e.args[0]) return prettyForm( *pform.above( hobj('_', pform.width())) ) def _print_Abs(self, e): pform = self._print(e.args[0]) pform = prettyForm(*pform.parens('|', '|')) return pform _print_Determinant = _print_Abs def _print_floor(self, e): if self._use_unicode: pform = self._print(e.args[0]) pform = prettyForm(*pform.parens('lfloor', 'rfloor')) return pform else: return self._print_Function(e) def _print_ceiling(self, e): if self._use_unicode: pform = self._print(e.args[0]) pform = prettyForm(*pform.parens('lceil', 'rceil')) return pform else: return self._print_Function(e) def _print_Derivative(self, deriv): if requires_partial(deriv.expr) and self._use_unicode: deriv_symbol = U('PARTIAL DIFFERENTIAL') else: deriv_symbol = r'd' x = None count_total_deriv = 0 for sym, num in reversed(deriv.variable_count): s = self._print(sym) ds = prettyForm(*s.left(deriv_symbol)) count_total_deriv += num if (not num.is_Integer) or (num > 1): ds = ds**prettyForm(str(num)) if x is None: x = ds else: x = prettyForm(*x.right(' ')) x = prettyForm(*x.right(ds)) f = prettyForm( binding=prettyForm.FUNC, *self._print(deriv.expr).parens()) pform = prettyForm(deriv_symbol) if (count_total_deriv > 1) != False: pform = pform**prettyForm(str(count_total_deriv)) pform = prettyForm(*pform.below(stringPict.LINE, x)) pform.baseline = pform.baseline + 1 pform = prettyForm(*stringPict.next(pform, f)) pform.binding = prettyForm.MUL return pform def _print_Cycle(self, dc): from sympy.combinatorics.permutations import Permutation, Cycle # for Empty Cycle if dc == Cycle(): cyc = stringPict('') return prettyForm(*cyc.parens()) dc_list = Permutation(dc.list()).cyclic_form # for Identity Cycle if dc_list == []: cyc = self._print(dc.size - 1) return prettyForm(*cyc.parens()) cyc = stringPict('') for i in dc_list: l = self._print(str(tuple(i)).replace(',', '')) cyc = prettyForm(*cyc.right(l)) return cyc def _print_Permutation(self, expr): from sympy.combinatorics.permutations import Permutation, Cycle perm_cyclic = Permutation.print_cyclic if perm_cyclic is not None: SymPyDeprecationWarning( feature="Permutation.print_cyclic = {}".format(perm_cyclic), useinstead="init_printing(perm_cyclic={})" .format(perm_cyclic), issue=15201, deprecated_since_version="1.6").warn() else: perm_cyclic = self._settings.get("perm_cyclic", True) if perm_cyclic: return self._print_Cycle(Cycle(expr)) lower = expr.array_form upper = list(range(len(lower))) result = stringPict('') first = True for u, l in zip(upper, lower): s1 = self._print(u) s2 = self._print(l) col = prettyForm(*s1.below(s2)) if first: first = False else: col = prettyForm(*col.left(" ")) result = prettyForm(*result.right(col)) return prettyForm(*result.parens()) def _print_Integral(self, integral): f = integral.function # Add parentheses if arg involves addition of terms and # create a pretty form for the argument prettyF = self._print(f) # XXX generalize parens if f.is_Add: prettyF = prettyForm(*prettyF.parens()) # dx dy dz ... arg = prettyF for x in integral.limits: prettyArg = self._print(x[0]) # XXX qparens (parens if needs-parens) if prettyArg.width() > 1: prettyArg = prettyForm(*prettyArg.parens()) arg = prettyForm(*arg.right(' d', prettyArg)) # \int \int \int ... firstterm = True s = None for lim in integral.limits: x = lim[0] # Create bar based on the height of the argument h = arg.height() H = h + 2 # XXX hack! ascii_mode = not self._use_unicode if ascii_mode: H += 2 vint = vobj('int', H) # Construct the pretty form with the integral sign and the argument pform = prettyForm(vint) pform.baseline = arg.baseline + ( H - h)//2 # covering the whole argument if len(lim) > 1: # Create pretty forms for endpoints, if definite integral. # Do not print empty endpoints. if len(lim) == 2: prettyA = prettyForm("") prettyB = self._print(lim[1]) if len(lim) == 3: prettyA = self._print(lim[1]) prettyB = self._print(lim[2]) if ascii_mode: # XXX hack # Add spacing so that endpoint can more easily be # identified with the correct integral sign spc = max(1, 3 - prettyB.width()) prettyB = prettyForm(*prettyB.left(' ' * spc)) spc = max(1, 4 - prettyA.width()) prettyA = prettyForm(*prettyA.right(' ' * spc)) pform = prettyForm(*pform.above(prettyB)) pform = prettyForm(*pform.below(prettyA)) if not ascii_mode: # XXX hack pform = prettyForm(*pform.right(' ')) if firstterm: s = pform # first term firstterm = False else: s = prettyForm(*s.left(pform)) pform = prettyForm(*arg.left(s)) pform.binding = prettyForm.MUL return pform def _print_Product(self, expr): func = expr.term pretty_func = self._print(func) horizontal_chr = xobj('_', 1) corner_chr = xobj('_', 1) vertical_chr = xobj('|', 1) if self._use_unicode: # use unicode corners horizontal_chr = xobj('-', 1) corner_chr = u'\N{BOX DRAWINGS LIGHT DOWN AND HORIZONTAL}' func_height = pretty_func.height() first = True max_upper = 0 sign_height = 0 for lim in expr.limits: pretty_lower, pretty_upper = self.__print_SumProduct_Limits(lim) width = (func_height + 2) * 5 // 3 - 2 sign_lines = [horizontal_chr + corner_chr + (horizontal_chr * (width-2)) + corner_chr + horizontal_chr] for _ in range(func_height + 1): sign_lines.append(' ' + vertical_chr + (' ' * (width-2)) + vertical_chr + ' ') pretty_sign = stringPict('') pretty_sign = prettyForm(*pretty_sign.stack(*sign_lines)) max_upper = max(max_upper, pretty_upper.height()) if first: sign_height = pretty_sign.height() pretty_sign = prettyForm(*pretty_sign.above(pretty_upper)) pretty_sign = prettyForm(*pretty_sign.below(pretty_lower)) if first: pretty_func.baseline = 0 first = False height = pretty_sign.height() padding = stringPict('') padding = prettyForm(*padding.stack(*[' ']*(height - 1))) pretty_sign = prettyForm(*pretty_sign.right(padding)) pretty_func = prettyForm(*pretty_sign.right(pretty_func)) pretty_func.baseline = max_upper + sign_height//2 pretty_func.binding = prettyForm.MUL return pretty_func def __print_SumProduct_Limits(self, lim): def print_start(lhs, rhs): op = prettyForm(' ' + xsym("==") + ' ') l = self._print(lhs) r = self._print(rhs) pform = prettyForm(*stringPict.next(l, op, r)) return pform prettyUpper = self._print(lim[2]) prettyLower = print_start(lim[0], lim[1]) return prettyLower, prettyUpper def _print_Sum(self, expr): ascii_mode = not self._use_unicode def asum(hrequired, lower, upper, use_ascii): def adjust(s, wid=None, how='<^>'): if not wid or len(s) > wid: return s need = wid - len(s) if how == '<^>' or how == "<" or how not in list('<^>'): return s + ' '*need half = need//2 lead = ' '*half if how == ">": return " "*need + s return lead + s + ' '*(need - len(lead)) h = max(hrequired, 2) d = h//2 w = d + 1 more = hrequired % 2 lines = [] if use_ascii: lines.append("_"*(w) + ' ') lines.append(r"\%s`" % (' '*(w - 1))) for i in range(1, d): lines.append('%s\\%s' % (' '*i, ' '*(w - i))) if more: lines.append('%s)%s' % (' '*(d), ' '*(w - d))) for i in reversed(range(1, d)): lines.append('%s/%s' % (' '*i, ' '*(w - i))) lines.append("/" + "_"*(w - 1) + ',') return d, h + more, lines, more else: w = w + more d = d + more vsum = vobj('sum', 4) lines.append("_"*(w)) for i in range(0, d): lines.append('%s%s%s' % (' '*i, vsum[2], ' '*(w - i - 1))) for i in reversed(range(0, d)): lines.append('%s%s%s' % (' '*i, vsum[4], ' '*(w - i - 1))) lines.append(vsum[8]*(w)) return d, h + 2*more, lines, more f = expr.function prettyF = self._print(f) if f.is_Add: # add parens prettyF = prettyForm(*prettyF.parens()) H = prettyF.height() + 2 # \sum \sum \sum ... first = True max_upper = 0 sign_height = 0 for lim in expr.limits: prettyLower, prettyUpper = self.__print_SumProduct_Limits(lim) max_upper = max(max_upper, prettyUpper.height()) # Create sum sign based on the height of the argument d, h, slines, adjustment = asum( H, prettyLower.width(), prettyUpper.width(), ascii_mode) prettySign = stringPict('') prettySign = prettyForm(*prettySign.stack(*slines)) if first: sign_height = prettySign.height() prettySign = prettyForm(*prettySign.above(prettyUpper)) prettySign = prettyForm(*prettySign.below(prettyLower)) if first: # change F baseline so it centers on the sign prettyF.baseline -= d - (prettyF.height()//2 - prettyF.baseline) first = False # put padding to the right pad = stringPict('') pad = prettyForm(*pad.stack(*[' ']*h)) prettySign = prettyForm(*prettySign.right(pad)) # put the present prettyF to the right prettyF = prettyForm(*prettySign.right(prettyF)) # adjust baseline of ascii mode sigma with an odd height so that it is # exactly through the center ascii_adjustment = ascii_mode if not adjustment else 0 prettyF.baseline = max_upper + sign_height//2 + ascii_adjustment prettyF.binding = prettyForm.MUL return prettyF def _print_Limit(self, l): e, z, z0, dir = l.args E = self._print(e) if precedence(e) <= PRECEDENCE["Mul"]: E = prettyForm(*E.parens('(', ')')) Lim = prettyForm('lim') LimArg = self._print(z) if self._use_unicode: LimArg = prettyForm(*LimArg.right(u'\N{BOX DRAWINGS LIGHT HORIZONTAL}\N{RIGHTWARDS ARROW}')) else: LimArg = prettyForm(*LimArg.right('->')) LimArg = prettyForm(*LimArg.right(self._print(z0))) if str(dir) == '+-' or z0 in (S.Infinity, S.NegativeInfinity): dir = "" else: if self._use_unicode: dir = u'\N{SUPERSCRIPT PLUS SIGN}' if str(dir) == "+" else u'\N{SUPERSCRIPT MINUS}' LimArg = prettyForm(*LimArg.right(self._print(dir))) Lim = prettyForm(*Lim.below(LimArg)) Lim = prettyForm(*Lim.right(E), binding=prettyForm.MUL) return Lim def _print_matrix_contents(self, e): """ This method factors out what is essentially grid printing. """ M = e # matrix Ms = {} # i,j -> pretty(M[i,j]) for i in range(M.rows): for j in range(M.cols): Ms[i, j] = self._print(M[i, j]) # h- and v- spacers hsep = 2 vsep = 1 # max width for columns maxw = [-1] * M.cols for j in range(M.cols): maxw[j] = max([Ms[i, j].width() for i in range(M.rows)] or [0]) # drawing result D = None for i in range(M.rows): D_row = None for j in range(M.cols): s = Ms[i, j] # reshape s to maxw # XXX this should be generalized, and go to stringPict.reshape ? assert s.width() <= maxw[j] # hcenter it, +0.5 to the right 2 # ( it's better to align formula starts for say 0 and r ) # XXX this is not good in all cases -- maybe introduce vbaseline? wdelta = maxw[j] - s.width() wleft = wdelta // 2 wright = wdelta - wleft s = prettyForm(*s.right(' '*wright)) s = prettyForm(*s.left(' '*wleft)) # we don't need vcenter cells -- this is automatically done in # a pretty way because when their baselines are taking into # account in .right() if D_row is None: D_row = s # first box in a row continue D_row = prettyForm(*D_row.right(' '*hsep)) # h-spacer D_row = prettyForm(*D_row.right(s)) if D is None: D = D_row # first row in a picture continue # v-spacer for _ in range(vsep): D = prettyForm(*D.below(' ')) D = prettyForm(*D.below(D_row)) if D is None: D = prettyForm('') # Empty Matrix return D def _print_MatrixBase(self, e): D = self._print_matrix_contents(e) D.baseline = D.height()//2 D = prettyForm(*D.parens('[', ']')) return D _print_ImmutableMatrix = _print_MatrixBase _print_Matrix = _print_MatrixBase def _print_TensorProduct(self, expr): # This should somehow share the code with _print_WedgeProduct: circled_times = "\u2297" return self._print_seq(expr.args, None, None, circled_times, parenthesize=lambda x: precedence_traditional(x) <= PRECEDENCE["Mul"]) def _print_WedgeProduct(self, expr): # This should somehow share the code with _print_TensorProduct: wedge_symbol = u"\u2227" return self._print_seq(expr.args, None, None, wedge_symbol, parenthesize=lambda x: precedence_traditional(x) <= PRECEDENCE["Mul"]) def _print_Trace(self, e): D = self._print(e.arg) D = prettyForm(*D.parens('(',')')) D.baseline = D.height()//2 D = prettyForm(*D.left('\n'*(0) + 'tr')) return D def _print_MatrixElement(self, expr): from sympy.matrices import MatrixSymbol from sympy import Symbol if (isinstance(expr.parent, MatrixSymbol) and expr.i.is_number and expr.j.is_number): return self._print( Symbol(expr.parent.name + '_%d%d' % (expr.i, expr.j))) else: prettyFunc = self._print(expr.parent) prettyFunc = prettyForm(*prettyFunc.parens()) prettyIndices = self._print_seq((expr.i, expr.j), delimiter=', ' ).parens(left='[', right=']')[0] pform = prettyForm(binding=prettyForm.FUNC, *stringPict.next(prettyFunc, prettyIndices)) # store pform parts so it can be reassembled e.g. when powered pform.prettyFunc = prettyFunc pform.prettyArgs = prettyIndices return pform def _print_MatrixSlice(self, m): # XXX works only for applied functions prettyFunc = self._print(m.parent) def ppslice(x): x = list(x) if x[2] == 1: del x[2] if x[1] == x[0] + 1: del x[1] if x[0] == 0: x[0] = '' return prettyForm(*self._print_seq(x, delimiter=':')) prettyArgs = self._print_seq((ppslice(m.rowslice), ppslice(m.colslice)), delimiter=', ').parens(left='[', right=']')[0] pform = prettyForm( binding=prettyForm.FUNC, *stringPict.next(prettyFunc, prettyArgs)) # store pform parts so it can be reassembled e.g. when powered pform.prettyFunc = prettyFunc pform.prettyArgs = prettyArgs return pform def _print_Transpose(self, expr): pform = self._print(expr.arg) from sympy.matrices import MatrixSymbol if not isinstance(expr.arg, MatrixSymbol): pform = prettyForm(*pform.parens()) pform = pform**(prettyForm('T')) return pform def _print_Adjoint(self, expr): pform = self._print(expr.arg) if self._use_unicode: dag = prettyForm(u'\N{DAGGER}') else: dag = prettyForm('+') from sympy.matrices import MatrixSymbol if not isinstance(expr.arg, MatrixSymbol): pform = prettyForm(*pform.parens()) pform = pform**dag return pform def _print_BlockMatrix(self, B): if B.blocks.shape == (1, 1): return self._print(B.blocks[0, 0]) return self._print(B.blocks) def _print_MatAdd(self, expr): s = None for item in expr.args: pform = self._print(item) if s is None: s = pform # First element else: coeff = item.as_coeff_mmul()[0] if _coeff_isneg(S(coeff)): s = prettyForm(*stringPict.next(s, ' ')) pform = self._print(item) else: s = prettyForm(*stringPict.next(s, ' + ')) s = prettyForm(*stringPict.next(s, pform)) return s def _print_MatMul(self, expr): args = list(expr.args) from sympy import Add, MatAdd, HadamardProduct, KroneckerProduct for i, a in enumerate(args): if (isinstance(a, (Add, MatAdd, HadamardProduct, KroneckerProduct)) and len(expr.args) > 1): args[i] = prettyForm(*self._print(a).parens()) else: args[i] = self._print(a) return prettyForm.__mul__(*args) def _print_Identity(self, expr): if self._use_unicode: return prettyForm(u'\N{MATHEMATICAL DOUBLE-STRUCK CAPITAL I}') else: return prettyForm('I') def _print_ZeroMatrix(self, expr): if self._use_unicode: return prettyForm(u'\N{MATHEMATICAL DOUBLE-STRUCK DIGIT ZERO}') else: return prettyForm('0') def _print_OneMatrix(self, expr): if self._use_unicode: return prettyForm(u'\N{MATHEMATICAL DOUBLE-STRUCK DIGIT ONE}') else: return prettyForm('1') def _print_DotProduct(self, expr): args = list(expr.args) for i, a in enumerate(args): args[i] = self._print(a) return prettyForm.__mul__(*args) def _print_MatPow(self, expr): pform = self._print(expr.base) from sympy.matrices import MatrixSymbol if not isinstance(expr.base, MatrixSymbol): pform = prettyForm(*pform.parens()) pform = pform**(self._print(expr.exp)) return pform def _print_HadamardProduct(self, expr): from sympy import MatAdd, MatMul, HadamardProduct if self._use_unicode: delim = pretty_atom('Ring') else: delim = '.*' return self._print_seq(expr.args, None, None, delim, parenthesize=lambda x: isinstance(x, (MatAdd, MatMul, HadamardProduct))) def _print_HadamardPower(self, expr): # from sympy import MatAdd, MatMul if self._use_unicode: circ = pretty_atom('Ring') else: circ = self._print('.') pretty_base = self._print(expr.base) pretty_exp = self._print(expr.exp) if precedence(expr.exp) < PRECEDENCE["Mul"]: pretty_exp = prettyForm(*pretty_exp.parens()) pretty_circ_exp = prettyForm( binding=prettyForm.LINE, *stringPict.next(circ, pretty_exp) ) return pretty_base**pretty_circ_exp def _print_KroneckerProduct(self, expr): from sympy import MatAdd, MatMul if self._use_unicode: delim = u' \N{N-ARY CIRCLED TIMES OPERATOR} ' else: delim = ' x ' return self._print_seq(expr.args, None, None, delim, parenthesize=lambda x: isinstance(x, (MatAdd, MatMul))) def _print_FunctionMatrix(self, X): D = self._print(X.lamda.expr) D = prettyForm(*D.parens('[', ']')) return D def _print_BasisDependent(self, expr): from sympy.vector import Vector if not self._use_unicode: raise NotImplementedError("ASCII pretty printing of BasisDependent is not implemented") if expr == expr.zero: return prettyForm(expr.zero._pretty_form) o1 = [] vectstrs = [] if isinstance(expr, Vector): items = expr.separate().items() else: items = [(0, expr)] for system, vect in items: inneritems = list(vect.components.items()) inneritems.sort(key = lambda x: x[0].__str__()) for k, v in inneritems: #if the coef of the basis vector is 1 #we skip the 1 if v == 1: o1.append(u"" + k._pretty_form) #Same for -1 elif v == -1: o1.append(u"(-1) " + k._pretty_form) #For a general expr else: #We always wrap the measure numbers in #parentheses arg_str = self._print( v).parens()[0] o1.append(arg_str + ' ' + k._pretty_form) vectstrs.append(k._pretty_form) #outstr = u("").join(o1) if o1[0].startswith(u" + "): o1[0] = o1[0][3:] elif o1[0].startswith(" "): o1[0] = o1[0][1:] #Fixing the newlines lengths = [] strs = [''] flag = [] for i, partstr in enumerate(o1): flag.append(0) # XXX: What is this hack? if '\n' in partstr: tempstr = partstr tempstr = tempstr.replace(vectstrs[i], '') if u'\N{right parenthesis extension}' in tempstr: # If scalar is a fraction for paren in range(len(tempstr)): flag[i] = 1 if tempstr[paren] == u'\N{right parenthesis extension}': tempstr = tempstr[:paren] + u'\N{right parenthesis extension}'\ + ' ' + vectstrs[i] + tempstr[paren + 1:] break elif u'\N{RIGHT PARENTHESIS LOWER HOOK}' in tempstr: flag[i] = 1 tempstr = tempstr.replace(u'\N{RIGHT PARENTHESIS LOWER HOOK}', u'\N{RIGHT PARENTHESIS LOWER HOOK}' + ' ' + vectstrs[i]) else: tempstr = tempstr.replace(u'\N{RIGHT PARENTHESIS UPPER HOOK}', u'\N{RIGHT PARENTHESIS UPPER HOOK}' + ' ' + vectstrs[i]) o1[i] = tempstr o1 = [x.split('\n') for x in o1] n_newlines = max([len(x) for x in o1]) # Width of part in its pretty form if 1 in flag: # If there was a fractional scalar for i, parts in enumerate(o1): if len(parts) == 1: # If part has no newline parts.insert(0, ' ' * (len(parts[0]))) flag[i] = 1 for i, parts in enumerate(o1): lengths.append(len(parts[flag[i]])) for j in range(n_newlines): if j+1 <= len(parts): if j >= len(strs): strs.append(' ' * (sum(lengths[:-1]) + 3*(len(lengths)-1))) if j == flag[i]: strs[flag[i]] += parts[flag[i]] + ' + ' else: strs[j] += parts[j] + ' '*(lengths[-1] - len(parts[j])+ 3) else: if j >= len(strs): strs.append(' ' * (sum(lengths[:-1]) + 3*(len(lengths)-1))) strs[j] += ' '*(lengths[-1]+3) return prettyForm(u'\n'.join([s[:-3] for s in strs])) def _print_NDimArray(self, expr): from sympy import ImmutableMatrix if expr.rank() == 0: return self._print(expr[()]) level_str = [[]] + [[] for i in range(expr.rank())] shape_ranges = [list(range(i)) for i in expr.shape] # leave eventual matrix elements unflattened mat = lambda x: ImmutableMatrix(x, evaluate=False) for outer_i in itertools.product(*shape_ranges): level_str[-1].append(expr[outer_i]) even = True for back_outer_i in range(expr.rank()-1, -1, -1): if len(level_str[back_outer_i+1]) < expr.shape[back_outer_i]: break if even: level_str[back_outer_i].append(level_str[back_outer_i+1]) else: level_str[back_outer_i].append(mat( level_str[back_outer_i+1])) if len(level_str[back_outer_i + 1]) == 1: level_str[back_outer_i][-1] = mat( [[level_str[back_outer_i][-1]]]) even = not even level_str[back_outer_i+1] = [] out_expr = level_str[0][0] if expr.rank() % 2 == 1: out_expr = mat([out_expr]) return self._print(out_expr) _print_ImmutableDenseNDimArray = _print_NDimArray _print_ImmutableSparseNDimArray = _print_NDimArray _print_MutableDenseNDimArray = _print_NDimArray _print_MutableSparseNDimArray = _print_NDimArray def _printer_tensor_indices(self, name, indices, index_map={}): center = stringPict(name) top = stringPict(" "*center.width()) bot = stringPict(" "*center.width()) last_valence = None prev_map = None for i, index in enumerate(indices): indpic = self._print(index.args[0]) if ((index in index_map) or prev_map) and last_valence == index.is_up: if index.is_up: top = prettyForm(*stringPict.next(top, ",")) else: bot = prettyForm(*stringPict.next(bot, ",")) if index in index_map: indpic = prettyForm(*stringPict.next(indpic, "=")) indpic = prettyForm(*stringPict.next(indpic, self._print(index_map[index]))) prev_map = True else: prev_map = False if index.is_up: top = stringPict(*top.right(indpic)) center = stringPict(*center.right(" "*indpic.width())) bot = stringPict(*bot.right(" "*indpic.width())) else: bot = stringPict(*bot.right(indpic)) center = stringPict(*center.right(" "*indpic.width())) top = stringPict(*top.right(" "*indpic.width())) last_valence = index.is_up pict = prettyForm(*center.above(top)) pict = prettyForm(*pict.below(bot)) return pict def _print_Tensor(self, expr): name = expr.args[0].name indices = expr.get_indices() return self._printer_tensor_indices(name, indices) def _print_TensorElement(self, expr): name = expr.expr.args[0].name indices = expr.expr.get_indices() index_map = expr.index_map return self._printer_tensor_indices(name, indices, index_map) def _print_TensMul(self, expr): sign, args = expr._get_args_for_traditional_printer() args = [ prettyForm(*self._print(i).parens()) if precedence_traditional(i) < PRECEDENCE["Mul"] else self._print(i) for i in args ] pform = prettyForm.__mul__(*args) if sign: return prettyForm(*pform.left(sign)) else: return pform def _print_TensAdd(self, expr): args = [ prettyForm(*self._print(i).parens()) if precedence_traditional(i) < PRECEDENCE["Mul"] else self._print(i) for i in expr.args ] return prettyForm.__add__(*args) def _print_TensorIndex(self, expr): sym = expr.args[0] if not expr.is_up: sym = -sym return self._print(sym) def _print_PartialDerivative(self, deriv): if self._use_unicode: deriv_symbol = U('PARTIAL DIFFERENTIAL') else: deriv_symbol = r'd' x = None for variable in reversed(deriv.variables): s = self._print(variable) ds = prettyForm(*s.left(deriv_symbol)) if x is None: x = ds else: x = prettyForm(*x.right(' ')) x = prettyForm(*x.right(ds)) f = prettyForm( binding=prettyForm.FUNC, *self._print(deriv.expr).parens()) pform = prettyForm(deriv_symbol) if len(deriv.variables) > 1: pform = pform**self._print(len(deriv.variables)) pform = prettyForm(*pform.below(stringPict.LINE, x)) pform.baseline = pform.baseline + 1 pform = prettyForm(*stringPict.next(pform, f)) pform.binding = prettyForm.MUL return pform def _print_Piecewise(self, pexpr): P = {} for n, ec in enumerate(pexpr.args): P[n, 0] = self._print(ec.expr) if ec.cond == True: P[n, 1] = prettyForm('otherwise') else: P[n, 1] = prettyForm( *prettyForm('for ').right(self._print(ec.cond))) hsep = 2 vsep = 1 len_args = len(pexpr.args) # max widths maxw = [max([P[i, j].width() for i in range(len_args)]) for j in range(2)] # FIXME: Refactor this code and matrix into some tabular environment. # drawing result D = None for i in range(len_args): D_row = None for j in range(2): p = P[i, j] assert p.width() <= maxw[j] wdelta = maxw[j] - p.width() wleft = wdelta // 2 wright = wdelta - wleft p = prettyForm(*p.right(' '*wright)) p = prettyForm(*p.left(' '*wleft)) if D_row is None: D_row = p continue D_row = prettyForm(*D_row.right(' '*hsep)) # h-spacer D_row = prettyForm(*D_row.right(p)) if D is None: D = D_row # first row in a picture continue # v-spacer for _ in range(vsep): D = prettyForm(*D.below(' ')) D = prettyForm(*D.below(D_row)) D = prettyForm(*D.parens('{', '')) D.baseline = D.height()//2 D.binding = prettyForm.OPEN return D def _print_ITE(self, ite): from sympy.functions.elementary.piecewise import Piecewise return self._print(ite.rewrite(Piecewise)) def _hprint_vec(self, v): D = None for a in v: p = a if D is None: D = p else: D = prettyForm(*D.right(', ')) D = prettyForm(*D.right(p)) if D is None: D = stringPict(' ') return D def _hprint_vseparator(self, p1, p2): tmp = prettyForm(*p1.right(p2)) sep = stringPict(vobj('|', tmp.height()), baseline=tmp.baseline) return prettyForm(*p1.right(sep, p2)) def _print_hyper(self, e): # FIXME refactor Matrix, Piecewise, and this into a tabular environment ap = [self._print(a) for a in e.ap] bq = [self._print(b) for b in e.bq] P = self._print(e.argument) P.baseline = P.height()//2 # Drawing result - first create the ap, bq vectors D = None for v in [ap, bq]: D_row = self._hprint_vec(v) if D is None: D = D_row # first row in a picture else: D = prettyForm(*D.below(' ')) D = prettyForm(*D.below(D_row)) # make sure that the argument `z' is centred vertically D.baseline = D.height()//2 # insert horizontal separator P = prettyForm(*P.left(' ')) D = prettyForm(*D.right(' ')) # insert separating `|` D = self._hprint_vseparator(D, P) # add parens D = prettyForm(*D.parens('(', ')')) # create the F symbol above = D.height()//2 - 1 below = D.height() - above - 1 sz, t, b, add, img = annotated('F') F = prettyForm('\n' * (above - t) + img + '\n' * (below - b), baseline=above + sz) add = (sz + 1)//2 F = prettyForm(*F.left(self._print(len(e.ap)))) F = prettyForm(*F.right(self._print(len(e.bq)))) F.baseline = above + add D = prettyForm(*F.right(' ', D)) return D def _print_meijerg(self, e): # FIXME refactor Matrix, Piecewise, and this into a tabular environment v = {} v[(0, 0)] = [self._print(a) for a in e.an] v[(0, 1)] = [self._print(a) for a in e.aother] v[(1, 0)] = [self._print(b) for b in e.bm] v[(1, 1)] = [self._print(b) for b in e.bother] P = self._print(e.argument) P.baseline = P.height()//2 vp = {} for idx in v: vp[idx] = self._hprint_vec(v[idx]) for i in range(2): maxw = max(vp[(0, i)].width(), vp[(1, i)].width()) for j in range(2): s = vp[(j, i)] left = (maxw - s.width()) // 2 right = maxw - left - s.width() s = prettyForm(*s.left(' ' * left)) s = prettyForm(*s.right(' ' * right)) vp[(j, i)] = s D1 = prettyForm(*vp[(0, 0)].right(' ', vp[(0, 1)])) D1 = prettyForm(*D1.below(' ')) D2 = prettyForm(*vp[(1, 0)].right(' ', vp[(1, 1)])) D = prettyForm(*D1.below(D2)) # make sure that the argument `z' is centred vertically D.baseline = D.height()//2 # insert horizontal separator P = prettyForm(*P.left(' ')) D = prettyForm(*D.right(' ')) # insert separating `|` D = self._hprint_vseparator(D, P) # add parens D = prettyForm(*D.parens('(', ')')) # create the G symbol above = D.height()//2 - 1 below = D.height() - above - 1 sz, t, b, add, img = annotated('G') F = prettyForm('\n' * (above - t) + img + '\n' * (below - b), baseline=above + sz) pp = self._print(len(e.ap)) pq = self._print(len(e.bq)) pm = self._print(len(e.bm)) pn = self._print(len(e.an)) def adjust(p1, p2): diff = p1.width() - p2.width() if diff == 0: return p1, p2 elif diff > 0: return p1, prettyForm(*p2.left(' '*diff)) else: return prettyForm(*p1.left(' '*-diff)), p2 pp, pm = adjust(pp, pm) pq, pn = adjust(pq, pn) pu = prettyForm(*pm.right(', ', pn)) pl = prettyForm(*pp.right(', ', pq)) ht = F.baseline - above - 2 if ht > 0: pu = prettyForm(*pu.below('\n'*ht)) p = prettyForm(*pu.below(pl)) F.baseline = above F = prettyForm(*F.right(p)) F.baseline = above + add D = prettyForm(*F.right(' ', D)) return D def _print_ExpBase(self, e): # TODO should exp_polar be printed differently? # what about exp_polar(0), exp_polar(1)? base = prettyForm(pretty_atom('Exp1', 'e')) return base ** self._print(e.args[0]) def _print_Function(self, e, sort=False, func_name=None): # optional argument func_name for supplying custom names # XXX works only for applied functions return self._helper_print_function(e.func, e.args, sort=sort, func_name=func_name) def _print_mathieuc(self, e): return self._print_Function(e, func_name='C') def _print_mathieus(self, e): return self._print_Function(e, func_name='S') def _print_mathieucprime(self, e): return self._print_Function(e, func_name="C'") def _print_mathieusprime(self, e): return self._print_Function(e, func_name="S'") def _helper_print_function(self, func, args, sort=False, func_name=None, delimiter=', ', elementwise=False): if sort: args = sorted(args, key=default_sort_key) if not func_name and hasattr(func, "__name__"): func_name = func.__name__ if func_name: prettyFunc = self._print(Symbol(func_name)) else: prettyFunc = prettyForm(*self._print(func).parens()) if elementwise: if self._use_unicode: circ = pretty_atom('Modifier Letter Low Ring') else: circ = '.' circ = self._print(circ) prettyFunc = prettyForm( binding=prettyForm.LINE, *stringPict.next(prettyFunc, circ) ) prettyArgs = prettyForm(*self._print_seq(args, delimiter=delimiter).parens()) pform = prettyForm( binding=prettyForm.FUNC, *stringPict.next(prettyFunc, prettyArgs)) # store pform parts so it can be reassembled e.g. when powered pform.prettyFunc = prettyFunc pform.prettyArgs = prettyArgs return pform def _print_ElementwiseApplyFunction(self, e): func = e.function arg = e.expr args = [arg] return self._helper_print_function(func, args, delimiter="", elementwise=True) @property def _special_function_classes(self): from sympy.functions.special.tensor_functions import KroneckerDelta from sympy.functions.special.gamma_functions import gamma, lowergamma from sympy.functions.special.zeta_functions import lerchphi from sympy.functions.special.beta_functions import beta from sympy.functions.special.delta_functions import DiracDelta from sympy.functions.special.error_functions import Chi return {KroneckerDelta: [greek_unicode['delta'], 'delta'], gamma: [greek_unicode['Gamma'], 'Gamma'], lerchphi: [greek_unicode['Phi'], 'lerchphi'], lowergamma: [greek_unicode['gamma'], 'gamma'], beta: [greek_unicode['Beta'], 'B'], DiracDelta: [greek_unicode['delta'], 'delta'], Chi: ['Chi', 'Chi']} def _print_FunctionClass(self, expr): for cls in self._special_function_classes: if issubclass(expr, cls) and expr.__name__ == cls.__name__: if self._use_unicode: return prettyForm(self._special_function_classes[cls][0]) else: return prettyForm(self._special_function_classes[cls][1]) func_name = expr.__name__ return prettyForm(pretty_symbol(func_name)) def _print_GeometryEntity(self, expr): # GeometryEntity is based on Tuple but should not print like a Tuple return self.emptyPrinter(expr) def _print_lerchphi(self, e): func_name = greek_unicode['Phi'] if self._use_unicode else 'lerchphi' return self._print_Function(e, func_name=func_name) def _print_dirichlet_eta(self, e): func_name = greek_unicode['eta'] if self._use_unicode else 'dirichlet_eta' return self._print_Function(e, func_name=func_name) def _print_Heaviside(self, e): func_name = greek_unicode['theta'] if self._use_unicode else 'Heaviside' return self._print_Function(e, func_name=func_name) def _print_fresnels(self, e): return self._print_Function(e, func_name="S") def _print_fresnelc(self, e): return self._print_Function(e, func_name="C") def _print_airyai(self, e): return self._print_Function(e, func_name="Ai") def _print_airybi(self, e): return self._print_Function(e, func_name="Bi") def _print_airyaiprime(self, e): return self._print_Function(e, func_name="Ai'") def _print_airybiprime(self, e): return self._print_Function(e, func_name="Bi'") def _print_LambertW(self, e): return self._print_Function(e, func_name="W") def _print_Lambda(self, e): expr = e.expr sig = e.signature if self._use_unicode: arrow = u" \N{RIGHTWARDS ARROW FROM BAR} " else: arrow = " -> " if len(sig) == 1 and sig[0].is_symbol: sig = sig[0] var_form = self._print(sig) return prettyForm(*stringPict.next(var_form, arrow, self._print(expr)), binding=8) def _print_Order(self, expr): pform = self._print(expr.expr) if (expr.point and any(p != S.Zero for p in expr.point)) or \ len(expr.variables) > 1: pform = prettyForm(*pform.right("; ")) if len(expr.variables) > 1: pform = prettyForm(*pform.right(self._print(expr.variables))) elif len(expr.variables): pform = prettyForm(*pform.right(self._print(expr.variables[0]))) if self._use_unicode: pform = prettyForm(*pform.right(u" \N{RIGHTWARDS ARROW} ")) else: pform = prettyForm(*pform.right(" -> ")) if len(expr.point) > 1: pform = prettyForm(*pform.right(self._print(expr.point))) else: pform = prettyForm(*pform.right(self._print(expr.point[0]))) pform = prettyForm(*pform.parens()) pform = prettyForm(*pform.left("O")) return pform def _print_SingularityFunction(self, e): if self._use_unicode: shift = self._print(e.args[0]-e.args[1]) n = self._print(e.args[2]) base = prettyForm("<") base = prettyForm(*base.right(shift)) base = prettyForm(*base.right(">")) pform = base**n return pform else: n = self._print(e.args[2]) shift = self._print(e.args[0]-e.args[1]) base = self._print_seq(shift, "<", ">", ' ') return base**n def _print_beta(self, e): func_name = greek_unicode['Beta'] if self._use_unicode else 'B' return self._print_Function(e, func_name=func_name) def _print_gamma(self, e): func_name = greek_unicode['Gamma'] if self._use_unicode else 'Gamma' return self._print_Function(e, func_name=func_name) def _print_uppergamma(self, e): func_name = greek_unicode['Gamma'] if self._use_unicode else 'Gamma' return self._print_Function(e, func_name=func_name) def _print_lowergamma(self, e): func_name = greek_unicode['gamma'] if self._use_unicode else 'lowergamma' return self._print_Function(e, func_name=func_name) def _print_DiracDelta(self, e): if self._use_unicode: if len(e.args) == 2: a = prettyForm(greek_unicode['delta']) b = self._print(e.args[1]) b = prettyForm(*b.parens()) c = self._print(e.args[0]) c = prettyForm(*c.parens()) pform = a**b pform = prettyForm(*pform.right(' ')) pform = prettyForm(*pform.right(c)) return pform pform = self._print(e.args[0]) pform = prettyForm(*pform.parens()) pform = prettyForm(*pform.left(greek_unicode['delta'])) return pform else: return self._print_Function(e) def _print_expint(self, e): from sympy import Function if e.args[0].is_Integer and self._use_unicode: return self._print_Function(Function('E_%s' % e.args[0])(e.args[1])) return self._print_Function(e) def _print_Chi(self, e): # This needs a special case since otherwise it comes out as greek # letter chi... prettyFunc = prettyForm("Chi") prettyArgs = prettyForm(*self._print_seq(e.args).parens()) pform = prettyForm( binding=prettyForm.FUNC, *stringPict.next(prettyFunc, prettyArgs)) # store pform parts so it can be reassembled e.g. when powered pform.prettyFunc = prettyFunc pform.prettyArgs = prettyArgs return pform def _print_elliptic_e(self, e): pforma0 = self._print(e.args[0]) if len(e.args) == 1: pform = pforma0 else: pforma1 = self._print(e.args[1]) pform = self._hprint_vseparator(pforma0, pforma1) pform = prettyForm(*pform.parens()) pform = prettyForm(*pform.left('E')) return pform def _print_elliptic_k(self, e): pform = self._print(e.args[0]) pform = prettyForm(*pform.parens()) pform = prettyForm(*pform.left('K')) return pform def _print_elliptic_f(self, e): pforma0 = self._print(e.args[0]) pforma1 = self._print(e.args[1]) pform = self._hprint_vseparator(pforma0, pforma1) pform = prettyForm(*pform.parens()) pform = prettyForm(*pform.left('F')) return pform def _print_elliptic_pi(self, e): name = greek_unicode['Pi'] if self._use_unicode else 'Pi' pforma0 = self._print(e.args[0]) pforma1 = self._print(e.args[1]) if len(e.args) == 2: pform = self._hprint_vseparator(pforma0, pforma1) else: pforma2 = self._print(e.args[2]) pforma = self._hprint_vseparator(pforma1, pforma2) pforma = prettyForm(*pforma.left('; ')) pform = prettyForm(*pforma.left(pforma0)) pform = prettyForm(*pform.parens()) pform = prettyForm(*pform.left(name)) return pform def _print_GoldenRatio(self, expr): if self._use_unicode: return prettyForm(pretty_symbol('phi')) return self._print(Symbol("GoldenRatio")) def _print_EulerGamma(self, expr): if self._use_unicode: return prettyForm(pretty_symbol('gamma')) return self._print(Symbol("EulerGamma")) def _print_Mod(self, expr): pform = self._print(expr.args[0]) if pform.binding > prettyForm.MUL: pform = prettyForm(*pform.parens()) pform = prettyForm(*pform.right(' mod ')) pform = prettyForm(*pform.right(self._print(expr.args[1]))) pform.binding = prettyForm.OPEN return pform def _print_Add(self, expr, order=None): if self.order == 'none': terms = list(expr.args) else: terms = self._as_ordered_terms(expr, order=order) pforms, indices = [], [] def pretty_negative(pform, index): """Prepend a minus sign to a pretty form. """ #TODO: Move this code to prettyForm if index == 0: if pform.height() > 1: pform_neg = '- ' else: pform_neg = '-' else: pform_neg = ' - ' if (pform.binding > prettyForm.NEG or pform.binding == prettyForm.ADD): p = stringPict(*pform.parens()) else: p = pform p = stringPict.next(pform_neg, p) # Lower the binding to NEG, even if it was higher. Otherwise, it # will print as a + ( - (b)), instead of a - (b). return prettyForm(binding=prettyForm.NEG, *p) for i, term in enumerate(terms): if term.is_Mul and _coeff_isneg(term): coeff, other = term.as_coeff_mul(rational=False) pform = self._print(Mul(-coeff, *other, evaluate=False)) pforms.append(pretty_negative(pform, i)) elif term.is_Rational and term.q > 1: pforms.append(None) indices.append(i) elif term.is_Number and term < 0: pform = self._print(-term) pforms.append(pretty_negative(pform, i)) elif term.is_Relational: pforms.append(prettyForm(*self._print(term).parens())) else: pforms.append(self._print(term)) if indices: large = True for pform in pforms: if pform is not None and pform.height() > 1: break else: large = False for i in indices: term, negative = terms[i], False if term < 0: term, negative = -term, True if large: pform = prettyForm(str(term.p))/prettyForm(str(term.q)) else: pform = self._print(term) if negative: pform = pretty_negative(pform, i) pforms[i] = pform return prettyForm.__add__(*pforms) def _print_Mul(self, product): from sympy.physics.units import Quantity a = [] # items in the numerator b = [] # items that are in the denominator (if any) if self.order not in ('old', 'none'): args = product.as_ordered_factors() else: args = list(product.args) # If quantities are present append them at the back args = sorted(args, key=lambda x: isinstance(x, Quantity) or (isinstance(x, Pow) and isinstance(x.base, Quantity))) # Gather terms for numerator/denominator for item in args: if item.is_commutative and item.is_Pow and item.exp.is_Rational and item.exp.is_negative: if item.exp != -1: b.append(Pow(item.base, -item.exp, evaluate=False)) else: b.append(Pow(item.base, -item.exp)) elif item.is_Rational and item is not S.Infinity: if item.p != 1: a.append( Rational(item.p) ) if item.q != 1: b.append( Rational(item.q) ) else: a.append(item) from sympy import Integral, Piecewise, Product, Sum # Convert to pretty forms. Add parens to Add instances if there # is more than one term in the numer/denom for i in range(0, len(a)): if (a[i].is_Add and len(a) > 1) or (i != len(a) - 1 and isinstance(a[i], (Integral, Piecewise, Product, Sum))): a[i] = prettyForm(*self._print(a[i]).parens()) elif a[i].is_Relational: a[i] = prettyForm(*self._print(a[i]).parens()) else: a[i] = self._print(a[i]) for i in range(0, len(b)): if (b[i].is_Add and len(b) > 1) or (i != len(b) - 1 and isinstance(b[i], (Integral, Piecewise, Product, Sum))): b[i] = prettyForm(*self._print(b[i]).parens()) else: b[i] = self._print(b[i]) # Construct a pretty form if len(b) == 0: return prettyForm.__mul__(*a) else: if len(a) == 0: a.append( self._print(S.One) ) return prettyForm.__mul__(*a)/prettyForm.__mul__(*b) # A helper function for _print_Pow to print x**(1/n) def _print_nth_root(self, base, expt): bpretty = self._print(base) # In very simple cases, use a single-char root sign if (self._settings['use_unicode_sqrt_char'] and self._use_unicode and expt is S.Half and bpretty.height() == 1 and (bpretty.width() == 1 or (base.is_Integer and base.is_nonnegative))): return prettyForm(*bpretty.left(u'\N{SQUARE ROOT}')) # Construct root sign, start with the \/ shape _zZ = xobj('/', 1) rootsign = xobj('\\', 1) + _zZ # Make exponent number to put above it if isinstance(expt, Rational): exp = str(expt.q) if exp == '2': exp = '' else: exp = str(expt.args[0]) exp = exp.ljust(2) if len(exp) > 2: rootsign = ' '*(len(exp) - 2) + rootsign # Stack the exponent rootsign = stringPict(exp + '\n' + rootsign) rootsign.baseline = 0 # Diagonal: length is one less than height of base linelength = bpretty.height() - 1 diagonal = stringPict('\n'.join( ' '*(linelength - i - 1) + _zZ + ' '*i for i in range(linelength) )) # Put baseline just below lowest line: next to exp diagonal.baseline = linelength - 1 # Make the root symbol rootsign = prettyForm(*rootsign.right(diagonal)) # Det the baseline to match contents to fix the height # but if the height of bpretty is one, the rootsign must be one higher rootsign.baseline = max(1, bpretty.baseline) #build result s = prettyForm(hobj('_', 2 + bpretty.width())) s = prettyForm(*bpretty.above(s)) s = prettyForm(*s.left(rootsign)) return s def _print_Pow(self, power): from sympy.simplify.simplify import fraction b, e = power.as_base_exp() if power.is_commutative: if e is S.NegativeOne: return prettyForm("1")/self._print(b) n, d = fraction(e) if n is S.One and d.is_Atom and not e.is_Integer and self._settings['root_notation']: return self._print_nth_root(b, e) if e.is_Rational and e < 0: return prettyForm("1")/self._print(Pow(b, -e, evaluate=False)) if b.is_Relational: return prettyForm(*self._print(b).parens()).__pow__(self._print(e)) return self._print(b)**self._print(e) def _print_UnevaluatedExpr(self, expr): return self._print(expr.args[0]) def __print_numer_denom(self, p, q): if q == 1: if p < 0: return prettyForm(str(p), binding=prettyForm.NEG) else: return prettyForm(str(p)) elif abs(p) >= 10 and abs(q) >= 10: # If more than one digit in numer and denom, print larger fraction if p < 0: return prettyForm(str(p), binding=prettyForm.NEG)/prettyForm(str(q)) # Old printing method: #pform = prettyForm(str(-p))/prettyForm(str(q)) #return prettyForm(binding=prettyForm.NEG, *pform.left('- ')) else: return prettyForm(str(p))/prettyForm(str(q)) else: return None def _print_Rational(self, expr): result = self.__print_numer_denom(expr.p, expr.q) if result is not None: return result else: return self.emptyPrinter(expr) def _print_Fraction(self, expr): result = self.__print_numer_denom(expr.numerator, expr.denominator) if result is not None: return result else: return self.emptyPrinter(expr) def _print_ProductSet(self, p): if len(p.sets) >= 1 and not has_variety(p.sets): from sympy import Pow return self._print(Pow(p.sets[0], len(p.sets), evaluate=False)) else: prod_char = u"\N{MULTIPLICATION SIGN}" if self._use_unicode else 'x' return self._print_seq(p.sets, None, None, ' %s ' % prod_char, parenthesize=lambda set: set.is_Union or set.is_Intersection or set.is_ProductSet) def _print_FiniteSet(self, s): items = sorted(s.args, key=default_sort_key) return self._print_seq(items, '{', '}', ', ' ) def _print_Range(self, s): if self._use_unicode: dots = u"\N{HORIZONTAL ELLIPSIS}" else: dots = '...' if s.start.is_infinite and s.stop.is_infinite: if s.step.is_positive: printset = dots, -1, 0, 1, dots else: printset = dots, 1, 0, -1, dots elif s.start.is_infinite: printset = dots, s[-1] - s.step, s[-1] elif s.stop.is_infinite: it = iter(s) printset = next(it), next(it), dots elif len(s) > 4: it = iter(s) printset = next(it), next(it), dots, s[-1] else: printset = tuple(s) return self._print_seq(printset, '{', '}', ', ' ) def _print_Interval(self, i): if i.start == i.end: return self._print_seq(i.args[:1], '{', '}') else: if i.left_open: left = '(' else: left = '[' if i.right_open: right = ')' else: right = ']' return self._print_seq(i.args[:2], left, right) def _print_AccumulationBounds(self, i): left = '<' right = '>' return self._print_seq(i.args[:2], left, right) def _print_Intersection(self, u): delimiter = ' %s ' % pretty_atom('Intersection', 'n') return self._print_seq(u.args, None, None, delimiter, parenthesize=lambda set: set.is_ProductSet or set.is_Union or set.is_Complement) def _print_Union(self, u): union_delimiter = ' %s ' % pretty_atom('Union', 'U') return self._print_seq(u.args, None, None, union_delimiter, parenthesize=lambda set: set.is_ProductSet or set.is_Intersection or set.is_Complement) def _print_SymmetricDifference(self, u): if not self._use_unicode: raise NotImplementedError("ASCII pretty printing of SymmetricDifference is not implemented") sym_delimeter = ' %s ' % pretty_atom('SymmetricDifference') return self._print_seq(u.args, None, None, sym_delimeter) def _print_Complement(self, u): delimiter = r' \ ' return self._print_seq(u.args, None, None, delimiter, parenthesize=lambda set: set.is_ProductSet or set.is_Intersection or set.is_Union) def _print_ImageSet(self, ts): if self._use_unicode: inn = u"\N{SMALL ELEMENT OF}" else: inn = 'in' fun = ts.lamda sets = ts.base_sets signature = fun.signature expr = self._print(fun.expr) bar = self._print("|") if len(signature) == 1: return self._print_seq((expr, bar, signature[0], inn, sets[0]), "{", "}", ' ') else: pargs = tuple(j for var, setv in zip(signature, sets) for j in (var, inn, setv, ",")) return self._print_seq((expr, bar) + pargs[:-1], "{", "}", ' ') def _print_ConditionSet(self, ts): if self._use_unicode: inn = u"\N{SMALL ELEMENT OF}" # using _and because and is a keyword and it is bad practice to # overwrite them _and = u"\N{LOGICAL AND}" else: inn = 'in' _and = 'and' variables = self._print_seq(Tuple(ts.sym)) as_expr = getattr(ts.condition, 'as_expr', None) if as_expr is not None: cond = self._print(ts.condition.as_expr()) else: cond = self._print(ts.condition) if self._use_unicode: cond = self._print(cond) cond = prettyForm(*cond.parens()) bar = self._print("|") if ts.base_set is S.UniversalSet: return self._print_seq((variables, bar, cond), "{", "}", ' ') base = self._print(ts.base_set) return self._print_seq((variables, bar, variables, inn, base, _and, cond), "{", "}", ' ') def _print_ComplexRegion(self, ts): if self._use_unicode: inn = u"\N{SMALL ELEMENT OF}" else: inn = 'in' variables = self._print_seq(ts.variables) expr = self._print(ts.expr) bar = self._print("|") prodsets = self._print(ts.sets) return self._print_seq((expr, bar, variables, inn, prodsets), "{", "}", ' ') def _print_Contains(self, e): var, set = e.args if self._use_unicode: el = u" \N{ELEMENT OF} " return prettyForm(*stringPict.next(self._print(var), el, self._print(set)), binding=8) else: return prettyForm(sstr(e)) def _print_FourierSeries(self, s): if self._use_unicode: dots = u"\N{HORIZONTAL ELLIPSIS}" else: dots = '...' return self._print_Add(s.truncate()) + self._print(dots) def _print_FormalPowerSeries(self, s): return self._print_Add(s.infinite) def _print_SetExpr(self, se): pretty_set = prettyForm(*self._print(se.set).parens()) pretty_name = self._print(Symbol("SetExpr")) return prettyForm(*pretty_name.right(pretty_set)) def _print_SeqFormula(self, s): if self._use_unicode: dots = u"\N{HORIZONTAL ELLIPSIS}" else: dots = '...' if len(s.start.free_symbols) > 0 or len(s.stop.free_symbols) > 0: raise NotImplementedError("Pretty printing of sequences with symbolic bound not implemented") if s.start is S.NegativeInfinity: stop = s.stop printset = (dots, s.coeff(stop - 3), s.coeff(stop - 2), s.coeff(stop - 1), s.coeff(stop)) elif s.stop is S.Infinity or s.length > 4: printset = s[:4] printset.append(dots) printset = tuple(printset) else: printset = tuple(s) return self._print_list(printset) _print_SeqPer = _print_SeqFormula _print_SeqAdd = _print_SeqFormula _print_SeqMul = _print_SeqFormula def _print_seq(self, seq, left=None, right=None, delimiter=', ', parenthesize=lambda x: False): s = None try: for item in seq: pform = self._print(item) if parenthesize(item): pform = prettyForm(*pform.parens()) if s is None: # first element s = pform else: # XXX: Under the tests from #15686 this raises: # AttributeError: 'Fake' object has no attribute 'baseline' # This is caught below but that is not the right way to # fix it. s = prettyForm(*stringPict.next(s, delimiter)) s = prettyForm(*stringPict.next(s, pform)) if s is None: s = stringPict('') except AttributeError: s = None for item in seq: pform = self.doprint(item) if parenthesize(item): pform = prettyForm(*pform.parens()) if s is None: # first element s = pform else : s = prettyForm(*stringPict.next(s, delimiter)) s = prettyForm(*stringPict.next(s, pform)) if s is None: s = stringPict('') s = prettyForm(*s.parens(left, right, ifascii_nougly=True)) return s def join(self, delimiter, args): pform = None for arg in args: if pform is None: pform = arg else: pform = prettyForm(*pform.right(delimiter)) pform = prettyForm(*pform.right(arg)) if pform is None: return prettyForm("") else: return pform def _print_list(self, l): return self._print_seq(l, '[', ']') def _print_tuple(self, t): if len(t) == 1: ptuple = prettyForm(*stringPict.next(self._print(t[0]), ',')) return prettyForm(*ptuple.parens('(', ')', ifascii_nougly=True)) else: return self._print_seq(t, '(', ')') def _print_Tuple(self, expr): return self._print_tuple(expr) def _print_dict(self, d): keys = sorted(d.keys(), key=default_sort_key) items = [] for k in keys: K = self._print(k) V = self._print(d[k]) s = prettyForm(*stringPict.next(K, ': ', V)) items.append(s) return self._print_seq(items, '{', '}') def _print_Dict(self, d): return self._print_dict(d) def _print_set(self, s): if not s: return prettyForm('set()') items = sorted(s, key=default_sort_key) pretty = self._print_seq(items) pretty = prettyForm(*pretty.parens('{', '}', ifascii_nougly=True)) return pretty def _print_frozenset(self, s): if not s: return prettyForm('frozenset()') items = sorted(s, key=default_sort_key) pretty = self._print_seq(items) pretty = prettyForm(*pretty.parens('{', '}', ifascii_nougly=True)) pretty = prettyForm(*pretty.parens('(', ')', ifascii_nougly=True)) pretty = prettyForm(*stringPict.next(type(s).__name__, pretty)) return pretty def _print_UniversalSet(self, s): if self._use_unicode: return prettyForm(u"\N{MATHEMATICAL DOUBLE-STRUCK CAPITAL U}") else: return prettyForm('UniversalSet') def _print_PolyRing(self, ring): return prettyForm(sstr(ring)) def _print_FracField(self, field): return prettyForm(sstr(field)) def _print_FreeGroupElement(self, elm): return prettyForm(str(elm)) def _print_PolyElement(self, poly): return prettyForm(sstr(poly)) def _print_FracElement(self, frac): return prettyForm(sstr(frac)) def _print_AlgebraicNumber(self, expr): if expr.is_aliased: return self._print(expr.as_poly().as_expr()) else: return self._print(expr.as_expr()) def _print_ComplexRootOf(self, expr): args = [self._print_Add(expr.expr, order='lex'), expr.index] pform = prettyForm(*self._print_seq(args).parens()) pform = prettyForm(*pform.left('CRootOf')) return pform def _print_RootSum(self, expr): args = [self._print_Add(expr.expr, order='lex')] if expr.fun is not S.IdentityFunction: args.append(self._print(expr.fun)) pform = prettyForm(*self._print_seq(args).parens()) pform = prettyForm(*pform.left('RootSum')) return pform def _print_FiniteField(self, expr): if self._use_unicode: form = u'\N{DOUBLE-STRUCK CAPITAL Z}_%d' else: form = 'GF(%d)' return prettyForm(pretty_symbol(form % expr.mod)) def _print_IntegerRing(self, expr): if self._use_unicode: return prettyForm(u'\N{DOUBLE-STRUCK CAPITAL Z}') else: return prettyForm('ZZ') def _print_RationalField(self, expr): if self._use_unicode: return prettyForm(u'\N{DOUBLE-STRUCK CAPITAL Q}') else: return prettyForm('QQ') def _print_RealField(self, domain): if self._use_unicode: prefix = u'\N{DOUBLE-STRUCK CAPITAL R}' else: prefix = 'RR' if domain.has_default_precision: return prettyForm(prefix) else: return self._print(pretty_symbol(prefix + "_" + str(domain.precision))) def _print_ComplexField(self, domain): if self._use_unicode: prefix = u'\N{DOUBLE-STRUCK CAPITAL C}' else: prefix = 'CC' if domain.has_default_precision: return prettyForm(prefix) else: return self._print(pretty_symbol(prefix + "_" + str(domain.precision))) def _print_PolynomialRing(self, expr): args = list(expr.symbols) if not expr.order.is_default: order = prettyForm(*prettyForm("order=").right(self._print(expr.order))) args.append(order) pform = self._print_seq(args, '[', ']') pform = prettyForm(*pform.left(self._print(expr.domain))) return pform def _print_FractionField(self, expr): args = list(expr.symbols) if not expr.order.is_default: order = prettyForm(*prettyForm("order=").right(self._print(expr.order))) args.append(order) pform = self._print_seq(args, '(', ')') pform = prettyForm(*pform.left(self._print(expr.domain))) return pform def _print_PolynomialRingBase(self, expr): g = expr.symbols if str(expr.order) != str(expr.default_order): g = g + ("order=" + str(expr.order),) pform = self._print_seq(g, '[', ']') pform = prettyForm(*pform.left(self._print(expr.domain))) return pform def _print_GroebnerBasis(self, basis): exprs = [ self._print_Add(arg, order=basis.order) for arg in basis.exprs ] exprs = prettyForm(*self.join(", ", exprs).parens(left="[", right="]")) gens = [ self._print(gen) for gen in basis.gens ] domain = prettyForm( *prettyForm("domain=").right(self._print(basis.domain))) order = prettyForm( *prettyForm("order=").right(self._print(basis.order))) pform = self.join(", ", [exprs] + gens + [domain, order]) pform = prettyForm(*pform.parens()) pform = prettyForm(*pform.left(basis.__class__.__name__)) return pform def _print_Subs(self, e): pform = self._print(e.expr) pform = prettyForm(*pform.parens()) h = pform.height() if pform.height() > 1 else 2 rvert = stringPict(vobj('|', h), baseline=pform.baseline) pform = prettyForm(*pform.right(rvert)) b = pform.baseline pform.baseline = pform.height() - 1 pform = prettyForm(*pform.right(self._print_seq([ self._print_seq((self._print(v[0]), xsym('=='), self._print(v[1])), delimiter='') for v in zip(e.variables, e.point) ]))) pform.baseline = b return pform def _print_number_function(self, e, name): # Print name_arg[0] for one argument or name_arg[0](arg[1]) # for more than one argument pform = prettyForm(name) arg = self._print(e.args[0]) pform_arg = prettyForm(" "*arg.width()) pform_arg = prettyForm(*pform_arg.below(arg)) pform = prettyForm(*pform.right(pform_arg)) if len(e.args) == 1: return pform m, x = e.args # TODO: copy-pasted from _print_Function: can we do better? prettyFunc = pform prettyArgs = prettyForm(*self._print_seq([x]).parens()) pform = prettyForm( binding=prettyForm.FUNC, *stringPict.next(prettyFunc, prettyArgs)) pform.prettyFunc = prettyFunc pform.prettyArgs = prettyArgs return pform def _print_euler(self, e): return self._print_number_function(e, "E") def _print_catalan(self, e): return self._print_number_function(e, "C") def _print_bernoulli(self, e): return self._print_number_function(e, "B") _print_bell = _print_bernoulli def _print_lucas(self, e): return self._print_number_function(e, "L") def _print_fibonacci(self, e): return self._print_number_function(e, "F") def _print_tribonacci(self, e): return self._print_number_function(e, "T") def _print_stieltjes(self, e): if self._use_unicode: return self._print_number_function(e, u'\N{GREEK SMALL LETTER GAMMA}') else: return self._print_number_function(e, "stieltjes") def _print_KroneckerDelta(self, e): pform = self._print(e.args[0]) pform = prettyForm(*pform.right((prettyForm(',')))) pform = prettyForm(*pform.right((self._print(e.args[1])))) if self._use_unicode: a = stringPict(pretty_symbol('delta')) else: a = stringPict('d') b = pform top = stringPict(*b.left(' '*a.width())) bot = stringPict(*a.right(' '*b.width())) return prettyForm(binding=prettyForm.POW, *bot.below(top)) def _print_RandomDomain(self, d): if hasattr(d, 'as_boolean'): pform = self._print('Domain: ') pform = prettyForm(*pform.right(self._print(d.as_boolean()))) return pform elif hasattr(d, 'set'): pform = self._print('Domain: ') pform = prettyForm(*pform.right(self._print(d.symbols))) pform = prettyForm(*pform.right(self._print(' in '))) pform = prettyForm(*pform.right(self._print(d.set))) return pform elif hasattr(d, 'symbols'): pform = self._print('Domain on ') pform = prettyForm(*pform.right(self._print(d.symbols))) return pform else: return self._print(None) def _print_DMP(self, p): try: if p.ring is not None: # TODO incorporate order return self._print(p.ring.to_sympy(p)) except SympifyError: pass return self._print(repr(p)) def _print_DMF(self, p): return self._print_DMP(p) def _print_Object(self, object): return self._print(pretty_symbol(object.name)) def _print_Morphism(self, morphism): arrow = xsym("-->") domain = self._print(morphism.domain) codomain = self._print(morphism.codomain) tail = domain.right(arrow, codomain)[0] return prettyForm(tail) def _print_NamedMorphism(self, morphism): pretty_name = self._print(pretty_symbol(morphism.name)) pretty_morphism = self._print_Morphism(morphism) return prettyForm(pretty_name.right(":", pretty_morphism)[0]) def _print_IdentityMorphism(self, morphism): from sympy.categories import NamedMorphism return self._print_NamedMorphism( NamedMorphism(morphism.domain, morphism.codomain, "id")) def _print_CompositeMorphism(self, morphism): circle = xsym(".") # All components of the morphism have names and it is thus # possible to build the name of the composite. component_names_list = [pretty_symbol(component.name) for component in morphism.components] component_names_list.reverse() component_names = circle.join(component_names_list) + ":" pretty_name = self._print(component_names) pretty_morphism = self._print_Morphism(morphism) return prettyForm(pretty_name.right(pretty_morphism)[0]) def _print_Category(self, category): return self._print(pretty_symbol(category.name)) def _print_Diagram(self, diagram): if not diagram.premises: # This is an empty diagram. return self._print(S.EmptySet) pretty_result = self._print(diagram.premises) if diagram.conclusions: results_arrow = " %s " % xsym("==>") pretty_conclusions = self._print(diagram.conclusions)[0] pretty_result = pretty_result.right( results_arrow, pretty_conclusions) return prettyForm(pretty_result[0]) def _print_DiagramGrid(self, grid): from sympy.matrices import Matrix from sympy import Symbol matrix = Matrix([[grid[i, j] if grid[i, j] else Symbol(" ") for j in range(grid.width)] for i in range(grid.height)]) return self._print_matrix_contents(matrix) def _print_FreeModuleElement(self, m): # Print as row vector for convenience, for now. return self._print_seq(m, '[', ']') def _print_SubModule(self, M): return self._print_seq(M.gens, '<', '>') def _print_FreeModule(self, M): return self._print(M.ring)**self._print(M.rank) def _print_ModuleImplementedIdeal(self, M): return self._print_seq([x for [x] in M._module.gens], '<', '>') def _print_QuotientRing(self, R): return self._print(R.ring) / self._print(R.base_ideal) def _print_QuotientRingElement(self, R): return self._print(R.data) + self._print(R.ring.base_ideal) def _print_QuotientModuleElement(self, m): return self._print(m.data) + self._print(m.module.killed_module) def _print_QuotientModule(self, M): return self._print(M.base) / self._print(M.killed_module) def _print_MatrixHomomorphism(self, h): matrix = self._print(h._sympy_matrix()) matrix.baseline = matrix.height() // 2 pform = prettyForm(*matrix.right(' : ', self._print(h.domain), ' %s> ' % hobj('-', 2), self._print(h.codomain))) return pform def _print_BaseScalarField(self, field): string = field._coord_sys._names[field._index] return self._print(pretty_symbol(string)) def _print_BaseVectorField(self, field): s = U('PARTIAL DIFFERENTIAL') + '_' + field._coord_sys._names[field._index] return self._print(pretty_symbol(s)) def _print_Differential(self, diff): field = diff._form_field if hasattr(field, '_coord_sys'): string = field._coord_sys._names[field._index] return self._print(u'\N{DOUBLE-STRUCK ITALIC SMALL D} ' + pretty_symbol(string)) else: pform = self._print(field) pform = prettyForm(*pform.parens()) return prettyForm(*pform.left(u"\N{DOUBLE-STRUCK ITALIC SMALL D}")) def _print_Tr(self, p): #TODO: Handle indices pform = self._print(p.args[0]) pform = prettyForm(*pform.left('%s(' % (p.__class__.__name__))) pform = prettyForm(*pform.right(')')) return pform def _print_primenu(self, e): pform = self._print(e.args[0]) pform = prettyForm(*pform.parens()) if self._use_unicode: pform = prettyForm(*pform.left(greek_unicode['nu'])) else: pform = prettyForm(*pform.left('nu')) return pform def _print_primeomega(self, e): pform = self._print(e.args[0]) pform = prettyForm(*pform.parens()) if self._use_unicode: pform = prettyForm(*pform.left(greek_unicode['Omega'])) else: pform = prettyForm(*pform.left('Omega')) return pform def _print_Quantity(self, e): if e.name.name == 'degree': pform = self._print(u"\N{DEGREE SIGN}") return pform else: return self.emptyPrinter(e) def _print_AssignmentBase(self, e): op = prettyForm(' ' + xsym(e.op) + ' ') l = self._print(e.lhs) r = self._print(e.rhs) pform = prettyForm(*stringPict.next(l, op, r)) return pform def pretty(expr, **settings): """Returns a string containing the prettified form of expr. For information on keyword arguments see pretty_print function. """ pp = PrettyPrinter(settings) # XXX: this is an ugly hack, but at least it works use_unicode = pp._settings['use_unicode'] uflag = pretty_use_unicode(use_unicode) try: return pp.doprint(expr) finally: pretty_use_unicode(uflag) def pretty_print(expr, **kwargs): """Prints expr in pretty form. pprint is just a shortcut for this function. Parameters ========== expr : expression The expression to print. wrap_line : bool, optional (default=True) Line wrapping enabled/disabled. num_columns : int or None, optional (default=None) Number of columns before line breaking (default to None which reads the terminal width), useful when using SymPy without terminal. use_unicode : bool or None, optional (default=None) Use unicode characters, such as the Greek letter pi instead of the string pi. full_prec : bool or string, optional (default="auto") Use full precision. order : bool or string, optional (default=None) Set to 'none' for long expressions if slow; default is None. use_unicode_sqrt_char : bool, optional (default=True) Use compact single-character square root symbol (when unambiguous). root_notation : bool, optional (default=True) Set to 'False' for printing exponents of the form 1/n in fractional form. By default exponent is printed in root form. mat_symbol_style : string, optional (default="plain") Set to "bold" for printing MatrixSymbols using a bold mathematical symbol face. By default the standard face is used. imaginary_unit : string, optional (default="i") Letter to use for imaginary unit when use_unicode is True. Can be "i" (default) or "j". """ print(pretty(expr, **kwargs)) pprint = pretty_print def pager_print(expr, **settings): """Prints expr using the pager, in pretty form. This invokes a pager command using pydoc. Lines are not wrapped automatically. This routine is meant to be used with a pager that allows sideways scrolling, like ``less -S``. Parameters are the same as for ``pretty_print``. If you wish to wrap lines, pass ``num_columns=None`` to auto-detect the width of the terminal. """ from pydoc import pager from locale import getpreferredencoding if 'num_columns' not in settings: settings['num_columns'] = 500000 # disable line wrap pager(pretty(expr, **settings).encode(getpreferredencoding()))
c1373e8ad6f23a82cc7ad52ddec7a90402830bdbed36cc03d9093866be7026b5
"""Symbolic primitives + unicode/ASCII abstraction for pretty.py""" from __future__ import print_function, division import sys import warnings from string import ascii_lowercase, ascii_uppercase unicode_warnings = '' from sympy.core.compatibility import unicode # first, setup unicodedate environment try: import unicodedata def U(name): """unicode character by name or None if not found""" try: u = unicodedata.lookup(name) except KeyError: u = None global unicode_warnings unicode_warnings += 'No \'%s\' in unicodedata\n' % name return u except ImportError: unicode_warnings += 'No unicodedata available\n' U = lambda name: None from sympy.printing.conventions import split_super_sub from sympy.core.alphabets import greeks # prefix conventions when constructing tables # L - LATIN i # G - GREEK beta # D - DIGIT 0 # S - SYMBOL + __all__ = ['greek_unicode', 'sub', 'sup', 'xsym', 'vobj', 'hobj', 'pretty_symbol', 'annotated'] _use_unicode = False def pretty_use_unicode(flag=None): """Set whether pretty-printer should use unicode by default""" global _use_unicode global unicode_warnings if flag is None: return _use_unicode # we know that some letters are not supported in Python 2.X so # ignore those warnings. Remove this when 2.X support is dropped. if unicode_warnings: known = ['LATIN SUBSCRIPT SMALL LETTER %s' % i for i in 'HKLMNPST'] unicode_warnings = '\n'.join([ l for l in unicode_warnings.splitlines() if not any( i in l for i in known)]) # ------------ end of 2.X warning filtering if flag and unicode_warnings: # print warnings (if any) on first unicode usage warnings.warn(unicode_warnings) unicode_warnings = '' use_unicode_prev = _use_unicode _use_unicode = flag return use_unicode_prev def pretty_try_use_unicode(): """See if unicode output is available and leverage it if possible""" try: symbols = [] # see, if we can represent greek alphabet symbols.extend(greek_unicode.values()) # and atoms symbols += atoms_table.values() for s in symbols: if s is None: return # common symbols not present! encoding = getattr(sys.stdout, 'encoding', None) # this happens when e.g. stdout is redirected through a pipe, or is # e.g. a cStringIO.StringO if encoding is None: return # sys.stdout has no encoding # try to encode s.encode(encoding) except UnicodeEncodeError: pass else: pretty_use_unicode(True) def xstr(*args): """call str or unicode depending on current mode""" if _use_unicode: return unicode(*args) else: return str(*args) # GREEK g = lambda l: U('GREEK SMALL LETTER %s' % l.upper()) G = lambda l: U('GREEK CAPITAL LETTER %s' % l.upper()) greek_letters = list(greeks) # make a copy # deal with Unicode's funny spelling of lambda greek_letters[greek_letters.index('lambda')] = 'lamda' # {} greek letter -> (g,G) greek_unicode = dict((L, g(L)) for L in greek_letters) greek_unicode.update((L[0].upper() + L[1:], G(L)) for L in greek_letters) # aliases greek_unicode['lambda'] = greek_unicode['lamda'] greek_unicode['Lambda'] = greek_unicode['Lamda'] greek_unicode['varsigma'] = u'\N{GREEK SMALL LETTER FINAL SIGMA}' # BOLD b = lambda l: U('MATHEMATICAL BOLD SMALL %s' % l.upper()) B = lambda l: U('MATHEMATICAL BOLD CAPITAL %s' % l.upper()) bold_unicode = dict((l, b(l)) for l in ascii_lowercase) bold_unicode.update((L, B(L)) for L in ascii_uppercase) # GREEK BOLD gb = lambda l: U('MATHEMATICAL BOLD SMALL %s' % l.upper()) GB = lambda l: U('MATHEMATICAL BOLD CAPITAL %s' % l.upper()) greek_bold_letters = list(greeks) # make a copy, not strictly required here # deal with Unicode's funny spelling of lambda greek_bold_letters[greek_bold_letters.index('lambda')] = 'lamda' # {} greek letter -> (g,G) greek_bold_unicode = dict((L, g(L)) for L in greek_bold_letters) greek_bold_unicode.update((L[0].upper() + L[1:], G(L)) for L in greek_bold_letters) greek_bold_unicode['lambda'] = greek_unicode['lamda'] greek_bold_unicode['Lambda'] = greek_unicode['Lamda'] greek_bold_unicode['varsigma'] = u'\N{MATHEMATICAL BOLD SMALL FINAL SIGMA}' digit_2txt = { '0': 'ZERO', '1': 'ONE', '2': 'TWO', '3': 'THREE', '4': 'FOUR', '5': 'FIVE', '6': 'SIX', '7': 'SEVEN', '8': 'EIGHT', '9': 'NINE', } symb_2txt = { '+': 'PLUS SIGN', '-': 'MINUS', '=': 'EQUALS SIGN', '(': 'LEFT PARENTHESIS', ')': 'RIGHT PARENTHESIS', '[': 'LEFT SQUARE BRACKET', ']': 'RIGHT SQUARE BRACKET', '{': 'LEFT CURLY BRACKET', '}': 'RIGHT CURLY BRACKET', # non-std '{}': 'CURLY BRACKET', 'sum': 'SUMMATION', 'int': 'INTEGRAL', } # SUBSCRIPT & SUPERSCRIPT LSUB = lambda letter: U('LATIN SUBSCRIPT SMALL LETTER %s' % letter.upper()) GSUB = lambda letter: U('GREEK SUBSCRIPT SMALL LETTER %s' % letter.upper()) DSUB = lambda digit: U('SUBSCRIPT %s' % digit_2txt[digit]) SSUB = lambda symb: U('SUBSCRIPT %s' % symb_2txt[symb]) LSUP = lambda letter: U('SUPERSCRIPT LATIN SMALL LETTER %s' % letter.upper()) DSUP = lambda digit: U('SUPERSCRIPT %s' % digit_2txt[digit]) SSUP = lambda symb: U('SUPERSCRIPT %s' % symb_2txt[symb]) sub = {} # symb -> subscript symbol sup = {} # symb -> superscript symbol # latin subscripts for l in 'aeioruvxhklmnpst': sub[l] = LSUB(l) for l in 'in': sup[l] = LSUP(l) for gl in ['beta', 'gamma', 'rho', 'phi', 'chi']: sub[gl] = GSUB(gl) for d in [str(i) for i in range(10)]: sub[d] = DSUB(d) sup[d] = DSUP(d) for s in '+-=()': sub[s] = SSUB(s) sup[s] = SSUP(s) # Variable modifiers # TODO: Make brackets adjust to height of contents modifier_dict = { # Accents 'mathring': lambda s: center_accent(s, u'\N{COMBINING RING ABOVE}'), 'ddddot': lambda s: center_accent(s, u'\N{COMBINING FOUR DOTS ABOVE}'), 'dddot': lambda s: center_accent(s, u'\N{COMBINING THREE DOTS ABOVE}'), 'ddot': lambda s: center_accent(s, u'\N{COMBINING DIAERESIS}'), 'dot': lambda s: center_accent(s, u'\N{COMBINING DOT ABOVE}'), 'check': lambda s: center_accent(s, u'\N{COMBINING CARON}'), 'breve': lambda s: center_accent(s, u'\N{COMBINING BREVE}'), 'acute': lambda s: center_accent(s, u'\N{COMBINING ACUTE ACCENT}'), 'grave': lambda s: center_accent(s, u'\N{COMBINING GRAVE ACCENT}'), 'tilde': lambda s: center_accent(s, u'\N{COMBINING TILDE}'), 'hat': lambda s: center_accent(s, u'\N{COMBINING CIRCUMFLEX ACCENT}'), 'bar': lambda s: center_accent(s, u'\N{COMBINING OVERLINE}'), 'vec': lambda s: center_accent(s, u'\N{COMBINING RIGHT ARROW ABOVE}'), 'prime': lambda s: s+u'\N{PRIME}', 'prm': lambda s: s+u'\N{PRIME}', # # Faces -- these are here for some compatibility with latex printing # 'bold': lambda s: s, # 'bm': lambda s: s, # 'cal': lambda s: s, # 'scr': lambda s: s, # 'frak': lambda s: s, # Brackets 'norm': lambda s: u'\N{DOUBLE VERTICAL LINE}'+s+u'\N{DOUBLE VERTICAL LINE}', 'avg': lambda s: u'\N{MATHEMATICAL LEFT ANGLE BRACKET}'+s+u'\N{MATHEMATICAL RIGHT ANGLE BRACKET}', 'abs': lambda s: u'\N{VERTICAL LINE}'+s+u'\N{VERTICAL LINE}', 'mag': lambda s: u'\N{VERTICAL LINE}'+s+u'\N{VERTICAL LINE}', } # VERTICAL OBJECTS HUP = lambda symb: U('%s UPPER HOOK' % symb_2txt[symb]) CUP = lambda symb: U('%s UPPER CORNER' % symb_2txt[symb]) MID = lambda symb: U('%s MIDDLE PIECE' % symb_2txt[symb]) EXT = lambda symb: U('%s EXTENSION' % symb_2txt[symb]) HLO = lambda symb: U('%s LOWER HOOK' % symb_2txt[symb]) CLO = lambda symb: U('%s LOWER CORNER' % symb_2txt[symb]) TOP = lambda symb: U('%s TOP' % symb_2txt[symb]) BOT = lambda symb: U('%s BOTTOM' % symb_2txt[symb]) # {} '(' -> (extension, start, end, middle) 1-character _xobj_unicode = { # vertical symbols # (( ext, top, bot, mid ), c1) '(': (( EXT('('), HUP('('), HLO('(') ), '('), ')': (( EXT(')'), HUP(')'), HLO(')') ), ')'), '[': (( EXT('['), CUP('['), CLO('[') ), '['), ']': (( EXT(']'), CUP(']'), CLO(']') ), ']'), '{': (( EXT('{}'), HUP('{'), HLO('{'), MID('{') ), '{'), '}': (( EXT('{}'), HUP('}'), HLO('}'), MID('}') ), '}'), '|': U('BOX DRAWINGS LIGHT VERTICAL'), '<': ((U('BOX DRAWINGS LIGHT VERTICAL'), U('BOX DRAWINGS LIGHT DIAGONAL UPPER RIGHT TO LOWER LEFT'), U('BOX DRAWINGS LIGHT DIAGONAL UPPER LEFT TO LOWER RIGHT')), '<'), '>': ((U('BOX DRAWINGS LIGHT VERTICAL'), U('BOX DRAWINGS LIGHT DIAGONAL UPPER LEFT TO LOWER RIGHT'), U('BOX DRAWINGS LIGHT DIAGONAL UPPER RIGHT TO LOWER LEFT')), '>'), 'lfloor': (( EXT('['), EXT('['), CLO('[') ), U('LEFT FLOOR')), 'rfloor': (( EXT(']'), EXT(']'), CLO(']') ), U('RIGHT FLOOR')), 'lceil': (( EXT('['), CUP('['), EXT('[') ), U('LEFT CEILING')), 'rceil': (( EXT(']'), CUP(']'), EXT(']') ), U('RIGHT CEILING')), 'int': (( EXT('int'), U('TOP HALF INTEGRAL'), U('BOTTOM HALF INTEGRAL') ), U('INTEGRAL')), 'sum': (( U('BOX DRAWINGS LIGHT DIAGONAL UPPER LEFT TO LOWER RIGHT'), '_', U('OVERLINE'), U('BOX DRAWINGS LIGHT DIAGONAL UPPER RIGHT TO LOWER LEFT')), U('N-ARY SUMMATION')), # horizontal objects #'-': '-', '-': U('BOX DRAWINGS LIGHT HORIZONTAL'), '_': U('LOW LINE'), # We used to use this, but LOW LINE looks better for roots, as it's a # little lower (i.e., it lines up with the / perfectly. But perhaps this # one would still be wanted for some cases? # '_': U('HORIZONTAL SCAN LINE-9'), # diagonal objects '\' & '/' ? '/': U('BOX DRAWINGS LIGHT DIAGONAL UPPER RIGHT TO LOWER LEFT'), '\\': U('BOX DRAWINGS LIGHT DIAGONAL UPPER LEFT TO LOWER RIGHT'), } _xobj_ascii = { # vertical symbols # (( ext, top, bot, mid ), c1) '(': (( '|', '/', '\\' ), '('), ')': (( '|', '\\', '/' ), ')'), # XXX this looks ugly # '[': (( '|', '-', '-' ), '['), # ']': (( '|', '-', '-' ), ']'), # XXX not so ugly :( '[': (( '[', '[', '[' ), '['), ']': (( ']', ']', ']' ), ']'), '{': (( '|', '/', '\\', '<' ), '{'), '}': (( '|', '\\', '/', '>' ), '}'), '|': '|', '<': (( '|', '/', '\\' ), '<'), '>': (( '|', '\\', '/' ), '>'), 'int': ( ' | ', ' /', '/ ' ), # horizontal objects '-': '-', '_': '_', # diagonal objects '\' & '/' ? '/': '/', '\\': '\\', } def xobj(symb, length): """Construct spatial object of given length. return: [] of equal-length strings """ if length <= 0: raise ValueError("Length should be greater than 0") # TODO robustify when no unicodedat available if _use_unicode: _xobj = _xobj_unicode else: _xobj = _xobj_ascii vinfo = _xobj[symb] c1 = top = bot = mid = None if not isinstance(vinfo, tuple): # 1 entry ext = vinfo else: if isinstance(vinfo[0], tuple): # (vlong), c1 vlong = vinfo[0] c1 = vinfo[1] else: # (vlong), c1 vlong = vinfo ext = vlong[0] try: top = vlong[1] bot = vlong[2] mid = vlong[3] except IndexError: pass if c1 is None: c1 = ext if top is None: top = ext if bot is None: bot = ext if mid is not None: if (length % 2) == 0: # even height, but we have to print it somehow anyway... # XXX is it ok? length += 1 else: mid = ext if length == 1: return c1 res = [] next = (length - 2)//2 nmid = (length - 2) - next*2 res += [top] res += [ext]*next res += [mid]*nmid res += [ext]*next res += [bot] return res def vobj(symb, height): """Construct vertical object of a given height see: xobj """ return '\n'.join( xobj(symb, height) ) def hobj(symb, width): """Construct horizontal object of a given width see: xobj """ return ''.join( xobj(symb, width) ) # RADICAL # n -> symbol root = { 2: U('SQUARE ROOT'), # U('RADICAL SYMBOL BOTTOM') 3: U('CUBE ROOT'), 4: U('FOURTH ROOT'), } # RATIONAL VF = lambda txt: U('VULGAR FRACTION %s' % txt) # (p,q) -> symbol frac = { (1, 2): VF('ONE HALF'), (1, 3): VF('ONE THIRD'), (2, 3): VF('TWO THIRDS'), (1, 4): VF('ONE QUARTER'), (3, 4): VF('THREE QUARTERS'), (1, 5): VF('ONE FIFTH'), (2, 5): VF('TWO FIFTHS'), (3, 5): VF('THREE FIFTHS'), (4, 5): VF('FOUR FIFTHS'), (1, 6): VF('ONE SIXTH'), (5, 6): VF('FIVE SIXTHS'), (1, 8): VF('ONE EIGHTH'), (3, 8): VF('THREE EIGHTHS'), (5, 8): VF('FIVE EIGHTHS'), (7, 8): VF('SEVEN EIGHTHS'), } # atom symbols _xsym = { '==': ('=', '='), '<': ('<', '<'), '>': ('>', '>'), '<=': ('<=', U('LESS-THAN OR EQUAL TO')), '>=': ('>=', U('GREATER-THAN OR EQUAL TO')), '!=': ('!=', U('NOT EQUAL TO')), ':=': (':=', ':='), '+=': ('+=', '+='), '-=': ('-=', '-='), '*=': ('*=', '*='), '/=': ('/=', '/='), '%=': ('%=', '%='), '*': ('*', U('DOT OPERATOR')), '-->': ('-->', U('EM DASH') + U('EM DASH') + U('BLACK RIGHT-POINTING TRIANGLE') if U('EM DASH') and U('BLACK RIGHT-POINTING TRIANGLE') else None), '==>': ('==>', U('BOX DRAWINGS DOUBLE HORIZONTAL') + U('BOX DRAWINGS DOUBLE HORIZONTAL') + U('BLACK RIGHT-POINTING TRIANGLE') if U('BOX DRAWINGS DOUBLE HORIZONTAL') and U('BOX DRAWINGS DOUBLE HORIZONTAL') and U('BLACK RIGHT-POINTING TRIANGLE') else None), '.': ('*', U('RING OPERATOR')), } def xsym(sym): """get symbology for a 'character'""" op = _xsym[sym] if _use_unicode: return op[1] else: return op[0] # SYMBOLS atoms_table = { # class how-to-display 'Exp1': U('SCRIPT SMALL E'), 'Pi': U('GREEK SMALL LETTER PI'), 'Infinity': U('INFINITY'), 'NegativeInfinity': U('INFINITY') and ('-' + U('INFINITY')), # XXX what to do here #'ImaginaryUnit': U('GREEK SMALL LETTER IOTA'), #'ImaginaryUnit': U('MATHEMATICAL ITALIC SMALL I'), 'ImaginaryUnit': U('DOUBLE-STRUCK ITALIC SMALL I'), 'EmptySet': U('EMPTY SET'), 'Naturals': U('DOUBLE-STRUCK CAPITAL N'), 'Naturals0': (U('DOUBLE-STRUCK CAPITAL N') and (U('DOUBLE-STRUCK CAPITAL N') + U('SUBSCRIPT ZERO'))), 'Integers': U('DOUBLE-STRUCK CAPITAL Z'), 'Rationals': U('DOUBLE-STRUCK CAPITAL Q'), 'Reals': U('DOUBLE-STRUCK CAPITAL R'), 'Complexes': U('DOUBLE-STRUCK CAPITAL C'), 'Union': U('UNION'), 'SymmetricDifference': U('INCREMENT'), 'Intersection': U('INTERSECTION'), 'Ring': U('RING OPERATOR'), 'Modifier Letter Low Ring':U('Modifier Letter Low Ring'), 'EmptySequence': 'EmptySequence', } def pretty_atom(atom_name, default=None, printer=None): """return pretty representation of an atom""" if _use_unicode: if printer is not None and atom_name == 'ImaginaryUnit' and printer._settings['imaginary_unit'] == 'j': return U('DOUBLE-STRUCK ITALIC SMALL J') else: return atoms_table[atom_name] else: if default is not None: return default raise KeyError('only unicode') # send it default printer def pretty_symbol(symb_name, bold_name=False): """return pretty representation of a symbol""" # let's split symb_name into symbol + index # UC: beta1 # UC: f_beta if not _use_unicode: return symb_name name, sups, subs = split_super_sub(symb_name) def translate(s, bold_name) : if bold_name: gG = greek_bold_unicode.get(s) else: gG = greek_unicode.get(s) if gG is not None: return gG for key in sorted(modifier_dict.keys(), key=lambda k:len(k), reverse=True) : if s.lower().endswith(key) and len(s)>len(key): return modifier_dict[key](translate(s[:-len(key)], bold_name)) if bold_name: return ''.join([bold_unicode[c] for c in s]) return s name = translate(name, bold_name) # Let's prettify sups/subs. If it fails at one of them, pretty sups/subs are # not used at all. def pretty_list(l, mapping): result = [] for s in l: pretty = mapping.get(s) if pretty is None: try: # match by separate characters pretty = ''.join([mapping[c] for c in s]) except (TypeError, KeyError): return None result.append(pretty) return result pretty_sups = pretty_list(sups, sup) if pretty_sups is not None: pretty_subs = pretty_list(subs, sub) else: pretty_subs = None # glue the results into one string if pretty_subs is None: # nice formatting of sups/subs did not work if subs: name += '_'+'_'.join([translate(s, bold_name) for s in subs]) if sups: name += '__'+'__'.join([translate(s, bold_name) for s in sups]) return name else: sups_result = ' '.join(pretty_sups) subs_result = ' '.join(pretty_subs) return ''.join([name, sups_result, subs_result]) def annotated(letter): """ Return a stylised drawing of the letter ``letter``, together with information on how to put annotations (super- and subscripts to the left and to the right) on it. See pretty.py functions _print_meijerg, _print_hyper on how to use this information. """ ucode_pics = { 'F': (2, 0, 2, 0, u'\N{BOX DRAWINGS LIGHT DOWN AND RIGHT}\N{BOX DRAWINGS LIGHT HORIZONTAL}\n' u'\N{BOX DRAWINGS LIGHT VERTICAL AND RIGHT}\N{BOX DRAWINGS LIGHT HORIZONTAL}\n' u'\N{BOX DRAWINGS LIGHT UP}'), 'G': (3, 0, 3, 1, u'\N{BOX DRAWINGS LIGHT ARC DOWN AND RIGHT}\N{BOX DRAWINGS LIGHT HORIZONTAL}\N{BOX DRAWINGS LIGHT ARC DOWN AND LEFT}\n' u'\N{BOX DRAWINGS LIGHT VERTICAL}\N{BOX DRAWINGS LIGHT RIGHT}\N{BOX DRAWINGS LIGHT DOWN AND LEFT}\n' u'\N{BOX DRAWINGS LIGHT ARC UP AND RIGHT}\N{BOX DRAWINGS LIGHT HORIZONTAL}\N{BOX DRAWINGS LIGHT ARC UP AND LEFT}') } ascii_pics = { 'F': (3, 0, 3, 0, ' _\n|_\n|\n'), 'G': (3, 0, 3, 1, ' __\n/__\n\\_|') } if _use_unicode: return ucode_pics[letter] else: return ascii_pics[letter] def is_combining(sym): """Check whether symbol is a unicode modifier. See stringPict.width on usage. """ return True if (u'\N{COMBINING GRAVE ACCENT}' <= sym <= u'\N{COMBINING LATIN SMALL LETTER X}' or u'\N{COMBINING LEFT HARPOON ABOVE}' <= sym <= u'\N{COMBINING ASTERISK ABOVE}') else False def center_accent(string, accent): """ Returns a string with accent inserted on the middle character. Useful to put combining accents on symbol names, including multi-character names. Parameters ========== string : string The string to place the accent in. accent : string The combining accent to insert References ========== .. [1] https://en.wikipedia.org/wiki/Combining_character .. [2] https://en.wikipedia.org/wiki/Combining_Diacritical_Marks """ # Accent is placed on the previous character, although it may not always look # like that depending on console midpoint = len(string) // 2 + 1 firstpart = string[:midpoint] secondpart = string[midpoint:] return firstpart + accent + secondpart
00bee68507eb28fd5d041f9ab28bccbfa0ca1b48d2edcd30c602f3c11b03cfb6
"""Prettyprinter by Jurjen Bos. (I hate spammers: mail me at pietjepuk314 at the reverse of ku.oc.oohay). All objects have a method that create a "stringPict", that can be used in the str method for pretty printing. Updates by Jason Gedge (email <my last name> at cs mun ca) - terminal_string() method - minor fixes and changes (mostly to prettyForm) TODO: - Allow left/center/right alignment options for above/below and top/center/bottom alignment options for left/right """ from __future__ import print_function, division from .pretty_symbology import hobj, vobj, xsym, xobj, pretty_use_unicode, is_combining from sympy.core.compatibility import unicode class stringPict(object): """An ASCII picture. The pictures are represented as a list of equal length strings. """ #special value for stringPict.below LINE = 'line' def __init__(self, s, baseline=0): """Initialize from string. Multiline strings are centered. """ self.s = s #picture is a string that just can be printed self.picture = stringPict.equalLengths(s.splitlines()) #baseline is the line number of the "base line" self.baseline = baseline self.binding = None @staticmethod def line_width(line): """Unicode combining symbols (modifiers) are not ever displayed as separate symbols and thus shouldn't be counted """ return sum(1 for sym in line if not is_combining(sym)) @staticmethod def equalLengths(lines): # empty lines if not lines: return [''] width = max(stringPict.line_width(line) for line in lines) return [line.center(width) for line in lines] def height(self): """The height of the picture in characters.""" return len(self.picture) def width(self): """The width of the picture in characters.""" return stringPict.line_width(self.picture[0]) @staticmethod def next(*args): """Put a string of stringPicts next to each other. Returns string, baseline arguments for stringPict. """ #convert everything to stringPicts objects = [] for arg in args: if isinstance(arg, str): arg = stringPict(arg) objects.append(arg) #make a list of pictures, with equal height and baseline newBaseline = max(obj.baseline for obj in objects) newHeightBelowBaseline = max( obj.height() - obj.baseline for obj in objects) newHeight = newBaseline + newHeightBelowBaseline pictures = [] for obj in objects: oneEmptyLine = [' '*obj.width()] basePadding = newBaseline - obj.baseline totalPadding = newHeight - obj.height() pictures.append( oneEmptyLine * basePadding + obj.picture + oneEmptyLine * (totalPadding - basePadding)) result = [''.join(lines) for lines in zip(*pictures)] return '\n'.join(result), newBaseline def right(self, *args): r"""Put pictures next to this one. Returns string, baseline arguments for stringPict. (Multiline) strings are allowed, and are given a baseline of 0. Examples ======== >>> from sympy.printing.pretty.stringpict import stringPict >>> print(stringPict("10").right(" + ",stringPict("1\r-\r2",1))[0]) 1 10 + - 2 """ return stringPict.next(self, *args) def left(self, *args): """Put pictures (left to right) at left. Returns string, baseline arguments for stringPict. """ return stringPict.next(*(args + (self,))) @staticmethod def stack(*args): """Put pictures on top of each other, from top to bottom. Returns string, baseline arguments for stringPict. The baseline is the baseline of the second picture. Everything is centered. Baseline is the baseline of the second picture. Strings are allowed. The special value stringPict.LINE is a row of '-' extended to the width. """ #convert everything to stringPicts; keep LINE objects = [] for arg in args: if arg is not stringPict.LINE and isinstance(arg, str): arg = stringPict(arg) objects.append(arg) #compute new width newWidth = max( obj.width() for obj in objects if obj is not stringPict.LINE) lineObj = stringPict(hobj('-', newWidth)) #replace LINE with proper lines for i, obj in enumerate(objects): if obj is stringPict.LINE: objects[i] = lineObj #stack the pictures, and center the result newPicture = [] for obj in objects: newPicture.extend(obj.picture) newPicture = [line.center(newWidth) for line in newPicture] newBaseline = objects[0].height() + objects[1].baseline return '\n'.join(newPicture), newBaseline def below(self, *args): """Put pictures under this picture. Returns string, baseline arguments for stringPict. Baseline is baseline of top picture Examples ======== >>> from sympy.printing.pretty.stringpict import stringPict >>> print(stringPict("x+3").below( ... stringPict.LINE, '3')[0]) #doctest: +NORMALIZE_WHITESPACE x+3 --- 3 """ s, baseline = stringPict.stack(self, *args) return s, self.baseline def above(self, *args): """Put pictures above this picture. Returns string, baseline arguments for stringPict. Baseline is baseline of bottom picture. """ string, baseline = stringPict.stack(*(args + (self,))) baseline = len(string.splitlines()) - self.height() + self.baseline return string, baseline def parens(self, left='(', right=')', ifascii_nougly=False): """Put parentheses around self. Returns string, baseline arguments for stringPict. left or right can be None or empty string which means 'no paren from that side' """ h = self.height() b = self.baseline # XXX this is a hack -- ascii parens are ugly! if ifascii_nougly and not pretty_use_unicode(): h = 1 b = 0 res = self if left: lparen = stringPict(vobj(left, h), baseline=b) res = stringPict(*lparen.right(self)) if right: rparen = stringPict(vobj(right, h), baseline=b) res = stringPict(*res.right(rparen)) return ('\n'.join(res.picture), res.baseline) def leftslash(self): """Precede object by a slash of the proper size. """ # XXX not used anywhere ? height = max( self.baseline, self.height() - 1 - self.baseline)*2 + 1 slash = '\n'.join( ' '*(height - i - 1) + xobj('/', 1) + ' '*i for i in range(height) ) return self.left(stringPict(slash, height//2)) def root(self, n=None): """Produce a nice root symbol. Produces ugly results for big n inserts. """ # XXX not used anywhere # XXX duplicate of root drawing in pretty.py #put line over expression result = self.above('_'*self.width()) #construct right half of root symbol height = self.height() slash = '\n'.join( ' ' * (height - i - 1) + '/' + ' ' * i for i in range(height) ) slash = stringPict(slash, height - 1) #left half of root symbol if height > 2: downline = stringPict('\\ \n \\', 1) else: downline = stringPict('\\') #put n on top, as low as possible if n is not None and n.width() > downline.width(): downline = downline.left(' '*(n.width() - downline.width())) downline = downline.above(n) #build root symbol root = downline.right(slash) #glue it on at the proper height #normally, the root symbel is as high as self #which is one less than result #this moves the root symbol one down #if the root became higher, the baseline has to grow too root.baseline = result.baseline - result.height() + root.height() return result.left(root) def render(self, * args, **kwargs): """Return the string form of self. Unless the argument line_break is set to False, it will break the expression in a form that can be printed on the terminal without being broken up. """ if kwargs["wrap_line"] is False: return "\n".join(self.picture) if kwargs["num_columns"] is not None: # Read the argument num_columns if it is not None ncols = kwargs["num_columns"] else: # Attempt to get a terminal width ncols = self.terminal_width() ncols -= 2 if ncols <= 0: ncols = 78 # If smaller than the terminal width, no need to correct if self.width() <= ncols: return type(self.picture[0])(self) # for one-line pictures we don't need v-spacers. on the other hand, for # multiline-pictures, we need v-spacers between blocks, compare: # # 2 2 3 | a*c*e + a*c*f + a*d | a*c*e + a*c*f + a*d | 3.14159265358979323 # 6*x *y + 4*x*y + | | *e + a*d*f + b*c*e | 84626433832795 # | *e + a*d*f + b*c*e | + b*c*f + b*d*e + b | # 3 4 4 | | *d*f | # 4*y*x + x + y | + b*c*f + b*d*e + b | | # | | | # | *d*f i = 0 svals = [] do_vspacers = (self.height() > 1) while i < self.width(): svals.extend([ sval[i:i + ncols] for sval in self.picture ]) if do_vspacers: svals.append("") # a vertical spacer i += ncols if svals[-1] == '': del svals[-1] # Get rid of the last spacer return "\n".join(svals) def terminal_width(self): """Return the terminal width if possible, otherwise return 0. """ ncols = 0 try: import curses import io try: curses.setupterm() ncols = curses.tigetnum('cols') except AttributeError: # windows curses doesn't implement setupterm or tigetnum # code below from # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440694 from ctypes import windll, create_string_buffer # stdin handle is -10 # stdout handle is -11 # stderr handle is -12 h = windll.kernel32.GetStdHandle(-12) csbi = create_string_buffer(22) res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi) if res: import struct (bufx, bufy, curx, cury, wattr, left, top, right, bottom, maxx, maxy) = struct.unpack("hhhhHhhhhhh", csbi.raw) ncols = right - left + 1 except curses.error: pass except io.UnsupportedOperation: pass except (ImportError, TypeError): pass return ncols def __eq__(self, o): if isinstance(o, str): return '\n'.join(self.picture) == o elif isinstance(o, stringPict): return o.picture == self.picture return False def __hash__(self): return super(stringPict, self).__hash__() def __str__(self): return str.join('\n', self.picture) def __unicode__(self): return unicode.join(u'\n', self.picture) def __repr__(self): return "stringPict(%r,%d)" % ('\n'.join(self.picture), self.baseline) def __getitem__(self, index): return self.picture[index] def __len__(self): return len(self.s) class prettyForm(stringPict): """ Extension of the stringPict class that knows about basic math applications, optimizing double minus signs. "Binding" is interpreted as follows:: ATOM this is an atom: never needs to be parenthesized FUNC this is a function application: parenthesize if added (?) DIV this is a division: make wider division if divided POW this is a power: only parenthesize if exponent MUL this is a multiplication: parenthesize if powered ADD this is an addition: parenthesize if multiplied or powered NEG this is a negative number: optimize if added, parenthesize if multiplied or powered OPEN this is an open object: parenthesize if added, multiplied, or powered (example: Piecewise) """ ATOM, FUNC, DIV, POW, MUL, ADD, NEG, OPEN = range(8) def __init__(self, s, baseline=0, binding=0, unicode=None): """Initialize from stringPict and binding power.""" stringPict.__init__(self, s, baseline) self.binding = binding self.unicode = unicode or s # Note: code to handle subtraction is in _print_Add def __add__(self, *others): """Make a pretty addition. Addition of negative numbers is simplified. """ arg = self if arg.binding > prettyForm.NEG: arg = stringPict(*arg.parens()) result = [arg] for arg in others: #add parentheses for weak binders if arg.binding > prettyForm.NEG: arg = stringPict(*arg.parens()) #use existing minus sign if available if arg.binding != prettyForm.NEG: result.append(' + ') result.append(arg) return prettyForm(binding=prettyForm.ADD, *stringPict.next(*result)) def __div__(self, den, slashed=False): """Make a pretty division; stacked or slashed. """ if slashed: raise NotImplementedError("Can't do slashed fraction yet") num = self if num.binding == prettyForm.DIV: num = stringPict(*num.parens()) if den.binding == prettyForm.DIV: den = stringPict(*den.parens()) if num.binding==prettyForm.NEG: num = num.right(" ")[0] return prettyForm(binding=prettyForm.DIV, *stringPict.stack( num, stringPict.LINE, den)) def __truediv__(self, o): return self.__div__(o) def __mul__(self, *others): """Make a pretty multiplication. Parentheses are needed around +, - and neg. """ quantity = { 'degree': u"\N{DEGREE SIGN}" } if len(others) == 0: return self # We aren't actually multiplying... So nothing to do here. args = self if args.binding > prettyForm.MUL: arg = stringPict(*args.parens()) result = [args] for arg in others: if arg.picture[0] not in quantity.values(): result.append(xsym('*')) #add parentheses for weak binders if arg.binding > prettyForm.MUL: arg = stringPict(*arg.parens()) result.append(arg) len_res = len(result) for i in range(len_res): if i < len_res - 1 and result[i] == '-1' and result[i + 1] == xsym('*'): # substitute -1 by -, like in -1*x -> -x result.pop(i) result.pop(i) result.insert(i, '-') if result[0][0] == '-': # if there is a - sign in front of all # This test was failing to catch a prettyForm.__mul__(prettyForm("-1", 0, 6)) being negative bin = prettyForm.NEG if result[0] == '-': right = result[1] if right.picture[right.baseline][0] == '-': result[0] = '- ' else: bin = prettyForm.MUL return prettyForm(binding=bin, *stringPict.next(*result)) def __repr__(self): return "prettyForm(%r,%d,%d)" % ( '\n'.join(self.picture), self.baseline, self.binding) def __pow__(self, b): """Make a pretty power. """ a = self use_inline_func_form = False if b.binding == prettyForm.POW: b = stringPict(*b.parens()) if a.binding > prettyForm.FUNC: a = stringPict(*a.parens()) elif a.binding == prettyForm.FUNC: # heuristic for when to use inline power if b.height() > 1: a = stringPict(*a.parens()) else: use_inline_func_form = True if use_inline_func_form: # 2 # sin + + (x) b.baseline = a.prettyFunc.baseline + b.height() func = stringPict(*a.prettyFunc.right(b)) return prettyForm(*func.right(a.prettyArgs)) else: # 2 <-- top # (x+y) <-- bot top = stringPict(*b.left(' '*a.width())) bot = stringPict(*a.right(' '*b.width())) return prettyForm(binding=prettyForm.POW, *bot.above(top)) simpleFunctions = ["sin", "cos", "tan"] @staticmethod def apply(function, *args): """Functions of one or more variables. """ if function in prettyForm.simpleFunctions: #simple function: use only space if possible assert len( args) == 1, "Simple function %s must have 1 argument" % function arg = args[0].__pretty__() if arg.binding <= prettyForm.DIV: #optimization: no parentheses necessary return prettyForm(binding=prettyForm.FUNC, *arg.left(function + ' ')) argumentList = [] for arg in args: argumentList.append(',') argumentList.append(arg.__pretty__()) argumentList = stringPict(*stringPict.next(*argumentList[1:])) argumentList = stringPict(*argumentList.parens()) return prettyForm(binding=prettyForm.ATOM, *argumentList.left(function))
039ee071956c0468a6e3aa82e24c452391352a5cc2eeef6a1e9c94298a8a2427
from typing import Any, Dict from sympy.testing.pytest import raises from sympy import (symbols, Function, Integer, Matrix, Abs, Rational, Float, S, WildFunction, ImmutableDenseMatrix, sin, true, false, ones, sqrt, root, AlgebraicNumber, Symbol, Dummy, Wild, MatrixSymbol) from sympy.combinatorics import Cycle, Permutation from sympy.core.compatibility import exec_ from sympy.geometry import Point, Ellipse from sympy.printing import srepr from sympy.polys import ring, field, ZZ, QQ, lex, grlex, Poly from sympy.polys.polyclasses import DMP from sympy.polys.agca.extensions import FiniteExtension x, y = symbols('x,y') # eval(srepr(expr)) == expr has to succeed in the right environment. The right # environment is the scope of "from sympy import *" for most cases. ENV = {} # type: Dict[str, Any] exec_("from sympy import *", ENV) def sT(expr, string, import_stmt=None): """ sT := sreprTest Tests that srepr delivers the expected string and that the condition eval(srepr(expr))==expr holds. """ if import_stmt is None: ENV2 = ENV else: ENV2 = ENV.copy() exec_(import_stmt, ENV2) assert srepr(expr) == string assert eval(string, ENV2) == expr def test_printmethod(): class R(Abs): def _sympyrepr(self, printer): return "foo(%s)" % printer._print(self.args[0]) assert srepr(R(x)) == "foo(Symbol('x'))" def test_Add(): sT(x + y, "Add(Symbol('x'), Symbol('y'))") assert srepr(x**2 + 1, order='lex') == "Add(Pow(Symbol('x'), Integer(2)), Integer(1))" assert srepr(x**2 + 1, order='old') == "Add(Integer(1), Pow(Symbol('x'), Integer(2)))" def test_more_than_255_args_issue_10259(): from sympy import Add, Mul for op in (Add, Mul): expr = op(*symbols('x:256')) assert eval(srepr(expr)) == expr def test_Function(): sT(Function("f")(x), "Function('f')(Symbol('x'))") # test unapplied Function sT(Function('f'), "Function('f')") sT(sin(x), "sin(Symbol('x'))") sT(sin, "sin") def test_Geometry(): sT(Point(0, 0), "Point2D(Integer(0), Integer(0))") sT(Ellipse(Point(0, 0), 5, 1), "Ellipse(Point2D(Integer(0), Integer(0)), Integer(5), Integer(1))") # TODO more tests def test_Singletons(): sT(S.Catalan, 'Catalan') sT(S.ComplexInfinity, 'zoo') sT(S.EulerGamma, 'EulerGamma') sT(S.Exp1, 'E') sT(S.GoldenRatio, 'GoldenRatio') sT(S.TribonacciConstant, 'TribonacciConstant') sT(S.Half, 'Rational(1, 2)') sT(S.ImaginaryUnit, 'I') sT(S.Infinity, 'oo') sT(S.NaN, 'nan') sT(S.NegativeInfinity, '-oo') sT(S.NegativeOne, 'Integer(-1)') sT(S.One, 'Integer(1)') sT(S.Pi, 'pi') sT(S.Zero, 'Integer(0)') def test_Integer(): sT(Integer(4), "Integer(4)") def test_list(): sT([x, Integer(4)], "[Symbol('x'), Integer(4)]") def test_Matrix(): for cls, name in [(Matrix, "MutableDenseMatrix"), (ImmutableDenseMatrix, "ImmutableDenseMatrix")]: sT(cls([[x**+1, 1], [y, x + y]]), "%s([[Symbol('x'), Integer(1)], [Symbol('y'), Add(Symbol('x'), Symbol('y'))]])" % name) sT(cls(), "%s([])" % name) sT(cls([[x**+1, 1], [y, x + y]]), "%s([[Symbol('x'), Integer(1)], [Symbol('y'), Add(Symbol('x'), Symbol('y'))]])" % name) def test_empty_Matrix(): sT(ones(0, 3), "MutableDenseMatrix(0, 3, [])") sT(ones(4, 0), "MutableDenseMatrix(4, 0, [])") sT(ones(0, 0), "MutableDenseMatrix([])") def test_Rational(): sT(Rational(1, 3), "Rational(1, 3)") sT(Rational(-1, 3), "Rational(-1, 3)") def test_Float(): sT(Float('1.23', dps=3), "Float('1.22998', precision=13)") sT(Float('1.23456789', dps=9), "Float('1.23456788994', precision=33)") sT(Float('1.234567890123456789', dps=19), "Float('1.234567890123456789013', precision=66)") sT(Float('0.60038617995049726', dps=15), "Float('0.60038617995049726', precision=53)") sT(Float('1.23', precision=13), "Float('1.22998', precision=13)") sT(Float('1.23456789', precision=33), "Float('1.23456788994', precision=33)") sT(Float('1.234567890123456789', precision=66), "Float('1.234567890123456789013', precision=66)") sT(Float('0.60038617995049726', precision=53), "Float('0.60038617995049726', precision=53)") sT(Float('0.60038617995049726', 15), "Float('0.60038617995049726', precision=53)") def test_Symbol(): sT(x, "Symbol('x')") sT(y, "Symbol('y')") sT(Symbol('x', negative=True), "Symbol('x', negative=True)") def test_Symbol_two_assumptions(): x = Symbol('x', negative=0, integer=1) # order could vary s1 = "Symbol('x', integer=True, negative=False)" s2 = "Symbol('x', negative=False, integer=True)" assert srepr(x) in (s1, s2) assert eval(srepr(x), ENV) == x def test_Symbol_no_special_commutative_treatment(): sT(Symbol('x'), "Symbol('x')") sT(Symbol('x', commutative=False), "Symbol('x', commutative=False)") sT(Symbol('x', commutative=0), "Symbol('x', commutative=False)") sT(Symbol('x', commutative=True), "Symbol('x', commutative=True)") sT(Symbol('x', commutative=1), "Symbol('x', commutative=True)") def test_Wild(): sT(Wild('x', even=True), "Wild('x', even=True)") def test_Dummy(): d = Dummy('d') sT(d, "Dummy('d', dummy_index=%s)" % str(d.dummy_index)) def test_Dummy_assumption(): d = Dummy('d', nonzero=True) assert d == eval(srepr(d)) s1 = "Dummy('d', dummy_index=%s, nonzero=True)" % str(d.dummy_index) s2 = "Dummy('d', nonzero=True, dummy_index=%s)" % str(d.dummy_index) assert srepr(d) in (s1, s2) def test_Dummy_from_Symbol(): # should not get the full dictionary of assumptions n = Symbol('n', integer=True) d = n.as_dummy() assert srepr(d ) == "Dummy('n', dummy_index=%s)" % str(d.dummy_index) def test_tuple(): sT((x,), "(Symbol('x'),)") sT((x, y), "(Symbol('x'), Symbol('y'))") def test_WildFunction(): sT(WildFunction('w'), "WildFunction('w')") def test_settins(): raises(TypeError, lambda: srepr(x, method="garbage")) def test_Mul(): sT(3*x**3*y, "Mul(Integer(3), Pow(Symbol('x'), Integer(3)), Symbol('y'))") assert srepr(3*x**3*y, order='old') == "Mul(Integer(3), Symbol('y'), Pow(Symbol('x'), Integer(3)))" def test_AlgebraicNumber(): a = AlgebraicNumber(sqrt(2)) sT(a, "AlgebraicNumber(Pow(Integer(2), Rational(1, 2)), [Integer(1), Integer(0)])") a = AlgebraicNumber(root(-2, 3)) sT(a, "AlgebraicNumber(Pow(Integer(-2), Rational(1, 3)), [Integer(1), Integer(0)])") def test_PolyRing(): assert srepr(ring("x", ZZ, lex)[0]) == "PolyRing((Symbol('x'),), ZZ, lex)" assert srepr(ring("x,y", QQ, grlex)[0]) == "PolyRing((Symbol('x'), Symbol('y')), QQ, grlex)" assert srepr(ring("x,y,z", ZZ["t"], lex)[0]) == "PolyRing((Symbol('x'), Symbol('y'), Symbol('z')), ZZ[t], lex)" def test_FracField(): assert srepr(field("x", ZZ, lex)[0]) == "FracField((Symbol('x'),), ZZ, lex)" assert srepr(field("x,y", QQ, grlex)[0]) == "FracField((Symbol('x'), Symbol('y')), QQ, grlex)" assert srepr(field("x,y,z", ZZ["t"], lex)[0]) == "FracField((Symbol('x'), Symbol('y'), Symbol('z')), ZZ[t], lex)" def test_PolyElement(): R, x, y = ring("x,y", ZZ) assert srepr(3*x**2*y + 1) == "PolyElement(PolyRing((Symbol('x'), Symbol('y')), ZZ, lex), [((2, 1), 3), ((0, 0), 1)])" def test_FracElement(): F, x, y = field("x,y", ZZ) assert srepr((3*x**2*y + 1)/(x - y**2)) == "FracElement(FracField((Symbol('x'), Symbol('y')), ZZ, lex), [((2, 1), 3), ((0, 0), 1)], [((1, 0), 1), ((0, 2), -1)])" def test_FractionField(): assert srepr(QQ.frac_field(x)) == \ "FractionField(FracField((Symbol('x'),), QQ, lex))" assert srepr(QQ.frac_field(x, y, order=grlex)) == \ "FractionField(FracField((Symbol('x'), Symbol('y')), QQ, grlex))" def test_PolynomialRingBase(): assert srepr(ZZ.old_poly_ring(x)) == \ "GlobalPolynomialRing(ZZ, Symbol('x'))" assert srepr(ZZ[x].old_poly_ring(y)) == \ "GlobalPolynomialRing(ZZ[x], Symbol('y'))" assert srepr(QQ.frac_field(x).old_poly_ring(y)) == \ "GlobalPolynomialRing(FractionField(FracField((Symbol('x'),), QQ, lex)), Symbol('y'))" def test_DMP(): assert srepr(DMP([1, 2], ZZ)) == 'DMP([1, 2], ZZ)' assert srepr(ZZ.old_poly_ring(x)([1, 2])) == \ "DMP([1, 2], ZZ, ring=GlobalPolynomialRing(ZZ, Symbol('x')))" def test_FiniteExtension(): assert srepr(FiniteExtension(Poly(x**2 + 1, x))) == \ "FiniteExtension(Poly(x**2 + 1, x, domain='ZZ'))" def test_ExtensionElement(): A = FiniteExtension(Poly(x**2 + 1, x)) assert srepr(A.generator) == \ "ExtElem(DMP([1, 0], ZZ, ring=GlobalPolynomialRing(ZZ, Symbol('x'))), FiniteExtension(Poly(x**2 + 1, x, domain='ZZ')))" def test_BooleanAtom(): assert srepr(true) == "true" assert srepr(false) == "false" def test_Integers(): sT(S.Integers, "Integers") def test_Naturals(): sT(S.Naturals, "Naturals") def test_Naturals0(): sT(S.Naturals0, "Naturals0") def test_Reals(): sT(S.Reals, "Reals") def test_matrix_expressions(): n = symbols('n', integer=True) A = MatrixSymbol("A", n, n) B = MatrixSymbol("B", n, n) sT(A, "MatrixSymbol(Symbol('A'), Symbol('n', integer=True), Symbol('n', integer=True))") sT(A*B, "MatMul(MatrixSymbol(Symbol('A'), Symbol('n', integer=True), Symbol('n', integer=True)), MatrixSymbol(Symbol('B'), Symbol('n', integer=True), Symbol('n', integer=True)))") sT(A + B, "MatAdd(MatrixSymbol(Symbol('A'), Symbol('n', integer=True), Symbol('n', integer=True)), MatrixSymbol(Symbol('B'), Symbol('n', integer=True), Symbol('n', integer=True)))") def test_Cycle(): # FIXME: sT fails because Cycle is not immutable and calling srepr(Cycle(1, 2)) # adds keys to the Cycle dict (GH-17661) #import_stmt = "from sympy.combinatorics import Cycle" #sT(Cycle(1, 2), "Cycle(1, 2)", import_stmt) assert srepr(Cycle(1, 2)) == "Cycle(1, 2)" def test_Permutation(): import_stmt = "from sympy.combinatorics import Permutation" sT(Permutation(1, 2), "Permutation(1, 2)", import_stmt)
f994472880c2699cfff1abb5c9d953e3819fa03003498ab52a45ed7dd41284d0
from __future__ import absolute_import 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, KroneckerDelta, 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' assert prntr.module_imports == {'math': {'pi'}} assert prntr.doprint(x**Rational(1, 2)) == 'math.sqrt(x)' assert prntr.doprint(sqrt(x)) == 'math.sqrt(x)' assert prntr.module_imports == {'math': {'pi', 'sqrt'}} assert prntr.doprint(acos(x)) == 'math.acos(x)' assert prntr.doprint(Assignment(x, 2)) == 'x = 2' assert prntr.doprint(Piecewise((1, Eq(x, 0)), (2, x>6))) == '((1) if (x == 0) else (2) if (x > 6) else None)' assert prntr.doprint(Piecewise((2, Le(x, 0)), (3, Gt(x, 0)), evaluate=False)) == '((2) if (x <= 0) else'\ ' (3) if (x > 0) else None)' assert prntr.doprint(sign(x)) == '(0.0 if x == 0 else math.copysign(1, x))' assert prntr.doprint(p[0, 1]) == 'p[0, 1]' assert prntr.doprint(KroneckerDelta(x,y)) == '(1 if x == y else 0)' def test_PythonCodePrinter_standard(): import sys prntr = PythonCodePrinter({'standard':None}) python_version = sys.version_info.major if python_version == 2: assert prntr.standard == 'python2' if python_version == 3: assert prntr.standard == 'python3' raises(ValueError, lambda: PythonCodePrinter({'standard':'python4'})) def test_MpmathPrinter(): p = MpmathPrinter() assert p.doprint(sign(x)) == 'mpmath.sign(x)' assert p.doprint(Rational(1, 2)) == 'mpmath.mpf(1)/mpmath.mpf(2)' assert p.doprint(S.Exp1) == 'mpmath.e' assert p.doprint(S.Pi) == 'mpmath.pi' assert p.doprint(S.GoldenRatio) == 'mpmath.phi' assert p.doprint(S.EulerGamma) == 'mpmath.euler' assert p.doprint(S.NaN) == 'mpmath.nan' assert p.doprint(S.Infinity) == 'mpmath.inf' assert p.doprint(S.NegativeInfinity) == 'mpmath.ninf' def test_NumPyPrinter(): from sympy import (Lambda, ZeroMatrix, OneMatrix, FunctionMatrix, HadamardProduct, KroneckerProduct, Adjoint, DiagonalOf, DiagMatrix, DiagonalMatrix) from sympy.abc import a, b p = NumPyPrinter() assert p.doprint(sign(x)) == 'numpy.sign(x)' A = MatrixSymbol("A", 2, 2) B = MatrixSymbol("B", 2, 2) C = MatrixSymbol("C", 1, 5) D = MatrixSymbol("D", 3, 4) assert p.doprint(A**(-1)) == "numpy.linalg.inv(A)" assert p.doprint(A**5) == "numpy.linalg.matrix_power(A, 5)" assert p.doprint(Identity(3)) == "numpy.eye(3)" u = MatrixSymbol('x', 2, 1) v = MatrixSymbol('y', 2, 1) assert p.doprint(MatrixSolve(A, u)) == 'numpy.linalg.solve(A, x)' assert p.doprint(MatrixSolve(A, u) + v) == 'numpy.linalg.solve(A, x) + y' assert p.doprint(ZeroMatrix(2, 3)) == "numpy.zeros((2, 3))" assert p.doprint(OneMatrix(2, 3)) == "numpy.ones((2, 3))" assert p.doprint(FunctionMatrix(4, 5, Lambda((a, b), a + b))) == \ "numpy.fromfunction(lambda a, b: a + b, (4, 5))" assert p.doprint(HadamardProduct(A, B)) == "numpy.multiply(A, B)" assert p.doprint(KroneckerProduct(A, B)) == "numpy.kron(A, B)" assert p.doprint(Adjoint(A)) == "numpy.conjugate(numpy.transpose(A))" assert p.doprint(DiagonalOf(A)) == "numpy.reshape(numpy.diag(A), (-1, 1))" assert p.doprint(DiagMatrix(C)) == "numpy.diagflat(C)" assert p.doprint(DiagonalMatrix(D)) == "numpy.multiply(D, numpy.eye(3, 4))" # Workaround for numpy negative integer power errors assert p.doprint(x**-1) == 'x**(-1.0)' assert p.doprint(x**-2) == 'x**(-2.0)' assert p.doprint(S.Exp1) == 'numpy.e' assert p.doprint(S.Pi) == 'numpy.pi' assert p.doprint(S.EulerGamma) == 'numpy.euler_gamma' assert p.doprint(S.NaN) == 'numpy.nan' assert p.doprint(S.Infinity) == 'numpy.PINF' assert p.doprint(S.NegativeInfinity) == 'numpy.NINF' def test_SciPyPrinter(): p = SciPyPrinter() expr = acos(x) assert 'numpy' not in p.module_imports assert p.doprint(expr) == 'numpy.arccos(x)' assert 'numpy' in p.module_imports assert not any(m.startswith('scipy') for m in p.module_imports) smat = SparseMatrix(2, 5, {(0, 1): 3}) assert p.doprint(smat) == 'scipy.sparse.coo_matrix([3], ([0], [1]), shape=(2, 5))' assert 'scipy.sparse' in p.module_imports assert p.doprint(S.GoldenRatio) == 'scipy.constants.golden_ratio' assert p.doprint(S.Pi) == 'scipy.constants.pi' assert p.doprint(S.Exp1) == 'numpy.e' 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_') def test_sqrt(): prntr = PythonCodePrinter() assert prntr._print_Pow(sqrt(x), rational=False) == 'math.sqrt(x)' assert prntr._print_Pow(1/sqrt(x), rational=False) == '1/math.sqrt(x)' prntr = PythonCodePrinter({'standard' : 'python2'}) assert prntr._print_Pow(sqrt(x), rational=True) == 'x**(1./2.)' assert prntr._print_Pow(1/sqrt(x), rational=True) == 'x**(-1./2.)' prntr = PythonCodePrinter({'standard' : 'python3'}) assert prntr._print_Pow(sqrt(x), rational=True) == 'x**(1/2)' assert prntr._print_Pow(1/sqrt(x), rational=True) == 'x**(-1/2)' prntr = MpmathPrinter() assert prntr._print_Pow(sqrt(x), rational=False) == 'mpmath.sqrt(x)' assert prntr._print_Pow(sqrt(x), rational=True) == \ "x**(mpmath.mpf(1)/mpmath.mpf(2))" prntr = NumPyPrinter() assert prntr._print_Pow(sqrt(x), rational=False) == 'numpy.sqrt(x)' assert prntr._print_Pow(sqrt(x), rational=True) == 'x**(1/2)' prntr = SciPyPrinter() assert prntr._print_Pow(sqrt(x), rational=False) == 'numpy.sqrt(x)' assert prntr._print_Pow(sqrt(x), rational=True) == 'x**(1/2)' prntr = SymPyPrinter() assert prntr._print_Pow(sqrt(x), rational=False) == 'sympy.sqrt(x)' assert prntr._print_Pow(sqrt(x), rational=True) == 'x**(1/2)' class CustomPrintedObject(Expr): def _numpycode(self, printer): return 'numpy' def _mpmathcode(self, printer): return 'mpmath' def test_printmethod(): obj = CustomPrintedObject() assert NumPyPrinter().doprint(obj) == 'numpy' assert MpmathPrinter().doprint(obj) == 'mpmath' def test_codegen_ast_nodes(): assert pycode(none) == 'None' def test_issue_14283(): prntr = PythonCodePrinter() assert prntr.doprint(zoo) == "float('nan')" assert prntr.doprint(-oo) == "float('-inf')" def test_NumPyPrinter_print_seq(): n = NumPyPrinter() assert n._print_seq(range(2)) == '(0, 1,)' def test_issue_16535_16536(): from sympy import lowergamma, uppergamma a = symbols('a') expr1 = lowergamma(a, x) expr2 = uppergamma(a, x) prntr = SciPyPrinter() assert prntr.doprint(expr1) == 'scipy.special.gamma(a)*scipy.special.gammainc(a, x)' assert prntr.doprint(expr2) == 'scipy.special.gamma(a)*scipy.special.gammaincc(a, x)' prntr = NumPyPrinter() assert prntr.doprint(expr1) == ' # Not supported in Python with NumPy:\n # lowergamma\nlowergamma(a, x)' assert prntr.doprint(expr2) == ' # Not supported in Python with NumPy:\n # uppergamma\nuppergamma(a, x)' prntr = PythonCodePrinter() assert prntr.doprint(expr1) == ' # Not supported in Python:\n # lowergamma\nlowergamma(a, x)' assert prntr.doprint(expr2) == ' # Not supported in Python:\n # uppergamma\nuppergamma(a, x)' def test_fresnel_integrals(): from sympy import fresnelc, fresnels expr1 = fresnelc(x) expr2 = fresnels(x) prntr = SciPyPrinter() assert prntr.doprint(expr1) == 'scipy.special.fresnel(x)[1]' assert prntr.doprint(expr2) == 'scipy.special.fresnel(x)[0]' prntr = NumPyPrinter() assert prntr.doprint(expr1) == ' # Not supported in Python with NumPy:\n # fresnelc\nfresnelc(x)' assert prntr.doprint(expr2) == ' # Not supported in Python with NumPy:\n # fresnels\nfresnels(x)' prntr = PythonCodePrinter() assert prntr.doprint(expr1) == ' # Not supported in Python:\n # fresnelc\nfresnelc(x)' assert prntr.doprint(expr2) == ' # Not supported in Python:\n # fresnels\nfresnels(x)' prntr = MpmathPrinter() assert prntr.doprint(expr1) == 'mpmath.fresnelc(x)' assert prntr.doprint(expr2) == 'mpmath.fresnels(x)' def test_beta(): from sympy import beta expr = beta(x, y) prntr = SciPyPrinter() assert prntr.doprint(expr) == 'scipy.special.beta(x, y)' prntr = NumPyPrinter() assert prntr.doprint(expr) == 'math.gamma(x)*math.gamma(y)/math.gamma(x + y)' prntr = PythonCodePrinter() assert prntr.doprint(expr) == 'math.gamma(x)*math.gamma(y)/math.gamma(x + y)' prntr = PythonCodePrinter({'allow_unknown_functions': True}) assert prntr.doprint(expr) == 'math.gamma(x)*math.gamma(y)/math.gamma(x + y)' prntr = MpmathPrinter() assert prntr.doprint(expr) == 'mpmath.beta(x, y)'
a7ecac91eef6552b89ae7bd4e0af62d72b343e957d903d2c420bcab378b47dcc
from sympy import (Abs, Catalan, cos, Derivative, E, EulerGamma, exp, factorial, factorial2, Function, GoldenRatio, TribonacciConstant, I, Integer, Integral, Interval, Lambda, Limit, Matrix, nan, O, oo, pi, Pow, Rational, Float, Rel, S, sin, SparseMatrix, sqrt, summation, Sum, Symbol, symbols, Wild, WildFunction, zeta, zoo, Dummy, Dict, Tuple, FiniteSet, factor, subfactorial, true, false, Equivalent, Xor, Complement, SymmetricDifference, AccumBounds, UnevaluatedExpr, Eq, Ne, Quaternion, Subs, MatrixSymbol) from sympy.core import Expr, Mul from sympy.physics.units import second, joule from sympy.polys import Poly, rootof, RootSum, groebner, ring, field, ZZ, QQ, lex, grlex from sympy.geometry import Point, Circle, Polygon, Ellipse, Triangle from sympy.testing.pytest import raises from sympy.printing import sstr, sstrrepr, StrPrinter from sympy.core.trace import Tr x, y, z, w, t = symbols('x,y,z,w,t') d = Dummy('d') def test_printmethod(): class R(Abs): def _sympystr(self, printer): return "foo(%s)" % printer._print(self.args[0]) assert sstr(R(x)) == "foo(x)" class R(Abs): def _sympystr(self, printer): return "foo" assert sstr(R(x)) == "foo" def test_Abs(): assert str(Abs(x)) == "Abs(x)" assert str(Abs(Rational(1, 6))) == "1/6" assert str(Abs(Rational(-1, 6))) == "1/6" def test_Add(): assert str(x + y) == "x + y" assert str(x + 1) == "x + 1" assert str(x + x**2) == "x**2 + x" assert str(5 + x + y + x*y + x**2 + y**2) == "x**2 + x*y + x + y**2 + y + 5" assert str(1 + x + x**2/2 + x**3/3) == "x**3/3 + x**2/2 + x + 1" assert str(2*x - 7*x**2 + 2 + 3*y) == "-7*x**2 + 2*x + 3*y + 2" assert str(x - y) == "x - y" assert str(2 - x) == "2 - x" assert str(x - 2) == "x - 2" assert str(x - y - z - w) == "-w + x - y - z" assert str(x - z*y**2*z*w) == "-w*y**2*z**2 + x" assert str(x - 1*y*x*y) == "-x*y**2 + x" assert str(sin(x).series(x, 0, 15)) == "x - x**3/6 + x**5/120 - x**7/5040 + x**9/362880 - x**11/39916800 + x**13/6227020800 + O(x**15)" def test_Catalan(): assert str(Catalan) == "Catalan" def test_ComplexInfinity(): assert str(zoo) == "zoo" def test_Derivative(): assert str(Derivative(x, y)) == "Derivative(x, y)" assert str(Derivative(x**2, x, evaluate=False)) == "Derivative(x**2, x)" assert str(Derivative( x**2/y, x, y, evaluate=False)) == "Derivative(x**2/y, x, y)" def test_dict(): assert str({1: 1 + x}) == sstr({1: 1 + x}) == "{1: x + 1}" assert str({1: x**2, 2: y*x}) in ("{1: x**2, 2: x*y}", "{2: x*y, 1: x**2}") assert sstr({1: x**2, 2: y*x}) == "{1: x**2, 2: x*y}" def test_Dict(): assert str(Dict({1: 1 + x})) == sstr({1: 1 + x}) == "{1: x + 1}" assert str(Dict({1: x**2, 2: y*x})) in ( "{1: x**2, 2: x*y}", "{2: x*y, 1: x**2}") assert sstr(Dict({1: x**2, 2: y*x})) == "{1: x**2, 2: x*y}" def test_Dummy(): assert str(d) == "_d" assert str(d + x) == "_d + x" def test_EulerGamma(): assert str(EulerGamma) == "EulerGamma" def test_Exp(): assert str(E) == "E" def test_factorial(): n = Symbol('n', integer=True) assert str(factorial(-2)) == "zoo" assert str(factorial(0)) == "1" assert str(factorial(7)) == "5040" assert str(factorial(n)) == "factorial(n)" assert str(factorial(2*n)) == "factorial(2*n)" assert str(factorial(factorial(n))) == 'factorial(factorial(n))' assert str(factorial(factorial2(n))) == 'factorial(factorial2(n))' assert str(factorial2(factorial(n))) == 'factorial2(factorial(n))' assert str(factorial2(factorial2(n))) == 'factorial2(factorial2(n))' assert str(subfactorial(3)) == "2" assert str(subfactorial(n)) == "subfactorial(n)" assert str(subfactorial(2*n)) == "subfactorial(2*n)" def test_Function(): f = Function('f') fx = f(x) w = WildFunction('w') assert str(f) == "f" assert str(fx) == "f(x)" assert str(w) == "w_" def test_Geometry(): assert sstr(Point(0, 0)) == 'Point2D(0, 0)' assert sstr(Circle(Point(0, 0), 3)) == 'Circle(Point2D(0, 0), 3)' assert sstr(Ellipse(Point(1, 2), 3, 4)) == 'Ellipse(Point2D(1, 2), 3, 4)' assert sstr(Triangle(Point(1, 1), Point(7, 8), Point(0, -1))) == \ 'Triangle(Point2D(1, 1), Point2D(7, 8), Point2D(0, -1))' assert sstr(Polygon(Point(5, 6), Point(-2, -3), Point(0, 0), Point(4, 7))) == \ 'Polygon(Point2D(5, 6), Point2D(-2, -3), Point2D(0, 0), Point2D(4, 7))' assert sstr(Triangle(Point(0, 0), Point(1, 0), Point(0, 1)), sympy_integers=True) == \ 'Triangle(Point2D(S(0), S(0)), Point2D(S(1), S(0)), Point2D(S(0), S(1)))' assert sstr(Ellipse(Point(1, 2), 3, 4), sympy_integers=True) == \ 'Ellipse(Point2D(S(1), S(2)), S(3), S(4))' def test_GoldenRatio(): assert str(GoldenRatio) == "GoldenRatio" def test_TribonacciConstant(): assert str(TribonacciConstant) == "TribonacciConstant" def test_ImaginaryUnit(): assert str(I) == "I" def test_Infinity(): assert str(oo) == "oo" assert str(oo*I) == "oo*I" def test_Integer(): assert str(Integer(-1)) == "-1" assert str(Integer(1)) == "1" assert str(Integer(-3)) == "-3" assert str(Integer(0)) == "0" assert str(Integer(25)) == "25" def test_Integral(): assert str(Integral(sin(x), y)) == "Integral(sin(x), y)" assert str(Integral(sin(x), (y, 0, 1))) == "Integral(sin(x), (y, 0, 1))" def test_Interval(): n = (S.NegativeInfinity, 1, 2, S.Infinity) for i in range(len(n)): for j in range(i + 1, len(n)): for l in (True, False): for r in (True, False): ival = Interval(n[i], n[j], l, r) assert S(str(ival)) == ival def test_AccumBounds(): a = Symbol('a', real=True) assert str(AccumBounds(0, a)) == "AccumBounds(0, a)" assert str(AccumBounds(0, 1)) == "AccumBounds(0, 1)" def test_Lambda(): assert str(Lambda(d, d**2)) == "Lambda(_d, _d**2)" # issue 2908 assert str(Lambda((), 1)) == "Lambda((), 1)" assert str(Lambda((), x)) == "Lambda((), x)" assert str(Lambda((x, y), x+y)) == "Lambda((x, y), x + y)" assert str(Lambda(((x, y),), x+y)) == "Lambda(((x, y),), x + y)" def test_Limit(): assert str(Limit(sin(x)/x, x, y)) == "Limit(sin(x)/x, x, y)" assert str(Limit(1/x, x, 0)) == "Limit(1/x, x, 0)" assert str( Limit(sin(x)/x, x, y, dir="-")) == "Limit(sin(x)/x, x, y, dir='-')" def test_list(): assert str([x]) == sstr([x]) == "[x]" assert str([x**2, x*y + 1]) == sstr([x**2, x*y + 1]) == "[x**2, x*y + 1]" assert str([x**2, [y + x]]) == sstr([x**2, [y + x]]) == "[x**2, [x + y]]" def test_Matrix_str(): M = Matrix([[x**+1, 1], [y, x + y]]) assert str(M) == "Matrix([[x, 1], [y, x + y]])" assert sstr(M) == "Matrix([\n[x, 1],\n[y, x + y]])" M = Matrix([[1]]) assert str(M) == sstr(M) == "Matrix([[1]])" M = Matrix([[1, 2]]) assert str(M) == sstr(M) == "Matrix([[1, 2]])" M = Matrix() assert str(M) == sstr(M) == "Matrix(0, 0, [])" M = Matrix(0, 1, lambda i, j: 0) assert str(M) == sstr(M) == "Matrix(0, 1, [])" def test_Mul(): assert str(x/y) == "x/y" assert str(y/x) == "y/x" assert str(x/y/z) == "x/(y*z)" assert str((x + 1)/(y + 2)) == "(x + 1)/(y + 2)" assert str(2*x/3) == '2*x/3' assert str(-2*x/3) == '-2*x/3' assert str(-1.0*x) == '-1.0*x' assert str(1.0*x) == '1.0*x' # For issue 14160 assert str(Mul(-2, x, Pow(Mul(y,y,evaluate=False), -1, evaluate=False), evaluate=False)) == '-2*x/(y*y)' class CustomClass1(Expr): is_commutative = True class CustomClass2(Expr): is_commutative = True cc1 = CustomClass1() cc2 = CustomClass2() assert str(Rational(2)*cc1) == '2*CustomClass1()' assert str(cc1*Rational(2)) == '2*CustomClass1()' assert str(cc1*Float("1.5")) == '1.5*CustomClass1()' assert str(cc2*Rational(2)) == '2*CustomClass2()' assert str(cc2*Rational(2)*cc1) == '2*CustomClass1()*CustomClass2()' assert str(cc1*Rational(2)*cc2) == '2*CustomClass1()*CustomClass2()' def test_NaN(): assert str(nan) == "nan" def test_NegativeInfinity(): assert str(-oo) == "-oo" def test_Order(): assert str(O(x)) == "O(x)" assert str(O(x**2)) == "O(x**2)" assert str(O(x*y)) == "O(x*y, x, y)" assert str(O(x, x)) == "O(x)" assert str(O(x, (x, 0))) == "O(x)" assert str(O(x, (x, oo))) == "O(x, (x, oo))" assert str(O(x, x, y)) == "O(x, x, y)" assert str(O(x, x, y)) == "O(x, x, y)" assert str(O(x, (x, oo), (y, oo))) == "O(x, (x, oo), (y, oo))" def test_Permutation_Cycle(): from sympy.combinatorics import Permutation, Cycle # general principle: economically, canonically show all moved elements # and the size of the permutation. for p, s in [ (Cycle(), '()'), (Cycle(2), '(2)'), (Cycle(2, 1), '(1 2)'), (Cycle(1, 2)(5)(6, 7)(10), '(1 2)(6 7)(10)'), (Cycle(3, 4)(1, 2)(3, 4), '(1 2)(4)'), ]: assert sstr(p) == s for p, s in [ (Permutation([]), 'Permutation([])'), (Permutation([], size=1), 'Permutation([0])'), (Permutation([], size=2), 'Permutation([0, 1])'), (Permutation([], size=10), 'Permutation([], size=10)'), (Permutation([1, 0, 2]), 'Permutation([1, 0, 2])'), (Permutation([1, 0, 2, 3, 4, 5]), 'Permutation([1, 0], size=6)'), (Permutation([1, 0, 2, 3, 4, 5], size=10), 'Permutation([1, 0], size=10)'), ]: assert sstr(p, perm_cyclic=False) == s for p, s in [ (Permutation([]), '()'), (Permutation([], size=1), '(0)'), (Permutation([], size=2), '(1)'), (Permutation([], size=10), '(9)'), (Permutation([1, 0, 2]), '(2)(0 1)'), (Permutation([1, 0, 2, 3, 4, 5]), '(5)(0 1)'), (Permutation([1, 0, 2, 3, 4, 5], size=10), '(9)(0 1)'), (Permutation([0, 1, 3, 2, 4, 5], size=10), '(9)(2 3)'), ]: assert sstr(p) == s def test_Pi(): assert str(pi) == "pi" def test_Poly(): assert str(Poly(0, x)) == "Poly(0, x, domain='ZZ')" assert str(Poly(1, x)) == "Poly(1, x, domain='ZZ')" assert str(Poly(x, x)) == "Poly(x, x, domain='ZZ')" assert str(Poly(2*x + 1, x)) == "Poly(2*x + 1, x, domain='ZZ')" assert str(Poly(2*x - 1, x)) == "Poly(2*x - 1, x, domain='ZZ')" assert str(Poly(-1, x)) == "Poly(-1, x, domain='ZZ')" assert str(Poly(-x, x)) == "Poly(-x, x, domain='ZZ')" assert str(Poly(-2*x + 1, x)) == "Poly(-2*x + 1, x, domain='ZZ')" assert str(Poly(-2*x - 1, x)) == "Poly(-2*x - 1, x, domain='ZZ')" assert str(Poly(x - 1, x)) == "Poly(x - 1, x, domain='ZZ')" assert str(Poly(2*x + x**5, x)) == "Poly(x**5 + 2*x, x, domain='ZZ')" assert str(Poly(3**(2*x), 3**x)) == "Poly((3**x)**2, 3**x, domain='ZZ')" assert str(Poly((x**2)**x)) == "Poly(((x**2)**x), (x**2)**x, domain='ZZ')" assert str(Poly((x + y)**3, (x + y), expand=False) ) == "Poly((x + y)**3, x + y, domain='ZZ')" assert str(Poly((x - 1)**2, (x - 1), expand=False) ) == "Poly((x - 1)**2, x - 1, domain='ZZ')" assert str( Poly(x**2 + 1 + y, x)) == "Poly(x**2 + y + 1, x, domain='ZZ[y]')" assert str( Poly(x**2 - 1 + y, x)) == "Poly(x**2 + y - 1, x, domain='ZZ[y]')" assert str(Poly(x**2 + I*x, x)) == "Poly(x**2 + I*x, x, domain='EX')" assert str(Poly(x**2 - I*x, x)) == "Poly(x**2 - I*x, x, domain='EX')" assert str(Poly(-x*y*z + x*y - 1, x, y, z) ) == "Poly(-x*y*z + x*y - 1, x, y, z, domain='ZZ')" assert str(Poly(-w*x**21*y**7*z + (1 + w)*z**3 - 2*x*z + 1, x, y, z)) == \ "Poly(-w*x**21*y**7*z - 2*x*z + (w + 1)*z**3 + 1, x, y, z, domain='ZZ[w]')" assert str(Poly(x**2 + 1, x, modulus=2)) == "Poly(x**2 + 1, x, modulus=2)" assert str(Poly(2*x**2 + 3*x + 4, x, modulus=17)) == "Poly(2*x**2 + 3*x + 4, x, modulus=17)" def test_PolyRing(): assert str(ring("x", ZZ, lex)[0]) == "Polynomial ring in x over ZZ with lex order" assert str(ring("x,y", QQ, grlex)[0]) == "Polynomial ring in x, y over QQ with grlex order" assert str(ring("x,y,z", ZZ["t"], lex)[0]) == "Polynomial ring in x, y, z over ZZ[t] with lex order" def test_FracField(): assert str(field("x", ZZ, lex)[0]) == "Rational function field in x over ZZ with lex order" assert str(field("x,y", QQ, grlex)[0]) == "Rational function field in x, y over QQ with grlex order" assert str(field("x,y,z", ZZ["t"], lex)[0]) == "Rational function field in x, y, z over ZZ[t] with lex order" def test_PolyElement(): Ruv, u,v = ring("u,v", ZZ) Rxyz, x,y,z = ring("x,y,z", Ruv) assert str(x - x) == "0" assert str(x - 1) == "x - 1" assert str(x + 1) == "x + 1" assert str(x**2) == "x**2" assert str(x**(-2)) == "x**(-2)" assert str(x**QQ(1, 2)) == "x**(1/2)" assert str((u**2 + 3*u*v + 1)*x**2*y + u + 1) == "(u**2 + 3*u*v + 1)*x**2*y + u + 1" assert str((u**2 + 3*u*v + 1)*x**2*y + (u + 1)*x) == "(u**2 + 3*u*v + 1)*x**2*y + (u + 1)*x" assert str((u**2 + 3*u*v + 1)*x**2*y + (u + 1)*x + 1) == "(u**2 + 3*u*v + 1)*x**2*y + (u + 1)*x + 1" assert str((-u**2 + 3*u*v - 1)*x**2*y - (u + 1)*x - 1) == "-(u**2 - 3*u*v + 1)*x**2*y - (u + 1)*x - 1" assert str(-(v**2 + v + 1)*x + 3*u*v + 1) == "-(v**2 + v + 1)*x + 3*u*v + 1" assert str(-(v**2 + v + 1)*x - 3*u*v + 1) == "-(v**2 + v + 1)*x - 3*u*v + 1" def test_FracElement(): Fuv, u,v = field("u,v", ZZ) Fxyzt, x,y,z,t = field("x,y,z,t", Fuv) assert str(x - x) == "0" assert str(x - 1) == "x - 1" assert str(x + 1) == "x + 1" assert str(x/3) == "x/3" assert str(x/z) == "x/z" assert str(x*y/z) == "x*y/z" assert str(x/(z*t)) == "x/(z*t)" assert str(x*y/(z*t)) == "x*y/(z*t)" assert str((x - 1)/y) == "(x - 1)/y" assert str((x + 1)/y) == "(x + 1)/y" assert str((-x - 1)/y) == "(-x - 1)/y" assert str((x + 1)/(y*z)) == "(x + 1)/(y*z)" assert str(-y/(x + 1)) == "-y/(x + 1)" assert str(y*z/(x + 1)) == "y*z/(x + 1)" assert str(((u + 1)*x*y + 1)/((v - 1)*z - 1)) == "((u + 1)*x*y + 1)/((v - 1)*z - 1)" assert str(((u + 1)*x*y + 1)/((v - 1)*z - t*u*v - 1)) == "((u + 1)*x*y + 1)/((v - 1)*z - u*v*t - 1)" def test_Pow(): assert str(x**-1) == "1/x" assert str(x**-2) == "x**(-2)" assert str(x**2) == "x**2" assert str((x + y)**-1) == "1/(x + y)" assert str((x + y)**-2) == "(x + y)**(-2)" assert str((x + y)**2) == "(x + y)**2" assert str((x + y)**(1 + x)) == "(x + y)**(x + 1)" assert str(x**Rational(1, 3)) == "x**(1/3)" assert str(1/x**Rational(1, 3)) == "x**(-1/3)" assert str(sqrt(sqrt(x))) == "x**(1/4)" # not the same as x**-1 assert str(x**-1.0) == 'x**(-1.0)' # see issue #2860 assert str(Pow(S(2), -1.0, evaluate=False)) == '2**(-1.0)' def test_sqrt(): assert str(sqrt(x)) == "sqrt(x)" assert str(sqrt(x**2)) == "sqrt(x**2)" assert str(1/sqrt(x)) == "1/sqrt(x)" assert str(1/sqrt(x**2)) == "1/sqrt(x**2)" assert str(y/sqrt(x)) == "y/sqrt(x)" assert str(x**0.5) == "x**0.5" assert str(1/x**0.5) == "x**(-0.5)" def test_Rational(): n1 = Rational(1, 4) n2 = Rational(1, 3) n3 = Rational(2, 4) n4 = Rational(2, -4) n5 = Rational(0) n7 = Rational(3) n8 = Rational(-3) assert str(n1*n2) == "1/12" assert str(n1*n2) == "1/12" assert str(n3) == "1/2" assert str(n1*n3) == "1/8" assert str(n1 + n3) == "3/4" assert str(n1 + n2) == "7/12" assert str(n1 + n4) == "-1/4" assert str(n4*n4) == "1/4" assert str(n4 + n2) == "-1/6" assert str(n4 + n5) == "-1/2" assert str(n4*n5) == "0" assert str(n3 + n4) == "0" assert str(n1**n7) == "1/64" assert str(n2**n7) == "1/27" assert str(n2**n8) == "27" assert str(n7**n8) == "1/27" assert str(Rational("-25")) == "-25" assert str(Rational("1.25")) == "5/4" assert str(Rational("-2.6e-2")) == "-13/500" assert str(S("25/7")) == "25/7" assert str(S("-123/569")) == "-123/569" assert str(S("0.1[23]", rational=1)) == "61/495" assert str(S("5.1[666]", rational=1)) == "31/6" assert str(S("-5.1[666]", rational=1)) == "-31/6" assert str(S("0.[9]", rational=1)) == "1" assert str(S("-0.[9]", rational=1)) == "-1" assert str(sqrt(Rational(1, 4))) == "1/2" assert str(sqrt(Rational(1, 36))) == "1/6" assert str((123**25) ** Rational(1, 25)) == "123" assert str((123**25 + 1)**Rational(1, 25)) != "123" assert str((123**25 - 1)**Rational(1, 25)) != "123" assert str((123**25 - 1)**Rational(1, 25)) != "122" assert str(sqrt(Rational(81, 36))**3) == "27/8" assert str(1/sqrt(Rational(81, 36))**3) == "8/27" assert str(sqrt(-4)) == str(2*I) assert str(2**Rational(1, 10**10)) == "2**(1/10000000000)" assert sstr(Rational(2, 3), sympy_integers=True) == "S(2)/3" x = Symbol("x") assert sstr(x**Rational(2, 3), sympy_integers=True) == "x**(S(2)/3)" assert sstr(Eq(x, Rational(2, 3)), sympy_integers=True) == "Eq(x, S(2)/3)" assert sstr(Limit(x, x, Rational(7, 2)), sympy_integers=True) == \ "Limit(x, x, S(7)/2)" def test_Float(): # NOTE dps is the whole number of decimal digits assert str(Float('1.23', dps=1 + 2)) == '1.23' assert str(Float('1.23456789', dps=1 + 8)) == '1.23456789' assert str( Float('1.234567890123456789', dps=1 + 18)) == '1.234567890123456789' assert str(pi.evalf(1 + 2)) == '3.14' assert str(pi.evalf(1 + 14)) == '3.14159265358979' assert str(pi.evalf(1 + 64)) == ('3.141592653589793238462643383279' '5028841971693993751058209749445923') assert str(pi.round(-1)) == '0.0' assert str((pi**400 - (pi**400).round(1)).n(2)) == '-0.e+88' assert sstr(Float("100"), full_prec=False, min=-2, max=2) == '1.0e+2' assert sstr(Float("100"), full_prec=False, min=-2, max=3) == '100.0' assert sstr(Float("0.1"), full_prec=False, min=-2, max=3) == '0.1' assert sstr(Float("0.099"), min=-2, max=3) == '9.90000000000000e-2' def test_Relational(): assert str(Rel(x, y, "<")) == "x < y" assert str(Rel(x + y, y, "==")) == "Eq(x + y, y)" assert str(Rel(x, y, "!=")) == "Ne(x, y)" assert str(Eq(x, 1) | Eq(x, 2)) == "Eq(x, 1) | Eq(x, 2)" assert str(Ne(x, 1) & Ne(x, 2)) == "Ne(x, 1) & Ne(x, 2)" def test_CRootOf(): assert str(rootof(x**5 + 2*x - 1, 0)) == "CRootOf(x**5 + 2*x - 1, 0)" def test_RootSum(): f = x**5 + 2*x - 1 assert str( RootSum(f, Lambda(z, z), auto=False)) == "RootSum(x**5 + 2*x - 1)" assert str(RootSum(f, Lambda( z, z**2), auto=False)) == "RootSum(x**5 + 2*x - 1, Lambda(z, z**2))" def test_GroebnerBasis(): assert str(groebner( [], x, y)) == "GroebnerBasis([], x, y, domain='ZZ', order='lex')" F = [x**2 - 3*y - x + 1, y**2 - 2*x + y - 1] assert str(groebner(F, order='grlex')) == \ "GroebnerBasis([x**2 - x - 3*y + 1, y**2 - 2*x + y - 1], x, y, domain='ZZ', order='grlex')" assert str(groebner(F, order='lex')) == \ "GroebnerBasis([2*x - y**2 - y + 1, y**4 + 2*y**3 - 3*y**2 - 16*y + 7], x, y, domain='ZZ', order='lex')" def test_set(): assert sstr(set()) == 'set()' assert sstr(frozenset()) == 'frozenset()' assert sstr(set([1])) == '{1}' assert sstr(frozenset([1])) == 'frozenset({1})' assert sstr(set([1, 2, 3])) == '{1, 2, 3}' assert sstr(frozenset([1, 2, 3])) == 'frozenset({1, 2, 3})' assert sstr( set([1, x, x**2, x**3, x**4])) == '{1, x, x**2, x**3, x**4}' assert sstr( frozenset([1, x, x**2, x**3, x**4])) == 'frozenset({1, x, x**2, x**3, x**4})' def test_SparseMatrix(): M = SparseMatrix([[x**+1, 1], [y, x + y]]) assert str(M) == "Matrix([[x, 1], [y, x + y]])" assert sstr(M) == "Matrix([\n[x, 1],\n[y, x + y]])" def test_Sum(): assert str(summation(cos(3*z), (z, x, y))) == "Sum(cos(3*z), (z, x, y))" assert str(Sum(x*y**2, (x, -2, 2), (y, -5, 5))) == \ "Sum(x*y**2, (x, -2, 2), (y, -5, 5))" def test_Symbol(): assert str(y) == "y" assert str(x) == "x" e = x assert str(e) == "x" def test_tuple(): assert str((x,)) == sstr((x,)) == "(x,)" assert str((x + y, 1 + x)) == sstr((x + y, 1 + x)) == "(x + y, x + 1)" assert str((x + y, ( 1 + x, x**2))) == sstr((x + y, (1 + x, x**2))) == "(x + y, (x + 1, x**2))" def test_Quaternion_str_printer(): q = Quaternion(x, y, z, t) assert str(q) == "x + y*i + z*j + t*k" q = Quaternion(x,y,z,x*t) assert str(q) == "x + y*i + z*j + t*x*k" q = Quaternion(x,y,z,x+t) assert str(q) == "x + y*i + z*j + (t + x)*k" def test_Quantity_str(): assert sstr(second, abbrev=True) == "s" assert sstr(joule, abbrev=True) == "J" assert str(second) == "second" assert str(joule) == "joule" def test_wild_str(): # Check expressions containing Wild not causing infinite recursion w = Wild('x') assert str(w + 1) == 'x_ + 1' assert str(exp(2**w) + 5) == 'exp(2**x_) + 5' assert str(3*w + 1) == '3*x_ + 1' assert str(1/w + 1) == '1 + 1/x_' assert str(w**2 + 1) == 'x_**2 + 1' assert str(1/(1 - w)) == '1/(1 - x_)' def test_zeta(): assert str(zeta(3)) == "zeta(3)" def test_issue_3101(): e = x - y a = str(e) b = str(e) assert a == b def test_issue_3103(): e = -2*sqrt(x) - y/sqrt(x)/2 assert str(e) not in ["(-2)*x**1/2(-1/2)*x**(-1/2)*y", "-2*x**1/2(-1/2)*x**(-1/2)*y", "-2*x**1/2-1/2*x**-1/2*w"] assert str(e) == "-2*sqrt(x) - y/(2*sqrt(x))" def test_issue_4021(): e = Integral(x, x) + 1 assert str(e) == 'Integral(x, x) + 1' def test_sstrrepr(): assert sstr('abc') == 'abc' assert sstrrepr('abc') == "'abc'" e = ['a', 'b', 'c', x] assert sstr(e) == "[a, b, c, x]" assert sstrrepr(e) == "['a', 'b', 'c', x]" def test_infinity(): assert sstr(oo*I) == "oo*I" def test_full_prec(): assert sstr(S("0.3"), full_prec=True) == "0.300000000000000" assert sstr(S("0.3"), full_prec="auto") == "0.300000000000000" assert sstr(S("0.3"), full_prec=False) == "0.3" assert sstr(S("0.3")*x, full_prec=True) in [ "0.300000000000000*x", "x*0.300000000000000" ] assert sstr(S("0.3")*x, full_prec="auto") in [ "0.3*x", "x*0.3" ] assert sstr(S("0.3")*x, full_prec=False) in [ "0.3*x", "x*0.3" ] def test_noncommutative(): A, B, C = symbols('A,B,C', commutative=False) assert sstr(A*B*C**-1) == "A*B*C**(-1)" assert sstr(C**-1*A*B) == "C**(-1)*A*B" assert sstr(A*C**-1*B) == "A*C**(-1)*B" assert sstr(sqrt(A)) == "sqrt(A)" assert sstr(1/sqrt(A)) == "A**(-1/2)" def test_empty_printer(): str_printer = StrPrinter() assert str_printer.emptyPrinter("foo") == "foo" assert str_printer.emptyPrinter(x*y) == "x*y" assert str_printer.emptyPrinter(32) == "32" def test_settings(): raises(TypeError, lambda: sstr(S(4), method="garbage")) def test_RandomDomain(): from sympy.stats import Normal, Die, Exponential, pspace, where X = Normal('x1', 0, 1) assert str(where(X > 0)) == "Domain: (0 < x1) & (x1 < oo)" D = Die('d1', 6) assert str(where(D > 4)) == "Domain: Eq(d1, 5) | Eq(d1, 6)" A = Exponential('a', 1) B = Exponential('b', 1) assert str(pspace(Tuple(A, B)).domain) == "Domain: (0 <= a) & (0 <= b) & (a < oo) & (b < oo)" def test_FiniteSet(): assert str(FiniteSet(*range(1, 51))) == ( 'FiniteSet(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,' ' 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34,' ' 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50)' ) assert str(FiniteSet(*range(1, 6))) == 'FiniteSet(1, 2, 3, 4, 5)' def test_UniversalSet(): assert str(S.UniversalSet) == 'UniversalSet' def test_PrettyPoly(): from sympy.polys.domains import QQ F = QQ.frac_field(x, y) R = QQ[x, y] assert sstr(F.convert(x/(x + y))) == sstr(x/(x + y)) assert sstr(R.convert(x + y)) == sstr(x + y) def test_categories(): from sympy.categories import (Object, NamedMorphism, IdentityMorphism, Category) A = Object("A") B = Object("B") f = NamedMorphism(A, B, "f") id_A = IdentityMorphism(A) K = Category("K") assert str(A) == 'Object("A")' assert str(f) == 'NamedMorphism(Object("A"), Object("B"), "f")' assert str(id_A) == 'IdentityMorphism(Object("A"))' assert str(K) == 'Category("K")' def test_Tr(): A, B = symbols('A B', commutative=False) t = Tr(A*B) assert str(t) == 'Tr(A*B)' def test_issue_6387(): assert str(factor(-3.0*z + 3)) == '-3.0*(1.0*z - 1.0)' def test_MatMul_MatAdd(): from sympy import MatrixSymbol assert str(2*(MatrixSymbol("X", 2, 2) + MatrixSymbol("Y", 2, 2))) == \ "2*(X + Y)" def test_MatrixSlice(): from sympy.matrices.expressions import MatrixSymbol assert str(MatrixSymbol('X', 10, 10)[:5, 1:9:2]) == 'X[:5, 1:9:2]' assert str(MatrixSymbol('X', 10, 10)[5, :5:2]) == 'X[5, :5:2]' def test_true_false(): assert str(true) == repr(true) == sstr(true) == "True" assert str(false) == repr(false) == sstr(false) == "False" def test_Equivalent(): assert str(Equivalent(y, x)) == "Equivalent(x, y)" def test_Xor(): assert str(Xor(y, x, evaluate=False)) == "x ^ y" def test_Complement(): assert str(Complement(S.Reals, S.Naturals)) == 'Complement(Reals, Naturals)' def test_SymmetricDifference(): assert str(SymmetricDifference(Interval(2, 3), Interval(3, 4),evaluate=False)) == \ 'SymmetricDifference(Interval(2, 3), Interval(3, 4))' def test_UnevaluatedExpr(): a, b = symbols("a b") expr1 = 2*UnevaluatedExpr(a+b) assert str(expr1) == "2*(a + b)" def test_MatrixElement_printing(): # test cases for issue #11821 A = MatrixSymbol("A", 1, 3) B = MatrixSymbol("B", 1, 3) C = MatrixSymbol("C", 1, 3) assert(str(A[0, 0]) == "A[0, 0]") assert(str(3 * A[0, 0]) == "3*A[0, 0]") F = C[0, 0].subs(C, A - B) assert str(F) == "(A - B)[0, 0]" def test_MatrixSymbol_printing(): A = MatrixSymbol("A", 3, 3) B = MatrixSymbol("B", 3, 3) assert str(A - A*B - B) == "A - A*B - B" assert str(A*B - (A+B)) == "-(A + B) + A*B" assert str(A**(-1)) == "A**(-1)" assert str(A**3) == "A**3" def test_MatrixExpressions(): n = Symbol('n', integer=True) X = MatrixSymbol('X', n, n) assert str(X) == "X" Y = X[1:2:3, 4:5:6] assert str(Y) == "X[1:3, 4:6]" Z = X[1:10:2] assert str(Z) == "X[1:10:2, :n]" # Apply function elementwise (`ElementwiseApplyFunc`): expr = (X.T*X).applyfunc(sin) assert str(expr) == 'Lambda(_d, sin(_d)).(X.T*X)' lamda = Lambda(x, 1/x) expr = (n*X).applyfunc(lamda) assert str(expr) == 'Lambda(_d, 1/_d).(n*X)' def test_Subs_printing(): assert str(Subs(x, (x,), (1,))) == 'Subs(x, x, 1)' assert str(Subs(x + y, (x, y), (1, 2))) == 'Subs(x + y, (x, y), (1, 2))' def test_issue_15716(): e = Integral(factorial(x), (x, -oo, oo)) assert e.as_terms() == ([(e, ((1.0, 0.0), (1,), ()))], [e]) def test_str_special_matrices(): from sympy.matrices import Identity, ZeroMatrix, OneMatrix assert str(Identity(4)) == 'I' assert str(ZeroMatrix(2, 2)) == '0' assert str(OneMatrix(2, 2)) == '1' def test_issue_14567(): assert factorial(Sum(-1, (x, 0, 0))) + y # doesn't raise an error
8a984add7cfd671c97f481f3623a0b43d02c0bfb48c1011582a44f0acfe75bde
from sympy import (sin, cos, atan2, log, exp, gamma, conjugate, sqrt, factorial, Integral, Piecewise, Add, diff, symbols, S, Float, Dummy, Eq, Range, Catalan, EulerGamma, E, GoldenRatio, I, pi, Function, Rational, Integer, Lambda, sign, Mod) from sympy.codegen import For, Assignment, aug_assign from sympy.codegen.ast import Declaration, Variable, float32, float64, \ value_const, real, bool_, While, FunctionPrototype, FunctionDefinition, \ integer, Return from sympy.core.relational import Relational from sympy.logic.boolalg import And, Or, Not, Equivalent, Xor from sympy.matrices import Matrix, MatrixSymbol from sympy.printing.fcode import fcode, FCodePrinter from sympy.tensor import IndexedBase, Idx from sympy.utilities.lambdify import implemented_function from sympy.testing.pytest import raises def test_printmethod(): x = symbols('x') class nint(Function): def _fcode(self, printer): return "nint(%s)" % printer._print(self.args[0]) assert fcode(nint(x)) == " nint(x)" def test_fcode_sign(): #issue 12267 x=symbols('x') y=symbols('y', integer=True) z=symbols('z', complex=True) assert fcode(sign(x), standard=95, source_format='free') == "merge(0d0, dsign(1d0, x), x == 0d0)" assert fcode(sign(y), standard=95, source_format='free') == "merge(0, isign(1, y), y == 0)" assert fcode(sign(z), standard=95, source_format='free') == "merge(cmplx(0d0, 0d0), z/abs(z), abs(z) == 0d0)" raises(NotImplementedError, lambda: fcode(sign(x))) def test_fcode_Pow(): x, y = symbols('x,y') n = symbols('n', integer=True) assert fcode(x**3) == " x**3" assert fcode(x**(y**3)) == " x**(y**3)" assert fcode(1/(sin(x)*3.5)**(x - y**x)/(x**2 + y)) == \ " (3.5d0*sin(x))**(-x + y**x)/(x**2 + y)" assert fcode(sqrt(x)) == ' sqrt(x)' assert fcode(sqrt(n)) == ' sqrt(dble(n))' assert fcode(x**0.5) == ' sqrt(x)' assert fcode(sqrt(x)) == ' sqrt(x)' assert fcode(sqrt(10)) == ' sqrt(10.0d0)' assert fcode(x**-1.0) == ' 1d0/x' assert fcode(x**-2.0, 'y', source_format='free') == 'y = x**(-2.0d0)' # 2823 assert fcode(x**Rational(3, 7)) == ' x**(3.0d0/7.0d0)' def test_fcode_Rational(): x = symbols('x') assert fcode(Rational(3, 7)) == " 3.0d0/7.0d0" assert fcode(Rational(18, 9)) == " 2" assert fcode(Rational(3, -7)) == " -3.0d0/7.0d0" assert fcode(Rational(-3, -7)) == " 3.0d0/7.0d0" assert fcode(x + Rational(3, 7)) == " x + 3.0d0/7.0d0" assert fcode(Rational(3, 7)*x) == " (3.0d0/7.0d0)*x" def test_fcode_Integer(): assert fcode(Integer(67)) == " 67" assert fcode(Integer(-1)) == " -1" def test_fcode_Float(): assert fcode(Float(42.0)) == " 42.0000000000000d0" assert fcode(Float(-1e20)) == " -1.00000000000000d+20" def test_fcode_functions(): x, y = symbols('x,y') assert fcode(sin(x) ** cos(y)) == " sin(x)**cos(y)" raises(NotImplementedError, lambda: fcode(Mod(x, y), standard=66)) raises(NotImplementedError, lambda: fcode(x % y, standard=66)) raises(NotImplementedError, lambda: fcode(Mod(x, y), standard=77)) raises(NotImplementedError, lambda: fcode(x % y, standard=77)) for standard in [90, 95, 2003, 2008]: assert fcode(Mod(x, y), standard=standard) == " modulo(x, y)" assert fcode(x % y, standard=standard) == " modulo(x, y)" def test_case(): ob = FCodePrinter() x,x_,x__,y,X,X_,Y = symbols('x,x_,x__,y,X,X_,Y') assert fcode(exp(x_) + sin(x*y) + cos(X*Y)) == \ ' exp(x_) + sin(x*y) + cos(X__*Y_)' assert fcode(exp(x__) + 2*x*Y*X_**Rational(7, 2)) == \ ' 2*X_**(7.0d0/2.0d0)*Y*x + exp(x__)' assert fcode(exp(x_) + sin(x*y) + cos(X*Y), name_mangling=False) == \ ' exp(x_) + sin(x*y) + cos(X*Y)' assert fcode(x - cos(X), name_mangling=False) == ' x - cos(X)' assert ob.doprint(X*sin(x) + x_, assign_to='me') == ' me = X*sin(x_) + x__' assert ob.doprint(X*sin(x), assign_to='mu') == ' mu = X*sin(x_)' assert ob.doprint(x_, assign_to='ad') == ' ad = x__' n, m = symbols('n,m', integer=True) A = IndexedBase('A') x = IndexedBase('x') y = IndexedBase('y') i = Idx('i', m) I = Idx('I', n) assert fcode(A[i, I]*x[I], assign_to=y[i], source_format='free') == ( "do i = 1, m\n" " y(i) = 0\n" "end do\n" "do i = 1, m\n" " do I_ = 1, n\n" " y(i) = A(i, I_)*x(I_) + y(i)\n" " end do\n" "end do" ) #issue 6814 def test_fcode_functions_with_integers(): x= symbols('x') log10_17 = log(10).evalf(17) loglog10_17 = '0.8340324452479558d0' assert fcode(x * log(10)) == " x*%sd0" % log10_17 assert fcode(x * log(10)) == " x*%sd0" % log10_17 assert fcode(x * log(S(10))) == " x*%sd0" % log10_17 assert fcode(log(S(10))) == " %sd0" % log10_17 assert fcode(exp(10)) == " %sd0" % exp(10).evalf(17) assert fcode(x * log(log(10))) == " x*%s" % loglog10_17 assert fcode(x * log(log(S(10)))) == " x*%s" % loglog10_17 def test_fcode_NumberSymbol(): prec = 17 p = FCodePrinter() assert fcode(Catalan) == ' parameter (Catalan = %sd0)\n Catalan' % Catalan.evalf(prec) assert fcode(EulerGamma) == ' parameter (EulerGamma = %sd0)\n EulerGamma' % EulerGamma.evalf(prec) assert fcode(E) == ' parameter (E = %sd0)\n E' % E.evalf(prec) assert fcode(GoldenRatio) == ' parameter (GoldenRatio = %sd0)\n GoldenRatio' % GoldenRatio.evalf(prec) assert fcode(pi) == ' parameter (pi = %sd0)\n pi' % pi.evalf(prec) assert fcode( pi, precision=5) == ' parameter (pi = %sd0)\n pi' % pi.evalf(5) assert fcode(Catalan, human=False) == (set( [(Catalan, p._print(Catalan.evalf(prec)))]), set([]), ' Catalan') assert fcode(EulerGamma, human=False) == (set([(EulerGamma, p._print( EulerGamma.evalf(prec)))]), set([]), ' EulerGamma') assert fcode(E, human=False) == ( set([(E, p._print(E.evalf(prec)))]), set([]), ' E') assert fcode(GoldenRatio, human=False) == (set([(GoldenRatio, p._print( GoldenRatio.evalf(prec)))]), set([]), ' GoldenRatio') assert fcode(pi, human=False) == ( set([(pi, p._print(pi.evalf(prec)))]), set([]), ' pi') assert fcode(pi, precision=5, human=False) == ( set([(pi, p._print(pi.evalf(5)))]), set([]), ' pi') def test_fcode_complex(): assert fcode(I) == " cmplx(0,1)" x = symbols('x') assert fcode(4*I) == " cmplx(0,4)" assert fcode(3 + 4*I) == " cmplx(3,4)" assert fcode(3 + 4*I + x) == " cmplx(3,4) + x" assert fcode(I*x) == " cmplx(0,1)*x" assert fcode(3 + 4*I - x) == " cmplx(3,4) - x" x = symbols('x', imaginary=True) assert fcode(5*x) == " 5*x" assert fcode(I*x) == " cmplx(0,1)*x" assert fcode(3 + x) == " x + 3" def test_implicit(): x, y = symbols('x,y') assert fcode(sin(x)) == " sin(x)" assert fcode(atan2(x, y)) == " atan2(x, y)" assert fcode(conjugate(x)) == " conjg(x)" def test_not_fortran(): x = symbols('x') g = Function('g') gamma_f = fcode(gamma(x)) assert gamma_f == "C Not supported in Fortran:\nC gamma\n gamma(x)" assert fcode(Integral(sin(x))) == "C Not supported in Fortran:\nC Integral\n Integral(sin(x), x)" assert fcode(g(x)) == "C Not supported in Fortran:\nC g\n g(x)" def test_user_functions(): x = symbols('x') assert fcode(sin(x), user_functions={"sin": "zsin"}) == " zsin(x)" x = symbols('x') assert fcode( gamma(x), user_functions={"gamma": "mygamma"}) == " mygamma(x)" g = Function('g') assert fcode(g(x), user_functions={"g": "great"}) == " great(x)" n = symbols('n', integer=True) assert fcode( factorial(n), user_functions={"factorial": "fct"}) == " fct(n)" def test_inline_function(): x = symbols('x') g = implemented_function('g', Lambda(x, 2*x)) assert fcode(g(x)) == " 2*x" g = implemented_function('g', Lambda(x, 2*pi/x)) assert fcode(g(x)) == ( " parameter (pi = %sd0)\n" " 2*pi/x" ) % pi.evalf(17) A = IndexedBase('A') i = Idx('i', symbols('n', integer=True)) g = implemented_function('g', Lambda(x, x*(1 + x)*(2 + x))) assert fcode(g(A[i]), assign_to=A[i]) == ( " do i = 1, n\n" " A(i) = (A(i) + 1)*(A(i) + 2)*A(i)\n" " end do" ) def test_assign_to(): x = symbols('x') assert fcode(sin(x), assign_to="s") == " s = sin(x)" def test_line_wrapping(): x, y = symbols('x,y') assert fcode(((x + y)**10).expand(), assign_to="var") == ( " var = x**10 + 10*x**9*y + 45*x**8*y**2 + 120*x**7*y**3 + 210*x**6*\n" " @ y**4 + 252*x**5*y**5 + 210*x**4*y**6 + 120*x**3*y**7 + 45*x**2*y\n" " @ **8 + 10*x*y**9 + y**10" ) e = [x**i for i in range(11)] assert fcode(Add(*e)) == ( " x**10 + x**9 + x**8 + x**7 + x**6 + x**5 + x**4 + x**3 + x**2 + x\n" " @ + 1" ) def test_fcode_precedence(): x, y = symbols("x y") assert fcode(And(x < y, y < x + 1), source_format="free") == \ "x < y .and. y < x + 1" assert fcode(Or(x < y, y < x + 1), source_format="free") == \ "x < y .or. y < x + 1" assert fcode(Xor(x < y, y < x + 1, evaluate=False), source_format="free") == "x < y .neqv. y < x + 1" assert fcode(Equivalent(x < y, y < x + 1), source_format="free") == \ "x < y .eqv. y < x + 1" def test_fcode_Logical(): x, y, z = symbols("x y z") # unary Not assert fcode(Not(x), source_format="free") == ".not. x" # binary And assert fcode(And(x, y), source_format="free") == "x .and. y" assert fcode(And(x, Not(y)), source_format="free") == "x .and. .not. y" assert fcode(And(Not(x), y), source_format="free") == "y .and. .not. x" assert fcode(And(Not(x), Not(y)), source_format="free") == \ ".not. x .and. .not. y" assert fcode(Not(And(x, y), evaluate=False), source_format="free") == \ ".not. (x .and. y)" # binary Or assert fcode(Or(x, y), source_format="free") == "x .or. y" assert fcode(Or(x, Not(y)), source_format="free") == "x .or. .not. y" assert fcode(Or(Not(x), y), source_format="free") == "y .or. .not. x" assert fcode(Or(Not(x), Not(y)), source_format="free") == \ ".not. x .or. .not. y" assert fcode(Not(Or(x, y), evaluate=False), source_format="free") == \ ".not. (x .or. y)" # mixed And/Or assert fcode(And(Or(y, z), x), source_format="free") == "x .and. (y .or. z)" assert fcode(And(Or(z, x), y), source_format="free") == "y .and. (x .or. z)" assert fcode(And(Or(x, y), z), source_format="free") == "z .and. (x .or. y)" assert fcode(Or(And(y, z), x), source_format="free") == "x .or. y .and. z" assert fcode(Or(And(z, x), y), source_format="free") == "y .or. x .and. z" assert fcode(Or(And(x, y), z), source_format="free") == "z .or. x .and. y" # trinary And assert fcode(And(x, y, z), source_format="free") == "x .and. y .and. z" assert fcode(And(x, y, Not(z)), source_format="free") == \ "x .and. y .and. .not. z" assert fcode(And(x, Not(y), z), source_format="free") == \ "x .and. z .and. .not. y" assert fcode(And(Not(x), y, z), source_format="free") == \ "y .and. z .and. .not. x" assert fcode(Not(And(x, y, z), evaluate=False), source_format="free") == \ ".not. (x .and. y .and. z)" # trinary Or assert fcode(Or(x, y, z), source_format="free") == "x .or. y .or. z" assert fcode(Or(x, y, Not(z)), source_format="free") == \ "x .or. y .or. .not. z" assert fcode(Or(x, Not(y), z), source_format="free") == \ "x .or. z .or. .not. y" assert fcode(Or(Not(x), y, z), source_format="free") == \ "y .or. z .or. .not. x" assert fcode(Not(Or(x, y, z), evaluate=False), source_format="free") == \ ".not. (x .or. y .or. z)" def test_fcode_Xlogical(): x, y, z = symbols("x y z") # binary Xor assert fcode(Xor(x, y, evaluate=False), source_format="free") == \ "x .neqv. y" assert fcode(Xor(x, Not(y), evaluate=False), source_format="free") == \ "x .neqv. .not. y" assert fcode(Xor(Not(x), y, evaluate=False), source_format="free") == \ "y .neqv. .not. x" assert fcode(Xor(Not(x), Not(y), evaluate=False), source_format="free") == ".not. x .neqv. .not. y" assert fcode(Not(Xor(x, y, evaluate=False), evaluate=False), source_format="free") == ".not. (x .neqv. y)" # binary Equivalent assert fcode(Equivalent(x, y), source_format="free") == "x .eqv. y" assert fcode(Equivalent(x, Not(y)), source_format="free") == \ "x .eqv. .not. y" assert fcode(Equivalent(Not(x), y), source_format="free") == \ "y .eqv. .not. x" assert fcode(Equivalent(Not(x), Not(y)), source_format="free") == \ ".not. x .eqv. .not. y" assert fcode(Not(Equivalent(x, y), evaluate=False), source_format="free") == ".not. (x .eqv. y)" # mixed And/Equivalent assert fcode(Equivalent(And(y, z), x), source_format="free") == \ "x .eqv. y .and. z" assert fcode(Equivalent(And(z, x), y), source_format="free") == \ "y .eqv. x .and. z" assert fcode(Equivalent(And(x, y), z), source_format="free") == \ "z .eqv. x .and. y" assert fcode(And(Equivalent(y, z), x), source_format="free") == \ "x .and. (y .eqv. z)" assert fcode(And(Equivalent(z, x), y), source_format="free") == \ "y .and. (x .eqv. z)" assert fcode(And(Equivalent(x, y), z), source_format="free") == \ "z .and. (x .eqv. y)" # mixed Or/Equivalent assert fcode(Equivalent(Or(y, z), x), source_format="free") == \ "x .eqv. y .or. z" assert fcode(Equivalent(Or(z, x), y), source_format="free") == \ "y .eqv. x .or. z" assert fcode(Equivalent(Or(x, y), z), source_format="free") == \ "z .eqv. x .or. y" assert fcode(Or(Equivalent(y, z), x), source_format="free") == \ "x .or. (y .eqv. z)" assert fcode(Or(Equivalent(z, x), y), source_format="free") == \ "y .or. (x .eqv. z)" assert fcode(Or(Equivalent(x, y), z), source_format="free") == \ "z .or. (x .eqv. y)" # mixed Xor/Equivalent assert fcode(Equivalent(Xor(y, z, evaluate=False), x), source_format="free") == "x .eqv. (y .neqv. z)" assert fcode(Equivalent(Xor(z, x, evaluate=False), y), source_format="free") == "y .eqv. (x .neqv. z)" assert fcode(Equivalent(Xor(x, y, evaluate=False), z), source_format="free") == "z .eqv. (x .neqv. y)" assert fcode(Xor(Equivalent(y, z), x, evaluate=False), source_format="free") == "x .neqv. (y .eqv. z)" assert fcode(Xor(Equivalent(z, x), y, evaluate=False), source_format="free") == "y .neqv. (x .eqv. z)" assert fcode(Xor(Equivalent(x, y), z, evaluate=False), source_format="free") == "z .neqv. (x .eqv. y)" # mixed And/Xor assert fcode(Xor(And(y, z), x, evaluate=False), source_format="free") == \ "x .neqv. y .and. z" assert fcode(Xor(And(z, x), y, evaluate=False), source_format="free") == \ "y .neqv. x .and. z" assert fcode(Xor(And(x, y), z, evaluate=False), source_format="free") == \ "z .neqv. x .and. y" assert fcode(And(Xor(y, z, evaluate=False), x), source_format="free") == \ "x .and. (y .neqv. z)" assert fcode(And(Xor(z, x, evaluate=False), y), source_format="free") == \ "y .and. (x .neqv. z)" assert fcode(And(Xor(x, y, evaluate=False), z), source_format="free") == \ "z .and. (x .neqv. y)" # mixed Or/Xor assert fcode(Xor(Or(y, z), x, evaluate=False), source_format="free") == \ "x .neqv. y .or. z" assert fcode(Xor(Or(z, x), y, evaluate=False), source_format="free") == \ "y .neqv. x .or. z" assert fcode(Xor(Or(x, y), z, evaluate=False), source_format="free") == \ "z .neqv. x .or. y" assert fcode(Or(Xor(y, z, evaluate=False), x), source_format="free") == \ "x .or. (y .neqv. z)" assert fcode(Or(Xor(z, x, evaluate=False), y), source_format="free") == \ "y .or. (x .neqv. z)" assert fcode(Or(Xor(x, y, evaluate=False), z), source_format="free") == \ "z .or. (x .neqv. y)" # trinary Xor assert fcode(Xor(x, y, z, evaluate=False), source_format="free") == \ "x .neqv. y .neqv. z" assert fcode(Xor(x, y, Not(z), evaluate=False), source_format="free") == \ "x .neqv. y .neqv. .not. z" assert fcode(Xor(x, Not(y), z, evaluate=False), source_format="free") == \ "x .neqv. z .neqv. .not. y" assert fcode(Xor(Not(x), y, z, evaluate=False), source_format="free") == \ "y .neqv. z .neqv. .not. x" def test_fcode_Relational(): x, y = symbols("x y") assert fcode(Relational(x, y, "=="), source_format="free") == "x == y" assert fcode(Relational(x, y, "!="), source_format="free") == "x /= y" assert fcode(Relational(x, y, ">="), source_format="free") == "x >= y" assert fcode(Relational(x, y, "<="), source_format="free") == "x <= y" assert fcode(Relational(x, y, ">"), source_format="free") == "x > y" assert fcode(Relational(x, y, "<"), source_format="free") == "x < y" def test_fcode_Piecewise(): x = symbols('x') expr = Piecewise((x, x < 1), (x**2, True)) # Check that inline conditional (merge) fails if standard isn't 95+ raises(NotImplementedError, lambda: fcode(expr)) code = fcode(expr, standard=95) expected = " merge(x, x**2, x < 1)" assert code == expected assert fcode(Piecewise((x, x < 1), (x**2, True)), assign_to="var") == ( " if (x < 1) then\n" " var = x\n" " else\n" " var = x**2\n" " end if" ) a = cos(x)/x b = sin(x)/x for i in range(10): a = diff(a, x) b = diff(b, x) expected = ( " if (x < 0) then\n" " weird_name = -cos(x)/x + 10*sin(x)/x**2 + 90*cos(x)/x**3 - 720*\n" " @ sin(x)/x**4 - 5040*cos(x)/x**5 + 30240*sin(x)/x**6 + 151200*cos(x\n" " @ )/x**7 - 604800*sin(x)/x**8 - 1814400*cos(x)/x**9 + 3628800*sin(x\n" " @ )/x**10 + 3628800*cos(x)/x**11\n" " else\n" " weird_name = -sin(x)/x - 10*cos(x)/x**2 + 90*sin(x)/x**3 + 720*\n" " @ cos(x)/x**4 - 5040*sin(x)/x**5 - 30240*cos(x)/x**6 + 151200*sin(x\n" " @ )/x**7 + 604800*cos(x)/x**8 - 1814400*sin(x)/x**9 - 3628800*cos(x\n" " @ )/x**10 + 3628800*sin(x)/x**11\n" " end if" ) code = fcode(Piecewise((a, x < 0), (b, True)), assign_to="weird_name") assert code == expected code = fcode(Piecewise((x, x < 1), (x**2, x > 1), (sin(x), True)), standard=95) expected = " merge(x, merge(x**2, sin(x), x > 1), x < 1)" assert code == expected # Check that Piecewise without a True (default) condition error expr = Piecewise((x, x < 1), (x**2, x > 1), (sin(x), x > 0)) raises(ValueError, lambda: fcode(expr)) def test_wrap_fortran(): # "########################################################################" printer = FCodePrinter() lines = [ "C This is a long comment on a single line that must be wrapped properly to produce nice output", " this = is + a + long + and + nasty + fortran + statement + that * must + be + wrapped + properly", " this = is + a + long + and + nasty + fortran + statement + that * must + be + wrapped + properly", " this = is + a + long + and + nasty + fortran + statement + that * must + be + wrapped + properly", " this = is + a + long + and + nasty + fortran + statement + that*must + be + wrapped + properly", " this = is + a + long + and + nasty + fortran + statement + that*must + be + wrapped + properly", " this = is + a + long + and + nasty + fortran + statement + that*must + be + wrapped + properly", " this = is + a + long + and + nasty + fortran + statement + that*must + be + wrapped + properly", " this = is + a + long + and + nasty + fortran + statement + that**must + be + wrapped + properly", " this = is + a + long + and + nasty + fortran + statement + that**must + be + wrapped + properly", " this = is + a + long + and + nasty + fortran + statement + that**must + be + wrapped + properly", " this = is + a + long + and + nasty + fortran + statement + that**must + be + wrapped + properly", " this = is + a + long + and + nasty + fortran + statement + that**must + be + wrapped + properly", " this = is + a + long + and + nasty + fortran + statement(that)/must + be + wrapped + properly", " this = is + a + long + and + nasty + fortran + statement(that)/must + be + wrapped + properly", ] wrapped_lines = printer._wrap_fortran(lines) expected_lines = [ "C This is a long comment on a single line that must be wrapped", "C properly to produce nice output", " this = is + a + long + and + nasty + fortran + statement + that *", " @ must + be + wrapped + properly", " this = is + a + long + and + nasty + fortran + statement + that *", " @ must + be + wrapped + properly", " this = is + a + long + and + nasty + fortran + statement + that", " @ * must + be + wrapped + properly", " this = is + a + long + and + nasty + fortran + statement + that*", " @ must + be + wrapped + properly", " this = is + a + long + and + nasty + fortran + statement + that*", " @ must + be + wrapped + properly", " this = is + a + long + and + nasty + fortran + statement + that", " @ *must + be + wrapped + properly", " this = is + a + long + and + nasty + fortran + statement +", " @ that*must + be + wrapped + properly", " this = is + a + long + and + nasty + fortran + statement + that**", " @ must + be + wrapped + properly", " this = is + a + long + and + nasty + fortran + statement + that**", " @ must + be + wrapped + properly", " this = is + a + long + and + nasty + fortran + statement + that", " @ **must + be + wrapped + properly", " this = is + a + long + and + nasty + fortran + statement + that", " @ **must + be + wrapped + properly", " this = is + a + long + and + nasty + fortran + statement +", " @ that**must + be + wrapped + properly", " this = is + a + long + and + nasty + fortran + statement(that)/", " @ must + be + wrapped + properly", " this = is + a + long + and + nasty + fortran + statement(that)", " @ /must + be + wrapped + properly", ] for line in wrapped_lines: assert len(line) <= 72 for w, e in zip(wrapped_lines, expected_lines): assert w == e assert len(wrapped_lines) == len(expected_lines) def test_wrap_fortran_keep_d0(): printer = FCodePrinter() lines = [ ' this_variable_is_very_long_because_we_try_to_test_line_break=1.0d0', ' this_variable_is_very_long_because_we_try_to_test_line_break =1.0d0', ' this_variable_is_very_long_because_we_try_to_test_line_break = 1.0d0', ' this_variable_is_very_long_because_we_try_to_test_line_break = 1.0d0', ' this_variable_is_very_long_because_we_try_to_test_line_break = 1.0d0', ' this_variable_is_very_long_because_we_try_to_test_line_break = 10.0d0' ] expected = [ ' this_variable_is_very_long_because_we_try_to_test_line_break=1.0d0', ' this_variable_is_very_long_because_we_try_to_test_line_break =', ' @ 1.0d0', ' this_variable_is_very_long_because_we_try_to_test_line_break =', ' @ 1.0d0', ' this_variable_is_very_long_because_we_try_to_test_line_break =', ' @ 1.0d0', ' this_variable_is_very_long_because_we_try_to_test_line_break =', ' @ 1.0d0', ' this_variable_is_very_long_because_we_try_to_test_line_break =', ' @ 10.0d0' ] assert printer._wrap_fortran(lines) == expected def test_settings(): raises(TypeError, lambda: fcode(S(4), method="garbage")) def test_free_form_code_line(): x, y = symbols('x,y') assert fcode(cos(x) + sin(y), source_format='free') == "sin(y) + cos(x)" def test_free_form_continuation_line(): x, y = symbols('x,y') result = fcode(((cos(x) + sin(y))**(7)).expand(), source_format='free') expected = ( 'sin(y)**7 + 7*sin(y)**6*cos(x) + 21*sin(y)**5*cos(x)**2 + 35*sin(y)**4* &\n' ' cos(x)**3 + 35*sin(y)**3*cos(x)**4 + 21*sin(y)**2*cos(x)**5 + 7* &\n' ' sin(y)*cos(x)**6 + cos(x)**7' ) assert result == expected def test_free_form_comment_line(): printer = FCodePrinter({'source_format': 'free'}) lines = [ "! This is a long comment on a single line that must be wrapped properly to produce nice output"] expected = [ '! This is a long comment on a single line that must be wrapped properly', '! to produce nice output'] assert printer._wrap_fortran(lines) == expected def test_loops(): n, m = symbols('n,m', integer=True) A = IndexedBase('A') x = IndexedBase('x') y = IndexedBase('y') i = Idx('i', m) j = Idx('j', n) expected = ( 'do i = 1, m\n' ' y(i) = 0\n' 'end do\n' 'do i = 1, m\n' ' do j = 1, n\n' ' y(i) = %(rhs)s\n' ' end do\n' 'end do' ) code = fcode(A[i, j]*x[j], assign_to=y[i], source_format='free') assert (code == expected % {'rhs': 'y(i) + A(i, j)*x(j)'} or code == expected % {'rhs': 'y(i) + x(j)*A(i, j)'} or code == expected % {'rhs': 'x(j)*A(i, j) + y(i)'} or code == expected % {'rhs': 'A(i, j)*x(j) + y(i)'}) def test_dummy_loops(): i, m = symbols('i m', integer=True, cls=Dummy) x = IndexedBase('x') y = IndexedBase('y') i = Idx(i, m) expected = ( 'do i_%(icount)i = 1, m_%(mcount)i\n' ' y(i_%(icount)i) = x(i_%(icount)i)\n' 'end do' ) % {'icount': i.label.dummy_index, 'mcount': m.dummy_index} code = fcode(x[i], assign_to=y[i], source_format='free') assert code == expected def test_fcode_Indexed_without_looking_for_contraction(): len_y = 5 y = IndexedBase('y', shape=(len_y,)) x = IndexedBase('x', shape=(len_y,)) Dy = IndexedBase('Dy', shape=(len_y-1,)) i = Idx('i', len_y-1) e=Eq(Dy[i], (y[i+1]-y[i])/(x[i+1]-x[i])) code0 = fcode(e.rhs, assign_to=e.lhs, contract=False) assert code0.endswith('Dy(i) = (y(i + 1) - y(i))/(x(i + 1) - x(i))') def test_derived_classes(): class MyFancyFCodePrinter(FCodePrinter): _default_settings = FCodePrinter._default_settings.copy() printer = MyFancyFCodePrinter() x = symbols('x') assert printer.doprint(sin(x), "bork") == " bork = sin(x)" def test_indent(): codelines = ( 'subroutine test(a)\n' 'integer :: a, i, j\n' '\n' 'do\n' 'do \n' 'do j = 1, 5\n' 'if (a>b) then\n' 'if(b>0) then\n' 'a = 3\n' 'donot_indent_me = 2\n' 'do_not_indent_me_either = 2\n' 'ifIam_indented_something_went_wrong = 2\n' 'if_I_am_indented_something_went_wrong = 2\n' 'end should not be unindented here\n' 'end if\n' 'endif\n' 'end do\n' 'end do\n' 'enddo\n' 'end subroutine\n' '\n' 'subroutine test2(a)\n' 'integer :: a\n' 'do\n' 'a = a + 1\n' 'end do \n' 'end subroutine\n' ) expected = ( 'subroutine test(a)\n' 'integer :: a, i, j\n' '\n' 'do\n' ' do \n' ' do j = 1, 5\n' ' if (a>b) then\n' ' if(b>0) then\n' ' a = 3\n' ' donot_indent_me = 2\n' ' do_not_indent_me_either = 2\n' ' ifIam_indented_something_went_wrong = 2\n' ' if_I_am_indented_something_went_wrong = 2\n' ' end should not be unindented here\n' ' end if\n' ' endif\n' ' end do\n' ' end do\n' 'enddo\n' 'end subroutine\n' '\n' 'subroutine test2(a)\n' 'integer :: a\n' 'do\n' ' a = a + 1\n' 'end do \n' 'end subroutine\n' ) p = FCodePrinter({'source_format': 'free'}) result = p.indent_code(codelines) assert result == expected def test_Matrix_printing(): x, y, z = symbols('x,y,z') # Test returning a Matrix mat = Matrix([x*y, Piecewise((2 + x, y>0), (y, True)), sin(z)]) A = MatrixSymbol('A', 3, 1) assert fcode(mat, A) == ( " A(1, 1) = x*y\n" " if (y > 0) then\n" " A(2, 1) = x + 2\n" " else\n" " A(2, 1) = y\n" " end if\n" " A(3, 1) = sin(z)") # Test using MatrixElements in expressions expr = Piecewise((2*A[2, 0], x > 0), (A[2, 0], True)) + sin(A[1, 0]) + A[0, 0] assert fcode(expr, standard=95) == ( " merge(2*A(3, 1), A(3, 1), x > 0) + sin(A(2, 1)) + A(1, 1)") # Test using MatrixElements in a Matrix q = MatrixSymbol('q', 5, 1) M = MatrixSymbol('M', 3, 3) m = Matrix([[sin(q[1,0]), 0, cos(q[2,0])], [q[1,0] + q[2,0], q[3, 0], 5], [2*q[4, 0]/q[1,0], sqrt(q[0,0]) + 4, 0]]) assert fcode(m, M) == ( " M(1, 1) = sin(q(2, 1))\n" " M(2, 1) = q(2, 1) + q(3, 1)\n" " M(3, 1) = 2*q(5, 1)/q(2, 1)\n" " M(1, 2) = 0\n" " M(2, 2) = q(4, 1)\n" " M(3, 2) = sqrt(q(1, 1)) + 4\n" " M(1, 3) = cos(q(3, 1))\n" " M(2, 3) = 5\n" " M(3, 3) = 0") def test_fcode_For(): x, y = symbols('x y') f = For(x, Range(0, 10, 2), [Assignment(y, x * y)]) sol = fcode(f) assert sol == (" do x = 0, 10, 2\n" " y = x*y\n" " end do") def test_fcode_Declaration(): def check(expr, ref, **kwargs): assert fcode(expr, standard=95, source_format='free', **kwargs) == ref i = symbols('i', integer=True) var1 = Variable.deduced(i) dcl1 = Declaration(var1) check(dcl1, "integer*4 :: i") x, y = symbols('x y') var2 = Variable(x, float32, value=42, attrs={value_const}) dcl2b = Declaration(var2) check(dcl2b, 'real*4, parameter :: x = 42') var3 = Variable(y, type=bool_) dcl3 = Declaration(var3) check(dcl3, 'logical :: y') check(float32, "real*4") check(float64, "real*8") check(real, "real*4", type_aliases={real: float32}) check(real, "real*8", type_aliases={real: float64}) def test_MatrixElement_printing(): # test cases for issue #11821 A = MatrixSymbol("A", 1, 3) B = MatrixSymbol("B", 1, 3) C = MatrixSymbol("C", 1, 3) assert(fcode(A[0, 0]) == " A(1, 1)") assert(fcode(3 * A[0, 0]) == " 3*A(1, 1)") F = C[0, 0].subs(C, A - B) assert(fcode(F) == " (A - B)(1, 1)") def test_aug_assign(): x = symbols('x') assert fcode(aug_assign(x, '+', 1), source_format='free') == 'x = x + 1' def test_While(): x = symbols('x') assert fcode(While(abs(x) > 1, [aug_assign(x, '-', 1)]), source_format='free') == ( 'do while (abs(x) > 1)\n' ' x = x - 1\n' 'end do' ) def test_FunctionPrototype_print(): x = symbols('x') n = symbols('n', integer=True) vx = Variable(x, type=real) vn = Variable(n, type=integer) fp1 = FunctionPrototype(real, 'power', [vx, vn]) # Should be changed to proper test once multi-line generation is working # see https://github.com/sympy/sympy/issues/15824 raises(NotImplementedError, lambda: fcode(fp1)) def test_FunctionDefinition_print(): x = symbols('x') n = symbols('n', integer=True) vx = Variable(x, type=real) vn = Variable(n, type=integer) body = [Assignment(x, x**n), Return(x)] fd1 = FunctionDefinition(real, 'power', [vx, vn], body) # Should be changed to proper test once multi-line generation is working # see https://github.com/sympy/sympy/issues/15824 raises(NotImplementedError, lambda: fcode(fd1))
efae39c37691924c1edbaa23e29d95aaa7e54b01678c48f0e42108944bfd5b8b
from sympy import symbols, sin, Matrix, Interval, Piecewise, Sum, lambdify, \ Expr, sqrt from sympy.testing.pytest import raises from sympy.printing.tensorflow import TensorflowPrinter from sympy.printing.lambdarepr import lambdarepr, LambdaPrinter, NumExprPrinter x, y, z = symbols("x,y,z") i, a, b = symbols("i,a,b") j, c, d = symbols("j,c,d") def test_basic(): assert lambdarepr(x*y) == "x*y" assert lambdarepr(x + y) in ["y + x", "x + y"] assert lambdarepr(x**y) == "x**y" def test_matrix(): A = Matrix([[x, y], [y*x, z**2]]) # assert lambdarepr(A) == "ImmutableDenseMatrix([[x, y], [x*y, z**2]])" # Test printing a Matrix that has an element that is printed differently # with the LambdaPrinter than in the StrPrinter. p = Piecewise((x, True), evaluate=False) A = Matrix([p]) assert lambdarepr(A) == "ImmutableDenseMatrix([[((x))]])" def test_piecewise(): # In each case, test eval() the lambdarepr() to make sure there are a # correct number of parentheses. It will give a SyntaxError if there aren't. h = "lambda x: " p = Piecewise((x, True), evaluate=False) l = lambdarepr(p) eval(h + l) assert l == "((x))" p = Piecewise((x, x < 0)) l = lambdarepr(p) eval(h + l) assert l == "((x) if (x < 0) else None)" p = Piecewise( (1, x < 1), (2, x < 2), (0, True) ) l = lambdarepr(p) eval(h + l) assert l == "((1) if (x < 1) else (2) if (x < 2) else (0))" p = Piecewise( (1, x < 1), (2, x < 2), ) l = lambdarepr(p) eval(h + l) assert l == "((1) if (x < 1) else (2) if (x < 2) else None)" p = Piecewise( (x, x < 1), (x**2, Interval(3, 4, True, False).contains(x)), (0, True), ) l = lambdarepr(p) eval(h + l) assert l == "((x) if (x < 1) else (x**2) if (((x <= 4)) and ((x > 3))) else (0))" p = Piecewise( (x**2, x < 0), (x, x < 1), (2 - x, x >= 1), (0, True), evaluate=False ) l = lambdarepr(p) eval(h + l) assert l == "((x**2) if (x < 0) else (x) if (x < 1)"\ " else (2 - x) if (x >= 1) else (0))" p = Piecewise( (x**2, x < 0), (x, x < 1), (2 - x, x >= 1), evaluate=False ) l = lambdarepr(p) eval(h + l) assert l == "((x**2) if (x < 0) else (x) if (x < 1)"\ " else (2 - x) if (x >= 1) else None)" p = Piecewise( (1, x >= 1), (2, x >= 2), (3, x >= 3), (4, x >= 4), (5, x >= 5), (6, True) ) l = lambdarepr(p) eval(h + l) assert l == "((1) if (x >= 1) else (2) if (x >= 2) else (3) if (x >= 3)"\ " else (4) if (x >= 4) else (5) if (x >= 5) else (6))" p = Piecewise( (1, x <= 1), (2, x <= 2), (3, x <= 3), (4, x <= 4), (5, x <= 5), (6, True) ) l = lambdarepr(p) eval(h + l) assert l == "((1) if (x <= 1) else (2) if (x <= 2) else (3) if (x <= 3)"\ " else (4) if (x <= 4) else (5) if (x <= 5) else (6))" p = Piecewise( (1, x > 1), (2, x > 2), (3, x > 3), (4, x > 4), (5, x > 5), (6, True) ) l = lambdarepr(p) eval(h + l) assert l =="((1) if (x > 1) else (2) if (x > 2) else (3) if (x > 3)"\ " else (4) if (x > 4) else (5) if (x > 5) else (6))" p = Piecewise( (1, x < 1), (2, x < 2), (3, x < 3), (4, x < 4), (5, x < 5), (6, True) ) l = lambdarepr(p) eval(h + l) assert l == "((1) if (x < 1) else (2) if (x < 2) else (3) if (x < 3)"\ " else (4) if (x < 4) else (5) if (x < 5) else (6))" p = Piecewise( (Piecewise( (1, x > 0), (2, True) ), y > 0), (3, True) ) l = lambdarepr(p) eval(h + l) assert l == "((((1) if (x > 0) else (2))) if (y > 0) else (3))" def test_sum__1(): # In each case, test eval() the lambdarepr() to make sure that # it evaluates to the same results as the symbolic expression s = Sum(x ** i, (i, a, b)) l = lambdarepr(s) assert l == "(builtins.sum(x**i for i in range(a, b+1)))" args = x, a, b f = lambdify(args, s) v = 2, 3, 8 assert f(*v) == s.subs(zip(args, v)).doit() def test_sum__2(): s = Sum(i * x, (i, a, b)) l = lambdarepr(s) assert l == "(builtins.sum(i*x for i in range(a, b+1)))" args = x, a, b f = lambdify(args, s) v = 2, 3, 8 assert f(*v) == s.subs(zip(args, v)).doit() def test_multiple_sums(): s = Sum(i * x + j, (i, a, b), (j, c, d)) l = lambdarepr(s) assert l == "(builtins.sum(i*x + j for i in range(a, b+1) for j in range(c, d+1)))" args = x, a, b, c, d f = lambdify(args, s) vals = 2, 3, 4, 5, 6 f_ref = s.subs(zip(args, vals)).doit() f_res = f(*vals) assert f_res == f_ref def test_sqrt(): prntr = LambdaPrinter({'standard' : 'python2'}) assert prntr._print_Pow(sqrt(x), rational=False) == 'sqrt(x)' assert prntr._print_Pow(sqrt(x), rational=True) == 'x**(1./2.)' prntr = LambdaPrinter({'standard' : 'python3'}) assert prntr._print_Pow(sqrt(x), rational=True) == 'x**(1/2)' def test_settings(): raises(TypeError, lambda: lambdarepr(sin(x), method="garbage")) class CustomPrintedObject(Expr): def _lambdacode(self, printer): return 'lambda' def _tensorflowcode(self, printer): return 'tensorflow' def _numpycode(self, printer): return 'numpy' def _numexprcode(self, printer): return 'numexpr' def _mpmathcode(self, printer): return 'mpmath' def test_printmethod(): # In each case, printmethod is called to test # its working obj = CustomPrintedObject() assert LambdaPrinter().doprint(obj) == 'lambda' assert TensorflowPrinter().doprint(obj) == 'tensorflow' assert NumExprPrinter().doprint(obj) == "evaluate('numexpr', truediv=True)" assert NumExprPrinter().doprint(Piecewise((y, x >= 0), (z, x < 0))) == \ "evaluate('where((x >= 0), y, z)', truediv=True)"
16737e28fd3ea8febe4eb1fce378d0296dcd513f7695dbb2dafa309262521777
from sympy.core import ( S, pi, oo, symbols, Rational, Integer, Float, Mod, GoldenRatio, EulerGamma, Catalan, Lambda, Dummy, Eq, nan, Mul, Pow ) from sympy.functions import ( Abs, acos, acosh, asin, asinh, atan, atanh, atan2, ceiling, cos, cosh, erf, erfc, exp, floor, gamma, log, loggamma, Max, Min, Piecewise, sign, sin, sinh, sqrt, tan, tanh ) from sympy.sets import Range from sympy.logic import ITE from sympy.codegen import For, aug_assign, Assignment from sympy.testing.pytest import raises, XFAIL from sympy.printing.ccode import C89CodePrinter, C99CodePrinter, get_math_macros from sympy.codegen.ast import ( AddAugmentedAssignment, Element, Type, FloatType, Declaration, Pointer, Variable, value_const, pointer_const, While, Scope, Print, FunctionPrototype, FunctionDefinition, FunctionCall, Return, real, float32, float64, float80, float128, intc, Comment, CodeBlock ) from sympy.codegen.cfunctions import expm1, log1p, exp2, log2, fma, log10, Cbrt, hypot, Sqrt from sympy.codegen.cnodes import restrict from sympy.utilities.lambdify import implemented_function from sympy.tensor import IndexedBase, Idx from sympy.matrices import Matrix, MatrixSymbol from sympy import ccode x, y, z = symbols('x,y,z') 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(x)) == "sqrt(x)" def test_ccode_Pow(): assert ccode(x**3) == "pow(x, 3)" assert ccode(x**(y**3)) == "pow(x, pow(y, 3))" g = implemented_function('g', Lambda(x, 2*x)) assert ccode(1/(g(x)*3.5)**(x - y**x)/(x**2 + y)) == \ "pow(3.5*2*x, -x + pow(y, x))/(pow(x, 2) + y)" assert ccode(x**-1.0) == '1.0/x' assert ccode(x**Rational(2, 3)) == 'pow(x, 2.0/3.0)' assert ccode(x**Rational(2, 3), type_aliases={real: float80}) == 'powl(x, 2.0L/3.0L)' _cond_cfunc = [(lambda base, exp: exp.is_integer, "dpowi"), (lambda base, exp: not exp.is_integer, "pow")] assert ccode(x**3, user_functions={'Pow': _cond_cfunc}) == 'dpowi(x, 3)' assert ccode(x**0.5, user_functions={'Pow': _cond_cfunc}) == 'pow(x, 0.5)' assert ccode(x**Rational(16, 5), user_functions={'Pow': _cond_cfunc}) == 'pow(x, 16.0/5.0)' _cond_cfunc2 = [(lambda base, exp: base == 2, lambda base, exp: 'exp2(%s)' % exp), (lambda base, exp: base != 2, 'pow')] # Related to gh-11353 assert ccode(2**x, user_functions={'Pow': _cond_cfunc2}) == 'exp2(x)' assert ccode(x**2, user_functions={'Pow': _cond_cfunc2}) == 'pow(x, 2)' # For issue 14160 assert ccode(Mul(-2, x, Pow(Mul(y,y,evaluate=False), -1, evaluate=False), evaluate=False)) == '-2*x/(y*y)' def test_ccode_Max(): # Test for gh-11926 assert ccode(Max(x,x*x),user_functions={"Max":"my_max", "Pow":"my_pow"}) == 'my_max(x, my_pow(x, 2))' def test_ccode_Min_performance(): #Shouldn't take more than a few seconds big_min = Min(*symbols('a[0:50]')) for curr_standard in ('c89', 'c99', 'c11'): output = ccode(big_min, standard=curr_standard) assert output.count('(') == output.count(')') def test_ccode_constants_mathh(): assert ccode(exp(1)) == "M_E" assert ccode(pi) == "M_PI" assert ccode(oo, standard='c89') == "HUGE_VAL" assert ccode(-oo, standard='c89') == "-HUGE_VAL" assert ccode(oo) == "INFINITY" assert ccode(-oo, standard='c99') == "-INFINITY" assert ccode(pi, type_aliases={real: float80}) == "M_PIl" def test_ccode_constants_other(): assert ccode(2*GoldenRatio) == "const double GoldenRatio = %s;\n2*GoldenRatio" % GoldenRatio.evalf(17) assert ccode( 2*Catalan) == "const double Catalan = %s;\n2*Catalan" % Catalan.evalf(17) assert ccode(2*EulerGamma) == "const double EulerGamma = %s;\n2*EulerGamma" % EulerGamma.evalf(17) def test_ccode_Rational(): assert ccode(Rational(3, 7)) == "3.0/7.0" assert ccode(Rational(3, 7), type_aliases={real: float80}) == "3.0L/7.0L" assert ccode(Rational(18, 9)) == "2" assert ccode(Rational(3, -7)) == "-3.0/7.0" assert ccode(Rational(3, -7), type_aliases={real: float80}) == "-3.0L/7.0L" assert ccode(Rational(-3, -7)) == "3.0/7.0" assert ccode(Rational(-3, -7), type_aliases={real: float80}) == "3.0L/7.0L" assert ccode(x + Rational(3, 7)) == "x + 3.0/7.0" assert ccode(x + Rational(3, 7), type_aliases={real: float80}) == "x + 3.0L/7.0L" assert ccode(Rational(3, 7)*x) == "(3.0/7.0)*x" assert ccode(Rational(3, 7)*x, type_aliases={real: float80}) == "(3.0L/7.0L)*x" def test_ccode_Integer(): assert ccode(Integer(67)) == "67" assert ccode(Integer(-1)) == "-1" def test_ccode_functions(): assert ccode(sin(x) ** cos(x)) == "pow(sin(x), cos(x))" 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)) == "const double Catalan = %s;\n2*x/Catalan" % Catalan.evalf(17) 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_ccode_exceptions(): assert ccode(gamma(x), standard='C99') == "tgamma(x)" gamma_c89 = ccode(gamma(x), standard='C89') assert 'not supported in c' in gamma_c89.lower() gamma_c89 = ccode(gamma(x), standard='C89', allow_unknown_functions=False) assert 'not supported in c' in gamma_c89.lower() gamma_c89 = ccode(gamma(x), standard='C89', allow_unknown_functions=True) assert not 'not supported in c' in gamma_c89.lower() assert ccode(ceiling(x)) == "ceil(x)" assert ccode(Abs(x)) == "fabs(x)" assert ccode(gamma(x)) == "tgamma(x)" r, s = symbols('r,s', real=True) assert ccode(Mod(ceiling(r), ceiling(s))) == "((ceil(r)) % (ceil(s)))" assert ccode(Mod(r, s)) == "fmod(r, s)" 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_ccode_boolean(): assert ccode(True) == "true" assert ccode(S.true) == "true" assert ccode(False) == "false" assert ccode(S.false) == "false" assert ccode(x & y) == "x && y" assert ccode(x | y) == "x || y" assert ccode(~x) == "!x" assert ccode(x & y & z) == "x && y && z" assert ccode(x | y | z) == "x || y || z" assert ccode((x & y) | z) == "z || x && y" assert ccode((x | y) & z) == "z && (x || y)" def test_ccode_Relational(): from sympy import Eq, Ne, Le, Lt, Gt, Ge assert ccode(Eq(x, y)) == "x == y" assert ccode(Ne(x, y)) == "x != y" assert ccode(Le(x, y)) == "x <= y" assert ccode(Lt(x, y)) == "x < y" assert ccode(Gt(x, y)) == "x > y" assert ccode(Ge(x, y)) == "x >= y" def test_ccode_Piecewise(): expr = Piecewise((x, x < 1), (x**2, True)) assert ccode(expr) == ( "((x < 1) ? (\n" " x\n" ")\n" ": (\n" " pow(x, 2)\n" "))") assert ccode(expr, assign_to="c") == ( "if (x < 1) {\n" " c = x;\n" "}\n" "else {\n" " c = pow(x, 2);\n" "}") expr = Piecewise((x, x < 1), (x + 1, x < 2), (x**2, True)) assert ccode(expr) == ( "((x < 1) ? (\n" " x\n" ")\n" ": ((x < 2) ? (\n" " x + 1\n" ")\n" ": (\n" " pow(x, 2)\n" ")))") assert ccode(expr, assign_to='c') == ( "if (x < 1) {\n" " c = x;\n" "}\n" "else if (x < 2) {\n" " c = x + 1;\n" "}\n" "else {\n" " c = pow(x, 2);\n" "}") # Check that Piecewise without a True (default) condition error expr = Piecewise((x, x < 1), (x**2, x > 1), (sin(x), x > 0)) raises(ValueError, lambda: ccode(expr)) def test_ccode_sinc(): from sympy import sinc expr = sinc(x) assert ccode(expr) == ( "((x != 0) ? (\n" " sin(x)/x\n" ")\n" ": (\n" " 1\n" "))") def test_ccode_Piecewise_deep(): p = ccode(2*Piecewise((x, x < 1), (x + 1, x < 2), (x**2, True))) assert p == ( "2*((x < 1) ? (\n" " x\n" ")\n" ": ((x < 2) ? (\n" " x + 1\n" ")\n" ": (\n" " pow(x, 2)\n" ")))") expr = x*y*z + x**2 + y**2 + Piecewise((0, x < 0.5), (1, True)) + cos(z) - 1 assert ccode(expr) == ( "pow(x, 2) + x*y*z + pow(y, 2) + ((x < 0.5) ? (\n" " 0\n" ")\n" ": (\n" " 1\n" ")) + cos(z) - 1") assert ccode(expr, assign_to='c') == ( "c = pow(x, 2) + x*y*z + pow(y, 2) + ((x < 0.5) ? (\n" " 0\n" ")\n" ": (\n" " 1\n" ")) + cos(z) - 1;") def test_ccode_ITE(): expr = ITE(x < 1, y, z) assert ccode(expr) == ( "((x < 1) ? (\n" " y\n" ")\n" ": (\n" " z\n" "))") def test_ccode_settings(): raises(TypeError, lambda: ccode(sin(x), method="garbage")) def test_ccode_Indexed(): from sympy.tensor import IndexedBase, Idx from sympy import symbols s, n, m, o = symbols('s n m o', integer=True) i, j, k = Idx('i', n), Idx('j', m), Idx('k', o) x = IndexedBase('x')[j] A = IndexedBase('A')[i, j] B = IndexedBase('B')[i, j, k] p = C99CodePrinter() assert p._print_Indexed(x) == 'x[j]' assert p._print_Indexed(A) == 'A[%s]' % (m*i+j) assert p._print_Indexed(B) == 'B[%s]' % (i*o*m+j*o+k) A = IndexedBase('A', shape=(5,3))[i, j] assert p._print_Indexed(A) == 'A[%s]' % (3*i + j) A = IndexedBase('A', shape=(5,3), strides='F')[i, j] assert ccode(A) == 'A[%s]' % (i + 5*j) A = IndexedBase('A', shape=(29,29), strides=(1, s), offset=o)[i, j] assert ccode(A) == 'A[o + s*j + i]' Abase = IndexedBase('A', strides=(s, m, n), offset=o) assert ccode(Abase[i, j, k]) == 'A[m*j + n*k + o + s*i]' assert ccode(Abase[2, 3, k]) == 'A[3*m + n*k + o + 2*s]' def test_Element(): assert ccode(Element('x', 'ij')) == 'x[i][j]' assert ccode(Element('x', 'ij', strides='kl', offset='o')) == 'x[i*k + j*l + o]' assert ccode(Element('x', (3,))) == 'x[3]' assert ccode(Element('x', (3,4,5))) == 'x[3][4][5]' def test_ccode_Indexed_without_looking_for_contraction(): len_y = 5 y = IndexedBase('y', shape=(len_y,)) x = IndexedBase('x', shape=(len_y,)) Dy = IndexedBase('Dy', shape=(len_y-1,)) i = Idx('i', len_y-1) e=Eq(Dy[i], (y[i+1]-y[i])/(x[i+1]-x[i])) code0 = ccode(e.rhs, assign_to=e.lhs, contract=False) assert code0 == 'Dy[i] = (y[%s] - y[i])/(x[%s] - x[i]);' % (i + 1, i + 1) 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] = A[%s]*x[j] + y[i];\n' % (i*n + j) +\ ' }\n' '}' ) assert ccode(A[i, j]*x[j], assign_to=y[i]) == s def test_dummy_loops(): i, m = symbols('i m', integer=True, cls=Dummy) x = IndexedBase('x') y = IndexedBase('y') i = Idx(i, m) expected = ( 'for (int i_%(icount)i=0; i_%(icount)i<m_%(mcount)i; i_%(icount)i++){\n' ' y[i_%(icount)i] = x[i_%(icount)i];\n' '}' ) % {'icount': i.label.dummy_index, 'mcount': m.dummy_index} assert ccode(x[i], assign_to=y[i]) == expected def test_ccode_loops_add(): from sympy.tensor import IndexedBase, Idx from sympy import symbols n, m = symbols('n m', integer=True) A = IndexedBase('A') x = IndexedBase('x') y = IndexedBase('y') z = IndexedBase('z') i = Idx('i', m) j = Idx('j', n) s = ( 'for (int i=0; i<m; i++){\n' ' y[i] = x[i] + z[i];\n' '}\n' 'for (int i=0; i<m; i++){\n' ' for (int j=0; j<n; j++){\n' ' y[i] = A[%s]*x[j] + y[i];\n' % (i*n + j) +\ ' }\n' '}' ) assert ccode(A[i, j]*x[j] + x[i] + z[i], assign_to=y[i]) == s def test_ccode_loops_multiple_contractions(): from sympy.tensor import IndexedBase, Idx from sympy 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] = a[%s]*b[%s] + y[i];\n' % (i*n*o*p + j*o*p + k*p + l, j*o*p + k*p + l) +\ ' }\n' ' }\n' ' }\n' '}' ) assert ccode(b[j, k, l]*a[i, j, k, l], assign_to=y[i]) == s def test_ccode_loops_addfactor(): from sympy.tensor import IndexedBase, Idx from sympy 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 (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' '}' ) assert ccode((a[i, j, k, l] + b[i, j, k, l])*c[j, k, l], assign_to=y[i]) == s def test_ccode_loops_multiple_terms(): from sympy.tensor import IndexedBase, Idx from sympy 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] = a[%s]*b[k] + 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] = a[%s]*b[j] + 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_dereference_printing(): expr = x + y + sin(z) + z assert ccode(expr, dereference=[z]) == "x + y + (*z) + sin((*z))" def test_Matrix_printing(): # Test returning a Matrix mat = Matrix([x*y, Piecewise((2 + x, y>0), (y, True)), sin(z)]) A = MatrixSymbol('A', 3, 1) assert ccode(mat, A) == ( "A[0] = x*y;\n" "if (y > 0) {\n" " A[1] = x + 2;\n" "}\n" "else {\n" " A[1] = y;\n" "}\n" "A[2] = sin(z);") # Test using MatrixElements in expressions expr = Piecewise((2*A[2, 0], x > 0), (A[2, 0], True)) + sin(A[1, 0]) + A[0, 0] assert ccode(expr) == ( "((x > 0) ? (\n" " 2*A[2]\n" ")\n" ": (\n" " A[2]\n" ")) + sin(A[1]) + A[0]") # Test using MatrixElements in a Matrix q = MatrixSymbol('q', 5, 1) M = MatrixSymbol('M', 3, 3) m = Matrix([[sin(q[1,0]), 0, cos(q[2,0])], [q[1,0] + q[2,0], q[3, 0], 5], [2*q[4, 0]/q[1,0], sqrt(q[0,0]) + 4, 0]]) assert ccode(m, M) == ( "M[0] = sin(q[1]);\n" "M[1] = 0;\n" "M[2] = cos(q[2]);\n" "M[3] = q[1] + q[2];\n" "M[4] = q[3];\n" "M[5] = 5;\n" "M[6] = 2*q[4]/q[1];\n" "M[7] = sqrt(q[0]) + 4;\n" "M[8] = 0;") def test_ccode_reserved_words(): x, y = symbols('x, if') with raises(ValueError): ccode(y**2, error_on_reserved=True, standard='C99') assert ccode(y**2) == 'pow(if_, 2)' assert ccode(x * y**2, dereference=[y]) == 'pow((*if_), 2)*x' assert ccode(y**2, reserved_word_suffix='_unreserved') == 'pow(if_unreserved, 2)' def test_ccode_sign(): expr1, ref1 = sign(x) * y, 'y*(((x) > 0) - ((x) < 0))' expr2, ref2 = sign(cos(x)), '(((cos(x)) > 0) - ((cos(x)) < 0))' expr3, ref3 = sign(2 * x + x**2) * x + x**2, 'pow(x, 2) + x*(((pow(x, 2) + 2*x) > 0) - ((pow(x, 2) + 2*x) < 0))' assert ccode(expr1) == ref1 assert ccode(expr1, 'z') == 'z = %s;' % ref1 assert ccode(expr2) == ref2 assert ccode(expr3) == ref3 def test_ccode_Assignment(): assert ccode(Assignment(x, y + z)) == 'x = y + z;' assert ccode(aug_assign(x, '+', y + z)) == 'x += y + z;' def test_ccode_For(): f = For(x, Range(0, 10, 2), [aug_assign(y, '*', x)]) assert ccode(f) == ("for (x = 0; x < 10; x += 2) {\n" " y *= x;\n" "}") def test_ccode_Max_Min(): assert ccode(Max(x, 0), standard='C89') == '((0 > x) ? 0 : x)' assert ccode(Max(x, 0), standard='C99') == 'fmax(0, x)' assert ccode(Min(x, 0, sqrt(x)), standard='c89') == ( '((0 < ((x < sqrt(x)) ? x : sqrt(x))) ? 0 : ((x < sqrt(x)) ? x : sqrt(x)))' ) def test_ccode_standard(): assert ccode(expm1(x), standard='c99') == 'expm1(x)' assert ccode(nan, standard='c99') == 'NAN' assert ccode(float('nan'), standard='c99') == 'NAN' def test_C89CodePrinter(): c89printer = C89CodePrinter() assert c89printer.language == 'C' assert c89printer.standard == 'C89' assert 'void' in c89printer.reserved_words assert 'template' not in c89printer.reserved_words def test_C99CodePrinter(): assert C99CodePrinter().doprint(expm1(x)) == 'expm1(x)' assert C99CodePrinter().doprint(log1p(x)) == 'log1p(x)' assert C99CodePrinter().doprint(exp2(x)) == 'exp2(x)' assert C99CodePrinter().doprint(log2(x)) == 'log2(x)' assert C99CodePrinter().doprint(fma(x, y, -z)) == 'fma(x, y, -z)' assert C99CodePrinter().doprint(log10(x)) == 'log10(x)' assert C99CodePrinter().doprint(Cbrt(x)) == 'cbrt(x)' # note Cbrt due to cbrt already taken. assert C99CodePrinter().doprint(hypot(x, y)) == 'hypot(x, y)' assert C99CodePrinter().doprint(loggamma(x)) == 'lgamma(x)' assert C99CodePrinter().doprint(Max(x, 3, x**2)) == 'fmax(3, fmax(x, pow(x, 2)))' assert C99CodePrinter().doprint(Min(x, 3)) == 'fmin(3, x)' c99printer = C99CodePrinter() assert c99printer.language == 'C' assert c99printer.standard == 'C99' assert 'restrict' in c99printer.reserved_words assert 'using' not in c99printer.reserved_words @XFAIL def test_C99CodePrinter__precision_f80(): f80_printer = C99CodePrinter(dict(type_aliases={real: float80})) assert f80_printer.doprint(sin(x+Float('2.1'))) == 'sinl(x + 2.1L)' def test_C99CodePrinter__precision(): n = symbols('n', integer=True) f32_printer = C99CodePrinter(dict(type_aliases={real: float32})) f64_printer = C99CodePrinter(dict(type_aliases={real: float64})) f80_printer = C99CodePrinter(dict(type_aliases={real: float80})) assert f32_printer.doprint(sin(x+2.1)) == 'sinf(x + 2.1F)' assert f64_printer.doprint(sin(x+2.1)) == 'sin(x + 2.1000000000000001)' assert f80_printer.doprint(sin(x+Float('2.0'))) == 'sinl(x + 2.0L)' for printer, suffix in zip([f32_printer, f64_printer, f80_printer], ['f', '', 'l']): def check(expr, ref): assert printer.doprint(expr) == ref.format(s=suffix, S=suffix.upper()) check(Abs(n), 'abs(n)') check(Abs(x + 2.0), 'fabs{s}(x + 2.0{S})') check(sin(x + 4.0)**cos(x - 2.0), 'pow{s}(sin{s}(x + 4.0{S}), cos{s}(x - 2.0{S}))') check(exp(x*8.0), 'exp{s}(8.0{S}*x)') check(exp2(x), 'exp2{s}(x)') check(expm1(x*4.0), 'expm1{s}(4.0{S}*x)') check(Mod(n, 2), '((n) % (2))') check(Mod(2*n + 3, 3*n + 5), '((2*n + 3) % (3*n + 5))') check(Mod(x + 2.0, 3.0), 'fmod{s}(1.0{S}*x + 2.0{S}, 3.0{S})') check(Mod(x, 2.0*x + 3.0), 'fmod{s}(1.0{S}*x, 2.0{S}*x + 3.0{S})') check(log(x/2), 'log{s}((1.0{S}/2.0{S})*x)') check(log10(3*x/2), 'log10{s}((3.0{S}/2.0{S})*x)') check(log2(x*8.0), 'log2{s}(8.0{S}*x)') check(log1p(x), 'log1p{s}(x)') check(2**x, 'pow{s}(2, x)') check(2.0**x, 'pow{s}(2.0{S}, x)') check(x**3, 'pow{s}(x, 3)') check(x**4.0, 'pow{s}(x, 4.0{S})') check(sqrt(3+x), 'sqrt{s}(x + 3)') check(Cbrt(x-2.0), 'cbrt{s}(x - 2.0{S})') check(hypot(x, y), 'hypot{s}(x, y)') check(sin(3.*x + 2.), 'sin{s}(3.0{S}*x + 2.0{S})') check(cos(3.*x - 1.), 'cos{s}(3.0{S}*x - 1.0{S})') check(tan(4.*y + 2.), 'tan{s}(4.0{S}*y + 2.0{S})') check(asin(3.*x + 2.), 'asin{s}(3.0{S}*x + 2.0{S})') check(acos(3.*x + 2.), 'acos{s}(3.0{S}*x + 2.0{S})') check(atan(3.*x + 2.), 'atan{s}(3.0{S}*x + 2.0{S})') check(atan2(3.*x, 2.*y), 'atan2{s}(3.0{S}*x, 2.0{S}*y)') check(sinh(3.*x + 2.), 'sinh{s}(3.0{S}*x + 2.0{S})') check(cosh(3.*x - 1.), 'cosh{s}(3.0{S}*x - 1.0{S})') check(tanh(4.0*y + 2.), 'tanh{s}(4.0{S}*y + 2.0{S})') check(asinh(3.*x + 2.), 'asinh{s}(3.0{S}*x + 2.0{S})') check(acosh(3.*x + 2.), 'acosh{s}(3.0{S}*x + 2.0{S})') check(atanh(3.*x + 2.), 'atanh{s}(3.0{S}*x + 2.0{S})') check(erf(42.*x), 'erf{s}(42.0{S}*x)') check(erfc(42.*x), 'erfc{s}(42.0{S}*x)') check(gamma(x), 'tgamma{s}(x)') check(loggamma(x), 'lgamma{s}(x)') check(ceiling(x + 2.), "ceil{s}(x + 2.0{S})") check(floor(x + 2.), "floor{s}(x + 2.0{S})") check(fma(x, y, -z), 'fma{s}(x, y, -z)') check(Max(x, 8.0, x**4.0), 'fmax{s}(8.0{S}, fmax{s}(x, pow{s}(x, 4.0{S})))') check(Min(x, 2.0), 'fmin{s}(2.0{S}, x)') def test_get_math_macros(): macros = get_math_macros() assert macros[exp(1)] == 'M_E' assert macros[1/Sqrt(2)] == 'M_SQRT1_2' 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' def test_C99CodePrinter_custom_type(): # We will look at __float128 (new in glibc 2.26) f128 = FloatType('_Float128', float128.nbits, float128.nmant, float128.nexp) p128 = C99CodePrinter(dict( type_aliases={real: f128}, type_literal_suffixes={f128: 'Q'}, type_func_suffixes={f128: 'f128'}, type_math_macro_suffixes={ real: 'f128', f128: 'f128' }, type_macros={ f128: ('__STDC_WANT_IEC_60559_TYPES_EXT__',) } )) assert p128.doprint(x) == 'x' assert not p128.headers assert not p128.libraries assert not p128.macros assert p128.doprint(2.0) == '2.0Q' assert not p128.headers assert not p128.libraries assert p128.macros == {'__STDC_WANT_IEC_60559_TYPES_EXT__'} assert p128.doprint(Rational(1, 2)) == '1.0Q/2.0Q' assert p128.doprint(sin(x)) == 'sinf128(x)' assert p128.doprint(cos(2., evaluate=False)) == 'cosf128(2.0Q)' var5 = Variable(x, f128, attrs={value_const}) dcl5a = Declaration(var5) assert ccode(dcl5a) == 'const _Float128 x' var5b = Variable(x, f128, pi, attrs={value_const}) dcl5b = Declaration(var5b) assert p128.doprint(dcl5b) == 'const _Float128 x = M_PIf128' var5b = Variable(x, f128, value=Catalan.evalf(38), attrs={value_const}) dcl5c = Declaration(var5b) assert p128.doprint(dcl5c) == 'const _Float128 x = %sQ' % Catalan.evalf(f128.decimal_dig) def test_MatrixElement_printing(): # test cases for issue #11821 A = MatrixSymbol("A", 1, 3) B = MatrixSymbol("B", 1, 3) C = MatrixSymbol("C", 1, 3) assert(ccode(A[0, 0]) == "A[0]") assert(ccode(3 * A[0, 0]) == "3*A[0]") F = C[0, 0].subs(C, A - B) assert(ccode(F) == "(A - B)[0]") def test_ccode_math_macros(): assert ccode(z + exp(1)) == 'z + M_E' assert ccode(z + log2(exp(1))) == 'z + M_LOG2E' assert ccode(z + 1/log(2)) == 'z + M_LOG2E' assert ccode(z + log(2)) == 'z + M_LN2' assert ccode(z + log(10)) == 'z + M_LN10' assert ccode(z + pi) == 'z + M_PI' assert ccode(z + pi/2) == 'z + M_PI_2' assert ccode(z + pi/4) == 'z + M_PI_4' assert ccode(z + 1/pi) == 'z + M_1_PI' assert ccode(z + 2/pi) == 'z + M_2_PI' assert ccode(z + 2/sqrt(pi)) == 'z + M_2_SQRTPI' assert ccode(z + 2/Sqrt(pi)) == 'z + M_2_SQRTPI' assert ccode(z + sqrt(2)) == 'z + M_SQRT2' assert ccode(z + Sqrt(2)) == 'z + M_SQRT2' assert ccode(z + 1/sqrt(2)) == 'z + M_SQRT1_2' assert ccode(z + 1/Sqrt(2)) == 'z + M_SQRT1_2' def test_ccode_Type(): assert ccode(Type('float')) == 'float' assert ccode(intc) == 'int' def test_ccode_codegen_ast(): assert ccode(Comment("this is a comment")) == "// this is a comment" assert ccode(While(abs(x) > 1, [aug_assign(x, '-', 1)])) == ( 'while (fabs(x) > 1) {\n' ' x -= 1;\n' '}' ) assert ccode(Scope([AddAugmentedAssignment(x, 1)])) == ( '{\n' ' x += 1;\n' '}' ) inp_x = Declaration(Variable(x, type=real)) assert ccode(FunctionPrototype(real, 'pwer', [inp_x])) == 'double pwer(double x)' assert ccode(FunctionDefinition(real, 'pwer', [inp_x], [Assignment(x, x**2)])) == ( 'double pwer(double x){\n' ' x = pow(x, 2);\n' '}' ) # Elements of CodeBlock are formatted as statements: block = CodeBlock( x, Print([x, y], "%d %d"), FunctionCall('pwer', [x]), Return(x), ) assert ccode(block) == '\n'.join([ 'x;', 'printf("%d %d", x, y);', 'pwer(x);', 'return x;', ])
9d4ea81ef85da2aa795429eb1b2feee6d5c9aa1b02416f86764c0643f68e3421
from sympy import symbols, Derivative, Integral, exp, cos, oo, Function from sympy.functions.special.bessel import besselj from sympy.functions.special.polynomials import legendre from sympy.functions.combinatorial.numbers import bell from sympy.printing.conventions import split_super_sub, requires_partial from sympy.testing.pytest import XFAIL def test_super_sub(): assert split_super_sub("beta_13_2") == ("beta", [], ["13", "2"]) assert split_super_sub("beta_132_20") == ("beta", [], ["132", "20"]) assert split_super_sub("beta_13") == ("beta", [], ["13"]) assert split_super_sub("x_a_b") == ("x", [], ["a", "b"]) assert split_super_sub("x_1_2_3") == ("x", [], ["1", "2", "3"]) assert split_super_sub("x_a_b1") == ("x", [], ["a", "b1"]) assert split_super_sub("x_a_1") == ("x", [], ["a", "1"]) assert split_super_sub("x_1_a") == ("x", [], ["1", "a"]) assert split_super_sub("x_1^aa") == ("x", ["aa"], ["1"]) assert split_super_sub("x_1__aa") == ("x", ["aa"], ["1"]) assert split_super_sub("x_11^a") == ("x", ["a"], ["11"]) assert split_super_sub("x_11__a") == ("x", ["a"], ["11"]) assert split_super_sub("x_a_b_c_d") == ("x", [], ["a", "b", "c", "d"]) assert split_super_sub("x_a_b^c^d") == ("x", ["c", "d"], ["a", "b"]) assert split_super_sub("x_a_b__c__d") == ("x", ["c", "d"], ["a", "b"]) assert split_super_sub("x_a^b_c^d") == ("x", ["b", "d"], ["a", "c"]) assert split_super_sub("x_a__b_c__d") == ("x", ["b", "d"], ["a", "c"]) assert split_super_sub("x^a^b_c_d") == ("x", ["a", "b"], ["c", "d"]) assert split_super_sub("x__a__b_c_d") == ("x", ["a", "b"], ["c", "d"]) assert split_super_sub("x^a^b^c^d") == ("x", ["a", "b", "c", "d"], []) assert split_super_sub("x__a__b__c__d") == ("x", ["a", "b", "c", "d"], []) assert split_super_sub("alpha_11") == ("alpha", [], ["11"]) assert split_super_sub("alpha_11_11") == ("alpha", [], ["11", "11"]) assert split_super_sub("") == ("", [], []) def test_requires_partial(): x, y, z, t, nu = symbols('x y z t nu') n = symbols('n', integer=True) f = x * y assert requires_partial(Derivative(f, x)) is True assert requires_partial(Derivative(f, y)) is True ## integrating out one of the variables assert requires_partial(Derivative(Integral(exp(-x * y), (x, 0, oo)), y, evaluate=False)) is False ## bessel function with smooth parameter f = besselj(nu, x) assert requires_partial(Derivative(f, x)) is True assert requires_partial(Derivative(f, nu)) is True ## bessel function with integer parameter f = besselj(n, x) assert requires_partial(Derivative(f, x)) is False # this is not really valid (differentiating with respect to an integer) # but there's no reason to use the partial derivative symbol there. make # sure we don't throw an exception here, though assert requires_partial(Derivative(f, n)) is False ## bell polynomial f = bell(n, x) assert requires_partial(Derivative(f, x)) is False # again, invalid assert requires_partial(Derivative(f, n)) is False ## legendre polynomial f = legendre(0, x) assert requires_partial(Derivative(f, x)) is False f = legendre(n, x) assert requires_partial(Derivative(f, x)) is False # again, invalid assert requires_partial(Derivative(f, n)) is False f = x ** n assert requires_partial(Derivative(f, x)) is False assert requires_partial(Derivative(Integral((x*y) ** n * exp(-x * y), (x, 0, oo)), y, evaluate=False)) is False # parametric equation f = (exp(t), cos(t)) g = sum(f) assert requires_partial(Derivative(g, t)) is False f = symbols('f', cls=Function) assert requires_partial(Derivative(f(x), x)) is False assert requires_partial(Derivative(f(x), y)) is False assert requires_partial(Derivative(f(x, y), x)) is True assert requires_partial(Derivative(f(x, y), y)) is True assert requires_partial(Derivative(f(x, y), z)) is True assert requires_partial(Derivative(f(x, y), x, y)) is True @XFAIL def test_requires_partial_unspecified_variables(): x, y = symbols('x y') # function of unspecified variables f = symbols('f', cls=Function) assert requires_partial(Derivative(f, x)) is False assert requires_partial(Derivative(f, x, y)) is True
463120e548e586fb9e0a9bc8bd56fae494828a30e587c97730eb271208023ef5
from sympy.tensor.toperators import PartialDerivative from sympy import ( Abs, Chi, Ci, CosineTransform, Dict, Ei, Eq, FallingFactorial, FiniteSet, Float, FourierTransform, Function, Indexed, IndexedBase, Integral, Interval, InverseCosineTransform, InverseFourierTransform, Derivative, InverseLaplaceTransform, InverseMellinTransform, InverseSineTransform, Lambda, LaplaceTransform, Limit, Matrix, Max, MellinTransform, Min, Mul, Order, Piecewise, Poly, ring, field, ZZ, Pow, Product, Range, Rational, RisingFactorial, rootof, RootSum, S, Shi, Si, SineTransform, Subs, Sum, Symbol, ImageSet, Tuple, Ynm, Znm, arg, asin, acsc, Mod, assoc_laguerre, assoc_legendre, beta, binomial, catalan, ceiling, chebyshevt, chebyshevu, conjugate, cot, coth, diff, dirichlet_eta, euler, exp, expint, factorial, factorial2, floor, gamma, gegenbauer, hermite, hyper, im, jacobi, laguerre, legendre, lerchphi, log, frac, meijerg, oo, polar_lift, polylog, re, root, sin, sqrt, symbols, uppergamma, zeta, subfactorial, totient, elliptic_k, elliptic_f, elliptic_e, elliptic_pi, cos, tan, Wild, true, false, Equivalent, Not, Contains, divisor_sigma, SeqPer, SeqFormula, SeqAdd, SeqMul, fourier_series, pi, ConditionSet, ComplexRegion, fps, AccumBounds, reduced_totient, primenu, primeomega, SingularityFunction, stieltjes, mathieuc, mathieus, mathieucprime, mathieusprime, UnevaluatedExpr, Quaternion, I, KroneckerProduct, LambertW) from sympy.ntheory.factor_ import udivisor_sigma from sympy.abc import mu, tau from sympy.printing.latex import (latex, translate, greek_letters_set, tex_greek_dictionary, multiline_latex) from sympy.tensor.array import (ImmutableDenseNDimArray, ImmutableSparseNDimArray, MutableSparseNDimArray, MutableDenseNDimArray, tensorproduct) from sympy.testing.pytest import XFAIL, raises from sympy.functions import DiracDelta, Heaviside, KroneckerDelta, LeviCivita from sympy.functions.combinatorial.numbers import bernoulli, bell, lucas, \ fibonacci, tribonacci from sympy.logic import Implies from sympy.logic.boolalg import And, Or, Xor from sympy.physics.quantum import Commutator, Operator from sympy.physics.units import meter, gibibyte, microgram, second from sympy.core.trace import Tr from sympy.combinatorics.permutations import \ Cycle, Permutation, AppliedPermutation from sympy.matrices.expressions.permutation import PermutationMatrix from sympy import MatrixSymbol, ln from sympy.vector import CoordSys3D, Cross, Curl, Dot, Divergence, Gradient, Laplacian from sympy.sets.setexpr import SetExpr from sympy.sets.sets import \ Union, Intersection, Complement, SymmetricDifference, ProductSet import sympy as sym class lowergamma(sym.lowergamma): pass # testing notation inheritance by a subclass with same name x, y, z, t, a, b, c = symbols('x y z t a b c') k, m, n = symbols('k m n', integer=True) def test_printmethod(): class R(Abs): def _latex(self, printer): return "foo(%s)" % printer._print(self.args[0]) assert latex(R(x)) == "foo(x)" class R(Abs): def _latex(self, printer): return "foo" assert latex(R(x)) == "foo" def test_latex_basic(): assert latex(1 + x) == "x + 1" assert latex(x**2) == "x^{2}" assert latex(x**(1 + x)) == "x^{x + 1}" assert latex(x**3 + x + 1 + x**2) == "x^{3} + x^{2} + x + 1" assert latex(2*x*y) == "2 x y" assert latex(2*x*y, mul_symbol='dot') == r"2 \cdot x \cdot y" assert latex(3*x**2*y, mul_symbol='\\,') == r"3\,x^{2}\,y" assert latex(1.5*3**x, mul_symbol='\\,') == r"1.5 \cdot 3^{x}" assert latex(1/x) == r"\frac{1}{x}" assert latex(1/x, fold_short_frac=True) == "1 / x" assert latex(-S(3)/2) == r"- \frac{3}{2}" assert latex(-S(3)/2, fold_short_frac=True) == r"- 3 / 2" assert latex(1/x**2) == r"\frac{1}{x^{2}}" assert latex(1/(x + y)/2) == r"\frac{1}{2 \left(x + y\right)}" assert latex(x/2) == r"\frac{x}{2}" assert latex(x/2, fold_short_frac=True) == "x / 2" assert latex((x + y)/(2*x)) == r"\frac{x + y}{2 x}" assert latex((x + y)/(2*x), fold_short_frac=True) == \ r"\left(x + y\right) / 2 x" assert latex((x + y)/(2*x), long_frac_ratio=0) == \ r"\frac{1}{2 x} \left(x + y\right)" assert latex((x + y)/x) == r"\frac{x + y}{x}" assert latex((x + y)/x, long_frac_ratio=3) == r"\frac{x + y}{x}" assert latex((2*sqrt(2)*x)/3) == r"\frac{2 \sqrt{2} x}{3}" assert latex((2*sqrt(2)*x)/3, long_frac_ratio=2) == \ r"\frac{2 x}{3} \sqrt{2}" assert latex(2*Integral(x, x)/3) == r"\frac{2 \int x\, dx}{3}" assert latex(2*Integral(x, x)/3, fold_short_frac=True) == \ r"\left(2 \int x\, dx\right) / 3" assert latex(sqrt(x)) == r"\sqrt{x}" assert latex(x**Rational(1, 3)) == r"\sqrt[3]{x}" assert latex(x**Rational(1, 3), root_notation=False) == r"x^{\frac{1}{3}}" assert latex(sqrt(x)**3) == r"x^{\frac{3}{2}}" assert latex(sqrt(x), itex=True) == r"\sqrt{x}" assert latex(x**Rational(1, 3), itex=True) == r"\root{3}{x}" assert latex(sqrt(x)**3, itex=True) == r"x^{\frac{3}{2}}" assert latex(x**Rational(3, 4)) == r"x^{\frac{3}{4}}" assert latex(x**Rational(3, 4), fold_frac_powers=True) == "x^{3/4}" assert latex((x + 1)**Rational(3, 4)) == \ r"\left(x + 1\right)^{\frac{3}{4}}" assert latex((x + 1)**Rational(3, 4), fold_frac_powers=True) == \ r"\left(x + 1\right)^{3/4}" assert latex(1.5e20*x) == r"1.5 \cdot 10^{20} x" assert latex(1.5e20*x, mul_symbol='dot') == r"1.5 \cdot 10^{20} \cdot x" assert latex(1.5e20*x, mul_symbol='times') == \ r"1.5 \times 10^{20} \times x" assert latex(1/sin(x)) == r"\frac{1}{\sin{\left(x \right)}}" assert latex(sin(x)**-1) == r"\frac{1}{\sin{\left(x \right)}}" assert latex(sin(x)**Rational(3, 2)) == \ r"\sin^{\frac{3}{2}}{\left(x \right)}" assert latex(sin(x)**Rational(3, 2), fold_frac_powers=True) == \ r"\sin^{3/2}{\left(x \right)}" assert latex(~x) == r"\neg x" assert latex(x & y) == r"x \wedge y" assert latex(x & y & z) == r"x \wedge y \wedge z" assert latex(x | y) == r"x \vee y" assert latex(x | y | z) == r"x \vee y \vee z" assert latex((x & y) | z) == r"z \vee \left(x \wedge y\right)" assert latex(Implies(x, y)) == r"x \Rightarrow y" assert latex(~(x >> ~y)) == r"x \not\Rightarrow \neg y" assert latex(Implies(Or(x,y), z)) == r"\left(x \vee y\right) \Rightarrow z" assert latex(Implies(z, Or(x,y))) == r"z \Rightarrow \left(x \vee y\right)" assert latex(~(x & y)) == r"\neg \left(x \wedge y\right)" assert latex(~x, symbol_names={x: "x_i"}) == r"\neg x_i" assert latex(x & y, symbol_names={x: "x_i", y: "y_i"}) == \ r"x_i \wedge y_i" assert latex(x & y & z, symbol_names={x: "x_i", y: "y_i", z: "z_i"}) == \ r"x_i \wedge y_i \wedge z_i" assert latex(x | y, symbol_names={x: "x_i", y: "y_i"}) == r"x_i \vee y_i" assert latex(x | y | z, symbol_names={x: "x_i", y: "y_i", z: "z_i"}) == \ r"x_i \vee y_i \vee z_i" assert latex((x & y) | z, symbol_names={x: "x_i", y: "y_i", z: "z_i"}) == \ r"z_i \vee \left(x_i \wedge y_i\right)" assert latex(Implies(x, y), symbol_names={x: "x_i", y: "y_i"}) == \ r"x_i \Rightarrow y_i" p = Symbol('p', positive=True) assert latex(exp(-p)*log(p)) == r"e^{- p} \log{\left(p \right)}" def test_latex_builtins(): assert latex(True) == r"\text{True}" assert latex(False) == r"\text{False}" assert latex(None) == r"\text{None}" assert latex(true) == r"\text{True}" assert latex(false) == r'\text{False}' def test_latex_SingularityFunction(): assert latex(SingularityFunction(x, 4, 5)) == \ r"{\left\langle x - 4 \right\rangle}^{5}" assert latex(SingularityFunction(x, -3, 4)) == \ r"{\left\langle x + 3 \right\rangle}^{4}" assert latex(SingularityFunction(x, 0, 4)) == \ r"{\left\langle x \right\rangle}^{4}" assert latex(SingularityFunction(x, a, n)) == \ r"{\left\langle - a + x \right\rangle}^{n}" assert latex(SingularityFunction(x, 4, -2)) == \ r"{\left\langle x - 4 \right\rangle}^{-2}" assert latex(SingularityFunction(x, 4, -1)) == \ r"{\left\langle x - 4 \right\rangle}^{-1}" def test_latex_cycle(): assert latex(Cycle(1, 2, 4)) == r"\left( 1\; 2\; 4\right)" assert latex(Cycle(1, 2)(4, 5, 6)) == \ r"\left( 1\; 2\right)\left( 4\; 5\; 6\right)" assert latex(Cycle()) == r"\left( \right)" def test_latex_permutation(): assert latex(Permutation(1, 2, 4)) == r"\left( 1\; 2\; 4\right)" assert latex(Permutation(1, 2)(4, 5, 6)) == \ r"\left( 1\; 2\right)\left( 4\; 5\; 6\right)" assert latex(Permutation()) == r"\left( \right)" assert latex(Permutation(2, 4)*Permutation(5)) == \ r"\left( 2\; 4\right)\left( 5\right)" assert latex(Permutation(5)) == r"\left( 5\right)" assert latex(Permutation(0, 1), perm_cyclic=False) == \ r"\begin{pmatrix} 0 & 1 \\ 1 & 0 \end{pmatrix}" assert latex(Permutation(0, 1)(2, 3), perm_cyclic=False) == \ r"\begin{pmatrix} 0 & 1 & 2 & 3 \\ 1 & 0 & 3 & 2 \end{pmatrix}" assert latex(Permutation(), perm_cyclic=False) == \ r"\left( \right)" def test_latex_Float(): assert latex(Float(1.0e100)) == r"1.0 \cdot 10^{100}" assert latex(Float(1.0e-100)) == r"1.0 \cdot 10^{-100}" assert latex(Float(1.0e-100), mul_symbol="times") == \ r"1.0 \times 10^{-100}" assert latex(Float('10000.0'), full_prec=False, min=-2, max=2) == \ r"1.0 \cdot 10^{4}" assert latex(Float('10000.0'), full_prec=False, min=-2, max=4) == \ r"1.0 \cdot 10^{4}" assert latex(Float('10000.0'), full_prec=False, min=-2, max=5) == \ r"10000.0" assert latex(Float('0.099999'), full_prec=True, min=-2, max=5) == \ r"9.99990000000000 \cdot 10^{-2}" def test_latex_vector_expressions(): A = CoordSys3D('A') assert latex(Cross(A.i, A.j*A.x*3+A.k)) == \ r"\mathbf{\hat{i}_{A}} \times \left((3 \mathbf{{x}_{A}})\mathbf{\hat{j}_{A}} + \mathbf{\hat{k}_{A}}\right)" assert latex(Cross(A.i, A.j)) == \ r"\mathbf{\hat{i}_{A}} \times \mathbf{\hat{j}_{A}}" assert latex(x*Cross(A.i, A.j)) == \ r"x \left(\mathbf{\hat{i}_{A}} \times \mathbf{\hat{j}_{A}}\right)" assert latex(Cross(x*A.i, A.j)) == \ r'- \mathbf{\hat{j}_{A}} \times \left((x)\mathbf{\hat{i}_{A}}\right)' assert latex(Curl(3*A.x*A.j)) == \ r"\nabla\times \left((3 \mathbf{{x}_{A}})\mathbf{\hat{j}_{A}}\right)" assert latex(Curl(3*A.x*A.j+A.i)) == \ r"\nabla\times \left(\mathbf{\hat{i}_{A}} + (3 \mathbf{{x}_{A}})\mathbf{\hat{j}_{A}}\right)" assert latex(Curl(3*x*A.x*A.j)) == \ r"\nabla\times \left((3 \mathbf{{x}_{A}} x)\mathbf{\hat{j}_{A}}\right)" assert latex(x*Curl(3*A.x*A.j)) == \ r"x \left(\nabla\times \left((3 \mathbf{{x}_{A}})\mathbf{\hat{j}_{A}}\right)\right)" assert latex(Divergence(3*A.x*A.j+A.i)) == \ r"\nabla\cdot \left(\mathbf{\hat{i}_{A}} + (3 \mathbf{{x}_{A}})\mathbf{\hat{j}_{A}}\right)" assert latex(Divergence(3*A.x*A.j)) == \ r"\nabla\cdot \left((3 \mathbf{{x}_{A}})\mathbf{\hat{j}_{A}}\right)" assert latex(x*Divergence(3*A.x*A.j)) == \ r"x \left(\nabla\cdot \left((3 \mathbf{{x}_{A}})\mathbf{\hat{j}_{A}}\right)\right)" assert latex(Dot(A.i, A.j*A.x*3+A.k)) == \ r"\mathbf{\hat{i}_{A}} \cdot \left((3 \mathbf{{x}_{A}})\mathbf{\hat{j}_{A}} + \mathbf{\hat{k}_{A}}\right)" assert latex(Dot(A.i, A.j)) == \ r"\mathbf{\hat{i}_{A}} \cdot \mathbf{\hat{j}_{A}}" assert latex(Dot(x*A.i, A.j)) == \ r"\mathbf{\hat{j}_{A}} \cdot \left((x)\mathbf{\hat{i}_{A}}\right)" assert latex(x*Dot(A.i, A.j)) == \ r"x \left(\mathbf{\hat{i}_{A}} \cdot \mathbf{\hat{j}_{A}}\right)" assert latex(Gradient(A.x)) == r"\nabla \mathbf{{x}_{A}}" assert latex(Gradient(A.x + 3*A.y)) == \ r"\nabla \left(\mathbf{{x}_{A}} + 3 \mathbf{{y}_{A}}\right)" assert latex(x*Gradient(A.x)) == r"x \left(\nabla \mathbf{{x}_{A}}\right)" assert latex(Gradient(x*A.x)) == r"\nabla \left(\mathbf{{x}_{A}} x\right)" assert latex(Laplacian(A.x)) == r"\triangle \mathbf{{x}_{A}}" assert latex(Laplacian(A.x + 3*A.y)) == \ r"\triangle \left(\mathbf{{x}_{A}} + 3 \mathbf{{y}_{A}}\right)" assert latex(x*Laplacian(A.x)) == r"x \left(\triangle \mathbf{{x}_{A}}\right)" assert latex(Laplacian(x*A.x)) == r"\triangle \left(\mathbf{{x}_{A}} x\right)" def test_latex_symbols(): Gamma, lmbda, rho = symbols('Gamma, lambda, rho') tau, Tau, TAU, taU = symbols('tau, Tau, TAU, taU') assert latex(tau) == r"\tau" assert latex(Tau) == "T" assert latex(TAU) == r"\tau" assert latex(taU) == r"\tau" # Check that all capitalized greek letters are handled explicitly capitalized_letters = set(l.capitalize() for l in greek_letters_set) assert len(capitalized_letters - set(tex_greek_dictionary.keys())) == 0 assert latex(Gamma + lmbda) == r"\Gamma + \lambda" assert latex(Gamma * lmbda) == r"\Gamma \lambda" assert latex(Symbol('q1')) == r"q_{1}" assert latex(Symbol('q21')) == r"q_{21}" assert latex(Symbol('epsilon0')) == r"\epsilon_{0}" assert latex(Symbol('omega1')) == r"\omega_{1}" assert latex(Symbol('91')) == r"91" assert latex(Symbol('alpha_new')) == r"\alpha_{new}" assert latex(Symbol('C^orig')) == r"C^{orig}" assert latex(Symbol('x^alpha')) == r"x^{\alpha}" assert latex(Symbol('beta^alpha')) == r"\beta^{\alpha}" assert latex(Symbol('e^Alpha')) == r"e^{A}" assert latex(Symbol('omega_alpha^beta')) == r"\omega^{\beta}_{\alpha}" assert latex(Symbol('omega') ** Symbol('beta')) == r"\omega^{\beta}" @XFAIL def test_latex_symbols_failing(): rho, mass, volume = symbols('rho, mass, volume') assert latex( volume * rho == mass) == r"\rho \mathrm{volume} = \mathrm{mass}" assert latex(volume / mass * rho == 1) == \ r"\rho \mathrm{volume} {\mathrm{mass}}^{(-1)} = 1" assert latex(mass**3 * volume**3) == \ r"{\mathrm{mass}}^{3} \cdot {\mathrm{volume}}^{3}" def test_latex_functions(): assert latex(exp(x)) == "e^{x}" assert latex(exp(1) + exp(2)) == "e + e^{2}" f = Function('f') assert latex(f(x)) == r'f{\left(x \right)}' assert latex(f) == r'f' g = Function('g') assert latex(g(x, y)) == r'g{\left(x,y \right)}' assert latex(g) == r'g' h = Function('h') assert latex(h(x, y, z)) == r'h{\left(x,y,z \right)}' assert latex(h) == r'h' Li = Function('Li') assert latex(Li) == r'\operatorname{Li}' assert latex(Li(x)) == r'\operatorname{Li}{\left(x \right)}' mybeta = Function('beta') # not to be confused with the beta function assert latex(mybeta(x, y, z)) == r"\beta{\left(x,y,z \right)}" assert latex(beta(x, y)) == r'\operatorname{B}\left(x, y\right)' assert latex(beta(x, y)**2) == r'\operatorname{B}^{2}\left(x, y\right)' assert latex(mybeta(x)) == r"\beta{\left(x \right)}" assert latex(mybeta) == r"\beta" g = Function('gamma') # not to be confused with the gamma function assert latex(g(x, y, z)) == r"\gamma{\left(x,y,z \right)}" assert latex(g(x)) == r"\gamma{\left(x \right)}" assert latex(g) == r"\gamma" a1 = Function('a_1') assert latex(a1) == r"\operatorname{a_{1}}" assert latex(a1(x)) == r"\operatorname{a_{1}}{\left(x \right)}" # issue 5868 omega1 = Function('omega1') assert latex(omega1) == r"\omega_{1}" assert latex(omega1(x)) == r"\omega_{1}{\left(x \right)}" assert latex(sin(x)) == r"\sin{\left(x \right)}" assert latex(sin(x), fold_func_brackets=True) == r"\sin {x}" assert latex(sin(2*x**2), fold_func_brackets=True) == \ r"\sin {2 x^{2}}" assert latex(sin(x**2), fold_func_brackets=True) == \ r"\sin {x^{2}}" assert latex(asin(x)**2) == r"\operatorname{asin}^{2}{\left(x \right)}" assert latex(asin(x)**2, inv_trig_style="full") == \ r"\arcsin^{2}{\left(x \right)}" assert latex(asin(x)**2, inv_trig_style="power") == \ r"\sin^{-1}{\left(x \right)}^{2}" assert latex(asin(x**2), inv_trig_style="power", fold_func_brackets=True) == \ r"\sin^{-1} {x^{2}}" assert latex(acsc(x), inv_trig_style="full") == \ r"\operatorname{arccsc}{\left(x \right)}" assert latex(factorial(k)) == r"k!" assert latex(factorial(-k)) == r"\left(- k\right)!" assert latex(factorial(k)**2) == r"k!^{2}" assert latex(subfactorial(k)) == r"!k" assert latex(subfactorial(-k)) == r"!\left(- k\right)" assert latex(subfactorial(k)**2) == r"\left(!k\right)^{2}" assert latex(factorial2(k)) == r"k!!" assert latex(factorial2(-k)) == r"\left(- k\right)!!" assert latex(factorial2(k)**2) == r"k!!^{2}" assert latex(binomial(2, k)) == r"{\binom{2}{k}}" assert latex(binomial(2, k)**2) == r"{\binom{2}{k}}^{2}" assert latex(FallingFactorial(3, k)) == r"{\left(3\right)}_{k}" assert latex(RisingFactorial(3, k)) == r"{3}^{\left(k\right)}" assert latex(floor(x)) == r"\left\lfloor{x}\right\rfloor" assert latex(ceiling(x)) == r"\left\lceil{x}\right\rceil" assert latex(frac(x)) == r"\operatorname{frac}{\left(x\right)}" assert latex(floor(x)**2) == r"\left\lfloor{x}\right\rfloor^{2}" assert latex(ceiling(x)**2) == r"\left\lceil{x}\right\rceil^{2}" assert latex(frac(x)**2) == r"\operatorname{frac}{\left(x\right)}^{2}" assert latex(Min(x, 2, x**3)) == r"\min\left(2, x, x^{3}\right)" assert latex(Min(x, y)**2) == r"\min\left(x, y\right)^{2}" assert latex(Max(x, 2, x**3)) == r"\max\left(2, x, x^{3}\right)" assert latex(Max(x, y)**2) == r"\max\left(x, y\right)^{2}" assert latex(Abs(x)) == r"\left|{x}\right|" assert latex(Abs(x)**2) == r"\left|{x}\right|^{2}" assert latex(re(x)) == r"\operatorname{re}{\left(x\right)}" assert latex(re(x + y)) == \ r"\operatorname{re}{\left(x\right)} + \operatorname{re}{\left(y\right)}" assert latex(im(x)) == r"\operatorname{im}{\left(x\right)}" assert latex(conjugate(x)) == r"\overline{x}" assert latex(conjugate(x)**2) == r"\overline{x}^{2}" assert latex(conjugate(x**2)) == r"\overline{x}^{2}" assert latex(gamma(x)) == r"\Gamma\left(x\right)" w = Wild('w') assert latex(gamma(w)) == r"\Gamma\left(w\right)" assert latex(Order(x)) == r"O\left(x\right)" assert latex(Order(x, x)) == r"O\left(x\right)" assert latex(Order(x, (x, 0))) == r"O\left(x\right)" assert latex(Order(x, (x, oo))) == r"O\left(x; x\rightarrow \infty\right)" assert latex(Order(x - y, (x, y))) == \ r"O\left(x - y; x\rightarrow y\right)" assert latex(Order(x, x, y)) == \ r"O\left(x; \left( x, \ y\right)\rightarrow \left( 0, \ 0\right)\right)" assert latex(Order(x, x, y)) == \ r"O\left(x; \left( x, \ y\right)\rightarrow \left( 0, \ 0\right)\right)" assert latex(Order(x, (x, oo), (y, oo))) == \ r"O\left(x; \left( x, \ y\right)\rightarrow \left( \infty, \ \infty\right)\right)" assert latex(lowergamma(x, y)) == r'\gamma\left(x, y\right)' assert latex(lowergamma(x, y)**2) == r'\gamma^{2}\left(x, y\right)' assert latex(uppergamma(x, y)) == r'\Gamma\left(x, y\right)' assert latex(uppergamma(x, y)**2) == r'\Gamma^{2}\left(x, y\right)' assert latex(cot(x)) == r'\cot{\left(x \right)}' assert latex(coth(x)) == r'\coth{\left(x \right)}' assert latex(re(x)) == r'\operatorname{re}{\left(x\right)}' assert latex(im(x)) == r'\operatorname{im}{\left(x\right)}' assert latex(root(x, y)) == r'x^{\frac{1}{y}}' assert latex(arg(x)) == r'\arg{\left(x \right)}' assert latex(zeta(x)) == r"\zeta\left(x\right)" assert latex(zeta(x)**2) == r"\zeta^{2}\left(x\right)" assert latex(zeta(x, y)) == r"\zeta\left(x, y\right)" assert latex(zeta(x, y)**2) == r"\zeta^{2}\left(x, y\right)" assert latex(dirichlet_eta(x)) == r"\eta\left(x\right)" assert latex(dirichlet_eta(x)**2) == r"\eta^{2}\left(x\right)" assert latex(polylog(x, y)) == r"\operatorname{Li}_{x}\left(y\right)" assert latex( polylog(x, y)**2) == r"\operatorname{Li}_{x}^{2}\left(y\right)" assert latex(lerchphi(x, y, n)) == r"\Phi\left(x, y, n\right)" assert latex(lerchphi(x, y, n)**2) == r"\Phi^{2}\left(x, y, n\right)" assert latex(stieltjes(x)) == r"\gamma_{x}" assert latex(stieltjes(x)**2) == r"\gamma_{x}^{2}" assert latex(stieltjes(x, y)) == r"\gamma_{x}\left(y\right)" assert latex(stieltjes(x, y)**2) == r"\gamma_{x}\left(y\right)^{2}" assert latex(elliptic_k(z)) == r"K\left(z\right)" assert latex(elliptic_k(z)**2) == r"K^{2}\left(z\right)" assert latex(elliptic_f(x, y)) == r"F\left(x\middle| y\right)" assert latex(elliptic_f(x, y)**2) == r"F^{2}\left(x\middle| y\right)" assert latex(elliptic_e(x, y)) == r"E\left(x\middle| y\right)" assert latex(elliptic_e(x, y)**2) == r"E^{2}\left(x\middle| y\right)" assert latex(elliptic_e(z)) == r"E\left(z\right)" assert latex(elliptic_e(z)**2) == r"E^{2}\left(z\right)" assert latex(elliptic_pi(x, y, z)) == r"\Pi\left(x; y\middle| z\right)" assert latex(elliptic_pi(x, y, z)**2) == \ r"\Pi^{2}\left(x; y\middle| z\right)" assert latex(elliptic_pi(x, y)) == r"\Pi\left(x\middle| y\right)" assert latex(elliptic_pi(x, y)**2) == r"\Pi^{2}\left(x\middle| y\right)" assert latex(Ei(x)) == r'\operatorname{Ei}{\left(x \right)}' assert latex(Ei(x)**2) == r'\operatorname{Ei}^{2}{\left(x \right)}' assert latex(expint(x, y)) == r'\operatorname{E}_{x}\left(y\right)' assert latex(expint(x, y)**2) == r'\operatorname{E}_{x}^{2}\left(y\right)' assert latex(Shi(x)**2) == r'\operatorname{Shi}^{2}{\left(x \right)}' assert latex(Si(x)**2) == r'\operatorname{Si}^{2}{\left(x \right)}' assert latex(Ci(x)**2) == r'\operatorname{Ci}^{2}{\left(x \right)}' assert latex(Chi(x)**2) == r'\operatorname{Chi}^{2}\left(x\right)' assert latex(Chi(x)) == r'\operatorname{Chi}\left(x\right)' assert latex(jacobi(n, a, b, x)) == \ r'P_{n}^{\left(a,b\right)}\left(x\right)' assert latex(jacobi(n, a, b, x)**2) == \ r'\left(P_{n}^{\left(a,b\right)}\left(x\right)\right)^{2}' assert latex(gegenbauer(n, a, x)) == \ r'C_{n}^{\left(a\right)}\left(x\right)' assert latex(gegenbauer(n, a, x)**2) == \ r'\left(C_{n}^{\left(a\right)}\left(x\right)\right)^{2}' assert latex(chebyshevt(n, x)) == r'T_{n}\left(x\right)' assert latex(chebyshevt(n, x)**2) == \ r'\left(T_{n}\left(x\right)\right)^{2}' assert latex(chebyshevu(n, x)) == r'U_{n}\left(x\right)' assert latex(chebyshevu(n, x)**2) == \ r'\left(U_{n}\left(x\right)\right)^{2}' assert latex(legendre(n, x)) == r'P_{n}\left(x\right)' assert latex(legendre(n, x)**2) == r'\left(P_{n}\left(x\right)\right)^{2}' assert latex(assoc_legendre(n, a, x)) == \ r'P_{n}^{\left(a\right)}\left(x\right)' assert latex(assoc_legendre(n, a, x)**2) == \ r'\left(P_{n}^{\left(a\right)}\left(x\right)\right)^{2}' assert latex(laguerre(n, x)) == r'L_{n}\left(x\right)' assert latex(laguerre(n, x)**2) == r'\left(L_{n}\left(x\right)\right)^{2}' assert latex(assoc_laguerre(n, a, x)) == \ r'L_{n}^{\left(a\right)}\left(x\right)' assert latex(assoc_laguerre(n, a, x)**2) == \ r'\left(L_{n}^{\left(a\right)}\left(x\right)\right)^{2}' assert latex(hermite(n, x)) == r'H_{n}\left(x\right)' assert latex(hermite(n, x)**2) == r'\left(H_{n}\left(x\right)\right)^{2}' theta = Symbol("theta", real=True) phi = Symbol("phi", real=True) assert latex(Ynm(n, m, theta, phi)) == r'Y_{n}^{m}\left(\theta,\phi\right)' assert latex(Ynm(n, m, theta, phi)**3) == \ r'\left(Y_{n}^{m}\left(\theta,\phi\right)\right)^{3}' assert latex(Znm(n, m, theta, phi)) == r'Z_{n}^{m}\left(\theta,\phi\right)' assert latex(Znm(n, m, theta, phi)**3) == \ r'\left(Z_{n}^{m}\left(\theta,\phi\right)\right)^{3}' # Test latex printing of function names with "_" assert latex(polar_lift(0)) == \ r"\operatorname{polar\_lift}{\left(0 \right)}" assert latex(polar_lift(0)**3) == \ r"\operatorname{polar\_lift}^{3}{\left(0 \right)}" assert latex(totient(n)) == r'\phi\left(n\right)' assert latex(totient(n) ** 2) == r'\left(\phi\left(n\right)\right)^{2}' assert latex(reduced_totient(n)) == r'\lambda\left(n\right)' assert latex(reduced_totient(n) ** 2) == \ r'\left(\lambda\left(n\right)\right)^{2}' assert latex(divisor_sigma(x)) == r"\sigma\left(x\right)" assert latex(divisor_sigma(x)**2) == r"\sigma^{2}\left(x\right)" assert latex(divisor_sigma(x, y)) == r"\sigma_y\left(x\right)" assert latex(divisor_sigma(x, y)**2) == r"\sigma^{2}_y\left(x\right)" assert latex(udivisor_sigma(x)) == r"\sigma^*\left(x\right)" assert latex(udivisor_sigma(x)**2) == r"\sigma^*^{2}\left(x\right)" assert latex(udivisor_sigma(x, y)) == r"\sigma^*_y\left(x\right)" assert latex(udivisor_sigma(x, y)**2) == r"\sigma^*^{2}_y\left(x\right)" assert latex(primenu(n)) == r'\nu\left(n\right)' assert latex(primenu(n) ** 2) == r'\left(\nu\left(n\right)\right)^{2}' assert latex(primeomega(n)) == r'\Omega\left(n\right)' assert latex(primeomega(n) ** 2) == \ r'\left(\Omega\left(n\right)\right)^{2}' assert latex(LambertW(n)) == r'W\left(n\right)' assert latex(LambertW(n, -1)) == r'W_{-1}\left(n\right)' assert latex(LambertW(n, k)) == r'W_{k}\left(n\right)' assert latex(Mod(x, 7)) == r'x\bmod{7}' assert latex(Mod(x + 1, 7)) == r'\left(x + 1\right)\bmod{7}' assert latex(Mod(2 * x, 7)) == r'2 x\bmod{7}' assert latex(Mod(x, 7) + 1) == r'\left(x\bmod{7}\right) + 1' assert latex(2 * Mod(x, 7)) == r'2 \left(x\bmod{7}\right)' # some unknown function name should get rendered with \operatorname fjlkd = Function('fjlkd') assert latex(fjlkd(x)) == r'\operatorname{fjlkd}{\left(x \right)}' # even when it is referred to without an argument assert latex(fjlkd) == r'\operatorname{fjlkd}' # test that notation passes to subclasses of the same name only def test_function_subclass_different_name(): class mygamma(gamma): pass assert latex(mygamma) == r"\operatorname{mygamma}" assert latex(mygamma(x)) == r"\operatorname{mygamma}{\left(x \right)}" def test_hyper_printing(): from sympy import pi from sympy.abc import x, z assert latex(meijerg(Tuple(pi, pi, x), Tuple(1), (0, 1), Tuple(1, 2, 3/pi), z)) == \ r'{G_{4, 5}^{2, 3}\left(\begin{matrix} \pi, \pi, x & 1 \\0, 1 & 1, 2, '\ r'\frac{3}{\pi} \end{matrix} \middle| {z} \right)}' assert latex(meijerg(Tuple(), Tuple(1), (0,), Tuple(), z)) == \ r'{G_{1, 1}^{1, 0}\left(\begin{matrix} & 1 \\0 & \end{matrix} \middle| {z} \right)}' assert latex(hyper((x, 2), (3,), z)) == \ r'{{}_{2}F_{1}\left(\begin{matrix} x, 2 ' \ r'\\ 3 \end{matrix}\middle| {z} \right)}' assert latex(hyper(Tuple(), Tuple(1), z)) == \ r'{{}_{0}F_{1}\left(\begin{matrix} ' \ r'\\ 1 \end{matrix}\middle| {z} \right)}' def test_latex_bessel(): from sympy.functions.special.bessel import (besselj, bessely, besseli, besselk, hankel1, hankel2, jn, yn, hn1, hn2) from sympy.abc import z assert latex(besselj(n, z**2)**k) == r'J^{k}_{n}\left(z^{2}\right)' assert latex(bessely(n, z)) == r'Y_{n}\left(z\right)' assert latex(besseli(n, z)) == r'I_{n}\left(z\right)' assert latex(besselk(n, z)) == r'K_{n}\left(z\right)' assert latex(hankel1(n, z**2)**2) == \ r'\left(H^{(1)}_{n}\left(z^{2}\right)\right)^{2}' assert latex(hankel2(n, z)) == r'H^{(2)}_{n}\left(z\right)' assert latex(jn(n, z)) == r'j_{n}\left(z\right)' assert latex(yn(n, z)) == r'y_{n}\left(z\right)' assert latex(hn1(n, z)) == r'h^{(1)}_{n}\left(z\right)' assert latex(hn2(n, z)) == r'h^{(2)}_{n}\left(z\right)' def test_latex_fresnel(): from sympy.functions.special.error_functions import (fresnels, fresnelc) from sympy.abc import z assert latex(fresnels(z)) == r'S\left(z\right)' assert latex(fresnelc(z)) == r'C\left(z\right)' assert latex(fresnels(z)**2) == r'S^{2}\left(z\right)' assert latex(fresnelc(z)**2) == r'C^{2}\left(z\right)' def test_latex_brackets(): assert latex((-1)**x) == r"\left(-1\right)^{x}" def test_latex_indexed(): Psi_symbol = Symbol('Psi_0', complex=True, real=False) Psi_indexed = IndexedBase(Symbol('Psi', complex=True, real=False)) symbol_latex = latex(Psi_symbol * conjugate(Psi_symbol)) indexed_latex = latex(Psi_indexed[0] * conjugate(Psi_indexed[0])) # \\overline{{\\Psi}_{0}} {\\Psi}_{0} vs. \\Psi_{0} \\overline{\\Psi_{0}} assert symbol_latex == '\\Psi_{0} \\overline{\\Psi_{0}}' assert indexed_latex == '\\overline{{\\Psi}_{0}} {\\Psi}_{0}' # Symbol('gamma') gives r'\gamma' assert latex(Indexed('x1', Symbol('i'))) == '{x_{1}}_{i}' assert latex(IndexedBase('gamma')) == r'\gamma' assert latex(IndexedBase('a b')) == 'a b' assert latex(IndexedBase('a_b')) == 'a_{b}' def test_latex_derivatives(): # regular "d" for ordinary derivatives assert latex(diff(x**3, x, evaluate=False)) == \ r"\frac{d}{d x} x^{3}" assert latex(diff(sin(x) + x**2, x, evaluate=False)) == \ r"\frac{d}{d x} \left(x^{2} + \sin{\left(x \right)}\right)" assert latex(diff(diff(sin(x) + x**2, x, evaluate=False), evaluate=False))\ == \ r"\frac{d^{2}}{d x^{2}} \left(x^{2} + \sin{\left(x \right)}\right)" assert latex(diff(diff(diff(sin(x) + x**2, x, evaluate=False), evaluate=False), evaluate=False)) == \ r"\frac{d^{3}}{d x^{3}} \left(x^{2} + \sin{\left(x \right)}\right)" # \partial for partial derivatives assert latex(diff(sin(x * y), x, evaluate=False)) == \ r"\frac{\partial}{\partial x} \sin{\left(x y \right)}" assert latex(diff(sin(x * y) + x**2, x, evaluate=False)) == \ r"\frac{\partial}{\partial x} \left(x^{2} + \sin{\left(x y \right)}\right)" assert latex(diff(diff(sin(x*y) + x**2, x, evaluate=False), x, evaluate=False)) == \ r"\frac{\partial^{2}}{\partial x^{2}} \left(x^{2} + \sin{\left(x y \right)}\right)" assert latex(diff(diff(diff(sin(x*y) + x**2, x, evaluate=False), x, evaluate=False), x, evaluate=False)) == \ r"\frac{\partial^{3}}{\partial x^{3}} \left(x^{2} + \sin{\left(x y \right)}\right)" # mixed partial derivatives f = Function("f") assert latex(diff(diff(f(x, y), x, evaluate=False), y, evaluate=False)) == \ r"\frac{\partial^{2}}{\partial y\partial x} " + latex(f(x, y)) assert latex(diff(diff(diff(f(x, y), x, evaluate=False), x, evaluate=False), y, evaluate=False)) == \ r"\frac{\partial^{3}}{\partial y\partial x^{2}} " + latex(f(x, y)) # use ordinary d when one of the variables has been integrated out assert latex(diff(Integral(exp(-x*y), (x, 0, oo)), y, evaluate=False)) == \ r"\frac{d}{d y} \int\limits_{0}^{\infty} e^{- x y}\, dx" # Derivative wrapped in power: assert latex(diff(x, x, evaluate=False)**2) == \ r"\left(\frac{d}{d x} x\right)^{2}" assert latex(diff(f(x), x)**2) == \ r"\left(\frac{d}{d x} f{\left(x \right)}\right)^{2}" assert latex(diff(f(x), (x, n))) == \ r"\frac{d^{n}}{d x^{n}} f{\left(x \right)}" x1 = Symbol('x1') x2 = Symbol('x2') assert latex(diff(f(x1, x2), x1)) == r'\frac{\partial}{\partial x_{1}} f{\left(x_{1},x_{2} \right)}' n1 = Symbol('n1') assert latex(diff(f(x), (x, n1))) == r'\frac{d^{n_{1}}}{d x^{n_{1}}} f{\left(x \right)}' n2 = Symbol('n2') assert latex(diff(f(x), (x, Max(n1, n2)))) == \ r'\frac{d^{\max\left(n_{1}, n_{2}\right)}}{d x^{\max\left(n_{1}, n_{2}\right)}} f{\left(x \right)}' def test_latex_subs(): assert latex(Subs(x*y, ( x, y), (1, 2))) == r'\left. x y \right|_{\substack{ x=1\\ y=2 }}' def test_latex_integrals(): assert latex(Integral(log(x), x)) == r"\int \log{\left(x \right)}\, dx" assert latex(Integral(x**2, (x, 0, 1))) == \ r"\int\limits_{0}^{1} x^{2}\, dx" assert latex(Integral(x**2, (x, 10, 20))) == \ r"\int\limits_{10}^{20} x^{2}\, dx" assert latex(Integral(y*x**2, (x, 0, 1), y)) == \ r"\int\int\limits_{0}^{1} x^{2} y\, dx\, dy" assert latex(Integral(y*x**2, (x, 0, 1), y), mode='equation*') == \ r"\begin{equation*}\int\int\limits_{0}^{1} x^{2} y\, dx\, dy\end{equation*}" assert latex(Integral(y*x**2, (x, 0, 1), y), mode='equation*', itex=True) \ == r"$$\int\int_{0}^{1} x^{2} y\, dx\, dy$$" assert latex(Integral(x, (x, 0))) == r"\int\limits^{0} x\, dx" assert latex(Integral(x*y, x, y)) == r"\iint x y\, dx\, dy" assert latex(Integral(x*y*z, x, y, z)) == r"\iiint x y z\, dx\, dy\, dz" assert latex(Integral(x*y*z*t, x, y, z, t)) == \ r"\iiiint t x y z\, dx\, dy\, dz\, dt" assert latex(Integral(x, x, x, x, x, x, x)) == \ r"\int\int\int\int\int\int x\, dx\, dx\, dx\, dx\, dx\, dx" assert latex(Integral(x, x, y, (z, 0, 1))) == \ r"\int\limits_{0}^{1}\int\int x\, dx\, dy\, dz" # fix issue #10806 assert latex(Integral(z, z)**2) == r"\left(\int z\, dz\right)^{2}" assert latex(Integral(x + z, z)) == r"\int \left(x + z\right)\, dz" assert latex(Integral(x+z/2, z)) == \ r"\int \left(x + \frac{z}{2}\right)\, dz" assert latex(Integral(x**y, z)) == r"\int x^{y}\, dz" def test_latex_sets(): for s in (frozenset, set): assert latex(s([x*y, x**2])) == r"\left\{x^{2}, x y\right\}" assert latex(s(range(1, 6))) == r"\left\{1, 2, 3, 4, 5\right\}" assert latex(s(range(1, 13))) == \ r"\left\{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12\right\}" s = FiniteSet assert latex(s(*[x*y, x**2])) == r"\left\{x^{2}, x y\right\}" assert latex(s(*range(1, 6))) == r"\left\{1, 2, 3, 4, 5\right\}" assert latex(s(*range(1, 13))) == \ r"\left\{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12\right\}" def test_latex_SetExpr(): iv = Interval(1, 3) se = SetExpr(iv) assert latex(se) == r"SetExpr\left(\left[1, 3\right]\right)" def test_latex_Range(): assert latex(Range(1, 51)) == r'\left\{1, 2, \ldots, 50\right\}' assert latex(Range(1, 4)) == r'\left\{1, 2, 3\right\}' assert latex(Range(0, 3, 1)) == r'\left\{0, 1, 2\right\}' assert latex(Range(0, 30, 1)) == r'\left\{0, 1, \ldots, 29\right\}' assert latex(Range(30, 1, -1)) == r'\left\{30, 29, \ldots, 2\right\}' assert latex(Range(0, oo, 2)) == r'\left\{0, 2, \ldots\right\}' assert latex(Range(oo, -2, -2)) == r'\left\{\ldots, 2, 0\right\}' assert latex(Range(-2, -oo, -1)) == r'\left\{-2, -3, \ldots\right\}' assert latex(Range(-oo, oo)) == r'\left\{\ldots, -1, 0, 1, \ldots\right\}' assert latex(Range(oo, -oo, -1)) == \ r'\left\{\ldots, 1, 0, -1, \ldots\right\}' a, b, c = symbols('a:c') assert latex(Range(a, b, c)) == r'Range\left(a, b, c\right)' assert latex(Range(a, 10, 1)) == r'Range\left(a, 10, 1\right)' assert latex(Range(0, b, 1)) == r'Range\left(0, b, 1\right)' assert latex(Range(0, 10, c)) == r'Range\left(0, 10, c\right)' def test_latex_sequences(): s1 = SeqFormula(a**2, (0, oo)) s2 = SeqPer((1, 2)) latex_str = r'\left[0, 1, 4, 9, \ldots\right]' assert latex(s1) == latex_str latex_str = r'\left[1, 2, 1, 2, \ldots\right]' assert latex(s2) == latex_str s3 = SeqFormula(a**2, (0, 2)) s4 = SeqPer((1, 2), (0, 2)) latex_str = r'\left[0, 1, 4\right]' assert latex(s3) == latex_str latex_str = r'\left[1, 2, 1\right]' assert latex(s4) == latex_str s5 = SeqFormula(a**2, (-oo, 0)) s6 = SeqPer((1, 2), (-oo, 0)) latex_str = r'\left[\ldots, 9, 4, 1, 0\right]' assert latex(s5) == latex_str latex_str = r'\left[\ldots, 2, 1, 2, 1\right]' assert latex(s6) == latex_str latex_str = r'\left[1, 3, 5, 11, \ldots\right]' assert latex(SeqAdd(s1, s2)) == latex_str latex_str = r'\left[1, 3, 5\right]' assert latex(SeqAdd(s3, s4)) == latex_str latex_str = r'\left[\ldots, 11, 5, 3, 1\right]' assert latex(SeqAdd(s5, s6)) == latex_str latex_str = r'\left[0, 2, 4, 18, \ldots\right]' assert latex(SeqMul(s1, s2)) == latex_str latex_str = r'\left[0, 2, 4\right]' assert latex(SeqMul(s3, s4)) == latex_str latex_str = r'\left[\ldots, 18, 4, 2, 0\right]' assert latex(SeqMul(s5, s6)) == latex_str # Sequences with symbolic limits, issue 12629 s7 = SeqFormula(a**2, (a, 0, x)) latex_str = r'\left\{a^{2}\right\}_{a=0}^{x}' assert latex(s7) == latex_str b = Symbol('b') s8 = SeqFormula(b*a**2, (a, 0, 2)) latex_str = r'\left[0, b, 4 b\right]' assert latex(s8) == latex_str def test_latex_FourierSeries(): latex_str = \ r'2 \sin{\left(x \right)} - \sin{\left(2 x \right)} + \frac{2 \sin{\left(3 x \right)}}{3} + \ldots' assert latex(fourier_series(x, (x, -pi, pi))) == latex_str def test_latex_FormalPowerSeries(): latex_str = r'\sum_{k=1}^{\infty} - \frac{\left(-1\right)^{- k} x^{k}}{k}' assert latex(fps(log(1 + x))) == latex_str def test_latex_intervals(): a = Symbol('a', real=True) assert latex(Interval(0, 0)) == r"\left\{0\right\}" assert latex(Interval(0, a)) == r"\left[0, a\right]" assert latex(Interval(0, a, False, False)) == r"\left[0, a\right]" assert latex(Interval(0, a, True, False)) == r"\left(0, a\right]" assert latex(Interval(0, a, False, True)) == r"\left[0, a\right)" assert latex(Interval(0, a, True, True)) == r"\left(0, a\right)" def test_latex_AccumuBounds(): a = Symbol('a', real=True) assert latex(AccumBounds(0, 1)) == r"\left\langle 0, 1\right\rangle" assert latex(AccumBounds(0, a)) == r"\left\langle 0, a\right\rangle" assert latex(AccumBounds(a + 1, a + 2)) == \ r"\left\langle a + 1, a + 2\right\rangle" def test_latex_emptyset(): assert latex(S.EmptySet) == r"\emptyset" def test_latex_universalset(): assert latex(S.UniversalSet) == r"\mathbb{U}" def test_latex_commutator(): A = Operator('A') B = Operator('B') comm = Commutator(B, A) assert latex(comm.doit()) == r"- (A B - B A)" def test_latex_union(): assert latex(Union(Interval(0, 1), Interval(2, 3))) == \ r"\left[0, 1\right] \cup \left[2, 3\right]" assert latex(Union(Interval(1, 1), Interval(2, 2), Interval(3, 4))) == \ r"\left\{1, 2\right\} \cup \left[3, 4\right]" def test_latex_intersection(): assert latex(Intersection(Interval(0, 1), Interval(x, y))) == \ r"\left[0, 1\right] \cap \left[x, y\right]" def test_latex_symmetric_difference(): assert latex(SymmetricDifference(Interval(2, 5), Interval(4, 7), evaluate=False)) == \ r'\left[2, 5\right] \triangle \left[4, 7\right]' def test_latex_Complement(): assert latex(Complement(S.Reals, S.Naturals)) == \ r"\mathbb{R} \setminus \mathbb{N}" def test_latex_productset(): line = Interval(0, 1) bigline = Interval(0, 10) fset = FiniteSet(1, 2, 3) assert latex(line**2) == r"%s^{2}" % latex(line) assert latex(line**10) == r"%s^{10}" % latex(line) assert latex((line * bigline * fset).flatten()) == r"%s \times %s \times %s" % ( latex(line), latex(bigline), latex(fset)) def test_set_operators_parenthesis(): a, b, c, d = symbols('a:d') A = FiniteSet(a) B = FiniteSet(b) C = FiniteSet(c) D = FiniteSet(d) U1 = Union(A, B, evaluate=False) U2 = Union(C, D, evaluate=False) I1 = Intersection(A, B, evaluate=False) I2 = Intersection(C, D, evaluate=False) C1 = Complement(A, B, evaluate=False) C2 = Complement(C, D, evaluate=False) D1 = SymmetricDifference(A, B, evaluate=False) D2 = SymmetricDifference(C, D, evaluate=False) # XXX ProductSet does not support evaluate keyword P1 = ProductSet(A, B) P2 = ProductSet(C, D) assert latex(Intersection(A, U2, evaluate=False)) == \ '\\left\\{a\\right\\} \\cap ' \ '\\left(\\left\\{c\\right\\} \\cup \\left\\{d\\right\\}\\right)' assert latex(Intersection(U1, U2, evaluate=False)) == \ '\\left(\\left\\{a\\right\\} \\cup \\left\\{b\\right\\}\\right) ' \ '\\cap \\left(\\left\\{c\\right\\} \\cup \\left\\{d\\right\\}\\right)' assert latex(Intersection(C1, C2, evaluate=False)) == \ '\\left(\\left\\{a\\right\\} \\setminus ' \ '\\left\\{b\\right\\}\\right) \\cap \\left(\\left\\{c\\right\\} ' \ '\\setminus \\left\\{d\\right\\}\\right)' assert latex(Intersection(D1, D2, evaluate=False)) == \ '\\left(\\left\\{a\\right\\} \\triangle ' \ '\\left\\{b\\right\\}\\right) \\cap \\left(\\left\\{c\\right\\} ' \ '\\triangle \\left\\{d\\right\\}\\right)' assert latex(Intersection(P1, P2, evaluate=False)) == \ '\\left(\\left\\{a\\right\\} \\times \\left\\{b\\right\\}\\right) ' \ '\\cap \\left(\\left\\{c\\right\\} \\times ' \ '\\left\\{d\\right\\}\\right)' assert latex(Union(A, I2, evaluate=False)) == \ '\\left\\{a\\right\\} \\cup ' \ '\\left(\\left\\{c\\right\\} \\cap \\left\\{d\\right\\}\\right)' assert latex(Union(I1, I2, evaluate=False)) == \ '\\left(\\left\\{a\\right\\} \\cap ''\\left\\{b\\right\\}\\right) ' \ '\\cup \\left(\\left\\{c\\right\\} \\cap \\left\\{d\\right\\}\\right)' assert latex(Union(C1, C2, evaluate=False)) == \ '\\left(\\left\\{a\\right\\} \\setminus ' \ '\\left\\{b\\right\\}\\right) \\cup \\left(\\left\\{c\\right\\} ' \ '\\setminus \\left\\{d\\right\\}\\right)' assert latex(Union(D1, D2, evaluate=False)) == \ '\\left(\\left\\{a\\right\\} \\triangle ' \ '\\left\\{b\\right\\}\\right) \\cup \\left(\\left\\{c\\right\\} ' \ '\\triangle \\left\\{d\\right\\}\\right)' assert latex(Union(P1, P2, evaluate=False)) == \ '\\left(\\left\\{a\\right\\} \\times \\left\\{b\\right\\}\\right) ' \ '\\cup \\left(\\left\\{c\\right\\} \\times ' \ '\\left\\{d\\right\\}\\right)' assert latex(Complement(A, C2, evaluate=False)) == \ '\\left\\{a\\right\\} \\setminus \\left(\\left\\{c\\right\\} ' \ '\\setminus \\left\\{d\\right\\}\\right)' assert latex(Complement(U1, U2, evaluate=False)) == \ '\\left(\\left\\{a\\right\\} \\cup \\left\\{b\\right\\}\\right) ' \ '\\setminus \\left(\\left\\{c\\right\\} \\cup ' \ '\\left\\{d\\right\\}\\right)' assert latex(Complement(I1, I2, evaluate=False)) == \ '\\left(\\left\\{a\\right\\} \\cap \\left\\{b\\right\\}\\right) ' \ '\\setminus \\left(\\left\\{c\\right\\} \\cap ' \ '\\left\\{d\\right\\}\\right)' assert latex(Complement(D1, D2, evaluate=False)) == \ '\\left(\\left\\{a\\right\\} \\triangle ' \ '\\left\\{b\\right\\}\\right) \\setminus ' \ '\\left(\\left\\{c\\right\\} \\triangle \\left\\{d\\right\\}\\right)' assert latex(Complement(P1, P2, evaluate=False)) == \ '\\left(\\left\\{a\\right\\} \\times \\left\\{b\\right\\}\\right) '\ '\\setminus \\left(\\left\\{c\\right\\} \\times '\ '\\left\\{d\\right\\}\\right)' assert latex(SymmetricDifference(A, D2, evaluate=False)) == \ '\\left\\{a\\right\\} \\triangle \\left(\\left\\{c\\right\\} ' \ '\\triangle \\left\\{d\\right\\}\\right)' assert latex(SymmetricDifference(U1, U2, evaluate=False)) == \ '\\left(\\left\\{a\\right\\} \\cup \\left\\{b\\right\\}\\right) ' \ '\\triangle \\left(\\left\\{c\\right\\} \\cup ' \ '\\left\\{d\\right\\}\\right)' assert latex(SymmetricDifference(I1, I2, evaluate=False)) == \ '\\left(\\left\\{a\\right\\} \\cap \\left\\{b\\right\\}\\right) ' \ '\\triangle \\left(\\left\\{c\\right\\} \\cap ' \ '\\left\\{d\\right\\}\\right)' assert latex(SymmetricDifference(C1, C2, evaluate=False)) == \ '\\left(\\left\\{a\\right\\} \\setminus ' \ '\\left\\{b\\right\\}\\right) \\triangle ' \ '\\left(\\left\\{c\\right\\} \\setminus \\left\\{d\\right\\}\\right)' assert latex(SymmetricDifference(P1, P2, evaluate=False)) == \ '\\left(\\left\\{a\\right\\} \\times \\left\\{b\\right\\}\\right) ' \ '\\triangle \\left(\\left\\{c\\right\\} \\times ' \ '\\left\\{d\\right\\}\\right)' # XXX This can be incorrect since cartesian product is not associative assert latex(ProductSet(A, P2).flatten()) == \ '\\left\\{a\\right\\} \\times \\left\\{c\\right\\} \\times ' \ '\\left\\{d\\right\\}' assert latex(ProductSet(U1, U2)) == \ '\\left(\\left\\{a\\right\\} \\cup \\left\\{b\\right\\}\\right) ' \ '\\times \\left(\\left\\{c\\right\\} \\cup ' \ '\\left\\{d\\right\\}\\right)' assert latex(ProductSet(I1, I2)) == \ '\\left(\\left\\{a\\right\\} \\cap \\left\\{b\\right\\}\\right) ' \ '\\times \\left(\\left\\{c\\right\\} \\cap ' \ '\\left\\{d\\right\\}\\right)' assert latex(ProductSet(C1, C2)) == \ '\\left(\\left\\{a\\right\\} \\setminus ' \ '\\left\\{b\\right\\}\\right) \\times \\left(\\left\\{c\\right\\} ' \ '\\setminus \\left\\{d\\right\\}\\right)' assert latex(ProductSet(D1, D2)) == \ '\\left(\\left\\{a\\right\\} \\triangle ' \ '\\left\\{b\\right\\}\\right) \\times \\left(\\left\\{c\\right\\} ' \ '\\triangle \\left\\{d\\right\\}\\right)' def test_latex_Complexes(): assert latex(S.Complexes) == r"\mathbb{C}" def test_latex_Naturals(): assert latex(S.Naturals) == r"\mathbb{N}" def test_latex_Naturals0(): assert latex(S.Naturals0) == r"\mathbb{N}_0" def test_latex_Integers(): assert latex(S.Integers) == r"\mathbb{Z}" def test_latex_ImageSet(): x = Symbol('x') assert latex(ImageSet(Lambda(x, x**2), S.Naturals)) == \ r"\left\{x^{2}\; |\; x \in \mathbb{N}\right\}" y = Symbol('y') imgset = ImageSet(Lambda((x, y), x + y), {1, 2, 3}, {3, 4}) assert latex(imgset) == \ r"\left\{x + y\; |\; x \in \left\{1, 2, 3\right\} , y \in \left\{3, 4\right\}\right\}" imgset = ImageSet(Lambda(((x, y),), x + y), ProductSet({1, 2, 3}, {3, 4})) assert latex(imgset) == \ r"\left\{x + y\; |\; \left( x, \ y\right) \in \left\{1, 2, 3\right\} \times \left\{3, 4\right\}\right\}" def test_latex_ConditionSet(): x = Symbol('x') assert latex(ConditionSet(x, Eq(x**2, 1), S.Reals)) == \ r"\left\{x \mid x \in \mathbb{R} \wedge x^{2} = 1 \right\}" assert latex(ConditionSet(x, Eq(x**2, 1), S.UniversalSet)) == \ r"\left\{x \mid x^{2} = 1 \right\}" def test_latex_ComplexRegion(): assert latex(ComplexRegion(Interval(3, 5)*Interval(4, 6))) == \ r"\left\{x + y i\; |\; x, y \in \left[3, 5\right] \times \left[4, 6\right] \right\}" assert latex(ComplexRegion(Interval(0, 1)*Interval(0, 2*pi), polar=True)) == \ r"\left\{r \left(i \sin{\left(\theta \right)} + \cos{\left(\theta "\ r"\right)}\right)\; |\; r, \theta \in \left[0, 1\right] \times \left[0, 2 \pi\right) \right\}" def test_latex_Contains(): x = Symbol('x') assert latex(Contains(x, S.Naturals)) == r"x \in \mathbb{N}" def test_latex_sum(): assert latex(Sum(x*y**2, (x, -2, 2), (y, -5, 5))) == \ r"\sum_{\substack{-2 \leq x \leq 2\\-5 \leq y \leq 5}} x y^{2}" assert latex(Sum(x**2, (x, -2, 2))) == \ r"\sum_{x=-2}^{2} x^{2}" assert latex(Sum(x**2 + y, (x, -2, 2))) == \ r"\sum_{x=-2}^{2} \left(x^{2} + y\right)" assert latex(Sum(x**2 + y, (x, -2, 2))**2) == \ r"\left(\sum_{x=-2}^{2} \left(x^{2} + y\right)\right)^{2}" def test_latex_product(): assert latex(Product(x*y**2, (x, -2, 2), (y, -5, 5))) == \ r"\prod_{\substack{-2 \leq x \leq 2\\-5 \leq y \leq 5}} x y^{2}" assert latex(Product(x**2, (x, -2, 2))) == \ r"\prod_{x=-2}^{2} x^{2}" assert latex(Product(x**2 + y, (x, -2, 2))) == \ r"\prod_{x=-2}^{2} \left(x^{2} + y\right)" assert latex(Product(x, (x, -2, 2))**2) == \ r"\left(\prod_{x=-2}^{2} x\right)^{2}" def test_latex_limits(): assert latex(Limit(x, x, oo)) == r"\lim_{x \to \infty} x" # issue 8175 f = Function('f') assert latex(Limit(f(x), x, 0)) == r"\lim_{x \to 0^+} f{\left(x \right)}" assert latex(Limit(f(x), x, 0, "-")) == \ r"\lim_{x \to 0^-} f{\left(x \right)}" # issue #10806 assert latex(Limit(f(x), x, 0)**2) == \ r"\left(\lim_{x \to 0^+} f{\left(x \right)}\right)^{2}" # bi-directional limit assert latex(Limit(f(x), x, 0, dir='+-')) == \ r"\lim_{x \to 0} f{\left(x \right)}" def test_latex_log(): assert latex(log(x)) == r"\log{\left(x \right)}" assert latex(ln(x)) == r"\log{\left(x \right)}" assert latex(log(x), ln_notation=True) == r"\ln{\left(x \right)}" assert latex(log(x)+log(y)) == \ r"\log{\left(x \right)} + \log{\left(y \right)}" assert latex(log(x)+log(y), ln_notation=True) == \ r"\ln{\left(x \right)} + \ln{\left(y \right)}" assert latex(pow(log(x), x)) == r"\log{\left(x \right)}^{x}" assert latex(pow(log(x), x), ln_notation=True) == \ r"\ln{\left(x \right)}^{x}" def test_issue_3568(): beta = Symbol(r'\beta') y = beta + x assert latex(y) in [r'\beta + x', r'x + \beta'] beta = Symbol(r'beta') y = beta + x assert latex(y) in [r'\beta + x', r'x + \beta'] def test_latex(): assert latex((2*tau)**Rational(7, 2)) == "8 \\sqrt{2} \\tau^{\\frac{7}{2}}" assert latex((2*mu)**Rational(7, 2), mode='equation*') == \ "\\begin{equation*}8 \\sqrt{2} \\mu^{\\frac{7}{2}}\\end{equation*}" assert latex((2*mu)**Rational(7, 2), mode='equation', itex=True) == \ "$$8 \\sqrt{2} \\mu^{\\frac{7}{2}}$$" assert latex([2/x, y]) == r"\left[ \frac{2}{x}, \ y\right]" def test_latex_dict(): d = {Rational(1): 1, x**2: 2, x: 3, x**3: 4} assert latex(d) == \ r'\left\{ 1 : 1, \ x : 3, \ x^{2} : 2, \ x^{3} : 4\right\}' D = Dict(d) assert latex(D) == \ r'\left\{ 1 : 1, \ x : 3, \ x^{2} : 2, \ x^{3} : 4\right\}' def test_latex_list(): ll = [Symbol('omega1'), Symbol('a'), Symbol('alpha')] assert latex(ll) == r'\left[ \omega_{1}, \ a, \ \alpha\right]' def test_latex_rational(): # tests issue 3973 assert latex(-Rational(1, 2)) == "- \\frac{1}{2}" assert latex(Rational(-1, 2)) == "- \\frac{1}{2}" assert latex(Rational(1, -2)) == "- \\frac{1}{2}" assert latex(-Rational(-1, 2)) == "\\frac{1}{2}" assert latex(-Rational(1, 2)*x) == "- \\frac{x}{2}" assert latex(-Rational(1, 2)*x + Rational(-2, 3)*y) == \ "- \\frac{x}{2} - \\frac{2 y}{3}" def test_latex_inverse(): # tests issue 4129 assert latex(1/x) == "\\frac{1}{x}" assert latex(1/(x + y)) == "\\frac{1}{x + y}" def test_latex_DiracDelta(): assert latex(DiracDelta(x)) == r"\delta\left(x\right)" assert latex(DiracDelta(x)**2) == r"\left(\delta\left(x\right)\right)^{2}" assert latex(DiracDelta(x, 0)) == r"\delta\left(x\right)" assert latex(DiracDelta(x, 5)) == \ r"\delta^{\left( 5 \right)}\left( x \right)" assert latex(DiracDelta(x, 5)**2) == \ r"\left(\delta^{\left( 5 \right)}\left( x \right)\right)^{2}" def test_latex_Heaviside(): assert latex(Heaviside(x)) == r"\theta\left(x\right)" assert latex(Heaviside(x)**2) == r"\left(\theta\left(x\right)\right)^{2}" def test_latex_KroneckerDelta(): assert latex(KroneckerDelta(x, y)) == r"\delta_{x y}" assert latex(KroneckerDelta(x, y + 1)) == r"\delta_{x, y + 1}" # issue 6578 assert latex(KroneckerDelta(x + 1, y)) == r"\delta_{y, x + 1}" assert latex(Pow(KroneckerDelta(x, y), 2, evaluate=False)) == \ r"\left(\delta_{x y}\right)^{2}" def test_latex_LeviCivita(): assert latex(LeviCivita(x, y, z)) == r"\varepsilon_{x y z}" assert latex(LeviCivita(x, y, z)**2) == \ r"\left(\varepsilon_{x y z}\right)^{2}" assert latex(LeviCivita(x, y, z + 1)) == r"\varepsilon_{x, y, z + 1}" assert latex(LeviCivita(x, y + 1, z)) == r"\varepsilon_{x, y + 1, z}" assert latex(LeviCivita(x + 1, y, z)) == r"\varepsilon_{x + 1, y, z}" def test_mode(): expr = x + y assert latex(expr) == 'x + y' assert latex(expr, mode='plain') == 'x + y' assert latex(expr, mode='inline') == '$x + y$' assert latex( expr, mode='equation*') == '\\begin{equation*}x + y\\end{equation*}' assert latex( expr, mode='equation') == '\\begin{equation}x + y\\end{equation}' raises(ValueError, lambda: latex(expr, mode='foo')) def test_latex_mathieu(): assert latex(mathieuc(x, y, z)) == r"C\left(x, y, z\right)" assert latex(mathieus(x, y, z)) == r"S\left(x, y, z\right)" assert latex(mathieuc(x, y, z)**2) == r"C\left(x, y, z\right)^{2}" assert latex(mathieus(x, y, z)**2) == r"S\left(x, y, z\right)^{2}" assert latex(mathieucprime(x, y, z)) == r"C^{\prime}\left(x, y, z\right)" assert latex(mathieusprime(x, y, z)) == r"S^{\prime}\left(x, y, z\right)" assert latex(mathieucprime(x, y, z)**2) == r"C^{\prime}\left(x, y, z\right)^{2}" assert latex(mathieusprime(x, y, z)**2) == r"S^{\prime}\left(x, y, z\right)^{2}" def test_latex_Piecewise(): p = Piecewise((x, x < 1), (x**2, True)) assert latex(p) == "\\begin{cases} x & \\text{for}\\: x < 1 \\\\x^{2} &" \ " \\text{otherwise} \\end{cases}" assert latex(p, itex=True) == \ "\\begin{cases} x & \\text{for}\\: x \\lt 1 \\\\x^{2} &" \ " \\text{otherwise} \\end{cases}" p = Piecewise((x, x < 0), (0, x >= 0)) assert latex(p) == '\\begin{cases} x & \\text{for}\\: x < 0 \\\\0 &' \ ' \\text{otherwise} \\end{cases}' A, B = symbols("A B", commutative=False) p = Piecewise((A**2, Eq(A, B)), (A*B, True)) s = r"\begin{cases} A^{2} & \text{for}\: A = B \\A B & \text{otherwise} \end{cases}" assert latex(p) == s assert latex(A*p) == r"A \left(%s\right)" % s assert latex(p*A) == r"\left(%s\right) A" % s assert latex(Piecewise((x, x < 1), (x**2, x < 2))) == \ '\\begin{cases} x & ' \ '\\text{for}\\: x < 1 \\\\x^{2} & \\text{for}\\: x < 2 \\end{cases}' def test_latex_Matrix(): M = Matrix([[1 + x, y], [y, x - 1]]) assert latex(M) == \ r'\left[\begin{matrix}x + 1 & y\\y & x - 1\end{matrix}\right]' assert latex(M, mode='inline') == \ r'$\left[\begin{smallmatrix}x + 1 & y\\' \ r'y & x - 1\end{smallmatrix}\right]$' assert latex(M, mat_str='array') == \ r'\left[\begin{array}{cc}x + 1 & y\\y & x - 1\end{array}\right]' assert latex(M, mat_str='bmatrix') == \ r'\left[\begin{bmatrix}x + 1 & y\\y & x - 1\end{bmatrix}\right]' assert latex(M, mat_delim=None, mat_str='bmatrix') == \ r'\begin{bmatrix}x + 1 & y\\y & x - 1\end{bmatrix}' M2 = Matrix(1, 11, range(11)) assert latex(M2) == \ r'\left[\begin{array}{ccccccccccc}' \ r'0 & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10\end{array}\right]' def test_latex_matrix_with_functions(): t = symbols('t') theta1 = symbols('theta1', cls=Function) M = Matrix([[sin(theta1(t)), cos(theta1(t))], [cos(theta1(t).diff(t)), sin(theta1(t).diff(t))]]) expected = (r'\left[\begin{matrix}\sin{\left(' r'\theta_{1}{\left(t \right)} \right)} & ' r'\cos{\left(\theta_{1}{\left(t \right)} \right)' r'}\\\cos{\left(\frac{d}{d t} \theta_{1}{\left(t ' r'\right)} \right)} & \sin{\left(\frac{d}{d t} ' r'\theta_{1}{\left(t \right)} \right' r')}\end{matrix}\right]') assert latex(M) == expected def test_latex_NDimArray(): x, y, z, w = symbols("x y z w") for ArrayType in (ImmutableDenseNDimArray, ImmutableSparseNDimArray, MutableDenseNDimArray, MutableSparseNDimArray): # Basic: scalar array M = ArrayType(x) assert latex(M) == "x" M = ArrayType([[1 / x, y], [z, w]]) M1 = ArrayType([1 / x, y, z]) M2 = tensorproduct(M1, M) M3 = tensorproduct(M, M) assert latex(M) == \ '\\left[\\begin{matrix}\\frac{1}{x} & y\\\\z & w\\end{matrix}\\right]' assert latex(M1) == \ "\\left[\\begin{matrix}\\frac{1}{x} & y & z\\end{matrix}\\right]" assert latex(M2) == \ r"\left[\begin{matrix}" \ r"\left[\begin{matrix}\frac{1}{x^{2}} & \frac{y}{x}\\\frac{z}{x} & \frac{w}{x}\end{matrix}\right] & " \ r"\left[\begin{matrix}\frac{y}{x} & y^{2}\\y z & w y\end{matrix}\right] & " \ r"\left[\begin{matrix}\frac{z}{x} & y z\\z^{2} & w z\end{matrix}\right]" \ r"\end{matrix}\right]" assert latex(M3) == \ r"""\left[\begin{matrix}"""\ r"""\left[\begin{matrix}\frac{1}{x^{2}} & \frac{y}{x}\\\frac{z}{x} & \frac{w}{x}\end{matrix}\right] & """\ r"""\left[\begin{matrix}\frac{y}{x} & y^{2}\\y z & w y\end{matrix}\right]\\"""\ r"""\left[\begin{matrix}\frac{z}{x} & y z\\z^{2} & w z\end{matrix}\right] & """\ r"""\left[\begin{matrix}\frac{w}{x} & w y\\w z & w^{2}\end{matrix}\right]"""\ r"""\end{matrix}\right]""" Mrow = ArrayType([[x, y, 1/z]]) Mcolumn = ArrayType([[x], [y], [1/z]]) Mcol2 = ArrayType([Mcolumn.tolist()]) assert latex(Mrow) == \ r"\left[\left[\begin{matrix}x & y & \frac{1}{z}\end{matrix}\right]\right]" assert latex(Mcolumn) == \ r"\left[\begin{matrix}x\\y\\\frac{1}{z}\end{matrix}\right]" assert latex(Mcol2) == \ r'\left[\begin{matrix}\left[\begin{matrix}x\\y\\\frac{1}{z}\end{matrix}\right]\end{matrix}\right]' def test_latex_mul_symbol(): assert latex(4*4**x, mul_symbol='times') == "4 \\times 4^{x}" assert latex(4*4**x, mul_symbol='dot') == "4 \\cdot 4^{x}" assert latex(4*4**x, mul_symbol='ldot') == r"4 \,.\, 4^{x}" assert latex(4*x, mul_symbol='times') == "4 \\times x" assert latex(4*x, mul_symbol='dot') == "4 \\cdot x" assert latex(4*x, mul_symbol='ldot') == r"4 \,.\, x" def test_latex_issue_4381(): y = 4*4**log(2) assert latex(y) == r'4 \cdot 4^{\log{\left(2 \right)}}' assert latex(1/y) == r'\frac{1}{4 \cdot 4^{\log{\left(2 \right)}}}' def test_latex_issue_4576(): assert latex(Symbol("beta_13_2")) == r"\beta_{13 2}" assert latex(Symbol("beta_132_20")) == r"\beta_{132 20}" assert latex(Symbol("beta_13")) == r"\beta_{13}" assert latex(Symbol("x_a_b")) == r"x_{a b}" assert latex(Symbol("x_1_2_3")) == r"x_{1 2 3}" assert latex(Symbol("x_a_b1")) == r"x_{a b1}" assert latex(Symbol("x_a_1")) == r"x_{a 1}" assert latex(Symbol("x_1_a")) == r"x_{1 a}" assert latex(Symbol("x_1^aa")) == r"x^{aa}_{1}" assert latex(Symbol("x_1__aa")) == r"x^{aa}_{1}" assert latex(Symbol("x_11^a")) == r"x^{a}_{11}" assert latex(Symbol("x_11__a")) == r"x^{a}_{11}" assert latex(Symbol("x_a_a_a_a")) == r"x_{a a a a}" assert latex(Symbol("x_a_a^a^a")) == r"x^{a a}_{a a}" assert latex(Symbol("x_a_a__a__a")) == r"x^{a a}_{a a}" assert latex(Symbol("alpha_11")) == r"\alpha_{11}" assert latex(Symbol("alpha_11_11")) == r"\alpha_{11 11}" assert latex(Symbol("alpha_alpha")) == r"\alpha_{\alpha}" assert latex(Symbol("alpha^aleph")) == r"\alpha^{\aleph}" assert latex(Symbol("alpha__aleph")) == r"\alpha^{\aleph}" def test_latex_pow_fraction(): x = Symbol('x') # Testing exp assert 'e^{-x}' in latex(exp(-x)/2).replace(' ', '') # Remove Whitespace # Testing e^{-x} in case future changes alter behavior of muls or fracs # In particular current output is \frac{1}{2}e^{- x} but perhaps this will # change to \frac{e^{-x}}{2} # Testing general, non-exp, power assert '3^{-x}' in latex(3**-x/2).replace(' ', '') def test_noncommutative(): A, B, C = symbols('A,B,C', commutative=False) assert latex(A*B*C**-1) == "A B C^{-1}" assert latex(C**-1*A*B) == "C^{-1} A B" assert latex(A*C**-1*B) == "A C^{-1} B" def test_latex_order(): expr = x**3 + x**2*y + y**4 + 3*x*y**3 assert latex(expr, order='lex') == "x^{3} + x^{2} y + 3 x y^{3} + y^{4}" assert latex( expr, order='rev-lex') == "y^{4} + 3 x y^{3} + x^{2} y + x^{3}" assert latex(expr, order='none') == "x^{3} + y^{4} + y x^{2} + 3 x y^{3}" def test_latex_Lambda(): assert latex(Lambda(x, x + 1)) == \ r"\left( x \mapsto x + 1 \right)" assert latex(Lambda((x, y), x + 1)) == \ r"\left( \left( x, \ y\right) \mapsto x + 1 \right)" def test_latex_PolyElement(): Ruv, u, v = ring("u,v", ZZ) Rxyz, x, y, z = ring("x,y,z", Ruv) assert latex(x - x) == r"0" assert latex(x - 1) == r"x - 1" assert latex(x + 1) == r"x + 1" assert latex((u**2 + 3*u*v + 1)*x**2*y + u + 1) == \ r"\left({u}^{2} + 3 u v + 1\right) {x}^{2} y + u + 1" assert latex((u**2 + 3*u*v + 1)*x**2*y + (u + 1)*x) == \ r"\left({u}^{2} + 3 u v + 1\right) {x}^{2} y + \left(u + 1\right) x" assert latex((u**2 + 3*u*v + 1)*x**2*y + (u + 1)*x + 1) == \ r"\left({u}^{2} + 3 u v + 1\right) {x}^{2} y + \left(u + 1\right) x + 1" assert latex((-u**2 + 3*u*v - 1)*x**2*y - (u + 1)*x - 1) == \ r"-\left({u}^{2} - 3 u v + 1\right) {x}^{2} y - \left(u + 1\right) x - 1" assert latex(-(v**2 + v + 1)*x + 3*u*v + 1) == \ r"-\left({v}^{2} + v + 1\right) x + 3 u v + 1" assert latex(-(v**2 + v + 1)*x - 3*u*v + 1) == \ r"-\left({v}^{2} + v + 1\right) x - 3 u v + 1" def test_latex_FracElement(): Fuv, u, v = field("u,v", ZZ) Fxyzt, x, y, z, t = field("x,y,z,t", Fuv) assert latex(x - x) == r"0" assert latex(x - 1) == r"x - 1" assert latex(x + 1) == r"x + 1" assert latex(x/3) == r"\frac{x}{3}" assert latex(x/z) == r"\frac{x}{z}" assert latex(x*y/z) == r"\frac{x y}{z}" assert latex(x/(z*t)) == r"\frac{x}{z t}" assert latex(x*y/(z*t)) == r"\frac{x y}{z t}" assert latex((x - 1)/y) == r"\frac{x - 1}{y}" assert latex((x + 1)/y) == r"\frac{x + 1}{y}" assert latex((-x - 1)/y) == r"\frac{-x - 1}{y}" assert latex((x + 1)/(y*z)) == r"\frac{x + 1}{y z}" assert latex(-y/(x + 1)) == r"\frac{-y}{x + 1}" assert latex(y*z/(x + 1)) == r"\frac{y z}{x + 1}" assert latex(((u + 1)*x*y + 1)/((v - 1)*z - 1)) == \ r"\frac{\left(u + 1\right) x y + 1}{\left(v - 1\right) z - 1}" assert latex(((u + 1)*x*y + 1)/((v - 1)*z - t*u*v - 1)) == \ r"\frac{\left(u + 1\right) x y + 1}{\left(v - 1\right) z - u v t - 1}" def test_latex_Poly(): assert latex(Poly(x**2 + 2 * x, x)) == \ r"\operatorname{Poly}{\left( x^{2} + 2 x, x, domain=\mathbb{Z} \right)}" assert latex(Poly(x/y, x)) == \ r"\operatorname{Poly}{\left( \frac{1}{y} x, x, domain=\mathbb{Z}\left(y\right) \right)}" assert latex(Poly(2.0*x + y)) == \ r"\operatorname{Poly}{\left( 2.0 x + 1.0 y, x, y, domain=\mathbb{R} \right)}" def test_latex_Poly_order(): assert latex(Poly([a, 1, b, 2, c, 3], x)) == \ '\\operatorname{Poly}{\\left( a x^{5} + x^{4} + b x^{3} + 2 x^{2} + c'\ ' x + 3, x, domain=\\mathbb{Z}\\left[a, b, c\\right] \\right)}' assert latex(Poly([a, 1, b+c, 2, 3], x)) == \ '\\operatorname{Poly}{\\left( a x^{4} + x^{3} + \\left(b + c\\right) '\ 'x^{2} + 2 x + 3, x, domain=\\mathbb{Z}\\left[a, b, c\\right] \\right)}' assert latex(Poly(a*x**3 + x**2*y - x*y - c*y**3 - b*x*y**2 + y - a*x + b, (x, y))) == \ '\\operatorname{Poly}{\\left( a x^{3} + x^{2}y - b xy^{2} - xy - '\ 'a x - c y^{3} + y + b, x, y, domain=\\mathbb{Z}\\left[a, b, c\\right] \\right)}' def test_latex_ComplexRootOf(): assert latex(rootof(x**5 + x + 3, 0)) == \ r"\operatorname{CRootOf} {\left(x^{5} + x + 3, 0\right)}" def test_latex_RootSum(): assert latex(RootSum(x**5 + x + 3, sin)) == \ r"\operatorname{RootSum} {\left(x^{5} + x + 3, \left( x \mapsto \sin{\left(x \right)} \right)\right)}" def test_settings(): raises(TypeError, lambda: latex(x*y, method="garbage")) def test_latex_numbers(): assert latex(catalan(n)) == r"C_{n}" assert latex(catalan(n)**2) == r"C_{n}^{2}" assert latex(bernoulli(n)) == r"B_{n}" assert latex(bernoulli(n, x)) == r"B_{n}\left(x\right)" assert latex(bernoulli(n)**2) == r"B_{n}^{2}" assert latex(bernoulli(n, x)**2) == r"B_{n}^{2}\left(x\right)" assert latex(bell(n)) == r"B_{n}" assert latex(bell(n, x)) == r"B_{n}\left(x\right)" assert latex(bell(n, m, (x, y))) == r"B_{n, m}\left(x, y\right)" assert latex(bell(n)**2) == r"B_{n}^{2}" assert latex(bell(n, x)**2) == r"B_{n}^{2}\left(x\right)" assert latex(bell(n, m, (x, y))**2) == r"B_{n, m}^{2}\left(x, y\right)" assert latex(fibonacci(n)) == r"F_{n}" assert latex(fibonacci(n, x)) == r"F_{n}\left(x\right)" assert latex(fibonacci(n)**2) == r"F_{n}^{2}" assert latex(fibonacci(n, x)**2) == r"F_{n}^{2}\left(x\right)" assert latex(lucas(n)) == r"L_{n}" assert latex(lucas(n)**2) == r"L_{n}^{2}" assert latex(tribonacci(n)) == r"T_{n}" assert latex(tribonacci(n, x)) == r"T_{n}\left(x\right)" assert latex(tribonacci(n)**2) == r"T_{n}^{2}" assert latex(tribonacci(n, x)**2) == r"T_{n}^{2}\left(x\right)" def test_latex_euler(): assert latex(euler(n)) == r"E_{n}" assert latex(euler(n, x)) == r"E_{n}\left(x\right)" assert latex(euler(n, x)**2) == r"E_{n}^{2}\left(x\right)" def test_lamda(): assert latex(Symbol('lamda')) == r"\lambda" assert latex(Symbol('Lamda')) == r"\Lambda" def test_custom_symbol_names(): x = Symbol('x') y = Symbol('y') assert latex(x) == "x" assert latex(x, symbol_names={x: "x_i"}) == "x_i" assert latex(x + y, symbol_names={x: "x_i"}) == "x_i + y" assert latex(x**2, symbol_names={x: "x_i"}) == "x_i^{2}" assert latex(x + y, symbol_names={x: "x_i", y: "y_j"}) == "x_i + y_j" def test_matAdd(): from sympy import MatrixSymbol from sympy.printing.latex import LatexPrinter C = MatrixSymbol('C', 5, 5) B = MatrixSymbol('B', 5, 5) l = LatexPrinter() assert l._print(C - 2*B) in ['- 2 B + C', 'C -2 B'] assert l._print(C + 2*B) in ['2 B + C', 'C + 2 B'] assert l._print(B - 2*C) in ['B - 2 C', '- 2 C + B'] assert l._print(B + 2*C) in ['B + 2 C', '2 C + B'] def test_matMul(): from sympy import MatrixSymbol from sympy.printing.latex import LatexPrinter A = MatrixSymbol('A', 5, 5) B = MatrixSymbol('B', 5, 5) x = Symbol('x') lp = LatexPrinter() assert lp._print_MatMul(2*A) == '2 A' assert lp._print_MatMul(2*x*A) == '2 x A' assert lp._print_MatMul(-2*A) == '- 2 A' assert lp._print_MatMul(1.5*A) == '1.5 A' assert lp._print_MatMul(sqrt(2)*A) == r'\sqrt{2} A' assert lp._print_MatMul(-sqrt(2)*A) == r'- \sqrt{2} A' assert lp._print_MatMul(2*sqrt(2)*x*A) == r'2 \sqrt{2} x A' assert lp._print_MatMul(-2*A*(A + 2*B)) in [r'- 2 A \left(A + 2 B\right)', r'- 2 A \left(2 B + A\right)'] def test_latex_MatrixSlice(): from sympy.matrices.expressions import MatrixSymbol assert latex(MatrixSymbol('X', 10, 10)[:5, 1:9:2]) == \ r'X\left[:5, 1:9:2\right]' assert latex(MatrixSymbol('X', 10, 10)[5, :5:2]) == \ r'X\left[5, :5:2\right]' def test_latex_RandomDomain(): from sympy.stats import Normal, Die, Exponential, pspace, where from sympy.stats.rv import RandomDomain X = Normal('x1', 0, 1) assert latex(where(X > 0)) == r"\text{Domain: }0 < x_{1} \wedge x_{1} < \infty" D = Die('d1', 6) assert latex(where(D > 4)) == r"\text{Domain: }d_{1} = 5 \vee d_{1} = 6" A = Exponential('a', 1) B = Exponential('b', 1) assert latex( pspace(Tuple(A, B)).domain) == \ r"\text{Domain: }0 \leq a \wedge 0 \leq b \wedge a < \infty \wedge b < \infty" assert latex(RandomDomain(FiniteSet(x), FiniteSet(1, 2))) == \ r'\text{Domain: }\left\{x\right\}\text{ in }\left\{1, 2\right\}' def test_PrettyPoly(): from sympy.polys.domains import QQ F = QQ.frac_field(x, y) R = QQ[x, y] assert latex(F.convert(x/(x + y))) == latex(x/(x + y)) assert latex(R.convert(x + y)) == latex(x + y) def test_integral_transforms(): x = Symbol("x") k = Symbol("k") f = Function("f") a = Symbol("a") b = Symbol("b") assert latex(MellinTransform(f(x), x, k)) == \ r"\mathcal{M}_{x}\left[f{\left(x \right)}\right]\left(k\right)" assert latex(InverseMellinTransform(f(k), k, x, a, b)) == \ r"\mathcal{M}^{-1}_{k}\left[f{\left(k \right)}\right]\left(x\right)" assert latex(LaplaceTransform(f(x), x, k)) == \ r"\mathcal{L}_{x}\left[f{\left(x \right)}\right]\left(k\right)" assert latex(InverseLaplaceTransform(f(k), k, x, (a, b))) == \ r"\mathcal{L}^{-1}_{k}\left[f{\left(k \right)}\right]\left(x\right)" assert latex(FourierTransform(f(x), x, k)) == \ r"\mathcal{F}_{x}\left[f{\left(x \right)}\right]\left(k\right)" assert latex(InverseFourierTransform(f(k), k, x)) == \ r"\mathcal{F}^{-1}_{k}\left[f{\left(k \right)}\right]\left(x\right)" assert latex(CosineTransform(f(x), x, k)) == \ r"\mathcal{COS}_{x}\left[f{\left(x \right)}\right]\left(k\right)" assert latex(InverseCosineTransform(f(k), k, x)) == \ r"\mathcal{COS}^{-1}_{k}\left[f{\left(k \right)}\right]\left(x\right)" assert latex(SineTransform(f(x), x, k)) == \ r"\mathcal{SIN}_{x}\left[f{\left(x \right)}\right]\left(k\right)" assert latex(InverseSineTransform(f(k), k, x)) == \ r"\mathcal{SIN}^{-1}_{k}\left[f{\left(k \right)}\right]\left(x\right)" def test_PolynomialRingBase(): from sympy.polys.domains import QQ assert latex(QQ.old_poly_ring(x, y)) == r"\mathbb{Q}\left[x, y\right]" assert latex(QQ.old_poly_ring(x, y, order="ilex")) == \ r"S_<^{-1}\mathbb{Q}\left[x, y\right]" def test_categories(): from sympy.categories import (Object, IdentityMorphism, NamedMorphism, Category, Diagram, DiagramGrid) A1 = Object("A1") A2 = Object("A2") A3 = Object("A3") f1 = NamedMorphism(A1, A2, "f1") f2 = NamedMorphism(A2, A3, "f2") id_A1 = IdentityMorphism(A1) K1 = Category("K1") assert latex(A1) == "A_{1}" assert latex(f1) == "f_{1}:A_{1}\\rightarrow A_{2}" assert latex(id_A1) == "id:A_{1}\\rightarrow A_{1}" assert latex(f2*f1) == "f_{2}\\circ f_{1}:A_{1}\\rightarrow A_{3}" assert latex(K1) == r"\mathbf{K_{1}}" d = Diagram() assert latex(d) == r"\emptyset" d = Diagram({f1: "unique", f2: S.EmptySet}) assert latex(d) == r"\left\{ f_{2}\circ f_{1}:A_{1}" \ r"\rightarrow A_{3} : \emptyset, \ id:A_{1}\rightarrow " \ r"A_{1} : \emptyset, \ id:A_{2}\rightarrow A_{2} : " \ r"\emptyset, \ id:A_{3}\rightarrow A_{3} : \emptyset, " \ r"\ f_{1}:A_{1}\rightarrow A_{2} : \left\{unique\right\}, " \ r"\ f_{2}:A_{2}\rightarrow A_{3} : \emptyset\right\}" d = Diagram({f1: "unique", f2: S.EmptySet}, {f2 * f1: "unique"}) assert latex(d) == r"\left\{ f_{2}\circ f_{1}:A_{1}" \ r"\rightarrow A_{3} : \emptyset, \ id:A_{1}\rightarrow " \ r"A_{1} : \emptyset, \ id:A_{2}\rightarrow A_{2} : " \ r"\emptyset, \ id:A_{3}\rightarrow A_{3} : \emptyset, " \ r"\ f_{1}:A_{1}\rightarrow A_{2} : \left\{unique\right\}," \ r" \ f_{2}:A_{2}\rightarrow A_{3} : \emptyset\right\}" \ r"\Longrightarrow \left\{ f_{2}\circ f_{1}:A_{1}" \ r"\rightarrow A_{3} : \left\{unique\right\}\right\}" # A linear diagram. A = Object("A") B = Object("B") C = Object("C") f = NamedMorphism(A, B, "f") g = NamedMorphism(B, C, "g") d = Diagram([f, g]) grid = DiagramGrid(d) assert latex(grid) == "\\begin{array}{cc}\n" \ "A & B \\\\\n" \ " & C \n" \ "\\end{array}\n" def test_Modules(): from sympy.polys.domains import QQ from sympy.polys.agca import homomorphism R = QQ.old_poly_ring(x, y) F = R.free_module(2) M = F.submodule([x, y], [1, x**2]) assert latex(F) == r"{\mathbb{Q}\left[x, y\right]}^{2}" assert latex(M) == \ r"\left\langle {\left[ {x},{y} \right]},{\left[ {1},{x^{2}} \right]} \right\rangle" I = R.ideal(x**2, y) assert latex(I) == r"\left\langle {x^{2}},{y} \right\rangle" Q = F / M assert latex(Q) == \ r"\frac{{\mathbb{Q}\left[x, y\right]}^{2}}{\left\langle {\left[ {x},"\ r"{y} \right]},{\left[ {1},{x^{2}} \right]} \right\rangle}" assert latex(Q.submodule([1, x**3/2], [2, y])) == \ r"\left\langle {{\left[ {1},{\frac{x^{3}}{2}} \right]} + {\left"\ r"\langle {\left[ {x},{y} \right]},{\left[ {1},{x^{2}} \right]} "\ r"\right\rangle}},{{\left[ {2},{y} \right]} + {\left\langle {\left[ "\ r"{x},{y} \right]},{\left[ {1},{x^{2}} \right]} \right\rangle}} \right\rangle" h = homomorphism(QQ.old_poly_ring(x).free_module(2), QQ.old_poly_ring(x).free_module(2), [0, 0]) assert latex(h) == \ r"{\left[\begin{matrix}0 & 0\\0 & 0\end{matrix}\right]} : "\ r"{{\mathbb{Q}\left[x\right]}^{2}} \to {{\mathbb{Q}\left[x\right]}^{2}}" def test_QuotientRing(): from sympy.polys.domains import QQ R = QQ.old_poly_ring(x)/[x**2 + 1] assert latex(R) == \ r"\frac{\mathbb{Q}\left[x\right]}{\left\langle {x^{2} + 1} \right\rangle}" assert latex(R.one) == r"{1} + {\left\langle {x^{2} + 1} \right\rangle}" def test_Tr(): #TODO: Handle indices A, B = symbols('A B', commutative=False) t = Tr(A*B) assert latex(t) == r'\operatorname{tr}\left(A B\right)' def test_Adjoint(): from sympy.matrices import MatrixSymbol, Adjoint, Inverse, Transpose X = MatrixSymbol('X', 2, 2) Y = MatrixSymbol('Y', 2, 2) assert latex(Adjoint(X)) == r'X^{\dagger}' assert latex(Adjoint(X + Y)) == r'\left(X + Y\right)^{\dagger}' assert latex(Adjoint(X) + Adjoint(Y)) == r'X^{\dagger} + Y^{\dagger}' assert latex(Adjoint(X*Y)) == r'\left(X Y\right)^{\dagger}' assert latex(Adjoint(Y)*Adjoint(X)) == r'Y^{\dagger} X^{\dagger}' assert latex(Adjoint(X**2)) == r'\left(X^{2}\right)^{\dagger}' assert latex(Adjoint(X)**2) == r'\left(X^{\dagger}\right)^{2}' assert latex(Adjoint(Inverse(X))) == r'\left(X^{-1}\right)^{\dagger}' assert latex(Inverse(Adjoint(X))) == r'\left(X^{\dagger}\right)^{-1}' assert latex(Adjoint(Transpose(X))) == r'\left(X^{T}\right)^{\dagger}' assert latex(Transpose(Adjoint(X))) == r'\left(X^{\dagger}\right)^{T}' assert latex(Transpose(Adjoint(X) + Y)) == r'\left(X^{\dagger} + Y\right)^{T}' def test_Transpose(): from sympy.matrices import Transpose, MatPow, HadamardPower X = MatrixSymbol('X', 2, 2) Y = MatrixSymbol('Y', 2, 2) assert latex(Transpose(X)) == r'X^{T}' assert latex(Transpose(X + Y)) == r'\left(X + Y\right)^{T}' assert latex(Transpose(HadamardPower(X, 2))) == \ r'\left(X^{\circ {2}}\right)^{T}' assert latex(HadamardPower(Transpose(X), 2)) == \ r'\left(X^{T}\right)^{\circ {2}}' assert latex(Transpose(MatPow(X, 2))) == \ r'\left(X^{2}\right)^{T}' assert latex(MatPow(Transpose(X), 2)) == \ r'\left(X^{T}\right)^{2}' def test_Hadamard(): from sympy.matrices import MatrixSymbol, HadamardProduct, HadamardPower from sympy.matrices.expressions import MatAdd, MatMul, MatPow X = MatrixSymbol('X', 2, 2) Y = MatrixSymbol('Y', 2, 2) assert latex(HadamardProduct(X, Y*Y)) == r'X \circ Y^{2}' assert latex(HadamardProduct(X, Y)*Y) == r'\left(X \circ Y\right) Y' assert latex(HadamardPower(X, 2)) == r'X^{\circ {2}}' assert latex(HadamardPower(X, -1)) == r'X^{\circ \left({-1}\right)}' assert latex(HadamardPower(MatAdd(X, Y), 2)) == \ r'\left(X + Y\right)^{\circ {2}}' assert latex(HadamardPower(MatMul(X, Y), 2)) == \ r'\left(X Y\right)^{\circ {2}}' assert latex(HadamardPower(MatPow(X, -1), -1)) == \ r'\left(X^{-1}\right)^{\circ \left({-1}\right)}' assert latex(MatPow(HadamardPower(X, -1), -1)) == \ r'\left(X^{\circ \left({-1}\right)}\right)^{-1}' assert latex(HadamardPower(X, n+1)) == \ r'X^{\circ \left({n + 1}\right)}' def test_ElementwiseApplyFunction(): from sympy.matrices import MatrixSymbol X = MatrixSymbol('X', 2, 2) expr = (X.T*X).applyfunc(sin) assert latex(expr) == r"{\left( d \mapsto \sin{\left(d \right)} \right)}_{\circ}\left({X^{T} X}\right)" expr = X.applyfunc(Lambda(x, 1/x)) assert latex(expr) == r'{\left( d \mapsto \frac{1}{d} \right)}_{\circ}\left({X}\right)' def test_ZeroMatrix(): from sympy import ZeroMatrix assert latex(ZeroMatrix(1, 1), mat_symbol_style='plain') == r"\mathbb{0}" assert latex(ZeroMatrix(1, 1), mat_symbol_style='bold') == r"\mathbf{0}" def test_OneMatrix(): from sympy import OneMatrix assert latex(OneMatrix(3, 4), mat_symbol_style='plain') == r"\mathbb{1}" assert latex(OneMatrix(3, 4), mat_symbol_style='bold') == r"\mathbf{1}" def test_Identity(): from sympy import Identity assert latex(Identity(1), mat_symbol_style='plain') == r"\mathbb{I}" assert latex(Identity(1), mat_symbol_style='bold') == r"\mathbf{I}" def test_boolean_args_order(): syms = symbols('a:f') expr = And(*syms) assert latex(expr) == 'a \\wedge b \\wedge c \\wedge d \\wedge e \\wedge f' expr = Or(*syms) assert latex(expr) == 'a \\vee b \\vee c \\vee d \\vee e \\vee f' expr = Equivalent(*syms) assert latex(expr) == \ 'a \\Leftrightarrow b \\Leftrightarrow c \\Leftrightarrow d \\Leftrightarrow e \\Leftrightarrow f' expr = Xor(*syms) assert latex(expr) == \ 'a \\veebar b \\veebar c \\veebar d \\veebar e \\veebar f' def test_imaginary(): i = sqrt(-1) assert latex(i) == r'i' def test_builtins_without_args(): assert latex(sin) == r'\sin' assert latex(cos) == r'\cos' assert latex(tan) == r'\tan' assert latex(log) == r'\log' assert latex(Ei) == r'\operatorname{Ei}' assert latex(zeta) == r'\zeta' def test_latex_greek_functions(): # bug because capital greeks that have roman equivalents should not use # \Alpha, \Beta, \Eta, etc. s = Function('Alpha') assert latex(s) == r'A' assert latex(s(x)) == r'A{\left(x \right)}' s = Function('Beta') assert latex(s) == r'B' s = Function('Eta') assert latex(s) == r'H' assert latex(s(x)) == r'H{\left(x \right)}' # bug because sympy.core.numbers.Pi is special p = Function('Pi') # assert latex(p(x)) == r'\Pi{\left(x \right)}' assert latex(p) == r'\Pi' # bug because not all greeks are included c = Function('chi') assert latex(c(x)) == r'\chi{\left(x \right)}' assert latex(c) == r'\chi' def test_translate(): s = 'Alpha' assert translate(s) == 'A' s = 'Beta' assert translate(s) == 'B' s = 'Eta' assert translate(s) == 'H' s = 'omicron' assert translate(s) == 'o' s = 'Pi' assert translate(s) == r'\Pi' s = 'pi' assert translate(s) == r'\pi' s = 'LamdaHatDOT' assert translate(s) == r'\dot{\hat{\Lambda}}' def test_other_symbols(): from sympy.printing.latex import other_symbols for s in other_symbols: assert latex(symbols(s)) == "\\"+s def test_modifiers(): # Test each modifier individually in the simplest case # (with funny capitalizations) assert latex(symbols("xMathring")) == r"\mathring{x}" assert latex(symbols("xCheck")) == r"\check{x}" assert latex(symbols("xBreve")) == r"\breve{x}" assert latex(symbols("xAcute")) == r"\acute{x}" assert latex(symbols("xGrave")) == r"\grave{x}" assert latex(symbols("xTilde")) == r"\tilde{x}" assert latex(symbols("xPrime")) == r"{x}'" assert latex(symbols("xddDDot")) == r"\ddddot{x}" assert latex(symbols("xDdDot")) == r"\dddot{x}" assert latex(symbols("xDDot")) == r"\ddot{x}" assert latex(symbols("xBold")) == r"\boldsymbol{x}" assert latex(symbols("xnOrM")) == r"\left\|{x}\right\|" assert latex(symbols("xAVG")) == r"\left\langle{x}\right\rangle" assert latex(symbols("xHat")) == r"\hat{x}" assert latex(symbols("xDot")) == r"\dot{x}" assert latex(symbols("xBar")) == r"\bar{x}" assert latex(symbols("xVec")) == r"\vec{x}" assert latex(symbols("xAbs")) == r"\left|{x}\right|" assert latex(symbols("xMag")) == r"\left|{x}\right|" assert latex(symbols("xPrM")) == r"{x}'" assert latex(symbols("xBM")) == r"\boldsymbol{x}" # Test strings that are *only* the names of modifiers assert latex(symbols("Mathring")) == r"Mathring" assert latex(symbols("Check")) == r"Check" assert latex(symbols("Breve")) == r"Breve" assert latex(symbols("Acute")) == r"Acute" assert latex(symbols("Grave")) == r"Grave" assert latex(symbols("Tilde")) == r"Tilde" assert latex(symbols("Prime")) == r"Prime" assert latex(symbols("DDot")) == r"\dot{D}" assert latex(symbols("Bold")) == r"Bold" assert latex(symbols("NORm")) == r"NORm" assert latex(symbols("AVG")) == r"AVG" assert latex(symbols("Hat")) == r"Hat" assert latex(symbols("Dot")) == r"Dot" assert latex(symbols("Bar")) == r"Bar" assert latex(symbols("Vec")) == r"Vec" assert latex(symbols("Abs")) == r"Abs" assert latex(symbols("Mag")) == r"Mag" assert latex(symbols("PrM")) == r"PrM" assert latex(symbols("BM")) == r"BM" assert latex(symbols("hbar")) == r"\hbar" # Check a few combinations assert latex(symbols("xvecdot")) == r"\dot{\vec{x}}" assert latex(symbols("xDotVec")) == r"\vec{\dot{x}}" assert latex(symbols("xHATNorm")) == r"\left\|{\hat{x}}\right\|" # Check a couple big, ugly combinations assert latex(symbols('xMathringBm_yCheckPRM__zbreveAbs')) == \ r"\boldsymbol{\mathring{x}}^{\left|{\breve{z}}\right|}_{{\check{y}}'}" assert latex(symbols('alphadothat_nVECDOT__tTildePrime')) == \ r"\hat{\dot{\alpha}}^{{\tilde{t}}'}_{\dot{\vec{n}}}" def test_greek_symbols(): assert latex(Symbol('alpha')) == r'\alpha' assert latex(Symbol('beta')) == r'\beta' assert latex(Symbol('gamma')) == r'\gamma' assert latex(Symbol('delta')) == r'\delta' assert latex(Symbol('epsilon')) == r'\epsilon' assert latex(Symbol('zeta')) == r'\zeta' assert latex(Symbol('eta')) == r'\eta' assert latex(Symbol('theta')) == r'\theta' assert latex(Symbol('iota')) == r'\iota' assert latex(Symbol('kappa')) == r'\kappa' assert latex(Symbol('lambda')) == r'\lambda' assert latex(Symbol('mu')) == r'\mu' assert latex(Symbol('nu')) == r'\nu' assert latex(Symbol('xi')) == r'\xi' assert latex(Symbol('omicron')) == r'o' assert latex(Symbol('pi')) == r'\pi' assert latex(Symbol('rho')) == r'\rho' assert latex(Symbol('sigma')) == r'\sigma' assert latex(Symbol('tau')) == r'\tau' assert latex(Symbol('upsilon')) == r'\upsilon' assert latex(Symbol('phi')) == r'\phi' assert latex(Symbol('chi')) == r'\chi' assert latex(Symbol('psi')) == r'\psi' assert latex(Symbol('omega')) == r'\omega' assert latex(Symbol('Alpha')) == r'A' assert latex(Symbol('Beta')) == r'B' assert latex(Symbol('Gamma')) == r'\Gamma' assert latex(Symbol('Delta')) == r'\Delta' assert latex(Symbol('Epsilon')) == r'E' assert latex(Symbol('Zeta')) == r'Z' assert latex(Symbol('Eta')) == r'H' assert latex(Symbol('Theta')) == r'\Theta' assert latex(Symbol('Iota')) == r'I' assert latex(Symbol('Kappa')) == r'K' assert latex(Symbol('Lambda')) == r'\Lambda' assert latex(Symbol('Mu')) == r'M' assert latex(Symbol('Nu')) == r'N' assert latex(Symbol('Xi')) == r'\Xi' assert latex(Symbol('Omicron')) == r'O' assert latex(Symbol('Pi')) == r'\Pi' assert latex(Symbol('Rho')) == r'P' assert latex(Symbol('Sigma')) == r'\Sigma' assert latex(Symbol('Tau')) == r'T' assert latex(Symbol('Upsilon')) == r'\Upsilon' assert latex(Symbol('Phi')) == r'\Phi' assert latex(Symbol('Chi')) == r'X' assert latex(Symbol('Psi')) == r'\Psi' assert latex(Symbol('Omega')) == r'\Omega' assert latex(Symbol('varepsilon')) == r'\varepsilon' assert latex(Symbol('varkappa')) == r'\varkappa' assert latex(Symbol('varphi')) == r'\varphi' assert latex(Symbol('varpi')) == r'\varpi' assert latex(Symbol('varrho')) == r'\varrho' assert latex(Symbol('varsigma')) == r'\varsigma' assert latex(Symbol('vartheta')) == r'\vartheta' def test_fancyset_symbols(): assert latex(S.Rationals) == '\\mathbb{Q}' assert latex(S.Naturals) == '\\mathbb{N}' assert latex(S.Naturals0) == '\\mathbb{N}_0' assert latex(S.Integers) == '\\mathbb{Z}' assert latex(S.Reals) == '\\mathbb{R}' assert latex(S.Complexes) == '\\mathbb{C}' @XFAIL def test_builtin_without_args_mismatched_names(): assert latex(CosineTransform) == r'\mathcal{COS}' def test_builtin_no_args(): assert latex(Chi) == r'\operatorname{Chi}' assert latex(beta) == r'\operatorname{B}' assert latex(gamma) == r'\Gamma' assert latex(KroneckerDelta) == r'\delta' assert latex(DiracDelta) == r'\delta' assert latex(lowergamma) == r'\gamma' def test_issue_6853(): p = Function('Pi') assert latex(p(x)) == r"\Pi{\left(x \right)}" def test_Mul(): e = Mul(-2, x + 1, evaluate=False) assert latex(e) == r'- 2 \left(x + 1\right)' e = Mul(2, x + 1, evaluate=False) assert latex(e) == r'2 \left(x + 1\right)' e = Mul(S.Half, x + 1, evaluate=False) assert latex(e) == r'\frac{x + 1}{2}' e = Mul(y, x + 1, evaluate=False) assert latex(e) == r'y \left(x + 1\right)' e = Mul(-y, x + 1, evaluate=False) assert latex(e) == r'- y \left(x + 1\right)' e = Mul(-2, x + 1) assert latex(e) == r'- 2 x - 2' e = Mul(2, x + 1) assert latex(e) == r'2 x + 2' def test_Pow(): e = Pow(2, 2, evaluate=False) assert latex(e) == r'2^{2}' assert latex(x**(Rational(-1, 3))) == r'\frac{1}{\sqrt[3]{x}}' x2 = Symbol(r'x^2') assert latex(x2**2) == r'\left(x^{2}\right)^{2}' def test_issue_7180(): assert latex(Equivalent(x, y)) == r"x \Leftrightarrow y" assert latex(Not(Equivalent(x, y))) == r"x \not\Leftrightarrow y" def test_issue_8409(): assert latex(S.Half**n) == r"\left(\frac{1}{2}\right)^{n}" def test_issue_8470(): from sympy.parsing.sympy_parser import parse_expr e = parse_expr("-B*A", evaluate=False) assert latex(e) == r"A \left(- B\right)" def test_issue_15439(): x = MatrixSymbol('x', 2, 2) y = MatrixSymbol('y', 2, 2) assert latex((x * y).subs(y, -y)) == r"x \left(- y\right)" assert latex((x * y).subs(y, -2*y)) == r"x \left(- 2 y\right)" assert latex((x * y).subs(x, -x)) == r"- x y" def test_issue_2934(): assert latex(Symbol(r'\frac{a_1}{b_1}')) == '\\frac{a_1}{b_1}' def test_issue_10489(): latexSymbolWithBrace = 'C_{x_{0}}' s = Symbol(latexSymbolWithBrace) assert latex(s) == latexSymbolWithBrace assert latex(cos(s)) == r'\cos{\left(C_{x_{0}} \right)}' def test_issue_12886(): m__1, l__1 = symbols('m__1, l__1') assert latex(m__1**2 + l__1**2) == \ r'\left(l^{1}\right)^{2} + \left(m^{1}\right)^{2}' def test_issue_13559(): from sympy.parsing.sympy_parser import parse_expr expr = parse_expr('5/1', evaluate=False) assert latex(expr) == r"\frac{5}{1}" def test_issue_13651(): expr = c + Mul(-1, a + b, evaluate=False) assert latex(expr) == r"c - \left(a + b\right)" def test_latex_UnevaluatedExpr(): x = symbols("x") he = UnevaluatedExpr(1/x) assert latex(he) == latex(1/x) == r"\frac{1}{x}" assert latex(he**2) == r"\left(\frac{1}{x}\right)^{2}" assert latex(he + 1) == r"1 + \frac{1}{x}" assert latex(x*he) == r"x \frac{1}{x}" def test_MatrixElement_printing(): # test cases for issue #11821 A = MatrixSymbol("A", 1, 3) B = MatrixSymbol("B", 1, 3) C = MatrixSymbol("C", 1, 3) assert latex(A[0, 0]) == r"A_{0, 0}" assert latex(3 * A[0, 0]) == r"3 A_{0, 0}" F = C[0, 0].subs(C, A - B) assert latex(F) == r"\left(A - B\right)_{0, 0}" i, j, k = symbols("i j k") M = MatrixSymbol("M", k, k) N = MatrixSymbol("N", k, k) assert latex((M*N)[i, j]) == \ r'\sum_{i_{1}=0}^{k - 1} M_{i, i_{1}} N_{i_{1}, j}' def test_MatrixSymbol_printing(): # test cases for issue #14237 A = MatrixSymbol("A", 3, 3) B = MatrixSymbol("B", 3, 3) C = MatrixSymbol("C", 3, 3) assert latex(-A) == r"- A" assert latex(A - A*B - B) == r"A - A B - B" assert latex(-A*B - A*B*C - B) == r"- A B - A B C - B" def test_KroneckerProduct_printing(): A = MatrixSymbol('A', 3, 3) B = MatrixSymbol('B', 2, 2) assert latex(KroneckerProduct(A, B)) == r'A \otimes B' def test_Quaternion_latex_printing(): q = Quaternion(x, y, z, t) assert latex(q) == "x + y i + z j + t k" q = Quaternion(x, y, z, x*t) assert latex(q) == "x + y i + z j + t x k" q = Quaternion(x, y, z, x + t) assert latex(q) == r"x + y i + z j + \left(t + x\right) k" def test_TensorProduct_printing(): from sympy.tensor.functions import TensorProduct A = MatrixSymbol("A", 3, 3) B = MatrixSymbol("B", 3, 3) assert latex(TensorProduct(A, B)) == r"A \otimes B" def test_WedgeProduct_printing(): from sympy.diffgeom.rn import R2 from sympy.diffgeom import WedgeProduct wp = WedgeProduct(R2.dx, R2.dy) assert latex(wp) == r"\operatorname{d}x \wedge \operatorname{d}y" def test_issue_14041(): import sympy.physics.mechanics as me A_frame = me.ReferenceFrame('A') thetad, phid = me.dynamicsymbols('theta, phi', 1) L = Symbol('L') assert latex(L*(phid + thetad)**2*A_frame.x) == \ r"L \left(\dot{\phi} + \dot{\theta}\right)^{2}\mathbf{\hat{a}_x}" assert latex((phid + thetad)**2*A_frame.x) == \ r"\left(\dot{\phi} + \dot{\theta}\right)^{2}\mathbf{\hat{a}_x}" assert latex((phid*thetad)**a*A_frame.x) == \ r"\left(\dot{\phi} \dot{\theta}\right)^{a}\mathbf{\hat{a}_x}" def test_issue_9216(): expr_1 = Pow(1, -1, evaluate=False) assert latex(expr_1) == r"1^{-1}" expr_2 = Pow(1, Pow(1, -1, evaluate=False), evaluate=False) assert latex(expr_2) == r"1^{1^{-1}}" expr_3 = Pow(3, -2, evaluate=False) assert latex(expr_3) == r"\frac{1}{9}" expr_4 = Pow(1, -2, evaluate=False) assert latex(expr_4) == r"1^{-2}" def test_latex_printer_tensor(): from sympy.tensor.tensor import TensorIndexType, tensor_indices, TensorHead, tensor_heads L = TensorIndexType("L") i, j, k, l = tensor_indices("i j k l", L) i0 = tensor_indices("i_0", L) A, B, C, D = tensor_heads("A B C D", [L]) H = TensorHead("H", [L, L]) K = TensorHead("K", [L, L, L, L]) assert latex(i) == "{}^{i}" assert latex(-i) == "{}_{i}" expr = A(i) assert latex(expr) == "A{}^{i}" expr = A(i0) assert latex(expr) == "A{}^{i_{0}}" expr = A(-i) assert latex(expr) == "A{}_{i}" expr = -3*A(i) assert latex(expr) == r"-3A{}^{i}" expr = K(i, j, -k, -i0) assert latex(expr) == "K{}^{ij}{}_{ki_{0}}" expr = K(i, -j, -k, i0) assert latex(expr) == "K{}^{i}{}_{jk}{}^{i_{0}}" expr = K(i, -j, k, -i0) assert latex(expr) == "K{}^{i}{}_{j}{}^{k}{}_{i_{0}}" expr = H(i, -j) assert latex(expr) == "H{}^{i}{}_{j}" expr = H(i, j) assert latex(expr) == "H{}^{ij}" expr = H(-i, -j) assert latex(expr) == "H{}_{ij}" expr = (1+x)*A(i) assert latex(expr) == r"\left(x + 1\right)A{}^{i}" expr = H(i, -i) assert latex(expr) == "H{}^{L_{0}}{}_{L_{0}}" expr = H(i, -j)*A(j)*B(k) assert latex(expr) == "H{}^{i}{}_{L_{0}}A{}^{L_{0}}B{}^{k}" expr = A(i) + 3*B(i) assert latex(expr) == "3B{}^{i} + A{}^{i}" # Test ``TensorElement``: from sympy.tensor.tensor import TensorElement expr = TensorElement(K(i, j, k, l), {i: 3, k: 2}) assert latex(expr) == 'K{}^{i=3,j,k=2,l}' expr = TensorElement(K(i, j, k, l), {i: 3}) assert latex(expr) == 'K{}^{i=3,jkl}' expr = TensorElement(K(i, -j, k, l), {i: 3, k: 2}) assert latex(expr) == 'K{}^{i=3}{}_{j}{}^{k=2,l}' expr = TensorElement(K(i, -j, k, -l), {i: 3, k: 2}) assert latex(expr) == 'K{}^{i=3}{}_{j}{}^{k=2}{}_{l}' expr = TensorElement(K(i, j, -k, -l), {i: 3, -k: 2}) assert latex(expr) == 'K{}^{i=3,j}{}_{k=2,l}' expr = TensorElement(K(i, j, -k, -l), {i: 3}) assert latex(expr) == 'K{}^{i=3,j}{}_{kl}' expr = PartialDerivative(A(i), A(i)) assert latex(expr) == r"\frac{\partial}{\partial {A{}^{L_{0}}}}{A{}^{L_{0}}}" expr = PartialDerivative(A(-i), A(-j)) assert latex(expr) == r"\frac{\partial}{\partial {A{}_{j}}}{A{}_{i}}" expr = PartialDerivative(K(i, j, -k, -l), A(m), A(-n)) assert latex(expr) == r"\frac{\partial^{2}}{\partial {A{}^{m}} \partial {A{}_{n}}}{K{}^{ij}{}_{kl}}" expr = PartialDerivative(B(-i) + A(-i), A(-j), A(-n)) assert latex(expr) == r"\frac{\partial^{2}}{\partial {A{}_{j}} \partial {A{}_{n}}}{\left(A{}_{i} + B{}_{i}\right)}" expr = PartialDerivative(3*A(-i), A(-j), A(-n)) assert latex(expr) == r"\frac{\partial^{2}}{\partial {A{}_{j}} \partial {A{}_{n}}}{\left(3A{}_{i}\right)}" def test_multiline_latex(): a, b, c, d, e, f = symbols('a b c d e f') expr = -a + 2*b -3*c +4*d -5*e expected = r"\begin{eqnarray}" + "\n"\ r"f & = &- a \nonumber\\" + "\n"\ r"& & + 2 b \nonumber\\" + "\n"\ r"& & - 3 c \nonumber\\" + "\n"\ r"& & + 4 d \nonumber\\" + "\n"\ r"& & - 5 e " + "\n"\ r"\end{eqnarray}" assert multiline_latex(f, expr, environment="eqnarray") == expected expected2 = r'\begin{eqnarray}' + '\n'\ r'f & = &- a + 2 b \nonumber\\' + '\n'\ r'& & - 3 c + 4 d \nonumber\\' + '\n'\ r'& & - 5 e ' + '\n'\ r'\end{eqnarray}' assert multiline_latex(f, expr, 2, environment="eqnarray") == expected2 expected3 = r'\begin{eqnarray}' + '\n'\ r'f & = &- a + 2 b - 3 c \nonumber\\'+ '\n'\ r'& & + 4 d - 5 e ' + '\n'\ r'\end{eqnarray}' assert multiline_latex(f, expr, 3, environment="eqnarray") == expected3 expected3dots = r'\begin{eqnarray}' + '\n'\ r'f & = &- a + 2 b - 3 c \dots\nonumber\\'+ '\n'\ r'& & + 4 d - 5 e ' + '\n'\ r'\end{eqnarray}' assert multiline_latex(f, expr, 3, environment="eqnarray", use_dots=True) == expected3dots expected3align = r'\begin{align*}' + '\n'\ r'f = &- a + 2 b - 3 c \\'+ '\n'\ r'& + 4 d - 5 e ' + '\n'\ r'\end{align*}' assert multiline_latex(f, expr, 3) == expected3align assert multiline_latex(f, expr, 3, environment='align*') == expected3align expected2ieee = r'\begin{IEEEeqnarray}{rCl}' + '\n'\ r'f & = &- a + 2 b \nonumber\\' + '\n'\ r'& & - 3 c + 4 d \nonumber\\' + '\n'\ r'& & - 5 e ' + '\n'\ r'\end{IEEEeqnarray}' assert multiline_latex(f, expr, 2, environment="IEEEeqnarray") == expected2ieee raises(ValueError, lambda: multiline_latex(f, expr, environment="foo")) def test_issue_15353(): from sympy import ConditionSet, Tuple, S, sin, cos a, x = symbols('a x') # Obtained from nonlinsolve([(sin(a*x)),cos(a*x)],[x,a]) sol = ConditionSet( Tuple(x, a), Eq(sin(a*x), 0) & Eq(cos(a*x), 0), S.Complexes**2) assert latex(sol) == \ r'\left\{\left( x, \ a\right) \mid \left( x, \ a\right) \in ' \ r'\mathbb{C}^{2} \wedge \sin{\left(a x \right)} = 0 \wedge ' \ r'\cos{\left(a x \right)} = 0 \right\}' def test_trace(): # Issue 15303 from sympy import trace A = MatrixSymbol("A", 2, 2) assert latex(trace(A)) == r"\operatorname{tr}\left(A \right)" assert latex(trace(A**2)) == r"\operatorname{tr}\left(A^{2} \right)" def test_print_basic(): # Issue 15303 from sympy import Basic, Expr # dummy class for testing printing where the function is not # implemented in latex.py class UnimplementedExpr(Expr): def __new__(cls, e): return Basic.__new__(cls, e) # dummy function for testing def unimplemented_expr(expr): return UnimplementedExpr(expr).doit() # override class name to use superscript / subscript def unimplemented_expr_sup_sub(expr): result = UnimplementedExpr(expr) result.__class__.__name__ = 'UnimplementedExpr_x^1' return result assert latex(unimplemented_expr(x)) == r'UnimplementedExpr\left(x\right)' assert latex(unimplemented_expr(x**2)) == \ r'UnimplementedExpr\left(x^{2}\right)' assert latex(unimplemented_expr_sup_sub(x)) == \ r'UnimplementedExpr^{1}_{x}\left(x\right)' def test_MatrixSymbol_bold(): # Issue #15871 from sympy import trace A = MatrixSymbol("A", 2, 2) assert latex(trace(A), mat_symbol_style='bold') == \ r"\operatorname{tr}\left(\mathbf{A} \right)" assert latex(trace(A), mat_symbol_style='plain') == \ r"\operatorname{tr}\left(A \right)" A = MatrixSymbol("A", 3, 3) B = MatrixSymbol("B", 3, 3) C = MatrixSymbol("C", 3, 3) assert latex(-A, mat_symbol_style='bold') == r"- \mathbf{A}" assert latex(A - A*B - B, mat_symbol_style='bold') == \ r"\mathbf{A} - \mathbf{A} \mathbf{B} - \mathbf{B}" assert latex(-A*B - A*B*C - B, mat_symbol_style='bold') == \ r"- \mathbf{A} \mathbf{B} - \mathbf{A} \mathbf{B} \mathbf{C} - \mathbf{B}" A = MatrixSymbol("A_k", 3, 3) assert latex(A, mat_symbol_style='bold') == r"\mathbf{A_{k}}" def test_AppliedPermutation(): p = Permutation(0, 1, 2) x = Symbol('x') assert latex(AppliedPermutation(p, x)) == \ r'\sigma_{\left( 0\; 1\; 2\right)}(x)' def test_PermutationMatrix(): p = Permutation(0, 1, 2) assert latex(PermutationMatrix(p)) == r'P_{\left( 0\; 1\; 2\right)}' p = Permutation(0, 3)(1, 2) assert latex(PermutationMatrix(p)) == \ r'P_{\left( 0\; 3\right)\left( 1\; 2\right)}' def test_imaginary_unit(): assert latex(1 + I) == '1 + i' assert latex(1 + I, imaginary_unit='i') == '1 + i' assert latex(1 + I, imaginary_unit='j') == '1 + j' assert latex(1 + I, imaginary_unit='foo') == '1 + foo' assert latex(I, imaginary_unit="ti") == '\\text{i}' assert latex(I, imaginary_unit="tj") == '\\text{j}' def test_text_re_im(): assert latex(im(x), gothic_re_im=True) == r'\Im{\left(x\right)}' assert latex(im(x), gothic_re_im=False) == r'\operatorname{im}{\left(x\right)}' assert latex(re(x), gothic_re_im=True) == r'\Re{\left(x\right)}' assert latex(re(x), gothic_re_im=False) == r'\operatorname{re}{\left(x\right)}' def test_DiffGeomMethods(): from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseScalarField, Differential from sympy.diffgeom.rn import R2 m = Manifold('M', 2) assert latex(m) == r'\text{M}' p = Patch('P', m) assert latex(p) == r'\text{P}_{\text{M}}' rect = CoordSystem('rect', p) assert latex(rect) == r'\text{rect}^{\text{P}}_{\text{M}}' b = BaseScalarField(rect, 0) assert latex(b) == r'\mathbf{rect_{0}}' g = Function('g') s_field = g(R2.x, R2.y) assert latex(Differential(s_field)) == \ r'\operatorname{d}\left(g{\left(\mathbf{x},\mathbf{y} \right)}\right)' def test_unit_printing(): assert latex(5*meter) == r'5 \text{m}' assert latex(3*gibibyte) == r'3 \text{gibibyte}' assert latex(4*microgram/second) == r'\frac{4 \mu\text{g}}{\text{s}}' def test_issue_17092(): x_star = Symbol('x^*') assert latex(Derivative(x_star, x_star,2)) == r'\frac{d^{2}}{d \left(x^{*}\right)^{2}} x^{*}' def test_latex_decimal_separator(): x, y, z, t = symbols('x y z t') k, m, n = symbols('k m n', integer=True) f, g, h = symbols('f g h', cls=Function) # comma decimal_separator assert(latex([1, 2.3, 4.5], decimal_separator='comma') == r'\left[ 1; \ 2{,}3; \ 4{,}5\right]') assert(latex(FiniteSet(1, 2.3, 4.5), decimal_separator='comma') == r'\left\{1; 2{,}3; 4{,}5\right\}') assert(latex((1, 2.3, 4.6), decimal_separator = 'comma') == r'\left( 1; \ 2{,}3; \ 4{,}6\right)') # period decimal_separator assert(latex([1, 2.3, 4.5], decimal_separator='period') == r'\left[ 1, \ 2.3, \ 4.5\right]' ) assert(latex(FiniteSet(1, 2.3, 4.5), decimal_separator='period') == r'\left\{1, 2.3, 4.5\right\}') assert(latex((1, 2.3, 4.6), decimal_separator = 'period') == r'\left( 1, \ 2.3, \ 4.6\right)') # default decimal_separator assert(latex([1, 2.3, 4.5]) == r'\left[ 1, \ 2.3, \ 4.5\right]') assert(latex(FiniteSet(1, 2.3, 4.5)) == r'\left\{1, 2.3, 4.5\right\}') assert(latex((1, 2.3, 4.6)) == r'\left( 1, \ 2.3, \ 4.6\right)') assert(latex(Mul(3.4,5.3), decimal_separator = 'comma') ==r'18{,}02') assert(latex(3.4*5.3, decimal_separator = 'comma')==r'18{,}02') x = symbols('x') y = symbols('y') z = symbols('z') assert(latex(x*5.3 + 2**y**3.4 + 4.5 + z, decimal_separator = 'comma')== r'2^{y^{3{,}4}} + 5{,}3 x + z + 4{,}5') assert(latex(0.987, decimal_separator='comma') == r'0{,}987') assert(latex(S(0.987), decimal_separator='comma')== r'0{,}987') assert(latex(.3, decimal_separator='comma')== r'0{,}3') assert(latex(S(.3), decimal_separator='comma')== r'0{,}3') assert(latex(5.8*10**(-7), decimal_separator='comma') ==r'5{,}8e-07') assert(latex(S(5.7)*10**(-7), decimal_separator='comma')==r'5{,}7 \cdot 10^{-7}') assert(latex(S(5.7*10**(-7)), decimal_separator='comma')==r'5{,}7 \cdot 10^{-7}') x = symbols('x') assert(latex(1.2*x+3.4, decimal_separator='comma')==r'1{,}2 x + 3{,}4') assert(latex(FiniteSet(1, 2.3, 4.5), decimal_separator='period')==r'\left\{1, 2.3, 4.5\right\}') # Error Handling tests raises(ValueError, lambda: latex([1,2.3,4.5], decimal_separator='non_existing_decimal_separator_in_list')) raises(ValueError, lambda: latex(FiniteSet(1,2.3,4.5), decimal_separator='non_existing_decimal_separator_in_set')) raises(ValueError, lambda: latex((1,2.3,4.5), decimal_separator='non_existing_decimal_separator_in_tuple'))
6518f9cd1f0839a256d64c306385ef72c23c4f82e73ccfef51137c32dbdeae1c
from sympy.core import (S, pi, oo, symbols, Rational, Integer, GoldenRatio, EulerGamma, Catalan, Lambda, Dummy, Eq, Ne, Le, Lt, Gt, Ge) from sympy.functions import (Piecewise, sin, cos, Abs, exp, ceiling, sqrt, sign) from sympy.logic import ITE from sympy.testing.pytest import raises from sympy.utilities.lambdify import implemented_function from sympy.tensor import IndexedBase, Idx from sympy.matrices import MatrixSymbol from sympy import rust_code x, y, z = symbols('x,y,z') def test_Integer(): assert rust_code(Integer(42)) == "42" assert rust_code(Integer(-56)) == "-56" def test_Relational(): assert rust_code(Eq(x, y)) == "x == y" assert rust_code(Ne(x, y)) == "x != y" assert rust_code(Le(x, y)) == "x <= y" assert rust_code(Lt(x, y)) == "x < y" assert rust_code(Gt(x, y)) == "x > y" assert rust_code(Ge(x, y)) == "x >= y" def test_Rational(): assert rust_code(Rational(3, 7)) == "3_f64/7.0" assert rust_code(Rational(18, 9)) == "2" assert rust_code(Rational(3, -7)) == "-3_f64/7.0" assert rust_code(Rational(-3, -7)) == "3_f64/7.0" assert rust_code(x + Rational(3, 7)) == "x + 3_f64/7.0" assert rust_code(Rational(3, 7)*x) == "(3_f64/7.0)*x" def test_basic_ops(): assert rust_code(x + y) == "x + y" assert rust_code(x - y) == "x - y" assert rust_code(x * y) == "x*y" assert rust_code(x / y) == "x/y" assert rust_code(-x) == "-x" def test_printmethod(): class fabs(Abs): def _rust_code(self, printer): return "%s.fabs()" % printer._print(self.args[0]) assert rust_code(fabs(x)) == "x.fabs()" a = MatrixSymbol("a", 1 ,3) assert rust_code(a[0,0]) == 'a[0]' def test_Functions(): assert rust_code(sin(x) ** cos(x)) == "x.sin().powf(x.cos())" assert rust_code(abs(x)) == "x.abs()" assert rust_code(ceiling(x)) == "x.ceil()" def test_Pow(): assert rust_code(1/x) == "x.recip()" assert rust_code(x**-1) == rust_code(x**-1.0) == "x.recip()" assert rust_code(sqrt(x)) == "x.sqrt()" assert rust_code(x**S.Half) == rust_code(x**0.5) == "x.sqrt()" assert rust_code(1/sqrt(x)) == "x.sqrt().recip()" assert rust_code(x**-S.Half) == rust_code(x**-0.5) == "x.sqrt().recip()" assert rust_code(1/pi) == "PI.recip()" assert rust_code(pi**-1) == rust_code(pi**-1.0) == "PI.recip()" assert rust_code(pi**-0.5) == "PI.sqrt().recip()" assert rust_code(x**Rational(1, 3)) == "x.cbrt()" assert rust_code(2**x) == "x.exp2()" assert rust_code(exp(x)) == "x.exp()" assert rust_code(x**3) == "x.powi(3)" assert rust_code(x**(y**3)) == "x.powf(y.powi(3))" assert rust_code(x**Rational(2, 3)) == "x.powf(2_f64/3.0)" g = implemented_function('g', Lambda(x, 2*x)) assert rust_code(1/(g(x)*3.5)**(x - y**x)/(x**2 + y)) == \ "(3.5*2*x).powf(-x + y.powf(x))/(x.powi(2) + y)" _cond_cfunc = [(lambda base, exp: exp.is_integer, "dpowi", 1), (lambda base, exp: not exp.is_integer, "pow", 1)] assert rust_code(x**3, user_functions={'Pow': _cond_cfunc}) == 'x.dpowi(3)' assert rust_code(x**3.2, user_functions={'Pow': _cond_cfunc}) == 'x.pow(3.2)' def test_constants(): assert rust_code(pi) == "PI" assert rust_code(oo) == "INFINITY" assert rust_code(S.Infinity) == "INFINITY" assert rust_code(-oo) == "NEG_INFINITY" assert rust_code(S.NegativeInfinity) == "NEG_INFINITY" assert rust_code(S.NaN) == "NAN" assert rust_code(exp(1)) == "E" assert rust_code(S.Exp1) == "E" def test_constants_other(): assert rust_code(2*GoldenRatio) == "const GoldenRatio: f64 = %s;\n2*GoldenRatio" % GoldenRatio.evalf(17) assert rust_code( 2*Catalan) == "const Catalan: f64 = %s;\n2*Catalan" % Catalan.evalf(17) assert rust_code(2*EulerGamma) == "const EulerGamma: f64 = %s;\n2*EulerGamma" % EulerGamma.evalf(17) def test_boolean(): assert rust_code(True) == "true" assert rust_code(S.true) == "true" assert rust_code(False) == "false" assert rust_code(S.false) == "false" assert rust_code(x & y) == "x && y" assert rust_code(x | y) == "x || y" assert rust_code(~x) == "!x" assert rust_code(x & y & z) == "x && y && z" assert rust_code(x | y | z) == "x || y || z" assert rust_code((x & y) | z) == "z || x && y" assert rust_code((x | y) & z) == "z && (x || y)" def test_Piecewise(): expr = Piecewise((x, x < 1), (x + 2, True)) assert rust_code(expr) == ( "if (x < 1) {\n" " x\n" "} else {\n" " x + 2\n" "}") assert rust_code(expr, assign_to="r") == ( "r = if (x < 1) {\n" " x\n" "} else {\n" " x + 2\n" "};") assert rust_code(expr, assign_to="r", inline=True) == ( "r = if (x < 1) { x } else { x + 2 };") expr = Piecewise((x, x < 1), (x + 1, x < 5), (x + 2, True)) assert rust_code(expr, inline=True) == ( "if (x < 1) { x } else if (x < 5) { x + 1 } else { x + 2 }") assert rust_code(expr, assign_to="r", inline=True) == ( "r = if (x < 1) { x } else if (x < 5) { x + 1 } else { x + 2 };") assert rust_code(expr, assign_to="r") == ( "r = if (x < 1) {\n" " x\n" "} else if (x < 5) {\n" " x + 1\n" "} else {\n" " x + 2\n" "};") expr = 2*Piecewise((x, x < 1), (x + 1, x < 5), (x + 2, True)) assert rust_code(expr, inline=True) == ( "2*if (x < 1) { x } else if (x < 5) { x + 1 } else { x + 2 }") expr = 2*Piecewise((x, x < 1), (x + 1, x < 5), (x + 2, True)) - 42 assert rust_code(expr, inline=True) == ( "2*if (x < 1) { x } else if (x < 5) { x + 1 } else { x + 2 } - 42") # Check that Piecewise without a True (default) condition error expr = Piecewise((x, x < 1), (x**2, x > 1), (sin(x), x > 0)) raises(ValueError, lambda: rust_code(expr)) def test_dereference_printing(): expr = x + y + sin(z) + z assert rust_code(expr, dereference=[z]) == "x + y + (*z) + (*z).sin()" def test_sign(): expr = sign(x) * y assert rust_code(expr) == "y*x.signum()" assert rust_code(expr, assign_to='r') == "r = y*x.signum();" expr = sign(x + y) + 42 assert rust_code(expr) == "(x + y).signum() + 42" assert rust_code(expr, assign_to='r') == "r = (x + y).signum() + 42;" expr = sign(cos(x)) assert rust_code(expr) == "x.cos().signum()" def test_reserved_words(): x, y = symbols("x if") expr = sin(y) assert rust_code(expr) == "if_.sin()" assert rust_code(expr, dereference=[y]) == "(*if_).sin()" assert rust_code(expr, reserved_word_suffix='_unreserved') == "if_unreserved.sin()" with raises(ValueError): rust_code(expr, error_on_reserved=True) def test_ITE(): expr = ITE(x < 1, y, z) assert rust_code(expr) == ( "if (x < 1) {\n" " y\n" "} else {\n" " z\n" "}") def test_Indexed(): from sympy.tensor import IndexedBase, Idx from sympy import symbols n, m, o = symbols('n m o', integer=True) i, j, k = Idx('i', n), Idx('j', m), Idx('k', o) x = IndexedBase('x')[j] assert rust_code(x) == "x[j]" A = IndexedBase('A')[i, j] assert rust_code(A) == "A[m*i + j]" B = IndexedBase('B')[i, j, k] assert rust_code(B) == "B[m*o*i + o*j + k]" def test_dummy_loops(): i, m = symbols('i m', integer=True, cls=Dummy) x = IndexedBase('x') y = IndexedBase('y') i = Idx(i, m) assert rust_code(x[i], assign_to=y[i]) == ( "for i in 0..m {\n" " y[i] = x[i];\n" "}") def test_loops(): from sympy.tensor import IndexedBase, Idx from sympy import symbols m, n = symbols('m n', integer=True) A = IndexedBase('A') x = IndexedBase('x') y = IndexedBase('y') z = IndexedBase('z') i = Idx('i', m) j = Idx('j', n) assert rust_code(A[i, j]*x[j], assign_to=y[i]) == ( "for i in 0..m {\n" " y[i] = 0;\n" "}\n" "for i in 0..m {\n" " for j in 0..n {\n" " y[i] = A[n*i + j]*x[j] + y[i];\n" " }\n" "}") assert rust_code(A[i, j]*x[j] + x[i] + z[i], assign_to=y[i]) == ( "for i in 0..m {\n" " y[i] = x[i] + z[i];\n" "}\n" "for i in 0..m {\n" " for j in 0..n {\n" " y[i] = A[n*i + j]*x[j] + y[i];\n" " }\n" "}") def test_loops_multiple_contractions(): from sympy.tensor import IndexedBase, Idx from sympy 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) assert rust_code(b[j, k, l]*a[i, j, k, l], assign_to=y[i]) == ( "for i in 0..m {\n" " y[i] = 0;\n" "}\n" "for i in 0..m {\n" " for j in 0..n {\n" " for k in 0..o {\n" " for l in 0..p {\n" " y[i] = a[%s]*b[%s] + y[i];\n" % (i*n*o*p + j*o*p + k*p + l, j*o*p + k*p + l) +\ " }\n" " }\n" " }\n" "}") def test_loops_addfactor(): from sympy.tensor import IndexedBase, Idx from sympy import symbols m, n, o, p = symbols('m n 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) code = rust_code((a[i, j, k, l] + b[i, j, k, l])*c[j, k, l], assign_to=y[i]) assert code == ( "for i in 0..m {\n" " y[i] = 0;\n" "}\n" "for i in 0..m {\n" " for j in 0..n {\n" " for k in 0..o {\n" " for l in 0..p {\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" "}") def test_settings(): raises(TypeError, lambda: rust_code(sin(x), method="garbage")) def test_inline_function(): x = symbols('x') g = implemented_function('g', Lambda(x, 2*x)) assert rust_code(g(x)) == "2*x" g = implemented_function('g', Lambda(x, 2*x/Catalan)) assert rust_code(g(x)) == ( "const Catalan: f64 = %s;\n2*x/Catalan" % Catalan.evalf(17)) A = IndexedBase('A') i = Idx('i', symbols('n', integer=True)) g = implemented_function('g', Lambda(x, x*(1 + x)*(2 + x))) assert rust_code(g(A[i]), assign_to=A[i]) == ( "for i in 0..n {\n" " A[i] = (A[i] + 1)*(A[i] + 2)*A[i];\n" "}") 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)"
959854af6022d18c0fc3956152452e007a03132c5dbd94d7b0edfc8c6b032fc3
from sympy.core import (S, pi, oo, symbols, Function, Rational, Integer, Tuple, Symbol, Eq, Ne, Le, Lt, Gt, Ge) from sympy.core import EulerGamma, GoldenRatio, Catalan, Lambda, Mul, Pow from sympy.functions import Piecewise, sqrt, ceiling, exp, sin, cos from sympy.testing.pytest import raises from sympy.utilities.lambdify import implemented_function from sympy.matrices import (eye, Matrix, MatrixSymbol, Identity, HadamardProduct, SparseMatrix) from sympy.functions.special.bessel import (jn, yn, 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" def test_Relational(): assert julia_code(Eq(x, y)) == "x == y" assert julia_code(Ne(x, y)) == "x != y" assert julia_code(Le(x, y)) == "x <= y" assert julia_code(Lt(x, y)) == "x < y" assert julia_code(Gt(x, y)) == "x > y" assert julia_code(Ge(x, y)) == "x >= y" def test_Function(): assert julia_code(sin(x) ** cos(x)) == "sin(x).^cos(x)" assert julia_code(abs(x)) == "abs(x)" assert julia_code(ceiling(x)) == "ceil(x)" def test_Pow(): assert julia_code(x**3) == "x.^3" assert julia_code(x**(y**3)) == "x.^(y.^3)" assert julia_code(x**Rational(2, 3)) == 'x.^(2/3)' g = implemented_function('g', Lambda(x, 2*x)) assert julia_code(1/(g(x)*3.5)**(x - y**x)/(x**2 + y)) == \ "(3.5*2*x).^(-x + y.^x)./(x.^2 + y)" # For issue 14160 assert julia_code(Mul(-2, x, Pow(Mul(y,y,evaluate=False), -1, evaluate=False), evaluate=False)) == '-2*x./(y.*y)' def test_basic_ops(): assert julia_code(x*y) == "x.*y" assert julia_code(x + y) == "x + y" assert julia_code(x - y) == "x - y" assert julia_code(-x) == "-x" def test_1_over_x_and_sqrt(): # 1.0 and 0.5 would do something different in regular StrPrinter, # but these are exact in IEEE floating point so no different here. assert julia_code(1/x) == '1./x' assert julia_code(x**-1) == julia_code(x**-1.0) == '1./x' assert julia_code(1/sqrt(x)) == '1./sqrt(x)' assert julia_code(x**-S.Half) == julia_code(x**-0.5) == '1./sqrt(x)' assert julia_code(sqrt(x)) == 'sqrt(x)' assert julia_code(x**S.Half) == julia_code(x**0.5) == 'sqrt(x)' assert julia_code(1/pi) == '1/pi' assert julia_code(pi**-1) == julia_code(pi**-1.0) == '1/pi' assert julia_code(pi**-0.5) == '1/sqrt(pi)' def test_mix_number_mult_symbols(): assert julia_code(3*x) == "3*x" assert julia_code(pi*x) == "pi*x" assert julia_code(3/x) == "3./x" assert julia_code(pi/x) == "pi./x" assert julia_code(x/3) == "x/3" assert julia_code(x/pi) == "x/pi" assert julia_code(x*y) == "x.*y" assert julia_code(3*x*y) == "3*x.*y" assert julia_code(3*pi*x*y) == "3*pi*x.*y" assert julia_code(x/y) == "x./y" assert julia_code(3*x/y) == "3*x./y" assert julia_code(x*y/z) == "x.*y./z" assert julia_code(x/y*z) == "x.*z./y" assert julia_code(1/x/y) == "1./(x.*y)" assert julia_code(2*pi*x/y/z) == "2*pi*x./(y.*z)" assert julia_code(3*pi/x) == "3*pi./x" assert julia_code(S(3)/5) == "3/5" assert julia_code(S(3)/5*x) == "3*x/5" assert julia_code(x/y/z) == "x./(y.*z)" assert julia_code((x+y)/z) == "(x + y)./z" assert julia_code((x+y)/(z+x)) == "(x + y)./(x + z)" assert julia_code((x+y)/EulerGamma) == "(x + y)/eulergamma" assert julia_code(x/3/pi) == "x/(3*pi)" assert julia_code(S(3)/5*x*y/pi) == "3*x.*y/(5*pi)" def test_mix_number_pow_symbols(): assert julia_code(pi**3) == 'pi^3' assert julia_code(x**2) == 'x.^2' assert julia_code(x**(pi**3)) == 'x.^(pi^3)' assert julia_code(x**y) == 'x.^y' assert julia_code(x**(y**z)) == 'x.^(y.^z)' assert julia_code((x**y)**z) == '(x.^y).^z' def test_imag(): I = S('I') assert julia_code(I) == "im" assert julia_code(5*I) == "5im" assert julia_code((S(3)/2)*I) == "3*im/2" assert julia_code(3+4*I) == "3 + 4im" def test_constants(): assert julia_code(pi) == "pi" assert julia_code(oo) == "Inf" assert julia_code(-oo) == "-Inf" assert julia_code(S.NegativeInfinity) == "-Inf" assert julia_code(S.NaN) == "NaN" assert julia_code(S.Exp1) == "e" assert julia_code(exp(1)) == "e" def test_constants_other(): assert julia_code(2*GoldenRatio) == "2*golden" assert julia_code(2*Catalan) == "2*catalan" assert julia_code(2*EulerGamma) == "2*eulergamma" def test_boolean(): assert julia_code(x & y) == "x && y" assert julia_code(x | y) == "x || y" assert julia_code(~x) == "!x" assert julia_code(x & y & z) == "x && y && z" assert julia_code(x | y | z) == "x || y || z" assert julia_code((x & y) | z) == "z || x && y" assert julia_code((x | y) & z) == "z && (x || y)" def test_Matrices(): assert julia_code(Matrix(1, 1, [10])) == "[10]" A = Matrix([[1, sin(x/2), abs(x)], [0, 1, pi], [0, exp(1), ceiling(x)]]); expected = ("[1 sin(x/2) abs(x);\n" "0 1 pi;\n" "0 e ceil(x)]") assert julia_code(A) == expected # row and columns assert julia_code(A[:,0]) == "[1, 0, 0]" assert julia_code(A[0,:]) == "[1 sin(x/2) abs(x)]" # empty matrices assert julia_code(Matrix(0, 0, [])) == 'zeros(0, 0)' assert julia_code(Matrix(0, 3, [])) == 'zeros(0, 3)' # annoying to read but correct assert julia_code(Matrix([[x, x - y, -y]])) == "[x x - y -y]" def test_vector_entries_hadamard(): # For a row or column, user might to use the other dimension A = Matrix([[1, sin(2/x), 3*pi/x/5]]) assert julia_code(A) == "[1 sin(2./x) 3*pi./(5*x)]" assert julia_code(A.T) == "[1, sin(2./x), 3*pi./(5*x)]" @XFAIL def test_Matrices_entries_not_hadamard(): # For Matrix with col >= 2, row >= 2, they need to be scalars # FIXME: is it worth worrying about this? Its not wrong, just # leave it user's responsibility to put scalar data for x. A = Matrix([[1, sin(2/x), 3*pi/x/5], [1, 2, x*y]]) expected = ("[1 sin(2/x) 3*pi/(5*x);\n" "1 2 x*y]") # <- we give x.*y assert julia_code(A) == expected def test_MatrixSymbol(): n = Symbol('n', integer=True) A = MatrixSymbol('A', n, n) B = MatrixSymbol('B', n, n) assert julia_code(A*B) == "A*B" assert julia_code(B*A) == "B*A" assert julia_code(2*A*B) == "2*A*B" assert julia_code(B*2*A) == "2*B*A" assert julia_code(A*(B + 3*Identity(n))) == "A*(3*eye(n) + B)" assert julia_code(A**(x**2)) == "A^(x.^2)" assert julia_code(A**3) == "A^3" assert julia_code(A**S.Half) == "A^(1/2)" def test_special_matrices(): assert julia_code(6*Identity(3)) == "6*eye(3)" def test_containers(): assert julia_code([1, 2, 3, [4, 5, [6, 7]], 8, [9, 10], 11]) == \ "Any[1, 2, 3, Any[4, 5, Any[6, 7]], 8, Any[9, 10], 11]" assert julia_code((1, 2, (3, 4))) == "(1, 2, (3, 4))" assert julia_code([1]) == "Any[1]" assert julia_code((1,)) == "(1,)" assert julia_code(Tuple(*[1, 2, 3])) == "(1, 2, 3)" assert julia_code((1, x*y, (3, x**2))) == "(1, x.*y, (3, x.^2))" # scalar, matrix, empty matrix and empty list assert julia_code((1, eye(3), Matrix(0, 0, []), [])) == "(1, [1 0 0;\n0 1 0;\n0 0 1], zeros(0, 0), Any[])" def test_julia_noninline(): source = julia_code((x+y)/Catalan, assign_to='me', inline=False) expected = ( "const Catalan = %s\n" "me = (x + y)/Catalan" ) % Catalan.evalf(17) assert source == expected def test_julia_piecewise(): expr = Piecewise((x, x < 1), (x**2, True)) assert julia_code(expr) == "((x < 1) ? (x) : (x.^2))" assert julia_code(expr, assign_to="r") == ( "r = ((x < 1) ? (x) : (x.^2))") assert julia_code(expr, assign_to="r", inline=False) == ( "if (x < 1)\n" " r = x\n" "else\n" " r = x.^2\n" "end") expr = Piecewise((x**2, x < 1), (x**3, x < 2), (x**4, x < 3), (x**5, True)) expected = ("((x < 1) ? (x.^2) :\n" "(x < 2) ? (x.^3) :\n" "(x < 3) ? (x.^4) : (x.^5))") assert julia_code(expr) == expected assert julia_code(expr, assign_to="r") == "r = " + expected assert julia_code(expr, assign_to="r", inline=False) == ( "if (x < 1)\n" " r = x.^2\n" "elseif (x < 2)\n" " r = x.^3\n" "elseif (x < 3)\n" " r = x.^4\n" "else\n" " r = x.^5\n" "end") # Check that Piecewise without a True (default) condition error expr = Piecewise((x, x < 1), (x**2, x > 1), (sin(x), x > 0)) raises(ValueError, lambda: julia_code(expr)) def test_julia_piecewise_times_const(): pw = Piecewise((x, x < 1), (x**2, True)) assert julia_code(2*pw) == "2*((x < 1) ? (x) : (x.^2))" assert julia_code(pw/x) == "((x < 1) ? (x) : (x.^2))./x" assert julia_code(pw/(x*y)) == "((x < 1) ? (x) : (x.^2))./(x.*y)" assert julia_code(pw/3) == "((x < 1) ? (x) : (x.^2))/3" def test_julia_matrix_assign_to(): A = Matrix([[1, 2, 3]]) assert julia_code(A, assign_to='a') == "a = [1 2 3]" A = Matrix([[1, 2], [3, 4]]) assert julia_code(A, assign_to='A') == "A = [1 2;\n3 4]" def test_julia_matrix_assign_to_more(): # assigning to Symbol or MatrixSymbol requires lhs/rhs match A = Matrix([[1, 2, 3]]) B = MatrixSymbol('B', 1, 3) C = MatrixSymbol('C', 2, 3) assert julia_code(A, assign_to=B) == "B = [1 2 3]" raises(ValueError, lambda: julia_code(A, assign_to=x)) raises(ValueError, lambda: julia_code(A, assign_to=C)) def test_julia_matrix_1x1(): A = Matrix([[3]]) B = MatrixSymbol('B', 1, 1) C = MatrixSymbol('C', 1, 2) assert julia_code(A, assign_to=B) == "B = [3]" # FIXME? #assert julia_code(A, assign_to=x) == "x = [3]" raises(ValueError, lambda: julia_code(A, assign_to=C)) def test_julia_matrix_elements(): A = Matrix([[x, 2, x*y]]) assert julia_code(A[0, 0]**2 + A[0, 1] + A[0, 2]) == "x.^2 + x.*y + 2" A = MatrixSymbol('AA', 1, 3) assert julia_code(A) == "AA" assert julia_code(A[0, 0]**2 + sin(A[0,1]) + A[0,2]) == \ "sin(AA[1,2]) + AA[1,1].^2 + AA[1,3]" assert julia_code(sum(A)) == "AA[1,1] + AA[1,2] + AA[1,3]" def test_julia_boolean(): assert julia_code(True) == "true" assert julia_code(S.true) == "true" assert julia_code(False) == "false" assert julia_code(S.false) == "false" def test_julia_not_supported(): assert julia_code(S.ComplexInfinity) == ( "# Not supported in Julia:\n" "# ComplexInfinity\n" "zoo" ) f = Function('f') assert julia_code(f(x).diff(x)) == ( "# Not supported in Julia:\n" "# Derivative\n" "Derivative(f(x), x)" ) def test_trick_indent_with_end_else_words(): # words starting with "end" or "else" do not confuse the indenter t1 = S('endless'); t2 = S('elsewhere'); pw = Piecewise((t1, x < 0), (t2, x <= 1), (1, True)) assert julia_code(pw, inline=False) == ( "if (x < 0)\n" " endless\n" "elseif (x <= 1)\n" " elsewhere\n" "else\n" " 1\n" "end") def test_haramard(): A = MatrixSymbol('A', 3, 3) B = MatrixSymbol('B', 3, 3) v = MatrixSymbol('v', 3, 1) h = MatrixSymbol('h', 1, 3) C = HadamardProduct(A, B) assert julia_code(C) == "A.*B" assert julia_code(C*v) == "(A.*B)*v" assert julia_code(h*C*v) == "h*(A.*B)*v" assert julia_code(C*A) == "(A.*B)*A" # mixing Hadamard and scalar strange b/c we vectorize scalars assert julia_code(C*x*y) == "(x.*y)*(A.*B)" def test_sparse(): M = SparseMatrix(5, 6, {}) M[2, 2] = 10; M[1, 2] = 20; M[1, 3] = 22; M[0, 3] = 30; M[3, 0] = x*y; assert julia_code(M) == ( "sparse([4, 2, 3, 1, 2], [1, 3, 3, 4, 4], [x.*y, 20, 10, 30, 22], 5, 6)" ) def test_specfun(): n = Symbol('n') for f in [besselj, bessely, besseli, besselk]: assert julia_code(f(n, x)) == f.__name__ + '(n, x)' for f in [airyai, airyaiprime, airybi, airybiprime]: assert julia_code(f(x)) == f.__name__ + '(x)' assert julia_code(hankel1(n, x)) == 'hankelh1(n, x)' assert julia_code(hankel2(n, x)) == 'hankelh2(n, x)' assert julia_code(jn(n, x)) == 'sqrt(2)*sqrt(pi)*sqrt(1./x).*besselj(n + 1/2, x)/2' assert julia_code(yn(n, x)) == 'sqrt(2)*sqrt(pi)*sqrt(1./x).*bessely(n + 1/2, x)/2' def test_MatrixElement_printing(): # test cases for issue #11821 A = MatrixSymbol("A", 1, 3) B = MatrixSymbol("B", 1, 3) C = MatrixSymbol("C", 1, 3) assert(julia_code(A[0, 0]) == "A[1,1]") assert(julia_code(3 * A[0, 0]) == "3*A[1,1]") F = C[0, 0].subs(C, A - B) assert(julia_code(F) == "(A - B)[1,1]")
d8738a7f7601e75892ad51672cbf56dc48298502d22dd2e4a0e9bd6d63a7a7c7
from sympy.core import (S, pi, oo, Symbol, symbols, Rational, Integer, GoldenRatio, EulerGamma, Catalan, Lambda, Dummy, Eq) from sympy.functions import (Piecewise, sin, cos, Abs, exp, ceiling, sqrt, gamma, sign, Max, Min, factorial, beta) from sympy.sets import Range from sympy.logic import ITE from sympy.codegen import For, aug_assign, Assignment from sympy.testing.pytest import raises from sympy.printing.rcode import RCodePrinter from sympy.utilities.lambdify import implemented_function from sympy.tensor import IndexedBase, Idx from sympy.matrices import Matrix, MatrixSymbol from sympy import rcode x, y, z = symbols('x,y,z') def test_printmethod(): class fabs(Abs): def _rcode(self, printer): return "abs(%s)" % printer._print(self.args[0]) assert rcode(fabs(x)) == "abs(x)" def test_rcode_sqrt(): assert rcode(sqrt(x)) == "sqrt(x)" assert rcode(x**0.5) == "sqrt(x)" assert rcode(sqrt(x)) == "sqrt(x)" def test_rcode_Pow(): assert rcode(x**3) == "x^3" assert rcode(x**(y**3)) == "x^(y^3)" g = implemented_function('g', Lambda(x, 2*x)) assert rcode(1/(g(x)*3.5)**(x - y**x)/(x**2 + y)) == \ "(3.5*2*x)^(-x + y^x)/(x^2 + y)" assert rcode(x**-1.0) == '1.0/x' assert rcode(x**Rational(2, 3)) == 'x^(2.0/3.0)' _cond_cfunc = [(lambda base, exp: exp.is_integer, "dpowi"), (lambda base, exp: not exp.is_integer, "pow")] assert rcode(x**3, user_functions={'Pow': _cond_cfunc}) == 'dpowi(x, 3)' assert rcode(x**3.2, user_functions={'Pow': _cond_cfunc}) == 'pow(x, 3.2)' def test_rcode_Max(): # Test for gh-11926 assert rcode(Max(x,x*x),user_functions={"Max":"my_max", "Pow":"my_pow"}) == 'my_max(x, my_pow(x, 2))' def test_rcode_constants_mathh(): assert rcode(exp(1)) == "exp(1)" assert rcode(pi) == "pi" assert rcode(oo) == "Inf" assert rcode(-oo) == "-Inf" def test_rcode_constants_other(): assert rcode(2*GoldenRatio) == "GoldenRatio = 1.61803398874989;\n2*GoldenRatio" assert rcode( 2*Catalan) == "Catalan = 0.915965594177219;\n2*Catalan" assert rcode(2*EulerGamma) == "EulerGamma = 0.577215664901533;\n2*EulerGamma" def test_rcode_Rational(): assert rcode(Rational(3, 7)) == "3.0/7.0" assert rcode(Rational(18, 9)) == "2" assert rcode(Rational(3, -7)) == "-3.0/7.0" assert rcode(Rational(-3, -7)) == "3.0/7.0" assert rcode(x + Rational(3, 7)) == "x + 3.0/7.0" assert rcode(Rational(3, 7)*x) == "(3.0/7.0)*x" def test_rcode_Integer(): assert rcode(Integer(67)) == "67" assert rcode(Integer(-1)) == "-1" def test_rcode_functions(): assert rcode(sin(x) ** cos(x)) == "sin(x)^cos(x)" assert rcode(factorial(x) + gamma(y)) == "factorial(x) + gamma(y)" assert rcode(beta(Min(x, y), Max(x, y))) == "beta(min(x, y), max(x, y))" def test_rcode_inline_function(): x = symbols('x') g = implemented_function('g', Lambda(x, 2*x)) assert rcode(g(x)) == "2*x" g = implemented_function('g', Lambda(x, 2*x/Catalan)) assert rcode( g(x)) == "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))) res=rcode(g(A[i]), assign_to=A[i]) ref=( "for (i in 1:n){\n" " A[i] = (A[i] + 1)*(A[i] + 2)*A[i];\n" "}" ) assert res == ref def test_rcode_exceptions(): assert rcode(ceiling(x)) == "ceiling(x)" assert rcode(Abs(x)) == "abs(x)" assert rcode(gamma(x)) == "gamma(x)" def test_rcode_user_functions(): x = symbols('x', integer=False) n = symbols('n', integer=True) custom_functions = { "ceiling": "myceil", "Abs": [(lambda x: not x.is_integer, "fabs"), (lambda x: x.is_integer, "abs")], } assert rcode(ceiling(x), user_functions=custom_functions) == "myceil(x)" assert rcode(Abs(x), user_functions=custom_functions) == "fabs(x)" assert rcode(Abs(n), user_functions=custom_functions) == "abs(n)" def test_rcode_boolean(): assert rcode(True) == "True" assert rcode(S.true) == "True" assert rcode(False) == "False" assert rcode(S.false) == "False" assert rcode(x & y) == "x & y" assert rcode(x | y) == "x | y" assert rcode(~x) == "!x" assert rcode(x & y & z) == "x & y & z" assert rcode(x | y | z) == "x | y | z" assert rcode((x & y) | z) == "z | x & y" assert rcode((x | y) & z) == "z & (x | y)" def test_rcode_Relational(): from sympy import Eq, Ne, Le, Lt, Gt, Ge assert rcode(Eq(x, y)) == "x == y" assert rcode(Ne(x, y)) == "x != y" assert rcode(Le(x, y)) == "x <= y" assert rcode(Lt(x, y)) == "x < y" assert rcode(Gt(x, y)) == "x > y" assert rcode(Ge(x, y)) == "x >= y" def test_rcode_Piecewise(): expr = Piecewise((x, x < 1), (x**2, True)) res=rcode(expr) ref="ifelse(x < 1,x,x^2)" assert res == ref tau=Symbol("tau") res=rcode(expr,tau) ref="tau = ifelse(x < 1,x,x^2);" assert res == ref expr = 2*Piecewise((x, x < 1), (x**2, x<2), (x**3,True)) assert rcode(expr) == "2*ifelse(x < 1,x,ifelse(x < 2,x^2,x^3))" res = rcode(expr, assign_to='c') assert res == "c = 2*ifelse(x < 1,x,ifelse(x < 2,x^2,x^3));" # Check that Piecewise without a True (default) condition error #expr = Piecewise((x, x < 1), (x**2, x > 1), (sin(x), x > 0)) #raises(ValueError, lambda: rcode(expr)) expr = 2*Piecewise((x, x < 1), (x**2, x<2)) assert(rcode(expr))== "2*ifelse(x < 1,x,ifelse(x < 2,x^2,NA))" def test_rcode_sinc(): from sympy import sinc expr = sinc(x) res = rcode(expr) ref = "ifelse(x != 0,sin(x)/x,1)" assert res == ref def test_rcode_Piecewise_deep(): p = rcode(2*Piecewise((x, x < 1), (x + 1, x < 2), (x**2, True))) assert p == "2*ifelse(x < 1,x,ifelse(x < 2,x + 1,x^2))" expr = x*y*z + x**2 + y**2 + Piecewise((0, x < 0.5), (1, True)) + cos(z) - 1 p = rcode(expr) ref="x^2 + x*y*z + y^2 + ifelse(x < 0.5,0,1) + cos(z) - 1" assert p == ref ref="c = x^2 + x*y*z + y^2 + ifelse(x < 0.5,0,1) + cos(z) - 1;" p = rcode(expr, assign_to='c') assert p == ref def test_rcode_ITE(): expr = ITE(x < 1, y, z) p = rcode(expr) ref="ifelse(x < 1,y,z)" assert p == ref def test_rcode_settings(): raises(TypeError, lambda: rcode(sin(x), method="garbage")) def test_rcode_Indexed(): from sympy.tensor import IndexedBase, Idx from sympy import symbols n, m, o = symbols('n m o', integer=True) i, j, k = Idx('i', n), Idx('j', m), Idx('k', o) p = RCodePrinter() p._not_r = set() x = IndexedBase('x')[j] assert p._print_Indexed(x) == 'x[j]' A = IndexedBase('A')[i, j] assert p._print_Indexed(A) == 'A[i, j]' B = IndexedBase('B')[i, j, k] assert p._print_Indexed(B) == 'B[i, j, k]' assert p._not_r == set() def test_rcode_Indexed_without_looking_for_contraction(): len_y = 5 y = IndexedBase('y', shape=(len_y,)) x = IndexedBase('x', shape=(len_y,)) Dy = IndexedBase('Dy', shape=(len_y-1,)) i = Idx('i', len_y-1) e=Eq(Dy[i], (y[i+1]-y[i])/(x[i+1]-x[i])) code0 = rcode(e.rhs, assign_to=e.lhs, contract=False) assert code0 == 'Dy[i] = (y[%s] - y[i])/(x[%s] - x[i]);' % (i + 1, i + 1) def test_rcode_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 (i in 1:m){\n' ' y[i] = 0;\n' '}\n' 'for (i in 1:m){\n' ' for (j in 1:n){\n' ' y[i] = A[i, j]*x[j] + y[i];\n' ' }\n' '}' ) c = rcode(A[i, j]*x[j], assign_to=y[i]) assert c == s def test_dummy_loops(): # the following line could also be # [Dummy(s, integer=True) for s in 'im'] # or [Dummy(integer=True) for s in 'im'] i, m = symbols('i m', integer=True, cls=Dummy) x = IndexedBase('x') y = IndexedBase('y') i = Idx(i, m) expected = ( 'for (i_%(icount)i in 1:m_%(mcount)i){\n' ' y[i_%(icount)i] = x[i_%(icount)i];\n' '}' ) % {'icount': i.label.dummy_index, 'mcount': m.dummy_index} code = rcode(x[i], assign_to=y[i]) assert code == expected def test_rcode_loops_add(): from sympy.tensor import IndexedBase, Idx from sympy import symbols n, m = symbols('n m', integer=True) A = IndexedBase('A') x = IndexedBase('x') y = IndexedBase('y') z = IndexedBase('z') i = Idx('i', m) j = Idx('j', n) s = ( 'for (i in 1:m){\n' ' y[i] = x[i] + z[i];\n' '}\n' 'for (i in 1:m){\n' ' for (j in 1:n){\n' ' y[i] = A[i, j]*x[j] + y[i];\n' ' }\n' '}' ) c = rcode(A[i, j]*x[j] + x[i] + z[i], assign_to=y[i]) assert c == s def test_rcode_loops_multiple_contractions(): from sympy.tensor import IndexedBase, Idx from sympy 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 (i in 1:m){\n' ' y[i] = 0;\n' '}\n' 'for (i in 1:m){\n' ' for (j in 1:n){\n' ' for (k in 1:o){\n' ' for (l in 1:p){\n' ' y[i] = a[i, j, k, l]*b[j, k, l] + y[i];\n' ' }\n' ' }\n' ' }\n' '}' ) c = rcode(b[j, k, l]*a[i, j, k, l], assign_to=y[i]) assert c == s def test_rcode_loops_addfactor(): from sympy.tensor import IndexedBase, Idx from sympy 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 (i in 1:m){\n' ' y[i] = 0;\n' '}\n' 'for (i in 1:m){\n' ' for (j in 1:n){\n' ' for (k in 1:o){\n' ' for (l in 1:p){\n' ' y[i] = (a[i, j, k, l] + b[i, j, k, l])*c[j, k, l] + y[i];\n' ' }\n' ' }\n' ' }\n' '}' ) c = rcode((a[i, j, k, l] + b[i, j, k, l])*c[j, k, l], assign_to=y[i]) assert c == s def test_rcode_loops_multiple_terms(): from sympy.tensor import IndexedBase, Idx from sympy 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 (i in 1:m){\n' ' y[i] = 0;\n' '}\n' ) s1 = ( 'for (i in 1:m){\n' ' for (j in 1:n){\n' ' for (k in 1:o){\n' ' y[i] = b[j]*b[k]*c[i, j, k] + y[i];\n' ' }\n' ' }\n' '}\n' ) s2 = ( 'for (i in 1:m){\n' ' for (k in 1:o){\n' ' y[i] = a[i, k]*b[k] + y[i];\n' ' }\n' '}\n' ) s3 = ( 'for (i in 1:m){\n' ' for (j in 1:n){\n' ' y[i] = a[i, j]*b[j] + y[i];\n' ' }\n' '}\n' ) c = rcode( b[j]*a[i, j] + b[k]*a[i, k] + b[j]*b[k]*c[i, j, k], assign_to=y[i]) ref=dict() ref[0] = s0 + s1 + s2 + s3[:-1] ref[1] = s0 + s1 + s3 + s2[:-1] ref[2] = s0 + s2 + s1 + s3[:-1] ref[3] = s0 + s2 + s3 + s1[:-1] ref[4] = s0 + s3 + s1 + s2[:-1] ref[5] = s0 + s3 + s2 + s1[:-1] assert (c == ref[0] or c == ref[1] or c == ref[2] or c == ref[3] or c == ref[4] or c == ref[5]) def test_dereference_printing(): expr = x + y + sin(z) + z assert rcode(expr, dereference=[z]) == "x + y + (*z) + sin((*z))" def test_Matrix_printing(): # Test returning a Matrix mat = Matrix([x*y, Piecewise((2 + x, y>0), (y, True)), sin(z)]) A = MatrixSymbol('A', 3, 1) p = rcode(mat, A) assert p == ( "A[0] = x*y;\n" "A[1] = ifelse(y > 0,x + 2,y);\n" "A[2] = sin(z);") # Test using MatrixElements in expressions expr = Piecewise((2*A[2, 0], x > 0), (A[2, 0], True)) + sin(A[1, 0]) + A[0, 0] p = rcode(expr) assert p == ("ifelse(x > 0,2*A[2],A[2]) + sin(A[1]) + A[0]") # Test using MatrixElements in a Matrix q = MatrixSymbol('q', 5, 1) M = MatrixSymbol('M', 3, 3) m = Matrix([[sin(q[1,0]), 0, cos(q[2,0])], [q[1,0] + q[2,0], q[3, 0], 5], [2*q[4, 0]/q[1,0], sqrt(q[0,0]) + 4, 0]]) assert rcode(m, M) == ( "M[0] = sin(q[1]);\n" "M[1] = 0;\n" "M[2] = cos(q[2]);\n" "M[3] = q[1] + q[2];\n" "M[4] = q[3];\n" "M[5] = 5;\n" "M[6] = 2*q[4]/q[1];\n" "M[7] = sqrt(q[0]) + 4;\n" "M[8] = 0;") def test_rcode_sgn(): expr = sign(x) * y assert rcode(expr) == 'y*sign(x)' p = rcode(expr, 'z') assert p == 'z = y*sign(x);' p = rcode(sign(2 * x + x**2) * x + x**2) assert p == "x^2 + x*sign(x^2 + 2*x)" expr = sign(cos(x)) p = rcode(expr) assert p == 'sign(cos(x))' def test_rcode_Assignment(): assert rcode(Assignment(x, y + z)) == 'x = y + z;' assert rcode(aug_assign(x, '+', y + z)) == 'x += y + z;' def test_rcode_For(): f = For(x, Range(0, 10, 2), [aug_assign(y, '*', x)]) sol = rcode(f) assert sol == ("for (x = 0; x < 10; x += 2) {\n" " y *= x;\n" "}") def test_MatrixElement_printing(): # test cases for issue #11821 A = MatrixSymbol("A", 1, 3) B = MatrixSymbol("B", 1, 3) C = MatrixSymbol("C", 1, 3) assert(rcode(A[0, 0]) == "A[0]") assert(rcode(3 * A[0, 0]) == "3*A[0]") F = C[0, 0].subs(C, A - B) assert(rcode(F) == "(A - B)[0]")
1d354f9ca3e2543056596087d04e2a60433f5867fe8d6b56b44ad79860db6a31
from sympy.printing.tree import tree from sympy.testing.pytest import XFAIL # Remove this flag after making _assumptions cache deterministic. @XFAIL def test_print_tree_MatAdd(): from sympy.matrices.expressions import MatrixSymbol A = MatrixSymbol('A', 3, 3) B = MatrixSymbol('B', 3, 3) test_str = [ 'MatAdd: A + B\n', 'algebraic: False\n', 'commutative: False\n', 'complex: False\n', 'composite: False\n', 'even: False\n', 'extended_negative: False\n', 'extended_nonnegative: False\n', 'extended_nonpositive: False\n', 'extended_nonzero: False\n', 'extended_positive: False\n', 'extended_real: False\n', 'imaginary: False\n', 'integer: False\n', 'irrational: False\n', 'negative: False\n', 'noninteger: False\n', 'nonnegative: False\n', 'nonpositive: False\n', 'nonzero: False\n', 'odd: False\n', 'positive: False\n', 'prime: False\n', 'rational: False\n', 'real: False\n', 'transcendental: False\n', 'zero: False\n', '+-MatrixSymbol: A\n', '| algebraic: False\n', '| commutative: False\n', '| complex: False\n', '| composite: False\n', '| even: False\n', '| extended_negative: False\n', '| extended_nonnegative: False\n', '| extended_nonpositive: False\n', '| extended_nonzero: False\n', '| extended_positive: False\n', '| extended_real: False\n', '| imaginary: False\n', '| integer: False\n', '| irrational: False\n', '| negative: False\n', '| noninteger: False\n', '| nonnegative: False\n', '| nonpositive: False\n', '| nonzero: False\n', '| odd: False\n', '| positive: False\n', '| prime: False\n', '| rational: False\n', '| real: False\n', '| transcendental: False\n', '| zero: False\n', '| +-Symbol: A\n', '| | commutative: True\n', '| +-Integer: 3\n', '| | algebraic: True\n', '| | commutative: True\n', '| | complex: True\n', '| | extended_negative: False\n', '| | extended_nonnegative: True\n', '| | extended_real: True\n', '| | finite: True\n', '| | hermitian: True\n', '| | imaginary: False\n', '| | infinite: False\n', '| | integer: True\n', '| | irrational: False\n', '| | negative: False\n', '| | noninteger: False\n', '| | nonnegative: True\n', '| | rational: True\n', '| | real: True\n', '| | transcendental: False\n', '| +-Integer: 3\n', '| algebraic: True\n', '| commutative: True\n', '| complex: True\n', '| extended_negative: False\n', '| extended_nonnegative: True\n', '| extended_real: True\n', '| finite: True\n', '| hermitian: True\n', '| imaginary: False\n', '| infinite: False\n', '| integer: True\n', '| irrational: False\n', '| negative: False\n', '| noninteger: False\n', '| nonnegative: True\n', '| rational: True\n', '| real: True\n', '| transcendental: False\n', '+-MatrixSymbol: B\n', ' algebraic: False\n', ' commutative: False\n', ' complex: False\n', ' composite: False\n', ' even: False\n', ' extended_negative: False\n', ' extended_nonnegative: False\n', ' extended_nonpositive: False\n', ' extended_nonzero: False\n', ' extended_positive: False\n', ' extended_real: False\n', ' imaginary: False\n', ' integer: False\n', ' irrational: False\n', ' negative: False\n', ' noninteger: False\n', ' nonnegative: False\n', ' nonpositive: False\n', ' nonzero: False\n', ' odd: False\n', ' positive: False\n', ' prime: False\n', ' rational: False\n', ' real: False\n', ' transcendental: False\n', ' zero: False\n', ' +-Symbol: B\n', ' | commutative: True\n', ' +-Integer: 3\n', ' | algebraic: True\n', ' | commutative: True\n', ' | complex: True\n', ' | extended_negative: False\n', ' | extended_nonnegative: True\n', ' | extended_real: True\n', ' | finite: True\n', ' | hermitian: True\n', ' | imaginary: False\n', ' | infinite: False\n', ' | integer: True\n', ' | irrational: False\n', ' | negative: False\n', ' | noninteger: False\n', ' | nonnegative: True\n', ' | rational: True\n', ' | real: True\n', ' | transcendental: False\n', ' +-Integer: 3\n', ' algebraic: True\n', ' commutative: True\n', ' complex: True\n', ' extended_negative: False\n', ' extended_nonnegative: True\n', ' extended_real: True\n', ' finite: True\n', ' hermitian: True\n', ' imaginary: False\n', ' infinite: False\n', ' integer: True\n', ' irrational: False\n', ' negative: False\n', ' noninteger: False\n', ' nonnegative: True\n', ' rational: True\n', ' real: True\n', ' transcendental: False\n' ] assert tree(A + B) == "".join(test_str) def test_print_tree_MatAdd_noassumptions(): from sympy.matrices.expressions import MatrixSymbol A = MatrixSymbol('A', 3, 3) B = MatrixSymbol('B', 3, 3) test_str = \ """MatAdd: A + B +-MatrixSymbol: A | +-Symbol: A | +-Integer: 3 | +-Integer: 3 +-MatrixSymbol: B +-Symbol: B +-Integer: 3 +-Integer: 3 """ assert tree(A + B, assumptions=False) == test_str
5e9346c876fe695c9a1e9a669e531461711e29f42406d80fc55652b8e013218b
from sympy import (Symbol, symbols, oo, limit, Rational, Integral, Derivative, log, exp, sqrt, pi, Function, sin, Eq, Ge, Le, Gt, Lt, Ne, Abs, conjugate, I, Matrix) from sympy.printing.python import python from sympy.testing.pytest import raises, XFAIL x, y = symbols('x,y') th = Symbol('theta') ph = Symbol('phi') def test_python_basic(): # Simple numbers/symbols assert python(-Rational(1)/2) == "e = Rational(-1, 2)" assert python(-Rational(13)/22) == "e = Rational(-13, 22)" assert python(oo) == "e = oo" # Powers assert python((x**2)) == "x = Symbol(\'x\')\ne = x**2" assert python(1/x) == "x = Symbol('x')\ne = 1/x" assert python(y*x**-2) == "y = Symbol('y')\nx = Symbol('x')\ne = y/x**2" assert python( x**Rational(-5, 2)) == "x = Symbol('x')\ne = x**Rational(-5, 2)" # Sums of terms assert python((x**2 + x + 1)) in [ "x = Symbol('x')\ne = 1 + x + x**2", "x = Symbol('x')\ne = x + x**2 + 1", "x = Symbol('x')\ne = x**2 + x + 1", ] assert python(1 - x) in [ "x = Symbol('x')\ne = 1 - x", "x = Symbol('x')\ne = -x + 1"] assert python(1 - 2*x) in [ "x = Symbol('x')\ne = 1 - 2*x", "x = Symbol('x')\ne = -2*x + 1"] assert python(1 - Rational(3, 2)*y/x) in [ "y = Symbol('y')\nx = Symbol('x')\ne = 1 - 3/2*y/x", "y = Symbol('y')\nx = Symbol('x')\ne = -3/2*y/x + 1", "y = Symbol('y')\nx = Symbol('x')\ne = 1 - 3*y/(2*x)"] # Multiplication assert python(x/y) == "x = Symbol('x')\ny = Symbol('y')\ne = x/y" assert python(-x/y) == "x = Symbol('x')\ny = Symbol('y')\ne = -x/y" assert python((x + 2)/y) in [ "y = Symbol('y')\nx = Symbol('x')\ne = 1/y*(2 + x)", "y = Symbol('y')\nx = Symbol('x')\ne = 1/y*(x + 2)", "x = Symbol('x')\ny = Symbol('y')\ne = 1/y*(2 + x)", "x = Symbol('x')\ny = Symbol('y')\ne = (2 + x)/y", "x = Symbol('x')\ny = Symbol('y')\ne = (x + 2)/y"] assert python((1 + x)*y) in [ "y = Symbol('y')\nx = Symbol('x')\ne = y*(1 + x)", "y = Symbol('y')\nx = Symbol('x')\ne = y*(x + 1)", ] # Check for proper placement of negative sign assert python(-5*x/(x + 10)) == "x = Symbol('x')\ne = -5*x/(x + 10)" assert python(1 - Rational(3, 2)*(x + 1)) in [ "x = Symbol('x')\ne = Rational(-3, 2)*x + Rational(-1, 2)", "x = Symbol('x')\ne = -3*x/2 + Rational(-1, 2)", "x = Symbol('x')\ne = -3*x/2 + Rational(-1, 2)" ] def test_python_keyword_symbol_name_escaping(): # Check for escaping of keywords assert python( 5*Symbol("lambda")) == "lambda_ = Symbol('lambda')\ne = 5*lambda_" assert (python(5*Symbol("lambda") + 7*Symbol("lambda_")) == "lambda__ = Symbol('lambda')\nlambda_ = Symbol('lambda_')\ne = 7*lambda_ + 5*lambda__") assert (python(5*Symbol("for") + Function("for_")(8)) == "for__ = Symbol('for')\nfor_ = Function('for_')\ne = 5*for__ + for_(8)") def test_python_keyword_function_name_escaping(): assert python( 5*Function("for")(8)) == "for_ = Function('for')\ne = 5*for_(8)" def test_python_relational(): assert python(Eq(x, y)) == "x = Symbol('x')\ny = Symbol('y')\ne = Eq(x, y)" assert python(Ge(x, y)) == "x = Symbol('x')\ny = Symbol('y')\ne = x >= y" assert python(Le(x, y)) == "x = Symbol('x')\ny = Symbol('y')\ne = x <= y" assert python(Gt(x, y)) == "x = Symbol('x')\ny = Symbol('y')\ne = x > y" assert python(Lt(x, y)) == "x = Symbol('x')\ny = Symbol('y')\ne = x < y" assert python(Ne(x/(y + 1), y**2)) in [ "x = Symbol('x')\ny = Symbol('y')\ne = Ne(x/(1 + y), y**2)", "x = Symbol('x')\ny = Symbol('y')\ne = Ne(x/(y + 1), y**2)"] def test_python_functions(): # Simple assert python((2*x + exp(x))) in "x = Symbol('x')\ne = 2*x + exp(x)" assert python(sqrt(2)) == 'e = sqrt(2)' assert python(2**Rational(1, 3)) == 'e = 2**Rational(1, 3)' assert python(sqrt(2 + pi)) == 'e = sqrt(2 + pi)' assert python((2 + pi)**Rational(1, 3)) == 'e = (2 + pi)**Rational(1, 3)' assert python(2**Rational(1, 4)) == 'e = 2**Rational(1, 4)' assert python(Abs(x)) == "x = Symbol('x')\ne = Abs(x)" assert python( Abs(x/(x**2 + 1))) in ["x = Symbol('x')\ne = Abs(x/(1 + x**2))", "x = Symbol('x')\ne = Abs(x/(x**2 + 1))"] # Univariate/Multivariate functions f = Function('f') assert python(f(x)) == "x = Symbol('x')\nf = Function('f')\ne = f(x)" assert python(f(x, y)) == "x = Symbol('x')\ny = Symbol('y')\nf = Function('f')\ne = f(x, y)" assert python(f(x/(y + 1), y)) in [ "x = Symbol('x')\ny = Symbol('y')\nf = Function('f')\ne = f(x/(1 + y), y)", "x = Symbol('x')\ny = Symbol('y')\nf = Function('f')\ne = f(x/(y + 1), y)"] # Nesting of square roots assert python(sqrt((sqrt(x + 1)) + 1)) in [ "x = Symbol('x')\ne = sqrt(1 + sqrt(1 + x))", "x = Symbol('x')\ne = sqrt(sqrt(x + 1) + 1)"] # Nesting of powers assert python((((x + 1)**Rational(1, 3)) + 1)**Rational(1, 3)) in [ "x = Symbol('x')\ne = (1 + (1 + x)**Rational(1, 3))**Rational(1, 3)", "x = Symbol('x')\ne = ((x + 1)**Rational(1, 3) + 1)**Rational(1, 3)"] # Function powers assert python(sin(x)**2) == "x = Symbol('x')\ne = sin(x)**2" @XFAIL def test_python_functions_conjugates(): a, b = map(Symbol, 'ab') assert python( conjugate(a + b*I) ) == '_ _\na - I*b' assert python( conjugate(exp(a + b*I)) ) == ' _ _\n a - I*b\ne ' def test_python_derivatives(): # Simple f_1 = Derivative(log(x), x, evaluate=False) assert python(f_1) == "x = Symbol('x')\ne = Derivative(log(x), x)" f_2 = Derivative(log(x), x, evaluate=False) + x assert python(f_2) == "x = Symbol('x')\ne = x + Derivative(log(x), x)" # Multiple symbols f_3 = Derivative(log(x) + x**2, x, y, evaluate=False) assert python(f_3) == \ "x = Symbol('x')\ny = Symbol('y')\ne = Derivative(x**2 + log(x), x, y)" f_4 = Derivative(2*x*y, y, x, evaluate=False) + x**2 assert python(f_4) in [ "x = Symbol('x')\ny = Symbol('y')\ne = x**2 + Derivative(2*x*y, y, x)", "x = Symbol('x')\ny = Symbol('y')\ne = Derivative(2*x*y, y, x) + x**2"] def test_python_integrals(): # Simple f_1 = Integral(log(x), x) assert python(f_1) == "x = Symbol('x')\ne = Integral(log(x), x)" f_2 = Integral(x**2, x) assert python(f_2) == "x = Symbol('x')\ne = Integral(x**2, x)" # Double nesting of pow f_3 = Integral(x**(2**x), x) assert python(f_3) == "x = Symbol('x')\ne = Integral(x**(2**x), x)" # Definite integrals f_4 = Integral(x**2, (x, 1, 2)) assert python(f_4) == "x = Symbol('x')\ne = Integral(x**2, (x, 1, 2))" f_5 = Integral(x**2, (x, Rational(1, 2), 10)) assert python( f_5) == "x = Symbol('x')\ne = Integral(x**2, (x, Rational(1, 2), 10))" # Nested integrals f_6 = Integral(x**2*y**2, x, y) assert python(f_6) == "x = Symbol('x')\ny = Symbol('y')\ne = Integral(x**2*y**2, x, y)" def test_python_matrix(): p = python(Matrix([[x**2+1, 1], [y, x+y]])) s = "x = Symbol('x')\ny = Symbol('y')\ne = MutableDenseMatrix([[x**2 + 1, 1], [y, x + y]])" assert p == s def test_python_limits(): assert python(limit(x, x, oo)) == 'e = oo' assert python(limit(x**2, x, 0)) == 'e = 0' def test_settings(): raises(TypeError, lambda: python(x, method="garbage"))
652cccced7a0f7da209800b9e06153df0d942c28f559c45d6afa8aafaf53d73f
from sympy import TableForm, S from sympy.printing.latex import latex from sympy.abc import x from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import sin from sympy.testing.pytest import raises from textwrap import dedent def test_TableForm(): s = str(TableForm([["a", "b"], ["c", "d"], ["e", 0]], headings="automatic")) assert s == ( ' | 1 2\n' '-------\n' '1 | a b\n' '2 | c d\n' '3 | e ' ) s = str(TableForm([["a", "b"], ["c", "d"], ["e", 0]], headings="automatic", wipe_zeros=False)) assert s == dedent('''\ | 1 2 ------- 1 | a b 2 | c d 3 | e 0''') s = str(TableForm([[x**2, "b"], ["c", x**2], ["e", "f"]], headings=("automatic", None))) assert s == ( '1 | x**2 b \n' '2 | c x**2\n' '3 | e f ' ) s = str(TableForm([["a", "b"], ["c", "d"], ["e", "f"]], headings=(None, "automatic"))) assert s == dedent('''\ 1 2 --- a b c d e f''') s = str(TableForm([[5, 7], [4, 2], [10, 3]], headings=[["Group A", "Group B", "Group C"], ["y1", "y2"]])) assert s == ( ' | y1 y2\n' '---------------\n' 'Group A | 5 7 \n' 'Group B | 4 2 \n' 'Group C | 10 3 ' ) raises( ValueError, lambda: TableForm( [[5, 7], [4, 2], [10, 3]], headings=[["Group A", "Group B", "Group C"], ["y1", "y2"]], alignments="middle") ) s = str(TableForm([[5, 7], [4, 2], [10, 3]], headings=[["Group A", "Group B", "Group C"], ["y1", "y2"]], alignments="right")) assert s == dedent('''\ | y1 y2 --------------- Group A | 5 7 Group B | 4 2 Group C | 10 3''') # other alignment permutations d = [[1, 100], [100, 1]] s = TableForm(d, headings=(('xxx', 'x'), None), alignments='l') assert str(s) == ( 'xxx | 1 100\n' ' x | 100 1 ' ) s = TableForm(d, headings=(('xxx', 'x'), None), alignments='lr') assert str(s) == dedent('''\ xxx | 1 100 x | 100 1''') s = TableForm(d, headings=(('xxx', 'x'), None), alignments='clr') assert str(s) == dedent('''\ xxx | 1 100 x | 100 1''') s = TableForm(d, headings=(('xxx', 'x'), None)) assert str(s) == ( 'xxx | 1 100\n' ' x | 100 1 ' ) raises(ValueError, lambda: TableForm(d, alignments='clr')) #pad s = str(TableForm([[None, "-", 2], [1]], pad='?')) assert s == dedent('''\ ? - 2 1 ? ?''') def test_TableForm_latex(): s = latex(TableForm([[0, x**3], ["c", S.One/4], [sqrt(x), sin(x**2)]], wipe_zeros=True, headings=("automatic", "automatic"))) assert s == ( '\\begin{tabular}{r l l}\n' ' & 1 & 2 \\\\\n' '\\hline\n' '1 & & $x^{3}$ \\\\\n' '2 & $c$ & $\\frac{1}{4}$ \\\\\n' '3 & $\\sqrt{x}$ & $\\sin{\\left(x^{2} \\right)}$ \\\\\n' '\\end{tabular}' ) s = latex(TableForm([[0, x**3], ["c", S.One/4], [sqrt(x), sin(x**2)]], wipe_zeros=True, headings=("automatic", "automatic"), alignments='l')) assert s == ( '\\begin{tabular}{r l l}\n' ' & 1 & 2 \\\\\n' '\\hline\n' '1 & & $x^{3}$ \\\\\n' '2 & $c$ & $\\frac{1}{4}$ \\\\\n' '3 & $\\sqrt{x}$ & $\\sin{\\left(x^{2} \\right)}$ \\\\\n' '\\end{tabular}' ) s = latex(TableForm([[0, x**3], ["c", S.One/4], [sqrt(x), sin(x**2)]], wipe_zeros=True, headings=("automatic", "automatic"), alignments='l'*3)) assert s == ( '\\begin{tabular}{l l l}\n' ' & 1 & 2 \\\\\n' '\\hline\n' '1 & & $x^{3}$ \\\\\n' '2 & $c$ & $\\frac{1}{4}$ \\\\\n' '3 & $\\sqrt{x}$ & $\\sin{\\left(x^{2} \\right)}$ \\\\\n' '\\end{tabular}' ) s = latex(TableForm([["a", x**3], ["c", S.One/4], [sqrt(x), sin(x**2)]], headings=("automatic", "automatic"))) assert s == ( '\\begin{tabular}{r l l}\n' ' & 1 & 2 \\\\\n' '\\hline\n' '1 & $a$ & $x^{3}$ \\\\\n' '2 & $c$ & $\\frac{1}{4}$ \\\\\n' '3 & $\\sqrt{x}$ & $\\sin{\\left(x^{2} \\right)}$ \\\\\n' '\\end{tabular}' ) s = latex(TableForm([["a", x**3], ["c", S.One/4], [sqrt(x), sin(x**2)]], formats=['(%s)', None], headings=("automatic", "automatic"))) assert s == ( '\\begin{tabular}{r l l}\n' ' & 1 & 2 \\\\\n' '\\hline\n' '1 & (a) & $x^{3}$ \\\\\n' '2 & (c) & $\\frac{1}{4}$ \\\\\n' '3 & (sqrt(x)) & $\\sin{\\left(x^{2} \\right)}$ \\\\\n' '\\end{tabular}' ) def neg_in_paren(x, i, j): if i % 2: return ('(%s)' if x < 0 else '%s') % x else: pass # use default print s = latex(TableForm([[-1, 2], [-3, 4]], formats=[neg_in_paren]*2, headings=("automatic", "automatic"))) assert s == ( '\\begin{tabular}{r l l}\n' ' & 1 & 2 \\\\\n' '\\hline\n' '1 & -1 & 2 \\\\\n' '2 & (-3) & 4 \\\\\n' '\\end{tabular}' ) s = latex(TableForm([["a", x**3], ["c", S.One/4], [sqrt(x), sin(x**2)]])) assert s == ( '\\begin{tabular}{l l}\n' '$a$ & $x^{3}$ \\\\\n' '$c$ & $\\frac{1}{4}$ \\\\\n' '$\\sqrt{x}$ & $\\sin{\\left(x^{2} \\right)}$ \\\\\n' '\\end{tabular}' )
b9e8b08f1a1e531b4bc4ed2d1c8dae7ab59994ff30b2a52c0454a4c503c4bae9
from sympy import diff, Integral, Limit, sin, Symbol, Integer, Rational, cos, \ tan, asin, acos, atan, sinh, cosh, tanh, asinh, acosh, atanh, E, I, oo, \ pi, GoldenRatio, EulerGamma, Sum, Eq, Ne, Ge, Lt, Float, Matrix, Basic, \ S, MatrixSymbol, Function, Derivative, log, true, false, Range, Min, Max, \ Lambda, IndexedBase, symbols, zoo, elliptic_f, elliptic_e, elliptic_pi, Ei, \ expint, jacobi, gegenbauer, chebyshevt, chebyshevu, legendre, assoc_legendre, \ laguerre, assoc_laguerre, hermite, euler, stieltjes, mathieuc, mathieus, \ mathieucprime, mathieusprime, TribonacciConstant, Contains, LambertW, \ cot, coth, acot, acoth, csc, acsc, csch, acsch, sec, asec, sech, asech from sympy import elliptic_k, totient, reduced_totient, primenu, primeomega, \ fresnelc, fresnels, Heaviside from sympy.calculus.util import AccumBounds from sympy.core.containers import Tuple from sympy.functions.combinatorial.factorials import factorial, factorial2, \ binomial from sympy.functions.combinatorial.numbers import bernoulli, bell, lucas, \ fibonacci, tribonacci, catalan from sympy.functions.elementary.complexes import re, im, Abs, conjugate from sympy.functions.elementary.exponential import exp from sympy.functions.elementary.integers import floor, ceiling from sympy.functions.special.gamma_functions import gamma, lowergamma, uppergamma from sympy.functions.special.singularity_functions import SingularityFunction from sympy.functions.special.zeta_functions import polylog, lerchphi, zeta, dirichlet_eta from sympy.logic.boolalg import And, Or, Implies, Equivalent, Xor, Not from sympy.matrices.expressions.determinant import Determinant from sympy.physics.quantum import ComplexSpace, HilbertSpace, FockSpace, hbar, Dagger from sympy.printing.mathml import mathml, MathMLContentPrinter, \ MathMLPresentationPrinter, MathMLPrinter from sympy.sets.sets import FiniteSet, Union, Intersection, Complement, \ SymmetricDifference, Interval, EmptySet, ProductSet from sympy.stats.rv import RandomSymbol from sympy.testing.pytest import raises from sympy.vector import CoordSys3D, Cross, Curl, Dot, Divergence, Gradient, Laplacian x, y, z, a, b, c, d, e, n = symbols('x:z a:e n') mp = MathMLContentPrinter() mpp = MathMLPresentationPrinter() def test_mathml_printer(): m = MathMLPrinter() assert m.doprint(1+x) == mp.doprint(1+x) def test_content_printmethod(): assert mp.doprint(1 + x) == '<apply><plus/><ci>x</ci><cn>1</cn></apply>' def test_content_mathml_core(): mml_1 = mp._print(1 + x) assert mml_1.nodeName == 'apply' nodes = mml_1.childNodes assert len(nodes) == 3 assert nodes[0].nodeName == 'plus' assert nodes[0].hasChildNodes() is False assert nodes[0].nodeValue is None assert nodes[1].nodeName in ['cn', 'ci'] if nodes[1].nodeName == 'cn': assert nodes[1].childNodes[0].nodeValue == '1' assert nodes[2].childNodes[0].nodeValue == 'x' else: assert nodes[1].childNodes[0].nodeValue == 'x' assert nodes[2].childNodes[0].nodeValue == '1' mml_2 = mp._print(x**2) assert mml_2.nodeName == 'apply' nodes = mml_2.childNodes assert nodes[1].childNodes[0].nodeValue == 'x' assert nodes[2].childNodes[0].nodeValue == '2' mml_3 = mp._print(2*x) assert mml_3.nodeName == 'apply' nodes = mml_3.childNodes assert nodes[0].nodeName == 'times' assert nodes[1].childNodes[0].nodeValue == '2' assert nodes[2].childNodes[0].nodeValue == 'x' mml = mp._print(Float(1.0, 2)*x) assert mml.nodeName == 'apply' nodes = mml.childNodes assert nodes[0].nodeName == 'times' assert nodes[1].childNodes[0].nodeValue == '1.0' assert nodes[2].childNodes[0].nodeValue == 'x' def test_content_mathml_functions(): mml_1 = mp._print(sin(x)) assert mml_1.nodeName == 'apply' assert mml_1.childNodes[0].nodeName == 'sin' assert mml_1.childNodes[1].nodeName == 'ci' mml_2 = mp._print(diff(sin(x), x, evaluate=False)) assert mml_2.nodeName == 'apply' assert mml_2.childNodes[0].nodeName == 'diff' assert mml_2.childNodes[1].nodeName == 'bvar' assert mml_2.childNodes[1].childNodes[ 0].nodeName == 'ci' # below bvar there's <ci>x/ci> mml_3 = mp._print(diff(cos(x*y), x, evaluate=False)) assert mml_3.nodeName == 'apply' assert mml_3.childNodes[0].nodeName == 'partialdiff' assert mml_3.childNodes[1].nodeName == 'bvar' assert mml_3.childNodes[1].childNodes[ 0].nodeName == 'ci' # below bvar there's <ci>x/ci> def test_content_mathml_limits(): # XXX No unevaluated limits lim_fun = sin(x)/x mml_1 = mp._print(Limit(lim_fun, x, 0)) assert mml_1.childNodes[0].nodeName == 'limit' assert mml_1.childNodes[1].nodeName == 'bvar' assert mml_1.childNodes[2].nodeName == 'lowlimit' assert mml_1.childNodes[3].toxml() == mp._print(lim_fun).toxml() def test_content_mathml_integrals(): integrand = x mml_1 = mp._print(Integral(integrand, (x, 0, 1))) assert mml_1.childNodes[0].nodeName == 'int' assert mml_1.childNodes[1].nodeName == 'bvar' assert mml_1.childNodes[2].nodeName == 'lowlimit' assert mml_1.childNodes[3].nodeName == 'uplimit' assert mml_1.childNodes[4].toxml() == mp._print(integrand).toxml() def test_content_mathml_matrices(): A = Matrix([1, 2, 3]) B = Matrix([[0, 5, 4], [2, 3, 1], [9, 7, 9]]) mll_1 = mp._print(A) assert mll_1.childNodes[0].nodeName == 'matrixrow' assert mll_1.childNodes[0].childNodes[0].nodeName == 'cn' assert mll_1.childNodes[0].childNodes[0].childNodes[0].nodeValue == '1' assert mll_1.childNodes[1].nodeName == 'matrixrow' assert mll_1.childNodes[1].childNodes[0].nodeName == 'cn' assert mll_1.childNodes[1].childNodes[0].childNodes[0].nodeValue == '2' assert mll_1.childNodes[2].nodeName == 'matrixrow' assert mll_1.childNodes[2].childNodes[0].nodeName == 'cn' assert mll_1.childNodes[2].childNodes[0].childNodes[0].nodeValue == '3' mll_2 = mp._print(B) assert mll_2.childNodes[0].nodeName == 'matrixrow' assert mll_2.childNodes[0].childNodes[0].nodeName == 'cn' assert mll_2.childNodes[0].childNodes[0].childNodes[0].nodeValue == '0' assert mll_2.childNodes[0].childNodes[1].nodeName == 'cn' assert mll_2.childNodes[0].childNodes[1].childNodes[0].nodeValue == '5' assert mll_2.childNodes[0].childNodes[2].nodeName == 'cn' assert mll_2.childNodes[0].childNodes[2].childNodes[0].nodeValue == '4' assert mll_2.childNodes[1].nodeName == 'matrixrow' assert mll_2.childNodes[1].childNodes[0].nodeName == 'cn' assert mll_2.childNodes[1].childNodes[0].childNodes[0].nodeValue == '2' assert mll_2.childNodes[1].childNodes[1].nodeName == 'cn' assert mll_2.childNodes[1].childNodes[1].childNodes[0].nodeValue == '3' assert mll_2.childNodes[1].childNodes[2].nodeName == 'cn' assert mll_2.childNodes[1].childNodes[2].childNodes[0].nodeValue == '1' assert mll_2.childNodes[2].nodeName == 'matrixrow' assert mll_2.childNodes[2].childNodes[0].nodeName == 'cn' assert mll_2.childNodes[2].childNodes[0].childNodes[0].nodeValue == '9' assert mll_2.childNodes[2].childNodes[1].nodeName == 'cn' assert mll_2.childNodes[2].childNodes[1].childNodes[0].nodeValue == '7' assert mll_2.childNodes[2].childNodes[2].nodeName == 'cn' assert mll_2.childNodes[2].childNodes[2].childNodes[0].nodeValue == '9' def test_content_mathml_sums(): summand = x mml_1 = mp._print(Sum(summand, (x, 1, 10))) assert mml_1.childNodes[0].nodeName == 'sum' assert mml_1.childNodes[1].nodeName == 'bvar' assert mml_1.childNodes[2].nodeName == 'lowlimit' assert mml_1.childNodes[3].nodeName == 'uplimit' assert mml_1.childNodes[4].toxml() == mp._print(summand).toxml() def test_content_mathml_tuples(): mml_1 = mp._print([2]) assert mml_1.nodeName == 'list' assert mml_1.childNodes[0].nodeName == 'cn' assert len(mml_1.childNodes) == 1 mml_2 = mp._print([2, Integer(1)]) assert mml_2.nodeName == 'list' assert mml_2.childNodes[0].nodeName == 'cn' assert mml_2.childNodes[1].nodeName == 'cn' assert len(mml_2.childNodes) == 2 def test_content_mathml_add(): mml = mp._print(x**5 - x**4 + x) assert mml.childNodes[0].nodeName == 'plus' assert mml.childNodes[1].childNodes[0].nodeName == 'minus' assert mml.childNodes[1].childNodes[1].nodeName == 'apply' def test_content_mathml_Rational(): mml_1 = mp._print(Rational(1, 1)) """should just return a number""" assert mml_1.nodeName == 'cn' mml_2 = mp._print(Rational(2, 5)) assert mml_2.childNodes[0].nodeName == 'divide' def test_content_mathml_constants(): mml = mp._print(I) assert mml.nodeName == 'imaginaryi' mml = mp._print(E) assert mml.nodeName == 'exponentiale' mml = mp._print(oo) assert mml.nodeName == 'infinity' mml = mp._print(pi) assert mml.nodeName == 'pi' assert mathml(GoldenRatio) == '<cn>&#966;</cn>' mml = mathml(EulerGamma) assert mml == '<eulergamma/>' mml = mathml(EmptySet()) assert mml == '<emptyset/>' mml = mathml(S.true) assert mml == '<true/>' mml = mathml(S.false) assert mml == '<false/>' mml = mathml(S.NaN) assert mml == '<notanumber/>' def test_content_mathml_trig(): mml = mp._print(sin(x)) assert mml.childNodes[0].nodeName == 'sin' mml = mp._print(cos(x)) assert mml.childNodes[0].nodeName == 'cos' mml = mp._print(tan(x)) assert mml.childNodes[0].nodeName == 'tan' mml = mp._print(cot(x)) assert mml.childNodes[0].nodeName == 'cot' mml = mp._print(csc(x)) assert mml.childNodes[0].nodeName == 'csc' mml = mp._print(sec(x)) assert mml.childNodes[0].nodeName == 'sec' mml = mp._print(asin(x)) assert mml.childNodes[0].nodeName == 'arcsin' mml = mp._print(acos(x)) assert mml.childNodes[0].nodeName == 'arccos' mml = mp._print(atan(x)) assert mml.childNodes[0].nodeName == 'arctan' mml = mp._print(acot(x)) assert mml.childNodes[0].nodeName == 'arccot' mml = mp._print(acsc(x)) assert mml.childNodes[0].nodeName == 'arccsc' mml = mp._print(asec(x)) assert mml.childNodes[0].nodeName == 'arcsec' mml = mp._print(sinh(x)) assert mml.childNodes[0].nodeName == 'sinh' mml = mp._print(cosh(x)) assert mml.childNodes[0].nodeName == 'cosh' mml = mp._print(tanh(x)) assert mml.childNodes[0].nodeName == 'tanh' mml = mp._print(coth(x)) assert mml.childNodes[0].nodeName == 'coth' mml = mp._print(csch(x)) assert mml.childNodes[0].nodeName == 'csch' mml = mp._print(sech(x)) assert mml.childNodes[0].nodeName == 'sech' mml = mp._print(asinh(x)) assert mml.childNodes[0].nodeName == 'arcsinh' mml = mp._print(atanh(x)) assert mml.childNodes[0].nodeName == 'arctanh' mml = mp._print(acosh(x)) assert mml.childNodes[0].nodeName == 'arccosh' mml = mp._print(acoth(x)) assert mml.childNodes[0].nodeName == 'arccoth' mml = mp._print(acsch(x)) assert mml.childNodes[0].nodeName == 'arccsch' mml = mp._print(asech(x)) assert mml.childNodes[0].nodeName == 'arcsech' def test_content_mathml_relational(): mml_1 = mp._print(Eq(x, 1)) assert mml_1.nodeName == 'apply' assert mml_1.childNodes[0].nodeName == 'eq' assert mml_1.childNodes[1].nodeName == 'ci' assert mml_1.childNodes[1].childNodes[0].nodeValue == 'x' assert mml_1.childNodes[2].nodeName == 'cn' assert mml_1.childNodes[2].childNodes[0].nodeValue == '1' mml_2 = mp._print(Ne(1, x)) assert mml_2.nodeName == 'apply' assert mml_2.childNodes[0].nodeName == 'neq' assert mml_2.childNodes[1].nodeName == 'cn' assert mml_2.childNodes[1].childNodes[0].nodeValue == '1' assert mml_2.childNodes[2].nodeName == 'ci' assert mml_2.childNodes[2].childNodes[0].nodeValue == 'x' mml_3 = mp._print(Ge(1, x)) assert mml_3.nodeName == 'apply' assert mml_3.childNodes[0].nodeName == 'geq' assert mml_3.childNodes[1].nodeName == 'cn' assert mml_3.childNodes[1].childNodes[0].nodeValue == '1' assert mml_3.childNodes[2].nodeName == 'ci' assert mml_3.childNodes[2].childNodes[0].nodeValue == 'x' mml_4 = mp._print(Lt(1, x)) assert mml_4.nodeName == 'apply' assert mml_4.childNodes[0].nodeName == 'lt' assert mml_4.childNodes[1].nodeName == 'cn' assert mml_4.childNodes[1].childNodes[0].nodeValue == '1' assert mml_4.childNodes[2].nodeName == 'ci' assert mml_4.childNodes[2].childNodes[0].nodeValue == 'x' def test_content_symbol(): mml = mp._print(x) assert mml.nodeName == 'ci' assert mml.childNodes[0].nodeValue == 'x' del mml mml = mp._print(Symbol("x^2")) assert mml.nodeName == 'ci' assert mml.childNodes[0].nodeName == 'mml:msup' assert mml.childNodes[0].childNodes[0].nodeName == 'mml:mi' assert mml.childNodes[0].childNodes[0].childNodes[0].nodeValue == 'x' assert mml.childNodes[0].childNodes[1].nodeName == 'mml:mi' assert mml.childNodes[0].childNodes[1].childNodes[0].nodeValue == '2' del mml mml = mp._print(Symbol("x__2")) assert mml.nodeName == 'ci' assert mml.childNodes[0].nodeName == 'mml:msup' assert mml.childNodes[0].childNodes[0].nodeName == 'mml:mi' assert mml.childNodes[0].childNodes[0].childNodes[0].nodeValue == 'x' assert mml.childNodes[0].childNodes[1].nodeName == 'mml:mi' assert mml.childNodes[0].childNodes[1].childNodes[0].nodeValue == '2' del mml mml = mp._print(Symbol("x_2")) assert mml.nodeName == 'ci' assert mml.childNodes[0].nodeName == 'mml:msub' assert mml.childNodes[0].childNodes[0].nodeName == 'mml:mi' assert mml.childNodes[0].childNodes[0].childNodes[0].nodeValue == 'x' assert mml.childNodes[0].childNodes[1].nodeName == 'mml:mi' assert mml.childNodes[0].childNodes[1].childNodes[0].nodeValue == '2' del mml mml = mp._print(Symbol("x^3_2")) assert mml.nodeName == 'ci' assert mml.childNodes[0].nodeName == 'mml:msubsup' assert mml.childNodes[0].childNodes[0].nodeName == 'mml:mi' assert mml.childNodes[0].childNodes[0].childNodes[0].nodeValue == 'x' assert mml.childNodes[0].childNodes[1].nodeName == 'mml:mi' assert mml.childNodes[0].childNodes[1].childNodes[0].nodeValue == '2' assert mml.childNodes[0].childNodes[2].nodeName == 'mml:mi' assert mml.childNodes[0].childNodes[2].childNodes[0].nodeValue == '3' del mml mml = mp._print(Symbol("x__3_2")) assert mml.nodeName == 'ci' assert mml.childNodes[0].nodeName == 'mml:msubsup' assert mml.childNodes[0].childNodes[0].nodeName == 'mml:mi' assert mml.childNodes[0].childNodes[0].childNodes[0].nodeValue == 'x' assert mml.childNodes[0].childNodes[1].nodeName == 'mml:mi' assert mml.childNodes[0].childNodes[1].childNodes[0].nodeValue == '2' assert mml.childNodes[0].childNodes[2].nodeName == 'mml:mi' assert mml.childNodes[0].childNodes[2].childNodes[0].nodeValue == '3' del mml mml = mp._print(Symbol("x_2_a")) assert mml.nodeName == 'ci' assert mml.childNodes[0].nodeName == 'mml:msub' assert mml.childNodes[0].childNodes[0].nodeName == 'mml:mi' assert mml.childNodes[0].childNodes[0].childNodes[0].nodeValue == 'x' assert mml.childNodes[0].childNodes[1].nodeName == 'mml:mrow' assert mml.childNodes[0].childNodes[1].childNodes[0].nodeName == 'mml:mi' assert mml.childNodes[0].childNodes[1].childNodes[0].childNodes[ 0].nodeValue == '2' assert mml.childNodes[0].childNodes[1].childNodes[1].nodeName == 'mml:mo' assert mml.childNodes[0].childNodes[1].childNodes[1].childNodes[ 0].nodeValue == ' ' assert mml.childNodes[0].childNodes[1].childNodes[2].nodeName == 'mml:mi' assert mml.childNodes[0].childNodes[1].childNodes[2].childNodes[ 0].nodeValue == 'a' del mml mml = mp._print(Symbol("x^2^a")) assert mml.nodeName == 'ci' assert mml.childNodes[0].nodeName == 'mml:msup' assert mml.childNodes[0].childNodes[0].nodeName == 'mml:mi' assert mml.childNodes[0].childNodes[0].childNodes[0].nodeValue == 'x' assert mml.childNodes[0].childNodes[1].nodeName == 'mml:mrow' assert mml.childNodes[0].childNodes[1].childNodes[0].nodeName == 'mml:mi' assert mml.childNodes[0].childNodes[1].childNodes[0].childNodes[ 0].nodeValue == '2' assert mml.childNodes[0].childNodes[1].childNodes[1].nodeName == 'mml:mo' assert mml.childNodes[0].childNodes[1].childNodes[1].childNodes[ 0].nodeValue == ' ' assert mml.childNodes[0].childNodes[1].childNodes[2].nodeName == 'mml:mi' assert mml.childNodes[0].childNodes[1].childNodes[2].childNodes[ 0].nodeValue == 'a' del mml mml = mp._print(Symbol("x__2__a")) assert mml.nodeName == 'ci' assert mml.childNodes[0].nodeName == 'mml:msup' assert mml.childNodes[0].childNodes[0].nodeName == 'mml:mi' assert mml.childNodes[0].childNodes[0].childNodes[0].nodeValue == 'x' assert mml.childNodes[0].childNodes[1].nodeName == 'mml:mrow' assert mml.childNodes[0].childNodes[1].childNodes[0].nodeName == 'mml:mi' assert mml.childNodes[0].childNodes[1].childNodes[0].childNodes[ 0].nodeValue == '2' assert mml.childNodes[0].childNodes[1].childNodes[1].nodeName == 'mml:mo' assert mml.childNodes[0].childNodes[1].childNodes[1].childNodes[ 0].nodeValue == ' ' assert mml.childNodes[0].childNodes[1].childNodes[2].nodeName == 'mml:mi' assert mml.childNodes[0].childNodes[1].childNodes[2].childNodes[ 0].nodeValue == 'a' del mml def test_content_mathml_greek(): mml = mp._print(Symbol('alpha')) assert mml.nodeName == 'ci' assert mml.childNodes[0].nodeValue == u'\N{GREEK SMALL LETTER ALPHA}' assert mp.doprint(Symbol('alpha')) == '<ci>&#945;</ci>' assert mp.doprint(Symbol('beta')) == '<ci>&#946;</ci>' assert mp.doprint(Symbol('gamma')) == '<ci>&#947;</ci>' assert mp.doprint(Symbol('delta')) == '<ci>&#948;</ci>' assert mp.doprint(Symbol('epsilon')) == '<ci>&#949;</ci>' assert mp.doprint(Symbol('zeta')) == '<ci>&#950;</ci>' assert mp.doprint(Symbol('eta')) == '<ci>&#951;</ci>' assert mp.doprint(Symbol('theta')) == '<ci>&#952;</ci>' assert mp.doprint(Symbol('iota')) == '<ci>&#953;</ci>' assert mp.doprint(Symbol('kappa')) == '<ci>&#954;</ci>' assert mp.doprint(Symbol('lambda')) == '<ci>&#955;</ci>' assert mp.doprint(Symbol('mu')) == '<ci>&#956;</ci>' assert mp.doprint(Symbol('nu')) == '<ci>&#957;</ci>' assert mp.doprint(Symbol('xi')) == '<ci>&#958;</ci>' assert mp.doprint(Symbol('omicron')) == '<ci>&#959;</ci>' assert mp.doprint(Symbol('pi')) == '<ci>&#960;</ci>' assert mp.doprint(Symbol('rho')) == '<ci>&#961;</ci>' assert mp.doprint(Symbol('varsigma')) == '<ci>&#962;</ci>' assert mp.doprint(Symbol('sigma')) == '<ci>&#963;</ci>' assert mp.doprint(Symbol('tau')) == '<ci>&#964;</ci>' assert mp.doprint(Symbol('upsilon')) == '<ci>&#965;</ci>' assert mp.doprint(Symbol('phi')) == '<ci>&#966;</ci>' assert mp.doprint(Symbol('chi')) == '<ci>&#967;</ci>' assert mp.doprint(Symbol('psi')) == '<ci>&#968;</ci>' assert mp.doprint(Symbol('omega')) == '<ci>&#969;</ci>' assert mp.doprint(Symbol('Alpha')) == '<ci>&#913;</ci>' assert mp.doprint(Symbol('Beta')) == '<ci>&#914;</ci>' assert mp.doprint(Symbol('Gamma')) == '<ci>&#915;</ci>' assert mp.doprint(Symbol('Delta')) == '<ci>&#916;</ci>' assert mp.doprint(Symbol('Epsilon')) == '<ci>&#917;</ci>' assert mp.doprint(Symbol('Zeta')) == '<ci>&#918;</ci>' assert mp.doprint(Symbol('Eta')) == '<ci>&#919;</ci>' assert mp.doprint(Symbol('Theta')) == '<ci>&#920;</ci>' assert mp.doprint(Symbol('Iota')) == '<ci>&#921;</ci>' assert mp.doprint(Symbol('Kappa')) == '<ci>&#922;</ci>' assert mp.doprint(Symbol('Lambda')) == '<ci>&#923;</ci>' assert mp.doprint(Symbol('Mu')) == '<ci>&#924;</ci>' assert mp.doprint(Symbol('Nu')) == '<ci>&#925;</ci>' assert mp.doprint(Symbol('Xi')) == '<ci>&#926;</ci>' assert mp.doprint(Symbol('Omicron')) == '<ci>&#927;</ci>' assert mp.doprint(Symbol('Pi')) == '<ci>&#928;</ci>' assert mp.doprint(Symbol('Rho')) == '<ci>&#929;</ci>' assert mp.doprint(Symbol('Sigma')) == '<ci>&#931;</ci>' assert mp.doprint(Symbol('Tau')) == '<ci>&#932;</ci>' assert mp.doprint(Symbol('Upsilon')) == '<ci>&#933;</ci>' assert mp.doprint(Symbol('Phi')) == '<ci>&#934;</ci>' assert mp.doprint(Symbol('Chi')) == '<ci>&#935;</ci>' assert mp.doprint(Symbol('Psi')) == '<ci>&#936;</ci>' assert mp.doprint(Symbol('Omega')) == '<ci>&#937;</ci>' def test_content_mathml_order(): expr = x**3 + x**2*y + 3*x*y**3 + y**4 mp = MathMLContentPrinter({'order': 'lex'}) mml = mp._print(expr) assert mml.childNodes[1].childNodes[0].nodeName == 'power' assert mml.childNodes[1].childNodes[1].childNodes[0].data == 'x' assert mml.childNodes[1].childNodes[2].childNodes[0].data == '3' assert mml.childNodes[4].childNodes[0].nodeName == 'power' assert mml.childNodes[4].childNodes[1].childNodes[0].data == 'y' assert mml.childNodes[4].childNodes[2].childNodes[0].data == '4' mp = MathMLContentPrinter({'order': 'rev-lex'}) mml = mp._print(expr) assert mml.childNodes[1].childNodes[0].nodeName == 'power' assert mml.childNodes[1].childNodes[1].childNodes[0].data == 'y' assert mml.childNodes[1].childNodes[2].childNodes[0].data == '4' assert mml.childNodes[4].childNodes[0].nodeName == 'power' assert mml.childNodes[4].childNodes[1].childNodes[0].data == 'x' assert mml.childNodes[4].childNodes[2].childNodes[0].data == '3' def test_content_settings(): raises(TypeError, lambda: mathml(x, method="garbage")) def test_content_mathml_logic(): assert mathml(And(x, y)) == '<apply><and/><ci>x</ci><ci>y</ci></apply>' assert mathml(Or(x, y)) == '<apply><or/><ci>x</ci><ci>y</ci></apply>' assert mathml(Xor(x, y)) == '<apply><xor/><ci>x</ci><ci>y</ci></apply>' assert mathml(Implies(x, y)) == '<apply><implies/><ci>x</ci><ci>y</ci></apply>' assert mathml(Not(x)) == '<apply><not/><ci>x</ci></apply>' def test_content_finite_sets(): assert mathml(FiniteSet(a)) == '<set><ci>a</ci></set>' assert mathml(FiniteSet(a, b)) == '<set><ci>a</ci><ci>b</ci></set>' assert mathml(FiniteSet(FiniteSet(a, b), c)) == \ '<set><ci>c</ci><set><ci>a</ci><ci>b</ci></set></set>' A = FiniteSet(a) B = FiniteSet(b) C = FiniteSet(c) D = FiniteSet(d) U1 = Union(A, B, evaluate=False) U2 = Union(C, D, evaluate=False) I1 = Intersection(A, B, evaluate=False) I2 = Intersection(C, D, evaluate=False) C1 = Complement(A, B, evaluate=False) C2 = Complement(C, D, evaluate=False) # XXX ProductSet does not support evaluate keyword P1 = ProductSet(A, B) P2 = ProductSet(C, D) assert mathml(U1) == \ '<apply><union/><set><ci>a</ci></set><set><ci>b</ci></set></apply>' assert mathml(I1) == \ '<apply><intersect/><set><ci>a</ci></set><set><ci>b</ci></set>' \ '</apply>' assert mathml(C1) == \ '<apply><setdiff/><set><ci>a</ci></set><set><ci>b</ci></set></apply>' assert mathml(P1) == \ '<apply><cartesianproduct/><set><ci>a</ci></set><set><ci>b</ci>' \ '</set></apply>' assert mathml(Intersection(A, U2, evaluate=False)) == \ '<apply><intersect/><set><ci>a</ci></set><apply><union/><set>' \ '<ci>c</ci></set><set><ci>d</ci></set></apply></apply>' assert mathml(Intersection(U1, U2, evaluate=False)) == \ '<apply><intersect/><apply><union/><set><ci>a</ci></set><set>' \ '<ci>b</ci></set></apply><apply><union/><set><ci>c</ci></set>' \ '<set><ci>d</ci></set></apply></apply>' # XXX Does the parenthesis appear correctly for these examples in mathjax? assert mathml(Intersection(C1, C2, evaluate=False)) == \ '<apply><intersect/><apply><setdiff/><set><ci>a</ci></set><set>' \ '<ci>b</ci></set></apply><apply><setdiff/><set><ci>c</ci></set>' \ '<set><ci>d</ci></set></apply></apply>' assert mathml(Intersection(P1, P2, evaluate=False)) == \ '<apply><intersect/><apply><cartesianproduct/><set><ci>a</ci></set>' \ '<set><ci>b</ci></set></apply><apply><cartesianproduct/><set>' \ '<ci>c</ci></set><set><ci>d</ci></set></apply></apply>' assert mathml(Union(A, I2, evaluate=False)) == \ '<apply><union/><set><ci>a</ci></set><apply><intersect/><set>' \ '<ci>c</ci></set><set><ci>d</ci></set></apply></apply>' assert mathml(Union(I1, I2, evaluate=False)) == \ '<apply><union/><apply><intersect/><set><ci>a</ci></set><set>' \ '<ci>b</ci></set></apply><apply><intersect/><set><ci>c</ci></set>' \ '<set><ci>d</ci></set></apply></apply>' assert mathml(Union(C1, C2, evaluate=False)) == \ '<apply><union/><apply><setdiff/><set><ci>a</ci></set><set>' \ '<ci>b</ci></set></apply><apply><setdiff/><set><ci>c</ci></set>' \ '<set><ci>d</ci></set></apply></apply>' assert mathml(Union(P1, P2, evaluate=False)) == \ '<apply><union/><apply><cartesianproduct/><set><ci>a</ci></set>' \ '<set><ci>b</ci></set></apply><apply><cartesianproduct/><set>' \ '<ci>c</ci></set><set><ci>d</ci></set></apply></apply>' assert mathml(Complement(A, C2, evaluate=False)) == \ '<apply><setdiff/><set><ci>a</ci></set><apply><setdiff/><set>' \ '<ci>c</ci></set><set><ci>d</ci></set></apply></apply>' assert mathml(Complement(U1, U2, evaluate=False)) == \ '<apply><setdiff/><apply><union/><set><ci>a</ci></set><set>' \ '<ci>b</ci></set></apply><apply><union/><set><ci>c</ci></set>' \ '<set><ci>d</ci></set></apply></apply>' assert mathml(Complement(I1, I2, evaluate=False)) == \ '<apply><setdiff/><apply><intersect/><set><ci>a</ci></set><set>' \ '<ci>b</ci></set></apply><apply><intersect/><set><ci>c</ci></set>' \ '<set><ci>d</ci></set></apply></apply>' assert mathml(Complement(P1, P2, evaluate=False)) == \ '<apply><setdiff/><apply><cartesianproduct/><set><ci>a</ci></set>' \ '<set><ci>b</ci></set></apply><apply><cartesianproduct/><set>' \ '<ci>c</ci></set><set><ci>d</ci></set></apply></apply>' assert mathml(ProductSet(A, P2)) == \ '<apply><cartesianproduct/><set><ci>a</ci></set>' \ '<apply><cartesianproduct/><set><ci>c</ci></set>' \ '<set><ci>d</ci></set></apply></apply>' assert mathml(ProductSet(U1, U2)) == \ '<apply><cartesianproduct/><apply><union/><set><ci>a</ci></set>' \ '<set><ci>b</ci></set></apply><apply><union/><set><ci>c</ci></set>' \ '<set><ci>d</ci></set></apply></apply>' assert mathml(ProductSet(I1, I2)) == \ '<apply><cartesianproduct/><apply><intersect/><set><ci>a</ci></set>' \ '<set><ci>b</ci></set></apply><apply><intersect/><set>' \ '<ci>c</ci></set><set><ci>d</ci></set></apply></apply>' assert mathml(ProductSet(C1, C2)) == \ '<apply><cartesianproduct/><apply><setdiff/><set><ci>a</ci></set>' \ '<set><ci>b</ci></set></apply><apply><setdiff/><set>' \ '<ci>c</ci></set><set><ci>d</ci></set></apply></apply>' def test_presentation_printmethod(): assert mpp.doprint(1 + x) == '<mrow><mi>x</mi><mo>+</mo><mn>1</mn></mrow>' assert mpp.doprint(x**2) == '<msup><mi>x</mi><mn>2</mn></msup>' assert mpp.doprint(x**-1) == '<mfrac><mn>1</mn><mi>x</mi></mfrac>' assert mpp.doprint(x**-2) == \ '<mfrac><mn>1</mn><msup><mi>x</mi><mn>2</mn></msup></mfrac>' assert mpp.doprint(2*x) == \ '<mrow><mn>2</mn><mo>&InvisibleTimes;</mo><mi>x</mi></mrow>' def test_presentation_mathml_core(): mml_1 = mpp._print(1 + x) assert mml_1.nodeName == 'mrow' nodes = mml_1.childNodes assert len(nodes) == 3 assert nodes[0].nodeName in ['mi', 'mn'] assert nodes[1].nodeName == 'mo' if nodes[0].nodeName == 'mn': assert nodes[0].childNodes[0].nodeValue == '1' assert nodes[2].childNodes[0].nodeValue == 'x' else: assert nodes[0].childNodes[0].nodeValue == 'x' assert nodes[2].childNodes[0].nodeValue == '1' mml_2 = mpp._print(x**2) assert mml_2.nodeName == 'msup' nodes = mml_2.childNodes assert nodes[0].childNodes[0].nodeValue == 'x' assert nodes[1].childNodes[0].nodeValue == '2' mml_3 = mpp._print(2*x) assert mml_3.nodeName == 'mrow' nodes = mml_3.childNodes assert nodes[0].childNodes[0].nodeValue == '2' assert nodes[1].childNodes[0].nodeValue == '&InvisibleTimes;' assert nodes[2].childNodes[0].nodeValue == 'x' mml = mpp._print(Float(1.0, 2)*x) assert mml.nodeName == 'mrow' nodes = mml.childNodes assert nodes[0].childNodes[0].nodeValue == '1.0' assert nodes[1].childNodes[0].nodeValue == '&InvisibleTimes;' assert nodes[2].childNodes[0].nodeValue == 'x' def test_presentation_mathml_functions(): mml_1 = mpp._print(sin(x)) assert mml_1.childNodes[0].childNodes[0 ].nodeValue == 'sin' assert mml_1.childNodes[1].childNodes[0 ].childNodes[0].nodeValue == 'x' mml_2 = mpp._print(diff(sin(x), x, evaluate=False)) assert mml_2.nodeName == 'mrow' assert mml_2.childNodes[0].childNodes[0 ].childNodes[0].childNodes[0].nodeValue == '&dd;' assert mml_2.childNodes[1].childNodes[1 ].nodeName == 'mfenced' assert mml_2.childNodes[0].childNodes[1 ].childNodes[0].childNodes[0].nodeValue == '&dd;' mml_3 = mpp._print(diff(cos(x*y), x, evaluate=False)) assert mml_3.childNodes[0].nodeName == 'mfrac' assert mml_3.childNodes[0].childNodes[0 ].childNodes[0].childNodes[0].nodeValue == '&#x2202;' assert mml_3.childNodes[1].childNodes[0 ].childNodes[0].nodeValue == 'cos' def test_print_derivative(): f = Function('f') d = Derivative(f(x, y, z), x, z, x, z, z, y) assert mathml(d) == \ '<apply><partialdiff/><bvar><ci>y</ci><ci>z</ci><degree><cn>2</cn></degree><ci>x</ci><ci>z</ci><ci>x</ci></bvar><apply><f/><ci>x</ci><ci>y</ci><ci>z</ci></apply></apply>' assert mathml(d, printer='presentation') == \ '<mrow><mfrac><mrow><msup><mo>&#x2202;</mo><mn>6</mn></msup></mrow><mrow><mo>&#x2202;</mo><mi>y</mi><msup><mo>&#x2202;</mo><mn>2</mn></msup><mi>z</mi><mo>&#x2202;</mo><mi>x</mi><mo>&#x2202;</mo><mi>z</mi><mo>&#x2202;</mo><mi>x</mi></mrow></mfrac><mrow><mi>f</mi><mfenced><mi>x</mi><mi>y</mi><mi>z</mi></mfenced></mrow></mrow>' def test_presentation_mathml_limits(): lim_fun = sin(x)/x mml_1 = mpp._print(Limit(lim_fun, x, 0)) assert mml_1.childNodes[0].nodeName == 'munder' assert mml_1.childNodes[0].childNodes[0 ].childNodes[0].nodeValue == 'lim' assert mml_1.childNodes[0].childNodes[1 ].childNodes[0].childNodes[0 ].nodeValue == 'x' assert mml_1.childNodes[0].childNodes[1 ].childNodes[1].childNodes[0 ].nodeValue == '&#x2192;' assert mml_1.childNodes[0].childNodes[1 ].childNodes[2].childNodes[0 ].nodeValue == '0' def test_presentation_mathml_integrals(): assert mpp.doprint(Integral(x, (x, 0, 1))) == \ '<mrow><msubsup><mo>&#x222B;</mo><mn>0</mn><mn>1</mn></msubsup>'\ '<mi>x</mi><mo>&dd;</mo><mi>x</mi></mrow>' assert mpp.doprint(Integral(log(x), x)) == \ '<mrow><mo>&#x222B;</mo><mrow><mi>log</mi><mfenced><mi>x</mi>'\ '</mfenced></mrow><mo>&dd;</mo><mi>x</mi></mrow>' assert mpp.doprint(Integral(x*y, x, y)) == \ '<mrow><mo>&#x222C;</mo><mrow><mi>x</mi><mo>&InvisibleTimes;</mo>'\ '<mi>y</mi></mrow><mo>&dd;</mo><mi>y</mi><mo>&dd;</mo><mi>x</mi></mrow>' z, w = symbols('z w') assert mpp.doprint(Integral(x*y*z, x, y, z)) == \ '<mrow><mo>&#x222D;</mo><mrow><mi>x</mi><mo>&InvisibleTimes;</mo>'\ '<mi>y</mi><mo>&InvisibleTimes;</mo><mi>z</mi></mrow><mo>&dd;</mo>'\ '<mi>z</mi><mo>&dd;</mo><mi>y</mi><mo>&dd;</mo><mi>x</mi></mrow>' assert mpp.doprint(Integral(x*y*z*w, x, y, z, w)) == \ '<mrow><mo>&#x222B;</mo><mo>&#x222B;</mo><mo>&#x222B;</mo>'\ '<mo>&#x222B;</mo><mrow><mi>w</mi><mo>&InvisibleTimes;</mo>'\ '<mi>x</mi><mo>&InvisibleTimes;</mo><mi>y</mi>'\ '<mo>&InvisibleTimes;</mo><mi>z</mi></mrow><mo>&dd;</mo><mi>w</mi>'\ '<mo>&dd;</mo><mi>z</mi><mo>&dd;</mo><mi>y</mi><mo>&dd;</mo><mi>x</mi></mrow>' assert mpp.doprint(Integral(x, x, y, (z, 0, 1))) == \ '<mrow><msubsup><mo>&#x222B;</mo><mn>0</mn><mn>1</mn></msubsup>'\ '<mo>&#x222B;</mo><mo>&#x222B;</mo><mi>x</mi><mo>&dd;</mo><mi>z</mi>'\ '<mo>&dd;</mo><mi>y</mi><mo>&dd;</mo><mi>x</mi></mrow>' assert mpp.doprint(Integral(x, (x, 0))) == \ '<mrow><msup><mo>&#x222B;</mo><mn>0</mn></msup><mi>x</mi><mo>&dd;</mo>'\ '<mi>x</mi></mrow>' def test_presentation_mathml_matrices(): A = Matrix([1, 2, 3]) B = Matrix([[0, 5, 4], [2, 3, 1], [9, 7, 9]]) mll_1 = mpp._print(A) assert mll_1.childNodes[0].nodeName == 'mtable' assert mll_1.childNodes[0].childNodes[0].nodeName == 'mtr' assert len(mll_1.childNodes[0].childNodes) == 3 assert mll_1.childNodes[0].childNodes[0].childNodes[0].nodeName == 'mtd' assert len(mll_1.childNodes[0].childNodes[0].childNodes) == 1 assert mll_1.childNodes[0].childNodes[0].childNodes[0 ].childNodes[0].childNodes[0].nodeValue == '1' assert mll_1.childNodes[0].childNodes[1].childNodes[0 ].childNodes[0].childNodes[0].nodeValue == '2' assert mll_1.childNodes[0].childNodes[2].childNodes[0 ].childNodes[0].childNodes[0].nodeValue == '3' mll_2 = mpp._print(B) assert mll_2.childNodes[0].nodeName == 'mtable' assert mll_2.childNodes[0].childNodes[0].nodeName == 'mtr' assert len(mll_2.childNodes[0].childNodes) == 3 assert mll_2.childNodes[0].childNodes[0].childNodes[0].nodeName == 'mtd' assert len(mll_2.childNodes[0].childNodes[0].childNodes) == 3 assert mll_2.childNodes[0].childNodes[0].childNodes[0 ].childNodes[0].childNodes[0].nodeValue == '0' assert mll_2.childNodes[0].childNodes[0].childNodes[1 ].childNodes[0].childNodes[0].nodeValue == '5' assert mll_2.childNodes[0].childNodes[0].childNodes[2 ].childNodes[0].childNodes[0].nodeValue == '4' assert mll_2.childNodes[0].childNodes[1].childNodes[0 ].childNodes[0].childNodes[0].nodeValue == '2' assert mll_2.childNodes[0].childNodes[1].childNodes[1 ].childNodes[0].childNodes[0].nodeValue == '3' assert mll_2.childNodes[0].childNodes[1].childNodes[2 ].childNodes[0].childNodes[0].nodeValue == '1' assert mll_2.childNodes[0].childNodes[2].childNodes[0 ].childNodes[0].childNodes[0].nodeValue == '9' assert mll_2.childNodes[0].childNodes[2].childNodes[1 ].childNodes[0].childNodes[0].nodeValue == '7' assert mll_2.childNodes[0].childNodes[2].childNodes[2 ].childNodes[0].childNodes[0].nodeValue == '9' def test_presentation_mathml_sums(): summand = x mml_1 = mpp._print(Sum(summand, (x, 1, 10))) assert mml_1.childNodes[0].nodeName == 'munderover' assert len(mml_1.childNodes[0].childNodes) == 3 assert mml_1.childNodes[0].childNodes[0].childNodes[0 ].nodeValue == '&#x2211;' assert len(mml_1.childNodes[0].childNodes[1].childNodes) == 3 assert mml_1.childNodes[0].childNodes[2].childNodes[0 ].nodeValue == '10' assert mml_1.childNodes[1].childNodes[0].nodeValue == 'x' def test_presentation_mathml_add(): mml = mpp._print(x**5 - x**4 + x) assert len(mml.childNodes) == 5 assert mml.childNodes[0].childNodes[0].childNodes[0 ].nodeValue == 'x' assert mml.childNodes[0].childNodes[1].childNodes[0 ].nodeValue == '5' assert mml.childNodes[1].childNodes[0].nodeValue == '-' assert mml.childNodes[2].childNodes[0].childNodes[0 ].nodeValue == 'x' assert mml.childNodes[2].childNodes[1].childNodes[0 ].nodeValue == '4' assert mml.childNodes[3].childNodes[0].nodeValue == '+' assert mml.childNodes[4].childNodes[0].nodeValue == 'x' def test_presentation_mathml_Rational(): mml_1 = mpp._print(Rational(1, 1)) assert mml_1.nodeName == 'mn' mml_2 = mpp._print(Rational(2, 5)) assert mml_2.nodeName == 'mfrac' assert mml_2.childNodes[0].childNodes[0].nodeValue == '2' assert mml_2.childNodes[1].childNodes[0].nodeValue == '5' def test_presentation_mathml_constants(): mml = mpp._print(I) assert mml.childNodes[0].nodeValue == '&ImaginaryI;' mml = mpp._print(E) assert mml.childNodes[0].nodeValue == '&ExponentialE;' mml = mpp._print(oo) assert mml.childNodes[0].nodeValue == '&#x221E;' mml = mpp._print(pi) assert mml.childNodes[0].nodeValue == '&pi;' assert mathml(GoldenRatio, printer='presentation') == '<mi>&#x3A6;</mi>' assert mathml(zoo, printer='presentation') == \ '<mover><mo>&#x221E;</mo><mo>~</mo></mover>' assert mathml(S.NaN, printer='presentation') == '<mi>NaN</mi>' def test_presentation_mathml_trig(): mml = mpp._print(sin(x)) assert mml.childNodes[0].childNodes[0].nodeValue == 'sin' mml = mpp._print(cos(x)) assert mml.childNodes[0].childNodes[0].nodeValue == 'cos' mml = mpp._print(tan(x)) assert mml.childNodes[0].childNodes[0].nodeValue == 'tan' mml = mpp._print(asin(x)) assert mml.childNodes[0].childNodes[0].nodeValue == 'arcsin' mml = mpp._print(acos(x)) assert mml.childNodes[0].childNodes[0].nodeValue == 'arccos' mml = mpp._print(atan(x)) assert mml.childNodes[0].childNodes[0].nodeValue == 'arctan' mml = mpp._print(sinh(x)) assert mml.childNodes[0].childNodes[0].nodeValue == 'sinh' mml = mpp._print(cosh(x)) assert mml.childNodes[0].childNodes[0].nodeValue == 'cosh' mml = mpp._print(tanh(x)) assert mml.childNodes[0].childNodes[0].nodeValue == 'tanh' mml = mpp._print(asinh(x)) assert mml.childNodes[0].childNodes[0].nodeValue == 'arcsinh' mml = mpp._print(atanh(x)) assert mml.childNodes[0].childNodes[0].nodeValue == 'arctanh' mml = mpp._print(acosh(x)) assert mml.childNodes[0].childNodes[0].nodeValue == 'arccosh' def test_presentation_mathml_relational(): mml_1 = mpp._print(Eq(x, 1)) assert len(mml_1.childNodes) == 3 assert mml_1.childNodes[0].nodeName == 'mi' assert mml_1.childNodes[0].childNodes[0].nodeValue == 'x' assert mml_1.childNodes[1].nodeName == 'mo' assert mml_1.childNodes[1].childNodes[0].nodeValue == '=' assert mml_1.childNodes[2].nodeName == 'mn' assert mml_1.childNodes[2].childNodes[0].nodeValue == '1' mml_2 = mpp._print(Ne(1, x)) assert len(mml_2.childNodes) == 3 assert mml_2.childNodes[0].nodeName == 'mn' assert mml_2.childNodes[0].childNodes[0].nodeValue == '1' assert mml_2.childNodes[1].nodeName == 'mo' assert mml_2.childNodes[1].childNodes[0].nodeValue == '&#x2260;' assert mml_2.childNodes[2].nodeName == 'mi' assert mml_2.childNodes[2].childNodes[0].nodeValue == 'x' mml_3 = mpp._print(Ge(1, x)) assert len(mml_3.childNodes) == 3 assert mml_3.childNodes[0].nodeName == 'mn' assert mml_3.childNodes[0].childNodes[0].nodeValue == '1' assert mml_3.childNodes[1].nodeName == 'mo' assert mml_3.childNodes[1].childNodes[0].nodeValue == '&#x2265;' assert mml_3.childNodes[2].nodeName == 'mi' assert mml_3.childNodes[2].childNodes[0].nodeValue == 'x' mml_4 = mpp._print(Lt(1, x)) assert len(mml_4.childNodes) == 3 assert mml_4.childNodes[0].nodeName == 'mn' assert mml_4.childNodes[0].childNodes[0].nodeValue == '1' assert mml_4.childNodes[1].nodeName == 'mo' assert mml_4.childNodes[1].childNodes[0].nodeValue == '<' assert mml_4.childNodes[2].nodeName == 'mi' assert mml_4.childNodes[2].childNodes[0].nodeValue == 'x' def test_presentation_symbol(): mml = mpp._print(x) assert mml.nodeName == 'mi' assert mml.childNodes[0].nodeValue == 'x' del mml mml = mpp._print(Symbol("x^2")) assert mml.nodeName == 'msup' assert mml.childNodes[0].nodeName == 'mi' assert mml.childNodes[0].childNodes[0].nodeValue == 'x' assert mml.childNodes[1].nodeName == 'mi' assert mml.childNodes[1].childNodes[0].nodeValue == '2' del mml mml = mpp._print(Symbol("x__2")) assert mml.nodeName == 'msup' assert mml.childNodes[0].nodeName == 'mi' assert mml.childNodes[0].childNodes[0].nodeValue == 'x' assert mml.childNodes[1].nodeName == 'mi' assert mml.childNodes[1].childNodes[0].nodeValue == '2' del mml mml = mpp._print(Symbol("x_2")) assert mml.nodeName == 'msub' assert mml.childNodes[0].nodeName == 'mi' assert mml.childNodes[0].childNodes[0].nodeValue == 'x' assert mml.childNodes[1].nodeName == 'mi' assert mml.childNodes[1].childNodes[0].nodeValue == '2' del mml mml = mpp._print(Symbol("x^3_2")) assert mml.nodeName == 'msubsup' assert mml.childNodes[0].nodeName == 'mi' assert mml.childNodes[0].childNodes[0].nodeValue == 'x' assert mml.childNodes[1].nodeName == 'mi' assert mml.childNodes[1].childNodes[0].nodeValue == '2' assert mml.childNodes[2].nodeName == 'mi' assert mml.childNodes[2].childNodes[0].nodeValue == '3' del mml mml = mpp._print(Symbol("x__3_2")) assert mml.nodeName == 'msubsup' assert mml.childNodes[0].nodeName == 'mi' assert mml.childNodes[0].childNodes[0].nodeValue == 'x' assert mml.childNodes[1].nodeName == 'mi' assert mml.childNodes[1].childNodes[0].nodeValue == '2' assert mml.childNodes[2].nodeName == 'mi' assert mml.childNodes[2].childNodes[0].nodeValue == '3' del mml mml = mpp._print(Symbol("x_2_a")) assert mml.nodeName == 'msub' assert mml.childNodes[0].nodeName == 'mi' assert mml.childNodes[0].childNodes[0].nodeValue == 'x' assert mml.childNodes[1].nodeName == 'mrow' assert mml.childNodes[1].childNodes[0].nodeName == 'mi' assert mml.childNodes[1].childNodes[0].childNodes[0].nodeValue == '2' assert mml.childNodes[1].childNodes[1].nodeName == 'mo' assert mml.childNodes[1].childNodes[1].childNodes[0].nodeValue == ' ' assert mml.childNodes[1].childNodes[2].nodeName == 'mi' assert mml.childNodes[1].childNodes[2].childNodes[0].nodeValue == 'a' del mml mml = mpp._print(Symbol("x^2^a")) assert mml.nodeName == 'msup' assert mml.childNodes[0].nodeName == 'mi' assert mml.childNodes[0].childNodes[0].nodeValue == 'x' assert mml.childNodes[1].nodeName == 'mrow' assert mml.childNodes[1].childNodes[0].nodeName == 'mi' assert mml.childNodes[1].childNodes[0].childNodes[0].nodeValue == '2' assert mml.childNodes[1].childNodes[1].nodeName == 'mo' assert mml.childNodes[1].childNodes[1].childNodes[0].nodeValue == ' ' assert mml.childNodes[1].childNodes[2].nodeName == 'mi' assert mml.childNodes[1].childNodes[2].childNodes[0].nodeValue == 'a' del mml mml = mpp._print(Symbol("x__2__a")) assert mml.nodeName == 'msup' assert mml.childNodes[0].nodeName == 'mi' assert mml.childNodes[0].childNodes[0].nodeValue == 'x' assert mml.childNodes[1].nodeName == 'mrow' assert mml.childNodes[1].childNodes[0].nodeName == 'mi' assert mml.childNodes[1].childNodes[0].childNodes[0].nodeValue == '2' assert mml.childNodes[1].childNodes[1].nodeName == 'mo' assert mml.childNodes[1].childNodes[1].childNodes[0].nodeValue == ' ' assert mml.childNodes[1].childNodes[2].nodeName == 'mi' assert mml.childNodes[1].childNodes[2].childNodes[0].nodeValue == 'a' del mml def test_presentation_mathml_greek(): mml = mpp._print(Symbol('alpha')) assert mml.nodeName == 'mi' assert mml.childNodes[0].nodeValue == u'\N{GREEK SMALL LETTER ALPHA}' assert mpp.doprint(Symbol('alpha')) == '<mi>&#945;</mi>' assert mpp.doprint(Symbol('beta')) == '<mi>&#946;</mi>' assert mpp.doprint(Symbol('gamma')) == '<mi>&#947;</mi>' assert mpp.doprint(Symbol('delta')) == '<mi>&#948;</mi>' assert mpp.doprint(Symbol('epsilon')) == '<mi>&#949;</mi>' assert mpp.doprint(Symbol('zeta')) == '<mi>&#950;</mi>' assert mpp.doprint(Symbol('eta')) == '<mi>&#951;</mi>' assert mpp.doprint(Symbol('theta')) == '<mi>&#952;</mi>' assert mpp.doprint(Symbol('iota')) == '<mi>&#953;</mi>' assert mpp.doprint(Symbol('kappa')) == '<mi>&#954;</mi>' assert mpp.doprint(Symbol('lambda')) == '<mi>&#955;</mi>' assert mpp.doprint(Symbol('mu')) == '<mi>&#956;</mi>' assert mpp.doprint(Symbol('nu')) == '<mi>&#957;</mi>' assert mpp.doprint(Symbol('xi')) == '<mi>&#958;</mi>' assert mpp.doprint(Symbol('omicron')) == '<mi>&#959;</mi>' assert mpp.doprint(Symbol('pi')) == '<mi>&#960;</mi>' assert mpp.doprint(Symbol('rho')) == '<mi>&#961;</mi>' assert mpp.doprint(Symbol('varsigma')) == '<mi>&#962;</mi>' assert mpp.doprint(Symbol('sigma')) == '<mi>&#963;</mi>' assert mpp.doprint(Symbol('tau')) == '<mi>&#964;</mi>' assert mpp.doprint(Symbol('upsilon')) == '<mi>&#965;</mi>' assert mpp.doprint(Symbol('phi')) == '<mi>&#966;</mi>' assert mpp.doprint(Symbol('chi')) == '<mi>&#967;</mi>' assert mpp.doprint(Symbol('psi')) == '<mi>&#968;</mi>' assert mpp.doprint(Symbol('omega')) == '<mi>&#969;</mi>' assert mpp.doprint(Symbol('Alpha')) == '<mi>&#913;</mi>' assert mpp.doprint(Symbol('Beta')) == '<mi>&#914;</mi>' assert mpp.doprint(Symbol('Gamma')) == '<mi>&#915;</mi>' assert mpp.doprint(Symbol('Delta')) == '<mi>&#916;</mi>' assert mpp.doprint(Symbol('Epsilon')) == '<mi>&#917;</mi>' assert mpp.doprint(Symbol('Zeta')) == '<mi>&#918;</mi>' assert mpp.doprint(Symbol('Eta')) == '<mi>&#919;</mi>' assert mpp.doprint(Symbol('Theta')) == '<mi>&#920;</mi>' assert mpp.doprint(Symbol('Iota')) == '<mi>&#921;</mi>' assert mpp.doprint(Symbol('Kappa')) == '<mi>&#922;</mi>' assert mpp.doprint(Symbol('Lambda')) == '<mi>&#923;</mi>' assert mpp.doprint(Symbol('Mu')) == '<mi>&#924;</mi>' assert mpp.doprint(Symbol('Nu')) == '<mi>&#925;</mi>' assert mpp.doprint(Symbol('Xi')) == '<mi>&#926;</mi>' assert mpp.doprint(Symbol('Omicron')) == '<mi>&#927;</mi>' assert mpp.doprint(Symbol('Pi')) == '<mi>&#928;</mi>' assert mpp.doprint(Symbol('Rho')) == '<mi>&#929;</mi>' assert mpp.doprint(Symbol('Sigma')) == '<mi>&#931;</mi>' assert mpp.doprint(Symbol('Tau')) == '<mi>&#932;</mi>' assert mpp.doprint(Symbol('Upsilon')) == '<mi>&#933;</mi>' assert mpp.doprint(Symbol('Phi')) == '<mi>&#934;</mi>' assert mpp.doprint(Symbol('Chi')) == '<mi>&#935;</mi>' assert mpp.doprint(Symbol('Psi')) == '<mi>&#936;</mi>' assert mpp.doprint(Symbol('Omega')) == '<mi>&#937;</mi>' def test_presentation_mathml_order(): expr = x**3 + x**2*y + 3*x*y**3 + y**4 mp = MathMLPresentationPrinter({'order': 'lex'}) mml = mp._print(expr) assert mml.childNodes[0].nodeName == 'msup' assert mml.childNodes[0].childNodes[0].childNodes[0].nodeValue == 'x' assert mml.childNodes[0].childNodes[1].childNodes[0].nodeValue == '3' assert mml.childNodes[6].nodeName == 'msup' assert mml.childNodes[6].childNodes[0].childNodes[0].nodeValue == 'y' assert mml.childNodes[6].childNodes[1].childNodes[0].nodeValue == '4' mp = MathMLPresentationPrinter({'order': 'rev-lex'}) mml = mp._print(expr) assert mml.childNodes[0].nodeName == 'msup' assert mml.childNodes[0].childNodes[0].childNodes[0].nodeValue == 'y' assert mml.childNodes[0].childNodes[1].childNodes[0].nodeValue == '4' assert mml.childNodes[6].nodeName == 'msup' assert mml.childNodes[6].childNodes[0].childNodes[0].nodeValue == 'x' assert mml.childNodes[6].childNodes[1].childNodes[0].nodeValue == '3' def test_print_intervals(): a = Symbol('a', real=True) assert mpp.doprint(Interval(0, a)) == \ '<mrow><mfenced close="]" open="["><mn>0</mn><mi>a</mi></mfenced></mrow>' assert mpp.doprint(Interval(0, a, False, False)) == \ '<mrow><mfenced close="]" open="["><mn>0</mn><mi>a</mi></mfenced></mrow>' assert mpp.doprint(Interval(0, a, True, False)) == \ '<mrow><mfenced close="]" open="("><mn>0</mn><mi>a</mi></mfenced></mrow>' assert mpp.doprint(Interval(0, a, False, True)) == \ '<mrow><mfenced close=")" open="["><mn>0</mn><mi>a</mi></mfenced></mrow>' assert mpp.doprint(Interval(0, a, True, True)) == \ '<mrow><mfenced close=")" open="("><mn>0</mn><mi>a</mi></mfenced></mrow>' def test_print_tuples(): assert mpp.doprint(Tuple(0,)) == \ '<mrow><mfenced><mn>0</mn></mfenced></mrow>' assert mpp.doprint(Tuple(0, a)) == \ '<mrow><mfenced><mn>0</mn><mi>a</mi></mfenced></mrow>' assert mpp.doprint(Tuple(0, a, a)) == \ '<mrow><mfenced><mn>0</mn><mi>a</mi><mi>a</mi></mfenced></mrow>' assert mpp.doprint(Tuple(0, 1, 2, 3, 4)) == \ '<mrow><mfenced><mn>0</mn><mn>1</mn><mn>2</mn><mn>3</mn><mn>4</mn></mfenced></mrow>' assert mpp.doprint(Tuple(0, 1, Tuple(2, 3, 4))) == \ '<mrow><mfenced><mn>0</mn><mn>1</mn><mrow><mfenced><mn>2</mn><mn>3'\ '</mn><mn>4</mn></mfenced></mrow></mfenced></mrow>' def test_print_re_im(): assert mpp.doprint(re(x)) == \ '<mrow><mi mathvariant="fraktur">R</mi><mfenced><mi>x</mi></mfenced></mrow>' assert mpp.doprint(im(x)) == \ '<mrow><mi mathvariant="fraktur">I</mi><mfenced><mi>x</mi></mfenced></mrow>' assert mpp.doprint(re(x + 1)) == \ '<mrow><mrow><mi mathvariant="fraktur">R</mi><mfenced><mi>x</mi>'\ '</mfenced></mrow><mo>+</mo><mn>1</mn></mrow>' assert mpp.doprint(im(x + 1)) == \ '<mrow><mi mathvariant="fraktur">I</mi><mfenced><mi>x</mi></mfenced></mrow>' def test_print_Abs(): assert mpp.doprint(Abs(x)) == \ '<mrow><mfenced close="|" open="|"><mi>x</mi></mfenced></mrow>' assert mpp.doprint(Abs(x + 1)) == \ '<mrow><mfenced close="|" open="|"><mrow><mi>x</mi><mo>+</mo><mn>1</mn></mrow></mfenced></mrow>' def test_print_Determinant(): assert mpp.doprint(Determinant(Matrix([[1, 2], [3, 4]]))) == \ '<mrow><mfenced close="|" open="|"><mfenced close="]" open="["><mtable><mtr><mtd><mn>1</mn></mtd><mtd><mn>2</mn></mtd></mtr><mtr><mtd><mn>3</mn></mtd><mtd><mn>4</mn></mtd></mtr></mtable></mfenced></mfenced></mrow>' def test_presentation_settings(): raises(TypeError, lambda: mathml(x, printer='presentation', method="garbage")) def test_toprettyxml_hooking(): # test that the patch doesn't influence the behavior of the standard # library import xml.dom.minidom doc1 = xml.dom.minidom.parseString( "<apply><plus/><ci>x</ci><cn>1</cn></apply>") doc2 = xml.dom.minidom.parseString( "<mrow><mi>x</mi><mo>+</mo><mn>1</mn></mrow>") prettyxml_old1 = doc1.toprettyxml() prettyxml_old2 = doc2.toprettyxml() mp.apply_patch() mp.restore_patch() assert prettyxml_old1 == doc1.toprettyxml() assert prettyxml_old2 == doc2.toprettyxml() def test_print_domains(): from sympy import Complexes, Integers, Naturals, Naturals0, Reals assert mpp.doprint(Complexes) == '<mi mathvariant="normal">&#x2102;</mi>' assert mpp.doprint(Integers) == '<mi mathvariant="normal">&#x2124;</mi>' assert mpp.doprint(Naturals) == '<mi mathvariant="normal">&#x2115;</mi>' assert mpp.doprint(Naturals0) == \ '<msub><mi mathvariant="normal">&#x2115;</mi><mn>0</mn></msub>' assert mpp.doprint(Reals) == '<mi mathvariant="normal">&#x211D;</mi>' def test_print_expression_with_minus(): assert mpp.doprint(-x) == '<mrow><mo>-</mo><mi>x</mi></mrow>' assert mpp.doprint(-x/y) == \ '<mrow><mo>-</mo><mfrac><mi>x</mi><mi>y</mi></mfrac></mrow>' assert mpp.doprint(-Rational(1, 2)) == \ '<mrow><mo>-</mo><mfrac><mn>1</mn><mn>2</mn></mfrac></mrow>' def test_print_AssocOp(): from sympy.core.operations import AssocOp class TestAssocOp(AssocOp): identity = 0 expr = TestAssocOp(1, 2) mpp.doprint(expr) == \ '<mrow><mi>testassocop</mi><mn>2</mn><mn>1</mn></mrow>' def test_print_basic(): expr = Basic(1, 2) assert mpp.doprint(expr) == \ '<mrow><mi>basic</mi><mfenced><mn>1</mn><mn>2</mn></mfenced></mrow>' assert mp.doprint(expr) == '<basic><cn>1</cn><cn>2</cn></basic>' def test_mat_delim_print(): expr = Matrix([[1, 2], [3, 4]]) assert mathml(expr, printer='presentation', mat_delim='[') == \ '<mfenced close="]" open="["><mtable><mtr><mtd><mn>1</mn></mtd><mtd>'\ '<mn>2</mn></mtd></mtr><mtr><mtd><mn>3</mn></mtd><mtd><mn>4</mn>'\ '</mtd></mtr></mtable></mfenced>' assert mathml(expr, printer='presentation', mat_delim='(') == \ '<mfenced><mtable><mtr><mtd><mn>1</mn></mtd><mtd><mn>2</mn></mtd>'\ '</mtr><mtr><mtd><mn>3</mn></mtd><mtd><mn>4</mn></mtd></mtr></mtable></mfenced>' assert mathml(expr, printer='presentation', mat_delim='') == \ '<mtable><mtr><mtd><mn>1</mn></mtd><mtd><mn>2</mn></mtd></mtr><mtr>'\ '<mtd><mn>3</mn></mtd><mtd><mn>4</mn></mtd></mtr></mtable>' def test_ln_notation_print(): expr = log(x) assert mathml(expr, printer='presentation') == \ '<mrow><mi>log</mi><mfenced><mi>x</mi></mfenced></mrow>' assert mathml(expr, printer='presentation', ln_notation=False) == \ '<mrow><mi>log</mi><mfenced><mi>x</mi></mfenced></mrow>' assert mathml(expr, printer='presentation', ln_notation=True) == \ '<mrow><mi>ln</mi><mfenced><mi>x</mi></mfenced></mrow>' def test_mul_symbol_print(): expr = x * y assert mathml(expr, printer='presentation') == \ '<mrow><mi>x</mi><mo>&InvisibleTimes;</mo><mi>y</mi></mrow>' assert mathml(expr, printer='presentation', mul_symbol=None) == \ '<mrow><mi>x</mi><mo>&InvisibleTimes;</mo><mi>y</mi></mrow>' assert mathml(expr, printer='presentation', mul_symbol='dot') == \ '<mrow><mi>x</mi><mo>&#xB7;</mo><mi>y</mi></mrow>' assert mathml(expr, printer='presentation', mul_symbol='ldot') == \ '<mrow><mi>x</mi><mo>&#x2024;</mo><mi>y</mi></mrow>' assert mathml(expr, printer='presentation', mul_symbol='times') == \ '<mrow><mi>x</mi><mo>&#xD7;</mo><mi>y</mi></mrow>' def test_print_lerchphi(): assert mpp.doprint(lerchphi(1, 2, 3)) == \ '<mrow><mi>&#x3A6;</mi><mfenced><mn>1</mn><mn>2</mn><mn>3</mn></mfenced></mrow>' def test_print_polylog(): assert mp.doprint(polylog(x, y)) == \ '<apply><polylog/><ci>x</ci><ci>y</ci></apply>' assert mpp.doprint(polylog(x, y)) == \ '<mrow><msub><mi>Li</mi><mi>x</mi></msub><mfenced><mi>y</mi></mfenced></mrow>' def test_print_set_frozenset(): f = frozenset({1, 5, 3}) assert mpp.doprint(f) == \ '<mfenced close="}" open="{"><mn>1</mn><mn>3</mn><mn>5</mn></mfenced>' s = set({1, 2, 3}) assert mpp.doprint(s) == \ '<mfenced close="}" open="{"><mn>1</mn><mn>2</mn><mn>3</mn></mfenced>' def test_print_FiniteSet(): f1 = FiniteSet(x, 1, 3) assert mpp.doprint(f1) == \ '<mfenced close="}" open="{"><mn>1</mn><mn>3</mn><mi>x</mi></mfenced>' def test_print_LambertW(): assert mpp.doprint(LambertW(x)) == '<mrow><mi>W</mi><mfenced><mi>x</mi></mfenced></mrow>' assert mpp.doprint(LambertW(x, y)) == '<mrow><mi>W</mi><mfenced><mi>x</mi><mi>y</mi></mfenced></mrow>' def test_print_EmptySet(): assert mpp.doprint(EmptySet()) == '<mo>&#x2205;</mo>' def test_print_UniversalSet(): assert mpp.doprint(S.UniversalSet) == '<mo>&#x1D54C;</mo>' def test_print_spaces(): assert mpp.doprint(HilbertSpace()) == '<mi>&#x210B;</mi>' assert mpp.doprint(ComplexSpace(2)) == '<msup>&#x1D49E;<mn>2</mn></msup>' assert mpp.doprint(FockSpace()) == '<mi>&#x2131;</mi>' def test_print_constants(): assert mpp.doprint(hbar) == '<mi>&#x210F;</mi>' assert mpp.doprint(TribonacciConstant) == '<mi>TribonacciConstant</mi>' assert mpp.doprint(EulerGamma) == '<mi>&#x3B3;</mi>' def test_print_Contains(): assert mpp.doprint(Contains(x, S.Naturals)) == \ '<mrow><mi>x</mi><mo>&#x2208;</mo><mi mathvariant="normal">&#x2115;</mi></mrow>' def test_print_Dagger(): assert mpp.doprint(Dagger(x)) == '<msup><mi>x</mi>&#x2020;</msup>' def test_print_SetOp(): f1 = FiniteSet(x, 1, 3) f2 = FiniteSet(y, 2, 4) prntr = lambda x: mathml(x, printer='presentation') assert prntr(Union(f1, f2, evaluate=False)) == \ '<mrow><mfenced close="}" open="{"><mn>1</mn><mn>3</mn><mi>x</mi>'\ '</mfenced><mo>&#x222A;</mo><mfenced close="}" open="{"><mn>2</mn>'\ '<mn>4</mn><mi>y</mi></mfenced></mrow>' assert prntr(Intersection(f1, f2, evaluate=False)) == \ '<mrow><mfenced close="}" open="{"><mn>1</mn><mn>3</mn><mi>x</mi>'\ '</mfenced><mo>&#x2229;</mo><mfenced close="}" open="{"><mn>2</mn>'\ '<mn>4</mn><mi>y</mi></mfenced></mrow>' assert prntr(Complement(f1, f2, evaluate=False)) == \ '<mrow><mfenced close="}" open="{"><mn>1</mn><mn>3</mn><mi>x</mi>'\ '</mfenced><mo>&#x2216;</mo><mfenced close="}" open="{"><mn>2</mn>'\ '<mn>4</mn><mi>y</mi></mfenced></mrow>' assert prntr(SymmetricDifference(f1, f2, evaluate=False)) == \ '<mrow><mfenced close="}" open="{"><mn>1</mn><mn>3</mn><mi>x</mi>'\ '</mfenced><mo>&#x2206;</mo><mfenced close="}" open="{"><mn>2</mn>'\ '<mn>4</mn><mi>y</mi></mfenced></mrow>' A = FiniteSet(a) C = FiniteSet(c) D = FiniteSet(d) U1 = Union(C, D, evaluate=False) I1 = Intersection(C, D, evaluate=False) C1 = Complement(C, D, evaluate=False) D1 = SymmetricDifference(C, D, evaluate=False) # XXX ProductSet does not support evaluate keyword P1 = ProductSet(C, D) assert prntr(Union(A, I1, evaluate=False)) == \ '<mrow><mfenced close="}" open="{"><mi>a</mi></mfenced>' \ '<mo>&#x222A;</mo><mfenced><mrow><mfenced close="}" open="{">' \ '<mi>c</mi></mfenced><mo>&#x2229;</mo><mfenced close="}" open="{">' \ '<mi>d</mi></mfenced></mrow></mfenced></mrow>' assert prntr(Intersection(A, C1, evaluate=False)) == \ '<mrow><mfenced close="}" open="{"><mi>a</mi></mfenced>' \ '<mo>&#x2229;</mo><mfenced><mrow><mfenced close="}" open="{">' \ '<mi>c</mi></mfenced><mo>&#x2216;</mo><mfenced close="}" open="{">' \ '<mi>d</mi></mfenced></mrow></mfenced></mrow>' assert prntr(Complement(A, D1, evaluate=False)) == \ '<mrow><mfenced close="}" open="{"><mi>a</mi></mfenced>' \ '<mo>&#x2216;</mo><mfenced><mrow><mfenced close="}" open="{">' \ '<mi>c</mi></mfenced><mo>&#x2206;</mo><mfenced close="}" open="{">' \ '<mi>d</mi></mfenced></mrow></mfenced></mrow>' assert prntr(SymmetricDifference(A, P1, evaluate=False)) == \ '<mrow><mfenced close="}" open="{"><mi>a</mi></mfenced>' \ '<mo>&#x2206;</mo><mfenced><mrow><mfenced close="}" open="{">' \ '<mi>c</mi></mfenced><mo>&#x00d7;</mo><mfenced close="}" open="{">' \ '<mi>d</mi></mfenced></mrow></mfenced></mrow>' assert prntr(ProductSet(A, U1)) == \ '<mrow><mfenced close="}" open="{"><mi>a</mi></mfenced>' \ '<mo>&#x00d7;</mo><mfenced><mrow><mfenced close="}" open="{">' \ '<mi>c</mi></mfenced><mo>&#x222A;</mo><mfenced close="}" open="{">' \ '<mi>d</mi></mfenced></mrow></mfenced></mrow>' def test_print_logic(): assert mpp.doprint(And(x, y)) == \ '<mrow><mi>x</mi><mo>&#x2227;</mo><mi>y</mi></mrow>' assert mpp.doprint(Or(x, y)) == \ '<mrow><mi>x</mi><mo>&#x2228;</mo><mi>y</mi></mrow>' assert mpp.doprint(Xor(x, y)) == \ '<mrow><mi>x</mi><mo>&#x22BB;</mo><mi>y</mi></mrow>' assert mpp.doprint(Implies(x, y)) == \ '<mrow><mi>x</mi><mo>&#x21D2;</mo><mi>y</mi></mrow>' assert mpp.doprint(Equivalent(x, y)) == \ '<mrow><mi>x</mi><mo>&#x21D4;</mo><mi>y</mi></mrow>' assert mpp.doprint(And(Eq(x, y), x > 4)) == \ '<mrow><mrow><mi>x</mi><mo>=</mo><mi>y</mi></mrow><mo>&#x2227;</mo>'\ '<mrow><mi>x</mi><mo>></mo><mn>4</mn></mrow></mrow>' assert mpp.doprint(And(Eq(x, 3), y < 3, x > y + 1)) == \ '<mrow><mrow><mi>x</mi><mo>=</mo><mn>3</mn></mrow><mo>&#x2227;</mo>'\ '<mrow><mi>x</mi><mo>></mo><mrow><mi>y</mi><mo>+</mo><mn>1</mn></mrow>'\ '</mrow><mo>&#x2227;</mo><mrow><mi>y</mi><mo><</mo><mn>3</mn></mrow></mrow>' assert mpp.doprint(Or(Eq(x, y), x > 4)) == \ '<mrow><mrow><mi>x</mi><mo>=</mo><mi>y</mi></mrow><mo>&#x2228;</mo>'\ '<mrow><mi>x</mi><mo>></mo><mn>4</mn></mrow></mrow>' assert mpp.doprint(And(Eq(x, 3), Or(y < 3, x > y + 1))) == \ '<mrow><mrow><mi>x</mi><mo>=</mo><mn>3</mn></mrow><mo>&#x2227;</mo>'\ '<mfenced><mrow><mrow><mi>x</mi><mo>></mo><mrow><mi>y</mi><mo>+</mo>'\ '<mn>1</mn></mrow></mrow><mo>&#x2228;</mo><mrow><mi>y</mi><mo><</mo>'\ '<mn>3</mn></mrow></mrow></mfenced></mrow>' assert mpp.doprint(Not(x)) == '<mrow><mo>&#xAC;</mo><mi>x</mi></mrow>' assert mpp.doprint(Not(And(x, y))) == \ '<mrow><mo>&#xAC;</mo><mfenced><mrow><mi>x</mi><mo>&#x2227;</mo>'\ '<mi>y</mi></mrow></mfenced></mrow>' def test_root_notation_print(): assert mathml(x**(S.One/3), printer='presentation') == \ '<mroot><mi>x</mi><mn>3</mn></mroot>' assert mathml(x**(S.One/3), printer='presentation', root_notation=False) ==\ '<msup><mi>x</mi><mfrac><mn>1</mn><mn>3</mn></mfrac></msup>' assert mathml(x**(S.One/3), printer='content') == \ '<apply><root/><degree><ci>3</ci></degree><ci>x</ci></apply>' assert mathml(x**(S.One/3), printer='content', root_notation=False) == \ '<apply><power/><ci>x</ci><apply><divide/><cn>1</cn><cn>3</cn></apply></apply>' assert mathml(x**(Rational(-1, 3)), printer='presentation') == \ '<mfrac><mn>1</mn><mroot><mi>x</mi><mn>3</mn></mroot></mfrac>' assert mathml(x**(Rational(-1, 3)), printer='presentation', root_notation=False) \ == '<mfrac><mn>1</mn><msup><mi>x</mi><mfrac><mn>1</mn><mn>3</mn></mfrac></msup></mfrac>' def test_fold_frac_powers_print(): expr = x ** Rational(5, 2) assert mathml(expr, printer='presentation') == \ '<msup><mi>x</mi><mfrac><mn>5</mn><mn>2</mn></mfrac></msup>' assert mathml(expr, printer='presentation', fold_frac_powers=True) == \ '<msup><mi>x</mi><mfrac bevelled="true"><mn>5</mn><mn>2</mn></mfrac></msup>' assert mathml(expr, printer='presentation', fold_frac_powers=False) == \ '<msup><mi>x</mi><mfrac><mn>5</mn><mn>2</mn></mfrac></msup>' def test_fold_short_frac_print(): expr = Rational(2, 5) assert mathml(expr, printer='presentation') == \ '<mfrac><mn>2</mn><mn>5</mn></mfrac>' assert mathml(expr, printer='presentation', fold_short_frac=True) == \ '<mfrac bevelled="true"><mn>2</mn><mn>5</mn></mfrac>' assert mathml(expr, printer='presentation', fold_short_frac=False) == \ '<mfrac><mn>2</mn><mn>5</mn></mfrac>' def test_print_factorials(): assert mpp.doprint(factorial(x)) == '<mrow><mi>x</mi><mo>!</mo></mrow>' assert mpp.doprint(factorial(x + 1)) == \ '<mrow><mfenced><mrow><mi>x</mi><mo>+</mo><mn>1</mn></mrow></mfenced><mo>!</mo></mrow>' assert mpp.doprint(factorial2(x)) == '<mrow><mi>x</mi><mo>!!</mo></mrow>' assert mpp.doprint(factorial2(x + 1)) == \ '<mrow><mfenced><mrow><mi>x</mi><mo>+</mo><mn>1</mn></mrow></mfenced><mo>!!</mo></mrow>' assert mpp.doprint(binomial(x, y)) == \ '<mfenced><mfrac linethickness="0"><mi>x</mi><mi>y</mi></mfrac></mfenced>' assert mpp.doprint(binomial(4, x + y)) == \ '<mfenced><mfrac linethickness="0"><mn>4</mn><mrow><mi>x</mi>'\ '<mo>+</mo><mi>y</mi></mrow></mfrac></mfenced>' def test_print_floor(): expr = floor(x) assert mathml(expr, printer='presentation') == \ '<mrow><mfenced close="&#8971;" open="&#8970;"><mi>x</mi></mfenced></mrow>' def test_print_ceiling(): expr = ceiling(x) assert mathml(expr, printer='presentation') == \ '<mrow><mfenced close="&#8969;" open="&#8968;"><mi>x</mi></mfenced></mrow>' def test_print_Lambda(): expr = Lambda(x, x+1) assert mathml(expr, printer='presentation') == \ '<mfenced><mrow><mi>x</mi><mo>&#x21A6;</mo><mrow><mi>x</mi><mo>+</mo>'\ '<mn>1</mn></mrow></mrow></mfenced>' expr = Lambda((x, y), x + y) assert mathml(expr, printer='presentation') == \ '<mfenced><mrow><mrow><mfenced><mi>x</mi><mi>y</mi></mfenced></mrow>'\ '<mo>&#x21A6;</mo><mrow><mi>x</mi><mo>+</mo><mi>y</mi></mrow></mrow></mfenced>' def test_print_conjugate(): assert mpp.doprint(conjugate(x)) == \ '<menclose notation="top"><mi>x</mi></menclose>' assert mpp.doprint(conjugate(x + 1)) == \ '<mrow><menclose notation="top"><mi>x</mi></menclose><mo>+</mo><mn>1</mn></mrow>' def test_print_AccumBounds(): a = Symbol('a', real=True) assert mpp.doprint(AccumBounds(0, 1)) == '<mfenced close="&#10217;" open="&#10216;"><mn>0</mn><mn>1</mn></mfenced>' assert mpp.doprint(AccumBounds(0, a)) == '<mfenced close="&#10217;" open="&#10216;"><mn>0</mn><mi>a</mi></mfenced>' assert mpp.doprint(AccumBounds(a + 1, a + 2)) == '<mfenced close="&#10217;" open="&#10216;"><mrow><mi>a</mi><mo>+</mo><mn>1</mn></mrow><mrow><mi>a</mi><mo>+</mo><mn>2</mn></mrow></mfenced>' def test_print_Float(): assert mpp.doprint(Float(1e100)) == '<mrow><mn>1.0</mn><mo>&#xB7;</mo><msup><mn>10</mn><mn>100</mn></msup></mrow>' assert mpp.doprint(Float(1e-100)) == '<mrow><mn>1.0</mn><mo>&#xB7;</mo><msup><mn>10</mn><mn>-100</mn></msup></mrow>' assert mpp.doprint(Float(-1e100)) == '<mrow><mn>-1.0</mn><mo>&#xB7;</mo><msup><mn>10</mn><mn>100</mn></msup></mrow>' assert mpp.doprint(Float(1.0*oo)) == '<mi>&#x221E;</mi>' assert mpp.doprint(Float(-1.0*oo)) == '<mrow><mo>-</mo><mi>&#x221E;</mi></mrow>' def test_print_different_functions(): assert mpp.doprint(gamma(x)) == '<mrow><mi>&#x393;</mi><mfenced><mi>x</mi></mfenced></mrow>' assert mpp.doprint(lowergamma(x, y)) == '<mrow><mi>&#x3B3;</mi><mfenced><mi>x</mi><mi>y</mi></mfenced></mrow>' assert mpp.doprint(uppergamma(x, y)) == '<mrow><mi>&#x393;</mi><mfenced><mi>x</mi><mi>y</mi></mfenced></mrow>' assert mpp.doprint(zeta(x)) == '<mrow><mi>&#x3B6;</mi><mfenced><mi>x</mi></mfenced></mrow>' assert mpp.doprint(zeta(x, y)) == '<mrow><mi>&#x3B6;</mi><mfenced><mi>x</mi><mi>y</mi></mfenced></mrow>' assert mpp.doprint(dirichlet_eta(x)) == '<mrow><mi>&#x3B7;</mi><mfenced><mi>x</mi></mfenced></mrow>' assert mpp.doprint(elliptic_k(x)) == '<mrow><mi>&#x39A;</mi><mfenced><mi>x</mi></mfenced></mrow>' assert mpp.doprint(totient(x)) == '<mrow><mi>&#x3D5;</mi><mfenced><mi>x</mi></mfenced></mrow>' assert mpp.doprint(reduced_totient(x)) == '<mrow><mi>&#x3BB;</mi><mfenced><mi>x</mi></mfenced></mrow>' assert mpp.doprint(primenu(x)) == '<mrow><mi>&#x3BD;</mi><mfenced><mi>x</mi></mfenced></mrow>' assert mpp.doprint(primeomega(x)) == '<mrow><mi>&#x3A9;</mi><mfenced><mi>x</mi></mfenced></mrow>' assert mpp.doprint(fresnels(x)) == '<mrow><mi>S</mi><mfenced><mi>x</mi></mfenced></mrow>' assert mpp.doprint(fresnelc(x)) == '<mrow><mi>C</mi><mfenced><mi>x</mi></mfenced></mrow>' assert mpp.doprint(Heaviside(x)) == '<mrow><mi>&#x398;</mi><mfenced><mi>x</mi></mfenced></mrow>' def test_mathml_builtins(): assert mpp.doprint(None) == '<mi>None</mi>' assert mpp.doprint(true) == '<mi>True</mi>' assert mpp.doprint(false) == '<mi>False</mi>' def test_mathml_Range(): assert mpp.doprint(Range(1, 51)) == \ '<mfenced close="}" open="{"><mn>1</mn><mn>2</mn><mi>&#8230;</mi><mn>50</mn></mfenced>' assert mpp.doprint(Range(1, 4)) == \ '<mfenced close="}" open="{"><mn>1</mn><mn>2</mn><mn>3</mn></mfenced>' assert mpp.doprint(Range(0, 3, 1)) == \ '<mfenced close="}" open="{"><mn>0</mn><mn>1</mn><mn>2</mn></mfenced>' assert mpp.doprint(Range(0, 30, 1)) == \ '<mfenced close="}" open="{"><mn>0</mn><mn>1</mn><mi>&#8230;</mi><mn>29</mn></mfenced>' assert mpp.doprint(Range(30, 1, -1)) == \ '<mfenced close="}" open="{"><mn>30</mn><mn>29</mn><mi>&#8230;</mi>'\ '<mn>2</mn></mfenced>' assert mpp.doprint(Range(0, oo, 2)) == \ '<mfenced close="}" open="{"><mn>0</mn><mn>2</mn><mi>&#8230;</mi></mfenced>' assert mpp.doprint(Range(oo, -2, -2)) == \ '<mfenced close="}" open="{"><mi>&#8230;</mi><mn>2</mn><mn>0</mn></mfenced>' assert mpp.doprint(Range(-2, -oo, -1)) == \ '<mfenced close="}" open="{"><mn>-2</mn><mn>-3</mn><mi>&#8230;</mi></mfenced>' def test_print_exp(): assert mpp.doprint(exp(x)) == \ '<msup><mi>&ExponentialE;</mi><mi>x</mi></msup>' assert mpp.doprint(exp(1) + exp(2)) == \ '<mrow><mi>&ExponentialE;</mi><mo>+</mo><msup><mi>&ExponentialE;</mi><mn>2</mn></msup></mrow>' def test_print_MinMax(): assert mpp.doprint(Min(x, y)) == \ '<mrow><mo>min</mo><mfenced><mi>x</mi><mi>y</mi></mfenced></mrow>' assert mpp.doprint(Min(x, 2, x**3)) == \ '<mrow><mo>min</mo><mfenced><mn>2</mn><mi>x</mi><msup><mi>x</mi>'\ '<mn>3</mn></msup></mfenced></mrow>' assert mpp.doprint(Max(x, y)) == \ '<mrow><mo>max</mo><mfenced><mi>x</mi><mi>y</mi></mfenced></mrow>' assert mpp.doprint(Max(x, 2, x**3)) == \ '<mrow><mo>max</mo><mfenced><mn>2</mn><mi>x</mi><msup><mi>x</mi>'\ '<mn>3</mn></msup></mfenced></mrow>' def test_mathml_presentation_numbers(): n = Symbol('n') assert mathml(catalan(n), printer='presentation') == \ '<msub><mi>C</mi><mi>n</mi></msub>' assert mathml(bernoulli(n), printer='presentation') == \ '<msub><mi>B</mi><mi>n</mi></msub>' assert mathml(bell(n), printer='presentation') == \ '<msub><mi>B</mi><mi>n</mi></msub>' assert mathml(euler(n), printer='presentation') == \ '<msub><mi>E</mi><mi>n</mi></msub>' assert mathml(fibonacci(n), printer='presentation') == \ '<msub><mi>F</mi><mi>n</mi></msub>' assert mathml(lucas(n), printer='presentation') == \ '<msub><mi>L</mi><mi>n</mi></msub>' assert mathml(tribonacci(n), printer='presentation') == \ '<msub><mi>T</mi><mi>n</mi></msub>' assert mathml(bernoulli(n, x), printer='presentation') == \ '<mrow><msub><mi>B</mi><mi>n</mi></msub><mfenced><mi>x</mi></mfenced></mrow>' assert mathml(bell(n, x), printer='presentation') == \ '<mrow><msub><mi>B</mi><mi>n</mi></msub><mfenced><mi>x</mi></mfenced></mrow>' assert mathml(euler(n, x), printer='presentation') == \ '<mrow><msub><mi>E</mi><mi>n</mi></msub><mfenced><mi>x</mi></mfenced></mrow>' assert mathml(fibonacci(n, x), printer='presentation') == \ '<mrow><msub><mi>F</mi><mi>n</mi></msub><mfenced><mi>x</mi></mfenced></mrow>' assert mathml(tribonacci(n, x), printer='presentation') == \ '<mrow><msub><mi>T</mi><mi>n</mi></msub><mfenced><mi>x</mi></mfenced></mrow>' def test_mathml_presentation_mathieu(): assert mathml(mathieuc(x, y, z), printer='presentation') == \ '<mrow><mi>C</mi><mfenced><mi>x</mi><mi>y</mi><mi>z</mi></mfenced></mrow>' assert mathml(mathieus(x, y, z), printer='presentation') == \ '<mrow><mi>S</mi><mfenced><mi>x</mi><mi>y</mi><mi>z</mi></mfenced></mrow>' assert mathml(mathieucprime(x, y, z), printer='presentation') == \ '<mrow><mi>C&#x2032;</mi><mfenced><mi>x</mi><mi>y</mi><mi>z</mi></mfenced></mrow>' assert mathml(mathieusprime(x, y, z), printer='presentation') == \ '<mrow><mi>S&#x2032;</mi><mfenced><mi>x</mi><mi>y</mi><mi>z</mi></mfenced></mrow>' def test_mathml_presentation_stieltjes(): assert mathml(stieltjes(n), printer='presentation') == \ '<msub><mi>&#x03B3;</mi><mi>n</mi></msub>' assert mathml(stieltjes(n, x), printer='presentation') == \ '<mrow><msub><mi>&#x03B3;</mi><mi>n</mi></msub><mfenced><mi>x</mi></mfenced></mrow>' def test_print_matrix_symbol(): A = MatrixSymbol('A', 1, 2) assert mpp.doprint(A) == '<mi>A</mi>' assert mp.doprint(A) == '<ci>A</ci>' assert mathml(A, printer='presentation', mat_symbol_style="bold") == \ '<mi mathvariant="bold">A</mi>' # No effect in content printer assert mathml(A, mat_symbol_style="bold") == '<ci>A</ci>' def test_print_hadamard(): from sympy.matrices.expressions import HadamardProduct from sympy.matrices.expressions import Transpose X = MatrixSymbol('X', 2, 2) Y = MatrixSymbol('Y', 2, 2) assert mathml(HadamardProduct(X, Y*Y), printer="presentation") == \ '<mrow>' \ '<mi>X</mi>' \ '<mo>&#x2218;</mo>' \ '<msup><mi>Y</mi><mn>2</mn></msup>' \ '</mrow>' assert mathml(HadamardProduct(X, Y)*Y, printer="presentation") == \ '<mrow>' \ '<mfenced>' \ '<mrow><mi>X</mi><mo>&#x2218;</mo><mi>Y</mi></mrow>' \ '</mfenced>' \ '<mo>&InvisibleTimes;</mo><mi>Y</mi>' \ '</mrow>' assert mathml(HadamardProduct(X, Y, Y), printer="presentation") == \ '<mrow>' \ '<mi>X</mi><mo>&#x2218;</mo>' \ '<mi>Y</mi><mo>&#x2218;</mo>' \ '<mi>Y</mi>' \ '</mrow>' assert mathml( Transpose(HadamardProduct(X, Y)), printer="presentation") == \ '<msup>' \ '<mfenced>' \ '<mrow><mi>X</mi><mo>&#x2218;</mo><mi>Y</mi></mrow>' \ '</mfenced>' \ '<mo>T</mo>' \ '</msup>' def test_print_random_symbol(): R = RandomSymbol(Symbol('R')) assert mpp.doprint(R) == '<mi>R</mi>' assert mp.doprint(R) == '<ci>R</ci>' def test_print_IndexedBase(): assert mathml(IndexedBase(a)[b], printer='presentation') == \ '<msub><mi>a</mi><mi>b</mi></msub>' assert mathml(IndexedBase(a)[b, c, d], printer='presentation') == \ '<msub><mi>a</mi><mfenced><mi>b</mi><mi>c</mi><mi>d</mi></mfenced></msub>' assert mathml(IndexedBase(a)[b]*IndexedBase(c)[d]*IndexedBase(e), printer='presentation') == \ '<mrow><msub><mi>a</mi><mi>b</mi></msub><mo>&InvisibleTimes;'\ '</mo><msub><mi>c</mi><mi>d</mi></msub><mo>&InvisibleTimes;</mo><mi>e</mi></mrow>' def test_print_Indexed(): assert mathml(IndexedBase(a), printer='presentation') == '<mi>a</mi>' assert mathml(IndexedBase(a/b), printer='presentation') == \ '<mrow><mfrac><mi>a</mi><mi>b</mi></mfrac></mrow>' assert mathml(IndexedBase((a, b)), printer='presentation') == \ '<mrow><mfenced><mi>a</mi><mi>b</mi></mfenced></mrow>' def test_print_MatrixElement(): i, j = symbols('i j') A = MatrixSymbol('A', i, j) assert mathml(A[0,0],printer = 'presentation') == \ '<msub><mi>A</mi><mfenced close="" open=""><mn>0</mn><mn>0</mn></mfenced></msub>' assert mathml(A[i,j], printer = 'presentation') == \ '<msub><mi>A</mi><mfenced close="" open=""><mi>i</mi><mi>j</mi></mfenced></msub>' assert mathml(A[i*j,0], printer = 'presentation') == \ '<msub><mi>A</mi><mfenced close="" open=""><mrow><mi>i</mi><mo>&InvisibleTimes;</mo><mi>j</mi></mrow><mn>0</mn></mfenced></msub>' def test_print_Vector(): ACS = CoordSys3D('A') assert mathml(Cross(ACS.i, ACS.j*ACS.x*3 + ACS.k), printer='presentation') == \ '<mrow><msub><mover><mi mathvariant="bold">i</mi><mo>^</mo></mover>'\ '<mi mathvariant="bold">A</mi></msub><mo>&#xD7;</mo><mfenced><mrow>'\ '<mfenced><mrow><mn>3</mn><mo>&InvisibleTimes;</mo><msub>'\ '<mi mathvariant="bold">x</mi><mi mathvariant="bold">A</mi></msub>'\ '</mrow></mfenced><mo>&InvisibleTimes;</mo><msub><mover>'\ '<mi mathvariant="bold">j</mi><mo>^</mo></mover>'\ '<mi mathvariant="bold">A</mi></msub><mo>+</mo><msub><mover>'\ '<mi mathvariant="bold">k</mi><mo>^</mo></mover><mi mathvariant="bold">'\ 'A</mi></msub></mrow></mfenced></mrow>' assert mathml(Cross(ACS.i, ACS.j), printer='presentation') == \ '<mrow><msub><mover><mi mathvariant="bold">i</mi><mo>^</mo></mover>'\ '<mi mathvariant="bold">A</mi></msub><mo>&#xD7;</mo><msub><mover>'\ '<mi mathvariant="bold">j</mi><mo>^</mo></mover>'\ '<mi mathvariant="bold">A</mi></msub></mrow>' assert mathml(x*Cross(ACS.i, ACS.j), printer='presentation') == \ '<mrow><mi>x</mi><mo>&InvisibleTimes;</mo><mfenced><mrow><msub><mover>'\ '<mi mathvariant="bold">i</mi><mo>^</mo></mover>'\ '<mi mathvariant="bold">A</mi></msub><mo>&#xD7;</mo><msub><mover>'\ '<mi mathvariant="bold">j</mi><mo>^</mo></mover>'\ '<mi mathvariant="bold">A</mi></msub></mrow></mfenced></mrow>' assert mathml(Cross(x*ACS.i, ACS.j), printer='presentation') == \ '<mrow><mo>-</mo><mrow><msub><mover><mi mathvariant="bold">j</mi>'\ '<mo>^</mo></mover><mi mathvariant="bold">A</mi></msub>'\ '<mo>&#xD7;</mo><mfenced><mrow><mfenced><mi>x</mi></mfenced>'\ '<mo>&InvisibleTimes;</mo><msub><mover><mi mathvariant="bold">i</mi>'\ '<mo>^</mo></mover><mi mathvariant="bold">A</mi></msub></mrow>'\ '</mfenced></mrow></mrow>' assert mathml(Curl(3*ACS.x*ACS.j), printer='presentation') == \ '<mrow><mo>&#x2207;</mo><mo>&#xD7;</mo><mfenced><mrow><mfenced><mrow>'\ '<mn>3</mn><mo>&InvisibleTimes;</mo><msub>'\ '<mi mathvariant="bold">x</mi><mi mathvariant="bold">A</mi></msub>'\ '</mrow></mfenced><mo>&InvisibleTimes;</mo><msub><mover>'\ '<mi mathvariant="bold">j</mi><mo>^</mo></mover>'\ '<mi mathvariant="bold">A</mi></msub></mrow></mfenced></mrow>' assert mathml(Curl(3*x*ACS.x*ACS.j), printer='presentation') == \ '<mrow><mo>&#x2207;</mo><mo>&#xD7;</mo><mfenced><mrow><mfenced><mrow>'\ '<mn>3</mn><mo>&InvisibleTimes;</mo><msub><mi mathvariant="bold">x'\ '</mi><mi mathvariant="bold">A</mi></msub><mo>&InvisibleTimes;</mo>'\ '<mi>x</mi></mrow></mfenced><mo>&InvisibleTimes;</mo><msub><mover>'\ '<mi mathvariant="bold">j</mi><mo>^</mo></mover>'\ '<mi mathvariant="bold">A</mi></msub></mrow></mfenced></mrow>' assert mathml(x*Curl(3*ACS.x*ACS.j), printer='presentation') == \ '<mrow><mi>x</mi><mo>&InvisibleTimes;</mo><mfenced><mrow><mo>&#x2207;</mo>'\ '<mo>&#xD7;</mo><mfenced><mrow><mfenced><mrow><mn>3</mn>'\ '<mo>&InvisibleTimes;</mo><msub><mi mathvariant="bold">x</mi>'\ '<mi mathvariant="bold">A</mi></msub></mrow></mfenced>'\ '<mo>&InvisibleTimes;</mo><msub><mover><mi mathvariant="bold">j</mi>'\ '<mo>^</mo></mover><mi mathvariant="bold">A</mi></msub></mrow>'\ '</mfenced></mrow></mfenced></mrow>' assert mathml(Curl(3*x*ACS.x*ACS.j + ACS.i), printer='presentation') == \ '<mrow><mo>&#x2207;</mo><mo>&#xD7;</mo><mfenced><mrow><msub><mover>'\ '<mi mathvariant="bold">i</mi><mo>^</mo></mover>'\ '<mi mathvariant="bold">A</mi></msub><mo>+</mo><mfenced><mrow>'\ '<mn>3</mn><mo>&InvisibleTimes;</mo><msub><mi mathvariant="bold">x'\ '</mi><mi mathvariant="bold">A</mi></msub><mo>&InvisibleTimes;</mo>'\ '<mi>x</mi></mrow></mfenced><mo>&InvisibleTimes;</mo><msub><mover>'\ '<mi mathvariant="bold">j</mi><mo>^</mo></mover>'\ '<mi mathvariant="bold">A</mi></msub></mrow></mfenced></mrow>' assert mathml(Divergence(3*ACS.x*ACS.j), printer='presentation') == \ '<mrow><mo>&#x2207;</mo><mo>&#xB7;</mo><mfenced><mrow><mfenced><mrow>'\ '<mn>3</mn><mo>&InvisibleTimes;</mo><msub><mi mathvariant="bold">x'\ '</mi><mi mathvariant="bold">A</mi></msub></mrow></mfenced>'\ '<mo>&InvisibleTimes;</mo><msub><mover><mi mathvariant="bold">j</mi>'\ '<mo>^</mo></mover><mi mathvariant="bold">A</mi></msub></mrow></mfenced></mrow>' assert mathml(x*Divergence(3*ACS.x*ACS.j), printer='presentation') == \ '<mrow><mi>x</mi><mo>&InvisibleTimes;</mo><mfenced><mrow><mo>&#x2207;</mo>'\ '<mo>&#xB7;</mo><mfenced><mrow><mfenced><mrow><mn>3</mn>'\ '<mo>&InvisibleTimes;</mo><msub><mi mathvariant="bold">x</mi>'\ '<mi mathvariant="bold">A</mi></msub></mrow></mfenced>'\ '<mo>&InvisibleTimes;</mo><msub><mover><mi mathvariant="bold">j</mi>'\ '<mo>^</mo></mover><mi mathvariant="bold">A</mi></msub></mrow>'\ '</mfenced></mrow></mfenced></mrow>' assert mathml(Divergence(3*x*ACS.x*ACS.j + ACS.i), printer='presentation') == \ '<mrow><mo>&#x2207;</mo><mo>&#xB7;</mo><mfenced><mrow><msub><mover>'\ '<mi mathvariant="bold">i</mi><mo>^</mo></mover>'\ '<mi mathvariant="bold">A</mi></msub><mo>+</mo><mfenced><mrow>'\ '<mn>3</mn><mo>&InvisibleTimes;</mo><msub>'\ '<mi mathvariant="bold">x</mi><mi mathvariant="bold">A</mi></msub>'\ '<mo>&InvisibleTimes;</mo><mi>x</mi></mrow></mfenced>'\ '<mo>&InvisibleTimes;</mo><msub><mover><mi mathvariant="bold">j</mi>'\ '<mo>^</mo></mover><mi mathvariant="bold">A</mi></msub></mrow></mfenced></mrow>' assert mathml(Dot(ACS.i, ACS.j*ACS.x*3+ACS.k), printer='presentation') == \ '<mrow><msub><mover><mi mathvariant="bold">i</mi><mo>^</mo></mover>'\ '<mi mathvariant="bold">A</mi></msub><mo>&#xB7;</mo><mfenced><mrow>'\ '<mfenced><mrow><mn>3</mn><mo>&InvisibleTimes;</mo><msub>'\ '<mi mathvariant="bold">x</mi><mi mathvariant="bold">A</mi></msub>'\ '</mrow></mfenced><mo>&InvisibleTimes;</mo><msub><mover>'\ '<mi mathvariant="bold">j</mi><mo>^</mo></mover>'\ '<mi mathvariant="bold">A</mi></msub><mo>+</mo><msub><mover>'\ '<mi mathvariant="bold">k</mi><mo>^</mo></mover>'\ '<mi mathvariant="bold">A</mi></msub></mrow></mfenced></mrow>' assert mathml(Dot(ACS.i, ACS.j), printer='presentation') == \ '<mrow><msub><mover><mi mathvariant="bold">i</mi><mo>^</mo></mover>'\ '<mi mathvariant="bold">A</mi></msub><mo>&#xB7;</mo><msub><mover>'\ '<mi mathvariant="bold">j</mi><mo>^</mo></mover>'\ '<mi mathvariant="bold">A</mi></msub></mrow>' assert mathml(Dot(x*ACS.i, ACS.j), printer='presentation') == \ '<mrow><msub><mover><mi mathvariant="bold">j</mi><mo>^</mo></mover>'\ '<mi mathvariant="bold">A</mi></msub><mo>&#xB7;</mo><mfenced><mrow>'\ '<mfenced><mi>x</mi></mfenced><mo>&InvisibleTimes;</mo><msub><mover>'\ '<mi mathvariant="bold">i</mi><mo>^</mo></mover>'\ '<mi mathvariant="bold">A</mi></msub></mrow></mfenced></mrow>' assert mathml(x*Dot(ACS.i, ACS.j), printer='presentation') == \ '<mrow><mi>x</mi><mo>&InvisibleTimes;</mo><mfenced><mrow><msub><mover>'\ '<mi mathvariant="bold">i</mi><mo>^</mo></mover>'\ '<mi mathvariant="bold">A</mi></msub><mo>&#xB7;</mo><msub><mover>'\ '<mi mathvariant="bold">j</mi><mo>^</mo></mover>'\ '<mi mathvariant="bold">A</mi></msub></mrow></mfenced></mrow>' assert mathml(Gradient(ACS.x), printer='presentation') == \ '<mrow><mo>&#x2207;</mo><msub><mi mathvariant="bold">x</mi>'\ '<mi mathvariant="bold">A</mi></msub></mrow>' assert mathml(Gradient(ACS.x + 3*ACS.y), printer='presentation') == \ '<mrow><mo>&#x2207;</mo><mfenced><mrow><msub><mi mathvariant="bold">'\ 'x</mi><mi mathvariant="bold">A</mi></msub><mo>+</mo><mrow><mn>3</mn>'\ '<mo>&InvisibleTimes;</mo><msub><mi mathvariant="bold">y</mi>'\ '<mi mathvariant="bold">A</mi></msub></mrow></mrow></mfenced></mrow>' assert mathml(x*Gradient(ACS.x), printer='presentation') == \ '<mrow><mi>x</mi><mo>&InvisibleTimes;</mo><mfenced><mrow><mo>&#x2207;</mo>'\ '<msub><mi mathvariant="bold">x</mi><mi mathvariant="bold">A</mi>'\ '</msub></mrow></mfenced></mrow>' assert mathml(Gradient(x*ACS.x), printer='presentation') == \ '<mrow><mo>&#x2207;</mo><mfenced><mrow><msub><mi mathvariant="bold">'\ 'x</mi><mi mathvariant="bold">A</mi></msub><mo>&InvisibleTimes;</mo>'\ '<mi>x</mi></mrow></mfenced></mrow>' assert mathml(Cross(ACS.x, ACS.z) + Cross(ACS.z, ACS.x), printer='presentation') == \ '<mover><mi mathvariant="bold">0</mi><mo>^</mo></mover>' assert mathml(Cross(ACS.z, ACS.x), printer='presentation') == \ '<mrow><mo>-</mo><mrow><msub><mi mathvariant="bold">x</mi>'\ '<mi mathvariant="bold">A</mi></msub><mo>&#xD7;</mo><msub>'\ '<mi mathvariant="bold">z</mi><mi mathvariant="bold">A</mi></msub></mrow></mrow>' assert mathml(Laplacian(ACS.x), printer='presentation') == \ '<mrow><mo>&#x2206;</mo><msub><mi mathvariant="bold">x</mi>'\ '<mi mathvariant="bold">A</mi></msub></mrow>' assert mathml(Laplacian(ACS.x + 3*ACS.y), printer='presentation') == \ '<mrow><mo>&#x2206;</mo><mfenced><mrow><msub><mi mathvariant="bold">'\ 'x</mi><mi mathvariant="bold">A</mi></msub><mo>+</mo><mrow><mn>3</mn>'\ '<mo>&InvisibleTimes;</mo><msub><mi mathvariant="bold">y</mi>'\ '<mi mathvariant="bold">A</mi></msub></mrow></mrow></mfenced></mrow>' assert mathml(x*Laplacian(ACS.x), printer='presentation') == \ '<mrow><mi>x</mi><mo>&InvisibleTimes;</mo><mfenced><mrow><mo>&#x2206;</mo>'\ '<msub><mi mathvariant="bold">x</mi><mi mathvariant="bold">A</mi>'\ '</msub></mrow></mfenced></mrow>' assert mathml(Laplacian(x*ACS.x), printer='presentation') == \ '<mrow><mo>&#x2206;</mo><mfenced><mrow><msub><mi mathvariant="bold">'\ 'x</mi><mi mathvariant="bold">A</mi></msub><mo>&InvisibleTimes;</mo>'\ '<mi>x</mi></mrow></mfenced></mrow>' def test_print_elliptic_f(): assert mathml(elliptic_f(x, y), printer = 'presentation') == \ '<mrow><mi>&#x1d5a5;</mi><mfenced separators="|"><mi>x</mi><mi>y</mi></mfenced></mrow>' assert mathml(elliptic_f(x/y, y), printer = 'presentation') == \ '<mrow><mi>&#x1d5a5;</mi><mfenced separators="|"><mrow><mfrac><mi>x</mi><mi>y</mi></mfrac></mrow><mi>y</mi></mfenced></mrow>' def test_print_elliptic_e(): assert mathml(elliptic_e(x), printer = 'presentation') == \ '<mrow><mi>&#x1d5a4;</mi><mfenced separators="|"><mi>x</mi></mfenced></mrow>' assert mathml(elliptic_e(x, y), printer = 'presentation') == \ '<mrow><mi>&#x1d5a4;</mi><mfenced separators="|"><mi>x</mi><mi>y</mi></mfenced></mrow>' def test_print_elliptic_pi(): assert mathml(elliptic_pi(x, y), printer = 'presentation') == \ '<mrow><mi>&#x1d6f1;</mi><mfenced separators="|"><mi>x</mi><mi>y</mi></mfenced></mrow>' assert mathml(elliptic_pi(x, y, z), printer = 'presentation') == \ '<mrow><mi>&#x1d6f1;</mi><mfenced separators=";|"><mi>x</mi><mi>y</mi><mi>z</mi></mfenced></mrow>' def test_print_Ei(): assert mathml(Ei(x), printer = 'presentation') == \ '<mrow><mi>Ei</mi><mfenced><mi>x</mi></mfenced></mrow>' assert mathml(Ei(x**y), printer = 'presentation') == \ '<mrow><mi>Ei</mi><mfenced><msup><mi>x</mi><mi>y</mi></msup></mfenced></mrow>' def test_print_expint(): assert mathml(expint(x, y), printer = 'presentation') == \ '<mrow><msub><mo>E</mo><mi>x</mi></msub><mfenced><mi>y</mi></mfenced></mrow>' assert mathml(expint(IndexedBase(x)[1], IndexedBase(x)[2]), printer = 'presentation') == \ '<mrow><msub><mo>E</mo><msub><mi>x</mi><mn>1</mn></msub></msub><mfenced><msub><mi>x</mi><mn>2</mn></msub></mfenced></mrow>' def test_print_jacobi(): assert mathml(jacobi(n, a, b, x), printer = 'presentation') == \ '<mrow><msubsup><mo>P</mo><mi>n</mi><mfenced><mi>a</mi><mi>b</mi></mfenced></msubsup><mfenced><mi>x</mi></mfenced></mrow>' def test_print_gegenbauer(): assert mathml(gegenbauer(n, a, x), printer = 'presentation') == \ '<mrow><msubsup><mo>C</mo><mi>n</mi><mfenced><mi>a</mi></mfenced></msubsup><mfenced><mi>x</mi></mfenced></mrow>' def test_print_chebyshevt(): assert mathml(chebyshevt(n, x), printer = 'presentation') == \ '<mrow><msub><mo>T</mo><mi>n</mi></msub><mfenced><mi>x</mi></mfenced></mrow>' def test_print_chebyshevu(): assert mathml(chebyshevu(n, x), printer = 'presentation') == \ '<mrow><msub><mo>U</mo><mi>n</mi></msub><mfenced><mi>x</mi></mfenced></mrow>' def test_print_legendre(): assert mathml(legendre(n, x), printer = 'presentation') == \ '<mrow><msub><mo>P</mo><mi>n</mi></msub><mfenced><mi>x</mi></mfenced></mrow>' def test_print_assoc_legendre(): assert mathml(assoc_legendre(n, a, x), printer = 'presentation') == \ '<mrow><msubsup><mo>P</mo><mi>n</mi><mfenced><mi>a</mi></mfenced></msubsup><mfenced><mi>x</mi></mfenced></mrow>' def test_print_laguerre(): assert mathml(laguerre(n, x), printer = 'presentation') == \ '<mrow><msub><mo>L</mo><mi>n</mi></msub><mfenced><mi>x</mi></mfenced></mrow>' def test_print_assoc_laguerre(): assert mathml(assoc_laguerre(n, a, x), printer = 'presentation') == \ '<mrow><msubsup><mo>L</mo><mi>n</mi><mfenced><mi>a</mi></mfenced></msubsup><mfenced><mi>x</mi></mfenced></mrow>' def test_print_hermite(): assert mathml(hermite(n, x), printer = 'presentation') == \ '<mrow><msub><mo>H</mo><mi>n</mi></msub><mfenced><mi>x</mi></mfenced></mrow>' def test_mathml_SingularityFunction(): assert mathml(SingularityFunction(x, 4, 5), printer='presentation') == \ '<msup><mfenced close="&#10217;" open="&#10216;"><mrow><mi>x</mi>' \ '<mo>-</mo><mn>4</mn></mrow></mfenced><mn>5</mn></msup>' assert mathml(SingularityFunction(x, -3, 4), printer='presentation') == \ '<msup><mfenced close="&#10217;" open="&#10216;"><mrow><mi>x</mi>' \ '<mo>+</mo><mn>3</mn></mrow></mfenced><mn>4</mn></msup>' assert mathml(SingularityFunction(x, 0, 4), printer='presentation') == \ '<msup><mfenced close="&#10217;" open="&#10216;"><mi>x</mi></mfenced>' \ '<mn>4</mn></msup>' assert mathml(SingularityFunction(x, a, n), printer='presentation') == \ '<msup><mfenced close="&#10217;" open="&#10216;"><mrow><mrow>' \ '<mo>-</mo><mi>a</mi></mrow><mo>+</mo><mi>x</mi></mrow></mfenced>' \ '<mi>n</mi></msup>' assert mathml(SingularityFunction(x, 4, -2), printer='presentation') == \ '<msup><mfenced close="&#10217;" open="&#10216;"><mrow><mi>x</mi>' \ '<mo>-</mo><mn>4</mn></mrow></mfenced><mn>-2</mn></msup>' assert mathml(SingularityFunction(x, 4, -1), printer='presentation') == \ '<msup><mfenced close="&#10217;" open="&#10216;"><mrow><mi>x</mi>' \ '<mo>-</mo><mn>4</mn></mrow></mfenced><mn>-1</mn></msup>' def test_mathml_matrix_functions(): from sympy.matrices import MatrixSymbol, Adjoint, Inverse, Transpose X = MatrixSymbol('X', 2, 2) Y = MatrixSymbol('Y', 2, 2) assert mathml(Adjoint(X), printer='presentation') == \ '<msup><mi>X</mi><mo>&#x2020;</mo></msup>' assert mathml(Adjoint(X + Y), printer='presentation') == \ '<msup><mfenced><mrow><mi>X</mi><mo>+</mo><mi>Y</mi></mrow></mfenced><mo>&#x2020;</mo></msup>' assert mathml(Adjoint(X) + Adjoint(Y), printer='presentation') == \ '<mrow><msup><mi>X</mi><mo>&#x2020;</mo></msup><mo>+</mo><msup>' \ '<mi>Y</mi><mo>&#x2020;</mo></msup></mrow>' assert mathml(Adjoint(X*Y), printer='presentation') == \ '<msup><mfenced><mrow><mi>X</mi><mo>&InvisibleTimes;</mo>' \ '<mi>Y</mi></mrow></mfenced><mo>&#x2020;</mo></msup>' assert mathml(Adjoint(Y)*Adjoint(X), printer='presentation') == \ '<mrow><msup><mi>Y</mi><mo>&#x2020;</mo></msup><mo>&InvisibleTimes;' \ '</mo><msup><mi>X</mi><mo>&#x2020;</mo></msup></mrow>' assert mathml(Adjoint(X**2), printer='presentation') == \ '<msup><mfenced><msup><mi>X</mi><mn>2</mn></msup></mfenced><mo>&#x2020;</mo></msup>' assert mathml(Adjoint(X)**2, printer='presentation') == \ '<msup><mfenced><msup><mi>X</mi><mo>&#x2020;</mo></msup></mfenced><mn>2</mn></msup>' assert mathml(Adjoint(Inverse(X)), printer='presentation') == \ '<msup><mfenced><msup><mi>X</mi><mn>-1</mn></msup></mfenced><mo>&#x2020;</mo></msup>' assert mathml(Inverse(Adjoint(X)), printer='presentation') == \ '<msup><mfenced><msup><mi>X</mi><mo>&#x2020;</mo></msup></mfenced><mn>-1</mn></msup>' assert mathml(Adjoint(Transpose(X)), printer='presentation') == \ '<msup><mfenced><msup><mi>X</mi><mo>T</mo></msup></mfenced><mo>&#x2020;</mo></msup>' assert mathml(Transpose(Adjoint(X)), printer='presentation') == \ '<msup><mfenced><msup><mi>X</mi><mo>&#x2020;</mo></msup></mfenced><mo>T</mo></msup>' assert mathml(Transpose(Adjoint(X) + Y), printer='presentation') == \ '<msup><mfenced><mrow><msup><mi>X</mi><mo>&#x2020;</mo></msup>' \ '<mo>+</mo><mi>Y</mi></mrow></mfenced><mo>T</mo></msup>' assert mathml(Transpose(X), printer='presentation') == \ '<msup><mi>X</mi><mo>T</mo></msup>' assert mathml(Transpose(X + Y), printer='presentation') == \ '<msup><mfenced><mrow><mi>X</mi><mo>+</mo><mi>Y</mi></mrow></mfenced><mo>T</mo></msup>' def test_mathml_special_matrices(): from sympy.matrices import Identity, ZeroMatrix, OneMatrix assert mathml(Identity(4), printer='presentation') == '<mi>&#x1D540;</mi>' assert mathml(ZeroMatrix(2, 2), printer='presentation') == '<mn>&#x1D7D8</mn>' assert mathml(OneMatrix(2, 2), printer='presentation') == '<mn>&#x1D7D9</mn>' def test_mathml_piecewise(): from sympy import Piecewise # Content MathML assert mathml(Piecewise((x, x <= 1), (x**2, True))) == \ '<piecewise><piece><ci>x</ci><apply><leq/><ci>x</ci><cn>1</cn></apply></piece><otherwise><apply><power/><ci>x</ci><cn>2</cn></apply></otherwise></piecewise>' raises(ValueError, lambda: mathml(Piecewise((x, x <= 1)))) def test_issue_17857(): assert mathml(Range(-oo, oo), printer='presentation') == \ '<mfenced close="}" open="{"><mi>&#8230;</mi><mn>-1</mn><mn>0</mn><mn>1</mn><mi>&#8230;</mi></mfenced>' assert mathml(Range(oo, -oo, -1), printer='presentation') == \ '<mfenced close="}" open="{"><mi>&#8230;</mi><mn>1</mn><mn>0</mn><mn>-1</mn><mi>&#8230;</mi></mfenced>'
7c87437c7000428b999972468e50797d035b1f9e6c10f8ad56b3c22bf7de4e34
from sympy.core import (pi, oo, symbols, Rational, Integer, GoldenRatio, EulerGamma, Catalan, Lambda, Dummy, S, Eq, Ne, Le, Lt, Gt, Ge) from sympy.functions import (Piecewise, sin, cos, Abs, exp, ceiling, sqrt, sinh, cosh, tanh, asin, acos, acosh, Max, Min) from sympy.testing.pytest import raises from sympy.printing.jscode import JavascriptCodePrinter from sympy.utilities.lambdify import implemented_function from sympy.tensor import IndexedBase, Idx from sympy.matrices import Matrix, MatrixSymbol from sympy import jscode x, y, z = symbols('x,y,z') def test_printmethod(): assert jscode(Abs(x)) == "Math.abs(x)" def test_jscode_sqrt(): assert jscode(sqrt(x)) == "Math.sqrt(x)" assert jscode(x**0.5) == "Math.sqrt(x)" assert jscode(x**(S.One/3)) == "Math.cbrt(x)" def test_jscode_Pow(): g = implemented_function('g', Lambda(x, 2*x)) assert jscode(x**3) == "Math.pow(x, 3)" assert jscode(x**(y**3)) == "Math.pow(x, Math.pow(y, 3))" assert jscode(1/(g(x)*3.5)**(x - y**x)/(x**2 + y)) == \ "Math.pow(3.5*2*x, -x + Math.pow(y, x))/(Math.pow(x, 2) + y)" assert jscode(x**-1.0) == '1/x' def test_jscode_constants_mathh(): assert jscode(exp(1)) == "Math.E" assert jscode(pi) == "Math.PI" assert jscode(oo) == "Number.POSITIVE_INFINITY" assert jscode(-oo) == "Number.NEGATIVE_INFINITY" def test_jscode_constants_other(): assert jscode( 2*GoldenRatio) == "var GoldenRatio = %s;\n2*GoldenRatio" % GoldenRatio.evalf(17) assert jscode(2*Catalan) == "var Catalan = %s;\n2*Catalan" % Catalan.evalf(17) assert jscode( 2*EulerGamma) == "var EulerGamma = %s;\n2*EulerGamma" % EulerGamma.evalf(17) def test_jscode_Rational(): assert jscode(Rational(3, 7)) == "3/7" assert jscode(Rational(18, 9)) == "2" assert jscode(Rational(3, -7)) == "-3/7" assert jscode(Rational(-3, -7)) == "3/7" def test_Relational(): assert jscode(Eq(x, y)) == "x == y" assert jscode(Ne(x, y)) == "x != y" assert jscode(Le(x, y)) == "x <= y" assert jscode(Lt(x, y)) == "x < y" assert jscode(Gt(x, y)) == "x > y" assert jscode(Ge(x, y)) == "x >= y" def test_jscode_Integer(): assert jscode(Integer(67)) == "67" assert jscode(Integer(-1)) == "-1" def test_jscode_functions(): assert jscode(sin(x) ** cos(x)) == "Math.pow(Math.sin(x), Math.cos(x))" assert jscode(sinh(x) * cosh(x)) == "Math.sinh(x)*Math.cosh(x)" assert jscode(Max(x, y) + Min(x, y)) == "Math.max(x, y) + Math.min(x, y)" assert jscode(tanh(x)*acosh(y)) == "Math.tanh(x)*Math.acosh(y)" assert jscode(asin(x)-acos(y)) == "-Math.acos(y) + Math.asin(x)" 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.evalf(17) 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_jscode_exceptions(): assert jscode(ceiling(x)) == "Math.ceil(x)" assert jscode(Abs(x)) == "Math.abs(x)" def test_jscode_boolean(): assert jscode(x & y) == "x && y" assert jscode(x | y) == "x || y" assert jscode(~x) == "!x" assert jscode(x & y & z) == "x && y && z" assert jscode(x | y | z) == "x || y || z" assert jscode((x & y) | z) == "z || x && y" assert jscode((x | y) & z) == "z && (x || y)" def test_jscode_Piecewise(): expr = Piecewise((x, x < 1), (x**2, True)) p = jscode(expr) s = \ """\ ((x < 1) ? ( x ) : ( Math.pow(x, 2) ))\ """ assert p == s assert jscode(expr, assign_to="c") == ( "if (x < 1) {\n" " c = x;\n" "}\n" "else {\n" " c = Math.pow(x, 2);\n" "}") # Check that Piecewise without a True (default) condition error expr = Piecewise((x, x < 1), (x**2, x > 1), (sin(x), x > 0)) raises(ValueError, lambda: jscode(expr)) def test_jscode_Piecewise_deep(): p = jscode(2*Piecewise((x, x < 1), (x**2, True))) s = \ """\ 2*((x < 1) ? ( x ) : ( Math.pow(x, 2) ))\ """ assert p == s def test_jscode_settings(): raises(TypeError, lambda: jscode(sin(x), method="garbage")) def test_jscode_Indexed(): from sympy.tensor import IndexedBase, Idx from sympy import symbols n, m, o = symbols('n m o', integer=True) i, j, k = Idx('i', n), Idx('j', m), Idx('k', o) p = JavascriptCodePrinter() p._not_c = set() x = IndexedBase('x')[j] assert p._print_Indexed(x) == 'x[j]' A = IndexedBase('A')[i, j] assert p._print_Indexed(A) == 'A[%s]' % (m*i+j) B = IndexedBase('B')[i, j, k] assert p._print_Indexed(B) == 'B[%s]' % (i*o*m+j*o+k) assert p._not_c == set() def test_jscode_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 (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' ' y[i] = A[n*i + j]*x[j] + y[i];\n' ' }\n' '}' ) c = jscode(A[i, j]*x[j], assign_to=y[i]) assert c == s def test_dummy_loops(): i, m = symbols('i m', integer=True, cls=Dummy) x = IndexedBase('x') y = IndexedBase('y') i = Idx(i, m) expected = ( 'for (var i_%(icount)i=0; i_%(icount)i<m_%(mcount)i; i_%(icount)i++){\n' ' y[i_%(icount)i] = x[i_%(icount)i];\n' '}' ) % {'icount': i.label.dummy_index, 'mcount': m.dummy_index} code = jscode(x[i], assign_to=y[i]) assert code == expected def test_jscode_loops_add(): from sympy.tensor import IndexedBase, Idx from sympy import symbols n, m = symbols('n m', integer=True) A = IndexedBase('A') x = IndexedBase('x') y = IndexedBase('y') z = IndexedBase('z') i = Idx('i', m) j = Idx('j', n) s = ( 'for (var i=0; i<m; i++){\n' ' y[i] = x[i] + z[i];\n' '}\n' 'for (var i=0; i<m; i++){\n' ' for (var j=0; j<n; j++){\n' ' y[i] = A[n*i + j]*x[j] + y[i];\n' ' }\n' '}' ) c = jscode(A[i, j]*x[j] + x[i] + z[i], assign_to=y[i]) assert c == s def test_jscode_loops_multiple_contractions(): from sympy.tensor import IndexedBase, Idx from sympy 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 (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] + y[i];\n' % (i*n*o*p + j*o*p + k*p + l, j*o*p + k*p + l) +\ ' }\n' ' }\n' ' }\n' '}' ) c = jscode(b[j, k, l]*a[i, j, k, l], assign_to=y[i]) assert c == s def test_jscode_loops_addfactor(): from sympy.tensor import IndexedBase, Idx from sympy 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_jscode_loops_multiple_terms(): from sympy.tensor import IndexedBase, Idx from sympy 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 (var i=0; i<m; i++){\n' ' y[i] = 0;\n' '}\n' ) s1 = ( 'for (var i=0; i<m; i++){\n' ' for (var j=0; j<n; j++){\n' ' for (var 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 (var i=0; i<m; i++){\n' ' for (var k=0; k<o; k++){\n' ' y[i] = a[%s]*b[k] + y[i];\n' % (i*o + k) +\ ' }\n' '}\n' ) s3 = ( 'for (var i=0; i<m; i++){\n' ' for (var j=0; j<n; j++){\n' ' y[i] = a[%s]*b[j] + y[i];\n' % (i*n + j) +\ ' }\n' '}\n' ) c = jscode( 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_Matrix_printing(): # Test returning a Matrix mat = Matrix([x*y, Piecewise((2 + x, y>0), (y, True)), sin(z)]) A = MatrixSymbol('A', 3, 1) assert jscode(mat, A) == ( "A[0] = x*y;\n" "if (y > 0) {\n" " A[1] = x + 2;\n" "}\n" "else {\n" " A[1] = y;\n" "}\n" "A[2] = Math.sin(z);") # Test using MatrixElements in expressions expr = Piecewise((2*A[2, 0], x > 0), (A[2, 0], True)) + sin(A[1, 0]) + A[0, 0] assert jscode(expr) == ( "((x > 0) ? (\n" " 2*A[2]\n" ")\n" ": (\n" " A[2]\n" ")) + Math.sin(A[1]) + A[0]") # Test using MatrixElements in a Matrix q = MatrixSymbol('q', 5, 1) M = MatrixSymbol('M', 3, 3) m = Matrix([[sin(q[1,0]), 0, cos(q[2,0])], [q[1,0] + q[2,0], q[3, 0], 5], [2*q[4, 0]/q[1,0], sqrt(q[0,0]) + 4, 0]]) assert jscode(m, M) == ( "M[0] = Math.sin(q[1]);\n" "M[1] = 0;\n" "M[2] = Math.cos(q[2]);\n" "M[3] = q[1] + q[2];\n" "M[4] = q[3];\n" "M[5] = 5;\n" "M[6] = 2*q[4]/q[1];\n" "M[7] = Math.sqrt(q[0]) + 4;\n" "M[8] = 0;") def test_MatrixElement_printing(): # test cases for issue #11821 A = MatrixSymbol("A", 1, 3) B = MatrixSymbol("B", 1, 3) C = MatrixSymbol("C", 1, 3) assert(jscode(A[0, 0]) == "A[0]") assert(jscode(3 * A[0, 0]) == "3*A[0]") F = C[0, 0].subs(C, A - B) assert(jscode(F) == "(A - B)[0]")
2c0d57647fbbbbcf33f4e73f23f3032d9cfd2eeba6b79557522dcd463aa1668e
""" Important note on tests in this module - the Theano printing functions use a global cache by default, which means that tests using it will modify global state and thus not be independent from each other. Instead of using the "cache" keyword argument each time, this module uses the theano_code_ and theano_function_ functions defined below which default to using a new, empty cache instead. """ import logging from sympy.external import import_module from sympy.testing.pytest import raises, SKIP theanologger = logging.getLogger('theano.configdefaults') theanologger.setLevel(logging.CRITICAL) theano = import_module('theano') theanologger.setLevel(logging.WARNING) if theano: import numpy as np ts = theano.scalar tt = theano.tensor xt, yt, zt = [tt.scalar(name, 'floatX') for name in 'xyz'] Xt, Yt, Zt = [tt.tensor('floatX', (False, False), name=n) for n in 'XYZ'] else: #bin/test will not execute any tests now disabled = True import sympy as sy from sympy import S from sympy.abc import x, y, z, t from sympy.printing.theanocode import (theano_code, dim_handling, theano_function) # Default set of matrix symbols for testing - make square so we can both # multiply and perform elementwise operations between them. X, Y, Z = [sy.MatrixSymbol(n, 4, 4) for n in 'XYZ'] # For testing AppliedUndef f_t = sy.Function('f')(t) def theano_code_(expr, **kwargs): """ Wrapper for theano_code that uses a new, empty cache by default. """ kwargs.setdefault('cache', {}) return theano_code(expr, **kwargs) def theano_function_(inputs, outputs, **kwargs): """ Wrapper for theano_function that uses a new, empty cache by default. """ kwargs.setdefault('cache', {}) return theano_function(inputs, outputs, **kwargs) def fgraph_of(*exprs): """ Transform SymPy expressions into Theano Computation. Parameters ========== exprs Sympy expressions Returns ======= theano.gof.FunctionGraph """ outs = list(map(theano_code_, exprs)) ins = theano.gof.graph.inputs(outs) ins, outs = theano.gof.graph.clone(ins, outs) return theano.gof.FunctionGraph(ins, outs) def theano_simplify(fgraph): """ Simplify a Theano Computation. Parameters ========== fgraph : theano.gof.FunctionGraph Returns ======= theano.gof.FunctionGraph """ mode = theano.compile.get_default_mode().excluding("fusion") fgraph = fgraph.clone() mode.optimizer.optimize(fgraph) return fgraph def theq(a, b): """ Test two Theano objects for equality. Also accepts numeric types and lists/tuples of supported types. Note - debugprint() has a bug where it will accept numeric types but does not respect the "file" argument and in this case and instead prints the number to stdout and returns an empty string. This can lead to tests passing where they should fail because any two numbers will always compare as equal. To prevent this we treat numbers as a separate case. """ numeric_types = (int, float, np.number) a_is_num = isinstance(a, numeric_types) b_is_num = isinstance(b, numeric_types) # Compare numeric types using regular equality if a_is_num or b_is_num: if not (a_is_num and b_is_num): return False return a == b # Compare sequences element-wise a_is_seq = isinstance(a, (tuple, list)) b_is_seq = isinstance(b, (tuple, list)) if a_is_seq or b_is_seq: if not (a_is_seq and b_is_seq) or type(a) != type(b): return False return list(map(theq, a)) == list(map(theq, b)) # Otherwise, assume debugprint() can handle it astr = theano.printing.debugprint(a, file='str') bstr = theano.printing.debugprint(b, file='str') # Check for bug mentioned above for argname, argval, argstr in [('a', a, astr), ('b', b, bstr)]: if argstr == '': raise TypeError( 'theano.printing.debugprint(%s) returned empty string ' '(%s is instance of %r)' % (argname, argname, type(argval)) ) return astr == bstr def test_example_symbols(): """ Check that the example symbols in this module print to their Theano equivalents, as many of the other tests depend on this. """ assert theq(xt, theano_code_(x)) assert theq(yt, theano_code_(y)) assert theq(zt, theano_code_(z)) assert theq(Xt, theano_code_(X)) assert theq(Yt, theano_code_(Y)) assert theq(Zt, theano_code_(Z)) def test_Symbol(): """ Test printing a Symbol to a theano variable. """ xx = theano_code_(x) assert isinstance(xx, (tt.TensorVariable, ts.ScalarVariable)) assert xx.broadcastable == () assert xx.name == x.name xx2 = theano_code_(x, broadcastables={x: (False,)}) assert xx2.broadcastable == (False,) assert xx2.name == x.name def test_MatrixSymbol(): """ Test printing a MatrixSymbol to a theano variable. """ XX = theano_code_(X) assert isinstance(XX, tt.TensorVariable) assert XX.broadcastable == (False, False) @SKIP # TODO - this is currently not checked but should be implemented def test_MatrixSymbol_wrong_dims(): """ Test MatrixSymbol with invalid broadcastable. """ bcs = [(), (False,), (True,), (True, False), (False, True,), (True, True)] for bc in bcs: with raises(ValueError): theano_code_(X, broadcastables={X: bc}) def test_AppliedUndef(): """ Test printing AppliedUndef instance, which works similarly to Symbol. """ ftt = theano_code_(f_t) assert isinstance(ftt, tt.TensorVariable) assert ftt.broadcastable == () assert ftt.name == 'f_t' def test_add(): expr = x + y comp = theano_code_(expr) assert comp.owner.op == theano.tensor.add def test_trig(): assert theq(theano_code_(sy.sin(x)), tt.sin(xt)) assert theq(theano_code_(sy.tan(x)), tt.tan(xt)) def test_many(): """ Test printing a complex expression with multiple symbols. """ expr = sy.exp(x**2 + sy.cos(y)) * sy.log(2*z) comp = theano_code_(expr) expected = tt.exp(xt**2 + tt.cos(yt)) * tt.log(2*zt) assert theq(comp, expected) def test_dtype(): """ Test specifying specific data types through the dtype argument. """ for dtype in ['float32', 'float64', 'int8', 'int16', 'int32', 'int64']: assert theano_code_(x, dtypes={x: dtype}).type.dtype == dtype # "floatX" type assert theano_code_(x, dtypes={x: 'floatX'}).type.dtype in ('float32', 'float64') # Type promotion assert theano_code_(x + 1, dtypes={x: 'float32'}).type.dtype == 'float32' assert theano_code_(x + y, dtypes={x: 'float64', y: 'float32'}).type.dtype == 'float64' def test_broadcastables(): """ Test the "broadcastables" argument when printing symbol-like objects. """ # No restrictions on shape for s in [x, f_t]: for bc in [(), (False,), (True,), (False, False), (True, False)]: assert theano_code_(s, broadcastables={s: bc}).broadcastable == bc # TODO - matrix broadcasting? def test_broadcasting(): """ Test "broadcastable" attribute after applying element-wise binary op. """ expr = x + y cases = [ [(), (), ()], [(False,), (False,), (False,)], [(True,), (False,), (False,)], [(False, True), (False, False), (False, False)], [(True, False), (False, False), (False, False)], ] for bc1, bc2, bc3 in cases: comp = theano_code_(expr, broadcastables={x: bc1, y: bc2}) assert comp.broadcastable == bc3 def test_MatMul(): expr = X*Y*Z expr_t = theano_code_(expr) assert isinstance(expr_t.owner.op, tt.Dot) assert theq(expr_t, Xt.dot(Yt).dot(Zt)) def test_Transpose(): assert isinstance(theano_code_(X.T).owner.op, tt.DimShuffle) def test_MatAdd(): expr = X+Y+Z assert isinstance(theano_code_(expr).owner.op, tt.Elemwise) def test_Rationals(): assert theq(theano_code_(sy.Integer(2) / 3), tt.true_div(2, 3)) assert theq(theano_code_(S.Half), tt.true_div(1, 2)) def test_Integers(): assert theano_code_(sy.Integer(3)) == 3 def test_factorial(): n = sy.Symbol('n') assert theano_code_(sy.factorial(n)) def test_Derivative(): simp = lambda expr: theano_simplify(fgraph_of(expr)) assert theq(simp(theano_code_(sy.Derivative(sy.sin(x), x, evaluate=False))), simp(theano.grad(tt.sin(xt), xt))) def test_theano_function_simple(): """ Test theano_function() with single output. """ f = theano_function_([x, y], [x+y]) assert f(2, 3) == 5 def test_theano_function_multi(): """ Test theano_function() with multiple outputs. """ f = theano_function_([x, y], [x+y, x-y]) o1, o2 = f(2, 3) assert o1 == 5 assert o2 == -1 def test_theano_function_numpy(): """ Test theano_function() vs Numpy implementation. """ f = theano_function_([x, y], [x+y], dim=1, dtypes={x: 'float64', y: 'float64'}) assert np.linalg.norm(f([1, 2], [3, 4]) - np.asarray([4, 6])) < 1e-9 f = theano_function_([x, y], [x+y], dtypes={x: 'float64', y: 'float64'}, dim=1) xx = np.arange(3).astype('float64') yy = 2*np.arange(3).astype('float64') assert np.linalg.norm(f(xx, yy) - 3*np.arange(3)) < 1e-9 def test_theano_function_matrix(): m = sy.Matrix([[x, y], [z, x + y + z]]) expected = np.array([[1.0, 2.0], [3.0, 1.0 + 2.0 + 3.0]]) f = theano_function_([x, y, z], [m]) np.testing.assert_allclose(f(1.0, 2.0, 3.0), expected) f = theano_function_([x, y, z], [m], scalar=True) np.testing.assert_allclose(f(1.0, 2.0, 3.0), expected) f = theano_function_([x, y, z], [m, m]) assert isinstance(f(1.0, 2.0, 3.0), type([])) np.testing.assert_allclose(f(1.0, 2.0, 3.0)[0], expected) np.testing.assert_allclose(f(1.0, 2.0, 3.0)[1], expected) def test_dim_handling(): assert dim_handling([x], dim=2) == {x: (False, False)} assert dim_handling([x, y], dims={x: 1, y: 2}) == {x: (False, True), y: (False, False)} assert dim_handling([x], broadcastables={x: (False,)}) == {x: (False,)} def test_theano_function_kwargs(): """ Test passing additional kwargs from theano_function() to theano.function(). """ import numpy as np f = theano_function_([x, y, z], [x+y], dim=1, on_unused_input='ignore', dtypes={x: 'float64', y: 'float64', z: 'float64'}) assert np.linalg.norm(f([1, 2], [3, 4], [0, 0]) - np.asarray([4, 6])) < 1e-9 f = theano_function_([x, y, z], [x+y], dtypes={x: 'float64', y: 'float64', z: 'float64'}, dim=1, on_unused_input='ignore') xx = np.arange(3).astype('float64') yy = 2*np.arange(3).astype('float64') zz = 2*np.arange(3).astype('float64') assert np.linalg.norm(f(xx, yy, zz) - 3*np.arange(3)) < 1e-9 def test_theano_function_scalar(): """ Test the "scalar" argument to theano_function(). """ args = [ ([x, y], [x + y], None, [0]), # Single 0d output ([X, Y], [X + Y], None, [2]), # Single 2d output ([x, y], [x + y], {x: 0, y: 1}, [1]), # Single 1d output ([x, y], [x + y, x - y], None, [0, 0]), # Two 0d outputs ([x, y, X, Y], [x + y, X + Y], None, [0, 2]), # One 0d output, one 2d ] # Create and test functions with and without the scalar setting for inputs, outputs, in_dims, out_dims in args: for scalar in [False, True]: f = theano_function_(inputs, outputs, dims=in_dims, scalar=scalar) # Check the theano_function attribute is set whether wrapped or not assert isinstance(f.theano_function, theano.compile.function_module.Function) # Feed in inputs of the appropriate size and get outputs in_values = [ np.ones([1 if bc else 5 for bc in i.type.broadcastable]) for i in f.theano_function.input_storage ] out_values = f(*in_values) if not isinstance(out_values, list): out_values = [out_values] # Check output types and shapes assert len(out_dims) == len(out_values) for d, value in zip(out_dims, out_values): if scalar and d == 0: # Should have been converted to a scalar value assert isinstance(value, np.number) else: # Otherwise should be an array assert isinstance(value, np.ndarray) assert value.ndim == d def test_theano_function_bad_kwarg(): """ Passing an unknown keyword argument to theano_function() should raise an exception. """ raises(Exception, lambda : theano_function_([x], [x+1], foobar=3)) def test_slice(): assert theano_code_(slice(1, 2, 3)) == slice(1, 2, 3) def theq_slice(s1, s2): for attr in ['start', 'stop', 'step']: a1 = getattr(s1, attr) a2 = getattr(s2, attr) if a1 is None or a2 is None: if not (a1 is None or a2 is None): return False elif not theq(a1, a2): return False return True dtypes = {x: 'int32', y: 'int32'} assert theq_slice(theano_code_(slice(x, y), dtypes=dtypes), slice(xt, yt)) assert theq_slice(theano_code_(slice(1, x, 3), dtypes=dtypes), slice(1, xt, 3)) def test_MatrixSlice(): from theano import Constant cache = {} n = sy.Symbol('n', integer=True) X = sy.MatrixSymbol('X', n, n) Y = X[1:2:3, 4:5:6] Yt = theano_code_(Y, cache=cache) s = ts.Scalar('int64') assert tuple(Yt.owner.op.idx_list) == (slice(s, s, s), slice(s, s, s)) assert Yt.owner.inputs[0] == theano_code_(X, cache=cache) # == doesn't work in theano like it does in SymPy. You have to use # equals. assert all(Yt.owner.inputs[i].equals(Constant(s, i)) for i in range(1, 7)) k = sy.Symbol('k') theano_code_(k, dtypes={k: 'int32'}) start, stop, step = 4, k, 2 Y = X[start:stop:step] Yt = theano_code_(Y, dtypes={n: 'int32', k: 'int32'}) # assert Yt.owner.op.idx_list[0].stop == kt def test_BlockMatrix(): n = sy.Symbol('n', integer=True) A, B, C, D = [sy.MatrixSymbol(name, n, n) for name in 'ABCD'] At, Bt, Ct, Dt = map(theano_code_, (A, B, C, D)) Block = sy.BlockMatrix([[A, B], [C, D]]) Blockt = theano_code_(Block) solutions = [tt.join(0, tt.join(1, At, Bt), tt.join(1, Ct, Dt)), tt.join(1, tt.join(0, At, Ct), tt.join(0, Bt, Dt))] assert any(theq(Blockt, solution) for solution in solutions) @SKIP def test_BlockMatrix_Inverse_execution(): k, n = 2, 4 dtype = 'float32' A = sy.MatrixSymbol('A', n, k) B = sy.MatrixSymbol('B', n, n) inputs = A, B output = B.I*A cutsizes = {A: [(n//2, n//2), (k//2, k//2)], B: [(n//2, n//2), (n//2, n//2)]} cutinputs = [sy.blockcut(i, *cutsizes[i]) for i in inputs] cutoutput = output.subs(dict(zip(inputs, cutinputs))) dtypes = dict(zip(inputs, [dtype]*len(inputs))) f = theano_function_(inputs, [output], dtypes=dtypes, cache={}) fblocked = theano_function_(inputs, [sy.block_collapse(cutoutput)], dtypes=dtypes, cache={}) ninputs = [np.random.rand(*x.shape).astype(dtype) for x in inputs] ninputs = [np.arange(n*k).reshape(A.shape).astype(dtype), np.eye(n).astype(dtype)] ninputs[1] += np.ones(B.shape)*1e-5 assert np.allclose(f(*ninputs), fblocked(*ninputs), rtol=1e-5) def test_DenseMatrix(): t = sy.Symbol('theta') for MatrixType in [sy.Matrix, sy.ImmutableMatrix]: X = MatrixType([[sy.cos(t), -sy.sin(t)], [sy.sin(t), sy.cos(t)]]) tX = theano_code_(X) assert isinstance(tX, tt.TensorVariable) assert tX.owner.op == tt.join_ def test_cache_basic(): """ Test single symbol-like objects are cached when printed by themselves. """ # Pairs of objects which should be considered equivalent with respect to caching pairs = [ (x, sy.Symbol('x')), (X, sy.MatrixSymbol('X', *X.shape)), (f_t, sy.Function('f')(sy.Symbol('t'))), ] for s1, s2 in pairs: cache = {} st = theano_code_(s1, cache=cache) # Test hit with same instance assert theano_code_(s1, cache=cache) is st # Test miss with same instance but new cache assert theano_code_(s1, cache={}) is not st # Test hit with different but equivalent instance assert theano_code_(s2, cache=cache) is st def test_global_cache(): """ Test use of the global cache. """ from sympy.printing.theanocode import global_cache backup = dict(global_cache) try: # Temporarily empty global cache global_cache.clear() for s in [x, X, f_t]: st = theano_code(s) assert theano_code(s) is st finally: # Restore global cache global_cache.update(backup) def test_cache_types_distinct(): """ Test that symbol-like objects of different types (Symbol, MatrixSymbol, AppliedUndef) are distinguished by the cache even if they have the same name. """ symbols = [sy.Symbol('f_t'), sy.MatrixSymbol('f_t', 4, 4), f_t] cache = {} # Single shared cache printed = {} for s in symbols: st = theano_code_(s, cache=cache) assert st not in printed.values() printed[s] = st # Check all printed objects are distinct assert len(set(map(id, printed.values()))) == len(symbols) # Check retrieving for s, st in printed.items(): assert theano_code(s, cache=cache) is st def test_symbols_are_created_once(): """ Test that a symbol is cached and reused when it appears in an expression more than once. """ expr = sy.Add(x, x, evaluate=False) comp = theano_code_(expr) assert theq(comp, xt + xt) assert not theq(comp, xt + theano_code_(x)) def test_cache_complex(): """ Test caching on a complicated expression with multiple symbols appearing multiple times. """ expr = x ** 2 + (y - sy.exp(x)) * sy.sin(z - x * y) symbol_names = {s.name for s in expr.free_symbols} expr_t = theano_code_(expr) # Iterate through variables in the Theano computational graph that the # printed expression depends on seen = set() for v in theano.gof.graph.ancestors([expr_t]): # Owner-less, non-constant variables should be our symbols if v.owner is None and not isinstance(v, theano.gof.graph.Constant): # Check it corresponds to a symbol and appears only once assert v.name in symbol_names assert v.name not in seen seen.add(v.name) # Check all were present assert seen == symbol_names def test_Piecewise(): # A piecewise linear expr = sy.Piecewise((0, x<0), (x, x<2), (1, True)) # ___/III result = theano_code_(expr) assert result.owner.op == tt.switch expected = tt.switch(xt<0, 0, tt.switch(xt<2, xt, 1)) assert theq(result, expected) expr = sy.Piecewise((x, x < 0)) result = theano_code_(expr) expected = tt.switch(xt < 0, xt, np.nan) assert theq(result, expected) expr = sy.Piecewise((0, sy.And(x>0, x<2)), \ (x, sy.Or(x>2, x<0))) result = theano_code_(expr) expected = tt.switch(tt.and_(xt>0,xt<2), 0, \ tt.switch(tt.or_(xt>2, xt<0), xt, np.nan)) assert theq(result, expected) def test_Relationals(): assert theq(theano_code_(sy.Eq(x, y)), tt.eq(xt, yt)) # assert theq(theano_code_(sy.Ne(x, y)), tt.neq(xt, yt)) # TODO - implement assert theq(theano_code_(x > y), xt > yt) assert theq(theano_code_(x < y), xt < yt) assert theq(theano_code_(x >= y), xt >= yt) assert theq(theano_code_(x <= y), xt <= yt) def test_complexfunctions(): xt, yt = theano_code(x, dtypes={x:'complex128'}), theano_code(y, dtypes={y: 'complex128'}) from sympy import conjugate from theano.tensor import as_tensor_variable as atv from theano.tensor import complex as cplx assert theq(theano_code(y*conjugate(x)), yt*(xt.conj())) assert theq(theano_code((1+2j)*x), xt*(atv(1.0)+atv(2.0)*cplx(0,1))) def test_constantfunctions(): tf = theano_function([],[1+1j]) assert(tf()==1+1j)
9f56acd7c29a684dc2fd1232374d133a694500afd06663c5e5cb3883427c92a3
from sympy.core import (S, pi, oo, symbols, Function, Rational, Integer, Tuple, Symbol, EulerGamma, GoldenRatio, Catalan, Lambda, Mul, Pow, Mod, Eq, Ne, Le, Lt, Gt, Ge) from sympy.codegen.matrix_nodes import MatrixSolve from sympy.functions import (arg, atan2, bernoulli, beta, ceiling, chebyshevu, chebyshevt, conjugate, DiracDelta, exp, expint, factorial, floor, harmonic, Heaviside, im, laguerre, LambertW, log, Max, Min, Piecewise, polylog, re, RisingFactorial, sign, sinc, sqrt, zeta, binomial, legendre) from sympy.functions import (sin, cos, tan, cot, sec, csc, asin, acos, acot, atan, asec, acsc, sinh, cosh, tanh, coth, csch, sech, asinh, acosh, atanh, acoth, asech, acsch) from sympy.testing.pytest import raises, XFAIL from sympy.utilities.lambdify import implemented_function from sympy.matrices import (eye, Matrix, MatrixSymbol, Identity, HadamardProduct, SparseMatrix, HadamardPower) from sympy.functions.special.bessel import (jn, yn, besselj, bessely, besseli, besselk, hankel1, hankel2, airyai, airybi, airyaiprime, airybiprime) from sympy.functions.special.gamma_functions import (gamma, lowergamma, uppergamma, loggamma, polygamma) from sympy.functions.special.error_functions import (Chi, Ci, erf, erfc, erfi, erfcinv, erfinv, fresnelc, fresnels, li, Shi, Si, Li, erf2) from sympy import octave_code from sympy import octave_code as mcode x, y, z = symbols('x,y,z') def test_Integer(): assert mcode(Integer(67)) == "67" assert mcode(Integer(-1)) == "-1" def test_Rational(): assert mcode(Rational(3, 7)) == "3/7" assert mcode(Rational(18, 9)) == "2" assert mcode(Rational(3, -7)) == "-3/7" assert mcode(Rational(-3, -7)) == "3/7" assert mcode(x + Rational(3, 7)) == "x + 3/7" assert mcode(Rational(3, 7)*x) == "3*x/7" def test_Relational(): assert mcode(Eq(x, y)) == "x == y" assert mcode(Ne(x, y)) == "x != y" assert mcode(Le(x, y)) == "x <= y" assert mcode(Lt(x, y)) == "x < y" assert mcode(Gt(x, y)) == "x > y" assert mcode(Ge(x, y)) == "x >= y" def test_Function(): assert mcode(sin(x) ** cos(x)) == "sin(x).^cos(x)" assert mcode(sign(x)) == "sign(x)" assert mcode(exp(x)) == "exp(x)" assert mcode(log(x)) == "log(x)" assert mcode(factorial(x)) == "factorial(x)" assert mcode(floor(x)) == "floor(x)" assert mcode(atan2(y, x)) == "atan2(y, x)" assert mcode(beta(x, y)) == 'beta(x, y)' assert mcode(polylog(x, y)) == 'polylog(x, y)' assert mcode(harmonic(x)) == 'harmonic(x)' assert mcode(bernoulli(x)) == "bernoulli(x)" assert mcode(bernoulli(x, y)) == "bernoulli(x, y)" assert mcode(legendre(x, y)) == "legendre(x, y)" def test_Function_change_name(): assert mcode(abs(x)) == "abs(x)" assert mcode(ceiling(x)) == "ceil(x)" assert mcode(arg(x)) == "angle(x)" assert mcode(im(x)) == "imag(x)" assert mcode(re(x)) == "real(x)" assert mcode(conjugate(x)) == "conj(x)" assert mcode(chebyshevt(y, x)) == "chebyshevT(y, x)" assert mcode(chebyshevu(y, x)) == "chebyshevU(y, x)" assert mcode(laguerre(x, y)) == "laguerreL(x, y)" assert mcode(Chi(x)) == "coshint(x)" assert mcode(Shi(x)) == "sinhint(x)" assert mcode(Ci(x)) == "cosint(x)" assert mcode(Si(x)) == "sinint(x)" assert mcode(li(x)) == "logint(x)" assert mcode(loggamma(x)) == "gammaln(x)" assert mcode(polygamma(x, y)) == "psi(x, y)" assert mcode(RisingFactorial(x, y)) == "pochhammer(x, y)" assert mcode(DiracDelta(x)) == "dirac(x)" assert mcode(DiracDelta(x, 3)) == "dirac(3, x)" assert mcode(Heaviside(x)) == "heaviside(x)" assert mcode(Heaviside(x, y)) == "heaviside(x, y)" assert mcode(binomial(x, y)) == "bincoeff(x, y)" assert mcode(Mod(x, y)) == "mod(x, y)" def test_minmax(): assert mcode(Max(x, y) + Min(x, y)) == "max(x, y) + min(x, y)" assert mcode(Max(x, y, z)) == "max(x, max(y, z))" assert mcode(Min(x, y, z)) == "min(x, min(y, z))" def test_Pow(): assert mcode(x**3) == "x.^3" assert mcode(x**(y**3)) == "x.^(y.^3)" assert mcode(x**Rational(2, 3)) == 'x.^(2/3)' g = implemented_function('g', Lambda(x, 2*x)) assert mcode(1/(g(x)*3.5)**(x - y**x)/(x**2 + y)) == \ "(3.5*2*x).^(-x + y.^x)./(x.^2 + y)" # For issue 14160 assert mcode(Mul(-2, x, Pow(Mul(y,y,evaluate=False), -1, evaluate=False), evaluate=False)) == '-2*x./(y.*y)' def test_basic_ops(): assert mcode(x*y) == "x.*y" assert mcode(x + y) == "x + y" assert mcode(x - y) == "x - y" assert mcode(-x) == "-x" def test_1_over_x_and_sqrt(): # 1.0 and 0.5 would do something different in regular StrPrinter, # but these are exact in IEEE floating point so no different here. assert mcode(1/x) == '1./x' assert mcode(x**-1) == mcode(x**-1.0) == '1./x' assert mcode(1/sqrt(x)) == '1./sqrt(x)' assert mcode(x**-S.Half) == mcode(x**-0.5) == '1./sqrt(x)' assert mcode(sqrt(x)) == 'sqrt(x)' assert mcode(x**S.Half) == mcode(x**0.5) == 'sqrt(x)' assert mcode(1/pi) == '1/pi' assert mcode(pi**-1) == mcode(pi**-1.0) == '1/pi' assert mcode(pi**-0.5) == '1/sqrt(pi)' def test_mix_number_mult_symbols(): assert mcode(3*x) == "3*x" assert mcode(pi*x) == "pi*x" assert mcode(3/x) == "3./x" assert mcode(pi/x) == "pi./x" assert mcode(x/3) == "x/3" assert mcode(x/pi) == "x/pi" assert mcode(x*y) == "x.*y" assert mcode(3*x*y) == "3*x.*y" assert mcode(3*pi*x*y) == "3*pi*x.*y" assert mcode(x/y) == "x./y" assert mcode(3*x/y) == "3*x./y" assert mcode(x*y/z) == "x.*y./z" assert mcode(x/y*z) == "x.*z./y" assert mcode(1/x/y) == "1./(x.*y)" assert mcode(2*pi*x/y/z) == "2*pi*x./(y.*z)" assert mcode(3*pi/x) == "3*pi./x" assert mcode(S(3)/5) == "3/5" assert mcode(S(3)/5*x) == "3*x/5" assert mcode(x/y/z) == "x./(y.*z)" assert mcode((x+y)/z) == "(x + y)./z" assert mcode((x+y)/(z+x)) == "(x + y)./(x + z)" assert mcode((x+y)/EulerGamma) == "(x + y)/%s" % EulerGamma.evalf(17) assert mcode(x/3/pi) == "x/(3*pi)" assert mcode(S(3)/5*x*y/pi) == "3*x.*y/(5*pi)" def test_mix_number_pow_symbols(): assert mcode(pi**3) == 'pi^3' assert mcode(x**2) == 'x.^2' assert mcode(x**(pi**3)) == 'x.^(pi^3)' assert mcode(x**y) == 'x.^y' assert mcode(x**(y**z)) == 'x.^(y.^z)' assert mcode((x**y)**z) == '(x.^y).^z' def test_imag(): I = S('I') assert mcode(I) == "1i" assert mcode(5*I) == "5i" assert mcode((S(3)/2)*I) == "3*1i/2" assert mcode(3+4*I) == "3 + 4i" assert mcode(sqrt(3)*I) == "sqrt(3)*1i" def test_constants(): assert mcode(pi) == "pi" assert mcode(oo) == "inf" assert mcode(-oo) == "-inf" assert mcode(S.NegativeInfinity) == "-inf" assert mcode(S.NaN) == "NaN" assert mcode(S.Exp1) == "exp(1)" assert mcode(exp(1)) == "exp(1)" def test_constants_other(): assert mcode(2*GoldenRatio) == "2*(1+sqrt(5))/2" assert mcode(2*Catalan) == "2*%s" % Catalan.evalf(17) assert mcode(2*EulerGamma) == "2*%s" % EulerGamma.evalf(17) def test_boolean(): assert mcode(x & y) == "x & y" assert mcode(x | y) == "x | y" assert mcode(~x) == "~x" assert mcode(x & y & z) == "x & y & z" assert mcode(x | y | z) == "x | y | z" assert mcode((x & y) | z) == "z | x & y" assert mcode((x | y) & z) == "z & (x | y)" def test_KroneckerDelta(): from sympy.functions import KroneckerDelta assert mcode(KroneckerDelta(x, y)) == "double(x == y)" assert mcode(KroneckerDelta(x, y + 1)) == "double(x == (y + 1))" assert mcode(KroneckerDelta(2**x, y)) == "double((2.^x) == y)" def test_Matrices(): assert mcode(Matrix(1, 1, [10])) == "10" A = Matrix([[1, sin(x/2), abs(x)], [0, 1, pi], [0, exp(1), ceiling(x)]]); expected = "[1 sin(x/2) abs(x); 0 1 pi; 0 exp(1) ceil(x)]" assert mcode(A) == expected # row and columns assert mcode(A[:,0]) == "[1; 0; 0]" assert mcode(A[0,:]) == "[1 sin(x/2) abs(x)]" # empty matrices assert mcode(Matrix(0, 0, [])) == '[]' assert mcode(Matrix(0, 3, [])) == 'zeros(0, 3)' # annoying to read but correct assert mcode(Matrix([[x, x - y, -y]])) == "[x x - y -y]" def test_vector_entries_hadamard(): # For a row or column, user might to use the other dimension A = Matrix([[1, sin(2/x), 3*pi/x/5]]) assert mcode(A) == "[1 sin(2./x) 3*pi./(5*x)]" assert mcode(A.T) == "[1; sin(2./x); 3*pi./(5*x)]" @XFAIL def test_Matrices_entries_not_hadamard(): # For Matrix with col >= 2, row >= 2, they need to be scalars # FIXME: is it worth worrying about this? Its not wrong, just # leave it user's responsibility to put scalar data for x. A = Matrix([[1, sin(2/x), 3*pi/x/5], [1, 2, x*y]]) expected = ("[1 sin(2/x) 3*pi/(5*x);\n" "1 2 x*y]") # <- we give x.*y assert mcode(A) == expected def test_MatrixSymbol(): n = Symbol('n', integer=True) A = MatrixSymbol('A', n, n) B = MatrixSymbol('B', n, n) assert mcode(A*B) == "A*B" assert mcode(B*A) == "B*A" assert mcode(2*A*B) == "2*A*B" assert mcode(B*2*A) == "2*B*A" assert mcode(A*(B + 3*Identity(n))) == "A*(3*eye(n) + B)" assert mcode(A**(x**2)) == "A^(x.^2)" assert mcode(A**3) == "A^3" assert mcode(A**S.Half) == "A^(1/2)" def test_MatrixSolve(): n = Symbol('n', integer=True) A = MatrixSymbol('A', n, n) x = MatrixSymbol('x', n, 1) assert mcode(MatrixSolve(A, x)) == "A \\ x" def test_special_matrices(): assert mcode(6*Identity(3)) == "6*eye(3)" def test_containers(): assert mcode([1, 2, 3, [4, 5, [6, 7]], 8, [9, 10], 11]) == \ "{1, 2, 3, {4, 5, {6, 7}}, 8, {9, 10}, 11}" assert mcode((1, 2, (3, 4))) == "{1, 2, {3, 4}}" assert mcode([1]) == "{1}" assert mcode((1,)) == "{1}" assert mcode(Tuple(*[1, 2, 3])) == "{1, 2, 3}" assert mcode((1, x*y, (3, x**2))) == "{1, x.*y, {3, x.^2}}" # scalar, matrix, empty matrix and empty list assert mcode((1, eye(3), Matrix(0, 0, []), [])) == "{1, [1 0 0; 0 1 0; 0 0 1], [], {}}" def test_octave_noninline(): source = mcode((x+y)/Catalan, assign_to='me', inline=False) expected = ( "Catalan = %s;\n" "me = (x + y)/Catalan;" ) % Catalan.evalf(17) assert source == expected def test_octave_piecewise(): expr = Piecewise((x, x < 1), (x**2, True)) assert mcode(expr) == "((x < 1).*(x) + (~(x < 1)).*(x.^2))" assert mcode(expr, assign_to="r") == ( "r = ((x < 1).*(x) + (~(x < 1)).*(x.^2));") assert mcode(expr, assign_to="r", inline=False) == ( "if (x < 1)\n" " r = x;\n" "else\n" " r = x.^2;\n" "end") expr = Piecewise((x**2, x < 1), (x**3, x < 2), (x**4, x < 3), (x**5, True)) expected = ("((x < 1).*(x.^2) + (~(x < 1)).*( ...\n" "(x < 2).*(x.^3) + (~(x < 2)).*( ...\n" "(x < 3).*(x.^4) + (~(x < 3)).*(x.^5))))") assert mcode(expr) == expected assert mcode(expr, assign_to="r") == "r = " + expected + ";" assert mcode(expr, assign_to="r", inline=False) == ( "if (x < 1)\n" " r = x.^2;\n" "elseif (x < 2)\n" " r = x.^3;\n" "elseif (x < 3)\n" " r = x.^4;\n" "else\n" " r = x.^5;\n" "end") # Check that Piecewise without a True (default) condition error expr = Piecewise((x, x < 1), (x**2, x > 1), (sin(x), x > 0)) raises(ValueError, lambda: mcode(expr)) def test_octave_piecewise_times_const(): pw = Piecewise((x, x < 1), (x**2, True)) assert mcode(2*pw) == "2*((x < 1).*(x) + (~(x < 1)).*(x.^2))" assert mcode(pw/x) == "((x < 1).*(x) + (~(x < 1)).*(x.^2))./x" assert mcode(pw/(x*y)) == "((x < 1).*(x) + (~(x < 1)).*(x.^2))./(x.*y)" assert mcode(pw/3) == "((x < 1).*(x) + (~(x < 1)).*(x.^2))/3" def test_octave_matrix_assign_to(): A = Matrix([[1, 2, 3]]) assert mcode(A, assign_to='a') == "a = [1 2 3];" A = Matrix([[1, 2], [3, 4]]) assert mcode(A, assign_to='A') == "A = [1 2; 3 4];" def test_octave_matrix_assign_to_more(): # assigning to Symbol or MatrixSymbol requires lhs/rhs match A = Matrix([[1, 2, 3]]) B = MatrixSymbol('B', 1, 3) C = MatrixSymbol('C', 2, 3) assert mcode(A, assign_to=B) == "B = [1 2 3];" raises(ValueError, lambda: mcode(A, assign_to=x)) raises(ValueError, lambda: mcode(A, assign_to=C)) def test_octave_matrix_1x1(): A = Matrix([[3]]) B = MatrixSymbol('B', 1, 1) C = MatrixSymbol('C', 1, 2) assert mcode(A, assign_to=B) == "B = 3;" # FIXME? #assert mcode(A, assign_to=x) == "x = 3;" raises(ValueError, lambda: mcode(A, assign_to=C)) def test_octave_matrix_elements(): A = Matrix([[x, 2, x*y]]) assert mcode(A[0, 0]**2 + A[0, 1] + A[0, 2]) == "x.^2 + x.*y + 2" A = MatrixSymbol('AA', 1, 3) assert mcode(A) == "AA" assert mcode(A[0, 0]**2 + sin(A[0,1]) + A[0,2]) == \ "sin(AA(1, 2)) + AA(1, 1).^2 + AA(1, 3)" assert mcode(sum(A)) == "AA(1, 1) + AA(1, 2) + AA(1, 3)" def test_octave_boolean(): assert mcode(True) == "true" assert mcode(S.true) == "true" assert mcode(False) == "false" assert mcode(S.false) == "false" def test_octave_not_supported(): assert mcode(S.ComplexInfinity) == ( "% Not supported in Octave:\n" "% ComplexInfinity\n" "zoo" ) f = Function('f') assert mcode(f(x).diff(x)) == ( "% Not supported in Octave:\n" "% Derivative\n" "Derivative(f(x), x)" ) def test_octave_not_supported_not_on_whitelist(): from sympy import assoc_laguerre assert mcode(assoc_laguerre(x, y, z)) == ( "% Not supported in Octave:\n" "% assoc_laguerre\n" "assoc_laguerre(x, y, z)" ) def test_octave_expint(): assert mcode(expint(1, x)) == "expint(x)" assert mcode(expint(2, x)) == ( "% Not supported in Octave:\n" "% expint\n" "expint(2, x)" ) assert mcode(expint(y, x)) == ( "% Not supported in Octave:\n" "% expint\n" "expint(y, x)" ) def test_trick_indent_with_end_else_words(): # words starting with "end" or "else" do not confuse the indenter t1 = S('endless'); t2 = S('elsewhere'); pw = Piecewise((t1, x < 0), (t2, x <= 1), (1, True)) assert mcode(pw, inline=False) == ( "if (x < 0)\n" " endless\n" "elseif (x <= 1)\n" " elsewhere\n" "else\n" " 1\n" "end") def test_hadamard(): A = MatrixSymbol('A', 3, 3) B = MatrixSymbol('B', 3, 3) v = MatrixSymbol('v', 3, 1) h = MatrixSymbol('h', 1, 3) C = HadamardProduct(A, B) n = Symbol('n') assert mcode(C) == "A.*B" assert mcode(C*v) == "(A.*B)*v" assert mcode(h*C*v) == "h*(A.*B)*v" assert mcode(C*A) == "(A.*B)*A" # mixing Hadamard and scalar strange b/c we vectorize scalars assert mcode(C*x*y) == "(x.*y)*(A.*B)" # Testing HadamardPower: assert mcode(HadamardPower(A, n)) == "A.**n" assert mcode(HadamardPower(A, 1+n)) == "A.**(n + 1)" assert mcode(HadamardPower(A*B.T, 1+n)) == "(A*B.T).**(n + 1)" def test_sparse(): M = SparseMatrix(5, 6, {}) M[2, 2] = 10; M[1, 2] = 20; M[1, 3] = 22; M[0, 3] = 30; M[3, 0] = x*y; assert mcode(M) == ( "sparse([4 2 3 1 2], [1 3 3 4 4], [x.*y 20 10 30 22], 5, 6)" ) def test_sinc(): assert mcode(sinc(x)) == 'sinc(x/pi)' assert mcode(sinc((x + 3))) == 'sinc((x + 3)/pi)' assert mcode(sinc(pi*(x + 3))) == 'sinc(x + 3)' def test_trigfun(): for f in (sin, cos, tan, cot, sec, csc, asin, acos, acot, atan, asec, acsc, sinh, cosh, tanh, coth, csch, sech, asinh, acosh, atanh, acoth, asech, acsch): assert octave_code(f(x) == f.__name__ + '(x)') def test_specfun(): n = Symbol('n') for f in [besselj, bessely, besseli, besselk]: assert octave_code(f(n, x)) == f.__name__ + '(n, x)' for f in (erfc, erfi, erf, erfinv, erfcinv, fresnelc, fresnels, gamma): assert octave_code(f(x)) == f.__name__ + '(x)' assert octave_code(hankel1(n, x)) == 'besselh(n, 1, x)' assert octave_code(hankel2(n, x)) == 'besselh(n, 2, x)' assert octave_code(airyai(x)) == 'airy(0, x)' assert octave_code(airyaiprime(x)) == 'airy(1, x)' assert octave_code(airybi(x)) == 'airy(2, x)' assert octave_code(airybiprime(x)) == 'airy(3, x)' assert octave_code(uppergamma(n, x)) == '(gammainc(x, n, \'upper\').*gamma(n))' assert octave_code(lowergamma(n, x)) == '(gammainc(x, n).*gamma(n))' assert octave_code(z**lowergamma(n, x)) == 'z.^(gammainc(x, n).*gamma(n))' assert octave_code(jn(n, x)) == 'sqrt(2)*sqrt(pi)*sqrt(1./x).*besselj(n + 1/2, x)/2' assert octave_code(yn(n, x)) == 'sqrt(2)*sqrt(pi)*sqrt(1./x).*bessely(n + 1/2, x)/2' assert octave_code(LambertW(x)) == 'lambertw(x)' assert octave_code(LambertW(x, n)) == 'lambertw(n, x)' def test_MatrixElement_printing(): # test cases for issue #11821 A = MatrixSymbol("A", 1, 3) B = MatrixSymbol("B", 1, 3) C = MatrixSymbol("C", 1, 3) assert mcode(A[0, 0]) == "A(1, 1)" assert mcode(3 * A[0, 0]) == "3*A(1, 1)" F = C[0, 0].subs(C, A - B) assert mcode(F) == "(A - B)(1, 1)" def test_zeta_printing_issue_14820(): assert octave_code(zeta(x)) == 'zeta(x)' assert octave_code(zeta(x, y)) == '% Not supported in Octave:\n% zeta\nzeta(x, y)' def test_automatic_rewrite(): assert octave_code(Li(x)) == 'logint(x) - logint(2)' assert octave_code(erf2(x, y)) == '-erf(x) + erf(y)'
b6d2f2d5757ede003cc821d066683cf2cbbd8fa347f2a3b6fb258fe37be299f7
from sympy.core import (S, pi, oo, symbols, Function, Rational, Integer, Tuple, Symbol, Eq, Ne, Le, Lt, Gt, Ge) from sympy.core import EulerGamma, GoldenRatio, Catalan, Lambda, Mul, Pow from sympy.functions import Piecewise, sqrt, ceiling, exp, sin, cos from sympy.testing.pytest import raises from sympy.utilities.lambdify import implemented_function from sympy.matrices import (eye, Matrix, MatrixSymbol, Identity, HadamardProduct, SparseMatrix) from sympy.functions.special.bessel import besseli from sympy import maple_code x, y, z = symbols('x,y,z') def test_Integer(): assert maple_code(Integer(67)) == "67" assert maple_code(Integer(-1)) == "-1" def test_Rational(): assert maple_code(Rational(3, 7)) == "3/7" assert maple_code(Rational(18, 9)) == "2" assert maple_code(Rational(3, -7)) == "-3/7" assert maple_code(Rational(-3, -7)) == "3/7" assert maple_code(x + Rational(3, 7)) == "x + 3/7" assert maple_code(Rational(3, 7) * x) == '(3/7)*x' def test_Relational(): assert maple_code(Eq(x, y)) == "x = y" assert maple_code(Ne(x, y)) == "x <> y" assert maple_code(Le(x, y)) == "x <= y" assert maple_code(Lt(x, y)) == "x < y" assert maple_code(Gt(x, y)) == "x > y" assert maple_code(Ge(x, y)) == "x >= y" def test_Function(): assert maple_code(sin(x) ** cos(x)) == "sin(x)^cos(x)" assert maple_code(abs(x)) == "abs(x)" assert maple_code(ceiling(x)) == "ceil(x)" def test_Pow(): assert maple_code(x ** 3) == "x^3" assert maple_code(x ** (y ** 3)) == "x^(y^3)" assert maple_code((x ** 3) ** y) == "(x^3)^y" assert maple_code(x ** Rational(2, 3)) == 'x^(2/3)' g = implemented_function('g', Lambda(x, 2 * x)) assert maple_code(1 / (g(x) * 3.5) ** (x - y ** x) / (x ** 2 + y)) == \ "(3.5*2*x)^(-x + y^x)/(x^2 + y)" # For issue 14160 assert maple_code(Mul(-2, x, Pow(Mul(y, y, evaluate=False), -1, evaluate=False), evaluate=False)) == '-2*x/(y*y)' def test_basic_ops(): assert maple_code(x * y) == "x*y" assert maple_code(x + y) == "x + y" assert maple_code(x - y) == "x - y" assert maple_code(-x) == "-x" def test_1_over_x_and_sqrt(): # 1.0 and 0.5 would do something different in regular StrPrinter, # but these are exact in IEEE floating point so no different here. assert maple_code(1 / x) == '1/x' assert maple_code(x ** -1) == maple_code(x ** -1.0) == '1/x' assert maple_code(1 / sqrt(x)) == '1/sqrt(x)' assert maple_code(x ** -S.Half) == maple_code(x ** -0.5) == '1/sqrt(x)' assert maple_code(sqrt(x)) == 'sqrt(x)' assert maple_code(x ** S.Half) == maple_code(x ** 0.5) == 'sqrt(x)' assert maple_code(1 / pi) == '1/Pi' assert maple_code(pi ** -1) == maple_code(pi ** -1.0) == '1/Pi' assert maple_code(pi ** -0.5) == '1/sqrt(Pi)' def test_mix_number_mult_symbols(): assert maple_code(3 * x) == "3*x" assert maple_code(pi * x) == "Pi*x" assert maple_code(3 / x) == "3/x" assert maple_code(pi / x) == "Pi/x" assert maple_code(x / 3) == '(1/3)*x' assert maple_code(x / pi) == "x/Pi" assert maple_code(x * y) == "x*y" assert maple_code(3 * x * y) == "3*x*y" assert maple_code(3 * pi * x * y) == "3*Pi*x*y" assert maple_code(x / y) == "x/y" assert maple_code(3 * x / y) == "3*x/y" assert maple_code(x * y / z) == "x*y/z" assert maple_code(x / y * z) == "x*z/y" assert maple_code(1 / x / y) == "1/(x*y)" assert maple_code(2 * pi * x / y / z) == "2*Pi*x/(y*z)" assert maple_code(3 * pi / x) == "3*Pi/x" assert maple_code(S(3) / 5) == "3/5" assert maple_code(S(3) / 5 * x) == '(3/5)*x' assert maple_code(x / y / z) == "x/(y*z)" assert maple_code((x + y) / z) == "(x + y)/z" assert maple_code((x + y) / (z + x)) == "(x + y)/(x + z)" assert maple_code((x + y) / EulerGamma) == '(x + y)/gamma' assert maple_code(x / 3 / pi) == '(1/3)*x/Pi' assert maple_code(S(3) / 5 * x * y / pi) == '(3/5)*x*y/Pi' def test_mix_number_pow_symbols(): assert maple_code(pi ** 3) == 'Pi^3' assert maple_code(x ** 2) == 'x^2' assert maple_code(x ** (pi ** 3)) == 'x^(Pi^3)' assert maple_code(x ** y) == 'x^y' assert maple_code(x ** (y ** z)) == 'x^(y^z)' assert maple_code((x ** y) ** z) == '(x^y)^z' def test_imag(): I = S('I') assert maple_code(I) == "I" assert maple_code(5 * I) == "5*I" assert maple_code((S(3) / 2) * I) == "(3/2)*I" assert maple_code(3 + 4 * I) == "3 + 4*I" def test_constants(): assert maple_code(pi) == "Pi" assert maple_code(oo) == "infinity" assert maple_code(-oo) == "-infinity" assert maple_code(S.NegativeInfinity) == "-infinity" assert maple_code(S.NaN) == "undefined" assert maple_code(S.Exp1) == "exp(1)" assert maple_code(exp(1)) == "exp(1)" def test_constants_other(): assert maple_code(2 * GoldenRatio) == '2*(1/2 + (1/2)*sqrt(5))' assert maple_code(2 * Catalan) == '2*Catalan' assert maple_code(2 * EulerGamma) == "2*gamma" def test_boolean(): assert maple_code(x & y) == "x && y" assert maple_code(x | y) == "x || y" assert maple_code(~x) == "!x" assert maple_code(x & y & z) == "x && y && z" assert maple_code(x | y | z) == "x || y || z" assert maple_code((x & y) | z) == "z || x && y" assert maple_code((x | y) & z) == "z && (x || y)" def test_Matrices(): assert maple_code(Matrix(1, 1, [10])) == \ 'Matrix([[10]], storage = rectangular)' A = Matrix([[1, sin(x / 2), abs(x)], [0, 1, pi], [0, exp(1), ceiling(x)]]) expected = \ 'Matrix(' \ '[[1, sin((1/2)*x), abs(x)],' \ ' [0, 1, Pi],' \ ' [0, exp(1), ceil(x)]], ' \ 'storage = rectangular)' assert maple_code(A) == expected # row and columns assert maple_code(A[:, 0]) == \ 'Matrix([[1], [0], [0]], storage = rectangular)' assert maple_code(A[0, :]) == \ 'Matrix([[1, sin((1/2)*x), abs(x)]], storage = rectangular)' assert maple_code(Matrix([[x, x - y, -y]])) == \ 'Matrix([[x, x - y, -y]], storage = rectangular)' # empty matrices assert maple_code(Matrix(0, 0, [])) == \ 'Matrix([], storage = rectangular)' assert maple_code(Matrix(0, 3, [])) == \ 'Matrix([], storage = rectangular)' def test_SparseMatrices(): assert maple_code(SparseMatrix(Identity(2))) == 'Matrix([[1, 0], [0, 1]], storage = sparse)' def test_vector_entries_hadamard(): # For a row or column, user might to use the other dimension A = Matrix([[1, sin(2 / x), 3 * pi / x / 5]]) assert maple_code(A) == \ 'Matrix([[1, sin(2/x), (3/5)*Pi/x]], storage = rectangular)' assert maple_code(A.T) == \ 'Matrix([[1], [sin(2/x)], [(3/5)*Pi/x]], storage = rectangular)' def test_Matrices_entries_not_hadamard(): A = Matrix([[1, sin(2 / x), 3 * pi / x / 5], [1, 2, x * y]]) expected = \ 'Matrix([[1, sin(2/x), (3/5)*Pi/x], [1, 2, x*y]], ' \ 'storage = rectangular)' assert maple_code(A) == expected def test_MatrixSymbol(): n = Symbol('n', integer=True) A = MatrixSymbol('A', n, n) B = MatrixSymbol('B', n, n) assert maple_code(A * B) == "A.B" assert maple_code(B * A) == "B.A" assert maple_code(2 * A * B) == "2*A.B" assert maple_code(B * 2 * A) == "2*B.A" assert maple_code( A * (B + 3 * Identity(n))) == "A.(3*Matrix(n, shape = identity) + B)" assert maple_code(A ** (x ** 2)) == "MatrixPower(A, x^2)" assert maple_code(A ** 3) == "MatrixPower(A, 3)" assert maple_code(A ** (S.Half)) == "MatrixPower(A, 1/2)" def test_special_matrices(): assert maple_code(6 * Identity(3)) == "6*Matrix([[1, 0, 0], [0, 1, 0], [0, 0, 1]], storage = sparse)" assert maple_code(Identity(x)) == 'Matrix(x, shape = identity)' def test_containers(): assert maple_code([1, 2, 3, [4, 5, [6, 7]], 8, [9, 10], 11]) == \ "[1, 2, 3, [4, 5, [6, 7]], 8, [9, 10], 11]" assert maple_code((1, 2, (3, 4))) == "[1, 2, [3, 4]]" assert maple_code([1]) == "[1]" assert maple_code((1,)) == "[1]" assert maple_code(Tuple(*[1, 2, 3])) == "[1, 2, 3]" assert maple_code((1, x * y, (3, x ** 2))) == "[1, x*y, [3, x^2]]" # scalar, matrix, empty matrix and empty list assert maple_code((1, eye(3), Matrix(0, 0, []), [])) == \ "[1, Matrix([[1, 0, 0], [0, 1, 0], [0, 0, 1]], storage = rectangular), Matrix([], storage = rectangular), []]" def test_maple_noninline(): source = maple_code((x + y)/Catalan, assign_to='me', inline=False) expected = "me := (x + y)/Catalan" assert source == expected def test_maple_matrix_assign_to(): A = Matrix([[1, 2, 3]]) assert maple_code(A, assign_to='a') == "a := Matrix([[1, 2, 3]], storage = rectangular)" A = Matrix([[1, 2], [3, 4]]) assert maple_code(A, assign_to='A') == "A := Matrix([[1, 2], [3, 4]], storage = rectangular)" def test_maple_matrix_assign_to_more(): # assigning to Symbol or MatrixSymbol requires lhs/rhs match A = Matrix([[1, 2, 3]]) B = MatrixSymbol('B', 1, 3) C = MatrixSymbol('C', 2, 3) assert maple_code(A, assign_to=B) == "B := Matrix([[1, 2, 3]], storage = rectangular)" raises(ValueError, lambda: maple_code(A, assign_to=x)) raises(ValueError, lambda: maple_code(A, assign_to=C)) def test_maple_matrix_1x1(): A = Matrix([[3]]) assert maple_code(A, assign_to='B') == "B := Matrix([[3]], storage = rectangular)" def test_maple_matrix_elements(): A = Matrix([[x, 2, x * y]]) assert maple_code(A[0, 0] ** 2 + A[0, 1] + A[0, 2]) == "x^2 + x*y + 2" AA = MatrixSymbol('AA', 1, 3) assert maple_code(AA) == "AA" assert maple_code(AA[0, 0] ** 2 + sin(AA[0, 1]) + AA[0, 2]) == \ "sin(AA[1, 2]) + AA[1, 1]^2 + AA[1, 3]" assert maple_code(sum(AA)) == "AA[1, 1] + AA[1, 2] + AA[1, 3]" def test_maple_boolean(): assert maple_code(True) == "true" assert maple_code(S.true) == "true" assert maple_code(False) == "false" assert maple_code(S.false) == "false" def test_sparse(): M = SparseMatrix(5, 6, {}) M[2, 2] = 10 M[1, 2] = 20 M[1, 3] = 22 M[0, 3] = 30 M[3, 0] = x * y assert maple_code(M) == \ 'Matrix([[0, 0, 0, 30, 0, 0],' \ ' [0, 0, 20, 22, 0, 0],' \ ' [0, 0, 10, 0, 0, 0],' \ ' [x*y, 0, 0, 0, 0, 0],' \ ' [0, 0, 0, 0, 0, 0]], ' \ 'storage = sparse)' # Not an important point. def test_maple_not_supported(): assert maple_code(S.ComplexInfinity) == ( "# Not supported in maple:\n" "# ComplexInfinity\n" "zoo" ) # PROBLEM def test_MatrixElement_printing(): # test cases for issue #11821 A = MatrixSymbol("A", 1, 3) B = MatrixSymbol("B", 1, 3) assert (maple_code(A[0, 0]) == "A[1, 1]") assert (maple_code(3 * A[0, 0]) == "3*A[1, 1]") F = A-B assert (maple_code(F[0,0]) == "A[1, 1] - B[1, 1]") def test_hadamard(): A = MatrixSymbol('A', 3, 3) B = MatrixSymbol('B', 3, 3) v = MatrixSymbol('v', 3, 1) h = MatrixSymbol('h', 1, 3) C = HadamardProduct(A, B) assert maple_code(C) == "A*B" assert maple_code(C * v) == "(A*B).v" # HadamardProduct is higher than dot product. assert maple_code(h * C * v) == "h.(A*B).v" assert maple_code(C * A) == "(A*B).A" # mixing Hadamard and scalar strange b/c we vectorize scalars assert maple_code(C * x * y) == "x*y*(A*B)" def test_maple_piecewise(): expr = Piecewise((x, x < 1), (x ** 2, True)) assert maple_code(expr) == "piecewise(x < 1, x, x^2)" assert maple_code(expr, assign_to="r") == ( "r := piecewise(x < 1, x, x^2)") expr = Piecewise((x ** 2, x < 1), (x ** 3, x < 2), (x ** 4, x < 3), (x ** 5, True)) expected = "piecewise(x < 1, x^2, x < 2, x^3, x < 3, x^4, x^5)" assert maple_code(expr) == expected assert maple_code(expr, assign_to="r") == "r := " + expected # Check that Piecewise without a True (default) condition error expr = Piecewise((x, x < 1), (x ** 2, x > 1), (sin(x), x > 0)) raises(ValueError, lambda: maple_code(expr)) def test_maple_piecewise_times_const(): pw = Piecewise((x, x < 1), (x ** 2, True)) assert maple_code(2 * pw) == "2*piecewise(x < 1, x, x^2)" assert maple_code(pw / x) == "piecewise(x < 1, x, x^2)/x" assert maple_code(pw / (x * y)) == "piecewise(x < 1, x, x^2)/(x*y)" assert maple_code(pw / 3) == "(1/3)*piecewise(x < 1, x, x^2)" def test_maple_derivatives(): f = Function('f') assert maple_code(f(x).diff(x)) == 'diff(f(x), x)' assert maple_code(f(x).diff(x, 2)) == 'diff(f(x), x$2)' def test_specfun(): assert maple_code('asin(x)') == 'arcsin(x)' assert maple_code(besseli(x, y)) == 'BesselI(x, y)'
dfadb45a172253ac487e3695627887c10155083b47d0c782c8a5939207424639
from sympy import print_gtk, sin from sympy.testing.pytest import XFAIL, raises # this test fails if python-lxml isn't installed. We don't want to depend on # anything with SymPy @XFAIL def test_1(): from sympy.abc import x print_gtk(x**2, start_viewer=False) print_gtk(x**2 + sin(x)/4, start_viewer=False) def test_settings(): from sympy.abc import x raises(TypeError, lambda: print_gtk(x, method="garbage"))
548917040884ac2ce519d5129ca04ff9f48b4ed04eb2fabfc53f57502621e3d7
from sympy.printing.codeprinter import CodePrinter from sympy.printing.str import StrPrinter from sympy.core import symbols from sympy.core.symbol import Dummy from sympy.testing.pytest import raises def setup_test_printer(**kwargs): p = CodePrinter(settings=kwargs) p._not_supported = set() p._number_symbols = set() return p def test_print_Dummy(): d = Dummy('d') p = setup_test_printer() assert p._print_Dummy(d) == "d_%i" % d.dummy_index def test_print_Symbol(): x, y = symbols('x, if') p = setup_test_printer() assert p._print(x) == 'x' assert p._print(y) == 'if' p.reserved_words.update(['if']) assert p._print(y) == 'if_' p = setup_test_printer(error_on_reserved=True) p.reserved_words.update(['if']) with raises(ValueError): p._print(y) p = setup_test_printer(reserved_word_suffix='_He_Man') p.reserved_words.update(['if']) assert p._print(y) == 'if_He_Man' def test_issue_15791(): assert (CodePrinter._print_MutableSparseMatrix.__name__ == CodePrinter._print_not_supported.__name__) assert (CodePrinter._print_ImmutableSparseMatrix.__name__ == CodePrinter._print_not_supported.__name__) assert (CodePrinter._print_MutableSparseMatrix.__name__ != StrPrinter._print_MatrixBase.__name__) assert (CodePrinter._print_ImmutableSparseMatrix.__name__ != StrPrinter._print_MatrixBase.__name__)
5e5cc3d0322ea99fed15a809689596bc84677a954f86a0a533271dea92718653
from sympy.core import (pi, symbols, Rational, Integer, GoldenRatio, EulerGamma, Catalan, Lambda, Dummy, Eq, Ne, Le, Lt, Gt, Ge) from sympy.functions import Piecewise, sin, cos, Abs, exp, ceiling, sqrt from sympy.testing.pytest import raises from sympy.printing.glsl import GLSLPrinter from sympy.printing.str import StrPrinter from sympy.utilities.lambdify import implemented_function from sympy.tensor import IndexedBase, Idx from sympy.matrices import Matrix, MatrixSymbol from sympy.core import Tuple from sympy import glsl_code x, y, z = symbols('x,y,z') def test_printmethod(): assert glsl_code(Abs(x)) == "abs(x)" def test_print_without_operators(): assert glsl_code(x*y,use_operators = False) == 'mul(x, y)' assert glsl_code(x**y+z,use_operators = False) == 'add(pow(x, y), z)' assert glsl_code(x*(y+z),use_operators = False) == 'mul(x, add(y, z))' assert glsl_code(x*(y+z),use_operators = False) == 'mul(x, add(y, z))' assert glsl_code(x*(y+z**y**0.5),use_operators = False) == 'mul(x, add(y, pow(z, sqrt(y))))' def test_glsl_code_sqrt(): assert glsl_code(sqrt(x)) == "sqrt(x)" assert glsl_code(x**0.5) == "sqrt(x)" assert glsl_code(sqrt(x)) == "sqrt(x)" def test_glsl_code_Pow(): g = implemented_function('g', Lambda(x, 2*x)) assert glsl_code(x**3) == "pow(x, 3.0)" assert glsl_code(x**(y**3)) == "pow(x, pow(y, 3.0))" assert glsl_code(1/(g(x)*3.5)**(x - y**x)/(x**2 + y)) == \ "pow(3.5*2*x, -x + pow(y, x))/(pow(x, 2.0) + y)" assert glsl_code(x**-1.0) == '1.0/x' def test_glsl_code_Relational(): assert glsl_code(Eq(x, y)) == "x == y" assert glsl_code(Ne(x, y)) == "x != y" assert glsl_code(Le(x, y)) == "x <= y" assert glsl_code(Lt(x, y)) == "x < y" assert glsl_code(Gt(x, y)) == "x > y" assert glsl_code(Ge(x, y)) == "x >= y" def test_glsl_code_constants_mathh(): assert glsl_code(exp(1)) == "float E = 2.71828183;\nE" assert glsl_code(pi) == "float pi = 3.14159265;\npi" # assert glsl_code(oo) == "Number.POSITIVE_INFINITY" # assert glsl_code(-oo) == "Number.NEGATIVE_INFINITY" def test_glsl_code_constants_other(): assert glsl_code(2*GoldenRatio) == "float GoldenRatio = 1.61803399;\n2*GoldenRatio" assert glsl_code(2*Catalan) == "float Catalan = 0.915965594;\n2*Catalan" assert glsl_code(2*EulerGamma) == "float EulerGamma = 0.577215665;\n2*EulerGamma" def test_glsl_code_Rational(): assert glsl_code(Rational(3, 7)) == "3.0/7.0" assert glsl_code(Rational(18, 9)) == "2" assert glsl_code(Rational(3, -7)) == "-3.0/7.0" assert glsl_code(Rational(-3, -7)) == "3.0/7.0" def test_glsl_code_Integer(): assert glsl_code(Integer(67)) == "67" assert glsl_code(Integer(-1)) == "-1" def test_glsl_code_functions(): assert glsl_code(sin(x) ** cos(x)) == "pow(sin(x), cos(x))" def test_glsl_code_inline_function(): x = symbols('x') g = implemented_function('g', Lambda(x, 2*x)) assert glsl_code(g(x)) == "2*x" g = implemented_function('g', Lambda(x, 2*x/Catalan)) assert glsl_code(g(x)) == "float Catalan = 0.915965594;\n2*x/Catalan" A = IndexedBase('A') i = Idx('i', symbols('n', integer=True)) g = implemented_function('g', Lambda(x, x*(1 + x)*(2 + x))) assert glsl_code(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_glsl_code_exceptions(): assert glsl_code(ceiling(x)) == "ceil(x)" assert glsl_code(Abs(x)) == "abs(x)" def test_glsl_code_boolean(): assert glsl_code(x & y) == "x && y" assert glsl_code(x | y) == "x || y" assert glsl_code(~x) == "!x" assert glsl_code(x & y & z) == "x && y && z" assert glsl_code(x | y | z) == "x || y || z" assert glsl_code((x & y) | z) == "z || x && y" assert glsl_code((x | y) & z) == "z && (x || y)" def test_glsl_code_Piecewise(): expr = Piecewise((x, x < 1), (x**2, True)) p = glsl_code(expr) s = \ """\ ((x < 1) ? ( x ) : ( pow(x, 2.0) ))\ """ assert p == s assert glsl_code(expr, assign_to="c") == ( "if (x < 1) {\n" " c = x;\n" "}\n" "else {\n" " c = pow(x, 2.0);\n" "}") # Check that Piecewise without a True (default) condition error expr = Piecewise((x, x < 1), (x**2, x > 1), (sin(x), x > 0)) raises(ValueError, lambda: glsl_code(expr)) def test_glsl_code_Piecewise_deep(): p = glsl_code(2*Piecewise((x, x < 1), (x**2, True))) s = \ """\ 2*((x < 1) ? ( x ) : ( pow(x, 2.0) ))\ """ assert p == s def test_glsl_code_settings(): raises(TypeError, lambda: glsl_code(sin(x), method="garbage")) def test_glsl_code_Indexed(): from sympy.tensor import IndexedBase, Idx from sympy import symbols n, m, o = symbols('n m o', integer=True) i, j, k = Idx('i', n), Idx('j', m), Idx('k', o) p = GLSLPrinter() p._not_c = set() x = IndexedBase('x')[j] assert p._print_Indexed(x) == 'x[j]' A = IndexedBase('A')[i, j] assert p._print_Indexed(A) == 'A[%s]' % (m*i+j) B = IndexedBase('B')[i, j, k] assert p._print_Indexed(B) == 'B[%s]' % (i*o*m+j*o+k) assert p._not_c == set() def test_glsl_code_list_tuple_Tuple(): assert glsl_code([1,2,3,4]) == 'vec4(1, 2, 3, 4)' assert glsl_code([1,2,3],glsl_types=False) == 'float[3](1, 2, 3)' assert glsl_code([1,2,3]) == glsl_code((1,2,3)) assert glsl_code([1,2,3]) == glsl_code(Tuple(1,2,3)) m = MatrixSymbol('A',3,4) assert glsl_code([m[0],m[1]]) def test_glsl_code_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.0;\n' '}\n' 'for (int i=0; i<m; i++){\n' ' for (int j=0; j<n; j++){\n' ' y[i] = A[n*i + j]*x[j] + y[i];\n' ' }\n' '}' ) c = glsl_code(A[i, j]*x[j], assign_to=y[i]) assert c == s def test_dummy_loops(): i, m = symbols('i m', integer=True, cls=Dummy) x = IndexedBase('x') y = IndexedBase('y') i = Idx(i, m) expected = ( 'for (int i_%(icount)i=0; i_%(icount)i<m_%(mcount)i; i_%(icount)i++){\n' ' y[i_%(icount)i] = x[i_%(icount)i];\n' '}' ) % {'icount': i.label.dummy_index, 'mcount': m.dummy_index} code = glsl_code(x[i], assign_to=y[i]) assert code == expected def test_glsl_code_loops_add(): from sympy.tensor import IndexedBase, Idx from sympy import symbols n, m = symbols('n m', integer=True) A = IndexedBase('A') x = IndexedBase('x') y = IndexedBase('y') z = IndexedBase('z') i = Idx('i', m) j = Idx('j', n) s = ( 'for (int i=0; i<m; i++){\n' ' y[i] = x[i] + z[i];\n' '}\n' 'for (int i=0; i<m; i++){\n' ' for (int j=0; j<n; j++){\n' ' y[i] = A[n*i + j]*x[j] + y[i];\n' ' }\n' '}' ) c = glsl_code(A[i, j]*x[j] + x[i] + z[i], assign_to=y[i]) assert c == s def test_glsl_code_loops_multiple_contractions(): from sympy.tensor import IndexedBase, Idx from sympy 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.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] + y[i];\n' % (i*n*o*p + j*o*p + k*p + l, j*o*p + k*p + l) +\ ' }\n' ' }\n' ' }\n' '}' ) c = glsl_code(b[j, k, l]*a[i, j, k, l], assign_to=y[i]) assert c == s def test_glsl_code_loops_addfactor(): from sympy.tensor import IndexedBase, Idx from sympy 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 (int i=0; i<m; i++){\n' ' y[i] = 0.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 = glsl_code((a[i, j, k, l] + b[i, j, k, l])*c[j, k, l], assign_to=y[i]) assert c == s def test_glsl_code_loops_multiple_terms(): from sympy.tensor import IndexedBase, Idx from sympy 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.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] = a[%s]*b[k] + 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] = a[%s]*b[j] + y[i];\n' % (i*n + j) +\ ' }\n' '}\n' ) c = glsl_code( 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_Matrix_printing(): # Test returning a Matrix mat = Matrix([x*y, Piecewise((2 + x, y>0), (y, True)), sin(z)]) A = MatrixSymbol('A', 3, 1) assert glsl_code(mat, assign_to=A) == ( '''A[0][0] = x*y; if (y > 0) { A[1][0] = x + 2; } else { A[1][0] = y; } A[2][0] = sin(z);''' ) assert glsl_code(Matrix([A[0],A[1]])) # Test using MatrixElements in expressions expr = Piecewise((2*A[2, 0], x > 0), (A[2, 0], True)) + sin(A[1, 0]) + A[0, 0] assert glsl_code(expr) == ( '''((x > 0) ? ( 2*A[2][0] ) : ( A[2][0] )) + sin(A[1][0]) + A[0][0]''' ) # Test using MatrixElements in a Matrix q = MatrixSymbol('q', 5, 1) M = MatrixSymbol('M', 3, 3) m = Matrix([[sin(q[1,0]), 0, cos(q[2,0])], [q[1,0] + q[2,0], q[3, 0], 5], [2*q[4, 0]/q[1,0], sqrt(q[0,0]) + 4, 0]]) assert glsl_code(m,M) == ( '''M[0][0] = sin(q[1]); M[0][1] = 0; M[0][2] = cos(q[2]); M[1][0] = q[1] + q[2]; M[1][1] = q[3]; M[1][2] = 5; M[2][0] = 2*q[4]/q[1]; M[2][1] = sqrt(q[0]) + 4; M[2][2] = 0;''' ) def test_Matrices_1x7(): gl = glsl_code A = Matrix([1,2,3,4,5,6,7]) assert gl(A) == 'float[7](1, 2, 3, 4, 5, 6, 7)' assert gl(A.transpose()) == 'float[7](1, 2, 3, 4, 5, 6, 7)' def test_1xN_vecs(): gl = glsl_code for i in range(1,10): A = Matrix(range(i)) assert gl(A.transpose()) == gl(A) assert gl(A,mat_transpose=True) == gl(A) if i > 1: if i <= 4: assert gl(A) == 'vec%s(%s)' % (i,', '.join(str(s) for s in range(i))) else: assert gl(A) == 'float[%s](%s)' % (i,', '.join(str(s) for s in range(i))) def test_MxN_mats(): generatedAssertions='def test_misc_mats():\n' for i in range(1,6): for j in range(1,6): A = Matrix([[x + y*j for x in range(j)] for y in range(i)]) gl = glsl_code(A) glTransposed = glsl_code(A,mat_transpose=True) generatedAssertions+=' mat = '+StrPrinter()._print(A)+'\n\n' generatedAssertions+=' gl = \'\'\''+gl+'\'\'\'\n' generatedAssertions+=' glTransposed = \'\'\''+glTransposed+'\'\'\'\n\n' generatedAssertions+=' assert glsl_code(mat) == gl\n' generatedAssertions+=' assert glsl_code(mat,mat_transpose=True) == glTransposed\n' if i == 1 and j == 1: assert gl == '0' elif i <= 4 and j <= 4 and i>1 and j>1: assert gl.startswith('mat%s' % j) assert glTransposed.startswith('mat%s' % i) elif i == 1 and j <= 4: assert gl.startswith('vec') elif j == 1 and i <= 4: assert gl.startswith('vec') elif i == 1: assert gl.startswith('float[%s]('% j*i) assert glTransposed.startswith('float[%s]('% j*i) elif j == 1: assert gl.startswith('float[%s]('% i*j) assert glTransposed.startswith('float[%s]('% i*j) else: assert gl.startswith('float[%s](' % (i*j)) assert glTransposed.startswith('float[%s](' % (i*j)) glNested = glsl_code(A,mat_nested=True) glNestedTransposed = glsl_code(A,mat_transpose=True,mat_nested=True) assert glNested.startswith('float[%s][%s]' % (i,j)) assert glNestedTransposed.startswith('float[%s][%s]' % (j,i)) generatedAssertions+=' glNested = \'\'\''+glNested+'\'\'\'\n' generatedAssertions+=' glNestedTransposed = \'\'\''+glNestedTransposed+'\'\'\'\n\n' generatedAssertions+=' assert glsl_code(mat,mat_nested=True) == glNested\n' generatedAssertions+=' assert glsl_code(mat,mat_nested=True,mat_transpose=True) == glNestedTransposed\n\n' generateAssertions = False # set this to true to write bake these generated tests to a file if generateAssertions: gen = open('test_glsl_generated_matrices.py','w') gen.write(generatedAssertions) gen.close() # these assertions were generated from the previous function # glsl has complicated rules and this makes it easier to look over all the cases def test_misc_mats(): mat = Matrix([[0]]) gl = '''0''' glTransposed = '''0''' assert glsl_code(mat) == gl assert glsl_code(mat,mat_transpose=True) == glTransposed mat = Matrix([[0, 1]]) gl = '''vec2(0, 1)''' glTransposed = '''vec2(0, 1)''' assert glsl_code(mat) == gl assert glsl_code(mat,mat_transpose=True) == glTransposed mat = Matrix([[0, 1, 2]]) gl = '''vec3(0, 1, 2)''' glTransposed = '''vec3(0, 1, 2)''' assert glsl_code(mat) == gl assert glsl_code(mat,mat_transpose=True) == glTransposed mat = Matrix([[0, 1, 2, 3]]) gl = '''vec4(0, 1, 2, 3)''' glTransposed = '''vec4(0, 1, 2, 3)''' assert glsl_code(mat) == gl assert glsl_code(mat,mat_transpose=True) == glTransposed mat = Matrix([[0, 1, 2, 3, 4]]) gl = '''float[5](0, 1, 2, 3, 4)''' glTransposed = '''float[5](0, 1, 2, 3, 4)''' assert glsl_code(mat) == gl assert glsl_code(mat,mat_transpose=True) == glTransposed mat = Matrix([ [0], [1]]) gl = '''vec2(0, 1)''' glTransposed = '''vec2(0, 1)''' assert glsl_code(mat) == gl assert glsl_code(mat,mat_transpose=True) == glTransposed mat = Matrix([ [0, 1], [2, 3]]) gl = '''mat2(0, 1, 2, 3)''' glTransposed = '''mat2(0, 2, 1, 3)''' assert glsl_code(mat) == gl assert glsl_code(mat,mat_transpose=True) == glTransposed mat = Matrix([ [0, 1, 2], [3, 4, 5]]) gl = '''mat3x2(0, 1, 2, 3, 4, 5)''' glTransposed = '''mat2x3(0, 3, 1, 4, 2, 5)''' assert glsl_code(mat) == gl assert glsl_code(mat,mat_transpose=True) == glTransposed mat = Matrix([ [0, 1, 2, 3], [4, 5, 6, 7]]) gl = '''mat4x2(0, 1, 2, 3, 4, 5, 6, 7)''' glTransposed = '''mat2x4(0, 4, 1, 5, 2, 6, 3, 7)''' assert glsl_code(mat) == gl assert glsl_code(mat,mat_transpose=True) == glTransposed mat = Matrix([ [0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]) gl = '''float[10]( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ) /* a 2x5 matrix */''' glTransposed = '''float[10]( 0, 5, 1, 6, 2, 7, 3, 8, 4, 9 ) /* a 5x2 matrix */''' assert glsl_code(mat) == gl assert glsl_code(mat,mat_transpose=True) == glTransposed glNested = '''float[2][5]( float[](0, 1, 2, 3, 4), float[](5, 6, 7, 8, 9) )''' glNestedTransposed = '''float[5][2]( float[](0, 5), float[](1, 6), float[](2, 7), float[](3, 8), float[](4, 9) )''' assert glsl_code(mat,mat_nested=True) == glNested assert glsl_code(mat,mat_nested=True,mat_transpose=True) == glNestedTransposed mat = Matrix([ [0], [1], [2]]) gl = '''vec3(0, 1, 2)''' glTransposed = '''vec3(0, 1, 2)''' assert glsl_code(mat) == gl assert glsl_code(mat,mat_transpose=True) == glTransposed mat = Matrix([ [0, 1], [2, 3], [4, 5]]) gl = '''mat2x3(0, 1, 2, 3, 4, 5)''' glTransposed = '''mat3x2(0, 2, 4, 1, 3, 5)''' assert glsl_code(mat) == gl assert glsl_code(mat,mat_transpose=True) == glTransposed mat = Matrix([ [0, 1, 2], [3, 4, 5], [6, 7, 8]]) gl = '''mat3(0, 1, 2, 3, 4, 5, 6, 7, 8)''' glTransposed = '''mat3(0, 3, 6, 1, 4, 7, 2, 5, 8)''' assert glsl_code(mat) == gl assert glsl_code(mat,mat_transpose=True) == glTransposed mat = Matrix([ [0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]]) gl = '''mat4x3(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)''' glTransposed = '''mat3x4(0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11)''' assert glsl_code(mat) == gl assert glsl_code(mat,mat_transpose=True) == glTransposed mat = Matrix([ [ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14]]) gl = '''float[15]( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 ) /* a 3x5 matrix */''' glTransposed = '''float[15]( 0, 5, 10, 1, 6, 11, 2, 7, 12, 3, 8, 13, 4, 9, 14 ) /* a 5x3 matrix */''' assert glsl_code(mat) == gl assert glsl_code(mat,mat_transpose=True) == glTransposed glNested = '''float[3][5]( float[]( 0, 1, 2, 3, 4), float[]( 5, 6, 7, 8, 9), float[](10, 11, 12, 13, 14) )''' glNestedTransposed = '''float[5][3]( float[](0, 5, 10), float[](1, 6, 11), float[](2, 7, 12), float[](3, 8, 13), float[](4, 9, 14) )''' assert glsl_code(mat,mat_nested=True) == glNested assert glsl_code(mat,mat_nested=True,mat_transpose=True) == glNestedTransposed mat = Matrix([ [0], [1], [2], [3]]) gl = '''vec4(0, 1, 2, 3)''' glTransposed = '''vec4(0, 1, 2, 3)''' assert glsl_code(mat) == gl assert glsl_code(mat,mat_transpose=True) == glTransposed mat = Matrix([ [0, 1], [2, 3], [4, 5], [6, 7]]) gl = '''mat2x4(0, 1, 2, 3, 4, 5, 6, 7)''' glTransposed = '''mat4x2(0, 2, 4, 6, 1, 3, 5, 7)''' assert glsl_code(mat) == gl assert glsl_code(mat,mat_transpose=True) == glTransposed mat = Matrix([ [0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]]) gl = '''mat3x4(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)''' glTransposed = '''mat4x3(0, 3, 6, 9, 1, 4, 7, 10, 2, 5, 8, 11)''' assert glsl_code(mat) == gl assert glsl_code(mat,mat_transpose=True) == glTransposed mat = Matrix([ [ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11], [12, 13, 14, 15]]) gl = '''mat4( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)''' glTransposed = '''mat4(0, 4, 8, 12, 1, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15)''' assert glsl_code(mat) == gl assert glsl_code(mat,mat_transpose=True) == glTransposed mat = Matrix([ [ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19]]) gl = '''float[20]( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 ) /* a 4x5 matrix */''' glTransposed = '''float[20]( 0, 5, 10, 15, 1, 6, 11, 16, 2, 7, 12, 17, 3, 8, 13, 18, 4, 9, 14, 19 ) /* a 5x4 matrix */''' assert glsl_code(mat) == gl assert glsl_code(mat,mat_transpose=True) == glTransposed glNested = '''float[4][5]( float[]( 0, 1, 2, 3, 4), float[]( 5, 6, 7, 8, 9), float[](10, 11, 12, 13, 14), float[](15, 16, 17, 18, 19) )''' glNestedTransposed = '''float[5][4]( float[](0, 5, 10, 15), float[](1, 6, 11, 16), float[](2, 7, 12, 17), float[](3, 8, 13, 18), float[](4, 9, 14, 19) )''' assert glsl_code(mat,mat_nested=True) == glNested assert glsl_code(mat,mat_nested=True,mat_transpose=True) == glNestedTransposed mat = Matrix([ [0], [1], [2], [3], [4]]) gl = '''float[5](0, 1, 2, 3, 4)''' glTransposed = '''float[5](0, 1, 2, 3, 4)''' assert glsl_code(mat) == gl assert glsl_code(mat,mat_transpose=True) == glTransposed mat = Matrix([ [0, 1], [2, 3], [4, 5], [6, 7], [8, 9]]) gl = '''float[10]( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ) /* a 5x2 matrix */''' glTransposed = '''float[10]( 0, 2, 4, 6, 8, 1, 3, 5, 7, 9 ) /* a 2x5 matrix */''' assert glsl_code(mat) == gl assert glsl_code(mat,mat_transpose=True) == glTransposed glNested = '''float[5][2]( float[](0, 1), float[](2, 3), float[](4, 5), float[](6, 7), float[](8, 9) )''' glNestedTransposed = '''float[2][5]( float[](0, 2, 4, 6, 8), float[](1, 3, 5, 7, 9) )''' assert glsl_code(mat,mat_nested=True) == glNested assert glsl_code(mat,mat_nested=True,mat_transpose=True) == glNestedTransposed mat = Matrix([ [ 0, 1, 2], [ 3, 4, 5], [ 6, 7, 8], [ 9, 10, 11], [12, 13, 14]]) gl = '''float[15]( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 ) /* a 5x3 matrix */''' glTransposed = '''float[15]( 0, 3, 6, 9, 12, 1, 4, 7, 10, 13, 2, 5, 8, 11, 14 ) /* a 3x5 matrix */''' assert glsl_code(mat) == gl assert glsl_code(mat,mat_transpose=True) == glTransposed glNested = '''float[5][3]( float[]( 0, 1, 2), float[]( 3, 4, 5), float[]( 6, 7, 8), float[]( 9, 10, 11), float[](12, 13, 14) )''' glNestedTransposed = '''float[3][5]( float[](0, 3, 6, 9, 12), float[](1, 4, 7, 10, 13), float[](2, 5, 8, 11, 14) )''' assert glsl_code(mat,mat_nested=True) == glNested assert glsl_code(mat,mat_nested=True,mat_transpose=True) == glNestedTransposed mat = Matrix([ [ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11], [12, 13, 14, 15], [16, 17, 18, 19]]) gl = '''float[20]( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 ) /* a 5x4 matrix */''' glTransposed = '''float[20]( 0, 4, 8, 12, 16, 1, 5, 9, 13, 17, 2, 6, 10, 14, 18, 3, 7, 11, 15, 19 ) /* a 4x5 matrix */''' assert glsl_code(mat) == gl assert glsl_code(mat,mat_transpose=True) == glTransposed glNested = '''float[5][4]( float[]( 0, 1, 2, 3), float[]( 4, 5, 6, 7), float[]( 8, 9, 10, 11), float[](12, 13, 14, 15), float[](16, 17, 18, 19) )''' glNestedTransposed = '''float[4][5]( float[](0, 4, 8, 12, 16), float[](1, 5, 9, 13, 17), float[](2, 6, 10, 14, 18), float[](3, 7, 11, 15, 19) )''' assert glsl_code(mat,mat_nested=True) == glNested assert glsl_code(mat,mat_nested=True,mat_transpose=True) == glNestedTransposed mat = Matrix([ [ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19], [20, 21, 22, 23, 24]]) gl = '''float[25]( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24 ) /* a 5x5 matrix */''' glTransposed = '''float[25]( 0, 5, 10, 15, 20, 1, 6, 11, 16, 21, 2, 7, 12, 17, 22, 3, 8, 13, 18, 23, 4, 9, 14, 19, 24 ) /* a 5x5 matrix */''' assert glsl_code(mat) == gl assert glsl_code(mat,mat_transpose=True) == glTransposed glNested = '''float[5][5]( float[]( 0, 1, 2, 3, 4), float[]( 5, 6, 7, 8, 9), float[](10, 11, 12, 13, 14), float[](15, 16, 17, 18, 19), float[](20, 21, 22, 23, 24) )''' glNestedTransposed = '''float[5][5]( float[](0, 5, 10, 15, 20), float[](1, 6, 11, 16, 21), float[](2, 7, 12, 17, 22), float[](3, 8, 13, 18, 23), float[](4, 9, 14, 19, 24) )''' assert glsl_code(mat,mat_nested=True) == glNested assert glsl_code(mat,mat_nested=True,mat_transpose=True) == glNestedTransposed
d9ee2f7e186c484a25281d48a3a6edec8e3c565f981a36a3591741eca357dcfc
import random from sympy import symbols, Derivative from sympy.codegen.array_utils import (CodegenArrayContraction, CodegenArrayTensorProduct, CodegenArrayElementwiseAdd, CodegenArrayPermuteDims, CodegenArrayDiagonal) from sympy.core.relational import Eq, Ne, Ge, Gt, Le, Lt from sympy.external import import_module from sympy.functions import \ Abs, ceiling, exp, floor, sign, sin, asin, sqrt, cos, \ acos, tan, atan, atan2, cosh, acosh, sinh, asinh, tanh, atanh, \ re, im, arg, erf, loggamma, log from sympy.matrices import Matrix, MatrixBase, eye, randMatrix from sympy.matrices.expressions import \ Determinant, HadamardProduct, Inverse, MatrixSymbol, Trace from sympy.printing.tensorflow import tensorflow_code from sympy.utilities.lambdify import lambdify from sympy.testing.pytest import skip from sympy.testing.pytest import XFAIL tf = tensorflow = import_module("tensorflow") if tensorflow: # Hide Tensorflow warnings import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' M = MatrixSymbol("M", 3, 3) N = MatrixSymbol("N", 3, 3) P = MatrixSymbol("P", 3, 3) Q = MatrixSymbol("Q", 3, 3) x, y, z, t = symbols("x y z t") if tf is not None: llo = [[j for j in range(i, i+3)] for i in range(0, 9, 3)] m3x3 = tf.constant(llo) m3x3sympy = Matrix(llo) def _compare_tensorflow_matrix(variables, expr, use_float=False): f = lambdify(variables, expr, 'tensorflow') if not use_float: random_matrices = [randMatrix(v.rows, v.cols) for v in variables] else: random_matrices = [randMatrix(v.rows, v.cols)/100. for v in variables] graph = tf.Graph() r = None with graph.as_default(): random_variables = [eval(tensorflow_code(i)) for i in random_matrices] session = tf.compat.v1.Session(graph=graph) r = session.run(f(*random_variables)) e = expr.subs({k: v for k, v in zip(variables, random_matrices)}) e = e.doit() if e.is_Matrix: if not isinstance(e, MatrixBase): e = e.as_explicit() e = e.tolist() if not use_float: assert (r == e).all() else: r = [i for row in r for i in row] e = [i for row in e for i in row] assert all( abs(a-b) < 10**-(4-int(log(abs(a), 10))) for a, b in zip(r, e)) # Creating a custom inverse test. # See https://github.com/sympy/sympy/issues/18469 def _compare_tensorflow_matrix_inverse(variables, expr, use_float=False): f = lambdify(variables, expr, 'tensorflow') if not use_float: random_matrices = [eye(v.rows, v.cols)*4 for v in variables] else: random_matrices = [eye(v.rows, v.cols)*3.14 for v in variables] graph = tf.Graph() r = None with graph.as_default(): random_variables = [eval(tensorflow_code(i)) for i in random_matrices] session = tf.compat.v1.Session(graph=graph) r = session.run(f(*random_variables)) e = expr.subs({k: v for k, v in zip(variables, random_matrices)}) e = e.doit() if e.is_Matrix: if not isinstance(e, MatrixBase): e = e.as_explicit() e = e.tolist() if not use_float: assert (r == e).all() else: r = [i for row in r for i in row] e = [i for row in e for i in row] assert all( abs(a-b) < 10**-(4-int(log(abs(a), 10))) for a, b in zip(r, e)) def _compare_tensorflow_matrix_scalar(variables, expr): f = lambdify(variables, expr, 'tensorflow') random_matrices = [ randMatrix(v.rows, v.cols).evalf() / 100 for v in variables] graph = tf.Graph() r = None with graph.as_default(): random_variables = [eval(tensorflow_code(i)) for i in random_matrices] session = tf.compat.v1.Session(graph=graph) r = session.run(f(*random_variables)) e = expr.subs({k: v for k, v in zip(variables, random_matrices)}) e = e.doit() assert abs(r-e) < 10**-6 def _compare_tensorflow_scalar( variables, expr, rng=lambda: random.randint(0, 10)): f = lambdify(variables, expr, 'tensorflow') rvs = [rng() for v in variables] graph = tf.Graph() r = None with graph.as_default(): tf_rvs = [eval(tensorflow_code(i)) for i in rvs] session = tf.compat.v1.Session(graph=graph) r = session.run(f(*tf_rvs)) e = expr.subs({k: v for k, v in zip(variables, rvs)}).evalf().doit() assert abs(r-e) < 10**-6 def _compare_tensorflow_relational( variables, expr, rng=lambda: random.randint(0, 10)): f = lambdify(variables, expr, 'tensorflow') rvs = [rng() for v in variables] graph = tf.Graph() r = None with graph.as_default(): tf_rvs = [eval(tensorflow_code(i)) for i in rvs] session = tf.compat.v1.Session(graph=graph) r = session.run(f(*tf_rvs)) e = expr.subs({k: v for k, v in zip(variables, rvs)}).doit() assert r == e def test_tensorflow_printing(): assert tensorflow_code(eye(3)) == \ "tensorflow.constant([[1, 0, 0], [0, 1, 0], [0, 0, 1]])" expr = Matrix([[x, sin(y)], [exp(z), -t]]) assert tensorflow_code(expr) == \ "tensorflow.Variable(" \ "[[x, tensorflow.math.sin(y)]," \ " [tensorflow.math.exp(z), -t]])" # This (random) test is XFAIL because it fails occasionally # See https://github.com/sympy/sympy/issues/18469 @XFAIL def test_tensorflow_math(): if not tf: skip("TensorFlow not installed") expr = Abs(x) assert tensorflow_code(expr) == "tensorflow.math.abs(x)" _compare_tensorflow_scalar((x,), expr) expr = sign(x) assert tensorflow_code(expr) == "tensorflow.math.sign(x)" _compare_tensorflow_scalar((x,), expr) expr = ceiling(x) assert tensorflow_code(expr) == "tensorflow.math.ceil(x)" _compare_tensorflow_scalar((x,), expr, rng=lambda: random.random()) expr = floor(x) assert tensorflow_code(expr) == "tensorflow.math.floor(x)" _compare_tensorflow_scalar((x,), expr, rng=lambda: random.random()) expr = exp(x) assert tensorflow_code(expr) == "tensorflow.math.exp(x)" _compare_tensorflow_scalar((x,), expr, rng=lambda: random.random()) expr = sqrt(x) assert tensorflow_code(expr) == "tensorflow.math.sqrt(x)" _compare_tensorflow_scalar((x,), expr, rng=lambda: random.random()) expr = x ** 4 assert tensorflow_code(expr) == "tensorflow.math.pow(x, 4)" _compare_tensorflow_scalar((x,), expr, rng=lambda: random.random()) expr = cos(x) assert tensorflow_code(expr) == "tensorflow.math.cos(x)" _compare_tensorflow_scalar((x,), expr, rng=lambda: random.random()) expr = acos(x) assert tensorflow_code(expr) == "tensorflow.math.acos(x)" _compare_tensorflow_scalar((x,), expr, rng=lambda: random.uniform(0, 0.95)) expr = sin(x) assert tensorflow_code(expr) == "tensorflow.math.sin(x)" _compare_tensorflow_scalar((x,), expr, rng=lambda: random.random()) expr = asin(x) assert tensorflow_code(expr) == "tensorflow.math.asin(x)" _compare_tensorflow_scalar((x,), expr, rng=lambda: random.random()) expr = tan(x) assert tensorflow_code(expr) == "tensorflow.math.tan(x)" _compare_tensorflow_scalar((x,), expr, rng=lambda: random.random()) expr = atan(x) assert tensorflow_code(expr) == "tensorflow.math.atan(x)" _compare_tensorflow_scalar((x,), expr, rng=lambda: random.random()) expr = atan2(y, x) assert tensorflow_code(expr) == "tensorflow.math.atan2(y, x)" _compare_tensorflow_scalar((y, x), expr, rng=lambda: random.random()) expr = cosh(x) assert tensorflow_code(expr) == "tensorflow.math.cosh(x)" _compare_tensorflow_scalar((x,), expr, rng=lambda: random.random()) expr = acosh(x) assert tensorflow_code(expr) == "tensorflow.math.acosh(x)" _compare_tensorflow_scalar((x,), expr, rng=lambda: random.uniform(1, 2)) expr = sinh(x) assert tensorflow_code(expr) == "tensorflow.math.sinh(x)" _compare_tensorflow_scalar((x,), expr, rng=lambda: random.uniform(1, 2)) expr = asinh(x) assert tensorflow_code(expr) == "tensorflow.math.asinh(x)" _compare_tensorflow_scalar((x,), expr, rng=lambda: random.uniform(1, 2)) expr = tanh(x) assert tensorflow_code(expr) == "tensorflow.math.tanh(x)" _compare_tensorflow_scalar((x,), expr, rng=lambda: random.uniform(1, 2)) expr = atanh(x) assert tensorflow_code(expr) == "tensorflow.math.atanh(x)" _compare_tensorflow_scalar( (x,), expr, rng=lambda: random.uniform(-.5, .5)) expr = erf(x) assert tensorflow_code(expr) == "tensorflow.math.erf(x)" _compare_tensorflow_scalar( (x,), expr, rng=lambda: random.random()) expr = loggamma(x) assert tensorflow_code(expr) == "tensorflow.math.lgamma(x)" _compare_tensorflow_scalar( (x,), expr, rng=lambda: random.random()) def test_tensorflow_complexes(): assert tensorflow_code(re(x)) == "tensorflow.math.real(x)" assert tensorflow_code(im(x)) == "tensorflow.math.imag(x)" assert tensorflow_code(arg(x)) == "tensorflow.math.angle(x)" def test_tensorflow_relational(): if not tf: skip("TensorFlow not installed") expr = Eq(x, y) assert tensorflow_code(expr) == "tensorflow.math.equal(x, y)" _compare_tensorflow_relational((x, y), expr) expr = Ne(x, y) assert tensorflow_code(expr) == "tensorflow.math.not_equal(x, y)" _compare_tensorflow_relational((x, y), expr) expr = Ge(x, y) assert tensorflow_code(expr) == "tensorflow.math.greater_equal(x, y)" _compare_tensorflow_relational((x, y), expr) expr = Gt(x, y) assert tensorflow_code(expr) == "tensorflow.math.greater(x, y)" _compare_tensorflow_relational((x, y), expr) expr = Le(x, y) assert tensorflow_code(expr) == "tensorflow.math.less_equal(x, y)" _compare_tensorflow_relational((x, y), expr) expr = Lt(x, y) assert tensorflow_code(expr) == "tensorflow.math.less(x, y)" _compare_tensorflow_relational((x, y), expr) # This (random) test is XFAIL because it fails occasionally # See https://github.com/sympy/sympy/issues/18469 @XFAIL def test_tensorflow_matrices(): if not tf: skip("TensorFlow not installed") expr = M assert tensorflow_code(expr) == "M" _compare_tensorflow_matrix((M,), expr) expr = M + N assert tensorflow_code(expr) == "tensorflow.math.add(M, N)" _compare_tensorflow_matrix((M, N), expr) expr = M * N assert tensorflow_code(expr) == "tensorflow.linalg.matmul(M, N)" _compare_tensorflow_matrix((M, N), expr) expr = HadamardProduct(M, N) assert tensorflow_code(expr) == "tensorflow.math.multiply(M, N)" _compare_tensorflow_matrix((M, N), expr) expr = M*N*P*Q assert tensorflow_code(expr) == \ "tensorflow.linalg.matmul(" \ "tensorflow.linalg.matmul(" \ "tensorflow.linalg.matmul(M, N), P), Q)" _compare_tensorflow_matrix((M, N, P, Q), expr) expr = M**3 assert tensorflow_code(expr) == \ "tensorflow.linalg.matmul(tensorflow.linalg.matmul(M, M), M)" _compare_tensorflow_matrix((M,), expr) expr = Trace(M) assert tensorflow_code(expr) == "tensorflow.linalg.trace(M)" _compare_tensorflow_matrix((M,), expr) expr = Determinant(M) assert tensorflow_code(expr) == "tensorflow.linalg.det(M)" _compare_tensorflow_matrix_scalar((M,), expr) expr = Inverse(M) assert tensorflow_code(expr) == "tensorflow.linalg.inv(M)" _compare_tensorflow_matrix_inverse((M,), expr, use_float=True) expr = M.T assert tensorflow_code(expr, tensorflow_version='1.14') == \ "tensorflow.linalg.matrix_transpose(M)" assert tensorflow_code(expr, tensorflow_version='1.13') == \ "tensorflow.matrix_transpose(M)" _compare_tensorflow_matrix((M,), expr) def test_codegen_einsum(): if not tf: skip("TensorFlow not installed") graph = tf.Graph() with graph.as_default(): session = tf.compat.v1.Session(graph=graph) M = MatrixSymbol("M", 2, 2) N = MatrixSymbol("N", 2, 2) cg = CodegenArrayContraction.from_MatMul(M*N) f = lambdify((M, N), cg, 'tensorflow') ma = tf.constant([[1, 2], [3, 4]]) mb = tf.constant([[1,-2], [-1, 3]]) y = session.run(f(ma, mb)) c = session.run(tf.matmul(ma, mb)) assert (y == c).all() def test_codegen_extra(): if not tf: skip("TensorFlow not installed") graph = tf.Graph() with graph.as_default(): session = tf.compat.v1.Session() M = MatrixSymbol("M", 2, 2) N = MatrixSymbol("N", 2, 2) P = MatrixSymbol("P", 2, 2) Q = MatrixSymbol("Q", 2, 2) ma = tf.constant([[1, 2], [3, 4]]) mb = tf.constant([[1,-2], [-1, 3]]) mc = tf.constant([[2, 0], [1, 2]]) md = tf.constant([[1,-1], [4, 7]]) cg = CodegenArrayTensorProduct(M, N) assert tensorflow_code(cg) == \ 'tensorflow.linalg.einsum("ab,cd", M, N)' f = lambdify((M, N), cg, 'tensorflow') y = session.run(f(ma, mb)) c = session.run(tf.einsum("ij,kl", ma, mb)) assert (y == c).all() cg = CodegenArrayElementwiseAdd(M, N) assert tensorflow_code(cg) == 'tensorflow.math.add(M, N)' f = lambdify((M, N), cg, 'tensorflow') y = session.run(f(ma, mb)) c = session.run(ma + mb) assert (y == c).all() cg = CodegenArrayElementwiseAdd(M, N, P) assert tensorflow_code(cg) == \ 'tensorflow.math.add(tensorflow.math.add(M, N), P)' f = lambdify((M, N, P), cg, 'tensorflow') y = session.run(f(ma, mb, mc)) c = session.run(ma + mb + mc) assert (y == c).all() cg = CodegenArrayElementwiseAdd(M, N, P, Q) assert tensorflow_code(cg) == \ 'tensorflow.math.add(' \ 'tensorflow.math.add(tensorflow.math.add(M, N), P), Q)' f = lambdify((M, N, P, Q), cg, 'tensorflow') y = session.run(f(ma, mb, mc, md)) c = session.run(ma + mb + mc + md) assert (y == c).all() cg = CodegenArrayPermuteDims(M, [1, 0]) assert tensorflow_code(cg) == 'tensorflow.transpose(M, [1, 0])' f = lambdify((M,), cg, 'tensorflow') y = session.run(f(ma)) c = session.run(tf.transpose(ma)) assert (y == c).all() cg = CodegenArrayPermuteDims(CodegenArrayTensorProduct(M, N), [1, 2, 3, 0]) assert tensorflow_code(cg) == \ 'tensorflow.transpose(' \ 'tensorflow.linalg.einsum("ab,cd", M, N), [1, 2, 3, 0])' f = lambdify((M, N), cg, 'tensorflow') y = session.run(f(ma, mb)) c = session.run(tf.transpose(tf.einsum("ab,cd", ma, mb), [1, 2, 3, 0])) assert (y == c).all() cg = CodegenArrayDiagonal(CodegenArrayTensorProduct(M, N), (1, 2)) assert tensorflow_code(cg) == \ 'tensorflow.linalg.einsum("ab,bc->acb", M, N)' f = lambdify((M, N), cg, 'tensorflow') y = session.run(f(ma, mb)) c = session.run(tf.einsum("ab,bc->acb", ma, mb)) assert (y == c).all() def test_MatrixElement_printing(): A = MatrixSymbol("A", 1, 3) B = MatrixSymbol("B", 1, 3) C = MatrixSymbol("C", 1, 3) assert tensorflow_code(A[0, 0]) == "A[0, 0]" assert tensorflow_code(3 * A[0, 0]) == "3*A[0, 0]" F = C[0, 0].subs(C, A - B) assert tensorflow_code(F) == "(tensorflow.math.add((-1)*B, A))[0, 0]" def test_tensorflow_Derivative(): expr = Derivative(sin(x), x) assert tensorflow_code(expr) == \ "tensorflow.gradients(tensorflow.math.sin(x), x)[0]"
829a62d0462bc66951021b1452b0b141e0be50e49b52f8363848981aead82196
from sympy import ( Piecewise, lambdify, Equality, Unequality, Sum, Mod, sqrt, MatrixSymbol, BlockMatrix, Identity ) from sympy import eye from sympy.abc import x, i, j, a, b, c, d from sympy.codegen.matrix_nodes import MatrixSolve from sympy.codegen.cfunctions import log1p, expm1, hypot, log10, exp2, log2, Sqrt from sympy.codegen.array_utils import (CodegenArrayContraction, CodegenArrayTensorProduct, CodegenArrayDiagonal, CodegenArrayPermuteDims, CodegenArrayElementwiseAdd) from sympy.printing.lambdarepr import NumPyPrinter from sympy.testing.pytest import warns_deprecated_sympy from sympy.testing.pytest import skip, raises from sympy.external import import_module np = import_module('numpy') def test_numpy_piecewise_regression(): """ NumPyPrinter needs to print Piecewise()'s choicelist as a list to avoid breaking compatibility with numpy 1.8. This is not necessary in numpy 1.9+. See gh-9747 and gh-9749 for details. """ printer = NumPyPrinter() p = Piecewise((1, x < 0), (0, True)) assert printer.doprint(p) == \ 'numpy.select([numpy.less(x, 0),True], [1,0], default=numpy.nan)' assert printer.module_imports == {'numpy': {'select', 'less', 'nan'}} def test_sum(): if not np: skip("NumPy not installed") s = Sum(x ** i, (i, a, b)) f = lambdify((a, b, x), s, 'numpy') a_, b_ = 0, 10 x_ = np.linspace(-1, +1, 10) assert np.allclose(f(a_, b_, x_), sum(x_ ** i_ for i_ in range(a_, b_ + 1))) s = Sum(i * x, (i, a, b)) f = lambdify((a, b, x), s, 'numpy') a_, b_ = 0, 10 x_ = np.linspace(-1, +1, 10) assert np.allclose(f(a_, b_, x_), sum(i_ * x_ for i_ in range(a_, b_ + 1))) def test_multiple_sums(): if not np: skip("NumPy not installed") s = Sum((x + j) * i, (i, a, b), (j, c, d)) f = lambdify((a, b, c, d, x), s, 'numpy') a_, b_ = 0, 10 c_, d_ = 11, 21 x_ = np.linspace(-1, +1, 10) assert np.allclose(f(a_, b_, c_, d_, x_), sum((x_ + j_) * i_ for i_ in range(a_, b_ + 1) for j_ in range(c_, d_ + 1))) def test_codegen_einsum(): if not np: skip("NumPy not installed") M = MatrixSymbol("M", 2, 2) N = MatrixSymbol("N", 2, 2) cg = CodegenArrayContraction.from_MatMul(M*N) f = lambdify((M, N), cg, 'numpy') ma = np.matrix([[1, 2], [3, 4]]) mb = np.matrix([[1,-2], [-1, 3]]) assert (f(ma, mb) == ma*mb).all() def test_codegen_extra(): if not np: skip("NumPy not installed") M = MatrixSymbol("M", 2, 2) N = MatrixSymbol("N", 2, 2) P = MatrixSymbol("P", 2, 2) Q = MatrixSymbol("Q", 2, 2) ma = np.matrix([[1, 2], [3, 4]]) mb = np.matrix([[1,-2], [-1, 3]]) mc = np.matrix([[2, 0], [1, 2]]) md = np.matrix([[1,-1], [4, 7]]) cg = CodegenArrayTensorProduct(M, N) f = lambdify((M, N), cg, 'numpy') assert (f(ma, mb) == np.einsum(ma, [0, 1], mb, [2, 3])).all() cg = CodegenArrayElementwiseAdd(M, N) f = lambdify((M, N), cg, 'numpy') assert (f(ma, mb) == ma+mb).all() cg = CodegenArrayElementwiseAdd(M, N, P) f = lambdify((M, N, P), cg, 'numpy') assert (f(ma, mb, mc) == ma+mb+mc).all() cg = CodegenArrayElementwiseAdd(M, N, P, Q) f = lambdify((M, N, P, Q), cg, 'numpy') assert (f(ma, mb, mc, md) == ma+mb+mc+md).all() cg = CodegenArrayPermuteDims(M, [1, 0]) f = lambdify((M,), cg, 'numpy') assert (f(ma) == ma.T).all() cg = CodegenArrayPermuteDims(CodegenArrayTensorProduct(M, N), [1, 2, 3, 0]) f = lambdify((M, N), cg, 'numpy') assert (f(ma, mb) == np.transpose(np.einsum(ma, [0, 1], mb, [2, 3]), (1, 2, 3, 0))).all() cg = CodegenArrayDiagonal(CodegenArrayTensorProduct(M, N), (1, 2)) f = lambdify((M, N), cg, 'numpy') assert (f(ma, mb) == np.diagonal(np.einsum(ma, [0, 1], mb, [2, 3]), axis1=1, axis2=2)).all() def test_relational(): if not np: skip("NumPy not installed") e = Equality(x, 1) f = lambdify((x,), e) x_ = np.array([0, 1, 2]) assert np.array_equal(f(x_), [False, True, False]) e = Unequality(x, 1) f = lambdify((x,), e) x_ = np.array([0, 1, 2]) assert np.array_equal(f(x_), [True, False, True]) e = (x < 1) f = lambdify((x,), e) x_ = np.array([0, 1, 2]) assert np.array_equal(f(x_), [True, False, False]) e = (x <= 1) f = lambdify((x,), e) x_ = np.array([0, 1, 2]) assert np.array_equal(f(x_), [True, True, False]) e = (x > 1) f = lambdify((x,), e) x_ = np.array([0, 1, 2]) assert np.array_equal(f(x_), [False, False, True]) e = (x >= 1) f = lambdify((x,), e) x_ = np.array([0, 1, 2]) assert np.array_equal(f(x_), [False, True, True]) def test_mod(): if not np: skip("NumPy not installed") e = Mod(a, b) f = lambdify((a, b), e) a_ = np.array([0, 1, 2, 3]) b_ = 2 assert np.array_equal(f(a_, b_), [0, 1, 0, 1]) a_ = np.array([0, 1, 2, 3]) b_ = np.array([2, 2, 2, 2]) assert np.array_equal(f(a_, b_), [0, 1, 0, 1]) a_ = np.array([2, 3, 4, 5]) b_ = np.array([2, 3, 4, 5]) assert np.array_equal(f(a_, b_), [0, 0, 0, 0]) def test_expm1(): if not np: skip("NumPy not installed") f = lambdify((a,), expm1(a), 'numpy') assert abs(f(1e-10) - 1e-10 - 5e-21) < 1e-22 def test_log1p(): if not np: skip("NumPy not installed") f = lambdify((a,), log1p(a), 'numpy') assert abs(f(1e-99) - 1e-99) < 1e-100 def test_hypot(): if not np: skip("NumPy not installed") assert abs(lambdify((a, b), hypot(a, b), 'numpy')(3, 4) - 5) < 1e-16 def test_log10(): if not np: skip("NumPy not installed") assert abs(lambdify((a,), log10(a), 'numpy')(100) - 2) < 1e-16 def test_exp2(): if not np: skip("NumPy not installed") assert abs(lambdify((a,), exp2(a), 'numpy')(5) - 32) < 1e-16 def test_log2(): if not np: skip("NumPy not installed") assert abs(lambdify((a,), log2(a), 'numpy')(256) - 8) < 1e-16 def test_Sqrt(): if not np: skip("NumPy not installed") assert abs(lambdify((a,), Sqrt(a), 'numpy')(4) - 2) < 1e-16 def test_sqrt(): if not np: skip("NumPy not installed") assert abs(lambdify((a,), sqrt(a), 'numpy')(4) - 2) < 1e-16 def test_matsolve(): if not np: skip("NumPy not installed") M = MatrixSymbol("M", 3, 3) x = MatrixSymbol("x", 3, 1) expr = M**(-1) * x + x matsolve_expr = MatrixSolve(M, x) + x f = lambdify((M, x), expr) f_matsolve = lambdify((M, x), matsolve_expr) m0 = np.array([[1, 2, 3], [3, 2, 5], [5, 6, 7]]) assert np.linalg.matrix_rank(m0) == 3 x0 = np.array([3, 4, 5]) assert np.allclose(f_matsolve(m0, x0), f(m0, x0)) def test_issue_15601(): if not np: skip("Numpy not installed") M = MatrixSymbol("M", 3, 3) N = MatrixSymbol("N", 3, 3) expr = M*N f = lambdify((M, N), expr, "numpy") with warns_deprecated_sympy(): ans = f(eye(3), eye(3)) assert np.array_equal(ans, np.array([1, 0, 0, 0, 1, 0, 0, 0, 1])) def test_16857(): if not np: skip("NumPy not installed") a_1 = MatrixSymbol('a_1', 10, 3) a_2 = MatrixSymbol('a_2', 10, 3) a_3 = MatrixSymbol('a_3', 10, 3) a_4 = MatrixSymbol('a_4', 10, 3) A = BlockMatrix([[a_1, a_2], [a_3, a_4]]) assert A.shape == (20, 6) printer = NumPyPrinter() assert printer.doprint(A) == 'numpy.block([[a_1, a_2], [a_3, a_4]])' def test_issue_17006(): if not np: skip("NumPy not installed") M = MatrixSymbol("M", 2, 2) f = lambdify(M, M + Identity(2)) ma = np.array([[1, 2], [3, 4]]) mr = np.array([[2, 2], [3, 5]]) assert (f(ma) == mr).all() from sympy import symbols n = symbols('n', integer=True) N = MatrixSymbol("M", n, n) raises(NotImplementedError, lambda: lambdify(N, N + Identity(n)))
e029ad6d542fa88394da02af423358ce110555b093186ed987ade630386f2ec7
from sympy.external import import_module from sympy.testing.pytest import raises import ctypes if import_module('llvmlite'): import sympy.printing.llvmjitcode as g else: disabled = True import sympy from sympy.abc import a, b, n # copied from numpy.isclose documentation def isclose(a, b): rtol = 1e-5 atol = 1e-8 return abs(a-b) <= atol + rtol*abs(b) def test_simple_expr(): e = a + 1.0 f = g.llvm_callable([a], e) res = float(e.subs({a: 4.0}).evalf()) jit_res = f(4.0) assert isclose(jit_res, res) def test_two_arg(): e = 4.0*a + b + 3.0 f = g.llvm_callable([a, b], e) res = float(e.subs({a: 4.0, b: 3.0}).evalf()) jit_res = f(4.0, 3.0) assert isclose(jit_res, res) def test_func(): e = 4.0*sympy.exp(-a) f = g.llvm_callable([a], e) res = float(e.subs({a: 1.5}).evalf()) jit_res = f(1.5) assert isclose(jit_res, res) def test_two_func(): e = 4.0*sympy.exp(-a) + sympy.exp(b) f = g.llvm_callable([a, b], e) res = float(e.subs({a: 1.5, b: 2.0}).evalf()) jit_res = f(1.5, 2.0) assert isclose(jit_res, res) def test_two_sqrt(): e = 4.0*sympy.sqrt(a) + sympy.sqrt(b) f = g.llvm_callable([a, b], e) res = float(e.subs({a: 1.5, b: 2.0}).evalf()) jit_res = f(1.5, 2.0) assert isclose(jit_res, res) def test_two_pow(): e = a**1.5 + b**7 f = g.llvm_callable([a, b], e) res = float(e.subs({a: 1.5, b: 2.0}).evalf()) jit_res = f(1.5, 2.0) assert isclose(jit_res, res) def test_callback(): e = a + 1.2 f = g.llvm_callable([a], e, callback_type='scipy.integrate.test') m = ctypes.c_int(1) array_type = ctypes.c_double * 1 inp = {a: 2.2} array = array_type(inp[a]) jit_res = f(m, array) res = float(e.subs(inp).evalf()) assert isclose(jit_res, res) def test_callback_cubature(): e = a + 1.2 f = g.llvm_callable([a], e, callback_type='cubature') m = ctypes.c_int(1) array_type = ctypes.c_double * 1 inp = {a: 2.2} array = array_type(inp[a]) out_array = array_type(0.0) jit_ret = f(m, array, None, m, out_array) assert jit_ret == 0 res = float(e.subs(inp).evalf()) assert isclose(out_array[0], res) def test_callback_two(): e = 3*a*b f = g.llvm_callable([a, b], e, callback_type='scipy.integrate.test') m = ctypes.c_int(2) array_type = ctypes.c_double * 2 inp = {a: 0.2, b: 1.7} array = array_type(inp[a], inp[b]) jit_res = f(m, array) res = float(e.subs(inp).evalf()) assert isclose(jit_res, res) def test_callback_alt_two(): d = sympy.IndexedBase('d') e = 3*d[0]*d[1] f = g.llvm_callable([n, d], e, callback_type='scipy.integrate.test') m = ctypes.c_int(2) array_type = ctypes.c_double * 2 inp = {d[0]: 0.2, d[1]: 1.7} array = array_type(inp[d[0]], inp[d[1]]) jit_res = f(m, array) res = float(e.subs(inp).evalf()) assert isclose(jit_res, res) def test_multiple_statements(): # Match return from CSE e = [[(b, 4.0*a)], [b + 5]] f = g.llvm_callable([a], e) b_val = e[0][0][1].subs({a: 1.5}) res = float(e[1][0].subs({b: b_val}).evalf()) jit_res = f(1.5) assert isclose(jit_res, res) f_callback = g.llvm_callable([a], e, callback_type='scipy.integrate.test') m = ctypes.c_int(1) array_type = ctypes.c_double * 1 array = array_type(1.5) jit_callback_res = f_callback(m, array) assert isclose(jit_callback_res, res) def test_cse(): e = a*a + b*b + sympy.exp(-a*a - b*b) e2 = sympy.cse(e) f = g.llvm_callable([a, b], e2) res = float(e.subs({a: 2.3, b: 0.1}).evalf()) jit_res = f(2.3, 0.1) assert isclose(jit_res, res) def eval_cse(e, sub_dict): tmp_dict = dict() for tmp_name, tmp_expr in e[0]: e2 = tmp_expr.subs(sub_dict) e3 = e2.subs(tmp_dict) tmp_dict[tmp_name] = e3 return [e.subs(sub_dict).subs(tmp_dict) for e in e[1]] def test_cse_multiple(): e1 = a*a e2 = a*a + b*b e3 = sympy.cse([e1, e2]) raises(NotImplementedError, lambda: g.llvm_callable([a, b], e3, callback_type='scipy.integrate')) f = g.llvm_callable([a, b], e3) jit_res = f(0.1, 1.5) assert len(jit_res) == 2 res = eval_cse(e3, {a: 0.1, b: 1.5}) assert isclose(res[0], jit_res[0]) assert isclose(res[1], jit_res[1]) def test_callback_cubature_multiple(): e1 = a*a e2 = a*a + b*b e3 = sympy.cse([e1, e2, 4*e2]) f = g.llvm_callable([a, b], e3, callback_type='cubature') # Number of input variables ndim = 2 # Number of output expression values outdim = 3 m = ctypes.c_int(ndim) fdim = ctypes.c_int(outdim) array_type = ctypes.c_double * ndim out_array_type = ctypes.c_double * outdim inp = {a: 0.2, b: 1.5} array = array_type(inp[a], inp[b]) out_array = out_array_type() jit_ret = f(m, array, None, fdim, out_array) assert jit_ret == 0 res = eval_cse(e3, inp) assert isclose(out_array[0], res[0]) assert isclose(out_array[1], res[1]) assert isclose(out_array[2], res[2]) def test_symbol_not_found(): e = a*a + b raises(LookupError, lambda: g.llvm_callable([a], e)) def test_bad_callback(): e = a raises(ValueError, lambda: g.llvm_callable([a], e, callback_type='bad_callback'))
f39db3ffcae74103abb8a82f421c4ca62efa4ea15a7f81a6bb6271d8f297b053
# -*- coding: utf-8 -*- from sympy import ( And, Basic, Derivative, Dict, Eq, Equivalent, FF, FiniteSet, Function, Ge, Gt, I, Implies, Integral, SingularityFunction, Lambda, Le, Limit, Lt, Matrix, Mul, Nand, Ne, Nor, Not, O, Or, Pow, Product, QQ, RR, Rational, Ray, rootof, RootSum, S, Segment, Subs, Sum, Symbol, Tuple, Trace, Xor, ZZ, conjugate, groebner, oo, pi, symbols, ilex, grlex, Range, Contains, SeqPer, SeqFormula, SeqAdd, SeqMul, fourier_series, fps, ITE, Complement, Interval, Intersection, Union, EulerGamma, GoldenRatio, LambertW, airyai, airybi, airyaiprime, airybiprime, fresnelc, fresnels, Heaviside, dirichlet_eta, diag) from sympy.codegen.ast import (Assignment, AddAugmentedAssignment, SubAugmentedAssignment, MulAugmentedAssignment, DivAugmentedAssignment, ModAugmentedAssignment) from sympy.core.compatibility import u_decode as u from sympy.core.expr import UnevaluatedExpr from sympy.core.trace import Tr from sympy.functions import (Abs, Chi, Ci, Ei, KroneckerDelta, Piecewise, Shi, Si, atan2, beta, binomial, catalan, ceiling, cos, euler, exp, expint, factorial, factorial2, floor, gamma, hyper, log, meijerg, sin, sqrt, subfactorial, tan, uppergamma, lerchphi, elliptic_k, elliptic_f, elliptic_e, elliptic_pi, DiracDelta, bell, bernoulli, fibonacci, tribonacci, lucas, stieltjes, mathieuc, mathieus, mathieusprime, mathieucprime) from sympy.matrices import Adjoint, Inverse, MatrixSymbol, Transpose, KroneckerProduct from sympy.matrices.expressions import hadamard_power from sympy.physics import mechanics from sympy.physics.units import joule, degree from sympy.printing.pretty import pprint, pretty as xpretty from sympy.printing.pretty.pretty_symbology import center_accent, is_combining from sympy import ConditionSet from sympy.sets import ImageSet, ProductSet from sympy.sets.setexpr import SetExpr from sympy.tensor.array import (ImmutableDenseNDimArray, ImmutableSparseNDimArray, MutableDenseNDimArray, MutableSparseNDimArray, tensorproduct) from sympy.tensor.functions import TensorProduct from sympy.tensor.tensor import (TensorIndexType, tensor_indices, TensorHead, TensorElement, tensor_heads) from sympy.testing.pytest import raises from sympy.vector import CoordSys3D, Gradient, Curl, Divergence, Dot, Cross, Laplacian import sympy as sym class lowergamma(sym.lowergamma): pass # testing notation inheritance by a subclass with same name a, b, c, d, x, y, z, k, n = symbols('a,b,c,d,x,y,z,k,n') f = Function("f") th = Symbol('theta') ph = Symbol('phi') """ Expressions whose pretty-printing is tested here: (A '#' to the right of an expression indicates that its various acceptable orderings are accounted for by the tests.) BASIC EXPRESSIONS: oo (x**2) 1/x y*x**-2 x**Rational(-5,2) (-2)**x Pow(3, 1, evaluate=False) (x**2 + x + 1) # 1-x # 1-2*x # x/y -x/y (x+2)/y # (1+x)*y #3 -5*x/(x+10) # correct placement of negative sign 1 - Rational(3,2)*(x+1) -(-x + 5)*(-x - 2*sqrt(2) + 5) - (-y + 5)*(-y + 5) # issue 5524 ORDERING: x**2 + x + 1 1 - x 1 - 2*x 2*x**4 + y**2 - x**2 + y**3 RELATIONAL: Eq(x, y) Lt(x, y) Gt(x, y) Le(x, y) Ge(x, y) Ne(x/(y+1), y**2) # RATIONAL NUMBERS: y*x**-2 y**Rational(3,2) * x**Rational(-5,2) sin(x)**3/tan(x)**2 FUNCTIONS (ABS, CONJ, EXP, FUNCTION BRACES, FACTORIAL, FLOOR, CEILING): (2*x + exp(x)) # Abs(x) Abs(x/(x**2+1)) # Abs(1 / (y - Abs(x))) factorial(n) factorial(2*n) subfactorial(n) subfactorial(2*n) factorial(factorial(factorial(n))) factorial(n+1) # conjugate(x) conjugate(f(x+1)) # f(x) f(x, y) f(x/(y+1), y) # f(x**x**x**x**x**x) sin(x)**2 conjugate(a+b*I) conjugate(exp(a+b*I)) conjugate( f(1 + conjugate(f(x))) ) # f(x/(y+1), y) # denom of first arg floor(1 / (y - floor(x))) ceiling(1 / (y - ceiling(x))) SQRT: sqrt(2) 2**Rational(1,3) 2**Rational(1,1000) sqrt(x**2 + 1) (1 + sqrt(5))**Rational(1,3) 2**(1/x) sqrt(2+pi) (2+(1+x**2)/(2+x))**Rational(1,4)+(1+x**Rational(1,1000))/sqrt(3+x**2) DERIVATIVES: Derivative(log(x), x, evaluate=False) Derivative(log(x), x, evaluate=False) + x # Derivative(log(x) + x**2, x, y, evaluate=False) Derivative(2*x*y, y, x, evaluate=False) + x**2 # beta(alpha).diff(alpha) INTEGRALS: Integral(log(x), x) Integral(x**2, x) Integral((sin(x))**2 / (tan(x))**2) Integral(x**(2**x), x) Integral(x**2, (x,1,2)) Integral(x**2, (x,Rational(1,2),10)) Integral(x**2*y**2, x,y) Integral(x**2, (x, None, 1)) Integral(x**2, (x, 1, None)) Integral(sin(th)/cos(ph), (th,0,pi), (ph, 0, 2*pi)) MATRICES: Matrix([[x**2+1, 1], [y, x+y]]) # Matrix([[x/y, y, th], [0, exp(I*k*ph), 1]]) PIECEWISE: Piecewise((x,x<1),(x**2,True)) ITE: ITE(x, y, z) SEQUENCES (TUPLES, LISTS, DICTIONARIES): () [] {} (1/x,) [x**2, 1/x, x, y, sin(th)**2/cos(ph)**2] (x**2, 1/x, x, y, sin(th)**2/cos(ph)**2) {x: sin(x)} {1/x: 1/y, x: sin(x)**2} # [x**2] (x**2,) {x**2: 1} LIMITS: Limit(x, x, oo) Limit(x**2, x, 0) Limit(1/x, x, 0) Limit(sin(x)/x, x, 0) UNITS: joule => kg*m**2/s SUBS: Subs(f(x), x, ph**2) Subs(f(x).diff(x), x, 0) Subs(f(x).diff(x)/y, (x, y), (0, Rational(1, 2))) ORDER: O(1) O(1/x) O(x**2 + y**2) """ def pretty(expr, order=None): """ASCII pretty-printing""" return xpretty(expr, order=order, use_unicode=False, wrap_line=False) def upretty(expr, order=None): """Unicode pretty-printing""" return xpretty(expr, order=order, use_unicode=True, wrap_line=False) def test_pretty_ascii_str(): assert pretty( 'xxx' ) == 'xxx' assert pretty( "xxx" ) == 'xxx' assert pretty( 'xxx\'xxx' ) == 'xxx\'xxx' assert pretty( 'xxx"xxx' ) == 'xxx\"xxx' assert pretty( 'xxx\"xxx' ) == 'xxx\"xxx' assert pretty( "xxx'xxx" ) == 'xxx\'xxx' assert pretty( "xxx\'xxx" ) == 'xxx\'xxx' assert pretty( "xxx\"xxx" ) == 'xxx\"xxx' assert pretty( "xxx\"xxx\'xxx" ) == 'xxx"xxx\'xxx' assert pretty( "xxx\nxxx" ) == 'xxx\nxxx' def test_pretty_unicode_str(): assert pretty( u'xxx' ) == u'xxx' assert pretty( u'xxx' ) == u'xxx' assert pretty( u'xxx\'xxx' ) == u'xxx\'xxx' assert pretty( u'xxx"xxx' ) == u'xxx\"xxx' assert pretty( u'xxx\"xxx' ) == u'xxx\"xxx' assert pretty( u"xxx'xxx" ) == u'xxx\'xxx' assert pretty( u"xxx\'xxx" ) == u'xxx\'xxx' assert pretty( u"xxx\"xxx" ) == u'xxx\"xxx' assert pretty( u"xxx\"xxx\'xxx" ) == u'xxx"xxx\'xxx' assert pretty( u"xxx\nxxx" ) == u'xxx\nxxx' def test_upretty_greek(): assert upretty( oo ) == u'∞' assert upretty( Symbol('alpha^+_1') ) == u'α⁺₁' assert upretty( Symbol('beta') ) == u'β' assert upretty(Symbol('lambda')) == u'λ' def test_upretty_multiindex(): assert upretty( Symbol('beta12') ) == u'β₁₂' assert upretty( Symbol('Y00') ) == u'Y₀₀' assert upretty( Symbol('Y_00') ) == u'Y₀₀' assert upretty( Symbol('F^+-') ) == u'F⁺⁻' def test_upretty_sub_super(): assert upretty( Symbol('beta_1_2') ) == u'β₁ ₂' assert upretty( Symbol('beta^1^2') ) == u'β¹ ²' assert upretty( Symbol('beta_1^2') ) == u'β²₁' assert upretty( Symbol('beta_10_20') ) == u'β₁₀ ₂₀' assert upretty( Symbol('beta_ax_gamma^i') ) == u'βⁱₐₓ ᵧ' assert upretty( Symbol("F^1^2_3_4") ) == u'F¹ ²₃ ₄' assert upretty( Symbol("F_1_2^3^4") ) == u'F³ ⁴₁ ₂' assert upretty( Symbol("F_1_2_3_4") ) == u'F₁ ₂ ₃ ₄' assert upretty( Symbol("F^1^2^3^4") ) == u'F¹ ² ³ ⁴' def test_upretty_subs_missing_in_24(): assert upretty( Symbol('F_beta') ) == u'Fᵦ' assert upretty( Symbol('F_gamma') ) == u'Fᵧ' assert upretty( Symbol('F_rho') ) == u'Fᵨ' assert upretty( Symbol('F_phi') ) == u'Fᵩ' assert upretty( Symbol('F_chi') ) == u'Fᵪ' assert upretty( Symbol('F_a') ) == u'Fₐ' assert upretty( Symbol('F_e') ) == u'Fₑ' assert upretty( Symbol('F_i') ) == u'Fᵢ' assert upretty( Symbol('F_o') ) == u'Fₒ' assert upretty( Symbol('F_u') ) == u'Fᵤ' assert upretty( Symbol('F_r') ) == u'Fᵣ' assert upretty( Symbol('F_v') ) == u'Fᵥ' assert upretty( Symbol('F_x') ) == u'Fₓ' def test_missing_in_2X_issue_9047(): assert upretty( Symbol('F_h') ) == u'Fₕ' assert upretty( Symbol('F_k') ) == u'Fₖ' assert upretty( Symbol('F_l') ) == u'Fₗ' assert upretty( Symbol('F_m') ) == u'Fₘ' assert upretty( Symbol('F_n') ) == u'Fₙ' assert upretty( Symbol('F_p') ) == u'Fₚ' assert upretty( Symbol('F_s') ) == u'Fₛ' assert upretty( Symbol('F_t') ) == u'Fₜ' def test_upretty_modifiers(): # Accents assert upretty( Symbol('Fmathring') ) == u'F̊' assert upretty( Symbol('Fddddot') ) == u'F⃜' assert upretty( Symbol('Fdddot') ) == u'F⃛' assert upretty( Symbol('Fddot') ) == u'F̈' assert upretty( Symbol('Fdot') ) == u'Ḟ' assert upretty( Symbol('Fcheck') ) == u'F̌' assert upretty( Symbol('Fbreve') ) == u'F̆' assert upretty( Symbol('Facute') ) == u'F́' assert upretty( Symbol('Fgrave') ) == u'F̀' assert upretty( Symbol('Ftilde') ) == u'F̃' assert upretty( Symbol('Fhat') ) == u'F̂' assert upretty( Symbol('Fbar') ) == u'F̅' assert upretty( Symbol('Fvec') ) == u'F⃗' assert upretty( Symbol('Fprime') ) == u'F′' assert upretty( Symbol('Fprm') ) == u'F′' # No faces are actually implemented, but test to make sure the modifiers are stripped assert upretty( Symbol('Fbold') ) == u'Fbold' assert upretty( Symbol('Fbm') ) == u'Fbm' assert upretty( Symbol('Fcal') ) == u'Fcal' assert upretty( Symbol('Fscr') ) == u'Fscr' assert upretty( Symbol('Ffrak') ) == u'Ffrak' # Brackets assert upretty( Symbol('Fnorm') ) == u'‖F‖' assert upretty( Symbol('Favg') ) == u'⟨F⟩' assert upretty( Symbol('Fabs') ) == u'|F|' assert upretty( Symbol('Fmag') ) == u'|F|' # Combinations assert upretty( Symbol('xvecdot') ) == u'x⃗̇' assert upretty( Symbol('xDotVec') ) == u'ẋ⃗' assert upretty( Symbol('xHATNorm') ) == u'‖x̂‖' assert upretty( Symbol('xMathring_yCheckPRM__zbreveAbs') ) == u'x̊_y̌′__|z̆|' assert upretty( Symbol('alphadothat_nVECDOT__tTildePrime') ) == u'α̇̂_n⃗̇__t̃′' assert upretty( Symbol('x_dot') ) == u'x_dot' assert upretty( Symbol('x__dot') ) == u'x__dot' def test_pretty_Cycle(): from sympy.combinatorics.permutations import Cycle assert pretty(Cycle(1, 2)) == '(1 2)' assert pretty(Cycle(2)) == '(2)' assert pretty(Cycle(1, 3)(4, 5)) == '(1 3)(4 5)' assert pretty(Cycle()) == '()' def test_pretty_Permutation(): from sympy.combinatorics.permutations import Permutation p1 = Permutation(1, 2)(3, 4) assert xpretty(p1, perm_cyclic=True, use_unicode=True) == "(1 2)(3 4)" assert xpretty(p1, perm_cyclic=True, use_unicode=False) == "(1 2)(3 4)" assert xpretty(p1, perm_cyclic=False, use_unicode=True) == \ u'⎛0 1 2 3 4⎞\n'\ u'⎝0 2 1 4 3⎠' assert xpretty(p1, perm_cyclic=False, use_unicode=False) == \ "/0 1 2 3 4\\\n"\ "\\0 2 1 4 3/" def test_pretty_basic(): assert pretty( -Rational(1)/2 ) == '-1/2' assert pretty( -Rational(13)/22 ) == \ """\ -13 \n\ ----\n\ 22 \ """ expr = oo ascii_str = \ """\ oo\ """ ucode_str = \ u("""\ ∞\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = (x**2) ascii_str = \ """\ 2\n\ x \ """ ucode_str = \ u("""\ 2\n\ x \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = 1/x ascii_str = \ """\ 1\n\ -\n\ x\ """ ucode_str = \ u("""\ 1\n\ ─\n\ x\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str # not the same as 1/x expr = x**-1.0 ascii_str = \ """\ -1.0\n\ x \ """ ucode_str = \ ("""\ -1.0\n\ x \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str # see issue #2860 expr = Pow(S(2), -1.0, evaluate=False) ascii_str = \ """\ -1.0\n\ 2 \ """ ucode_str = \ ("""\ -1.0\n\ 2 \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = y*x**-2 ascii_str = \ """\ y \n\ --\n\ 2\n\ x \ """ ucode_str = \ u("""\ y \n\ ──\n\ 2\n\ x \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str #see issue #14033 expr = x**Rational(1, 3) ascii_str = \ """\ 1/3\n\ x \ """ ucode_str = \ u("""\ 1/3\n\ x \ """) assert xpretty(expr, use_unicode=False, wrap_line=False,\ root_notation = False) == ascii_str assert xpretty(expr, use_unicode=True, wrap_line=False,\ root_notation = False) == ucode_str expr = x**Rational(-5, 2) ascii_str = \ """\ 1 \n\ ----\n\ 5/2\n\ x \ """ ucode_str = \ u("""\ 1 \n\ ────\n\ 5/2\n\ x \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = (-2)**x ascii_str = \ """\ x\n\ (-2) \ """ ucode_str = \ u("""\ x\n\ (-2) \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str # See issue 4923 expr = Pow(3, 1, evaluate=False) ascii_str = \ """\ 1\n\ 3 \ """ ucode_str = \ u("""\ 1\n\ 3 \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = (x**2 + x + 1) ascii_str_1 = \ """\ 2\n\ 1 + x + x \ """ ascii_str_2 = \ """\ 2 \n\ x + x + 1\ """ ascii_str_3 = \ """\ 2 \n\ x + 1 + x\ """ ucode_str_1 = \ u("""\ 2\n\ 1 + x + x \ """) ucode_str_2 = \ u("""\ 2 \n\ x + x + 1\ """) ucode_str_3 = \ u("""\ 2 \n\ x + 1 + x\ """) assert pretty(expr) in [ascii_str_1, ascii_str_2, ascii_str_3] assert upretty(expr) in [ucode_str_1, ucode_str_2, ucode_str_3] expr = 1 - x ascii_str_1 = \ """\ 1 - x\ """ ascii_str_2 = \ """\ -x + 1\ """ ucode_str_1 = \ u("""\ 1 - x\ """) ucode_str_2 = \ u("""\ -x + 1\ """) assert pretty(expr) in [ascii_str_1, ascii_str_2] assert upretty(expr) in [ucode_str_1, ucode_str_2] expr = 1 - 2*x ascii_str_1 = \ """\ 1 - 2*x\ """ ascii_str_2 = \ """\ -2*x + 1\ """ ucode_str_1 = \ u("""\ 1 - 2⋅x\ """) ucode_str_2 = \ u("""\ -2⋅x + 1\ """) assert pretty(expr) in [ascii_str_1, ascii_str_2] assert upretty(expr) in [ucode_str_1, ucode_str_2] expr = x/y ascii_str = \ """\ x\n\ -\n\ y\ """ ucode_str = \ u("""\ x\n\ ─\n\ y\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = -x/y ascii_str = \ """\ -x \n\ ---\n\ y \ """ ucode_str = \ u("""\ -x \n\ ───\n\ y \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = (x + 2)/y ascii_str_1 = \ """\ 2 + x\n\ -----\n\ y \ """ ascii_str_2 = \ """\ x + 2\n\ -----\n\ y \ """ ucode_str_1 = \ u("""\ 2 + x\n\ ─────\n\ y \ """) ucode_str_2 = \ u("""\ x + 2\n\ ─────\n\ y \ """) assert pretty(expr) in [ascii_str_1, ascii_str_2] assert upretty(expr) in [ucode_str_1, ucode_str_2] expr = (1 + x)*y ascii_str_1 = \ """\ y*(1 + x)\ """ ascii_str_2 = \ """\ (1 + x)*y\ """ ascii_str_3 = \ """\ y*(x + 1)\ """ ucode_str_1 = \ u("""\ y⋅(1 + x)\ """) ucode_str_2 = \ u("""\ (1 + x)⋅y\ """) ucode_str_3 = \ u("""\ y⋅(x + 1)\ """) assert pretty(expr) in [ascii_str_1, ascii_str_2, ascii_str_3] assert upretty(expr) in [ucode_str_1, ucode_str_2, ucode_str_3] # Test for correct placement of the negative sign expr = -5*x/(x + 10) ascii_str_1 = \ """\ -5*x \n\ ------\n\ 10 + x\ """ ascii_str_2 = \ """\ -5*x \n\ ------\n\ x + 10\ """ ucode_str_1 = \ u("""\ -5⋅x \n\ ──────\n\ 10 + x\ """) ucode_str_2 = \ u("""\ -5⋅x \n\ ──────\n\ x + 10\ """) assert pretty(expr) in [ascii_str_1, ascii_str_2] assert upretty(expr) in [ucode_str_1, ucode_str_2] expr = -S.Half - 3*x ascii_str = \ """\ -3*x - 1/2\ """ ucode_str = \ u("""\ -3⋅x - 1/2\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = S.Half - 3*x ascii_str = \ """\ 1/2 - 3*x\ """ ucode_str = \ u("""\ 1/2 - 3⋅x\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = -S.Half - 3*x/2 ascii_str = \ """\ 3*x 1\n\ - --- - -\n\ 2 2\ """ ucode_str = \ u("""\ 3⋅x 1\n\ - ─── - ─\n\ 2 2\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = S.Half - 3*x/2 ascii_str = \ """\ 1 3*x\n\ - - ---\n\ 2 2 \ """ ucode_str = \ u("""\ 1 3⋅x\n\ ─ - ───\n\ 2 2 \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_negative_fractions(): expr = -x/y ascii_str =\ """\ -x \n\ ---\n\ y \ """ ucode_str =\ u("""\ -x \n\ ───\n\ y \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = -x*z/y ascii_str =\ """\ -x*z \n\ -----\n\ y \ """ ucode_str =\ u("""\ -x⋅z \n\ ─────\n\ y \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = x**2/y ascii_str =\ """\ 2\n\ x \n\ --\n\ y \ """ ucode_str =\ u("""\ 2\n\ x \n\ ──\n\ y \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = -x**2/y ascii_str =\ """\ 2 \n\ -x \n\ ----\n\ y \ """ ucode_str =\ u("""\ 2 \n\ -x \n\ ────\n\ y \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = -x/(y*z) ascii_str =\ """\ -x \n\ ---\n\ y*z\ """ ucode_str =\ u("""\ -x \n\ ───\n\ y⋅z\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = -a/y**2 ascii_str =\ """\ -a \n\ ---\n\ 2\n\ y \ """ ucode_str =\ u("""\ -a \n\ ───\n\ 2\n\ y \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = y**(-a/b) ascii_str =\ """\ -a \n\ ---\n\ b \n\ y \ """ ucode_str =\ u("""\ -a \n\ ───\n\ b \n\ y \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = -1/y**2 ascii_str =\ """\ -1 \n\ ---\n\ 2\n\ y \ """ ucode_str =\ u("""\ -1 \n\ ───\n\ 2\n\ y \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = -10/b**2 ascii_str =\ """\ -10 \n\ ----\n\ 2 \n\ b \ """ ucode_str =\ u("""\ -10 \n\ ────\n\ 2 \n\ b \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Rational(-200, 37) ascii_str =\ """\ -200 \n\ -----\n\ 37 \ """ ucode_str =\ u("""\ -200 \n\ ─────\n\ 37 \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_issue_5524(): assert pretty(-(-x + 5)*(-x - 2*sqrt(2) + 5) - (-y + 5)*(-y + 5)) == \ """\ 2 / ___ \\\n\ - (5 - y) + (x - 5)*\\-x - 2*\\/ 2 + 5/\ """ assert upretty(-(-x + 5)*(-x - 2*sqrt(2) + 5) - (-y + 5)*(-y + 5)) == \ u("""\ 2 \n\ - (5 - y) + (x - 5)⋅(-x - 2⋅√2 + 5)\ """) def test_pretty_ordering(): assert pretty(x**2 + x + 1, order='lex') == \ """\ 2 \n\ x + x + 1\ """ assert pretty(x**2 + x + 1, order='rev-lex') == \ """\ 2\n\ 1 + x + x \ """ assert pretty(1 - x, order='lex') == '-x + 1' assert pretty(1 - x, order='rev-lex') == '1 - x' assert pretty(1 - 2*x, order='lex') == '-2*x + 1' assert pretty(1 - 2*x, order='rev-lex') == '1 - 2*x' f = 2*x**4 + y**2 - x**2 + y**3 assert pretty(f, order=None) == \ """\ 4 2 3 2\n\ 2*x - x + y + y \ """ assert pretty(f, order='lex') == \ """\ 4 2 3 2\n\ 2*x - x + y + y \ """ assert pretty(f, order='rev-lex') == \ """\ 2 3 2 4\n\ y + y - x + 2*x \ """ expr = x - x**3/6 + x**5/120 + O(x**6) ascii_str = \ """\ 3 5 \n\ x x / 6\\\n\ x - -- + --- + O\\x /\n\ 6 120 \ """ ucode_str = \ u("""\ 3 5 \n\ x x ⎛ 6⎞\n\ x - ── + ─── + O⎝x ⎠\n\ 6 120 \ """) assert pretty(expr, order=None) == ascii_str assert upretty(expr, order=None) == ucode_str assert pretty(expr, order='lex') == ascii_str assert upretty(expr, order='lex') == ucode_str assert pretty(expr, order='rev-lex') == ascii_str assert upretty(expr, order='rev-lex') == ucode_str def test_EulerGamma(): assert pretty(EulerGamma) == str(EulerGamma) == "EulerGamma" assert upretty(EulerGamma) == u"γ" def test_GoldenRatio(): assert pretty(GoldenRatio) == str(GoldenRatio) == "GoldenRatio" assert upretty(GoldenRatio) == u"φ" def test_pretty_relational(): expr = Eq(x, y) ascii_str = \ """\ x = y\ """ ucode_str = \ u("""\ x = y\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Lt(x, y) ascii_str = \ """\ x < y\ """ ucode_str = \ u("""\ x < y\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Gt(x, y) ascii_str = \ """\ x > y\ """ ucode_str = \ u("""\ x > y\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Le(x, y) ascii_str = \ """\ x <= y\ """ ucode_str = \ u("""\ x ≤ y\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Ge(x, y) ascii_str = \ """\ x >= y\ """ ucode_str = \ u("""\ x ≥ y\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Ne(x/(y + 1), y**2) ascii_str_1 = \ """\ x 2\n\ ----- != y \n\ 1 + y \ """ ascii_str_2 = \ """\ x 2\n\ ----- != y \n\ y + 1 \ """ ucode_str_1 = \ u("""\ x 2\n\ ───── ≠ y \n\ 1 + y \ """) ucode_str_2 = \ u("""\ x 2\n\ ───── ≠ y \n\ y + 1 \ """) assert pretty(expr) in [ascii_str_1, ascii_str_2] assert upretty(expr) in [ucode_str_1, ucode_str_2] def test_Assignment(): expr = Assignment(x, y) ascii_str = \ """\ x := y\ """ ucode_str = \ u("""\ x := y\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_AugmentedAssignment(): expr = AddAugmentedAssignment(x, y) ascii_str = \ """\ x += y\ """ ucode_str = \ u("""\ x += y\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = SubAugmentedAssignment(x, y) ascii_str = \ """\ x -= y\ """ ucode_str = \ u("""\ x -= y\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = MulAugmentedAssignment(x, y) ascii_str = \ """\ x *= y\ """ ucode_str = \ u("""\ x *= y\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = DivAugmentedAssignment(x, y) ascii_str = \ """\ x /= y\ """ ucode_str = \ u("""\ x /= y\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = ModAugmentedAssignment(x, y) ascii_str = \ """\ x %= y\ """ ucode_str = \ u("""\ x %= y\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_pretty_rational(): expr = y*x**-2 ascii_str = \ """\ y \n\ --\n\ 2\n\ x \ """ ucode_str = \ u("""\ y \n\ ──\n\ 2\n\ x \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = y**Rational(3, 2) * x**Rational(-5, 2) ascii_str = \ """\ 3/2\n\ y \n\ ----\n\ 5/2\n\ x \ """ ucode_str = \ u("""\ 3/2\n\ y \n\ ────\n\ 5/2\n\ x \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = sin(x)**3/tan(x)**2 ascii_str = \ """\ 3 \n\ sin (x)\n\ -------\n\ 2 \n\ tan (x)\ """ ucode_str = \ u("""\ 3 \n\ sin (x)\n\ ───────\n\ 2 \n\ tan (x)\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_pretty_functions(): """Tests for Abs, conjugate, exp, function braces, and factorial.""" expr = (2*x + exp(x)) ascii_str_1 = \ """\ x\n\ 2*x + e \ """ ascii_str_2 = \ """\ x \n\ e + 2*x\ """ ucode_str_1 = \ u("""\ x\n\ 2⋅x + ℯ \ """) ucode_str_2 = \ u("""\ x \n\ ℯ + 2⋅x\ """) assert pretty(expr) in [ascii_str_1, ascii_str_2] assert upretty(expr) in [ucode_str_1, ucode_str_2] expr = Abs(x) ascii_str = \ """\ |x|\ """ ucode_str = \ u("""\ │x│\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Abs(x/(x**2 + 1)) ascii_str_1 = \ """\ | x |\n\ |------|\n\ | 2|\n\ |1 + x |\ """ ascii_str_2 = \ """\ | x |\n\ |------|\n\ | 2 |\n\ |x + 1|\ """ ucode_str_1 = \ u("""\ │ x │\n\ │──────│\n\ │ 2│\n\ │1 + x │\ """) ucode_str_2 = \ u("""\ │ x │\n\ │──────│\n\ │ 2 │\n\ │x + 1│\ """) assert pretty(expr) in [ascii_str_1, ascii_str_2] assert upretty(expr) in [ucode_str_1, ucode_str_2] expr = Abs(1 / (y - Abs(x))) ascii_str = \ """\ 1 \n\ ---------\n\ |y - |x||\ """ ucode_str = \ u("""\ 1 \n\ ─────────\n\ │y - │x││\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str n = Symbol('n', integer=True) expr = factorial(n) ascii_str = \ """\ n!\ """ ucode_str = \ u("""\ n!\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = factorial(2*n) ascii_str = \ """\ (2*n)!\ """ ucode_str = \ u("""\ (2⋅n)!\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = factorial(factorial(factorial(n))) ascii_str = \ """\ ((n!)!)!\ """ ucode_str = \ u("""\ ((n!)!)!\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = factorial(n + 1) ascii_str_1 = \ """\ (1 + n)!\ """ ascii_str_2 = \ """\ (n + 1)!\ """ ucode_str_1 = \ u("""\ (1 + n)!\ """) ucode_str_2 = \ u("""\ (n + 1)!\ """) assert pretty(expr) in [ascii_str_1, ascii_str_2] assert upretty(expr) in [ucode_str_1, ucode_str_2] expr = subfactorial(n) ascii_str = \ """\ !n\ """ ucode_str = \ u("""\ !n\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = subfactorial(2*n) ascii_str = \ """\ !(2*n)\ """ ucode_str = \ u("""\ !(2⋅n)\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str n = Symbol('n', integer=True) expr = factorial2(n) ascii_str = \ """\ n!!\ """ ucode_str = \ u("""\ n!!\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = factorial2(2*n) ascii_str = \ """\ (2*n)!!\ """ ucode_str = \ u("""\ (2⋅n)!!\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = factorial2(factorial2(factorial2(n))) ascii_str = \ """\ ((n!!)!!)!!\ """ ucode_str = \ u("""\ ((n!!)!!)!!\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = factorial2(n + 1) ascii_str_1 = \ """\ (1 + n)!!\ """ ascii_str_2 = \ """\ (n + 1)!!\ """ ucode_str_1 = \ u("""\ (1 + n)!!\ """) ucode_str_2 = \ u("""\ (n + 1)!!\ """) assert pretty(expr) in [ascii_str_1, ascii_str_2] assert upretty(expr) in [ucode_str_1, ucode_str_2] expr = 2*binomial(n, k) ascii_str = \ """\ /n\\\n\ 2*| |\n\ \\k/\ """ ucode_str = \ u("""\ ⎛n⎞\n\ 2⋅⎜ ⎟\n\ ⎝k⎠\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = 2*binomial(2*n, k) ascii_str = \ """\ /2*n\\\n\ 2*| |\n\ \\ k /\ """ ucode_str = \ u("""\ ⎛2⋅n⎞\n\ 2⋅⎜ ⎟\n\ ⎝ k ⎠\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = 2*binomial(n**2, k) ascii_str = \ """\ / 2\\\n\ |n |\n\ 2*| |\n\ \\k /\ """ ucode_str = \ u("""\ ⎛ 2⎞\n\ ⎜n ⎟\n\ 2⋅⎜ ⎟\n\ ⎝k ⎠\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = catalan(n) ascii_str = \ """\ C \n\ n\ """ ucode_str = \ u("""\ C \n\ n\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = catalan(n) ascii_str = \ """\ C \n\ n\ """ ucode_str = \ u("""\ C \n\ n\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = bell(n) ascii_str = \ """\ B \n\ n\ """ ucode_str = \ u("""\ B \n\ n\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = bernoulli(n) ascii_str = \ """\ B \n\ n\ """ ucode_str = \ u("""\ B \n\ n\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = bernoulli(n, x) ascii_str = \ """\ B (x)\n\ n \ """ ucode_str = \ u("""\ B (x)\n\ n \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = fibonacci(n) ascii_str = \ """\ F \n\ n\ """ ucode_str = \ u("""\ F \n\ n\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = lucas(n) ascii_str = \ """\ L \n\ n\ """ ucode_str = \ u("""\ L \n\ n\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = tribonacci(n) ascii_str = \ """\ T \n\ n\ """ ucode_str = \ u("""\ T \n\ n\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = stieltjes(n) ascii_str = \ """\ stieltjes \n\ n\ """ ucode_str = \ u("""\ γ \n\ n\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = stieltjes(n, x) ascii_str = \ """\ stieltjes (x)\n\ n \ """ ucode_str = \ u("""\ γ (x)\n\ n \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = mathieuc(x, y, z) ascii_str = 'C(x, y, z)' ucode_str = u('C(x, y, z)') assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = mathieus(x, y, z) ascii_str = 'S(x, y, z)' ucode_str = u('S(x, y, z)') assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = mathieucprime(x, y, z) ascii_str = "C'(x, y, z)" ucode_str = u("C'(x, y, z)") assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = mathieusprime(x, y, z) ascii_str = "S'(x, y, z)" ucode_str = u("S'(x, y, z)") assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = conjugate(x) ascii_str = \ """\ _\n\ x\ """ ucode_str = \ u("""\ _\n\ x\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str f = Function('f') expr = conjugate(f(x + 1)) ascii_str_1 = \ """\ ________\n\ f(1 + x)\ """ ascii_str_2 = \ """\ ________\n\ f(x + 1)\ """ ucode_str_1 = \ u("""\ ________\n\ f(1 + x)\ """) ucode_str_2 = \ u("""\ ________\n\ f(x + 1)\ """) assert pretty(expr) in [ascii_str_1, ascii_str_2] assert upretty(expr) in [ucode_str_1, ucode_str_2] expr = f(x) ascii_str = \ """\ f(x)\ """ ucode_str = \ u("""\ f(x)\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = f(x, y) ascii_str = \ """\ f(x, y)\ """ ucode_str = \ u("""\ f(x, y)\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = f(x/(y + 1), y) ascii_str_1 = \ """\ / x \\\n\ f|-----, y|\n\ \\1 + y /\ """ ascii_str_2 = \ """\ / x \\\n\ f|-----, y|\n\ \\y + 1 /\ """ ucode_str_1 = \ u("""\ ⎛ x ⎞\n\ f⎜─────, y⎟\n\ ⎝1 + y ⎠\ """) ucode_str_2 = \ u("""\ ⎛ x ⎞\n\ f⎜─────, y⎟\n\ ⎝y + 1 ⎠\ """) assert pretty(expr) in [ascii_str_1, ascii_str_2] assert upretty(expr) in [ucode_str_1, ucode_str_2] expr = f(x**x**x**x**x**x) ascii_str = \ """\ / / / / / x\\\\\\\\\\ | | | | \\x /|||| | | | \\x /||| | | \\x /|| | \\x /| f\\x /\ """ ucode_str = \ u("""\ ⎛ ⎛ ⎛ ⎛ ⎛ x⎞⎞⎞⎞⎞ ⎜ ⎜ ⎜ ⎜ ⎝x ⎠⎟⎟⎟⎟ ⎜ ⎜ ⎜ ⎝x ⎠⎟⎟⎟ ⎜ ⎜ ⎝x ⎠⎟⎟ ⎜ ⎝x ⎠⎟ f⎝x ⎠\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = sin(x)**2 ascii_str = \ """\ 2 \n\ sin (x)\ """ ucode_str = \ u("""\ 2 \n\ sin (x)\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = conjugate(a + b*I) ascii_str = \ """\ _ _\n\ a - I*b\ """ ucode_str = \ u("""\ _ _\n\ a - ⅈ⋅b\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = conjugate(exp(a + b*I)) ascii_str = \ """\ _ _\n\ a - I*b\n\ e \ """ ucode_str = \ u("""\ _ _\n\ a - ⅈ⋅b\n\ ℯ \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = conjugate( f(1 + conjugate(f(x))) ) ascii_str_1 = \ """\ ___________\n\ / ____\\\n\ f\\1 + f(x)/\ """ ascii_str_2 = \ """\ ___________\n\ /____ \\\n\ f\\f(x) + 1/\ """ ucode_str_1 = \ u("""\ ___________\n\ ⎛ ____⎞\n\ f⎝1 + f(x)⎠\ """) ucode_str_2 = \ u("""\ ___________\n\ ⎛____ ⎞\n\ f⎝f(x) + 1⎠\ """) assert pretty(expr) in [ascii_str_1, ascii_str_2] assert upretty(expr) in [ucode_str_1, ucode_str_2] expr = f(x/(y + 1), y) ascii_str_1 = \ """\ / x \\\n\ f|-----, y|\n\ \\1 + y /\ """ ascii_str_2 = \ """\ / x \\\n\ f|-----, y|\n\ \\y + 1 /\ """ ucode_str_1 = \ u("""\ ⎛ x ⎞\n\ f⎜─────, y⎟\n\ ⎝1 + y ⎠\ """) ucode_str_2 = \ u("""\ ⎛ x ⎞\n\ f⎜─────, y⎟\n\ ⎝y + 1 ⎠\ """) assert pretty(expr) in [ascii_str_1, ascii_str_2] assert upretty(expr) in [ucode_str_1, ucode_str_2] expr = floor(1 / (y - floor(x))) ascii_str = \ """\ / 1 \\\n\ floor|------------|\n\ \\y - floor(x)/\ """ ucode_str = \ u("""\ ⎢ 1 ⎥\n\ ⎢───────⎥\n\ ⎣y - ⌊x⌋⎦\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = ceiling(1 / (y - ceiling(x))) ascii_str = \ """\ / 1 \\\n\ ceiling|--------------|\n\ \\y - ceiling(x)/\ """ ucode_str = \ u("""\ ⎡ 1 ⎤\n\ ⎢───────⎥\n\ ⎢y - ⌈x⌉⎥\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = euler(n) ascii_str = \ """\ E \n\ n\ """ ucode_str = \ u("""\ E \n\ n\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = euler(1/(1 + 1/(1 + 1/n))) ascii_str = \ """\ E \n\ 1 \n\ ---------\n\ 1 \n\ 1 + -----\n\ 1\n\ 1 + -\n\ n\ """ ucode_str = \ u("""\ E \n\ 1 \n\ ─────────\n\ 1 \n\ 1 + ─────\n\ 1\n\ 1 + ─\n\ n\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = euler(n, x) ascii_str = \ """\ E (x)\n\ n \ """ ucode_str = \ u("""\ E (x)\n\ n \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = euler(n, x/2) ascii_str = \ """\ /x\\\n\ E |-|\n\ n\\2/\ """ ucode_str = \ u("""\ ⎛x⎞\n\ E ⎜─⎟\n\ n⎝2⎠\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_pretty_sqrt(): expr = sqrt(2) ascii_str = \ """\ ___\n\ \\/ 2 \ """ ucode_str = \ u"√2" assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = 2**Rational(1, 3) ascii_str = \ """\ 3 ___\n\ \\/ 2 \ """ ucode_str = \ u("""\ 3 ___\n\ ╲╱ 2 \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = 2**Rational(1, 1000) ascii_str = \ """\ 1000___\n\ \\/ 2 \ """ ucode_str = \ u("""\ 1000___\n\ ╲╱ 2 \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = sqrt(x**2 + 1) ascii_str = \ """\ ________\n\ / 2 \n\ \\/ x + 1 \ """ ucode_str = \ u("""\ ________\n\ ╱ 2 \n\ ╲╱ x + 1 \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = (1 + sqrt(5))**Rational(1, 3) ascii_str = \ """\ ___________\n\ 3 / ___ \n\ \\/ 1 + \\/ 5 \ """ ucode_str = \ u("""\ 3 ________\n\ ╲╱ 1 + √5 \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = 2**(1/x) ascii_str = \ """\ x ___\n\ \\/ 2 \ """ ucode_str = \ u("""\ x ___\n\ ╲╱ 2 \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = sqrt(2 + pi) ascii_str = \ """\ ________\n\ \\/ 2 + pi \ """ ucode_str = \ u("""\ _______\n\ ╲╱ 2 + π \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = (2 + ( 1 + x**2)/(2 + x))**Rational(1, 4) + (1 + x**Rational(1, 1000))/sqrt(3 + x**2) ascii_str = \ """\ ____________ \n\ / 2 1000___ \n\ / x + 1 \\/ x + 1\n\ 4 / 2 + ------ + -----------\n\ \\/ x + 2 ________\n\ / 2 \n\ \\/ x + 3 \ """ ucode_str = \ u("""\ ____________ \n\ ╱ 2 1000___ \n\ ╱ x + 1 ╲╱ x + 1\n\ 4 ╱ 2 + ────── + ───────────\n\ ╲╱ x + 2 ________\n\ ╱ 2 \n\ ╲╱ x + 3 \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_pretty_sqrt_char_knob(): # See PR #9234. expr = sqrt(2) ucode_str1 = \ u("""\ ___\n\ ╲╱ 2 \ """) ucode_str2 = \ u"√2" assert xpretty(expr, use_unicode=True, use_unicode_sqrt_char=False) == ucode_str1 assert xpretty(expr, use_unicode=True, use_unicode_sqrt_char=True) == ucode_str2 def test_pretty_sqrt_longsymbol_no_sqrt_char(): # Do not use unicode sqrt char for long symbols (see PR #9234). expr = sqrt(Symbol('C1')) ucode_str = \ u("""\ ____\n\ ╲╱ C₁ \ """) assert upretty(expr) == ucode_str def test_pretty_KroneckerDelta(): x, y = symbols("x, y") expr = KroneckerDelta(x, y) ascii_str = \ """\ d \n\ x,y\ """ ucode_str = \ u("""\ δ \n\ x,y\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_pretty_product(): n, m, k, l = symbols('n m k l') f = symbols('f', cls=Function) expr = Product(f((n/3)**2), (n, k**2, l)) unicode_str = \ u("""\ l \n\ ─┬──────┬─ \n\ │ │ ⎛ 2⎞\n\ │ │ ⎜n ⎟\n\ │ │ f⎜──⎟\n\ │ │ ⎝9 ⎠\n\ │ │ \n\ 2 \n\ n = k """) ascii_str = \ """\ l \n\ __________ \n\ | | / 2\\\n\ | | |n |\n\ | | f|--|\n\ | | \\9 /\n\ | | \n\ 2 \n\ n = k """ expr = Product(f((n/3)**2), (n, k**2, l), (l, 1, m)) unicode_str = \ u("""\ m l \n\ ─┬──────┬─ ─┬──────┬─ \n\ │ │ │ │ ⎛ 2⎞\n\ │ │ │ │ ⎜n ⎟\n\ │ │ │ │ f⎜──⎟\n\ │ │ │ │ ⎝9 ⎠\n\ │ │ │ │ \n\ l = 1 2 \n\ n = k """) ascii_str = \ """\ m l \n\ __________ __________ \n\ | | | | / 2\\\n\ | | | | |n |\n\ | | | | f|--|\n\ | | | | \\9 /\n\ | | | | \n\ l = 1 2 \n\ n = k """ assert pretty(expr) == ascii_str assert upretty(expr) == unicode_str def test_pretty_Lambda(): # S.IdentityFunction is a special case expr = Lambda(y, y) assert pretty(expr) == "x -> x" assert upretty(expr) == u"x ↦ x" expr = Lambda(x, x+1) assert pretty(expr) == "x -> x + 1" assert upretty(expr) == u"x ↦ x + 1" expr = Lambda(x, x**2) ascii_str = \ """\ 2\n\ x -> x \ """ ucode_str = \ u("""\ 2\n\ x ↦ x \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Lambda(x, x**2)**2 ascii_str = \ """\ 2 / 2\\ \n\ \\x -> x / \ """ ucode_str = \ u("""\ 2 ⎛ 2⎞ \n\ ⎝x ↦ x ⎠ \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Lambda((x, y), x) ascii_str = "(x, y) -> x" ucode_str = u"(x, y) ↦ x" assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Lambda((x, y), x**2) ascii_str = \ """\ 2\n\ (x, y) -> x \ """ ucode_str = \ u("""\ 2\n\ (x, y) ↦ x \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Lambda(((x, y),), x**2) ascii_str = \ """\ 2\n\ ((x, y),) -> x \ """ ucode_str = \ u("""\ 2\n\ ((x, y),) ↦ x \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_pretty_order(): expr = O(1) ascii_str = \ """\ O(1)\ """ ucode_str = \ u("""\ O(1)\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = O(1/x) ascii_str = \ """\ /1\\\n\ O|-|\n\ \\x/\ """ ucode_str = \ u("""\ ⎛1⎞\n\ O⎜─⎟\n\ ⎝x⎠\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = O(x**2 + y**2) ascii_str = \ """\ / 2 2 \\\n\ O\\x + y ; (x, y) -> (0, 0)/\ """ ucode_str = \ u("""\ ⎛ 2 2 ⎞\n\ O⎝x + y ; (x, y) → (0, 0)⎠\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = O(1, (x, oo)) ascii_str = \ """\ O(1; x -> oo)\ """ ucode_str = \ u("""\ O(1; x → ∞)\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = O(1/x, (x, oo)) ascii_str = \ """\ /1 \\\n\ O|-; x -> oo|\n\ \\x /\ """ ucode_str = \ u("""\ ⎛1 ⎞\n\ O⎜─; x → ∞⎟\n\ ⎝x ⎠\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = O(x**2 + y**2, (x, oo), (y, oo)) ascii_str = \ """\ / 2 2 \\\n\ O\\x + y ; (x, y) -> (oo, oo)/\ """ ucode_str = \ u("""\ ⎛ 2 2 ⎞\n\ O⎝x + y ; (x, y) → (∞, ∞)⎠\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_pretty_derivatives(): # Simple expr = Derivative(log(x), x, evaluate=False) ascii_str = \ """\ d \n\ --(log(x))\n\ dx \ """ ucode_str = \ u("""\ d \n\ ──(log(x))\n\ dx \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Derivative(log(x), x, evaluate=False) + x ascii_str_1 = \ """\ d \n\ x + --(log(x))\n\ dx \ """ ascii_str_2 = \ """\ d \n\ --(log(x)) + x\n\ dx \ """ ucode_str_1 = \ u("""\ d \n\ x + ──(log(x))\n\ dx \ """) ucode_str_2 = \ u("""\ d \n\ ──(log(x)) + x\n\ dx \ """) assert pretty(expr) in [ascii_str_1, ascii_str_2] assert upretty(expr) in [ucode_str_1, ucode_str_2] # basic partial derivatives expr = Derivative(log(x + y) + x, x) ascii_str_1 = \ """\ d \n\ --(log(x + y) + x)\n\ dx \ """ ascii_str_2 = \ """\ d \n\ --(x + log(x + y))\n\ dx \ """ ucode_str_1 = \ u("""\ ∂ \n\ ──(log(x + y) + x)\n\ ∂x \ """) ucode_str_2 = \ u("""\ ∂ \n\ ──(x + log(x + y))\n\ ∂x \ """) assert pretty(expr) in [ascii_str_1, ascii_str_2] assert upretty(expr) in [ucode_str_1, ucode_str_2], upretty(expr) # Multiple symbols expr = Derivative(log(x) + x**2, x, y) ascii_str_1 = \ """\ 2 \n\ d / 2\\\n\ -----\\log(x) + x /\n\ dy dx \ """ ascii_str_2 = \ """\ 2 \n\ d / 2 \\\n\ -----\\x + log(x)/\n\ dy dx \ """ ucode_str_1 = \ u("""\ 2 \n\ d ⎛ 2⎞\n\ ─────⎝log(x) + x ⎠\n\ dy dx \ """) ucode_str_2 = \ u("""\ 2 \n\ d ⎛ 2 ⎞\n\ ─────⎝x + log(x)⎠\n\ dy dx \ """) assert pretty(expr) in [ascii_str_1, ascii_str_2] assert upretty(expr) in [ucode_str_1, ucode_str_2] expr = Derivative(2*x*y, y, x) + x**2 ascii_str_1 = \ """\ 2 \n\ d 2\n\ -----(2*x*y) + x \n\ dx dy \ """ ascii_str_2 = \ """\ 2 \n\ 2 d \n\ x + -----(2*x*y)\n\ dx dy \ """ ucode_str_1 = \ u("""\ 2 \n\ ∂ 2\n\ ─────(2⋅x⋅y) + x \n\ ∂x ∂y \ """) ucode_str_2 = \ u("""\ 2 \n\ 2 ∂ \n\ x + ─────(2⋅x⋅y)\n\ ∂x ∂y \ """) assert pretty(expr) in [ascii_str_1, ascii_str_2] assert upretty(expr) in [ucode_str_1, ucode_str_2] expr = Derivative(2*x*y, x, x) ascii_str = \ """\ 2 \n\ d \n\ ---(2*x*y)\n\ 2 \n\ dx \ """ ucode_str = \ u("""\ 2 \n\ ∂ \n\ ───(2⋅x⋅y)\n\ 2 \n\ ∂x \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Derivative(2*x*y, x, 17) ascii_str = \ """\ 17 \n\ d \n\ ----(2*x*y)\n\ 17 \n\ dx \ """ ucode_str = \ u("""\ 17 \n\ ∂ \n\ ────(2⋅x⋅y)\n\ 17 \n\ ∂x \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Derivative(2*x*y, x, x, y) ascii_str = \ """\ 3 \n\ d \n\ ------(2*x*y)\n\ 2 \n\ dy dx \ """ ucode_str = \ u("""\ 3 \n\ ∂ \n\ ──────(2⋅x⋅y)\n\ 2 \n\ ∂y ∂x \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str # Greek letters alpha = Symbol('alpha') beta = Function('beta') expr = beta(alpha).diff(alpha) ascii_str = \ """\ d \n\ ------(beta(alpha))\n\ dalpha \ """ ucode_str = \ u("""\ d \n\ ──(β(α))\n\ dα \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Derivative(f(x), (x, n)) ascii_str = \ """\ n \n\ d \n\ ---(f(x))\n\ n \n\ dx \ """ ucode_str = \ u("""\ n \n\ d \n\ ───(f(x))\n\ n \n\ dx \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_pretty_integrals(): expr = Integral(log(x), x) ascii_str = \ """\ / \n\ | \n\ | log(x) dx\n\ | \n\ / \ """ ucode_str = \ u("""\ ⌠ \n\ ⎮ log(x) dx\n\ ⌡ \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Integral(x**2, x) ascii_str = \ """\ / \n\ | \n\ | 2 \n\ | x dx\n\ | \n\ / \ """ ucode_str = \ u("""\ ⌠ \n\ ⎮ 2 \n\ ⎮ x dx\n\ ⌡ \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Integral((sin(x))**2 / (tan(x))**2) ascii_str = \ """\ / \n\ | \n\ | 2 \n\ | sin (x) \n\ | ------- dx\n\ | 2 \n\ | tan (x) \n\ | \n\ / \ """ ucode_str = \ u("""\ ⌠ \n\ ⎮ 2 \n\ ⎮ sin (x) \n\ ⎮ ─────── dx\n\ ⎮ 2 \n\ ⎮ tan (x) \n\ ⌡ \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Integral(x**(2**x), x) ascii_str = \ """\ / \n\ | \n\ | / x\\ \n\ | \\2 / \n\ | x dx\n\ | \n\ / \ """ ucode_str = \ u("""\ ⌠ \n\ ⎮ ⎛ x⎞ \n\ ⎮ ⎝2 ⎠ \n\ ⎮ x dx\n\ ⌡ \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Integral(x**2, (x, 1, 2)) ascii_str = \ """\ 2 \n\ / \n\ | \n\ | 2 \n\ | x dx\n\ | \n\ / \n\ 1 \ """ ucode_str = \ u("""\ 2 \n\ ⌠ \n\ ⎮ 2 \n\ ⎮ x dx\n\ ⌡ \n\ 1 \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Integral(x**2, (x, Rational(1, 2), 10)) ascii_str = \ """\ 10 \n\ / \n\ | \n\ | 2 \n\ | x dx\n\ | \n\ / \n\ 1/2 \ """ ucode_str = \ u("""\ 10 \n\ ⌠ \n\ ⎮ 2 \n\ ⎮ x dx\n\ ⌡ \n\ 1/2 \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Integral(x**2*y**2, x, y) ascii_str = \ """\ / / \n\ | | \n\ | | 2 2 \n\ | | x *y dx dy\n\ | | \n\ / / \ """ ucode_str = \ u("""\ ⌠ ⌠ \n\ ⎮ ⎮ 2 2 \n\ ⎮ ⎮ x ⋅y dx dy\n\ ⌡ ⌡ \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Integral(sin(th)/cos(ph), (th, 0, pi), (ph, 0, 2*pi)) ascii_str = \ """\ 2*pi pi \n\ / / \n\ | | \n\ | | sin(theta) \n\ | | ---------- d(theta) d(phi)\n\ | | cos(phi) \n\ | | \n\ / / \n\ 0 0 \ """ ucode_str = \ u("""\ 2⋅π π \n\ ⌠ ⌠ \n\ ⎮ ⎮ sin(θ) \n\ ⎮ ⎮ ────── dθ dφ\n\ ⎮ ⎮ cos(φ) \n\ ⌡ ⌡ \n\ 0 0 \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_pretty_matrix(): # Empty Matrix expr = Matrix() ascii_str = "[]" unicode_str = "[]" assert pretty(expr) == ascii_str assert upretty(expr) == unicode_str expr = Matrix(2, 0, lambda i, j: 0) ascii_str = "[]" unicode_str = "[]" assert pretty(expr) == ascii_str assert upretty(expr) == unicode_str expr = Matrix(0, 2, lambda i, j: 0) ascii_str = "[]" unicode_str = "[]" assert pretty(expr) == ascii_str assert upretty(expr) == unicode_str expr = Matrix([[x**2 + 1, 1], [y, x + y]]) ascii_str_1 = \ """\ [ 2 ] [1 + x 1 ] [ ] [ y x + y]\ """ ascii_str_2 = \ """\ [ 2 ] [x + 1 1 ] [ ] [ y x + y]\ """ ucode_str_1 = \ u("""\ ⎡ 2 ⎤ ⎢1 + x 1 ⎥ ⎢ ⎥ ⎣ y x + y⎦\ """) ucode_str_2 = \ u("""\ ⎡ 2 ⎤ ⎢x + 1 1 ⎥ ⎢ ⎥ ⎣ y x + y⎦\ """) assert pretty(expr) in [ascii_str_1, ascii_str_2] assert upretty(expr) in [ucode_str_1, ucode_str_2] expr = Matrix([[x/y, y, th], [0, exp(I*k*ph), 1]]) ascii_str = \ """\ [x ] [- y theta] [y ] [ ] [ I*k*phi ] [0 e 1 ]\ """ ucode_str = \ u("""\ ⎡x ⎤ ⎢─ y θ⎥ ⎢y ⎥ ⎢ ⎥ ⎢ ⅈ⋅k⋅φ ⎥ ⎣0 ℯ 1⎦\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str unicode_str = \ u("""\ ⎡v̇_msc_00 0 0 ⎤ ⎢ ⎥ ⎢ 0 v̇_msc_01 0 ⎥ ⎢ ⎥ ⎣ 0 0 v̇_msc_02⎦\ """) expr = diag(*MatrixSymbol('vdot_msc',1,3)) assert upretty(expr) == unicode_str def test_pretty_ndim_arrays(): x, y, z, w = symbols("x y z w") for ArrayType in (ImmutableDenseNDimArray, ImmutableSparseNDimArray, MutableDenseNDimArray, MutableSparseNDimArray): # Basic: scalar array M = ArrayType(x) assert pretty(M) == "x" assert upretty(M) == "x" M = ArrayType([[1/x, y], [z, w]]) M1 = ArrayType([1/x, y, z]) M2 = tensorproduct(M1, M) M3 = tensorproduct(M, M) ascii_str = \ """\ [1 ]\n\ [- y]\n\ [x ]\n\ [ ]\n\ [z w]\ """ ucode_str = \ u("""\ ⎡1 ⎤\n\ ⎢─ y⎥\n\ ⎢x ⎥\n\ ⎢ ⎥\n\ ⎣z w⎦\ """) assert pretty(M) == ascii_str assert upretty(M) == ucode_str ascii_str = \ """\ [1 ]\n\ [- y z]\n\ [x ]\ """ ucode_str = \ u("""\ ⎡1 ⎤\n\ ⎢─ y z⎥\n\ ⎣x ⎦\ """) assert pretty(M1) == ascii_str assert upretty(M1) == ucode_str ascii_str = \ """\ [[1 y] ]\n\ [[-- -] [z ]]\n\ [[ 2 x] [ y 2 ] [- y*z]]\n\ [[x ] [ - y ] [x ]]\n\ [[ ] [ x ] [ ]]\n\ [[z w] [ ] [ 2 ]]\n\ [[- -] [y*z w*y] [z w*z]]\n\ [[x x] ]\ """ ucode_str = \ u("""\ ⎡⎡1 y⎤ ⎤\n\ ⎢⎢── ─⎥ ⎡z ⎤⎥\n\ ⎢⎢ 2 x⎥ ⎡ y 2 ⎤ ⎢─ y⋅z⎥⎥\n\ ⎢⎢x ⎥ ⎢ ─ y ⎥ ⎢x ⎥⎥\n\ ⎢⎢ ⎥ ⎢ x ⎥ ⎢ ⎥⎥\n\ ⎢⎢z w⎥ ⎢ ⎥ ⎢ 2 ⎥⎥\n\ ⎢⎢─ ─⎥ ⎣y⋅z w⋅y⎦ ⎣z w⋅z⎦⎥\n\ ⎣⎣x x⎦ ⎦\ """) assert pretty(M2) == ascii_str assert upretty(M2) == ucode_str ascii_str = \ """\ [ [1 y] ]\n\ [ [-- -] ]\n\ [ [ 2 x] [ y 2 ]]\n\ [ [x ] [ - y ]]\n\ [ [ ] [ x ]]\n\ [ [z w] [ ]]\n\ [ [- -] [y*z w*y]]\n\ [ [x x] ]\n\ [ ]\n\ [[z ] [ w ]]\n\ [[- y*z] [ - w*y]]\n\ [[x ] [ x ]]\n\ [[ ] [ ]]\n\ [[ 2 ] [ 2 ]]\n\ [[z w*z] [w*z w ]]\ """ ucode_str = \ u("""\ ⎡ ⎡1 y⎤ ⎤\n\ ⎢ ⎢── ─⎥ ⎥\n\ ⎢ ⎢ 2 x⎥ ⎡ y 2 ⎤⎥\n\ ⎢ ⎢x ⎥ ⎢ ─ y ⎥⎥\n\ ⎢ ⎢ ⎥ ⎢ x ⎥⎥\n\ ⎢ ⎢z w⎥ ⎢ ⎥⎥\n\ ⎢ ⎢─ ─⎥ ⎣y⋅z w⋅y⎦⎥\n\ ⎢ ⎣x x⎦ ⎥\n\ ⎢ ⎥\n\ ⎢⎡z ⎤ ⎡ w ⎤⎥\n\ ⎢⎢─ y⋅z⎥ ⎢ ─ w⋅y⎥⎥\n\ ⎢⎢x ⎥ ⎢ x ⎥⎥\n\ ⎢⎢ ⎥ ⎢ ⎥⎥\n\ ⎢⎢ 2 ⎥ ⎢ 2 ⎥⎥\n\ ⎣⎣z w⋅z⎦ ⎣w⋅z w ⎦⎦\ """) assert pretty(M3) == ascii_str assert upretty(M3) == ucode_str Mrow = ArrayType([[x, y, 1 / z]]) Mcolumn = ArrayType([[x], [y], [1 / z]]) Mcol2 = ArrayType([Mcolumn.tolist()]) ascii_str = \ """\ [[ 1]]\n\ [[x y -]]\n\ [[ z]]\ """ ucode_str = \ u("""\ ⎡⎡ 1⎤⎤\n\ ⎢⎢x y ─⎥⎥\n\ ⎣⎣ z⎦⎦\ """) assert pretty(Mrow) == ascii_str assert upretty(Mrow) == ucode_str ascii_str = \ """\ [x]\n\ [ ]\n\ [y]\n\ [ ]\n\ [1]\n\ [-]\n\ [z]\ """ ucode_str = \ u("""\ ⎡x⎤\n\ ⎢ ⎥\n\ ⎢y⎥\n\ ⎢ ⎥\n\ ⎢1⎥\n\ ⎢─⎥\n\ ⎣z⎦\ """) assert pretty(Mcolumn) == ascii_str assert upretty(Mcolumn) == ucode_str ascii_str = \ """\ [[x]]\n\ [[ ]]\n\ [[y]]\n\ [[ ]]\n\ [[1]]\n\ [[-]]\n\ [[z]]\ """ ucode_str = \ u("""\ ⎡⎡x⎤⎤\n\ ⎢⎢ ⎥⎥\n\ ⎢⎢y⎥⎥\n\ ⎢⎢ ⎥⎥\n\ ⎢⎢1⎥⎥\n\ ⎢⎢─⎥⎥\n\ ⎣⎣z⎦⎦\ """) assert pretty(Mcol2) == ascii_str assert upretty(Mcol2) == ucode_str def test_tensor_TensorProduct(): A = MatrixSymbol("A", 3, 3) B = MatrixSymbol("B", 3, 3) assert upretty(TensorProduct(A, B)) == "A\u2297B" assert upretty(TensorProduct(A, B, A)) == "A\u2297B\u2297A" def test_diffgeom_print_WedgeProduct(): from sympy.diffgeom.rn import R2 from sympy.diffgeom import WedgeProduct wp = WedgeProduct(R2.dx, R2.dy) assert upretty(wp) == u("ⅆ x∧ⅆ y") def test_Adjoint(): X = MatrixSymbol('X', 2, 2) Y = MatrixSymbol('Y', 2, 2) assert pretty(Adjoint(X)) == " +\nX " assert pretty(Adjoint(X + Y)) == " +\n(X + Y) " assert pretty(Adjoint(X) + Adjoint(Y)) == " + +\nX + Y " assert pretty(Adjoint(X*Y)) == " +\n(X*Y) " assert pretty(Adjoint(Y)*Adjoint(X)) == " + +\nY *X " assert pretty(Adjoint(X**2)) == " +\n/ 2\\ \n\\X / " assert pretty(Adjoint(X)**2) == " 2\n/ +\\ \n\\X / " assert pretty(Adjoint(Inverse(X))) == " +\n/ -1\\ \n\\X / " assert pretty(Inverse(Adjoint(X))) == " -1\n/ +\\ \n\\X / " assert pretty(Adjoint(Transpose(X))) == " +\n/ T\\ \n\\X / " assert pretty(Transpose(Adjoint(X))) == " T\n/ +\\ \n\\X / " assert upretty(Adjoint(X)) == u" †\nX " assert upretty(Adjoint(X + Y)) == u" †\n(X + Y) " assert upretty(Adjoint(X) + Adjoint(Y)) == u" † †\nX + Y " assert upretty(Adjoint(X*Y)) == u" †\n(X⋅Y) " assert upretty(Adjoint(Y)*Adjoint(X)) == u" † †\nY ⋅X " assert upretty(Adjoint(X**2)) == \ u" †\n⎛ 2⎞ \n⎝X ⎠ " assert upretty(Adjoint(X)**2) == \ u" 2\n⎛ †⎞ \n⎝X ⎠ " assert upretty(Adjoint(Inverse(X))) == \ u" †\n⎛ -1⎞ \n⎝X ⎠ " assert upretty(Inverse(Adjoint(X))) == \ u" -1\n⎛ †⎞ \n⎝X ⎠ " assert upretty(Adjoint(Transpose(X))) == \ u" †\n⎛ T⎞ \n⎝X ⎠ " assert upretty(Transpose(Adjoint(X))) == \ u" T\n⎛ †⎞ \n⎝X ⎠ " def test_pretty_Trace_issue_9044(): X = Matrix([[1, 2], [3, 4]]) Y = Matrix([[2, 4], [6, 8]]) ascii_str_1 = \ """\ /[1 2]\\ tr|[ ]| \\[3 4]/\ """ ucode_str_1 = \ u("""\ ⎛⎡1 2⎤⎞ tr⎜⎢ ⎥⎟ ⎝⎣3 4⎦⎠\ """) ascii_str_2 = \ """\ /[1 2]\\ /[2 4]\\ tr|[ ]| + tr|[ ]| \\[3 4]/ \\[6 8]/\ """ ucode_str_2 = \ u("""\ ⎛⎡1 2⎤⎞ ⎛⎡2 4⎤⎞ tr⎜⎢ ⎥⎟ + tr⎜⎢ ⎥⎟ ⎝⎣3 4⎦⎠ ⎝⎣6 8⎦⎠\ """) assert pretty(Trace(X)) == ascii_str_1 assert upretty(Trace(X)) == ucode_str_1 assert pretty(Trace(X) + Trace(Y)) == ascii_str_2 assert upretty(Trace(X) + Trace(Y)) == ucode_str_2 def test_MatrixExpressions(): n = Symbol('n', integer=True) X = MatrixSymbol('X', n, n) assert pretty(X) == upretty(X) == "X" Y = X[1:2:3, 4:5:6] ascii_str = ucode_str = "X[1:3, 4:6]" assert pretty(Y) == ascii_str assert upretty(Y) == ucode_str Z = X[1:10:2] ascii_str = ucode_str = "X[1:10:2, :n]" assert pretty(Z) == ascii_str assert upretty(Z) == ucode_str # Apply function elementwise (`ElementwiseApplyFunc`): expr = (X.T*X).applyfunc(sin) ascii_str = """\ / T \\\n\ (d -> sin(d)).\\X *X/\ """ ucode_str = u("""\ ⎛ T ⎞\n\ (d ↦ sin(d))˳⎝X ⋅X⎠\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str lamda = Lambda(x, 1/x) expr = (n*X).applyfunc(lamda) ascii_str = """\ / 1\\ \n\ |d -> -|.(n*X)\n\ \\ d/ \ """ ucode_str = u("""\ ⎛ 1⎞ \n\ ⎜d ↦ ─⎟˳(n⋅X)\n\ ⎝ d⎠ \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_pretty_dotproduct(): from sympy.matrices import Matrix, MatrixSymbol from sympy.matrices.expressions.dotproduct import DotProduct n = symbols("n", integer=True) A = MatrixSymbol('A', n, 1) B = MatrixSymbol('B', n, 1) C = Matrix(1, 3, [1, 2, 3]) D = Matrix(1, 3, [1, 3, 4]) assert pretty(DotProduct(A, B)) == u"A*B" assert pretty(DotProduct(C, D)) == u"[1 2 3]*[1 3 4]" assert upretty(DotProduct(A, B)) == u"A⋅B" assert upretty(DotProduct(C, D)) == u"[1 2 3]⋅[1 3 4]" def test_pretty_piecewise(): expr = Piecewise((x, x < 1), (x**2, True)) ascii_str = \ """\ /x for x < 1\n\ | \n\ < 2 \n\ |x otherwise\n\ \\ \ """ ucode_str = \ u("""\ ⎧x for x < 1\n\ ⎪ \n\ ⎨ 2 \n\ ⎪x otherwise\n\ ⎩ \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = -Piecewise((x, x < 1), (x**2, True)) ascii_str = \ """\ //x for x < 1\\\n\ || |\n\ -|< 2 |\n\ ||x otherwise|\n\ \\\\ /\ """ ucode_str = \ u("""\ ⎛⎧x for x < 1⎞\n\ ⎜⎪ ⎟\n\ -⎜⎨ 2 ⎟\n\ ⎜⎪x otherwise⎟\n\ ⎝⎩ ⎠\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = x + Piecewise((x, x > 0), (y, True)) + Piecewise((x/y, x < 2), (y**2, x > 2), (1, True)) + 1 ascii_str = \ """\ //x \\ \n\ ||- for x < 2| \n\ ||y | \n\ //x for x > 0\\ || | \n\ x + |< | + |< 2 | + 1\n\ \\\\y otherwise/ ||y for x > 2| \n\ || | \n\ ||1 otherwise| \n\ \\\\ / \ """ ucode_str = \ u("""\ ⎛⎧x ⎞ \n\ ⎜⎪─ for x < 2⎟ \n\ ⎜⎪y ⎟ \n\ ⎛⎧x for x > 0⎞ ⎜⎪ ⎟ \n\ x + ⎜⎨ ⎟ + ⎜⎨ 2 ⎟ + 1\n\ ⎝⎩y otherwise⎠ ⎜⎪y for x > 2⎟ \n\ ⎜⎪ ⎟ \n\ ⎜⎪1 otherwise⎟ \n\ ⎝⎩ ⎠ \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = x - Piecewise((x, x > 0), (y, True)) + Piecewise((x/y, x < 2), (y**2, x > 2), (1, True)) + 1 ascii_str = \ """\ //x \\ \n\ ||- for x < 2| \n\ ||y | \n\ //x for x > 0\\ || | \n\ x - |< | + |< 2 | + 1\n\ \\\\y otherwise/ ||y for x > 2| \n\ || | \n\ ||1 otherwise| \n\ \\\\ / \ """ ucode_str = \ u("""\ ⎛⎧x ⎞ \n\ ⎜⎪─ for x < 2⎟ \n\ ⎜⎪y ⎟ \n\ ⎛⎧x for x > 0⎞ ⎜⎪ ⎟ \n\ x - ⎜⎨ ⎟ + ⎜⎨ 2 ⎟ + 1\n\ ⎝⎩y otherwise⎠ ⎜⎪y for x > 2⎟ \n\ ⎜⎪ ⎟ \n\ ⎜⎪1 otherwise⎟ \n\ ⎝⎩ ⎠ \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = x*Piecewise((x, x > 0), (y, True)) ascii_str = \ """\ //x for x > 0\\\n\ x*|< |\n\ \\\\y otherwise/\ """ ucode_str = \ u("""\ ⎛⎧x for x > 0⎞\n\ x⋅⎜⎨ ⎟\n\ ⎝⎩y otherwise⎠\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Piecewise((x, x > 0), (y, True))*Piecewise((x/y, x < 2), (y**2, x > 2), (1, True)) ascii_str = \ """\ //x \\\n\ ||- for x < 2|\n\ ||y |\n\ //x for x > 0\\ || |\n\ |< |*|< 2 |\n\ \\\\y otherwise/ ||y for x > 2|\n\ || |\n\ ||1 otherwise|\n\ \\\\ /\ """ ucode_str = \ u("""\ ⎛⎧x ⎞\n\ ⎜⎪─ for x < 2⎟\n\ ⎜⎪y ⎟\n\ ⎛⎧x for x > 0⎞ ⎜⎪ ⎟\n\ ⎜⎨ ⎟⋅⎜⎨ 2 ⎟\n\ ⎝⎩y otherwise⎠ ⎜⎪y for x > 2⎟\n\ ⎜⎪ ⎟\n\ ⎜⎪1 otherwise⎟\n\ ⎝⎩ ⎠\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = -Piecewise((x, x > 0), (y, True))*Piecewise((x/y, x < 2), (y**2, x > 2), (1, True)) ascii_str = \ """\ //x \\\n\ ||- for x < 2|\n\ ||y |\n\ //x for x > 0\\ || |\n\ -|< |*|< 2 |\n\ \\\\y otherwise/ ||y for x > 2|\n\ || |\n\ ||1 otherwise|\n\ \\\\ /\ """ ucode_str = \ u("""\ ⎛⎧x ⎞\n\ ⎜⎪─ for x < 2⎟\n\ ⎜⎪y ⎟\n\ ⎛⎧x for x > 0⎞ ⎜⎪ ⎟\n\ -⎜⎨ ⎟⋅⎜⎨ 2 ⎟\n\ ⎝⎩y otherwise⎠ ⎜⎪y for x > 2⎟\n\ ⎜⎪ ⎟\n\ ⎜⎪1 otherwise⎟\n\ ⎝⎩ ⎠\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Piecewise((0, Abs(1/y) < 1), (1, Abs(y) < 1), (y*meijerg(((2, 1), ()), ((), (1, 0)), 1/y), True)) ascii_str = \ """\ / 1 \n\ | 0 for --- < 1\n\ | |y| \n\ | \n\ < 1 for |y| < 1\n\ | \n\ | __0, 2 /2, 1 | 1\\ \n\ |y*/__ | | -| otherwise \n\ \\ \\_|2, 2 \\ 1, 0 | y/ \ """ ucode_str = \ u("""\ ⎧ 1 \n\ ⎪ 0 for ─── < 1\n\ ⎪ │y│ \n\ ⎪ \n\ ⎨ 1 for │y│ < 1\n\ ⎪ \n\ ⎪ ╭─╮0, 2 ⎛2, 1 │ 1⎞ \n\ ⎪y⋅│╶┐ ⎜ │ ─⎟ otherwise \n\ ⎩ ╰─╯2, 2 ⎝ 1, 0 │ y⎠ \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str # XXX: We have to use evaluate=False here because Piecewise._eval_power # denests the power. expr = Pow(Piecewise((x, x > 0), (y, True)), 2, evaluate=False) ascii_str = \ """\ 2\n\ //x for x > 0\\ \n\ |< | \n\ \\\\y otherwise/ \ """ ucode_str = \ u("""\ 2\n\ ⎛⎧x for x > 0⎞ \n\ ⎜⎨ ⎟ \n\ ⎝⎩y otherwise⎠ \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_pretty_ITE(): expr = ITE(x, y, z) assert pretty(expr) == ( '/y for x \n' '< \n' '\\z otherwise' ) assert upretty(expr) == u("""\ ⎧y for x \n\ ⎨ \n\ ⎩z otherwise\ """) def test_pretty_seq(): expr = () ascii_str = \ """\ ()\ """ ucode_str = \ u("""\ ()\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = [] ascii_str = \ """\ []\ """ ucode_str = \ u("""\ []\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = {} expr_2 = {} ascii_str = \ """\ {}\ """ ucode_str = \ u("""\ {}\ """) assert pretty(expr) == ascii_str assert pretty(expr_2) == ascii_str assert upretty(expr) == ucode_str assert upretty(expr_2) == ucode_str expr = (1/x,) ascii_str = \ """\ 1 \n\ (-,)\n\ x \ """ ucode_str = \ u("""\ ⎛1 ⎞\n\ ⎜─,⎟\n\ ⎝x ⎠\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = [x**2, 1/x, x, y, sin(th)**2/cos(ph)**2] ascii_str = \ """\ 2 \n\ 2 1 sin (theta) \n\ [x , -, x, y, -----------]\n\ x 2 \n\ cos (phi) \ """ ucode_str = \ u("""\ ⎡ 2 ⎤\n\ ⎢ 2 1 sin (θ)⎥\n\ ⎢x , ─, x, y, ───────⎥\n\ ⎢ x 2 ⎥\n\ ⎣ cos (φ)⎦\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = (x**2, 1/x, x, y, sin(th)**2/cos(ph)**2) ascii_str = \ """\ 2 \n\ 2 1 sin (theta) \n\ (x , -, x, y, -----------)\n\ x 2 \n\ cos (phi) \ """ ucode_str = \ u("""\ ⎛ 2 ⎞\n\ ⎜ 2 1 sin (θ)⎟\n\ ⎜x , ─, x, y, ───────⎟\n\ ⎜ x 2 ⎟\n\ ⎝ cos (φ)⎠\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Tuple(x**2, 1/x, x, y, sin(th)**2/cos(ph)**2) ascii_str = \ """\ 2 \n\ 2 1 sin (theta) \n\ (x , -, x, y, -----------)\n\ x 2 \n\ cos (phi) \ """ ucode_str = \ u("""\ ⎛ 2 ⎞\n\ ⎜ 2 1 sin (θ)⎟\n\ ⎜x , ─, x, y, ───────⎟\n\ ⎜ x 2 ⎟\n\ ⎝ cos (φ)⎠\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = {x: sin(x)} expr_2 = Dict({x: sin(x)}) ascii_str = \ """\ {x: sin(x)}\ """ ucode_str = \ u("""\ {x: sin(x)}\ """) assert pretty(expr) == ascii_str assert pretty(expr_2) == ascii_str assert upretty(expr) == ucode_str assert upretty(expr_2) == ucode_str expr = {1/x: 1/y, x: sin(x)**2} expr_2 = Dict({1/x: 1/y, x: sin(x)**2}) ascii_str = \ """\ 1 1 2 \n\ {-: -, x: sin (x)}\n\ x y \ """ ucode_str = \ u("""\ ⎧1 1 2 ⎫\n\ ⎨─: ─, x: sin (x)⎬\n\ ⎩x y ⎭\ """) assert pretty(expr) == ascii_str assert pretty(expr_2) == ascii_str assert upretty(expr) == ucode_str assert upretty(expr_2) == ucode_str # There used to be a bug with pretty-printing sequences of even height. expr = [x**2] ascii_str = \ """\ 2 \n\ [x ]\ """ ucode_str = \ u("""\ ⎡ 2⎤\n\ ⎣x ⎦\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = (x**2,) ascii_str = \ """\ 2 \n\ (x ,)\ """ ucode_str = \ u("""\ ⎛ 2 ⎞\n\ ⎝x ,⎠\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Tuple(x**2) ascii_str = \ """\ 2 \n\ (x ,)\ """ ucode_str = \ u("""\ ⎛ 2 ⎞\n\ ⎝x ,⎠\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = {x**2: 1} expr_2 = Dict({x**2: 1}) ascii_str = \ """\ 2 \n\ {x : 1}\ """ ucode_str = \ u("""\ ⎧ 2 ⎫\n\ ⎨x : 1⎬\n\ ⎩ ⎭\ """) assert pretty(expr) == ascii_str assert pretty(expr_2) == ascii_str assert upretty(expr) == ucode_str assert upretty(expr_2) == ucode_str def test_any_object_in_sequence(): # Cf. issue 5306 b1 = Basic() b2 = Basic(Basic()) expr = [b2, b1] assert pretty(expr) == "[Basic(Basic()), Basic()]" assert upretty(expr) == u"[Basic(Basic()), Basic()]" expr = {b2, b1} assert pretty(expr) == "{Basic(), Basic(Basic())}" assert upretty(expr) == u"{Basic(), Basic(Basic())}" expr = {b2: b1, b1: b2} expr2 = Dict({b2: b1, b1: b2}) assert pretty(expr) == "{Basic(): Basic(Basic()), Basic(Basic()): Basic()}" assert pretty( expr2) == "{Basic(): Basic(Basic()), Basic(Basic()): Basic()}" assert upretty( expr) == u"{Basic(): Basic(Basic()), Basic(Basic()): Basic()}" assert upretty( expr2) == u"{Basic(): Basic(Basic()), Basic(Basic()): Basic()}" def test_print_builtin_set(): assert pretty(set()) == 'set()' assert upretty(set()) == u'set()' assert pretty(frozenset()) == 'frozenset()' assert upretty(frozenset()) == u'frozenset()' s1 = {1/x, x} s2 = frozenset(s1) assert pretty(s1) == \ """\ 1 \n\ {-, x} x \ """ assert upretty(s1) == \ u"""\ ⎧1 ⎫ ⎨─, x⎬ ⎩x ⎭\ """ assert pretty(s2) == \ """\ 1 \n\ frozenset({-, x}) x \ """ assert upretty(s2) == \ u"""\ ⎛⎧1 ⎫⎞ frozenset⎜⎨─, x⎬⎟ ⎝⎩x ⎭⎠\ """ def test_pretty_sets(): s = FiniteSet assert pretty(s(*[x*y, x**2])) == \ """\ 2 \n\ {x , x*y}\ """ assert pretty(s(*range(1, 6))) == "{1, 2, 3, 4, 5}" assert pretty(s(*range(1, 13))) == "{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}" assert pretty(set([x*y, x**2])) == \ """\ 2 \n\ {x , x*y}\ """ assert pretty(set(range(1, 6))) == "{1, 2, 3, 4, 5}" assert pretty(set(range(1, 13))) == \ "{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}" assert pretty(frozenset([x*y, x**2])) == \ """\ 2 \n\ frozenset({x , x*y})\ """ assert pretty(frozenset(range(1, 6))) == "frozenset({1, 2, 3, 4, 5})" assert pretty(frozenset(range(1, 13))) == \ "frozenset({1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12})" assert pretty(Range(0, 3, 1)) == '{0, 1, 2}' ascii_str = '{0, 1, ..., 29}' ucode_str = u'{0, 1, …, 29}' assert pretty(Range(0, 30, 1)) == ascii_str assert upretty(Range(0, 30, 1)) == ucode_str ascii_str = '{30, 29, ..., 2}' ucode_str = u('{30, 29, …, 2}') assert pretty(Range(30, 1, -1)) == ascii_str assert upretty(Range(30, 1, -1)) == ucode_str ascii_str = '{0, 2, ...}' ucode_str = u'{0, 2, …}' assert pretty(Range(0, oo, 2)) == ascii_str assert upretty(Range(0, oo, 2)) == ucode_str ascii_str = '{..., 2, 0}' ucode_str = u('{…, 2, 0}') assert pretty(Range(oo, -2, -2)) == ascii_str assert upretty(Range(oo, -2, -2)) == ucode_str ascii_str = '{-2, -3, ...}' ucode_str = u('{-2, -3, …}') assert pretty(Range(-2, -oo, -1)) == ascii_str assert upretty(Range(-2, -oo, -1)) == ucode_str def test_pretty_SetExpr(): iv = Interval(1, 3) se = SetExpr(iv) ascii_str = "SetExpr([1, 3])" ucode_str = u("SetExpr([1, 3])") assert pretty(se) == ascii_str assert upretty(se) == ucode_str def test_pretty_ImageSet(): imgset = ImageSet(Lambda((x, y), x + y), {1, 2, 3}, {3, 4}) ascii_str = '{x + y | x in {1, 2, 3} , y in {3, 4}}' ucode_str = u('{x + y | x ∊ {1, 2, 3} , y ∊ {3, 4}}') assert pretty(imgset) == ascii_str assert upretty(imgset) == ucode_str imgset = ImageSet(Lambda(((x, y),), x + y), ProductSet({1, 2, 3}, {3, 4})) ascii_str = '{x + y | (x, y) in {1, 2, 3} x {3, 4}}' ucode_str = u('{x + y | (x, y) ∊ {1, 2, 3} × {3, 4}}') assert pretty(imgset) == ascii_str assert upretty(imgset) == ucode_str imgset = ImageSet(Lambda(x, x**2), S.Naturals) ascii_str = \ ' 2 \n'\ '{x | x in Naturals}' ucode_str = u('''\ ⎧ 2 ⎫\n\ ⎨x | x ∊ ℕ⎬\n\ ⎩ ⎭''') assert pretty(imgset) == ascii_str assert upretty(imgset) == ucode_str def test_pretty_ConditionSet(): from sympy import ConditionSet ascii_str = '{x | x in (-oo, oo) and sin(x) = 0}' ucode_str = u'{x | x ∊ ℝ ∧ (sin(x) = 0)}' assert pretty(ConditionSet(x, Eq(sin(x), 0), S.Reals)) == ascii_str assert upretty(ConditionSet(x, Eq(sin(x), 0), S.Reals)) == ucode_str assert pretty(ConditionSet(x, Contains(x, S.Reals, evaluate=False), FiniteSet(1))) == '{1}' assert upretty(ConditionSet(x, Contains(x, S.Reals, evaluate=False), FiniteSet(1))) == u'{1}' assert pretty(ConditionSet(x, And(x > 1, x < -1), FiniteSet(1, 2, 3))) == "EmptySet" assert upretty(ConditionSet(x, And(x > 1, x < -1), FiniteSet(1, 2, 3))) == u"∅" assert pretty(ConditionSet(x, Or(x > 1, x < -1), FiniteSet(1, 2))) == '{2}' assert upretty(ConditionSet(x, Or(x > 1, x < -1), FiniteSet(1, 2))) == u'{2}' def test_pretty_ComplexRegion(): from sympy import ComplexRegion ucode_str = u'{x + y⋅ⅈ | x, y ∊ [3, 5] × [4, 6]}' assert upretty(ComplexRegion(Interval(3, 5)*Interval(4, 6))) == ucode_str ucode_str = u'{r⋅(ⅈ⋅sin(θ) + cos(θ)) | r, θ ∊ [0, 1] × [0, 2⋅π)}' assert upretty(ComplexRegion(Interval(0, 1)*Interval(0, 2*pi), polar=True)) == ucode_str def test_pretty_Union_issue_10414(): a, b = Interval(2, 3), Interval(4, 7) ucode_str = u'[2, 3] ∪ [4, 7]' ascii_str = '[2, 3] U [4, 7]' assert upretty(Union(a, b)) == ucode_str assert pretty(Union(a, b)) == ascii_str def test_pretty_Intersection_issue_10414(): x, y, z, w = symbols('x, y, z, w') a, b = Interval(x, y), Interval(z, w) ucode_str = u'[x, y] ∩ [z, w]' ascii_str = '[x, y] n [z, w]' assert upretty(Intersection(a, b)) == ucode_str assert pretty(Intersection(a, b)) == ascii_str def test_ProductSet_exponent(): ucode_str = ' 1\n[0, 1] ' assert upretty(Interval(0, 1)**1) == ucode_str ucode_str = ' 2\n[0, 1] ' assert upretty(Interval(0, 1)**2) == ucode_str def test_ProductSet_parenthesis(): ucode_str = u'([4, 7] × {1, 2}) ∪ ([2, 3] × [4, 7])' a, b = Interval(2, 3), Interval(4, 7) assert upretty(Union(a*b, b*FiniteSet(1, 2))) == ucode_str def test_ProductSet_prod_char_issue_10413(): ascii_str = '[2, 3] x [4, 7]' ucode_str = u'[2, 3] × [4, 7]' a, b = Interval(2, 3), Interval(4, 7) assert pretty(a*b) == ascii_str assert upretty(a*b) == ucode_str def test_pretty_sequences(): s1 = SeqFormula(a**2, (0, oo)) s2 = SeqPer((1, 2)) ascii_str = '[0, 1, 4, 9, ...]' ucode_str = u'[0, 1, 4, 9, …]' assert pretty(s1) == ascii_str assert upretty(s1) == ucode_str ascii_str = '[1, 2, 1, 2, ...]' ucode_str = u'[1, 2, 1, 2, …]' assert pretty(s2) == ascii_str assert upretty(s2) == ucode_str s3 = SeqFormula(a**2, (0, 2)) s4 = SeqPer((1, 2), (0, 2)) ascii_str = '[0, 1, 4]' ucode_str = u'[0, 1, 4]' assert pretty(s3) == ascii_str assert upretty(s3) == ucode_str ascii_str = '[1, 2, 1]' ucode_str = u'[1, 2, 1]' assert pretty(s4) == ascii_str assert upretty(s4) == ucode_str s5 = SeqFormula(a**2, (-oo, 0)) s6 = SeqPer((1, 2), (-oo, 0)) ascii_str = '[..., 9, 4, 1, 0]' ucode_str = u'[…, 9, 4, 1, 0]' assert pretty(s5) == ascii_str assert upretty(s5) == ucode_str ascii_str = '[..., 2, 1, 2, 1]' ucode_str = u'[…, 2, 1, 2, 1]' assert pretty(s6) == ascii_str assert upretty(s6) == ucode_str ascii_str = '[1, 3, 5, 11, ...]' ucode_str = u'[1, 3, 5, 11, …]' assert pretty(SeqAdd(s1, s2)) == ascii_str assert upretty(SeqAdd(s1, s2)) == ucode_str ascii_str = '[1, 3, 5]' ucode_str = u'[1, 3, 5]' assert pretty(SeqAdd(s3, s4)) == ascii_str assert upretty(SeqAdd(s3, s4)) == ucode_str ascii_str = '[..., 11, 5, 3, 1]' ucode_str = u'[…, 11, 5, 3, 1]' assert pretty(SeqAdd(s5, s6)) == ascii_str assert upretty(SeqAdd(s5, s6)) == ucode_str ascii_str = '[0, 2, 4, 18, ...]' ucode_str = u'[0, 2, 4, 18, …]' assert pretty(SeqMul(s1, s2)) == ascii_str assert upretty(SeqMul(s1, s2)) == ucode_str ascii_str = '[0, 2, 4]' ucode_str = u'[0, 2, 4]' assert pretty(SeqMul(s3, s4)) == ascii_str assert upretty(SeqMul(s3, s4)) == ucode_str ascii_str = '[..., 18, 4, 2, 0]' ucode_str = u'[…, 18, 4, 2, 0]' assert pretty(SeqMul(s5, s6)) == ascii_str assert upretty(SeqMul(s5, s6)) == ucode_str # Sequences with symbolic limits, issue 12629 s7 = SeqFormula(a**2, (a, 0, x)) raises(NotImplementedError, lambda: pretty(s7)) raises(NotImplementedError, lambda: upretty(s7)) b = Symbol('b') s8 = SeqFormula(b*a**2, (a, 0, 2)) ascii_str = u'[0, b, 4*b]' ucode_str = u'[0, b, 4⋅b]' assert pretty(s8) == ascii_str assert upretty(s8) == ucode_str def test_pretty_FourierSeries(): f = fourier_series(x, (x, -pi, pi)) ascii_str = \ """\ 2*sin(3*x) \n\ 2*sin(x) - sin(2*x) + ---------- + ...\n\ 3 \ """ ucode_str = \ u("""\ 2⋅sin(3⋅x) \n\ 2⋅sin(x) - sin(2⋅x) + ────────── + …\n\ 3 \ """) assert pretty(f) == ascii_str assert upretty(f) == ucode_str def test_pretty_FormalPowerSeries(): f = fps(log(1 + x)) ascii_str = \ """\ oo \n\ ____ \n\ \\ ` \n\ \\ -k k \n\ \\ -(-1) *x \n\ / -----------\n\ / k \n\ /___, \n\ k = 1 \ """ ucode_str = \ u("""\ ∞ \n\ ____ \n\ ╲ \n\ ╲ -k k \n\ ╲ -(-1) ⋅x \n\ ╱ ───────────\n\ ╱ k \n\ ╱ \n\ ‾‾‾‾ \n\ k = 1 \ """) assert pretty(f) == ascii_str assert upretty(f) == ucode_str def test_pretty_limits(): expr = Limit(x, x, oo) ascii_str = \ """\ lim x\n\ x->oo \ """ ucode_str = \ u("""\ lim x\n\ x─→∞ \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Limit(x**2, x, 0) ascii_str = \ """\ 2\n\ lim x \n\ x->0+ \ """ ucode_str = \ u("""\ 2\n\ lim x \n\ x─→0⁺ \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Limit(1/x, x, 0) ascii_str = \ """\ 1\n\ lim -\n\ x->0+x\ """ ucode_str = \ u("""\ 1\n\ lim ─\n\ x─→0⁺x\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Limit(sin(x)/x, x, 0) ascii_str = \ """\ /sin(x)\\\n\ lim |------|\n\ x->0+\\ x /\ """ ucode_str = \ u("""\ ⎛sin(x)⎞\n\ lim ⎜──────⎟\n\ x─→0⁺⎝ x ⎠\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Limit(sin(x)/x, x, 0, "-") ascii_str = \ """\ /sin(x)\\\n\ lim |------|\n\ x->0-\\ x /\ """ ucode_str = \ u("""\ ⎛sin(x)⎞\n\ lim ⎜──────⎟\n\ x─→0⁻⎝ x ⎠\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Limit(x + sin(x), x, 0) ascii_str = \ """\ lim (x + sin(x))\n\ x->0+ \ """ ucode_str = \ u("""\ lim (x + sin(x))\n\ x─→0⁺ \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Limit(x, x, 0)**2 ascii_str = \ """\ 2\n\ / lim x\\ \n\ \\x->0+ / \ """ ucode_str = \ u("""\ 2\n\ ⎛ lim x⎞ \n\ ⎝x─→0⁺ ⎠ \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Limit(x*Limit(y/2,y,0), x, 0) ascii_str = \ """\ / /y\\\\\n\ lim |x* lim |-||\n\ x->0+\\ y->0+\\2//\ """ ucode_str = \ u("""\ ⎛ ⎛y⎞⎞\n\ lim ⎜x⋅ lim ⎜─⎟⎟\n\ x─→0⁺⎝ y─→0⁺⎝2⎠⎠\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = 2*Limit(x*Limit(y/2,y,0), x, 0) ascii_str = \ """\ / /y\\\\\n\ 2* lim |x* lim |-||\n\ x->0+\\ y->0+\\2//\ """ ucode_str = \ u("""\ ⎛ ⎛y⎞⎞\n\ 2⋅ lim ⎜x⋅ lim ⎜─⎟⎟\n\ x─→0⁺⎝ y─→0⁺⎝2⎠⎠\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Limit(sin(x), x, 0, dir='+-') ascii_str = \ """\ lim sin(x)\n\ x->0 \ """ ucode_str = \ u("""\ lim sin(x)\n\ x─→0 \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_pretty_ComplexRootOf(): expr = rootof(x**5 + 11*x - 2, 0) ascii_str = \ """\ / 5 \\\n\ CRootOf\\x + 11*x - 2, 0/\ """ ucode_str = \ u("""\ ⎛ 5 ⎞\n\ CRootOf⎝x + 11⋅x - 2, 0⎠\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_pretty_RootSum(): expr = RootSum(x**5 + 11*x - 2, auto=False) ascii_str = \ """\ / 5 \\\n\ RootSum\\x + 11*x - 2/\ """ ucode_str = \ u("""\ ⎛ 5 ⎞\n\ RootSum⎝x + 11⋅x - 2⎠\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = RootSum(x**5 + 11*x - 2, Lambda(z, exp(z))) ascii_str = \ """\ / 5 z\\\n\ RootSum\\x + 11*x - 2, z -> e /\ """ ucode_str = \ u("""\ ⎛ 5 z⎞\n\ RootSum⎝x + 11⋅x - 2, z ↦ ℯ ⎠\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_GroebnerBasis(): expr = groebner([], x, y) ascii_str = \ """\ GroebnerBasis([], x, y, domain=ZZ, order=lex)\ """ ucode_str = \ u("""\ GroebnerBasis([], x, y, domain=ℤ, order=lex)\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str F = [x**2 - 3*y - x + 1, y**2 - 2*x + y - 1] expr = groebner(F, x, y, order='grlex') ascii_str = \ """\ /[ 2 2 ] \\\n\ GroebnerBasis\\[x - x - 3*y + 1, y - 2*x + y - 1], x, y, domain=ZZ, order=grlex/\ """ ucode_str = \ u("""\ ⎛⎡ 2 2 ⎤ ⎞\n\ GroebnerBasis⎝⎣x - x - 3⋅y + 1, y - 2⋅x + y - 1⎦, x, y, domain=ℤ, order=grlex⎠\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = expr.fglm('lex') ascii_str = \ """\ /[ 2 4 3 2 ] \\\n\ GroebnerBasis\\[2*x - y - y + 1, y + 2*y - 3*y - 16*y + 7], x, y, domain=ZZ, order=lex/\ """ ucode_str = \ u("""\ ⎛⎡ 2 4 3 2 ⎤ ⎞\n\ GroebnerBasis⎝⎣2⋅x - y - y + 1, y + 2⋅y - 3⋅y - 16⋅y + 7⎦, x, y, domain=ℤ, order=lex⎠\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_pretty_UniversalSet(): assert pretty(S.UniversalSet) == "UniversalSet" assert upretty(S.UniversalSet) == u'𝕌' def test_pretty_Boolean(): expr = Not(x, evaluate=False) assert pretty(expr) == "Not(x)" assert upretty(expr) == u"¬x" expr = And(x, y) assert pretty(expr) == "And(x, y)" assert upretty(expr) == u"x ∧ y" expr = Or(x, y) assert pretty(expr) == "Or(x, y)" assert upretty(expr) == u"x ∨ y" syms = symbols('a:f') expr = And(*syms) assert pretty(expr) == "And(a, b, c, d, e, f)" assert upretty(expr) == u"a ∧ b ∧ c ∧ d ∧ e ∧ f" expr = Or(*syms) assert pretty(expr) == "Or(a, b, c, d, e, f)" assert upretty(expr) == u"a ∨ b ∨ c ∨ d ∨ e ∨ f" expr = Xor(x, y, evaluate=False) assert pretty(expr) == "Xor(x, y)" assert upretty(expr) == u"x ⊻ y" expr = Nand(x, y, evaluate=False) assert pretty(expr) == "Nand(x, y)" assert upretty(expr) == u"x ⊼ y" expr = Nor(x, y, evaluate=False) assert pretty(expr) == "Nor(x, y)" assert upretty(expr) == u"x ⊽ y" expr = Implies(x, y, evaluate=False) assert pretty(expr) == "Implies(x, y)" assert upretty(expr) == u"x → y" # don't sort args expr = Implies(y, x, evaluate=False) assert pretty(expr) == "Implies(y, x)" assert upretty(expr) == u"y → x" expr = Equivalent(x, y, evaluate=False) assert pretty(expr) == "Equivalent(x, y)" assert upretty(expr) == u"x ⇔ y" expr = Equivalent(y, x, evaluate=False) assert pretty(expr) == "Equivalent(x, y)" assert upretty(expr) == u"x ⇔ y" def test_pretty_Domain(): expr = FF(23) assert pretty(expr) == "GF(23)" assert upretty(expr) == u"ℤ₂₃" expr = ZZ assert pretty(expr) == "ZZ" assert upretty(expr) == u"ℤ" expr = QQ assert pretty(expr) == "QQ" assert upretty(expr) == u"ℚ" expr = RR assert pretty(expr) == "RR" assert upretty(expr) == u"ℝ" expr = QQ[x] assert pretty(expr) == "QQ[x]" assert upretty(expr) == u"ℚ[x]" expr = QQ[x, y] assert pretty(expr) == "QQ[x, y]" assert upretty(expr) == u"ℚ[x, y]" expr = ZZ.frac_field(x) assert pretty(expr) == "ZZ(x)" assert upretty(expr) == u"ℤ(x)" expr = ZZ.frac_field(x, y) assert pretty(expr) == "ZZ(x, y)" assert upretty(expr) == u"ℤ(x, y)" expr = QQ.poly_ring(x, y, order=grlex) assert pretty(expr) == "QQ[x, y, order=grlex]" assert upretty(expr) == u"ℚ[x, y, order=grlex]" expr = QQ.poly_ring(x, y, order=ilex) assert pretty(expr) == "QQ[x, y, order=ilex]" assert upretty(expr) == u"ℚ[x, y, order=ilex]" def test_pretty_prec(): assert xpretty(S("0.3"), full_prec=True, wrap_line=False) == "0.300000000000000" assert xpretty(S("0.3"), full_prec="auto", wrap_line=False) == "0.300000000000000" assert xpretty(S("0.3"), full_prec=False, wrap_line=False) == "0.3" assert xpretty(S("0.3")*x, full_prec=True, use_unicode=False, wrap_line=False) in [ "0.300000000000000*x", "x*0.300000000000000" ] assert xpretty(S("0.3")*x, full_prec="auto", use_unicode=False, wrap_line=False) in [ "0.3*x", "x*0.3" ] assert xpretty(S("0.3")*x, full_prec=False, use_unicode=False, wrap_line=False) in [ "0.3*x", "x*0.3" ] def test_pprint(): import sys from sympy.core.compatibility import StringIO fd = StringIO() sso = sys.stdout sys.stdout = fd try: pprint(pi, use_unicode=False, wrap_line=False) finally: sys.stdout = sso assert fd.getvalue() == 'pi\n' def test_pretty_class(): """Test that the printer dispatcher correctly handles classes.""" class C: pass # C has no .__class__ and this was causing problems class D(object): pass assert pretty( C ) == str( C ) assert pretty( D ) == str( D ) def test_pretty_no_wrap_line(): huge_expr = 0 for i in range(20): huge_expr += i*sin(i + x) assert xpretty(huge_expr ).find('\n') != -1 assert xpretty(huge_expr, wrap_line=False).find('\n') == -1 def test_settings(): raises(TypeError, lambda: pretty(S(4), method="garbage")) def test_pretty_sum(): from sympy.abc import x, a, b, k, m, n expr = Sum(k**k, (k, 0, n)) ascii_str = \ """\ n \n\ ___ \n\ \\ ` \n\ \\ k\n\ / k \n\ /__, \n\ k = 0 \ """ ucode_str = \ u("""\ n \n\ ___ \n\ ╲ \n\ ╲ k\n\ ╱ k \n\ ╱ \n\ ‾‾‾ \n\ k = 0 \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Sum(k**k, (k, oo, n)) ascii_str = \ """\ n \n\ ___ \n\ \\ ` \n\ \\ k\n\ / k \n\ /__, \n\ k = oo \ """ ucode_str = \ u("""\ n \n\ ___ \n\ ╲ \n\ ╲ k\n\ ╱ k \n\ ╱ \n\ ‾‾‾ \n\ k = ∞ \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Sum(k**(Integral(x**n, (x, -oo, oo))), (k, 0, n**n)) ascii_str = \ """\ n \n\ n \n\ ______ \n\ \\ ` \n\ \\ oo \n\ \\ / \n\ \\ | \n\ \\ | n \n\ ) | x dx\n\ / | \n\ / / \n\ / -oo \n\ / k \n\ /_____, \n\ k = 0 \ """ ucode_str = \ u("""\ n \n\ n \n\ ______ \n\ ╲ \n\ ╲ \n\ ╲ ∞ \n\ ╲ ⌠ \n\ ╲ ⎮ n \n\ ╱ ⎮ x dx\n\ ╱ ⌡ \n\ ╱ -∞ \n\ ╱ k \n\ ╱ \n\ ‾‾‾‾‾‾ \n\ k = 0 \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Sum(k**( Integral(x**n, (x, -oo, oo))), (k, 0, Integral(x**x, (x, -oo, oo)))) ascii_str = \ """\ oo \n\ / \n\ | \n\ | x \n\ | x dx \n\ | \n\ / \n\ -oo \n\ ______ \n\ \\ ` \n\ \\ oo \n\ \\ / \n\ \\ | \n\ \\ | n \n\ ) | x dx\n\ / | \n\ / / \n\ / -oo \n\ / k \n\ /_____, \n\ k = 0 \ """ ucode_str = \ u("""\ ∞ \n\ ⌠ \n\ ⎮ x \n\ ⎮ x dx \n\ ⌡ \n\ -∞ \n\ ______ \n\ ╲ \n\ ╲ \n\ ╲ ∞ \n\ ╲ ⌠ \n\ ╲ ⎮ n \n\ ╱ ⎮ x dx\n\ ╱ ⌡ \n\ ╱ -∞ \n\ ╱ k \n\ ╱ \n\ ‾‾‾‾‾‾ \n\ k = 0 \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Sum(k**(Integral(x**n, (x, -oo, oo))), ( k, x + n + x**2 + n**2 + (x/n) + (1/x), Integral(x**x, (x, -oo, oo)))) ascii_str = \ """\ oo \n\ / \n\ | \n\ | x \n\ | x dx \n\ | \n\ / \n\ -oo \n\ ______ \n\ \\ ` \n\ \\ oo \n\ \\ / \n\ \\ | \n\ \\ | n \n\ ) | x dx\n\ / | \n\ / / \n\ / -oo \n\ / k \n\ /_____, \n\ 2 2 1 x \n\ k = n + n + x + x + - + - \n\ x n \ """ ucode_str = \ u("""\ ∞ \n\ ⌠ \n\ ⎮ x \n\ ⎮ x dx \n\ ⌡ \n\ -∞ \n\ ______ \n\ ╲ \n\ ╲ \n\ ╲ ∞ \n\ ╲ ⌠ \n\ ╲ ⎮ n \n\ ╱ ⎮ x dx\n\ ╱ ⌡ \n\ ╱ -∞ \n\ ╱ k \n\ ╱ \n\ ‾‾‾‾‾‾ \n\ 2 2 1 x \n\ k = n + n + x + x + ─ + ─ \n\ x n \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Sum(k**( Integral(x**n, (x, -oo, oo))), (k, 0, x + n + x**2 + n**2 + (x/n) + (1/x))) ascii_str = \ """\ 2 2 1 x \n\ n + n + x + x + - + - \n\ x n \n\ ______ \n\ \\ ` \n\ \\ oo \n\ \\ / \n\ \\ | \n\ \\ | n \n\ ) | x dx\n\ / | \n\ / / \n\ / -oo \n\ / k \n\ /_____, \n\ k = 0 \ """ ucode_str = \ u("""\ 2 2 1 x \n\ n + n + x + x + ─ + ─ \n\ x n \n\ ______ \n\ ╲ \n\ ╲ \n\ ╲ ∞ \n\ ╲ ⌠ \n\ ╲ ⎮ n \n\ ╱ ⎮ x dx\n\ ╱ ⌡ \n\ ╱ -∞ \n\ ╱ k \n\ ╱ \n\ ‾‾‾‾‾‾ \n\ k = 0 \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Sum(x, (x, 0, oo)) ascii_str = \ """\ oo \n\ __ \n\ \\ ` \n\ ) x\n\ /_, \n\ x = 0 \ """ ucode_str = \ u("""\ ∞ \n\ ___ \n\ ╲ \n\ ╲ \n\ ╱ x\n\ ╱ \n\ ‾‾‾ \n\ x = 0 \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Sum(x**2, (x, 0, oo)) ascii_str = \ u("""\ oo \n\ ___ \n\ \\ ` \n\ \\ 2\n\ / x \n\ /__, \n\ x = 0 \ """) ucode_str = \ u("""\ ∞ \n\ ___ \n\ ╲ \n\ ╲ 2\n\ ╱ x \n\ ╱ \n\ ‾‾‾ \n\ x = 0 \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Sum(x/2, (x, 0, oo)) ascii_str = \ """\ oo \n\ ___ \n\ \\ ` \n\ \\ x\n\ ) -\n\ / 2\n\ /__, \n\ x = 0 \ """ ucode_str = \ u("""\ ∞ \n\ ____ \n\ ╲ \n\ ╲ \n\ ╲ x\n\ ╱ ─\n\ ╱ 2\n\ ╱ \n\ ‾‾‾‾ \n\ x = 0 \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Sum(x**3/2, (x, 0, oo)) ascii_str = \ """\ oo \n\ ____ \n\ \\ ` \n\ \\ 3\n\ \\ x \n\ / --\n\ / 2 \n\ /___, \n\ x = 0 \ """ ucode_str = \ u("""\ ∞ \n\ ____ \n\ ╲ \n\ ╲ 3\n\ ╲ x \n\ ╱ ──\n\ ╱ 2 \n\ ╱ \n\ ‾‾‾‾ \n\ x = 0 \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Sum((x**3*y**(x/2))**n, (x, 0, oo)) ascii_str = \ """\ oo \n\ ____ \n\ \\ ` \n\ \\ n\n\ \\ / x\\ \n\ ) | -| \n\ / | 3 2| \n\ / \\x *y / \n\ /___, \n\ x = 0 \ """ ucode_str = \ u("""\ ∞ \n\ _____ \n\ ╲ \n\ ╲ \n\ ╲ n\n\ ╲ ⎛ x⎞ \n\ ╱ ⎜ ─⎟ \n\ ╱ ⎜ 3 2⎟ \n\ ╱ ⎝x ⋅y ⎠ \n\ ╱ \n\ ‾‾‾‾‾ \n\ x = 0 \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Sum(1/x**2, (x, 0, oo)) ascii_str = \ """\ oo \n\ ____ \n\ \\ ` \n\ \\ 1 \n\ \\ --\n\ / 2\n\ / x \n\ /___, \n\ x = 0 \ """ ucode_str = \ u("""\ ∞ \n\ ____ \n\ ╲ \n\ ╲ 1 \n\ ╲ ──\n\ ╱ 2\n\ ╱ x \n\ ╱ \n\ ‾‾‾‾ \n\ x = 0 \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Sum(1/y**(a/b), (x, 0, oo)) ascii_str = \ """\ oo \n\ ____ \n\ \\ ` \n\ \\ -a \n\ \\ ---\n\ / b \n\ / y \n\ /___, \n\ x = 0 \ """ ucode_str = \ u("""\ ∞ \n\ ____ \n\ ╲ \n\ ╲ -a \n\ ╲ ───\n\ ╱ b \n\ ╱ y \n\ ╱ \n\ ‾‾‾‾ \n\ x = 0 \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Sum(1/y**(a/b), (x, 0, oo), (y, 1, 2)) ascii_str = \ """\ 2 oo \n\ ____ ____ \n\ \\ ` \\ ` \n\ \\ \\ -a\n\ \\ \\ --\n\ / / b \n\ / / y \n\ /___, /___, \n\ y = 1 x = 0 \ """ ucode_str = \ u("""\ 2 ∞ \n\ ____ ____ \n\ ╲ ╲ \n\ ╲ ╲ -a\n\ ╲ ╲ ──\n\ ╱ ╱ b \n\ ╱ ╱ y \n\ ╱ ╱ \n\ ‾‾‾‾ ‾‾‾‾ \n\ y = 1 x = 0 \ """) expr = Sum(1/(1 + 1/( 1 + 1/k)) + 1, (k, 111, 1 + 1/n), (k, 1/(1 + m), oo)) + 1/(1 + 1/k) ascii_str = \ """\ 1 \n\ 1 + - \n\ oo n \n\ _____ _____ \n\ \\ ` \\ ` \n\ \\ \\ / 1 \\ \n\ \\ \\ |1 + ---------| \n\ \\ \\ | 1 | 1 \n\ ) ) | 1 + -----| + -----\n\ / / | 1| 1\n\ / / | 1 + -| 1 + -\n\ / / \\ k/ k\n\ /____, /____, \n\ 1 k = 111 \n\ k = ----- \n\ m + 1 \ """ ucode_str = \ u("""\ 1 \n\ 1 + ─ \n\ ∞ n \n\ ______ ______ \n\ ╲ ╲ \n\ ╲ ╲ \n\ ╲ ╲ ⎛ 1 ⎞ \n\ ╲ ╲ ⎜1 + ─────────⎟ \n\ ╲ ╲ ⎜ 1 ⎟ 1 \n\ ╱ ╱ ⎜ 1 + ─────⎟ + ─────\n\ ╱ ╱ ⎜ 1⎟ 1\n\ ╱ ╱ ⎜ 1 + ─⎟ 1 + ─\n\ ╱ ╱ ⎝ k⎠ k\n\ ╱ ╱ \n\ ‾‾‾‾‾‾ ‾‾‾‾‾‾ \n\ 1 k = 111 \n\ k = ───── \n\ m + 1 \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_units(): expr = joule ascii_str1 = \ """\ 2\n\ kilogram*meter \n\ ---------------\n\ 2 \n\ second \ """ unicode_str1 = \ u("""\ 2\n\ kilogram⋅meter \n\ ───────────────\n\ 2 \n\ second \ """) ascii_str2 = \ """\ 2\n\ 3*x*y*kilogram*meter \n\ ---------------------\n\ 2 \n\ second \ """ unicode_str2 = \ u("""\ 2\n\ 3⋅x⋅y⋅kilogram⋅meter \n\ ─────────────────────\n\ 2 \n\ second \ """) from sympy.physics.units import kg, m, s assert upretty(expr) == u("joule") assert pretty(expr) == "joule" assert upretty(expr.convert_to(kg*m**2/s**2)) == unicode_str1 assert pretty(expr.convert_to(kg*m**2/s**2)) == ascii_str1 assert upretty(3*kg*x*m**2*y/s**2) == unicode_str2 assert pretty(3*kg*x*m**2*y/s**2) == ascii_str2 def test_pretty_Subs(): f = Function('f') expr = Subs(f(x), x, ph**2) ascii_str = \ """\ (f(x))| 2\n\ |x=phi \ """ unicode_str = \ u("""\ (f(x))│ 2\n\ │x=φ \ """) assert pretty(expr) == ascii_str assert upretty(expr) == unicode_str expr = Subs(f(x).diff(x), x, 0) ascii_str = \ """\ /d \\| \n\ |--(f(x))|| \n\ \\dx /|x=0\ """ unicode_str = \ u("""\ ⎛d ⎞│ \n\ ⎜──(f(x))⎟│ \n\ ⎝dx ⎠│x=0\ """) assert pretty(expr) == ascii_str assert upretty(expr) == unicode_str expr = Subs(f(x).diff(x)/y, (x, y), (0, Rational(1, 2))) ascii_str = \ """\ /d \\| \n\ |--(f(x))|| \n\ |dx || \n\ |--------|| \n\ \\ y /|x=0, y=1/2\ """ unicode_str = \ u("""\ ⎛d ⎞│ \n\ ⎜──(f(x))⎟│ \n\ ⎜dx ⎟│ \n\ ⎜────────⎟│ \n\ ⎝ y ⎠│x=0, y=1/2\ """) assert pretty(expr) == ascii_str assert upretty(expr) == unicode_str def test_gammas(): assert upretty(lowergamma(x, y)) == u"γ(x, y)" assert upretty(uppergamma(x, y)) == u"Γ(x, y)" assert xpretty(gamma(x), use_unicode=True) == u'Γ(x)' assert xpretty(gamma, use_unicode=True) == u'Γ' assert xpretty(symbols('gamma', cls=Function)(x), use_unicode=True) == u'γ(x)' assert xpretty(symbols('gamma', cls=Function), use_unicode=True) == u'γ' def test_beta(): assert xpretty(beta(x,y), use_unicode=True) == u'Β(x, y)' assert xpretty(beta(x,y), use_unicode=False) == u'B(x, y)' assert xpretty(beta, use_unicode=True) == u'Β' assert xpretty(beta, use_unicode=False) == u'B' mybeta = Function('beta') assert xpretty(mybeta(x), use_unicode=True) == u'β(x)' assert xpretty(mybeta(x, y, z), use_unicode=False) == u'beta(x, y, z)' assert xpretty(mybeta, use_unicode=True) == u'β' # test that notation passes to subclasses of the same name only def test_function_subclass_different_name(): class mygamma(gamma): pass assert xpretty(mygamma, use_unicode=True) == r"mygamma" assert xpretty(mygamma(x), use_unicode=True) == r"mygamma(x)" def test_SingularityFunction(): assert xpretty(SingularityFunction(x, 0, n), use_unicode=True) == ( """\ n\n\ <x> \ """) assert xpretty(SingularityFunction(x, 1, n), use_unicode=True) == ( """\ n\n\ <x - 1> \ """) assert xpretty(SingularityFunction(x, -1, n), use_unicode=True) == ( """\ n\n\ <x + 1> \ """) assert xpretty(SingularityFunction(x, a, n), use_unicode=True) == ( """\ n\n\ <-a + x> \ """) assert xpretty(SingularityFunction(x, y, n), use_unicode=True) == ( """\ n\n\ <x - y> \ """) assert xpretty(SingularityFunction(x, 0, n), use_unicode=False) == ( """\ n\n\ <x> \ """) assert xpretty(SingularityFunction(x, 1, n), use_unicode=False) == ( """\ n\n\ <x - 1> \ """) assert xpretty(SingularityFunction(x, -1, n), use_unicode=False) == ( """\ n\n\ <x + 1> \ """) assert xpretty(SingularityFunction(x, a, n), use_unicode=False) == ( """\ n\n\ <-a + x> \ """) assert xpretty(SingularityFunction(x, y, n), use_unicode=False) == ( """\ n\n\ <x - y> \ """) def test_deltas(): assert xpretty(DiracDelta(x), use_unicode=True) == u'δ(x)' assert xpretty(DiracDelta(x, 1), use_unicode=True) == \ u("""\ (1) \n\ δ (x)\ """) assert xpretty(x*DiracDelta(x, 1), use_unicode=True) == \ u("""\ (1) \n\ x⋅δ (x)\ """) def test_hyper(): expr = hyper((), (), z) ucode_str = \ u("""\ ┌─ ⎛ │ ⎞\n\ ├─ ⎜ │ z⎟\n\ 0╵ 0 ⎝ │ ⎠\ """) ascii_str = \ """\ _ \n\ |_ / | \\\n\ | | | z|\n\ 0 0 \\ | /\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = hyper((), (1,), x) ucode_str = \ u("""\ ┌─ ⎛ │ ⎞\n\ ├─ ⎜ │ x⎟\n\ 0╵ 1 ⎝1 │ ⎠\ """) ascii_str = \ """\ _ \n\ |_ / | \\\n\ | | | x|\n\ 0 1 \\1 | /\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = hyper([2], [1], x) ucode_str = \ u("""\ ┌─ ⎛2 │ ⎞\n\ ├─ ⎜ │ x⎟\n\ 1╵ 1 ⎝1 │ ⎠\ """) ascii_str = \ """\ _ \n\ |_ /2 | \\\n\ | | | x|\n\ 1 1 \\1 | /\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = hyper((pi/3, -2*k), (3, 4, 5, -3), x) ucode_str = \ u("""\ ⎛ π │ ⎞\n\ ┌─ ⎜ ─, -2⋅k │ ⎟\n\ ├─ ⎜ 3 │ x⎟\n\ 2╵ 4 ⎜ │ ⎟\n\ ⎝3, 4, 5, -3 │ ⎠\ """) ascii_str = \ """\ \n\ _ / pi | \\\n\ |_ | --, -2*k | |\n\ | | 3 | x|\n\ 2 4 | | |\n\ \\3, 4, 5, -3 | /\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = hyper((pi, S('2/3'), -2*k), (3, 4, 5, -3), x**2) ucode_str = \ u("""\ ┌─ ⎛π, 2/3, -2⋅k │ 2⎞\n\ ├─ ⎜ │ x ⎟\n\ 3╵ 4 ⎝3, 4, 5, -3 │ ⎠\ """) ascii_str = \ """\ _ \n\ |_ /pi, 2/3, -2*k | 2\\\n\ | | | x |\n\ 3 4 \\ 3, 4, 5, -3 | /\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = hyper([1, 2], [3, 4], 1/(1/(1/(1/x + 1) + 1) + 1)) ucode_str = \ u("""\ ⎛ │ 1 ⎞\n\ ⎜ │ ─────────────⎟\n\ ⎜ │ 1 ⎟\n\ ┌─ ⎜1, 2 │ 1 + ─────────⎟\n\ ├─ ⎜ │ 1 ⎟\n\ 2╵ 2 ⎜3, 4 │ 1 + ─────⎟\n\ ⎜ │ 1⎟\n\ ⎜ │ 1 + ─⎟\n\ ⎝ │ x⎠\ """) ascii_str = \ """\ \n\ / | 1 \\\n\ | | -------------|\n\ _ | | 1 |\n\ |_ |1, 2 | 1 + ---------|\n\ | | | 1 |\n\ 2 2 |3, 4 | 1 + -----|\n\ | | 1|\n\ | | 1 + -|\n\ \\ | x/\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_meijerg(): expr = meijerg([pi, pi, x], [1], [0, 1], [1, 2, 3], z) ucode_str = \ u("""\ ╭─╮2, 3 ⎛π, π, x 1 │ ⎞\n\ │╶┐ ⎜ │ z⎟\n\ ╰─╯4, 5 ⎝ 0, 1 1, 2, 3 │ ⎠\ """) ascii_str = \ """\ __2, 3 /pi, pi, x 1 | \\\n\ /__ | | z|\n\ \\_|4, 5 \\ 0, 1 1, 2, 3 | /\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = meijerg([1, pi/7], [2, pi, 5], [], [], z**2) ucode_str = \ u("""\ ⎛ π │ ⎞\n\ ╭─╮0, 2 ⎜1, ─ 2, π, 5 │ 2⎟\n\ │╶┐ ⎜ 7 │ z ⎟\n\ ╰─╯5, 0 ⎜ │ ⎟\n\ ⎝ │ ⎠\ """) ascii_str = \ """\ / pi | \\\n\ __0, 2 |1, -- 2, pi, 5 | 2|\n\ /__ | 7 | z |\n\ \\_|5, 0 | | |\n\ \\ | /\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str ucode_str = \ u("""\ ╭─╮ 1, 10 ⎛1, 1, 1, 1, 1, 1, 1, 1, 1, 1 1 │ ⎞\n\ │╶┐ ⎜ │ z⎟\n\ ╰─╯11, 2 ⎝ 1 1 │ ⎠\ """) ascii_str = \ """\ __ 1, 10 /1, 1, 1, 1, 1, 1, 1, 1, 1, 1 1 | \\\n\ /__ | | z|\n\ \\_|11, 2 \\ 1 1 | /\ """ expr = meijerg([1]*10, [1], [1], [1], z) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = meijerg([1, 2, ], [4, 3], [3], [4, 5], 1/(1/(1/(1/x + 1) + 1) + 1)) ucode_str = \ u("""\ ⎛ │ 1 ⎞\n\ ⎜ │ ─────────────⎟\n\ ⎜ │ 1 ⎟\n\ ╭─╮1, 2 ⎜1, 2 4, 3 │ 1 + ─────────⎟\n\ │╶┐ ⎜ │ 1 ⎟\n\ ╰─╯4, 3 ⎜ 3 4, 5 │ 1 + ─────⎟\n\ ⎜ │ 1⎟\n\ ⎜ │ 1 + ─⎟\n\ ⎝ │ x⎠\ """) ascii_str = \ """\ / | 1 \\\n\ | | -------------|\n\ | | 1 |\n\ __1, 2 |1, 2 4, 3 | 1 + ---------|\n\ /__ | | 1 |\n\ \\_|4, 3 | 3 4, 5 | 1 + -----|\n\ | | 1|\n\ | | 1 + -|\n\ \\ | x/\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Integral(expr, x) ucode_str = \ u("""\ ⌠ \n\ ⎮ ⎛ │ 1 ⎞ \n\ ⎮ ⎜ │ ─────────────⎟ \n\ ⎮ ⎜ │ 1 ⎟ \n\ ⎮ ╭─╮1, 2 ⎜1, 2 4, 3 │ 1 + ─────────⎟ \n\ ⎮ │╶┐ ⎜ │ 1 ⎟ dx\n\ ⎮ ╰─╯4, 3 ⎜ 3 4, 5 │ 1 + ─────⎟ \n\ ⎮ ⎜ │ 1⎟ \n\ ⎮ ⎜ │ 1 + ─⎟ \n\ ⎮ ⎝ │ x⎠ \n\ ⌡ \ """) ascii_str = \ """\ / \n\ | \n\ | / | 1 \\ \n\ | | | -------------| \n\ | | | 1 | \n\ | __1, 2 |1, 2 4, 3 | 1 + ---------| \n\ | /__ | | 1 | dx\n\ | \\_|4, 3 | 3 4, 5 | 1 + -----| \n\ | | | 1| \n\ | | | 1 + -| \n\ | \\ | x/ \n\ | \n\ / \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_noncommutative(): A, B, C = symbols('A,B,C', commutative=False) expr = A*B*C**-1 ascii_str = \ """\ -1\n\ A*B*C \ """ ucode_str = \ u("""\ -1\n\ A⋅B⋅C \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = C**-1*A*B ascii_str = \ """\ -1 \n\ C *A*B\ """ ucode_str = \ u("""\ -1 \n\ C ⋅A⋅B\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = A*C**-1*B ascii_str = \ """\ -1 \n\ A*C *B\ """ ucode_str = \ u("""\ -1 \n\ A⋅C ⋅B\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = A*C**-1*B/x ascii_str = \ """\ -1 \n\ A*C *B\n\ -------\n\ x \ """ ucode_str = \ u("""\ -1 \n\ A⋅C ⋅B\n\ ───────\n\ x \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_pretty_special_functions(): x, y = symbols("x y") # atan2 expr = atan2(y/sqrt(200), sqrt(x)) ascii_str = \ """\ / ___ \\\n\ |\\/ 2 *y ___|\n\ atan2|-------, \\/ x |\n\ \\ 20 /\ """ ucode_str = \ u("""\ ⎛√2⋅y ⎞\n\ atan2⎜────, √x⎟\n\ ⎝ 20 ⎠\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_pretty_geometry(): e = Segment((0, 1), (0, 2)) assert pretty(e) == 'Segment2D(Point2D(0, 1), Point2D(0, 2))' e = Ray((1, 1), angle=4.02*pi) assert pretty(e) == 'Ray2D(Point2D(1, 1), Point2D(2, tan(pi/50) + 1))' def test_expint(): expr = Ei(x) string = 'Ei(x)' assert pretty(expr) == string assert upretty(expr) == string expr = expint(1, z) ucode_str = u"E₁(z)" ascii_str = "expint(1, z)" assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str assert pretty(Shi(x)) == 'Shi(x)' assert pretty(Si(x)) == 'Si(x)' assert pretty(Ci(x)) == 'Ci(x)' assert pretty(Chi(x)) == 'Chi(x)' assert upretty(Shi(x)) == 'Shi(x)' assert upretty(Si(x)) == 'Si(x)' assert upretty(Ci(x)) == 'Ci(x)' assert upretty(Chi(x)) == 'Chi(x)' def test_elliptic_functions(): ascii_str = \ """\ / 1 \\\n\ K|-----|\n\ \\z + 1/\ """ ucode_str = \ u("""\ ⎛ 1 ⎞\n\ K⎜─────⎟\n\ ⎝z + 1⎠\ """) expr = elliptic_k(1/(z + 1)) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str ascii_str = \ """\ / | 1 \\\n\ F|1|-----|\n\ \\ |z + 1/\ """ ucode_str = \ u("""\ ⎛ │ 1 ⎞\n\ F⎜1│─────⎟\n\ ⎝ │z + 1⎠\ """) expr = elliptic_f(1, 1/(1 + z)) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str ascii_str = \ """\ / 1 \\\n\ E|-----|\n\ \\z + 1/\ """ ucode_str = \ u("""\ ⎛ 1 ⎞\n\ E⎜─────⎟\n\ ⎝z + 1⎠\ """) expr = elliptic_e(1/(z + 1)) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str ascii_str = \ """\ / | 1 \\\n\ E|1|-----|\n\ \\ |z + 1/\ """ ucode_str = \ u("""\ ⎛ │ 1 ⎞\n\ E⎜1│─────⎟\n\ ⎝ │z + 1⎠\ """) expr = elliptic_e(1, 1/(1 + z)) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str ascii_str = \ """\ / |4\\\n\ Pi|3|-|\n\ \\ |x/\ """ ucode_str = \ u("""\ ⎛ │4⎞\n\ Π⎜3│─⎟\n\ ⎝ │x⎠\ """) expr = elliptic_pi(3, 4/x) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str ascii_str = \ """\ / 4| \\\n\ Pi|3; -|6|\n\ \\ x| /\ """ ucode_str = \ u("""\ ⎛ 4│ ⎞\n\ Π⎜3; ─│6⎟\n\ ⎝ x│ ⎠\ """) expr = elliptic_pi(3, 4/x, 6) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_RandomDomain(): from sympy.stats import Normal, Die, Exponential, pspace, where X = Normal('x1', 0, 1) assert upretty(where(X > 0)) == u"Domain: 0 < x₁ ∧ x₁ < ∞" D = Die('d1', 6) assert upretty(where(D > 4)) == u'Domain: d₁ = 5 ∨ d₁ = 6' A = Exponential('a', 1) B = Exponential('b', 1) assert upretty(pspace(Tuple(A, B)).domain) == \ u'Domain: 0 ≤ a ∧ 0 ≤ b ∧ a < ∞ ∧ b < ∞' def test_PrettyPoly(): F = QQ.frac_field(x, y) R = QQ.poly_ring(x, y) expr = F.convert(x/(x + y)) assert pretty(expr) == "x/(x + y)" assert upretty(expr) == u"x/(x + y)" expr = R.convert(x + y) assert pretty(expr) == "x + y" assert upretty(expr) == u"x + y" def test_issue_6285(): assert pretty(Pow(2, -5, evaluate=False)) == '1 \n--\n 5\n2 ' assert pretty(Pow(x, (1/pi))) == 'pi___\n\\/ x ' def test_issue_6359(): assert pretty(Integral(x**2, x)**2) == \ """\ 2 / / \\ \n\ | | | \n\ | | 2 | \n\ | | x dx| \n\ | | | \n\ \\/ / \ """ assert upretty(Integral(x**2, x)**2) == \ u("""\ 2 ⎛⌠ ⎞ \n\ ⎜⎮ 2 ⎟ \n\ ⎜⎮ x dx⎟ \n\ ⎝⌡ ⎠ \ """) assert pretty(Sum(x**2, (x, 0, 1))**2) == \ """\ 2 / 1 \\ \n\ | ___ | \n\ | \\ ` | \n\ | \\ 2| \n\ | / x | \n\ | /__, | \n\ \\x = 0 / \ """ assert upretty(Sum(x**2, (x, 0, 1))**2) == \ u("""\ 2 ⎛ 1 ⎞ \n\ ⎜ ___ ⎟ \n\ ⎜ ╲ ⎟ \n\ ⎜ ╲ 2⎟ \n\ ⎜ ╱ x ⎟ \n\ ⎜ ╱ ⎟ \n\ ⎜ ‾‾‾ ⎟ \n\ ⎝x = 0 ⎠ \ """) assert pretty(Product(x**2, (x, 1, 2))**2) == \ """\ 2 / 2 \\ \n\ |______ | \n\ | | | 2| \n\ | | | x | \n\ | | | | \n\ \\x = 1 / \ """ assert upretty(Product(x**2, (x, 1, 2))**2) == \ u("""\ 2 ⎛ 2 ⎞ \n\ ⎜─┬──┬─ ⎟ \n\ ⎜ │ │ 2⎟ \n\ ⎜ │ │ x ⎟ \n\ ⎜ │ │ ⎟ \n\ ⎝x = 1 ⎠ \ """) f = Function('f') assert pretty(Derivative(f(x), x)**2) == \ """\ 2 /d \\ \n\ |--(f(x))| \n\ \\dx / \ """ assert upretty(Derivative(f(x), x)**2) == \ u("""\ 2 ⎛d ⎞ \n\ ⎜──(f(x))⎟ \n\ ⎝dx ⎠ \ """) def test_issue_6739(): ascii_str = \ """\ 1 \n\ -----\n\ ___\n\ \\/ x \ """ ucode_str = \ u("""\ 1 \n\ ──\n\ √x\ """) assert pretty(1/sqrt(x)) == ascii_str assert upretty(1/sqrt(x)) == ucode_str def test_complicated_symbol_unchanged(): for symb_name in ["dexpr2_d1tau", "dexpr2^d1tau"]: assert pretty(Symbol(symb_name)) == symb_name def test_categories(): from sympy.categories import (Object, IdentityMorphism, NamedMorphism, Category, Diagram, DiagramGrid) A1 = Object("A1") A2 = Object("A2") A3 = Object("A3") f1 = NamedMorphism(A1, A2, "f1") f2 = NamedMorphism(A2, A3, "f2") id_A1 = IdentityMorphism(A1) K1 = Category("K1") assert pretty(A1) == "A1" assert upretty(A1) == u"A₁" assert pretty(f1) == "f1:A1-->A2" assert upretty(f1) == u"f₁:A₁——▶A₂" assert pretty(id_A1) == "id:A1-->A1" assert upretty(id_A1) == u"id:A₁——▶A₁" assert pretty(f2*f1) == "f2*f1:A1-->A3" assert upretty(f2*f1) == u"f₂∘f₁:A₁——▶A₃" assert pretty(K1) == "K1" assert upretty(K1) == u"K₁" # Test how diagrams are printed. d = Diagram() assert pretty(d) == "EmptySet" assert upretty(d) == u"∅" d = Diagram({f1: "unique", f2: S.EmptySet}) assert pretty(d) == "{f2*f1:A1-->A3: EmptySet, id:A1-->A1: " \ "EmptySet, id:A2-->A2: EmptySet, id:A3-->A3: " \ "EmptySet, f1:A1-->A2: {unique}, f2:A2-->A3: EmptySet}" assert upretty(d) == u("{f₂∘f₁:A₁——▶A₃: ∅, id:A₁——▶A₁: ∅, " \ "id:A₂——▶A₂: ∅, id:A₃——▶A₃: ∅, f₁:A₁——▶A₂: {unique}, f₂:A₂——▶A₃: ∅}") d = Diagram({f1: "unique", f2: S.EmptySet}, {f2 * f1: "unique"}) assert pretty(d) == "{f2*f1:A1-->A3: EmptySet, id:A1-->A1: " \ "EmptySet, id:A2-->A2: EmptySet, id:A3-->A3: " \ "EmptySet, f1:A1-->A2: {unique}, f2:A2-->A3: EmptySet}" \ " ==> {f2*f1:A1-->A3: {unique}}" assert upretty(d) == u("{f₂∘f₁:A₁——▶A₃: ∅, id:A₁——▶A₁: ∅, id:A₂——▶A₂: " \ "∅, id:A₃——▶A₃: ∅, f₁:A₁——▶A₂: {unique}, f₂:A₂——▶A₃: ∅}" \ " ══▶ {f₂∘f₁:A₁——▶A₃: {unique}}") grid = DiagramGrid(d) assert pretty(grid) == "A1 A2\n \nA3 " assert upretty(grid) == u"A₁ A₂\n \nA₃ " def test_PrettyModules(): R = QQ.old_poly_ring(x, y) F = R.free_module(2) M = F.submodule([x, y], [1, x**2]) ucode_str = \ u("""\ 2\n\ ℚ[x, y] \ """) ascii_str = \ """\ 2\n\ QQ[x, y] \ """ assert upretty(F) == ucode_str assert pretty(F) == ascii_str ucode_str = \ u("""\ ╱ ⎡ 2⎤╲\n\ ╲[x, y], ⎣1, x ⎦╱\ """) ascii_str = \ """\ 2 \n\ <[x, y], [1, x ]>\ """ assert upretty(M) == ucode_str assert pretty(M) == ascii_str I = R.ideal(x**2, y) ucode_str = \ u("""\ ╱ 2 ╲\n\ ╲x , y╱\ """) ascii_str = \ """\ 2 \n\ <x , y>\ """ assert upretty(I) == ucode_str assert pretty(I) == ascii_str Q = F / M ucode_str = \ u("""\ 2 \n\ ℚ[x, y] \n\ ─────────────────\n\ ╱ ⎡ 2⎤╲\n\ ╲[x, y], ⎣1, x ⎦╱\ """) ascii_str = \ """\ 2 \n\ QQ[x, y] \n\ -----------------\n\ 2 \n\ <[x, y], [1, x ]>\ """ assert upretty(Q) == ucode_str assert pretty(Q) == ascii_str ucode_str = \ u("""\ ╱⎡ 3⎤ ╲\n\ │⎢ x ⎥ ╱ ⎡ 2⎤╲ ╱ ⎡ 2⎤╲│\n\ │⎢1, ──⎥ + ╲[x, y], ⎣1, x ⎦╱, [2, y] + ╲[x, y], ⎣1, x ⎦╱│\n\ ╲⎣ 2 ⎦ ╱\ """) ascii_str = \ """\ 3 \n\ x 2 2 \n\ <[1, --] + <[x, y], [1, x ]>, [2, y] + <[x, y], [1, x ]>>\n\ 2 \ """ def test_QuotientRing(): R = QQ.old_poly_ring(x)/[x**2 + 1] ucode_str = \ u("""\ ℚ[x] \n\ ────────\n\ ╱ 2 ╲\n\ ╲x + 1╱\ """) ascii_str = \ """\ QQ[x] \n\ --------\n\ 2 \n\ <x + 1>\ """ assert upretty(R) == ucode_str assert pretty(R) == ascii_str ucode_str = \ u("""\ ╱ 2 ╲\n\ 1 + ╲x + 1╱\ """) ascii_str = \ """\ 2 \n\ 1 + <x + 1>\ """ assert upretty(R.one) == ucode_str assert pretty(R.one) == ascii_str def test_Homomorphism(): from sympy.polys.agca import homomorphism R = QQ.old_poly_ring(x) expr = homomorphism(R.free_module(1), R.free_module(1), [0]) ucode_str = \ u("""\ 1 1\n\ [0] : ℚ[x] ──> ℚ[x] \ """) ascii_str = \ """\ 1 1\n\ [0] : QQ[x] --> QQ[x] \ """ assert upretty(expr) == ucode_str assert pretty(expr) == ascii_str expr = homomorphism(R.free_module(2), R.free_module(2), [0, 0]) ucode_str = \ u("""\ ⎡0 0⎤ 2 2\n\ ⎢ ⎥ : ℚ[x] ──> ℚ[x] \n\ ⎣0 0⎦ \ """) ascii_str = \ """\ [0 0] 2 2\n\ [ ] : QQ[x] --> QQ[x] \n\ [0 0] \ """ assert upretty(expr) == ucode_str assert pretty(expr) == ascii_str expr = homomorphism(R.free_module(1), R.free_module(1) / [[x]], [0]) ucode_str = \ u("""\ 1\n\ 1 ℚ[x] \n\ [0] : ℚ[x] ──> ─────\n\ <[x]>\ """) ascii_str = \ """\ 1\n\ 1 QQ[x] \n\ [0] : QQ[x] --> ------\n\ <[x]> \ """ assert upretty(expr) == ucode_str assert pretty(expr) == ascii_str def test_Tr(): A, B = symbols('A B', commutative=False) t = Tr(A*B) assert pretty(t) == r'Tr(A*B)' assert upretty(t) == u'Tr(A⋅B)' def test_pretty_Add(): eq = Mul(-2, x - 2, evaluate=False) + 5 assert pretty(eq) == '5 - 2*(x - 2)' def test_issue_7179(): assert upretty(Not(Equivalent(x, y))) == u'x ⇎ y' assert upretty(Not(Implies(x, y))) == u'x ↛ y' def test_issue_7180(): assert upretty(Equivalent(x, y)) == u'x ⇔ y' def test_pretty_Complement(): assert pretty(S.Reals - S.Naturals) == '(-oo, oo) \\ Naturals' assert upretty(S.Reals - S.Naturals) == u'ℝ \\ ℕ' assert pretty(S.Reals - S.Naturals0) == '(-oo, oo) \\ Naturals0' assert upretty(S.Reals - S.Naturals0) == u'ℝ \\ ℕ₀' def test_pretty_SymmetricDifference(): from sympy import SymmetricDifference, Interval from sympy.testing.pytest import raises assert upretty(SymmetricDifference(Interval(2,3), Interval(3,5), \ evaluate = False)) == u'[2, 3] ∆ [3, 5]' with raises(NotImplementedError): pretty(SymmetricDifference(Interval(2,3), Interval(3,5), evaluate = False)) def test_pretty_Contains(): assert pretty(Contains(x, S.Integers)) == 'Contains(x, Integers)' assert upretty(Contains(x, S.Integers)) == u'x ∈ ℤ' def test_issue_8292(): from sympy.core import sympify e = sympify('((x+x**4)/(x-1))-(2*(x-1)**4/(x-1)**4)', evaluate=False) ucode_str = \ u("""\ 4 4 \n\ 2⋅(x - 1) x + x\n\ - ────────── + ──────\n\ 4 x - 1 \n\ (x - 1) \ """) ascii_str = \ """\ 4 4 \n\ 2*(x - 1) x + x\n\ - ---------- + ------\n\ 4 x - 1 \n\ (x - 1) \ """ assert pretty(e) == ascii_str assert upretty(e) == ucode_str def test_issue_4335(): y = Function('y') expr = -y(x).diff(x) ucode_str = \ u("""\ d \n\ -──(y(x))\n\ dx \ """) ascii_str = \ """\ d \n\ - --(y(x))\n\ dx \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_issue_8344(): from sympy.core import sympify e = sympify('2*x*y**2/1**2 + 1', evaluate=False) ucode_str = \ u("""\ 2 \n\ 2⋅x⋅y \n\ ────── + 1\n\ 2 \n\ 1 \ """) assert upretty(e) == ucode_str def test_issue_6324(): x = Pow(2, 3, evaluate=False) y = Pow(10, -2, evaluate=False) e = Mul(x, y, evaluate=False) ucode_str = \ u("""\ 3\n\ 2 \n\ ───\n\ 2\n\ 10 \ """) assert upretty(e) == ucode_str def test_issue_7927(): e = sin(x/2)**cos(x/2) ucode_str = \ u("""\ ⎛x⎞\n\ cos⎜─⎟\n\ ⎝2⎠\n\ ⎛ ⎛x⎞⎞ \n\ ⎜sin⎜─⎟⎟ \n\ ⎝ ⎝2⎠⎠ \ """) assert upretty(e) == ucode_str e = sin(x)**(S(11)/13) ucode_str = \ u("""\ 11\n\ ──\n\ 13\n\ (sin(x)) \ """) assert upretty(e) == ucode_str def test_issue_6134(): from sympy.abc import lamda, t phi = Function('phi') e = lamda*x*Integral(phi(t)*pi*sin(pi*t), (t, 0, 1)) + lamda*x**2*Integral(phi(t)*2*pi*sin(2*pi*t), (t, 0, 1)) ucode_str = \ u("""\ 1 1 \n\ 2 ⌠ ⌠ \n\ λ⋅x ⋅⎮ 2⋅π⋅φ(t)⋅sin(2⋅π⋅t) dt + λ⋅x⋅⎮ π⋅φ(t)⋅sin(π⋅t) dt\n\ ⌡ ⌡ \n\ 0 0 \ """) assert upretty(e) == ucode_str def test_issue_9877(): ucode_str1 = u'(2, 3) ∪ ([1, 2] \\ {x})' a, b, c = Interval(2, 3, True, True), Interval(1, 2), FiniteSet(x) assert upretty(Union(a, Complement(b, c))) == ucode_str1 ucode_str2 = u'{x} ∩ {y} ∩ ({z} \\ [1, 2])' d, e, f, g = FiniteSet(x), FiniteSet(y), FiniteSet(z), Interval(1, 2) assert upretty(Intersection(d, e, Complement(f, g))) == ucode_str2 def test_issue_13651(): expr1 = c + Mul(-1, a + b, evaluate=False) assert pretty(expr1) == 'c - (a + b)' expr2 = c + Mul(-1, a - b + d, evaluate=False) assert pretty(expr2) == 'c - (a - b + d)' def test_pretty_primenu(): from sympy.ntheory.factor_ import primenu ascii_str1 = "nu(n)" ucode_str1 = u("ν(n)") n = symbols('n', integer=True) assert pretty(primenu(n)) == ascii_str1 assert upretty(primenu(n)) == ucode_str1 def test_pretty_primeomega(): from sympy.ntheory.factor_ import primeomega ascii_str1 = "Omega(n)" ucode_str1 = u("Ω(n)") n = symbols('n', integer=True) assert pretty(primeomega(n)) == ascii_str1 assert upretty(primeomega(n)) == ucode_str1 def test_pretty_Mod(): from sympy.core import Mod ascii_str1 = "x mod 7" ucode_str1 = u("x mod 7") ascii_str2 = "(x + 1) mod 7" ucode_str2 = u("(x + 1) mod 7") ascii_str3 = "2*x mod 7" ucode_str3 = u("2⋅x mod 7") ascii_str4 = "(x mod 7) + 1" ucode_str4 = u("(x mod 7) + 1") ascii_str5 = "2*(x mod 7)" ucode_str5 = u("2⋅(x mod 7)") x = symbols('x', integer=True) assert pretty(Mod(x, 7)) == ascii_str1 assert upretty(Mod(x, 7)) == ucode_str1 assert pretty(Mod(x + 1, 7)) == ascii_str2 assert upretty(Mod(x + 1, 7)) == ucode_str2 assert pretty(Mod(2 * x, 7)) == ascii_str3 assert upretty(Mod(2 * x, 7)) == ucode_str3 assert pretty(Mod(x, 7) + 1) == ascii_str4 assert upretty(Mod(x, 7) + 1) == ucode_str4 assert pretty(2 * Mod(x, 7)) == ascii_str5 assert upretty(2 * Mod(x, 7)) == ucode_str5 def test_issue_11801(): assert pretty(Symbol("")) == "" assert upretty(Symbol("")) == "" def test_pretty_UnevaluatedExpr(): x = symbols('x') he = UnevaluatedExpr(1/x) ucode_str = \ u("""\ 1\n\ ─\n\ x\ """) assert upretty(he) == ucode_str ucode_str = \ u("""\ 2\n\ ⎛1⎞ \n\ ⎜─⎟ \n\ ⎝x⎠ \ """) assert upretty(he**2) == ucode_str ucode_str = \ u("""\ 1\n\ 1 + ─\n\ x\ """) assert upretty(he + 1) == ucode_str ucode_str = \ u('''\ 1\n\ x⋅─\n\ x\ ''') assert upretty(x*he) == ucode_str def test_issue_10472(): M = (Matrix([[0, 0], [0, 0]]), Matrix([0, 0])) ucode_str = \ u("""\ ⎛⎡0 0⎤ ⎡0⎤⎞ ⎜⎢ ⎥, ⎢ ⎥⎟ ⎝⎣0 0⎦ ⎣0⎦⎠\ """) assert upretty(M) == ucode_str def test_MatrixElement_printing(): # test cases for issue #11821 A = MatrixSymbol("A", 1, 3) B = MatrixSymbol("B", 1, 3) C = MatrixSymbol("C", 1, 3) ascii_str1 = "A_00" ucode_str1 = u("A₀₀") assert pretty(A[0, 0]) == ascii_str1 assert upretty(A[0, 0]) == ucode_str1 ascii_str1 = "3*A_00" ucode_str1 = u("3⋅A₀₀") assert pretty(3*A[0, 0]) == ascii_str1 assert upretty(3*A[0, 0]) == ucode_str1 ascii_str1 = "(-B + A)[0, 0]" ucode_str1 = u("(-B + A)[0, 0]") F = C[0, 0].subs(C, A - B) assert pretty(F) == ascii_str1 assert upretty(F) == ucode_str1 def test_issue_12675(): from sympy.vector import CoordSys3D x, y, t, j = symbols('x y t j') e = CoordSys3D('e') ucode_str = \ u("""\ ⎛ t⎞ \n\ ⎜⎛x⎞ ⎟ j_e\n\ ⎜⎜─⎟ ⎟ \n\ ⎝⎝y⎠ ⎠ \ """) assert upretty((x/y)**t*e.j) == ucode_str ucode_str = \ u("""\ ⎛1⎞ \n\ ⎜─⎟ j_e\n\ ⎝y⎠ \ """) assert upretty((1/y)*e.j) == ucode_str def test_MatrixSymbol_printing(): # test cases for issue #14237 A = MatrixSymbol("A", 3, 3) B = MatrixSymbol("B", 3, 3) C = MatrixSymbol("C", 3, 3) assert pretty(-A*B*C) == "-A*B*C" assert pretty(A - B) == "-B + A" assert pretty(A*B*C - A*B - B*C) == "-A*B -B*C + A*B*C" # issue #14814 x = MatrixSymbol('x', n, n) y = MatrixSymbol('y*', n, n) assert pretty(x + y) == "x + y*" ascii_str = \ """\ 2 \n\ -2*y* -a*x\ """ assert pretty(-a*x + -2*y*y) == ascii_str def test_degree_printing(): expr1 = 90*degree assert pretty(expr1) == u'90°' expr2 = x*degree assert pretty(expr2) == u'x°' expr3 = cos(x*degree + 90*degree) assert pretty(expr3) == u'cos(x° + 90°)' def test_vector_expr_pretty_printing(): A = CoordSys3D('A') assert upretty(Cross(A.i, A.x*A.i+3*A.y*A.j)) == u("(i_A)×((x_A) i_A + (3⋅y_A) j_A)") assert upretty(x*Cross(A.i, A.j)) == u('x⋅(i_A)×(j_A)') assert upretty(Curl(A.x*A.i + 3*A.y*A.j)) == u("∇×((x_A) i_A + (3⋅y_A) j_A)") assert upretty(Divergence(A.x*A.i + 3*A.y*A.j)) == u("∇⋅((x_A) i_A + (3⋅y_A) j_A)") assert upretty(Dot(A.i, A.x*A.i+3*A.y*A.j)) == u("(i_A)⋅((x_A) i_A + (3⋅y_A) j_A)") assert upretty(Gradient(A.x+3*A.y)) == u("∇(x_A + 3⋅y_A)") assert upretty(Laplacian(A.x+3*A.y)) == u("∆(x_A + 3⋅y_A)") # TODO: add support for ASCII pretty. def test_pretty_print_tensor_expr(): L = TensorIndexType("L") i, j, k = tensor_indices("i j k", L) i0 = tensor_indices("i_0", L) A, B, C, D = tensor_heads("A B C D", [L]) H = TensorHead("H", [L, L]) expr = -i ascii_str = \ """\ -i\ """ ucode_str = \ u("""\ -i\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = A(i) ascii_str = \ """\ i\n\ A \n\ \ """ ucode_str = \ u("""\ i\n\ A \n\ \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = A(i0) ascii_str = \ """\ i_0\n\ A \n\ \ """ ucode_str = \ u("""\ i₀\n\ A \n\ \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = A(-i) ascii_str = \ """\ \n\ A \n\ i\ """ ucode_str = \ u("""\ \n\ A \n\ i\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = -3*A(-i) ascii_str = \ """\ \n\ -3*A \n\ i\ """ ucode_str = \ u("""\ \n\ -3⋅A \n\ i\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = H(i, -j) ascii_str = \ """\ i \n\ H \n\ j\ """ ucode_str = \ u("""\ i \n\ H \n\ j\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = H(i, -i) ascii_str = \ """\ L_0 \n\ H \n\ L_0\ """ ucode_str = \ u("""\ L₀ \n\ H \n\ L₀\ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = H(i, -j)*A(j)*B(k) ascii_str = \ """\ i L_0 k\n\ H *A *B \n\ L_0 \ """ ucode_str = \ u("""\ i L₀ k\n\ H ⋅A ⋅B \n\ L₀ \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = (1+x)*A(i) ascii_str = \ """\ i\n\ (x + 1)*A \n\ \ """ ucode_str = \ u("""\ i\n\ (x + 1)⋅A \n\ \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = A(i) + 3*B(i) ascii_str = \ """\ i i\n\ 3*B + A \n\ \ """ ucode_str = \ u("""\ i i\n\ 3⋅B + A \n\ \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_pretty_print_tensor_partial_deriv(): from sympy.tensor.toperators import PartialDerivative from sympy.tensor.tensor import TensorIndexType, tensor_indices, TensorHead, tensor_heads L = TensorIndexType("L") i, j, k = tensor_indices("i j k", L) A, B, C, D = tensor_heads("A B C D", [L]) H = TensorHead("H", [L, L]) expr = PartialDerivative(A(i), A(j)) ascii_str = \ """\ d / i\\\n\ ---|A |\n\ j\\ /\n\ dA \n\ \ """ ucode_str = \ u("""\ ∂ ⎛ i⎞\n\ ───⎜A ⎟\n\ j⎝ ⎠\n\ ∂A \n\ \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = A(i)*PartialDerivative(H(k, -i), A(j)) ascii_str = \ """\ L_0 d / k \\\n\ A *---|H |\n\ j\\ L_0/\n\ dA \n\ \ """ ucode_str = \ u("""\ L₀ ∂ ⎛ k ⎞\n\ A ⋅───⎜H ⎟\n\ j⎝ L₀⎠\n\ ∂A \n\ \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = A(i)*PartialDerivative(B(k)*C(-i) + 3*H(k, -i), A(j)) ascii_str = \ """\ L_0 d / k k \\\n\ A *---|3*H + B *C |\n\ j\\ L_0 L_0/\n\ dA \n\ \ """ ucode_str = \ u("""\ L₀ ∂ ⎛ k k ⎞\n\ A ⋅───⎜3⋅H + B ⋅C ⎟\n\ j⎝ L₀ L₀⎠\n\ ∂A \n\ \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = (A(i) + B(i))*PartialDerivative(C(j), D(j)) ascii_str = \ """\ / i i\\ d / L_0\\\n\ |A + B |*-----|C |\n\ \\ / L_0\\ /\n\ dD \n\ \ """ ucode_str = \ u("""\ ⎛ i i⎞ ∂ ⎛ L₀⎞\n\ ⎜A + B ⎟⋅────⎜C ⎟\n\ ⎝ ⎠ L₀⎝ ⎠\n\ ∂D \n\ \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = (A(i) + B(i))*PartialDerivative(C(-i), D(j)) ascii_str = \ """\ / L_0 L_0\\ d / \\\n\ |A + B |*---|C |\n\ \\ / j\\ L_0/\n\ dD \n\ \ """ ucode_str = \ u("""\ ⎛ L₀ L₀⎞ ∂ ⎛ ⎞\n\ ⎜A + B ⎟⋅───⎜C ⎟\n\ ⎝ ⎠ j⎝ L₀⎠\n\ ∂D \n\ \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = PartialDerivative(B(-i) + A(-i), A(-j), A(-n)) ucode_str = u("""\ 2 \n\ ∂ ⎛ ⎞\n\ ───────⎜A + B ⎟\n\ ⎝ i i⎠\n\ ∂A ∂A \n\ n j \ """) assert upretty(expr) == ucode_str expr = PartialDerivative(3*A(-i), A(-j), A(-n)) ucode_str = u("""\ 2 \n\ ∂ ⎛ ⎞\n\ ───────⎜3⋅A ⎟\n\ ⎝ i⎠\n\ ∂A ∂A \n\ n j \ """) assert upretty(expr) == ucode_str expr = TensorElement(H(i, j), {i:1}) ascii_str = \ """\ i=1,j\n\ H \n\ \ """ ucode_str = ascii_str assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = TensorElement(H(i, j), {i: 1, j: 1}) ascii_str = \ """\ i=1,j=1\n\ H \n\ \ """ ucode_str = ascii_str assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = TensorElement(H(i, j), {j: 1}) ascii_str = \ """\ i,j=1\n\ H \n\ \ """ ucode_str = ascii_str expr = TensorElement(H(-i, j), {-i: 1}) ascii_str = \ """\ j\n\ H \n\ i=1 \ """ ucode_str = ascii_str assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_issue_15560(): a = MatrixSymbol('a', 1, 1) e = pretty(a*(KroneckerProduct(a, a))) result = 'a*(a x a)' assert e == result def test_print_lerchphi(): # Part of issue 6013 a = Symbol('a') pretty(lerchphi(a, 1, 2)) uresult = u'Φ(a, 1, 2)' aresult = 'lerchphi(a, 1, 2)' assert pretty(lerchphi(a, 1, 2)) == aresult assert upretty(lerchphi(a, 1, 2)) == uresult def test_issue_15583(): N = mechanics.ReferenceFrame('N') result = '(n_x, n_y, n_z)' e = pretty((N.x, N.y, N.z)) assert e == result def test_matrixSymbolBold(): # Issue 15871 def boldpretty(expr): return xpretty(expr, use_unicode=True, wrap_line=False, mat_symbol_style="bold") from sympy import trace A = MatrixSymbol("A", 2, 2) assert boldpretty(trace(A)) == u'tr(𝐀)' A = MatrixSymbol("A", 3, 3) B = MatrixSymbol("B", 3, 3) C = MatrixSymbol("C", 3, 3) assert boldpretty(-A) == u'-𝐀' assert boldpretty(A - A*B - B) == u'-𝐁 -𝐀⋅𝐁 + 𝐀' assert boldpretty(-A*B - A*B*C - B) == u'-𝐁 -𝐀⋅𝐁 -𝐀⋅𝐁⋅𝐂' A = MatrixSymbol("Addot", 3, 3) assert boldpretty(A) == u'𝐀̈' omega = MatrixSymbol("omega", 3, 3) assert boldpretty(omega) == u'ω' omega = MatrixSymbol("omeganorm", 3, 3) assert boldpretty(omega) == u'‖ω‖' a = Symbol('alpha') b = Symbol('b') c = MatrixSymbol("c", 3, 1) d = MatrixSymbol("d", 3, 1) assert boldpretty(a*B*c+b*d) == u'b⋅𝐝 + α⋅𝐁⋅𝐜' d = MatrixSymbol("delta", 3, 1) B = MatrixSymbol("Beta", 3, 3) assert boldpretty(a*B*c+b*d) == u'b⋅δ + α⋅Β⋅𝐜' A = MatrixSymbol("A_2", 3, 3) assert boldpretty(A) == u'𝐀₂' def test_center_accent(): assert center_accent('a', u'\N{COMBINING TILDE}') == u'ã' assert center_accent('aa', u'\N{COMBINING TILDE}') == u'aã' assert center_accent('aaa', u'\N{COMBINING TILDE}') == u'aãa' assert center_accent('aaaa', u'\N{COMBINING TILDE}') == u'aaãa' assert center_accent('aaaaa', u'\N{COMBINING TILDE}') == u'aaãaa' assert center_accent('abcdefg', u'\N{COMBINING FOUR DOTS ABOVE}') == u'abcd⃜efg' def test_imaginary_unit(): from sympy import pretty # As it is redefined above assert pretty(1 + I, use_unicode=False) == '1 + I' assert pretty(1 + I, use_unicode=True) == u'1 + ⅈ' assert pretty(1 + I, use_unicode=False, imaginary_unit='j') == '1 + I' assert pretty(1 + I, use_unicode=True, imaginary_unit='j') == u'1 + ⅉ' raises(TypeError, lambda: pretty(I, imaginary_unit=I)) raises(ValueError, lambda: pretty(I, imaginary_unit="kkk")) def test_str_special_matrices(): from sympy.matrices import Identity, ZeroMatrix, OneMatrix assert pretty(Identity(4)) == 'I' assert upretty(Identity(4)) == u'𝕀' assert pretty(ZeroMatrix(2, 2)) == '0' assert upretty(ZeroMatrix(2, 2)) == u'𝟘' assert pretty(OneMatrix(2, 2)) == '1' assert upretty(OneMatrix(2, 2)) == u'𝟙' def test_pretty_misc_functions(): assert pretty(LambertW(x)) == 'W(x)' assert upretty(LambertW(x)) == u'W(x)' assert pretty(LambertW(x, y)) == 'W(x, y)' assert upretty(LambertW(x, y)) == u'W(x, y)' assert pretty(airyai(x)) == 'Ai(x)' assert upretty(airyai(x)) == u'Ai(x)' assert pretty(airybi(x)) == 'Bi(x)' assert upretty(airybi(x)) == u'Bi(x)' assert pretty(airyaiprime(x)) == "Ai'(x)" assert upretty(airyaiprime(x)) == u"Ai'(x)" assert pretty(airybiprime(x)) == "Bi'(x)" assert upretty(airybiprime(x)) == u"Bi'(x)" assert pretty(fresnelc(x)) == 'C(x)' assert upretty(fresnelc(x)) == u'C(x)' assert pretty(fresnels(x)) == 'S(x)' assert upretty(fresnels(x)) == u'S(x)' assert pretty(Heaviside(x)) == 'Heaviside(x)' assert upretty(Heaviside(x)) == u'θ(x)' assert pretty(Heaviside(x, y)) == 'Heaviside(x, y)' assert upretty(Heaviside(x, y)) == u'θ(x, y)' assert pretty(dirichlet_eta(x)) == 'dirichlet_eta(x)' assert upretty(dirichlet_eta(x)) == u'η(x)' def test_hadamard_power(): m, n, p = symbols('m, n, p', integer=True) A = MatrixSymbol('A', m, n) B = MatrixSymbol('B', m, n) # Testing printer: expr = hadamard_power(A, n) ascii_str = \ """\ .n\n\ A \ """ ucode_str = \ u("""\ ∘n\n\ A \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = hadamard_power(A, 1+n) ascii_str = \ """\ .(n + 1)\n\ A \ """ ucode_str = \ u("""\ ∘(n + 1)\n\ A \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = hadamard_power(A*B.T, 1+n) ascii_str = \ """\ .(n + 1)\n\ / T\\ \n\ \\A*B / \ """ ucode_str = \ u("""\ ∘(n + 1)\n\ ⎛ T⎞ \n\ ⎝A⋅B ⎠ \ """) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_issue_17258(): n = Symbol('n', integer=True) assert pretty(Sum(n, (n, -oo, 1))) == \ ' 1 \n'\ ' __ \n'\ ' \\ ` \n'\ ' ) n\n'\ ' /_, \n'\ 'n = -oo ' assert upretty(Sum(n, (n, -oo, 1))) == \ u("""\ 1 \n\ ___ \n\ ╲ \n\ ╲ \n\ ╱ n\n\ ╱ \n\ ‾‾‾ \n\ n = -∞ \ """) def test_is_combining(): line = u("v̇_m") assert [is_combining(sym) for sym in line] == \ [False, True, False, False] def test_issue_17857(): assert pretty(Range(-oo, oo)) == '{..., -1, 0, 1, ...}' assert pretty(Range(oo, -oo, -1)) == '{..., 1, 0, -1, ...}' def test_issue_18272(): x = Symbol('x') n = Symbol('n') assert upretty(ConditionSet(x, Eq(-x + exp(x), 0), S.Complexes)) == \ '⎧ ⎛ x ⎞⎫\n'\ '⎨x | x ∊ ℂ ∧ ⎝-x + ℯ = 0⎠⎬\n'\ '⎩ ⎭' assert upretty(ConditionSet(x, Contains(n/2, Interval(0, oo)), FiniteSet(-n/2, n/2))) == \ '⎧ ⎧-n n⎫ ⎛n ⎞⎫\n'\ '⎨x | x ∊ ⎨───, ─⎬ ∧ ⎜─ ∈ [0, ∞)⎟⎬\n'\ '⎩ ⎩ 2 2⎭ ⎝2 ⎠⎭' assert upretty(ConditionSet(x, Eq(Piecewise((1, x >= 3), (x/2 - 1/2, x >= 2), (1/2, x >= 1), (x/2, True)) - 1/2, 0), Interval(0, 3))) == \ '⎧ ⎛⎛⎧ 1 for x ≥ 3⎞ ⎞⎫\n'\ '⎪ ⎜⎜⎪ ⎟ ⎟⎪\n'\ '⎪ ⎜⎜⎪x ⎟ ⎟⎪\n'\ '⎪ ⎜⎜⎪─ - 0.5 for x ≥ 2⎟ ⎟⎪\n'\ '⎪ ⎜⎜⎪2 ⎟ ⎟⎪\n'\ '⎨x | x ∊ [0, 3] ∧ ⎜⎜⎨ ⎟ - 0.5 = 0⎟⎬\n'\ '⎪ ⎜⎜⎪ 0.5 for x ≥ 1⎟ ⎟⎪\n'\ '⎪ ⎜⎜⎪ ⎟ ⎟⎪\n'\ '⎪ ⎜⎜⎪ x ⎟ ⎟⎪\n'\ '⎪ ⎜⎜⎪ ─ otherwise⎟ ⎟⎪\n'\ '⎩ ⎝⎝⎩ 2 ⎠ ⎠⎭'
0edcae3c39edc4b83a566aa5c659afe57aff5880b1a422b28632b64bc0a406ea
from sympy import cos, DiracDelta, Heaviside, Function, pi, S, sin, symbols, Rational from sympy.integrals.deltafunctions import change_mul, deltaintegrate f = Function("f") x_1, x_2, x, y, z = symbols("x_1 x_2 x y z") def test_change_mul(): assert change_mul(x, x) == (None, None) assert change_mul(x*y, x) == (None, None) assert change_mul(x*y*DiracDelta(x), x) == (DiracDelta(x), x*y) assert change_mul(x*y*DiracDelta(x)*DiracDelta(y), x) == \ (DiracDelta(x), x*y*DiracDelta(y)) assert change_mul(DiracDelta(x)**2, x) == \ (DiracDelta(x), DiracDelta(x)) assert change_mul(y*DiracDelta(x)**2, x) == \ (DiracDelta(x), y*DiracDelta(x)) def test_deltaintegrate(): assert deltaintegrate(x, x) is None assert deltaintegrate(x + DiracDelta(x), x) is None assert deltaintegrate(DiracDelta(x, 0), x) == Heaviside(x) for n in range(10): assert deltaintegrate(DiracDelta(x, n + 1), x) == DiracDelta(x, n) assert deltaintegrate(DiracDelta(x), x) == Heaviside(x) assert deltaintegrate(DiracDelta(-x), x) == Heaviside(x) assert deltaintegrate(DiracDelta(x - y), x) == Heaviside(x - y) assert deltaintegrate(DiracDelta(y - x), x) == Heaviside(x - y) assert deltaintegrate(x*DiracDelta(x), x) == 0 assert deltaintegrate((x - y)*DiracDelta(x - y), x) == 0 assert deltaintegrate(DiracDelta(x)**2, x) == DiracDelta(0)*Heaviside(x) assert deltaintegrate(y*DiracDelta(x)**2, x) == \ y*DiracDelta(0)*Heaviside(x) assert deltaintegrate(DiracDelta(x, 1), x) == DiracDelta(x, 0) assert deltaintegrate(y*DiracDelta(x, 1), x) == y*DiracDelta(x, 0) assert deltaintegrate(DiracDelta(x, 1)**2, x) == -DiracDelta(0, 2)*Heaviside(x) assert deltaintegrate(y*DiracDelta(x, 1)**2, x) == -y*DiracDelta(0, 2)*Heaviside(x) assert deltaintegrate(DiracDelta(x) * f(x), x) == f(0) * Heaviside(x) assert deltaintegrate(DiracDelta(-x) * f(x), x) == f(0) * Heaviside(x) assert deltaintegrate(DiracDelta(x - 1) * f(x), x) == f(1) * Heaviside(x - 1) assert deltaintegrate(DiracDelta(1 - x) * f(x), x) == f(1) * Heaviside(x - 1) assert deltaintegrate(DiracDelta(x**2 + x - 2), x) == \ Heaviside(x - 1)/3 + Heaviside(x + 2)/3 p = cos(x)*(DiracDelta(x) + DiracDelta(x**2 - 1))*sin(x)*(x - pi) assert deltaintegrate(p, x) - (-pi*(cos(1)*Heaviside(-1 + x)*sin(1)/2 - \ cos(1)*Heaviside(1 + x)*sin(1)/2) + \ cos(1)*Heaviside(1 + x)*sin(1)/2 + \ cos(1)*Heaviside(-1 + x)*sin(1)/2) == 0 p = x_2*DiracDelta(x - x_2)*DiracDelta(x_2 - x_1) assert deltaintegrate(p, x_2) == x*DiracDelta(x - x_1)*Heaviside(x_2 - x) p = x*y**2*z*DiracDelta(y - x)*DiracDelta(y - z)*DiracDelta(x - z) assert deltaintegrate(p, y) == x**3*z*DiracDelta(x - z)**2*Heaviside(y - x) assert deltaintegrate((x + 1)*DiracDelta(2*x), x) == S.Half * Heaviside(x) assert deltaintegrate((x + 1)*DiracDelta(x*Rational(2, 3) + Rational(4, 9)), x) == \ S.Half * Heaviside(x + Rational(2, 3)) a, b, c = symbols('a b c', commutative=False) assert deltaintegrate(DiracDelta(x - y)*f(x - b)*f(x - a), x) == \ f(y - b)*f(y - a)*Heaviside(x - y) p = f(x - a)*DiracDelta(x - y)*f(x - c)*f(x - b) assert deltaintegrate(p, x) == f(y - a)*f(y - c)*f(y - b)*Heaviside(x - y) p = DiracDelta(x - z)*f(x - b)*f(x - a)*DiracDelta(x - y) assert deltaintegrate(p, x) == DiracDelta(y - z)*f(y - b)*f(y - a) * \ Heaviside(x - y)
a4703b4af738fa6ba59f5cf335a972ce20da3c9ce6220fedd05dc08174e1d742
"""Most of these tests come from the examples in Bronstein's book.""" from sympy import Poly, symbols, oo, I, Rational from sympy.integrals.risch import (DifferentialExtension, NonElementaryIntegralException) from sympy.integrals.rde import (order_at, order_at_oo, weak_normalizer, normal_denom, special_denom, bound_degree, spde, solve_poly_rde, no_cancel_equal, cancel_primitive, cancel_exp, rischDE) from sympy.testing.pytest import raises from sympy.abc import x, t, z, n t0, t1, t2, k = symbols('t:3 k') def test_order_at(): a = Poly(t**4, t) b = Poly((t**2 + 1)**3*t, t) c = Poly((t**2 + 1)**6*t, t) d = Poly((t**2 + 1)**10*t**10, t) e = Poly((t**2 + 1)**100*t**37, t) p1 = Poly(t, t) p2 = Poly(1 + t**2, t) assert order_at(a, p1, t) == 4 assert order_at(b, p1, t) == 1 assert order_at(c, p1, t) == 1 assert order_at(d, p1, t) == 10 assert order_at(e, p1, t) == 37 assert order_at(a, p2, t) == 0 assert order_at(b, p2, t) == 3 assert order_at(c, p2, t) == 6 assert order_at(d, p1, t) == 10 assert order_at(e, p2, t) == 100 assert order_at(Poly(0, t), Poly(t, t), t) is oo assert order_at_oo(Poly(t**2 - 1, t), Poly(t + 1), t) == \ order_at_oo(Poly(t - 1, t), Poly(1, t), t) == -1 assert order_at_oo(Poly(0, t), Poly(1, t), t) is oo def test_weak_normalizer(): a = Poly((1 + x)*t**5 + 4*t**4 + (-1 - 3*x)*t**3 - 4*t**2 + (-2 + 2*x)*t, t) d = Poly(t**4 - 3*t**2 + 2, t) DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t, t)]}) r = weak_normalizer(a, d, DE, z) assert r == (Poly(t**5 - t**4 - 4*t**3 + 4*t**2 + 4*t - 4, t, domain='ZZ[x]'), (Poly((1 + x)*t**2 + x*t, t, domain='ZZ[x]'), Poly(t + 1, t, domain='ZZ[x]'))) assert weak_normalizer(r[1][0], r[1][1], DE) == (Poly(1, t), r[1]) r = weak_normalizer(Poly(1 + t**2), Poly(t**2 - 1, t), DE, z) assert r == (Poly(t**4 - 2*t**2 + 1, t), (Poly(-3*t**2 + 1, t), Poly(t**2 - 1, t))) assert weak_normalizer(r[1][0], r[1][1], DE, z) == (Poly(1, t), r[1]) DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1 + t**2)]}) r = weak_normalizer(Poly(1 + t**2), Poly(t, t), DE, z) assert r == (Poly(t, t), (Poly(0, t), Poly(1, t))) assert weak_normalizer(r[1][0], r[1][1], DE, z) == (Poly(1, t), r[1]) def test_normal_denom(): DE = DifferentialExtension(extension={'D': [Poly(1, x)]}) raises(NonElementaryIntegralException, lambda: normal_denom(Poly(1, x), Poly(1, x), Poly(1, x), Poly(x, x), DE)) fa, fd = Poly(t**2 + 1, t), Poly(1, t) ga, gd = Poly(1, t), Poly(t**2, t) DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t**2 + 1, t)]}) assert normal_denom(fa, fd, ga, gd, DE) == \ (Poly(t, t), (Poly(t**3 - t**2 + t - 1, t), Poly(1, t)), (Poly(1, t), Poly(1, t)), Poly(t, t)) def test_special_denom(): # TODO: add more tests here DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t, t)]}) assert special_denom(Poly(1, t), Poly(t**2, t), Poly(1, t), Poly(t**2 - 1, t), Poly(t, t), DE) == \ (Poly(1, t), Poly(t**2 - 1, t), Poly(t**2 - 1, t), Poly(t, t)) # assert special_denom(Poly(1, t), Poly(2*x, t), Poly((1 + 2*x)*t, t), DE) == 1 # issue 3940 # Note, this isn't a very good test, because the denominator is just 1, # but at least it tests the exp cancellation case DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(-2*x*t0, t0), Poly(I*k*t1, t1)]}) DE.decrement_level() assert special_denom(Poly(1, t0), Poly(I*k, t0), Poly(1, t0), Poly(t0, t0), Poly(1, t0), DE) == \ (Poly(1, t0), Poly(I*k, t0), Poly(t0, t0), Poly(1, t0)) assert special_denom(Poly(1, t), Poly(t**2, t), Poly(1, t), Poly(t**2 - 1, t), Poly(t, t), DE, case='tan') == \ (Poly(1, t, t0, domain='ZZ'), Poly(t**2, t0, t, domain='ZZ[x]'), Poly(t, t, t0, domain='ZZ'), Poly(1, t0, domain='ZZ')) raises(ValueError, lambda: special_denom(Poly(1, t), Poly(t**2, t), Poly(1, t), Poly(t**2 - 1, t), Poly(t, t), DE, case='unrecognized_case')) def test_bound_degree_fail(): # Primitive DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t0/x**2, t0), Poly(1/x, t)]}) assert bound_degree(Poly(t**2, t), Poly(-(1/x**2*t**2 + 1/x), t), Poly((2*x - 1)*t**4 + (t0 + x)/x*t**3 - (t0 + 4*x**2)/2*x*t**2 + x*t, t), DE) == 3 def test_bound_degree(): # Base DE = DifferentialExtension(extension={'D': [Poly(1, x)]}) assert bound_degree(Poly(1, x), Poly(-2*x, x), Poly(1, x), DE) == 0 # Primitive (see above test_bound_degree_fail) # TODO: Add test for when the degree bound becomes larger after limited_integrate # TODO: Add test for db == da - 1 case # Exp # TODO: Add tests # TODO: Add test for when the degree becomes larger after parametric_log_deriv() # Nonlinear DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t**2 + 1, t)]}) assert bound_degree(Poly(t, t), Poly((t - 1)*(t**2 + 1), t), Poly(1, t), DE) == 0 def test_spde(): DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t**2 + 1, t)]}) raises(NonElementaryIntegralException, lambda: spde(Poly(t, t), Poly((t - 1)*(t**2 + 1), t), Poly(1, t), 0, DE)) DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t, t)]}) assert spde(Poly(t**2 + x*t*2 + x**2, t), Poly(t**2/x**2 + (2/x - 1)*t, t), Poly(t**2/x**2 + (2/x - 1)*t, t), 0, DE) == \ (Poly(0, t), Poly(0, t), 0, Poly(0, t), Poly(1, t, domain='ZZ(x)')) DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t0/x**2, t0), Poly(1/x, t)]}) assert spde(Poly(t**2, t), Poly(-t**2/x**2 - 1/x, t), Poly((2*x - 1)*t**4 + (t0 + x)/x*t**3 - (t0 + 4*x**2)/(2*x)*t**2 + x*t, t), 3, DE) == \ (Poly(0, t), Poly(0, t), 0, Poly(0, t), Poly(t0*t**2/2 + x**2*t**2 - x**2*t, t, domain='ZZ(x,t0)')) DE = DifferentialExtension(extension={'D': [Poly(1, x)]}) assert spde(Poly(x**2 + x + 1, x), Poly(-2*x - 1, x), Poly(x**5/2 + 3*x**4/4 + x**3 - x**2 + 1, x), 4, DE) == \ (Poly(0, x, domain='QQ'), Poly(x/2 - Rational(1, 4), x), 2, Poly(x**2 + x + 1, x), Poly(x*Rational(5, 4), x)) assert spde(Poly(x**2 + x + 1, x), Poly(-2*x - 1, x), Poly(x**5/2 + 3*x**4/4 + x**3 - x**2 + 1, x), n, DE) == \ (Poly(0, x, domain='QQ'), Poly(x/2 - Rational(1, 4), x), -2 + n, Poly(x**2 + x + 1, x), Poly(x*Rational(5, 4), x)) DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1, t)]}) raises(NonElementaryIntegralException, lambda: spde(Poly((t - 1)*(t**2 + 1)**2, t), Poly((t - 1)*(t**2 + 1), t), Poly(1, t), 0, DE)) DE = DifferentialExtension(extension={'D': [Poly(1, x)]}) assert spde(Poly(x**2 - x, x), Poly(1, x), Poly(9*x**4 - 10*x**3 + 2*x**2, x), 4, DE) == \ (Poly(0, x, domain='ZZ'), Poly(0, x), 0, Poly(0, x), Poly(3*x**3 - 2*x**2, x, domain='QQ')) assert spde(Poly(x**2 - x, x), Poly(x**2 - 5*x + 3, x), Poly(x**7 - x**6 - 2*x**4 + 3*x**3 - x**2, x), 5, DE) == \ (Poly(1, x, domain='QQ'), Poly(x + 1, x, domain='QQ'), 1, Poly(x**4 - x**3, x), Poly(x**3 - x**2, x, domain='QQ')) def test_solve_poly_rde_no_cancel(): # deg(b) large DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1 + t**2, t)]}) assert solve_poly_rde(Poly(t**2 + 1, t), Poly(t**3 + (x + 1)*t**2 + t + x + 2, t), oo, DE) == Poly(t + x, t) # deg(b) small DE = DifferentialExtension(extension={'D': [Poly(1, x)]}) assert solve_poly_rde(Poly(0, x), Poly(x/2 - Rational(1, 4), x), oo, DE) == \ Poly(x**2/4 - x/4, x) DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t**2 + 1, t)]}) assert solve_poly_rde(Poly(2, t), Poly(t**2 + 2*t + 3, t), 1, DE) == \ Poly(t + 1, t, x) # deg(b) == deg(D) - 1 DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t**2 + 1, t)]}) assert no_cancel_equal(Poly(1 - t, t), Poly(t**3 + t**2 - 2*x*t - 2*x, t), oo, DE) == \ (Poly(t**2, t), 1, Poly((-2 - 2*x)*t - 2*x, t)) def test_solve_poly_rde_cancel(): # exp DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t, t)]}) assert cancel_exp(Poly(2*x, t), Poly(2*x, t), 0, DE) == \ Poly(1, t) assert cancel_exp(Poly(2*x, t), Poly((1 + 2*x)*t, t), 1, DE) == \ Poly(t, t) # TODO: Add more exp tests, including tests that require is_deriv_in_field() # primitive DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1/x, t)]}) # If the DecrementLevel context manager is working correctly, this shouldn't # cause any problems with the further tests. raises(NonElementaryIntegralException, lambda: cancel_primitive(Poly(1, t), Poly(t, t), oo, DE)) assert cancel_primitive(Poly(1, t), Poly(t + 1/x, t), 2, DE) == \ Poly(t, t) assert cancel_primitive(Poly(4*x, t), Poly(4*x*t**2 + 2*t/x, t), 3, DE) == \ Poly(t**2, t) # TODO: Add more primitive tests, including tests that require is_deriv_in_field() def test_rischDE(): # TODO: Add more tests for rischDE, including ones from the text DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t, t)]}) DE.decrement_level() assert rischDE(Poly(-2*x, x), Poly(1, x), Poly(1 - 2*x - 2*x**2, x), Poly(1, x), DE) == \ (Poly(x + 1, x), Poly(1, x))
eb5b48abdd86342dfaad6c726b148e7cdf6f677a2613713e15cd558ff83f4152
from sympy import sqrt, Abs from sympy.core import S, Rational from sympy.integrals.intpoly import (decompose, best_origin, distance_to_side, polytope_integrate, point_sort, hyperplane_parameters, main_integrate3d, main_integrate, polygon_integrate, lineseg_integrate, integration_reduction, integration_reduction_dynamic, is_vertex) from sympy.geometry.line import Segment2D from sympy.geometry.polygon import Polygon from sympy.geometry.point import Point, Point2D from sympy.abc import x, y, z from sympy.testing.pytest import slow def test_decompose(): assert decompose(x) == {1: x} assert decompose(x**2) == {2: x**2} assert decompose(x*y) == {2: x*y} assert decompose(x + y) == {1: x + y} assert decompose(x**2 + y) == {1: y, 2: x**2} assert decompose(8*x**2 + 4*y + 7) == {0: 7, 1: 4*y, 2: 8*x**2} assert decompose(x**2 + 3*y*x) == {2: x**2 + 3*x*y} assert decompose(9*x**2 + y + 4*x + x**3 + y**2*x + 3) ==\ {0: 3, 1: 4*x + y, 2: 9*x**2, 3: x**3 + x*y**2} assert decompose(x, True) == {x} assert decompose(x ** 2, True) == {x**2} assert decompose(x * y, True) == {x * y} assert decompose(x + y, True) == {x, y} assert decompose(x ** 2 + y, True) == {y, x ** 2} assert decompose(8 * x ** 2 + 4 * y + 7, True) == {7, 4*y, 8*x**2} assert decompose(x ** 2 + 3 * y * x, True) == {x ** 2, 3 * x * y} assert decompose(9 * x ** 2 + y + 4 * x + x ** 3 + y ** 2 * x + 3, True) == \ {3, y, 4*x, 9*x**2, x*y**2, x**3} def test_best_origin(): expr1 = y ** 2 * x ** 5 + y ** 5 * x ** 7 + 7 * x + x ** 12 + y ** 7 * x l1 = Segment2D(Point(0, 3), Point(1, 1)) l2 = Segment2D(Point(S(3) / 2, 0), Point(S(3) / 2, 3)) l3 = Segment2D(Point(0, S(3) / 2), Point(3, S(3) / 2)) l4 = Segment2D(Point(0, 2), Point(2, 0)) l5 = Segment2D(Point(0, 2), Point(1, 1)) l6 = Segment2D(Point(2, 0), Point(1, 1)) assert best_origin((2, 1), 3, l1, expr1) == (0, 3) assert best_origin((2, 0), 3, l2, x ** 7) == (S(3) / 2, 0) assert best_origin((0, 2), 3, l3, x ** 7) == (0, S(3) / 2) assert best_origin((1, 1), 2, l4, x ** 7 * y ** 3) == (0, 2) assert best_origin((1, 1), 2, l4, x ** 3 * y ** 7) == (2, 0) assert best_origin((1, 1), 2, l5, x ** 2 * y ** 9) == (0, 2) assert best_origin((1, 1), 2, l6, x ** 9 * y ** 2) == (2, 0) @slow def test_polytope_integrate(): # Convex 2-Polytopes # Vertex representation assert polytope_integrate(Polygon(Point(0, 0), Point(0, 2), Point(4, 0)), 1, dims=(x, y)) == 4 assert polytope_integrate(Polygon(Point(0, 0), Point(0, 1), Point(1, 1), Point(1, 0)), x * y) ==\ Rational(1, 4) assert polytope_integrate(Polygon(Point(0, 3), Point(5, 3), Point(1, 1)), 6*x**2 - 40*y) == Rational(-935, 3) assert polytope_integrate(Polygon(Point(0, 0), Point(0, sqrt(3)), Point(sqrt(3), sqrt(3)), Point(sqrt(3), 0)), 1) == 3 hexagon = Polygon(Point(0, 0), Point(-sqrt(3) / 2, S.Half), Point(-sqrt(3) / 2, S(3) / 2), Point(0, 2), Point(sqrt(3) / 2, S(3) / 2), Point(sqrt(3) / 2, S.Half)) assert polytope_integrate(hexagon, 1) == S(3*sqrt(3)) / 2 # Hyperplane representation assert polytope_integrate([((-1, 0), 0), ((1, 2), 4), ((0, -1), 0)], 1, dims=(x, y)) == 4 assert polytope_integrate([((-1, 0), 0), ((0, 1), 1), ((1, 0), 1), ((0, -1), 0)], x * y) == Rational(1, 4) assert polytope_integrate([((0, 1), 3), ((1, -2), -1), ((-2, -1), -3)], 6*x**2 - 40*y) == Rational(-935, 3) assert polytope_integrate([((-1, 0), 0), ((0, sqrt(3)), 3), ((sqrt(3), 0), 3), ((0, -1), 0)], 1) == 3 hexagon = [((Rational(-1, 2), -sqrt(3) / 2), 0), ((-1, 0), sqrt(3) / 2), ((Rational(-1, 2), sqrt(3) / 2), sqrt(3)), ((S.Half, sqrt(3) / 2), sqrt(3)), ((1, 0), sqrt(3) / 2), ((S.Half, -sqrt(3) / 2), 0)] assert polytope_integrate(hexagon, 1) == S(3*sqrt(3)) / 2 # Non-convex polytopes # Vertex representation assert polytope_integrate(Polygon(Point(-1, -1), Point(-1, 1), Point(1, 1), Point(0, 0), Point(1, -1)), 1) == 3 assert polytope_integrate(Polygon(Point(-1, -1), Point(-1, 1), Point(0, 0), Point(1, 1), Point(1, -1), Point(0, 0)), 1) == 2 # Hyperplane representation assert polytope_integrate([((-1, 0), 1), ((0, 1), 1), ((1, -1), 0), ((1, 1), 0), ((0, -1), 1)], 1) == 3 assert polytope_integrate([((-1, 0), 1), ((1, 1), 0), ((-1, 1), 0), ((1, 0), 1), ((-1, -1), 0), ((1, -1), 0)], 1) == 2 # Tests for 2D polytopes mentioned in Chin et al(Page 10): # http://dilbert.engr.ucdavis.edu/~suku/quadrature/cls-integration.pdf fig1 = Polygon(Point(1.220, -0.827), Point(-1.490, -4.503), Point(-3.766, -1.622), Point(-4.240, -0.091), Point(-3.160, 4), Point(-0.981, 4.447), Point(0.132, 4.027)) assert polytope_integrate(fig1, x**2 + x*y + y**2) ==\ S(2031627344735367)/(8*10**12) fig2 = Polygon(Point(4.561, 2.317), Point(1.491, -1.315), Point(-3.310, -3.164), Point(-4.845, -3.110), Point(-4.569, 1.867)) assert polytope_integrate(fig2, x**2 + x*y + y**2) ==\ S(517091313866043)/(16*10**11) fig3 = Polygon(Point(-2.740, -1.888), Point(-3.292, 4.233), Point(-2.723, -0.697), Point(-0.643, -3.151)) assert polytope_integrate(fig3, x**2 + x*y + y**2) ==\ S(147449361647041)/(8*10**12) fig4 = Polygon(Point(0.211, -4.622), Point(-2.684, 3.851), Point(0.468, 4.879), Point(4.630, -1.325), Point(-0.411, -1.044)) assert polytope_integrate(fig4, x**2 + x*y + y**2) ==\ S(180742845225803)/(10**12) # Tests for many polynomials with maximum degree given(2D case). tri = Polygon(Point(0, 3), Point(5, 3), Point(1, 1)) polys = [] expr1 = x**9*y + x**7*y**3 + 2*x**2*y**8 expr2 = x**6*y**4 + x**5*y**5 + 2*y**10 expr3 = x**10 + x**9*y + x**8*y**2 + x**5*y**5 polys.extend((expr1, expr2, expr3)) result_dict = polytope_integrate(tri, polys, max_degree=10) assert result_dict[expr1] == Rational(615780107, 594) assert result_dict[expr2] == Rational(13062161, 27) assert result_dict[expr3] == Rational(1946257153, 924) # Tests when all integral of all monomials up to a max_degree is to be # calculated. assert polytope_integrate(Polygon(Point(0, 0), Point(0, 1), Point(1, 1), Point(1, 0)), max_degree=4) == {0: 0, 1: 1, x: S.Half, x ** 2 * y ** 2: S.One / 9, x ** 4: S.One / 5, y ** 4: S.One / 5, y: S.Half, x * y ** 2: S.One / 6, y ** 2: S.One / 3, x ** 3: S.One / 4, x ** 2 * y: S.One / 6, x ** 3 * y: S.One / 8, x * y: S.One / 4, y ** 3: S.One / 4, x ** 2: S.One / 3, x * y ** 3: S.One / 8} # Tests for 3D polytopes cube1 = [[(0, 0, 0), (0, 6, 6), (6, 6, 6), (3, 6, 0), (0, 6, 0), (6, 0, 6), (3, 0, 0), (0, 0, 6)], [1, 2, 3, 4], [3, 2, 5, 6], [1, 7, 5, 2], [0, 6, 5, 7], [1, 4, 0, 7], [0, 4, 3, 6]] assert polytope_integrate(cube1, 1) == S(162) # 3D Test cases in Chin et al(2015) cube2 = [[(0, 0, 0), (0, 0, 5), (0, 5, 0), (0, 5, 5), (5, 0, 0), (5, 0, 5), (5, 5, 0), (5, 5, 5)], [3, 7, 6, 2], [1, 5, 7, 3], [5, 4, 6, 7], [0, 4, 5, 1], [2, 0, 1, 3], [2, 6, 4, 0]] cube3 = [[(0, 0, 0), (5, 0, 0), (5, 4, 0), (3, 2, 0), (3, 5, 0), (0, 5, 0), (0, 0, 5), (5, 0, 5), (5, 4, 5), (3, 2, 5), (3, 5, 5), (0, 5, 5)], [6, 11, 5, 0], [1, 7, 6, 0], [5, 4, 3, 2, 1, 0], [11, 10, 4, 5], [10, 9, 3, 4], [9, 8, 2, 3], [8, 7, 1, 2], [7, 8, 9, 10, 11, 6]] cube4 = [[(0, 0, 0), (1, 0, 0), (0, 1, 0), (0, 0, 1), (S.One / 4, S.One / 4, S.One / 4)], [0, 2, 1], [1, 3, 0], [4, 2, 3], [4, 3, 1], [0, 1, 2], [2, 4, 1], [0, 3, 2]] assert polytope_integrate(cube2, x ** 2 + y ** 2 + x * y + z ** 2) ==\ Rational(15625, 4) assert polytope_integrate(cube3, x ** 2 + y ** 2 + x * y + z ** 2) ==\ S(33835) / 12 assert polytope_integrate(cube4, x ** 2 + y ** 2 + x * y + z ** 2) ==\ S(37) / 960 # Test cases from Mathematica's PolyhedronData library octahedron = [[(S.NegativeOne / sqrt(2), 0, 0), (0, S.One / sqrt(2), 0), (0, 0, S.NegativeOne / sqrt(2)), (0, 0, S.One / sqrt(2)), (0, S.NegativeOne / sqrt(2), 0), (S.One / sqrt(2), 0, 0)], [3, 4, 5], [3, 5, 1], [3, 1, 0], [3, 0, 4], [4, 0, 2], [4, 2, 5], [2, 0, 1], [5, 2, 1]] assert polytope_integrate(octahedron, 1) == sqrt(2) / 3 great_stellated_dodecahedron =\ [[(-0.32491969623290634095, 0, 0.42532540417601993887), (0.32491969623290634095, 0, -0.42532540417601993887), (-0.52573111211913359231, 0, 0.10040570794311363956), (0.52573111211913359231, 0, -0.10040570794311363956), (-0.10040570794311363956, -0.3090169943749474241, 0.42532540417601993887), (-0.10040570794311363956, 0.30901699437494742410, 0.42532540417601993887), (0.10040570794311363956, -0.3090169943749474241, -0.42532540417601993887), (0.10040570794311363956, 0.30901699437494742410, -0.42532540417601993887), (-0.16245984811645317047, -0.5, 0.10040570794311363956), (-0.16245984811645317047, 0.5, 0.10040570794311363956), (0.16245984811645317047, -0.5, -0.10040570794311363956), (0.16245984811645317047, 0.5, -0.10040570794311363956), (-0.42532540417601993887, -0.3090169943749474241, -0.10040570794311363956), (-0.42532540417601993887, 0.30901699437494742410, -0.10040570794311363956), (-0.26286555605956679615, 0.1909830056250525759, -0.42532540417601993887), (-0.26286555605956679615, -0.1909830056250525759, -0.42532540417601993887), (0.26286555605956679615, 0.1909830056250525759, 0.42532540417601993887), (0.26286555605956679615, -0.1909830056250525759, 0.42532540417601993887), (0.42532540417601993887, -0.3090169943749474241, 0.10040570794311363956), (0.42532540417601993887, 0.30901699437494742410, 0.10040570794311363956)], [12, 3, 0, 6, 16], [17, 7, 0, 3, 13], [9, 6, 0, 7, 8], [18, 2, 1, 4, 14], [15, 5, 1, 2, 19], [11, 4, 1, 5, 10], [8, 19, 2, 18, 9], [10, 13, 3, 12, 11], [16, 14, 4, 11, 12], [13, 10, 5, 15, 17], [14, 16, 6, 9, 18], [19, 8, 7, 17, 15]] # Actual volume is : 0.163118960624632 assert Abs(polytope_integrate(great_stellated_dodecahedron, 1) -\ 0.163118960624632) < 1e-12 expr = x **2 + y ** 2 + z ** 2 octahedron_five_compound = [[(0, -0.7071067811865475244, 0), (0, 0.70710678118654752440, 0), (0.1148764602736805918, -0.35355339059327376220, -0.60150095500754567366), (0.1148764602736805918, 0.35355339059327376220, -0.60150095500754567366), (0.18587401723009224507, -0.57206140281768429760, 0.37174803446018449013), (0.18587401723009224507, 0.57206140281768429760, 0.37174803446018449013), (0.30075047750377283683, -0.21850801222441053540, 0.60150095500754567366), (0.30075047750377283683, 0.21850801222441053540, 0.60150095500754567366), (0.48662449473386508189, -0.35355339059327376220, -0.37174803446018449013), (0.48662449473386508189, 0.35355339059327376220, -0.37174803446018449013), (-0.60150095500754567366, 0, -0.37174803446018449013), (-0.30075047750377283683, -0.21850801222441053540, -0.60150095500754567366), (-0.30075047750377283683, 0.21850801222441053540, -0.60150095500754567366), (0.60150095500754567366, 0, 0.37174803446018449013), (0.4156269377774534286, -0.57206140281768429760, 0), (0.4156269377774534286, 0.57206140281768429760, 0), (0.37174803446018449013, 0, -0.60150095500754567366), (-0.4156269377774534286, -0.57206140281768429760, 0), (-0.4156269377774534286, 0.57206140281768429760, 0), (-0.67249851196395732696, -0.21850801222441053540, 0), (-0.67249851196395732696, 0.21850801222441053540, 0), (0.67249851196395732696, -0.21850801222441053540, 0), (0.67249851196395732696, 0.21850801222441053540, 0), (-0.37174803446018449013, 0, 0.60150095500754567366), (-0.48662449473386508189, -0.35355339059327376220, 0.37174803446018449013), (-0.48662449473386508189, 0.35355339059327376220, 0.37174803446018449013), (-0.18587401723009224507, -0.57206140281768429760, -0.37174803446018449013), (-0.18587401723009224507, 0.57206140281768429760, -0.37174803446018449013), (-0.11487646027368059176, -0.35355339059327376220, 0.60150095500754567366), (-0.11487646027368059176, 0.35355339059327376220, 0.60150095500754567366)], [0, 10, 16], [23, 10, 0], [16, 13, 0], [0, 13, 23], [16, 10, 1], [1, 10, 23], [1, 13, 16], [23, 13, 1], [2, 4, 19], [22, 4, 2], [2, 19, 27], [27, 22, 2], [20, 5, 3], [3, 5, 21], [26, 20, 3], [3, 21, 26], [29, 19, 4], [4, 22, 29], [5, 20, 28], [28, 21, 5], [6, 8, 15], [17, 8, 6], [6, 15, 25], [25, 17, 6], [14, 9, 7], [7, 9, 18], [24, 14, 7], [7, 18, 24], [8, 12, 15], [17, 12, 8], [14, 11, 9], [9, 11, 18], [11, 14, 24], [24, 18, 11], [25, 15, 12], [12, 17, 25], [29, 27, 19], [20, 26, 28], [28, 26, 21], [22, 27, 29]] assert Abs(polytope_integrate(octahedron_five_compound, expr)) - 0.353553\ < 1e-6 cube_five_compound = [[(-0.1624598481164531631, -0.5, -0.6881909602355867691), (-0.1624598481164531631, 0.5, -0.6881909602355867691), (0.1624598481164531631, -0.5, 0.68819096023558676910), (0.1624598481164531631, 0.5, 0.68819096023558676910), (-0.52573111211913359231, 0, -0.6881909602355867691), (0.52573111211913359231, 0, 0.68819096023558676910), (-0.26286555605956679615, -0.8090169943749474241, -0.1624598481164531631), (-0.26286555605956679615, 0.8090169943749474241, -0.1624598481164531631), (0.26286555605956680301, -0.8090169943749474241, 0.1624598481164531631), (0.26286555605956680301, 0.8090169943749474241, 0.1624598481164531631), (-0.42532540417601993887, -0.3090169943749474241, 0.68819096023558676910), (-0.42532540417601993887, 0.30901699437494742410, 0.68819096023558676910), (0.42532540417601996609, -0.3090169943749474241, -0.6881909602355867691), (0.42532540417601996609, 0.30901699437494742410, -0.6881909602355867691), (-0.6881909602355867691, -0.5, 0.1624598481164531631), (-0.6881909602355867691, 0.5, 0.1624598481164531631), (0.68819096023558676910, -0.5, -0.1624598481164531631), (0.68819096023558676910, 0.5, -0.1624598481164531631), (-0.85065080835203998877, 0, -0.1624598481164531631), (0.85065080835203993218, 0, 0.1624598481164531631)], [18, 10, 3, 7], [13, 19, 8, 0], [18, 0, 8, 10], [3, 19, 13, 7], [18, 7, 13, 0], [8, 19, 3, 10], [6, 2, 11, 18], [1, 9, 19, 12], [11, 9, 1, 18], [6, 12, 19, 2], [1, 12, 6, 18], [11, 2, 19, 9], [4, 14, 11, 7], [17, 5, 8, 12], [4, 12, 8, 14], [11, 5, 17, 7], [4, 7, 17, 12], [8, 5, 11, 14], [6, 10, 15, 4], [13, 9, 5, 16], [15, 9, 13, 4], [6, 16, 5, 10], [13, 16, 6, 4], [15, 10, 5, 9], [14, 15, 1, 0], [16, 17, 3, 2], [14, 2, 3, 15], [1, 17, 16, 0], [14, 0, 16, 2], [3, 17, 1, 15]] assert Abs(polytope_integrate(cube_five_compound, expr) - 1.25) < 1e-12 echidnahedron = [[(0, 0, -2.4898982848827801995), (0, 0, 2.4898982848827802734), (0, -4.2360679774997896964, -2.4898982848827801995), (0, -4.2360679774997896964, 2.4898982848827802734), (0, 4.2360679774997896964, -2.4898982848827801995), (0, 4.2360679774997896964, 2.4898982848827802734), (-4.0287400534704067567, -1.3090169943749474241, -2.4898982848827801995), (-4.0287400534704067567, -1.3090169943749474241, 2.4898982848827802734), (-4.0287400534704067567, 1.3090169943749474241, -2.4898982848827801995), (-4.0287400534704067567, 1.3090169943749474241, 2.4898982848827802734), (4.0287400534704069747, -1.3090169943749474241, -2.4898982848827801995), (4.0287400534704069747, -1.3090169943749474241, 2.4898982848827802734), (4.0287400534704069747, 1.3090169943749474241, -2.4898982848827801995), (4.0287400534704069747, 1.3090169943749474241, 2.4898982848827802734), (-2.4898982848827801995, -3.4270509831248422723, -2.4898982848827801995), (-2.4898982848827801995, -3.4270509831248422723, 2.4898982848827802734), (-2.4898982848827801995, 3.4270509831248422723, -2.4898982848827801995), (-2.4898982848827801995, 3.4270509831248422723, 2.4898982848827802734), (2.4898982848827802734, -3.4270509831248422723, -2.4898982848827801995), (2.4898982848827802734, -3.4270509831248422723, 2.4898982848827802734), (2.4898982848827802734, 3.4270509831248422723, -2.4898982848827801995), (2.4898982848827802734, 3.4270509831248422723, 2.4898982848827802734), (-4.7169310137059934362, -0.8090169943749474241, -1.1135163644116066184), (-4.7169310137059934362, 0.8090169943749474241, -1.1135163644116066184), (4.7169310137059937438, -0.8090169943749474241, 1.11351636441160673519), (4.7169310137059937438, 0.8090169943749474241, 1.11351636441160673519), (-4.2916056095299737777, -2.1180339887498948482, 1.11351636441160673519), (-4.2916056095299737777, 2.1180339887498948482, 1.11351636441160673519), (4.2916056095299737777, -2.1180339887498948482, -1.1135163644116066184), (4.2916056095299737777, 2.1180339887498948482, -1.1135163644116066184), (-3.6034146492943870399, 0, -3.3405490932348205213), (3.6034146492943870399, 0, 3.3405490932348202056), (-3.3405490932348205213, -3.4270509831248422723, 1.11351636441160673519), (-3.3405490932348205213, 3.4270509831248422723, 1.11351636441160673519), (3.3405490932348202056, -3.4270509831248422723, -1.1135163644116066184), (3.3405490932348202056, 3.4270509831248422723, -1.1135163644116066184), (-2.9152236890588002395, -2.1180339887498948482, 3.3405490932348202056), (-2.9152236890588002395, 2.1180339887498948482, 3.3405490932348202056), (2.9152236890588002395, -2.1180339887498948482, -3.3405490932348205213), (2.9152236890588002395, 2.1180339887498948482, -3.3405490932348205213), (-2.2270327288232132368, 0, -1.1135163644116066184), (-2.2270327288232132368, -4.2360679774997896964, -1.1135163644116066184), (-2.2270327288232132368, 4.2360679774997896964, -1.1135163644116066184), (2.2270327288232134704, 0, 1.11351636441160673519), (2.2270327288232134704, -4.2360679774997896964, 1.11351636441160673519), (2.2270327288232134704, 4.2360679774997896964, 1.11351636441160673519), (-1.8017073246471935200, -1.3090169943749474241, 1.11351636441160673519), (-1.8017073246471935200, 1.3090169943749474241, 1.11351636441160673519), (1.8017073246471935043, -1.3090169943749474241, -1.1135163644116066184), (1.8017073246471935043, 1.3090169943749474241, -1.1135163644116066184), (-1.3763819204711735382, 0, -4.7169310137059934362), (-1.3763819204711735382, 0, 0.26286555605956679615), (1.37638192047117353821, 0, 4.7169310137059937438), (1.37638192047117353821, 0, -0.26286555605956679615), (-1.1135163644116066184, -3.4270509831248422723, -3.3405490932348205213), (-1.1135163644116066184, -0.8090169943749474241, 4.7169310137059937438), (-1.1135163644116066184, -0.8090169943749474241, -0.26286555605956679615), (-1.1135163644116066184, 0.8090169943749474241, 4.7169310137059937438), (-1.1135163644116066184, 0.8090169943749474241, -0.26286555605956679615), (-1.1135163644116066184, 3.4270509831248422723, -3.3405490932348205213), (1.11351636441160673519, -3.4270509831248422723, 3.3405490932348202056), (1.11351636441160673519, -0.8090169943749474241, -4.7169310137059934362), (1.11351636441160673519, -0.8090169943749474241, 0.26286555605956679615), (1.11351636441160673519, 0.8090169943749474241, -4.7169310137059934362), (1.11351636441160673519, 0.8090169943749474241, 0.26286555605956679615), (1.11351636441160673519, 3.4270509831248422723, 3.3405490932348202056), (-0.85065080835203998877, 0, 1.11351636441160673519), (0.85065080835203993218, 0, -1.1135163644116066184), (-0.6881909602355867691, -0.5, -1.1135163644116066184), (-0.6881909602355867691, 0.5, -1.1135163644116066184), (-0.6881909602355867691, -4.7360679774997896964, -1.1135163644116066184), (-0.6881909602355867691, -2.1180339887498948482, -1.1135163644116066184), (-0.6881909602355867691, 2.1180339887498948482, -1.1135163644116066184), (-0.6881909602355867691, 4.7360679774997896964, -1.1135163644116066184), (0.68819096023558676910, -0.5, 1.11351636441160673519), (0.68819096023558676910, 0.5, 1.11351636441160673519), (0.68819096023558676910, -4.7360679774997896964, 1.11351636441160673519), (0.68819096023558676910, -2.1180339887498948482, 1.11351636441160673519), (0.68819096023558676910, 2.1180339887498948482, 1.11351636441160673519), (0.68819096023558676910, 4.7360679774997896964, 1.11351636441160673519), (-0.42532540417601993887, -1.3090169943749474241, -4.7169310137059934362), (-0.42532540417601993887, -1.3090169943749474241, 0.26286555605956679615), (-0.42532540417601993887, 1.3090169943749474241, -4.7169310137059934362), (-0.42532540417601993887, 1.3090169943749474241, 0.26286555605956679615), (-0.26286555605956679615, -0.8090169943749474241, 1.11351636441160673519), (-0.26286555605956679615, 0.8090169943749474241, 1.11351636441160673519), (0.26286555605956679615, -0.8090169943749474241, -1.1135163644116066184), (0.26286555605956679615, 0.8090169943749474241, -1.1135163644116066184), (0.42532540417601996609, -1.3090169943749474241, 4.7169310137059937438), (0.42532540417601996609, -1.3090169943749474241, -0.26286555605956679615), (0.42532540417601996609, 1.3090169943749474241, 4.7169310137059937438), (0.42532540417601996609, 1.3090169943749474241, -0.26286555605956679615)], [9, 66, 47], [44, 62, 77], [20, 91, 49], [33, 47, 83], [3, 77, 84], [12, 49, 53], [36, 84, 66], [28, 53, 62], [73, 83, 91], [15, 84, 46], [25, 64, 43], [16, 58, 72], [26, 46, 51], [11, 43, 74], [4, 72, 91], [60, 74, 84], [35, 91, 64], [23, 51, 58], [19, 74, 77], [79, 83, 78], [6, 56, 40], [76, 77, 81], [21, 78, 75], [8, 40, 58], [31, 75, 74], [42, 58, 83], [41, 81, 56], [13, 75, 43], [27, 51, 47], [2, 89, 71], [24, 43, 62], [17, 47, 85], [14, 71, 56], [65, 85, 75], [22, 56, 51], [34, 62, 89], [5, 85, 78], [32, 81, 46], [10, 53, 48], [45, 78, 64], [7, 46, 66], [18, 48, 89], [37, 66, 85], [70, 89, 81], [29, 64, 53], [88, 74, 1], [38, 67, 48], [42, 83, 72], [57, 1, 85], [34, 48, 62], [59, 72, 87], [19, 62, 74], [63, 87, 67], [17, 85, 83], [52, 75, 1], [39, 87, 49], [22, 51, 40], [55, 1, 66], [29, 49, 64], [30, 40, 69], [13, 64, 75], [82, 69, 87], [7, 66, 51], [90, 85, 1], [59, 69, 72], [70, 81, 71], [88, 1, 84], [73, 72, 83], [54, 71, 68], [5, 83, 85], [50, 68, 69], [3, 84, 81], [57, 66, 1], [30, 68, 40], [28, 62, 48], [52, 1, 74], [23, 40, 51], [38, 48, 86], [9, 51, 66], [80, 86, 68], [11, 74, 62], [55, 84, 1], [54, 86, 71], [35, 64, 49], [90, 1, 75], [41, 71, 81], [39, 49, 67], [15, 81, 84], [61, 67, 86], [21, 75, 64], [24, 53, 43], [50, 69, 0], [37, 85, 47], [31, 43, 75], [61, 0, 67], [27, 47, 58], [10, 67, 53], [8, 58, 69], [90, 75, 85], [45, 91, 78], [80, 68, 0], [36, 66, 46], [65, 78, 85], [63, 0, 87], [32, 46, 56], [20, 87, 91], [14, 56, 68], [57, 85, 66], [33, 58, 47], [61, 86, 0], [60, 84, 77], [37, 47, 66], [82, 0, 69], [44, 77, 89], [16, 69, 58], [18, 89, 86], [55, 66, 84], [26, 56, 46], [63, 67, 0], [31, 74, 43], [36, 46, 84], [50, 0, 68], [25, 43, 53], [6, 68, 56], [12, 53, 67], [88, 84, 74], [76, 89, 77], [82, 87, 0], [65, 75, 78], [60, 77, 74], [80, 0, 86], [79, 78, 91], [2, 86, 89], [4, 91, 87], [52, 74, 75], [21, 64, 78], [18, 86, 48], [23, 58, 40], [5, 78, 83], [28, 48, 53], [6, 40, 68], [25, 53, 64], [54, 68, 86], [33, 83, 58], [17, 83, 47], [12, 67, 49], [41, 56, 71], [9, 47, 51], [35, 49, 91], [2, 71, 86], [79, 91, 83], [38, 86, 67], [26, 51, 56], [7, 51, 46], [4, 87, 72], [34, 89, 48], [15, 46, 81], [42, 72, 58], [10, 48, 67], [27, 58, 51], [39, 67, 87], [76, 81, 89], [3, 81, 77], [8, 69, 40], [29, 53, 49], [19, 77, 62], [22, 40, 56], [20, 49, 87], [32, 56, 81], [59, 87, 69], [24, 62, 53], [11, 62, 43], [14, 68, 71], [73, 91, 72], [13, 43, 64], [70, 71, 89], [16, 72, 69], [44, 89, 62], [30, 69, 68], [45, 64, 91]] # Actual volume is : 51.405764746872634 assert Abs(polytope_integrate(echidnahedron, 1) - 51.4057647468726) < 1e-12 assert Abs(polytope_integrate(echidnahedron, expr) - 253.569603474519) <\ 1e-12 # Tests for many polynomials with maximum degree given(2D case). assert polytope_integrate(cube2, [x**2, y*z], max_degree=2) == \ {y * z: 3125 / S(4), x ** 2: 3125 / S(3)} assert polytope_integrate(cube2, max_degree=2) == \ {1: 125, x: 625 / S(2), x * z: 3125 / S(4), y: 625 / S(2), y * z: 3125 / S(4), z ** 2: 3125 / S(3), y ** 2: 3125 / S(3), z: 625 / S(2), x * y: 3125 / S(4), x ** 2: 3125 / S(3)} def test_point_sort(): assert point_sort([Point(0, 0), Point(1, 0), Point(1, 1)]) == \ [Point2D(1, 1), Point2D(1, 0), Point2D(0, 0)] fig6 = Polygon((0, 0), (1, 0), (1, 1)) assert polytope_integrate(fig6, x*y) == Rational(-1, 8) assert polytope_integrate(fig6, x*y, clockwise = True) == Rational(1, 8) def test_polytopes_intersecting_sides(): fig5 = Polygon(Point(-4.165, -0.832), Point(-3.668, 1.568), Point(-3.266, 1.279), Point(-1.090, -2.080), Point(3.313, -0.683), Point(3.033, -4.845), Point(-4.395, 4.840), Point(-1.007, -3.328)) assert polytope_integrate(fig5, x**2 + x*y + y**2) ==\ S(1633405224899363)/(24*10**12) fig6 = Polygon(Point(-3.018, -4.473), Point(-0.103, 2.378), Point(-1.605, -2.308), Point(4.516, -0.771), Point(4.203, 0.478)) assert polytope_integrate(fig6, x**2 + x*y + y**2) ==\ S(88161333955921)/(3*10**12) def test_max_degree(): polygon = Polygon((0, 0), (0, 1), (1, 1), (1, 0)) polys = [1, x, y, x*y, x**2*y, x*y**2] assert polytope_integrate(polygon, polys, max_degree=3) == \ {1: 1, x: S.Half, y: S.Half, x*y: Rational(1, 4), x**2*y: Rational(1, 6), x*y**2: Rational(1, 6)} def test_main_integrate3d(): cube = [[(0, 0, 0), (0, 0, 5), (0, 5, 0), (0, 5, 5), (5, 0, 0),\ (5, 0, 5), (5, 5, 0), (5, 5, 5)],\ [2, 6, 7, 3], [3, 7, 5, 1], [7, 6, 4, 5], [1, 5, 4, 0],\ [3, 1, 0, 2], [0, 4, 6, 2]] vertices = cube[0] faces = cube[1:] hp_params = hyperplane_parameters(faces, vertices) assert main_integrate3d(1, faces, vertices, hp_params) == -125 assert main_integrate3d(1, faces, vertices, hp_params, max_degree=1) == \ {1: -125, y: Rational(-625, 2), z: Rational(-625, 2), x: Rational(-625, 2)} def test_main_integrate(): triangle = Polygon((0, 3), (5, 3), (1, 1)) facets = triangle.sides hp_params = hyperplane_parameters(triangle) assert main_integrate(x**2 + y**2, facets, hp_params) == Rational(325, 6) assert main_integrate(x**2 + y**2, facets, hp_params, max_degree=1) == \ {0: 0, 1: 5, y: Rational(35, 3), x: 10} def test_polygon_integrate(): cube = [[(0, 0, 0), (0, 0, 5), (0, 5, 0), (0, 5, 5), (5, 0, 0),\ (5, 0, 5), (5, 5, 0), (5, 5, 5)],\ [2, 6, 7, 3], [3, 7, 5, 1], [7, 6, 4, 5], [1, 5, 4, 0],\ [3, 1, 0, 2], [0, 4, 6, 2]] facet = cube[1] facets = cube[1:] vertices = cube[0] assert polygon_integrate(facet, [(0, 1, 0), 5], 0, facets, vertices, 1, 0) == -25 def test_distance_to_side(): point = (0, 0, 0) assert distance_to_side(point, [(0, 0, 1), (0, 1, 0)], (1, 0, 0)) == -sqrt(2)/2 def test_lineseg_integrate(): polygon = [(0, 5, 0), (5, 5, 0), (5, 5, 5), (0, 5, 5)] line_seg = [(0, 5, 0), (5, 5, 0)] assert lineseg_integrate(polygon, 0, line_seg, 1, 0) == 5 assert lineseg_integrate(polygon, 0, line_seg, 0, 0) == 0 def test_integration_reduction(): triangle = Polygon(Point(0, 3), Point(5, 3), Point(1, 1)) facets = triangle.sides a, b = hyperplane_parameters(triangle)[0] assert integration_reduction(facets, 0, a, b, 1, (x, y), 0) == 5 assert integration_reduction(facets, 0, a, b, 0, (x, y), 0) == 0 def test_integration_reduction_dynamic(): triangle = Polygon(Point(0, 3), Point(5, 3), Point(1, 1)) facets = triangle.sides a, b = hyperplane_parameters(triangle)[0] x0 = facets[0].points[0] monomial_values = [[0, 0, 0, 0], [1, 0, 0, 5],\ [y, 0, 1, 15], [x, 1, 0, None]] assert integration_reduction_dynamic(facets, 0, a, b, x, 1, (x, y), 1,\ 0, 1, x0, monomial_values, 3) == Rational(25, 2) assert integration_reduction_dynamic(facets, 0, a, b, 0, 1, (x, y), 1,\ 0, 1, x0, monomial_values, 3) == 0 def test_is_vertex(): assert is_vertex(2) is False assert is_vertex((2, 3)) is True assert is_vertex(Point(2, 3)) is True assert is_vertex((2, 3, 4)) is True assert is_vertex((2, 3, 4, 5)) is False
2467bf4070f6b92c47c8fa9fd1ca4e044005ef370419a52dec0697850ddba8af
from sympy import Rational, sqrt, symbols, sin, exp, log, sinh, cosh, cos, pi, \ I, erf, tan, asin, asinh, acos, atan, Function, Derivative, diff, simplify, \ LambertW, Ne, Piecewise, Symbol, Add, ratsimp, Integral, Sum, \ besselj, besselk, bessely, jn, tanh from sympy.integrals.heurisch import components, heurisch, heurisch_wrapper from sympy.testing.pytest import XFAIL, skip, slow, ON_TRAVIS from sympy.integrals.integrals import integrate x, y, z, nu = symbols('x,y,z,nu') f = Function('f') def test_components(): assert components(x*y, x) == {x} assert components(1/(x + y), x) == {x} assert components(sin(x), x) == {sin(x), x} assert components(sin(x)*sqrt(log(x)), x) == \ {log(x), sin(x), sqrt(log(x)), x} assert components(x*sin(exp(x)*y), x) == \ {sin(y*exp(x)), x, exp(x)} assert components(x**Rational(17, 54)/sqrt(sin(x)), x) == \ {sin(x), x**Rational(1, 54), sqrt(sin(x)), x} assert components(f(x), x) == \ {x, f(x)} assert components(Derivative(f(x), x), x) == \ {x, f(x), Derivative(f(x), x)} assert components(f(x)*diff(f(x), x), x) == \ {x, f(x), Derivative(f(x), x), Derivative(f(x), x)} def test_issue_10680(): assert isinstance(integrate(x**log(x**log(x**log(x))),x), Integral) def test_heurisch_polynomials(): assert heurisch(1, x) == x assert heurisch(x, x) == x**2/2 assert heurisch(x**17, x) == x**18/18 # For coverage assert heurisch_wrapper(y, x) == y*x def test_heurisch_fractions(): assert heurisch(1/x, x) == log(x) assert heurisch(1/(2 + x), x) == log(x + 2) assert heurisch(1/(x + sin(y)), x) == log(x + sin(y)) # Up to a constant, where C = pi*I*Rational(5, 12), Mathematica gives identical # result in the first case. The difference is because sympy changes # signs of expressions without any care. # XXX ^ ^ ^ is this still correct? assert heurisch(5*x**5/( 2*x**6 - 5), x) in [5*log(2*x**6 - 5) / 12, 5*log(-2*x**6 + 5) / 12] assert heurisch(5*x**5/(2*x**6 + 5), x) == 5*log(2*x**6 + 5) / 12 assert heurisch(1/x**2, x) == -1/x assert heurisch(-1/x**5, x) == 1/(4*x**4) def test_heurisch_log(): assert heurisch(log(x), x) == x*log(x) - x assert heurisch(log(3*x), x) == -x + x*log(3) + x*log(x) assert heurisch(log(x**2), x) in [x*log(x**2) - 2*x, 2*x*log(x) - 2*x] def test_heurisch_exp(): assert heurisch(exp(x), x) == exp(x) assert heurisch(exp(-x), x) == -exp(-x) assert heurisch(exp(17*x), x) == exp(17*x) / 17 assert heurisch(x*exp(x), x) == x*exp(x) - exp(x) assert heurisch(x*exp(x**2), x) == exp(x**2) / 2 assert heurisch(exp(-x**2), x) is None assert heurisch(2**x, x) == 2**x/log(2) assert heurisch(x*2**x, x) == x*2**x/log(2) - 2**x*log(2)**(-2) assert heurisch(Integral(x**z*y, (y, 1, 2), (z, 2, 3)).function, x) == (x*x**z*y)/(z+1) assert heurisch(Sum(x**z, (z, 1, 2)).function, z) == x**z/log(x) def test_heurisch_trigonometric(): assert heurisch(sin(x), x) == -cos(x) assert heurisch(pi*sin(x) + 1, x) == x - pi*cos(x) assert heurisch(cos(x), x) == sin(x) assert heurisch(tan(x), x) in [ log(1 + tan(x)**2)/2, log(tan(x) + I) + I*x, log(tan(x) - I) - I*x, ] assert heurisch(sin(x)*sin(y), x) == -cos(x)*sin(y) assert heurisch(sin(x)*sin(y), y) == -cos(y)*sin(x) # gives sin(x) in answer when run via setup.py and cos(x) when run via py.test assert heurisch(sin(x)*cos(x), x) in [sin(x)**2 / 2, -cos(x)**2 / 2] assert heurisch(cos(x)/sin(x), x) == log(sin(x)) assert heurisch(x*sin(7*x), x) == sin(7*x) / 49 - x*cos(7*x) / 7 assert heurisch(1/pi/4 * x**2*cos(x), x) == 1/pi/4*(x**2*sin(x) - 2*sin(x) + 2*x*cos(x)) assert heurisch(acos(x/4) * asin(x/4), x) == 2*x - (sqrt(16 - x**2))*asin(x/4) \ + (sqrt(16 - x**2))*acos(x/4) + x*asin(x/4)*acos(x/4) assert heurisch(sin(x)/(cos(x)**2+1), x) == -atan(cos(x)) #fixes issue 13723 assert heurisch(1/(cos(x)+2), x) == 2*sqrt(3)*atan(sqrt(3)*tan(x/2)/3)/3 assert heurisch(2*sin(x)*cos(x)/(sin(x)**4 + 1), x) == atan(sqrt(2)*sin(x) - 1) - atan(sqrt(2)*sin(x) + 1) assert heurisch(1/cosh(x), x) == 2*atan(tanh(x/2)) def test_heurisch_hyperbolic(): assert heurisch(sinh(x), x) == cosh(x) assert heurisch(cosh(x), x) == sinh(x) assert heurisch(x*sinh(x), x) == x*cosh(x) - sinh(x) assert heurisch(x*cosh(x), x) == x*sinh(x) - cosh(x) assert heurisch( x*asinh(x/2), x) == x**2*asinh(x/2)/2 + asinh(x/2) - x*sqrt(4 + x**2)/4 def test_heurisch_mixed(): assert heurisch(sin(x)*exp(x), x) == exp(x)*sin(x)/2 - exp(x)*cos(x)/2 def test_heurisch_radicals(): assert heurisch(1/sqrt(x), x) == 2*sqrt(x) assert heurisch(1/sqrt(x)**3, x) == -2/sqrt(x) assert heurisch(sqrt(x)**3, x) == 2*sqrt(x)**5/5 assert heurisch(sin(x)*sqrt(cos(x)), x) == -2*sqrt(cos(x))**3/3 y = Symbol('y') assert heurisch(sin(y*sqrt(x)), x) == 2/y**2*sin(y*sqrt(x)) - \ 2*sqrt(x)*cos(y*sqrt(x))/y assert heurisch_wrapper(sin(y*sqrt(x)), x) == Piecewise( (-2*sqrt(x)*cos(sqrt(x)*y)/y + 2*sin(sqrt(x)*y)/y**2, Ne(y, 0)), (0, True)) y = Symbol('y', positive=True) assert heurisch_wrapper(sin(y*sqrt(x)), x) == 2/y**2*sin(y*sqrt(x)) - \ 2*sqrt(x)*cos(y*sqrt(x))/y def test_heurisch_special(): assert heurisch(erf(x), x) == x*erf(x) + exp(-x**2)/sqrt(pi) assert heurisch(exp(-x**2)*erf(x), x) == sqrt(pi)*erf(x)**2 / 4 def test_heurisch_symbolic_coeffs(): assert heurisch(1/(x + y), x) == log(x + y) assert heurisch(1/(x + sqrt(2)), x) == log(x + sqrt(2)) assert simplify(diff(heurisch(log(x + y + z), y), y)) == log(x + y + z) def test_heurisch_symbolic_coeffs_1130(): y = Symbol('y') assert heurisch_wrapper(1/(x**2 + y), x) == Piecewise( (-I*log(x - I*sqrt(y))/(2*sqrt(y)) + I*log(x + I*sqrt(y))/(2*sqrt(y)), Ne(y, 0)), (-1/x, True)) y = Symbol('y', positive=True) assert heurisch_wrapper(1/(x**2 + y), x) == (atan(x/sqrt(y))/sqrt(y)) def test_heurisch_hacking(): assert heurisch(sqrt(1 + 7*x**2), x, hints=[]) == \ x*sqrt(1 + 7*x**2)/2 + sqrt(7)*asinh(sqrt(7)*x)/14 assert heurisch(sqrt(1 - 7*x**2), x, hints=[]) == \ x*sqrt(1 - 7*x**2)/2 + sqrt(7)*asin(sqrt(7)*x)/14 assert heurisch(1/sqrt(1 + 7*x**2), x, hints=[]) == \ sqrt(7)*asinh(sqrt(7)*x)/7 assert heurisch(1/sqrt(1 - 7*x**2), x, hints=[]) == \ sqrt(7)*asin(sqrt(7)*x)/7 assert heurisch(exp(-7*x**2), x, hints=[]) == \ sqrt(7*pi)*erf(sqrt(7)*x)/14 assert heurisch(1/sqrt(9 - 4*x**2), x, hints=[]) == \ asin(x*Rational(2, 3))/2 assert heurisch(1/sqrt(9 + 4*x**2), x, hints=[]) == \ asinh(x*Rational(2, 3))/2 def test_heurisch_function(): assert heurisch(f(x), x) is None @XFAIL def test_heurisch_function_derivative(): # TODO: it looks like this used to work just by coincindence and # thanks to sloppy implementation. Investigate why this used to # work at all and if support for this can be restored. df = diff(f(x), x) assert heurisch(f(x)*df, x) == f(x)**2/2 assert heurisch(f(x)**2*df, x) == f(x)**3/3 assert heurisch(df/f(x), x) == log(f(x)) def test_heurisch_wrapper(): f = 1/(y + x) assert heurisch_wrapper(f, x) == log(x + y) f = 1/(y - x) assert heurisch_wrapper(f, x) == -log(x - y) f = 1/((y - x)*(y + x)) assert heurisch_wrapper(f, x) == Piecewise( (-log(x - y)/(2*y) + log(x + y)/(2*y), Ne(y, 0)), (1/x, True)) # issue 6926 f = sqrt(x**2/((y - x)*(y + x))) assert heurisch_wrapper(f, x) == x*sqrt(x**2)*sqrt(1/(-x**2 + y**2)) \ - y**2*sqrt(x**2)*sqrt(1/(-x**2 + y**2))/x def test_issue_3609(): assert heurisch(1/(x * (1 + log(x)**2)), x) == atan(log(x)) ### These are examples from the Poor Man's Integrator ### http://www-sop.inria.fr/cafe/Manuel.Bronstein/pmint/examples/ def test_pmint_rat(): # TODO: heurisch() is off by a constant: -3/4. Possibly different permutation # would give the optimal result? def drop_const(expr, x): if expr.is_Add: return Add(*[ arg for arg in expr.args if arg.has(x) ]) else: return expr f = (x**7 - 24*x**4 - 4*x**2 + 8*x - 8)/(x**8 + 6*x**6 + 12*x**4 + 8*x**2) g = (4 + 8*x**2 + 6*x + 3*x**3)/(x**5 + 4*x**3 + 4*x) + log(x) assert drop_const(ratsimp(heurisch(f, x)), x) == g def test_pmint_trig(): f = (x - tan(x)) / tan(x)**2 + tan(x) g = -x**2/2 - x/tan(x) + log(tan(x)**2 + 1)/2 assert heurisch(f, x) == g @slow # 8 seconds on 3.4 GHz def test_pmint_logexp(): if ON_TRAVIS: # See https://github.com/sympy/sympy/pull/12795 skip("Too slow for travis.") f = (1 + x + x*exp(x))*(x + log(x) + exp(x) - 1)/(x + log(x) + exp(x))**2/x g = log(x + exp(x) + log(x)) + 1/(x + exp(x) + log(x)) assert ratsimp(heurisch(f, x)) == g @XFAIL # there's a hash dependent failure lurking here def test_pmint_erf(): f = exp(-x**2)*erf(x)/(erf(x)**3 - erf(x)**2 - erf(x) + 1) g = sqrt(pi)*log(erf(x) - 1)/8 - sqrt(pi)*log(erf(x) + 1)/8 - sqrt(pi)/(4*erf(x) - 4) assert ratsimp(heurisch(f, x)) == g def test_pmint_LambertW(): f = LambertW(x) g = x*LambertW(x) - x + x/LambertW(x) assert heurisch(f, x) == g def test_pmint_besselj(): f = besselj(nu + 1, x)/besselj(nu, x) g = nu*log(x) - log(besselj(nu, x)) assert heurisch(f, x) == g f = (nu*besselj(nu, x) - x*besselj(nu + 1, x))/x g = besselj(nu, x) assert heurisch(f, x) == g f = jn(nu + 1, x)/jn(nu, x) g = nu*log(x) - log(jn(nu, x)) assert heurisch(f, x) == g @slow def test_pmint_bessel_products(): # Note: Derivatives of Bessel functions have many forms. # Recurrence relations are needed for comparisons. if ON_TRAVIS: skip("Too slow for travis.") f = x*besselj(nu, x)*bessely(nu, 2*x) g = -2*x*besselj(nu, x)*bessely(nu - 1, 2*x)/3 + x*besselj(nu - 1, x)*bessely(nu, 2*x)/3 assert heurisch(f, x) == g f = x*besselj(nu, x)*besselk(nu, 2*x) g = -2*x*besselj(nu, x)*besselk(nu - 1, 2*x)/5 - x*besselj(nu - 1, x)*besselk(nu, 2*x)/5 assert heurisch(f, x) == g @slow # 110 seconds on 3.4 GHz def test_pmint_WrightOmega(): if ON_TRAVIS: skip("Too slow for travis.") def omega(x): return LambertW(exp(x)) f = (1 + omega(x) * (2 + cos(omega(x)) * (x + omega(x))))/(1 + omega(x))/(x + omega(x)) g = log(x + LambertW(exp(x))) + sin(LambertW(exp(x))) assert heurisch(f, x) == g def test_RR(): # Make sure the algorithm does the right thing if the ring is RR. See # issue 8685. assert heurisch(sqrt(1 + 0.25*x**2), x, hints=[]) == \ 0.5*x*sqrt(0.25*x**2 + 1) + 1.0*asinh(0.5*x) # TODO: convert the rest of PMINT tests: # Airy functions # f = (x - AiryAi(x)*AiryAi(1, x)) / (x**2 - AiryAi(x)**2) # g = Rational(1,2)*ln(x + AiryAi(x)) + Rational(1,2)*ln(x - AiryAi(x)) # f = x**2 * AiryAi(x) # g = -AiryAi(x) + AiryAi(1, x)*x # Whittaker functions # f = WhittakerW(mu + 1, nu, x) / (WhittakerW(mu, nu, x) * x) # g = x/2 - mu*ln(x) - ln(WhittakerW(mu, nu, x))
742686ad052964dff15292550f8f7cbb320f15a433945173f36a98ec80eb7bd3
from sympy import ( Abs, acos, acosh, Add, And, asin, asinh, atan, Ci, cos, sinh, cosh, tanh, Derivative, diff, DiracDelta, E, Ei, Eq, exp, erf, erfc, erfi, EulerGamma, Expr, factor, Function, gamma, gammasimp, I, Idx, im, IndexedBase, integrate, Interval, Lambda, LambertW, log, Matrix, Max, meijerg, Min, nan, Ne, O, oo, pi, Piecewise, polar_lift, Poly, polygamma, Rational, re, S, Si, sign, simplify, sin, sinc, SingularityFunction, sqrt, sstr, Sum, Symbol, summation, symbols, sympify, tan, trigsimp, Tuple, lerchphi, exp_polar, li, hyper ) from sympy.core.expr import unchanged from sympy.functions.elementary.complexes import periodic_argument from sympy.functions.elementary.integers import floor from sympy.integrals.integrals import Integral from sympy.integrals.risch import NonElementaryIntegral from sympy.physics import units from sympy.testing.pytest import (raises, slow, skip, ON_TRAVIS, warns_deprecated_sympy) from sympy.testing.randtest import verify_numerically x, y, a, t, x_1, x_2, z, s, b = symbols('x y a t x_1 x_2 z s b') n = Symbol('n', integer=True) f = Function('f') def NS(e, n=15, **options): return sstr(sympify(e).evalf(n, **options), full_prec=True) def test_poly_deprecated(): p = Poly(2*x, x) assert p.integrate(x) == Poly(x**2, x, domain='QQ') with warns_deprecated_sympy(): integrate(p, x) with warns_deprecated_sympy(): Integral(p, (x,)) def test_principal_value(): g = 1 / x assert Integral(g, (x, -oo, oo)).principal_value() == 0 assert Integral(g, (y, -oo, oo)).principal_value() == oo * sign(1 / x) raises(ValueError, lambda: Integral(g, (x)).principal_value()) raises(ValueError, lambda: Integral(g).principal_value()) l = 1 / ((x ** 3) - 1) assert Integral(l, (x, -oo, oo)).principal_value() == -sqrt(3)*pi/3 raises(ValueError, lambda: Integral(l, (x, -oo, 1)).principal_value()) d = 1 / (x ** 2 - 1) assert Integral(d, (x, -oo, oo)).principal_value() == 0 assert Integral(d, (x, -2, 2)).principal_value() == -log(3) v = x / (x ** 2 - 1) assert Integral(v, (x, -oo, oo)).principal_value() == 0 assert Integral(v, (x, -2, 2)).principal_value() == 0 s = x ** 2 / (x ** 2 - 1) assert Integral(s, (x, -oo, oo)).principal_value() is oo assert Integral(s, (x, -2, 2)).principal_value() == -log(3) + 4 f = 1 / ((x ** 2 - 1) * (1 + x ** 2)) assert Integral(f, (x, -oo, oo)).principal_value() == -pi / 2 assert Integral(f, (x, -2, 2)).principal_value() == -atan(2) - log(3) / 2 def diff_test(i): """Return the set of symbols, s, which were used in testing that i.diff(s) agrees with i.doit().diff(s). If there is an error then the assertion will fail, causing the test to fail.""" syms = i.free_symbols for s in syms: assert (i.diff(s).doit() - i.doit().diff(s)).expand() == 0 return syms def test_improper_integral(): assert integrate(log(x), (x, 0, 1)) == -1 assert integrate(x**(-2), (x, 1, oo)) == 1 assert integrate(1/(1 + exp(x)), (x, 0, oo)) == log(2) def test_constructor(): # this is shared by Sum, so testing Integral's constructor # is equivalent to testing Sum's s1 = Integral(n, n) assert s1.limits == (Tuple(n),) s2 = Integral(n, (n,)) assert s2.limits == (Tuple(n),) s3 = Integral(Sum(x, (x, 1, y))) assert s3.limits == (Tuple(y),) s4 = Integral(n, Tuple(n,)) assert s4.limits == (Tuple(n),) s5 = Integral(n, (n, Interval(1, 2))) assert s5.limits == (Tuple(n, 1, 2),) # Testing constructor with inequalities: s6 = Integral(n, n > 10) assert s6.limits == (Tuple(n, 10, oo),) s7 = Integral(n, (n > 2) & (n < 5)) assert s7.limits == (Tuple(n, 2, 5),) def test_basics(): assert Integral(0, x) != 0 assert Integral(x, (x, 1, 1)) != 0 assert Integral(oo, x) != oo assert Integral(S.NaN, x) is S.NaN assert diff(Integral(y, y), x) == 0 assert diff(Integral(x, (x, 0, 1)), x) == 0 assert diff(Integral(x, x), x) == x assert diff(Integral(t, (t, 0, x)), x) == x e = (t + 1)**2 assert diff(integrate(e, (t, 0, x)), x) == \ diff(Integral(e, (t, 0, x)), x).doit().expand() == \ ((1 + x)**2).expand() assert diff(integrate(e, (t, 0, x)), t) == \ diff(Integral(e, (t, 0, x)), t) == 0 assert diff(integrate(e, (t, 0, x)), a) == \ diff(Integral(e, (t, 0, x)), a) == 0 assert diff(integrate(e, t), a) == diff(Integral(e, t), a) == 0 assert integrate(e, (t, a, x)).diff(x) == \ Integral(e, (t, a, x)).diff(x).doit().expand() assert Integral(e, (t, a, x)).diff(x).doit() == ((1 + x)**2) assert integrate(e, (t, x, a)).diff(x).doit() == (-(1 + x)**2).expand() assert integrate(t**2, (t, x, 2*x)).diff(x) == 7*x**2 assert Integral(x, x).atoms() == {x} assert Integral(f(x), (x, 0, 1)).atoms() == {S.Zero, S.One, x} assert diff_test(Integral(x, (x, 3*y))) == {y} assert diff_test(Integral(x, (a, 3*y))) == {x, y} assert integrate(x, (x, oo, oo)) == 0 #issue 8171 assert integrate(x, (x, -oo, -oo)) == 0 # sum integral of terms assert integrate(y + x + exp(x), x) == x*y + x**2/2 + exp(x) assert Integral(x).is_commutative n = Symbol('n', commutative=False) assert Integral(n + x, x).is_commutative is False def test_diff_wrt(): class Test(Expr): _diff_wrt = True is_commutative = True t = Test() assert integrate(t + 1, t) == t**2/2 + t assert integrate(t + 1, (t, 0, 1)) == Rational(3, 2) raises(ValueError, lambda: integrate(x + 1, x + 1)) raises(ValueError, lambda: integrate(x + 1, (x + 1, 0, 1))) def test_basics_multiple(): assert diff_test(Integral(x, (x, 3*x, 5*y), (y, x, 2*x))) == {x} assert diff_test(Integral(x, (x, 5*y), (y, x, 2*x))) == {x} assert diff_test(Integral(x, (x, 5*y), (y, y, 2*x))) == {x, y} assert diff_test(Integral(y, y, x)) == {x, y} assert diff_test(Integral(y*x, x, y)) == {x, y} assert diff_test(Integral(x + y, y, (y, 1, x))) == {x} assert diff_test(Integral(x + y, (x, x, y), (y, y, x))) == {x, y} def test_conjugate_transpose(): A, B = symbols("A B", commutative=False) x = Symbol("x", complex=True) p = Integral(A*B, (x,)) assert p.adjoint().doit() == p.doit().adjoint() assert p.conjugate().doit() == p.doit().conjugate() assert p.transpose().doit() == p.doit().transpose() x = Symbol("x", real=True) p = Integral(A*B, (x,)) assert p.adjoint().doit() == p.doit().adjoint() assert p.conjugate().doit() == p.doit().conjugate() assert p.transpose().doit() == p.doit().transpose() def test_integration(): assert integrate(0, (t, 0, x)) == 0 assert integrate(3, (t, 0, x)) == 3*x assert integrate(t, (t, 0, x)) == x**2/2 assert integrate(3*t, (t, 0, x)) == 3*x**2/2 assert integrate(3*t**2, (t, 0, x)) == x**3 assert integrate(1/t, (t, 1, x)) == log(x) assert integrate(-1/t**2, (t, 1, x)) == 1/x - 1 assert integrate(t**2 + 5*t - 8, (t, 0, x)) == x**3/3 + 5*x**2/2 - 8*x assert integrate(x**2, x) == x**3/3 assert integrate((3*t*x)**5, x) == (3*t)**5 * x**6 / 6 b = Symbol("b") c = Symbol("c") assert integrate(a*t, (t, 0, x)) == a*x**2/2 assert integrate(a*t**4, (t, 0, x)) == a*x**5/5 assert integrate(a*t**2 + b*t + c, (t, 0, x)) == a*x**3/3 + b*x**2/2 + c*x def test_multiple_integration(): assert integrate((x**2)*(y**2), (x, 0, 1), (y, -1, 2)) == Rational(1) assert integrate((y**2)*(x**2), x, y) == Rational(1, 9)*(x**3)*(y**3) assert integrate(1/(x + 3)/(1 + x)**3, x) == \ log(3 + x)*Rational(-1, 8) + log(1 + x)*Rational(1, 8) + x/(4 + 8*x + 4*x**2) assert integrate(sin(x*y)*y, (x, 0, 1), (y, 0, 1)) == -sin(1) + 1 def test_issue_3532(): assert integrate(exp(-x), (x, 0, oo)) == 1 def test_issue_3560(): assert integrate(sqrt(x)**3, x) == 2*sqrt(x)**5/5 assert integrate(sqrt(x), x) == 2*sqrt(x)**3/3 assert integrate(1/sqrt(x)**3, x) == -2/sqrt(x) def test_issue_18038(): raises(AttributeError, lambda: integrate((x, x))) def test_integrate_poly(): p = Poly(x + x**2*y + y**3, x, y) with warns_deprecated_sympy(): qx = integrate(p, x) with warns_deprecated_sympy(): qy = integrate(p, y) assert isinstance(qx, Poly) is True assert isinstance(qy, Poly) is True assert qx.gens == (x, y) assert qy.gens == (x, y) assert qx.as_expr() == x**2/2 + x**3*y/3 + x*y**3 assert qy.as_expr() == x*y + x**2*y**2/2 + y**4/4 def test_integrate_poly_defined(): p = Poly(x + x**2*y + y**3, x, y) with warns_deprecated_sympy(): Qx = integrate(p, (x, 0, 1)) with warns_deprecated_sympy(): Qy = integrate(p, (y, 0, pi)) assert isinstance(Qx, Poly) is True assert isinstance(Qy, Poly) is True assert Qx.gens == (y,) assert Qy.gens == (x,) assert Qx.as_expr() == S.Half + y/3 + y**3 assert Qy.as_expr() == pi**4/4 + pi*x + pi**2*x**2/2 def test_integrate_omit_var(): y = Symbol('y') assert integrate(x) == x**2/2 raises(ValueError, lambda: integrate(2)) raises(ValueError, lambda: integrate(x*y)) def test_integrate_poly_accurately(): y = Symbol('y') assert integrate(x*sin(y), x) == x**2*sin(y)/2 # when passed to risch_norman, this will be a CPU hog, so this really # checks, that integrated function is recognized as polynomial assert integrate(x**1000*sin(y), x) == x**1001*sin(y)/1001 def test_issue_3635(): y = Symbol('y') assert integrate(x**2, y) == x**2*y assert integrate(x**2, (y, -1, 1)) == 2*x**2 # works in sympy and py.test but hangs in `setup.py test` def test_integrate_linearterm_pow(): # check integrate((a*x+b)^c, x) -- issue 3499 y = Symbol('y', positive=True) # TODO: Remove conds='none' below, let the assumption take care of it. assert integrate(x**y, x, conds='none') == x**(y + 1)/(y + 1) assert integrate((exp(y)*x + 1/y)**(1 + sin(y)), x, conds='none') == \ exp(-y)*(exp(y)*x + 1/y)**(2 + sin(y)) / (2 + sin(y)) def test_issue_3618(): assert integrate(pi*sqrt(x), x) == 2*pi*sqrt(x)**3/3 assert integrate(pi*sqrt(x) + E*sqrt(x)**3, x) == \ 2*pi*sqrt(x)**3/3 + 2*E *sqrt(x)**5/5 def test_issue_3623(): assert integrate(cos((n + 1)*x), x) == Piecewise( (sin(x*(n + 1))/(n + 1), Ne(n + 1, 0)), (x, True)) assert integrate(cos((n - 1)*x), x) == Piecewise( (sin(x*(n - 1))/(n - 1), Ne(n - 1, 0)), (x, True)) assert integrate(cos((n + 1)*x) + cos((n - 1)*x), x) == \ Piecewise((sin(x*(n - 1))/(n - 1), Ne(n - 1, 0)), (x, True)) + \ Piecewise((sin(x*(n + 1))/(n + 1), Ne(n + 1, 0)), (x, True)) def test_issue_3664(): n = Symbol('n', integer=True, nonzero=True) assert integrate(-1./2 * x * sin(n * pi * x/2), [x, -2, 0]) == \ 2.0*cos(pi*n)/(pi*n) assert integrate(x * sin(n * pi * x/2) * Rational(-1, 2), [x, -2, 0]) == \ 2*cos(pi*n)/(pi*n) def test_issue_3679(): # definite integration of rational functions gives wrong answers assert NS(Integral(1/(x**2 - 8*x + 17), (x, 2, 4))) == '1.10714871779409' def test_issue_3686(): # remove this when fresnel itegrals are implemented from sympy import expand_func, fresnels assert expand_func(integrate(sin(x**2), x)) == \ sqrt(2)*sqrt(pi)*fresnels(sqrt(2)*x/sqrt(pi))/2 def test_integrate_units(): m = units.m s = units.s assert integrate(x * m/s, (x, 1*s, 5*s)) == 12*m*s def test_transcendental_functions(): assert integrate(LambertW(2*x), x) == \ -x + x*LambertW(2*x) + x/LambertW(2*x) def test_log_polylog(): assert integrate(log(1 - x)/x, (x, 0, 1)) == -pi**2/6 assert integrate(log(x)*(1 - x)**(-1), (x, 0, 1)) == -pi**2/6 def test_issue_3740(): f = 4*log(x) - 2*log(x)**2 fid = diff(integrate(f, x), x) assert abs(f.subs(x, 42).evalf() - fid.subs(x, 42).evalf()) < 1e-10 def test_issue_3788(): assert integrate(1/(1 + x**2), x) == atan(x) def test_issue_3952(): f = sin(x) assert integrate(f, x) == -cos(x) raises(ValueError, lambda: integrate(f, 2*x)) def test_issue_4516(): assert integrate(2**x - 2*x, x) == 2**x/log(2) - x**2 def test_issue_7450(): ans = integrate(exp(-(1 + I)*x), (x, 0, oo)) assert re(ans) == S.Half and im(ans) == Rational(-1, 2) def test_issue_8623(): assert integrate((1 + cos(2*x)) / (3 - 2*cos(2*x)), (x, 0, pi)) == -pi/2 + sqrt(5)*pi/2 assert integrate((1 + cos(2*x))/(3 - 2*cos(2*x))) == -x/2 + sqrt(5)*(atan(sqrt(5)*tan(x)) + \ pi*floor((x - pi/2)/pi))/2 def test_issue_9569(): assert integrate(1 / (2 - cos(x)), (x, 0, pi)) == pi/sqrt(3) assert integrate(1/(2 - cos(x))) == 2*sqrt(3)*(atan(sqrt(3)*tan(x/2)) + pi*floor((x/2 - pi/2)/pi))/3 def test_issue_13749(): assert integrate(1 / (2 + cos(x)), (x, 0, pi)) == pi/sqrt(3) assert integrate(1/(2 + cos(x))) == 2*sqrt(3)*(atan(sqrt(3)*tan(x/2)/3) + pi*floor((x/2 - pi/2)/pi))/3 def test_issue_18133(): assert integrate(exp(x)/(1 + x)**2, x) == NonElementaryIntegral(exp(x)/(x + 1)**2, x) def test_matrices(): M = Matrix(2, 2, lambda i, j: (i + j + 1)*sin((i + j + 1)*x)) assert integrate(M, x) == Matrix([ [-cos(x), -cos(2*x)], [-cos(2*x), -cos(3*x)], ]) def test_integrate_functions(): # issue 4111 assert integrate(f(x), x) == Integral(f(x), x) assert integrate(f(x), (x, 0, 1)) == Integral(f(x), (x, 0, 1)) assert integrate(f(x)*diff(f(x), x), x) == f(x)**2/2 assert integrate(diff(f(x), x) / f(x), x) == log(f(x)) def test_integrate_derivatives(): assert integrate(Derivative(f(x), x), x) == f(x) assert integrate(Derivative(f(y), y), x) == x*Derivative(f(y), y) assert integrate(Derivative(f(x), x)**2, x) == \ Integral(Derivative(f(x), x)**2, x) def test_transform(): a = Integral(x**2 + 1, (x, -1, 2)) fx = x fy = 3*y + 1 assert a.doit() == a.transform(fx, fy).doit() assert a.transform(fx, fy).transform(fy, fx) == a fx = 3*x + 1 fy = y assert a.transform(fx, fy).transform(fy, fx) == a a = Integral(sin(1/x), (x, 0, 1)) assert a.transform(x, 1/y) == Integral(sin(y)/y**2, (y, 1, oo)) assert a.transform(x, 1/y).transform(y, 1/x) == a a = Integral(exp(-x**2), (x, -oo, oo)) assert a.transform(x, 2*y) == Integral(2*exp(-4*y**2), (y, -oo, oo)) # < 3 arg limit handled properly assert Integral(x, x).transform(x, a*y).doit() == \ Integral(y*a**2, y).doit() _3 = S(3) assert Integral(x, (x, 0, -_3)).transform(x, 1/y).doit() == \ Integral(-1/x**3, (x, -oo, -1/_3)).doit() assert Integral(x, (x, 0, _3)).transform(x, 1/y) == \ Integral(y**(-3), (y, 1/_3, oo)) # issue 8400 i = Integral(x + y, (x, 1, 2), (y, 1, 2)) assert i.transform(x, (x + 2*y, x)).doit() == \ i.transform(x, (x + 2*z, x)).doit() == 3 i = Integral(x, (x, a, b)) assert i.transform(x, 2*s) == Integral(4*s, (s, a/2, b/2)) raises(ValueError, lambda: i.transform(x, 1)) raises(ValueError, lambda: i.transform(x, s*t)) raises(ValueError, lambda: i.transform(x, -s)) raises(ValueError, lambda: i.transform(x, (s, t))) raises(ValueError, lambda: i.transform(2*x, 2*s)) i = Integral(x**2, (x, 1, 2)) raises(ValueError, lambda: i.transform(x**2, s)) am = Symbol('a', negative=True) bp = Symbol('b', positive=True) i = Integral(x, (x, bp, am)) i.transform(x, 2*s) assert i.transform(x, 2*s) == Integral(-4*s, (s, am/2, bp/2)) i = Integral(x, (x, a)) assert i.transform(x, 2*s) == Integral(4*s, (s, a/2)) def test_issue_4052(): f = S.Half*asin(x) + x*sqrt(1 - x**2)/2 assert integrate(cos(asin(x)), x) == f assert integrate(sin(acos(x)), x) == f @slow def test_evalf_integrals(): assert NS(Integral(x, (x, 2, 5)), 15) == '10.5000000000000' gauss = Integral(exp(-x**2), (x, -oo, oo)) assert NS(gauss, 15) == '1.77245385090552' assert NS(gauss**2 - pi + E*Rational( 1, 10**20), 15) in ('2.71828182845904e-20', '2.71828182845905e-20') # A monster of an integral from http://mathworld.wolfram.com/DefiniteIntegral.html t = Symbol('t') a = 8*sqrt(3)/(1 + 3*t**2) b = 16*sqrt(2)*(3*t + 1)*sqrt(4*t**2 + t + 1)**3 c = (3*t**2 + 1)*(11*t**2 + 2*t + 3)**2 d = sqrt(2)*(249*t**2 + 54*t + 65)/(11*t**2 + 2*t + 3)**2 f = a - b/c - d assert NS(Integral(f, (t, 0, 1)), 50) == \ NS((3*sqrt(2) - 49*pi + 162*atan(sqrt(2)))/12, 50) # http://mathworld.wolfram.com/VardisIntegral.html assert NS(Integral(log(log(1/x))/(1 + x + x**2), (x, 0, 1)), 15) == \ NS('pi/sqrt(3) * log(2*pi**(5/6) / gamma(1/6))', 15) # http://mathworld.wolfram.com/AhmedsIntegral.html assert NS(Integral(atan(sqrt(x**2 + 2))/(sqrt(x**2 + 2)*(x**2 + 1)), (x, 0, 1)), 15) == NS(5*pi**2/96, 15) # http://mathworld.wolfram.com/AbelsIntegral.html assert NS(Integral(x/((exp(pi*x) - exp( -pi*x))*(x**2 + 1)), (x, 0, oo)), 15) == NS('log(2)/2-1/4', 15) # Complex part trimming # http://mathworld.wolfram.com/VardisIntegral.html assert NS(Integral(log(log(sin(x)/cos(x))), (x, pi/4, pi/2)), 15, chop=True) == \ NS('pi/4*log(4*pi**3/gamma(1/4)**4)', 15) # # Endpoints causing trouble (rounding error in integration points -> complex log) assert NS( 2 + Integral(log(2*cos(x/2)), (x, -pi, pi)), 17, chop=True) == NS(2, 17) assert NS( 2 + Integral(log(2*cos(x/2)), (x, -pi, pi)), 20, chop=True) == NS(2, 20) assert NS( 2 + Integral(log(2*cos(x/2)), (x, -pi, pi)), 22, chop=True) == NS(2, 22) # Needs zero handling assert NS(pi - 4*Integral( 'sqrt(1-x**2)', (x, 0, 1)), 15, maxn=30, chop=True) in ('0.0', '0') # Oscillatory quadrature a = Integral(sin(x)/x**2, (x, 1, oo)).evalf(maxn=15) assert 0.49 < a < 0.51 assert NS( Integral(sin(x)/x**2, (x, 1, oo)), quad='osc') == '0.504067061906928' assert NS(Integral( cos(pi*x + 1)/x, (x, -oo, -1)), quad='osc') == '0.276374705640365' # indefinite integrals aren't evaluated assert NS(Integral(x, x)) == 'Integral(x, x)' assert NS(Integral(x, (x, y))) == 'Integral(x, (x, y))' def test_evalf_issue_939(): # https://github.com/sympy/sympy/issues/4038 # The output form of an integral may differ by a step function between # revisions, making this test a bit useless. This can't be said about # other two tests. For now, all values of this evaluation are used here, # but in future this should be reconsidered. assert NS(integrate(1/(x**5 + 1), x).subs(x, 4), chop=True) in \ ['-0.000976138910649103', '0.965906660135753', '1.93278945918216'] assert NS(Integral(1/(x**5 + 1), (x, 2, 4))) == '0.0144361088886740' assert NS( integrate(1/(x**5 + 1), (x, 2, 4)), chop=True) == '0.0144361088886740' def test_double_previously_failing_integrals(): # Double integrals not implemented <- Sure it is! res = integrate(sqrt(x) + x*y, (x, 1, 2), (y, -1, 1)) # Old numerical test assert NS(res, 15) == '2.43790283299492' # Symbolic test assert res == Rational(-4, 3) + 8*sqrt(2)/3 # double integral + zero detection assert integrate(sin(x + x*y), (x, -1, 1), (y, -1, 1)) is S.Zero def test_integrate_SingularityFunction(): in_1 = SingularityFunction(x, a, 3) + SingularityFunction(x, 5, -1) out_1 = SingularityFunction(x, a, 4)/4 + SingularityFunction(x, 5, 0) assert integrate(in_1, x) == out_1 in_2 = 10*SingularityFunction(x, 4, 0) - 5*SingularityFunction(x, -6, -2) out_2 = 10*SingularityFunction(x, 4, 1) - 5*SingularityFunction(x, -6, -1) assert integrate(in_2, x) == out_2 in_3 = 2*x**2*y -10*SingularityFunction(x, -4, 7) - 2*SingularityFunction(y, 10, -2) out_3_1 = 2*x**3*y/3 - 2*x*SingularityFunction(y, 10, -2) - 5*SingularityFunction(x, -4, 8)/4 out_3_2 = x**2*y**2 - 10*y*SingularityFunction(x, -4, 7) - 2*SingularityFunction(y, 10, -1) assert integrate(in_3, x) == out_3_1 assert integrate(in_3, y) == out_3_2 assert unchanged(Integral, in_3, (x,)) assert Integral(in_3, x) == Integral(in_3, (x,)) assert Integral(in_3, x).doit() == out_3_1 in_4 = 10*SingularityFunction(x, -4, 7) - 2*SingularityFunction(x, 10, -2) out_4 = 5*SingularityFunction(x, -4, 8)/4 - 2*SingularityFunction(x, 10, -1) assert integrate(in_4, (x, -oo, x)) == out_4 assert integrate(SingularityFunction(x, 5, -1), x) == SingularityFunction(x, 5, 0) assert integrate(SingularityFunction(x, 0, -1), (x, -oo, oo)) == 1 assert integrate(5*SingularityFunction(x, 5, -1), (x, -oo, oo)) == 5 assert integrate(SingularityFunction(x, 5, -1) * f(x), (x, -oo, oo)) == f(5) def test_integrate_DiracDelta(): # This is here to check that deltaintegrate is being called, but also # to test definite integrals. More tests are in test_deltafunctions.py assert integrate(DiracDelta(x) * f(x), (x, -oo, oo)) == f(0) assert integrate(DiracDelta(x)**2, (x, -oo, oo)) == DiracDelta(0) # issue 4522 assert integrate(integrate((4 - 4*x + x*y - 4*y) * \ DiracDelta(x)*DiracDelta(y - 1), (x, 0, 1)), (y, 0, 1)) == 0 # issue 5729 p = exp(-(x**2 + y**2))/pi assert integrate(p*DiracDelta(x - 10*y), (x, -oo, oo), (y, -oo, oo)) == \ integrate(p*DiracDelta(x - 10*y), (y, -oo, oo), (x, -oo, oo)) == \ integrate(p*DiracDelta(10*x - y), (x, -oo, oo), (y, -oo, oo)) == \ integrate(p*DiracDelta(10*x - y), (y, -oo, oo), (x, -oo, oo)) == \ 1/sqrt(101*pi) def test_integrate_returns_piecewise(): assert integrate(x**y, x) == Piecewise( (x**(y + 1)/(y + 1), Ne(y, -1)), (log(x), True)) assert integrate(x**y, y) == Piecewise( (x**y/log(x), Ne(log(x), 0)), (y, True)) assert integrate(exp(n*x), x) == Piecewise( (exp(n*x)/n, Ne(n, 0)), (x, True)) assert integrate(x*exp(n*x), x) == Piecewise( ((n*x - 1)*exp(n*x)/n**2, Ne(n**2, 0)), (x**2/2, True)) assert integrate(x**(n*y), x) == Piecewise( (x**(n*y + 1)/(n*y + 1), Ne(n*y, -1)), (log(x), True)) assert integrate(x**(n*y), y) == Piecewise( (x**(n*y)/(n*log(x)), Ne(n*log(x), 0)), (y, True)) assert integrate(cos(n*x), x) == Piecewise( (sin(n*x)/n, Ne(n, 0)), (x, True)) assert integrate(cos(n*x)**2, x) == Piecewise( ((n*x/2 + sin(n*x)*cos(n*x)/2)/n, Ne(n, 0)), (x, True)) assert integrate(x*cos(n*x), x) == Piecewise( (x*sin(n*x)/n + cos(n*x)/n**2, Ne(n, 0)), (x**2/2, True)) assert integrate(sin(n*x), x) == Piecewise( (-cos(n*x)/n, Ne(n, 0)), (0, True)) assert integrate(sin(n*x)**2, x) == Piecewise( ((n*x/2 - sin(n*x)*cos(n*x)/2)/n, Ne(n, 0)), (0, True)) assert integrate(x*sin(n*x), x) == Piecewise( (-x*cos(n*x)/n + sin(n*x)/n**2, Ne(n, 0)), (0, True)) assert integrate(exp(x*y), (x, 0, z)) == Piecewise( (exp(y*z)/y - 1/y, (y > -oo) & (y < oo) & Ne(y, 0)), (z, True)) def test_integrate_max_min(): x = symbols('x', real=True) assert integrate(Min(x, 2), (x, 0, 3)) == 4 assert integrate(Max(x**2, x**3), (x, 0, 2)) == Rational(49, 12) assert integrate(Min(exp(x), exp(-x))**2, x) == Piecewise( \ (exp(2*x)/2, x <= 0), (1 - exp(-2*x)/2, True)) # issue 7907 c = symbols('c', extended_real=True) int1 = integrate(Max(c, x)*exp(-x**2), (x, -oo, oo)) int2 = integrate(c*exp(-x**2), (x, -oo, c)) int3 = integrate(x*exp(-x**2), (x, c, oo)) assert int1 == int2 + int3 == sqrt(pi)*c*erf(c)/2 + \ sqrt(pi)*c/2 + exp(-c**2)/2 def test_integrate_Abs_sign(): assert integrate(Abs(x), (x, -2, 1)) == Rational(5, 2) assert integrate(Abs(x), (x, 0, 1)) == S.Half assert integrate(Abs(x + 1), (x, 0, 1)) == Rational(3, 2) assert integrate(Abs(x**2 - 1), (x, -2, 2)) == 4 assert integrate(Abs(x**2 - 3*x), (x, -15, 15)) == 2259 assert integrate(sign(x), (x, -1, 2)) == 1 assert integrate(sign(x)*sin(x), (x, -pi, pi)) == 4 assert integrate(sign(x - 2) * x**2, (x, 0, 3)) == Rational(11, 3) t, s = symbols('t s', real=True) assert integrate(Abs(t), t) == Piecewise( (-t**2/2, t <= 0), (t**2/2, True)) assert integrate(Abs(2*t - 6), t) == Piecewise( (-t**2 + 6*t, t <= 3), (t**2 - 6*t + 18, True)) assert (integrate(abs(t - s**2), (t, 0, 2)) == 2*s**2*Min(2, s**2) - 2*s**2 - Min(2, s**2)**2 + 2) assert integrate(exp(-Abs(t)), t) == Piecewise( (exp(t), t <= 0), (2 - exp(-t), True)) assert integrate(sign(2*t - 6), t) == Piecewise( (-t, t < 3), (t - 6, True)) assert integrate(2*t*sign(t**2 - 1), t) == Piecewise( (t**2, t < -1), (-t**2 + 2, t < 1), (t**2, True)) assert integrate(sign(t), (t, s + 1)) == Piecewise( (s + 1, s + 1 > 0), (-s - 1, s + 1 < 0), (0, True)) def test_subs1(): e = Integral(exp(x - y), x) assert e.subs(y, 3) == Integral(exp(x - 3), x) e = Integral(exp(x - y), (x, 0, 1)) assert e.subs(y, 3) == Integral(exp(x - 3), (x, 0, 1)) f = Lambda(x, exp(-x**2)) conv = Integral(f(x - y)*f(y), (y, -oo, oo)) assert conv.subs({x: 0}) == Integral(exp(-2*y**2), (y, -oo, oo)) def test_subs2(): e = Integral(exp(x - y), x, t) assert e.subs(y, 3) == Integral(exp(x - 3), x, t) e = Integral(exp(x - y), (x, 0, 1), (t, 0, 1)) assert e.subs(y, 3) == Integral(exp(x - 3), (x, 0, 1), (t, 0, 1)) f = Lambda(x, exp(-x**2)) conv = Integral(f(x - y)*f(y), (y, -oo, oo), (t, 0, 1)) assert conv.subs({x: 0}) == Integral(exp(-2*y**2), (y, -oo, oo), (t, 0, 1)) def test_subs3(): e = Integral(exp(x - y), (x, 0, y), (t, y, 1)) assert e.subs(y, 3) == Integral(exp(x - 3), (x, 0, 3), (t, 3, 1)) f = Lambda(x, exp(-x**2)) conv = Integral(f(x - y)*f(y), (y, -oo, oo), (t, x, 1)) assert conv.subs({x: 0}) == Integral(exp(-2*y**2), (y, -oo, oo), (t, 0, 1)) def test_subs4(): e = Integral(exp(x), (x, 0, y), (t, y, 1)) assert e.subs(y, 3) == Integral(exp(x), (x, 0, 3), (t, 3, 1)) f = Lambda(x, exp(-x**2)) conv = Integral(f(y)*f(y), (y, -oo, oo), (t, x, 1)) assert conv.subs({x: 0}) == Integral(exp(-2*y**2), (y, -oo, oo), (t, 0, 1)) def test_subs5(): e = Integral(exp(-x**2), (x, -oo, oo)) assert e.subs(x, 5) == e e = Integral(exp(-x**2 + y), x) assert e.subs(y, 5) == Integral(exp(-x**2 + 5), x) e = Integral(exp(-x**2 + y), (x, x)) assert e.subs(x, 5) == Integral(exp(y - x**2), (x, 5)) assert e.subs(y, 5) == Integral(exp(-x**2 + 5), x) e = Integral(exp(-x**2 + y), (y, -oo, oo), (x, -oo, oo)) assert e.subs(x, 5) == e assert e.subs(y, 5) == e # Test evaluation of antiderivatives e = Integral(exp(-x**2), (x, x)) assert e.subs(x, 5) == Integral(exp(-x**2), (x, 5)) e = Integral(exp(x), x) assert (e.subs(x,1) - e.subs(x,0) - Integral(exp(x), (x, 0, 1)) ).doit().is_zero def test_subs6(): a, b = symbols('a b') e = Integral(x*y, (x, f(x), f(y))) assert e.subs(x, 1) == Integral(x*y, (x, f(1), f(y))) assert e.subs(y, 1) == Integral(x, (x, f(x), f(1))) e = Integral(x*y, (x, f(x), f(y)), (y, f(x), f(y))) assert e.subs(x, 1) == Integral(x*y, (x, f(1), f(y)), (y, f(1), f(y))) assert e.subs(y, 1) == Integral(x*y, (x, f(x), f(y)), (y, f(x), f(1))) e = Integral(x*y, (x, f(x), f(a)), (y, f(x), f(a))) assert e.subs(a, 1) == Integral(x*y, (x, f(x), f(1)), (y, f(x), f(1))) def test_subs7(): e = Integral(x, (x, 1, y), (y, 1, 2)) assert e.subs({x: 1, y: 2}) == e e = Integral(sin(x) + sin(y), (x, sin(x), sin(y)), (y, 1, 2)) assert e.subs(sin(y), 1) == e assert e.subs(sin(x), 1) == Integral(sin(x) + sin(y), (x, 1, sin(y)), (y, 1, 2)) def test_expand(): e = Integral(f(x)+f(x**2), (x, 1, y)) assert e.expand() == Integral(f(x), (x, 1, y)) + Integral(f(x**2), (x, 1, y)) def test_integration_variable(): raises(ValueError, lambda: Integral(exp(-x**2), 3)) raises(ValueError, lambda: Integral(exp(-x**2), (3, -oo, oo))) def test_expand_integral(): assert Integral(cos(x**2)*(sin(x**2) + 1), (x, 0, 1)).expand() == \ Integral(cos(x**2)*sin(x**2), (x, 0, 1)) + \ Integral(cos(x**2), (x, 0, 1)) assert Integral(cos(x**2)*(sin(x**2) + 1), x).expand() == \ Integral(cos(x**2)*sin(x**2), x) + \ Integral(cos(x**2), x) def test_as_sum_midpoint1(): e = Integral(sqrt(x**3 + 1), (x, 2, 10)) assert e.as_sum(1, method="midpoint") == 8*sqrt(217) assert e.as_sum(2, method="midpoint") == 4*sqrt(65) + 12*sqrt(57) assert e.as_sum(3, method="midpoint") == 8*sqrt(217)/3 + \ 8*sqrt(3081)/27 + 8*sqrt(52809)/27 assert e.as_sum(4, method="midpoint") == 2*sqrt(730) + \ 4*sqrt(7) + 4*sqrt(86) + 6*sqrt(14) assert abs(e.as_sum(4, method="midpoint").n() - e.n()) < 0.5 e = Integral(sqrt(x**3 + y**3), (x, 2, 10), (y, 0, 10)) raises(NotImplementedError, lambda: e.as_sum(4)) def test_as_sum_midpoint2(): e = Integral((x + y)**2, (x, 0, 1)) n = Symbol('n', positive=True, integer=True) assert e.as_sum(1, method="midpoint").expand() == Rational(1, 4) + y + y**2 assert e.as_sum(2, method="midpoint").expand() == Rational(5, 16) + y + y**2 assert e.as_sum(3, method="midpoint").expand() == Rational(35, 108) + y + y**2 assert e.as_sum(4, method="midpoint").expand() == Rational(21, 64) + y + y**2 assert e.as_sum(n, method="midpoint").expand() == \ y**2 + y + Rational(1, 3) - 1/(12*n**2) def test_as_sum_left(): e = Integral((x + y)**2, (x, 0, 1)) assert e.as_sum(1, method="left").expand() == y**2 assert e.as_sum(2, method="left").expand() == Rational(1, 8) + y/2 + y**2 assert e.as_sum(3, method="left").expand() == Rational(5, 27) + y*Rational(2, 3) + y**2 assert e.as_sum(4, method="left").expand() == Rational(7, 32) + y*Rational(3, 4) + y**2 assert e.as_sum(n, method="left").expand() == \ y**2 + y + Rational(1, 3) - y/n - 1/(2*n) + 1/(6*n**2) assert e.as_sum(10, method="left", evaluate=False).has(Sum) def test_as_sum_right(): e = Integral((x + y)**2, (x, 0, 1)) assert e.as_sum(1, method="right").expand() == 1 + 2*y + y**2 assert e.as_sum(2, method="right").expand() == Rational(5, 8) + y*Rational(3, 2) + y**2 assert e.as_sum(3, method="right").expand() == Rational(14, 27) + y*Rational(4, 3) + y**2 assert e.as_sum(4, method="right").expand() == Rational(15, 32) + y*Rational(5, 4) + y**2 assert e.as_sum(n, method="right").expand() == \ y**2 + y + Rational(1, 3) + y/n + 1/(2*n) + 1/(6*n**2) def test_as_sum_trapezoid(): e = Integral((x + y)**2, (x, 0, 1)) assert e.as_sum(1, method="trapezoid").expand() == y**2 + y + S.Half assert e.as_sum(2, method="trapezoid").expand() == y**2 + y + Rational(3, 8) assert e.as_sum(3, method="trapezoid").expand() == y**2 + y + Rational(19, 54) assert e.as_sum(4, method="trapezoid").expand() == y**2 + y + Rational(11, 32) assert e.as_sum(n, method="trapezoid").expand() == \ y**2 + y + Rational(1, 3) + 1/(6*n**2) assert Integral(sign(x), (x, 0, 1)).as_sum(1, 'trapezoid') == S.Half def test_as_sum_raises(): e = Integral((x + y)**2, (x, 0, 1)) raises(ValueError, lambda: e.as_sum(-1)) raises(ValueError, lambda: e.as_sum(0)) raises(ValueError, lambda: Integral(x).as_sum(3)) raises(ValueError, lambda: e.as_sum(oo)) raises(ValueError, lambda: e.as_sum(3, method='xxxx2')) def test_nested_doit(): e = Integral(Integral(x, x), x) f = Integral(x, x, x) assert e.doit() == f.doit() def test_issue_4665(): # Allow only upper or lower limit evaluation e = Integral(x**2, (x, None, 1)) f = Integral(x**2, (x, 1, None)) assert e.doit() == Rational(1, 3) assert f.doit() == Rational(-1, 3) assert Integral(x*y, (x, None, y)).subs(y, t) == Integral(x*t, (x, None, t)) assert Integral(x*y, (x, y, None)).subs(y, t) == Integral(x*t, (x, t, None)) assert integrate(x**2, (x, None, 1)) == Rational(1, 3) assert integrate(x**2, (x, 1, None)) == Rational(-1, 3) assert integrate("x**2", ("x", "1", None)) == Rational(-1, 3) def test_integral_reconstruct(): e = Integral(x**2, (x, -1, 1)) assert e == Integral(*e.args) def test_doit_integrals(): e = Integral(Integral(2*x), (x, 0, 1)) assert e.doit() == Rational(1, 3) assert e.doit(deep=False) == Rational(1, 3) f = Function('f') # doesn't matter if the integral can't be performed assert Integral(f(x), (x, 1, 1)).doit() == 0 # doesn't matter if the limits can't be evaluated assert Integral(0, (x, 1, Integral(f(x), x))).doit() == 0 assert Integral(x, (a, 0)).doit() == 0 limits = ((a, 1, exp(x)), (x, 0)) assert Integral(a, *limits).doit() == Rational(1, 4) assert Integral(a, *list(reversed(limits))).doit() == 0 def test_issue_4884(): assert integrate(sqrt(x)*(1 + x)) == \ Piecewise( (2*sqrt(x)*(x + 1)**2/5 - 2*sqrt(x)*(x + 1)/15 - 4*sqrt(x)/15, Abs(x + 1) > 1), (2*I*sqrt(-x)*(x + 1)**2/5 - 2*I*sqrt(-x)*(x + 1)/15 - 4*I*sqrt(-x)/15, True)) assert integrate(x**x*(1 + log(x))) == x**x def test_issue_18153(): assert integrate(x**n*log(x),x) == \ Piecewise( (n*x*x**n*log(x)/(n**2 + 2*n + 1) + x*x**n*log(x)/(n**2 + 2*n + 1) - x*x**n/(n**2 + 2*n + 1) , Ne(n, -1)), (log(x)**2/2, True) ) def test_is_number(): from sympy.abc import x, y, z from sympy import cos, sin assert Integral(x).is_number is False assert Integral(1, x).is_number is False assert Integral(1, (x, 1)).is_number is True assert Integral(1, (x, 1, 2)).is_number is True assert Integral(1, (x, 1, y)).is_number is False assert Integral(1, (x, y)).is_number is False assert Integral(x, y).is_number is False assert Integral(x, (y, 1, x)).is_number is False assert Integral(x, (y, 1, 2)).is_number is False assert Integral(x, (x, 1, 2)).is_number is True # `foo.is_number` should always be equivalent to `not foo.free_symbols` # in each of these cases, there are pseudo-free symbols i = Integral(x, (y, 1, 1)) assert i.is_number is False and i.n() == 0 i = Integral(x, (y, z, z)) assert i.is_number is False and i.n() == 0 i = Integral(1, (y, z, z + 2)) assert i.is_number is False and i.n() == 2 assert Integral(x*y, (x, 1, 2), (y, 1, 3)).is_number is True assert Integral(x*y, (x, 1, 2), (y, 1, z)).is_number is False assert Integral(x, (x, 1)).is_number is True assert Integral(x, (x, 1, Integral(y, (y, 1, 2)))).is_number is True assert Integral(Sum(z, (z, 1, 2)), (x, 1, 2)).is_number is True # it is possible to get a false negative if the integrand is # actually an unsimplified zero, but this is true of is_number in general. assert Integral(sin(x)**2 + cos(x)**2 - 1, x).is_number is False assert Integral(f(x), (x, 0, 1)).is_number is True def test_symbols(): from sympy.abc import x, y, z assert Integral(0, x).free_symbols == {x} assert Integral(x).free_symbols == {x} assert Integral(x, (x, None, y)).free_symbols == {y} assert Integral(x, (x, y, None)).free_symbols == {y} assert Integral(x, (x, 1, y)).free_symbols == {y} assert Integral(x, (x, y, 1)).free_symbols == {y} assert Integral(x, (x, x, y)).free_symbols == {x, y} assert Integral(x, x, y).free_symbols == {x, y} assert Integral(x, (x, 1, 2)).free_symbols == set() assert Integral(x, (y, 1, 2)).free_symbols == {x} # pseudo-free in this case assert Integral(x, (y, z, z)).free_symbols == {x, z} assert Integral(x, (y, 1, 2), (y, None, None)).free_symbols == {x, y} assert Integral(x, (y, 1, 2), (x, 1, y)).free_symbols == {y} assert Integral(2, (y, 1, 2), (y, 1, x), (x, 1, 2)).free_symbols == set() assert Integral(2, (y, x, 2), (y, 1, x), (x, 1, 2)).free_symbols == set() assert Integral(2, (x, 1, 2), (y, x, 2), (y, 1, 2)).free_symbols == \ {x} def test_is_zero(): from sympy.abc import x, m assert Integral(0, (x, 1, x)).is_zero assert Integral(1, (x, 1, 1)).is_zero assert Integral(1, (x, 1, 2), (y, 2)).is_zero is False assert Integral(x, (m, 0)).is_zero assert Integral(x + m, (m, 0)).is_zero is None i = Integral(m, (m, 1, exp(x)), (x, 0)) assert i.is_zero is None assert Integral(m, (x, 0), (m, 1, exp(x))).is_zero is True assert Integral(x, (x, oo, oo)).is_zero # issue 8171 assert Integral(x, (x, -oo, -oo)).is_zero # this is zero but is beyond the scope of what is_zero # should be doing assert Integral(sin(x), (x, 0, 2*pi)).is_zero is None def test_series(): from sympy.abc import x i = Integral(cos(x), (x, x)) e = i.lseries(x) assert i.nseries(x, n=8).removeO() == Add(*[next(e) for j in range(4)]) def test_trig_nonelementary_integrals(): x = Symbol('x') assert integrate((1 + sin(x))/x, x) == log(x) + Si(x) # next one comes out as log(x) + log(x**2)/2 + Ci(x) # so not hardcoding this log ugliness assert integrate((cos(x) + 2)/x, x).has(Ci) def test_issue_4403(): x = Symbol('x') y = Symbol('y') z = Symbol('z', positive=True) assert integrate(sqrt(x**2 + z**2), x) == \ z**2*asinh(x/z)/2 + x*sqrt(x**2 + z**2)/2 assert integrate(sqrt(x**2 - z**2), x) == \ -z**2*acosh(x/z)/2 + x*sqrt(x**2 - z**2)/2 x = Symbol('x', real=True) y = Symbol('y', positive=True) assert integrate(1/(x**2 + y**2)**S('3/2'), x) == \ x/(y**2*sqrt(x**2 + y**2)) # If y is real and nonzero, we get x*Abs(y)/(y**3*sqrt(x**2 + y**2)), # which results from sqrt(1 + x**2/y**2) = sqrt(x**2 + y**2)/|y|. def test_issue_4403_2(): assert integrate(sqrt(-x**2 - 4), x) == \ -2*atan(x/sqrt(-4 - x**2)) + x*sqrt(-4 - x**2)/2 def test_issue_4100(): R = Symbol('R', positive=True) assert integrate(sqrt(R**2 - x**2), (x, 0, R)) == pi*R**2/4 def test_issue_5167(): from sympy.abc import w, x, y, z f = Function('f') assert Integral(Integral(f(x), x), x) == Integral(f(x), x, x) assert Integral(f(x)).args == (f(x), Tuple(x)) assert Integral(Integral(f(x))).args == (f(x), Tuple(x), Tuple(x)) assert Integral(Integral(f(x)), y).args == (f(x), Tuple(x), Tuple(y)) assert Integral(Integral(f(x), z), y).args == (f(x), Tuple(z), Tuple(y)) assert Integral(Integral(Integral(f(x), x), y), z).args == \ (f(x), Tuple(x), Tuple(y), Tuple(z)) assert integrate(Integral(f(x), x), x) == Integral(f(x), x, x) assert integrate(Integral(f(x), y), x) == y*Integral(f(x), x) assert integrate(Integral(f(x), x), y) in [Integral(y*f(x), x), y*Integral(f(x), x)] assert integrate(Integral(2, x), x) == x**2 assert integrate(Integral(2, x), y) == 2*x*y # don't re-order given limits assert Integral(1, x, y).args != Integral(1, y, x).args # do as many as possible assert Integral(f(x), y, x, y, x).doit() == y**2*Integral(f(x), x, x)/2 assert Integral(f(x), (x, 1, 2), (w, 1, x), (z, 1, y)).doit() == \ y*(x - 1)*Integral(f(x), (x, 1, 2)) - (x - 1)*Integral(f(x), (x, 1, 2)) def test_issue_4890(): z = Symbol('z', positive=True) assert integrate(exp(-log(x)**2), x) == \ sqrt(pi)*exp(Rational(1, 4))*erf(log(x) - S.Half)/2 assert integrate(exp(log(x)**2), x) == \ sqrt(pi)*exp(Rational(-1, 4))*erfi(log(x)+S.Half)/2 assert integrate(exp(-z*log(x)**2), x) == \ sqrt(pi)*exp(1/(4*z))*erf(sqrt(z)*log(x) - 1/(2*sqrt(z)))/(2*sqrt(z)) def test_issue_4551(): assert not integrate(1/(x*sqrt(1 - x**2)), x).has(Integral) def test_issue_4376(): n = Symbol('n', integer=True, positive=True) assert simplify(integrate(n*(x**(1/n) - 1), (x, 0, S.Half)) - (n**2 - 2**(1/n)*n**2 - n*2**(1/n))/(2**(1 + 1/n) + n*2**(1 + 1/n))) == 0 def test_issue_4517(): assert integrate((sqrt(x) - x**3)/x**Rational(1, 3), x) == \ 6*x**Rational(7, 6)/7 - 3*x**Rational(11, 3)/11 def test_issue_4527(): k, m = symbols('k m', integer=True) assert integrate(sin(k*x)*sin(m*x), (x, 0, pi)).simplify() == \ Piecewise((0, Eq(k, 0) | Eq(m, 0)), (-pi/2, Eq(k, -m) | (Eq(k, 0) & Eq(m, 0))), (pi/2, Eq(k, m) | (Eq(k, 0) & Eq(m, 0))), (0, True)) # Should be possible to further simplify to: # Piecewise( # (0, Eq(k, 0) | Eq(m, 0)), # (-pi/2, Eq(k, -m)), # (pi/2, Eq(k, m)), # (0, True)) assert integrate(sin(k*x)*sin(m*x), (x,)) == Piecewise( (0, And(Eq(k, 0), Eq(m, 0))), (-x*sin(m*x)**2/2 - x*cos(m*x)**2/2 + sin(m*x)*cos(m*x)/(2*m), Eq(k, -m)), (x*sin(m*x)**2/2 + x*cos(m*x)**2/2 - sin(m*x)*cos(m*x)/(2*m), Eq(k, m)), (m*sin(k*x)*cos(m*x)/(k**2 - m**2) - k*sin(m*x)*cos(k*x)/(k**2 - m**2), True)) def test_issue_4199(): ypos = Symbol('y', positive=True) # TODO: Remove conds='none' below, let the assumption take care of it. assert integrate(exp(-I*2*pi*ypos*x)*x, (x, -oo, oo), conds='none') == \ Integral(exp(-I*2*pi*ypos*x)*x, (x, -oo, oo)) @slow def test_issue_3940(): a, b, c, d = symbols('a:d', positive=True, finite=True) assert integrate(exp(-x**2 + I*c*x), x) == \ -sqrt(pi)*exp(-c**2/4)*erf(I*c/2 - x)/2 assert integrate(exp(a*x**2 + b*x + c), x) == \ sqrt(pi)*exp(c)*exp(-b**2/(4*a))*erfi(sqrt(a)*x + b/(2*sqrt(a)))/(2*sqrt(a)) from sympy import expand_mul from sympy.abc import k assert expand_mul(integrate(exp(-x**2)*exp(I*k*x), (x, -oo, oo))) == \ sqrt(pi)*exp(-k**2/4) a, d = symbols('a d', positive=True) assert expand_mul(integrate(exp(-a*x**2 + 2*d*x), (x, -oo, oo))) == \ sqrt(pi)*exp(d**2/a)/sqrt(a) def test_issue_5413(): # Note that this is not the same as testing ratint() because integrate() # pulls out the coefficient. assert integrate(-a/(a**2 + x**2), x) == I*log(-I*a + x)/2 - I*log(I*a + x)/2 def test_issue_4892a(): A, z = symbols('A z') c = Symbol('c', nonzero=True) P1 = -A*exp(-z) P2 = -A/(c*t)*(sin(x)**2 + cos(y)**2) h1 = -sin(x)**2 - cos(y)**2 h2 = -sin(x)**2 + sin(y)**2 - 1 # there is still some non-deterministic behavior in integrate # or trigsimp which permits one of the following assert integrate(c*(P2 - P1), t) in [ c*(-A*(-h1)*log(c*t)/c + A*t*exp(-z)), c*(-A*(-h2)*log(c*t)/c + A*t*exp(-z)), c*( A* h1 *log(c*t)/c + A*t*exp(-z)), c*( A* h2 *log(c*t)/c + A*t*exp(-z)), (A*c*t - A*(-h1)*log(t)*exp(z))*exp(-z), (A*c*t - A*(-h2)*log(t)*exp(z))*exp(-z), ] def test_issue_4892b(): # Issues relating to issue 4596 are making the actual result of this hard # to test. The answer should be something like # # (-sin(y) + sqrt(-72 + 48*cos(y) - 8*cos(y)**2)/2)*log(x + sqrt(-72 + # 48*cos(y) - 8*cos(y)**2)/(2*(3 - cos(y)))) + (-sin(y) - sqrt(-72 + # 48*cos(y) - 8*cos(y)**2)/2)*log(x - sqrt(-72 + 48*cos(y) - # 8*cos(y)**2)/(2*(3 - cos(y)))) + x**2*sin(y)/2 + 2*x*cos(y) expr = (sin(y)*x**3 + 2*cos(y)*x**2 + 12)/(x**2 + 2) assert trigsimp(factor(integrate(expr, x).diff(x) - expr)) == 0 def test_issue_5178(): assert integrate(sin(x)*f(y, z), (x, 0, pi), (y, 0, pi), (z, 0, pi)) == \ 2*Integral(f(y, z), (y, 0, pi), (z, 0, pi)) def test_integrate_series(): f = sin(x).series(x, 0, 10) g = x**2/2 - x**4/24 + x**6/720 - x**8/40320 + x**10/3628800 + O(x**11) assert integrate(f, x) == g assert diff(integrate(f, x), x) == f assert integrate(O(x**5), x) == O(x**6) def test_atom_bug(): from sympy import meijerg from sympy.integrals.heurisch import heurisch assert heurisch(meijerg([], [], [1], [], x), x) is None def test_limit_bug(): z = Symbol('z', zero=False) assert integrate(sin(x*y*z), (x, 0, pi), (y, 0, pi)) == \ (log(z) + EulerGamma + log(pi))/z - Ci(pi**2*z)/z + log(pi)/z def test_issue_4703(): g = Function('g') assert integrate(exp(x)*g(x), x).has(Integral) def test_issue_1888(): f = Function('f') assert integrate(f(x).diff(x)**2, x).has(Integral) # The following tests work using meijerint. def test_issue_3558(): from sympy import Si assert integrate(cos(x*y), (x, -pi/2, pi/2), (y, 0, pi)) == 2*Si(pi**2/2) def test_issue_4422(): assert integrate(1/sqrt(16 + 4*x**2), x) == asinh(x/2) / 2 def test_issue_4493(): from sympy import simplify assert simplify(integrate(x*sqrt(1 + 2*x), x)) == \ sqrt(2*x + 1)*(6*x**2 + x - 1)/15 def test_issue_4737(): assert integrate(sin(x)/x, (x, -oo, oo)) == pi assert integrate(sin(x)/x, (x, 0, oo)) == pi/2 assert integrate(sin(x)/x, x) == Si(x) def test_issue_4992(): # Note: psi in _check_antecedents becomes NaN. from sympy import simplify, expand_func, polygamma, gamma a = Symbol('a', positive=True) assert simplify(expand_func(integrate(exp(-x)*log(x)*x**a, (x, 0, oo)))) == \ (a*polygamma(0, a) + 1)*gamma(a) def test_issue_4487(): from sympy import lowergamma, simplify assert simplify(integrate(exp(-x)*x**y, x)) == lowergamma(y + 1, x) def test_issue_4215(): x = Symbol("x") assert integrate(1/(x**2), (x, -1, 1)) is oo def test_issue_4400(): n = Symbol('n', integer=True, positive=True) assert integrate((x**n)*log(x), x) == \ n*x*x**n*log(x)/(n**2 + 2*n + 1) + x*x**n*log(x)/(n**2 + 2*n + 1) - \ x*x**n/(n**2 + 2*n + 1) def test_issue_6253(): # Note: this used to raise NotImplementedError # Note: psi in _check_antecedents becomes NaN. assert integrate((sqrt(1 - x) + sqrt(1 + x))**2/x, x, meijerg=True) == \ Integral((sqrt(-x + 1) + sqrt(x + 1))**2/x, x) def test_issue_4153(): assert integrate(1/(1 + x + y + z), (x, 0, 1), (y, 0, 1), (z, 0, 1)) in [ -12*log(3) - 3*log(6)/2 + 3*log(8)/2 + 5*log(2) + 7*log(4), 6*log(2) + 8*log(4) - 27*log(3)/2, 22*log(2) - 27*log(3)/2, -12*log(3) - 3*log(6)/2 + 47*log(2)/2] def test_issue_4326(): R, b, h = symbols('R b h') # It doesn't matter if we can do the integral. Just make sure the result # doesn't contain nan. This is really a test against _eval_interval. e = integrate(((h*(x - R + b))/b)*sqrt(R**2 - x**2), (x, R - b, R)) assert not e.has(nan) # See that it evaluates assert not e.has(Integral) def test_powers(): assert integrate(2**x + 3**x, x) == 2**x/log(2) + 3**x/log(3) def test_manual_option(): raises(ValueError, lambda: integrate(1/x, x, manual=True, meijerg=True)) # an example of a function that manual integration cannot handle assert integrate(log(1+x)/x, (x, 0, 1), manual=True).has(Integral) def test_meijerg_option(): raises(ValueError, lambda: integrate(1/x, x, meijerg=True, risch=True)) # an example of a function that meijerg integration cannot handle assert integrate(tan(x), x, meijerg=True) == Integral(tan(x), x) def test_risch_option(): # risch=True only allowed on indefinite integrals raises(ValueError, lambda: integrate(1/log(x), (x, 0, oo), risch=True)) assert integrate(exp(-x**2), x, risch=True) == NonElementaryIntegral(exp(-x**2), x) assert integrate(log(1/x)*y, x, y, risch=True) == y**2*(x*log(1/x)/2 + x/2) assert integrate(erf(x), x, risch=True) == Integral(erf(x), x) # TODO: How to test risch=False? def test_heurisch_option(): raises(ValueError, lambda: integrate(1/x, x, risch=True, heurisch=True)) # an integral that heurisch can handle assert integrate(exp(x**2), x, heurisch=True) == sqrt(pi)*erfi(x)/2 # an integral that heurisch currently cannot handle assert integrate(exp(x)/x, x, heurisch=True) == Integral(exp(x)/x, x) # an integral where heurisch currently hangs, issue 15471 assert integrate(log(x)*cos(log(x))/x**Rational(3, 4), x, heurisch=False) == ( -128*x**Rational(1, 4)*sin(log(x))/289 + 240*x**Rational(1, 4)*cos(log(x))/289 + (16*x**Rational(1, 4)*sin(log(x))/17 + 4*x**Rational(1, 4)*cos(log(x))/17)*log(x)) def test_issue_6828(): f = 1/(1.08*x**2 - 4.3) g = integrate(f, x).diff(x) assert verify_numerically(f, g, tol=1e-12) def test_issue_4803(): x_max = Symbol("x_max") assert integrate(y/pi*exp(-(x_max - x)/cos(a)), x) == \ y*exp((x - x_max)/cos(a))*cos(a)/pi def test_issue_4234(): assert integrate(1/sqrt(1 + tan(x)**2)) == tan(x)/sqrt(1 + tan(x)**2) def test_issue_4492(): assert simplify(integrate(x**2 * sqrt(5 - x**2), x)) == Piecewise( (I*(2*x**5 - 15*x**3 + 25*x - 25*sqrt(x**2 - 5)*acosh(sqrt(5)*x/5)) / (8*sqrt(x**2 - 5)), 1 < Abs(x**2)/5), ((-2*x**5 + 15*x**3 - 25*x + 25*sqrt(-x**2 + 5)*asin(sqrt(5)*x/5)) / (8*sqrt(-x**2 + 5)), True)) def test_issue_2708(): # This test needs to use an integration function that can # not be evaluated in closed form. Update as needed. f = 1/(a + z + log(z)) integral_f = NonElementaryIntegral(f, (z, 2, 3)) assert Integral(f, (z, 2, 3)).doit() == integral_f assert integrate(f + exp(z), (z, 2, 3)) == integral_f - exp(2) + exp(3) assert integrate(2*f + exp(z), (z, 2, 3)) == \ 2*integral_f - exp(2) + exp(3) assert integrate(exp(1.2*n*s*z*(-t + z)/t), (z, 0, x)) == \ NonElementaryIntegral(exp(-1.2*n*s*z)*exp(1.2*n*s*z**2/t), (z, 0, x)) def test_issue_2884(): f = (4.000002016020*x + 4.000002016020*y + 4.000006024032)*exp(10.0*x) e = integrate(f, (x, 0.1, 0.2)) assert str(e) == '1.86831064982608*y + 2.16387491480008' def test_issue_8368(): assert integrate(exp(-s*x)*cosh(x), (x, 0, oo)) == \ Piecewise( ( pi*Piecewise( ( -s/(pi*(-s**2 + 1)), Abs(s**2) < 1), ( 1/(pi*s*(1 - 1/s**2)), Abs(s**(-2)) < 1), ( meijerg( ((S.Half,), (0, 0)), ((0, S.Half), (0,)), polar_lift(s)**2), True) ), And( Abs(periodic_argument(polar_lift(s)**2, oo)) < pi, cos(Abs(periodic_argument(polar_lift(s)**2, oo))/2)*sqrt(Abs(s**2)) - 1 > 0, Ne(s**2, 1)) ), ( Integral(exp(-s*x)*cosh(x), (x, 0, oo)), True)) assert integrate(exp(-s*x)*sinh(x), (x, 0, oo)) == \ Piecewise( ( -1/(s + 1)/2 - 1/(-s + 1)/2, And( Ne(1/s, 1), Abs(periodic_argument(s, oo)) < pi/2, Abs(periodic_argument(s, oo)) <= pi/2, cos(Abs(periodic_argument(s, oo)))*Abs(s) - 1 > 0)), ( Integral(exp(-s*x)*sinh(x), (x, 0, oo)), True)) def test_issue_8901(): assert integrate(sinh(1.0*x)) == 1.0*cosh(1.0*x) assert integrate(tanh(1.0*x)) == 1.0*x - 1.0*log(tanh(1.0*x) + 1) assert integrate(tanh(x)) == x - log(tanh(x) + 1) @slow def test_issue_8945(): assert integrate(sin(x)**3/x, (x, 0, 1)) == -Si(3)/4 + 3*Si(1)/4 assert integrate(sin(x)**3/x, (x, 0, oo)) == pi/4 assert integrate(cos(x)**2/x**2, x) == -Si(2*x) - cos(2*x)/(2*x) - 1/(2*x) @slow def test_issue_7130(): if ON_TRAVIS: skip("Too slow for travis.") i, L, a, b = symbols('i L a b') integrand = (cos(pi*i*x/L)**2 / (a + b*x)).rewrite(exp) assert x not in integrate(integrand, (x, 0, L)).free_symbols def test_issue_10567(): a, b, c, t = symbols('a b c t') vt = Matrix([a*t, b, c]) assert integrate(vt, t) == Integral(vt, t).doit() assert integrate(vt, t) == Matrix([[a*t**2/2], [b*t], [c*t]]) def test_issue_11856(): t = symbols('t') assert integrate(sinc(pi*t), t) == Si(pi*t)/pi @slow def test_issue_11876(): assert integrate(sqrt(log(1/x)), (x, 0, 1)) == sqrt(pi)/2 def test_issue_4950(): assert integrate((-60*exp(x) - 19.2*exp(4*x))*exp(4*x), x) ==\ -2.4*exp(8*x) - 12.0*exp(5*x) def test_issue_4968(): assert integrate(sin(log(x**2))) == x*sin(2*log(x))/5 - 2*x*cos(2*log(x))/5 def test_singularities(): assert integrate(1/x**2, (x, -oo, oo)) is oo assert integrate(1/x**2, (x, -1, 1)) is oo assert integrate(1/(x - 1)**2, (x, -2, 2)) is oo assert integrate(1/x**2, (x, 1, -1)) is -oo assert integrate(1/(x - 1)**2, (x, 2, -2)) is -oo def test_issue_12645(): x, y = symbols('x y', real=True) assert (integrate(sin(x*x*x + y*y), (x, -sqrt(pi - y*y), sqrt(pi - y*y)), (y, -sqrt(pi), sqrt(pi))) == Integral(sin(x**3 + y**2), (x, -sqrt(-y**2 + pi), sqrt(-y**2 + pi)), (y, -sqrt(pi), sqrt(pi)))) def test_issue_12677(): assert integrate(sin(x) / (cos(x)**3) , (x, 0, pi/6)) == Rational(1,6) def test_issue_14078(): assert integrate((cos(3*x)-cos(x))/x, (x, 0, oo)) == -log(3) def test_issue_14064(): assert integrate(1/cosh(x), (x, 0, oo)) == pi/2 def test_issue_14027(): assert integrate(1/(1 + exp(x - S.Half)/(1 + exp(x))), x) == \ x - exp(S.Half)*log(exp(x) + exp(S.Half)/(1 + exp(S.Half)))/(exp(S.Half) + E) def test_issue_8170(): assert integrate(tan(x), (x, 0, pi/2)) is S.Infinity def test_issue_8440_14040(): assert integrate(1/x, (x, -1, 1)) is S.NaN assert integrate(1/(x + 1), (x, -2, 3)) is S.NaN def test_issue_14096(): assert integrate(1/(x + y)**2, (x, 0, 1)) == -1/(y + 1) + 1/y assert integrate(1/(1 + x + y + z)**2, (x, 0, 1), (y, 0, 1), (z, 0, 1)) == \ -4*log(4) - 6*log(2) + 9*log(3) def test_issue_14144(): assert Abs(integrate(1/sqrt(1 - x**3), (x, 0, 1)).n() - 1.402182) < 1e-6 assert Abs(integrate(sqrt(1 - x**3), (x, 0, 1)).n() - 0.841309) < 1e-6 def test_issue_14375(): # This raised a TypeError. The antiderivative has exp_polar, which # may be possible to unpolarify, so the exact output is not asserted here. assert integrate(exp(I*x)*log(x), x).has(Ei) def test_issue_14437(): f = Function('f')(x, y, z) assert integrate(f, (x, 0, 1), (y, 0, 2), (z, 0, 3)) == \ Integral(f, (x, 0, 1), (y, 0, 2), (z, 0, 3)) def test_issue_14470(): assert integrate(1/sqrt(exp(x) + 1), x) == \ log(-1 + 1/sqrt(exp(x) + 1)) - log(1 + 1/sqrt(exp(x) + 1)) def test_issue_14877(): f = exp(1 - exp(x**2)*x + 2*x**2)*(2*x**3 + x)/(1 - exp(x**2)*x)**2 assert integrate(f, x) == \ -exp(2*x**2 - x*exp(x**2) + 1)/(x*exp(3*x**2) - exp(2*x**2)) def test_issue_14782(): f = sqrt(-x**2 + 1)*(-x**2 + x) assert integrate(f, [x, -1, 1]) == - pi / 8 @slow def test_issue_14782_slow(): f = sqrt(-x**2 + 1)*(-x**2 + x) assert integrate(f, [x, 0, 1]) == S.One / 3 - pi / 16 def test_issue_12081(): f = x**(Rational(-3, 2))*exp(-x) assert integrate(f, [x, 0, oo]) is oo def test_issue_15285(): y = 1/x - 1 f = 4*y*exp(-2*y)/x**2 assert integrate(f, [x, 0, 1]) == 1 def test_issue_15432(): assert integrate(x**n * exp(-x) * log(x), (x, 0, oo)).gammasimp() == Piecewise( (gamma(n + 1)*polygamma(0, n) + gamma(n + 1)/n, re(n) + 1 > 0), (Integral(x**n*exp(-x)*log(x), (x, 0, oo)), True)) def test_issue_15124(): omega = IndexedBase('omega') m, p = symbols('m p', cls=Idx) assert integrate(exp(x*I*(omega[m] + omega[p])), x, conds='none') == \ -I*exp(I*x*omega[m])*exp(I*x*omega[p])/(omega[m] + omega[p]) def test_issue_15218(): with warns_deprecated_sympy(): Integral(Eq(x, y)) with warns_deprecated_sympy(): assert Integral(Eq(x, y), x) == Eq(Integral(x, x), Integral(y, x)) with warns_deprecated_sympy(): assert Integral(Eq(x, y), x).doit() == Eq(x**2/2, x*y) with warns_deprecated_sympy(): assert Eq(x, y).integrate(x) == Eq(x**2/2, x*y) # These are not deprecated because they are definite integrals assert integrate(Eq(x, y), (x, 0, 1)) == Eq(S.Half, y) assert Eq(x, y).integrate((x, 0, 1)) == Eq(S.Half, y) def test_issue_15292(): res = integrate(exp(-x**2*cos(2*t)) * cos(x**2*sin(2*t)), (x, 0, oo)) assert isinstance(res, Piecewise) assert gammasimp((res - sqrt(pi)/2 * cos(t)).subs(t, pi/6)) == 0 def test_issue_4514(): assert integrate(sin(2*x)/sin(x), x) == 2*sin(x) def test_issue_15457(): x, a, b = symbols('x a b', real=True) definite = integrate(exp(Abs(x-2)), (x, a, b)) indefinite = integrate(exp(Abs(x-2)), x) assert definite.subs({a: 1, b: 3}) == -2 + 2*E assert indefinite.subs(x, 3) - indefinite.subs(x, 1) == -2 + 2*E assert definite.subs({a: -3, b: -1}) == -exp(3) + exp(5) assert indefinite.subs(x, -1) - indefinite.subs(x, -3) == -exp(3) + exp(5) def test_issue_15431(): assert integrate(x*exp(x)*log(x), x) == \ (x*exp(x) - exp(x))*log(x) - exp(x) + Ei(x) def test_issue_15640_log_substitutions(): f = x/log(x) F = Ei(2*log(x)) assert integrate(f, x) == F and F.diff(x) == f f = x**3/log(x)**2 F = -x**4/log(x) + 4*Ei(4*log(x)) assert integrate(f, x) == F and F.diff(x) == f f = sqrt(log(x))/x**2 F = -sqrt(pi)*erfc(sqrt(log(x)))/2 - sqrt(log(x))/x assert integrate(f, x) == F and F.diff(x) == f def test_issue_15509(): from sympy.vector import CoordSys3D N = CoordSys3D('N') x = N.x assert integrate(cos(a*x + b), (x, x_1, x_2), heurisch=True) == Piecewise( (-sin(a*x_1 + b)/a + sin(a*x_2 + b)/a, (a > -oo) & (a < oo) & Ne(a, 0)), \ (-x_1*cos(b) + x_2*cos(b), True)) def test_issue_4311_fast(): x = symbols('x', real=True) assert integrate(x*abs(9-x**2), x) == Piecewise( (x**4/4 - 9*x**2/2, x <= -3), (-x**4/4 + 9*x**2/2 - Rational(81, 2), x <= 3), (x**4/4 - 9*x**2/2, True)) def test_integrate_with_complex_constants(): K = Symbol('K', real=True, positive=True) x = Symbol('x', real=True) m = Symbol('m', real=True) assert integrate(exp(-I*K*x**2+m*x), x) == sqrt(I)*sqrt(pi)*exp(-I*m**2 /(4*K))*erfi((-2*I*K*x + m)/(2*sqrt(K)*sqrt(-I)))/(2*sqrt(K)) assert integrate(1/(1 + I*x**2), x) == -sqrt(I)*log(x - sqrt(I))/2 +\ sqrt(I)*log(x + sqrt(I))/2 assert integrate(exp(-I*x**2), x) == sqrt(pi)*erf(sqrt(I)*x)/(2*sqrt(I)) def test_issue_14241(): x = Symbol('x') n = Symbol('n', positive=True, integer=True) assert integrate(n * x ** (n - 1) / (x + 1), x) == \ n**2*x**n*lerchphi(x*exp_polar(I*pi), 1, n)*gamma(n)/gamma(n + 1) def test_issue_13112(): assert integrate(sin(t)**2 / (5 - 4*cos(t)), [t, 0, 2*pi]) == pi / 4 def test_issue_14709b(): h = Symbol('h', positive=True) i = integrate(x*acos(1 - 2*x/h), (x, 0, h)) assert i == 5*h**2*pi/16 def test_issue_8614(): x = Symbol('x') t = Symbol('t') assert integrate(exp(t)/t, (t, -oo, x)) == Ei(x) assert integrate((exp(-x) - exp(-2*x))/x, (x, 0, oo)) == log(2) def test_issue_15494(): s = symbols('s', real=True, positive=True) integrand = (exp(s/2) - 2*exp(1.6*s) + exp(s))*exp(s) solution = integrate(integrand, s) assert solution != S.NaN # Not sure how to test this properly as it is a symbolic expression with floats # assert str(solution) == '0.666666666666667*exp(1.5*s) + 0.5*exp(2.0*s) - 0.769230769230769*exp(2.6*s)' # Maybe assert abs(solution.subs(s, 1) - (-3.67440080236188)) <= 1e-8 integrand = (exp(s/2) - 2*exp(S(8)/5*s) + exp(s))*exp(s) assert integrate(integrand, s) == -10*exp(13*s/5)/13 + 2*exp(3*s/2)/3 + exp(2*s)/2 def test_li_integral(): y = Symbol('y') assert Integral(li(y*x**2), x).doit() == Piecewise( (x*li(x**2*y) - x*Ei(3*log(x) + 3*log(y)/2)/(sqrt(y)*sqrt(x**2)), Ne(y, 0)), (0, True)) def test_issue_17473(): x = Symbol('x') n = Symbol('n') assert integrate(sin(x**n), x) == \ x*x**n*gamma(S(1)/2 + 1/(2*n))*hyper((S(1)/2 + 1/(2*n),), (S(3)/2, S(3)/2 + 1/(2*n)), -x**(2*n)/4)/(2*n*gamma(S(3)/2 + 1/(2*n))) def test_issue_17671(): assert integrate(log(log(x)) / x**2, [x, 1, oo]) == -EulerGamma assert integrate(log(log(x)) / x**3, [x, 1, oo]) == -log(2)/2 - EulerGamma/2 assert integrate(log(log(x)) / x**10, [x, 1, oo]) == -2*log(3)/9 - EulerGamma/9 def test_issue_2975(): w = Symbol('w') C = Symbol('C') y = Symbol('y') assert integrate(1/(y**2+C)**(S(3)/2), (y, -w/2, w/2)) == w/(C**(S(3)/2)*sqrt(1 + w**2/(4*C))) def test_issue_7827(): x, n, M = symbols('x n M') N = Symbol('N', integer=True) assert integrate(summation(x*n, (n, 1, N)), x) == x**2*(N**2/4 + N/4) assert integrate(summation(x*sin(n), (n,1,N)), x) == \ Sum(x**2*sin(n)/2, (n, 1, N)) assert integrate(summation(sin(n*x), (n,1,N)), x) == \ Sum(Piecewise((-cos(n*x)/n, Ne(n, 0)), (0, True)), (n, 1, N)) assert integrate(integrate(summation(sin(n*x), (n,1,N)), x), x) == \ Piecewise((Sum(Piecewise((-sin(n*x)/n**2, Ne(n, 0)), (-x/n, True)), (n, 1, N)), (n > -oo) & (n < oo) & Ne(n, 0)), (0, True)) assert integrate(Sum(x, (n, 1, M)), x) == M*x**2/2 raises(ValueError, lambda: integrate(Sum(x, (x, y, n)), y)) raises(ValueError, lambda: integrate(Sum(x, (x, 1, n)), n)) raises(ValueError, lambda: integrate(Sum(x, (x, 1, y)), x)) def test_issue_4231(): f = (1 + 2*x + sqrt(x + log(x))*(1 + 3*x) + x**2)/(x*(x + sqrt(x + log(x)))*sqrt(x + log(x))) assert integrate(f, x) == 2*sqrt(x + log(x)) + 2*log(x + sqrt(x + log(x))) def test_issue_17841(): f = diff(1/(x**2+x+I), x) assert integrate(f, x) == 1/(x**2 + x + I)
86c86fe47761e0a8391155084bca9af85b1a7e1fcc3adcdd05a77187021906c6
"""Most of these tests come from the examples in Bronstein's book.""" from sympy import (Poly, I, S, Function, log, symbols, exp, tan, sqrt, Symbol, Lambda, sin, Ne, Piecewise, factor, expand_log, cancel, diff, pi, atan, Rational) from sympy.integrals.risch import (gcdex_diophantine, frac_in, as_poly_1t, derivation, splitfactor, splitfactor_sqf, canonical_representation, hermite_reduce, polynomial_reduce, residue_reduce, residue_reduce_to_basic, integrate_primitive, integrate_hyperexponential_polynomial, integrate_hyperexponential, integrate_hypertangent_polynomial, integrate_nonlinear_no_specials, integer_powers, DifferentialExtension, risch_integrate, DecrementLevel, NonElementaryIntegral, recognize_log_derivative, recognize_derivative, laurent_series) from sympy.testing.pytest import raises from sympy.abc import x, t, nu, z, a, y t0, t1, t2 = symbols('t:3') i = Symbol('i') def test_gcdex_diophantine(): assert gcdex_diophantine(Poly(x**4 - 2*x**3 - 6*x**2 + 12*x + 15), Poly(x**3 + x**2 - 4*x - 4), Poly(x**2 - 1)) == \ (Poly((-x**2 + 4*x - 3)/5), Poly((x**3 - 7*x**2 + 16*x - 10)/5)) assert gcdex_diophantine(Poly(x**3 + 6*x + 7), Poly(x**2 + 3*x + 2), Poly(x + 1)) == \ (Poly(1/13, x, domain='QQ'), Poly(-1/13*x + 3/13, x, domain='QQ')) def test_frac_in(): assert frac_in(Poly((x + 1)/x*t, t), x) == \ (Poly(t*x + t, x), Poly(x, x)) assert frac_in((x + 1)/x*t, x) == \ (Poly(t*x + t, x), Poly(x, x)) assert frac_in((Poly((x + 1)/x*t, t), Poly(t + 1, t)), x) == \ (Poly(t*x + t, x), Poly((1 + t)*x, x)) raises(ValueError, lambda: frac_in((x + 1)/log(x)*t, x)) assert frac_in(Poly((2 + 2*x + x*(1 + x))/(1 + x)**2, t), x, cancel=True) == \ (Poly(x + 2, x), Poly(x + 1, x)) def test_as_poly_1t(): assert as_poly_1t(2/t + t, t, z) in [ Poly(t + 2*z, t, z), Poly(t + 2*z, z, t)] assert as_poly_1t(2/t + 3/t**2, t, z) in [ Poly(2*z + 3*z**2, t, z), Poly(2*z + 3*z**2, z, t)] assert as_poly_1t(2/((exp(2) + 1)*t), t, z) in [ Poly(2/(exp(2) + 1)*z, t, z), Poly(2/(exp(2) + 1)*z, z, t)] assert as_poly_1t(2/((exp(2) + 1)*t) + t, t, z) in [ Poly(t + 2/(exp(2) + 1)*z, t, z), Poly(t + 2/(exp(2) + 1)*z, z, t)] assert as_poly_1t(S.Zero, t, z) == Poly(0, t, z) def test_derivation(): p = Poly(4*x**4*t**5 + (-4*x**3 - 4*x**4)*t**4 + (-3*x**2 + 2*x**3)*t**3 + (2*x + 7*x**2 + 2*x**3)*t**2 + (1 - 4*x - 4*x**2)*t - 1 + 2*x, t) DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(-t**2 - 3/(2*x)*t + 1/(2*x), t)]}) assert derivation(p, DE) == Poly(-20*x**4*t**6 + (2*x**3 + 16*x**4)*t**5 + (21*x**2 + 12*x**3)*t**4 + (x*Rational(7, 2) - 25*x**2 - 12*x**3)*t**3 + (-5 - x*Rational(15, 2) + 7*x**2)*t**2 - (3 - 8*x - 10*x**2 - 4*x**3)/(2*x)*t + (1 - 4*x**2)/(2*x), t) assert derivation(Poly(1, t), DE) == Poly(0, t) assert derivation(Poly(t, t), DE) == DE.d assert derivation(Poly(t**2 + 1/x*t + (1 - 2*x)/(4*x**2), t), DE) == \ Poly(-2*t**3 - 4/x*t**2 - (5 - 2*x)/(2*x**2)*t - (1 - 2*x)/(2*x**3), t, domain='ZZ(x)') DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1/x, t1), Poly(t, t)]}) assert derivation(Poly(x*t*t1, t), DE) == Poly(t*t1 + x*t*t1 + t, t) assert derivation(Poly(x*t*t1, t), DE, coefficientD=True) == \ Poly((1 + t1)*t, t) DE = DifferentialExtension(extension={'D': [Poly(1, x)]}) assert derivation(Poly(x, x), DE) == Poly(1, x) # Test basic option assert derivation((x + 1)/(x - 1), DE, basic=True) == -2/(1 - 2*x + x**2) DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t, t)]}) assert derivation((t + 1)/(t - 1), DE, basic=True) == -2*t/(1 - 2*t + t**2) assert derivation(t + 1, DE, basic=True) == t def test_splitfactor(): p = Poly(4*x**4*t**5 + (-4*x**3 - 4*x**4)*t**4 + (-3*x**2 + 2*x**3)*t**3 + (2*x + 7*x**2 + 2*x**3)*t**2 + (1 - 4*x - 4*x**2)*t - 1 + 2*x, t, field=True) DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(-t**2 - 3/(2*x)*t + 1/(2*x), t)]}) assert splitfactor(p, DE) == (Poly(4*x**4*t**3 + (-8*x**3 - 4*x**4)*t**2 + (4*x**2 + 8*x**3)*t - 4*x**2, t, domain='ZZ(x)'), Poly(t**2 + 1/x*t + (1 - 2*x)/(4*x**2), t, domain='ZZ(x)')) assert splitfactor(Poly(x, t), DE) == (Poly(x, t), Poly(1, t)) r = Poly(-4*x**4*z**2 + 4*x**6*z**2 - z*x**3 - 4*x**5*z**3 + 4*x**3*z**3 + x**4 + z*x**5 - x**6, t) DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1/x, t)]}) assert splitfactor(r, DE, coefficientD=True) == \ (Poly(x*z - x**2 - z*x**3 + x**4, t), Poly(-x**2 + 4*x**2*z**2, t)) assert splitfactor_sqf(r, DE, coefficientD=True) == \ (((Poly(x*z - x**2 - z*x**3 + x**4, t), 1),), ((Poly(-x**2 + 4*x**2*z**2, t), 1),)) assert splitfactor(Poly(0, t), DE) == (Poly(0, t), Poly(1, t)) assert splitfactor_sqf(Poly(0, t), DE) == (((Poly(0, t), 1),), ()) def test_canonical_representation(): DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1 + t**2, t)]}) assert canonical_representation(Poly(x - t, t), Poly(t**2, t), DE) == \ (Poly(0, t, domain='ZZ[x]'), (Poly(0, t, domain='QQ[x]'), Poly(1, t, domain='ZZ')), (Poly(-t + x, t, domain='QQ[x]'), Poly(t**2, t))) DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t**2 + 1, t)]}) assert canonical_representation(Poly(t**5 + t**3 + x**2*t + 1, t), Poly((t**2 + 1)**3, t), DE) == \ (Poly(0, t, domain='ZZ[x]'), (Poly(t**5 + t**3 + x**2*t + 1, t, domain='QQ[x]'), Poly(t**6 + 3*t**4 + 3*t**2 + 1, t, domain='QQ')), (Poly(0, t, domain='QQ[x]'), Poly(1, t, domain='QQ'))) def test_hermite_reduce(): DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t**2 + 1, t)]}) assert hermite_reduce(Poly(x - t, t), Poly(t**2, t), DE) == \ ((Poly(-x, t, domain='QQ[x]'), Poly(t, t, domain='QQ[x]')), (Poly(0, t, domain='QQ[x]'), Poly(1, t, domain='QQ[x]')), (Poly(-x, t, domain='QQ[x]'), Poly(1, t, domain='QQ[x]'))) DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(-t**2 - t/x - (1 - nu**2/x**2), t)]}) assert hermite_reduce( Poly(x**2*t**5 + x*t**4 - nu**2*t**3 - x*(x**2 + 1)*t**2 - (x**2 - nu**2)*t - x**5/4, t), Poly(x**2*t**4 + x**2*(x**2 + 2)*t**2 + x**2 + x**4 + x**6/4, t), DE) == \ ((Poly(-x**2 - 4, t, domain='ZZ(x,nu)'), Poly(4*t**2 + 2*x**2 + 4, t, domain='ZZ(x,nu)')), (Poly((-2*nu**2 - x**4)*t - (2*x**3 + 2*x), t, domain='ZZ(x,nu)'), Poly(2*x**2*t**2 + x**4 + 2*x**2, t, domain='ZZ(x,nu)')), (Poly(x*t + 1, t, domain='ZZ(x,nu)'), Poly(x, t, domain='ZZ(x,nu)'))) DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1/x, t)]}) a = Poly((-2 + 3*x)*t**3 + (-1 + x)*t**2 + (-4*x + 2*x**2)*t + x**2, t) d = Poly(x*t**6 - 4*x**2*t**5 + 6*x**3*t**4 - 4*x**4*t**3 + x**5*t**2, t) assert hermite_reduce(a, d, DE) == \ ((Poly(3*t**2 + t + 3*x, t, domain='ZZ(x)'), Poly(3*t**4 - 9*x*t**3 + 9*x**2*t**2 - 3*x**3*t, t, domain='ZZ(x)')), (Poly(0, t, domain='ZZ(x)'), Poly(1, t, domain='ZZ(x)')), (Poly(0, t, domain='ZZ(x)'), Poly(1, t, domain='ZZ(x)'))) assert hermite_reduce( Poly(-t**2 + 2*t + 2, t, domain='ZZ(x)'), Poly(-x*t**2 + 2*x*t - x, t, domain='ZZ(x)'), DE) == \ ((Poly(3, t, domain='ZZ(x)'), Poly(t - 1, t, domain='ZZ(x)')), (Poly(0, t, domain='ZZ(x)'), Poly(1, t, domain='ZZ(x)')), (Poly(1, t, domain='ZZ(x)'), Poly(x, t, domain='ZZ(x)'))) assert hermite_reduce( Poly(-x**2*t**6 + (-1 - 2*x**3 + x**4)*t**3 + (-3 - 3*x**4)*t**2 - 2*x*t - x - 3*x**2, t, domain='ZZ(x)'), Poly(x**4*t**6 - 2*x**2*t**3 + 1, t, domain='ZZ(x)'), DE) == \ ((Poly(x**3*t + x**4 + 1, t, domain='ZZ(x)'), Poly(x**3*t**3 - x, t, domain='ZZ(x)')), (Poly(0, t, domain='ZZ(x)'), Poly(1, t, domain='ZZ(x)')), (Poly(-1, t, domain='ZZ(x)'), Poly(x**2, t, domain='ZZ(x)'))) assert hermite_reduce( Poly((-2 + 3*x)*t**3 + (-1 + x)*t**2 + (-4*x + 2*x**2)*t + x**2, t), Poly(x*t**6 - 4*x**2*t**5 + 6*x**3*t**4 - 4*x**4*t**3 + x**5*t**2, t), DE) == \ ((Poly(3*t**2 + t + 3*x, t, domain='ZZ(x)'), Poly(3*t**4 - 9*x*t**3 + 9*x**2*t**2 - 3*x**3*t, t, domain='ZZ(x)')), (Poly(0, t, domain='ZZ(x)'), Poly(1, t, domain='ZZ(x)')), (Poly(0, t, domain='ZZ(x)'), Poly(1, t, domain='ZZ(x)'))) def test_polynomial_reduce(): DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1 + t**2, t)]}) assert polynomial_reduce(Poly(1 + x*t + t**2, t), DE) == \ (Poly(t, t), Poly(x*t, t)) assert polynomial_reduce(Poly(0, t), DE) == \ (Poly(0, t), Poly(0, t)) def test_laurent_series(): DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1, t)]}) a = Poly(36, t) d = Poly((t - 2)*(t**2 - 1)**2, t) F = Poly(t**2 - 1, t) n = 2 assert laurent_series(a, d, F, n, DE) == \ (Poly(-3*t**3 + 3*t**2 - 6*t - 8, t), Poly(t**5 + t**4 - 2*t**3 - 2*t**2 + t + 1, t), [Poly(-3*t**3 - 6*t**2, t, domain='QQ'), Poly(2*t**6 + 6*t**5 - 8*t**3, t, domain='QQ')]) def test_recognize_derivative(): DE = DifferentialExtension(extension={'D': [Poly(1, t)]}) a = Poly(36, t) d = Poly((t - 2)*(t**2 - 1)**2, t) assert recognize_derivative(a, d, DE) == False DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1/x, t)]}) a = Poly(2, t) d = Poly(t**2 - 1, t) assert recognize_derivative(a, d, DE) == False assert recognize_derivative(Poly(x*t, t), Poly(1, t), DE) == True DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t**2 + 1, t)]}) assert recognize_derivative(Poly(t, t), Poly(1, t), DE) == True def test_recognize_log_derivative(): a = Poly(2*x**2 + 4*x*t - 2*t - x**2*t, t) d = Poly((2*x + t)*(t + x**2), t) DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t, t)]}) assert recognize_log_derivative(a, d, DE, z) == True DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1/x, t)]}) assert recognize_log_derivative(Poly(t + 1, t), Poly(t + x, t), DE) == True assert recognize_log_derivative(Poly(2, t), Poly(t**2 - 1, t), DE) == True DE = DifferentialExtension(extension={'D': [Poly(1, x)]}) assert recognize_log_derivative(Poly(1, x), Poly(x**2 - 2, x), DE) == False assert recognize_log_derivative(Poly(1, x), Poly(x**2 + x, x), DE) == True DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t**2 + 1, t)]}) assert recognize_log_derivative(Poly(1, t), Poly(t**2 - 2, t), DE) == False assert recognize_log_derivative(Poly(1, t), Poly(t**2 + t, t), DE) == False def test_residue_reduce(): a = Poly(2*t**2 - t - x**2, t) d = Poly(t**3 - x**2*t, t) DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1/x, t)], 'Tfuncs': [log]}) assert residue_reduce(a, d, DE, z, invert=False) == \ ([(Poly(z**2 - Rational(1, 4), z, domain='ZZ(x)'), Poly((1 + 3*x*z - 6*z**2 - 2*x**2 + 4*x**2*z**2)*t - x*z + x**2 + 2*x**2*z**2 - 2*z*x**3, t, domain='ZZ(z, x)'))], False) assert residue_reduce(a, d, DE, z, invert=True) == \ ([(Poly(z**2 - Rational(1, 4), z, domain='ZZ(x)'), Poly(t + 2*x*z, t))], False) assert residue_reduce(Poly(-2/x, t), Poly(t**2 - 1, t,), DE, z, invert=False) == \ ([(Poly(z**2 - 1, z, domain='QQ'), Poly(-2*z*t/x - 2/x, t, domain='ZZ(z,x)'))], True) ans = residue_reduce(Poly(-2/x, t), Poly(t**2 - 1, t), DE, z, invert=True) assert ans == ([(Poly(z**2 - 1, z, domain='QQ'), Poly(t + z, t))], True) assert residue_reduce_to_basic(ans[0], DE, z) == -log(-1 + log(x)) + log(1 + log(x)) DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(-t**2 - t/x - (1 - nu**2/x**2), t)]}) # TODO: Skip or make faster assert residue_reduce(Poly((-2*nu**2 - x**4)/(2*x**2)*t - (1 + x**2)/x, t), Poly(t**2 + 1 + x**2/2, t), DE, z) == \ ([(Poly(z + S.Half, z, domain='QQ'), Poly(t**2 + 1 + x**2/2, t, domain='ZZ(x,nu)'))], True) DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1 + t**2, t)]}) assert residue_reduce(Poly(-2*x*t + 1 - x**2, t), Poly(t**2 + 2*x*t + 1 + x**2, t), DE, z) == \ ([(Poly(z**2 + Rational(1, 4), z), Poly(t + x + 2*z, t))], True) DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t, t)]}) assert residue_reduce(Poly(t, t), Poly(t + sqrt(2), t), DE, z) == \ ([(Poly(z - 1, z, domain='QQ'), Poly(t + sqrt(2), t))], True) def test_integrate_hyperexponential(): # TODO: Add tests for integrate_hyperexponential() from the book a = Poly((1 + 2*t1 + t1**2 + 2*t1**3)*t**2 + (1 + t1**2)*t + 1 + t1**2, t) d = Poly(1, t) DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1 + t1**2, t1), Poly(t*(1 + t1**2), t)], 'Tfuncs': [tan, Lambda(i, exp(tan(i)))]}) assert integrate_hyperexponential(a, d, DE) == \ (exp(2*tan(x))*tan(x) + exp(tan(x)), 1 + t1**2, True) a = Poly((t1**3 + (x + 1)*t1**2 + t1 + x + 2)*t, t) assert integrate_hyperexponential(a, d, DE) == \ ((x + tan(x))*exp(tan(x)), 0, True) a = Poly(t, t) d = Poly(1, t) DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(2*x*t, t)], 'Tfuncs': [Lambda(i, exp(x**2))]}) assert integrate_hyperexponential(a, d, DE) == \ (0, NonElementaryIntegral(exp(x**2), x), False) DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t, t)], 'Tfuncs': [exp]}) assert integrate_hyperexponential(a, d, DE) == (exp(x), 0, True) a = Poly(25*t**6 - 10*t**5 + 7*t**4 - 8*t**3 + 13*t**2 + 2*t - 1, t) d = Poly(25*t**6 + 35*t**4 + 11*t**2 + 1, t) assert integrate_hyperexponential(a, d, DE) == \ (-(11 - 10*exp(x))/(5 + 25*exp(2*x)) + log(1 + exp(2*x)), -1, True) DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t0, t0), Poly(t0*t, t)], 'Tfuncs': [exp, Lambda(i, exp(exp(i)))]}) assert integrate_hyperexponential(Poly(2*t0*t**2, t), Poly(1, t), DE) == (exp(2*exp(x)), 0, True) DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t0, t0), Poly(-t0*t, t)], 'Tfuncs': [exp, Lambda(i, exp(-exp(i)))]}) assert integrate_hyperexponential(Poly(-27*exp(9) - 162*t0*exp(9) + 27*x*t0*exp(9), t), Poly((36*exp(18) + x**2*exp(18) - 12*x*exp(18))*t, t), DE) == \ (27*exp(exp(x))/(-6*exp(9) + x*exp(9)), 0, True) DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t, t)], 'Tfuncs': [exp]}) assert integrate_hyperexponential(Poly(x**2/2*t, t), Poly(1, t), DE) == \ ((2 - 2*x + x**2)*exp(x)/2, 0, True) assert integrate_hyperexponential(Poly(1 + t, t), Poly(t, t), DE) == \ (-exp(-x), 1, True) # x - exp(-x) assert integrate_hyperexponential(Poly(x, t), Poly(t + 1, t), DE) == \ (0, NonElementaryIntegral(x/(1 + exp(x)), x), False) DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1/x, t0), Poly(2*x*t1, t1)], 'Tfuncs': [log, Lambda(i, exp(i**2))]}) elem, nonelem, b = integrate_hyperexponential(Poly((8*x**7 - 12*x**5 + 6*x**3 - x)*t1**4 + (8*t0*x**7 - 8*t0*x**6 - 4*t0*x**5 + 2*t0*x**3 + 2*t0*x**2 - t0*x + 24*x**8 - 36*x**6 - 4*x**5 + 22*x**4 + 4*x**3 - 7*x**2 - x + 1)*t1**3 + (8*t0*x**8 - 4*t0*x**6 - 16*t0*x**5 - 2*t0*x**4 + 12*t0*x**3 + t0*x**2 - 2*t0*x + 24*x**9 - 36*x**7 - 8*x**6 + 22*x**5 + 12*x**4 - 7*x**3 - 6*x**2 + x + 1)*t1**2 + (8*t0*x**8 - 8*t0*x**6 - 16*t0*x**5 + 6*t0*x**4 + 10*t0*x**3 - 2*t0*x**2 - t0*x + 8*x**10 - 12*x**8 - 4*x**7 + 2*x**6 + 12*x**5 + 3*x**4 - 9*x**3 - x**2 + 2*x)*t1 + 8*t0*x**7 - 12*t0*x**6 - 4*t0*x**5 + 8*t0*x**4 - t0*x**2 - 4*x**7 + 4*x**6 + 4*x**5 - 4*x**4 - x**3 + x**2, t1), Poly((8*x**7 - 12*x**5 + 6*x**3 - x)*t1**4 + (24*x**8 + 8*x**7 - 36*x**6 - 12*x**5 + 18*x**4 + 6*x**3 - 3*x**2 - x)*t1**3 + (24*x**9 + 24*x**8 - 36*x**7 - 36*x**6 + 18*x**5 + 18*x**4 - 3*x**3 - 3*x**2)*t1**2 + (8*x**10 + 24*x**9 - 12*x**8 - 36*x**7 + 6*x**6 + 18*x**5 - x**4 - 3*x**3)*t1 + 8*x**10 - 12*x**8 + 6*x**6 - x**4, t1), DE) assert factor(elem) == -((x - 1)*log(x)/((x + exp(x**2))*(2*x**2 - 1))) assert (nonelem, b) == (NonElementaryIntegral(exp(x**2)/(exp(x**2) + 1), x), False) def test_integrate_hyperexponential_polynomial(): # Without proper cancellation within integrate_hyperexponential_polynomial(), # this will take a long time to complete, and will return a complicated # expression p = Poly((-28*x**11*t0 - 6*x**8*t0 + 6*x**9*t0 - 15*x**8*t0**2 + 15*x**7*t0**2 + 84*x**10*t0**2 - 140*x**9*t0**3 - 20*x**6*t0**3 + 20*x**7*t0**3 - 15*x**6*t0**4 + 15*x**5*t0**4 + 140*x**8*t0**4 - 84*x**7*t0**5 - 6*x**4*t0**5 + 6*x**5*t0**5 + x**3*t0**6 - x**4*t0**6 + 28*x**6*t0**6 - 4*x**5*t0**7 + x**9 - x**10 + 4*x**12)/(-8*x**11*t0 + 28*x**10*t0**2 - 56*x**9*t0**3 + 70*x**8*t0**4 - 56*x**7*t0**5 + 28*x**6*t0**6 - 8*x**5*t0**7 + x**4*t0**8 + x**12)*t1**2 + (-28*x**11*t0 - 12*x**8*t0 + 12*x**9*t0 - 30*x**8*t0**2 + 30*x**7*t0**2 + 84*x**10*t0**2 - 140*x**9*t0**3 - 40*x**6*t0**3 + 40*x**7*t0**3 - 30*x**6*t0**4 + 30*x**5*t0**4 + 140*x**8*t0**4 - 84*x**7*t0**5 - 12*x**4*t0**5 + 12*x**5*t0**5 - 2*x**4*t0**6 + 2*x**3*t0**6 + 28*x**6*t0**6 - 4*x**5*t0**7 + 2*x**9 - 2*x**10 + 4*x**12)/(-8*x**11*t0 + 28*x**10*t0**2 - 56*x**9*t0**3 + 70*x**8*t0**4 - 56*x**7*t0**5 + 28*x**6*t0**6 - 8*x**5*t0**7 + x**4*t0**8 + x**12)*t1 + (-2*x**2*t0 + 2*x**3*t0 + x*t0**2 - x**2*t0**2 + x**3 - x**4)/(-4*x**5*t0 + 6*x**4*t0**2 - 4*x**3*t0**3 + x**2*t0**4 + x**6), t1, z, expand=False) DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1/x, t0), Poly(2*x*t1, t1)]}) assert integrate_hyperexponential_polynomial(p, DE, z) == ( Poly((x - t0)*t1**2 + (-2*t0 + 2*x)*t1, t1), Poly(-2*x*t0 + x**2 + t0**2, t1), True) DE = DifferentialExtension(extension={'D':[Poly(1, x), Poly(t0, t0)]}) assert integrate_hyperexponential_polynomial(Poly(0, t0), DE, z) == ( Poly(0, t0), Poly(1, t0), True) def test_integrate_hyperexponential_returns_piecewise(): a, b = symbols('a b') DE = DifferentialExtension(a**x, x) assert integrate_hyperexponential(DE.fa, DE.fd, DE) == (Piecewise( (exp(x*log(a))/log(a), Ne(log(a), 0)), (x, True)), 0, True) DE = DifferentialExtension(a**(b*x), x) assert integrate_hyperexponential(DE.fa, DE.fd, DE) == (Piecewise( (exp(b*x*log(a))/(b*log(a)), Ne(b*log(a), 0)), (x, True)), 0, True) DE = DifferentialExtension(exp(a*x), x) assert integrate_hyperexponential(DE.fa, DE.fd, DE) == (Piecewise( (exp(a*x)/a, Ne(a, 0)), (x, True)), 0, True) DE = DifferentialExtension(x*exp(a*x), x) assert integrate_hyperexponential(DE.fa, DE.fd, DE) == (Piecewise( ((a*x - 1)*exp(a*x)/a**2, Ne(a**2, 0)), (x**2/2, True)), 0, True) DE = DifferentialExtension(x**2*exp(a*x), x) assert integrate_hyperexponential(DE.fa, DE.fd, DE) == (Piecewise( ((x**2*a**2 - 2*a*x + 2)*exp(a*x)/a**3, Ne(a**3, 0)), (x**3/3, True)), 0, True) DE = DifferentialExtension(x**y + z, y) assert integrate_hyperexponential(DE.fa, DE.fd, DE) == (Piecewise( (exp(log(x)*y)/log(x), Ne(log(x), 0)), (y, True)), z, True) DE = DifferentialExtension(x**y + z + x**(2*y), y) assert integrate_hyperexponential(DE.fa, DE.fd, DE) == (Piecewise( ((exp(2*log(x)*y)*log(x) + 2*exp(log(x)*y)*log(x))/(2*log(x)**2), Ne(2*log(x)**2, 0)), (2*y, True), ), z, True) # TODO: Add a test where two different parts of the extension use a # Piecewise, like y**x + z**x. def test_issue_13947(): a, t, s = symbols('a t s') assert risch_integrate(2**(-pi)/(2**t + 1), t) == \ 2**(-pi)*t - 2**(-pi)*log(2**t + 1)/log(2) assert risch_integrate(a**(t - s)/(a**t + 1), t) == \ exp(-s*log(a))*log(a**t + 1)/log(a) def test_integrate_primitive(): DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1/x, t)], 'Tfuncs': [log]}) assert integrate_primitive(Poly(t, t), Poly(1, t), DE) == (x*log(x), -1, True) assert integrate_primitive(Poly(x, t), Poly(t, t), DE) == (0, NonElementaryIntegral(x/log(x), x), False) DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1/x, t1), Poly(1/(x + 1), t2)], 'Tfuncs': [log, Lambda(i, log(i + 1))]}) assert integrate_primitive(Poly(t1, t2), Poly(t2, t2), DE) == \ (0, NonElementaryIntegral(log(x)/log(1 + x), x), False) DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1/x, t1), Poly(1/(x*t1), t2)], 'Tfuncs': [log, Lambda(i, log(log(i)))]}) assert integrate_primitive(Poly(t2, t2), Poly(t1, t2), DE) == \ (0, NonElementaryIntegral(log(log(x))/log(x), x), False) DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1/x, t0)], 'Tfuncs': [log]}) assert integrate_primitive(Poly(x**2*t0**3 + (3*x**2 + x)*t0**2 + (3*x**2 + 2*x)*t0 + x**2 + x, t0), Poly(x**2*t0**4 + 4*x**2*t0**3 + 6*x**2*t0**2 + 4*x**2*t0 + x**2, t0), DE) == \ (-1/(log(x) + 1), NonElementaryIntegral(1/(log(x) + 1), x), False) def test_integrate_hypertangent_polynomial(): DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t**2 + 1, t)]}) assert integrate_hypertangent_polynomial(Poly(t**2 + x*t + 1, t), DE) == \ (Poly(t, t), Poly(x/2, t)) DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(a*(t**2 + 1), t)]}) assert integrate_hypertangent_polynomial(Poly(t**5, t), DE) == \ (Poly(1/(4*a)*t**4 - 1/(2*a)*t**2, t), Poly(1/(2*a), t)) def test_integrate_nonlinear_no_specials(): a, d, = Poly(x**2*t**5 + x*t**4 - nu**2*t**3 - x*(x**2 + 1)*t**2 - (x**2 - nu**2)*t - x**5/4, t), Poly(x**2*t**4 + x**2*(x**2 + 2)*t**2 + x**2 + x**4 + x**6/4, t) # f(x) == phi_nu(x), the logarithmic derivative of J_v, the Bessel function, # which has no specials (see Chapter 5, note 4 of Bronstein's book). f = Function('phi_nu') DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(-t**2 - t/x - (1 - nu**2/x**2), t)], 'Tfuncs': [f]}) assert integrate_nonlinear_no_specials(a, d, DE) == \ (-log(1 + f(x)**2 + x**2/2)/2 - (4 + x**2)/(4 + 2*x**2 + 4*f(x)**2), True) assert integrate_nonlinear_no_specials(Poly(t, t), Poly(1, t), DE) == \ (0, False) def test_integer_powers(): assert integer_powers([x, x/2, x**2 + 1, x*Rational(2, 3)]) == [ (x/6, [(x, 6), (x/2, 3), (x*Rational(2, 3), 4)]), (1 + x**2, [(1 + x**2, 1)])] def test_DifferentialExtension_exp(): assert DifferentialExtension(exp(x) + exp(x**2), x)._important_attrs == \ (Poly(t1 + t0, t1), Poly(1, t1), [Poly(1, x,), Poly(t0, t0), Poly(2*x*t1, t1)], [x, t0, t1], [Lambda(i, exp(i)), Lambda(i, exp(i**2))], [], [None, 'exp', 'exp'], [None, x, x**2]) assert DifferentialExtension(exp(x) + exp(2*x), x)._important_attrs == \ (Poly(t0**2 + t0, t0), Poly(1, t0), [Poly(1, x), Poly(t0, t0)], [x, t0], [Lambda(i, exp(i))], [], [None, 'exp'], [None, x]) assert DifferentialExtension(exp(x) + exp(x/2), x)._important_attrs == \ (Poly(t0**2 + t0, t0), Poly(1, t0), [Poly(1, x), Poly(t0/2, t0)], [x, t0], [Lambda(i, exp(i/2))], [], [None, 'exp'], [None, x/2]) assert DifferentialExtension(exp(x) + exp(x**2) + exp(x + x**2), x)._important_attrs == \ (Poly((1 + t0)*t1 + t0, t1), Poly(1, t1), [Poly(1, x), Poly(t0, t0), Poly(2*x*t1, t1)], [x, t0, t1], [Lambda(i, exp(i)), Lambda(i, exp(i**2))], [], [None, 'exp', 'exp'], [None, x, x**2]) assert DifferentialExtension(exp(x) + exp(x**2) + exp(x + x**2 + 1), x)._important_attrs == \ (Poly((1 + S.Exp1*t0)*t1 + t0, t1), Poly(1, t1), [Poly(1, x), Poly(t0, t0), Poly(2*x*t1, t1)], [x, t0, t1], [Lambda(i, exp(i)), Lambda(i, exp(i**2))], [], [None, 'exp', 'exp'], [None, x, x**2]) assert DifferentialExtension(exp(x) + exp(x**2) + exp(x/2 + x**2), x)._important_attrs == \ (Poly((t0 + 1)*t1 + t0**2, t1), Poly(1, t1), [Poly(1, x), Poly(t0/2, t0), Poly(2*x*t1, t1)], [x, t0, t1], [Lambda(i, exp(i/2)), Lambda(i, exp(i**2))], [(exp(x/2), sqrt(exp(x)))], [None, 'exp', 'exp'], [None, x/2, x**2]) assert DifferentialExtension(exp(x) + exp(x**2) + exp(x/2 + x**2 + 3), x)._important_attrs == \ (Poly((t0*exp(3) + 1)*t1 + t0**2, t1), Poly(1, t1), [Poly(1, x), Poly(t0/2, t0), Poly(2*x*t1, t1)], [x, t0, t1], [Lambda(i, exp(i/2)), Lambda(i, exp(i**2))], [(exp(x/2), sqrt(exp(x)))], [None, 'exp', 'exp'], [None, x/2, x**2]) assert DifferentialExtension(sqrt(exp(x)), x)._important_attrs == \ (Poly(t0, t0), Poly(1, t0), [Poly(1, x), Poly(t0/2, t0)], [x, t0], [Lambda(i, exp(i/2))], [(exp(x/2), sqrt(exp(x)))], [None, 'exp'], [None, x/2]) assert DifferentialExtension(exp(x/2), x)._important_attrs == \ (Poly(t0, t0), Poly(1, t0), [Poly(1, x), Poly(t0/2, t0)], [x, t0], [Lambda(i, exp(i/2))], [], [None, 'exp'], [None, x/2]) def test_DifferentialExtension_log(): assert DifferentialExtension(log(x)*log(x + 1)*log(2*x**2 + 2*x), x)._important_attrs == \ (Poly(t0*t1**2 + (t0*log(2) + t0**2)*t1, t1), Poly(1, t1), [Poly(1, x), Poly(1/x, t0), Poly(1/(x + 1), t1, expand=False)], [x, t0, t1], [Lambda(i, log(i)), Lambda(i, log(i + 1))], [], [None, 'log', 'log'], [None, x, x + 1]) assert DifferentialExtension(x**x*log(x), x)._important_attrs == \ (Poly(t0*t1, t1), Poly(1, t1), [Poly(1, x), Poly(1/x, t0), Poly((1 + t0)*t1, t1)], [x, t0, t1], [Lambda(i, log(i)), Lambda(i, exp(t0*i))], [(exp(x*log(x)), x**x)], [None, 'log', 'exp'], [None, x, t0*x]) def test_DifferentialExtension_symlog(): # See comment on test_risch_integrate below assert DifferentialExtension(log(x**x), x)._important_attrs == \ (Poly(t0*x, t1), Poly(1, t1), [Poly(1, x), Poly(1/x, t0), Poly((t0 + 1)*t1, t1)], [x, t0, t1], [Lambda(i, log(i)), Lambda(i, exp(i*t0))], [(exp(x*log(x)), x**x)], [None, 'log', 'exp'], [None, x, t0*x]) assert DifferentialExtension(log(x**y), x)._important_attrs == \ (Poly(y*t0, t0), Poly(1, t0), [Poly(1, x), Poly(1/x, t0)], [x, t0], [Lambda(i, log(i))], [(y*log(x), log(x**y))], [None, 'log'], [None, x]) assert DifferentialExtension(log(sqrt(x)), x)._important_attrs == \ (Poly(t0, t0), Poly(2, t0), [Poly(1, x), Poly(1/x, t0)], [x, t0], [Lambda(i, log(i))], [(log(x)/2, log(sqrt(x)))], [None, 'log'], [None, x]) def test_DifferentialExtension_handle_first(): assert DifferentialExtension(exp(x)*log(x), x, handle_first='log')._important_attrs == \ (Poly(t0*t1, t1), Poly(1, t1), [Poly(1, x), Poly(1/x, t0), Poly(t1, t1)], [x, t0, t1], [Lambda(i, log(i)), Lambda(i, exp(i))], [], [None, 'log', 'exp'], [None, x, x]) assert DifferentialExtension(exp(x)*log(x), x, handle_first='exp')._important_attrs == \ (Poly(t0*t1, t1), Poly(1, t1), [Poly(1, x), Poly(t0, t0), Poly(1/x, t1)], [x, t0, t1], [Lambda(i, exp(i)), Lambda(i, log(i))], [], [None, 'exp', 'log'], [None, x, x]) # This one must have the log first, regardless of what we set it to # (because the log is inside of the exponential: x**x == exp(x*log(x))) assert DifferentialExtension(-x**x*log(x)**2 + x**x - x**x/x, x, handle_first='exp')._important_attrs == \ DifferentialExtension(-x**x*log(x)**2 + x**x - x**x/x, x, handle_first='log')._important_attrs == \ (Poly((-1 + x - x*t0**2)*t1, t1), Poly(x, t1), [Poly(1, x), Poly(1/x, t0), Poly((1 + t0)*t1, t1)], [x, t0, t1], [Lambda(i, log(i)), Lambda(i, exp(t0*i))], [(exp(x*log(x)), x**x)], [None, 'log', 'exp'], [None, x, t0*x]) def test_DifferentialExtension_all_attrs(): # Test 'unimportant' attributes DE = DifferentialExtension(exp(x)*log(x), x, handle_first='exp') assert DE.f == exp(x)*log(x) assert DE.newf == t0*t1 assert DE.x == x assert DE.cases == ['base', 'exp', 'primitive'] assert DE.case == 'primitive' assert DE.level == -1 assert DE.t == t1 == DE.T[DE.level] assert DE.d == Poly(1/x, t1) == DE.D[DE.level] raises(ValueError, lambda: DE.increment_level()) DE.decrement_level() assert DE.level == -2 assert DE.t == t0 == DE.T[DE.level] assert DE.d == Poly(t0, t0) == DE.D[DE.level] assert DE.case == 'exp' DE.decrement_level() assert DE.level == -3 assert DE.t == x == DE.T[DE.level] == DE.x assert DE.d == Poly(1, x) == DE.D[DE.level] assert DE.case == 'base' raises(ValueError, lambda: DE.decrement_level()) DE.increment_level() DE.increment_level() assert DE.level == -1 assert DE.t == t1 == DE.T[DE.level] assert DE.d == Poly(1/x, t1) == DE.D[DE.level] assert DE.case == 'primitive' # Test methods assert DE.indices('log') == [2] assert DE.indices('exp') == [1] def test_DifferentialExtension_extension_flag(): raises(ValueError, lambda: DifferentialExtension(extension={'T': [x, t]})) DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t, t)]}) assert DE._important_attrs == (None, None, [Poly(1, x), Poly(t, t)], [x, t], None, None, None, None) assert DE.d == Poly(t, t) assert DE.t == t assert DE.level == -1 assert DE.cases == ['base', 'exp'] assert DE.x == x assert DE.case == 'exp' DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t, t)], 'exts': [None, 'exp'], 'extargs': [None, x]}) assert DE._important_attrs == (None, None, [Poly(1, x), Poly(t, t)], [x, t], None, None, [None, 'exp'], [None, x]) raises(ValueError, lambda: DifferentialExtension()) def test_DifferentialExtension_misc(): # Odd ends assert DifferentialExtension(sin(y)*exp(x), x)._important_attrs == \ (Poly(sin(y)*t0, t0, domain='ZZ[sin(y)]'), Poly(1, t0, domain='ZZ'), [Poly(1, x, domain='ZZ'), Poly(t0, t0, domain='ZZ')], [x, t0], [Lambda(i, exp(i))], [], [None, 'exp'], [None, x]) raises(NotImplementedError, lambda: DifferentialExtension(sin(x), x)) assert DifferentialExtension(10**x, x)._important_attrs == \ (Poly(t0, t0), Poly(1, t0), [Poly(1, x), Poly(log(10)*t0, t0)], [x, t0], [Lambda(i, exp(i*log(10)))], [(exp(x*log(10)), 10**x)], [None, 'exp'], [None, x*log(10)]) assert DifferentialExtension(log(x) + log(x**2), x)._important_attrs in [ (Poly(3*t0, t0), Poly(2, t0), [Poly(1, x), Poly(2/x, t0)], [x, t0], [Lambda(i, log(i**2))], [], [None, ], [], [1], [x**2]), (Poly(3*t0, t0), Poly(1, t0), [Poly(1, x), Poly(1/x, t0)], [x, t0], [Lambda(i, log(i))], [], [None, 'log'], [None, x])] assert DifferentialExtension(S.Zero, x)._important_attrs == \ (Poly(0, x), Poly(1, x), [Poly(1, x)], [x], [], [], [None], [None]) assert DifferentialExtension(tan(atan(x).rewrite(log)), x)._important_attrs == \ (Poly(x, x), Poly(1, x), [Poly(1, x)], [x], [], [], [None], [None]) def test_DifferentialExtension_Rothstein(): # Rothstein's integral f = (2581284541*exp(x) + 1757211400)/(39916800*exp(3*x) + 119750400*exp(x)**2 + 119750400*exp(x) + 39916800)*exp(1/(exp(x) + 1) - 10*x) assert DifferentialExtension(f, x)._important_attrs == \ (Poly((1757211400 + 2581284541*t0)*t1, t1), Poly(39916800 + 119750400*t0 + 119750400*t0**2 + 39916800*t0**3, t1), [Poly(1, x), Poly(t0, t0), Poly(-(10 + 21*t0 + 10*t0**2)/(1 + 2*t0 + t0**2)*t1, t1, domain='ZZ(t0)')], [x, t0, t1], [Lambda(i, exp(i)), Lambda(i, exp(1/(t0 + 1) - 10*i))], [], [None, 'exp', 'exp'], [None, x, 1/(t0 + 1) - 10*x]) class _TestingException(Exception): """Dummy Exception class for testing.""" pass def test_DecrementLevel(): DE = DifferentialExtension(x*log(exp(x) + 1), x) assert DE.level == -1 assert DE.t == t1 assert DE.d == Poly(t0/(t0 + 1), t1) assert DE.case == 'primitive' with DecrementLevel(DE): assert DE.level == -2 assert DE.t == t0 assert DE.d == Poly(t0, t0) assert DE.case == 'exp' with DecrementLevel(DE): assert DE.level == -3 assert DE.t == x assert DE.d == Poly(1, x) assert DE.case == 'base' assert DE.level == -2 assert DE.t == t0 assert DE.d == Poly(t0, t0) assert DE.case == 'exp' assert DE.level == -1 assert DE.t == t1 assert DE.d == Poly(t0/(t0 + 1), t1) assert DE.case == 'primitive' # Test that __exit__ is called after an exception correctly try: with DecrementLevel(DE): raise _TestingException except _TestingException: pass else: raise AssertionError("Did not raise.") assert DE.level == -1 assert DE.t == t1 assert DE.d == Poly(t0/(t0 + 1), t1) assert DE.case == 'primitive' def test_risch_integrate(): assert risch_integrate(t0*exp(x), x) == t0*exp(x) assert risch_integrate(sin(x), x, rewrite_complex=True) == -exp(I*x)/2 - exp(-I*x)/2 # From my GSoC writeup assert risch_integrate((1 + 2*x**2 + x**4 + 2*x**3*exp(2*x**2))/ (x**4*exp(x**2) + 2*x**2*exp(x**2) + exp(x**2)), x) == \ NonElementaryIntegral(exp(-x**2), x) + exp(x**2)/(1 + x**2) assert risch_integrate(0, x) == 0 # also tests prde_cancel() e1 = log(x/exp(x) + 1) ans1 = risch_integrate(e1, x) assert ans1 == (x*log(x*exp(-x) + 1) + NonElementaryIntegral((x**2 - x)/(x + exp(x)), x)) assert cancel(diff(ans1, x) - e1) == 0 # also tests issue #10798 e2 = (log(-1/y)/2 - log(1/y)/2)/y - (log(1 - 1/y)/2 - log(1 + 1/y)/2)/y ans2 = risch_integrate(e2, y) assert ans2 == log(1/y)*log(1 - 1/y)/2 - log(1/y)*log(1 + 1/y)/2 + \ NonElementaryIntegral((I*pi*y**2 - 2*y*log(1/y) - I*pi)/(2*y**3 - 2*y), y) assert expand_log(cancel(diff(ans2, y) - e2), force=True) == 0 # These are tested here in addition to in test_DifferentialExtension above # (symlogs) to test that backsubs works correctly. The integrals should be # written in terms of the original logarithms in the integrands. # XXX: Unfortunately, making backsubs work on this one is a little # trickier, because x**x is converted to exp(x*log(x)), and so log(x**x) # is converted to x*log(x). (x**2*log(x)).subs(x*log(x), log(x**x)) is # smart enough, the issue is that these splits happen at different places # in the algorithm. Maybe a heuristic is in order assert risch_integrate(log(x**x), x) == x**2*log(x)/2 - x**2/4 assert risch_integrate(log(x**y), x) == x*log(x**y) - x*y assert risch_integrate(log(sqrt(x)), x) == x*log(sqrt(x)) - x/2 def test_risch_integrate_float(): assert risch_integrate((-60*exp(x) - 19.2*exp(4*x))*exp(4*x), x) == -2.4*exp(8*x) - 12.0*exp(5*x) def test_NonElementaryIntegral(): assert isinstance(risch_integrate(exp(x**2), x), NonElementaryIntegral) assert isinstance(risch_integrate(x**x*log(x), x), NonElementaryIntegral) # Make sure methods of Integral still give back a NonElementaryIntegral assert isinstance(NonElementaryIntegral(x**x*t0, x).subs(t0, log(x)), NonElementaryIntegral) def test_xtothex(): a = risch_integrate(x**x, x) assert a == NonElementaryIntegral(x**x, x) assert isinstance(a, NonElementaryIntegral) def test_DifferentialExtension_equality(): DE1 = DE2 = DifferentialExtension(log(x), x) assert DE1 == DE2 def test_DifferentialExtension_printing(): DE = DifferentialExtension(exp(2*x**2) + log(exp(x**2) + 1), x) assert repr(DE) == ("DifferentialExtension(dict([('f', exp(2*x**2) + log(exp(x**2) + 1)), " "('x', x), ('T', [x, t0, t1]), ('D', [Poly(1, x, domain='ZZ'), Poly(2*x*t0, t0, domain='ZZ[x]'), " "Poly(2*t0*x/(t0 + 1), t1, domain='ZZ(x,t0)')]), ('fa', Poly(t1 + t0**2, t1, domain='ZZ[t0]')), " "('fd', Poly(1, t1, domain='ZZ')), ('Tfuncs', [Lambda(i, exp(i**2)), Lambda(i, log(t0 + 1))]), " "('backsubs', []), ('exts', [None, 'exp', 'log']), ('extargs', [None, x**2, t0 + 1]), " "('cases', ['base', 'exp', 'primitive']), ('case', 'primitive'), ('t', t1), " "('d', Poly(2*t0*x/(t0 + 1), t1, domain='ZZ(x,t0)')), ('newf', t0**2 + t1), ('level', -1), " "('dummy', False)]))") assert str(DE) == ("DifferentialExtension({fa=Poly(t1 + t0**2, t1, domain='ZZ[t0]'), " "fd=Poly(1, t1, domain='ZZ'), D=[Poly(1, x, domain='ZZ'), Poly(2*x*t0, t0, domain='ZZ[x]'), " "Poly(2*t0*x/(t0 + 1), t1, domain='ZZ(x,t0)')]})")
1dc74e7f02d0e872ef93022a413151193421934d67e984d59402a6e0f7bfaf6f
from sympy import (sin, cos, tan, sec, csc, cot, log, exp, atan, asin, acos, Symbol, Integral, integrate, pi, Dummy, Derivative, diff, I, sqrt, erf, Piecewise, Ne, symbols, Rational, And, Heaviside, S, asinh, acosh, atanh, acoth, expand, Function, jacobi, gegenbauer, chebyshevt, chebyshevu, legendre, hermite, laguerre, assoc_laguerre, uppergamma, li, Ei, Ci, Si, Chi, Shi, fresnels, fresnelc, polylog, erfi, sinh, cosh, elliptic_f, elliptic_e) from sympy.integrals.manualintegrate import (manualintegrate, find_substitutions, _parts_rule, integral_steps, contains_dont_know, manual_subs) from sympy.testing.pytest import raises, slow x, y, z, u, n, a, b, c = symbols('x y z u n a b c') f = Function('f') def test_find_substitutions(): assert find_substitutions((cot(x)**2 + 1)**2*csc(x)**2*cot(x)**2, x, u) == \ [(cot(x), 1, -u**6 - 2*u**4 - u**2)] assert find_substitutions((sec(x)**2 + tan(x) * sec(x)) / (sec(x) + tan(x)), x, u) == [(sec(x) + tan(x), 1, 1/u)] assert find_substitutions(x * exp(-x**2), x, u) == [(-x**2, Rational(-1, 2), exp(u))] def test_manualintegrate_polynomials(): assert manualintegrate(y, x) == x*y assert manualintegrate(exp(2), x) == x * exp(2) assert manualintegrate(x**2, x) == x**3 / 3 assert manualintegrate(3 * x**2 + 4 * x**3, x) == x**3 + x**4 assert manualintegrate((x + 2)**3, x) == (x + 2)**4 / 4 assert manualintegrate((3*x + 4)**2, x) == (3*x + 4)**3 / 9 assert manualintegrate((u + 2)**3, u) == (u + 2)**4 / 4 assert manualintegrate((3*u + 4)**2, u) == (3*u + 4)**3 / 9 def test_manualintegrate_exponentials(): assert manualintegrate(exp(2*x), x) == exp(2*x) / 2 assert manualintegrate(2**x, x) == (2 ** x) / log(2) assert manualintegrate(1 / x, x) == log(x) assert manualintegrate(1 / (2*x + 3), x) == log(2*x + 3) / 2 assert manualintegrate(log(x)**2 / x, x) == log(x)**3 / 3 def test_manualintegrate_parts(): assert manualintegrate(exp(x) * sin(x), x) == \ (exp(x) * sin(x)) / 2 - (exp(x) * cos(x)) / 2 assert manualintegrate(2*x*cos(x), x) == 2*x*sin(x) + 2*cos(x) assert manualintegrate(x * log(x), x) == x**2*log(x)/2 - x**2/4 assert manualintegrate(log(x), x) == x * log(x) - x assert manualintegrate((3*x**2 + 5) * exp(x), x) == \ 3*x**2*exp(x) - 6*x*exp(x) + 11*exp(x) assert manualintegrate(atan(x), x) == x*atan(x) - log(x**2 + 1)/2 # Make sure _parts_rule does not go into an infinite loop here assert manualintegrate(log(1/x)/(x + 1), x).has(Integral) # Make sure _parts_rule doesn't pick u = constant but can pick dv = # constant if necessary, e.g. for integrate(atan(x)) assert _parts_rule(cos(x), x) == None assert _parts_rule(exp(x), x) == None assert _parts_rule(x**2, x) == None result = _parts_rule(atan(x), x) assert result[0] == atan(x) and result[1] == 1 def test_manualintegrate_trigonometry(): assert manualintegrate(sin(x), x) == -cos(x) assert manualintegrate(tan(x), x) == -log(cos(x)) assert manualintegrate(sec(x), x) == log(sec(x) + tan(x)) assert manualintegrate(csc(x), x) == -log(csc(x) + cot(x)) assert manualintegrate(sin(x) * cos(x), x) in [sin(x) ** 2 / 2, -cos(x)**2 / 2] assert manualintegrate(-sec(x) * tan(x), x) == -sec(x) assert manualintegrate(csc(x) * cot(x), x) == -csc(x) assert manualintegrate(sec(x)**2, x) == tan(x) assert manualintegrate(csc(x)**2, x) == -cot(x) assert manualintegrate(x * sec(x**2), x) == log(tan(x**2) + sec(x**2))/2 assert manualintegrate(cos(x)*csc(sin(x)), x) == -log(cot(sin(x)) + csc(sin(x))) assert manualintegrate(cos(3*x)*sec(x), x) == -x + sin(2*x) assert manualintegrate(sin(3*x)*sec(x), x) == \ -3*log(cos(x)) + 2*log(cos(x)**2) - 2*cos(x)**2 def test_manualintegrate_trigpowers(): assert manualintegrate(sin(x)**2 * cos(x), x) == sin(x)**3 / 3 assert manualintegrate(sin(x)**2 * cos(x) **2, x) == \ x / 8 - sin(4*x) / 32 assert manualintegrate(sin(x) * cos(x)**3, x) == -cos(x)**4 / 4 assert manualintegrate(sin(x)**3 * cos(x)**2, x) == \ cos(x)**5 / 5 - cos(x)**3 / 3 assert manualintegrate(tan(x)**3 * sec(x), x) == sec(x)**3/3 - sec(x) assert manualintegrate(tan(x) * sec(x) **2, x) == sec(x)**2/2 assert manualintegrate(cot(x)**5 * csc(x), x) == \ -csc(x)**5/5 + 2*csc(x)**3/3 - csc(x) assert manualintegrate(cot(x)**2 * csc(x)**6, x) == \ -cot(x)**7/7 - 2*cot(x)**5/5 - cot(x)**3/3 def test_manualintegrate_inversetrig(): # atan assert manualintegrate(exp(x) / (1 + exp(2*x)), x) == atan(exp(x)) assert manualintegrate(1 / (4 + 9 * x**2), x) == atan(3 * x/2) / 6 assert manualintegrate(1 / (16 + 16 * x**2), x) == atan(x) / 16 assert manualintegrate(1 / (4 + x**2), x) == atan(x / 2) / 2 assert manualintegrate(1 / (1 + 4 * x**2), x) == atan(2*x) / 2 ra = Symbol('a', real=True) rb = Symbol('b', real=True) assert manualintegrate(1/(ra + rb*x**2), x) == \ Piecewise((atan(x/sqrt(ra/rb))/(rb*sqrt(ra/rb)), ra/rb > 0), (-acoth(x/sqrt(-ra/rb))/(rb*sqrt(-ra/rb)), And(ra/rb < 0, x**2 > -ra/rb)), (-atanh(x/sqrt(-ra/rb))/(rb*sqrt(-ra/rb)), And(ra/rb < 0, x**2 < -ra/rb))) assert manualintegrate(1/(4 + rb*x**2), x) == \ Piecewise((atan(x/(2*sqrt(1/rb)))/(2*rb*sqrt(1/rb)), 4/rb > 0), (-acoth(x/(2*sqrt(-1/rb)))/(2*rb*sqrt(-1/rb)), And(4/rb < 0, x**2 > -4/rb)), (-atanh(x/(2*sqrt(-1/rb)))/(2*rb*sqrt(-1/rb)), And(4/rb < 0, x**2 < -4/rb))) assert manualintegrate(1/(ra + 4*x**2), x) == \ Piecewise((atan(2*x/sqrt(ra))/(2*sqrt(ra)), ra/4 > 0), (-acoth(2*x/sqrt(-ra))/(2*sqrt(-ra)), And(ra/4 < 0, x**2 > -ra/4)), (-atanh(2*x/sqrt(-ra))/(2*sqrt(-ra)), And(ra/4 < 0, x**2 < -ra/4))) assert manualintegrate(1/(4 + 4*x**2), x) == atan(x) / 4 assert manualintegrate(1/(a + b*x**2), x) == atan(x/sqrt(a/b))/(b*sqrt(a/b)) # asin assert manualintegrate(1/sqrt(1-x**2), x) == asin(x) assert manualintegrate(1/sqrt(4-4*x**2), x) == asin(x)/2 assert manualintegrate(3/sqrt(1-9*x**2), x) == asin(3*x) assert manualintegrate(1/sqrt(4-9*x**2), x) == asin(x*Rational(3, 2))/3 # asinh assert manualintegrate(1/sqrt(x**2 + 1), x) == \ asinh(x) assert manualintegrate(1/sqrt(x**2 + 4), x) == \ asinh(x/2) assert manualintegrate(1/sqrt(4*x**2 + 4), x) == \ asinh(x)/2 assert manualintegrate(1/sqrt(4*x**2 + 1), x) == \ asinh(2*x)/2 assert manualintegrate(1/sqrt(a*x**2 + 1), x) == \ Piecewise((sqrt(-1/a)*asin(x*sqrt(-a)), a < 0), (sqrt(1/a)*asinh(sqrt(a)*x), a > 0)) assert manualintegrate(1/sqrt(a + x**2), x) == \ Piecewise((asinh(x*sqrt(1/a)), a > 0), (acosh(x*sqrt(-1/a)), a < 0)) # acosh assert manualintegrate(1/sqrt(x**2 - 1), x) == \ acosh(x) assert manualintegrate(1/sqrt(x**2 - 4), x) == \ acosh(x/2) assert manualintegrate(1/sqrt(4*x**2 - 4), x) == \ acosh(x)/2 assert manualintegrate(1/sqrt(9*x**2 - 1), x) == \ acosh(3*x)/3 assert manualintegrate(1/sqrt(a*x**2 - 4), x) == \ Piecewise((sqrt(1/a)*acosh(sqrt(a)*x/2), a > 0)) assert manualintegrate(1/sqrt(-a + 4*x**2), x) == \ Piecewise((asinh(2*x*sqrt(-1/a))/2, -a > 0), (acosh(2*x*sqrt(1/a))/2, -a < 0)) # piecewise assert manualintegrate(1/sqrt(a-b*x**2), x) == \ Piecewise((sqrt(a/b)*asin(x*sqrt(b/a))/sqrt(a), And(-b < 0, a > 0)), (sqrt(-a/b)*asinh(x*sqrt(-b/a))/sqrt(a), And(-b > 0, a > 0)), (sqrt(a/b)*acosh(x*sqrt(b/a))/sqrt(-a), And(-b > 0, a < 0))) assert manualintegrate(1/sqrt(a + b*x**2), x) == \ Piecewise((sqrt(-a/b)*asin(x*sqrt(-b/a))/sqrt(a), And(a > 0, b < 0)), (sqrt(a/b)*asinh(x*sqrt(b/a))/sqrt(a), And(a > 0, b > 0)), (sqrt(-a/b)*acosh(x*sqrt(-b/a))/sqrt(-a), And(a < 0, b > 0))) def test_manualintegrate_trig_substitution(): assert manualintegrate(sqrt(16*x**2 - 9)/x, x) == \ Piecewise((sqrt(16*x**2 - 9) - 3*acos(3/(4*x)), And(x < Rational(3, 4), x > Rational(-3, 4)))) assert manualintegrate(1/(x**4 * sqrt(25-x**2)), x) == \ Piecewise((-sqrt(-x**2/25 + 1)/(125*x) - (-x**2/25 + 1)**(3*S.Half)/(15*x**3), And(x < 5, x > -5))) assert manualintegrate(x**7/(49*x**2 + 1)**(3 * S.Half), x) == \ ((49*x**2 + 1)**(5*S.Half)/28824005 - (49*x**2 + 1)**(3*S.Half)/5764801 + 3*sqrt(49*x**2 + 1)/5764801 + 1/(5764801*sqrt(49*x**2 + 1))) def test_manualintegrate_trivial_substitution(): assert manualintegrate((exp(x) - exp(-x))/x, x) == -Ei(-x) + Ei(x) f = Function('f') assert manualintegrate((f(x) - f(-x))/x, x) == \ -Integral(f(-x)/x, x) + Integral(f(x)/x, x) def test_manualintegrate_rational(): assert manualintegrate(1/(4 - x**2), x) == Piecewise((acoth(x/2)/2, x**2 > 4), (atanh(x/2)/2, x**2 < 4)) assert manualintegrate(1/(-1 + x**2), x) == Piecewise((-acoth(x), x**2 > 1), (-atanh(x), x**2 < 1)) def test_manualintegrate_special(): f, F = 4*exp(-x**2/3), 2*sqrt(3)*sqrt(pi)*erf(sqrt(3)*x/3) assert manualintegrate(f, x) == F and F.diff(x).equals(f) f, F = 3*exp(4*x**2), 3*sqrt(pi)*erfi(2*x)/4 assert manualintegrate(f, x) == F and F.diff(x).equals(f) f, F = x**Rational(1, 3)*exp(-x/8), -16*uppergamma(Rational(4, 3), x/8) assert manualintegrate(f, x) == F and F.diff(x).equals(f) f, F = exp(2*x)/x, Ei(2*x) assert manualintegrate(f, x) == F and F.diff(x).equals(f) f, F = exp(1 + 2*x - x**2), sqrt(pi)*exp(2)*erf(x - 1)/2 assert manualintegrate(f, x) == F and F.diff(x).equals(f) f = sin(x**2 + 4*x + 1) F = (sqrt(2)*sqrt(pi)*(-sin(3)*fresnelc(sqrt(2)*(2*x + 4)/(2*sqrt(pi))) + cos(3)*fresnels(sqrt(2)*(2*x + 4)/(2*sqrt(pi))))/2) assert manualintegrate(f, x) == F and F.diff(x).equals(f) f, F = cos(4*x**2), sqrt(2)*sqrt(pi)*fresnelc(2*sqrt(2)*x/sqrt(pi))/4 assert manualintegrate(f, x) == F and F.diff(x).equals(f) f, F = sin(3*x + 2)/x, sin(2)*Ci(3*x) + cos(2)*Si(3*x) assert manualintegrate(f, x) == F and F.diff(x).equals(f) f, F = sinh(3*x - 2)/x, -sinh(2)*Chi(3*x) + cosh(2)*Shi(3*x) assert manualintegrate(f, x) == F and F.diff(x).equals(f) f, F = 5*cos(2*x - 3)/x, 5*cos(3)*Ci(2*x) + 5*sin(3)*Si(2*x) assert manualintegrate(f, x) == F and F.diff(x).equals(f) f, F = cosh(x/2)/x, Chi(x/2) assert manualintegrate(f, x) == F and F.diff(x).equals(f) f, F = cos(x**2)/x, Ci(x**2)/2 assert manualintegrate(f, x) == F and F.diff(x).equals(f) f, F = 1/log(2*x + 1), li(2*x + 1)/2 assert manualintegrate(f, x) == F and F.diff(x).equals(f) f, F = polylog(2, 5*x)/x, polylog(3, 5*x) assert manualintegrate(f, x) == F and F.diff(x).equals(f) f, F = 5/sqrt(3 - 2*sin(x)**2), 5*sqrt(3)*elliptic_f(x, Rational(2, 3))/3 assert manualintegrate(f, x) == F and F.diff(x).equals(f) f, F = sqrt(4 + 9*sin(x)**2), 2*elliptic_e(x, Rational(-9, 4)) assert manualintegrate(f, x) == F and F.diff(x).equals(f) def test_manualintegrate_derivative(): assert manualintegrate(pi * Derivative(x**2 + 2*x + 3), x) == \ pi * ((x**2 + 2*x + 3)) assert manualintegrate(Derivative(x**2 + 2*x + 3, y), x) == \ Integral(Derivative(x**2 + 2*x + 3, y)) assert manualintegrate(Derivative(sin(x), x, x, x, y), x) == \ Derivative(sin(x), x, x, y) def test_manualintegrate_Heaviside(): assert manualintegrate(Heaviside(x), x) == x*Heaviside(x) assert manualintegrate(x*Heaviside(2), x) == x**2/2 assert manualintegrate(x*Heaviside(-2), x) == 0 assert manualintegrate(x*Heaviside( x), x) == x**2*Heaviside( x)/2 assert manualintegrate(x*Heaviside(-x), x) == x**2*Heaviside(-x)/2 assert manualintegrate(Heaviside(2*x + 4), x) == (x+2)*Heaviside(2*x + 4) assert manualintegrate(x*Heaviside(x), x) == x**2*Heaviside(x)/2 assert manualintegrate(Heaviside(x + 1)*Heaviside(1 - x)*x**2, x) == \ ((x**3/3 + Rational(1, 3))*Heaviside(x + 1) - Rational(2, 3))*Heaviside(-x + 1) y = Symbol('y') assert manualintegrate(sin(7 + x)*Heaviside(3*x - 7), x) == \ (- cos(x + 7) + cos(Rational(28, 3)))*Heaviside(3*x - S(7)) assert manualintegrate(sin(y + x)*Heaviside(3*x - y), x) == \ (cos(y*Rational(4, 3)) - cos(x + y))*Heaviside(3*x - y) def test_manualintegrate_orthogonal_poly(): n = symbols('n') a, b = 7, Rational(5, 3) polys = [jacobi(n, a, b, x), gegenbauer(n, a, x), chebyshevt(n, x), chebyshevu(n, x), legendre(n, x), hermite(n, x), laguerre(n, x), assoc_laguerre(n, a, x)] for p in polys: integral = manualintegrate(p, x) for deg in [-2, -1, 0, 1, 3, 5, 8]: # some accept negative "degree", some do not try: p_subbed = p.subs(n, deg) except ValueError: continue assert (integral.subs(n, deg).diff(x) - p_subbed).expand() == 0 # can also integrate simple expressions with these polynomials q = x*p.subs(x, 2*x + 1) integral = manualintegrate(q, x) for deg in [2, 4, 7]: assert (integral.subs(n, deg).diff(x) - q.subs(n, deg)).expand() == 0 # cannot integrate with respect to any other parameter t = symbols('t') for i in range(len(p.args) - 1): new_args = list(p.args) new_args[i] = t assert isinstance(manualintegrate(p.func(*new_args), t), Integral) def test_issue_6799(): r, x, phi = map(Symbol, 'r x phi'.split()) n = Symbol('n', integer=True, positive=True) integrand = (cos(n*(x-phi))*cos(n*x)) limits = (x, -pi, pi) assert manualintegrate(integrand, x) == \ ((n*x/2 + sin(2*n*x)/4)*cos(n*phi) - sin(n*phi)*cos(n*x)**2/2)/n assert r * integrate(integrand, limits).trigsimp() / pi == r * cos(n * phi) assert not integrate(integrand, limits).has(Dummy) def test_issue_12251(): assert manualintegrate(x**y, x) == Piecewise( (x**(y + 1)/(y + 1), Ne(y, -1)), (log(x), True)) def test_issue_3796(): assert manualintegrate(diff(exp(x + x**2)), x) == exp(x + x**2) assert integrate(x * exp(x**4), x, risch=False) == -I*sqrt(pi)*erf(I*x**2)/4 def test_manual_true(): assert integrate(exp(x) * sin(x), x, manual=True) == \ (exp(x) * sin(x)) / 2 - (exp(x) * cos(x)) / 2 assert integrate(sin(x) * cos(x), x, manual=True) in \ [sin(x) ** 2 / 2, -cos(x)**2 / 2] def test_issue_6746(): y = Symbol('y') n = Symbol('n') assert manualintegrate(y**x, x) == Piecewise( (y**x/log(y), Ne(log(y), 0)), (x, True)) assert manualintegrate(y**(n*x), x) == Piecewise( (Piecewise( (y**(n*x)/log(y), Ne(log(y), 0)), (n*x, True) )/n, Ne(n, 0)), (x, True)) assert manualintegrate(exp(n*x), x) == Piecewise( (exp(n*x)/n, Ne(n, 0)), (x, True)) y = Symbol('y', positive=True) assert manualintegrate((y + 1)**x, x) == (y + 1)**x/log(y + 1) y = Symbol('y', zero=True) assert manualintegrate((y + 1)**x, x) == x y = Symbol('y') n = Symbol('n', nonzero=True) assert manualintegrate(y**(n*x), x) == Piecewise( (y**(n*x)/log(y), Ne(log(y), 0)), (n*x, True))/n y = Symbol('y', positive=True) assert manualintegrate((y + 1)**(n*x), x) == \ (y + 1)**(n*x)/(n*log(y + 1)) a = Symbol('a', negative=True) b = Symbol('b') assert manualintegrate(1/(a + b*x**2), x) == atan(x/sqrt(a/b))/(b*sqrt(a/b)) b = Symbol('b', negative=True) assert manualintegrate(1/(a + b*x**2), x) == \ atan(x/(sqrt(-a)*sqrt(-1/b)))/(b*sqrt(-a)*sqrt(-1/b)) assert manualintegrate(1/((x**a + y**b + 4)*sqrt(a*x**2 + 1)), x) == \ y**(-b)*Integral(x**(-a)/(y**(-b)*sqrt(a*x**2 + 1) + x**(-a)*sqrt(a*x**2 + 1) + 4*x**(-a)*y**(-b)*sqrt(a*x**2 + 1)), x) assert manualintegrate(1/((x**2 + 4)*sqrt(4*x**2 + 1)), x) == \ Integral(1/((x**2 + 4)*sqrt(4*x**2 + 1)), x) assert manualintegrate(1/(x - a**x + x*b**2), x) == \ Integral(1/(-a**x + b**2*x + x), x) @slow def test_issue_2850(): assert manualintegrate(asin(x)*log(x), x) == -x*asin(x) - sqrt(-x**2 + 1) \ + (x*asin(x) + sqrt(-x**2 + 1))*log(x) - Integral(sqrt(-x**2 + 1)/x, x) assert manualintegrate(acos(x)*log(x), x) == -x*acos(x) + sqrt(-x**2 + 1) + \ (x*acos(x) - sqrt(-x**2 + 1))*log(x) + Integral(sqrt(-x**2 + 1)/x, x) assert manualintegrate(atan(x)*log(x), x) == -x*atan(x) + (x*atan(x) - \ log(x**2 + 1)/2)*log(x) + log(x**2 + 1)/2 + Integral(log(x**2 + 1)/x, x)/2 def test_issue_9462(): assert manualintegrate(sin(2*x)*exp(x), x) == exp(x)*sin(2*x)/5 - 2*exp(x)*cos(2*x)/5 assert not contains_dont_know(integral_steps(sin(2*x)*exp(x), x)) assert manualintegrate((x - 3) / (x**2 - 2*x + 2)**2, x) == \ Integral(x/(x**4 - 4*x**3 + 8*x**2 - 8*x + 4), x) \ - 3*Integral(1/(x**4 - 4*x**3 + 8*x**2 - 8*x + 4), x) def test_cyclic_parts(): f = cos(x)*exp(x/4) F = 16*exp(x/4)*sin(x)/17 + 4*exp(x/4)*cos(x)/17 assert manualintegrate(f, x) == F and F.diff(x) == f f = x*cos(x)*exp(x/4) F = (x*(16*exp(x/4)*sin(x)/17 + 4*exp(x/4)*cos(x)/17) - 128*exp(x/4)*sin(x)/289 + 240*exp(x/4)*cos(x)/289) assert manualintegrate(f, x) == F and F.diff(x) == f @slow def test_issue_10847_slow(): assert manualintegrate((4*x**4 + 4*x**3 + 16*x**2 + 12*x + 8) / (x**6 + 2*x**5 + 3*x**4 + 4*x**3 + 3*x**2 + 2*x + 1), x) == \ 2*x/(x**2 + 1) + 3*atan(x) - 1/(x**2 + 1) - 3/(x + 1) def test_issue_10847(): assert manualintegrate(x**2 / (x**2 - c), x) == c*atan(x/sqrt(-c))/sqrt(-c) + x rc = Symbol('c', real=True) assert manualintegrate(x**2 / (x**2 - rc), x) == \ rc*Piecewise((atan(x/sqrt(-rc))/sqrt(-rc), -rc > 0), (-acoth(x/sqrt(rc))/sqrt(rc), And(-rc < 0, x**2 > rc)), (-atanh(x/sqrt(rc))/sqrt(rc), And(-rc < 0, x**2 < rc))) + x assert manualintegrate(sqrt(x - y) * log(z / x), x) == \ 4*y**Rational(3, 2)*atan(sqrt(x - y)/sqrt(y))/3 - 4*y*sqrt(x - y)/3 +\ 2*(x - y)**Rational(3, 2)*log(z/x)/3 + 4*(x - y)**Rational(3, 2)/9 ry = Symbol('y', real=True) rz = Symbol('z', real=True) assert manualintegrate(sqrt(x - ry) * log(rz / x), x) == \ 4*ry**2*Piecewise((atan(sqrt(x - ry)/sqrt(ry))/sqrt(ry), ry > 0), (-acoth(sqrt(x - ry)/sqrt(-ry))/sqrt(-ry), And(x - ry > -ry, ry < 0)), (-atanh(sqrt(x - ry)/sqrt(-ry))/sqrt(-ry), And(x - ry < -ry, ry < 0)))/3 \ - 4*ry*sqrt(x - ry)/3 + 2*(x - ry)**Rational(3, 2)*log(rz/x)/3 \ + 4*(x - ry)**Rational(3, 2)/9 assert manualintegrate(sqrt(x) * log(x), x) == 2*x**Rational(3, 2)*log(x)/3 - 4*x**Rational(3, 2)/9 assert manualintegrate(sqrt(a*x + b) / x, x) == \ 2*b*atan(sqrt(a*x + b)/sqrt(-b))/sqrt(-b) + 2*sqrt(a*x + b) ra = Symbol('a', real=True) rb = Symbol('b', real=True) assert manualintegrate(sqrt(ra*x + rb) / x, x) == \ -2*rb*Piecewise((-atan(sqrt(ra*x + rb)/sqrt(-rb))/sqrt(-rb), -rb > 0), (acoth(sqrt(ra*x + rb)/sqrt(rb))/sqrt(rb), And(-rb < 0, ra*x + rb > rb)), (atanh(sqrt(ra*x + rb)/sqrt(rb))/sqrt(rb), And(-rb < 0, ra*x + rb < rb))) \ + 2*sqrt(ra*x + rb) assert expand(manualintegrate(sqrt(ra*x + rb) / (x + rc), x)) == -2*ra*rc*Piecewise((atan(sqrt(ra*x + rb)/sqrt(ra*rc - rb))/sqrt(ra*rc - rb), \ ra*rc - rb > 0), (-acoth(sqrt(ra*x + rb)/sqrt(-ra*rc + rb))/sqrt(-ra*rc + rb), And(ra*rc - rb < 0, ra*x + rb > -ra*rc + rb)), \ (-atanh(sqrt(ra*x + rb)/sqrt(-ra*rc + rb))/sqrt(-ra*rc + rb), And(ra*rc - rb < 0, ra*x + rb < -ra*rc + rb))) \ + 2*rb*Piecewise((atan(sqrt(ra*x + rb)/sqrt(ra*rc - rb))/sqrt(ra*rc - rb), ra*rc - rb > 0), \ (-acoth(sqrt(ra*x + rb)/sqrt(-ra*rc + rb))/sqrt(-ra*rc + rb), And(ra*rc - rb < 0, ra*x + rb > -ra*rc + rb)), \ (-atanh(sqrt(ra*x + rb)/sqrt(-ra*rc + rb))/sqrt(-ra*rc + rb), And(ra*rc - rb < 0, ra*x + rb < -ra*rc + rb))) + 2*sqrt(ra*x + rb) assert manualintegrate(sqrt(2*x + 3) / (x + 1), x) == 2*sqrt(2*x + 3) - log(sqrt(2*x + 3) + 1) + log(sqrt(2*x + 3) - 1) assert manualintegrate(sqrt(2*x + 3) / 2 * x, x) == (2*x + 3)**Rational(5, 2)/20 - (2*x + 3)**Rational(3, 2)/4 assert manualintegrate(x**Rational(3,2) * log(x), x) == 2*x**Rational(5,2)*log(x)/5 - 4*x**Rational(5,2)/25 assert manualintegrate(x**(-3) * log(x), x) == -log(x)/(2*x**2) - 1/(4*x**2) assert manualintegrate(log(y)/(y**2*(1 - 1/y)), y) == \ log(y)*log(-1 + 1/y) - Integral(log(-1 + 1/y)/y, y) def test_issue_12899(): assert manualintegrate(f(x,y).diff(x),y) == Integral(Derivative(f(x,y),x),y) assert manualintegrate(f(x,y).diff(y).diff(x),y) == Derivative(f(x,y),x) def test_constant_independent_of_symbol(): assert manualintegrate(Integral(y, (x, 1, 2)), x) == \ x*Integral(y, (x, 1, 2)) def test_issue_12641(): assert manualintegrate(sin(2*x), x) == -cos(2*x)/2 assert manualintegrate(cos(x)*sin(2*x), x) == -2*cos(x)**3/3 assert manualintegrate((sin(2*x)*cos(x))/(1 + cos(x)), x) == \ -2*log(cos(x) + 1) - cos(x)**2 + 2*cos(x) def test_issue_13297(): assert manualintegrate(sin(x) * cos(x)**5, x) == -cos(x)**6 / 6 def test_issue_14470(): assert manualintegrate(1/(x*sqrt(x + 1)), x) == \ log(-1 + 1/sqrt(x + 1)) - log(1 + 1/sqrt(x + 1)) @slow def test_issue_9858(): assert manualintegrate(exp(x)*cos(exp(x)), x) == sin(exp(x)) assert manualintegrate(exp(2*x)*cos(exp(x)), x) == \ exp(x)*sin(exp(x)) + cos(exp(x)) res = manualintegrate(exp(10*x)*sin(exp(x)), x) assert not res.has(Integral) assert res.diff(x) == exp(10*x)*sin(exp(x)) # an example with many similar integrations by parts assert manualintegrate(sum([x*exp(k*x) for k in range(1, 8)]), x) == ( x*exp(7*x)/7 + x*exp(6*x)/6 + x*exp(5*x)/5 + x*exp(4*x)/4 + x*exp(3*x)/3 + x*exp(2*x)/2 + x*exp(x) - exp(7*x)/49 -exp(6*x)/36 - exp(5*x)/25 - exp(4*x)/16 - exp(3*x)/9 - exp(2*x)/4 - exp(x)) def test_issue_8520(): assert manualintegrate(x/(x**4 + 1), x) == atan(x**2)/2 assert manualintegrate(x**2/(x**6 + 25), x) == atan(x**3/5)/15 f = x/(9*x**4 + 4)**2 assert manualintegrate(f, x).diff(x).factor() == f def test_manual_subs(): x, y = symbols('x y') expr = log(x) + exp(x) # if log(x) is y, then exp(y) is x assert manual_subs(expr, log(x), y) == y + exp(exp(y)) # if exp(x) is y, then log(y) need not be x assert manual_subs(expr, exp(x), y) == log(x) + y raises(ValueError, lambda: manual_subs(expr, x)) raises(ValueError, lambda: manual_subs(expr, exp(x), x, y)) def test_issue_15471(): f = log(x)*cos(log(x))/x**Rational(3, 4) F = -128*x**Rational(1, 4)*sin(log(x))/289 + 240*x**Rational(1, 4)*cos(log(x))/289 + (16*x**Rational(1, 4)*sin(log(x))/17 + 4*x**Rational(1, 4)*cos(log(x))/17)*log(x) assert manualintegrate(f, x) == F and F.diff(x).equals(f) def test_quadratic_denom(): f = (5*x + 2)/(3*x**2 - 2*x + 8) assert manualintegrate(f, x) == 5*log(3*x**2 - 2*x + 8)/6 + 11*sqrt(23)*atan(3*sqrt(23)*(x - Rational(1, 3))/23)/69 g = 3/(2*x**2 + 3*x + 1) assert manualintegrate(g, x) == 3*log(4*x + 2) - 3*log(4*x + 4)
09e3f4663a432dd0bd494d7b430150e2dd04b07d6a2cd58119d3c71fee34d733
# A collection of failing integrals from the issues. from sympy import ( integrate, I, Integral, exp, oo, pi, sign, sqrt, sin, cos, Piecewise, tan, S, log, gamma, sinh, sec, acos, atan, sech, csch, DiracDelta, Rational ) from sympy.testing.pytest import XFAIL, SKIP, slow, skip, ON_TRAVIS from sympy.abc import x, k, c, y, b, h, a, m, z, n, t @SKIP("Too slow for @slow") @XFAIL def test_issue_3880(): # integrate_hyperexponential(Poly(t*2*(1 - t0**2)*t0*(x**3 + x**2), t), Poly((1 + t0**2)**2*2*(x**2 + x + 1), t), [Poly(1, x), Poly(1 + t0**2, t0), Poly(t, t)], [x, t0, t], [exp, tan]) assert not integrate(exp(x)*cos(2*x)*sin(2*x) * (x**3 + x**2)/(2*(x**2 + x + 1)), x).has(Integral) @XFAIL def test_issue_4212(): assert not integrate(sign(x), x).has(Integral) @XFAIL def test_issue_4491(): # Can be solved via variable transformation x = y - 1 assert not integrate(x*sqrt(x**2 + 2*x + 4), x).has(Integral) @XFAIL def test_issue_4511(): # This works, but gives a complicated answer. The correct answer is x - cos(x). # If current answer is simplified, 1 - cos(x) + x is obtained. # The last one is what Maple gives. It is also quite slow. assert integrate(cos(x)**2 / (1 - sin(x))) in [x - cos(x), 1 - cos(x) + x, -2/(tan((S.Half)*x)**2 + 1) + x] @XFAIL def test_integrate_DiracDelta_fails(): # issue 6427 assert integrate(integrate(integrate( DiracDelta(x - y - z), (z, 0, oo)), (y, 0, 1)), (x, 0, 1)) == S.Half @XFAIL @slow def test_issue_4525(): # Warning: takes a long time assert not integrate((x**m * (1 - x)**n * (a + b*x + c*x**2))/(1 + x**2), (x, 0, 1)).has(Integral) @XFAIL @slow def test_issue_4540(): if ON_TRAVIS: skip("Too slow for travis.") # Note, this integral is probably nonelementary assert not integrate( (sin(1/x) - x*exp(x)) / ((-sin(1/x) + x*exp(x))*x + x*sin(1/x)), x).has(Integral) @XFAIL @slow def test_issue_4891(): # Requires the hypergeometric function. assert not integrate(cos(x)**y, x).has(Integral) @XFAIL @slow def test_issue_1796a(): assert not integrate(exp(2*b*x)*exp(-a*x**2), x).has(Integral) @XFAIL def test_issue_4895b(): assert not integrate(exp(2*b*x)*exp(-a*x**2), (x, -oo, 0)).has(Integral) @XFAIL def test_issue_4895c(): assert not integrate(exp(2*b*x)*exp(-a*x**2), (x, -oo, oo)).has(Integral) @XFAIL def test_issue_4895d(): assert not integrate(exp(2*b*x)*exp(-a*x**2), (x, 0, oo)).has(Integral) @XFAIL @slow def test_issue_4941(): if ON_TRAVIS: skip("Too slow for travis.") assert not integrate(sqrt(1 + sinh(x/20)**2), (x, -25, 25)).has(Integral) @XFAIL def test_issue_4992(): # Nonelementary integral. Requires hypergeometric/Meijer-G handling. assert not integrate(log(x) * x**(k - 1) * exp(-x) / gamma(k), (x, 0, oo)).has(Integral) @XFAIL def test_issue_16396a(): i = integrate(1/(1+sqrt(tan(x))), (x, pi/3, pi/6)) assert not i.has(Integral) @XFAIL def test_issue_16396b(): i = integrate(x*sin(x)/(1+cos(x)**2), (x, 0, pi)) assert not i.has(Integral) @XFAIL def test_issue_16161(): i = integrate(x*sec(x)**2, x) assert not i.has(Integral) # assert i == x*tan(x) + log(cos(x)) @XFAIL def test_issue_16046(): assert integrate(exp(exp(I*x)), [x, 0, 2*pi]) == 2*pi @XFAIL def test_issue_15925a(): assert not integrate(sqrt((1+sin(x))**2+(cos(x))**2), (x, -pi/2, pi/2)).has(Integral) @XFAIL @slow def test_issue_15925b(): if ON_TRAVIS: skip("Too slow for travis.") assert not integrate(sqrt((-12*cos(x)**2*sin(x))**2+(12*cos(x)*sin(x)**2)**2), (x, 0, pi/6)).has(Integral) @XFAIL def test_issue_15925b_manual(): assert not integrate(sqrt((-12*cos(x)**2*sin(x))**2+(12*cos(x)*sin(x)**2)**2), (x, 0, pi/6), manual=True).has(Integral) @XFAIL @slow def test_issue_15227(): if ON_TRAVIS: skip("Too slow for travis.") i = integrate(log(1-x)*log((1+x)**2)/x, (x, 0, 1)) assert not i.has(Integral) # assert i == -5*zeta(3)/4 @XFAIL @slow def test_issue_14716(): i = integrate(log(x + 5)*cos(pi*x),(x, S.Half, 1)) assert not i.has(Integral) # Mathematica can not solve it either, but # integrate(log(x + 5)*cos(pi*x),(x, S.Half, 1)).transform(x, y - 5).doit() # works # assert i == -log(Rational(11, 2))/pi - Si(pi*Rational(11, 2))/pi + Si(6*pi)/pi @XFAIL def test_issue_14709a(): i = integrate(x*acos(1 - 2*x/h), (x, 0, h)) assert not i.has(Integral) # assert i == 5*h**2*pi/16 @slow @XFAIL def test_issue_14398(): assert not integrate(exp(x**2)*cos(x), x).has(Integral) @XFAIL def test_issue_14074(): i = integrate(log(sin(x)), (x, 0, pi/2)) assert not i.has(Integral) # assert i == -pi*log(2)/2 @XFAIL @slow def test_issue_14078b(): i = integrate((atan(4*x)-atan(2*x))/x, (x, 0, oo)) assert not i.has(Integral) # assert i == pi*log(2)/2 @XFAIL def test_issue_13792(): i = integrate(log(1/x) / (1 - x), (x, 0, 1)) assert not i.has(Integral) # assert i in [polylog(2, -exp_polar(I*pi)), pi**2/6] @XFAIL def test_issue_11845a(): assert not integrate(exp(y - x**3), (x, 0, 1)).has(Integral) @XFAIL def test_issue_11845b(): assert not integrate(exp(-y - x**3), (x, 0, 1)).has(Integral) @XFAIL def test_issue_11813(): assert not integrate((a - x)**Rational(-1, 2)*x, (x, 0, a)).has(Integral) @XFAIL def test_issue_11742(): i = integrate(sqrt(-x**2 + 8*x + 48), (x, 4, 12)) assert not i.has(Integral) # assert i == 16*pi @XFAIL def test_issue_11254a(): assert not integrate(sech(x), (x, 0, 1)).has(Integral) @XFAIL def test_issue_11254b(): assert not integrate(csch(x), (x, 0, 1)).has(Integral) @XFAIL def test_issue_10584(): assert not integrate(sqrt(x**2 + 1/x**2), x).has(Integral) @XFAIL def test_issue_9723(): assert not integrate(sqrt(x + sqrt(x))).has(Integral) @XFAIL def test_issue_9101(): assert not integrate(log(x + sqrt(x**2 + y**2 + z**2)), z).has(Integral) @XFAIL def test_issue_7264(): assert not integrate(exp(x)*sqrt(1 + exp(2*x))).has(Integral) @XFAIL def test_issue_7147(): assert not integrate(x/sqrt(a*x**2 + b*x + c)**3, x).has(Integral) @XFAIL def test_issue_7109(): assert not integrate(sqrt(a**2/(a**2 - x**2)), x).has(Integral) @XFAIL def test_integrate_Piecewise_rational_over_reals(): f = Piecewise( (0, t - 478.515625*pi < 0), (13.2075145209219*pi/(0.000871222*t + 0.995)**2, t - 478.515625*pi >= 0)) assert abs((integrate(f, (t, 0, oo)) - 15235.9375*pi).evalf()) <= 1e-7 @XFAIL def test_issue_4311_slow(): # Not slow when bypassing heurish assert not integrate(x*abs(9-x**2), x).has(Integral)