hash
stringlengths 64
64
| content
stringlengths 0
1.51M
|
---|---|
fe4676c3956e93dcfcca532394ea055d1095dfc50dfaa52f8b28478e9686b818 | from math import isclose
from sympy.core.add import Add
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, Integer)
from sympy.core.relational import (Eq, Gt, Ne, Ge)
from sympy.core.singleton import S
from sympy.core.sorting import ordered
from sympy.core.symbol import (Dummy, Symbol, symbols)
from sympy.core.sympify import sympify
from sympy.functions.elementary.complexes import (Abs, arg, im, re, sign, conjugate)
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, Range
from sympy.sets.sets import (Complement, FiniteSet,
Intersection, Interval, Union, imageset, ProductSet)
from sympy.simplify import simplify
from sympy.tensor.indexed import Indexed
from sympy.utilities.iterables import numbered_symbols
from sympy.testing.pytest import (XFAIL, raises, skip, slow, SKIP, _both_exp_pow)
from sympy.core.random import verify_numerically as tn
from sympy.physics.units import cm
from sympy.solvers import solve
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, _is_lambert,
_solve_logarithm, _term_factors, _is_modular, NonlinearError)
from sympy.abc import (a, b, c, d, e, f, g, h, i, j, k, l, m, n, q, r,
t, w, x, y, z)
def dumeq(i, j):
if type(i) in (list, tuple):
return all(dumeq(i, j) for i, j in zip(i, j))
return i == j or i.dummy_eq(j)
def assert_close_ss(sol1, sol2):
"""Test solutions with floats from solveset are close"""
sol1 = sympify(sol1)
sol2 = sympify(sol2)
assert isinstance(sol1, FiniteSet)
assert isinstance(sol2, FiniteSet)
assert len(sol1) == len(sol2)
assert all(isclose(v1, v2) for v1, v2 in zip(sol1, sol2))
def assert_close_nl(sol1, sol2):
"""Test solutions with floats from nonlinsolve are close"""
sol1 = sympify(sol1)
sol2 = sympify(sol2)
assert isinstance(sol1, FiniteSet)
assert isinstance(sol2, FiniteSet)
assert len(sol1) == len(sol2)
for s1, s2 in zip(sol1, sol2):
assert len(s1) == len(s2)
assert all(isclose(v1, v2) for v1, v2 in zip(s1, s2))
@_both_exp_pow
def test_invert_real():
x = Symbol('x', real=True)
def ireal(x, s=S.Reals):
return Intersection(s, x)
assert invert_real(exp(x), z, x) == (x, ireal(FiniteSet(log(z))))
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))
# issue 21236
assert invert_real(x**pi, y, x) == (x, FiniteSet(y**(1/pi)))
assert invert_real(x**pi, -E, x) == (x, S.EmptySet)
assert invert_real(x**Rational(3/2), 1000, x) == (x, FiniteSet(100))
assert invert_real(x**1.0, 1, x) == (x**1.0, FiniteSet(1))
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 dumeq(invert_real(sin(x), y, x),
(x, imageset(Lambda(n, n*pi + (-1)**n*asin(y)), S.Integers)))
assert dumeq(invert_real(sin(exp(x)), y, x),
(x, imageset(Lambda(n, log((-1)**n*asin(y) + n*pi)), S.Integers)))
assert dumeq(invert_real(csc(x), y, x),
(x, imageset(Lambda(n, n*pi + (-1)**n*acsc(y)), S.Integers)))
assert dumeq(invert_real(csc(exp(x)), y, x),
(x, imageset(Lambda(n, log((-1)**n*acsc(y) + n*pi)), S.Integers)))
assert dumeq(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 dumeq(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 dumeq(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 dumeq(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 dumeq(invert_real(tan(x), y, x),
(x, imageset(Lambda(n, n*pi + atan(y)), S.Integers)))
assert dumeq(invert_real(tan(exp(x)), y, x),
(x, imageset(Lambda(n, log(n*pi + atan(y))), S.Integers)))
assert dumeq(invert_real(cot(x), y, x),
(x, imageset(Lambda(n, n*pi + acot(y)), S.Integers)))
assert dumeq(invert_real(cot(exp(x)), y, x),
(x, imageset(Lambda(n, log(n*pi + acot(y))), S.Integers)))
assert dumeq(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((x - 1)**3, 0, x) == (x, FiniteSet(1))
assert dumeq(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():
f = (x**2 + y**2)**2 + (x**2 + z**2)**2 - 2*(2*x**2 + y**2 + z**2)
fx = f.diff(x)
fy = f.diff(y)
fz = f.diff(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_issue_21047():
f = (2 - x)**2 + (sqrt(x - 1) - 1)**6
assert solveset(f, x, S.Reals) == FiniteSet(2)
f = (sqrt(x)-1)**2 + (sqrt(x)+1)**2 -2*x**2 + sqrt(2)
assert solveset(f, x, S.Reals) == FiniteSet(
S.Half - sqrt(2*sqrt(2) + 5)/2, S.Half + sqrt(2*sqrt(2) + 5)/2)
def test_is_function_class_equation():
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([y], y))
x = Symbol('x', real=True)
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)
bb = Symbol('bb', real=True)
assert solveset_real((anz*x + bb)*(exp(x) - 3), x) == \
FiniteSet(-bb/anz, log(3))
assert solveset_real((2*x + 8)*(8 + exp(x)), x) == FiniteSet(S(-4))
assert solveset_real(x/log(x), x) is S.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():
x = Symbol('x', real=True)
y = Symbol('y', real=True)
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)
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) is S.EmptySet
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_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)
assert solveset_real(sqrt((x-3)/x), x) == FiniteSet(3)
assert solveset_real(sqrt((x-3)/x)-Rational(1, 2), x) == \
FiniteSet(4)
def test_solveset_sqrt_2():
x = Symbol('x', real=True)
y = Symbol('y', real=True)
# 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 = (x - 4)**2 + (sqrt(x) - 2)**4
assert solveset_real(eq, x) == FiniteSet(-4, 4)
eq = (sqrt(x) + sqrt(x + 1) + sqrt(1 - x) - 6*sqrt(5)/5)
ans = solveset_real(eq, x)
ra = S('''-1484/375 - 4*(-S(1)/2 + sqrt(3)*I/2)*(-12459439/52734375 +
114*sqrt(12657)/78125)**(S(1)/3) - 172564/(140625*(-S(1)/2 +
sqrt(3)*I/2)*(-12459439/52734375 + 114*sqrt(12657)/78125)**(S(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 \
{i.n(chop=True) for i in ans} == \
{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) is S.EmptySet
def test_no_sol():
assert solveset(1 - oo*x) is S.EmptySet
assert solveset(oo*x, x) is S.EmptySet
assert solveset(oo*x - oo, x) is S.EmptySet
assert solveset_real(4, x) is S.EmptySet
assert solveset_real(exp(x), x) is S.EmptySet
assert solveset_real(x**2 + 1, x) is S.EmptySet
assert solveset_real(-3*a/sqrt(x), x) is S.EmptySet
assert solveset_real(1/x, x) is S.EmptySet
assert solveset_real(-(1 + x)/(2 + x)**2 + 1/(2 + x), x
) is S.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) is S.EmptySet
assert solveset_real((x - 1)/(1 + 1/(x - 1)), x) is S.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"""
x = Symbol('x', real=True)
y = Symbol('y', real=True)
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():
n = Dummy('n')
raises(ValueError, lambda: solveset(Abs(x) - 1, x))
assert solveset(Abs(x) - n, x, S.Reals).dummy_eq(
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 si in sol.subs(reps):
assert not eqab.subs(x, si)
assert dumeq(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 dumeq(solveset(sin(x)**2 - 2*sin(x) + 1, x), ImageSet(Lambda(n, 2*n*pi + pi/2), S.Integers))
assert dumeq(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
assert solveset_real(eq, x) == Union(
Interval.open(0, 1), Interval.open(1, 2))
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)
# issue 19718
g = Piecewise((1, x > 10), (0, True))
assert solveset(g > 0, x, S.Reals) == Interval.open(10, oo)
from sympy.logic.boolalg import BooleanTrue
f = BooleanTrue()
assert solveset(f, x, domain=Interval(-3, 10)) == Interval(-3, 10)
# issue 20552
f = Piecewise((0, Eq(x, 0)), (x**2/Abs(x), True))
g = Piecewise((0, Eq(x, pi)), ((x - pi)/sin(x), True))
assert solveset(f, x, domain=S.Reals) == FiniteSet(0)
assert solveset(g) == FiniteSet(pi)
def test_solveset_complex_polynomial():
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) is 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():
assert dumeq(solveset_complex(exp(x) - 1, x),
imageset(Lambda(n, I*2*n*pi), S.Integers))
assert dumeq(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 dumeq(solveset_complex(sinh(x).rewrite(exp), x),
imageset(Lambda(n, n*pi*I), S.Integers))
def test_solveset_real_exp():
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 dumeq(s, imageset(Lambda(n, pi*n), S.Integers) - \
imageset(Lambda(n, pi*n + pi/2), S.Integers))
@_both_exp_pow
def test_solve_trig():
assert dumeq(solveset_real(sin(x), x),
Union(imageset(Lambda(n, 2*pi*n), S.Integers),
imageset(Lambda(n, 2*pi*n + pi), S.Integers)))
assert dumeq(solveset_real(sin(x) - 1, x),
imageset(Lambda(n, 2*pi*n + pi/2), S.Integers))
assert dumeq(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 dumeq(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
assert dumeq(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)))
assert dumeq(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 dumeq(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))
assert dumeq(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 dumeq(solveset_real(cos(2*x)*cos(4*x) - 1, x),
ImageSet(Lambda(n, n*pi), S.Integers))
assert dumeq(solveset(sin(x/10) + Rational(3, 4)), Union(
ImageSet(Lambda(n, 20*n*pi + 10*atan(3*sqrt(7)/7) + 10*pi), S.Integers),
ImageSet(Lambda(n, 20*n*pi - 10*atan(3*sqrt(7)/7) + 20*pi), S.Integers)))
assert dumeq(solveset(cos(x/15) + cos(x/5)), Union(
ImageSet(Lambda(n, 30*n*pi + 15*pi/2), S.Integers),
ImageSet(Lambda(n, 30*n*pi + 45*pi/2), S.Integers),
ImageSet(Lambda(n, 30*n*pi + 75*pi/4), S.Integers),
ImageSet(Lambda(n, 30*n*pi + 45*pi/4), S.Integers),
ImageSet(Lambda(n, 30*n*pi + 105*pi/4), S.Integers),
ImageSet(Lambda(n, 30*n*pi + 15*pi/4), S.Integers)))
assert dumeq(solveset(sec(sqrt(2)*x/3) + 5), Union(
ImageSet(Lambda(n, 3*sqrt(2)*(2*n*pi - pi + atan(2*sqrt(6)))/2), S.Integers),
ImageSet(Lambda(n, 3*sqrt(2)*(2*n*pi - atan(2*sqrt(6)) + pi)/2), S.Integers)))
assert dumeq(simplify(solveset(tan(pi*x) - cot(pi/2*x))), Union(
ImageSet(Lambda(n, 4*n + 1), S.Integers),
ImageSet(Lambda(n, 4*n + 3), S.Integers),
ImageSet(Lambda(n, 4*n + Rational(7, 3)), S.Integers),
ImageSet(Lambda(n, 4*n + Rational(5, 3)), S.Integers),
ImageSet(Lambda(n, 4*n + Rational(11, 3)), S.Integers),
ImageSet(Lambda(n, 4*n + Rational(1, 3)), S.Integers)))
assert dumeq(solveset(cos(9*x)), Union(
ImageSet(Lambda(n, 2*n*pi/9 + pi/18), S.Integers),
ImageSet(Lambda(n, 2*n*pi/9 + pi/6), S.Integers)))
assert dumeq(solveset(sin(8*x) + cot(12*x), x, S.Reals), Union(
ImageSet(Lambda(n, n*pi/2 + pi/8), S.Integers),
ImageSet(Lambda(n, n*pi/2 + 3*pi/8), S.Integers),
ImageSet(Lambda(n, n*pi/2 + 5*pi/16), S.Integers),
ImageSet(Lambda(n, n*pi/2 + 3*pi/16), S.Integers),
ImageSet(Lambda(n, n*pi/2 + 7*pi/16), S.Integers),
ImageSet(Lambda(n, n*pi/2 + pi/16), S.Integers)))
# This is the only remaining solveset test that actually ends up being solved
# by _solve_trig2(). All others are handled by the improved _solve_trig1.
assert dumeq(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)))
# issue #16870
assert dumeq(simplify(solveset(sin(x/180*pi) - S.Half, x, S.Reals)), Union(
ImageSet(Lambda(n, 360*n + 150), S.Integers),
ImageSet(Lambda(n, 360*n + 30), 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(3)/2, log(3)/2)
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(4 + sqrt(17))/2)
assert solveset_real(sinh(x) + tanh(x) - 1, x) == FiniteSet(
log(sqrt(2)/2 + sqrt(-S(1)/2 + sqrt(2))))
assert dumeq(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 dumeq(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)))
assert dumeq(solveset(sinh(x/10) + Rational(3, 4)), Union(
ImageSet(Lambda(n, 10*I*(2*n*pi + pi) + 10*log(2)), S.Integers),
ImageSet(Lambda(n, 20*n*I*pi - 10*log(2)), S.Integers)))
assert dumeq(solveset(cosh(x/15) + cosh(x/5)), Union(
ImageSet(Lambda(n, 15*I*(2*n*pi + pi/2)), S.Integers),
ImageSet(Lambda(n, 15*I*(2*n*pi - pi/2)), S.Integers),
ImageSet(Lambda(n, 15*I*(2*n*pi - 3*pi/4)), S.Integers),
ImageSet(Lambda(n, 15*I*(2*n*pi + 3*pi/4)), S.Integers),
ImageSet(Lambda(n, 15*I*(2*n*pi - pi/4)), S.Integers),
ImageSet(Lambda(n, 15*I*(2*n*pi + pi/4)), S.Integers)))
assert dumeq(solveset(sech(sqrt(2)*x/3) + 5), Union(
ImageSet(Lambda(n, 3*sqrt(2)*I*(2*n*pi - pi + atan(2*sqrt(6)))/2), S.Integers),
ImageSet(Lambda(n, 3*sqrt(2)*I*(2*n*pi - atan(2*sqrt(6)) + pi)/2), S.Integers)))
assert dumeq(solveset(tanh(pi*x) - coth(pi/2*x)), Union(
ImageSet(Lambda(n, 2*I*(2*n*pi + pi/2)/pi), S.Integers),
ImageSet(Lambda(n, 2*I*(2*n*pi - pi/2)/pi), S.Integers)))
assert dumeq(solveset(cosh(9*x)), Union(
ImageSet(Lambda(n, I*(2*n*pi + pi/2)/9), S.Integers),
ImageSet(Lambda(n, I*(2*n*pi - pi/2)/9), S.Integers)))
# issues #9606 / #9531:
assert solveset(sinh(x), x, S.Reals) == FiniteSet(0)
assert dumeq(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)))
# issues #11218 / #18427
assert dumeq(solveset(sin(pi*x), x, S.Reals), Union(
ImageSet(Lambda(n, (2*n*pi + pi)/pi), S.Integers),
ImageSet(Lambda(n, 2*n), S.Integers)))
assert dumeq(solveset(sin(pi*x), x), Union(
ImageSet(Lambda(n, (2*n*pi + pi)/pi), S.Integers),
ImageSet(Lambda(n, 2*n), S.Integers)))
# issue #17543
assert dumeq(simplify(solveset(I*cot(8*x - 8*E), x)), Union(
ImageSet(Lambda(n, n*pi/4 - 13*pi/16 + E), S.Integers),
ImageSet(Lambda(n, n*pi/4 - 11*pi/16 + E), S.Integers)))
# issues #18490 / #19489
assert solveset(cosh(x) + cosh(3*x) - cosh(5*x), x, S.Reals
).dummy_eq(ConditionSet(x,
Eq(cosh(x) + cosh(3*x) - cosh(5*x), 0), S.Reals))
assert solveset(sinh(8*x) + coth(12*x)).dummy_eq(
ConditionSet(x, Eq(sinh(8*x) + coth(12*x), 0), S.Complexes))
def test_solve_trig_hyp_symbolic():
# actual solver: _solve_trig1
assert dumeq(solveset(sin(a*x), x), ConditionSet(x, Ne(a, 0), Union(
ImageSet(Lambda(n, (2*n*pi + pi)/a), S.Integers),
ImageSet(Lambda(n, 2*n*pi/a), S.Integers))))
assert dumeq(solveset(cosh(x/a), x), ConditionSet(x, Ne(a, 0), Union(
ImageSet(Lambda(n, I*a*(2*n*pi + pi/2)), S.Integers),
ImageSet(Lambda(n, I*a*(2*n*pi - pi/2)), S.Integers))))
assert dumeq(solveset(sin(2*sqrt(3)/3*a**2/(b*pi)*x)
+ cos(4*sqrt(3)/3*a**2/(b*pi)*x), x),
ConditionSet(x, Ne(b, 0) & Ne(a**2, 0), Union(
ImageSet(Lambda(n, sqrt(3)*pi*b*(2*n*pi + pi/2)/(2*a**2)), S.Integers),
ImageSet(Lambda(n, sqrt(3)*pi*b*(2*n*pi - 5*pi/6)/(2*a**2)), S.Integers),
ImageSet(Lambda(n, sqrt(3)*pi*b*(2*n*pi - pi/6)/(2*a**2)), S.Integers))))
assert dumeq(simplify(solveset(cot((1 + I)*x) - cot((3 + 3*I)*x), x)), Union(
ImageSet(Lambda(n, pi*(1 - I)*(4*n + 1)/4), S.Integers),
ImageSet(Lambda(n, pi*(1 - I)*(4*n - 1)/4), S.Integers)))
assert dumeq(solveset(cosh((a**2 + 1)*x) - 3, x),
ConditionSet(x, Ne(a**2 + 1, 0), Union(
ImageSet(Lambda(n, (2*n*I*pi + log(3 - 2*sqrt(2)))/(a**2 + 1)), S.Integers),
ImageSet(Lambda(n, (2*n*I*pi + log(2*sqrt(2) + 3))/(a**2 + 1)), S.Integers))))
ar = Symbol('ar', real=True)
assert solveset(cosh((ar**2 + 1)*x) - 2, x, S.Reals) == FiniteSet(
log(sqrt(3) + 2)/(ar**2 + 1), log(2 - sqrt(3))/(ar**2 + 1))
def test_issue_9616():
assert dumeq(solveset(sinh(x) + tanh(x) - 1, x), Union(
ImageSet(Lambda(n, 2*n*I*pi + log(sqrt(2)/2 + sqrt(-S.Half + sqrt(2)))), S.Integers),
ImageSet(Lambda(n, I*(2*n*pi - atan(sqrt(2)*sqrt(S.Half + sqrt(2))) + pi)
+ log(sqrt(1 + sqrt(2)))), S.Integers),
ImageSet(Lambda(n, I*(2*n*pi + pi) + log(-sqrt(2)/2 + sqrt(-S.Half + sqrt(2)))), S.Integers),
ImageSet(Lambda(n, I*(2*n*pi - pi + atan(sqrt(2)*sqrt(S.Half + sqrt(2))))
+ log(sqrt(1 + sqrt(2)))), S.Integers)))
f1 = (sinh(x)).rewrite(exp)
f2 = (tanh(x)).rewrite(exp)
assert dumeq(solveset(f1 + f2 - 1, x), Union(
Complement(ImageSet(
Lambda(n, I*(2*n*pi + pi) + log(-sqrt(2)/2 + sqrt(-S.Half + sqrt(2)))), S.Integers),
ImageSet(Lambda(n, I*(2*n*pi + pi)/2), S.Integers)),
Complement(ImageSet(Lambda(n, I*(2*n*pi - pi + atan(sqrt(2)*sqrt(S.Half + sqrt(2))))
+ log(sqrt(1 + sqrt(2)))), S.Integers),
ImageSet(Lambda(n, I*(2*n*pi + pi)/2), S.Integers)),
Complement(ImageSet(Lambda(n, I*(2*n*pi - atan(sqrt(2)*sqrt(S.Half + sqrt(2))) + pi)
+ log(sqrt(1 + sqrt(2)))), S.Integers),
ImageSet(Lambda(n, I*(2*n*pi + pi)/2), S.Integers)),
Complement(
ImageSet(Lambda(n, 2*n*I*pi + log(sqrt(2)/2 + sqrt(-S.Half + sqrt(2)))), S.Integers),
ImageSet(Lambda(n, I*(2*n*pi + pi)/2), 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():
n = Dummy('n')
assert dumeq(solveset_real(sin(x), x),
imageset(Lambda(n, n*pi), S.Integers))
assert dumeq(solveset_real(cos(x), x),
imageset(Lambda(n, n*pi + pi/2), S.Integers))
assert dumeq(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) is S.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))
@_both_exp_pow
def test_solveset():
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 dumeq(solveset(exp(x) - 1, x), imageset(Lambda(n, 2*I*pi*n), S.Integers))
assert dumeq(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)}
# issue 19977
assert solveset(atan(log(x)) > 0, x, domain=Interval.open(0, oo)) == Interval.open(1, oo)
@_both_exp_pow
def test_multi_exp():
k1, k2, k3 = symbols('k1, k2, k3')
assert dumeq(solveset(exp(exp(x)) - 5, x),\
imageset(Lambda(((k1, n),), I*(2*k1*pi + arg(2*n*I*pi + log(5))) + log(Abs(2*n*I*pi + log(5)))),\
ProductSet(S.Integers, S.Integers)))
assert dumeq(solveset((d*exp(exp(a*x + b)) + c), x),\
imageset(Lambda(x, (-b + x)/a), ImageSet(Lambda(((k1, n),), \
I*(2*k1*pi + arg(I*(2*n*pi + arg(-c/d)) + log(Abs(c/d)))) + log(Abs(I*(2*n*pi + arg(-c/d)) + log(Abs(c/d))))), \
ProductSet(S.Integers, S.Integers))))
assert dumeq(solveset((d*exp(exp(exp(a*x + b))) + c), x),\
imageset(Lambda(x, (-b + x)/a), ImageSet(Lambda(((k2, k1, n),), \
I*(2*k2*pi + arg(I*(2*k1*pi + arg(I*(2*n*pi + arg(-c/d)) + log(Abs(c/d)))) + \
log(Abs(I*(2*n*pi + arg(-c/d)) + log(Abs(c/d)))))) + log(Abs(I*(2*k1*pi + arg(I*(2*n*pi + arg(-c/d)) + \
log(Abs(c/d)))) + log(Abs(I*(2*n*pi + arg(-c/d)) + log(Abs(c/d))))))), \
ProductSet(S.Integers, S.Integers, S.Integers))))
assert dumeq(solveset((d*exp(exp(exp(exp(a*x + b)))) + c), x),\
ImageSet(Lambda(x, (-b + x)/a), ImageSet(Lambda(((k3, k2, k1, n),), \
I*(2*k3*pi + arg(I*(2*k2*pi + arg(I*(2*k1*pi + arg(I*(2*n*pi + arg(-c/d)) + log(Abs(c/d)))) + \
log(Abs(I*(2*n*pi + arg(-c/d)) + log(Abs(c/d)))))) + log(Abs(I*(2*k1*pi + arg(I*(2*n*pi + arg(-c/d)) + \
log(Abs(c/d)))) + log(Abs(I*(2*n*pi + arg(-c/d)) + log(Abs(c/d)))))))) + log(Abs(I*(2*k2*pi + \
arg(I*(2*k1*pi + arg(I*(2*n*pi + arg(-c/d)) + log(Abs(c/d)))) + log(Abs(I*(2*n*pi + arg(-c/d)) + log(Abs(c/d)))))) + \
log(Abs(I*(2*k1*pi + arg(I*(2*n*pi + arg(-c/d)) + log(Abs(c/d)))) + log(Abs(I*(2*n*pi + arg(-c/d)) + log(Abs(c/d))))))))), \
ProductSet(S.Integers, S.Integers, S.Integers, S.Integers))))
def test__solveset_multi():
from sympy.solvers.solveset import _solveset_multi
from sympy.sets import Reals
# Basic univariate case:
assert _solveset_multi([x**2-1], [x], [S.Reals]) == FiniteSet((1,), (-1,))
# Linear systems of two equations
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 dumeq(_solveset_multi([x+y], [x, y], [Reals, Reals]), ImageSet(Lambda(x, (x, -x)), Reals))
assert dumeq(_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:
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 theta
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 dumeq(_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 dumeq(_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
) is S.Reals
assert solveset(Eq(x**2 + x*sin(x), 1), x, domain=S.Reals
).dummy_eq(ConditionSet(x, Eq(x**2 + x*sin(x) - 1, 0), S.Reals))
assert dumeq(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
).dummy_eq(ConditionSet(x, x + sin(x) > 1, S.Reals))
assert solveset(Eq(sin(Abs(x)), x), x, domain=S.Reals
).dummy_eq(ConditionSet(x, Eq(-x + sin(Abs(x)), 0), S.Reals))
assert solveset(y**x-z, x, S.Reals
).dummy_eq(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():
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():
solution = solveset(exp(x) + sin(x), x, S.Reals)
unsolved_object = ConditionSet(x, Eq(exp(x) + sin(x), 0), S.Reals)
assert solution.dummy_eq(unsolved_object)
def test_issue_9522():
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) is S.EmptySet
assert solveset(expr2, x, S.Reals) is S.EmptySet
def test_solvify():
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_solvify_piecewise():
p1 = Piecewise((0, x < -1), (x**2, x <= 1), (log(x), True))
p2 = Piecewise((0, x < -10), (x**2 + 5*x - 6, x >= -9))
p3 = Piecewise((0, Eq(x, 0)), (x**2/Abs(x), True))
p4 = Piecewise((0, Eq(x, pi)), ((x - pi)/sin(x), True))
# issue 21079
assert solvify(p1, x, S.Reals) == [0]
assert solvify(p2, x, S.Reals) == [-6, 1]
assert solvify(p3, x, S.Reals) == [0]
assert solvify(p4, x, S.Reals) == [pi]
def test_abs_invert_solvify():
x = Symbol('x',positive=True)
assert solvify(sin(Abs(x)), x, S.Reals) == [0, pi]
x = Symbol('x')
assert solvify(sin(Abs(x)), x, S.Reals) is None
def test_linear_eq_to_matrix():
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(NonlinearError, lambda: linear_eq_to_matrix(Eq(1/x + x, 1/x), [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_issue_10085():
assert invert_real(exp(x),0,x) == (x, S.EmptySet)
def test_linsolve():
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(NonlinearError, lambda: linsolve([x + y - 1, x ** 2 + y - 3], [x, y]))
raises(NonlinearError, 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 = Matrix([[a, b], [c, d]])
B = Matrix([[e], [g]])
system2 = (A, B)
sol = FiniteSet(((-b*g + d*e)/(a*d - b*c), (a*g - 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)) is S.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
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('tau00 tau01 tau02 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('tau00 tau01 tau02 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
kN = kilo*newton
Eqns = [8*kN + x + y, 28*kN*meter + 3*x*meter]
assert linsolve(Eqns, x, y) == {
(kilo*newton*Rational(-28, 3), kN*Rational(4, 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)}
# corner cases
#
# XXX: The case below should give the same as for [0]
# assert linsolve([], [x]) == {(x,)}
assert linsolve([], [x]) is S.EmptySet
assert linsolve([0], [x]) == {(x,)}
assert linsolve([x], [x, y]) == {(0, y)}
assert linsolve([x, 0], [x, y]) == {(0, y)}
def test_linsolve_large_sparse():
#
# This is mainly a performance test
#
def _mk_eqs_sol(n):
xs = symbols('x:{}'.format(n))
ys = symbols('y:{}'.format(n))
syms = xs + ys
eqs = []
sol = (-S.Half,) * n + (S.Half,) * n
for xi, yi in zip(xs, ys):
eqs.extend([xi + yi, xi - yi + 1])
return eqs, syms, FiniteSet(sol)
n = 500
eqs, syms, sol = _mk_eqs_sol(n)
assert linsolve(eqs, syms) == sol
def test_linsolve_immutable():
A = ImmutableDenseMatrix([[1, 1, 2], [0, 1, 2], [0, 0, 1]])
B = ImmutableDenseMatrix([2, 1, -1])
assert linsolve([A, B], (x, y, z)) == FiniteSet((1, 3, -1))
A = ImmutableDenseMatrix([[1, 1, 7], [1, -1, 3]])
assert linsolve(A) == FiniteSet((5, 2))
def test_solve_decomposition():
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 dumeq(solve_decomposition(f2, x, S.Reals), s3)
assert dumeq(solve_decomposition(f3, x, S.Reals), Union(s1, s2, s3))
assert dumeq(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]) == S.EmptySet
soln = (ImageSet(Lambda(n, 2*n*pi + pi/2), S.Integers),)
assert dumeq(nonlinsolve([sin(x) - 1], [x]), FiniteSet(tuple(soln)))
soln = ((ImageSet(Lambda(n, 2*n*pi + pi), S.Integers), FiniteSet(1)),
(ImageSet(Lambda(n, 2*n*pi), S.Integers), FiniteSet(1,)))
assert dumeq(nonlinsolve([sin(x), y - 1], [x, y]), FiniteSet(*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,))
assert nonlinsolve([Eq(1, x + y), Eq(1, -x + y - 1), Eq(1, -x + y - 1)], x, y) == FiniteSet(
(-S.Half, 3*S.Half))
def test_nonlinsolve_abs():
soln = FiniteSet((y, y), (-y, y))
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]))
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 dumeq(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 dumeq(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 dumeq(nonlinsolve(sys, [x, y]), FiniteSet((soln_x, soln_y)))
def test_nonlinsolve_positive_dimensional():
x, y, a, b, c, d = symbols('x, y, 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
assert nonlinsolve([x**4 - 3*x**2 + y*x, x*z**2, y*z - 1], [x, y, z]) == \
{(0, 1/z, z)}
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))
assert nonlinsolve([-x**2 - y**2 + z, -2*x, -2*y, S.One], [x, y, z]) == S.EmptySet
assert nonlinsolve([x + y + z, S.One, S.One, S.One], [x, y, z]) == S.EmptySet
system = [-x**2*z**2 + x*y*z + y**4, -2*x*z**2 + y*z, x*z + 4*y**3, -2*x**2*z + x*y]
assert nonlinsolve(system, [x, y, z]) == FiniteSet((0, 0, z), (x, 0, 0))
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():
n = Dummy('n')
assert dumeq(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 dumeq(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 dumeq(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)})
system = [exp(x) - 2, y ** 2 - 2]
assert dumeq(nonlinsolve(system, [x, y]), {
(log(2), -sqrt(2)), (log(2), sqrt(2)),
(ImageSet(Lambda(n, 2*n*I*pi + log(2)), S.Integers), FiniteSet(-sqrt(2))),
(ImageSet(Lambda(n, 2 * n * I * pi + log(2)), S.Integers), FiniteSet(sqrt(2)))})
def test_nonlinsolve_radical():
assert nonlinsolve([sqrt(y) - x - z, y - 1], [x, y, z]) == {(1 - z, 1, z)}
def test_nonlinsolve_inexact():
sol = [(-1.625, -1.375), (1.625, 1.375)]
res = nonlinsolve([(x + y)**2 - 9, x**2 - y**2 - 0.75], [x, y])
assert all(abs(res.args[i][j]-sol[i][j]) < 1e-9
for i in range(2) for j in range(2))
assert nonlinsolve([(x + y)**2 - 9, (x + y)**2 - 0.75], [x, y]) == S.EmptySet
assert nonlinsolve([y**2 + (x - 0.5)**2 - 0.0625, 2*x - 1.0, 2*y], [x, y]) == \
S.EmptySet
res = nonlinsolve([x**2 + y - 0.5, (x + y)**2, log(z)], [x, y, z])
sol = [(-0.366025403784439, 0.366025403784439, 1),
(-0.366025403784439, 0.366025403784439, 1),
(1.36602540378444, -1.36602540378444, 1)]
assert all(abs(res.args[i][j]-sol[i][j]) < 1e-9
for i in range(3) for j in range(3))
res = nonlinsolve([y - x**2, x**5 - x + 1.0], [x, y])
sol = [(-1.16730397826142, 1.36259857766493),
(-0.181232444469876 - 1.08395410131771*I,
-1.14211129483496 + 0.392895302949911*I),
(-0.181232444469876 + 1.08395410131771*I,
-1.14211129483496 - 0.392895302949911*I),
(0.764884433600585 - 0.352471546031726*I,
0.460812006002492 - 0.539199997693599*I),
(0.764884433600585 + 0.352471546031726*I,
0.460812006002492 + 0.539199997693599*I)]
assert all(abs(res.args[i][j] - sol[i][j]) < 1e-9
for i in range(5) for j in range(2))
@XFAIL
def test_solve_nonlinear_trans():
# After the transcendental equation solver these will work
x, y = symbols('x, y', 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_14642():
x = Symbol('x')
n1 = 0.5*x**3+x**2+0.5+I #add I in the Polynomials
solution = solveset(n1, x)
assert abs(solution.args[0] - (-2.28267560928153 - 0.312325580497716*I)) <= 1e-9
assert abs(solution.args[1] - (-0.297354141679308 + 1.01904778618762*I)) <= 1e-9
assert abs(solution.args[2] - (0.580029750960839 - 0.706722205689907*I)) <= 1e-9
# Symbolic
n1 = S.Half*x**3+x**2+S.Half+I
res = FiniteSet(-((3*sqrt(3)*31985**(S(1)/4)*sin(atan(S(172)/49)/2)/2 +
S(43)/2)**2 + (27 + 3*sqrt(3)*31985**(S(1)/4)*cos(atan(S(172)/49)
/2)/2)**2)**(S(1)/6)*cos(atan((27 + 3*sqrt(3)*31985**(S(1)/4)*
cos(atan(S(172)/49)/2)/2)/(3*sqrt(3)*31985**(S(1)/4)*sin(atan(
S(172)/49)/2)/2 + S(43)/2))/3)/3 - S(2)/3 - 4*cos(atan((27 +
3*sqrt(3)*31985**(S(1)/4)*cos(atan(S(172)/49)/2)/2)/(3*sqrt(3)*
31985**(S(1)/4)*sin(atan(S(172)/49)/2)/2 + S(43)/2))/3)/(3*((3*
sqrt(3)*31985**(S(1)/4)*sin(atan(S(172)/49)/2)/2 + S(43)/2)**2 +
(27 + 3*sqrt(3)*31985**(S(1)/4)*cos(atan(S(172)/49)/2)/2)**2)**(S(1)/
6)) + I*(-((3*sqrt(3)*31985**(S(1)/4)*sin(atan(S(172)/49)/2)/2 +
S(43)/2)**2 + (27 + 3*sqrt(3)*31985**(S(1)/4)*cos(atan(S(172)/49)/
2)/2)**2)**(S(1)/6)*sin(atan((27 + 3*sqrt(3)*31985**(S(1)/4)*cos(
atan(S(172)/49)/2)/2)/(3*sqrt(3)*31985**(S(1)/4)*sin(atan(S(172)/49)
/2)/2 + S(43)/2))/3)/3 + 4*sin(atan((27 + 3*sqrt(3)*31985**(S(1)/4)*
cos(atan(S(172)/49)/2)/2)/(3*sqrt(3)*31985**(S(1)/4)*sin(atan(S(172)
/49)/2)/2 + S(43)/2))/3)/(3*((3*sqrt(3)*31985**(S(1)/4)*sin(atan(
S(172)/49)/2)/2 + S(43)/2)**2 + (27 + 3*sqrt(3)*31985**(S(1)/4)*
cos(atan(S(172)/49)/2)/2)**2)**(S(1)/6))), -S(2)/3 - sqrt(3)*((3*
sqrt(3)*31985**(S(1)/4)*sin(atan(S(172)/49)/2)/2 + S(43)/2)**2 +
(27 + 3*sqrt(3)*31985**(S(1)/4)*cos(atan(S(172)/49)/2)/2)**2)**(S(1)
/6)*sin(atan((27 + 3*sqrt(3)*31985**(S(1)/4)*cos(atan(S(172)/49)/2)
/2)/(3*sqrt(3)*31985**(S(1)/4)*sin(atan(S(172)/49)/2)/2 + S(43)/2))
/3)/6 - 4*re(1/((-S(1)/2 - sqrt(3)*I/2)*(S(43)/2 + 27*I + sqrt(-256 +
(43 + 54*I)**2)/2)**(S(1)/3)))/3 + ((3*sqrt(3)*31985**(S(1)/4)*sin(
atan(S(172)/49)/2)/2 + S(43)/2)**2 + (27 + 3*sqrt(3)*31985**(S(1)/4)*
cos(atan(S(172)/49)/2)/2)**2)**(S(1)/6)*cos(atan((27 + 3*sqrt(3)*
31985**(S(1)/4)*cos(atan(S(172)/49)/2)/2)/(3*sqrt(3)*31985**(S(1)/4)*
sin(atan(S(172)/49)/2)/2 + S(43)/2))/3)/6 + I*(-4*im(1/((-S(1)/2 -
sqrt(3)*I/2)*(S(43)/2 + 27*I + sqrt(-256 + (43 + 54*I)**2)/2)**(S(1)/
3)))/3 + ((3*sqrt(3)*31985**(S(1)/4)*sin(atan(S(172)/49)/2)/2 +
S(43)/2)**2 + (27 + 3*sqrt(3)*31985**(S(1)/4)*cos(atan(S(172)/49)/2)
/2)**2)**(S(1)/6)*sin(atan((27 + 3*sqrt(3)*31985**(S(1)/4)*cos(atan(
S(172)/49)/2)/2)/(3*sqrt(3)*31985**(S(1)/4)*sin(atan(S(172)/49)/2)/2 +
S(43)/2))/3)/6 + sqrt(3)*((3*sqrt(3)*31985**(S(1)/4)*sin(atan(S(172)/
49)/2)/2 + S(43)/2)**2 + (27 + 3*sqrt(3)*31985**(S(1)/4)*cos(atan(
S(172)/49)/2)/2)**2)**(S(1)/6)*cos(atan((27 + 3*sqrt(3)*31985**(S(1)/
4)*cos(atan(S(172)/49)/2)/2)/(3*sqrt(3)*31985**(S(1)/4)*sin(atan(
S(172)/49)/2)/2 + S(43)/2))/3)/6), -S(2)/3 - 4*re(1/((-S(1)/2 +
sqrt(3)*I/2)*(S(43)/2 + 27*I + sqrt(-256 + (43 + 54*I)**2)/2)**(S(1)
/3)))/3 + sqrt(3)*((3*sqrt(3)*31985**(S(1)/4)*sin(atan(S(172)/49)/2)/2 +
S(43)/2)**2 + (27 + 3*sqrt(3)*31985**(S(1)/4)*cos(atan(S(172)/49)/2)
/2)**2)**(S(1)/6)*sin(atan((27 + 3*sqrt(3)*31985**(S(1)/4)*cos(atan(
S(172)/49)/2)/2)/(3*sqrt(3)*31985**(S(1)/4)*sin(atan(S(172)/49)/2)/2 +
S(43)/2))/3)/6 + ((3*sqrt(3)*31985**(S(1)/4)*sin(atan(S(172)/49)/2)/2 +
S(43)/2)**2 + (27 + 3*sqrt(3)*31985**(S(1)/4)*cos(atan(S(172)/49)/2)
/2)**2)**(S(1)/6)*cos(atan((27 + 3*sqrt(3)*31985**(S(1)/4)*cos(atan(
S(172)/49)/2)/2)/(3*sqrt(3)*31985**(S(1)/4)*sin(atan(S(172)/49)/2)/2 +
S(43)/2))/3)/6 + I*(-sqrt(3)*((3*sqrt(3)*31985**(S(1)/4)*sin(atan(
S(172)/49)/2)/2 + S(43)/2)**2 + (27 + 3*sqrt(3)*31985**(S(1)/4)*cos(
atan(S(172)/49)/2)/2)**2)**(S(1)/6)*cos(atan((27 + 3*sqrt(3)*31985**(
S(1)/4)*cos(atan(S(172)/49)/2)/2)/(3*sqrt(3)*31985**(S(1)/4)*sin(
atan(S(172)/49)/2)/2 + S(43)/2))/3)/6 + ((3*sqrt(3)*31985**(S(1)/4)*
sin(atan(S(172)/49)/2)/2 + S(43)/2)**2 + (27 + 3*sqrt(3)*31985**(S(1)/4)*
cos(atan(S(172)/49)/2)/2)**2)**(S(1)/6)*sin(atan((27 + 3*sqrt(3)*31985**(
S(1)/4)*cos(atan(S(172)/49)/2)/2)/(3*sqrt(3)*31985**(S(1)/4)*sin(
atan(S(172)/49)/2)/2 + S(43)/2))/3)/6 - 4*im(1/((-S(1)/2 + sqrt(3)*I/2)*
(S(43)/2 + 27*I + sqrt(-256 + (43 + 54*I)**2)/2)**(S(1)/3)))/3))
assert solveset(n1, x) == res
def test_issue_13961():
V = (ax, bx, cx, gx, jx, lx, mx, nx, q) = symbols('ax bx cx gx jx lx mx nx q')
S = (ax*q - lx*q - mx, ax - gx*q - lx, bx*q**2 + cx*q - jx*q - nx, q*(-ax*q + lx*q + mx), q*(-ax + gx*q + lx))
sol = FiniteSet((lx + mx/q, (-cx*q + jx*q + nx)/q**2, cx, mx/q**2, jx, lx, mx, nx, Complement({q}, {0})),
(lx + mx/q, (cx*q - jx*q - nx)/q**2*-1, cx, mx/q**2, jx, lx, mx, nx, Complement({q}, {0})))
assert nonlinsolve(S, *V) == sol
# The two solutions are in fact identical, so even better if only one is returned
def test_issue_14541():
solutions = solveset(sqrt(-x**2 - 2.0), x)
assert abs(solutions.args[0]+1.4142135623731*I) <= 1e-9
assert abs(solutions.args[1]-1.4142135623731*I) <= 1e-9
def test_issue_13396():
expr = -2*y*exp(-x**2 - y**2)*Abs(x)
sol = FiniteSet(0)
assert solveset(expr, y, domain=S.Reals) == sol
# Related type of equation also solved here
assert solveset(atan(x**2 - y**2)-pi/2, y, S.Reals) is S.EmptySet
def test_issue_12032():
sol = FiniteSet(-sqrt(-2/(3*(Rational(1, 16) + sqrt(849)/144)**(Rational(1, 3))) +
2*(Rational(1, 16) + sqrt(849)/144)**(Rational(1, 3)))/2 +
sqrt(Abs(-2*(Rational(1, 16) + sqrt(849)/144)**(Rational(1, 3)) +
2/(3*(Rational(1, 16) + sqrt(849)/144)**(Rational(1, 3))) +
2/sqrt(-2/(3*(Rational(1, 16) + sqrt(849)/144)**(Rational(1, 3))) +
2*(Rational(1, 16) + sqrt(849)/144)**(Rational(1, 3)))))/2,
-sqrt(Abs(-2*(Rational(1, 16) + sqrt(849)/144)**(Rational(1, 3)) +
2/(3*(Rational(1, 16) + sqrt(849)/144)**(Rational(1, 3))) +
2/sqrt(-2/(3*(Rational(1, 16) + sqrt(849)/144)**(Rational(1, 3))) +
2*(Rational(1, 16) + sqrt(849)/144)**(Rational(1, 3)))))/2 -
sqrt(-2/(3*(Rational(1, 16) + sqrt(849)/144)**(Rational(1, 3))) +
2*(Rational(1, 16) + sqrt(849)/144)**(Rational(1, 3)))/2,
sqrt(-2/(3*(Rational(1, 16) + sqrt(849)/144)**(Rational(1, 3))) +
2*(Rational(1, 16) + sqrt(849)/144)**(Rational(1, 3)))/2 -
I*sqrt(Abs(-2/sqrt(-2/(3*(Rational(1, 16) + sqrt(849)/144)**(Rational(1, 3))) +
2*(Rational(1, 16) + sqrt(849)/144)**(Rational(1, 3))) -
2*(Rational(1, 16) + sqrt(849)/144)**(Rational(1, 3)) +
2/(3*(Rational(1, 16) + sqrt(849)/144)**(Rational(1, 3)))))/2,
sqrt(-2/(3*(Rational(1, 16) + sqrt(849)/144)**(Rational(1, 3))) +
2*(Rational(1, 16) + sqrt(849)/144)**(Rational(1, 3)))/2 +
I*sqrt(Abs(-2/sqrt(-2/(3*(Rational(1, 16) + sqrt(849)/144)**(Rational(1, 3))) +
2*(Rational(1, 16) + sqrt(849)/144)**(Rational(1, 3))) -
2*(Rational(1, 16) + sqrt(849)/144)**(Rational(1, 3)) +
2/(3*(Rational(1, 16) + sqrt(849)/144)**(Rational(1,3)))))/2)
assert solveset(x**4 + x - 1, x) == sol
def test_issue_10876():
assert solveset(1/sqrt(x), x) == S.EmptySet
def test_issue_19050():
# test_issue_19050 --> TypeError removed
assert dumeq(nonlinsolve([x + y, sin(y)], [x, y]),
FiniteSet((ImageSet(Lambda(n, -2*n*pi), S.Integers), ImageSet(Lambda(n, 2*n*pi), S.Integers)),\
(ImageSet(Lambda(n, -2*n*pi - pi), S.Integers), ImageSet(Lambda(n, 2*n*pi + pi), S.Integers))))
assert dumeq(nonlinsolve([x + y, sin(y) + cos(y)], [x, y]),
FiniteSet((ImageSet(Lambda(n, -2*n*pi - 3*pi/4), S.Integers), ImageSet(Lambda(n, 2*n*pi + 3*pi/4), S.Integers)), \
(ImageSet(Lambda(n, -2*n*pi - 7*pi/4), S.Integers), ImageSet(Lambda(n, 2*n*pi + 7*pi/4), S.Integers))))
def test_issue_16618():
# AttributeError is removed !
eqn = [sin(x)*sin(y), cos(x)*cos(y) - 1]
ans = FiniteSet((x, 2*n*pi), (2*n*pi, y), (x, 2*n*pi + pi), (2*n*pi + pi, y))
sol = nonlinsolve(eqn, [x, y])
for i0, j0 in zip(ordered(sol), ordered(ans)):
assert len(i0) == len(j0) == 2
assert all(a.dummy_eq(b) for a, b in zip(i0, j0))
assert len(sol) == len(ans)
def test_issue_17566():
assert nonlinsolve([32*(2**x)/2**(-y) - 4**y, 27*(3**x) - S(1)/3**y], x, y) ==\
FiniteSet((-log(81)/log(3), 1))
def test_issue_16643():
n = Dummy('n')
assert solveset(x**2*sin(x), x).dummy_eq(Union(ImageSet(Lambda(n, 2*n*pi + pi), S.Integers),
ImageSet(Lambda(n, 2*n*pi), S.Integers)))
def test_issue_19587():
n,m = symbols('n m')
assert nonlinsolve([32*2**m*2**n - 4**n, 27*3**m - 3**(-n)], m, n) ==\
FiniteSet((-log(81)/log(3), 1))
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 dumeq(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]
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 dumeq(nonlinsolve(eqs, [x, z]), soln)
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 = symbols('a, b', real=True)
assert nonlinsolve([a**2 + a, a - b], [a, b]) == {(-1, -1), (0, 0)}
@SKIP("slow")
def test_issue_5114_solveset():
# slow testcase
from sympy.abc import o, p
# 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
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)
syms = Tuple(x, y)
soln = ConditionSet(
syms,
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],
{x + 1}, [y, x]) == S.EmptySet
def test_substitution_incorrect():
# the solutions in the following two tests are incorrect. The
# correct result is EmptySet in both cases.
assert substitution([h - 1, k - 1, f - 2, f - 4, -2 * k],
[h, k, f]) == {(1, 1, f)}
assert substitution([x + y + z, S.One, S.One, S.One], [x, y, z]) == \
{(-y - z, y, z)}
# the correct result in the test below is {(-I, I, I, -I),
# (I, -I, -I, I)}
assert substitution([a - d, b + d, c + d, d**2 + 1], [a, b, c, d]) == \
{(d, -d, -d, d)}
# the result in the test below is incomplete. The complete result
# is {(0, b), (log(2), 2)}
assert substitution([a*(a - log(b)), a*(b - 2)], [a, b]) == \
{(0, b)}
# The system in the test below is zero-dimensional, so the result
# should have no free symbols
assert substitution([-k*y + 6*x - 4*y, -81*k + 49*y**2 - 270,
-3*k*z + k + z**3, k**2 - 2*k + 4],
[x, y, z, k]).free_symbols == {z}
def test_substitution_redundant():
# the third and fourth solutions are redundant in the test below
assert substitution([x**2 - y**2, z - 1], [x, z]) == \
{(-y, 1), (y, 1), (-sqrt(y**2), 1), (sqrt(y**2), 1)}
# the system below has three solutions. Two of the solutions
# returned by substitution are redundant.
res = substitution([x - y, y**3 - 3*y**2 + 1], [x, y])
assert len(res) == 5
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 dumeq(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))
def test_issue_21022():
from sympy.core.sympify import sympify
eqs = [
'k-16',
'p-8',
'y*y+z*z-x*x',
'd - x + p',
'd*d+k*k-y*y',
'z*z-p*p-k*k',
'abc-efg',
]
efg = Symbol('efg')
eqs = [sympify(x) for x in eqs]
syb = list(ordered(set.union(*[x.free_symbols for x in eqs])))
res = nonlinsolve(eqs, syb)
ans = FiniteSet(
(efg, 32, efg, 16, 8, 40, -16*sqrt(5), -8*sqrt(5)),
(efg, 32, efg, 16, 8, 40, -16*sqrt(5), 8*sqrt(5)),
(efg, 32, efg, 16, 8, 40, 16*sqrt(5), -8*sqrt(5)),
(efg, 32, efg, 16, 8, 40, 16*sqrt(5), 8*sqrt(5)),
)
assert len(res) == len(ans) == 4
assert res == ans
for result in res.args:
assert len(result) == 8
def test_issue_17940():
n = Dummy('n')
k1 = Dummy('k1')
sol = ImageSet(Lambda(((k1, n),), I*(2*k1*pi + arg(2*n*I*pi + log(5)))
+ log(Abs(2*n*I*pi + log(5)))),
ProductSet(S.Integers, S.Integers))
assert solveset(exp(exp(x)) - 5, x).dummy_eq(sol)
def test_issue_17906():
assert solveset(7**(x**2 - 80) - 49**x, x) == FiniteSet(-8, 10)
def test_issue_17933():
eq1 = x*sin(45) - y*cos(q)
eq2 = x*cos(45) - y*sin(q)
eq3 = 9*x*sin(45)/10 + y*cos(q)
eq4 = 9*x*cos(45)/10 + y*sin(z) - z
assert nonlinsolve([eq1, eq2, eq3, eq4], x, y, z, q) ==\
FiniteSet((0, 0, 0, q))
def test_issue_14565():
# removed redundancy
assert dumeq(nonlinsolve([k + m, k + m*exp(-2*pi*k)], [k, m]) ,
FiniteSet((-n*I, ImageSet(Lambda(n, n*I), S.Integers))))
# end of tests for nonlinsolve
def test_issue_9556():
b = Symbol('b', positive=True)
assert solveset(Abs(x) + 1, x, S.Reals) is S.EmptySet
assert solveset(Abs(x) + b, x, S.Reals) is S.EmptySet
assert solveset(Eq(b, -1), b, S.Reals) is S.EmptySet
def test_issue_9611():
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():
assert solveset(x**2 + a, x, S.Reals) == Intersection(S.Reals,
FiniteSet(-sqrt(-a), sqrt(-a)))
def test_issue_9778():
x = Symbol('x', real=True)
y = Symbol('y', real=True)
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_integer_domain_relational():
eq1 = 2*x + 3 > 0
eq2 = x**2 + 3*x - 2 >= 0
eq3 = x + 1/x > -2 + 1/x
eq4 = x + sqrt(x**2 - 5) > 0
eq = x + 1/x > -2 + 1/x
eq5 = eq.subs(x,log(x))
eq6 = log(x)/x <= 0
eq7 = log(x)/x < 0
eq8 = x/(x-3) < 3
eq9 = x/(x**2-3) < 3
assert solveset(eq1, x, S.Integers) == Range(-1, oo, 1)
assert solveset(eq2, x, S.Integers) == Union(Range(-oo, -3, 1), Range(1, oo, 1))
assert solveset(eq3, x, S.Integers) == Union(Range(-1, 0, 1), Range(1, oo, 1))
assert solveset(eq4, x, S.Integers) == Range(3, oo, 1)
assert solveset(eq5, x, S.Integers) == Range(2, oo, 1)
assert solveset(eq6, x, S.Integers) == Range(1, 2, 1)
assert solveset(eq7, x, S.Integers) == S.EmptySet
assert solveset(eq8, x, domain=Range(0,5)) == Range(0, 3, 1)
assert solveset(eq9, x, domain=Range(0,5)) == Union(Range(0, 2, 1), Range(2, 5, 1))
# test_issue_19794
assert solveset(x + 2 < 0, x, S.Integers) == Range(-oo, -2, 1)
def test_issue_10555():
f = Function('f')
g = Function('g')
assert solveset(f(x) - pi/2, x, S.Reals).dummy_eq(
ConditionSet(x, Eq(f(x) - pi/2, 0), S.Reals))
assert solveset(f(g(x)) - pi/2, g(x), S.Reals).dummy_eq(
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():
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
x = Symbol('x', real=True)
y = Symbol('y', real=True)
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_issue_19506():
eq = arg(x + I)
C = Dummy('C')
assert solveset(eq).dummy_eq(Intersection(ConditionSet(C, Eq(im(C) + 1, 0), S.Complexes),
ConditionSet(C, re(C) > 0, S.Complexes)))
def test_solveset_arg():
assert solveset(arg(x), x, S.Reals) == Interval.open(0, oo)
assert solveset(arg(4*x -3), x, S.Reals) == 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():
assert nonlinsolve((t*(sqrt(5) + sqrt(2)) - sqrt(2), t), t) is S.EmptySet
def test_issue_14223():
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)
assert solveset(x, x, FiniteSet(1, 2)) is S.EmptySet
def test_issue_10158():
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():
f = 1 - exp(-18000000*x) - y
a1 = FiniteSet(-log(-y + 1)/18000000)
assert solveset(f, x, S.Reals) == \
Intersection(S.Reals, a1)
assert dumeq(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():
number = CRootOf(x**4 + x - 1, 2)
raises(ValueError, lambda: invert_real(number, 0, x))
assert invert_real(x**2, number, x) # 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)) == {
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)
def test_issue_21276():
eq = (2*x*(y - z) - y*erf(y - z) - y + z*erf(y - z) + z)**2
assert solveset(eq.expand(), y) == FiniteSet(z, z + erfinv(2*x - 1))
# exponential tests
def test_exponential_real():
from sympy.abc import y
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
e10 = 29*2**(x + 1)*615**(x) - 123*2726**(x)
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(e10,x, S.Reals) == FiniteSet((-log(29) - log(2) + log(123))/(-log(2726) + log(2) + log(615)))
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).dummy_eq(
ConditionSet(x, Eq((1 + 1/x)**(x + 1), 0), S.Reals))
@XFAIL
def test_exponential_complex():
n = Dummy('n')
assert dumeq(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 dumeq(solveset_complex(4**(x/2) - 2**(x/3), x), imageset(
Lambda(n, 3*n*I*pi/log(2)), S.Integers))
assert dumeq(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 dumeq(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 dumeq(res, ans)
def test_expo_conditionset():
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).dummy_eq(ConditionSet(
x, Eq((exp(x) + 1)**x - 2, 0), S.Reals))
assert solveset(f2, x, S.Reals).dummy_eq(ConditionSet(
x, Eq(x*(x + 2)**y - 3, 0), S.Reals))
assert solveset(f3, x, S.Reals).dummy_eq(ConditionSet(
x, Eq(2**x - exp(x) - 3, 0), S.Reals))
assert solveset(f4, x, S.Reals).dummy_eq(ConditionSet(
x, Eq(-exp(x) + log(x), 0), S.Reals))
assert solveset(f5, x, S.Reals).dummy_eq(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)
xr, zr = symbols('xr, zr', real=True)
assert solveset(z**x - y, x, S.Reals) == Intersection(
S.Reals, FiniteSet(log(y)/log(z)))
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, solveset(f1, w, S.Reals)
assert solveset(f2, w, S.Reals) == sol2, solveset(f2, w, S.Reals)
assert solveset(x**x, x, Interval.Lopen(0,oo)).dummy_eq(
ConditionSet(w, Eq(w**w, 0), Interval.open(0, oo)))
assert solveset(x**y - 1, y, S.Reals) == FiniteSet(0)
assert solveset(exp(x/y)*exp(-z/y) - 2, y, S.Reals) == \
Complement(ConditionSet(y, Eq(im(x)/y, 0) & Eq(im(z)/y, 0), \
Complement(Intersection(FiniteSet((x - z)/log(2)), S.Reals), FiniteSet(0))), FiniteSet(0))
assert solveset(exp(xr/y)*exp(-zr/y) - 2, y, S.Reals) == \
Complement(FiniteSet((xr - zr)/log(2)), FiniteSet(0))
assert solveset(a**x - b**x, x).dummy_eq(ConditionSet(
w, Ne(a, 0) & Ne(b, 0), FiniteSet(0)))
def test_ignore_assumptions():
# make sure assumptions are ignored
xpos = symbols('x', positive=True)
x = symbols('x')
assert solveset_complex(xpos**2 - 4, xpos
) == solveset_complex(x**2 - 4, x)
@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():
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) is S.EmptySet
eq = log(8*x) - log(sqrt(x) + 1) - 2
assert solveset_real(eq, x) is S.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
# lambert tests
def test_is_lambert():
a, b, c = symbols('a,b,c')
assert _is_lambert(x**2, x) is False
assert _is_lambert(a**x**2+b*x+c, x) is True
assert _is_lambert(E**2, x) is False
assert _is_lambert(x*E**2, x) is False
assert _is_lambert(3*log(x) - x*log(3), x) is True
assert _is_lambert(log(log(x - 3)) + log(x-3), x) is True
assert _is_lambert(5*x - 1 + 3*exp(2 - 7*x), x) is True
assert _is_lambert((a/x + exp(x/2)).diff(x, 2), x) is True
assert _is_lambert((x**2 - 2*x + 1).subs(x, (log(x) + 3*x)**2 - 1), x) is True
assert _is_lambert(x*sinh(x) - 1, x) is True
assert _is_lambert(x*cos(x) - 5, x) is True
assert _is_lambert(tanh(x) - 5*x, x) is True
assert _is_lambert(cosh(x) - sinh(x), x) is False
# end of lambert 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))
raises(ValueError, lambda:
linear_coeffs(x, 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():
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():
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 dumeq(invert_modular(Mod(x, 7), S(5), n, x),
(x, ImageSet(Lambda(n, 7*n + 5), S.Integers)))
# a.is_Add
assert dumeq(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 dumeq(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, S.EmptySet)
assert dumeq(invert_modular(Mod(3**x, 4), S(3), n, x),
(x, ImageSet(Lambda(n, 2*n + 1), S.Naturals0)))
assert dumeq(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, S.EmptySet)
def test_solve_modular():
n = Dummy('n', integer=True)
# if rhs has symbol (need to be implemented in future).
assert solveset(Mod(x, 4) - x, x, S.Integers
).dummy_eq(
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
).dummy_eq(
ConditionSet(x, Eq(Mod(sin(x), 7) - 3, 0), S.Integers))
assert solveset(3 - Mod(log(x), 7), x, S.Integers
).dummy_eq(
ConditionSet(x, Eq(Mod(log(x), 7) - 3, 0), S.Integers))
assert solveset(3 - Mod(exp(x), 7), x, S.Integers
).dummy_eq(ConditionSet(x, Eq(Mod(exp(x), 7) - 3, 0),
S.Integers))
# EmptySet solution definitely
assert solveset(7 - Mod(x, 5), x, S.Integers) is S.EmptySet
assert solveset(5 - Mod(x, 5), x, S.Integers) is S.EmptySet
# Negative m
assert dumeq(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) is S.EmptySet
# linear expression in Mod
assert dumeq(solveset(3 - Mod(x, 5), x, S.Integers),
ImageSet(Lambda(n, 5*n + 3), S.Integers))
assert dumeq(solveset(3 - Mod(5*x - 8, 7), x, S.Integers),
ImageSet(Lambda(n, 7*n + 5), S.Integers))
assert dumeq(solveset(3 - Mod(5*x, 7), x, S.Integers),
ImageSet(Lambda(n, 7*n + 2), S.Integers))
# higher degree expression in Mod
assert dumeq(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) is S.EmptySet
assert dumeq(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 dumeq(solveset(Mod(7**x, 41) - 15, x, S.Integers),
ImageSet(Lambda(n, 40*n + 3), S.Naturals0))
assert dumeq(solveset(Mod(12**x, 21) - 18, x, S.Integers),
ImageSet(Lambda(n, 6*n + 2), S.Naturals0))
assert dumeq(solveset(Mod(3**x, 4) - 3, x, S.Integers),
ImageSet(Lambda(n, 2*n + 1), S.Naturals0))
assert dumeq(solveset(Mod(2**x, 7) - 2 , x, S.Integers),
ImageSet(Lambda(n, 3*n + 1), S.Naturals0))
assert dumeq(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) is S.EmptySet
assert dumeq(solveset(Mod(x**3, 8) - 1, x, S.Integers),
ImageSet(Lambda(n, 8*n + 1), S.Integers))
assert dumeq(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 dumeq(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) == \
S.EmptySet
assert solveset(Mod(I*x, 3) - 2, x, S.Integers
).dummy_eq(
ConditionSet(x, Eq(Mod(I*x, 3) - 2, 0), S.Integers))
assert solveset(Mod(I + x, 3) - 2, x, S.Integers
).dummy_eq(
ConditionSet(x, Eq(Mod(x + I, 3) - 2, 0), S.Integers))
# issue 17373 (https://github.com/sympy/sympy/issues/17373)
assert dumeq(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 dumeq(solveset(Mod(x**31, 74) - 43, x, S.Integers),
ImageSet(Lambda(n, 74*n + 31), S.Integers))
# issue 13178
n = symbols('n', integer=True)
a = 742938285
b = 1898888478
m = 2**31 - 1
c = 20170816
assert dumeq(solveset(c - Mod(a**n*b, m), n, S.Integers),
ImageSet(Lambda(n, 2147483646*n + 100), S.Naturals0))
assert dumeq(solveset(c - Mod(a**n*b, m), n, S.Naturals0),
Intersection(ImageSet(Lambda(n, 2147483646*n + 100), S.Naturals0),
S.Naturals0))
assert dumeq(solveset(c - Mod(a**(2*n)*b, m), n, S.Integers),
Intersection(ImageSet(Lambda(n, 1073741823*n + 50), S.Naturals0),
S.Integers))
assert solveset(c - Mod(a**(2*n + 7)*b, m), n, S.Integers) is S.EmptySet
assert dumeq(solveset(c - Mod(a**(n - 4)*b, m), n, S.Integers),
Intersection(ImageSet(Lambda(n, 2147483646*n + 104), S.Naturals0),
S.Integers))
# end of modular tests
def test_issue_17276():
assert nonlinsolve([Eq(x, 5**(S(1)/5)), Eq(x*y, 25*sqrt(5))], x, y) == \
FiniteSet((5**(S(1)/5), 25*5**(S(3)/10)))
def test_issue_10426():
x = Dummy('x')
a = Symbol('a')
n = Dummy('n')
assert (solveset(sin(x + a) - sin(x), a)).dummy_eq(Dummy('x')) == (Union(
ImageSet(Lambda(n, 2*n*pi), S.Integers),
Intersection(S.Complexes, ImageSet(Lambda(n, -I*(I*(2*n*pi + arg(-exp(-2*I*x))) + 2*im(x))),
S.Integers)))).dummy_eq(Dummy('x,n'))
def test_solveset_conjugate():
"""Test solveset for simple conjugate functions"""
assert solveset(conjugate(x) -3 + I) == FiniteSet(3 + I)
def test_issue_18208():
variables = symbols('x0:16') + symbols('y0:12')
x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15,\
y0, y1, y2, y3, y4, y5, y6, y7, y8, y9, y10, y11 = variables
eqs = [x0 + x1 + x2 + x3 - 51,
x0 + x1 + x4 + x5 - 46,
x2 + x3 + x6 + x7 - 39,
x0 + x3 + x4 + x7 - 50,
x1 + x2 + x5 + x6 - 35,
x4 + x5 + x6 + x7 - 34,
x4 + x5 + x8 + x9 - 46,
x10 + x11 + x6 + x7 - 23,
x11 + x4 + x7 + x8 - 25,
x10 + x5 + x6 + x9 - 44,
x10 + x11 + x8 + x9 - 35,
x12 + x13 + x8 + x9 - 35,
x10 + x11 + x14 + x15 - 29,
x11 + x12 + x15 + x8 - 35,
x10 + x13 + x14 + x9 - 29,
x12 + x13 + x14 + x15 - 29,
y0 + y1 + y2 + y3 - 55,
y0 + y1 + y4 + y5 - 53,
y2 + y3 + y6 + y7 - 56,
y0 + y3 + y4 + y7 - 57,
y1 + y2 + y5 + y6 - 52,
y4 + y5 + y6 + y7 - 54,
y4 + y5 + y8 + y9 - 48,
y10 + y11 + y6 + y7 - 60,
y11 + y4 + y7 + y8 - 51,
y10 + y5 + y6 + y9 - 57,
y10 + y11 + y8 + y9 - 54,
x10 - 2,
x11 - 5,
x12 - 1,
x13 - 6,
x14 - 1,
x15 - 21,
y0 - 12,
y1 - 20]
expected = [38 - x3, x3 - 10, 23 - x3, x3, 12 - x7, x7 + 6, 16 - x7, x7,
8, 20, 2, 5, 1, 6, 1, 21, 12, 20, -y11 + y9 + 2, y11 - y9 + 21,
-y11 - y7 + y9 + 24, y11 + y7 - y9 - 3, 33 - y7, y7, 27 - y9, y9,
27 - y11, y11]
A, b = linear_eq_to_matrix(eqs, variables)
# solve
solve_expected = {v:eq for v, eq in zip(variables, expected) if v != eq}
assert solve(eqs, variables) == solve_expected
# linsolve
linsolve_expected = FiniteSet(Tuple(*expected))
assert linsolve(eqs, variables) == linsolve_expected
assert linsolve((A, b), variables) == linsolve_expected
# gauss_jordan_solve
gj_solve, new_vars = A.gauss_jordan_solve(b)
gj_solve = [i for i in gj_solve]
gj_expected = linsolve_expected.subs(zip([x3, x7, y7, y9, y11], new_vars))
assert FiniteSet(Tuple(*gj_solve)) == gj_expected
# nonlinsolve
# The solution set of nonlinsolve is currently equivalent to linsolve and is
# also correct. However, we would prefer to use the same symbols as parameters
# for the solution to the underdetermined system in all cases if possible.
# We want a solution that is not just equivalent but also given in the same form.
# This test may be changed should nonlinsolve be modified in this way.
nonlinsolve_expected = FiniteSet((38 - x3, x3 - 10, 23 - x3, x3, 12 - x7, x7 + 6,
16 - x7, x7, 8, 20, 2, 5, 1, 6, 1, 21, 12, 20,
-y5 + y7 - 1, y5 - y7 + 24, 21 - y5, y5, 33 - y7,
y7, 27 - y9, y9, -y5 + y7 - y9 + 24, y5 - y7 + y9 + 3))
assert nonlinsolve(eqs, variables) == nonlinsolve_expected
def test_substitution_with_infeasible_solution():
a00, a01, a10, a11, l0, l1, l2, l3, m0, m1, m2, m3, m4, m5, m6, m7, c00, c01, c10, c11, p00, p01, p10, p11 = symbols(
'a00, a01, a10, a11, l0, l1, l2, l3, m0, m1, m2, m3, m4, m5, m6, m7, c00, c01, c10, c11, p00, p01, p10, p11'
)
solvefor = [p00, p01, p10, p11, c00, c01, c10, c11, m0, m1, m3, l0, l1, l2, l3]
system = [
-l0 * c00 - l1 * c01 + m0 + c00 + c01,
-l0 * c10 - l1 * c11 + m1,
-l2 * c00 - l3 * c01 + c00 + c01,
-l2 * c10 - l3 * c11 + m3,
-l0 * p00 - l2 * p10 + p00 + p10,
-l1 * p00 - l3 * p10 + p00 + p10,
-l0 * p01 - l2 * p11,
-l1 * p01 - l3 * p11,
-a00 + c00 * p00 + c10 * p01,
-a01 + c01 * p00 + c11 * p01,
-a10 + c00 * p10 + c10 * p11,
-a11 + c01 * p10 + c11 * p11,
-m0 * p00,
-m1 * p01,
-m2 * p10,
-m3 * p11,
-m4 * c00,
-m5 * c01,
-m6 * c10,
-m7 * c11,
m2,
m4,
m5,
m6,
m7
]
sol = FiniteSet(
(0, Complement(FiniteSet(p01), FiniteSet(0)), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, l2, l3),
(p00, Complement(FiniteSet(p01), FiniteSet(0)), 0, p11, 0, 0, 0, 0, 0, 0, 0, 1, 1, -p01/p11, -p01/p11),
(0, Complement(FiniteSet(p01), FiniteSet(0)), 0, p11, 0, 0, 0, 0, 0, 0, 0, 1, -l3*p11/p01, -p01/p11, l3),
(0, Complement(FiniteSet(p01), FiniteSet(0)), 0, p11, 0, 0, 0, 0, 0, 0, 0, -l2*p11/p01, -l3*p11/p01, l2, l3),
)
assert sol != nonlinsolve(system, solvefor)
def test_issue_20097():
assert solveset(1/sqrt(x)) is S.EmptySet
def test_issue_15350():
assert solveset(diff(sqrt(1/x+x))) == FiniteSet(-1, 1)
def test_issue_18359():
c1 = Piecewise((0, x < 0), (Min(1, x)/2 - Min(2, x)/2 + Min(3, x)/2, True))
c2 = Piecewise((Piecewise((0, x < 0), (Min(1, x)/2 - Min(2, x)/2 + Min(3, x)/2, True)), x >= 0), (0, True))
correct_result = Interval(1, 2)
result1 = solveset(c1 - Rational(1, 2), x, Interval(0, 3))
result2 = solveset(c2 - Rational(1, 2), x, Interval(0, 3))
assert result1 == correct_result
assert result2 == correct_result
def test_issue_17604():
lhs = -2**(3*x/11)*exp(x/11) + pi**(x/11)
assert _is_exponential(lhs, x)
assert _solve_exponential(lhs, 0, x, S.Complexes) == FiniteSet(0)
def test_issue_17580():
assert solveset(1/(1 - x**3)**2, x, S.Reals) is S.EmptySet
def test_issue_17566_actual():
sys = [2**x + 2**y - 3, 4**x + 9**y - 5]
# Not clear this is the correct result, but at least no recursion error
assert nonlinsolve(sys, x, y) == FiniteSet((log(3 - 2**y)/log(2), y))
def test_issue_17565():
eq = Ge(2*(x - 2)**2/(3*(x + 1)**(Integer(1)/3)) + 2*(x - 2)*(x + 1)**(Integer(2)/3), 0)
res = Union(Interval.Lopen(-1, -Rational(1, 4)), Interval(2, oo))
assert solveset(eq, x, S.Reals) == res
def test_issue_15024():
function = (x + 5)/sqrt(-x**2 - 10*x)
assert solveset(function, x, S.Reals) == FiniteSet(Integer(-5))
def test_issue_16877():
assert dumeq(nonlinsolve([x - 1, sin(y)], x, y),
FiniteSet((FiniteSet(1), ImageSet(Lambda(n, 2*n*pi), S.Integers)),
(FiniteSet(1), ImageSet(Lambda(n, 2*n*pi + pi), S.Integers))))
# Even better if (FiniteSet(1), ImageSet(Lambda(n, n*pi), S.Integers)) is obtained
def test_issue_16876():
assert dumeq(nonlinsolve([sin(x), 2*x - 4*y], x, y),
FiniteSet((ImageSet(Lambda(n, 2*n*pi), S.Integers),
ImageSet(Lambda(n, n*pi), S.Integers)),
(ImageSet(Lambda(n, 2*n*pi + pi), S.Integers),
ImageSet(Lambda(n, n*pi + pi/2), S.Integers))))
# Even better if (ImageSet(Lambda(n, n*pi), S.Integers),
# ImageSet(Lambda(n, n*pi/2), S.Integers)) is obtained
def test_issue_21236():
x, z = symbols("x z")
y = symbols('y', rational=True)
assert solveset(x**y - z, x, S.Reals) == ConditionSet(x, Eq(x**y - z, 0), S.Reals)
e1, e2 = symbols('e1 e2', even=True)
y = e1/e2 # don't know if num or den will be odd and the other even
assert solveset(x**y - z, x, S.Reals) == ConditionSet(x, Eq(x**y - z, 0), S.Reals)
def test_issue_21908():
assert nonlinsolve([(x**2 + 2*x - y**2)*exp(x), -2*y*exp(x)], x, y
) == {(-2, 0), (0, 0)}
def test_issue_19144():
# test case 1
expr1 = [x + y - 1, y**2 + 1]
eq1 = [Eq(i, 0) for i in expr1]
soln1 = {(1 - I, I), (1 + I, -I)}
soln_expr1 = nonlinsolve(expr1, [x, y])
soln_eq1 = nonlinsolve(eq1, [x, y])
assert soln_eq1 == soln_expr1 == soln1
# test case 2 - with denoms
expr2 = [x/y - 1, y**2 + 1]
eq2 = [Eq(i, 0) for i in expr2]
soln2 = {(-I, -I), (I, I)}
soln_expr2 = nonlinsolve(expr2, [x, y])
soln_eq2 = nonlinsolve(eq2, [x, y])
assert soln_eq2 == soln_expr2 == soln2
# denominators that cancel in expression
assert nonlinsolve([Eq(x + 1/x, 1/x)], [x]) == FiniteSet((S.EmptySet,))
def test_issue_22413():
res = nonlinsolve((4*y*(2*x + 2*exp(y) + 1)*exp(2*x),
4*x*exp(2*x) + 4*y*exp(2*x + y) + 4*exp(2*x + y) + 1),
x, y)
# First solution is not correct, but the issue was an exception
sols = FiniteSet((x, S.Zero), (-exp(y) - S.Half, y))
assert res == sols
def test_issue_23318():
eqs_eq = [
Eq(53.5780461486929, x * log(y / (5.0 - y) + 1) / y),
Eq(x, 0.0015 * z),
Eq(0.0015, 7845.32 * y / z),
]
eqs_expr = [eq.rewrite(Add) for eq in eqs_eq]
sol = {(266.97755814852, 0.0340301680681629, 177985.03876568)}
assert_close_nl(nonlinsolve(eqs_eq, [x, y, z]), sol)
assert_close_nl(nonlinsolve(eqs_expr, [x, y, z]), sol)
logterm = log(1.91196789933362e-7*z/(5.0 - 1.91196789933362e-7*z) + 1)
eq = -0.0015*z*logterm + 1.02439504345316e-5*z
assert_close_ss(solveset(eq, z), {0, 177985.038765679})
def test_issue_19814():
assert nonlinsolve([ 2**m - 2**(2*n), 4*2**m - 2**(4*n)], m, n
) == FiniteSet((log(2**(2*n))/log(2), S.Complexes))
def test_issue_22058():
sol = solveset(-sqrt(t)*x**2 + 2*x + sqrt(t), x, S.Reals)
# doesn't fail (and following numerical check)
assert sol.xreplace({t: 1}) == {1 - sqrt(2), 1 + sqrt(2)}, sol.xreplace({t: 1})
def test_issue_11184():
assert solveset(20*sqrt(y**2 + (sqrt(-(y - 10)*(y + 10)) + 10)**2) - 60, y, S.Reals) is S.EmptySet
def test_issue_21890():
e = S(2)/3
assert nonlinsolve([4*x**3*y**4 - 2*y, 4*x**4*y**3 - 2*x], x, y) == {
(2**e/(2*y), y), ((-2**e/4 - 2**e*sqrt(3)*I/4)/y, y),
((-2**e/4 + 2**e*sqrt(3)*I/4)/y, y)}
assert nonlinsolve([(1 - 4*x**2)*exp(-2*x**2 - 2*y**2),
-4*x*y*exp(-2*x**2)*exp(-2*y**2)], x, y) == {(-S(1)/2, 0), (S(1)/2, 0)}
rx, ry = symbols('x y', real=True)
sol = nonlinsolve([4*rx**3*ry**4 - 2*ry, 4*rx**4*ry**3 - 2*rx], rx, ry)
ans = {(2**(S(2)/3)/(2*ry), ry),
((-2**(S(2)/3)/4 - 2**(S(2)/3)*sqrt(3)*I/4)/ry, ry),
((-2**(S(2)/3)/4 + 2**(S(2)/3)*sqrt(3)*I/4)/ry, ry)}
assert sol == ans
def test_issue_22628():
assert nonlinsolve([h - 1, k - 1, f - 2, f - 4, -2*k], h, k, f) == S.EmptySet
assert nonlinsolve([x**3 - 1, x + y, x**2 - 4], [x, y]) == S.EmptySet
|
f26f2f0dc244e1d3960877a99c884f444fb467f2ecdaea68bae686f31acf8be8 | from sympy.assumptions.ask import (Q, ask)
from sympy.core.add import Add
from sympy.core.containers import Tuple
from sympy.core.function import (Derivative, Function, diff)
from sympy.core.mul import Mul
from sympy.core import (GoldenRatio, TribonacciConstant)
from sympy.core.numbers import (E, Float, I, Rational, oo, pi)
from sympy.core.relational import (Eq, Gt, Lt, Ne)
from sympy.core.singleton import S
from sympy.core.symbol import (Dummy, Symbol, Wild, symbols)
from sympy.core.sympify import sympify
from sympy.functions.combinatorial.factorials import binomial
from sympy.functions.elementary.complexes import (Abs, arg, conjugate, im, re)
from sympy.functions.elementary.exponential import (LambertW, exp, log)
from sympy.functions.elementary.hyperbolic import (atanh, cosh, sinh, tanh)
from sympy.functions.elementary.miscellaneous import (cbrt, root, sqrt)
from sympy.functions.elementary.piecewise import Piecewise
from sympy.functions.elementary.trigonometric import (acos, asin, atan, atan2, cos, sec, sin, tan)
from sympy.functions.special.error_functions import (erf, erfc, erfcinv, erfinv)
from sympy.integrals.integrals import Integral
from sympy.logic.boolalg import (And, Or)
from sympy.matrices.dense import Matrix
from sympy.matrices import SparseMatrix
from sympy.polys.polytools import Poly
from sympy.printing.str import sstr
from sympy.simplify.radsimp import denom
from sympy.solvers.solvers import (nsolve, solve, solve_linear)
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, denoms
from sympy.physics.units import cm
from sympy.polys.rootoftools import CRootOf
from sympy.testing.pytest import slow, XFAIL, SKIP, raises
from sympy.core.random import verify_numerically as tn
from sympy.abc import a, b, c, d, e, k, h, p, x, y, z, t, q, m, R
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)) == {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]) == []
assert solve([sqrt(2)],[x]) == []
# duplicate symbols removed
assert solve((x - 3, y + 2), x, y, x) == {x: 3, y: -2}
# unordered symbols
# only 1
assert solve(y - 3, {y}) == [3]
# more than 1
assert solve(y - 3, {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], {(-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
assert solve([y, exp(x) + x], x, y) == {y: 0, x: -LambertW(1)}
# 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(Eq(x**2, 0.0)) == [0] # issue 19048
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())
assert solve([-y*(x + y - 1)/2, (y - 1)/x/y + 1/y],
set=True, check=False) == ([x, y], {(1 - y, y), (x, 0)})
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)) == {-S.One, S.One}
assert set(solve(Eq(x**2, 1), x)) == {-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 = {x: S.Zero, y: 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)) == {
-2 + 3**S.Half,
S(4),
-2 - 3**S.Half
}
assert set(solve((x**2 - 1)**2 - a, x)) == \
{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)) == {S.Zero, 1/a**2}
assert set(solve(x*(root(x, 3) - 3), x)) == {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_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
assert solve(x**5 - 6*x**3 - 6*x**2 + x - 6) == [
CRootOf(x**5 - 6*x**3 - 6*x**2 + x - 6, 0),
CRootOf(x**5 - 6*x**3 - 6*x**2 + x - 6, 1),
CRootOf(x**5 - 6*x**3 - 6*x**2 + x - 6, 2),
CRootOf(x**5 - 6*x**3 - 6*x**2 + x - 6, 3),
CRootOf(x**5 - 6*x**3 - 6*x**2 + x - 6, 4)]
def test_quintics_3():
y = x**5 + x**3 - 2**Rational(1, 3)
assert solve(y) == solve(-y) == []
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_solve_rational():
"""Test solve for rational functions"""
assert solve( ( x - y**3 )/( (y**2)*sqrt(1 - y**2) ), x) == [y**3]
def test_solve_conjugate():
"""Test solve for simple conjugate functions"""
assert solve(conjugate(x) -3 + I) == [3 + I]
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_issue_21004():
x = symbols('x')
f = x/sqrt(x**2+1)
f_diff = f.diff(x)
assert solve(f_diff, x) == []
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*(-n-1)/n, y: 0, z: t*(-n-1)/n}
assert solve([x + y + z + t, -z - t], x, y, z, t) == {x: -y, z: -t}
@XFAIL
def test_linear_system_xfail():
# https://github.com/sympy/sympy/issues/6420
M = Matrix([[0, 15.0, 10.0, 700.0],
[1, 1, 1, 100.0],
[0, 10.0, 5.0, 200.0],
[-5.0, 0, 0, 0 ]])
assert solve_linear_system(M, x, y, z) == {x: 0, y: -60.0, z: 160.0}
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_system_symbols_doesnt_hang_1():
def _mk_eqs(wy):
# Equations for fitting a wy*2 - 1 degree polynomial between two points,
# at end points derivatives are known up to order: wy - 1
order = 2*wy - 1
x, x0, x1 = symbols('x, x0, x1', real=True)
y0s = symbols('y0_:{}'.format(wy), real=True)
y1s = symbols('y1_:{}'.format(wy), real=True)
c = symbols('c_:{}'.format(order+1), real=True)
expr = sum([coeff*x**o for o, coeff in enumerate(c)])
eqs = []
for i in range(wy):
eqs.append(expr.diff(x, i).subs({x: x0}) - y0s[i])
eqs.append(expr.diff(x, i).subs({x: x1}) - y1s[i])
return eqs, c
#
# The purpose of this test is just to see that these calls don't hang. The
# expressions returned are complicated so are not included here. Testing
# their correctness takes longer than solving the system.
#
for n in range(1, 7+1):
eqs, c = _mk_eqs(n)
solve(eqs, c)
def test_linear_system_symbols_doesnt_hang_2():
M = Matrix([
[66, 24, 39, 50, 88, 40, 37, 96, 16, 65, 31, 11, 37, 72, 16, 19, 55, 37, 28, 76],
[10, 93, 34, 98, 59, 44, 67, 74, 74, 94, 71, 61, 60, 23, 6, 2, 57, 8, 29, 78],
[19, 91, 57, 13, 64, 65, 24, 53, 77, 34, 85, 58, 87, 39, 39, 7, 36, 67, 91, 3],
[74, 70, 15, 53, 68, 43, 86, 83, 81, 72, 25, 46, 67, 17, 59, 25, 78, 39, 63, 6],
[69, 40, 67, 21, 67, 40, 17, 13, 93, 44, 46, 89, 62, 31, 30, 38, 18, 20, 12, 81],
[50, 22, 74, 76, 34, 45, 19, 76, 28, 28, 11, 99, 97, 82, 8, 46, 99, 57, 68, 35],
[58, 18, 45, 88, 10, 64, 9, 34, 90, 82, 17, 41, 43, 81, 45, 83, 22, 88, 24, 39],
[42, 21, 70, 68, 6, 33, 64, 81, 83, 15, 86, 75, 86, 17, 77, 34, 62, 72, 20, 24],
[ 7, 8, 2, 72, 71, 52, 96, 5, 32, 51, 31, 36, 79, 88, 25, 77, 29, 26, 33, 13],
[19, 31, 30, 85, 81, 39, 63, 28, 19, 12, 16, 49, 37, 66, 38, 13, 3, 71, 61, 51],
[29, 82, 80, 49, 26, 85, 1, 37, 2, 74, 54, 82, 26, 47, 54, 9, 35, 0, 99, 40],
[15, 49, 82, 91, 93, 57, 45, 25, 45, 97, 15, 98, 48, 52, 66, 24, 62, 54, 97, 37],
[62, 23, 73, 53, 52, 86, 28, 38, 0, 74, 92, 38, 97, 70, 71, 29, 26, 90, 67, 45],
[ 2, 32, 23, 24, 71, 37, 25, 71, 5, 41, 97, 65, 93, 13, 65, 45, 25, 88, 69, 50],
[40, 56, 1, 29, 79, 98, 79, 62, 37, 28, 45, 47, 3, 1, 32, 74, 98, 35, 84, 32],
[33, 15, 87, 79, 65, 9, 14, 63, 24, 19, 46, 28, 74, 20, 29, 96, 84, 91, 93, 1],
[97, 18, 12, 52, 1, 2, 50, 14, 52, 76, 19, 82, 41, 73, 51, 79, 13, 3, 82, 96],
[40, 28, 52, 10, 10, 71, 56, 78, 82, 5, 29, 48, 1, 26, 16, 18, 50, 76, 86, 52],
[38, 89, 83, 43, 29, 52, 90, 77, 57, 0, 67, 20, 81, 88, 48, 96, 88, 58, 14, 3]])
syms = x0,x1,x2,x3,x4,x5,x6,x7,x8,x9,x10,x11,x12,x13,x14,x15,x16,x17,x18 = symbols('x:19')
sol = {
x0: -S(1967374186044955317099186851240896179)/3166636564687820453598895768302256588,
x1: -S(84268280268757263347292368432053826)/791659141171955113399723942075564147,
x2: -S(229962957341664730974463872411844965)/1583318282343910226799447884151128294,
x3: S(990156781744251750886760432229180537)/6333273129375640907197791536604513176,
x4: -S(2169830351210066092046760299593096265)/18999819388126922721593374609813539528,
x5: S(4680868883477577389628494526618745355)/9499909694063461360796687304906769764,
x6: -S(1590820774344371990683178396480879213)/3166636564687820453598895768302256588,
x7: -S(54104723404825537735226491634383072)/339282489073695048599881689460956063,
x8: S(3182076494196560075964847771774733847)/6333273129375640907197791536604513176,
x9: -S(10870817431029210431989147852497539675)/18999819388126922721593374609813539528,
x10: -S(13118019242576506476316318268573312603)/18999819388126922721593374609813539528,
x11: -S(5173852969886775824855781403820641259)/4749954847031730680398343652453384882,
x12: S(4261112042731942783763341580651820563)/4749954847031730680398343652453384882,
x13: -S(821833082694661608993818117038209051)/6333273129375640907197791536604513176,
x14: S(906881575107250690508618713632090559)/904753304196520129599684505229216168,
x15: -S(732162528717458388995329317371283987)/6333273129375640907197791536604513176,
x16: S(4524215476705983545537087360959896817)/9499909694063461360796687304906769764,
x17: -S(3898571347562055611881270844646055217)/6333273129375640907197791536604513176,
x18: S(7513502486176995632751685137907442269)/18999819388126922721593374609813539528
}
eqs = list(M * Matrix(syms + (1,)))
assert solve(eqs, syms) == sol
y = Symbol('y')
eqs = list(y * M * Matrix(syms + (1,)))
assert solve(eqs, syms) == sol
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)) == {-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/4]
assert set(solve(exp(x) + exp(-x) - y, x)) in [{
log(y/2 - sqrt(y**2 - 4)/2),
log(y/2 + sqrt(y**2 - 4)/2),
}, {
log(y - sqrt(y**2 - 4)) - log(2),
log(y + sqrt(y**2 - 4)) - log(2)},
{
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)) == {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)
x0 = -log(2401)
x1 = 3**Rational(1, 5)
x2 = log(7**(7*x1/20))
x3 = sqrt(2)
x4 = sqrt(5)
x5 = x3*sqrt(x4 - 5)
x6 = x4 + 1
x7 = 1/(3*log(7))
x8 = -x4
x9 = x3*sqrt(x8 - 5)
x10 = x8 + 1
ans = [x7*(x0 - 5*LambertW(x2*(-x5 + x6))),
x7*(x0 - 5*LambertW(x2*(x5 + x6))),
x7*(x0 - 5*LambertW(x2*(x10 - x9))),
x7*(x0 - 5*LambertW(x2*(x10 + x9))),
x7*(x0 - 5*LambertW(-log(7**(7*x1/5))))]
assert result == ans, result
# 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) == [1 + log(5)/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 = {3*x - 1, 2*y - 4}
assert solve(eqns, {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) }
# issue 13263
x = Symbol('x')
f = Function('f')
soln = solve([f(x).diff(x) + f(x).diff(x, 2) - 1, f(x).diff(x) - f(x).diff(x, 2)],
f(x).diff(x), f(x).diff(x, 2))
assert soln == { f(x).diff(x, 2): 1/2, f(x).diff(x): 1/2 }
soln = solve([f(x).diff(x, 2) + f(x).diff(x, 3) - 1, 1 - f(x).diff(x, 2) -
f(x).diff(x, 3), 1 - f(x).diff(x,3)], f(x).diff(x, 2), f(x).diff(x, 3))
assert soln == { f(x).diff(x, 2): 0, f(x).diff(x, 3): 1 }
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(0, x)) == [0]
assert solve(Eq(True, x)) == True
assert solve(Eq(1, x)) == [1]
assert solve(Eq(False, ~x)) == True
assert solve(Eq(True, ~x)) == False
assert solve(Ne(True, x)) == False
assert solve(Ne(1, x)) == (x > -oo) & (x < oo) & Ne(x, 1)
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))) == {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 \
[
{log((-sqrt(3) + 2)**2), log((sqrt(3) + 2)**2)},
{2*log(-sqrt(3) + 2), 2*log(sqrt(3) + 2)},
{log(-4*sqrt(3) + 7), log(4*sqrt(3) + 7)},
]
assert set(solve(Poly(exp(x) + exp(-x) - 4))) == \
{log(-sqrt(3) + 2), log(sqrt(3) + 2)}
assert set(solve(x**y + x**(2*y) - 1, x)) == \
{(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)) == {sqrt(y), S.Zero, -sqrt(y)}
assert set(solve(x*(x - y/x), x, check=True)) == {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 solve((a**2 + 1)*(sin(a*x) + cos(a*x)), x) == [-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)) == \
{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])) == \
{(
-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])) == \
{(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) == \
([y, z], {
(-log(3), sqrt(-exp(2*x) - sin(log(3)))),
(-log(3), -sqrt(-exp(2*x) - sin(log(3))))})
assert solve(eqs, x, z, set=True) == (
[x, z],
{(x, sqrt(-exp(2*x) + sin(y))), (x, -sqrt(-exp(2*x) + sin(y)))})
assert set(solve(eqs, x, y)) == \
{
(log(-sqrt(-z**2 - sin(log(3)))), -log(3)),
(log(-z**2 - sin(log(3)))/2, -log(3))}
assert set(solve(eqs, y, z)) == \
{
(-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) == ([y, z], {
(-log(3), -exp(2*x) - sin(log(3)))})
assert solve(eqs, x, z, set=True) == (
[x, z], {(x, -exp(2*x) + sin(y))})
assert set(solve(eqs, x, y)) == {
(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], {(S.One, S(3)), (S(3), S.One)})
assert set(solve((sqrt(x**2 + y**2) - sqrt(10), x + y - 4), x, y)) == \
{(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])) == \
{(-sqrt(-y - 4),), (sqrt(-y - 4),)}
def test_polysys():
assert set(solve([x**2 + 2/y - 2, x + y - 3], [x, y])) == \
{(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 unrad(1) is None
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)) == {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)))) == \
{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))) == {-S.One, S(2)}
assert set(solve(Eq(sqrt(2*x - 1) - sqrt(x - 4), 2))) == {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))) == \
{Rational(-1, 2), Rational(-1, 3)}
assert set(solve(sqrt(2*x**2 - 7) - (3 - x))) == {-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]))
# why does this pass
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), [])
# and this fail?
#assert unrad(sqrt(cosh(x)/x) + root(x + 1, 3)*sqrt(x) - 1) == (
# -s**6 + 6*s**5 - 15*s**4 + 20*s**3 - 15*s**2 + 6*s + x**5 +
# 2*x**4 + x**3 - 1, [s, s**2 - cosh(x)/x])
# watch for symbols in exponents
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]))
# should _Q be so lenient?
assert unrad(x**(S.Half/y) + y, x) == (x**(1/y) - y**2, [])
# 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) == [
2**(S(2)/3)*(27*x + 27*sqrt(x**2))**(S(1)/3)*S(4)/21 + (512*x/343 +
S(512)/343)**(S(1)/3)*(-S(1)/2 - sqrt(3)*I/2), 2**(S(2)/3)*(27*x +
27*sqrt(x**2))**(S(1)/3)*S(4)/21 + (512*x/343 +
S(512)/343)**(S(1)/3)*(-S(1)/2 + sqrt(3)*I/2), 2**(S(2)/3)*(27*x +
27*sqrt(x**2))**(S(1)/3)*S(4)/21 + (512*x/343 + S(512)/343)**(S(1)/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)),
(s*(4096*s**9 + 960*s**8 + 48*s**7 - s**6 - 1728),
[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]))
# make sure buried radicals are exposed
s = sqrt(x) - 1
assert unrad(s**2 - s**3) == (x**3 - 6*x**2 + 9*x - 4, [])
# make sure numerators which are already polynomial are rejected
assert unrad((x/(x + 1) + 3)**(-2), x) is None
# https://github.com/sympy/sympy/issues/23707
eq = sqrt(x - y)*exp(t*sqrt(x - y)) - exp(t*sqrt(x - y))
assert solve(eq, y) == [x - 1]
assert unrad(eq) is None
@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
assert checksol(0, {}) is True
assert checksol([1e-10, x - 2], x, 2) is False
assert checksol([0.5, 0, x], x, 0) is False
assert checksol(y, x, 2) is False
assert checksol(x+1e-10, x, 0, numerical=True) is True
assert checksol(x+1e-10, x, 0, numerical=False) is False
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():
#
# XXX: This system does not have a solution for most values of the
# parameters. Generally solve returns the empty set for systems that are
# generically inconsistent.
#
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 = [{
I1: I2 + I3,
dI1: -4*I2 - 8*I3 - 4*I5 - 6*I6 + 24,
I4: I3 - I5,
dQ4: I3 - I5,
Q4: -I3/2 + 3*I5/2 - dI4/2,
dQ2: I2,
Q2: 2*I3 + 2*I5 + 3*I6}]
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, check=False) == ans[0]
assert solve(e, *v, manual=True) == []
assert solve(e, *v) == []
# 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_issue_5849 but solved with the matrix solver.
A solution only exists if I3 == I6 which is not generically true,
but `solve` does not return conditions under which the solution is
valid, only a solution that is canonical and consistent with the input.
'''
# a simple example with the same issue
# assert solve([x+y+z, x+y], [x, y]) == {x: y}
# the longer example
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) == []
def test_issue_21882():
a, b, c, d, f, g, k = unknowns = symbols('a, b, c, d, f, g, k')
equations = [
-k*a + b + 5*f/6 + 2*c/9 + 5*d/6 + 4*a/3,
-k*f + 4*f/3 + d/2,
-k*d + f/6 + d,
13*b/18 + 13*c/18 + 13*a/18,
-k*c + b/2 + 20*c/9 + a,
-k*b + b + c/18 + a/6,
5*b/3 + c/3 + a,
2*b/3 + 2*c + 4*a/3,
-g,
]
answer = [
{a: 0, f: 0, b: 0, d: 0, c: 0, g: 0},
{a: 0, f: -d, b: 0, k: S(5)/6, c: 0, g: 0},
{a: -2*c, f: 0, b: c, d: 0, k: S(13)/18, g: 0},
]
assert solve(equations, unknowns, dict=True) == answer
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)], {
(-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)) == \
{(-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)], {
(-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))) == \
{-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)) == \
{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]
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():
pqt = dict(quick=True, particular=True)
pqf = dict(quick=False, particular=True)
assert solve([x + y - 5, 2*x - y - 1], **pqt) == {x: 2, y: 3}
assert solve([x + y - 5, 2*x - y - 1], **pqf) == {x: 2, y: 3}
def count(dic):
return len([x for x in dic.values() if x == 0])
assert count(solve([x + y + z, y + z + a + t], **pqt)) == 3
assert count(solve([x + y + z, y + z + a + t], **pqf)) == 3
assert count(solve([x + y + z, y + z + a], **pqt)) == 1
assert count(solve([x + y + z, y + z + a], **pqf)) == 2
# issue 22718
A = Matrix([
[ 1, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 1, 0],
[ 1, 1, 0, 1, 1, 0, 1, 0, 1, 0, -1, -1, 0, 0],
[-1, -1, 0, 0, -1, 0, 0, 0, 0, 0, 1, 1, 0, 1],
[ 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, -1, 0, -1, 0],
[-1, 0, -1, 0, 0, -1, 0, 0, 0, 0, 1, 0, 1, 1],
[-1, 0, 0, -1, 0, 0, -1, 0, 0, 0, -1, 0, 0, -1],
[ 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, -1, -1, 0],
[ 0, -1, -1, 0, 0, 0, 0, -1, 0, 0, 0, 1, 1, 1],
[ 0, -1, 0, -1, 0, 0, 0, 0, -1, 0, 0, -1, 0, -1],
[ 0, 0, -1, -1, 0, 0, 0, 0, 0, -1, 0, 0, -1, -1],
[ 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0],
[ 0, 0, 0, 0, -1, -1, 0, -1, 0, 0, 0, 0, 0, 0]])
v = Matrix(symbols("v:14", integer=True))
B = Matrix([[2], [-2], [0], [0], [0], [0], [0], [0], [0],
[0], [0], [0]])
eqs = A@v-B
assert solve(eqs) == []
assert solve(eqs, particular=True) == [] # assumption violated
assert all(v for v in solve([x + y + z, y + z + a]).values())
for _q in (True, False):
assert not all(v for v in solve(
[x + y + z, y + z + a], quick=_q,
particular=True).values())
# raise error if quick used w/o particular=True
raises(ValueError, lambda: solve([x + 1], quick=_q))
raises(ValueError, lambda: solve([x + 1], quick=_q, particular=False))
# and give a good error message if someone tries to use
# particular with a single equation
raises(ValueError, lambda: solve(x + 1, particular=True))
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,)]
assert set(solve(abs(x - 7) - 8)) == {-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) == {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) == {
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)) == {
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)))]
# issue 23253
assert solve((1/log(sqrt(x) + 2)**2 - 1/x)) == [
(LambertW(-exp(-2), -1) + 2)**2]
assert solve((1/log(1/sqrt(x) + 2)**2 - x)) == [
(LambertW(-exp(-2), -1) + 2)**-2]
assert solve((1/log(x**2 + 2)**2 - x**-4)) == [
-I*sqrt(2 - LambertW(exp(2))),
-I*sqrt(LambertW(-exp(-2)) + 2),
sqrt(-2 - LambertW(-exp(-2))),
sqrt(-2 + LambertW(exp(2))),
-sqrt(-2 - LambertW(-exp(-2), -1)),
sqrt(-2 - LambertW(-exp(-2), -1))]
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) == [atan(S.Half)]
@XFAIL
def test_rewrite_trigh():
# if this import passes then the test below should also pass
from sympy.functions.elementary.hyperbolic 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 == {(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()]) <= 3270
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]) == {x**y}
assert _simple_dens(1/root(x, 3), [x]) == {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 = [{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) == {2, y}
assert denoms(x/2 + 1/y, y) == {y}
assert denoms(x/2 + 1/y, [y]) == {y}
assert denoms(1/x + 1/y + 1/z, [x, y]) == {x, y}
assert denoms(1/x + 1/y + 1/z, x, y) == {x, y}
assert denoms(1/x + 1/y + 1/z, {x, y}) == {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) is None
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_10993():
assert solve(Eq(binomial(x, 2), 3)) == [-2, 3]
assert solve(Eq(pow(x, 2) + binomial(x, 3), x)) == [-4, 0, 1]
assert solve(Eq(binomial(x, 2), 0)) == [0, 1]
assert solve(a+binomial(x, 3), a) == [-binomial(x, 3)]
assert solve(x-binomial(a, 3) + binomial(y, 2) + sin(a), x) == [-sin(a) + binomial(a, 3) - binomial(y, 2)]
assert solve((x+1)-binomial(x+1, 3), x) == [-2, -1, 3]
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}
def test_issue_19113_19102():
t = S(1)/3
solve(cos(x)**5-sin(x)**5)
assert solve(4*cos(x)**3 - 2*sin(x)**3) == [
atan(2**(t)), -atan(2**(t)*(1 - sqrt(3)*I)/2),
-atan(2**(t)*(1 + sqrt(3)*I)/2)]
h = S.Half
assert solve(cos(x)**2 + sin(x)) == [
2*atan(-h + sqrt(5)/2 + sqrt(2)*sqrt(1 - sqrt(5))/2),
-2*atan(h + sqrt(5)/2 + sqrt(2)*sqrt(1 + sqrt(5))/2),
-2*atan(-sqrt(5)/2 + h + sqrt(2)*sqrt(1 - sqrt(5))/2),
-2*atan(-sqrt(2)*sqrt(1 + sqrt(5))/2 + h + sqrt(5)/2)]
assert solve(3*cos(x) - sin(x)) == [atan(3)]
def test_issue_19509():
a = S(3)/4
b = S(5)/8
c = sqrt(5)/8
d = sqrt(5)/4
assert solve(1/(x -1)**5 - 1) == [2,
-d + a - sqrt(-b + c),
-d + a + sqrt(-b + c),
d + a - sqrt(-b - c),
d + a + sqrt(-b - c)]
def test_issue_20747():
THT, HT, DBH, dib, c0, c1, c2, c3, c4 = symbols('THT HT DBH dib c0 c1 c2 c3 c4')
f = DBH*c3 + THT*c4 + c2
rhs = 1 - ((HT - 1)/(THT - 1))**c1*(1 - exp(c0/f))
eq = dib - DBH*(c0 - f*log(rhs))
term = ((1 - exp((DBH*c0 - dib)/(DBH*(DBH*c3 + THT*c4 + c2))))
/ (1 - exp(c0/(DBH*c3 + THT*c4 + c2))))
sol = [THT*term**(1/c1) - term**(1/c1) + 1]
assert solve(eq, HT) == sol
def test_issue_20902():
f = (t / ((1 + t) ** 2))
assert solve(f.subs({t: 3 * x + 2}).diff(x) > 0, x) == (S(-1) < x) & (x < S(-1)/3)
assert solve(f.subs({t: 3 * x + 3}).diff(x) > 0, x) == (S(-4)/3 < x) & (x < S(-2)/3)
assert solve(f.subs({t: 3 * x + 4}).diff(x) > 0, x) == (S(-5)/3 < x) & (x < S(-1))
assert solve(f.subs({t: 3 * x + 2}).diff(x) > 0, x) == (S(-1) < x) & (x < S(-1)/3)
def test_issue_21034():
a = symbols('a', real=True)
system = [x - cosh(cos(4)), y - sinh(cos(a)), z - tanh(x)]
assert solve(system, x, y, z) == {x: cosh(cos(4)), z: tanh(cosh(cos(4))),
y: sinh(cos(a))}
#Constants inside hyperbolic functions should not be rewritten in terms of exp
newsystem = [(exp(x) - exp(-x)) - tanh(x)*(exp(x) + exp(-x)) + x - 5]
assert solve(newsystem, x) == {x: 5}
#If the variable of interest is present in hyperbolic function, only then
# it shouuld be rewritten in terms of exp and solved further
def test_issue_4886():
z = a*sqrt(R**2*a**2 + R**2*b**2 - c**2)/(a**2 + b**2)
t = b*c/(a**2 + b**2)
sol = [((b*(t - z) - c)/(-a), t - z), ((b*(t + z) - c)/(-a), t + z)]
assert solve([x**2 + y**2 - R**2, a*x + b*y - c], x, y) == sol
def test_issue_6819():
a, b, c, d = symbols('a b c d', positive=True)
assert solve(a*b**x - c*d**x, x) == [log(c/a)/log(b/d)]
def test_issue_17454():
x = Symbol('x')
assert solve((1 - x - I)**4, x) == [1 - I]
def test_issue_21852():
solution = [21 - 21*sqrt(2)/2]
assert solve(2*x + sqrt(2*x**2) - 21) == solution
def test_issue_21942():
eq = -d + (a*c**(1 - e) + b**(1 - e)*(1 - a))**(1/(1 - e))
sol = solve(eq, c, simplify=False, check=False)
assert sol == [(b/b**e - b/(a*b**e) + d**(1 - e)/a)**(1/(1 - e))]
def test_solver_flags():
root = solve(x**5 + x**2 - x - 1, cubics=False)
rad = solve(x**5 + x**2 - x - 1, cubics=True)
assert root != rad
def test_issue_22768():
eq = 2*x**3 - 16*(y - 1)**6*z**3
assert solve(eq.expand(), x, simplify=False
) == [2*z*(y - 1)**2, z*(-1 + sqrt(3)*I)*(y - 1)**2,
-z*(1 + sqrt(3)*I)*(y - 1)**2]
def test_issue_22717():
assert solve((-y**2 + log(y**2/x) + 2, -2*x*y + 2*x/y)) == [
{y: -1, x: E}, {y: 1, x: E}]
def test_issue_10169():
eq = S(-8*a - x**5*(a + b + c + e) - x**4*(4*a - 2**Rational(3,4)*c + 4*c +
d + 2**Rational(3,4)*e + 4*e + k) - x**3*(-4*2**Rational(3,4)*c + sqrt(2)*c -
2**Rational(3,4)*d + 4*d + sqrt(2)*e + 4*2**Rational(3,4)*e + 2**Rational(3,4)*k + 4*k) -
x**2*(4*sqrt(2)*c - 4*2**Rational(3,4)*d + sqrt(2)*d + 4*sqrt(2)*e +
sqrt(2)*k + 4*2**Rational(3,4)*k) - x*(2*a + 2*b + 4*sqrt(2)*d +
4*sqrt(2)*k) + 5)
assert solve_undetermined_coeffs(eq, [a, b, c, d, e, k], x) == {
a: Rational(5,8),
b: Rational(-5,1032),
c: Rational(-40,129) - 5*2**Rational(3,4)/129 + 5*2**Rational(1,4)/1032,
d: -20*2**Rational(3,4)/129 - 10*sqrt(2)/129 - 5*2**Rational(1,4)/258,
e: Rational(-40,129) - 5*2**Rational(1,4)/1032 + 5*2**Rational(3,4)/129,
k: -10*sqrt(2)/129 + 5*2**Rational(1,4)/258 + 20*2**Rational(3,4)/129
}
|
19bff07611cf82599a673b38f3961acbfe454febb78970f27a5c2015abf45f7a | from sympy.core.function import (Function, Lambda, expand)
from sympy.core.numbers import (I, Rational)
from sympy.core.relational import Eq
from sympy.core.singleton import S
from sympy.core.symbol import (Symbol, symbols)
from sympy.functions.combinatorial.factorials import (rf, binomial, factorial)
from sympy.functions.elementary.complexes import Abs
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.trigonometric import (cos, sin)
from sympy.polys.polytools import factor
from sympy.solvers.recurr import rsolve, rsolve_hyper, rsolve_poly, rsolve_ratio
from sympy.testing.pytest import raises, slow, XFAIL
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) == 0
assert rsolve_hyper([-n - 1, -1, 1], 0, n) == 0
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) == 0
@XFAIL
def test_rsolve_ratio_missed():
# this arises during computation
# assert rsolve_hyper([-1, 1], 3*(n + n**2), n).expand() == C0 + n**3 - n
assert rsolve_ratio([-n, n + 2], n, n) is not 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) and len(c) <= 3:
assert rsolve_hyper(c, q, n).subs(zip(symbols('C:3'), [0, 0, 0])).expand() == p
def test_rsolve_0_sol_homogeneous():
# fixed by cherry-pick from
# https://github.com/diofant/diofant/commit/e1d2e52125199eb3df59f12e8944f8a5f24b00a5
assert rsolve_hyper([n**2 - n + 12, 1], n*(n**2 - n + 12) + n + 1, n) == n
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)
yn = rsolve(f, y(n), {y(1): binomial(2*n + 1, 3)})
sol = 2**(2*n)*n*(2*n - 1)**2*(2*n + 1)/12
assert factor(expand(yn, func=True)) == sol
sol = rsolve(y(n) + a*(y(n + 1) + y(n - 1))/2, y(n))
Y = lambda i: sol.subs(n, i)
assert (Y(n) + a*(Y(n + 1) + Y(n - 1))/2).expand().cancel() == 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)
assert rsolve(y(n) + y(n + 1) + 2**n + 3**n, y(n)) == (-1)**n*C0 - 2**n/3 - 3**n/4
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}))
raises(ValueError, lambda: rsolve(y(n) + y(n + 1) + 2**n + cos(n), y(n)))
def test_issue_6844():
f = y(n + 2) - y(n + 1) + y(n)/4
assert rsolve(f, y(n)) == 2**(-n + 1)*C1*n + 2**(-n)*C0
assert rsolve(f, y(n), {y(0): 0, y(1): 1}) == 2**(1 - n)*n
def test_issue_18751():
r = Symbol('r', positive=True)
theta = Symbol('theta', real=True)
f = y(n) - 2 * r * cos(theta) * y(n - 1) + r**2 * y(n - 2)
assert rsolve(f, y(n)) == \
C0*(r*(cos(theta) - I*Abs(sin(theta))))**n + C1*(r*(cos(theta) + I*Abs(sin(theta))))**n
def test_constant_naming():
#issue 8697
assert rsolve(y(n+3) - y(n+2) - y(n+1) + y(n), y(n)) == (-1)**n*C1 + C0 + C2*n
assert rsolve(y(n+3)+3*y(n+2)+3*y(n+1)+y(n), y(n)).expand() == (-1)**n*C0 - (-1)**n*C1*n - (-1)**n*C2*n**2
assert rsolve(y(n) - 2*y(n - 3) + 5*y(n - 2) - 4*y(n - 1),y(n),[1,3,8]) == 3*2**n - n - 2
#issue 19630
assert rsolve(y(n+3) - 3*y(n+1) + 2*y(n), y(n), {y(1):0, y(2):8, y(3):-2}) == (-2)**n + 2*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
def test_issue_17990():
f = -10*y(n) + 4*y(n + 1) + 6*y(n + 2) + 46*y(n + 3)
sol = rsolve(f, y(n))
expected = C0*((86*18**(S(1)/3)/69 + (-12 + (-1 + sqrt(3)*I)*(290412 +
3036*sqrt(9165))**(S(1)/3))*(1 - sqrt(3)*I)*(24201 + 253*sqrt(9165))**
(S(1)/3)/276)/((1 - sqrt(3)*I)*(24201 + 253*sqrt(9165))**(S(1)/3))
)**n + C1*((86*18**(S(1)/3)/69 + (-12 + (-1 - sqrt(3)*I)*(290412 + 3036
*sqrt(9165))**(S(1)/3))*(1 + sqrt(3)*I)*(24201 + 253*sqrt(9165))**
(S(1)/3)/276)/((1 + sqrt(3)*I)*(24201 + 253*sqrt(9165))**(S(1)/3))
)**n + C2*(-43*18**(S(1)/3)/(69*(24201 + 253*sqrt(9165))**(S(1)/3)) -
S(1)/23 + (290412 + 3036*sqrt(9165))**(S(1)/3)/138)**n
assert sol == expected
e = sol.subs({C0: 1, C1: 1, C2: 1, n: 1}).evalf()
assert abs(e + 0.130434782608696) < 1e-13
def test_issue_8697():
a = Function('a')
eq = a(n + 3) - a(n + 2) - a(n + 1) + a(n)
assert rsolve(eq, a(n)) == (-1)**n*C1 + C0 + C2*n
eq2 = a(n + 3) + 3*a(n + 2) + 3*a(n + 1) + a(n)
assert (rsolve(eq2, a(n)) ==
(-1)**n*C0 + (-1)**(n + 1)*C1*n + (-1)**(n + 1)*C2*n**2)
assert rsolve(a(n) - 2*a(n - 3) + 5*a(n - 2) - 4*a(n - 1),
a(n), {a(0): 1, a(1): 3, a(2): 8}) == 3*2**n - n - 2
# From issue thread (but fixed by https://github.com/diofant/diofant/commit/da9789c6cd7d0c2ceeea19fbf59645987125b289):
assert rsolve(a(n) - 2*a(n - 1) - n, a(n), {a(0): 1}) == 3*2**n - n - 2
def test_diofantissue_294():
f = y(n) - y(n - 1) - 2*y(n - 2) - 2*n
assert rsolve(f, y(n)) == (-1)**n*C0 + 2**n*C1 - n - Rational(5, 2)
# issue sympy/sympy#11261
assert rsolve(f, y(n), {y(0): -1, y(1): 1}) == (-(-1)**n/2 + 2*2**n -
n - Rational(5, 2))
# issue sympy/sympy#7055
assert rsolve(-2*y(n) + y(n + 1) + n - 1, y(n)) == 2**n*C0 + n
def test_issue_15553():
f = Function("f")
assert rsolve(Eq(f(n), 2*f(n - 1) + n), f(n)) == 2**n*C0 - n - 2
assert rsolve(Eq(f(n + 1), 2*f(n) + n**2 + 1), f(n)) == 2**n*C0 - n**2 - 2*n - 4
assert rsolve(Eq(f(n + 1), 2*f(n) + n**2 + 1), f(n), {f(1): 0}) == 7*2**n/2 - n**2 - 2*n - 4
assert rsolve(Eq(f(n), 2*f(n - 1) + 3*n**2), f(n)) == 2**n*C0 - 3*n**2 - 12*n - 18
assert rsolve(Eq(f(n), 2*f(n - 1) + n**2), f(n)) == 2**n*C0 - n**2 - 4*n - 6
assert rsolve(Eq(f(n), 2*f(n - 1) + n), f(n), {f(0): 1}) == 3*2**n - n - 2
|
261f9f011a647839144fbf2856abda34f22cdb9bfd56adc65f3eb95647d04991 | from sympy.core.add import Add
from sympy.core.mul import Mul
from sympy.core.numbers import (Rational, oo, pi)
from sympy.core.relational import Eq
from sympy.core.singleton import S
from sympy.core.symbol import symbols
from sympy.matrices.dense import Matrix
from sympy.ntheory.factor_ import factorint
from sympy.simplify.powsimp import powsimp
from sympy.core.function import _mexpand
from sympy.core.sorting import default_sort_key, 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, _nint_or_floor,
_odd, _even, _remove_gcd, _can_do_sum_of_squares, DiophantineSolutionSet, GeneralPythagorean,
BinaryQuadratic)
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')
assert classify_diop(x**2 + y**2 + z**2) == (
[x, y, z], {x**2: 1, y**2: 1, z**2: 1}, 'homogeneous_ternary_quadratic_normal')
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)
assert BinaryQuadratic(x**2 + y**2 + 2*x + 2*y + 2).solve() == {(-1, -1)}
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.
# https://web.archive.org/web/20160323033128/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)
assert GeneralPythagorean(a**2 + b**2 + c**2 - d**2).solve(parameters=[x, y, z]) == \
{(x**2 + y**2 - z**2, 2*x*z, 2*y*z, x**2 + y**2 + z**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)
assert diop_general_sum_of_squares(x**2 + y**2 - 2) is None
assert diop_general_sum_of_squares(x**2 + y**2 + z**2 + 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_issue_23807():
# fixes recursion error
eq = x**2 + y**2 + z**2 - 1000000
base_soln = {(0, 0, 1000), (0, 352, 936), (480, 600, 640), (24, 640, 768), (192, 640, 744),
(192, 480, 856), (168, 224, 960), (0, 600, 800), (280, 576, 768), (152, 480, 864),
(0, 280, 960), (352, 360, 864), (424, 480, 768), (360, 480, 800), (224, 600, 768),
(96, 360, 928), (168, 576, 800), (96, 480, 872)}
assert diophantine(eq) == base_soln
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 sympy.core.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, -t - 3), (2*t - 3, -t)}
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 len(check_param(S(3) + x/3, S(4) + x/2, S(2), [x])) == 0
assert len(check_param(Rational(3, 2), S(4) + x, S(2), [x])) == 0
assert len(check_param(S(4) + x, Rational(3, 2), S(2), [x])) == 0
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)
def test_diophantine_solution_set():
s1 = DiophantineSolutionSet([], [])
assert set(s1) == set()
assert s1.symbols == ()
assert s1.parameters == ()
raises(ValueError, lambda: s1.add((x,)))
assert list(s1.dict_iterator()) == []
s2 = DiophantineSolutionSet([x, y], [t, u])
assert s2.symbols == (x, y)
assert s2.parameters == (t, u)
raises(ValueError, lambda: s2.add((1,)))
s2.add((3, 4))
assert set(s2) == {(3, 4)}
s2.update((3, 4), (-1, u))
assert set(s2) == {(3, 4), (-1, u)}
raises(ValueError, lambda: s1.update(s2))
assert list(s2.dict_iterator()) == [{x: -1, y: u}, {x: 3, y: 4}]
s3 = DiophantineSolutionSet([x, y, z], [t, u])
assert len(s3.parameters) == 2
s3.add((t**2 + u, t - u, 1))
assert set(s3) == {(t**2 + u, t - u, 1)}
assert s3.subs(t, 2) == {(u + 4, 2 - u, 1)}
assert s3(2) == {(u + 4, 2 - u, 1)}
assert s3.subs({t: 7, u: 8}) == {(57, -1, 1)}
assert s3(7, 8) == {(57, -1, 1)}
assert s3.subs({t: 5}) == {(u + 25, 5 - u, 1)}
assert s3(5) == {(u + 25, 5 - u, 1)}
assert s3.subs(u, -3) == {(t**2 - 3, t + 3, 1)}
assert s3(None, -3) == {(t**2 - 3, t + 3, 1)}
assert s3.subs({t: 2, u: 8}) == {(12, -6, 1)}
assert s3(2, 8) == {(12, -6, 1)}
assert s3.subs({t: 5, u: -3}) == {(22, 8, 1)}
assert s3(5, -3) == {(22, 8, 1)}
raises(ValueError, lambda: s3.subs(x=1))
raises(ValueError, lambda: s3.subs(1, 2, 3))
raises(ValueError, lambda: s3.add(()))
raises(ValueError, lambda: s3.add((1, 2, 3, 4)))
raises(ValueError, lambda: s3.add((1, 2)))
raises(ValueError, lambda: s3(1, 2, 3))
raises(TypeError, lambda: s3(t=1))
s4 = DiophantineSolutionSet([x, y], [t, u])
s4.add((t, 11*t))
s4.add((-t, 22*t))
assert s4(0, 0) == {(0, 0)}
def test_quadratic_parameter_passing():
eq = -33*x*y + 3*y**2
solution = BinaryQuadratic(eq).solve(parameters=[t, u])
# test that parameters are passed all the way to the final solution
assert solution == {(t, 11*t), (-t, 22*t)}
assert solution(0, 0) == {(0, 0)}
|
5ac0de892d5cc4ee0d0833496bdf4d300ab2b0fb0eaca4d0d1ce9a63fbb6be37 | from sympy.core.function import (Derivative, Function, Subs, diff)
from sympy.core.numbers import (E, I, Rational, pi)
from sympy.core.relational import Eq
from sympy.core.singleton import S
from sympy.core.symbol import (Symbol, symbols)
from sympy.functions.elementary.complexes import (im, re)
from sympy.functions.elementary.exponential import (exp, log)
from sympy.functions.elementary.hyperbolic import acosh
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.trigonometric import (atan2, cos, sin, tan)
from sympy.integrals.integrals import Integral
from sympy.polys.polytools import Poly
from sympy.series.order import O
from sympy.simplify.radsimp import collect
from sympy.solvers.ode import (classify_ode,
homogeneous_order, dsolve)
from sympy.solvers.ode.subscheck import checkodesol
from sympy.solvers.ode.ode import (classify_sysode,
constant_renumber, constantsimp, get_numbered_constants, solve_ics)
from sympy.solvers.ode.nonhomogeneous import _undetermined_coefficients_match
from sympy.solvers.ode.single import LinearCoefficients
from sympy.solvers.deutils import ode_order
from sympy.testing.pytest import XFAIL, raises, slow
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: Examples which were specifically testing Single ODE solver are moved to test_single.py
# and all the system of ode examples are moved to test_systems.py
# 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_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 = {'Bernoulli_Integral': Eq(f(x), C1 + Integral(0, x)),
'1st_homogeneous_coeff_best': Eq(f(x), C1),
'Bernoulli': Eq(f(x), C1),
'nth_algebraic': Eq(f(x), C1),
'nth_linear_euler_eq_homogeneous': Eq(f(x), C1),
'nth_linear_constant_coeff_homogeneous': Eq(f(x), C1),
'separable': Eq(f(x), C1),
'1st_homogeneous_coeff_subs_indep_div_dep': Eq(f(x), C1),
'nth_algebraic_Integral': Eq(f(x), C1),
'1st_linear': Eq(f(x), C1),
'1st_linear_Integral': Eq(f(x), C1 + Integral(0, x)),
'1st_exact': Eq(f(x), C1),
'1st_exact_Integral': Eq(Subs(Integral(0, x) + Integral(1, _y), _y, f(x)), C1),
'lie_group': 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_power_series': Eq(f(x), C1),
'separable_Integral': Eq(Integral(1, (_y, f(x))), C1 + Integral(0, x)),
'1st_homogeneous_coeff_subs_indep_div_dep_Integral': Eq(f(x), C1),
'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})
@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', 'Bernoulli', 'Bernoulli_Integral',
'almost_linear', 'almost_linear_Integral', 'best', 'best_hint',
'default', 'factorable', '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',
'Bernoulli_Integral', 'almost_linear_Integral', 'best', 'best_hint', 'default',
'factorable', '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'] == 'factorable'
assert a['best_hint'] == 'factorable'
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'] == 'factorable'
assert b['best_hint'] == 'factorable'
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_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_homogeneous',
'nth_linear_euler_eq_homogeneous',
'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')
assert classify_ode(f(x).diff(x)**2, f(x)) == ('factorable',
'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_euler_eq_homogeneous',
'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')
# 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_exact',
'1st_linear',
'Bernoulli',
'almost_linear',
'1st_power_series', "lie_group",
'nth_linear_constant_coeff_undetermined_coefficients',
'nth_linear_constant_coeff_variation_of_parameters',
'1st_exact_Integral',
'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 == ('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 classify_ode(
2*x*f(x)*f(x).diff(x) + (1 + x)*f(x)**2 - exp(x), f(x)
) == ('factorable', '1st_exact', 'Bernoulli', 'almost_linear', 'lie_group',
'1st_exact_Integral', '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)) == \
('factorable', 'separable', '1st_exact', '1st_linear', 'Bernoulli',
'1st_power_series', 'lie_group', 'separable_Integral', '1st_exact_Integral',
'1st_linear_Integral', 'Bernoulli_Integral')
# preprocessing
ans = ('factorable', '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_exact',
'1st_linear', 'Bernoulli', '1st_power_series',
'lie_group', 'nth_linear_euler_eq_homogeneous',
'nth_algebraic_Integral', 'separable_Integral', '1st_exact_Integral',
'1st_linear_Integral', 'Bernoulli_Integral')
assert classify_ode(Eq(2*f(x)**3*f(x).diff(x), 0), f(x)) == \
('factorable', 'nth_algebraic', 'separable', '1st_exact', '1st_linear',
'Bernoulli', '1st_power_series', 'lie_group', 'nth_algebraic_Integral',
'separable_Integral', '1st_exact_Integral', '1st_linear_Integral',
'Bernoulli_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)
#This is for new behavior of classify_ode when called internally with default, It should
# return the first hint which matches therefore, 'ordered_hints' key will not be there.
assert sorted(classify_ode(Eq(f(x).diff(x), 0), f(x), dict=True).keys()) == \
['default', 'nth_linear_constant_coeff_homogeneous', 'order']
a = classify_ode(2*x*f(x)*f(x).diff(x) + (1 + x)*f(x)**2 - exp(x), f(x), dict=True, hint='Bernoulli')
assert sorted(a.keys()) == ['Bernoulli', 'Bernoulli_Integral', 'default', 'order', 'ordered_hints']
# test issue 22155
a = classify_ode(f(x).diff(x) - exp(f(x) - x), f(x))
assert a == ('separable',
'1st_exact', '1st_power_series',
'lie_group', 'separable_Integral',
'1st_exact_Integral')
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 x
ics = {f(0): f(x)}
raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics))
# Does not raise
ics = {f(0): f(0)}
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 x
ics = {f(x).diff(x).subs(x, 0): f(x)}
raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics))
# Does not raise
ics = {f(x).diff(x).subs(x, 0): f(x).diff(x).subs(x, 0)}
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 x
ics = {f(x).diff(x).subs(x, y): f(x)}
raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics))
# Does not raise
ics = {f(x).diff(x).subs(x, 0): f(0)}
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) ;
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
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
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
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)}
# Allow the ics to refer to f
ics = {f(0): f(0)}
assert dsolve(f(x).diff(x) - f(x), f(x), ics=ics) == Eq(f(x), f(0)*exp(x))
ics = {f(x).diff(x).subs(x, 0): f(x).diff(x).subs(x, 0), f(0): f(0)}
assert dsolve(f(x).diff(x, x) + f(x), f(x), ics=ics) == \
Eq(f(x), f(0)*cos(x) + f(x).diff(x).subs(x, 0)*sin(x))
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
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))
@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':
{cos(2*x + sqrt(5)), sin(2*x + sqrt(5))}}
assert _undetermined_coefficients_match(sin(x)*cos(x), x) == \
{'test': False}
s = {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': {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': {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': {exp(1 + 3*x)}}
assert _undetermined_coefficients_match(sin(x)*(x**2 + x + 1), x) == \
{'test': True, 'trialset': {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': {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': {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': {2**x, x*2**x}}
assert _undetermined_coefficients_match(2**x*exp(2*x), x) == \
{'test': True, 'trialset': {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': {S.One}}
assert _undetermined_coefficients_match(12*exp(x), x) == \
{'test': True, 'trialset': {exp(x)}}
assert _undetermined_coefficients_match(exp(I*x), x) == \
{'test': True, 'trialset': {exp(I*x)}}
assert _undetermined_coefficients_match(sin(x), x) == \
{'test': True, 'trialset': {cos(x), sin(x)}}
assert _undetermined_coefficients_match(cos(x), x) == \
{'test': True, 'trialset': {cos(x), sin(x)}}
assert _undetermined_coefficients_match(8 + 6*exp(x) + 2*sin(x), x) == \
{'test': True, 'trialset': {S.One, cos(x), sin(x), exp(x)}}
assert _undetermined_coefficients_match(x**2, x) == \
{'test': True, 'trialset': {S.One, x, x**2}}
assert _undetermined_coefficients_match(9*x*exp(x) + exp(-x), x) == \
{'test': True, 'trialset': {x*exp(x), exp(x), exp(-x)}}
assert _undetermined_coefficients_match(2*exp(2*x)*sin(x), x) == \
{'test': True, 'trialset': {exp(2*x)*sin(x), cos(x)*exp(2*x)}}
assert _undetermined_coefficients_match(x - sin(x), x) == \
{'test': True, 'trialset': {S.One, x, cos(x), sin(x)}}
assert _undetermined_coefficients_match(x**2 + 2*x, x) == \
{'test': True, 'trialset': {S.One, x, x**2}}
assert _undetermined_coefficients_match(4*x*sin(x), x) == \
{'test': True, 'trialset': {x*cos(x), x*sin(x), cos(x), sin(x)}}
assert _undetermined_coefficients_match(x*sin(2*x), x) == \
{'test': True, 'trialset':
{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': {x*exp(-x), x**2*exp(-x), exp(-x)}}
assert _undetermined_coefficients_match(2*exp(-x) - x**2*exp(-x), x) == \
{'test': True, 'trialset': {x*exp(-x), x**2*exp(-x), exp(-x)}}
assert _undetermined_coefficients_match(exp(-2*x) + x**2, x) == \
{'test': True, 'trialset': {S.One, x, x**2, exp(-2*x)}}
assert _undetermined_coefficients_match(x*exp(-x), x) == \
{'test': True, 'trialset': {x*exp(-x), exp(-x)}}
assert _undetermined_coefficients_match(x + exp(2*x), x) == \
{'test': True, 'trialset': {S.One, x, exp(2*x)}}
assert _undetermined_coefficients_match(sin(x) + exp(-x), x) == \
{'test': True, 'trialset': {cos(x), sin(x), exp(-x)}}
assert _undetermined_coefficients_match(exp(x), x) == \
{'test': True, 'trialset': {exp(x)}}
# converted from sin(x)**2
assert _undetermined_coefficients_match(S.Half - cos(2*x)/2, x) == \
{'test': True, 'trialset': {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': {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': {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': {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}
def test_issue_4785_22462():
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)) == ('factorable', '1st_exact', '1st_linear',
'Bernoulli', 'almost_linear', '1st_power_series', 'lie_group',
'nth_linear_constant_coeff_undetermined_coefficients',
'nth_linear_constant_coeff_variation_of_parameters',
'1st_exact_Integral', '1st_linear_Integral', 'Bernoulli_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)) == ('factorable', '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_constant_renumber():
e1, e2, x, y = symbols("e1:3 x y")
exprs = [e2*x, e1*x + e2*y]
assert constant_renumber(exprs[0]) == e2*x
assert constant_renumber(exprs[0], variables=[x]) == C1*x
assert constant_renumber(exprs[0], variables=[x], newconstants=[C2]) == C2*x
assert constant_renumber(exprs, variables=[x, y]) == [C1*x, C1*y + C2*x]
assert constant_renumber(exprs, variables=[x, y], newconstants=symbols("C3:5")) == [C3*x, C3*y + C4*x]
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), {C1, C2}) == \
C1*cos(x)*exp(x)
assert constantsimp(C1*cos(x) + C2*cos(x) + C3*sin(x), {C1, C2, C3}) == \
C1*cos(x) + C3*sin(x)
assert constantsimp(exp(C1 + x), {C1}) == C1*exp(x)
assert constantsimp(x + C1 + y, {C1, y}) == C1 + x
assert constantsimp(x + C1 + Integral(x, (x, 1, 2)), {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_issue_5095():
f = Function('f')
raises(ValueError, lambda: dsolve(f(x).diff(x)**2, f(x), 'fdsjf'))
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())
obj1 = LinearCoefficients(eq1)
eq2 = rat
obj2 = LinearCoefficients(eq2)
eq3 = log(sin(rat))
obj3 = LinearCoefficients(eq3)
ans = (4, Rational(-13, 3))
assert obj1._linear_coeff_match(eq1, f(x)) == ans
assert obj2._linear_coeff_match(eq2, f(x)) == ans
assert obj3._linear_coeff_match(eq3, f(x)) == ans
# no c
eq4 = (3*x)/f(x)
obj4 = LinearCoefficients(eq4)
# not x and f(x)
eq5 = (3*x + 2)/x
obj5 = LinearCoefficients(eq5)
# denom will be zero
eq6 = (3*x + 2*f(x) + 1)/(3*x + 2*f(x) + 5)
obj6 = LinearCoefficients(eq6)
# not rational coefficient
eq7 = (3*x + 2*f(x) + sqrt(2))/(3*x + 2*f(x) + 5)
obj7 = LinearCoefficients(eq7)
assert obj4._linear_coeff_match(eq4, f(x)) is None
assert obj5._linear_coeff_match(eq5, f(x)) is None
assert obj6._linear_coeff_match(eq6, f(x)) is None
assert obj7._linear_coeff_match(eq7, f(x)) is None
def test_constantsimp_take_problem():
c = exp(C1) + 2
assert len(Poly(constantsimp(exp(C1) + c + c*x, [C1])).gens) == 2
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]
@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) == ('factorable', '2nd_hypergeometric', '2nd_hypergeometric_Integral',
'2nd_power_series_ordinary')
sol = Eq(f(x), C2*(-x**4/3 + x**2 + 1) + C1*x + O(x**6))
assert dsolve(eq, hint='2nd_power_series_ordinary') == sol
assert checkodesol(eq, sol) == (True, 0)
eq = f(x).diff(x, 2) + x*(f(x).diff(x)) + f(x)
assert classify_ode(eq) == ('factorable', '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_2nd_power_series_regular():
C1, C2, a = symbols("C1 C2 a")
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)
eq = x*f(x).diff(x, 2) + f(x).diff(x) - a*x*f(x)
sol = Eq(f(x), C1*(a**2*x**4/64 + a*x**2/4 + 1) + O(x**6))
assert dsolve(eq, f(x), hint="2nd_power_series_regular") == sol
assert checkodesol(eq, sol) == (True, 0)
eq = f(x).diff(x, 2) + ((1 - x)/x)*f(x).diff(x) + (a/x)*f(x)
sol = Eq(f(x), C1*(-a*x**5*(a - 4)*(a - 3)*(a - 2)*(a - 1)/14400 + \
a*x**4*(a - 3)*(a - 2)*(a - 1)/576 - a*x**3*(a - 2)*(a - 1)/36 + \
a*x**2*(a - 1)/4 - a*x + 1) + O(x**6))
assert dsolve(eq, f(x), hint="2nd_power_series_regular") == sol
assert checkodesol(eq, sol) == (True, 0)
def test_issue_15056():
t = Symbol('t')
C3 = Symbol('C3')
assert get_numbered_constants(Symbol('C1') * Function('C2')(t)) == C3
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_issue_13060():
A, B = symbols("A B", cls=Function)
t = Symbol("t")
eq = [Eq(Derivative(A(t), t), A(t)*B(t)), Eq(Derivative(B(t), t), A(t)*B(t))]
sol = dsolve(eq)
assert checkodesol(eq, sol) == (True, [0, 0])
def test_issue_22523():
N, s = symbols('N s')
rho = Function('rho')
# intentionally use 4.0 to confirm issue with nfloat
# works here
eqn = 4.0*N*sqrt(N - 1)*rho(s) + (4*s**2*(N - 1) + (N - 2*s*(N - 1))**2
)*Derivative(rho(s), (s, 2))
match = classify_ode(eqn, dict=True, hint='all')
assert match['2nd_power_series_ordinary']['terms'] == 5
C1, C2 = symbols('C1,C2')
sol = dsolve(eqn, hint='2nd_power_series_ordinary')
# there is no r(2.0) in this result
assert filldedent(sol) == filldedent(str('''
Eq(rho(s), C2*(1 - 4.0*s**4*sqrt(N - 1.0)/N + 0.666666666666667*s**4/N
- 2.66666666666667*s**3*sqrt(N - 1.0)/N - 2.0*s**2*sqrt(N - 1.0)/N +
9.33333333333333*s**4*sqrt(N - 1.0)/N**2 - 0.666666666666667*s**4/N**2
+ 2.66666666666667*s**3*sqrt(N - 1.0)/N**2 -
5.33333333333333*s**4*sqrt(N - 1.0)/N**3) + C1*s*(1.0 -
1.33333333333333*s**3*sqrt(N - 1.0)/N - 0.666666666666667*s**2*sqrt(N
- 1.0)/N + 1.33333333333333*s**3*sqrt(N - 1.0)/N**2) + O(s**6))'''))
def test_issue_22604():
x1, x2 = symbols('x1, x2', cls = Function)
t, k1, k2, m1, m2 = symbols('t k1 k2 m1 m2', real = True)
k1, k2, m1, m2 = 1, 1, 1, 1
eq1 = Eq(m1*diff(x1(t), t, 2) + k1*x1(t) - k2*(x2(t) - x1(t)), 0)
eq2 = Eq(m2*diff(x2(t), t, 2) + k2*(x2(t) - x1(t)), 0)
eqs = [eq1, eq2]
[x1sol, x2sol] = dsolve(eqs, [x1(t), x2(t)], ics = {x1(0):0, x1(t).diff().subs(t,0):0, \
x2(0):1, x2(t).diff().subs(t,0):0})
assert x1sol == Eq(x1(t), sqrt(3 - sqrt(5))*(sqrt(10) + 5*sqrt(2))*cos(sqrt(2)*t*sqrt(3 - sqrt(5))/2)/20 + \
(-5*sqrt(2) + sqrt(10))*sqrt(sqrt(5) + 3)*cos(sqrt(2)*t*sqrt(sqrt(5) + 3)/2)/20)
assert x2sol == Eq(x2(t), (sqrt(5) + 5)*cos(sqrt(2)*t*sqrt(3 - sqrt(5))/2)/10 + (5 - sqrt(5))*cos(sqrt(2)*t*sqrt(sqrt(5) + 3)/2)/10)
def test_issue_22462():
for de in [
Eq(f(x).diff(x), -20*f(x)**2 - 500*f(x)/7200),
Eq(f(x).diff(x), -2*f(x)**2 - 5*f(x)/7)]:
assert 'Bernoulli' in classify_ode(de, f(x))
def test_issue_23425():
x = symbols('x')
y = Function('y')
eq = Eq(-E**x*y(x).diff().diff() + y(x).diff(), 0)
assert classify_ode(eq) == \
('Liouville', 'nth_order_reducible', \
'2nd_power_series_ordinary', 'Liouville_Integral')
|
95267ae8a31df9bf8eb1a9b25da0ad665eaedebf8e28c9eb9cabc4b4cfbb3824 | #
# The main tests for the code in single.py are currently located in
# sympy/solvers/tests/test_ode.py
#
r"""
This File contains test functions for the individual hints used for solving ODEs.
Examples of each solver will be returned by _get_examples_ode_sol_name_of_solver.
Examples should have a key 'XFAIL' which stores the list of hints if they are
expected to fail for that hint.
Functions that are for internal use:
1) _ode_solver_test(ode_examples) - It takes a dictionary of examples returned by
_get_examples method and tests them with their respective hints.
2) _test_particular_example(our_hint, example_name) - It tests the ODE example corresponding
to the hint provided.
3) _test_all_hints(runxfail=False) - It is used to test all the examples with all the hints
currently implemented. It calls _test_all_examples_for_one_hint() which outputs whether the
given hint functions properly if it classifies the ODE example.
If runxfail flag is set to True then it will only test the examples which are expected to fail.
Everytime the ODE of a particular solver is added, _test_all_hints() is to be executed to find
the possible failures of different solver hints.
4) _test_all_examples_for_one_hint(our_hint, all_examples) - It takes hint as argument and checks
this hint against all the ODE examples and gives output as the number of ODEs matched, number
of ODEs which were solved correctly, list of ODEs which gives incorrect solution and list of
ODEs which raises exception.
"""
from sympy.core.function import (Derivative, diff)
from sympy.core.mul import Mul
from sympy.core.numbers import (E, I, Rational, pi)
from sympy.core.relational import (Eq, Ne)
from sympy.core.singleton import S
from sympy.core.symbol import (Dummy, symbols)
from sympy.functions.elementary.complexes import (im, re)
from sympy.functions.elementary.exponential import (LambertW, exp, log)
from sympy.functions.elementary.hyperbolic import (asinh, cosh, sinh, tanh)
from sympy.functions.elementary.miscellaneous import (cbrt, sqrt)
from sympy.functions.elementary.piecewise import Piecewise
from sympy.functions.elementary.trigonometric import (acos, asin, atan, cos, sec, sin, tan)
from sympy.functions.special.error_functions import (Ei, erfi)
from sympy.functions.special.hyper import hyper
from sympy.integrals.integrals import (Integral, integrate)
from sympy.polys.rootoftools import rootof
from sympy.core import Function, Symbol
from sympy.functions import airyai, airybi, besselj, bessely, lowergamma
from sympy.integrals.risch import NonElementaryIntegral
from sympy.solvers.ode import classify_ode, dsolve
from sympy.solvers.ode.ode import allhints, _remove_redundant_solutions
from sympy.solvers.ode.single import (FirstLinear, ODEMatchError,
SingleODEProblem, SingleODESolver, NthOrderReducible)
from sympy.solvers.ode.subscheck import checkodesol
from sympy.testing.pytest import raises, slow, ON_TRAVIS
import traceback
x = Symbol('x')
u = Symbol('u')
_u = Dummy('u')
y = Symbol('y')
f = Function('f')
g = Function('g')
C1, C2, C3, C4, C5, C6, C7, C8, C9, C10 = symbols('C1:11')
hint_message = """\
Hint did not match the example {example}.
The ODE is:
{eq}.
The expected hint was
{our_hint}\
"""
expected_sol_message = """\
Different solution found from dsolve for example {example}.
The ODE is:
{eq}
The expected solution was
{sol}
What dsolve returned is:
{dsolve_sol}\
"""
checkodesol_msg = """\
solution found is not correct for example {example}.
The ODE is:
{eq}\
"""
dsol_incorrect_msg = """\
solution returned by dsolve is incorrect when using {hint}.
The ODE is:
{eq}
The expected solution was
{sol}
what dsolve returned is:
{dsolve_sol}
You can test this with:
eq = {eq}
sol = dsolve(eq, hint='{hint}')
print(sol)
print(checkodesol(eq, sol))
"""
exception_msg = """\
dsolve raised exception : {e}
when using {hint} for the example {example}
You can test this with:
from sympy.solvers.ode.tests.test_single import _test_an_example
_test_an_example('{hint}', example_name = '{example}')
The ODE is:
{eq}
\
"""
check_hint_msg = """\
Tested hint was : {hint}
Total of {matched} examples matched with this hint.
Out of which {solve} gave correct results.
Examples which gave incorrect results are {unsolve}.
Examples which raised exceptions are {exceptions}
\
"""
def _add_example_keys(func):
def inner():
solver=func()
examples=[]
for example in solver['examples']:
temp={
'eq': solver['examples'][example]['eq'],
'sol': solver['examples'][example]['sol'],
'XFAIL': solver['examples'][example].get('XFAIL', []),
'func': solver['examples'][example].get('func',solver['func']),
'example_name': example,
'slow': solver['examples'][example].get('slow', False),
'simplify_flag':solver['examples'][example].get('simplify_flag',True),
'checkodesol_XFAIL': solver['examples'][example].get('checkodesol_XFAIL', False),
'dsolve_too_slow':solver['examples'][example].get('dsolve_too_slow',False),
'checkodesol_too_slow':solver['examples'][example].get('checkodesol_too_slow',False),
'hint': solver['hint']
}
examples.append(temp)
return examples
return inner()
def _ode_solver_test(ode_examples, run_slow_test=False):
for example in ode_examples:
if ((not run_slow_test) and example['slow']) or (run_slow_test and (not example['slow'])):
continue
result = _test_particular_example(example['hint'], example, solver_flag=True)
if result['xpass_msg'] != "":
print(result['xpass_msg'])
def _test_all_hints(runxfail=False):
all_hints = list(allhints)+["default"]
all_examples = _get_all_examples()
for our_hint in all_hints:
if our_hint.endswith('_Integral') or 'series' in our_hint:
continue
_test_all_examples_for_one_hint(our_hint, all_examples, runxfail)
def _test_dummy_sol(expected_sol,dsolve_sol):
if type(dsolve_sol)==list:
return any(expected_sol.dummy_eq(sub_dsol) for sub_dsol in dsolve_sol)
else:
return expected_sol.dummy_eq(dsolve_sol)
def _test_an_example(our_hint, example_name):
all_examples = _get_all_examples()
for example in all_examples:
if example['example_name'] == example_name:
_test_particular_example(our_hint, example)
def _test_particular_example(our_hint, ode_example, solver_flag=False):
eq = ode_example['eq']
expected_sol = ode_example['sol']
example = ode_example['example_name']
xfail = our_hint in ode_example['XFAIL']
func = ode_example['func']
result = {'msg': '', 'xpass_msg': ''}
simplify_flag=ode_example['simplify_flag']
checkodesol_XFAIL = ode_example['checkodesol_XFAIL']
dsolve_too_slow = ode_example['dsolve_too_slow']
checkodesol_too_slow = ode_example['checkodesol_too_slow']
xpass = True
if solver_flag:
if our_hint not in classify_ode(eq, func):
message = hint_message.format(example=example, eq=eq, our_hint=our_hint)
raise AssertionError(message)
if our_hint in classify_ode(eq, func):
result['match_list'] = example
try:
if not (dsolve_too_slow):
dsolve_sol = dsolve(eq, func, simplify=simplify_flag,hint=our_hint)
else:
if len(expected_sol)==1:
dsolve_sol = expected_sol[0]
else:
dsolve_sol = expected_sol
except Exception as e:
dsolve_sol = []
result['exception_list'] = example
if not solver_flag:
traceback.print_exc()
result['msg'] = exception_msg.format(e=str(e), hint=our_hint, example=example, eq=eq)
if solver_flag and not xfail:
print(result['msg'])
raise
xpass = False
if solver_flag and dsolve_sol!=[]:
expect_sol_check = False
if type(dsolve_sol)==list:
for sub_sol in expected_sol:
if sub_sol.has(Dummy):
expect_sol_check = not _test_dummy_sol(sub_sol, dsolve_sol)
else:
expect_sol_check = sub_sol not in dsolve_sol
if expect_sol_check:
break
else:
expect_sol_check = dsolve_sol not in expected_sol
for sub_sol in expected_sol:
if sub_sol.has(Dummy):
expect_sol_check = not _test_dummy_sol(sub_sol, dsolve_sol)
if expect_sol_check:
message = expected_sol_message.format(example=example, eq=eq, sol=expected_sol, dsolve_sol=dsolve_sol)
raise AssertionError(message)
expected_checkodesol = [(True, 0) for i in range(len(expected_sol))]
if len(expected_sol) == 1:
expected_checkodesol = (True, 0)
if not (checkodesol_too_slow and ON_TRAVIS):
if not checkodesol_XFAIL:
if checkodesol(eq, dsolve_sol, func, solve_for_func=False) != expected_checkodesol:
result['unsolve_list'] = example
xpass = False
message = dsol_incorrect_msg.format(hint=our_hint, eq=eq, sol=expected_sol,dsolve_sol=dsolve_sol)
if solver_flag:
message = checkodesol_msg.format(example=example, eq=eq)
raise AssertionError(message)
else:
result['msg'] = 'AssertionError: ' + message
if xpass and xfail:
result['xpass_msg'] = example + "is now passing for the hint" + our_hint
return result
def _test_all_examples_for_one_hint(our_hint, all_examples=[], runxfail=None):
if all_examples == []:
all_examples = _get_all_examples()
match_list, unsolve_list, exception_list = [], [], []
for ode_example in all_examples:
xfail = our_hint in ode_example['XFAIL']
if runxfail and not xfail:
continue
if xfail:
continue
result = _test_particular_example(our_hint, ode_example)
match_list += result.get('match_list',[])
unsolve_list += result.get('unsolve_list',[])
exception_list += result.get('exception_list',[])
if runxfail is not None:
msg = result['msg']
if msg!='':
print(result['msg'])
# print(result.get('xpass_msg',''))
if runxfail is None:
match_count = len(match_list)
solved = len(match_list)-len(unsolve_list)-len(exception_list)
msg = check_hint_msg.format(hint=our_hint, matched=match_count, solve=solved, unsolve=unsolve_list, exceptions=exception_list)
print(msg)
def test_SingleODESolver():
# Test that not implemented methods give NotImplementedError
# Subclasses should override these methods.
problem = SingleODEProblem(f(x).diff(x), f(x), x)
solver = SingleODESolver(problem)
raises(NotImplementedError, lambda: solver.matches())
raises(NotImplementedError, lambda: solver.get_general_solution())
raises(NotImplementedError, lambda: solver._matches())
raises(NotImplementedError, lambda: solver._get_general_solution())
# This ODE can not be solved by the FirstLinear solver. Here we test that
# it does not match and the asking for a general solution gives
# ODEMatchError
problem = SingleODEProblem(f(x).diff(x) + f(x)*f(x), f(x), x)
solver = FirstLinear(problem)
raises(ODEMatchError, lambda: solver.get_general_solution())
solver = FirstLinear(problem)
assert solver.matches() is False
#These are just test for order of ODE
problem = SingleODEProblem(f(x).diff(x) + f(x), f(x), x)
assert problem.order == 1
problem = SingleODEProblem(f(x).diff(x,4) + f(x).diff(x,2) - f(x).diff(x,3), f(x), x)
assert problem.order == 4
problem = SingleODEProblem(f(x).diff(x, 3) + f(x).diff(x, 2) - f(x)**2, f(x), x)
assert problem.is_autonomous == True
problem = SingleODEProblem(f(x).diff(x, 3) + x*f(x).diff(x, 2) - f(x)**2, f(x), x)
assert problem.is_autonomous == False
def test_linear_coefficients():
_ode_solver_test(_get_examples_ode_sol_linear_coefficients)
@slow
def test_1st_homogeneous_coeff_ode():
#These were marked as 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
_ode_solver_test(_get_examples_ode_sol_1st_homogeneous_coeff_subs_dep_div_indep)
_ode_solver_test(_get_examples_ode_sol_1st_homogeneous_coeff_best)
@slow
def test_slow_examples_1st_homogeneous_coeff_ode():
_ode_solver_test(_get_examples_ode_sol_1st_homogeneous_coeff_subs_dep_div_indep, run_slow_test=True)
_ode_solver_test(_get_examples_ode_sol_1st_homogeneous_coeff_best, run_slow_test=True)
@slow
def test_nth_linear_constant_coeff_homogeneous():
_ode_solver_test(_get_examples_ode_sol_nth_linear_constant_coeff_homogeneous)
@slow
def test_slow_examples_nth_linear_constant_coeff_homogeneous():
_ode_solver_test(_get_examples_ode_sol_nth_linear_constant_coeff_homogeneous, run_slow_test=True)
def test_Airy_equation():
_ode_solver_test(_get_examples_ode_sol_2nd_linear_airy)
@slow
def test_lie_group():
_ode_solver_test(_get_examples_ode_sol_lie_group)
@slow
def test_separable_reduced():
df = f(x).diff(x)
eq = (x / f(x))*df + tan(x**2*f(x) / (x**2*f(x) - 1))
assert classify_ode(eq) == ('factorable', 'separable_reduced', 'lie_group',
'separable_reduced_Integral')
_ode_solver_test(_get_examples_ode_sol_separable_reduced)
@slow
def test_slow_examples_separable_reduced():
_ode_solver_test(_get_examples_ode_sol_separable_reduced, run_slow_test=True)
@slow
def test_2nd_2F1_hypergeometric():
_ode_solver_test(_get_examples_ode_sol_2nd_2F1_hypergeometric)
def test_2nd_2F1_hypergeometric_integral():
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)
@slow
def test_2nd_nonlinear_autonomous_conserved():
_ode_solver_test(_get_examples_ode_sol_2nd_nonlinear_autonomous_conserved)
def test_2nd_nonlinear_autonomous_conserved_integral():
eq = f(x).diff(x, 2) + asin(f(x))
actual = [Eq(Integral(1/sqrt(C1 - 2*Integral(asin(_u), _u)), (_u, f(x))), C2 + x),
Eq(Integral(1/sqrt(C1 - 2*Integral(asin(_u), _u)), (_u, f(x))), C2 - x)]
solved = dsolve(eq, hint='2nd_nonlinear_autonomous_conserved_Integral', simplify=False)
for a,s in zip(actual, solved):
assert a.dummy_eq(s)
# checkodesol unable to simplify solutions with f(x) in an integral equation
assert checkodesol(eq, [s.doit() for s in solved]) == [(True, 0), (True, 0)]
@slow
def test_2nd_linear_bessel_equation():
_ode_solver_test(_get_examples_ode_sol_2nd_linear_bessel)
@slow
def test_nth_algebraic():
eqn = f(x) + f(x)*f(x).diff(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))]
_ode_solver_test(_get_examples_ode_sol_nth_algebraic)
@slow
def test_slow_examples_nth_linear_constant_coeff_var_of_parameters():
_ode_solver_test(_get_examples_ode_sol_nth_linear_var_of_parameters, run_slow_test=True)
def test_nth_linear_constant_coeff_var_of_parameters():
_ode_solver_test(_get_examples_ode_sol_nth_linear_var_of_parameters)
@slow
def test_nth_linear_constant_coeff_variation_of_parameters__integral():
# 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)
@slow
def test_slow_examples_1st_exact():
_ode_solver_test(_get_examples_ode_sol_1st_exact, run_slow_test=True)
@slow
def test_1st_exact():
_ode_solver_test(_get_examples_ode_sol_1st_exact)
def test_1st_exact_integral():
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')
assert checkodesol(eq, sol_1, order=1, solve_for_func=False)
@slow
def test_slow_examples_nth_order_reducible():
_ode_solver_test(_get_examples_ode_sol_nth_order_reducible, run_slow_test=True)
@slow
def test_slow_examples_nth_linear_constant_coeff_undetermined_coefficients():
_ode_solver_test(_get_examples_ode_sol_nth_linear_undetermined_coefficients, run_slow_test=True)
@slow
def test_slow_examples_separable():
_ode_solver_test(_get_examples_ode_sol_separable, run_slow_test=True)
@slow
def test_nth_linear_constant_coeff_undetermined_coefficients():
#issue-https://github.com/sympy/sympy/issues/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)
_ode_solver_test(_get_examples_ode_sol_nth_linear_undetermined_coefficients)
def test_nth_order_reducible():
F = lambda eq: NthOrderReducible(SingleODEProblem(eq, f(x), x))._matches()
D = Derivative
assert F(D(y*f(x), x, y) + D(f(x), x)) == False
assert F(D(y*f(y), y, y) + D(f(y), y)) == False
assert F(f(x)*D(f(x), x) + D(f(x), x, 2))== False
assert F(D(x*f(y), y, 2) + D(u*y*f(x), x, 3)) == False # no simplification by design
assert F(D(f(y), y, 2) + D(f(y), y, 3) + D(f(x), x, 4)) == False
assert F(D(f(x), x, 2) + D(f(x), x, 3)) == True
_ode_solver_test(_get_examples_ode_sol_nth_order_reducible)
@slow
def test_separable():
_ode_solver_test(_get_examples_ode_sol_separable)
@slow
def test_factorable():
assert integrate(-asin(f(2*x)+pi), x) == -Integral(asin(pi + f(2*x)), x)
_ode_solver_test(_get_examples_ode_sol_factorable)
@slow
def test_slow_examples_factorable():
_ode_solver_test(_get_examples_ode_sol_factorable, run_slow_test=True)
def test_Riccati_special_minus2():
_ode_solver_test(_get_examples_ode_sol_riccati)
@slow
def test_1st_rational_riccati():
_ode_solver_test(_get_examples_ode_sol_1st_rational_riccati)
def test_Bernoulli():
_ode_solver_test(_get_examples_ode_sol_bernoulli)
def test_1st_linear():
_ode_solver_test(_get_examples_ode_sol_1st_linear)
def test_almost_linear():
_ode_solver_test(_get_examples_ode_sol_almost_linear)
@slow
def test_Liouville_ODE():
hint = 'Liouville'
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
_ode_solver_test(_get_examples_ode_sol_liouville)
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)
_ode_solver_test(_get_examples_ode_sol_euler_homogeneous)
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))
_ode_solver_test(_get_examples_ode_sol_euler_undetermined_coeff)
@slow
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))
_ode_solver_test(_get_examples_ode_sol_euler_var_para)
@_add_example_keys
def _get_examples_ode_sol_euler_homogeneous():
r1, r2, r3, r4, r5 = [rootof(x**5 - 14*x**4 + 71*x**3 - 154*x**2 + 120*x - 1, n) for n in range(5)]
return {
'hint': "nth_linear_euler_eq_homogeneous",
'func': f(x),
'examples':{
'euler_hom_01': {
'eq': Eq(-3*diff(f(x), x)*x + 2*x**2*diff(f(x), x, x), 0),
'sol': [Eq(f(x), C1 + C2*x**Rational(5, 2))],
},
'euler_hom_02': {
'eq': Eq(3*f(x) - 5*diff(f(x), x)*x + 2*x**2*diff(f(x), x, x), 0),
'sol': [Eq(f(x), C1*sqrt(x) + C2*x**3)]
},
'euler_hom_03': {
'eq': Eq(4*f(x) + 5*diff(f(x), x)*x + x**2*diff(f(x), x, x), 0),
'sol': [Eq(f(x), (C1 + C2*log(x))/x**2)]
},
'euler_hom_04': {
'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': [Eq(f(x), C1/x**2 + C2*x + C3*x**3)]
},
'euler_hom_05': {
'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': [Eq(f(x), x**5*(C1 + C2*log(x) + C3*log(x)**2))]
},
'euler_hom_06': {
'eq': x**2*diff(f(x), x, 2) + x*diff(f(x), x) - 9*f(x),
'sol': [Eq(f(x), C1*x**-3 + C2*x**3)]
},
'euler_hom_07': {
'eq': sin(x)*x**2*f(x).diff(x, 2) + sin(x)*x*f(x).diff(x) + sin(x)*f(x),
'sol': [Eq(f(x), C1*sin(log(x)) + C2*cos(log(x)))],
'XFAIL': ['2nd_power_series_regular','nth_linear_euler_eq_nonhomogeneous_undetermined_coefficients']
},
'euler_hom_08': {
'eq': x**6 * f(x).diff(x, 6) - x*f(x).diff(x) + f(x),
'sol': [Eq(f(x), C1*x + C2*x**r1 + C3*x**r2 + C4*x**r3 + C5*x**r4 + C6*x**r5)],
'checkodesol_XFAIL':True
},
#This example is from issue: https://github.com/sympy/sympy/issues/15237 #This example is from issue:
# https://github.com/sympy/sympy/issues/15237
'euler_hom_09': {
'eq': Derivative(x*f(x), x, x, x),
'sol': [Eq(f(x), C1 + C2/x + C3*x)],
},
}
}
@_add_example_keys
def _get_examples_ode_sol_euler_undetermined_coeff():
return {
'hint': "nth_linear_euler_eq_nonhomogeneous_undetermined_coefficients",
'func': f(x),
'examples':{
'euler_undet_01': {
'eq': Eq(x**2*diff(f(x), x, x) + x*diff(f(x), x), 1),
'sol': [Eq(f(x), C1 + C2*log(x) + log(x)**2/2)]
},
'euler_undet_02': {
'eq': Eq(x**2*diff(f(x), x, x) - 2*x*diff(f(x), x) + 2*f(x), x**3),
'sol': [Eq(f(x), x*(C1 + C2*x + Rational(1, 2)*x**2))]
},
'euler_undet_03': {
'eq': Eq(x**2*diff(f(x), x, x) - x*diff(f(x), x) - 3*f(x), log(x)/x),
'sol': [Eq(f(x), (C1 + C2*x**4 - log(x)**2/8 - log(x)/16)/x)]
},
'euler_undet_04': {
'eq': Eq(x**2*diff(f(x), x, x) + 3*x*diff(f(x), x) - 8*f(x), log(x)**3 - log(x)),
'sol': [Eq(f(x), 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))]
},
'euler_undet_05': {
'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': [Eq(f(x), C1*x + C2*x**2 + C3*x**3 - Rational(1, 6)*log(x) - Rational(11, 36))]
},
#Below examples were added for the issue: https://github.com/sympy/sympy/issues/5096
'euler_undet_06': {
'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))]
},
'euler_undet_07': {
'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)]
},
}
}
@_add_example_keys
def _get_examples_ode_sol_euler_var_para():
return {
'hint': "nth_linear_euler_eq_nonhomogeneous_variation_of_parameters",
'func': f(x),
'examples':{
'euler_var_01': {
'eq': Eq(x**2*Derivative(f(x), x, x) - 2*x*Derivative(f(x), x) + 2*f(x), x**4),
'sol': [Eq(f(x), x*(C1 + C2*x + x**3/6))]
},
'euler_var_02': {
'eq': Eq(3*x**2*diff(f(x), x, x) + 6*x*diff(f(x), x) - 6*f(x), x**3*exp(x)),
'sol': [Eq(f(x), C1/x**2 + C2*x + x*exp(x)/3 - 4*exp(x)/3 + 8*exp(x)/(3*x) - 8*exp(x)/(3*x**2))]
},
'euler_var_03': {
'eq': Eq(x**2*Derivative(f(x), x, x) - 2*x*Derivative(f(x), x) + 2*f(x), x**4*exp(x)),
'sol': [Eq(f(x), x*(C1 + C2*x + x*exp(x) - 2*exp(x)))]
},
'euler_var_04': {
'eq': x**2*Derivative(f(x), x, x) - 2*x*Derivative(f(x), x) + 2*f(x) - log(x),
'sol': [Eq(f(x), C1*x + C2*x**2 + log(x)/2 + Rational(3, 4))]
},
'euler_var_05': {
'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))]
},
'euler_var_06': {
'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))]
},
}
}
@_add_example_keys
def _get_examples_ode_sol_bernoulli():
# Type: Bernoulli, f'(x) + p(x)*f(x) == q(x)*f(x)**n
return {
'hint': "Bernoulli",
'func': f(x),
'examples':{
'bernoulli_01': {
'eq': Eq(x*f(x).diff(x) + f(x) - f(x)**2, 0),
'sol': [Eq(f(x), 1/(C1*x + 1))],
'XFAIL': ['separable_reduced']
},
'bernoulli_02': {
'eq': f(x).diff(x) - y*f(x),
'sol': [Eq(f(x), C1*exp(x*y))]
},
'bernoulli_03': {
'eq': f(x)*f(x).diff(x) - 1,
'sol': [Eq(f(x), -sqrt(C1 + 2*x)), Eq(f(x), sqrt(C1 + 2*x))]
},
}
}
@_add_example_keys
def _get_examples_ode_sol_riccati():
# Type: Riccati special alpha = -2, a*dy/dx + b*y**2 + c*y/x +d/x**2
return {
'hint': "Riccati_special_minus2",
'func': f(x),
'examples':{
'riccati_01': {
'eq': 2*f(x).diff(x) + f(x)**2 - f(x)/x + 3*x**(-2),
'sol': [Eq(f(x), (-sqrt(3)*tan(C1 + sqrt(3)*log(x)/4) + 3)/(2*x))],
},
},
}
@_add_example_keys
def _get_examples_ode_sol_1st_rational_riccati():
# Type: 1st Order Rational Riccati, dy/dx = a + b*y + c*y**2,
# a, b, c are rational functions of x
return {
'hint': "1st_rational_riccati",
'func': f(x),
'examples':{
# a(x) is a constant
"rational_riccati_01": {
"eq": Eq(f(x).diff(x) + f(x)**2 - 2, 0),
"sol": [Eq(f(x), sqrt(2)*(-C1 - exp(2*sqrt(2)*x))/(C1 - exp(2*sqrt(2)*x)))]
},
# a(x) is a constant
"rational_riccati_02": {
"eq": f(x)**2 + Derivative(f(x), x) + 4*f(x)/x + 2/x**2,
"sol": [Eq(f(x), (-2*C1 - x)/(x*(C1 + x)))]
},
# a(x) is a constant
"rational_riccati_03": {
"eq": 2*x**2*Derivative(f(x), x) - x*(4*f(x) + Derivative(f(x), x) - 4) + (f(x) - 1)*f(x),
"sol": [Eq(f(x), (C1 + 2*x**2)/(C1 + x))]
},
# Constant coefficients
"rational_riccati_04": {
"eq": f(x).diff(x) - 6 - 5*f(x) - f(x)**2,
"sol": [Eq(f(x), (-2*C1 + 3*exp(x))/(C1 - exp(x)))]
},
# One pole of multiplicity 2
"rational_riccati_05": {
"eq": x**2 - (2*x + 1/x)*f(x) + f(x)**2 + Derivative(f(x), x),
"sol": [Eq(f(x), x*(C1 + x**2 + 1)/(C1 + x**2 - 1))]
},
# One pole of multiplicity 2
"rational_riccati_06": {
"eq": x**4*Derivative(f(x), x) + x**2 - x*(2*f(x)**2 + Derivative(f(x), x)) + f(x),
"sol": [Eq(f(x), x*(C1*x - x + 1)/(C1 + x**2 - 1))]
},
# Multiple poles of multiplicity 2
"rational_riccati_07": {
"eq": -f(x)**2 + Derivative(f(x), x) + (15*x**2 - 20*x + 7)/((x - 1)**2*(2*x \
- 1)**2),
"sol": [Eq(f(x), (9*C1*x - 6*C1 - 15*x**5 + 60*x**4 - 94*x**3 + 72*x**2 - \
33*x + 8)/(6*C1*x**2 - 9*C1*x + 3*C1 + 6*x**6 - 29*x**5 + 57*x**4 - \
58*x**3 + 28*x**2 - 3*x - 1))]
},
# Imaginary poles
"rational_riccati_08": {
"eq": Derivative(f(x), x) + (3*x**2 + 1)*f(x)**2/x + (6*x**2 - x + 3)*f(x)/(x*(x \
- 1)) + (3*x**2 - 2*x + 2)/(x*(x - 1)**2),
"sol": [Eq(f(x), (-C1 - x**3 + x**2 - 2*x + 1)/(C1*x - C1 + x**4 - x**3 + x**2 - \
2*x + 1))],
},
# Imaginary coefficients in equation
"rational_riccati_09": {
"eq": Derivative(f(x), x) - 2*I*(f(x)**2 + 1)/x,
"sol": [Eq(f(x), (-I*C1 + I*x**4 + I)/(C1 + x**4 - 1))]
},
# Regression: linsolve returning empty solution
# Large value of m (> 10)
"rational_riccati_10": {
"eq": Eq(Derivative(f(x), x), x*f(x)/(S(3)/2 - 2*x) + (x/2 - S(1)/3)*f(x)**2/\
(2*x/3 - S(1)/2) - S(5)/4 + (281*x**2 - 1260*x + 756)/(16*x**3 - 12*x**2)),
"sol": [Eq(f(x), (40*C1*x**14 + 28*C1*x**13 + 420*C1*x**12 + 2940*C1*x**11 + \
18480*C1*x**10 + 103950*C1*x**9 + 519750*C1*x**8 + 2286900*C1*x**7 + \
8731800*C1*x**6 + 28378350*C1*x**5 + 76403250*C1*x**4 + 163721250*C1*x**3 \
+ 261954000*C1*x**2 + 278326125*C1*x + 147349125*C1 + x*exp(2*x) - 9*exp(2*x) \
)/(x*(24*C1*x**13 + 140*C1*x**12 + 840*C1*x**11 + 4620*C1*x**10 + 23100*C1*x**9 \
+ 103950*C1*x**8 + 415800*C1*x**7 + 1455300*C1*x**6 + 4365900*C1*x**5 + \
10914750*C1*x**4 + 21829500*C1*x**3 + 32744250*C1*x**2 + 32744250*C1*x + \
16372125*C1 - exp(2*x))))]
}
}
}
@_add_example_keys
def _get_examples_ode_sol_1st_linear():
# Type: first order linear form f'(x)+p(x)f(x)=q(x)
return {
'hint': "1st_linear",
'func': f(x),
'examples':{
'linear_01': {
'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))],
},
},
}
@_add_example_keys
def _get_examples_ode_sol_factorable():
""" some hints are marked as xfail for examples because they missed additional algebraic solution
which could be found by Factorable hint. Fact_01 raise exception for
nth_linear_constant_coeff_undetermined_coefficients"""
y = Dummy('y')
a0,a1,a2,a3,a4 = symbols('a0, a1, a2, a3, a4')
return {
'hint': "factorable",
'func': f(x),
'examples':{
'fact_01': {
'eq': f(x) + f(x)*f(x).diff(x),
'sol': [Eq(f(x), 0), Eq(f(x), C1 - x)],
'XFAIL': ['separable', '1st_exact', '1st_linear', 'Bernoulli', '1st_homogeneous_coeff_best',
'1st_homogeneous_coeff_subs_indep_div_dep', '1st_homogeneous_coeff_subs_dep_div_indep',
'lie_group', 'nth_linear_euler_eq_nonhomogeneous_undetermined_coefficients',
'nth_linear_constant_coeff_variation_of_parameters',
'nth_linear_euler_eq_nonhomogeneous_variation_of_parameters',
'nth_linear_constant_coeff_undetermined_coefficients']
},
'fact_02': {
'eq': f(x)*(f(x).diff(x)+f(x)*x+2),
'sol': [Eq(f(x), (C1 - sqrt(2)*sqrt(pi)*erfi(sqrt(2)*x/2))*exp(-x**2/2)), Eq(f(x), 0)],
'XFAIL': ['Bernoulli', '1st_linear', 'lie_group']
},
'fact_03': {
'eq': (f(x).diff(x)+f(x)*x**2)*(f(x).diff(x, 2) + x*f(x)),
'sol': [Eq(f(x), C1*airyai(-x) + C2*airybi(-x)),Eq(f(x), C1*exp(-x**3/3))]
},
'fact_04': {
'eq': (f(x).diff(x)+f(x)*x**2)*(f(x).diff(x, 2) + f(x)),
'sol': [Eq(f(x), C1*exp(-x**3/3)), Eq(f(x), C1*sin(x) + C2*cos(x))]
},
'fact_05': {
'eq': (f(x).diff(x)**2-1)*(f(x).diff(x)**2-4),
'sol': [Eq(f(x), C1 - x), Eq(f(x), C1 + x), Eq(f(x), C1 + 2*x), Eq(f(x), C1 - 2*x)]
},
'fact_06': {
'eq': (f(x).diff(x, 2)-exp(f(x)))*f(x).diff(x),
'sol': [
Eq(f(x), log(-C1/(cos(sqrt(-C1)*(C2 + x)) + 1))),
Eq(f(x), log(-C1/(cos(sqrt(-C1)*(C2 - x)) + 1))),
Eq(f(x), C1)
],
'slow': True,
},
'fact_07': {
'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)]
},
'fact_08': {
'eq': Derivative(f(x), x)**4 - 2*Derivative(f(x), x)**2 + 1,
'sol': [Eq(f(x), C1 - x), Eq(f(x), C1 + x)]
},
'fact_09': {
'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)
]
},
'fact_10': {
'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))
],
'slow': True,
},
'fact_11': {
'eq': (f(x).diff(x, 2)-exp(f(x)))*(f(x).diff(x, 2)+exp(f(x))),
'sol': [
Eq(f(x), log(C1/(cos(C1*sqrt(-1/C1)*(C2 + x)) - 1))),
Eq(f(x), log(C1/(cos(C1*sqrt(-1/C1)*(C2 - x)) - 1))),
Eq(f(x), log(C1/(1 - cos(C1*sqrt(-1/C1)*(C2 + x))))),
Eq(f(x), log(C1/(1 - cos(C1*sqrt(-1/C1)*(C2 - x)))))
],
'dsolve_too_slow': True,
},
#Below examples were added for the issue: https://github.com/sympy/sympy/issues/15889
'fact_12': {
'eq': exp(f(x).diff(x))-f(x)**2,
'sol': [Eq(NonElementaryIntegral(1/log(y**2), (y, f(x))), C1 + x)],
'XFAIL': ['lie_group'] #It shows not implemented error for lie_group.
},
'fact_13': {
'eq': f(x).diff(x)**2 - f(x)**3,
'sol': [Eq(f(x), 4/(C1**2 - 2*C1*x + x**2))],
'XFAIL': ['lie_group'] #It shows not implemented error for lie_group.
},
'fact_14': {
'eq': f(x).diff(x)**2 - f(x),
'sol': [Eq(f(x), C1**2/4 - C1*x/2 + x**2/4)]
},
'fact_15': {
'eq': f(x).diff(x)**2 - f(x)**2,
'sol': [Eq(f(x), C1*exp(x)), Eq(f(x), C1*exp(-x))]
},
'fact_16': {
'eq': f(x).diff(x)**2 - f(x)**3,
'sol': [Eq(f(x), 4/(C1**2 - 2*C1*x + x**2))],
},
# kamke ode 1.1
'fact_17': {
'eq': f(x).diff(x)-(a4*x**4 + a3*x**3 + a2*x**2 + a1*x + a0)**(-1/2),
'sol': [Eq(f(x), C1 + Integral(1/sqrt(a0 + a1*x + a2*x**2 + a3*x**3 + a4*x**4), x))],
'slow': True
},
# This is from issue: https://github.com/sympy/sympy/issues/9446
'fact_18':{
'eq': Eq(f(2 * x), sin(Derivative(f(x)))),
'sol': [Eq(f(x), C1 + Integral(pi - asin(f(2*x)), x)), Eq(f(x), C1 + Integral(asin(f(2*x)), x))],
'checkodesol_XFAIL':True
},
# This is from issue: https://github.com/sympy/sympy/issues/7093
'fact_19': {
'eq': Derivative(f(x), x)**2 - x**3,
'sol': [Eq(f(x), C1 - 2*x**Rational(5,2)/5), Eq(f(x), C1 + 2*x**Rational(5,2)/5)],
},
'fact_20': {
'eq': x*f(x).diff(x, 2) - x*f(x),
'sol': [Eq(f(x), C1*exp(-x) + C2*exp(x))],
},
}
}
@_add_example_keys
def _get_examples_ode_sol_almost_linear():
from sympy.functions.special.error_functions import Ei
A = Symbol('A', positive=True)
f = Function('f')
d = f(x).diff(x)
return {
'hint': "almost_linear",
'func': f(x),
'examples':{
'almost_lin_01': {
'eq': x**2*f(x)**2*d + f(x)**3 + 1,
'sol': [Eq(f(x), (C1*exp(3/x) - 1)**Rational(1, 3)),
Eq(f(x), (-1 - sqrt(3)*I)*(C1*exp(3/x) - 1)**Rational(1, 3)/2),
Eq(f(x), (-1 + sqrt(3)*I)*(C1*exp(3/x) - 1)**Rational(1, 3)/2)],
},
'almost_lin_02': {
'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)))]
},
'almost_lin_03': {
'eq': x*d + x*f(x) + 1,
'sol': [Eq(f(x), (C1 - Ei(x))*exp(-x))]
},
'almost_lin_04': {
'eq': x*exp(f(x))*d + exp(f(x)) + 3*x,
'sol': [Eq(f(x), log(C1/x - x*Rational(3, 2)))],
},
'almost_lin_05': {
'eq': x + A*(x + diff(f(x), x) + f(x)) + diff(f(x), x) + f(x) + 2,
'sol': [Eq(f(x), (C1 + Piecewise(
(x, Eq(A + 1, 0)), ((-A*x + A - x - 1)*exp(x)/(A + 1), True)))*exp(-x))],
},
}
}
@_add_example_keys
def _get_examples_ode_sol_liouville():
n = Symbol('n')
_y = Dummy('y')
return {
'hint': "Liouville",
'func': f(x),
'examples':{
'liouville_01': {
'eq': diff(f(x), x)/x + diff(f(x), x, x)/2 - diff(f(x), x)**2/2,
'sol': [Eq(f(x), log(x/(C1 + C2*x)))],
},
'liouville_02': {
'eq': diff(x*exp(-f(x)), x, x),
'sol': [Eq(f(x), log(x/(C1 + C2*x)))]
},
'liouville_03': {
'eq': ((diff(f(x), x)/x + diff(f(x), x, x)/2 - diff(f(x), x)**2/2)*exp(-f(x))/exp(f(x))).expand(),
'sol': [Eq(f(x), log(x/(C1 + C2*x)))]
},
'liouville_04': {
'eq': diff(f(x), x, x) + 1/f(x)*(diff(f(x), x))**2 + 1/x*diff(f(x), x),
'sol': [Eq(f(x), -sqrt(C1 + C2*log(x))), Eq(f(x), sqrt(C1 + C2*log(x)))],
},
'liouville_05': {
'eq': x*diff(f(x), x, x) + x/f(x)*diff(f(x), x)**2 + x*diff(f(x), x),
'sol': [Eq(f(x), -sqrt(C1 + C2*exp(-x))), Eq(f(x), sqrt(C1 + C2*exp(-x)))],
},
'liouville_06': {
'eq': Eq((x*exp(f(x))).diff(x, x), 0),
'sol': [Eq(f(x), log(C1 + C2/x))],
},
'liouville_07': {
'eq': (diff(f(x), x)/x + diff(f(x), x, x)/2 - diff(f(x), x)**2/2)*exp(-f(x))/exp(f(x)),
'sol': [Eq(f(x), log(x/(C1 + C2*x)))],
},
'liouville_08': {
'eq': x**2*diff(f(x),x) + (n*f(x) + f(x)**2)*diff(f(x),x)**2 + diff(f(x), (x, 2)),
'sol': [Eq(C1 + C2*lowergamma(Rational(1,3), x**3/3) + NonElementaryIntegral(exp(_y**3/3)*exp(_y**2*n/2), (_y, f(x))), 0)],
},
}
}
@_add_example_keys
def _get_examples_ode_sol_nth_algebraic():
M, m, r, t = symbols('M m r t')
phi = Function('phi')
k = Symbol('k')
# This one needs a substitution f' = g.
# 'algeb_12': {
# '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))],
# },
return {
'hint': "nth_algebraic",
'func': f(x),
'examples':{
'algeb_01': {
'eq': f(x) * f(x).diff(x) * f(x).diff(x, x) * (f(x) - 1) * (f(x).diff(x) - x),
'sol': [Eq(f(x), C1 + x**2/2), Eq(f(x), C1 + C2*x)]
},
'algeb_02': {
'eq': f(x) * f(x).diff(x) * f(x).diff(x, x) * (f(x) - 1),
'sol': [Eq(f(x), C1 + C2*x)]
},
'algeb_03': {
'eq': f(x) * f(x).diff(x) * f(x).diff(x, x),
'sol': [Eq(f(x), C1 + C2*x)]
},
'algeb_04': {
'eq': Eq(-M * phi(t).diff(t),
Rational(3, 2) * m * r**2 * phi(t).diff(t) * phi(t).diff(t,t)),
'sol': [Eq(phi(t), C1), Eq(phi(t), C1 + C2*t - M*t**2/(3*m*r**2))],
'func': phi(t)
},
'algeb_05': {
'eq': (1 - sin(f(x))) * f(x).diff(x),
'sol': [Eq(f(x), C1)],
'XFAIL': ['separable'] #It raised exception.
},
'algeb_06': {
'eq': (diff(f(x)) - x)*(diff(f(x)) + x),
'sol': [Eq(f(x), C1 - x**2/2), Eq(f(x), C1 + x**2/2)]
},
'algeb_07': {
'eq': Eq(Derivative(f(x), x), Derivative(g(x), x)),
'sol': [Eq(f(x), C1 + g(x))],
},
'algeb_08': {
'eq': f(x).diff(x) - C1, #this example is from issue 15999
'sol': [Eq(f(x), C1*x + C2)],
},
'algeb_09': {
'eq': f(x)*f(x).diff(x),
'sol': [Eq(f(x), C1)],
},
'algeb_10': {
'eq': (diff(f(x)) - x)*(diff(f(x)) + x),
'sol': [Eq(f(x), C1 - x**2/2), Eq(f(x), C1 + x**2/2)],
},
'algeb_11': {
'eq': f(x) + f(x)*f(x).diff(x),
'sol': [Eq(f(x), 0), Eq(f(x), C1 - x)],
'XFAIL': ['separable', '1st_exact', '1st_linear', 'Bernoulli', '1st_homogeneous_coeff_best',
'1st_homogeneous_coeff_subs_indep_div_dep', '1st_homogeneous_coeff_subs_dep_div_indep',
'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_linear_constant_coeff_undetermined_coefficients raises exception rest all of them misses a solution.
},
'algeb_12': {
'eq': Derivative(x*f(x), x, x, x),
'sol': [Eq(f(x), (C1 + C2*x + C3*x**2) / x)],
'XFAIL': ['nth_algebraic'] # It passes only when prep=False is set in dsolve.
},
'algeb_13': {
'eq': Eq(Derivative(x*Derivative(f(x), x), x)/x, exp(x)),
'sol': [Eq(f(x), C1 + C2*log(x) + exp(x) - Ei(x))],
'XFAIL': ['nth_algebraic'] # It passes only when prep=False is set in dsolve.
},
# These are simple tests from the old ode module example 14-18
'algeb_14': {
'eq': Eq(f(x).diff(x), 0),
'sol': [Eq(f(x), C1)],
},
'algeb_15': {
'eq': Eq(3*f(x).diff(x) - 5, 0),
'sol': [Eq(f(x), C1 + x*Rational(5, 3))],
},
'algeb_16': {
'eq': Eq(3*f(x).diff(x), 5),
'sol': [Eq(f(x), C1 + x*Rational(5, 3))],
},
# Type: 2nd order, constant coefficients (two complex roots)
'algeb_17': {
'eq': Eq(3*f(x).diff(x) - 1, 0),
'sol': [Eq(f(x), C1 + x/3)],
},
'algeb_18': {
'eq': Eq(x*f(x).diff(x) - 1, 0),
'sol': [Eq(f(x), C1 + log(x))],
},
# https://github.com/sympy/sympy/issues/6989
'algeb_19': {
'eq': f(x).diff(x) - x*exp(-k*x),
'sol': [Eq(f(x), C1 + Piecewise(((-k*x - 1)*exp(-k*x)/k**2, Ne(k**2, 0)),(x**2/2, True)))],
},
'algeb_20': {
'eq': -f(x).diff(x) + x*exp(-k*x),
'sol': [Eq(f(x), C1 + Piecewise(((-k*x - 1)*exp(-k*x)/k**2, Ne(k**2, 0)),(x**2/2, True)))],
},
# https://github.com/sympy/sympy/issues/10867
'algeb_21': {
'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)],
'func': g(x),
},
# https://github.com/sympy/sympy/issues/13691
'algeb_22': {
'eq': f(x).diff(x) - C1*g(x).diff(x),
'sol': [Eq(f(x), C2 + C1*g(x))],
'func': f(x),
},
# https://github.com/sympy/sympy/issues/4838
'algeb_23': {
'eq': f(x).diff(x) - 3*C1 - 3*x**2,
'sol': [Eq(f(x), C2 + 3*C1*x + x**3)],
},
}
}
@_add_example_keys
def _get_examples_ode_sol_nth_order_reducible():
return {
'hint': "nth_order_reducible",
'func': f(x),
'examples':{
'reducible_01': {
'eq': 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))],
'slow': True,
},
'reducible_02': {
'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))],
'slow': True,
},
'reducible_03': {
'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))],
'slow': True,
},
'reducible_04': {
'eq': f(x).diff(x, 2) + 2*f(x).diff(x),
'sol': [Eq(f(x), C1 + C2*exp(-2*x))],
},
'reducible_05': {
'eq': 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))],
'slow': True,
},
'reducible_06': {
'eq': 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(-2*x) + C3*exp(x) + C4*exp(2*x))],
'slow': True,
},
'reducible_07': {
'eq': 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))],
'slow': True,
},
'reducible_08': {
'eq': f(x).diff(x, 4) - 2*f(x).diff(x, 2),
'sol': [Eq(f(x), C1 + C2*x + C3*exp(-sqrt(2)*x) + C4*exp(sqrt(2)*x))],
'slow': True,
},
'reducible_09': {
'eq': f(x).diff(x, 4) + 4*f(x).diff(x, 2),
'sol': [Eq(f(x), C1 + C2*x + C3*sin(2*x) + C4*cos(2*x))],
'slow': True,
},
'reducible_10': {
'eq': f(x).diff(x, 5) + 2*f(x).diff(x, 3) + f(x).diff(x),
'sol': [Eq(f(x), C1 + C2*x*sin(x) + C2*cos(x) - C3*x*cos(x) + C3*sin(x) + C4*sin(x) + C5*cos(x))],
'slow': True,
},
'reducible_11': {
'eq': f(x).diff(x, 2) - f(x).diff(x)**3,
'sol': [Eq(f(x), C1 - sqrt(2)*sqrt(-1/(C2 + x))*(C2 + x)),
Eq(f(x), C1 + sqrt(2)*sqrt(-1/(C2 + x))*(C2 + x))],
'slow': True,
},
# Needs to be a way to know how to combine derivatives in the expression
'reducible_12': {
'eq': Derivative(x*f(x), x, x, x) + Derivative(f(x), x, x, x),
'sol': [Eq(f(x), C1 + C3/Mul(2, (x**2 + 2*x + 1), evaluate=False) +
x*(C2 + C3/Mul(2, (x**2 + 2*x + 1), evaluate=False)))], # 2-arg Mul!
'slow': True,
},
}
}
@_add_example_keys
def _get_examples_ode_sol_nth_linear_undetermined_coefficients():
# examples 3-27 below are from Ordinary Differential Equations,
# Tenenbaum and Pollard, pg. 231
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
t = symbols("t")
u = symbols("u",cls=Function)
R, L, C, E_0, alpha = symbols("R L C E_0 alpha",positive=True)
omega = Symbol('omega')
return {
'hint': "nth_linear_constant_coeff_undetermined_coefficients",
'func': f(x),
'examples':{
'undet_01': {
'eq': c - x*g,
'sol': [Eq(f(x), C3*exp(x/3) - x + (C1 + x*(C2 - x**2/24 - 3*x/32))*exp(-x) - 1)],
'slow': True,
},
'undet_02': {
'eq': c - g,
'sol': [Eq(f(x), C3*exp(x/3) - x + (C1 + x*(C2 - x/8))*exp(-x) - 1)],
'slow': True,
},
'undet_03': {
'eq': f2 + 3*f(x).diff(x) + 2*f(x) - 4,
'sol': [Eq(f(x), C1*exp(-2*x) + C2*exp(-x) + 2)],
'slow': True,
},
'undet_04': {
'eq': f2 + 3*f(x).diff(x) + 2*f(x) - 12*exp(x),
'sol': [Eq(f(x), C1*exp(-2*x) + C2*exp(-x) + 2*exp(x))],
'slow': True,
},
'undet_05': {
'eq': f2 + 3*f(x).diff(x) + 2*f(x) - exp(I*x),
'sol': [Eq(f(x), (S(3)/10 + I/10)*(C1*exp(-2*x) + C2*exp(-x) - I*exp(I*x)))],
'slow': True,
},
'undet_06': {
'eq': f2 + 3*f(x).diff(x) + 2*f(x) - sin(x),
'sol': [Eq(f(x), C1*exp(-2*x) + C2*exp(-x) + sin(x)/10 - 3*cos(x)/10)],
'slow': True,
},
'undet_07': {
'eq': f2 + 3*f(x).diff(x) + 2*f(x) - cos(x),
'sol': [Eq(f(x), C1*exp(-2*x) + C2*exp(-x) + 3*sin(x)/10 + cos(x)/10)],
'slow': True,
},
'undet_08': {
'eq': f2 + 3*f(x).diff(x) + 2*f(x) - (8 + 6*exp(x) + 2*sin(x)),
'sol': [Eq(f(x), C1*exp(-2*x) + C2*exp(-x) + exp(x) + sin(x)/5 - 3*cos(x)/5 + 4)],
'slow': True,
},
'undet_09': {
'eq': f2 + f(x).diff(x) + f(x) - x**2,
'sol': [Eq(f(x), -2*x + x**2 + (C1*sin(x*sqrt(3)/2) + C2*cos(x*sqrt(3)/2))*exp(-x/2))],
'slow': True,
},
'undet_10': {
'eq': f2 - 2*f(x).diff(x) - 8*f(x) - 9*x*exp(x) - 10*exp(-x),
'sol': [Eq(f(x), -x*exp(x) - 2*exp(-x) + C1*exp(-2*x) + C2*exp(4*x))],
'slow': True,
},
'undet_11': {
'eq': f2 - 3*f(x).diff(x) - 2*exp(2*x)*sin(x),
'sol': [Eq(f(x), C1 + C2*exp(3*x) - 3*exp(2*x)*sin(x)/5 - exp(2*x)*cos(x)/5)],
'slow': True,
},
'undet_12': {
'eq': f(x).diff(x, 4) - 2*f2 + f(x) - x + sin(x),
'sol': [Eq(f(x), x - sin(x)/4 + (C1 + C2*x)*exp(-x) + (C3 + C4*x)*exp(x))],
'slow': True,
},
'undet_13': {
'eq': f2 + f(x).diff(x) - x**2 - 2*x,
'sol': [Eq(f(x), C1 + x**3/3 + C2*exp(-x))],
'slow': True,
},
'undet_14': {
'eq': f2 + f(x).diff(x) - x - sin(2*x),
'sol': [Eq(f(x), C1 - x - sin(2*x)/5 - cos(2*x)/10 + x**2/2 + C2*exp(-x))],
'slow': True,
},
'undet_15': {
'eq': f2 + f(x) - 4*x*sin(x),
'sol': [Eq(f(x), (C1 - x**2)*cos(x) + (C2 + x)*sin(x))],
'slow': True,
},
'undet_16': {
'eq': f2 + 4*f(x) - x*sin(2*x),
'sol': [Eq(f(x), (C1 - x**2/8)*cos(2*x) + (C2 + x/16)*sin(2*x))],
'slow': True,
},
'undet_17': {
'eq': f2 + 2*f(x).diff(x) + f(x) - x**2*exp(-x),
'sol': [Eq(f(x), (C1 + x*(C2 + x**3/12))*exp(-x))],
'slow': True,
},
'undet_18': {
'eq': f(x).diff(x, 3) + 3*f2 + 3*f(x).diff(x) + f(x) - 2*exp(-x) + \
x**2*exp(-x),
'sol': [Eq(f(x), (C1 + x*(C2 + x*(C3 - x**3/60 + x/3)))*exp(-x))],
'slow': True,
},
'undet_19': {
'eq': f2 + 3*f(x).diff(x) + 2*f(x) - exp(-2*x) - x**2,
'sol': [Eq(f(x), C2*exp(-x) + x**2/2 - x*Rational(3,2) + (C1 - x)*exp(-2*x) + Rational(7,4))],
'slow': True,
},
'undet_20': {
'eq': f2 - 3*f(x).diff(x) + 2*f(x) - x*exp(-x),
'sol': [Eq(f(x), C1*exp(x) + C2*exp(2*x) + (6*x + 5)*exp(-x)/36)],
'slow': True,
},
'undet_21': {
'eq': f2 + f(x).diff(x) - 6*f(x) - x - exp(2*x),
'sol': [Eq(f(x), Rational(-1, 36) - x/6 + C2*exp(-3*x) + (C1 + x/5)*exp(2*x))],
'slow': True,
},
'undet_22': {
'eq': f2 + f(x) - sin(x) - exp(-x),
'sol': [Eq(f(x), C2*sin(x) + (C1 - x/2)*cos(x) + exp(-x)/2)],
'slow': True,
},
'undet_23': {
'eq': f(x).diff(x, 3) - 3*f2 + 3*f(x).diff(x) - f(x) - exp(x),
'sol': [Eq(f(x), (C1 + x*(C2 + x*(C3 + x/6)))*exp(x))],
'slow': True,
},
'undet_24': {
'eq': f2 + f(x) - S.Half - cos(2*x)/2,
'sol': [Eq(f(x), S.Half - cos(2*x)/6 + C1*sin(x) + C2*cos(x))],
'slow': True,
},
'undet_25': {
'eq': f(x).diff(x, 3) - f(x).diff(x) - exp(2*x)*(S.Half - cos(2*x)/2),
'sol': [Eq(f(x), C1 + C2*exp(-x) + C3*exp(x) + (-21*sin(2*x) + 27*cos(2*x) + 130)*exp(2*x)/1560)],
'slow': True,
},
#Note: 'undet_26' is referred in 'undet_37'
'undet_26': {
'eq': (f(x).diff(x, 5) + 2*f(x).diff(x, 3) + f(x).diff(x) - 2*x -
sin(x) - cos(x)),
'sol': [Eq(f(x), C1 + x**2 + (C2 + x*(C3 - x/8))*sin(x) + (C4 + x*(C5 + x/8))*cos(x))],
'slow': True,
},
'undet_27': {
'eq': f2 + f(x) - cos(x)/2 + cos(3*x)/2,
'sol': [Eq(f(x), cos(3*x)/16 + C2*cos(x) + (C1 + x/4)*sin(x))],
'slow': True,
},
'undet_28': {
'eq': f(x).diff(x) - 1,
'sol': [Eq(f(x), C1 + x)],
'slow': True,
},
# https://github.com/sympy/sympy/issues/19358
'undet_29': {
'eq': f2 + f(x).diff(x) + exp(x-C1),
'sol': [Eq(f(x), C2 + C3*exp(-x) - exp(-C1 + x)/2)],
'slow': True,
},
# https://github.com/sympy/sympy/issues/18408
'undet_30': {
'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)],
},
'undet_31': {
'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)],
},
'undet_32': {
'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))],
},
# https://github.com/sympy/sympy/issues/5096
'undet_33': {
'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)],
},
'undet_34': {
'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)],
},
'undet_35': {
'eq': f(x).diff(x, 2) - f(x) - exp(x - 1),
'sol': [Eq(f(x), C2*exp(-x) + (C1 + x*exp(-1)/2)*exp(x))],
},
'undet_36': {
'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)],
},
# Equivalent to example_name 'undet_26'.
# This previously failed because the algorithm for undetermined coefficients
# didn't know to multiply exp(I*x) by sufficient x because it is linearly
# dependent on sin(x) and cos(x).
'undet_37': {
'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*(I*exp(I*x)/8 + 1) + (C2 + C3*x)*sin(x) + (C4 + C5*x)*cos(x))],
},
# https://github.com/sympy/sympy/issues/12623
'undet_38': {
'eq': Eq( u(t).diff(t,t) + R /L*u(t).diff(t) + 1/(L*C)*u(t), alpha),
'sol': [Eq(u(t), C*L*alpha + C2*exp(-t*(R + sqrt(C*R**2 - 4*L)/sqrt(C))/(2*L))
+ C1*exp(t*(-R + sqrt(C*R**2 - 4*L)/sqrt(C))/(2*L)))],
'func': u(t)
},
'undet_39': {
'eq': Eq( L*C*u(t).diff(t,t) + R*C*u(t).diff(t) + u(t), E_0*exp(I*omega*t) ),
'sol': [Eq(u(t), C2*exp(-t*(R + sqrt(C*R**2 - 4*L)/sqrt(C))/(2*L))
+ C1*exp(t*(-R + sqrt(C*R**2 - 4*L)/sqrt(C))/(2*L))
- E_0*exp(I*omega*t)/(C*L*omega**2 - I*C*R*omega - 1))],
'func': u(t),
},
# https://github.com/sympy/sympy/issues/6879
'undet_40': {
'eq': Eq(Derivative(f(x), x, 2) - 2*Derivative(f(x), x) + f(x), sin(x)),
'sol': [Eq(f(x), (C1 + C2*x)*exp(x) + cos(x)/2)],
},
}
}
@_add_example_keys
def _get_examples_ode_sol_separable():
# test_separable1-5 are from Ordinary Differential Equations, Tenenbaum and
# Pollard, pg. 55
t,a = symbols('a,t')
m = 96
g = 9.8
k = .2
f1 = g * m
v = Function('v')
return {
'hint': "separable",
'func': f(x),
'examples':{
'separable_01': {
'eq': f(x).diff(x) - f(x),
'sol': [Eq(f(x), C1*exp(x))],
},
'separable_02': {
'eq': x*f(x).diff(x) - f(x),
'sol': [Eq(f(x), C1*x)],
},
'separable_03': {
'eq': f(x).diff(x) + sin(x),
'sol': [Eq(f(x), C1 + cos(x))],
},
'separable_04': {
'eq': f(x)**2 + 1 - (x**2 + 1)*f(x).diff(x),
'sol': [Eq(f(x), tan(C1 + atan(x)))],
},
'separable_05': {
'eq': f(x).diff(x)/tan(x) - f(x) - 2,
'sol': [Eq(f(x), C1/cos(x) - 2)],
},
'separable_06': {
'eq': f(x).diff(x) * (1 - sin(f(x))) - 1,
'sol': [Eq(-x + f(x) + cos(f(x)), C1)],
},
'separable_07': {
'eq': f(x)*x**2*f(x).diff(x) - f(x)**3 - 2*x**2*f(x).diff(x),
'sol': [Eq(f(x), (-x - sqrt(x*(4*C1*x + x - 4)))/(C1*x - 1)/2),
Eq(f(x), (-x + sqrt(x*(4*C1*x + x - 4)))/(C1*x - 1)/2)],
'slow': True,
},
'separable_08': {
'eq': f(x)**2 - 1 - (2*f(x) + x*f(x))*f(x).diff(x),
'sol': [Eq(f(x), -sqrt(C1*x**2 + 4*C1*x + 4*C1 + 1)),
Eq(f(x), sqrt(C1*x**2 + 4*C1*x + 4*C1 + 1))],
'slow': True,
},
'separable_09': {
'eq': x*log(x)*f(x).diff(x) + sqrt(1 + f(x)**2),
'sol': [Eq(f(x), sinh(C1 - log(log(x))))], #One more solution is f(x)=I
'slow': True,
'checkodesol_XFAIL': True,
},
'separable_10': {
'eq': exp(x + 1)*tan(f(x)) + cos(f(x))*f(x).diff(x),
'sol': [Eq(E*exp(x) + log(cos(f(x)) - 1)/2 - log(cos(f(x)) + 1)/2 + cos(f(x)), C1)],
'slow': True,
},
'separable_11': {
'eq': (x*cos(f(x)) + x**2*sin(f(x))*f(x).diff(x) - a**2*sin(f(x))*f(x).diff(x)),
'sol': [
Eq(f(x), -acos(C1*sqrt(-a**2 + x**2)) + 2*pi),
Eq(f(x), acos(C1*sqrt(-a**2 + x**2)))
],
'slow': True,
},
'separable_12': {
'eq': f(x).diff(x) - f(x)*tan(x),
'sol': [Eq(f(x), C1/cos(x))],
},
'separable_13': {
'eq': (x - 1)*cos(f(x))*f(x).diff(x) - 2*x*sin(f(x)),
'sol': [
Eq(f(x), pi - asin(C1*(x**2 - 2*x + 1)*exp(2*x))),
Eq(f(x), asin(C1*(x**2 - 2*x + 1)*exp(2*x)))
],
},
'separable_14': {
'eq': f(x).diff(x) - f(x)*log(f(x))/tan(x),
'sol': [Eq(f(x), exp(C1*sin(x)))],
},
'separable_15': {
'eq': x*f(x).diff(x) + (1 + f(x)**2)*atan(f(x)),
'sol': [Eq(f(x), tan(C1/x))], #Two more solutions are f(x)=0 and f(x)=I
'slow': True,
'checkodesol_XFAIL': True,
},
'separable_16': {
'eq': f(x).diff(x) + x*(f(x) + 1),
'sol': [Eq(f(x), -1 + C1*exp(-x**2/2))],
},
'separable_17': {
'eq': exp(f(x)**2)*(x**2 + 2*x + 1) + (x*f(x) + f(x))*f(x).diff(x),
'sol': [
Eq(f(x), -sqrt(log(1/(C1 + x**2 + 2*x)))),
Eq(f(x), sqrt(log(1/(C1 + x**2 + 2*x))))
],
},
'separable_18': {
'eq': f(x).diff(x) + f(x),
'sol': [Eq(f(x), C1*exp(-x))],
},
'separable_19': {
'eq': sin(x)*cos(2*f(x)) + cos(x)*sin(2*f(x))*f(x).diff(x),
'sol': [Eq(f(x), pi - acos(C1/cos(x)**2)/2), Eq(f(x), acos(C1/cos(x)**2)/2)],
},
'separable_20': {
'eq': (1 - x)*f(x).diff(x) - x*(f(x) + 1),
'sol': [Eq(f(x), (C1*exp(-x) - x + 1)/(x - 1))],
},
'separable_21': {
'eq': f(x)*diff(f(x), x) + x - 3*x*f(x)**2,
'sol': [Eq(f(x), -sqrt(3)*sqrt(C1*exp(3*x**2) + 1)/3),
Eq(f(x), sqrt(3)*sqrt(C1*exp(3*x**2) + 1)/3)],
},
'separable_22': {
'eq': f(x).diff(x) - exp(x + f(x)),
'sol': [Eq(f(x), log(-1/(C1 + exp(x))))],
'XFAIL': ['lie_group'] #It shows 'NoneType' object is not subscriptable for lie_group.
},
# https://github.com/sympy/sympy/issues/7081
'separable_23': {
'eq': x*(f(x).diff(x)) + 1 - f(x)**2,
'sol': [Eq(f(x), (-C1 - x**2)/(-C1 + x**2))],
},
# https://github.com/sympy/sympy/issues/10379
'separable_24': {
'eq': f(t).diff(t)-(1-51.05*y*f(t)),
'sol': [Eq(f(t), (0.019588638589618023*exp(y*(C1 - 51.049999999999997*t)) + 0.019588638589618023)/y)],
'func': f(t),
},
# https://github.com/sympy/sympy/issues/15999
'separable_25': {
'eq': f(x).diff(x) - C1*f(x),
'sol': [Eq(f(x), C2*exp(C1*x))],
},
'separable_26': {
'eq': f1 - k * (v(t) ** 2) - m * Derivative(v(t)),
'sol': [Eq(v(t), -68.585712797928991/tanh(C1 - 0.14288690166235204*t))],
'func': v(t),
'checkodesol_XFAIL': True,
},
#https://github.com/sympy/sympy/issues/22155
'separable_27': {
'eq': f(x).diff(x) - exp(f(x) - x),
'sol': [Eq(f(x), log(-exp(x)/(C1*exp(x) - 1)))],
}
}
}
@_add_example_keys
def _get_examples_ode_sol_1st_exact():
# Type: Exact differential equation, p(x,f) + q(x,f)*f' == 0,
# where dp/df == dq/dx
'''
Example 7 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.
'''
return {
'hint': "1st_exact",
'func': f(x),
'examples':{
'1st_exact_01': {
'eq': sin(x)*cos(f(x)) + cos(x)*sin(f(x))*f(x).diff(x),
'sol': [Eq(f(x), -acos(C1/cos(x)) + 2*pi), Eq(f(x), acos(C1/cos(x)))],
'slow': True,
},
'1st_exact_02': {
'eq': (2*x*f(x) + 1)/f(x) + (f(x) - x)/f(x)**2*f(x).diff(x),
'sol': [Eq(f(x), exp(C1 - x**2 + LambertW(-x*exp(-C1 + x**2))))],
'XFAIL': ['lie_group'], #It shows dsolve raises an exception: List index out of range for lie_group
'slow': True,
'checkodesol_XFAIL':True
},
'1st_exact_03': {
'eq': 2*x + f(x)*cos(x) + (2*f(x) + sin(x) - sin(f(x)))*f(x).diff(x),
'sol': [Eq(f(x)*sin(x) + cos(f(x)) + x**2 + f(x)**2, C1)],
'XFAIL': ['lie_group'], #It goes into infinite loop for lie_group.
'slow': True,
},
'1st_exact_04': {
'eq': cos(f(x)) - (x*sin(f(x)) - f(x)**2)*f(x).diff(x),
'sol': [Eq(x*cos(f(x)) + f(x)**3/3, C1)],
'slow': True,
},
'1st_exact_05': {
'eq': 2*x*f(x) + (x**2 + f(x)**2)*f(x).diff(x),
'sol': [Eq(x**2*f(x) + f(x)**3/3, C1)],
'slow': True,
'simplify_flag':False
},
# This was from issue: https://github.com/sympy/sympy/issues/11290
'1st_exact_06': {
'eq': cos(f(x)) - (x*sin(f(x)) - f(x)**2)*f(x).diff(x),
'sol': [Eq(x*cos(f(x)) + f(x)**3/3, C1)],
'simplify_flag':False
},
'1st_exact_07': {
'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': [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))))],
'slow': True,
'dsolve_too_slow':True
},
# Type: a(x)f'(x)+b(x)*f(x)+c(x)=0
'1st_exact_08': {
'eq': Eq(x**2*f(x).diff(x) + 3*x*f(x) - sin(x)/x, 0),
'sol': [Eq(f(x), (C1 - cos(x))/x**3)],
},
# these examples are from test_exact_enhancement
'1st_exact_09': {
'eq': f(x)/x**2 + ((f(x)*x - 1)/x)*f(x).diff(x),
'sol': [Eq(f(x), (i*sqrt(C1*x**2 + 1) + 1)/x) for i in (-1, 1)],
},
'1st_exact_10': {
'eq': (x*f(x) - 1) + f(x).diff(x)*(x**2 - x*f(x)),
'sol': [Eq(f(x), x - sqrt(C1 + x**2 - 2*log(x))), Eq(f(x), x + sqrt(C1 + x**2 - 2*log(x)))],
},
'1st_exact_11': {
'eq': (x + 2)*sin(f(x)) + f(x).diff(x)*x*cos(f(x)),
'sol': [Eq(f(x), -asin(C1*exp(-x)/x**2) + pi), Eq(f(x), asin(C1*exp(-x)/x**2))],
},
}
}
@_add_example_keys
def _get_examples_ode_sol_nth_linear_var_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
return {
'hint': "nth_linear_constant_coeff_variation_of_parameters",
'func': f(x),
'examples':{
'var_of_parameters_01': {
'eq': c - x*g,
'sol': [Eq(f(x), C3*exp(x/3) - x + (C1 + x*(C2 - x**2/24 - 3*x/32))*exp(-x) - 1)],
'slow': True,
},
'var_of_parameters_02': {
'eq': c - g,
'sol': [Eq(f(x), C3*exp(x/3) - x + (C1 + x*(C2 - x/8))*exp(-x) - 1)],
'slow': True,
},
'var_of_parameters_03': {
'eq': f(x).diff(x) - 1,
'sol': [Eq(f(x), C1 + x)],
'slow': True,
},
'var_of_parameters_04': {
'eq': f2 + 3*f(x).diff(x) + 2*f(x) - 4,
'sol': [Eq(f(x), C1*exp(-2*x) + C2*exp(-x) + 2)],
'slow': True,
},
'var_of_parameters_05': {
'eq': f2 + 3*f(x).diff(x) + 2*f(x) - 12*exp(x),
'sol': [Eq(f(x), C1*exp(-2*x) + C2*exp(-x) + 2*exp(x))],
'slow': True,
},
'var_of_parameters_06': {
'eq': f2 - 2*f(x).diff(x) - 8*f(x) - 9*x*exp(x) - 10*exp(-x),
'sol': [Eq(f(x), -x*exp(x) - 2*exp(-x) + C1*exp(-2*x) + C2*exp(4*x))],
'slow': True,
},
'var_of_parameters_07': {
'eq': f2 + 2*f(x).diff(x) + f(x) - x**2*exp(-x),
'sol': [Eq(f(x), (C1 + x*(C2 + x**3/12))*exp(-x))],
'slow': True,
},
'var_of_parameters_08': {
'eq': f2 - 3*f(x).diff(x) + 2*f(x) - x*exp(-x),
'sol': [Eq(f(x), C1*exp(x) + C2*exp(2*x) + (6*x + 5)*exp(-x)/36)],
'slow': True,
},
'var_of_parameters_09': {
'eq': f(x).diff(x, 3) - 3*f2 + 3*f(x).diff(x) - f(x) - exp(x),
'sol': [Eq(f(x), (C1 + x*(C2 + x*(C3 + x/6)))*exp(x))],
'slow': True,
},
'var_of_parameters_10': {
'eq': f2 + 2*f(x).diff(x) + f(x) - exp(-x)/x,
'sol': [Eq(f(x), (C1 + x*(C2 + log(x)))*exp(-x))],
'slow': True,
},
'var_of_parameters_11': {
'eq': f2 + f(x) - 1/sin(x)*1/cos(x),
'sol': [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))],
'slow': True,
},
'var_of_parameters_12': {
'eq': f(x).diff(x, 4) - 1/x,
'sol': [Eq(f(x), C1 + C2*x + C3*x**2 + x**3*(C4 + log(x)/6))],
'slow': True,
},
# These were from issue: https://github.com/sympy/sympy/issues/15996
'var_of_parameters_13': {
'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*(C3 - x/8 + 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 + x*(C5 + I*x/8 + 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))],
},
'var_of_parameters_14': {
'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 + x*(C3 - x/8) + 5*exp(2*I*x)/16)*sin(x) + (C4 + x*(C5 + I*x/8) + 5*I*exp(2*I*x)/16)*cos(x) - I*exp(I*x))],
},
# https://github.com/sympy/sympy/issues/14395
'var_of_parameters_15': {
'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))],
'slow': True,
},
}
}
@_add_example_keys
def _get_examples_ode_sol_2nd_linear_bessel():
return {
'hint': "2nd_linear_bessel",
'func': f(x),
'examples':{
'2nd_lin_bessel_01': {
'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))],
},
'2nd_lin_bessel_02': {
'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))],
},
'2nd_lin_bessel_03': {
'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))],
},
'2nd_lin_bessel_04': {
'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))],
},
'2nd_lin_bessel_05': {
'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))],
},
'2nd_lin_bessel_06': {
'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))],
},
'2nd_lin_bessel_07': {
'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))],
},
'2nd_lin_bessel_08': {
'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))))],
},
'2nd_lin_bessel_09': {
'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)))],
},
'2nd_lin_bessel_10': {
'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)))],
},
# https://github.com/sympy/sympy/issues/4414
'2nd_lin_bessel_11': {
'eq': f(x).diff(x, x) + 2/x*f(x).diff(x) + f(x),
'sol': [Eq(f(x), (C1*besselj(S(1)/2, x) + C2*bessely(S(1)/2, x))/sqrt(x))],
},
}
}
@_add_example_keys
def _get_examples_ode_sol_2nd_2F1_hypergeometric():
return {
'hint': "2nd_hypergeometric",
'func': f(x),
'examples':{
'2nd_2F1_hyper_01': {
'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))],
},
'2nd_2F1_hyper_02': {
'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))],
},
'2nd_2F1_hyper_03': {
'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))],
},
'2nd_2F1_hyper_04': {
'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))],
'checkodesol_XFAIL':True,
},
}
}
@_add_example_keys
def _get_examples_ode_sol_2nd_nonlinear_autonomous_conserved():
return {
'hint': "2nd_nonlinear_autonomous_conserved",
'func': f(x),
'examples': {
'2nd_nonlinear_autonomous_conserved_01': {
'eq': f(x).diff(x, 2) + exp(f(x)) + log(f(x)),
'sol': [
Eq(Integral(1/sqrt(C1 - 2*_u*log(_u) + 2*_u - 2*exp(_u)), (_u, f(x))), C2 + x),
Eq(Integral(1/sqrt(C1 - 2*_u*log(_u) + 2*_u - 2*exp(_u)), (_u, f(x))), C2 - x)
],
'simplify_flag': False,
},
'2nd_nonlinear_autonomous_conserved_02': {
'eq': f(x).diff(x, 2) + cbrt(f(x)) + 1/f(x),
'sol': [
Eq(sqrt(2)*Integral(1/sqrt(2*C1 - 3*_u**Rational(4, 3) - 4*log(_u)), (_u, f(x))), C2 + x),
Eq(sqrt(2)*Integral(1/sqrt(2*C1 - 3*_u**Rational(4, 3) - 4*log(_u)), (_u, f(x))), C2 - x)
],
'simplify_flag': False,
},
'2nd_nonlinear_autonomous_conserved_03': {
'eq': f(x).diff(x, 2) + sin(f(x)),
'sol': [
Eq(Integral(1/sqrt(C1 + 2*cos(_u)), (_u, f(x))), C2 + x),
Eq(Integral(1/sqrt(C1 + 2*cos(_u)), (_u, f(x))), C2 - x)
],
'simplify_flag': False,
},
'2nd_nonlinear_autonomous_conserved_04': {
'eq': f(x).diff(x, 2) + cosh(f(x)),
'sol': [
Eq(Integral(1/sqrt(C1 - 2*sinh(_u)), (_u, f(x))), C2 + x),
Eq(Integral(1/sqrt(C1 - 2*sinh(_u)), (_u, f(x))), C2 - x)
],
'simplify_flag': False,
},
'2nd_nonlinear_autonomous_conserved_05': {
'eq': f(x).diff(x, 2) + asin(f(x)),
'sol': [
Eq(Integral(1/sqrt(C1 - 2*_u*asin(_u) - 2*sqrt(1 - _u**2)), (_u, f(x))), C2 + x),
Eq(Integral(1/sqrt(C1 - 2*_u*asin(_u) - 2*sqrt(1 - _u**2)), (_u, f(x))), C2 - x)
],
'simplify_flag': False,
'XFAIL': ['2nd_nonlinear_autonomous_conserved_Integral']
}
}
}
@_add_example_keys
def _get_examples_ode_sol_separable_reduced():
df = f(x).diff(x)
return {
'hint': "separable_reduced",
'func': f(x),
'examples':{
'separable_reduced_01': {
'eq': x* df + f(x)* (1 / (x**2*f(x) - 1)),
'sol': [Eq(log(x**2*f(x))/3 + log(x**2*f(x) - Rational(3, 2))/6, C1 + log(x))],
'simplify_flag': False,
'XFAIL': ['lie_group'], #It hangs.
},
#Note: 'separable_reduced_02' is referred in 'separable_reduced_11'
'separable_reduced_02': {
'eq': f(x).diff(x) + (f(x) / (x**4*f(x) - x)),
'sol': [Eq(log(x**3*f(x))/4 + log(x**3*f(x) - Rational(4,3))/12, C1 + log(x))],
'simplify_flag': False,
'checkodesol_XFAIL':True, #It hangs for this.
},
'separable_reduced_03': {
'eq': x*df + f(x)*(x**2*f(x)),
'sol': [Eq(log(x**2*f(x))/2 - log(x**2*f(x) - 2)/2, C1 + log(x))],
'simplify_flag': False,
},
'separable_reduced_04': {
'eq': Eq(f(x).diff(x) + f(x)/x * (1 + (x**(S(2)/3)*f(x))**2), 0),
'sol': [Eq(-3*log(x**(S(2)/3)*f(x)) + 3*log(3*x**(S(4)/3)*f(x)**2 + 1)/2, C1 + log(x))],
'simplify_flag': False,
},
'separable_reduced_05': {
'eq': Eq(f(x).diff(x) + f(x)/x * (1 + (x*f(x))**2), 0),
'sol': [Eq(f(x), -sqrt(2)*sqrt(1/(C1 + log(x)))/(2*x)),\
Eq(f(x), sqrt(2)*sqrt(1/(C1 + log(x)))/(2*x))],
},
'separable_reduced_06': {
'eq': Eq(f(x).diff(x) + (x**4*f(x)**2 + x**2*f(x))*f(x)/(x*(x**6*f(x)**3 + x**4*f(x)**2)), 0),
'sol': [Eq(f(x), C1 + 1/(2*x**2))],
},
'separable_reduced_07': {
'eq': Eq(f(x).diff(x) + (f(x)**2)*f(x)/(x), 0),
'sol': [
Eq(f(x), -sqrt(2)*sqrt(1/(C1 + log(x)))/2),
Eq(f(x), sqrt(2)*sqrt(1/(C1 + log(x)))/2)
],
},
'separable_reduced_08': {
'eq': Eq(f(x).diff(x) + (f(x)+3)*f(x)/(x*(f(x)+2)), 0),
'sol': [Eq(-log(f(x) + 3)/3 - 2*log(f(x))/3, C1 + log(x))],
'simplify_flag': False,
'XFAIL': ['lie_group'], #It hangs.
},
'separable_reduced_09': {
'eq': Eq(f(x).diff(x) + (f(x)+3)*f(x)/x, 0),
'sol': [Eq(f(x), 3/(C1*x**3 - 1))],
},
'separable_reduced_10': {
'eq': Eq(f(x).diff(x) + (f(x)**2+f(x))*f(x)/(x), 0),
'sol': [Eq(- log(x) - log(f(x) + 1) + log(f(x)) + 1/f(x), C1)],
'XFAIL': ['lie_group'],#No algorithms are implemented to solve equation -C1 + x*(_y + 1)*exp(-1/_y)/_y
},
# Equivalent to example_name 'separable_reduced_02'. Only difference is testing with simplify=True
'separable_reduced_11': {
'eq': f(x).diff(x) + (f(x) / (x**4*f(x) - x)),
'sol': [Eq(f(x), -sqrt(2)*sqrt(3*3**Rational(1,3)*(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3)
- 3*3**Rational(2,3)*exp(12*C1)/(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3) + 2/x**6)/6
- sqrt(2)*sqrt(-3*3**Rational(1,3)*(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3)
+ 3*3**Rational(2,3)*exp(12*C1)/(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3) + 4/x**6
- 4*sqrt(2)/(x**9*sqrt(3*3**Rational(1,3)*(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3)
- 3*3**Rational(2,3)*exp(12*C1)/(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3) + 2/x**6)))/6 + 1/(3*x**3)),
Eq(f(x), -sqrt(2)*sqrt(3*3**Rational(1,3)*(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3)
- 3*3**Rational(2,3)*exp(12*C1)/(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3) + 2/x**6)/6
+ sqrt(2)*sqrt(-3*3**Rational(1,3)*(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3)
+ 3*3**Rational(2,3)*exp(12*C1)/(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3) + 4/x**6
- 4*sqrt(2)/(x**9*sqrt(3*3**Rational(1,3)*(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3)
- 3*3**Rational(2,3)*exp(12*C1)/(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3) + 2/x**6)))/6 + 1/(3*x**3)),
Eq(f(x), sqrt(2)*sqrt(3*3**Rational(1,3)*(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3)
- 3*3**Rational(2,3)*exp(12*C1)/(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3) + 2/x**6)/6
- sqrt(2)*sqrt(-3*3**Rational(1,3)*(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3)
+ 3*3**Rational(2,3)*exp(12*C1)/(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3)
+ 4/x**6 + 4*sqrt(2)/(x**9*sqrt(3*3**Rational(1,3)*(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3)
- 3*3**Rational(2,3)*exp(12*C1)/(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3) + 2/x**6)))/6 + 1/(3*x**3)),
Eq(f(x), sqrt(2)*sqrt(3*3**Rational(1,3)*(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3)
- 3*3**Rational(2,3)*exp(12*C1)/(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3) + 2/x**6)/6
+ sqrt(2)*sqrt(-3*3**Rational(1,3)*(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3) + 3*3**Rational(2,3)*exp(12*C1)/(sqrt((3*exp(12*C1)
+ x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3) + 4/x**6 + 4*sqrt(2)/(x**9*sqrt(3*3**Rational(1,3)*(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1))
- exp(12*C1)/x**6)**Rational(1,3) - 3*3**Rational(2,3)*exp(12*C1)/(sqrt((3*exp(12*C1) + x**(-12))*exp(24*C1)) - exp(12*C1)/x**6)**Rational(1,3) + 2/x**6)))/6 + 1/(3*x**3))],
'checkodesol_XFAIL':True, #It hangs for this.
'slow': True,
},
#These were from issue: https://github.com/sympy/sympy/issues/6247
'separable_reduced_12': {
'eq': x**2*f(x)**2 + x*Derivative(f(x), x),
'sol': [Eq(f(x), 2*C1/(C1*x**2 - 1))],
},
}
}
@_add_example_keys
def _get_examples_ode_sol_lie_group():
a, b, c = symbols("a b c")
return {
'hint': "lie_group",
'func': f(x),
'examples':{
#Example 1-4 and 19-20 were from issue: https://github.com/sympy/sympy/issues/17322
'lie_group_01': {
'eq': x*f(x).diff(x)*(f(x)+4) + (f(x)**2) -2*f(x)-2*x,
'sol': [],
'dsolve_too_slow': True,
'checkodesol_too_slow': True,
},
'lie_group_02': {
'eq': x*f(x).diff(x)*(f(x)+4) + (f(x)**2) -2*f(x)-2*x,
'sol': [],
'dsolve_too_slow': True,
},
'lie_group_03': {
'eq': Eq(x**7*Derivative(f(x), x) + 5*x**3*f(x)**2 - (2*x**2 + 2)*f(x)**3, 0),
'sol': [],
'dsolve_too_slow': True,
},
'lie_group_04': {
'eq': f(x).diff(x) - (f(x) - x*log(x))**2/x**2 + log(x),
'sol': [],
'XFAIL': ['lie_group'],
},
'lie_group_05': {
'eq': f(x).diff(x)**2,
'sol': [Eq(f(x), C1)],
'XFAIL': ['factorable'], #It raises Not Implemented error
},
'lie_group_06': {
'eq': Eq(f(x).diff(x), x**2*f(x)),
'sol': [Eq(f(x), C1*exp(x**3)**Rational(1, 3))],
},
'lie_group_07': {
'eq': f(x).diff(x) + a*f(x) - c*exp(b*x),
'sol': [Eq(f(x), Piecewise(((-C1*(a + b) + c*exp(x*(a + b)))*exp(-a*x)/(a + b),\
Ne(a, -b)), ((-C1 + c*x)*exp(-a*x), True)))],
},
'lie_group_08': {
'eq': f(x).diff(x) + 2*x*f(x) - x*exp(-x**2),
'sol': [Eq(f(x), (C1 + x**2/2)*exp(-x**2))],
},
'lie_group_09': {
'eq': (1 + 2*x)*(f(x).diff(x)) + 2 - 4*exp(-f(x)),
'sol': [Eq(f(x), log(C1/(2*x + 1) + 2))],
},
'lie_group_10': {
'eq': x**2*(f(x).diff(x)) - f(x) + x**2*exp(x - (1/x)),
'sol': [Eq(f(x), (C1 - exp(x))*exp(-1/x))],
'XFAIL': ['factorable'], #It raises Recursion Error (maixmum depth exceeded)
},
'lie_group_11': {
'eq': x**2*f(x)**2 + x*Derivative(f(x), x),
'sol': [Eq(f(x), 2/(C1 + x**2))],
},
'lie_group_12': {
'eq': diff(f(x),x) + 2*x*f(x) - x*exp(-x**2),
'sol': [Eq(f(x), exp(-x**2)*(C1 + x**2/2))],
},
'lie_group_13': {
'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)))],
},
'lie_group_14': {
'eq': diff(f(x),x) + f(x)*cos(x) - sin(2*x)/2,
'sol': [Eq(f(x), C1*exp(-sin(x)) + sin(x) - 1)],
},
'lie_group_15': {
'eq': x*diff(f(x),x) + f(x) - x*sin(x),
'sol': [Eq(f(x), (C1 - x*cos(x) + sin(x))/x)],
},
'lie_group_16': {
'eq': x*diff(f(x),x) - f(x) - x/log(x),
'sol': [Eq(f(x), x*(C1 + log(log(x))))],
},
'lie_group_17': {
'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))],
},
'lie_group_18': {
'eq': f(x).diff(x) * (f(x).diff(x) - f(x)),
'sol': [Eq(f(x), C1*exp(x)), Eq(f(x), C1)],
},
'lie_group_19': {
'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))],
},
'lie_group_20': {
'eq': f(x).diff(x)*(f(x).diff(x)+f(x)),
'sol': [Eq(f(x), C1), Eq(f(x), C1*exp(-x))],
},
}
}
@_add_example_keys
def _get_examples_ode_sol_2nd_linear_airy():
return {
'hint': "2nd_linear_airy",
'func': f(x),
'examples':{
'2nd_lin_airy_01': {
'eq': f(x).diff(x, 2) - x*f(x),
'sol': [Eq(f(x), C1*airyai(x) + C2*airybi(x))],
},
'2nd_lin_airy_02': {
'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))],
},
}
}
@_add_example_keys
def _get_examples_ode_sol_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)
r1, r2, r3, r4, r5 = [rootof(x**5 + 11*x - 2, n) for n in range(5)]
r6, r7, r8, r9, r10 = [rootof(x**5 - 3*x + 1, n) for n in range(5)]
r11, r12, r13, r14, r15 = [rootof(x**5 - 100*x**3 + 1000*x + 1, n) for n in range(5)]
r16, r17, r18, r19, r20 = [rootof(x**5 - x**4 + 10, n) for n in range(5)]
r21, r22, r23, r24, r25 = [rootof(x**5 - x + 1, n) for n in range(5)]
E = exp(1)
return {
'hint': "nth_linear_constant_coeff_homogeneous",
'func': f(x),
'examples':{
'lin_const_coeff_hom_01': {
'eq': f(x).diff(x, 2) + 2*f(x).diff(x),
'sol': [Eq(f(x), C1 + C2*exp(-2*x))],
},
'lin_const_coeff_hom_02': {
'eq': f(x).diff(x, 2) - 3*f(x).diff(x) + 2*f(x),
'sol': [Eq(f(x), (C1 + C2*exp(x))*exp(x))],
},
'lin_const_coeff_hom_03': {
'eq': f(x).diff(x, 2) - f(x),
'sol': [Eq(f(x), C1*exp(-x) + C2*exp(x))],
},
'lin_const_coeff_hom_04': {
'eq': 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))],
'slow': True,
},
'lin_const_coeff_hom_05': {
'eq': 6*f(x).diff(x, 2) - 11*f(x).diff(x) + 4*f(x),
'sol': [Eq(f(x), C1*exp(x/2) + C2*exp(x*Rational(4, 3)))],
'slow': True,
},
'lin_const_coeff_hom_06': {
'eq': Eq(f(x).diff(x, 2) + 2*f(x).diff(x) - f(x), 0),
'sol': [Eq(f(x), C1*exp(x*(-1 + sqrt(2))) + C2*exp(-x*(sqrt(2) + 1)))],
'slow': True,
},
'lin_const_coeff_hom_07': {
'eq': diff(f(x), x, 3) + diff(f(x), x, 2) - 10*diff(f(x), x) - 6*f(x),
'sol': [Eq(f(x), C1*exp(3*x) + C3*exp(-x*(2 + sqrt(2))) + C2*exp(x*(-2 + sqrt(2))))],
'slow': True,
},
'lin_const_coeff_hom_08': {
'eq': 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(-2*x) + C3*exp(x) + C4*exp(2*x))],
'slow': True,
},
'lin_const_coeff_hom_09': {
'eq': f(x).diff(x, 4) + 4*f(x).diff(x, 3) + f(x).diff(x, 2) - \
4*f(x).diff(x) - 2*f(x),
'sol': [Eq(f(x), C3*exp(-x) + C4*exp(x) + (C1*exp(-sqrt(2)*x) + C2*exp(sqrt(2)*x))*exp(-2*x))],
'slow': True,
},
'lin_const_coeff_hom_10': {
'eq': f(x).diff(x, 4) - a**2*f(x),
'sol': [Eq(f(x), C1*exp(-sqrt(a)*x) + C2*exp(sqrt(a)*x) + C3*sin(sqrt(a)*x) + C4*cos(sqrt(a)*x))],
'slow': True,
},
'lin_const_coeff_hom_11': {
'eq': f(x).diff(x, 2) - 2*k*f(x).diff(x) - 2*f(x),
'sol': [Eq(f(x), C1*exp(x*(k - sqrt(k**2 + 2))) + C2*exp(x*(k + sqrt(k**2 + 2))))],
'slow': True,
},
'lin_const_coeff_hom_12': {
'eq': f(x).diff(x, 2) + 4*k*f(x).diff(x) - 12*k**2*f(x),
'sol': [Eq(f(x), C1*exp(-6*k*x) + C2*exp(2*k*x))],
'slow': True,
},
'lin_const_coeff_hom_13': {
'eq': f(x).diff(x, 4),
'sol': [Eq(f(x), C1 + C2*x + C3*x**2 + C4*x**3)],
'slow': True,
},
'lin_const_coeff_hom_14': {
'eq': f(x).diff(x, 2) + 4*f(x).diff(x) + 4*f(x),
'sol': [Eq(f(x), (C1 + C2*x)*exp(-2*x))],
'slow': True,
},
'lin_const_coeff_hom_15': {
'eq': 3*f(x).diff(x, 3) + 5*f(x).diff(x, 2) + f(x).diff(x) - f(x),
'sol': [Eq(f(x), (C1 + C2*x)*exp(-x) + C3*exp(x/3))],
'slow': True,
},
'lin_const_coeff_hom_16': {
'eq': f(x).diff(x, 3) - 6*f(x).diff(x, 2) + 12*f(x).diff(x) - 8*f(x),
'sol': [Eq(f(x), (C1 + x*(C2 + C3*x))*exp(2*x))],
'slow': True,
},
'lin_const_coeff_hom_17': {
'eq': f(x).diff(x, 2) - 2*a*f(x).diff(x) + a**2*f(x),
'sol': [Eq(f(x), (C1 + C2*x)*exp(a*x))],
'slow': True,
},
'lin_const_coeff_hom_18': {
'eq': 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))],
'slow': True,
},
'lin_const_coeff_hom_19': {
'eq': f(x).diff(x, 4) - 2*f(x).diff(x, 2),
'sol': [Eq(f(x), C1 + C2*x + C3*exp(-sqrt(2)*x) + C4*exp(sqrt(2)*x))],
'slow': True,
},
'lin_const_coeff_hom_20': {
'eq': 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),
'sol': [Eq(f(x), (C1 + C2*x)*exp(-3*x) + (C3 + C4*x)*exp(2*x))],
'slow': True,
},
'lin_const_coeff_hom_21': {
'eq': 36*f(x).diff(x, 4) - 37*f(x).diff(x, 2) + 4*f(x).diff(x) + 5*f(x),
'sol': [Eq(f(x), C1*exp(-x) + C2*exp(-x/3) + C3*exp(x/2) + C4*exp(x*Rational(5, 6)))],
'slow': True,
},
'lin_const_coeff_hom_22': {
'eq': f(x).diff(x, 4) - 8*f(x).diff(x, 2) + 16*f(x),
'sol': [Eq(f(x), (C1 + C2*x)*exp(-2*x) + (C3 + C4*x)*exp(2*x))],
'slow': True,
},
'lin_const_coeff_hom_23': {
'eq': f(x).diff(x, 2) - 2*f(x).diff(x) + 5*f(x),
'sol': [Eq(f(x), (C1*sin(2*x) + C2*cos(2*x))*exp(x))],
'slow': True,
},
'lin_const_coeff_hom_24': {
'eq': f(x).diff(x, 2) - f(x).diff(x) + f(x),
'sol': [Eq(f(x), (C1*sin(x*sqrt(3)/2) + C2*cos(x*sqrt(3)/2))*exp(x/2))],
'slow': True,
},
'lin_const_coeff_hom_25': {
'eq': f(x).diff(x, 4) + 5*f(x).diff(x, 2) + 6*f(x),
'sol': [Eq(f(x),
C1*sin(sqrt(2)*x) + C2*sin(sqrt(3)*x) + C3*cos(sqrt(2)*x) + C4*cos(sqrt(3)*x))],
'slow': True,
},
'lin_const_coeff_hom_26': {
'eq': f(x).diff(x, 2) - 4*f(x).diff(x) + 20*f(x),
'sol': [Eq(f(x), (C1*sin(4*x) + C2*cos(4*x))*exp(2*x))],
'slow': True,
},
'lin_const_coeff_hom_27': {
'eq': f(x).diff(x, 4) + 4*f(x).diff(x, 2) + 4*f(x),
'sol': [Eq(f(x), (C1 + C2*x)*sin(x*sqrt(2)) + (C3 + C4*x)*cos(x*sqrt(2)))],
'slow': True,
},
'lin_const_coeff_hom_28': {
'eq': f(x).diff(x, 3) + 8*f(x),
'sol': [Eq(f(x), (C1*sin(x*sqrt(3)) + C2*cos(x*sqrt(3)))*exp(x) + C3*exp(-2*x))],
'slow': True,
},
'lin_const_coeff_hom_29': {
'eq': f(x).diff(x, 4) + 4*f(x).diff(x, 2),
'sol': [Eq(f(x), C1 + C2*x + C3*sin(2*x) + C4*cos(2*x))],
'slow': True,
},
'lin_const_coeff_hom_30': {
'eq': f(x).diff(x, 5) + 2*f(x).diff(x, 3) + f(x).diff(x),
'sol': [Eq(f(x), C1 + (C2 + C3*x)*sin(x) + (C4 + C5*x)*cos(x))],
'slow': True,
},
'lin_const_coeff_hom_31': {
'eq': f(x).diff(x, 4) + f(x).diff(x, 2) + f(x),
'sol': [Eq(f(x), (C1*sin(sqrt(3)*x/2) + C2*cos(sqrt(3)*x/2))*exp(-x/2)
+ (C3*sin(sqrt(3)*x/2) + C4*cos(sqrt(3)*x/2))*exp(x/2))],
'slow': True,
},
'lin_const_coeff_hom_32': {
'eq': f(x).diff(x, 4) + 4*f(x).diff(x, 2) + f(x),
'sol': [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)))],
'slow': True,
},
# One real root, two complex conjugate pairs
'lin_const_coeff_hom_33': {
'eq': f(x).diff(x, 5) + 11*f(x).diff(x) - 2*f(x),
'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)))],
'checkodesol_XFAIL':True, #It Hangs
},
# Three real roots, one complex conjugate pair
'lin_const_coeff_hom_34': {
'eq': f(x).diff(x,5) - 3*f(x).diff(x) + f(x),
'sol': [Eq(f(x),
C3*exp(r6*x) + C4*exp(r7*x) + C5*exp(r8*x)
+ exp(re(r9)*x) * (C1*sin(im(r9)*x) + C2*cos(im(r9)*x)))],
'checkodesol_XFAIL':True, #It Hangs
},
# Five distinct real roots
'lin_const_coeff_hom_35': {
'eq': f(x).diff(x,5) - 100*f(x).diff(x,3) + 1000*f(x).diff(x) + f(x),
'sol': [Eq(f(x), C1*exp(r11*x) + C2*exp(r12*x) + C3*exp(r13*x) + C4*exp(r14*x) + C5*exp(r15*x))],
'checkodesol_XFAIL':True, #It Hangs
},
# Rational root and unsolvable quintic
'lin_const_coeff_hom_36': {
'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),
'sol': [Eq(f(x),
C5*exp(5*x)
+ C6*exp(x*r16)
+ exp(re(r17)*x) * (C1*sin(im(r17)*x) + C2*cos(im(r17)*x))
+ exp(re(r19)*x) * (C3*sin(im(r19)*x) + C4*cos(im(r19)*x)))],
'checkodesol_XFAIL':True, #It Hangs
},
# Five double roots (this is (x**5 - x + 1)**2)
'lin_const_coeff_hom_37': {
'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),
'sol': [Eq(f(x), (C1 + C2*x)*exp(x*r21) + (-((C3 + C4*x)*sin(x*im(r22)))
+ (C5 + C6*x)*cos(x*im(r22)))*exp(x*re(r22)) + (-((C7 + C8*x)*sin(x*im(r24)))
+ (C10*x + C9)*cos(x*im(r24)))*exp(x*re(r24)))],
'checkodesol_XFAIL':True, #It Hangs
},
'lin_const_coeff_hom_38': {
'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))],
},
'lin_const_coeff_hom_39': {
'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)))],
},
'lin_const_coeff_hom_40': {
'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)))],
},
'lin_const_coeff_hom_41': {
'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))],
},
'lin_const_coeff_hom_42': {
'eq': f(x).diff(x, x) + y*f(x),
'sol': [Eq(f(x), C1*exp(-x*sqrt(-y)) + C2*exp(x*sqrt(-y)))],
},
'lin_const_coeff_hom_43': {
'eq': Eq(9*f(x).diff(x, x) + f(x), 0),
'sol': [Eq(f(x), C1*sin(x/3) + C2*cos(x/3))],
},
'lin_const_coeff_hom_44': {
'eq': Eq(9*f(x).diff(x, x), f(x)),
'sol': [Eq(f(x), C1*exp(-x/3) + C2*exp(x/3))],
},
'lin_const_coeff_hom_45': {
'eq': Eq(f(x).diff(x, x) - 3*diff(f(x), x) + 2*f(x), 0),
'sol': [Eq(f(x), (C1 + C2*exp(x))*exp(x))],
},
'lin_const_coeff_hom_46': {
'eq': Eq(f(x).diff(x, x) - 4*diff(f(x), x) + 4*f(x), 0),
'sol': [Eq(f(x), (C1 + C2*x)*exp(2*x))],
},
# Type: 2nd order, constant coefficients (two real equal roots)
'lin_const_coeff_hom_47': {
'eq': Eq(f(x).diff(x, x) + 2*diff(f(x), x) + 3*f(x), 0),
'sol': [Eq(f(x), (C1*sin(x*sqrt(2)) + C2*cos(x*sqrt(2)))*exp(-x))],
},
#These were from issue: https://github.com/sympy/sympy/issues/6247
'lin_const_coeff_hom_48': {
'eq': f(x).diff(x, x) + 4*f(x),
'sol': [Eq(f(x), C1*sin(2*x) + C2*cos(2*x))],
},
}
}
@_add_example_keys
def _get_examples_ode_sol_1st_homogeneous_coeff_subs_dep_div_indep():
return {
'hint': "1st_homogeneous_coeff_subs_dep_div_indep",
'func': f(x),
'examples':{
'dep_div_indep_01': {
'eq': f(x)/x*cos(f(x)/x) - (x/f(x)*sin(f(x)/x) + cos(f(x)/x))*f(x).diff(x),
'sol': [Eq(log(x), C1 - log(f(x)*sin(f(x)/x)/x))],
'slow': True
},
#indep_div_dep actually has a simpler solution for example 2 but it runs too slow.
'dep_div_indep_02': {
'eq': x*f(x).diff(x) - f(x) - x*sin(f(x)/x),
'sol': [Eq(log(x), log(C1) + log(cos(f(x)/x) - 1)/2 - log(cos(f(x)/x) + 1)/2)],
'simplify_flag':False,
},
'dep_div_indep_03': {
'eq': x*exp(f(x)/x) - f(x)*sin(f(x)/x) + x*sin(f(x)/x)*f(x).diff(x),
'sol': [Eq(log(x), C1 + exp(-f(x)/x)*sin(f(x)/x)/2 + exp(-f(x)/x)*cos(f(x)/x)/2)],
'slow': True
},
'dep_div_indep_04': {
'eq': f(x).diff(x) - f(x)/x + 1/sin(f(x)/x),
'sol': [Eq(f(x), x*(-acos(C1 + log(x)) + 2*pi)), Eq(f(x), x*acos(C1 + log(x)))],
'slow': True
},
# previous code was testing with these other solution:
# example5_solb = Eq(f(x), log(log(C1/x)**(-x)))
'dep_div_indep_05': {
'eq': x*exp(f(x)/x) + f(x) - x*f(x).diff(x),
'sol': [Eq(f(x), log((1/(C1 - log(x)))**x))],
'checkodesol_XFAIL':True, #(because of **x?)
},
}
}
@_add_example_keys
def _get_examples_ode_sol_linear_coefficients():
return {
'hint': "linear_coefficients",
'func': f(x),
'examples':{
'linear_coeff_01': {
'eq': f(x).diff(x) + (3 + 2*f(x))/(x + 3),
'sol': [Eq(f(x), C1/(x**2 + 6*x + 9) - Rational(3, 2))],
},
}
}
@_add_example_keys
def _get_examples_ode_sol_1st_homogeneous_coeff_best():
return {
'hint': "1st_homogeneous_coeff_best",
'func': f(x),
'examples':{
# previous code was testing this with other solution:
# example1_solb = Eq(-f(x)/(1 + log(x/f(x))), C1)
'1st_homogeneous_coeff_best_01': {
'eq': f(x) + (x*log(f(x)/x) - 2*x)*diff(f(x), x),
'sol': [Eq(f(x), -exp(C1)*LambertW(-x*exp(-C1 + 1)))],
'checkodesol_XFAIL':True, #(because of LambertW?)
},
'1st_homogeneous_coeff_best_02': {
'eq': 2*f(x)*exp(x/f(x)) + f(x)*f(x).diff(x) - 2*x*exp(x/f(x))*f(x).diff(x),
'sol': [Eq(log(f(x)), C1 - 2*exp(x/f(x)))],
},
# previous code was testing this with other solution:
# example3_solb = Eq(log(C1*x*sqrt(1/x)*sqrt(f(x))) + x**2/(2*f(x)**2), 0)
'1st_homogeneous_coeff_best_03': {
'eq': 2*x**2*f(x) + f(x)**3 + (x*f(x)**2 - 2*x**3)*f(x).diff(x),
'sol': [Eq(f(x), exp(2*C1 + LambertW(-2*x**4*exp(-4*C1))/2)/x)],
'checkodesol_XFAIL':True, #(because of LambertW?)
},
'1st_homogeneous_coeff_best_04': {
'eq': (x + sqrt(f(x)**2 - x*f(x)))*f(x).diff(x) - f(x),
'sol': [Eq(log(f(x)), C1 - 2*sqrt(-x/f(x) + 1))],
'slow': True,
},
'1st_homogeneous_coeff_best_05': {
'eq': x + f(x) - (x - f(x))*f(x).diff(x),
'sol': [Eq(log(x), C1 - log(sqrt(1 + f(x)**2/x**2)) + atan(f(x)/x))],
},
'1st_homogeneous_coeff_best_06': {
'eq': x*f(x).diff(x) - f(x) - x*sin(f(x)/x),
'sol': [Eq(f(x), 2*x*atan(C1*x))],
},
'1st_homogeneous_coeff_best_07': {
'eq': x**2 + f(x)**2 - 2*x*f(x)*f(x).diff(x),
'sol': [Eq(f(x), -sqrt(x*(C1 + x))), Eq(f(x), sqrt(x*(C1 + x)))],
},
'1st_homogeneous_coeff_best_08': {
'eq': f(x)**2 + (x*sqrt(f(x)**2 - x**2) - x*f(x))*f(x).diff(x),
'sol': [Eq(f(x), -sqrt(-x*exp(2*C1)/(x - 2*exp(C1)))), Eq(f(x), sqrt(-x*exp(2*C1)/(x - 2*exp(C1))))],
'checkodesol_XFAIL': True # solutions are valid in a range
},
}
}
def _get_all_examples():
all_examples = _get_examples_ode_sol_euler_homogeneous + \
_get_examples_ode_sol_euler_undetermined_coeff + \
_get_examples_ode_sol_euler_var_para + \
_get_examples_ode_sol_factorable + \
_get_examples_ode_sol_bernoulli + \
_get_examples_ode_sol_nth_algebraic + \
_get_examples_ode_sol_riccati + \
_get_examples_ode_sol_1st_linear + \
_get_examples_ode_sol_1st_exact + \
_get_examples_ode_sol_almost_linear + \
_get_examples_ode_sol_nth_order_reducible + \
_get_examples_ode_sol_nth_linear_undetermined_coefficients + \
_get_examples_ode_sol_liouville + \
_get_examples_ode_sol_separable + \
_get_examples_ode_sol_1st_rational_riccati + \
_get_examples_ode_sol_nth_linear_var_of_parameters + \
_get_examples_ode_sol_2nd_linear_bessel + \
_get_examples_ode_sol_2nd_2F1_hypergeometric + \
_get_examples_ode_sol_2nd_nonlinear_autonomous_conserved + \
_get_examples_ode_sol_separable_reduced + \
_get_examples_ode_sol_lie_group + \
_get_examples_ode_sol_2nd_linear_airy + \
_get_examples_ode_sol_nth_linear_constant_coeff_homogeneous +\
_get_examples_ode_sol_1st_homogeneous_coeff_best +\
_get_examples_ode_sol_1st_homogeneous_coeff_subs_dep_div_indep +\
_get_examples_ode_sol_linear_coefficients
return all_examples
|
529f2eb8596c3ecd707f61ef6a29a0e39d8874a059715f7c2f07f8ff7ecd51d2 | import glob
import os
import shutil
import subprocess
import sys
import tempfile
import warnings
from sysconfig import get_config_var, get_config_vars, get_path
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, CompileError
)
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 OSError("{} 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 += get_config_var('EXT_SUFFIX')
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:
if get_config_var('Py_ENABLE_SHARED'):
cfgDict = get_config_vars()
kwargs['linkline'] = kwargs.get('linkline', []) + [cfgDict['PY_LDFLAGS']] # PY_LDFLAGS or just LDFLAGS?
library_dirs += [cfgDict['LIBDIR']]
for opt in cfgDict['BLDLIBRARY'].split():
if opt.startswith('-l'):
libraries += [opt[2:]]
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)
# Set language_level if not set by cy_kwargs
# as not setting it is deprecated
if 'language_level' not in cy_kwargs:
cy_options.__dict__['language_level'] = 3
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:
py_inc_dir = get_path('include')
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.
"""
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'):
with open(dest + '.sha256') as fh:
sha256_on_disk = fh.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)
with open(dest + '.sha256', 'wt') as fh:
fh.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
|
258e76cb355ae23c62ec1947c0f8c592be44fa11e7ffca7b95d79511fb6cf2b3 | from collections import namedtuple
from hashlib import sha256
import os
import shutil
import sys
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
class CompilerNotFoundError(FileNotFoundError):
pass
class CompileError (Exception):
"""Failure to compile one or more C/C++ source files."""
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)
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.
"""
with open(path) as fh:
for line in fh:
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 ``which`` from shutils for provided candidates and returns
first hit.
Parameters
==========
candidates : iterable of str
Names of candidate commands
Raises
======
CompilerNotFoundError if no candidates match.
"""
from shutil import which
for c in candidates:
binary_path = which(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
|
6572836bc4115915914f35afb64d8d3aa22cf5e473b78e14440ec6d99cae1645 | # Tests that require installed backends go into
# sympy/test_external/test_autowrap
import os
import tempfile
import shutil
from io import StringIO
from sympy.core import symbols, Eq
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.core.relational 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.core.relational 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.core.relational 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 = {'compiler_directives': {'language_level': '3'}}
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.core.relational import Equality
from sympy.core.symbol import Dummy
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
|
c9e5f9afb930985d3a051deb133b97e4afbea470bebf185df05519cd5d540fa2 | from textwrap import dedent
import sys
from subprocess import Popen, PIPE
import os
from sympy.core.singleton import S
from sympy.testing.pytest import raises, warns_deprecated_sympy, skip
from sympy.utilities.misc import (translate, replace, ordinal, rawlines,
strlines, as_int, find_executable)
from sympy.external import import_module
pyodide_js = import_module('pyodide_js')
def test_translate():
abc = 'abc'
assert translate(abc, None, 'a') == 'bc'
assert translate(abc, None, '') == 'abc'
assert 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():
if pyodide_js:
skip("can't run on pyodide")
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*(1 - cos(x)), u: 1/x, u_var: _u'
assert expected in err, err
def test_as_int():
raises(ValueError, lambda : as_int(True))
raises(ValueError, lambda : as_int(1.1))
raises(ValueError, lambda : as_int([]))
raises(ValueError, lambda : as_int(S.NaN))
raises(ValueError, lambda : as_int(S.Infinity))
raises(ValueError, lambda : as_int(S.NegativeInfinity))
raises(ValueError, lambda : as_int(S.ComplexInfinity))
# for the following, limited precision makes int(arg) == arg
# but the int value is not necessarily what a user might have
# expected; Q.prime is more nuanced in its response for
# expressions which might be complex representations of an
# integer. This is not -- by design -- as_ints role.
raises(ValueError, lambda : as_int(1e23))
raises(ValueError, lambda : as_int(S('1.'+'0'*20+'1')))
assert as_int(True, strict=False) == 1
def test_deprecated_find_executable():
with warns_deprecated_sympy():
find_executable('python')
|
b5c36964fabb8c19d7fba3ac7c33cf2caf4d049842e1618fc4477ab58fb251c1 | from itertools import product
import math
import inspect
import mpmath
from sympy.testing.pytest import raises, warns_deprecated_sympy
from sympy.concrete.summations import Sum
from sympy.core.function import (Function, Lambda, diff)
from sympy.core.numbers import (E, Float, I, Rational, oo, pi)
from sympy.core.relational import Eq
from sympy.core.singleton import S
from sympy.core.symbol import (Dummy, symbols)
from sympy.functions.combinatorial.factorials import (RisingFactorial, factorial)
from sympy.functions.elementary.complexes import Abs
from sympy.functions.elementary.exponential import exp, log
from sympy.functions.elementary.hyperbolic import acosh
from sympy.functions.elementary.integers import floor
from sympy.functions.elementary.miscellaneous import (Max, Min, sqrt)
from sympy.functions.elementary.piecewise import Piecewise
from sympy.functions.elementary.trigonometric import (acos, cos, cot, sin,
sinc, tan)
from sympy.functions.special.bessel import (besseli, besselj, besselk, bessely)
from sympy.functions.special.beta_functions import (beta, betainc, betainc_regularized)
from sympy.functions.special.delta_functions import (Heaviside)
from sympy.functions.special.error_functions import (erf, erfc, fresnelc, fresnels)
from sympy.functions.special.gamma_functions import (digamma, gamma, loggamma)
from sympy.integrals.integrals import Integral
from sympy.logic.boolalg import (And, false, ITE, Not, Or, true)
from sympy.matrices.expressions.dotproduct import DotProduct
from sympy.tensor.array import derive_by_array, Array
from sympy.tensor.indexed import IndexedBase
from sympy.utilities.lambdify import lambdify
from sympy.core.expr import UnevaluatedExpr
from sympy.codegen.cfunctions import expm1, log1p, exp2, log2, log10, hypot
from sympy.codegen.numpy_nodes import logaddexp, logaddexp2
from sympy.codegen.scipy_nodes import cosm1
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.matrices import Matrix, MatrixSymbol, SparseMatrix
from sympy.printing.lambdarepr import LambdaPrinter
from sympy.printing.numpy 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.utilities.exceptions import ignore_warnings
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', import_kwargs={'fromlist': ['sparse']})
numexpr = import_module('numexpr')
tensorflow = import_module('tensorflow')
cupy = import_module('cupy')
jax = import_module('jax')
numba = import_module('numba')
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
p, q, r = symbols("p q r", real=True)
ae = abs(exp(p+UnevaluatedExpr(q+r)))
f = lambdify([p, q, r], [ae, ae], modules=math)
results = f(1.0, 1e18, -1e18)
refvals = [math.exp(1.0)]*2
for res, ref in zip(results, refvals):
assert abs((res-ref)/ref) < 1e-15
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():
if not numexpr:
skip("numexpr not installed.")
func_numexpr = lambdify((x,y,z), Piecewise((y, x >= 0), (z, x > -1)), numexpr)
with ignore_warnings(RuntimeWarning):
assert func_numexpr(1, 24, 42) == 24
assert str(func_numexpr(-1, 24, 42)) == 'nan'
def test_empty_modules():
x, y = symbols('x y')
expr = -(x % y)
no_modules = lambdify([x, y], expr)
empty_modules = lambdify([x, y], expr, modules=[])
assert no_modules(3, 7) == empty_modules(3, 7)
assert no_modules(3, 7) == -3
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
def test_integral():
if numpy and not scipy:
skip("scipy not installed.")
f = Lambda(x, exp(-x**2))
l = lambdify(y, Integral(f(x), (x, y, oo)))
d = l(-oo)
assert 1.77245385 < d < 1.772453851
def test_double_integral():
if numpy and not scipy:
skip("scipy not installed.")
# example from http://mpmath.org/doc/current/calculus/integration.html
i = Integral(1/(1 - x**2*y**2), (x, 0, 1), (y, 0, z))
l = lambdify([z], i)
d = l(1)
assert 1.23370055 < d < 1.233700551
#================== 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'])
with ignore_warnings(PendingDeprecationWarning):
numpy.testing.assert_allclose(f(1, 2, 3), sol_arr)
assert isinstance(f(1, 2, 3), numpy.matrix)
def test_scipy_sparse_matrix():
if not scipy:
skip("scipy not installed.")
A = SparseMatrix([[x, 0], [0, y]])
f = lambdify((x, y), A, modules="scipy")
B = f(1, 2)
assert isinstance(B, scipy.sparse.coo_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_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) == Integral(exp(-y**2), (y, -oo, oo))
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_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.printing.lambdarepr 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)
# To check Is lambdify loggamma works for mpmath or not
exp1 = lambdify(x, loggamma(x), 'mpmath')(5)
exp2 = lambdify(x, loggamma(x), 'mpmath')(1.8)
exp3 = lambdify(x, loggamma(x), 'mpmath')(15)
exp_ls = [exp1, exp2, exp3]
sol1 = mpmath.loggamma(5)
sol2 = mpmath.loggamma(1.8)
sol3 = mpmath.loggamma(15)
sol_ls = [sol1, sol2, sol3]
assert exp_ls == sol_ls
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
expr1 = lambdify((x, y), uppergamma(x, y),"mpmath")(1, 2)
expr2 = lambdify((x, y), lowergamma(x, y),"mpmath")(1, 2)
assert expr1 == uppergamma(1, 2).evalf()
assert expr2 == 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)
f2b = lambdify([], (1,)) # gh-23224
assert f2b() == (1,)
# 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_issue_13167_21411():
if not numpy:
skip("numpy not installed")
f1 = lambdify(x, sympy.Heaviside(x))
f2 = lambdify(x, sympy.Heaviside(x, 1))
res1 = f1([-1, 0, 1])
res2 = f2([-1, 0, 1])
assert Abs(res1[0]).n() < 1e-15 # First functionality: only one argument passed
assert Abs(res1[1] - 1/2).n() < 1e-15
assert Abs(res1[2] - 1).n() < 1e-15
assert Abs(res2[0]).n() < 1e-15 # Second functionality: two arguments passed
assert Abs(res2[1] - 1).n() < 1e-15
assert Abs(res2[2] - 1).n() < 1e-15
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_issue_22726():
if not numpy:
skip("numpy not installed")
x1, x2 = symbols('x1 x2')
f = Max(S.Zero, Min(x1, x2))
g = derive_by_array(f, (x1, x2))
G = lambdify((x1, x2), g, modules='numpy')
point = {x1: 1, x2: 2}
assert (abs(g.subs(point) - G(*point.values())) <= 1e-10).all()
def test_issue_22739():
if not numpy:
skip("numpy not installed")
x1, x2 = symbols('x1 x2')
f = Heaviside(Min(x1, x2))
F = lambdify((x1, x2), f, modules='numpy')
point = {x1: 1, x2: 2}
assert abs(f.subs(point) - F(*point.values())) <= 1e-10
def test_issue_22992():
if not numpy:
skip("numpy not installed")
a, t = symbols('a t')
expr = a*(log(cot(t/2)) - cos(t))
F = lambdify([a, t], expr, 'numpy')
point = {a: 10, t: 2}
assert abs(expr.subs(point) - F(*point.values())) <= 1e-10
# Standard math
F = lambdify([a, t], expr)
assert abs(expr.subs(point) - F(*point.values())) <= 1e-10
def test_issue_19764():
if not numpy:
skip("numpy not installed")
expr = Array([x, x**2])
f = lambdify(x, expr, 'numpy')
assert f(1).__class__ == numpy.ndarray
def test_issue_20070():
if not numba:
skip("numba not installed")
f = lambdify(x, sin(x), 'numpy')
assert numba.jit(f)(1)==0.8414709848078965
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
def test_betainc_scipy():
if not scipy:
skip("scipy not installed")
f = betainc(w, x, y, z)
F = lambdify((w, x, y, z), f, modules='scipy')
assert abs(betainc(1.4, 3.1, 0.1, 0.5) - F(1.4, 3.1, 0.1, 0.5)) <= 1e-10
def test_betainc_regularized_scipy():
if not scipy:
skip("scipy not installed")
f = betainc_regularized(w, x, y, z)
F = lambdify((w, x, y, z), f, modules='scipy')
assert abs(betainc_regularized(0.2, 3.5, 0.1, 1) - F(0.2, 3.5, 0.1, 1)) <= 1e-10
def test_numpy_special_math():
if not numpy:
skip("numpy not installed")
funcs = [expm1, log1p, exp2, log2, log10, hypot, logaddexp, logaddexp2]
for func in funcs:
if 2 in func.nargs:
expr = func(x, y)
args = (x, y)
num_args = (0.3, 0.4)
elif 1 in func.nargs:
expr = func(x)
args = (x,)
num_args = (0.3,)
else:
raise NotImplementedError("Need to handle other than unary & binary functions in test")
f = lambdify(args, expr)
result = f(*num_args)
reference = expr.subs(dict(zip(args, num_args))).evalf()
assert numpy.allclose(result, float(reference))
lae2 = lambdify((x, y), logaddexp2(log2(x), log2(y)))
assert abs(2.0**lae2(1e-50, 2.5e-50) - 3.5e-50) < 1e-62 # from NumPy's docstring
def test_scipy_special_math():
if not scipy:
skip("scipy not installed")
cm1 = lambdify((x,), cosm1(x), modules='scipy')
assert abs(cm1(1e-20) + 5e-41) < 1e-200
def test_cupy_array_arg():
if not cupy:
skip("CuPy not installed")
f = lambdify([[x, y]], x*x + y, 'cupy')
result = f(cupy.array([2.0, 1.0]))
assert result == 5
assert "cupy" in str(type(result))
def test_cupy_array_arg_using_numpy():
# numpy functions can be run on cupy arrays
# unclear if we can "officialy" support this,
# depends on numpy __array_function__ support
if not cupy:
skip("CuPy not installed")
f = lambdify([[x, y]], x*x + y, 'numpy')
result = f(cupy.array([2.0, 1.0]))
assert result == 5
assert "cupy" in str(type(result))
def test_cupy_dotproduct():
if not cupy:
skip("CuPy not installed")
A = Matrix([x, y, z])
f1 = lambdify([x, y, z], DotProduct(A, A), modules='cupy')
f2 = lambdify([x, y, z], DotProduct(A, A.T), modules='cupy')
f3 = lambdify([x, y, z], DotProduct(A.T, A), modules='cupy')
f4 = lambdify([x, y, z], DotProduct(A, A.T), modules='cupy')
assert f1(1, 2, 3) == \
f2(1, 2, 3) == \
f3(1, 2, 3) == \
f4(1, 2, 3) == \
cupy.array([14])
def test_jax_array_arg():
if not jax:
skip("JAX not installed")
f = lambdify([[x, y]], x*x + y, 'jax')
result = f(jax.numpy.array([2.0, 1.0]))
assert result == 5
assert "jax" in str(type(result))
def test_jax_array_arg_using_numpy():
if not jax:
skip("JAX not installed")
f = lambdify([[x, y]], x*x + y, 'numpy')
result = f(jax.numpy.array([2.0, 1.0]))
assert result == 5
assert "jax" in str(type(result))
def test_jax_dotproduct():
if not jax:
skip("JAX not installed")
A = Matrix([x, y, z])
f1 = lambdify([x, y, z], DotProduct(A, A), modules='jax')
f2 = lambdify([x, y, z], DotProduct(A, A.T), modules='jax')
f3 = lambdify([x, y, z], DotProduct(A.T, A), modules='jax')
f4 = lambdify([x, y, z], DotProduct(A, A.T), modules='jax')
assert f1(1, 2, 3) == \
f2(1, 2, 3) == \
f3(1, 2, 3) == \
f4(1, 2, 3) == \
jax.numpy.array([14])
def test_lambdify_cse():
def dummy_cse(exprs):
return (), exprs
def minmem(exprs):
from sympy.simplify.cse_main import cse_release_variables, cse
return cse(exprs, postprocess=cse_release_variables)
class Case:
def __init__(self, *, args, exprs, num_args, requires_numpy=False):
self.args = args
self.exprs = exprs
self.num_args = num_args
subs_dict = dict(zip(self.args, self.num_args))
self.ref = [e.subs(subs_dict).evalf() for e in exprs]
self.requires_numpy = requires_numpy
def lambdify(self, *, cse):
return lambdify(self.args, self.exprs, cse=cse)
def assertAllClose(self, result, *, abstol=1e-15, reltol=1e-15):
if self.requires_numpy:
assert all(numpy.allclose(result[i], numpy.asarray(r, dtype=float),
rtol=reltol, atol=abstol)
for i, r in enumerate(self.ref))
return
for i, r in enumerate(self.ref):
abs_err = abs(result[i] - r)
if r == 0:
assert abs_err < abstol
else:
assert abs_err/abs(r) < reltol
cases = [
Case(
args=(x, y, z),
exprs=[
x + y + z,
x + y - z,
2*x + 2*y - z,
(x+y)**2 + (y+z)**2,
],
num_args=(2., 3., 4.)
),
Case(
args=(x, y, z),
exprs=[
x + sympy.Heaviside(x),
y + sympy.Heaviside(x),
z + sympy.Heaviside(x, 1),
z/sympy.Heaviside(x, 1)
],
num_args=(0., 3., 4.)
),
Case(
args=(x, y, z),
exprs=[
x + sinc(y),
y + sinc(y),
z - sinc(y)
],
num_args=(0.1, 0.2, 0.3)
),
Case(
args=(x, y, z),
exprs=[
Matrix([[x, x*y], [sin(z) + 4, x**z]]),
x*y+sin(z)-x**z,
Matrix([x*x, sin(z), x**z])
],
num_args=(1.,2.,3.),
requires_numpy=True
),
Case(
args=(x, y),
exprs=[(x + y - 1)**2, x, x + y,
(x + y)/(2*x + 1) + (x + y - 1)**2, (2*x + 1)**(x + y)],
num_args=(1,2)
)
]
for case in cases:
if not numpy and case.requires_numpy:
continue
for cse in [False, True, minmem, dummy_cse]:
f = case.lambdify(cse=cse)
result = f(*case.num_args)
case.assertAllClose(result)
def test_deprecated_set():
with warns_deprecated_sympy():
lambdify({x, y}, x + y)
def test_23536_lambdify_cse_dummy():
f = Function('x')(y)
g = Function('w')(y)
expr = z + (f**4 + g**5)*(f**3 + (g*f)**3)
expr = expr.expand()
eval_expr = lambdify(((f, g), z), expr, cse=True)
eval_expr((1.0, 2.0), 3.0)
|
91bdeca09d4bee54df6646092b2b5f63f68aa07b7a7e43635a161b95e6f34e1c | from io import StringIO
from sympy.core import S, symbols, Eq, pi, Catalan, EulerGamma, Function
from sympy.core.relational import Equality
from sympy.functions.elementary.piecewise import Piecewise
from sympy.matrices import Matrix, MatrixSymbol
from sympy.utilities.codegen import JuliaCodeGen, codegen, make_routine
from sympy.testing.pytest import XFAIL
import sympy
x, y, z = symbols('x,y,z')
def test_empty_jl_code():
code_gen = JuliaCodeGen()
output = StringIO()
code_gen.dump_jl([], output, "file", header=False, empty=False)
source = output.getvalue()
assert source == ""
def test_jl_simple_code():
name_expr = ("test", (x + y)*z)
result, = codegen(name_expr, "Julia", header=False, empty=False)
assert result[0] == "test.jl"
source = result[1]
expected = (
"function test(x, y, z)\n"
" out1 = z .* (x + y)\n"
" return out1\n"
"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.functions.elementary.trigonometric import (cos, sin, 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.functions.elementary.trigonometric import (cos, sin)
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.core.symbol 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.core.symbol 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
|
9c57901c643d97e4765ff435b2730564fe0a434337e55e3c3ff8fd91d6a15b84 | from sympy.codegen import Assignment
from sympy.codegen.ast import none
from sympy.codegen.cfunctions import expm1, log1p
from sympy.codegen.scipy_nodes import cosm1
from sympy.codegen.matrix_nodes import MatrixSolve
from sympy.core import Expr, Mod, symbols, Eq, Le, Gt, zoo, oo, Rational, Pow
from sympy.core.numbers import pi
from sympy.core.singleton import S
from sympy.functions import acos, KroneckerDelta, Piecewise, sign, sqrt, Min, Max, cot, acsch, asec, coth
from sympy.logic import And, Or
from sympy.matrices import SparseMatrix, MatrixSymbol, Identity
from sympy.printing.pycode import (
MpmathPrinter, PythonCodePrinter, pycode, SymPyPrinter
)
from sympy.printing.tensorflow import TensorflowPrinter
from sympy.printing.numpy import NumPyPrinter, SciPyPrinter
from sympy.testing.pytest import raises, skip
from sympy.tensor import IndexedBase, Idx
from sympy.tensor.array.expressions.array_expressions import ArraySymbol, ArrayDiagonal, ArrayContraction, ZeroArray, OneArray
from sympy.external import import_module
from sympy.functions.special.gamma_functions import loggamma
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(-Mod(x, y)) == '-(x % y)'
assert prntr.doprint(Mod(-x, y)) == '(-x) % y'
assert prntr.doprint(And(x, y)) == 'x and y'
assert prntr.doprint(Or(x, y)) == 'x or y'
assert prntr.doprint(1/(x+y)) == '1/(x + 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(cot(x)) == '1/math.tan(x)'
assert prntr.doprint(coth(x)) == '(math.exp(x) + math.exp(-x))/(math.exp(x) - math.exp(-x))'
assert prntr.doprint(asec(x)) == 'math.acos(1/x)'
assert prntr.doprint(acsch(x)) == 'math.log(math.sqrt(1 + x**(-2)) + 1/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)'
assert prntr.doprint((2,3)) == "(2, 3)"
assert prntr.doprint([2,3]) == "[2, 3]"
assert prntr.doprint(Min(x, y)) == "min(x, y)"
assert prntr.doprint(Max(x, y)) == "max(x, y)"
def test_PythonCodePrinter_standard():
prntr = PythonCodePrinter()
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'
assert p.doprint(loggamma(x)) == 'mpmath.loggamma(x)'
def test_NumPyPrinter():
from sympy.core.function import Lambda
from sympy.matrices.expressions.adjoint import Adjoint
from sympy.matrices.expressions.diagonal import (DiagMatrix, DiagonalMatrix, DiagonalOf)
from sympy.matrices.expressions.funcmatrix import FunctionMatrix
from sympy.matrices.expressions.hadamard import HadamardProduct
from sympy.matrices.expressions.kronecker import KroneckerProduct
from sympy.matrices.expressions.special import (OneMatrix, ZeroMatrix)
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)'
expr = Pow(2, -1, evaluate=False)
assert p.doprint(expr) == "2**(-1.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_issue_18770():
numpy = import_module('numpy')
if not numpy:
skip("numpy not installed.")
from sympy.functions.elementary.miscellaneous import (Max, Min)
from sympy.utilities.lambdify import lambdify
expr1 = Min(0.1*x + 3, x + 1, 0.5*x + 1)
func = lambdify(x, expr1, "numpy")
assert (func(numpy.linspace(0, 3, 3)) == [1.0, 1.75, 2.5 ]).all()
assert func(4) == 3
expr1 = Max(x**2, x**3)
func = lambdify(x,expr1, "numpy")
assert (func(numpy.linspace(-1, 2, 4)) == [1, 0, 1, 8] ).all()
assert func(4) == 64
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_issue_20762():
# Make sure pycode removes curly braces from subscripted variables
a_b, b, a_11 = symbols('a_{b} b a_{11}')
expr = a_b*b
assert pycode(expr) == 'a_b*b'
expr = a_11*b
assert pycode(expr) == 'a_11*b'
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' : '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)'
def test_frac():
from sympy.functions.elementary.integers import frac
expr = frac(x)
prntr = NumPyPrinter()
assert prntr.doprint(expr) == 'numpy.mod(x, 1)'
prntr = SciPyPrinter()
assert prntr.doprint(expr) == 'numpy.mod(x, 1)'
prntr = PythonCodePrinter()
assert prntr.doprint(expr) == 'x % 1'
prntr = MpmathPrinter()
assert prntr.doprint(expr) == 'mpmath.frac(x)'
prntr = SymPyPrinter()
assert prntr.doprint(expr) == 'sympy.functions.elementary.integers.frac(x)'
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) == "math.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.functions.special.gamma_functions 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 "Not supported" in prntr.doprint(expr1)
assert "Not supported" in prntr.doprint(expr2)
prntr = PythonCodePrinter()
assert "Not supported" in prntr.doprint(expr1)
assert "Not supported" in prntr.doprint(expr2)
def test_Integral():
from sympy.functions.elementary.exponential import exp
from sympy.integrals.integrals import Integral
single = Integral(exp(-x), (x, 0, oo))
double = Integral(x**2*exp(x*y), (x, -z, z), (y, 0, z))
indefinite = Integral(x**2, x)
evaluateat = Integral(x**2, (x, 1))
prntr = SciPyPrinter()
assert prntr.doprint(single) == 'scipy.integrate.quad(lambda x: numpy.exp(-x), 0, numpy.PINF)[0]'
assert prntr.doprint(double) == 'scipy.integrate.nquad(lambda x, y: x**2*numpy.exp(x*y), ((-z, z), (0, z)))[0]'
raises(NotImplementedError, lambda: prntr.doprint(indefinite))
raises(NotImplementedError, lambda: prntr.doprint(evaluateat))
prntr = MpmathPrinter()
assert prntr.doprint(single) == 'mpmath.quad(lambda x: mpmath.exp(-x), (0, mpmath.inf))'
assert prntr.doprint(double) == 'mpmath.quad(lambda x, y: x**2*mpmath.exp(x*y), (-z, z), (0, z))'
raises(NotImplementedError, lambda: prntr.doprint(indefinite))
raises(NotImplementedError, lambda: prntr.doprint(evaluateat))
def test_fresnel_integrals():
from sympy.functions.special.error_functions 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 "Not supported" in prntr.doprint(expr1)
assert "Not supported" in prntr.doprint(expr2)
prntr = PythonCodePrinter()
assert "Not supported" in prntr.doprint(expr1)
assert "Not supported" in prntr.doprint(expr2)
prntr = MpmathPrinter()
assert prntr.doprint(expr1) == 'mpmath.fresnelc(x)'
assert prntr.doprint(expr2) == 'mpmath.fresnels(x)'
def test_beta():
from sympy.functions.special.beta_functions 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)'
def test_airy():
from sympy.functions.special.bessel import (airyai, airybi)
expr1 = airyai(x)
expr2 = airybi(x)
prntr = SciPyPrinter()
assert prntr.doprint(expr1) == 'scipy.special.airy(x)[0]'
assert prntr.doprint(expr2) == 'scipy.special.airy(x)[2]'
prntr = NumPyPrinter()
assert "Not supported" in prntr.doprint(expr1)
assert "Not supported" in prntr.doprint(expr2)
prntr = PythonCodePrinter()
assert "Not supported" in prntr.doprint(expr1)
assert "Not supported" in prntr.doprint(expr2)
def test_airy_prime():
from sympy.functions.special.bessel import (airyaiprime, airybiprime)
expr1 = airyaiprime(x)
expr2 = airybiprime(x)
prntr = SciPyPrinter()
assert prntr.doprint(expr1) == 'scipy.special.airy(x)[1]'
assert prntr.doprint(expr2) == 'scipy.special.airy(x)[3]'
prntr = NumPyPrinter()
assert "Not supported" in prntr.doprint(expr1)
assert "Not supported" in prntr.doprint(expr2)
prntr = PythonCodePrinter()
assert "Not supported" in prntr.doprint(expr1)
assert "Not supported" in prntr.doprint(expr2)
def test_numerical_accuracy_functions():
prntr = SciPyPrinter()
assert prntr.doprint(expm1(x)) == 'numpy.expm1(x)'
assert prntr.doprint(log1p(x)) == 'numpy.log1p(x)'
assert prntr.doprint(cosm1(x)) == 'scipy.special.cosm1(x)'
def test_array_printer():
A = ArraySymbol('A', (4,4,6,6,6))
I = IndexedBase('I')
i,j,k = Idx('i', (0,1)), Idx('j', (2,3)), Idx('k', (4,5))
prntr = NumPyPrinter()
assert prntr.doprint(ZeroArray(5)) == 'numpy.zeros((5,))'
assert prntr.doprint(OneArray(5)) == 'numpy.ones((5,))'
assert prntr.doprint(ArrayContraction(A, [2,3])) == 'numpy.einsum("abccd->abd", A)'
assert prntr.doprint(I) == 'I'
assert prntr.doprint(ArrayDiagonal(A, [2,3,4])) == 'numpy.einsum("abccc->abc", A)'
assert prntr.doprint(ArrayDiagonal(A, [0,1], [2,3])) == 'numpy.einsum("aabbc->cab", A)'
assert prntr.doprint(ArrayContraction(A, [2], [3])) == 'numpy.einsum("abcde->abe", A)'
assert prntr.doprint(Assignment(I[i,j,k], I[i,j,k])) == 'I = I'
prntr = TensorflowPrinter()
assert prntr.doprint(ZeroArray(5)) == 'tensorflow.zeros((5,))'
assert prntr.doprint(OneArray(5)) == 'tensorflow.ones((5,))'
assert prntr.doprint(ArrayContraction(A, [2,3])) == 'tensorflow.linalg.einsum("abccd->abd", A)'
assert prntr.doprint(I) == 'I'
assert prntr.doprint(ArrayDiagonal(A, [2,3,4])) == 'tensorflow.linalg.einsum("abccc->abc", A)'
assert prntr.doprint(ArrayDiagonal(A, [0,1], [2,3])) == 'tensorflow.linalg.einsum("aabbc->cab", A)'
assert prntr.doprint(ArrayContraction(A, [2], [3])) == 'tensorflow.linalg.einsum("abcde->abe", A)'
assert prntr.doprint(Assignment(I[i,j,k], I[i,j,k])) == 'I = I'
|
f74d1551f5294b9e737e59581907298dd0b85a6720e13f1357de0caf8df43597 | from sympy.core.symbol import symbols
from sympy.functions import beta, Ei, zeta, Max, Min, sqrt, riemann_xi, frac
from sympy.printing.cxx import CXX98CodePrinter, CXX11CodePrinter, CXX17CodePrinter, cxxcode
from sympy.codegen.cfunctions import log1p
x, y, u, v = symbols('x y u v')
def test_CXX98CodePrinter():
assert CXX98CodePrinter().doprint(Max(x, 3)) in ('std::max(x, 3)', 'std::max(3, x)')
assert CXX98CodePrinter().doprint(Min(x, 3, sqrt(x))) == 'std::min(3, std::min(x, std::sqrt(x)))'
cxx98printer = CXX98CodePrinter()
assert cxx98printer.language == 'C++'
assert cxx98printer.standard == 'C++98'
assert 'template' in cxx98printer.reserved_words
assert 'alignas' not in cxx98printer.reserved_words
def test_CXX11CodePrinter():
assert CXX11CodePrinter().doprint(log1p(x)) == 'std::log1p(x)'
cxx11printer = CXX11CodePrinter()
assert cxx11printer.language == 'C++'
assert cxx11printer.standard == 'C++11'
assert 'operator' in cxx11printer.reserved_words
assert 'noexcept' in cxx11printer.reserved_words
assert 'concept' not in cxx11printer.reserved_words
def test_subclass_print_method():
class MyPrinter(CXX11CodePrinter):
def _print_log1p(self, expr):
return 'my_library::log1p(%s)' % ', '.join(map(self._print, expr.args))
assert MyPrinter().doprint(log1p(x)) == 'my_library::log1p(x)'
def test_subclass_print_method__ns():
class MyPrinter(CXX11CodePrinter):
_ns = 'my_library::'
p = CXX11CodePrinter()
myp = MyPrinter()
assert p.doprint(log1p(x)) == 'std::log1p(x)'
assert myp.doprint(log1p(x)) == 'my_library::log1p(x)'
def test_CXX17CodePrinter():
assert CXX17CodePrinter().doprint(beta(x, y)) == 'std::beta(x, y)'
assert CXX17CodePrinter().doprint(Ei(x)) == 'std::expint(x)'
assert CXX17CodePrinter().doprint(zeta(x)) == 'std::riemann_zeta(x)'
# Automatic rewrite
assert CXX17CodePrinter().doprint(frac(x)) == 'x - std::floor(x)'
assert CXX17CodePrinter().doprint(riemann_xi(x)) == '(1.0/2.0)*std::pow(M_PI, -1.0/2.0*x)*x*(x - 1)*std::tgamma((1.0/2.0)*x)*std::riemann_zeta(x)'
def test_cxxcode():
assert sorted(cxxcode(sqrt(x)*.5).split('*')) == sorted(['0.5', 'std::sqrt(x)'])
def test_cxxcode_nested_minmax():
assert cxxcode(Max(Min(x, y), Min(u, v))) \
== 'std::max(std::min(u, v), std::min(x, y))'
assert cxxcode(Min(Max(x, y), Max(u, v))) \
== 'std::min(std::max(u, v), std::max(x, y))'
|
85155bad387754f494f06d53bcdb3957641f1d9023fdf3dc0ae9771e94579906 | from sympy.core.add import Add
from sympy.core.function import (Function, Lambda, diff)
from sympy.core.mod import Mod
from sympy.core import (Catalan, EulerGamma, GoldenRatio)
from sympy.core.numbers import (E, Float, I, Integer, Rational, pi)
from sympy.core.relational import Eq
from sympy.core.singleton import S
from sympy.core.symbol import (Dummy, symbols)
from sympy.functions.combinatorial.factorials import factorial
from sympy.functions.elementary.complexes import (conjugate, sign)
from sympy.functions.elementary.exponential import (exp, log)
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.piecewise import Piecewise
from sympy.functions.elementary.trigonometric import (atan2, cos, sin)
from sympy.functions.special.gamma_functions import gamma
from sympy.integrals.integrals import Integral
from sympy.sets.fancysets import Range
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.expr import UnevaluatedExpr
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.fortran import fcode, FCodePrinter
from sympy.tensor import IndexedBase, Idx
from sympy.utilities.lambdify import implemented_function
from sympy.testing.pytest import raises
def test_UnevaluatedExpr():
p, q, r = symbols("p q r", real=True)
q_r = UnevaluatedExpr(q + r)
expr = abs(exp(p+q_r))
assert fcode(expr, source_format="free") == "exp(p + (q + r))"
x, y, z = symbols("x y z")
y_z = UnevaluatedExpr(y + z)
expr2 = abs(exp(x+y_z))
assert fcode(expr2, human=False)[2].lstrip() == "exp(re(x) + re(y + z))"
assert fcode(expr2, user_functions={"re": "realpart"}).lstrip() == "exp(realpart(x) + realpart(y + z))"
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) == ({
(Catalan, p._print(Catalan.evalf(prec)))}, set(), ' Catalan')
assert fcode(EulerGamma, human=False) == ({(EulerGamma, p._print(
EulerGamma.evalf(prec)))}, set(), ' EulerGamma')
assert fcode(E, human=False) == (
{(E, p._print(E.evalf(prec)))}, set(), ' E')
assert fcode(GoldenRatio, human=False) == ({(GoldenRatio, p._print(
GoldenRatio.evalf(prec)))}, set(), ' GoldenRatio')
assert fcode(pi, human=False) == (
{(pi, p._print(pi.evalf(prec)))}, set(), ' pi')
assert fcode(pi, precision=5, human=False) == (
{(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))
|
d1f0cac19f85d0ab75878f9e13d27711d30a4d37557281eab91b2ee4b0c682ef | from sympy.core import (
S, pi, oo, symbols, Rational, Integer, Float, Mod, GoldenRatio, EulerGamma, Catalan,
Lambda, Dummy, nan, Mul, Pow, UnevaluatedExpr
)
from sympy.core.relational import (Eq, Ge, Gt, Le, Lt, Ne)
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, fibonacci, lucas
)
from sympy.sets import Range
from sympy.logic import ITE, Implies, Equivalent
from sympy.codegen import For, aug_assign, Assignment
from sympy.testing.pytest import raises, XFAIL
from sympy.printing.c 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, SparseMatrix
from sympy.printing.codeprinter 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 supported in c' not in gamma_c89.lower()
def test_ccode_functions2():
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)) + '\
'ceil(s)) % ceil(s)'
assert ccode(Mod(r, s)) == "fmod(r, s)"
p1, p2 = symbols('p1 p2', integer=True, positive=True)
assert ccode(Mod(p1, p2)) == 'p1 % p2'
assert ccode(Mod(p1, p2 + 3)) == 'p1 % (p2 + 3)'
assert ccode(Mod(-3, -7, evaluate=False)) == '(-3) % (-7)'
assert ccode(-Mod(3, 7, evaluate=False)) == '-(3 % 7)'
assert ccode(r*Mod(p1, p2)) == 'r*(p1 % p2)'
assert ccode(Mod(p1, p2)**s) == 'pow(p1 % p2, s)'
n = symbols('n', integer=True, negative=True)
assert ccode(Mod(-n, p2)) == '(-n) % p2'
assert ccode(fibonacci(n)) == '(1.0/5.0)*pow(2, -n)*sqrt(5)*(-pow(1 - sqrt(5), n) + pow(1 + sqrt(5), n))'
assert ccode(lucas(n)) == 'pow(2, -n)*(pow(1 - sqrt(5), n) + pow(1 + sqrt(5), n))'
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)"
# Automatic rewrites
assert ccode(x ^ y) == '(x || y) && (!x || !y)'
assert ccode((x ^ y) ^ z) == '(x || y || z) && (x || !y || !z) && (y || !x || !z) && (z || !x || !y)'
assert ccode(Implies(x, y)) == 'y || !x'
assert ccode(Equivalent(x, z ^ y, Implies(z, x))) == '(x || (y || !z) && (z || !y)) && (z && !x || (y || z) && (!y || !z))'
def test_ccode_Relational():
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.functions.elementary.trigonometric 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():
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():
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():
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():
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():
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_sparse_matrix():
# gh-15791
assert 'Not supported in C' in ccode(SparseMatrix([[1, 2, 3]]))
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)
p = symbols('p', integer=True, positive=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(p, 2), 'p % 2')
check(Mod(2*p + 3, 3*p + 5, evaluate=False), '(2*p + 3) % (3*p + 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)'
assert p128.doprint(x**-1.0) == '1.0Q/x'
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():
# Note that C only allows comments of the form /* ... */, double forward
# slash is not standard C, and some C compilers will grind to a halt upon
# encountering them.
assert ccode(Comment("this is a comment")) == "/* this is a comment */" # not //
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;',
])
def test_ccode_UnevaluatedExpr():
assert ccode(UnevaluatedExpr(y * x) + z) == "z + x*y"
assert ccode(UnevaluatedExpr(y + x) + z) == "z + (x + y)" # gh-21955
w = symbols('w')
assert ccode(UnevaluatedExpr(y + x) + UnevaluatedExpr(z + w)) == "(w + z) + (x + y)"
p, q, r = symbols("p q r", real=True)
q_r = UnevaluatedExpr(q + r)
expr = abs(exp(p+q_r))
assert ccode(expr) == "exp(p + (q + r))"
def test_ccode_array_like_containers():
assert ccode([2,3,4]) == "{2, 3, 4}"
assert ccode((2,3,4)) == "{2, 3, 4}"
|
614fe5010a62347289a418d99a05ebfae9f33b04ba4acfaef2c4b60ffbbe32ad | from sympy.concrete.summations import Sum
from sympy.core.expr import Expr
from sympy.core.symbol import symbols
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.piecewise import Piecewise
from sympy.functions.elementary.trigonometric import sin
from sympy.matrices.dense import MutableDenseMatrix as Matrix
from sympy.sets.sets import Interval
from sympy.utilities.lambdify import lambdify
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():
# Test printing a Matrix that has an element that is printed differently
# with the LambdaPrinter than with the StrPrinter.
e = x % 2
assert lambdarepr(e) != str(e)
assert lambdarepr(Matrix([e])) == 'ImmutableDenseMatrix([[x % 2]])'
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, 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' : 'python3'})
assert prntr._print_Pow(sqrt(x), rational=False) == 'sqrt(x)'
assert prntr._print_Pow(sqrt(x), rational=True) == 'x**(1/2)'
def test_settings():
raises(TypeError, lambda: lambdarepr(sin(x), method="garbage"))
def test_numexpr():
# test ITE rewrite as Piecewise
from sympy.logic.boolalg import ITE
expr = ITE(x > 0, True, False, evaluate=False)
assert NumExprPrinter().doprint(expr) == \
"numexpr.evaluate('where((x > 0), True, False)', truediv=True)"
from sympy.codegen.ast import Return, FunctionDefinition, Variable, Assignment
func_def = FunctionDefinition(None, 'foo', [Variable(x)], [Assignment(y,x), Return(y**2)])
expected = "def foo(x):\n"\
" y = numexpr.evaluate('x', truediv=True)\n"\
" return numexpr.evaluate('y**2', truediv=True)"
assert NumExprPrinter().doprint(func_def) == expected
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) == "numexpr.evaluate('numexpr', truediv=True)"
assert NumExprPrinter().doprint(Piecewise((y, x >= 0), (z, x < 0))) == \
"numexpr.evaluate('where((x >= 0), y, z)', truediv=True)"
|
13003a50106253cba1a69678a79991670c33a473467892970d73db2e05b06fa8 | from sympy import MatAdd, MatMul, Array
from sympy.algebras.quaternion import Quaternion
from sympy.calculus.accumulationbounds import AccumBounds
from sympy.combinatorics.permutations import Cycle, Permutation, AppliedPermutation
from sympy.concrete.products import Product
from sympy.concrete.summations import Sum
from sympy.core.containers import Tuple, Dict
from sympy.core.expr import UnevaluatedExpr
from sympy.core.function import (Derivative, Function, Lambda, Subs, diff)
from sympy.core.mod import Mod
from sympy.core.mul import Mul
from sympy.core.numbers import (AlgebraicNumber, Float, I, Integer, Rational, oo, pi)
from sympy.core.power import Pow
from sympy.core.relational import Eq, Ne
from sympy.core.singleton import S
from sympy.core.symbol import (Symbol, Wild, symbols)
from sympy.functions.combinatorial.factorials import (FallingFactorial, RisingFactorial, binomial, factorial, factorial2, subfactorial)
from sympy.functions.combinatorial.numbers import bernoulli, bell, catalan, euler, lucas, fibonacci, tribonacci
from sympy.functions.elementary.complexes import (Abs, arg, conjugate, im, polar_lift, re)
from sympy.functions.elementary.exponential import (LambertW, exp, log)
from sympy.functions.elementary.hyperbolic import (asinh, coth)
from sympy.functions.elementary.integers import (ceiling, floor, frac)
from sympy.functions.elementary.miscellaneous import (Max, Min, root, sqrt)
from sympy.functions.elementary.piecewise import Piecewise
from sympy.functions.elementary.trigonometric import (acsc, asin, cos, cot, sin, tan)
from sympy.functions.special.beta_functions import beta
from sympy.functions.special.delta_functions import (DiracDelta, Heaviside)
from sympy.functions.special.elliptic_integrals import (elliptic_e, elliptic_f, elliptic_k, elliptic_pi)
from sympy.functions.special.error_functions import (Chi, Ci, Ei, Shi, Si, expint)
from sympy.functions.special.gamma_functions import (gamma, uppergamma)
from sympy.functions.special.hyper import (hyper, meijerg)
from sympy.functions.special.mathieu_functions import (mathieuc, mathieucprime, mathieus, mathieusprime)
from sympy.functions.special.polynomials import (assoc_laguerre, assoc_legendre, chebyshevt, chebyshevu, gegenbauer, hermite, jacobi, laguerre, legendre)
from sympy.functions.special.singularity_functions import SingularityFunction
from sympy.functions.special.spherical_harmonics import (Ynm, Znm)
from sympy.functions.special.tensor_functions import (KroneckerDelta, LeviCivita)
from sympy.functions.special.zeta_functions import (dirichlet_eta, lerchphi, polylog, stieltjes, zeta)
from sympy.integrals.integrals import Integral
from sympy.integrals.transforms import (CosineTransform, FourierTransform, InverseCosineTransform, InverseFourierTransform, InverseLaplaceTransform, InverseMellinTransform, InverseSineTransform, LaplaceTransform, MellinTransform, SineTransform)
from sympy.logic import Implies
from sympy.logic.boolalg import (And, Or, Xor, Equivalent, false, Not, true)
from sympy.matrices.dense import Matrix
from sympy.matrices.expressions.kronecker import KroneckerProduct
from sympy.matrices.expressions.matexpr import MatrixSymbol
from sympy.matrices.expressions.permutation import PermutationMatrix
from sympy.matrices.expressions.slice import MatrixSlice
from sympy.physics.control.lti import TransferFunction, Series, Parallel, Feedback, TransferFunctionMatrix, MIMOSeries, MIMOParallel, MIMOFeedback
from sympy.ntheory.factor_ import (divisor_sigma, primenu, primeomega, reduced_totient, totient, udivisor_sigma)
from sympy.physics.quantum import Commutator, Operator
from sympy.physics.quantum.trace import Tr
from sympy.physics.units import meter, gibibyte, gram, microgram, second, milli, micro
from sympy.polys.domains.integerring import ZZ
from sympy.polys.fields import field
from sympy.polys.polytools import Poly
from sympy.polys.rings import ring
from sympy.polys.rootoftools import (RootSum, rootof)
from sympy.series.formal import fps
from sympy.series.fourier import fourier_series
from sympy.series.limits import Limit
from sympy.series.order import Order
from sympy.series.sequences import (SeqAdd, SeqFormula, SeqMul, SeqPer)
from sympy.sets.conditionset import ConditionSet
from sympy.sets.contains import Contains
from sympy.sets.fancysets import (ComplexRegion, ImageSet, Range)
from sympy.sets.ordinals import Ordinal, OrdinalOmega, OmegaPower
from sympy.sets.powerset import PowerSet
from sympy.sets.sets import (FiniteSet, Interval, Union, Intersection, Complement, SymmetricDifference, ProductSet)
from sympy.sets.setexpr import SetExpr
from sympy.stats.crv_types import Normal
from sympy.stats.symbolic_probability import (Covariance, Expectation,
Probability, Variance)
from sympy.tensor.array import (ImmutableDenseNDimArray,
ImmutableSparseNDimArray,
MutableSparseNDimArray,
MutableDenseNDimArray,
tensorproduct)
from sympy.tensor.array.expressions.array_expressions import ArraySymbol, ArrayElement
from sympy.tensor.indexed import (Idx, Indexed, IndexedBase)
from sympy.tensor.toperators import PartialDerivative
from sympy.vector import CoordSys3D, Cross, Curl, Dot, Divergence, Gradient, Laplacian
from sympy.testing.pytest import (XFAIL, raises, _both_exp_pow,
warns_deprecated_sympy)
from sympy.printing.latex import (latex, translate, greek_letters_set,
tex_greek_dictionary, multiline_latex,
latex_escape, LatexPrinter)
import sympy as sym
from sympy.abc import mu, tau
class lowergamma(sym.lowergamma):
pass # testing notation inheritance by a subclass with same name
x, y, z, t, w, a, b, c, s, p = symbols('x y z t w a b c s p')
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)) == r"foo(x)"
class R(Abs):
def _latex(self, printer):
return "foo"
assert latex(R(x)) == r"foo"
def test_latex_basic():
assert latex(1 + x) == r"x + 1"
assert latex(x**2) == r"x^{2}"
assert latex(x**(1 + x)) == r"x^{x + 1}"
assert latex(x**3 + x + 1 + x**2) == r"x^{3} + x^{2} + x + 1"
assert latex(2*x*y) == r"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(x**S.Half**5) == r"\sqrt[32]{x}"
assert latex(Mul(S.Half, x**2, -5, evaluate=False)) == r"\frac{1}{2} x^{2} \left(-5\right)"
assert latex(Mul(S.Half, x**2, 5, evaluate=False)) == r"\frac{1}{2} x^{2} \cdot 5"
assert latex(Mul(-5, -5, evaluate=False)) == r"\left(-5\right) \left(-5\right)"
assert latex(Mul(5, -5, evaluate=False)) == r"5 \left(-5\right)"
assert latex(Mul(S.Half, -5, S.Half, evaluate=False)) == r"\frac{1}{2} \left(-5\right) \frac{1}{2}"
assert latex(Mul(5, I, 5, evaluate=False)) == r"5 i 5"
assert latex(Mul(5, I, -5, evaluate=False)) == r"5 i \left(-5\right)"
assert latex(Mul(0, 1, evaluate=False)) == r'0 \cdot 1'
assert latex(Mul(1, 0, evaluate=False)) == r'1 \cdot 0'
assert latex(Mul(1, 1, evaluate=False)) == r'1 \cdot 1'
assert latex(Mul(-1, 1, evaluate=False)) == r'\left(-1\right) 1'
assert latex(Mul(1, 1, 1, evaluate=False)) == r'1 \cdot 1 \cdot 1'
assert latex(Mul(1, 2, evaluate=False)) == r'1 \cdot 2'
assert latex(Mul(1, S.Half, evaluate=False)) == r'1 \cdot \frac{1}{2}'
assert latex(Mul(1, 1, S.Half, evaluate=False)) == \
r'1 \cdot 1 \cdot \frac{1}{2}'
assert latex(Mul(1, 1, 2, 3, x, evaluate=False)) == \
r'1 \cdot 1 \cdot 2 \cdot 3 x'
assert latex(Mul(1, -1, evaluate=False)) == r'1 \left(-1\right)'
assert latex(Mul(4, 3, 2, 1, 0, y, x, evaluate=False)) == \
r'4 \cdot 3 \cdot 2 \cdot 1 \cdot 0 y x'
assert latex(Mul(4, 3, 2, 1+z, 0, y, x, evaluate=False)) == \
r'4 \cdot 3 \cdot 2 \left(z + 1\right) 0 y x'
assert latex(Mul(Rational(2, 3), Rational(5, 7), evaluate=False)) == \
r'\frac{2}{3} \cdot \frac{5}{7}'
assert latex(1/x) == r"\frac{1}{x}"
assert latex(1/x, fold_short_frac=True) == r"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) == r"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(binomial(x, y)) == r"{\binom{x}{y}}"
x_star = Symbol('x^*')
f = Function('f')
assert latex(x_star**2) == r"\left(x^{*}\right)^{2}"
assert latex(x_star**2, parenthesize_super=False) == r"{x^{*}}^{2}"
assert latex(Derivative(f(x_star), x_star,2)) == r"\frac{d^{2}}{d \left(x^{*}\right)^{2}} f{\left(x^{*} \right)}"
assert latex(Derivative(f(x_star), x_star,2), parenthesize_super=False) == r"\frac{d^{2}}{d {x^{*}}^{2}} f{\left(x^{*} \right)}"
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) == r"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(AlgebraicNumber(sqrt(2))) == r"\sqrt{2}"
assert latex(AlgebraicNumber(sqrt(2), [3, -7])) == r"-7 + 3 \sqrt{2}"
assert latex(AlgebraicNumber(sqrt(2), alias='alpha')) == r"\alpha"
assert latex(AlgebraicNumber(sqrt(2), [3, -7], alias='alpha')) == \
r"3 \alpha - 7"
assert latex(AlgebraicNumber(2**(S(1)/3), [1, 3, -7], alias='beta')) == \
r"\beta^{2} + 3 \beta - 7"
k = ZZ.cyclotomic_field(5)
assert latex(k.ext.field_element([1, 2, 3, 4])) == \
r"\zeta^{3} + 2 \zeta^{2} + 3 \zeta + 4"
assert latex(k.ext.field_element([1, 2, 3, 4]), order='old') == \
r"4 + 3 \zeta + 2 \zeta^{2} + \zeta^{3}"
assert latex(k.primes_above(19)[0]) == \
r"\left(19, \zeta^{2} + 5 \zeta + 1\right)"
assert latex(k.primes_above(19)[0], order='old') == \
r"\left(19, 1 + 5 \zeta + \zeta^{2}\right)"
assert latex(k.primes_above(7)[0]) == r"\left(7\right)"
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"
assert latex(Pow(Rational(1, 3), -1, evaluate=False)) == r"\frac{1}{\frac{1}{3}}"
assert latex(Pow(Rational(1, 3), -2, evaluate=False)) == r"\frac{1}{(\frac{1}{3})^{2}}"
assert latex(Pow(Integer(1)/100, -1, evaluate=False)) == r"\frac{1}{\frac{1}{100}}"
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}"
assert latex(SingularityFunction(x, 4, 5)**3) == \
r"{\left({\langle x - 4 \rangle}^{5}\right)}^{3}"
assert latex(SingularityFunction(x, -3, 4)**3) == \
r"{\left({\langle x + 3 \rangle}^{4}\right)}^{3}"
assert latex(SingularityFunction(x, 0, 4)**3) == \
r"{\left({\langle x \rangle}^{4}\right)}^{3}"
assert latex(SingularityFunction(x, a, n)**3) == \
r"{\left({\langle - a + x \rangle}^{n}\right)}^{3}"
assert latex(SingularityFunction(x, 4, -2)**3) == \
r"{\left({\langle x - 4 \rangle}^{-2}\right)}^{3}"
assert latex((SingularityFunction(x, 4, -1)**3)**3) == \
r"{\left({\langle x - 4 \rangle}^{-1}\right)}^{9}"
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)"
with warns_deprecated_sympy():
old_print_cyclic = Permutation.print_cyclic
Permutation.print_cyclic = False
assert latex(Permutation(0, 1)(2, 3)) == \
r"\begin{pmatrix} 0 & 1 & 2 & 3 \\ 1 & 0 & 3 & 2 \end{pmatrix}"
Permutation.print_cyclic = old_print_cyclic
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(\left(3 \mathbf{{x}_{A}}\right)\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(\left(x\right)\mathbf{\hat{i}_{A}}\right)'
assert latex(Curl(3*A.x*A.j)) == \
r"\nabla\times \left(\left(3 \mathbf{{x}_{A}}\right)\mathbf{\hat{j}_{A}}\right)"
assert latex(Curl(3*A.x*A.j+A.i)) == \
r"\nabla\times \left(\mathbf{\hat{i}_{A}} + \left(3 \mathbf{{x}_{A}}\right)\mathbf{\hat{j}_{A}}\right)"
assert latex(Curl(3*x*A.x*A.j)) == \
r"\nabla\times \left(\left(3 \mathbf{{x}_{A}} x\right)\mathbf{\hat{j}_{A}}\right)"
assert latex(x*Curl(3*A.x*A.j)) == \
r"x \left(\nabla\times \left(\left(3 \mathbf{{x}_{A}}\right)\mathbf{\hat{j}_{A}}\right)\right)"
assert latex(Divergence(3*A.x*A.j+A.i)) == \
r"\nabla\cdot \left(\mathbf{\hat{i}_{A}} + \left(3 \mathbf{{x}_{A}}\right)\mathbf{\hat{j}_{A}}\right)"
assert latex(Divergence(3*A.x*A.j)) == \
r"\nabla\cdot \left(\left(3 \mathbf{{x}_{A}}\right)\mathbf{\hat{j}_{A}}\right)"
assert latex(x*Divergence(3*A.x*A.j)) == \
r"x \left(\nabla\cdot \left(\left(3 \mathbf{{x}_{A}}\right)\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(\left(3 \mathbf{{x}_{A}}\right)\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(\left(x\right)\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"\Delta \mathbf{{x}_{A}}"
assert latex(Laplacian(A.x + 3*A.y)) == \
r"\Delta \left(\mathbf{{x}_{A}} + 3 \mathbf{{y}_{A}}\right)"
assert latex(x*Laplacian(A.x)) == r"x \left(\Delta \mathbf{{x}_{A}}\right)"
assert latex(Laplacian(x*A.x)) == r"\Delta \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) == r"\mathrm{T}"
assert latex(TAU) == r"\tau"
assert latex(taU) == r"\tau"
# Check that all capitalized greek letters are handled explicitly
capitalized_letters = {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^{\mathrm{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}"
@_both_exp_pow
def test_latex_functions():
assert latex(exp(x)) == r"e^{x}"
assert latex(exp(1) + exp(2)) == r"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"
a_1 = Function('a_1')
assert latex(a_1) == r"a_{1}"
assert latex(a_1(x)) == r"a_{1}{\left(x \right)}"
assert latex(Function('a_1')) == r"a_{1}"
# Issue #16925
# multi letter function names
# > simple
assert latex(Function('ab')) == r"\operatorname{ab}"
assert latex(Function('ab1')) == r"\operatorname{ab}_{1}"
assert latex(Function('ab12')) == r"\operatorname{ab}_{12}"
assert latex(Function('ab_1')) == r"\operatorname{ab}_{1}"
assert latex(Function('ab_12')) == r"\operatorname{ab}_{12}"
assert latex(Function('ab_c')) == r"\operatorname{ab}_{c}"
assert latex(Function('ab_cd')) == r"\operatorname{ab}_{cd}"
# > with argument
assert latex(Function('ab')(Symbol('x'))) == r"\operatorname{ab}{\left(x \right)}"
assert latex(Function('ab1')(Symbol('x'))) == r"\operatorname{ab}_{1}{\left(x \right)}"
assert latex(Function('ab12')(Symbol('x'))) == r"\operatorname{ab}_{12}{\left(x \right)}"
assert latex(Function('ab_1')(Symbol('x'))) == r"\operatorname{ab}_{1}{\left(x \right)}"
assert latex(Function('ab_c')(Symbol('x'))) == r"\operatorname{ab}_{c}{\left(x \right)}"
assert latex(Function('ab_cd')(Symbol('x'))) == r"\operatorname{ab}_{cd}{\left(x \right)}"
# > with power
# does not work on functions without brackets
# > with argument and power combined
assert latex(Function('ab')()**2) == r"\operatorname{ab}^{2}{\left( \right)}"
assert latex(Function('ab1')()**2) == r"\operatorname{ab}_{1}^{2}{\left( \right)}"
assert latex(Function('ab12')()**2) == r"\operatorname{ab}_{12}^{2}{\left( \right)}"
assert latex(Function('ab_1')()**2) == r"\operatorname{ab}_{1}^{2}{\left( \right)}"
assert latex(Function('ab_12')()**2) == r"\operatorname{ab}_{12}^{2}{\left( \right)}"
assert latex(Function('ab')(Symbol('x'))**2) == r"\operatorname{ab}^{2}{\left(x \right)}"
assert latex(Function('ab1')(Symbol('x'))**2) == r"\operatorname{ab}_{1}^{2}{\left(x \right)}"
assert latex(Function('ab12')(Symbol('x'))**2) == r"\operatorname{ab}_{12}^{2}{\left(x \right)}"
assert latex(Function('ab_1')(Symbol('x'))**2) == r"\operatorname{ab}_{1}^{2}{\left(x \right)}"
assert latex(Function('ab_12')(Symbol('x'))**2) == \
r"\operatorname{ab}_{12}^{2}{\left(x \right)}"
# single letter function names
# > simple
assert latex(Function('a')) == r"a"
assert latex(Function('a1')) == r"a_{1}"
assert latex(Function('a12')) == r"a_{12}"
assert latex(Function('a_1')) == r"a_{1}"
assert latex(Function('a_12')) == r"a_{12}"
# > with argument
assert latex(Function('a')()) == r"a{\left( \right)}"
assert latex(Function('a1')()) == r"a_{1}{\left( \right)}"
assert latex(Function('a12')()) == r"a_{12}{\left( \right)}"
assert latex(Function('a_1')()) == r"a_{1}{\left( \right)}"
assert latex(Function('a_12')()) == r"a_{12}{\left( \right)}"
# > with power
# does not work on functions without brackets
# > with argument and power combined
assert latex(Function('a')()**2) == r"a^{2}{\left( \right)}"
assert latex(Function('a1')()**2) == r"a_{1}^{2}{\left( \right)}"
assert latex(Function('a12')()**2) == r"a_{12}^{2}{\left( \right)}"
assert latex(Function('a_1')()**2) == r"a_{1}^{2}{\left( \right)}"
assert latex(Function('a_12')()**2) == r"a_{12}^{2}{\left( \right)}"
assert latex(Function('a')(Symbol('x'))**2) == r"a^{2}{\left(x \right)}"
assert latex(Function('a1')(Symbol('x'))**2) == r"a_{1}^{2}{\left(x \right)}"
assert latex(Function('a12')(Symbol('x'))**2) == r"a_{12}^{2}{\left(x \right)}"
assert latex(Function('a_1')(Symbol('x'))**2) == r"a_{1}^{2}{\left(x \right)}"
assert latex(Function('a_12')(Symbol('x'))**2) == r"a_{12}^{2}{\left(x \right)}"
assert latex(Function('a')()**32) == r"a^{32}{\left( \right)}"
assert latex(Function('a1')()**32) == r"a_{1}^{32}{\left( \right)}"
assert latex(Function('a12')()**32) == r"a_{12}^{32}{\left( \right)}"
assert latex(Function('a_1')()**32) == r"a_{1}^{32}{\left( \right)}"
assert latex(Function('a_12')()**32) == r"a_{12}^{32}{\left( \right)}"
assert latex(Function('a')(Symbol('x'))**32) == r"a^{32}{\left(x \right)}"
assert latex(Function('a1')(Symbol('x'))**32) == r"a_{1}^{32}{\left(x \right)}"
assert latex(Function('a12')(Symbol('x'))**32) == r"a_{12}^{32}{\left(x \right)}"
assert latex(Function('a_1')(Symbol('x'))**32) == r"a_{1}^{32}{\left(x \right)}"
assert latex(Function('a_12')(Symbol('x'))**32) == r"a_{12}^{32}{\left(x \right)}"
assert latex(Function('a')()**a) == r"a^{a}{\left( \right)}"
assert latex(Function('a1')()**a) == r"a_{1}^{a}{\left( \right)}"
assert latex(Function('a12')()**a) == r"a_{12}^{a}{\left( \right)}"
assert latex(Function('a_1')()**a) == r"a_{1}^{a}{\left( \right)}"
assert latex(Function('a_12')()**a) == r"a_{12}^{a}{\left( \right)}"
assert latex(Function('a')(Symbol('x'))**a) == r"a^{a}{\left(x \right)}"
assert latex(Function('a1')(Symbol('x'))**a) == r"a_{1}^{a}{\left(x \right)}"
assert latex(Function('a12')(Symbol('x'))**a) == r"a_{12}^{a}{\left(x \right)}"
assert latex(Function('a_1')(Symbol('x'))**a) == r"a_{1}^{a}{\left(x \right)}"
assert latex(Function('a_12')(Symbol('x'))**a) == r"a_{12}^{a}{\left(x \right)}"
ab = Symbol('ab')
assert latex(Function('a')()**ab) == r"a^{ab}{\left( \right)}"
assert latex(Function('a1')()**ab) == r"a_{1}^{ab}{\left( \right)}"
assert latex(Function('a12')()**ab) == r"a_{12}^{ab}{\left( \right)}"
assert latex(Function('a_1')()**ab) == r"a_{1}^{ab}{\left( \right)}"
assert latex(Function('a_12')()**ab) == r"a_{12}^{ab}{\left( \right)}"
assert latex(Function('a')(Symbol('x'))**ab) == r"a^{ab}{\left(x \right)}"
assert latex(Function('a1')(Symbol('x'))**ab) == r"a_{1}^{ab}{\left(x \right)}"
assert latex(Function('a12')(Symbol('x'))**ab) == r"a_{12}^{ab}{\left(x \right)}"
assert latex(Function('a_1')(Symbol('x'))**ab) == r"a_{1}^{ab}{\left(x \right)}"
assert latex(Function('a_12')(Symbol('x'))**ab) == r"a_{12}^{ab}{\left(x \right)}"
assert latex(Function('a^12')(x)) == R"a^{12}{\left(x \right)}"
assert latex(Function('a^12')(x) ** ab) == R"\left(a^{12}\right)^{ab}{\left(x \right)}"
assert latex(Function('a__12')(x)) == R"a^{12}{\left(x \right)}"
assert latex(Function('a__12')(x) ** ab) == R"\left(a^{12}\right)^{ab}{\left(x \right)}"
assert latex(Function('a_1__1_2')(x)) == R"a^{1}_{1 2}{\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(asinh(x), inv_trig_style="full") == \
r"\operatorname{arsinh}{\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(LambertW(n) * LambertW(n)) == r"W^{2}\left(n\right)"
assert latex(Pow(LambertW(n), 2)) == r"W^{2}\left(n\right)"
assert latex(LambertW(n)**k) == r"W^{k}\left(n\right)"
assert latex(LambertW(n, k)**p) == r"W^{p}_{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(7, x + 1)) == r'7 \bmod \left(x + 1\right)'
assert latex(Mod(2 * x, 7)) == r'2 x \bmod 7'
assert latex(Mod(7, 2 * x)) == r'7 \bmod 2 x'
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)'
assert latex(Mod(7, 2 * x)**n) == r'\left(7 \bmod 2 x\right)^{n}'
# 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.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 == r'\Psi_{0} \overline{\Psi_{0}}'
assert indexed_latex == r'\overline{{\Psi}_{0}} {\Psi}_{0}'
# Symbol('gamma') gives r'\gamma'
interval = '\\mathrel{..}\\nobreak '
assert latex(Indexed('x1', Symbol('i'))) == r'{x_{1}}_{i}'
assert latex(Indexed('x2', Idx('i'))) == r'{x_{2}}_{i}'
assert latex(Indexed('x3', Idx('i', Symbol('N')))) == r'{x_{3}}_{{i}_{0'+interval+'N - 1}}'
assert latex(Indexed('x3', Idx('i', Symbol('N')+1))) == r'{x_{3}}_{{i}_{0'+interval+'N}}'
assert latex(Indexed('x4', Idx('i', (Symbol('a'),Symbol('b'))))) == r'{x_{4}}_{{i}_{a'+interval+'b}}'
assert latex(IndexedBase('gamma')) == r'\gamma'
assert latex(IndexedBase('a b')) == r'a b'
assert latex(IndexedBase('a_b')) == r'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))
# for negative nested Derivative
assert latex(diff(-diff(y**2,x,evaluate=False),x,evaluate=False)) == r'\frac{d}{d x} \left(- \frac{d}{d x} y^{2}\right)'
assert latex(diff(diff(-diff(diff(y,x,evaluate=False),x,evaluate=False),x,evaluate=False),x,evaluate=False)) == \
r'\frac{d^{2}}{d x^{2}} \left(- \frac{d^{2}}{d x^{2}} y\right)'
# 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)}'
# set diff operator
assert latex(diff(f(x), x), diff_operator="rd") == r'\frac{\mathrm{d}}{\mathrm{d} x} 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"
# for negative nested Integral
assert latex(Integral(-Integral(y**2,x),x)) == \
r'\int \left(- \int y^{2}\, dx\right)\, dx'
assert latex(Integral(-Integral(-Integral(y,x),x),x)) == \
r'\int \left(- \int \left(- \int y\, dx\right)\, dx\right)\, dx'
# 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"
# set diff operator
assert latex(Integral(x, x), diff_operator="rd") == r'\int x\, \mathrm{d}x'
assert latex(Integral(x, (x, 0, 1)), diff_operator="rd") == r'\int\limits_{0}^{1} x\, \mathrm{d}x'
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'\text{Range}\left(a, b, c\right)'
assert latex(Range(a, 10, 1)) == r'\text{Range}\left(a, 10\right)'
assert latex(Range(0, b, 1)) == r'\text{Range}\left(b\right)'
assert latex(Range(0, 10, c)) == r'\text{Range}\left(0, 10, c\right)'
i = Symbol('i', integer=True)
n = Symbol('n', negative=True, integer=True)
p = Symbol('p', positive=True, integer=True)
assert latex(Range(i, i + 3)) == r'\left\{i, i + 1, i + 2\right\}'
assert latex(Range(-oo, n, 2)) == r'\left\{\ldots, n - 4, n - 2\right\}'
assert latex(Range(p, oo)) == r'\left\{p, p + 1, \ldots\right\}'
# The following will work if __iter__ is improved
# assert latex(Range(-3, p + 7)) == r'\left\{-3, -2, \ldots, p + 6\right\}'
# Must have integer assumptions
assert latex(Range(a, a + 3)) == r'\text{Range}\left(a, a + 3\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_latex_powerset():
fset = FiniteSet(1, 2, 3)
assert latex(PowerSet(fset)) == r'\mathcal{P}\left(\left\{1, 2, 3\right\}\right)'
def test_latex_ordinals():
w = OrdinalOmega()
assert latex(w) == r"\omega"
wp = OmegaPower(2, 3)
assert latex(wp) == r'3 \omega^{2}'
assert latex(Ordinal(wp, OmegaPower(1, 1))) == r'3 \omega^{2} + \omega'
assert latex(Ordinal(OmegaPower(2, 1), OmegaPower(1, 2))) == r'\omega^{2} + 2 \omega'
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)) == \
r'\left\{a\right\} \cap ' \
r'\left(\left\{c\right\} \cup \left\{d\right\}\right)'
assert latex(Intersection(U1, U2, evaluate=False)) == \
r'\left(\left\{a\right\} \cup \left\{b\right\}\right) ' \
r'\cap \left(\left\{c\right\} \cup \left\{d\right\}\right)'
assert latex(Intersection(C1, C2, evaluate=False)) == \
r'\left(\left\{a\right\} \setminus ' \
r'\left\{b\right\}\right) \cap \left(\left\{c\right\} ' \
r'\setminus \left\{d\right\}\right)'
assert latex(Intersection(D1, D2, evaluate=False)) == \
r'\left(\left\{a\right\} \triangle ' \
r'\left\{b\right\}\right) \cap \left(\left\{c\right\} ' \
r'\triangle \left\{d\right\}\right)'
assert latex(Intersection(P1, P2, evaluate=False)) == \
r'\left(\left\{a\right\} \times \left\{b\right\}\right) ' \
r'\cap \left(\left\{c\right\} \times ' \
r'\left\{d\right\}\right)'
assert latex(Union(A, I2, evaluate=False)) == \
r'\left\{a\right\} \cup ' \
r'\left(\left\{c\right\} \cap \left\{d\right\}\right)'
assert latex(Union(I1, I2, evaluate=False)) == \
r'\left(\left\{a\right\} \cap \left\{b\right\}\right) ' \
r'\cup \left(\left\{c\right\} \cap \left\{d\right\}\right)'
assert latex(Union(C1, C2, evaluate=False)) == \
r'\left(\left\{a\right\} \setminus ' \
r'\left\{b\right\}\right) \cup \left(\left\{c\right\} ' \
r'\setminus \left\{d\right\}\right)'
assert latex(Union(D1, D2, evaluate=False)) == \
r'\left(\left\{a\right\} \triangle ' \
r'\left\{b\right\}\right) \cup \left(\left\{c\right\} ' \
r'\triangle \left\{d\right\}\right)'
assert latex(Union(P1, P2, evaluate=False)) == \
r'\left(\left\{a\right\} \times \left\{b\right\}\right) ' \
r'\cup \left(\left\{c\right\} \times ' \
r'\left\{d\right\}\right)'
assert latex(Complement(A, C2, evaluate=False)) == \
r'\left\{a\right\} \setminus \left(\left\{c\right\} ' \
r'\setminus \left\{d\right\}\right)'
assert latex(Complement(U1, U2, evaluate=False)) == \
r'\left(\left\{a\right\} \cup \left\{b\right\}\right) ' \
r'\setminus \left(\left\{c\right\} \cup ' \
r'\left\{d\right\}\right)'
assert latex(Complement(I1, I2, evaluate=False)) == \
r'\left(\left\{a\right\} \cap \left\{b\right\}\right) ' \
r'\setminus \left(\left\{c\right\} \cap ' \
r'\left\{d\right\}\right)'
assert latex(Complement(D1, D2, evaluate=False)) == \
r'\left(\left\{a\right\} \triangle ' \
r'\left\{b\right\}\right) \setminus ' \
r'\left(\left\{c\right\} \triangle \left\{d\right\}\right)'
assert latex(Complement(P1, P2, evaluate=False)) == \
r'\left(\left\{a\right\} \times \left\{b\right\}\right) '\
r'\setminus \left(\left\{c\right\} \times '\
r'\left\{d\right\}\right)'
assert latex(SymmetricDifference(A, D2, evaluate=False)) == \
r'\left\{a\right\} \triangle \left(\left\{c\right\} ' \
r'\triangle \left\{d\right\}\right)'
assert latex(SymmetricDifference(U1, U2, evaluate=False)) == \
r'\left(\left\{a\right\} \cup \left\{b\right\}\right) ' \
r'\triangle \left(\left\{c\right\} \cup ' \
r'\left\{d\right\}\right)'
assert latex(SymmetricDifference(I1, I2, evaluate=False)) == \
r'\left(\left\{a\right\} \cap \left\{b\right\}\right) ' \
r'\triangle \left(\left\{c\right\} \cap ' \
r'\left\{d\right\}\right)'
assert latex(SymmetricDifference(C1, C2, evaluate=False)) == \
r'\left(\left\{a\right\} \setminus ' \
r'\left\{b\right\}\right) \triangle ' \
r'\left(\left\{c\right\} \setminus \left\{d\right\}\right)'
assert latex(SymmetricDifference(P1, P2, evaluate=False)) == \
r'\left(\left\{a\right\} \times \left\{b\right\}\right) ' \
r'\triangle \left(\left\{c\right\} \times ' \
r'\left\{d\right\}\right)'
# XXX This can be incorrect since cartesian product is not associative
assert latex(ProductSet(A, P2).flatten()) == \
r'\left\{a\right\} \times \left\{c\right\} \times ' \
r'\left\{d\right\}'
assert latex(ProductSet(U1, U2)) == \
r'\left(\left\{a\right\} \cup \left\{b\right\}\right) ' \
r'\times \left(\left\{c\right\} \cup ' \
r'\left\{d\right\}\right)'
assert latex(ProductSet(I1, I2)) == \
r'\left(\left\{a\right\} \cap \left\{b\right\}\right) ' \
r'\times \left(\left\{c\right\} \cap ' \
r'\left\{d\right\}\right)'
assert latex(ProductSet(C1, C2)) == \
r'\left(\left\{a\right\} \setminus ' \
r'\left\{b\right\}\right) \times \left(\left\{c\right\} ' \
r'\setminus \left\{d\right\}\right)'
assert latex(ProductSet(D1, D2)) == \
r'\left(\left\{a\right\} \triangle ' \
r'\left\{b\right\}\right) \times \left(\left\{c\right\} ' \
r'\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}\; \middle|\; 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\; \middle|\; 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\; \middle|\; \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\; \middle|\; x \in \mathbb{R} \wedge x^{2} = 1 \right\}"
assert latex(ConditionSet(x, Eq(x**2, 1), S.UniversalSet)) == \
r"\left\{x\; \middle|\; x^{2} = 1 \right\}"
def test_latex_ComplexRegion():
assert latex(ComplexRegion(Interval(3, 5)*Interval(4, 6))) == \
r"\left\{x + y i\; \middle|\; 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)\; \middle|\; 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(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)) == r"8 \sqrt{2} \tau^{\frac{7}{2}}"
assert latex((2*mu)**Rational(7, 2), mode='equation*') == \
r"\begin{equation*}8 \sqrt{2} \mu^{\frac{7}{2}}\end{equation*}"
assert latex((2*mu)**Rational(7, 2), mode='equation', itex=True) == \
r"$$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_NumberSymbols():
assert latex(S.Catalan) == "G"
assert latex(S.EulerGamma) == r"\gamma"
assert latex(S.Exp1) == "e"
assert latex(S.GoldenRatio) == r"\phi"
assert latex(S.Pi) == r"\pi"
assert latex(S.TribonacciConstant) == r"\text{TribonacciConstant}"
def test_latex_rational():
# tests issue 3973
assert latex(-Rational(1, 2)) == r"- \frac{1}{2}"
assert latex(Rational(-1, 2)) == r"- \frac{1}{2}"
assert latex(Rational(1, -2)) == r"- \frac{1}{2}"
assert latex(-Rational(-1, 2)) == r"\frac{1}{2}"
assert latex(-Rational(1, 2)*x) == r"- \frac{x}{2}"
assert latex(-Rational(1, 2)*x + Rational(-2, 3)*y) == \
r"- \frac{x}{2} - \frac{2 y}{3}"
def test_latex_inverse():
# tests issue 4129
assert latex(1/x) == r"\frac{1}{x}"
assert latex(1/(x + y)) == r"\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) == r'x + y'
assert latex(expr, mode='plain') == r'x + y'
assert latex(expr, mode='inline') == r'$x + y$'
assert latex(
expr, mode='equation*') == r'\begin{equation*}x + y\end{equation*}'
assert latex(
expr, mode='equation') == r'\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) == r"\begin{cases} x & \text{for}\: x < 1 \\x^{2} &" \
r" \text{otherwise} \end{cases}"
assert latex(p, itex=True) == \
r"\begin{cases} x & \text{for}\: x \lt 1 \\x^{2} &" \
r" \text{otherwise} \end{cases}"
p = Piecewise((x, x < 0), (0, x >= 0))
assert latex(p) == r'\begin{cases} x & \text{for}\: x < 0 \\0 &' \
r' \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))) == \
r'\begin{cases} x & ' \
r'\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) == r"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) == \
r'\left[\begin{matrix}\frac{1}{x} & y\\z & w\end{matrix}\right]'
assert latex(M1) == \
r"\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') == r"4 \times 4^{x}"
assert latex(4*4**x, mul_symbol='dot') == r"4 \cdot 4^{x}"
assert latex(4*4**x, mul_symbol='ldot') == r"4 \,.\, 4^{x}"
assert latex(4*x, mul_symbol='times') == r"4 \times x"
assert latex(4*x, mul_symbol='dot') == r"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 r'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 r'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) == r"A B C^{-1}"
assert latex(C**-1*A*B) == r"C^{-1} A B"
assert latex(A*C**-1*B) == r"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') == r"x^{3} + x^{2} y + 3 x y^{3} + y^{4}"
assert latex(
expr, order='rev-lex') == r"y^{4} + 3 x y^{3} + x^{2} y + x^{3}"
assert latex(expr, order='none') == r"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)"
assert latex(Lambda(x, x)) == r"\left( x \mapsto x \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)) == \
r'\operatorname{Poly}{\left( a x^{5} + x^{4} + b x^{3} + 2 x^{2} + c'\
r' x + 3, x, domain=\mathbb{Z}\left[a, b, c\right] \right)}'
assert latex(Poly([a, 1, b+c, 2, 3], x)) == \
r'\operatorname{Poly}{\left( a x^{4} + x^{3} + \left(b + c\right) '\
r'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))) == \
r'\operatorname{Poly}{\left( a x^{3} + x^{2}y - b xy^{2} - xy - '\
r'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) == r"x"
assert latex(x, symbol_names={x: "x_i"}) == r"x_i"
assert latex(x + y, symbol_names={x: "x_i"}) == r"x_i + y"
assert latex(x**2, symbol_names={x: "x_i"}) == r"x_i^{2}"
assert latex(x + y, symbol_names={x: "x_i", y: "y_j"}) == r"x_i + y_j"
def test_matAdd():
C = MatrixSymbol('C', 5, 5)
B = MatrixSymbol('B', 5, 5)
n = symbols("n")
h = MatrixSymbol("h", 1, 1)
assert latex(C - 2*B) in [r'- 2 B + C', r'C -2 B']
assert latex(C + 2*B) in [r'2 B + C', r'C + 2 B']
assert latex(B - 2*C) in [r'B - 2 C', r'- 2 C + B']
assert latex(B + 2*C) in [r'B + 2 C', r'2 C + B']
assert latex(n * h - (-h + h.T) * (h + h.T)) == 'n h - \\left(- h + h^{T}\\right) \\left(h + h^{T}\\right)'
assert latex(MatAdd(MatAdd(h, h), MatAdd(h, h))) == '\\left(h + h\\right) + \\left(h + h\\right)'
assert latex(MatMul(MatMul(h, h), MatMul(h, h))) == '\\left(h h\\right) \\left(h h\\right)'
def test_matMul():
A = MatrixSymbol('A', 5, 5)
B = MatrixSymbol('B', 5, 5)
x = Symbol('x')
assert latex(2*A) == r'2 A'
assert latex(2*x*A) == r'2 x A'
assert latex(-2*A) == r'- 2 A'
assert latex(1.5*A) == r'1.5 A'
assert latex(sqrt(2)*A) == r'\sqrt{2} A'
assert latex(-sqrt(2)*A) == r'- \sqrt{2} A'
assert latex(2*sqrt(2)*x*A) == r'2 \sqrt{2} x A'
assert latex(-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():
n = Symbol('n', integer=True)
x, y, z, w, t, = symbols('x y z w t')
X = MatrixSymbol('X', n, n)
Y = MatrixSymbol('Y', 10, 10)
Z = MatrixSymbol('Z', 10, 10)
assert latex(MatrixSlice(X, (None, None, None), (None, None, None))) == r'X\left[:, :\right]'
assert latex(X[x:x + 1, y:y + 1]) == r'X\left[x:x + 1, y:y + 1\right]'
assert latex(X[x:x + 1:2, y:y + 1:2]) == r'X\left[x:x + 1:2, y:y + 1:2\right]'
assert latex(X[:x, y:]) == r'X\left[:x, y:\right]'
assert latex(X[:x, y:]) == r'X\left[:x, y:\right]'
assert latex(X[x:, :y]) == r'X\left[x:, :y\right]'
assert latex(X[x:y, z:w]) == r'X\left[x:y, z:w\right]'
assert latex(X[x:y:t, w:t:x]) == r'X\left[x:y:t, w:t:x\right]'
assert latex(X[x::y, t::w]) == r'X\left[x::y, t::w\right]'
assert latex(X[:x:y, :t:w]) == r'X\left[:x:y, :t:w\right]'
assert latex(X[::x, ::y]) == r'X\left[::x, ::y\right]'
assert latex(MatrixSlice(X, (0, None, None), (0, None, None))) == r'X\left[:, :\right]'
assert latex(MatrixSlice(X, (None, n, None), (None, n, None))) == r'X\left[:, :\right]'
assert latex(MatrixSlice(X, (0, n, None), (0, n, None))) == r'X\left[:, :\right]'
assert latex(MatrixSlice(X, (0, n, 2), (0, n, 2))) == r'X\left[::2, ::2\right]'
assert latex(X[1:2:3, 4:5:6]) == r'X\left[1:2:3, 4:5:6\right]'
assert latex(X[1:3:5, 4:6:8]) == r'X\left[1:3:5, 4:6:8\right]'
assert latex(X[1:10:2]) == r'X\left[1:10:2, :\right]'
assert latex(Y[:5, 1:9:2]) == r'Y\left[:5, 1:9:2\right]'
assert latex(Y[:5, 1:10:2]) == r'Y\left[:5, 1::2\right]'
assert latex(Y[5, :5:2]) == r'Y\left[5:6, :5:2\right]'
assert latex(X[0:1, 0:1]) == r'X\left[:1, :1\right]'
assert latex(X[0:1:2, 0:1:2]) == r'X\left[:1:2, :1:2\right]'
assert latex((Y + Z)[2:, 2:]) == r'\left(Y + Z\right)\left[2:, 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\} \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) == r"A_{1}"
assert latex(f1) == r"f_{1}:A_{1}\rightarrow A_{2}"
assert latex(id_A1) == r"id:A_{1}\rightarrow A_{1}"
assert latex(f2*f1) == r"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) == r"\begin{array}{cc}" + "\n" \
r"A & B \\" + "\n" \
r" & C " + "\n" \
r"\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_Determinant():
from sympy.matrices import Determinant, Inverse, BlockMatrix, OneMatrix, ZeroMatrix
m = Matrix(((1, 2), (3, 4)))
assert latex(Determinant(m)) == '\\left|{\\begin{matrix}1 & 2\\\\3 & 4\\end{matrix}}\\right|'
assert latex(Determinant(Inverse(m))) == \
'\\left|{\\left[\\begin{matrix}1 & 2\\\\3 & 4\\end{matrix}\\right]^{-1}}\\right|'
X = MatrixSymbol('X', 2, 2)
assert latex(Determinant(X)) == '\\left|{X}\\right|'
assert latex(Determinant(X + m)) == \
'\\left|{\\left[\\begin{matrix}1 & 2\\\\3 & 4\\end{matrix}\\right] + X}\\right|'
assert latex(Determinant(BlockMatrix(((OneMatrix(2, 2), X),
(m, ZeroMatrix(2, 2)))))) == \
'\\left|{\\begin{matrix}1 & X\\\\\\left[\\begin{matrix}1 & 2\\\\3 & 4\\end{matrix}\\right] & 0\\end{matrix}}\\right|'
def test_Adjoint():
from sympy.matrices import 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}'
m = Matrix(((1, 2), (3, 4)))
assert latex(Adjoint(m)) == '\\left[\\begin{matrix}1 & 2\\\\3 & 4\\end{matrix}\\right]^{\\dagger}'
assert latex(Adjoint(m+X)) == \
'\\left(\\left[\\begin{matrix}1 & 2\\\\3 & 4\\end{matrix}\\right] + X\\right)^{\\dagger}'
from sympy.matrices import BlockMatrix, OneMatrix, ZeroMatrix
assert latex(Adjoint(BlockMatrix(((OneMatrix(2, 2), X),
(m, ZeroMatrix(2, 2)))))) == \
'\\left[\\begin{matrix}1 & X\\\\\\left[\\begin{matrix}1 & 2\\\\3 & 4\\end{matrix}\\right] & 0\\end{matrix}\\right]^{\\dagger}'
# Issue 20959
Mx = MatrixSymbol('M^x', 2, 2)
assert latex(Adjoint(Mx)) == r'\left(M^{x}\right)^{\dagger}'
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}'
m = Matrix(((1, 2), (3, 4)))
assert latex(Transpose(m)) == '\\left[\\begin{matrix}1 & 2\\\\3 & 4\\end{matrix}\\right]^{T}'
assert latex(Transpose(m+X)) == \
'\\left(\\left[\\begin{matrix}1 & 2\\\\3 & 4\\end{matrix}\\right] + X\\right)^{T}'
from sympy.matrices import BlockMatrix, OneMatrix, ZeroMatrix
assert latex(Transpose(BlockMatrix(((OneMatrix(2, 2), X),
(m, ZeroMatrix(2, 2)))))) == \
'\\left[\\begin{matrix}1 & X\\\\\\left[\\begin{matrix}1 & 2\\\\3 & 4\\end{matrix}\\right] & 0\\end{matrix}\\right]^{T}'
# Issue 20959
Mx = MatrixSymbol('M^x', 2, 2)
assert latex(Transpose(Mx)) == r'\left(M^{x}\right)^{T}'
def test_Hadamard():
from sympy.matrices import 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_MatPow():
from sympy.matrices.expressions import MatPow
X = MatrixSymbol('X', 2, 2)
Y = MatrixSymbol('Y', 2, 2)
assert latex(MatPow(X, 2)) == 'X^{2}'
assert latex(MatPow(X*X, 2)) == '\\left(X^{2}\\right)^{2}'
assert latex(MatPow(X*Y, 2)) == '\\left(X Y\\right)^{2}'
assert latex(MatPow(X + Y, 2)) == '\\left(X + Y\\right)^{2}'
assert latex(MatPow(X + X, 2)) == '\\left(2 X\\right)^{2}'
# Issue 20959
Mx = MatrixSymbol('M^x', 2, 2)
assert latex(MatPow(Mx, 2)) == r'\left(M^{x}\right)^{2}'
def test_ElementwiseApplyFunction():
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( x \mapsto \frac{1}{x} \right)}_{\circ}\left({X}\right)'
def test_ZeroMatrix():
from sympy.matrices.expressions.special import ZeroMatrix
assert latex(ZeroMatrix(1, 1), mat_symbol_style='plain') == r"0"
assert latex(ZeroMatrix(1, 1), mat_symbol_style='bold') == r"\mathbf{0}"
def test_OneMatrix():
from sympy.matrices.expressions.special import OneMatrix
assert latex(OneMatrix(3, 4), mat_symbol_style='plain') == r"1"
assert latex(OneMatrix(3, 4), mat_symbol_style='bold') == r"\mathbf{1}"
def test_Identity():
from sympy.matrices.expressions.special 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_latex_DFT_IDFT():
from sympy.matrices.expressions.fourier import DFT, IDFT
assert latex(DFT(13)) == r"\text{DFT}_{13}"
assert latex(IDFT(x)) == r"\text{IDFT}_{x}"
def test_boolean_args_order():
syms = symbols('a:f')
expr = And(*syms)
assert latex(expr) == r'a \wedge b \wedge c \wedge d \wedge e \wedge f'
expr = Or(*syms)
assert latex(expr) == r'a \vee b \vee c \vee d \vee e \vee f'
expr = Equivalent(*syms)
assert latex(expr) == \
r'a \Leftrightarrow b \Leftrightarrow c \Leftrightarrow d \Leftrightarrow e \Leftrightarrow f'
expr = Xor(*syms)
assert latex(expr) == \
r'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'\mathrm{A}'
assert latex(s(x)) == r'\mathrm{A}{\left(x \right)}'
s = Function('Beta')
assert latex(s) == r'\mathrm{B}'
s = Function('Eta')
assert latex(s) == r'\mathrm{H}'
assert latex(s(x)) == r'\mathrm{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) == r'\mathrm{A}'
s = 'Beta'
assert translate(s) == r'\mathrm{B}'
s = 'Eta'
assert translate(s) == r'\mathrm{H}'
s = 'omicron'
assert translate(s) == r'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)) == r"" "\\" + 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'\mathrm{A}'
assert latex(Symbol('Beta')) == r'\mathrm{B}'
assert latex(Symbol('Gamma')) == r'\Gamma'
assert latex(Symbol('Delta')) == r'\Delta'
assert latex(Symbol('Epsilon')) == r'\mathrm{E}'
assert latex(Symbol('Zeta')) == r'\mathrm{Z}'
assert latex(Symbol('Eta')) == r'\mathrm{H}'
assert latex(Symbol('Theta')) == r'\Theta'
assert latex(Symbol('Iota')) == r'\mathrm{I}'
assert latex(Symbol('Kappa')) == r'\mathrm{K}'
assert latex(Symbol('Lambda')) == r'\Lambda'
assert latex(Symbol('Mu')) == r'\mathrm{M}'
assert latex(Symbol('Nu')) == r'\mathrm{N}'
assert latex(Symbol('Xi')) == r'\Xi'
assert latex(Symbol('Omicron')) == r'\mathrm{O}'
assert latex(Symbol('Pi')) == r'\Pi'
assert latex(Symbol('Rho')) == r'\mathrm{P}'
assert latex(Symbol('Sigma')) == r'\Sigma'
assert latex(Symbol('Tau')) == r'\mathrm{T}'
assert latex(Symbol('Upsilon')) == r'\Upsilon'
assert latex(Symbol('Phi')) == r'\Phi'
assert latex(Symbol('Chi')) == r'\mathrm{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) == r'\mathbb{Q}'
assert latex(S.Naturals) == r'\mathbb{N}'
assert latex(S.Naturals0) == r'\mathbb{N}_0'
assert latex(S.Integers) == r'\mathbb{Z}'
assert latex(S.Reals) == r'\mathbb{R}'
assert latex(S.Complexes) == r'\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"\left(- x\right) y"
def test_issue_2934():
assert latex(Symbol(r'\frac{a_1}{b_1}')) == r'\frac{a_1}{b_1}'
def test_issue_10489():
latexSymbolWithBrace = r'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_Series_printing():
tf1 = TransferFunction(x*y**2 - z, y**3 - t**3, y)
tf2 = TransferFunction(x - y, x + y, y)
tf3 = TransferFunction(t*x**2 - t**w*x + w, t - y, y)
assert latex(Series(tf1, tf2)) == \
r'\left(\frac{x y^{2} - z}{- t^{3} + y^{3}}\right) \left(\frac{x - y}{x + y}\right)'
assert latex(Series(tf1, tf2, tf3)) == \
r'\left(\frac{x y^{2} - z}{- t^{3} + y^{3}}\right) \left(\frac{x - y}{x + y}\right) \left(\frac{t x^{2} - t^{w} x + w}{t - y}\right)'
assert latex(Series(-tf2, tf1)) == \
r'\left(\frac{- x + y}{x + y}\right) \left(\frac{x y^{2} - z}{- t^{3} + y^{3}}\right)'
M_1 = Matrix([[5/s], [5/(2*s)]])
T_1 = TransferFunctionMatrix.from_Matrix(M_1, s)
M_2 = Matrix([[5, 6*s**3]])
T_2 = TransferFunctionMatrix.from_Matrix(M_2, s)
# Brackets
assert latex(T_1*(T_2 + T_2)) == \
r'\left[\begin{matrix}\frac{5}{s}\\\frac{5}{2 s}\end{matrix}\right]_\tau\cdot\left(\left[\begin{matrix}\frac{5}{1} &' \
r' \frac{6 s^{3}}{1}\end{matrix}\right]_\tau + \left[\begin{matrix}\frac{5}{1} & \frac{6 s^{3}}{1}\end{matrix}\right]_\tau\right)' \
== latex(MIMOSeries(MIMOParallel(T_2, T_2), T_1))
# No Brackets
M_3 = Matrix([[5, 6], [6, 5/s]])
T_3 = TransferFunctionMatrix.from_Matrix(M_3, s)
assert latex(T_1*T_2 + T_3) == r'\left[\begin{matrix}\frac{5}{s}\\\frac{5}{2 s}\end{matrix}\right]_\tau\cdot\left[\begin{matrix}' \
r'\frac{5}{1} & \frac{6 s^{3}}{1}\end{matrix}\right]_\tau + \left[\begin{matrix}\frac{5}{1} & \frac{6}{1}\\\frac{6}{1} & ' \
r'\frac{5}{s}\end{matrix}\right]_\tau' == latex(MIMOParallel(MIMOSeries(T_2, T_1), T_3))
def test_TransferFunction_printing():
tf1 = TransferFunction(x - 1, x + 1, x)
assert latex(tf1) == r"\frac{x - 1}{x + 1}"
tf2 = TransferFunction(x + 1, 2 - y, x)
assert latex(tf2) == r"\frac{x + 1}{2 - y}"
tf3 = TransferFunction(y, y**2 + 2*y + 3, y)
assert latex(tf3) == r"\frac{y}{y^{2} + 2 y + 3}"
def test_Parallel_printing():
tf1 = TransferFunction(x*y**2 - z, y**3 - t**3, y)
tf2 = TransferFunction(x - y, x + y, y)
assert latex(Parallel(tf1, tf2)) == \
r'\frac{x y^{2} - z}{- t^{3} + y^{3}} + \frac{x - y}{x + y}'
assert latex(Parallel(-tf2, tf1)) == \
r'\frac{- x + y}{x + y} + \frac{x y^{2} - z}{- t^{3} + y^{3}}'
M_1 = Matrix([[5, 6], [6, 5/s]])
T_1 = TransferFunctionMatrix.from_Matrix(M_1, s)
M_2 = Matrix([[5/s, 6], [6, 5/(s - 1)]])
T_2 = TransferFunctionMatrix.from_Matrix(M_2, s)
M_3 = Matrix([[6, 5/(s*(s - 1))], [5, 6]])
T_3 = TransferFunctionMatrix.from_Matrix(M_3, s)
assert latex(T_1 + T_2 + T_3) == r'\left[\begin{matrix}\frac{5}{1} & \frac{6}{1}\\\frac{6}{1} & \frac{5}{s}\end{matrix}\right]' \
r'_\tau + \left[\begin{matrix}\frac{5}{s} & \frac{6}{1}\\\frac{6}{1} & \frac{5}{s - 1}\end{matrix}\right]_\tau + \left[\begin{matrix}' \
r'\frac{6}{1} & \frac{5}{s \left(s - 1\right)}\\\frac{5}{1} & \frac{6}{1}\end{matrix}\right]_\tau' \
== latex(MIMOParallel(T_1, T_2, T_3)) == latex(MIMOParallel(T_1, MIMOParallel(T_2, T_3))) == latex(MIMOParallel(MIMOParallel(T_1, T_2), T_3))
def test_TransferFunctionMatrix_printing():
tf1 = TransferFunction(p, p + x, p)
tf2 = TransferFunction(-s + p, p + s, p)
tf3 = TransferFunction(p, y**2 + 2*y + 3, p)
assert latex(TransferFunctionMatrix([[tf1], [tf2]])) == \
r'\left[\begin{matrix}\frac{p}{p + x}\\\frac{p - s}{p + s}\end{matrix}\right]_\tau'
assert latex(TransferFunctionMatrix([[tf1, tf2], [tf3, -tf1]])) == \
r'\left[\begin{matrix}\frac{p}{p + x} & \frac{p - s}{p + s}\\\frac{p}{y^{2} + 2 y + 3} & \frac{\left(-1\right) p}{p + x}\end{matrix}\right]_\tau'
def test_Feedback_printing():
tf1 = TransferFunction(p, p + x, p)
tf2 = TransferFunction(-s + p, p + s, p)
# Negative Feedback (Default)
assert latex(Feedback(tf1, tf2)) == \
r'\frac{\frac{p}{p + x}}{\frac{1}{1} + \left(\frac{p}{p + x}\right) \left(\frac{p - s}{p + s}\right)}'
assert latex(Feedback(tf1*tf2, TransferFunction(1, 1, p))) == \
r'\frac{\left(\frac{p}{p + x}\right) \left(\frac{p - s}{p + s}\right)}{\frac{1}{1} + \left(\frac{p}{p + x}\right) \left(\frac{p - s}{p + s}\right)}'
# Positive Feedback
assert latex(Feedback(tf1, tf2, 1)) == \
r'\frac{\frac{p}{p + x}}{\frac{1}{1} - \left(\frac{p}{p + x}\right) \left(\frac{p - s}{p + s}\right)}'
assert latex(Feedback(tf1*tf2, sign=1)) == \
r'\frac{\left(\frac{p}{p + x}\right) \left(\frac{p - s}{p + s}\right)}{\frac{1}{1} - \left(\frac{p}{p + x}\right) \left(\frac{p - s}{p + s}\right)}'
def test_MIMOFeedback_printing():
tf1 = TransferFunction(1, s, s)
tf2 = TransferFunction(s, s**2 - 1, s)
tf3 = TransferFunction(s, s - 1, s)
tf4 = TransferFunction(s**2, s**2 - 1, s)
tfm_1 = TransferFunctionMatrix([[tf1, tf2], [tf3, tf4]])
tfm_2 = TransferFunctionMatrix([[tf4, tf3], [tf2, tf1]])
# Negative Feedback (Default)
assert latex(MIMOFeedback(tfm_1, tfm_2)) == \
r'\left(I_{\tau} + \left[\begin{matrix}\frac{1}{s} & \frac{s}{s^{2} - 1}\\\frac{s}{s - 1} & \frac{s^{2}}{s^{2} - 1}\end{matrix}\right]_\tau\cdot\left[' \
r'\begin{matrix}\frac{s^{2}}{s^{2} - 1} & \frac{s}{s - 1}\\\frac{s}{s^{2} - 1} & \frac{1}{s}\end{matrix}\right]_\tau\right)^{-1} \cdot \left[\begin{matrix}' \
r'\frac{1}{s} & \frac{s}{s^{2} - 1}\\\frac{s}{s - 1} & \frac{s^{2}}{s^{2} - 1}\end{matrix}\right]_\tau'
# Positive Feedback
assert latex(MIMOFeedback(tfm_1*tfm_2, tfm_1, 1)) == \
r'\left(I_{\tau} - \left[\begin{matrix}\frac{1}{s} & \frac{s}{s^{2} - 1}\\\frac{s}{s - 1} & \frac{s^{2}}{s^{2} - 1}\end{matrix}\right]_\tau\cdot\left' \
r'[\begin{matrix}\frac{s^{2}}{s^{2} - 1} & \frac{s}{s - 1}\\\frac{s}{s^{2} - 1} & \frac{1}{s}\end{matrix}\right]_\tau\cdot\left[\begin{matrix}\frac{1}{s} & \frac{s}{s^{2} - 1}' \
r'\\\frac{s}{s - 1} & \frac{s^{2}}{s^{2} - 1}\end{matrix}\right]_\tau\right)^{-1} \cdot \left[\begin{matrix}\frac{1}{s} & \frac{s}{s^{2} - 1}' \
r'\\\frac{s}{s - 1} & \frac{s^{2}}{s^{2} - 1}\end{matrix}\right]_\tau\cdot\left[\begin{matrix}\frac{s^{2}}{s^{2} - 1} & \frac{s}{s - 1}\\\frac{s}{s^{2} - 1}' \
r' & \frac{1}{s}\end{matrix}\right]_\tau'
def test_Quaternion_latex_printing():
q = Quaternion(x, y, z, t)
assert latex(q) == r"x + y i + z j + t k"
q = Quaternion(x, y, z, x*t)
assert latex(q) == r"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_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) == r"{}^{i}"
assert latex(-i) == r"{}_{i}"
expr = A(i)
assert latex(expr) == r"A{}^{i}"
expr = A(i0)
assert latex(expr) == r"A{}^{i_{0}}"
expr = A(-i)
assert latex(expr) == r"A{}_{i}"
expr = -3*A(i)
assert latex(expr) == r"-3A{}^{i}"
expr = K(i, j, -k, -i0)
assert latex(expr) == r"K{}^{ij}{}_{ki_{0}}"
expr = K(i, -j, -k, i0)
assert latex(expr) == r"K{}^{i}{}_{jk}{}^{i_{0}}"
expr = K(i, -j, k, -i0)
assert latex(expr) == r"K{}^{i}{}_{j}{}^{k}{}_{i_{0}}"
expr = H(i, -j)
assert latex(expr) == r"H{}^{i}{}_{j}"
expr = H(i, j)
assert latex(expr) == r"H{}^{ij}"
expr = H(-i, -j)
assert latex(expr) == r"H{}_{ij}"
expr = (1+x)*A(i)
assert latex(expr) == r"\left(x + 1\right)A{}^{i}"
expr = H(i, -i)
assert latex(expr) == r"H{}^{L_{0}}{}_{L_{0}}"
expr = H(i, -j)*A(j)*B(k)
assert latex(expr) == r"H{}^{i}{}_{L_{0}}A{}^{L_{0}}B{}^{k}"
expr = A(i) + 3*B(i)
assert latex(expr) == r"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) == r'K{}^{i=3,j,k=2,l}'
expr = TensorElement(K(i, j, k, l), {i: 3})
assert latex(expr) == r'K{}^{i=3,jkl}'
expr = TensorElement(K(i, -j, k, l), {i: 3, k: 2})
assert latex(expr) == r'K{}^{i=3}{}_{j}{}^{k=2,l}'
expr = TensorElement(K(i, -j, k, -l), {i: 3, k: 2})
assert latex(expr) == r'K{}^{i=3}{}_{j}{}^{k=2}{}_{l}'
expr = TensorElement(K(i, j, -k, -l), {i: 3, -k: 2})
assert latex(expr) == r'K{}^{i=3,j}{}_{k=2,l}'
expr = TensorElement(K(i, j, -k, -l), {i: 3})
assert latex(expr) == r'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():
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)\; \middle|\; \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_latex_symbolic_probability():
mu = symbols("mu")
sigma = symbols("sigma", positive=True)
X = Normal("X", mu, sigma)
assert latex(Expectation(X)) == r'\operatorname{E}\left[X\right]'
assert latex(Variance(X)) == r'\operatorname{Var}\left(X\right)'
assert latex(Probability(X > 0)) == r'\operatorname{P}\left(X > 0\right)'
Y = Normal("Y", mu, sigma)
assert latex(Covariance(X, Y)) == r'\operatorname{Cov}\left(X, Y\right)'
def test_trace():
# Issue 15303
from sympy.matrices.expressions.trace 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.core.basic import Basic
from sympy.core.expr import 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'\operatorname{UnimplementedExpr}\left(x\right)'
assert latex(unimplemented_expr(x**2)) == \
r'\operatorname{UnimplementedExpr}\left(x^{2}\right)'
assert latex(unimplemented_expr_sup_sub(x)) == \
r'\operatorname{UnimplementedExpr^{1}_{x}}\left(x\right)'
def test_MatrixSymbol_bold():
# Issue #15871
from sympy.matrices.expressions.trace 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_k = MatrixSymbol("A_k", 3, 3)
assert latex(A_k, mat_symbol_style='bold') == r"\mathbf{A}_{k}"
A = MatrixSymbol(r"\nabla_k", 3, 3)
assert latex(A, mat_symbol_style='bold') == r"\mathbf{\nabla}_{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_issue_21758():
from sympy.functions.elementary.piecewise import piecewise_fold
from sympy.series.fourier import FourierSeries
x = Symbol('x')
k, n = symbols('k n')
fo = FourierSeries(x, (x, -pi, pi), (0, SeqFormula(0, (k, 1, oo)), SeqFormula(
Piecewise((-2*pi*cos(n*pi)/n + 2*sin(n*pi)/n**2, (n > -oo) & (n < oo) & Ne(n, 0)),
(0, True))*sin(n*x)/pi, (n, 1, oo))))
assert latex(piecewise_fold(fo)) == '\\begin{cases} 2 \\sin{\\left(x \\right)}' \
' - \\sin{\\left(2 x \\right)} + \\frac{2 \\sin{\\left(3 x \\right)}}{3} +' \
' \\ldots & \\text{for}\\: n > -\\infty \\wedge n < \\infty \\wedge ' \
'n \\neq 0 \\\\0 & \\text{otherwise} \\end{cases}'
assert latex(FourierSeries(x, (x, -pi, pi), (0, SeqFormula(0, (k, 1, oo)),
SeqFormula(0, (n, 1, oo))))) == '0'
def test_imaginary_unit():
assert latex(1 + I) == r'1 + i'
assert latex(1 + I, imaginary_unit='i') == r'1 + i'
assert latex(1 + I, imaginary_unit='j') == r'1 + j'
assert latex(1 + I, imaginary_unit='foo') == r'1 + foo'
assert latex(I, imaginary_unit="ti") == r'\text{i}'
assert latex(I, imaginary_unit="tj") == r'\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_latex_diffgeom():
from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseScalarField, Differential
from sympy.diffgeom.rn import R2
x,y = symbols('x y', real=True)
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, [x, y])
assert latex(rect) == r'\text{rect}^{\text{P}}_{\text{M}}'
b = BaseScalarField(rect, 0)
assert latex(b) == r'\mathbf{x}'
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}}'
assert latex(4*micro*gram/second) == r'\frac{4 \mu \text{g}}{\text{s}}'
assert latex(5*milli*meter) == r'5 \text{m} \text{m}'
assert latex(milli) == r'\text{m}'
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)')
assert(latex((1,), decimal_separator='comma') == r'\left( 1;\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)')
assert(latex((1,), decimal_separator='period') == r'\left( 1,\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((1,)) == r'\left( 1,\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{,}8 \cdot 10^{-7}')
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'))
def test_Str():
from sympy.core.symbol import Str
assert str(Str('x')) == r'x'
def test_latex_escape():
assert latex_escape(r"~^\&%$#_{}") == "".join([
r'\textasciitilde',
r'\textasciicircum',
r'\textbackslash',
r'\&',
r'\%',
r'\$',
r'\#',
r'\_',
r'\{',
r'\}',
])
def test_emptyPrinter():
class MyObject:
def __repr__(self):
return "<MyObject with {...}>"
# unknown objects are monospaced
assert latex(MyObject()) == r"\mathtt{\text{<MyObject with \{...\}>}}"
# even if they are nested within other objects
assert latex((MyObject(),)) == r"\left( \mathtt{\text{<MyObject with \{...\}>}},\right)"
def test_global_settings():
import inspect
# settings should be visible in the signature of `latex`
assert inspect.signature(latex).parameters['imaginary_unit'].default == r'i'
assert latex(I) == r'i'
try:
# but changing the defaults...
LatexPrinter.set_global_settings(imaginary_unit='j')
# ... should change the signature
assert inspect.signature(latex).parameters['imaginary_unit'].default == r'j'
assert latex(I) == r'j'
finally:
# there's no public API to undo this, but we need to make sure we do
# so as not to impact other tests
del LatexPrinter._global_settings['imaginary_unit']
# check we really did undo it
assert inspect.signature(latex).parameters['imaginary_unit'].default == r'i'
assert latex(I) == r'i'
def test_pickleable():
# this tests that the _PrintFunction instance is pickleable
import pickle
assert pickle.loads(pickle.dumps(latex)) is latex
def test_printing_latex_array_expressions():
assert latex(ArraySymbol("A", (2, 3, 4))) == "A"
assert latex(ArrayElement("A", (2, 1/(1-x), 0))) == "{{A}_{2, \\frac{1}{1 - x}, 0}}"
M = MatrixSymbol("M", 3, 3)
N = MatrixSymbol("N", 3, 3)
assert latex(ArrayElement(M*N, [x, 0])) == "{{\\left(M N\\right)}_{x, 0}}"
def test_Array():
arr = Array(range(10))
assert latex(arr) == r'\left[\begin{matrix}0 & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9\end{matrix}\right]'
arr = Array(range(11))
# added empty arguments {}
assert latex(arr) == r'\left[\begin{array}{}0 & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10\end{array}\right]'
|
53b47dcce724196cbdf5fe52b43144f6531791c126324187cd88f550cd71ce07 | 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.printing.julia 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 // 7) * x"
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 // 5) * 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+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 // 5) * x .* y / 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 // 2) * im"
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 // 5) * pi ./ x]"
assert julia_code(A.T) == "[1, sin(2 ./ x), (3 // 5) * pi ./ 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]")
|
4ebc1796fcbf3bf5bac8095486182be09bcf046fefe4feeadaefbb599c388997 | from sympy.concrete.summations import Sum
from sympy.core.mod import Mod
from sympy.core.relational import (Equality, Unequality)
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.piecewise import Piecewise
from sympy.matrices.expressions.blockmatrix import BlockMatrix
from sympy.matrices.expressions.matexpr import MatrixSymbol
from sympy.matrices.expressions.special import Identity
from sympy.utilities.lambdify import lambdify
from sympy.abc import x, i, j, a, b, c, d
from sympy.core import Pow
from sympy.codegen.matrix_nodes import MatrixSolve
from sympy.codegen.numpy_nodes import logaddexp, logaddexp2
from sympy.codegen.cfunctions import log1p, expm1, hypot, log10, exp2, log2, Sqrt
from sympy.tensor.array import Array
from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct, ArrayAdd, \
PermuteDims, ArrayDiagonal
from sympy.printing.numpy import JaxPrinter, _jax_known_constants, _jax_known_functions
from sympy.tensor.array.expressions.conv_matrix_to_array import convert_matrix_to_array
from sympy.testing.pytest import skip, raises
from sympy.external import import_module
# Unlike NumPy which will aggressively promote operands to double precision,
# jax always uses single precision. Double precision in jax can be
# configured before the call to `import jax`, however this must be explicity
# configured and is not fully supported. Thus, the tests here have been modified
# from the tests in test_numpy.py, only in the fact that they assert lambdify
# function accuracy to only single precision accuracy.
# https://jax.readthedocs.io/en/latest/notebooks/Common_Gotchas_in_JAX.html#double-64bit-precision
jax = import_module('jax')
if jax:
deafult_float_info = jax.numpy.finfo(jax.numpy.array([]).dtype)
JAX_DEFAULT_EPSILON = deafult_float_info.eps
def test_jax_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 = JaxPrinter()
p = Piecewise((1, x < 0), (0, True))
assert printer.doprint(p) == \
'jax.numpy.select([jax.numpy.less(x, 0),True], [1,0], default=jax.numpy.nan)'
assert printer.module_imports == {'jax.numpy': {'select', 'less', 'nan'}}
def test_jax_logaddexp():
lae = logaddexp(a, b)
assert JaxPrinter().doprint(lae) == 'jax.numpy.logaddexp(a, b)'
lae2 = logaddexp2(a, b)
assert JaxPrinter().doprint(lae2) == 'jax.numpy.logaddexp2(a, b)'
def test_jax_sum():
if not jax:
skip("JAX not installed")
s = Sum(x ** i, (i, a, b))
f = lambdify((a, b, x), s, 'jax')
a_, b_ = 0, 10
x_ = jax.numpy.linspace(-1, +1, 10)
assert jax.numpy.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, 'jax')
a_, b_ = 0, 10
x_ = jax.numpy.linspace(-1, +1, 10)
assert jax.numpy.allclose(f(a_, b_, x_), sum(i_ * x_ for i_ in range(a_, b_ + 1)))
def test_jax_multiple_sums():
if not jax:
skip("JAX not installed")
s = Sum((x + j) * i, (i, a, b), (j, c, d))
f = lambdify((a, b, c, d, x), s, 'jax')
a_, b_ = 0, 10
c_, d_ = 11, 21
x_ = jax.numpy.linspace(-1, +1, 10)
assert jax.numpy.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_jax_codegen_einsum():
if not jax:
skip("JAX not installed")
M = MatrixSymbol("M", 2, 2)
N = MatrixSymbol("N", 2, 2)
cg = convert_matrix_to_array(M * N)
f = lambdify((M, N), cg, 'jax')
ma = jax.numpy.array([[1, 2], [3, 4]])
mb = jax.numpy.array([[1,-2], [-1, 3]])
assert (f(ma, mb) == jax.numpy.matmul(ma, mb)).all()
def test_jax_codegen_extra():
if not jax:
skip("JAX not installed")
M = MatrixSymbol("M", 2, 2)
N = MatrixSymbol("N", 2, 2)
P = MatrixSymbol("P", 2, 2)
Q = MatrixSymbol("Q", 2, 2)
ma = jax.numpy.array([[1, 2], [3, 4]])
mb = jax.numpy.array([[1,-2], [-1, 3]])
mc = jax.numpy.array([[2, 0], [1, 2]])
md = jax.numpy.array([[1,-1], [4, 7]])
cg = ArrayTensorProduct(M, N)
f = lambdify((M, N), cg, 'jax')
assert (f(ma, mb) == jax.numpy.einsum(ma, [0, 1], mb, [2, 3])).all()
cg = ArrayAdd(M, N)
f = lambdify((M, N), cg, 'jax')
assert (f(ma, mb) == ma+mb).all()
cg = ArrayAdd(M, N, P)
f = lambdify((M, N, P), cg, 'jax')
assert (f(ma, mb, mc) == ma+mb+mc).all()
cg = ArrayAdd(M, N, P, Q)
f = lambdify((M, N, P, Q), cg, 'jax')
assert (f(ma, mb, mc, md) == ma+mb+mc+md).all()
cg = PermuteDims(M, [1, 0])
f = lambdify((M,), cg, 'jax')
assert (f(ma) == ma.T).all()
cg = PermuteDims(ArrayTensorProduct(M, N), [1, 2, 3, 0])
f = lambdify((M, N), cg, 'jax')
assert (f(ma, mb) == jax.numpy.transpose(jax.numpy.einsum(ma, [0, 1], mb, [2, 3]), (1, 2, 3, 0))).all()
cg = ArrayDiagonal(ArrayTensorProduct(M, N), (1, 2))
f = lambdify((M, N), cg, 'jax')
assert (f(ma, mb) == jax.numpy.diagonal(jax.numpy.einsum(ma, [0, 1], mb, [2, 3]), axis1=1, axis2=2)).all()
def test_jax_relational():
if not jax:
skip("JAX not installed")
e = Equality(x, 1)
f = lambdify((x,), e, 'jax')
x_ = jax.numpy.array([0, 1, 2])
assert jax.numpy.array_equal(f(x_), [False, True, False])
e = Unequality(x, 1)
f = lambdify((x,), e, 'jax')
x_ = jax.numpy.array([0, 1, 2])
assert jax.numpy.array_equal(f(x_), [True, False, True])
e = (x < 1)
f = lambdify((x,), e, 'jax')
x_ = jax.numpy.array([0, 1, 2])
assert jax.numpy.array_equal(f(x_), [True, False, False])
e = (x <= 1)
f = lambdify((x,), e, 'jax')
x_ = jax.numpy.array([0, 1, 2])
assert jax.numpy.array_equal(f(x_), [True, True, False])
e = (x > 1)
f = lambdify((x,), e, 'jax')
x_ = jax.numpy.array([0, 1, 2])
assert jax.numpy.array_equal(f(x_), [False, False, True])
e = (x >= 1)
f = lambdify((x,), e, 'jax')
x_ = jax.numpy.array([0, 1, 2])
assert jax.numpy.array_equal(f(x_), [False, True, True])
# Multi-condition expressions
e = (x >= 1) & (x < 2)
f = lambdify((x,), e, 'jax')
x_ = jax.numpy.array([0, 1, 2])
assert jax.numpy.array_equal(f(x_), [False, True, False])
e = (x >= 1) | (x < 2)
f = lambdify((x,), e, 'jax')
x_ = jax.numpy.array([0, 1, 2])
assert jax.numpy.array_equal(f(x_), [True, True, True])
def test_jax_mod():
if not jax:
skip("JAX not installed")
e = Mod(a, b)
f = lambdify((a, b), e, 'jax')
a_ = jax.numpy.array([0, 1, 2, 3])
b_ = 2
assert jax.numpy.array_equal(f(a_, b_), [0, 1, 0, 1])
a_ = jax.numpy.array([0, 1, 2, 3])
b_ = jax.numpy.array([2, 2, 2, 2])
assert jax.numpy.array_equal(f(a_, b_), [0, 1, 0, 1])
a_ = jax.numpy.array([2, 3, 4, 5])
b_ = jax.numpy.array([2, 3, 4, 5])
assert jax.numpy.array_equal(f(a_, b_), [0, 0, 0, 0])
def test_jax_pow():
if not jax:
skip('JAX not installed')
expr = Pow(2, -1, evaluate=False)
f = lambdify([], expr, 'jax')
assert f() == 0.5
def test_jax_expm1():
if not jax:
skip("JAX not installed")
f = lambdify((a,), expm1(a), 'jax')
assert abs(f(1e-10) - 1e-10 - 5e-21) <= 1e-10 * JAX_DEFAULT_EPSILON
def test_jax_log1p():
if not jax:
skip("JAX not installed")
f = lambdify((a,), log1p(a), 'jax')
assert abs(f(1e-99) - 1e-99) <= 1e-99 * JAX_DEFAULT_EPSILON
def test_jax_hypot():
if not jax:
skip("JAX not installed")
assert abs(lambdify((a, b), hypot(a, b), 'jax')(3, 4) - 5) <= JAX_DEFAULT_EPSILON
def test_jax_log10():
if not jax:
skip("JAX not installed")
assert abs(lambdify((a,), log10(a), 'jax')(100) - 2) <= JAX_DEFAULT_EPSILON
def test_jax_exp2():
if not jax:
skip("JAX not installed")
assert abs(lambdify((a,), exp2(a), 'jax')(5) - 32) <= JAX_DEFAULT_EPSILON
def test_jax_log2():
if not jax:
skip("JAX not installed")
assert abs(lambdify((a,), log2(a), 'jax')(256) - 8) <= JAX_DEFAULT_EPSILON
def test_jax_Sqrt():
if not jax:
skip("JAX not installed")
assert abs(lambdify((a,), Sqrt(a), 'jax')(4) - 2) <= JAX_DEFAULT_EPSILON
def test_jax_sqrt():
if not jax:
skip("JAX not installed")
assert abs(lambdify((a,), sqrt(a), 'jax')(4) - 2) <= JAX_DEFAULT_EPSILON
def test_jax_matsolve():
if not jax:
skip("JAX 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, 'jax')
f_matsolve = lambdify((M, x), matsolve_expr, 'jax')
m0 = jax.numpy.array([[1, 2, 3], [3, 2, 5], [5, 6, 7]])
assert jax.numpy.linalg.matrix_rank(m0) == 3
x0 = jax.numpy.array([3, 4, 5])
assert jax.numpy.allclose(f_matsolve(m0, x0), f(m0, x0))
def test_16857():
if not jax:
skip("JAX 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 = JaxPrinter()
assert printer.doprint(A) == 'jax.numpy.block([[a_1, a_2], [a_3, a_4]])'
def test_issue_17006():
if not jax:
skip("JAX not installed")
M = MatrixSymbol("M", 2, 2)
f = lambdify(M, M + Identity(2), 'jax')
ma = jax.numpy.array([[1, 2], [3, 4]])
mr = jax.numpy.array([[2, 2], [3, 5]])
assert (f(ma) == mr).all()
from sympy.core.symbol import symbols
n = symbols('n', integer=True)
N = MatrixSymbol("M", n, n)
raises(NotImplementedError, lambda: lambdify(N, N + Identity(n), 'jax'))
def test_jax_array():
assert JaxPrinter().doprint(Array(((1, 2), (3, 5)))) == 'jax.numpy.array([[1, 2], [3, 5]])'
assert JaxPrinter().doprint(Array((1, 2))) == 'jax.numpy.array((1, 2))'
def test_jax_known_funcs_consts():
assert _jax_known_constants['NaN'] == 'jax.numpy.nan'
assert _jax_known_constants['EulerGamma'] == 'jax.numpy.euler_gamma'
assert _jax_known_functions['acos'] == 'jax.numpy.arccos'
assert _jax_known_functions['log'] == 'jax.numpy.log'
def test_jax_print_methods():
prntr = JaxPrinter()
assert hasattr(prntr, '_print_acos')
assert hasattr(prntr, '_print_log')
|
1cdec993341c2929c1ebbd7c8bb91a109679a5832abb9eb3d664a61d01b36389 | from sympy.core.function import (Derivative, Function)
from sympy.core.numbers import (I, Rational, oo, pi)
from sympy.core.relational import (Eq, Ge, Gt, Le, Lt, Ne)
from sympy.core.symbol import (Symbol, symbols)
from sympy.functions.elementary.complexes import (Abs, conjugate)
from sympy.functions.elementary.exponential import (exp, log)
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.trigonometric import sin
from sympy.integrals.integrals import Integral
from sympy.matrices.dense import Matrix
from sympy.series.limits import limit
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_issue_20762():
# Make sure Python removes curly braces from subscripted variables
a_b = Symbol('a_{b}')
b = Symbol('b')
expr = a_b*b
assert python(expr) == "a_b = Symbol('a_{b}')\nb = Symbol('b')\ne = a_b*b"
def test_settings():
raises(TypeError, lambda: python(x, method="garbage"))
|
a75e30b3953e508f4e0260210d4e78c7c23732923fd3e5c91239d43864a10ba4 | """
Important note on tests in this module - the Aesara 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 aesara_code_ and
aesara_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
from sympy.utilities.exceptions import ignore_warnings
aesaralogger = logging.getLogger('aesara.configdefaults')
aesaralogger.setLevel(logging.CRITICAL)
aesara = import_module('aesara')
aesaralogger.setLevel(logging.WARNING)
if aesara:
import numpy as np
aet = aesara.tensor
from aesara.scalar.basic import Scalar
from aesara.graph.basic import Variable
from aesara.tensor.var import TensorVariable
from aesara.tensor.elemwise import Elemwise, DimShuffle
from aesara.tensor.math import Dot
xt, yt, zt = [aet.scalar(name, 'floatX') for name in 'xyz']
Xt, Yt, Zt = [aet.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.core.singleton import S
from sympy.abc import x, y, z, t
from sympy.printing.aesaracode import (aesara_code, dim_handling,
aesara_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 aesara_code_(expr, **kwargs):
""" Wrapper for aesara_code that uses a new, empty cache by default. """
kwargs.setdefault('cache', {})
return aesara_code(expr, **kwargs)
def aesara_function_(inputs, outputs, **kwargs):
""" Wrapper for aesara_function that uses a new, empty cache by default. """
kwargs.setdefault('cache', {})
return aesara_function(inputs, outputs, **kwargs)
def fgraph_of(*exprs):
""" Transform SymPy expressions into Aesara Computation.
Parameters
==========
exprs
SymPy expressions
Returns
=======
aesara.graph.fg.FunctionGraph
"""
outs = list(map(aesara_code_, exprs))
ins = list(aesara.graph.basic.graph_inputs(outs))
ins, outs = aesara.graph.basic.clone(ins, outs)
return aesara.graph.fg.FunctionGraph(ins, outs)
def aesara_simplify(fgraph):
""" Simplify a Aesara Computation.
Parameters
==========
fgraph : aesara.graph.fg.FunctionGraph
Returns
=======
aesara.graph.fg.FunctionGraph
"""
mode = aesara.compile.get_default_mode().excluding("fusion")
fgraph = fgraph.clone()
mode.optimizer.optimize(fgraph)
return fgraph
def theq(a, b):
""" Test two Aesara 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 = aesara.printing.debugprint(a, file='str')
bstr = aesara.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(
'aesara.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 Aesara
equivalents, as many of the other tests depend on this.
"""
assert theq(xt, aesara_code_(x))
assert theq(yt, aesara_code_(y))
assert theq(zt, aesara_code_(z))
assert theq(Xt, aesara_code_(X))
assert theq(Yt, aesara_code_(Y))
assert theq(Zt, aesara_code_(Z))
def test_Symbol():
""" Test printing a Symbol to a aesara variable. """
xx = aesara_code_(x)
assert isinstance(xx, Variable)
assert xx.broadcastable == ()
assert xx.name == x.name
xx2 = aesara_code_(x, broadcastables={x: (False,)})
assert xx2.broadcastable == (False,)
assert xx2.name == x.name
def test_MatrixSymbol():
""" Test printing a MatrixSymbol to a aesara variable. """
XX = aesara_code_(X)
assert isinstance(XX, 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):
aesara_code_(X, broadcastables={X: bc})
def test_AppliedUndef():
""" Test printing AppliedUndef instance, which works similarly to Symbol. """
ftt = aesara_code_(f_t)
assert isinstance(ftt, TensorVariable)
assert ftt.broadcastable == ()
assert ftt.name == 'f_t'
def test_add():
expr = x + y
comp = aesara_code_(expr)
assert comp.owner.op == aesara.tensor.add
def test_trig():
assert theq(aesara_code_(sy.sin(x)), aet.sin(xt))
assert theq(aesara_code_(sy.tan(x)), aet.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 = aesara_code_(expr)
expected = aet.exp(xt**2 + aet.cos(yt)) * aet.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 aesara_code_(x, dtypes={x: dtype}).type.dtype == dtype
# "floatX" type
assert aesara_code_(x, dtypes={x: 'floatX'}).type.dtype in ('float32', 'float64')
# Type promotion
assert aesara_code_(x + 1, dtypes={x: 'float32'}).type.dtype == 'float32'
assert aesara_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 aesara_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 = aesara_code_(expr, broadcastables={x: bc1, y: bc2})
assert comp.broadcastable == bc3
def test_MatMul():
expr = X*Y*Z
expr_t = aesara_code_(expr)
assert isinstance(expr_t.owner.op, Dot)
assert theq(expr_t, Xt.dot(Yt).dot(Zt))
def test_Transpose():
assert isinstance(aesara_code_(X.T).owner.op, DimShuffle)
def test_MatAdd():
expr = X+Y+Z
assert isinstance(aesara_code_(expr).owner.op, Elemwise)
def test_Rationals():
assert theq(aesara_code_(sy.Integer(2) / 3), aet.true_div(2, 3))
assert theq(aesara_code_(S.Half), aet.true_div(1, 2))
def test_Integers():
assert aesara_code_(sy.Integer(3)) == 3
def test_factorial():
n = sy.Symbol('n')
assert aesara_code_(sy.factorial(n))
def test_Derivative():
with ignore_warnings(UserWarning):
simp = lambda expr: aesara_simplify(fgraph_of(expr))
assert theq(simp(aesara_code_(sy.Derivative(sy.sin(x), x, evaluate=False))),
simp(aesara.grad(aet.sin(xt), xt)))
def test_aesara_function_simple():
""" Test aesara_function() with single output. """
f = aesara_function_([x, y], [x+y])
assert f(2, 3) == 5
def test_aesara_function_multi():
""" Test aesara_function() with multiple outputs. """
f = aesara_function_([x, y], [x+y, x-y])
o1, o2 = f(2, 3)
assert o1 == 5
assert o2 == -1
def test_aesara_function_numpy():
""" Test aesara_function() vs Numpy implementation. """
f = aesara_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 = aesara_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_aesara_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 = aesara_function_([x, y, z], [m])
np.testing.assert_allclose(f(1.0, 2.0, 3.0), expected)
f = aesara_function_([x, y, z], [m], scalar=True)
np.testing.assert_allclose(f(1.0, 2.0, 3.0), expected)
f = aesara_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_aesara_function_kwargs():
"""
Test passing additional kwargs from aesara_function() to aesara.function().
"""
import numpy as np
f = aesara_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 = aesara_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_aesara_function_scalar():
""" Test the "scalar" argument to aesara_function(). """
from aesara.compile.function.types import 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 = aesara_function_(inputs, outputs, dims=in_dims, scalar=scalar)
# Check the aesara_function attribute is set whether wrapped or not
assert isinstance(f.aesara_function, 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.aesara_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_aesara_function_bad_kwarg():
"""
Passing an unknown keyword argument to aesara_function() should raise an
exception.
"""
raises(Exception, lambda : aesara_function_([x], [x+1], foobar=3))
def test_slice():
assert aesara_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(aesara_code_(slice(x, y), dtypes=dtypes), slice(xt, yt))
assert theq_slice(aesara_code_(slice(1, x, 3), dtypes=dtypes), slice(1, xt, 3))
def test_MatrixSlice():
cache = {}
n = sy.Symbol('n', integer=True)
X = sy.MatrixSymbol('X', n, n)
Y = X[1:2:3, 4:5:6]
Yt = aesara_code_(Y, cache=cache)
s = Scalar('int64')
assert tuple(Yt.owner.op.idx_list) == (slice(s, s, s), slice(s, s, s))
assert Yt.owner.inputs[0] == aesara_code_(X, cache=cache)
# == doesn't work in Aesara like it does in SymPy. You have to use
# equals.
assert all(Yt.owner.inputs[i].data == i for i in range(1, 7))
k = sy.Symbol('k')
aesara_code_(k, dtypes={k: 'int32'})
start, stop, step = 4, k, 2
Y = X[start:stop:step]
Yt = aesara_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(aesara_code_, (A, B, C, D))
Block = sy.BlockMatrix([[A, B], [C, D]])
Blockt = aesara_code_(Block)
solutions = [aet.join(0, aet.join(1, At, Bt), aet.join(1, Ct, Dt)),
aet.join(1, aet.join(0, At, Ct), aet.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 = aesara_function_(inputs, [output], dtypes=dtypes, cache={})
fblocked = aesara_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():
from aesara.tensor.basic import Join
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 = aesara_code_(X)
assert isinstance(tX, TensorVariable)
assert isinstance(tX.owner.op, 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 = aesara_code_(s1, cache=cache)
# Test hit with same instance
assert aesara_code_(s1, cache=cache) is st
# Test miss with same instance but new cache
assert aesara_code_(s1, cache={}) is not st
# Test hit with different but equivalent instance
assert aesara_code_(s2, cache=cache) is st
def test_global_cache():
""" Test use of the global cache. """
from sympy.printing.aesaracode import global_cache
backup = dict(global_cache)
try:
# Temporarily empty global cache
global_cache.clear()
for s in [x, X, f_t]:
st = aesara_code(s)
assert aesara_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 = aesara_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 aesara_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 = aesara_code_(expr)
assert theq(comp, xt + xt)
assert not theq(comp, xt + aesara_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 = aesara_code_(expr)
# Iterate through variables in the Aesara computational graph that the
# printed expression depends on
seen = set()
for v in aesara.graph.basic.ancestors([expr_t]):
# Owner-less, non-constant variables should be our symbols
if v.owner is None and not isinstance(v, aesara.graph.basic.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 = aesara_code_(expr)
assert result.owner.op == aet.switch
expected = aet.switch(xt<0, 0, aet.switch(xt<2, xt, 1))
assert theq(result, expected)
expr = sy.Piecewise((x, x < 0))
result = aesara_code_(expr)
expected = aet.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 = aesara_code_(expr)
expected = aet.switch(aet.and_(xt>0,xt<2), 0, \
aet.switch(aet.or_(xt>2, xt<0), xt, np.nan))
assert theq(result, expected)
def test_Relationals():
assert theq(aesara_code_(sy.Eq(x, y)), aet.eq(xt, yt))
# assert theq(aesara_code_(sy.Ne(x, y)), aet.neq(xt, yt)) # TODO - implement
assert theq(aesara_code_(x > y), xt > yt)
assert theq(aesara_code_(x < y), xt < yt)
assert theq(aesara_code_(x >= y), xt >= yt)
assert theq(aesara_code_(x <= y), xt <= yt)
def test_complexfunctions():
dtypes = {x:'complex128', y:'complex128'}
xt, yt = aesara_code(x, dtypes=dtypes), aesara_code(y, dtypes=dtypes)
from sympy.functions.elementary.complexes import conjugate
from aesara.tensor import as_tensor_variable as atv
from aesara.tensor import complex as cplx
assert theq(aesara_code(y*conjugate(x), dtypes=dtypes), yt*(xt.conj()))
assert theq(aesara_code((1+2j)*x), xt*(atv(1.0)+atv(2.0)*cplx(0,1)))
def test_constantfunctions():
tf = aesara_function([],[1+1j])
assert(tf()==1+1j)
|
f11d5b02959322042d6dfba5de51ffe6d9b6aa19baae3468e590f3b9ccd89d17 | from sympy.concrete.summations import Sum
from sympy.core.mod import Mod
from sympy.core.relational import (Equality, Unequality)
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.piecewise import Piecewise
from sympy.matrices.expressions.blockmatrix import BlockMatrix
from sympy.matrices.expressions.matexpr import MatrixSymbol
from sympy.matrices.expressions.special import Identity
from sympy.utilities.lambdify import lambdify
from sympy.abc import x, i, j, a, b, c, d
from sympy.core import Pow
from sympy.codegen.matrix_nodes import MatrixSolve
from sympy.codegen.numpy_nodes import logaddexp, logaddexp2
from sympy.codegen.cfunctions import log1p, expm1, hypot, log10, exp2, log2, Sqrt
from sympy.tensor.array import Array
from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct, ArrayAdd, \
PermuteDims, ArrayDiagonal
from sympy.printing.numpy import NumPyPrinter, SciPyPrinter, _numpy_known_constants, \
_numpy_known_functions, _scipy_known_constants, _scipy_known_functions
from sympy.tensor.array.expressions.conv_matrix_to_array import convert_matrix_to_array
from sympy.testing.pytest import skip, raises
from sympy.external import import_module
np = import_module('numpy')
if np:
deafult_float_info = np.finfo(np.array([]).dtype)
NUMPY_DEFAULT_EPSILON = deafult_float_info.eps
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_numpy_logaddexp():
lae = logaddexp(a, b)
assert NumPyPrinter().doprint(lae) == 'numpy.logaddexp(a, b)'
lae2 = logaddexp2(a, b)
assert NumPyPrinter().doprint(lae2) == 'numpy.logaddexp2(a, b)'
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 = convert_matrix_to_array(M * N)
f = lambdify((M, N), cg, 'numpy')
ma = np.array([[1, 2], [3, 4]])
mb = np.array([[1,-2], [-1, 3]])
assert (f(ma, mb) == np.matmul(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.array([[1, 2], [3, 4]])
mb = np.array([[1,-2], [-1, 3]])
mc = np.array([[2, 0], [1, 2]])
md = np.array([[1,-1], [4, 7]])
cg = ArrayTensorProduct(M, N)
f = lambdify((M, N), cg, 'numpy')
assert (f(ma, mb) == np.einsum(ma, [0, 1], mb, [2, 3])).all()
cg = ArrayAdd(M, N)
f = lambdify((M, N), cg, 'numpy')
assert (f(ma, mb) == ma+mb).all()
cg = ArrayAdd(M, N, P)
f = lambdify((M, N, P), cg, 'numpy')
assert (f(ma, mb, mc) == ma+mb+mc).all()
cg = ArrayAdd(M, N, P, Q)
f = lambdify((M, N, P, Q), cg, 'numpy')
assert (f(ma, mb, mc, md) == ma+mb+mc+md).all()
cg = PermuteDims(M, [1, 0])
f = lambdify((M,), cg, 'numpy')
assert (f(ma) == ma.T).all()
cg = PermuteDims(ArrayTensorProduct(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 = ArrayDiagonal(ArrayTensorProduct(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_pow():
if not np:
skip('NumPy not installed')
expr = Pow(2, -1, evaluate=False)
f = lambdify([], expr, 'numpy')
assert f() == 0.5
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-10 * NUMPY_DEFAULT_EPSILON
def test_log1p():
if not np:
skip("NumPy not installed")
f = lambdify((a,), log1p(a), 'numpy')
assert abs(f(1e-99) - 1e-99) <= 1e-99 * NUMPY_DEFAULT_EPSILON
def test_hypot():
if not np:
skip("NumPy not installed")
assert abs(lambdify((a, b), hypot(a, b), 'numpy')(3, 4) - 5) <= NUMPY_DEFAULT_EPSILON
def test_log10():
if not np:
skip("NumPy not installed")
assert abs(lambdify((a,), log10(a), 'numpy')(100) - 2) <= NUMPY_DEFAULT_EPSILON
def test_exp2():
if not np:
skip("NumPy not installed")
assert abs(lambdify((a,), exp2(a), 'numpy')(5) - 32) <= NUMPY_DEFAULT_EPSILON
def test_log2():
if not np:
skip("NumPy not installed")
assert abs(lambdify((a,), log2(a), 'numpy')(256) - 8) <= NUMPY_DEFAULT_EPSILON
def test_Sqrt():
if not np:
skip("NumPy not installed")
assert abs(lambdify((a,), Sqrt(a), 'numpy')(4) - 2) <= NUMPY_DEFAULT_EPSILON
def test_sqrt():
if not np:
skip("NumPy not installed")
assert abs(lambdify((a,), sqrt(a), 'numpy')(4) - 2) <= NUMPY_DEFAULT_EPSILON
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_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.core.symbol import symbols
n = symbols('n', integer=True)
N = MatrixSymbol("M", n, n)
raises(NotImplementedError, lambda: lambdify(N, N + Identity(n)))
def test_numpy_array():
assert NumPyPrinter().doprint(Array(((1, 2), (3, 5)))) == 'numpy.array([[1, 2], [3, 5]])'
assert NumPyPrinter().doprint(Array((1, 2))) == 'numpy.array((1, 2))'
def test_numpy_known_funcs_consts():
assert _numpy_known_constants['NaN'] == 'numpy.nan'
assert _numpy_known_constants['EulerGamma'] == 'numpy.euler_gamma'
assert _numpy_known_functions['acos'] == 'numpy.arccos'
assert _numpy_known_functions['log'] == 'numpy.log'
def test_scipy_known_funcs_consts():
assert _scipy_known_constants['GoldenRatio'] == 'scipy.constants.golden_ratio'
assert _scipy_known_constants['Pi'] == 'scipy.constants.pi'
assert _scipy_known_functions['erf'] == 'scipy.special.erf'
assert _scipy_known_functions['factorial'] == 'scipy.special.factorial'
def test_numpy_print_methods():
prntr = NumPyPrinter()
assert hasattr(prntr, '_print_acos')
assert hasattr(prntr, '_print_log')
def test_scipy_print_methods():
prntr = SciPyPrinter()
assert hasattr(prntr, '_print_acos')
assert hasattr(prntr, '_print_log')
assert hasattr(prntr, '_print_erf')
assert hasattr(prntr, '_print_factorial')
assert hasattr(prntr, '_print_chebyshevt')
|
b0cabb4c909b34853bf3a32f86cdc081f2f7fbd6b47153156e2decaa37727b63 | """
Utility functions for Rubi integration.
See: http://www.apmaths.uwo.ca/~arich/IntegrationRules/PortableDocumentFiles/Integration%20utility%20functions.pdf
"""
from sympy.external import import_module
matchpy = import_module("matchpy")
from sympy.concrete.summations import Sum
from sympy.core.add import Add
from sympy.core.basic import Basic
from sympy.core.containers import Dict
from sympy.core.evalf import N
from sympy.core.expr import UnevaluatedExpr
from sympy.core.exprtools import factor_terms
from sympy.core.function import (Function, WildFunction, expand, expand_trig)
from sympy.core.mul import Mul
from sympy.core.numbers import (E, Float, I, Integer, Rational, oo, pi, zoo)
from sympy.core.power import Pow
from sympy.core.singleton import S
from sympy.core.symbol import (Dummy, Symbol, Wild, symbols)
from sympy.core.sympify import sympify
from sympy.core.traversal import postorder_traversal
from sympy.functions.combinatorial.factorials import factorial
from sympy.functions.elementary.complexes import im, re, Abs, sign
from sympy.functions.elementary.exponential import exp as sym_exp, log as sym_log, LambertW
from sympy.functions.elementary.hyperbolic import acosh, asinh, atanh, acoth, acsch, asech, cosh, sinh, tanh, coth, sech, csch
from sympy.functions.elementary.integers import floor, frac
from sympy.functions.elementary.miscellaneous import (Max, Min, sqrt)
from sympy.functions.elementary.trigonometric import atan, acsc, asin, acot, acos, asec, atan2, sin, cos, tan, cot, csc, sec
from sympy.functions.special.elliptic_integrals import elliptic_f, elliptic_e, elliptic_pi
from sympy.functions.special.error_functions import erf, fresnelc, fresnels, erfc, erfi, Ei, expint, li, Si, Ci, Shi, Chi
from sympy.functions.special.gamma_functions import (digamma, gamma, loggamma, polygamma, uppergamma)
from sympy.functions.special.hyper import (appellf1, hyper, TupleArg)
from sympy.functions.special.zeta_functions import polylog, zeta
from sympy.integrals.integrals import Integral
from sympy.logic.boolalg import And, Or
from sympy.ntheory.factor_ import (factorint, factorrat)
from sympy.polys.partfrac import apart
from sympy.polys.polyerrors import (PolynomialDivisionFailed, PolynomialError, UnificationFailed)
from sympy.polys.polytools import (discriminant, factor, gcd, lcm, poly, sqf, sqf_list, Poly, degree, quo, rem, total_degree)
from sympy.sets.sets import FiniteSet
from sympy.simplify.powsimp import powdenest
from sympy.simplify.radsimp import collect
from sympy.simplify.simplify import fraction, simplify, cancel, powsimp, nsimplify
from sympy.utilities.decorator import doctest_depends_on
from sympy.utilities.iterables import flatten
from sympy.core.random import randint
class rubi_unevaluated_expr(UnevaluatedExpr):
"""
This is needed to convert `exp` as `Pow`.
SymPy's UnevaluatedExpr has an issue with `is_commutative`.
"""
@property
def is_commutative(self):
from sympy.core.logic import fuzzy_and
return fuzzy_and(a.is_commutative for a in self.args)
_E = rubi_unevaluated_expr(E)
class rubi_exp(Function):
"""
SymPy's exp is not identified as `Pow`. So it is not matched with `Pow`.
Like `a = exp(2)` is not identified as `Pow(E, 2)`. Rubi rules need it.
So, another exp has been created only for rubi module.
Examples
========
>>> from sympy import Pow, exp as sym_exp
>>> isinstance(sym_exp(2), Pow)
False
>>> from sympy.integrals.rubi.utility_function import rubi_exp
>>> isinstance(rubi_exp(2), Pow)
True
"""
@classmethod
def eval(cls, *args):
return Pow(_E, args[0])
class rubi_log(Function):
"""
For rule matching different `exp` has been used. So for proper results,
`log` is modified little only for case when it encounters rubi's `exp`.
For other cases it is same.
Examples
========
>>> from sympy.integrals.rubi.utility_function import rubi_exp, rubi_log
>>> a = rubi_exp(2)
>>> rubi_log(a)
2
"""
@classmethod
def eval(cls, *args):
if args[0].has(_E):
return sym_log(args[0]).doit()
else:
return sym_log(args[0])
if matchpy:
from matchpy import Arity, Operation, CustomConstraint, Pattern, ReplacementRule, ManyToOneReplacer
from sympy.integrals.rubi.symbol import WC
from matchpy import is_match, replace_all
class UtilityOperator(Operation):
name = 'UtilityOperator'
arity = Arity.variadic
commutative = False
associative = True
Operation.register(rubi_log)
Operation.register(rubi_exp)
A_, B_, C_, F_, G_, a_, b_, c_, d_, e_, f_, g_, h_, i_, j_, k_, l_, m_, \
n_, p_, q_, r_, t_, u_, v_, s_, w_, x_, z_ = [WC(i) for i in 'ABCFGabcdefghijklmnpqrtuvswxz']
a, b, c, d, e = symbols('a b c d e')
Int = Integral
def replace_pow_exp(z):
"""
This function converts back rubi's `exp` to general SymPy's `exp`.
Examples
========
>>> from sympy.integrals.rubi.utility_function import rubi_exp, replace_pow_exp
>>> expr = rubi_exp(5)
>>> expr
E**5
>>> replace_pow_exp(expr)
exp(5)
"""
z = S(z)
if z.has(_E):
z = z.replace(_E, E)
return z
def Simplify(expr):
expr = simplify(expr)
return expr
def Set(expr, value):
return {expr: value}
def With(subs, expr):
if isinstance(subs, dict):
k = list(subs.keys())[0]
expr = expr.xreplace({k: subs[k]})
else:
for i in subs:
k = list(i.keys())[0]
expr = expr.xreplace({k: i[k]})
return expr
def Module(subs, expr):
return With(subs, expr)
def Scan(f, expr):
# evaluates f applied to each element of expr in turn.
for i in expr:
yield f(i)
def MapAnd(f, l, x=None):
# MapAnd[f,l] applies f to the elements of list l until False is returned; else returns True
if x:
for i in l:
if f(i, x) == False:
return False
return True
else:
for i in l:
if f(i) == False:
return False
return True
def FalseQ(u):
if isinstance(u, (Dict, dict)):
return FalseQ(*list(u.values()))
return u == False
def ZeroQ(*expr):
if len(expr) == 1:
if isinstance(expr[0], list):
return list(ZeroQ(i) for i in expr[0])
else:
return Simplify(expr[0]) == 0
else:
return all(ZeroQ(i) for i in expr)
def OneQ(a):
if a == S(1):
return True
return False
def NegativeQ(u):
u = Simplify(u)
if u in (zoo, oo):
return False
if u.is_comparable:
res = u < 0
if not res.is_Relational:
return res
return False
def NonzeroQ(expr):
return Simplify(expr) != 0
def FreeQ(nodes, var):
if isinstance(nodes, list):
return not any(S(expr).has(var) for expr in nodes)
else:
nodes = S(nodes)
return not nodes.has(var)
def NFreeQ(nodes, var):
""" Note that in rubi 4.10.8 this function was not defined in `Integration Utility Functions.m`,
but was used in rules. So explicitly its returning `False`
"""
return False
# return not FreeQ(nodes, var)
def List(*var):
return list(var)
def PositiveQ(var):
var = Simplify(var)
if var in (zoo, oo):
return False
if var.is_comparable:
res = var > 0
if not res.is_Relational:
return res
return False
def PositiveIntegerQ(*args):
return all(var.is_Integer and PositiveQ(var) for var in args)
def NegativeIntegerQ(*args):
return all(var.is_Integer and NegativeQ(var) for var in args)
def IntegerQ(var):
var = Simplify(var)
if isinstance(var, (int, Integer)):
return True
else:
return var.is_Integer
def IntegersQ(*var):
return all(IntegerQ(i) for i in var)
def _ComplexNumberQ(var):
i = S(im(var))
if isinstance(i, (Integer, Float)):
return i != 0
else:
return False
def ComplexNumberQ(*var):
"""
ComplexNumberQ(m, n,...) returns True if m, n, ... are all explicit complex numbers, else it returns False.
Examples
========
>>> from sympy.integrals.rubi.utility_function import ComplexNumberQ
>>> from sympy import I
>>> ComplexNumberQ(1 + I*2, I)
True
>>> ComplexNumberQ(2, I)
False
"""
return all(_ComplexNumberQ(i) for i in var)
def PureComplexNumberQ(*var):
return all((_ComplexNumberQ(i) and re(i)==0) for i in var)
def RealNumericQ(u):
return u.is_real
def PositiveOrZeroQ(u):
return u.is_real and u >= 0
def NegativeOrZeroQ(u):
return u.is_real and u <= 0
def FractionOrNegativeQ(u):
return FractionQ(u) or NegativeQ(u)
def NegQ(var):
return Not(PosQ(var)) and NonzeroQ(var)
def Equal(a, b):
return a == b
def Unequal(a, b):
return a != b
def IntPart(u):
# IntPart[u] returns the sum of the integer terms of u.
if ProductQ(u):
if IntegerQ(First(u)):
return First(u)*IntPart(Rest(u))
elif IntegerQ(u):
return u
elif FractionQ(u):
return IntegerPart(u)
elif SumQ(u):
res = 0
for i in u.args:
res += IntPart(i)
return res
return 0
def FracPart(u):
# FracPart[u] returns the sum of the non-integer terms of u.
if ProductQ(u):
if IntegerQ(First(u)):
return First(u)*FracPart(Rest(u))
if IntegerQ(u):
return 0
elif FractionQ(u):
return FractionalPart(u)
elif SumQ(u):
res = 0
for i in u.args:
res += FracPart(i)
return res
else:
return u
def RationalQ(*nodes):
return all(var.is_Rational for var in nodes)
def ProductQ(expr):
return S(expr).is_Mul
def SumQ(expr):
return expr.is_Add
def NonsumQ(expr):
return not SumQ(expr)
def Subst(a, x, y):
if None in [a, x, y]:
return None
if a.has(Function('Integrate')):
# substituting in `Function(Integrate)` won't take care of properties of Integral
a = a.replace(Function('Integrate'), Integral)
return a.subs(x, y)
# return a.xreplace({x: y})
def First(expr, d=None):
"""
Gives the first element if it exists, or d otherwise.
Examples
========
>>> from sympy.integrals.rubi.utility_function import First
>>> from sympy.abc import a, b, c
>>> First(a + b + c)
a
>>> First(a*b*c)
a
"""
if isinstance(expr, list):
return expr[0]
if isinstance(expr, Symbol):
return expr
else:
if SumQ(expr) or ProductQ(expr):
l = Sort(expr.args)
return l[0]
else:
return expr.args[0]
def Rest(expr):
"""
Gives rest of the elements if it exists
Examples
========
>>> from sympy.integrals.rubi.utility_function import Rest
>>> from sympy.abc import a, b, c
>>> Rest(a + b + c)
b + c
>>> Rest(a*b*c)
b*c
"""
if isinstance(expr, list):
return expr[1:]
else:
if SumQ(expr) or ProductQ(expr):
l = Sort(expr.args)
return expr.func(*l[1:])
else:
return expr.args[1]
def SqrtNumberQ(expr):
# SqrtNumberQ[u] returns True if u^2 is a rational number; else it returns False.
if PowerQ(expr):
m = expr.base
n = expr.exp
return (IntegerQ(n) and SqrtNumberQ(m)) or (IntegerQ(n-S(1)/2) and RationalQ(m))
elif expr.is_Mul:
return all(SqrtNumberQ(i) for i in expr.args)
else:
return RationalQ(expr) or expr == I
def SqrtNumberSumQ(u):
return SumQ(u) and SqrtNumberQ(First(u)) and SqrtNumberQ(Rest(u)) or ProductQ(u) and SqrtNumberQ(First(u)) and SqrtNumberSumQ(Rest(u))
def LinearQ(expr, x):
"""
LinearQ(expr, x) returns True iff u is a polynomial of degree 1.
Examples
========
>>> from sympy.integrals.rubi.utility_function import LinearQ
>>> from sympy.abc import x, y, a
>>> LinearQ(a, x)
False
>>> LinearQ(3*x + y**2, x)
True
>>> LinearQ(3*x + y**2, y)
False
"""
if isinstance(expr, list):
return all(LinearQ(i, x) for i in expr)
elif expr.is_polynomial(x):
if degree(Poly(expr, x), gen=x) == 1:
return True
return False
def Sqrt(a):
return sqrt(a)
def ArcCosh(a):
return acosh(a)
class Util_Coefficient(Function):
def doit(self):
if len(self.args) == 2:
n = 1
else:
n = Simplify(self.args[2])
if NumericQ(n):
expr = expand(self.args[0])
if isinstance(n, (int, Integer)):
return expr.coeff(self.args[1], n)
else:
return expr.coeff(self.args[1]**n)
else:
return self
def Coefficient(expr, var, n=1):
"""
Coefficient(expr, var) gives the coefficient of form in the polynomial expr.
Coefficient(expr, var, n) gives the coefficient of var**n in expr.
Examples
========
>>> from sympy.integrals.rubi.utility_function import Coefficient
>>> from sympy.abc import x, a, b, c
>>> Coefficient(7 + 2*x + 4*x**3, x, 1)
2
>>> Coefficient(a + b*x + c*x**3, x, 0)
a
>>> Coefficient(a + b*x + c*x**3, x, 4)
0
>>> Coefficient(b*x + c*x**3, x, 3)
c
"""
if NumericQ(n):
if expr == 0 or n in (zoo, oo):
return 0
expr = expand(expr)
if isinstance(n, (int, Integer)):
return expr.coeff(var, n)
else:
return expr.coeff(var**n)
return Util_Coefficient(expr, var, n)
def Denominator(var):
var = Simplify(var)
if isinstance(var, Pow):
if isinstance(var.exp, Integer):
if var.exp > 0:
return Pow(Denominator(var.base), var.exp)
elif var.exp < 0:
return Pow(Numerator(var.base), -1*var.exp)
elif isinstance(var, Add):
var = factor(var)
return fraction(var)[1]
def Hypergeometric2F1(a, b, c, z):
return hyper([a, b], [c], z)
def Not(var):
if isinstance(var, bool):
return not var
elif var.is_Relational:
var = False
return not var
def FractionalPart(a):
return frac(a)
def IntegerPart(a):
return floor(a)
def AppellF1(a, b1, b2, c, x, y):
return appellf1(a, b1, b2, c, x, y)
def EllipticPi(*args):
return elliptic_pi(*args)
def EllipticE(*args):
return elliptic_e(*args)
def EllipticF(Phi, m):
return elliptic_f(Phi, m)
def ArcTan(a, b = None):
if b is None:
return atan(a)
else:
return atan2(a, b)
def ArcCot(a):
return acot(a)
def ArcCoth(a):
return acoth(a)
def ArcTanh(a):
return atanh(a)
def ArcSin(a):
return asin(a)
def ArcSinh(a):
return asinh(a)
def ArcCos(a):
return acos(a)
def ArcCsc(a):
return acsc(a)
def ArcSec(a):
return asec(a)
def ArcCsch(a):
return acsch(a)
def ArcSech(a):
return asech(a)
def Sinh(u):
return sinh(u)
def Tanh(u):
return tanh(u)
def Cosh(u):
return cosh(u)
def Sech(u):
return sech(u)
def Csch(u):
return csch(u)
def Coth(u):
return coth(u)
def LessEqual(*args):
for i in range(0, len(args) - 1):
try:
if args[i] > args[i + 1]:
return False
except (IndexError, NotImplementedError):
return False
return True
def Less(*args):
for i in range(0, len(args) - 1):
try:
if args[i] >= args[i + 1]:
return False
except (IndexError, NotImplementedError):
return False
return True
def Greater(*args):
for i in range(0, len(args) - 1):
try:
if args[i] <= args[i + 1]:
return False
except (IndexError, NotImplementedError):
return False
return True
def GreaterEqual(*args):
for i in range(0, len(args) - 1):
try:
if args[i] < args[i + 1]:
return False
except (IndexError, NotImplementedError):
return False
return True
def FractionQ(*args):
"""
FractionQ(m, n,...) returns True if m, n, ... are all explicit fractions, else it returns False.
Examples
========
>>> from sympy import S
>>> from sympy.integrals.rubi.utility_function import FractionQ
>>> FractionQ(S('3'))
False
>>> FractionQ(S('3')/S('2'))
True
"""
return all(i.is_Rational for i in args) and all(Denominator(i) != S(1) for i in args)
def IntLinearcQ(a, b, c, d, m, n, x):
# returns True iff (a+b*x)^m*(c+d*x)^n is integrable wrt x in terms of non-hypergeometric functions.
return IntegerQ(m) or IntegerQ(n) or IntegersQ(S(3)*m, S(3)*n) or IntegersQ(S(4)*m, S(4)*n) or IntegersQ(S(2)*m, S(6)*n) or IntegersQ(S(6)*m, S(2)*n) or IntegerQ(m + n)
Defer = UnevaluatedExpr
def Expand(expr):
return expr.expand()
def IndependentQ(u, x):
"""
If u is free from x IndependentQ(u, x) returns True else False.
Examples
========
>>> from sympy.integrals.rubi.utility_function import IndependentQ
>>> from sympy.abc import x, a, b
>>> IndependentQ(a + b*x, x)
False
>>> IndependentQ(a + b, x)
True
"""
return FreeQ(u, x)
def PowerQ(expr):
return expr.is_Pow or ExpQ(expr)
def IntegerPowerQ(u):
if isinstance(u, sym_exp): #special case for exp
return IntegerQ(u.args[0])
return PowerQ(u) and IntegerQ(u.args[1])
def PositiveIntegerPowerQ(u):
if isinstance(u, sym_exp):
return IntegerQ(u.args[0]) and PositiveQ(u.args[0])
return PowerQ(u) and IntegerQ(u.args[1]) and PositiveQ(u.args[1])
def FractionalPowerQ(u):
if isinstance(u, sym_exp):
return FractionQ(u.args[0])
return PowerQ(u) and FractionQ(u.args[1])
def AtomQ(expr):
expr = sympify(expr)
if isinstance(expr, list):
return False
if expr in [None, True, False, _E]: # [None, True, False] are atoms in mathematica and _E is also an atom
return True
# elif isinstance(expr, list):
# return all(AtomQ(i) for i in expr)
else:
return expr.is_Atom
def ExpQ(u):
u = replace_pow_exp(u)
return Head(u) in (sym_exp, rubi_exp)
def LogQ(u):
return u.func in (sym_log, Log)
def Head(u):
return u.func
def MemberQ(l, u):
if isinstance(l, list):
return u in l
else:
return u in l.args
def TrigQ(u):
if AtomQ(u):
x = u
else:
x = Head(u)
return MemberQ([sin, cos, tan, cot, sec, csc], x)
def SinQ(u):
return Head(u) == sin
def CosQ(u):
return Head(u) == cos
def TanQ(u):
return Head(u) == tan
def CotQ(u):
return Head(u) == cot
def SecQ(u):
return Head(u) == sec
def CscQ(u):
return Head(u) == csc
def Sin(u):
return sin(u)
def Cos(u):
return cos(u)
def Tan(u):
return tan(u)
def Cot(u):
return cot(u)
def Sec(u):
return sec(u)
def Csc(u):
return csc(u)
def HyperbolicQ(u):
if AtomQ(u):
x = u
else:
x = Head(u)
return MemberQ([sinh, cosh, tanh, coth, sech, csch], x)
def SinhQ(u):
return Head(u) == sinh
def CoshQ(u):
return Head(u) == cosh
def TanhQ(u):
return Head(u) == tanh
def CothQ(u):
return Head(u) == coth
def SechQ(u):
return Head(u) == sech
def CschQ(u):
return Head(u) == csch
def InverseTrigQ(u):
if AtomQ(u):
x = u
else:
x = Head(u)
return MemberQ([asin, acos, atan, acot, asec, acsc], x)
def SinCosQ(f):
return MemberQ([sin, cos, sec, csc], Head(f))
def SinhCoshQ(f):
return MemberQ([sinh, cosh, sech, csch], Head(f))
def LeafCount(expr):
return len(list(postorder_traversal(expr)))
def Numerator(u):
u = Simplify(u)
if isinstance(u, Pow):
if isinstance(u.exp, Integer):
if u.exp > 0:
return Pow(Numerator(u.base), u.exp)
elif u.exp < 0:
return Pow(Denominator(u.base), -1*u.exp)
elif isinstance(u, Add):
u = factor(u)
return fraction(u)[0]
def NumberQ(u):
if isinstance(u, (int, float)):
return True
return u.is_number
def NumericQ(u):
return N(u).is_number
def Length(expr):
"""
Returns number of elements in the expression just as SymPy's len.
Examples
========
>>> from sympy.integrals.rubi.utility_function import Length
>>> from sympy.abc import x, a, b
>>> from sympy import cos, sin
>>> Length(a + b)
2
>>> Length(sin(a)*cos(a))
2
"""
if isinstance(expr, list):
return len(expr)
return len(expr.args)
def ListQ(u):
return isinstance(u, list)
def Im(u):
u = S(u)
return im(u.doit())
def Re(u):
u = S(u)
return re(u.doit())
def InverseHyperbolicQ(u):
if not u.is_Atom:
u = Head(u)
return u in [acosh, asinh, atanh, acoth, acsch, acsch]
def InverseFunctionQ(u):
# returns True if u is a call on an inverse function; else returns False.
return LogQ(u) or InverseTrigQ(u) and Length(u) <= 1 or InverseHyperbolicQ(u) or u.func == polylog
def TrigHyperbolicFreeQ(u, x):
# If u is free of trig, hyperbolic and calculus functions involving x, TrigHyperbolicFreeQ[u,x] returns true; else it returns False.
if AtomQ(u):
return True
else:
if TrigQ(u) | HyperbolicQ(u) | CalculusQ(u):
return FreeQ(u, x)
else:
for i in u.args:
if not TrigHyperbolicFreeQ(i, x):
return False
return True
def InverseFunctionFreeQ(u, x):
# If u is free of inverse, calculus and hypergeometric functions involving x, InverseFunctionFreeQ[u,x] returns true; else it returns False.
if AtomQ(u):
return True
else:
if InverseFunctionQ(u) or CalculusQ(u) or u.func in (hyper, appellf1):
return FreeQ(u, x)
else:
for i in u.args:
if not ElementaryFunctionQ(i):
return False
return True
def RealQ(u):
if ListQ(u):
return MapAnd(RealQ, u)
elif NumericQ(u):
return ZeroQ(Im(N(u)))
elif PowerQ(u):
u = u.base
v = u.exp
return RealQ(u) & RealQ(v) & (IntegerQ(v) | PositiveOrZeroQ(u))
elif u.is_Mul:
return all(RealQ(i) for i in u.args)
elif u.is_Add:
return all(RealQ(i) for i in u.args)
elif u.is_Function:
f = u.func
u = u.args[0]
if f in [sin, cos, tan, cot, sec, csc, atan, acot, erf]:
return RealQ(u)
else:
if f in [asin, acos]:
return LessEqual(-1, u, 1)
else:
if f == sym_log:
return PositiveOrZeroQ(u)
else:
return False
else:
return False
def EqQ(u, v):
return ZeroQ(u - v)
def FractionalPowerFreeQ(u):
if AtomQ(u):
return True
elif FractionalPowerQ(u):
return False
def ComplexFreeQ(u):
if AtomQ(u) and Not(ComplexNumberQ(u)):
return True
else:
return False
def PolynomialQ(u, x = None):
if x is None :
return u.is_polynomial()
if isinstance(x, Pow):
if isinstance(x.exp, Integer):
deg = degree(u, x.base)
if u.is_polynomial(x):
if deg % x.exp !=0 :
return False
try:
p = Poly(u, x.base)
except PolynomialError:
return False
c_list = p.all_coeffs()
coeff_list = c_list[:-1:x.exp]
coeff_list += [c_list[-1]]
for i in coeff_list:
if not i == 0:
index = c_list.index(i)
c_list[index] = 0
if all(i == 0 for i in c_list):
return True
else:
return False
else:
return False
elif isinstance(x.exp, (Float, Rational)): #not full - proof
if FreeQ(simplify(u), x.base) and Exponent(u, x.base) == 0:
if not all(FreeQ(u, i) for i in x.base.free_symbols):
return False
if isinstance(x, Mul):
return all(PolynomialQ(u, i) for i in x.args)
return u.is_polynomial(x)
def FactorSquareFree(u):
return sqf(u)
def PowerOfLinearQ(expr, x):
u = Wild('u')
w = Wild('w')
m = Wild('m')
n = Wild('n')
Match = expr.match(u**m)
if PolynomialQ(Match[u], x) and FreeQ(Match[m], x):
if IntegerQ(Match[m]):
e = FactorSquareFree(Match[u]).match(w**n)
if FreeQ(e[n], x) and LinearQ(e[w], x):
return True
else:
return False
else:
return LinearQ(Match[u], x)
else:
return False
def Exponent(expr, x):
expr = Expand(S(expr))
if S(expr).is_number or (not expr.has(x)):
return 0
if PolynomialQ(expr, x):
if isinstance(x, Rational):
return degree(Poly(expr, x), x)
return degree(expr, gen = x)
else:
return 0
def ExponentList(expr, x):
expr = Expand(S(expr))
if S(expr).is_number or (not expr.has(x)):
return [0]
if expr.is_Add:
expr = collect(expr, x)
lst = []
k = 1
for t in expr.args:
if t.has(x):
if isinstance(x, Rational):
lst += [degree(Poly(t, x), x)]
else:
lst += [degree(t, gen = x)]
else:
if k == 1:
lst += [0]
k += 1
lst.sort()
return lst
else:
if isinstance(x, Rational):
return [degree(Poly(expr, x), x)]
else:
return [degree(expr, gen = x)]
def QuadraticQ(u, x):
# QuadraticQ(u, x) returns True iff u is a polynomial of degree 2 and not a monomial of the form a x^2
if ListQ(u):
for expr in u:
if Not(PolyQ(expr, x, 2) and Not(Coefficient(expr, x, 0) == 0 and Coefficient(expr, x, 1) == 0)):
return False
return True
else:
return PolyQ(u, x, 2) and Not(Coefficient(u, x, 0) == 0 and Coefficient(u, x, 1) == 0)
def LinearPairQ(u, v, x):
# LinearPairQ(u, v, x) returns True iff u and v are linear not equal x but u/v is a constant wrt x
return LinearQ(u, x) and LinearQ(v, x) and NonzeroQ(u-x) and ZeroQ(Coefficient(u, x, 0)*Coefficient(v, x, 1)-Coefficient(u, x, 1)*Coefficient(v, x, 0))
def BinomialParts(u, x):
if PolynomialQ(u, x):
if Exponent(u, x) > 0:
lst = ExponentList(u, x)
if len(lst)==1:
return [0, Coefficient(u, x, Exponent(u, x)), Exponent(u, x)]
elif len(lst) == 2 and lst[0] == 0:
return [Coefficient(u, x, 0), Coefficient(u, x, Exponent(u, x)), Exponent(u, x)]
else:
return False
else:
return False
elif PowerQ(u):
if u.base == x and FreeQ(u.exp, x):
return [0, 1, u.exp]
else:
return False
elif ProductQ(u):
if FreeQ(First(u), x):
lst2 = BinomialParts(Rest(u), x)
if AtomQ(lst2):
return False
else:
return [First(u)*lst2[0], First(u)*lst2[1], lst2[2]]
elif FreeQ(Rest(u), x):
lst1 = BinomialParts(First(u), x)
if AtomQ(lst1):
return False
else:
return [Rest(u)*lst1[0], Rest(u)*lst1[1], lst1[2]]
lst1 = BinomialParts(First(u), x)
if AtomQ(lst1):
return False
lst2 = BinomialParts(Rest(u), x)
if AtomQ(lst2):
return False
a = lst1[0]
b = lst1[1]
m = lst1[2]
c = lst2[0]
d = lst2[1]
n = lst2[2]
if ZeroQ(a):
if ZeroQ(c):
return [0, b*d, m + n]
elif ZeroQ(m + n):
return [b*d, b*c, m]
else:
return False
if ZeroQ(c):
if ZeroQ(m + n):
return [b*d, a*d, n]
else:
return False
if EqQ(m, n) and ZeroQ(a*d + b*c):
return [a*c, b*d, 2*m]
else:
return False
elif SumQ(u):
if FreeQ(First(u),x):
lst2 = BinomialParts(Rest(u), x)
if AtomQ(lst2):
return False
else:
return [First(u) + lst2[0], lst2[1], lst2[2]]
elif FreeQ(Rest(u), x):
lst1 = BinomialParts(First(u), x)
if AtomQ(lst1):
return False
else:
return[Rest(u) + lst1[0], lst1[1], lst1[2]]
lst1 = BinomialParts(First(u), x)
if AtomQ(lst1):
return False
lst2 = BinomialParts(Rest(u),x)
if AtomQ(lst2):
return False
if EqQ(lst1[2], lst2[2]):
return [lst1[0] + lst2[0], lst1[1] + lst2[1], lst1[2]]
else:
return False
else:
return False
def TrinomialParts(u, x):
# If u is equivalent to a trinomial of the form a + b*x^n + c*x^(2*n) where n!=0, b!=0 and c!=0, TrinomialParts[u,x] returns the list {a,b,c,n}; else it returns False.
u = sympify(u)
if PolynomialQ(u, x):
lst = CoefficientList(u, x)
if len(lst)<3 or EvenQ(sympify(len(lst))) or ZeroQ((len(lst)+1)/2):
return False
#Catch(
# Scan(Function(if ZeroQ(lst), Null, Throw(False), Drop(Drop(Drop(lst, [(len(lst)+1)/2]), 1), -1];
# [First(lst), lst[(len(lst)+1)/2], Last(lst), (len(lst)-1)/2]):
if PowerQ(u):
if EqQ(u.exp, 2):
lst = BinomialParts(u.base, x)
if not lst or ZeroQ(lst[0]):
return False
else:
return [lst[0]**2, 2*lst[0]*lst[1], lst[1]**2, lst[2]]
else:
return False
if ProductQ(u):
if FreeQ(First(u), x):
lst2 = TrinomialParts(Rest(u), x)
if not lst2:
return False
else:
return [First(u)*lst2[0], First(u)*lst2[1], First(u)*lst2[2], lst2[3]]
if FreeQ(Rest(u), x):
lst1 = TrinomialParts(First(u), x)
if not lst1:
return False
else:
return [Rest(u)*lst1[0], Rest(u)*lst1[1], Rest(u)*lst1[2], lst1[3]]
lst1 = BinomialParts(First(u), x)
if not lst1:
return False
lst2 = BinomialParts(Rest(u), x)
if not lst2:
return False
a = lst1[0]
b = lst1[1]
m = lst1[2]
c = lst2[0]
d = lst2[1]
n = lst2[2]
if EqQ(m, n) and NonzeroQ(a*d+b*c):
return [a*c, a*d + b*c, b*d, m]
else:
return False
if SumQ(u):
if FreeQ(First(u), x):
lst2 = TrinomialParts(Rest(u), x)
if not lst2:
return False
else:
return [First(u)+lst2[0], lst2[1], lst2[2], lst2[3]]
if FreeQ(Rest(u), x):
lst1 = TrinomialParts(First(u), x)
if not lst1:
return False
else:
return [Rest(u)+lst1[0], lst1[1], lst1[2], lst1[3]]
lst1 = TrinomialParts(First(u), x)
if not lst1:
lst3 = BinomialParts(First(u), x)
if not lst3:
return False
lst2 = TrinomialParts(Rest(u), x)
if not lst2:
lst4 = BinomialParts(Rest(u), x)
if not lst4:
return False
if EqQ(lst3[2], 2*lst4[2]):
return [lst3[0]+lst4[0], lst4[1], lst3[1], lst4[2]]
if EqQ(lst4[2], 2*lst3[2]):
return [lst3[0]+lst4[0], lst3[1], lst4[1], lst3[2]]
else:
return False
if EqQ(lst3[2], lst2[3]) and NonzeroQ(lst3[1]+lst2[1]):
return [lst3[0]+lst2[0], lst3[1]+lst2[1], lst2[2], lst2[3]]
if EqQ(lst3[2], 2*lst2[3]) and NonzeroQ(lst3[1]+lst2[2]):
return [lst3[0]+lst2[0], lst2[1], lst3[1]+lst2[2], lst2[3]]
else:
return False
lst2 = TrinomialParts(Rest(u), x)
if AtomQ(lst2):
lst4 = BinomialParts(Rest(u), x)
if not lst4:
return False
if EqQ(lst4[2], lst1[3]) and NonzeroQ(lst1[1]+lst4[0]):
return [lst1[0]+lst4[0], lst1[1]+lst4[1], lst1[2], lst1[3]]
if EqQ(lst4[2], 2*lst1[3]) and NonzeroQ(lst1[2]+lst4[1]):
return [lst1[0]+lst4[0], lst1[1], lst1[2]+lst4[1], lst1[3]]
else:
return False
if EqQ(lst1[3], lst2[3]) and NonzeroQ(lst1[1]+lst2[1]) and NonzeroQ(lst1[2]+lst2[2]):
return [lst1[0]+lst2[0], lst1[1]+lst2[1], lst1[2]+lst2[2], lst1[3]]
else:
return False
else:
return False
def PolyQ(u, x, n=None):
# returns True iff u is a polynomial of degree n.
if ListQ(u):
return all(PolyQ(i, x) for i in u)
if n is None:
if u == x:
return False
elif isinstance(x, Pow):
n = x.exp
x_base = x.base
if FreeQ(n, x_base):
if PositiveIntegerQ(n):
return PolyQ(u, x_base) and (PolynomialQ(u, x) or PolynomialQ(Together(u), x))
elif AtomQ(n):
return PolynomialQ(u, x) and FreeQ(CoefficientList(u, x), x_base)
else:
return False
return PolynomialQ(u, x) or PolynomialQ(u, Together(x))
else:
return PolynomialQ(u, x) and Coefficient(u, x, n) != 0 and Exponent(u, x) == n
def EvenQ(u):
# gives True if expr is an even integer, and False otherwise.
return isinstance(u, (Integer, int)) and u%2 == 0
def OddQ(u):
# gives True if expr is an odd integer, and False otherwise.
return isinstance(u, (Integer, int)) and u%2 == 1
def PerfectSquareQ(u):
# (* If u is a rational number whose squareroot is rational or if u is of the form u1^n1 u2^n2 ...
# and n1, n2, ... are even, PerfectSquareQ[u] returns True; else it returns False. *)
if RationalQ(u):
return Greater(u, 0) and RationalQ(Sqrt(u))
elif PowerQ(u):
return EvenQ(u.exp)
elif ProductQ(u):
return PerfectSquareQ(First(u)) and PerfectSquareQ(Rest(u))
elif SumQ(u):
s = Simplify(u)
if NonsumQ(s):
return PerfectSquareQ(s)
return False
else:
return False
def NiceSqrtAuxQ(u):
if RationalQ(u):
return u > 0
elif PowerQ(u):
return EvenQ(u.exp)
elif ProductQ(u):
return NiceSqrtAuxQ(First(u)) and NiceSqrtAuxQ(Rest(u))
elif SumQ(u):
s = Simplify(u)
return NonsumQ(s) and NiceSqrtAuxQ(s)
else:
return False
def NiceSqrtQ(u):
return Not(NegativeQ(u)) and NiceSqrtAuxQ(u)
def Together(u):
return factor(u)
def PosAux(u):
if RationalQ(u):
return u>0
elif NumberQ(u):
if ZeroQ(Re(u)):
return Im(u) > 0
else:
return Re(u) > 0
elif NumericQ(u):
v = N(u)
if ZeroQ(Re(v)):
return Im(v) > 0
else:
return Re(v) > 0
elif PowerQ(u):
if OddQ(u.exp):
return PosAux(u.base)
else:
return True
elif ProductQ(u):
if PosAux(First(u)):
return PosAux(Rest(u))
else:
return not PosAux(Rest(u))
elif SumQ(u):
return PosAux(First(u))
else:
res = u > 0
if res in(True, False):
return res
return True
def PosQ(u):
# If u is not 0 and has a positive form, PosQ[u] returns True, else it returns False.
return PosAux(TogetherSimplify(u))
def CoefficientList(u, x):
if PolynomialQ(u, x):
return list(reversed(Poly(u, x).all_coeffs()))
else:
return []
def ReplaceAll(expr, args):
if isinstance(args, list):
n_args = {}
for i in args:
n_args.update(i)
return expr.subs(n_args)
return expr.subs(args)
def ExpandLinearProduct(v, u, a, b, x):
# If u is a polynomial in x, ExpandLinearProduct[v,u,a,b,x] expands v*u into a sum of terms of the form c*v*(a+b*x)^n.
if FreeQ([a, b], x) and PolynomialQ(u, x):
lst = CoefficientList(ReplaceAll(u, {x: (x - a)/b}), x)
lst = [SimplifyTerm(i, x) for i in lst]
res = 0
for k in range(1, len(lst)+1):
res = res + Simplify(v*lst[k-1]*(a + b*x)**(k - 1))
return res
return u*v
def GCD(*args):
args = S(args)
if len(args) == 1:
if isinstance(args[0], (int, Integer)):
return args[0]
else:
return S(1)
return gcd(*args)
def ContentFactor(expn):
return factor_terms(expn)
def NumericFactor(u):
# returns the real numeric factor of u.
if NumberQ(u):
if ZeroQ(Im(u)):
return u
elif ZeroQ(Re(u)):
return Im(u)
else:
return S(1)
elif PowerQ(u):
if RationalQ(u.base) and RationalQ(u.exp):
if u.exp > 0:
return 1/Denominator(u.base)
else:
return 1/(1/Denominator(u.base))
else:
return S(1)
elif ProductQ(u):
return Mul(*[NumericFactor(i) for i in u.args])
elif SumQ(u):
if LeafCount(u) < 50:
c = ContentFactor(u)
if SumQ(c):
return S(1)
else:
return NumericFactor(c)
else:
m = NumericFactor(First(u))
n = NumericFactor(Rest(u))
if m < 0 and n < 0:
return -GCD(-m, -n)
else:
return GCD(m, n)
return S(1)
def NonnumericFactors(u):
if NumberQ(u):
if ZeroQ(Im(u)):
return S(1)
elif ZeroQ(Re(u)):
return I
return u
elif PowerQ(u):
if RationalQ(u.base) and FractionQ(u.exp):
return u/NumericFactor(u)
return u
elif ProductQ(u):
result = 1
for i in u.args:
result *= NonnumericFactors(i)
return result
elif SumQ(u):
if LeafCount(u) < 50:
i = ContentFactor(u)
if SumQ(i):
return u
else:
return NonnumericFactors(i)
n = NumericFactor(u)
result = 0
for i in u.args:
result += i/n
return result
return u
def MakeAssocList(u, x, alst=None):
# (* MakeAssocList[u,x,alst] returns an association list of gensymed symbols with the nonatomic
# parameters of a u that are not integer powers, products or sums. *)
if alst is None:
alst = []
u = replace_pow_exp(u)
x = replace_pow_exp(x)
if AtomQ(u):
return alst
elif IntegerPowerQ(u):
return MakeAssocList(u.base, x, alst)
elif ProductQ(u) or SumQ(u):
return MakeAssocList(Rest(u), x, MakeAssocList(First(u), x, alst))
elif FreeQ(u, x):
tmp = []
for i in alst:
if PowerQ(i):
if i.exp == u:
tmp.append(i)
break
elif len(i.args) > 1: # make sure args has length > 1, else causes index error some times
if i.args[1] == u:
tmp.append(i)
break
if tmp == []:
alst.append(u)
return alst
return alst
def GensymSubst(u, x, alst=None):
# (* GensymSubst[u,x,alst] returns u with the kernels in alst free of x replaced by gensymed names. *)
if alst is None:
alst =[]
u = replace_pow_exp(u)
x = replace_pow_exp(x)
if AtomQ(u):
return u
elif IntegerPowerQ(u):
return GensymSubst(u.base, x, alst)**u.exp
elif ProductQ(u) or SumQ(u):
return u.func(*[GensymSubst(i, x, alst) for i in u.args])
elif FreeQ(u, x):
tmp = []
for i in alst:
if PowerQ(i):
if i.exp == u:
tmp.append(i)
break
elif len(i.args) > 1: # make sure args has length > 1, else causes index error some times
if i.args[1] == u:
tmp.append(i)
break
if tmp == []:
return u
return tmp[0][0]
return u
def KernelSubst(u, x, alst):
# (* KernelSubst[u,x,alst] returns u with the gensymed names in alst replaced by kernels free of x. *)
if AtomQ(u):
tmp = []
for i in alst:
if i.args[0] == u:
tmp.append(i)
break
if tmp == []:
return u
elif len(tmp[0].args) > 1: # make sure args has length > 1, else causes index error some times
return tmp[0].args[1]
elif IntegerPowerQ(u):
tmp = KernelSubst(u.base, x, alst)
if u.exp < 0 and ZeroQ(tmp):
return 'Indeterminate'
return tmp**u.exp
elif ProductQ(u) or SumQ(u):
return u.func(*[KernelSubst(i, x, alst) for i in u.args])
return u
def ExpandExpression(u, x):
if AlgebraicFunctionQ(u, x) and Not(RationalFunctionQ(u, x)):
v = ExpandAlgebraicFunction(u, x)
else:
v = S(0)
if SumQ(v):
return ExpandCleanup(v, x)
v = SmartApart(u, x)
if SumQ(v):
return ExpandCleanup(v, x)
v = SmartApart(RationalFunctionFactors(u, x), x, x)
if SumQ(v):
w = NonrationalFunctionFactors(u, x)
return ExpandCleanup(v.func(*[i*w for i in v.args]), x)
v = Expand(u)
if SumQ(v):
return ExpandCleanup(v, x)
v = Expand(u)
if SumQ(v):
return ExpandCleanup(v, x)
return SimplifyTerm(u, x)
def Apart(u, x):
if RationalFunctionQ(u, x):
return apart(u, x)
return u
def SmartApart(*args):
if len(args) == 2:
u, x = args
alst = MakeAssocList(u, x)
tmp = KernelSubst(Apart(GensymSubst(u, x, alst), x), x, alst)
if tmp == 'Indeterminate':
return u
return tmp
u, v, x = args
alst = MakeAssocList(u, x)
tmp = KernelSubst(Apart(GensymSubst(u, x, alst), x), x, alst)
if tmp == 'Indeterminate':
return u
return tmp
def MatchQ(expr, pattern, *var):
# returns the matched arguments after matching pattern with expression
match = expr.match(pattern)
if match:
return tuple(match[i] for i in var)
else:
return None
def PolynomialQuotientRemainder(p, q, x):
return [PolynomialQuotient(p, q, x), PolynomialRemainder(p, q, x)]
def FreeFactors(u, x):
# returns the product of the factors of u free of x.
if ProductQ(u):
result = 1
for i in u.args:
if FreeQ(i, x):
result *= i
return result
elif FreeQ(u, x):
return u
else:
return S(1)
def NonfreeFactors(u, x):
"""
Returns the product of the factors of u not free of x.
Examples
========
>>> from sympy.integrals.rubi.utility_function import NonfreeFactors
>>> from sympy.abc import x, a, b
>>> NonfreeFactors(a, x)
1
>>> NonfreeFactors(x + a, x)
a + x
>>> NonfreeFactors(a*b*x, x)
x
"""
if ProductQ(u):
result = 1
for i in u.args:
if not FreeQ(i, x):
result *= i
return result
elif FreeQ(u, x):
return 1
else:
return u
def RemoveContentAux(expr, x):
return RemoveContentAux_replacer.replace(UtilityOperator(expr, x))
def RemoveContent(u, x):
v = NonfreeFactors(u, x)
w = Together(v)
if EqQ(FreeFactors(w, x), 1):
return RemoveContentAux(v, x)
else:
return RemoveContentAux(NonfreeFactors(w, x), x)
def FreeTerms(u, x):
"""
Returns the sum of the terms of u free of x.
Examples
========
>>> from sympy.integrals.rubi.utility_function import FreeTerms
>>> from sympy.abc import x, a, b
>>> FreeTerms(a, x)
a
>>> FreeTerms(x*a, x)
0
>>> FreeTerms(a*x + b, x)
b
"""
if SumQ(u):
result = 0
for i in u.args:
if FreeQ(i, x):
result += i
return result
elif FreeQ(u, x):
return u
else:
return 0
def NonfreeTerms(u, x):
# returns the sum of the terms of u free of x.
if SumQ(u):
result = S(0)
for i in u.args:
if not FreeQ(i, x):
result += i
return result
elif not FreeQ(u, x):
return u
else:
return S(0)
def ExpandAlgebraicFunction(expr, x):
if ProductQ(expr):
u_ = Wild('u', exclude=[x])
n_ = Wild('n', exclude=[x])
v_ = Wild('v')
pattern = u_*v_
match = expr.match(pattern)
if match:
keys = [u_, v_]
if len(keys) == len(match):
u, v = tuple([match[i] for i in keys])
if SumQ(v):
u, v = v, u
if not FreeQ(u, x) and SumQ(u):
result = 0
for i in u.args:
result += i*v
return result
pattern = u_**n_*v_
match = expr.match(pattern)
if match:
keys = [u_, n_, v_]
if len(keys) == len(match):
u, n, v = tuple([match[i] for i in keys])
if PositiveIntegerQ(n) and SumQ(u):
w = Expand(u**n)
result = 0
for i in w.args:
result += i*v
return result
return expr
def CollectReciprocals(expr, x):
# Basis: e/(a+b x)+f/(c+d x)==(c e+a f+(d e+b f) x)/(a c+(b c+a d) x+b d x^2)
if SumQ(expr):
u_ = Wild('u')
a_ = Wild('a', exclude=[x])
b_ = Wild('b', exclude=[x])
c_ = Wild('c', exclude=[x])
d_ = Wild('d', exclude=[x])
e_ = Wild('e', exclude=[x])
f_ = Wild('f', exclude=[x])
pattern = u_ + e_/(a_ + b_*x) + f_/(c_+d_*x)
match = expr.match(pattern)
if match:
try: # .match() does not work properly always
keys = [u_, a_, b_, c_, d_, e_, f_]
u, a, b, c, d, e, f = tuple([match[i] for i in keys])
if ZeroQ(b*c + a*d) & ZeroQ(d*e + b*f):
return CollectReciprocals(u + (c*e + a*f)/(a*c + b*d*x**2),x)
elif ZeroQ(b*c + a*d) & ZeroQ(c*e + a*f):
return CollectReciprocals(u + (d*e + b*f)*x/(a*c + b*d*x**2),x)
except:
pass
return expr
def ExpandCleanup(u, x):
v = CollectReciprocals(u, x)
if SumQ(v):
res = 0
for i in v.args:
res += SimplifyTerm(i, x)
v = res
if SumQ(v):
return UnifySum(v, x)
else:
return v
else:
return v
def AlgebraicFunctionQ(u, x, flag=False):
if ListQ(u):
if u == []:
return True
elif AlgebraicFunctionQ(First(u), x, flag):
return AlgebraicFunctionQ(Rest(u), x, flag)
else:
return False
elif AtomQ(u) or FreeQ(u, x):
return True
elif PowerQ(u):
if RationalQ(u.exp) | flag & FreeQ(u.exp, x):
return AlgebraicFunctionQ(u.base, x, flag)
elif ProductQ(u) | SumQ(u):
for i in u.args:
if not AlgebraicFunctionQ(i, x, flag):
return False
return True
return False
def Coeff(expr, form, n=1):
if n == 1:
return Coefficient(Together(expr), form, n)
else:
coef1 = Coefficient(expr, form, n)
coef2 = Coefficient(Together(expr), form, n)
if Simplify(coef1 - coef2) == 0:
return coef1
else:
return coef2
def LeadTerm(u):
if SumQ(u):
return First(u)
return u
def RemainingTerms(u):
if SumQ(u):
return Rest(u)
return u
def LeadFactor(u):
# returns the leading factor of u.
if ComplexNumberQ(u) and Re(u) == 0:
if Im(u) == S(1):
return u
else:
return LeadFactor(Im(u))
elif ProductQ(u):
return LeadFactor(First(u))
return u
def RemainingFactors(u):
# returns the remaining factors of u.
if ComplexNumberQ(u) and Re(u) == 0:
if Im(u) == 1:
return S(1)
else:
return I*RemainingFactors(Im(u))
elif ProductQ(u):
return RemainingFactors(First(u))*Rest(u)
return S(1)
def LeadBase(u):
"""
returns the base of the leading factor of u.
Examples
========
>>> from sympy.integrals.rubi.utility_function import LeadBase
>>> from sympy.abc import a, b, c
>>> LeadBase(a**b)
a
>>> LeadBase(a**b*c)
a
"""
v = LeadFactor(u)
if PowerQ(v):
return v.base
return v
def LeadDegree(u):
# returns the degree of the leading factor of u.
v = LeadFactor(u)
if PowerQ(v):
return v.exp
return v
def Numer(expr):
# returns the numerator of u.
if PowerQ(expr):
if expr.exp < 0:
return 1
if ProductQ(expr):
return Mul(*[Numer(i) for i in expr.args])
return Numerator(expr)
def Denom(u):
# returns the denominator of u
if PowerQ(u):
if u.exp < 0:
return u.args[0]**(-u.args[1])
elif ProductQ(u):
return Mul(*[Denom(i) for i in u.args])
return Denominator(u)
def hypergeom(n, d, z):
return hyper(n, d, z)
def Expon(expr, form):
return Exponent(Together(expr), form)
def MergeMonomials(expr, x):
u_ = Wild('u')
p_ = Wild('p', exclude=[x, 1, 0])
a_ = Wild('a', exclude=[x])
b_ = Wild('b', exclude=[x, 0])
c_ = Wild('c', exclude=[x])
d_ = Wild('d', exclude=[x, 0])
n_ = Wild('n', exclude=[x])
m_ = Wild('m', exclude=[x])
# Basis: If m/n\[Element]\[DoubleStruckCapitalZ], then z^m (c z^n)^p==(c z^n)^(m/n+p)/c^(m/n)
pattern = u_*(a_ + b_*x)**m_*(c_*(a_ + b_*x)**n_)**p_
match = expr.match(pattern)
if match:
keys = [u_, a_, b_, m_, c_, n_, p_]
if len(keys) == len(match):
u, a, b, m, c, n, p = tuple([match[i] for i in keys])
if IntegerQ(m/n):
if u*(c*(a + b*x)**n)**(m/n + p)/c**(m/n) is S.NaN:
return expr
else:
return u*(c*(a + b*x)**n)**(m/n + p)/c**(m/n)
# Basis: If m\[Element]\[DoubleStruckCapitalZ] \[And] b c-a d==0, then (a+b z)^m==b^m/d^m (c+d z)^m
pattern = u_*(a_ + b_*x)**m_*(c_ + d_*x)**n_
match = expr.match(pattern)
if match:
keys = [u_, a_, b_, m_, c_, d_, n_]
if len(keys) == len(match):
u, a, b, m, c, d, n = tuple([match[i] for i in keys])
if IntegerQ(m) and ZeroQ(b*c - a*d):
if u*b**m/d**m*(c + d*x)**(m + n) is S.NaN:
return expr
else:
return u*b**m/d**m*(c + d*x)**(m + n)
return expr
def PolynomialDivide(u, v, x):
quo = PolynomialQuotient(u, v, x)
rem = PolynomialRemainder(u, v, x)
s = 0
for i in ExponentList(quo, x):
s += Simp(Together(Coefficient(quo, x, i)*x**i), x)
quo = s
rem = Together(rem)
free = FreeFactors(rem, x)
rem = NonfreeFactors(rem, x)
monomial = x**Min(*ExponentList(rem, x))
if NegQ(Coefficient(rem, x, 0)):
monomial = -monomial
s = 0
for i in ExponentList(rem, x):
s += Simp(Together(Coefficient(rem, x, i)*x**i/monomial), x)
rem = s
if BinomialQ(v, x):
return quo + free*monomial*rem/ExpandToSum(v, x)
else:
return quo + free*monomial*rem/v
def BinomialQ(u, x, n=None):
"""
If u is equivalent to an expression of the form a + b*x**n, BinomialQ(u, x, n) returns True, else it returns False.
Examples
========
>>> from sympy.integrals.rubi.utility_function import BinomialQ
>>> from sympy.abc import x
>>> BinomialQ(x**9, x)
True
>>> BinomialQ((1 + x)**3, x)
False
"""
if ListQ(u):
for i in u:
if Not(BinomialQ(i, x, n)):
return False
return True
elif NumberQ(x):
return False
return ListQ(BinomialParts(u, x))
def TrinomialQ(u, x):
"""
If u is equivalent to an expression of the form a + b*x**n + c*x**(2*n) where n, b and c are not 0,
TrinomialQ(u, x) returns True, else it returns False.
Examples
========
>>> from sympy.integrals.rubi.utility_function import TrinomialQ
>>> from sympy.abc import x
>>> TrinomialQ((7 + 2*x**6 + 3*x**12), x)
True
>>> TrinomialQ(x**2, x)
False
"""
if ListQ(u):
for i in u.args:
if Not(TrinomialQ(i, x)):
return False
return True
check = False
u = replace_pow_exp(u)
if PowerQ(u):
if u.exp == 2 and BinomialQ(u.base, x):
check = True
return ListQ(TrinomialParts(u,x)) and Not(QuadraticQ(u, x)) and Not(check)
def GeneralizedBinomialQ(u, x):
"""
If u is equivalent to an expression of the form a*x**q+b*x**n where n, q and b are not 0,
GeneralizedBinomialQ(u, x) returns True, else it returns False.
Examples
========
>>> from sympy.integrals.rubi.utility_function import GeneralizedBinomialQ
>>> from sympy.abc import a, x, q, b, n
>>> GeneralizedBinomialQ(a*x**q, x)
False
"""
if ListQ(u):
return all(GeneralizedBinomialQ(i, x) for i in u)
return ListQ(GeneralizedBinomialParts(u, x))
def GeneralizedTrinomialQ(u, x):
"""
If u is equivalent to an expression of the form a*x**q+b*x**n+c*x**(2*n-q) where n, q, b and c are not 0,
GeneralizedTrinomialQ(u, x) returns True, else it returns False.
Examples
========
>>> from sympy.integrals.rubi.utility_function import GeneralizedTrinomialQ
>>> from sympy.abc import x
>>> GeneralizedTrinomialQ(7 + 2*x**6 + 3*x**12, x)
False
"""
if ListQ(u):
return all(GeneralizedTrinomialQ(i, x) for i in u)
return ListQ(GeneralizedTrinomialParts(u, x))
def FactorSquareFreeList(poly):
r = sqf_list(poly)
result = [[1, 1]]
for i in r[1]:
result.append(list(i))
return result
def PerfectPowerTest(u, x):
# If u (x) is equivalent to a polynomial raised to an integer power greater than 1,
# PerfectPowerTest[u,x] returns u (x) as an expanded polynomial raised to the power;
# else it returns False.
if PolynomialQ(u, x):
lst = FactorSquareFreeList(u)
gcd = 0
v = 1
if lst[0] == [1, 1]:
lst = Rest(lst)
for i in lst:
gcd = GCD(gcd, i[1])
if gcd > 1:
for i in lst:
v = v*i[0]**(i[1]/gcd)
return Expand(v)**gcd
else:
return False
return False
def SquareFreeFactorTest(u, x):
# If u (x) can be square free factored, SquareFreeFactorTest[u,x] returns u (x) in
# factored form; else it returns False.
if PolynomialQ(u, x):
v = FactorSquareFree(u)
if PowerQ(v) or ProductQ(v):
return v
return False
return False
def RationalFunctionQ(u, x):
# If u is a rational function of x, RationalFunctionQ[u,x] returns True; else it returns False.
if AtomQ(u) or FreeQ(u, x):
return True
elif IntegerPowerQ(u):
return RationalFunctionQ(u.base, x)
elif ProductQ(u) or SumQ(u):
for i in u.args:
if Not(RationalFunctionQ(i, x)):
return False
return True
return False
def RationalFunctionFactors(u, x):
# RationalFunctionFactors[u,x] returns the product of the factors of u that are rational functions of x.
if ProductQ(u):
res = 1
for i in u.args:
if RationalFunctionQ(i, x):
res *= i
return res
elif RationalFunctionQ(u, x):
return u
return S(1)
def NonrationalFunctionFactors(u, x):
if ProductQ(u):
res = 1
for i in u.args:
if not RationalFunctionQ(i, x):
res *= i
return res
elif RationalFunctionQ(u, x):
return S(1)
return u
def Reverse(u):
if isinstance(u, list):
return list(reversed(u))
else:
l = list(u.args)
return u.func(*list(reversed(l)))
def RationalFunctionExponents(u, x):
"""
u is a polynomial or rational function of x.
RationalFunctionExponents(u, x) returns a list of the exponent of the
numerator of u and the exponent of the denominator of u.
Examples
========
>>> from sympy.integrals.rubi.utility_function import RationalFunctionExponents
>>> from sympy.abc import x, a
>>> RationalFunctionExponents(x, x)
[1, 0]
>>> RationalFunctionExponents(x**(-1), x)
[0, 1]
>>> RationalFunctionExponents(x**(-1)*a, x)
[0, 1]
"""
if PolynomialQ(u, x):
return [Exponent(u, x), 0]
elif IntegerPowerQ(u):
if PositiveQ(u.exp):
return u.exp*RationalFunctionExponents(u.base, x)
return (-u.exp)*Reverse(RationalFunctionExponents(u.base, x))
elif ProductQ(u):
lst1 = RationalFunctionExponents(First(u), x)
lst2 = RationalFunctionExponents(Rest(u), x)
return [lst1[0] + lst2[0], lst1[1] + lst2[1]]
elif SumQ(u):
v = Together(u)
if SumQ(v):
lst1 = RationalFunctionExponents(First(u), x)
lst2 = RationalFunctionExponents(Rest(u), x)
return [Max(lst1[0] + lst2[1], lst2[0] + lst1[1]), lst1[1] + lst2[1]]
else:
return RationalFunctionExponents(v, x)
return [0, 0]
def RationalFunctionExpand(expr, x):
# expr is a polynomial or rational function of x.
# RationalFunctionExpand[u,x] returns the expansion of the factors of u that are rational functions times the other factors.
def cons_f1(n):
return FractionQ(n)
cons1 = CustomConstraint(cons_f1)
def cons_f2(x, v):
if not isinstance(x, Symbol):
return False
return UnsameQ(v, x)
cons2 = CustomConstraint(cons_f2)
def With1(n, u, x, v):
w = RationalFunctionExpand(u, x)
return If(SumQ(w), Add(*[i*v**n for i in w.args]), v**n*w)
pattern1 = Pattern(UtilityOperator(u_*v_**n_, x_), cons1, cons2)
rule1 = ReplacementRule(pattern1, With1)
def With2(u, x):
v = ExpandIntegrand(u, x)
def _consf_u(a, b, c, d, p, m, n, x):
return And(FreeQ(List(a, b, c, d, p), x), IntegersQ(m, n), Equal(m, Add(n, S(-1))))
cons_u = CustomConstraint(_consf_u)
pat = Pattern(UtilityOperator(x_**WC('m', S(1))*(x_*WC('d', S(1)) + c_)**p_/(x_**n_*WC('b', S(1)) + a_), x_), cons_u)
result_matchq = is_match(UtilityOperator(u, x), pat)
if UnsameQ(v, u) and not result_matchq:
return v
else:
v = ExpandIntegrand(RationalFunctionFactors(u, x), x)
w = NonrationalFunctionFactors(u, x)
if SumQ(v):
return Add(*[i*w for i in v.args])
else:
return v*w
pattern2 = Pattern(UtilityOperator(u_, x_))
rule2 = ReplacementRule(pattern2, With2)
expr = expr.replace(sym_exp, rubi_exp)
res = replace_all(UtilityOperator(expr, x), [rule1, rule2])
return replace_pow_exp(res)
def ExpandIntegrand(expr, x, extra=None):
expr = replace_pow_exp(expr)
if extra is not None:
extra, x = x, extra
w = ExpandIntegrand(extra, x)
r = NonfreeTerms(w, x)
if SumQ(r):
result = [expr*FreeTerms(w, x)]
for i in r.args:
result.append(MergeMonomials(expr*i, x))
return r.func(*result)
else:
return expr*FreeTerms(w, x) + MergeMonomials(expr*r, x)
else:
u_ = Wild('u', exclude=[0, 1])
a_ = Wild('a', exclude=[x])
b_ = Wild('b', exclude=[x, 0])
F_ = Wild('F', exclude=[0])
c_ = Wild('c', exclude=[x])
d_ = Wild('d', exclude=[x, 0])
n_ = Wild('n', exclude=[0, 1])
pattern = u_*(a_ + b_*F_)**n_
match = expr.match(pattern)
if match:
if MemberQ([asin, acos, asinh, acosh], match[F_].func):
keys = [u_, a_, b_, F_, n_]
if len(match) == len(keys):
u, a, b, F, n = tuple([match[i] for i in keys])
match = F.args[0].match(c_ + d_*x)
if match:
keys = c_, d_
if len(keys) == len(match):
c, d = tuple([match[i] for i in keys])
if PolynomialQ(u, x):
F = F.func
return ExpandLinearProduct((a + b*F(c + d*x))**n, u, c, d, x)
expr = expr.replace(sym_exp, rubi_exp)
res = replace_all(UtilityOperator(expr, x), ExpandIntegrand_rules, max_count = 1)
return replace_pow_exp(res)
def SimplerQ(u, v):
# If u is simpler than v, SimplerQ(u, v) returns True, else it returns False. SimplerQ(u, u) returns False
if IntegerQ(u):
if IntegerQ(v):
if Abs(u)==Abs(v):
return v<0
else:
return Abs(u)<Abs(v)
else:
return True
elif IntegerQ(v):
return False
elif FractionQ(u):
if FractionQ(v):
if Denominator(u) == Denominator(v):
return SimplerQ(Numerator(u), Numerator(v))
else:
return Denominator(u)<Denominator(v)
else:
return True
elif FractionQ(v):
return False
elif (Re(u)==0 or Re(u) == 0) and (Re(v)==0 or Re(v) == 0):
return SimplerQ(Im(u), Im(v))
elif ComplexNumberQ(u):
if ComplexNumberQ(v):
if Re(u) == Re(v):
return SimplerQ(Im(u), Im(v))
else:
return SimplerQ(Re(u),Re(v))
else:
return False
elif NumberQ(u):
if NumberQ(v):
return OrderedQ([u,v])
else:
return True
elif NumberQ(v):
return False
elif AtomQ(u) or (Head(u) == re) or (Head(u) == im):
if AtomQ(v) or (Head(u) == re) or (Head(u) == im):
return OrderedQ([u,v])
else:
return True
elif AtomQ(v) or (Head(u) == re) or (Head(u) == im):
return False
elif Head(u) == Head(v):
if Length(u) == Length(v):
for i in range(len(u.args)):
if not u.args[i] == v.args[i]:
return SimplerQ(u.args[i], v.args[i])
return False
return Length(u) < Length(v)
elif LeafCount(u) < LeafCount(v):
return True
elif LeafCount(v) < LeafCount(u):
return False
return Not(OrderedQ([v,u]))
def SimplerSqrtQ(u, v):
# If Rt(u, 2) is simpler than Rt(v, 2), SimplerSqrtQ(u, v) returns True, else it returns False. SimplerSqrtQ(u, u) returns False
if NegativeQ(v) and Not(NegativeQ(u)):
return True
if NegativeQ(u) and Not(NegativeQ(v)):
return False
sqrtu = Rt(u, S(2))
sqrtv = Rt(v, S(2))
if IntegerQ(sqrtu):
if IntegerQ(sqrtv):
return sqrtu<sqrtv
else:
return True
if IntegerQ(sqrtv):
return False
if RationalQ(sqrtu):
if RationalQ(sqrtv):
return sqrtu<sqrtv
else:
return True
if RationalQ(sqrtv):
return False
if PosQ(u):
if PosQ(v):
return LeafCount(sqrtu)<LeafCount(sqrtv)
else:
return True
if PosQ(v):
return False
if LeafCount(sqrtu)<LeafCount(sqrtv):
return True
if LeafCount(sqrtv)<LeafCount(sqrtu):
return False
else:
return Not(OrderedQ([v, u]))
def SumSimplerQ(u, v):
"""
If u + v is simpler than u, SumSimplerQ(u, v) returns True, else it returns False.
If for every term w of v there is a term of u equal to n*w where n<-1/2, u + v will be simpler than u.
Examples
========
>>> from sympy.integrals.rubi.utility_function import SumSimplerQ
>>> from sympy.abc import x
>>> from sympy import S
>>> SumSimplerQ(S(4 + x),S(3 + x**3))
False
"""
if RationalQ(u, v):
if v == S(0):
return False
elif v > S(0):
return u < -S(1)
else:
return u >= -v
else:
return SumSimplerAuxQ(Expand(u), Expand(v))
def BinomialDegree(u, x):
# if u is a binomial. BinomialDegree[u,x] returns the degree of x in u.
bp = BinomialParts(u, x)
if bp == False:
return bp
return bp[2]
def TrinomialDegree(u, x):
# If u is equivalent to a trinomial of the form a + b*x^n + c*x^(2*n) where n!=0, b!=0 and c!=0, TrinomialDegree[u,x] returns n
t = TrinomialParts(u, x)
if t:
return t[3]
return t
def CancelCommonFactors(u, v):
def _delete_cases(a, b):
# only for CancelCommonFactors
lst = []
deleted = False
for i in a.args:
if i == b and not deleted:
deleted = True
continue
lst.append(i)
return a.func(*lst)
# CancelCommonFactors[u,v] returns {u',v'} are the noncommon factors of u and v respectively.
if ProductQ(u):
if ProductQ(v):
if MemberQ(v, First(u)):
return CancelCommonFactors(Rest(u), _delete_cases(v, First(u)))
else:
lst = CancelCommonFactors(Rest(u), v)
return [First(u)*lst[0], lst[1]]
else:
if MemberQ(u, v):
return [_delete_cases(u, v), 1]
else:
return[u, v]
elif ProductQ(v):
if MemberQ(v, u):
return [1, _delete_cases(v, u)]
else:
return [u, v]
return[u, v]
def SimplerIntegrandQ(u, v, x):
lst = CancelCommonFactors(u, v)
u1 = lst[0]
v1 = lst[1]
if Head(u1) == Head(v1) and Length(u1) == 1 and Length(v1) == 1:
return SimplerIntegrandQ(u1.args[0], v1.args[0], x)
if 4*LeafCount(u1) < 3*LeafCount(v1):
return True
if RationalFunctionQ(u1, x):
if RationalFunctionQ(v1, x):
t1 = 0
t2 = 0
for i in RationalFunctionExponents(u1, x):
t1 += i
for i in RationalFunctionExponents(v1, x):
t2 += i
return t1 < t2
else:
return True
else:
return False
def GeneralizedBinomialDegree(u, x):
b = GeneralizedBinomialParts(u, x)
if b:
return b[2] - b[3]
def GeneralizedBinomialParts(expr, x):
expr = Expand(expr)
if GeneralizedBinomialMatchQ(expr, x):
a = Wild('a', exclude=[x])
b = Wild('b', exclude=[x])
n = Wild('n', exclude=[x])
q = Wild('q', exclude=[x])
Match = expr.match(a*x**q + b*x**n)
if Match and PosQ(Match[q] - Match[n]):
return [Match[b], Match[a], Match[q], Match[n]]
else:
return False
def GeneralizedTrinomialDegree(u, x):
t = GeneralizedTrinomialParts(u, x)
if t:
return t[3] - t[4]
def GeneralizedTrinomialParts(expr, x):
expr = Expand(expr)
if GeneralizedTrinomialMatchQ(expr, x):
a = Wild('a', exclude=[x, 0])
b = Wild('b', exclude=[x, 0])
c = Wild('c', exclude=[x])
n = Wild('n', exclude=[x, 0])
q = Wild('q', exclude=[x])
Match = expr.match(a*x**q + b*x**n+c*x**(2*n-q))
if Match and expr.is_Add:
return [Match[c], Match[b], Match[a], Match[n], 2*Match[n]-Match[q]]
else:
return False
def MonomialQ(u, x):
# If u is of the form a*x^n where n!=0 and a!=0, MonomialQ[u,x] returns True; else False
if isinstance(u, list):
return all(MonomialQ(i, x) for i in u)
else:
a = Wild('a', exclude=[x])
b = Wild('b', exclude=[x])
re = u.match(a*x**b)
if re:
return True
return False
def MonomialSumQ(u, x):
# if u(x) is a sum and each term is free of x or an expression of the form a*x^n, MonomialSumQ(u, x) returns True; else it returns False
if SumQ(u):
for i in u.args:
if Not(FreeQ(i, x) or MonomialQ(i, x)):
return False
return True
@doctest_depends_on(modules=('matchpy',))
def MinimumMonomialExponent(u, x):
"""
u is sum whose terms are monomials. MinimumMonomialExponent(u, x) returns the exponent of the term having the smallest exponent
Examples
========
>>> from sympy.integrals.rubi.utility_function import MinimumMonomialExponent
>>> from sympy.abc import x
>>> MinimumMonomialExponent(x**2 + 5*x**2 + 3*x**5, x)
2
>>> MinimumMonomialExponent(x**2 + 5*x**2 + 1, x)
0
"""
n =MonomialExponent(First(u), x)
for i in u.args:
if PosQ(n - MonomialExponent(i, x)):
n = MonomialExponent(i, x)
return n
def MonomialExponent(u, x):
# u is a monomial. MonomialExponent(u, x) returns the exponent of x in u
a = Wild('a', exclude=[x])
b = Wild('b', exclude=[x])
re = u.match(a*x**b)
if re:
return re[b]
def LinearMatchQ(u, x):
# LinearMatchQ(u, x) returns True iff u matches patterns of the form a+b*x where a and b are free of x
if isinstance(u, list):
return all(LinearMatchQ(i, x) for i in u)
else:
a = Wild('a', exclude=[x])
b = Wild('b', exclude=[x])
re = u.match(a + b*x)
if re:
return True
return False
def PowerOfLinearMatchQ(u, x):
if isinstance(u, list):
for i in u:
if not PowerOfLinearMatchQ(i, x):
return False
return True
else:
a = Wild('a', exclude=[x])
b = Wild('b', exclude=[x, 0])
m = Wild('m', exclude=[x, 0])
Match = u.match((a + b*x)**m)
if Match:
return True
else:
return False
def QuadraticMatchQ(u, x):
if ListQ(u):
return all(QuadraticMatchQ(i, x) for i in u)
pattern1 = Pattern(UtilityOperator(x_**2*WC('c', 1) + x_*WC('b', 1) + WC('a', 0), x_), CustomConstraint(lambda a, b, c, x: FreeQ([a, b, c], x)))
pattern2 = Pattern(UtilityOperator(x_**2*WC('c', 1) + WC('a', 0), x_), CustomConstraint(lambda a, c, x: FreeQ([a, c], x)))
u1 = UtilityOperator(u, x)
return is_match(u1, pattern1) or is_match(u1, pattern2)
def CubicMatchQ(u, x):
if isinstance(u, list):
return all(CubicMatchQ(i, x) for i in u)
else:
pattern1 = Pattern(UtilityOperator(x_**3*WC('d', 1) + x_**2*WC('c', 1) + x_*WC('b', 1) + WC('a', 0), x_), CustomConstraint(lambda a, b, c, d, x: FreeQ([a, b, c, d], x)))
pattern2 = Pattern(UtilityOperator(x_**3*WC('d', 1) + x_*WC('b', 1) + WC('a', 0), x_), CustomConstraint(lambda a, b, d, x: FreeQ([a, b, d], x)))
pattern3 = Pattern(UtilityOperator(x_**3*WC('d', 1) + x_**2*WC('c', 1) + WC('a', 0), x_), CustomConstraint(lambda a, c, d, x: FreeQ([a, c, d], x)))
pattern4 = Pattern(UtilityOperator(x_**3*WC('d', 1) + WC('a', 0), x_), CustomConstraint(lambda a, d, x: FreeQ([a, d], x)))
u1 = UtilityOperator(u, x)
if is_match(u1, pattern1) or is_match(u1, pattern2) or is_match(u1, pattern3) or is_match(u1, pattern4):
return True
else:
return False
def BinomialMatchQ(u, x):
if isinstance(u, list):
return all(BinomialMatchQ(i, x) for i in u)
else:
pattern = Pattern(UtilityOperator(x_**WC('n', S(1))*WC('b', S(1)) + WC('a', S(0)), x_) , CustomConstraint(lambda a, b, n, x: FreeQ([a,b,n],x)))
u = UtilityOperator(u, x)
return is_match(u, pattern)
def TrinomialMatchQ(u, x):
if isinstance(u, list):
return all(TrinomialMatchQ(i, x) for i in u)
else:
pattern = Pattern(UtilityOperator(x_**WC('j', S(1))*WC('c', S(1)) + x_**WC('n', S(1))*WC('b', S(1)) + WC('a', S(0)), x_) , CustomConstraint(lambda a, b, c, n, x: FreeQ([a, b, c, n], x)), CustomConstraint(lambda j, n: ZeroQ(j-2*n) ))
u = UtilityOperator(u, x)
return is_match(u, pattern)
def GeneralizedBinomialMatchQ(u, x):
if isinstance(u, list):
return all(GeneralizedBinomialMatchQ(i, x) for i in u)
else:
a = Wild('a', exclude=[x, 0])
b = Wild('b', exclude=[x, 0])
n = Wild('n', exclude=[x, 0])
q = Wild('q', exclude=[x, 0])
Match = u.match(a*x**q + b*x**n)
if Match and len(Match) == 4 and Match[q] != 0 and Match[n] != 0:
return True
else:
return False
def GeneralizedTrinomialMatchQ(u, x):
if isinstance(u, list):
return all(GeneralizedTrinomialMatchQ(i, x) for i in u)
else:
a = Wild('a', exclude=[x, 0])
b = Wild('b', exclude=[x, 0])
n = Wild('n', exclude=[x, 0])
c = Wild('c', exclude=[x, 0])
q = Wild('q', exclude=[x, 0])
Match = u.match(a*x**q + b*x**n + c*x**(2*n - q))
if Match and len(Match) == 5 and 2*Match[n] - Match[q] != 0 and Match[n] != 0:
return True
else:
return False
def QuotientOfLinearsMatchQ(u, x):
if isinstance(u, list):
return all(QuotientOfLinearsMatchQ(i, x) for i in u)
else:
a = Wild('a', exclude=[x])
b = Wild('b', exclude=[x])
d = Wild('d', exclude=[x])
c = Wild('c', exclude=[x])
e = Wild('e')
Match = u.match(e*(a + b*x)/(c + d*x))
if Match and len(Match) == 5:
return True
else:
return False
def PolynomialTermQ(u, x):
a = Wild('a', exclude=[x])
n = Wild('n', exclude=[x])
Match = u.match(a*x**n)
if Match and IntegerQ(Match[n]) and Greater(Match[n], S(0)):
return True
else:
return False
def PolynomialTerms(u, x):
s = 0
for i in u.args:
if PolynomialTermQ(i, x):
s = s + i
return s
def NonpolynomialTerms(u, x):
s = 0
for i in u.args:
if not PolynomialTermQ(i, x):
s = s + i
return s
def PseudoBinomialParts(u, x):
if PolynomialQ(u, x) and Greater(Expon(u, x), S(2)):
n = Expon(u, x)
d = Rt(Coefficient(u, x, n), n)
c = d**(-n + S(1))*Coefficient(u, x, n + S(-1))/n
a = Simplify(u - (c + d*x)**n)
if NonzeroQ(a) and FreeQ(a, x):
return [a, S(1), c, d, n]
else:
return False
else:
return False
def NormalizePseudoBinomial(u, x):
lst = PseudoBinomialParts(u, x)
if lst:
return (lst[0] + lst[1]*(lst[2] + lst[3]*x)**lst[4])
def PseudoBinomialPairQ(u, v, x):
lst1 = PseudoBinomialParts(u, x)
if AtomQ(lst1):
return False
else:
lst2 = PseudoBinomialParts(v, x)
if AtomQ(lst2):
return False
else:
return Drop(lst1, 2) == Drop(lst2, 2)
def PseudoBinomialQ(u, x):
lst = PseudoBinomialParts(u, x)
if lst:
return True
else:
return False
def PolynomialGCD(f, g):
return gcd(f, g)
def PolyGCD(u, v, x):
# (* u and v are polynomials in x. *)
# (* PolyGCD[u,v,x] returns the factors of the gcd of u and v dependent on x. *)
return NonfreeFactors(PolynomialGCD(u, v), x)
def AlgebraicFunctionFactors(u, x, flag=False):
# (* AlgebraicFunctionFactors[u,x] returns the product of the factors of u that are algebraic functions of x. *)
if ProductQ(u):
result = 1
for i in u.args:
if AlgebraicFunctionQ(i, x, flag):
result *= i
return result
if AlgebraicFunctionQ(u, x, flag):
return u
return 1
def NonalgebraicFunctionFactors(u, x):
"""
NonalgebraicFunctionFactors[u,x] returns the product of the factors of u that are not algebraic functions of x.
Examples
========
>>> from sympy.integrals.rubi.utility_function import NonalgebraicFunctionFactors
>>> from sympy.abc import x
>>> from sympy import sin
>>> NonalgebraicFunctionFactors(sin(x), x)
sin(x)
>>> NonalgebraicFunctionFactors(x, x)
1
"""
if ProductQ(u):
result = 1
for i in u.args:
if not AlgebraicFunctionQ(i, x):
result *= i
return result
if AlgebraicFunctionQ(u, x):
return 1
return u
def QuotientOfLinearsP(u, x):
if LinearQ(u, x):
return True
elif SumQ(u):
if FreeQ(u.args[0], x):
return QuotientOfLinearsP(Rest(u), x)
elif LinearQ(Numerator(u), x) and LinearQ(Denominator(u), x):
return True
elif ProductQ(u):
if FreeQ(First(u), x):
return QuotientOfLinearsP(Rest(u), x)
elif Numerator(u) == 1 and PowerQ(u):
return QuotientOfLinearsP(Denominator(u), x)
return u == x or FreeQ(u, x)
def QuotientOfLinearsParts(u, x):
# If u is equivalent to an expression of the form (a+b*x)/(c+d*x), QuotientOfLinearsParts[u,x]
# returns the list {a, b, c, d}.
if LinearQ(u, x):
return [Coefficient(u, x, 0), Coefficient(u, x, 1), 1, 0]
elif PowerQ(u):
if Numerator(u) == 1:
u = Denominator(u)
r = QuotientOfLinearsParts(u, x)
return [r[2], r[3], r[0], r[1]]
elif SumQ(u):
a = First(u)
if FreeQ(a, x):
u = Rest(u)
r = QuotientOfLinearsParts(u, x)
return [r[0] + a*r[2], r[1] + a*r[3], r[2], r[3]]
elif ProductQ(u):
a = First(u)
if FreeQ(a, x):
r = QuotientOfLinearsParts(Rest(u), x)
return [a*r[0], a*r[1], r[2], r[3]]
a = Numerator(u)
d = Denominator(u)
if LinearQ(a, x) and LinearQ(d, x):
return [Coefficient(a, x, 0), Coefficient(a, x, 1), Coefficient(d, x, 0), Coefficient(d, x, 1)]
elif u == x:
return [0, 1, 1, 0]
elif FreeQ(u, x):
return [u, 0, 1, 0]
return [u, 0, 1, 0]
def QuotientOfLinearsQ(u, x):
# (*QuotientOfLinearsQ[u,x] returns True iff u is equivalent to an expression of the form (a+b x)/(c+d x) where b!=0 and d!=0.*)
if ListQ(u):
for i in u:
if not QuotientOfLinearsQ(i, x):
return False
return True
q = QuotientOfLinearsParts(u, x)
return QuotientOfLinearsP(u, x) and NonzeroQ(q[1]) and NonzeroQ(q[3])
def Flatten(l):
return flatten(l)
def Sort(u, r=False):
return sorted(u, key=lambda x: x.sort_key(), reverse=r)
# (*Definition: A number is absurd if it is a rational number, a positive rational number raised to a fractional power, or a product of absurd numbers.*)
def AbsurdNumberQ(u):
# (* AbsurdNumberQ[u] returns True if u is an absurd number, else it returns False. *)
if PowerQ(u):
v = u.exp
u = u.base
return RationalQ(u) and u > 0 and FractionQ(v)
elif ProductQ(u):
return all(AbsurdNumberQ(i) for i in u.args)
return RationalQ(u)
def AbsurdNumberFactors(u):
# (* AbsurdNumberFactors[u] returns the product of the factors of u that are absurd numbers. *)
if AbsurdNumberQ(u):
return u
elif ProductQ(u):
result = S(1)
for i in u.args:
if AbsurdNumberQ(i):
result *= i
return result
return NumericFactor(u)
def NonabsurdNumberFactors(u):
# (* NonabsurdNumberFactors[u] returns the product of the factors of u that are not absurd numbers. *)
if AbsurdNumberQ(u):
return S(1)
elif ProductQ(u):
result = 1
for i in u.args:
result *= NonabsurdNumberFactors(i)
return result
return NonnumericFactors(u)
def SumSimplerAuxQ(u, v):
if SumQ(v):
return (RationalQ(First(v)) or SumSimplerAuxQ(u,First(v))) and (RationalQ(Rest(v)) or SumSimplerAuxQ(u,Rest(v)))
elif SumQ(u):
return SumSimplerAuxQ(First(u), v) or SumSimplerAuxQ(Rest(u), v)
else:
return v!=0 and NonnumericFactors(u)==NonnumericFactors(v) and (NumericFactor(u)/NumericFactor(v)<-1/2 or NumericFactor(u)/NumericFactor(v)==-1/2 and NumericFactor(u)<0)
def Prepend(l1, l2):
if not isinstance(l2, list):
return [l2] + l1
return l2 + l1
def Drop(lst, n):
if isinstance(lst, list):
if isinstance(n, list):
lst = lst[:(n[0]-1)] + lst[n[1]:]
elif n > 0:
lst = lst[n:]
elif n < 0:
lst = lst[:-n]
else:
return lst
return lst
return lst.func(*[i for i in Drop(list(lst.args), n)])
def CombineExponents(lst):
if Length(lst) < 2:
return lst
elif lst[0][0] == lst[1][0]:
return CombineExponents(Prepend(Drop(lst,2),[lst[0][0], lst[0][1] + lst[1][1]]))
return Prepend(CombineExponents(Rest(lst)), First(lst))
def FactorInteger(n, l=None):
if isinstance(n, (int, Integer)):
return sorted(factorint(n, limit=l).items())
else:
return sorted(factorrat(n, limit=l).items())
def FactorAbsurdNumber(m):
# (* m must be an absurd number. FactorAbsurdNumber[m] returns the prime factorization of m *)
# (* as list of base-degree pairs where the bases are prime numbers and the degrees are rational. *)
if RationalQ(m):
return FactorInteger(m)
elif PowerQ(m):
r = FactorInteger(m.base)
return [r[0], r[1]*m.exp]
# CombineExponents[Sort[Flatten[Map[FactorAbsurdNumber,Apply[List,m]],1], Function[i1[[1]]<i2[[1]]]]]
return list((m.as_base_exp(),))
def SubstForInverseFunction(*args):
"""
SubstForInverseFunction(u, v, w, x) returns u with subexpressions equal to v replaced by x and x replaced by w.
Examples
========
>>> from sympy.integrals.rubi.utility_function import SubstForInverseFunction
>>> from sympy.abc import x, a, b
>>> SubstForInverseFunction(a, a, b, x)
a
>>> SubstForInverseFunction(x**a, x**a, b, x)
x
>>> SubstForInverseFunction(a*x**a, a, b, x)
a*b**a
"""
if len(args) == 3:
u, v, x = args[0], args[1], args[2]
return SubstForInverseFunction(u, v, (-Coefficient(v.args[0], x, 0) + InverseFunction(Head(v))(x))/Coefficient(v.args[0], x, 1), x)
elif len(args) == 4:
u, v, w, x = args[0], args[1], args[2], args[3]
if AtomQ(u):
if u == x:
return w
return u
elif Head(u) == Head(v) and ZeroQ(u.args[0] - v.args[0]):
return x
res = [SubstForInverseFunction(i, v, w, x) for i in u.args]
return u.func(*res)
def SubstForFractionalPower(u, v, n, w, x):
# (* SubstForFractionalPower[u,v,n,w,x] returns u with subexpressions equal to v^(m/n) replaced
# by x^m and x replaced by w. *)
if AtomQ(u):
if u == x:
return w
return u
elif FractionalPowerQ(u):
if ZeroQ(u.base - v):
return x**(n*u.exp)
res = [SubstForFractionalPower(i, v, n, w, x) for i in u.args]
return u.func(*res)
def SubstForFractionalPowerOfQuotientOfLinears(u, x):
# (* If u has a subexpression of the form ((a+b*x)/(c+d*x))^(m/n) where m and n>1 are integers,
# SubstForFractionalPowerOfQuotientOfLinears[u,x] returns the list {v,n,(a+b*x)/(c+d*x),b*c-a*d} where v is u
# with subexpressions of the form ((a+b*x)/(c+d*x))^(m/n) replaced by x^m and x replaced
lst = FractionalPowerOfQuotientOfLinears(u, 1, False, x)
if AtomQ(lst) or AtomQ(lst[1]):
return False
n = lst[0]
tmp = lst[1]
lst = QuotientOfLinearsParts(tmp, x)
a, b, c, d = lst[0], lst[1], lst[2], lst[3]
if ZeroQ(d):
return False
lst = Simplify(x**(n - 1)*SubstForFractionalPower(u, tmp, n, (-a + c*x**n)/(b - d*x**n), x)/(b - d*x**n)**2)
return [NonfreeFactors(lst, x), n, tmp, FreeFactors(lst, x)*(b*c - a*d)]
def FractionalPowerOfQuotientOfLinears(u, n, v, x):
# (* If u has a subexpression of the form ((a+b*x)/(c+d*x))^(m/n),
# FractionalPowerOfQuotientOfLinears[u,1,False,x] returns {n,(a+b*x)/(c+d*x)}; else it returns False. *)
if AtomQ(u) or FreeQ(u, x):
return [n, v]
elif CalculusQ(u):
return False
elif FractionalPowerQ(u):
if QuotientOfLinearsQ(u.base, x) and Not(LinearQ(u.base, x)) and (FalseQ(v) or ZeroQ(u.base - v)):
return [LCM(Denominator(u.exp), n), u.base]
lst = [n, v]
for i in u.args:
lst = FractionalPowerOfQuotientOfLinears(i, lst[0], lst[1],x)
if AtomQ(lst):
return False
return lst
def SubstForFractionalPowerQ(u, v, x):
# (* If the substitution x=v^(1/n) will not complicate algebraic subexpressions of u,
# SubstForFractionalPowerQ[u,v,x] returns True; else it returns False. *)
if AtomQ(u) or FreeQ(u, x):
return True
elif FractionalPowerQ(u):
return SubstForFractionalPowerAuxQ(u, v, x)
return all(SubstForFractionalPowerQ(i, v, x) for i in u.args)
def SubstForFractionalPowerAuxQ(u, v, x):
if AtomQ(u):
return False
elif FractionalPowerQ(u):
if ZeroQ(u.base - v):
return True
return any(SubstForFractionalPowerAuxQ(i, v, x) for i in u.args)
def FractionalPowerOfSquareQ(u):
# (* If a subexpression of u is of the form ((v+w)^2)^n where n is a fraction, *)
# (* FractionalPowerOfSquareQ[u] returns (v+w)^2; else it returns False. *)
if AtomQ(u):
return False
elif FractionalPowerQ(u):
a_ = Wild('a', exclude=[0])
b_ = Wild('b', exclude=[0])
c_ = Wild('c', exclude=[0])
match = u.base.match(a_*(b_ + c_)**(S(2)))
if match:
keys = [a_, b_, c_]
if len(keys) == len(match):
a, b, c = tuple(match[i] for i in keys)
if NonsumQ(a):
return (b + c)**S(2)
for i in u.args:
tmp = FractionalPowerOfSquareQ(i)
if Not(FalseQ(tmp)):
return tmp
return False
def FractionalPowerSubexpressionQ(u, v, w):
# (* If a subexpression of u is of the form w^n where n is a fraction but not equal to v, *)
# (* FractionalPowerSubexpressionQ[u,v,w] returns True; else it returns False. *)
if AtomQ(u):
return False
elif FractionalPowerQ(u):
if PositiveQ(u.base/w):
return Not(u.base == v) and LeafCount(w) < 3*LeafCount(v)
for i in u.args:
if FractionalPowerSubexpressionQ(i, v, w):
return True
return False
def Apply(f, lst):
return f(*lst)
def FactorNumericGcd(u):
# (* FactorNumericGcd[u] returns u with the gcd of the numeric coefficients of terms of sums factored out. *)
if PowerQ(u):
if RationalQ(u.exp):
return FactorNumericGcd(u.base)**u.exp
elif ProductQ(u):
res = [FactorNumericGcd(i) for i in u.args]
return Mul(*res)
elif SumQ(u):
g = GCD([NumericFactor(i) for i in u.args])
r = Add(*[i/g for i in u.args])
return g*r
return u
def MergeableFactorQ(bas, deg, v):
# (* MergeableFactorQ[bas,deg,v] returns True iff bas equals the base of a factor of v or bas is a factor of every term of v. *)
if bas == v:
return RationalQ(deg + S(1)) and (deg + 1>=0 or RationalQ(deg) and deg>0)
elif PowerQ(v):
if bas == v.base:
return RationalQ(deg+v.exp) and (deg+v.exp>=0 or RationalQ(deg) and deg>0)
return SumQ(v.base) and IntegerQ(v.exp) and (Not(IntegerQ(deg) or IntegerQ(deg/v.exp))) and MergeableFactorQ(bas, deg/v.exp, v.base)
elif ProductQ(v):
return MergeableFactorQ(bas, deg, First(v)) or MergeableFactorQ(bas, deg, Rest(v))
return SumQ(v) and MergeableFactorQ(bas, deg, First(v)) and MergeableFactorQ(bas, deg, Rest(v))
def MergeFactor(bas, deg, v):
# (* If MergeableFactorQ[bas,deg,v], MergeFactor[bas,deg,v] return the product of bas^deg and v,
# but with bas^deg merged into the factor of v whose base equals bas. *)
if bas == v:
return bas**(deg + 1)
elif PowerQ(v):
if bas == v.base:
return bas**(deg + v.exp)
return MergeFactor(bas, deg/v.exp, v.base**v.exp)
elif ProductQ(v):
if MergeableFactorQ(bas, deg, First(v)):
return MergeFactor(bas, deg, First(v))*Rest(v)
return First(v)*MergeFactor(bas, deg, Rest(v))
return MergeFactor(bas, deg, First(v)) + MergeFactor(bas, deg, Rest(v))
def MergeFactors(u, v):
# (* MergeFactors[u,v] returns the product of u and v, but with the mergeable factors of u merged into v. *)
if ProductQ(u):
return MergeFactors(Rest(u), MergeFactors(First(u), v))
elif PowerQ(u):
if MergeableFactorQ(u.base, u.exp, v):
return MergeFactor(u.base, u.exp, v)
elif RationalQ(u.exp) and u.exp < -1 and MergeableFactorQ(u.base, -S(1), v):
return MergeFactors(u.base**(u.exp + 1), MergeFactor(u.base, -S(1), v))
return u*v
elif MergeableFactorQ(u, S(1), v):
return MergeFactor(u, S(1), v)
return u*v
def TrigSimplifyQ(u):
# (* TrigSimplifyQ[u] returns True if TrigSimplify[u] actually simplifies u; else False. *)
return ActivateTrig(u) != TrigSimplify(u)
def TrigSimplify(u):
# (* TrigSimplify[u] returns a bottom-up trig simplification of u. *)
return ActivateTrig(TrigSimplifyRecur(u))
def TrigSimplifyRecur(u):
if AtomQ(u):
return u
return TrigSimplifyAux(u.func(*[TrigSimplifyRecur(i) for i in u.args]))
def Order(expr1, expr2):
if expr1 == expr2:
return 0
elif expr1.sort_key() > expr2.sort_key():
return -1
return 1
def FactorOrder(u, v):
if u == 1:
if v == 1:
return 0
return -1
elif v == 1:
return 1
return Order(u, v)
def Smallest(num1, num2=None):
if num2 is None:
lst = num1
num = lst[0]
for i in Rest(lst):
num = Smallest(num, i)
return num
return Min(num1, num2)
def OrderedQ(l):
return l == Sort(l)
def MinimumDegree(deg1, deg2):
if RationalQ(deg1):
if RationalQ(deg2):
return Min(deg1, deg2)
return deg1
elif RationalQ(deg2):
return deg2
deg = Simplify(deg1- deg2)
if RationalQ(deg):
if deg > 0:
return deg2
return deg1
elif OrderedQ([deg1, deg2]):
return deg1
return deg2
def PositiveFactors(u):
# (* PositiveFactors[u] returns the positive factors of u *)
if ZeroQ(u):
return S(1)
elif RationalQ(u):
return Abs(u)
elif PositiveQ(u):
return u
elif ProductQ(u):
res = 1
for i in u.args:
res *= PositiveFactors(i)
return res
return 1
def Sign(u):
return sign(u)
def NonpositiveFactors(u):
# (* NonpositiveFactors[u] returns the nonpositive factors of u *)
if ZeroQ(u):
return u
elif RationalQ(u):
return Sign(u)
elif PositiveQ(u):
return S(1)
elif ProductQ(u):
res = S(1)
for i in u.args:
res *= NonpositiveFactors(i)
return res
return u
def PolynomialInAuxQ(u, v, x):
if u == v:
return True
elif AtomQ(u):
return u != x
elif PowerQ(u):
if PowerQ(v):
if u.base == v.base:
return PositiveIntegerQ(u.exp/v.exp)
return PositiveIntegerQ(u.exp) and PolynomialInAuxQ(u.base, v, x)
elif SumQ(u) or ProductQ(u):
for i in u.args:
if Not(PolynomialInAuxQ(i, v, x)):
return False
return True
return False
def PolynomialInQ(u, v, x):
"""
If u is a polynomial in v(x), PolynomialInQ(u, v, x) returns True, else it returns False.
Examples
========
>>> from sympy.integrals.rubi.utility_function import PolynomialInQ
>>> from sympy.abc import x
>>> from sympy import log, S
>>> PolynomialInQ(S(1), log(x), x)
True
>>> PolynomialInQ(log(x), log(x), x)
True
>>> PolynomialInQ(1 + log(x)**2, log(x), x)
True
"""
return PolynomialInAuxQ(u, NonfreeFactors(NonfreeTerms(v, x), x), x)
def ExponentInAux(u, v, x):
if u == v:
return S(1)
elif AtomQ(u):
return S(0)
elif PowerQ(u):
if PowerQ(v):
if u.base == v.base:
return u.exp/v.exp
return u.exp*ExponentInAux(u.base, v, x)
elif ProductQ(u):
return Add(*[ExponentInAux(i, v, x) for i in u.args])
return Max(*[ExponentInAux(i, v, x) for i in u.args])
def ExponentIn(u, v, x):
return ExponentInAux(u, NonfreeFactors(NonfreeTerms(v, x), x), x)
def PolynomialInSubstAux(u, v, x):
if u == v:
return x
elif AtomQ(u):
return u
elif PowerQ(u):
if PowerQ(v):
if u.base == v.base:
return x**(u.exp/v.exp)
return PolynomialInSubstAux(u.base, v, x)**u.exp
return u.func(*[PolynomialInSubstAux(i, v, x) for i in u.args])
def PolynomialInSubst(u, v, x):
# If u is a polynomial in v[x], PolynomialInSubst[u,v,x] returns the polynomial u in x.
w = NonfreeTerms(v, x)
return ReplaceAll(PolynomialInSubstAux(u, NonfreeFactors(w, x), x), {x: x - FreeTerms(v, x)/FreeFactors(w, x)})
def Distrib(u, v):
# Distrib[u,v] returns the sum of u times each term of v.
if SumQ(v):
return Add(*[u*i for i in v.args])
return u*v
def DistributeDegree(u, m):
# DistributeDegree[u,m] returns the product of the factors of u each raised to the mth degree.
if AtomQ(u):
return u**m
elif PowerQ(u):
return u.base**(u.exp*m)
elif ProductQ(u):
return Mul(*[DistributeDegree(i, m) for i in u.args])
return u**m
def FunctionOfPower(*args):
"""
FunctionOfPower[u,x] returns the gcd of the integer degrees of x in u.
Examples
========
>>> from sympy.integrals.rubi.utility_function import FunctionOfPower
>>> from sympy.abc import x
>>> FunctionOfPower(x, x)
1
>>> FunctionOfPower(x**3, x)
3
"""
if len(args) == 2:
return FunctionOfPower(args[0], None, args[1])
u, n, x = args
if FreeQ(u, x):
return n
elif u == x:
return S(1)
elif PowerQ(u):
if u.base == x and IntegerQ(u.exp):
if n is None:
return u.exp
return GCD(n, u.exp)
tmp = n
for i in u.args:
tmp = FunctionOfPower(i, tmp, x)
return tmp
def DivideDegreesOfFactors(u, n):
"""
DivideDegreesOfFactors[u,n] returns the product of the base of the factors of u raised to the degree of the factors divided by n.
Examples
========
>>> from sympy import S
>>> from sympy.integrals.rubi.utility_function import DivideDegreesOfFactors
>>> from sympy.abc import a, b
>>> DivideDegreesOfFactors(a**b, S(3))
a**(b/3)
"""
if ProductQ(u):
return Mul(*[LeadBase(i)**(LeadDegree(i)/n) for i in u.args])
return LeadBase(u)**(LeadDegree(u)/n)
def MonomialFactor(u, x):
# MonomialFactor[u,x] returns the list {n,v} where x^n*v==u and n is free of x.
if AtomQ(u):
if u == x:
return [S(1), S(1)]
return [S(0), u]
elif PowerQ(u):
if IntegerQ(u.exp):
lst = MonomialFactor(u.base, x)
return [lst[0]*u.exp, lst[1]**u.exp]
elif u.base == x and FreeQ(u.exp, x):
return [u.exp, S(1)]
return [S(0), u]
elif ProductQ(u):
lst1 = MonomialFactor(First(u), x)
lst2 = MonomialFactor(Rest(u), x)
return [lst1[0] + lst2[0], lst1[1]*lst2[1]]
elif SumQ(u):
lst = [MonomialFactor(i, x) for i in u.args]
deg = lst[0][0]
for i in Rest(lst):
deg = MinimumDegree(deg, i[0])
if ZeroQ(deg) or RationalQ(deg) and deg < 0:
return [S(0), u]
return [deg, Add(*[x**(i[0] - deg)*i[1] for i in lst])]
return [S(0), u]
def FullSimplify(expr):
return Simplify(expr)
def FunctionOfLinearSubst(u, a, b, x):
if FreeQ(u, x):
return u
elif LinearQ(u, x):
tmp = Coefficient(u, x, 1)
if tmp == b:
tmp = S(1)
else:
tmp = tmp/b
return Coefficient(u, x, S(0)) - a*tmp + tmp*x
elif PowerQ(u):
if FreeQ(u.base, x):
return E**(FullSimplify(FunctionOfLinearSubst(Log(u.base)*u.exp, a, b, x)))
lst = MonomialFactor(u, x)
if ProductQ(u) and NonzeroQ(lst[0]):
if RationalQ(LeadFactor(lst[1])) and LeadFactor(lst[1]) < 0:
return -FunctionOfLinearSubst(DivideDegreesOfFactors(-lst[1], lst[0])*x, a, b, x)**lst[0]
return FunctionOfLinearSubst(DivideDegreesOfFactors(lst[1], lst[0])*x, a, b, x)**lst[0]
return u.func(*[FunctionOfLinearSubst(i, a, b, x) for i in u.args])
def FunctionOfLinear(*args):
# (* If u (x) is equivalent to an expression of the form f (a+b*x) and not the case that a==0 and
# b==1, FunctionOfLinear[u,x] returns the list {f (x),a,b}; else it returns False. *)
if len(args) == 2:
u, x = args
lst = FunctionOfLinear(u, False, False, x, False)
if AtomQ(lst) or FalseQ(lst[0]) or (lst[0] == 0 and lst[1] == 1):
return False
return [FunctionOfLinearSubst(u, lst[0], lst[1], x), lst[0], lst[1]]
u, a, b, x, flag = args
if FreeQ(u, x):
return [a, b]
elif CalculusQ(u):
return False
elif LinearQ(u, x):
if FalseQ(a):
return [Coefficient(u, x, 0), Coefficient(u, x, 1)]
lst = CommonFactors([b, Coefficient(u, x, 1)])
if ZeroQ(Coefficient(u, x, 0)) and Not(flag):
return [0, lst[0]]
elif ZeroQ(b*Coefficient(u, x, 0) - a*Coefficient(u, x, 1)):
return [a/lst[1], lst[0]]
return [0, 1]
elif PowerQ(u):
if FreeQ(u.base, x):
return FunctionOfLinear(Log(u.base)*u.exp, a, b, x, False)
lst = MonomialFactor(u, x)
if ProductQ(u) and NonzeroQ(lst[0]):
if False and IntegerQ(lst[0]) and lst[0] != -1 and FreeQ(lst[1], x):
if RationalQ(LeadFactor(lst[1])) and LeadFactor(lst[1]) < 0:
return FunctionOfLinear(DivideDegreesOfFactors(-lst[1], lst[0])*x, a, b, x, False)
return FunctionOfLinear(DivideDegreesOfFactors(lst[1], lst[0])*x, a, b, x, False)
return False
lst = [a, b]
for i in u.args:
lst = FunctionOfLinear(i, lst[0], lst[1], x, SumQ(u))
if AtomQ(lst):
return False
return lst
def NormalizeIntegrand(u, x):
v = NormalizeLeadTermSigns(NormalizeIntegrandAux(u, x))
if v == NormalizeLeadTermSigns(u):
return u
else:
return v
def NormalizeIntegrandAux(u, x):
if SumQ(u):
l = 0
for i in u.args:
l += NormalizeIntegrandAux(i, x)
return l
if ProductQ(MergeMonomials(u, x)):
l = 1
for i in MergeMonomials(u, x).args:
l *= NormalizeIntegrandFactor(i, x)
return l
else:
return NormalizeIntegrandFactor(MergeMonomials(u, x), x)
def NormalizeIntegrandFactor(u, x):
if PowerQ(u):
if FreeQ(u.exp, x):
bas = NormalizeIntegrandFactorBase(u.base, x)
deg = u.exp
if IntegerQ(deg) and SumQ(bas):
if all(MonomialQ(i, x) for i in bas.args):
mi = MinimumMonomialExponent(bas, x)
q = 0
for i in bas.args:
q += Simplify(i/x**mi)
return x**(mi*deg)*q**deg
else:
return bas**deg
else:
return bas**deg
if PowerQ(u):
if FreeQ(u.base, x):
return u.base**NormalizeIntegrandFactorBase(u.exp, x)
bas = NormalizeIntegrandFactorBase(u, x)
if SumQ(bas):
if all(MonomialQ(i, x) for i in bas.args):
mi = MinimumMonomialExponent(bas, x)
z = 0
for j in bas.args:
z += j/x**mi
return x**mi*z
else:
return bas
else:
return bas
def NormalizeIntegrandFactorBase(expr, x):
m = Wild('m', exclude=[x])
u = Wild('u')
match = expr.match(x**m*u)
if match and SumQ(u):
l = 0
for i in u.args:
l += NormalizeIntegrandFactorBase((x**m*i), x)
return l
if BinomialQ(expr, x):
if BinomialMatchQ(expr, x):
return expr
else:
return ExpandToSum(expr, x)
elif TrinomialQ(expr, x):
if TrinomialMatchQ(expr, x):
return expr
else:
return ExpandToSum(expr, x)
elif ProductQ(expr):
l = 1
for i in expr.args:
l *= NormalizeIntegrandFactor(i, x)
return l
elif PolynomialQ(expr, x) and Exponent(expr, x) <= 4:
return ExpandToSum(expr, x)
elif SumQ(expr):
w = Wild('w')
m = Wild('m', exclude=[x])
v = TogetherSimplify(expr)
if SumQ(v) or v.match(x**m*w) and SumQ(w) or LeafCount(v) > LeafCount(expr) + 2:
return UnifySum(expr, x)
else:
return NormalizeIntegrandFactorBase(v, x)
else:
return expr
def NormalizeTogether(u):
return NormalizeLeadTermSigns(Together(u))
def NormalizeLeadTermSigns(u):
if ProductQ(u):
t = 1
for i in u.args:
lst = SignOfFactor(i)
if lst[0] == 1:
t *= lst[1]
else:
t *= AbsorbMinusSign(lst[1])
return t
else:
lst = SignOfFactor(u)
if lst[0] == 1:
return lst[1]
else:
return AbsorbMinusSign(lst[1])
def AbsorbMinusSign(expr, *x):
m = Wild('m', exclude=[x])
u = Wild('u')
v = Wild('v')
match = expr.match(u*v**m)
if match:
if len(match) == 3:
if SumQ(match[v]) and OddQ(match[m]):
return match[u]*(-match[v])**match[m]
return -expr
def NormalizeSumFactors(u):
if AtomQ(u):
return u
elif ProductQ(u):
k = 1
for i in u.args:
k *= NormalizeSumFactors(i)
return SignOfFactor(k)[0]*SignOfFactor(k)[1]
elif SumQ(u):
k = 0
for i in u.args:
k += NormalizeSumFactors(i)
return k
else:
return u
def SignOfFactor(u):
if RationalQ(u) and u < 0 or SumQ(u) and NumericFactor(First(u)) < 0:
return [-1, -u]
elif IntegerPowerQ(u):
if SumQ(u.base) and NumericFactor(First(u.base)) < 0:
return [(-1)**u.exp, (-u.base)**u.exp]
elif ProductQ(u):
k = 1
h = 1
for i in u.args:
k *= SignOfFactor(i)[0]
h *= SignOfFactor(i)[1]
return [k, h]
return [1, u]
def NormalizePowerOfLinear(u, x):
v = FactorSquareFree(u)
if PowerQ(v):
if LinearQ(v.base, x) and FreeQ(v.exp, x):
return ExpandToSum(v.base, x)**v.exp
return ExpandToSum(v, x)
def SimplifyIntegrand(u, x):
v = NormalizeLeadTermSigns(NormalizeIntegrandAux(Simplify(u), x))
if 5*LeafCount(v) < 4*LeafCount(u):
return v
if v != NormalizeLeadTermSigns(u):
return v
else:
return u
def SimplifyTerm(u, x):
v = Simplify(u)
w = Together(v)
if LeafCount(v) < LeafCount(w):
return NormalizeIntegrand(v, x)
else:
return NormalizeIntegrand(w, x)
def TogetherSimplify(u):
v = Together(Simplify(Together(u)))
return FixSimplify(v)
def SmartSimplify(u):
v = Simplify(u)
w = factor(v)
if LeafCount(w) < LeafCount(v):
v = w
if Not(FalseQ(w == FractionalPowerOfSquareQ(v))) and FractionalPowerSubexpressionQ(u, w, Expand(w)):
v = SubstForExpn(v, w, Expand(w))
else:
v = FactorNumericGcd(v)
return FixSimplify(v)
def SubstForExpn(u, v, w):
if u == v:
return w
if AtomQ(u):
return u
else:
k = 0
for i in u.args:
k += SubstForExpn(i, v, w)
return k
def ExpandToSum(u, *x):
if len(x) == 1:
x = x[0]
expr = 0
if PolyQ(S(u), x):
for t in ExponentList(u, x):
expr += Coeff(u, x, t)*x**t
return expr
if BinomialQ(u, x):
i = BinomialParts(u, x)
expr += i[0] + i[1]*x**i[2]
return expr
if TrinomialQ(u, x):
i = TrinomialParts(u, x)
expr += i[0] + i[1]*x**i[3] + i[2]*x**(2*i[3])
return expr
if GeneralizedBinomialMatchQ(u, x):
i = GeneralizedBinomialParts(u, x)
expr += i[0]*x**i[3] + i[1]*x**i[2]
return expr
if GeneralizedTrinomialMatchQ(u, x):
i = GeneralizedTrinomialParts(u, x)
expr += i[0]*x**i[4] + i[1]*x**i[3] + i[2]*x**(2*i[3]-i[4])
return expr
else:
return Expand(u)
else:
v = x[0]
x = x[1]
w = ExpandToSum(v, x)
r = NonfreeTerms(w, x)
if SumQ(r):
k = u*FreeTerms(w, x)
for i in r.args:
k += MergeMonomials(u*i, x)
return k
else:
return u*FreeTerms(w, x) + MergeMonomials(u*r, x)
def UnifySum(u, x):
if SumQ(u):
t = 0
lst = []
for i in u.args:
lst += [i]
for j in UnifyTerms(lst, x):
t += j
return t
else:
return SimplifyTerm(u, x)
def UnifyTerms(lst, x):
if lst==[]:
return lst
else:
return UnifyTerm(First(lst), UnifyTerms(Rest(lst), x), x)
def UnifyTerm(term, lst, x):
if lst==[]:
return [term]
tmp = Simplify(First(lst)/term)
if FreeQ(tmp, x):
return Prepend(Rest(lst), [(1+tmp)*term])
else:
return Prepend(UnifyTerm(term, Rest(lst), x), [First(lst)])
def CalculusQ(u):
return False
def FunctionOfInverseLinear(*args):
# (* If u is a function of an inverse linear binomial of the form 1/(a+b*x),
# FunctionOfInverseLinear[u,x] returns the list {a,b}; else it returns False. *)
if len(args) == 2:
u, x = args
return FunctionOfInverseLinear(u, None, x)
u, lst, x = args
if FreeQ(u, x):
return lst
elif u == x:
return False
elif QuotientOfLinearsQ(u, x):
tmp = Drop(QuotientOfLinearsParts(u, x), 2)
if tmp[1] == 0:
return False
elif lst is None:
return tmp
elif ZeroQ(lst[0]*tmp[1] - lst[1]*tmp[0]):
return lst
return False
elif CalculusQ(u):
return False
tmp = lst
for i in u.args:
tmp = FunctionOfInverseLinear(i, tmp, x)
if AtomQ(tmp):
return False
return tmp
def PureFunctionOfSinhQ(u, v, x):
# (* If u is a pure function of Sinh[v] and/or Csch[v], PureFunctionOfSinhQ[u,v,x] returns True;
# else it returns False. *)
if AtomQ(u):
return u != x
elif CalculusQ(u):
return False
elif HyperbolicQ(u) and ZeroQ(u.args[0] - v):
return SinhQ(u) or CschQ(u)
for i in u.args:
if Not(PureFunctionOfSinhQ(i, v, x)):
return False
return True
def PureFunctionOfTanhQ(u, v , x):
# (* If u is a pure function of Tanh[v] and/or Coth[v], PureFunctionOfTanhQ[u,v,x] returns True;
# else it returns False. *)
if AtomQ(u):
return u != x
elif CalculusQ(u):
return False
elif HyperbolicQ(u) and ZeroQ(u.args[0] - v):
return TanhQ(u) or CothQ(u)
for i in u.args:
if Not(PureFunctionOfTanhQ(i, v, x)):
return False
return True
def PureFunctionOfCoshQ(u, v, x):
# (* If u is a pure function of Cosh[v] and/or Sech[v], PureFunctionOfCoshQ[u,v,x] returns True;
# else it returns False. *)
if AtomQ(u):
return u != x
elif CalculusQ(u):
return False
elif HyperbolicQ(u) and ZeroQ(u.args[0] - v):
return CoshQ(u) or SechQ(u)
for i in u.args:
if Not(PureFunctionOfCoshQ(i, v, x)):
return False
return True
def IntegerQuotientQ(u, v):
# (* If u/v is an integer, IntegerQuotientQ[u,v] returns True; else it returns False. *)
return IntegerQ(Simplify(u/v))
def OddQuotientQ(u, v):
# (* If u/v is odd, OddQuotientQ[u,v] returns True; else it returns False. *)
return OddQ(Simplify(u/v))
def EvenQuotientQ(u, v):
# (* If u/v is even, EvenQuotientQ[u,v] returns True; else it returns False. *)
return EvenQ(Simplify(u/v))
def FindTrigFactor(func1, func2, u, v, flag):
# (* If func[w]^m is a factor of u where m is odd and w is an integer multiple of v,
# FindTrigFactor[func1,func2,u,v,True] returns the list {w,u/func[w]^n}; else it returns False. *)
# (* If func[w]^m is a factor of u where m is odd and w is an integer multiple of v not equal to v,
# FindTrigFactor[func1,func2,u,v,False] returns the list {w,u/func[w]^n}; else it returns False. *)
if u == 1:
return False
elif (Head(LeadBase(u)) == func1 or Head(LeadBase(u)) == func2) and OddQ(LeadDegree(u)) and IntegerQuotientQ(LeadBase(u).args[0], v) and (flag or NonzeroQ(LeadBase(u).args[0] - v)):
return [LeadBase[u].args[0], RemainingFactors(u)]
lst = FindTrigFactor(func1, func2, RemainingFactors(u), v, flag)
if AtomQ(lst):
return False
return [lst[0], LeadFactor(u)*lst[1]]
def FunctionOfSinhQ(u, v, x):
# (* If u is a function of Sinh[v], FunctionOfSinhQ[u,v,x] returns True; else it returns False. *)
if AtomQ(u):
return u != x
elif CalculusQ(u):
return False
elif HyperbolicQ(u) and IntegerQuotientQ(u.args[0], v):
if OddQuotientQ(u.args[0], v):
# (* Basis: If m odd, Sinh[m*v]^n is a function of Sinh[v]. *)
return SinhQ(u) or CschQ(u)
# (* Basis: If m even, Cos[m*v]^n is a function of Sinh[v]. *)
return CoshQ(u) or SechQ(u)
elif IntegerPowerQ(u):
if HyperbolicQ(u.base) and IntegerQuotientQ(u.base.args[0], v):
if EvenQ(u.exp):
# (* Basis: If m integer and n even, Hyper[m*v]^n is a function of Sinh[v]. *)
return True
return FunctionOfSinhQ(u.base, v, x)
elif ProductQ(u):
if CoshQ(u.args[0]) and SinhQ(u.args[1]) and ZeroQ(u.args[0].args[0] - v/2) and ZeroQ(u.args[1].args[0] - v/2):
return FunctionOfSinhQ(Drop(u, 2), v, x)
lst = FindTrigFactor(Sinh, Csch, u, v, False)
if ListQ(lst) and EvenQuotientQ(lst[0], v):
# (* Basis: If m even and n odd, Sinh[m*v]^n == Cosh[v]*u where u is a function of Sinh[v]. *)
return FunctionOfSinhQ(Cosh(v)*lst[1], v, x)
lst = FindTrigFactor(Cosh, Sech, u, v, False)
if ListQ(lst) and OddQuotientQ(lst[0], v):
# (* Basis: If m odd and n odd, Cosh[m*v]^n == Cosh[v]*u where u is a function of Sinh[v]. *)
return FunctionOfSinhQ(Cosh(v)*lst[1], v, x)
lst = FindTrigFactor(Tanh, Coth, u, v, True)
if ListQ(lst):
# (* Basis: If m integer and n odd, Tanh[m*v]^n == Cosh[v]*u where u is a function of Sinh[v]. *)
return FunctionOfSinhQ(Cosh(v)*lst[1], v, x)
return all(FunctionOfSinhQ(i, v, x) for i in u.args)
return all(FunctionOfSinhQ(i, v, x) for i in u.args)
def FunctionOfCoshQ(u, v, x):
#(* If u is a function of Cosh[v], FunctionOfCoshQ[u,v,x] returns True; else it returns False. *)
if AtomQ(u):
return u != x
elif CalculusQ(u):
return False
elif HyperbolicQ(u) and IntegerQuotientQ(u.args[0], v):
# (* Basis: If m integer, Cosh[m*v]^n is a function of Cosh[v]. *)
return CoshQ(u) or SechQ(u)
elif IntegerPowerQ(u):
if HyperbolicQ(u.base) and IntegerQuotientQ(u.base.args[0], v):
if EvenQ(u.exp):
# (* Basis: If m integer and n even, Hyper[m*v]^n is a function of Cosh[v]. *)
return True
return FunctionOfCoshQ(u.base, v, x)
elif ProductQ(u):
lst = FindTrigFactor(Sinh, Csch, u, v, False)
if ListQ(lst):
# (* Basis: If m integer and n odd, Sinh[m*v]^n == Sinh[v]*u where u is a function of Cosh[v]. *)
return FunctionOfCoshQ(Sinh(v)*lst[1], v, x)
lst = FindTrigFactor(Tanh, Coth, u, v, True)
if ListQ(lst):
# (* Basis: If m integer and n odd, Tanh[m*v]^n == Sinh[v]*u where u is a function of Cosh[v]. *)
return FunctionOfCoshQ(Sinh(v)*lst[1], v, x)
return all(FunctionOfCoshQ(i, v, x) for i in u.args)
return all(FunctionOfCoshQ(i, v, x) for i in u.args)
def OddHyperbolicPowerQ(u, v, x):
if SinhQ(u) or CoshQ(u) or SechQ(u) or CschQ(u):
return OddQuotientQ(u.args[0], v)
if PowerQ(u):
return OddQ(u.exp) and OddHyperbolicPowerQ(u.base, v, x)
if ProductQ(u):
if Not(EqQ(FreeFactors(u, x), 1)):
return OddHyperbolicPowerQ(NonfreeFactors(u, x), v, x)
lst = []
for i in u.args:
if Not(FunctionOfTanhQ(i, v, x)):
lst.append(i)
if lst == []:
return True
return Length(lst)==1 and OddHyperbolicPowerQ(lst[0], v, x)
if SumQ(u):
return all(OddHyperbolicPowerQ(i, v, x) for i in u.args)
return False
def FunctionOfTanhQ(u, v, x):
#(* If u is a function of the form f[Tanh[v],Coth[v]] where f is independent of x,
# FunctionOfTanhQ[u,v,x] returns True; else it returns False. *)
if AtomQ(u):
return u != x
elif CalculusQ(u):
return False
elif HyperbolicQ(u) and IntegerQuotientQ(u.args[0], v):
return TanhQ(u) or CothQ(u) or EvenQuotientQ(u.args[0], v)
elif PowerQ(u):
if EvenQ(u.exp) and HyperbolicQ(u.base) and IntegerQuotientQ(u.base.args[0], v):
return True
elif EvenQ(u.args[1]) and SumQ(u.args[0]):
return FunctionOfTanhQ(Expand(u.args[0]**2, v, x))
if ProductQ(u):
lst = []
for i in u.args:
if Not(FunctionOfTanhQ(i, v, x)):
lst.append(i)
if lst == []:
return True
return Length(lst)==2 and OddHyperbolicPowerQ(lst[0], v, x) and OddHyperbolicPowerQ(lst[1], v, x)
return all(FunctionOfTanhQ(i, v, x) for i in u.args)
def FunctionOfTanhWeight(u, v, x):
"""
u is a function of the form f(tanh(v), coth(v)) where f is independent of x.
FunctionOfTanhWeight(u, v, x) returns a nonnegative number if u is best considered a function of tanh(v), else it returns a negative number.
Examples
========
>>> from sympy import sinh, log, tanh
>>> from sympy.abc import x
>>> from sympy.integrals.rubi.utility_function import FunctionOfTanhWeight
>>> FunctionOfTanhWeight(x, log(x), x)
0
>>> FunctionOfTanhWeight(sinh(log(x)), log(x), x)
0
>>> FunctionOfTanhWeight(tanh(log(x)), log(x), x)
1
"""
if AtomQ(u):
return S(0)
elif CalculusQ(u):
return S(0)
elif HyperbolicQ(u) and IntegerQuotientQ(u.args[0], v):
if TanhQ(u) and ZeroQ(u.args[0] - v):
return S(1)
elif CothQ(u) and ZeroQ(u.args[0] - v):
return S(-1)
return S(0)
elif PowerQ(u):
if EvenQ(u.exp) and HyperbolicQ(u.base) and IntegerQuotientQ(u.base.args[0], v):
if TanhQ(u.base) or CoshQ(u.base) or SechQ(u.base):
return S(1)
return S(-1)
if ProductQ(u):
if all(FunctionOfTanhQ(i, v, x) for i in u.args):
return Add(*[FunctionOfTanhWeight(i, v, x) for i in u.args])
return S(0)
return Add(*[FunctionOfTanhWeight(i, v, x) for i in u.args])
def FunctionOfHyperbolicQ(u, v, x):
# (* If u (x) is equivalent to a function of the form f (Sinh[v],Cosh[v],Tanh[v],Coth[v],Sech[v],Csch[v])
# where f is independent of x, FunctionOfHyperbolicQ[u,v,x] returns True; else it returns False. *)
if AtomQ(u):
return u != x
elif CalculusQ(u):
return False
elif HyperbolicQ(u) and IntegerQuotientQ(u.args[0], v):
return True
return all(FunctionOfHyperbolicQ(i, v, x) for i in u.args)
def SmartNumerator(expr):
if PowerQ(expr):
n = expr.exp
u = expr.base
if RationalQ(n) and n < 0:
return SmartDenominator(u**(-n))
elif ProductQ(expr):
return Mul(*[SmartNumerator(i) for i in expr.args])
return Numerator(expr)
def SmartDenominator(expr):
if PowerQ(expr):
u = expr.base
n = expr.exp
if RationalQ(n) and n < 0:
return SmartNumerator(u**(-n))
elif ProductQ(expr):
return Mul(*[SmartDenominator(i) for i in expr.args])
return Denominator(expr)
def ActivateTrig(u):
return u
def ExpandTrig(*args):
if len(args) == 2:
u, x = args
return ActivateTrig(ExpandIntegrand(u, x))
u, v, x = args
w = ExpandTrig(v, x)
z = ActivateTrig(u)
if SumQ(w):
return w.func(*[z*i for i in w.args])
return z*w
def TrigExpand(u):
return expand_trig(u)
# SubstForTrig[u_,sin_,cos_,v_,x_] :=
# If[AtomQ[u],
# u,
# If[TrigQ[u] && IntegerQuotientQ[u[[1]],v],
# If[u[[1]]===v || ZeroQ[u[[1]]-v],
# If[SinQ[u],
# sin,
# If[CosQ[u],
# cos,
# If[TanQ[u],
# sin/cos,
# If[CotQ[u],
# cos/sin,
# If[SecQ[u],
# 1/cos,
# 1/sin]]]]],
# Map[Function[SubstForTrig[#,sin,cos,v,x]],
# ReplaceAll[TrigExpand[Head[u][Simplify[u[[1]]/v]*x]],x->v]]],
# If[ProductQ[u] && CosQ[u[[1]]] && SinQ[u[[2]]] && ZeroQ[u[[1,1]]-v/2] && ZeroQ[u[[2,1]]-v/2],
# sin/2*SubstForTrig[Drop[u,2],sin,cos,v,x],
# Map[Function[SubstForTrig[#,sin,cos,v,x]],u]]]]
def SubstForTrig(u, sin_ , cos_, v, x):
# (* u (v) is an expression of the form f (Sin[v],Cos[v],Tan[v],Cot[v],Sec[v],Csc[v]). *)
# (* SubstForTrig[u,sin,cos,v,x] returns the expression f (sin,cos,sin/cos,cos/sin,1/cos,1/sin). *)
if AtomQ(u):
return u
elif TrigQ(u) and IntegerQuotientQ(u.args[0], v):
if u.args[0] == v or ZeroQ(u.args[0] - v):
if SinQ(u):
return sin_
elif CosQ(u):
return cos_
elif TanQ(u):
return sin_/cos_
elif CotQ(u):
return cos_/sin_
elif SecQ(u):
return 1/cos_
return 1/sin_
r = ReplaceAll(TrigExpand(Head(u)(Simplify(u.args[0]/v*x))), {x: v})
return r.func(*[SubstForTrig(i, sin_, cos_, v, x) for i in r.args])
if ProductQ(u) and CosQ(u.args[0]) and SinQ(u.args[1]) and ZeroQ(u.args[0].args[0] - v/2) and ZeroQ(u.args[1].args[0] - v/2):
return sin(x)/2*SubstForTrig(Drop(u, 2), sin_, cos_, v, x)
return u.func(*[SubstForTrig(i, sin_, cos_, v, x) for i in u.args])
def SubstForHyperbolic(u, sinh_, cosh_, v, x):
# (* u (v) is an expression of the form f (Sinh[v],Cosh[v],Tanh[v],Coth[v],Sech[v],Csch[v]). *)
# (* SubstForHyperbolic[u,sinh,cosh,v,x] returns the expression
# f (sinh,cosh,sinh/cosh,cosh/sinh,1/cosh,1/sinh). *)
if AtomQ(u):
return u
elif HyperbolicQ(u) and IntegerQuotientQ(u.args[0], v):
if u.args[0] == v or ZeroQ(u.args[0] - v):
if SinhQ(u):
return sinh_
elif CoshQ(u):
return cosh_
elif TanhQ(u):
return sinh_/cosh_
elif CothQ(u):
return cosh_/sinh_
if SechQ(u):
return 1/cosh_
return 1/sinh_
r = ReplaceAll(TrigExpand(Head(u)(Simplify(u.args[0]/v)*x)), {x: v})
return r.func(*[SubstForHyperbolic(i, sinh_, cosh_, v, x) for i in r.args])
elif ProductQ(u) and CoshQ(u.args[0]) and SinhQ(u.args[1]) and ZeroQ(u.args[0].args[0] - v/2) and ZeroQ(u.args[1].args[0] - v/2):
return sinh(x)/2*SubstForHyperbolic(Drop(u, 2), sinh_, cosh_, v, x)
return u.func(*[SubstForHyperbolic(i, sinh_, cosh_, v, x) for i in u.args])
def InertTrigFreeQ(u):
return FreeQ(u, sin) and FreeQ(u, cos) and FreeQ(u, tan) and FreeQ(u, cot) and FreeQ(u, sec) and FreeQ(u, csc)
def LCM(a, b):
return lcm(a, b)
def SubstForFractionalPowerOfLinear(u, x):
# (* If u has a subexpression of the form (a+b*x)^(m/n) where m and n>1 are integers,
# SubstForFractionalPowerOfLinear[u,x] returns the list {v,n,a+b*x,1/b} where v is u
# with subexpressions of the form (a+b*x)^(m/n) replaced by x^m and x replaced
# by -a/b+x^n/b, and all times x^(n-1); else it returns False. *)
lst = FractionalPowerOfLinear(u, S(1), False, x)
if AtomQ(lst) or FalseQ(lst[1]):
return False
n = lst[0]
a = Coefficient(lst[1], x, 0)
b = Coefficient(lst[1], x, 1)
tmp = Simplify(x**(n-1)*SubstForFractionalPower(u, lst[1], n, -a/b + x**n/b, x))
return [NonfreeFactors(tmp, x), n, lst[1], FreeFactors(tmp, x)/b]
def FractionalPowerOfLinear(u, n, v, x):
# If u has a subexpression of the form (a + b*x)**(m/n), FractionalPowerOfLinear(u, 1, False, x) returns [n, a + b*x], else it returns False.
if AtomQ(u) or FreeQ(u, x):
return [n, v]
elif CalculusQ(u):
return False
elif FractionalPowerQ(u):
if LinearQ(u.base, x) and (FalseQ(v) or ZeroQ(u.base - v)):
return [LCM(Denominator(u.exp), n), u.base]
lst = [n, v]
for i in u.args:
lst = FractionalPowerOfLinear(i, lst[0], lst[1], x)
if AtomQ(lst):
return False
return lst
def InverseFunctionOfLinear(u, x):
# (* If u has a subexpression of the form g[a+b*x] where g is an inverse function,
# InverseFunctionOfLinear[u,x] returns g[a+b*x]; else it returns False. *)
if AtomQ(u) or CalculusQ(u) or FreeQ(u, x):
return False
elif InverseFunctionQ(u) and LinearQ(u.args[0], x):
return u
for i in u.args:
tmp = InverseFunctionOfLinear(i, x)
if Not(AtomQ(tmp)):
return tmp
return False
def InertTrigQ(*args):
if len(args) == 1:
f = args[0]
l = [sin,cos,tan,cot,sec,csc]
return any(Head(f) == i for i in l)
elif len(args) == 2:
f, g = args
if f == g:
return InertTrigQ(f)
return InertReciprocalQ(f, g) or InertReciprocalQ(g, f)
else:
f, g, h = args
return InertTrigQ(g, f) and InertTrigQ(g, h)
def InertReciprocalQ(f, g):
return (f.func == sin and g.func == csc) or (f.func == cos and g.func == sec) or (f.func == tan and g.func == cot)
def DeactivateTrig(u, x):
# (* u is a function of trig functions of a linear function of x. *)
# (* DeactivateTrig[u,x] returns u with the trig functions replaced with inert trig functions. *)
return FixInertTrigFunction(DeactivateTrigAux(u, x), x)
def FixInertTrigFunction(u, x):
return u
def DeactivateTrigAux(u, x):
if AtomQ(u):
return u
elif TrigQ(u) and LinearQ(u.args[0], x):
v = ExpandToSum(u.args[0], x)
if SinQ(u):
return sin(v)
elif CosQ(u):
return cos(v)
elif TanQ(u):
return tan(u)
elif CotQ(u):
return cot(v)
elif SecQ(u):
return sec(v)
return csc(v)
elif HyperbolicQ(u) and LinearQ(u.args[0], x):
v = ExpandToSum(I*u.args[0], x)
if SinhQ(u):
return -I*sin(v)
elif CoshQ(u):
return cos(v)
elif TanhQ(u):
return -I*tan(v)
elif CothQ(u):
I*cot(v)
elif SechQ(u):
return sec(v)
return I*csc(v)
return u.func(*[DeactivateTrigAux(i, x) for i in u.args])
def PowerOfInertTrigSumQ(u, func, x):
p_ = Wild('p', exclude=[x])
q_ = Wild('q', exclude=[x])
a_ = Wild('a', exclude=[x])
b_ = Wild('b', exclude=[x])
c_ = Wild('c', exclude=[x])
d_ = Wild('d', exclude=[x])
n_ = Wild('n', exclude=[x])
w_ = Wild('w')
pattern = (a_ + b_*(c_*func(w_))**p_)**n_
match = u.match(pattern)
if match:
keys = [a_, b_, c_, n_, p_, w_]
if len(keys) == len(match):
return True
pattern = (a_ + b_*(d_*func(w_))**p_ + c_*(d_*func(w_))**q_)**n_
match = u.match(pattern)
if match:
keys = [a_, b_, c_, d_, n_, p_, q_, w_]
if len(keys) == len(match):
return True
return False
def PiecewiseLinearQ(*args):
# (* If the derivative of u wrt x is a constant wrt x, PiecewiseLinearQ[u,x] returns True;
# else it returns False. *)
if len(args) == 3:
u, v, x = args
return PiecewiseLinearQ(u, x) and PiecewiseLinearQ(v, x)
u, x = args
if LinearQ(u, x):
return True
c_ = Wild('c', exclude=[x])
F_ = Wild('F', exclude=[x])
v_ = Wild('v')
match = u.match(Log(c_*F_**v_))
if match:
if len(match) == 3:
if LinearQ(match[v_], x):
return True
try:
F = type(u)
G = type(u.args[0])
v = u.args[0].args[0]
if LinearQ(v, x):
if MemberQ([[atanh, tanh], [atanh, coth], [acoth, coth], [acoth, tanh], [atan, tan], [atan, cot], [acot, cot], [acot, tan]], [F, G]):
return True
except:
pass
return False
def KnownTrigIntegrandQ(lst, u, x):
if u == 1:
return True
a_ = Wild('a', exclude=[x])
b_ = Wild('b', exclude=[x, 0])
func_ = WildFunction('func')
m_ = Wild('m', exclude=[x])
A_ = Wild('A', exclude=[x])
B_ = Wild('B', exclude=[x, 0])
C_ = Wild('C', exclude=[x, 0])
match = u.match((a_ + b_*func_)**m_)
if match:
func = match[func_]
if LinearQ(func.args[0], x) and MemberQ(lst, func.func):
return True
match = u.match((a_ + b_*func_)**m_*(A_ + B_*func_))
if match:
func = match[func_]
if LinearQ(func.args[0], x) and MemberQ(lst, func.func):
return True
match = u.match(A_ + C_*func_**2)
if match:
func = match[func_]
if LinearQ(func.args[0], x) and MemberQ(lst, func.func):
return True
match = u.match(A_ + B_*func_ + C_*func_**2)
if match:
func = match[func_]
if LinearQ(func.args[0], x) and MemberQ(lst, func.func):
return True
match = u.match((a_ + b_*func_)**m_*(A_ + C_*func_**2))
if match:
func = match[func_]
if LinearQ(func.args[0], x) and MemberQ(lst, func.func):
return True
match = u.match((a_ + b_*func_)**m_*(A_ + B_*func_ + C_*func_**2))
if match:
func = match[func_]
if LinearQ(func.args[0], x) and MemberQ(lst, func.func):
return True
return False
def KnownSineIntegrandQ(u, x):
return KnownTrigIntegrandQ([sin, cos], u, x)
def KnownTangentIntegrandQ(u, x):
return KnownTrigIntegrandQ([tan], u, x)
def KnownCotangentIntegrandQ(u, x):
return KnownTrigIntegrandQ([cot], u, x)
def KnownSecantIntegrandQ(u, x):
return KnownTrigIntegrandQ([sec, csc], u, x)
def TryPureTanSubst(u, x):
a_ = Wild('a', exclude=[x])
b_ = Wild('b', exclude=[x])
c_ = Wild('c', exclude=[x])
G_ = Wild('G')
F = u.func
try:
if MemberQ([atan, acot, atanh, acoth], F):
match = u.args[0].match(c_*(a_ + b_*G_))
if match:
if len(match) == 4:
G = match[G_]
if MemberQ([tan, cot, tanh, coth], G.func):
if LinearQ(G.args[0], x):
return True
except:
pass
return False
def TryTanhSubst(u, x):
if LogQ(u):
return False
elif not FalseQ(FunctionOfLinear(u, x)):
return False
a_ = Wild('a', exclude=[x])
m_ = Wild('m', exclude=[x])
p_ = Wild('p', exclude=[x])
r_, s_, t_, n_, b_, f_, g_ = map(Wild, 'rstnbfg')
match = u.match(r_*(s_ + t_)**n_)
if match:
if len(match) == 4:
r, s, t, n = [match[i] for i in [r_, s_, t_, n_]]
if IntegerQ(n) and PositiveQ(n):
return False
match = u.match(1/(a_ + b_*f_**n_))
if match:
if len(match) == 4:
a, b, f, n = [match[i] for i in [a_, b_, f_, n_]]
if SinhCoshQ(f) and IntegerQ(n) and n > 2:
return False
match = u.match(f_*g_)
if match:
if len(match) == 2:
f, g = match[f_], match[g_]
if SinhCoshQ(f) and SinhCoshQ(g):
if IntegersQ(f.args[0]/x, g.args[0]/x):
return False
match = u.match(r_*(a_*s_**m_)**p_)
if match:
if len(match) == 5:
r, a, s, m, p = [match[i] for i in [r_, a_, s_, m_, p_]]
if Not(m==2 and (s == Sech(x) or s == Csch(x))):
return False
if u != ExpandIntegrand(u, x):
return False
return True
def TryPureTanhSubst(u, x):
F = u.func
a_ = Wild('a', exclude=[x])
G_ = Wild('G')
if F == sym_log:
return False
match = u.args[0].match(a_*G_)
if match and len(match) == 2:
G = match[G_].func
if MemberQ([atanh, acoth], F) and MemberQ([tanh, coth], G):
return False
if u != ExpandIntegrand(u, x):
return False
return True
def AbsurdNumberGCD(*seq):
# (* m, n, ... must be absurd numbers. AbsurdNumberGCD[m,n,...] returns the gcd of m, n, ... *)
lst = list(seq)
if Length(lst) == 1:
return First(lst)
return AbsurdNumberGCDList(FactorAbsurdNumber(First(lst)), FactorAbsurdNumber(AbsurdNumberGCD(*Rest(lst))))
def AbsurdNumberGCDList(lst1, lst2):
# (* lst1 and lst2 must be absurd number prime factorization lists. *)
# (* AbsurdNumberGCDList[lst1,lst2] returns the gcd of the absurd numbers represented by lst1 and lst2. *)
if lst1 == []:
return Mul(*[i[0]**Min(i[1],0) for i in lst2])
elif lst2 == []:
return Mul(*[i[0]**Min(i[1],0) for i in lst1])
elif lst1[0][0] == lst2[0][0]:
if lst1[0][1] <= lst2[0][1]:
return lst1[0][0]**lst1[0][1]*AbsurdNumberGCDList(Rest(lst1), Rest(lst2))
return lst1[0][0]**lst2[0][1]*AbsurdNumberGCDList(Rest(lst1), Rest(lst2))
elif lst1[0][0] < lst2[0][0]:
if lst1[0][1] < 0:
return lst1[0][0]**lst1[0][1]*AbsurdNumberGCDList(Rest(lst1), lst2)
return AbsurdNumberGCDList(Rest(lst1), lst2)
elif lst2[0][1] < 0:
return lst2[0][0]**lst2[0][1]*AbsurdNumberGCDList(lst1, Rest(lst2))
return AbsurdNumberGCDList(lst1, Rest(lst2))
def ExpandTrigExpand(u, F, v, m, n, x):
w = Expand(TrigExpand(F.xreplace({x: n*x}))**m).xreplace({x: v})
if SumQ(w):
t = 0
for i in w.args:
t += u*i
return t
else:
return u*w
def ExpandTrigReduce(*args):
if len(args) == 3:
u = args[0]
v = args[1]
x = args[2]
w = ExpandTrigReduce(v, x)
if SumQ(w):
t = 0
for i in w.args:
t += u*i
return t
else:
return u*w
else:
u = args[0]
x = args[1]
return ExpandTrigReduceAux(u, x)
def ExpandTrigReduceAux(u, x):
v = TrigReduce(u).expand()
if SumQ(v):
t = 0
for i in v.args:
t += NormalizeTrig(i, x)
return t
return NormalizeTrig(v, x)
def NormalizeTrig(v, x):
a = Wild('a', exclude=[x])
n = Wild('n', exclude=[x, 0])
F = Wild('F')
expr = a*F**n
M = v.match(expr)
if M and len(M[F].args) == 1 and PolynomialQ(M[F].args[0], x) and Exponent(M[F].args[0], x) > 0:
u = M[F].args[0]
return M[a]*M[F].xreplace({u: ExpandToSum(u, x)})**M[n]
else:
return v
#=================================
def TrigToExp(expr):
ex = expr.rewrite(sin, sym_exp).rewrite(cos, sym_exp).rewrite(tan, sym_exp).rewrite(sec, sym_exp).rewrite(csc, sym_exp).rewrite(cot, sym_exp)
return ex.replace(sym_exp, rubi_exp)
def ExpandTrigToExp(u, *args):
if len(args) == 1:
x = args[0]
return ExpandTrigToExp(1, u, x)
else:
v = args[0]
x = args[1]
w = TrigToExp(v)
k = 0
if SumQ(w):
for i in w.args:
k += SimplifyIntegrand(u*i, x)
w = k
else:
w = SimplifyIntegrand(u*w, x)
return ExpandIntegrand(FreeFactors(w, x), NonfreeFactors(w, x),x)
#======================================
def TrigReduce(i):
"""
TrigReduce(expr) rewrites products and powers of trigonometric functions in expr in terms of trigonometric functions with combined arguments.
Examples
========
>>> from sympy import sin, cos
>>> from sympy.integrals.rubi.utility_function import TrigReduce
>>> from sympy.abc import x
>>> TrigReduce(cos(x)**2)
cos(2*x)/2 + 1/2
>>> TrigReduce(cos(x)**2*sin(x))
sin(x)/4 + sin(3*x)/4
>>> TrigReduce(cos(x)**2+sin(x))
sin(x) + cos(2*x)/2 + 1/2
"""
if SumQ(i):
t = 0
for k in i.args:
t += TrigReduce(k)
return t
if ProductQ(i):
if any(PowerQ(k) for k in i.args):
if (i.rewrite((sin, sinh), sym_exp).rewrite((cos, cosh), sym_exp).expand().rewrite(sym_exp, sin)).has(I, cosh, sinh):
return i.rewrite((sin, sinh), sym_exp).rewrite((cos, cosh), sym_exp).expand().rewrite(sym_exp, sin).simplify()
else:
return i.rewrite((sin, sinh), sym_exp).rewrite((cos, cosh), sym_exp).expand().rewrite(sym_exp, sin)
else:
a = Wild('a')
b = Wild('b')
v = Wild('v')
Match = i.match(v*sin(a)*cos(b))
if Match:
a = Match[a]
b = Match[b]
v = Match[v]
return i.subs(v*sin(a)*cos(b), v*S(1)/2*(sin(a + b) + sin(a - b)))
Match = i.match(v*sin(a)*sin(b))
if Match:
a = Match[a]
b = Match[b]
v = Match[v]
return i.subs(v*sin(a)*sin(b), v*S(1)/2*cos(a - b) - cos(a + b))
Match = i.match(v*cos(a)*cos(b))
if Match:
a = Match[a]
b = Match[b]
v = Match[v]
return i.subs(v*cos(a)*cos(b), v*S(1)/2*cos(a + b) + cos(a - b))
Match = i.match(v*sinh(a)*cosh(b))
if Match:
a = Match[a]
b = Match[b]
v = Match[v]
return i.subs(v*sinh(a)*cosh(b), v*S(1)/2*(sinh(a + b) + sinh(a - b)))
Match = i.match(v*sinh(a)*sinh(b))
if Match:
a = Match[a]
b = Match[b]
v = Match[v]
return i.subs(v*sinh(a)*sinh(b), v*S(1)/2*cosh(a - b) - cosh(a + b))
Match = i.match(v*cosh(a)*cosh(b))
if Match:
a = Match[a]
b = Match[b]
v = Match[v]
return i.subs(v*cosh(a)*cosh(b), v*S(1)/2*cosh(a + b) + cosh(a - b))
if PowerQ(i):
if i.has(sin, sinh):
if (i.rewrite((sin, sinh), sym_exp).expand().rewrite(sym_exp, sin)).has(I, cosh, sinh):
return i.rewrite((sin, sinh), sym_exp).expand().rewrite(sym_exp, sin).simplify()
else:
return i.rewrite((sin, sinh), sym_exp).expand().rewrite(sym_exp, sin)
if i.has(cos, cosh):
if (i.rewrite((cos, cosh), sym_exp).expand().rewrite(sym_exp, cos)).has(I, cosh, sinh):
return i.rewrite((cos, cosh), sym_exp).expand().rewrite(sym_exp, cos).simplify()
else:
return i.rewrite((cos, cosh), sym_exp).expand().rewrite(sym_exp, cos)
return i
def FunctionOfTrig(u, *args):
# If u is a function of trig functions of v where v is a linear function of x,
# FunctionOfTrig[u,x] returns v; else it returns False.
if len(args) == 1:
x = args[0]
v = FunctionOfTrig(u, None, x)
if v:
return v
else:
return False
else:
v, x = args
if AtomQ(u):
if u == x:
return False
else:
return v
if TrigQ(u) and LinearQ(u.args[0], x):
if v is None:
return u.args[0]
else:
a = Coefficient(v, x, 0)
b = Coefficient(v, x, 1)
c = Coefficient(u.args[0], x, 0)
d = Coefficient(u.args[0], x, 1)
if ZeroQ(a*d - b*c) and RationalQ(b/d):
return a/Numerator(b/d) + b*x/Numerator(b/d)
else:
return False
if HyperbolicQ(u) and LinearQ(u.args[0], x):
if v is None:
return I*u.args[0]
a = Coefficient(v, x, 0)
b = Coefficient(v, x, 1)
c = I*Coefficient(u.args[0], x, 0)
d = I*Coefficient(u.args[0], x, 1)
if ZeroQ(a*d - b*c) and RationalQ(b/d):
return a/Numerator(b/d) + b*x/Numerator(b/d)
else:
return False
if CalculusQ(u):
return False
else:
w = v
for i in u.args:
w = FunctionOfTrig(i, w, x)
if FalseQ(w):
return False
return w
def AlgebraicTrigFunctionQ(u, x):
# If u is algebraic function of trig functions, AlgebraicTrigFunctionQ(u,x) returns True; else it returns False.
if AtomQ(u):
return True
elif TrigQ(u) and LinearQ(u.args[0], x):
return True
elif HyperbolicQ(u) and LinearQ(u.args[0], x):
return True
elif PowerQ(u):
if FreeQ(u.exp, x):
return AlgebraicTrigFunctionQ(u.base, x)
elif ProductQ(u) or SumQ(u):
for i in u.args:
if not AlgebraicTrigFunctionQ(i, x):
return False
return True
return False
def FunctionOfHyperbolic(u, *x):
# If u is a function of hyperbolic trig functions of v where v is linear in x,
# FunctionOfHyperbolic(u,x) returns v; else it returns False.
if len(x) == 1:
x = x[0]
v = FunctionOfHyperbolic(u, None, x)
if v is None:
return False
else:
return v
else:
v = x[0]
x = x[1]
if AtomQ(u):
if u == x:
return False
return v
if HyperbolicQ(u) and LinearQ(u.args[0], x):
if v is None:
return u.args[0]
a = Coefficient(v, x, 0)
b = Coefficient(v, x, 1)
c = Coefficient(u.args[0], x, 0)
d = Coefficient(u.args[0], x, 1)
if ZeroQ(a*d - b*c) and RationalQ(b/d):
return a/Numerator(b/d) + b*x/Numerator(b/d)
else:
return False
if CalculusQ(u):
return False
w = v
for i in u.args:
if w == FunctionOfHyperbolic(i, w, x):
return False
return w
def FunctionOfQ(v, u, x, PureFlag=False):
# v is a function of x. If u is a function of v, FunctionOfQ(v, u, x) returns True; else it returns False. *)
if FreeQ(u, x):
return False
elif AtomQ(v):
return True
elif ProductQ(v) and Not(EqQ(FreeFactors(v, x), 1)):
return FunctionOfQ(NonfreeFactors(v, x), u, x, PureFlag)
elif PureFlag:
if SinQ(v) or CscQ(v):
return PureFunctionOfSinQ(u, v.args[0], x)
elif CosQ(v) or SecQ(v):
return PureFunctionOfCosQ(u, v.args[0], x)
elif TanQ(v):
return PureFunctionOfTanQ(u, v.args[0], x)
elif CotQ(v):
return PureFunctionOfCotQ(u, v.args[0], x)
elif SinhQ(v) or CschQ(v):
return PureFunctionOfSinhQ(u, v.args[0], x)
elif CoshQ(v) or SechQ(v):
return PureFunctionOfCoshQ(u, v.args[0], x)
elif TanhQ(v):
return PureFunctionOfTanhQ(u, v.args[0], x)
elif CothQ(v):
return PureFunctionOfCothQ(u, v.args[0], x)
else:
return FunctionOfExpnQ(u, v, x) != False
elif SinQ(v) or CscQ(v):
return FunctionOfSinQ(u, v.args[0], x)
elif CosQ(v) or SecQ(v):
return FunctionOfCosQ(u, v.args[0], x)
elif TanQ(v) or CotQ(v):
FunctionOfTanQ(u, v.args[0], x)
elif SinhQ(v) or CschQ(v):
return FunctionOfSinhQ(u, v.args[0], x)
elif CoshQ(v) or SechQ(v):
return FunctionOfCoshQ(u, v.args[0], x)
elif TanhQ(v) or CothQ(v):
return FunctionOfTanhQ(u, v.args[0], x)
return FunctionOfExpnQ(u, v, x) != False
def FunctionOfExpnQ(u, v, x):
if u == v:
return 1
if AtomQ(u):
if u == x:
return False
else:
return 0
if CalculusQ(u):
return False
if PowerQ(u):
if FreeQ(u.exp, x):
if ZeroQ(u.base - v):
if IntegerQ(u.exp):
return u.exp
else:
return 1
if PowerQ(v):
if FreeQ(v.exp, x) and ZeroQ(u.base-v.base):
if RationalQ(v.exp):
if RationalQ(u.exp) and IntegerQ(u.exp/v.exp) and (v.exp>0 or u.exp<0):
return u.exp/v.exp
else:
return False
if IntegerQ(Simplify(u.exp/v.exp)):
return Simplify(u.exp/v.exp)
else:
return False
return FunctionOfExpnQ(u.base, v, x)
if ProductQ(u) and Not(EqQ(FreeFactors(u, x), 1)):
return FunctionOfExpnQ(NonfreeFactors(u, x), v, x)
if ProductQ(u) and ProductQ(v):
deg1 = FunctionOfExpnQ(First(u), First(v), x)
if deg1==False:
return False
deg2 = FunctionOfExpnQ(Rest(u), Rest(v), x);
if deg1==deg2 and FreeQ(Simplify(u/v^deg1), x):
return deg1
else:
return False
lst = []
for i in u.args:
if FunctionOfExpnQ(i, v, x) is False:
return False
lst.append(FunctionOfExpnQ(i, v, x))
return Apply(GCD, lst)
def PureFunctionOfSinQ(u, v, x):
# If u is a pure function of Sin(v) and/or Csc(v), PureFunctionOfSinQ(u, v, x) returns True; else it returns False.
if AtomQ(u):
return u!=x
if CalculusQ(u):
return False
if TrigQ(u) and ZeroQ(u.args[0]-v):
return SinQ(u) or CscQ(u)
for i in u.args:
if Not(PureFunctionOfSinQ(i, v, x)):
return False
return True
def PureFunctionOfCosQ(u, v, x):
# If u is a pure function of Cos(v) and/or Sec(v), PureFunctionOfCosQ(u, v, x) returns True; else it returns False.
if AtomQ(u):
return u!=x
if CalculusQ(u):
return False
if TrigQ(u) and ZeroQ(u.args[0]-v):
return CosQ(u) or SecQ(u)
for i in u.args:
if Not(PureFunctionOfCosQ(i, v, x)):
return False
return True
def PureFunctionOfTanQ(u, v, x):
# If u is a pure function of Tan(v) and/or Cot(v), PureFunctionOfTanQ(u, v, x) returns True; else it returns False.
if AtomQ(u):
return u!=x
if CalculusQ(u):
return False
if TrigQ(u) and ZeroQ(u.args[0]-v):
return TanQ(u) or CotQ(u)
for i in u.args:
if Not(PureFunctionOfTanQ(i, v, x)):
return False
return True
def PureFunctionOfCotQ(u, v, x):
# If u is a pure function of Cot(v), PureFunctionOfCotQ(u, v, x) returns True; else it returns False.
if AtomQ(u):
return u!=x
if CalculusQ(u):
return False
if TrigQ(u) and ZeroQ(u.args[0]-v):
return CotQ(u)
for i in u.args:
if Not(PureFunctionOfCotQ(i, v, x)):
return False
return True
def FunctionOfCosQ(u, v, x):
# If u is a function of Cos[v], FunctionOfCosQ[u,v,x] returns True; else it returns False.
if AtomQ(u):
return u != x
elif CalculusQ(u):
return False
elif TrigQ(u) and IntegerQuotientQ(u.args[0], v):
# Basis: If m integer, Cos[m*v]^n is a function of Cos[v]. *)
return CosQ(u) or SecQ(u)
elif IntegerPowerQ(u):
if TrigQ(u.base) and IntegerQuotientQ(u.base.args[0], v):
if EvenQ(u.exp):
# Basis: If m integer and n even, Trig[m*v]^n is a function of Cos[v]. *)
return True
return FunctionOfCosQ(u.base, v, x)
elif ProductQ(u):
lst = FindTrigFactor(sin, csc, u, v, False)
if ListQ(lst):
# (* Basis: If m integer and n odd, Sin[m*v]^n == Sin[v]*u where u is a function of Cos[v]. *)
return FunctionOfCosQ(Sin(v)*lst[1], v, x)
lst = FindTrigFactor(tan, cot, u, v, True)
if ListQ(lst):
# (* Basis: If m integer and n odd, Tan[m*v]^n == Sin[v]*u where u is a function of Cos[v]. *)
return FunctionOfCosQ(Sin(v)*lst[1], v, x)
return all(FunctionOfCosQ(i, v, x) for i in u.args)
return all(FunctionOfCosQ(i, v, x) for i in u.args)
def FunctionOfSinQ(u, v, x):
# If u is a function of Sin[v], FunctionOfSinQ[u,v,x] returns True; else it returns False.
if AtomQ(u):
return u != x
elif CalculusQ(u):
return False
elif TrigQ(u) and IntegerQuotientQ(u.args[0], v):
if OddQuotientQ(u.args[0], v):
# Basis: If m odd, Sin[m*v]^n is a function of Sin[v].
return SinQ(u) or CscQ(u)
# Basis: If m even, Cos[m*v]^n is a function of Sin[v].
return CosQ(u) or SecQ(u)
elif IntegerPowerQ(u):
if TrigQ(u.base) and IntegerQuotientQ(u.base.args[0], v):
if EvenQ(u.exp):
# Basis: If m integer and n even, Hyper[m*v]^n is a function of Sin[v].
return True
return FunctionOfSinQ(u.base, v, x)
elif ProductQ(u):
if CosQ(u.args[0]) and SinQ(u.args[1]) and ZeroQ(u.args[0].args[0] - v/2) and ZeroQ(u.args[1].args[0] - v/2):
return FunctionOfSinQ(Drop(u, 2), v, x)
lst = FindTrigFactor(sin, csch, u, v, False)
if ListQ(lst) and EvenQuotientQ(lst[0], v):
# Basis: If m even and n odd, Sin[m*v]^n == Cos[v]*u where u is a function of Sin[v].
return FunctionOfSinQ(Cos(v)*lst[1], v, x)
lst = FindTrigFactor(cos, sec, u, v, False)
if ListQ(lst) and OddQuotientQ(lst[0], v):
# Basis: If m odd and n odd, Cos[m*v]^n == Cos[v]*u where u is a function of Sin[v].
return FunctionOfSinQ(Cos(v)*lst[1], v, x)
lst = FindTrigFactor(tan, cot, u, v, True)
if ListQ(lst):
# Basis: If m integer and n odd, Tan[m*v]^n == Cos[v]*u where u is a function of Sin[v].
return FunctionOfSinQ(Cos(v)*lst[1], v, x)
return all(FunctionOfSinQ(i, v, x) for i in u.args)
return all(FunctionOfSinQ(i, v, x) for i in u.args)
def OddTrigPowerQ(u, v, x):
if SinQ(u) or CosQ(u) or SecQ(u) or CscQ(u):
return OddQuotientQ(u.args[0], v)
if PowerQ(u):
return OddQ(u.exp) and OddTrigPowerQ(u.base, v, x)
if ProductQ(u):
if not FreeFactors(u, x) == 1:
return OddTrigPowerQ(NonfreeFactors(u, x), v, x)
lst = []
for i in u.args:
if Not(FunctionOfTanQ(i, v, x)):
lst.append(i)
if lst == []:
return True
return Length(lst)==1 and OddTrigPowerQ(lst[0], v, x)
if SumQ(u):
return all(OddTrigPowerQ(i, v, x) for i in u.args)
return False
def FunctionOfTanQ(u, v, x):
# If u is a function of the form f[Tan[v],Cot[v]] where f is independent of x,
# FunctionOfTanQ[u,v,x] returns True; else it returns False.
if AtomQ(u):
return u != x
elif CalculusQ(u):
return False
elif TrigQ(u) and IntegerQuotientQ(u.args[0], v):
return TanQ(u) or CotQ(u) or EvenQuotientQ(u.args[0], v)
elif PowerQ(u):
if EvenQ(u.exp) and TrigQ(u.base) and IntegerQuotientQ(u.base.args[0], v):
return True
elif EvenQ(u.exp) and SumQ(u.base):
return FunctionOfTanQ(Expand(u.base**2, v, x))
if ProductQ(u):
lst = []
for i in u.args:
if Not(FunctionOfTanQ(i, v, x)):
lst.append(i)
if lst == []:
return True
return Length(lst)==2 and OddTrigPowerQ(lst[0], v, x) and OddTrigPowerQ(lst[1], v, x)
return all(FunctionOfTanQ(i, v, x) for i in u.args)
def FunctionOfTanWeight(u, v, x):
# (* u is a function of the form f[Tan[v],Cot[v]] where f is independent of x.
# FunctionOfTanWeight[u,v,x] returns a nonnegative number if u is best considered a function
# of Tan[v]; else it returns a negative number. *)
if AtomQ(u):
return S(0)
elif CalculusQ(u):
return S(0)
elif TrigQ(u) and IntegerQuotientQ(u.args[0], v):
if TanQ(u) and ZeroQ(u.args[0] - v):
return S(1)
elif CotQ(u) and ZeroQ(u.args[0] - v):
return S(-1)
return S(0)
elif PowerQ(u):
if EvenQ(u.exp) and TrigQ(u.base) and IntegerQuotientQ(u.base.args[0], v):
if TanQ(u.base) or CosQ(u.base) or SecQ(u.base):
return S(1)
return S(-1)
if ProductQ(u):
if all(FunctionOfTanQ(i, v, x) for i in u.args):
return Add(*[FunctionOfTanWeight(i, v, x) for i in u.args])
return S(0)
return Add(*[FunctionOfTanWeight(i, v, x) for i in u.args])
def FunctionOfTrigQ(u, v, x):
# If u (x) is equivalent to a function of the form f (Sin[v],Cos[v],Tan[v],Cot[v],Sec[v],Csc[v]) where f is independent of x, FunctionOfTrigQ[u,v,x] returns True; else it returns False.
if AtomQ(u):
return u != x
elif CalculusQ(u):
return False
elif TrigQ(u) and IntegerQuotientQ(u.args[0], v):
return True
return all(FunctionOfTrigQ(i, v, x) for i in u.args)
def FunctionOfDensePolynomialsQ(u, x):
# If all occurrences of x in u (x) are in dense polynomials, FunctionOfDensePolynomialsQ[u,x] returns True; else it returns False.
if FreeQ(u, x):
return True
if PolynomialQ(u, x):
return Length(ExponentList(u, x)) > 1
return all(FunctionOfDensePolynomialsQ(i, x) for i in u.args)
def FunctionOfLog(u, *args):
# If u (x) is equivalent to an expression of the form f (Log[a*x^n]), FunctionOfLog[u,x] returns
# the list {f (x),a*x^n,n}; else it returns False.
if len(args) == 1:
x = args[0]
lst = FunctionOfLog(u, False, False, x)
if AtomQ(lst) or FalseQ(lst[1]) or not isinstance(x, Symbol):
return False
else:
return lst
else:
v = args[0]
n = args[1]
x = args[2]
if AtomQ(u):
if u==x:
return False
else:
return [u, v, n]
if CalculusQ(u):
return False
lst = BinomialParts(u.args[0], x)
if LogQ(u) and ListQ(lst) and ZeroQ(lst[0]):
if FalseQ(v) or u.args[0] == v:
return [x, u.args[0], lst[2]]
else:
return False
lst = [0, v, n]
l = []
for i in u.args:
lst = FunctionOfLog(i, lst[1], lst[2], x)
if AtomQ(lst):
return False
else:
l.append(lst[0])
return [u.func(*l), lst[1], lst[2]]
def PowerVariableExpn(u, m, x):
# If m is an integer, u is an expression of the form f((c*x)**n) and g=GCD(m,n)>1,
# PowerVariableExpn(u,m,x) returns the list {x**(m/g)*f((c*x)**(n/g)),g,c}; else it returns False.
if IntegerQ(m):
lst = PowerVariableDegree(u, m, 1, x)
if not lst:
return False
else:
return [x**(m/lst[0])*PowerVariableSubst(u, lst[0], x), lst[0], lst[1]]
else:
return False
def PowerVariableDegree(u, m, c, x):
if FreeQ(u, x):
return [m, c]
if AtomQ(u) or CalculusQ(u):
return False
if PowerQ(u):
if FreeQ(u.base/x, x):
if ZeroQ(m) or m == u.exp and c == u.base/x:
return [u.exp, u.base/x]
if IntegerQ(u.exp) and IntegerQ(m) and GCD(m, u.exp)>1 and c==u.base/x:
return [GCD(m, u.exp), c]
else:
return False
lst = [m, c]
for i in u.args:
if PowerVariableDegree(i, lst[0], lst[1], x) == False:
return False
lst1 = PowerVariableDegree(i, lst[0], lst[1], x)
if not lst1:
return False
else:
return lst1
def PowerVariableSubst(u, m, x):
if FreeQ(u, x) or AtomQ(u) or CalculusQ(u):
return u
if PowerQ(u):
if FreeQ(u.base/x, x):
return x**(u.exp/m)
if ProductQ(u):
l = 1
for i in u.args:
l *= (PowerVariableSubst(i, m, x))
return l
if SumQ(u):
l = 0
for i in u.args:
l += (PowerVariableSubst(i, m, x))
return l
return u
def EulerIntegrandQ(expr, x):
a = Wild('a', exclude=[x])
b = Wild('b', exclude=[x])
n = Wild('n', exclude=[x, 0])
m = Wild('m', exclude=[x, 0])
p = Wild('p', exclude=[x, 0])
u = Wild('u')
v = Wild('v')
# Pattern 1
M = expr.match((a*x + b*u**n)**p)
if M:
if len(M) == 5 and FreeQ([M[a], M[b]], x) and IntegerQ(M[n] + 1/2) and QuadraticQ(M[u], x) and Not(RationalQ(M[p])) or NegativeIntegerQ(M[p]) and Not(BinomialQ(M[u], x)):
return True
# Pattern 2
M = expr.match(v**m*(a*x + b*u**n)**p)
if M:
if len(M) == 6 and FreeQ([M[a], M[b]], x) and ZeroQ(M[u] - M[v]) and IntegersQ(2*M[m], M[n] + 1/2) and QuadraticQ(M[u], x) and Not(RationalQ(M[p])) or NegativeIntegerQ(M[p]) and Not(BinomialQ(M[u], x)):
return True
# Pattern 3
M = expr.match(u**n*v**p)
if M:
if len(M) == 3 and NegativeIntegerQ(M[p]) and IntegerQ(M[n] + 1/2) and QuadraticQ(M[u], x) and QuadraticQ(M[v], x) and Not(BinomialQ(M[v], x)):
return True
else:
return False
def FunctionOfSquareRootOfQuadratic(u, *args):
if len(args) == 1:
x = args[0]
pattern = Pattern(UtilityOperator(x_**WC('m', 1)*(a_ + x**WC('n', 1)*WC('b', 1))**p_, x), CustomConstraint(lambda a, b, m, n, p, x: FreeQ([a, b, m, n, p], x)))
M = is_match(UtilityOperator(u, args[0]), pattern)
if M:
return False
tmp = FunctionOfSquareRootOfQuadratic(u, False, x)
if AtomQ(tmp) or FalseQ(tmp[0]):
return False
tmp = tmp[0]
a = Coefficient(tmp, x, 0)
b = Coefficient(tmp, x, 1)
c = Coefficient(tmp, x, 2)
if ZeroQ(a) and ZeroQ(b) or ZeroQ(b**2-4*a*c):
return False
if PosQ(c):
sqrt = Rt(c, S(2));
q = a*sqrt + b*x + sqrt*x**2
r = b + 2*sqrt*x
return [Simplify(SquareRootOfQuadraticSubst(u, q/r, (-a+x**2)/r, x)*q/r**2), Simplify(sqrt*x + Sqrt(tmp)), 2]
if PosQ(a):
sqrt = Rt(a, S(2))
q = c*sqrt - b*x + sqrt*x**2
r = c - x**2
return [Simplify(SquareRootOfQuadraticSubst(u, q/r, (-b+2*sqrt*x)/r, x)*q/r**2), Simplify((-sqrt+Sqrt(tmp))/x), 1]
sqrt = Rt(b**2 - 4*a*c, S(2))
r = c - x**2
return[Simplify(-sqrt*SquareRootOfQuadraticSubst(u, -sqrt*x/r, -(b*c+c*sqrt+(-b+sqrt)*x**2)/(2*c*r), x)*x/r**2), FullSimplify(2*c*Sqrt(tmp)/(b-sqrt+2*c*x)), 3]
else:
v = args[0]
x = args[1]
if AtomQ(u) or FreeQ(u, x):
return [v]
if PowerQ(u):
if FreeQ(u.exp, x):
if FractionQ(u.exp) and Denominator(u.exp) == 2 and PolynomialQ(u.base, x) and Exponent(u.base, x) == 2:
if FalseQ(v) or u.base == v:
return [u.base]
else:
return False
return FunctionOfSquareRootOfQuadratic(u.base, v, x)
if ProductQ(u) or SumQ(u):
lst = [v]
lst1 = []
for i in u.args:
if FunctionOfSquareRootOfQuadratic(i, lst[0], x) == False:
return False
lst1 = FunctionOfSquareRootOfQuadratic(i, lst[0], x)
return lst1
else:
return False
def SquareRootOfQuadraticSubst(u, vv, xx, x):
# SquareRootOfQuadraticSubst(u, vv, xx, x) returns u with fractional powers replaced by vv raised to the power and x replaced by xx.
if AtomQ(u) or FreeQ(u, x):
if u==x:
return xx
return u
if PowerQ(u):
if FreeQ(u.exp, x):
if FractionQ(u.exp) and Denominator(u.exp)==2 and PolynomialQ(u.base, x) and Exponent(u.base, x)==2:
return vv**Numerator(u.exp)
return SquareRootOfQuadraticSubst(u.base, vv, xx, x)**u.exp
elif SumQ(u):
t = 0
for i in u.args:
t += SquareRootOfQuadraticSubst(i, vv, xx, x)
return t
elif ProductQ(u):
t = 1
for i in u.args:
t *= SquareRootOfQuadraticSubst(i, vv, xx, x)
return t
def Divides(y, u, x):
# If u divided by y is free of x, Divides[y,u,x] returns the quotient; else it returns False.
v = Simplify(u/y)
if FreeQ(v, x):
return v
else:
return False
def DerivativeDivides(y, u, x):
"""
If y not equal to x, y is easy to differentiate wrt x, and u divided by the derivative of y
is free of x, DerivativeDivides[y,u,x] returns the quotient; else it returns False.
"""
from matchpy import is_match
pattern0 = Pattern(Mul(a , b_), CustomConstraint(lambda a, b : FreeQ(a, b)))
def f1(y, u, x):
if PolynomialQ(y, x):
return PolynomialQ(u, x) and Exponent(u, x) == Exponent(y, x) - 1
else:
return EasyDQ(y, x)
if is_match(y, pattern0):
return False
elif f1(y, u, x):
v = D(y ,x)
if EqQ(v, 0):
return False
else:
v = Simplify(u/v)
if FreeQ(v, x):
return v
else:
return False
else:
return False
def EasyDQ(expr, x):
# If u is easy to differentiate wrt x, EasyDQ(u, x) returns True; else it returns False *)
u = Wild('u',exclude=[1])
m = Wild('m',exclude=[x, 0])
M = expr.match(u*x**m)
if M:
return EasyDQ(M[u], x)
if AtomQ(expr) or FreeQ(expr, x) or Length(expr)==0:
return True
elif CalculusQ(expr):
return False
elif Length(expr)==1:
return EasyDQ(expr.args[0], x)
elif BinomialQ(expr, x) or ProductOfLinearPowersQ(expr, x):
return True
elif RationalFunctionQ(expr, x) and RationalFunctionExponents(expr, x)==[1, 1]:
return True
elif ProductQ(expr):
if FreeQ(First(expr), x):
return EasyDQ(Rest(expr), x)
elif FreeQ(Rest(expr), x):
return EasyDQ(First(expr), x)
else:
return False
elif SumQ(expr):
return EasyDQ(First(expr), x) and EasyDQ(Rest(expr), x)
elif Length(expr)==2:
if FreeQ(expr.args[0], x):
EasyDQ(expr.args[1], x)
elif FreeQ(expr.args[1], x):
return EasyDQ(expr.args[0], x)
else:
return False
return False
def ProductOfLinearPowersQ(u, x):
# ProductOfLinearPowersQ(u, x) returns True iff u is a product of factors of the form v^n where v is linear in x
v = Wild('v')
n = Wild('n', exclude=[x])
M = u.match(v**n)
return FreeQ(u, x) or M and LinearQ(M[v], x) or ProductQ(u) and ProductOfLinearPowersQ(First(u), x) and ProductOfLinearPowersQ(Rest(u), x)
def Rt(u, n):
return RtAux(TogetherSimplify(u), n)
def NthRoot(u, n):
return nsimplify(u**(S(1)/n))
def AtomBaseQ(u):
# If u is an atom or an atom raised to an odd degree, AtomBaseQ(u) returns True; else it returns False
return AtomQ(u) or PowerQ(u) and OddQ(u.args[1]) and AtomBaseQ(u.args[0])
def SumBaseQ(u):
# If u is a sum or a sum raised to an odd degree, SumBaseQ(u) returns True; else it returns False
return SumQ(u) or PowerQ(u) and OddQ(u.args[1]) and SumBaseQ(u.args[0])
def NegSumBaseQ(u):
# If u is a sum or a sum raised to an odd degree whose lead term has a negative form, NegSumBaseQ(u) returns True; else it returns False
return SumQ(u) and NegQ(First(u)) or PowerQ(u) and OddQ(u.args[1]) and NegSumBaseQ(u.args[0])
def AllNegTermQ(u):
# If all terms of u have a negative form, AllNegTermQ(u) returns True; else it returns False
if PowerQ(u):
if OddQ(u.exp):
return AllNegTermQ(u.base)
if SumQ(u):
return NegQ(First(u)) and AllNegTermQ(Rest(u))
return NegQ(u)
def SomeNegTermQ(u):
# If some term of u has a negative form, SomeNegTermQ(u) returns True; else it returns False
if PowerQ(u):
if OddQ(u.exp):
return SomeNegTermQ(u.base)
if SumQ(u):
return NegQ(First(u)) or SomeNegTermQ(Rest(u))
return NegQ(u)
def TrigSquareQ(u):
# If u is an expression of the form Sin(z)^2 or Cos(z)^2, TrigSquareQ(u) returns True, else it returns False
return PowerQ(u) and EqQ(u.args[1], 2) and MemberQ([sin, cos], Head(u.args[0]))
def RtAux(u, n):
if PowerQ(u):
return u.base**(u.exp/n)
if ComplexNumberQ(u):
a = Re(u)
b = Im(u)
if Not(IntegerQ(a) and IntegerQ(b)) and IntegerQ(a/(a**2 + b**2)) and IntegerQ(b/(a**2 + b**2)):
# Basis: a+b*I==1/(a/(a^2+b^2)-b/(a^2+b^2)*I)
return S(1)/RtAux(a/(a**2 + b**2) - b/(a**2 + b**2)*I, n)
else:
return NthRoot(u, n)
if ProductQ(u):
lst = SplitProduct(PositiveQ, u)
if ListQ(lst):
return RtAux(lst[0], n)*RtAux(lst[1], n)
lst = SplitProduct(NegativeQ, u)
if ListQ(lst):
if EqQ(lst[0], -1):
v = lst[1]
if PowerQ(v):
if NegativeQ(v.exp):
return 1/RtAux(-v.base**(-v.exp), n)
if ProductQ(v):
if ListQ(SplitProduct(SumBaseQ, v)):
lst = SplitProduct(AllNegTermQ, v)
if ListQ(lst):
return RtAux(-lst[0], n)*RtAux(lst[1], n)
lst = SplitProduct(NegSumBaseQ, v)
if ListQ(lst):
return RtAux(-lst[0], n)*RtAux(lst[1], n)
lst = SplitProduct(SomeNegTermQ, v)
if ListQ(lst):
return RtAux(-lst[0], n)*RtAux(lst[1], n)
lst = SplitProduct(SumBaseQ, v)
return RtAux(-lst[0], n)*RtAux(lst[1], n)
lst = SplitProduct(AtomBaseQ, v)
if ListQ(lst):
return RtAux(-lst[0], n)*RtAux(lst[1], n)
else:
return RtAux(-First(v), n)*RtAux(Rest(v), n)
if OddQ(n):
return -RtAux(v, n)
else:
return NthRoot(u, n)
else:
return RtAux(-lst[0], n)*RtAux(-lst[1], n)
lst = SplitProduct(AllNegTermQ, u)
if ListQ(lst) and ListQ(SplitProduct(SumBaseQ, lst[1])):
return RtAux(-lst[0], n)*RtAux(-lst[1], n)
lst = SplitProduct(NegSumBaseQ, u)
if ListQ(lst) and ListQ(SplitProduct(NegSumBaseQ, lst[1])):
return RtAux(-lst[0], n)*RtAux(-lst[1], n)
return u.func(*[RtAux(i, n) for i in u.args])
v = TrigSquare(u)
if Not(AtomQ(v)):
return RtAux(v, n)
if OddQ(n) and NegativeQ(u):
return -RtAux(-u, n)
if OddQ(n) and NegQ(u) and PosQ(-u):
return -RtAux(-u, n)
else:
return NthRoot(u, n)
def TrigSquare(u):
# If u is an expression of the form a-a*Sin(z)^2 or a-a*Cos(z)^2, TrigSquare(u) returns Cos(z)^2 or Sin(z)^2 respectively,
# else it returns False.
if SumQ(u):
for i in u.args:
v = SplitProduct(TrigSquareQ, i)
if v == False or SplitSum(v, u) == False:
return False
lst = SplitSum(SplitProduct(TrigSquareQ, i))
if lst and ZeroQ(lst[1][2] + lst[1]):
if Head(lst[0][0].args[0]) == sin:
return lst[1]*cos(lst[1][1][1][1])**2
return lst[1]*sin(lst[1][1][1][1])**2
else:
return False
else:
return False
def IntSum(u, x):
# If u is free of x or of the form c*(a+b*x)^m, IntSum[u,x] returns the antiderivative of u wrt x;
# else it returns d*Int[v,x] where d*v=u and d is free of x.
return Add(*[Integral(i, x) for i in u.args])
def IntTerm(expr, x):
# If u is of the form c*(a+b*x)**m, IntTerm(u,x) returns the antiderivative of u wrt x;
# else it returns d*Int(v,x) where d*v=u and d is free of x.
c = Wild('c', exclude=[x])
m = Wild('m', exclude=[x, 0])
v = Wild('v')
M = expr.match(c/v)
if M and len(M) == 2 and FreeQ(M[c], x) and LinearQ(M[v], x):
return Simp(M[c]*Log(RemoveContent(M[v], x))/Coefficient(M[v], x, 1), x)
M = expr.match(c*v**m)
if M and len(M) == 3 and NonzeroQ(M[m] + 1) and LinearQ(M[v], x):
return Simp(M[c]*M[v]**(M[m] + 1)/(Coefficient(M[v], x, 1)*(M[m] + 1)), x)
if SumQ(expr):
t = 0
for i in expr.args:
t += IntTerm(i, x)
return t
else:
u = expr
return Dist(FreeFactors(u,x), Integral(NonfreeFactors(u, x), x), x)
def Map2(f, lst1, lst2):
result = []
for i in range(0, len(lst1)):
result.append(f(lst1[i], lst2[i]))
return result
def ConstantFactor(u, x):
# (* ConstantFactor[u,x] returns a 2-element list of the factors of u[x] free of x and the
# factors not free of u[x]. Common constant factors of the terms of sums are also collected. *)
if FreeQ(u, x):
return [u, S(1)]
elif AtomQ(u):
return [S(1), u]
elif PowerQ(u):
if FreeQ(u.exp, x):
lst = ConstantFactor(u.base, x)
if IntegerQ(u.exp):
return [lst[0]**u.exp, lst[1]**u.exp]
tmp = PositiveFactors(lst[0])
if tmp == 1:
return [S(1), u]
return [tmp**u.exp, (NonpositiveFactors(lst[0])*lst[1])**u.exp]
elif ProductQ(u):
lst = [ConstantFactor(i, x) for i in u.args]
return [Mul(*[First(i) for i in lst]), Mul(*[i[1] for i in lst])]
elif SumQ(u):
lst1 = [ConstantFactor(i, x) for i in u.args]
if SameQ(*[i[1] for i in lst1]):
return [Add(*[i[0] for i in lst]), lst1[0][1]]
lst2 = CommonFactors([First(i) for i in lst1])
return [First(lst2), Add(*Map2(Mul, Rest(lst2), [i[1] for i in lst1]))]
return [S(1), u]
def SameQ(*args):
for i in range(0, len(args) - 1):
if args[i] != args[i+1]:
return False
return True
def ReplacePart(lst, a, b):
lst[b] = a
return lst
def CommonFactors(lst):
# (* If lst is a list of n terms, CommonFactors[lst] returns a n+1-element list whose first
# element is the product of the factors common to all terms of lst, and whose remaining
# elements are quotients of each term divided by the common factor. *)
lst1 = [NonabsurdNumberFactors(i) for i in lst]
lst2 = [AbsurdNumberFactors(i) for i in lst]
num = AbsurdNumberGCD(*lst2)
common = num
lst2 = [i/num for i in lst2]
while (True):
lst3 = [LeadFactor(i) for i in lst1]
if SameQ(*lst3):
common = common*lst3[0]
lst1 = [RemainingFactors(i) for i in lst1]
elif (all((LogQ(i) and IntegerQ(First(i)) and First(i) > 0) for i in lst3) and
all(RationalQ(i) for i in [FullSimplify(j/First(lst3)) for j in lst3])):
lst4 = [FullSimplify(j/First(lst3)) for j in lst3]
num = GCD(*lst4)
common = common*Log((First(lst3)[0])**num)
lst2 = [lst2[i]*lst4[i]/num for i in range(0, len(lst2))]
lst1 = [RemainingFactors(i) for i in lst1]
lst4 = [LeadDegree(i) for i in lst1]
if SameQ(*[LeadBase(i) for i in lst1]) and RationalQ(*lst4):
num = Smallest(lst4)
base = LeadBase(lst1[0])
if num != 0:
common = common*base**num
lst2 = [lst2[i]*base**(lst4[i] - num) for i in range(0, len(lst2))]
lst1 = [RemainingFactors(i) for i in lst1]
elif (Length(lst1) == 2 and ZeroQ(LeadBase(lst1[0]) + LeadBase(lst1[1])) and
NonzeroQ(lst1[0] - 1) and IntegerQ(lst4[0]) and FractionQ(lst4[1])):
num = Min(*lst4)
base = LeadBase(lst1[1])
if num != 0:
common = common*base**num
lst2 = [lst2[0]*(-1)**lst4[0], lst2[1]]
lst2 = [lst2[i]*base**(lst4[i] - num) for i in range(0, len(lst2))]
lst1 = [RemainingFactors(i) for i in lst1]
elif (Length(lst1) == 2 and ZeroQ(lst1[0] + LeadBase(lst1[1])) and
NonzeroQ(lst1[1] - 1) and IntegerQ(lst1[1]) and FractionQ(lst4[0])):
num = Min(*lst4)
base = LeadBase(lst1[0])
if num != 0:
common = common*base**num
lst2 = [lst2[0], lst2[1]*(-1)**lst4[1]]
lst2 = [lst2[i]*base**(lst4[i] - num) for i in range(0, len(lst2))]
lst1 = [RemainingFactors(i) for i in lst1]
else:
num = MostMainFactorPosition(lst3)
lst2 = ReplacePart(lst2, lst3[num]*lst2[num], num)
lst1 = ReplacePart(lst1, RemainingFactors(lst1[num]), num)
if all(i==1 for i in lst1):
return Prepend(lst2, common)
def MostMainFactorPosition(lst):
factor = S(1)
num = 0
for i in range(0, Length(lst)):
if FactorOrder(lst[i], factor) > 0:
factor = lst[i]
num = i
return num
SbaseS, SexponS = None, None
SexponFlagS = False
def FunctionOfExponentialQ(u, x):
# (* FunctionOfExponentialQ[u,x] returns True iff u is a function of F^v where F is a constant and v is linear in x, *)
# (* and such an exponential explicitly occurs in u (i.e. not just implicitly in hyperbolic functions). *)
global SbaseS, SexponS, SexponFlagS
SbaseS, SexponS = None, None
SexponFlagS = False
res = FunctionOfExponentialTest(u, x)
return res and SexponFlagS
def FunctionOfExponential(u, x):
global SbaseS, SexponS, SexponFlagS
# (* u is a function of F^v where v is linear in x. FunctionOfExponential[u,x] returns F^v. *)
SbaseS, SexponS = None, None
SexponFlagS = False
FunctionOfExponentialTest(u, x)
return SbaseS**SexponS
def FunctionOfExponentialFunction(u, x):
global SbaseS, SexponS, SexponFlagS
# (* u is a function of F^v where v is linear in x. FunctionOfExponentialFunction[u,x] returns u with F^v replaced by x. *)
SbaseS, SexponS = None, None
SexponFlagS = False
FunctionOfExponentialTest(u, x)
return SimplifyIntegrand(FunctionOfExponentialFunctionAux(u, x), x)
def FunctionOfExponentialFunctionAux(u, x):
# (* u is a function of F^v where v is linear in x, and the fluid variables $base$=F and $expon$=v. *)
# (* FunctionOfExponentialFunctionAux[u,x] returns u with F^v replaced by x. *)
global SbaseS, SexponS, SexponFlagS
if AtomQ(u):
return u
elif PowerQ(u):
if FreeQ(u.base, x) and LinearQ(u.exp, x):
if ZeroQ(Coefficient(SexponS, x, 0)):
return u.base**Coefficient(u.exp, x, 0)*x**FullSimplify(Log(u.base)*Coefficient(u.exp, x, 1)/(Log(SbaseS)*Coefficient(SexponS, x, 1)))
return x**FullSimplify(Log(u.base)*Coefficient(u.exp, x, 1)/(Log(SbaseS)*Coefficient(SexponS, x, 1)))
elif HyperbolicQ(u) and LinearQ(u.args[0], x):
tmp = x**FullSimplify(Coefficient(u.args[0], x, 1)/(Log(SbaseS)*Coefficient(SexponS, x, 1)))
if SinhQ(u):
return tmp/2 - 1/(2*tmp)
elif CoshQ(u):
return tmp/2 + 1/(2*tmp)
elif TanhQ(u):
return (tmp - 1/tmp)/(tmp + 1/tmp)
elif CothQ(u):
return (tmp + 1/tmp)/(tmp - 1/tmp)
elif SechQ(u):
return 2/(tmp + 1/tmp)
return 2/(tmp - 1/tmp)
if PowerQ(u):
if FreeQ(u.base, x) and SumQ(u.exp):
return FunctionOfExponentialFunctionAux(u.base**First(u.exp), x)*FunctionOfExponentialFunctionAux(u.base**Rest(u.exp), x)
return u.func(*[FunctionOfExponentialFunctionAux(i, x) for i in u.args])
def FunctionOfExponentialTest(u, x):
# (* FunctionOfExponentialTest[u,x] returns True iff u is a function of F^v where F is a constant and v is linear in x. *)
# (* Before it is called, the fluid variables $base$ and $expon$ should be set to Null and $exponFlag$ to False. *)
# (* If u is a function of F^v, $base$ and $expon$ are set to F and v, respectively. *)
# (* If an explicit exponential occurs in u, $exponFlag$ is set to True. *)
global SbaseS, SexponS, SexponFlagS
if FreeQ(u, x):
return True
elif u == x or CalculusQ(u):
return False
elif PowerQ(u):
if FreeQ(u.base, x) and LinearQ(u.exp, x):
SexponFlagS = True
return FunctionOfExponentialTestAux(u.base, u.exp, x)
elif HyperbolicQ(u) and LinearQ(u.args[0], x):
return FunctionOfExponentialTestAux(E, u.args[0], x)
if PowerQ(u):
if FreeQ(u.base, x) and SumQ(u.exp):
return FunctionOfExponentialTest(u.base**First(u.exp), x) and FunctionOfExponentialTest(u.base**Rest(u.exp), x)
return all(FunctionOfExponentialTest(i, x) for i in u.args)
def FunctionOfExponentialTestAux(base, expon, x):
global SbaseS, SexponS, SexponFlagS
if SbaseS is None:
SbaseS = base
SexponS = expon
return True
tmp = FullSimplify(Log(base)*Coefficient(expon, x, 1)/(Log(SbaseS)*Coefficient(SexponS, x, 1)))
if Not(RationalQ(tmp)):
return False
elif ZeroQ(Coefficient(SexponS, x, 0)) or NonzeroQ(tmp - FullSimplify(Log(base)*Coefficient(expon, x, 0)/(Log(SbaseS)*Coefficient(SexponS, x, 0)))):
if PositiveIntegerQ(base, SbaseS) and base < SbaseS:
SbaseS = base
SexponS = expon
tmp = 1/tmp
SexponS = Coefficient(SexponS, x, 1)*x/Denominator(tmp)
if tmp < 0 and NegQ(Coefficient(SexponS, x, 1)):
SexponS = -SexponS
return True
SexponS = SexponS/Denominator(tmp)
if tmp < 0 and NegQ(Coefficient(SexponS, x, 1)):
SexponS = -SexponS
return True
def stdev(lst):
"""Calculates the standard deviation for a list of numbers."""
num_items = len(lst)
mean = sum(lst) / num_items
differences = [x - mean for x in lst]
sq_differences = [d ** 2 for d in differences]
ssd = sum(sq_differences)
variance = ssd / num_items
sd = sqrt(variance)
return sd
def rubi_test(expr, x, optimal_output, expand=False, _hyper_check=False, _diff=False, _numerical=False):
#Returns True if (expr - optimal_output) is equal to 0 or a constant
#expr: integrated expression
#x: integration variable
#expand=True equates `expr` with `optimal_output` in expanded form
#_hyper_check=True evaluates numerically
#_diff=True differentiates the expressions before equating
#_numerical=True equates the expressions at random `x`. Normally used for large expressions.
from sympy.simplify.simplify import nsimplify
if not expr.has(csc, sec, cot, csch, sech, coth):
optimal_output = process_trig(optimal_output)
if expr == optimal_output:
return True
if simplify(expr) == simplify(optimal_output):
return True
if nsimplify(expr) == nsimplify(optimal_output):
return True
if expr.has(sym_exp):
expr = powsimp(powdenest(expr), force=True)
if simplify(expr) == simplify(powsimp(optimal_output, force=True)):
return True
res = expr - optimal_output
if _numerical:
args = res.free_symbols
rand_val = []
try:
for i in range(0, 5): # check at 5 random points
rand_x = randint(1, 40)
substitutions = {s: rand_x for s in args}
rand_val.append(float(abs(res.subs(substitutions).n())))
if stdev(rand_val) < Pow(10, -3):
return True
except:
pass
# return False
dres = res.diff(x)
if _numerical:
args = dres.free_symbols
rand_val = []
try:
for i in range(0, 5): # check at 5 random points
rand_x = randint(1, 40)
substitutions = {s: rand_x for s in args}
rand_val.append(float(abs(dres.subs(substitutions).n())))
if stdev(rand_val) < Pow(10, -3):
return True
# return False
except:
pass
# return False
r = Simplify(nsimplify(res))
if r == 0 or (not r.has(x)):
return True
if _diff:
if dres == 0:
return True
elif Simplify(dres) == 0:
return True
if expand: # expands the expression and equates
e = res.expand()
if Simplify(e) == 0 or (not e.has(x)):
return True
return False
def If(cond, t, f):
# returns t if condition is true else f
if cond:
return t
return f
def IntQuadraticQ(a, b, c, d, e, m, p, x):
# (* IntQuadraticQ[a,b,c,d,e,m,p,x] returns True iff (d+e*x)^m*(a+b*x+c*x^2)^p is integrable wrt x in terms of non-Appell functions. *)
return IntegerQ(p) or PositiveIntegerQ(m) or IntegersQ(2*m, 2*p) or IntegersQ(m, 4*p) or IntegersQ(m, p + S(1)/3) and (ZeroQ(c**2*d**2 - b*c*d*e + b**2*e**2 - 3*a*c*e**2) or ZeroQ(c**2*d**2 - b*c*d*e - 2*b**2*e**2 + 9*a*c*e**2))
def IntBinomialQ(*args):
#(* IntBinomialQ(a,b,c,n,m,p,x) returns True iff (c*x)^m*(a+b*x^n)^p is integrable wrt x in terms of non-hypergeometric functions. *)
if len(args) == 8:
a, b, c, d, n, p, q, x = args
return IntegersQ(p,q) or PositiveIntegerQ(p) or PositiveIntegerQ(q) or (ZeroQ(n-2) or ZeroQ(n-4)) and (IntegersQ(p,4*q) or IntegersQ(4*p,q)) or ZeroQ(n-2) and (IntegersQ(2*p,2*q) or IntegersQ(3*p,q) and ZeroQ(b*c+3*a*d) or IntegersQ(p,3*q) and ZeroQ(3*b*c+a*d))
elif len(args) == 7:
a, b, c, n, m, p, x = args
return IntegerQ(2*p) or IntegerQ((m+1)/n + p) or (ZeroQ(n - 2) or ZeroQ(n - 4)) and IntegersQ(2*m, 4*p) or ZeroQ(n - 2) and IntegerQ(6*p) and (IntegerQ(m) or IntegerQ(m - p))
elif len(args) == 10:
a, b, c, d, e, m, n, p, q, x = args
return IntegersQ(p,q) or PositiveIntegerQ(p) or PositiveIntegerQ(q) or ZeroQ(n-2) and IntegerQ(m) and IntegersQ(2*p,2*q) or ZeroQ(n-4) and (IntegersQ(m,p,2*q) or IntegersQ(m,2*p,q))
def RectifyTangent(*args):
# (* RectifyTangent(u,a,b,r,x) returns an expression whose derivative equals the derivative of r*ArcTan(a+b*Tan(u)) wrt x. *)
if len(args) == 5:
u, a, b, r, x = args
t1 = Together(a)
t2 = Together(b)
if (PureComplexNumberQ(t1) or (ProductQ(t1) and any(PureComplexNumberQ(i) for i in t1.args))) and (PureComplexNumberQ(t2) or ProductQ(t2) and any(PureComplexNumberQ(i) for i in t2.args)):
c = a/I
d = b/I
if NegativeQ(d):
return RectifyTangent(u, -a, -b, -r, x)
e = SmartDenominator(Together(c + d*x))
c = c*e
d = d*e
if EvenQ(Denominator(NumericFactor(Together(u)))):
return I*r*Log(RemoveContent(Simplify((c+e)**2+d**2)+Simplify((c+e)**2-d**2)*Cos(2*u)+Simplify(2*(c+e)*d)*Sin(2*u),x))/4 - I*r*Log(RemoveContent(Simplify((c-e)**2+d**2)+Simplify((c-e)**2-d**2)*Cos(2*u)+Simplify(2*(c-e)*d)*Sin(2*u),x))/4
return I*r*Log(RemoveContent(Simplify((c+e)**2)+Simplify(2*(c+e)*d)*Cos(u)*Sin(u)-Simplify((c+e)**2-d**2)*Sin(u)**2,x))/4 - I*r*Log(RemoveContent(Simplify((c-e)**2)+Simplify(2*(c-e)*d)*Cos(u)*Sin(u)-Simplify((c-e)**2-d**2)*Sin(u)**2,x))/4
elif NegativeQ(b):
return RectifyTangent(u, -a, -b, -r, x)
elif EvenQ(Denominator(NumericFactor(Together(u)))):
return r*SimplifyAntiderivative(u,x) + r*ArcTan(Simplify((2*a*b*Cos(2*u)-(1+a**2-b**2)*Sin(2*u))/(a**2+(1+b)**2+(1+a**2-b**2)*Cos(2*u)+2*a*b*Sin(2*u))))
return r*SimplifyAntiderivative(u,x) - r*ArcTan(ActivateTrig(Simplify((a*b-2*a*b*cos(u)**2+(1+a**2-b**2)*cos(u)*sin(u))/(b*(1+b)+(1+a**2-b**2)*cos(u)**2+2*a*b*cos(u)*sin(u)))))
u, a, b, x = args
t = Together(a)
if PureComplexNumberQ(t) or (ProductQ(t) and any(PureComplexNumberQ(i) for i in t.args)):
c = a/I
if NegativeQ(c):
return RectifyTangent(u, -a, -b, x)
if ZeroQ(c - 1):
if EvenQ(Denominator(NumericFactor(Together(u)))):
return I*b*ArcTanh(Sin(2*u))/2
return I*b*ArcTanh(2*cos(u)*sin(u))/2
e = SmartDenominator(c)
c = c*e
return I*b*Log(RemoveContent(e*Cos(u)+c*Sin(u),x))/2 - I*b*Log(RemoveContent(e*Cos(u)-c*Sin(u),x))/2
elif NegativeQ(a):
return RectifyTangent(u, -a, -b, x)
elif ZeroQ(a - 1):
return b*SimplifyAntiderivative(u, x)
elif EvenQ(Denominator(NumericFactor(Together(u)))):
c = Simplify((1 + a)/(1 - a))
numr = SmartNumerator(c)
denr = SmartDenominator(c)
return b*SimplifyAntiderivative(u,x) - b*ArcTan(NormalizeLeadTermSigns(denr*Sin(2*u)/(numr+denr*Cos(2*u)))),
elif PositiveQ(a - 1):
c = Simplify(1/(a - 1))
numr = SmartNumerator(c)
denr = SmartDenominator(c)
return b*SimplifyAntiderivative(u,x) + b*ArcTan(NormalizeLeadTermSigns(denr*Cos(u)*Sin(u)/(numr+denr*Sin(u)**2))),
c = Simplify(a/(1 - a))
numr = SmartNumerator(c)
denr = SmartDenominator(c)
return b*SimplifyAntiderivative(u,x) - b*ArcTan(NormalizeLeadTermSigns(denr*Cos(u)*Sin(u)/(numr+denr*Cos(u)**2)))
def RectifyCotangent(*args):
#(* RectifyCotangent[u,a,b,r,x] returns an expression whose derivative equals the derivative of r*ArcTan[a+b*Cot[u]] wrt x. *)
if len(args) == 5:
u, a, b, r, x = args
t1 = Together(a)
t2 = Together(b)
if (PureComplexNumberQ(t1) or (ProductQ(t1) and any(PureComplexNumberQ(i) for i in t1.args))) and (PureComplexNumberQ(t2) or ProductQ(t2) and any(PureComplexNumberQ(i) for i in t2.args)):
c = a/I
d = b/I
if NegativeQ(d):
return RectifyTangent(u,-a,-b,-r,x)
e = SmartDenominator(Together(c + d*x))
c = c*e
d = d*e
if EvenQ(Denominator(NumericFactor(Together(u)))):
return I*r*Log(RemoveContent(Simplify((c+e)**2+d**2)-Simplify((c+e)**2-d**2)*Cos(2*u)+Simplify(2*(c+e)*d)*Sin(2*u),x))/4 - I*r*Log(RemoveContent(Simplify((c-e)**2+d**2)-Simplify((c-e)**2-d**2)*Cos(2*u)+Simplify(2*(c-e)*d)*Sin(2*u),x))/4
return I*r*Log(RemoveContent(Simplify((c+e)**2)-Simplify((c+e)**2-d**2)*Cos(u)**2+Simplify(2*(c+e)*d)*Cos(u)*Sin(u),x))/4 - I*r*Log(RemoveContent(Simplify((c-e)**2)-Simplify((c-e)**2-d**2)*Cos(u)**2+Simplify(2*(c-e)*d)*Cos(u)*Sin(u),x))/4
elif NegativeQ(b):
return RectifyCotangent(u,-a,-b,-r,x)
elif EvenQ(Denominator(NumericFactor(Together(u)))):
return -r*SimplifyAntiderivative(u,x) - r*ArcTan(Simplify((2*a*b*Cos(2*u)+(1+a**2-b**2)*Sin(2*u))/(a**2+(1+b)**2-(1+a**2-b**2)*Cos(2*u)+2*a*b*Sin(2*u))))
return -r*SimplifyAntiderivative(u,x) - r*ArcTan(ActivateTrig(Simplify((a*b-2*a*b*sin(u)**2+(1+a**2-b**2)*cos(u)*sin(u))/(b*(1+b)+(1+a**2-b**2)*sin(u)**2+2*a*b*cos(u)*sin(u)))))
u, a, b, x = args
t = Together(a)
if PureComplexNumberQ(t) or (ProductQ(t) and any(PureComplexNumberQ(i) for i in t.args)):
c = a/I
if NegativeQ(c):
return RectifyCotangent(u,-a,-b,x)
elif ZeroQ(c - 1):
if EvenQ(Denominator(NumericFactor(Together(u)))):
return -I*b*ArcTanh(Sin(2*u))/2
return -I*b*ArcTanh(2*Cos(u)*Sin(u))/2
e = SmartDenominator(c)
c = c*e
return -I*b*Log(RemoveContent(c*Cos(u)+e*Sin(u),x))/2 + I*b*Log(RemoveContent(c*Cos(u)-e*Sin(u),x))/2
elif NegativeQ(a):
return RectifyCotangent(u,-a,-b,x)
elif ZeroQ(a-1):
return b*SimplifyAntiderivative(u,x)
elif EvenQ(Denominator(NumericFactor(Together(u)))):
c = Simplify(a - 1)
numr = SmartNumerator(c)
denr = SmartDenominator(c)
return b*SimplifyAntiderivative(u,x) - b*ArcTan(NormalizeLeadTermSigns(denr*Cos(u)*Sin(u)/(numr+denr*Cos(u)**2)))
c = Simplify(a/(1-a))
numr = SmartNumerator(c)
denr = SmartDenominator(c)
return b*SimplifyAntiderivative(u,x) + b*ArcTan(NormalizeLeadTermSigns(denr*Cos(u)*Sin(u)/(numr+denr*Sin(u)**2)))
def Inequality(*args):
f = args[1::2]
e = args[0::2]
r = []
for i in range(0, len(f)):
r.append(f[i](e[i], e[i + 1]))
return all(r)
def Condition(r, c):
# returns r if c is True
if c:
return r
else:
raise NotImplementedError('In Condition()')
def Simp(u, x):
u = replace_pow_exp(u)
return NormalizeSumFactors(SimpHelp(u, x))
def SimpHelp(u, x):
if AtomQ(u):
return u
elif FreeQ(u, x):
v = SmartSimplify(u)
if LeafCount(v) <= LeafCount(u):
return v
return u
elif ProductQ(u):
#m = MatchQ[Rest[u],a_.+n_*Pi+b_.*v_ /; FreeQ[{a,b},x] && Not[FreeQ[v,x]] && EqQ[n^2,1/4]]
#if EqQ(First(u), S(1)/2) and m:
# if
#If[EqQ[First[u],1/2] && MatchQ[Rest[u],a_.+n_*Pi+b_.*v_ /; FreeQ[{a,b},x] && Not[FreeQ[v,x]] && EqQ[n^2,1/4]],
# If[MatchQ[Rest[u],n_*Pi+b_.*v_ /; FreeQ[b,x] && Not[FreeQ[v,x]] && EqQ[n^2,1/4]],
# Map[Function[1/2*#],Rest[u]],
# If[MatchQ[Rest[u],m_*a_.+n_*Pi+p_*b_.*v_ /; FreeQ[{a,b},x] && Not[FreeQ[v,x]] && IntegersQ[m/2,p/2]],
# Map[Function[1/2*#],Rest[u]],
# u]],
v = FreeFactors(u, x)
w = NonfreeFactors(u, x)
v = NumericFactor(v)*SmartSimplify(NonnumericFactors(v)*x**2)/x**2
if ProductQ(w):
w = Mul(*[SimpHelp(i,x) for i in w.args])
else:
w = SimpHelp(w, x)
w = FactorNumericGcd(w)
v = MergeFactors(v, w)
if ProductQ(v):
return Mul(*[SimpFixFactor(i, x) for i in v.args])
return v
elif SumQ(u):
Pi = pi
a_ = Wild('a', exclude=[x])
b_ = Wild('b', exclude=[x, 0])
n_ = Wild('n', exclude=[x, 0, 0])
pattern = a_ + n_*Pi + b_*x
match = u.match(pattern)
m = False
if match:
if EqQ(match[n_]**3, S(1)/16):
m = True
if m:
return u
elif PolynomialQ(u, x) and Exponent(u, x) <= 0:
return SimpHelp(Coefficient(u, x, 0), x)
elif PolynomialQ(u, x) and Exponent(u, x) == 1 and Coefficient(u, x, 0) == 0:
return SimpHelp(Coefficient(u, x, 1), x)*x
v = 0
w = 0
for i in u.args:
if FreeQ(i, x):
v = i + v
else:
w = i + w
v = SmartSimplify(v)
if SumQ(w):
w = Add(*[SimpHelp(i, x) for i in w.args])
else:
w = SimpHelp(w, x)
return v + w
return u.func(*[SimpHelp(i, x) for i in u.args])
def SplitProduct(func, u):
#(* If func[v] is True for a factor v of u, SplitProduct[func,u] returns {v, u/v} where v is the first such factor; else it returns False. *)
if ProductQ(u):
if func(First(u)):
return [First(u), Rest(u)]
lst = SplitProduct(func, Rest(u))
if AtomQ(lst):
return False
return [lst[0], First(u)*lst[1]]
if func(u):
return [u, 1]
return False
def SplitSum(func, u):
# (* If func[v] is nonatomic for a term v of u, SplitSum[func,u] returns {func[v], u-v} where v is the first such term; else it returns False. *)
if SumQ(u):
if Not(AtomQ(func(First(u)))):
return [func(First(u)), Rest(u)]
lst = SplitSum(func, Rest(u))
if AtomQ(lst):
return False
return [lst[0], First(u) + lst[1]]
elif Not(AtomQ(func(u))):
return [func(u), 0]
return False
def SubstFor(*args):
if len(args) == 4:
w, v, u, x = args
# u is a function of v. SubstFor(w,v,u,x) returns w times u with v replaced by x.
return SimplifyIntegrand(w*SubstFor(v, u, x), x)
v, u, x = args
# u is a function of v. SubstFor(v, u, x) returns u with v replaced by x.
if AtomQ(v):
return Subst(u, v, x)
elif Not(EqQ(FreeFactors(v, x), 1)):
return SubstFor(NonfreeFactors(v, x), u, x/FreeFactors(v, x))
elif SinQ(v):
return SubstForTrig(u, x, Sqrt(1 - x**2), v.args[0], x)
elif CosQ(v):
return SubstForTrig(u, Sqrt(1 - x**2), x, v.args[0], x)
elif TanQ(v):
return SubstForTrig(u, x/Sqrt(1 + x**2), 1/Sqrt(1 + x**2), v.args[0], x)
elif CotQ(v):
return SubstForTrig(u, 1/Sqrt(1 + x**2), x/Sqrt(1 + x**2), v.args[0], x)
elif SecQ(v):
return SubstForTrig(u, 1/Sqrt(1 - x**2), 1/x, v.args[0], x)
elif CscQ(v):
return SubstForTrig(u, 1/x, 1/Sqrt(1 - x**2), v.args[0], x)
elif SinhQ(v):
return SubstForHyperbolic(u, x, Sqrt(1 + x**2), v.args[0], x)
elif CoshQ(v):
return SubstForHyperbolic(u, Sqrt( - 1 + x**2), x, v.args[0], x)
elif TanhQ(v):
return SubstForHyperbolic(u, x/Sqrt(1 - x**2), 1/Sqrt(1 - x**2), v.args[0], x)
elif CothQ(v):
return SubstForHyperbolic(u, 1/Sqrt( - 1 + x**2), x/Sqrt( - 1 + x**2), v.args[0], x)
elif SechQ(v):
return SubstForHyperbolic(u, 1/Sqrt( - 1 + x**2), 1/x, v.args[0], x)
elif CschQ(v):
return SubstForHyperbolic(u, 1/x, 1/Sqrt(1 + x**2), v.args[0], x)
else:
return SubstForAux(u, v, x)
def SubstForAux(u, v, x):
# u is a function of v. SubstForAux(u, v, x) returns u with v replaced by x.
if u==v:
return x
elif AtomQ(u):
if PowerQ(v):
if FreeQ(v.exp, x) and ZeroQ(u - v.base):
return x**Simplify(1/v.exp)
return u
elif PowerQ(u):
if FreeQ(u.exp, x):
if ZeroQ(u.base - v):
return x**u.exp
if PowerQ(v):
if FreeQ(v.exp, x) and ZeroQ(u.base - v.base):
return x**Simplify(u.exp/v.exp)
return SubstForAux(u.base, v, x)**u.exp
elif ProductQ(u) and Not(EqQ(FreeFactors(u, x), 1)):
return FreeFactors(u, x)*SubstForAux(NonfreeFactors(u, x), v, x)
elif ProductQ(u) and ProductQ(v):
return SubstForAux(First(u), First(v), x)
return u.func(*[SubstForAux(i, v, x) for i in u.args])
def FresnelS(x):
return fresnels(x)
def FresnelC(x):
return fresnelc(x)
def Erf(x):
return erf(x)
def Erfc(x):
return erfc(x)
def Erfi(x):
return erfi(x)
class Gamma(Function):
@classmethod
def eval(cls,*args):
a = args[0]
if len(args) == 1:
return gamma(a)
else:
b = args[1]
if (NumericQ(a) and NumericQ(b)) or a == 1:
return uppergamma(a, b)
def FunctionOfTrigOfLinearQ(u, x):
# If u is an algebraic function of trig functions of a linear function of x,
# FunctionOfTrigOfLinearQ[u,x] returns True; else it returns False.
if FunctionOfTrig(u, None, x) and AlgebraicTrigFunctionQ(u, x) and FunctionOfLinear(FunctionOfTrig(u, None, x), x):
return True
else:
return False
def ElementaryFunctionQ(u):
# ElementaryExpressionQ[u] returns True if u is a sum, product, or power and all the operands
# are elementary expressions; or if u is a call on a trig, hyperbolic, or inverse function
# and all the arguments are elementary expressions; else it returns False.
if AtomQ(u):
return True
elif SumQ(u) or ProductQ(u) or PowerQ(u) or TrigQ(u) or HyperbolicQ(u) or InverseFunctionQ(u):
for i in u.args:
if not ElementaryFunctionQ(i):
return False
return True
return False
def Complex(a, b):
return a + I*b
def UnsameQ(a, b):
return a != b
@doctest_depends_on(modules=('matchpy',))
def _SimpFixFactor():
replacer = ManyToOneReplacer()
pattern1 = Pattern(UtilityOperator(Pow(Add(Mul(Complex(S(0), c_), WC('a', S(1))), Mul(Complex(S(0), d_), WC('b', S(1)))), WC('p', S(1))), x_), CustomConstraint(lambda p: IntegerQ(p)))
rule1 = ReplacementRule(pattern1, lambda b, c, x, a, p, d : Mul(Pow(I, p), SimpFixFactor(Pow(Add(Mul(a, c), Mul(b, d)), p), x)))
replacer.add(rule1)
pattern2 = Pattern(UtilityOperator(Pow(Add(Mul(Complex(S(0), d_), WC('a', S(1))), Mul(Complex(S(0), e_), WC('b', S(1))), Mul(Complex(S(0), f_), WC('c', S(1)))), WC('p', S(1))), x_), CustomConstraint(lambda p: IntegerQ(p)))
rule2 = ReplacementRule(pattern2, lambda b, c, x, f, a, p, e, d : Mul(Pow(I, p), SimpFixFactor(Pow(Add(Mul(a, d), Mul(b, e), Mul(c, f)), p), x)))
replacer.add(rule2)
pattern3 = Pattern(UtilityOperator(Pow(Add(Mul(WC('a', S(1)), Pow(c_, r_)), Mul(WC('b', S(1)), Pow(x_, WC('n', S(1))))), WC('p', S(1))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda b, x: FreeQ(b, x)), CustomConstraint(lambda c, x: FreeQ(c, x)), CustomConstraint(lambda n, p: IntegersQ(n, p)), CustomConstraint(lambda c: AtomQ(c)), CustomConstraint(lambda r: RationalQ(r)), CustomConstraint(lambda r: Less(r, S(0))))
rule3 = ReplacementRule(pattern3, lambda b, c, r, n, x, a, p : Mul(Pow(c, Mul(r, p)), SimpFixFactor(Pow(Add(a, Mul(Mul(b, Pow(Pow(c, r), S(-1))), Pow(x, n))), p), x)))
replacer.add(rule3)
pattern4 = Pattern(UtilityOperator(Pow(Add(WC('a', S(0)), Mul(WC('b', S(1)), Pow(c_, r_), Pow(x_, WC('n', S(1))))), WC('p', S(1))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda b, x: FreeQ(b, x)), CustomConstraint(lambda c, x: FreeQ(c, x)), CustomConstraint(lambda n, p: IntegersQ(n, p)), CustomConstraint(lambda c: AtomQ(c)), CustomConstraint(lambda r: RationalQ(r)), CustomConstraint(lambda r: Less(r, S(0))))
rule4 = ReplacementRule(pattern4, lambda b, c, r, n, x, a, p : Mul(Pow(c, Mul(r, p)), SimpFixFactor(Pow(Add(Mul(a, Pow(Pow(c, r), S(-1))), Mul(b, Pow(x, n))), p), x)))
replacer.add(rule4)
pattern5 = Pattern(UtilityOperator(Pow(Add(Mul(WC('a', S(1)), Pow(c_, WC('s', S(1)))), Mul(WC('b', S(1)), Pow(c_, WC('r', S(1))), Pow(x_, WC('n', S(1))))), WC('p', S(1))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda b, x: FreeQ(b, x)), CustomConstraint(lambda c, x: FreeQ(c, x)), CustomConstraint(lambda n, p: IntegersQ(n, p)), CustomConstraint(lambda r, s: RationalQ(s, r)), CustomConstraint(lambda r, s: Inequality(S(0), Less, s, LessEqual, r)), CustomConstraint(lambda p, c, s: UnsameQ(Pow(c, Mul(s, p)), S(-1))))
rule5 = ReplacementRule(pattern5, lambda b, c, r, n, x, a, p, s : Mul(Pow(c, Mul(s, p)), SimpFixFactor(Pow(Add(a, Mul(b, Pow(c, Add(r, Mul(S(-1), s))), Pow(x, n))), p), x)))
replacer.add(rule5)
pattern6 = Pattern(UtilityOperator(Pow(Add(Mul(WC('a', S(1)), Pow(c_, WC('s', S(1)))), Mul(WC('b', S(1)), Pow(c_, WC('r', S(1))), Pow(x_, WC('n', S(1))))), WC('p', S(1))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda b, x: FreeQ(b, x)), CustomConstraint(lambda c, x: FreeQ(c, x)), CustomConstraint(lambda n, p: IntegersQ(n, p)), CustomConstraint(lambda r, s: RationalQ(s, r)), CustomConstraint(lambda s, r: Less(S(0), r, s)), CustomConstraint(lambda p, c, r: UnsameQ(Pow(c, Mul(r, p)), S(-1))))
rule6 = ReplacementRule(pattern6, lambda b, c, r, n, x, a, p, s : Mul(Pow(c, Mul(r, p)), SimpFixFactor(Pow(Add(Mul(a, Pow(c, Add(s, Mul(S(-1), r)))), Mul(b, Pow(x, n))), p), x)))
replacer.add(rule6)
return replacer
@doctest_depends_on(modules=('matchpy',))
def SimpFixFactor(expr, x):
r = SimpFixFactor_replacer.replace(UtilityOperator(expr, x))
if isinstance(r, UtilityOperator):
return expr
return r
@doctest_depends_on(modules=('matchpy',))
def _FixSimplify():
Plus = Add
def cons_f1(n):
return OddQ(n)
cons1 = CustomConstraint(cons_f1)
def cons_f2(m):
return RationalQ(m)
cons2 = CustomConstraint(cons_f2)
def cons_f3(n):
return FractionQ(n)
cons3 = CustomConstraint(cons_f3)
def cons_f4(u):
return SqrtNumberSumQ(u)
cons4 = CustomConstraint(cons_f4)
def cons_f5(v):
return SqrtNumberSumQ(v)
cons5 = CustomConstraint(cons_f5)
def cons_f6(u):
return PositiveQ(u)
cons6 = CustomConstraint(cons_f6)
def cons_f7(v):
return PositiveQ(v)
cons7 = CustomConstraint(cons_f7)
def cons_f8(v):
return SqrtNumberSumQ(S(1)/v)
cons8 = CustomConstraint(cons_f8)
def cons_f9(m):
return IntegerQ(m)
cons9 = CustomConstraint(cons_f9)
def cons_f10(u):
return NegativeQ(u)
cons10 = CustomConstraint(cons_f10)
def cons_f11(n, m, a, b):
return RationalQ(a, b, m, n)
cons11 = CustomConstraint(cons_f11)
def cons_f12(a):
return Greater(a, S(0))
cons12 = CustomConstraint(cons_f12)
def cons_f13(b):
return Greater(b, S(0))
cons13 = CustomConstraint(cons_f13)
def cons_f14(p):
return PositiveIntegerQ(p)
cons14 = CustomConstraint(cons_f14)
def cons_f15(p):
return IntegerQ(p)
cons15 = CustomConstraint(cons_f15)
def cons_f16(p, n):
return Greater(-n + p, S(0))
cons16 = CustomConstraint(cons_f16)
def cons_f17(a, b):
return SameQ(a + b, S(0))
cons17 = CustomConstraint(cons_f17)
def cons_f18(n):
return Not(IntegerQ(n))
cons18 = CustomConstraint(cons_f18)
def cons_f19(c, a, b, d):
return ZeroQ(-a*d + b*c)
cons19 = CustomConstraint(cons_f19)
def cons_f20(a):
return Not(RationalQ(a))
cons20 = CustomConstraint(cons_f20)
def cons_f21(t):
return IntegerQ(t)
cons21 = CustomConstraint(cons_f21)
def cons_f22(n, m):
return RationalQ(m, n)
cons22 = CustomConstraint(cons_f22)
def cons_f23(n, m):
return Inequality(S(0), Less, m, LessEqual, n)
cons23 = CustomConstraint(cons_f23)
def cons_f24(p, n, m):
return RationalQ(m, n, p)
cons24 = CustomConstraint(cons_f24)
def cons_f25(p, n, m):
return Inequality(S(0), Less, m, LessEqual, n, LessEqual, p)
cons25 = CustomConstraint(cons_f25)
def cons_f26(p, n, m, q):
return Inequality(S(0), Less, m, LessEqual, n, LessEqual, p, LessEqual, q)
cons26 = CustomConstraint(cons_f26)
def cons_f27(w):
return Not(RationalQ(w))
cons27 = CustomConstraint(cons_f27)
def cons_f28(n):
return Less(n, S(0))
cons28 = CustomConstraint(cons_f28)
def cons_f29(n, w, v):
return ZeroQ(v + w**(-n))
cons29 = CustomConstraint(cons_f29)
def cons_f30(n):
return IntegerQ(n)
cons30 = CustomConstraint(cons_f30)
def cons_f31(w, v):
return ZeroQ(v + w)
cons31 = CustomConstraint(cons_f31)
def cons_f32(p, n):
return IntegerQ(n/p)
cons32 = CustomConstraint(cons_f32)
def cons_f33(w, v):
return ZeroQ(v - w)
cons33 = CustomConstraint(cons_f33)
def cons_f34(p, n):
return IntegersQ(n, n/p)
cons34 = CustomConstraint(cons_f34)
def cons_f35(a):
return AtomQ(a)
cons35 = CustomConstraint(cons_f35)
def cons_f36(b):
return AtomQ(b)
cons36 = CustomConstraint(cons_f36)
pattern1 = Pattern(UtilityOperator((w_ + Complex(S(0), b_)*WC('v', S(1)))**WC('n', S(1))*Complex(S(0), a_)*WC('u', S(1))), cons1)
def replacement1(n, u, w, v, a, b):
return (S(-1))**(n/S(2) + S(1)/2)*a*u*FixSimplify((b*v - w*Complex(S(0), S(1)))**n)
rule1 = ReplacementRule(pattern1, replacement1)
def With2(m, n, u, w, v):
z = u**(m/GCD(m, n))*v**(n/GCD(m, n))
if Or(AbsurdNumberQ(z), SqrtNumberSumQ(z)):
return True
return False
pattern2 = Pattern(UtilityOperator(u_**WC('m', S(1))*v_**n_*WC('w', S(1))), cons2, cons3, cons4, cons5, cons6, cons7, CustomConstraint(With2))
def replacement2(m, n, u, w, v):
z = u**(m/GCD(m, n))*v**(n/GCD(m, n))
return FixSimplify(w*z**GCD(m, n))
rule2 = ReplacementRule(pattern2, replacement2)
def With3(m, n, u, w, v):
z = u**(m/GCD(m, -n))*v**(n/GCD(m, -n))
if Or(AbsurdNumberQ(z), SqrtNumberSumQ(z)):
return True
return False
pattern3 = Pattern(UtilityOperator(u_**WC('m', S(1))*v_**n_*WC('w', S(1))), cons2, cons3, cons4, cons8, cons6, cons7, CustomConstraint(With3))
def replacement3(m, n, u, w, v):
z = u**(m/GCD(m, -n))*v**(n/GCD(m, -n))
return FixSimplify(w*z**GCD(m, -n))
rule3 = ReplacementRule(pattern3, replacement3)
def With4(m, n, u, w, v):
z = v**(n/GCD(m, n))*(-u)**(m/GCD(m, n))
if Or(AbsurdNumberQ(z), SqrtNumberSumQ(z)):
return True
return False
pattern4 = Pattern(UtilityOperator(u_**WC('m', S(1))*v_**n_*WC('w', S(1))), cons9, cons3, cons4, cons5, cons10, cons7, CustomConstraint(With4))
def replacement4(m, n, u, w, v):
z = v**(n/GCD(m, n))*(-u)**(m/GCD(m, n))
return FixSimplify(-w*z**GCD(m, n))
rule4 = ReplacementRule(pattern4, replacement4)
def With5(m, n, u, w, v):
z = v**(n/GCD(m, -n))*(-u)**(m/GCD(m, -n))
if Or(AbsurdNumberQ(z), SqrtNumberSumQ(z)):
return True
return False
pattern5 = Pattern(UtilityOperator(u_**WC('m', S(1))*v_**n_*WC('w', S(1))), cons9, cons3, cons4, cons8, cons10, cons7, CustomConstraint(With5))
def replacement5(m, n, u, w, v):
z = v**(n/GCD(m, -n))*(-u)**(m/GCD(m, -n))
return FixSimplify(-w*z**GCD(m, -n))
rule5 = ReplacementRule(pattern5, replacement5)
def With6(p, m, n, u, w, v, a, b):
c = a**(m/p)*b**n
if RationalQ(c):
return True
return False
pattern6 = Pattern(UtilityOperator(a_**m_*(b_**n_*WC('v', S(1)) + u_)**WC('p', S(1))*WC('w', S(1))), cons11, cons12, cons13, cons14, CustomConstraint(With6))
def replacement6(p, m, n, u, w, v, a, b):
c = a**(m/p)*b**n
return FixSimplify(w*(a**(m/p)*u + c*v)**p)
rule6 = ReplacementRule(pattern6, replacement6)
pattern7 = Pattern(UtilityOperator(a_**WC('m', S(1))*(a_**n_*WC('u', S(1)) + b_**WC('p', S(1))*WC('v', S(1)))*WC('w', S(1))), cons2, cons3, cons15, cons16, cons17)
def replacement7(p, m, n, u, w, v, a, b):
return FixSimplify(a**(m + n)*w*((S(-1))**p*a**(-n + p)*v + u))
rule7 = ReplacementRule(pattern7, replacement7)
def With8(m, d, n, w, c, a, b):
q = b/d
if FreeQ(q, Plus):
return True
return False
pattern8 = Pattern(UtilityOperator((a_ + b_)**WC('m', S(1))*(c_ + d_)**n_*WC('w', S(1))), cons9, cons18, cons19, CustomConstraint(With8))
def replacement8(m, d, n, w, c, a, b):
q = b/d
return FixSimplify(q**m*w*(c + d)**(m + n))
rule8 = ReplacementRule(pattern8, replacement8)
pattern9 = Pattern(UtilityOperator((a_**WC('m', S(1))*WC('u', S(1)) + a_**WC('n', S(1))*WC('v', S(1)))**WC('t', S(1))*WC('w', S(1))), cons20, cons21, cons22, cons23)
def replacement9(m, n, u, w, v, a, t):
return FixSimplify(a**(m*t)*w*(a**(-m + n)*v + u)**t)
rule9 = ReplacementRule(pattern9, replacement9)
pattern10 = Pattern(UtilityOperator((a_**WC('m', S(1))*WC('u', S(1)) + a_**WC('n', S(1))*WC('v', S(1)) + a_**WC('p', S(1))*WC('z', S(1)))**WC('t', S(1))*WC('w', S(1))), cons20, cons21, cons24, cons25)
def replacement10(p, m, n, u, w, v, a, z, t):
return FixSimplify(a**(m*t)*w*(a**(-m + n)*v + a**(-m + p)*z + u)**t)
rule10 = ReplacementRule(pattern10, replacement10)
pattern11 = Pattern(UtilityOperator((a_**WC('m', S(1))*WC('u', S(1)) + a_**WC('n', S(1))*WC('v', S(1)) + a_**WC('p', S(1))*WC('z', S(1)) + a_**WC('q', S(1))*WC('y', S(1)))**WC('t', S(1))*WC('w', S(1))), cons20, cons21, cons24, cons26)
def replacement11(p, m, n, u, q, w, v, a, z, y, t):
return FixSimplify(a**(m*t)*w*(a**(-m + n)*v + a**(-m + p)*z + a**(-m + q)*y + u)**t)
rule11 = ReplacementRule(pattern11, replacement11)
pattern12 = Pattern(UtilityOperator((sqrt(v_)*WC('b', S(1)) + sqrt(v_)*WC('c', S(1)) + sqrt(v_)*WC('d', S(1)) + sqrt(v_)*WC('a', S(1)) + WC('u', S(0)))*WC('w', S(1))))
def replacement12(d, u, w, v, c, a, b):
return FixSimplify(w*(u + sqrt(v)*FixSimplify(a + b + c + d)))
rule12 = ReplacementRule(pattern12, replacement12)
pattern13 = Pattern(UtilityOperator((sqrt(v_)*WC('b', S(1)) + sqrt(v_)*WC('c', S(1)) + sqrt(v_)*WC('a', S(1)) + WC('u', S(0)))*WC('w', S(1))))
def replacement13(u, w, v, c, a, b):
return FixSimplify(w*(u + sqrt(v)*FixSimplify(a + b + c)))
rule13 = ReplacementRule(pattern13, replacement13)
pattern14 = Pattern(UtilityOperator((sqrt(v_)*WC('b', S(1)) + sqrt(v_)*WC('a', S(1)) + WC('u', S(0)))*WC('w', S(1))))
def replacement14(u, w, v, a, b):
return FixSimplify(w*(u + sqrt(v)*FixSimplify(a + b)))
rule14 = ReplacementRule(pattern14, replacement14)
pattern15 = Pattern(UtilityOperator(v_**m_*w_**n_*WC('u', S(1))), cons2, cons27, cons3, cons28, cons29)
def replacement15(m, n, u, w, v):
return -FixSimplify(u*v**(m + S(-1)))
rule15 = ReplacementRule(pattern15, replacement15)
pattern16 = Pattern(UtilityOperator(v_**m_*w_**WC('n', S(1))*WC('u', S(1))), cons2, cons27, cons30, cons31)
def replacement16(m, n, u, w, v):
return (S(-1))**n*FixSimplify(u*v**(m + n))
rule16 = ReplacementRule(pattern16, replacement16)
pattern17 = Pattern(UtilityOperator(w_**WC('n', S(1))*(-v_**WC('p', S(1)))**m_*WC('u', S(1))), cons2, cons27, cons32, cons33)
def replacement17(p, m, n, u, w, v):
return (S(-1))**(n/p)*FixSimplify(u*(-v**p)**(m + n/p))
rule17 = ReplacementRule(pattern17, replacement17)
pattern18 = Pattern(UtilityOperator(w_**WC('n', S(1))*(-v_**WC('p', S(1)))**m_*WC('u', S(1))), cons2, cons27, cons34, cons31)
def replacement18(p, m, n, u, w, v):
return (S(-1))**(n + n/p)*FixSimplify(u*(-v**p)**(m + n/p))
rule18 = ReplacementRule(pattern18, replacement18)
pattern19 = Pattern(UtilityOperator((a_ - b_)**WC('m', S(1))*(a_ + b_)**WC('m', S(1))*WC('u', S(1))), cons9, cons35, cons36)
def replacement19(m, u, a, b):
return u*(a**S(2) - b**S(2))**m
rule19 = ReplacementRule(pattern19, replacement19)
pattern20 = Pattern(UtilityOperator((S(729)*c - e*(-S(20)*e + S(540)))**WC('m', S(1))*WC('u', S(1))), cons2)
def replacement20(m, u):
return u*(a*e**S(2) - b*d*e + c*d**S(2))**m
rule20 = ReplacementRule(pattern20, replacement20)
pattern21 = Pattern(UtilityOperator((S(729)*c + e*(S(20)*e + S(-540)))**WC('m', S(1))*WC('u', S(1))), cons2)
def replacement21(m, u):
return u*(a*e**S(2) - b*d*e + c*d**S(2))**m
rule21 = ReplacementRule(pattern21, replacement21)
pattern22 = Pattern(UtilityOperator(u_))
def replacement22(u):
return u
rule22 = ReplacementRule(pattern22, replacement22)
return [rule1, rule2, rule3, rule4, rule5, rule6, rule7, rule8, rule9, rule10, rule11, rule12, rule13, rule14, rule15, rule16, rule17, rule18, rule19, rule20, rule21, rule22, ]
@doctest_depends_on(modules=('matchpy',))
def FixSimplify(expr):
if isinstance(expr, (list, tuple, TupleArg)):
return [replace_all(UtilityOperator(i), FixSimplify_rules) for i in expr]
return replace_all(UtilityOperator(expr), FixSimplify_rules)
@doctest_depends_on(modules=('matchpy',))
def _SimplifyAntiderivativeSum():
replacer = ManyToOneReplacer()
pattern1 = Pattern(UtilityOperator(Add(Mul(Log(Add(a_, Mul(WC('b', S(1)), Pow(Tan(u_), WC('n', S(1)))))), WC('A', S(1))), Mul(Log(Cos(u_)), WC('B', S(1))), WC('v', S(0))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda b, x: FreeQ(b, x)), CustomConstraint(lambda A, x: FreeQ(A, x)), CustomConstraint(lambda B, x: FreeQ(B, x)), CustomConstraint(lambda n: IntegerQ(n)), CustomConstraint(lambda B, A, n: ZeroQ(Add(Mul(n, A), Mul(S(1), B)))))
rule1 = ReplacementRule(pattern1, lambda n, x, v, b, B, A, u, a : Add(SimplifyAntiderivativeSum(v, x), Mul(A, Log(RemoveContent(Add(Mul(a, Pow(Cos(u), n)), Mul(b, Pow(Sin(u), n))), x)))))
replacer.add(rule1)
pattern2 = Pattern(UtilityOperator(Add(Mul(Log(Add(Mul(Pow(Cot(u_), WC('n', S(1))), WC('b', S(1))), a_)), WC('A', S(1))), Mul(Log(Sin(u_)), WC('B', S(1))), WC('v', S(0))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda b, x: FreeQ(b, x)), CustomConstraint(lambda A, x: FreeQ(A, x)), CustomConstraint(lambda B, x: FreeQ(B, x)), CustomConstraint(lambda n: IntegerQ(n)), CustomConstraint(lambda B, A, n: ZeroQ(Add(Mul(n, A), Mul(S(1), B)))))
rule2 = ReplacementRule(pattern2, lambda n, x, v, b, B, A, a, u : Add(SimplifyAntiderivativeSum(v, x), Mul(A, Log(RemoveContent(Add(Mul(a, Pow(Sin(u), n)), Mul(b, Pow(Cos(u), n))), x)))))
replacer.add(rule2)
pattern3 = Pattern(UtilityOperator(Add(Mul(Log(Add(a_, Mul(WC('b', S(1)), Pow(Tan(u_), WC('n', S(1)))))), WC('A', S(1))), Mul(Log(Add(c_, Mul(WC('d', S(1)), Pow(Tan(u_), WC('n', S(1)))))), WC('B', S(1))), WC('v', S(0))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda b, x: FreeQ(b, x)), CustomConstraint(lambda c, x: FreeQ(c, x)), CustomConstraint(lambda d, x: FreeQ(d, x)), CustomConstraint(lambda A, x: FreeQ(A, x)), CustomConstraint(lambda B, x: FreeQ(B, x)), CustomConstraint(lambda n: IntegerQ(n)), CustomConstraint(lambda B, A: ZeroQ(Add(A, B))))
rule3 = ReplacementRule(pattern3, lambda n, x, v, b, A, B, u, c, d, a : Add(SimplifyAntiderivativeSum(v, x), Mul(A, Log(RemoveContent(Add(Mul(a, Pow(Cos(u), n)), Mul(b, Pow(Sin(u), n))), x))), Mul(B, Log(RemoveContent(Add(Mul(c, Pow(Cos(u), n)), Mul(d, Pow(Sin(u), n))), x)))))
replacer.add(rule3)
pattern4 = Pattern(UtilityOperator(Add(Mul(Log(Add(Mul(Pow(Cot(u_), WC('n', S(1))), WC('b', S(1))), a_)), WC('A', S(1))), Mul(Log(Add(Mul(Pow(Cot(u_), WC('n', S(1))), WC('d', S(1))), c_)), WC('B', S(1))), WC('v', S(0))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda b, x: FreeQ(b, x)), CustomConstraint(lambda c, x: FreeQ(c, x)), CustomConstraint(lambda d, x: FreeQ(d, x)), CustomConstraint(lambda A, x: FreeQ(A, x)), CustomConstraint(lambda B, x: FreeQ(B, x)), CustomConstraint(lambda n: IntegerQ(n)), CustomConstraint(lambda B, A: ZeroQ(Add(A, B))))
rule4 = ReplacementRule(pattern4, lambda n, x, v, b, A, B, c, a, d, u : Add(SimplifyAntiderivativeSum(v, x), Mul(A, Log(RemoveContent(Add(Mul(b, Pow(Cos(u), n)), Mul(a, Pow(Sin(u), n))), x))), Mul(B, Log(RemoveContent(Add(Mul(d, Pow(Cos(u), n)), Mul(c, Pow(Sin(u), n))), x)))))
replacer.add(rule4)
pattern5 = Pattern(UtilityOperator(Add(Mul(Log(Add(a_, Mul(WC('b', S(1)), Pow(Tan(u_), WC('n', S(1)))))), WC('A', S(1))), Mul(Log(Add(c_, Mul(WC('d', S(1)), Pow(Tan(u_), WC('n', S(1)))))), WC('B', S(1))), Mul(Log(Add(e_, Mul(WC('f', S(1)), Pow(Tan(u_), WC('n', S(1)))))), WC('C', S(1))), WC('v', S(0))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda b, x: FreeQ(b, x)), CustomConstraint(lambda c, x: FreeQ(c, x)), CustomConstraint(lambda d, x: FreeQ(d, x)), CustomConstraint(lambda e, x: FreeQ(e, x)), CustomConstraint(lambda f, x: FreeQ(f, x)), CustomConstraint(lambda A, x: FreeQ(A, x)), CustomConstraint(lambda B, x: FreeQ(B, x)), CustomConstraint(lambda C, x: FreeQ(C, x)), CustomConstraint(lambda n: IntegerQ(n)), CustomConstraint(lambda B, A, C: ZeroQ(Add(A, B, C))))
rule5 = ReplacementRule(pattern5, lambda n, e, x, v, b, A, B, u, c, f, d, a, C : Add(SimplifyAntiderivativeSum(v, x), Mul(A, Log(RemoveContent(Add(Mul(a, Pow(Cos(u), n)), Mul(b, Pow(Sin(u), n))), x))), Mul(B, Log(RemoveContent(Add(Mul(c, Pow(Cos(u), n)), Mul(d, Pow(Sin(u), n))), x))), Mul(C, Log(RemoveContent(Add(Mul(e, Pow(Cos(u), n)), Mul(f, Pow(Sin(u), n))), x)))))
replacer.add(rule5)
pattern6 = Pattern(UtilityOperator(Add(Mul(Log(Add(Mul(Pow(Cot(u_), WC('n', S(1))), WC('b', S(1))), a_)), WC('A', S(1))), Mul(Log(Add(Mul(Pow(Cot(u_), WC('n', S(1))), WC('d', S(1))), c_)), WC('B', S(1))), Mul(Log(Add(Mul(Pow(Cot(u_), WC('n', S(1))), WC('f', S(1))), e_)), WC('C', S(1))), WC('v', S(0))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda b, x: FreeQ(b, x)), CustomConstraint(lambda c, x: FreeQ(c, x)), CustomConstraint(lambda d, x: FreeQ(d, x)), CustomConstraint(lambda e, x: FreeQ(e, x)), CustomConstraint(lambda f, x: FreeQ(f, x)), CustomConstraint(lambda A, x: FreeQ(A, x)), CustomConstraint(lambda B, x: FreeQ(B, x)), CustomConstraint(lambda C, x: FreeQ(C, x)), CustomConstraint(lambda n: IntegerQ(n)), CustomConstraint(lambda B, A, C: ZeroQ(Add(A, B, C))))
rule6 = ReplacementRule(pattern6, lambda n, e, x, v, b, A, B, c, a, f, d, u, C : Add(SimplifyAntiderivativeSum(v, x), Mul(A, Log(RemoveContent(Add(Mul(b, Pow(Cos(u), n)), Mul(a, Pow(Sin(u), n))), x))), Mul(B, Log(RemoveContent(Add(Mul(d, Pow(Cos(u), n)), Mul(c, Pow(Sin(u), n))), x))), Mul(C, Log(RemoveContent(Add(Mul(f, Pow(Cos(u), n)), Mul(e, Pow(Sin(u), n))), x)))))
replacer.add(rule6)
return replacer
@doctest_depends_on(modules=('matchpy',))
def SimplifyAntiderivativeSum(expr, x):
r = SimplifyAntiderivativeSum_replacer.replace(UtilityOperator(expr, x))
if isinstance(r, UtilityOperator):
return expr
return r
@doctest_depends_on(modules=('matchpy',))
def _SimplifyAntiderivative():
replacer = ManyToOneReplacer()
pattern2 = Pattern(UtilityOperator(Log(Mul(c_, u_)), x_), CustomConstraint(lambda c, x: FreeQ(c, x)))
rule2 = ReplacementRule(pattern2, lambda x, c, u : SimplifyAntiderivative(Log(u), x))
replacer.add(rule2)
pattern3 = Pattern(UtilityOperator(Log(Pow(u_, n_)), x_), CustomConstraint(lambda n, x: FreeQ(n, x)))
rule3 = ReplacementRule(pattern3, lambda x, n, u : Mul(n, SimplifyAntiderivative(Log(u), x)))
replacer.add(rule3)
pattern7 = Pattern(UtilityOperator(Log(Pow(f_, u_)), x_), CustomConstraint(lambda f, x: FreeQ(f, x)))
rule7 = ReplacementRule(pattern7, lambda x, f, u : Mul(Log(f), SimplifyAntiderivative(u, x)))
replacer.add(rule7)
pattern8 = Pattern(UtilityOperator(Log(Add(a_, Mul(WC('b', S(1)), Tan(u_)))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda b, x: FreeQ(b, x)), CustomConstraint(lambda b, a: ZeroQ(Add(Pow(a, S(2)), Pow(b, S(2))))))
rule8 = ReplacementRule(pattern8, lambda x, b, u, a : Add(Mul(Mul(b, Pow(a, S(1))), SimplifyAntiderivative(u, x)), Mul(S(1), SimplifyAntiderivative(Log(Cos(u)), x))))
replacer.add(rule8)
pattern9 = Pattern(UtilityOperator(Log(Add(Mul(Cot(u_), WC('b', S(1))), a_)), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda b, x: FreeQ(b, x)), CustomConstraint(lambda b, a: ZeroQ(Add(Pow(a, S(2)), Pow(b, S(2))))))
rule9 = ReplacementRule(pattern9, lambda x, b, u, a : Add(Mul(Mul(Mul(S(1), b), Pow(a, S(1))), SimplifyAntiderivative(u, x)), Mul(S(1), SimplifyAntiderivative(Log(Sin(u)), x))))
replacer.add(rule9)
pattern10 = Pattern(UtilityOperator(ArcTan(Mul(WC('a', S(1)), Tan(u_))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda a: PositiveQ(Pow(a, S(2)))), CustomConstraint(lambda u: ComplexFreeQ(u)))
rule10 = ReplacementRule(pattern10, lambda x, u, a : RectifyTangent(u, a, S(1), x))
replacer.add(rule10)
pattern11 = Pattern(UtilityOperator(ArcCot(Mul(WC('a', S(1)), Tan(u_))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda a: PositiveQ(Pow(a, S(2)))), CustomConstraint(lambda u: ComplexFreeQ(u)))
rule11 = ReplacementRule(pattern11, lambda x, u, a : RectifyTangent(u, a, S(1), x))
replacer.add(rule11)
pattern12 = Pattern(UtilityOperator(ArcCot(Mul(WC('a', S(1)), Tanh(u_))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda u: ComplexFreeQ(u)))
rule12 = ReplacementRule(pattern12, lambda x, u, a : Mul(S(1), SimplifyAntiderivative(ArcTan(Mul(a, Tanh(u))), x)))
replacer.add(rule12)
pattern13 = Pattern(UtilityOperator(ArcTanh(Mul(WC('a', S(1)), Tan(u_))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda a: PositiveQ(Pow(a, S(2)))), CustomConstraint(lambda u: ComplexFreeQ(u)))
rule13 = ReplacementRule(pattern13, lambda x, u, a : RectifyTangent(u, Mul(I, a), Mul(S(1), I), x))
replacer.add(rule13)
pattern14 = Pattern(UtilityOperator(ArcCoth(Mul(WC('a', S(1)), Tan(u_))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda a: PositiveQ(Pow(a, S(2)))), CustomConstraint(lambda u: ComplexFreeQ(u)))
rule14 = ReplacementRule(pattern14, lambda x, u, a : RectifyTangent(u, Mul(I, a), Mul(S(1), I), x))
replacer.add(rule14)
pattern15 = Pattern(UtilityOperator(ArcTanh(Tanh(u_)), x_))
rule15 = ReplacementRule(pattern15, lambda x, u : SimplifyAntiderivative(u, x))
replacer.add(rule15)
pattern16 = Pattern(UtilityOperator(ArcCoth(Tanh(u_)), x_))
rule16 = ReplacementRule(pattern16, lambda x, u : SimplifyAntiderivative(u, x))
replacer.add(rule16)
pattern17 = Pattern(UtilityOperator(ArcCot(Mul(Cot(u_), WC('a', S(1)))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda a: PositiveQ(Pow(a, S(2)))), CustomConstraint(lambda u: ComplexFreeQ(u)))
rule17 = ReplacementRule(pattern17, lambda x, u, a : RectifyCotangent(u, a, S(1), x))
replacer.add(rule17)
pattern18 = Pattern(UtilityOperator(ArcTan(Mul(Cot(u_), WC('a', S(1)))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda a: PositiveQ(Pow(a, S(2)))), CustomConstraint(lambda u: ComplexFreeQ(u)))
rule18 = ReplacementRule(pattern18, lambda x, u, a : RectifyCotangent(u, a, S(1), x))
replacer.add(rule18)
pattern19 = Pattern(UtilityOperator(ArcTan(Mul(Coth(u_), WC('a', S(1)))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda u: ComplexFreeQ(u)))
rule19 = ReplacementRule(pattern19, lambda x, u, a : Mul(S(1), SimplifyAntiderivative(ArcTan(Mul(Tanh(u), Pow(a, S(1)))), x)))
replacer.add(rule19)
pattern20 = Pattern(UtilityOperator(ArcCoth(Mul(Cot(u_), WC('a', S(1)))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda a: PositiveQ(Pow(a, S(2)))), CustomConstraint(lambda u: ComplexFreeQ(u)))
rule20 = ReplacementRule(pattern20, lambda x, u, a : RectifyCotangent(u, Mul(I, a), I, x))
replacer.add(rule20)
pattern21 = Pattern(UtilityOperator(ArcTanh(Mul(Cot(u_), WC('a', S(1)))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda a: PositiveQ(Pow(a, S(2)))), CustomConstraint(lambda u: ComplexFreeQ(u)))
rule21 = ReplacementRule(pattern21, lambda x, u, a : RectifyCotangent(u, Mul(I, a), I, x))
replacer.add(rule21)
pattern22 = Pattern(UtilityOperator(ArcCoth(Coth(u_)), x_))
rule22 = ReplacementRule(pattern22, lambda x, u : SimplifyAntiderivative(u, x))
replacer.add(rule22)
pattern23 = Pattern(UtilityOperator(ArcTanh(Mul(Coth(u_), WC('a', S(1)))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda u: ComplexFreeQ(u)))
rule23 = ReplacementRule(pattern23, lambda x, u, a : SimplifyAntiderivative(ArcTanh(Mul(Tanh(u), Pow(a, S(1)))), x))
replacer.add(rule23)
pattern24 = Pattern(UtilityOperator(ArcTanh(Coth(u_)), x_))
rule24 = ReplacementRule(pattern24, lambda x, u : SimplifyAntiderivative(u, x))
replacer.add(rule24)
pattern25 = Pattern(UtilityOperator(ArcTan(Mul(WC('c', S(1)), Add(a_, Mul(WC('b', S(1)), Tan(u_))))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda b, x: FreeQ(b, x)), CustomConstraint(lambda c, x: FreeQ(c, x)), CustomConstraint(lambda c, a: PositiveQ(Mul(Pow(a, S(2)), Pow(c, S(2))))), CustomConstraint(lambda c, b: PositiveQ(Mul(Pow(b, S(2)), Pow(c, S(2))))), CustomConstraint(lambda u: ComplexFreeQ(u)))
rule25 = ReplacementRule(pattern25, lambda x, a, b, u, c : RectifyTangent(u, Mul(a, c), Mul(b, c), S(1), x))
replacer.add(rule25)
pattern26 = Pattern(UtilityOperator(ArcTanh(Mul(WC('c', S(1)), Add(a_, Mul(WC('b', S(1)), Tan(u_))))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda b, x: FreeQ(b, x)), CustomConstraint(lambda c, x: FreeQ(c, x)), CustomConstraint(lambda c, a: PositiveQ(Mul(Pow(a, S(2)), Pow(c, S(2))))), CustomConstraint(lambda c, b: PositiveQ(Mul(Pow(b, S(2)), Pow(c, S(2))))), CustomConstraint(lambda u: ComplexFreeQ(u)))
rule26 = ReplacementRule(pattern26, lambda x, a, b, u, c : RectifyTangent(u, Mul(I, a, c), Mul(I, b, c), Mul(S(1), I), x))
replacer.add(rule26)
pattern27 = Pattern(UtilityOperator(ArcTan(Mul(WC('c', S(1)), Add(Mul(Cot(u_), WC('b', S(1))), a_))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda b, x: FreeQ(b, x)), CustomConstraint(lambda c, x: FreeQ(c, x)), CustomConstraint(lambda c, a: PositiveQ(Mul(Pow(a, S(2)), Pow(c, S(2))))), CustomConstraint(lambda c, b: PositiveQ(Mul(Pow(b, S(2)), Pow(c, S(2))))), CustomConstraint(lambda u: ComplexFreeQ(u)))
rule27 = ReplacementRule(pattern27, lambda x, a, b, u, c : RectifyCotangent(u, Mul(a, c), Mul(b, c), S(1), x))
replacer.add(rule27)
pattern28 = Pattern(UtilityOperator(ArcTanh(Mul(WC('c', S(1)), Add(Mul(Cot(u_), WC('b', S(1))), a_))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda b, x: FreeQ(b, x)), CustomConstraint(lambda c, x: FreeQ(c, x)), CustomConstraint(lambda c, a: PositiveQ(Mul(Pow(a, S(2)), Pow(c, S(2))))), CustomConstraint(lambda c, b: PositiveQ(Mul(Pow(b, S(2)), Pow(c, S(2))))), CustomConstraint(lambda u: ComplexFreeQ(u)))
rule28 = ReplacementRule(pattern28, lambda x, a, b, u, c : RectifyCotangent(u, Mul(I, a, c), Mul(I, b, c), Mul(S(1), I), x))
replacer.add(rule28)
pattern29 = Pattern(UtilityOperator(ArcTan(Add(WC('a', S(0)), Mul(WC('b', S(1)), Tan(u_)), Mul(WC('c', S(1)), Pow(Tan(u_), S(2))))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda b, x: FreeQ(b, x)), CustomConstraint(lambda c, x: FreeQ(c, x)), CustomConstraint(lambda u: ComplexFreeQ(u)))
rule29 = ReplacementRule(pattern29, lambda x, a, b, u, c : If(EvenQ(Denominator(NumericFactor(Together(u)))), ArcTan(NormalizeTogether(Mul(Add(a, c, S(1), Mul(Add(a, Mul(S(1), c), S(1)), Cos(Mul(S(2), u))), Mul(b, Sin(Mul(S(2), u)))), Pow(Add(a, c, S(1), Mul(Add(a, Mul(S(1), c), S(1)), Cos(Mul(S(2), u))), Mul(b, Sin(Mul(S(2), u)))), S(1))))), ArcTan(NormalizeTogether(Mul(Add(c, Mul(Add(a, Mul(S(1), c), S(1)), Pow(Cos(u), S(2))), Mul(b, Cos(u), Sin(u))), Pow(Add(c, Mul(Add(a, Mul(S(1), c), S(1)), Pow(Cos(u), S(2))), Mul(b, Cos(u), Sin(u))), S(1)))))))
replacer.add(rule29)
pattern30 = Pattern(UtilityOperator(ArcTan(Add(WC('a', S(0)), Mul(WC('b', S(1)), Add(WC('d', S(0)), Mul(WC('e', S(1)), Tan(u_)))), Mul(WC('c', S(1)), Pow(Add(WC('f', S(0)), Mul(WC('g', S(1)), Tan(u_))), S(2))))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda b, x: FreeQ(b, x)), CustomConstraint(lambda c, x: FreeQ(c, x)), CustomConstraint(lambda u: ComplexFreeQ(u)))
rule30 = ReplacementRule(pattern30, lambda x, d, a, e, f, b, u, c, g : SimplifyAntiderivative(ArcTan(Add(a, Mul(b, d), Mul(c, Pow(f, S(2))), Mul(Add(Mul(b, e), Mul(S(2), c, f, g)), Tan(u)), Mul(c, Pow(g, S(2)), Pow(Tan(u), S(2))))), x))
replacer.add(rule30)
pattern31 = Pattern(UtilityOperator(ArcTan(Add(WC('a', S(0)), Mul(WC('c', S(1)), Pow(Tan(u_), S(2))))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda c, x: FreeQ(c, x)), CustomConstraint(lambda u: ComplexFreeQ(u)))
rule31 = ReplacementRule(pattern31, lambda x, c, u, a : If(EvenQ(Denominator(NumericFactor(Together(u)))), ArcTan(NormalizeTogether(Mul(Add(a, c, S(1), Mul(Add(a, Mul(S(1), c), S(1)), Cos(Mul(S(2), u)))), Pow(Add(a, c, S(1), Mul(Add(a, Mul(S(1), c), S(1)), Cos(Mul(S(2), u)))), S(1))))), ArcTan(NormalizeTogether(Mul(Add(c, Mul(Add(a, Mul(S(1), c), S(1)), Pow(Cos(u), S(2)))), Pow(Add(c, Mul(Add(a, Mul(S(1), c), S(1)), Pow(Cos(u), S(2)))), S(1)))))))
replacer.add(rule31)
pattern32 = Pattern(UtilityOperator(ArcTan(Add(WC('a', S(0)), Mul(WC('c', S(1)), Pow(Add(WC('f', S(0)), Mul(WC('g', S(1)), Tan(u_))), S(2))))), x_), CustomConstraint(lambda a, x: FreeQ(a, x)), CustomConstraint(lambda c, x: FreeQ(c, x)), CustomConstraint(lambda u: ComplexFreeQ(u)))
rule32 = ReplacementRule(pattern32, lambda x, a, f, u, c, g : SimplifyAntiderivative(ArcTan(Add(a, Mul(c, Pow(f, S(2))), Mul(Mul(S(2), c, f, g), Tan(u)), Mul(c, Pow(g, S(2)), Pow(Tan(u), S(2))))), x))
replacer.add(rule32)
return replacer
@doctest_depends_on(modules=('matchpy',))
def SimplifyAntiderivative(expr, x):
r = SimplifyAntiderivative_replacer.replace(UtilityOperator(expr, x))
if isinstance(r, UtilityOperator):
if ProductQ(expr):
u, c = S(1), S(1)
for i in expr.args:
if FreeQ(i, x):
c *= i
else:
u *= i
if FreeQ(c, x) and c != S(1):
v = SimplifyAntiderivative(u, x)
if SumQ(v) and NonsumQ(u):
return Add(*[c*i for i in v.args])
return c*v
elif LogQ(expr):
F = expr.args[0]
if MemberQ([cot, sec, csc, coth, sech, csch], Head(F)):
return -SimplifyAntiderivative(Log(1/F), x)
if MemberQ([Log, atan, acot], Head(expr)):
F = Head(expr)
G = expr.args[0]
if MemberQ([cot, sec, csc, coth, sech, csch], Head(G)):
return -SimplifyAntiderivative(F(1/G), x)
if MemberQ([atanh, acoth], Head(expr)):
F = Head(expr)
G = expr.args[0]
if MemberQ([cot, sec, csc, coth, sech, csch], Head(G)):
return SimplifyAntiderivative(F(1/G), x)
u = expr
if FreeQ(u, x):
return S(0)
elif LogQ(u):
return Log(RemoveContent(u.args[0], x))
elif SumQ(u):
return SimplifyAntiderivativeSum(Add(*[SimplifyAntiderivative(i, x) for i in u.args]), x)
return u
else:
return r
@doctest_depends_on(modules=('matchpy',))
def _TrigSimplifyAux():
replacer = ManyToOneReplacer()
pattern1 = Pattern(UtilityOperator(Mul(WC('u', S(1)), Pow(Add(Mul(WC('a', S(1)), Pow(v_, WC('m', S(1)))), Mul(WC('b', S(1)), Pow(v_, WC('n', S(1))))), p_))), CustomConstraint(lambda v: InertTrigQ(v)), CustomConstraint(lambda p: IntegerQ(p)), CustomConstraint(lambda n, m: RationalQ(m, n)), CustomConstraint(lambda n, m: Less(m, n)))
rule1 = ReplacementRule(pattern1, lambda n, a, p, m, u, v, b : Mul(u, Pow(v, Mul(m, p)), Pow(TrigSimplifyAux(Add(a, Mul(b, Pow(v, Add(n, Mul(S(-1), m)))))), p)))
replacer.add(rule1)
pattern2 = Pattern(UtilityOperator(Add(Mul(Pow(cos(u_), S('2')), WC('a', S(1))), WC('v', S(0)), Mul(WC('b', S(1)), Pow(sin(u_), S('2'))))), CustomConstraint(lambda b, a: SameQ(a, b)))
rule2 = ReplacementRule(pattern2, lambda u, v, b, a : Add(a, v))
replacer.add(rule2)
pattern3 = Pattern(UtilityOperator(Add(WC('v', S(0)), Mul(WC('a', S(1)), Pow(sec(u_), S('2'))), Mul(WC('b', S(1)), Pow(tan(u_), S('2'))))), CustomConstraint(lambda b, a: SameQ(a, Mul(S(-1), b))))
rule3 = ReplacementRule(pattern3, lambda u, v, b, a : Add(a, v))
replacer.add(rule3)
pattern4 = Pattern(UtilityOperator(Add(Mul(Pow(csc(u_), S('2')), WC('a', S(1))), Mul(Pow(cot(u_), S('2')), WC('b', S(1))), WC('v', S(0)))), CustomConstraint(lambda b, a: SameQ(a, Mul(S(-1), b))))
rule4 = ReplacementRule(pattern4, lambda u, v, b, a : Add(a, v))
replacer.add(rule4)
pattern5 = Pattern(UtilityOperator(Pow(Add(Mul(Pow(cos(u_), S('2')), WC('a', S(1))), WC('v', S(0)), Mul(WC('b', S(1)), Pow(sin(u_), S('2')))), n_)))
rule5 = ReplacementRule(pattern5, lambda n, a, u, v, b : Pow(Add(Mul(Add(b, Mul(S(-1), a)), Pow(Sin(u), S('2'))), a, v), n))
replacer.add(rule5)
pattern6 = Pattern(UtilityOperator(Add(WC('w', S(0)), u_, Mul(WC('v', S(1)), Pow(sin(z_), S('2'))))), CustomConstraint(lambda u, v: SameQ(u, Mul(S(-1), v))))
rule6 = ReplacementRule(pattern6, lambda u, w, z, v : Add(Mul(u, Pow(Cos(z), S('2'))), w))
replacer.add(rule6)
pattern7 = Pattern(UtilityOperator(Add(Mul(Pow(cos(z_), S('2')), WC('v', S(1))), WC('w', S(0)), u_)), CustomConstraint(lambda u, v: SameQ(u, Mul(S(-1), v))))
rule7 = ReplacementRule(pattern7, lambda z, w, v, u : Add(Mul(u, Pow(Sin(z), S('2'))), w))
replacer.add(rule7)
pattern8 = Pattern(UtilityOperator(Add(WC('w', S(0)), u_, Mul(WC('v', S(1)), Pow(tan(z_), S('2'))))), CustomConstraint(lambda u, v: SameQ(u, v)))
rule8 = ReplacementRule(pattern8, lambda u, w, z, v : Add(Mul(u, Pow(Sec(z), S('2'))), w))
replacer.add(rule8)
pattern9 = Pattern(UtilityOperator(Add(Mul(Pow(cot(z_), S('2')), WC('v', S(1))), WC('w', S(0)), u_)), CustomConstraint(lambda u, v: SameQ(u, v)))
rule9 = ReplacementRule(pattern9, lambda z, w, v, u : Add(Mul(u, Pow(Csc(z), S('2'))), w))
replacer.add(rule9)
pattern10 = Pattern(UtilityOperator(Add(WC('w', S(0)), u_, Mul(WC('v', S(1)), Pow(sec(z_), S('2'))))), CustomConstraint(lambda u, v: SameQ(u, Mul(S(-1), v))))
rule10 = ReplacementRule(pattern10, lambda u, w, z, v : Add(Mul(v, Pow(Tan(z), S('2'))), w))
replacer.add(rule10)
pattern11 = Pattern(UtilityOperator(Add(Mul(Pow(csc(z_), S('2')), WC('v', S(1))), WC('w', S(0)), u_)), CustomConstraint(lambda u, v: SameQ(u, Mul(S(-1), v))))
rule11 = ReplacementRule(pattern11, lambda z, w, v, u : Add(Mul(v, Pow(Cot(z), S('2'))), w))
replacer.add(rule11)
pattern12 = Pattern(UtilityOperator(Mul(WC('u', S(1)), Pow(Add(Mul(cos(v_), WC('b', S(1))), a_), S(-1)), Pow(sin(v_), S('2')))), CustomConstraint(lambda b, a: ZeroQ(Add(Pow(a, S('2')), Mul(S(-1), Pow(b, S('2')))))))
rule12 = ReplacementRule(pattern12, lambda u, v, b, a : Mul(u, Add(Mul(S(1), Pow(a, S(-1))), Mul(S(-1), Mul(Cos(v), Pow(b, S(-1)))))))
replacer.add(rule12)
pattern13 = Pattern(UtilityOperator(Mul(Pow(cos(v_), S('2')), WC('u', S(1)), Pow(Add(a_, Mul(WC('b', S(1)), sin(v_))), S(-1)))), CustomConstraint(lambda b, a: ZeroQ(Add(Pow(a, S('2')), Mul(S(-1), Pow(b, S('2')))))))
rule13 = ReplacementRule(pattern13, lambda u, v, b, a : Mul(u, Add(Mul(S(1), Pow(a, S(-1))), Mul(S(-1), Mul(Sin(v), Pow(b, S(-1)))))))
replacer.add(rule13)
pattern14 = Pattern(UtilityOperator(Mul(WC('u', S(1)), Pow(tan(v_), WC('n', S(1))), Pow(Add(a_, Mul(WC('b', S(1)), Pow(tan(v_), WC('n', S(1))))), S(-1)))), CustomConstraint(lambda n: PositiveIntegerQ(n)), CustomConstraint(lambda a: NonsumQ(a)))
rule14 = ReplacementRule(pattern14, lambda n, a, u, v, b : Mul(u, Pow(Add(b, Mul(a, Pow(Cot(v), n))), S(-1))))
replacer.add(rule14)
pattern15 = Pattern(UtilityOperator(Mul(Pow(cot(v_), WC('n', S(1))), WC('u', S(1)), Pow(Add(Mul(Pow(cot(v_), WC('n', S(1))), WC('b', S(1))), a_), S(-1)))), CustomConstraint(lambda n: PositiveIntegerQ(n)), CustomConstraint(lambda a: NonsumQ(a)))
rule15 = ReplacementRule(pattern15, lambda n, a, u, v, b : Mul(u, Pow(Add(b, Mul(a, Pow(Tan(v), n))), S(-1))))
replacer.add(rule15)
pattern16 = Pattern(UtilityOperator(Mul(WC('u', S(1)), Pow(sec(v_), WC('n', S(1))), Pow(Add(a_, Mul(WC('b', S(1)), Pow(sec(v_), WC('n', S(1))))), S(-1)))), CustomConstraint(lambda n: PositiveIntegerQ(n)), CustomConstraint(lambda a: NonsumQ(a)))
rule16 = ReplacementRule(pattern16, lambda n, a, u, v, b : Mul(u, Pow(Add(b, Mul(a, Pow(Cos(v), n))), S(-1))))
replacer.add(rule16)
pattern17 = Pattern(UtilityOperator(Mul(Pow(csc(v_), WC('n', S(1))), WC('u', S(1)), Pow(Add(Mul(Pow(csc(v_), WC('n', S(1))), WC('b', S(1))), a_), S(-1)))), CustomConstraint(lambda n: PositiveIntegerQ(n)), CustomConstraint(lambda a: NonsumQ(a)))
rule17 = ReplacementRule(pattern17, lambda n, a, u, v, b : Mul(u, Pow(Add(b, Mul(a, Pow(Sin(v), n))), S(-1))))
replacer.add(rule17)
pattern18 = Pattern(UtilityOperator(Mul(WC('u', S(1)), Pow(Add(a_, Mul(WC('b', S(1)), Pow(sec(v_), WC('n', S(1))))), S(-1)), Pow(tan(v_), WC('n', S(1))))), CustomConstraint(lambda n: PositiveIntegerQ(n)), CustomConstraint(lambda a: NonsumQ(a)))
rule18 = ReplacementRule(pattern18, lambda n, a, u, v, b : Mul(u, Mul(Pow(Sin(v), n), Pow(Add(b, Mul(a, Pow(Cos(v), n))), S(-1)))))
replacer.add(rule18)
pattern19 = Pattern(UtilityOperator(Mul(Pow(cot(v_), WC('n', S(1))), WC('u', S(1)), Pow(Add(Mul(Pow(csc(v_), WC('n', S(1))), WC('b', S(1))), a_), S(-1)))), CustomConstraint(lambda n: PositiveIntegerQ(n)), CustomConstraint(lambda a: NonsumQ(a)))
rule19 = ReplacementRule(pattern19, lambda n, a, u, v, b : Mul(u, Mul(Pow(Cos(v), n), Pow(Add(b, Mul(a, Pow(Sin(v), n))), S(-1)))))
replacer.add(rule19)
pattern20 = Pattern(UtilityOperator(Mul(WC('u', S(1)), Pow(Add(Mul(WC('a', S(1)), Pow(sec(v_), WC('n', S(1)))), Mul(WC('b', S(1)), Pow(tan(v_), WC('n', S(1))))), WC('p', S(1))))), CustomConstraint(lambda n, p: IntegersQ(n, p)))
rule20 = ReplacementRule(pattern20, lambda n, a, p, u, v, b : Mul(u, Pow(Sec(v), Mul(n, p)), Pow(Add(a, Mul(b, Pow(Sin(v), n))), p)))
replacer.add(rule20)
pattern21 = Pattern(UtilityOperator(Mul(Pow(Add(Mul(Pow(csc(v_), WC('n', S(1))), WC('a', S(1))), Mul(Pow(cot(v_), WC('n', S(1))), WC('b', S(1)))), WC('p', S(1))), WC('u', S(1)))), CustomConstraint(lambda n, p: IntegersQ(n, p)))
rule21 = ReplacementRule(pattern21, lambda n, a, p, u, v, b : Mul(u, Pow(Csc(v), Mul(n, p)), Pow(Add(a, Mul(b, Pow(Cos(v), n))), p)))
replacer.add(rule21)
pattern22 = Pattern(UtilityOperator(Mul(WC('u', S(1)), Pow(Add(Mul(WC('b', S(1)), Pow(sin(v_), WC('n', S(1)))), Mul(WC('a', S(1)), Pow(tan(v_), WC('n', S(1))))), WC('p', S(1))))), CustomConstraint(lambda n, p: IntegersQ(n, p)))
rule22 = ReplacementRule(pattern22, lambda n, a, p, u, v, b : Mul(u, Pow(Tan(v), Mul(n, p)), Pow(Add(a, Mul(b, Pow(Cos(v), n))), p)))
replacer.add(rule22)
pattern23 = Pattern(UtilityOperator(Mul(Pow(Add(Mul(Pow(cot(v_), WC('n', S(1))), WC('a', S(1))), Mul(Pow(cos(v_), WC('n', S(1))), WC('b', S(1)))), WC('p', S(1))), WC('u', S(1)))), CustomConstraint(lambda n, p: IntegersQ(n, p)))
rule23 = ReplacementRule(pattern23, lambda n, a, p, u, v, b : Mul(u, Pow(Cot(v), Mul(n, p)), Pow(Add(a, Mul(b, Pow(Sin(v), n))), p)))
replacer.add(rule23)
pattern24 = Pattern(UtilityOperator(Mul(Pow(cos(v_), WC('m', S(1))), WC('u', S(1)), Pow(Add(WC('a', S(0)), Mul(WC('c', S(1)), Pow(sec(v_), WC('n', S(1)))), Mul(WC('b', S(1)), Pow(tan(v_), WC('n', S(1))))), WC('p', S(1))))), CustomConstraint(lambda n, p, m: IntegersQ(m, n, p)))
rule24 = ReplacementRule(pattern24, lambda n, a, c, p, m, u, v, b : Mul(u, Pow(Cos(v), Add(m, Mul(S(-1), Mul(n, p)))), Pow(Add(c, Mul(b, Pow(Sin(v), n)), Mul(a, Pow(Cos(v), n))), p)))
replacer.add(rule24)
pattern25 = Pattern(UtilityOperator(Mul(WC('u', S(1)), Pow(sec(v_), WC('m', S(1))), Pow(Add(WC('a', S(0)), Mul(WC('c', S(1)), Pow(sec(v_), WC('n', S(1)))), Mul(WC('b', S(1)), Pow(tan(v_), WC('n', S(1))))), WC('p', S(1))))), CustomConstraint(lambda n, p, m: IntegersQ(m, n, p)))
rule25 = ReplacementRule(pattern25, lambda n, a, c, p, m, u, v, b : Mul(u, Pow(Sec(v), Add(m, Mul(n, p))), Pow(Add(c, Mul(b, Pow(Sin(v), n)), Mul(a, Pow(Cos(v), n))), p)))
replacer.add(rule25)
pattern26 = Pattern(UtilityOperator(Mul(Pow(Add(WC('a', S(0)), Mul(Pow(cot(v_), WC('n', S(1))), WC('b', S(1))), Mul(Pow(csc(v_), WC('n', S(1))), WC('c', S(1)))), WC('p', S(1))), WC('u', S(1)), Pow(sin(v_), WC('m', S(1))))), CustomConstraint(lambda n, p, m: IntegersQ(m, n, p)))
rule26 = ReplacementRule(pattern26, lambda n, a, c, p, m, u, v, b : Mul(u, Pow(Sin(v), Add(m, Mul(S(-1), Mul(n, p)))), Pow(Add(c, Mul(b, Pow(Cos(v), n)), Mul(a, Pow(Sin(v), n))), p)))
replacer.add(rule26)
pattern27 = Pattern(UtilityOperator(Mul(Pow(csc(v_), WC('m', S(1))), Pow(Add(WC('a', S(0)), Mul(Pow(cot(v_), WC('n', S(1))), WC('b', S(1))), Mul(Pow(csc(v_), WC('n', S(1))), WC('c', S(1)))), WC('p', S(1))), WC('u', S(1)))), CustomConstraint(lambda n, p, m: IntegersQ(m, n, p)))
rule27 = ReplacementRule(pattern27, lambda n, a, c, p, m, u, v, b : Mul(u, Pow(Csc(v), Add(m, Mul(n, p))), Pow(Add(c, Mul(b, Pow(Cos(v), n)), Mul(a, Pow(Sin(v), n))), p)))
replacer.add(rule27)
pattern28 = Pattern(UtilityOperator(Mul(WC('u', S(1)), Pow(Add(Mul(Pow(csc(v_), WC('m', S(1))), WC('a', S(1))), Mul(WC('b', S(1)), Pow(sin(v_), WC('n', S(1))))), WC('p', S(1))))), CustomConstraint(lambda n, m: IntegersQ(m, n)))
rule28 = ReplacementRule(pattern28, lambda n, a, p, m, u, v, b : If(And(ZeroQ(Add(m, n, S(-2))), ZeroQ(Add(a, b))), Mul(u, Pow(Mul(a, Mul(Pow(Cos(v), S('2')), Pow(Pow(Sin(v), m), S(-1)))), p)), Mul(u, Pow(Mul(Add(a, Mul(b, Pow(Sin(v), Add(m, n)))), Pow(Pow(Sin(v), m), S(-1))), p))))
replacer.add(rule28)
pattern29 = Pattern(UtilityOperator(Mul(WC('u', S(1)), Pow(Add(Mul(Pow(cos(v_), WC('n', S(1))), WC('b', S(1))), Mul(WC('a', S(1)), Pow(sec(v_), WC('m', S(1))))), WC('p', S(1))))), CustomConstraint(lambda n, m: IntegersQ(m, n)))
rule29 = ReplacementRule(pattern29, lambda n, a, p, m, u, v, b : If(And(ZeroQ(Add(m, n, S(-2))), ZeroQ(Add(a, b))), Mul(u, Pow(Mul(a, Mul(Pow(Sin(v), S('2')), Pow(Pow(Cos(v), m), S(-1)))), p)), Mul(u, Pow(Mul(Add(a, Mul(b, Pow(Cos(v), Add(m, n)))), Pow(Pow(Cos(v), m), S(-1))), p))))
replacer.add(rule29)
pattern30 = Pattern(UtilityOperator(u_))
rule30 = ReplacementRule(pattern30, lambda u : u)
replacer.add(rule30)
return replacer
@doctest_depends_on(modules=('matchpy',))
def TrigSimplifyAux(expr):
return TrigSimplifyAux_replacer.replace(UtilityOperator(expr))
def Cancel(expr):
return cancel(expr)
class Util_Part(Function):
def doit(self):
i = Simplify(self.args[0])
if len(self.args) > 2 :
lst = list(self.args[1:])
else:
lst = self.args[1]
if isinstance(i, (int, Integer)):
if isinstance(lst, list):
return lst[i - 1]
elif AtomQ(lst):
return lst
return lst.args[i - 1]
else:
return self
def Part(lst, i): #see i = -1
if isinstance(lst, list):
return Util_Part(i, *lst).doit()
return Util_Part(i, lst).doit()
def PolyLog(n, p, z=None):
return polylog(n, p)
def D(f, x):
try:
return f.diff(x)
except ValueError:
return Function('D')(f, x)
def IntegralFreeQ(u):
return FreeQ(u, Integral)
def Dist(u, v, x):
#Dist(u,v) returns the sum of u times each term of v, provided v is free of Int
u = replace_pow_exp(u) # to replace back to SymPy's exp
v = replace_pow_exp(v)
w = Simp(u*x**2, x)/x**2
if u == 1:
return v
elif u == 0:
return 0
elif NumericFactor(u) < 0 and NumericFactor(-u) > 0:
return -Dist(-u, v, x)
elif SumQ(v):
return Add(*[Dist(u, i, x) for i in v.args])
elif IntegralFreeQ(v):
return Simp(u*v, x)
elif w != u and FreeQ(w, x) and w == Simp(w, x) and w == Simp(w*x**2, x)/x**2:
return Dist(w, v, x)
else:
return Simp(u*v, x)
def PureFunctionOfCothQ(u, v, x):
# If u is a pure function of Coth[v], PureFunctionOfCothQ[u,v,x] returns True;
if AtomQ(u):
return u != x
elif CalculusQ(u):
return False
elif HyperbolicQ(u) and ZeroQ(u.args[0] - v):
return CothQ(u)
return all(PureFunctionOfCothQ(i, v, x) for i in u.args)
def LogIntegral(z):
return li(z)
def ExpIntegralEi(z):
return Ei(z)
def ExpIntegralE(a, b):
return expint(a, b).evalf()
def SinIntegral(z):
return Si(z)
def CosIntegral(z):
return Ci(z)
def SinhIntegral(z):
return Shi(z)
def CoshIntegral(z):
return Chi(z)
class PolyGamma(Function):
@classmethod
def eval(cls, *args):
if len(args) == 2:
return polygamma(args[0], args[1])
return digamma(args[0])
def LogGamma(z):
return loggamma(z)
class ProductLog(Function):
@classmethod
def eval(cls, *args):
if len(args) == 2:
return LambertW(args[1], args[0]).evalf()
return LambertW(args[0]).evalf()
def Factorial(a):
return factorial(a)
def Zeta(*args):
return zeta(*args)
def HypergeometricPFQ(a, b, c):
return hyper(a, b, c)
def Sum_doit(exp, args):
"""
This function perform summation using SymPy's `Sum`.
Examples
========
>>> from sympy.integrals.rubi.utility_function import Sum_doit
>>> from sympy.abc import x
>>> Sum_doit(2*x + 2, [x, 0, 1.7])
6
"""
exp = replace_pow_exp(exp)
if not isinstance(args[2], (int, Integer)):
new_args = [args[0], args[1], Floor(args[2])]
return Sum(exp, new_args).doit()
return Sum(exp, args).doit()
def PolynomialQuotient(p, q, x):
try:
p = poly(p, x)
q = poly(q, x)
except:
p = poly(p)
q = poly(q)
try:
return quo(p, q).as_expr()
except (PolynomialDivisionFailed, UnificationFailed):
return p/q
def PolynomialRemainder(p, q, x):
try:
p = poly(p, x)
q = poly(q, x)
except:
p = poly(p)
q = poly(q)
try:
return rem(p, q).as_expr()
except (PolynomialDivisionFailed, UnificationFailed):
return S(0)
def Floor(x, a = None):
if a is None:
return floor(x)
return a*floor(x/a)
def Factor(var):
return factor(var)
def Rule(a, b):
return {a: b}
def Distribute(expr, *args):
if len(args) == 1:
if isinstance(expr, args[0]):
return expr
else:
return expr.expand()
if len(args) == 2:
if isinstance(expr, args[1]):
return expr.expand()
else:
return expr
return expr.expand()
def CoprimeQ(*args):
args = S(args)
g = gcd(*args)
if g == 1:
return True
return False
def Discriminant(a, b):
try:
return discriminant(a, b)
except PolynomialError:
return Function('Discriminant')(a, b)
def Negative(x):
return x < S(0)
def Quotient(m, n):
return Floor(m/n)
def process_trig(expr):
"""
This function processes trigonometric expressions such that all `cot` is
rewritten in terms of `tan`, `sec` in terms of `cos`, `csc` in terms of `sin` and
similarly for `coth`, `sech` and `csch`.
Examples
========
>>> from sympy.integrals.rubi.utility_function import process_trig
>>> from sympy.abc import x
>>> from sympy import coth, cot, csc
>>> process_trig(x*cot(x))
x/tan(x)
>>> process_trig(coth(x)*csc(x))
1/(sin(x)*tanh(x))
"""
expr = expr.replace(lambda x: isinstance(x, cot), lambda x: 1/tan(x.args[0]))
expr = expr.replace(lambda x: isinstance(x, sec), lambda x: 1/cos(x.args[0]))
expr = expr.replace(lambda x: isinstance(x, csc), lambda x: 1/sin(x.args[0]))
expr = expr.replace(lambda x: isinstance(x, coth), lambda x: 1/tanh(x.args[0]))
expr = expr.replace(lambda x: isinstance(x, sech), lambda x: 1/cosh(x.args[0]))
expr = expr.replace(lambda x: isinstance(x, csch), lambda x: 1/sinh(x.args[0]))
return expr
def _ExpandIntegrand():
Plus = Add
Times = Mul
def cons_f1(m):
return PositiveIntegerQ(m)
cons1 = CustomConstraint(cons_f1)
def cons_f2(d, c, b, a):
return ZeroQ(-a*d + b*c)
cons2 = CustomConstraint(cons_f2)
def cons_f3(a, x):
return FreeQ(a, x)
cons3 = CustomConstraint(cons_f3)
def cons_f4(b, x):
return FreeQ(b, x)
cons4 = CustomConstraint(cons_f4)
def cons_f5(c, x):
return FreeQ(c, x)
cons5 = CustomConstraint(cons_f5)
def cons_f6(d, x):
return FreeQ(d, x)
cons6 = CustomConstraint(cons_f6)
def cons_f7(e, x):
return FreeQ(e, x)
cons7 = CustomConstraint(cons_f7)
def cons_f8(f, x):
return FreeQ(f, x)
cons8 = CustomConstraint(cons_f8)
def cons_f9(g, x):
return FreeQ(g, x)
cons9 = CustomConstraint(cons_f9)
def cons_f10(h, x):
return FreeQ(h, x)
cons10 = CustomConstraint(cons_f10)
def cons_f11(e, b, c, f, n, p, F, x, d, m):
if not isinstance(x, Symbol):
return False
return FreeQ(List(F, b, c, d, e, f, m, n, p), x)
cons11 = CustomConstraint(cons_f11)
def cons_f12(F, x):
return FreeQ(F, x)
cons12 = CustomConstraint(cons_f12)
def cons_f13(m, x):
return FreeQ(m, x)
cons13 = CustomConstraint(cons_f13)
def cons_f14(n, x):
return FreeQ(n, x)
cons14 = CustomConstraint(cons_f14)
def cons_f15(p, x):
return FreeQ(p, x)
cons15 = CustomConstraint(cons_f15)
def cons_f16(e, b, c, f, n, a, p, F, x, d, m):
if not isinstance(x, Symbol):
return False
return FreeQ(List(F, a, b, c, d, e, f, m, n, p), x)
cons16 = CustomConstraint(cons_f16)
def cons_f17(n, m):
return IntegersQ(m, n)
cons17 = CustomConstraint(cons_f17)
def cons_f18(n):
return Less(n, S(0))
cons18 = CustomConstraint(cons_f18)
def cons_f19(x, u):
if not isinstance(x, Symbol):
return False
return PolynomialQ(u, x)
cons19 = CustomConstraint(cons_f19)
def cons_f20(G, F, u):
return SameQ(F(u)*G(u), S(1))
cons20 = CustomConstraint(cons_f20)
def cons_f21(q, x):
return FreeQ(q, x)
cons21 = CustomConstraint(cons_f21)
def cons_f22(F):
return MemberQ(List(ArcSin, ArcCos, ArcSinh, ArcCosh), F)
cons22 = CustomConstraint(cons_f22)
def cons_f23(j, n):
return ZeroQ(j - S(2)*n)
cons23 = CustomConstraint(cons_f23)
def cons_f24(A, x):
return FreeQ(A, x)
cons24 = CustomConstraint(cons_f24)
def cons_f25(B, x):
return FreeQ(B, x)
cons25 = CustomConstraint(cons_f25)
def cons_f26(m, u, x):
if not isinstance(x, Symbol):
return False
def _cons_f_u(d, w, c, p, x):
return And(FreeQ(List(c, d), x), IntegerQ(p), Greater(p, m))
cons_u = CustomConstraint(_cons_f_u)
pat = Pattern(UtilityOperator((c_ + x_*WC('d', S(1)))**p_*WC('w', S(1)), x_), cons_u)
result_matchq = is_match(UtilityOperator(u, x), pat)
return Not(And(PositiveIntegerQ(m), result_matchq))
cons26 = CustomConstraint(cons_f26)
def cons_f27(b, v, n, a, x, u, m):
if not isinstance(x, Symbol):
return False
return And(FreeQ(List(a, b, m), x), NegativeIntegerQ(n), Not(IntegerQ(m)), PolynomialQ(u, x), PolynomialQ(v, x),\
RationalQ(m), Less(m, -1), GreaterEqual(Exponent(u, x), (-n - IntegerPart(m))*Exponent(v, x)))
cons27 = CustomConstraint(cons_f27)
def cons_f28(v, n, x, u, m):
if not isinstance(x, Symbol):
return False
return And(FreeQ(List(a, b, m), x), NegativeIntegerQ(n), Not(IntegerQ(m)), PolynomialQ(u, x),\
PolynomialQ(v, x), GreaterEqual(Exponent(u, x), -n*Exponent(v, x)))
cons28 = CustomConstraint(cons_f28)
def cons_f29(n):
return PositiveIntegerQ(n/S(4))
cons29 = CustomConstraint(cons_f29)
def cons_f30(n):
return IntegerQ(n)
cons30 = CustomConstraint(cons_f30)
def cons_f31(n):
return Greater(n, S(1))
cons31 = CustomConstraint(cons_f31)
def cons_f32(n, m):
return Less(S(0), m, n)
cons32 = CustomConstraint(cons_f32)
def cons_f33(n, m):
return OddQ(n/GCD(m, n))
cons33 = CustomConstraint(cons_f33)
def cons_f34(a, b):
return PosQ(a/b)
cons34 = CustomConstraint(cons_f34)
def cons_f35(n, m, p):
return IntegersQ(m, n, p)
cons35 = CustomConstraint(cons_f35)
def cons_f36(n, m, p):
return Less(S(0), m, p, n)
cons36 = CustomConstraint(cons_f36)
def cons_f37(q, n, m, p):
return IntegersQ(m, n, p, q)
cons37 = CustomConstraint(cons_f37)
def cons_f38(n, q, m, p):
return Less(S(0), m, p, q, n)
cons38 = CustomConstraint(cons_f38)
def cons_f39(n):
return IntegerQ(n/S(2))
cons39 = CustomConstraint(cons_f39)
def cons_f40(p):
return NegativeIntegerQ(p)
cons40 = CustomConstraint(cons_f40)
def cons_f41(n, m):
return IntegersQ(m, n/S(2))
cons41 = CustomConstraint(cons_f41)
def cons_f42(n, m):
return Unequal(m, n/S(2))
cons42 = CustomConstraint(cons_f42)
def cons_f43(c, b, a):
return NonzeroQ(-S(4)*a*c + b**S(2))
cons43 = CustomConstraint(cons_f43)
def cons_f44(j, n, m):
return IntegersQ(m, n, j)
cons44 = CustomConstraint(cons_f44)
def cons_f45(n, m):
return Less(S(0), m, S(2)*n)
cons45 = CustomConstraint(cons_f45)
def cons_f46(n, m, p):
return Not(And(Equal(m, n), Equal(p, S(-1))))
cons46 = CustomConstraint(cons_f46)
def cons_f47(v, x):
if not isinstance(x, Symbol):
return False
return PolynomialQ(v, x)
cons47 = CustomConstraint(cons_f47)
def cons_f48(v, x):
if not isinstance(x, Symbol):
return False
return BinomialQ(v, x)
cons48 = CustomConstraint(cons_f48)
def cons_f49(v, x, u):
if not isinstance(x, Symbol):
return False
return Inequality(Exponent(u, x), Equal, Exponent(v, x) + S(-1), GreaterEqual, S(2))
cons49 = CustomConstraint(cons_f49)
def cons_f50(v, x, u):
if not isinstance(x, Symbol):
return False
return GreaterEqual(Exponent(u, x), Exponent(v, x))
cons50 = CustomConstraint(cons_f50)
def cons_f51(p):
return Not(IntegerQ(p))
cons51 = CustomConstraint(cons_f51)
def With2(e, b, c, f, n, a, g, h, x, d, m):
tmp = a*h - b*g
k = Symbol('k')
return f**(e*(c + d*x)**n)*SimplifyTerm(h**(-m)*tmp**m, x)/(g + h*x) + Sum_doit(f**(e*(c + d*x)**n)*(a + b*x)**(-k + m)*SimplifyTerm(b*h**(-k)*tmp**(k - 1), x), List(k, 1, m))
pattern2 = Pattern(UtilityOperator(f_**((x_*WC('d', S(1)) + WC('c', S(0)))**WC('n', S(1))*WC('e', S(1)))*(x_*WC('b', S(1)) + WC('a', S(0)))**WC('m', S(1))/(x_*WC('h', S(1)) + WC('g', S(0))), x_), cons3, cons4, cons5, cons6, cons7, cons8, cons9, cons10, cons1, cons2)
rule2 = ReplacementRule(pattern2, With2)
pattern3 = Pattern(UtilityOperator(F_**((x_*WC('d', S(1)) + WC('c', S(0)))**WC('n', S(1))*WC('b', S(1)))*x_**WC('m', S(1))*(e_ + x_*WC('f', S(1)))**WC('p', S(1)), x_), cons12, cons4, cons5, cons6, cons7, cons8, cons13, cons14, cons15, cons11)
def replacement3(e, b, c, f, n, p, F, x, d, m):
return If(And(PositiveIntegerQ(m, p), LessEqual(m, p), Or(EqQ(n, S(1)), ZeroQ(-c*f + d*e))), ExpandLinearProduct(F**(b*(c + d*x)**n)*(e + f*x)**p, x**m, e, f, x), If(PositiveIntegerQ(p), Distribute(F**(b*(c + d*x)**n)*x**m*(e + f*x)**p, Plus, Times), ExpandIntegrand(F**(b*(c + d*x)**n), x**m*(e + f*x)**p, x)))
rule3 = ReplacementRule(pattern3, replacement3)
pattern4 = Pattern(UtilityOperator(F_**((x_*WC('d', S(1)) + WC('c', S(0)))**WC('n', S(1))*WC('b', S(1)) + WC('a', S(0)))*x_**WC('m', S(1))*(e_ + x_*WC('f', S(1)))**WC('p', S(1)), x_), cons12, cons3, cons4, cons5, cons6, cons7, cons8, cons13, cons14, cons15, cons16)
def replacement4(e, b, c, f, n, a, p, F, x, d, m):
return If(And(PositiveIntegerQ(m, p), LessEqual(m, p), Or(EqQ(n, S(1)), ZeroQ(-c*f + d*e))), ExpandLinearProduct(F**(a + b*(c + d*x)**n)*(e + f*x)**p, x**m, e, f, x), If(PositiveIntegerQ(p), Distribute(F**(a + b*(c + d*x)**n)*x**m*(e + f*x)**p, Plus, Times), ExpandIntegrand(F**(a + b*(c + d*x)**n), x**m*(e + f*x)**p, x)))
rule4 = ReplacementRule(pattern4, replacement4)
def With5(b, v, c, n, a, F, u, x, d, m):
if not isinstance(x, Symbol) or not (FreeQ([F, a, b, c, d], x) and IntegersQ(m, n) and n < 0):
return False
w = ExpandIntegrand((a + b*x)**m*(c + d*x)**n, x)
w = ReplaceAll(w, Rule(x, F**v))
if SumQ(w):
return True
return False
pattern5 = Pattern(UtilityOperator((F_**v_*WC('b', S(1)) + a_)**WC('m', S(1))*(F_**v_*WC('d', S(1)) + c_)**n_*WC('u', S(1)), x_), cons12, cons3, cons4, cons5, cons6, cons17, cons18, CustomConstraint(With5))
def replacement5(b, v, c, n, a, F, u, x, d, m):
w = ReplaceAll(ExpandIntegrand((a + b*x)**m*(c + d*x)**n, x), Rule(x, F**v))
return w.func(*[u*i for i in w.args])
rule5 = ReplacementRule(pattern5, replacement5)
def With6(e, b, c, f, n, a, x, u, d, m):
if not isinstance(x, Symbol) or not (FreeQ([a, b, c, d, e, f, m, n], x) and PolynomialQ(u,x)):
return False
v = ExpandIntegrand(u*(a + b*x)**m, x)
if SumQ(v):
return True
return False
pattern6 = Pattern(UtilityOperator(f_**((x_*WC('d', S(1)) + WC('c', S(0)))**WC('n', S(1))*WC('e', S(1)))*u_*(x_*WC('b', S(1)) + WC('a', S(0)))**WC('m', S(1)), x_), cons3, cons4, cons5, cons6, cons7, cons8, cons13, cons14, cons19, CustomConstraint(With6))
def replacement6(e, b, c, f, n, a, x, u, d, m):
v = ExpandIntegrand(u*(a + b*x)**m, x)
return Distribute(f**(e*(c + d*x)**n)*v, Plus, Times)
rule6 = ReplacementRule(pattern6, replacement6)
pattern7 = Pattern(UtilityOperator(u_*(x_*WC('b', S(1)) + WC('a', S(0)))**WC('m', S(1))*Log((x_**WC('n', S(1))*WC('e', S(1)) + WC('d', S(0)))**WC('p', S(1))*WC('c', S(1))), x_), cons3, cons4, cons5, cons6, cons7, cons13, cons14, cons15, cons19)
def replacement7(e, b, c, n, a, p, x, u, d, m):
return ExpandIntegrand(Log(c*(d + e*x**n)**p), u*(a + b*x)**m, x)
rule7 = ReplacementRule(pattern7, replacement7)
pattern8 = Pattern(UtilityOperator(f_**((x_*WC('d', S(1)) + WC('c', S(0)))**WC('n', S(1))*WC('e', S(1)))*u_, x_), cons5, cons6, cons7, cons8, cons14, cons19)
def replacement8(e, c, f, n, x, u, d):
return If(EqQ(n, S(1)), ExpandIntegrand(f**(e*(c + d*x)**n), u, x), ExpandLinearProduct(f**(e*(c + d*x)**n), u, c, d, x))
rule8 = ReplacementRule(pattern8, replacement8)
# pattern9 = Pattern(UtilityOperator(F_**u_*(G_*u_*WC('b', S(1)) + a_)**WC('n', S(1)), x_), cons3, cons4, cons17, cons20)
# def replacement9(b, G, n, a, F, u, x, m):
# return ReplaceAll(ExpandIntegrand(x**(-m)*(a + b*x)**n, x), Rule(x, G(u)))
# rule9 = ReplacementRule(pattern9, replacement9)
pattern10 = Pattern(UtilityOperator(u_*(WC('a', S(0)) + WC('b', S(1))*Log(((x_*WC('f', S(1)) + WC('e', S(0)))**WC('p', S(1))*WC('d', S(1)))**WC('q', S(1))*WC('c', S(1))))**n_, x_), cons3, cons4, cons5, cons6, cons7, cons8, cons14, cons15, cons21, cons19)
def replacement10(e, b, c, f, n, a, p, x, u, d, q):
return ExpandLinearProduct((a + b*Log(c*(d*(e + f*x)**p)**q))**n, u, e, f, x)
rule10 = ReplacementRule(pattern10, replacement10)
# pattern11 = Pattern(UtilityOperator(u_*(F_*(x_*WC('d', S(1)) + WC('c', S(0)))*WC('b', S(1)) + WC('a', S(0)))**n_, x_), cons3, cons4, cons5, cons6, cons14, cons19, cons22)
# def replacement11(b, c, n, a, F, u, x, d):
# return ExpandLinearProduct((a + b*F(c + d*x))**n, u, c, d, x)
# rule11 = ReplacementRule(pattern11, replacement11)
pattern12 = Pattern(UtilityOperator(WC('u', S(1))/(x_**n_*WC('a', S(1)) + sqrt(c_ + x_**j_*WC('d', S(1)))*WC('b', S(1))), x_), cons3, cons4, cons5, cons6, cons14, cons23)
def replacement12(b, c, n, a, x, u, d, j):
return ExpandIntegrand(u*(a*x**n - b*sqrt(c + d*x**(S(2)*n)))/(-b**S(2)*c + x**(S(2)*n)*(a**S(2) - b**S(2)*d)), x)
rule12 = ReplacementRule(pattern12, replacement12)
pattern13 = Pattern(UtilityOperator((a_ + x_*WC('b', S(1)))**m_/(c_ + x_*WC('d', S(1))), x_), cons3, cons4, cons5, cons6, cons1)
def replacement13(b, c, a, x, d, m):
if RationalQ(a, b, c, d):
return ExpandExpression((a + b*x)**m/(c + d*x), x)
else:
tmp = a*d - b*c
k = Symbol("k")
return Sum_doit((a + b*x)**(-k + m)*SimplifyTerm(b*d**(-k)*tmp**(k + S(-1)), x), List(k, S(1), m)) + SimplifyTerm(d**(-m)*tmp**m, x)/(c + d*x)
rule13 = ReplacementRule(pattern13, replacement13)
pattern14 = Pattern(UtilityOperator((A_ + x_*WC('B', S(1)))*(a_ + x_*WC('b', S(1)))**WC('m', S(1))/(c_ + x_*WC('d', S(1))), x_), cons3, cons4, cons5, cons6, cons24, cons25, cons1)
def replacement14(b, B, A, c, a, x, d, m):
if RationalQ(a, b, c, d, A, B):
return ExpandExpression((A + B*x)*(a + b*x)**m/(c + d*x), x)
else:
tmp1 = (A*d - B*c)/d
tmp2 = ExpandIntegrand((a + b*x)**m/(c + d*x), x)
tmp2 = If(SumQ(tmp2), tmp2.func(*[SimplifyTerm(tmp1*i, x) for i in tmp2.args]), SimplifyTerm(tmp1*tmp2, x))
return SimplifyTerm(B/d, x)*(a + b*x)**m + tmp2
rule14 = ReplacementRule(pattern14, replacement14)
def With15(b, a, x, u, m):
tmp1 = ExpandLinearProduct((a + b*x)**m, u, a, b, x)
if not IntegerQ(m):
return tmp1
else:
tmp2 = ExpandExpression(u*(a + b*x)**m, x)
if SumQ(tmp2) and LessEqual(LeafCount(tmp2), LeafCount(tmp1) + S(2)):
return tmp2
else:
return tmp1
pattern15 = Pattern(UtilityOperator(u_*(a_ + x_*WC('b', S(1)))**m_, x_), cons3, cons4, cons13, cons19, cons26)
rule15 = ReplacementRule(pattern15, With15)
pattern16 = Pattern(UtilityOperator(u_*v_**n_*(a_ + x_*WC('b', S(1)))**m_, x_), cons27)
def replacement16(b, v, n, a, x, u, m):
s = PolynomialQuotientRemainder(u, v**(-n)*(a+b*x)**(-IntegerPart(m)), x)
return ExpandIntegrand((a + b*x)**FractionalPart(m)*s[0], x) + ExpandIntegrand(v**n*(a + b*x)**m*s[1], x)
rule16 = ReplacementRule(pattern16, replacement16)
pattern17 = Pattern(UtilityOperator(u_*v_**n_*(a_ + x_*WC('b', S(1)))**m_, x_), cons28)
def replacement17(b, v, n, a, x, u, m):
s = PolynomialQuotientRemainder(u, v**(-n),x)
return ExpandIntegrand((a + b*x)**(m)*s[0], x) + ExpandIntegrand(v**n*(a + b*x)**m*s[1], x)
rule17 = ReplacementRule(pattern17, replacement17)
def With18(b, n, a, x, u):
r = Numerator(Rt(-a/b, S(2)))
s = Denominator(Rt(-a/b, S(2)))
return r/(S(2)*a*(r + s*u**(n/S(2)))) + r/(S(2)*a*(r - s*u**(n/S(2))))
pattern18 = Pattern(UtilityOperator(S(1)/(a_ + u_**n_*WC('b', S(1))), x_), cons3, cons4, cons29)
rule18 = ReplacementRule(pattern18, With18)
def With19(b, n, a, x, u):
k = Symbol("k")
r = Numerator(Rt(-a/b, n))
s = Denominator(Rt(-a/b, n))
return Sum_doit(r/(a*n*(-(-1)**(2*k/n)*s*u + r)), List(k, 1, n))
pattern19 = Pattern(UtilityOperator(S(1)/(a_ + u_**n_*WC('b', S(1))), x_), cons3, cons4, cons30, cons31)
rule19 = ReplacementRule(pattern19, With19)
def With20(b, n, a, x, u, m):
k = Symbol("k")
g = GCD(m, n)
r = Numerator(Rt(a/b, n/GCD(m, n)))
s = Denominator(Rt(a/b, n/GCD(m, n)))
return If(CoprimeQ(g + m, n), Sum_doit((-1)**(-2*k*m/n)*r*(-r/s)**(m/g)/(a*n*((-1)**(2*g*k/n)*s*u**g + r)), List(k, 1, n/g)), Sum_doit((-1)**(2*k*(g + m)/n)*r*(-r/s)**(m/g)/(a*n*((-1)**(2*g*k/n)*r + s*u**g)), List(k, 1, n/g)))
pattern20 = Pattern(UtilityOperator(u_**WC('m', S(1))/(a_ + u_**n_*WC('b', S(1))), x_), cons3, cons4, cons17, cons32, cons33, cons34)
rule20 = ReplacementRule(pattern20, With20)
def With21(b, n, a, x, u, m):
k = Symbol("k")
g = GCD(m, n)
r = Numerator(Rt(-a/b, n/GCD(m, n)))
s = Denominator(Rt(-a/b, n/GCD(m, n)))
return If(Equal(n/g, S(2)), s/(S(2)*b*(r + s*u**g)) - s/(S(2)*b*(r - s*u**g)), If(CoprimeQ(g + m, n), Sum_doit((S(-1))**(-S(2)*k*m/n)*r*(r/s)**(m/g)/(a*n*(-(S(-1))**(S(2)*g*k/n)*s*u**g + r)), List(k, S(1), n/g)), Sum_doit((S(-1))**(S(2)*k*(g + m)/n)*r*(r/s)**(m/g)/(a*n*((S(-1))**(S(2)*g*k/n)*r - s*u**g)), List(k, S(1), n/g))))
pattern21 = Pattern(UtilityOperator(u_**WC('m', S(1))/(a_ + u_**n_*WC('b', S(1))), x_), cons3, cons4, cons17, cons32)
rule21 = ReplacementRule(pattern21, With21)
def With22(b, c, n, a, x, u, d, m):
k = Symbol("k")
r = Numerator(Rt(-a/b, n))
s = Denominator(Rt(-a/b, n))
return Sum_doit((c*r + (-1)**(-2*k*m/n)*d*r*(r/s)**m)/(a*n*(-(-1)**(2*k/n)*s*u + r)), List(k, 1, n))
pattern22 = Pattern(UtilityOperator((c_ + u_**WC('m', S(1))*WC('d', S(1)))/(a_ + u_**n_*WC('b', S(1))), x_), cons3, cons4, cons5, cons6, cons17, cons32)
rule22 = ReplacementRule(pattern22, With22)
def With23(e, b, c, n, a, p, x, u, d, m):
k = Symbol("k")
r = Numerator(Rt(-a/b, n))
s = Denominator(Rt(-a/b, n))
return Sum_doit((c*r + (-1)**(-2*k*p/n)*e*r*(r/s)**p + (-1)**(-2*k*m/n)*d*r*(r/s)**m)/(a*n*(-(-1)**(2*k/n)*s*u + r)), List(k, 1, n))
pattern23 = Pattern(UtilityOperator((u_**p_*WC('e', S(1)) + u_**WC('m', S(1))*WC('d', S(1)) + WC('c', S(0)))/(a_ + u_**n_*WC('b', S(1))), x_), cons3, cons4, cons5, cons6, cons7, cons35, cons36)
rule23 = ReplacementRule(pattern23, With23)
def With24(e, b, c, f, n, a, p, x, u, d, q, m):
k = Symbol("k")
r = Numerator(Rt(-a/b, n))
s = Denominator(Rt(-a/b, n))
return Sum_doit((c*r + (-1)**(-2*k*q/n)*f*r*(r/s)**q + (-1)**(-2*k*p/n)*e*r*(r/s)**p + (-1)**(-2*k*m/n)*d*r*(r/s)**m)/(a*n*(-(-1)**(2*k/n)*s*u + r)), List(k, 1, n))
pattern24 = Pattern(UtilityOperator((u_**p_*WC('e', S(1)) + u_**q_*WC('f', S(1)) + u_**WC('m', S(1))*WC('d', S(1)) + WC('c', S(0)))/(a_ + u_**n_*WC('b', S(1))), x_), cons3, cons4, cons5, cons6, cons7, cons8, cons37, cons38)
rule24 = ReplacementRule(pattern24, With24)
def With25(c, n, a, p, x, u):
q = Symbol('q')
return ReplaceAll(ExpandIntegrand(c**(-p), (c*x - q)**p*(c*x + q)**p, x), List(Rule(q, Rt(-a*c, S(2))), Rule(x, u**(n/S(2)))))
pattern25 = Pattern(UtilityOperator((a_ + u_**WC('n', S(1))*WC('c', S(1)))**p_, x_), cons3, cons5, cons39, cons40)
rule25 = ReplacementRule(pattern25, With25)
def With26(c, n, a, p, x, u, m):
q = Symbol('q')
return ReplaceAll(ExpandIntegrand(c**(-p), x**m*(c*x**(n/S(2)) - q)**p*(c*x**(n/S(2)) + q)**p, x), List(Rule(q, Rt(-a*c, S(2))), Rule(x, u)))
pattern26 = Pattern(UtilityOperator(u_**WC('m', S(1))*(u_**WC('n', S(1))*WC('c', S(1)) + WC('a', S(0)))**p_, x_), cons3, cons5, cons41, cons40, cons32, cons42)
rule26 = ReplacementRule(pattern26, With26)
def With27(b, c, n, a, p, x, u, j):
q = Symbol('q')
return ReplaceAll(ExpandIntegrand(S(4)**(-p)*c**(-p), (b + S(2)*c*x - q)**p*(b + S(2)*c*x + q)**p, x), List(Rule(q, Rt(-S(4)*a*c + b**S(2), S(2))), Rule(x, u**n)))
pattern27 = Pattern(UtilityOperator((u_**WC('j', S(1))*WC('c', S(1)) + u_**WC('n', S(1))*WC('b', S(1)) + WC('a', S(0)))**p_, x_), cons3, cons4, cons5, cons30, cons23, cons40, cons43)
rule27 = ReplacementRule(pattern27, With27)
def With28(b, c, n, a, p, x, u, j, m):
q = Symbol('q')
return ReplaceAll(ExpandIntegrand(S(4)**(-p)*c**(-p), x**m*(b + S(2)*c*x**n - q)**p*(b + S(2)*c*x**n + q)**p, x), List(Rule(q, Rt(-S(4)*a*c + b**S(2), S(2))), Rule(x, u)))
pattern28 = Pattern(UtilityOperator(u_**WC('m', S(1))*(u_**WC('j', S(1))*WC('c', S(1)) + u_**WC('n', S(1))*WC('b', S(1)) + WC('a', S(0)))**p_, x_), cons3, cons4, cons5, cons44, cons23, cons40, cons45, cons46, cons43)
rule28 = ReplacementRule(pattern28, With28)
def With29(b, c, n, a, x, u, d, j):
q = Rt(-a/b, S(2))
return -(c - d*q)/(S(2)*b*q*(q + u**n)) - (c + d*q)/(S(2)*b*q*(q - u**n))
pattern29 = Pattern(UtilityOperator((u_**WC('n', S(1))*WC('d', S(1)) + WC('c', S(0)))/(a_ + u_**WC('j', S(1))*WC('b', S(1))), x_), cons3, cons4, cons5, cons6, cons14, cons23)
rule29 = ReplacementRule(pattern29, With29)
def With30(e, b, c, f, n, a, g, x, u, d, j):
q = Rt(-S(4)*a*c + b**S(2), S(2))
r = TogetherSimplify((-b*e*g + S(2)*c*(d + e*f))/q)
return (e*g - r)/(b + 2*c*u**n + q) + (e*g + r)/(b + 2*c*u**n - q)
pattern30 = Pattern(UtilityOperator(((u_**WC('n', S(1))*WC('g', S(1)) + WC('f', S(0)))*WC('e', S(1)) + WC('d', S(0)))/(u_**WC('j', S(1))*WC('c', S(1)) + u_**WC('n', S(1))*WC('b', S(1)) + WC('a', S(0))), x_), cons3, cons4, cons5, cons6, cons7, cons8, cons9, cons14, cons23, cons43)
rule30 = ReplacementRule(pattern30, With30)
def With31(v, x, u):
lst = CoefficientList(u, x)
i = Symbol('i')
return x**Exponent(u, x)*lst[-1]/v + Sum_doit(x**(i - 1)*Part(lst, i), List(i, 1, Exponent(u, x)))/v
pattern31 = Pattern(UtilityOperator(u_/v_, x_), cons19, cons47, cons48, cons49)
rule31 = ReplacementRule(pattern31, With31)
pattern32 = Pattern(UtilityOperator(u_/v_, x_), cons19, cons47, cons50)
def replacement32(v, x, u):
return PolynomialDivide(u, v, x)
rule32 = ReplacementRule(pattern32, replacement32)
pattern33 = Pattern(UtilityOperator(u_*(x_*WC('a', S(1)))**p_, x_), cons51, cons19)
def replacement33(x, a, u, p):
return ExpandToSum((a*x)**p, u, x)
rule33 = ReplacementRule(pattern33, replacement33)
pattern34 = Pattern(UtilityOperator(v_**p_*WC('u', S(1)), x_), cons51)
def replacement34(v, x, u, p):
return ExpandIntegrand(NormalizeIntegrand(v**p, x), u, x)
rule34 = ReplacementRule(pattern34, replacement34)
pattern35 = Pattern(UtilityOperator(u_, x_))
def replacement35(x, u):
return ExpandExpression(u, x)
rule35 = ReplacementRule(pattern35, replacement35)
return [ rule2,rule3, rule4, rule5, rule6, rule7, rule8, rule10, rule12, rule13, rule14, rule15, rule16, rule17, rule18, rule19, rule20, rule21, rule22, rule23, rule24, rule25, rule26, rule27, rule28, rule29, rule30, rule31, rule32, rule33, rule34, rule35]
def _RemoveContentAux():
def cons_f1(b, a):
return IntegersQ(a, b)
cons1 = CustomConstraint(cons_f1)
def cons_f2(b, a):
return Equal(a + b, S(0))
cons2 = CustomConstraint(cons_f2)
def cons_f3(m):
return RationalQ(m)
cons3 = CustomConstraint(cons_f3)
def cons_f4(m, n):
return RationalQ(m, n)
cons4 = CustomConstraint(cons_f4)
def cons_f5(m, n):
return GreaterEqual(-m + n, S(0))
cons5 = CustomConstraint(cons_f5)
def cons_f6(a, x):
return FreeQ(a, x)
cons6 = CustomConstraint(cons_f6)
def cons_f7(m, n, p):
return RationalQ(m, n, p)
cons7 = CustomConstraint(cons_f7)
def cons_f8(m, p):
return GreaterEqual(-m + p, S(0))
cons8 = CustomConstraint(cons_f8)
pattern1 = Pattern(UtilityOperator(a_**m_*WC('u', S(1)) + b_*WC('v', S(1)), x_), cons1, cons2, cons3)
def replacement1(v, x, a, u, m, b):
return If(Greater(m, S(1)), RemoveContentAux(a**(m + S(-1))*u - v, x), RemoveContentAux(-a**(-m + S(1))*v + u, x))
rule1 = ReplacementRule(pattern1, replacement1)
pattern2 = Pattern(UtilityOperator(a_**WC('m', S(1))*WC('u', S(1)) + a_**WC('n', S(1))*WC('v', S(1)), x_), cons6, cons4, cons5)
def replacement2(n, v, x, u, m, a):
return RemoveContentAux(a**(-m + n)*v + u, x)
rule2 = ReplacementRule(pattern2, replacement2)
pattern3 = Pattern(UtilityOperator(a_**WC('m', S(1))*WC('u', S(1)) + a_**WC('n', S(1))*WC('v', S(1)) + a_**WC('p', S(1))*WC('w', S(1)), x_), cons6, cons7, cons5, cons8)
def replacement3(n, v, x, p, u, w, m, a):
return RemoveContentAux(a**(-m + n)*v + a**(-m + p)*w + u, x)
rule3 = ReplacementRule(pattern3, replacement3)
pattern4 = Pattern(UtilityOperator(u_, x_))
def replacement4(u, x):
return If(And(SumQ(u), NegQ(First(u))), -u, u)
rule4 = ReplacementRule(pattern4, replacement4)
return [rule1, rule2, rule3, rule4, ]
IntHide = Int
Log = rubi_log
Null = None
if matchpy:
RemoveContentAux_replacer = ManyToOneReplacer(* _RemoveContentAux())
ExpandIntegrand_rules = _ExpandIntegrand()
TrigSimplifyAux_replacer = _TrigSimplifyAux()
SimplifyAntiderivative_replacer = _SimplifyAntiderivative()
SimplifyAntiderivativeSum_replacer = _SimplifyAntiderivativeSum()
FixSimplify_rules = _FixSimplify()
SimpFixFactor_replacer = _SimpFixFactor()
|
76e23cb10aadfb9e0600edc9a2d846b24d7bd5e1a3b14042c9ad189e7ab6fb43 | from sympy.concrete.summations import Sum
from sympy.core.add import Add
from sympy.core.function import (Derivative, Function, diff)
from sympy.core.numbers import (I, Rational, pi)
from sympy.core.relational import Ne
from sympy.core.symbol import (Symbol, symbols)
from sympy.functions.elementary.exponential import (LambertW, exp, log)
from sympy.functions.elementary.hyperbolic import (asinh, cosh, sinh, tanh)
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.piecewise import Piecewise
from sympy.functions.elementary.trigonometric import (acos, asin, atan, cos, sin, tan)
from sympy.functions.special.bessel import (besselj, besselk, bessely, jn)
from sympy.functions.special.error_functions import erf
from sympy.integrals.integrals import Integral
from sympy.simplify.ratsimp import ratsimp
from sympy.simplify.simplify import simplify
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_issue_21166():
assert integrate(sin(x/sqrt(abs(x))), (x, -1, 1)) == 0
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)
# https://github.com/sympy/sympy/issues/23707
anti = -exp(z)/(sqrt(x - y)*exp(z*sqrt(x - y)) - exp(z*sqrt(x - y)))
assert heurisch(exp(z)*exp(-z*sqrt(x - y)), z) == anti
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
assert heurisch(sin(x/sqrt(-x)), x) == 2*x*cos(x/sqrt(-x))/sqrt(-x) - 2*sin(x/sqrt(-x))
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(
(log(x - sqrt(-y))/(2*sqrt(-y)) - log(x + 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
assert heurisch(1/sqrt(3*x**2-4), x, hints=[]) == \
sqrt(3)*log(3*x + sqrt(3)*sqrt(3*x**2 - 4))/3
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/(x**2 - y**2)) \
- y**2*sqrt(-x**2/(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
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))
def test_issue_22527():
t, R = symbols(r't R')
z = Function('z')(t)
def f(x):
return x/sqrt(R**2 - x**2)
Uz = integrate(f(z), z)
Ut = integrate(f(t), t)
assert Ut == Uz.subs(z, t)
|
79dfc5b337378a63afc551d1ce3eff21e06ce06e3f8ed655d8436d5608d76a84 | import math
from sympy.concrete.summations import (Sum, summation)
from sympy.core.add import Add
from sympy.core.containers import Tuple
from sympy.core.expr import Expr
from sympy.core.function import (Derivative, Function, Lambda, diff)
from sympy.core import EulerGamma
from sympy.core.numbers import (E, Float, I, Rational, nan, oo, pi, zoo)
from sympy.core.relational import (Eq, Ne)
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 (Abs, im, polar_lift, re, sign)
from sympy.functions.elementary.exponential import (LambertW, exp, exp_polar, log)
from sympy.functions.elementary.hyperbolic import (acosh, asinh, cosh, coth, csch, sinh, tanh, sech)
from sympy.functions.elementary.miscellaneous import (Max, Min, sqrt)
from sympy.functions.elementary.piecewise import Piecewise
from sympy.functions.elementary.trigonometric import (acos, asin, atan, cos, sin, sinc, tan, sec)
from sympy.functions.special.delta_functions import DiracDelta, Heaviside
from sympy.functions.special.error_functions import (Ci, Ei, Si, erf, erfc, erfi, fresnelc, li)
from sympy.functions.special.gamma_functions import (gamma, polygamma)
from sympy.functions.special.hyper import (hyper, meijerg)
from sympy.functions.special.singularity_functions import SingularityFunction
from sympy.functions.special.zeta_functions import lerchphi
from sympy.integrals.integrals import integrate
from sympy.logic.boolalg import And
from sympy.matrices.dense import Matrix
from sympy.polys.polytools import (Poly, factor)
from sympy.printing.str import sstr
from sympy.series.order import O
from sympy.sets.sets import Interval
from sympy.simplify.gammasimp import gammasimp
from sympy.simplify.simplify import simplify
from sympy.simplify.trigsimp import trigsimp
from sympy.tensor.indexed import (Idx, IndexedBase)
from sympy.core.expr import unchanged
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, warns)
from sympy.utilities.exceptions import SymPyDeprecationWarning
from sympy.core.random import verify_numerically
x, y, z, a, b, c, d, e, s, t, x_1, x_2 = symbols('x y z a b c d e s t x_1 x_2')
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')
# The stacklevel is based on Integral(Poly)
with warns(SymPyDeprecationWarning, test_stacklevel=False):
integrate(p, x)
with warns(SymPyDeprecationWarning, test_stacklevel=False):
Integral(p, (x,))
@slow
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().together() == -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)
# The stacklevel is based on Integral(Poly)
with warns_deprecated_sympy():
qx = Integral(p, x)
with warns(SymPyDeprecationWarning, test_stacklevel=False):
qx = integrate(p, x)
with warns(SymPyDeprecationWarning, test_stacklevel=False):
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_definite():
p = Poly(x + x**2*y + y**3, x, y)
with warns_deprecated_sympy():
Qx = Integral(p, (x, 0, 1))
with warns(SymPyDeprecationWarning, test_stacklevel=False):
Qx = integrate(p, (x, 0, 1))
with warns(SymPyDeprecationWarning, test_stacklevel=False):
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.core.function import expand_func
from sympy.functions.special.error_functions import 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_13733():
s = Symbol('s', positive=True)
pz = exp(-(z - y)**2/(2*s*s))/sqrt(2*pi*s*s)
pzgx = integrate(pz, (z, x, oo))
assert integrate(pzgx, (x, 0, oo)) == sqrt(2)*s*exp(-y**2/(2*s**2))/(2*sqrt(pi)) + \
y*erf(sqrt(2)*y/(2*s))/2 + y/2
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_issue_21741():
a = Float('3999999.9999999995', precision=53)
b = Float('2.5000000000000004e-7', precision=53)
r = Piecewise((b*I*exp(-a*I*pi*t*y)*exp(-a*I*pi*x*z)/(pi*x),
Ne(1.0*pi*x*exp(a*I*pi*t*y), 0)),
(z*exp(-a*I*pi*t*y), True))
fun = E**((-2*I*pi*(z*x+t*y))/(500*10**(-9)))
assert integrate(fun, z) == r
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))
# https://github.com/sympy/sympy/issues/23707
assert integrate(exp(t)*exp(-t*sqrt(x - y)), t) == Piecewise(
(-exp(t)/(sqrt(x - y)*exp(t*sqrt(x - y)) - exp(t*sqrt(x - y))),
Ne(x, y + 1)), (t, 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
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_free_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}
assert Integral(f(x), (f(x), 1, y)).free_symbols == {y}
assert Integral(f(x), (f(x), 1, x)).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) == \
x*sqrt(x**2 - z**2)/2 - z**2*log(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))
def test_issue_3940():
a, b, c, d = symbols('a:d', positive=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.core.function 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.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)).together() == \
(log(z) - Ci(pi**2*z) + EulerGamma + 2*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():
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():
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.core.function import expand_func
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.functions.special.gamma_functions import lowergamma
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?
@slow
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)).factor(
deep=True) == 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)), (x > sqrt(5)) | (x < -sqrt(5))),
((2*x**5 - 15*x**3 + 25*x - 25*sqrt(5 - x**2)*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_8368i():
from sympy.functions.elementary.complexes import arg, Abs
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)
),
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(
Abs(s) > 1,
Abs(arg(s)) < pi/2,
Abs(arg(s)) <= pi/2
)),
( 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_11742():
assert integrate(sqrt(-x**2 + 8*x + 48), (x, 4, 12)) == 16*pi
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(log(x**2))/5 - 2*x*cos(log(x**2))/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(sqrt(exp(x) + 1) - 1) - log(sqrt(exp(x) + 1) + 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(SymPyDeprecationWarning, test_stacklevel=False):
# The warning is made in the ExprWithLimits superclass. The stacklevel
# is correct for integrate(Eq) but not Eq.integrate
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', positive=True)
x = Symbol('x', real=True)
m = Symbol('m', real=True)
t = Symbol('t', 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) == (-I*(sqrt(-I)*log(x - I*sqrt(-I))/2
- sqrt(-I)*log(x + I*sqrt(-I))/2))
assert integrate(exp(-I*x**2), x) == sqrt(pi)*erf(sqrt(I)*x)/(2*sqrt(I))
assert integrate((1/(exp(I*t)-2)), t) == -t/2 - I*log(exp(I*t) - 2)/2
assert integrate((1/(exp(I*t)-2)), (t, 0, 2*pi)) == -pi
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)
@slow
def test_issue_15494():
s = symbols('s', 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**2*y)/2)/sqrt(x**2*y),
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]) == -log(9)/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)
def test_issue_21034():
x = Symbol('x', real=True, nonzero=True)
f1 = x*(-x**4/asin(5)**4 - x*sinh(x + log(asin(5))) + 5)
f2 = (x + cosh(cos(4)))/(x*(x + 1/(12*x)))
assert integrate(f1, x) == \
-x**6/(6*asin(5)**4) - x**2*cosh(x + log(asin(5))) + 5*x**2/2 + 2*x*sinh(x + log(asin(5))) - 2*cosh(x + log(asin(5)))
assert integrate(f2, x) == \
log(x**2 + S(1)/12)/2 + 2*sqrt(3)*cosh(cos(4))*atan(2*sqrt(3)*x)
def test_issue_4187():
assert integrate(log(x)*exp(-x), x) == Ei(-x) - exp(-x)*log(x)
assert integrate(log(x)*exp(-x), (x, 0, oo)) == -EulerGamma
def test_issue_5547():
L = Symbol('L')
z = Symbol('z')
r0 = Symbol('r0')
R0 = Symbol('R0')
assert integrate(r0**2*cos(z)**2, (z, -L/2, L/2)) == -r0**2*(-L/4 -
sin(L/2)*cos(L/2)/2) + r0**2*(L/4 + sin(L/2)*cos(L/2)/2)
assert integrate(r0**2*cos(R0*z)**2, (z, -L/2, L/2)) == Piecewise(
(-r0**2*(-L*R0/4 - sin(L*R0/2)*cos(L*R0/2)/2)/R0 +
r0**2*(L*R0/4 + sin(L*R0/2)*cos(L*R0/2)/2)/R0, (R0 > -oo) & (R0 < oo) & Ne(R0, 0)),
(L*r0**2, True))
w = 2*pi*z/L
sol = sqrt(2)*sqrt(L)*r0**2*fresnelc(sqrt(2)*sqrt(L))*gamma(S.One/4)/(16*gamma(S(5)/4)) + L*r0**2/2
assert integrate(r0**2*cos(w*z)**2, (z, -L/2, L/2)) == sol
def test_issue_15810():
assert integrate(1/(2**(2*x/3) + 1), (x, 0, oo)) == Rational(3, 2)
def test_issue_21024():
x = Symbol('x', real=True, nonzero=True)
f = log(x)*log(4*x) + log(3*x + exp(2))
F = x*log(x)**2 + x*(1 - 2*log(2)) + (-2*x + 2*x*log(2))*log(x) + \
(x + exp(2)/6)*log(3*x + exp(2)) + exp(2)*log(3*x + exp(2))/6
assert F == integrate(f, x)
f = (x + exp(3))/x**2
F = log(x) - exp(3)/x
assert F == integrate(f, x)
f = (x**2 + exp(5))/x
F = x**2/2 + exp(5)*log(x)
assert F == integrate(f, x)
f = x/(2*x + tanh(1))
F = x/2 - log(2*x + tanh(1))*tanh(1)/4
assert F == integrate(f, x)
f = x - sinh(4)/x
F = x**2/2 - log(x)*sinh(4)
assert F == integrate(f, x)
f = log(x + exp(5)/x)
F = x*log(x + exp(5)/x) - x + 2*exp(Rational(5, 2))*atan(x*exp(Rational(-5, 2)))
assert F == integrate(f, x)
f = x**5/(x + E)
F = x**5/5 - E*x**4/4 + x**3*exp(2)/3 - x**2*exp(3)/2 + x*exp(4) - exp(5)*log(x + E)
assert F == integrate(f, x)
f = 4*x/(x + sinh(5))
F = 4*x - 4*log(x + sinh(5))*sinh(5)
assert F == integrate(f, x)
f = x**2/(2*x + sinh(2))
F = x**2/4 - x*sinh(2)/4 + log(2*x + sinh(2))*sinh(2)**2/8
assert F == integrate(f, x)
f = -x**2/(x + E)
F = -x**2/2 + E*x - exp(2)*log(x + E)
assert F == integrate(f, x)
f = (2*x + 3)*exp(5)/x
F = 2*x*exp(5) + 3*exp(5)*log(x)
assert F == integrate(f, x)
f = x + 2 + cosh(3)/x
F = x**2/2 + 2*x + log(x)*cosh(3)
assert F == integrate(f, x)
f = x - tanh(1)/x**3
F = x**2/2 + tanh(1)/(2*x**2)
assert F == integrate(f, x)
f = (3*x - exp(6))/x
F = 3*x - exp(6)*log(x)
assert F == integrate(f, x)
f = x**4/(x + exp(5))**2 + x
F = x**3/3 + x**2*(Rational(1, 2) - exp(5)) + 3*x*exp(10) - 4*exp(15)*log(x + exp(5)) - exp(20)/(x + exp(5))
assert F == integrate(f, x)
f = x*(x + exp(10)/x**2) + x
F = x**3/3 + x**2/2 + exp(10)*log(x)
assert F == integrate(f, x)
f = x + x/(5*x + sinh(3))
F = x**2/2 + x/5 - log(5*x + sinh(3))*sinh(3)/25
assert F == integrate(f, x)
f = (x + exp(3))/(2*x**2 + 2*x)
F = exp(3)*log(x)/2 - exp(3)*log(x + 1)/2 + log(x + 1)/2
assert F == integrate(f, x).expand()
f = log(x + 4*sinh(4))
F = x*log(x + 4*sinh(4)) - x + 4*log(x + 4*sinh(4))*sinh(4)
assert F == integrate(f, x)
f = -x + 20*(exp(-5) - atan(4)/x)**3*sin(4)/x
F = (-x**2*exp(15)/2 + 20*log(x)*sin(4) - (-180*x**2*exp(5)*sin(4)*atan(4) + 90*x*exp(10)*sin(4)*atan(4)**2 - \
20*exp(15)*sin(4)*atan(4)**3)/(3*x**3))*exp(-15)
assert F == integrate(f, x)
f = 2*x**2*exp(-4) + 6/x
F_true = (2*x**3/3 + 6*exp(4)*log(x))*exp(-4)
assert F_true == integrate(f, x)
def test_issue_21721():
a = Symbol('a')
assert integrate(1/(pi*(1+(x-a)**2)),(x,-oo,oo)).expand() == \
-Heaviside(im(a) - 1, 0) + Heaviside(im(a) + 1, 0)
def test_issue_21831():
theta = symbols('theta')
assert integrate(cos(3*theta)/(5-4*cos(theta)), (theta, 0, 2*pi)) == pi/12
integrand = cos(2*theta)/(5 - 4*cos(theta))
assert integrate(integrand, (theta, 0, 2*pi)) == pi/6
@slow
def test_issue_22033_integral():
assert integrate((x**2 - Rational(1, 4))**2 * sqrt(1 - x**2), (x, -1, 1)) == pi/32
@slow
def test_issue_21671():
assert integrate(1,(z,x**2+y**2,2-x**2-y**2),(y,-sqrt(1-x**2),sqrt(1-x**2)),(x,-1,1)) == pi
assert integrate(-4*(1 - x**2)**(S(3)/2)/3 + 2*sqrt(1 - x**2)*(2 - 2*x**2), (x, -1, 1)) == pi
def test_issue_18527():
# The manual integrator can not currently solve this. Assert that it does
# not give an incorrect result involving Abs when x has real assumptions.
xr = symbols('xr', real=True)
expr = (cos(x)/(4+(sin(x))**2))
res_real = integrate(expr.subs(x, xr), xr, manual=True).subs(xr, x)
assert integrate(expr, x, manual=True) == res_real == Integral(expr, x)
def test_issue_23718():
f = 1/(b*cos(x) + a*sin(x))
Fpos = (-log(-a/b + tan(x/2) - sqrt(a**2 + b**2)/b)/sqrt(a**2 + b**2)
+log(-a/b + tan(x/2) + sqrt(a**2 + b**2)/b)/sqrt(a**2 + b**2))
F = Piecewise(
# XXX: The zoo case here is for a=b=0 so it should just be zoo or maybe
# it doesn't really need to be included at all given that the original
# integrand is really undefined in that case anyway.
(zoo*(-log(tan(x/2) - 1) + log(tan(x/2) + 1)), Eq(a, 0) & Eq(b, 0)),
(log(tan(x/2))/a, Eq(b, 0)),
(-I/(-I*b*sin(x) + b*cos(x)), Eq(a, -I*b)),
(I/(I*b*sin(x) + b*cos(x)), Eq(a, I*b)),
(Fpos, True),
)
assert integrate(f, x) == F
ap, bp = symbols('a, b', positive=True)
rep = {a: ap, b: bp}
assert integrate(f.subs(rep), x) == Fpos.subs(rep)
def test_issue_23566():
i = integrate(1/sqrt(x**2-1), (x, -2, -1))
assert i == -log(2 - sqrt(3))
assert math.isclose(i.n(), 1.31695789692482)
def test_pr_23583():
# This result from meijerg is wrong. Check whether new result is correct when this test fail.
assert integrate(1/sqrt((x - I)**2-1)) == Piecewise((acosh(x - I), Abs((x - I)**2) > 1), (-I*asin(x - I), True))
def test_issue_7264():
assert integrate(exp(x)*sqrt(1 + exp(2*x))) == sqrt(exp(2*x) + 1)*exp(x)/2 + asinh(exp(x))/2
def test_issue_11254a():
assert integrate(sech(x), (x, 0, 1)) == 2*atan(tanh(S.Half))
def test_issue_11254b():
assert integrate(csch(x), x) == log(tanh(x/2))
assert integrate(csch(x), (x, 0, 1)) == oo
def test_issue_11254d():
assert integrate((sech(x)**2).rewrite(sinh), x) == 2*tanh(x/2)/(tanh(x/2)**2 + 1)
def test_issue_22863():
i = integrate((3*x**3-x**2+2*x-4)/sqrt(x**2-3*x+2), (x, 0, 1))
assert i == -101*sqrt(2)/8 - 135*log(3 - 2*sqrt(2))/16
assert math.isclose(i.n(), -2.98126694400554)
def test_issue_9723():
assert integrate(sqrt(x + sqrt(x))) == \
2*sqrt(sqrt(x) + x)*(sqrt(x)/12 + x/3 - S(1)/8) + log(2*sqrt(x) + 2*sqrt(sqrt(x) + x) + 1)/8
assert integrate(sqrt(2*x+3+sqrt(4*x+5))**3) == \
sqrt(2*x + sqrt(4*x + 5) + 3) * \
(9*x/10 + 11*(4*x + 5)**(S(3)/2)/40 + sqrt(4*x + 5)/40 + (4*x + 5)**2/10 + S(11)/10)/2
def test_issue_23704():
# XXX: This is testing that an exception is not raised in risch Ideally
# manualintegrate (manual=True) would be able to compute this but
# manualintegrate is very slow for this example so we don't test that here.
assert (integrate(log(x)/x**2/(c*x**2+b*x+a),x, risch=True)
== NonElementaryIntegral(log(x)/(a*x**2 + b*x**3 + c*x**4), x))
def test_exp_substitution():
assert integrate(1/sqrt(1-exp(2*x))) == log(sqrt(1 - exp(2*x)) - 1)/2 - log(sqrt(1 - exp(2*x)) + 1)/2
def test_hyperbolic():
assert integrate(coth(x)) == x - log(tanh(x) + 1) + log(tanh(x))
assert integrate(sech(x)) == 2*atan(tanh(x/2))
assert integrate(csch(x)) == log(tanh(x/2))
def test_nested_pow():
assert integrate(sqrt(x**2)) == x*sqrt(x**2)/2
def test_sqrt_quadratic():
assert integrate(1/sqrt(3*x**2+4*x+5)) == sqrt(3)*asinh(3*sqrt(11)*(x + S(2)/3)/11)/3
assert integrate(1/sqrt(-3*x**2+4*x+5)) == sqrt(3)*asin(3*sqrt(19)*(x - S(2)/3)/19)/3
assert integrate(1/sqrt(3*x**2+4*x-5)) == sqrt(3)*log(6*x + 2*sqrt(3)*sqrt(3*x**2 + 4*x - 5) + 4)/3
assert integrate(1/sqrt(a+b*x+c*x**2), x) == \
Piecewise((log(b + 2*sqrt(c)*sqrt(a + b*x + c*x**2) + 2*c*x)/sqrt(c), Ne(c, 0)),
(2*sqrt(a + b*x)/b, Ne(b, 0)), (x/sqrt(a), True))
assert integrate((7*x+6)/sqrt(3*x**2+4*x+5)) == \
7*sqrt(3*x**2 + 4*x + 5)/3 + 4*sqrt(3)*asinh(3*sqrt(11)*(x + S(2)/3)/11)/9
assert integrate((7*x+6)/sqrt(-3*x**2+4*x+5)) == \
-7*sqrt(-3*x**2 + 4*x + 5)/3 + 32*sqrt(3)*asin(3*sqrt(19)*(x - S(2)/3)/19)/9
assert integrate((7*x+6)/sqrt(3*x**2+4*x-5)) == \
7*sqrt(3*x**2 + 4*x - 5)/3 + 4*sqrt(3)*log(6*x + 2*sqrt(3)*sqrt(3*x**2 + 4*x - 5) + 4)/9
assert integrate((d+e*x)/sqrt(a+b*x+c*x**2), x) == \
Piecewise((e*sqrt(a + b*x + c*x**2)/c +
(-b*e/(2*c) + d)*log(b + 2*sqrt(c)*sqrt(a + b*x + c*x**2) + 2*c*x)/sqrt(c), Ne(c, 0)),
((2*d*sqrt(a + b*x) + 2*e*(-a*sqrt(a + b*x) + (a + b*x)**(S(3)/2)/3)/b)/b, Ne(b, 0)),
((d*x + e*x**2/2)/sqrt(a), True))
assert integrate((3*x**3-x**2+2*x-4)/sqrt(x**2-3*x+2)) == \
sqrt(x**2 - 3*x + 2)*(x**2 + 13*x/4 + S(101)/8) + 135*log(2*x + 2*sqrt(x**2 - 3*x + 2) - 3)/16
assert integrate(sqrt(53225*x**2-66732*x+23013)) == \
(x/2 - S(16683)/53225)*sqrt(53225*x**2 - 66732*x + 23013) + \
111576969*sqrt(2129)*asinh(53225*x/10563 - S(11122)/3521)/1133160250
assert integrate(sqrt(a+b*x+c*x**2), x) == \
Piecewise(((x/2 + b/(4*c))*sqrt(a + b*x + c*x**2) +
(a/2 - b**2/(8*c))*log(b + 2*sqrt(c)*sqrt(a + b*x + c*x**2) + 2*c*x)/sqrt(c), Ne(c, 0)),
(2*(a + b*x)**(S(3)/2)/(3*b), Ne(b, 0)),
(sqrt(a)*x, True))
assert integrate(x*sqrt(x**2+2*x+4)) == \
(x**2/3 + x/6 + S(5)/6)*sqrt(x**2 + 2*x + 4) - 3*asinh(sqrt(3)*(x + 1)/3)/2
def test_mul_pow_derivative():
assert integrate(x*sec(x)*tan(x)) == x*sec(x) - log(tan(x) + sec(x))
assert integrate(x*sec(x)**2, x) == x*tan(x) + log(cos(x))
assert integrate(x**3*Derivative(f(x), (x, 4))) == \
x**3*Derivative(f(x), (x, 3)) - 3*x**2*Derivative(f(x), (x, 2)) + 6*x*Derivative(f(x), x) - 6*f(x)
|
d044bed9f815ac87ecd450e5f9b93bb471d9f216f1422fa8569d801ef4ab7a7f | from sympy.core.expr import Expr
from sympy.core.mul import Mul
from sympy.core.function import (Derivative, Function, diff, expand)
from sympy.core.numbers import (I, Rational, pi)
from sympy.core.relational import Ne
from sympy.core.singleton import S
from sympy.core.symbol import (Dummy, Symbol, symbols)
from sympy.functions.elementary.exponential import (exp, log)
from sympy.functions.elementary.hyperbolic import (asinh, csch, cosh, coth, sech, sinh, tanh)
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.piecewise import Piecewise
from sympy.functions.elementary.trigonometric import (acos, acot, acsc, asec, asin, atan, cos, cot, csc, sec, sin, tan)
from sympy.functions.special.delta_functions import Heaviside, DiracDelta
from sympy.functions.special.elliptic_integrals import (elliptic_e, elliptic_f)
from sympy.functions.special.error_functions import (Chi, Ci, Ei, Shi, Si, erf, erfi, fresnelc, fresnels, li)
from sympy.functions.special.gamma_functions import uppergamma
from sympy.functions.special.polynomials import (assoc_laguerre, chebyshevt, chebyshevu, gegenbauer, hermite, jacobi, laguerre, legendre)
from sympy.functions.special.zeta_functions import polylog
from sympy.integrals.integrals import (Integral, integrate)
from sympy.logic.boolalg import And
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, d, e = symbols('x y z u n a b c d e')
f = Function('f')
def assert_is_integral_of(f: Expr, F: Expr):
assert manualintegrate(f, x) == F
assert F.diff(x).equals(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 (-x**2, Rational(-1, 2), exp(u)) in find_substitutions(x * exp(-x**2), x, 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_is_integral_of(1/sqrt(1-exp(2*x)),
log(sqrt(1 - exp(2*x)) - 1)/2 - log(sqrt(1 - exp(2*x)) + 1)/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
assert_is_integral_of(x**x*(log(x)+1), x**x)
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 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
assert_is_integral_of(sinh(2*x), cosh(2*x)/2)
assert_is_integral_of(x*cosh(x**2), sinh(x**2)/2)
assert_is_integral_of(tanh(x), log(cosh(x)))
assert_is_integral_of(coth(x), log(sinh(x)))
f, F = sech(x), 2*atan(tanh(x/2))
assert manualintegrate(f, x) == F
assert (F.diff(x) - f).rewrite(exp).simplify() == 0 # todo: equals returns None
f, F = csch(x), log(tanh(x/2))
assert manualintegrate(f, x) == F
assert (F.diff(x) - f).rewrite(exp).simplify() == 0
@slow
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
@slow
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),
((log(x - sqrt(-ra/rb)) - log(x + sqrt(-ra/rb)))/(2*sqrt(rb)*sqrt(-ra)), True))
assert manualintegrate(1/(4 + rb*x**2), x) == \
Piecewise((atan(x/(2*sqrt(1/rb)))/(2*rb*sqrt(1/rb)), 1/rb > 0),
(-I*(log(x - 2*sqrt(-1/rb)) - log(x + 2*sqrt(-1/rb)))/(4*sqrt(rb)), True))
assert manualintegrate(1/(ra + 4*x**2), x) == \
Piecewise((atan(2*x/sqrt(ra))/(2*sqrt(ra)), ra > 0),
((log(x - sqrt(-ra)/2) - log(x + sqrt(-ra)/2))/(4*sqrt(-ra)), True))
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(ra*x**2 + 1), x) == \
Piecewise((asin(x*sqrt(-ra))/sqrt(-ra), ra < 0), (asinh(sqrt(ra)*x)/sqrt(ra), ra > 0), (x, True))
assert manualintegrate(1/sqrt(ra + x**2), x) == \
Piecewise((asinh(x*sqrt(1/ra)), ra > 0), (log(2*x + 2*sqrt(ra + x**2)), True))
# log
assert manualintegrate(1/sqrt(x**2 - 1), x) == log(2*x + 2*sqrt(x**2 - 1))
assert manualintegrate(1/sqrt(x**2 - 4), x) == log(2*x + 2*sqrt(x**2 - 4))
assert manualintegrate(1/sqrt(4*x**2 - 4), x) == log(8*x + 4*sqrt(4*x**2 - 4))/2
assert manualintegrate(1/sqrt(9*x**2 - 1), x) == log(18*x + 6*sqrt(9*x**2 - 1))/3
assert manualintegrate(1/sqrt(ra*x**2 - 4), x) == \
Piecewise((log(2*sqrt(ra)*sqrt(ra*x**2 - 4) + 2*ra*x)/sqrt(ra), Ne(ra, 0)), (-I*x/2, True))
assert manualintegrate(1/sqrt(-ra + 4*x**2), x) == \
Piecewise((asinh(2*x*sqrt(-1/ra))/2, ra < 0), (log(8*x + 4*sqrt(-ra + 4*x**2))/2, True))
# From https://www.wikiwand.com/en/List_of_integrals_of_inverse_trigonometric_functions
# asin
assert manualintegrate(asin(x), x) == x*asin(x) + sqrt(1 - x**2)
assert manualintegrate(asin(a*x), x) == Piecewise(((a*x*asin(a*x) + sqrt(-a**2*x**2 + 1))/a, Ne(a, 0)), (0, True))
assert manualintegrate(x*asin(a*x), x) == \
-a*Piecewise((-x*sqrt(-a**2*x**2 + 1)/(2*a**2) +
log(-2*a**2*x + 2*sqrt(-a**2)*sqrt(-a**2*x**2 + 1))/(2*a**2*sqrt(-a**2)), Ne(a**2, 0)),
(x**3/3, True))/2 + x**2*asin(a*x)/2
# acos
assert manualintegrate(acos(x), x) == x*acos(x) - sqrt(1 - x**2)
assert manualintegrate(acos(a*x), x) == Piecewise(((a*x*acos(a*x) - sqrt(-a**2*x**2 + 1))/a, Ne(a, 0)), (pi*x/2, True))
assert manualintegrate(x*acos(a*x), x) == \
a*Piecewise((-x*sqrt(-a**2*x**2 + 1)/(2*a**2) +
log(-2*a**2*x + 2*sqrt(-a**2)*sqrt(-a**2*x**2 + 1))/(2*a**2*sqrt(-a**2)), Ne(a**2, 0)),
(x**3/3, True))/2 + x**2*acos(a*x)/2
# atan
assert manualintegrate(atan(x), x) == x*atan(x) - log(x**2 + 1)/2
assert manualintegrate(atan(a*x), x) == Piecewise(((a*x*atan(a*x) - log(a**2*x**2 + 1)/2)/a, Ne(a, 0)), (0, True))
assert manualintegrate(x*atan(a*x), x) == -a*(x/a**2 - atan(x/sqrt(a**(-2)))/(a**4*sqrt(a**(-2))))/2 + x**2*atan(a*x)/2
# acsc
assert manualintegrate(acsc(x), x) == x*acsc(x) + Integral(1/(x*sqrt(1 - 1/x**2)), x)
assert manualintegrate(acsc(a*x), x) == x*acsc(a*x) + Integral(1/(x*sqrt(1 - 1/(a**2*x**2))), x)/a
assert manualintegrate(x*acsc(a*x), x) == x**2*acsc(a*x)/2 + Integral(1/sqrt(1 - 1/(a**2*x**2)), x)/(2*a)
# asec
assert manualintegrate(asec(x), x) == x*asec(x) - Integral(1/(x*sqrt(1 - 1/x**2)), x)
assert manualintegrate(asec(a*x), x) == x*asec(a*x) - Integral(1/(x*sqrt(1 - 1/(a**2*x**2))), x)/a
assert manualintegrate(x*asec(a*x), x) == x**2*asec(a*x)/2 - Integral(1/sqrt(1 - 1/(a**2*x**2)), x)/(2*a)
# acot
assert manualintegrate(acot(x), x) == x*acot(x) + log(x**2 + 1)/2
assert manualintegrate(acot(a*x), x) == Piecewise(((a*x*acot(a*x) + log(a**2*x**2 + 1)/2)/a, Ne(a, 0)), (pi*x/2, True))
assert manualintegrate(x*acot(a*x), x) == a*(x/a**2 - atan(x/sqrt(a**(-2)))/(a**4*sqrt(a**(-2))))/2 + x**2*acot(a*x)/2
# piecewise
assert manualintegrate(1/sqrt(ra-rb*x**2), x) == \
Piecewise((asin(x*sqrt(rb/ra))/sqrt(rb), And(-rb < 0, ra > 0)),
(asinh(x*sqrt(-rb/ra))/sqrt(-rb), And(-rb > 0, ra > 0)),
(log(-2*rb*x + 2*sqrt(-rb)*sqrt(ra - rb*x**2))/sqrt(-rb), Ne(rb, 0)),
(x/sqrt(ra), True))
assert manualintegrate(1/sqrt(ra + rb*x**2), x) == \
Piecewise((asin(x*sqrt(-rb/ra))/sqrt(-rb), And(ra > 0, rb < 0)),
(asinh(x*sqrt(rb/ra))/sqrt(rb), And(ra > 0, rb > 0)),
(log(2*sqrt(rb)*sqrt(ra + rb*x**2) + 2*rb*x)/sqrt(rb), Ne(rb, 0)),
(x/sqrt(ra), True))
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) == -log(x - 2)/4 + log(x + 2)/4
assert manualintegrate(1/(-1 + x**2), x) == log(x - 1)/2 - log(x + 1)/2
def test_manualintegrate_special():
f, F = 4*exp(-x**2/3), 2*sqrt(3)*sqrt(pi)*erf(sqrt(3)*x/3)
assert_is_integral_of(f, F)
f, F = 3*exp(4*x**2), 3*sqrt(pi)*erfi(2*x)/4
assert_is_integral_of(f, F)
f, F = x**Rational(1, 3)*exp(-x/8), -16*uppergamma(Rational(4, 3), x/8)
assert_is_integral_of(f, F)
f, F = exp(2*x)/x, Ei(2*x)
assert_is_integral_of(f, F)
f, F = exp(1 + 2*x - x**2), sqrt(pi)*exp(2)*erf(x - 1)/2
assert_is_integral_of(f, 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_is_integral_of(f, F)
f, F = cos(4*x**2), sqrt(2)*sqrt(pi)*fresnelc(2*sqrt(2)*x/sqrt(pi))/4
assert_is_integral_of(f, F)
f, F = sin(3*x + 2)/x, sin(2)*Ci(3*x) + cos(2)*Si(3*x)
assert_is_integral_of(f, F)
f, F = sinh(3*x - 2)/x, -sinh(2)*Chi(3*x) + cosh(2)*Shi(3*x)
assert_is_integral_of(f, F)
f, F = 5*cos(2*x - 3)/x, 5*cos(3)*Ci(2*x) + 5*sin(3)*Si(2*x)
assert_is_integral_of(f, F)
f, F = cosh(x/2)/x, Chi(x/2)
assert_is_integral_of(f, F)
f, F = cos(x**2)/x, Ci(x**2)/2
assert_is_integral_of(f, F)
f, F = 1/log(2*x + 1), li(2*x + 1)/2
assert_is_integral_of(f, F)
f, F = polylog(2, 5*x)/x, polylog(3, 5*x)
assert_is_integral_of(f, F)
f, F = 5/sqrt(3 - 2*sin(x)**2), 5*sqrt(3)*elliptic_f(x, Rational(2, 3))/3
assert_is_integral_of(f, F)
f, F = sqrt(4 + 9*sin(x)**2), 2*elliptic_e(x, Rational(-9, 4))
assert_is_integral_of(f, 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_is_integral_of(DiracDelta(3*x+2), Heaviside(3*x+2)/3)
assert_is_integral_of(DiracDelta(3*x, 0), Heaviside(3*x)/3)
assert manualintegrate(DiracDelta(a+b*x, 1), x) == \
Piecewise((DiracDelta(a + b*x)/b, Ne(b, 0)), (x*DiracDelta(a, 1), True))
assert_is_integral_of(DiracDelta(x/3-1, 2), 3*DiracDelta(x/3-1, 1))
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)
@slow
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)
@slow
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),
((log(-sqrt(rc) + x) - log(sqrt(rc) + x))/(2*sqrt(rc)), True)) + 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),
((log(-sqrt(-ry) + sqrt(x - ry)) - log(sqrt(-ry) + sqrt(x - ry)))/(2*sqrt(-ry)), True))/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) == \
Piecewise((2*b*atan(sqrt(a*x + b)/sqrt(-b))/sqrt(-b) + 2*sqrt(a*x + b), Ne(a, 0)), (sqrt(b)*log(x), True))
ra = Symbol('a', real=True)
rb = Symbol('b', real=True)
assert manualintegrate(sqrt(ra*x + rb) / x, x) == \
Piecewise(
(-2*rb*Piecewise(
(-atan(sqrt(ra*x + rb)/sqrt(-rb))/sqrt(-rb), rb < 0),
(-I*(log(-sqrt(rb) + sqrt(ra*x + rb)) - log(sqrt(rb) + sqrt(ra*x + rb)))/(2*sqrt(-rb)), True)) +
2*sqrt(ra*x + rb), Ne(ra, 0)),
(sqrt(rb)*log(x), True))
assert expand(manualintegrate(sqrt(ra*x + rb) / (x + rc), x)) == \
Piecewise((-2*ra*rc*Piecewise((atan(sqrt(ra*x + rb)/sqrt(ra*rc - rb))/sqrt(ra*rc - rb), ra*rc - rb > 0),
(log(-sqrt(-ra*rc + rb) + sqrt(ra*x + rb))/(2*sqrt(-ra*rc + rb)) -
log(sqrt(-ra*rc + rb) + sqrt(ra*x + rb))/(2*sqrt(-ra*rc + rb)), True)) +
2*rb*Piecewise((atan(sqrt(ra*x + rb)/sqrt(ra*rc - rb))/sqrt(ra*rc - rb), ra*rc - rb > 0),
(log(-sqrt(-ra*rc + rb) + sqrt(ra*x + rb))/(2*sqrt(-ra*rc + rb)) -
log(sqrt(-ra*rc + rb) + sqrt(ra*x + rb))/(2*sqrt(-ra*rc + rb)), True)) +
2*sqrt(ra*x + rb), Ne(ra, 0)), (sqrt(rb)*log(rc + x), True))
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)
@slow
def test_issue_13297():
assert manualintegrate(sin(x) * cos(x)**5, x) == -cos(x)**6 / 6
def test_issue_14470():
assert_is_integral_of(1/(x*sqrt(x + 1)), log(sqrt(x + 1) - 1) - log(sqrt(x + 1) + 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))
@slow
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_is_integral_of(f, 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)
def test_issue_22757():
assert manualintegrate(sin(x), y) == y * sin(x)
def test_issue_23348():
steps = integral_steps(tan(x), x)
constant_times_step = steps.substep.substep
assert constant_times_step.context == constant_times_step.constant * constant_times_step.other
def test_issue_23566():
i = Integral(1/sqrt(x**2 - 1), (x, -2, -1)).doit(manual=True)
assert i == -log(4 - 2*sqrt(3)) + log(2)
assert str(i.n()) == '1.31695789692482'
def test_manualintegrate_sqrt_linear():
assert_is_integral_of((5*x**3+4)/sqrt(2+3*x),
10*(3*x + 2)**(S(7)/2)/567 - 4*(3*x + 2)**(S(5)/2)/27 +
40*(3*x + 2)**(S(3)/2)/81 + 136*sqrt(3*x + 2)/81)
assert manualintegrate(x/sqrt(a+b*x)**3, x) == \
Piecewise((Mul(2, b**-2, a/sqrt(a + b*x) + sqrt(a + b*x)), Ne(b, 0)), (x**2/(2*a**(S(3)/2)), True))
assert_is_integral_of((sqrt(3*x+3)+1)/((2*x+2)**(1/S(3))+1),
3*sqrt(6)*(2*x + 2)**(S(7)/6)/14 - 3*sqrt(6)*(2*x + 2)**(S(5)/6)/10 -
3*sqrt(6)*(2*x + 2)**(S.One/6)/2 + 3*(2*x + 2)**(S(2)/3)/4 - 3*(2*x + 2)**(S.One/3)/2 +
sqrt(6)*sqrt(2*x + 2)/2 + 3*log((2*x + 2)**(S.One/3) + 1)/2 +
3*sqrt(6)*atan((2*x + 2)**(S.One/6))/2)
assert_is_integral_of(sqrt(x+sqrt(x)),
2*sqrt(sqrt(x) + x)*(sqrt(x)/12 + x/3 - S(1)/8) + log(2*sqrt(x) + 2*sqrt(sqrt(x) + x) + 1)/8)
assert_is_integral_of(sqrt(2*x+3+sqrt(4*x+5))**3,
sqrt(2*x + sqrt(4*x + 5) + 3) *
(9*x/10 + 11*(4*x + 5)**(S(3)/2)/40 + sqrt(4*x + 5)/40 + (4*x + 5)**2/10 + S(11)/10)/2)
def test_manualintegrate_sqrt_quadratic():
assert_is_integral_of(1/sqrt((x - I)**2-1), log(2*x + 2*sqrt(x**2 - 2*I*x - 2) - 2*I))
assert_is_integral_of(1/sqrt(3*x**2+4*x+5), sqrt(3)*asinh(3*sqrt(11)*(x + S(2)/3)/11)/3)
assert_is_integral_of(1/sqrt(-3*x**2+4*x+5), sqrt(3)*asin(3*sqrt(19)*(x - S(2)/3)/19)/3)
assert_is_integral_of(1/sqrt(3*x**2+4*x-5), sqrt(3)*log(6*x + 2*sqrt(3)*sqrt(3*x**2 + 4*x - 5) + 4)/3)
assert manualintegrate(1/sqrt(a+b*x+c*x**2), x) == \
Piecewise((log(b + 2*sqrt(c)*sqrt(a + b*x + c*x**2) + 2*c*x)/sqrt(c), Ne(c, 0)),
(2*sqrt(a + b*x)/b, Ne(b, 0)), (x/sqrt(a), True))
assert_is_integral_of((7*x+6)/sqrt(3*x**2+4*x+5),
7*sqrt(3*x**2 + 4*x + 5)/3 + 4*sqrt(3)*asinh(3*sqrt(11)*(x + S(2)/3)/11)/9)
assert_is_integral_of((7*x+6)/sqrt(-3*x**2+4*x+5),
-7*sqrt(-3*x**2 + 4*x + 5)/3 + 32*sqrt(3)*asin(3*sqrt(19)*(x - S(2)/3)/19)/9)
assert_is_integral_of((7*x+6)/sqrt(3*x**2+4*x-5),
7*sqrt(3*x**2 + 4*x - 5)/3 + 4*sqrt(3)*log(6*x + 2*sqrt(3)*sqrt(3*x**2 + 4*x - 5) + 4)/9)
assert manualintegrate((d+e*x)/sqrt(a+b*x+c*x**2), x) == \
Piecewise((e*sqrt(a + b*x + c*x**2)/c +
(-b*e/(2*c) + d)*log(b + 2*sqrt(c)*sqrt(a + b*x + c*x**2) + 2*c*x)/sqrt(c), Ne(c, 0)),
((2*d*sqrt(a + b*x) + 2*e*(-a*sqrt(a + b*x) + (a + b*x)**(S(3)/2)/3)/b)/b, Ne(b, 0)),
((d*x + e*x**2/2)/sqrt(a), True))
assert manualintegrate((3*x**3-x**2+2*x-4)/sqrt(x**2-3*x+2), x) == \
sqrt(x**2 - 3*x + 2)*(x**2 + 13*x/4 + S(101)/8) + 135*log(2*x + 2*sqrt(x**2 - 3*x + 2) - 3)/16
assert_is_integral_of(sqrt(53225*x**2-66732*x+23013),
(x/2 - S(16683)/53225)*sqrt(53225*x**2 - 66732*x + 23013) +
111576969*sqrt(2129)*asinh(53225*x/10563 - S(11122)/3521)/1133160250)
assert manualintegrate(sqrt(a+c*x**2), x) == \
Piecewise((a*log(2*sqrt(c)*sqrt(a + c*x**2) + 2*c*x)/(2*sqrt(c)) + x*sqrt(a + c*x**2)/2, Ne(c, 0)),
(sqrt(a)*x, True))
assert manualintegrate(sqrt(a+b*x+c*x**2), x) == \
Piecewise(((x/2 + b/(4*c))*sqrt(a + b*x + c*x**2) +
(a/2 - b**2/(8*c))*log(b + 2*sqrt(c)*sqrt(a + b*x + c*x**2) + 2*c*x)/sqrt(c), Ne(c, 0)),
(2*(a + b*x)**(S(3)/2)/(3*b), Ne(b, 0)),
(sqrt(a)*x, True))
assert_is_integral_of(x*sqrt(x**2+2*x+4),
(x**2/3 + x/6 + S(5)/6)*sqrt(x**2 + 2*x + 4) - 3*asinh(sqrt(3)*(x + 1)/3)/2)
def test_mul_pow_derivative():
assert_is_integral_of(x*sec(x)*tan(x), x*sec(x) - log(tan(x) + sec(x)))
assert_is_integral_of(x*sec(x)**2, x*tan(x) + log(cos(x)))
assert_is_integral_of(x**3*Derivative(f(x), (x, 4)),
x**3*Derivative(f(x), (x, 3)) - 3*x**2*Derivative(f(x), (x, 2)) +
6*x*Derivative(f(x), x) - 6*f(x))
|
6006c5e589f21d58a4b9f9facc5f694a910240bfcf2115570a58bdb63bbafcb6 | # A collection of failing integrals from the issues.
from sympy.core.numbers import (I, Rational, oo, pi)
from sympy.core.singleton import S
from sympy.core.symbol import symbols
from sympy.functions.elementary.complexes import sign
from sympy.functions.elementary.exponential import (exp, log)
from sympy.functions.elementary.hyperbolic import (sech, sinh)
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.piecewise import Piecewise
from sympy.functions.elementary.trigonometric import (acos, atan, cos, sin, tan)
from sympy.functions.special.delta_functions import DiracDelta
from sympy.functions.special.gamma_functions import gamma
from sympy.integrals.integrals import (Integral, integrate)
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_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_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_11254c():
assert not integrate(sech(x)**2, (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_9101():
assert not integrate(log(x + sqrt(x**2 + y**2 + z**2)), z).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)
@XFAIL
def test_issue_20370():
a = symbols('a', positive=True)
assert integrate((1 + a * cos(x))**-1, (x, 0, 2 * pi)) == (2 * pi / sqrt(1 - a**2))
@XFAIL
def test_polylog():
# log(1/x)*log(x+1)-polylog(2, -x)
assert not integrate(log(1/x)/(x + 1), x).has(Integral)
@XFAIL
def test_polylog_manual():
# Make sure _parts_rule does not go into an infinite loop here
assert not integrate(log(1/x)/(x + 1), x, manual=True).has(Integral)
|
ad26511aa95073028d909bf08736e2a24b82375718825353215df937c36c4baa | from sympy.core.function import expand_func
from sympy.core.numbers import (I, Rational, oo, pi)
from sympy.core.singleton import S
from sympy.core.sorting import default_sort_key
from sympy.functions.elementary.complexes import Abs, arg, re, unpolarify
from sympy.functions.elementary.exponential import (exp, exp_polar, log)
from sympy.functions.elementary.hyperbolic import cosh, acosh
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.piecewise import Piecewise, piecewise_fold
from sympy.functions.elementary.trigonometric import (cos, sin, sinc, asin)
from sympy.functions.special.error_functions import (erf, erfc)
from sympy.functions.special.gamma_functions import (gamma, polygamma)
from sympy.functions.special.hyper import (hyper, meijerg)
from sympy.integrals.integrals import (Integral, integrate)
from sympy.simplify.hyperexpand import hyperexpand
from sympy.simplify.simplify import simplify
from sympy.integrals.meijerint import (_rewrite_single, _rewrite1,
meijerint_indefinite, _inflate_g, _create_lookup_table,
meijerint_definite, meijerint_inversion)
from sympy.testing.pytest import slow
from sympy.core.random import (verify_numerically,
random_complex_number as randcplx)
from sympy.abc import x, y, a, b, c, d, s, t, z
def test_rewrite_single():
def t(expr, c, m):
e = _rewrite_single(meijerg([a], [b], [c], [d], expr), x)
assert e is not None
assert isinstance(e[0][0][2], meijerg)
assert e[0][0][2].argument.as_coeff_mul(x) == (c, (m,))
def tn(expr):
assert _rewrite_single(meijerg([a], [b], [c], [d], expr), x) is None
t(x, 1, x)
t(x**2, 1, x**2)
t(x**2 + y*x**2, y + 1, x**2)
tn(x**2 + x)
tn(x**y)
def u(expr, x):
from sympy.core.add import Add
r = _rewrite_single(expr, x)
e = Add(*[res[0]*res[2] for res in r[0]]).replace(
exp_polar, exp) # XXX Hack?
assert verify_numerically(e, expr, x)
u(exp(-x)*sin(x), x)
# The following has stopped working because hyperexpand changed slightly.
# It is probably not worth fixing
#u(exp(-x)*sin(x)*cos(x), x)
# This one cannot be done numerically, since it comes out as a g-function
# of argument 4*pi
# NOTE This also tests a bug in inverse mellin transform (which used to
# turn exp(4*pi*I*t) into a factor of exp(4*pi*I)**t instead of
# exp_polar).
#u(exp(x)*sin(x), x)
assert _rewrite_single(exp(x)*sin(x), x) == \
([(-sqrt(2)/(2*sqrt(pi)), 0,
meijerg(((Rational(-1, 2), 0, Rational(1, 4), S.Half, Rational(3, 4)), (1,)),
((), (Rational(-1, 2), 0)), 64*exp_polar(-4*I*pi)/x**4))], True)
def test_rewrite1():
assert _rewrite1(x**3*meijerg([a], [b], [c], [d], x**2 + y*x**2)*5, x) == \
(5, x**3, [(1, 0, meijerg([a], [b], [c], [d], x**2*(y + 1)))], True)
def test_meijerint_indefinite_numerically():
def t(fac, arg):
g = meijerg([a], [b], [c], [d], arg)*fac
subs = {a: randcplx()/10, b: randcplx()/10 + I,
c: randcplx(), d: randcplx()}
integral = meijerint_indefinite(g, x)
assert integral is not None
assert verify_numerically(g.subs(subs), integral.diff(x).subs(subs), x)
t(1, x)
t(2, x)
t(1, 2*x)
t(1, x**2)
t(5, x**S('3/2'))
t(x**3, x)
t(3*x**S('3/2'), 4*x**S('7/3'))
def test_meijerint_definite():
v, b = meijerint_definite(x, x, 0, 0)
assert v.is_zero and b is True
v, b = meijerint_definite(x, x, oo, oo)
assert v.is_zero and b is True
def test_inflate():
subs = {a: randcplx()/10, b: randcplx()/10 + I, c: randcplx(),
d: randcplx(), y: randcplx()/10}
def t(a, b, arg, n):
from sympy.core.mul import Mul
m1 = meijerg(a, b, arg)
m2 = Mul(*_inflate_g(m1, n))
# NOTE: (the random number)**9 must still be on the principal sheet.
# Thus make b&d small to create random numbers of small imaginary part.
return verify_numerically(m1.subs(subs), m2.subs(subs), x, b=0.1, d=-0.1)
assert t([[a], [b]], [[c], [d]], x, 3)
assert t([[a, y], [b]], [[c], [d]], x, 3)
assert t([[a], [b]], [[c, y], [d]], 2*x**3, 3)
def test_recursive():
from sympy.core.symbol import symbols
a, b, c = symbols('a b c', positive=True)
r = exp(-(x - a)**2)*exp(-(x - b)**2)
e = integrate(r, (x, 0, oo), meijerg=True)
assert simplify(e.expand()) == (
sqrt(2)*sqrt(pi)*(
(erf(sqrt(2)*(a + b)/2) + 1)*exp(-a**2/2 + a*b - b**2/2))/4)
e = integrate(exp(-(x - a)**2)*exp(-(x - b)**2)*exp(c*x), (x, 0, oo), meijerg=True)
assert simplify(e) == (
sqrt(2)*sqrt(pi)*(erf(sqrt(2)*(2*a + 2*b + c)/4) + 1)*exp(-a**2 - b**2
+ (2*a + 2*b + c)**2/8)/4)
assert simplify(integrate(exp(-(x - a - b - c)**2), (x, 0, oo), meijerg=True)) == \
sqrt(pi)/2*(1 + erf(a + b + c))
assert simplify(integrate(exp(-(x + a + b + c)**2), (x, 0, oo), meijerg=True)) == \
sqrt(pi)/2*(1 - erf(a + b + c))
@slow
def test_meijerint():
from sympy.core.function import expand
from sympy.core.symbol import symbols
s, t, mu = symbols('s t mu', real=True)
assert integrate(meijerg([], [], [0], [], s*t)
*meijerg([], [], [mu/2], [-mu/2], t**2/4),
(t, 0, oo)).is_Piecewise
s = symbols('s', positive=True)
assert integrate(x**s*meijerg([[], []], [[0], []], x), (x, 0, oo)) == \
gamma(s + 1)
assert integrate(x**s*meijerg([[], []], [[0], []], x), (x, 0, oo),
meijerg=True) == gamma(s + 1)
assert isinstance(integrate(x**s*meijerg([[], []], [[0], []], x),
(x, 0, oo), meijerg=False),
Integral)
assert meijerint_indefinite(exp(x), x) == exp(x)
# TODO what simplifications should be done automatically?
# This tests "extra case" for antecedents_1.
a, b = symbols('a b', positive=True)
assert simplify(meijerint_definite(x**a, x, 0, b)[0]) == \
b**(a + 1)/(a + 1)
# This tests various conditions and expansions:
assert meijerint_definite((x + 1)**3*exp(-x), x, 0, oo) == (16, True)
# Again, how about simplifications?
sigma, mu = symbols('sigma mu', positive=True)
i, c = meijerint_definite(exp(-((x - mu)/(2*sigma))**2), x, 0, oo)
assert simplify(i) == sqrt(pi)*sigma*(2 - erfc(mu/(2*sigma)))
assert c == True
i, _ = meijerint_definite(exp(-mu*x)*exp(sigma*x), x, 0, oo)
# TODO it would be nice to test the condition
assert simplify(i) == 1/(mu - sigma)
# Test substitutions to change limits
assert meijerint_definite(exp(x), x, -oo, 2) == (exp(2), True)
# Note: causes a NaN in _check_antecedents
assert expand(meijerint_definite(exp(x), x, 0, I)[0]) == exp(I) - 1
assert expand(meijerint_definite(exp(-x), x, 0, x)[0]) == \
1 - exp(-exp(I*arg(x))*abs(x))
# Test -oo to oo
assert meijerint_definite(exp(-x**2), x, -oo, oo) == (sqrt(pi), True)
assert meijerint_definite(exp(-abs(x)), x, -oo, oo) == (2, True)
assert meijerint_definite(exp(-(2*x - 3)**2), x, -oo, oo) == \
(sqrt(pi)/2, True)
assert meijerint_definite(exp(-abs(2*x - 3)), x, -oo, oo) == (1, True)
assert meijerint_definite(exp(-((x - mu)/sigma)**2/2)/sqrt(2*pi*sigma**2),
x, -oo, oo) == (1, True)
assert meijerint_definite(sinc(x)**2, x, -oo, oo) == (pi, True)
# Test one of the extra conditions for 2 g-functinos
assert meijerint_definite(exp(-x)*sin(x), x, 0, oo) == (S.Half, True)
# Test a bug
def res(n):
return (1/(1 + x**2)).diff(x, n).subs(x, 1)*(-1)**n
for n in range(6):
assert integrate(exp(-x)*sin(x)*x**n, (x, 0, oo), meijerg=True) == \
res(n)
# This used to test trigexpand... now it is done by linear substitution
assert simplify(integrate(exp(-x)*sin(x + a), (x, 0, oo), meijerg=True)
) == sqrt(2)*sin(a + pi/4)/2
# Test the condition 14 from prudnikov.
# (This is besselj*besselj in disguise, to stop the product from being
# recognised in the tables.)
a, b, s = symbols('a b s')
assert meijerint_definite(meijerg([], [], [a/2], [-a/2], x/4)
*meijerg([], [], [b/2], [-b/2], x/4)*x**(s - 1), x, 0, oo
) == (
(4*2**(2*s - 2)*gamma(-2*s + 1)*gamma(a/2 + b/2 + s)
/(gamma(-a/2 + b/2 - s + 1)*gamma(a/2 - b/2 - s + 1)
*gamma(a/2 + b/2 - s + 1)),
(re(s) < 1) & (re(s) < S(1)/2) & (re(a)/2 + re(b)/2 + re(s) > 0)))
# test a bug
assert integrate(sin(x**a)*sin(x**b), (x, 0, oo), meijerg=True) == \
Integral(sin(x**a)*sin(x**b), (x, 0, oo))
# test better hyperexpand
assert integrate(exp(-x**2)*log(x), (x, 0, oo), meijerg=True) == \
(sqrt(pi)*polygamma(0, S.Half)/4).expand()
# Test hyperexpand bug.
from sympy.functions.special.gamma_functions import lowergamma
n = symbols('n', integer=True)
assert simplify(integrate(exp(-x)*x**n, x, meijerg=True)) == \
lowergamma(n + 1, x)
# Test a bug with argument 1/x
alpha = symbols('alpha', positive=True)
assert meijerint_definite((2 - x)**alpha*sin(alpha/x), x, 0, 2) == \
(sqrt(pi)*alpha*gamma(alpha + 1)*meijerg(((), (alpha/2 + S.Half,
alpha/2 + 1)), ((0, 0, S.Half), (Rational(-1, 2),)), alpha**2/16)/4, True)
# test a bug related to 3016
a, s = symbols('a s', positive=True)
assert simplify(integrate(x**s*exp(-a*x**2), (x, -oo, oo))) == \
a**(-s/2 - S.Half)*((-1)**s + 1)*gamma(s/2 + S.Half)/2
def test_bessel():
from sympy.functions.special.bessel import (besseli, besselj)
assert simplify(integrate(besselj(a, z)*besselj(b, z)/z, (z, 0, oo),
meijerg=True, conds='none')) == \
2*sin(pi*(a/2 - b/2))/(pi*(a - b)*(a + b))
assert simplify(integrate(besselj(a, z)*besselj(a, z)/z, (z, 0, oo),
meijerg=True, conds='none')) == 1/(2*a)
# TODO more orthogonality integrals
assert simplify(integrate(sin(z*x)*(x**2 - 1)**(-(y + S.Half)),
(x, 1, oo), meijerg=True, conds='none')
*2/((z/2)**y*sqrt(pi)*gamma(S.Half - y))) == \
besselj(y, z)
# Werner Rosenheinrich
# SOME INDEFINITE INTEGRALS OF BESSEL FUNCTIONS
assert integrate(x*besselj(0, x), x, meijerg=True) == x*besselj(1, x)
assert integrate(x*besseli(0, x), x, meijerg=True) == x*besseli(1, x)
# TODO can do higher powers, but come out as high order ... should they be
# reduced to order 0, 1?
assert integrate(besselj(1, x), x, meijerg=True) == -besselj(0, x)
assert integrate(besselj(1, x)**2/x, x, meijerg=True) == \
-(besselj(0, x)**2 + besselj(1, x)**2)/2
# TODO more besseli when tables are extended or recursive mellin works
assert integrate(besselj(0, x)**2/x**2, x, meijerg=True) == \
-2*x*besselj(0, x)**2 - 2*x*besselj(1, x)**2 \
+ 2*besselj(0, x)*besselj(1, x) - besselj(0, x)**2/x
assert integrate(besselj(0, x)*besselj(1, x), x, meijerg=True) == \
-besselj(0, x)**2/2
assert integrate(x**2*besselj(0, x)*besselj(1, x), x, meijerg=True) == \
x**2*besselj(1, x)**2/2
assert integrate(besselj(0, x)*besselj(1, x)/x, x, meijerg=True) == \
(x*besselj(0, x)**2 + x*besselj(1, x)**2 -
besselj(0, x)*besselj(1, x))
# TODO how does besselj(0, a*x)*besselj(0, b*x) work?
# TODO how does besselj(0, x)**2*besselj(1, x)**2 work?
# TODO sin(x)*besselj(0, x) etc come out a mess
# TODO can x*log(x)*besselj(0, x) be done?
# TODO how does besselj(1, x)*besselj(0, x+a) work?
# TODO more indefinite integrals when struve functions etc are implemented
# test a substitution
assert integrate(besselj(1, x**2)*x, x, meijerg=True) == \
-besselj(0, x**2)/2
def test_inversion():
from sympy.functions.special.bessel import besselj
from sympy.functions.special.delta_functions import Heaviside
def inv(f):
return piecewise_fold(meijerint_inversion(f, s, t))
assert inv(1/(s**2 + 1)) == sin(t)*Heaviside(t)
assert inv(s/(s**2 + 1)) == cos(t)*Heaviside(t)
assert inv(exp(-s)/s) == Heaviside(t - 1)
assert inv(1/sqrt(1 + s**2)) == besselj(0, t)*Heaviside(t)
# Test some antcedents checking.
assert meijerint_inversion(sqrt(s)/sqrt(1 + s**2), s, t) is None
assert inv(exp(s**2)) is None
assert meijerint_inversion(exp(-s**2), s, t) is None
def test_inversion_conditional_output():
from sympy.core.symbol import Symbol
from sympy.integrals.transforms import InverseLaplaceTransform
a = Symbol('a', positive=True)
F = sqrt(pi/a)*exp(-2*sqrt(a)*sqrt(s))
f = meijerint_inversion(F, s, t)
assert not f.is_Piecewise
b = Symbol('b', real=True)
F = F.subs(a, b)
f2 = meijerint_inversion(F, s, t)
assert f2.is_Piecewise
# first piece is same as f
assert f2.args[0][0] == f.subs(a, b)
# last piece is an unevaluated transform
assert f2.args[-1][1]
ILT = InverseLaplaceTransform(F, s, t, None)
assert f2.args[-1][0] == ILT or f2.args[-1][0] == ILT.as_integral
def test_inversion_exp_real_nonreal_shift():
from sympy.core.symbol import Symbol
from sympy.functions.special.delta_functions import DiracDelta
r = Symbol('r', real=True)
c = Symbol('c', extended_real=False)
a = 1 + 2*I
z = Symbol('z')
assert not meijerint_inversion(exp(r*s), s, t).is_Piecewise
assert meijerint_inversion(exp(a*s), s, t) is None
assert meijerint_inversion(exp(c*s), s, t) is None
f = meijerint_inversion(exp(z*s), s, t)
assert f.is_Piecewise
assert isinstance(f.args[0][0], DiracDelta)
@slow
def test_lookup_table():
from sympy.core.random import uniform, randrange
from sympy.core.add import Add
from sympy.integrals.meijerint import z as z_dummy
table = {}
_create_lookup_table(table)
for _, l in sorted(table.items()):
for formula, terms, cond, hint in sorted(l, key=default_sort_key):
subs = {}
for ai in list(formula.free_symbols) + [z_dummy]:
if hasattr(ai, 'properties') and ai.properties:
# these Wilds match positive integers
subs[ai] = randrange(1, 10)
else:
subs[ai] = uniform(1.5, 2.0)
if not isinstance(terms, list):
terms = terms(subs)
# First test that hyperexpand can do this.
expanded = [hyperexpand(g) for (_, g) in terms]
assert all(x.is_Piecewise or not x.has(meijerg) for x in expanded)
# Now test that the meijer g-function is indeed as advertised.
expanded = Add(*[f*x for (f, x) in terms])
a, b = formula.n(subs=subs), expanded.n(subs=subs)
r = min(abs(a), abs(b))
if r < 1:
assert abs(a - b).n() <= 1e-10
else:
assert (abs(a - b)/r).n() <= 1e-10
def test_branch_bug():
from sympy.functions.special.gamma_functions import lowergamma
from sympy.simplify.powsimp import powdenest
# TODO gammasimp cannot prove that the factor is unity
assert powdenest(integrate(erf(x**3), x, meijerg=True).diff(x),
polar=True) == 2*erf(x**3)*gamma(Rational(2, 3))/3/gamma(Rational(5, 3))
assert integrate(erf(x**3), x, meijerg=True) == \
2*x*erf(x**3)*gamma(Rational(2, 3))/(3*gamma(Rational(5, 3))) \
- 2*gamma(Rational(2, 3))*lowergamma(Rational(2, 3), x**6)/(3*sqrt(pi)*gamma(Rational(5, 3)))
def test_linear_subs():
from sympy.functions.special.bessel import besselj
assert integrate(sin(x - 1), x, meijerg=True) == -cos(1 - x)
assert integrate(besselj(1, x - 1), x, meijerg=True) == -besselj(0, 1 - x)
@slow
def test_probability():
# various integrals from probability theory
from sympy.core.function import expand_mul
from sympy.core.symbol import (Symbol, symbols)
from sympy.simplify.gammasimp import gammasimp
from sympy.simplify.powsimp import powsimp
mu1, mu2 = symbols('mu1 mu2', nonzero=True)
sigma1, sigma2 = symbols('sigma1 sigma2', positive=True)
rate = Symbol('lambda', positive=True)
def normal(x, mu, sigma):
return 1/sqrt(2*pi*sigma**2)*exp(-(x - mu)**2/2/sigma**2)
def exponential(x, rate):
return rate*exp(-rate*x)
assert integrate(normal(x, mu1, sigma1), (x, -oo, oo), meijerg=True) == 1
assert integrate(x*normal(x, mu1, sigma1), (x, -oo, oo), meijerg=True) == \
mu1
assert integrate(x**2*normal(x, mu1, sigma1), (x, -oo, oo), meijerg=True) \
== mu1**2 + sigma1**2
assert integrate(x**3*normal(x, mu1, sigma1), (x, -oo, oo), meijerg=True) \
== mu1**3 + 3*mu1*sigma1**2
assert integrate(normal(x, mu1, sigma1)*normal(y, mu2, sigma2),
(x, -oo, oo), (y, -oo, oo), meijerg=True) == 1
assert integrate(x*normal(x, mu1, sigma1)*normal(y, mu2, sigma2),
(x, -oo, oo), (y, -oo, oo), meijerg=True) == mu1
assert integrate(y*normal(x, mu1, sigma1)*normal(y, mu2, sigma2),
(x, -oo, oo), (y, -oo, oo), meijerg=True) == mu2
assert integrate(x*y*normal(x, mu1, sigma1)*normal(y, mu2, sigma2),
(x, -oo, oo), (y, -oo, oo), meijerg=True) == mu1*mu2
assert integrate((x + y + 1)*normal(x, mu1, sigma1)*normal(y, mu2, sigma2),
(x, -oo, oo), (y, -oo, oo), meijerg=True) == 1 + mu1 + mu2
assert integrate((x + y - 1)*normal(x, mu1, sigma1)*normal(y, mu2, sigma2),
(x, -oo, oo), (y, -oo, oo), meijerg=True) == \
-1 + mu1 + mu2
i = integrate(x**2*normal(x, mu1, sigma1)*normal(y, mu2, sigma2),
(x, -oo, oo), (y, -oo, oo), meijerg=True)
assert not i.has(Abs)
assert simplify(i) == mu1**2 + sigma1**2
assert integrate(y**2*normal(x, mu1, sigma1)*normal(y, mu2, sigma2),
(x, -oo, oo), (y, -oo, oo), meijerg=True) == \
sigma2**2 + mu2**2
assert integrate(exponential(x, rate), (x, 0, oo), meijerg=True) == 1
assert integrate(x*exponential(x, rate), (x, 0, oo), meijerg=True) == \
1/rate
assert integrate(x**2*exponential(x, rate), (x, 0, oo), meijerg=True) == \
2/rate**2
def E(expr):
res1 = integrate(expr*exponential(x, rate)*normal(y, mu1, sigma1),
(x, 0, oo), (y, -oo, oo), meijerg=True)
res2 = integrate(expr*exponential(x, rate)*normal(y, mu1, sigma1),
(y, -oo, oo), (x, 0, oo), meijerg=True)
assert expand_mul(res1) == expand_mul(res2)
return res1
assert E(1) == 1
assert E(x*y) == mu1/rate
assert E(x*y**2) == mu1**2/rate + sigma1**2/rate
ans = sigma1**2 + 1/rate**2
assert simplify(E((x + y + 1)**2) - E(x + y + 1)**2) == ans
assert simplify(E((x + y - 1)**2) - E(x + y - 1)**2) == ans
assert simplify(E((x + y)**2) - E(x + y)**2) == ans
# Beta' distribution
alpha, beta = symbols('alpha beta', positive=True)
betadist = x**(alpha - 1)*(1 + x)**(-alpha - beta)*gamma(alpha + beta) \
/gamma(alpha)/gamma(beta)
assert integrate(betadist, (x, 0, oo), meijerg=True) == 1
i = integrate(x*betadist, (x, 0, oo), meijerg=True, conds='separate')
assert (gammasimp(i[0]), i[1]) == (alpha/(beta - 1), 1 < beta)
j = integrate(x**2*betadist, (x, 0, oo), meijerg=True, conds='separate')
assert j[1] == (beta > 2)
assert gammasimp(j[0] - i[0]**2) == (alpha + beta - 1)*alpha \
/(beta - 2)/(beta - 1)**2
# Beta distribution
# NOTE: this is evaluated using antiderivatives. It also tests that
# meijerint_indefinite returns the simplest possible answer.
a, b = symbols('a b', positive=True)
betadist = x**(a - 1)*(-x + 1)**(b - 1)*gamma(a + b)/(gamma(a)*gamma(b))
assert simplify(integrate(betadist, (x, 0, 1), meijerg=True)) == 1
assert simplify(integrate(x*betadist, (x, 0, 1), meijerg=True)) == \
a/(a + b)
assert simplify(integrate(x**2*betadist, (x, 0, 1), meijerg=True)) == \
a*(a + 1)/(a + b)/(a + b + 1)
assert simplify(integrate(x**y*betadist, (x, 0, 1), meijerg=True)) == \
gamma(a + b)*gamma(a + y)/gamma(a)/gamma(a + b + y)
# Chi distribution
k = Symbol('k', integer=True, positive=True)
chi = 2**(1 - k/2)*x**(k - 1)*exp(-x**2/2)/gamma(k/2)
assert powsimp(integrate(chi, (x, 0, oo), meijerg=True)) == 1
assert simplify(integrate(x*chi, (x, 0, oo), meijerg=True)) == \
sqrt(2)*gamma((k + 1)/2)/gamma(k/2)
assert simplify(integrate(x**2*chi, (x, 0, oo), meijerg=True)) == k
# Chi^2 distribution
chisquared = 2**(-k/2)/gamma(k/2)*x**(k/2 - 1)*exp(-x/2)
assert powsimp(integrate(chisquared, (x, 0, oo), meijerg=True)) == 1
assert simplify(integrate(x*chisquared, (x, 0, oo), meijerg=True)) == k
assert simplify(integrate(x**2*chisquared, (x, 0, oo), meijerg=True)) == \
k*(k + 2)
assert gammasimp(integrate(((x - k)/sqrt(2*k))**3*chisquared, (x, 0, oo),
meijerg=True)) == 2*sqrt(2)/sqrt(k)
# Dagum distribution
a, b, p = symbols('a b p', positive=True)
# XXX (x/b)**a does not work
dagum = a*p/x*(x/b)**(a*p)/(1 + x**a/b**a)**(p + 1)
assert simplify(integrate(dagum, (x, 0, oo), meijerg=True)) == 1
# XXX conditions are a mess
arg = x*dagum
assert simplify(integrate(arg, (x, 0, oo), meijerg=True, conds='none')
) == a*b*gamma(1 - 1/a)*gamma(p + 1 + 1/a)/(
(a*p + 1)*gamma(p))
assert simplify(integrate(x*arg, (x, 0, oo), meijerg=True, conds='none')
) == a*b**2*gamma(1 - 2/a)*gamma(p + 1 + 2/a)/(
(a*p + 2)*gamma(p))
# F-distribution
d1, d2 = symbols('d1 d2', positive=True)
f = sqrt(((d1*x)**d1 * d2**d2)/(d1*x + d2)**(d1 + d2))/x \
/gamma(d1/2)/gamma(d2/2)*gamma((d1 + d2)/2)
assert simplify(integrate(f, (x, 0, oo), meijerg=True)) == 1
# TODO conditions are a mess
assert simplify(integrate(x*f, (x, 0, oo), meijerg=True, conds='none')
) == d2/(d2 - 2)
assert simplify(integrate(x**2*f, (x, 0, oo), meijerg=True, conds='none')
) == d2**2*(d1 + 2)/d1/(d2 - 4)/(d2 - 2)
# TODO gamma, rayleigh
# inverse gaussian
lamda, mu = symbols('lamda mu', positive=True)
dist = sqrt(lamda/2/pi)*x**(Rational(-3, 2))*exp(-lamda*(x - mu)**2/x/2/mu**2)
mysimp = lambda expr: simplify(expr.rewrite(exp))
assert mysimp(integrate(dist, (x, 0, oo))) == 1
assert mysimp(integrate(x*dist, (x, 0, oo))) == mu
assert mysimp(integrate((x - mu)**2*dist, (x, 0, oo))) == mu**3/lamda
assert mysimp(integrate((x - mu)**3*dist, (x, 0, oo))) == 3*mu**5/lamda**2
# Levi
c = Symbol('c', positive=True)
assert integrate(sqrt(c/2/pi)*exp(-c/2/(x - mu))/(x - mu)**S('3/2'),
(x, mu, oo)) == 1
# higher moments oo
# log-logistic
alpha, beta = symbols('alpha beta', positive=True)
distn = (beta/alpha)*x**(beta - 1)/alpha**(beta - 1)/ \
(1 + x**beta/alpha**beta)**2
# FIXME: If alpha, beta are not declared as finite the line below hangs
# after the changes in:
# https://github.com/sympy/sympy/pull/16603
assert simplify(integrate(distn, (x, 0, oo))) == 1
# NOTE the conditions are a mess, but correctly state beta > 1
assert simplify(integrate(x*distn, (x, 0, oo), conds='none')) == \
pi*alpha/beta/sin(pi/beta)
# (similar comment for conditions applies)
assert simplify(integrate(x**y*distn, (x, 0, oo), conds='none')) == \
pi*alpha**y*y/beta/sin(pi*y/beta)
# weibull
k = Symbol('k', positive=True)
n = Symbol('n', positive=True)
distn = k/lamda*(x/lamda)**(k - 1)*exp(-(x/lamda)**k)
assert simplify(integrate(distn, (x, 0, oo))) == 1
assert simplify(integrate(x**n*distn, (x, 0, oo))) == \
lamda**n*gamma(1 + n/k)
# rice distribution
from sympy.functions.special.bessel import besseli
nu, sigma = symbols('nu sigma', positive=True)
rice = x/sigma**2*exp(-(x**2 + nu**2)/2/sigma**2)*besseli(0, x*nu/sigma**2)
assert integrate(rice, (x, 0, oo), meijerg=True) == 1
# can someone verify higher moments?
# Laplace distribution
mu = Symbol('mu', real=True)
b = Symbol('b', positive=True)
laplace = exp(-abs(x - mu)/b)/2/b
assert integrate(laplace, (x, -oo, oo), meijerg=True) == 1
assert integrate(x*laplace, (x, -oo, oo), meijerg=True) == mu
assert integrate(x**2*laplace, (x, -oo, oo), meijerg=True) == \
2*b**2 + mu**2
# TODO are there other distributions supported on (-oo, oo) that we can do?
# misc tests
k = Symbol('k', positive=True)
assert gammasimp(expand_mul(integrate(log(x)*x**(k - 1)*exp(-x)/gamma(k),
(x, 0, oo)))) == polygamma(0, k)
@slow
def test_expint():
""" Test various exponential integrals. """
from sympy.core.symbol import Symbol
from sympy.functions.elementary.hyperbolic import sinh
from sympy.functions.special.error_functions import (Chi, Ci, Ei, Shi, Si, expint)
assert simplify(unpolarify(integrate(exp(-z*x)/x**y, (x, 1, oo),
meijerg=True, conds='none'
).rewrite(expint).expand(func=True))) == expint(y, z)
assert integrate(exp(-z*x)/x, (x, 1, oo), meijerg=True,
conds='none').rewrite(expint).expand() == \
expint(1, z)
assert integrate(exp(-z*x)/x**2, (x, 1, oo), meijerg=True,
conds='none').rewrite(expint).expand() == \
expint(2, z).rewrite(Ei).rewrite(expint)
assert integrate(exp(-z*x)/x**3, (x, 1, oo), meijerg=True,
conds='none').rewrite(expint).expand() == \
expint(3, z).rewrite(Ei).rewrite(expint).expand()
t = Symbol('t', positive=True)
assert integrate(-cos(x)/x, (x, t, oo), meijerg=True).expand() == Ci(t)
assert integrate(-sin(x)/x, (x, t, oo), meijerg=True).expand() == \
Si(t) - pi/2
assert integrate(sin(x)/x, (x, 0, z), meijerg=True) == Si(z)
assert integrate(sinh(x)/x, (x, 0, z), meijerg=True) == Shi(z)
assert integrate(exp(-x)/x, x, meijerg=True).expand().rewrite(expint) == \
I*pi - expint(1, x)
assert integrate(exp(-x)/x**2, x, meijerg=True).rewrite(expint).expand() \
== expint(1, x) - exp(-x)/x - I*pi
u = Symbol('u', polar=True)
assert integrate(cos(u)/u, u, meijerg=True).expand().as_independent(u)[1] \
== Ci(u)
assert integrate(cosh(u)/u, u, meijerg=True).expand().as_independent(u)[1] \
== Chi(u)
assert integrate(expint(1, x), x, meijerg=True
).rewrite(expint).expand() == x*expint(1, x) - exp(-x)
assert integrate(expint(2, x), x, meijerg=True
).rewrite(expint).expand() == \
-x**2*expint(1, x)/2 + x*exp(-x)/2 - exp(-x)/2
assert simplify(unpolarify(integrate(expint(y, x), x,
meijerg=True).rewrite(expint).expand(func=True))) == \
-expint(y + 1, x)
assert integrate(Si(x), x, meijerg=True) == x*Si(x) + cos(x)
assert integrate(Ci(u), u, meijerg=True).expand() == u*Ci(u) - sin(u)
assert integrate(Shi(x), x, meijerg=True) == x*Shi(x) - cosh(x)
assert integrate(Chi(u), u, meijerg=True).expand() == u*Chi(u) - sinh(u)
assert integrate(Si(x)*exp(-x), (x, 0, oo), meijerg=True) == pi/4
assert integrate(expint(1, x)*sin(x), (x, 0, oo), meijerg=True) == log(2)/2
def test_messy():
from sympy.functions.elementary.hyperbolic import (acosh, acoth)
from sympy.functions.elementary.trigonometric import (asin, atan)
from sympy.functions.special.bessel import besselj
from sympy.functions.special.error_functions import (Chi, E1, Shi, Si)
from sympy.integrals.transforms import (fourier_transform, laplace_transform)
assert laplace_transform(Si(x), x, s) == ((-atan(s) + pi/2)/s, 0, True)
assert laplace_transform(Shi(x), x, s) == (
acoth(s)/s, -oo, s**2 > 1)
# where should the logs be simplified?
assert laplace_transform(Chi(x), x, s) == (
(log(s**(-2)) - log(1 - 1/s**2))/(2*s), -oo, s**2 > 1)
# TODO maybe simplify the inequalities? when the simplification
# allows for generators instead of symbols this will work
assert laplace_transform(besselj(a, x), x, s)[1:] == \
(0, (re(a) > -2) & (re(a) > -1))
# NOTE s < 0 can be done, but argument reduction is not good enough yet
ans = fourier_transform(besselj(1, x)/x, x, s, noconds=False)
assert tuple([ans[0].factor(deep=True).expand(), ans[1]]) == \
(Piecewise((0, (s > 1/(2*pi)) | (s < -1/(2*pi))),
(2*sqrt(-4*pi**2*s**2 + 1), True)), s > 0)
# TODO FT(besselj(0,x)) - conditions are messy (but for acceptable reasons)
# - folding could be better
assert integrate(E1(x)*besselj(0, x), (x, 0, oo), meijerg=True) == \
log(1 + sqrt(2))
assert integrate(E1(x)*besselj(1, x), (x, 0, oo), meijerg=True) == \
log(S.Half + sqrt(2)/2)
assert integrate(1/x/sqrt(1 - x**2), x, meijerg=True) == \
Piecewise((-acosh(1/x), abs(x**(-2)) > 1), (I*asin(1/x), True))
def test_issue_6122():
assert integrate(exp(-I*x**2), (x, -oo, oo), meijerg=True) == \
-I*sqrt(pi)*exp(I*pi/4)
def test_issue_6252():
expr = 1/x/(a + b*x)**Rational(1, 3)
anti = integrate(expr, x, meijerg=True)
assert not anti.has(hyper)
# XXX the expression is a mess, but actually upon differentiation and
# putting in numerical values seems to work...
def test_issue_6348():
assert integrate(exp(I*x)/(1 + x**2), (x, -oo, oo)).simplify().rewrite(exp) \
== pi*exp(-1)
def test_fresnel():
from sympy.functions.special.error_functions import (fresnelc, fresnels)
assert expand_func(integrate(sin(pi*x**2/2), x)) == fresnels(x)
assert expand_func(integrate(cos(pi*x**2/2), x)) == fresnelc(x)
def test_issue_6860():
assert meijerint_indefinite(x**x**x, x) is None
def test_issue_7337():
f = meijerint_indefinite(x*sqrt(2*x + 3), x).together()
assert f == sqrt(2*x + 3)*(2*x**2 + x - 3)/5
assert f._eval_interval(x, S.NegativeOne, S.One) == Rational(2, 5)
def test_issue_8368():
assert meijerint_indefinite(cosh(x)*exp(-x*t), x) == (
(-t - 1)*exp(x) + (-t + 1)*exp(-x))*exp(-t*x)/2/(t**2 - 1)
def test_issue_10211():
from sympy.abc import h, w
assert integrate((1/sqrt((y-x)**2 + h**2)**3), (x,0,w), (y,0,w)) == \
2*sqrt(1 + w**2/h**2)/h - 2/h
def test_issue_11806():
from sympy.core.symbol import symbols
y, L = symbols('y L', positive=True)
assert integrate(1/sqrt(x**2 + y**2)**3, (x, -L, L)) == \
2*L/(y**2*sqrt(L**2 + y**2))
def test_issue_10681():
from sympy.polys.domains.realfield import RR
from sympy.abc import R, r
f = integrate(r**2*(R**2-r**2)**0.5, r, meijerg=True)
g = (1.0/3)*R**1.0*r**3*hyper((-0.5, Rational(3, 2)), (Rational(5, 2),),
r**2*exp_polar(2*I*pi)/R**2)
assert RR.almosteq((f/g).n(), 1.0, 1e-12)
def test_issue_13536():
from sympy.core.symbol import Symbol
a = Symbol('a', positive=True)
assert integrate(1/x**2, (x, oo, a)) == -1/a
def test_issue_6462():
from sympy.core.symbol import Symbol
x = Symbol('x')
n = Symbol('n')
# Not the actual issue, still wrong answer for n = 1, but that there is no
# exception
assert integrate(cos(x**n)/x**n, x, meijerg=True).subs(n, 2).equals(
integrate(cos(x**2)/x**2, x, meijerg=True))
def test_indefinite_1_bug():
assert integrate((b + t)**(-a), t, meijerg=True
) == -b/(b**a*(1 + t/b)**a*(a - 1)
) - t/(b**a*(1 + t/b)**a*(a - 1))
def test_pr_23583():
# This result is wrong. Check whether new result is correct when this test fail.
assert integrate(1/sqrt((x - I)**2-1), meijerg=True) == \
Piecewise((acosh(x - I), Abs((x - I)**2) > 1), (-I*asin(x - I), True))
|
5d3ebd6e0a7d0ec9a6b5c1bd1a28f6830dabe47c74ff888cc4d50e6c86a78e58 | from sympy.assumptions.refine import refine
from sympy.concrete.summations import Sum
from sympy.core.add import Add
from sympy.core.basic import Basic
from sympy.core.containers import Tuple
from sympy.core.expr import (ExprBuilder, unchanged, Expr,
UnevaluatedExpr)
from sympy.core.function import (Function, expand, WildFunction,
AppliedUndef, Derivative, diff, Subs)
from sympy.core.mul import Mul
from sympy.core.numbers import (NumberSymbol, E, zoo, oo, Float, I,
Rational, nan, Integer, Number, pi)
from sympy.core.power import Pow
from sympy.core.relational import Ge, Lt, Gt, Le
from sympy.core.singleton import S
from sympy.core.sorting import default_sort_key
from sympy.core.symbol import Symbol, symbols, Dummy, Wild
from sympy.core.sympify import sympify
from sympy.functions.combinatorial.factorials import factorial
from sympy.functions.elementary.exponential import exp_polar, exp, log
from sympy.functions.elementary.miscellaneous import sqrt, Max
from sympy.functions.elementary.piecewise import Piecewise
from sympy.functions.elementary.trigonometric import tan, sin, cos
from sympy.functions.special.delta_functions import (Heaviside,
DiracDelta)
from sympy.functions.special.error_functions import Si
from sympy.functions.special.gamma_functions import gamma
from sympy.integrals.integrals import integrate, Integral
from sympy.physics.secondquant import FockState
from sympy.polys.partfrac import apart
from sympy.polys.polytools import factor, cancel, Poly
from sympy.polys.rationaltools import together
from sympy.series.order import O
from sympy.simplify.combsimp import combsimp
from sympy.simplify.gammasimp import gammasimp
from sympy.simplify.powsimp import powsimp
from sympy.simplify.radsimp import collect, radsimp
from sympy.simplify.ratsimp import ratsimp
from sympy.simplify.simplify import simplify, nsimplify
from sympy.simplify.trigsimp import trigsimp
from sympy.tensor.indexed import Indexed
from sympy.physics.units import meter
from sympy.testing.pytest import raises, XFAIL
from sympy.abc import a, b, c, n, t, u, x, y, z
f, g, h = symbols('f,g,h', cls=Function)
class DummyNumber:
"""
Minimal implementation of a number that works with SymPy.
If one has a Number class (e.g. Sage Integer, or some other custom class)
that one wants to work well with SymPy, one has to implement at least the
methods of this class DummyNumber, resp. its subclasses I5 and F1_1.
Basically, one just needs to implement either __int__() or __float__() and
then one needs to make sure that the class works with Python integers and
with itself.
"""
def __radd__(self, a):
if isinstance(a, (int, float)):
return a + self.number
return NotImplemented
def __add__(self, a):
if isinstance(a, (int, float, DummyNumber)):
return self.number + a
return NotImplemented
def __rsub__(self, a):
if isinstance(a, (int, float)):
return a - self.number
return NotImplemented
def __sub__(self, a):
if isinstance(a, (int, float, DummyNumber)):
return self.number - a
return NotImplemented
def __rmul__(self, a):
if isinstance(a, (int, float)):
return a * self.number
return NotImplemented
def __mul__(self, a):
if isinstance(a, (int, float, DummyNumber)):
return self.number * a
return NotImplemented
def __rtruediv__(self, a):
if isinstance(a, (int, float)):
return a / self.number
return NotImplemented
def __truediv__(self, a):
if isinstance(a, (int, float, DummyNumber)):
return self.number / a
return NotImplemented
def __rpow__(self, a):
if isinstance(a, (int, float)):
return a ** self.number
return NotImplemented
def __pow__(self, a):
if isinstance(a, (int, float, DummyNumber)):
return self.number ** a
return NotImplemented
def __pos__(self):
return self.number
def __neg__(self):
return - self.number
class I5(DummyNumber):
number = 5
def __int__(self):
return self.number
class F1_1(DummyNumber):
number = 1.1
def __float__(self):
return self.number
i5 = I5()
f1_1 = F1_1()
# basic SymPy objects
basic_objs = [
Rational(2),
Float("1.3"),
x,
y,
pow(x, y)*y,
]
# all supported objects
all_objs = basic_objs + [
5,
5.5,
i5,
f1_1
]
def dotest(s):
for xo in all_objs:
for yo in all_objs:
s(xo, yo)
return True
def test_basic():
def j(a, b):
x = a
x = +a
x = -a
x = a + b
x = a - b
x = a*b
x = a/b
x = a**b
del x
assert dotest(j)
def test_ibasic():
def s(a, b):
x = a
x += b
x = a
x -= b
x = a
x *= b
x = a
x /= b
assert dotest(s)
class NonBasic:
'''This class represents an object that knows how to implement binary
operations like +, -, etc with Expr but is not a subclass of Basic itself.
The NonExpr subclass below does subclass Basic but not Expr.
For both NonBasic and NonExpr it should be possible for them to override
Expr.__add__ etc because Expr.__add__ should be returning NotImplemented
for non Expr classes. Otherwise Expr.__add__ would create meaningless
objects like Add(Integer(1), FiniteSet(2)) and it wouldn't be possible for
other classes to override these operations when interacting with Expr.
'''
def __add__(self, other):
return SpecialOp('+', self, other)
def __radd__(self, other):
return SpecialOp('+', other, self)
def __sub__(self, other):
return SpecialOp('-', self, other)
def __rsub__(self, other):
return SpecialOp('-', other, self)
def __mul__(self, other):
return SpecialOp('*', self, other)
def __rmul__(self, other):
return SpecialOp('*', other, self)
def __truediv__(self, other):
return SpecialOp('/', self, other)
def __rtruediv__(self, other):
return SpecialOp('/', other, self)
def __floordiv__(self, other):
return SpecialOp('//', self, other)
def __rfloordiv__(self, other):
return SpecialOp('//', other, self)
def __mod__(self, other):
return SpecialOp('%', self, other)
def __rmod__(self, other):
return SpecialOp('%', other, self)
def __divmod__(self, other):
return SpecialOp('divmod', self, other)
def __rdivmod__(self, other):
return SpecialOp('divmod', other, self)
def __pow__(self, other):
return SpecialOp('**', self, other)
def __rpow__(self, other):
return SpecialOp('**', other, self)
def __lt__(self, other):
return SpecialOp('<', self, other)
def __gt__(self, other):
return SpecialOp('>', self, other)
def __le__(self, other):
return SpecialOp('<=', self, other)
def __ge__(self, other):
return SpecialOp('>=', self, other)
class NonExpr(Basic, NonBasic):
'''Like NonBasic above except this is a subclass of Basic but not Expr'''
pass
class SpecialOp():
'''Represents the results of operations with NonBasic and NonExpr'''
def __new__(cls, op, arg1, arg2):
obj = object.__new__(cls)
obj.args = (op, arg1, arg2)
return obj
class NonArithmetic(Basic):
'''Represents a Basic subclass that does not support arithmetic operations'''
pass
def test_cooperative_operations():
'''Tests that Expr uses binary operations cooperatively.
In particular it should be possible for non-Expr classes to override
binary operators like +, - etc when used with Expr instances. This should
work for non-Expr classes whether they are Basic subclasses or not. Also
non-Expr classes that do not define binary operators with Expr should give
TypeError.
'''
# A bunch of instances of Expr subclasses
exprs = [
Expr(),
S.Zero,
S.One,
S.Infinity,
S.NegativeInfinity,
S.ComplexInfinity,
S.Half,
Float(0.5),
Integer(2),
Symbol('x'),
Mul(2, Symbol('x')),
Add(2, Symbol('x')),
Pow(2, Symbol('x')),
]
for e in exprs:
# Test that these classes can override arithmetic operations in
# combination with various Expr types.
for ne in [NonBasic(), NonExpr()]:
results = [
(ne + e, ('+', ne, e)),
(e + ne, ('+', e, ne)),
(ne - e, ('-', ne, e)),
(e - ne, ('-', e, ne)),
(ne * e, ('*', ne, e)),
(e * ne, ('*', e, ne)),
(ne / e, ('/', ne, e)),
(e / ne, ('/', e, ne)),
(ne // e, ('//', ne, e)),
(e // ne, ('//', e, ne)),
(ne % e, ('%', ne, e)),
(e % ne, ('%', e, ne)),
(divmod(ne, e), ('divmod', ne, e)),
(divmod(e, ne), ('divmod', e, ne)),
(ne ** e, ('**', ne, e)),
(e ** ne, ('**', e, ne)),
(e < ne, ('>', ne, e)),
(ne < e, ('<', ne, e)),
(e > ne, ('<', ne, e)),
(ne > e, ('>', ne, e)),
(e <= ne, ('>=', ne, e)),
(ne <= e, ('<=', ne, e)),
(e >= ne, ('<=', ne, e)),
(ne >= e, ('>=', ne, e)),
]
for res, args in results:
assert type(res) is SpecialOp and res.args == args
# These classes do not support binary operators with Expr. Every
# operation should raise in combination with any of the Expr types.
for na in [NonArithmetic(), object()]:
raises(TypeError, lambda : e + na)
raises(TypeError, lambda : na + e)
raises(TypeError, lambda : e - na)
raises(TypeError, lambda : na - e)
raises(TypeError, lambda : e * na)
raises(TypeError, lambda : na * e)
raises(TypeError, lambda : e / na)
raises(TypeError, lambda : na / e)
raises(TypeError, lambda : e // na)
raises(TypeError, lambda : na // e)
raises(TypeError, lambda : e % na)
raises(TypeError, lambda : na % e)
raises(TypeError, lambda : divmod(e, na))
raises(TypeError, lambda : divmod(na, e))
raises(TypeError, lambda : e ** na)
raises(TypeError, lambda : na ** e)
raises(TypeError, lambda : e > na)
raises(TypeError, lambda : na > e)
raises(TypeError, lambda : e < na)
raises(TypeError, lambda : na < e)
raises(TypeError, lambda : e >= na)
raises(TypeError, lambda : na >= e)
raises(TypeError, lambda : e <= na)
raises(TypeError, lambda : na <= e)
def test_relational():
from sympy.core.relational import Lt
assert (pi < 3) is S.false
assert (pi <= 3) is S.false
assert (pi > 3) is S.true
assert (pi >= 3) is S.true
assert (-pi < 3) is S.true
assert (-pi <= 3) is S.true
assert (-pi > 3) is S.false
assert (-pi >= 3) is S.false
r = Symbol('r', real=True)
assert (r - 2 < r - 3) is S.false
assert Lt(x + I, x + I + 2).func == Lt # issue 8288
def test_relational_assumptions():
m1 = Symbol("m1", nonnegative=False)
m2 = Symbol("m2", positive=False)
m3 = Symbol("m3", nonpositive=False)
m4 = Symbol("m4", negative=False)
assert (m1 < 0) == Lt(m1, 0)
assert (m2 <= 0) == Le(m2, 0)
assert (m3 > 0) == Gt(m3, 0)
assert (m4 >= 0) == Ge(m4, 0)
m1 = Symbol("m1", nonnegative=False, real=True)
m2 = Symbol("m2", positive=False, real=True)
m3 = Symbol("m3", nonpositive=False, real=True)
m4 = Symbol("m4", negative=False, real=True)
assert (m1 < 0) is S.true
assert (m2 <= 0) is S.true
assert (m3 > 0) is S.true
assert (m4 >= 0) is S.true
m1 = Symbol("m1", negative=True)
m2 = Symbol("m2", nonpositive=True)
m3 = Symbol("m3", positive=True)
m4 = Symbol("m4", nonnegative=True)
assert (m1 < 0) is S.true
assert (m2 <= 0) is S.true
assert (m3 > 0) is S.true
assert (m4 >= 0) is S.true
m1 = Symbol("m1", negative=False, real=True)
m2 = Symbol("m2", nonpositive=False, real=True)
m3 = Symbol("m3", positive=False, real=True)
m4 = Symbol("m4", nonnegative=False, real=True)
assert (m1 < 0) is S.false
assert (m2 <= 0) is S.false
assert (m3 > 0) is S.false
assert (m4 >= 0) is S.false
# See https://github.com/sympy/sympy/issues/17708
#def test_relational_noncommutative():
# from sympy import Lt, Gt, Le, Ge
# A, B = symbols('A,B', commutative=False)
# assert (A < B) == Lt(A, B)
# assert (A <= B) == Le(A, B)
# assert (A > B) == Gt(A, B)
# assert (A >= B) == Ge(A, B)
def test_basic_nostr():
for obj in basic_objs:
raises(TypeError, lambda: obj + '1')
raises(TypeError, lambda: obj - '1')
if obj == 2:
assert obj * '1' == '11'
else:
raises(TypeError, lambda: obj * '1')
raises(TypeError, lambda: obj / '1')
raises(TypeError, lambda: obj ** '1')
def test_series_expansion_for_uniform_order():
assert (1/x + y + x).series(x, 0, 0) == 1/x + O(1, x)
assert (1/x + y + x).series(x, 0, 1) == 1/x + y + O(x)
assert (1/x + 1 + x).series(x, 0, 0) == 1/x + O(1, x)
assert (1/x + 1 + x).series(x, 0, 1) == 1/x + 1 + O(x)
assert (1/x + x).series(x, 0, 0) == 1/x + O(1, x)
assert (1/x + y + y*x + x).series(x, 0, 0) == 1/x + O(1, x)
assert (1/x + y + y*x + x).series(x, 0, 1) == 1/x + y + O(x)
def test_leadterm():
assert (3 + 2*x**(log(3)/log(2) - 1)).leadterm(x) == (3, 0)
assert (1/x**2 + 1 + x + x**2).leadterm(x)[1] == -2
assert (1/x + 1 + x + x**2).leadterm(x)[1] == -1
assert (x**2 + 1/x).leadterm(x)[1] == -1
assert (1 + x**2).leadterm(x)[1] == 0
assert (x + 1).leadterm(x)[1] == 0
assert (x + x**2).leadterm(x)[1] == 1
assert (x**2).leadterm(x)[1] == 2
def test_as_leading_term():
assert (3 + 2*x**(log(3)/log(2) - 1)).as_leading_term(x) == 3
assert (1/x**2 + 1 + x + x**2).as_leading_term(x) == 1/x**2
assert (1/x + 1 + x + x**2).as_leading_term(x) == 1/x
assert (x**2 + 1/x).as_leading_term(x) == 1/x
assert (1 + x**2).as_leading_term(x) == 1
assert (x + 1).as_leading_term(x) == 1
assert (x + x**2).as_leading_term(x) == x
assert (x**2).as_leading_term(x) == x**2
assert (x + oo).as_leading_term(x) is oo
raises(ValueError, lambda: (x + 1).as_leading_term(1))
# https://github.com/sympy/sympy/issues/21177
e = -3*x + (x + Rational(3, 2) - sqrt(3)*S.ImaginaryUnit/2)**2\
- Rational(3, 2) + 3*sqrt(3)*S.ImaginaryUnit/2
assert e.as_leading_term(x) == \
(12*sqrt(3)*x - 12*S.ImaginaryUnit*x)/(4*sqrt(3) + 12*S.ImaginaryUnit)
# https://github.com/sympy/sympy/issues/21245
e = 1 - x - x**2
d = (1 + sqrt(5))/2
assert e.subs(x, y + 1/d).as_leading_term(y) == \
(-576*sqrt(5)*y - 1280*y)/(256*sqrt(5) + 576)
def test_leadterm2():
assert (x*cos(1)*cos(1 + sin(1)) + sin(1 + sin(1))).leadterm(x) == \
(sin(1 + sin(1)), 0)
def test_leadterm3():
assert (y + z + x).leadterm(x) == (y + z, 0)
def test_as_leading_term2():
assert (x*cos(1)*cos(1 + sin(1)) + sin(1 + sin(1))).as_leading_term(x) == \
sin(1 + sin(1))
def test_as_leading_term3():
assert (2 + pi + x).as_leading_term(x) == 2 + pi
assert (2*x + pi*x + x**2).as_leading_term(x) == 2*x + pi*x
def test_as_leading_term4():
# see issue 6843
n = Symbol('n', integer=True, positive=True)
r = -n**3/(2*n**2 + 4*n + 2) - n**2/(n**2 + 2*n + 1) + \
n**2/(n + 1) - n/(2*n**2 + 4*n + 2) + n/(n*x + x) + 2*n/(n + 1) - \
1 + 1/(n*x + x) + 1/(n + 1) - 1/x
assert r.as_leading_term(x).cancel() == n/2
def test_as_leading_term_stub():
class foo(Function):
pass
assert foo(1/x).as_leading_term(x) == foo(1/x)
assert foo(1).as_leading_term(x) == foo(1)
raises(NotImplementedError, lambda: foo(x).as_leading_term(x))
def test_as_leading_term_deriv_integral():
# related to issue 11313
assert Derivative(x ** 3, x).as_leading_term(x) == 3*x**2
assert Derivative(x ** 3, y).as_leading_term(x) == 0
assert Integral(x ** 3, x).as_leading_term(x) == x**4/4
assert Integral(x ** 3, y).as_leading_term(x) == y*x**3
assert Derivative(exp(x), x).as_leading_term(x) == 1
assert Derivative(log(x), x).as_leading_term(x) == (1/x).as_leading_term(x)
def test_atoms():
assert x.atoms() == {x}
assert (1 + x).atoms() == {x, S.One}
assert (1 + 2*cos(x)).atoms(Symbol) == {x}
assert (1 + 2*cos(x)).atoms(Symbol, Number) == {S.One, S(2), x}
assert (2*(x**(y**x))).atoms() == {S(2), x, y}
assert S.Half.atoms() == {S.Half}
assert S.Half.atoms(Symbol) == set()
assert sin(oo).atoms(oo) == set()
assert Poly(0, x).atoms() == {S.Zero, x}
assert Poly(1, x).atoms() == {S.One, x}
assert Poly(x, x).atoms() == {x}
assert Poly(x, x, y).atoms() == {x, y}
assert Poly(x + y, x, y).atoms() == {x, y}
assert Poly(x + y, x, y, z).atoms() == {x, y, z}
assert Poly(x + y*t, x, y, z).atoms() == {t, x, y, z}
assert (I*pi).atoms(NumberSymbol) == {pi}
assert (I*pi).atoms(NumberSymbol, I) == \
(I*pi).atoms(I, NumberSymbol) == {pi, I}
assert exp(exp(x)).atoms(exp) == {exp(exp(x)), exp(x)}
assert (1 + x*(2 + y) + exp(3 + z)).atoms(Add) == \
{1 + x*(2 + y) + exp(3 + z), 2 + y, 3 + z}
# issue 6132
e = (f(x) + sin(x) + 2)
assert e.atoms(AppliedUndef) == \
{f(x)}
assert e.atoms(AppliedUndef, Function) == \
{f(x), sin(x)}
assert e.atoms(Function) == \
{f(x), sin(x)}
assert e.atoms(AppliedUndef, Number) == \
{f(x), S(2)}
assert e.atoms(Function, Number) == \
{S(2), sin(x), f(x)}
def test_is_polynomial():
k = Symbol('k', nonnegative=True, integer=True)
assert Rational(2).is_polynomial(x, y, z) is True
assert (S.Pi).is_polynomial(x, y, z) is True
assert x.is_polynomial(x) is True
assert x.is_polynomial(y) is True
assert (x**2).is_polynomial(x) is True
assert (x**2).is_polynomial(y) is True
assert (x**(-2)).is_polynomial(x) is False
assert (x**(-2)).is_polynomial(y) is True
assert (2**x).is_polynomial(x) is False
assert (2**x).is_polynomial(y) is True
assert (x**k).is_polynomial(x) is False
assert (x**k).is_polynomial(k) is False
assert (x**x).is_polynomial(x) is False
assert (k**k).is_polynomial(k) is False
assert (k**x).is_polynomial(k) is False
assert (x**(-k)).is_polynomial(x) is False
assert ((2*x)**k).is_polynomial(x) is False
assert (x**2 + 3*x - 8).is_polynomial(x) is True
assert (x**2 + 3*x - 8).is_polynomial(y) is True
assert (x**2 + 3*x - 8).is_polynomial() is True
assert sqrt(x).is_polynomial(x) is False
assert (sqrt(x)**3).is_polynomial(x) is False
assert (x**2 + 3*x*sqrt(y) - 8).is_polynomial(x) is True
assert (x**2 + 3*x*sqrt(y) - 8).is_polynomial(y) is False
assert ((x**2)*(y**2) + x*(y**2) + y*x + exp(2)).is_polynomial() is True
assert ((x**2)*(y**2) + x*(y**2) + y*x + exp(x)).is_polynomial() is False
assert (
(x**2)*(y**2) + x*(y**2) + y*x + exp(2)).is_polynomial(x, y) is True
assert (
(x**2)*(y**2) + x*(y**2) + y*x + exp(x)).is_polynomial(x, y) is False
assert (1/f(x) + 1).is_polynomial(f(x)) is False
def test_is_rational_function():
assert Integer(1).is_rational_function() is True
assert Integer(1).is_rational_function(x) is True
assert Rational(17, 54).is_rational_function() is True
assert Rational(17, 54).is_rational_function(x) is True
assert (12/x).is_rational_function() is True
assert (12/x).is_rational_function(x) is True
assert (x/y).is_rational_function() is True
assert (x/y).is_rational_function(x) is True
assert (x/y).is_rational_function(x, y) is True
assert (x**2 + 1/x/y).is_rational_function() is True
assert (x**2 + 1/x/y).is_rational_function(x) is True
assert (x**2 + 1/x/y).is_rational_function(x, y) is True
assert (sin(y)/x).is_rational_function() is False
assert (sin(y)/x).is_rational_function(y) is False
assert (sin(y)/x).is_rational_function(x) is True
assert (sin(y)/x).is_rational_function(x, y) is False
assert (S.NaN).is_rational_function() is False
assert (S.Infinity).is_rational_function() is False
assert (S.NegativeInfinity).is_rational_function() is False
assert (S.ComplexInfinity).is_rational_function() is False
def test_is_meromorphic():
f = a/x**2 + b + x + c*x**2
assert f.is_meromorphic(x, 0) is True
assert f.is_meromorphic(x, 1) is True
assert f.is_meromorphic(x, zoo) is True
g = 3 + 2*x**(log(3)/log(2) - 1)
assert g.is_meromorphic(x, 0) is False
assert g.is_meromorphic(x, 1) is True
assert g.is_meromorphic(x, zoo) is False
n = Symbol('n', integer=True)
e = sin(1/x)**n*x
assert e.is_meromorphic(x, 0) is False
assert e.is_meromorphic(x, 1) is True
assert e.is_meromorphic(x, zoo) is False
e = log(x)**pi
assert e.is_meromorphic(x, 0) is False
assert e.is_meromorphic(x, 1) is False
assert e.is_meromorphic(x, 2) is True
assert e.is_meromorphic(x, zoo) is False
assert (log(x)**a).is_meromorphic(x, 0) is False
assert (log(x)**a).is_meromorphic(x, 1) is False
assert (a**log(x)).is_meromorphic(x, 0) is None
assert (3**log(x)).is_meromorphic(x, 0) is False
assert (3**log(x)).is_meromorphic(x, 1) is True
def test_is_algebraic_expr():
assert sqrt(3).is_algebraic_expr(x) is True
assert sqrt(3).is_algebraic_expr() is True
eq = ((1 + x**2)/(1 - y**2))**(S.One/3)
assert eq.is_algebraic_expr(x) is True
assert eq.is_algebraic_expr(y) is True
assert (sqrt(x) + y**(S(2)/3)).is_algebraic_expr(x) is True
assert (sqrt(x) + y**(S(2)/3)).is_algebraic_expr(y) is True
assert (sqrt(x) + y**(S(2)/3)).is_algebraic_expr() is True
assert (cos(y)/sqrt(x)).is_algebraic_expr() is False
assert (cos(y)/sqrt(x)).is_algebraic_expr(x) is True
assert (cos(y)/sqrt(x)).is_algebraic_expr(y) is False
assert (cos(y)/sqrt(x)).is_algebraic_expr(x, y) is False
def test_SAGE1():
#see https://github.com/sympy/sympy/issues/3346
class MyInt:
def _sympy_(self):
return Integer(5)
m = MyInt()
e = Rational(2)*m
assert e == 10
raises(TypeError, lambda: Rational(2)*MyInt)
def test_SAGE2():
class MyInt:
def __int__(self):
return 5
assert sympify(MyInt()) == 5
e = Rational(2)*MyInt()
assert e == 10
raises(TypeError, lambda: Rational(2)*MyInt)
def test_SAGE3():
class MySymbol:
def __rmul__(self, other):
return ('mys', other, self)
o = MySymbol()
e = x*o
assert e == ('mys', x, o)
def test_len():
e = x*y
assert len(e.args) == 2
e = x + y + z
assert len(e.args) == 3
def test_doit():
a = Integral(x**2, x)
assert isinstance(a.doit(), Integral) is False
assert isinstance(a.doit(integrals=True), Integral) is False
assert isinstance(a.doit(integrals=False), Integral) is True
assert (2*Integral(x, x)).doit() == x**2
def test_attribute_error():
raises(AttributeError, lambda: x.cos())
raises(AttributeError, lambda: x.sin())
raises(AttributeError, lambda: x.exp())
def test_args():
assert (x*y).args in ((x, y), (y, x))
assert (x + y).args in ((x, y), (y, x))
assert (x*y + 1).args in ((x*y, 1), (1, x*y))
assert sin(x*y).args == (x*y,)
assert sin(x*y).args[0] == x*y
assert (x**y).args == (x, y)
assert (x**y).args[0] == x
assert (x**y).args[1] == y
def test_noncommutative_expand_issue_3757():
A, B, C = symbols('A,B,C', commutative=False)
assert A*B - B*A != 0
assert (A*(A + B)*B).expand() == A**2*B + A*B**2
assert (A*(A + B + C)*B).expand() == A**2*B + A*B**2 + A*C*B
def test_as_numer_denom():
a, b, c = symbols('a, b, c')
assert nan.as_numer_denom() == (nan, 1)
assert oo.as_numer_denom() == (oo, 1)
assert (-oo).as_numer_denom() == (-oo, 1)
assert zoo.as_numer_denom() == (zoo, 1)
assert (-zoo).as_numer_denom() == (zoo, 1)
assert x.as_numer_denom() == (x, 1)
assert (1/x).as_numer_denom() == (1, x)
assert (x/y).as_numer_denom() == (x, y)
assert (x/2).as_numer_denom() == (x, 2)
assert (x*y/z).as_numer_denom() == (x*y, z)
assert (x/(y*z)).as_numer_denom() == (x, y*z)
assert S.Half.as_numer_denom() == (1, 2)
assert (1/y**2).as_numer_denom() == (1, y**2)
assert (x/y**2).as_numer_denom() == (x, y**2)
assert ((x**2 + 1)/y).as_numer_denom() == (x**2 + 1, y)
assert (x*(y + 1)/y**7).as_numer_denom() == (x*(y + 1), y**7)
assert (x**-2).as_numer_denom() == (1, x**2)
assert (a/x + b/2/x + c/3/x).as_numer_denom() == \
(6*a + 3*b + 2*c, 6*x)
assert (a/x + b/2/x + c/3/y).as_numer_denom() == \
(2*c*x + y*(6*a + 3*b), 6*x*y)
assert (a/x + b/2/x + c/.5/x).as_numer_denom() == \
(2*a + b + 4.0*c, 2*x)
# this should take no more than a few seconds
assert int(log(Add(*[Dummy()/i/x for i in range(1, 705)]
).as_numer_denom()[1]/x).n(4)) == 705
for i in [S.Infinity, S.NegativeInfinity, S.ComplexInfinity]:
assert (i + x/3).as_numer_denom() == \
(x + i, 3)
assert (S.Infinity + x/3 + y/4).as_numer_denom() == \
(4*x + 3*y + S.Infinity, 12)
assert (oo*x + zoo*y).as_numer_denom() == \
(zoo*y + oo*x, 1)
A, B, C = symbols('A,B,C', commutative=False)
assert (A*B*C**-1).as_numer_denom() == (A*B*C**-1, 1)
assert (A*B*C**-1/x).as_numer_denom() == (A*B*C**-1, x)
assert (C**-1*A*B).as_numer_denom() == (C**-1*A*B, 1)
assert (C**-1*A*B/x).as_numer_denom() == (C**-1*A*B, x)
assert ((A*B*C)**-1).as_numer_denom() == ((A*B*C)**-1, 1)
assert ((A*B*C)**-1/x).as_numer_denom() == ((A*B*C)**-1, x)
# the following morphs from Add to Mul during processing
assert Add(0, (x + y)/z/-2, evaluate=False).as_numer_denom(
) == (-x - y, 2*z)
def test_trunc():
import math
x, y = symbols('x y')
assert math.trunc(2) == 2
assert math.trunc(4.57) == 4
assert math.trunc(-5.79) == -5
assert math.trunc(pi) == 3
assert math.trunc(log(7)) == 1
assert math.trunc(exp(5)) == 148
assert math.trunc(cos(pi)) == -1
assert math.trunc(sin(5)) == 0
raises(TypeError, lambda: math.trunc(x))
raises(TypeError, lambda: math.trunc(x + y**2))
raises(TypeError, lambda: math.trunc(oo))
def test_as_independent():
assert S.Zero.as_independent(x, as_Add=True) == (0, 0)
assert S.Zero.as_independent(x, as_Add=False) == (0, 0)
assert (2*x*sin(x) + y + x).as_independent(x) == (y, x + 2*x*sin(x))
assert (2*x*sin(x) + y + x).as_independent(y) == (x + 2*x*sin(x), y)
assert (2*x*sin(x) + y + x).as_independent(x, y) == (0, y + x + 2*x*sin(x))
assert (x*sin(x)*cos(y)).as_independent(x) == (cos(y), x*sin(x))
assert (x*sin(x)*cos(y)).as_independent(y) == (x*sin(x), cos(y))
assert (x*sin(x)*cos(y)).as_independent(x, y) == (1, x*sin(x)*cos(y))
assert (sin(x)).as_independent(x) == (1, sin(x))
assert (sin(x)).as_independent(y) == (sin(x), 1)
assert (2*sin(x)).as_independent(x) == (2, sin(x))
assert (2*sin(x)).as_independent(y) == (2*sin(x), 1)
# issue 4903 = 1766b
n1, n2, n3 = symbols('n1 n2 n3', commutative=False)
assert (n1 + n1*n2).as_independent(n2) == (n1, n1*n2)
assert (n2*n1 + n1*n2).as_independent(n2) == (0, n1*n2 + n2*n1)
assert (n1*n2*n1).as_independent(n2) == (n1, n2*n1)
assert (n1*n2*n1).as_independent(n1) == (1, n1*n2*n1)
assert (3*x).as_independent(x, as_Add=True) == (0, 3*x)
assert (3*x).as_independent(x, as_Add=False) == (3, x)
assert (3 + x).as_independent(x, as_Add=True) == (3, x)
assert (3 + x).as_independent(x, as_Add=False) == (1, 3 + x)
# issue 5479
assert (3*x).as_independent(Symbol) == (3, x)
# issue 5648
assert (n1*x*y).as_independent(x) == (n1*y, x)
assert ((x + n1)*(x - y)).as_independent(x) == (1, (x + n1)*(x - y))
assert ((x + n1)*(x - y)).as_independent(y) == (x + n1, x - y)
assert (DiracDelta(x - n1)*DiracDelta(x - y)).as_independent(x) \
== (1, DiracDelta(x - n1)*DiracDelta(x - y))
assert (x*y*n1*n2*n3).as_independent(n2) == (x*y*n1, n2*n3)
assert (x*y*n1*n2*n3).as_independent(n1) == (x*y, n1*n2*n3)
assert (x*y*n1*n2*n3).as_independent(n3) == (x*y*n1*n2, n3)
assert (DiracDelta(x - n1)*DiracDelta(y - n1)*DiracDelta(x - n2)).as_independent(y) == \
(DiracDelta(x - n1)*DiracDelta(x - n2), DiracDelta(y - n1))
# issue 5784
assert (x + Integral(x, (x, 1, 2))).as_independent(x, strict=True) == \
(Integral(x, (x, 1, 2)), x)
eq = Add(x, -x, 2, -3, evaluate=False)
assert eq.as_independent(x) == (-1, Add(x, -x, evaluate=False))
eq = Mul(x, 1/x, 2, -3, evaluate=False)
assert eq.as_independent(x) == (-6, Mul(x, 1/x, evaluate=False))
assert (x*y).as_independent(z, as_Add=True) == (x*y, 0)
@XFAIL
def test_call_2():
# TODO UndefinedFunction does not subclass Expr
assert (2*f)(x) == 2*f(x)
def test_replace():
e = log(sin(x)) + tan(sin(x**2))
assert e.replace(sin, cos) == log(cos(x)) + tan(cos(x**2))
assert e.replace(
sin, lambda a: sin(2*a)) == log(sin(2*x)) + tan(sin(2*x**2))
a = Wild('a')
b = Wild('b')
assert e.replace(sin(a), cos(a)) == log(cos(x)) + tan(cos(x**2))
assert e.replace(
sin(a), lambda a: sin(2*a)) == log(sin(2*x)) + tan(sin(2*x**2))
# test exact
assert (2*x).replace(a*x + b, b - a, exact=True) == 2*x
assert (2*x).replace(a*x + b, b - a) == 2*x
assert (2*x).replace(a*x + b, b - a, exact=False) == 2/x
assert (2*x).replace(a*x + b, lambda a, b: b - a, exact=True) == 2*x
assert (2*x).replace(a*x + b, lambda a, b: b - a) == 2*x
assert (2*x).replace(a*x + b, lambda a, b: b - a, exact=False) == 2/x
g = 2*sin(x**3)
assert g.replace(
lambda expr: expr.is_Number, lambda expr: expr**2) == 4*sin(x**9)
assert cos(x).replace(cos, sin, map=True) == (sin(x), {cos(x): sin(x)})
assert sin(x).replace(cos, sin) == sin(x)
cond, func = lambda x: x.is_Mul, lambda x: 2*x
assert (x*y).replace(cond, func, map=True) == (2*x*y, {x*y: 2*x*y})
assert (x*(1 + x*y)).replace(cond, func, map=True) == \
(2*x*(2*x*y + 1), {x*(2*x*y + 1): 2*x*(2*x*y + 1), x*y: 2*x*y})
assert (y*sin(x)).replace(sin, lambda expr: sin(expr)/y, map=True) == \
(sin(x), {sin(x): sin(x)/y})
# if not simultaneous then y*sin(x) -> y*sin(x)/y = sin(x) -> sin(x)/y
assert (y*sin(x)).replace(sin, lambda expr: sin(expr)/y,
simultaneous=False) == sin(x)/y
assert (x**2 + O(x**3)).replace(Pow, lambda b, e: b**e/e
) == x**2/2 + O(x**3)
assert (x**2 + O(x**3)).replace(Pow, lambda b, e: b**e/e,
simultaneous=False) == x**2/2 + O(x**3)
assert (x*(x*y + 3)).replace(lambda x: x.is_Mul, lambda x: 2 + x) == \
x*(x*y + 5) + 2
e = (x*y + 1)*(2*x*y + 1) + 1
assert e.replace(cond, func, map=True) == (
2*((2*x*y + 1)*(4*x*y + 1)) + 1,
{2*x*y: 4*x*y, x*y: 2*x*y, (2*x*y + 1)*(4*x*y + 1):
2*((2*x*y + 1)*(4*x*y + 1))})
assert x.replace(x, y) == y
assert (x + 1).replace(1, 2) == x + 2
# https://groups.google.com/forum/#!topic/sympy/8wCgeC95tz0
n1, n2, n3 = symbols('n1:4', commutative=False)
assert (n1*f(n2)).replace(f, lambda x: x) == n1*n2
assert (n3*f(n2)).replace(f, lambda x: x) == n3*n2
# issue 16725
assert S.Zero.replace(Wild('x'), 1) == 1
# let the user override the default decision of False
assert S.Zero.replace(Wild('x'), 1, exact=True) == 0
def test_find():
expr = (x + y + 2 + sin(3*x))
assert expr.find(lambda u: u.is_Integer) == {S(2), S(3)}
assert expr.find(lambda u: u.is_Symbol) == {x, y}
assert expr.find(lambda u: u.is_Integer, group=True) == {S(2): 1, S(3): 1}
assert expr.find(lambda u: u.is_Symbol, group=True) == {x: 2, y: 1}
assert expr.find(Integer) == {S(2), S(3)}
assert expr.find(Symbol) == {x, y}
assert expr.find(Integer, group=True) == {S(2): 1, S(3): 1}
assert expr.find(Symbol, group=True) == {x: 2, y: 1}
a = Wild('a')
expr = sin(sin(x)) + sin(x) + cos(x) + x
assert expr.find(lambda u: type(u) is sin) == {sin(x), sin(sin(x))}
assert expr.find(
lambda u: type(u) is sin, group=True) == {sin(x): 2, sin(sin(x)): 1}
assert expr.find(sin(a)) == {sin(x), sin(sin(x))}
assert expr.find(sin(a), group=True) == {sin(x): 2, sin(sin(x)): 1}
assert expr.find(sin) == {sin(x), sin(sin(x))}
assert expr.find(sin, group=True) == {sin(x): 2, sin(sin(x)): 1}
def test_count():
expr = (x + y + 2 + sin(3*x))
assert expr.count(lambda u: u.is_Integer) == 2
assert expr.count(lambda u: u.is_Symbol) == 3
assert expr.count(Integer) == 2
assert expr.count(Symbol) == 3
assert expr.count(2) == 1
a = Wild('a')
assert expr.count(sin) == 1
assert expr.count(sin(a)) == 1
assert expr.count(lambda u: type(u) is sin) == 1
assert f(x).count(f(x)) == 1
assert f(x).diff(x).count(f(x)) == 1
assert f(x).diff(x).count(x) == 2
def test_has_basics():
p = Wild('p')
assert sin(x).has(x)
assert sin(x).has(sin)
assert not sin(x).has(y)
assert not sin(x).has(cos)
assert f(x).has(x)
assert f(x).has(f)
assert not f(x).has(y)
assert not f(x).has(g)
assert f(x).diff(x).has(x)
assert f(x).diff(x).has(f)
assert f(x).diff(x).has(Derivative)
assert not f(x).diff(x).has(y)
assert not f(x).diff(x).has(g)
assert not f(x).diff(x).has(sin)
assert (x**2).has(Symbol)
assert not (x**2).has(Wild)
assert (2*p).has(Wild)
assert not x.has()
def test_has_multiple():
f = x**2*y + sin(2**t + log(z))
assert f.has(x)
assert f.has(y)
assert f.has(z)
assert f.has(t)
assert not f.has(u)
assert f.has(x, y, z, t)
assert f.has(x, y, z, t, u)
i = Integer(4400)
assert not i.has(x)
assert (i*x**i).has(x)
assert not (i*y**i).has(x)
assert (i*y**i).has(x, y)
assert not (i*y**i).has(x, z)
def test_has_piecewise():
f = (x*y + 3/y)**(3 + 2)
p = Piecewise((g(x), x < -1), (1, x <= 1), (f, True))
assert p.has(x)
assert p.has(y)
assert not p.has(z)
assert p.has(1)
assert p.has(3)
assert not p.has(4)
assert p.has(f)
assert p.has(g)
assert not p.has(h)
def test_has_iterative():
A, B, C = symbols('A,B,C', commutative=False)
f = x*gamma(x)*sin(x)*exp(x*y)*A*B*C*cos(x*A*B)
assert f.has(x)
assert f.has(x*y)
assert f.has(x*sin(x))
assert not f.has(x*sin(y))
assert f.has(x*A)
assert f.has(x*A*B)
assert not f.has(x*A*C)
assert f.has(x*A*B*C)
assert not f.has(x*A*C*B)
assert f.has(x*sin(x)*A*B*C)
assert not f.has(x*sin(x)*A*C*B)
assert not f.has(x*sin(y)*A*B*C)
assert f.has(x*gamma(x))
assert not f.has(x + sin(x))
assert (x & y & z).has(x & z)
def test_has_integrals():
f = Integral(x**2 + sin(x*y*z), (x, 0, x + y + z))
assert f.has(x + y)
assert f.has(x + z)
assert f.has(y + z)
assert f.has(x*y)
assert f.has(x*z)
assert f.has(y*z)
assert not f.has(2*x + y)
assert not f.has(2*x*y)
def test_has_tuple():
assert Tuple(x, y).has(x)
assert not Tuple(x, y).has(z)
assert Tuple(f(x), g(x)).has(x)
assert not Tuple(f(x), g(x)).has(y)
assert Tuple(f(x), g(x)).has(f)
assert Tuple(f(x), g(x)).has(f(x))
# XXX to be deprecated
#assert not Tuple(f, g).has(x)
#assert Tuple(f, g).has(f)
#assert not Tuple(f, g).has(h)
assert Tuple(True).has(True)
assert Tuple(True).has(S.true)
assert not Tuple(True).has(1)
def test_has_units():
from sympy.physics.units import m, s
assert (x*m/s).has(x)
assert (x*m/s).has(y, z) is False
def test_has_polys():
poly = Poly(x**2 + x*y*sin(z), x, y, t)
assert poly.has(x)
assert poly.has(x, y, z)
assert poly.has(x, y, z, t)
def test_has_physics():
assert FockState((x, y)).has(x)
def test_as_poly_as_expr():
f = x**2 + 2*x*y
assert f.as_poly().as_expr() == f
assert f.as_poly(x, y).as_expr() == f
assert (f + sin(x)).as_poly(x, y) is None
p = Poly(f, x, y)
assert p.as_poly() == p
# https://github.com/sympy/sympy/issues/20610
assert S(2).as_poly() is None
assert sqrt(2).as_poly(extension=True) is None
raises(AttributeError, lambda: Tuple(x, x).as_poly(x))
raises(AttributeError, lambda: Tuple(x ** 2, x, y).as_poly(x))
def test_nonzero():
assert bool(S.Zero) is False
assert bool(S.One) is True
assert bool(x) is True
assert bool(x + y) is True
assert bool(x - x) is False
assert bool(x*y) is True
assert bool(x*1) is True
assert bool(x*0) is False
def test_is_number():
assert Float(3.14).is_number is True
assert Integer(737).is_number is True
assert Rational(3, 2).is_number is True
assert Rational(8).is_number is True
assert x.is_number is False
assert (2*x).is_number is False
assert (x + y).is_number is False
assert log(2).is_number is True
assert log(x).is_number is False
assert (2 + log(2)).is_number is True
assert (8 + log(2)).is_number is True
assert (2 + log(x)).is_number is False
assert (8 + log(2) + x).is_number is False
assert (1 + x**2/x - x).is_number is True
assert Tuple(Integer(1)).is_number is False
assert Add(2, x).is_number is False
assert Mul(3, 4).is_number is True
assert Pow(log(2), 2).is_number is True
assert oo.is_number is True
g = WildFunction('g')
assert g.is_number is False
assert (2*g).is_number is False
assert (x**2).subs(x, 3).is_number is True
# test extensibility of .is_number
# on subinstances of Basic
class A(Basic):
pass
a = A()
assert a.is_number is False
def test_as_coeff_add():
assert S(2).as_coeff_add() == (2, ())
assert S(3.0).as_coeff_add() == (0, (S(3.0),))
assert S(-3.0).as_coeff_add() == (0, (S(-3.0),))
assert x.as_coeff_add() == (0, (x,))
assert (x - 1).as_coeff_add() == (-1, (x,))
assert (x + 1).as_coeff_add() == (1, (x,))
assert (x + 2).as_coeff_add() == (2, (x,))
assert (x + y).as_coeff_add(y) == (x, (y,))
assert (3*x).as_coeff_add(y) == (3*x, ())
# don't do expansion
e = (x + y)**2
assert e.as_coeff_add(y) == (0, (e,))
def test_as_coeff_mul():
assert S(2).as_coeff_mul() == (2, ())
assert S(3.0).as_coeff_mul() == (1, (S(3.0),))
assert S(-3.0).as_coeff_mul() == (-1, (S(3.0),))
assert S(-3.0).as_coeff_mul(rational=False) == (-S(3.0), ())
assert x.as_coeff_mul() == (1, (x,))
assert (-x).as_coeff_mul() == (-1, (x,))
assert (2*x).as_coeff_mul() == (2, (x,))
assert (x*y).as_coeff_mul(y) == (x, (y,))
assert (3 + x).as_coeff_mul() == (1, (3 + x,))
assert (3 + x).as_coeff_mul(y) == (3 + x, ())
# don't do expansion
e = exp(x + y)
assert e.as_coeff_mul(y) == (1, (e,))
e = 2**(x + y)
assert e.as_coeff_mul(y) == (1, (e,))
assert (1.1*x).as_coeff_mul(rational=False) == (1.1, (x,))
assert (1.1*x).as_coeff_mul() == (1, (1.1, x))
assert (-oo*x).as_coeff_mul(rational=True) == (-1, (oo, x))
def test_as_coeff_exponent():
assert (3*x**4).as_coeff_exponent(x) == (3, 4)
assert (2*x**3).as_coeff_exponent(x) == (2, 3)
assert (4*x**2).as_coeff_exponent(x) == (4, 2)
assert (6*x**1).as_coeff_exponent(x) == (6, 1)
assert (3*x**0).as_coeff_exponent(x) == (3, 0)
assert (2*x**0).as_coeff_exponent(x) == (2, 0)
assert (1*x**0).as_coeff_exponent(x) == (1, 0)
assert (0*x**0).as_coeff_exponent(x) == (0, 0)
assert (-1*x**0).as_coeff_exponent(x) == (-1, 0)
assert (-2*x**0).as_coeff_exponent(x) == (-2, 0)
assert (2*x**3 + pi*x**3).as_coeff_exponent(x) == (2 + pi, 3)
assert (x*log(2)/(2*x + pi*x)).as_coeff_exponent(x) == \
(log(2)/(2 + pi), 0)
# issue 4784
D = Derivative
fx = D(f(x), x)
assert fx.as_coeff_exponent(f(x)) == (fx, 0)
def test_extractions():
for base in (2, S.Exp1):
assert Pow(base**x, 3, evaluate=False
).extract_multiplicatively(base**x) == base**(2*x)
assert (base**(5*x)).extract_multiplicatively(
base**(3*x)) == base**(2*x)
assert ((x*y)**3).extract_multiplicatively(x**2 * y) == x*y**2
assert ((x*y)**3).extract_multiplicatively(x**4 * y) is None
assert (2*x).extract_multiplicatively(2) == x
assert (2*x).extract_multiplicatively(3) is None
assert (2*x).extract_multiplicatively(-1) is None
assert (S.Half*x).extract_multiplicatively(3) == x/6
assert (sqrt(x)).extract_multiplicatively(x) is None
assert (sqrt(x)).extract_multiplicatively(1/x) is None
assert x.extract_multiplicatively(-x) is None
assert (-2 - 4*I).extract_multiplicatively(-2) == 1 + 2*I
assert (-2 - 4*I).extract_multiplicatively(3) is None
assert (-2*x - 4*y - 8).extract_multiplicatively(-2) == x + 2*y + 4
assert (-2*x*y - 4*x**2*y).extract_multiplicatively(-2*y) == 2*x**2 + x
assert (2*x*y + 4*x**2*y).extract_multiplicatively(2*y) == 2*x**2 + x
assert (-4*y**2*x).extract_multiplicatively(-3*y) is None
assert (2*x).extract_multiplicatively(1) == 2*x
assert (-oo).extract_multiplicatively(5) is -oo
assert (oo).extract_multiplicatively(5) is oo
assert ((x*y)**3).extract_additively(1) is None
assert (x + 1).extract_additively(x) == 1
assert (x + 1).extract_additively(2*x) is None
assert (x + 1).extract_additively(-x) is None
assert (-x + 1).extract_additively(2*x) is None
assert (2*x + 3).extract_additively(x) == x + 3
assert (2*x + 3).extract_additively(2) == 2*x + 1
assert (2*x + 3).extract_additively(3) == 2*x
assert (2*x + 3).extract_additively(-2) is None
assert (2*x + 3).extract_additively(3*x) is None
assert (2*x + 3).extract_additively(2*x) == 3
assert x.extract_additively(0) == x
assert S(2).extract_additively(x) is None
assert S(2.).extract_additively(2) is S.Zero
assert S(2*x + 3).extract_additively(x + 1) == x + 2
assert S(2*x + 3).extract_additively(y + 1) is None
assert S(2*x - 3).extract_additively(x + 1) is None
assert S(2*x - 3).extract_additively(y + z) is None
assert ((a + 1)*x*4 + y).extract_additively(x).expand() == \
4*a*x + 3*x + y
assert ((a + 1)*x*4 + 3*y).extract_additively(x + 2*y).expand() == \
4*a*x + 3*x + y
assert (y*(x + 1)).extract_additively(x + 1) is None
assert ((y + 1)*(x + 1) + 3).extract_additively(x + 1) == \
y*(x + 1) + 3
assert ((x + y)*(x + 1) + x + y + 3).extract_additively(x + y) == \
x*(x + y) + 3
assert (x + y + 2*((x + y)*(x + 1)) + 3).extract_additively((x + y)*(x + 1)) == \
x + y + (x + 1)*(x + y) + 3
assert ((y + 1)*(x + 2*y + 1) + 3).extract_additively(y + 1) == \
(x + 2*y)*(y + 1) + 3
assert (-x - x*I).extract_additively(-x) == -I*x
# extraction does not leave artificats, now
assert (4*x*(y + 1) + y).extract_additively(x) == x*(4*y + 3) + y
n = Symbol("n", integer=True)
assert (Integer(-3)).could_extract_minus_sign() is True
assert (-n*x + x).could_extract_minus_sign() != \
(n*x - x).could_extract_minus_sign()
assert (x - y).could_extract_minus_sign() != \
(-x + y).could_extract_minus_sign()
assert (1 - x - y).could_extract_minus_sign() is True
assert (1 - x + y).could_extract_minus_sign() is False
assert ((-x - x*y)/y).could_extract_minus_sign() is False
assert ((x + x*y)/(-y)).could_extract_minus_sign() is True
assert ((x + x*y)/y).could_extract_minus_sign() is False
assert ((-x - y)/(x + y)).could_extract_minus_sign() is False
class sign_invariant(Function, Expr):
nargs = 1
def __neg__(self):
return self
foo = sign_invariant(x)
assert foo == -foo
assert foo.could_extract_minus_sign() is False
assert (x - y).could_extract_minus_sign() is False
assert (-x + y).could_extract_minus_sign() is True
assert (x - 1).could_extract_minus_sign() is False
assert (1 - x).could_extract_minus_sign() is True
assert (sqrt(2) - 1).could_extract_minus_sign() is True
assert (1 - sqrt(2)).could_extract_minus_sign() is False
# check that result is canonical
eq = (3*x + 15*y).extract_multiplicatively(3)
assert eq.args == eq.func(*eq.args).args
def test_nan_extractions():
for r in (1, 0, I, nan):
assert nan.extract_additively(r) is None
assert nan.extract_multiplicatively(r) is None
def test_coeff():
assert (x + 1).coeff(x + 1) == 1
assert (3*x).coeff(0) == 0
assert (z*(1 + x)*x**2).coeff(1 + x) == z*x**2
assert (1 + 2*x*x**(1 + x)).coeff(x*x**(1 + x)) == 2
assert (1 + 2*x**(y + z)).coeff(x**(y + z)) == 2
assert (3 + 2*x + 4*x**2).coeff(1) == 0
assert (3 + 2*x + 4*x**2).coeff(-1) == 0
assert (3 + 2*x + 4*x**2).coeff(x) == 2
assert (3 + 2*x + 4*x**2).coeff(x**2) == 4
assert (3 + 2*x + 4*x**2).coeff(x**3) == 0
assert (-x/8 + x*y).coeff(x) == Rational(-1, 8) + y
assert (-x/8 + x*y).coeff(-x) == S.One/8
assert (4*x).coeff(2*x) == 0
assert (2*x).coeff(2*x) == 1
assert (-oo*x).coeff(x*oo) == -1
assert (10*x).coeff(x, 0) == 0
assert (10*x).coeff(10*x, 0) == 0
n1, n2 = symbols('n1 n2', commutative=False)
assert (n1*n2).coeff(n1) == 1
assert (n1*n2).coeff(n2) == n1
assert (n1*n2 + x*n1).coeff(n1) == 1 # 1*n1*(n2+x)
assert (n2*n1 + x*n1).coeff(n1) == n2 + x
assert (n2*n1 + x*n1**2).coeff(n1) == n2
assert (n1**x).coeff(n1) == 0
assert (n1*n2 + n2*n1).coeff(n1) == 0
assert (2*(n1 + n2)*n2).coeff(n1 + n2, right=1) == n2
assert (2*(n1 + n2)*n2).coeff(n1 + n2, right=0) == 2
assert (2*f(x) + 3*f(x).diff(x)).coeff(f(x)) == 2
expr = z*(x + y)**2
expr2 = z*(x + y)**2 + z*(2*x + 2*y)**2
assert expr.coeff(z) == (x + y)**2
assert expr.coeff(x + y) == 0
assert expr2.coeff(z) == (x + y)**2 + (2*x + 2*y)**2
assert (x + y + 3*z).coeff(1) == x + y
assert (-x + 2*y).coeff(-1) == x
assert (x - 2*y).coeff(-1) == 2*y
assert (3 + 2*x + 4*x**2).coeff(1) == 0
assert (-x - 2*y).coeff(2) == -y
assert (x + sqrt(2)*x).coeff(sqrt(2)) == x
assert (3 + 2*x + 4*x**2).coeff(x) == 2
assert (3 + 2*x + 4*x**2).coeff(x**2) == 4
assert (3 + 2*x + 4*x**2).coeff(x**3) == 0
assert (z*(x + y)**2).coeff((x + y)**2) == z
assert (z*(x + y)**2).coeff(x + y) == 0
assert (2 + 2*x + (x + 1)*y).coeff(x + 1) == y
assert (x + 2*y + 3).coeff(1) == x
assert (x + 2*y + 3).coeff(x, 0) == 2*y + 3
assert (x**2 + 2*y + 3*x).coeff(x**2, 0) == 2*y + 3*x
assert x.coeff(0, 0) == 0
assert x.coeff(x, 0) == 0
n, m, o, l = symbols('n m o l', commutative=False)
assert n.coeff(n) == 1
assert y.coeff(n) == 0
assert (3*n).coeff(n) == 3
assert (2 + n).coeff(x*m) == 0
assert (2*x*n*m).coeff(x) == 2*n*m
assert (2 + n).coeff(x*m*n + y) == 0
assert (2*x*n*m).coeff(3*n) == 0
assert (n*m + m*n*m).coeff(n) == 1 + m
assert (n*m + m*n*m).coeff(n, right=True) == m # = (1 + m)*n*m
assert (n*m + m*n).coeff(n) == 0
assert (n*m + o*m*n).coeff(m*n) == o
assert (n*m + o*m*n).coeff(m*n, right=True) == 1
assert (n*m + n*m*n).coeff(n*m, right=True) == 1 + n # = n*m*(n + 1)
assert (x*y).coeff(z, 0) == x*y
assert (x*n + y*n + z*m).coeff(n) == x + y
assert (n*m + n*o + o*l).coeff(n, right=True) == m + o
assert (x*n*m*n + y*n*m*o + z*l).coeff(m, right=True) == x*n + y*o
assert (x*n*m*n + x*n*m*o + z*l).coeff(m, right=True) == n + o
assert (x*n*m*n + x*n*m*o + z*l).coeff(m) == x*n
def test_coeff2():
r, kappa = symbols('r, kappa')
psi = Function("psi")
g = 1/r**2 * (2*r*psi(r).diff(r, 1) + r**2 * psi(r).diff(r, 2))
g = g.expand()
assert g.coeff(psi(r).diff(r)) == 2/r
def test_coeff2_0():
r, kappa = symbols('r, kappa')
psi = Function("psi")
g = 1/r**2 * (2*r*psi(r).diff(r, 1) + r**2 * psi(r).diff(r, 2))
g = g.expand()
assert g.coeff(psi(r).diff(r, 2)) == 1
def test_coeff_expand():
expr = z*(x + y)**2
expr2 = z*(x + y)**2 + z*(2*x + 2*y)**2
assert expr.coeff(z) == (x + y)**2
assert expr2.coeff(z) == (x + y)**2 + (2*x + 2*y)**2
def test_integrate():
assert x.integrate(x) == x**2/2
assert x.integrate((x, 0, 1)) == S.Half
def test_as_base_exp():
assert x.as_base_exp() == (x, S.One)
assert (x*y*z).as_base_exp() == (x*y*z, S.One)
assert (x + y + z).as_base_exp() == (x + y + z, S.One)
assert ((x + y)**z).as_base_exp() == (x + y, z)
def test_issue_4963():
assert hasattr(Mul(x, y), "is_commutative")
assert hasattr(Mul(x, y, evaluate=False), "is_commutative")
assert hasattr(Pow(x, y), "is_commutative")
assert hasattr(Pow(x, y, evaluate=False), "is_commutative")
expr = Mul(Pow(2, 2, evaluate=False), 3, evaluate=False) + 1
assert hasattr(expr, "is_commutative")
def test_action_verbs():
assert nsimplify(1/(exp(3*pi*x/5) + 1)) == \
(1/(exp(3*pi*x/5) + 1)).nsimplify()
assert ratsimp(1/x + 1/y) == (1/x + 1/y).ratsimp()
assert trigsimp(log(x), deep=True) == (log(x)).trigsimp(deep=True)
assert radsimp(1/(2 + sqrt(2))) == (1/(2 + sqrt(2))).radsimp()
assert radsimp(1/(a + b*sqrt(c)), symbolic=False) == \
(1/(a + b*sqrt(c))).radsimp(symbolic=False)
assert powsimp(x**y*x**z*y**z, combine='all') == \
(x**y*x**z*y**z).powsimp(combine='all')
assert (x**t*y**t).powsimp(force=True) == (x*y)**t
assert simplify(x**y*x**z*y**z) == (x**y*x**z*y**z).simplify()
assert together(1/x + 1/y) == (1/x + 1/y).together()
assert collect(a*x**2 + b*x**2 + a*x - b*x + c, x) == \
(a*x**2 + b*x**2 + a*x - b*x + c).collect(x)
assert apart(y/(y + 2)/(y + 1), y) == (y/(y + 2)/(y + 1)).apart(y)
assert combsimp(y/(x + 2)/(x + 1)) == (y/(x + 2)/(x + 1)).combsimp()
assert gammasimp(gamma(x)/gamma(x-5)) == (gamma(x)/gamma(x-5)).gammasimp()
assert factor(x**2 + 5*x + 6) == (x**2 + 5*x + 6).factor()
assert refine(sqrt(x**2)) == sqrt(x**2).refine()
assert cancel((x**2 + 5*x + 6)/(x + 2)) == ((x**2 + 5*x + 6)/(x + 2)).cancel()
def test_as_powers_dict():
assert x.as_powers_dict() == {x: 1}
assert (x**y*z).as_powers_dict() == {x: y, z: 1}
assert Mul(2, 2, evaluate=False).as_powers_dict() == {S(2): S(2)}
assert (x*y).as_powers_dict()[z] == 0
assert (x + y).as_powers_dict()[z] == 0
def test_as_coefficients_dict():
check = [S.One, x, y, x*y, 1]
assert [Add(3*x, 2*x, y, 3).as_coefficients_dict()[i] for i in check] == \
[3, 5, 1, 0, 3]
assert [Add(3*x, 2*x, y, 3, evaluate=False).as_coefficients_dict()[i]
for i in check] == [3, 5, 1, 0, 3]
assert [(3*x*y).as_coefficients_dict()[i] for i in check] == \
[0, 0, 0, 3, 0]
assert [(3.0*x*y).as_coefficients_dict()[i] for i in check] == \
[0, 0, 0, 3.0, 0]
assert (3.0*x*y).as_coefficients_dict()[3.0*x*y] == 0
eq = x*(x + 1)*a + x*b + c/x
assert eq.as_coefficients_dict(x) == {x: b, 1/x: c,
x*(x + 1): a}
assert eq.expand().as_coefficients_dict(x) == {x**2: a, x: a + b, 1/x: c}
assert x.as_coefficients_dict() == {x: S.One}
def test_args_cnc():
A = symbols('A', commutative=False)
assert (x + A).args_cnc() == \
[[], [x + A]]
assert (x + a).args_cnc() == \
[[a + x], []]
assert (x*a).args_cnc() == \
[[a, x], []]
assert (x*y*A*(A + 1)).args_cnc(cset=True) == \
[{x, y}, [A, 1 + A]]
assert Mul(x, x, evaluate=False).args_cnc(cset=True, warn=False) == \
[{x}, []]
assert Mul(x, x**2, evaluate=False).args_cnc(cset=True, warn=False) == \
[{x, x**2}, []]
raises(ValueError, lambda: Mul(x, x, evaluate=False).args_cnc(cset=True))
assert Mul(x, y, x, evaluate=False).args_cnc() == \
[[x, y, x], []]
# always split -1 from leading number
assert (-1.*x).args_cnc() == [[-1, 1.0, x], []]
def test_new_rawargs():
n = Symbol('n', commutative=False)
a = x + n
assert a.is_commutative is False
assert a._new_rawargs(x).is_commutative
assert a._new_rawargs(x, y).is_commutative
assert a._new_rawargs(x, n).is_commutative is False
assert a._new_rawargs(x, y, n).is_commutative is False
m = x*n
assert m.is_commutative is False
assert m._new_rawargs(x).is_commutative
assert m._new_rawargs(n).is_commutative is False
assert m._new_rawargs(x, y).is_commutative
assert m._new_rawargs(x, n).is_commutative is False
assert m._new_rawargs(x, y, n).is_commutative is False
assert m._new_rawargs(x, n, reeval=False).is_commutative is False
assert m._new_rawargs(S.One) is S.One
def test_issue_5226():
assert Add(evaluate=False) == 0
assert Mul(evaluate=False) == 1
assert Mul(x + y, evaluate=False).is_Add
def test_free_symbols():
# free_symbols should return the free symbols of an object
assert S.One.free_symbols == set()
assert x.free_symbols == {x}
assert Integral(x, (x, 1, y)).free_symbols == {y}
assert (-Integral(x, (x, 1, y))).free_symbols == {y}
assert meter.free_symbols == set()
assert (meter**x).free_symbols == {x}
def test_has_free():
assert x.has_free(x)
assert not x.has_free(y)
assert (x + y).has_free(x)
assert (x + y).has_free(*(x, z))
assert f(x).has_free(x)
assert f(x).has_free(f(x))
assert Integral(f(x), (f(x), 1, y)).has_free(y)
assert not Integral(f(x), (f(x), 1, y)).has_free(x)
assert not Integral(f(x), (f(x), 1, y)).has_free(f(x))
def test_issue_5300():
x = Symbol('x', commutative=False)
assert x*sqrt(2)/sqrt(6) == x*sqrt(3)/3
def test_floordiv():
from sympy.functions.elementary.integers import floor
assert x // y == floor(x / y)
def test_as_coeff_Mul():
assert Integer(3).as_coeff_Mul() == (Integer(3), Integer(1))
assert Rational(3, 4).as_coeff_Mul() == (Rational(3, 4), Integer(1))
assert Float(5.0).as_coeff_Mul() == (Float(5.0), Integer(1))
assert (Integer(3)*x).as_coeff_Mul() == (Integer(3), x)
assert (Rational(3, 4)*x).as_coeff_Mul() == (Rational(3, 4), x)
assert (Float(5.0)*x).as_coeff_Mul() == (Float(5.0), x)
assert (Integer(3)*x*y).as_coeff_Mul() == (Integer(3), x*y)
assert (Rational(3, 4)*x*y).as_coeff_Mul() == (Rational(3, 4), x*y)
assert (Float(5.0)*x*y).as_coeff_Mul() == (Float(5.0), x*y)
assert (x).as_coeff_Mul() == (S.One, x)
assert (x*y).as_coeff_Mul() == (S.One, x*y)
assert (-oo*x).as_coeff_Mul(rational=True) == (-1, oo*x)
def test_as_coeff_Add():
assert Integer(3).as_coeff_Add() == (Integer(3), Integer(0))
assert Rational(3, 4).as_coeff_Add() == (Rational(3, 4), Integer(0))
assert Float(5.0).as_coeff_Add() == (Float(5.0), Integer(0))
assert (Integer(3) + x).as_coeff_Add() == (Integer(3), x)
assert (Rational(3, 4) + x).as_coeff_Add() == (Rational(3, 4), x)
assert (Float(5.0) + x).as_coeff_Add() == (Float(5.0), x)
assert (Float(5.0) + x).as_coeff_Add(rational=True) == (0, Float(5.0) + x)
assert (Integer(3) + x + y).as_coeff_Add() == (Integer(3), x + y)
assert (Rational(3, 4) + x + y).as_coeff_Add() == (Rational(3, 4), x + y)
assert (Float(5.0) + x + y).as_coeff_Add() == (Float(5.0), x + y)
assert (x).as_coeff_Add() == (S.Zero, x)
assert (x*y).as_coeff_Add() == (S.Zero, x*y)
def test_expr_sorting():
exprs = [1/x**2, 1/x, sqrt(sqrt(x)), sqrt(x), x, sqrt(x)**3, x**2]
assert sorted(exprs, key=default_sort_key) == exprs
exprs = [x, 2*x, 2*x**2, 2*x**3, x**n, 2*x**n, sin(x), sin(x)**n,
sin(x**2), cos(x), cos(x**2), tan(x)]
assert sorted(exprs, key=default_sort_key) == exprs
exprs = [x + 1, x**2 + x + 1, x**3 + x**2 + x + 1]
assert sorted(exprs, key=default_sort_key) == exprs
exprs = [S(4), x - 3*I/2, x + 3*I/2, x - 4*I + 1, x + 4*I + 1]
assert sorted(exprs, key=default_sort_key) == exprs
exprs = [f(1), f(2), f(3), f(1, 2, 3), g(1), g(2), g(3), g(1, 2, 3)]
assert sorted(exprs, key=default_sort_key) == exprs
exprs = [f(x), g(x), exp(x), sin(x), cos(x), factorial(x)]
assert sorted(exprs, key=default_sort_key) == exprs
exprs = [Tuple(x, y), Tuple(x, z), Tuple(x, y, z)]
assert sorted(exprs, key=default_sort_key) == exprs
exprs = [[3], [1, 2]]
assert sorted(exprs, key=default_sort_key) == exprs
exprs = [[1, 2], [2, 3]]
assert sorted(exprs, key=default_sort_key) == exprs
exprs = [[1, 2], [1, 2, 3]]
assert sorted(exprs, key=default_sort_key) == exprs
exprs = [{x: -y}, {x: y}]
assert sorted(exprs, key=default_sort_key) == exprs
exprs = [{1}, {1, 2}]
assert sorted(exprs, key=default_sort_key) == exprs
a, b = exprs = [Dummy('x'), Dummy('x')]
assert sorted([b, a], key=default_sort_key) == exprs
def test_as_ordered_factors():
assert x.as_ordered_factors() == [x]
assert (2*x*x**n*sin(x)*cos(x)).as_ordered_factors() \
== [Integer(2), x, x**n, sin(x), cos(x)]
args = [f(1), f(2), f(3), f(1, 2, 3), g(1), g(2), g(3), g(1, 2, 3)]
expr = Mul(*args)
assert expr.as_ordered_factors() == args
A, B = symbols('A,B', commutative=False)
assert (A*B).as_ordered_factors() == [A, B]
assert (B*A).as_ordered_factors() == [B, A]
def test_as_ordered_terms():
assert x.as_ordered_terms() == [x]
assert (sin(x)**2*cos(x) + sin(x)*cos(x)**2 + 1).as_ordered_terms() \
== [sin(x)**2*cos(x), sin(x)*cos(x)**2, 1]
args = [f(1), f(2), f(3), f(1, 2, 3), g(1), g(2), g(3), g(1, 2, 3)]
expr = Add(*args)
assert expr.as_ordered_terms() == args
assert (1 + 4*sqrt(3)*pi*x).as_ordered_terms() == [4*pi*x*sqrt(3), 1]
assert ( 2 + 3*I).as_ordered_terms() == [2, 3*I]
assert (-2 + 3*I).as_ordered_terms() == [-2, 3*I]
assert ( 2 - 3*I).as_ordered_terms() == [2, -3*I]
assert (-2 - 3*I).as_ordered_terms() == [-2, -3*I]
assert ( 4 + 3*I).as_ordered_terms() == [4, 3*I]
assert (-4 + 3*I).as_ordered_terms() == [-4, 3*I]
assert ( 4 - 3*I).as_ordered_terms() == [4, -3*I]
assert (-4 - 3*I).as_ordered_terms() == [-4, -3*I]
e = x**2*y**2 + x*y**4 + y + 2
assert e.as_ordered_terms(order="lex") == [x**2*y**2, x*y**4, y, 2]
assert e.as_ordered_terms(order="grlex") == [x*y**4, x**2*y**2, y, 2]
assert e.as_ordered_terms(order="rev-lex") == [2, y, x*y**4, x**2*y**2]
assert e.as_ordered_terms(order="rev-grlex") == [2, y, x**2*y**2, x*y**4]
k = symbols('k')
assert k.as_ordered_terms(data=True) == ([(k, ((1.0, 0.0), (1,), ()))], [k])
def test_sort_key_atomic_expr():
from sympy.physics.units import m, s
assert sorted([-m, s], key=lambda arg: arg.sort_key()) == [-m, s]
def test_eval_interval():
assert exp(x)._eval_interval(*Tuple(x, 0, 1)) == exp(1) - exp(0)
# issue 4199
a = x/y
raises(NotImplementedError, lambda: a._eval_interval(x, S.Zero, oo)._eval_interval(y, oo, S.Zero))
raises(NotImplementedError, lambda: a._eval_interval(x, S.Zero, oo)._eval_interval(y, S.Zero, oo))
a = x - y
raises(NotImplementedError, lambda: a._eval_interval(x, S.One, oo)._eval_interval(y, oo, S.One))
raises(ValueError, lambda: x._eval_interval(x, None, None))
a = -y*Heaviside(x - y)
assert a._eval_interval(x, -oo, oo) == -y
assert a._eval_interval(x, oo, -oo) == y
def test_eval_interval_zoo():
# Test that limit is used when zoo is returned
assert Si(1/x)._eval_interval(x, S.Zero, S.One) == -pi/2 + Si(1)
def test_primitive():
assert (3*(x + 1)**2).primitive() == (3, (x + 1)**2)
assert (6*x + 2).primitive() == (2, 3*x + 1)
assert (x/2 + 3).primitive() == (S.Half, x + 6)
eq = (6*x + 2)*(x/2 + 3)
assert eq.primitive()[0] == 1
eq = (2 + 2*x)**2
assert eq.primitive()[0] == 1
assert (4.0*x).primitive() == (1, 4.0*x)
assert (4.0*x + y/2).primitive() == (S.Half, 8.0*x + y)
assert (-2*x).primitive() == (2, -x)
assert Add(5*z/7, 0.5*x, 3*y/2, evaluate=False).primitive() == \
(S.One/14, 7.0*x + 21*y + 10*z)
for i in [S.Infinity, S.NegativeInfinity, S.ComplexInfinity]:
assert (i + x/3).primitive() == \
(S.One/3, i + x)
assert (S.Infinity + 2*x/3 + 4*y/7).primitive() == \
(S.One/21, 14*x + 12*y + oo)
assert S.Zero.primitive() == (S.One, S.Zero)
def test_issue_5843():
a = 1 + x
assert (2*a).extract_multiplicatively(a) == 2
assert (4*a).extract_multiplicatively(2*a) == 2
assert ((3*a)*(2*a)).extract_multiplicatively(a) == 6*a
def test_is_constant():
from sympy.solvers.solvers import checksol
assert Sum(x, (x, 1, 10)).is_constant() is True
assert Sum(x, (x, 1, n)).is_constant() is False
assert Sum(x, (x, 1, n)).is_constant(y) is True
assert Sum(x, (x, 1, n)).is_constant(n) is False
assert Sum(x, (x, 1, n)).is_constant(x) is True
eq = a*cos(x)**2 + a*sin(x)**2 - a
assert eq.is_constant() is True
assert eq.subs({x: pi, a: 2}) == eq.subs({x: pi, a: 3}) == 0
assert x.is_constant() is False
assert x.is_constant(y) is True
assert log(x/y).is_constant() is False
assert checksol(x, x, Sum(x, (x, 1, n))) is False
assert checksol(x, x, Sum(x, (x, 1, n))) is False
assert f(1).is_constant
assert checksol(x, x, f(x)) is False
assert Pow(x, S.Zero, evaluate=False).is_constant() is True # == 1
assert Pow(S.Zero, x, evaluate=False).is_constant() is False # == 0 or 1
assert (2**x).is_constant() is False
assert Pow(S(2), S(3), evaluate=False).is_constant() is True
z1, z2 = symbols('z1 z2', zero=True)
assert (z1 + 2*z2).is_constant() is True
assert meter.is_constant() is True
assert (3*meter).is_constant() is True
assert (x*meter).is_constant() is False
def test_equals():
assert (-3 - sqrt(5) + (-sqrt(10)/2 - sqrt(2)/2)**2).equals(0)
assert (x**2 - 1).equals((x + 1)*(x - 1))
assert (cos(x)**2 + sin(x)**2).equals(1)
assert (a*cos(x)**2 + a*sin(x)**2).equals(a)
r = sqrt(2)
assert (-1/(r + r*x) + 1/r/(1 + x)).equals(0)
assert factorial(x + 1).equals((x + 1)*factorial(x))
assert sqrt(3).equals(2*sqrt(3)) is False
assert (sqrt(5)*sqrt(3)).equals(sqrt(3)) is False
assert (sqrt(5) + sqrt(3)).equals(0) is False
assert (sqrt(5) + pi).equals(0) is False
assert meter.equals(0) is False
assert (3*meter**2).equals(0) is False
eq = -(-1)**(S(3)/4)*6**(S.One/4) + (-6)**(S.One/4)*I
if eq != 0: # if canonicalization makes this zero, skip the test
assert eq.equals(0)
assert sqrt(x).equals(0) is False
# from integrate(x*sqrt(1 + 2*x), x);
# diff is zero only when assumptions allow
i = 2*sqrt(2)*x**(S(5)/2)*(1 + 1/(2*x))**(S(5)/2)/5 + \
2*sqrt(2)*x**(S(3)/2)*(1 + 1/(2*x))**(S(5)/2)/(-6 - 3/x)
ans = sqrt(2*x + 1)*(6*x**2 + x - 1)/15
diff = i - ans
assert diff.equals(0) is None # should be False, but previously this was False due to wrong intermediate result
assert diff.subs(x, Rational(-1, 2)/2) == 7*sqrt(2)/120
# there are regions for x for which the expression is True, for
# example, when x < -1/2 or x > 0 the expression is zero
p = Symbol('p', positive=True)
assert diff.subs(x, p).equals(0) is True
assert diff.subs(x, -1).equals(0) is True
# prove via minimal_polynomial or self-consistency
eq = sqrt(1 + sqrt(3)) + sqrt(3 + 3*sqrt(3)) - sqrt(10 + 6*sqrt(3))
assert eq.equals(0)
q = 3**Rational(1, 3) + 3
p = expand(q**3)**Rational(1, 3)
assert (p - q).equals(0)
# issue 6829
# eq = q*x + q/4 + x**4 + x**3 + 2*x**2 - S.One/3
# z = eq.subs(x, solve(eq, x)[0])
q = symbols('q')
z = (q*(-sqrt(-2*(-(q - S(7)/8)**S(2)/8 - S(2197)/13824)**(S.One/3) -
S(13)/12)/2 - sqrt((2*q - S(7)/4)/sqrt(-2*(-(q - S(7)/8)**S(2)/8 -
S(2197)/13824)**(S.One/3) - S(13)/12) + 2*(-(q - S(7)/8)**S(2)/8 -
S(2197)/13824)**(S.One/3) - S(13)/6)/2 - S.One/4) + q/4 + (-sqrt(-2*(-(q
- S(7)/8)**S(2)/8 - S(2197)/13824)**(S.One/3) - S(13)/12)/2 - sqrt((2*q
- S(7)/4)/sqrt(-2*(-(q - S(7)/8)**S(2)/8 - S(2197)/13824)**(S.One/3) -
S(13)/12) + 2*(-(q - S(7)/8)**S(2)/8 - S(2197)/13824)**(S.One/3) -
S(13)/6)/2 - S.One/4)**4 + (-sqrt(-2*(-(q - S(7)/8)**S(2)/8 -
S(2197)/13824)**(S.One/3) - S(13)/12)/2 - sqrt((2*q -
S(7)/4)/sqrt(-2*(-(q - S(7)/8)**S(2)/8 - S(2197)/13824)**(S.One/3) -
S(13)/12) + 2*(-(q - S(7)/8)**S(2)/8 - S(2197)/13824)**(S.One/3) -
S(13)/6)/2 - S.One/4)**3 + 2*(-sqrt(-2*(-(q - S(7)/8)**S(2)/8 -
S(2197)/13824)**(S.One/3) - S(13)/12)/2 - sqrt((2*q -
S(7)/4)/sqrt(-2*(-(q - S(7)/8)**S(2)/8 - S(2197)/13824)**(S.One/3) -
S(13)/12) + 2*(-(q - S(7)/8)**S(2)/8 - S(2197)/13824)**(S.One/3) -
S(13)/6)/2 - S.One/4)**2 - Rational(1, 3))
assert z.equals(0)
def test_random():
from sympy.functions.combinatorial.numbers import lucas
from sympy.simplify.simplify import posify
assert posify(x)[0]._random() is not None
assert lucas(n)._random(2, -2, 0, -1, 1) is None
# issue 8662
assert Piecewise((Max(x, y), z))._random() is None
def test_round():
assert str(Float('0.1249999').round(2)) == '0.12'
d20 = 12345678901234567890
ans = S(d20).round(2)
assert ans.is_Integer and ans == d20
ans = S(d20).round(-2)
assert ans.is_Integer and ans == 12345678901234567900
assert str(S('1/7').round(4)) == '0.1429'
assert str(S('.[12345]').round(4)) == '0.1235'
assert str(S('.1349').round(2)) == '0.13'
n = S(12345)
ans = n.round()
assert ans.is_Integer
assert ans == n
ans = n.round(1)
assert ans.is_Integer
assert ans == n
ans = n.round(4)
assert ans.is_Integer
assert ans == n
assert n.round(-1) == 12340
r = Float(str(n)).round(-4)
assert r == 10000
assert n.round(-5) == 0
assert str((pi + sqrt(2)).round(2)) == '4.56'
assert (10*(pi + sqrt(2))).round(-1) == 50
raises(TypeError, lambda: round(x + 2, 2))
assert str(S(2.3).round(1)) == '2.3'
# rounding in SymPy (as in Decimal) should be
# exact for the given precision; we check here
# that when a 5 follows the last digit that
# the rounded digit will be even.
for i in range(-99, 100):
# construct a decimal that ends in 5, e.g. 123 -> 0.1235
s = str(abs(i))
p = len(s) # we are going to round to the last digit of i
n = '0.%s5' % s # put a 5 after i's digits
j = p + 2 # 2 for '0.'
if i < 0: # 1 for '-'
j += 1
n = '-' + n
v = str(Float(n).round(p))[:j] # pertinent digits
if v.endswith('.'):
continue # it ends with 0 which is even
L = int(v[-1]) # last digit
assert L % 2 == 0, (n, '->', v)
assert (Float(.3, 3) + 2*pi).round() == 7
assert (Float(.3, 3) + 2*pi*100).round() == 629
assert (pi + 2*E*I).round() == 3 + 5*I
# don't let request for extra precision give more than
# what is known (in this case, only 3 digits)
assert str((Float(.03, 3) + 2*pi/100).round(5)) == '0.0928'
assert str((Float(.03, 3) + 2*pi/100).round(4)) == '0.0928'
assert S.Zero.round() == 0
a = (Add(1, Float('1.' + '9'*27, ''), evaluate=0))
assert a.round(10) == Float('3.0000000000', '')
assert a.round(25) == Float('3.0000000000000000000000000', '')
assert a.round(26) == Float('3.00000000000000000000000000', '')
assert a.round(27) == Float('2.999999999999999999999999999', '')
assert a.round(30) == Float('2.999999999999999999999999999', '')
raises(TypeError, lambda: x.round())
raises(TypeError, lambda: f(1).round())
# exact magnitude of 10
assert str(S.One.round()) == '1'
assert str(S(100).round()) == '100'
# applied to real and imaginary portions
assert (2*pi + E*I).round() == 6 + 3*I
assert (2*pi + I/10).round() == 6
assert (pi/10 + 2*I).round() == 2*I
# the lhs re and im parts are Float with dps of 2
# and those on the right have dps of 15 so they won't compare
# equal unless we use string or compare components (which will
# then coerce the floats to the same precision) or re-create
# the floats
assert str((pi/10 + E*I).round(2)) == '0.31 + 2.72*I'
assert str((pi/10 + E*I).round(2).as_real_imag()) == '(0.31, 2.72)'
assert str((pi/10 + E*I).round(2)) == '0.31 + 2.72*I'
# issue 6914
assert (I**(I + 3)).round(3) == Float('-0.208', '')*I
# issue 8720
assert S(-123.6).round() == -124
assert S(-1.5).round() == -2
assert S(-100.5).round() == -100
assert S(-1.5 - 10.5*I).round() == -2 - 10*I
# issue 7961
assert str(S(0.006).round(2)) == '0.01'
assert str(S(0.00106).round(4)) == '0.0011'
# issue 8147
assert S.NaN.round() is S.NaN
assert S.Infinity.round() is S.Infinity
assert S.NegativeInfinity.round() is S.NegativeInfinity
assert S.ComplexInfinity.round() is S.ComplexInfinity
# check that types match
for i in range(2):
fi = float(i)
# 2 args
assert all(type(round(i, p)) is int for p in (-1, 0, 1))
assert all(S(i).round(p).is_Integer for p in (-1, 0, 1))
assert all(type(round(fi, p)) is float for p in (-1, 0, 1))
assert all(S(fi).round(p).is_Float for p in (-1, 0, 1))
# 1 arg (p is None)
assert type(round(i)) is int
assert S(i).round().is_Integer
assert type(round(fi)) is int
assert S(fi).round().is_Integer
def test_held_expression_UnevaluatedExpr():
x = symbols("x")
he = UnevaluatedExpr(1/x)
e1 = x*he
assert isinstance(e1, Mul)
assert e1.args == (x, he)
assert e1.doit() == 1
assert UnevaluatedExpr(Derivative(x, x)).doit(deep=False
) == Derivative(x, x)
assert UnevaluatedExpr(Derivative(x, x)).doit() == 1
xx = Mul(x, x, evaluate=False)
assert xx != x**2
ue2 = UnevaluatedExpr(xx)
assert isinstance(ue2, UnevaluatedExpr)
assert ue2.args == (xx,)
assert ue2.doit() == x**2
assert ue2.doit(deep=False) == xx
x2 = UnevaluatedExpr(2)*2
assert type(x2) is Mul
assert x2.args == (2, UnevaluatedExpr(2))
def test_round_exception_nostr():
# Don't use the string form of the expression in the round exception, as
# it's too slow
s = Symbol('bad')
try:
s.round()
except TypeError as e:
assert 'bad' not in str(e)
else:
# Did not raise
raise AssertionError("Did not raise")
def test_extract_branch_factor():
assert exp_polar(2.0*I*pi).extract_branch_factor() == (1, 1)
def test_identity_removal():
assert Add.make_args(x + 0) == (x,)
assert Mul.make_args(x*1) == (x,)
def test_float_0():
assert Float(0.0) + 1 == Float(1.0)
@XFAIL
def test_float_0_fail():
assert Float(0.0)*x == Float(0.0)
assert (x + Float(0.0)).is_Add
def test_issue_6325():
ans = (b**2 + z**2 - (b*(a + b*t) + z*(c + t*z))**2/(
(a + b*t)**2 + (c + t*z)**2))/sqrt((a + b*t)**2 + (c + t*z)**2)
e = sqrt((a + b*t)**2 + (c + z*t)**2)
assert diff(e, t, 2) == ans
assert e.diff(t, 2) == ans
assert diff(e, t, 2, simplify=False) != ans
def test_issue_7426():
f1 = a % c
f2 = x % z
assert f1.equals(f2) is None
def test_issue_11122():
x = Symbol('x', extended_positive=False)
assert unchanged(Gt, x, 0) # (x > 0)
# (x > 0) should remain unevaluated after PR #16956
x = Symbol('x', positive=False, real=True)
assert (x > 0) is S.false
def test_issue_10651():
x = Symbol('x', real=True)
e1 = (-1 + x)/(1 - x)
e3 = (4*x**2 - 4)/((1 - x)*(1 + x))
e4 = 1/(cos(x)**2) - (tan(x))**2
x = Symbol('x', positive=True)
e5 = (1 + x)/x
assert e1.is_constant() is None
assert e3.is_constant() is None
assert e4.is_constant() is None
assert e5.is_constant() is False
def test_issue_10161():
x = symbols('x', real=True)
assert x*abs(x)*abs(x) == x**3
def test_issue_10755():
x = symbols('x')
raises(TypeError, lambda: int(log(x)))
raises(TypeError, lambda: log(x).round(2))
def test_issue_11877():
x = symbols('x')
assert integrate(log(S.Half - x), (x, 0, S.Half)) == Rational(-1, 2) -log(2)/2
def test_normal():
x = symbols('x')
e = Mul(S.Half, 1 + x, evaluate=False)
assert e.normal() == e
def test_expr():
x = symbols('x')
raises(TypeError, lambda: tan(x).series(x, 2, oo, "+"))
def test_ExprBuilder():
eb = ExprBuilder(Mul)
eb.args.extend([x, x])
assert eb.build() == x**2
def test_issue_22020():
from sympy.parsing.sympy_parser import parse_expr
x = parse_expr("log((2*V/3-V)/C)/-(R+r)*C")
y = parse_expr("log((2*V/3-V)/C)/-(R+r)*2")
assert x.equals(y) is False
def test_non_string_equality():
# Expressions should not compare equal to strings
x = symbols('x')
one = sympify(1)
assert (x == 'x') is False
assert (x != 'x') is True
assert (one == '1') is False
assert (one != '1') is True
assert (x + 1 == 'x + 1') is False
assert (x + 1 != 'x + 1') is True
# Make sure == doesn't try to convert the resulting expression to a string
# (e.g., by calling sympify() instead of _sympify())
class BadRepr:
def __repr__(self):
raise RuntimeError
assert (x == BadRepr()) is False
assert (x != BadRepr()) is True
def test_21494():
from sympy.testing.pytest import warns_deprecated_sympy
with warns_deprecated_sympy():
assert x.expr_free_symbols == {x}
with warns_deprecated_sympy():
assert Basic().expr_free_symbols == set()
with warns_deprecated_sympy():
assert S(2).expr_free_symbols == {S(2)}
with warns_deprecated_sympy():
assert Indexed("A", x).expr_free_symbols == {Indexed("A", x)}
with warns_deprecated_sympy():
assert Subs(x, x, 0).expr_free_symbols == set()
def test_Expr__eq__iterable_handling():
assert x != range(3)
def test_format():
assert '{:1.2f}'.format(S.Zero) == '0.00'
assert '{:+3.0f}'.format(S(3)) == ' +3'
assert '{:23.20f}'.format(pi) == ' 3.14159265358979323846'
assert '{:50.48f}'.format(exp(sin(1))) == '2.319776824715853173956590377503266813254904772376'
|
3ec121aeded28316ef2e6c521a17d171b28fe911c5fdc0d27b8a2a832ad9abf6 | from sympy.core.function import Function, UndefinedFunction
from sympy.core.numbers import (I, Rational, pi)
from sympy.core.relational import (GreaterThan, LessThan, StrictGreaterThan, StrictLessThan)
from sympy.core.symbol import (Dummy, Symbol, Wild, symbols)
from sympy.core.sympify import sympify # can't import as S yet
from sympy.core.symbol import uniquely_named_symbol, _symbol, Str
from sympy.testing.pytest import raises
from sympy.core.symbol import disambiguate
def test_Str():
a1 = Str('a')
a2 = Str('a')
b = Str('b')
assert a1 == a2 != b
raises(TypeError, lambda: Str())
def test_Symbol():
a = Symbol("a")
x1 = Symbol("x")
x2 = Symbol("x")
xdummy1 = Dummy("x")
xdummy2 = Dummy("x")
assert a != x1
assert a != x2
assert x1 == x2
assert x1 != xdummy1
assert xdummy1 != xdummy2
assert Symbol("x") == Symbol("x")
assert Dummy("x") != Dummy("x")
d = symbols('d', cls=Dummy)
assert isinstance(d, Dummy)
c, d = symbols('c,d', cls=Dummy)
assert isinstance(c, Dummy)
assert isinstance(d, Dummy)
raises(TypeError, lambda: Symbol())
def test_Dummy():
assert Dummy() != Dummy()
def test_Dummy_force_dummy_index():
raises(AssertionError, lambda: Dummy(dummy_index=1))
assert Dummy('d', dummy_index=2) == Dummy('d', dummy_index=2)
assert Dummy('d1', dummy_index=2) != Dummy('d2', dummy_index=2)
d1 = Dummy('d', dummy_index=3)
d2 = Dummy('d')
# might fail if d1 were created with dummy_index >= 10**6
assert d1 != d2
d3 = Dummy('d', dummy_index=3)
assert d1 == d3
assert Dummy()._count == Dummy('d', dummy_index=3)._count
def test_lt_gt():
S = sympify
x, y = Symbol('x'), Symbol('y')
assert (x >= y) == GreaterThan(x, y)
assert (x >= 0) == GreaterThan(x, 0)
assert (x <= y) == LessThan(x, y)
assert (x <= 0) == LessThan(x, 0)
assert (0 <= x) == GreaterThan(x, 0)
assert (0 >= x) == LessThan(x, 0)
assert (S(0) >= x) == GreaterThan(0, x)
assert (S(0) <= x) == LessThan(0, x)
assert (x > y) == StrictGreaterThan(x, y)
assert (x > 0) == StrictGreaterThan(x, 0)
assert (x < y) == StrictLessThan(x, y)
assert (x < 0) == StrictLessThan(x, 0)
assert (0 < x) == StrictGreaterThan(x, 0)
assert (0 > x) == StrictLessThan(x, 0)
assert (S(0) > x) == StrictGreaterThan(0, x)
assert (S(0) < x) == StrictLessThan(0, x)
e = x**2 + 4*x + 1
assert (e >= 0) == GreaterThan(e, 0)
assert (0 <= e) == GreaterThan(e, 0)
assert (e > 0) == StrictGreaterThan(e, 0)
assert (0 < e) == StrictGreaterThan(e, 0)
assert (e <= 0) == LessThan(e, 0)
assert (0 >= e) == LessThan(e, 0)
assert (e < 0) == StrictLessThan(e, 0)
assert (0 > e) == StrictLessThan(e, 0)
assert (S(0) >= e) == GreaterThan(0, e)
assert (S(0) <= e) == LessThan(0, e)
assert (S(0) < e) == StrictLessThan(0, e)
assert (S(0) > e) == StrictGreaterThan(0, e)
def test_no_len():
# there should be no len for numbers
x = Symbol('x')
raises(TypeError, lambda: len(x))
def test_ineq_unequal():
S = sympify
x, y, z = symbols('x,y,z')
e = (
S(-1) >= x, S(-1) >= y, S(-1) >= z,
S(-1) > x, S(-1) > y, S(-1) > z,
S(-1) <= x, S(-1) <= y, S(-1) <= z,
S(-1) < x, S(-1) < y, S(-1) < z,
S(0) >= x, S(0) >= y, S(0) >= z,
S(0) > x, S(0) > y, S(0) > z,
S(0) <= x, S(0) <= y, S(0) <= z,
S(0) < x, S(0) < y, S(0) < z,
S('3/7') >= x, S('3/7') >= y, S('3/7') >= z,
S('3/7') > x, S('3/7') > y, S('3/7') > z,
S('3/7') <= x, S('3/7') <= y, S('3/7') <= z,
S('3/7') < x, S('3/7') < y, S('3/7') < z,
S(1.5) >= x, S(1.5) >= y, S(1.5) >= z,
S(1.5) > x, S(1.5) > y, S(1.5) > z,
S(1.5) <= x, S(1.5) <= y, S(1.5) <= z,
S(1.5) < x, S(1.5) < y, S(1.5) < z,
S(2) >= x, S(2) >= y, S(2) >= z,
S(2) > x, S(2) > y, S(2) > z,
S(2) <= x, S(2) <= y, S(2) <= z,
S(2) < x, S(2) < y, S(2) < z,
x >= -1, y >= -1, z >= -1,
x > -1, y > -1, z > -1,
x <= -1, y <= -1, z <= -1,
x < -1, y < -1, z < -1,
x >= 0, y >= 0, z >= 0,
x > 0, y > 0, z > 0,
x <= 0, y <= 0, z <= 0,
x < 0, y < 0, z < 0,
x >= 1.5, y >= 1.5, z >= 1.5,
x > 1.5, y > 1.5, z > 1.5,
x <= 1.5, y <= 1.5, z <= 1.5,
x < 1.5, y < 1.5, z < 1.5,
x >= 2, y >= 2, z >= 2,
x > 2, y > 2, z > 2,
x <= 2, y <= 2, z <= 2,
x < 2, y < 2, z < 2,
x >= y, x >= z, y >= x, y >= z, z >= x, z >= y,
x > y, x > z, y > x, y > z, z > x, z > y,
x <= y, x <= z, y <= x, y <= z, z <= x, z <= y,
x < y, x < z, y < x, y < z, z < x, z < y,
x - pi >= y + z, y - pi >= x + z, z - pi >= x + y,
x - pi > y + z, y - pi > x + z, z - pi > x + y,
x - pi <= y + z, y - pi <= x + z, z - pi <= x + y,
x - pi < y + z, y - pi < x + z, z - pi < x + y,
True, False
)
left_e = e[:-1]
for i, e1 in enumerate( left_e ):
for e2 in e[i + 1:]:
assert e1 != e2
def test_Wild_properties():
S = sympify
# these tests only include Atoms
x = Symbol("x")
y = Symbol("y")
p = Symbol("p", positive=True)
k = Symbol("k", integer=True)
n = Symbol("n", integer=True, positive=True)
given_patterns = [ x, y, p, k, -k, n, -n, S(-3), S(3),
pi, Rational(3, 2), I ]
integerp = lambda k: k.is_integer
positivep = lambda k: k.is_positive
symbolp = lambda k: k.is_Symbol
realp = lambda k: k.is_extended_real
S = Wild("S", properties=[symbolp])
R = Wild("R", properties=[realp])
Y = Wild("Y", exclude=[x, p, k, n])
P = Wild("P", properties=[positivep])
K = Wild("K", properties=[integerp])
N = Wild("N", properties=[positivep, integerp])
given_wildcards = [ S, R, Y, P, K, N ]
goodmatch = {
S: (x, y, p, k, n),
R: (p, k, -k, n, -n, -3, 3, pi, Rational(3, 2)),
Y: (y, -3, 3, pi, Rational(3, 2), I ),
P: (p, n, 3, pi, Rational(3, 2)),
K: (k, -k, n, -n, -3, 3),
N: (n, 3)}
for A in given_wildcards:
for pat in given_patterns:
d = pat.match(A)
if pat in goodmatch[A]:
assert d[A] in goodmatch[A]
else:
assert d is None
def test_symbols():
x = Symbol('x')
y = Symbol('y')
z = Symbol('z')
assert symbols('x') == x
assert symbols('x ') == x
assert symbols(' x ') == x
assert symbols('x,') == (x,)
assert symbols('x, ') == (x,)
assert symbols('x ,') == (x,)
assert symbols('x , y') == (x, y)
assert symbols('x,y,z') == (x, y, z)
assert symbols('x y z') == (x, y, z)
assert symbols('x,y,z,') == (x, y, z)
assert symbols('x y z ') == (x, y, z)
xyz = Symbol('xyz')
abc = Symbol('abc')
assert symbols('xyz') == xyz
assert symbols('xyz,') == (xyz,)
assert symbols('xyz,abc') == (xyz, abc)
assert symbols(('xyz',)) == (xyz,)
assert symbols(('xyz,',)) == ((xyz,),)
assert symbols(('x,y,z,',)) == ((x, y, z),)
assert symbols(('xyz', 'abc')) == (xyz, abc)
assert symbols(('xyz,abc',)) == ((xyz, abc),)
assert symbols(('xyz,abc', 'x,y,z')) == ((xyz, abc), (x, y, z))
assert symbols(('x', 'y', 'z')) == (x, y, z)
assert symbols(['x', 'y', 'z']) == [x, y, z]
assert symbols({'x', 'y', 'z'}) == {x, y, z}
raises(ValueError, lambda: symbols(''))
raises(ValueError, lambda: symbols(','))
raises(ValueError, lambda: symbols('x,,y,,z'))
raises(ValueError, lambda: symbols(('x', '', 'y', '', 'z')))
a, b = symbols('x,y', real=True)
assert a.is_real and b.is_real
x0 = Symbol('x0')
x1 = Symbol('x1')
x2 = Symbol('x2')
y0 = Symbol('y0')
y1 = Symbol('y1')
assert symbols('x0:0') == ()
assert symbols('x0:1') == (x0,)
assert symbols('x0:2') == (x0, x1)
assert symbols('x0:3') == (x0, x1, x2)
assert symbols('x:0') == ()
assert symbols('x:1') == (x0,)
assert symbols('x:2') == (x0, x1)
assert symbols('x:3') == (x0, x1, x2)
assert symbols('x1:1') == ()
assert symbols('x1:2') == (x1,)
assert symbols('x1:3') == (x1, x2)
assert symbols('x1:3,x,y,z') == (x1, x2, x, y, z)
assert symbols('x:3,y:2') == (x0, x1, x2, y0, y1)
assert symbols(('x:3', 'y:2')) == ((x0, x1, x2), (y0, y1))
a = Symbol('a')
b = Symbol('b')
c = Symbol('c')
d = Symbol('d')
assert symbols('x:z') == (x, y, z)
assert symbols('a:d,x:z') == (a, b, c, d, x, y, z)
assert symbols(('a:d', 'x:z')) == ((a, b, c, d), (x, y, z))
aa = Symbol('aa')
ab = Symbol('ab')
ac = Symbol('ac')
ad = Symbol('ad')
assert symbols('aa:d') == (aa, ab, ac, ad)
assert symbols('aa:d,x:z') == (aa, ab, ac, ad, x, y, z)
assert symbols(('aa:d','x:z')) == ((aa, ab, ac, ad), (x, y, z))
assert type(symbols(('q:2', 'u:2'), cls=Function)[0][0]) == UndefinedFunction # issue 23532
# issue 6675
def sym(s):
return str(symbols(s))
assert sym('a0:4') == '(a0, a1, a2, a3)'
assert sym('a2:4,b1:3') == '(a2, a3, b1, b2)'
assert sym('a1(2:4)') == '(a12, a13)'
assert sym('a0:2.0:2') == '(a0.0, a0.1, a1.0, a1.1)'
assert sym('aa:cz') == '(aaz, abz, acz)'
assert sym('aa:c0:2') == '(aa0, aa1, ab0, ab1, ac0, ac1)'
assert sym('aa:ba:b') == '(aaa, aab, aba, abb)'
assert sym('a:3b') == '(a0b, a1b, a2b)'
assert sym('a-1:3b') == '(a-1b, a-2b)'
assert sym(r'a:2\,:2' + chr(0)) == '(a0,0%s, a0,1%s, a1,0%s, a1,1%s)' % (
(chr(0),)*4)
assert sym('x(:a:3)') == '(x(a0), x(a1), x(a2))'
assert sym('x(:c):1') == '(xa0, xb0, xc0)'
assert sym('x((:a)):3') == '(x(a)0, x(a)1, x(a)2)'
assert sym('x(:a:3') == '(x(a0, x(a1, x(a2)'
assert sym(':2') == '(0, 1)'
assert sym(':b') == '(a, b)'
assert sym(':b:2') == '(a0, a1, b0, b1)'
assert sym(':2:2') == '(00, 01, 10, 11)'
assert sym(':b:b') == '(aa, ab, ba, bb)'
raises(ValueError, lambda: symbols(':'))
raises(ValueError, lambda: symbols('a:'))
raises(ValueError, lambda: symbols('::'))
raises(ValueError, lambda: symbols('a::'))
raises(ValueError, lambda: symbols(':a:'))
raises(ValueError, lambda: symbols('::a'))
def test_symbols_become_functions_issue_3539():
from sympy.abc import alpha, phi, beta, t
raises(TypeError, lambda: beta(2))
raises(TypeError, lambda: beta(2.5))
raises(TypeError, lambda: phi(2.5))
raises(TypeError, lambda: alpha(2.5))
raises(TypeError, lambda: phi(t))
def test_unicode():
xu = Symbol('x')
x = Symbol('x')
assert x == xu
raises(TypeError, lambda: Symbol(1))
def test_uniquely_named_symbol_and_Symbol():
F = uniquely_named_symbol
x = Symbol('x')
assert F(x) == x
assert F('x') == x
assert str(F('x', x)) == 'x0'
assert str(F('x', (x + 1, 1/x))) == 'x0'
_x = Symbol('x', real=True)
assert F(('x', _x)) == _x
assert F((x, _x)) == _x
assert F('x', real=True).is_real
y = Symbol('y')
assert F(('x', y), real=True).is_real
r = Symbol('x', real=True)
assert F(('x', r)).is_real
assert F(('x', r), real=False).is_real
assert F('x1', Symbol('x1'),
compare=lambda i: str(i).rstrip('1')).name == 'x0'
assert F('x1', Symbol('x1'),
modify=lambda i: i + '_').name == 'x1_'
assert _symbol(x, _x) == x
def test_disambiguate():
x, y, y_1, _x, x_1, x_2 = symbols('x y y_1 _x x_1 x_2')
t1 = Dummy('y'), _x, Dummy('x'), Dummy('x')
t2 = Dummy('x'), Dummy('x')
t3 = Dummy('x'), Dummy('y')
t4 = x, Dummy('x')
t5 = Symbol('x', integer=True), x, Symbol('x_1')
assert disambiguate(*t1) == (y, x_2, x, x_1)
assert disambiguate(*t2) == (x, x_1)
assert disambiguate(*t3) == (x, y)
assert disambiguate(*t4) == (x_1, x)
assert disambiguate(*t5) == (t5[0], x_2, x_1)
assert disambiguate(*t5)[0] != x # assumptions are retained
t6 = _x, Dummy('x')/y
t7 = y*Dummy('y'), y
assert disambiguate(*t6) == (x_1, x/y)
assert disambiguate(*t7) == (y*y_1, y_1)
assert disambiguate(Dummy('x_1'), Dummy('x_1')
) == (x_1, Symbol('x_1_1'))
|
fcd75b9d1951b9b3cefa57c0f18ae9de494779aa331e0a877f42999cf134d138 | from sympy.core.cache import cacheit, cached_property
from sympy.testing.pytest import raises
def test_cacheit_doc():
@cacheit
def testfn():
"test docstring"
pass
assert testfn.__doc__ == "test docstring"
assert testfn.__name__ == "testfn"
def test_cacheit_unhashable():
@cacheit
def testit(x):
return x
assert testit(1) == 1
assert testit(1) == 1
a = {}
assert testit(a) == {}
a[1] = 2
assert testit(a) == {1: 2}
def test_cachit_exception():
# Make sure the cache doesn't call functions multiple times when they
# raise TypeError
a = []
@cacheit
def testf(x):
a.append(0)
raise TypeError
raises(TypeError, lambda: testf(1))
assert len(a) == 1
a.clear()
# Unhashable type
raises(TypeError, lambda: testf([]))
assert len(a) == 1
@cacheit
def testf2(x):
a.append(0)
raise TypeError("Error")
a.clear()
raises(TypeError, lambda: testf2(1))
assert len(a) == 1
a.clear()
# Unhashable type
raises(TypeError, lambda: testf2([]))
assert len(a) == 1
def test_cached_property():
class A:
def __init__(self, value):
self.value = value
self.calls = 0
@cached_property
def prop(self):
self.calls = self.calls + 1
return self.value
a = A(2)
assert a.calls == 0
assert a.prop == 2
assert a.calls == 1
assert a.prop == 2
assert a.calls == 1
b = A(None)
assert b.prop == None
|
9080614c84c226a34253fb5c870917f02cbcfa7fbf4ea321482dacceb0bce996 | """Tests for tools for manipulating of large commutative expressions. """
from sympy.concrete.summations import Sum
from sympy.core.add import Add
from sympy.core.basic import Basic
from sympy.core.containers import (Dict, Tuple)
from sympy.core.function import Function
from sympy.core.mul import Mul
from sympy.core.numbers import (I, Rational, oo)
from sympy.core.singleton import S
from sympy.core.symbol import (Dummy, Symbol, symbols)
from sympy.functions.elementary.exponential import (exp, log)
from sympy.functions.elementary.miscellaneous import (root, sqrt)
from sympy.functions.elementary.trigonometric import (cos, sin)
from sympy.integrals.integrals import Integral
from sympy.series.order import O
from sympy.sets.sets import Interval
from sympy.simplify.radsimp import collect
from sympy.simplify.simplify import simplify
from sympy.core.exprtools import (decompose_power, Factors, Term, _gcd_terms,
gcd_terms, factor_terms, factor_nc, _mask_nc,
_monotonic_sign)
from sympy.core.mul import _keep_coeff as _keep_coeff
from sympy.simplify.cse_opts import sub_pre
from sympy.testing.pytest import raises
from sympy.abc import a, b, t, x, y, z
def test_decompose_power():
assert decompose_power(x) == (x, 1)
assert decompose_power(x**2) == (x, 2)
assert decompose_power(x**(2*y)) == (x**y, 2)
assert decompose_power(x**(2*y/3)) == (x**(y/3), 2)
assert decompose_power(x**(y*Rational(2, 3))) == (x**(y/3), 2)
def test_Factors():
assert Factors() == Factors({}) == Factors(S.One)
assert Factors().as_expr() is S.One
assert Factors({x: 2, y: 3, sin(x): 4}).as_expr() == x**2*y**3*sin(x)**4
assert Factors(S.Infinity) == Factors({oo: 1})
assert Factors(S.NegativeInfinity) == Factors({oo: 1, -1: 1})
# issue #18059:
assert Factors((x**2)**S.Half).as_expr() == (x**2)**S.Half
a = Factors({x: 5, y: 3, z: 7})
b = Factors({ y: 4, z: 3, t: 10})
assert a.mul(b) == a*b == Factors({x: 5, y: 7, z: 10, t: 10})
assert a.div(b) == divmod(a, b) == \
(Factors({x: 5, z: 4}), Factors({y: 1, t: 10}))
assert a.quo(b) == a/b == Factors({x: 5, z: 4})
assert a.rem(b) == a % b == Factors({y: 1, t: 10})
assert a.pow(3) == a**3 == Factors({x: 15, y: 9, z: 21})
assert b.pow(3) == b**3 == Factors({y: 12, z: 9, t: 30})
assert a.gcd(b) == Factors({y: 3, z: 3})
assert a.lcm(b) == Factors({x: 5, y: 4, z: 7, t: 10})
a = Factors({x: 4, y: 7, t: 7})
b = Factors({z: 1, t: 3})
assert a.normal(b) == (Factors({x: 4, y: 7, t: 4}), Factors({z: 1}))
assert Factors(sqrt(2)*x).as_expr() == sqrt(2)*x
assert Factors(-I)*I == Factors()
assert Factors({S.NegativeOne: S(3)})*Factors({S.NegativeOne: S.One, I: S(5)}) == \
Factors(I)
assert Factors(sqrt(I)*I) == Factors(I**(S(3)/2)) == Factors({I: S(3)/2})
assert Factors({I: S(3)/2}).as_expr() == I**(S(3)/2)
assert Factors(S(2)**x).div(S(3)**x) == \
(Factors({S(2): x}), Factors({S(3): x}))
assert Factors(2**(2*x + 2)).div(S(8)) == \
(Factors({S(2): 2*x + 2}), Factors({S(8): S.One}))
# coverage
# /!\ things break if this is not True
assert Factors({S.NegativeOne: Rational(3, 2)}) == Factors({I: S.One, S.NegativeOne: S.One})
assert Factors({I: S.One, S.NegativeOne: Rational(1, 3)}).as_expr() == I*(-1)**Rational(1, 3)
assert Factors(-1.) == Factors({S.NegativeOne: S.One, S(1.): 1})
assert Factors(-2.) == Factors({S.NegativeOne: S.One, S(2.): 1})
assert Factors((-2.)**x) == Factors({S(-2.): x})
assert Factors(S(-2)) == Factors({S.NegativeOne: S.One, S(2): 1})
assert Factors(S.Half) == Factors({S(2): -S.One})
assert Factors(Rational(3, 2)) == Factors({S(3): S.One, S(2): S.NegativeOne})
assert Factors({I: S.One}) == Factors(I)
assert Factors({-1.0: 2, I: 1}) == Factors({S(1.0): 1, I: 1})
assert Factors({S.NegativeOne: Rational(-3, 2)}).as_expr() == I
A = symbols('A', commutative=False)
assert Factors(2*A**2) == Factors({S(2): 1, A**2: 1})
assert Factors(I) == Factors({I: S.One})
assert Factors(x).normal(S(2)) == (Factors(x), Factors(S(2)))
assert Factors(x).normal(S.Zero) == (Factors(), Factors(S.Zero))
raises(ZeroDivisionError, lambda: Factors(x).div(S.Zero))
assert Factors(x).mul(S(2)) == Factors(2*x)
assert Factors(x).mul(S.Zero).is_zero
assert Factors(x).mul(1/x).is_one
assert Factors(x**sqrt(2)**3).as_expr() == x**(2*sqrt(2))
assert Factors(x)**Factors(S(2)) == Factors(x**2)
assert Factors(x).gcd(S.Zero) == Factors(x)
assert Factors(x).lcm(S.Zero).is_zero
assert Factors(S.Zero).div(x) == (Factors(S.Zero), Factors())
assert Factors(x).div(x) == (Factors(), Factors())
assert Factors({x: .2})/Factors({x: .2}) == Factors()
assert Factors(x) != Factors()
assert Factors(S.Zero).normal(x) == (Factors(S.Zero), Factors())
n, d = x**(2 + y), x**2
f = Factors(n)
assert f.div(d) == f.normal(d) == (Factors(x**y), Factors())
assert f.gcd(d) == Factors()
d = x**y
assert f.div(d) == f.normal(d) == (Factors(x**2), Factors())
assert f.gcd(d) == Factors(d)
n = d = 2**x
f = Factors(n)
assert f.div(d) == f.normal(d) == (Factors(), Factors())
assert f.gcd(d) == Factors(d)
n, d = 2**x, 2**y
f = Factors(n)
assert f.div(d) == f.normal(d) == (Factors({S(2): x}), Factors({S(2): y}))
assert f.gcd(d) == Factors()
# extraction of constant only
n = x**(x + 3)
assert Factors(n).normal(x**-3) == (Factors({x: x + 6}), Factors({}))
assert Factors(n).normal(x**3) == (Factors({x: x}), Factors({}))
assert Factors(n).normal(x**4) == (Factors({x: x}), Factors({x: 1}))
assert Factors(n).normal(x**(y - 3)) == \
(Factors({x: x + 6}), Factors({x: y}))
assert Factors(n).normal(x**(y + 3)) == (Factors({x: x}), Factors({x: y}))
assert Factors(n).normal(x**(y + 4)) == \
(Factors({x: x}), Factors({x: y + 1}))
assert Factors(n).div(x**-3) == (Factors({x: x + 6}), Factors({}))
assert Factors(n).div(x**3) == (Factors({x: x}), Factors({}))
assert Factors(n).div(x**4) == (Factors({x: x}), Factors({x: 1}))
assert Factors(n).div(x**(y - 3)) == \
(Factors({x: x + 6}), Factors({x: y}))
assert Factors(n).div(x**(y + 3)) == (Factors({x: x}), Factors({x: y}))
assert Factors(n).div(x**(y + 4)) == \
(Factors({x: x}), Factors({x: y + 1}))
assert Factors(3 * x / 2) == Factors({3: 1, 2: -1, x: 1})
assert Factors(x * x / y) == Factors({x: 2, y: -1})
assert Factors(27 * x / y**9) == Factors({27: 1, x: 1, y: -9})
def test_Term():
a = Term(4*x*y**2/z/t**3)
b = Term(2*x**3*y**5/t**3)
assert a == Term(4, Factors({x: 1, y: 2}), Factors({z: 1, t: 3}))
assert b == Term(2, Factors({x: 3, y: 5}), Factors({t: 3}))
assert a.as_expr() == 4*x*y**2/z/t**3
assert b.as_expr() == 2*x**3*y**5/t**3
assert a.inv() == \
Term(S.One/4, Factors({z: 1, t: 3}), Factors({x: 1, y: 2}))
assert b.inv() == Term(S.Half, Factors({t: 3}), Factors({x: 3, y: 5}))
assert a.mul(b) == a*b == \
Term(8, Factors({x: 4, y: 7}), Factors({z: 1, t: 6}))
assert a.quo(b) == a/b == Term(2, Factors({}), Factors({x: 2, y: 3, z: 1}))
assert a.pow(3) == a**3 == \
Term(64, Factors({x: 3, y: 6}), Factors({z: 3, t: 9}))
assert b.pow(3) == b**3 == Term(8, Factors({x: 9, y: 15}), Factors({t: 9}))
assert a.pow(-3) == a**(-3) == \
Term(S.One/64, Factors({z: 3, t: 9}), Factors({x: 3, y: 6}))
assert b.pow(-3) == b**(-3) == \
Term(S.One/8, Factors({t: 9}), Factors({x: 9, y: 15}))
assert a.gcd(b) == Term(2, Factors({x: 1, y: 2}), Factors({t: 3}))
assert a.lcm(b) == Term(4, Factors({x: 3, y: 5}), Factors({z: 1, t: 3}))
a = Term(4*x*y**2/z/t**3)
b = Term(2*x**3*y**5*t**7)
assert a.mul(b) == Term(8, Factors({x: 4, y: 7, t: 4}), Factors({z: 1}))
assert Term((2*x + 2)**3) == Term(8, Factors({x + 1: 3}), Factors({}))
assert Term((2*x + 2)*(3*x + 6)**2) == \
Term(18, Factors({x + 1: 1, x + 2: 2}), Factors({}))
def test_gcd_terms():
f = 2*(x + 1)*(x + 4)/(5*x**2 + 5) + (2*x + 2)*(x + 5)/(x**2 + 1)/5 + \
(2*x + 2)*(x + 6)/(5*x**2 + 5)
assert _gcd_terms(f) == ((Rational(6, 5))*((1 + x)/(1 + x**2)), 5 + x, 1)
assert _gcd_terms(Add.make_args(f)) == \
((Rational(6, 5))*((1 + x)/(1 + x**2)), 5 + x, 1)
newf = (Rational(6, 5))*((1 + x)*(5 + x)/(1 + x**2))
assert gcd_terms(f) == newf
args = Add.make_args(f)
# non-Basic sequences of terms treated as terms of Add
assert gcd_terms(list(args)) == newf
assert gcd_terms(tuple(args)) == newf
assert gcd_terms(set(args)) == newf
# but a Basic sequence is treated as a container
assert gcd_terms(Tuple(*args)) != newf
assert gcd_terms(Basic(Tuple(S(1), 3*y + 3*x*y), Tuple(S(1), S(3)))) == \
Basic(Tuple(S(1), 3*y*(x + 1)), Tuple(S(1), S(3)))
# but we shouldn't change keys of a dictionary or some may be lost
assert gcd_terms(Dict((x*(1 + y), S(2)), (x + x*y, y + x*y))) == \
Dict({x*(y + 1): S(2), x + x*y: y*(1 + x)})
assert gcd_terms((2*x + 2)**3 + (2*x + 2)**2) == 4*(x + 1)**2*(2*x + 3)
assert gcd_terms(0) == 0
assert gcd_terms(1) == 1
assert gcd_terms(x) == x
assert gcd_terms(2 + 2*x) == Mul(2, 1 + x, evaluate=False)
arg = x*(2*x + 4*y)
garg = 2*x*(x + 2*y)
assert gcd_terms(arg) == garg
assert gcd_terms(sin(arg)) == sin(garg)
# issue 6139-like
alpha, alpha1, alpha2, alpha3 = symbols('alpha:4')
a = alpha**2 - alpha*x**2 + alpha + x**3 - x*(alpha + 1)
rep = (alpha, (1 + sqrt(5))/2 + alpha1*x + alpha2*x**2 + alpha3*x**3)
s = (a/(x - alpha)).subs(*rep).series(x, 0, 1)
assert simplify(collect(s, x)) == -sqrt(5)/2 - Rational(3, 2) + O(x)
# issue 5917
assert _gcd_terms([S.Zero, S.Zero]) == (0, 0, 1)
assert _gcd_terms([2*x + 4]) == (2, x + 2, 1)
eq = x/(x + 1/x)
assert gcd_terms(eq, fraction=False) == eq
eq = x/2/y + 1/x/y
assert gcd_terms(eq, fraction=True, clear=True) == \
(x**2 + 2)/(2*x*y)
assert gcd_terms(eq, fraction=True, clear=False) == \
(x**2/2 + 1)/(x*y)
assert gcd_terms(eq, fraction=False, clear=True) == \
(x + 2/x)/(2*y)
assert gcd_terms(eq, fraction=False, clear=False) == \
(x/2 + 1/x)/y
def test_factor_terms():
A = Symbol('A', commutative=False)
assert factor_terms(9*(x + x*y + 1) + (3*x + 3)**(2 + 2*x)) == \
9*x*y + 9*x + _keep_coeff(S(3), x + 1)**_keep_coeff(S(2), x + 1) + 9
assert factor_terms(9*(x + x*y + 1) + (3)**(2 + 2*x)) == \
_keep_coeff(S(9), 3**(2*x) + x*y + x + 1)
assert factor_terms(3**(2 + 2*x) + a*3**(2 + 2*x)) == \
9*3**(2*x)*(a + 1)
assert factor_terms(x + x*A) == \
x*(1 + A)
assert factor_terms(sin(x + x*A)) == \
sin(x*(1 + A))
assert factor_terms((3*x + 3)**((2 + 2*x)/3)) == \
_keep_coeff(S(3), x + 1)**_keep_coeff(Rational(2, 3), x + 1)
assert factor_terms(x + (x*y + x)**(3*x + 3)) == \
x + (x*(y + 1))**_keep_coeff(S(3), x + 1)
assert factor_terms(a*(x + x*y) + b*(x*2 + y*x*2)) == \
x*(a + 2*b)*(y + 1)
i = Integral(x, (x, 0, oo))
assert factor_terms(i) == i
assert factor_terms(x/2 + y) == x/2 + y
# fraction doesn't apply to integer denominators
assert factor_terms(x/2 + y, fraction=True) == x/2 + y
# clear *does* apply to the integer denominators
assert factor_terms(x/2 + y, clear=True) == Mul(S.Half, x + 2*y, evaluate=False)
# check radical extraction
eq = sqrt(2) + sqrt(10)
assert factor_terms(eq) == eq
assert factor_terms(eq, radical=True) == sqrt(2)*(1 + sqrt(5))
eq = root(-6, 3) + root(6, 3)
assert factor_terms(eq, radical=True) == 6**(S.One/3)*(1 + (-1)**(S.One/3))
eq = [x + x*y]
ans = [x*(y + 1)]
for c in [list, tuple, set]:
assert factor_terms(c(eq)) == c(ans)
assert factor_terms(Tuple(x + x*y)) == Tuple(x*(y + 1))
assert factor_terms(Interval(0, 1)) == Interval(0, 1)
e = 1/sqrt(a/2 + 1)
assert factor_terms(e, clear=False) == 1/sqrt(a/2 + 1)
assert factor_terms(e, clear=True) == sqrt(2)/sqrt(a + 2)
eq = x/(x + 1/x) + 1/(x**2 + 1)
assert factor_terms(eq, fraction=False) == eq
assert factor_terms(eq, fraction=True) == 1
assert factor_terms((1/(x**3 + x**2) + 2/x**2)*y) == \
y*(2 + 1/(x + 1))/x**2
# if not True, then processesing for this in factor_terms is not necessary
assert gcd_terms(-x - y) == -x - y
assert factor_terms(-x - y) == Mul(-1, x + y, evaluate=False)
# if not True, then "special" processesing in factor_terms is not necessary
assert gcd_terms(exp(Mul(-1, x + 1))) == exp(-x - 1)
e = exp(-x - 2) + x
assert factor_terms(e) == exp(Mul(-1, x + 2, evaluate=False)) + x
assert factor_terms(e, sign=False) == e
assert factor_terms(exp(-4*x - 2) - x) == -x + exp(Mul(-2, 2*x + 1, evaluate=False))
# sum/integral tests
for F in (Sum, Integral):
assert factor_terms(F(x, (y, 1, 10))) == x * F(1, (y, 1, 10))
assert factor_terms(F(x, (y, 1, 10)) + x) == x * (1 + F(1, (y, 1, 10)))
assert factor_terms(F(x*y + x*y**2, (y, 1, 10))) == x*F(y*(y + 1), (y, 1, 10))
# expressions involving Pow terms with base 0
assert factor_terms(0**(x - 2) - 1) == 0**(x - 2) - 1
assert factor_terms(0**(x + 2) - 1) == 0**(x + 2) - 1
assert factor_terms((0**(x + 2) - 1).subs(x,-2)) == 0
def test_xreplace():
e = Mul(2, 1 + x, evaluate=False)
assert e.xreplace({}) == e
assert e.xreplace({y: x}) == e
def test_factor_nc():
x, y = symbols('x,y')
k = symbols('k', integer=True)
n, m, o = symbols('n,m,o', commutative=False)
# mul and multinomial expansion is needed
from sympy.core.function import _mexpand
e = x*(1 + y)**2
assert _mexpand(e) == x + x*2*y + x*y**2
def factor_nc_test(e):
ex = _mexpand(e)
assert ex.is_Add
f = factor_nc(ex)
assert not f.is_Add and _mexpand(f) == ex
factor_nc_test(x*(1 + y))
factor_nc_test(n*(x + 1))
factor_nc_test(n*(x + m))
factor_nc_test((x + m)*n)
factor_nc_test(n*m*(x*o + n*o*m)*n)
s = Sum(x, (x, 1, 2))
factor_nc_test(x*(1 + s))
factor_nc_test(x*(1 + s)*s)
factor_nc_test(x*(1 + sin(s)))
factor_nc_test((1 + n)**2)
factor_nc_test((x + n)*(x + m)*(x + y))
factor_nc_test(x*(n*m + 1))
factor_nc_test(x*(n*m + x))
factor_nc_test(x*(x*n*m + 1))
factor_nc_test(n*(m/x + o))
factor_nc_test(m*(n + o/2))
factor_nc_test(x*n*(x*m + 1))
factor_nc_test(x*(m*n + x*n*m))
factor_nc_test(n*(1 - m)*n**2)
factor_nc_test((n + m)**2)
factor_nc_test((n - m)*(n + m)**2)
factor_nc_test((n + m)**2*(n - m))
factor_nc_test((m - n)*(n + m)**2*(n - m))
assert factor_nc(n*(n + n*m)) == n**2*(1 + m)
assert factor_nc(m*(m*n + n*m*n**2)) == m*(m + n*m*n)*n
eq = m*sin(n) - sin(n)*m
assert factor_nc(eq) == eq
# for coverage:
from sympy.physics.secondquant import Commutator
from sympy.polys.polytools import factor
eq = 1 + x*Commutator(m, n)
assert factor_nc(eq) == eq
eq = x*Commutator(m, n) + x*Commutator(m, o)*Commutator(m, n)
assert factor(eq) == x*(1 + Commutator(m, o))*Commutator(m, n)
# issue 6534
assert (2*n + 2*m).factor() == 2*(n + m)
# issue 6701
assert factor_nc(n**k + n**(k + 1)) == n**k*(1 + n)
assert factor_nc((m*n)**k + (m*n)**(k + 1)) == (1 + m*n)*(m*n)**k
# issue 6918
assert factor_nc(-n*(2*x**2 + 2*x)) == -2*n*x*(x + 1)
def test_issue_6360():
a, b = symbols("a b")
apb = a + b
eq = apb + apb**2*(-2*a - 2*b)
assert factor_terms(sub_pre(eq)) == a + b - 2*(a + b)**3
def test_issue_7903():
a = symbols(r'a', real=True)
t = exp(I*cos(a)) + exp(-I*sin(a))
assert t.simplify()
def test_issue_8263():
F, G = symbols('F, G', commutative=False, cls=Function)
x, y = symbols('x, y')
expr, dummies, _ = _mask_nc(F(x)*G(y) - G(y)*F(x))
for v in dummies.values():
assert not v.is_commutative
assert not expr.is_zero
def test_monotonic_sign():
F = _monotonic_sign
x = symbols('x')
assert F(x) is None
assert F(-x) is None
assert F(Dummy(prime=True)) == 2
assert F(Dummy(prime=True, odd=True)) == 3
assert F(Dummy(composite=True)) == 4
assert F(Dummy(composite=True, odd=True)) == 9
assert F(Dummy(positive=True, integer=True)) == 1
assert F(Dummy(positive=True, even=True)) == 2
assert F(Dummy(positive=True, even=True, prime=False)) == 4
assert F(Dummy(negative=True, integer=True)) == -1
assert F(Dummy(negative=True, even=True)) == -2
assert F(Dummy(zero=True)) == 0
assert F(Dummy(nonnegative=True)) == 0
assert F(Dummy(nonpositive=True)) == 0
assert F(Dummy(positive=True) + 1).is_positive
assert F(Dummy(positive=True, integer=True) - 1).is_nonnegative
assert F(Dummy(positive=True) - 1) is None
assert F(Dummy(negative=True) + 1) is None
assert F(Dummy(negative=True, integer=True) - 1).is_nonpositive
assert F(Dummy(negative=True) - 1).is_negative
assert F(-Dummy(positive=True) + 1) is None
assert F(-Dummy(positive=True, integer=True) - 1).is_negative
assert F(-Dummy(positive=True) - 1).is_negative
assert F(-Dummy(negative=True) + 1).is_positive
assert F(-Dummy(negative=True, integer=True) - 1).is_nonnegative
assert F(-Dummy(negative=True) - 1) is None
x = Dummy(negative=True)
assert F(x**3).is_nonpositive
assert F(x**3 + log(2)*x - 1).is_negative
x = Dummy(positive=True)
assert F(-x**3).is_nonpositive
p = Dummy(positive=True)
assert F(1/p).is_positive
assert F(p/(p + 1)).is_positive
p = Dummy(nonnegative=True)
assert F(p/(p + 1)).is_nonnegative
p = Dummy(positive=True)
assert F(-1/p).is_negative
p = Dummy(nonpositive=True)
assert F(p/(-p + 1)).is_nonpositive
p = Dummy(positive=True, integer=True)
q = Dummy(positive=True, integer=True)
assert F(-2/p/q).is_negative
assert F(-2/(p - 1)/q) is None
assert F((p - 1)*q + 1).is_positive
assert F(-(p - 1)*q - 1).is_negative
def test_issue_17256():
from sympy.sets.fancysets import Range
x = Symbol('x')
s1 = Sum(x + 1, (x, 1, 9))
s2 = Sum(x + 1, (x, Range(1, 10)))
a = Symbol('a')
r1 = s1.xreplace({x:a})
r2 = s2.xreplace({x:a})
assert r1.doit() == r2.doit()
s1 = Sum(x + 1, (x, 0, 9))
s2 = Sum(x + 1, (x, Range(10)))
a = Symbol('a')
r1 = s1.xreplace({x:a})
r2 = s2.xreplace({x:a})
assert r1 == r2
def test_issue_21623():
from sympy.matrices.expressions.matexpr import MatrixSymbol
M = MatrixSymbol('X', 2, 2)
assert gcd_terms(M[0,0], 1) == M[0,0]
|
faedad0188d9cd4c90386d5cbbd32e063afa5cf26740453363de188f02126fbc | from sympy.core import (
Basic, Rational, Symbol, S, Float, Integer, Mul, Number, Pow,
Expr, I, nan, pi, symbols, oo, zoo, N)
from sympy.core.parameters import global_parameters
from sympy.core.tests.test_evalf import NS
from sympy.core.function import expand_multinomial
from sympy.functions.elementary.miscellaneous import sqrt, cbrt
from sympy.functions.elementary.exponential import exp, log
from sympy.functions.special.error_functions import erf
from sympy.functions.elementary.trigonometric import (
sin, cos, tan, sec, csc, atan)
from sympy.functions.elementary.hyperbolic import cosh, sinh, tanh
from sympy.polys import Poly
from sympy.series.order import O
from sympy.sets import FiniteSet
from sympy.core.power import power, integer_nthroot
from sympy.testing.pytest import warns, _both_exp_pow
from sympy.utilities.exceptions import SymPyDeprecationWarning
def test_rational():
a = Rational(1, 5)
r = sqrt(5)/5
assert sqrt(a) == r
assert 2*sqrt(a) == 2*r
r = a*a**S.Half
assert a**Rational(3, 2) == r
assert 2*a**Rational(3, 2) == 2*r
r = a**5*a**Rational(2, 3)
assert a**Rational(17, 3) == r
assert 2 * a**Rational(17, 3) == 2*r
def test_large_rational():
e = (Rational(123712**12 - 1, 7) + Rational(1, 7))**Rational(1, 3)
assert e == 234232585392159195136 * (Rational(1, 7)**Rational(1, 3))
def test_negative_real():
def feq(a, b):
return abs(a - b) < 1E-10
assert feq(S.One / Float(-0.5), -Integer(2))
def test_expand():
x = Symbol('x')
assert (2**(-1 - x)).expand() == S.Half*2**(-x)
def test_issue_3449():
#test if powers are simplified correctly
#see also issue 3995
x = Symbol('x')
assert ((x**Rational(1, 3))**Rational(2)) == x**Rational(2, 3)
assert (
(x**Rational(3))**Rational(2, 5)) == (x**Rational(3))**Rational(2, 5)
a = Symbol('a', real=True)
b = Symbol('b', real=True)
assert (a**2)**b == (abs(a)**b)**2
assert sqrt(1/a) != 1/sqrt(a) # e.g. for a = -1
assert (a**3)**Rational(1, 3) != a
assert (x**a)**b != x**(a*b) # e.g. x = -1, a=2, b=1/2
assert (x**.5)**b == x**(.5*b)
assert (x**.5)**.5 == x**.25
assert (x**2.5)**.5 != x**1.25 # e.g. for x = 5*I
k = Symbol('k', integer=True)
m = Symbol('m', integer=True)
assert (x**k)**m == x**(k*m)
assert Number(5)**Rational(2, 3) == Number(25)**Rational(1, 3)
assert (x**.5)**2 == x**1.0
assert (x**2)**k == (x**k)**2 == x**(2*k)
a = Symbol('a', positive=True)
assert (a**3)**Rational(2, 5) == a**Rational(6, 5)
assert (a**2)**b == (a**b)**2
assert (a**Rational(2, 3))**x == a**(x*Rational(2, 3)) != (a**x)**Rational(2, 3)
def test_issue_3866():
assert --sqrt(sqrt(5) - 1) == sqrt(sqrt(5) - 1)
def test_negative_one():
x = Symbol('x', complex=True)
y = Symbol('y', complex=True)
assert 1/x**y == x**(-y)
def test_issue_4362():
neg = Symbol('neg', negative=True)
nonneg = Symbol('nonneg', nonnegative=True)
any = Symbol('any')
num, den = sqrt(1/neg).as_numer_denom()
assert num == sqrt(-1)
assert den == sqrt(-neg)
num, den = sqrt(1/nonneg).as_numer_denom()
assert num == 1
assert den == sqrt(nonneg)
num, den = sqrt(1/any).as_numer_denom()
assert num == sqrt(1/any)
assert den == 1
def eqn(num, den, pow):
return (num/den)**pow
npos = 1
nneg = -1
dpos = 2 - sqrt(3)
dneg = 1 - sqrt(3)
assert dpos > 0 and dneg < 0 and npos > 0 and nneg < 0
# pos or neg integer
eq = eqn(npos, dpos, 2)
assert eq.is_Pow and eq.as_numer_denom() == (1, dpos**2)
eq = eqn(npos, dneg, 2)
assert eq.is_Pow and eq.as_numer_denom() == (1, dneg**2)
eq = eqn(nneg, dpos, 2)
assert eq.is_Pow and eq.as_numer_denom() == (1, dpos**2)
eq = eqn(nneg, dneg, 2)
assert eq.is_Pow and eq.as_numer_denom() == (1, dneg**2)
eq = eqn(npos, dpos, -2)
assert eq.is_Pow and eq.as_numer_denom() == (dpos**2, 1)
eq = eqn(npos, dneg, -2)
assert eq.is_Pow and eq.as_numer_denom() == (dneg**2, 1)
eq = eqn(nneg, dpos, -2)
assert eq.is_Pow and eq.as_numer_denom() == (dpos**2, 1)
eq = eqn(nneg, dneg, -2)
assert eq.is_Pow and eq.as_numer_denom() == (dneg**2, 1)
# pos or neg rational
pow = S.Half
eq = eqn(npos, dpos, pow)
assert eq.is_Pow and eq.as_numer_denom() == (npos**pow, dpos**pow)
eq = eqn(npos, dneg, pow)
assert eq.is_Pow is False and eq.as_numer_denom() == ((-npos)**pow, (-dneg)**pow)
eq = eqn(nneg, dpos, pow)
assert not eq.is_Pow or eq.as_numer_denom() == (nneg**pow, dpos**pow)
eq = eqn(nneg, dneg, pow)
assert eq.is_Pow and eq.as_numer_denom() == ((-nneg)**pow, (-dneg)**pow)
eq = eqn(npos, dpos, -pow)
assert eq.is_Pow and eq.as_numer_denom() == (dpos**pow, npos**pow)
eq = eqn(npos, dneg, -pow)
assert eq.is_Pow is False and eq.as_numer_denom() == (-(-npos)**pow*(-dneg)**pow, npos)
eq = eqn(nneg, dpos, -pow)
assert not eq.is_Pow or eq.as_numer_denom() == (dpos**pow, nneg**pow)
eq = eqn(nneg, dneg, -pow)
assert eq.is_Pow and eq.as_numer_denom() == ((-dneg)**pow, (-nneg)**pow)
# unknown exponent
pow = 2*any
eq = eqn(npos, dpos, pow)
assert eq.is_Pow and eq.as_numer_denom() == (npos**pow, dpos**pow)
eq = eqn(npos, dneg, pow)
assert eq.is_Pow and eq.as_numer_denom() == ((-npos)**pow, (-dneg)**pow)
eq = eqn(nneg, dpos, pow)
assert eq.is_Pow and eq.as_numer_denom() == (nneg**pow, dpos**pow)
eq = eqn(nneg, dneg, pow)
assert eq.is_Pow and eq.as_numer_denom() == ((-nneg)**pow, (-dneg)**pow)
eq = eqn(npos, dpos, -pow)
assert eq.as_numer_denom() == (dpos**pow, npos**pow)
eq = eqn(npos, dneg, -pow)
assert eq.is_Pow and eq.as_numer_denom() == ((-dneg)**pow, (-npos)**pow)
eq = eqn(nneg, dpos, -pow)
assert eq.is_Pow and eq.as_numer_denom() == (dpos**pow, nneg**pow)
eq = eqn(nneg, dneg, -pow)
assert eq.is_Pow and eq.as_numer_denom() == ((-dneg)**pow, (-nneg)**pow)
x = Symbol('x')
y = Symbol('y')
assert ((1/(1 + x/3))**(-S.One)).as_numer_denom() == (3 + x, 3)
notp = Symbol('notp', positive=False) # not positive does not imply real
b = ((1 + x/notp)**-2)
assert (b**(-y)).as_numer_denom() == (1, b**y)
assert (b**(-S.One)).as_numer_denom() == ((notp + x)**2, notp**2)
nonp = Symbol('nonp', nonpositive=True)
assert (((1 + x/nonp)**-2)**(-S.One)).as_numer_denom() == ((-nonp -
x)**2, nonp**2)
n = Symbol('n', negative=True)
assert (x**n).as_numer_denom() == (1, x**-n)
assert sqrt(1/n).as_numer_denom() == (S.ImaginaryUnit, sqrt(-n))
n = Symbol('0 or neg', nonpositive=True)
# if x and n are split up without negating each term and n is negative
# then the answer might be wrong; if n is 0 it won't matter since
# 1/oo and 1/zoo are both zero as is sqrt(0)/sqrt(-x) unless x is also
# zero (in which case the negative sign doesn't matter):
# 1/sqrt(1/-1) = -I but sqrt(-1)/sqrt(1) = I
assert (1/sqrt(x/n)).as_numer_denom() == (sqrt(-n), sqrt(-x))
c = Symbol('c', complex=True)
e = sqrt(1/c)
assert e.as_numer_denom() == (e, 1)
i = Symbol('i', integer=True)
assert ((1 + x/y)**i).as_numer_denom() == ((x + y)**i, y**i)
def test_Pow_Expr_args():
x = Symbol('x')
bases = [Basic(), Poly(x, x), FiniteSet(x)]
for base in bases:
# The cache can mess with the stacklevel test
with warns(SymPyDeprecationWarning, test_stacklevel=False):
Pow(base, S.One)
def test_Pow_signs():
"""Cf. issues 4595 and 5250"""
x = Symbol('x')
y = Symbol('y')
n = Symbol('n', even=True)
assert (3 - y)**2 != (y - 3)**2
assert (3 - y)**n != (y - 3)**n
assert (-3 + y - x)**2 != (3 - y + x)**2
assert (y - 3)**3 != -(3 - y)**3
def test_power_with_noncommutative_mul_as_base():
x = Symbol('x', commutative=False)
y = Symbol('y', commutative=False)
assert not (x*y)**3 == x**3*y**3
assert (2*x*y)**3 == 8*(x*y)**3
@_both_exp_pow
def test_power_rewrite_exp():
assert (I**I).rewrite(exp) == exp(-pi/2)
expr = (2 + 3*I)**(4 + 5*I)
assert expr.rewrite(exp) == exp((4 + 5*I)*(log(sqrt(13)) + I*atan(Rational(3, 2))))
assert expr.rewrite(exp).expand() == \
169*exp(5*I*log(13)/2)*exp(4*I*atan(Rational(3, 2)))*exp(-5*atan(Rational(3, 2)))
assert ((6 + 7*I)**5).rewrite(exp) == 7225*sqrt(85)*exp(5*I*atan(Rational(7, 6)))
expr = 5**(6 + 7*I)
assert expr.rewrite(exp) == exp((6 + 7*I)*log(5))
assert expr.rewrite(exp).expand() == 15625*exp(7*I*log(5))
assert Pow(123, 789, evaluate=False).rewrite(exp) == 123**789
assert (1**I).rewrite(exp) == 1**I
assert (0**I).rewrite(exp) == 0**I
expr = (-2)**(2 + 5*I)
assert expr.rewrite(exp) == exp((2 + 5*I)*(log(2) + I*pi))
assert expr.rewrite(exp).expand() == 4*exp(-5*pi)*exp(5*I*log(2))
assert ((-2)**S(-5)).rewrite(exp) == (-2)**S(-5)
x, y = symbols('x y')
assert (x**y).rewrite(exp) == exp(y*log(x))
if global_parameters.exp_is_pow:
assert (7**x).rewrite(exp) == Pow(S.Exp1, x*log(7), evaluate=False)
else:
assert (7**x).rewrite(exp) == exp(x*log(7), evaluate=False)
assert ((2 + 3*I)**x).rewrite(exp) == exp(x*(log(sqrt(13)) + I*atan(Rational(3, 2))))
assert (y**(5 + 6*I)).rewrite(exp) == exp(log(y)*(5 + 6*I))
assert all((1/func(x)).rewrite(exp) == 1/(func(x).rewrite(exp)) for func in
(sin, cos, tan, sec, csc, sinh, cosh, tanh))
def test_zero():
x = Symbol('x')
y = Symbol('y')
assert 0**x != 0
assert 0**(2*x) == 0**x
assert 0**(1.0*x) == 0**x
assert 0**(2.0*x) == 0**x
assert (0**(2 - x)).as_base_exp() == (0, 2 - x)
assert 0**(x - 2) != S.Infinity**(2 - x)
assert 0**(2*x*y) == 0**(x*y)
assert 0**(-2*x*y) == S.ComplexInfinity**(x*y)
assert Float(0)**2 is not S.Zero
assert Float(0)**2 == 0.0
assert Float(0)**-2 is zoo
assert Float(0)**oo is S.Zero
#Test issue 19572
assert 0 ** -oo is zoo
assert power(0, -oo) is zoo
assert Float(0)**-oo is zoo
def test_pow_as_base_exp():
x = Symbol('x')
assert (S.Infinity**(2 - x)).as_base_exp() == (S.Infinity, 2 - x)
assert (S.Infinity**(x - 2)).as_base_exp() == (S.Infinity, x - 2)
p = S.Half**x
assert p.base, p.exp == p.as_base_exp() == (S(2), -x)
# issue 8344:
assert Pow(1, 2, evaluate=False).as_base_exp() == (S.One, S(2))
def test_nseries():
x = Symbol('x')
assert sqrt(I*x - 1)._eval_nseries(x, 4, None, 1) == I + x/2 + I*x**2/8 - x**3/16 + O(x**4)
assert sqrt(I*x - 1)._eval_nseries(x, 4, None, -1) == -I - x/2 - I*x**2/8 + x**3/16 + O(x**4)
assert cbrt(I*x - 1)._eval_nseries(x, 4, None, 1) == (-1)**(S(1)/3) - (-1)**(S(5)/6)*x/3 + \
(-1)**(S(1)/3)*x**2/9 + 5*(-1)**(S(5)/6)*x**3/81 + O(x**4)
assert cbrt(I*x - 1)._eval_nseries(x, 4, None, -1) == -(-1)**(S(2)/3) - (-1)**(S(1)/6)*x/3 - \
(-1)**(S(2)/3)*x**2/9 + 5*(-1)**(S(1)/6)*x**3/81 + O(x**4)
assert (1 / (exp(-1/x) + 1/x))._eval_nseries(x, 2, None) == x + O(x**2)
# test issue 23752
assert sqrt(-I*x**2 + x - 3)._eval_nseries(x, 4, None, 1) == -sqrt(3)*I + sqrt(3)*I*x/6 - \
sqrt(3)*I*x**2*(-S(1)/72 + I/6) - sqrt(3)*I*x**3*(-S(1)/432 + I/36) + O(x**4)
assert sqrt(-I*x**2 + x - 3)._eval_nseries(x, 4, None, -1) == -sqrt(3)*I + sqrt(3)*I*x/6 - \
sqrt(3)*I*x**2*(-S(1)/72 + I/6) - sqrt(3)*I*x**3*(-S(1)/432 + I/36) + O(x**4)
assert cbrt(-I*x**2 + x - 3)._eval_nseries(x, 4, None, 1) == -(-1)**(S(2)/3)*3**(S(1)/3) + \
(-1)**(S(2)/3)*3**(S(1)/3)*x/9 - (-1)**(S(2)/3)*3**(S(1)/3)*x**2*(-S(1)/81 + I/9) - \
(-1)**(S(2)/3)*3**(S(1)/3)*x**3*(-S(5)/2187 + 2*I/81) + O(x**4)
assert cbrt(-I*x**2 + x - 3)._eval_nseries(x, 4, None, -1) == -(-1)**(S(2)/3)*3**(S(1)/3) + \
(-1)**(S(2)/3)*3**(S(1)/3)*x/9 - (-1)**(S(2)/3)*3**(S(1)/3)*x**2*(-S(1)/81 + I/9) - \
(-1)**(S(2)/3)*3**(S(1)/3)*x**3*(-S(5)/2187 + 2*I/81) + O(x**4)
def test_issue_6100_12942_4473():
x = Symbol('x')
y = Symbol('y')
assert x**1.0 != x
assert x != x**1.0
assert True != x**1.0
assert x**1.0 is not True
assert x is not True
assert x*y != (x*y)**1.0
# Pow != Symbol
assert (x**1.0)**1.0 != x
assert (x**1.0)**2.0 != x**2
b = Expr()
assert Pow(b, 1.0, evaluate=False) != b
# if the following gets distributed as a Mul (x**1.0*y**1.0 then
# __eq__ methods could be added to Symbol and Pow to detect the
# power-of-1.0 case.
assert ((x*y)**1.0).func is Pow
def test_issue_6208():
from sympy.functions.elementary.miscellaneous import root
assert sqrt(33**(I*9/10)) == -33**(I*9/20)
assert root((6*I)**(2*I), 3).as_base_exp()[1] == Rational(1, 3) # != 2*I/3
assert root((6*I)**(I/3), 3).as_base_exp()[1] == I/9
assert sqrt(exp(3*I)) == exp(3*I/2)
assert sqrt(-sqrt(3)*(1 + 2*I)) == sqrt(sqrt(3))*sqrt(-1 - 2*I)
assert sqrt(exp(5*I)) == -exp(5*I/2)
assert root(exp(5*I), 3).exp == Rational(1, 3)
def test_issue_6990():
x = Symbol('x')
a = Symbol('a')
b = Symbol('b')
assert (sqrt(a + b*x + x**2)).series(x, 0, 3).removeO() == \
sqrt(a)*x**2*(1/(2*a) - b**2/(8*a**2)) + sqrt(a) + b*x/(2*sqrt(a))
def test_issue_6068():
x = Symbol('x')
assert sqrt(sin(x)).series(x, 0, 7) == \
sqrt(x) - x**Rational(5, 2)/12 + x**Rational(9, 2)/1440 - \
x**Rational(13, 2)/24192 + O(x**7)
assert sqrt(sin(x)).series(x, 0, 9) == \
sqrt(x) - x**Rational(5, 2)/12 + x**Rational(9, 2)/1440 - \
x**Rational(13, 2)/24192 - 67*x**Rational(17, 2)/29030400 + O(x**9)
assert sqrt(sin(x**3)).series(x, 0, 19) == \
x**Rational(3, 2) - x**Rational(15, 2)/12 + x**Rational(27, 2)/1440 + O(x**19)
assert sqrt(sin(x**3)).series(x, 0, 20) == \
x**Rational(3, 2) - x**Rational(15, 2)/12 + x**Rational(27, 2)/1440 - \
x**Rational(39, 2)/24192 + O(x**20)
def test_issue_6782():
x = Symbol('x')
assert sqrt(sin(x**3)).series(x, 0, 7) == x**Rational(3, 2) + O(x**7)
assert sqrt(sin(x**4)).series(x, 0, 3) == x**2 + O(x**3)
def test_issue_6653():
x = Symbol('x')
assert (1 / sqrt(1 + sin(x**2))).series(x, 0, 3) == 1 - x**2/2 + O(x**3)
def test_issue_6429():
x = Symbol('x')
c = Symbol('c')
f = (c**2 + x)**(0.5)
assert f.series(x, x0=0, n=1) == (c**2)**0.5 + O(x)
assert f.taylor_term(0, x) == (c**2)**0.5
assert f.taylor_term(1, x) == 0.5*x*(c**2)**(-0.5)
assert f.taylor_term(2, x) == -0.125*x**2*(c**2)**(-1.5)
def test_issue_7638():
f = pi/log(sqrt(2))
assert ((1 + I)**(I*f/2))**0.3 == (1 + I)**(0.15*I*f)
# if 1/3 -> 1.0/3 this should fail since it cannot be shown that the
# sign will be +/-1; for the previous "small arg" case, it didn't matter
# that this could not be proved
assert (1 + I)**(4*I*f) == ((1 + I)**(12*I*f))**Rational(1, 3)
assert (((1 + I)**(I*(1 + 7*f)))**Rational(1, 3)).exp == Rational(1, 3)
r = symbols('r', real=True)
assert sqrt(r**2) == abs(r)
assert cbrt(r**3) != r
assert sqrt(Pow(2*I, 5*S.Half)) != (2*I)**Rational(5, 4)
p = symbols('p', positive=True)
assert cbrt(p**2) == p**Rational(2, 3)
assert NS(((0.2 + 0.7*I)**(0.7 + 1.0*I))**(0.5 - 0.1*I), 1) == '0.4 + 0.2*I'
assert sqrt(1/(1 + I)) == sqrt(1 - I)/sqrt(2) # or 1/sqrt(1 + I)
e = 1/(1 - sqrt(2))
assert sqrt(e) == I/sqrt(-1 + sqrt(2))
assert e**Rational(-1, 2) == -I*sqrt(-1 + sqrt(2))
assert sqrt((cos(1)**2 + sin(1)**2 - 1)**(3 + I)).exp in [S.Half,
Rational(3, 2) + I/2]
assert sqrt(r**Rational(4, 3)) != r**Rational(2, 3)
assert sqrt((p + I)**Rational(4, 3)) == (p + I)**Rational(2, 3)
for q in 1+I, 1-I:
assert sqrt(q**2) == q
for q in -1+I, -1-I:
assert sqrt(q**2) == -q
assert sqrt((p + r*I)**2) != p + r*I
e = (1 + I/5)
assert sqrt(e**5) == e**(5*S.Half)
assert sqrt(e**6) == e**3
assert sqrt((1 + I*r)**6) != (1 + I*r)**3
def test_issue_8582():
assert 1**oo is nan
assert 1**(-oo) is nan
assert 1**zoo is nan
assert 1**(oo + I) is nan
assert 1**(1 + I*oo) is nan
assert 1**(oo + I*oo) is nan
def test_issue_8650():
n = Symbol('n', integer=True, nonnegative=True)
assert (n**n).is_positive is True
x = 5*n + 5
assert (x**(5*(n + 1))).is_positive is True
def test_issue_13914():
b = Symbol('b')
assert (-1)**zoo is nan
assert 2**zoo is nan
assert (S.Half)**(1 + zoo) is nan
assert I**(zoo + I) is nan
assert b**(I + zoo) is nan
def test_better_sqrt():
n = Symbol('n', integer=True, nonnegative=True)
assert sqrt(3 + 4*I) == 2 + I
assert sqrt(3 - 4*I) == 2 - I
assert sqrt(-3 - 4*I) == 1 - 2*I
assert sqrt(-3 + 4*I) == 1 + 2*I
assert sqrt(32 + 24*I) == 6 + 2*I
assert sqrt(32 - 24*I) == 6 - 2*I
assert sqrt(-32 - 24*I) == 2 - 6*I
assert sqrt(-32 + 24*I) == 2 + 6*I
# triple (3, 4, 5):
# parity of 3 matches parity of 5 and
# den, 4, is a square
assert sqrt((3 + 4*I)/4) == 1 + I/2
# triple (8, 15, 17)
# parity of 8 doesn't match parity of 17 but
# den/2, 8/2, is a square
assert sqrt((8 + 15*I)/8) == (5 + 3*I)/4
# handle the denominator
assert sqrt((3 - 4*I)/25) == (2 - I)/5
assert sqrt((3 - 4*I)/26) == (2 - I)/sqrt(26)
# mul
# issue #12739
assert sqrt((3 + 4*I)/(3 - 4*I)) == (3 + 4*I)/5
assert sqrt(2/(3 + 4*I)) == sqrt(2)/5*(2 - I)
assert sqrt(n/(3 + 4*I)).subs(n, 2) == sqrt(2)/5*(2 - I)
assert sqrt(-2/(3 + 4*I)) == sqrt(2)/5*(1 + 2*I)
assert sqrt(-n/(3 + 4*I)).subs(n, 2) == sqrt(2)/5*(1 + 2*I)
# power
assert sqrt(1/(3 + I*4)) == (2 - I)/5
assert sqrt(1/(3 - I)) == sqrt(10)*sqrt(3 + I)/10
# symbolic
i = symbols('i', imaginary=True)
assert sqrt(3/i) == Mul(sqrt(3), 1/sqrt(i), evaluate=False)
# multiples of 1/2; don't make this too automatic
assert sqrt(3 + 4*I)**3 == (2 + I)**3
assert Pow(3 + 4*I, Rational(3, 2)) == 2 + 11*I
assert Pow(6 + 8*I, Rational(3, 2)) == 2*sqrt(2)*(2 + 11*I)
n, d = (3 + 4*I), (3 - 4*I)**3
a = n/d
assert a.args == (1/d, n)
eq = sqrt(a)
assert eq.args == (a, S.Half)
assert expand_multinomial(eq) == sqrt((-117 + 44*I)*(3 + 4*I))/125
assert eq.expand() == (7 - 24*I)/125
# issue 12775
# pos im part
assert sqrt(2*I) == (1 + I)
assert sqrt(2*9*I) == Mul(3, 1 + I, evaluate=False)
assert Pow(2*I, 3*S.Half) == (1 + I)**3
# neg im part
assert sqrt(-I/2) == Mul(S.Half, 1 - I, evaluate=False)
# fractional im part
assert Pow(Rational(-9, 2)*I, Rational(3, 2)) == 27*(1 - I)**3/8
def test_issue_2993():
x = Symbol('x')
assert str((2.3*x - 4)**0.3) == '1.5157165665104*(0.575*x - 1)**0.3'
assert str((2.3*x + 4)**0.3) == '1.5157165665104*(0.575*x + 1)**0.3'
assert str((-2.3*x + 4)**0.3) == '1.5157165665104*(1 - 0.575*x)**0.3'
assert str((-2.3*x - 4)**0.3) == '1.5157165665104*(-0.575*x - 1)**0.3'
assert str((2.3*x - 2)**0.3) == '1.28386201800527*(x - 0.869565217391304)**0.3'
assert str((-2.3*x - 2)**0.3) == '1.28386201800527*(-x - 0.869565217391304)**0.3'
assert str((-2.3*x + 2)**0.3) == '1.28386201800527*(0.869565217391304 - x)**0.3'
assert str((2.3*x + 2)**0.3) == '1.28386201800527*(x + 0.869565217391304)**0.3'
assert str((2.3*x - 4)**Rational(1, 3)) == '2**(2/3)*(0.575*x - 1)**(1/3)'
eq = (2.3*x + 4)
assert eq**2 == 16*(0.575*x + 1)**2
assert (1/eq).args == (eq, -1) # don't change trivial power
# issue 17735
q=.5*exp(x) - .5*exp(-x) + 0.1
assert int((q**2).subs(x, 1)) == 1
# issue 17756
y = Symbol('y')
assert len(sqrt(x/(x + y)**2 + Float('0.008', 30)).subs(y, pi.n(25)).atoms(Float)) == 2
# issue 17756
a, b, c, d, e, f, g = symbols('a:g')
expr = sqrt(1 + a*(c**4 + g*d - 2*g*e - f*(-g + d))**2/
(c**3*b**2*(d - 3*e + 2*f)**2))/2
r = [
(a, N('0.0170992456333788667034850458615', 30)),
(b, N('0.0966594956075474769169134801223', 30)),
(c, N('0.390911862903463913632151616184', 30)),
(d, N('0.152812084558656566271750185933', 30)),
(e, N('0.137562344465103337106561623432', 30)),
(f, N('0.174259178881496659302933610355', 30)),
(g, N('0.220745448491223779615401870086', 30))]
tru = expr.n(30, subs=dict(r))
seq = expr.subs(r)
# although `tru` is the right way to evaluate
# expr with numerical values, `seq` will have
# significant loss of precision if extraction of
# the largest coefficient of a power's base's terms
# is done improperly
assert seq == tru
def test_issue_17450():
assert (erf(cosh(1)**7)**I).is_real is None
assert (erf(cosh(1)**7)**I).is_imaginary is False
assert (Pow(exp(1+sqrt(2)), ((1-sqrt(2))*I*pi), evaluate=False)).is_real is None
assert ((-10)**(10*I*pi/3)).is_real is False
assert ((-5)**(4*I*pi)).is_real is False
def test_issue_18190():
assert sqrt(1 / tan(1 + I)) == 1 / sqrt(tan(1 + I))
def test_issue_14815():
x = Symbol('x', real=True)
assert sqrt(x).is_extended_negative is False
x = Symbol('x', real=False)
assert sqrt(x).is_extended_negative is None
x = Symbol('x', complex=True)
assert sqrt(x).is_extended_negative is False
x = Symbol('x', extended_real=True)
assert sqrt(x).is_extended_negative is False
assert sqrt(zoo, evaluate=False).is_extended_negative is None
assert sqrt(nan, evaluate=False).is_extended_negative is None
def test_issue_18509():
x = Symbol('x', prime=True)
assert x**oo is oo
assert (1/x)**oo is S.Zero
assert (-1/x)**oo is S.Zero
assert (-x)**oo is zoo
assert (-oo)**(-1 + I) is S.Zero
assert (-oo)**(1 + I) is zoo
assert (oo)**(-1 + I) is S.Zero
assert (oo)**(1 + I) is zoo
def test_issue_18762():
e, p = symbols('e p')
g0 = sqrt(1 + e**2 - 2*e*cos(p))
assert len(g0.series(e, 1, 3).args) == 4
def test_issue_21860():
x = Symbol('x')
e = 3*2**Rational(66666666667,200000000000)*3**Rational(16666666667,50000000000)*x**Rational(66666666667, 200000000000)
ans = Mul(Rational(3, 2),
Pow(Integer(2), Rational(33333333333, 100000000000)),
Pow(Integer(3), Rational(26666666667, 40000000000)))
assert e.xreplace({x: Rational(3,8)}) == ans
def test_issue_21647():
x = Symbol('x')
e = log((Integer(567)/500)**(811*(Integer(567)/500)**x/100))
ans = log(Mul(Rational(64701150190720499096094005280169087619821081527,
76293945312500000000000000000000000000000000000),
Pow(Integer(2), Rational(396204892125479941, 781250000000000000)),
Pow(Integer(3), Rational(385045107874520059, 390625000000000000)),
Pow(Integer(5), Rational(407364676376439823, 1562500000000000000)),
Pow(Integer(7), Rational(385045107874520059, 1562500000000000000))))
assert e.xreplace({x: 6}) == ans
def test_issue_21762():
x = Symbol('x')
e = (x**2 + 6)**(Integer(33333333333333333)/50000000000000000)
ans = Mul(Rational(5, 4),
Pow(Integer(2), Rational(16666666666666667, 25000000000000000)),
Pow(Integer(5), Rational(8333333333333333, 25000000000000000)))
assert e.xreplace({x: S.Half}) == ans
def test_issue_14704():
a = 144**144
x, xexact = integer_nthroot(a,a)
assert x == 1 and xexact is False
def test_rational_powers_larger_than_one():
assert Rational(2, 3)**Rational(3, 2) == 2*sqrt(6)/9
assert Rational(1, 6)**Rational(9, 4) == 6**Rational(3, 4)/216
assert Rational(3, 7)**Rational(7, 3) == 9*3**Rational(1, 3)*7**Rational(2, 3)/343
def test_power_dispatcher():
class NewBase(Expr):
pass
class NewPow(NewBase, Pow):
pass
a, b = Symbol('a'), NewBase()
@power.register(Expr, NewBase)
@power.register(NewBase, Expr)
@power.register(NewBase, NewBase)
def _(a, b):
return NewPow(a, b)
# Pow called as fallback
assert power(2, 3) == 8*S.One
assert power(a, 2) == Pow(a, 2)
assert power(a, a) == Pow(a, a)
# NewPow called by dispatch
assert power(a, b) == NewPow(a, b)
assert power(b, a) == NewPow(b, a)
assert power(b, b) == NewPow(b, b)
def test_powers_of_I():
assert [sqrt(I)**i for i in range(13)] == [
1, sqrt(I), I, sqrt(I)**3, -1, -sqrt(I), -I, -sqrt(I)**3,
1, sqrt(I), I, sqrt(I)**3, -1]
assert sqrt(I)**(S(9)/2) == -I**(S(1)/4)
|
61aaa6a0d712b8bbe8a7d43dd3e32d1954a4608588284fbce71e262e425820c2 | """Minimal polynomials for algebraic numbers."""
from functools import reduce
from sympy.core.add import Add
from sympy.core.exprtools import Factors
from sympy.core.function import expand_mul, expand_multinomial, _mexpand
from sympy.core.mul import Mul
from sympy.core.numbers import (I, Rational, pi, _illegal)
from sympy.core.singleton import S
from sympy.core.symbol import Dummy
from sympy.core.sympify import sympify
from sympy.core.traversal import preorder_traversal
from sympy.functions.elementary.exponential import exp
from sympy.functions.elementary.miscellaneous import sqrt, cbrt
from sympy.functions.elementary.trigonometric import cos, sin, tan
from sympy.ntheory.factor_ import divisors
from sympy.utilities.iterables import subsets
from sympy.polys.domains import ZZ, QQ, FractionField
from sympy.polys.orthopolys import dup_chebyshevt
from sympy.polys.polyerrors import (
NotAlgebraic,
GeneratorsError,
)
from sympy.polys.polytools import (
Poly, PurePoly, invert, factor_list, groebner, resultant,
degree, poly_from_expr, parallel_poly_from_expr, lcm
)
from sympy.polys.polyutils import dict_from_expr, expr_from_dict
from sympy.polys.ring_series import rs_compose_add
from sympy.polys.rings import ring
from sympy.polys.rootoftools import CRootOf
from sympy.polys.specialpolys import cyclotomic_poly
from sympy.utilities import (
numbered_symbols, public, sift
)
def _choose_factor(factors, x, v, dom=QQ, prec=200, bound=5):
"""
Return a factor having root ``v``
It is assumed that one of the factors has root ``v``.
"""
if isinstance(factors[0], tuple):
factors = [f[0] for f in factors]
if len(factors) == 1:
return factors[0]
prec1 = 10
points = {}
symbols = dom.symbols if hasattr(dom, 'symbols') else []
while prec1 <= prec:
# when dealing with non-Rational numbers we usually evaluate
# with `subs` argument but we only need a ballpark evaluation
fe = [f.as_expr().xreplace({x:v}) for f in factors]
if v.is_number:
fe = [f.n(prec) for f in fe]
# assign integers [0, n) to symbols (if any)
for n in subsets(range(bound), k=len(symbols), repetition=True):
for s, i in zip(symbols, n):
points[s] = i
# evaluate the expression at these points
candidates = [(abs(f.subs(points).n(prec1)), i)
for i,f in enumerate(fe)]
# if we get invalid numbers (e.g. from division by zero)
# we try again
if any(i in _illegal for i, _ in candidates):
continue
# find the smallest two -- if they differ significantly
# then we assume we have found the factor that becomes
# 0 when v is substituted into it
can = sorted(candidates)
(a, ix), (b, _) = can[:2]
if b > a * 10**6: # XXX what to use?
return factors[ix]
prec1 *= 2
raise NotImplementedError("multiple candidates for the minimal polynomial of %s" % v)
def _is_sum_surds(p):
args = p.args if p.is_Add else [p]
for y in args:
if not ((y**2).is_Rational and y.is_extended_real):
return False
return True
def _separate_sq(p):
"""
helper function for ``_minimal_polynomial_sq``
It selects a rational ``g`` such that the polynomial ``p``
consists of a sum of terms whose surds squared have gcd equal to ``g``
and a sum of terms with surds squared prime with ``g``;
then it takes the field norm to eliminate ``sqrt(g)``
See simplify.simplify.split_surds and polytools.sqf_norm.
Examples
========
>>> from sympy import sqrt
>>> from sympy.abc import x
>>> from sympy.polys.numberfields.minpoly import _separate_sq
>>> p= -x + sqrt(2) + sqrt(3) + sqrt(7)
>>> p = _separate_sq(p); p
-x**2 + 2*sqrt(3)*x + 2*sqrt(7)*x - 2*sqrt(21) - 8
>>> p = _separate_sq(p); p
-x**4 + 4*sqrt(7)*x**3 - 32*x**2 + 8*sqrt(7)*x + 20
>>> p = _separate_sq(p); p
-x**8 + 48*x**6 - 536*x**4 + 1728*x**2 - 400
"""
def is_sqrt(expr):
return expr.is_Pow and expr.exp is S.Half
# p = c1*sqrt(q1) + ... + cn*sqrt(qn) -> a = [(c1, q1), .., (cn, qn)]
a = []
for y in p.args:
if not y.is_Mul:
if is_sqrt(y):
a.append((S.One, y**2))
elif y.is_Atom:
a.append((y, S.One))
elif y.is_Pow and y.exp.is_integer:
a.append((y, S.One))
else:
raise NotImplementedError
else:
T, F = sift(y.args, is_sqrt, binary=True)
a.append((Mul(*F), Mul(*T)**2))
a.sort(key=lambda z: z[1])
if a[-1][1] is S.One:
# there are no surds
return p
surds = [z for y, z in a]
for i in range(len(surds)):
if surds[i] != 1:
break
from sympy.simplify.radsimp import _split_gcd
g, b1, b2 = _split_gcd(*surds[i:])
a1 = []
a2 = []
for y, z in a:
if z in b1:
a1.append(y*z**S.Half)
else:
a2.append(y*z**S.Half)
p1 = Add(*a1)
p2 = Add(*a2)
p = _mexpand(p1**2) - _mexpand(p2**2)
return p
def _minimal_polynomial_sq(p, n, x):
"""
Returns the minimal polynomial for the ``nth-root`` of a sum of surds
or ``None`` if it fails.
Parameters
==========
p : sum of surds
n : positive integer
x : variable of the returned polynomial
Examples
========
>>> from sympy.polys.numberfields.minpoly import _minimal_polynomial_sq
>>> from sympy import sqrt
>>> from sympy.abc import x
>>> q = 1 + sqrt(2) + sqrt(3)
>>> _minimal_polynomial_sq(q, 3, x)
x**12 - 4*x**9 - 4*x**6 + 16*x**3 - 8
"""
p = sympify(p)
n = sympify(n)
if not n.is_Integer or not n > 0 or not _is_sum_surds(p):
return None
pn = p**Rational(1, n)
# eliminate the square roots
p -= x
while 1:
p1 = _separate_sq(p)
if p1 is p:
p = p1.subs({x:x**n})
break
else:
p = p1
# _separate_sq eliminates field extensions in a minimal way, so that
# if n = 1 then `p = constant*(minimal_polynomial(p))`
# if n > 1 it contains the minimal polynomial as a factor.
if n == 1:
p1 = Poly(p)
if p.coeff(x**p1.degree(x)) < 0:
p = -p
p = p.primitive()[1]
return p
# by construction `p` has root `pn`
# the minimal polynomial is the factor vanishing in x = pn
factors = factor_list(p)[1]
result = _choose_factor(factors, x, pn)
return result
def _minpoly_op_algebraic_element(op, ex1, ex2, x, dom, mp1=None, mp2=None):
"""
return the minimal polynomial for ``op(ex1, ex2)``
Parameters
==========
op : operation ``Add`` or ``Mul``
ex1, ex2 : expressions for the algebraic elements
x : indeterminate of the polynomials
dom: ground domain
mp1, mp2 : minimal polynomials for ``ex1`` and ``ex2`` or None
Examples
========
>>> from sympy import sqrt, Add, Mul, QQ
>>> from sympy.polys.numberfields.minpoly import _minpoly_op_algebraic_element
>>> from sympy.abc import x, y
>>> p1 = sqrt(sqrt(2) + 1)
>>> p2 = sqrt(sqrt(2) - 1)
>>> _minpoly_op_algebraic_element(Mul, p1, p2, x, QQ)
x - 1
>>> q1 = sqrt(y)
>>> q2 = 1 / y
>>> _minpoly_op_algebraic_element(Add, q1, q2, x, QQ.frac_field(y))
x**2*y**2 - 2*x*y - y**3 + 1
References
==========
.. [1] https://en.wikipedia.org/wiki/Resultant
.. [2] I.M. Isaacs, Proc. Amer. Math. Soc. 25 (1970), 638
"Degrees of sums in a separable field extension".
"""
y = Dummy(str(x))
if mp1 is None:
mp1 = _minpoly_compose(ex1, x, dom)
if mp2 is None:
mp2 = _minpoly_compose(ex2, y, dom)
else:
mp2 = mp2.subs({x: y})
if op is Add:
# mp1a = mp1.subs({x: x - y})
if dom == QQ:
R, X = ring('X', QQ)
p1 = R(dict_from_expr(mp1)[0])
p2 = R(dict_from_expr(mp2)[0])
else:
(p1, p2), _ = parallel_poly_from_expr((mp1, x - y), x, y)
r = p1.compose(p2)
mp1a = r.as_expr()
elif op is Mul:
mp1a = _muly(mp1, x, y)
else:
raise NotImplementedError('option not available')
if op is Mul or dom != QQ:
r = resultant(mp1a, mp2, gens=[y, x])
else:
r = rs_compose_add(p1, p2)
r = expr_from_dict(r.as_expr_dict(), x)
deg1 = degree(mp1, x)
deg2 = degree(mp2, y)
if op is Mul and deg1 == 1 or deg2 == 1:
# if deg1 = 1, then mp1 = x - a; mp1a = x - y - a;
# r = mp2(x - a), so that `r` is irreducible
return r
r = Poly(r, x, domain=dom)
_, factors = r.factor_list()
res = _choose_factor(factors, x, op(ex1, ex2), dom)
return res.as_expr()
def _invertx(p, x):
"""
Returns ``expand_mul(x**degree(p, x)*p.subs(x, 1/x))``
"""
p1 = poly_from_expr(p, x)[0]
n = degree(p1)
a = [c * x**(n - i) for (i,), c in p1.terms()]
return Add(*a)
def _muly(p, x, y):
"""
Returns ``_mexpand(y**deg*p.subs({x:x / y}))``
"""
p1 = poly_from_expr(p, x)[0]
n = degree(p1)
a = [c * x**i * y**(n - i) for (i,), c in p1.terms()]
return Add(*a)
def _minpoly_pow(ex, pw, x, dom, mp=None):
"""
Returns ``minpoly(ex**pw, x)``
Parameters
==========
ex : algebraic element
pw : rational number
x : indeterminate of the polynomial
dom: ground domain
mp : minimal polynomial of ``p``
Examples
========
>>> from sympy import sqrt, QQ, Rational
>>> from sympy.polys.numberfields.minpoly import _minpoly_pow, minpoly
>>> from sympy.abc import x, y
>>> p = sqrt(1 + sqrt(2))
>>> _minpoly_pow(p, 2, x, QQ)
x**2 - 2*x - 1
>>> minpoly(p**2, x)
x**2 - 2*x - 1
>>> _minpoly_pow(y, Rational(1, 3), x, QQ.frac_field(y))
x**3 - y
>>> minpoly(y**Rational(1, 3), x)
x**3 - y
"""
pw = sympify(pw)
if not mp:
mp = _minpoly_compose(ex, x, dom)
if not pw.is_rational:
raise NotAlgebraic("%s does not seem to be an algebraic element" % ex)
if pw < 0:
if mp == x:
raise ZeroDivisionError('%s is zero' % ex)
mp = _invertx(mp, x)
if pw == -1:
return mp
pw = -pw
ex = 1/ex
y = Dummy(str(x))
mp = mp.subs({x: y})
n, d = pw.as_numer_denom()
res = Poly(resultant(mp, x**d - y**n, gens=[y]), x, domain=dom)
_, factors = res.factor_list()
res = _choose_factor(factors, x, ex**pw, dom)
return res.as_expr()
def _minpoly_add(x, dom, *a):
"""
returns ``minpoly(Add(*a), dom, x)``
"""
mp = _minpoly_op_algebraic_element(Add, a[0], a[1], x, dom)
p = a[0] + a[1]
for px in a[2:]:
mp = _minpoly_op_algebraic_element(Add, p, px, x, dom, mp1=mp)
p = p + px
return mp
def _minpoly_mul(x, dom, *a):
"""
returns ``minpoly(Mul(*a), dom, x)``
"""
mp = _minpoly_op_algebraic_element(Mul, a[0], a[1], x, dom)
p = a[0] * a[1]
for px in a[2:]:
mp = _minpoly_op_algebraic_element(Mul, p, px, x, dom, mp1=mp)
p = p * px
return mp
def _minpoly_sin(ex, x):
"""
Returns the minimal polynomial of ``sin(ex)``
see http://mathworld.wolfram.com/TrigonometryAngles.html
"""
c, a = ex.args[0].as_coeff_Mul()
if a is pi:
if c.is_rational:
n = c.q
q = sympify(n)
if q.is_prime:
# for a = pi*p/q with q odd prime, using chebyshevt
# write sin(q*a) = mp(sin(a))*sin(a);
# the roots of mp(x) are sin(pi*p/q) for p = 1,..., q - 1
a = dup_chebyshevt(n, ZZ)
return Add(*[x**(n - i - 1)*a[i] for i in range(n)])
if c.p == 1:
if q == 9:
return 64*x**6 - 96*x**4 + 36*x**2 - 3
if n % 2 == 1:
# for a = pi*p/q with q odd, use
# sin(q*a) = 0 to see that the minimal polynomial must be
# a factor of dup_chebyshevt(n, ZZ)
a = dup_chebyshevt(n, ZZ)
a = [x**(n - i)*a[i] for i in range(n + 1)]
r = Add(*a)
_, factors = factor_list(r)
res = _choose_factor(factors, x, ex)
return res
expr = ((1 - cos(2*c*pi))/2)**S.Half
res = _minpoly_compose(expr, x, QQ)
return res
raise NotAlgebraic("%s does not seem to be an algebraic element" % ex)
def _minpoly_cos(ex, x):
"""
Returns the minimal polynomial of ``cos(ex)``
see http://mathworld.wolfram.com/TrigonometryAngles.html
"""
c, a = ex.args[0].as_coeff_Mul()
if a is pi:
if c.is_rational:
if c.p == 1:
if c.q == 7:
return 8*x**3 - 4*x**2 - 4*x + 1
if c.q == 9:
return 8*x**3 - 6*x - 1
elif c.p == 2:
q = sympify(c.q)
if q.is_prime:
s = _minpoly_sin(ex, x)
return _mexpand(s.subs({x:sqrt((1 - x)/2)}))
# for a = pi*p/q, cos(q*a) =T_q(cos(a)) = (-1)**p
n = int(c.q)
a = dup_chebyshevt(n, ZZ)
a = [x**(n - i)*a[i] for i in range(n + 1)]
r = Add(*a) - (-1)**c.p
_, factors = factor_list(r)
res = _choose_factor(factors, x, ex)
return res
raise NotAlgebraic("%s does not seem to be an algebraic element" % ex)
def _minpoly_tan(ex, x):
"""
Returns the minimal polynomial of ``tan(ex)``
see https://github.com/sympy/sympy/issues/21430
"""
c, a = ex.args[0].as_coeff_Mul()
if a is pi:
if c.is_rational:
c = c * 2
n = int(c.q)
a = n if c.p % 2 == 0 else 1
terms = []
for k in range((c.p+1)%2, n+1, 2):
terms.append(a*x**k)
a = -(a*(n-k-1)*(n-k)) // ((k+1)*(k+2))
r = Add(*terms)
_, factors = factor_list(r)
res = _choose_factor(factors, x, ex)
return res
raise NotAlgebraic("%s does not seem to be an algebraic element" % ex)
def _minpoly_exp(ex, x):
"""
Returns the minimal polynomial of ``exp(ex)``
"""
c, a = ex.args[0].as_coeff_Mul()
if a == I*pi:
if c.is_rational:
q = sympify(c.q)
if c.p == 1 or c.p == -1:
if q == 3:
return x**2 - x + 1
if q == 4:
return x**4 + 1
if q == 6:
return x**4 - x**2 + 1
if q == 8:
return x**8 + 1
if q == 9:
return x**6 - x**3 + 1
if q == 10:
return x**8 - x**6 + x**4 - x**2 + 1
if q.is_prime:
s = 0
for i in range(q):
s += (-x)**i
return s
# x**(2*q) = product(factors)
factors = [cyclotomic_poly(i, x) for i in divisors(2*q)]
mp = _choose_factor(factors, x, ex)
return mp
else:
raise NotAlgebraic("%s does not seem to be an algebraic element" % ex)
raise NotAlgebraic("%s does not seem to be an algebraic element" % ex)
def _minpoly_rootof(ex, x):
"""
Returns the minimal polynomial of a ``CRootOf`` object.
"""
p = ex.expr
p = p.subs({ex.poly.gens[0]:x})
_, factors = factor_list(p, x)
result = _choose_factor(factors, x, ex)
return result
def _minpoly_compose(ex, x, dom):
"""
Computes the minimal polynomial of an algebraic element
using operations on minimal polynomials
Examples
========
>>> from sympy import minimal_polynomial, sqrt, Rational
>>> from sympy.abc import x, y
>>> minimal_polynomial(sqrt(2) + 3*Rational(1, 3), x, compose=True)
x**2 - 2*x - 1
>>> minimal_polynomial(sqrt(y) + 1/y, x, compose=True)
x**2*y**2 - 2*x*y - y**3 + 1
"""
if ex.is_Rational:
return ex.q*x - ex.p
if ex is I:
_, factors = factor_list(x**2 + 1, x, domain=dom)
return x**2 + 1 if len(factors) == 1 else x - I
if ex is S.GoldenRatio:
_, factors = factor_list(x**2 - x - 1, x, domain=dom)
if len(factors) == 1:
return x**2 - x - 1
else:
return _choose_factor(factors, x, (1 + sqrt(5))/2, dom=dom)
if ex is S.TribonacciConstant:
_, factors = factor_list(x**3 - x**2 - x - 1, x, domain=dom)
if len(factors) == 1:
return x**3 - x**2 - x - 1
else:
fac = (1 + cbrt(19 - 3*sqrt(33)) + cbrt(19 + 3*sqrt(33))) / 3
return _choose_factor(factors, x, fac, dom=dom)
if hasattr(dom, 'symbols') and ex in dom.symbols:
return x - ex
if dom.is_QQ and _is_sum_surds(ex):
# eliminate the square roots
ex -= x
while 1:
ex1 = _separate_sq(ex)
if ex1 is ex:
return ex
else:
ex = ex1
if ex.is_Add:
res = _minpoly_add(x, dom, *ex.args)
elif ex.is_Mul:
f = Factors(ex).factors
r = sift(f.items(), lambda itx: itx[0].is_Rational and itx[1].is_Rational)
if r[True] and dom == QQ:
ex1 = Mul(*[bx**ex for bx, ex in r[False] + r[None]])
r1 = dict(r[True])
dens = [y.q for y in r1.values()]
lcmdens = reduce(lcm, dens, 1)
neg1 = S.NegativeOne
expn1 = r1.pop(neg1, S.Zero)
nums = [base**(y.p*lcmdens // y.q) for base, y in r1.items()]
ex2 = Mul(*nums)
mp1 = minimal_polynomial(ex1, x)
# use the fact that in SymPy canonicalization products of integers
# raised to rational powers are organized in relatively prime
# bases, and that in ``base**(n/d)`` a perfect power is
# simplified with the root
# Powers of -1 have to be treated separately to preserve sign.
mp2 = ex2.q*x**lcmdens - ex2.p*neg1**(expn1*lcmdens)
ex2 = neg1**expn1 * ex2**Rational(1, lcmdens)
res = _minpoly_op_algebraic_element(Mul, ex1, ex2, x, dom, mp1=mp1, mp2=mp2)
else:
res = _minpoly_mul(x, dom, *ex.args)
elif ex.is_Pow:
res = _minpoly_pow(ex.base, ex.exp, x, dom)
elif ex.__class__ is sin:
res = _minpoly_sin(ex, x)
elif ex.__class__ is cos:
res = _minpoly_cos(ex, x)
elif ex.__class__ is tan:
res = _minpoly_tan(ex, x)
elif ex.__class__ is exp:
res = _minpoly_exp(ex, x)
elif ex.__class__ is CRootOf:
res = _minpoly_rootof(ex, x)
else:
raise NotAlgebraic("%s does not seem to be an algebraic element" % ex)
return res
@public
def minimal_polynomial(ex, x=None, compose=True, polys=False, domain=None):
"""
Computes the minimal polynomial of an algebraic element.
Parameters
==========
ex : Expr
Element or expression whose minimal polynomial is to be calculated.
x : Symbol, optional
Independent variable of the minimal polynomial
compose : boolean, optional (default=True)
Method to use for computing minimal polynomial. If ``compose=True``
(default) then ``_minpoly_compose`` is used, if ``compose=False`` then
groebner bases are used.
polys : boolean, optional (default=False)
If ``True`` returns a ``Poly`` object else an ``Expr`` object.
domain : Domain, optional
Ground domain
Notes
=====
By default ``compose=True``, the minimal polynomial of the subexpressions of ``ex``
are computed, then the arithmetic operations on them are performed using the resultant
and factorization.
If ``compose=False``, a bottom-up algorithm is used with ``groebner``.
The default algorithm stalls less frequently.
If no ground domain is given, it will be generated automatically from the expression.
Examples
========
>>> from sympy import minimal_polynomial, sqrt, solve, QQ
>>> from sympy.abc import x, y
>>> minimal_polynomial(sqrt(2), x)
x**2 - 2
>>> minimal_polynomial(sqrt(2), x, domain=QQ.algebraic_field(sqrt(2)))
x - sqrt(2)
>>> minimal_polynomial(sqrt(2) + sqrt(3), x)
x**4 - 10*x**2 + 1
>>> minimal_polynomial(solve(x**3 + x + 3)[0], x)
x**3 + x + 3
>>> minimal_polynomial(sqrt(y), x)
x**2 - y
"""
ex = sympify(ex)
if ex.is_number:
# not sure if it's always needed but try it for numbers (issue 8354)
ex = _mexpand(ex, recursive=True)
for expr in preorder_traversal(ex):
if expr.is_AlgebraicNumber:
compose = False
break
if x is not None:
x, cls = sympify(x), Poly
else:
x, cls = Dummy('x'), PurePoly
if not domain:
if ex.free_symbols:
domain = FractionField(QQ, list(ex.free_symbols))
else:
domain = QQ
if hasattr(domain, 'symbols') and x in domain.symbols:
raise GeneratorsError("the variable %s is an element of the ground "
"domain %s" % (x, domain))
if compose:
result = _minpoly_compose(ex, x, domain)
result = result.primitive()[1]
c = result.coeff(x**degree(result, x))
if c.is_negative:
result = expand_mul(-result)
return cls(result, x, field=True) if polys else result.collect(x)
if not domain.is_QQ:
raise NotImplementedError("groebner method only works for QQ")
result = _minpoly_groebner(ex, x, cls)
return cls(result, x, field=True) if polys else result.collect(x)
def _minpoly_groebner(ex, x, cls):
"""
Computes the minimal polynomial of an algebraic number
using Groebner bases
Examples
========
>>> from sympy import minimal_polynomial, sqrt, Rational
>>> from sympy.abc import x
>>> minimal_polynomial(sqrt(2) + 3*Rational(1, 3), x, compose=False)
x**2 - 2*x - 1
"""
generator = numbered_symbols('a', cls=Dummy)
mapping, symbols = {}, {}
def update_mapping(ex, exp, base=None):
a = next(generator)
symbols[ex] = a
if base is not None:
mapping[ex] = a**exp + base
else:
mapping[ex] = exp.as_expr(a)
return a
def bottom_up_scan(ex):
"""
Transform a given algebraic expression *ex* into a multivariate
polynomial, by introducing fresh variables with defining equations.
Explanation
===========
The critical elements of the algebraic expression *ex* are root
extractions, instances of :py:class:`~.AlgebraicNumber`, and negative
powers.
When we encounter a root extraction or an :py:class:`~.AlgebraicNumber`
we replace this expression with a fresh variable ``a_i``, and record
the defining polynomial for ``a_i``. For example, if ``a_0**(1/3)``
occurs, we will replace it with ``a_1``, and record the new defining
polynomial ``a_1**3 - a_0``.
When we encounter a negative power we transform it into a positive
power by algebraically inverting the base. This means computing the
minimal polynomial in ``x`` for the base, inverting ``x`` modulo this
poly (which generates a new polynomial) and then substituting the
original base expression for ``x`` in this last polynomial.
We return the transformed expression, and we record the defining
equations for new symbols using the ``update_mapping()`` function.
"""
if ex.is_Atom:
if ex is S.ImaginaryUnit:
if ex not in mapping:
return update_mapping(ex, 2, 1)
else:
return symbols[ex]
elif ex.is_Rational:
return ex
elif ex.is_Add:
return Add(*[ bottom_up_scan(g) for g in ex.args ])
elif ex.is_Mul:
return Mul(*[ bottom_up_scan(g) for g in ex.args ])
elif ex.is_Pow:
if ex.exp.is_Rational:
if ex.exp < 0:
minpoly_base = _minpoly_groebner(ex.base, x, cls)
inverse = invert(x, minpoly_base).as_expr()
base_inv = inverse.subs(x, ex.base).expand()
if ex.exp == -1:
return bottom_up_scan(base_inv)
else:
ex = base_inv**(-ex.exp)
if not ex.exp.is_Integer:
base, exp = (
ex.base**ex.exp.p).expand(), Rational(1, ex.exp.q)
else:
base, exp = ex.base, ex.exp
base = bottom_up_scan(base)
expr = base**exp
if expr not in mapping:
if exp.is_Integer:
return expr.expand()
else:
return update_mapping(expr, 1 / exp, -base)
else:
return symbols[expr]
elif ex.is_AlgebraicNumber:
if ex not in mapping:
return update_mapping(ex, ex.minpoly_of_element())
else:
return symbols[ex]
raise NotAlgebraic("%s does not seem to be an algebraic number" % ex)
def simpler_inverse(ex):
"""
Returns True if it is more likely that the minimal polynomial
algorithm works better with the inverse
"""
if ex.is_Pow:
if (1/ex.exp).is_integer and ex.exp < 0:
if ex.base.is_Add:
return True
if ex.is_Mul:
hit = True
for p in ex.args:
if p.is_Add:
return False
if p.is_Pow:
if p.base.is_Add and p.exp > 0:
return False
if hit:
return True
return False
inverted = False
ex = expand_multinomial(ex)
if ex.is_AlgebraicNumber:
return ex.minpoly_of_element().as_expr(x)
elif ex.is_Rational:
result = ex.q*x - ex.p
else:
inverted = simpler_inverse(ex)
if inverted:
ex = ex**-1
res = None
if ex.is_Pow and (1/ex.exp).is_Integer:
n = 1/ex.exp
res = _minimal_polynomial_sq(ex.base, n, x)
elif _is_sum_surds(ex):
res = _minimal_polynomial_sq(ex, S.One, x)
if res is not None:
result = res
if res is None:
bus = bottom_up_scan(ex)
F = [x - bus] + list(mapping.values())
G = groebner(F, list(symbols.values()) + [x], order='lex')
_, factors = factor_list(G[-1])
# by construction G[-1] has root `ex`
result = _choose_factor(factors, x, ex)
if inverted:
result = _invertx(result, x)
if result.coeff(x**degree(result, x)) < 0:
result = expand_mul(-result)
return result
@public
def minpoly(ex, x=None, compose=True, polys=False, domain=None):
"""This is a synonym for :py:func:`~.minimal_polynomial`."""
return minimal_polynomial(ex, x=x, compose=compose, polys=polys, domain=domain)
|
27121c827c801687348c9da080e7ae4dcc44d2f5ff85a536c96ffb4096a376b5 | """
Module for the DomainMatrix class.
A DomainMatrix represents a matrix with elements that are in a particular
Domain. Each DomainMatrix internally wraps a DDM which is used for the
lower-level operations. The idea is that the DomainMatrix class provides the
convenience routines for converting between Expr and the poly domains as well
as unifying matrices with different domains.
"""
from functools import reduce
from typing import Union as tUnion, Tuple as tTuple
from sympy.core.sympify import _sympify
from ..domains import Domain
from ..constructor import construct_domain
from .exceptions import (DMNonSquareMatrixError, DMShapeError,
DMDomainError, DMFormatError, DMBadInputError,
DMNotAField)
from .ddm import DDM
from .sdm import SDM
from .domainscalar import DomainScalar
from sympy.polys.domains import ZZ, EXRAW
def DM(rows, domain):
"""Convenient alias for DomainMatrix.from_list
Examples
=======
>>> from sympy import ZZ
>>> from sympy.polys.matrices import DM
>>> DM([[1, 2], [3, 4]], ZZ)
DomainMatrix([[1, 2], [3, 4]], (2, 2), ZZ)
See also
=======
DomainMatrix.from_list
"""
return DomainMatrix.from_list(rows, domain)
class DomainMatrix:
r"""
Associate Matrix with :py:class:`~.Domain`
Explanation
===========
DomainMatrix uses :py:class:`~.Domain` for its internal representation
which makes it faster than the SymPy Matrix class (currently) for many
common operations, but this advantage makes it not entirely compatible
with Matrix. DomainMatrix are analogous to numpy arrays with "dtype".
In the DomainMatrix, each element has a domain such as :ref:`ZZ`
or :ref:`QQ(a)`.
Examples
========
Creating a DomainMatrix from the existing Matrix class:
>>> from sympy import Matrix
>>> from sympy.polys.matrices import DomainMatrix
>>> Matrix1 = Matrix([
... [1, 2],
... [3, 4]])
>>> A = DomainMatrix.from_Matrix(Matrix1)
>>> A
DomainMatrix({0: {0: 1, 1: 2}, 1: {0: 3, 1: 4}}, (2, 2), ZZ)
Directly forming a DomainMatrix:
>>> from sympy import ZZ
>>> from sympy.polys.matrices import DomainMatrix
>>> A = DomainMatrix([
... [ZZ(1), ZZ(2)],
... [ZZ(3), ZZ(4)]], (2, 2), ZZ)
>>> A
DomainMatrix([[1, 2], [3, 4]], (2, 2), ZZ)
See Also
========
DDM
SDM
Domain
Poly
"""
rep: tUnion[SDM, DDM]
shape: tTuple[int, int]
domain: Domain
def __new__(cls, rows, shape, domain, *, fmt=None):
"""
Creates a :py:class:`~.DomainMatrix`.
Parameters
==========
rows : Represents elements of DomainMatrix as list of lists
shape : Represents dimension of DomainMatrix
domain : Represents :py:class:`~.Domain` of DomainMatrix
Raises
======
TypeError
If any of rows, shape and domain are not provided
"""
if isinstance(rows, (DDM, SDM)):
raise TypeError("Use from_rep to initialise from SDM/DDM")
elif isinstance(rows, list):
rep = DDM(rows, shape, domain)
elif isinstance(rows, dict):
rep = SDM(rows, shape, domain)
else:
msg = "Input should be list-of-lists or dict-of-dicts"
raise TypeError(msg)
if fmt is not None:
if fmt == 'sparse':
rep = rep.to_sdm()
elif fmt == 'dense':
rep = rep.to_ddm()
else:
raise ValueError("fmt should be 'sparse' or 'dense'")
return cls.from_rep(rep)
def __getnewargs__(self):
rep = self.rep
if isinstance(rep, DDM):
arg = list(rep)
elif isinstance(rep, SDM):
arg = dict(rep)
else:
raise RuntimeError # pragma: no cover
return arg, self.shape, self.domain
def __getitem__(self, key):
i, j = key
m, n = self.shape
if not (isinstance(i, slice) or isinstance(j, slice)):
return DomainScalar(self.rep.getitem(i, j), self.domain)
if not isinstance(i, slice):
if not -m <= i < m:
raise IndexError("Row index out of range")
i = i % m
i = slice(i, i+1)
if not isinstance(j, slice):
if not -n <= j < n:
raise IndexError("Column index out of range")
j = j % n
j = slice(j, j+1)
return self.from_rep(self.rep.extract_slice(i, j))
def getitem_sympy(self, i, j):
return self.domain.to_sympy(self.rep.getitem(i, j))
def extract(self, rowslist, colslist):
return self.from_rep(self.rep.extract(rowslist, colslist))
def __setitem__(self, key, value):
i, j = key
if not self.domain.of_type(value):
raise TypeError
if isinstance(i, int) and isinstance(j, int):
self.rep.setitem(i, j, value)
else:
raise NotImplementedError
@classmethod
def from_rep(cls, rep):
"""Create a new DomainMatrix efficiently from DDM/SDM.
Examples
========
Create a :py:class:`~.DomainMatrix` with an dense internal
representation as :py:class:`~.DDM`:
>>> from sympy.polys.domains import ZZ
>>> from sympy.polys.matrices import DomainMatrix
>>> from sympy.polys.matrices.ddm import DDM
>>> drep = DDM([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
>>> dM = DomainMatrix.from_rep(drep)
>>> dM
DomainMatrix([[1, 2], [3, 4]], (2, 2), ZZ)
Create a :py:class:`~.DomainMatrix` with a sparse internal
representation as :py:class:`~.SDM`:
>>> from sympy.polys.matrices import DomainMatrix
>>> from sympy.polys.matrices.sdm import SDM
>>> from sympy import ZZ
>>> drep = SDM({0:{1:ZZ(1)},1:{0:ZZ(2)}}, (2, 2), ZZ)
>>> dM = DomainMatrix.from_rep(drep)
>>> dM
DomainMatrix({0: {1: 1}, 1: {0: 2}}, (2, 2), ZZ)
Parameters
==========
rep: SDM or DDM
The internal sparse or dense representation of the matrix.
Returns
=======
DomainMatrix
A :py:class:`~.DomainMatrix` wrapping *rep*.
Notes
=====
This takes ownership of rep as its internal representation. If rep is
being mutated elsewhere then a copy should be provided to
``from_rep``. Only minimal verification or checking is done on *rep*
as this is supposed to be an efficient internal routine.
"""
if not isinstance(rep, (DDM, SDM)):
raise TypeError("rep should be of type DDM or SDM")
self = super().__new__(cls)
self.rep = rep
self.shape = rep.shape
self.domain = rep.domain
return self
@classmethod
def from_list(cls, rows, domain):
r"""
Convert a list of lists into a DomainMatrix
Parameters
==========
rows: list of lists
Each element of the inner lists should be either the single arg,
or tuple of args, that would be passed to the domain constructor
in order to form an element of the domain. See examples.
Returns
=======
DomainMatrix containing elements defined in rows
Examples
========
>>> from sympy.polys.matrices import DomainMatrix
>>> from sympy import FF, QQ, ZZ
>>> A = DomainMatrix.from_list([[1, 0, 1], [0, 0, 1]], ZZ)
>>> A
DomainMatrix([[1, 0, 1], [0, 0, 1]], (2, 3), ZZ)
>>> B = DomainMatrix.from_list([[1, 0, 1], [0, 0, 1]], FF(7))
>>> B
DomainMatrix([[1 mod 7, 0 mod 7, 1 mod 7], [0 mod 7, 0 mod 7, 1 mod 7]], (2, 3), GF(7))
>>> C = DomainMatrix.from_list([[(1, 2), (3, 1)], [(1, 4), (5, 1)]], QQ)
>>> C
DomainMatrix([[1/2, 3], [1/4, 5]], (2, 2), QQ)
See Also
========
from_list_sympy
"""
nrows = len(rows)
ncols = 0 if not nrows else len(rows[0])
conv = lambda e: domain(*e) if isinstance(e, tuple) else domain(e)
domain_rows = [[conv(e) for e in row] for row in rows]
return DomainMatrix(domain_rows, (nrows, ncols), domain)
@classmethod
def from_list_sympy(cls, nrows, ncols, rows, **kwargs):
r"""
Convert a list of lists of Expr into a DomainMatrix using construct_domain
Parameters
==========
nrows: number of rows
ncols: number of columns
rows: list of lists
Returns
=======
DomainMatrix containing elements of rows
Examples
========
>>> from sympy.polys.matrices import DomainMatrix
>>> from sympy.abc import x, y, z
>>> A = DomainMatrix.from_list_sympy(1, 3, [[x, y, z]])
>>> A
DomainMatrix([[x, y, z]], (1, 3), ZZ[x,y,z])
See Also
========
sympy.polys.constructor.construct_domain, from_dict_sympy
"""
assert len(rows) == nrows
assert all(len(row) == ncols for row in rows)
items_sympy = [_sympify(item) for row in rows for item in row]
domain, items_domain = cls.get_domain(items_sympy, **kwargs)
domain_rows = [[items_domain[ncols*r + c] for c in range(ncols)] for r in range(nrows)]
return DomainMatrix(domain_rows, (nrows, ncols), domain)
@classmethod
def from_dict_sympy(cls, nrows, ncols, elemsdict, **kwargs):
"""
Parameters
==========
nrows: number of rows
ncols: number of cols
elemsdict: dict of dicts containing non-zero elements of the DomainMatrix
Returns
=======
DomainMatrix containing elements of elemsdict
Examples
========
>>> from sympy.polys.matrices import DomainMatrix
>>> from sympy.abc import x,y,z
>>> elemsdict = {0: {0:x}, 1:{1: y}, 2: {2: z}}
>>> A = DomainMatrix.from_dict_sympy(3, 3, elemsdict)
>>> A
DomainMatrix({0: {0: x}, 1: {1: y}, 2: {2: z}}, (3, 3), ZZ[x,y,z])
See Also
========
from_list_sympy
"""
if not all(0 <= r < nrows for r in elemsdict):
raise DMBadInputError("Row out of range")
if not all(0 <= c < ncols for row in elemsdict.values() for c in row):
raise DMBadInputError("Column out of range")
items_sympy = [_sympify(item) for row in elemsdict.values() for item in row.values()]
domain, items_domain = cls.get_domain(items_sympy, **kwargs)
idx = 0
items_dict = {}
for i, row in elemsdict.items():
items_dict[i] = {}
for j in row:
items_dict[i][j] = items_domain[idx]
idx += 1
return DomainMatrix(items_dict, (nrows, ncols), domain)
@classmethod
def from_Matrix(cls, M, fmt='sparse',**kwargs):
r"""
Convert Matrix to DomainMatrix
Parameters
==========
M: Matrix
Returns
=======
Returns DomainMatrix with identical elements as M
Examples
========
>>> from sympy import Matrix
>>> from sympy.polys.matrices import DomainMatrix
>>> M = Matrix([
... [1.0, 3.4],
... [2.4, 1]])
>>> A = DomainMatrix.from_Matrix(M)
>>> A
DomainMatrix({0: {0: 1.0, 1: 3.4}, 1: {0: 2.4, 1: 1.0}}, (2, 2), RR)
We can keep internal representation as ddm using fmt='dense'
>>> from sympy import Matrix, QQ
>>> from sympy.polys.matrices import DomainMatrix
>>> A = DomainMatrix.from_Matrix(Matrix([[QQ(1, 2), QQ(3, 4)], [QQ(0, 1), QQ(0, 1)]]), fmt='dense')
>>> A.rep
[[1/2, 3/4], [0, 0]]
See Also
========
Matrix
"""
if fmt == 'dense':
return cls.from_list_sympy(*M.shape, M.tolist(), **kwargs)
return cls.from_dict_sympy(*M.shape, M.todod(), **kwargs)
@classmethod
def get_domain(cls, items_sympy, **kwargs):
K, items_K = construct_domain(items_sympy, **kwargs)
return K, items_K
def copy(self):
return self.from_rep(self.rep.copy())
def convert_to(self, K):
r"""
Change the domain of DomainMatrix to desired domain or field
Parameters
==========
K : Represents the desired domain or field.
Alternatively, ``None`` may be passed, in which case this method
just returns a copy of this DomainMatrix.
Returns
=======
DomainMatrix
DomainMatrix with the desired domain or field
Examples
========
>>> from sympy import ZZ, ZZ_I
>>> from sympy.polys.matrices import DomainMatrix
>>> A = DomainMatrix([
... [ZZ(1), ZZ(2)],
... [ZZ(3), ZZ(4)]], (2, 2), ZZ)
>>> A.convert_to(ZZ_I)
DomainMatrix([[1, 2], [3, 4]], (2, 2), ZZ_I)
"""
if K is None:
return self.copy()
return self.from_rep(self.rep.convert_to(K))
def to_sympy(self):
return self.convert_to(EXRAW)
def to_field(self):
r"""
Returns a DomainMatrix with the appropriate field
Returns
=======
DomainMatrix
DomainMatrix with the appropriate field
Examples
========
>>> from sympy import ZZ
>>> from sympy.polys.matrices import DomainMatrix
>>> A = DomainMatrix([
... [ZZ(1), ZZ(2)],
... [ZZ(3), ZZ(4)]], (2, 2), ZZ)
>>> A.to_field()
DomainMatrix([[1, 2], [3, 4]], (2, 2), QQ)
"""
K = self.domain.get_field()
return self.convert_to(K)
def to_sparse(self):
"""
Return a sparse DomainMatrix representation of *self*.
Examples
========
>>> from sympy.polys.matrices import DomainMatrix
>>> from sympy import QQ
>>> A = DomainMatrix([[1, 0],[0, 2]], (2, 2), QQ)
>>> A.rep
[[1, 0], [0, 2]]
>>> B = A.to_sparse()
>>> B.rep
{0: {0: 1}, 1: {1: 2}}
"""
if self.rep.fmt == 'sparse':
return self
return self.from_rep(SDM.from_ddm(self.rep))
def to_dense(self):
"""
Return a dense DomainMatrix representation of *self*.
Examples
========
>>> from sympy.polys.matrices import DomainMatrix
>>> from sympy import QQ
>>> A = DomainMatrix({0: {0: 1}, 1: {1: 2}}, (2, 2), QQ)
>>> A.rep
{0: {0: 1}, 1: {1: 2}}
>>> B = A.to_dense()
>>> B.rep
[[1, 0], [0, 2]]
"""
if self.rep.fmt == 'dense':
return self
return self.from_rep(SDM.to_ddm(self.rep))
@classmethod
def _unify_domain(cls, *matrices):
"""Convert matrices to a common domain"""
domains = {matrix.domain for matrix in matrices}
if len(domains) == 1:
return matrices
domain = reduce(lambda x, y: x.unify(y), domains)
return tuple(matrix.convert_to(domain) for matrix in matrices)
@classmethod
def _unify_fmt(cls, *matrices, fmt=None):
"""Convert matrices to the same format.
If all matrices have the same format, then return unmodified.
Otherwise convert both to the preferred format given as *fmt* which
should be 'dense' or 'sparse'.
"""
formats = {matrix.rep.fmt for matrix in matrices}
if len(formats) == 1:
return matrices
if fmt == 'sparse':
return tuple(matrix.to_sparse() for matrix in matrices)
elif fmt == 'dense':
return tuple(matrix.to_dense() for matrix in matrices)
else:
raise ValueError("fmt should be 'sparse' or 'dense'")
def unify(self, *others, fmt=None):
"""
Unifies the domains and the format of self and other
matrices.
Parameters
==========
others : DomainMatrix
fmt: string 'dense', 'sparse' or `None` (default)
The preferred format to convert to if self and other are not
already in the same format. If `None` or not specified then no
conversion if performed.
Returns
=======
Tuple[DomainMatrix]
Matrices with unified domain and format
Examples
========
Unify the domain of DomainMatrix that have different domains:
>>> from sympy import ZZ, QQ
>>> from sympy.polys.matrices import DomainMatrix
>>> A = DomainMatrix([[ZZ(1), ZZ(2)]], (1, 2), ZZ)
>>> B = DomainMatrix([[QQ(1, 2), QQ(2)]], (1, 2), QQ)
>>> Aq, Bq = A.unify(B)
>>> Aq
DomainMatrix([[1, 2]], (1, 2), QQ)
>>> Bq
DomainMatrix([[1/2, 2]], (1, 2), QQ)
Unify the format (dense or sparse):
>>> A = DomainMatrix([[ZZ(1), ZZ(2)]], (1, 2), ZZ)
>>> B = DomainMatrix({0:{0: ZZ(1)}}, (2, 2), ZZ)
>>> B.rep
{0: {0: 1}}
>>> A2, B2 = A.unify(B, fmt='dense')
>>> B2.rep
[[1, 0], [0, 0]]
See Also
========
convert_to, to_dense, to_sparse
"""
matrices = (self,) + others
matrices = DomainMatrix._unify_domain(*matrices)
if fmt is not None:
matrices = DomainMatrix._unify_fmt(*matrices, fmt=fmt)
return matrices
def to_Matrix(self):
r"""
Convert DomainMatrix to Matrix
Returns
=======
Matrix
MutableDenseMatrix for the DomainMatrix
Examples
========
>>> from sympy import ZZ
>>> from sympy.polys.matrices import DomainMatrix
>>> A = DomainMatrix([
... [ZZ(1), ZZ(2)],
... [ZZ(3), ZZ(4)]], (2, 2), ZZ)
>>> A.to_Matrix()
Matrix([
[1, 2],
[3, 4]])
See Also
========
from_Matrix
"""
from sympy.matrices.dense import MutableDenseMatrix
elemlist = self.rep.to_list()
elements_sympy = [self.domain.to_sympy(e) for row in elemlist for e in row]
return MutableDenseMatrix(*self.shape, elements_sympy)
def to_list(self):
return self.rep.to_list()
def to_list_flat(self):
return self.rep.to_list_flat()
def to_dok(self):
return self.rep.to_dok()
def __repr__(self):
return 'DomainMatrix(%s, %r, %r)' % (str(self.rep), self.shape, self.domain)
def transpose(self):
"""Matrix transpose of ``self``"""
return self.from_rep(self.rep.transpose())
def flat(self):
rows, cols = self.shape
return [self[i,j].element for i in range(rows) for j in range(cols)]
@property
def is_zero_matrix(self):
return self.rep.is_zero_matrix()
@property
def is_upper(self):
"""
Says whether this matrix is upper-triangular. True can be returned
even if the matrix is not square.
"""
return self.rep.is_upper()
@property
def is_lower(self):
"""
Says whether this matrix is lower-triangular. True can be returned
even if the matrix is not square.
"""
return self.rep.is_lower()
@property
def is_square(self):
return self.shape[0] == self.shape[1]
def rank(self):
rref, pivots = self.rref()
return len(pivots)
def hstack(A, *B):
r"""Horizontally stack the given matrices.
Parameters
==========
B: DomainMatrix
Matrices to stack horizontally.
Returns
=======
DomainMatrix
DomainMatrix by stacking horizontally.
Examples
========
>>> from sympy import ZZ
>>> from sympy.polys.matrices import DomainMatrix
>>> A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
>>> B = DomainMatrix([[ZZ(5), ZZ(6)], [ZZ(7), ZZ(8)]], (2, 2), ZZ)
>>> A.hstack(B)
DomainMatrix([[1, 2, 5, 6], [3, 4, 7, 8]], (2, 4), ZZ)
>>> C = DomainMatrix([[ZZ(9), ZZ(10)], [ZZ(11), ZZ(12)]], (2, 2), ZZ)
>>> A.hstack(B, C)
DomainMatrix([[1, 2, 5, 6, 9, 10], [3, 4, 7, 8, 11, 12]], (2, 6), ZZ)
See Also
========
unify
"""
A, *B = A.unify(*B, fmt='dense')
return DomainMatrix.from_rep(A.rep.hstack(*(Bk.rep for Bk in B)))
def vstack(A, *B):
r"""Vertically stack the given matrices.
Parameters
==========
B: DomainMatrix
Matrices to stack vertically.
Returns
=======
DomainMatrix
DomainMatrix by stacking vertically.
Examples
========
>>> from sympy import ZZ
>>> from sympy.polys.matrices import DomainMatrix
>>> A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ)
>>> B = DomainMatrix([[ZZ(5), ZZ(6)], [ZZ(7), ZZ(8)]], (2, 2), ZZ)
>>> A.vstack(B)
DomainMatrix([[1, 2], [3, 4], [5, 6], [7, 8]], (4, 2), ZZ)
>>> C = DomainMatrix([[ZZ(9), ZZ(10)], [ZZ(11), ZZ(12)]], (2, 2), ZZ)
>>> A.vstack(B, C)
DomainMatrix([[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11, 12]], (6, 2), ZZ)
See Also
========
unify
"""
A, *B = A.unify(*B, fmt='dense')
return DomainMatrix.from_rep(A.rep.vstack(*(Bk.rep for Bk in B)))
def applyfunc(self, func, domain=None):
if domain is None:
domain = self.domain
return self.from_rep(self.rep.applyfunc(func, domain))
def __add__(A, B):
if not isinstance(B, DomainMatrix):
return NotImplemented
A, B = A.unify(B, fmt='dense')
return A.add(B)
def __sub__(A, B):
if not isinstance(B, DomainMatrix):
return NotImplemented
A, B = A.unify(B, fmt='dense')
return A.sub(B)
def __neg__(A):
return A.neg()
def __mul__(A, B):
"""A * B"""
if isinstance(B, DomainMatrix):
A, B = A.unify(B, fmt='dense')
return A.matmul(B)
elif B in A.domain:
return A.scalarmul(B)
elif isinstance(B, DomainScalar):
A, B = A.unify(B)
return A.scalarmul(B.element)
else:
return NotImplemented
def __rmul__(A, B):
if B in A.domain:
return A.rscalarmul(B)
elif isinstance(B, DomainScalar):
A, B = A.unify(B)
return A.rscalarmul(B.element)
else:
return NotImplemented
def __pow__(A, n):
"""A ** n"""
if not isinstance(n, int):
return NotImplemented
return A.pow(n)
def _check(a, op, b, ashape, bshape):
if a.domain != b.domain:
msg = "Domain mismatch: %s %s %s" % (a.domain, op, b.domain)
raise DMDomainError(msg)
if ashape != bshape:
msg = "Shape mismatch: %s %s %s" % (a.shape, op, b.shape)
raise DMShapeError(msg)
if a.rep.fmt != b.rep.fmt:
msg = "Format mismatch: %s %s %s" % (a.rep.fmt, op, b.rep.fmt)
raise DMFormatError(msg)
def add(A, B):
r"""
Adds two DomainMatrix matrices of the same Domain
Parameters
==========
A, B: DomainMatrix
matrices to add
Returns
=======
DomainMatrix
DomainMatrix after Addition
Raises
======
DMShapeError
If the dimensions of the two DomainMatrix are not equal
ValueError
If the domain of the two DomainMatrix are not same
Examples
========
>>> from sympy import ZZ
>>> from sympy.polys.matrices import DomainMatrix
>>> A = DomainMatrix([
... [ZZ(1), ZZ(2)],
... [ZZ(3), ZZ(4)]], (2, 2), ZZ)
>>> B = DomainMatrix([
... [ZZ(4), ZZ(3)],
... [ZZ(2), ZZ(1)]], (2, 2), ZZ)
>>> A.add(B)
DomainMatrix([[5, 5], [5, 5]], (2, 2), ZZ)
See Also
========
sub, matmul
"""
A._check('+', B, A.shape, B.shape)
return A.from_rep(A.rep.add(B.rep))
def sub(A, B):
r"""
Subtracts two DomainMatrix matrices of the same Domain
Parameters
==========
A, B: DomainMatrix
matrices to substract
Returns
=======
DomainMatrix
DomainMatrix after Substraction
Raises
======
DMShapeError
If the dimensions of the two DomainMatrix are not equal
ValueError
If the domain of the two DomainMatrix are not same
Examples
========
>>> from sympy import ZZ
>>> from sympy.polys.matrices import DomainMatrix
>>> A = DomainMatrix([
... [ZZ(1), ZZ(2)],
... [ZZ(3), ZZ(4)]], (2, 2), ZZ)
>>> B = DomainMatrix([
... [ZZ(4), ZZ(3)],
... [ZZ(2), ZZ(1)]], (2, 2), ZZ)
>>> A.sub(B)
DomainMatrix([[-3, -1], [1, 3]], (2, 2), ZZ)
See Also
========
add, matmul
"""
A._check('-', B, A.shape, B.shape)
return A.from_rep(A.rep.sub(B.rep))
def neg(A):
r"""
Returns the negative of DomainMatrix
Parameters
==========
A : Represents a DomainMatrix
Returns
=======
DomainMatrix
DomainMatrix after Negation
Examples
========
>>> from sympy import ZZ
>>> from sympy.polys.matrices import DomainMatrix
>>> A = DomainMatrix([
... [ZZ(1), ZZ(2)],
... [ZZ(3), ZZ(4)]], (2, 2), ZZ)
>>> A.neg()
DomainMatrix([[-1, -2], [-3, -4]], (2, 2), ZZ)
"""
return A.from_rep(A.rep.neg())
def mul(A, b):
r"""
Performs term by term multiplication for the second DomainMatrix
w.r.t first DomainMatrix. Returns a DomainMatrix whose rows are
list of DomainMatrix matrices created after term by term multiplication.
Parameters
==========
A, B: DomainMatrix
matrices to multiply term-wise
Returns
=======
DomainMatrix
DomainMatrix after term by term multiplication
Examples
========
>>> from sympy import ZZ
>>> from sympy.polys.matrices import DomainMatrix
>>> A = DomainMatrix([
... [ZZ(1), ZZ(2)],
... [ZZ(3), ZZ(4)]], (2, 2), ZZ)
>>> B = DomainMatrix([
... [ZZ(1), ZZ(1)],
... [ZZ(0), ZZ(1)]], (2, 2), ZZ)
>>> A.mul(B)
DomainMatrix([[DomainMatrix([[1, 1], [0, 1]], (2, 2), ZZ),
DomainMatrix([[2, 2], [0, 2]], (2, 2), ZZ)],
[DomainMatrix([[3, 3], [0, 3]], (2, 2), ZZ),
DomainMatrix([[4, 4], [0, 4]], (2, 2), ZZ)]], (2, 2), ZZ)
See Also
========
matmul
"""
return A.from_rep(A.rep.mul(b))
def rmul(A, b):
return A.from_rep(A.rep.rmul(b))
def matmul(A, B):
r"""
Performs matrix multiplication of two DomainMatrix matrices
Parameters
==========
A, B: DomainMatrix
to multiply
Returns
=======
DomainMatrix
DomainMatrix after multiplication
Examples
========
>>> from sympy import ZZ
>>> from sympy.polys.matrices import DomainMatrix
>>> A = DomainMatrix([
... [ZZ(1), ZZ(2)],
... [ZZ(3), ZZ(4)]], (2, 2), ZZ)
>>> B = DomainMatrix([
... [ZZ(1), ZZ(1)],
... [ZZ(0), ZZ(1)]], (2, 2), ZZ)
>>> A.matmul(B)
DomainMatrix([[1, 3], [3, 7]], (2, 2), ZZ)
See Also
========
mul, pow, add, sub
"""
A._check('*', B, A.shape[1], B.shape[0])
return A.from_rep(A.rep.matmul(B.rep))
def _scalarmul(A, lamda, reverse):
if lamda == A.domain.zero:
return DomainMatrix.zeros(A.shape, A.domain)
elif lamda == A.domain.one:
return A.copy()
elif reverse:
return A.rmul(lamda)
else:
return A.mul(lamda)
def scalarmul(A, lamda):
return A._scalarmul(lamda, reverse=False)
def rscalarmul(A, lamda):
return A._scalarmul(lamda, reverse=True)
def mul_elementwise(A, B):
assert A.domain == B.domain
return A.from_rep(A.rep.mul_elementwise(B.rep))
def __truediv__(A, lamda):
""" Method for Scalar Divison"""
if isinstance(lamda, int) or ZZ.of_type(lamda):
lamda = DomainScalar(ZZ(lamda), ZZ)
if not isinstance(lamda, DomainScalar):
return NotImplemented
A, lamda = A.to_field().unify(lamda)
if lamda.element == lamda.domain.zero:
raise ZeroDivisionError
if lamda.element == lamda.domain.one:
return A.to_field()
return A.mul(1 / lamda.element)
def pow(A, n):
r"""
Computes A**n
Parameters
==========
A : DomainMatrix
n : exponent for A
Returns
=======
DomainMatrix
DomainMatrix on computing A**n
Raises
======
NotImplementedError
if n is negative.
Examples
========
>>> from sympy import ZZ
>>> from sympy.polys.matrices import DomainMatrix
>>> A = DomainMatrix([
... [ZZ(1), ZZ(1)],
... [ZZ(0), ZZ(1)]], (2, 2), ZZ)
>>> A.pow(2)
DomainMatrix([[1, 2], [0, 1]], (2, 2), ZZ)
See Also
========
matmul
"""
nrows, ncols = A.shape
if nrows != ncols:
raise DMNonSquareMatrixError('Power of a nonsquare matrix')
if n < 0:
raise NotImplementedError('Negative powers')
elif n == 0:
return A.eye(nrows, A.domain)
elif n == 1:
return A
elif n % 2 == 1:
return A * A**(n - 1)
else:
sqrtAn = A ** (n // 2)
return sqrtAn * sqrtAn
def scc(self):
"""Compute the strongly connected components of a DomainMatrix
Explanation
===========
A square matrix can be considered as the adjacency matrix for a
directed graph where the row and column indices are the vertices. In
this graph if there is an edge from vertex ``i`` to vertex ``j`` if
``M[i, j]`` is nonzero. This routine computes the strongly connected
components of that graph which are subsets of the rows and columns that
are connected by some nonzero element of the matrix. The strongly
connected components are useful because many operations such as the
determinant can be computed by working with the submatrices
corresponding to each component.
Examples
========
Find the strongly connected components of a matrix:
>>> from sympy import ZZ
>>> from sympy.polys.matrices import DomainMatrix
>>> M = DomainMatrix([[ZZ(1), ZZ(0), ZZ(2)],
... [ZZ(0), ZZ(3), ZZ(0)],
... [ZZ(4), ZZ(6), ZZ(5)]], (3, 3), ZZ)
>>> M.scc()
[[1], [0, 2]]
Compute the determinant from the components:
>>> MM = M.to_Matrix()
>>> MM
Matrix([
[1, 0, 2],
[0, 3, 0],
[4, 6, 5]])
>>> MM[[1], [1]]
Matrix([[3]])
>>> MM[[0, 2], [0, 2]]
Matrix([
[1, 2],
[4, 5]])
>>> MM.det()
-9
>>> MM[[1], [1]].det() * MM[[0, 2], [0, 2]].det()
-9
The components are given in reverse topological order and represent a
permutation of the rows and columns that will bring the matrix into
block lower-triangular form:
>>> MM[[1, 0, 2], [1, 0, 2]]
Matrix([
[3, 0, 0],
[0, 1, 2],
[6, 4, 5]])
Returns
=======
List of lists of integers
Each list represents a strongly connected component.
See also
========
sympy.matrices.matrices.MatrixBase.strongly_connected_components
sympy.utilities.iterables.strongly_connected_components
"""
rows, cols = self.shape
assert rows == cols
return self.rep.scc()
def rref(self):
r"""
Returns reduced-row echelon form and list of pivots for the DomainMatrix
Returns
=======
(DomainMatrix, list)
reduced-row echelon form and list of pivots for the DomainMatrix
Raises
======
ValueError
If the domain of DomainMatrix not a Field
Examples
========
>>> from sympy import QQ
>>> from sympy.polys.matrices import DomainMatrix
>>> A = DomainMatrix([
... [QQ(2), QQ(-1), QQ(0)],
... [QQ(-1), QQ(2), QQ(-1)],
... [QQ(0), QQ(0), QQ(2)]], (3, 3), QQ)
>>> rref_matrix, rref_pivots = A.rref()
>>> rref_matrix
DomainMatrix([[1, 0, 0], [0, 1, 0], [0, 0, 1]], (3, 3), QQ)
>>> rref_pivots
(0, 1, 2)
See Also
========
convert_to, lu
"""
if not self.domain.is_Field:
raise DMNotAField('Not a field')
rref_ddm, pivots = self.rep.rref()
return self.from_rep(rref_ddm), tuple(pivots)
def columnspace(self):
r"""
Returns the columnspace for the DomainMatrix
Returns
=======
DomainMatrix
The columns of this matrix form a basis for the columnspace.
Examples
========
>>> from sympy import QQ
>>> from sympy.polys.matrices import DomainMatrix
>>> A = DomainMatrix([
... [QQ(1), QQ(-1)],
... [QQ(2), QQ(-2)]], (2, 2), QQ)
>>> A.columnspace()
DomainMatrix([[1], [2]], (2, 1), QQ)
"""
if not self.domain.is_Field:
raise DMNotAField('Not a field')
rref, pivots = self.rref()
rows, cols = self.shape
return self.extract(range(rows), pivots)
def rowspace(self):
r"""
Returns the rowspace for the DomainMatrix
Returns
=======
DomainMatrix
The rows of this matrix form a basis for the rowspace.
Examples
========
>>> from sympy import QQ
>>> from sympy.polys.matrices import DomainMatrix
>>> A = DomainMatrix([
... [QQ(1), QQ(-1)],
... [QQ(2), QQ(-2)]], (2, 2), QQ)
>>> A.rowspace()
DomainMatrix([[1, -1]], (1, 2), QQ)
"""
if not self.domain.is_Field:
raise DMNotAField('Not a field')
rref, pivots = self.rref()
rows, cols = self.shape
return self.extract(range(len(pivots)), range(cols))
def nullspace(self):
r"""
Returns the nullspace for the DomainMatrix
Returns
=======
DomainMatrix
The rows of this matrix form a basis for the nullspace.
Examples
========
>>> from sympy import QQ
>>> from sympy.polys.matrices import DomainMatrix
>>> A = DomainMatrix([
... [QQ(1), QQ(-1)],
... [QQ(2), QQ(-2)]], (2, 2), QQ)
>>> A.nullspace()
DomainMatrix([[1, 1]], (1, 2), QQ)
"""
if not self.domain.is_Field:
raise DMNotAField('Not a field')
return self.from_rep(self.rep.nullspace()[0])
def inv(self):
r"""
Finds the inverse of the DomainMatrix if exists
Returns
=======
DomainMatrix
DomainMatrix after inverse
Raises
======
ValueError
If the domain of DomainMatrix not a Field
DMNonSquareMatrixError
If the DomainMatrix is not a not Square DomainMatrix
Examples
========
>>> from sympy import QQ
>>> from sympy.polys.matrices import DomainMatrix
>>> A = DomainMatrix([
... [QQ(2), QQ(-1), QQ(0)],
... [QQ(-1), QQ(2), QQ(-1)],
... [QQ(0), QQ(0), QQ(2)]], (3, 3), QQ)
>>> A.inv()
DomainMatrix([[2/3, 1/3, 1/6], [1/3, 2/3, 1/3], [0, 0, 1/2]], (3, 3), QQ)
See Also
========
neg
"""
if not self.domain.is_Field:
raise DMNotAField('Not a field')
m, n = self.shape
if m != n:
raise DMNonSquareMatrixError
inv = self.rep.inv()
return self.from_rep(inv)
def det(self):
r"""
Returns the determinant of a Square DomainMatrix
Returns
=======
S.Complexes
determinant of Square DomainMatrix
Raises
======
ValueError
If the domain of DomainMatrix not a Field
Examples
========
>>> from sympy import ZZ
>>> from sympy.polys.matrices import DomainMatrix
>>> A = DomainMatrix([
... [ZZ(1), ZZ(2)],
... [ZZ(3), ZZ(4)]], (2, 2), ZZ)
>>> A.det()
-2
"""
m, n = self.shape
if m != n:
raise DMNonSquareMatrixError
return self.rep.det()
def lu(self):
r"""
Returns Lower and Upper decomposition of the DomainMatrix
Returns
=======
(L, U, exchange)
L, U are Lower and Upper decomposition of the DomainMatrix,
exchange is the list of indices of rows exchanged in the decomposition.
Raises
======
ValueError
If the domain of DomainMatrix not a Field
Examples
========
>>> from sympy import QQ
>>> from sympy.polys.matrices import DomainMatrix
>>> A = DomainMatrix([
... [QQ(1), QQ(-1)],
... [QQ(2), QQ(-2)]], (2, 2), QQ)
>>> A.lu()
(DomainMatrix([[1, 0], [2, 1]], (2, 2), QQ), DomainMatrix([[1, -1], [0, 0]], (2, 2), QQ), [])
See Also
========
lu_solve
"""
if not self.domain.is_Field:
raise DMNotAField('Not a field')
L, U, swaps = self.rep.lu()
return self.from_rep(L), self.from_rep(U), swaps
def lu_solve(self, rhs):
r"""
Solver for DomainMatrix x in the A*x = B
Parameters
==========
rhs : DomainMatrix B
Returns
=======
DomainMatrix
x in A*x = B
Raises
======
DMShapeError
If the DomainMatrix A and rhs have different number of rows
ValueError
If the domain of DomainMatrix A not a Field
Examples
========
>>> from sympy import QQ
>>> from sympy.polys.matrices import DomainMatrix
>>> A = DomainMatrix([
... [QQ(1), QQ(2)],
... [QQ(3), QQ(4)]], (2, 2), QQ)
>>> B = DomainMatrix([
... [QQ(1), QQ(1)],
... [QQ(0), QQ(1)]], (2, 2), QQ)
>>> A.lu_solve(B)
DomainMatrix([[-2, -1], [3/2, 1]], (2, 2), QQ)
See Also
========
lu
"""
if self.shape[0] != rhs.shape[0]:
raise DMShapeError("Shape")
if not self.domain.is_Field:
raise DMNotAField('Not a field')
sol = self.rep.lu_solve(rhs.rep)
return self.from_rep(sol)
def _solve(A, b):
# XXX: Not sure about this method or its signature. It is just created
# because it is needed by the holonomic module.
if A.shape[0] != b.shape[0]:
raise DMShapeError("Shape")
if A.domain != b.domain or not A.domain.is_Field:
raise DMNotAField('Not a field')
Aaug = A.hstack(b)
Arref, pivots = Aaug.rref()
particular = Arref.from_rep(Arref.rep.particular())
nullspace_rep, nonpivots = Arref[:,:-1].rep.nullspace()
nullspace = Arref.from_rep(nullspace_rep)
return particular, nullspace
def charpoly(self):
r"""
Returns the coefficients of the characteristic polynomial
of the DomainMatrix. These elements will be domain elements.
The domain of the elements will be same as domain of the DomainMatrix.
Returns
=======
list
coefficients of the characteristic polynomial
Raises
======
DMNonSquareMatrixError
If the DomainMatrix is not a not Square DomainMatrix
Examples
========
>>> from sympy import ZZ
>>> from sympy.polys.matrices import DomainMatrix
>>> A = DomainMatrix([
... [ZZ(1), ZZ(2)],
... [ZZ(3), ZZ(4)]], (2, 2), ZZ)
>>> A.charpoly()
[1, -5, -2]
"""
m, n = self.shape
if m != n:
raise DMNonSquareMatrixError("not square")
return self.rep.charpoly()
@classmethod
def eye(cls, shape, domain):
r"""
Return identity matrix of size n
Examples
========
>>> from sympy.polys.matrices import DomainMatrix
>>> from sympy import QQ
>>> DomainMatrix.eye(3, QQ)
DomainMatrix({0: {0: 1}, 1: {1: 1}, 2: {2: 1}}, (3, 3), QQ)
"""
if isinstance(shape, int):
shape = (shape, shape)
return cls.from_rep(SDM.eye(shape, domain))
@classmethod
def diag(cls, diagonal, domain, shape=None):
r"""
Return diagonal matrix with entries from ``diagonal``.
Examples
========
>>> from sympy.polys.matrices import DomainMatrix
>>> from sympy import ZZ
>>> DomainMatrix.diag([ZZ(5), ZZ(6)], ZZ)
DomainMatrix({0: {0: 5}, 1: {1: 6}}, (2, 2), ZZ)
"""
if shape is None:
N = len(diagonal)
shape = (N, N)
return cls.from_rep(SDM.diag(diagonal, domain, shape))
@classmethod
def zeros(cls, shape, domain, *, fmt='sparse'):
"""Returns a zero DomainMatrix of size shape, belonging to the specified domain
Examples
========
>>> from sympy.polys.matrices import DomainMatrix
>>> from sympy import QQ
>>> DomainMatrix.zeros((2, 3), QQ)
DomainMatrix({}, (2, 3), QQ)
"""
return cls.from_rep(SDM.zeros(shape, domain))
@classmethod
def ones(cls, shape, domain):
"""Returns a DomainMatrix of 1s, of size shape, belonging to the specified domain
Examples
========
>>> from sympy.polys.matrices import DomainMatrix
>>> from sympy import QQ
>>> DomainMatrix.ones((2,3), QQ)
DomainMatrix([[1, 1, 1], [1, 1, 1]], (2, 3), QQ)
"""
return cls.from_rep(DDM.ones(shape, domain))
def __eq__(A, B):
r"""
Checks for two DomainMatrix matrices to be equal or not
Parameters
==========
A, B: DomainMatrix
to check equality
Returns
=======
Boolean
True for equal, else False
Raises
======
NotImplementedError
If B is not a DomainMatrix
Examples
========
>>> from sympy import ZZ
>>> from sympy.polys.matrices import DomainMatrix
>>> A = DomainMatrix([
... [ZZ(1), ZZ(2)],
... [ZZ(3), ZZ(4)]], (2, 2), ZZ)
>>> B = DomainMatrix([
... [ZZ(1), ZZ(1)],
... [ZZ(0), ZZ(1)]], (2, 2), ZZ)
>>> A.__eq__(A)
True
>>> A.__eq__(B)
False
"""
if not isinstance(A, type(B)):
return NotImplemented
return A.domain == B.domain and A.rep == B.rep
def unify_eq(A, B):
if A.shape != B.shape:
return False
if A.domain != B.domain:
A, B = A.unify(B)
return A == B
|
200d161f9eaf3176d24298a697bf2365eb353355d94870d1011bf9b4ce151934 | """Tests for minimal polynomials. """
from sympy.core.function import expand
from sympy.core import (GoldenRatio, TribonacciConstant)
from sympy.core.numbers import (AlgebraicNumber, I, Rational, oo, pi)
from sympy.core.power import Pow
from sympy.core.singleton import S
from sympy.functions.elementary.exponential import exp
from sympy.functions.elementary.miscellaneous import (cbrt, sqrt)
from sympy.functions.elementary.trigonometric import (cos, sin, tan)
from sympy.polys.polytools import Poly
from sympy.polys.rootoftools import CRootOf
from sympy.solvers.solveset import nonlinsolve
from sympy.geometry import Circle, intersection
from sympy.testing.pytest import raises, slow
from sympy.sets.sets import FiniteSet
from sympy.geometry.point import Point2D
from sympy.polys.numberfields.minpoly import (
minimal_polynomial,
_choose_factor,
_minpoly_op_algebraic_element,
_separate_sq,
_minpoly_groebner,
)
from sympy.polys.partfrac import apart
from sympy.polys.polyerrors import (
NotAlgebraic,
GeneratorsError,
)
from sympy.polys.domains import QQ
from sympy.polys.rootoftools import rootof
from sympy.polys.polytools import degree
from sympy.abc import x, y, z
Q = Rational
def test_minimal_polynomial():
assert minimal_polynomial(-7, x) == x + 7
assert minimal_polynomial(-1, x) == x + 1
assert minimal_polynomial( 0, x) == x
assert minimal_polynomial( 1, x) == x - 1
assert minimal_polynomial( 7, x) == x - 7
assert minimal_polynomial(sqrt(2), x) == x**2 - 2
assert minimal_polynomial(sqrt(5), x) == x**2 - 5
assert minimal_polynomial(sqrt(6), x) == x**2 - 6
assert minimal_polynomial(2*sqrt(2), x) == x**2 - 8
assert minimal_polynomial(3*sqrt(5), x) == x**2 - 45
assert minimal_polynomial(4*sqrt(6), x) == x**2 - 96
assert minimal_polynomial(2*sqrt(2) + 3, x) == x**2 - 6*x + 1
assert minimal_polynomial(3*sqrt(5) + 6, x) == x**2 - 12*x - 9
assert minimal_polynomial(4*sqrt(6) + 7, x) == x**2 - 14*x - 47
assert minimal_polynomial(2*sqrt(2) - 3, x) == x**2 + 6*x + 1
assert minimal_polynomial(3*sqrt(5) - 6, x) == x**2 + 12*x - 9
assert minimal_polynomial(4*sqrt(6) - 7, x) == x**2 + 14*x - 47
assert minimal_polynomial(sqrt(1 + sqrt(6)), x) == x**4 - 2*x**2 - 5
assert minimal_polynomial(sqrt(I + sqrt(6)), x) == x**8 - 10*x**4 + 49
assert minimal_polynomial(2*I + sqrt(2 + I), x) == x**4 + 4*x**2 + 8*x + 37
assert minimal_polynomial(sqrt(2) + sqrt(3), x) == x**4 - 10*x**2 + 1
assert minimal_polynomial(
sqrt(2) + sqrt(3) + sqrt(6), x) == x**4 - 22*x**2 - 48*x - 23
a = 1 - 9*sqrt(2) + 7*sqrt(3)
assert minimal_polynomial(
1/a, x) == 392*x**4 - 1232*x**3 + 612*x**2 + 4*x - 1
assert minimal_polynomial(
1/sqrt(a), x) == 392*x**8 - 1232*x**6 + 612*x**4 + 4*x**2 - 1
raises(NotAlgebraic, lambda: minimal_polynomial(oo, x))
raises(NotAlgebraic, lambda: minimal_polynomial(2**y, x))
raises(NotAlgebraic, lambda: minimal_polynomial(sin(1), x))
assert minimal_polynomial(sqrt(2)).dummy_eq(x**2 - 2)
assert minimal_polynomial(sqrt(2), x) == x**2 - 2
assert minimal_polynomial(sqrt(2), polys=True) == Poly(x**2 - 2)
assert minimal_polynomial(sqrt(2), x, polys=True) == Poly(x**2 - 2, domain='QQ')
assert minimal_polynomial(sqrt(2), x, polys=True, compose=False) == Poly(x**2 - 2, domain='QQ')
a = AlgebraicNumber(sqrt(2))
b = AlgebraicNumber(sqrt(3))
assert minimal_polynomial(a, x) == x**2 - 2
assert minimal_polynomial(b, x) == x**2 - 3
assert minimal_polynomial(a, x, polys=True) == Poly(x**2 - 2, domain='QQ')
assert minimal_polynomial(b, x, polys=True) == Poly(x**2 - 3, domain='QQ')
assert minimal_polynomial(sqrt(a/2 + 17), x) == 2*x**4 - 68*x**2 + 577
assert minimal_polynomial(sqrt(b/2 + 17), x) == 4*x**4 - 136*x**2 + 1153
a, b = sqrt(2)/3 + 7, AlgebraicNumber(sqrt(2)/3 + 7)
f = 81*x**8 - 2268*x**6 - 4536*x**5 + 22644*x**4 + 63216*x**3 - \
31608*x**2 - 189648*x + 141358
assert minimal_polynomial(sqrt(a) + sqrt(sqrt(a)), x) == f
assert minimal_polynomial(sqrt(b) + sqrt(sqrt(b)), x) == f
assert minimal_polynomial(
a**Q(3, 2), x) == 729*x**4 - 506898*x**2 + 84604519
# issue 5994
eq = S('''
-1/(800*sqrt(-1/240 + 1/(18000*(-1/17280000 +
sqrt(15)*I/28800000)**(1/3)) + 2*(-1/17280000 +
sqrt(15)*I/28800000)**(1/3)))''')
assert minimal_polynomial(eq, x) == 8000*x**2 - 1
ex = (sqrt(5)*sqrt(I)/(5*sqrt(1 + 125*I))
+ 25*sqrt(5)/(I**Q(5,2)*(1 + 125*I)**Q(3,2))
+ 3125*sqrt(5)/(I**Q(11,2)*(1 + 125*I)**Q(3,2))
+ 5*I*sqrt(1 - I/125))
mp = minimal_polynomial(ex, x)
assert mp == 25*x**4 + 5000*x**2 + 250016
ex = 1 + sqrt(2) + sqrt(3)
mp = minimal_polynomial(ex, x)
assert mp == x**4 - 4*x**3 - 4*x**2 + 16*x - 8
ex = 1/(1 + sqrt(2) + sqrt(3))
mp = minimal_polynomial(ex, x)
assert mp == 8*x**4 - 16*x**3 + 4*x**2 + 4*x - 1
p = (expand((1 + sqrt(2) - 2*sqrt(3) + sqrt(7))**3))**Rational(1, 3)
mp = minimal_polynomial(p, x)
assert mp == x**8 - 8*x**7 - 56*x**6 + 448*x**5 + 480*x**4 - 5056*x**3 + 1984*x**2 + 7424*x - 3008
p = expand((1 + sqrt(2) - 2*sqrt(3) + sqrt(7))**3)
mp = minimal_polynomial(p, x)
assert mp == x**8 - 512*x**7 - 118208*x**6 + 31131136*x**5 + 647362560*x**4 - 56026611712*x**3 + 116994310144*x**2 + 404854931456*x - 27216576512
assert minimal_polynomial(S("-sqrt(5)/2 - 1/2 + (-sqrt(5)/2 - 1/2)**2"), x) == x - 1
a = 1 + sqrt(2)
assert minimal_polynomial((a*sqrt(2) + a)**3, x) == x**2 - 198*x + 1
p = 1/(1 + sqrt(2) + sqrt(3))
assert minimal_polynomial(p, x, compose=False) == 8*x**4 - 16*x**3 + 4*x**2 + 4*x - 1
p = 2/(1 + sqrt(2) + sqrt(3))
assert minimal_polynomial(p, x, compose=False) == x**4 - 4*x**3 + 2*x**2 + 4*x - 2
assert minimal_polynomial(1 + sqrt(2)*I, x, compose=False) == x**2 - 2*x + 3
assert minimal_polynomial(1/(1 + sqrt(2)) + 1, x, compose=False) == x**2 - 2
assert minimal_polynomial(sqrt(2)*I + I*(1 + sqrt(2)), x,
compose=False) == x**4 + 18*x**2 + 49
# minimal polynomial of I
assert minimal_polynomial(I, x, domain=QQ.algebraic_field(I)) == x - I
K = QQ.algebraic_field(I*(sqrt(2) + 1))
assert minimal_polynomial(I, x, domain=K) == x - I
assert minimal_polynomial(I, x, domain=QQ) == x**2 + 1
assert minimal_polynomial(I, x, domain='QQ(y)') == x**2 + 1
#issue 11553
assert minimal_polynomial(GoldenRatio, x) == x**2 - x - 1
assert minimal_polynomial(TribonacciConstant + 3, x) == x**3 - 10*x**2 + 32*x - 34
assert minimal_polynomial(GoldenRatio, x, domain=QQ.algebraic_field(sqrt(5))) == \
2*x - sqrt(5) - 1
assert minimal_polynomial(TribonacciConstant, x, domain=QQ.algebraic_field(cbrt(19 - 3*sqrt(33)))) == \
48*x - 19*(19 - 3*sqrt(33))**Rational(2, 3) - 3*sqrt(33)*(19 - 3*sqrt(33))**Rational(2, 3) \
- 16*(19 - 3*sqrt(33))**Rational(1, 3) - 16
# AlgebraicNumber with an alias.
# Wester H24
phi = AlgebraicNumber(S.GoldenRatio.expand(func=True), alias='phi')
assert minimal_polynomial(phi, x) == x**2 - x - 1
def test_minimal_polynomial_issue_19732():
# https://github.com/sympy/sympy/issues/19732
expr = (-280898097948878450887044002323982963174671632174995451265117559518123750720061943079105185551006003416773064305074191140286225850817291393988597615/(-488144716373031204149459129212782509078221364279079444636386844223983756114492222145074506571622290776245390771587888364089507840000000*sqrt(238368341569)*sqrt(S(11918417078450)/63568729
- 24411360*sqrt(238368341569)/63568729) +
238326799225996604451373809274348704114327860564921529846705817404208077866956345381951726531296652901169111729944612727047670549086208000000*sqrt(S(11918417078450)/63568729
- 24411360*sqrt(238368341569)/63568729)) -
180561807339168676696180573852937120123827201075968945871075967679148461189459480842956689723484024031016208588658753107/(-59358007109636562851035004992802812513575019937126272896569856090962677491318275291141463850327474176000000*sqrt(238368341569)*sqrt(S(11918417078450)/63568729
- 24411360*sqrt(238368341569)/63568729) +
28980348180319251787320809875930301310576055074938369007463004788921613896002936637780993064387310446267596800000*sqrt(S(11918417078450)/63568729
- 24411360*sqrt(238368341569)/63568729)))
poly = (2151288870990266634727173620565483054187142169311153766675688628985237817262915166497766867289157986631135400926544697981091151416655364879773546003475813114962656742744975460025956167152918469472166170500512008351638710934022160294849059721218824490226159355197136265032810944357335461128949781377875451881300105989490353140886315677977149440000000000000000000000*x**4
- 5773274155644072033773937864114266313663195672820501581692669271302387257492905909558846459600429795784309388968498783843631580008547382703258503404023153694528041873101120067477617592651525155101107144042679962433039557235772239171616433004024998230222455940044709064078962397144550855715640331680262171410099614469231080995436488414164502751395405398078353242072696360734131090111239998110773292915337556205692674790561090109440000000000000*x**2
+ 211295968822207088328287206509522887719741955693091053353263782924470627623790749534705683380138972642560898936171035770539616881000369889020398551821767092685775598633794696371561234818461806577723412581353857653829324364446419444210520602157621008010129702779407422072249192199762604318993590841636967747488049176548615614290254356975376588506729604345612047361483789518445332415765213187893207704958013682516462853001964919444736320672860140355089)
assert minimal_polynomial(expr, x) == poly
def test_minimal_polynomial_hi_prec():
p = 1/sqrt(1 - 9*sqrt(2) + 7*sqrt(3) + Rational(1, 10)**30)
mp = minimal_polynomial(p, x)
# checked with Wolfram Alpha
assert mp.coeff(x**6) == -1232000000000000000000000000001223999999999999999999999999999987999999999999999999999999999996000000000000000000000000000000
def test_minimal_polynomial_sq():
from sympy.core.add import Add
from sympy.core.function import expand_multinomial
p = expand_multinomial((1 + 5*sqrt(2) + 2*sqrt(3))**3)
mp = minimal_polynomial(p**Rational(1, 3), x)
assert mp == x**4 - 4*x**3 - 118*x**2 + 244*x + 1321
p = expand_multinomial((1 + sqrt(2) - 2*sqrt(3) + sqrt(7))**3)
mp = minimal_polynomial(p**Rational(1, 3), x)
assert mp == x**8 - 8*x**7 - 56*x**6 + 448*x**5 + 480*x**4 - 5056*x**3 + 1984*x**2 + 7424*x - 3008
p = Add(*[sqrt(i) for i in range(1, 12)])
mp = minimal_polynomial(p, x)
assert mp.subs({x: 0}) == -71965773323122507776
def test_minpoly_compose():
# issue 6868
eq = S('''
-1/(800*sqrt(-1/240 + 1/(18000*(-1/17280000 +
sqrt(15)*I/28800000)**(1/3)) + 2*(-1/17280000 +
sqrt(15)*I/28800000)**(1/3)))''')
mp = minimal_polynomial(eq + 3, x)
assert mp == 8000*x**2 - 48000*x + 71999
# issue 5888
assert minimal_polynomial(exp(I*pi/8), x) == x**8 + 1
mp = minimal_polynomial(sin(pi/7) + sqrt(2), x)
assert mp == 4096*x**12 - 63488*x**10 + 351488*x**8 - 826496*x**6 + \
770912*x**4 - 268432*x**2 + 28561
mp = minimal_polynomial(cos(pi/7) + sqrt(2), x)
assert mp == 64*x**6 - 64*x**5 - 432*x**4 + 304*x**3 + 712*x**2 - \
232*x - 239
mp = minimal_polynomial(exp(I*pi/7) + sqrt(2), x)
assert mp == x**12 - 2*x**11 - 9*x**10 + 16*x**9 + 43*x**8 - 70*x**7 - 97*x**6 + 126*x**5 + 211*x**4 - 212*x**3 - 37*x**2 + 142*x + 127
mp = minimal_polynomial(sin(pi/7) + sqrt(2), x)
assert mp == 4096*x**12 - 63488*x**10 + 351488*x**8 - 826496*x**6 + \
770912*x**4 - 268432*x**2 + 28561
mp = minimal_polynomial(cos(pi/7) + sqrt(2), x)
assert mp == 64*x**6 - 64*x**5 - 432*x**4 + 304*x**3 + 712*x**2 - \
232*x - 239
mp = minimal_polynomial(exp(I*pi/7) + sqrt(2), x)
assert mp == x**12 - 2*x**11 - 9*x**10 + 16*x**9 + 43*x**8 - 70*x**7 - 97*x**6 + 126*x**5 + 211*x**4 - 212*x**3 - 37*x**2 + 142*x + 127
mp = minimal_polynomial(exp(I*pi*Rational(2, 7)), x)
assert mp == x**6 + x**5 + x**4 + x**3 + x**2 + x + 1
mp = minimal_polynomial(exp(I*pi*Rational(2, 15)), x)
assert mp == x**8 - x**7 + x**5 - x**4 + x**3 - x + 1
mp = minimal_polynomial(cos(pi*Rational(2, 7)), x)
assert mp == 8*x**3 + 4*x**2 - 4*x - 1
mp = minimal_polynomial(sin(pi*Rational(2, 7)), x)
ex = (5*cos(pi*Rational(2, 7)) - 7)/(9*cos(pi/7) - 5*cos(pi*Rational(3, 7)))
mp = minimal_polynomial(ex, x)
assert mp == x**3 + 2*x**2 - x - 1
assert minimal_polynomial(-1/(2*cos(pi/7)), x) == x**3 + 2*x**2 - x - 1
assert minimal_polynomial(sin(pi*Rational(2, 15)), x) == \
256*x**8 - 448*x**6 + 224*x**4 - 32*x**2 + 1
assert minimal_polynomial(sin(pi*Rational(5, 14)), x) == 8*x**3 - 4*x**2 - 4*x + 1
assert minimal_polynomial(cos(pi/15), x) == 16*x**4 + 8*x**3 - 16*x**2 - 8*x + 1
ex = rootof(x**3 +x*4 + 1, 0)
mp = minimal_polynomial(ex, x)
assert mp == x**3 + 4*x + 1
mp = minimal_polynomial(ex + 1, x)
assert mp == x**3 - 3*x**2 + 7*x - 4
assert minimal_polynomial(exp(I*pi/3), x) == x**2 - x + 1
assert minimal_polynomial(exp(I*pi/4), x) == x**4 + 1
assert minimal_polynomial(exp(I*pi/6), x) == x**4 - x**2 + 1
assert minimal_polynomial(exp(I*pi/9), x) == x**6 - x**3 + 1
assert minimal_polynomial(exp(I*pi/10), x) == x**8 - x**6 + x**4 - x**2 + 1
assert minimal_polynomial(sin(pi/9), x) == 64*x**6 - 96*x**4 + 36*x**2 - 3
assert minimal_polynomial(sin(pi/11), x) == 1024*x**10 - 2816*x**8 + \
2816*x**6 - 1232*x**4 + 220*x**2 - 11
assert minimal_polynomial(sin(pi/21), x) == 4096*x**12 - 11264*x**10 + \
11264*x**8 - 4992*x**6 + 960*x**4 - 64*x**2 + 1
assert minimal_polynomial(cos(pi/9), x) == 8*x**3 - 6*x - 1
ex = 2**Rational(1, 3)*exp(2*I*pi/3)
assert minimal_polynomial(ex, x) == x**3 - 2
raises(NotAlgebraic, lambda: minimal_polynomial(cos(pi*sqrt(2)), x))
raises(NotAlgebraic, lambda: minimal_polynomial(sin(pi*sqrt(2)), x))
raises(NotAlgebraic, lambda: minimal_polynomial(exp(1.618*I*pi), x))
raises(NotAlgebraic, lambda: minimal_polynomial(exp(I*pi*sqrt(2)), x))
# issue 5934
ex = 1/(-36000 - 7200*sqrt(5) + (12*sqrt(10)*sqrt(sqrt(5) + 5) +
24*sqrt(10)*sqrt(-sqrt(5) + 5))**2) + 1
raises(ZeroDivisionError, lambda: minimal_polynomial(ex, x))
ex = sqrt(1 + 2**Rational(1,3)) + sqrt(1 + 2**Rational(1,4)) + sqrt(2)
mp = minimal_polynomial(ex, x)
assert degree(mp) == 48 and mp.subs({x:0}) == -16630256576
ex = tan(pi/5, evaluate=False)
mp = minimal_polynomial(ex, x)
assert mp == x**4 - 10*x**2 + 5
assert mp.subs(x, tan(pi/5)).is_zero
ex = tan(pi/6, evaluate=False)
mp = minimal_polynomial(ex, x)
assert mp == 3*x**2 - 1
assert mp.subs(x, tan(pi/6)).is_zero
ex = tan(pi/10, evaluate=False)
mp = minimal_polynomial(ex, x)
assert mp == 5*x**4 - 10*x**2 + 1
assert mp.subs(x, tan(pi/10)).is_zero
raises(NotAlgebraic, lambda: minimal_polynomial(tan(pi*sqrt(2)), x))
def test_minpoly_issue_7113():
# see discussion in https://github.com/sympy/sympy/pull/2234
from sympy.simplify.simplify import nsimplify
r = nsimplify(pi, tolerance=0.000000001)
mp = minimal_polynomial(r, x)
assert mp == 1768292677839237920489538677417507171630859375*x**109 - \
2734577732179183863586489182929671773182898498218854181690460140337930774573792597743853652058046464
def test_minpoly_issue_23677():
r1 = CRootOf(4000000*x**3 - 239960000*x**2 + 4782399900*x - 31663998001, 0)
r2 = CRootOf(4000000*x**3 - 239960000*x**2 + 4782399900*x - 31663998001, 1)
num = (7680000000000000000*r1**4*r2**4 - 614323200000000000000*r1**4*r2**3
+ 18458112576000000000000*r1**4*r2**2 - 246896663036160000000000*r1**4*r2
+ 1240473830323209600000000*r1**4 - 614323200000000000000*r1**3*r2**4
- 1476464424954240000000000*r1**3*r2**2 - 99225501687553535904000000*r1**3
+ 18458112576000000000000*r1**2*r2**4 - 1476464424954240000000000*r1**2*r2**3
- 593391458458356671712000000*r1**2*r2 + 2981354896834339226880720000*r1**2
- 246896663036160000000000*r1*r2**4 - 593391458458356671712000000*r1*r2**2
- 39878756418031796275267195200*r1 + 1240473830323209600000000*r2**4
- 99225501687553535904000000*r2**3 + 2981354896834339226880720000*r2**2 -
39878756418031796275267195200*r2 + 200361370275616536577343808012)
mp = (x**3 + 59426520028417434406408556687919*x**2 +
1161475464966574421163316896737773190861975156439163671112508400*x +
7467465541178623874454517208254940823818304424383315270991298807299003671748074773558707779600)
assert minimal_polynomial(num, x) == mp
def test_minpoly_issue_7574():
ex = -(-1)**Rational(1, 3) + (-1)**Rational(2,3)
assert minimal_polynomial(ex, x) == x + 1
def test_choose_factor():
# Test that this does not enter an infinite loop:
bad_factors = [Poly(x-2, x), Poly(x+2, x)]
raises(NotImplementedError, lambda: _choose_factor(bad_factors, x, sqrt(3)))
def test_minpoly_fraction_field():
assert minimal_polynomial(1/x, y) == -x*y + 1
assert minimal_polynomial(1 / (x + 1), y) == (x + 1)*y - 1
assert minimal_polynomial(sqrt(x), y) == y**2 - x
assert minimal_polynomial(sqrt(x + 1), y) == y**2 - x - 1
assert minimal_polynomial(sqrt(x) / x, y) == x*y**2 - 1
assert minimal_polynomial(sqrt(2) * sqrt(x), y) == y**2 - 2 * x
assert minimal_polynomial(sqrt(2) + sqrt(x), y) == \
y**4 + (-2*x - 4)*y**2 + x**2 - 4*x + 4
assert minimal_polynomial(x**Rational(1,3), y) == y**3 - x
assert minimal_polynomial(x**Rational(1,3) + sqrt(x), y) == \
y**6 - 3*x*y**4 - 2*x*y**3 + 3*x**2*y**2 - 6*x**2*y - x**3 + x**2
assert minimal_polynomial(sqrt(x) / z, y) == z**2*y**2 - x
assert minimal_polynomial(sqrt(x) / (z + 1), y) == (z**2 + 2*z + 1)*y**2 - x
assert minimal_polynomial(1/x, y, polys=True) == Poly(-x*y + 1, y, domain='ZZ(x)')
assert minimal_polynomial(1 / (x + 1), y, polys=True) == \
Poly((x + 1)*y - 1, y, domain='ZZ(x)')
assert minimal_polynomial(sqrt(x), y, polys=True) == Poly(y**2 - x, y, domain='ZZ(x)')
assert minimal_polynomial(sqrt(x) / z, y, polys=True) == \
Poly(z**2*y**2 - x, y, domain='ZZ(x, z)')
# this is (sqrt(1 + x**3)/x).integrate(x).diff(x) - sqrt(1 + x**3)/x
a = sqrt(x)/sqrt(1 + x**(-3)) - sqrt(x**3 + 1)/x + 1/(x**Rational(5, 2)* \
(1 + x**(-3))**Rational(3, 2)) + 1/(x**Rational(11, 2)*(1 + x**(-3))**Rational(3, 2))
assert minimal_polynomial(a, y) == y
raises(NotAlgebraic, lambda: minimal_polynomial(exp(x), y))
raises(GeneratorsError, lambda: minimal_polynomial(sqrt(x), x))
raises(GeneratorsError, lambda: minimal_polynomial(sqrt(x) - y, x))
raises(NotImplementedError, lambda: minimal_polynomial(sqrt(x), y, compose=False))
@slow
def test_minpoly_fraction_field_slow():
assert minimal_polynomial(minimal_polynomial(sqrt(x**Rational(1,5) - 1),
y).subs(y, sqrt(x**Rational(1,5) - 1)), z) == z
def test_minpoly_domain():
assert minimal_polynomial(sqrt(2), x, domain=QQ.algebraic_field(sqrt(2))) == \
x - sqrt(2)
assert minimal_polynomial(sqrt(8), x, domain=QQ.algebraic_field(sqrt(2))) == \
x - 2*sqrt(2)
assert minimal_polynomial(sqrt(Rational(3,2)), x,
domain=QQ.algebraic_field(sqrt(2))) == 2*x**2 - 3
raises(NotAlgebraic, lambda: minimal_polynomial(y, x, domain=QQ))
def test_issue_14831():
a = -2*sqrt(2)*sqrt(12*sqrt(2) + 17)
assert minimal_polynomial(a, x) == x**2 + 16*x - 8
e = (-3*sqrt(12*sqrt(2) + 17) + 12*sqrt(2) +
17 - 2*sqrt(2)*sqrt(12*sqrt(2) + 17))
assert minimal_polynomial(e, x) == x
def test_issue_18248():
assert nonlinsolve([x*y**3-sqrt(2)/3, x*y**6-4/(9*(sqrt(3)))],x,y) == \
FiniteSet((sqrt(3)/2, sqrt(6)/3), (sqrt(3)/2, -sqrt(6)/6 - sqrt(2)*I/2),
(sqrt(3)/2, -sqrt(6)/6 + sqrt(2)*I/2))
def test_issue_13230():
c1 = Circle(Point2D(3, sqrt(5)), 5)
c2 = Circle(Point2D(4, sqrt(7)), 6)
assert intersection(c1, c2) == [Point2D(-1 + (-sqrt(7) + sqrt(5))*(-2*sqrt(7)/29
+ 9*sqrt(5)/29 + sqrt(196*sqrt(35) + 1941)/29), -2*sqrt(7)/29 + 9*sqrt(5)/29
+ sqrt(196*sqrt(35) + 1941)/29), Point2D(-1 + (-sqrt(7) + sqrt(5))*(-sqrt(196*sqrt(35)
+ 1941)/29 - 2*sqrt(7)/29 + 9*sqrt(5)/29), -sqrt(196*sqrt(35) + 1941)/29 - 2*sqrt(7)/29 + 9*sqrt(5)/29)]
def test_issue_19760():
e = 1/(sqrt(1 + sqrt(2)) - sqrt(2)*sqrt(1 + sqrt(2))) + 1
mp_expected = x**4 - 4*x**3 + 4*x**2 - 2
for comp in (True, False):
mp = Poly(minimal_polynomial(e, compose=comp))
assert mp(x) == mp_expected, "minimal_polynomial(e, compose=%s) = %s; %s expected" % (comp, mp(x), mp_expected)
def test_issue_20163():
assert apart(1/(x**6+1), extension=[sqrt(3), I]) == \
(sqrt(3) + I)/(2*x + sqrt(3) + I)/6 + \
(sqrt(3) - I)/(2*x + sqrt(3) - I)/6 - \
(sqrt(3) - I)/(2*x - sqrt(3) + I)/6 - \
(sqrt(3) + I)/(2*x - sqrt(3) - I)/6 + \
I/(x + I)/6 - I/(x - I)/6
def test_issue_22559():
alpha = AlgebraicNumber(sqrt(2))
assert minimal_polynomial(alpha**3, x) == x**2 - 8
def test_issue_22561():
a = AlgebraicNumber(sqrt(2) + sqrt(3), [S(1) / 2, 0, S(-9) / 2, 0], gen=x)
assert a.as_expr() == sqrt(2)
assert minimal_polynomial(a, x) == x**2 - 2
assert minimal_polynomial(a**3, x) == x**2 - 8
def test_separate_sq_not_impl():
raises(NotImplementedError, lambda: _separate_sq(x**(S(1)/3) + x))
def test_minpoly_op_algebraic_element_not_impl():
raises(NotImplementedError,
lambda: _minpoly_op_algebraic_element(Pow, sqrt(2), sqrt(3), x, QQ))
def test_minpoly_groebner():
assert _minpoly_groebner(S(2)/3, x, Poly) == 3*x - 2
assert _minpoly_groebner(
(sqrt(2) + 3)*(sqrt(2) + 1), x, Poly) == x**2 - 10*x - 7
assert _minpoly_groebner((sqrt(2) + 3)**(S(1)/3)*(sqrt(2) + 1)**(S(1)/3),
x, Poly) == x**6 - 10*x**3 - 7
assert _minpoly_groebner((sqrt(2) + 3)**(-S(1)/3)*(sqrt(2) + 1)**(S(1)/3),
x, Poly) == 7*x**6 - 2*x**3 - 1
raises(NotAlgebraic, lambda: _minpoly_groebner(pi**2, x, Poly))
|
5a247b6101f6eaca86a80224293d2240b10555ca64c7760bf17788de0d407f3c | from math import prod
from sympy import QQ, ZZ
from sympy.abc import x, theta
from sympy.ntheory import factorint
from sympy.ntheory.residue_ntheory import n_order
from sympy.polys import Poly, cyclotomic_poly
from sympy.polys.matrices import DomainMatrix
from sympy.polys.numberfields.basis import round_two
from sympy.polys.numberfields.exceptions import StructureError
from sympy.polys.numberfields.modules import PowerBasis, to_col
from sympy.polys.numberfields.primes import (
prime_decomp, _two_elt_rep,
_check_formal_conditions_for_maximal_order,
)
from sympy.testing.pytest import raises
def test_check_formal_conditions_for_maximal_order():
T = Poly(cyclotomic_poly(5, x))
A = PowerBasis(T)
B = A.submodule_from_matrix(2 * DomainMatrix.eye(4, ZZ))
C = B.submodule_from_matrix(3 * DomainMatrix.eye(4, ZZ))
D = A.submodule_from_matrix(DomainMatrix.eye(4, ZZ)[:, :-1])
# Is a direct submodule of a power basis, but lacks 1 as first generator:
raises(StructureError, lambda: _check_formal_conditions_for_maximal_order(B))
# Is not a direct submodule of a power basis:
raises(StructureError, lambda: _check_formal_conditions_for_maximal_order(C))
# Is direct submod of pow basis, and starts with 1, but not sq/max rank/HNF:
raises(StructureError, lambda: _check_formal_conditions_for_maximal_order(D))
def test_two_elt_rep():
ell = 7
T = Poly(cyclotomic_poly(ell))
ZK, dK = round_two(T)
for p in [29, 13, 11, 5]:
P = prime_decomp(p, T)
for Pi in P:
# We have Pi in two-element representation, and, because we are
# looking at a cyclotomic field, this was computed by the "easy"
# method that just factors T mod p. We will now convert this to
# a set of Z-generators, then convert that back into a two-element
# rep. The latter need not be identical to the two-elt rep we
# already have, but it must have the same HNF.
H = p*ZK + Pi.alpha*ZK
gens = H.basis_element_pullbacks()
# Note: we could supply f = Pi.f, but prefer to test behavior without it.
b = _two_elt_rep(gens, ZK, p)
if b != Pi.alpha:
H2 = p*ZK + b*ZK
assert H2 == H
def test_valuation_at_prime_ideal():
p = 7
T = Poly(cyclotomic_poly(p))
ZK, dK = round_two(T)
P = prime_decomp(p, T, dK=dK, ZK=ZK)
assert len(P) == 1
P0 = P[0]
v = P0.valuation(p*ZK)
assert v == P0.e
# Test easy 0 case:
assert P0.valuation(5*ZK) == 0
def test_decomp_1():
# All prime decompositions in cyclotomic fields are in the "easy case,"
# since the index is unity.
# Here we check the ramified prime.
T = Poly(cyclotomic_poly(7))
raises(ValueError, lambda: prime_decomp(7))
P = prime_decomp(7, T)
assert len(P) == 1
P0 = P[0]
assert P0.e == 6
assert P0.f == 1
# Test powers:
assert P0**0 == P0.ZK
assert P0**1 == P0
assert P0**6 == 7 * P0.ZK
def test_decomp_2():
# More easy cyclotomic cases, but here we check unramified primes.
ell = 7
T = Poly(cyclotomic_poly(ell))
for p in [29, 13, 11, 5]:
f_exp = n_order(p, ell)
g_exp = (ell - 1) // f_exp
P = prime_decomp(p, T)
assert len(P) == g_exp
for Pi in P:
assert Pi.e == 1
assert Pi.f == f_exp
def test_decomp_3():
T = Poly(x ** 2 - 35)
rad = {}
ZK, dK = round_two(T, radicals=rad)
# 35 is 3 mod 4, so field disc is 4*5*7, and theory says each of the
# rational primes 2, 5, 7 should be the square of a prime ideal.
for p in [2, 5, 7]:
P = prime_decomp(p, T, dK=dK, ZK=ZK, radical=rad.get(p))
assert len(P) == 1
assert P[0].e == 2
assert P[0]**2 == p*ZK
def test_decomp_4():
T = Poly(x ** 2 - 21)
rad = {}
ZK, dK = round_two(T, radicals=rad)
# 21 is 1 mod 4, so field disc is 3*7, and theory says the
# rational primes 3, 7 should be the square of a prime ideal.
for p in [3, 7]:
P = prime_decomp(p, T, dK=dK, ZK=ZK, radical=rad.get(p))
assert len(P) == 1
assert P[0].e == 2
assert P[0]**2 == p*ZK
def test_decomp_5():
# Here is our first test of the "hard case" of prime decomposition.
# We work in a quadratic extension Q(sqrt(d)) where d is 1 mod 4, and
# we consider the factorization of the rational prime 2, which divides
# the index.
# Theory says the form of p's factorization depends on the residue of
# d mod 8, so we consider both cases, d = 1 mod 8 and d = 5 mod 8.
for d in [-7, -3]:
T = Poly(x ** 2 - d)
rad = {}
ZK, dK = round_two(T, radicals=rad)
p = 2
P = prime_decomp(p, T, dK=dK, ZK=ZK, radical=rad.get(p))
if d % 8 == 1:
assert len(P) == 2
assert all(P[i].e == 1 and P[i].f == 1 for i in range(2))
assert prod(Pi**Pi.e for Pi in P) == p * ZK
else:
assert d % 8 == 5
assert len(P) == 1
assert P[0].e == 1
assert P[0].f == 2
assert P[0].as_submodule() == p * ZK
def test_decomp_6():
# Another case where 2 divides the index. This is Dedekind's example of
# an essential discriminant divisor. (See Cohen, Excercise 6.10.)
T = Poly(x ** 3 + x ** 2 - 2 * x + 8)
rad = {}
ZK, dK = round_two(T, radicals=rad)
p = 2
P = prime_decomp(p, T, dK=dK, ZK=ZK, radical=rad.get(p))
assert len(P) == 3
assert all(Pi.e == Pi.f == 1 for Pi in P)
assert prod(Pi**Pi.e for Pi in P) == p*ZK
def test_decomp_7():
# Try working through an AlgebraicField
T = Poly(x ** 3 + x ** 2 - 2 * x + 8)
K = QQ.alg_field_from_poly(T)
p = 2
P = K.primes_above(p)
ZK = K.maximal_order()
assert len(P) == 3
assert all(Pi.e == Pi.f == 1 for Pi in P)
assert prod(Pi**Pi.e for Pi in P) == p*ZK
def test_decomp_8():
# This time we consider various cubics, and try factoring all primes
# dividing the index.
cases = (
x ** 3 + 3 * x ** 2 - 4 * x + 4,
x ** 3 + 3 * x ** 2 + 3 * x - 3,
x ** 3 + 5 * x ** 2 - x + 3,
x ** 3 + 5 * x ** 2 - 5 * x - 5,
x ** 3 + 3 * x ** 2 + 5,
x ** 3 + 6 * x ** 2 + 3 * x - 1,
x ** 3 + 6 * x ** 2 + 4,
x ** 3 + 7 * x ** 2 + 7 * x - 7,
x ** 3 + 7 * x ** 2 - x + 5,
x ** 3 + 7 * x ** 2 - 5 * x + 5,
x ** 3 + 4 * x ** 2 - 3 * x + 7,
x ** 3 + 8 * x ** 2 + 5 * x - 1,
x ** 3 + 8 * x ** 2 - 2 * x + 6,
x ** 3 + 6 * x ** 2 - 3 * x + 8,
x ** 3 + 9 * x ** 2 + 6 * x - 8,
x ** 3 + 15 * x ** 2 - 9 * x + 13,
)
def display(T, p, radical, P, I, J):
"""Useful for inspection, when running test manually."""
print('=' * 20)
print(T, p, radical)
for Pi in P:
print(f' ({Pi!r})')
print("I: ", I)
print("J: ", J)
print(f'Equal: {I == J}')
inspect = False
for g in cases:
T = Poly(g)
rad = {}
ZK, dK = round_two(T, radicals=rad)
dT = T.discriminant()
f_squared = dT // dK
F = factorint(f_squared)
for p in F:
radical = rad.get(p)
P = prime_decomp(p, T, dK=dK, ZK=ZK, radical=radical)
I = prod(Pi**Pi.e for Pi in P)
J = p * ZK
if inspect:
display(T, p, radical, P, I, J)
assert I == J
def test_PrimeIdeal_eq():
# `==` should fail on objects of different types, so even a completely
# inert PrimeIdeal should test unequal to the rational prime it divides.
T = Poly(cyclotomic_poly(7))
P0 = prime_decomp(5, T)[0]
assert P0.f == 6
assert P0.as_submodule() == 5 * P0.ZK
assert P0 != 5
def test_PrimeIdeal_add():
T = Poly(cyclotomic_poly(7))
P0 = prime_decomp(7, T)[0]
# Adding ideals computes their GCD, so adding the ramified prime dividing
# 7 to 7 itself should reproduce this prime (as a submodule).
assert P0 + 7 * P0.ZK == P0.as_submodule()
def test_str():
# Without alias:
k = QQ.alg_field_from_poly(Poly(x**2 + 7))
frp = k.primes_above(2)[0]
assert str(frp) == '(2, 3*_x/2 + 1/2)'
frp = k.primes_above(3)[0]
assert str(frp) == '(3)'
# With alias:
k = QQ.alg_field_from_poly(Poly(x ** 2 + 7), alias='alpha')
frp = k.primes_above(2)[0]
assert str(frp) == '(2, 3*alpha/2 + 1/2)'
frp = k.primes_above(3)[0]
assert str(frp) == '(3)'
def test_repr():
T = Poly(x**2 + 7)
ZK, dK = round_two(T)
P = prime_decomp(2, T, dK=dK, ZK=ZK)
assert repr(P[0]) == '[ (2, (3*x + 1)/2) e=1, f=1 ]'
assert P[0].repr(field_gen=theta) == '[ (2, (3*theta + 1)/2) e=1, f=1 ]'
assert P[0].repr(field_gen=theta, just_gens=True) == '(2, (3*theta + 1)/2)'
def test_PrimeIdeal_reduce():
k = QQ.alg_field_from_poly(Poly(x ** 3 + x ** 2 - 2 * x + 8))
Zk = k.maximal_order()
P = k.primes_above(2)
frp = P[2]
# reduce_element
a = Zk.parent(to_col([23, 20, 11]), denom=6)
a_bar_expected = Zk.parent(to_col([11, 5, 2]), denom=6)
a_bar = frp.reduce_element(a)
assert a_bar == a_bar_expected
# reduce_ANP
a = k([QQ(11, 6), QQ(20, 6), QQ(23, 6)])
a_bar_expected = k([QQ(2, 6), QQ(5, 6), QQ(11, 6)])
a_bar = frp.reduce_ANP(a)
assert a_bar == a_bar_expected
# reduce_alg_num
a = k.to_alg_num(a)
a_bar_expected = k.to_alg_num(a_bar_expected)
a_bar = frp.reduce_alg_num(a)
assert a_bar == a_bar_expected
def test_issue_23402():
k = QQ.alg_field_from_poly(Poly(x ** 3 + x ** 2 - 2 * x + 8))
P = k.primes_above(3)
assert P[0].alpha.equiv(0)
|
154b0128d8028ff5d7c117ef448ca710e009f7599849fcce120a1677f68e82aa | # coding=utf-8
from os import walk, sep, pardir
from os.path import split, join, abspath, exists, isfile
from glob import glob
import re
import random
import ast
from sympy.testing.pytest import raises
from sympy.testing.quality_unicode import _test_this_file_encoding
# System path separator (usually slash or backslash) to be
# used with excluded files, e.g.
# exclude = set([
# "%(sep)smpmath%(sep)s" % sepd,
# ])
sepd = {"sep": sep}
# path and sympy_path
SYMPY_PATH = abspath(join(split(__file__)[0], pardir, pardir)) # go to sympy/
assert exists(SYMPY_PATH)
TOP_PATH = abspath(join(SYMPY_PATH, pardir))
BIN_PATH = join(TOP_PATH, "bin")
EXAMPLES_PATH = join(TOP_PATH, "examples")
# Error messages
message_space = "File contains trailing whitespace: %s, line %s."
message_implicit = "File contains an implicit import: %s, line %s."
message_tabs = "File contains tabs instead of spaces: %s, line %s."
message_carriage = "File contains carriage returns at end of line: %s, line %s"
message_str_raise = "File contains string exception: %s, line %s"
message_gen_raise = "File contains generic exception: %s, line %s"
message_old_raise = "File contains old-style raise statement: %s, line %s, \"%s\""
message_eof = "File does not end with a newline: %s, line %s"
message_multi_eof = "File ends with more than 1 newline: %s, line %s"
message_test_suite_def = "Function should start with 'test_' or '_': %s, line %s"
message_duplicate_test = "This is a duplicate test function: %s, line %s"
message_self_assignments = "File contains assignments to self/cls: %s, line %s."
message_func_is = "File contains '.func is': %s, line %s."
message_bare_expr = "File contains bare expression: %s, line %s."
implicit_test_re = re.compile(r'^\s*(>>> )?(\.\.\. )?from .* import .*\*')
str_raise_re = re.compile(
r'^\s*(>>> )?(\.\.\. )?raise(\s+(\'|\")|\s*(\(\s*)+(\'|\"))')
gen_raise_re = re.compile(
r'^\s*(>>> )?(\.\.\. )?raise(\s+Exception|\s*(\(\s*)+Exception)')
old_raise_re = re.compile(r'^\s*(>>> )?(\.\.\. )?raise((\s*\(\s*)|\s+)\w+\s*,')
test_suite_def_re = re.compile(r'^def\s+(?!(_|test))[^(]*\(\s*\)\s*:$')
test_ok_def_re = re.compile(r'^def\s+test_.*:$')
test_file_re = re.compile(r'.*[/\\]test_.*\.py$')
func_is_re = re.compile(r'\.\s*func\s+is')
def tab_in_leading(s):
"""Returns True if there are tabs in the leading whitespace of a line,
including the whitespace of docstring code samples."""
n = len(s) - len(s.lstrip())
if not s[n:n + 3] in ['...', '>>>']:
check = s[:n]
else:
smore = s[n + 3:]
check = s[:n] + smore[:len(smore) - len(smore.lstrip())]
return not (check.expandtabs() == check)
def find_self_assignments(s):
"""Returns a list of "bad" assignments: if there are instances
of assigning to the first argument of the class method (except
for staticmethod's).
"""
t = [n for n in ast.parse(s).body if isinstance(n, ast.ClassDef)]
bad = []
for c in t:
for n in c.body:
if not isinstance(n, ast.FunctionDef):
continue
if any(d.id == 'staticmethod'
for d in n.decorator_list if isinstance(d, ast.Name)):
continue
if n.name == '__new__':
continue
if not n.args.args:
continue
first_arg = n.args.args[0].arg
for m in ast.walk(n):
if isinstance(m, ast.Assign):
for a in m.targets:
if isinstance(a, ast.Name) and a.id == first_arg:
bad.append(m)
elif (isinstance(a, ast.Tuple) and
any(q.id == first_arg for q in a.elts
if isinstance(q, ast.Name))):
bad.append(m)
return bad
def check_directory_tree(base_path, file_check, exclusions=set(), pattern="*.py"):
"""
Checks all files in the directory tree (with base_path as starting point)
with the file_check function provided, skipping files that contain
any of the strings in the set provided by exclusions.
"""
if not base_path:
return
for root, dirs, files in walk(base_path):
check_files(glob(join(root, pattern)), file_check, exclusions)
def check_files(files, file_check, exclusions=set(), pattern=None):
"""
Checks all files with the file_check function provided, skipping files
that contain any of the strings in the set provided by exclusions.
"""
if not files:
return
for fname in files:
if not exists(fname) or not isfile(fname):
continue
if any(ex in fname for ex in exclusions):
continue
if pattern is None or re.match(pattern, fname):
file_check(fname)
class _Visit(ast.NodeVisitor):
"""return the line number corresponding to the
line on which a bare expression appears if it is a binary op
or a comparison that is not in a with block.
EXAMPLES
========
>>> import ast
>>> class _Visit(ast.NodeVisitor):
... def visit_Expr(self, node):
... if isinstance(node.value, (ast.BinOp, ast.Compare)):
... print(node.lineno)
... def visit_With(self, node):
... pass # no checking there
...
>>> code='''x = 1 # line 1
... for i in range(3):
... x == 2 # <-- 3
... if x == 2:
... x == 3 # <-- 5
... x + 1 # <-- 6
... x = 1
... if x == 1:
... print(1)
... while x != 1:
... x == 1 # <-- 11
... with raises(TypeError):
... c == 1
... raise TypeError
... assert x == 1
... '''
>>> _Visit().visit(ast.parse(code))
3
5
6
11
"""
def visit_Expr(self, node):
if isinstance(node.value, (ast.BinOp, ast.Compare)):
assert None, message_bare_expr % ('', node.lineno)
def visit_With(self, node):
pass
BareExpr = _Visit()
def line_with_bare_expr(code):
"""return None or else 0-based line number of code on which
a bare expression appeared.
"""
tree = ast.parse(code)
try:
BareExpr.visit(tree)
except AssertionError as msg:
assert msg.args
msg = msg.args[0]
assert msg.startswith(message_bare_expr.split(':', 1)[0])
return int(msg.rsplit(' ', 1)[1].rstrip('.')) # the line number
def test_files():
"""
This test tests all files in SymPy and checks that:
o no lines contains a trailing whitespace
o no lines end with \r\n
o no line uses tabs instead of spaces
o that the file ends with a single newline
o there are no general or string exceptions
o there are no old style raise statements
o name of arg-less test suite functions start with _ or test_
o no duplicate function names that start with test_
o no assignments to self variable in class methods
o no lines contain ".func is" except in the test suite
o there is no do-nothing expression like `a == b` or `x + 1`
"""
def test(fname):
with open(fname, encoding="utf8") as test_file:
test_this_file(fname, test_file)
with open(fname, encoding='utf8') as test_file:
_test_this_file_encoding(fname, test_file)
def test_this_file(fname, test_file):
idx = None
code = test_file.read()
test_file.seek(0) # restore reader to head
py = fname if sep not in fname else fname.rsplit(sep, 1)[-1]
if py.startswith('test_'):
idx = line_with_bare_expr(code)
if idx is not None:
assert False, message_bare_expr % (fname, idx + 1)
line = None # to flag the case where there were no lines in file
tests = 0
test_set = set()
for idx, line in enumerate(test_file):
if test_file_re.match(fname):
if test_suite_def_re.match(line):
assert False, message_test_suite_def % (fname, idx + 1)
if test_ok_def_re.match(line):
tests += 1
test_set.add(line[3:].split('(')[0].strip())
if len(test_set) != tests:
assert False, message_duplicate_test % (fname, idx + 1)
if line.endswith(" \n") or line.endswith("\t\n"):
assert False, message_space % (fname, idx + 1)
if line.endswith("\r\n"):
assert False, message_carriage % (fname, idx + 1)
if tab_in_leading(line):
assert False, message_tabs % (fname, idx + 1)
if str_raise_re.search(line):
assert False, message_str_raise % (fname, idx + 1)
if gen_raise_re.search(line):
assert False, message_gen_raise % (fname, idx + 1)
if (implicit_test_re.search(line) and
not list(filter(lambda ex: ex in fname, import_exclude))):
assert False, message_implicit % (fname, idx + 1)
if func_is_re.search(line) and not test_file_re.search(fname):
assert False, message_func_is % (fname, idx + 1)
result = old_raise_re.search(line)
if result is not None:
assert False, message_old_raise % (
fname, idx + 1, result.group(2))
if line is not None:
if line == '\n' and idx > 0:
assert False, message_multi_eof % (fname, idx + 1)
elif not line.endswith('\n'):
# eof newline check
assert False, message_eof % (fname, idx + 1)
# Files to test at top level
top_level_files = [join(TOP_PATH, file) for file in [
"isympy.py",
"build.py",
"setup.py",
"setupegg.py",
]]
# Files to exclude from all tests
exclude = {
"%(sep)ssympy%(sep)sparsing%(sep)sautolev%(sep)s_antlr%(sep)sautolevparser.py" % sepd,
"%(sep)ssympy%(sep)sparsing%(sep)sautolev%(sep)s_antlr%(sep)sautolevlexer.py" % sepd,
"%(sep)ssympy%(sep)sparsing%(sep)sautolev%(sep)s_antlr%(sep)sautolevlistener.py" % sepd,
"%(sep)ssympy%(sep)sparsing%(sep)slatex%(sep)s_antlr%(sep)slatexparser.py" % sepd,
"%(sep)ssympy%(sep)sparsing%(sep)slatex%(sep)s_antlr%(sep)slatexlexer.py" % sepd,
}
# Files to exclude from the implicit import test
import_exclude = {
# glob imports are allowed in top-level __init__.py:
"%(sep)ssympy%(sep)s__init__.py" % sepd,
# these __init__.py should be fixed:
# XXX: not really, they use useful import pattern (DRY)
"%(sep)svector%(sep)s__init__.py" % sepd,
"%(sep)smechanics%(sep)s__init__.py" % sepd,
"%(sep)squantum%(sep)s__init__.py" % sepd,
"%(sep)spolys%(sep)s__init__.py" % sepd,
"%(sep)spolys%(sep)sdomains%(sep)s__init__.py" % sepd,
# interactive SymPy executes ``from sympy import *``:
"%(sep)sinteractive%(sep)ssession.py" % sepd,
# isympy.py executes ``from sympy import *``:
"%(sep)sisympy.py" % sepd,
# these two are import timing tests:
"%(sep)sbin%(sep)ssympy_time.py" % sepd,
"%(sep)sbin%(sep)ssympy_time_cache.py" % sepd,
# Taken from Python stdlib:
"%(sep)sparsing%(sep)ssympy_tokenize.py" % sepd,
# this one should be fixed:
"%(sep)splotting%(sep)spygletplot%(sep)s" % sepd,
# False positive in the docstring
"%(sep)sbin%(sep)stest_external_imports.py" % sepd,
"%(sep)sbin%(sep)stest_submodule_imports.py" % sepd,
# These are deprecated stubs that can be removed at some point:
"%(sep)sutilities%(sep)sruntests.py" % sepd,
"%(sep)sutilities%(sep)spytest.py" % sepd,
"%(sep)sutilities%(sep)srandtest.py" % sepd,
"%(sep)sutilities%(sep)stmpfiles.py" % sepd,
"%(sep)sutilities%(sep)squality_unicode.py" % sepd,
"%(sep)sutilities%(sep)sbenchmarking.py" % sepd,
}
check_files(top_level_files, test)
check_directory_tree(BIN_PATH, test, {"~", ".pyc", ".sh", ".mjs"}, "*")
check_directory_tree(SYMPY_PATH, test, exclude)
check_directory_tree(EXAMPLES_PATH, test, exclude)
def _with_space(c):
# return c with a random amount of leading space
return random.randint(0, 10)*' ' + c
def test_raise_statement_regular_expression():
candidates_ok = [
"some text # raise Exception, 'text'",
"raise ValueError('text') # raise Exception, 'text'",
"raise ValueError('text')",
"raise ValueError",
"raise ValueError('text')",
"raise ValueError('text') #,",
# Talking about an exception in a docstring
''''"""This function will raise ValueError, except when it doesn't"""''',
"raise (ValueError('text')",
]
str_candidates_fail = [
"raise 'exception'",
"raise 'Exception'",
'raise "exception"',
'raise "Exception"',
"raise 'ValueError'",
]
gen_candidates_fail = [
"raise Exception('text') # raise Exception, 'text'",
"raise Exception('text')",
"raise Exception",
"raise Exception('text')",
"raise Exception('text') #,",
"raise Exception, 'text'",
"raise Exception, 'text' # raise Exception('text')",
"raise Exception, 'text' # raise Exception, 'text'",
">>> raise Exception, 'text'",
">>> raise Exception, 'text' # raise Exception('text')",
">>> raise Exception, 'text' # raise Exception, 'text'",
]
old_candidates_fail = [
"raise Exception, 'text'",
"raise Exception, 'text' # raise Exception('text')",
"raise Exception, 'text' # raise Exception, 'text'",
">>> raise Exception, 'text'",
">>> raise Exception, 'text' # raise Exception('text')",
">>> raise Exception, 'text' # raise Exception, 'text'",
"raise ValueError, 'text'",
"raise ValueError, 'text' # raise Exception('text')",
"raise ValueError, 'text' # raise Exception, 'text'",
">>> raise ValueError, 'text'",
">>> raise ValueError, 'text' # raise Exception('text')",
">>> raise ValueError, 'text' # raise Exception, 'text'",
"raise(ValueError,",
"raise (ValueError,",
"raise( ValueError,",
"raise ( ValueError,",
"raise(ValueError ,",
"raise (ValueError ,",
"raise( ValueError ,",
"raise ( ValueError ,",
]
for c in candidates_ok:
assert str_raise_re.search(_with_space(c)) is None, c
assert gen_raise_re.search(_with_space(c)) is None, c
assert old_raise_re.search(_with_space(c)) is None, c
for c in str_candidates_fail:
assert str_raise_re.search(_with_space(c)) is not None, c
for c in gen_candidates_fail:
assert gen_raise_re.search(_with_space(c)) is not None, c
for c in old_candidates_fail:
assert old_raise_re.search(_with_space(c)) is not None, c
def test_implicit_imports_regular_expression():
candidates_ok = [
"from sympy import something",
">>> from sympy import something",
"from sympy.somewhere import something",
">>> from sympy.somewhere import something",
"import sympy",
">>> import sympy",
"import sympy.something.something",
"... import sympy",
"... import sympy.something.something",
"... from sympy import something",
"... from sympy.somewhere import something",
">> from sympy import *", # To allow 'fake' docstrings
"# from sympy import *",
"some text # from sympy import *",
]
candidates_fail = [
"from sympy import *",
">>> from sympy import *",
"from sympy.somewhere import *",
">>> from sympy.somewhere import *",
"... from sympy import *",
"... from sympy.somewhere import *",
]
for c in candidates_ok:
assert implicit_test_re.search(_with_space(c)) is None, c
for c in candidates_fail:
assert implicit_test_re.search(_with_space(c)) is not None, c
def test_test_suite_defs():
candidates_ok = [
" def foo():\n",
"def foo(arg):\n",
"def _foo():\n",
"def test_foo():\n",
]
candidates_fail = [
"def foo():\n",
"def foo() :\n",
"def foo( ):\n",
"def foo():\n",
]
for c in candidates_ok:
assert test_suite_def_re.search(c) is None, c
for c in candidates_fail:
assert test_suite_def_re.search(c) is not None, c
def test_test_duplicate_defs():
candidates_ok = [
"def foo():\ndef foo():\n",
"def test():\ndef test_():\n",
"def test_():\ndef test__():\n",
]
candidates_fail = [
"def test_():\ndef test_ ():\n",
"def test_1():\ndef test_1():\n",
]
ok = (None, 'check')
def check(file):
tests = 0
test_set = set()
for idx, line in enumerate(file.splitlines()):
if test_ok_def_re.match(line):
tests += 1
test_set.add(line[3:].split('(')[0].strip())
if len(test_set) != tests:
return False, message_duplicate_test % ('check', idx + 1)
return None, 'check'
for c in candidates_ok:
assert check(c) == ok
for c in candidates_fail:
assert check(c) != ok
def test_find_self_assignments():
candidates_ok = [
"class A(object):\n def foo(self, arg): arg = self\n",
"class A(object):\n def foo(self, arg): self.prop = arg\n",
"class A(object):\n def foo(self, arg): obj, obj2 = arg, self\n",
"class A(object):\n @classmethod\n def bar(cls, arg): arg = cls\n",
"class A(object):\n def foo(var, arg): arg = var\n",
]
candidates_fail = [
"class A(object):\n def foo(self, arg): self = arg\n",
"class A(object):\n def foo(self, arg): obj, self = arg, arg\n",
"class A(object):\n def foo(self, arg):\n if arg: self = arg",
"class A(object):\n @classmethod\n def foo(cls, arg): cls = arg\n",
"class A(object):\n def foo(var, arg): var = arg\n",
]
for c in candidates_ok:
assert find_self_assignments(c) == []
for c in candidates_fail:
assert find_self_assignments(c) != []
def test_test_unicode_encoding():
unicode_whitelist = ['foo']
unicode_strict_whitelist = ['bar']
fname = 'abc'
test_file = ['α']
raises(AssertionError, lambda: _test_this_file_encoding(
fname, test_file, unicode_whitelist, unicode_strict_whitelist))
fname = 'abc'
test_file = ['abc']
_test_this_file_encoding(
fname, test_file, unicode_whitelist, unicode_strict_whitelist)
fname = 'foo'
test_file = ['abc']
raises(AssertionError, lambda: _test_this_file_encoding(
fname, test_file, unicode_whitelist, unicode_strict_whitelist))
fname = 'bar'
test_file = ['abc']
_test_this_file_encoding(
fname, test_file, unicode_whitelist, unicode_strict_whitelist)
|
bae2b32c332cf388c23fd87f8b403fbacc8211c0fe7d95ea616a43d3119a82aa | from sympy.core.function import (Derivative, Function)
from sympy.core.singleton import S
from sympy.core.symbol import Symbol
from sympy.functions import exp, cos, sin, tan, cosh, sinh
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.geometry import Point, Point2D, Line, Polygon, Segment, convex_hull,\
intersection, centroid, Point3D, Line3D
from sympy.geometry.util import idiff, closest_points, farthest_points, _ordered_points, are_coplanar
from sympy.solvers.solvers import solve
from sympy.testing.pytest import raises
def test_idiff():
x = Symbol('x', real=True)
y = Symbol('y', real=True)
t = Symbol('t', real=True)
f = Function('f')
g = Function('g')
# the use of idiff in ellipse also provides coverage
circ = x**2 + y**2 - 4
ans = -3*x*(x**2/y**2 + 1)/y**3
assert ans == idiff(circ, y, x, 3), idiff(circ, y, x, 3)
assert ans == idiff(circ, [y], x, 3)
assert idiff(circ, y, x, 3) == ans
explicit = 12*x/sqrt(-x**2 + 4)**5
assert ans.subs(y, solve(circ, y)[0]).equals(explicit)
assert True in [sol.diff(x, 3).equals(explicit) for sol in solve(circ, y)]
assert idiff(x + t + y, [y, t], x) == -Derivative(t, x) - 1
assert idiff(f(x) * exp(f(x)) - x * exp(x), f(x), x) == (x + 1)*exp(x)*exp(-f(x))/(f(x) + 1)
assert idiff(f(x) - y * exp(x), [f(x), y], x) == (y + Derivative(y, x))*exp(x)
assert idiff(f(x) - y * exp(x), [y, f(x)], x) == -y + Derivative(f(x), x)*exp(-x)
assert idiff(f(x) - g(x), [f(x), g(x)], x) == Derivative(g(x), x)
# this should be fast
fxy = y - (-10*(-sin(x) + 1/x)**2 + tan(x)**2 + 2*cosh(x/10))
assert idiff(fxy, y, x) == -20*sin(x)*cos(x) + 2*tan(x)**3 + \
2*tan(x) + sinh(x/10)/5 + 20*cos(x)/x - 20*sin(x)/x**2 + 20/x**3
def test_intersection():
assert intersection(Point(0, 0)) == []
raises(TypeError, lambda: intersection(Point(0, 0), 3))
assert intersection(
Segment((0, 0), (2, 0)),
Segment((-1, 0), (1, 0)),
Line((0, 0), (0, 1)), pairwise=True) == [
Point(0, 0), Segment((0, 0), (1, 0))]
assert intersection(
Line((0, 0), (0, 1)),
Segment((0, 0), (2, 0)),
Segment((-1, 0), (1, 0)), pairwise=True) == [
Point(0, 0), Segment((0, 0), (1, 0))]
assert intersection(
Line((0, 0), (0, 1)),
Segment((0, 0), (2, 0)),
Segment((-1, 0), (1, 0)),
Line((0, 0), slope=1), pairwise=True) == [
Point(0, 0), Segment((0, 0), (1, 0))]
def test_convex_hull():
raises(TypeError, lambda: convex_hull(Point(0, 0), 3))
points = [(1, -1), (1, -2), (3, -1), (-5, -2), (15, -4)]
assert convex_hull(*points, **dict(polygon=False)) == (
[Point2D(-5, -2), Point2D(1, -1), Point2D(3, -1), Point2D(15, -4)],
[Point2D(-5, -2), Point2D(15, -4)])
def test_centroid():
p = Polygon((0, 0), (10, 0), (10, 10))
q = p.translate(0, 20)
assert centroid(p, q) == Point(20, 40)/3
p = Segment((0, 0), (2, 0))
q = Segment((0, 0), (2, 2))
assert centroid(p, q) == Point(1, -sqrt(2) + 2)
assert centroid(Point(0, 0), Point(2, 0)) == Point(2, 0)/2
assert centroid(Point(0, 0), Point(0, 0), Point(2, 0)) == Point(2, 0)/3
def test_farthest_points_closest_points():
from sympy.core.random import randint
from sympy.utilities.iterables import subsets
for how in (min, max):
if how == min:
func = closest_points
else:
func = farthest_points
raises(ValueError, lambda: func(Point2D(0, 0), Point2D(0, 0)))
# 3rd pt dx is close and pt is closer to 1st pt
p1 = [Point2D(0, 0), Point2D(3, 0), Point2D(1, 1)]
# 3rd pt dx is close and pt is closer to 2nd pt
p2 = [Point2D(0, 0), Point2D(3, 0), Point2D(2, 1)]
# 3rd pt dx is close and but pt is not closer
p3 = [Point2D(0, 0), Point2D(3, 0), Point2D(1, 10)]
# 3rd pt dx is not closer and it's closer to 2nd pt
p4 = [Point2D(0, 0), Point2D(3, 0), Point2D(4, 0)]
# 3rd pt dx is not closer and it's closer to 1st pt
p5 = [Point2D(0, 0), Point2D(3, 0), Point2D(-1, 0)]
# duplicate point doesn't affect outcome
dup = [Point2D(0, 0), Point2D(3, 0), Point2D(3, 0), Point2D(-1, 0)]
# symbolic
x = Symbol('x', positive=True)
s = [Point2D(a) for a in ((x, 1), (x + 3, 2), (x + 2, 2))]
for points in (p1, p2, p3, p4, p5, dup, s):
d = how(i.distance(j) for i, j in subsets(set(points), 2))
ans = a, b = list(func(*points))[0]
assert a.distance(b) == d
assert ans == _ordered_points(ans)
# if the following ever fails, the above tests were not sufficient
# and the logical error in the routine should be fixed
points = set()
while len(points) != 7:
points.add(Point2D(randint(1, 100), randint(1, 100)))
points = list(points)
d = how(i.distance(j) for i, j in subsets(points, 2))
ans = a, b = list(func(*points))[0]
assert a.distance(b) == d
assert ans == _ordered_points(ans)
# equidistant points
a, b, c = (
Point2D(0, 0), Point2D(1, 0), Point2D(S.Half, sqrt(3)/2))
ans = {_ordered_points((i, j))
for i, j in subsets((a, b, c), 2)}
assert closest_points(b, c, a) == ans
assert farthest_points(b, c, a) == ans
# unique to farthest
points = [(1, 1), (1, 2), (3, 1), (-5, 2), (15, 4)]
assert farthest_points(*points) == {
(Point2D(-5, 2), Point2D(15, 4))}
points = [(1, -1), (1, -2), (3, -1), (-5, -2), (15, -4)]
assert farthest_points(*points) == {
(Point2D(-5, -2), Point2D(15, -4))}
assert farthest_points((1, 1), (0, 0)) == {
(Point2D(0, 0), Point2D(1, 1))}
raises(ValueError, lambda: farthest_points((1, 1)))
def test_are_coplanar():
a = Line3D(Point3D(5, 0, 0), Point3D(1, -1, 1))
b = Line3D(Point3D(0, -2, 0), Point3D(3, 1, 1))
c = Line3D(Point3D(0, -1, 0), Point3D(5, -1, 9))
d = Line(Point2D(0, 3), Point2D(1, 5))
assert are_coplanar(a, b, c) == False
assert are_coplanar(a, d) == False
|
c78d8a0b4fc2fa09230b692bcac0c86c9de76e35690101822f883e32d3f1b848 | from sympy.testing.pytest import raises, XFAIL
from sympy.external import import_module
from sympy.concrete.products import Product
from sympy.concrete.summations import Sum
from sympy.core.add import Add
from sympy.core.function import (Derivative, Function)
from sympy.core.mul import Mul
from sympy.core.numbers import (E, oo)
from sympy.core.power import Pow
from sympy.core.relational import (GreaterThan, LessThan, StrictGreaterThan, StrictLessThan, Unequality)
from sympy.core.symbol import Symbol
from sympy.functions.combinatorial.factorials import (binomial, factorial)
from sympy.functions.elementary.complexes import (Abs, conjugate)
from sympy.functions.elementary.exponential import (exp, log)
from sympy.functions.elementary.integers import (ceiling, floor)
from sympy.functions.elementary.miscellaneous import (root, sqrt)
from sympy.functions.elementary.trigonometric import (asin, cos, csc, sec, sin, tan)
from sympy.integrals.integrals import Integral
from sympy.series.limits import Limit
from sympy.core.relational import Eq, Ne, Lt, Le, Gt, Ge
from sympy.physics.quantum.state import Bra, Ket
from sympy.abc import x, y, z, a, b, c, t, k, n
antlr4 = import_module("antlr4")
# disable tests if antlr4-python3-runtime is not present
if not antlr4:
disabled = True
theta = Symbol('theta')
f = Function('f')
# shorthand definitions
def _Add(a, b):
return Add(a, b, evaluate=False)
def _Mul(a, b):
return Mul(a, b, evaluate=False)
def _Pow(a, b):
return Pow(a, b, evaluate=False)
def _Sqrt(a):
return sqrt(a, evaluate=False)
def _Conjugate(a):
return conjugate(a, evaluate=False)
def _Abs(a):
return Abs(a, evaluate=False)
def _factorial(a):
return factorial(a, evaluate=False)
def _exp(a):
return exp(a, evaluate=False)
def _log(a, b):
return log(a, b, evaluate=False)
def _binomial(n, k):
return binomial(n, k, evaluate=False)
def test_import():
from sympy.parsing.latex._build_latex_antlr import (
build_parser,
check_antlr_version,
dir_latex_antlr
)
# XXX: It would be better to come up with a test for these...
del build_parser, check_antlr_version, dir_latex_antlr
# These LaTeX strings should parse to the corresponding SymPy expression
GOOD_PAIRS = [
(r"0", 0),
(r"1", 1),
(r"-3.14", -3.14),
(r"(-7.13)(1.5)", _Mul(-7.13, 1.5)),
(r"x", x),
(r"2x", 2*x),
(r"x^2", x**2),
(r"x^\frac{1}{2}", _Pow(x, _Pow(2, -1))),
(r"x^{3 + 1}", x**_Add(3, 1)),
(r"-c", -c),
(r"a \cdot b", a * b),
(r"a / b", a / b),
(r"a \div b", a / b),
(r"a + b", a + b),
(r"a + b - a", _Add(a+b, -a)),
(r"a^2 + b^2 = c^2", Eq(a**2 + b**2, c**2)),
(r"(x + y) z", _Mul(_Add(x, y), z)),
(r"a'b+ab'", _Add(_Mul(Symbol("a'"), b), _Mul(a, Symbol("b'")))),
(r"y''_1", Symbol("y_{1}''")),
(r"y_1''", Symbol("y_{1}''")),
(r"\left(x + y\right) z", _Mul(_Add(x, y), z)),
(r"\left( x + y\right ) z", _Mul(_Add(x, y), z)),
(r"\left( x + y\right ) z", _Mul(_Add(x, y), z)),
(r"\left[x + y\right] z", _Mul(_Add(x, y), z)),
(r"\left\{x + y\right\} z", _Mul(_Add(x, y), z)),
(r"1+1", _Add(1, 1)),
(r"0+1", _Add(0, 1)),
(r"1*2", _Mul(1, 2)),
(r"0*1", _Mul(0, 1)),
(r"1 \times 2 ", _Mul(1, 2)),
(r"x = y", Eq(x, y)),
(r"x \neq y", Ne(x, y)),
(r"x < y", Lt(x, y)),
(r"x > y", Gt(x, y)),
(r"x \leq y", Le(x, y)),
(r"x \geq y", Ge(x, y)),
(r"x \le y", Le(x, y)),
(r"x \ge y", Ge(x, y)),
(r"\lfloor x \rfloor", floor(x)),
(r"\lceil x \rceil", ceiling(x)),
(r"\langle x |", Bra('x')),
(r"| x \rangle", Ket('x')),
(r"\sin \theta", sin(theta)),
(r"\sin(\theta)", sin(theta)),
(r"\sin^{-1} a", asin(a)),
(r"\sin a \cos b", _Mul(sin(a), cos(b))),
(r"\sin \cos \theta", sin(cos(theta))),
(r"\sin(\cos \theta)", sin(cos(theta))),
(r"\frac{a}{b}", a / b),
(r"\dfrac{a}{b}", a / b),
(r"\tfrac{a}{b}", a / b),
(r"\frac12", _Pow(2, -1)),
(r"\frac12y", _Mul(_Pow(2, -1), y)),
(r"\frac1234", _Mul(_Pow(2, -1), 34)),
(r"\frac2{3}", _Mul(2, _Pow(3, -1))),
(r"\frac{\sin{x}}2", _Mul(sin(x), _Pow(2, -1))),
(r"\frac{a + b}{c}", _Mul(a + b, _Pow(c, -1))),
(r"\frac{7}{3}", _Mul(7, _Pow(3, -1))),
(r"(\csc x)(\sec y)", csc(x)*sec(y)),
(r"\lim_{x \to 3} a", Limit(a, x, 3)),
(r"\lim_{x \rightarrow 3} a", Limit(a, x, 3)),
(r"\lim_{x \Rightarrow 3} a", Limit(a, x, 3)),
(r"\lim_{x \longrightarrow 3} a", Limit(a, x, 3)),
(r"\lim_{x \Longrightarrow 3} a", Limit(a, x, 3)),
(r"\lim_{x \to 3^{+}} a", Limit(a, x, 3, dir='+')),
(r"\lim_{x \to 3^{-}} a", Limit(a, x, 3, dir='-')),
(r"\lim_{x \to 3^+} a", Limit(a, x, 3, dir='+')),
(r"\lim_{x \to 3^-} a", Limit(a, x, 3, dir='-')),
(r"\infty", oo),
(r"\lim_{x \to \infty} \frac{1}{x}", Limit(_Pow(x, -1), x, oo)),
(r"\frac{d}{dx} x", Derivative(x, x)),
(r"\frac{d}{dt} x", Derivative(x, t)),
(r"f(x)", f(x)),
(r"f(x, y)", f(x, y)),
(r"f(x, y, z)", f(x, y, z)),
(r"f'_1(x)", Function("f_{1}'")(x)),
(r"f_{1}''(x+y)", Function("f_{1}''")(x+y)),
(r"\frac{d f(x)}{dx}", Derivative(f(x), x)),
(r"\frac{d\theta(x)}{dx}", Derivative(Function('theta')(x), x)),
(r"x \neq y", Unequality(x, y)),
(r"|x|", _Abs(x)),
(r"||x||", _Abs(Abs(x))),
(r"|x||y|", _Abs(x)*_Abs(y)),
(r"||x||y||", _Abs(_Abs(x)*_Abs(y))),
(r"\pi^{|xy|}", Symbol('pi')**_Abs(x*y)),
(r"\int x dx", Integral(x, x)),
(r"\int x d\theta", Integral(x, theta)),
(r"\int (x^2 - y)dx", Integral(x**2 - y, x)),
(r"\int x + a dx", Integral(_Add(x, a), x)),
(r"\int da", Integral(1, a)),
(r"\int_0^7 dx", Integral(1, (x, 0, 7))),
(r"\int\limits_{0}^{1} x dx", Integral(x, (x, 0, 1))),
(r"\int_a^b x dx", Integral(x, (x, a, b))),
(r"\int^b_a x dx", Integral(x, (x, a, b))),
(r"\int_{a}^b x dx", Integral(x, (x, a, b))),
(r"\int^{b}_a x dx", Integral(x, (x, a, b))),
(r"\int_{a}^{b} x dx", Integral(x, (x, a, b))),
(r"\int^{b}_{a} x dx", Integral(x, (x, a, b))),
(r"\int_{f(a)}^{f(b)} f(z) dz", Integral(f(z), (z, f(a), f(b)))),
(r"\int (x+a)", Integral(_Add(x, a), x)),
(r"\int a + b + c dx", Integral(_Add(_Add(a, b), c), x)),
(r"\int \frac{dz}{z}", Integral(Pow(z, -1), z)),
(r"\int \frac{3 dz}{z}", Integral(3*Pow(z, -1), z)),
(r"\int \frac{1}{x} dx", Integral(Pow(x, -1), x)),
(r"\int \frac{1}{a} + \frac{1}{b} dx",
Integral(_Add(_Pow(a, -1), Pow(b, -1)), x)),
(r"\int \frac{3 \cdot d\theta}{\theta}",
Integral(3*_Pow(theta, -1), theta)),
(r"\int \frac{1}{x} + 1 dx", Integral(_Add(_Pow(x, -1), 1), x)),
(r"x_0", Symbol('x_{0}')),
(r"x_{1}", Symbol('x_{1}')),
(r"x_a", Symbol('x_{a}')),
(r"x_{b}", Symbol('x_{b}')),
(r"h_\theta", Symbol('h_{theta}')),
(r"h_{\theta}", Symbol('h_{theta}')),
(r"h_{\theta}(x_0, x_1)",
Function('h_{theta}')(Symbol('x_{0}'), Symbol('x_{1}'))),
(r"x!", _factorial(x)),
(r"100!", _factorial(100)),
(r"\theta!", _factorial(theta)),
(r"(x + 1)!", _factorial(_Add(x, 1))),
(r"(x!)!", _factorial(_factorial(x))),
(r"x!!!", _factorial(_factorial(_factorial(x)))),
(r"5!7!", _Mul(_factorial(5), _factorial(7))),
(r"\sqrt{x}", sqrt(x)),
(r"\sqrt{x + b}", sqrt(_Add(x, b))),
(r"\sqrt[3]{\sin x}", root(sin(x), 3)),
(r"\sqrt[y]{\sin x}", root(sin(x), y)),
(r"\sqrt[\theta]{\sin x}", root(sin(x), theta)),
(r"\sqrt{\frac{12}{6}}", _Sqrt(_Mul(12, _Pow(6, -1)))),
(r"\overline{z}", _Conjugate(z)),
(r"\overline{\overline{z}}", _Conjugate(_Conjugate(z))),
(r"\overline{x + y}", _Conjugate(_Add(x, y))),
(r"\overline{x} + \overline{y}", _Conjugate(x) + _Conjugate(y)),
(r"x < y", StrictLessThan(x, y)),
(r"x \leq y", LessThan(x, y)),
(r"x > y", StrictGreaterThan(x, y)),
(r"x \geq y", GreaterThan(x, y)),
(r"\mathit{x}", Symbol('x')),
(r"\mathit{test}", Symbol('test')),
(r"\mathit{TEST}", Symbol('TEST')),
(r"\mathit{HELLO world}", Symbol('HELLO world')),
(r"\sum_{k = 1}^{3} c", Sum(c, (k, 1, 3))),
(r"\sum_{k = 1}^3 c", Sum(c, (k, 1, 3))),
(r"\sum^{3}_{k = 1} c", Sum(c, (k, 1, 3))),
(r"\sum^3_{k = 1} c", Sum(c, (k, 1, 3))),
(r"\sum_{k = 1}^{10} k^2", Sum(k**2, (k, 1, 10))),
(r"\sum_{n = 0}^{\infty} \frac{1}{n!}",
Sum(_Pow(_factorial(n), -1), (n, 0, oo))),
(r"\prod_{a = b}^{c} x", Product(x, (a, b, c))),
(r"\prod_{a = b}^c x", Product(x, (a, b, c))),
(r"\prod^{c}_{a = b} x", Product(x, (a, b, c))),
(r"\prod^c_{a = b} x", Product(x, (a, b, c))),
(r"\exp x", _exp(x)),
(r"\exp(x)", _exp(x)),
(r"\lg x", _log(x, 10)),
(r"\ln x", _log(x, E)),
(r"\ln xy", _log(x*y, E)),
(r"\log x", _log(x, E)),
(r"\log xy", _log(x*y, E)),
(r"\log_{2} x", _log(x, 2)),
(r"\log_{a} x", _log(x, a)),
(r"\log_{11} x", _log(x, 11)),
(r"\log_{a^2} x", _log(x, _Pow(a, 2))),
(r"[x]", x),
(r"[a + b]", _Add(a, b)),
(r"\frac{d}{dx} [ \tan x ]", Derivative(tan(x), x)),
(r"\binom{n}{k}", _binomial(n, k)),
(r"\tbinom{n}{k}", _binomial(n, k)),
(r"\dbinom{n}{k}", _binomial(n, k)),
(r"\binom{n}{0}", _binomial(n, 0)),
(r"x^\binom{n}{k}", _Pow(x, _binomial(n, k))),
(r"a \, b", _Mul(a, b)),
(r"a \thinspace b", _Mul(a, b)),
(r"a \: b", _Mul(a, b)),
(r"a \medspace b", _Mul(a, b)),
(r"a \; b", _Mul(a, b)),
(r"a \thickspace b", _Mul(a, b)),
(r"a \quad b", _Mul(a, b)),
(r"a \qquad b", _Mul(a, b)),
(r"a \! b", _Mul(a, b)),
(r"a \negthinspace b", _Mul(a, b)),
(r"a \negmedspace b", _Mul(a, b)),
(r"a \negthickspace b", _Mul(a, b)),
(r"\int x \, dx", Integral(x, x)),
(r"\log_2 x", _log(x, 2)),
(r"\log_a x", _log(x, a)),
(r"5^0 - 4^0", _Add(_Pow(5, 0), _Mul(-1, _Pow(4, 0)))),
]
def test_parseable():
from sympy.parsing.latex import parse_latex
for latex_str, sympy_expr in GOOD_PAIRS:
assert parse_latex(latex_str) == sympy_expr, latex_str
# These bad LaTeX strings should raise a LaTeXParsingError when parsed
BAD_STRINGS = [
r"(",
r")",
r"\frac{d}{dx}",
r"(\frac{d}{dx})",
r"\sqrt{}",
r"\sqrt",
r"\overline{}",
r"\overline",
r"{",
r"}",
r"\mathit{x + y}",
r"\mathit{21}",
r"\frac{2}{}",
r"\frac{}{2}",
r"\int",
r"!",
r"!0",
r"_",
r"^",
r"|",
r"||x|",
r"()",
r"((((((((((((((((()))))))))))))))))",
r"-",
r"\frac{d}{dx} + \frac{d}{dt}",
r"f(x,,y)",
r"f(x,y,",
r"\sin^x",
r"\cos^2",
r"@",
r"#",
r"$",
r"%",
r"&",
r"*",
r"" "\\",
r"~",
r"\frac{(2 + x}{1 - x)}",
]
def test_not_parseable():
from sympy.parsing.latex import parse_latex, LaTeXParsingError
for latex_str in BAD_STRINGS:
with raises(LaTeXParsingError):
parse_latex(latex_str)
# At time of migration from latex2sympy, should fail but doesn't
FAILING_BAD_STRINGS = [
r"\cos 1 \cos",
r"f(,",
r"f()",
r"a \div \div b",
r"a \cdot \cdot b",
r"a // b",
r"a +",
r"1.1.1",
r"1 +",
r"a / b /",
]
@XFAIL
def test_failing_not_parseable():
from sympy.parsing.latex import parse_latex, LaTeXParsingError
for latex_str in FAILING_BAD_STRINGS:
with raises(LaTeXParsingError):
parse_latex(latex_str)
|
a1ee6f9b67882a7d3966209c5d468ef17e8709c466375a82b93b33ead07b42b9 | from sympy.external import import_module
from sympy.testing.pytest import ignore_warnings, raises
antlr4 = import_module("antlr4", warn_not_installed=False)
# disable tests if antlr4-python3-runtime is not present
if antlr4:
disabled = True
def test_no_import():
from sympy.parsing.latex import parse_latex
with ignore_warnings(UserWarning):
with raises(ImportError):
parse_latex('1 + 1')
|
5ce478e0f08fa36df823f6754279de480ad8f1a3e9a78c4fe3e77270c6a5410c | import os
import subprocess
import glob
from sympy.utilities.misc import debug
here = os.path.dirname(__file__)
grammar_file = os.path.abspath(os.path.join(here, "Autolev.g4"))
dir_autolev_antlr = os.path.join(here, "_antlr")
header = '''\
# *** GENERATED BY `setup.py antlr`, DO NOT EDIT BY HAND ***
#
# Generated with antlr4
# antlr4 is licensed under the BSD-3-Clause License
# https://github.com/antlr/antlr4/blob/master/LICENSE.txt
'''
def check_antlr_version():
debug("Checking antlr4 version...")
try:
debug(subprocess.check_output(["antlr4"])
.decode('utf-8').split("\n")[0])
return True
except (subprocess.CalledProcessError, FileNotFoundError):
debug("The 'antlr4' command line tool is not installed, "
"or not on your PATH.\n"
"> Please refer to the README.md file for more information.")
return False
def build_parser(output_dir=dir_autolev_antlr):
check_antlr_version()
debug("Updating ANTLR-generated code in {}".format(output_dir))
if not os.path.exists(output_dir):
os.makedirs(output_dir)
with open(os.path.join(output_dir, "__init__.py"), "w+") as fp:
fp.write(header)
args = [
"antlr4",
grammar_file,
"-o", output_dir,
"-no-visitor",
]
debug("Running code generation...\n\t$ {}".format(" ".join(args)))
subprocess.check_output(args, cwd=output_dir)
debug("Applying headers, removing unnecessary files and renaming...")
# Handle case insensitive file systems. If the files are already
# generated, they will be written to autolev* but Autolev*.* won't match them.
for path in (glob.glob(os.path.join(output_dir, "Autolev*.*")) or
glob.glob(os.path.join(output_dir, "autolev*.*"))):
# Remove files ending in .interp or .tokens as they are not needed.
if not path.endswith(".py"):
os.unlink(path)
continue
new_path = os.path.join(output_dir, os.path.basename(path).lower())
with open(path, 'r') as f:
lines = [line.rstrip().replace('AutolevParser import', 'autolevparser import') +'\n'
for line in f.readlines()]
os.unlink(path)
with open(new_path, "w") as out_file:
offset = 0
while lines[offset].startswith('#'):
offset += 1
out_file.write(header)
out_file.writelines(lines[offset:])
debug("\t{}".format(new_path))
return True
if __name__ == "__main__":
build_parser()
|
ad225ce8f88383645bcba8d5e05feecf0ad05e63928e33d023738e643f1b98ca | from importlib.metadata import version
from sympy.external import import_module
autolevparser = import_module('sympy.parsing.autolev._antlr.autolevparser',
import_kwargs={'fromlist': ['AutolevParser']})
autolevlexer = import_module('sympy.parsing.autolev._antlr.autolevlexer',
import_kwargs={'fromlist': ['AutolevLexer']})
autolevlistener = import_module('sympy.parsing.autolev._antlr.autolevlistener',
import_kwargs={'fromlist': ['AutolevListener']})
AutolevParser = getattr(autolevparser, 'AutolevParser', None)
AutolevLexer = getattr(autolevlexer, 'AutolevLexer', None)
AutolevListener = getattr(autolevlistener, 'AutolevListener', None)
def parse_autolev(autolev_code, include_numeric):
antlr4 = import_module('antlr4')
if not antlr4 or version('antlr4-python3-runtime') != '4.10':
raise ImportError("Autolev parsing requires the antlr4 Python package,"
" provided by pip (antlr4-python3-runtime)"
" conda (antlr-python-runtime), version 4.10")
try:
l = autolev_code.readlines()
input_stream = antlr4.InputStream("".join(l))
except Exception:
input_stream = antlr4.InputStream(autolev_code)
if AutolevListener:
from ._listener_autolev_antlr import MyListener
lexer = AutolevLexer(input_stream)
token_stream = antlr4.CommonTokenStream(lexer)
parser = AutolevParser(token_stream)
tree = parser.prog()
my_listener = MyListener(include_numeric)
walker = antlr4.ParseTreeWalker()
walker.walk(my_listener, tree)
return "".join(my_listener.output_code)
|
89dff8a5b708e2701ad2d1ee98dd25657d146dbf81689ddccc6c22411fe364f1 | import os
import subprocess
import glob
from sympy.utilities.misc import debug
here = os.path.dirname(__file__)
grammar_file = os.path.abspath(os.path.join(here, "LaTeX.g4"))
dir_latex_antlr = os.path.join(here, "_antlr")
header = '''\
# *** GENERATED BY `setup.py antlr`, DO NOT EDIT BY HAND ***
#
# Generated from ../LaTeX.g4, derived from latex2sympy
# latex2sympy is licensed under the MIT license
# https://github.com/augustt198/latex2sympy/blob/master/LICENSE.txt
#
# Generated with antlr4
# antlr4 is licensed under the BSD-3-Clause License
# https://github.com/antlr/antlr4/blob/master/LICENSE.txt
'''
def check_antlr_version():
debug("Checking antlr4 version...")
try:
debug(subprocess.check_output(["antlr4"])
.decode('utf-8').split("\n")[0])
return True
except (subprocess.CalledProcessError, FileNotFoundError):
debug("The 'antlr4' command line tool is not installed, "
"or not on your PATH.\n"
"> Please refer to the README.md file for more information.")
return False
def build_parser(output_dir=dir_latex_antlr):
check_antlr_version()
debug("Updating ANTLR-generated code in {}".format(output_dir))
if not os.path.exists(output_dir):
os.makedirs(output_dir)
with open(os.path.join(output_dir, "__init__.py"), "w+") as fp:
fp.write(header)
args = [
"antlr4",
grammar_file,
"-o", output_dir,
# for now, not generating these as latex2sympy did not use them
"-no-visitor",
"-no-listener",
]
debug("Running code generation...\n\t$ {}".format(" ".join(args)))
subprocess.check_output(args, cwd=output_dir)
debug("Applying headers, removing unnecessary files and renaming...")
# Handle case insensitive file systems. If the files are already
# generated, they will be written to latex* but LaTeX*.* won't match them.
for path in (glob.glob(os.path.join(output_dir, "LaTeX*.*")) or
glob.glob(os.path.join(output_dir, "latex*.*"))):
# Remove files ending in .interp or .tokens as they are not needed.
if not path.endswith(".py"):
os.unlink(path)
continue
new_path = os.path.join(output_dir, os.path.basename(path).lower())
with open(path, 'r') as f:
lines = [line.rstrip() + '\n' for line in f.readlines()]
os.unlink(path)
with open(new_path, "w") as out_file:
offset = 0
while lines[offset].startswith('#'):
offset += 1
out_file.write(header)
out_file.writelines(lines[offset:])
debug("\t{}".format(new_path))
return True
if __name__ == "__main__":
build_parser()
|
24b329225f6a23a2c45c9441e2b18ef7d7fbde0ca9a2ada4c6e0ca067eaa2975 | # Ported from latex2sympy by @augustt198
# https://github.com/augustt198/latex2sympy
# See license in LICENSE.txt
from importlib.metadata import version
import sympy
from sympy.external import import_module
from sympy.printing.str import StrPrinter
from sympy.physics.quantum.state import Bra, Ket
from .errors import LaTeXParsingError
LaTeXParser = LaTeXLexer = MathErrorListener = None
try:
LaTeXParser = import_module('sympy.parsing.latex._antlr.latexparser',
import_kwargs={'fromlist': ['LaTeXParser']}).LaTeXParser
LaTeXLexer = import_module('sympy.parsing.latex._antlr.latexlexer',
import_kwargs={'fromlist': ['LaTeXLexer']}).LaTeXLexer
except Exception:
pass
ErrorListener = import_module('antlr4.error.ErrorListener',
warn_not_installed=True,
import_kwargs={'fromlist': ['ErrorListener']}
)
if ErrorListener:
class MathErrorListener(ErrorListener.ErrorListener): # type: ignore
def __init__(self, src):
super(ErrorListener.ErrorListener, self).__init__()
self.src = src
def syntaxError(self, recog, symbol, line, col, msg, e):
fmt = "%s\n%s\n%s"
marker = "~" * col + "^"
if msg.startswith("missing"):
err = fmt % (msg, self.src, marker)
elif msg.startswith("no viable"):
err = fmt % ("I expected something else here", self.src, marker)
elif msg.startswith("mismatched"):
names = LaTeXParser.literalNames
expected = [
names[i] for i in e.getExpectedTokens() if i < len(names)
]
if len(expected) < 10:
expected = " ".join(expected)
err = (fmt % ("I expected one of these: " + expected, self.src,
marker))
else:
err = (fmt % ("I expected something else here", self.src,
marker))
else:
err = fmt % ("I don't understand this", self.src, marker)
raise LaTeXParsingError(err)
def parse_latex(sympy):
antlr4 = import_module('antlr4')
if None in [antlr4, MathErrorListener] or \
version('antlr4-python3-runtime') != '4.10':
raise ImportError("LaTeX parsing requires the antlr4 Python package,"
" provided by pip (antlr4-python3-runtime) or"
" conda (antlr-python-runtime), version 4.10")
matherror = MathErrorListener(sympy)
stream = antlr4.InputStream(sympy)
lex = LaTeXLexer(stream)
lex.removeErrorListeners()
lex.addErrorListener(matherror)
tokens = antlr4.CommonTokenStream(lex)
parser = LaTeXParser(tokens)
# remove default console error listener
parser.removeErrorListeners()
parser.addErrorListener(matherror)
relation = parser.math().relation()
expr = convert_relation(relation)
return expr
def convert_relation(rel):
if rel.expr():
return convert_expr(rel.expr())
lh = convert_relation(rel.relation(0))
rh = convert_relation(rel.relation(1))
if rel.LT():
return sympy.StrictLessThan(lh, rh)
elif rel.LTE():
return sympy.LessThan(lh, rh)
elif rel.GT():
return sympy.StrictGreaterThan(lh, rh)
elif rel.GTE():
return sympy.GreaterThan(lh, rh)
elif rel.EQUAL():
return sympy.Eq(lh, rh)
elif rel.NEQ():
return sympy.Ne(lh, rh)
def convert_expr(expr):
return convert_add(expr.additive())
def convert_add(add):
if add.ADD():
lh = convert_add(add.additive(0))
rh = convert_add(add.additive(1))
return sympy.Add(lh, rh, evaluate=False)
elif add.SUB():
lh = convert_add(add.additive(0))
rh = convert_add(add.additive(1))
return sympy.Add(lh, sympy.Mul(-1, rh, evaluate=False),
evaluate=False)
else:
return convert_mp(add.mp())
def convert_mp(mp):
if hasattr(mp, 'mp'):
mp_left = mp.mp(0)
mp_right = mp.mp(1)
else:
mp_left = mp.mp_nofunc(0)
mp_right = mp.mp_nofunc(1)
if mp.MUL() or mp.CMD_TIMES() or mp.CMD_CDOT():
lh = convert_mp(mp_left)
rh = convert_mp(mp_right)
return sympy.Mul(lh, rh, evaluate=False)
elif mp.DIV() or mp.CMD_DIV() or mp.COLON():
lh = convert_mp(mp_left)
rh = convert_mp(mp_right)
return sympy.Mul(lh, sympy.Pow(rh, -1, evaluate=False), evaluate=False)
else:
if hasattr(mp, 'unary'):
return convert_unary(mp.unary())
else:
return convert_unary(mp.unary_nofunc())
def convert_unary(unary):
if hasattr(unary, 'unary'):
nested_unary = unary.unary()
else:
nested_unary = unary.unary_nofunc()
if hasattr(unary, 'postfix_nofunc'):
first = unary.postfix()
tail = unary.postfix_nofunc()
postfix = [first] + tail
else:
postfix = unary.postfix()
if unary.ADD():
return convert_unary(nested_unary)
elif unary.SUB():
numabs = convert_unary(nested_unary)
# Use Integer(-n) instead of Mul(-1, n)
return -numabs
elif postfix:
return convert_postfix_list(postfix)
def convert_postfix_list(arr, i=0):
if i >= len(arr):
raise LaTeXParsingError("Index out of bounds")
res = convert_postfix(arr[i])
if isinstance(res, sympy.Expr):
if i == len(arr) - 1:
return res # nothing to multiply by
else:
if i > 0:
left = convert_postfix(arr[i - 1])
right = convert_postfix(arr[i + 1])
if isinstance(left, sympy.Expr) and isinstance(
right, sympy.Expr):
left_syms = convert_postfix(arr[i - 1]).atoms(sympy.Symbol)
right_syms = convert_postfix(arr[i + 1]).atoms(
sympy.Symbol)
# if the left and right sides contain no variables and the
# symbol in between is 'x', treat as multiplication.
if not (left_syms or right_syms) and str(res) == 'x':
return convert_postfix_list(arr, i + 1)
# multiply by next
return sympy.Mul(
res, convert_postfix_list(arr, i + 1), evaluate=False)
else: # must be derivative
wrt = res[0]
if i == len(arr) - 1:
raise LaTeXParsingError("Expected expression for derivative")
else:
expr = convert_postfix_list(arr, i + 1)
return sympy.Derivative(expr, wrt)
def do_subs(expr, at):
if at.expr():
at_expr = convert_expr(at.expr())
syms = at_expr.atoms(sympy.Symbol)
if len(syms) == 0:
return expr
elif len(syms) > 0:
sym = next(iter(syms))
return expr.subs(sym, at_expr)
elif at.equality():
lh = convert_expr(at.equality().expr(0))
rh = convert_expr(at.equality().expr(1))
return expr.subs(lh, rh)
def convert_postfix(postfix):
if hasattr(postfix, 'exp'):
exp_nested = postfix.exp()
else:
exp_nested = postfix.exp_nofunc()
exp = convert_exp(exp_nested)
for op in postfix.postfix_op():
if op.BANG():
if isinstance(exp, list):
raise LaTeXParsingError("Cannot apply postfix to derivative")
exp = sympy.factorial(exp, evaluate=False)
elif op.eval_at():
ev = op.eval_at()
at_b = None
at_a = None
if ev.eval_at_sup():
at_b = do_subs(exp, ev.eval_at_sup())
if ev.eval_at_sub():
at_a = do_subs(exp, ev.eval_at_sub())
if at_b is not None and at_a is not None:
exp = sympy.Add(at_b, -1 * at_a, evaluate=False)
elif at_b is not None:
exp = at_b
elif at_a is not None:
exp = at_a
return exp
def convert_exp(exp):
if hasattr(exp, 'exp'):
exp_nested = exp.exp()
else:
exp_nested = exp.exp_nofunc()
if exp_nested:
base = convert_exp(exp_nested)
if isinstance(base, list):
raise LaTeXParsingError("Cannot raise derivative to power")
if exp.atom():
exponent = convert_atom(exp.atom())
elif exp.expr():
exponent = convert_expr(exp.expr())
return sympy.Pow(base, exponent, evaluate=False)
else:
if hasattr(exp, 'comp'):
return convert_comp(exp.comp())
else:
return convert_comp(exp.comp_nofunc())
def convert_comp(comp):
if comp.group():
return convert_expr(comp.group().expr())
elif comp.abs_group():
return sympy.Abs(convert_expr(comp.abs_group().expr()), evaluate=False)
elif comp.atom():
return convert_atom(comp.atom())
elif comp.floor():
return convert_floor(comp.floor())
elif comp.ceil():
return convert_ceil(comp.ceil())
elif comp.func():
return convert_func(comp.func())
def convert_atom(atom):
if atom.LETTER():
sname = atom.LETTER().getText()
if atom.subexpr():
if atom.subexpr().expr(): # subscript is expr
subscript = convert_expr(atom.subexpr().expr())
else: # subscript is atom
subscript = convert_atom(atom.subexpr().atom())
sname += '_{' + StrPrinter().doprint(subscript) + '}'
if atom.SINGLE_QUOTES():
sname += atom.SINGLE_QUOTES().getText() # put after subscript for easy identify
return sympy.Symbol(sname)
elif atom.SYMBOL():
s = atom.SYMBOL().getText()[1:]
if s == "infty":
return sympy.oo
else:
if atom.subexpr():
subscript = None
if atom.subexpr().expr(): # subscript is expr
subscript = convert_expr(atom.subexpr().expr())
else: # subscript is atom
subscript = convert_atom(atom.subexpr().atom())
subscriptName = StrPrinter().doprint(subscript)
s += '_{' + subscriptName + '}'
return sympy.Symbol(s)
elif atom.number():
s = atom.number().getText().replace(",", "")
return sympy.Number(s)
elif atom.DIFFERENTIAL():
var = get_differential_var(atom.DIFFERENTIAL())
return sympy.Symbol('d' + var.name)
elif atom.mathit():
text = rule2text(atom.mathit().mathit_text())
return sympy.Symbol(text)
elif atom.frac():
return convert_frac(atom.frac())
elif atom.binom():
return convert_binom(atom.binom())
elif atom.bra():
val = convert_expr(atom.bra().expr())
return Bra(val)
elif atom.ket():
val = convert_expr(atom.ket().expr())
return Ket(val)
def rule2text(ctx):
stream = ctx.start.getInputStream()
# starting index of starting token
startIdx = ctx.start.start
# stopping index of stopping token
stopIdx = ctx.stop.stop
return stream.getText(startIdx, stopIdx)
def convert_frac(frac):
diff_op = False
partial_op = False
if frac.lower and frac.upper:
lower_itv = frac.lower.getSourceInterval()
lower_itv_len = lower_itv[1] - lower_itv[0] + 1
if (frac.lower.start == frac.lower.stop
and frac.lower.start.type == LaTeXLexer.DIFFERENTIAL):
wrt = get_differential_var_str(frac.lower.start.text)
diff_op = True
elif (lower_itv_len == 2 and frac.lower.start.type == LaTeXLexer.SYMBOL
and frac.lower.start.text == '\\partial'
and (frac.lower.stop.type == LaTeXLexer.LETTER
or frac.lower.stop.type == LaTeXLexer.SYMBOL)):
partial_op = True
wrt = frac.lower.stop.text
if frac.lower.stop.type == LaTeXLexer.SYMBOL:
wrt = wrt[1:]
if diff_op or partial_op:
wrt = sympy.Symbol(wrt)
if (diff_op and frac.upper.start == frac.upper.stop
and frac.upper.start.type == LaTeXLexer.LETTER
and frac.upper.start.text == 'd'):
return [wrt]
elif (partial_op and frac.upper.start == frac.upper.stop
and frac.upper.start.type == LaTeXLexer.SYMBOL
and frac.upper.start.text == '\\partial'):
return [wrt]
upper_text = rule2text(frac.upper)
expr_top = None
if diff_op and upper_text.startswith('d'):
expr_top = parse_latex(upper_text[1:])
elif partial_op and frac.upper.start.text == '\\partial':
expr_top = parse_latex(upper_text[len('\\partial'):])
if expr_top:
return sympy.Derivative(expr_top, wrt)
if frac.upper:
expr_top = convert_expr(frac.upper)
else:
expr_top = sympy.Number(frac.upperd.text)
if frac.lower:
expr_bot = convert_expr(frac.lower)
else:
expr_bot = sympy.Number(frac.lowerd.text)
inverse_denom = sympy.Pow(expr_bot, -1, evaluate=False)
if expr_top == 1:
return inverse_denom
else:
return sympy.Mul(expr_top, inverse_denom, evaluate=False)
def convert_binom(binom):
expr_n = convert_expr(binom.n)
expr_k = convert_expr(binom.k)
return sympy.binomial(expr_n, expr_k, evaluate=False)
def convert_floor(floor):
val = convert_expr(floor.val)
return sympy.floor(val, evaluate=False)
def convert_ceil(ceil):
val = convert_expr(ceil.val)
return sympy.ceiling(val, evaluate=False)
def convert_func(func):
if func.func_normal():
if func.L_PAREN(): # function called with parenthesis
arg = convert_func_arg(func.func_arg())
else:
arg = convert_func_arg(func.func_arg_noparens())
name = func.func_normal().start.text[1:]
# change arc<trig> -> a<trig>
if name in [
"arcsin", "arccos", "arctan", "arccsc", "arcsec", "arccot"
]:
name = "a" + name[3:]
expr = getattr(sympy.functions, name)(arg, evaluate=False)
if name in ["arsinh", "arcosh", "artanh"]:
name = "a" + name[2:]
expr = getattr(sympy.functions, name)(arg, evaluate=False)
if name == "exp":
expr = sympy.exp(arg, evaluate=False)
if name in ("log", "lg", "ln"):
if func.subexpr():
if func.subexpr().expr():
base = convert_expr(func.subexpr().expr())
else:
base = convert_atom(func.subexpr().atom())
elif name == "lg": # ISO 80000-2:2019
base = 10
elif name in ("ln", "log"): # SymPy's latex printer prints ln as log by default
base = sympy.E
expr = sympy.log(arg, base, evaluate=False)
func_pow = None
should_pow = True
if func.supexpr():
if func.supexpr().expr():
func_pow = convert_expr(func.supexpr().expr())
else:
func_pow = convert_atom(func.supexpr().atom())
if name in [
"sin", "cos", "tan", "csc", "sec", "cot", "sinh", "cosh",
"tanh"
]:
if func_pow == -1:
name = "a" + name
should_pow = False
expr = getattr(sympy.functions, name)(arg, evaluate=False)
if func_pow and should_pow:
expr = sympy.Pow(expr, func_pow, evaluate=False)
return expr
elif func.LETTER() or func.SYMBOL():
if func.LETTER():
fname = func.LETTER().getText()
elif func.SYMBOL():
fname = func.SYMBOL().getText()[1:]
fname = str(fname) # can't be unicode
if func.subexpr():
if func.subexpr().expr(): # subscript is expr
subscript = convert_expr(func.subexpr().expr())
else: # subscript is atom
subscript = convert_atom(func.subexpr().atom())
subscriptName = StrPrinter().doprint(subscript)
fname += '_{' + subscriptName + '}'
if func.SINGLE_QUOTES():
fname += func.SINGLE_QUOTES().getText()
input_args = func.args()
output_args = []
while input_args.args(): # handle multiple arguments to function
output_args.append(convert_expr(input_args.expr()))
input_args = input_args.args()
output_args.append(convert_expr(input_args.expr()))
return sympy.Function(fname)(*output_args)
elif func.FUNC_INT():
return handle_integral(func)
elif func.FUNC_SQRT():
expr = convert_expr(func.base)
if func.root:
r = convert_expr(func.root)
return sympy.root(expr, r, evaluate=False)
else:
return sympy.sqrt(expr, evaluate=False)
elif func.FUNC_OVERLINE():
expr = convert_expr(func.base)
return sympy.conjugate(expr, evaluate=False)
elif func.FUNC_SUM():
return handle_sum_or_prod(func, "summation")
elif func.FUNC_PROD():
return handle_sum_or_prod(func, "product")
elif func.FUNC_LIM():
return handle_limit(func)
def convert_func_arg(arg):
if hasattr(arg, 'expr'):
return convert_expr(arg.expr())
else:
return convert_mp(arg.mp_nofunc())
def handle_integral(func):
if func.additive():
integrand = convert_add(func.additive())
elif func.frac():
integrand = convert_frac(func.frac())
else:
integrand = 1
int_var = None
if func.DIFFERENTIAL():
int_var = get_differential_var(func.DIFFERENTIAL())
else:
for sym in integrand.atoms(sympy.Symbol):
s = str(sym)
if len(s) > 1 and s[0] == 'd':
if s[1] == '\\':
int_var = sympy.Symbol(s[2:])
else:
int_var = sympy.Symbol(s[1:])
int_sym = sym
if int_var:
integrand = integrand.subs(int_sym, 1)
else:
# Assume dx by default
int_var = sympy.Symbol('x')
if func.subexpr():
if func.subexpr().atom():
lower = convert_atom(func.subexpr().atom())
else:
lower = convert_expr(func.subexpr().expr())
if func.supexpr().atom():
upper = convert_atom(func.supexpr().atom())
else:
upper = convert_expr(func.supexpr().expr())
return sympy.Integral(integrand, (int_var, lower, upper))
else:
return sympy.Integral(integrand, int_var)
def handle_sum_or_prod(func, name):
val = convert_mp(func.mp())
iter_var = convert_expr(func.subeq().equality().expr(0))
start = convert_expr(func.subeq().equality().expr(1))
if func.supexpr().expr(): # ^{expr}
end = convert_expr(func.supexpr().expr())
else: # ^atom
end = convert_atom(func.supexpr().atom())
if name == "summation":
return sympy.Sum(val, (iter_var, start, end))
elif name == "product":
return sympy.Product(val, (iter_var, start, end))
def handle_limit(func):
sub = func.limit_sub()
if sub.LETTER():
var = sympy.Symbol(sub.LETTER().getText())
elif sub.SYMBOL():
var = sympy.Symbol(sub.SYMBOL().getText()[1:])
else:
var = sympy.Symbol('x')
if sub.SUB():
direction = "-"
else:
direction = "+"
approaching = convert_expr(sub.expr())
content = convert_mp(func.mp())
return sympy.Limit(content, var, approaching, direction)
def get_differential_var(d):
text = get_differential_var_str(d.getText())
return sympy.Symbol(text)
def get_differential_var_str(text):
for i in range(1, len(text)):
c = text[i]
if not (c == " " or c == "\r" or c == "\n" or c == "\t"):
idx = i
break
text = text[idx:]
if text[0] == "\\":
text = text[1:]
return text
|
310e1969ca53b8ff8d9abb855ca7562d06ada1e54943c49a050d839d8bedc84f | # *** GENERATED BY `setup.py antlr`, DO NOT EDIT BY HAND ***
#
# Generated with antlr4
# antlr4 is licensed under the BSD-3-Clause License
# https://github.com/antlr/antlr4/blob/master/LICENSE.txt
|
f82719f416c0043dc6016aada4bb457eac60feb061a6b8376af29c90fc818e0e | # *** GENERATED BY `setup.py antlr`, DO NOT EDIT BY HAND ***
#
# Generated with antlr4
# antlr4 is licensed under the BSD-3-Clause License
# https://github.com/antlr/antlr4/blob/master/LICENSE.txt
from antlr4 import *
from io import StringIO
import sys
if sys.version_info[1] > 5:
from typing import TextIO
else:
from typing.io import TextIO
def serializedATN():
return [
4,0,49,393,6,-1,2,0,7,0,2,1,7,1,2,2,7,2,2,3,7,3,2,4,7,4,2,5,7,5,
2,6,7,6,2,7,7,7,2,8,7,8,2,9,7,9,2,10,7,10,2,11,7,11,2,12,7,12,2,
13,7,13,2,14,7,14,2,15,7,15,2,16,7,16,2,17,7,17,2,18,7,18,2,19,7,
19,2,20,7,20,2,21,7,21,2,22,7,22,2,23,7,23,2,24,7,24,2,25,7,25,2,
26,7,26,2,27,7,27,2,28,7,28,2,29,7,29,2,30,7,30,2,31,7,31,2,32,7,
32,2,33,7,33,2,34,7,34,2,35,7,35,2,36,7,36,2,37,7,37,2,38,7,38,2,
39,7,39,2,40,7,40,2,41,7,41,2,42,7,42,2,43,7,43,2,44,7,44,2,45,7,
45,2,46,7,46,2,47,7,47,2,48,7,48,2,49,7,49,2,50,7,50,1,0,1,0,1,1,
1,1,1,2,1,2,1,3,1,3,1,3,1,4,1,4,1,4,1,5,1,5,1,5,1,6,1,6,1,6,1,7,
1,7,1,7,1,8,1,8,1,8,1,9,1,9,1,10,1,10,1,11,1,11,1,12,1,12,1,13,1,
13,1,14,1,14,1,15,1,15,1,16,1,16,1,17,1,17,1,18,1,18,1,19,1,19,1,
20,1,20,1,21,1,21,1,21,1,22,1,22,1,22,1,22,1,23,1,23,1,24,1,24,1,
25,1,25,1,26,1,26,1,26,1,26,1,26,1,27,1,27,1,27,1,27,1,27,1,27,1,
27,1,27,1,28,1,28,1,28,1,28,1,28,1,28,3,28,184,8,28,1,29,1,29,1,
29,1,29,1,29,1,29,1,29,1,30,1,30,1,30,1,30,1,30,1,31,1,31,1,31,1,
31,1,31,1,31,1,31,1,31,1,31,1,31,1,31,1,32,1,32,1,32,1,32,1,32,1,
32,1,32,1,33,1,33,1,33,1,33,1,33,1,33,1,33,1,33,1,33,1,33,1,34,1,
34,1,34,1,34,1,34,1,34,3,34,232,8,34,1,35,1,35,1,35,1,35,1,35,1,
35,3,35,240,8,35,1,36,1,36,1,36,1,36,1,36,1,36,1,36,1,36,1,36,3,
36,251,8,36,1,37,1,37,1,37,1,37,1,37,1,37,3,37,259,8,37,1,38,1,38,
1,38,1,38,1,38,1,38,1,38,1,38,1,38,3,38,270,8,38,1,39,1,39,1,39,
1,39,1,39,1,39,1,39,1,39,1,39,1,39,3,39,282,8,39,1,40,1,40,1,40,
1,40,1,40,1,40,1,40,1,40,1,40,1,40,1,41,1,41,1,41,1,41,1,41,1,41,
1,41,1,41,1,41,3,41,303,8,41,1,42,1,42,1,42,1,42,1,42,1,42,1,42,
1,42,1,42,1,42,1,42,1,42,1,42,1,42,1,42,3,42,320,8,42,1,43,5,43,
323,8,43,10,43,12,43,326,9,43,1,44,1,44,1,45,4,45,331,8,45,11,45,
12,45,332,1,46,4,46,336,8,46,11,46,12,46,337,1,46,1,46,5,46,342,
8,46,10,46,12,46,345,9,46,1,46,1,46,4,46,349,8,46,11,46,12,46,350,
3,46,353,8,46,1,47,1,47,1,47,1,47,1,47,1,47,1,47,1,47,1,47,3,47,
364,8,47,1,48,1,48,5,48,368,8,48,10,48,12,48,371,9,48,1,48,3,48,
374,8,48,1,48,1,48,1,48,1,48,1,49,1,49,5,49,382,8,49,10,49,12,49,
385,9,49,1,50,4,50,388,8,50,11,50,12,50,389,1,50,1,50,1,369,0,51,
1,1,3,2,5,3,7,4,9,5,11,6,13,7,15,8,17,9,19,10,21,11,23,12,25,13,
27,14,29,15,31,16,33,17,35,18,37,19,39,20,41,21,43,22,45,23,47,24,
49,25,51,26,53,27,55,28,57,29,59,30,61,31,63,32,65,33,67,34,69,35,
71,36,73,37,75,38,77,39,79,40,81,41,83,42,85,43,87,0,89,0,91,44,
93,45,95,46,97,47,99,48,101,49,1,0,24,2,0,77,77,109,109,2,0,65,65,
97,97,2,0,83,83,115,115,2,0,73,73,105,105,2,0,78,78,110,110,2,0,
69,69,101,101,2,0,82,82,114,114,2,0,84,84,116,116,2,0,80,80,112,
112,2,0,85,85,117,117,2,0,79,79,111,111,2,0,86,86,118,118,2,0,89,
89,121,121,2,0,67,67,99,99,2,0,68,68,100,100,2,0,87,87,119,119,2,
0,70,70,102,102,2,0,66,66,98,98,2,0,76,76,108,108,2,0,71,71,103,
103,1,0,48,57,2,0,65,90,97,122,4,0,48,57,65,90,95,95,97,122,4,0,
9,10,13,13,32,32,38,38,410,0,1,1,0,0,0,0,3,1,0,0,0,0,5,1,0,0,0,0,
7,1,0,0,0,0,9,1,0,0,0,0,11,1,0,0,0,0,13,1,0,0,0,0,15,1,0,0,0,0,17,
1,0,0,0,0,19,1,0,0,0,0,21,1,0,0,0,0,23,1,0,0,0,0,25,1,0,0,0,0,27,
1,0,0,0,0,29,1,0,0,0,0,31,1,0,0,0,0,33,1,0,0,0,0,35,1,0,0,0,0,37,
1,0,0,0,0,39,1,0,0,0,0,41,1,0,0,0,0,43,1,0,0,0,0,45,1,0,0,0,0,47,
1,0,0,0,0,49,1,0,0,0,0,51,1,0,0,0,0,53,1,0,0,0,0,55,1,0,0,0,0,57,
1,0,0,0,0,59,1,0,0,0,0,61,1,0,0,0,0,63,1,0,0,0,0,65,1,0,0,0,0,67,
1,0,0,0,0,69,1,0,0,0,0,71,1,0,0,0,0,73,1,0,0,0,0,75,1,0,0,0,0,77,
1,0,0,0,0,79,1,0,0,0,0,81,1,0,0,0,0,83,1,0,0,0,0,85,1,0,0,0,0,91,
1,0,0,0,0,93,1,0,0,0,0,95,1,0,0,0,0,97,1,0,0,0,0,99,1,0,0,0,0,101,
1,0,0,0,1,103,1,0,0,0,3,105,1,0,0,0,5,107,1,0,0,0,7,109,1,0,0,0,
9,112,1,0,0,0,11,115,1,0,0,0,13,118,1,0,0,0,15,121,1,0,0,0,17,124,
1,0,0,0,19,127,1,0,0,0,21,129,1,0,0,0,23,131,1,0,0,0,25,133,1,0,
0,0,27,135,1,0,0,0,29,137,1,0,0,0,31,139,1,0,0,0,33,141,1,0,0,0,
35,143,1,0,0,0,37,145,1,0,0,0,39,147,1,0,0,0,41,149,1,0,0,0,43,151,
1,0,0,0,45,154,1,0,0,0,47,158,1,0,0,0,49,160,1,0,0,0,51,162,1,0,
0,0,53,164,1,0,0,0,55,169,1,0,0,0,57,177,1,0,0,0,59,185,1,0,0,0,
61,192,1,0,0,0,63,197,1,0,0,0,65,208,1,0,0,0,67,215,1,0,0,0,69,225,
1,0,0,0,71,233,1,0,0,0,73,241,1,0,0,0,75,252,1,0,0,0,77,260,1,0,
0,0,79,271,1,0,0,0,81,283,1,0,0,0,83,293,1,0,0,0,85,304,1,0,0,0,
87,324,1,0,0,0,89,327,1,0,0,0,91,330,1,0,0,0,93,352,1,0,0,0,95,363,
1,0,0,0,97,365,1,0,0,0,99,379,1,0,0,0,101,387,1,0,0,0,103,104,5,
91,0,0,104,2,1,0,0,0,105,106,5,93,0,0,106,4,1,0,0,0,107,108,5,61,
0,0,108,6,1,0,0,0,109,110,5,43,0,0,110,111,5,61,0,0,111,8,1,0,0,
0,112,113,5,45,0,0,113,114,5,61,0,0,114,10,1,0,0,0,115,116,5,58,
0,0,116,117,5,61,0,0,117,12,1,0,0,0,118,119,5,42,0,0,119,120,5,61,
0,0,120,14,1,0,0,0,121,122,5,47,0,0,122,123,5,61,0,0,123,16,1,0,
0,0,124,125,5,94,0,0,125,126,5,61,0,0,126,18,1,0,0,0,127,128,5,44,
0,0,128,20,1,0,0,0,129,130,5,39,0,0,130,22,1,0,0,0,131,132,5,40,
0,0,132,24,1,0,0,0,133,134,5,41,0,0,134,26,1,0,0,0,135,136,5,123,
0,0,136,28,1,0,0,0,137,138,5,125,0,0,138,30,1,0,0,0,139,140,5,58,
0,0,140,32,1,0,0,0,141,142,5,43,0,0,142,34,1,0,0,0,143,144,5,45,
0,0,144,36,1,0,0,0,145,146,5,59,0,0,146,38,1,0,0,0,147,148,5,46,
0,0,148,40,1,0,0,0,149,150,5,62,0,0,150,42,1,0,0,0,151,152,5,48,
0,0,152,153,5,62,0,0,153,44,1,0,0,0,154,155,5,49,0,0,155,156,5,62,
0,0,156,157,5,62,0,0,157,46,1,0,0,0,158,159,5,94,0,0,159,48,1,0,
0,0,160,161,5,42,0,0,161,50,1,0,0,0,162,163,5,47,0,0,163,52,1,0,
0,0,164,165,7,0,0,0,165,166,7,1,0,0,166,167,7,2,0,0,167,168,7,2,
0,0,168,54,1,0,0,0,169,170,7,3,0,0,170,171,7,4,0,0,171,172,7,5,0,
0,172,173,7,6,0,0,173,174,7,7,0,0,174,175,7,3,0,0,175,176,7,1,0,
0,176,56,1,0,0,0,177,178,7,3,0,0,178,179,7,4,0,0,179,180,7,8,0,0,
180,181,7,9,0,0,181,183,7,7,0,0,182,184,7,2,0,0,183,182,1,0,0,0,
183,184,1,0,0,0,184,58,1,0,0,0,185,186,7,10,0,0,186,187,7,9,0,0,
187,188,7,7,0,0,188,189,7,8,0,0,189,190,7,9,0,0,190,191,7,7,0,0,
191,60,1,0,0,0,192,193,7,2,0,0,193,194,7,1,0,0,194,195,7,11,0,0,
195,196,7,5,0,0,196,62,1,0,0,0,197,198,7,9,0,0,198,199,7,4,0,0,199,
200,7,3,0,0,200,201,7,7,0,0,201,202,7,2,0,0,202,203,7,12,0,0,203,
204,7,2,0,0,204,205,7,7,0,0,205,206,7,5,0,0,206,207,7,0,0,0,207,
64,1,0,0,0,208,209,7,5,0,0,209,210,7,4,0,0,210,211,7,13,0,0,211,
212,7,10,0,0,212,213,7,14,0,0,213,214,7,5,0,0,214,66,1,0,0,0,215,
216,7,4,0,0,216,217,7,5,0,0,217,218,7,15,0,0,218,219,7,7,0,0,219,
220,7,10,0,0,220,221,7,4,0,0,221,222,7,3,0,0,222,223,7,1,0,0,223,
224,7,4,0,0,224,68,1,0,0,0,225,226,7,16,0,0,226,227,7,6,0,0,227,
228,7,1,0,0,228,229,7,0,0,0,229,231,7,5,0,0,230,232,7,2,0,0,231,
230,1,0,0,0,231,232,1,0,0,0,232,70,1,0,0,0,233,234,7,17,0,0,234,
235,7,10,0,0,235,236,7,14,0,0,236,237,7,3,0,0,237,239,7,5,0,0,238,
240,7,2,0,0,239,238,1,0,0,0,239,240,1,0,0,0,240,72,1,0,0,0,241,242,
7,8,0,0,242,243,7,1,0,0,243,244,7,6,0,0,244,245,7,7,0,0,245,246,
7,3,0,0,246,247,7,13,0,0,247,248,7,18,0,0,248,250,7,5,0,0,249,251,
7,2,0,0,250,249,1,0,0,0,250,251,1,0,0,0,251,74,1,0,0,0,252,253,7,
8,0,0,253,254,7,10,0,0,254,255,7,3,0,0,255,256,7,4,0,0,256,258,7,
7,0,0,257,259,7,2,0,0,258,257,1,0,0,0,258,259,1,0,0,0,259,76,1,0,
0,0,260,261,7,13,0,0,261,262,7,10,0,0,262,263,7,4,0,0,263,264,7,
2,0,0,264,265,7,7,0,0,265,266,7,1,0,0,266,267,7,4,0,0,267,269,7,
7,0,0,268,270,7,2,0,0,269,268,1,0,0,0,269,270,1,0,0,0,270,78,1,0,
0,0,271,272,7,2,0,0,272,273,7,8,0,0,273,274,7,5,0,0,274,275,7,13,
0,0,275,276,7,3,0,0,276,277,7,16,0,0,277,278,7,3,0,0,278,279,7,5,
0,0,279,281,7,14,0,0,280,282,7,2,0,0,281,280,1,0,0,0,281,282,1,0,
0,0,282,80,1,0,0,0,283,284,7,3,0,0,284,285,7,0,0,0,285,286,7,1,0,
0,286,287,7,19,0,0,287,288,7,3,0,0,288,289,7,4,0,0,289,290,7,1,0,
0,290,291,7,6,0,0,291,292,7,12,0,0,292,82,1,0,0,0,293,294,7,11,0,
0,294,295,7,1,0,0,295,296,7,6,0,0,296,297,7,3,0,0,297,298,7,1,0,
0,298,299,7,17,0,0,299,300,7,18,0,0,300,302,7,5,0,0,301,303,7,2,
0,0,302,301,1,0,0,0,302,303,1,0,0,0,303,84,1,0,0,0,304,305,7,0,0,
0,305,306,7,10,0,0,306,307,7,7,0,0,307,308,7,3,0,0,308,309,7,10,
0,0,309,310,7,4,0,0,310,311,7,11,0,0,311,312,7,1,0,0,312,313,7,6,
0,0,313,314,7,3,0,0,314,315,7,1,0,0,315,316,7,17,0,0,316,317,7,18,
0,0,317,319,7,5,0,0,318,320,7,2,0,0,319,318,1,0,0,0,319,320,1,0,
0,0,320,86,1,0,0,0,321,323,5,39,0,0,322,321,1,0,0,0,323,326,1,0,
0,0,324,322,1,0,0,0,324,325,1,0,0,0,325,88,1,0,0,0,326,324,1,0,0,
0,327,328,7,20,0,0,328,90,1,0,0,0,329,331,7,20,0,0,330,329,1,0,0,
0,331,332,1,0,0,0,332,330,1,0,0,0,332,333,1,0,0,0,333,92,1,0,0,0,
334,336,3,89,44,0,335,334,1,0,0,0,336,337,1,0,0,0,337,335,1,0,0,
0,337,338,1,0,0,0,338,339,1,0,0,0,339,343,5,46,0,0,340,342,3,89,
44,0,341,340,1,0,0,0,342,345,1,0,0,0,343,341,1,0,0,0,343,344,1,0,
0,0,344,353,1,0,0,0,345,343,1,0,0,0,346,348,5,46,0,0,347,349,3,89,
44,0,348,347,1,0,0,0,349,350,1,0,0,0,350,348,1,0,0,0,350,351,1,0,
0,0,351,353,1,0,0,0,352,335,1,0,0,0,352,346,1,0,0,0,353,94,1,0,0,
0,354,355,3,93,46,0,355,356,5,69,0,0,356,357,3,91,45,0,357,364,1,
0,0,0,358,359,3,93,46,0,359,360,5,69,0,0,360,361,5,45,0,0,361,362,
3,91,45,0,362,364,1,0,0,0,363,354,1,0,0,0,363,358,1,0,0,0,364,96,
1,0,0,0,365,369,5,37,0,0,366,368,9,0,0,0,367,366,1,0,0,0,368,371,
1,0,0,0,369,370,1,0,0,0,369,367,1,0,0,0,370,373,1,0,0,0,371,369,
1,0,0,0,372,374,5,13,0,0,373,372,1,0,0,0,373,374,1,0,0,0,374,375,
1,0,0,0,375,376,5,10,0,0,376,377,1,0,0,0,377,378,6,48,0,0,378,98,
1,0,0,0,379,383,7,21,0,0,380,382,7,22,0,0,381,380,1,0,0,0,382,385,
1,0,0,0,383,381,1,0,0,0,383,384,1,0,0,0,384,100,1,0,0,0,385,383,
1,0,0,0,386,388,7,23,0,0,387,386,1,0,0,0,388,389,1,0,0,0,389,387,
1,0,0,0,389,390,1,0,0,0,390,391,1,0,0,0,391,392,6,50,0,0,392,102,
1,0,0,0,21,0,183,231,239,250,258,269,281,302,319,324,332,337,343,
350,352,363,369,373,383,389,1,6,0,0
]
class AutolevLexer(Lexer):
atn = ATNDeserializer().deserialize(serializedATN())
decisionsToDFA = [ DFA(ds, i) for i, ds in enumerate(atn.decisionToState) ]
T__0 = 1
T__1 = 2
T__2 = 3
T__3 = 4
T__4 = 5
T__5 = 6
T__6 = 7
T__7 = 8
T__8 = 9
T__9 = 10
T__10 = 11
T__11 = 12
T__12 = 13
T__13 = 14
T__14 = 15
T__15 = 16
T__16 = 17
T__17 = 18
T__18 = 19
T__19 = 20
T__20 = 21
T__21 = 22
T__22 = 23
T__23 = 24
T__24 = 25
T__25 = 26
Mass = 27
Inertia = 28
Input = 29
Output = 30
Save = 31
UnitSystem = 32
Encode = 33
Newtonian = 34
Frames = 35
Bodies = 36
Particles = 37
Points = 38
Constants = 39
Specifieds = 40
Imaginary = 41
Variables = 42
MotionVariables = 43
INT = 44
FLOAT = 45
EXP = 46
LINE_COMMENT = 47
ID = 48
WS = 49
channelNames = [ u"DEFAULT_TOKEN_CHANNEL", u"HIDDEN" ]
modeNames = [ "DEFAULT_MODE" ]
literalNames = [ "<INVALID>",
"'['", "']'", "'='", "'+='", "'-='", "':='", "'*='", "'/='",
"'^='", "','", "'''", "'('", "')'", "'{'", "'}'", "':'", "'+'",
"'-'", "';'", "'.'", "'>'", "'0>'", "'1>>'", "'^'", "'*'", "'/'" ]
symbolicNames = [ "<INVALID>",
"Mass", "Inertia", "Input", "Output", "Save", "UnitSystem",
"Encode", "Newtonian", "Frames", "Bodies", "Particles", "Points",
"Constants", "Specifieds", "Imaginary", "Variables", "MotionVariables",
"INT", "FLOAT", "EXP", "LINE_COMMENT", "ID", "WS" ]
ruleNames = [ "T__0", "T__1", "T__2", "T__3", "T__4", "T__5", "T__6",
"T__7", "T__8", "T__9", "T__10", "T__11", "T__12", "T__13",
"T__14", "T__15", "T__16", "T__17", "T__18", "T__19",
"T__20", "T__21", "T__22", "T__23", "T__24", "T__25",
"Mass", "Inertia", "Input", "Output", "Save", "UnitSystem",
"Encode", "Newtonian", "Frames", "Bodies", "Particles",
"Points", "Constants", "Specifieds", "Imaginary", "Variables",
"MotionVariables", "DIFF", "DIGIT", "INT", "FLOAT", "EXP",
"LINE_COMMENT", "ID", "WS" ]
grammarFileName = "Autolev.g4"
def __init__(self, input=None, output:TextIO = sys.stdout):
super().__init__(input, output)
self.checkVersion("4.10")
self._interp = LexerATNSimulator(self, self.atn, self.decisionsToDFA, PredictionContextCache())
self._actions = None
self._predicates = None
|
1036f75e41fd63b08bcf118cfad63e9c6ab13067c11d592a29d5423f10018111 | # *** GENERATED BY `setup.py antlr`, DO NOT EDIT BY HAND ***
#
# Generated with antlr4
# antlr4 is licensed under the BSD-3-Clause License
# https://github.com/antlr/antlr4/blob/master/LICENSE.txt
from antlr4 import *
if __name__ is not None and "." in __name__:
from .autolevparser import AutolevParser
else:
from autolevparser import AutolevParser
# This class defines a complete listener for a parse tree produced by AutolevParser.
class AutolevListener(ParseTreeListener):
# Enter a parse tree produced by AutolevParser#prog.
def enterProg(self, ctx:AutolevParser.ProgContext):
pass
# Exit a parse tree produced by AutolevParser#prog.
def exitProg(self, ctx:AutolevParser.ProgContext):
pass
# Enter a parse tree produced by AutolevParser#stat.
def enterStat(self, ctx:AutolevParser.StatContext):
pass
# Exit a parse tree produced by AutolevParser#stat.
def exitStat(self, ctx:AutolevParser.StatContext):
pass
# Enter a parse tree produced by AutolevParser#vecAssign.
def enterVecAssign(self, ctx:AutolevParser.VecAssignContext):
pass
# Exit a parse tree produced by AutolevParser#vecAssign.
def exitVecAssign(self, ctx:AutolevParser.VecAssignContext):
pass
# Enter a parse tree produced by AutolevParser#indexAssign.
def enterIndexAssign(self, ctx:AutolevParser.IndexAssignContext):
pass
# Exit a parse tree produced by AutolevParser#indexAssign.
def exitIndexAssign(self, ctx:AutolevParser.IndexAssignContext):
pass
# Enter a parse tree produced by AutolevParser#regularAssign.
def enterRegularAssign(self, ctx:AutolevParser.RegularAssignContext):
pass
# Exit a parse tree produced by AutolevParser#regularAssign.
def exitRegularAssign(self, ctx:AutolevParser.RegularAssignContext):
pass
# Enter a parse tree produced by AutolevParser#equals.
def enterEquals(self, ctx:AutolevParser.EqualsContext):
pass
# Exit a parse tree produced by AutolevParser#equals.
def exitEquals(self, ctx:AutolevParser.EqualsContext):
pass
# Enter a parse tree produced by AutolevParser#index.
def enterIndex(self, ctx:AutolevParser.IndexContext):
pass
# Exit a parse tree produced by AutolevParser#index.
def exitIndex(self, ctx:AutolevParser.IndexContext):
pass
# Enter a parse tree produced by AutolevParser#diff.
def enterDiff(self, ctx:AutolevParser.DiffContext):
pass
# Exit a parse tree produced by AutolevParser#diff.
def exitDiff(self, ctx:AutolevParser.DiffContext):
pass
# Enter a parse tree produced by AutolevParser#functionCall.
def enterFunctionCall(self, ctx:AutolevParser.FunctionCallContext):
pass
# Exit a parse tree produced by AutolevParser#functionCall.
def exitFunctionCall(self, ctx:AutolevParser.FunctionCallContext):
pass
# Enter a parse tree produced by AutolevParser#varDecl.
def enterVarDecl(self, ctx:AutolevParser.VarDeclContext):
pass
# Exit a parse tree produced by AutolevParser#varDecl.
def exitVarDecl(self, ctx:AutolevParser.VarDeclContext):
pass
# Enter a parse tree produced by AutolevParser#varType.
def enterVarType(self, ctx:AutolevParser.VarTypeContext):
pass
# Exit a parse tree produced by AutolevParser#varType.
def exitVarType(self, ctx:AutolevParser.VarTypeContext):
pass
# Enter a parse tree produced by AutolevParser#varDecl2.
def enterVarDecl2(self, ctx:AutolevParser.VarDecl2Context):
pass
# Exit a parse tree produced by AutolevParser#varDecl2.
def exitVarDecl2(self, ctx:AutolevParser.VarDecl2Context):
pass
# Enter a parse tree produced by AutolevParser#ranges.
def enterRanges(self, ctx:AutolevParser.RangesContext):
pass
# Exit a parse tree produced by AutolevParser#ranges.
def exitRanges(self, ctx:AutolevParser.RangesContext):
pass
# Enter a parse tree produced by AutolevParser#massDecl.
def enterMassDecl(self, ctx:AutolevParser.MassDeclContext):
pass
# Exit a parse tree produced by AutolevParser#massDecl.
def exitMassDecl(self, ctx:AutolevParser.MassDeclContext):
pass
# Enter a parse tree produced by AutolevParser#massDecl2.
def enterMassDecl2(self, ctx:AutolevParser.MassDecl2Context):
pass
# Exit a parse tree produced by AutolevParser#massDecl2.
def exitMassDecl2(self, ctx:AutolevParser.MassDecl2Context):
pass
# Enter a parse tree produced by AutolevParser#inertiaDecl.
def enterInertiaDecl(self, ctx:AutolevParser.InertiaDeclContext):
pass
# Exit a parse tree produced by AutolevParser#inertiaDecl.
def exitInertiaDecl(self, ctx:AutolevParser.InertiaDeclContext):
pass
# Enter a parse tree produced by AutolevParser#matrix.
def enterMatrix(self, ctx:AutolevParser.MatrixContext):
pass
# Exit a parse tree produced by AutolevParser#matrix.
def exitMatrix(self, ctx:AutolevParser.MatrixContext):
pass
# Enter a parse tree produced by AutolevParser#matrixInOutput.
def enterMatrixInOutput(self, ctx:AutolevParser.MatrixInOutputContext):
pass
# Exit a parse tree produced by AutolevParser#matrixInOutput.
def exitMatrixInOutput(self, ctx:AutolevParser.MatrixInOutputContext):
pass
# Enter a parse tree produced by AutolevParser#codeCommands.
def enterCodeCommands(self, ctx:AutolevParser.CodeCommandsContext):
pass
# Exit a parse tree produced by AutolevParser#codeCommands.
def exitCodeCommands(self, ctx:AutolevParser.CodeCommandsContext):
pass
# Enter a parse tree produced by AutolevParser#settings.
def enterSettings(self, ctx:AutolevParser.SettingsContext):
pass
# Exit a parse tree produced by AutolevParser#settings.
def exitSettings(self, ctx:AutolevParser.SettingsContext):
pass
# Enter a parse tree produced by AutolevParser#units.
def enterUnits(self, ctx:AutolevParser.UnitsContext):
pass
# Exit a parse tree produced by AutolevParser#units.
def exitUnits(self, ctx:AutolevParser.UnitsContext):
pass
# Enter a parse tree produced by AutolevParser#inputs.
def enterInputs(self, ctx:AutolevParser.InputsContext):
pass
# Exit a parse tree produced by AutolevParser#inputs.
def exitInputs(self, ctx:AutolevParser.InputsContext):
pass
# Enter a parse tree produced by AutolevParser#id_diff.
def enterId_diff(self, ctx:AutolevParser.Id_diffContext):
pass
# Exit a parse tree produced by AutolevParser#id_diff.
def exitId_diff(self, ctx:AutolevParser.Id_diffContext):
pass
# Enter a parse tree produced by AutolevParser#inputs2.
def enterInputs2(self, ctx:AutolevParser.Inputs2Context):
pass
# Exit a parse tree produced by AutolevParser#inputs2.
def exitInputs2(self, ctx:AutolevParser.Inputs2Context):
pass
# Enter a parse tree produced by AutolevParser#outputs.
def enterOutputs(self, ctx:AutolevParser.OutputsContext):
pass
# Exit a parse tree produced by AutolevParser#outputs.
def exitOutputs(self, ctx:AutolevParser.OutputsContext):
pass
# Enter a parse tree produced by AutolevParser#outputs2.
def enterOutputs2(self, ctx:AutolevParser.Outputs2Context):
pass
# Exit a parse tree produced by AutolevParser#outputs2.
def exitOutputs2(self, ctx:AutolevParser.Outputs2Context):
pass
# Enter a parse tree produced by AutolevParser#codegen.
def enterCodegen(self, ctx:AutolevParser.CodegenContext):
pass
# Exit a parse tree produced by AutolevParser#codegen.
def exitCodegen(self, ctx:AutolevParser.CodegenContext):
pass
# Enter a parse tree produced by AutolevParser#commands.
def enterCommands(self, ctx:AutolevParser.CommandsContext):
pass
# Exit a parse tree produced by AutolevParser#commands.
def exitCommands(self, ctx:AutolevParser.CommandsContext):
pass
# Enter a parse tree produced by AutolevParser#vec.
def enterVec(self, ctx:AutolevParser.VecContext):
pass
# Exit a parse tree produced by AutolevParser#vec.
def exitVec(self, ctx:AutolevParser.VecContext):
pass
# Enter a parse tree produced by AutolevParser#parens.
def enterParens(self, ctx:AutolevParser.ParensContext):
pass
# Exit a parse tree produced by AutolevParser#parens.
def exitParens(self, ctx:AutolevParser.ParensContext):
pass
# Enter a parse tree produced by AutolevParser#VectorOrDyadic.
def enterVectorOrDyadic(self, ctx:AutolevParser.VectorOrDyadicContext):
pass
# Exit a parse tree produced by AutolevParser#VectorOrDyadic.
def exitVectorOrDyadic(self, ctx:AutolevParser.VectorOrDyadicContext):
pass
# Enter a parse tree produced by AutolevParser#Exponent.
def enterExponent(self, ctx:AutolevParser.ExponentContext):
pass
# Exit a parse tree produced by AutolevParser#Exponent.
def exitExponent(self, ctx:AutolevParser.ExponentContext):
pass
# Enter a parse tree produced by AutolevParser#MulDiv.
def enterMulDiv(self, ctx:AutolevParser.MulDivContext):
pass
# Exit a parse tree produced by AutolevParser#MulDiv.
def exitMulDiv(self, ctx:AutolevParser.MulDivContext):
pass
# Enter a parse tree produced by AutolevParser#AddSub.
def enterAddSub(self, ctx:AutolevParser.AddSubContext):
pass
# Exit a parse tree produced by AutolevParser#AddSub.
def exitAddSub(self, ctx:AutolevParser.AddSubContext):
pass
# Enter a parse tree produced by AutolevParser#float.
def enterFloat(self, ctx:AutolevParser.FloatContext):
pass
# Exit a parse tree produced by AutolevParser#float.
def exitFloat(self, ctx:AutolevParser.FloatContext):
pass
# Enter a parse tree produced by AutolevParser#int.
def enterInt(self, ctx:AutolevParser.IntContext):
pass
# Exit a parse tree produced by AutolevParser#int.
def exitInt(self, ctx:AutolevParser.IntContext):
pass
# Enter a parse tree produced by AutolevParser#idEqualsExpr.
def enterIdEqualsExpr(self, ctx:AutolevParser.IdEqualsExprContext):
pass
# Exit a parse tree produced by AutolevParser#idEqualsExpr.
def exitIdEqualsExpr(self, ctx:AutolevParser.IdEqualsExprContext):
pass
# Enter a parse tree produced by AutolevParser#negativeOne.
def enterNegativeOne(self, ctx:AutolevParser.NegativeOneContext):
pass
# Exit a parse tree produced by AutolevParser#negativeOne.
def exitNegativeOne(self, ctx:AutolevParser.NegativeOneContext):
pass
# Enter a parse tree produced by AutolevParser#function.
def enterFunction(self, ctx:AutolevParser.FunctionContext):
pass
# Exit a parse tree produced by AutolevParser#function.
def exitFunction(self, ctx:AutolevParser.FunctionContext):
pass
# Enter a parse tree produced by AutolevParser#rangess.
def enterRangess(self, ctx:AutolevParser.RangessContext):
pass
# Exit a parse tree produced by AutolevParser#rangess.
def exitRangess(self, ctx:AutolevParser.RangessContext):
pass
# Enter a parse tree produced by AutolevParser#colon.
def enterColon(self, ctx:AutolevParser.ColonContext):
pass
# Exit a parse tree produced by AutolevParser#colon.
def exitColon(self, ctx:AutolevParser.ColonContext):
pass
# Enter a parse tree produced by AutolevParser#id.
def enterId(self, ctx:AutolevParser.IdContext):
pass
# Exit a parse tree produced by AutolevParser#id.
def exitId(self, ctx:AutolevParser.IdContext):
pass
# Enter a parse tree produced by AutolevParser#exp.
def enterExp(self, ctx:AutolevParser.ExpContext):
pass
# Exit a parse tree produced by AutolevParser#exp.
def exitExp(self, ctx:AutolevParser.ExpContext):
pass
# Enter a parse tree produced by AutolevParser#matrices.
def enterMatrices(self, ctx:AutolevParser.MatricesContext):
pass
# Exit a parse tree produced by AutolevParser#matrices.
def exitMatrices(self, ctx:AutolevParser.MatricesContext):
pass
# Enter a parse tree produced by AutolevParser#Indexing.
def enterIndexing(self, ctx:AutolevParser.IndexingContext):
pass
# Exit a parse tree produced by AutolevParser#Indexing.
def exitIndexing(self, ctx:AutolevParser.IndexingContext):
pass
del AutolevParser
|
a64ceec49b163d0dac1741eada7ab6b2e476f3e58a5b046bea9ac6d0c37b5c60 | # *** GENERATED BY `setup.py antlr`, DO NOT EDIT BY HAND ***
#
# Generated with antlr4
# antlr4 is licensed under the BSD-3-Clause License
# https://github.com/antlr/antlr4/blob/master/LICENSE.txt
from antlr4 import *
from io import StringIO
import sys
if sys.version_info[1] > 5:
from typing import TextIO
else:
from typing.io import TextIO
def serializedATN():
return [
4,1,49,431,2,0,7,0,2,1,7,1,2,2,7,2,2,3,7,3,2,4,7,4,2,5,7,5,2,6,7,
6,2,7,7,7,2,8,7,8,2,9,7,9,2,10,7,10,2,11,7,11,2,12,7,12,2,13,7,13,
2,14,7,14,2,15,7,15,2,16,7,16,2,17,7,17,2,18,7,18,2,19,7,19,2,20,
7,20,2,21,7,21,2,22,7,22,2,23,7,23,2,24,7,24,2,25,7,25,2,26,7,26,
2,27,7,27,1,0,4,0,58,8,0,11,0,12,0,59,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,3,1,69,8,1,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,
3,2,84,8,2,1,2,1,2,1,2,3,2,89,8,2,1,3,1,3,1,4,1,4,1,4,5,4,96,8,4,
10,4,12,4,99,9,4,1,5,4,5,102,8,5,11,5,12,5,103,1,6,1,6,1,6,1,6,1,
6,5,6,111,8,6,10,6,12,6,114,9,6,3,6,116,8,6,1,6,1,6,1,6,1,6,1,6,
1,6,5,6,124,8,6,10,6,12,6,127,9,6,3,6,129,8,6,1,6,3,6,132,8,6,1,
7,1,7,1,7,1,7,5,7,138,8,7,10,7,12,7,141,9,7,1,8,1,8,1,8,1,8,1,8,
1,8,1,8,1,8,1,8,1,8,5,8,153,8,8,10,8,12,8,156,9,8,1,8,1,8,5,8,160,
8,8,10,8,12,8,163,9,8,3,8,165,8,8,1,9,1,9,1,9,1,9,1,9,1,9,3,9,173,
8,9,1,9,1,9,1,9,1,9,1,9,1,9,1,9,1,9,5,9,183,8,9,10,9,12,9,186,9,
9,1,9,3,9,189,8,9,1,9,1,9,1,9,3,9,194,8,9,1,9,3,9,197,8,9,1,9,5,
9,200,8,9,10,9,12,9,203,9,9,1,9,1,9,3,9,207,8,9,1,10,1,10,1,10,1,
10,1,10,1,10,1,10,1,10,5,10,217,8,10,10,10,12,10,220,9,10,1,10,1,
10,1,11,1,11,1,11,1,11,5,11,228,8,11,10,11,12,11,231,9,11,1,12,1,
12,1,12,1,12,1,13,1,13,1,13,1,13,1,13,3,13,242,8,13,1,13,1,13,4,
13,246,8,13,11,13,12,13,247,1,14,1,14,1,14,1,14,5,14,254,8,14,10,
14,12,14,257,9,14,1,14,1,14,1,15,1,15,1,15,1,15,3,15,265,8,15,1,
15,1,15,3,15,269,8,15,1,16,1,16,1,16,1,16,1,16,3,16,276,8,16,1,17,
1,17,3,17,280,8,17,1,18,1,18,1,18,1,18,5,18,286,8,18,10,18,12,18,
289,9,18,1,19,1,19,1,19,1,19,5,19,295,8,19,10,19,12,19,298,9,19,
1,20,1,20,3,20,302,8,20,1,21,1,21,1,21,1,21,3,21,308,8,21,1,22,1,
22,1,22,1,22,5,22,314,8,22,10,22,12,22,317,9,22,1,23,1,23,3,23,321,
8,23,1,24,1,24,1,24,1,24,1,24,1,24,5,24,329,8,24,10,24,12,24,332,
9,24,1,24,1,24,3,24,336,8,24,1,24,1,24,1,24,1,24,1,25,1,25,1,25,
1,25,1,25,1,25,1,25,1,25,5,25,350,8,25,10,25,12,25,353,9,25,3,25,
355,8,25,1,26,1,26,4,26,359,8,26,11,26,12,26,360,1,26,1,26,3,26,
365,8,26,1,27,1,27,1,27,1,27,1,27,1,27,1,27,1,27,5,27,375,8,27,10,
27,12,27,378,9,27,1,27,1,27,1,27,1,27,1,27,1,27,5,27,386,8,27,10,
27,12,27,389,9,27,1,27,1,27,1,27,1,27,1,27,1,27,1,27,1,27,1,27,3,
27,400,8,27,1,27,1,27,5,27,404,8,27,10,27,12,27,407,9,27,3,27,409,
8,27,1,27,1,27,1,27,1,27,1,27,1,27,1,27,1,27,1,27,1,27,1,27,1,27,
1,27,1,27,1,27,5,27,426,8,27,10,27,12,27,429,9,27,1,27,0,1,54,28,
0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,
46,48,50,52,54,0,7,1,0,3,9,1,0,27,28,1,0,17,18,2,0,10,10,19,19,1,
0,44,45,2,0,44,46,48,48,1,0,25,26,483,0,57,1,0,0,0,2,68,1,0,0,0,
4,88,1,0,0,0,6,90,1,0,0,0,8,92,1,0,0,0,10,101,1,0,0,0,12,131,1,0,
0,0,14,133,1,0,0,0,16,164,1,0,0,0,18,166,1,0,0,0,20,208,1,0,0,0,
22,223,1,0,0,0,24,232,1,0,0,0,26,236,1,0,0,0,28,249,1,0,0,0,30,268,
1,0,0,0,32,275,1,0,0,0,34,277,1,0,0,0,36,281,1,0,0,0,38,290,1,0,
0,0,40,299,1,0,0,0,42,303,1,0,0,0,44,309,1,0,0,0,46,318,1,0,0,0,
48,322,1,0,0,0,50,354,1,0,0,0,52,364,1,0,0,0,54,408,1,0,0,0,56,58,
3,2,1,0,57,56,1,0,0,0,58,59,1,0,0,0,59,57,1,0,0,0,59,60,1,0,0,0,
60,1,1,0,0,0,61,69,3,14,7,0,62,69,3,12,6,0,63,69,3,32,16,0,64,69,
3,22,11,0,65,69,3,26,13,0,66,69,3,4,2,0,67,69,3,34,17,0,68,61,1,
0,0,0,68,62,1,0,0,0,68,63,1,0,0,0,68,64,1,0,0,0,68,65,1,0,0,0,68,
66,1,0,0,0,68,67,1,0,0,0,69,3,1,0,0,0,70,71,3,52,26,0,71,72,3,6,
3,0,72,73,3,54,27,0,73,89,1,0,0,0,74,75,5,48,0,0,75,76,5,1,0,0,76,
77,3,8,4,0,77,78,5,2,0,0,78,79,3,6,3,0,79,80,3,54,27,0,80,89,1,0,
0,0,81,83,5,48,0,0,82,84,3,10,5,0,83,82,1,0,0,0,83,84,1,0,0,0,84,
85,1,0,0,0,85,86,3,6,3,0,86,87,3,54,27,0,87,89,1,0,0,0,88,70,1,0,
0,0,88,74,1,0,0,0,88,81,1,0,0,0,89,5,1,0,0,0,90,91,7,0,0,0,91,7,
1,0,0,0,92,97,3,54,27,0,93,94,5,10,0,0,94,96,3,54,27,0,95,93,1,0,
0,0,96,99,1,0,0,0,97,95,1,0,0,0,97,98,1,0,0,0,98,9,1,0,0,0,99,97,
1,0,0,0,100,102,5,11,0,0,101,100,1,0,0,0,102,103,1,0,0,0,103,101,
1,0,0,0,103,104,1,0,0,0,104,11,1,0,0,0,105,106,5,48,0,0,106,115,
5,12,0,0,107,112,3,54,27,0,108,109,5,10,0,0,109,111,3,54,27,0,110,
108,1,0,0,0,111,114,1,0,0,0,112,110,1,0,0,0,112,113,1,0,0,0,113,
116,1,0,0,0,114,112,1,0,0,0,115,107,1,0,0,0,115,116,1,0,0,0,116,
117,1,0,0,0,117,132,5,13,0,0,118,119,7,1,0,0,119,128,5,12,0,0,120,
125,5,48,0,0,121,122,5,10,0,0,122,124,5,48,0,0,123,121,1,0,0,0,124,
127,1,0,0,0,125,123,1,0,0,0,125,126,1,0,0,0,126,129,1,0,0,0,127,
125,1,0,0,0,128,120,1,0,0,0,128,129,1,0,0,0,129,130,1,0,0,0,130,
132,5,13,0,0,131,105,1,0,0,0,131,118,1,0,0,0,132,13,1,0,0,0,133,
134,3,16,8,0,134,139,3,18,9,0,135,136,5,10,0,0,136,138,3,18,9,0,
137,135,1,0,0,0,138,141,1,0,0,0,139,137,1,0,0,0,139,140,1,0,0,0,
140,15,1,0,0,0,141,139,1,0,0,0,142,165,5,34,0,0,143,165,5,35,0,0,
144,165,5,36,0,0,145,165,5,37,0,0,146,165,5,38,0,0,147,165,5,39,
0,0,148,165,5,40,0,0,149,165,5,41,0,0,150,154,5,42,0,0,151,153,5,
11,0,0,152,151,1,0,0,0,153,156,1,0,0,0,154,152,1,0,0,0,154,155,1,
0,0,0,155,165,1,0,0,0,156,154,1,0,0,0,157,161,5,43,0,0,158,160,5,
11,0,0,159,158,1,0,0,0,160,163,1,0,0,0,161,159,1,0,0,0,161,162,1,
0,0,0,162,165,1,0,0,0,163,161,1,0,0,0,164,142,1,0,0,0,164,143,1,
0,0,0,164,144,1,0,0,0,164,145,1,0,0,0,164,146,1,0,0,0,164,147,1,
0,0,0,164,148,1,0,0,0,164,149,1,0,0,0,164,150,1,0,0,0,164,157,1,
0,0,0,165,17,1,0,0,0,166,172,5,48,0,0,167,168,5,14,0,0,168,169,5,
44,0,0,169,170,5,10,0,0,170,171,5,44,0,0,171,173,5,15,0,0,172,167,
1,0,0,0,172,173,1,0,0,0,173,188,1,0,0,0,174,175,5,14,0,0,175,176,
5,44,0,0,176,177,5,16,0,0,177,184,5,44,0,0,178,179,5,10,0,0,179,
180,5,44,0,0,180,181,5,16,0,0,181,183,5,44,0,0,182,178,1,0,0,0,183,
186,1,0,0,0,184,182,1,0,0,0,184,185,1,0,0,0,185,187,1,0,0,0,186,
184,1,0,0,0,187,189,5,15,0,0,188,174,1,0,0,0,188,189,1,0,0,0,189,
193,1,0,0,0,190,191,5,14,0,0,191,192,5,44,0,0,192,194,5,15,0,0,193,
190,1,0,0,0,193,194,1,0,0,0,194,196,1,0,0,0,195,197,7,2,0,0,196,
195,1,0,0,0,196,197,1,0,0,0,197,201,1,0,0,0,198,200,5,11,0,0,199,
198,1,0,0,0,200,203,1,0,0,0,201,199,1,0,0,0,201,202,1,0,0,0,202,
206,1,0,0,0,203,201,1,0,0,0,204,205,5,3,0,0,205,207,3,54,27,0,206,
204,1,0,0,0,206,207,1,0,0,0,207,19,1,0,0,0,208,209,5,14,0,0,209,
210,5,44,0,0,210,211,5,16,0,0,211,218,5,44,0,0,212,213,5,10,0,0,
213,214,5,44,0,0,214,215,5,16,0,0,215,217,5,44,0,0,216,212,1,0,0,
0,217,220,1,0,0,0,218,216,1,0,0,0,218,219,1,0,0,0,219,221,1,0,0,
0,220,218,1,0,0,0,221,222,5,15,0,0,222,21,1,0,0,0,223,224,5,27,0,
0,224,229,3,24,12,0,225,226,5,10,0,0,226,228,3,24,12,0,227,225,1,
0,0,0,228,231,1,0,0,0,229,227,1,0,0,0,229,230,1,0,0,0,230,23,1,0,
0,0,231,229,1,0,0,0,232,233,5,48,0,0,233,234,5,3,0,0,234,235,3,54,
27,0,235,25,1,0,0,0,236,237,5,28,0,0,237,241,5,48,0,0,238,239,5,
12,0,0,239,240,5,48,0,0,240,242,5,13,0,0,241,238,1,0,0,0,241,242,
1,0,0,0,242,245,1,0,0,0,243,244,5,10,0,0,244,246,3,54,27,0,245,243,
1,0,0,0,246,247,1,0,0,0,247,245,1,0,0,0,247,248,1,0,0,0,248,27,1,
0,0,0,249,250,5,1,0,0,250,255,3,54,27,0,251,252,7,3,0,0,252,254,
3,54,27,0,253,251,1,0,0,0,254,257,1,0,0,0,255,253,1,0,0,0,255,256,
1,0,0,0,256,258,1,0,0,0,257,255,1,0,0,0,258,259,5,2,0,0,259,29,1,
0,0,0,260,261,5,48,0,0,261,262,5,48,0,0,262,264,5,3,0,0,263,265,
7,4,0,0,264,263,1,0,0,0,264,265,1,0,0,0,265,269,1,0,0,0,266,269,
5,45,0,0,267,269,5,44,0,0,268,260,1,0,0,0,268,266,1,0,0,0,268,267,
1,0,0,0,269,31,1,0,0,0,270,276,3,36,18,0,271,276,3,38,19,0,272,276,
3,44,22,0,273,276,3,48,24,0,274,276,3,50,25,0,275,270,1,0,0,0,275,
271,1,0,0,0,275,272,1,0,0,0,275,273,1,0,0,0,275,274,1,0,0,0,276,
33,1,0,0,0,277,279,5,48,0,0,278,280,7,5,0,0,279,278,1,0,0,0,279,
280,1,0,0,0,280,35,1,0,0,0,281,282,5,32,0,0,282,287,5,48,0,0,283,
284,5,10,0,0,284,286,5,48,0,0,285,283,1,0,0,0,286,289,1,0,0,0,287,
285,1,0,0,0,287,288,1,0,0,0,288,37,1,0,0,0,289,287,1,0,0,0,290,291,
5,29,0,0,291,296,3,42,21,0,292,293,5,10,0,0,293,295,3,42,21,0,294,
292,1,0,0,0,295,298,1,0,0,0,296,294,1,0,0,0,296,297,1,0,0,0,297,
39,1,0,0,0,298,296,1,0,0,0,299,301,5,48,0,0,300,302,3,10,5,0,301,
300,1,0,0,0,301,302,1,0,0,0,302,41,1,0,0,0,303,304,3,40,20,0,304,
305,5,3,0,0,305,307,3,54,27,0,306,308,3,54,27,0,307,306,1,0,0,0,
307,308,1,0,0,0,308,43,1,0,0,0,309,310,5,30,0,0,310,315,3,46,23,
0,311,312,5,10,0,0,312,314,3,46,23,0,313,311,1,0,0,0,314,317,1,0,
0,0,315,313,1,0,0,0,315,316,1,0,0,0,316,45,1,0,0,0,317,315,1,0,0,
0,318,320,3,54,27,0,319,321,3,54,27,0,320,319,1,0,0,0,320,321,1,
0,0,0,321,47,1,0,0,0,322,323,5,48,0,0,323,335,3,12,6,0,324,325,5,
1,0,0,325,330,3,30,15,0,326,327,5,10,0,0,327,329,3,30,15,0,328,326,
1,0,0,0,329,332,1,0,0,0,330,328,1,0,0,0,330,331,1,0,0,0,331,333,
1,0,0,0,332,330,1,0,0,0,333,334,5,2,0,0,334,336,1,0,0,0,335,324,
1,0,0,0,335,336,1,0,0,0,336,337,1,0,0,0,337,338,5,48,0,0,338,339,
5,20,0,0,339,340,5,48,0,0,340,49,1,0,0,0,341,342,5,31,0,0,342,343,
5,48,0,0,343,344,5,20,0,0,344,355,5,48,0,0,345,346,5,33,0,0,346,
351,5,48,0,0,347,348,5,10,0,0,348,350,5,48,0,0,349,347,1,0,0,0,350,
353,1,0,0,0,351,349,1,0,0,0,351,352,1,0,0,0,352,355,1,0,0,0,353,
351,1,0,0,0,354,341,1,0,0,0,354,345,1,0,0,0,355,51,1,0,0,0,356,358,
5,48,0,0,357,359,5,21,0,0,358,357,1,0,0,0,359,360,1,0,0,0,360,358,
1,0,0,0,360,361,1,0,0,0,361,365,1,0,0,0,362,365,5,22,0,0,363,365,
5,23,0,0,364,356,1,0,0,0,364,362,1,0,0,0,364,363,1,0,0,0,365,53,
1,0,0,0,366,367,6,27,-1,0,367,409,5,46,0,0,368,369,5,18,0,0,369,
409,3,54,27,12,370,409,5,45,0,0,371,409,5,44,0,0,372,376,5,48,0,
0,373,375,5,11,0,0,374,373,1,0,0,0,375,378,1,0,0,0,376,374,1,0,0,
0,376,377,1,0,0,0,377,409,1,0,0,0,378,376,1,0,0,0,379,409,3,52,26,
0,380,381,5,48,0,0,381,382,5,1,0,0,382,387,3,54,27,0,383,384,5,10,
0,0,384,386,3,54,27,0,385,383,1,0,0,0,386,389,1,0,0,0,387,385,1,
0,0,0,387,388,1,0,0,0,388,390,1,0,0,0,389,387,1,0,0,0,390,391,5,
2,0,0,391,409,1,0,0,0,392,409,3,12,6,0,393,409,3,28,14,0,394,395,
5,12,0,0,395,396,3,54,27,0,396,397,5,13,0,0,397,409,1,0,0,0,398,
400,5,48,0,0,399,398,1,0,0,0,399,400,1,0,0,0,400,401,1,0,0,0,401,
405,3,20,10,0,402,404,5,11,0,0,403,402,1,0,0,0,404,407,1,0,0,0,405,
403,1,0,0,0,405,406,1,0,0,0,406,409,1,0,0,0,407,405,1,0,0,0,408,
366,1,0,0,0,408,368,1,0,0,0,408,370,1,0,0,0,408,371,1,0,0,0,408,
372,1,0,0,0,408,379,1,0,0,0,408,380,1,0,0,0,408,392,1,0,0,0,408,
393,1,0,0,0,408,394,1,0,0,0,408,399,1,0,0,0,409,427,1,0,0,0,410,
411,10,16,0,0,411,412,5,24,0,0,412,426,3,54,27,17,413,414,10,15,
0,0,414,415,7,6,0,0,415,426,3,54,27,16,416,417,10,14,0,0,417,418,
7,2,0,0,418,426,3,54,27,15,419,420,10,3,0,0,420,421,5,3,0,0,421,
426,3,54,27,4,422,423,10,2,0,0,423,424,5,16,0,0,424,426,3,54,27,
3,425,410,1,0,0,0,425,413,1,0,0,0,425,416,1,0,0,0,425,419,1,0,0,
0,425,422,1,0,0,0,426,429,1,0,0,0,427,425,1,0,0,0,427,428,1,0,0,
0,428,55,1,0,0,0,429,427,1,0,0,0,50,59,68,83,88,97,103,112,115,125,
128,131,139,154,161,164,172,184,188,193,196,201,206,218,229,241,
247,255,264,268,275,279,287,296,301,307,315,320,330,335,351,354,
360,364,376,387,399,405,408,425,427
]
class AutolevParser ( Parser ):
grammarFileName = "Autolev.g4"
atn = ATNDeserializer().deserialize(serializedATN())
decisionsToDFA = [ DFA(ds, i) for i, ds in enumerate(atn.decisionToState) ]
sharedContextCache = PredictionContextCache()
literalNames = [ "<INVALID>", "'['", "']'", "'='", "'+='", "'-='", "':='",
"'*='", "'/='", "'^='", "','", "'''", "'('", "')'",
"'{'", "'}'", "':'", "'+'", "'-'", "';'", "'.'", "'>'",
"'0>'", "'1>>'", "'^'", "'*'", "'/'" ]
symbolicNames = [ "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>",
"<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>",
"<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>",
"<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>",
"<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>",
"<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>",
"<INVALID>", "<INVALID>", "<INVALID>", "Mass", "Inertia",
"Input", "Output", "Save", "UnitSystem", "Encode",
"Newtonian", "Frames", "Bodies", "Particles", "Points",
"Constants", "Specifieds", "Imaginary", "Variables",
"MotionVariables", "INT", "FLOAT", "EXP", "LINE_COMMENT",
"ID", "WS" ]
RULE_prog = 0
RULE_stat = 1
RULE_assignment = 2
RULE_equals = 3
RULE_index = 4
RULE_diff = 5
RULE_functionCall = 6
RULE_varDecl = 7
RULE_varType = 8
RULE_varDecl2 = 9
RULE_ranges = 10
RULE_massDecl = 11
RULE_massDecl2 = 12
RULE_inertiaDecl = 13
RULE_matrix = 14
RULE_matrixInOutput = 15
RULE_codeCommands = 16
RULE_settings = 17
RULE_units = 18
RULE_inputs = 19
RULE_id_diff = 20
RULE_inputs2 = 21
RULE_outputs = 22
RULE_outputs2 = 23
RULE_codegen = 24
RULE_commands = 25
RULE_vec = 26
RULE_expr = 27
ruleNames = [ "prog", "stat", "assignment", "equals", "index", "diff",
"functionCall", "varDecl", "varType", "varDecl2", "ranges",
"massDecl", "massDecl2", "inertiaDecl", "matrix", "matrixInOutput",
"codeCommands", "settings", "units", "inputs", "id_diff",
"inputs2", "outputs", "outputs2", "codegen", "commands",
"vec", "expr" ]
EOF = Token.EOF
T__0=1
T__1=2
T__2=3
T__3=4
T__4=5
T__5=6
T__6=7
T__7=8
T__8=9
T__9=10
T__10=11
T__11=12
T__12=13
T__13=14
T__14=15
T__15=16
T__16=17
T__17=18
T__18=19
T__19=20
T__20=21
T__21=22
T__22=23
T__23=24
T__24=25
T__25=26
Mass=27
Inertia=28
Input=29
Output=30
Save=31
UnitSystem=32
Encode=33
Newtonian=34
Frames=35
Bodies=36
Particles=37
Points=38
Constants=39
Specifieds=40
Imaginary=41
Variables=42
MotionVariables=43
INT=44
FLOAT=45
EXP=46
LINE_COMMENT=47
ID=48
WS=49
def __init__(self, input:TokenStream, output:TextIO = sys.stdout):
super().__init__(input, output)
self.checkVersion("4.10")
self._interp = ParserATNSimulator(self, self.atn, self.decisionsToDFA, self.sharedContextCache)
self._predicates = None
class ProgContext(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def stat(self, i:int=None):
if i is None:
return self.getTypedRuleContexts(AutolevParser.StatContext)
else:
return self.getTypedRuleContext(AutolevParser.StatContext,i)
def getRuleIndex(self):
return AutolevParser.RULE_prog
def enterRule(self, listener:ParseTreeListener):
if hasattr( listener, "enterProg" ):
listener.enterProg(self)
def exitRule(self, listener:ParseTreeListener):
if hasattr( listener, "exitProg" ):
listener.exitProg(self)
def prog(self):
localctx = AutolevParser.ProgContext(self, self._ctx, self.state)
self.enterRule(localctx, 0, self.RULE_prog)
self._la = 0 # Token type
try:
self.enterOuterAlt(localctx, 1)
self.state = 57
self._errHandler.sync(self)
_la = self._input.LA(1)
while True:
self.state = 56
self.stat()
self.state = 59
self._errHandler.sync(self)
_la = self._input.LA(1)
if not ((((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << AutolevParser.T__21) | (1 << AutolevParser.T__22) | (1 << AutolevParser.Mass) | (1 << AutolevParser.Inertia) | (1 << AutolevParser.Input) | (1 << AutolevParser.Output) | (1 << AutolevParser.Save) | (1 << AutolevParser.UnitSystem) | (1 << AutolevParser.Encode) | (1 << AutolevParser.Newtonian) | (1 << AutolevParser.Frames) | (1 << AutolevParser.Bodies) | (1 << AutolevParser.Particles) | (1 << AutolevParser.Points) | (1 << AutolevParser.Constants) | (1 << AutolevParser.Specifieds) | (1 << AutolevParser.Imaginary) | (1 << AutolevParser.Variables) | (1 << AutolevParser.MotionVariables) | (1 << AutolevParser.ID))) != 0)):
break
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class StatContext(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def varDecl(self):
return self.getTypedRuleContext(AutolevParser.VarDeclContext,0)
def functionCall(self):
return self.getTypedRuleContext(AutolevParser.FunctionCallContext,0)
def codeCommands(self):
return self.getTypedRuleContext(AutolevParser.CodeCommandsContext,0)
def massDecl(self):
return self.getTypedRuleContext(AutolevParser.MassDeclContext,0)
def inertiaDecl(self):
return self.getTypedRuleContext(AutolevParser.InertiaDeclContext,0)
def assignment(self):
return self.getTypedRuleContext(AutolevParser.AssignmentContext,0)
def settings(self):
return self.getTypedRuleContext(AutolevParser.SettingsContext,0)
def getRuleIndex(self):
return AutolevParser.RULE_stat
def enterRule(self, listener:ParseTreeListener):
if hasattr( listener, "enterStat" ):
listener.enterStat(self)
def exitRule(self, listener:ParseTreeListener):
if hasattr( listener, "exitStat" ):
listener.exitStat(self)
def stat(self):
localctx = AutolevParser.StatContext(self, self._ctx, self.state)
self.enterRule(localctx, 2, self.RULE_stat)
try:
self.state = 68
self._errHandler.sync(self)
la_ = self._interp.adaptivePredict(self._input,1,self._ctx)
if la_ == 1:
self.enterOuterAlt(localctx, 1)
self.state = 61
self.varDecl()
pass
elif la_ == 2:
self.enterOuterAlt(localctx, 2)
self.state = 62
self.functionCall()
pass
elif la_ == 3:
self.enterOuterAlt(localctx, 3)
self.state = 63
self.codeCommands()
pass
elif la_ == 4:
self.enterOuterAlt(localctx, 4)
self.state = 64
self.massDecl()
pass
elif la_ == 5:
self.enterOuterAlt(localctx, 5)
self.state = 65
self.inertiaDecl()
pass
elif la_ == 6:
self.enterOuterAlt(localctx, 6)
self.state = 66
self.assignment()
pass
elif la_ == 7:
self.enterOuterAlt(localctx, 7)
self.state = 67
self.settings()
pass
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class AssignmentContext(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def getRuleIndex(self):
return AutolevParser.RULE_assignment
def copyFrom(self, ctx:ParserRuleContext):
super().copyFrom(ctx)
class VecAssignContext(AssignmentContext):
def __init__(self, parser, ctx:ParserRuleContext): # actually a AutolevParser.AssignmentContext
super().__init__(parser)
self.copyFrom(ctx)
def vec(self):
return self.getTypedRuleContext(AutolevParser.VecContext,0)
def equals(self):
return self.getTypedRuleContext(AutolevParser.EqualsContext,0)
def expr(self):
return self.getTypedRuleContext(AutolevParser.ExprContext,0)
def enterRule(self, listener:ParseTreeListener):
if hasattr( listener, "enterVecAssign" ):
listener.enterVecAssign(self)
def exitRule(self, listener:ParseTreeListener):
if hasattr( listener, "exitVecAssign" ):
listener.exitVecAssign(self)
class RegularAssignContext(AssignmentContext):
def __init__(self, parser, ctx:ParserRuleContext): # actually a AutolevParser.AssignmentContext
super().__init__(parser)
self.copyFrom(ctx)
def ID(self):
return self.getToken(AutolevParser.ID, 0)
def equals(self):
return self.getTypedRuleContext(AutolevParser.EqualsContext,0)
def expr(self):
return self.getTypedRuleContext(AutolevParser.ExprContext,0)
def diff(self):
return self.getTypedRuleContext(AutolevParser.DiffContext,0)
def enterRule(self, listener:ParseTreeListener):
if hasattr( listener, "enterRegularAssign" ):
listener.enterRegularAssign(self)
def exitRule(self, listener:ParseTreeListener):
if hasattr( listener, "exitRegularAssign" ):
listener.exitRegularAssign(self)
class IndexAssignContext(AssignmentContext):
def __init__(self, parser, ctx:ParserRuleContext): # actually a AutolevParser.AssignmentContext
super().__init__(parser)
self.copyFrom(ctx)
def ID(self):
return self.getToken(AutolevParser.ID, 0)
def index(self):
return self.getTypedRuleContext(AutolevParser.IndexContext,0)
def equals(self):
return self.getTypedRuleContext(AutolevParser.EqualsContext,0)
def expr(self):
return self.getTypedRuleContext(AutolevParser.ExprContext,0)
def enterRule(self, listener:ParseTreeListener):
if hasattr( listener, "enterIndexAssign" ):
listener.enterIndexAssign(self)
def exitRule(self, listener:ParseTreeListener):
if hasattr( listener, "exitIndexAssign" ):
listener.exitIndexAssign(self)
def assignment(self):
localctx = AutolevParser.AssignmentContext(self, self._ctx, self.state)
self.enterRule(localctx, 4, self.RULE_assignment)
self._la = 0 # Token type
try:
self.state = 88
self._errHandler.sync(self)
la_ = self._interp.adaptivePredict(self._input,3,self._ctx)
if la_ == 1:
localctx = AutolevParser.VecAssignContext(self, localctx)
self.enterOuterAlt(localctx, 1)
self.state = 70
self.vec()
self.state = 71
self.equals()
self.state = 72
self.expr(0)
pass
elif la_ == 2:
localctx = AutolevParser.IndexAssignContext(self, localctx)
self.enterOuterAlt(localctx, 2)
self.state = 74
self.match(AutolevParser.ID)
self.state = 75
self.match(AutolevParser.T__0)
self.state = 76
self.index()
self.state = 77
self.match(AutolevParser.T__1)
self.state = 78
self.equals()
self.state = 79
self.expr(0)
pass
elif la_ == 3:
localctx = AutolevParser.RegularAssignContext(self, localctx)
self.enterOuterAlt(localctx, 3)
self.state = 81
self.match(AutolevParser.ID)
self.state = 83
self._errHandler.sync(self)
_la = self._input.LA(1)
if _la==AutolevParser.T__10:
self.state = 82
self.diff()
self.state = 85
self.equals()
self.state = 86
self.expr(0)
pass
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class EqualsContext(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def getRuleIndex(self):
return AutolevParser.RULE_equals
def enterRule(self, listener:ParseTreeListener):
if hasattr( listener, "enterEquals" ):
listener.enterEquals(self)
def exitRule(self, listener:ParseTreeListener):
if hasattr( listener, "exitEquals" ):
listener.exitEquals(self)
def equals(self):
localctx = AutolevParser.EqualsContext(self, self._ctx, self.state)
self.enterRule(localctx, 6, self.RULE_equals)
self._la = 0 # Token type
try:
self.enterOuterAlt(localctx, 1)
self.state = 90
_la = self._input.LA(1)
if not((((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << AutolevParser.T__2) | (1 << AutolevParser.T__3) | (1 << AutolevParser.T__4) | (1 << AutolevParser.T__5) | (1 << AutolevParser.T__6) | (1 << AutolevParser.T__7) | (1 << AutolevParser.T__8))) != 0)):
self._errHandler.recoverInline(self)
else:
self._errHandler.reportMatch(self)
self.consume()
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class IndexContext(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def expr(self, i:int=None):
if i is None:
return self.getTypedRuleContexts(AutolevParser.ExprContext)
else:
return self.getTypedRuleContext(AutolevParser.ExprContext,i)
def getRuleIndex(self):
return AutolevParser.RULE_index
def enterRule(self, listener:ParseTreeListener):
if hasattr( listener, "enterIndex" ):
listener.enterIndex(self)
def exitRule(self, listener:ParseTreeListener):
if hasattr( listener, "exitIndex" ):
listener.exitIndex(self)
def index(self):
localctx = AutolevParser.IndexContext(self, self._ctx, self.state)
self.enterRule(localctx, 8, self.RULE_index)
self._la = 0 # Token type
try:
self.enterOuterAlt(localctx, 1)
self.state = 92
self.expr(0)
self.state = 97
self._errHandler.sync(self)
_la = self._input.LA(1)
while _la==AutolevParser.T__9:
self.state = 93
self.match(AutolevParser.T__9)
self.state = 94
self.expr(0)
self.state = 99
self._errHandler.sync(self)
_la = self._input.LA(1)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class DiffContext(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def getRuleIndex(self):
return AutolevParser.RULE_diff
def enterRule(self, listener:ParseTreeListener):
if hasattr( listener, "enterDiff" ):
listener.enterDiff(self)
def exitRule(self, listener:ParseTreeListener):
if hasattr( listener, "exitDiff" ):
listener.exitDiff(self)
def diff(self):
localctx = AutolevParser.DiffContext(self, self._ctx, self.state)
self.enterRule(localctx, 10, self.RULE_diff)
self._la = 0 # Token type
try:
self.enterOuterAlt(localctx, 1)
self.state = 101
self._errHandler.sync(self)
_la = self._input.LA(1)
while True:
self.state = 100
self.match(AutolevParser.T__10)
self.state = 103
self._errHandler.sync(self)
_la = self._input.LA(1)
if not (_la==AutolevParser.T__10):
break
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class FunctionCallContext(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def ID(self, i:int=None):
if i is None:
return self.getTokens(AutolevParser.ID)
else:
return self.getToken(AutolevParser.ID, i)
def expr(self, i:int=None):
if i is None:
return self.getTypedRuleContexts(AutolevParser.ExprContext)
else:
return self.getTypedRuleContext(AutolevParser.ExprContext,i)
def Mass(self):
return self.getToken(AutolevParser.Mass, 0)
def Inertia(self):
return self.getToken(AutolevParser.Inertia, 0)
def getRuleIndex(self):
return AutolevParser.RULE_functionCall
def enterRule(self, listener:ParseTreeListener):
if hasattr( listener, "enterFunctionCall" ):
listener.enterFunctionCall(self)
def exitRule(self, listener:ParseTreeListener):
if hasattr( listener, "exitFunctionCall" ):
listener.exitFunctionCall(self)
def functionCall(self):
localctx = AutolevParser.FunctionCallContext(self, self._ctx, self.state)
self.enterRule(localctx, 12, self.RULE_functionCall)
self._la = 0 # Token type
try:
self.state = 131
self._errHandler.sync(self)
token = self._input.LA(1)
if token in [AutolevParser.ID]:
self.enterOuterAlt(localctx, 1)
self.state = 105
self.match(AutolevParser.ID)
self.state = 106
self.match(AutolevParser.T__11)
self.state = 115
self._errHandler.sync(self)
_la = self._input.LA(1)
if (((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << AutolevParser.T__0) | (1 << AutolevParser.T__11) | (1 << AutolevParser.T__13) | (1 << AutolevParser.T__17) | (1 << AutolevParser.T__21) | (1 << AutolevParser.T__22) | (1 << AutolevParser.Mass) | (1 << AutolevParser.Inertia) | (1 << AutolevParser.INT) | (1 << AutolevParser.FLOAT) | (1 << AutolevParser.EXP) | (1 << AutolevParser.ID))) != 0):
self.state = 107
self.expr(0)
self.state = 112
self._errHandler.sync(self)
_la = self._input.LA(1)
while _la==AutolevParser.T__9:
self.state = 108
self.match(AutolevParser.T__9)
self.state = 109
self.expr(0)
self.state = 114
self._errHandler.sync(self)
_la = self._input.LA(1)
self.state = 117
self.match(AutolevParser.T__12)
pass
elif token in [AutolevParser.Mass, AutolevParser.Inertia]:
self.enterOuterAlt(localctx, 2)
self.state = 118
_la = self._input.LA(1)
if not(_la==AutolevParser.Mass or _la==AutolevParser.Inertia):
self._errHandler.recoverInline(self)
else:
self._errHandler.reportMatch(self)
self.consume()
self.state = 119
self.match(AutolevParser.T__11)
self.state = 128
self._errHandler.sync(self)
_la = self._input.LA(1)
if _la==AutolevParser.ID:
self.state = 120
self.match(AutolevParser.ID)
self.state = 125
self._errHandler.sync(self)
_la = self._input.LA(1)
while _la==AutolevParser.T__9:
self.state = 121
self.match(AutolevParser.T__9)
self.state = 122
self.match(AutolevParser.ID)
self.state = 127
self._errHandler.sync(self)
_la = self._input.LA(1)
self.state = 130
self.match(AutolevParser.T__12)
pass
else:
raise NoViableAltException(self)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class VarDeclContext(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def varType(self):
return self.getTypedRuleContext(AutolevParser.VarTypeContext,0)
def varDecl2(self, i:int=None):
if i is None:
return self.getTypedRuleContexts(AutolevParser.VarDecl2Context)
else:
return self.getTypedRuleContext(AutolevParser.VarDecl2Context,i)
def getRuleIndex(self):
return AutolevParser.RULE_varDecl
def enterRule(self, listener:ParseTreeListener):
if hasattr( listener, "enterVarDecl" ):
listener.enterVarDecl(self)
def exitRule(self, listener:ParseTreeListener):
if hasattr( listener, "exitVarDecl" ):
listener.exitVarDecl(self)
def varDecl(self):
localctx = AutolevParser.VarDeclContext(self, self._ctx, self.state)
self.enterRule(localctx, 14, self.RULE_varDecl)
self._la = 0 # Token type
try:
self.enterOuterAlt(localctx, 1)
self.state = 133
self.varType()
self.state = 134
self.varDecl2()
self.state = 139
self._errHandler.sync(self)
_la = self._input.LA(1)
while _la==AutolevParser.T__9:
self.state = 135
self.match(AutolevParser.T__9)
self.state = 136
self.varDecl2()
self.state = 141
self._errHandler.sync(self)
_la = self._input.LA(1)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class VarTypeContext(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def Newtonian(self):
return self.getToken(AutolevParser.Newtonian, 0)
def Frames(self):
return self.getToken(AutolevParser.Frames, 0)
def Bodies(self):
return self.getToken(AutolevParser.Bodies, 0)
def Particles(self):
return self.getToken(AutolevParser.Particles, 0)
def Points(self):
return self.getToken(AutolevParser.Points, 0)
def Constants(self):
return self.getToken(AutolevParser.Constants, 0)
def Specifieds(self):
return self.getToken(AutolevParser.Specifieds, 0)
def Imaginary(self):
return self.getToken(AutolevParser.Imaginary, 0)
def Variables(self):
return self.getToken(AutolevParser.Variables, 0)
def MotionVariables(self):
return self.getToken(AutolevParser.MotionVariables, 0)
def getRuleIndex(self):
return AutolevParser.RULE_varType
def enterRule(self, listener:ParseTreeListener):
if hasattr( listener, "enterVarType" ):
listener.enterVarType(self)
def exitRule(self, listener:ParseTreeListener):
if hasattr( listener, "exitVarType" ):
listener.exitVarType(self)
def varType(self):
localctx = AutolevParser.VarTypeContext(self, self._ctx, self.state)
self.enterRule(localctx, 16, self.RULE_varType)
self._la = 0 # Token type
try:
self.state = 164
self._errHandler.sync(self)
token = self._input.LA(1)
if token in [AutolevParser.Newtonian]:
self.enterOuterAlt(localctx, 1)
self.state = 142
self.match(AutolevParser.Newtonian)
pass
elif token in [AutolevParser.Frames]:
self.enterOuterAlt(localctx, 2)
self.state = 143
self.match(AutolevParser.Frames)
pass
elif token in [AutolevParser.Bodies]:
self.enterOuterAlt(localctx, 3)
self.state = 144
self.match(AutolevParser.Bodies)
pass
elif token in [AutolevParser.Particles]:
self.enterOuterAlt(localctx, 4)
self.state = 145
self.match(AutolevParser.Particles)
pass
elif token in [AutolevParser.Points]:
self.enterOuterAlt(localctx, 5)
self.state = 146
self.match(AutolevParser.Points)
pass
elif token in [AutolevParser.Constants]:
self.enterOuterAlt(localctx, 6)
self.state = 147
self.match(AutolevParser.Constants)
pass
elif token in [AutolevParser.Specifieds]:
self.enterOuterAlt(localctx, 7)
self.state = 148
self.match(AutolevParser.Specifieds)
pass
elif token in [AutolevParser.Imaginary]:
self.enterOuterAlt(localctx, 8)
self.state = 149
self.match(AutolevParser.Imaginary)
pass
elif token in [AutolevParser.Variables]:
self.enterOuterAlt(localctx, 9)
self.state = 150
self.match(AutolevParser.Variables)
self.state = 154
self._errHandler.sync(self)
_la = self._input.LA(1)
while _la==AutolevParser.T__10:
self.state = 151
self.match(AutolevParser.T__10)
self.state = 156
self._errHandler.sync(self)
_la = self._input.LA(1)
pass
elif token in [AutolevParser.MotionVariables]:
self.enterOuterAlt(localctx, 10)
self.state = 157
self.match(AutolevParser.MotionVariables)
self.state = 161
self._errHandler.sync(self)
_la = self._input.LA(1)
while _la==AutolevParser.T__10:
self.state = 158
self.match(AutolevParser.T__10)
self.state = 163
self._errHandler.sync(self)
_la = self._input.LA(1)
pass
else:
raise NoViableAltException(self)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class VarDecl2Context(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def ID(self):
return self.getToken(AutolevParser.ID, 0)
def INT(self, i:int=None):
if i is None:
return self.getTokens(AutolevParser.INT)
else:
return self.getToken(AutolevParser.INT, i)
def expr(self):
return self.getTypedRuleContext(AutolevParser.ExprContext,0)
def getRuleIndex(self):
return AutolevParser.RULE_varDecl2
def enterRule(self, listener:ParseTreeListener):
if hasattr( listener, "enterVarDecl2" ):
listener.enterVarDecl2(self)
def exitRule(self, listener:ParseTreeListener):
if hasattr( listener, "exitVarDecl2" ):
listener.exitVarDecl2(self)
def varDecl2(self):
localctx = AutolevParser.VarDecl2Context(self, self._ctx, self.state)
self.enterRule(localctx, 18, self.RULE_varDecl2)
self._la = 0 # Token type
try:
self.enterOuterAlt(localctx, 1)
self.state = 166
self.match(AutolevParser.ID)
self.state = 172
self._errHandler.sync(self)
la_ = self._interp.adaptivePredict(self._input,15,self._ctx)
if la_ == 1:
self.state = 167
self.match(AutolevParser.T__13)
self.state = 168
self.match(AutolevParser.INT)
self.state = 169
self.match(AutolevParser.T__9)
self.state = 170
self.match(AutolevParser.INT)
self.state = 171
self.match(AutolevParser.T__14)
self.state = 188
self._errHandler.sync(self)
la_ = self._interp.adaptivePredict(self._input,17,self._ctx)
if la_ == 1:
self.state = 174
self.match(AutolevParser.T__13)
self.state = 175
self.match(AutolevParser.INT)
self.state = 176
self.match(AutolevParser.T__15)
self.state = 177
self.match(AutolevParser.INT)
self.state = 184
self._errHandler.sync(self)
_la = self._input.LA(1)
while _la==AutolevParser.T__9:
self.state = 178
self.match(AutolevParser.T__9)
self.state = 179
self.match(AutolevParser.INT)
self.state = 180
self.match(AutolevParser.T__15)
self.state = 181
self.match(AutolevParser.INT)
self.state = 186
self._errHandler.sync(self)
_la = self._input.LA(1)
self.state = 187
self.match(AutolevParser.T__14)
self.state = 193
self._errHandler.sync(self)
_la = self._input.LA(1)
if _la==AutolevParser.T__13:
self.state = 190
self.match(AutolevParser.T__13)
self.state = 191
self.match(AutolevParser.INT)
self.state = 192
self.match(AutolevParser.T__14)
self.state = 196
self._errHandler.sync(self)
_la = self._input.LA(1)
if _la==AutolevParser.T__16 or _la==AutolevParser.T__17:
self.state = 195
_la = self._input.LA(1)
if not(_la==AutolevParser.T__16 or _la==AutolevParser.T__17):
self._errHandler.recoverInline(self)
else:
self._errHandler.reportMatch(self)
self.consume()
self.state = 201
self._errHandler.sync(self)
_la = self._input.LA(1)
while _la==AutolevParser.T__10:
self.state = 198
self.match(AutolevParser.T__10)
self.state = 203
self._errHandler.sync(self)
_la = self._input.LA(1)
self.state = 206
self._errHandler.sync(self)
_la = self._input.LA(1)
if _la==AutolevParser.T__2:
self.state = 204
self.match(AutolevParser.T__2)
self.state = 205
self.expr(0)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class RangesContext(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def INT(self, i:int=None):
if i is None:
return self.getTokens(AutolevParser.INT)
else:
return self.getToken(AutolevParser.INT, i)
def getRuleIndex(self):
return AutolevParser.RULE_ranges
def enterRule(self, listener:ParseTreeListener):
if hasattr( listener, "enterRanges" ):
listener.enterRanges(self)
def exitRule(self, listener:ParseTreeListener):
if hasattr( listener, "exitRanges" ):
listener.exitRanges(self)
def ranges(self):
localctx = AutolevParser.RangesContext(self, self._ctx, self.state)
self.enterRule(localctx, 20, self.RULE_ranges)
self._la = 0 # Token type
try:
self.enterOuterAlt(localctx, 1)
self.state = 208
self.match(AutolevParser.T__13)
self.state = 209
self.match(AutolevParser.INT)
self.state = 210
self.match(AutolevParser.T__15)
self.state = 211
self.match(AutolevParser.INT)
self.state = 218
self._errHandler.sync(self)
_la = self._input.LA(1)
while _la==AutolevParser.T__9:
self.state = 212
self.match(AutolevParser.T__9)
self.state = 213
self.match(AutolevParser.INT)
self.state = 214
self.match(AutolevParser.T__15)
self.state = 215
self.match(AutolevParser.INT)
self.state = 220
self._errHandler.sync(self)
_la = self._input.LA(1)
self.state = 221
self.match(AutolevParser.T__14)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class MassDeclContext(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def Mass(self):
return self.getToken(AutolevParser.Mass, 0)
def massDecl2(self, i:int=None):
if i is None:
return self.getTypedRuleContexts(AutolevParser.MassDecl2Context)
else:
return self.getTypedRuleContext(AutolevParser.MassDecl2Context,i)
def getRuleIndex(self):
return AutolevParser.RULE_massDecl
def enterRule(self, listener:ParseTreeListener):
if hasattr( listener, "enterMassDecl" ):
listener.enterMassDecl(self)
def exitRule(self, listener:ParseTreeListener):
if hasattr( listener, "exitMassDecl" ):
listener.exitMassDecl(self)
def massDecl(self):
localctx = AutolevParser.MassDeclContext(self, self._ctx, self.state)
self.enterRule(localctx, 22, self.RULE_massDecl)
self._la = 0 # Token type
try:
self.enterOuterAlt(localctx, 1)
self.state = 223
self.match(AutolevParser.Mass)
self.state = 224
self.massDecl2()
self.state = 229
self._errHandler.sync(self)
_la = self._input.LA(1)
while _la==AutolevParser.T__9:
self.state = 225
self.match(AutolevParser.T__9)
self.state = 226
self.massDecl2()
self.state = 231
self._errHandler.sync(self)
_la = self._input.LA(1)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class MassDecl2Context(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def ID(self):
return self.getToken(AutolevParser.ID, 0)
def expr(self):
return self.getTypedRuleContext(AutolevParser.ExprContext,0)
def getRuleIndex(self):
return AutolevParser.RULE_massDecl2
def enterRule(self, listener:ParseTreeListener):
if hasattr( listener, "enterMassDecl2" ):
listener.enterMassDecl2(self)
def exitRule(self, listener:ParseTreeListener):
if hasattr( listener, "exitMassDecl2" ):
listener.exitMassDecl2(self)
def massDecl2(self):
localctx = AutolevParser.MassDecl2Context(self, self._ctx, self.state)
self.enterRule(localctx, 24, self.RULE_massDecl2)
try:
self.enterOuterAlt(localctx, 1)
self.state = 232
self.match(AutolevParser.ID)
self.state = 233
self.match(AutolevParser.T__2)
self.state = 234
self.expr(0)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class InertiaDeclContext(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def Inertia(self):
return self.getToken(AutolevParser.Inertia, 0)
def ID(self, i:int=None):
if i is None:
return self.getTokens(AutolevParser.ID)
else:
return self.getToken(AutolevParser.ID, i)
def expr(self, i:int=None):
if i is None:
return self.getTypedRuleContexts(AutolevParser.ExprContext)
else:
return self.getTypedRuleContext(AutolevParser.ExprContext,i)
def getRuleIndex(self):
return AutolevParser.RULE_inertiaDecl
def enterRule(self, listener:ParseTreeListener):
if hasattr( listener, "enterInertiaDecl" ):
listener.enterInertiaDecl(self)
def exitRule(self, listener:ParseTreeListener):
if hasattr( listener, "exitInertiaDecl" ):
listener.exitInertiaDecl(self)
def inertiaDecl(self):
localctx = AutolevParser.InertiaDeclContext(self, self._ctx, self.state)
self.enterRule(localctx, 26, self.RULE_inertiaDecl)
self._la = 0 # Token type
try:
self.enterOuterAlt(localctx, 1)
self.state = 236
self.match(AutolevParser.Inertia)
self.state = 237
self.match(AutolevParser.ID)
self.state = 241
self._errHandler.sync(self)
_la = self._input.LA(1)
if _la==AutolevParser.T__11:
self.state = 238
self.match(AutolevParser.T__11)
self.state = 239
self.match(AutolevParser.ID)
self.state = 240
self.match(AutolevParser.T__12)
self.state = 245
self._errHandler.sync(self)
_la = self._input.LA(1)
while True:
self.state = 243
self.match(AutolevParser.T__9)
self.state = 244
self.expr(0)
self.state = 247
self._errHandler.sync(self)
_la = self._input.LA(1)
if not (_la==AutolevParser.T__9):
break
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class MatrixContext(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def expr(self, i:int=None):
if i is None:
return self.getTypedRuleContexts(AutolevParser.ExprContext)
else:
return self.getTypedRuleContext(AutolevParser.ExprContext,i)
def getRuleIndex(self):
return AutolevParser.RULE_matrix
def enterRule(self, listener:ParseTreeListener):
if hasattr( listener, "enterMatrix" ):
listener.enterMatrix(self)
def exitRule(self, listener:ParseTreeListener):
if hasattr( listener, "exitMatrix" ):
listener.exitMatrix(self)
def matrix(self):
localctx = AutolevParser.MatrixContext(self, self._ctx, self.state)
self.enterRule(localctx, 28, self.RULE_matrix)
self._la = 0 # Token type
try:
self.enterOuterAlt(localctx, 1)
self.state = 249
self.match(AutolevParser.T__0)
self.state = 250
self.expr(0)
self.state = 255
self._errHandler.sync(self)
_la = self._input.LA(1)
while _la==AutolevParser.T__9 or _la==AutolevParser.T__18:
self.state = 251
_la = self._input.LA(1)
if not(_la==AutolevParser.T__9 or _la==AutolevParser.T__18):
self._errHandler.recoverInline(self)
else:
self._errHandler.reportMatch(self)
self.consume()
self.state = 252
self.expr(0)
self.state = 257
self._errHandler.sync(self)
_la = self._input.LA(1)
self.state = 258
self.match(AutolevParser.T__1)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class MatrixInOutputContext(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def ID(self, i:int=None):
if i is None:
return self.getTokens(AutolevParser.ID)
else:
return self.getToken(AutolevParser.ID, i)
def FLOAT(self):
return self.getToken(AutolevParser.FLOAT, 0)
def INT(self):
return self.getToken(AutolevParser.INT, 0)
def getRuleIndex(self):
return AutolevParser.RULE_matrixInOutput
def enterRule(self, listener:ParseTreeListener):
if hasattr( listener, "enterMatrixInOutput" ):
listener.enterMatrixInOutput(self)
def exitRule(self, listener:ParseTreeListener):
if hasattr( listener, "exitMatrixInOutput" ):
listener.exitMatrixInOutput(self)
def matrixInOutput(self):
localctx = AutolevParser.MatrixInOutputContext(self, self._ctx, self.state)
self.enterRule(localctx, 30, self.RULE_matrixInOutput)
self._la = 0 # Token type
try:
self.state = 268
self._errHandler.sync(self)
token = self._input.LA(1)
if token in [AutolevParser.ID]:
self.enterOuterAlt(localctx, 1)
self.state = 260
self.match(AutolevParser.ID)
self.state = 261
self.match(AutolevParser.ID)
self.state = 262
self.match(AutolevParser.T__2)
self.state = 264
self._errHandler.sync(self)
_la = self._input.LA(1)
if _la==AutolevParser.INT or _la==AutolevParser.FLOAT:
self.state = 263
_la = self._input.LA(1)
if not(_la==AutolevParser.INT or _la==AutolevParser.FLOAT):
self._errHandler.recoverInline(self)
else:
self._errHandler.reportMatch(self)
self.consume()
pass
elif token in [AutolevParser.FLOAT]:
self.enterOuterAlt(localctx, 2)
self.state = 266
self.match(AutolevParser.FLOAT)
pass
elif token in [AutolevParser.INT]:
self.enterOuterAlt(localctx, 3)
self.state = 267
self.match(AutolevParser.INT)
pass
else:
raise NoViableAltException(self)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class CodeCommandsContext(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def units(self):
return self.getTypedRuleContext(AutolevParser.UnitsContext,0)
def inputs(self):
return self.getTypedRuleContext(AutolevParser.InputsContext,0)
def outputs(self):
return self.getTypedRuleContext(AutolevParser.OutputsContext,0)
def codegen(self):
return self.getTypedRuleContext(AutolevParser.CodegenContext,0)
def commands(self):
return self.getTypedRuleContext(AutolevParser.CommandsContext,0)
def getRuleIndex(self):
return AutolevParser.RULE_codeCommands
def enterRule(self, listener:ParseTreeListener):
if hasattr( listener, "enterCodeCommands" ):
listener.enterCodeCommands(self)
def exitRule(self, listener:ParseTreeListener):
if hasattr( listener, "exitCodeCommands" ):
listener.exitCodeCommands(self)
def codeCommands(self):
localctx = AutolevParser.CodeCommandsContext(self, self._ctx, self.state)
self.enterRule(localctx, 32, self.RULE_codeCommands)
try:
self.state = 275
self._errHandler.sync(self)
token = self._input.LA(1)
if token in [AutolevParser.UnitSystem]:
self.enterOuterAlt(localctx, 1)
self.state = 270
self.units()
pass
elif token in [AutolevParser.Input]:
self.enterOuterAlt(localctx, 2)
self.state = 271
self.inputs()
pass
elif token in [AutolevParser.Output]:
self.enterOuterAlt(localctx, 3)
self.state = 272
self.outputs()
pass
elif token in [AutolevParser.ID]:
self.enterOuterAlt(localctx, 4)
self.state = 273
self.codegen()
pass
elif token in [AutolevParser.Save, AutolevParser.Encode]:
self.enterOuterAlt(localctx, 5)
self.state = 274
self.commands()
pass
else:
raise NoViableAltException(self)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class SettingsContext(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def ID(self, i:int=None):
if i is None:
return self.getTokens(AutolevParser.ID)
else:
return self.getToken(AutolevParser.ID, i)
def EXP(self):
return self.getToken(AutolevParser.EXP, 0)
def FLOAT(self):
return self.getToken(AutolevParser.FLOAT, 0)
def INT(self):
return self.getToken(AutolevParser.INT, 0)
def getRuleIndex(self):
return AutolevParser.RULE_settings
def enterRule(self, listener:ParseTreeListener):
if hasattr( listener, "enterSettings" ):
listener.enterSettings(self)
def exitRule(self, listener:ParseTreeListener):
if hasattr( listener, "exitSettings" ):
listener.exitSettings(self)
def settings(self):
localctx = AutolevParser.SettingsContext(self, self._ctx, self.state)
self.enterRule(localctx, 34, self.RULE_settings)
self._la = 0 # Token type
try:
self.enterOuterAlt(localctx, 1)
self.state = 277
self.match(AutolevParser.ID)
self.state = 279
self._errHandler.sync(self)
la_ = self._interp.adaptivePredict(self._input,30,self._ctx)
if la_ == 1:
self.state = 278
_la = self._input.LA(1)
if not((((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << AutolevParser.INT) | (1 << AutolevParser.FLOAT) | (1 << AutolevParser.EXP) | (1 << AutolevParser.ID))) != 0)):
self._errHandler.recoverInline(self)
else:
self._errHandler.reportMatch(self)
self.consume()
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class UnitsContext(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def UnitSystem(self):
return self.getToken(AutolevParser.UnitSystem, 0)
def ID(self, i:int=None):
if i is None:
return self.getTokens(AutolevParser.ID)
else:
return self.getToken(AutolevParser.ID, i)
def getRuleIndex(self):
return AutolevParser.RULE_units
def enterRule(self, listener:ParseTreeListener):
if hasattr( listener, "enterUnits" ):
listener.enterUnits(self)
def exitRule(self, listener:ParseTreeListener):
if hasattr( listener, "exitUnits" ):
listener.exitUnits(self)
def units(self):
localctx = AutolevParser.UnitsContext(self, self._ctx, self.state)
self.enterRule(localctx, 36, self.RULE_units)
self._la = 0 # Token type
try:
self.enterOuterAlt(localctx, 1)
self.state = 281
self.match(AutolevParser.UnitSystem)
self.state = 282
self.match(AutolevParser.ID)
self.state = 287
self._errHandler.sync(self)
_la = self._input.LA(1)
while _la==AutolevParser.T__9:
self.state = 283
self.match(AutolevParser.T__9)
self.state = 284
self.match(AutolevParser.ID)
self.state = 289
self._errHandler.sync(self)
_la = self._input.LA(1)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class InputsContext(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def Input(self):
return self.getToken(AutolevParser.Input, 0)
def inputs2(self, i:int=None):
if i is None:
return self.getTypedRuleContexts(AutolevParser.Inputs2Context)
else:
return self.getTypedRuleContext(AutolevParser.Inputs2Context,i)
def getRuleIndex(self):
return AutolevParser.RULE_inputs
def enterRule(self, listener:ParseTreeListener):
if hasattr( listener, "enterInputs" ):
listener.enterInputs(self)
def exitRule(self, listener:ParseTreeListener):
if hasattr( listener, "exitInputs" ):
listener.exitInputs(self)
def inputs(self):
localctx = AutolevParser.InputsContext(self, self._ctx, self.state)
self.enterRule(localctx, 38, self.RULE_inputs)
self._la = 0 # Token type
try:
self.enterOuterAlt(localctx, 1)
self.state = 290
self.match(AutolevParser.Input)
self.state = 291
self.inputs2()
self.state = 296
self._errHandler.sync(self)
_la = self._input.LA(1)
while _la==AutolevParser.T__9:
self.state = 292
self.match(AutolevParser.T__9)
self.state = 293
self.inputs2()
self.state = 298
self._errHandler.sync(self)
_la = self._input.LA(1)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class Id_diffContext(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def ID(self):
return self.getToken(AutolevParser.ID, 0)
def diff(self):
return self.getTypedRuleContext(AutolevParser.DiffContext,0)
def getRuleIndex(self):
return AutolevParser.RULE_id_diff
def enterRule(self, listener:ParseTreeListener):
if hasattr( listener, "enterId_diff" ):
listener.enterId_diff(self)
def exitRule(self, listener:ParseTreeListener):
if hasattr( listener, "exitId_diff" ):
listener.exitId_diff(self)
def id_diff(self):
localctx = AutolevParser.Id_diffContext(self, self._ctx, self.state)
self.enterRule(localctx, 40, self.RULE_id_diff)
self._la = 0 # Token type
try:
self.enterOuterAlt(localctx, 1)
self.state = 299
self.match(AutolevParser.ID)
self.state = 301
self._errHandler.sync(self)
_la = self._input.LA(1)
if _la==AutolevParser.T__10:
self.state = 300
self.diff()
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class Inputs2Context(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def id_diff(self):
return self.getTypedRuleContext(AutolevParser.Id_diffContext,0)
def expr(self, i:int=None):
if i is None:
return self.getTypedRuleContexts(AutolevParser.ExprContext)
else:
return self.getTypedRuleContext(AutolevParser.ExprContext,i)
def getRuleIndex(self):
return AutolevParser.RULE_inputs2
def enterRule(self, listener:ParseTreeListener):
if hasattr( listener, "enterInputs2" ):
listener.enterInputs2(self)
def exitRule(self, listener:ParseTreeListener):
if hasattr( listener, "exitInputs2" ):
listener.exitInputs2(self)
def inputs2(self):
localctx = AutolevParser.Inputs2Context(self, self._ctx, self.state)
self.enterRule(localctx, 42, self.RULE_inputs2)
try:
self.enterOuterAlt(localctx, 1)
self.state = 303
self.id_diff()
self.state = 304
self.match(AutolevParser.T__2)
self.state = 305
self.expr(0)
self.state = 307
self._errHandler.sync(self)
la_ = self._interp.adaptivePredict(self._input,34,self._ctx)
if la_ == 1:
self.state = 306
self.expr(0)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class OutputsContext(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def Output(self):
return self.getToken(AutolevParser.Output, 0)
def outputs2(self, i:int=None):
if i is None:
return self.getTypedRuleContexts(AutolevParser.Outputs2Context)
else:
return self.getTypedRuleContext(AutolevParser.Outputs2Context,i)
def getRuleIndex(self):
return AutolevParser.RULE_outputs
def enterRule(self, listener:ParseTreeListener):
if hasattr( listener, "enterOutputs" ):
listener.enterOutputs(self)
def exitRule(self, listener:ParseTreeListener):
if hasattr( listener, "exitOutputs" ):
listener.exitOutputs(self)
def outputs(self):
localctx = AutolevParser.OutputsContext(self, self._ctx, self.state)
self.enterRule(localctx, 44, self.RULE_outputs)
self._la = 0 # Token type
try:
self.enterOuterAlt(localctx, 1)
self.state = 309
self.match(AutolevParser.Output)
self.state = 310
self.outputs2()
self.state = 315
self._errHandler.sync(self)
_la = self._input.LA(1)
while _la==AutolevParser.T__9:
self.state = 311
self.match(AutolevParser.T__9)
self.state = 312
self.outputs2()
self.state = 317
self._errHandler.sync(self)
_la = self._input.LA(1)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class Outputs2Context(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def expr(self, i:int=None):
if i is None:
return self.getTypedRuleContexts(AutolevParser.ExprContext)
else:
return self.getTypedRuleContext(AutolevParser.ExprContext,i)
def getRuleIndex(self):
return AutolevParser.RULE_outputs2
def enterRule(self, listener:ParseTreeListener):
if hasattr( listener, "enterOutputs2" ):
listener.enterOutputs2(self)
def exitRule(self, listener:ParseTreeListener):
if hasattr( listener, "exitOutputs2" ):
listener.exitOutputs2(self)
def outputs2(self):
localctx = AutolevParser.Outputs2Context(self, self._ctx, self.state)
self.enterRule(localctx, 46, self.RULE_outputs2)
try:
self.enterOuterAlt(localctx, 1)
self.state = 318
self.expr(0)
self.state = 320
self._errHandler.sync(self)
la_ = self._interp.adaptivePredict(self._input,36,self._ctx)
if la_ == 1:
self.state = 319
self.expr(0)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class CodegenContext(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def ID(self, i:int=None):
if i is None:
return self.getTokens(AutolevParser.ID)
else:
return self.getToken(AutolevParser.ID, i)
def functionCall(self):
return self.getTypedRuleContext(AutolevParser.FunctionCallContext,0)
def matrixInOutput(self, i:int=None):
if i is None:
return self.getTypedRuleContexts(AutolevParser.MatrixInOutputContext)
else:
return self.getTypedRuleContext(AutolevParser.MatrixInOutputContext,i)
def getRuleIndex(self):
return AutolevParser.RULE_codegen
def enterRule(self, listener:ParseTreeListener):
if hasattr( listener, "enterCodegen" ):
listener.enterCodegen(self)
def exitRule(self, listener:ParseTreeListener):
if hasattr( listener, "exitCodegen" ):
listener.exitCodegen(self)
def codegen(self):
localctx = AutolevParser.CodegenContext(self, self._ctx, self.state)
self.enterRule(localctx, 48, self.RULE_codegen)
self._la = 0 # Token type
try:
self.enterOuterAlt(localctx, 1)
self.state = 322
self.match(AutolevParser.ID)
self.state = 323
self.functionCall()
self.state = 335
self._errHandler.sync(self)
_la = self._input.LA(1)
if _la==AutolevParser.T__0:
self.state = 324
self.match(AutolevParser.T__0)
self.state = 325
self.matrixInOutput()
self.state = 330
self._errHandler.sync(self)
_la = self._input.LA(1)
while _la==AutolevParser.T__9:
self.state = 326
self.match(AutolevParser.T__9)
self.state = 327
self.matrixInOutput()
self.state = 332
self._errHandler.sync(self)
_la = self._input.LA(1)
self.state = 333
self.match(AutolevParser.T__1)
self.state = 337
self.match(AutolevParser.ID)
self.state = 338
self.match(AutolevParser.T__19)
self.state = 339
self.match(AutolevParser.ID)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class CommandsContext(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def Save(self):
return self.getToken(AutolevParser.Save, 0)
def ID(self, i:int=None):
if i is None:
return self.getTokens(AutolevParser.ID)
else:
return self.getToken(AutolevParser.ID, i)
def Encode(self):
return self.getToken(AutolevParser.Encode, 0)
def getRuleIndex(self):
return AutolevParser.RULE_commands
def enterRule(self, listener:ParseTreeListener):
if hasattr( listener, "enterCommands" ):
listener.enterCommands(self)
def exitRule(self, listener:ParseTreeListener):
if hasattr( listener, "exitCommands" ):
listener.exitCommands(self)
def commands(self):
localctx = AutolevParser.CommandsContext(self, self._ctx, self.state)
self.enterRule(localctx, 50, self.RULE_commands)
self._la = 0 # Token type
try:
self.state = 354
self._errHandler.sync(self)
token = self._input.LA(1)
if token in [AutolevParser.Save]:
self.enterOuterAlt(localctx, 1)
self.state = 341
self.match(AutolevParser.Save)
self.state = 342
self.match(AutolevParser.ID)
self.state = 343
self.match(AutolevParser.T__19)
self.state = 344
self.match(AutolevParser.ID)
pass
elif token in [AutolevParser.Encode]:
self.enterOuterAlt(localctx, 2)
self.state = 345
self.match(AutolevParser.Encode)
self.state = 346
self.match(AutolevParser.ID)
self.state = 351
self._errHandler.sync(self)
_la = self._input.LA(1)
while _la==AutolevParser.T__9:
self.state = 347
self.match(AutolevParser.T__9)
self.state = 348
self.match(AutolevParser.ID)
self.state = 353
self._errHandler.sync(self)
_la = self._input.LA(1)
pass
else:
raise NoViableAltException(self)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class VecContext(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def ID(self):
return self.getToken(AutolevParser.ID, 0)
def getRuleIndex(self):
return AutolevParser.RULE_vec
def enterRule(self, listener:ParseTreeListener):
if hasattr( listener, "enterVec" ):
listener.enterVec(self)
def exitRule(self, listener:ParseTreeListener):
if hasattr( listener, "exitVec" ):
listener.exitVec(self)
def vec(self):
localctx = AutolevParser.VecContext(self, self._ctx, self.state)
self.enterRule(localctx, 52, self.RULE_vec)
try:
self.state = 364
self._errHandler.sync(self)
token = self._input.LA(1)
if token in [AutolevParser.ID]:
self.enterOuterAlt(localctx, 1)
self.state = 356
self.match(AutolevParser.ID)
self.state = 358
self._errHandler.sync(self)
_alt = 1
while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:
if _alt == 1:
self.state = 357
self.match(AutolevParser.T__20)
else:
raise NoViableAltException(self)
self.state = 360
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input,41,self._ctx)
pass
elif token in [AutolevParser.T__21]:
self.enterOuterAlt(localctx, 2)
self.state = 362
self.match(AutolevParser.T__21)
pass
elif token in [AutolevParser.T__22]:
self.enterOuterAlt(localctx, 3)
self.state = 363
self.match(AutolevParser.T__22)
pass
else:
raise NoViableAltException(self)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class ExprContext(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def getRuleIndex(self):
return AutolevParser.RULE_expr
def copyFrom(self, ctx:ParserRuleContext):
super().copyFrom(ctx)
class ParensContext(ExprContext):
def __init__(self, parser, ctx:ParserRuleContext): # actually a AutolevParser.ExprContext
super().__init__(parser)
self.copyFrom(ctx)
def expr(self):
return self.getTypedRuleContext(AutolevParser.ExprContext,0)
def enterRule(self, listener:ParseTreeListener):
if hasattr( listener, "enterParens" ):
listener.enterParens(self)
def exitRule(self, listener:ParseTreeListener):
if hasattr( listener, "exitParens" ):
listener.exitParens(self)
class VectorOrDyadicContext(ExprContext):
def __init__(self, parser, ctx:ParserRuleContext): # actually a AutolevParser.ExprContext
super().__init__(parser)
self.copyFrom(ctx)
def vec(self):
return self.getTypedRuleContext(AutolevParser.VecContext,0)
def enterRule(self, listener:ParseTreeListener):
if hasattr( listener, "enterVectorOrDyadic" ):
listener.enterVectorOrDyadic(self)
def exitRule(self, listener:ParseTreeListener):
if hasattr( listener, "exitVectorOrDyadic" ):
listener.exitVectorOrDyadic(self)
class ExponentContext(ExprContext):
def __init__(self, parser, ctx:ParserRuleContext): # actually a AutolevParser.ExprContext
super().__init__(parser)
self.copyFrom(ctx)
def expr(self, i:int=None):
if i is None:
return self.getTypedRuleContexts(AutolevParser.ExprContext)
else:
return self.getTypedRuleContext(AutolevParser.ExprContext,i)
def enterRule(self, listener:ParseTreeListener):
if hasattr( listener, "enterExponent" ):
listener.enterExponent(self)
def exitRule(self, listener:ParseTreeListener):
if hasattr( listener, "exitExponent" ):
listener.exitExponent(self)
class MulDivContext(ExprContext):
def __init__(self, parser, ctx:ParserRuleContext): # actually a AutolevParser.ExprContext
super().__init__(parser)
self.copyFrom(ctx)
def expr(self, i:int=None):
if i is None:
return self.getTypedRuleContexts(AutolevParser.ExprContext)
else:
return self.getTypedRuleContext(AutolevParser.ExprContext,i)
def enterRule(self, listener:ParseTreeListener):
if hasattr( listener, "enterMulDiv" ):
listener.enterMulDiv(self)
def exitRule(self, listener:ParseTreeListener):
if hasattr( listener, "exitMulDiv" ):
listener.exitMulDiv(self)
class AddSubContext(ExprContext):
def __init__(self, parser, ctx:ParserRuleContext): # actually a AutolevParser.ExprContext
super().__init__(parser)
self.copyFrom(ctx)
def expr(self, i:int=None):
if i is None:
return self.getTypedRuleContexts(AutolevParser.ExprContext)
else:
return self.getTypedRuleContext(AutolevParser.ExprContext,i)
def enterRule(self, listener:ParseTreeListener):
if hasattr( listener, "enterAddSub" ):
listener.enterAddSub(self)
def exitRule(self, listener:ParseTreeListener):
if hasattr( listener, "exitAddSub" ):
listener.exitAddSub(self)
class FloatContext(ExprContext):
def __init__(self, parser, ctx:ParserRuleContext): # actually a AutolevParser.ExprContext
super().__init__(parser)
self.copyFrom(ctx)
def FLOAT(self):
return self.getToken(AutolevParser.FLOAT, 0)
def enterRule(self, listener:ParseTreeListener):
if hasattr( listener, "enterFloat" ):
listener.enterFloat(self)
def exitRule(self, listener:ParseTreeListener):
if hasattr( listener, "exitFloat" ):
listener.exitFloat(self)
class IntContext(ExprContext):
def __init__(self, parser, ctx:ParserRuleContext): # actually a AutolevParser.ExprContext
super().__init__(parser)
self.copyFrom(ctx)
def INT(self):
return self.getToken(AutolevParser.INT, 0)
def enterRule(self, listener:ParseTreeListener):
if hasattr( listener, "enterInt" ):
listener.enterInt(self)
def exitRule(self, listener:ParseTreeListener):
if hasattr( listener, "exitInt" ):
listener.exitInt(self)
class IdEqualsExprContext(ExprContext):
def __init__(self, parser, ctx:ParserRuleContext): # actually a AutolevParser.ExprContext
super().__init__(parser)
self.copyFrom(ctx)
def expr(self, i:int=None):
if i is None:
return self.getTypedRuleContexts(AutolevParser.ExprContext)
else:
return self.getTypedRuleContext(AutolevParser.ExprContext,i)
def enterRule(self, listener:ParseTreeListener):
if hasattr( listener, "enterIdEqualsExpr" ):
listener.enterIdEqualsExpr(self)
def exitRule(self, listener:ParseTreeListener):
if hasattr( listener, "exitIdEqualsExpr" ):
listener.exitIdEqualsExpr(self)
class NegativeOneContext(ExprContext):
def __init__(self, parser, ctx:ParserRuleContext): # actually a AutolevParser.ExprContext
super().__init__(parser)
self.copyFrom(ctx)
def expr(self):
return self.getTypedRuleContext(AutolevParser.ExprContext,0)
def enterRule(self, listener:ParseTreeListener):
if hasattr( listener, "enterNegativeOne" ):
listener.enterNegativeOne(self)
def exitRule(self, listener:ParseTreeListener):
if hasattr( listener, "exitNegativeOne" ):
listener.exitNegativeOne(self)
class FunctionContext(ExprContext):
def __init__(self, parser, ctx:ParserRuleContext): # actually a AutolevParser.ExprContext
super().__init__(parser)
self.copyFrom(ctx)
def functionCall(self):
return self.getTypedRuleContext(AutolevParser.FunctionCallContext,0)
def enterRule(self, listener:ParseTreeListener):
if hasattr( listener, "enterFunction" ):
listener.enterFunction(self)
def exitRule(self, listener:ParseTreeListener):
if hasattr( listener, "exitFunction" ):
listener.exitFunction(self)
class RangessContext(ExprContext):
def __init__(self, parser, ctx:ParserRuleContext): # actually a AutolevParser.ExprContext
super().__init__(parser)
self.copyFrom(ctx)
def ranges(self):
return self.getTypedRuleContext(AutolevParser.RangesContext,0)
def ID(self):
return self.getToken(AutolevParser.ID, 0)
def enterRule(self, listener:ParseTreeListener):
if hasattr( listener, "enterRangess" ):
listener.enterRangess(self)
def exitRule(self, listener:ParseTreeListener):
if hasattr( listener, "exitRangess" ):
listener.exitRangess(self)
class ColonContext(ExprContext):
def __init__(self, parser, ctx:ParserRuleContext): # actually a AutolevParser.ExprContext
super().__init__(parser)
self.copyFrom(ctx)
def expr(self, i:int=None):
if i is None:
return self.getTypedRuleContexts(AutolevParser.ExprContext)
else:
return self.getTypedRuleContext(AutolevParser.ExprContext,i)
def enterRule(self, listener:ParseTreeListener):
if hasattr( listener, "enterColon" ):
listener.enterColon(self)
def exitRule(self, listener:ParseTreeListener):
if hasattr( listener, "exitColon" ):
listener.exitColon(self)
class IdContext(ExprContext):
def __init__(self, parser, ctx:ParserRuleContext): # actually a AutolevParser.ExprContext
super().__init__(parser)
self.copyFrom(ctx)
def ID(self):
return self.getToken(AutolevParser.ID, 0)
def enterRule(self, listener:ParseTreeListener):
if hasattr( listener, "enterId" ):
listener.enterId(self)
def exitRule(self, listener:ParseTreeListener):
if hasattr( listener, "exitId" ):
listener.exitId(self)
class ExpContext(ExprContext):
def __init__(self, parser, ctx:ParserRuleContext): # actually a AutolevParser.ExprContext
super().__init__(parser)
self.copyFrom(ctx)
def EXP(self):
return self.getToken(AutolevParser.EXP, 0)
def enterRule(self, listener:ParseTreeListener):
if hasattr( listener, "enterExp" ):
listener.enterExp(self)
def exitRule(self, listener:ParseTreeListener):
if hasattr( listener, "exitExp" ):
listener.exitExp(self)
class MatricesContext(ExprContext):
def __init__(self, parser, ctx:ParserRuleContext): # actually a AutolevParser.ExprContext
super().__init__(parser)
self.copyFrom(ctx)
def matrix(self):
return self.getTypedRuleContext(AutolevParser.MatrixContext,0)
def enterRule(self, listener:ParseTreeListener):
if hasattr( listener, "enterMatrices" ):
listener.enterMatrices(self)
def exitRule(self, listener:ParseTreeListener):
if hasattr( listener, "exitMatrices" ):
listener.exitMatrices(self)
class IndexingContext(ExprContext):
def __init__(self, parser, ctx:ParserRuleContext): # actually a AutolevParser.ExprContext
super().__init__(parser)
self.copyFrom(ctx)
def ID(self):
return self.getToken(AutolevParser.ID, 0)
def expr(self, i:int=None):
if i is None:
return self.getTypedRuleContexts(AutolevParser.ExprContext)
else:
return self.getTypedRuleContext(AutolevParser.ExprContext,i)
def enterRule(self, listener:ParseTreeListener):
if hasattr( listener, "enterIndexing" ):
listener.enterIndexing(self)
def exitRule(self, listener:ParseTreeListener):
if hasattr( listener, "exitIndexing" ):
listener.exitIndexing(self)
def expr(self, _p:int=0):
_parentctx = self._ctx
_parentState = self.state
localctx = AutolevParser.ExprContext(self, self._ctx, _parentState)
_prevctx = localctx
_startState = 54
self.enterRecursionRule(localctx, 54, self.RULE_expr, _p)
self._la = 0 # Token type
try:
self.enterOuterAlt(localctx, 1)
self.state = 408
self._errHandler.sync(self)
la_ = self._interp.adaptivePredict(self._input,47,self._ctx)
if la_ == 1:
localctx = AutolevParser.ExpContext(self, localctx)
self._ctx = localctx
_prevctx = localctx
self.state = 367
self.match(AutolevParser.EXP)
pass
elif la_ == 2:
localctx = AutolevParser.NegativeOneContext(self, localctx)
self._ctx = localctx
_prevctx = localctx
self.state = 368
self.match(AutolevParser.T__17)
self.state = 369
self.expr(12)
pass
elif la_ == 3:
localctx = AutolevParser.FloatContext(self, localctx)
self._ctx = localctx
_prevctx = localctx
self.state = 370
self.match(AutolevParser.FLOAT)
pass
elif la_ == 4:
localctx = AutolevParser.IntContext(self, localctx)
self._ctx = localctx
_prevctx = localctx
self.state = 371
self.match(AutolevParser.INT)
pass
elif la_ == 5:
localctx = AutolevParser.IdContext(self, localctx)
self._ctx = localctx
_prevctx = localctx
self.state = 372
self.match(AutolevParser.ID)
self.state = 376
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input,43,self._ctx)
while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:
if _alt==1:
self.state = 373
self.match(AutolevParser.T__10)
self.state = 378
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input,43,self._ctx)
pass
elif la_ == 6:
localctx = AutolevParser.VectorOrDyadicContext(self, localctx)
self._ctx = localctx
_prevctx = localctx
self.state = 379
self.vec()
pass
elif la_ == 7:
localctx = AutolevParser.IndexingContext(self, localctx)
self._ctx = localctx
_prevctx = localctx
self.state = 380
self.match(AutolevParser.ID)
self.state = 381
self.match(AutolevParser.T__0)
self.state = 382
self.expr(0)
self.state = 387
self._errHandler.sync(self)
_la = self._input.LA(1)
while _la==AutolevParser.T__9:
self.state = 383
self.match(AutolevParser.T__9)
self.state = 384
self.expr(0)
self.state = 389
self._errHandler.sync(self)
_la = self._input.LA(1)
self.state = 390
self.match(AutolevParser.T__1)
pass
elif la_ == 8:
localctx = AutolevParser.FunctionContext(self, localctx)
self._ctx = localctx
_prevctx = localctx
self.state = 392
self.functionCall()
pass
elif la_ == 9:
localctx = AutolevParser.MatricesContext(self, localctx)
self._ctx = localctx
_prevctx = localctx
self.state = 393
self.matrix()
pass
elif la_ == 10:
localctx = AutolevParser.ParensContext(self, localctx)
self._ctx = localctx
_prevctx = localctx
self.state = 394
self.match(AutolevParser.T__11)
self.state = 395
self.expr(0)
self.state = 396
self.match(AutolevParser.T__12)
pass
elif la_ == 11:
localctx = AutolevParser.RangessContext(self, localctx)
self._ctx = localctx
_prevctx = localctx
self.state = 399
self._errHandler.sync(self)
_la = self._input.LA(1)
if _la==AutolevParser.ID:
self.state = 398
self.match(AutolevParser.ID)
self.state = 401
self.ranges()
self.state = 405
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input,46,self._ctx)
while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:
if _alt==1:
self.state = 402
self.match(AutolevParser.T__10)
self.state = 407
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input,46,self._ctx)
pass
self._ctx.stop = self._input.LT(-1)
self.state = 427
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input,49,self._ctx)
while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:
if _alt==1:
if self._parseListeners is not None:
self.triggerExitRuleEvent()
_prevctx = localctx
self.state = 425
self._errHandler.sync(self)
la_ = self._interp.adaptivePredict(self._input,48,self._ctx)
if la_ == 1:
localctx = AutolevParser.ExponentContext(self, AutolevParser.ExprContext(self, _parentctx, _parentState))
self.pushNewRecursionContext(localctx, _startState, self.RULE_expr)
self.state = 410
if not self.precpred(self._ctx, 16):
from antlr4.error.Errors import FailedPredicateException
raise FailedPredicateException(self, "self.precpred(self._ctx, 16)")
self.state = 411
self.match(AutolevParser.T__23)
self.state = 412
self.expr(17)
pass
elif la_ == 2:
localctx = AutolevParser.MulDivContext(self, AutolevParser.ExprContext(self, _parentctx, _parentState))
self.pushNewRecursionContext(localctx, _startState, self.RULE_expr)
self.state = 413
if not self.precpred(self._ctx, 15):
from antlr4.error.Errors import FailedPredicateException
raise FailedPredicateException(self, "self.precpred(self._ctx, 15)")
self.state = 414
_la = self._input.LA(1)
if not(_la==AutolevParser.T__24 or _la==AutolevParser.T__25):
self._errHandler.recoverInline(self)
else:
self._errHandler.reportMatch(self)
self.consume()
self.state = 415
self.expr(16)
pass
elif la_ == 3:
localctx = AutolevParser.AddSubContext(self, AutolevParser.ExprContext(self, _parentctx, _parentState))
self.pushNewRecursionContext(localctx, _startState, self.RULE_expr)
self.state = 416
if not self.precpred(self._ctx, 14):
from antlr4.error.Errors import FailedPredicateException
raise FailedPredicateException(self, "self.precpred(self._ctx, 14)")
self.state = 417
_la = self._input.LA(1)
if not(_la==AutolevParser.T__16 or _la==AutolevParser.T__17):
self._errHandler.recoverInline(self)
else:
self._errHandler.reportMatch(self)
self.consume()
self.state = 418
self.expr(15)
pass
elif la_ == 4:
localctx = AutolevParser.IdEqualsExprContext(self, AutolevParser.ExprContext(self, _parentctx, _parentState))
self.pushNewRecursionContext(localctx, _startState, self.RULE_expr)
self.state = 419
if not self.precpred(self._ctx, 3):
from antlr4.error.Errors import FailedPredicateException
raise FailedPredicateException(self, "self.precpred(self._ctx, 3)")
self.state = 420
self.match(AutolevParser.T__2)
self.state = 421
self.expr(4)
pass
elif la_ == 5:
localctx = AutolevParser.ColonContext(self, AutolevParser.ExprContext(self, _parentctx, _parentState))
self.pushNewRecursionContext(localctx, _startState, self.RULE_expr)
self.state = 422
if not self.precpred(self._ctx, 2):
from antlr4.error.Errors import FailedPredicateException
raise FailedPredicateException(self, "self.precpred(self._ctx, 2)")
self.state = 423
self.match(AutolevParser.T__15)
self.state = 424
self.expr(3)
pass
self.state = 429
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input,49,self._ctx)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.unrollRecursionContexts(_parentctx)
return localctx
def sempred(self, localctx:RuleContext, ruleIndex:int, predIndex:int):
if self._predicates == None:
self._predicates = dict()
self._predicates[27] = self.expr_sempred
pred = self._predicates.get(ruleIndex, None)
if pred is None:
raise Exception("No predicate with index:" + str(ruleIndex))
else:
return pred(localctx, predIndex)
def expr_sempred(self, localctx:ExprContext, predIndex:int):
if predIndex == 0:
return self.precpred(self._ctx, 16)
if predIndex == 1:
return self.precpred(self._ctx, 15)
if predIndex == 2:
return self.precpred(self._ctx, 14)
if predIndex == 3:
return self.precpred(self._ctx, 3)
if predIndex == 4:
return self.precpred(self._ctx, 2)
|
4c06fbf6c7a7a2b12ca182c22f051af3083c014087ce6999eed2dd8b45c635a1 | # *** GENERATED BY `setup.py antlr`, DO NOT EDIT BY HAND ***
#
# Generated from ../LaTeX.g4, derived from latex2sympy
# latex2sympy is licensed under the MIT license
# https://github.com/augustt198/latex2sympy/blob/master/LICENSE.txt
#
# Generated with antlr4
# antlr4 is licensed under the BSD-3-Clause License
# https://github.com/antlr/antlr4/blob/master/LICENSE.txt
|
33d000b76803a3e514d45899be129fc5c75eb7d8154bcb5127d00791c0a9e2cb | # *** GENERATED BY `setup.py antlr`, DO NOT EDIT BY HAND ***
#
# Generated from ../LaTeX.g4, derived from latex2sympy
# latex2sympy is licensed under the MIT license
# https://github.com/augustt198/latex2sympy/blob/master/LICENSE.txt
#
# Generated with antlr4
# antlr4 is licensed under the BSD-3-Clause License
# https://github.com/antlr/antlr4/blob/master/LICENSE.txt
from antlr4 import *
from io import StringIO
import sys
if sys.version_info[1] > 5:
from typing import TextIO
else:
from typing.io import TextIO
def serializedATN():
return [
4,0,91,911,6,-1,2,0,7,0,2,1,7,1,2,2,7,2,2,3,7,3,2,4,7,4,2,5,7,5,
2,6,7,6,2,7,7,7,2,8,7,8,2,9,7,9,2,10,7,10,2,11,7,11,2,12,7,12,2,
13,7,13,2,14,7,14,2,15,7,15,2,16,7,16,2,17,7,17,2,18,7,18,2,19,7,
19,2,20,7,20,2,21,7,21,2,22,7,22,2,23,7,23,2,24,7,24,2,25,7,25,2,
26,7,26,2,27,7,27,2,28,7,28,2,29,7,29,2,30,7,30,2,31,7,31,2,32,7,
32,2,33,7,33,2,34,7,34,2,35,7,35,2,36,7,36,2,37,7,37,2,38,7,38,2,
39,7,39,2,40,7,40,2,41,7,41,2,42,7,42,2,43,7,43,2,44,7,44,2,45,7,
45,2,46,7,46,2,47,7,47,2,48,7,48,2,49,7,49,2,50,7,50,2,51,7,51,2,
52,7,52,2,53,7,53,2,54,7,54,2,55,7,55,2,56,7,56,2,57,7,57,2,58,7,
58,2,59,7,59,2,60,7,60,2,61,7,61,2,62,7,62,2,63,7,63,2,64,7,64,2,
65,7,65,2,66,7,66,2,67,7,67,2,68,7,68,2,69,7,69,2,70,7,70,2,71,7,
71,2,72,7,72,2,73,7,73,2,74,7,74,2,75,7,75,2,76,7,76,2,77,7,77,2,
78,7,78,2,79,7,79,2,80,7,80,2,81,7,81,2,82,7,82,2,83,7,83,2,84,7,
84,2,85,7,85,2,86,7,86,2,87,7,87,2,88,7,88,2,89,7,89,2,90,7,90,2,
91,7,91,1,0,1,0,1,1,1,1,1,2,4,2,191,8,2,11,2,12,2,192,1,2,1,2,1,
3,1,3,1,3,1,3,1,3,1,3,1,3,1,3,1,3,1,3,1,3,1,3,3,3,209,8,3,1,3,1,
3,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,3,4,224,8,4,1,4,1,
4,1,5,1,5,1,5,1,5,1,5,1,5,1,5,1,5,1,5,1,5,1,5,1,5,1,5,3,5,241,8,
5,1,5,1,5,1,6,1,6,1,6,1,6,1,6,1,6,1,6,1,6,1,7,1,7,1,7,1,7,1,7,1,
7,1,7,1,7,1,7,1,8,1,8,1,8,1,8,1,8,1,8,1,8,1,8,1,8,1,8,1,8,1,8,1,
8,1,8,1,8,3,8,277,8,8,1,8,1,8,1,9,1,9,1,9,1,9,1,9,1,9,1,9,1,9,1,
9,1,9,1,9,1,9,1,9,1,9,1,9,1,10,1,10,1,10,1,10,1,10,1,10,1,10,1,10,
1,10,1,10,1,10,1,10,1,10,1,10,1,10,1,10,1,10,1,11,1,11,1,11,1,11,
1,11,1,11,1,11,1,11,1,12,1,12,1,12,1,12,1,12,1,12,1,12,1,12,1,12,
1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,
1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,
1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,
1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,1,13,3,13,
381,8,13,1,13,1,13,1,14,1,14,1,15,1,15,1,16,1,16,1,17,1,17,1,18,
1,18,1,19,1,19,1,20,1,20,1,21,1,21,1,22,1,22,1,22,1,23,1,23,1,23,
1,24,1,24,1,25,1,25,1,26,1,26,1,27,1,27,1,27,1,27,1,27,1,27,1,27,
1,27,1,28,1,28,1,28,1,28,1,28,1,28,1,28,1,29,1,29,1,29,1,29,1,29,
1,29,1,29,1,29,1,30,1,30,1,30,1,30,1,30,1,30,1,30,1,30,1,31,1,31,
1,31,1,31,1,31,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,
1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,
1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,
1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,
1,32,1,32,1,32,1,32,1,32,1,32,3,32,504,8,32,1,33,1,33,1,33,1,33,
1,33,1,33,1,33,1,33,1,33,1,33,1,33,1,33,1,33,1,33,1,33,3,33,521,
8,33,1,34,1,34,1,34,1,34,1,34,1,35,1,35,1,35,1,35,1,35,1,35,1,36,
1,36,1,36,1,36,1,36,1,37,1,37,1,37,1,37,1,37,1,38,1,38,1,38,1,38,
1,39,1,39,1,39,1,39,1,40,1,40,1,40,1,40,1,40,1,41,1,41,1,41,1,41,
1,41,1,42,1,42,1,42,1,42,1,42,1,43,1,43,1,43,1,43,1,43,1,44,1,44,
1,44,1,44,1,44,1,45,1,45,1,45,1,45,1,45,1,46,1,46,1,46,1,46,1,46,
1,46,1,46,1,46,1,47,1,47,1,47,1,47,1,47,1,47,1,47,1,47,1,48,1,48,
1,48,1,48,1,48,1,48,1,48,1,48,1,49,1,49,1,49,1,49,1,49,1,49,1,49,
1,49,1,50,1,50,1,50,1,50,1,50,1,50,1,50,1,50,1,51,1,51,1,51,1,51,
1,51,1,51,1,51,1,51,1,52,1,52,1,52,1,52,1,52,1,52,1,53,1,53,1,53,
1,53,1,53,1,53,1,54,1,54,1,54,1,54,1,54,1,54,1,55,1,55,1,55,1,55,
1,55,1,55,1,55,1,55,1,56,1,56,1,56,1,56,1,56,1,56,1,56,1,56,1,57,
1,57,1,57,1,57,1,57,1,57,1,57,1,57,1,58,1,58,1,58,1,58,1,58,1,58,
1,58,1,58,1,59,1,59,1,59,1,59,1,59,1,59,1,59,1,59,1,60,1,60,1,60,
1,60,1,60,1,60,1,60,1,61,1,61,1,61,1,61,1,61,1,61,1,61,1,62,1,62,
1,62,1,62,1,62,1,62,1,63,1,63,1,63,1,63,1,63,1,63,1,63,1,63,1,63,
1,63,1,64,1,64,1,64,1,64,1,64,1,64,1,64,1,65,1,65,1,65,1,65,1,65,
1,65,1,66,1,66,1,66,1,66,1,66,1,67,1,67,1,67,1,67,1,67,1,67,1,67,
1,67,1,67,1,67,1,67,1,67,1,67,1,67,1,67,1,67,1,67,3,67,753,8,67,
1,68,1,68,1,68,1,68,1,68,1,68,1,68,1,69,1,69,1,69,1,69,1,69,1,69,
1,69,1,69,1,70,1,70,1,70,1,70,1,70,1,70,1,70,1,70,1,71,1,71,1,71,
1,71,1,71,1,71,1,71,1,71,1,72,1,72,1,73,1,73,1,74,1,74,1,75,1,75,
1,76,1,76,5,76,796,8,76,10,76,12,76,799,9,76,1,76,1,76,1,76,4,76,
804,8,76,11,76,12,76,805,3,76,808,8,76,1,77,1,77,1,78,1,78,1,79,
1,79,5,79,816,8,79,10,79,12,79,819,9,79,3,79,821,8,79,1,79,1,79,
1,79,5,79,826,8,79,10,79,12,79,829,9,79,1,79,3,79,832,8,79,3,79,
834,8,79,1,80,1,80,1,80,1,80,1,80,1,81,1,81,1,82,1,82,1,82,1,82,
1,82,1,82,1,82,1,82,1,82,3,82,852,8,82,1,83,1,83,1,83,1,83,1,83,
1,83,1,84,1,84,1,84,1,84,1,84,1,84,1,84,1,84,1,84,1,84,1,85,1,85,
1,86,1,86,1,86,1,86,1,86,1,86,1,86,1,86,1,86,3,86,881,8,86,1,87,
1,87,1,87,1,87,1,87,1,87,1,88,1,88,1,88,1,88,1,88,1,88,1,88,1,88,
1,88,1,88,1,89,1,89,1,90,4,90,902,8,90,11,90,12,90,903,1,91,1,91,
4,91,908,8,91,11,91,12,91,909,3,797,817,827,0,92,1,1,3,2,5,3,7,4,
9,5,11,6,13,7,15,8,17,9,19,10,21,11,23,12,25,13,27,14,29,15,31,16,
33,17,35,18,37,19,39,20,41,21,43,22,45,23,47,24,49,25,51,26,53,27,
55,28,57,29,59,30,61,31,63,32,65,33,67,34,69,35,71,36,73,37,75,38,
77,39,79,40,81,41,83,42,85,43,87,44,89,45,91,46,93,47,95,48,97,49,
99,50,101,51,103,52,105,53,107,54,109,55,111,56,113,57,115,58,117,
59,119,60,121,61,123,62,125,63,127,64,129,65,131,66,133,67,135,68,
137,69,139,70,141,71,143,72,145,73,147,74,149,75,151,0,153,76,155,
77,157,78,159,79,161,80,163,81,165,82,167,83,169,84,171,85,173,86,
175,87,177,88,179,89,181,90,183,91,1,0,3,3,0,9,10,13,13,32,32,2,
0,65,90,97,122,1,0,48,57,949,0,1,1,0,0,0,0,3,1,0,0,0,0,5,1,0,0,0,
0,7,1,0,0,0,0,9,1,0,0,0,0,11,1,0,0,0,0,13,1,0,0,0,0,15,1,0,0,0,0,
17,1,0,0,0,0,19,1,0,0,0,0,21,1,0,0,0,0,23,1,0,0,0,0,25,1,0,0,0,0,
27,1,0,0,0,0,29,1,0,0,0,0,31,1,0,0,0,0,33,1,0,0,0,0,35,1,0,0,0,0,
37,1,0,0,0,0,39,1,0,0,0,0,41,1,0,0,0,0,43,1,0,0,0,0,45,1,0,0,0,0,
47,1,0,0,0,0,49,1,0,0,0,0,51,1,0,0,0,0,53,1,0,0,0,0,55,1,0,0,0,0,
57,1,0,0,0,0,59,1,0,0,0,0,61,1,0,0,0,0,63,1,0,0,0,0,65,1,0,0,0,0,
67,1,0,0,0,0,69,1,0,0,0,0,71,1,0,0,0,0,73,1,0,0,0,0,75,1,0,0,0,0,
77,1,0,0,0,0,79,1,0,0,0,0,81,1,0,0,0,0,83,1,0,0,0,0,85,1,0,0,0,0,
87,1,0,0,0,0,89,1,0,0,0,0,91,1,0,0,0,0,93,1,0,0,0,0,95,1,0,0,0,0,
97,1,0,0,0,0,99,1,0,0,0,0,101,1,0,0,0,0,103,1,0,0,0,0,105,1,0,0,
0,0,107,1,0,0,0,0,109,1,0,0,0,0,111,1,0,0,0,0,113,1,0,0,0,0,115,
1,0,0,0,0,117,1,0,0,0,0,119,1,0,0,0,0,121,1,0,0,0,0,123,1,0,0,0,
0,125,1,0,0,0,0,127,1,0,0,0,0,129,1,0,0,0,0,131,1,0,0,0,0,133,1,
0,0,0,0,135,1,0,0,0,0,137,1,0,0,0,0,139,1,0,0,0,0,141,1,0,0,0,0,
143,1,0,0,0,0,145,1,0,0,0,0,147,1,0,0,0,0,149,1,0,0,0,0,153,1,0,
0,0,0,155,1,0,0,0,0,157,1,0,0,0,0,159,1,0,0,0,0,161,1,0,0,0,0,163,
1,0,0,0,0,165,1,0,0,0,0,167,1,0,0,0,0,169,1,0,0,0,0,171,1,0,0,0,
0,173,1,0,0,0,0,175,1,0,0,0,0,177,1,0,0,0,0,179,1,0,0,0,0,181,1,
0,0,0,0,183,1,0,0,0,1,185,1,0,0,0,3,187,1,0,0,0,5,190,1,0,0,0,7,
208,1,0,0,0,9,223,1,0,0,0,11,240,1,0,0,0,13,244,1,0,0,0,15,252,1,
0,0,0,17,276,1,0,0,0,19,280,1,0,0,0,21,295,1,0,0,0,23,312,1,0,0,
0,25,320,1,0,0,0,27,380,1,0,0,0,29,384,1,0,0,0,31,386,1,0,0,0,33,
388,1,0,0,0,35,390,1,0,0,0,37,392,1,0,0,0,39,394,1,0,0,0,41,396,
1,0,0,0,43,398,1,0,0,0,45,400,1,0,0,0,47,403,1,0,0,0,49,406,1,0,
0,0,51,408,1,0,0,0,53,410,1,0,0,0,55,412,1,0,0,0,57,420,1,0,0,0,
59,427,1,0,0,0,61,435,1,0,0,0,63,443,1,0,0,0,65,503,1,0,0,0,67,520,
1,0,0,0,69,522,1,0,0,0,71,527,1,0,0,0,73,533,1,0,0,0,75,538,1,0,
0,0,77,543,1,0,0,0,79,547,1,0,0,0,81,551,1,0,0,0,83,556,1,0,0,0,
85,561,1,0,0,0,87,566,1,0,0,0,89,571,1,0,0,0,91,576,1,0,0,0,93,581,
1,0,0,0,95,589,1,0,0,0,97,597,1,0,0,0,99,605,1,0,0,0,101,613,1,0,
0,0,103,621,1,0,0,0,105,629,1,0,0,0,107,635,1,0,0,0,109,641,1,0,
0,0,111,647,1,0,0,0,113,655,1,0,0,0,115,663,1,0,0,0,117,671,1,0,
0,0,119,679,1,0,0,0,121,687,1,0,0,0,123,694,1,0,0,0,125,701,1,0,
0,0,127,707,1,0,0,0,129,717,1,0,0,0,131,724,1,0,0,0,133,730,1,0,
0,0,135,752,1,0,0,0,137,754,1,0,0,0,139,761,1,0,0,0,141,769,1,0,
0,0,143,777,1,0,0,0,145,785,1,0,0,0,147,787,1,0,0,0,149,789,1,0,
0,0,151,791,1,0,0,0,153,793,1,0,0,0,155,809,1,0,0,0,157,811,1,0,
0,0,159,833,1,0,0,0,161,835,1,0,0,0,163,840,1,0,0,0,165,851,1,0,
0,0,167,853,1,0,0,0,169,859,1,0,0,0,171,869,1,0,0,0,173,880,1,0,
0,0,175,882,1,0,0,0,177,888,1,0,0,0,179,898,1,0,0,0,181,901,1,0,
0,0,183,905,1,0,0,0,185,186,5,44,0,0,186,2,1,0,0,0,187,188,5,46,
0,0,188,4,1,0,0,0,189,191,7,0,0,0,190,189,1,0,0,0,191,192,1,0,0,
0,192,190,1,0,0,0,192,193,1,0,0,0,193,194,1,0,0,0,194,195,6,2,0,
0,195,6,1,0,0,0,196,197,5,92,0,0,197,209,5,44,0,0,198,199,5,92,0,
0,199,200,5,116,0,0,200,201,5,104,0,0,201,202,5,105,0,0,202,203,
5,110,0,0,203,204,5,115,0,0,204,205,5,112,0,0,205,206,5,97,0,0,206,
207,5,99,0,0,207,209,5,101,0,0,208,196,1,0,0,0,208,198,1,0,0,0,209,
210,1,0,0,0,210,211,6,3,0,0,211,8,1,0,0,0,212,213,5,92,0,0,213,224,
5,58,0,0,214,215,5,92,0,0,215,216,5,109,0,0,216,217,5,101,0,0,217,
218,5,100,0,0,218,219,5,115,0,0,219,220,5,112,0,0,220,221,5,97,0,
0,221,222,5,99,0,0,222,224,5,101,0,0,223,212,1,0,0,0,223,214,1,0,
0,0,224,225,1,0,0,0,225,226,6,4,0,0,226,10,1,0,0,0,227,228,5,92,
0,0,228,241,5,59,0,0,229,230,5,92,0,0,230,231,5,116,0,0,231,232,
5,104,0,0,232,233,5,105,0,0,233,234,5,99,0,0,234,235,5,107,0,0,235,
236,5,115,0,0,236,237,5,112,0,0,237,238,5,97,0,0,238,239,5,99,0,
0,239,241,5,101,0,0,240,227,1,0,0,0,240,229,1,0,0,0,241,242,1,0,
0,0,242,243,6,5,0,0,243,12,1,0,0,0,244,245,5,92,0,0,245,246,5,113,
0,0,246,247,5,117,0,0,247,248,5,97,0,0,248,249,5,100,0,0,249,250,
1,0,0,0,250,251,6,6,0,0,251,14,1,0,0,0,252,253,5,92,0,0,253,254,
5,113,0,0,254,255,5,113,0,0,255,256,5,117,0,0,256,257,5,97,0,0,257,
258,5,100,0,0,258,259,1,0,0,0,259,260,6,7,0,0,260,16,1,0,0,0,261,
262,5,92,0,0,262,277,5,33,0,0,263,264,5,92,0,0,264,265,5,110,0,0,
265,266,5,101,0,0,266,267,5,103,0,0,267,268,5,116,0,0,268,269,5,
104,0,0,269,270,5,105,0,0,270,271,5,110,0,0,271,272,5,115,0,0,272,
273,5,112,0,0,273,274,5,97,0,0,274,275,5,99,0,0,275,277,5,101,0,
0,276,261,1,0,0,0,276,263,1,0,0,0,277,278,1,0,0,0,278,279,6,8,0,
0,279,18,1,0,0,0,280,281,5,92,0,0,281,282,5,110,0,0,282,283,5,101,
0,0,283,284,5,103,0,0,284,285,5,109,0,0,285,286,5,101,0,0,286,287,
5,100,0,0,287,288,5,115,0,0,288,289,5,112,0,0,289,290,5,97,0,0,290,
291,5,99,0,0,291,292,5,101,0,0,292,293,1,0,0,0,293,294,6,9,0,0,294,
20,1,0,0,0,295,296,5,92,0,0,296,297,5,110,0,0,297,298,5,101,0,0,
298,299,5,103,0,0,299,300,5,116,0,0,300,301,5,104,0,0,301,302,5,
105,0,0,302,303,5,99,0,0,303,304,5,107,0,0,304,305,5,115,0,0,305,
306,5,112,0,0,306,307,5,97,0,0,307,308,5,99,0,0,308,309,5,101,0,
0,309,310,1,0,0,0,310,311,6,10,0,0,311,22,1,0,0,0,312,313,5,92,0,
0,313,314,5,108,0,0,314,315,5,101,0,0,315,316,5,102,0,0,316,317,
5,116,0,0,317,318,1,0,0,0,318,319,6,11,0,0,319,24,1,0,0,0,320,321,
5,92,0,0,321,322,5,114,0,0,322,323,5,105,0,0,323,324,5,103,0,0,324,
325,5,104,0,0,325,326,5,116,0,0,326,327,1,0,0,0,327,328,6,12,0,0,
328,26,1,0,0,0,329,330,5,92,0,0,330,331,5,118,0,0,331,332,5,114,
0,0,332,333,5,117,0,0,333,334,5,108,0,0,334,381,5,101,0,0,335,336,
5,92,0,0,336,337,5,118,0,0,337,338,5,99,0,0,338,339,5,101,0,0,339,
340,5,110,0,0,340,341,5,116,0,0,341,342,5,101,0,0,342,381,5,114,
0,0,343,344,5,92,0,0,344,345,5,118,0,0,345,346,5,98,0,0,346,347,
5,111,0,0,347,381,5,120,0,0,348,349,5,92,0,0,349,350,5,118,0,0,350,
351,5,115,0,0,351,352,5,107,0,0,352,353,5,105,0,0,353,381,5,112,
0,0,354,355,5,92,0,0,355,356,5,118,0,0,356,357,5,115,0,0,357,358,
5,112,0,0,358,359,5,97,0,0,359,360,5,99,0,0,360,381,5,101,0,0,361,
362,5,92,0,0,362,363,5,104,0,0,363,364,5,102,0,0,364,365,5,105,0,
0,365,381,5,108,0,0,366,367,5,92,0,0,367,381,5,42,0,0,368,369,5,
92,0,0,369,381,5,45,0,0,370,371,5,92,0,0,371,381,5,46,0,0,372,373,
5,92,0,0,373,381,5,47,0,0,374,375,5,92,0,0,375,381,5,34,0,0,376,
377,5,92,0,0,377,381,5,40,0,0,378,379,5,92,0,0,379,381,5,61,0,0,
380,329,1,0,0,0,380,335,1,0,0,0,380,343,1,0,0,0,380,348,1,0,0,0,
380,354,1,0,0,0,380,361,1,0,0,0,380,366,1,0,0,0,380,368,1,0,0,0,
380,370,1,0,0,0,380,372,1,0,0,0,380,374,1,0,0,0,380,376,1,0,0,0,
380,378,1,0,0,0,381,382,1,0,0,0,382,383,6,13,0,0,383,28,1,0,0,0,
384,385,5,43,0,0,385,30,1,0,0,0,386,387,5,45,0,0,387,32,1,0,0,0,
388,389,5,42,0,0,389,34,1,0,0,0,390,391,5,47,0,0,391,36,1,0,0,0,
392,393,5,40,0,0,393,38,1,0,0,0,394,395,5,41,0,0,395,40,1,0,0,0,
396,397,5,123,0,0,397,42,1,0,0,0,398,399,5,125,0,0,399,44,1,0,0,
0,400,401,5,92,0,0,401,402,5,123,0,0,402,46,1,0,0,0,403,404,5,92,
0,0,404,405,5,125,0,0,405,48,1,0,0,0,406,407,5,91,0,0,407,50,1,0,
0,0,408,409,5,93,0,0,409,52,1,0,0,0,410,411,5,124,0,0,411,54,1,0,
0,0,412,413,5,92,0,0,413,414,5,114,0,0,414,415,5,105,0,0,415,416,
5,103,0,0,416,417,5,104,0,0,417,418,5,116,0,0,418,419,5,124,0,0,
419,56,1,0,0,0,420,421,5,92,0,0,421,422,5,108,0,0,422,423,5,101,
0,0,423,424,5,102,0,0,424,425,5,116,0,0,425,426,5,124,0,0,426,58,
1,0,0,0,427,428,5,92,0,0,428,429,5,108,0,0,429,430,5,97,0,0,430,
431,5,110,0,0,431,432,5,103,0,0,432,433,5,108,0,0,433,434,5,101,
0,0,434,60,1,0,0,0,435,436,5,92,0,0,436,437,5,114,0,0,437,438,5,
97,0,0,438,439,5,110,0,0,439,440,5,103,0,0,440,441,5,108,0,0,441,
442,5,101,0,0,442,62,1,0,0,0,443,444,5,92,0,0,444,445,5,108,0,0,
445,446,5,105,0,0,446,447,5,109,0,0,447,64,1,0,0,0,448,449,5,92,
0,0,449,450,5,116,0,0,450,504,5,111,0,0,451,452,5,92,0,0,452,453,
5,114,0,0,453,454,5,105,0,0,454,455,5,103,0,0,455,456,5,104,0,0,
456,457,5,116,0,0,457,458,5,97,0,0,458,459,5,114,0,0,459,460,5,114,
0,0,460,461,5,111,0,0,461,504,5,119,0,0,462,463,5,92,0,0,463,464,
5,82,0,0,464,465,5,105,0,0,465,466,5,103,0,0,466,467,5,104,0,0,467,
468,5,116,0,0,468,469,5,97,0,0,469,470,5,114,0,0,470,471,5,114,0,
0,471,472,5,111,0,0,472,504,5,119,0,0,473,474,5,92,0,0,474,475,5,
108,0,0,475,476,5,111,0,0,476,477,5,110,0,0,477,478,5,103,0,0,478,
479,5,114,0,0,479,480,5,105,0,0,480,481,5,103,0,0,481,482,5,104,
0,0,482,483,5,116,0,0,483,484,5,97,0,0,484,485,5,114,0,0,485,486,
5,114,0,0,486,487,5,111,0,0,487,504,5,119,0,0,488,489,5,92,0,0,489,
490,5,76,0,0,490,491,5,111,0,0,491,492,5,110,0,0,492,493,5,103,0,
0,493,494,5,114,0,0,494,495,5,105,0,0,495,496,5,103,0,0,496,497,
5,104,0,0,497,498,5,116,0,0,498,499,5,97,0,0,499,500,5,114,0,0,500,
501,5,114,0,0,501,502,5,111,0,0,502,504,5,119,0,0,503,448,1,0,0,
0,503,451,1,0,0,0,503,462,1,0,0,0,503,473,1,0,0,0,503,488,1,0,0,
0,504,66,1,0,0,0,505,506,5,92,0,0,506,507,5,105,0,0,507,508,5,110,
0,0,508,521,5,116,0,0,509,510,5,92,0,0,510,511,5,105,0,0,511,512,
5,110,0,0,512,513,5,116,0,0,513,514,5,92,0,0,514,515,5,108,0,0,515,
516,5,105,0,0,516,517,5,109,0,0,517,518,5,105,0,0,518,519,5,116,
0,0,519,521,5,115,0,0,520,505,1,0,0,0,520,509,1,0,0,0,521,68,1,0,
0,0,522,523,5,92,0,0,523,524,5,115,0,0,524,525,5,117,0,0,525,526,
5,109,0,0,526,70,1,0,0,0,527,528,5,92,0,0,528,529,5,112,0,0,529,
530,5,114,0,0,530,531,5,111,0,0,531,532,5,100,0,0,532,72,1,0,0,0,
533,534,5,92,0,0,534,535,5,101,0,0,535,536,5,120,0,0,536,537,5,112,
0,0,537,74,1,0,0,0,538,539,5,92,0,0,539,540,5,108,0,0,540,541,5,
111,0,0,541,542,5,103,0,0,542,76,1,0,0,0,543,544,5,92,0,0,544,545,
5,108,0,0,545,546,5,103,0,0,546,78,1,0,0,0,547,548,5,92,0,0,548,
549,5,108,0,0,549,550,5,110,0,0,550,80,1,0,0,0,551,552,5,92,0,0,
552,553,5,115,0,0,553,554,5,105,0,0,554,555,5,110,0,0,555,82,1,0,
0,0,556,557,5,92,0,0,557,558,5,99,0,0,558,559,5,111,0,0,559,560,
5,115,0,0,560,84,1,0,0,0,561,562,5,92,0,0,562,563,5,116,0,0,563,
564,5,97,0,0,564,565,5,110,0,0,565,86,1,0,0,0,566,567,5,92,0,0,567,
568,5,99,0,0,568,569,5,115,0,0,569,570,5,99,0,0,570,88,1,0,0,0,571,
572,5,92,0,0,572,573,5,115,0,0,573,574,5,101,0,0,574,575,5,99,0,
0,575,90,1,0,0,0,576,577,5,92,0,0,577,578,5,99,0,0,578,579,5,111,
0,0,579,580,5,116,0,0,580,92,1,0,0,0,581,582,5,92,0,0,582,583,5,
97,0,0,583,584,5,114,0,0,584,585,5,99,0,0,585,586,5,115,0,0,586,
587,5,105,0,0,587,588,5,110,0,0,588,94,1,0,0,0,589,590,5,92,0,0,
590,591,5,97,0,0,591,592,5,114,0,0,592,593,5,99,0,0,593,594,5,99,
0,0,594,595,5,111,0,0,595,596,5,115,0,0,596,96,1,0,0,0,597,598,5,
92,0,0,598,599,5,97,0,0,599,600,5,114,0,0,600,601,5,99,0,0,601,602,
5,116,0,0,602,603,5,97,0,0,603,604,5,110,0,0,604,98,1,0,0,0,605,
606,5,92,0,0,606,607,5,97,0,0,607,608,5,114,0,0,608,609,5,99,0,0,
609,610,5,99,0,0,610,611,5,115,0,0,611,612,5,99,0,0,612,100,1,0,
0,0,613,614,5,92,0,0,614,615,5,97,0,0,615,616,5,114,0,0,616,617,
5,99,0,0,617,618,5,115,0,0,618,619,5,101,0,0,619,620,5,99,0,0,620,
102,1,0,0,0,621,622,5,92,0,0,622,623,5,97,0,0,623,624,5,114,0,0,
624,625,5,99,0,0,625,626,5,99,0,0,626,627,5,111,0,0,627,628,5,116,
0,0,628,104,1,0,0,0,629,630,5,92,0,0,630,631,5,115,0,0,631,632,5,
105,0,0,632,633,5,110,0,0,633,634,5,104,0,0,634,106,1,0,0,0,635,
636,5,92,0,0,636,637,5,99,0,0,637,638,5,111,0,0,638,639,5,115,0,
0,639,640,5,104,0,0,640,108,1,0,0,0,641,642,5,92,0,0,642,643,5,116,
0,0,643,644,5,97,0,0,644,645,5,110,0,0,645,646,5,104,0,0,646,110,
1,0,0,0,647,648,5,92,0,0,648,649,5,97,0,0,649,650,5,114,0,0,650,
651,5,115,0,0,651,652,5,105,0,0,652,653,5,110,0,0,653,654,5,104,
0,0,654,112,1,0,0,0,655,656,5,92,0,0,656,657,5,97,0,0,657,658,5,
114,0,0,658,659,5,99,0,0,659,660,5,111,0,0,660,661,5,115,0,0,661,
662,5,104,0,0,662,114,1,0,0,0,663,664,5,92,0,0,664,665,5,97,0,0,
665,666,5,114,0,0,666,667,5,116,0,0,667,668,5,97,0,0,668,669,5,110,
0,0,669,670,5,104,0,0,670,116,1,0,0,0,671,672,5,92,0,0,672,673,5,
108,0,0,673,674,5,102,0,0,674,675,5,108,0,0,675,676,5,111,0,0,676,
677,5,111,0,0,677,678,5,114,0,0,678,118,1,0,0,0,679,680,5,92,0,0,
680,681,5,114,0,0,681,682,5,102,0,0,682,683,5,108,0,0,683,684,5,
111,0,0,684,685,5,111,0,0,685,686,5,114,0,0,686,120,1,0,0,0,687,
688,5,92,0,0,688,689,5,108,0,0,689,690,5,99,0,0,690,691,5,101,0,
0,691,692,5,105,0,0,692,693,5,108,0,0,693,122,1,0,0,0,694,695,5,
92,0,0,695,696,5,114,0,0,696,697,5,99,0,0,697,698,5,101,0,0,698,
699,5,105,0,0,699,700,5,108,0,0,700,124,1,0,0,0,701,702,5,92,0,0,
702,703,5,115,0,0,703,704,5,113,0,0,704,705,5,114,0,0,705,706,5,
116,0,0,706,126,1,0,0,0,707,708,5,92,0,0,708,709,5,111,0,0,709,710,
5,118,0,0,710,711,5,101,0,0,711,712,5,114,0,0,712,713,5,108,0,0,
713,714,5,105,0,0,714,715,5,110,0,0,715,716,5,101,0,0,716,128,1,
0,0,0,717,718,5,92,0,0,718,719,5,116,0,0,719,720,5,105,0,0,720,721,
5,109,0,0,721,722,5,101,0,0,722,723,5,115,0,0,723,130,1,0,0,0,724,
725,5,92,0,0,725,726,5,99,0,0,726,727,5,100,0,0,727,728,5,111,0,
0,728,729,5,116,0,0,729,132,1,0,0,0,730,731,5,92,0,0,731,732,5,100,
0,0,732,733,5,105,0,0,733,734,5,118,0,0,734,134,1,0,0,0,735,736,
5,92,0,0,736,737,5,102,0,0,737,738,5,114,0,0,738,739,5,97,0,0,739,
753,5,99,0,0,740,741,5,92,0,0,741,742,5,100,0,0,742,743,5,102,0,
0,743,744,5,114,0,0,744,745,5,97,0,0,745,753,5,99,0,0,746,747,5,
92,0,0,747,748,5,116,0,0,748,749,5,102,0,0,749,750,5,114,0,0,750,
751,5,97,0,0,751,753,5,99,0,0,752,735,1,0,0,0,752,740,1,0,0,0,752,
746,1,0,0,0,753,136,1,0,0,0,754,755,5,92,0,0,755,756,5,98,0,0,756,
757,5,105,0,0,757,758,5,110,0,0,758,759,5,111,0,0,759,760,5,109,
0,0,760,138,1,0,0,0,761,762,5,92,0,0,762,763,5,100,0,0,763,764,5,
98,0,0,764,765,5,105,0,0,765,766,5,110,0,0,766,767,5,111,0,0,767,
768,5,109,0,0,768,140,1,0,0,0,769,770,5,92,0,0,770,771,5,116,0,0,
771,772,5,98,0,0,772,773,5,105,0,0,773,774,5,110,0,0,774,775,5,111,
0,0,775,776,5,109,0,0,776,142,1,0,0,0,777,778,5,92,0,0,778,779,5,
109,0,0,779,780,5,97,0,0,780,781,5,116,0,0,781,782,5,104,0,0,782,
783,5,105,0,0,783,784,5,116,0,0,784,144,1,0,0,0,785,786,5,95,0,0,
786,146,1,0,0,0,787,788,5,94,0,0,788,148,1,0,0,0,789,790,5,58,0,
0,790,150,1,0,0,0,791,792,7,0,0,0,792,152,1,0,0,0,793,797,5,100,
0,0,794,796,3,151,75,0,795,794,1,0,0,0,796,799,1,0,0,0,797,798,1,
0,0,0,797,795,1,0,0,0,798,807,1,0,0,0,799,797,1,0,0,0,800,808,7,
1,0,0,801,803,5,92,0,0,802,804,7,1,0,0,803,802,1,0,0,0,804,805,1,
0,0,0,805,803,1,0,0,0,805,806,1,0,0,0,806,808,1,0,0,0,807,800,1,
0,0,0,807,801,1,0,0,0,808,154,1,0,0,0,809,810,7,1,0,0,810,156,1,
0,0,0,811,812,7,2,0,0,812,158,1,0,0,0,813,817,5,38,0,0,814,816,3,
151,75,0,815,814,1,0,0,0,816,819,1,0,0,0,817,818,1,0,0,0,817,815,
1,0,0,0,818,821,1,0,0,0,819,817,1,0,0,0,820,813,1,0,0,0,820,821,
1,0,0,0,821,822,1,0,0,0,822,834,5,61,0,0,823,831,5,61,0,0,824,826,
3,151,75,0,825,824,1,0,0,0,826,829,1,0,0,0,827,828,1,0,0,0,827,825,
1,0,0,0,828,830,1,0,0,0,829,827,1,0,0,0,830,832,5,38,0,0,831,827,
1,0,0,0,831,832,1,0,0,0,832,834,1,0,0,0,833,820,1,0,0,0,833,823,
1,0,0,0,834,160,1,0,0,0,835,836,5,92,0,0,836,837,5,110,0,0,837,838,
5,101,0,0,838,839,5,113,0,0,839,162,1,0,0,0,840,841,5,60,0,0,841,
164,1,0,0,0,842,843,5,92,0,0,843,844,5,108,0,0,844,845,5,101,0,0,
845,852,5,113,0,0,846,847,5,92,0,0,847,848,5,108,0,0,848,852,5,101,
0,0,849,852,3,167,83,0,850,852,3,169,84,0,851,842,1,0,0,0,851,846,
1,0,0,0,851,849,1,0,0,0,851,850,1,0,0,0,852,166,1,0,0,0,853,854,
5,92,0,0,854,855,5,108,0,0,855,856,5,101,0,0,856,857,5,113,0,0,857,
858,5,113,0,0,858,168,1,0,0,0,859,860,5,92,0,0,860,861,5,108,0,0,
861,862,5,101,0,0,862,863,5,113,0,0,863,864,5,115,0,0,864,865,5,
108,0,0,865,866,5,97,0,0,866,867,5,110,0,0,867,868,5,116,0,0,868,
170,1,0,0,0,869,870,5,62,0,0,870,172,1,0,0,0,871,872,5,92,0,0,872,
873,5,103,0,0,873,874,5,101,0,0,874,881,5,113,0,0,875,876,5,92,0,
0,876,877,5,103,0,0,877,881,5,101,0,0,878,881,3,175,87,0,879,881,
3,177,88,0,880,871,1,0,0,0,880,875,1,0,0,0,880,878,1,0,0,0,880,879,
1,0,0,0,881,174,1,0,0,0,882,883,5,92,0,0,883,884,5,103,0,0,884,885,
5,101,0,0,885,886,5,113,0,0,886,887,5,113,0,0,887,176,1,0,0,0,888,
889,5,92,0,0,889,890,5,103,0,0,890,891,5,101,0,0,891,892,5,113,0,
0,892,893,5,115,0,0,893,894,5,108,0,0,894,895,5,97,0,0,895,896,5,
110,0,0,896,897,5,116,0,0,897,178,1,0,0,0,898,899,5,33,0,0,899,180,
1,0,0,0,900,902,5,39,0,0,901,900,1,0,0,0,902,903,1,0,0,0,903,901,
1,0,0,0,903,904,1,0,0,0,904,182,1,0,0,0,905,907,5,92,0,0,906,908,
7,1,0,0,907,906,1,0,0,0,908,909,1,0,0,0,909,907,1,0,0,0,909,910,
1,0,0,0,910,184,1,0,0,0,22,0,192,208,223,240,276,380,503,520,752,
797,805,807,817,820,827,831,833,851,880,903,909,1,6,0,0
]
class LaTeXLexer(Lexer):
atn = ATNDeserializer().deserialize(serializedATN())
decisionsToDFA = [ DFA(ds, i) for i, ds in enumerate(atn.decisionToState) ]
T__0 = 1
T__1 = 2
WS = 3
THINSPACE = 4
MEDSPACE = 5
THICKSPACE = 6
QUAD = 7
QQUAD = 8
NEGTHINSPACE = 9
NEGMEDSPACE = 10
NEGTHICKSPACE = 11
CMD_LEFT = 12
CMD_RIGHT = 13
IGNORE = 14
ADD = 15
SUB = 16
MUL = 17
DIV = 18
L_PAREN = 19
R_PAREN = 20
L_BRACE = 21
R_BRACE = 22
L_BRACE_LITERAL = 23
R_BRACE_LITERAL = 24
L_BRACKET = 25
R_BRACKET = 26
BAR = 27
R_BAR = 28
L_BAR = 29
L_ANGLE = 30
R_ANGLE = 31
FUNC_LIM = 32
LIM_APPROACH_SYM = 33
FUNC_INT = 34
FUNC_SUM = 35
FUNC_PROD = 36
FUNC_EXP = 37
FUNC_LOG = 38
FUNC_LG = 39
FUNC_LN = 40
FUNC_SIN = 41
FUNC_COS = 42
FUNC_TAN = 43
FUNC_CSC = 44
FUNC_SEC = 45
FUNC_COT = 46
FUNC_ARCSIN = 47
FUNC_ARCCOS = 48
FUNC_ARCTAN = 49
FUNC_ARCCSC = 50
FUNC_ARCSEC = 51
FUNC_ARCCOT = 52
FUNC_SINH = 53
FUNC_COSH = 54
FUNC_TANH = 55
FUNC_ARSINH = 56
FUNC_ARCOSH = 57
FUNC_ARTANH = 58
L_FLOOR = 59
R_FLOOR = 60
L_CEIL = 61
R_CEIL = 62
FUNC_SQRT = 63
FUNC_OVERLINE = 64
CMD_TIMES = 65
CMD_CDOT = 66
CMD_DIV = 67
CMD_FRAC = 68
CMD_BINOM = 69
CMD_DBINOM = 70
CMD_TBINOM = 71
CMD_MATHIT = 72
UNDERSCORE = 73
CARET = 74
COLON = 75
DIFFERENTIAL = 76
LETTER = 77
DIGIT = 78
EQUAL = 79
NEQ = 80
LT = 81
LTE = 82
LTE_Q = 83
LTE_S = 84
GT = 85
GTE = 86
GTE_Q = 87
GTE_S = 88
BANG = 89
SINGLE_QUOTES = 90
SYMBOL = 91
channelNames = [ u"DEFAULT_TOKEN_CHANNEL", u"HIDDEN" ]
modeNames = [ "DEFAULT_MODE" ]
literalNames = [ "<INVALID>",
"','", "'.'", "'\\quad'", "'\\qquad'", "'\\negmedspace'", "'\\negthickspace'",
"'\\left'", "'\\right'", "'+'", "'-'", "'*'", "'/'", "'('",
"')'", "'{'", "'}'", "'\\{'", "'\\}'", "'['", "']'", "'|'",
"'\\right|'", "'\\left|'", "'\\langle'", "'\\rangle'", "'\\lim'",
"'\\sum'", "'\\prod'", "'\\exp'", "'\\log'", "'\\lg'", "'\\ln'",
"'\\sin'", "'\\cos'", "'\\tan'", "'\\csc'", "'\\sec'", "'\\cot'",
"'\\arcsin'", "'\\arccos'", "'\\arctan'", "'\\arccsc'", "'\\arcsec'",
"'\\arccot'", "'\\sinh'", "'\\cosh'", "'\\tanh'", "'\\arsinh'",
"'\\arcosh'", "'\\artanh'", "'\\lfloor'", "'\\rfloor'", "'\\lceil'",
"'\\rceil'", "'\\sqrt'", "'\\overline'", "'\\times'", "'\\cdot'",
"'\\div'", "'\\binom'", "'\\dbinom'", "'\\tbinom'", "'\\mathit'",
"'_'", "'^'", "':'", "'\\neq'", "'<'", "'\\leqq'", "'\\leqslant'",
"'>'", "'\\geqq'", "'\\geqslant'", "'!'" ]
symbolicNames = [ "<INVALID>",
"WS", "THINSPACE", "MEDSPACE", "THICKSPACE", "QUAD", "QQUAD",
"NEGTHINSPACE", "NEGMEDSPACE", "NEGTHICKSPACE", "CMD_LEFT",
"CMD_RIGHT", "IGNORE", "ADD", "SUB", "MUL", "DIV", "L_PAREN",
"R_PAREN", "L_BRACE", "R_BRACE", "L_BRACE_LITERAL", "R_BRACE_LITERAL",
"L_BRACKET", "R_BRACKET", "BAR", "R_BAR", "L_BAR", "L_ANGLE",
"R_ANGLE", "FUNC_LIM", "LIM_APPROACH_SYM", "FUNC_INT", "FUNC_SUM",
"FUNC_PROD", "FUNC_EXP", "FUNC_LOG", "FUNC_LG", "FUNC_LN", "FUNC_SIN",
"FUNC_COS", "FUNC_TAN", "FUNC_CSC", "FUNC_SEC", "FUNC_COT",
"FUNC_ARCSIN", "FUNC_ARCCOS", "FUNC_ARCTAN", "FUNC_ARCCSC",
"FUNC_ARCSEC", "FUNC_ARCCOT", "FUNC_SINH", "FUNC_COSH", "FUNC_TANH",
"FUNC_ARSINH", "FUNC_ARCOSH", "FUNC_ARTANH", "L_FLOOR", "R_FLOOR",
"L_CEIL", "R_CEIL", "FUNC_SQRT", "FUNC_OVERLINE", "CMD_TIMES",
"CMD_CDOT", "CMD_DIV", "CMD_FRAC", "CMD_BINOM", "CMD_DBINOM",
"CMD_TBINOM", "CMD_MATHIT", "UNDERSCORE", "CARET", "COLON",
"DIFFERENTIAL", "LETTER", "DIGIT", "EQUAL", "NEQ", "LT", "LTE",
"LTE_Q", "LTE_S", "GT", "GTE", "GTE_Q", "GTE_S", "BANG", "SINGLE_QUOTES",
"SYMBOL" ]
ruleNames = [ "T__0", "T__1", "WS", "THINSPACE", "MEDSPACE", "THICKSPACE",
"QUAD", "QQUAD", "NEGTHINSPACE", "NEGMEDSPACE", "NEGTHICKSPACE",
"CMD_LEFT", "CMD_RIGHT", "IGNORE", "ADD", "SUB", "MUL",
"DIV", "L_PAREN", "R_PAREN", "L_BRACE", "R_BRACE", "L_BRACE_LITERAL",
"R_BRACE_LITERAL", "L_BRACKET", "R_BRACKET", "BAR", "R_BAR",
"L_BAR", "L_ANGLE", "R_ANGLE", "FUNC_LIM", "LIM_APPROACH_SYM",
"FUNC_INT", "FUNC_SUM", "FUNC_PROD", "FUNC_EXP", "FUNC_LOG",
"FUNC_LG", "FUNC_LN", "FUNC_SIN", "FUNC_COS", "FUNC_TAN",
"FUNC_CSC", "FUNC_SEC", "FUNC_COT", "FUNC_ARCSIN", "FUNC_ARCCOS",
"FUNC_ARCTAN", "FUNC_ARCCSC", "FUNC_ARCSEC", "FUNC_ARCCOT",
"FUNC_SINH", "FUNC_COSH", "FUNC_TANH", "FUNC_ARSINH",
"FUNC_ARCOSH", "FUNC_ARTANH", "L_FLOOR", "R_FLOOR", "L_CEIL",
"R_CEIL", "FUNC_SQRT", "FUNC_OVERLINE", "CMD_TIMES", "CMD_CDOT",
"CMD_DIV", "CMD_FRAC", "CMD_BINOM", "CMD_DBINOM", "CMD_TBINOM",
"CMD_MATHIT", "UNDERSCORE", "CARET", "COLON", "WS_CHAR",
"DIFFERENTIAL", "LETTER", "DIGIT", "EQUAL", "NEQ", "LT",
"LTE", "LTE_Q", "LTE_S", "GT", "GTE", "GTE_Q", "GTE_S",
"BANG", "SINGLE_QUOTES", "SYMBOL" ]
grammarFileName = "LaTeX.g4"
def __init__(self, input=None, output:TextIO = sys.stdout):
super().__init__(input, output)
self.checkVersion("4.10")
self._interp = LexerATNSimulator(self, self.atn, self.decisionsToDFA, PredictionContextCache())
self._actions = None
self._predicates = None
|
a7aca1d47c3006d6e0f9b18f32709b2c13e974d3d8c70ddd21708cf68411c10c | # *** GENERATED BY `setup.py antlr`, DO NOT EDIT BY HAND ***
#
# Generated from ../LaTeX.g4, derived from latex2sympy
# latex2sympy is licensed under the MIT license
# https://github.com/augustt198/latex2sympy/blob/master/LICENSE.txt
#
# Generated with antlr4
# antlr4 is licensed under the BSD-3-Clause License
# https://github.com/antlr/antlr4/blob/master/LICENSE.txt
from antlr4 import *
from io import StringIO
import sys
if sys.version_info[1] > 5:
from typing import TextIO
else:
from typing.io import TextIO
def serializedATN():
return [
4,1,91,522,2,0,7,0,2,1,7,1,2,2,7,2,2,3,7,3,2,4,7,4,2,5,7,5,2,6,7,
6,2,7,7,7,2,8,7,8,2,9,7,9,2,10,7,10,2,11,7,11,2,12,7,12,2,13,7,13,
2,14,7,14,2,15,7,15,2,16,7,16,2,17,7,17,2,18,7,18,2,19,7,19,2,20,
7,20,2,21,7,21,2,22,7,22,2,23,7,23,2,24,7,24,2,25,7,25,2,26,7,26,
2,27,7,27,2,28,7,28,2,29,7,29,2,30,7,30,2,31,7,31,2,32,7,32,2,33,
7,33,2,34,7,34,2,35,7,35,2,36,7,36,2,37,7,37,2,38,7,38,2,39,7,39,
2,40,7,40,1,0,1,0,1,1,1,1,1,1,1,1,1,1,1,1,5,1,91,8,1,10,1,12,1,94,
9,1,1,2,1,2,1,2,1,2,1,3,1,3,1,4,1,4,1,4,1,4,1,4,1,4,5,4,108,8,4,
10,4,12,4,111,9,4,1,5,1,5,1,5,1,5,1,5,1,5,5,5,119,8,5,10,5,12,5,
122,9,5,1,6,1,6,1,6,1,6,1,6,1,6,5,6,130,8,6,10,6,12,6,133,9,6,1,
7,1,7,1,7,4,7,138,8,7,11,7,12,7,139,3,7,142,8,7,1,8,1,8,1,8,1,8,
5,8,148,8,8,10,8,12,8,151,9,8,3,8,153,8,8,1,9,1,9,5,9,157,8,9,10,
9,12,9,160,9,9,1,10,1,10,5,10,164,8,10,10,10,12,10,167,9,10,1,11,
1,11,3,11,171,8,11,1,12,1,12,1,12,1,12,1,12,1,12,3,12,179,8,12,1,
13,1,13,1,13,1,13,3,13,185,8,13,1,13,1,13,1,14,1,14,1,14,1,14,3,
14,193,8,14,1,14,1,14,1,15,1,15,1,15,1,15,1,15,1,15,1,15,1,15,1,
15,1,15,3,15,207,8,15,1,15,3,15,210,8,15,5,15,212,8,15,10,15,12,
15,215,9,15,1,16,1,16,1,16,1,16,1,16,1,16,1,16,1,16,1,16,1,16,3,
16,227,8,16,1,16,3,16,230,8,16,5,16,232,8,16,10,16,12,16,235,9,16,
1,17,1,17,1,17,1,17,1,17,1,17,3,17,243,8,17,1,18,1,18,1,18,1,18,
1,18,3,18,250,8,18,1,19,1,19,1,19,1,19,1,19,1,19,1,19,1,19,1,19,
1,19,1,19,1,19,1,19,1,19,1,19,1,19,3,19,268,8,19,1,20,1,20,1,20,
1,20,1,21,4,21,275,8,21,11,21,12,21,276,1,21,1,21,1,21,1,21,5,21,
283,8,21,10,21,12,21,286,9,21,1,21,1,21,4,21,290,8,21,11,21,12,21,
291,3,21,294,8,21,1,22,1,22,3,22,298,8,22,1,22,3,22,301,8,22,1,22,
3,22,304,8,22,1,22,3,22,307,8,22,3,22,309,8,22,1,22,1,22,1,22,1,
22,1,22,1,22,1,22,3,22,318,8,22,1,23,1,23,1,23,1,23,1,24,1,24,1,
24,1,24,1,25,1,25,1,25,1,25,1,25,1,26,5,26,334,8,26,10,26,12,26,
337,9,26,1,27,1,27,1,27,1,27,1,27,1,27,3,27,345,8,27,1,27,1,27,1,
27,1,27,1,27,3,27,352,8,27,1,28,1,28,1,28,1,28,1,28,1,28,1,28,1,
28,1,29,1,29,1,29,1,29,1,30,1,30,1,30,1,30,1,31,1,31,1,32,1,32,3,
32,374,8,32,1,32,3,32,377,8,32,1,32,3,32,380,8,32,1,32,3,32,383,
8,32,3,32,385,8,32,1,32,1,32,1,32,1,32,1,32,3,32,392,8,32,1,32,1,
32,3,32,396,8,32,1,32,3,32,399,8,32,1,32,3,32,402,8,32,1,32,3,32,
405,8,32,3,32,407,8,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,
32,1,32,1,32,3,32,420,8,32,1,32,3,32,423,8,32,1,32,1,32,1,32,3,32,
428,8,32,1,32,1,32,1,32,1,32,1,32,3,32,435,8,32,1,32,1,32,1,32,1,
32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,1,32,3,
32,453,8,32,1,32,1,32,1,32,1,32,1,32,1,32,3,32,461,8,32,1,33,1,33,
1,33,1,33,1,33,3,33,468,8,33,1,34,1,34,1,34,1,34,1,34,1,34,1,34,
1,34,1,34,1,34,1,34,3,34,481,8,34,3,34,483,8,34,1,34,1,34,1,35,1,
35,1,35,1,35,1,35,3,35,492,8,35,1,36,1,36,1,37,1,37,1,37,1,37,1,
37,1,37,3,37,502,8,37,1,38,1,38,1,38,1,38,1,38,1,38,3,38,510,8,38,
1,39,1,39,1,39,1,39,1,39,1,40,1,40,1,40,1,40,1,40,1,40,0,6,2,8,10,
12,30,32,41,0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,
38,40,42,44,46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80,
0,9,2,0,79,82,85,86,1,0,15,16,3,0,17,18,65,67,75,75,2,0,77,77,91,
91,1,0,27,28,2,0,27,27,29,29,1,0,69,71,1,0,37,58,1,0,35,36,563,0,
82,1,0,0,0,2,84,1,0,0,0,4,95,1,0,0,0,6,99,1,0,0,0,8,101,1,0,0,0,
10,112,1,0,0,0,12,123,1,0,0,0,14,141,1,0,0,0,16,152,1,0,0,0,18,154,
1,0,0,0,20,161,1,0,0,0,22,170,1,0,0,0,24,172,1,0,0,0,26,180,1,0,
0,0,28,188,1,0,0,0,30,196,1,0,0,0,32,216,1,0,0,0,34,242,1,0,0,0,
36,249,1,0,0,0,38,267,1,0,0,0,40,269,1,0,0,0,42,274,1,0,0,0,44,317,
1,0,0,0,46,319,1,0,0,0,48,323,1,0,0,0,50,327,1,0,0,0,52,335,1,0,
0,0,54,338,1,0,0,0,56,353,1,0,0,0,58,361,1,0,0,0,60,365,1,0,0,0,
62,369,1,0,0,0,64,460,1,0,0,0,66,467,1,0,0,0,68,469,1,0,0,0,70,491,
1,0,0,0,72,493,1,0,0,0,74,495,1,0,0,0,76,503,1,0,0,0,78,511,1,0,
0,0,80,516,1,0,0,0,82,83,3,2,1,0,83,1,1,0,0,0,84,85,6,1,-1,0,85,
86,3,6,3,0,86,92,1,0,0,0,87,88,10,2,0,0,88,89,7,0,0,0,89,91,3,2,
1,3,90,87,1,0,0,0,91,94,1,0,0,0,92,90,1,0,0,0,92,93,1,0,0,0,93,3,
1,0,0,0,94,92,1,0,0,0,95,96,3,6,3,0,96,97,5,79,0,0,97,98,3,6,3,0,
98,5,1,0,0,0,99,100,3,8,4,0,100,7,1,0,0,0,101,102,6,4,-1,0,102,103,
3,10,5,0,103,109,1,0,0,0,104,105,10,2,0,0,105,106,7,1,0,0,106,108,
3,8,4,3,107,104,1,0,0,0,108,111,1,0,0,0,109,107,1,0,0,0,109,110,
1,0,0,0,110,9,1,0,0,0,111,109,1,0,0,0,112,113,6,5,-1,0,113,114,3,
14,7,0,114,120,1,0,0,0,115,116,10,2,0,0,116,117,7,2,0,0,117,119,
3,10,5,3,118,115,1,0,0,0,119,122,1,0,0,0,120,118,1,0,0,0,120,121,
1,0,0,0,121,11,1,0,0,0,122,120,1,0,0,0,123,124,6,6,-1,0,124,125,
3,16,8,0,125,131,1,0,0,0,126,127,10,2,0,0,127,128,7,2,0,0,128,130,
3,12,6,3,129,126,1,0,0,0,130,133,1,0,0,0,131,129,1,0,0,0,131,132,
1,0,0,0,132,13,1,0,0,0,133,131,1,0,0,0,134,135,7,1,0,0,135,142,3,
14,7,0,136,138,3,18,9,0,137,136,1,0,0,0,138,139,1,0,0,0,139,137,
1,0,0,0,139,140,1,0,0,0,140,142,1,0,0,0,141,134,1,0,0,0,141,137,
1,0,0,0,142,15,1,0,0,0,143,144,7,1,0,0,144,153,3,16,8,0,145,149,
3,18,9,0,146,148,3,20,10,0,147,146,1,0,0,0,148,151,1,0,0,0,149,147,
1,0,0,0,149,150,1,0,0,0,150,153,1,0,0,0,151,149,1,0,0,0,152,143,
1,0,0,0,152,145,1,0,0,0,153,17,1,0,0,0,154,158,3,30,15,0,155,157,
3,22,11,0,156,155,1,0,0,0,157,160,1,0,0,0,158,156,1,0,0,0,158,159,
1,0,0,0,159,19,1,0,0,0,160,158,1,0,0,0,161,165,3,32,16,0,162,164,
3,22,11,0,163,162,1,0,0,0,164,167,1,0,0,0,165,163,1,0,0,0,165,166,
1,0,0,0,166,21,1,0,0,0,167,165,1,0,0,0,168,171,5,89,0,0,169,171,
3,24,12,0,170,168,1,0,0,0,170,169,1,0,0,0,171,23,1,0,0,0,172,178,
5,27,0,0,173,179,3,28,14,0,174,179,3,26,13,0,175,176,3,28,14,0,176,
177,3,26,13,0,177,179,1,0,0,0,178,173,1,0,0,0,178,174,1,0,0,0,178,
175,1,0,0,0,179,25,1,0,0,0,180,181,5,73,0,0,181,184,5,21,0,0,182,
185,3,6,3,0,183,185,3,4,2,0,184,182,1,0,0,0,184,183,1,0,0,0,185,
186,1,0,0,0,186,187,5,22,0,0,187,27,1,0,0,0,188,189,5,74,0,0,189,
192,5,21,0,0,190,193,3,6,3,0,191,193,3,4,2,0,192,190,1,0,0,0,192,
191,1,0,0,0,193,194,1,0,0,0,194,195,5,22,0,0,195,29,1,0,0,0,196,
197,6,15,-1,0,197,198,3,34,17,0,198,213,1,0,0,0,199,200,10,2,0,0,
200,206,5,74,0,0,201,207,3,44,22,0,202,203,5,21,0,0,203,204,3,6,
3,0,204,205,5,22,0,0,205,207,1,0,0,0,206,201,1,0,0,0,206,202,1,0,
0,0,207,209,1,0,0,0,208,210,3,74,37,0,209,208,1,0,0,0,209,210,1,
0,0,0,210,212,1,0,0,0,211,199,1,0,0,0,212,215,1,0,0,0,213,211,1,
0,0,0,213,214,1,0,0,0,214,31,1,0,0,0,215,213,1,0,0,0,216,217,6,16,
-1,0,217,218,3,36,18,0,218,233,1,0,0,0,219,220,10,2,0,0,220,226,
5,74,0,0,221,227,3,44,22,0,222,223,5,21,0,0,223,224,3,6,3,0,224,
225,5,22,0,0,225,227,1,0,0,0,226,221,1,0,0,0,226,222,1,0,0,0,227,
229,1,0,0,0,228,230,3,74,37,0,229,228,1,0,0,0,229,230,1,0,0,0,230,
232,1,0,0,0,231,219,1,0,0,0,232,235,1,0,0,0,233,231,1,0,0,0,233,
234,1,0,0,0,234,33,1,0,0,0,235,233,1,0,0,0,236,243,3,38,19,0,237,
243,3,40,20,0,238,243,3,64,32,0,239,243,3,44,22,0,240,243,3,58,29,
0,241,243,3,60,30,0,242,236,1,0,0,0,242,237,1,0,0,0,242,238,1,0,
0,0,242,239,1,0,0,0,242,240,1,0,0,0,242,241,1,0,0,0,243,35,1,0,0,
0,244,250,3,38,19,0,245,250,3,40,20,0,246,250,3,44,22,0,247,250,
3,58,29,0,248,250,3,60,30,0,249,244,1,0,0,0,249,245,1,0,0,0,249,
246,1,0,0,0,249,247,1,0,0,0,249,248,1,0,0,0,250,37,1,0,0,0,251,252,
5,19,0,0,252,253,3,6,3,0,253,254,5,20,0,0,254,268,1,0,0,0,255,256,
5,25,0,0,256,257,3,6,3,0,257,258,5,26,0,0,258,268,1,0,0,0,259,260,
5,21,0,0,260,261,3,6,3,0,261,262,5,22,0,0,262,268,1,0,0,0,263,264,
5,23,0,0,264,265,3,6,3,0,265,266,5,24,0,0,266,268,1,0,0,0,267,251,
1,0,0,0,267,255,1,0,0,0,267,259,1,0,0,0,267,263,1,0,0,0,268,39,1,
0,0,0,269,270,5,27,0,0,270,271,3,6,3,0,271,272,5,27,0,0,272,41,1,
0,0,0,273,275,5,78,0,0,274,273,1,0,0,0,275,276,1,0,0,0,276,274,1,
0,0,0,276,277,1,0,0,0,277,284,1,0,0,0,278,279,5,1,0,0,279,280,5,
78,0,0,280,281,5,78,0,0,281,283,5,78,0,0,282,278,1,0,0,0,283,286,
1,0,0,0,284,282,1,0,0,0,284,285,1,0,0,0,285,293,1,0,0,0,286,284,
1,0,0,0,287,289,5,2,0,0,288,290,5,78,0,0,289,288,1,0,0,0,290,291,
1,0,0,0,291,289,1,0,0,0,291,292,1,0,0,0,292,294,1,0,0,0,293,287,
1,0,0,0,293,294,1,0,0,0,294,43,1,0,0,0,295,308,7,3,0,0,296,298,3,
74,37,0,297,296,1,0,0,0,297,298,1,0,0,0,298,300,1,0,0,0,299,301,
5,90,0,0,300,299,1,0,0,0,300,301,1,0,0,0,301,309,1,0,0,0,302,304,
5,90,0,0,303,302,1,0,0,0,303,304,1,0,0,0,304,306,1,0,0,0,305,307,
3,74,37,0,306,305,1,0,0,0,306,307,1,0,0,0,307,309,1,0,0,0,308,297,
1,0,0,0,308,303,1,0,0,0,309,318,1,0,0,0,310,318,3,42,21,0,311,318,
5,76,0,0,312,318,3,50,25,0,313,318,3,54,27,0,314,318,3,56,28,0,315,
318,3,46,23,0,316,318,3,48,24,0,317,295,1,0,0,0,317,310,1,0,0,0,
317,311,1,0,0,0,317,312,1,0,0,0,317,313,1,0,0,0,317,314,1,0,0,0,
317,315,1,0,0,0,317,316,1,0,0,0,318,45,1,0,0,0,319,320,5,30,0,0,
320,321,3,6,3,0,321,322,7,4,0,0,322,47,1,0,0,0,323,324,7,5,0,0,324,
325,3,6,3,0,325,326,5,31,0,0,326,49,1,0,0,0,327,328,5,72,0,0,328,
329,5,21,0,0,329,330,3,52,26,0,330,331,5,22,0,0,331,51,1,0,0,0,332,
334,5,77,0,0,333,332,1,0,0,0,334,337,1,0,0,0,335,333,1,0,0,0,335,
336,1,0,0,0,336,53,1,0,0,0,337,335,1,0,0,0,338,344,5,68,0,0,339,
345,5,78,0,0,340,341,5,21,0,0,341,342,3,6,3,0,342,343,5,22,0,0,343,
345,1,0,0,0,344,339,1,0,0,0,344,340,1,0,0,0,345,351,1,0,0,0,346,
352,5,78,0,0,347,348,5,21,0,0,348,349,3,6,3,0,349,350,5,22,0,0,350,
352,1,0,0,0,351,346,1,0,0,0,351,347,1,0,0,0,352,55,1,0,0,0,353,354,
7,6,0,0,354,355,5,21,0,0,355,356,3,6,3,0,356,357,5,22,0,0,357,358,
5,21,0,0,358,359,3,6,3,0,359,360,5,22,0,0,360,57,1,0,0,0,361,362,
5,59,0,0,362,363,3,6,3,0,363,364,5,60,0,0,364,59,1,0,0,0,365,366,
5,61,0,0,366,367,3,6,3,0,367,368,5,62,0,0,368,61,1,0,0,0,369,370,
7,7,0,0,370,63,1,0,0,0,371,384,3,62,31,0,372,374,3,74,37,0,373,372,
1,0,0,0,373,374,1,0,0,0,374,376,1,0,0,0,375,377,3,76,38,0,376,375,
1,0,0,0,376,377,1,0,0,0,377,385,1,0,0,0,378,380,3,76,38,0,379,378,
1,0,0,0,379,380,1,0,0,0,380,382,1,0,0,0,381,383,3,74,37,0,382,381,
1,0,0,0,382,383,1,0,0,0,383,385,1,0,0,0,384,373,1,0,0,0,384,379,
1,0,0,0,385,391,1,0,0,0,386,387,5,19,0,0,387,388,3,70,35,0,388,389,
5,20,0,0,389,392,1,0,0,0,390,392,3,72,36,0,391,386,1,0,0,0,391,390,
1,0,0,0,392,461,1,0,0,0,393,406,7,3,0,0,394,396,3,74,37,0,395,394,
1,0,0,0,395,396,1,0,0,0,396,398,1,0,0,0,397,399,5,90,0,0,398,397,
1,0,0,0,398,399,1,0,0,0,399,407,1,0,0,0,400,402,5,90,0,0,401,400,
1,0,0,0,401,402,1,0,0,0,402,404,1,0,0,0,403,405,3,74,37,0,404,403,
1,0,0,0,404,405,1,0,0,0,405,407,1,0,0,0,406,395,1,0,0,0,406,401,
1,0,0,0,407,408,1,0,0,0,408,409,5,19,0,0,409,410,3,66,33,0,410,411,
5,20,0,0,411,461,1,0,0,0,412,419,5,34,0,0,413,414,3,74,37,0,414,
415,3,76,38,0,415,420,1,0,0,0,416,417,3,76,38,0,417,418,3,74,37,
0,418,420,1,0,0,0,419,413,1,0,0,0,419,416,1,0,0,0,419,420,1,0,0,
0,420,427,1,0,0,0,421,423,3,8,4,0,422,421,1,0,0,0,422,423,1,0,0,
0,423,424,1,0,0,0,424,428,5,76,0,0,425,428,3,54,27,0,426,428,3,8,
4,0,427,422,1,0,0,0,427,425,1,0,0,0,427,426,1,0,0,0,428,461,1,0,
0,0,429,434,5,63,0,0,430,431,5,25,0,0,431,432,3,6,3,0,432,433,5,
26,0,0,433,435,1,0,0,0,434,430,1,0,0,0,434,435,1,0,0,0,435,436,1,
0,0,0,436,437,5,21,0,0,437,438,3,6,3,0,438,439,5,22,0,0,439,461,
1,0,0,0,440,441,5,64,0,0,441,442,5,21,0,0,442,443,3,6,3,0,443,444,
5,22,0,0,444,461,1,0,0,0,445,452,7,8,0,0,446,447,3,78,39,0,447,448,
3,76,38,0,448,453,1,0,0,0,449,450,3,76,38,0,450,451,3,78,39,0,451,
453,1,0,0,0,452,446,1,0,0,0,452,449,1,0,0,0,453,454,1,0,0,0,454,
455,3,10,5,0,455,461,1,0,0,0,456,457,5,32,0,0,457,458,3,68,34,0,
458,459,3,10,5,0,459,461,1,0,0,0,460,371,1,0,0,0,460,393,1,0,0,0,
460,412,1,0,0,0,460,429,1,0,0,0,460,440,1,0,0,0,460,445,1,0,0,0,
460,456,1,0,0,0,461,65,1,0,0,0,462,463,3,6,3,0,463,464,5,1,0,0,464,
465,3,66,33,0,465,468,1,0,0,0,466,468,3,6,3,0,467,462,1,0,0,0,467,
466,1,0,0,0,468,67,1,0,0,0,469,470,5,73,0,0,470,471,5,21,0,0,471,
472,7,3,0,0,472,473,5,33,0,0,473,482,3,6,3,0,474,480,5,74,0,0,475,
476,5,21,0,0,476,477,7,1,0,0,477,481,5,22,0,0,478,481,5,15,0,0,479,
481,5,16,0,0,480,475,1,0,0,0,480,478,1,0,0,0,480,479,1,0,0,0,481,
483,1,0,0,0,482,474,1,0,0,0,482,483,1,0,0,0,483,484,1,0,0,0,484,
485,5,22,0,0,485,69,1,0,0,0,486,492,3,6,3,0,487,488,3,6,3,0,488,
489,5,1,0,0,489,490,3,70,35,0,490,492,1,0,0,0,491,486,1,0,0,0,491,
487,1,0,0,0,492,71,1,0,0,0,493,494,3,12,6,0,494,73,1,0,0,0,495,501,
5,73,0,0,496,502,3,44,22,0,497,498,5,21,0,0,498,499,3,6,3,0,499,
500,5,22,0,0,500,502,1,0,0,0,501,496,1,0,0,0,501,497,1,0,0,0,502,
75,1,0,0,0,503,509,5,74,0,0,504,510,3,44,22,0,505,506,5,21,0,0,506,
507,3,6,3,0,507,508,5,22,0,0,508,510,1,0,0,0,509,504,1,0,0,0,509,
505,1,0,0,0,510,77,1,0,0,0,511,512,5,73,0,0,512,513,5,21,0,0,513,
514,3,4,2,0,514,515,5,22,0,0,515,79,1,0,0,0,516,517,5,73,0,0,517,
518,5,21,0,0,518,519,3,4,2,0,519,520,5,22,0,0,520,81,1,0,0,0,59,
92,109,120,131,139,141,149,152,158,165,170,178,184,192,206,209,213,
226,229,233,242,249,267,276,284,291,293,297,300,303,306,308,317,
335,344,351,373,376,379,382,384,391,395,398,401,404,406,419,422,
427,434,452,460,467,480,482,491,501,509
]
class LaTeXParser ( Parser ):
grammarFileName = "LaTeX.g4"
atn = ATNDeserializer().deserialize(serializedATN())
decisionsToDFA = [ DFA(ds, i) for i, ds in enumerate(atn.decisionToState) ]
sharedContextCache = PredictionContextCache()
literalNames = [ "<INVALID>", "','", "'.'", "<INVALID>", "<INVALID>",
"<INVALID>", "<INVALID>", "'\\quad'", "'\\qquad'",
"<INVALID>", "'\\negmedspace'", "'\\negthickspace'",
"'\\left'", "'\\right'", "<INVALID>", "'+'", "'-'",
"'*'", "'/'", "'('", "')'", "'{'", "'}'", "'\\{'",
"'\\}'", "'['", "']'", "'|'", "'\\right|'", "'\\left|'",
"'\\langle'", "'\\rangle'", "'\\lim'", "<INVALID>",
"<INVALID>", "'\\sum'", "'\\prod'", "'\\exp'", "'\\log'",
"'\\lg'", "'\\ln'", "'\\sin'", "'\\cos'", "'\\tan'",
"'\\csc'", "'\\sec'", "'\\cot'", "'\\arcsin'", "'\\arccos'",
"'\\arctan'", "'\\arccsc'", "'\\arcsec'", "'\\arccot'",
"'\\sinh'", "'\\cosh'", "'\\tanh'", "'\\arsinh'", "'\\arcosh'",
"'\\artanh'", "'\\lfloor'", "'\\rfloor'", "'\\lceil'",
"'\\rceil'", "'\\sqrt'", "'\\overline'", "'\\times'",
"'\\cdot'", "'\\div'", "<INVALID>", "'\\binom'", "'\\dbinom'",
"'\\tbinom'", "'\\mathit'", "'_'", "'^'", "':'", "<INVALID>",
"<INVALID>", "<INVALID>", "<INVALID>", "'\\neq'", "'<'",
"<INVALID>", "'\\leqq'", "'\\leqslant'", "'>'", "<INVALID>",
"'\\geqq'", "'\\geqslant'", "'!'" ]
symbolicNames = [ "<INVALID>", "<INVALID>", "<INVALID>", "WS", "THINSPACE",
"MEDSPACE", "THICKSPACE", "QUAD", "QQUAD", "NEGTHINSPACE",
"NEGMEDSPACE", "NEGTHICKSPACE", "CMD_LEFT", "CMD_RIGHT",
"IGNORE", "ADD", "SUB", "MUL", "DIV", "L_PAREN", "R_PAREN",
"L_BRACE", "R_BRACE", "L_BRACE_LITERAL", "R_BRACE_LITERAL",
"L_BRACKET", "R_BRACKET", "BAR", "R_BAR", "L_BAR",
"L_ANGLE", "R_ANGLE", "FUNC_LIM", "LIM_APPROACH_SYM",
"FUNC_INT", "FUNC_SUM", "FUNC_PROD", "FUNC_EXP", "FUNC_LOG",
"FUNC_LG", "FUNC_LN", "FUNC_SIN", "FUNC_COS", "FUNC_TAN",
"FUNC_CSC", "FUNC_SEC", "FUNC_COT", "FUNC_ARCSIN",
"FUNC_ARCCOS", "FUNC_ARCTAN", "FUNC_ARCCSC", "FUNC_ARCSEC",
"FUNC_ARCCOT", "FUNC_SINH", "FUNC_COSH", "FUNC_TANH",
"FUNC_ARSINH", "FUNC_ARCOSH", "FUNC_ARTANH", "L_FLOOR",
"R_FLOOR", "L_CEIL", "R_CEIL", "FUNC_SQRT", "FUNC_OVERLINE",
"CMD_TIMES", "CMD_CDOT", "CMD_DIV", "CMD_FRAC", "CMD_BINOM",
"CMD_DBINOM", "CMD_TBINOM", "CMD_MATHIT", "UNDERSCORE",
"CARET", "COLON", "DIFFERENTIAL", "LETTER", "DIGIT",
"EQUAL", "NEQ", "LT", "LTE", "LTE_Q", "LTE_S", "GT",
"GTE", "GTE_Q", "GTE_S", "BANG", "SINGLE_QUOTES",
"SYMBOL" ]
RULE_math = 0
RULE_relation = 1
RULE_equality = 2
RULE_expr = 3
RULE_additive = 4
RULE_mp = 5
RULE_mp_nofunc = 6
RULE_unary = 7
RULE_unary_nofunc = 8
RULE_postfix = 9
RULE_postfix_nofunc = 10
RULE_postfix_op = 11
RULE_eval_at = 12
RULE_eval_at_sub = 13
RULE_eval_at_sup = 14
RULE_exp = 15
RULE_exp_nofunc = 16
RULE_comp = 17
RULE_comp_nofunc = 18
RULE_group = 19
RULE_abs_group = 20
RULE_number = 21
RULE_atom = 22
RULE_bra = 23
RULE_ket = 24
RULE_mathit = 25
RULE_mathit_text = 26
RULE_frac = 27
RULE_binom = 28
RULE_floor = 29
RULE_ceil = 30
RULE_func_normal = 31
RULE_func = 32
RULE_args = 33
RULE_limit_sub = 34
RULE_func_arg = 35
RULE_func_arg_noparens = 36
RULE_subexpr = 37
RULE_supexpr = 38
RULE_subeq = 39
RULE_supeq = 40
ruleNames = [ "math", "relation", "equality", "expr", "additive", "mp",
"mp_nofunc", "unary", "unary_nofunc", "postfix", "postfix_nofunc",
"postfix_op", "eval_at", "eval_at_sub", "eval_at_sup",
"exp", "exp_nofunc", "comp", "comp_nofunc", "group",
"abs_group", "number", "atom", "bra", "ket", "mathit",
"mathit_text", "frac", "binom", "floor", "ceil", "func_normal",
"func", "args", "limit_sub", "func_arg", "func_arg_noparens",
"subexpr", "supexpr", "subeq", "supeq" ]
EOF = Token.EOF
T__0=1
T__1=2
WS=3
THINSPACE=4
MEDSPACE=5
THICKSPACE=6
QUAD=7
QQUAD=8
NEGTHINSPACE=9
NEGMEDSPACE=10
NEGTHICKSPACE=11
CMD_LEFT=12
CMD_RIGHT=13
IGNORE=14
ADD=15
SUB=16
MUL=17
DIV=18
L_PAREN=19
R_PAREN=20
L_BRACE=21
R_BRACE=22
L_BRACE_LITERAL=23
R_BRACE_LITERAL=24
L_BRACKET=25
R_BRACKET=26
BAR=27
R_BAR=28
L_BAR=29
L_ANGLE=30
R_ANGLE=31
FUNC_LIM=32
LIM_APPROACH_SYM=33
FUNC_INT=34
FUNC_SUM=35
FUNC_PROD=36
FUNC_EXP=37
FUNC_LOG=38
FUNC_LG=39
FUNC_LN=40
FUNC_SIN=41
FUNC_COS=42
FUNC_TAN=43
FUNC_CSC=44
FUNC_SEC=45
FUNC_COT=46
FUNC_ARCSIN=47
FUNC_ARCCOS=48
FUNC_ARCTAN=49
FUNC_ARCCSC=50
FUNC_ARCSEC=51
FUNC_ARCCOT=52
FUNC_SINH=53
FUNC_COSH=54
FUNC_TANH=55
FUNC_ARSINH=56
FUNC_ARCOSH=57
FUNC_ARTANH=58
L_FLOOR=59
R_FLOOR=60
L_CEIL=61
R_CEIL=62
FUNC_SQRT=63
FUNC_OVERLINE=64
CMD_TIMES=65
CMD_CDOT=66
CMD_DIV=67
CMD_FRAC=68
CMD_BINOM=69
CMD_DBINOM=70
CMD_TBINOM=71
CMD_MATHIT=72
UNDERSCORE=73
CARET=74
COLON=75
DIFFERENTIAL=76
LETTER=77
DIGIT=78
EQUAL=79
NEQ=80
LT=81
LTE=82
LTE_Q=83
LTE_S=84
GT=85
GTE=86
GTE_Q=87
GTE_S=88
BANG=89
SINGLE_QUOTES=90
SYMBOL=91
def __init__(self, input:TokenStream, output:TextIO = sys.stdout):
super().__init__(input, output)
self.checkVersion("4.10")
self._interp = ParserATNSimulator(self, self.atn, self.decisionsToDFA, self.sharedContextCache)
self._predicates = None
class MathContext(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def relation(self):
return self.getTypedRuleContext(LaTeXParser.RelationContext,0)
def getRuleIndex(self):
return LaTeXParser.RULE_math
def math(self):
localctx = LaTeXParser.MathContext(self, self._ctx, self.state)
self.enterRule(localctx, 0, self.RULE_math)
try:
self.enterOuterAlt(localctx, 1)
self.state = 82
self.relation(0)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class RelationContext(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def expr(self):
return self.getTypedRuleContext(LaTeXParser.ExprContext,0)
def relation(self, i:int=None):
if i is None:
return self.getTypedRuleContexts(LaTeXParser.RelationContext)
else:
return self.getTypedRuleContext(LaTeXParser.RelationContext,i)
def EQUAL(self):
return self.getToken(LaTeXParser.EQUAL, 0)
def LT(self):
return self.getToken(LaTeXParser.LT, 0)
def LTE(self):
return self.getToken(LaTeXParser.LTE, 0)
def GT(self):
return self.getToken(LaTeXParser.GT, 0)
def GTE(self):
return self.getToken(LaTeXParser.GTE, 0)
def NEQ(self):
return self.getToken(LaTeXParser.NEQ, 0)
def getRuleIndex(self):
return LaTeXParser.RULE_relation
def relation(self, _p:int=0):
_parentctx = self._ctx
_parentState = self.state
localctx = LaTeXParser.RelationContext(self, self._ctx, _parentState)
_prevctx = localctx
_startState = 2
self.enterRecursionRule(localctx, 2, self.RULE_relation, _p)
self._la = 0 # Token type
try:
self.enterOuterAlt(localctx, 1)
self.state = 85
self.expr()
self._ctx.stop = self._input.LT(-1)
self.state = 92
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input,0,self._ctx)
while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:
if _alt==1:
if self._parseListeners is not None:
self.triggerExitRuleEvent()
_prevctx = localctx
localctx = LaTeXParser.RelationContext(self, _parentctx, _parentState)
self.pushNewRecursionContext(localctx, _startState, self.RULE_relation)
self.state = 87
if not self.precpred(self._ctx, 2):
from antlr4.error.Errors import FailedPredicateException
raise FailedPredicateException(self, "self.precpred(self._ctx, 2)")
self.state = 88
_la = self._input.LA(1)
if not(((((_la - 79)) & ~0x3f) == 0 and ((1 << (_la - 79)) & ((1 << (LaTeXParser.EQUAL - 79)) | (1 << (LaTeXParser.NEQ - 79)) | (1 << (LaTeXParser.LT - 79)) | (1 << (LaTeXParser.LTE - 79)) | (1 << (LaTeXParser.GT - 79)) | (1 << (LaTeXParser.GTE - 79)))) != 0)):
self._errHandler.recoverInline(self)
else:
self._errHandler.reportMatch(self)
self.consume()
self.state = 89
self.relation(3)
self.state = 94
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input,0,self._ctx)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.unrollRecursionContexts(_parentctx)
return localctx
class EqualityContext(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def expr(self, i:int=None):
if i is None:
return self.getTypedRuleContexts(LaTeXParser.ExprContext)
else:
return self.getTypedRuleContext(LaTeXParser.ExprContext,i)
def EQUAL(self):
return self.getToken(LaTeXParser.EQUAL, 0)
def getRuleIndex(self):
return LaTeXParser.RULE_equality
def equality(self):
localctx = LaTeXParser.EqualityContext(self, self._ctx, self.state)
self.enterRule(localctx, 4, self.RULE_equality)
try:
self.enterOuterAlt(localctx, 1)
self.state = 95
self.expr()
self.state = 96
self.match(LaTeXParser.EQUAL)
self.state = 97
self.expr()
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class ExprContext(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def additive(self):
return self.getTypedRuleContext(LaTeXParser.AdditiveContext,0)
def getRuleIndex(self):
return LaTeXParser.RULE_expr
def expr(self):
localctx = LaTeXParser.ExprContext(self, self._ctx, self.state)
self.enterRule(localctx, 6, self.RULE_expr)
try:
self.enterOuterAlt(localctx, 1)
self.state = 99
self.additive(0)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class AdditiveContext(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def mp(self):
return self.getTypedRuleContext(LaTeXParser.MpContext,0)
def additive(self, i:int=None):
if i is None:
return self.getTypedRuleContexts(LaTeXParser.AdditiveContext)
else:
return self.getTypedRuleContext(LaTeXParser.AdditiveContext,i)
def ADD(self):
return self.getToken(LaTeXParser.ADD, 0)
def SUB(self):
return self.getToken(LaTeXParser.SUB, 0)
def getRuleIndex(self):
return LaTeXParser.RULE_additive
def additive(self, _p:int=0):
_parentctx = self._ctx
_parentState = self.state
localctx = LaTeXParser.AdditiveContext(self, self._ctx, _parentState)
_prevctx = localctx
_startState = 8
self.enterRecursionRule(localctx, 8, self.RULE_additive, _p)
self._la = 0 # Token type
try:
self.enterOuterAlt(localctx, 1)
self.state = 102
self.mp(0)
self._ctx.stop = self._input.LT(-1)
self.state = 109
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input,1,self._ctx)
while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:
if _alt==1:
if self._parseListeners is not None:
self.triggerExitRuleEvent()
_prevctx = localctx
localctx = LaTeXParser.AdditiveContext(self, _parentctx, _parentState)
self.pushNewRecursionContext(localctx, _startState, self.RULE_additive)
self.state = 104
if not self.precpred(self._ctx, 2):
from antlr4.error.Errors import FailedPredicateException
raise FailedPredicateException(self, "self.precpred(self._ctx, 2)")
self.state = 105
_la = self._input.LA(1)
if not(_la==LaTeXParser.ADD or _la==LaTeXParser.SUB):
self._errHandler.recoverInline(self)
else:
self._errHandler.reportMatch(self)
self.consume()
self.state = 106
self.additive(3)
self.state = 111
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input,1,self._ctx)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.unrollRecursionContexts(_parentctx)
return localctx
class MpContext(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def unary(self):
return self.getTypedRuleContext(LaTeXParser.UnaryContext,0)
def mp(self, i:int=None):
if i is None:
return self.getTypedRuleContexts(LaTeXParser.MpContext)
else:
return self.getTypedRuleContext(LaTeXParser.MpContext,i)
def MUL(self):
return self.getToken(LaTeXParser.MUL, 0)
def CMD_TIMES(self):
return self.getToken(LaTeXParser.CMD_TIMES, 0)
def CMD_CDOT(self):
return self.getToken(LaTeXParser.CMD_CDOT, 0)
def DIV(self):
return self.getToken(LaTeXParser.DIV, 0)
def CMD_DIV(self):
return self.getToken(LaTeXParser.CMD_DIV, 0)
def COLON(self):
return self.getToken(LaTeXParser.COLON, 0)
def getRuleIndex(self):
return LaTeXParser.RULE_mp
def mp(self, _p:int=0):
_parentctx = self._ctx
_parentState = self.state
localctx = LaTeXParser.MpContext(self, self._ctx, _parentState)
_prevctx = localctx
_startState = 10
self.enterRecursionRule(localctx, 10, self.RULE_mp, _p)
self._la = 0 # Token type
try:
self.enterOuterAlt(localctx, 1)
self.state = 113
self.unary()
self._ctx.stop = self._input.LT(-1)
self.state = 120
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input,2,self._ctx)
while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:
if _alt==1:
if self._parseListeners is not None:
self.triggerExitRuleEvent()
_prevctx = localctx
localctx = LaTeXParser.MpContext(self, _parentctx, _parentState)
self.pushNewRecursionContext(localctx, _startState, self.RULE_mp)
self.state = 115
if not self.precpred(self._ctx, 2):
from antlr4.error.Errors import FailedPredicateException
raise FailedPredicateException(self, "self.precpred(self._ctx, 2)")
self.state = 116
_la = self._input.LA(1)
if not(((((_la - 17)) & ~0x3f) == 0 and ((1 << (_la - 17)) & ((1 << (LaTeXParser.MUL - 17)) | (1 << (LaTeXParser.DIV - 17)) | (1 << (LaTeXParser.CMD_TIMES - 17)) | (1 << (LaTeXParser.CMD_CDOT - 17)) | (1 << (LaTeXParser.CMD_DIV - 17)) | (1 << (LaTeXParser.COLON - 17)))) != 0)):
self._errHandler.recoverInline(self)
else:
self._errHandler.reportMatch(self)
self.consume()
self.state = 117
self.mp(3)
self.state = 122
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input,2,self._ctx)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.unrollRecursionContexts(_parentctx)
return localctx
class Mp_nofuncContext(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def unary_nofunc(self):
return self.getTypedRuleContext(LaTeXParser.Unary_nofuncContext,0)
def mp_nofunc(self, i:int=None):
if i is None:
return self.getTypedRuleContexts(LaTeXParser.Mp_nofuncContext)
else:
return self.getTypedRuleContext(LaTeXParser.Mp_nofuncContext,i)
def MUL(self):
return self.getToken(LaTeXParser.MUL, 0)
def CMD_TIMES(self):
return self.getToken(LaTeXParser.CMD_TIMES, 0)
def CMD_CDOT(self):
return self.getToken(LaTeXParser.CMD_CDOT, 0)
def DIV(self):
return self.getToken(LaTeXParser.DIV, 0)
def CMD_DIV(self):
return self.getToken(LaTeXParser.CMD_DIV, 0)
def COLON(self):
return self.getToken(LaTeXParser.COLON, 0)
def getRuleIndex(self):
return LaTeXParser.RULE_mp_nofunc
def mp_nofunc(self, _p:int=0):
_parentctx = self._ctx
_parentState = self.state
localctx = LaTeXParser.Mp_nofuncContext(self, self._ctx, _parentState)
_prevctx = localctx
_startState = 12
self.enterRecursionRule(localctx, 12, self.RULE_mp_nofunc, _p)
self._la = 0 # Token type
try:
self.enterOuterAlt(localctx, 1)
self.state = 124
self.unary_nofunc()
self._ctx.stop = self._input.LT(-1)
self.state = 131
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input,3,self._ctx)
while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:
if _alt==1:
if self._parseListeners is not None:
self.triggerExitRuleEvent()
_prevctx = localctx
localctx = LaTeXParser.Mp_nofuncContext(self, _parentctx, _parentState)
self.pushNewRecursionContext(localctx, _startState, self.RULE_mp_nofunc)
self.state = 126
if not self.precpred(self._ctx, 2):
from antlr4.error.Errors import FailedPredicateException
raise FailedPredicateException(self, "self.precpred(self._ctx, 2)")
self.state = 127
_la = self._input.LA(1)
if not(((((_la - 17)) & ~0x3f) == 0 and ((1 << (_la - 17)) & ((1 << (LaTeXParser.MUL - 17)) | (1 << (LaTeXParser.DIV - 17)) | (1 << (LaTeXParser.CMD_TIMES - 17)) | (1 << (LaTeXParser.CMD_CDOT - 17)) | (1 << (LaTeXParser.CMD_DIV - 17)) | (1 << (LaTeXParser.COLON - 17)))) != 0)):
self._errHandler.recoverInline(self)
else:
self._errHandler.reportMatch(self)
self.consume()
self.state = 128
self.mp_nofunc(3)
self.state = 133
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input,3,self._ctx)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.unrollRecursionContexts(_parentctx)
return localctx
class UnaryContext(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def unary(self):
return self.getTypedRuleContext(LaTeXParser.UnaryContext,0)
def ADD(self):
return self.getToken(LaTeXParser.ADD, 0)
def SUB(self):
return self.getToken(LaTeXParser.SUB, 0)
def postfix(self, i:int=None):
if i is None:
return self.getTypedRuleContexts(LaTeXParser.PostfixContext)
else:
return self.getTypedRuleContext(LaTeXParser.PostfixContext,i)
def getRuleIndex(self):
return LaTeXParser.RULE_unary
def unary(self):
localctx = LaTeXParser.UnaryContext(self, self._ctx, self.state)
self.enterRule(localctx, 14, self.RULE_unary)
self._la = 0 # Token type
try:
self.state = 141
self._errHandler.sync(self)
token = self._input.LA(1)
if token in [LaTeXParser.ADD, LaTeXParser.SUB]:
self.enterOuterAlt(localctx, 1)
self.state = 134
_la = self._input.LA(1)
if not(_la==LaTeXParser.ADD or _la==LaTeXParser.SUB):
self._errHandler.recoverInline(self)
else:
self._errHandler.reportMatch(self)
self.consume()
self.state = 135
self.unary()
pass
elif token in [LaTeXParser.L_PAREN, LaTeXParser.L_BRACE, LaTeXParser.L_BRACE_LITERAL, LaTeXParser.L_BRACKET, LaTeXParser.BAR, LaTeXParser.L_BAR, LaTeXParser.L_ANGLE, LaTeXParser.FUNC_LIM, LaTeXParser.FUNC_INT, LaTeXParser.FUNC_SUM, LaTeXParser.FUNC_PROD, LaTeXParser.FUNC_EXP, LaTeXParser.FUNC_LOG, LaTeXParser.FUNC_LG, LaTeXParser.FUNC_LN, LaTeXParser.FUNC_SIN, LaTeXParser.FUNC_COS, LaTeXParser.FUNC_TAN, LaTeXParser.FUNC_CSC, LaTeXParser.FUNC_SEC, LaTeXParser.FUNC_COT, LaTeXParser.FUNC_ARCSIN, LaTeXParser.FUNC_ARCCOS, LaTeXParser.FUNC_ARCTAN, LaTeXParser.FUNC_ARCCSC, LaTeXParser.FUNC_ARCSEC, LaTeXParser.FUNC_ARCCOT, LaTeXParser.FUNC_SINH, LaTeXParser.FUNC_COSH, LaTeXParser.FUNC_TANH, LaTeXParser.FUNC_ARSINH, LaTeXParser.FUNC_ARCOSH, LaTeXParser.FUNC_ARTANH, LaTeXParser.L_FLOOR, LaTeXParser.L_CEIL, LaTeXParser.FUNC_SQRT, LaTeXParser.FUNC_OVERLINE, LaTeXParser.CMD_FRAC, LaTeXParser.CMD_BINOM, LaTeXParser.CMD_DBINOM, LaTeXParser.CMD_TBINOM, LaTeXParser.CMD_MATHIT, LaTeXParser.DIFFERENTIAL, LaTeXParser.LETTER, LaTeXParser.DIGIT, LaTeXParser.SYMBOL]:
self.enterOuterAlt(localctx, 2)
self.state = 137
self._errHandler.sync(self)
_alt = 1
while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:
if _alt == 1:
self.state = 136
self.postfix()
else:
raise NoViableAltException(self)
self.state = 139
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input,4,self._ctx)
pass
else:
raise NoViableAltException(self)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class Unary_nofuncContext(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def unary_nofunc(self):
return self.getTypedRuleContext(LaTeXParser.Unary_nofuncContext,0)
def ADD(self):
return self.getToken(LaTeXParser.ADD, 0)
def SUB(self):
return self.getToken(LaTeXParser.SUB, 0)
def postfix(self):
return self.getTypedRuleContext(LaTeXParser.PostfixContext,0)
def postfix_nofunc(self, i:int=None):
if i is None:
return self.getTypedRuleContexts(LaTeXParser.Postfix_nofuncContext)
else:
return self.getTypedRuleContext(LaTeXParser.Postfix_nofuncContext,i)
def getRuleIndex(self):
return LaTeXParser.RULE_unary_nofunc
def unary_nofunc(self):
localctx = LaTeXParser.Unary_nofuncContext(self, self._ctx, self.state)
self.enterRule(localctx, 16, self.RULE_unary_nofunc)
self._la = 0 # Token type
try:
self.state = 152
self._errHandler.sync(self)
token = self._input.LA(1)
if token in [LaTeXParser.ADD, LaTeXParser.SUB]:
self.enterOuterAlt(localctx, 1)
self.state = 143
_la = self._input.LA(1)
if not(_la==LaTeXParser.ADD or _la==LaTeXParser.SUB):
self._errHandler.recoverInline(self)
else:
self._errHandler.reportMatch(self)
self.consume()
self.state = 144
self.unary_nofunc()
pass
elif token in [LaTeXParser.L_PAREN, LaTeXParser.L_BRACE, LaTeXParser.L_BRACE_LITERAL, LaTeXParser.L_BRACKET, LaTeXParser.BAR, LaTeXParser.L_BAR, LaTeXParser.L_ANGLE, LaTeXParser.FUNC_LIM, LaTeXParser.FUNC_INT, LaTeXParser.FUNC_SUM, LaTeXParser.FUNC_PROD, LaTeXParser.FUNC_EXP, LaTeXParser.FUNC_LOG, LaTeXParser.FUNC_LG, LaTeXParser.FUNC_LN, LaTeXParser.FUNC_SIN, LaTeXParser.FUNC_COS, LaTeXParser.FUNC_TAN, LaTeXParser.FUNC_CSC, LaTeXParser.FUNC_SEC, LaTeXParser.FUNC_COT, LaTeXParser.FUNC_ARCSIN, LaTeXParser.FUNC_ARCCOS, LaTeXParser.FUNC_ARCTAN, LaTeXParser.FUNC_ARCCSC, LaTeXParser.FUNC_ARCSEC, LaTeXParser.FUNC_ARCCOT, LaTeXParser.FUNC_SINH, LaTeXParser.FUNC_COSH, LaTeXParser.FUNC_TANH, LaTeXParser.FUNC_ARSINH, LaTeXParser.FUNC_ARCOSH, LaTeXParser.FUNC_ARTANH, LaTeXParser.L_FLOOR, LaTeXParser.L_CEIL, LaTeXParser.FUNC_SQRT, LaTeXParser.FUNC_OVERLINE, LaTeXParser.CMD_FRAC, LaTeXParser.CMD_BINOM, LaTeXParser.CMD_DBINOM, LaTeXParser.CMD_TBINOM, LaTeXParser.CMD_MATHIT, LaTeXParser.DIFFERENTIAL, LaTeXParser.LETTER, LaTeXParser.DIGIT, LaTeXParser.SYMBOL]:
self.enterOuterAlt(localctx, 2)
self.state = 145
self.postfix()
self.state = 149
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input,6,self._ctx)
while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:
if _alt==1:
self.state = 146
self.postfix_nofunc()
self.state = 151
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input,6,self._ctx)
pass
else:
raise NoViableAltException(self)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class PostfixContext(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def exp(self):
return self.getTypedRuleContext(LaTeXParser.ExpContext,0)
def postfix_op(self, i:int=None):
if i is None:
return self.getTypedRuleContexts(LaTeXParser.Postfix_opContext)
else:
return self.getTypedRuleContext(LaTeXParser.Postfix_opContext,i)
def getRuleIndex(self):
return LaTeXParser.RULE_postfix
def postfix(self):
localctx = LaTeXParser.PostfixContext(self, self._ctx, self.state)
self.enterRule(localctx, 18, self.RULE_postfix)
try:
self.enterOuterAlt(localctx, 1)
self.state = 154
self.exp(0)
self.state = 158
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input,8,self._ctx)
while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:
if _alt==1:
self.state = 155
self.postfix_op()
self.state = 160
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input,8,self._ctx)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class Postfix_nofuncContext(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def exp_nofunc(self):
return self.getTypedRuleContext(LaTeXParser.Exp_nofuncContext,0)
def postfix_op(self, i:int=None):
if i is None:
return self.getTypedRuleContexts(LaTeXParser.Postfix_opContext)
else:
return self.getTypedRuleContext(LaTeXParser.Postfix_opContext,i)
def getRuleIndex(self):
return LaTeXParser.RULE_postfix_nofunc
def postfix_nofunc(self):
localctx = LaTeXParser.Postfix_nofuncContext(self, self._ctx, self.state)
self.enterRule(localctx, 20, self.RULE_postfix_nofunc)
try:
self.enterOuterAlt(localctx, 1)
self.state = 161
self.exp_nofunc(0)
self.state = 165
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input,9,self._ctx)
while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:
if _alt==1:
self.state = 162
self.postfix_op()
self.state = 167
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input,9,self._ctx)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class Postfix_opContext(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def BANG(self):
return self.getToken(LaTeXParser.BANG, 0)
def eval_at(self):
return self.getTypedRuleContext(LaTeXParser.Eval_atContext,0)
def getRuleIndex(self):
return LaTeXParser.RULE_postfix_op
def postfix_op(self):
localctx = LaTeXParser.Postfix_opContext(self, self._ctx, self.state)
self.enterRule(localctx, 22, self.RULE_postfix_op)
try:
self.state = 170
self._errHandler.sync(self)
token = self._input.LA(1)
if token in [LaTeXParser.BANG]:
self.enterOuterAlt(localctx, 1)
self.state = 168
self.match(LaTeXParser.BANG)
pass
elif token in [LaTeXParser.BAR]:
self.enterOuterAlt(localctx, 2)
self.state = 169
self.eval_at()
pass
else:
raise NoViableAltException(self)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class Eval_atContext(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def BAR(self):
return self.getToken(LaTeXParser.BAR, 0)
def eval_at_sup(self):
return self.getTypedRuleContext(LaTeXParser.Eval_at_supContext,0)
def eval_at_sub(self):
return self.getTypedRuleContext(LaTeXParser.Eval_at_subContext,0)
def getRuleIndex(self):
return LaTeXParser.RULE_eval_at
def eval_at(self):
localctx = LaTeXParser.Eval_atContext(self, self._ctx, self.state)
self.enterRule(localctx, 24, self.RULE_eval_at)
try:
self.enterOuterAlt(localctx, 1)
self.state = 172
self.match(LaTeXParser.BAR)
self.state = 178
self._errHandler.sync(self)
la_ = self._interp.adaptivePredict(self._input,11,self._ctx)
if la_ == 1:
self.state = 173
self.eval_at_sup()
pass
elif la_ == 2:
self.state = 174
self.eval_at_sub()
pass
elif la_ == 3:
self.state = 175
self.eval_at_sup()
self.state = 176
self.eval_at_sub()
pass
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class Eval_at_subContext(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def UNDERSCORE(self):
return self.getToken(LaTeXParser.UNDERSCORE, 0)
def L_BRACE(self):
return self.getToken(LaTeXParser.L_BRACE, 0)
def R_BRACE(self):
return self.getToken(LaTeXParser.R_BRACE, 0)
def expr(self):
return self.getTypedRuleContext(LaTeXParser.ExprContext,0)
def equality(self):
return self.getTypedRuleContext(LaTeXParser.EqualityContext,0)
def getRuleIndex(self):
return LaTeXParser.RULE_eval_at_sub
def eval_at_sub(self):
localctx = LaTeXParser.Eval_at_subContext(self, self._ctx, self.state)
self.enterRule(localctx, 26, self.RULE_eval_at_sub)
try:
self.enterOuterAlt(localctx, 1)
self.state = 180
self.match(LaTeXParser.UNDERSCORE)
self.state = 181
self.match(LaTeXParser.L_BRACE)
self.state = 184
self._errHandler.sync(self)
la_ = self._interp.adaptivePredict(self._input,12,self._ctx)
if la_ == 1:
self.state = 182
self.expr()
pass
elif la_ == 2:
self.state = 183
self.equality()
pass
self.state = 186
self.match(LaTeXParser.R_BRACE)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class Eval_at_supContext(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def CARET(self):
return self.getToken(LaTeXParser.CARET, 0)
def L_BRACE(self):
return self.getToken(LaTeXParser.L_BRACE, 0)
def R_BRACE(self):
return self.getToken(LaTeXParser.R_BRACE, 0)
def expr(self):
return self.getTypedRuleContext(LaTeXParser.ExprContext,0)
def equality(self):
return self.getTypedRuleContext(LaTeXParser.EqualityContext,0)
def getRuleIndex(self):
return LaTeXParser.RULE_eval_at_sup
def eval_at_sup(self):
localctx = LaTeXParser.Eval_at_supContext(self, self._ctx, self.state)
self.enterRule(localctx, 28, self.RULE_eval_at_sup)
try:
self.enterOuterAlt(localctx, 1)
self.state = 188
self.match(LaTeXParser.CARET)
self.state = 189
self.match(LaTeXParser.L_BRACE)
self.state = 192
self._errHandler.sync(self)
la_ = self._interp.adaptivePredict(self._input,13,self._ctx)
if la_ == 1:
self.state = 190
self.expr()
pass
elif la_ == 2:
self.state = 191
self.equality()
pass
self.state = 194
self.match(LaTeXParser.R_BRACE)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class ExpContext(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def comp(self):
return self.getTypedRuleContext(LaTeXParser.CompContext,0)
def exp(self):
return self.getTypedRuleContext(LaTeXParser.ExpContext,0)
def CARET(self):
return self.getToken(LaTeXParser.CARET, 0)
def atom(self):
return self.getTypedRuleContext(LaTeXParser.AtomContext,0)
def L_BRACE(self):
return self.getToken(LaTeXParser.L_BRACE, 0)
def expr(self):
return self.getTypedRuleContext(LaTeXParser.ExprContext,0)
def R_BRACE(self):
return self.getToken(LaTeXParser.R_BRACE, 0)
def subexpr(self):
return self.getTypedRuleContext(LaTeXParser.SubexprContext,0)
def getRuleIndex(self):
return LaTeXParser.RULE_exp
def exp(self, _p:int=0):
_parentctx = self._ctx
_parentState = self.state
localctx = LaTeXParser.ExpContext(self, self._ctx, _parentState)
_prevctx = localctx
_startState = 30
self.enterRecursionRule(localctx, 30, self.RULE_exp, _p)
try:
self.enterOuterAlt(localctx, 1)
self.state = 197
self.comp()
self._ctx.stop = self._input.LT(-1)
self.state = 213
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input,16,self._ctx)
while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:
if _alt==1:
if self._parseListeners is not None:
self.triggerExitRuleEvent()
_prevctx = localctx
localctx = LaTeXParser.ExpContext(self, _parentctx, _parentState)
self.pushNewRecursionContext(localctx, _startState, self.RULE_exp)
self.state = 199
if not self.precpred(self._ctx, 2):
from antlr4.error.Errors import FailedPredicateException
raise FailedPredicateException(self, "self.precpred(self._ctx, 2)")
self.state = 200
self.match(LaTeXParser.CARET)
self.state = 206
self._errHandler.sync(self)
token = self._input.LA(1)
if token in [LaTeXParser.BAR, LaTeXParser.L_BAR, LaTeXParser.L_ANGLE, LaTeXParser.CMD_FRAC, LaTeXParser.CMD_BINOM, LaTeXParser.CMD_DBINOM, LaTeXParser.CMD_TBINOM, LaTeXParser.CMD_MATHIT, LaTeXParser.DIFFERENTIAL, LaTeXParser.LETTER, LaTeXParser.DIGIT, LaTeXParser.SYMBOL]:
self.state = 201
self.atom()
pass
elif token in [LaTeXParser.L_BRACE]:
self.state = 202
self.match(LaTeXParser.L_BRACE)
self.state = 203
self.expr()
self.state = 204
self.match(LaTeXParser.R_BRACE)
pass
else:
raise NoViableAltException(self)
self.state = 209
self._errHandler.sync(self)
la_ = self._interp.adaptivePredict(self._input,15,self._ctx)
if la_ == 1:
self.state = 208
self.subexpr()
self.state = 215
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input,16,self._ctx)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.unrollRecursionContexts(_parentctx)
return localctx
class Exp_nofuncContext(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def comp_nofunc(self):
return self.getTypedRuleContext(LaTeXParser.Comp_nofuncContext,0)
def exp_nofunc(self):
return self.getTypedRuleContext(LaTeXParser.Exp_nofuncContext,0)
def CARET(self):
return self.getToken(LaTeXParser.CARET, 0)
def atom(self):
return self.getTypedRuleContext(LaTeXParser.AtomContext,0)
def L_BRACE(self):
return self.getToken(LaTeXParser.L_BRACE, 0)
def expr(self):
return self.getTypedRuleContext(LaTeXParser.ExprContext,0)
def R_BRACE(self):
return self.getToken(LaTeXParser.R_BRACE, 0)
def subexpr(self):
return self.getTypedRuleContext(LaTeXParser.SubexprContext,0)
def getRuleIndex(self):
return LaTeXParser.RULE_exp_nofunc
def exp_nofunc(self, _p:int=0):
_parentctx = self._ctx
_parentState = self.state
localctx = LaTeXParser.Exp_nofuncContext(self, self._ctx, _parentState)
_prevctx = localctx
_startState = 32
self.enterRecursionRule(localctx, 32, self.RULE_exp_nofunc, _p)
try:
self.enterOuterAlt(localctx, 1)
self.state = 217
self.comp_nofunc()
self._ctx.stop = self._input.LT(-1)
self.state = 233
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input,19,self._ctx)
while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:
if _alt==1:
if self._parseListeners is not None:
self.triggerExitRuleEvent()
_prevctx = localctx
localctx = LaTeXParser.Exp_nofuncContext(self, _parentctx, _parentState)
self.pushNewRecursionContext(localctx, _startState, self.RULE_exp_nofunc)
self.state = 219
if not self.precpred(self._ctx, 2):
from antlr4.error.Errors import FailedPredicateException
raise FailedPredicateException(self, "self.precpred(self._ctx, 2)")
self.state = 220
self.match(LaTeXParser.CARET)
self.state = 226
self._errHandler.sync(self)
token = self._input.LA(1)
if token in [LaTeXParser.BAR, LaTeXParser.L_BAR, LaTeXParser.L_ANGLE, LaTeXParser.CMD_FRAC, LaTeXParser.CMD_BINOM, LaTeXParser.CMD_DBINOM, LaTeXParser.CMD_TBINOM, LaTeXParser.CMD_MATHIT, LaTeXParser.DIFFERENTIAL, LaTeXParser.LETTER, LaTeXParser.DIGIT, LaTeXParser.SYMBOL]:
self.state = 221
self.atom()
pass
elif token in [LaTeXParser.L_BRACE]:
self.state = 222
self.match(LaTeXParser.L_BRACE)
self.state = 223
self.expr()
self.state = 224
self.match(LaTeXParser.R_BRACE)
pass
else:
raise NoViableAltException(self)
self.state = 229
self._errHandler.sync(self)
la_ = self._interp.adaptivePredict(self._input,18,self._ctx)
if la_ == 1:
self.state = 228
self.subexpr()
self.state = 235
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input,19,self._ctx)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.unrollRecursionContexts(_parentctx)
return localctx
class CompContext(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def group(self):
return self.getTypedRuleContext(LaTeXParser.GroupContext,0)
def abs_group(self):
return self.getTypedRuleContext(LaTeXParser.Abs_groupContext,0)
def func(self):
return self.getTypedRuleContext(LaTeXParser.FuncContext,0)
def atom(self):
return self.getTypedRuleContext(LaTeXParser.AtomContext,0)
def floor(self):
return self.getTypedRuleContext(LaTeXParser.FloorContext,0)
def ceil(self):
return self.getTypedRuleContext(LaTeXParser.CeilContext,0)
def getRuleIndex(self):
return LaTeXParser.RULE_comp
def comp(self):
localctx = LaTeXParser.CompContext(self, self._ctx, self.state)
self.enterRule(localctx, 34, self.RULE_comp)
try:
self.state = 242
self._errHandler.sync(self)
la_ = self._interp.adaptivePredict(self._input,20,self._ctx)
if la_ == 1:
self.enterOuterAlt(localctx, 1)
self.state = 236
self.group()
pass
elif la_ == 2:
self.enterOuterAlt(localctx, 2)
self.state = 237
self.abs_group()
pass
elif la_ == 3:
self.enterOuterAlt(localctx, 3)
self.state = 238
self.func()
pass
elif la_ == 4:
self.enterOuterAlt(localctx, 4)
self.state = 239
self.atom()
pass
elif la_ == 5:
self.enterOuterAlt(localctx, 5)
self.state = 240
self.floor()
pass
elif la_ == 6:
self.enterOuterAlt(localctx, 6)
self.state = 241
self.ceil()
pass
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class Comp_nofuncContext(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def group(self):
return self.getTypedRuleContext(LaTeXParser.GroupContext,0)
def abs_group(self):
return self.getTypedRuleContext(LaTeXParser.Abs_groupContext,0)
def atom(self):
return self.getTypedRuleContext(LaTeXParser.AtomContext,0)
def floor(self):
return self.getTypedRuleContext(LaTeXParser.FloorContext,0)
def ceil(self):
return self.getTypedRuleContext(LaTeXParser.CeilContext,0)
def getRuleIndex(self):
return LaTeXParser.RULE_comp_nofunc
def comp_nofunc(self):
localctx = LaTeXParser.Comp_nofuncContext(self, self._ctx, self.state)
self.enterRule(localctx, 36, self.RULE_comp_nofunc)
try:
self.state = 249
self._errHandler.sync(self)
la_ = self._interp.adaptivePredict(self._input,21,self._ctx)
if la_ == 1:
self.enterOuterAlt(localctx, 1)
self.state = 244
self.group()
pass
elif la_ == 2:
self.enterOuterAlt(localctx, 2)
self.state = 245
self.abs_group()
pass
elif la_ == 3:
self.enterOuterAlt(localctx, 3)
self.state = 246
self.atom()
pass
elif la_ == 4:
self.enterOuterAlt(localctx, 4)
self.state = 247
self.floor()
pass
elif la_ == 5:
self.enterOuterAlt(localctx, 5)
self.state = 248
self.ceil()
pass
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class GroupContext(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def L_PAREN(self):
return self.getToken(LaTeXParser.L_PAREN, 0)
def expr(self):
return self.getTypedRuleContext(LaTeXParser.ExprContext,0)
def R_PAREN(self):
return self.getToken(LaTeXParser.R_PAREN, 0)
def L_BRACKET(self):
return self.getToken(LaTeXParser.L_BRACKET, 0)
def R_BRACKET(self):
return self.getToken(LaTeXParser.R_BRACKET, 0)
def L_BRACE(self):
return self.getToken(LaTeXParser.L_BRACE, 0)
def R_BRACE(self):
return self.getToken(LaTeXParser.R_BRACE, 0)
def L_BRACE_LITERAL(self):
return self.getToken(LaTeXParser.L_BRACE_LITERAL, 0)
def R_BRACE_LITERAL(self):
return self.getToken(LaTeXParser.R_BRACE_LITERAL, 0)
def getRuleIndex(self):
return LaTeXParser.RULE_group
def group(self):
localctx = LaTeXParser.GroupContext(self, self._ctx, self.state)
self.enterRule(localctx, 38, self.RULE_group)
try:
self.state = 267
self._errHandler.sync(self)
token = self._input.LA(1)
if token in [LaTeXParser.L_PAREN]:
self.enterOuterAlt(localctx, 1)
self.state = 251
self.match(LaTeXParser.L_PAREN)
self.state = 252
self.expr()
self.state = 253
self.match(LaTeXParser.R_PAREN)
pass
elif token in [LaTeXParser.L_BRACKET]:
self.enterOuterAlt(localctx, 2)
self.state = 255
self.match(LaTeXParser.L_BRACKET)
self.state = 256
self.expr()
self.state = 257
self.match(LaTeXParser.R_BRACKET)
pass
elif token in [LaTeXParser.L_BRACE]:
self.enterOuterAlt(localctx, 3)
self.state = 259
self.match(LaTeXParser.L_BRACE)
self.state = 260
self.expr()
self.state = 261
self.match(LaTeXParser.R_BRACE)
pass
elif token in [LaTeXParser.L_BRACE_LITERAL]:
self.enterOuterAlt(localctx, 4)
self.state = 263
self.match(LaTeXParser.L_BRACE_LITERAL)
self.state = 264
self.expr()
self.state = 265
self.match(LaTeXParser.R_BRACE_LITERAL)
pass
else:
raise NoViableAltException(self)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class Abs_groupContext(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def BAR(self, i:int=None):
if i is None:
return self.getTokens(LaTeXParser.BAR)
else:
return self.getToken(LaTeXParser.BAR, i)
def expr(self):
return self.getTypedRuleContext(LaTeXParser.ExprContext,0)
def getRuleIndex(self):
return LaTeXParser.RULE_abs_group
def abs_group(self):
localctx = LaTeXParser.Abs_groupContext(self, self._ctx, self.state)
self.enterRule(localctx, 40, self.RULE_abs_group)
try:
self.enterOuterAlt(localctx, 1)
self.state = 269
self.match(LaTeXParser.BAR)
self.state = 270
self.expr()
self.state = 271
self.match(LaTeXParser.BAR)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class NumberContext(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def DIGIT(self, i:int=None):
if i is None:
return self.getTokens(LaTeXParser.DIGIT)
else:
return self.getToken(LaTeXParser.DIGIT, i)
def getRuleIndex(self):
return LaTeXParser.RULE_number
def number(self):
localctx = LaTeXParser.NumberContext(self, self._ctx, self.state)
self.enterRule(localctx, 42, self.RULE_number)
try:
self.enterOuterAlt(localctx, 1)
self.state = 274
self._errHandler.sync(self)
_alt = 1
while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:
if _alt == 1:
self.state = 273
self.match(LaTeXParser.DIGIT)
else:
raise NoViableAltException(self)
self.state = 276
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input,23,self._ctx)
self.state = 284
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input,24,self._ctx)
while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:
if _alt==1:
self.state = 278
self.match(LaTeXParser.T__0)
self.state = 279
self.match(LaTeXParser.DIGIT)
self.state = 280
self.match(LaTeXParser.DIGIT)
self.state = 281
self.match(LaTeXParser.DIGIT)
self.state = 286
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input,24,self._ctx)
self.state = 293
self._errHandler.sync(self)
la_ = self._interp.adaptivePredict(self._input,26,self._ctx)
if la_ == 1:
self.state = 287
self.match(LaTeXParser.T__1)
self.state = 289
self._errHandler.sync(self)
_alt = 1
while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:
if _alt == 1:
self.state = 288
self.match(LaTeXParser.DIGIT)
else:
raise NoViableAltException(self)
self.state = 291
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input,25,self._ctx)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class AtomContext(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def LETTER(self):
return self.getToken(LaTeXParser.LETTER, 0)
def SYMBOL(self):
return self.getToken(LaTeXParser.SYMBOL, 0)
def subexpr(self):
return self.getTypedRuleContext(LaTeXParser.SubexprContext,0)
def SINGLE_QUOTES(self):
return self.getToken(LaTeXParser.SINGLE_QUOTES, 0)
def number(self):
return self.getTypedRuleContext(LaTeXParser.NumberContext,0)
def DIFFERENTIAL(self):
return self.getToken(LaTeXParser.DIFFERENTIAL, 0)
def mathit(self):
return self.getTypedRuleContext(LaTeXParser.MathitContext,0)
def frac(self):
return self.getTypedRuleContext(LaTeXParser.FracContext,0)
def binom(self):
return self.getTypedRuleContext(LaTeXParser.BinomContext,0)
def bra(self):
return self.getTypedRuleContext(LaTeXParser.BraContext,0)
def ket(self):
return self.getTypedRuleContext(LaTeXParser.KetContext,0)
def getRuleIndex(self):
return LaTeXParser.RULE_atom
def atom(self):
localctx = LaTeXParser.AtomContext(self, self._ctx, self.state)
self.enterRule(localctx, 44, self.RULE_atom)
self._la = 0 # Token type
try:
self.state = 317
self._errHandler.sync(self)
token = self._input.LA(1)
if token in [LaTeXParser.LETTER, LaTeXParser.SYMBOL]:
self.enterOuterAlt(localctx, 1)
self.state = 295
_la = self._input.LA(1)
if not(_la==LaTeXParser.LETTER or _la==LaTeXParser.SYMBOL):
self._errHandler.recoverInline(self)
else:
self._errHandler.reportMatch(self)
self.consume()
self.state = 308
self._errHandler.sync(self)
la_ = self._interp.adaptivePredict(self._input,31,self._ctx)
if la_ == 1:
self.state = 297
self._errHandler.sync(self)
la_ = self._interp.adaptivePredict(self._input,27,self._ctx)
if la_ == 1:
self.state = 296
self.subexpr()
self.state = 300
self._errHandler.sync(self)
la_ = self._interp.adaptivePredict(self._input,28,self._ctx)
if la_ == 1:
self.state = 299
self.match(LaTeXParser.SINGLE_QUOTES)
pass
elif la_ == 2:
self.state = 303
self._errHandler.sync(self)
la_ = self._interp.adaptivePredict(self._input,29,self._ctx)
if la_ == 1:
self.state = 302
self.match(LaTeXParser.SINGLE_QUOTES)
self.state = 306
self._errHandler.sync(self)
la_ = self._interp.adaptivePredict(self._input,30,self._ctx)
if la_ == 1:
self.state = 305
self.subexpr()
pass
pass
elif token in [LaTeXParser.DIGIT]:
self.enterOuterAlt(localctx, 2)
self.state = 310
self.number()
pass
elif token in [LaTeXParser.DIFFERENTIAL]:
self.enterOuterAlt(localctx, 3)
self.state = 311
self.match(LaTeXParser.DIFFERENTIAL)
pass
elif token in [LaTeXParser.CMD_MATHIT]:
self.enterOuterAlt(localctx, 4)
self.state = 312
self.mathit()
pass
elif token in [LaTeXParser.CMD_FRAC]:
self.enterOuterAlt(localctx, 5)
self.state = 313
self.frac()
pass
elif token in [LaTeXParser.CMD_BINOM, LaTeXParser.CMD_DBINOM, LaTeXParser.CMD_TBINOM]:
self.enterOuterAlt(localctx, 6)
self.state = 314
self.binom()
pass
elif token in [LaTeXParser.L_ANGLE]:
self.enterOuterAlt(localctx, 7)
self.state = 315
self.bra()
pass
elif token in [LaTeXParser.BAR, LaTeXParser.L_BAR]:
self.enterOuterAlt(localctx, 8)
self.state = 316
self.ket()
pass
else:
raise NoViableAltException(self)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class BraContext(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def L_ANGLE(self):
return self.getToken(LaTeXParser.L_ANGLE, 0)
def expr(self):
return self.getTypedRuleContext(LaTeXParser.ExprContext,0)
def R_BAR(self):
return self.getToken(LaTeXParser.R_BAR, 0)
def BAR(self):
return self.getToken(LaTeXParser.BAR, 0)
def getRuleIndex(self):
return LaTeXParser.RULE_bra
def bra(self):
localctx = LaTeXParser.BraContext(self, self._ctx, self.state)
self.enterRule(localctx, 46, self.RULE_bra)
self._la = 0 # Token type
try:
self.enterOuterAlt(localctx, 1)
self.state = 319
self.match(LaTeXParser.L_ANGLE)
self.state = 320
self.expr()
self.state = 321
_la = self._input.LA(1)
if not(_la==LaTeXParser.BAR or _la==LaTeXParser.R_BAR):
self._errHandler.recoverInline(self)
else:
self._errHandler.reportMatch(self)
self.consume()
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class KetContext(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def expr(self):
return self.getTypedRuleContext(LaTeXParser.ExprContext,0)
def R_ANGLE(self):
return self.getToken(LaTeXParser.R_ANGLE, 0)
def L_BAR(self):
return self.getToken(LaTeXParser.L_BAR, 0)
def BAR(self):
return self.getToken(LaTeXParser.BAR, 0)
def getRuleIndex(self):
return LaTeXParser.RULE_ket
def ket(self):
localctx = LaTeXParser.KetContext(self, self._ctx, self.state)
self.enterRule(localctx, 48, self.RULE_ket)
self._la = 0 # Token type
try:
self.enterOuterAlt(localctx, 1)
self.state = 323
_la = self._input.LA(1)
if not(_la==LaTeXParser.BAR or _la==LaTeXParser.L_BAR):
self._errHandler.recoverInline(self)
else:
self._errHandler.reportMatch(self)
self.consume()
self.state = 324
self.expr()
self.state = 325
self.match(LaTeXParser.R_ANGLE)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class MathitContext(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def CMD_MATHIT(self):
return self.getToken(LaTeXParser.CMD_MATHIT, 0)
def L_BRACE(self):
return self.getToken(LaTeXParser.L_BRACE, 0)
def mathit_text(self):
return self.getTypedRuleContext(LaTeXParser.Mathit_textContext,0)
def R_BRACE(self):
return self.getToken(LaTeXParser.R_BRACE, 0)
def getRuleIndex(self):
return LaTeXParser.RULE_mathit
def mathit(self):
localctx = LaTeXParser.MathitContext(self, self._ctx, self.state)
self.enterRule(localctx, 50, self.RULE_mathit)
try:
self.enterOuterAlt(localctx, 1)
self.state = 327
self.match(LaTeXParser.CMD_MATHIT)
self.state = 328
self.match(LaTeXParser.L_BRACE)
self.state = 329
self.mathit_text()
self.state = 330
self.match(LaTeXParser.R_BRACE)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class Mathit_textContext(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def LETTER(self, i:int=None):
if i is None:
return self.getTokens(LaTeXParser.LETTER)
else:
return self.getToken(LaTeXParser.LETTER, i)
def getRuleIndex(self):
return LaTeXParser.RULE_mathit_text
def mathit_text(self):
localctx = LaTeXParser.Mathit_textContext(self, self._ctx, self.state)
self.enterRule(localctx, 52, self.RULE_mathit_text)
self._la = 0 # Token type
try:
self.enterOuterAlt(localctx, 1)
self.state = 335
self._errHandler.sync(self)
_la = self._input.LA(1)
while _la==LaTeXParser.LETTER:
self.state = 332
self.match(LaTeXParser.LETTER)
self.state = 337
self._errHandler.sync(self)
_la = self._input.LA(1)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class FracContext(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
self.upperd = None # Token
self.upper = None # ExprContext
self.lowerd = None # Token
self.lower = None # ExprContext
def CMD_FRAC(self):
return self.getToken(LaTeXParser.CMD_FRAC, 0)
def L_BRACE(self, i:int=None):
if i is None:
return self.getTokens(LaTeXParser.L_BRACE)
else:
return self.getToken(LaTeXParser.L_BRACE, i)
def R_BRACE(self, i:int=None):
if i is None:
return self.getTokens(LaTeXParser.R_BRACE)
else:
return self.getToken(LaTeXParser.R_BRACE, i)
def DIGIT(self, i:int=None):
if i is None:
return self.getTokens(LaTeXParser.DIGIT)
else:
return self.getToken(LaTeXParser.DIGIT, i)
def expr(self, i:int=None):
if i is None:
return self.getTypedRuleContexts(LaTeXParser.ExprContext)
else:
return self.getTypedRuleContext(LaTeXParser.ExprContext,i)
def getRuleIndex(self):
return LaTeXParser.RULE_frac
def frac(self):
localctx = LaTeXParser.FracContext(self, self._ctx, self.state)
self.enterRule(localctx, 54, self.RULE_frac)
try:
self.enterOuterAlt(localctx, 1)
self.state = 338
self.match(LaTeXParser.CMD_FRAC)
self.state = 344
self._errHandler.sync(self)
token = self._input.LA(1)
if token in [LaTeXParser.DIGIT]:
self.state = 339
localctx.upperd = self.match(LaTeXParser.DIGIT)
pass
elif token in [LaTeXParser.L_BRACE]:
self.state = 340
self.match(LaTeXParser.L_BRACE)
self.state = 341
localctx.upper = self.expr()
self.state = 342
self.match(LaTeXParser.R_BRACE)
pass
else:
raise NoViableAltException(self)
self.state = 351
self._errHandler.sync(self)
token = self._input.LA(1)
if token in [LaTeXParser.DIGIT]:
self.state = 346
localctx.lowerd = self.match(LaTeXParser.DIGIT)
pass
elif token in [LaTeXParser.L_BRACE]:
self.state = 347
self.match(LaTeXParser.L_BRACE)
self.state = 348
localctx.lower = self.expr()
self.state = 349
self.match(LaTeXParser.R_BRACE)
pass
else:
raise NoViableAltException(self)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class BinomContext(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
self.n = None # ExprContext
self.k = None # ExprContext
def L_BRACE(self, i:int=None):
if i is None:
return self.getTokens(LaTeXParser.L_BRACE)
else:
return self.getToken(LaTeXParser.L_BRACE, i)
def R_BRACE(self, i:int=None):
if i is None:
return self.getTokens(LaTeXParser.R_BRACE)
else:
return self.getToken(LaTeXParser.R_BRACE, i)
def CMD_BINOM(self):
return self.getToken(LaTeXParser.CMD_BINOM, 0)
def CMD_DBINOM(self):
return self.getToken(LaTeXParser.CMD_DBINOM, 0)
def CMD_TBINOM(self):
return self.getToken(LaTeXParser.CMD_TBINOM, 0)
def expr(self, i:int=None):
if i is None:
return self.getTypedRuleContexts(LaTeXParser.ExprContext)
else:
return self.getTypedRuleContext(LaTeXParser.ExprContext,i)
def getRuleIndex(self):
return LaTeXParser.RULE_binom
def binom(self):
localctx = LaTeXParser.BinomContext(self, self._ctx, self.state)
self.enterRule(localctx, 56, self.RULE_binom)
self._la = 0 # Token type
try:
self.enterOuterAlt(localctx, 1)
self.state = 353
_la = self._input.LA(1)
if not(((((_la - 69)) & ~0x3f) == 0 and ((1 << (_la - 69)) & ((1 << (LaTeXParser.CMD_BINOM - 69)) | (1 << (LaTeXParser.CMD_DBINOM - 69)) | (1 << (LaTeXParser.CMD_TBINOM - 69)))) != 0)):
self._errHandler.recoverInline(self)
else:
self._errHandler.reportMatch(self)
self.consume()
self.state = 354
self.match(LaTeXParser.L_BRACE)
self.state = 355
localctx.n = self.expr()
self.state = 356
self.match(LaTeXParser.R_BRACE)
self.state = 357
self.match(LaTeXParser.L_BRACE)
self.state = 358
localctx.k = self.expr()
self.state = 359
self.match(LaTeXParser.R_BRACE)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class FloorContext(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
self.val = None # ExprContext
def L_FLOOR(self):
return self.getToken(LaTeXParser.L_FLOOR, 0)
def R_FLOOR(self):
return self.getToken(LaTeXParser.R_FLOOR, 0)
def expr(self):
return self.getTypedRuleContext(LaTeXParser.ExprContext,0)
def getRuleIndex(self):
return LaTeXParser.RULE_floor
def floor(self):
localctx = LaTeXParser.FloorContext(self, self._ctx, self.state)
self.enterRule(localctx, 58, self.RULE_floor)
try:
self.enterOuterAlt(localctx, 1)
self.state = 361
self.match(LaTeXParser.L_FLOOR)
self.state = 362
localctx.val = self.expr()
self.state = 363
self.match(LaTeXParser.R_FLOOR)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class CeilContext(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
self.val = None # ExprContext
def L_CEIL(self):
return self.getToken(LaTeXParser.L_CEIL, 0)
def R_CEIL(self):
return self.getToken(LaTeXParser.R_CEIL, 0)
def expr(self):
return self.getTypedRuleContext(LaTeXParser.ExprContext,0)
def getRuleIndex(self):
return LaTeXParser.RULE_ceil
def ceil(self):
localctx = LaTeXParser.CeilContext(self, self._ctx, self.state)
self.enterRule(localctx, 60, self.RULE_ceil)
try:
self.enterOuterAlt(localctx, 1)
self.state = 365
self.match(LaTeXParser.L_CEIL)
self.state = 366
localctx.val = self.expr()
self.state = 367
self.match(LaTeXParser.R_CEIL)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class Func_normalContext(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def FUNC_EXP(self):
return self.getToken(LaTeXParser.FUNC_EXP, 0)
def FUNC_LOG(self):
return self.getToken(LaTeXParser.FUNC_LOG, 0)
def FUNC_LG(self):
return self.getToken(LaTeXParser.FUNC_LG, 0)
def FUNC_LN(self):
return self.getToken(LaTeXParser.FUNC_LN, 0)
def FUNC_SIN(self):
return self.getToken(LaTeXParser.FUNC_SIN, 0)
def FUNC_COS(self):
return self.getToken(LaTeXParser.FUNC_COS, 0)
def FUNC_TAN(self):
return self.getToken(LaTeXParser.FUNC_TAN, 0)
def FUNC_CSC(self):
return self.getToken(LaTeXParser.FUNC_CSC, 0)
def FUNC_SEC(self):
return self.getToken(LaTeXParser.FUNC_SEC, 0)
def FUNC_COT(self):
return self.getToken(LaTeXParser.FUNC_COT, 0)
def FUNC_ARCSIN(self):
return self.getToken(LaTeXParser.FUNC_ARCSIN, 0)
def FUNC_ARCCOS(self):
return self.getToken(LaTeXParser.FUNC_ARCCOS, 0)
def FUNC_ARCTAN(self):
return self.getToken(LaTeXParser.FUNC_ARCTAN, 0)
def FUNC_ARCCSC(self):
return self.getToken(LaTeXParser.FUNC_ARCCSC, 0)
def FUNC_ARCSEC(self):
return self.getToken(LaTeXParser.FUNC_ARCSEC, 0)
def FUNC_ARCCOT(self):
return self.getToken(LaTeXParser.FUNC_ARCCOT, 0)
def FUNC_SINH(self):
return self.getToken(LaTeXParser.FUNC_SINH, 0)
def FUNC_COSH(self):
return self.getToken(LaTeXParser.FUNC_COSH, 0)
def FUNC_TANH(self):
return self.getToken(LaTeXParser.FUNC_TANH, 0)
def FUNC_ARSINH(self):
return self.getToken(LaTeXParser.FUNC_ARSINH, 0)
def FUNC_ARCOSH(self):
return self.getToken(LaTeXParser.FUNC_ARCOSH, 0)
def FUNC_ARTANH(self):
return self.getToken(LaTeXParser.FUNC_ARTANH, 0)
def getRuleIndex(self):
return LaTeXParser.RULE_func_normal
def func_normal(self):
localctx = LaTeXParser.Func_normalContext(self, self._ctx, self.state)
self.enterRule(localctx, 62, self.RULE_func_normal)
self._la = 0 # Token type
try:
self.enterOuterAlt(localctx, 1)
self.state = 369
_la = self._input.LA(1)
if not((((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << LaTeXParser.FUNC_EXP) | (1 << LaTeXParser.FUNC_LOG) | (1 << LaTeXParser.FUNC_LG) | (1 << LaTeXParser.FUNC_LN) | (1 << LaTeXParser.FUNC_SIN) | (1 << LaTeXParser.FUNC_COS) | (1 << LaTeXParser.FUNC_TAN) | (1 << LaTeXParser.FUNC_CSC) | (1 << LaTeXParser.FUNC_SEC) | (1 << LaTeXParser.FUNC_COT) | (1 << LaTeXParser.FUNC_ARCSIN) | (1 << LaTeXParser.FUNC_ARCCOS) | (1 << LaTeXParser.FUNC_ARCTAN) | (1 << LaTeXParser.FUNC_ARCCSC) | (1 << LaTeXParser.FUNC_ARCSEC) | (1 << LaTeXParser.FUNC_ARCCOT) | (1 << LaTeXParser.FUNC_SINH) | (1 << LaTeXParser.FUNC_COSH) | (1 << LaTeXParser.FUNC_TANH) | (1 << LaTeXParser.FUNC_ARSINH) | (1 << LaTeXParser.FUNC_ARCOSH) | (1 << LaTeXParser.FUNC_ARTANH))) != 0)):
self._errHandler.recoverInline(self)
else:
self._errHandler.reportMatch(self)
self.consume()
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class FuncContext(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
self.root = None # ExprContext
self.base = None # ExprContext
def func_normal(self):
return self.getTypedRuleContext(LaTeXParser.Func_normalContext,0)
def L_PAREN(self):
return self.getToken(LaTeXParser.L_PAREN, 0)
def func_arg(self):
return self.getTypedRuleContext(LaTeXParser.Func_argContext,0)
def R_PAREN(self):
return self.getToken(LaTeXParser.R_PAREN, 0)
def func_arg_noparens(self):
return self.getTypedRuleContext(LaTeXParser.Func_arg_noparensContext,0)
def subexpr(self):
return self.getTypedRuleContext(LaTeXParser.SubexprContext,0)
def supexpr(self):
return self.getTypedRuleContext(LaTeXParser.SupexprContext,0)
def args(self):
return self.getTypedRuleContext(LaTeXParser.ArgsContext,0)
def LETTER(self):
return self.getToken(LaTeXParser.LETTER, 0)
def SYMBOL(self):
return self.getToken(LaTeXParser.SYMBOL, 0)
def SINGLE_QUOTES(self):
return self.getToken(LaTeXParser.SINGLE_QUOTES, 0)
def FUNC_INT(self):
return self.getToken(LaTeXParser.FUNC_INT, 0)
def DIFFERENTIAL(self):
return self.getToken(LaTeXParser.DIFFERENTIAL, 0)
def frac(self):
return self.getTypedRuleContext(LaTeXParser.FracContext,0)
def additive(self):
return self.getTypedRuleContext(LaTeXParser.AdditiveContext,0)
def FUNC_SQRT(self):
return self.getToken(LaTeXParser.FUNC_SQRT, 0)
def L_BRACE(self):
return self.getToken(LaTeXParser.L_BRACE, 0)
def R_BRACE(self):
return self.getToken(LaTeXParser.R_BRACE, 0)
def expr(self, i:int=None):
if i is None:
return self.getTypedRuleContexts(LaTeXParser.ExprContext)
else:
return self.getTypedRuleContext(LaTeXParser.ExprContext,i)
def L_BRACKET(self):
return self.getToken(LaTeXParser.L_BRACKET, 0)
def R_BRACKET(self):
return self.getToken(LaTeXParser.R_BRACKET, 0)
def FUNC_OVERLINE(self):
return self.getToken(LaTeXParser.FUNC_OVERLINE, 0)
def mp(self):
return self.getTypedRuleContext(LaTeXParser.MpContext,0)
def FUNC_SUM(self):
return self.getToken(LaTeXParser.FUNC_SUM, 0)
def FUNC_PROD(self):
return self.getToken(LaTeXParser.FUNC_PROD, 0)
def subeq(self):
return self.getTypedRuleContext(LaTeXParser.SubeqContext,0)
def FUNC_LIM(self):
return self.getToken(LaTeXParser.FUNC_LIM, 0)
def limit_sub(self):
return self.getTypedRuleContext(LaTeXParser.Limit_subContext,0)
def getRuleIndex(self):
return LaTeXParser.RULE_func
def func(self):
localctx = LaTeXParser.FuncContext(self, self._ctx, self.state)
self.enterRule(localctx, 64, self.RULE_func)
self._la = 0 # Token type
try:
self.state = 460
self._errHandler.sync(self)
token = self._input.LA(1)
if token in [LaTeXParser.FUNC_EXP, LaTeXParser.FUNC_LOG, LaTeXParser.FUNC_LG, LaTeXParser.FUNC_LN, LaTeXParser.FUNC_SIN, LaTeXParser.FUNC_COS, LaTeXParser.FUNC_TAN, LaTeXParser.FUNC_CSC, LaTeXParser.FUNC_SEC, LaTeXParser.FUNC_COT, LaTeXParser.FUNC_ARCSIN, LaTeXParser.FUNC_ARCCOS, LaTeXParser.FUNC_ARCTAN, LaTeXParser.FUNC_ARCCSC, LaTeXParser.FUNC_ARCSEC, LaTeXParser.FUNC_ARCCOT, LaTeXParser.FUNC_SINH, LaTeXParser.FUNC_COSH, LaTeXParser.FUNC_TANH, LaTeXParser.FUNC_ARSINH, LaTeXParser.FUNC_ARCOSH, LaTeXParser.FUNC_ARTANH]:
self.enterOuterAlt(localctx, 1)
self.state = 371
self.func_normal()
self.state = 384
self._errHandler.sync(self)
la_ = self._interp.adaptivePredict(self._input,40,self._ctx)
if la_ == 1:
self.state = 373
self._errHandler.sync(self)
_la = self._input.LA(1)
if _la==LaTeXParser.UNDERSCORE:
self.state = 372
self.subexpr()
self.state = 376
self._errHandler.sync(self)
_la = self._input.LA(1)
if _la==LaTeXParser.CARET:
self.state = 375
self.supexpr()
pass
elif la_ == 2:
self.state = 379
self._errHandler.sync(self)
_la = self._input.LA(1)
if _la==LaTeXParser.CARET:
self.state = 378
self.supexpr()
self.state = 382
self._errHandler.sync(self)
_la = self._input.LA(1)
if _la==LaTeXParser.UNDERSCORE:
self.state = 381
self.subexpr()
pass
self.state = 391
self._errHandler.sync(self)
la_ = self._interp.adaptivePredict(self._input,41,self._ctx)
if la_ == 1:
self.state = 386
self.match(LaTeXParser.L_PAREN)
self.state = 387
self.func_arg()
self.state = 388
self.match(LaTeXParser.R_PAREN)
pass
elif la_ == 2:
self.state = 390
self.func_arg_noparens()
pass
pass
elif token in [LaTeXParser.LETTER, LaTeXParser.SYMBOL]:
self.enterOuterAlt(localctx, 2)
self.state = 393
_la = self._input.LA(1)
if not(_la==LaTeXParser.LETTER or _la==LaTeXParser.SYMBOL):
self._errHandler.recoverInline(self)
else:
self._errHandler.reportMatch(self)
self.consume()
self.state = 406
self._errHandler.sync(self)
la_ = self._interp.adaptivePredict(self._input,46,self._ctx)
if la_ == 1:
self.state = 395
self._errHandler.sync(self)
_la = self._input.LA(1)
if _la==LaTeXParser.UNDERSCORE:
self.state = 394
self.subexpr()
self.state = 398
self._errHandler.sync(self)
_la = self._input.LA(1)
if _la==LaTeXParser.SINGLE_QUOTES:
self.state = 397
self.match(LaTeXParser.SINGLE_QUOTES)
pass
elif la_ == 2:
self.state = 401
self._errHandler.sync(self)
_la = self._input.LA(1)
if _la==LaTeXParser.SINGLE_QUOTES:
self.state = 400
self.match(LaTeXParser.SINGLE_QUOTES)
self.state = 404
self._errHandler.sync(self)
_la = self._input.LA(1)
if _la==LaTeXParser.UNDERSCORE:
self.state = 403
self.subexpr()
pass
self.state = 408
self.match(LaTeXParser.L_PAREN)
self.state = 409
self.args()
self.state = 410
self.match(LaTeXParser.R_PAREN)
pass
elif token in [LaTeXParser.FUNC_INT]:
self.enterOuterAlt(localctx, 3)
self.state = 412
self.match(LaTeXParser.FUNC_INT)
self.state = 419
self._errHandler.sync(self)
token = self._input.LA(1)
if token in [LaTeXParser.UNDERSCORE]:
self.state = 413
self.subexpr()
self.state = 414
self.supexpr()
pass
elif token in [LaTeXParser.CARET]:
self.state = 416
self.supexpr()
self.state = 417
self.subexpr()
pass
elif token in [LaTeXParser.ADD, LaTeXParser.SUB, LaTeXParser.L_PAREN, LaTeXParser.L_BRACE, LaTeXParser.L_BRACE_LITERAL, LaTeXParser.L_BRACKET, LaTeXParser.BAR, LaTeXParser.L_BAR, LaTeXParser.L_ANGLE, LaTeXParser.FUNC_LIM, LaTeXParser.FUNC_INT, LaTeXParser.FUNC_SUM, LaTeXParser.FUNC_PROD, LaTeXParser.FUNC_EXP, LaTeXParser.FUNC_LOG, LaTeXParser.FUNC_LG, LaTeXParser.FUNC_LN, LaTeXParser.FUNC_SIN, LaTeXParser.FUNC_COS, LaTeXParser.FUNC_TAN, LaTeXParser.FUNC_CSC, LaTeXParser.FUNC_SEC, LaTeXParser.FUNC_COT, LaTeXParser.FUNC_ARCSIN, LaTeXParser.FUNC_ARCCOS, LaTeXParser.FUNC_ARCTAN, LaTeXParser.FUNC_ARCCSC, LaTeXParser.FUNC_ARCSEC, LaTeXParser.FUNC_ARCCOT, LaTeXParser.FUNC_SINH, LaTeXParser.FUNC_COSH, LaTeXParser.FUNC_TANH, LaTeXParser.FUNC_ARSINH, LaTeXParser.FUNC_ARCOSH, LaTeXParser.FUNC_ARTANH, LaTeXParser.L_FLOOR, LaTeXParser.L_CEIL, LaTeXParser.FUNC_SQRT, LaTeXParser.FUNC_OVERLINE, LaTeXParser.CMD_FRAC, LaTeXParser.CMD_BINOM, LaTeXParser.CMD_DBINOM, LaTeXParser.CMD_TBINOM, LaTeXParser.CMD_MATHIT, LaTeXParser.DIFFERENTIAL, LaTeXParser.LETTER, LaTeXParser.DIGIT, LaTeXParser.SYMBOL]:
pass
else:
pass
self.state = 427
self._errHandler.sync(self)
la_ = self._interp.adaptivePredict(self._input,49,self._ctx)
if la_ == 1:
self.state = 422
self._errHandler.sync(self)
la_ = self._interp.adaptivePredict(self._input,48,self._ctx)
if la_ == 1:
self.state = 421
self.additive(0)
self.state = 424
self.match(LaTeXParser.DIFFERENTIAL)
pass
elif la_ == 2:
self.state = 425
self.frac()
pass
elif la_ == 3:
self.state = 426
self.additive(0)
pass
pass
elif token in [LaTeXParser.FUNC_SQRT]:
self.enterOuterAlt(localctx, 4)
self.state = 429
self.match(LaTeXParser.FUNC_SQRT)
self.state = 434
self._errHandler.sync(self)
_la = self._input.LA(1)
if _la==LaTeXParser.L_BRACKET:
self.state = 430
self.match(LaTeXParser.L_BRACKET)
self.state = 431
localctx.root = self.expr()
self.state = 432
self.match(LaTeXParser.R_BRACKET)
self.state = 436
self.match(LaTeXParser.L_BRACE)
self.state = 437
localctx.base = self.expr()
self.state = 438
self.match(LaTeXParser.R_BRACE)
pass
elif token in [LaTeXParser.FUNC_OVERLINE]:
self.enterOuterAlt(localctx, 5)
self.state = 440
self.match(LaTeXParser.FUNC_OVERLINE)
self.state = 441
self.match(LaTeXParser.L_BRACE)
self.state = 442
localctx.base = self.expr()
self.state = 443
self.match(LaTeXParser.R_BRACE)
pass
elif token in [LaTeXParser.FUNC_SUM, LaTeXParser.FUNC_PROD]:
self.enterOuterAlt(localctx, 6)
self.state = 445
_la = self._input.LA(1)
if not(_la==LaTeXParser.FUNC_SUM or _la==LaTeXParser.FUNC_PROD):
self._errHandler.recoverInline(self)
else:
self._errHandler.reportMatch(self)
self.consume()
self.state = 452
self._errHandler.sync(self)
token = self._input.LA(1)
if token in [LaTeXParser.UNDERSCORE]:
self.state = 446
self.subeq()
self.state = 447
self.supexpr()
pass
elif token in [LaTeXParser.CARET]:
self.state = 449
self.supexpr()
self.state = 450
self.subeq()
pass
else:
raise NoViableAltException(self)
self.state = 454
self.mp(0)
pass
elif token in [LaTeXParser.FUNC_LIM]:
self.enterOuterAlt(localctx, 7)
self.state = 456
self.match(LaTeXParser.FUNC_LIM)
self.state = 457
self.limit_sub()
self.state = 458
self.mp(0)
pass
else:
raise NoViableAltException(self)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class ArgsContext(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def expr(self):
return self.getTypedRuleContext(LaTeXParser.ExprContext,0)
def args(self):
return self.getTypedRuleContext(LaTeXParser.ArgsContext,0)
def getRuleIndex(self):
return LaTeXParser.RULE_args
def args(self):
localctx = LaTeXParser.ArgsContext(self, self._ctx, self.state)
self.enterRule(localctx, 66, self.RULE_args)
try:
self.state = 467
self._errHandler.sync(self)
la_ = self._interp.adaptivePredict(self._input,53,self._ctx)
if la_ == 1:
self.enterOuterAlt(localctx, 1)
self.state = 462
self.expr()
self.state = 463
self.match(LaTeXParser.T__0)
self.state = 464
self.args()
pass
elif la_ == 2:
self.enterOuterAlt(localctx, 2)
self.state = 466
self.expr()
pass
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class Limit_subContext(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def UNDERSCORE(self):
return self.getToken(LaTeXParser.UNDERSCORE, 0)
def L_BRACE(self, i:int=None):
if i is None:
return self.getTokens(LaTeXParser.L_BRACE)
else:
return self.getToken(LaTeXParser.L_BRACE, i)
def LIM_APPROACH_SYM(self):
return self.getToken(LaTeXParser.LIM_APPROACH_SYM, 0)
def expr(self):
return self.getTypedRuleContext(LaTeXParser.ExprContext,0)
def R_BRACE(self, i:int=None):
if i is None:
return self.getTokens(LaTeXParser.R_BRACE)
else:
return self.getToken(LaTeXParser.R_BRACE, i)
def LETTER(self):
return self.getToken(LaTeXParser.LETTER, 0)
def SYMBOL(self):
return self.getToken(LaTeXParser.SYMBOL, 0)
def CARET(self):
return self.getToken(LaTeXParser.CARET, 0)
def ADD(self):
return self.getToken(LaTeXParser.ADD, 0)
def SUB(self):
return self.getToken(LaTeXParser.SUB, 0)
def getRuleIndex(self):
return LaTeXParser.RULE_limit_sub
def limit_sub(self):
localctx = LaTeXParser.Limit_subContext(self, self._ctx, self.state)
self.enterRule(localctx, 68, self.RULE_limit_sub)
self._la = 0 # Token type
try:
self.enterOuterAlt(localctx, 1)
self.state = 469
self.match(LaTeXParser.UNDERSCORE)
self.state = 470
self.match(LaTeXParser.L_BRACE)
self.state = 471
_la = self._input.LA(1)
if not(_la==LaTeXParser.LETTER or _la==LaTeXParser.SYMBOL):
self._errHandler.recoverInline(self)
else:
self._errHandler.reportMatch(self)
self.consume()
self.state = 472
self.match(LaTeXParser.LIM_APPROACH_SYM)
self.state = 473
self.expr()
self.state = 482
self._errHandler.sync(self)
_la = self._input.LA(1)
if _la==LaTeXParser.CARET:
self.state = 474
self.match(LaTeXParser.CARET)
self.state = 480
self._errHandler.sync(self)
token = self._input.LA(1)
if token in [LaTeXParser.L_BRACE]:
self.state = 475
self.match(LaTeXParser.L_BRACE)
self.state = 476
_la = self._input.LA(1)
if not(_la==LaTeXParser.ADD or _la==LaTeXParser.SUB):
self._errHandler.recoverInline(self)
else:
self._errHandler.reportMatch(self)
self.consume()
self.state = 477
self.match(LaTeXParser.R_BRACE)
pass
elif token in [LaTeXParser.ADD]:
self.state = 478
self.match(LaTeXParser.ADD)
pass
elif token in [LaTeXParser.SUB]:
self.state = 479
self.match(LaTeXParser.SUB)
pass
else:
raise NoViableAltException(self)
self.state = 484
self.match(LaTeXParser.R_BRACE)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class Func_argContext(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def expr(self):
return self.getTypedRuleContext(LaTeXParser.ExprContext,0)
def func_arg(self):
return self.getTypedRuleContext(LaTeXParser.Func_argContext,0)
def getRuleIndex(self):
return LaTeXParser.RULE_func_arg
def func_arg(self):
localctx = LaTeXParser.Func_argContext(self, self._ctx, self.state)
self.enterRule(localctx, 70, self.RULE_func_arg)
try:
self.state = 491
self._errHandler.sync(self)
la_ = self._interp.adaptivePredict(self._input,56,self._ctx)
if la_ == 1:
self.enterOuterAlt(localctx, 1)
self.state = 486
self.expr()
pass
elif la_ == 2:
self.enterOuterAlt(localctx, 2)
self.state = 487
self.expr()
self.state = 488
self.match(LaTeXParser.T__0)
self.state = 489
self.func_arg()
pass
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class Func_arg_noparensContext(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def mp_nofunc(self):
return self.getTypedRuleContext(LaTeXParser.Mp_nofuncContext,0)
def getRuleIndex(self):
return LaTeXParser.RULE_func_arg_noparens
def func_arg_noparens(self):
localctx = LaTeXParser.Func_arg_noparensContext(self, self._ctx, self.state)
self.enterRule(localctx, 72, self.RULE_func_arg_noparens)
try:
self.enterOuterAlt(localctx, 1)
self.state = 493
self.mp_nofunc(0)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class SubexprContext(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def UNDERSCORE(self):
return self.getToken(LaTeXParser.UNDERSCORE, 0)
def atom(self):
return self.getTypedRuleContext(LaTeXParser.AtomContext,0)
def L_BRACE(self):
return self.getToken(LaTeXParser.L_BRACE, 0)
def expr(self):
return self.getTypedRuleContext(LaTeXParser.ExprContext,0)
def R_BRACE(self):
return self.getToken(LaTeXParser.R_BRACE, 0)
def getRuleIndex(self):
return LaTeXParser.RULE_subexpr
def subexpr(self):
localctx = LaTeXParser.SubexprContext(self, self._ctx, self.state)
self.enterRule(localctx, 74, self.RULE_subexpr)
try:
self.enterOuterAlt(localctx, 1)
self.state = 495
self.match(LaTeXParser.UNDERSCORE)
self.state = 501
self._errHandler.sync(self)
token = self._input.LA(1)
if token in [LaTeXParser.BAR, LaTeXParser.L_BAR, LaTeXParser.L_ANGLE, LaTeXParser.CMD_FRAC, LaTeXParser.CMD_BINOM, LaTeXParser.CMD_DBINOM, LaTeXParser.CMD_TBINOM, LaTeXParser.CMD_MATHIT, LaTeXParser.DIFFERENTIAL, LaTeXParser.LETTER, LaTeXParser.DIGIT, LaTeXParser.SYMBOL]:
self.state = 496
self.atom()
pass
elif token in [LaTeXParser.L_BRACE]:
self.state = 497
self.match(LaTeXParser.L_BRACE)
self.state = 498
self.expr()
self.state = 499
self.match(LaTeXParser.R_BRACE)
pass
else:
raise NoViableAltException(self)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class SupexprContext(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def CARET(self):
return self.getToken(LaTeXParser.CARET, 0)
def atom(self):
return self.getTypedRuleContext(LaTeXParser.AtomContext,0)
def L_BRACE(self):
return self.getToken(LaTeXParser.L_BRACE, 0)
def expr(self):
return self.getTypedRuleContext(LaTeXParser.ExprContext,0)
def R_BRACE(self):
return self.getToken(LaTeXParser.R_BRACE, 0)
def getRuleIndex(self):
return LaTeXParser.RULE_supexpr
def supexpr(self):
localctx = LaTeXParser.SupexprContext(self, self._ctx, self.state)
self.enterRule(localctx, 76, self.RULE_supexpr)
try:
self.enterOuterAlt(localctx, 1)
self.state = 503
self.match(LaTeXParser.CARET)
self.state = 509
self._errHandler.sync(self)
token = self._input.LA(1)
if token in [LaTeXParser.BAR, LaTeXParser.L_BAR, LaTeXParser.L_ANGLE, LaTeXParser.CMD_FRAC, LaTeXParser.CMD_BINOM, LaTeXParser.CMD_DBINOM, LaTeXParser.CMD_TBINOM, LaTeXParser.CMD_MATHIT, LaTeXParser.DIFFERENTIAL, LaTeXParser.LETTER, LaTeXParser.DIGIT, LaTeXParser.SYMBOL]:
self.state = 504
self.atom()
pass
elif token in [LaTeXParser.L_BRACE]:
self.state = 505
self.match(LaTeXParser.L_BRACE)
self.state = 506
self.expr()
self.state = 507
self.match(LaTeXParser.R_BRACE)
pass
else:
raise NoViableAltException(self)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class SubeqContext(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def UNDERSCORE(self):
return self.getToken(LaTeXParser.UNDERSCORE, 0)
def L_BRACE(self):
return self.getToken(LaTeXParser.L_BRACE, 0)
def equality(self):
return self.getTypedRuleContext(LaTeXParser.EqualityContext,0)
def R_BRACE(self):
return self.getToken(LaTeXParser.R_BRACE, 0)
def getRuleIndex(self):
return LaTeXParser.RULE_subeq
def subeq(self):
localctx = LaTeXParser.SubeqContext(self, self._ctx, self.state)
self.enterRule(localctx, 78, self.RULE_subeq)
try:
self.enterOuterAlt(localctx, 1)
self.state = 511
self.match(LaTeXParser.UNDERSCORE)
self.state = 512
self.match(LaTeXParser.L_BRACE)
self.state = 513
self.equality()
self.state = 514
self.match(LaTeXParser.R_BRACE)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class SupeqContext(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def UNDERSCORE(self):
return self.getToken(LaTeXParser.UNDERSCORE, 0)
def L_BRACE(self):
return self.getToken(LaTeXParser.L_BRACE, 0)
def equality(self):
return self.getTypedRuleContext(LaTeXParser.EqualityContext,0)
def R_BRACE(self):
return self.getToken(LaTeXParser.R_BRACE, 0)
def getRuleIndex(self):
return LaTeXParser.RULE_supeq
def supeq(self):
localctx = LaTeXParser.SupeqContext(self, self._ctx, self.state)
self.enterRule(localctx, 80, self.RULE_supeq)
try:
self.enterOuterAlt(localctx, 1)
self.state = 516
self.match(LaTeXParser.UNDERSCORE)
self.state = 517
self.match(LaTeXParser.L_BRACE)
self.state = 518
self.equality()
self.state = 519
self.match(LaTeXParser.R_BRACE)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
def sempred(self, localctx:RuleContext, ruleIndex:int, predIndex:int):
if self._predicates == None:
self._predicates = dict()
self._predicates[1] = self.relation_sempred
self._predicates[4] = self.additive_sempred
self._predicates[5] = self.mp_sempred
self._predicates[6] = self.mp_nofunc_sempred
self._predicates[15] = self.exp_sempred
self._predicates[16] = self.exp_nofunc_sempred
pred = self._predicates.get(ruleIndex, None)
if pred is None:
raise Exception("No predicate with index:" + str(ruleIndex))
else:
return pred(localctx, predIndex)
def relation_sempred(self, localctx:RelationContext, predIndex:int):
if predIndex == 0:
return self.precpred(self._ctx, 2)
def additive_sempred(self, localctx:AdditiveContext, predIndex:int):
if predIndex == 1:
return self.precpred(self._ctx, 2)
def mp_sempred(self, localctx:MpContext, predIndex:int):
if predIndex == 2:
return self.precpred(self._ctx, 2)
def mp_nofunc_sempred(self, localctx:Mp_nofuncContext, predIndex:int):
if predIndex == 3:
return self.precpred(self._ctx, 2)
def exp_sempred(self, localctx:ExpContext, predIndex:int):
if predIndex == 4:
return self.precpred(self._ctx, 2)
def exp_nofunc_sempred(self, localctx:Exp_nofuncContext, predIndex:int):
if predIndex == 5:
return self.precpred(self._ctx, 2)
|
8d1877f211f97fe14d003f42f6b75dea6c550a258a96e4a981b6d10076020f14 | from typing import Type
from sympy.core.add import Add
from sympy.core.basic import Basic
from sympy.core.containers import Tuple
from sympy.core.evalf import EvalfMixin
from sympy.core.expr import Expr
from sympy.core.function import expand
from sympy.core.logic import fuzzy_and
from sympy.core.mul import Mul
from sympy.core.power import Pow
from sympy.core.singleton import S
from sympy.core.symbol import Dummy, Symbol
from sympy.core.sympify import sympify, _sympify
from sympy.matrices import ImmutableMatrix, eye
from sympy.matrices.expressions import MatMul, MatAdd
from sympy.polys import Poly, rootof
from sympy.polys.polyroots import roots
from sympy.polys.polytools import (cancel, degree)
from sympy.series import limit
from mpmath.libmp.libmpf import prec_to_dps
__all__ = ['TransferFunction', 'Series', 'MIMOSeries', 'Parallel', 'MIMOParallel',
'Feedback', 'MIMOFeedback', 'TransferFunctionMatrix']
def _roots(poly, var):
""" like roots, but works on higher-order polynomials. """
r = roots(poly, var, multiple=True)
n = degree(poly)
if len(r) != n:
r = [rootof(poly, var, k) for k in range(n)]
return r
class LinearTimeInvariant(Basic, EvalfMixin):
"""A common class for all the Linear Time-Invariant Dynamical Systems."""
_clstype: Type
# Users should not directly interact with this class.
def __new__(cls, *system, **kwargs):
if cls is LinearTimeInvariant:
raise NotImplementedError('The LTICommon class is not meant to be used directly.')
return super(LinearTimeInvariant, cls).__new__(cls, *system, **kwargs)
@classmethod
def _check_args(cls, args):
if not args:
raise ValueError("Atleast 1 argument must be passed.")
if not all(isinstance(arg, cls._clstype) for arg in args):
raise TypeError(f"All arguments must be of type {cls._clstype}.")
var_set = {arg.var for arg in args}
if len(var_set) != 1:
raise ValueError("All transfer functions should use the same complex variable"
f" of the Laplace transform. {len(var_set)} different values found.")
@property
def is_SISO(self):
"""Returns `True` if the passed LTI system is SISO else returns False."""
return self._is_SISO
class SISOLinearTimeInvariant(LinearTimeInvariant):
"""A common class for all the SISO Linear Time-Invariant Dynamical Systems."""
# Users should not directly interact with this class.
_is_SISO = True
class MIMOLinearTimeInvariant(LinearTimeInvariant):
"""A common class for all the MIMO Linear Time-Invariant Dynamical Systems."""
# Users should not directly interact with this class.
_is_SISO = False
SISOLinearTimeInvariant._clstype = SISOLinearTimeInvariant
MIMOLinearTimeInvariant._clstype = MIMOLinearTimeInvariant
def _check_other_SISO(func):
def wrapper(*args, **kwargs):
if not isinstance(args[-1], SISOLinearTimeInvariant):
return NotImplemented
else:
return func(*args, **kwargs)
return wrapper
def _check_other_MIMO(func):
def wrapper(*args, **kwargs):
if not isinstance(args[-1], MIMOLinearTimeInvariant):
return NotImplemented
else:
return func(*args, **kwargs)
return wrapper
class TransferFunction(SISOLinearTimeInvariant):
r"""
A class for representing LTI (Linear, time-invariant) systems that can be strictly described
by ratio of polynomials in the Laplace transform complex variable. The arguments
are ``num``, ``den``, and ``var``, where ``num`` and ``den`` are numerator and
denominator polynomials of the ``TransferFunction`` respectively, and the third argument is
a complex variable of the Laplace transform used by these polynomials of the transfer function.
``num`` and ``den`` can be either polynomials or numbers, whereas ``var``
has to be a :py:class:`~.Symbol`.
Explanation
===========
Generally, a dynamical system representing a physical model can be described in terms of Linear
Ordinary Differential Equations like -
$\small{b_{m}y^{\left(m\right)}+b_{m-1}y^{\left(m-1\right)}+\dots+b_{1}y^{\left(1\right)}+b_{0}y=
a_{n}x^{\left(n\right)}+a_{n-1}x^{\left(n-1\right)}+\dots+a_{1}x^{\left(1\right)}+a_{0}x}$
Here, $x$ is the input signal and $y$ is the output signal and superscript on both is the order of derivative
(not exponent). Derivative is taken with respect to the independent variable, $t$. Also, generally $m$ is greater
than $n$.
It is not feasible to analyse the properties of such systems in their native form therefore, we use
mathematical tools like Laplace transform to get a better perspective. Taking the Laplace transform
of both the sides in the equation (at zero initial conditions), we get -
$\small{\mathcal{L}[b_{m}y^{\left(m\right)}+b_{m-1}y^{\left(m-1\right)}+\dots+b_{1}y^{\left(1\right)}+b_{0}y]=
\mathcal{L}[a_{n}x^{\left(n\right)}+a_{n-1}x^{\left(n-1\right)}+\dots+a_{1}x^{\left(1\right)}+a_{0}x]}$
Using the linearity property of Laplace transform and also considering zero initial conditions
(i.e. $\small{y(0^{-}) = 0}$, $\small{y'(0^{-}) = 0}$ and so on), the equation
above gets translated to -
$\small{b_{m}\mathcal{L}[y^{\left(m\right)}]+\dots+b_{1}\mathcal{L}[y^{\left(1\right)}]+b_{0}\mathcal{L}[y]=
a_{n}\mathcal{L}[x^{\left(n\right)}]+\dots+a_{1}\mathcal{L}[x^{\left(1\right)}]+a_{0}\mathcal{L}[x]}$
Now, applying Derivative property of Laplace transform,
$\small{b_{m}s^{m}\mathcal{L}[y]+\dots+b_{1}s\mathcal{L}[y]+b_{0}\mathcal{L}[y]=
a_{n}s^{n}\mathcal{L}[x]+\dots+a_{1}s\mathcal{L}[x]+a_{0}\mathcal{L}[x]}$
Here, the superscript on $s$ is **exponent**. Note that the zero initial conditions assumption, mentioned above, is very important
and cannot be ignored otherwise the dynamical system cannot be considered time-independent and the simplified equation above
cannot be reached.
Collecting $\mathcal{L}[y]$ and $\mathcal{L}[x]$ terms from both the sides and taking the ratio
$\frac{ \mathcal{L}\left\{y\right\} }{ \mathcal{L}\left\{x\right\} }$, we get the typical rational form of transfer
function.
The numerator of the transfer function is, therefore, the Laplace transform of the output signal
(The signals are represented as functions of time) and similarly, the denominator
of the transfer function is the Laplace transform of the input signal. It is also a convention
to denote the input and output signal's Laplace transform with capital alphabets like shown below.
$H(s) = \frac{Y(s)}{X(s)} = \frac{ \mathcal{L}\left\{y(t)\right\} }{ \mathcal{L}\left\{x(t)\right\} }$
$s$, also known as complex frequency, is a complex variable in the Laplace domain. It corresponds to the
equivalent variable $t$, in the time domain. Transfer functions are sometimes also referred to as the Laplace
transform of the system's impulse response. Transfer function, $H$, is represented as a rational
function in $s$ like,
$H(s) =\ \frac{a_{n}s^{n}+a_{n-1}s^{n-1}+\dots+a_{1}s+a_{0}}{b_{m}s^{m}+b_{m-1}s^{m-1}+\dots+b_{1}s+b_{0}}$
Parameters
==========
num : Expr, Number
The numerator polynomial of the transfer function.
den : Expr, Number
The denominator polynomial of the transfer function.
var : Symbol
Complex variable of the Laplace transform used by the
polynomials of the transfer function.
Raises
======
TypeError
When ``var`` is not a Symbol or when ``num`` or ``den`` is not a
number or a polynomial.
ValueError
When ``den`` is zero.
Examples
========
>>> from sympy.abc import s, p, a
>>> from sympy.physics.control.lti import TransferFunction
>>> tf1 = TransferFunction(s + a, s**2 + s + 1, s)
>>> tf1
TransferFunction(a + s, s**2 + s + 1, s)
>>> tf1.num
a + s
>>> tf1.den
s**2 + s + 1
>>> tf1.var
s
>>> tf1.args
(a + s, s**2 + s + 1, s)
Any complex variable can be used for ``var``.
>>> tf2 = TransferFunction(a*p**3 - a*p**2 + s*p, p + a**2, p)
>>> tf2
TransferFunction(a*p**3 - a*p**2 + p*s, a**2 + p, p)
>>> tf3 = TransferFunction((p + 3)*(p - 1), (p - 1)*(p + 5), p)
>>> tf3
TransferFunction((p - 1)*(p + 3), (p - 1)*(p + 5), p)
To negate a transfer function the ``-`` operator can be prepended:
>>> tf4 = TransferFunction(-a + s, p**2 + s, p)
>>> -tf4
TransferFunction(a - s, p**2 + s, p)
>>> tf5 = TransferFunction(s**4 - 2*s**3 + 5*s + 4, s + 4, s)
>>> -tf5
TransferFunction(-s**4 + 2*s**3 - 5*s - 4, s + 4, s)
You can use a float or an integer (or other constants) as numerator and denominator:
>>> tf6 = TransferFunction(1/2, 4, s)
>>> tf6.num
0.500000000000000
>>> tf6.den
4
>>> tf6.var
s
>>> tf6.args
(0.5, 4, s)
You can take the integer power of a transfer function using the ``**`` operator:
>>> tf7 = TransferFunction(s + a, s - a, s)
>>> tf7**3
TransferFunction((a + s)**3, (-a + s)**3, s)
>>> tf7**0
TransferFunction(1, 1, s)
>>> tf8 = TransferFunction(p + 4, p - 3, p)
>>> tf8**-1
TransferFunction(p - 3, p + 4, p)
Addition, subtraction, and multiplication of transfer functions can form
unevaluated ``Series`` or ``Parallel`` objects.
>>> tf9 = TransferFunction(s + 1, s**2 + s + 1, s)
>>> tf10 = TransferFunction(s - p, s + 3, s)
>>> tf11 = TransferFunction(4*s**2 + 2*s - 4, s - 1, s)
>>> tf12 = TransferFunction(1 - s, s**2 + 4, s)
>>> tf9 + tf10
Parallel(TransferFunction(s + 1, s**2 + s + 1, s), TransferFunction(-p + s, s + 3, s))
>>> tf10 - tf11
Parallel(TransferFunction(-p + s, s + 3, s), TransferFunction(-4*s**2 - 2*s + 4, s - 1, s))
>>> tf9 * tf10
Series(TransferFunction(s + 1, s**2 + s + 1, s), TransferFunction(-p + s, s + 3, s))
>>> tf10 - (tf9 + tf12)
Parallel(TransferFunction(-p + s, s + 3, s), TransferFunction(-s - 1, s**2 + s + 1, s), TransferFunction(s - 1, s**2 + 4, s))
>>> tf10 - (tf9 * tf12)
Parallel(TransferFunction(-p + s, s + 3, s), Series(TransferFunction(-1, 1, s), TransferFunction(s + 1, s**2 + s + 1, s), TransferFunction(1 - s, s**2 + 4, s)))
>>> tf11 * tf10 * tf9
Series(TransferFunction(4*s**2 + 2*s - 4, s - 1, s), TransferFunction(-p + s, s + 3, s), TransferFunction(s + 1, s**2 + s + 1, s))
>>> tf9 * tf11 + tf10 * tf12
Parallel(Series(TransferFunction(s + 1, s**2 + s + 1, s), TransferFunction(4*s**2 + 2*s - 4, s - 1, s)), Series(TransferFunction(-p + s, s + 3, s), TransferFunction(1 - s, s**2 + 4, s)))
>>> (tf9 + tf12) * (tf10 + tf11)
Series(Parallel(TransferFunction(s + 1, s**2 + s + 1, s), TransferFunction(1 - s, s**2 + 4, s)), Parallel(TransferFunction(-p + s, s + 3, s), TransferFunction(4*s**2 + 2*s - 4, s - 1, s)))
These unevaluated ``Series`` or ``Parallel`` objects can convert into the
resultant transfer function using ``.doit()`` method or by ``.rewrite(TransferFunction)``.
>>> ((tf9 + tf10) * tf12).doit()
TransferFunction((1 - s)*((-p + s)*(s**2 + s + 1) + (s + 1)*(s + 3)), (s + 3)*(s**2 + 4)*(s**2 + s + 1), s)
>>> (tf9 * tf10 - tf11 * tf12).rewrite(TransferFunction)
TransferFunction(-(1 - s)*(s + 3)*(s**2 + s + 1)*(4*s**2 + 2*s - 4) + (-p + s)*(s - 1)*(s + 1)*(s**2 + 4), (s - 1)*(s + 3)*(s**2 + 4)*(s**2 + s + 1), s)
See Also
========
Feedback, Series, Parallel
References
==========
.. [1] https://en.wikipedia.org/wiki/Transfer_function
.. [2] https://en.wikipedia.org/wiki/Laplace_transform
"""
def __new__(cls, num, den, var):
num, den = _sympify(num), _sympify(den)
if not isinstance(var, Symbol):
raise TypeError("Variable input must be a Symbol.")
if den == 0:
raise ValueError("TransferFunction cannot have a zero denominator.")
if (((isinstance(num, Expr) and num.has(Symbol)) or num.is_number) and
((isinstance(den, Expr) and den.has(Symbol)) or den.is_number)):
obj = super(TransferFunction, cls).__new__(cls, num, den, var)
obj._num = num
obj._den = den
obj._var = var
return obj
else:
raise TypeError("Unsupported type for numerator or denominator of TransferFunction.")
@classmethod
def from_rational_expression(cls, expr, var=None):
r"""
Creates a new ``TransferFunction`` efficiently from a rational expression.
Parameters
==========
expr : Expr, Number
The rational expression representing the ``TransferFunction``.
var : Symbol, optional
Complex variable of the Laplace transform used by the
polynomials of the transfer function.
Raises
======
ValueError
When ``expr`` is of type ``Number`` and optional parameter ``var``
is not passed.
When ``expr`` has more than one variables and an optional parameter
``var`` is not passed.
ZeroDivisionError
When denominator of ``expr`` is zero or it has ``ComplexInfinity``
in its numerator.
Examples
========
>>> from sympy.abc import s, p, a
>>> from sympy.physics.control.lti import TransferFunction
>>> expr1 = (s + 5)/(3*s**2 + 2*s + 1)
>>> tf1 = TransferFunction.from_rational_expression(expr1)
>>> tf1
TransferFunction(s + 5, 3*s**2 + 2*s + 1, s)
>>> expr2 = (a*p**3 - a*p**2 + s*p)/(p + a**2) # Expr with more than one variables
>>> tf2 = TransferFunction.from_rational_expression(expr2, p)
>>> tf2
TransferFunction(a*p**3 - a*p**2 + p*s, a**2 + p, p)
In case of conflict between two or more variables in a expression, SymPy will
raise a ``ValueError``, if ``var`` is not passed by the user.
>>> tf = TransferFunction.from_rational_expression((a + a*s)/(s**2 + s + 1))
Traceback (most recent call last):
...
ValueError: Conflicting values found for positional argument `var` ({a, s}). Specify it manually.
This can be corrected by specifying the ``var`` parameter manually.
>>> tf = TransferFunction.from_rational_expression((a + a*s)/(s**2 + s + 1), s)
>>> tf
TransferFunction(a*s + a, s**2 + s + 1, s)
``var`` also need to be specified when ``expr`` is a ``Number``
>>> tf3 = TransferFunction.from_rational_expression(10, s)
>>> tf3
TransferFunction(10, 1, s)
"""
expr = _sympify(expr)
if var is None:
_free_symbols = expr.free_symbols
_len_free_symbols = len(_free_symbols)
if _len_free_symbols == 1:
var = list(_free_symbols)[0]
elif _len_free_symbols == 0:
raise ValueError("Positional argument `var` not found in the TransferFunction defined. Specify it manually.")
else:
raise ValueError("Conflicting values found for positional argument `var` ({}). Specify it manually.".format(_free_symbols))
_num, _den = expr.as_numer_denom()
if _den == 0 or _num.has(S.ComplexInfinity):
raise ZeroDivisionError("TransferFunction cannot have a zero denominator.")
return cls(_num, _den, var)
@property
def num(self):
"""
Returns the numerator polynomial of the transfer function.
Examples
========
>>> from sympy.abc import s, p
>>> from sympy.physics.control.lti import TransferFunction
>>> G1 = TransferFunction(s**2 + p*s + 3, s - 4, s)
>>> G1.num
p*s + s**2 + 3
>>> G2 = TransferFunction((p + 5)*(p - 3), (p - 3)*(p + 1), p)
>>> G2.num
(p - 3)*(p + 5)
"""
return self._num
@property
def den(self):
"""
Returns the denominator polynomial of the transfer function.
Examples
========
>>> from sympy.abc import s, p
>>> from sympy.physics.control.lti import TransferFunction
>>> G1 = TransferFunction(s + 4, p**3 - 2*p + 4, s)
>>> G1.den
p**3 - 2*p + 4
>>> G2 = TransferFunction(3, 4, s)
>>> G2.den
4
"""
return self._den
@property
def var(self):
"""
Returns the complex variable of the Laplace transform used by the polynomials of
the transfer function.
Examples
========
>>> from sympy.abc import s, p
>>> from sympy.physics.control.lti import TransferFunction
>>> G1 = TransferFunction(p**2 + 2*p + 4, p - 6, p)
>>> G1.var
p
>>> G2 = TransferFunction(0, s - 5, s)
>>> G2.var
s
"""
return self._var
def _eval_subs(self, old, new):
arg_num = self.num.subs(old, new)
arg_den = self.den.subs(old, new)
argnew = TransferFunction(arg_num, arg_den, self.var)
return self if old == self.var else argnew
def _eval_evalf(self, prec):
return TransferFunction(
self.num._eval_evalf(prec),
self.den._eval_evalf(prec),
self.var)
def _eval_simplify(self, **kwargs):
tf = cancel(Mul(self.num, 1/self.den, evaluate=False), expand=False).as_numer_denom()
num_, den_ = tf[0], tf[1]
return TransferFunction(num_, den_, self.var)
def expand(self):
"""
Returns the transfer function with numerator and denominator
in expanded form.
Examples
========
>>> from sympy.abc import s, p, a, b
>>> from sympy.physics.control.lti import TransferFunction
>>> G1 = TransferFunction((a - s)**2, (s**2 + a)**2, s)
>>> G1.expand()
TransferFunction(a**2 - 2*a*s + s**2, a**2 + 2*a*s**2 + s**4, s)
>>> G2 = TransferFunction((p + 3*b)*(p - b), (p - b)*(p + 2*b), p)
>>> G2.expand()
TransferFunction(-3*b**2 + 2*b*p + p**2, -2*b**2 + b*p + p**2, p)
"""
return TransferFunction(expand(self.num), expand(self.den), self.var)
def dc_gain(self):
"""
Computes the gain of the response as the frequency approaches zero.
The DC gain is infinite for systems with pure integrators.
Examples
========
>>> from sympy.abc import s, p, a, b
>>> from sympy.physics.control.lti import TransferFunction
>>> tf1 = TransferFunction(s + 3, s**2 - 9, s)
>>> tf1.dc_gain()
-1/3
>>> tf2 = TransferFunction(p**2, p - 3 + p**3, p)
>>> tf2.dc_gain()
0
>>> tf3 = TransferFunction(a*p**2 - b, s + b, s)
>>> tf3.dc_gain()
(a*p**2 - b)/b
>>> tf4 = TransferFunction(1, s, s)
>>> tf4.dc_gain()
oo
"""
m = Mul(self.num, Pow(self.den, -1, evaluate=False), evaluate=False)
return limit(m, self.var, 0)
def poles(self):
"""
Returns the poles of a transfer function.
Examples
========
>>> from sympy.abc import s, p, a
>>> from sympy.physics.control.lti import TransferFunction
>>> tf1 = TransferFunction((p + 3)*(p - 1), (p - 1)*(p + 5), p)
>>> tf1.poles()
[-5, 1]
>>> tf2 = TransferFunction((1 - s)**2, (s**2 + 1)**2, s)
>>> tf2.poles()
[I, I, -I, -I]
>>> tf3 = TransferFunction(s**2, a*s + p, s)
>>> tf3.poles()
[-p/a]
"""
return _roots(Poly(self.den, self.var), self.var)
def zeros(self):
"""
Returns the zeros of a transfer function.
Examples
========
>>> from sympy.abc import s, p, a
>>> from sympy.physics.control.lti import TransferFunction
>>> tf1 = TransferFunction((p + 3)*(p - 1), (p - 1)*(p + 5), p)
>>> tf1.zeros()
[-3, 1]
>>> tf2 = TransferFunction((1 - s)**2, (s**2 + 1)**2, s)
>>> tf2.zeros()
[1, 1]
>>> tf3 = TransferFunction(s**2, a*s + p, s)
>>> tf3.zeros()
[0, 0]
"""
return _roots(Poly(self.num, self.var), self.var)
def is_stable(self):
"""
Returns True if the transfer function is asymptotically stable; else False.
This would not check the marginal or conditional stability of the system.
Examples
========
>>> from sympy.abc import s, p, a
>>> from sympy import symbols
>>> from sympy.physics.control.lti import TransferFunction
>>> q, r = symbols('q, r', negative=True)
>>> tf1 = TransferFunction((1 - s)**2, (s + 1)**2, s)
>>> tf1.is_stable()
True
>>> tf2 = TransferFunction((1 - p)**2, (s**2 + 1)**2, s)
>>> tf2.is_stable()
False
>>> tf3 = TransferFunction(4, q*s - r, s)
>>> tf3.is_stable()
False
>>> tf4 = TransferFunction(p + 1, a*p - s**2, p)
>>> tf4.is_stable() is None # Not enough info about the symbols to determine stability
True
"""
return fuzzy_and(pole.as_real_imag()[0].is_negative for pole in self.poles())
def __add__(self, other):
if isinstance(other, (TransferFunction, Series)):
if not self.var == other.var:
raise ValueError("All the transfer functions should use the same complex variable "
"of the Laplace transform.")
return Parallel(self, other)
elif isinstance(other, Parallel):
if not self.var == other.var:
raise ValueError("All the transfer functions should use the same complex variable "
"of the Laplace transform.")
arg_list = list(other.args)
return Parallel(self, *arg_list)
else:
raise ValueError("TransferFunction cannot be added with {}.".
format(type(other)))
def __radd__(self, other):
return self + other
def __sub__(self, other):
if isinstance(other, (TransferFunction, Series)):
if not self.var == other.var:
raise ValueError("All the transfer functions should use the same complex variable "
"of the Laplace transform.")
return Parallel(self, -other)
elif isinstance(other, Parallel):
if not self.var == other.var:
raise ValueError("All the transfer functions should use the same complex variable "
"of the Laplace transform.")
arg_list = [-i for i in list(other.args)]
return Parallel(self, *arg_list)
else:
raise ValueError("{} cannot be subtracted from a TransferFunction."
.format(type(other)))
def __rsub__(self, other):
return -self + other
def __mul__(self, other):
if isinstance(other, (TransferFunction, Parallel)):
if not self.var == other.var:
raise ValueError("All the transfer functions should use the same complex variable "
"of the Laplace transform.")
return Series(self, other)
elif isinstance(other, Series):
if not self.var == other.var:
raise ValueError("All the transfer functions should use the same complex variable "
"of the Laplace transform.")
arg_list = list(other.args)
return Series(self, *arg_list)
else:
raise ValueError("TransferFunction cannot be multiplied with {}."
.format(type(other)))
__rmul__ = __mul__
def __truediv__(self, other):
if (isinstance(other, Parallel) and len(other.args) == 2 and isinstance(other.args[0], TransferFunction)
and isinstance(other.args[1], (Series, TransferFunction))):
if not self.var == other.var:
raise ValueError("Both TransferFunction and Parallel should use the"
" same complex variable of the Laplace transform.")
if other.args[1] == self:
# plant and controller with unit feedback.
return Feedback(self, other.args[0])
other_arg_list = list(other.args[1].args) if isinstance(other.args[1], Series) else other.args[1]
if other_arg_list == other.args[1]:
return Feedback(self, other_arg_list)
elif self in other_arg_list:
other_arg_list.remove(self)
else:
return Feedback(self, Series(*other_arg_list))
if len(other_arg_list) == 1:
return Feedback(self, *other_arg_list)
else:
return Feedback(self, Series(*other_arg_list))
else:
raise ValueError("TransferFunction cannot be divided by {}.".
format(type(other)))
__rtruediv__ = __truediv__
def __pow__(self, p):
p = sympify(p)
if not p.is_Integer:
raise ValueError("Exponent must be an integer.")
if p is S.Zero:
return TransferFunction(1, 1, self.var)
elif p > 0:
num_, den_ = self.num**p, self.den**p
else:
p = abs(p)
num_, den_ = self.den**p, self.num**p
return TransferFunction(num_, den_, self.var)
def __neg__(self):
return TransferFunction(-self.num, self.den, self.var)
@property
def is_proper(self):
"""
Returns True if degree of the numerator polynomial is less than
or equal to degree of the denominator polynomial, else False.
Examples
========
>>> from sympy.abc import s, p, a, b
>>> from sympy.physics.control.lti import TransferFunction
>>> tf1 = TransferFunction(b*s**2 + p**2 - a*p + s, b - p**2, s)
>>> tf1.is_proper
False
>>> tf2 = TransferFunction(p**2 - 4*p, p**3 + 3*p + 2, p)
>>> tf2.is_proper
True
"""
return degree(self.num, self.var) <= degree(self.den, self.var)
@property
def is_strictly_proper(self):
"""
Returns True if degree of the numerator polynomial is strictly less
than degree of the denominator polynomial, else False.
Examples
========
>>> from sympy.abc import s, p, a, b
>>> from sympy.physics.control.lti import TransferFunction
>>> tf1 = TransferFunction(a*p**2 + b*s, s - p, s)
>>> tf1.is_strictly_proper
False
>>> tf2 = TransferFunction(s**3 - 2, s**4 + 5*s + 6, s)
>>> tf2.is_strictly_proper
True
"""
return degree(self.num, self.var) < degree(self.den, self.var)
@property
def is_biproper(self):
"""
Returns True if degree of the numerator polynomial is equal to
degree of the denominator polynomial, else False.
Examples
========
>>> from sympy.abc import s, p, a, b
>>> from sympy.physics.control.lti import TransferFunction
>>> tf1 = TransferFunction(a*p**2 + b*s, s - p, s)
>>> tf1.is_biproper
True
>>> tf2 = TransferFunction(p**2, p + a, p)
>>> tf2.is_biproper
False
"""
return degree(self.num, self.var) == degree(self.den, self.var)
def to_expr(self):
"""
Converts a ``TransferFunction`` object to SymPy Expr.
Examples
========
>>> from sympy.abc import s, p, a, b
>>> from sympy.physics.control.lti import TransferFunction
>>> from sympy import Expr
>>> tf1 = TransferFunction(s, a*s**2 + 1, s)
>>> tf1.to_expr()
s/(a*s**2 + 1)
>>> isinstance(_, Expr)
True
>>> tf2 = TransferFunction(1, (p + 3*b)*(b - p), p)
>>> tf2.to_expr()
1/((b - p)*(3*b + p))
>>> tf3 = TransferFunction((s - 2)*(s - 3), (s - 1)*(s - 2)*(s - 3), s)
>>> tf3.to_expr()
((s - 3)*(s - 2))/(((s - 3)*(s - 2)*(s - 1)))
"""
if self.num != 1:
return Mul(self.num, Pow(self.den, -1, evaluate=False), evaluate=False)
else:
return Pow(self.den, -1, evaluate=False)
def _flatten_args(args, _cls):
temp_args = []
for arg in args:
if isinstance(arg, _cls):
temp_args.extend(arg.args)
else:
temp_args.append(arg)
return tuple(temp_args)
def _dummify_args(_arg, var):
dummy_dict = {}
dummy_arg_list = []
for arg in _arg:
_s = Dummy()
dummy_dict[_s] = var
dummy_arg = arg.subs({var: _s})
dummy_arg_list.append(dummy_arg)
return dummy_arg_list, dummy_dict
class Series(SISOLinearTimeInvariant):
r"""
A class for representing a series configuration of SISO systems.
Parameters
==========
args : SISOLinearTimeInvariant
SISO systems in a series configuration.
evaluate : Boolean, Keyword
When passed ``True``, returns the equivalent
``Series(*args).doit()``. Set to ``False`` by default.
Raises
======
ValueError
When no argument is passed.
``var`` attribute is not same for every system.
TypeError
Any of the passed ``*args`` has unsupported type
A combination of SISO and MIMO systems is
passed. There should be homogeneity in the
type of systems passed, SISO in this case.
Examples
========
>>> from sympy.abc import s, p, a, b
>>> from sympy.physics.control.lti import TransferFunction, Series, Parallel
>>> tf1 = TransferFunction(a*p**2 + b*s, s - p, s)
>>> tf2 = TransferFunction(s**3 - 2, s**4 + 5*s + 6, s)
>>> tf3 = TransferFunction(p**2, p + s, s)
>>> S1 = Series(tf1, tf2)
>>> S1
Series(TransferFunction(a*p**2 + b*s, -p + s, s), TransferFunction(s**3 - 2, s**4 + 5*s + 6, s))
>>> S1.var
s
>>> S2 = Series(tf2, Parallel(tf3, -tf1))
>>> S2
Series(TransferFunction(s**3 - 2, s**4 + 5*s + 6, s), Parallel(TransferFunction(p**2, p + s, s), TransferFunction(-a*p**2 - b*s, -p + s, s)))
>>> S2.var
s
>>> S3 = Series(Parallel(tf1, tf2), Parallel(tf2, tf3))
>>> S3
Series(Parallel(TransferFunction(a*p**2 + b*s, -p + s, s), TransferFunction(s**3 - 2, s**4 + 5*s + 6, s)), Parallel(TransferFunction(s**3 - 2, s**4 + 5*s + 6, s), TransferFunction(p**2, p + s, s)))
>>> S3.var
s
You can get the resultant transfer function by using ``.doit()`` method:
>>> S3 = Series(tf1, tf2, -tf3)
>>> S3.doit()
TransferFunction(-p**2*(s**3 - 2)*(a*p**2 + b*s), (-p + s)*(p + s)*(s**4 + 5*s + 6), s)
>>> S4 = Series(tf2, Parallel(tf1, -tf3))
>>> S4.doit()
TransferFunction((s**3 - 2)*(-p**2*(-p + s) + (p + s)*(a*p**2 + b*s)), (-p + s)*(p + s)*(s**4 + 5*s + 6), s)
Notes
=====
All the transfer functions should use the same complex variable
``var`` of the Laplace transform.
See Also
========
MIMOSeries, Parallel, TransferFunction, Feedback
"""
def __new__(cls, *args, evaluate=False):
args = _flatten_args(args, Series)
cls._check_args(args)
obj = super().__new__(cls, *args)
return obj.doit() if evaluate else obj
@property
def var(self):
"""
Returns the complex variable used by all the transfer functions.
Examples
========
>>> from sympy.abc import p
>>> from sympy.physics.control.lti import TransferFunction, Series, Parallel
>>> G1 = TransferFunction(p**2 + 2*p + 4, p - 6, p)
>>> G2 = TransferFunction(p, 4 - p, p)
>>> G3 = TransferFunction(0, p**4 - 1, p)
>>> Series(G1, G2).var
p
>>> Series(-G3, Parallel(G1, G2)).var
p
"""
return self.args[0].var
def doit(self, **hints):
"""
Returns the resultant transfer function obtained after evaluating
the transfer functions in series configuration.
Examples
========
>>> from sympy.abc import s, p, a, b
>>> from sympy.physics.control.lti import TransferFunction, Series
>>> tf1 = TransferFunction(a*p**2 + b*s, s - p, s)
>>> tf2 = TransferFunction(s**3 - 2, s**4 + 5*s + 6, s)
>>> Series(tf2, tf1).doit()
TransferFunction((s**3 - 2)*(a*p**2 + b*s), (-p + s)*(s**4 + 5*s + 6), s)
>>> Series(-tf1, -tf2).doit()
TransferFunction((2 - s**3)*(-a*p**2 - b*s), (-p + s)*(s**4 + 5*s + 6), s)
"""
_num_arg = (arg.doit().num for arg in self.args)
_den_arg = (arg.doit().den for arg in self.args)
res_num = Mul(*_num_arg, evaluate=True)
res_den = Mul(*_den_arg, evaluate=True)
return TransferFunction(res_num, res_den, self.var)
def _eval_rewrite_as_TransferFunction(self, *args, **kwargs):
return self.doit()
@_check_other_SISO
def __add__(self, other):
if isinstance(other, Parallel):
arg_list = list(other.args)
return Parallel(self, *arg_list)
return Parallel(self, other)
__radd__ = __add__
@_check_other_SISO
def __sub__(self, other):
return self + (-other)
def __rsub__(self, other):
return -self + other
@_check_other_SISO
def __mul__(self, other):
arg_list = list(self.args)
return Series(*arg_list, other)
def __truediv__(self, other):
if (isinstance(other, Parallel) and len(other.args) == 2
and isinstance(other.args[0], TransferFunction) and isinstance(other.args[1], Series)):
if not self.var == other.var:
raise ValueError("All the transfer functions should use the same complex variable "
"of the Laplace transform.")
self_arg_list = set(list(self.args))
other_arg_list = set(list(other.args[1].args))
res = list(self_arg_list ^ other_arg_list)
if len(res) == 0:
return Feedback(self, other.args[0])
elif len(res) == 1:
return Feedback(self, *res)
else:
return Feedback(self, Series(*res))
else:
raise ValueError("This transfer function expression is invalid.")
def __neg__(self):
return Series(TransferFunction(-1, 1, self.var), self)
def to_expr(self):
"""Returns the equivalent ``Expr`` object."""
return Mul(*(arg.to_expr() for arg in self.args), evaluate=False)
@property
def is_proper(self):
"""
Returns True if degree of the numerator polynomial of the resultant transfer
function is less than or equal to degree of the denominator polynomial of
the same, else False.
Examples
========
>>> from sympy.abc import s, p, a, b
>>> from sympy.physics.control.lti import TransferFunction, Series
>>> tf1 = TransferFunction(b*s**2 + p**2 - a*p + s, b - p**2, s)
>>> tf2 = TransferFunction(p**2 - 4*p, p**3 + 3*s + 2, s)
>>> tf3 = TransferFunction(s, s**2 + s + 1, s)
>>> S1 = Series(-tf2, tf1)
>>> S1.is_proper
False
>>> S2 = Series(tf1, tf2, tf3)
>>> S2.is_proper
True
"""
return self.doit().is_proper
@property
def is_strictly_proper(self):
"""
Returns True if degree of the numerator polynomial of the resultant transfer
function is strictly less than degree of the denominator polynomial of
the same, else False.
Examples
========
>>> from sympy.abc import s, p, a, b
>>> from sympy.physics.control.lti import TransferFunction, Series
>>> tf1 = TransferFunction(a*p**2 + b*s, s - p, s)
>>> tf2 = TransferFunction(s**3 - 2, s**2 + 5*s + 6, s)
>>> tf3 = TransferFunction(1, s**2 + s + 1, s)
>>> S1 = Series(tf1, tf2)
>>> S1.is_strictly_proper
False
>>> S2 = Series(tf1, tf2, tf3)
>>> S2.is_strictly_proper
True
"""
return self.doit().is_strictly_proper
@property
def is_biproper(self):
r"""
Returns True if degree of the numerator polynomial of the resultant transfer
function is equal to degree of the denominator polynomial of
the same, else False.
Examples
========
>>> from sympy.abc import s, p, a, b
>>> from sympy.physics.control.lti import TransferFunction, Series
>>> tf1 = TransferFunction(a*p**2 + b*s, s - p, s)
>>> tf2 = TransferFunction(p, s**2, s)
>>> tf3 = TransferFunction(s**2, 1, s)
>>> S1 = Series(tf1, -tf2)
>>> S1.is_biproper
False
>>> S2 = Series(tf2, tf3)
>>> S2.is_biproper
True
"""
return self.doit().is_biproper
def _mat_mul_compatible(*args):
"""To check whether shapes are compatible for matrix mul."""
return all(args[i].num_outputs == args[i+1].num_inputs for i in range(len(args)-1))
class MIMOSeries(MIMOLinearTimeInvariant):
r"""
A class for representing a series configuration of MIMO systems.
Parameters
==========
args : MIMOLinearTimeInvariant
MIMO systems in a series configuration.
evaluate : Boolean, Keyword
When passed ``True``, returns the equivalent
``MIMOSeries(*args).doit()``. Set to ``False`` by default.
Raises
======
ValueError
When no argument is passed.
``var`` attribute is not same for every system.
``num_outputs`` of the MIMO system is not equal to the
``num_inputs`` of its adjacent MIMO system. (Matrix
multiplication constraint, basically)
TypeError
Any of the passed ``*args`` has unsupported type
A combination of SISO and MIMO systems is
passed. There should be homogeneity in the
type of systems passed, MIMO in this case.
Examples
========
>>> from sympy.abc import s
>>> from sympy.physics.control.lti import MIMOSeries, TransferFunctionMatrix
>>> from sympy import Matrix, pprint
>>> mat_a = Matrix([[5*s], [5]]) # 2 Outputs 1 Input
>>> mat_b = Matrix([[5, 1/(6*s**2)]]) # 1 Output 2 Inputs
>>> mat_c = Matrix([[1, s], [5/s, 1]]) # 2 Outputs 2 Inputs
>>> tfm_a = TransferFunctionMatrix.from_Matrix(mat_a, s)
>>> tfm_b = TransferFunctionMatrix.from_Matrix(mat_b, s)
>>> tfm_c = TransferFunctionMatrix.from_Matrix(mat_c, s)
>>> MIMOSeries(tfm_c, tfm_b, tfm_a)
MIMOSeries(TransferFunctionMatrix(((TransferFunction(1, 1, s), TransferFunction(s, 1, s)), (TransferFunction(5, s, s), TransferFunction(1, 1, s)))), TransferFunctionMatrix(((TransferFunction(5, 1, s), TransferFunction(1, 6*s**2, s)),)), TransferFunctionMatrix(((TransferFunction(5*s, 1, s),), (TransferFunction(5, 1, s),))))
>>> pprint(_, use_unicode=False) # For Better Visualization
[5*s] [1 s]
[---] [5 1 ] [- -]
[ 1 ] [- ----] [1 1]
[ ] *[1 2] *[ ]
[ 5 ] [ 6*s ]{t} [5 1]
[ - ] [- -]
[ 1 ]{t} [s 1]{t}
>>> MIMOSeries(tfm_c, tfm_b, tfm_a).doit()
TransferFunctionMatrix(((TransferFunction(150*s**4 + 25*s, 6*s**3, s), TransferFunction(150*s**4 + 5*s, 6*s**2, s)), (TransferFunction(150*s**3 + 25, 6*s**3, s), TransferFunction(150*s**3 + 5, 6*s**2, s))))
>>> pprint(_, use_unicode=False) # (2 Inputs -A-> 2 Outputs) -> (2 Inputs -B-> 1 Output) -> (1 Input -C-> 2 Outputs) is equivalent to (2 Inputs -Series Equivalent-> 2 Outputs).
[ 4 4 ]
[150*s + 25*s 150*s + 5*s]
[------------- ------------]
[ 3 2 ]
[ 6*s 6*s ]
[ ]
[ 3 3 ]
[ 150*s + 25 150*s + 5 ]
[ ----------- ---------- ]
[ 3 2 ]
[ 6*s 6*s ]{t}
Notes
=====
All the transfer function matrices should use the same complex variable ``var`` of the Laplace transform.
``MIMOSeries(A, B)`` is not equivalent to ``A*B``. It is always in the reverse order, that is ``B*A``.
See Also
========
Series, MIMOParallel
"""
def __new__(cls, *args, evaluate=False):
cls._check_args(args)
if _mat_mul_compatible(*args):
obj = super().__new__(cls, *args)
else:
raise ValueError("Number of input signals do not match the number"
" of output signals of adjacent systems for some args.")
return obj.doit() if evaluate else obj
@property
def var(self):
"""
Returns the complex variable used by all the transfer functions.
Examples
========
>>> from sympy.abc import p
>>> from sympy.physics.control.lti import TransferFunction, MIMOSeries, TransferFunctionMatrix
>>> G1 = TransferFunction(p**2 + 2*p + 4, p - 6, p)
>>> G2 = TransferFunction(p, 4 - p, p)
>>> G3 = TransferFunction(0, p**4 - 1, p)
>>> tfm_1 = TransferFunctionMatrix([[G1, G2, G3]])
>>> tfm_2 = TransferFunctionMatrix([[G1], [G2], [G3]])
>>> MIMOSeries(tfm_2, tfm_1).var
p
"""
return self.args[0].var
@property
def num_inputs(self):
"""Returns the number of input signals of the series system."""
return self.args[0].num_inputs
@property
def num_outputs(self):
"""Returns the number of output signals of the series system."""
return self.args[-1].num_outputs
@property
def shape(self):
"""Returns the shape of the equivalent MIMO system."""
return self.num_outputs, self.num_inputs
def doit(self, cancel=False, **kwargs):
"""
Returns the resultant transfer function matrix obtained after evaluating
the MIMO systems arranged in a series configuration.
Examples
========
>>> from sympy.abc import s, p, a, b
>>> from sympy.physics.control.lti import TransferFunction, MIMOSeries, TransferFunctionMatrix
>>> tf1 = TransferFunction(a*p**2 + b*s, s - p, s)
>>> tf2 = TransferFunction(s**3 - 2, s**4 + 5*s + 6, s)
>>> tfm1 = TransferFunctionMatrix([[tf1, tf2], [tf2, tf2]])
>>> tfm2 = TransferFunctionMatrix([[tf2, tf1], [tf1, tf1]])
>>> MIMOSeries(tfm2, tfm1).doit()
TransferFunctionMatrix(((TransferFunction(2*(-p + s)*(s**3 - 2)*(a*p**2 + b*s)*(s**4 + 5*s + 6), (-p + s)**2*(s**4 + 5*s + 6)**2, s), TransferFunction((-p + s)**2*(s**3 - 2)*(a*p**2 + b*s) + (-p + s)*(a*p**2 + b*s)**2*(s**4 + 5*s + 6), (-p + s)**3*(s**4 + 5*s + 6), s)), (TransferFunction((-p + s)*(s**3 - 2)**2*(s**4 + 5*s + 6) + (s**3 - 2)*(a*p**2 + b*s)*(s**4 + 5*s + 6)**2, (-p + s)*(s**4 + 5*s + 6)**3, s), TransferFunction(2*(s**3 - 2)*(a*p**2 + b*s), (-p + s)*(s**4 + 5*s + 6), s))))
"""
_arg = (arg.doit()._expr_mat for arg in reversed(self.args))
if cancel:
res = MatMul(*_arg, evaluate=True)
return TransferFunctionMatrix.from_Matrix(res, self.var)
_dummy_args, _dummy_dict = _dummify_args(_arg, self.var)
res = MatMul(*_dummy_args, evaluate=True)
temp_tfm = TransferFunctionMatrix.from_Matrix(res, self.var)
return temp_tfm.subs(_dummy_dict)
def _eval_rewrite_as_TransferFunctionMatrix(self, *args, **kwargs):
return self.doit()
@_check_other_MIMO
def __add__(self, other):
if isinstance(other, MIMOParallel):
arg_list = list(other.args)
return MIMOParallel(self, *arg_list)
return MIMOParallel(self, other)
__radd__ = __add__
@_check_other_MIMO
def __sub__(self, other):
return self + (-other)
def __rsub__(self, other):
return -self + other
@_check_other_MIMO
def __mul__(self, other):
if isinstance(other, MIMOSeries):
self_arg_list = list(self.args)
other_arg_list = list(other.args)
return MIMOSeries(*other_arg_list, *self_arg_list) # A*B = MIMOSeries(B, A)
arg_list = list(self.args)
return MIMOSeries(other, *arg_list)
def __neg__(self):
arg_list = list(self.args)
arg_list[0] = -arg_list[0]
return MIMOSeries(*arg_list)
class Parallel(SISOLinearTimeInvariant):
r"""
A class for representing a parallel configuration of SISO systems.
Parameters
==========
args : SISOLinearTimeInvariant
SISO systems in a parallel arrangement.
evaluate : Boolean, Keyword
When passed ``True``, returns the equivalent
``Parallel(*args).doit()``. Set to ``False`` by default.
Raises
======
ValueError
When no argument is passed.
``var`` attribute is not same for every system.
TypeError
Any of the passed ``*args`` has unsupported type
A combination of SISO and MIMO systems is
passed. There should be homogeneity in the
type of systems passed.
Examples
========
>>> from sympy.abc import s, p, a, b
>>> from sympy.physics.control.lti import TransferFunction, Parallel, Series
>>> tf1 = TransferFunction(a*p**2 + b*s, s - p, s)
>>> tf2 = TransferFunction(s**3 - 2, s**4 + 5*s + 6, s)
>>> tf3 = TransferFunction(p**2, p + s, s)
>>> P1 = Parallel(tf1, tf2)
>>> P1
Parallel(TransferFunction(a*p**2 + b*s, -p + s, s), TransferFunction(s**3 - 2, s**4 + 5*s + 6, s))
>>> P1.var
s
>>> P2 = Parallel(tf2, Series(tf3, -tf1))
>>> P2
Parallel(TransferFunction(s**3 - 2, s**4 + 5*s + 6, s), Series(TransferFunction(p**2, p + s, s), TransferFunction(-a*p**2 - b*s, -p + s, s)))
>>> P2.var
s
>>> P3 = Parallel(Series(tf1, tf2), Series(tf2, tf3))
>>> P3
Parallel(Series(TransferFunction(a*p**2 + b*s, -p + s, s), TransferFunction(s**3 - 2, s**4 + 5*s + 6, s)), Series(TransferFunction(s**3 - 2, s**4 + 5*s + 6, s), TransferFunction(p**2, p + s, s)))
>>> P3.var
s
You can get the resultant transfer function by using ``.doit()`` method:
>>> Parallel(tf1, tf2, -tf3).doit()
TransferFunction(-p**2*(-p + s)*(s**4 + 5*s + 6) + (-p + s)*(p + s)*(s**3 - 2) + (p + s)*(a*p**2 + b*s)*(s**4 + 5*s + 6), (-p + s)*(p + s)*(s**4 + 5*s + 6), s)
>>> Parallel(tf2, Series(tf1, -tf3)).doit()
TransferFunction(-p**2*(a*p**2 + b*s)*(s**4 + 5*s + 6) + (-p + s)*(p + s)*(s**3 - 2), (-p + s)*(p + s)*(s**4 + 5*s + 6), s)
Notes
=====
All the transfer functions should use the same complex variable
``var`` of the Laplace transform.
See Also
========
Series, TransferFunction, Feedback
"""
def __new__(cls, *args, evaluate=False):
args = _flatten_args(args, Parallel)
cls._check_args(args)
obj = super().__new__(cls, *args)
return obj.doit() if evaluate else obj
@property
def var(self):
"""
Returns the complex variable used by all the transfer functions.
Examples
========
>>> from sympy.abc import p
>>> from sympy.physics.control.lti import TransferFunction, Parallel, Series
>>> G1 = TransferFunction(p**2 + 2*p + 4, p - 6, p)
>>> G2 = TransferFunction(p, 4 - p, p)
>>> G3 = TransferFunction(0, p**4 - 1, p)
>>> Parallel(G1, G2).var
p
>>> Parallel(-G3, Series(G1, G2)).var
p
"""
return self.args[0].var
def doit(self, **hints):
"""
Returns the resultant transfer function obtained after evaluating
the transfer functions in parallel configuration.
Examples
========
>>> from sympy.abc import s, p, a, b
>>> from sympy.physics.control.lti import TransferFunction, Parallel
>>> tf1 = TransferFunction(a*p**2 + b*s, s - p, s)
>>> tf2 = TransferFunction(s**3 - 2, s**4 + 5*s + 6, s)
>>> Parallel(tf2, tf1).doit()
TransferFunction((-p + s)*(s**3 - 2) + (a*p**2 + b*s)*(s**4 + 5*s + 6), (-p + s)*(s**4 + 5*s + 6), s)
>>> Parallel(-tf1, -tf2).doit()
TransferFunction((2 - s**3)*(-p + s) + (-a*p**2 - b*s)*(s**4 + 5*s + 6), (-p + s)*(s**4 + 5*s + 6), s)
"""
_arg = (arg.doit().to_expr() for arg in self.args)
res = Add(*_arg).as_numer_denom()
return TransferFunction(*res, self.var)
def _eval_rewrite_as_TransferFunction(self, *args, **kwargs):
return self.doit()
@_check_other_SISO
def __add__(self, other):
self_arg_list = list(self.args)
return Parallel(*self_arg_list, other)
__radd__ = __add__
@_check_other_SISO
def __sub__(self, other):
return self + (-other)
def __rsub__(self, other):
return -self + other
@_check_other_SISO
def __mul__(self, other):
if isinstance(other, Series):
arg_list = list(other.args)
return Series(self, *arg_list)
return Series(self, other)
def __neg__(self):
return Series(TransferFunction(-1, 1, self.var), self)
def to_expr(self):
"""Returns the equivalent ``Expr`` object."""
return Add(*(arg.to_expr() for arg in self.args), evaluate=False)
@property
def is_proper(self):
"""
Returns True if degree of the numerator polynomial of the resultant transfer
function is less than or equal to degree of the denominator polynomial of
the same, else False.
Examples
========
>>> from sympy.abc import s, p, a, b
>>> from sympy.physics.control.lti import TransferFunction, Parallel
>>> tf1 = TransferFunction(b*s**2 + p**2 - a*p + s, b - p**2, s)
>>> tf2 = TransferFunction(p**2 - 4*p, p**3 + 3*s + 2, s)
>>> tf3 = TransferFunction(s, s**2 + s + 1, s)
>>> P1 = Parallel(-tf2, tf1)
>>> P1.is_proper
False
>>> P2 = Parallel(tf2, tf3)
>>> P2.is_proper
True
"""
return self.doit().is_proper
@property
def is_strictly_proper(self):
"""
Returns True if degree of the numerator polynomial of the resultant transfer
function is strictly less than degree of the denominator polynomial of
the same, else False.
Examples
========
>>> from sympy.abc import s, p, a, b
>>> from sympy.physics.control.lti import TransferFunction, Parallel
>>> tf1 = TransferFunction(a*p**2 + b*s, s - p, s)
>>> tf2 = TransferFunction(s**3 - 2, s**4 + 5*s + 6, s)
>>> tf3 = TransferFunction(s, s**2 + s + 1, s)
>>> P1 = Parallel(tf1, tf2)
>>> P1.is_strictly_proper
False
>>> P2 = Parallel(tf2, tf3)
>>> P2.is_strictly_proper
True
"""
return self.doit().is_strictly_proper
@property
def is_biproper(self):
"""
Returns True if degree of the numerator polynomial of the resultant transfer
function is equal to degree of the denominator polynomial of
the same, else False.
Examples
========
>>> from sympy.abc import s, p, a, b
>>> from sympy.physics.control.lti import TransferFunction, Parallel
>>> tf1 = TransferFunction(a*p**2 + b*s, s - p, s)
>>> tf2 = TransferFunction(p**2, p + s, s)
>>> tf3 = TransferFunction(s, s**2 + s + 1, s)
>>> P1 = Parallel(tf1, -tf2)
>>> P1.is_biproper
True
>>> P2 = Parallel(tf2, tf3)
>>> P2.is_biproper
False
"""
return self.doit().is_biproper
class MIMOParallel(MIMOLinearTimeInvariant):
r"""
A class for representing a parallel configuration of MIMO systems.
Parameters
==========
args : MIMOLinearTimeInvariant
MIMO Systems in a parallel arrangement.
evaluate : Boolean, Keyword
When passed ``True``, returns the equivalent
``MIMOParallel(*args).doit()``. Set to ``False`` by default.
Raises
======
ValueError
When no argument is passed.
``var`` attribute is not same for every system.
All MIMO systems passed do not have same shape.
TypeError
Any of the passed ``*args`` has unsupported type
A combination of SISO and MIMO systems is
passed. There should be homogeneity in the
type of systems passed, MIMO in this case.
Examples
========
>>> from sympy.abc import s
>>> from sympy.physics.control.lti import TransferFunctionMatrix, MIMOParallel
>>> from sympy import Matrix, pprint
>>> expr_1 = 1/s
>>> expr_2 = s/(s**2-1)
>>> expr_3 = (2 + s)/(s**2 - 1)
>>> expr_4 = 5
>>> tfm_a = TransferFunctionMatrix.from_Matrix(Matrix([[expr_1, expr_2], [expr_3, expr_4]]), s)
>>> tfm_b = TransferFunctionMatrix.from_Matrix(Matrix([[expr_2, expr_1], [expr_4, expr_3]]), s)
>>> tfm_c = TransferFunctionMatrix.from_Matrix(Matrix([[expr_3, expr_4], [expr_1, expr_2]]), s)
>>> MIMOParallel(tfm_a, tfm_b, tfm_c)
MIMOParallel(TransferFunctionMatrix(((TransferFunction(1, s, s), TransferFunction(s, s**2 - 1, s)), (TransferFunction(s + 2, s**2 - 1, s), TransferFunction(5, 1, s)))), TransferFunctionMatrix(((TransferFunction(s, s**2 - 1, s), TransferFunction(1, s, s)), (TransferFunction(5, 1, s), TransferFunction(s + 2, s**2 - 1, s)))), TransferFunctionMatrix(((TransferFunction(s + 2, s**2 - 1, s), TransferFunction(5, 1, s)), (TransferFunction(1, s, s), TransferFunction(s, s**2 - 1, s)))))
>>> pprint(_, use_unicode=False) # For Better Visualization
[ 1 s ] [ s 1 ] [s + 2 5 ]
[ - ------] [------ - ] [------ - ]
[ s 2 ] [ 2 s ] [ 2 1 ]
[ s - 1] [s - 1 ] [s - 1 ]
[ ] + [ ] + [ ]
[s + 2 5 ] [ 5 s + 2 ] [ 1 s ]
[------ - ] [ - ------] [ - ------]
[ 2 1 ] [ 1 2 ] [ s 2 ]
[s - 1 ]{t} [ s - 1]{t} [ s - 1]{t}
>>> MIMOParallel(tfm_a, tfm_b, tfm_c).doit()
TransferFunctionMatrix(((TransferFunction(s**2 + s*(2*s + 2) - 1, s*(s**2 - 1), s), TransferFunction(2*s**2 + 5*s*(s**2 - 1) - 1, s*(s**2 - 1), s)), (TransferFunction(s**2 + s*(s + 2) + 5*s*(s**2 - 1) - 1, s*(s**2 - 1), s), TransferFunction(5*s**2 + 2*s - 3, s**2 - 1, s))))
>>> pprint(_, use_unicode=False)
[ 2 2 / 2 \ ]
[ s + s*(2*s + 2) - 1 2*s + 5*s*\s - 1/ - 1]
[ -------------------- -----------------------]
[ / 2 \ / 2 \ ]
[ s*\s - 1/ s*\s - 1/ ]
[ ]
[ 2 / 2 \ 2 ]
[s + s*(s + 2) + 5*s*\s - 1/ - 1 5*s + 2*s - 3 ]
[--------------------------------- -------------- ]
[ / 2 \ 2 ]
[ s*\s - 1/ s - 1 ]{t}
Notes
=====
All the transfer function matrices should use the same complex variable
``var`` of the Laplace transform.
See Also
========
Parallel, MIMOSeries
"""
def __new__(cls, *args, evaluate=False):
args = _flatten_args(args, MIMOParallel)
cls._check_args(args)
if any(arg.shape != args[0].shape for arg in args):
raise TypeError("Shape of all the args is not equal.")
obj = super().__new__(cls, *args)
return obj.doit() if evaluate else obj
@property
def var(self):
"""
Returns the complex variable used by all the systems.
Examples
========
>>> from sympy.abc import p
>>> from sympy.physics.control.lti import TransferFunction, TransferFunctionMatrix, MIMOParallel
>>> G1 = TransferFunction(p**2 + 2*p + 4, p - 6, p)
>>> G2 = TransferFunction(p, 4 - p, p)
>>> G3 = TransferFunction(0, p**4 - 1, p)
>>> G4 = TransferFunction(p**2, p**2 - 1, p)
>>> tfm_a = TransferFunctionMatrix([[G1, G2], [G3, G4]])
>>> tfm_b = TransferFunctionMatrix([[G2, G1], [G4, G3]])
>>> MIMOParallel(tfm_a, tfm_b).var
p
"""
return self.args[0].var
@property
def num_inputs(self):
"""Returns the number of input signals of the parallel system."""
return self.args[0].num_inputs
@property
def num_outputs(self):
"""Returns the number of output signals of the parallel system."""
return self.args[0].num_outputs
@property
def shape(self):
"""Returns the shape of the equivalent MIMO system."""
return self.num_outputs, self.num_inputs
def doit(self, **hints):
"""
Returns the resultant transfer function matrix obtained after evaluating
the MIMO systems arranged in a parallel configuration.
Examples
========
>>> from sympy.abc import s, p, a, b
>>> from sympy.physics.control.lti import TransferFunction, MIMOParallel, TransferFunctionMatrix
>>> tf1 = TransferFunction(a*p**2 + b*s, s - p, s)
>>> tf2 = TransferFunction(s**3 - 2, s**4 + 5*s + 6, s)
>>> tfm_1 = TransferFunctionMatrix([[tf1, tf2], [tf2, tf1]])
>>> tfm_2 = TransferFunctionMatrix([[tf2, tf1], [tf1, tf2]])
>>> MIMOParallel(tfm_1, tfm_2).doit()
TransferFunctionMatrix(((TransferFunction((-p + s)*(s**3 - 2) + (a*p**2 + b*s)*(s**4 + 5*s + 6), (-p + s)*(s**4 + 5*s + 6), s), TransferFunction((-p + s)*(s**3 - 2) + (a*p**2 + b*s)*(s**4 + 5*s + 6), (-p + s)*(s**4 + 5*s + 6), s)), (TransferFunction((-p + s)*(s**3 - 2) + (a*p**2 + b*s)*(s**4 + 5*s + 6), (-p + s)*(s**4 + 5*s + 6), s), TransferFunction((-p + s)*(s**3 - 2) + (a*p**2 + b*s)*(s**4 + 5*s + 6), (-p + s)*(s**4 + 5*s + 6), s))))
"""
_arg = (arg.doit()._expr_mat for arg in self.args)
res = MatAdd(*_arg, evaluate=True)
return TransferFunctionMatrix.from_Matrix(res, self.var)
def _eval_rewrite_as_TransferFunctionMatrix(self, *args, **kwargs):
return self.doit()
@_check_other_MIMO
def __add__(self, other):
self_arg_list = list(self.args)
return MIMOParallel(*self_arg_list, other)
__radd__ = __add__
@_check_other_MIMO
def __sub__(self, other):
return self + (-other)
def __rsub__(self, other):
return -self + other
@_check_other_MIMO
def __mul__(self, other):
if isinstance(other, MIMOSeries):
arg_list = list(other.args)
return MIMOSeries(*arg_list, self)
return MIMOSeries(other, self)
def __neg__(self):
arg_list = [-arg for arg in list(self.args)]
return MIMOParallel(*arg_list)
class Feedback(SISOLinearTimeInvariant):
r"""
A class for representing closed-loop feedback interconnection between two
SISO input/output systems.
The first argument, ``sys1``, is the feedforward part of the closed-loop
system or in simple words, the dynamical model representing the process
to be controlled. The second argument, ``sys2``, is the feedback system
and controls the fed back signal to ``sys1``. Both ``sys1`` and ``sys2``
can either be ``Series`` or ``TransferFunction`` objects.
Parameters
==========
sys1 : Series, TransferFunction
The feedforward path system.
sys2 : Series, TransferFunction, optional
The feedback path system (often a feedback controller).
It is the model sitting on the feedback path.
If not specified explicitly, the sys2 is
assumed to be unit (1.0) transfer function.
sign : int, optional
The sign of feedback. Can either be ``1``
(for positive feedback) or ``-1`` (for negative feedback).
Default value is `-1`.
Raises
======
ValueError
When ``sys1`` and ``sys2`` are not using the
same complex variable of the Laplace transform.
When a combination of ``sys1`` and ``sys2`` yields
zero denominator.
TypeError
When either ``sys1`` or ``sys2`` is not a ``Series`` or a
``TransferFunction`` object.
Examples
========
>>> from sympy.abc import s
>>> from sympy.physics.control.lti import TransferFunction, Feedback
>>> plant = TransferFunction(3*s**2 + 7*s - 3, s**2 - 4*s + 2, s)
>>> controller = TransferFunction(5*s - 10, s + 7, s)
>>> F1 = Feedback(plant, controller)
>>> F1
Feedback(TransferFunction(3*s**2 + 7*s - 3, s**2 - 4*s + 2, s), TransferFunction(5*s - 10, s + 7, s), -1)
>>> F1.var
s
>>> F1.args
(TransferFunction(3*s**2 + 7*s - 3, s**2 - 4*s + 2, s), TransferFunction(5*s - 10, s + 7, s), -1)
You can get the feedforward and feedback path systems by using ``.sys1`` and ``.sys2`` respectively.
>>> F1.sys1
TransferFunction(3*s**2 + 7*s - 3, s**2 - 4*s + 2, s)
>>> F1.sys2
TransferFunction(5*s - 10, s + 7, s)
You can get the resultant closed loop transfer function obtained by negative feedback
interconnection using ``.doit()`` method.
>>> F1.doit()
TransferFunction((s + 7)*(s**2 - 4*s + 2)*(3*s**2 + 7*s - 3), ((s + 7)*(s**2 - 4*s + 2) + (5*s - 10)*(3*s**2 + 7*s - 3))*(s**2 - 4*s + 2), s)
>>> G = TransferFunction(2*s**2 + 5*s + 1, s**2 + 2*s + 3, s)
>>> C = TransferFunction(5*s + 10, s + 10, s)
>>> F2 = Feedback(G*C, TransferFunction(1, 1, s))
>>> F2.doit()
TransferFunction((s + 10)*(5*s + 10)*(s**2 + 2*s + 3)*(2*s**2 + 5*s + 1), (s + 10)*((s + 10)*(s**2 + 2*s + 3) + (5*s + 10)*(2*s**2 + 5*s + 1))*(s**2 + 2*s + 3), s)
To negate a ``Feedback`` object, the ``-`` operator can be prepended:
>>> -F1
Feedback(TransferFunction(-3*s**2 - 7*s + 3, s**2 - 4*s + 2, s), TransferFunction(10 - 5*s, s + 7, s), -1)
>>> -F2
Feedback(Series(TransferFunction(-1, 1, s), TransferFunction(2*s**2 + 5*s + 1, s**2 + 2*s + 3, s), TransferFunction(5*s + 10, s + 10, s)), TransferFunction(-1, 1, s), -1)
See Also
========
MIMOFeedback, Series, Parallel
"""
def __new__(cls, sys1, sys2=None, sign=-1):
if not sys2:
sys2 = TransferFunction(1, 1, sys1.var)
if not (isinstance(sys1, (TransferFunction, Series))
and isinstance(sys2, (TransferFunction, Series))):
raise TypeError("Unsupported type for `sys1` or `sys2` of Feedback.")
if sign not in [-1, 1]:
raise ValueError("Unsupported type for feedback. `sign` arg should "
"either be 1 (positive feedback loop) or -1 (negative feedback loop).")
if Mul(sys1.to_expr(), sys2.to_expr()).simplify() == sign:
raise ValueError("The equivalent system will have zero denominator.")
if sys1.var != sys2.var:
raise ValueError("Both `sys1` and `sys2` should be using the"
" same complex variable.")
return super().__new__(cls, sys1, sys2, _sympify(sign))
@property
def sys1(self):
"""
Returns the feedforward system of the feedback interconnection.
Examples
========
>>> from sympy.abc import s, p
>>> from sympy.physics.control.lti import TransferFunction, Feedback
>>> plant = TransferFunction(3*s**2 + 7*s - 3, s**2 - 4*s + 2, s)
>>> controller = TransferFunction(5*s - 10, s + 7, s)
>>> F1 = Feedback(plant, controller)
>>> F1.sys1
TransferFunction(3*s**2 + 7*s - 3, s**2 - 4*s + 2, s)
>>> G = TransferFunction(2*s**2 + 5*s + 1, p**2 + 2*p + 3, p)
>>> C = TransferFunction(5*p + 10, p + 10, p)
>>> P = TransferFunction(1 - s, p + 2, p)
>>> F2 = Feedback(TransferFunction(1, 1, p), G*C*P)
>>> F2.sys1
TransferFunction(1, 1, p)
"""
return self.args[0]
@property
def sys2(self):
"""
Returns the feedback controller of the feedback interconnection.
Examples
========
>>> from sympy.abc import s, p
>>> from sympy.physics.control.lti import TransferFunction, Feedback
>>> plant = TransferFunction(3*s**2 + 7*s - 3, s**2 - 4*s + 2, s)
>>> controller = TransferFunction(5*s - 10, s + 7, s)
>>> F1 = Feedback(plant, controller)
>>> F1.sys2
TransferFunction(5*s - 10, s + 7, s)
>>> G = TransferFunction(2*s**2 + 5*s + 1, p**2 + 2*p + 3, p)
>>> C = TransferFunction(5*p + 10, p + 10, p)
>>> P = TransferFunction(1 - s, p + 2, p)
>>> F2 = Feedback(TransferFunction(1, 1, p), G*C*P)
>>> F2.sys2
Series(TransferFunction(2*s**2 + 5*s + 1, p**2 + 2*p + 3, p), TransferFunction(5*p + 10, p + 10, p), TransferFunction(1 - s, p + 2, p))
"""
return self.args[1]
@property
def var(self):
"""
Returns the complex variable of the Laplace transform used by all
the transfer functions involved in the feedback interconnection.
Examples
========
>>> from sympy.abc import s, p
>>> from sympy.physics.control.lti import TransferFunction, Feedback
>>> plant = TransferFunction(3*s**2 + 7*s - 3, s**2 - 4*s + 2, s)
>>> controller = TransferFunction(5*s - 10, s + 7, s)
>>> F1 = Feedback(plant, controller)
>>> F1.var
s
>>> G = TransferFunction(2*s**2 + 5*s + 1, p**2 + 2*p + 3, p)
>>> C = TransferFunction(5*p + 10, p + 10, p)
>>> P = TransferFunction(1 - s, p + 2, p)
>>> F2 = Feedback(TransferFunction(1, 1, p), G*C*P)
>>> F2.var
p
"""
return self.sys1.var
@property
def sign(self):
"""
Returns the type of MIMO Feedback model. ``1``
for Positive and ``-1`` for Negative.
"""
return self.args[2]
@property
def sensitivity(self):
"""
Returns the sensitivity function of the feedback loop.
Sensitivity of a Feedback system is the ratio
of change in the open loop gain to the change in
the closed loop gain.
.. note::
This method would not return the complementary
sensitivity function.
Examples
========
>>> from sympy.abc import p
>>> from sympy.physics.control.lti import TransferFunction, Feedback
>>> C = TransferFunction(5*p + 10, p + 10, p)
>>> P = TransferFunction(1 - p, p + 2, p)
>>> F_1 = Feedback(P, C)
>>> F_1.sensitivity
1/((1 - p)*(5*p + 10)/((p + 2)*(p + 10)) + 1)
"""
return 1/(1 - self.sign*self.sys1.to_expr()*self.sys2.to_expr())
def doit(self, cancel=False, expand=False, **hints):
"""
Returns the resultant transfer function obtained by the
feedback interconnection.
Examples
========
>>> from sympy.abc import s
>>> from sympy.physics.control.lti import TransferFunction, Feedback
>>> plant = TransferFunction(3*s**2 + 7*s - 3, s**2 - 4*s + 2, s)
>>> controller = TransferFunction(5*s - 10, s + 7, s)
>>> F1 = Feedback(plant, controller)
>>> F1.doit()
TransferFunction((s + 7)*(s**2 - 4*s + 2)*(3*s**2 + 7*s - 3), ((s + 7)*(s**2 - 4*s + 2) + (5*s - 10)*(3*s**2 + 7*s - 3))*(s**2 - 4*s + 2), s)
>>> G = TransferFunction(2*s**2 + 5*s + 1, s**2 + 2*s + 3, s)
>>> F2 = Feedback(G, TransferFunction(1, 1, s))
>>> F2.doit()
TransferFunction((s**2 + 2*s + 3)*(2*s**2 + 5*s + 1), (s**2 + 2*s + 3)*(3*s**2 + 7*s + 4), s)
Use kwarg ``expand=True`` to expand the resultant transfer function.
Use ``cancel=True`` to cancel out the common terms in numerator and
denominator.
>>> F2.doit(cancel=True, expand=True)
TransferFunction(2*s**2 + 5*s + 1, 3*s**2 + 7*s + 4, s)
>>> F2.doit(expand=True)
TransferFunction(2*s**4 + 9*s**3 + 17*s**2 + 17*s + 3, 3*s**4 + 13*s**3 + 27*s**2 + 29*s + 12, s)
"""
arg_list = list(self.sys1.args) if isinstance(self.sys1, Series) else [self.sys1]
# F_n and F_d are resultant TFs of num and den of Feedback.
F_n, unit = self.sys1.doit(), TransferFunction(1, 1, self.sys1.var)
if self.sign == -1:
F_d = Parallel(unit, Series(self.sys2, *arg_list)).doit()
else:
F_d = Parallel(unit, -Series(self.sys2, *arg_list)).doit()
_resultant_tf = TransferFunction(F_n.num * F_d.den, F_n.den * F_d.num, F_n.var)
if cancel:
_resultant_tf = _resultant_tf.simplify()
if expand:
_resultant_tf = _resultant_tf.expand()
return _resultant_tf
def _eval_rewrite_as_TransferFunction(self, num, den, sign, **kwargs):
return self.doit()
def __neg__(self):
return Feedback(-self.sys1, -self.sys2, self.sign)
def _is_invertible(a, b, sign):
"""
Checks whether a given pair of MIMO
systems passed is invertible or not.
"""
_mat = eye(a.num_outputs) - sign*(a.doit()._expr_mat)*(b.doit()._expr_mat)
_det = _mat.det()
return _det != 0
class MIMOFeedback(MIMOLinearTimeInvariant):
r"""
A class for representing closed-loop feedback interconnection between two
MIMO input/output systems.
Parameters
==========
sys1 : MIMOSeries, TransferFunctionMatrix
The MIMO system placed on the feedforward path.
sys2 : MIMOSeries, TransferFunctionMatrix
The system placed on the feedback path
(often a feedback controller).
sign : int, optional
The sign of feedback. Can either be ``1``
(for positive feedback) or ``-1`` (for negative feedback).
Default value is `-1`.
Raises
======
ValueError
When ``sys1`` and ``sys2`` are not using the
same complex variable of the Laplace transform.
Forward path model should have an equal number of inputs/outputs
to the feedback path outputs/inputs.
When product of ``sys1`` and ``sys2`` is not a square matrix.
When the equivalent MIMO system is not invertible.
TypeError
When either ``sys1`` or ``sys2`` is not a ``MIMOSeries`` or a
``TransferFunctionMatrix`` object.
Examples
========
>>> from sympy import Matrix, pprint
>>> from sympy.abc import s
>>> from sympy.physics.control.lti import TransferFunctionMatrix, MIMOFeedback
>>> plant_mat = Matrix([[1, 1/s], [0, 1]])
>>> controller_mat = Matrix([[10, 0], [0, 10]]) # Constant Gain
>>> plant = TransferFunctionMatrix.from_Matrix(plant_mat, s)
>>> controller = TransferFunctionMatrix.from_Matrix(controller_mat, s)
>>> feedback = MIMOFeedback(plant, controller) # Negative Feedback (default)
>>> pprint(feedback, use_unicode=False)
/ [1 1] [10 0 ] \-1 [1 1]
| [- -] [-- - ] | [- -]
| [1 s] [1 1 ] | [1 s]
|I + [ ] *[ ] | * [ ]
| [0 1] [0 10] | [0 1]
| [- -] [- --] | [- -]
\ [1 1]{t} [1 1 ]{t}/ [1 1]{t}
To get the equivalent system matrix, use either ``doit`` or ``rewrite`` method.
>>> pprint(feedback.doit(), use_unicode=False)
[1 1 ]
[-- -----]
[11 121*s]
[ ]
[0 1 ]
[- -- ]
[1 11 ]{t}
To negate the ``MIMOFeedback`` object, use ``-`` operator.
>>> neg_feedback = -feedback
>>> pprint(neg_feedback.doit(), use_unicode=False)
[-1 -1 ]
[--- -----]
[ 11 121*s]
[ ]
[ 0 -1 ]
[ - --- ]
[ 1 11 ]{t}
See Also
========
Feedback, MIMOSeries, MIMOParallel
"""
def __new__(cls, sys1, sys2, sign=-1):
if not (isinstance(sys1, (TransferFunctionMatrix, MIMOSeries))
and isinstance(sys2, (TransferFunctionMatrix, MIMOSeries))):
raise TypeError("Unsupported type for `sys1` or `sys2` of MIMO Feedback.")
if sys1.num_inputs != sys2.num_outputs or \
sys1.num_outputs != sys2.num_inputs:
raise ValueError("Product of `sys1` and `sys2` "
"must yield a square matrix.")
if sign not in (-1, 1):
raise ValueError("Unsupported type for feedback. `sign` arg should "
"either be 1 (positive feedback loop) or -1 (negative feedback loop).")
if not _is_invertible(sys1, sys2, sign):
raise ValueError("Non-Invertible system inputted.")
if sys1.var != sys2.var:
raise ValueError("Both `sys1` and `sys2` should be using the"
" same complex variable.")
return super().__new__(cls, sys1, sys2, _sympify(sign))
@property
def sys1(self):
r"""
Returns the system placed on the feedforward path of the MIMO feedback interconnection.
Examples
========
>>> from sympy import pprint
>>> from sympy.abc import s
>>> from sympy.physics.control.lti import TransferFunction, TransferFunctionMatrix, MIMOFeedback
>>> tf1 = TransferFunction(s**2 + s + 1, s**2 - s + 1, s)
>>> tf2 = TransferFunction(1, s, s)
>>> tf3 = TransferFunction(1, 1, s)
>>> sys1 = TransferFunctionMatrix([[tf1, tf2], [tf2, tf1]])
>>> sys2 = TransferFunctionMatrix([[tf3, tf3], [tf3, tf2]])
>>> F_1 = MIMOFeedback(sys1, sys2, 1)
>>> F_1.sys1
TransferFunctionMatrix(((TransferFunction(s**2 + s + 1, s**2 - s + 1, s), TransferFunction(1, s, s)), (TransferFunction(1, s, s), TransferFunction(s**2 + s + 1, s**2 - s + 1, s))))
>>> pprint(_, use_unicode=False)
[ 2 ]
[s + s + 1 1 ]
[---------- - ]
[ 2 s ]
[s - s + 1 ]
[ ]
[ 2 ]
[ 1 s + s + 1]
[ - ----------]
[ s 2 ]
[ s - s + 1]{t}
"""
return self.args[0]
@property
def sys2(self):
r"""
Returns the feedback controller of the MIMO feedback interconnection.
Examples
========
>>> from sympy import pprint
>>> from sympy.abc import s
>>> from sympy.physics.control.lti import TransferFunction, TransferFunctionMatrix, MIMOFeedback
>>> tf1 = TransferFunction(s**2, s**3 - s + 1, s)
>>> tf2 = TransferFunction(1, s, s)
>>> tf3 = TransferFunction(1, 1, s)
>>> sys1 = TransferFunctionMatrix([[tf1, tf2], [tf2, tf1]])
>>> sys2 = TransferFunctionMatrix([[tf1, tf3], [tf3, tf2]])
>>> F_1 = MIMOFeedback(sys1, sys2)
>>> F_1.sys2
TransferFunctionMatrix(((TransferFunction(s**2, s**3 - s + 1, s), TransferFunction(1, 1, s)), (TransferFunction(1, 1, s), TransferFunction(1, s, s))))
>>> pprint(_, use_unicode=False)
[ 2 ]
[ s 1]
[---------- -]
[ 3 1]
[s - s + 1 ]
[ ]
[ 1 1]
[ - -]
[ 1 s]{t}
"""
return self.args[1]
@property
def var(self):
r"""
Returns the complex variable of the Laplace transform used by all
the transfer functions involved in the MIMO feedback loop.
Examples
========
>>> from sympy.abc import p
>>> from sympy.physics.control.lti import TransferFunction, TransferFunctionMatrix, MIMOFeedback
>>> tf1 = TransferFunction(p, 1 - p, p)
>>> tf2 = TransferFunction(1, p, p)
>>> tf3 = TransferFunction(1, 1, p)
>>> sys1 = TransferFunctionMatrix([[tf1, tf2], [tf2, tf1]])
>>> sys2 = TransferFunctionMatrix([[tf1, tf3], [tf3, tf2]])
>>> F_1 = MIMOFeedback(sys1, sys2, 1) # Positive feedback
>>> F_1.var
p
"""
return self.sys1.var
@property
def sign(self):
r"""
Returns the type of feedback interconnection of two models. ``1``
for Positive and ``-1`` for Negative.
"""
return self.args[2]
@property
def sensitivity(self):
r"""
Returns the sensitivity function matrix of the feedback loop.
Sensitivity of a closed-loop system is the ratio of change
in the open loop gain to the change in the closed loop gain.
.. note::
This method would not return the complementary
sensitivity function.
Examples
========
>>> from sympy import pprint
>>> from sympy.abc import p
>>> from sympy.physics.control.lti import TransferFunction, TransferFunctionMatrix, MIMOFeedback
>>> tf1 = TransferFunction(p, 1 - p, p)
>>> tf2 = TransferFunction(1, p, p)
>>> tf3 = TransferFunction(1, 1, p)
>>> sys1 = TransferFunctionMatrix([[tf1, tf2], [tf2, tf1]])
>>> sys2 = TransferFunctionMatrix([[tf1, tf3], [tf3, tf2]])
>>> F_1 = MIMOFeedback(sys1, sys2, 1) # Positive feedback
>>> F_2 = MIMOFeedback(sys1, sys2) # Negative feedback
>>> pprint(F_1.sensitivity, use_unicode=False)
[ 4 3 2 5 4 2 ]
[- p + 3*p - 4*p + 3*p - 1 p - 2*p + 3*p - 3*p + 1 ]
[---------------------------- -----------------------------]
[ 4 3 2 5 4 3 2 ]
[ p + 3*p - 8*p + 8*p - 3 p + 3*p - 8*p + 8*p - 3*p]
[ ]
[ 4 3 2 3 2 ]
[ p - p - p + p 3*p - 6*p + 4*p - 1 ]
[ -------------------------- -------------------------- ]
[ 4 3 2 4 3 2 ]
[ p + 3*p - 8*p + 8*p - 3 p + 3*p - 8*p + 8*p - 3 ]
>>> pprint(F_2.sensitivity, use_unicode=False)
[ 4 3 2 5 4 2 ]
[p - 3*p + 2*p + p - 1 p - 2*p + 3*p - 3*p + 1]
[------------------------ --------------------------]
[ 4 3 5 4 2 ]
[ p - 3*p + 2*p - 1 p - 3*p + 2*p - p ]
[ ]
[ 4 3 2 4 3 ]
[ p - p - p + p 2*p - 3*p + 2*p - 1 ]
[ ------------------- --------------------- ]
[ 4 3 4 3 ]
[ p - 3*p + 2*p - 1 p - 3*p + 2*p - 1 ]
"""
_sys1_mat = self.sys1.doit()._expr_mat
_sys2_mat = self.sys2.doit()._expr_mat
return (eye(self.sys1.num_inputs) - \
self.sign*_sys1_mat*_sys2_mat).inv()
def doit(self, cancel=True, expand=False, **hints):
r"""
Returns the resultant transfer function matrix obtained by the
feedback interconnection.
Examples
========
>>> from sympy import pprint
>>> from sympy.abc import s
>>> from sympy.physics.control.lti import TransferFunction, TransferFunctionMatrix, MIMOFeedback
>>> tf1 = TransferFunction(s, 1 - s, s)
>>> tf2 = TransferFunction(1, s, s)
>>> tf3 = TransferFunction(5, 1, s)
>>> tf4 = TransferFunction(s - 1, s, s)
>>> tf5 = TransferFunction(0, 1, s)
>>> sys1 = TransferFunctionMatrix([[tf1, tf2], [tf3, tf4]])
>>> sys2 = TransferFunctionMatrix([[tf3, tf5], [tf5, tf5]])
>>> F_1 = MIMOFeedback(sys1, sys2, 1)
>>> pprint(F_1, use_unicode=False)
/ [ s 1 ] [5 0] \-1 [ s 1 ]
| [----- - ] [- -] | [----- - ]
| [1 - s s ] [1 1] | [1 - s s ]
|I - [ ] *[ ] | * [ ]
| [ 5 s - 1] [0 0] | [ 5 s - 1]
| [ - -----] [- -] | [ - -----]
\ [ 1 s ]{t} [1 1]{t}/ [ 1 s ]{t}
>>> pprint(F_1.doit(), use_unicode=False)
[ -s s - 1 ]
[------- ----------- ]
[6*s - 1 s*(6*s - 1) ]
[ ]
[5*s - 5 (s - 1)*(6*s + 24)]
[------- ------------------]
[6*s - 1 s*(6*s - 1) ]{t}
If the user wants the resultant ``TransferFunctionMatrix`` object without
canceling the common factors then the ``cancel`` kwarg should be passed ``False``.
>>> pprint(F_1.doit(cancel=False), use_unicode=False)
[ 25*s*(1 - s) 25 - 25*s ]
[ -------------------- -------------- ]
[ 25*(1 - 6*s)*(1 - s) 25*s*(1 - 6*s) ]
[ ]
[s*(25*s - 25) + 5*(1 - s)*(6*s - 1) s*(s - 1)*(6*s - 1) + s*(25*s - 25)]
[----------------------------------- -----------------------------------]
[ (1 - s)*(6*s - 1) 2 ]
[ s *(6*s - 1) ]{t}
If the user wants the expanded form of the resultant transfer function matrix,
the ``expand`` kwarg should be passed as ``True``.
>>> pprint(F_1.doit(expand=True), use_unicode=False)
[ -s s - 1 ]
[------- -------- ]
[6*s - 1 2 ]
[ 6*s - s ]
[ ]
[ 2 ]
[5*s - 5 6*s + 18*s - 24]
[------- ----------------]
[6*s - 1 2 ]
[ 6*s - s ]{t}
"""
_mat = self.sensitivity * self.sys1.doit()._expr_mat
_resultant_tfm = _to_TFM(_mat, self.var)
if cancel:
_resultant_tfm = _resultant_tfm.simplify()
if expand:
_resultant_tfm = _resultant_tfm.expand()
return _resultant_tfm
def _eval_rewrite_as_TransferFunctionMatrix(self, sys1, sys2, sign, **kwargs):
return self.doit()
def __neg__(self):
return MIMOFeedback(-self.sys1, -self.sys2, self.sign)
def _to_TFM(mat, var):
"""Private method to convert ImmutableMatrix to TransferFunctionMatrix efficiently"""
to_tf = lambda expr: TransferFunction.from_rational_expression(expr, var)
arg = [[to_tf(expr) for expr in row] for row in mat.tolist()]
return TransferFunctionMatrix(arg)
class TransferFunctionMatrix(MIMOLinearTimeInvariant):
r"""
A class for representing the MIMO (multiple-input and multiple-output)
generalization of the SISO (single-input and single-output) transfer function.
It is a matrix of transfer functions (``TransferFunction``, SISO-``Series`` or SISO-``Parallel``).
There is only one argument, ``arg`` which is also the compulsory argument.
``arg`` is expected to be strictly of the type list of lists
which holds the transfer functions or reducible to transfer functions.
Parameters
==========
arg : Nested ``List`` (strictly).
Users are expected to input a nested list of ``TransferFunction``, ``Series``
and/or ``Parallel`` objects.
Examples
========
.. note::
``pprint()`` can be used for better visualization of ``TransferFunctionMatrix`` objects.
>>> from sympy.abc import s, p, a
>>> from sympy import pprint
>>> from sympy.physics.control.lti import TransferFunction, TransferFunctionMatrix, Series, Parallel
>>> tf_1 = TransferFunction(s + a, s**2 + s + 1, s)
>>> tf_2 = TransferFunction(p**4 - 3*p + 2, s + p, s)
>>> tf_3 = TransferFunction(3, s + 2, s)
>>> tf_4 = TransferFunction(-a + p, 9*s - 9, s)
>>> tfm_1 = TransferFunctionMatrix([[tf_1], [tf_2], [tf_3]])
>>> tfm_1
TransferFunctionMatrix(((TransferFunction(a + s, s**2 + s + 1, s),), (TransferFunction(p**4 - 3*p + 2, p + s, s),), (TransferFunction(3, s + 2, s),)))
>>> tfm_1.var
s
>>> tfm_1.num_inputs
1
>>> tfm_1.num_outputs
3
>>> tfm_1.shape
(3, 1)
>>> tfm_1.args
(((TransferFunction(a + s, s**2 + s + 1, s),), (TransferFunction(p**4 - 3*p + 2, p + s, s),), (TransferFunction(3, s + 2, s),)),)
>>> tfm_2 = TransferFunctionMatrix([[tf_1, -tf_3], [tf_2, -tf_1], [tf_3, -tf_2]])
>>> tfm_2
TransferFunctionMatrix(((TransferFunction(a + s, s**2 + s + 1, s), TransferFunction(-3, s + 2, s)), (TransferFunction(p**4 - 3*p + 2, p + s, s), TransferFunction(-a - s, s**2 + s + 1, s)), (TransferFunction(3, s + 2, s), TransferFunction(-p**4 + 3*p - 2, p + s, s))))
>>> pprint(tfm_2, use_unicode=False) # pretty-printing for better visualization
[ a + s -3 ]
[ ---------- ----- ]
[ 2 s + 2 ]
[ s + s + 1 ]
[ ]
[ 4 ]
[p - 3*p + 2 -a - s ]
[------------ ---------- ]
[ p + s 2 ]
[ s + s + 1 ]
[ ]
[ 4 ]
[ 3 - p + 3*p - 2]
[ ----- --------------]
[ s + 2 p + s ]{t}
TransferFunctionMatrix can be transposed, if user wants to switch the input and output transfer functions
>>> tfm_2.transpose()
TransferFunctionMatrix(((TransferFunction(a + s, s**2 + s + 1, s), TransferFunction(p**4 - 3*p + 2, p + s, s), TransferFunction(3, s + 2, s)), (TransferFunction(-3, s + 2, s), TransferFunction(-a - s, s**2 + s + 1, s), TransferFunction(-p**4 + 3*p - 2, p + s, s))))
>>> pprint(_, use_unicode=False)
[ 4 ]
[ a + s p - 3*p + 2 3 ]
[---------- ------------ ----- ]
[ 2 p + s s + 2 ]
[s + s + 1 ]
[ ]
[ 4 ]
[ -3 -a - s - p + 3*p - 2]
[ ----- ---------- --------------]
[ s + 2 2 p + s ]
[ s + s + 1 ]{t}
>>> tf_5 = TransferFunction(5, s, s)
>>> tf_6 = TransferFunction(5*s, (2 + s**2), s)
>>> tf_7 = TransferFunction(5, (s*(2 + s**2)), s)
>>> tf_8 = TransferFunction(5, 1, s)
>>> tfm_3 = TransferFunctionMatrix([[tf_5, tf_6], [tf_7, tf_8]])
>>> tfm_3
TransferFunctionMatrix(((TransferFunction(5, s, s), TransferFunction(5*s, s**2 + 2, s)), (TransferFunction(5, s*(s**2 + 2), s), TransferFunction(5, 1, s))))
>>> pprint(tfm_3, use_unicode=False)
[ 5 5*s ]
[ - ------]
[ s 2 ]
[ s + 2]
[ ]
[ 5 5 ]
[---------- - ]
[ / 2 \ 1 ]
[s*\s + 2/ ]{t}
>>> tfm_3.var
s
>>> tfm_3.shape
(2, 2)
>>> tfm_3.num_outputs
2
>>> tfm_3.num_inputs
2
>>> tfm_3.args
(((TransferFunction(5, s, s), TransferFunction(5*s, s**2 + 2, s)), (TransferFunction(5, s*(s**2 + 2), s), TransferFunction(5, 1, s))),)
To access the ``TransferFunction`` at any index in the ``TransferFunctionMatrix``, use the index notation.
>>> tfm_3[1, 0] # gives the TransferFunction present at 2nd Row and 1st Col. Similar to that in Matrix classes
TransferFunction(5, s*(s**2 + 2), s)
>>> tfm_3[0, 0] # gives the TransferFunction present at 1st Row and 1st Col.
TransferFunction(5, s, s)
>>> tfm_3[:, 0] # gives the first column
TransferFunctionMatrix(((TransferFunction(5, s, s),), (TransferFunction(5, s*(s**2 + 2), s),)))
>>> pprint(_, use_unicode=False)
[ 5 ]
[ - ]
[ s ]
[ ]
[ 5 ]
[----------]
[ / 2 \]
[s*\s + 2/]{t}
>>> tfm_3[0, :] # gives the first row
TransferFunctionMatrix(((TransferFunction(5, s, s), TransferFunction(5*s, s**2 + 2, s)),))
>>> pprint(_, use_unicode=False)
[5 5*s ]
[- ------]
[s 2 ]
[ s + 2]{t}
To negate a transfer function matrix, ``-`` operator can be prepended:
>>> tfm_4 = TransferFunctionMatrix([[tf_2], [-tf_1], [tf_3]])
>>> -tfm_4
TransferFunctionMatrix(((TransferFunction(-p**4 + 3*p - 2, p + s, s),), (TransferFunction(a + s, s**2 + s + 1, s),), (TransferFunction(-3, s + 2, s),)))
>>> tfm_5 = TransferFunctionMatrix([[tf_1, tf_2], [tf_3, -tf_1]])
>>> -tfm_5
TransferFunctionMatrix(((TransferFunction(-a - s, s**2 + s + 1, s), TransferFunction(-p**4 + 3*p - 2, p + s, s)), (TransferFunction(-3, s + 2, s), TransferFunction(a + s, s**2 + s + 1, s))))
``subs()`` returns the ``TransferFunctionMatrix`` object with the value substituted in the expression. This will not
mutate your original ``TransferFunctionMatrix``.
>>> tfm_2.subs(p, 2) # substituting p everywhere in tfm_2 with 2.
TransferFunctionMatrix(((TransferFunction(a + s, s**2 + s + 1, s), TransferFunction(-3, s + 2, s)), (TransferFunction(12, s + 2, s), TransferFunction(-a - s, s**2 + s + 1, s)), (TransferFunction(3, s + 2, s), TransferFunction(-12, s + 2, s))))
>>> pprint(_, use_unicode=False)
[ a + s -3 ]
[---------- ----- ]
[ 2 s + 2 ]
[s + s + 1 ]
[ ]
[ 12 -a - s ]
[ ----- ----------]
[ s + 2 2 ]
[ s + s + 1]
[ ]
[ 3 -12 ]
[ ----- ----- ]
[ s + 2 s + 2 ]{t}
>>> pprint(tfm_2, use_unicode=False) # State of tfm_2 is unchanged after substitution
[ a + s -3 ]
[ ---------- ----- ]
[ 2 s + 2 ]
[ s + s + 1 ]
[ ]
[ 4 ]
[p - 3*p + 2 -a - s ]
[------------ ---------- ]
[ p + s 2 ]
[ s + s + 1 ]
[ ]
[ 4 ]
[ 3 - p + 3*p - 2]
[ ----- --------------]
[ s + 2 p + s ]{t}
``subs()`` also supports multiple substitutions.
>>> tfm_2.subs({p: 2, a: 1}) # substituting p with 2 and a with 1
TransferFunctionMatrix(((TransferFunction(s + 1, s**2 + s + 1, s), TransferFunction(-3, s + 2, s)), (TransferFunction(12, s + 2, s), TransferFunction(-s - 1, s**2 + s + 1, s)), (TransferFunction(3, s + 2, s), TransferFunction(-12, s + 2, s))))
>>> pprint(_, use_unicode=False)
[ s + 1 -3 ]
[---------- ----- ]
[ 2 s + 2 ]
[s + s + 1 ]
[ ]
[ 12 -s - 1 ]
[ ----- ----------]
[ s + 2 2 ]
[ s + s + 1]
[ ]
[ 3 -12 ]
[ ----- ----- ]
[ s + 2 s + 2 ]{t}
Users can reduce the ``Series`` and ``Parallel`` elements of the matrix to ``TransferFunction`` by using
``doit()``.
>>> tfm_6 = TransferFunctionMatrix([[Series(tf_3, tf_4), Parallel(tf_3, tf_4)]])
>>> tfm_6
TransferFunctionMatrix(((Series(TransferFunction(3, s + 2, s), TransferFunction(-a + p, 9*s - 9, s)), Parallel(TransferFunction(3, s + 2, s), TransferFunction(-a + p, 9*s - 9, s))),))
>>> pprint(tfm_6, use_unicode=False)
[ -a + p 3 -a + p 3 ]
[-------*----- ------- + -----]
[9*s - 9 s + 2 9*s - 9 s + 2]{t}
>>> tfm_6.doit()
TransferFunctionMatrix(((TransferFunction(-3*a + 3*p, (s + 2)*(9*s - 9), s), TransferFunction(27*s + (-a + p)*(s + 2) - 27, (s + 2)*(9*s - 9), s)),))
>>> pprint(_, use_unicode=False)
[ -3*a + 3*p 27*s + (-a + p)*(s + 2) - 27]
[----------------- ----------------------------]
[(s + 2)*(9*s - 9) (s + 2)*(9*s - 9) ]{t}
>>> tf_9 = TransferFunction(1, s, s)
>>> tf_10 = TransferFunction(1, s**2, s)
>>> tfm_7 = TransferFunctionMatrix([[Series(tf_9, tf_10), tf_9], [tf_10, Parallel(tf_9, tf_10)]])
>>> tfm_7
TransferFunctionMatrix(((Series(TransferFunction(1, s, s), TransferFunction(1, s**2, s)), TransferFunction(1, s, s)), (TransferFunction(1, s**2, s), Parallel(TransferFunction(1, s, s), TransferFunction(1, s**2, s)))))
>>> pprint(tfm_7, use_unicode=False)
[ 1 1 ]
[---- - ]
[ 2 s ]
[s*s ]
[ ]
[ 1 1 1]
[ -- -- + -]
[ 2 2 s]
[ s s ]{t}
>>> tfm_7.doit()
TransferFunctionMatrix(((TransferFunction(1, s**3, s), TransferFunction(1, s, s)), (TransferFunction(1, s**2, s), TransferFunction(s**2 + s, s**3, s))))
>>> pprint(_, use_unicode=False)
[1 1 ]
[-- - ]
[ 3 s ]
[s ]
[ ]
[ 2 ]
[1 s + s]
[-- ------]
[ 2 3 ]
[s s ]{t}
Addition, subtraction, and multiplication of transfer function matrices can form
unevaluated ``Series`` or ``Parallel`` objects.
- For addition and subtraction:
All the transfer function matrices must have the same shape.
- For multiplication (C = A * B):
The number of inputs of the first transfer function matrix (A) must be equal to the
number of outputs of the second transfer function matrix (B).
Also, use pretty-printing (``pprint``) to analyse better.
>>> tfm_8 = TransferFunctionMatrix([[tf_3], [tf_2], [-tf_1]])
>>> tfm_9 = TransferFunctionMatrix([[-tf_3]])
>>> tfm_10 = TransferFunctionMatrix([[tf_1], [tf_2], [tf_4]])
>>> tfm_11 = TransferFunctionMatrix([[tf_4], [-tf_1]])
>>> tfm_12 = TransferFunctionMatrix([[tf_4, -tf_1, tf_3], [-tf_2, -tf_4, -tf_3]])
>>> tfm_8 + tfm_10
MIMOParallel(TransferFunctionMatrix(((TransferFunction(3, s + 2, s),), (TransferFunction(p**4 - 3*p + 2, p + s, s),), (TransferFunction(-a - s, s**2 + s + 1, s),))), TransferFunctionMatrix(((TransferFunction(a + s, s**2 + s + 1, s),), (TransferFunction(p**4 - 3*p + 2, p + s, s),), (TransferFunction(-a + p, 9*s - 9, s),))))
>>> pprint(_, use_unicode=False)
[ 3 ] [ a + s ]
[ ----- ] [ ---------- ]
[ s + 2 ] [ 2 ]
[ ] [ s + s + 1 ]
[ 4 ] [ ]
[p - 3*p + 2] [ 4 ]
[------------] + [p - 3*p + 2]
[ p + s ] [------------]
[ ] [ p + s ]
[ -a - s ] [ ]
[ ---------- ] [ -a + p ]
[ 2 ] [ ------- ]
[ s + s + 1 ]{t} [ 9*s - 9 ]{t}
>>> -tfm_10 - tfm_8
MIMOParallel(TransferFunctionMatrix(((TransferFunction(-a - s, s**2 + s + 1, s),), (TransferFunction(-p**4 + 3*p - 2, p + s, s),), (TransferFunction(a - p, 9*s - 9, s),))), TransferFunctionMatrix(((TransferFunction(-3, s + 2, s),), (TransferFunction(-p**4 + 3*p - 2, p + s, s),), (TransferFunction(a + s, s**2 + s + 1, s),))))
>>> pprint(_, use_unicode=False)
[ -a - s ] [ -3 ]
[ ---------- ] [ ----- ]
[ 2 ] [ s + 2 ]
[ s + s + 1 ] [ ]
[ ] [ 4 ]
[ 4 ] [- p + 3*p - 2]
[- p + 3*p - 2] + [--------------]
[--------------] [ p + s ]
[ p + s ] [ ]
[ ] [ a + s ]
[ a - p ] [ ---------- ]
[ ------- ] [ 2 ]
[ 9*s - 9 ]{t} [ s + s + 1 ]{t}
>>> tfm_12 * tfm_8
MIMOSeries(TransferFunctionMatrix(((TransferFunction(3, s + 2, s),), (TransferFunction(p**4 - 3*p + 2, p + s, s),), (TransferFunction(-a - s, s**2 + s + 1, s),))), TransferFunctionMatrix(((TransferFunction(-a + p, 9*s - 9, s), TransferFunction(-a - s, s**2 + s + 1, s), TransferFunction(3, s + 2, s)), (TransferFunction(-p**4 + 3*p - 2, p + s, s), TransferFunction(a - p, 9*s - 9, s), TransferFunction(-3, s + 2, s)))))
>>> pprint(_, use_unicode=False)
[ 3 ]
[ ----- ]
[ -a + p -a - s 3 ] [ s + 2 ]
[ ------- ---------- -----] [ ]
[ 9*s - 9 2 s + 2] [ 4 ]
[ s + s + 1 ] [p - 3*p + 2]
[ ] *[------------]
[ 4 ] [ p + s ]
[- p + 3*p - 2 a - p -3 ] [ ]
[-------------- ------- -----] [ -a - s ]
[ p + s 9*s - 9 s + 2]{t} [ ---------- ]
[ 2 ]
[ s + s + 1 ]{t}
>>> tfm_12 * tfm_8 * tfm_9
MIMOSeries(TransferFunctionMatrix(((TransferFunction(-3, s + 2, s),),)), TransferFunctionMatrix(((TransferFunction(3, s + 2, s),), (TransferFunction(p**4 - 3*p + 2, p + s, s),), (TransferFunction(-a - s, s**2 + s + 1, s),))), TransferFunctionMatrix(((TransferFunction(-a + p, 9*s - 9, s), TransferFunction(-a - s, s**2 + s + 1, s), TransferFunction(3, s + 2, s)), (TransferFunction(-p**4 + 3*p - 2, p + s, s), TransferFunction(a - p, 9*s - 9, s), TransferFunction(-3, s + 2, s)))))
>>> pprint(_, use_unicode=False)
[ 3 ]
[ ----- ]
[ -a + p -a - s 3 ] [ s + 2 ]
[ ------- ---------- -----] [ ]
[ 9*s - 9 2 s + 2] [ 4 ]
[ s + s + 1 ] [p - 3*p + 2] [ -3 ]
[ ] *[------------] *[-----]
[ 4 ] [ p + s ] [s + 2]{t}
[- p + 3*p - 2 a - p -3 ] [ ]
[-------------- ------- -----] [ -a - s ]
[ p + s 9*s - 9 s + 2]{t} [ ---------- ]
[ 2 ]
[ s + s + 1 ]{t}
>>> tfm_10 + tfm_8*tfm_9
MIMOParallel(TransferFunctionMatrix(((TransferFunction(a + s, s**2 + s + 1, s),), (TransferFunction(p**4 - 3*p + 2, p + s, s),), (TransferFunction(-a + p, 9*s - 9, s),))), MIMOSeries(TransferFunctionMatrix(((TransferFunction(-3, s + 2, s),),)), TransferFunctionMatrix(((TransferFunction(3, s + 2, s),), (TransferFunction(p**4 - 3*p + 2, p + s, s),), (TransferFunction(-a - s, s**2 + s + 1, s),)))))
>>> pprint(_, use_unicode=False)
[ a + s ] [ 3 ]
[ ---------- ] [ ----- ]
[ 2 ] [ s + 2 ]
[ s + s + 1 ] [ ]
[ ] [ 4 ]
[ 4 ] [p - 3*p + 2] [ -3 ]
[p - 3*p + 2] + [------------] *[-----]
[------------] [ p + s ] [s + 2]{t}
[ p + s ] [ ]
[ ] [ -a - s ]
[ -a + p ] [ ---------- ]
[ ------- ] [ 2 ]
[ 9*s - 9 ]{t} [ s + s + 1 ]{t}
These unevaluated ``Series`` or ``Parallel`` objects can convert into the
resultant transfer function matrix using ``.doit()`` method or by
``.rewrite(TransferFunctionMatrix)``.
>>> (-tfm_8 + tfm_10 + tfm_8*tfm_9).doit()
TransferFunctionMatrix(((TransferFunction((a + s)*(s + 2)**3 - 3*(s + 2)**2*(s**2 + s + 1) - 9*(s + 2)*(s**2 + s + 1), (s + 2)**3*(s**2 + s + 1), s),), (TransferFunction((p + s)*(-3*p**4 + 9*p - 6), (p + s)**2*(s + 2), s),), (TransferFunction((-a + p)*(s + 2)*(s**2 + s + 1)**2 + (a + s)*(s + 2)*(9*s - 9)*(s**2 + s + 1) + (3*a + 3*s)*(9*s - 9)*(s**2 + s + 1), (s + 2)*(9*s - 9)*(s**2 + s + 1)**2, s),)))
>>> (-tfm_12 * -tfm_8 * -tfm_9).rewrite(TransferFunctionMatrix)
TransferFunctionMatrix(((TransferFunction(3*(-3*a + 3*p)*(p + s)*(s + 2)*(s**2 + s + 1)**2 + 3*(-3*a - 3*s)*(p + s)*(s + 2)*(9*s - 9)*(s**2 + s + 1) + 3*(a + s)*(s + 2)**2*(9*s - 9)*(-p**4 + 3*p - 2)*(s**2 + s + 1), (p + s)*(s + 2)**3*(9*s - 9)*(s**2 + s + 1)**2, s),), (TransferFunction(3*(-a + p)*(p + s)*(s + 2)**2*(-p**4 + 3*p - 2)*(s**2 + s + 1) + 3*(3*a + 3*s)*(p + s)**2*(s + 2)*(9*s - 9) + 3*(p + s)*(s + 2)*(9*s - 9)*(-3*p**4 + 9*p - 6)*(s**2 + s + 1), (p + s)**2*(s + 2)**3*(9*s - 9)*(s**2 + s + 1), s),)))
See Also
========
TransferFunction, MIMOSeries, MIMOParallel, Feedback
"""
def __new__(cls, arg):
expr_mat_arg = []
try:
var = arg[0][0].var
except TypeError:
raise ValueError("`arg` param in TransferFunctionMatrix should "
"strictly be a nested list containing TransferFunction objects.")
for row_index, row in enumerate(arg):
temp = []
for col_index, element in enumerate(row):
if not isinstance(element, SISOLinearTimeInvariant):
raise TypeError("Each element is expected to be of type `SISOLinearTimeInvariant`.")
if var != element.var:
raise ValueError("Conflicting value(s) found for `var`. All TransferFunction instances in "
"TransferFunctionMatrix should use the same complex variable in Laplace domain.")
temp.append(element.to_expr())
expr_mat_arg.append(temp)
if isinstance(arg, (tuple, list, Tuple)):
# Making nested Tuple (sympy.core.containers.Tuple) from nested list or nested Python tuple
arg = Tuple(*(Tuple(*r, sympify=False) for r in arg), sympify=False)
obj = super(TransferFunctionMatrix, cls).__new__(cls, arg)
obj._expr_mat = ImmutableMatrix(expr_mat_arg)
return obj
@classmethod
def from_Matrix(cls, matrix, var):
"""
Creates a new ``TransferFunctionMatrix`` efficiently from a SymPy Matrix of ``Expr`` objects.
Parameters
==========
matrix : ``ImmutableMatrix`` having ``Expr``/``Number`` elements.
var : Symbol
Complex variable of the Laplace transform which will be used by the
all the ``TransferFunction`` objects in the ``TransferFunctionMatrix``.
Examples
========
>>> from sympy.abc import s
>>> from sympy.physics.control.lti import TransferFunctionMatrix
>>> from sympy import Matrix, pprint
>>> M = Matrix([[s, 1/s], [1/(s+1), s]])
>>> M_tf = TransferFunctionMatrix.from_Matrix(M, s)
>>> pprint(M_tf, use_unicode=False)
[ s 1]
[ - -]
[ 1 s]
[ ]
[ 1 s]
[----- -]
[s + 1 1]{t}
>>> M_tf.elem_poles()
[[[], [0]], [[-1], []]]
>>> M_tf.elem_zeros()
[[[0], []], [[], [0]]]
"""
return _to_TFM(matrix, var)
@property
def var(self):
"""
Returns the complex variable used by all the transfer functions or
``Series``/``Parallel`` objects in a transfer function matrix.
Examples
========
>>> from sympy.abc import p, s
>>> from sympy.physics.control.lti import TransferFunction, TransferFunctionMatrix, Series, Parallel
>>> G1 = TransferFunction(p**2 + 2*p + 4, p - 6, p)
>>> G2 = TransferFunction(p, 4 - p, p)
>>> G3 = TransferFunction(0, p**4 - 1, p)
>>> G4 = TransferFunction(s + 1, s**2 + s + 1, s)
>>> S1 = Series(G1, G2)
>>> S2 = Series(-G3, Parallel(G2, -G1))
>>> tfm1 = TransferFunctionMatrix([[G1], [G2], [G3]])
>>> tfm1.var
p
>>> tfm2 = TransferFunctionMatrix([[-S1, -S2], [S1, S2]])
>>> tfm2.var
p
>>> tfm3 = TransferFunctionMatrix([[G4]])
>>> tfm3.var
s
"""
return self.args[0][0][0].var
@property
def num_inputs(self):
"""
Returns the number of inputs of the system.
Examples
========
>>> from sympy.abc import s, p
>>> from sympy.physics.control.lti import TransferFunction, TransferFunctionMatrix
>>> G1 = TransferFunction(s + 3, s**2 - 3, s)
>>> G2 = TransferFunction(4, s**2, s)
>>> G3 = TransferFunction(p**2 + s**2, p - 3, s)
>>> tfm_1 = TransferFunctionMatrix([[G2, -G1, G3], [-G2, -G1, -G3]])
>>> tfm_1.num_inputs
3
See Also
========
num_outputs
"""
return self._expr_mat.shape[1]
@property
def num_outputs(self):
"""
Returns the number of outputs of the system.
Examples
========
>>> from sympy.abc import s
>>> from sympy.physics.control.lti import TransferFunctionMatrix
>>> from sympy import Matrix
>>> M_1 = Matrix([[s], [1/s]])
>>> TFM = TransferFunctionMatrix.from_Matrix(M_1, s)
>>> print(TFM)
TransferFunctionMatrix(((TransferFunction(s, 1, s),), (TransferFunction(1, s, s),)))
>>> TFM.num_outputs
2
See Also
========
num_inputs
"""
return self._expr_mat.shape[0]
@property
def shape(self):
"""
Returns the shape of the transfer function matrix, that is, ``(# of outputs, # of inputs)``.
Examples
========
>>> from sympy.abc import s, p
>>> from sympy.physics.control.lti import TransferFunction, TransferFunctionMatrix
>>> tf1 = TransferFunction(p**2 - 1, s**4 + s**3 - p, p)
>>> tf2 = TransferFunction(1 - p, p**2 - 3*p + 7, p)
>>> tf3 = TransferFunction(3, 4, p)
>>> tfm1 = TransferFunctionMatrix([[tf1, -tf2]])
>>> tfm1.shape
(1, 2)
>>> tfm2 = TransferFunctionMatrix([[-tf2, tf3], [tf1, -tf1]])
>>> tfm2.shape
(2, 2)
"""
return self._expr_mat.shape
def __neg__(self):
neg = -self._expr_mat
return _to_TFM(neg, self.var)
@_check_other_MIMO
def __add__(self, other):
if not isinstance(other, MIMOParallel):
return MIMOParallel(self, other)
other_arg_list = list(other.args)
return MIMOParallel(self, *other_arg_list)
@_check_other_MIMO
def __sub__(self, other):
return self + (-other)
@_check_other_MIMO
def __mul__(self, other):
if not isinstance(other, MIMOSeries):
return MIMOSeries(other, self)
other_arg_list = list(other.args)
return MIMOSeries(*other_arg_list, self)
def __getitem__(self, key):
trunc = self._expr_mat.__getitem__(key)
if isinstance(trunc, ImmutableMatrix):
return _to_TFM(trunc, self.var)
return TransferFunction.from_rational_expression(trunc, self.var)
def transpose(self):
"""Returns the transpose of the ``TransferFunctionMatrix`` (switched input and output layers)."""
transposed_mat = self._expr_mat.transpose()
return _to_TFM(transposed_mat, self.var)
def elem_poles(self):
"""
Returns the poles of each element of the ``TransferFunctionMatrix``.
.. note::
Actual poles of a MIMO system are NOT the poles of individual elements.
Examples
========
>>> from sympy.abc import s
>>> from sympy.physics.control.lti import TransferFunction, TransferFunctionMatrix
>>> tf_1 = TransferFunction(3, (s + 1), s)
>>> tf_2 = TransferFunction(s + 6, (s + 1)*(s + 2), s)
>>> tf_3 = TransferFunction(s + 3, s**2 + 3*s + 2, s)
>>> tf_4 = TransferFunction(s + 2, s**2 + 5*s - 10, s)
>>> tfm_1 = TransferFunctionMatrix([[tf_1, tf_2], [tf_3, tf_4]])
>>> tfm_1
TransferFunctionMatrix(((TransferFunction(3, s + 1, s), TransferFunction(s + 6, (s + 1)*(s + 2), s)), (TransferFunction(s + 3, s**2 + 3*s + 2, s), TransferFunction(s + 2, s**2 + 5*s - 10, s))))
>>> tfm_1.elem_poles()
[[[-1], [-2, -1]], [[-2, -1], [-5/2 + sqrt(65)/2, -sqrt(65)/2 - 5/2]]]
See Also
========
elem_zeros
"""
return [[element.poles() for element in row] for row in self.doit().args[0]]
def elem_zeros(self):
"""
Returns the zeros of each element of the ``TransferFunctionMatrix``.
.. note::
Actual zeros of a MIMO system are NOT the zeros of individual elements.
Examples
========
>>> from sympy.abc import s
>>> from sympy.physics.control.lti import TransferFunction, TransferFunctionMatrix
>>> tf_1 = TransferFunction(3, (s + 1), s)
>>> tf_2 = TransferFunction(s + 6, (s + 1)*(s + 2), s)
>>> tf_3 = TransferFunction(s + 3, s**2 + 3*s + 2, s)
>>> tf_4 = TransferFunction(s**2 - 9*s + 20, s**2 + 5*s - 10, s)
>>> tfm_1 = TransferFunctionMatrix([[tf_1, tf_2], [tf_3, tf_4]])
>>> tfm_1
TransferFunctionMatrix(((TransferFunction(3, s + 1, s), TransferFunction(s + 6, (s + 1)*(s + 2), s)), (TransferFunction(s + 3, s**2 + 3*s + 2, s), TransferFunction(s**2 - 9*s + 20, s**2 + 5*s - 10, s))))
>>> tfm_1.elem_zeros()
[[[], [-6]], [[-3], [4, 5]]]
See Also
========
elem_poles
"""
return [[element.zeros() for element in row] for row in self.doit().args[0]]
def _flat(self):
"""Returns flattened list of args in TransferFunctionMatrix"""
return [elem for tup in self.args[0] for elem in tup]
def _eval_evalf(self, prec):
"""Calls evalf() on each transfer function in the transfer function matrix"""
dps = prec_to_dps(prec)
mat = self._expr_mat.applyfunc(lambda a: a.evalf(n=dps))
return _to_TFM(mat, self.var)
def _eval_simplify(self, **kwargs):
"""Simplifies the transfer function matrix"""
simp_mat = self._expr_mat.applyfunc(lambda a: cancel(a, expand=False))
return _to_TFM(simp_mat, self.var)
def expand(self, **hints):
"""Expands the transfer function matrix"""
expand_mat = self._expr_mat.expand(**hints)
return _to_TFM(expand_mat, self.var)
|
7e8f49af4ce1eca957f86583f14e7f6bdf6ea0b08708a24905cd3f30a014f6a8 | """Dirac notation for states."""
from sympy.core.cache import cacheit
from sympy.core.containers import Tuple
from sympy.core.expr import Expr
from sympy.core.function import Function
from sympy.core.numbers import oo
from sympy.core.singleton import S
from sympy.functions.elementary.complexes import conjugate
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.integrals.integrals import integrate
from sympy.printing.pretty.stringpict import stringPict
from sympy.physics.quantum.qexpr import QExpr, dispatch_method
__all__ = [
'KetBase',
'BraBase',
'StateBase',
'State',
'Ket',
'Bra',
'TimeDepState',
'TimeDepBra',
'TimeDepKet',
'OrthogonalKet',
'OrthogonalBra',
'OrthogonalState',
'Wavefunction'
]
#-----------------------------------------------------------------------------
# States, bras and kets.
#-----------------------------------------------------------------------------
# ASCII brackets
_lbracket = "<"
_rbracket = ">"
_straight_bracket = "|"
# Unicode brackets
# MATHEMATICAL ANGLE BRACKETS
_lbracket_ucode = "\N{MATHEMATICAL LEFT ANGLE BRACKET}"
_rbracket_ucode = "\N{MATHEMATICAL RIGHT ANGLE BRACKET}"
# LIGHT VERTICAL BAR
_straight_bracket_ucode = "\N{LIGHT VERTICAL BAR}"
# Other options for unicode printing of <, > and | for Dirac notation.
# LEFT-POINTING ANGLE BRACKET
# _lbracket = "\u2329"
# _rbracket = "\u232A"
# LEFT ANGLE BRACKET
# _lbracket = "\u3008"
# _rbracket = "\u3009"
# VERTICAL LINE
# _straight_bracket = "\u007C"
class StateBase(QExpr):
"""Abstract base class for general abstract states in quantum mechanics.
All other state classes defined will need to inherit from this class. It
carries the basic structure for all other states such as dual, _eval_adjoint
and label.
This is an abstract base class and you should not instantiate it directly,
instead use State.
"""
@classmethod
def _operators_to_state(self, ops, **options):
""" Returns the eigenstate instance for the passed operators.
This method should be overridden in subclasses. It will handle being
passed either an Operator instance or set of Operator instances. It
should return the corresponding state INSTANCE or simply raise a
NotImplementedError. See cartesian.py for an example.
"""
raise NotImplementedError("Cannot map operators to states in this class. Method not implemented!")
def _state_to_operators(self, op_classes, **options):
""" Returns the operators which this state instance is an eigenstate
of.
This method should be overridden in subclasses. It will be called on
state instances and be passed the operator classes that we wish to make
into instances. The state instance will then transform the classes
appropriately, or raise a NotImplementedError if it cannot return
operator instances. See cartesian.py for examples,
"""
raise NotImplementedError(
"Cannot map this state to operators. Method not implemented!")
@property
def operators(self):
"""Return the operator(s) that this state is an eigenstate of"""
from .operatorset import state_to_operators # import internally to avoid circular import errors
return state_to_operators(self)
def _enumerate_state(self, num_states, **options):
raise NotImplementedError("Cannot enumerate this state!")
def _represent_default_basis(self, **options):
return self._represent(basis=self.operators)
#-------------------------------------------------------------------------
# Dagger/dual
#-------------------------------------------------------------------------
@property
def dual(self):
"""Return the dual state of this one."""
return self.dual_class()._new_rawargs(self.hilbert_space, *self.args)
@classmethod
def dual_class(self):
"""Return the class used to construct the dual."""
raise NotImplementedError(
'dual_class must be implemented in a subclass'
)
def _eval_adjoint(self):
"""Compute the dagger of this state using the dual."""
return self.dual
#-------------------------------------------------------------------------
# Printing
#-------------------------------------------------------------------------
def _pretty_brackets(self, height, use_unicode=True):
# Return pretty printed brackets for the state
# Ideally, this could be done by pform.parens but it does not support the angled < and >
# Setup for unicode vs ascii
if use_unicode:
lbracket, rbracket = getattr(self, 'lbracket_ucode', ""), getattr(self, 'rbracket_ucode', "")
slash, bslash, vert = '\N{BOX DRAWINGS LIGHT DIAGONAL UPPER RIGHT TO LOWER LEFT}', \
'\N{BOX DRAWINGS LIGHT DIAGONAL UPPER LEFT TO LOWER RIGHT}', \
'\N{BOX DRAWINGS LIGHT VERTICAL}'
else:
lbracket, rbracket = getattr(self, 'lbracket', ""), getattr(self, 'rbracket', "")
slash, bslash, vert = '/', '\\', '|'
# If height is 1, just return brackets
if height == 1:
return stringPict(lbracket), stringPict(rbracket)
# Make height even
height += (height % 2)
brackets = []
for bracket in lbracket, rbracket:
# Create left bracket
if bracket in {_lbracket, _lbracket_ucode}:
bracket_args = [ ' ' * (height//2 - i - 1) +
slash for i in range(height // 2)]
bracket_args.extend(
[' ' * i + bslash for i in range(height // 2)])
# Create right bracket
elif bracket in {_rbracket, _rbracket_ucode}:
bracket_args = [ ' ' * i + bslash for i in range(height // 2)]
bracket_args.extend([ ' ' * (
height//2 - i - 1) + slash for i in range(height // 2)])
# Create straight bracket
elif bracket in {_straight_bracket, _straight_bracket_ucode}:
bracket_args = [vert] * height
else:
raise ValueError(bracket)
brackets.append(
stringPict('\n'.join(bracket_args), baseline=height//2))
return brackets
def _sympystr(self, printer, *args):
contents = self._print_contents(printer, *args)
return '%s%s%s' % (getattr(self, 'lbracket', ""), contents, getattr(self, 'rbracket', ""))
def _pretty(self, printer, *args):
from sympy.printing.pretty.stringpict import prettyForm
# Get brackets
pform = self._print_contents_pretty(printer, *args)
lbracket, rbracket = self._pretty_brackets(
pform.height(), printer._use_unicode)
# Put together state
pform = prettyForm(*pform.left(lbracket))
pform = prettyForm(*pform.right(rbracket))
return pform
def _latex(self, printer, *args):
contents = self._print_contents_latex(printer, *args)
# The extra {} brackets are needed to get matplotlib's latex
# rendered to render this properly.
return '{%s%s%s}' % (getattr(self, 'lbracket_latex', ""), contents, getattr(self, 'rbracket_latex', ""))
class KetBase(StateBase):
"""Base class for Kets.
This class defines the dual property and the brackets for printing. This is
an abstract base class and you should not instantiate it directly, instead
use Ket.
"""
lbracket = _straight_bracket
rbracket = _rbracket
lbracket_ucode = _straight_bracket_ucode
rbracket_ucode = _rbracket_ucode
lbracket_latex = r'\left|'
rbracket_latex = r'\right\rangle '
@classmethod
def default_args(self):
return ("psi",)
@classmethod
def dual_class(self):
return BraBase
def __mul__(self, other):
"""KetBase*other"""
from sympy.physics.quantum.operator import OuterProduct
if isinstance(other, BraBase):
return OuterProduct(self, other)
else:
return Expr.__mul__(self, other)
def __rmul__(self, other):
"""other*KetBase"""
from sympy.physics.quantum.innerproduct import InnerProduct
if isinstance(other, BraBase):
return InnerProduct(other, self)
else:
return Expr.__rmul__(self, other)
#-------------------------------------------------------------------------
# _eval_* methods
#-------------------------------------------------------------------------
def _eval_innerproduct(self, bra, **hints):
"""Evaluate the inner product between this ket and a bra.
This is called to compute <bra|ket>, where the ket is ``self``.
This method will dispatch to sub-methods having the format::
``def _eval_innerproduct_BraClass(self, **hints):``
Subclasses should define these methods (one for each BraClass) to
teach the ket how to take inner products with bras.
"""
return dispatch_method(self, '_eval_innerproduct', bra, **hints)
def _apply_operator(self, op, **options):
"""Apply an Operator to this Ket.
This method will dispatch to methods having the format::
``def _apply_operator_OperatorName(op, **options):``
Subclasses should define these methods (one for each OperatorName) to
teach the Ket how operators act on it.
Parameters
==========
op : Operator
The Operator that is acting on the Ket.
options : dict
A dict of key/value pairs that control how the operator is applied
to the Ket.
"""
return dispatch_method(self, '_apply_operator', op, **options)
class BraBase(StateBase):
"""Base class for Bras.
This class defines the dual property and the brackets for printing. This
is an abstract base class and you should not instantiate it directly,
instead use Bra.
"""
lbracket = _lbracket
rbracket = _straight_bracket
lbracket_ucode = _lbracket_ucode
rbracket_ucode = _straight_bracket_ucode
lbracket_latex = r'\left\langle '
rbracket_latex = r'\right|'
@classmethod
def _operators_to_state(self, ops, **options):
state = self.dual_class()._operators_to_state(ops, **options)
return state.dual
def _state_to_operators(self, op_classes, **options):
return self.dual._state_to_operators(op_classes, **options)
def _enumerate_state(self, num_states, **options):
dual_states = self.dual._enumerate_state(num_states, **options)
return [x.dual for x in dual_states]
@classmethod
def default_args(self):
return self.dual_class().default_args()
@classmethod
def dual_class(self):
return KetBase
def __mul__(self, other):
"""BraBase*other"""
from sympy.physics.quantum.innerproduct import InnerProduct
if isinstance(other, KetBase):
return InnerProduct(self, other)
else:
return Expr.__mul__(self, other)
def __rmul__(self, other):
"""other*BraBase"""
from sympy.physics.quantum.operator import OuterProduct
if isinstance(other, KetBase):
return OuterProduct(other, self)
else:
return Expr.__rmul__(self, other)
def _represent(self, **options):
"""A default represent that uses the Ket's version."""
from sympy.physics.quantum.dagger import Dagger
return Dagger(self.dual._represent(**options))
class State(StateBase):
"""General abstract quantum state used as a base class for Ket and Bra."""
pass
class Ket(State, KetBase):
"""A general time-independent Ket in quantum mechanics.
Inherits from State and KetBase. This class should be used as the base
class for all physical, time-independent Kets in a system. This class
and its subclasses will be the main classes that users will use for
expressing Kets in Dirac notation [1]_.
Parameters
==========
args : tuple
The list of numbers or parameters that uniquely specify the
ket. This will usually be its symbol or its quantum numbers. For
time-dependent state, this will include the time.
Examples
========
Create a simple Ket and looking at its properties::
>>> from sympy.physics.quantum import Ket
>>> from sympy import symbols, I
>>> k = Ket('psi')
>>> k
|psi>
>>> k.hilbert_space
H
>>> k.is_commutative
False
>>> k.label
(psi,)
Ket's know about their associated bra::
>>> k.dual
<psi|
>>> k.dual_class()
<class 'sympy.physics.quantum.state.Bra'>
Take a linear combination of two kets::
>>> k0 = Ket(0)
>>> k1 = Ket(1)
>>> 2*I*k0 - 4*k1
2*I*|0> - 4*|1>
Compound labels are passed as tuples::
>>> n, m = symbols('n,m')
>>> k = Ket(n,m)
>>> k
|nm>
References
==========
.. [1] https://en.wikipedia.org/wiki/Bra-ket_notation
"""
@classmethod
def dual_class(self):
return Bra
class Bra(State, BraBase):
"""A general time-independent Bra in quantum mechanics.
Inherits from State and BraBase. A Bra is the dual of a Ket [1]_. This
class and its subclasses will be the main classes that users will use for
expressing Bras in Dirac notation.
Parameters
==========
args : tuple
The list of numbers or parameters that uniquely specify the
ket. This will usually be its symbol or its quantum numbers. For
time-dependent state, this will include the time.
Examples
========
Create a simple Bra and look at its properties::
>>> from sympy.physics.quantum import Bra
>>> from sympy import symbols, I
>>> b = Bra('psi')
>>> b
<psi|
>>> b.hilbert_space
H
>>> b.is_commutative
False
Bra's know about their dual Ket's::
>>> b.dual
|psi>
>>> b.dual_class()
<class 'sympy.physics.quantum.state.Ket'>
Like Kets, Bras can have compound labels and be manipulated in a similar
manner::
>>> n, m = symbols('n,m')
>>> b = Bra(n,m) - I*Bra(m,n)
>>> b
-I*<mn| + <nm|
Symbols in a Bra can be substituted using ``.subs``::
>>> b.subs(n,m)
<mm| - I*<mm|
References
==========
.. [1] https://en.wikipedia.org/wiki/Bra-ket_notation
"""
@classmethod
def dual_class(self):
return Ket
#-----------------------------------------------------------------------------
# Time dependent states, bras and kets.
#-----------------------------------------------------------------------------
class TimeDepState(StateBase):
"""Base class for a general time-dependent quantum state.
This class is used as a base class for any time-dependent state. The main
difference between this class and the time-independent state is that this
class takes a second argument that is the time in addition to the usual
label argument.
Parameters
==========
args : tuple
The list of numbers or parameters that uniquely specify the ket. This
will usually be its symbol or its quantum numbers. For time-dependent
state, this will include the time as the final argument.
"""
#-------------------------------------------------------------------------
# Initialization
#-------------------------------------------------------------------------
@classmethod
def default_args(self):
return ("psi", "t")
#-------------------------------------------------------------------------
# Properties
#-------------------------------------------------------------------------
@property
def label(self):
"""The label of the state."""
return self.args[:-1]
@property
def time(self):
"""The time of the state."""
return self.args[-1]
#-------------------------------------------------------------------------
# Printing
#-------------------------------------------------------------------------
def _print_time(self, printer, *args):
return printer._print(self.time, *args)
_print_time_repr = _print_time
_print_time_latex = _print_time
def _print_time_pretty(self, printer, *args):
pform = printer._print(self.time, *args)
return pform
def _print_contents(self, printer, *args):
label = self._print_label(printer, *args)
time = self._print_time(printer, *args)
return '%s;%s' % (label, time)
def _print_label_repr(self, printer, *args):
label = self._print_sequence(self.label, ',', printer, *args)
time = self._print_time_repr(printer, *args)
return '%s,%s' % (label, time)
def _print_contents_pretty(self, printer, *args):
label = self._print_label_pretty(printer, *args)
time = self._print_time_pretty(printer, *args)
return printer._print_seq((label, time), delimiter=';')
def _print_contents_latex(self, printer, *args):
label = self._print_sequence(
self.label, self._label_separator, printer, *args)
time = self._print_time_latex(printer, *args)
return '%s;%s' % (label, time)
class TimeDepKet(TimeDepState, KetBase):
"""General time-dependent Ket in quantum mechanics.
This inherits from ``TimeDepState`` and ``KetBase`` and is the main class
that should be used for Kets that vary with time. Its dual is a
``TimeDepBra``.
Parameters
==========
args : tuple
The list of numbers or parameters that uniquely specify the ket. This
will usually be its symbol or its quantum numbers. For time-dependent
state, this will include the time as the final argument.
Examples
========
Create a TimeDepKet and look at its attributes::
>>> from sympy.physics.quantum import TimeDepKet
>>> k = TimeDepKet('psi', 't')
>>> k
|psi;t>
>>> k.time
t
>>> k.label
(psi,)
>>> k.hilbert_space
H
TimeDepKets know about their dual bra::
>>> k.dual
<psi;t|
>>> k.dual_class()
<class 'sympy.physics.quantum.state.TimeDepBra'>
"""
@classmethod
def dual_class(self):
return TimeDepBra
class TimeDepBra(TimeDepState, BraBase):
"""General time-dependent Bra in quantum mechanics.
This inherits from TimeDepState and BraBase and is the main class that
should be used for Bras that vary with time. Its dual is a TimeDepBra.
Parameters
==========
args : tuple
The list of numbers or parameters that uniquely specify the ket. This
will usually be its symbol or its quantum numbers. For time-dependent
state, this will include the time as the final argument.
Examples
========
>>> from sympy.physics.quantum import TimeDepBra
>>> b = TimeDepBra('psi', 't')
>>> b
<psi;t|
>>> b.time
t
>>> b.label
(psi,)
>>> b.hilbert_space
H
>>> b.dual
|psi;t>
"""
@classmethod
def dual_class(self):
return TimeDepKet
class OrthogonalState(State, StateBase):
"""General abstract quantum state used as a base class for Ket and Bra."""
pass
class OrthogonalKet(OrthogonalState, KetBase):
"""Orthogonal Ket in quantum mechanics.
The inner product of two states with different labels will give zero,
states with the same label will give one.
>>> from sympy.physics.quantum import OrthogonalBra, OrthogonalKet
>>> from sympy.abc import m, n
>>> (OrthogonalBra(n)*OrthogonalKet(n)).doit()
1
>>> (OrthogonalBra(n)*OrthogonalKet(n+1)).doit()
0
>>> (OrthogonalBra(n)*OrthogonalKet(m)).doit()
<n|m>
"""
@classmethod
def dual_class(self):
return OrthogonalBra
def _eval_innerproduct(self, bra, **hints):
if len(self.args) != len(bra.args):
raise ValueError('Cannot multiply a ket that has a different number of labels.')
for arg, bra_arg in zip(self.args, bra.args):
diff = arg - bra_arg
diff = diff.expand()
is_zero = diff.is_zero
if is_zero is False:
return 0
if is_zero is None:
return None
return 1
class OrthogonalBra(OrthogonalState, BraBase):
"""Orthogonal Bra in quantum mechanics.
"""
@classmethod
def dual_class(self):
return OrthogonalKet
class Wavefunction(Function):
"""Class for representations in continuous bases
This class takes an expression and coordinates in its constructor. It can
be used to easily calculate normalizations and probabilities.
Parameters
==========
expr : Expr
The expression representing the functional form of the w.f.
coords : Symbol or tuple
The coordinates to be integrated over, and their bounds
Examples
========
Particle in a box, specifying bounds in the more primitive way of using
Piecewise:
>>> from sympy import Symbol, Piecewise, pi, N
>>> from sympy.functions import sqrt, sin
>>> from sympy.physics.quantum.state import Wavefunction
>>> x = Symbol('x', real=True)
>>> n = 1
>>> L = 1
>>> g = Piecewise((0, x < 0), (0, x > L), (sqrt(2//L)*sin(n*pi*x/L), True))
>>> f = Wavefunction(g, x)
>>> f.norm
1
>>> f.is_normalized
True
>>> p = f.prob()
>>> p(0)
0
>>> p(L)
0
>>> p(0.5)
2
>>> p(0.85*L)
2*sin(0.85*pi)**2
>>> N(p(0.85*L))
0.412214747707527
Additionally, you can specify the bounds of the function and the indices in
a more compact way:
>>> from sympy import symbols, pi, diff
>>> from sympy.functions import sqrt, sin
>>> from sympy.physics.quantum.state import Wavefunction
>>> x, L = symbols('x,L', positive=True)
>>> n = symbols('n', integer=True, positive=True)
>>> g = sqrt(2/L)*sin(n*pi*x/L)
>>> f = Wavefunction(g, (x, 0, L))
>>> f.norm
1
>>> f(L+1)
0
>>> f(L-1)
sqrt(2)*sin(pi*n*(L - 1)/L)/sqrt(L)
>>> f(-1)
0
>>> f(0.85)
sqrt(2)*sin(0.85*pi*n/L)/sqrt(L)
>>> f(0.85, n=1, L=1)
sqrt(2)*sin(0.85*pi)
>>> f.is_commutative
False
All arguments are automatically sympified, so you can define the variables
as strings rather than symbols:
>>> expr = x**2
>>> f = Wavefunction(expr, 'x')
>>> type(f.variables[0])
<class 'sympy.core.symbol.Symbol'>
Derivatives of Wavefunctions will return Wavefunctions:
>>> diff(f, x)
Wavefunction(2*x, x)
"""
#Any passed tuples for coordinates and their bounds need to be
#converted to Tuples before Function's constructor is called, to
#avoid errors from calling is_Float in the constructor
def __new__(cls, *args, **options):
new_args = [None for i in args]
ct = 0
for arg in args:
if isinstance(arg, tuple):
new_args[ct] = Tuple(*arg)
else:
new_args[ct] = arg
ct += 1
return super().__new__(cls, *new_args, **options)
def __call__(self, *args, **options):
var = self.variables
if len(args) != len(var):
raise NotImplementedError(
"Incorrect number of arguments to function!")
ct = 0
#If the passed value is outside the specified bounds, return 0
for v in var:
lower, upper = self.limits[v]
#Do the comparison to limits only if the passed symbol is actually
#a symbol present in the limits;
#Had problems with a comparison of x > L
if isinstance(args[ct], Expr) and \
not (lower in args[ct].free_symbols
or upper in args[ct].free_symbols):
continue
if (args[ct] < lower) == True or (args[ct] > upper) == True:
return S.Zero
ct += 1
expr = self.expr
#Allows user to make a call like f(2, 4, m=1, n=1)
for symbol in list(expr.free_symbols):
if str(symbol) in options.keys():
val = options[str(symbol)]
expr = expr.subs(symbol, val)
return expr.subs(zip(var, args))
def _eval_derivative(self, symbol):
expr = self.expr
deriv = expr._eval_derivative(symbol)
return Wavefunction(deriv, *self.args[1:])
def _eval_conjugate(self):
return Wavefunction(conjugate(self.expr), *self.args[1:])
def _eval_transpose(self):
return self
@property
def free_symbols(self):
return self.expr.free_symbols
@property
def is_commutative(self):
"""
Override Function's is_commutative so that order is preserved in
represented expressions
"""
return False
@classmethod
def eval(self, *args):
return None
@property
def variables(self):
"""
Return the coordinates which the wavefunction depends on
Examples
========
>>> from sympy.physics.quantum.state import Wavefunction
>>> from sympy import symbols
>>> x,y = symbols('x,y')
>>> f = Wavefunction(x*y, x, y)
>>> f.variables
(x, y)
>>> g = Wavefunction(x*y, x)
>>> g.variables
(x,)
"""
var = [g[0] if isinstance(g, Tuple) else g for g in self._args[1:]]
return tuple(var)
@property
def limits(self):
"""
Return the limits of the coordinates which the w.f. depends on If no
limits are specified, defaults to ``(-oo, oo)``.
Examples
========
>>> from sympy.physics.quantum.state import Wavefunction
>>> from sympy import symbols
>>> x, y = symbols('x, y')
>>> f = Wavefunction(x**2, (x, 0, 1))
>>> f.limits
{x: (0, 1)}
>>> f = Wavefunction(x**2, x)
>>> f.limits
{x: (-oo, oo)}
>>> f = Wavefunction(x**2 + y**2, x, (y, -1, 2))
>>> f.limits
{x: (-oo, oo), y: (-1, 2)}
"""
limits = [(g[1], g[2]) if isinstance(g, Tuple) else (-oo, oo)
for g in self._args[1:]]
return dict(zip(self.variables, tuple(limits)))
@property
def expr(self):
"""
Return the expression which is the functional form of the Wavefunction
Examples
========
>>> from sympy.physics.quantum.state import Wavefunction
>>> from sympy import symbols
>>> x, y = symbols('x, y')
>>> f = Wavefunction(x**2, x)
>>> f.expr
x**2
"""
return self._args[0]
@property
def is_normalized(self):
"""
Returns true if the Wavefunction is properly normalized
Examples
========
>>> from sympy import symbols, pi
>>> from sympy.functions import sqrt, sin
>>> from sympy.physics.quantum.state import Wavefunction
>>> x, L = symbols('x,L', positive=True)
>>> n = symbols('n', integer=True, positive=True)
>>> g = sqrt(2/L)*sin(n*pi*x/L)
>>> f = Wavefunction(g, (x, 0, L))
>>> f.is_normalized
True
"""
return (self.norm == 1.0)
@property # type: ignore
@cacheit
def norm(self):
"""
Return the normalization of the specified functional form.
This function integrates over the coordinates of the Wavefunction, with
the bounds specified.
Examples
========
>>> from sympy import symbols, pi
>>> from sympy.functions import sqrt, sin
>>> from sympy.physics.quantum.state import Wavefunction
>>> x, L = symbols('x,L', positive=True)
>>> n = symbols('n', integer=True, positive=True)
>>> g = sqrt(2/L)*sin(n*pi*x/L)
>>> f = Wavefunction(g, (x, 0, L))
>>> f.norm
1
>>> g = sin(n*pi*x/L)
>>> f = Wavefunction(g, (x, 0, L))
>>> f.norm
sqrt(2)*sqrt(L)/2
"""
exp = self.expr*conjugate(self.expr)
var = self.variables
limits = self.limits
for v in var:
curr_limits = limits[v]
exp = integrate(exp, (v, curr_limits[0], curr_limits[1]))
return sqrt(exp)
def normalize(self):
"""
Return a normalized version of the Wavefunction
Examples
========
>>> from sympy import symbols, pi
>>> from sympy.functions import sin
>>> from sympy.physics.quantum.state import Wavefunction
>>> x = symbols('x', real=True)
>>> L = symbols('L', positive=True)
>>> n = symbols('n', integer=True, positive=True)
>>> g = sin(n*pi*x/L)
>>> f = Wavefunction(g, (x, 0, L))
>>> f.normalize()
Wavefunction(sqrt(2)*sin(pi*n*x/L)/sqrt(L), (x, 0, L))
"""
const = self.norm
if const is oo:
raise NotImplementedError("The function is not normalizable!")
else:
return Wavefunction((const)**(-1)*self.expr, *self.args[1:])
def prob(self):
r"""
Return the absolute magnitude of the w.f., `|\psi(x)|^2`
Examples
========
>>> from sympy import symbols, pi
>>> from sympy.functions import sin
>>> from sympy.physics.quantum.state import Wavefunction
>>> x, L = symbols('x,L', real=True)
>>> n = symbols('n', integer=True)
>>> g = sin(n*pi*x/L)
>>> f = Wavefunction(g, (x, 0, L))
>>> f.prob()
Wavefunction(sin(pi*n*x/L)**2, x)
"""
return Wavefunction(self.expr*conjugate(self.expr), *self.variables)
|
64bfb26316589ee136ee9133fa5364d3142dbb6051787573b39add3c9ca49639 | """An implementation of gates that act on qubits.
Gates are unitary operators that act on the space of qubits.
Medium Term Todo:
* Optimize Gate._apply_operators_Qubit to remove the creation of many
intermediate Qubit objects.
* Add commutation relationships to all operators and use this in gate_sort.
* Fix gate_sort and gate_simp.
* Get multi-target UGates plotting properly.
* Get UGate to work with either sympy/numpy matrices and output either
format. This should also use the matrix slots.
"""
from itertools import chain
import random
from sympy.core.add import Add
from sympy.core.containers import Tuple
from sympy.core.mul import Mul
from sympy.core.numbers import (I, Integer)
from sympy.core.power import Pow
from sympy.core.numbers import Number
from sympy.core.singleton import S as _S
from sympy.core.sorting import default_sort_key
from sympy.core.sympify import _sympify
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.printing.pretty.stringpict import prettyForm, stringPict
from sympy.physics.quantum.anticommutator import AntiCommutator
from sympy.physics.quantum.commutator import Commutator
from sympy.physics.quantum.qexpr import QuantumError
from sympy.physics.quantum.hilbert import ComplexSpace
from sympy.physics.quantum.operator import (UnitaryOperator, Operator,
HermitianOperator)
from sympy.physics.quantum.matrixutils import matrix_tensor_product, matrix_eye
from sympy.physics.quantum.matrixcache import matrix_cache
from sympy.matrices.matrices import MatrixBase
from sympy.utilities.iterables import is_sequence
__all__ = [
'Gate',
'CGate',
'UGate',
'OneQubitGate',
'TwoQubitGate',
'IdentityGate',
'HadamardGate',
'XGate',
'YGate',
'ZGate',
'TGate',
'PhaseGate',
'SwapGate',
'CNotGate',
# Aliased gate names
'CNOT',
'SWAP',
'H',
'X',
'Y',
'Z',
'T',
'S',
'Phase',
'normalized',
'gate_sort',
'gate_simp',
'random_circuit',
'CPHASE',
'CGateS',
]
#-----------------------------------------------------------------------------
# Gate Super-Classes
#-----------------------------------------------------------------------------
_normalized = True
def _max(*args, **kwargs):
if "key" not in kwargs:
kwargs["key"] = default_sort_key
return max(*args, **kwargs)
def _min(*args, **kwargs):
if "key" not in kwargs:
kwargs["key"] = default_sort_key
return min(*args, **kwargs)
def normalized(normalize):
r"""Set flag controlling normalization of Hadamard gates by `1/\sqrt{2}`.
This is a global setting that can be used to simplify the look of various
expressions, by leaving off the leading `1/\sqrt{2}` of the Hadamard gate.
Parameters
----------
normalize : bool
Should the Hadamard gate include the `1/\sqrt{2}` normalization factor?
When True, the Hadamard gate will have the `1/\sqrt{2}`. When False, the
Hadamard gate will not have this factor.
"""
global _normalized
_normalized = normalize
def _validate_targets_controls(tandc):
tandc = list(tandc)
# Check for integers
for bit in tandc:
if not bit.is_Integer and not bit.is_Symbol:
raise TypeError('Integer expected, got: %r' % tandc[bit])
# Detect duplicates
if len(list(set(tandc))) != len(tandc):
raise QuantumError(
'Target/control qubits in a gate cannot be duplicated'
)
class Gate(UnitaryOperator):
"""Non-controlled unitary gate operator that acts on qubits.
This is a general abstract gate that needs to be subclassed to do anything
useful.
Parameters
----------
label : tuple, int
A list of the target qubits (as ints) that the gate will apply to.
Examples
========
"""
_label_separator = ','
gate_name = 'G'
gate_name_latex = 'G'
#-------------------------------------------------------------------------
# Initialization/creation
#-------------------------------------------------------------------------
@classmethod
def _eval_args(cls, args):
args = Tuple(*UnitaryOperator._eval_args(args))
_validate_targets_controls(args)
return args
@classmethod
def _eval_hilbert_space(cls, args):
"""This returns the smallest possible Hilbert space."""
return ComplexSpace(2)**(_max(args) + 1)
#-------------------------------------------------------------------------
# Properties
#-------------------------------------------------------------------------
@property
def nqubits(self):
"""The total number of qubits this gate acts on.
For controlled gate subclasses this includes both target and control
qubits, so that, for examples the CNOT gate acts on 2 qubits.
"""
return len(self.targets)
@property
def min_qubits(self):
"""The minimum number of qubits this gate needs to act on."""
return _max(self.targets) + 1
@property
def targets(self):
"""A tuple of target qubits."""
return self.label
@property
def gate_name_plot(self):
return r'$%s$' % self.gate_name_latex
#-------------------------------------------------------------------------
# Gate methods
#-------------------------------------------------------------------------
def get_target_matrix(self, format='sympy'):
"""The matrix represenation of the target part of the gate.
Parameters
----------
format : str
The format string ('sympy','numpy', etc.)
"""
raise NotImplementedError(
'get_target_matrix is not implemented in Gate.')
#-------------------------------------------------------------------------
# Apply
#-------------------------------------------------------------------------
def _apply_operator_IntQubit(self, qubits, **options):
"""Redirect an apply from IntQubit to Qubit"""
return self._apply_operator_Qubit(qubits, **options)
def _apply_operator_Qubit(self, qubits, **options):
"""Apply this gate to a Qubit."""
# Check number of qubits this gate acts on.
if qubits.nqubits < self.min_qubits:
raise QuantumError(
'Gate needs a minimum of %r qubits to act on, got: %r' %
(self.min_qubits, qubits.nqubits)
)
# If the controls are not met, just return
if isinstance(self, CGate):
if not self.eval_controls(qubits):
return qubits
targets = self.targets
target_matrix = self.get_target_matrix(format='sympy')
# Find which column of the target matrix this applies to.
column_index = 0
n = 1
for target in targets:
column_index += n*qubits[target]
n = n << 1
column = target_matrix[:, int(column_index)]
# Now apply each column element to the qubit.
result = 0
for index in range(column.rows):
# TODO: This can be optimized to reduce the number of Qubit
# creations. We should simply manipulate the raw list of qubit
# values and then build the new Qubit object once.
# Make a copy of the incoming qubits.
new_qubit = qubits.__class__(*qubits.args)
# Flip the bits that need to be flipped.
for bit, target in enumerate(targets):
if new_qubit[target] != (index >> bit) & 1:
new_qubit = new_qubit.flip(target)
# The value in that row and column times the flipped-bit qubit
# is the result for that part.
result += column[index]*new_qubit
return result
#-------------------------------------------------------------------------
# Represent
#-------------------------------------------------------------------------
def _represent_default_basis(self, **options):
return self._represent_ZGate(None, **options)
def _represent_ZGate(self, basis, **options):
format = options.get('format', 'sympy')
nqubits = options.get('nqubits', 0)
if nqubits == 0:
raise QuantumError(
'The number of qubits must be given as nqubits.')
# Make sure we have enough qubits for the gate.
if nqubits < self.min_qubits:
raise QuantumError(
'The number of qubits %r is too small for the gate.' % nqubits
)
target_matrix = self.get_target_matrix(format)
targets = self.targets
if isinstance(self, CGate):
controls = self.controls
else:
controls = []
m = represent_zbasis(
controls, targets, target_matrix, nqubits, format
)
return m
#-------------------------------------------------------------------------
# Print methods
#-------------------------------------------------------------------------
def _sympystr(self, printer, *args):
label = self._print_label(printer, *args)
return '%s(%s)' % (self.gate_name, label)
def _pretty(self, printer, *args):
a = stringPict(self.gate_name)
b = self._print_label_pretty(printer, *args)
return self._print_subscript_pretty(a, b)
def _latex(self, printer, *args):
label = self._print_label(printer, *args)
return '%s_{%s}' % (self.gate_name_latex, label)
def plot_gate(self, axes, gate_idx, gate_grid, wire_grid):
raise NotImplementedError('plot_gate is not implemented.')
class CGate(Gate):
"""A general unitary gate with control qubits.
A general control gate applies a target gate to a set of targets if all
of the control qubits have a particular values (set by
``CGate.control_value``).
Parameters
----------
label : tuple
The label in this case has the form (controls, gate), where controls
is a tuple/list of control qubits (as ints) and gate is a ``Gate``
instance that is the target operator.
Examples
========
"""
gate_name = 'C'
gate_name_latex = 'C'
# The values this class controls for.
control_value = _S.One
simplify_cgate = False
#-------------------------------------------------------------------------
# Initialization
#-------------------------------------------------------------------------
@classmethod
def _eval_args(cls, args):
# _eval_args has the right logic for the controls argument.
controls = args[0]
gate = args[1]
if not is_sequence(controls):
controls = (controls,)
controls = UnitaryOperator._eval_args(controls)
_validate_targets_controls(chain(controls, gate.targets))
return (Tuple(*controls), gate)
@classmethod
def _eval_hilbert_space(cls, args):
"""This returns the smallest possible Hilbert space."""
return ComplexSpace(2)**_max(_max(args[0]) + 1, args[1].min_qubits)
#-------------------------------------------------------------------------
# Properties
#-------------------------------------------------------------------------
@property
def nqubits(self):
"""The total number of qubits this gate acts on.
For controlled gate subclasses this includes both target and control
qubits, so that, for examples the CNOT gate acts on 2 qubits.
"""
return len(self.targets) + len(self.controls)
@property
def min_qubits(self):
"""The minimum number of qubits this gate needs to act on."""
return _max(_max(self.controls), _max(self.targets)) + 1
@property
def targets(self):
"""A tuple of target qubits."""
return self.gate.targets
@property
def controls(self):
"""A tuple of control qubits."""
return tuple(self.label[0])
@property
def gate(self):
"""The non-controlled gate that will be applied to the targets."""
return self.label[1]
#-------------------------------------------------------------------------
# Gate methods
#-------------------------------------------------------------------------
def get_target_matrix(self, format='sympy'):
return self.gate.get_target_matrix(format)
def eval_controls(self, qubit):
"""Return True/False to indicate if the controls are satisfied."""
return all(qubit[bit] == self.control_value for bit in self.controls)
def decompose(self, **options):
"""Decompose the controlled gate into CNOT and single qubits gates."""
if len(self.controls) == 1:
c = self.controls[0]
t = self.gate.targets[0]
if isinstance(self.gate, YGate):
g1 = PhaseGate(t)
g2 = CNotGate(c, t)
g3 = PhaseGate(t)
g4 = ZGate(t)
return g1*g2*g3*g4
if isinstance(self.gate, ZGate):
g1 = HadamardGate(t)
g2 = CNotGate(c, t)
g3 = HadamardGate(t)
return g1*g2*g3
else:
return self
#-------------------------------------------------------------------------
# Print methods
#-------------------------------------------------------------------------
def _print_label(self, printer, *args):
controls = self._print_sequence(self.controls, ',', printer, *args)
gate = printer._print(self.gate, *args)
return '(%s),%s' % (controls, gate)
def _pretty(self, printer, *args):
controls = self._print_sequence_pretty(
self.controls, ',', printer, *args)
gate = printer._print(self.gate)
gate_name = stringPict(self.gate_name)
first = self._print_subscript_pretty(gate_name, controls)
gate = self._print_parens_pretty(gate)
final = prettyForm(*first.right(gate))
return final
def _latex(self, printer, *args):
controls = self._print_sequence(self.controls, ',', printer, *args)
gate = printer._print(self.gate, *args)
return r'%s_{%s}{\left(%s\right)}' % \
(self.gate_name_latex, controls, gate)
def plot_gate(self, circ_plot, gate_idx):
"""
Plot the controlled gate. If *simplify_cgate* is true, simplify
C-X and C-Z gates into their more familiar forms.
"""
min_wire = int(_min(chain(self.controls, self.targets)))
max_wire = int(_max(chain(self.controls, self.targets)))
circ_plot.control_line(gate_idx, min_wire, max_wire)
for c in self.controls:
circ_plot.control_point(gate_idx, int(c))
if self.simplify_cgate:
if self.gate.gate_name == 'X':
self.gate.plot_gate_plus(circ_plot, gate_idx)
elif self.gate.gate_name == 'Z':
circ_plot.control_point(gate_idx, self.targets[0])
else:
self.gate.plot_gate(circ_plot, gate_idx)
else:
self.gate.plot_gate(circ_plot, gate_idx)
#-------------------------------------------------------------------------
# Miscellaneous
#-------------------------------------------------------------------------
def _eval_dagger(self):
if isinstance(self.gate, HermitianOperator):
return self
else:
return Gate._eval_dagger(self)
def _eval_inverse(self):
if isinstance(self.gate, HermitianOperator):
return self
else:
return Gate._eval_inverse(self)
def _eval_power(self, exp):
if isinstance(self.gate, HermitianOperator):
if exp == -1:
return Gate._eval_power(self, exp)
elif abs(exp) % 2 == 0:
return self*(Gate._eval_inverse(self))
else:
return self
else:
return Gate._eval_power(self, exp)
class CGateS(CGate):
"""Version of CGate that allows gate simplifications.
I.e. cnot looks like an oplus, cphase has dots, etc.
"""
simplify_cgate=True
class UGate(Gate):
"""General gate specified by a set of targets and a target matrix.
Parameters
----------
label : tuple
A tuple of the form (targets, U), where targets is a tuple of the
target qubits and U is a unitary matrix with dimension of
len(targets).
"""
gate_name = 'U'
gate_name_latex = 'U'
#-------------------------------------------------------------------------
# Initialization
#-------------------------------------------------------------------------
@classmethod
def _eval_args(cls, args):
targets = args[0]
if not is_sequence(targets):
targets = (targets,)
targets = Gate._eval_args(targets)
_validate_targets_controls(targets)
mat = args[1]
if not isinstance(mat, MatrixBase):
raise TypeError('Matrix expected, got: %r' % mat)
#make sure this matrix is of a Basic type
mat = _sympify(mat)
dim = 2**len(targets)
if not all(dim == shape for shape in mat.shape):
raise IndexError(
'Number of targets must match the matrix size: %r %r' %
(targets, mat)
)
return (targets, mat)
@classmethod
def _eval_hilbert_space(cls, args):
"""This returns the smallest possible Hilbert space."""
return ComplexSpace(2)**(_max(args[0]) + 1)
#-------------------------------------------------------------------------
# Properties
#-------------------------------------------------------------------------
@property
def targets(self):
"""A tuple of target qubits."""
return tuple(self.label[0])
#-------------------------------------------------------------------------
# Gate methods
#-------------------------------------------------------------------------
def get_target_matrix(self, format='sympy'):
"""The matrix rep. of the target part of the gate.
Parameters
----------
format : str
The format string ('sympy','numpy', etc.)
"""
return self.label[1]
#-------------------------------------------------------------------------
# Print methods
#-------------------------------------------------------------------------
def _pretty(self, printer, *args):
targets = self._print_sequence_pretty(
self.targets, ',', printer, *args)
gate_name = stringPict(self.gate_name)
return self._print_subscript_pretty(gate_name, targets)
def _latex(self, printer, *args):
targets = self._print_sequence(self.targets, ',', printer, *args)
return r'%s_{%s}' % (self.gate_name_latex, targets)
def plot_gate(self, circ_plot, gate_idx):
circ_plot.one_qubit_box(
self.gate_name_plot,
gate_idx, int(self.targets[0])
)
class OneQubitGate(Gate):
"""A single qubit unitary gate base class."""
nqubits = _S.One
def plot_gate(self, circ_plot, gate_idx):
circ_plot.one_qubit_box(
self.gate_name_plot,
gate_idx, int(self.targets[0])
)
def _eval_commutator(self, other, **hints):
if isinstance(other, OneQubitGate):
if self.targets != other.targets or self.__class__ == other.__class__:
return _S.Zero
return Operator._eval_commutator(self, other, **hints)
def _eval_anticommutator(self, other, **hints):
if isinstance(other, OneQubitGate):
if self.targets != other.targets or self.__class__ == other.__class__:
return Integer(2)*self*other
return Operator._eval_anticommutator(self, other, **hints)
class TwoQubitGate(Gate):
"""A two qubit unitary gate base class."""
nqubits = Integer(2)
#-----------------------------------------------------------------------------
# Single Qubit Gates
#-----------------------------------------------------------------------------
class IdentityGate(OneQubitGate):
"""The single qubit identity gate.
Parameters
----------
target : int
The target qubit this gate will apply to.
Examples
========
"""
gate_name = '1'
gate_name_latex = '1'
def get_target_matrix(self, format='sympy'):
return matrix_cache.get_matrix('eye2', format)
def _eval_commutator(self, other, **hints):
return _S.Zero
def _eval_anticommutator(self, other, **hints):
return Integer(2)*other
class HadamardGate(HermitianOperator, OneQubitGate):
"""The single qubit Hadamard gate.
Parameters
----------
target : int
The target qubit this gate will apply to.
Examples
========
>>> from sympy import sqrt
>>> from sympy.physics.quantum.qubit import Qubit
>>> from sympy.physics.quantum.gate import HadamardGate
>>> from sympy.physics.quantum.qapply import qapply
>>> qapply(HadamardGate(0)*Qubit('1'))
sqrt(2)*|0>/2 - sqrt(2)*|1>/2
>>> # Hadamard on bell state, applied on 2 qubits.
>>> psi = 1/sqrt(2)*(Qubit('00')+Qubit('11'))
>>> qapply(HadamardGate(0)*HadamardGate(1)*psi)
sqrt(2)*|00>/2 + sqrt(2)*|11>/2
"""
gate_name = 'H'
gate_name_latex = 'H'
def get_target_matrix(self, format='sympy'):
if _normalized:
return matrix_cache.get_matrix('H', format)
else:
return matrix_cache.get_matrix('Hsqrt2', format)
def _eval_commutator_XGate(self, other, **hints):
return I*sqrt(2)*YGate(self.targets[0])
def _eval_commutator_YGate(self, other, **hints):
return I*sqrt(2)*(ZGate(self.targets[0]) - XGate(self.targets[0]))
def _eval_commutator_ZGate(self, other, **hints):
return -I*sqrt(2)*YGate(self.targets[0])
def _eval_anticommutator_XGate(self, other, **hints):
return sqrt(2)*IdentityGate(self.targets[0])
def _eval_anticommutator_YGate(self, other, **hints):
return _S.Zero
def _eval_anticommutator_ZGate(self, other, **hints):
return sqrt(2)*IdentityGate(self.targets[0])
class XGate(HermitianOperator, OneQubitGate):
"""The single qubit X, or NOT, gate.
Parameters
----------
target : int
The target qubit this gate will apply to.
Examples
========
"""
gate_name = 'X'
gate_name_latex = 'X'
def get_target_matrix(self, format='sympy'):
return matrix_cache.get_matrix('X', format)
def plot_gate(self, circ_plot, gate_idx):
OneQubitGate.plot_gate(self,circ_plot,gate_idx)
def plot_gate_plus(self, circ_plot, gate_idx):
circ_plot.not_point(
gate_idx, int(self.label[0])
)
def _eval_commutator_YGate(self, other, **hints):
return Integer(2)*I*ZGate(self.targets[0])
def _eval_anticommutator_XGate(self, other, **hints):
return Integer(2)*IdentityGate(self.targets[0])
def _eval_anticommutator_YGate(self, other, **hints):
return _S.Zero
def _eval_anticommutator_ZGate(self, other, **hints):
return _S.Zero
class YGate(HermitianOperator, OneQubitGate):
"""The single qubit Y gate.
Parameters
----------
target : int
The target qubit this gate will apply to.
Examples
========
"""
gate_name = 'Y'
gate_name_latex = 'Y'
def get_target_matrix(self, format='sympy'):
return matrix_cache.get_matrix('Y', format)
def _eval_commutator_ZGate(self, other, **hints):
return Integer(2)*I*XGate(self.targets[0])
def _eval_anticommutator_YGate(self, other, **hints):
return Integer(2)*IdentityGate(self.targets[0])
def _eval_anticommutator_ZGate(self, other, **hints):
return _S.Zero
class ZGate(HermitianOperator, OneQubitGate):
"""The single qubit Z gate.
Parameters
----------
target : int
The target qubit this gate will apply to.
Examples
========
"""
gate_name = 'Z'
gate_name_latex = 'Z'
def get_target_matrix(self, format='sympy'):
return matrix_cache.get_matrix('Z', format)
def _eval_commutator_XGate(self, other, **hints):
return Integer(2)*I*YGate(self.targets[0])
def _eval_anticommutator_YGate(self, other, **hints):
return _S.Zero
class PhaseGate(OneQubitGate):
"""The single qubit phase, or S, gate.
This gate rotates the phase of the state by pi/2 if the state is ``|1>`` and
does nothing if the state is ``|0>``.
Parameters
----------
target : int
The target qubit this gate will apply to.
Examples
========
"""
gate_name = 'S'
gate_name_latex = 'S'
def get_target_matrix(self, format='sympy'):
return matrix_cache.get_matrix('S', format)
def _eval_commutator_ZGate(self, other, **hints):
return _S.Zero
def _eval_commutator_TGate(self, other, **hints):
return _S.Zero
class TGate(OneQubitGate):
"""The single qubit pi/8 gate.
This gate rotates the phase of the state by pi/4 if the state is ``|1>`` and
does nothing if the state is ``|0>``.
Parameters
----------
target : int
The target qubit this gate will apply to.
Examples
========
"""
gate_name = 'T'
gate_name_latex = 'T'
def get_target_matrix(self, format='sympy'):
return matrix_cache.get_matrix('T', format)
def _eval_commutator_ZGate(self, other, **hints):
return _S.Zero
def _eval_commutator_PhaseGate(self, other, **hints):
return _S.Zero
# Aliases for gate names.
H = HadamardGate
X = XGate
Y = YGate
Z = ZGate
T = TGate
Phase = S = PhaseGate
#-----------------------------------------------------------------------------
# 2 Qubit Gates
#-----------------------------------------------------------------------------
class CNotGate(HermitianOperator, CGate, TwoQubitGate):
"""Two qubit controlled-NOT.
This gate performs the NOT or X gate on the target qubit if the control
qubits all have the value 1.
Parameters
----------
label : tuple
A tuple of the form (control, target).
Examples
========
>>> from sympy.physics.quantum.gate import CNOT
>>> from sympy.physics.quantum.qapply import qapply
>>> from sympy.physics.quantum.qubit import Qubit
>>> c = CNOT(1,0)
>>> qapply(c*Qubit('10')) # note that qubits are indexed from right to left
|11>
"""
gate_name = 'CNOT'
gate_name_latex = r'\text{CNOT}'
simplify_cgate = True
#-------------------------------------------------------------------------
# Initialization
#-------------------------------------------------------------------------
@classmethod
def _eval_args(cls, args):
args = Gate._eval_args(args)
return args
@classmethod
def _eval_hilbert_space(cls, args):
"""This returns the smallest possible Hilbert space."""
return ComplexSpace(2)**(_max(args) + 1)
#-------------------------------------------------------------------------
# Properties
#-------------------------------------------------------------------------
@property
def min_qubits(self):
"""The minimum number of qubits this gate needs to act on."""
return _max(self.label) + 1
@property
def targets(self):
"""A tuple of target qubits."""
return (self.label[1],)
@property
def controls(self):
"""A tuple of control qubits."""
return (self.label[0],)
@property
def gate(self):
"""The non-controlled gate that will be applied to the targets."""
return XGate(self.label[1])
#-------------------------------------------------------------------------
# Properties
#-------------------------------------------------------------------------
# The default printing of Gate works better than those of CGate, so we
# go around the overridden methods in CGate.
def _print_label(self, printer, *args):
return Gate._print_label(self, printer, *args)
def _pretty(self, printer, *args):
return Gate._pretty(self, printer, *args)
def _latex(self, printer, *args):
return Gate._latex(self, printer, *args)
#-------------------------------------------------------------------------
# Commutator/AntiCommutator
#-------------------------------------------------------------------------
def _eval_commutator_ZGate(self, other, **hints):
"""[CNOT(i, j), Z(i)] == 0."""
if self.controls[0] == other.targets[0]:
return _S.Zero
else:
raise NotImplementedError('Commutator not implemented: %r' % other)
def _eval_commutator_TGate(self, other, **hints):
"""[CNOT(i, j), T(i)] == 0."""
return self._eval_commutator_ZGate(other, **hints)
def _eval_commutator_PhaseGate(self, other, **hints):
"""[CNOT(i, j), S(i)] == 0."""
return self._eval_commutator_ZGate(other, **hints)
def _eval_commutator_XGate(self, other, **hints):
"""[CNOT(i, j), X(j)] == 0."""
if self.targets[0] == other.targets[0]:
return _S.Zero
else:
raise NotImplementedError('Commutator not implemented: %r' % other)
def _eval_commutator_CNotGate(self, other, **hints):
"""[CNOT(i, j), CNOT(i,k)] == 0."""
if self.controls[0] == other.controls[0]:
return _S.Zero
else:
raise NotImplementedError('Commutator not implemented: %r' % other)
class SwapGate(TwoQubitGate):
"""Two qubit SWAP gate.
This gate swap the values of the two qubits.
Parameters
----------
label : tuple
A tuple of the form (target1, target2).
Examples
========
"""
gate_name = 'SWAP'
gate_name_latex = r'\text{SWAP}'
def get_target_matrix(self, format='sympy'):
return matrix_cache.get_matrix('SWAP', format)
def decompose(self, **options):
"""Decompose the SWAP gate into CNOT gates."""
i, j = self.targets[0], self.targets[1]
g1 = CNotGate(i, j)
g2 = CNotGate(j, i)
return g1*g2*g1
def plot_gate(self, circ_plot, gate_idx):
min_wire = int(_min(self.targets))
max_wire = int(_max(self.targets))
circ_plot.control_line(gate_idx, min_wire, max_wire)
circ_plot.swap_point(gate_idx, min_wire)
circ_plot.swap_point(gate_idx, max_wire)
def _represent_ZGate(self, basis, **options):
"""Represent the SWAP gate in the computational basis.
The following representation is used to compute this:
SWAP = |1><1|x|1><1| + |0><0|x|0><0| + |1><0|x|0><1| + |0><1|x|1><0|
"""
format = options.get('format', 'sympy')
targets = [int(t) for t in self.targets]
min_target = _min(targets)
max_target = _max(targets)
nqubits = options.get('nqubits', self.min_qubits)
op01 = matrix_cache.get_matrix('op01', format)
op10 = matrix_cache.get_matrix('op10', format)
op11 = matrix_cache.get_matrix('op11', format)
op00 = matrix_cache.get_matrix('op00', format)
eye2 = matrix_cache.get_matrix('eye2', format)
result = None
for i, j in ((op01, op10), (op10, op01), (op00, op00), (op11, op11)):
product = nqubits*[eye2]
product[nqubits - min_target - 1] = i
product[nqubits - max_target - 1] = j
new_result = matrix_tensor_product(*product)
if result is None:
result = new_result
else:
result = result + new_result
return result
# Aliases for gate names.
CNOT = CNotGate
SWAP = SwapGate
def CPHASE(a,b): return CGateS((a,),Z(b))
#-----------------------------------------------------------------------------
# Represent
#-----------------------------------------------------------------------------
def represent_zbasis(controls, targets, target_matrix, nqubits, format='sympy'):
"""Represent a gate with controls, targets and target_matrix.
This function does the low-level work of representing gates as matrices
in the standard computational basis (ZGate). Currently, we support two
main cases:
1. One target qubit and no control qubits.
2. One target qubits and multiple control qubits.
For the base of multiple controls, we use the following expression [1]:
1_{2**n} + (|1><1|)^{(n-1)} x (target-matrix - 1_{2})
Parameters
----------
controls : list, tuple
A sequence of control qubits.
targets : list, tuple
A sequence of target qubits.
target_matrix : sympy.Matrix, numpy.matrix, scipy.sparse
The matrix form of the transformation to be performed on the target
qubits. The format of this matrix must match that passed into
the `format` argument.
nqubits : int
The total number of qubits used for the representation.
format : str
The format of the final matrix ('sympy', 'numpy', 'scipy.sparse').
Examples
========
References
----------
[1] http://www.johnlapeyre.com/qinf/qinf_html/node6.html.
"""
controls = [int(x) for x in controls]
targets = [int(x) for x in targets]
nqubits = int(nqubits)
# This checks for the format as well.
op11 = matrix_cache.get_matrix('op11', format)
eye2 = matrix_cache.get_matrix('eye2', format)
# Plain single qubit case
if len(controls) == 0 and len(targets) == 1:
product = []
bit = targets[0]
# Fill product with [I1,Gate,I2] such that the unitaries,
# I, cause the gate to be applied to the correct Qubit
if bit != nqubits - 1:
product.append(matrix_eye(2**(nqubits - bit - 1), format=format))
product.append(target_matrix)
if bit != 0:
product.append(matrix_eye(2**bit, format=format))
return matrix_tensor_product(*product)
# Single target, multiple controls.
elif len(targets) == 1 and len(controls) >= 1:
target = targets[0]
# Build the non-trivial part.
product2 = []
for i in range(nqubits):
product2.append(matrix_eye(2, format=format))
for control in controls:
product2[nqubits - 1 - control] = op11
product2[nqubits - 1 - target] = target_matrix - eye2
return matrix_eye(2**nqubits, format=format) + \
matrix_tensor_product(*product2)
# Multi-target, multi-control is not yet implemented.
else:
raise NotImplementedError(
'The representation of multi-target, multi-control gates '
'is not implemented.'
)
#-----------------------------------------------------------------------------
# Gate manipulation functions.
#-----------------------------------------------------------------------------
def gate_simp(circuit):
"""Simplifies gates symbolically
It first sorts gates using gate_sort. It then applies basic
simplification rules to the circuit, e.g., XGate**2 = Identity
"""
# Bubble sort out gates that commute.
circuit = gate_sort(circuit)
# Do simplifications by subing a simplification into the first element
# which can be simplified. We recursively call gate_simp with new circuit
# as input more simplifications exist.
if isinstance(circuit, Add):
return sum(gate_simp(t) for t in circuit.args)
elif isinstance(circuit, Mul):
circuit_args = circuit.args
elif isinstance(circuit, Pow):
b, e = circuit.as_base_exp()
circuit_args = (gate_simp(b)**e,)
else:
return circuit
# Iterate through each element in circuit, simplify if possible.
for i in range(len(circuit_args)):
# H,X,Y or Z squared is 1.
# T**2 = S, S**2 = Z
if isinstance(circuit_args[i], Pow):
if isinstance(circuit_args[i].base,
(HadamardGate, XGate, YGate, ZGate)) \
and isinstance(circuit_args[i].exp, Number):
# Build a new circuit taking replacing the
# H,X,Y,Z squared with one.
newargs = (circuit_args[:i] +
(circuit_args[i].base**(circuit_args[i].exp % 2),) +
circuit_args[i + 1:])
# Recursively simplify the new circuit.
circuit = gate_simp(Mul(*newargs))
break
elif isinstance(circuit_args[i].base, PhaseGate):
# Build a new circuit taking old circuit but splicing
# in simplification.
newargs = circuit_args[:i]
# Replace PhaseGate**2 with ZGate.
newargs = newargs + (ZGate(circuit_args[i].base.args[0])**
(Integer(circuit_args[i].exp/2)), circuit_args[i].base**
(circuit_args[i].exp % 2))
# Append the last elements.
newargs = newargs + circuit_args[i + 1:]
# Recursively simplify the new circuit.
circuit = gate_simp(Mul(*newargs))
break
elif isinstance(circuit_args[i].base, TGate):
# Build a new circuit taking all the old elements.
newargs = circuit_args[:i]
# Put an Phasegate in place of any TGate**2.
newargs = newargs + (PhaseGate(circuit_args[i].base.args[0])**
Integer(circuit_args[i].exp/2), circuit_args[i].base**
(circuit_args[i].exp % 2))
# Append the last elements.
newargs = newargs + circuit_args[i + 1:]
# Recursively simplify the new circuit.
circuit = gate_simp(Mul(*newargs))
break
return circuit
def gate_sort(circuit):
"""Sorts the gates while keeping track of commutation relations
This function uses a bubble sort to rearrange the order of gate
application. Keeps track of Quantum computations special commutation
relations (e.g. things that apply to the same Qubit do not commute with
each other)
circuit is the Mul of gates that are to be sorted.
"""
# Make sure we have an Add or Mul.
if isinstance(circuit, Add):
return sum(gate_sort(t) for t in circuit.args)
if isinstance(circuit, Pow):
return gate_sort(circuit.base)**circuit.exp
elif isinstance(circuit, Gate):
return circuit
if not isinstance(circuit, Mul):
return circuit
changes = True
while changes:
changes = False
circ_array = circuit.args
for i in range(len(circ_array) - 1):
# Go through each element and switch ones that are in wrong order
if isinstance(circ_array[i], (Gate, Pow)) and \
isinstance(circ_array[i + 1], (Gate, Pow)):
# If we have a Pow object, look at only the base
first_base, first_exp = circ_array[i].as_base_exp()
second_base, second_exp = circ_array[i + 1].as_base_exp()
# Use SymPy's hash based sorting. This is not mathematical
# sorting, but is rather based on comparing hashes of objects.
# See Basic.compare for details.
if first_base.compare(second_base) > 0:
if Commutator(first_base, second_base).doit() == 0:
new_args = (circuit.args[:i] + (circuit.args[i + 1],) +
(circuit.args[i],) + circuit.args[i + 2:])
circuit = Mul(*new_args)
changes = True
break
if AntiCommutator(first_base, second_base).doit() == 0:
new_args = (circuit.args[:i] + (circuit.args[i + 1],) +
(circuit.args[i],) + circuit.args[i + 2:])
sign = _S.NegativeOne**(first_exp*second_exp)
circuit = sign*Mul(*new_args)
changes = True
break
return circuit
#-----------------------------------------------------------------------------
# Utility functions
#-----------------------------------------------------------------------------
def random_circuit(ngates, nqubits, gate_space=(X, Y, Z, S, T, H, CNOT, SWAP)):
"""Return a random circuit of ngates and nqubits.
This uses an equally weighted sample of (X, Y, Z, S, T, H, CNOT, SWAP)
gates.
Parameters
----------
ngates : int
The number of gates in the circuit.
nqubits : int
The number of qubits in the circuit.
gate_space : tuple
A tuple of the gate classes that will be used in the circuit.
Repeating gate classes multiple times in this tuple will increase
the frequency they appear in the random circuit.
"""
qubit_space = range(nqubits)
result = []
for i in range(ngates):
g = random.choice(gate_space)
if g == CNotGate or g == SwapGate:
qubits = random.sample(qubit_space, 2)
g = g(*qubits)
else:
qubit = random.choice(qubit_space)
g = g(qubit)
result.append(g)
return Mul(*result)
def zx_basis_transform(self, format='sympy'):
"""Transformation matrix from Z to X basis."""
return matrix_cache.get_matrix('ZX', format)
def zy_basis_transform(self, format='sympy'):
"""Transformation matrix from Z to Y basis."""
return matrix_cache.get_matrix('ZY', format)
|
b994fcdadd9ba4a74605667bf86b47ef962b855f9ab08b19d9f08eca97958782 | from sympy.core.expr import Expr
from sympy.core.symbol import Symbol
from sympy.core.sympify import sympify
from sympy.matrices.dense import Matrix
from sympy.printing.pretty.stringpict import prettyForm
from sympy.core.containers import Tuple
from sympy.utilities.iterables import is_sequence
from sympy.physics.quantum.dagger import Dagger
from sympy.physics.quantum.matrixutils import (
numpy_ndarray, scipy_sparse_matrix,
to_sympy, to_numpy, to_scipy_sparse
)
__all__ = [
'QuantumError',
'QExpr'
]
#-----------------------------------------------------------------------------
# Error handling
#-----------------------------------------------------------------------------
class QuantumError(Exception):
pass
def _qsympify_sequence(seq):
"""Convert elements of a sequence to standard form.
This is like sympify, but it performs special logic for arguments passed
to QExpr. The following conversions are done:
* (list, tuple, Tuple) => _qsympify_sequence each element and convert
sequence to a Tuple.
* basestring => Symbol
* Matrix => Matrix
* other => sympify
Strings are passed to Symbol, not sympify to make sure that variables like
'pi' are kept as Symbols, not the SymPy built-in number subclasses.
Examples
========
>>> from sympy.physics.quantum.qexpr import _qsympify_sequence
>>> _qsympify_sequence((1,2,[3,4,[1,]]))
(1, 2, (3, 4, (1,)))
"""
return tuple(__qsympify_sequence_helper(seq))
def __qsympify_sequence_helper(seq):
"""
Helper function for _qsympify_sequence
This function does the actual work.
"""
#base case. If not a list, do Sympification
if not is_sequence(seq):
if isinstance(seq, Matrix):
return seq
elif isinstance(seq, str):
return Symbol(seq)
else:
return sympify(seq)
# base condition, when seq is QExpr and also
# is iterable.
if isinstance(seq, QExpr):
return seq
#if list, recurse on each item in the list
result = [__qsympify_sequence_helper(item) for item in seq]
return Tuple(*result)
#-----------------------------------------------------------------------------
# Basic Quantum Expression from which all objects descend
#-----------------------------------------------------------------------------
class QExpr(Expr):
"""A base class for all quantum object like operators and states."""
# In sympy, slots are for instance attributes that are computed
# dynamically by the __new__ method. They are not part of args, but they
# derive from args.
# The Hilbert space a quantum Object belongs to.
__slots__ = ('hilbert_space', )
is_commutative = False
# The separator used in printing the label.
_label_separator = ''
@property
def free_symbols(self):
return {self}
def __new__(cls, *args, **kwargs):
"""Construct a new quantum object.
Parameters
==========
args : tuple
The list of numbers or parameters that uniquely specify the
quantum object. For a state, this will be its symbol or its
set of quantum numbers.
Examples
========
>>> from sympy.physics.quantum.qexpr import QExpr
>>> q = QExpr(0)
>>> q
0
>>> q.label
(0,)
>>> q.hilbert_space
H
>>> q.args
(0,)
>>> q.is_commutative
False
"""
# First compute args and call Expr.__new__ to create the instance
args = cls._eval_args(args, **kwargs)
if len(args) == 0:
args = cls._eval_args(tuple(cls.default_args()), **kwargs)
inst = Expr.__new__(cls, *args)
# Now set the slots on the instance
inst.hilbert_space = cls._eval_hilbert_space(args)
return inst
@classmethod
def _new_rawargs(cls, hilbert_space, *args, **old_assumptions):
"""Create new instance of this class with hilbert_space and args.
This is used to bypass the more complex logic in the ``__new__``
method in cases where you already have the exact ``hilbert_space``
and ``args``. This should be used when you are positive these
arguments are valid, in their final, proper form and want to optimize
the creation of the object.
"""
obj = Expr.__new__(cls, *args, **old_assumptions)
obj.hilbert_space = hilbert_space
return obj
#-------------------------------------------------------------------------
# Properties
#-------------------------------------------------------------------------
@property
def label(self):
"""The label is the unique set of identifiers for the object.
Usually, this will include all of the information about the state
*except* the time (in the case of time-dependent objects).
This must be a tuple, rather than a Tuple.
"""
if len(self.args) == 0: # If there is no label specified, return the default
return self._eval_args(list(self.default_args()))
else:
return self.args
@property
def is_symbolic(self):
return True
@classmethod
def default_args(self):
"""If no arguments are specified, then this will return a default set
of arguments to be run through the constructor.
NOTE: Any classes that override this MUST return a tuple of arguments.
Should be overridden by subclasses to specify the default arguments for kets and operators
"""
raise NotImplementedError("No default arguments for this class!")
#-------------------------------------------------------------------------
# _eval_* methods
#-------------------------------------------------------------------------
def _eval_adjoint(self):
obj = Expr._eval_adjoint(self)
if obj is None:
obj = Expr.__new__(Dagger, self)
if isinstance(obj, QExpr):
obj.hilbert_space = self.hilbert_space
return obj
@classmethod
def _eval_args(cls, args):
"""Process the args passed to the __new__ method.
This simply runs args through _qsympify_sequence.
"""
return _qsympify_sequence(args)
@classmethod
def _eval_hilbert_space(cls, args):
"""Compute the Hilbert space instance from the args.
"""
from sympy.physics.quantum.hilbert import HilbertSpace
return HilbertSpace()
#-------------------------------------------------------------------------
# Printing
#-------------------------------------------------------------------------
# Utilities for printing: these operate on raw SymPy objects
def _print_sequence(self, seq, sep, printer, *args):
result = []
for item in seq:
result.append(printer._print(item, *args))
return sep.join(result)
def _print_sequence_pretty(self, seq, sep, printer, *args):
pform = printer._print(seq[0], *args)
for item in seq[1:]:
pform = prettyForm(*pform.right(sep))
pform = prettyForm(*pform.right(printer._print(item, *args)))
return pform
# Utilities for printing: these operate prettyForm objects
def _print_subscript_pretty(self, a, b):
top = prettyForm(*b.left(' '*a.width()))
bot = prettyForm(*a.right(' '*b.width()))
return prettyForm(binding=prettyForm.POW, *bot.below(top))
def _print_superscript_pretty(self, a, b):
return a**b
def _print_parens_pretty(self, pform, left='(', right=')'):
return prettyForm(*pform.parens(left=left, right=right))
# Printing of labels (i.e. args)
def _print_label(self, printer, *args):
"""Prints the label of the QExpr
This method prints self.label, using self._label_separator to separate
the elements. This method should not be overridden, instead, override
_print_contents to change printing behavior.
"""
return self._print_sequence(
self.label, self._label_separator, printer, *args
)
def _print_label_repr(self, printer, *args):
return self._print_sequence(
self.label, ',', printer, *args
)
def _print_label_pretty(self, printer, *args):
return self._print_sequence_pretty(
self.label, self._label_separator, printer, *args
)
def _print_label_latex(self, printer, *args):
return self._print_sequence(
self.label, self._label_separator, printer, *args
)
# Printing of contents (default to label)
def _print_contents(self, printer, *args):
"""Printer for contents of QExpr
Handles the printing of any unique identifying contents of a QExpr to
print as its contents, such as any variables or quantum numbers. The
default is to print the label, which is almost always the args. This
should not include printing of any brackets or parenteses.
"""
return self._print_label(printer, *args)
def _print_contents_pretty(self, printer, *args):
return self._print_label_pretty(printer, *args)
def _print_contents_latex(self, printer, *args):
return self._print_label_latex(printer, *args)
# Main printing methods
def _sympystr(self, printer, *args):
"""Default printing behavior of QExpr objects
Handles the default printing of a QExpr. To add other things to the
printing of the object, such as an operator name to operators or
brackets to states, the class should override the _print/_pretty/_latex
functions directly and make calls to _print_contents where appropriate.
This allows things like InnerProduct to easily control its printing the
printing of contents.
"""
return self._print_contents(printer, *args)
def _sympyrepr(self, printer, *args):
classname = self.__class__.__name__
label = self._print_label_repr(printer, *args)
return '%s(%s)' % (classname, label)
def _pretty(self, printer, *args):
pform = self._print_contents_pretty(printer, *args)
return pform
def _latex(self, printer, *args):
return self._print_contents_latex(printer, *args)
#-------------------------------------------------------------------------
# Represent
#-------------------------------------------------------------------------
def _represent_default_basis(self, **options):
raise NotImplementedError('This object does not have a default basis')
def _represent(self, *, basis=None, **options):
"""Represent this object in a given basis.
This method dispatches to the actual methods that perform the
representation. Subclases of QExpr should define various methods to
determine how the object will be represented in various bases. The
format of these methods is::
def _represent_BasisName(self, basis, **options):
Thus to define how a quantum object is represented in the basis of
the operator Position, you would define::
def _represent_Position(self, basis, **options):
Usually, basis object will be instances of Operator subclasses, but
there is a chance we will relax this in the future to accommodate other
types of basis sets that are not associated with an operator.
If the ``format`` option is given it can be ("sympy", "numpy",
"scipy.sparse"). This will ensure that any matrices that result from
representing the object are returned in the appropriate matrix format.
Parameters
==========
basis : Operator
The Operator whose basis functions will be used as the basis for
representation.
options : dict
A dictionary of key/value pairs that give options and hints for
the representation, such as the number of basis functions to
be used.
"""
if basis is None:
result = self._represent_default_basis(**options)
else:
result = dispatch_method(self, '_represent', basis, **options)
# If we get a matrix representation, convert it to the right format.
format = options.get('format', 'sympy')
result = self._format_represent(result, format)
return result
def _format_represent(self, result, format):
if format == 'sympy' and not isinstance(result, Matrix):
return to_sympy(result)
elif format == 'numpy' and not isinstance(result, numpy_ndarray):
return to_numpy(result)
elif format == 'scipy.sparse' and \
not isinstance(result, scipy_sparse_matrix):
return to_scipy_sparse(result)
return result
def split_commutative_parts(e):
"""Split into commutative and non-commutative parts."""
c_part, nc_part = e.args_cnc()
c_part = list(c_part)
return c_part, nc_part
def split_qexpr_parts(e):
"""Split an expression into Expr and noncommutative QExpr parts."""
expr_part = []
qexpr_part = []
for arg in e.args:
if not isinstance(arg, QExpr):
expr_part.append(arg)
else:
qexpr_part.append(arg)
return expr_part, qexpr_part
def dispatch_method(self, basename, arg, **options):
"""Dispatch a method to the proper handlers."""
method_name = '%s_%s' % (basename, arg.__class__.__name__)
if hasattr(self, method_name):
f = getattr(self, method_name)
# This can raise and we will allow it to propagate.
result = f(arg, **options)
if result is not None:
return result
raise NotImplementedError(
"%s.%s cannot handle: %r" %
(self.__class__.__name__, basename, arg)
)
|
bb6a794c019d6a7c7715f97148f3e06f2e31470605d5662f40f4e29545ecd1da | """
qasm.py - Functions to parse a set of qasm commands into a SymPy Circuit.
Examples taken from Chuang's page: http://www.media.mit.edu/quanta/qasm2circ/
The code returns a circuit and an associated list of labels.
>>> from sympy.physics.quantum.qasm import Qasm
>>> q = Qasm('qubit q0', 'qubit q1', 'h q0', 'cnot q0,q1')
>>> q.get_circuit()
CNOT(1,0)*H(1)
>>> q = Qasm('qubit q0', 'qubit q1', 'cnot q0,q1', 'cnot q1,q0', 'cnot q0,q1')
>>> q.get_circuit()
CNOT(1,0)*CNOT(0,1)*CNOT(1,0)
"""
__all__ = [
'Qasm',
]
from math import prod
from sympy.physics.quantum.gate import H, CNOT, X, Z, CGate, CGateS, SWAP, S, T,CPHASE
from sympy.physics.quantum.circuitplot import Mz
def read_qasm(lines):
return Qasm(*lines.splitlines())
def read_qasm_file(filename):
return Qasm(*open(filename).readlines())
def flip_index(i, n):
"""Reorder qubit indices from largest to smallest.
>>> from sympy.physics.quantum.qasm import flip_index
>>> flip_index(0, 2)
1
>>> flip_index(1, 2)
0
"""
return n-i-1
def trim(line):
"""Remove everything following comment # characters in line.
>>> from sympy.physics.quantum.qasm import trim
>>> trim('nothing happens here')
'nothing happens here'
>>> trim('something #happens here')
'something '
"""
if '#' not in line:
return line
return line.split('#')[0]
def get_index(target, labels):
"""Get qubit labels from the rest of the line,and return indices
>>> from sympy.physics.quantum.qasm import get_index
>>> get_index('q0', ['q0', 'q1'])
1
>>> get_index('q1', ['q0', 'q1'])
0
"""
nq = len(labels)
return flip_index(labels.index(target), nq)
def get_indices(targets, labels):
return [get_index(t, labels) for t in targets]
def nonblank(args):
for line in args:
line = trim(line)
if line.isspace():
continue
yield line
return
def fullsplit(line):
words = line.split()
rest = ' '.join(words[1:])
return fixcommand(words[0]), [s.strip() for s in rest.split(',')]
def fixcommand(c):
"""Fix Qasm command names.
Remove all of forbidden characters from command c, and
replace 'def' with 'qdef'.
"""
forbidden_characters = ['-']
c = c.lower()
for char in forbidden_characters:
c = c.replace(char, '')
if c == 'def':
return 'qdef'
return c
def stripquotes(s):
"""Replace explicit quotes in a string.
>>> from sympy.physics.quantum.qasm import stripquotes
>>> stripquotes("'S'") == 'S'
True
>>> stripquotes('"S"') == 'S'
True
>>> stripquotes('S') == 'S'
True
"""
s = s.replace('"', '') # Remove second set of quotes?
s = s.replace("'", '')
return s
class Qasm:
"""Class to form objects from Qasm lines
>>> from sympy.physics.quantum.qasm import Qasm
>>> q = Qasm('qubit q0', 'qubit q1', 'h q0', 'cnot q0,q1')
>>> q.get_circuit()
CNOT(1,0)*H(1)
>>> q = Qasm('qubit q0', 'qubit q1', 'cnot q0,q1', 'cnot q1,q0', 'cnot q0,q1')
>>> q.get_circuit()
CNOT(1,0)*CNOT(0,1)*CNOT(1,0)
"""
def __init__(self, *args, **kwargs):
self.defs = {}
self.circuit = []
self.labels = []
self.inits = {}
self.add(*args)
self.kwargs = kwargs
def add(self, *lines):
for line in nonblank(lines):
command, rest = fullsplit(line)
if self.defs.get(command): #defs come first, since you can override built-in
function = self.defs.get(command)
indices = self.indices(rest)
if len(indices) == 1:
self.circuit.append(function(indices[0]))
else:
self.circuit.append(function(indices[:-1], indices[-1]))
elif hasattr(self, command):
function = getattr(self, command)
function(*rest)
else:
print("Function %s not defined. Skipping" % command)
def get_circuit(self):
return prod(reversed(self.circuit))
def get_labels(self):
return list(reversed(self.labels))
def plot(self):
from sympy.physics.quantum.circuitplot import CircuitPlot
circuit, labels = self.get_circuit(), self.get_labels()
CircuitPlot(circuit, len(labels), labels=labels, inits=self.inits)
def qubit(self, arg, init=None):
self.labels.append(arg)
if init: self.inits[arg] = init
def indices(self, args):
return get_indices(args, self.labels)
def index(self, arg):
return get_index(arg, self.labels)
def nop(self, *args):
pass
def x(self, arg):
self.circuit.append(X(self.index(arg)))
def z(self, arg):
self.circuit.append(Z(self.index(arg)))
def h(self, arg):
self.circuit.append(H(self.index(arg)))
def s(self, arg):
self.circuit.append(S(self.index(arg)))
def t(self, arg):
self.circuit.append(T(self.index(arg)))
def measure(self, arg):
self.circuit.append(Mz(self.index(arg)))
def cnot(self, a1, a2):
self.circuit.append(CNOT(*self.indices([a1, a2])))
def swap(self, a1, a2):
self.circuit.append(SWAP(*self.indices([a1, a2])))
def cphase(self, a1, a2):
self.circuit.append(CPHASE(*self.indices([a1, a2])))
def toffoli(self, a1, a2, a3):
i1, i2, i3 = self.indices([a1, a2, a3])
self.circuit.append(CGateS((i1, i2), X(i3)))
def cx(self, a1, a2):
fi, fj = self.indices([a1, a2])
self.circuit.append(CGate(fi, X(fj)))
def cz(self, a1, a2):
fi, fj = self.indices([a1, a2])
self.circuit.append(CGate(fi, Z(fj)))
def defbox(self, *args):
print("defbox not supported yet. Skipping: ", args)
def qdef(self, name, ncontrols, symbol):
from sympy.physics.quantum.circuitplot import CreateOneQubitGate, CreateCGate
ncontrols = int(ncontrols)
command = fixcommand(name)
symbol = stripquotes(symbol)
if ncontrols > 0:
self.defs[command] = CreateCGate(symbol)
else:
self.defs[command] = CreateOneQubitGate(symbol)
|
de1f6e182e6f25c9eedea4735e766bfa750dc87902e00bc8381fab0666e5889e | """Quantum mechanical angular momemtum."""
from sympy.concrete.summations import Sum
from sympy.core.add import Add
from sympy.core.containers import Tuple
from sympy.core.expr import Expr
from sympy.core.mul import Mul
from sympy.core.numbers import (I, Integer, Rational, pi)
from sympy.core.singleton import S
from sympy.core.symbol import (Dummy, symbols)
from sympy.core.sympify import sympify
from sympy.functions.combinatorial.factorials import (binomial, factorial)
from sympy.functions.elementary.exponential import exp
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.trigonometric import (cos, sin)
from sympy.simplify.simplify import simplify
from sympy.matrices import zeros
from sympy.printing.pretty.stringpict import prettyForm, stringPict
from sympy.printing.pretty.pretty_symbology import pretty_symbol
from sympy.physics.quantum.qexpr import QExpr
from sympy.physics.quantum.operator import (HermitianOperator, Operator,
UnitaryOperator)
from sympy.physics.quantum.state import Bra, Ket, State
from sympy.functions.special.tensor_functions import KroneckerDelta
from sympy.physics.quantum.constants import hbar
from sympy.physics.quantum.hilbert import ComplexSpace, DirectSumHilbertSpace
from sympy.physics.quantum.tensorproduct import TensorProduct
from sympy.physics.quantum.cg import CG
from sympy.physics.quantum.qapply import qapply
__all__ = [
'm_values',
'Jplus',
'Jminus',
'Jx',
'Jy',
'Jz',
'J2',
'Rotation',
'WignerD',
'JxKet',
'JxBra',
'JyKet',
'JyBra',
'JzKet',
'JzBra',
'JzOp',
'J2Op',
'JxKetCoupled',
'JxBraCoupled',
'JyKetCoupled',
'JyBraCoupled',
'JzKetCoupled',
'JzBraCoupled',
'couple',
'uncouple'
]
def m_values(j):
j = sympify(j)
size = 2*j + 1
if not size.is_Integer or not size > 0:
raise ValueError(
'Only integer or half-integer values allowed for j, got: : %r' % j
)
return size, [j - i for i in range(int(2*j + 1))]
#-----------------------------------------------------------------------------
# Spin Operators
#-----------------------------------------------------------------------------
class SpinOpBase:
"""Base class for spin operators."""
@classmethod
def _eval_hilbert_space(cls, label):
# We consider all j values so our space is infinite.
return ComplexSpace(S.Infinity)
@property
def name(self):
return self.args[0]
def _print_contents(self, printer, *args):
return '%s%s' % (self.name, self._coord)
def _print_contents_pretty(self, printer, *args):
a = stringPict(str(self.name))
b = stringPict(self._coord)
return self._print_subscript_pretty(a, b)
def _print_contents_latex(self, printer, *args):
return r'%s_%s' % ((self.name, self._coord))
def _represent_base(self, basis, **options):
j = options.get('j', S.Half)
size, mvals = m_values(j)
result = zeros(size, size)
for p in range(size):
for q in range(size):
me = self.matrix_element(j, mvals[p], j, mvals[q])
result[p, q] = me
return result
def _apply_op(self, ket, orig_basis, **options):
state = ket.rewrite(self.basis)
# If the state has only one term
if isinstance(state, State):
ret = (hbar*state.m)*state
# state is a linear combination of states
elif isinstance(state, Sum):
ret = self._apply_operator_Sum(state, **options)
else:
ret = qapply(self*state)
if ret == self*state:
raise NotImplementedError
return ret.rewrite(orig_basis)
def _apply_operator_JxKet(self, ket, **options):
return self._apply_op(ket, 'Jx', **options)
def _apply_operator_JxKetCoupled(self, ket, **options):
return self._apply_op(ket, 'Jx', **options)
def _apply_operator_JyKet(self, ket, **options):
return self._apply_op(ket, 'Jy', **options)
def _apply_operator_JyKetCoupled(self, ket, **options):
return self._apply_op(ket, 'Jy', **options)
def _apply_operator_JzKet(self, ket, **options):
return self._apply_op(ket, 'Jz', **options)
def _apply_operator_JzKetCoupled(self, ket, **options):
return self._apply_op(ket, 'Jz', **options)
def _apply_operator_TensorProduct(self, tp, **options):
# Uncoupling operator is only easily found for coordinate basis spin operators
# TODO: add methods for uncoupling operators
if not isinstance(self, (JxOp, JyOp, JzOp)):
raise NotImplementedError
result = []
for n in range(len(tp.args)):
arg = []
arg.extend(tp.args[:n])
arg.append(self._apply_operator(tp.args[n]))
arg.extend(tp.args[n + 1:])
result.append(tp.__class__(*arg))
return Add(*result).expand()
# TODO: move this to qapply_Mul
def _apply_operator_Sum(self, s, **options):
new_func = qapply(self*s.function)
if new_func == self*s.function:
raise NotImplementedError
return Sum(new_func, *s.limits)
def _eval_trace(self, **options):
#TODO: use options to use different j values
#For now eval at default basis
# is it efficient to represent each time
# to do a trace?
return self._represent_default_basis().trace()
class JplusOp(SpinOpBase, Operator):
"""The J+ operator."""
_coord = '+'
basis = 'Jz'
def _eval_commutator_JminusOp(self, other):
return 2*hbar*JzOp(self.name)
def _apply_operator_JzKet(self, ket, **options):
j = ket.j
m = ket.m
if m.is_Number and j.is_Number:
if m >= j:
return S.Zero
return hbar*sqrt(j*(j + S.One) - m*(m + S.One))*JzKet(j, m + S.One)
def _apply_operator_JzKetCoupled(self, ket, **options):
j = ket.j
m = ket.m
jn = ket.jn
coupling = ket.coupling
if m.is_Number and j.is_Number:
if m >= j:
return S.Zero
return hbar*sqrt(j*(j + S.One) - m*(m + S.One))*JzKetCoupled(j, m + S.One, jn, coupling)
def matrix_element(self, j, m, jp, mp):
result = hbar*sqrt(j*(j + S.One) - mp*(mp + S.One))
result *= KroneckerDelta(m, mp + 1)
result *= KroneckerDelta(j, jp)
return result
def _represent_default_basis(self, **options):
return self._represent_JzOp(None, **options)
def _represent_JzOp(self, basis, **options):
return self._represent_base(basis, **options)
def _eval_rewrite_as_xyz(self, *args, **kwargs):
return JxOp(args[0]) + I*JyOp(args[0])
class JminusOp(SpinOpBase, Operator):
"""The J- operator."""
_coord = '-'
basis = 'Jz'
def _apply_operator_JzKet(self, ket, **options):
j = ket.j
m = ket.m
if m.is_Number and j.is_Number:
if m <= -j:
return S.Zero
return hbar*sqrt(j*(j + S.One) - m*(m - S.One))*JzKet(j, m - S.One)
def _apply_operator_JzKetCoupled(self, ket, **options):
j = ket.j
m = ket.m
jn = ket.jn
coupling = ket.coupling
if m.is_Number and j.is_Number:
if m <= -j:
return S.Zero
return hbar*sqrt(j*(j + S.One) - m*(m - S.One))*JzKetCoupled(j, m - S.One, jn, coupling)
def matrix_element(self, j, m, jp, mp):
result = hbar*sqrt(j*(j + S.One) - mp*(mp - S.One))
result *= KroneckerDelta(m, mp - 1)
result *= KroneckerDelta(j, jp)
return result
def _represent_default_basis(self, **options):
return self._represent_JzOp(None, **options)
def _represent_JzOp(self, basis, **options):
return self._represent_base(basis, **options)
def _eval_rewrite_as_xyz(self, *args, **kwargs):
return JxOp(args[0]) - I*JyOp(args[0])
class JxOp(SpinOpBase, HermitianOperator):
"""The Jx operator."""
_coord = 'x'
basis = 'Jx'
def _eval_commutator_JyOp(self, other):
return I*hbar*JzOp(self.name)
def _eval_commutator_JzOp(self, other):
return -I*hbar*JyOp(self.name)
def _apply_operator_JzKet(self, ket, **options):
jp = JplusOp(self.name)._apply_operator_JzKet(ket, **options)
jm = JminusOp(self.name)._apply_operator_JzKet(ket, **options)
return (jp + jm)/Integer(2)
def _apply_operator_JzKetCoupled(self, ket, **options):
jp = JplusOp(self.name)._apply_operator_JzKetCoupled(ket, **options)
jm = JminusOp(self.name)._apply_operator_JzKetCoupled(ket, **options)
return (jp + jm)/Integer(2)
def _represent_default_basis(self, **options):
return self._represent_JzOp(None, **options)
def _represent_JzOp(self, basis, **options):
jp = JplusOp(self.name)._represent_JzOp(basis, **options)
jm = JminusOp(self.name)._represent_JzOp(basis, **options)
return (jp + jm)/Integer(2)
def _eval_rewrite_as_plusminus(self, *args, **kwargs):
return (JplusOp(args[0]) + JminusOp(args[0]))/2
class JyOp(SpinOpBase, HermitianOperator):
"""The Jy operator."""
_coord = 'y'
basis = 'Jy'
def _eval_commutator_JzOp(self, other):
return I*hbar*JxOp(self.name)
def _eval_commutator_JxOp(self, other):
return -I*hbar*J2Op(self.name)
def _apply_operator_JzKet(self, ket, **options):
jp = JplusOp(self.name)._apply_operator_JzKet(ket, **options)
jm = JminusOp(self.name)._apply_operator_JzKet(ket, **options)
return (jp - jm)/(Integer(2)*I)
def _apply_operator_JzKetCoupled(self, ket, **options):
jp = JplusOp(self.name)._apply_operator_JzKetCoupled(ket, **options)
jm = JminusOp(self.name)._apply_operator_JzKetCoupled(ket, **options)
return (jp - jm)/(Integer(2)*I)
def _represent_default_basis(self, **options):
return self._represent_JzOp(None, **options)
def _represent_JzOp(self, basis, **options):
jp = JplusOp(self.name)._represent_JzOp(basis, **options)
jm = JminusOp(self.name)._represent_JzOp(basis, **options)
return (jp - jm)/(Integer(2)*I)
def _eval_rewrite_as_plusminus(self, *args, **kwargs):
return (JplusOp(args[0]) - JminusOp(args[0]))/(2*I)
class JzOp(SpinOpBase, HermitianOperator):
"""The Jz operator."""
_coord = 'z'
basis = 'Jz'
def _eval_commutator_JxOp(self, other):
return I*hbar*JyOp(self.name)
def _eval_commutator_JyOp(self, other):
return -I*hbar*JxOp(self.name)
def _eval_commutator_JplusOp(self, other):
return hbar*JplusOp(self.name)
def _eval_commutator_JminusOp(self, other):
return -hbar*JminusOp(self.name)
def matrix_element(self, j, m, jp, mp):
result = hbar*mp
result *= KroneckerDelta(m, mp)
result *= KroneckerDelta(j, jp)
return result
def _represent_default_basis(self, **options):
return self._represent_JzOp(None, **options)
def _represent_JzOp(self, basis, **options):
return self._represent_base(basis, **options)
class J2Op(SpinOpBase, HermitianOperator):
"""The J^2 operator."""
_coord = '2'
def _eval_commutator_JxOp(self, other):
return S.Zero
def _eval_commutator_JyOp(self, other):
return S.Zero
def _eval_commutator_JzOp(self, other):
return S.Zero
def _eval_commutator_JplusOp(self, other):
return S.Zero
def _eval_commutator_JminusOp(self, other):
return S.Zero
def _apply_operator_JxKet(self, ket, **options):
j = ket.j
return hbar**2*j*(j + 1)*ket
def _apply_operator_JxKetCoupled(self, ket, **options):
j = ket.j
return hbar**2*j*(j + 1)*ket
def _apply_operator_JyKet(self, ket, **options):
j = ket.j
return hbar**2*j*(j + 1)*ket
def _apply_operator_JyKetCoupled(self, ket, **options):
j = ket.j
return hbar**2*j*(j + 1)*ket
def _apply_operator_JzKet(self, ket, **options):
j = ket.j
return hbar**2*j*(j + 1)*ket
def _apply_operator_JzKetCoupled(self, ket, **options):
j = ket.j
return hbar**2*j*(j + 1)*ket
def matrix_element(self, j, m, jp, mp):
result = (hbar**2)*j*(j + 1)
result *= KroneckerDelta(m, mp)
result *= KroneckerDelta(j, jp)
return result
def _represent_default_basis(self, **options):
return self._represent_JzOp(None, **options)
def _represent_JzOp(self, basis, **options):
return self._represent_base(basis, **options)
def _print_contents_pretty(self, printer, *args):
a = prettyForm(str(self.name))
b = prettyForm('2')
return a**b
def _print_contents_latex(self, printer, *args):
return r'%s^2' % str(self.name)
def _eval_rewrite_as_xyz(self, *args, **kwargs):
return JxOp(args[0])**2 + JyOp(args[0])**2 + JzOp(args[0])**2
def _eval_rewrite_as_plusminus(self, *args, **kwargs):
a = args[0]
return JzOp(a)**2 + \
S.Half*(JplusOp(a)*JminusOp(a) + JminusOp(a)*JplusOp(a))
class Rotation(UnitaryOperator):
"""Wigner D operator in terms of Euler angles.
Defines the rotation operator in terms of the Euler angles defined by
the z-y-z convention for a passive transformation. That is the coordinate
axes are rotated first about the z-axis, giving the new x'-y'-z' axes. Then
this new coordinate system is rotated about the new y'-axis, giving new
x''-y''-z'' axes. Then this new coordinate system is rotated about the
z''-axis. Conventions follow those laid out in [1]_.
Parameters
==========
alpha : Number, Symbol
First Euler Angle
beta : Number, Symbol
Second Euler angle
gamma : Number, Symbol
Third Euler angle
Examples
========
A simple example rotation operator:
>>> from sympy import pi
>>> from sympy.physics.quantum.spin import Rotation
>>> Rotation(pi, 0, pi/2)
R(pi,0,pi/2)
With symbolic Euler angles and calculating the inverse rotation operator:
>>> from sympy import symbols
>>> a, b, c = symbols('a b c')
>>> Rotation(a, b, c)
R(a,b,c)
>>> Rotation(a, b, c).inverse()
R(-c,-b,-a)
See Also
========
WignerD: Symbolic Wigner-D function
D: Wigner-D function
d: Wigner small-d function
References
==========
.. [1] Varshalovich, D A, Quantum Theory of Angular Momentum. 1988.
"""
@classmethod
def _eval_args(cls, args):
args = QExpr._eval_args(args)
if len(args) != 3:
raise ValueError('3 Euler angles required, got: %r' % args)
return args
@classmethod
def _eval_hilbert_space(cls, label):
# We consider all j values so our space is infinite.
return ComplexSpace(S.Infinity)
@property
def alpha(self):
return self.label[0]
@property
def beta(self):
return self.label[1]
@property
def gamma(self):
return self.label[2]
def _print_operator_name(self, printer, *args):
return 'R'
def _print_operator_name_pretty(self, printer, *args):
if printer._use_unicode:
return prettyForm('\N{SCRIPT CAPITAL R}' + ' ')
else:
return prettyForm("R ")
def _print_operator_name_latex(self, printer, *args):
return r'\mathcal{R}'
def _eval_inverse(self):
return Rotation(-self.gamma, -self.beta, -self.alpha)
@classmethod
def D(cls, j, m, mp, alpha, beta, gamma):
"""Wigner D-function.
Returns an instance of the WignerD class corresponding to the Wigner-D
function specified by the parameters.
Parameters
===========
j : Number
Total angular momentum
m : Number
Eigenvalue of angular momentum along axis after rotation
mp : Number
Eigenvalue of angular momentum along rotated axis
alpha : Number, Symbol
First Euler angle of rotation
beta : Number, Symbol
Second Euler angle of rotation
gamma : Number, Symbol
Third Euler angle of rotation
Examples
========
Return the Wigner-D matrix element for a defined rotation, both
numerical and symbolic:
>>> from sympy.physics.quantum.spin import Rotation
>>> from sympy import pi, symbols
>>> alpha, beta, gamma = symbols('alpha beta gamma')
>>> Rotation.D(1, 1, 0,pi, pi/2,-pi)
WignerD(1, 1, 0, pi, pi/2, -pi)
See Also
========
WignerD: Symbolic Wigner-D function
"""
return WignerD(j, m, mp, alpha, beta, gamma)
@classmethod
def d(cls, j, m, mp, beta):
"""Wigner small-d function.
Returns an instance of the WignerD class corresponding to the Wigner-D
function specified by the parameters with the alpha and gamma angles
given as 0.
Parameters
===========
j : Number
Total angular momentum
m : Number
Eigenvalue of angular momentum along axis after rotation
mp : Number
Eigenvalue of angular momentum along rotated axis
beta : Number, Symbol
Second Euler angle of rotation
Examples
========
Return the Wigner-D matrix element for a defined rotation, both
numerical and symbolic:
>>> from sympy.physics.quantum.spin import Rotation
>>> from sympy import pi, symbols
>>> beta = symbols('beta')
>>> Rotation.d(1, 1, 0, pi/2)
WignerD(1, 1, 0, 0, pi/2, 0)
See Also
========
WignerD: Symbolic Wigner-D function
"""
return WignerD(j, m, mp, 0, beta, 0)
def matrix_element(self, j, m, jp, mp):
result = self.__class__.D(
jp, m, mp, self.alpha, self.beta, self.gamma
)
result *= KroneckerDelta(j, jp)
return result
def _represent_base(self, basis, **options):
j = sympify(options.get('j', S.Half))
# TODO: move evaluation up to represent function/implement elsewhere
evaluate = sympify(options.get('doit'))
size, mvals = m_values(j)
result = zeros(size, size)
for p in range(size):
for q in range(size):
me = self.matrix_element(j, mvals[p], j, mvals[q])
if evaluate:
result[p, q] = me.doit()
else:
result[p, q] = me
return result
def _represent_default_basis(self, **options):
return self._represent_JzOp(None, **options)
def _represent_JzOp(self, basis, **options):
return self._represent_base(basis, **options)
def _apply_operator_uncoupled(self, state, ket, *, dummy=True, **options):
a = self.alpha
b = self.beta
g = self.gamma
j = ket.j
m = ket.m
if j.is_number:
s = []
size = m_values(j)
sz = size[1]
for mp in sz:
r = Rotation.D(j, m, mp, a, b, g)
z = r.doit()
s.append(z*state(j, mp))
return Add(*s)
else:
if dummy:
mp = Dummy('mp')
else:
mp = symbols('mp')
return Sum(Rotation.D(j, m, mp, a, b, g)*state(j, mp), (mp, -j, j))
def _apply_operator_JxKet(self, ket, **options):
return self._apply_operator_uncoupled(JxKet, ket, **options)
def _apply_operator_JyKet(self, ket, **options):
return self._apply_operator_uncoupled(JyKet, ket, **options)
def _apply_operator_JzKet(self, ket, **options):
return self._apply_operator_uncoupled(JzKet, ket, **options)
def _apply_operator_coupled(self, state, ket, *, dummy=True, **options):
a = self.alpha
b = self.beta
g = self.gamma
j = ket.j
m = ket.m
jn = ket.jn
coupling = ket.coupling
if j.is_number:
s = []
size = m_values(j)
sz = size[1]
for mp in sz:
r = Rotation.D(j, m, mp, a, b, g)
z = r.doit()
s.append(z*state(j, mp, jn, coupling))
return Add(*s)
else:
if dummy:
mp = Dummy('mp')
else:
mp = symbols('mp')
return Sum(Rotation.D(j, m, mp, a, b, g)*state(
j, mp, jn, coupling), (mp, -j, j))
def _apply_operator_JxKetCoupled(self, ket, **options):
return self._apply_operator_coupled(JxKetCoupled, ket, **options)
def _apply_operator_JyKetCoupled(self, ket, **options):
return self._apply_operator_coupled(JyKetCoupled, ket, **options)
def _apply_operator_JzKetCoupled(self, ket, **options):
return self._apply_operator_coupled(JzKetCoupled, ket, **options)
class WignerD(Expr):
r"""Wigner-D function
The Wigner D-function gives the matrix elements of the rotation
operator in the jm-representation. For the Euler angles `\alpha`,
`\beta`, `\gamma`, the D-function is defined such that:
.. math ::
<j,m| \mathcal{R}(\alpha, \beta, \gamma ) |j',m'> = \delta_{jj'} D(j, m, m', \alpha, \beta, \gamma)
Where the rotation operator is as defined by the Rotation class [1]_.
The Wigner D-function defined in this way gives:
.. math ::
D(j, m, m', \alpha, \beta, \gamma) = e^{-i m \alpha} d(j, m, m', \beta) e^{-i m' \gamma}
Where d is the Wigner small-d function, which is given by Rotation.d.
The Wigner small-d function gives the component of the Wigner
D-function that is determined by the second Euler angle. That is the
Wigner D-function is:
.. math ::
D(j, m, m', \alpha, \beta, \gamma) = e^{-i m \alpha} d(j, m, m', \beta) e^{-i m' \gamma}
Where d is the small-d function. The Wigner D-function is given by
Rotation.D.
Note that to evaluate the D-function, the j, m and mp parameters must
be integer or half integer numbers.
Parameters
==========
j : Number
Total angular momentum
m : Number
Eigenvalue of angular momentum along axis after rotation
mp : Number
Eigenvalue of angular momentum along rotated axis
alpha : Number, Symbol
First Euler angle of rotation
beta : Number, Symbol
Second Euler angle of rotation
gamma : Number, Symbol
Third Euler angle of rotation
Examples
========
Evaluate the Wigner-D matrix elements of a simple rotation:
>>> from sympy.physics.quantum.spin import Rotation
>>> from sympy import pi
>>> rot = Rotation.D(1, 1, 0, pi, pi/2, 0)
>>> rot
WignerD(1, 1, 0, pi, pi/2, 0)
>>> rot.doit()
sqrt(2)/2
Evaluate the Wigner-d matrix elements of a simple rotation
>>> rot = Rotation.d(1, 1, 0, pi/2)
>>> rot
WignerD(1, 1, 0, 0, pi/2, 0)
>>> rot.doit()
-sqrt(2)/2
See Also
========
Rotation: Rotation operator
References
==========
.. [1] Varshalovich, D A, Quantum Theory of Angular Momentum. 1988.
"""
is_commutative = True
def __new__(cls, *args, **hints):
if not len(args) == 6:
raise ValueError('6 parameters expected, got %s' % args)
args = sympify(args)
evaluate = hints.get('evaluate', False)
if evaluate:
return Expr.__new__(cls, *args)._eval_wignerd()
return Expr.__new__(cls, *args)
@property
def j(self):
return self.args[0]
@property
def m(self):
return self.args[1]
@property
def mp(self):
return self.args[2]
@property
def alpha(self):
return self.args[3]
@property
def beta(self):
return self.args[4]
@property
def gamma(self):
return self.args[5]
def _latex(self, printer, *args):
if self.alpha == 0 and self.gamma == 0:
return r'd^{%s}_{%s,%s}\left(%s\right)' % \
(
printer._print(self.j), printer._print(
self.m), printer._print(self.mp),
printer._print(self.beta) )
return r'D^{%s}_{%s,%s}\left(%s,%s,%s\right)' % \
(
printer._print(
self.j), printer._print(self.m), printer._print(self.mp),
printer._print(self.alpha), printer._print(self.beta), printer._print(self.gamma) )
def _pretty(self, printer, *args):
top = printer._print(self.j)
bot = printer._print(self.m)
bot = prettyForm(*bot.right(','))
bot = prettyForm(*bot.right(printer._print(self.mp)))
pad = max(top.width(), bot.width())
top = prettyForm(*top.left(' '))
bot = prettyForm(*bot.left(' '))
if pad > top.width():
top = prettyForm(*top.right(' '*(pad - top.width())))
if pad > bot.width():
bot = prettyForm(*bot.right(' '*(pad - bot.width())))
if self.alpha == 0 and self.gamma == 0:
args = printer._print(self.beta)
s = stringPict('d' + ' '*pad)
else:
args = printer._print(self.alpha)
args = prettyForm(*args.right(','))
args = prettyForm(*args.right(printer._print(self.beta)))
args = prettyForm(*args.right(','))
args = prettyForm(*args.right(printer._print(self.gamma)))
s = stringPict('D' + ' '*pad)
args = prettyForm(*args.parens())
s = prettyForm(*s.above(top))
s = prettyForm(*s.below(bot))
s = prettyForm(*s.right(args))
return s
def doit(self, **hints):
hints['evaluate'] = True
return WignerD(*self.args, **hints)
def _eval_wignerd(self):
j = self.j
m = self.m
mp = self.mp
alpha = self.alpha
beta = self.beta
gamma = self.gamma
if alpha == 0 and beta == 0 and gamma == 0:
return KroneckerDelta(m, mp)
if not j.is_number:
raise ValueError(
'j parameter must be numerical to evaluate, got %s' % j)
r = 0
if beta == pi/2:
# Varshalovich Equation (5), Section 4.16, page 113, setting
# alpha=gamma=0.
for k in range(2*j + 1):
if k > j + mp or k > j - m or k < mp - m:
continue
r += (S.NegativeOne)**k*binomial(j + mp, k)*binomial(j - mp, k + m - mp)
r *= (S.NegativeOne)**(m - mp) / 2**j*sqrt(factorial(j + m) *
factorial(j - m) / (factorial(j + mp)*factorial(j - mp)))
else:
# Varshalovich Equation(5), Section 4.7.2, page 87, where we set
# beta1=beta2=pi/2, and we get alpha=gamma=pi/2 and beta=phi+pi,
# then we use the Eq. (1), Section 4.4. page 79, to simplify:
# d(j, m, mp, beta+pi) = (-1)**(j-mp)*d(j, m, -mp, beta)
# This happens to be almost the same as in Eq.(10), Section 4.16,
# except that we need to substitute -mp for mp.
size, mvals = m_values(j)
for mpp in mvals:
r += Rotation.d(j, m, mpp, pi/2).doit()*(cos(-mpp*beta) + I*sin(-mpp*beta))*\
Rotation.d(j, mpp, -mp, pi/2).doit()
# Empirical normalization factor so results match Varshalovich
# Tables 4.3-4.12
# Note that this exact normalization does not follow from the
# above equations
r = r*I**(2*j - m - mp)*(-1)**(2*m)
# Finally, simplify the whole expression
r = simplify(r)
r *= exp(-I*m*alpha)*exp(-I*mp*gamma)
return r
Jx = JxOp('J')
Jy = JyOp('J')
Jz = JzOp('J')
J2 = J2Op('J')
Jplus = JplusOp('J')
Jminus = JminusOp('J')
#-----------------------------------------------------------------------------
# Spin States
#-----------------------------------------------------------------------------
class SpinState(State):
"""Base class for angular momentum states."""
_label_separator = ','
def __new__(cls, j, m):
j = sympify(j)
m = sympify(m)
if j.is_number:
if 2*j != int(2*j):
raise ValueError(
'j must be integer or half-integer, got: %s' % j)
if j < 0:
raise ValueError('j must be >= 0, got: %s' % j)
if m.is_number:
if 2*m != int(2*m):
raise ValueError(
'm must be integer or half-integer, got: %s' % m)
if j.is_number and m.is_number:
if abs(m) > j:
raise ValueError('Allowed values for m are -j <= m <= j, got j, m: %s, %s' % (j, m))
if int(j - m) != j - m:
raise ValueError('Both j and m must be integer or half-integer, got j, m: %s, %s' % (j, m))
return State.__new__(cls, j, m)
@property
def j(self):
return self.label[0]
@property
def m(self):
return self.label[1]
@classmethod
def _eval_hilbert_space(cls, label):
return ComplexSpace(2*label[0] + 1)
def _represent_base(self, **options):
j = self.j
m = self.m
alpha = sympify(options.get('alpha', 0))
beta = sympify(options.get('beta', 0))
gamma = sympify(options.get('gamma', 0))
size, mvals = m_values(j)
result = zeros(size, 1)
# breaks finding angles on L930
for p, mval in enumerate(mvals):
if m.is_number:
result[p, 0] = Rotation.D(
self.j, mval, self.m, alpha, beta, gamma).doit()
else:
result[p, 0] = Rotation.D(self.j, mval,
self.m, alpha, beta, gamma)
return result
def _eval_rewrite_as_Jx(self, *args, **options):
if isinstance(self, Bra):
return self._rewrite_basis(Jx, JxBra, **options)
return self._rewrite_basis(Jx, JxKet, **options)
def _eval_rewrite_as_Jy(self, *args, **options):
if isinstance(self, Bra):
return self._rewrite_basis(Jy, JyBra, **options)
return self._rewrite_basis(Jy, JyKet, **options)
def _eval_rewrite_as_Jz(self, *args, **options):
if isinstance(self, Bra):
return self._rewrite_basis(Jz, JzBra, **options)
return self._rewrite_basis(Jz, JzKet, **options)
def _rewrite_basis(self, basis, evect, **options):
from sympy.physics.quantum.represent import represent
j = self.j
args = self.args[2:]
if j.is_number:
if isinstance(self, CoupledSpinState):
if j == int(j):
start = j**2
else:
start = (2*j - 1)*(2*j + 1)/4
else:
start = 0
vect = represent(self, basis=basis, **options)
result = Add(
*[vect[start + i]*evect(j, j - i, *args) for i in range(2*j + 1)])
if isinstance(self, CoupledSpinState) and options.get('coupled') is False:
return uncouple(result)
return result
else:
i = 0
mi = symbols('mi')
# make sure not to introduce a symbol already in the state
while self.subs(mi, 0) != self:
i += 1
mi = symbols('mi%d' % i)
break
# TODO: better way to get angles of rotation
if isinstance(self, CoupledSpinState):
test_args = (0, mi, (0, 0))
else:
test_args = (0, mi)
if isinstance(self, Ket):
angles = represent(
self.__class__(*test_args), basis=basis)[0].args[3:6]
else:
angles = represent(self.__class__(
*test_args), basis=basis)[0].args[0].args[3:6]
if angles == (0, 0, 0):
return self
else:
state = evect(j, mi, *args)
lt = Rotation.D(j, mi, self.m, *angles)
return Sum(lt*state, (mi, -j, j))
def _eval_innerproduct_JxBra(self, bra, **hints):
result = KroneckerDelta(self.j, bra.j)
if bra.dual_class() is not self.__class__:
result *= self._represent_JxOp(None)[bra.j - bra.m]
else:
result *= KroneckerDelta(
self.j, bra.j)*KroneckerDelta(self.m, bra.m)
return result
def _eval_innerproduct_JyBra(self, bra, **hints):
result = KroneckerDelta(self.j, bra.j)
if bra.dual_class() is not self.__class__:
result *= self._represent_JyOp(None)[bra.j - bra.m]
else:
result *= KroneckerDelta(
self.j, bra.j)*KroneckerDelta(self.m, bra.m)
return result
def _eval_innerproduct_JzBra(self, bra, **hints):
result = KroneckerDelta(self.j, bra.j)
if bra.dual_class() is not self.__class__:
result *= self._represent_JzOp(None)[bra.j - bra.m]
else:
result *= KroneckerDelta(
self.j, bra.j)*KroneckerDelta(self.m, bra.m)
return result
def _eval_trace(self, bra, **hints):
# One way to implement this method is to assume the basis set k is
# passed.
# Then we can apply the discrete form of Trace formula here
# Tr(|i><j| ) = \Sum_k <k|i><j|k>
#then we do qapply() on each each inner product and sum over them.
# OR
# Inner product of |i><j| = Trace(Outer Product).
# we could just use this unless there are cases when this is not true
return (bra*self).doit()
class JxKet(SpinState, Ket):
"""Eigenket of Jx.
See JzKet for the usage of spin eigenstates.
See Also
========
JzKet: Usage of spin states
"""
@classmethod
def dual_class(self):
return JxBra
@classmethod
def coupled_class(self):
return JxKetCoupled
def _represent_default_basis(self, **options):
return self._represent_JxOp(None, **options)
def _represent_JxOp(self, basis, **options):
return self._represent_base(**options)
def _represent_JyOp(self, basis, **options):
return self._represent_base(alpha=pi*Rational(3, 2), **options)
def _represent_JzOp(self, basis, **options):
return self._represent_base(beta=pi/2, **options)
class JxBra(SpinState, Bra):
"""Eigenbra of Jx.
See JzKet for the usage of spin eigenstates.
See Also
========
JzKet: Usage of spin states
"""
@classmethod
def dual_class(self):
return JxKet
@classmethod
def coupled_class(self):
return JxBraCoupled
class JyKet(SpinState, Ket):
"""Eigenket of Jy.
See JzKet for the usage of spin eigenstates.
See Also
========
JzKet: Usage of spin states
"""
@classmethod
def dual_class(self):
return JyBra
@classmethod
def coupled_class(self):
return JyKetCoupled
def _represent_default_basis(self, **options):
return self._represent_JyOp(None, **options)
def _represent_JxOp(self, basis, **options):
return self._represent_base(gamma=pi/2, **options)
def _represent_JyOp(self, basis, **options):
return self._represent_base(**options)
def _represent_JzOp(self, basis, **options):
return self._represent_base(alpha=pi*Rational(3, 2), beta=-pi/2, gamma=pi/2, **options)
class JyBra(SpinState, Bra):
"""Eigenbra of Jy.
See JzKet for the usage of spin eigenstates.
See Also
========
JzKet: Usage of spin states
"""
@classmethod
def dual_class(self):
return JyKet
@classmethod
def coupled_class(self):
return JyBraCoupled
class JzKet(SpinState, Ket):
"""Eigenket of Jz.
Spin state which is an eigenstate of the Jz operator. Uncoupled states,
that is states representing the interaction of multiple separate spin
states, are defined as a tensor product of states.
Parameters
==========
j : Number, Symbol
Total spin angular momentum
m : Number, Symbol
Eigenvalue of the Jz spin operator
Examples
========
*Normal States:*
Defining simple spin states, both numerical and symbolic:
>>> from sympy.physics.quantum.spin import JzKet, JxKet
>>> from sympy import symbols
>>> JzKet(1, 0)
|1,0>
>>> j, m = symbols('j m')
>>> JzKet(j, m)
|j,m>
Rewriting the JzKet in terms of eigenkets of the Jx operator:
Note: that the resulting eigenstates are JxKet's
>>> JzKet(1,1).rewrite("Jx")
|1,-1>/2 - sqrt(2)*|1,0>/2 + |1,1>/2
Get the vector representation of a state in terms of the basis elements
of the Jx operator:
>>> from sympy.physics.quantum.represent import represent
>>> from sympy.physics.quantum.spin import Jx, Jz
>>> represent(JzKet(1,-1), basis=Jx)
Matrix([
[ 1/2],
[sqrt(2)/2],
[ 1/2]])
Apply innerproducts between states:
>>> from sympy.physics.quantum.innerproduct import InnerProduct
>>> from sympy.physics.quantum.spin import JxBra
>>> i = InnerProduct(JxBra(1,1), JzKet(1,1))
>>> i
<1,1|1,1>
>>> i.doit()
1/2
*Uncoupled States:*
Define an uncoupled state as a TensorProduct between two Jz eigenkets:
>>> from sympy.physics.quantum.tensorproduct import TensorProduct
>>> j1,m1,j2,m2 = symbols('j1 m1 j2 m2')
>>> TensorProduct(JzKet(1,0), JzKet(1,1))
|1,0>x|1,1>
>>> TensorProduct(JzKet(j1,m1), JzKet(j2,m2))
|j1,m1>x|j2,m2>
A TensorProduct can be rewritten, in which case the eigenstates that make
up the tensor product is rewritten to the new basis:
>>> TensorProduct(JzKet(1,1),JxKet(1,1)).rewrite('Jz')
|1,1>x|1,-1>/2 + sqrt(2)*|1,1>x|1,0>/2 + |1,1>x|1,1>/2
The represent method for TensorProduct's gives the vector representation of
the state. Note that the state in the product basis is the equivalent of the
tensor product of the vector representation of the component eigenstates:
>>> represent(TensorProduct(JzKet(1,0),JzKet(1,1)))
Matrix([
[0],
[0],
[0],
[1],
[0],
[0],
[0],
[0],
[0]])
>>> represent(TensorProduct(JzKet(1,1),JxKet(1,1)), basis=Jz)
Matrix([
[ 1/2],
[sqrt(2)/2],
[ 1/2],
[ 0],
[ 0],
[ 0],
[ 0],
[ 0],
[ 0]])
See Also
========
JzKetCoupled: Coupled eigenstates
sympy.physics.quantum.tensorproduct.TensorProduct: Used to specify uncoupled states
uncouple: Uncouples states given coupling parameters
couple: Couples uncoupled states
"""
@classmethod
def dual_class(self):
return JzBra
@classmethod
def coupled_class(self):
return JzKetCoupled
def _represent_default_basis(self, **options):
return self._represent_JzOp(None, **options)
def _represent_JxOp(self, basis, **options):
return self._represent_base(beta=pi*Rational(3, 2), **options)
def _represent_JyOp(self, basis, **options):
return self._represent_base(alpha=pi*Rational(3, 2), beta=pi/2, gamma=pi/2, **options)
def _represent_JzOp(self, basis, **options):
return self._represent_base(**options)
class JzBra(SpinState, Bra):
"""Eigenbra of Jz.
See the JzKet for the usage of spin eigenstates.
See Also
========
JzKet: Usage of spin states
"""
@classmethod
def dual_class(self):
return JzKet
@classmethod
def coupled_class(self):
return JzBraCoupled
# Method used primarily to create coupled_n and coupled_jn by __new__ in
# CoupledSpinState
# This same method is also used by the uncouple method, and is separated from
# the CoupledSpinState class to maintain consistency in defining coupling
def _build_coupled(jcoupling, length):
n_list = [ [n + 1] for n in range(length) ]
coupled_jn = []
coupled_n = []
for n1, n2, j_new in jcoupling:
coupled_jn.append(j_new)
coupled_n.append( (n_list[n1 - 1], n_list[n2 - 1]) )
n_sort = sorted(n_list[n1 - 1] + n_list[n2 - 1])
n_list[n_sort[0] - 1] = n_sort
return coupled_n, coupled_jn
class CoupledSpinState(SpinState):
"""Base class for coupled angular momentum states."""
def __new__(cls, j, m, jn, *jcoupling):
# Check j and m values using SpinState
SpinState(j, m)
# Build and check coupling scheme from arguments
if len(jcoupling) == 0:
# Use default coupling scheme
jcoupling = []
for n in range(2, len(jn)):
jcoupling.append( (1, n, Add(*[jn[i] for i in range(n)])) )
jcoupling.append( (1, len(jn), j) )
elif len(jcoupling) == 1:
# Use specified coupling scheme
jcoupling = jcoupling[0]
else:
raise TypeError("CoupledSpinState only takes 3 or 4 arguments, got: %s" % (len(jcoupling) + 3) )
# Check arguments have correct form
if not isinstance(jn, (list, tuple, Tuple)):
raise TypeError('jn must be Tuple, list or tuple, got %s' %
jn.__class__.__name__)
if not isinstance(jcoupling, (list, tuple, Tuple)):
raise TypeError('jcoupling must be Tuple, list or tuple, got %s' %
jcoupling.__class__.__name__)
if not all(isinstance(term, (list, tuple, Tuple)) for term in jcoupling):
raise TypeError(
'All elements of jcoupling must be list, tuple or Tuple')
if not len(jn) - 1 == len(jcoupling):
raise ValueError('jcoupling must have length of %d, got %d' %
(len(jn) - 1, len(jcoupling)))
if not all(len(x) == 3 for x in jcoupling):
raise ValueError('All elements of jcoupling must have length 3')
# Build sympified args
j = sympify(j)
m = sympify(m)
jn = Tuple( *[sympify(ji) for ji in jn] )
jcoupling = Tuple( *[Tuple(sympify(
n1), sympify(n2), sympify(ji)) for (n1, n2, ji) in jcoupling] )
# Check values in coupling scheme give physical state
if any(2*ji != int(2*ji) for ji in jn if ji.is_number):
raise ValueError('All elements of jn must be integer or half-integer, got: %s' % jn)
if any(n1 != int(n1) or n2 != int(n2) for (n1, n2, _) in jcoupling):
raise ValueError('Indices in jcoupling must be integers')
if any(n1 < 1 or n2 < 1 or n1 > len(jn) or n2 > len(jn) for (n1, n2, _) in jcoupling):
raise ValueError('Indices must be between 1 and the number of coupled spin spaces')
if any(2*ji != int(2*ji) for (_, _, ji) in jcoupling if ji.is_number):
raise ValueError('All coupled j values in coupling scheme must be integer or half-integer')
coupled_n, coupled_jn = _build_coupled(jcoupling, len(jn))
jvals = list(jn)
for n, (n1, n2) in enumerate(coupled_n):
j1 = jvals[min(n1) - 1]
j2 = jvals[min(n2) - 1]
j3 = coupled_jn[n]
if sympify(j1).is_number and sympify(j2).is_number and sympify(j3).is_number:
if j1 + j2 < j3:
raise ValueError('All couplings must have j1+j2 >= j3, '
'in coupling number %d got j1,j2,j3: %d,%d,%d' % (n + 1, j1, j2, j3))
if abs(j1 - j2) > j3:
raise ValueError("All couplings must have |j1+j2| <= j3, "
"in coupling number %d got j1,j2,j3: %d,%d,%d" % (n + 1, j1, j2, j3))
if int(j1 + j2) == j1 + j2:
pass
jvals[min(n1 + n2) - 1] = j3
if len(jcoupling) > 0 and jcoupling[-1][2] != j:
raise ValueError('Last j value coupled together must be the final j of the state')
# Return state
return State.__new__(cls, j, m, jn, jcoupling)
def _print_label(self, printer, *args):
label = [printer._print(self.j), printer._print(self.m)]
for i, ji in enumerate(self.jn, start=1):
label.append('j%d=%s' % (
i, printer._print(ji)
))
for jn, (n1, n2) in zip(self.coupled_jn[:-1], self.coupled_n[:-1]):
label.append('j(%s)=%s' % (
','.join(str(i) for i in sorted(n1 + n2)), printer._print(jn)
))
return ','.join(label)
def _print_label_pretty(self, printer, *args):
label = [self.j, self.m]
for i, ji in enumerate(self.jn, start=1):
symb = 'j%d' % i
symb = pretty_symbol(symb)
symb = prettyForm(symb + '=')
item = prettyForm(*symb.right(printer._print(ji)))
label.append(item)
for jn, (n1, n2) in zip(self.coupled_jn[:-1], self.coupled_n[:-1]):
n = ','.join(pretty_symbol("j%d" % i)[-1] for i in sorted(n1 + n2))
symb = prettyForm('j' + n + '=')
item = prettyForm(*symb.right(printer._print(jn)))
label.append(item)
return self._print_sequence_pretty(
label, self._label_separator, printer, *args
)
def _print_label_latex(self, printer, *args):
label = [
printer._print(self.j, *args),
printer._print(self.m, *args)
]
for i, ji in enumerate(self.jn, start=1):
label.append('j_{%d}=%s' % (i, printer._print(ji, *args)) )
for jn, (n1, n2) in zip(self.coupled_jn[:-1], self.coupled_n[:-1]):
n = ','.join(str(i) for i in sorted(n1 + n2))
label.append('j_{%s}=%s' % (n, printer._print(jn, *args)) )
return self._label_separator.join(label)
@property
def jn(self):
return self.label[2]
@property
def coupling(self):
return self.label[3]
@property
def coupled_jn(self):
return _build_coupled(self.label[3], len(self.label[2]))[1]
@property
def coupled_n(self):
return _build_coupled(self.label[3], len(self.label[2]))[0]
@classmethod
def _eval_hilbert_space(cls, label):
j = Add(*label[2])
if j.is_number:
return DirectSumHilbertSpace(*[ ComplexSpace(x) for x in range(int(2*j + 1), 0, -2) ])
else:
# TODO: Need hilbert space fix, see issue 5732
# Desired behavior:
#ji = symbols('ji')
#ret = Sum(ComplexSpace(2*ji + 1), (ji, 0, j))
# Temporary fix:
return ComplexSpace(2*j + 1)
def _represent_coupled_base(self, **options):
evect = self.uncoupled_class()
if not self.j.is_number:
raise ValueError(
'State must not have symbolic j value to represent')
if not self.hilbert_space.dimension.is_number:
raise ValueError(
'State must not have symbolic j values to represent')
result = zeros(self.hilbert_space.dimension, 1)
if self.j == int(self.j):
start = self.j**2
else:
start = (2*self.j - 1)*(1 + 2*self.j)/4
result[start:start + 2*self.j + 1, 0] = evect(
self.j, self.m)._represent_base(**options)
return result
def _eval_rewrite_as_Jx(self, *args, **options):
if isinstance(self, Bra):
return self._rewrite_basis(Jx, JxBraCoupled, **options)
return self._rewrite_basis(Jx, JxKetCoupled, **options)
def _eval_rewrite_as_Jy(self, *args, **options):
if isinstance(self, Bra):
return self._rewrite_basis(Jy, JyBraCoupled, **options)
return self._rewrite_basis(Jy, JyKetCoupled, **options)
def _eval_rewrite_as_Jz(self, *args, **options):
if isinstance(self, Bra):
return self._rewrite_basis(Jz, JzBraCoupled, **options)
return self._rewrite_basis(Jz, JzKetCoupled, **options)
class JxKetCoupled(CoupledSpinState, Ket):
"""Coupled eigenket of Jx.
See JzKetCoupled for the usage of coupled spin eigenstates.
See Also
========
JzKetCoupled: Usage of coupled spin states
"""
@classmethod
def dual_class(self):
return JxBraCoupled
@classmethod
def uncoupled_class(self):
return JxKet
def _represent_default_basis(self, **options):
return self._represent_JzOp(None, **options)
def _represent_JxOp(self, basis, **options):
return self._represent_coupled_base(**options)
def _represent_JyOp(self, basis, **options):
return self._represent_coupled_base(alpha=pi*Rational(3, 2), **options)
def _represent_JzOp(self, basis, **options):
return self._represent_coupled_base(beta=pi/2, **options)
class JxBraCoupled(CoupledSpinState, Bra):
"""Coupled eigenbra of Jx.
See JzKetCoupled for the usage of coupled spin eigenstates.
See Also
========
JzKetCoupled: Usage of coupled spin states
"""
@classmethod
def dual_class(self):
return JxKetCoupled
@classmethod
def uncoupled_class(self):
return JxBra
class JyKetCoupled(CoupledSpinState, Ket):
"""Coupled eigenket of Jy.
See JzKetCoupled for the usage of coupled spin eigenstates.
See Also
========
JzKetCoupled: Usage of coupled spin states
"""
@classmethod
def dual_class(self):
return JyBraCoupled
@classmethod
def uncoupled_class(self):
return JyKet
def _represent_default_basis(self, **options):
return self._represent_JzOp(None, **options)
def _represent_JxOp(self, basis, **options):
return self._represent_coupled_base(gamma=pi/2, **options)
def _represent_JyOp(self, basis, **options):
return self._represent_coupled_base(**options)
def _represent_JzOp(self, basis, **options):
return self._represent_coupled_base(alpha=pi*Rational(3, 2), beta=-pi/2, gamma=pi/2, **options)
class JyBraCoupled(CoupledSpinState, Bra):
"""Coupled eigenbra of Jy.
See JzKetCoupled for the usage of coupled spin eigenstates.
See Also
========
JzKetCoupled: Usage of coupled spin states
"""
@classmethod
def dual_class(self):
return JyKetCoupled
@classmethod
def uncoupled_class(self):
return JyBra
class JzKetCoupled(CoupledSpinState, Ket):
r"""Coupled eigenket of Jz
Spin state that is an eigenket of Jz which represents the coupling of
separate spin spaces.
The arguments for creating instances of JzKetCoupled are ``j``, ``m``,
``jn`` and an optional ``jcoupling`` argument. The ``j`` and ``m`` options
are the total angular momentum quantum numbers, as used for normal states
(e.g. JzKet).
The other required parameter in ``jn``, which is a tuple defining the `j_n`
angular momentum quantum numbers of the product spaces. So for example, if
a state represented the coupling of the product basis state
`\left|j_1,m_1\right\rangle\times\left|j_2,m_2\right\rangle`, the ``jn``
for this state would be ``(j1,j2)``.
The final option is ``jcoupling``, which is used to define how the spaces
specified by ``jn`` are coupled, which includes both the order these spaces
are coupled together and the quantum numbers that arise from these
couplings. The ``jcoupling`` parameter itself is a list of lists, such that
each of the sublists defines a single coupling between the spin spaces. If
there are N coupled angular momentum spaces, that is ``jn`` has N elements,
then there must be N-1 sublists. Each of these sublists making up the
``jcoupling`` parameter have length 3. The first two elements are the
indices of the product spaces that are considered to be coupled together.
For example, if we want to couple `j_1` and `j_4`, the indices would be 1
and 4. If a state has already been coupled, it is referenced by the
smallest index that is coupled, so if `j_2` and `j_4` has already been
coupled to some `j_{24}`, then this value can be coupled by referencing it
with index 2. The final element of the sublist is the quantum number of the
coupled state. So putting everything together, into a valid sublist for
``jcoupling``, if `j_1` and `j_2` are coupled to an angular momentum space
with quantum number `j_{12}` with the value ``j12``, the sublist would be
``(1,2,j12)``, N-1 of these sublists are used in the list for
``jcoupling``.
Note the ``jcoupling`` parameter is optional, if it is not specified, the
default coupling is taken. This default value is to coupled the spaces in
order and take the quantum number of the coupling to be the maximum value.
For example, if the spin spaces are `j_1`, `j_2`, `j_3`, `j_4`, then the
default coupling couples `j_1` and `j_2` to `j_{12}=j_1+j_2`, then,
`j_{12}` and `j_3` are coupled to `j_{123}=j_{12}+j_3`, and finally
`j_{123}` and `j_4` to `j=j_{123}+j_4`. The jcoupling value that would
correspond to this is:
``((1,2,j1+j2),(1,3,j1+j2+j3))``
Parameters
==========
args : tuple
The arguments that must be passed are ``j``, ``m``, ``jn``, and
``jcoupling``. The ``j`` value is the total angular momentum. The ``m``
value is the eigenvalue of the Jz spin operator. The ``jn`` list are
the j values of argular momentum spaces coupled together. The
``jcoupling`` parameter is an optional parameter defining how the spaces
are coupled together. See the above description for how these coupling
parameters are defined.
Examples
========
Defining simple spin states, both numerical and symbolic:
>>> from sympy.physics.quantum.spin import JzKetCoupled
>>> from sympy import symbols
>>> JzKetCoupled(1, 0, (1, 1))
|1,0,j1=1,j2=1>
>>> j, m, j1, j2 = symbols('j m j1 j2')
>>> JzKetCoupled(j, m, (j1, j2))
|j,m,j1=j1,j2=j2>
Defining coupled spin states for more than 2 coupled spaces with various
coupling parameters:
>>> JzKetCoupled(2, 1, (1, 1, 1))
|2,1,j1=1,j2=1,j3=1,j(1,2)=2>
>>> JzKetCoupled(2, 1, (1, 1, 1), ((1,2,2),(1,3,2)) )
|2,1,j1=1,j2=1,j3=1,j(1,2)=2>
>>> JzKetCoupled(2, 1, (1, 1, 1), ((2,3,1),(1,2,2)) )
|2,1,j1=1,j2=1,j3=1,j(2,3)=1>
Rewriting the JzKetCoupled in terms of eigenkets of the Jx operator:
Note: that the resulting eigenstates are JxKetCoupled
>>> JzKetCoupled(1,1,(1,1)).rewrite("Jx")
|1,-1,j1=1,j2=1>/2 - sqrt(2)*|1,0,j1=1,j2=1>/2 + |1,1,j1=1,j2=1>/2
The rewrite method can be used to convert a coupled state to an uncoupled
state. This is done by passing coupled=False to the rewrite function:
>>> JzKetCoupled(1, 0, (1, 1)).rewrite('Jz', coupled=False)
-sqrt(2)*|1,-1>x|1,1>/2 + sqrt(2)*|1,1>x|1,-1>/2
Get the vector representation of a state in terms of the basis elements
of the Jx operator:
>>> from sympy.physics.quantum.represent import represent
>>> from sympy.physics.quantum.spin import Jx
>>> from sympy import S
>>> represent(JzKetCoupled(1,-1,(S(1)/2,S(1)/2)), basis=Jx)
Matrix([
[ 0],
[ 1/2],
[sqrt(2)/2],
[ 1/2]])
See Also
========
JzKet: Normal spin eigenstates
uncouple: Uncoupling of coupling spin states
couple: Coupling of uncoupled spin states
"""
@classmethod
def dual_class(self):
return JzBraCoupled
@classmethod
def uncoupled_class(self):
return JzKet
def _represent_default_basis(self, **options):
return self._represent_JzOp(None, **options)
def _represent_JxOp(self, basis, **options):
return self._represent_coupled_base(beta=pi*Rational(3, 2), **options)
def _represent_JyOp(self, basis, **options):
return self._represent_coupled_base(alpha=pi*Rational(3, 2), beta=pi/2, gamma=pi/2, **options)
def _represent_JzOp(self, basis, **options):
return self._represent_coupled_base(**options)
class JzBraCoupled(CoupledSpinState, Bra):
"""Coupled eigenbra of Jz.
See the JzKetCoupled for the usage of coupled spin eigenstates.
See Also
========
JzKetCoupled: Usage of coupled spin states
"""
@classmethod
def dual_class(self):
return JzKetCoupled
@classmethod
def uncoupled_class(self):
return JzBra
#-----------------------------------------------------------------------------
# Coupling/uncoupling
#-----------------------------------------------------------------------------
def couple(expr, jcoupling_list=None):
""" Couple a tensor product of spin states
This function can be used to couple an uncoupled tensor product of spin
states. All of the eigenstates to be coupled must be of the same class. It
will return a linear combination of eigenstates that are subclasses of
CoupledSpinState determined by Clebsch-Gordan angular momentum coupling
coefficients.
Parameters
==========
expr : Expr
An expression involving TensorProducts of spin states to be coupled.
Each state must be a subclass of SpinState and they all must be the
same class.
jcoupling_list : list or tuple
Elements of this list are sub-lists of length 2 specifying the order of
the coupling of the spin spaces. The length of this must be N-1, where N
is the number of states in the tensor product to be coupled. The
elements of this sublist are the same as the first two elements of each
sublist in the ``jcoupling`` parameter defined for JzKetCoupled. If this
parameter is not specified, the default value is taken, which couples
the first and second product basis spaces, then couples this new coupled
space to the third product space, etc
Examples
========
Couple a tensor product of numerical states for two spaces:
>>> from sympy.physics.quantum.spin import JzKet, couple
>>> from sympy.physics.quantum.tensorproduct import TensorProduct
>>> couple(TensorProduct(JzKet(1,0), JzKet(1,1)))
-sqrt(2)*|1,1,j1=1,j2=1>/2 + sqrt(2)*|2,1,j1=1,j2=1>/2
Numerical coupling of three spaces using the default coupling method, i.e.
first and second spaces couple, then this couples to the third space:
>>> couple(TensorProduct(JzKet(1,1), JzKet(1,1), JzKet(1,0)))
sqrt(6)*|2,2,j1=1,j2=1,j3=1,j(1,2)=2>/3 + sqrt(3)*|3,2,j1=1,j2=1,j3=1,j(1,2)=2>/3
Perform this same coupling, but we define the coupling to first couple
the first and third spaces:
>>> couple(TensorProduct(JzKet(1,1), JzKet(1,1), JzKet(1,0)), ((1,3),(1,2)) )
sqrt(2)*|2,2,j1=1,j2=1,j3=1,j(1,3)=1>/2 - sqrt(6)*|2,2,j1=1,j2=1,j3=1,j(1,3)=2>/6 + sqrt(3)*|3,2,j1=1,j2=1,j3=1,j(1,3)=2>/3
Couple a tensor product of symbolic states:
>>> from sympy import symbols
>>> j1,m1,j2,m2 = symbols('j1 m1 j2 m2')
>>> couple(TensorProduct(JzKet(j1,m1), JzKet(j2,m2)))
Sum(CG(j1, m1, j2, m2, j, m1 + m2)*|j,m1 + m2,j1=j1,j2=j2>, (j, m1 + m2, j1 + j2))
"""
a = expr.atoms(TensorProduct)
for tp in a:
# Allow other tensor products to be in expression
if not all(isinstance(state, SpinState) for state in tp.args):
continue
# If tensor product has all spin states, raise error for invalid tensor product state
if not all(state.__class__ is tp.args[0].__class__ for state in tp.args):
raise TypeError('All states must be the same basis')
expr = expr.subs(tp, _couple(tp, jcoupling_list))
return expr
def _couple(tp, jcoupling_list):
states = tp.args
coupled_evect = states[0].coupled_class()
# Define default coupling if none is specified
if jcoupling_list is None:
jcoupling_list = []
for n in range(1, len(states)):
jcoupling_list.append( (1, n + 1) )
# Check jcoupling_list valid
if not len(jcoupling_list) == len(states) - 1:
raise TypeError('jcoupling_list must be length %d, got %d' %
(len(states) - 1, len(jcoupling_list)))
if not all( len(coupling) == 2 for coupling in jcoupling_list):
raise ValueError('Each coupling must define 2 spaces')
if any(n1 == n2 for n1, n2 in jcoupling_list):
raise ValueError('Spin spaces cannot couple to themselves')
if all(sympify(n1).is_number and sympify(n2).is_number for n1, n2 in jcoupling_list):
j_test = [0]*len(states)
for n1, n2 in jcoupling_list:
if j_test[n1 - 1] == -1 or j_test[n2 - 1] == -1:
raise ValueError('Spaces coupling j_n\'s are referenced by smallest n value')
j_test[max(n1, n2) - 1] = -1
# j values of states to be coupled together
jn = [state.j for state in states]
mn = [state.m for state in states]
# Create coupling_list, which defines all the couplings between all
# the spaces from jcoupling_list
coupling_list = []
n_list = [ [i + 1] for i in range(len(states)) ]
for j_coupling in jcoupling_list:
# Least n for all j_n which is coupled as first and second spaces
n1, n2 = j_coupling
# List of all n's coupled in first and second spaces
j1_n = list(n_list[n1 - 1])
j2_n = list(n_list[n2 - 1])
coupling_list.append( (j1_n, j2_n) )
# Set new j_n to be coupling of all j_n in both first and second spaces
n_list[ min(n1, n2) - 1 ] = sorted(j1_n + j2_n)
if all(state.j.is_number and state.m.is_number for state in states):
# Numerical coupling
# Iterate over difference between maximum possible j value of each coupling and the actual value
diff_max = [ Add( *[ jn[n - 1] - mn[n - 1] for n in coupling[0] +
coupling[1] ] ) for coupling in coupling_list ]
result = []
for diff in range(diff_max[-1] + 1):
# Determine available configurations
n = len(coupling_list)
tot = binomial(diff + n - 1, diff)
for config_num in range(tot):
diff_list = _confignum_to_difflist(config_num, diff, n)
# Skip the configuration if non-physical
# This is a lazy check for physical states given the loose restrictions of diff_max
if any(d > m for d, m in zip(diff_list, diff_max)):
continue
# Determine term
cg_terms = []
coupled_j = list(jn)
jcoupling = []
for (j1_n, j2_n), coupling_diff in zip(coupling_list, diff_list):
j1 = coupled_j[ min(j1_n) - 1 ]
j2 = coupled_j[ min(j2_n) - 1 ]
j3 = j1 + j2 - coupling_diff
coupled_j[ min(j1_n + j2_n) - 1 ] = j3
m1 = Add( *[ mn[x - 1] for x in j1_n] )
m2 = Add( *[ mn[x - 1] for x in j2_n] )
m3 = m1 + m2
cg_terms.append( (j1, m1, j2, m2, j3, m3) )
jcoupling.append( (min(j1_n), min(j2_n), j3) )
# Better checks that state is physical
if any(abs(term[5]) > term[4] for term in cg_terms):
continue
if any(term[0] + term[2] < term[4] for term in cg_terms):
continue
if any(abs(term[0] - term[2]) > term[4] for term in cg_terms):
continue
coeff = Mul( *[ CG(*term).doit() for term in cg_terms] )
state = coupled_evect(j3, m3, jn, jcoupling)
result.append(coeff*state)
return Add(*result)
else:
# Symbolic coupling
cg_terms = []
jcoupling = []
sum_terms = []
coupled_j = list(jn)
for j1_n, j2_n in coupling_list:
j1 = coupled_j[ min(j1_n) - 1 ]
j2 = coupled_j[ min(j2_n) - 1 ]
if len(j1_n + j2_n) == len(states):
j3 = symbols('j')
else:
j3_name = 'j' + ''.join(["%s" % n for n in j1_n + j2_n])
j3 = symbols(j3_name)
coupled_j[ min(j1_n + j2_n) - 1 ] = j3
m1 = Add( *[ mn[x - 1] for x in j1_n] )
m2 = Add( *[ mn[x - 1] for x in j2_n] )
m3 = m1 + m2
cg_terms.append( (j1, m1, j2, m2, j3, m3) )
jcoupling.append( (min(j1_n), min(j2_n), j3) )
sum_terms.append((j3, m3, j1 + j2))
coeff = Mul( *[ CG(*term) for term in cg_terms] )
state = coupled_evect(j3, m3, jn, jcoupling)
return Sum(coeff*state, *sum_terms)
def uncouple(expr, jn=None, jcoupling_list=None):
""" Uncouple a coupled spin state
Gives the uncoupled representation of a coupled spin state. Arguments must
be either a spin state that is a subclass of CoupledSpinState or a spin
state that is a subclass of SpinState and an array giving the j values
of the spaces that are to be coupled
Parameters
==========
expr : Expr
The expression containing states that are to be coupled. If the states
are a subclass of SpinState, the ``jn`` and ``jcoupling`` parameters
must be defined. If the states are a subclass of CoupledSpinState,
``jn`` and ``jcoupling`` will be taken from the state.
jn : list or tuple
The list of the j-values that are coupled. If state is a
CoupledSpinState, this parameter is ignored. This must be defined if
state is not a subclass of CoupledSpinState. The syntax of this
parameter is the same as the ``jn`` parameter of JzKetCoupled.
jcoupling_list : list or tuple
The list defining how the j-values are coupled together. If state is a
CoupledSpinState, this parameter is ignored. This must be defined if
state is not a subclass of CoupledSpinState. The syntax of this
parameter is the same as the ``jcoupling`` parameter of JzKetCoupled.
Examples
========
Uncouple a numerical state using a CoupledSpinState state:
>>> from sympy.physics.quantum.spin import JzKetCoupled, uncouple
>>> from sympy import S
>>> uncouple(JzKetCoupled(1, 0, (S(1)/2, S(1)/2)))
sqrt(2)*|1/2,-1/2>x|1/2,1/2>/2 + sqrt(2)*|1/2,1/2>x|1/2,-1/2>/2
Perform the same calculation using a SpinState state:
>>> from sympy.physics.quantum.spin import JzKet
>>> uncouple(JzKet(1, 0), (S(1)/2, S(1)/2))
sqrt(2)*|1/2,-1/2>x|1/2,1/2>/2 + sqrt(2)*|1/2,1/2>x|1/2,-1/2>/2
Uncouple a numerical state of three coupled spaces using a CoupledSpinState state:
>>> uncouple(JzKetCoupled(1, 1, (1, 1, 1), ((1,3,1),(1,2,1)) ))
|1,-1>x|1,1>x|1,1>/2 - |1,0>x|1,0>x|1,1>/2 + |1,1>x|1,0>x|1,0>/2 - |1,1>x|1,1>x|1,-1>/2
Perform the same calculation using a SpinState state:
>>> uncouple(JzKet(1, 1), (1, 1, 1), ((1,3,1),(1,2,1)) )
|1,-1>x|1,1>x|1,1>/2 - |1,0>x|1,0>x|1,1>/2 + |1,1>x|1,0>x|1,0>/2 - |1,1>x|1,1>x|1,-1>/2
Uncouple a symbolic state using a CoupledSpinState state:
>>> from sympy import symbols
>>> j,m,j1,j2 = symbols('j m j1 j2')
>>> uncouple(JzKetCoupled(j, m, (j1, j2)))
Sum(CG(j1, m1, j2, m2, j, m)*|j1,m1>x|j2,m2>, (m1, -j1, j1), (m2, -j2, j2))
Perform the same calculation using a SpinState state
>>> uncouple(JzKet(j, m), (j1, j2))
Sum(CG(j1, m1, j2, m2, j, m)*|j1,m1>x|j2,m2>, (m1, -j1, j1), (m2, -j2, j2))
"""
a = expr.atoms(SpinState)
for state in a:
expr = expr.subs(state, _uncouple(state, jn, jcoupling_list))
return expr
def _uncouple(state, jn, jcoupling_list):
if isinstance(state, CoupledSpinState):
jn = state.jn
coupled_n = state.coupled_n
coupled_jn = state.coupled_jn
evect = state.uncoupled_class()
elif isinstance(state, SpinState):
if jn is None:
raise ValueError("Must specify j-values for coupled state")
if not isinstance(jn, (list, tuple)):
raise TypeError("jn must be list or tuple")
if jcoupling_list is None:
# Use default
jcoupling_list = []
for i in range(1, len(jn)):
jcoupling_list.append(
(1, 1 + i, Add(*[jn[j] for j in range(i + 1)])) )
if not isinstance(jcoupling_list, (list, tuple)):
raise TypeError("jcoupling must be a list or tuple")
if not len(jcoupling_list) == len(jn) - 1:
raise ValueError("Must specify 2 fewer coupling terms than the number of j values")
coupled_n, coupled_jn = _build_coupled(jcoupling_list, len(jn))
evect = state.__class__
else:
raise TypeError("state must be a spin state")
j = state.j
m = state.m
coupling_list = []
j_list = list(jn)
# Create coupling, which defines all the couplings between all the spaces
for j3, (n1, n2) in zip(coupled_jn, coupled_n):
# j's which are coupled as first and second spaces
j1 = j_list[n1[0] - 1]
j2 = j_list[n2[0] - 1]
# Build coupling list
coupling_list.append( (n1, n2, j1, j2, j3) )
# Set new value in j_list
j_list[min(n1 + n2) - 1] = j3
if j.is_number and m.is_number:
diff_max = [ 2*x for x in jn ]
diff = Add(*jn) - m
n = len(jn)
tot = binomial(diff + n - 1, diff)
result = []
for config_num in range(tot):
diff_list = _confignum_to_difflist(config_num, diff, n)
if any(d > p for d, p in zip(diff_list, diff_max)):
continue
cg_terms = []
for coupling in coupling_list:
j1_n, j2_n, j1, j2, j3 = coupling
m1 = Add( *[ jn[x - 1] - diff_list[x - 1] for x in j1_n ] )
m2 = Add( *[ jn[x - 1] - diff_list[x - 1] for x in j2_n ] )
m3 = m1 + m2
cg_terms.append( (j1, m1, j2, m2, j3, m3) )
coeff = Mul( *[ CG(*term).doit() for term in cg_terms ] )
state = TensorProduct(
*[ evect(j, j - d) for j, d in zip(jn, diff_list) ] )
result.append(coeff*state)
return Add(*result)
else:
# Symbolic coupling
m_str = "m1:%d" % (len(jn) + 1)
mvals = symbols(m_str)
cg_terms = [(j1, Add(*[mvals[n - 1] for n in j1_n]),
j2, Add(*[mvals[n - 1] for n in j2_n]),
j3, Add(*[mvals[n - 1] for n in j1_n + j2_n])) for j1_n, j2_n, j1, j2, j3 in coupling_list[:-1] ]
cg_terms.append(*[(j1, Add(*[mvals[n - 1] for n in j1_n]),
j2, Add(*[mvals[n - 1] for n in j2_n]),
j, m) for j1_n, j2_n, j1, j2, j3 in [coupling_list[-1]] ])
cg_coeff = Mul(*[CG(*cg_term) for cg_term in cg_terms])
sum_terms = [ (m, -j, j) for j, m in zip(jn, mvals) ]
state = TensorProduct( *[ evect(j, m) for j, m in zip(jn, mvals) ] )
return Sum(cg_coeff*state, *sum_terms)
def _confignum_to_difflist(config_num, diff, list_len):
# Determines configuration of diffs into list_len number of slots
diff_list = []
for n in range(list_len):
prev_diff = diff
# Number of spots after current one
rem_spots = list_len - n - 1
# Number of configurations of distributing diff among the remaining spots
rem_configs = binomial(diff + rem_spots - 1, diff)
while config_num >= rem_configs:
config_num -= rem_configs
diff -= 1
rem_configs = binomial(diff + rem_spots - 1, diff)
diff_list.append(prev_diff - diff)
return diff_list
|
d99a8df4812ccf72ca1d32d5f190f04cad2c3393dfc0bd29dac61eb7437b1a2b | from sympy.core.add import Add
from sympy.core.containers import Tuple
from sympy.core.expr import Expr
from sympy.core.mul import Mul
from sympy.core.power import Pow
from sympy.core.sorting import default_sort_key
from sympy.core.sympify import sympify
from sympy.matrices import Matrix
def _is_scalar(e):
""" Helper method used in Tr"""
# sympify to set proper attributes
e = sympify(e)
if isinstance(e, Expr):
if (e.is_Integer or e.is_Float or
e.is_Rational or e.is_Number or
(e.is_Symbol and e.is_commutative)
):
return True
return False
def _cycle_permute(l):
""" Cyclic permutations based on canonical ordering
Explanation
===========
This method does the sort based ascii values while
a better approach would be to used lexicographic sort.
TODO: Handle condition such as symbols have subscripts/superscripts
in case of lexicographic sort
"""
if len(l) == 1:
return l
min_item = min(l, key=default_sort_key)
indices = [i for i, x in enumerate(l) if x == min_item]
le = list(l)
le.extend(l) # duplicate and extend string for easy processing
# adding the first min_item index back for easier looping
indices.append(len(l) + indices[0])
# create sublist of items with first item as min_item and last_item
# in each of the sublist is item just before the next occurrence of
# minitem in the cycle formed.
sublist = [[le[indices[i]:indices[i + 1]]] for i in
range(len(indices) - 1)]
# we do comparison of strings by comparing elements
# in each sublist
idx = sublist.index(min(sublist))
ordered_l = le[indices[idx]:indices[idx] + len(l)]
return ordered_l
def _rearrange_args(l):
""" this just moves the last arg to first position
to enable expansion of args
A,B,A ==> A**2,B
"""
if len(l) == 1:
return l
x = list(l[-1:])
x.extend(l[0:-1])
return Mul(*x).args
class Tr(Expr):
""" Generic Trace operation than can trace over:
a) SymPy matrix
b) operators
c) outer products
Parameters
==========
o : operator, matrix, expr
i : tuple/list indices (optional)
Examples
========
# TODO: Need to handle printing
a) Trace(A+B) = Tr(A) + Tr(B)
b) Trace(scalar*Operator) = scalar*Trace(Operator)
>>> from sympy.physics.quantum.trace import Tr
>>> from sympy import symbols, Matrix
>>> a, b = symbols('a b', commutative=True)
>>> A, B = symbols('A B', commutative=False)
>>> Tr(a*A,[2])
a*Tr(A)
>>> m = Matrix([[1,2],[1,1]])
>>> Tr(m)
2
"""
def __new__(cls, *args):
""" Construct a Trace object.
Parameters
==========
args = SymPy expression
indices = tuple/list if indices, optional
"""
# expect no indices,int or a tuple/list/Tuple
if (len(args) == 2):
if not isinstance(args[1], (list, Tuple, tuple)):
indices = Tuple(args[1])
else:
indices = Tuple(*args[1])
expr = args[0]
elif (len(args) == 1):
indices = Tuple()
expr = args[0]
else:
raise ValueError("Arguments to Tr should be of form "
"(expr[, [indices]])")
if isinstance(expr, Matrix):
return expr.trace()
elif hasattr(expr, 'trace') and callable(expr.trace):
#for any objects that have trace() defined e.g numpy
return expr.trace()
elif isinstance(expr, Add):
return Add(*[Tr(arg, indices) for arg in expr.args])
elif isinstance(expr, Mul):
c_part, nc_part = expr.args_cnc()
if len(nc_part) == 0:
return Mul(*c_part)
else:
obj = Expr.__new__(cls, Mul(*nc_part), indices )
#this check is needed to prevent cached instances
#being returned even if len(c_part)==0
return Mul(*c_part)*obj if len(c_part) > 0 else obj
elif isinstance(expr, Pow):
if (_is_scalar(expr.args[0]) and
_is_scalar(expr.args[1])):
return expr
else:
return Expr.__new__(cls, expr, indices)
else:
if (_is_scalar(expr)):
return expr
return Expr.__new__(cls, expr, indices)
@property
def kind(self):
expr = self.args[0]
expr_kind = expr.kind
return expr_kind.element_kind
def doit(self, **hints):
""" Perform the trace operation.
#TODO: Current version ignores the indices set for partial trace.
>>> from sympy.physics.quantum.trace import Tr
>>> from sympy.physics.quantum.operator import OuterProduct
>>> from sympy.physics.quantum.spin import JzKet, JzBra
>>> t = Tr(OuterProduct(JzKet(1,1), JzBra(1,1)))
>>> t.doit()
1
"""
if hasattr(self.args[0], '_eval_trace'):
return self.args[0]._eval_trace(indices=self.args[1])
return self
@property
def is_number(self):
# TODO : improve this implementation
return True
#TODO: Review if the permute method is needed
# and if it needs to return a new instance
def permute(self, pos):
""" Permute the arguments cyclically.
Parameters
==========
pos : integer, if positive, shift-right, else shift-left
Examples
========
>>> from sympy.physics.quantum.trace import Tr
>>> from sympy import symbols
>>> A, B, C, D = symbols('A B C D', commutative=False)
>>> t = Tr(A*B*C*D)
>>> t.permute(2)
Tr(C*D*A*B)
>>> t.permute(-2)
Tr(C*D*A*B)
"""
if pos > 0:
pos = pos % len(self.args[0].args)
else:
pos = -(abs(pos) % len(self.args[0].args))
args = list(self.args[0].args[-pos:] + self.args[0].args[0:-pos])
return Tr(Mul(*(args)))
def _hashable_content(self):
if isinstance(self.args[0], Mul):
args = _cycle_permute(_rearrange_args(self.args[0].args))
else:
args = [self.args[0]]
return tuple(args) + (self.args[1], )
|
084a88937f58aa37f435c7b86e869a4d01d8b8915e58e85ed38f3479dd0a79ff | #TODO:
# -Implement Clebsch-Gordan symmetries
# -Improve simplification method
# -Implement new simpifications
"""Clebsch-Gordon Coefficients."""
from sympy.concrete.summations import Sum
from sympy.core.add import Add
from sympy.core.expr import Expr
from sympy.core.function import expand
from sympy.core.mul import Mul
from sympy.core.power import Pow
from sympy.core.relational import Eq
from sympy.core.singleton import S
from sympy.core.symbol import (Wild, symbols)
from sympy.core.sympify import sympify
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.piecewise import Piecewise
from sympy.printing.pretty.stringpict import prettyForm, stringPict
from sympy.functions.special.tensor_functions import KroneckerDelta
from sympy.physics.wigner import clebsch_gordan, wigner_3j, wigner_6j, wigner_9j
from sympy.printing.precedence import PRECEDENCE
__all__ = [
'CG',
'Wigner3j',
'Wigner6j',
'Wigner9j',
'cg_simp'
]
#-----------------------------------------------------------------------------
# CG Coefficients
#-----------------------------------------------------------------------------
class Wigner3j(Expr):
"""Class for the Wigner-3j symbols.
Explanation
===========
Wigner 3j-symbols are coefficients determined by the coupling of
two angular momenta. When created, they are expressed as symbolic
quantities that, for numerical parameters, can be evaluated using the
``.doit()`` method [1]_.
Parameters
==========
j1, m1, j2, m2, j3, m3 : Number, Symbol
Terms determining the angular momentum of coupled angular momentum
systems.
Examples
========
Declare a Wigner-3j coefficient and calculate its value
>>> from sympy.physics.quantum.cg import Wigner3j
>>> w3j = Wigner3j(6,0,4,0,2,0)
>>> w3j
Wigner3j(6, 0, 4, 0, 2, 0)
>>> w3j.doit()
sqrt(715)/143
See Also
========
CG: Clebsch-Gordan coefficients
References
==========
.. [1] Varshalovich, D A, Quantum Theory of Angular Momentum. 1988.
"""
is_commutative = True
def __new__(cls, j1, m1, j2, m2, j3, m3):
args = map(sympify, (j1, m1, j2, m2, j3, m3))
return Expr.__new__(cls, *args)
@property
def j1(self):
return self.args[0]
@property
def m1(self):
return self.args[1]
@property
def j2(self):
return self.args[2]
@property
def m2(self):
return self.args[3]
@property
def j3(self):
return self.args[4]
@property
def m3(self):
return self.args[5]
@property
def is_symbolic(self):
return not all(arg.is_number for arg in self.args)
# This is modified from the _print_Matrix method
def _pretty(self, printer, *args):
m = ((printer._print(self.j1), printer._print(self.m1)),
(printer._print(self.j2), printer._print(self.m2)),
(printer._print(self.j3), printer._print(self.m3)))
hsep = 2
vsep = 1
maxw = [-1]*3
for j in range(3):
maxw[j] = max([ m[j][i].width() for i in range(2) ])
D = None
for i in range(2):
D_row = None
for j in range(3):
s = m[j][i]
wdelta = maxw[j] - s.width()
wleft = wdelta //2
wright = wdelta - wleft
s = prettyForm(*s.right(' '*wright))
s = prettyForm(*s.left(' '*wleft))
if D_row is None:
D_row = s
continue
D_row = prettyForm(*D_row.right(' '*hsep))
D_row = prettyForm(*D_row.right(s))
if D is None:
D = D_row
continue
for _ in range(vsep):
D = prettyForm(*D.below(' '))
D = prettyForm(*D.below(D_row))
D = prettyForm(*D.parens())
return D
def _latex(self, printer, *args):
label = map(printer._print, (self.j1, self.j2, self.j3,
self.m1, self.m2, self.m3))
return r'\left(\begin{array}{ccc} %s & %s & %s \\ %s & %s & %s \end{array}\right)' % \
tuple(label)
def doit(self, **hints):
if self.is_symbolic:
raise ValueError("Coefficients must be numerical")
return wigner_3j(self.j1, self.j2, self.j3, self.m1, self.m2, self.m3)
class CG(Wigner3j):
r"""Class for Clebsch-Gordan coefficient.
Explanation
===========
Clebsch-Gordan coefficients describe the angular momentum coupling between
two systems. The coefficients give the expansion of a coupled total angular
momentum state and an uncoupled tensor product state. The Clebsch-Gordan
coefficients are defined as [1]_:
.. math ::
C^{j_3,m_3}_{j_1,m_1,j_2,m_2} = \left\langle j_1,m_1;j_2,m_2 | j_3,m_3\right\rangle
Parameters
==========
j1, m1, j2, m2 : Number, Symbol
Angular momenta of states 1 and 2.
j3, m3: Number, Symbol
Total angular momentum of the coupled system.
Examples
========
Define a Clebsch-Gordan coefficient and evaluate its value
>>> from sympy.physics.quantum.cg import CG
>>> from sympy import S
>>> cg = CG(S(3)/2, S(3)/2, S(1)/2, -S(1)/2, 1, 1)
>>> cg
CG(3/2, 3/2, 1/2, -1/2, 1, 1)
>>> cg.doit()
sqrt(3)/2
>>> CG(j1=S(1)/2, m1=-S(1)/2, j2=S(1)/2, m2=+S(1)/2, j3=1, m3=0).doit()
sqrt(2)/2
Compare [2]_.
See Also
========
Wigner3j: Wigner-3j symbols
References
==========
.. [1] Varshalovich, D A, Quantum Theory of Angular Momentum. 1988.
.. [2] `Clebsch-Gordan Coefficients, Spherical Harmonics, and d Functions
<https://pdg.lbl.gov/2020/reviews/rpp2020-rev-clebsch-gordan-coefs.pdf>`_
in P.A. Zyla *et al.* (Particle Data Group), Prog. Theor. Exp. Phys.
2020, 083C01 (2020).
"""
precedence = PRECEDENCE["Pow"] - 1
def doit(self, **hints):
if self.is_symbolic:
raise ValueError("Coefficients must be numerical")
return clebsch_gordan(self.j1, self.j2, self.j3, self.m1, self.m2, self.m3)
def _pretty(self, printer, *args):
bot = printer._print_seq(
(self.j1, self.m1, self.j2, self.m2), delimiter=',')
top = printer._print_seq((self.j3, self.m3), delimiter=',')
pad = max(top.width(), bot.width())
bot = prettyForm(*bot.left(' '))
top = prettyForm(*top.left(' '))
if not pad == bot.width():
bot = prettyForm(*bot.right(' '*(pad - bot.width())))
if not pad == top.width():
top = prettyForm(*top.right(' '*(pad - top.width())))
s = stringPict('C' + ' '*pad)
s = prettyForm(*s.below(bot))
s = prettyForm(*s.above(top))
return s
def _latex(self, printer, *args):
label = map(printer._print, (self.j3, self.m3, self.j1,
self.m1, self.j2, self.m2))
return r'C^{%s,%s}_{%s,%s,%s,%s}' % tuple(label)
class Wigner6j(Expr):
"""Class for the Wigner-6j symbols
See Also
========
Wigner3j: Wigner-3j symbols
"""
def __new__(cls, j1, j2, j12, j3, j, j23):
args = map(sympify, (j1, j2, j12, j3, j, j23))
return Expr.__new__(cls, *args)
@property
def j1(self):
return self.args[0]
@property
def j2(self):
return self.args[1]
@property
def j12(self):
return self.args[2]
@property
def j3(self):
return self.args[3]
@property
def j(self):
return self.args[4]
@property
def j23(self):
return self.args[5]
@property
def is_symbolic(self):
return not all(arg.is_number for arg in self.args)
# This is modified from the _print_Matrix method
def _pretty(self, printer, *args):
m = ((printer._print(self.j1), printer._print(self.j3)),
(printer._print(self.j2), printer._print(self.j)),
(printer._print(self.j12), printer._print(self.j23)))
hsep = 2
vsep = 1
maxw = [-1]*3
for j in range(3):
maxw[j] = max([ m[j][i].width() for i in range(2) ])
D = None
for i in range(2):
D_row = None
for j in range(3):
s = m[j][i]
wdelta = maxw[j] - s.width()
wleft = wdelta //2
wright = wdelta - wleft
s = prettyForm(*s.right(' '*wright))
s = prettyForm(*s.left(' '*wleft))
if D_row is None:
D_row = s
continue
D_row = prettyForm(*D_row.right(' '*hsep))
D_row = prettyForm(*D_row.right(s))
if D is None:
D = D_row
continue
for _ in range(vsep):
D = prettyForm(*D.below(' '))
D = prettyForm(*D.below(D_row))
D = prettyForm(*D.parens(left='{', right='}'))
return D
def _latex(self, printer, *args):
label = map(printer._print, (self.j1, self.j2, self.j12,
self.j3, self.j, self.j23))
return r'\left\{\begin{array}{ccc} %s & %s & %s \\ %s & %s & %s \end{array}\right\}' % \
tuple(label)
def doit(self, **hints):
if self.is_symbolic:
raise ValueError("Coefficients must be numerical")
return wigner_6j(self.j1, self.j2, self.j12, self.j3, self.j, self.j23)
class Wigner9j(Expr):
"""Class for the Wigner-9j symbols
See Also
========
Wigner3j: Wigner-3j symbols
"""
def __new__(cls, j1, j2, j12, j3, j4, j34, j13, j24, j):
args = map(sympify, (j1, j2, j12, j3, j4, j34, j13, j24, j))
return Expr.__new__(cls, *args)
@property
def j1(self):
return self.args[0]
@property
def j2(self):
return self.args[1]
@property
def j12(self):
return self.args[2]
@property
def j3(self):
return self.args[3]
@property
def j4(self):
return self.args[4]
@property
def j34(self):
return self.args[5]
@property
def j13(self):
return self.args[6]
@property
def j24(self):
return self.args[7]
@property
def j(self):
return self.args[8]
@property
def is_symbolic(self):
return not all(arg.is_number for arg in self.args)
# This is modified from the _print_Matrix method
def _pretty(self, printer, *args):
m = (
(printer._print(
self.j1), printer._print(self.j3), printer._print(self.j13)),
(printer._print(
self.j2), printer._print(self.j4), printer._print(self.j24)),
(printer._print(self.j12), printer._print(self.j34), printer._print(self.j)))
hsep = 2
vsep = 1
maxw = [-1]*3
for j in range(3):
maxw[j] = max([ m[j][i].width() for i in range(3) ])
D = None
for i in range(3):
D_row = None
for j in range(3):
s = m[j][i]
wdelta = maxw[j] - s.width()
wleft = wdelta //2
wright = wdelta - wleft
s = prettyForm(*s.right(' '*wright))
s = prettyForm(*s.left(' '*wleft))
if D_row is None:
D_row = s
continue
D_row = prettyForm(*D_row.right(' '*hsep))
D_row = prettyForm(*D_row.right(s))
if D is None:
D = D_row
continue
for _ in range(vsep):
D = prettyForm(*D.below(' '))
D = prettyForm(*D.below(D_row))
D = prettyForm(*D.parens(left='{', right='}'))
return D
def _latex(self, printer, *args):
label = map(printer._print, (self.j1, self.j2, self.j12, self.j3,
self.j4, self.j34, self.j13, self.j24, self.j))
return r'\left\{\begin{array}{ccc} %s & %s & %s \\ %s & %s & %s \\ %s & %s & %s \end{array}\right\}' % \
tuple(label)
def doit(self, **hints):
if self.is_symbolic:
raise ValueError("Coefficients must be numerical")
return wigner_9j(self.j1, self.j2, self.j12, self.j3, self.j4, self.j34, self.j13, self.j24, self.j)
def cg_simp(e):
"""Simplify and combine CG coefficients.
Explanation
===========
This function uses various symmetry and properties of sums and
products of Clebsch-Gordan coefficients to simplify statements
involving these terms [1]_.
Examples
========
Simplify the sum over CG(a,alpha,0,0,a,alpha) for all alpha to
2*a+1
>>> from sympy.physics.quantum.cg import CG, cg_simp
>>> a = CG(1,1,0,0,1,1)
>>> b = CG(1,0,0,0,1,0)
>>> c = CG(1,-1,0,0,1,-1)
>>> cg_simp(a+b+c)
3
See Also
========
CG: Clebsh-Gordan coefficients
References
==========
.. [1] Varshalovich, D A, Quantum Theory of Angular Momentum. 1988.
"""
if isinstance(e, Add):
return _cg_simp_add(e)
elif isinstance(e, Sum):
return _cg_simp_sum(e)
elif isinstance(e, Mul):
return Mul(*[cg_simp(arg) for arg in e.args])
elif isinstance(e, Pow):
return Pow(cg_simp(e.base), e.exp)
else:
return e
def _cg_simp_add(e):
#TODO: Improve simplification method
"""Takes a sum of terms involving Clebsch-Gordan coefficients and
simplifies the terms.
Explanation
===========
First, we create two lists, cg_part, which is all the terms involving CG
coefficients, and other_part, which is all other terms. The cg_part list
is then passed to the simplification methods, which return the new cg_part
and any additional terms that are added to other_part
"""
cg_part = []
other_part = []
e = expand(e)
for arg in e.args:
if arg.has(CG):
if isinstance(arg, Sum):
other_part.append(_cg_simp_sum(arg))
elif isinstance(arg, Mul):
terms = 1
for term in arg.args:
if isinstance(term, Sum):
terms *= _cg_simp_sum(term)
else:
terms *= term
if terms.has(CG):
cg_part.append(terms)
else:
other_part.append(terms)
else:
cg_part.append(arg)
else:
other_part.append(arg)
cg_part, other = _check_varsh_871_1(cg_part)
other_part.append(other)
cg_part, other = _check_varsh_871_2(cg_part)
other_part.append(other)
cg_part, other = _check_varsh_872_9(cg_part)
other_part.append(other)
return Add(*cg_part) + Add(*other_part)
def _check_varsh_871_1(term_list):
# Sum( CG(a,alpha,b,0,a,alpha), (alpha, -a, a)) == KroneckerDelta(b,0)
a, alpha, b, lt = map(Wild, ('a', 'alpha', 'b', 'lt'))
expr = lt*CG(a, alpha, b, 0, a, alpha)
simp = (2*a + 1)*KroneckerDelta(b, 0)
sign = lt/abs(lt)
build_expr = 2*a + 1
index_expr = a + alpha
return _check_cg_simp(expr, simp, sign, lt, term_list, (a, alpha, b, lt), (a, b), build_expr, index_expr)
def _check_varsh_871_2(term_list):
# Sum((-1)**(a-alpha)*CG(a,alpha,a,-alpha,c,0),(alpha,-a,a))
a, alpha, c, lt = map(Wild, ('a', 'alpha', 'c', 'lt'))
expr = lt*CG(a, alpha, a, -alpha, c, 0)
simp = sqrt(2*a + 1)*KroneckerDelta(c, 0)
sign = (-1)**(a - alpha)*lt/abs(lt)
build_expr = 2*a + 1
index_expr = a + alpha
return _check_cg_simp(expr, simp, sign, lt, term_list, (a, alpha, c, lt), (a, c), build_expr, index_expr)
def _check_varsh_872_9(term_list):
# Sum( CG(a,alpha,b,beta,c,gamma)*CG(a,alpha',b,beta',c,gamma), (gamma, -c, c), (c, abs(a-b), a+b))
a, alpha, alphap, b, beta, betap, c, gamma, lt = map(Wild, (
'a', 'alpha', 'alphap', 'b', 'beta', 'betap', 'c', 'gamma', 'lt'))
# Case alpha==alphap, beta==betap
# For numerical alpha,beta
expr = lt*CG(a, alpha, b, beta, c, gamma)**2
simp = S.One
sign = lt/abs(lt)
x = abs(a - b)
y = abs(alpha + beta)
build_expr = a + b + 1 - Piecewise((x, x > y), (0, Eq(x, y)), (y, y > x))
index_expr = a + b - c
term_list, other1 = _check_cg_simp(expr, simp, sign, lt, term_list, (a, alpha, b, beta, c, gamma, lt), (a, alpha, b, beta), build_expr, index_expr)
# For symbolic alpha,beta
x = abs(a - b)
y = a + b
build_expr = (y + 1 - x)*(x + y + 1)
index_expr = (c - x)*(x + c) + c + gamma
term_list, other2 = _check_cg_simp(expr, simp, sign, lt, term_list, (a, alpha, b, beta, c, gamma, lt), (a, alpha, b, beta), build_expr, index_expr)
# Case alpha!=alphap or beta!=betap
# Note: this only works with leading term of 1, pattern matching is unable to match when there is a Wild leading term
# For numerical alpha,alphap,beta,betap
expr = CG(a, alpha, b, beta, c, gamma)*CG(a, alphap, b, betap, c, gamma)
simp = KroneckerDelta(alpha, alphap)*KroneckerDelta(beta, betap)
sign = S.One
x = abs(a - b)
y = abs(alpha + beta)
build_expr = a + b + 1 - Piecewise((x, x > y), (0, Eq(x, y)), (y, y > x))
index_expr = a + b - c
term_list, other3 = _check_cg_simp(expr, simp, sign, S.One, term_list, (a, alpha, alphap, b, beta, betap, c, gamma), (a, alpha, alphap, b, beta, betap), build_expr, index_expr)
# For symbolic alpha,alphap,beta,betap
x = abs(a - b)
y = a + b
build_expr = (y + 1 - x)*(x + y + 1)
index_expr = (c - x)*(x + c) + c + gamma
term_list, other4 = _check_cg_simp(expr, simp, sign, S.One, term_list, (a, alpha, alphap, b, beta, betap, c, gamma), (a, alpha, alphap, b, beta, betap), build_expr, index_expr)
return term_list, other1 + other2 + other4
def _check_cg_simp(expr, simp, sign, lt, term_list, variables, dep_variables, build_index_expr, index_expr):
""" Checks for simplifications that can be made, returning a tuple of the
simplified list of terms and any terms generated by simplification.
Parameters
==========
expr: expression
The expression with Wild terms that will be matched to the terms in
the sum
simp: expression
The expression with Wild terms that is substituted in place of the CG
terms in the case of simplification
sign: expression
The expression with Wild terms denoting the sign that is on expr that
must match
lt: expression
The expression with Wild terms that gives the leading term of the
matched expr
term_list: list
A list of all of the terms is the sum to be simplified
variables: list
A list of all the variables that appears in expr
dep_variables: list
A list of the variables that must match for all the terms in the sum,
i.e. the dependent variables
build_index_expr: expression
Expression with Wild terms giving the number of elements in cg_index
index_expr: expression
Expression with Wild terms giving the index terms have when storing
them to cg_index
"""
other_part = 0
i = 0
while i < len(term_list):
sub_1 = _check_cg(term_list[i], expr, len(variables))
if sub_1 is None:
i += 1
continue
if not build_index_expr.subs(sub_1).is_number:
i += 1
continue
sub_dep = [(x, sub_1[x]) for x in dep_variables]
cg_index = [None]*build_index_expr.subs(sub_1)
for j in range(i, len(term_list)):
sub_2 = _check_cg(term_list[j], expr.subs(sub_dep), len(variables) - len(dep_variables), sign=(sign.subs(sub_1), sign.subs(sub_dep)))
if sub_2 is None:
continue
if not index_expr.subs(sub_dep).subs(sub_2).is_number:
continue
cg_index[index_expr.subs(sub_dep).subs(sub_2)] = j, expr.subs(lt, 1).subs(sub_dep).subs(sub_2), lt.subs(sub_2), sign.subs(sub_dep).subs(sub_2)
if not any(i is None for i in cg_index):
min_lt = min(*[ abs(term[2]) for term in cg_index ])
indices = [ term[0] for term in cg_index]
indices.sort()
indices.reverse()
[ term_list.pop(j) for j in indices ]
for term in cg_index:
if abs(term[2]) > min_lt:
term_list.append( (term[2] - min_lt*term[3])*term[1] )
other_part += min_lt*(sign*simp).subs(sub_1)
else:
i += 1
return term_list, other_part
def _check_cg(cg_term, expr, length, sign=None):
"""Checks whether a term matches the given expression"""
# TODO: Check for symmetries
matches = cg_term.match(expr)
if matches is None:
return
if sign is not None:
if not isinstance(sign, tuple):
raise TypeError('sign must be a tuple')
if not sign[0] == (sign[1]).subs(matches):
return
if len(matches) == length:
return matches
def _cg_simp_sum(e):
e = _check_varsh_sum_871_1(e)
e = _check_varsh_sum_871_2(e)
e = _check_varsh_sum_872_4(e)
return e
def _check_varsh_sum_871_1(e):
a = Wild('a')
alpha = symbols('alpha')
b = Wild('b')
match = e.match(Sum(CG(a, alpha, b, 0, a, alpha), (alpha, -a, a)))
if match is not None and len(match) == 2:
return ((2*a + 1)*KroneckerDelta(b, 0)).subs(match)
return e
def _check_varsh_sum_871_2(e):
a = Wild('a')
alpha = symbols('alpha')
c = Wild('c')
match = e.match(
Sum((-1)**(a - alpha)*CG(a, alpha, a, -alpha, c, 0), (alpha, -a, a)))
if match is not None and len(match) == 2:
return (sqrt(2*a + 1)*KroneckerDelta(c, 0)).subs(match)
return e
def _check_varsh_sum_872_4(e):
alpha = symbols('alpha')
beta = symbols('beta')
a = Wild('a')
b = Wild('b')
c = Wild('c')
cp = Wild('cp')
gamma = Wild('gamma')
gammap = Wild('gammap')
cg1 = CG(a, alpha, b, beta, c, gamma)
cg2 = CG(a, alpha, b, beta, cp, gammap)
match1 = e.match(Sum(cg1*cg2, (alpha, -a, a), (beta, -b, b)))
if match1 is not None and len(match1) == 6:
return (KroneckerDelta(c, cp)*KroneckerDelta(gamma, gammap)).subs(match1)
match2 = e.match(Sum(cg1**2, (alpha, -a, a), (beta, -b, b)))
if match2 is not None and len(match2) == 4:
return S.One
return e
def _cg_list(term):
if isinstance(term, CG):
return (term,), 1, 1
cg = []
coeff = 1
if not isinstance(term, (Mul, Pow)):
raise NotImplementedError('term must be CG, Add, Mul or Pow')
if isinstance(term, Pow) and term.exp.is_number:
if term.exp.is_number:
[ cg.append(term.base) for _ in range(term.exp) ]
else:
return (term,), 1, 1
if isinstance(term, Mul):
for arg in term.args:
if isinstance(arg, CG):
cg.append(arg)
else:
coeff *= arg
return cg, coeff, coeff/abs(coeff)
|
aab8daf76bc5ec151e4b21ce2ca557f3e5ca70f193ed0690316aea5978d136eb | """Hilbert spaces for quantum mechanics.
Authors:
* Brian Granger
* Matt Curry
"""
from functools import reduce
from sympy.core.basic import Basic
from sympy.core.singleton import S
from sympy.core.sympify import sympify
from sympy.sets.sets import Interval
from sympy.printing.pretty.stringpict import prettyForm
from sympy.physics.quantum.qexpr import QuantumError
__all__ = [
'HilbertSpaceError',
'HilbertSpace',
'TensorProductHilbertSpace',
'TensorPowerHilbertSpace',
'DirectSumHilbertSpace',
'ComplexSpace',
'L2',
'FockSpace'
]
#-----------------------------------------------------------------------------
# Main objects
#-----------------------------------------------------------------------------
class HilbertSpaceError(QuantumError):
pass
#-----------------------------------------------------------------------------
# Main objects
#-----------------------------------------------------------------------------
class HilbertSpace(Basic):
"""An abstract Hilbert space for quantum mechanics.
In short, a Hilbert space is an abstract vector space that is complete
with inner products defined [1]_.
Examples
========
>>> from sympy.physics.quantum.hilbert import HilbertSpace
>>> hs = HilbertSpace()
>>> hs
H
References
==========
.. [1] https://en.wikipedia.org/wiki/Hilbert_space
"""
def __new__(cls):
obj = Basic.__new__(cls)
return obj
@property
def dimension(self):
"""Return the Hilbert dimension of the space."""
raise NotImplementedError('This Hilbert space has no dimension.')
def __add__(self, other):
return DirectSumHilbertSpace(self, other)
def __radd__(self, other):
return DirectSumHilbertSpace(other, self)
def __mul__(self, other):
return TensorProductHilbertSpace(self, other)
def __rmul__(self, other):
return TensorProductHilbertSpace(other, self)
def __pow__(self, other, mod=None):
if mod is not None:
raise ValueError('The third argument to __pow__ is not supported \
for Hilbert spaces.')
return TensorPowerHilbertSpace(self, other)
def __contains__(self, other):
"""Is the operator or state in this Hilbert space.
This is checked by comparing the classes of the Hilbert spaces, not
the instances. This is to allow Hilbert Spaces with symbolic
dimensions.
"""
if other.hilbert_space.__class__ == self.__class__:
return True
else:
return False
def _sympystr(self, printer, *args):
return 'H'
def _pretty(self, printer, *args):
ustr = '\N{LATIN CAPITAL LETTER H}'
return prettyForm(ustr)
def _latex(self, printer, *args):
return r'\mathcal{H}'
class ComplexSpace(HilbertSpace):
"""Finite dimensional Hilbert space of complex vectors.
The elements of this Hilbert space are n-dimensional complex valued
vectors with the usual inner product that takes the complex conjugate
of the vector on the right.
A classic example of this type of Hilbert space is spin-1/2, which is
``ComplexSpace(2)``. Generalizing to spin-s, the space is
``ComplexSpace(2*s+1)``. Quantum computing with N qubits is done with the
direct product space ``ComplexSpace(2)**N``.
Examples
========
>>> from sympy import symbols
>>> from sympy.physics.quantum.hilbert import ComplexSpace
>>> c1 = ComplexSpace(2)
>>> c1
C(2)
>>> c1.dimension
2
>>> n = symbols('n')
>>> c2 = ComplexSpace(n)
>>> c2
C(n)
>>> c2.dimension
n
"""
def __new__(cls, dimension):
dimension = sympify(dimension)
r = cls.eval(dimension)
if isinstance(r, Basic):
return r
obj = Basic.__new__(cls, dimension)
return obj
@classmethod
def eval(cls, dimension):
if len(dimension.atoms()) == 1:
if not (dimension.is_Integer and dimension > 0 or dimension is S.Infinity
or dimension.is_Symbol):
raise TypeError('The dimension of a ComplexSpace can only'
'be a positive integer, oo, or a Symbol: %r'
% dimension)
else:
for dim in dimension.atoms():
if not (dim.is_Integer or dim is S.Infinity or dim.is_Symbol):
raise TypeError('The dimension of a ComplexSpace can only'
' contain integers, oo, or a Symbol: %r'
% dim)
@property
def dimension(self):
return self.args[0]
def _sympyrepr(self, printer, *args):
return "%s(%s)" % (self.__class__.__name__,
printer._print(self.dimension, *args))
def _sympystr(self, printer, *args):
return "C(%s)" % printer._print(self.dimension, *args)
def _pretty(self, printer, *args):
ustr = '\N{LATIN CAPITAL LETTER C}'
pform_exp = printer._print(self.dimension, *args)
pform_base = prettyForm(ustr)
return pform_base**pform_exp
def _latex(self, printer, *args):
return r'\mathcal{C}^{%s}' % printer._print(self.dimension, *args)
class L2(HilbertSpace):
"""The Hilbert space of square integrable functions on an interval.
An L2 object takes in a single SymPy Interval argument which represents
the interval its functions (vectors) are defined on.
Examples
========
>>> from sympy import Interval, oo
>>> from sympy.physics.quantum.hilbert import L2
>>> hs = L2(Interval(0,oo))
>>> hs
L2(Interval(0, oo))
>>> hs.dimension
oo
>>> hs.interval
Interval(0, oo)
"""
def __new__(cls, interval):
if not isinstance(interval, Interval):
raise TypeError('L2 interval must be an Interval instance: %r'
% interval)
obj = Basic.__new__(cls, interval)
return obj
@property
def dimension(self):
return S.Infinity
@property
def interval(self):
return self.args[0]
def _sympyrepr(self, printer, *args):
return "L2(%s)" % printer._print(self.interval, *args)
def _sympystr(self, printer, *args):
return "L2(%s)" % printer._print(self.interval, *args)
def _pretty(self, printer, *args):
pform_exp = prettyForm('2')
pform_base = prettyForm('L')
return pform_base**pform_exp
def _latex(self, printer, *args):
interval = printer._print(self.interval, *args)
return r'{\mathcal{L}^2}\left( %s \right)' % interval
class FockSpace(HilbertSpace):
"""The Hilbert space for second quantization.
Technically, this Hilbert space is a infinite direct sum of direct
products of single particle Hilbert spaces [1]_. This is a mess, so we have
a class to represent it directly.
Examples
========
>>> from sympy.physics.quantum.hilbert import FockSpace
>>> hs = FockSpace()
>>> hs
F
>>> hs.dimension
oo
References
==========
.. [1] https://en.wikipedia.org/wiki/Fock_space
"""
def __new__(cls):
obj = Basic.__new__(cls)
return obj
@property
def dimension(self):
return S.Infinity
def _sympyrepr(self, printer, *args):
return "FockSpace()"
def _sympystr(self, printer, *args):
return "F"
def _pretty(self, printer, *args):
ustr = '\N{LATIN CAPITAL LETTER F}'
return prettyForm(ustr)
def _latex(self, printer, *args):
return r'\mathcal{F}'
class TensorProductHilbertSpace(HilbertSpace):
"""A tensor product of Hilbert spaces [1]_.
The tensor product between Hilbert spaces is represented by the
operator ``*`` Products of the same Hilbert space will be combined into
tensor powers.
A ``TensorProductHilbertSpace`` object takes in an arbitrary number of
``HilbertSpace`` objects as its arguments. In addition, multiplication of
``HilbertSpace`` objects will automatically return this tensor product
object.
Examples
========
>>> from sympy.physics.quantum.hilbert import ComplexSpace, FockSpace
>>> from sympy import symbols
>>> c = ComplexSpace(2)
>>> f = FockSpace()
>>> hs = c*f
>>> hs
C(2)*F
>>> hs.dimension
oo
>>> hs.spaces
(C(2), F)
>>> c1 = ComplexSpace(2)
>>> n = symbols('n')
>>> c2 = ComplexSpace(n)
>>> hs = c1*c2
>>> hs
C(2)*C(n)
>>> hs.dimension
2*n
References
==========
.. [1] https://en.wikipedia.org/wiki/Hilbert_space#Tensor_products
"""
def __new__(cls, *args):
r = cls.eval(args)
if isinstance(r, Basic):
return r
obj = Basic.__new__(cls, *args)
return obj
@classmethod
def eval(cls, args):
"""Evaluates the direct product."""
new_args = []
recall = False
#flatten arguments
for arg in args:
if isinstance(arg, TensorProductHilbertSpace):
new_args.extend(arg.args)
recall = True
elif isinstance(arg, (HilbertSpace, TensorPowerHilbertSpace)):
new_args.append(arg)
else:
raise TypeError('Hilbert spaces can only be multiplied by \
other Hilbert spaces: %r' % arg)
#combine like arguments into direct powers
comb_args = []
prev_arg = None
for new_arg in new_args:
if prev_arg is not None:
if isinstance(new_arg, TensorPowerHilbertSpace) and \
isinstance(prev_arg, TensorPowerHilbertSpace) and \
new_arg.base == prev_arg.base:
prev_arg = new_arg.base**(new_arg.exp + prev_arg.exp)
elif isinstance(new_arg, TensorPowerHilbertSpace) and \
new_arg.base == prev_arg:
prev_arg = prev_arg**(new_arg.exp + 1)
elif isinstance(prev_arg, TensorPowerHilbertSpace) and \
new_arg == prev_arg.base:
prev_arg = new_arg**(prev_arg.exp + 1)
elif new_arg == prev_arg:
prev_arg = new_arg**2
else:
comb_args.append(prev_arg)
prev_arg = new_arg
elif prev_arg is None:
prev_arg = new_arg
comb_args.append(prev_arg)
if recall:
return TensorProductHilbertSpace(*comb_args)
elif len(comb_args) == 1:
return TensorPowerHilbertSpace(comb_args[0].base, comb_args[0].exp)
else:
return None
@property
def dimension(self):
arg_list = [arg.dimension for arg in self.args]
if S.Infinity in arg_list:
return S.Infinity
else:
return reduce(lambda x, y: x*y, arg_list)
@property
def spaces(self):
"""A tuple of the Hilbert spaces in this tensor product."""
return self.args
def _spaces_printer(self, printer, *args):
spaces_strs = []
for arg in self.args:
s = printer._print(arg, *args)
if isinstance(arg, DirectSumHilbertSpace):
s = '(%s)' % s
spaces_strs.append(s)
return spaces_strs
def _sympyrepr(self, printer, *args):
spaces_reprs = self._spaces_printer(printer, *args)
return "TensorProductHilbertSpace(%s)" % ','.join(spaces_reprs)
def _sympystr(self, printer, *args):
spaces_strs = self._spaces_printer(printer, *args)
return '*'.join(spaces_strs)
def _pretty(self, printer, *args):
length = len(self.args)
pform = printer._print('', *args)
for i in range(length):
next_pform = printer._print(self.args[i], *args)
if isinstance(self.args[i], (DirectSumHilbertSpace,
TensorProductHilbertSpace)):
next_pform = prettyForm(
*next_pform.parens(left='(', right=')')
)
pform = prettyForm(*pform.right(next_pform))
if i != length - 1:
if printer._use_unicode:
pform = prettyForm(*pform.right(' ' + '\N{N-ARY CIRCLED TIMES OPERATOR}' + ' '))
else:
pform = prettyForm(*pform.right(' x '))
return pform
def _latex(self, printer, *args):
length = len(self.args)
s = ''
for i in range(length):
arg_s = printer._print(self.args[i], *args)
if isinstance(self.args[i], (DirectSumHilbertSpace,
TensorProductHilbertSpace)):
arg_s = r'\left(%s\right)' % arg_s
s = s + arg_s
if i != length - 1:
s = s + r'\otimes '
return s
class DirectSumHilbertSpace(HilbertSpace):
"""A direct sum of Hilbert spaces [1]_.
This class uses the ``+`` operator to represent direct sums between
different Hilbert spaces.
A ``DirectSumHilbertSpace`` object takes in an arbitrary number of
``HilbertSpace`` objects as its arguments. Also, addition of
``HilbertSpace`` objects will automatically return a direct sum object.
Examples
========
>>> from sympy.physics.quantum.hilbert import ComplexSpace, FockSpace
>>> c = ComplexSpace(2)
>>> f = FockSpace()
>>> hs = c+f
>>> hs
C(2)+F
>>> hs.dimension
oo
>>> list(hs.spaces)
[C(2), F]
References
==========
.. [1] https://en.wikipedia.org/wiki/Hilbert_space#Direct_sums
"""
def __new__(cls, *args):
r = cls.eval(args)
if isinstance(r, Basic):
return r
obj = Basic.__new__(cls, *args)
return obj
@classmethod
def eval(cls, args):
"""Evaluates the direct product."""
new_args = []
recall = False
#flatten arguments
for arg in args:
if isinstance(arg, DirectSumHilbertSpace):
new_args.extend(arg.args)
recall = True
elif isinstance(arg, HilbertSpace):
new_args.append(arg)
else:
raise TypeError('Hilbert spaces can only be summed with other \
Hilbert spaces: %r' % arg)
if recall:
return DirectSumHilbertSpace(*new_args)
else:
return None
@property
def dimension(self):
arg_list = [arg.dimension for arg in self.args]
if S.Infinity in arg_list:
return S.Infinity
else:
return reduce(lambda x, y: x + y, arg_list)
@property
def spaces(self):
"""A tuple of the Hilbert spaces in this direct sum."""
return self.args
def _sympyrepr(self, printer, *args):
spaces_reprs = [printer._print(arg, *args) for arg in self.args]
return "DirectSumHilbertSpace(%s)" % ','.join(spaces_reprs)
def _sympystr(self, printer, *args):
spaces_strs = [printer._print(arg, *args) for arg in self.args]
return '+'.join(spaces_strs)
def _pretty(self, printer, *args):
length = len(self.args)
pform = printer._print('', *args)
for i in range(length):
next_pform = printer._print(self.args[i], *args)
if isinstance(self.args[i], (DirectSumHilbertSpace,
TensorProductHilbertSpace)):
next_pform = prettyForm(
*next_pform.parens(left='(', right=')')
)
pform = prettyForm(*pform.right(next_pform))
if i != length - 1:
if printer._use_unicode:
pform = prettyForm(*pform.right(' \N{CIRCLED PLUS} '))
else:
pform = prettyForm(*pform.right(' + '))
return pform
def _latex(self, printer, *args):
length = len(self.args)
s = ''
for i in range(length):
arg_s = printer._print(self.args[i], *args)
if isinstance(self.args[i], (DirectSumHilbertSpace,
TensorProductHilbertSpace)):
arg_s = r'\left(%s\right)' % arg_s
s = s + arg_s
if i != length - 1:
s = s + r'\oplus '
return s
class TensorPowerHilbertSpace(HilbertSpace):
"""An exponentiated Hilbert space [1]_.
Tensor powers (repeated tensor products) are represented by the
operator ``**`` Identical Hilbert spaces that are multiplied together
will be automatically combined into a single tensor power object.
Any Hilbert space, product, or sum may be raised to a tensor power. The
``TensorPowerHilbertSpace`` takes two arguments: the Hilbert space; and the
tensor power (number).
Examples
========
>>> from sympy.physics.quantum.hilbert import ComplexSpace, FockSpace
>>> from sympy import symbols
>>> n = symbols('n')
>>> c = ComplexSpace(2)
>>> hs = c**n
>>> hs
C(2)**n
>>> hs.dimension
2**n
>>> c = ComplexSpace(2)
>>> c*c
C(2)**2
>>> f = FockSpace()
>>> c*f*f
C(2)*F**2
References
==========
.. [1] https://en.wikipedia.org/wiki/Hilbert_space#Tensor_products
"""
def __new__(cls, *args):
r = cls.eval(args)
if isinstance(r, Basic):
return r
return Basic.__new__(cls, *r)
@classmethod
def eval(cls, args):
new_args = args[0], sympify(args[1])
exp = new_args[1]
#simplify hs**1 -> hs
if exp is S.One:
return args[0]
#simplify hs**0 -> 1
if exp is S.Zero:
return S.One
#check (and allow) for hs**(x+42+y...) case
if len(exp.atoms()) == 1:
if not (exp.is_Integer and exp >= 0 or exp.is_Symbol):
raise ValueError('Hilbert spaces can only be raised to \
positive integers or Symbols: %r' % exp)
else:
for power in exp.atoms():
if not (power.is_Integer or power.is_Symbol):
raise ValueError('Tensor powers can only contain integers \
or Symbols: %r' % power)
return new_args
@property
def base(self):
return self.args[0]
@property
def exp(self):
return self.args[1]
@property
def dimension(self):
if self.base.dimension is S.Infinity:
return S.Infinity
else:
return self.base.dimension**self.exp
def _sympyrepr(self, printer, *args):
return "TensorPowerHilbertSpace(%s,%s)" % (printer._print(self.base,
*args), printer._print(self.exp, *args))
def _sympystr(self, printer, *args):
return "%s**%s" % (printer._print(self.base, *args),
printer._print(self.exp, *args))
def _pretty(self, printer, *args):
pform_exp = printer._print(self.exp, *args)
if printer._use_unicode:
pform_exp = prettyForm(*pform_exp.left(prettyForm('\N{N-ARY CIRCLED TIMES OPERATOR}')))
else:
pform_exp = prettyForm(*pform_exp.left(prettyForm('x')))
pform_base = printer._print(self.base, *args)
return pform_base**pform_exp
def _latex(self, printer, *args):
base = printer._print(self.base, *args)
exp = printer._print(self.exp, *args)
return r'{%s}^{\otimes %s}' % (base, exp)
|
5d013ef411619ee62430a330b0e9672187779aa13d2889cf435ace6777fbfb5f | """Logic for applying operators to states.
Todo:
* Sometimes the final result needs to be expanded, we should do this by hand.
"""
from sympy.core.add import Add
from sympy.core.mul import Mul
from sympy.core.power import Pow
from sympy.core.singleton import S
from sympy.core.sympify import sympify
from sympy.physics.quantum.anticommutator import AntiCommutator
from sympy.physics.quantum.commutator import Commutator
from sympy.physics.quantum.dagger import Dagger
from sympy.physics.quantum.innerproduct import InnerProduct
from sympy.physics.quantum.operator import OuterProduct, Operator
from sympy.physics.quantum.state import State, KetBase, BraBase, Wavefunction
from sympy.physics.quantum.tensorproduct import TensorProduct
__all__ = [
'qapply'
]
#-----------------------------------------------------------------------------
# Main code
#-----------------------------------------------------------------------------
def qapply(e, **options):
"""Apply operators to states in a quantum expression.
Parameters
==========
e : Expr
The expression containing operators and states. This expression tree
will be walked to find operators acting on states symbolically.
options : dict
A dict of key/value pairs that determine how the operator actions
are carried out.
The following options are valid:
* ``dagger``: try to apply Dagger operators to the left
(default: False).
* ``ip_doit``: call ``.doit()`` in inner products when they are
encountered (default: True).
Returns
=======
e : Expr
The original expression, but with the operators applied to states.
Examples
========
>>> from sympy.physics.quantum import qapply, Ket, Bra
>>> b = Bra('b')
>>> k = Ket('k')
>>> A = k * b
>>> A
|k><b|
>>> qapply(A * b.dual / (b * b.dual))
|k>
>>> qapply(k.dual * A / (k.dual * k), dagger=True)
<b|
>>> qapply(k.dual * A / (k.dual * k))
<k|*|k><b|/<k|k>
"""
from sympy.physics.quantum.density import Density
dagger = options.get('dagger', False)
if e == 0:
return S.Zero
# This may be a bit aggressive but ensures that everything gets expanded
# to its simplest form before trying to apply operators. This includes
# things like (A+B+C)*|a> and A*(|a>+|b>) and all Commutators and
# TensorProducts. The only problem with this is that if we can't apply
# all the Operators, we have just expanded everything.
# TODO: don't expand the scalars in front of each Mul.
e = e.expand(commutator=True, tensorproduct=True)
# If we just have a raw ket, return it.
if isinstance(e, KetBase):
return e
# We have an Add(a, b, c, ...) and compute
# Add(qapply(a), qapply(b), ...)
elif isinstance(e, Add):
result = 0
for arg in e.args:
result += qapply(arg, **options)
return result.expand()
# For a Density operator call qapply on its state
elif isinstance(e, Density):
new_args = [(qapply(state, **options), prob) for (state,
prob) in e.args]
return Density(*new_args)
# For a raw TensorProduct, call qapply on its args.
elif isinstance(e, TensorProduct):
return TensorProduct(*[qapply(t, **options) for t in e.args])
# For a Pow, call qapply on its base.
elif isinstance(e, Pow):
return qapply(e.base, **options)**e.exp
# We have a Mul where there might be actual operators to apply to kets.
elif isinstance(e, Mul):
c_part, nc_part = e.args_cnc()
c_mul = Mul(*c_part)
nc_mul = Mul(*nc_part)
if isinstance(nc_mul, Mul):
result = c_mul*qapply_Mul(nc_mul, **options)
else:
result = c_mul*qapply(nc_mul, **options)
if result == e and dagger:
return Dagger(qapply_Mul(Dagger(e), **options))
else:
return result
# In all other cases (State, Operator, Pow, Commutator, InnerProduct,
# OuterProduct) we won't ever have operators to apply to kets.
else:
return e
def qapply_Mul(e, **options):
ip_doit = options.get('ip_doit', True)
args = list(e.args)
# If we only have 0 or 1 args, we have nothing to do and return.
if len(args) <= 1 or not isinstance(e, Mul):
return e
rhs = args.pop()
lhs = args.pop()
# Make sure we have two non-commutative objects before proceeding.
if (not isinstance(rhs, Wavefunction) and sympify(rhs).is_commutative) or \
(not isinstance(lhs, Wavefunction) and sympify(lhs).is_commutative):
return e
# For a Pow with an integer exponent, apply one of them and reduce the
# exponent by one.
if isinstance(lhs, Pow) and lhs.exp.is_Integer:
args.append(lhs.base**(lhs.exp - 1))
lhs = lhs.base
# Pull OuterProduct apart
if isinstance(lhs, OuterProduct):
args.append(lhs.ket)
lhs = lhs.bra
# Call .doit() on Commutator/AntiCommutator.
if isinstance(lhs, (Commutator, AntiCommutator)):
comm = lhs.doit()
if isinstance(comm, Add):
return qapply(
e.func(*(args + [comm.args[0], rhs])) +
e.func(*(args + [comm.args[1], rhs])),
**options
)
else:
return qapply(e.func(*args)*comm*rhs, **options)
# Apply tensor products of operators to states
if isinstance(lhs, TensorProduct) and all(isinstance(arg, (Operator, State, Mul, Pow)) or arg == 1 for arg in lhs.args) and \
isinstance(rhs, TensorProduct) and all(isinstance(arg, (Operator, State, Mul, Pow)) or arg == 1 for arg in rhs.args) and \
len(lhs.args) == len(rhs.args):
result = TensorProduct(*[qapply(lhs.args[n]*rhs.args[n], **options) for n in range(len(lhs.args))]).expand(tensorproduct=True)
return qapply_Mul(e.func(*args), **options)*result
# Now try to actually apply the operator and build an inner product.
try:
result = lhs._apply_operator(rhs, **options)
except (NotImplementedError, AttributeError):
try:
result = rhs._apply_operator(lhs, **options)
except (NotImplementedError, AttributeError):
if isinstance(lhs, BraBase) and isinstance(rhs, KetBase):
result = InnerProduct(lhs, rhs)
if ip_doit:
result = result.doit()
else:
result = None
# TODO: I may need to expand before returning the final result.
if result == 0:
return S.Zero
elif result is None:
if len(args) == 0:
# We had two args to begin with so args=[].
return e
else:
return qapply_Mul(e.func(*(args + [lhs])), **options)*rhs
elif isinstance(result, InnerProduct):
return result*qapply_Mul(e.func(*args), **options)
else: # result is a scalar times a Mul, Add or TensorProduct
return qapply(e.func(*args)*result, **options)
|
f5d74911c3b9367d5722e0906ad078ae46cc4075289170618bf141dfe5629a0f | from sympy.utilities import dict_merge
from sympy.utilities.iterables import iterable
from sympy.physics.vector import (Dyadic, Vector, ReferenceFrame,
Point, dynamicsymbols)
from sympy.physics.vector.printing import (vprint, vsprint, vpprint, vlatex,
init_vprinting)
from sympy.physics.mechanics.particle import Particle
from sympy.physics.mechanics.rigidbody import RigidBody
from sympy.simplify.simplify import simplify
from sympy.core.backend import (Matrix, sympify, Mul, Derivative, sin, cos,
tan, AppliedUndef, S)
__all__ = ['inertia',
'inertia_of_point_mass',
'linear_momentum',
'angular_momentum',
'kinetic_energy',
'potential_energy',
'Lagrangian',
'mechanics_printing',
'mprint',
'msprint',
'mpprint',
'mlatex',
'msubs',
'find_dynamicsymbols']
# These are functions that we've moved and renamed during extracting the
# basic vector calculus code from the mechanics packages.
mprint = vprint
msprint = vsprint
mpprint = vpprint
mlatex = vlatex
def mechanics_printing(**kwargs):
"""
Initializes time derivative printing for all SymPy objects in
mechanics module.
"""
init_vprinting(**kwargs)
mechanics_printing.__doc__ = init_vprinting.__doc__
def inertia(frame, ixx, iyy, izz, ixy=0, iyz=0, izx=0):
"""Simple way to create inertia Dyadic object.
Explanation
===========
If you do not know what a Dyadic is, just treat this like the inertia
tensor. Then, do the easy thing and define it in a body-fixed frame.
Parameters
==========
frame : ReferenceFrame
The frame the inertia is defined in
ixx : Sympifyable
the xx element in the inertia dyadic
iyy : Sympifyable
the yy element in the inertia dyadic
izz : Sympifyable
the zz element in the inertia dyadic
ixy : Sympifyable
the xy element in the inertia dyadic
iyz : Sympifyable
the yz element in the inertia dyadic
izx : Sympifyable
the zx element in the inertia dyadic
Examples
========
>>> from sympy.physics.mechanics import ReferenceFrame, inertia
>>> N = ReferenceFrame('N')
>>> inertia(N, 1, 2, 3)
(N.x|N.x) + 2*(N.y|N.y) + 3*(N.z|N.z)
"""
if not isinstance(frame, ReferenceFrame):
raise TypeError('Need to define the inertia in a frame')
ixx = sympify(ixx)
ixy = sympify(ixy)
iyy = sympify(iyy)
iyz = sympify(iyz)
izx = sympify(izx)
izz = sympify(izz)
ol = ixx * (frame.x | frame.x)
ol += ixy * (frame.x | frame.y)
ol += izx * (frame.x | frame.z)
ol += ixy * (frame.y | frame.x)
ol += iyy * (frame.y | frame.y)
ol += iyz * (frame.y | frame.z)
ol += izx * (frame.z | frame.x)
ol += iyz * (frame.z | frame.y)
ol += izz * (frame.z | frame.z)
return ol
def inertia_of_point_mass(mass, pos_vec, frame):
"""Inertia dyadic of a point mass relative to point O.
Parameters
==========
mass : Sympifyable
Mass of the point mass
pos_vec : Vector
Position from point O to point mass
frame : ReferenceFrame
Reference frame to express the dyadic in
Examples
========
>>> from sympy import symbols
>>> from sympy.physics.mechanics import ReferenceFrame, inertia_of_point_mass
>>> N = ReferenceFrame('N')
>>> r, m = symbols('r m')
>>> px = r * N.x
>>> inertia_of_point_mass(m, px, N)
m*r**2*(N.y|N.y) + m*r**2*(N.z|N.z)
"""
return mass * (((frame.x | frame.x) + (frame.y | frame.y) +
(frame.z | frame.z)) * (pos_vec & pos_vec) -
(pos_vec | pos_vec))
def linear_momentum(frame, *body):
"""Linear momentum of the system.
Explanation
===========
This function returns the linear momentum of a system of Particle's and/or
RigidBody's. The linear momentum of a system is equal to the vector sum of
the linear momentum of its constituents. Consider a system, S, comprised of
a rigid body, A, and a particle, P. The linear momentum of the system, L,
is equal to the vector sum of the linear momentum of the particle, L1, and
the linear momentum of the rigid body, L2, i.e.
L = L1 + L2
Parameters
==========
frame : ReferenceFrame
The frame in which linear momentum is desired.
body1, body2, body3... : Particle and/or RigidBody
The body (or bodies) whose linear momentum is required.
Examples
========
>>> from sympy.physics.mechanics import Point, Particle, ReferenceFrame
>>> from sympy.physics.mechanics import RigidBody, outer, linear_momentum
>>> N = ReferenceFrame('N')
>>> P = Point('P')
>>> P.set_vel(N, 10 * N.x)
>>> Pa = Particle('Pa', P, 1)
>>> Ac = Point('Ac')
>>> Ac.set_vel(N, 25 * N.y)
>>> I = outer(N.x, N.x)
>>> A = RigidBody('A', Ac, N, 20, (I, Ac))
>>> linear_momentum(N, A, Pa)
10*N.x + 500*N.y
"""
if not isinstance(frame, ReferenceFrame):
raise TypeError('Please specify a valid ReferenceFrame')
else:
linear_momentum_sys = Vector(0)
for e in body:
if isinstance(e, (RigidBody, Particle)):
linear_momentum_sys += e.linear_momentum(frame)
else:
raise TypeError('*body must have only Particle or RigidBody')
return linear_momentum_sys
def angular_momentum(point, frame, *body):
"""Angular momentum of a system.
Explanation
===========
This function returns the angular momentum of a system of Particle's and/or
RigidBody's. The angular momentum of such a system is equal to the vector
sum of the angular momentum of its constituents. Consider a system, S,
comprised of a rigid body, A, and a particle, P. The angular momentum of
the system, H, is equal to the vector sum of the angular momentum of the
particle, H1, and the angular momentum of the rigid body, H2, i.e.
H = H1 + H2
Parameters
==========
point : Point
The point about which angular momentum of the system is desired.
frame : ReferenceFrame
The frame in which angular momentum is desired.
body1, body2, body3... : Particle and/or RigidBody
The body (or bodies) whose angular momentum is required.
Examples
========
>>> from sympy.physics.mechanics import Point, Particle, ReferenceFrame
>>> from sympy.physics.mechanics import RigidBody, outer, angular_momentum
>>> N = ReferenceFrame('N')
>>> O = Point('O')
>>> O.set_vel(N, 0 * N.x)
>>> P = O.locatenew('P', 1 * N.x)
>>> P.set_vel(N, 10 * N.x)
>>> Pa = Particle('Pa', P, 1)
>>> Ac = O.locatenew('Ac', 2 * N.y)
>>> Ac.set_vel(N, 5 * N.y)
>>> a = ReferenceFrame('a')
>>> a.set_ang_vel(N, 10 * N.z)
>>> I = outer(N.z, N.z)
>>> A = RigidBody('A', Ac, a, 20, (I, Ac))
>>> angular_momentum(O, N, Pa, A)
10*N.z
"""
if not isinstance(frame, ReferenceFrame):
raise TypeError('Please enter a valid ReferenceFrame')
if not isinstance(point, Point):
raise TypeError('Please specify a valid Point')
else:
angular_momentum_sys = Vector(0)
for e in body:
if isinstance(e, (RigidBody, Particle)):
angular_momentum_sys += e.angular_momentum(point, frame)
else:
raise TypeError('*body must have only Particle or RigidBody')
return angular_momentum_sys
def kinetic_energy(frame, *body):
"""Kinetic energy of a multibody system.
Explanation
===========
This function returns the kinetic energy of a system of Particle's and/or
RigidBody's. The kinetic energy of such a system is equal to the sum of
the kinetic energies of its constituents. Consider a system, S, comprising
a rigid body, A, and a particle, P. The kinetic energy of the system, T,
is equal to the vector sum of the kinetic energy of the particle, T1, and
the kinetic energy of the rigid body, T2, i.e.
T = T1 + T2
Kinetic energy is a scalar.
Parameters
==========
frame : ReferenceFrame
The frame in which the velocity or angular velocity of the body is
defined.
body1, body2, body3... : Particle and/or RigidBody
The body (or bodies) whose kinetic energy is required.
Examples
========
>>> from sympy.physics.mechanics import Point, Particle, ReferenceFrame
>>> from sympy.physics.mechanics import RigidBody, outer, kinetic_energy
>>> N = ReferenceFrame('N')
>>> O = Point('O')
>>> O.set_vel(N, 0 * N.x)
>>> P = O.locatenew('P', 1 * N.x)
>>> P.set_vel(N, 10 * N.x)
>>> Pa = Particle('Pa', P, 1)
>>> Ac = O.locatenew('Ac', 2 * N.y)
>>> Ac.set_vel(N, 5 * N.y)
>>> a = ReferenceFrame('a')
>>> a.set_ang_vel(N, 10 * N.z)
>>> I = outer(N.z, N.z)
>>> A = RigidBody('A', Ac, a, 20, (I, Ac))
>>> kinetic_energy(N, Pa, A)
350
"""
if not isinstance(frame, ReferenceFrame):
raise TypeError('Please enter a valid ReferenceFrame')
ke_sys = S.Zero
for e in body:
if isinstance(e, (RigidBody, Particle)):
ke_sys += e.kinetic_energy(frame)
else:
raise TypeError('*body must have only Particle or RigidBody')
return ke_sys
def potential_energy(*body):
"""Potential energy of a multibody system.
Explanation
===========
This function returns the potential energy of a system of Particle's and/or
RigidBody's. The potential energy of such a system is equal to the sum of
the potential energy of its constituents. Consider a system, S, comprising
a rigid body, A, and a particle, P. The potential energy of the system, V,
is equal to the vector sum of the potential energy of the particle, V1, and
the potential energy of the rigid body, V2, i.e.
V = V1 + V2
Potential energy is a scalar.
Parameters
==========
body1, body2, body3... : Particle and/or RigidBody
The body (or bodies) whose potential energy is required.
Examples
========
>>> from sympy.physics.mechanics import Point, Particle, ReferenceFrame
>>> from sympy.physics.mechanics import RigidBody, outer, potential_energy
>>> from sympy import symbols
>>> M, m, g, h = symbols('M m g h')
>>> N = ReferenceFrame('N')
>>> O = Point('O')
>>> O.set_vel(N, 0 * N.x)
>>> P = O.locatenew('P', 1 * N.x)
>>> Pa = Particle('Pa', P, m)
>>> Ac = O.locatenew('Ac', 2 * N.y)
>>> a = ReferenceFrame('a')
>>> I = outer(N.z, N.z)
>>> A = RigidBody('A', Ac, a, M, (I, Ac))
>>> Pa.potential_energy = m * g * h
>>> A.potential_energy = M * g * h
>>> potential_energy(Pa, A)
M*g*h + g*h*m
"""
pe_sys = S.Zero
for e in body:
if isinstance(e, (RigidBody, Particle)):
pe_sys += e.potential_energy
else:
raise TypeError('*body must have only Particle or RigidBody')
return pe_sys
def gravity(acceleration, *bodies):
"""
Returns a list of gravity forces given the acceleration
due to gravity and any number of particles or rigidbodies.
Example
=======
>>> from sympy.physics.mechanics import ReferenceFrame, Point, Particle, outer, RigidBody
>>> from sympy.physics.mechanics.functions import gravity
>>> from sympy import symbols
>>> N = ReferenceFrame('N')
>>> m, M, g = symbols('m M g')
>>> F1, F2 = symbols('F1 F2')
>>> po = Point('po')
>>> pa = Particle('pa', po, m)
>>> A = ReferenceFrame('A')
>>> P = Point('P')
>>> I = outer(A.x, A.x)
>>> B = RigidBody('B', P, A, M, (I, P))
>>> forceList = [(po, F1), (P, F2)]
>>> forceList.extend(gravity(g*N.y, pa, B))
>>> forceList
[(po, F1), (P, F2), (po, g*m*N.y), (P, M*g*N.y)]
"""
gravity_force = []
if not bodies:
raise TypeError("No bodies(instances of Particle or Rigidbody) were passed.")
for e in bodies:
point = getattr(e, 'masscenter', None)
if point is None:
point = e.point
gravity_force.append((point, e.mass*acceleration))
return gravity_force
def center_of_mass(point, *bodies):
"""
Returns the position vector from the given point to the center of mass
of the given bodies(particles or rigidbodies).
Example
=======
>>> from sympy import symbols, S
>>> from sympy.physics.vector import Point
>>> from sympy.physics.mechanics import Particle, ReferenceFrame, RigidBody, outer
>>> from sympy.physics.mechanics.functions import center_of_mass
>>> a = ReferenceFrame('a')
>>> m = symbols('m', real=True)
>>> p1 = Particle('p1', Point('p1_pt'), S(1))
>>> p2 = Particle('p2', Point('p2_pt'), S(2))
>>> p3 = Particle('p3', Point('p3_pt'), S(3))
>>> p4 = Particle('p4', Point('p4_pt'), m)
>>> b_f = ReferenceFrame('b_f')
>>> b_cm = Point('b_cm')
>>> mb = symbols('mb')
>>> b = RigidBody('b', b_cm, b_f, mb, (outer(b_f.x, b_f.x), b_cm))
>>> p2.point.set_pos(p1.point, a.x)
>>> p3.point.set_pos(p1.point, a.x + a.y)
>>> p4.point.set_pos(p1.point, a.y)
>>> b.masscenter.set_pos(p1.point, a.y + a.z)
>>> point_o=Point('o')
>>> point_o.set_pos(p1.point, center_of_mass(p1.point, p1, p2, p3, p4, b))
>>> expr = 5/(m + mb + 6)*a.x + (m + mb + 3)/(m + mb + 6)*a.y + mb/(m + mb + 6)*a.z
>>> point_o.pos_from(p1.point)
5/(m + mb + 6)*a.x + (m + mb + 3)/(m + mb + 6)*a.y + mb/(m + mb + 6)*a.z
"""
if not bodies:
raise TypeError("No bodies(instances of Particle or Rigidbody) were passed.")
total_mass = 0
vec = Vector(0)
for i in bodies:
total_mass += i.mass
masscenter = getattr(i, 'masscenter', None)
if masscenter is None:
masscenter = i.point
vec += i.mass*masscenter.pos_from(point)
return vec/total_mass
def Lagrangian(frame, *body):
"""Lagrangian of a multibody system.
Explanation
===========
This function returns the Lagrangian of a system of Particle's and/or
RigidBody's. The Lagrangian of such a system is equal to the difference
between the kinetic energies and potential energies of its constituents. If
T and V are the kinetic and potential energies of a system then it's
Lagrangian, L, is defined as
L = T - V
The Lagrangian is a scalar.
Parameters
==========
frame : ReferenceFrame
The frame in which the velocity or angular velocity of the body is
defined to determine the kinetic energy.
body1, body2, body3... : Particle and/or RigidBody
The body (or bodies) whose Lagrangian is required.
Examples
========
>>> from sympy.physics.mechanics import Point, Particle, ReferenceFrame
>>> from sympy.physics.mechanics import RigidBody, outer, Lagrangian
>>> from sympy import symbols
>>> M, m, g, h = symbols('M m g h')
>>> N = ReferenceFrame('N')
>>> O = Point('O')
>>> O.set_vel(N, 0 * N.x)
>>> P = O.locatenew('P', 1 * N.x)
>>> P.set_vel(N, 10 * N.x)
>>> Pa = Particle('Pa', P, 1)
>>> Ac = O.locatenew('Ac', 2 * N.y)
>>> Ac.set_vel(N, 5 * N.y)
>>> a = ReferenceFrame('a')
>>> a.set_ang_vel(N, 10 * N.z)
>>> I = outer(N.z, N.z)
>>> A = RigidBody('A', Ac, a, 20, (I, Ac))
>>> Pa.potential_energy = m * g * h
>>> A.potential_energy = M * g * h
>>> Lagrangian(N, Pa, A)
-M*g*h - g*h*m + 350
"""
if not isinstance(frame, ReferenceFrame):
raise TypeError('Please supply a valid ReferenceFrame')
for e in body:
if not isinstance(e, (RigidBody, Particle)):
raise TypeError('*body must have only Particle or RigidBody')
return kinetic_energy(frame, *body) - potential_energy(*body)
def find_dynamicsymbols(expression, exclude=None, reference_frame=None):
"""Find all dynamicsymbols in expression.
Explanation
===========
If the optional ``exclude`` kwarg is used, only dynamicsymbols
not in the iterable ``exclude`` are returned.
If we intend to apply this function on a vector, the optional
``reference_frame`` is also used to inform about the corresponding frame
with respect to which the dynamic symbols of the given vector is to be
determined.
Parameters
==========
expression : SymPy expression
exclude : iterable of dynamicsymbols, optional
reference_frame : ReferenceFrame, optional
The frame with respect to which the dynamic symbols of the
given vector is to be determined.
Examples
========
>>> from sympy.physics.mechanics import dynamicsymbols, find_dynamicsymbols
>>> from sympy.physics.mechanics import ReferenceFrame
>>> x, y = dynamicsymbols('x, y')
>>> expr = x + x.diff()*y
>>> find_dynamicsymbols(expr)
{x(t), y(t), Derivative(x(t), t)}
>>> find_dynamicsymbols(expr, exclude=[x, y])
{Derivative(x(t), t)}
>>> a, b, c = dynamicsymbols('a, b, c')
>>> A = ReferenceFrame('A')
>>> v = a * A.x + b * A.y + c * A.z
>>> find_dynamicsymbols(v, reference_frame=A)
{a(t), b(t), c(t)}
"""
t_set = {dynamicsymbols._t}
if exclude:
if iterable(exclude):
exclude_set = set(exclude)
else:
raise TypeError("exclude kwarg must be iterable")
else:
exclude_set = set()
if isinstance(expression, Vector):
if reference_frame is None:
raise ValueError("You must provide reference_frame when passing a "
"vector expression, got %s." % reference_frame)
else:
expression = expression.to_matrix(reference_frame)
return {i for i in expression.atoms(AppliedUndef, Derivative) if
i.free_symbols == t_set} - exclude_set
def msubs(expr, *sub_dicts, smart=False, **kwargs):
"""A custom subs for use on expressions derived in physics.mechanics.
Traverses the expression tree once, performing the subs found in sub_dicts.
Terms inside ``Derivative`` expressions are ignored:
Examples
========
>>> from sympy.physics.mechanics import dynamicsymbols, msubs
>>> x = dynamicsymbols('x')
>>> msubs(x.diff() + x, {x: 1})
Derivative(x(t), t) + 1
Note that sub_dicts can be a single dictionary, or several dictionaries:
>>> x, y, z = dynamicsymbols('x, y, z')
>>> sub1 = {x: 1, y: 2}
>>> sub2 = {z: 3, x.diff(): 4}
>>> msubs(x.diff() + x + y + z, sub1, sub2)
10
If smart=True (default False), also checks for conditions that may result
in ``nan``, but if simplified would yield a valid expression. For example:
>>> from sympy import sin, tan
>>> (sin(x)/tan(x)).subs(x, 0)
nan
>>> msubs(sin(x)/tan(x), {x: 0}, smart=True)
1
It does this by first replacing all ``tan`` with ``sin/cos``. Then each
node is traversed. If the node is a fraction, subs is first evaluated on
the denominator. If this results in 0, simplification of the entire
fraction is attempted. Using this selective simplification, only
subexpressions that result in 1/0 are targeted, resulting in faster
performance.
"""
sub_dict = dict_merge(*sub_dicts)
if smart:
func = _smart_subs
elif hasattr(expr, 'msubs'):
return expr.msubs(sub_dict)
else:
func = lambda expr, sub_dict: _crawl(expr, _sub_func, sub_dict)
if isinstance(expr, (Matrix, Vector, Dyadic)):
return expr.applyfunc(lambda x: func(x, sub_dict))
else:
return func(expr, sub_dict)
def _crawl(expr, func, *args, **kwargs):
"""Crawl the expression tree, and apply func to every node."""
val = func(expr, *args, **kwargs)
if val is not None:
return val
new_args = (_crawl(arg, func, *args, **kwargs) for arg in expr.args)
return expr.func(*new_args)
def _sub_func(expr, sub_dict):
"""Perform direct matching substitution, ignoring derivatives."""
if expr in sub_dict:
return sub_dict[expr]
elif not expr.args or expr.is_Derivative:
return expr
def _tan_repl_func(expr):
"""Replace tan with sin/cos."""
if isinstance(expr, tan):
return sin(*expr.args) / cos(*expr.args)
elif not expr.args or expr.is_Derivative:
return expr
def _smart_subs(expr, sub_dict):
"""Performs subs, checking for conditions that may result in `nan` or
`oo`, and attempts to simplify them out.
The expression tree is traversed twice, and the following steps are
performed on each expression node:
- First traverse:
Replace all `tan` with `sin/cos`.
- Second traverse:
If node is a fraction, check if the denominator evaluates to 0.
If so, attempt to simplify it out. Then if node is in sub_dict,
sub in the corresponding value."""
expr = _crawl(expr, _tan_repl_func)
def _recurser(expr, sub_dict):
# Decompose the expression into num, den
num, den = _fraction_decomp(expr)
if den != 1:
# If there is a non trivial denominator, we need to handle it
denom_subbed = _recurser(den, sub_dict)
if denom_subbed.evalf() == 0:
# If denom is 0 after this, attempt to simplify the bad expr
expr = simplify(expr)
else:
# Expression won't result in nan, find numerator
num_subbed = _recurser(num, sub_dict)
return num_subbed / denom_subbed
# We have to crawl the tree manually, because `expr` may have been
# modified in the simplify step. First, perform subs as normal:
val = _sub_func(expr, sub_dict)
if val is not None:
return val
new_args = (_recurser(arg, sub_dict) for arg in expr.args)
return expr.func(*new_args)
return _recurser(expr, sub_dict)
def _fraction_decomp(expr):
"""Return num, den such that expr = num/den"""
if not isinstance(expr, Mul):
return expr, 1
num = []
den = []
for a in expr.args:
if a.is_Pow and a.args[1] < 0:
den.append(1 / a)
else:
num.append(a)
if not den:
return expr, 1
num = Mul(*num)
den = Mul(*den)
return num, den
def _f_list_parser(fl, ref_frame):
"""Parses the provided forcelist composed of items
of the form (obj, force).
Returns a tuple containing:
vel_list: The velocity (ang_vel for Frames, vel for Points) in
the provided reference frame.
f_list: The forces.
Used internally in the KanesMethod and LagrangesMethod classes.
"""
def flist_iter():
for pair in fl:
obj, force = pair
if isinstance(obj, ReferenceFrame):
yield obj.ang_vel_in(ref_frame), force
elif isinstance(obj, Point):
yield obj.vel(ref_frame), force
else:
raise TypeError('First entry in each forcelist pair must '
'be a point or frame.')
if not fl:
vel_list, f_list = (), ()
else:
unzip = lambda l: list(zip(*l)) if l[0] else [(), ()]
vel_list, f_list = unzip(list(flist_iter()))
return vel_list, f_list
|
e4fd55a5445348a8be60ec40cff2cee70d5050c165d7c63867020cb8adb95e3d | # coding=utf-8
from abc import ABC, abstractmethod
from sympy.core.numbers import pi
from sympy.physics.mechanics.body import Body
from sympy.physics.vector import Vector, dynamicsymbols, cross
from sympy.physics.vector.frame import ReferenceFrame
import warnings
__all__ = ['Joint', 'PinJoint', 'PrismaticJoint']
class Joint(ABC):
"""Abstract base class for all specific joints.
Explanation
===========
A joint subtracts degrees of freedom from a body. This is the base class
for all specific joints and holds all common methods acting as an interface
for all joints. Custom joint can be created by inheriting Joint class and
defining all abstract functions.
The abstract methods are:
- ``_generate_coordinates``
- ``_generate_speeds``
- ``_orient_frames``
- ``_set_angular_velocity``
- ``_set_linar_velocity``
Parameters
==========
name : string
A unique name for the joint.
parent : Body
The parent body of joint.
child : Body
The child body of joint.
coordinates: List of dynamicsymbols, optional
Generalized coordinates of the joint.
speeds : List of dynamicsymbols, optional
Generalized speeds of joint.
parent_joint_pos : Vector, optional
Vector from the parent body's mass center to the point where the parent
and child are connected. The default value is the zero vector.
child_joint_pos : Vector, optional
Vector from the child body's mass center to the point where the parent
and child are connected. The default value is the zero vector.
parent_axis : Vector, optional
Axis fixed in the parent body which aligns with an axis fixed in the
child body. The default is x axis in parent's reference frame.
child_axis : Vector, optional
Axis fixed in the child body which aligns with an axis fixed in the
parent body. The default is x axis in child's reference frame.
Attributes
==========
name : string
The joint's name.
parent : Body
The joint's parent body.
child : Body
The joint's child body.
coordinates : list
List of the joint's generalized coordinates.
speeds : list
List of the joint's generalized speeds.
parent_point : Point
The point fixed in the parent body that represents the joint.
child_point : Point
The point fixed in the child body that represents the joint.
parent_axis : Vector
The axis fixed in the parent frame that represents the joint.
child_axis : Vector
The axis fixed in the child frame that represents the joint.
kdes : list
Kinematical differential equations of the joint.
Notes
=====
The direction cosine matrix between the child and parent is formed using a
simple rotation about an axis that is normal to both ``child_axis`` and
``parent_axis``. In general, the normal axis is formed by crossing the
``child_axis`` into the ``parent_axis`` except if the child and parent axes
are in exactly opposite directions. In that case the rotation vector is chosen
using the rules in the following table where ``C`` is the child reference
frame and ``P`` is the parent reference frame:
.. list-table::
:header-rows: 1
* - ``child_axis``
- ``parent_axis``
- ``rotation_axis``
* - ``-C.x``
- ``P.x``
- ``P.z``
* - ``-C.y``
- ``P.y``
- ``P.x``
* - ``-C.z``
- ``P.z``
- ``P.y``
* - ``-C.x-C.y``
- ``P.x+P.y``
- ``P.z``
* - ``-C.y-C.z``
- ``P.y+P.z``
- ``P.x``
* - ``-C.x-C.z``
- ``P.x+P.z``
- ``P.y``
* - ``-C.x-C.y-C.z``
- ``P.x+P.y+P.z``
- ``(P.x+P.y+P.z) × P.x``
"""
def __init__(self, name, parent, child, coordinates=None, speeds=None,
parent_joint_pos=None, child_joint_pos=None, parent_axis=None,
child_axis=None):
if not isinstance(name, str):
raise TypeError('Supply a valid name.')
self._name = name
if not isinstance(parent, Body):
raise TypeError('Parent must be an instance of Body.')
self._parent = parent
if not isinstance(child, Body):
raise TypeError('Parent must be an instance of Body.')
self._child = child
self._coordinates = self._generate_coordinates(coordinates)
self._speeds = self._generate_speeds(speeds)
self._kdes = self._generate_kdes()
self._parent_axis = self._axis(parent, parent_axis)
self._child_axis = self._axis(child, child_axis)
self._parent_point = self._locate_joint_pos(parent, parent_joint_pos)
self._child_point = self._locate_joint_pos(child, child_joint_pos)
self._orient_frames()
self._set_angular_velocity()
self._set_linear_velocity()
def __str__(self):
return self.name
def __repr__(self):
return self.__str__()
@property
def name(self):
return self._name
@property
def parent(self):
"""Parent body of Joint."""
return self._parent
@property
def child(self):
"""Child body of Joint."""
return self._child
@property
def coordinates(self):
"""List generalized coordinates of the joint."""
return self._coordinates
@property
def speeds(self):
"""List generalized coordinates of the joint.."""
return self._speeds
@property
def kdes(self):
"""Kinematical differential equations of the joint."""
return self._kdes
@property
def parent_axis(self):
"""The axis of parent frame."""
return self._parent_axis
@property
def child_axis(self):
"""The axis of child frame."""
return self._child_axis
@property
def parent_point(self):
"""The joint's point where parent body is connected to the joint."""
return self._parent_point
@property
def child_point(self):
"""The joint's point where child body is connected to the joint."""
return self._child_point
@abstractmethod
def _generate_coordinates(self, coordinates):
"""Generate list generalized coordinates of the joint."""
pass
@abstractmethod
def _generate_speeds(self, speeds):
"""Generate list generalized speeds of the joint."""
pass
@abstractmethod
def _orient_frames(self):
"""Orient frames as per the joint."""
pass
@abstractmethod
def _set_angular_velocity(self):
pass
@abstractmethod
def _set_linear_velocity(self):
pass
def _generate_kdes(self):
kdes = []
t = dynamicsymbols._t
for i in range(len(self.coordinates)):
kdes.append(-self.coordinates[i].diff(t) + self.speeds[i])
return kdes
def _axis(self, body, ax):
if ax is None:
ax = body.frame.x
return ax
if not isinstance(ax, Vector):
raise TypeError("Axis must be of type Vector.")
if not ax.dt(body.frame) == 0:
msg = ('Axis cannot be time-varying when viewed from the '
'associated body.')
raise ValueError(msg)
return ax
def _locate_joint_pos(self, body, joint_pos):
if joint_pos is None:
joint_pos = Vector(0)
if not isinstance(joint_pos, Vector):
raise ValueError('Joint Position must be supplied as Vector.')
if not joint_pos.dt(body.frame) == 0:
msg = ('Position Vector cannot be time-varying when viewed from '
'the associated body.')
raise ValueError(msg)
point_name = self._name + '_' + body.name + '_joint'
return body.masscenter.locatenew(point_name, joint_pos)
def _alignment_rotation(self, parent, child):
# Returns the axis and angle between two axis(vectors).
angle = parent.angle_between(child)
axis = cross(child, parent).normalize()
return angle, axis
def _generate_vector(self):
parent_frame = self.parent.frame
components = self.parent_axis.to_matrix(parent_frame)
x, y, z = components[0], components[1], components[2]
if x != 0:
if y!=0:
if z!=0:
return cross(self.parent_axis,
parent_frame.x)
if z!=0:
return parent_frame.y
return parent_frame.z
if x == 0:
if y!=0:
if z!=0:
return parent_frame.x
return parent_frame.x
return parent_frame.y
def _set_orientation(self):
#Helper method for `orient_axis()`
self.child.frame.orient_axis(self.parent.frame, self.parent_axis, 0)
angle, axis = self._alignment_rotation(self.parent_axis,
self.child_axis)
with warnings.catch_warnings():
warnings.filterwarnings("ignore", category=UserWarning)
if axis != Vector(0) or angle == pi:
if angle == pi:
axis = self._generate_vector()
int_frame = ReferenceFrame('int_frame')
int_frame.orient_axis(self.child.frame, self.child_axis, 0)
int_frame.orient_axis(self.parent.frame, axis, angle)
return int_frame
return self.parent.frame
class PinJoint(Joint):
"""Pin (Revolute) Joint.
.. image:: PinJoint.png
Explanation
===========
A pin joint is defined such that the joint rotation axis is fixed in both
the child and parent and the location of the joint is relative to the mass
center of each body. The child rotates an angle, θ, from the parent about
the rotation axis and has a simple angular speed, ω, relative to the
parent. The direction cosine matrix between the child and parent is formed
using a simple rotation about an axis that is normal to both ``child_axis``
and ``parent_axis``, see the Notes section for a detailed explanation of
this.
Parameters
==========
name : string
A unique name for the joint.
parent : Body
The parent body of joint.
child : Body
The child body of joint.
coordinates: dynamicsymbol, optional
Generalized coordinates of the joint.
speeds : dynamicsymbol, optional
Generalized speeds of joint.
parent_joint_pos : Vector, optional
Vector from the parent body's mass center to the point where the parent
and child are connected. The default value is the zero vector.
child_joint_pos : Vector, optional
Vector from the child body's mass center to the point where the parent
and child are connected. The default value is the zero vector.
parent_axis : Vector, optional
Axis fixed in the parent body which aligns with an axis fixed in the
child body. The default is x axis in parent's reference frame.
child_axis : Vector, optional
Axis fixed in the child body which aligns with an axis fixed in the
parent body. The default is x axis in child's reference frame.
Attributes
==========
name : string
The joint's name.
parent : Body
The joint's parent body.
child : Body
The joint's child body.
coordinates : list
List of the joint's generalized coordinates.
speeds : list
List of the joint's generalized speeds.
parent_point : Point
The point fixed in the parent body that represents the joint.
child_point : Point
The point fixed in the child body that represents the joint.
parent_axis : Vector
The axis fixed in the parent frame that represents the joint.
child_axis : Vector
The axis fixed in the child frame that represents the joint.
kdes : list
Kinematical differential equations of the joint.
Examples
=========
A single pin joint is created from two bodies and has the following basic
attributes:
>>> from sympy.physics.mechanics import Body, PinJoint
>>> parent = Body('P')
>>> parent
P
>>> child = Body('C')
>>> child
C
>>> joint = PinJoint('PC', parent, child)
>>> joint
PinJoint: PC parent: P child: C
>>> joint.name
'PC'
>>> joint.parent
P
>>> joint.child
C
>>> joint.parent_point
PC_P_joint
>>> joint.child_point
PC_C_joint
>>> joint.parent_axis
P_frame.x
>>> joint.child_axis
C_frame.x
>>> joint.coordinates
[theta_PC(t)]
>>> joint.speeds
[omega_PC(t)]
>>> joint.child.frame.ang_vel_in(joint.parent.frame)
omega_PC(t)*P_frame.x
>>> joint.child.frame.dcm(joint.parent.frame)
Matrix([
[1, 0, 0],
[0, cos(theta_PC(t)), sin(theta_PC(t))],
[0, -sin(theta_PC(t)), cos(theta_PC(t))]])
>>> joint.child_point.pos_from(joint.parent_point)
0
To further demonstrate the use of the pin joint, the kinematics of simple
double pendulum that rotates about the Z axis of each connected body can be
created as follows.
>>> from sympy import symbols, trigsimp
>>> from sympy.physics.mechanics import Body, PinJoint
>>> l1, l2 = symbols('l1 l2')
First create bodies to represent the fixed ceiling and one to represent
each pendulum bob.
>>> ceiling = Body('C')
>>> upper_bob = Body('U')
>>> lower_bob = Body('L')
The first joint will connect the upper bob to the ceiling by a distance of
``l1`` and the joint axis will be about the Z axis for each body.
>>> ceiling_joint = PinJoint('P1', ceiling, upper_bob,
... child_joint_pos=-l1*upper_bob.frame.x,
... parent_axis=ceiling.frame.z,
... child_axis=upper_bob.frame.z)
The second joint will connect the lower bob to the upper bob by a distance
of ``l2`` and the joint axis will also be about the Z axis for each body.
>>> pendulum_joint = PinJoint('P2', upper_bob, lower_bob,
... child_joint_pos=-l2*lower_bob.frame.x,
... parent_axis=upper_bob.frame.z,
... child_axis=lower_bob.frame.z)
Once the joints are established the kinematics of the connected bodies can
be accessed. First the direction cosine matrices of pendulum link relative
to the ceiling are found:
>>> upper_bob.frame.dcm(ceiling.frame)
Matrix([
[ cos(theta_P1(t)), sin(theta_P1(t)), 0],
[-sin(theta_P1(t)), cos(theta_P1(t)), 0],
[ 0, 0, 1]])
>>> trigsimp(lower_bob.frame.dcm(ceiling.frame))
Matrix([
[ cos(theta_P1(t) + theta_P2(t)), sin(theta_P1(t) + theta_P2(t)), 0],
[-sin(theta_P1(t) + theta_P2(t)), cos(theta_P1(t) + theta_P2(t)), 0],
[ 0, 0, 1]])
The position of the lower bob's masscenter is found with:
>>> lower_bob.masscenter.pos_from(ceiling.masscenter)
l1*U_frame.x + l2*L_frame.x
The angular velocities of the two pendulum links can be computed with
respect to the ceiling.
>>> upper_bob.frame.ang_vel_in(ceiling.frame)
omega_P1(t)*C_frame.z
>>> lower_bob.frame.ang_vel_in(ceiling.frame)
omega_P1(t)*C_frame.z + omega_P2(t)*U_frame.z
And finally, the linear velocities of the two pendulum bobs can be computed
with respect to the ceiling.
>>> upper_bob.masscenter.vel(ceiling.frame)
l1*omega_P1(t)*U_frame.y
>>> lower_bob.masscenter.vel(ceiling.frame)
l1*omega_P1(t)*U_frame.y + l2*(omega_P1(t) + omega_P2(t))*L_frame.y
"""
def __init__(self, name, parent, child, coordinates=None, speeds=None,
parent_joint_pos=None, child_joint_pos=None, parent_axis=None,
child_axis=None):
super().__init__(name, parent, child, coordinates, speeds,
parent_joint_pos, child_joint_pos, parent_axis,
child_axis)
def __str__(self):
return (f'PinJoint: {self.name} parent: {self.parent} '
f'child: {self.child}')
def _generate_coordinates(self, coordinate):
coordinates = []
if coordinate is None:
theta = dynamicsymbols('theta' + '_' + self._name)
coordinate = theta
coordinates.append(coordinate)
return coordinates
def _generate_speeds(self, speed):
speeds = []
if speed is None:
omega = dynamicsymbols('omega' + '_' + self._name)
speed = omega
speeds.append(speed)
return speeds
def _orient_frames(self):
frame = self._set_orientation()
self.child.frame.orient_axis(frame, self.parent_axis,
self.coordinates[0])
def _set_angular_velocity(self):
self.child.frame.set_ang_vel(self.parent.frame, self.speeds[0] *
self.parent_axis.normalize())
def _set_linear_velocity(self):
self.parent_point.set_vel(self.parent.frame, 0)
self.child_point.set_vel(self.child.frame, 0)
self.child_point.set_pos(self.parent_point, 0)
self.child.masscenter.v2pt_theory(self.parent_point,
self.parent.frame, self.child.frame)
class PrismaticJoint(Joint):
"""Prismatic (Sliding) Joint.
.. image:: PrismaticJoint.png
Explanation
===========
It is defined such that the child body translates with respect to the parent
body along the body fixed parent axis. The location of the joint is defined
by two points in each body which coincides when the generalized coordinate is zero. The direction cosine matrix between
the child and parent is formed using a simple rotation about an axis that is normal to
both ``child_axis`` and ``parent_axis``, see the Notes section for a detailed explanation of
this.
Parameters
==========
name : string
A unique name for the joint.
parent : Body
The parent body of joint.
child : Body
The child body of joint.
coordinates: dynamicsymbol, optional
Generalized coordinates of the joint.
speeds : dynamicsymbol, optional
Generalized speeds of joint.
parent_joint_pos : Vector, optional
Vector from the parent body's mass center to the point where the parent
and child are connected. The default value is the zero vector.
child_joint_pos : Vector, optional
Vector from the child body's mass center to the point where the parent
and child are connected. The default value is the zero vector.
parent_axis : Vector, optional
Axis fixed in the parent body which aligns with an axis fixed in the
child body. The default is x axis in parent's reference frame.
child_axis : Vector, optional
Axis fixed in the child body which aligns with an axis fixed in the
parent body. The default is x axis in child's reference frame.
Attributes
==========
name : string
The joint's name.
parent : Body
The joint's parent body.
child : Body
The joint's child body.
coordinates : list
List of the joint's generalized coordinates.
speeds : list
List of the joint's generalized speeds.
parent_point : Point
The point fixed in the parent body that represents the joint.
child_point : Point
The point fixed in the child body that represents the joint.
parent_axis : Vector
The axis fixed in the parent frame that represents the joint.
child_axis : Vector
The axis fixed in the child frame that represents the joint.
kdes : list
Kinematical differential equations of the joint.
Examples
=========
A single prismatic joint is created from two bodies and has the following basic
attributes:
>>> from sympy.physics.mechanics import Body, PrismaticJoint
>>> parent = Body('P')
>>> parent
P
>>> child = Body('C')
>>> child
C
>>> joint = PrismaticJoint('PC', parent, child)
>>> joint
PrismaticJoint: PC parent: P child: C
>>> joint.name
'PC'
>>> joint.parent
P
>>> joint.child
C
>>> joint.parent_point
PC_P_joint
>>> joint.child_point
PC_C_joint
>>> joint.parent_axis
P_frame.x
>>> joint.child_axis
C_frame.x
>>> joint.coordinates
[x_PC(t)]
>>> joint.speeds
[v_PC(t)]
>>> joint.child.frame.ang_vel_in(joint.parent.frame)
0
>>> joint.child.frame.dcm(joint.parent.frame)
Matrix([
[1, 0, 0],
[0, 1, 0],
[0, 0, 1]])
>>> joint.child_point.pos_from(joint.parent_point)
x_PC(t)*P_frame.x
To further demonstrate the use of the prismatic joint, the kinematics of
two masses sliding, one moving relative to a fixed body and the other relative to the
moving body. about the X axis of each connected body can be created as follows.
>>> from sympy.physics.mechanics import PrismaticJoint, Body
First create bodies to represent the fixed ceiling and one to represent
a particle.
>>> wall = Body('W')
>>> Part1 = Body('P1')
>>> Part2 = Body('P2')
The first joint will connect the particle to the ceiling and the
joint axis will be about the X axis for each body.
>>> J1 = PrismaticJoint('J1', wall, Part1)
The second joint will connect the second particle to the first particle
and the joint axis will also be about the X axis for each body.
>>> J2 = PrismaticJoint('J2', Part1, Part2)
Once the joint is established the kinematics of the connected bodies can
be accessed. First the direction cosine matrices of Part relative
to the ceiling are found:
>>> Part1.dcm(wall)
Matrix([
[1, 0, 0],
[0, 1, 0],
[0, 0, 1]])
>>> Part2.dcm(wall)
Matrix([
[1, 0, 0],
[0, 1, 0],
[0, 0, 1]])
The position of the particles' masscenter is found with:
>>> Part1.masscenter.pos_from(wall.masscenter)
x_J1(t)*W_frame.x
>>> Part2.masscenter.pos_from(wall.masscenter)
x_J1(t)*W_frame.x + x_J2(t)*P1_frame.x
The angular velocities of the two particle links can be computed with
respect to the ceiling.
>>> Part1.ang_vel_in(wall)
0
>>> Part2.ang_vel_in(wall)
0
And finally, the linear velocities of the two particles can be computed
with respect to the ceiling.
>>> Part1.masscenter_vel(wall)
v_J1(t)*W_frame.x
>>> Part2.masscenter.vel(wall.frame)
v_J1(t)*W_frame.x + Derivative(x_J2(t), t)*P1_frame.x
"""
def __init__(self, name, parent, child, coordinates=None, speeds=None, parent_joint_pos=None,
child_joint_pos=None, parent_axis=None, child_axis=None):
super().__init__(name, parent, child, coordinates, speeds, parent_joint_pos,
child_joint_pos, parent_axis, child_axis)
def __str__(self):
return (f'PrismaticJoint: {self.name} parent: {self.parent} '
f'child: {self.child}')
def _generate_coordinates(self, coordinate):
coordinates = []
if coordinate is None:
x = dynamicsymbols('x' + '_' + self._name)
coordinate = x
coordinates.append(coordinate)
return coordinates
def _generate_speeds(self, speed):
speeds = []
if speed is None:
y = dynamicsymbols('v' + '_' + self._name)
speed = y
speeds.append(speed)
return speeds
def _orient_frames(self):
frame = self._set_orientation()
self.child.frame.orient_axis(frame, self.parent_axis, 0)
def _set_angular_velocity(self):
self.child.frame.set_ang_vel(self.parent.frame, 0)
def _set_linear_velocity(self):
self.parent_point.set_vel(self.parent.frame, 0)
self.child_point.set_vel(self.child.frame, 0)
self.child_point.set_pos(self.parent_point, self.coordinates[0] * self.parent_axis.normalize())
self.child_point.set_vel(self.parent.frame, self.speeds[0] * self.parent_axis.normalize())
self.child.masscenter.set_vel(self.parent.frame, self.speeds[0] * self.parent_axis.normalize())
|
6c013a2e7c4711ec2c97c5290315653f224efabb0b6bb12fcb6752bd77571b43 | from sympy.physics.mechanics import (Body, Lagrangian, KanesMethod, LagrangesMethod,
RigidBody, Particle)
from sympy.physics.mechanics.method import _Methods
__all__ = ['JointsMethod']
class JointsMethod(_Methods):
"""Method for formulating the equations of motion using a set of interconnected bodies with joints.
Parameters
==========
newtonion : Body or ReferenceFrame
The newtonion(inertial) frame.
*joints : Joint
The joints in the system
Attributes
==========
q, u : iterable
Iterable of the generalized coordinates and speeds
bodies : iterable
Iterable of Body objects in the system.
loads : iterable
Iterable of (Point, vector) or (ReferenceFrame, vector) tuples
describing the forces on the system.
mass_matrix : Matrix, shape(n, n)
The system's mass matrix
forcing : Matrix, shape(n, 1)
The system's forcing vector
mass_matrix_full : Matrix, shape(2*n, 2*n)
The "mass matrix" for the u's and q's
forcing_full : Matrix, shape(2*n, 1)
The "forcing vector" for the u's and q's
method : KanesMethod or Lagrange's method
Method's object.
kdes : iterable
Iterable of kde in they system.
Examples
========
This is a simple example for a one degree of freedom translational
spring-mass-damper.
>>> from sympy import symbols
>>> from sympy.physics.mechanics import Body, JointsMethod, PrismaticJoint
>>> from sympy.physics.vector import dynamicsymbols
>>> c, k = symbols('c k')
>>> x, v = dynamicsymbols('x v')
>>> wall = Body('W')
>>> body = Body('B')
>>> J = PrismaticJoint('J', wall, body, coordinates=x, speeds=v)
>>> wall.apply_force(c*v*wall.x, reaction_body=body)
>>> wall.apply_force(k*x*wall.x, reaction_body=body)
>>> method = JointsMethod(wall, J)
>>> method.form_eoms()
Matrix([[-B_mass*Derivative(v(t), t) - c*v(t) - k*x(t)]])
>>> M = method.mass_matrix_full
>>> F = method.forcing_full
>>> rhs = M.LUsolve(F)
>>> rhs
Matrix([
[ v(t)],
[(-c*v(t) - k*x(t))/B_mass]])
Notes
=====
``JointsMethod`` currently only works with systems that do not have any
configuration or motion constraints.
"""
def __init__(self, newtonion, *joints):
if isinstance(newtonion, Body):
self.frame = newtonion.frame
else:
self.frame = newtonion
self._joints = joints
self._bodies = self._generate_bodylist()
self._loads = self._generate_loadlist()
self._q = self._generate_q()
self._u = self._generate_u()
self._kdes = self._generate_kdes()
self._method = None
@property
def bodies(self):
"""List of bodies in they system."""
return self._bodies
@property
def loads(self):
"""List of loads on the system."""
return self._loads
@property
def q(self):
"""List of the generalized coordinates."""
return self._q
@property
def u(self):
"""List of the generalized speeds."""
return self._u
@property
def kdes(self):
"""List of the generalized coordinates."""
return self._kdes
@property
def forcing_full(self):
"""The "forcing vector" for the u's and q's."""
return self.method.forcing_full
@property
def mass_matrix_full(self):
"""The "mass matrix" for the u's and q's."""
return self.method.mass_matrix_full
@property
def mass_matrix(self):
"""The system's mass matrix."""
return self.method.mass_matrix
@property
def forcing(self):
"""The system's forcing vector."""
return self.method.forcing
@property
def method(self):
"""Object of method used to form equations of systems."""
return self._method
def _generate_bodylist(self):
bodies = []
for joint in self._joints:
if joint.child not in bodies:
bodies.append(joint.child)
if joint.parent not in bodies:
bodies.append(joint.parent)
return bodies
def _generate_loadlist(self):
load_list = []
for body in self.bodies:
load_list.extend(body.loads)
return load_list
def _generate_q(self):
q_ind = []
for joint in self._joints:
for coordinate in joint.coordinates:
if coordinate in q_ind:
raise ValueError('Coordinates of joints should be unique.')
q_ind.append(coordinate)
return q_ind
def _generate_u(self):
u_ind = []
for joint in self._joints:
for speed in joint.speeds:
if speed in u_ind:
raise ValueError('Speeds of joints should be unique.')
u_ind.append(speed)
return u_ind
def _generate_kdes(self):
kd_ind = []
for joint in self._joints:
kd_ind.extend(joint.kdes)
return kd_ind
def _convert_bodies(self):
# Convert `Body` to `Particle` and `RigidBody`
bodylist = []
for body in self.bodies:
if body.is_rigidbody:
rb = RigidBody(body.name, body.masscenter, body.frame, body.mass,
(body.central_inertia, body.masscenter))
rb.potential_energy = body.potential_energy
bodylist.append(rb)
else:
part = Particle(body.name, body.masscenter, body.mass)
part.potential_energy = body.potential_energy
bodylist.append(part)
return bodylist
def form_eoms(self, method=KanesMethod):
"""Method to form system's equation of motions.
Parameters
==========
method : Class
Class name of method.
Returns
========
Matrix
Vector of equations of motions.
Examples
========
This is a simple example for a one degree of freedom translational
spring-mass-damper.
>>> from sympy import S, symbols
>>> from sympy.physics.mechanics import LagrangesMethod, dynamicsymbols, Body
>>> from sympy.physics.mechanics import PrismaticJoint, JointsMethod
>>> q = dynamicsymbols('q')
>>> qd = dynamicsymbols('q', 1)
>>> m, k, b = symbols('m k b')
>>> wall = Body('W')
>>> part = Body('P', mass=m)
>>> part.potential_energy = k * q**2 / S(2)
>>> J = PrismaticJoint('J', wall, part, coordinates=q, speeds=qd)
>>> wall.apply_force(b * qd * wall.x, reaction_body=part)
>>> method = JointsMethod(wall, J)
>>> method.form_eoms(LagrangesMethod)
Matrix([[b*Derivative(q(t), t) + k*q(t) + m*Derivative(q(t), (t, 2))]])
We can also solve for the states using the 'rhs' method.
>>> method.rhs()
Matrix([
[ Derivative(q(t), t)],
[(-b*Derivative(q(t), t) - k*q(t))/m]])
"""
bodylist = self._convert_bodies()
if issubclass(method, LagrangesMethod): #LagrangesMethod or similar
L = Lagrangian(self.frame, *bodylist)
self._method = method(L, self.q, self.loads, bodylist, self.frame)
else: #KanesMethod or similar
self._method = method(self.frame, q_ind=self.q, u_ind=self.u, kd_eqs=self.kdes,
forcelist=self.loads, bodies=bodylist)
soln = self.method._form_eoms()
return soln
def rhs(self, inv_method=None):
"""Returns equations that can be solved numerically.
Parameters
==========
inv_method : str
The specific sympy inverse matrix calculation method to use. For a
list of valid methods, see
:meth:`~sympy.matrices.matrices.MatrixBase.inv`
Returns
========
Matrix
Numerically solveable equations.
See Also
========
sympy.physics.mechanics.kane.KanesMethod.rhs():
KanesMethod's rhs function.
sympy.physics.mechanics.lagrange.LagrangesMethod.rhs():
LagrangesMethod's rhs function.
"""
return self.method.rhs(inv_method=inv_method)
|
0fd6ea9c6c13e23fb1e2d9c79f842d7cccdd3685be8686b6322290596afe10ba | """
Definition of physical dimensions.
Unit systems will be constructed on top of these dimensions.
Most of the examples in the doc use MKS system and are presented from the
computer point of view: from a human point, adding length to time is not legal
in MKS but it is in natural system; for a computer in natural system there is
no time dimension (but a velocity dimension instead) - in the basis - so the
question of adding time to length has no meaning.
"""
from typing import Dict as tDict
import collections
from functools import reduce
from sympy.core.basic import Basic
from sympy.core.containers import (Dict, Tuple)
from sympy.core.singleton import S
from sympy.core.sorting import default_sort_key
from sympy.core.symbol import Symbol
from sympy.core.sympify import sympify
from sympy.matrices.dense import Matrix
from sympy.functions.elementary.trigonometric import TrigonometricFunction
from sympy.core.expr import Expr
from sympy.core.power import Pow
class _QuantityMapper:
_quantity_scale_factors_global = {} # type: tDict[Expr, Expr]
_quantity_dimensional_equivalence_map_global = {} # type: tDict[Expr, Expr]
_quantity_dimension_global = {} # type: tDict[Expr, Expr]
def __init__(self, *args, **kwargs):
self._quantity_dimension_map = {}
self._quantity_scale_factors = {}
def set_quantity_dimension(self, unit, dimension):
from sympy.physics.units import Quantity
dimension = sympify(dimension)
if not isinstance(dimension, Dimension):
if dimension == 1:
dimension = Dimension(1)
else:
raise ValueError("expected dimension or 1")
elif isinstance(dimension, Quantity):
dimension = self.get_quantity_dimension(dimension)
self._quantity_dimension_map[unit] = dimension
def set_quantity_scale_factor(self, unit, scale_factor):
from sympy.physics.units import Quantity
from sympy.physics.units.prefixes import Prefix
scale_factor = sympify(scale_factor)
# replace all prefixes by their ratio to canonical units:
scale_factor = scale_factor.replace(
lambda x: isinstance(x, Prefix),
lambda x: x.scale_factor
)
# replace all quantities by their ratio to canonical units:
scale_factor = scale_factor.replace(
lambda x: isinstance(x, Quantity),
lambda x: self.get_quantity_scale_factor(x)
)
self._quantity_scale_factors[unit] = scale_factor
def get_quantity_dimension(self, unit):
from sympy.physics.units import Quantity
# First look-up the local dimension map, then the global one:
if unit in self._quantity_dimension_map:
return self._quantity_dimension_map[unit]
if unit in self._quantity_dimension_global:
return self._quantity_dimension_global[unit]
if unit in self._quantity_dimensional_equivalence_map_global:
dep_unit = self._quantity_dimensional_equivalence_map_global[unit]
if isinstance(dep_unit, Quantity):
return self.get_quantity_dimension(dep_unit)
else:
return Dimension(self.get_dimensional_expr(dep_unit))
if isinstance(unit, Quantity):
return Dimension(unit.name)
else:
return Dimension(1)
def get_quantity_scale_factor(self, unit):
if unit in self._quantity_scale_factors:
return self._quantity_scale_factors[unit]
if unit in self._quantity_scale_factors_global:
mul_factor, other_unit = self._quantity_scale_factors_global[unit]
return mul_factor*self.get_quantity_scale_factor(other_unit)
return S.One
class Dimension(Expr):
"""
This class represent the dimension of a physical quantities.
The ``Dimension`` constructor takes as parameters a name and an optional
symbol.
For example, in classical mechanics we know that time is different from
temperature and dimensions make this difference (but they do not provide
any measure of these quantites.
>>> from sympy.physics.units import Dimension
>>> length = Dimension('length')
>>> length
Dimension(length)
>>> time = Dimension('time')
>>> time
Dimension(time)
Dimensions can be composed using multiplication, division and
exponentiation (by a number) to give new dimensions. Addition and
subtraction is defined only when the two objects are the same dimension.
>>> velocity = length / time
>>> velocity
Dimension(length/time)
It is possible to use a dimension system object to get the dimensionsal
dependencies of a dimension, for example the dimension system used by the
SI units convention can be used:
>>> from sympy.physics.units.systems.si import dimsys_SI
>>> dimsys_SI.get_dimensional_dependencies(velocity)
{Dimension(length, L): 1, Dimension(time, T): -1}
>>> length + length
Dimension(length)
>>> l2 = length**2
>>> l2
Dimension(length**2)
>>> dimsys_SI.get_dimensional_dependencies(l2)
{Dimension(length, L): 2}
"""
_op_priority = 13.0
# XXX: This doesn't seem to be used anywhere...
_dimensional_dependencies = {} # type: ignore
is_commutative = True
is_number = False
# make sqrt(M**2) --> M
is_positive = True
is_real = True
def __new__(cls, name, symbol=None):
if isinstance(name, str):
name = Symbol(name)
else:
name = sympify(name)
if not isinstance(name, Expr):
raise TypeError("Dimension name needs to be a valid math expression")
if isinstance(symbol, str):
symbol = Symbol(symbol)
elif symbol is not None:
assert isinstance(symbol, Symbol)
obj = Expr.__new__(cls, name)
obj._name = name
obj._symbol = symbol
return obj
@property
def name(self):
return self._name
@property
def symbol(self):
return self._symbol
def __str__(self):
"""
Display the string representation of the dimension.
"""
if self.symbol is None:
return "Dimension(%s)" % (self.name)
else:
return "Dimension(%s, %s)" % (self.name, self.symbol)
def __repr__(self):
return self.__str__()
def __neg__(self):
return self
def __add__(self, other):
from sympy.physics.units.quantities import Quantity
other = sympify(other)
if isinstance(other, Basic):
if other.has(Quantity):
raise TypeError("cannot sum dimension and quantity")
if isinstance(other, Dimension) and self == other:
return self
return super().__add__(other)
return self
def __radd__(self, other):
return self.__add__(other)
def __sub__(self, other):
# there is no notion of ordering (or magnitude) among dimension,
# subtraction is equivalent to addition when the operation is legal
return self + other
def __rsub__(self, other):
# there is no notion of ordering (or magnitude) among dimension,
# subtraction is equivalent to addition when the operation is legal
return self + other
def __pow__(self, other):
return self._eval_power(other)
def _eval_power(self, other):
other = sympify(other)
return Dimension(self.name**other)
def __mul__(self, other):
from sympy.physics.units.quantities import Quantity
if isinstance(other, Basic):
if other.has(Quantity):
raise TypeError("cannot sum dimension and quantity")
if isinstance(other, Dimension):
return Dimension(self.name*other.name)
if not other.free_symbols: # other.is_number cannot be used
return self
return super().__mul__(other)
return self
def __rmul__(self, other):
return self.__mul__(other)
def __truediv__(self, other):
return self*Pow(other, -1)
def __rtruediv__(self, other):
return other * pow(self, -1)
@classmethod
def _from_dimensional_dependencies(cls, dependencies):
return reduce(lambda x, y: x * y, (
d**e for d, e in dependencies.items()
), 1)
def has_integer_powers(self, dim_sys):
"""
Check if the dimension object has only integer powers.
All the dimension powers should be integers, but rational powers may
appear in intermediate steps. This method may be used to check that the
final result is well-defined.
"""
return all(dpow.is_Integer for dpow in dim_sys.get_dimensional_dependencies(self).values())
# Create dimensions according to the base units in MKSA.
# For other unit systems, they can be derived by transforming the base
# dimensional dependency dictionary.
class DimensionSystem(Basic, _QuantityMapper):
r"""
DimensionSystem represents a coherent set of dimensions.
The constructor takes three parameters:
- base dimensions;
- derived dimensions: these are defined in terms of the base dimensions
(for example velocity is defined from the division of length by time);
- dependency of dimensions: how the derived dimensions depend
on the base dimensions.
Optionally either the ``derived_dims`` or the ``dimensional_dependencies``
may be omitted.
"""
def __new__(cls, base_dims, derived_dims=(), dimensional_dependencies={}):
dimensional_dependencies = dict(dimensional_dependencies)
def parse_dim(dim):
if isinstance(dim, str):
dim = Dimension(Symbol(dim))
elif isinstance(dim, Dimension):
pass
elif isinstance(dim, Symbol):
dim = Dimension(dim)
else:
raise TypeError("%s wrong type" % dim)
return dim
base_dims = [parse_dim(i) for i in base_dims]
derived_dims = [parse_dim(i) for i in derived_dims]
for dim in base_dims:
if (dim in dimensional_dependencies
and (len(dimensional_dependencies[dim]) != 1 or
dimensional_dependencies[dim].get(dim, None) != 1)):
raise IndexError("Repeated value in base dimensions")
dimensional_dependencies[dim] = Dict({dim: 1})
def parse_dim_name(dim):
if isinstance(dim, Dimension):
return dim
elif isinstance(dim, str):
return Dimension(Symbol(dim))
elif isinstance(dim, Symbol):
return Dimension(dim)
else:
raise TypeError("unrecognized type %s for %s" % (type(dim), dim))
for dim in dimensional_dependencies.keys():
dim = parse_dim(dim)
if (dim not in derived_dims) and (dim not in base_dims):
derived_dims.append(dim)
def parse_dict(d):
return Dict({parse_dim_name(i): j for i, j in d.items()})
# Make sure everything is a SymPy type:
dimensional_dependencies = {parse_dim_name(i): parse_dict(j) for i, j in
dimensional_dependencies.items()}
for dim in derived_dims:
if dim in base_dims:
raise ValueError("Dimension %s both in base and derived" % dim)
if dim not in dimensional_dependencies:
# TODO: should this raise a warning?
dimensional_dependencies[dim] = Dict({dim: 1})
base_dims.sort(key=default_sort_key)
derived_dims.sort(key=default_sort_key)
base_dims = Tuple(*base_dims)
derived_dims = Tuple(*derived_dims)
dimensional_dependencies = Dict({i: Dict(j) for i, j in dimensional_dependencies.items()})
obj = Basic.__new__(cls, base_dims, derived_dims, dimensional_dependencies)
return obj
@property
def base_dims(self):
return self.args[0]
@property
def derived_dims(self):
return self.args[1]
@property
def dimensional_dependencies(self):
return self.args[2]
def _get_dimensional_dependencies_for_name(self, dimension):
if isinstance(dimension, str):
dimension = Dimension(Symbol(dimension))
elif not isinstance(dimension, Dimension):
dimension = Dimension(dimension)
if dimension.name.is_Symbol:
# Dimensions not included in the dependencies are considered
# as base dimensions:
return dict(self.dimensional_dependencies.get(dimension, {dimension: 1}))
if dimension.name.is_number or dimension.name.is_NumberSymbol:
return {}
get_for_name = self._get_dimensional_dependencies_for_name
if dimension.name.is_Mul:
ret = collections.defaultdict(int)
dicts = [get_for_name(i) for i in dimension.name.args]
for d in dicts:
for k, v in d.items():
ret[k] += v
return {k: v for (k, v) in ret.items() if v != 0}
if dimension.name.is_Add:
dicts = [get_for_name(i) for i in dimension.name.args]
if all(d == dicts[0] for d in dicts[1:]):
return dicts[0]
raise TypeError("Only equivalent dimensions can be added or subtracted.")
if dimension.name.is_Pow:
dim_base = get_for_name(dimension.name.base)
dim_exp = get_for_name(dimension.name.exp)
if dim_exp == {} or dimension.name.exp.is_Symbol:
return {k: v * dimension.name.exp for (k, v) in dim_base.items()}
else:
raise TypeError("The exponent for the power operator must be a Symbol or dimensionless.")
if dimension.name.is_Function:
args = (Dimension._from_dimensional_dependencies(
get_for_name(arg)) for arg in dimension.name.args)
result = dimension.name.func(*args)
dicts = [get_for_name(i) for i in dimension.name.args]
if isinstance(result, Dimension):
return self.get_dimensional_dependencies(result)
elif result.func == dimension.name.func:
if isinstance(dimension.name, TrigonometricFunction):
if dicts[0] in ({}, {Dimension('angle'): 1}):
return {}
else:
raise TypeError("The input argument for the function {} must be dimensionless or have dimensions of angle.".format(dimension.func))
else:
if all(item == {} for item in dicts):
return {}
else:
raise TypeError("The input arguments for the function {} must be dimensionless.".format(dimension.func))
else:
return get_for_name(result)
raise TypeError("Type {} not implemented for get_dimensional_dependencies".format(type(dimension.name)))
def get_dimensional_dependencies(self, name, mark_dimensionless=False):
dimdep = self._get_dimensional_dependencies_for_name(name)
if mark_dimensionless and dimdep == {}:
return {Dimension(1): 1}
return {k: v for k, v in dimdep.items()}
def equivalent_dims(self, dim1, dim2):
deps1 = self.get_dimensional_dependencies(dim1)
deps2 = self.get_dimensional_dependencies(dim2)
return deps1 == deps2
def extend(self, new_base_dims, new_derived_dims=(), new_dim_deps=None):
deps = dict(self.dimensional_dependencies)
if new_dim_deps:
deps.update(new_dim_deps)
new_dim_sys = DimensionSystem(
tuple(self.base_dims) + tuple(new_base_dims),
tuple(self.derived_dims) + tuple(new_derived_dims),
deps
)
new_dim_sys._quantity_dimension_map.update(self._quantity_dimension_map)
new_dim_sys._quantity_scale_factors.update(self._quantity_scale_factors)
return new_dim_sys
def is_dimensionless(self, dimension):
"""
Check if the dimension object really has a dimension.
A dimension should have at least one component with non-zero power.
"""
if dimension.name == 1:
return True
return self.get_dimensional_dependencies(dimension) == {}
@property
def list_can_dims(self):
"""
Useless method, kept for compatibility with previous versions.
DO NOT USE.
List all canonical dimension names.
"""
dimset = set()
for i in self.base_dims:
dimset.update(set(self.get_dimensional_dependencies(i).keys()))
return tuple(sorted(dimset, key=str))
@property
def inv_can_transf_matrix(self):
"""
Useless method, kept for compatibility with previous versions.
DO NOT USE.
Compute the inverse transformation matrix from the base to the
canonical dimension basis.
It corresponds to the matrix where columns are the vector of base
dimensions in canonical basis.
This matrix will almost never be used because dimensions are always
defined with respect to the canonical basis, so no work has to be done
to get them in this basis. Nonetheless if this matrix is not square
(or not invertible) it means that we have chosen a bad basis.
"""
matrix = reduce(lambda x, y: x.row_join(y),
[self.dim_can_vector(d) for d in self.base_dims])
return matrix
@property
def can_transf_matrix(self):
"""
Useless method, kept for compatibility with previous versions.
DO NOT USE.
Return the canonical transformation matrix from the canonical to the
base dimension basis.
It is the inverse of the matrix computed with inv_can_transf_matrix().
"""
#TODO: the inversion will fail if the system is inconsistent, for
# example if the matrix is not a square
return reduce(lambda x, y: x.row_join(y),
[self.dim_can_vector(d) for d in sorted(self.base_dims, key=str)]
).inv()
def dim_can_vector(self, dim):
"""
Useless method, kept for compatibility with previous versions.
DO NOT USE.
Dimensional representation in terms of the canonical base dimensions.
"""
vec = []
for d in self.list_can_dims:
vec.append(self.get_dimensional_dependencies(dim).get(d, 0))
return Matrix(vec)
def dim_vector(self, dim):
"""
Useless method, kept for compatibility with previous versions.
DO NOT USE.
Vector representation in terms of the base dimensions.
"""
return self.can_transf_matrix * Matrix(self.dim_can_vector(dim))
def print_dim_base(self, dim):
"""
Give the string expression of a dimension in term of the basis symbols.
"""
dims = self.dim_vector(dim)
symbols = [i.symbol if i.symbol is not None else i.name for i in self.base_dims]
res = S.One
for (s, p) in zip(symbols, dims):
res *= s**p
return res
@property
def dim(self):
"""
Useless method, kept for compatibility with previous versions.
DO NOT USE.
Give the dimension of the system.
That is return the number of dimensions forming the basis.
"""
return len(self.base_dims)
@property
def is_consistent(self):
"""
Useless method, kept for compatibility with previous versions.
DO NOT USE.
Check if the system is well defined.
"""
# not enough or too many base dimensions compared to independent
# dimensions
# in vector language: the set of vectors do not form a basis
return self.inv_can_transf_matrix.is_square
|
f87dcd882f47ed3a0b1960418d28298f841d3dafa846dead654e302359a46422 | """
Module defining unit prefixe class and some constants.
Constant dict for SI and binary prefixes are defined as PREFIXES and
BIN_PREFIXES.
"""
from sympy.core.expr import Expr
from sympy.core.sympify import sympify
class Prefix(Expr):
"""
This class represent prefixes, with their name, symbol and factor.
Prefixes are used to create derived units from a given unit. They should
always be encapsulated into units.
The factor is constructed from a base (default is 10) to some power, and
it gives the total multiple or fraction. For example the kilometer km
is constructed from the meter (factor 1) and the kilo (10 to the power 3,
i.e. 1000). The base can be changed to allow e.g. binary prefixes.
A prefix multiplied by something will always return the product of this
other object times the factor, except if the other object:
- is a prefix and they can be combined into a new prefix;
- defines multiplication with prefixes (which is the case for the Unit
class).
"""
_op_priority = 13.0
is_commutative = True
def __new__(cls, name, abbrev, exponent, base=sympify(10), latex_repr=None):
name = sympify(name)
abbrev = sympify(abbrev)
exponent = sympify(exponent)
base = sympify(base)
obj = Expr.__new__(cls, name, abbrev, exponent, base)
obj._name = name
obj._abbrev = abbrev
obj._scale_factor = base**exponent
obj._exponent = exponent
obj._base = base
obj._latex_repr = latex_repr
return obj
@property
def name(self):
return self._name
@property
def abbrev(self):
return self._abbrev
@property
def scale_factor(self):
return self._scale_factor
def _latex(self, printer):
if self._latex_repr is None:
return r'\text{%s}' % self._abbrev
return self._latex_repr
@property
def base(self):
return self._base
def __str__(self):
return str(self._abbrev)
def __repr__(self):
if self.base == 10:
return "Prefix(%r, %r, %r)" % (
str(self.name), str(self.abbrev), self._exponent)
else:
return "Prefix(%r, %r, %r, %r)" % (
str(self.name), str(self.abbrev), self._exponent, self.base)
def __mul__(self, other):
from sympy.physics.units import Quantity
if not isinstance(other, (Quantity, Prefix)):
return super().__mul__(other)
fact = self.scale_factor * other.scale_factor
if fact == 1:
return 1
elif isinstance(other, Prefix):
# simplify prefix
for p in PREFIXES:
if PREFIXES[p].scale_factor == fact:
return PREFIXES[p]
return fact
return self.scale_factor * other
def __truediv__(self, other):
if not hasattr(other, "scale_factor"):
return super().__truediv__(other)
fact = self.scale_factor / other.scale_factor
if fact == 1:
return 1
elif isinstance(other, Prefix):
for p in PREFIXES:
if PREFIXES[p].scale_factor == fact:
return PREFIXES[p]
return fact
return self.scale_factor / other
def __rtruediv__(self, other):
if other == 1:
for p in PREFIXES:
if PREFIXES[p].scale_factor == 1 / self.scale_factor:
return PREFIXES[p]
return other / self.scale_factor
def prefix_unit(unit, prefixes):
"""
Return a list of all units formed by unit and the given prefixes.
You can use the predefined PREFIXES or BIN_PREFIXES, but you can also
pass as argument a subdict of them if you do not want all prefixed units.
>>> from sympy.physics.units.prefixes import (PREFIXES,
... prefix_unit)
>>> from sympy.physics.units import m
>>> pref = {"m": PREFIXES["m"], "c": PREFIXES["c"], "d": PREFIXES["d"]}
>>> prefix_unit(m, pref) # doctest: +SKIP
[millimeter, centimeter, decimeter]
"""
from sympy.physics.units.quantities import Quantity
from sympy.physics.units import UnitSystem
prefixed_units = []
for prefix_abbr, prefix in prefixes.items():
quantity = Quantity(
"%s%s" % (prefix.name, unit.name),
abbrev=("%s%s" % (prefix.abbrev, unit.abbrev)),
is_prefixed=True,
)
UnitSystem._quantity_dimensional_equivalence_map_global[quantity] = unit
UnitSystem._quantity_scale_factors_global[quantity] = (prefix.scale_factor, unit)
prefixed_units.append(quantity)
return prefixed_units
yotta = Prefix('yotta', 'Y', 24)
zetta = Prefix('zetta', 'Z', 21)
exa = Prefix('exa', 'E', 18)
peta = Prefix('peta', 'P', 15)
tera = Prefix('tera', 'T', 12)
giga = Prefix('giga', 'G', 9)
mega = Prefix('mega', 'M', 6)
kilo = Prefix('kilo', 'k', 3)
hecto = Prefix('hecto', 'h', 2)
deca = Prefix('deca', 'da', 1)
deci = Prefix('deci', 'd', -1)
centi = Prefix('centi', 'c', -2)
milli = Prefix('milli', 'm', -3)
micro = Prefix('micro', 'mu', -6, latex_repr=r"\mu")
nano = Prefix('nano', 'n', -9)
pico = Prefix('pico', 'p', -12)
femto = Prefix('femto', 'f', -15)
atto = Prefix('atto', 'a', -18)
zepto = Prefix('zepto', 'z', -21)
yocto = Prefix('yocto', 'y', -24)
# http://physics.nist.gov/cuu/Units/prefixes.html
PREFIXES = {
'Y': yotta,
'Z': zetta,
'E': exa,
'P': peta,
'T': tera,
'G': giga,
'M': mega,
'k': kilo,
'h': hecto,
'da': deca,
'd': deci,
'c': centi,
'm': milli,
'mu': micro,
'n': nano,
'p': pico,
'f': femto,
'a': atto,
'z': zepto,
'y': yocto,
}
kibi = Prefix('kibi', 'Y', 10, 2)
mebi = Prefix('mebi', 'Y', 20, 2)
gibi = Prefix('gibi', 'Y', 30, 2)
tebi = Prefix('tebi', 'Y', 40, 2)
pebi = Prefix('pebi', 'Y', 50, 2)
exbi = Prefix('exbi', 'Y', 60, 2)
# http://physics.nist.gov/cuu/Units/binary.html
BIN_PREFIXES = {
'Ki': kibi,
'Mi': mebi,
'Gi': gibi,
'Ti': tebi,
'Pi': pebi,
'Ei': exbi,
}
|
ce9b9b758bcbcac1781463e668d3c4e16ffbccab5504b47e8069b8e19a0a9cce | """
Several methods to simplify expressions involving unit objects.
"""
from functools import reduce
from collections.abc import Iterable
from typing import Optional
from sympy import default_sort_key
from sympy.core.add import Add
from sympy.core.containers import Tuple
from sympy.core.mul import Mul
from sympy.core.power import Pow
from sympy.core.sorting import ordered
from sympy.core.sympify import sympify
from sympy.matrices.common import NonInvertibleMatrixError
from sympy.physics.units.dimensions import Dimension, DimensionSystem
from sympy.physics.units.prefixes import Prefix
from sympy.physics.units.quantities import Quantity
from sympy.physics.units.unitsystem import UnitSystem
from sympy.utilities.iterables import sift
def _get_conversion_matrix_for_expr(expr, target_units, unit_system):
from sympy.matrices.dense import Matrix
dimension_system = unit_system.get_dimension_system()
expr_dim = Dimension(unit_system.get_dimensional_expr(expr))
dim_dependencies = dimension_system.get_dimensional_dependencies(expr_dim, mark_dimensionless=True)
target_dims = [Dimension(unit_system.get_dimensional_expr(x)) for x in target_units]
canon_dim_units = [i for x in target_dims for i in dimension_system.get_dimensional_dependencies(x, mark_dimensionless=True)]
canon_expr_units = {i for i in dim_dependencies}
if not canon_expr_units.issubset(set(canon_dim_units)):
return None
seen = set()
canon_dim_units = [i for i in canon_dim_units if not (i in seen or seen.add(i))]
camat = Matrix([[dimension_system.get_dimensional_dependencies(i, mark_dimensionless=True).get(j, 0) for i in target_dims] for j in canon_dim_units])
exprmat = Matrix([dim_dependencies.get(k, 0) for k in canon_dim_units])
try:
res_exponents = camat.solve(exprmat)
except NonInvertibleMatrixError:
return None
return res_exponents
def convert_to(expr, target_units, unit_system="SI"):
"""
Convert ``expr`` to the same expression with all of its units and quantities
represented as factors of ``target_units``, whenever the dimension is compatible.
``target_units`` may be a single unit/quantity, or a collection of
units/quantities.
Examples
========
>>> from sympy.physics.units import speed_of_light, meter, gram, second, day
>>> from sympy.physics.units import mile, newton, kilogram, atomic_mass_constant
>>> from sympy.physics.units import kilometer, centimeter
>>> from sympy.physics.units import gravitational_constant, hbar
>>> from sympy.physics.units import convert_to
>>> convert_to(mile, kilometer)
25146*kilometer/15625
>>> convert_to(mile, kilometer).n()
1.609344*kilometer
>>> convert_to(speed_of_light, meter/second)
299792458*meter/second
>>> convert_to(day, second)
86400*second
>>> 3*newton
3*newton
>>> convert_to(3*newton, kilogram*meter/second**2)
3*kilogram*meter/second**2
>>> convert_to(atomic_mass_constant, gram)
1.660539060e-24*gram
Conversion to multiple units:
>>> convert_to(speed_of_light, [meter, second])
299792458*meter/second
>>> convert_to(3*newton, [centimeter, gram, second])
300000*centimeter*gram/second**2
Conversion to Planck units:
>>> convert_to(atomic_mass_constant, [gravitational_constant, speed_of_light, hbar]).n()
7.62963087839509e-20*hbar**0.5*speed_of_light**0.5/gravitational_constant**0.5
"""
from sympy.physics.units import UnitSystem
unit_system = UnitSystem.get_unit_system(unit_system)
if not isinstance(target_units, (Iterable, Tuple)):
target_units = [target_units]
if isinstance(expr, Add):
return Add.fromiter(convert_to(i, target_units, unit_system)
for i in expr.args)
expr = sympify(expr)
target_units = sympify(target_units)
if not isinstance(expr, Quantity) and expr.has(Quantity):
expr = expr.replace(lambda x: isinstance(x, Quantity),
lambda x: x.convert_to(target_units, unit_system))
def get_total_scale_factor(expr):
if isinstance(expr, Mul):
return reduce(lambda x, y: x * y,
[get_total_scale_factor(i) for i in expr.args])
elif isinstance(expr, Pow):
return get_total_scale_factor(expr.base) ** expr.exp
elif isinstance(expr, Quantity):
return unit_system.get_quantity_scale_factor(expr)
return expr
depmat = _get_conversion_matrix_for_expr(expr, target_units, unit_system)
if depmat is None:
return expr
expr_scale_factor = get_total_scale_factor(expr)
return expr_scale_factor * Mul.fromiter(
(1/get_total_scale_factor(u)*u)**p for u, p in
zip(target_units, depmat))
def quantity_simplify(expr, across_dimensions: bool=False, unit_system=None):
"""Return an equivalent expression in which prefixes are replaced
with numerical values and all units of a given dimension are the
unified in a canonical manner by default. `across_dimensions` allows
for units of different dimensions to be simplified together.
`unit_system` must be specified if `across_dimensions` is True.
Examples
========
>>> from sympy.physics.units.util import quantity_simplify
>>> from sympy.physics.units.prefixes import kilo
>>> from sympy.physics.units import foot, inch, joule, coulomb
>>> quantity_simplify(kilo*foot*inch)
250*foot**2/3
>>> quantity_simplify(foot - 6*inch)
foot/2
>>> quantity_simplify(5*joule/coulomb, across_dimensions=True, unit_system="SI")
5*volt
"""
if expr.is_Atom or not expr.has(Prefix, Quantity):
return expr
# replace all prefixes with numerical values
p = expr.atoms(Prefix)
expr = expr.xreplace({p: p.scale_factor for p in p})
# replace all quantities of given dimension with a canonical
# quantity, chosen from those in the expression
d = sift(expr.atoms(Quantity), lambda i: i.dimension)
for k in d:
if len(d[k]) == 1:
continue
v = list(ordered(d[k]))
ref = v[0]/v[0].scale_factor
expr = expr.xreplace({vi: ref*vi.scale_factor for vi in v[1:]})
if across_dimensions:
# combine quantities of different dimensions into a single
# quantity that is equivalent to the original expression
if unit_system is None:
raise ValueError("unit_system must be specified if across_dimensions is True")
unit_system = UnitSystem.get_unit_system(unit_system)
dimension_system: DimensionSystem = unit_system.get_dimension_system()
dim_expr = unit_system.get_dimensional_expr(expr)
dim_deps = dimension_system.get_dimensional_dependencies(dim_expr, mark_dimensionless=True)
target_dimension: Optional[Dimension] = None
for ds_dim, ds_dim_deps in dimension_system.dimensional_dependencies.items():
if ds_dim_deps == dim_deps:
target_dimension = ds_dim
break
if target_dimension is None:
# if we can't find a target dimension, we can't do anything. unsure how to handle this case.
return expr
target_unit = unit_system.derived_units.get(target_dimension)
if target_unit:
expr = convert_to(expr, target_unit, unit_system)
return expr
def check_dimensions(expr, unit_system="SI"):
"""Return expr if units in addends have the same
base dimensions, else raise a ValueError."""
# the case of adding a number to a dimensional quantity
# is ignored for the sake of SymPy core routines, so this
# function will raise an error now if such an addend is
# found.
# Also, when doing substitutions, multiplicative constants
# might be introduced, so remove those now
from sympy.physics.units import UnitSystem
unit_system = UnitSystem.get_unit_system(unit_system)
def addDict(dict1, dict2):
"""Merge dictionaries by adding values of common keys and
removing keys with value of 0."""
dict3 = {**dict1, **dict2}
for key, value in dict3.items():
if key in dict1 and key in dict2:
dict3[key] = value + dict1[key]
return {key:val for key, val in dict3.items() if val != 0}
adds = expr.atoms(Add)
DIM_OF = unit_system.get_dimension_system().get_dimensional_dependencies
for a in adds:
deset = set()
for ai in a.args:
if ai.is_number:
deset.add(())
continue
dims = []
skip = False
dimdict = {}
for i in Mul.make_args(ai):
if i.has(Quantity):
i = Dimension(unit_system.get_dimensional_expr(i))
if i.has(Dimension):
dimdict = addDict(dimdict, DIM_OF(i))
elif i.free_symbols:
skip = True
break
dims.extend(dimdict.items())
if not skip:
deset.add(tuple(sorted(dims, key=default_sort_key)))
if len(deset) > 1:
raise ValueError(
"addends have incompatible dimensions: {}".format(deset))
# clear multiplicative constants on Dimensions which may be
# left after substitution
reps = {}
for m in expr.atoms(Mul):
if any(isinstance(i, Dimension) for i in m.args):
reps[m] = m.func(*[
i for i in m.args if not i.is_number])
return expr.xreplace(reps)
|
aa357f2295e0d081cf0357d11f52706f07d1008463120b724f0197ffb57381a3 | """
Module to handle gamma matrices expressed as tensor objects.
Examples
========
>>> from sympy.physics.hep.gamma_matrices import GammaMatrix as G, LorentzIndex
>>> from sympy.tensor.tensor import tensor_indices
>>> i = tensor_indices('i', LorentzIndex)
>>> G(i)
GammaMatrix(i)
Note that there is already an instance of GammaMatrixHead in four dimensions:
GammaMatrix, which is simply declare as
>>> from sympy.physics.hep.gamma_matrices import GammaMatrix
>>> from sympy.tensor.tensor import tensor_indices
>>> i = tensor_indices('i', LorentzIndex)
>>> GammaMatrix(i)
GammaMatrix(i)
To access the metric tensor
>>> LorentzIndex.metric
metric(LorentzIndex,LorentzIndex)
"""
from sympy.core.mul import Mul
from sympy.core.singleton import S
from sympy.matrices.dense import eye
from sympy.matrices.expressions.trace import trace
from sympy.tensor.tensor import TensorIndexType, TensorIndex,\
TensMul, TensAdd, tensor_mul, Tensor, TensorHead, TensorSymmetry
# DiracSpinorIndex = TensorIndexType('DiracSpinorIndex', dim=4, dummy_name="S")
LorentzIndex = TensorIndexType('LorentzIndex', dim=4, dummy_name="L")
GammaMatrix = TensorHead("GammaMatrix", [LorentzIndex],
TensorSymmetry.no_symmetry(1), comm=None)
def extract_type_tens(expression, component):
"""
Extract from a ``TensExpr`` all tensors with `component`.
Returns two tensor expressions:
* the first contains all ``Tensor`` of having `component`.
* the second contains all remaining.
"""
if isinstance(expression, Tensor):
sp = [expression]
elif isinstance(expression, TensMul):
sp = expression.args
else:
raise ValueError('wrong type')
# Collect all gamma matrices of the same dimension
new_expr = S.One
residual_expr = S.One
for i in sp:
if isinstance(i, Tensor) and i.component == component:
new_expr *= i
else:
residual_expr *= i
return new_expr, residual_expr
def simplify_gamma_expression(expression):
extracted_expr, residual_expr = extract_type_tens(expression, GammaMatrix)
res_expr = _simplify_single_line(extracted_expr)
return res_expr * residual_expr
def simplify_gpgp(ex, sort=True):
"""
simplify products ``G(i)*p(-i)*G(j)*p(-j) -> p(i)*p(-i)``
Examples
========
>>> from sympy.physics.hep.gamma_matrices import GammaMatrix as G, \
LorentzIndex, simplify_gpgp
>>> from sympy.tensor.tensor import tensor_indices, tensor_heads
>>> p, q = tensor_heads('p, q', [LorentzIndex])
>>> i0,i1,i2,i3,i4,i5 = tensor_indices('i0:6', LorentzIndex)
>>> ps = p(i0)*G(-i0)
>>> qs = q(i0)*G(-i0)
>>> simplify_gpgp(ps*qs*qs)
GammaMatrix(-L_0)*p(L_0)*q(L_1)*q(-L_1)
"""
def _simplify_gpgp(ex):
components = ex.components
a = []
comp_map = []
for i, comp in enumerate(components):
comp_map.extend([i]*comp.rank)
dum = [(i[0], i[1], comp_map[i[0]], comp_map[i[1]]) for i in ex.dum]
for i in range(len(components)):
if components[i] != GammaMatrix:
continue
for dx in dum:
if dx[2] == i:
p_pos1 = dx[3]
elif dx[3] == i:
p_pos1 = dx[2]
else:
continue
comp1 = components[p_pos1]
if comp1.comm == 0 and comp1.rank == 1:
a.append((i, p_pos1))
if not a:
return ex
elim = set()
tv = []
hit = True
coeff = S.One
ta = None
while hit:
hit = False
for i, ai in enumerate(a[:-1]):
if ai[0] in elim:
continue
if ai[0] != a[i + 1][0] - 1:
continue
if components[ai[1]] != components[a[i + 1][1]]:
continue
elim.add(ai[0])
elim.add(ai[1])
elim.add(a[i + 1][0])
elim.add(a[i + 1][1])
if not ta:
ta = ex.split()
mu = TensorIndex('mu', LorentzIndex)
hit = True
if i == 0:
coeff = ex.coeff
tx = components[ai[1]](mu)*components[ai[1]](-mu)
if len(a) == 2:
tx *= 4 # eye(4)
tv.append(tx)
break
if tv:
a = [x for j, x in enumerate(ta) if j not in elim]
a.extend(tv)
t = tensor_mul(*a)*coeff
# t = t.replace(lambda x: x.is_Matrix, lambda x: 1)
return t
else:
return ex
if sort:
ex = ex.sorted_components()
# this would be better off with pattern matching
while 1:
t = _simplify_gpgp(ex)
if t != ex:
ex = t
else:
return t
def gamma_trace(t):
"""
trace of a single line of gamma matrices
Examples
========
>>> from sympy.physics.hep.gamma_matrices import GammaMatrix as G, \
gamma_trace, LorentzIndex
>>> from sympy.tensor.tensor import tensor_indices, tensor_heads
>>> p, q = tensor_heads('p, q', [LorentzIndex])
>>> i0,i1,i2,i3,i4,i5 = tensor_indices('i0:6', LorentzIndex)
>>> ps = p(i0)*G(-i0)
>>> qs = q(i0)*G(-i0)
>>> gamma_trace(G(i0)*G(i1))
4*metric(i0, i1)
>>> gamma_trace(ps*ps) - 4*p(i0)*p(-i0)
0
>>> gamma_trace(ps*qs + ps*ps) - 4*p(i0)*p(-i0) - 4*p(i0)*q(-i0)
0
"""
if isinstance(t, TensAdd):
res = TensAdd(*[_trace_single_line(x) for x in t.args])
return res
t = _simplify_single_line(t)
res = _trace_single_line(t)
return res
def _simplify_single_line(expression):
"""
Simplify single-line product of gamma matrices.
Examples
========
>>> from sympy.physics.hep.gamma_matrices import GammaMatrix as G, \
LorentzIndex, _simplify_single_line
>>> from sympy.tensor.tensor import tensor_indices, TensorHead
>>> p = TensorHead('p', [LorentzIndex])
>>> i0,i1 = tensor_indices('i0:2', LorentzIndex)
>>> _simplify_single_line(G(i0)*G(i1)*p(-i1)*G(-i0)) + 2*G(i0)*p(-i0)
0
"""
t1, t2 = extract_type_tens(expression, GammaMatrix)
if t1 != 1:
t1 = kahane_simplify(t1)
res = t1*t2
return res
def _trace_single_line(t):
"""
Evaluate the trace of a single gamma matrix line inside a ``TensExpr``.
Notes
=====
If there are ``DiracSpinorIndex.auto_left`` and ``DiracSpinorIndex.auto_right``
indices trace over them; otherwise traces are not implied (explain)
Examples
========
>>> from sympy.physics.hep.gamma_matrices import GammaMatrix as G, \
LorentzIndex, _trace_single_line
>>> from sympy.tensor.tensor import tensor_indices, TensorHead
>>> p = TensorHead('p', [LorentzIndex])
>>> i0,i1,i2,i3,i4,i5 = tensor_indices('i0:6', LorentzIndex)
>>> _trace_single_line(G(i0)*G(i1))
4*metric(i0, i1)
>>> _trace_single_line(G(i0)*p(-i0)*G(i1)*p(-i1)) - 4*p(i0)*p(-i0)
0
"""
def _trace_single_line1(t):
t = t.sorted_components()
components = t.components
ncomps = len(components)
g = LorentzIndex.metric
# gamma matirices are in a[i:j]
hit = 0
for i in range(ncomps):
if components[i] == GammaMatrix:
hit = 1
break
for j in range(i + hit, ncomps):
if components[j] != GammaMatrix:
break
else:
j = ncomps
numG = j - i
if numG == 0:
tcoeff = t.coeff
return t.nocoeff if tcoeff else t
if numG % 2 == 1:
return TensMul.from_data(S.Zero, [], [], [])
elif numG > 4:
# find the open matrix indices and connect them:
a = t.split()
ind1 = a[i].get_indices()[0]
ind2 = a[i + 1].get_indices()[0]
aa = a[:i] + a[i + 2:]
t1 = tensor_mul(*aa)*g(ind1, ind2)
t1 = t1.contract_metric(g)
args = [t1]
sign = 1
for k in range(i + 2, j):
sign = -sign
ind2 = a[k].get_indices()[0]
aa = a[:i] + a[i + 1:k] + a[k + 1:]
t2 = sign*tensor_mul(*aa)*g(ind1, ind2)
t2 = t2.contract_metric(g)
t2 = simplify_gpgp(t2, False)
args.append(t2)
t3 = TensAdd(*args)
t3 = _trace_single_line(t3)
return t3
else:
a = t.split()
t1 = _gamma_trace1(*a[i:j])
a2 = a[:i] + a[j:]
t2 = tensor_mul(*a2)
t3 = t1*t2
if not t3:
return t3
t3 = t3.contract_metric(g)
return t3
t = t.expand()
if isinstance(t, TensAdd):
a = [_trace_single_line1(x)*x.coeff for x in t.args]
return TensAdd(*a)
elif isinstance(t, (Tensor, TensMul)):
r = t.coeff*_trace_single_line1(t)
return r
else:
return trace(t)
def _gamma_trace1(*a):
gctr = 4 # FIXME specific for d=4
g = LorentzIndex.metric
if not a:
return gctr
n = len(a)
if n%2 == 1:
#return TensMul.from_data(S.Zero, [], [], [])
return S.Zero
if n == 2:
ind0 = a[0].get_indices()[0]
ind1 = a[1].get_indices()[0]
return gctr*g(ind0, ind1)
if n == 4:
ind0 = a[0].get_indices()[0]
ind1 = a[1].get_indices()[0]
ind2 = a[2].get_indices()[0]
ind3 = a[3].get_indices()[0]
return gctr*(g(ind0, ind1)*g(ind2, ind3) - \
g(ind0, ind2)*g(ind1, ind3) + g(ind0, ind3)*g(ind1, ind2))
def kahane_simplify(expression):
r"""
This function cancels contracted elements in a product of four
dimensional gamma matrices, resulting in an expression equal to the given
one, without the contracted gamma matrices.
Parameters
==========
`expression` the tensor expression containing the gamma matrices to simplify.
Notes
=====
If spinor indices are given, the matrices must be given in
the order given in the product.
Algorithm
=========
The idea behind the algorithm is to use some well-known identities,
i.e., for contractions enclosing an even number of `\gamma` matrices
`\gamma^\mu \gamma_{a_1} \cdots \gamma_{a_{2N}} \gamma_\mu = 2 (\gamma_{a_{2N}} \gamma_{a_1} \cdots \gamma_{a_{2N-1}} + \gamma_{a_{2N-1}} \cdots \gamma_{a_1} \gamma_{a_{2N}} )`
for an odd number of `\gamma` matrices
`\gamma^\mu \gamma_{a_1} \cdots \gamma_{a_{2N+1}} \gamma_\mu = -2 \gamma_{a_{2N+1}} \gamma_{a_{2N}} \cdots \gamma_{a_{1}}`
Instead of repeatedly applying these identities to cancel out all contracted indices,
it is possible to recognize the links that would result from such an operation,
the problem is thus reduced to a simple rearrangement of free gamma matrices.
Examples
========
When using, always remember that the original expression coefficient
has to be handled separately
>>> from sympy.physics.hep.gamma_matrices import GammaMatrix as G, LorentzIndex
>>> from sympy.physics.hep.gamma_matrices import kahane_simplify
>>> from sympy.tensor.tensor import tensor_indices
>>> i0, i1, i2 = tensor_indices('i0:3', LorentzIndex)
>>> ta = G(i0)*G(-i0)
>>> kahane_simplify(ta)
Matrix([
[4, 0, 0, 0],
[0, 4, 0, 0],
[0, 0, 4, 0],
[0, 0, 0, 4]])
>>> tb = G(i0)*G(i1)*G(-i0)
>>> kahane_simplify(tb)
-2*GammaMatrix(i1)
>>> t = G(i0)*G(-i0)
>>> kahane_simplify(t)
Matrix([
[4, 0, 0, 0],
[0, 4, 0, 0],
[0, 0, 4, 0],
[0, 0, 0, 4]])
>>> t = G(i0)*G(-i0)
>>> kahane_simplify(t)
Matrix([
[4, 0, 0, 0],
[0, 4, 0, 0],
[0, 0, 4, 0],
[0, 0, 0, 4]])
If there are no contractions, the same expression is returned
>>> tc = G(i0)*G(i1)
>>> kahane_simplify(tc)
GammaMatrix(i0)*GammaMatrix(i1)
References
==========
[1] Algorithm for Reducing Contracted Products of gamma Matrices,
Joseph Kahane, Journal of Mathematical Physics, Vol. 9, No. 10, October 1968.
"""
if isinstance(expression, Mul):
return expression
if isinstance(expression, TensAdd):
return TensAdd(*[kahane_simplify(arg) for arg in expression.args])
if isinstance(expression, Tensor):
return expression
assert isinstance(expression, TensMul)
gammas = expression.args
for gamma in gammas:
assert gamma.component == GammaMatrix
free = expression.free
# spinor_free = [_ for _ in expression.free_in_args if _[1] != 0]
# if len(spinor_free) == 2:
# spinor_free.sort(key=lambda x: x[2])
# assert spinor_free[0][1] == 1 and spinor_free[-1][1] == 2
# assert spinor_free[0][2] == 0
# elif spinor_free:
# raise ValueError('spinor indices do not match')
dum = []
for dum_pair in expression.dum:
if expression.index_types[dum_pair[0]] == LorentzIndex:
dum.append((dum_pair[0], dum_pair[1]))
dum = sorted(dum)
if len(dum) == 0: # or GammaMatrixHead:
# no contractions in `expression`, just return it.
return expression
# find the `first_dum_pos`, i.e. the position of the first contracted
# gamma matrix, Kahane's algorithm as described in his paper requires the
# gamma matrix expression to start with a contracted gamma matrix, this is
# a workaround which ignores possible initial free indices, and re-adds
# them later.
first_dum_pos = min(map(min, dum))
# for p1, p2, a1, a2 in expression.dum_in_args:
# if p1 != 0 or p2 != 0:
# # only Lorentz indices, skip Dirac indices:
# continue
# first_dum_pos = min(p1, p2)
# break
total_number = len(free) + len(dum)*2
number_of_contractions = len(dum)
free_pos = [None]*total_number
for i in free:
free_pos[i[1]] = i[0]
# `index_is_free` is a list of booleans, to identify index position
# and whether that index is free or dummy.
index_is_free = [False]*total_number
for i, indx in enumerate(free):
index_is_free[indx[1]] = True
# `links` is a dictionary containing the graph described in Kahane's paper,
# to every key correspond one or two values, representing the linked indices.
# All values in `links` are integers, negative numbers are used in the case
# where it is necessary to insert gamma matrices between free indices, in
# order to make Kahane's algorithm work (see paper).
links = {i: [] for i in range(first_dum_pos, total_number)}
# `cum_sign` is a step variable to mark the sign of every index, see paper.
cum_sign = -1
# `cum_sign_list` keeps storage for all `cum_sign` (every index).
cum_sign_list = [None]*total_number
block_free_count = 0
# multiply `resulting_coeff` by the coefficient parameter, the rest
# of the algorithm ignores a scalar coefficient.
resulting_coeff = S.One
# initialize a list of lists of indices. The outer list will contain all
# additive tensor expressions, while the inner list will contain the
# free indices (rearranged according to the algorithm).
resulting_indices = [[]]
# start to count the `connected_components`, which together with the number
# of contractions, determines a -1 or +1 factor to be multiplied.
connected_components = 1
# First loop: here we fill `cum_sign_list`, and draw the links
# among consecutive indices (they are stored in `links`). Links among
# non-consecutive indices will be drawn later.
for i, is_free in enumerate(index_is_free):
# if `expression` starts with free indices, they are ignored here;
# they are later added as they are to the beginning of all
# `resulting_indices` list of lists of indices.
if i < first_dum_pos:
continue
if is_free:
block_free_count += 1
# if previous index was free as well, draw an arch in `links`.
if block_free_count > 1:
links[i - 1].append(i)
links[i].append(i - 1)
else:
# Change the sign of the index (`cum_sign`) if the number of free
# indices preceding it is even.
cum_sign *= 1 if (block_free_count % 2) else -1
if block_free_count == 0 and i != first_dum_pos:
# check if there are two consecutive dummy indices:
# in this case create virtual indices with negative position,
# these "virtual" indices represent the insertion of two
# gamma^0 matrices to separate consecutive dummy indices, as
# Kahane's algorithm requires dummy indices to be separated by
# free indices. The product of two gamma^0 matrices is unity,
# so the new expression being examined is the same as the
# original one.
if cum_sign == -1:
links[-1-i] = [-1-i+1]
links[-1-i+1] = [-1-i]
if (i - cum_sign) in links:
if i != first_dum_pos:
links[i].append(i - cum_sign)
if block_free_count != 0:
if i - cum_sign < len(index_is_free):
if index_is_free[i - cum_sign]:
links[i - cum_sign].append(i)
block_free_count = 0
cum_sign_list[i] = cum_sign
# The previous loop has only created links between consecutive free indices,
# it is necessary to properly create links among dummy (contracted) indices,
# according to the rules described in Kahane's paper. There is only one exception
# to Kahane's rules: the negative indices, which handle the case of some
# consecutive free indices (Kahane's paper just describes dummy indices
# separated by free indices, hinting that free indices can be added without
# altering the expression result).
for i in dum:
# get the positions of the two contracted indices:
pos1 = i[0]
pos2 = i[1]
# create Kahane's upper links, i.e. the upper arcs between dummy
# (i.e. contracted) indices:
links[pos1].append(pos2)
links[pos2].append(pos1)
# create Kahane's lower links, this corresponds to the arcs below
# the line described in the paper:
# first we move `pos1` and `pos2` according to the sign of the indices:
linkpos1 = pos1 + cum_sign_list[pos1]
linkpos2 = pos2 + cum_sign_list[pos2]
# otherwise, perform some checks before creating the lower arcs:
# make sure we are not exceeding the total number of indices:
if linkpos1 >= total_number:
continue
if linkpos2 >= total_number:
continue
# make sure we are not below the first dummy index in `expression`:
if linkpos1 < first_dum_pos:
continue
if linkpos2 < first_dum_pos:
continue
# check if the previous loop created "virtual" indices between dummy
# indices, in such a case relink `linkpos1` and `linkpos2`:
if (-1-linkpos1) in links:
linkpos1 = -1-linkpos1
if (-1-linkpos2) in links:
linkpos2 = -1-linkpos2
# move only if not next to free index:
if linkpos1 >= 0 and not index_is_free[linkpos1]:
linkpos1 = pos1
if linkpos2 >=0 and not index_is_free[linkpos2]:
linkpos2 = pos2
# create the lower arcs:
if linkpos2 not in links[linkpos1]:
links[linkpos1].append(linkpos2)
if linkpos1 not in links[linkpos2]:
links[linkpos2].append(linkpos1)
# This loop starts from the `first_dum_pos` index (first dummy index)
# walks through the graph deleting the visited indices from `links`,
# it adds a gamma matrix for every free index in encounters, while it
# completely ignores dummy indices and virtual indices.
pointer = first_dum_pos
previous_pointer = 0
while True:
if pointer in links:
next_ones = links.pop(pointer)
else:
break
if previous_pointer in next_ones:
next_ones.remove(previous_pointer)
previous_pointer = pointer
if next_ones:
pointer = next_ones[0]
else:
break
if pointer == previous_pointer:
break
if pointer >=0 and free_pos[pointer] is not None:
for ri in resulting_indices:
ri.append(free_pos[pointer])
# The following loop removes the remaining connected components in `links`.
# If there are free indices inside a connected component, it gives a
# contribution to the resulting expression given by the factor
# `gamma_a gamma_b ... gamma_z + gamma_z ... gamma_b gamma_a`, in Kahanes's
# paper represented as {gamma_a, gamma_b, ... , gamma_z},
# virtual indices are ignored. The variable `connected_components` is
# increased by one for every connected component this loop encounters.
# If the connected component has virtual and dummy indices only
# (no free indices), it contributes to `resulting_indices` by a factor of two.
# The multiplication by two is a result of the
# factor {gamma^0, gamma^0} = 2 I, as it appears in Kahane's paper.
# Note: curly brackets are meant as in the paper, as a generalized
# multi-element anticommutator!
while links:
connected_components += 1
pointer = min(links.keys())
previous_pointer = pointer
# the inner loop erases the visited indices from `links`, and it adds
# all free indices to `prepend_indices` list, virtual indices are
# ignored.
prepend_indices = []
while True:
if pointer in links:
next_ones = links.pop(pointer)
else:
break
if previous_pointer in next_ones:
if len(next_ones) > 1:
next_ones.remove(previous_pointer)
previous_pointer = pointer
if next_ones:
pointer = next_ones[0]
if pointer >= first_dum_pos and free_pos[pointer] is not None:
prepend_indices.insert(0, free_pos[pointer])
# if `prepend_indices` is void, it means there are no free indices
# in the loop (and it can be shown that there must be a virtual index),
# loops of virtual indices only contribute by a factor of two:
if len(prepend_indices) == 0:
resulting_coeff *= 2
# otherwise, add the free indices in `prepend_indices` to
# the `resulting_indices`:
else:
expr1 = prepend_indices
expr2 = list(reversed(prepend_indices))
resulting_indices = [expri + ri for ri in resulting_indices for expri in (expr1, expr2)]
# sign correction, as described in Kahane's paper:
resulting_coeff *= -1 if (number_of_contractions - connected_components + 1) % 2 else 1
# power of two factor, as described in Kahane's paper:
resulting_coeff *= 2**(number_of_contractions)
# If `first_dum_pos` is not zero, it means that there are trailing free gamma
# matrices in front of `expression`, so multiply by them:
for i in range(0, first_dum_pos):
[ri.insert(0, free_pos[i]) for ri in resulting_indices]
resulting_expr = S.Zero
for i in resulting_indices:
temp_expr = S.One
for j in i:
temp_expr *= GammaMatrix(j)
resulting_expr += temp_expr
t = resulting_coeff * resulting_expr
t1 = None
if isinstance(t, TensAdd):
t1 = t.args[0]
elif isinstance(t, TensMul):
t1 = t
if t1:
pass
else:
t = eye(4)*t
return t
|
4be3faa00867791f339e85ee10c768fac0f44b6e696ab5f26a443af388151c4e | from sympy.core.backend import (S, sympify, expand, sqrt, Add, zeros, acos,
ImmutableMatrix as Matrix, _simplify_matrix)
from sympy.simplify.trigsimp import trigsimp
from sympy.printing.defaults import Printable
from sympy.utilities.misc import filldedent
from sympy.core.evalf import EvalfMixin
from mpmath.libmp.libmpf import prec_to_dps
__all__ = ['Vector']
class Vector(Printable, EvalfMixin):
"""The class used to define vectors.
It along with ReferenceFrame are the building blocks of describing a
classical mechanics system in PyDy and sympy.physics.vector.
Attributes
==========
simp : Boolean
Let certain methods use trigsimp on their outputs
"""
simp = False
is_number = False
def __init__(self, inlist):
"""This is the constructor for the Vector class. You should not be
calling this, it should only be used by other functions. You should be
treating Vectors like you would with if you were doing the math by
hand, and getting the first 3 from the standard basis vectors from a
ReferenceFrame.
The only exception is to create a zero vector:
zv = Vector(0)
"""
self.args = []
if inlist == 0:
inlist = []
if isinstance(inlist, dict):
d = inlist
else:
d = {}
for inp in inlist:
if inp[1] in d:
d[inp[1]] += inp[0]
else:
d[inp[1]] = inp[0]
for k, v in d.items():
if v != Matrix([0, 0, 0]):
self.args.append((v, k))
@property
def func(self):
"""Returns the class Vector. """
return Vector
def __hash__(self):
return hash(tuple(self.args))
def __add__(self, other):
"""The add operator for Vector. """
if other == 0:
return self
other = _check_vector(other)
return Vector(self.args + other.args)
def __and__(self, other):
"""Dot product of two vectors.
Returns a scalar, the dot product of the two Vectors
Parameters
==========
other : Vector
The Vector which we are dotting with
Examples
========
>>> from sympy.physics.vector import ReferenceFrame, dot
>>> from sympy import symbols
>>> q1 = symbols('q1')
>>> N = ReferenceFrame('N')
>>> dot(N.x, N.x)
1
>>> dot(N.x, N.y)
0
>>> A = N.orientnew('A', 'Axis', [q1, N.x])
>>> dot(N.y, A.y)
cos(q1)
"""
from sympy.physics.vector.dyadic import Dyadic
if isinstance(other, Dyadic):
return NotImplemented
other = _check_vector(other)
out = S.Zero
for i, v1 in enumerate(self.args):
for j, v2 in enumerate(other.args):
out += ((v2[0].T)
* (v2[1].dcm(v1[1]))
* (v1[0]))[0]
if Vector.simp:
return trigsimp(out, recursive=True)
else:
return out
def __truediv__(self, other):
"""This uses mul and inputs self and 1 divided by other. """
return self.__mul__(S.One / other)
def __eq__(self, other):
"""Tests for equality.
It is very import to note that this is only as good as the SymPy
equality test; False does not always mean they are not equivalent
Vectors.
If other is 0, and self is empty, returns True.
If other is 0 and self is not empty, returns False.
If none of the above, only accepts other as a Vector.
"""
if other == 0:
other = Vector(0)
try:
other = _check_vector(other)
except TypeError:
return False
if (self.args == []) and (other.args == []):
return True
elif (self.args == []) or (other.args == []):
return False
frame = self.args[0][1]
for v in frame:
if expand((self - other) & v) != 0:
return False
return True
def __mul__(self, other):
"""Multiplies the Vector by a sympifyable expression.
Parameters
==========
other : Sympifyable
The scalar to multiply this Vector with
Examples
========
>>> from sympy.physics.vector import ReferenceFrame
>>> from sympy import Symbol
>>> N = ReferenceFrame('N')
>>> b = Symbol('b')
>>> V = 10 * b * N.x
>>> print(V)
10*b*N.x
"""
newlist = [v for v in self.args]
other = sympify(other)
for i, v in enumerate(newlist):
newlist[i] = (other * newlist[i][0], newlist[i][1])
return Vector(newlist)
def __neg__(self):
return self * -1
def __or__(self, other):
"""Outer product between two Vectors.
A rank increasing operation, which returns a Dyadic from two Vectors
Parameters
==========
other : Vector
The Vector to take the outer product with
Examples
========
>>> from sympy.physics.vector import ReferenceFrame, outer
>>> N = ReferenceFrame('N')
>>> outer(N.x, N.x)
(N.x|N.x)
"""
from sympy.physics.vector.dyadic import Dyadic
other = _check_vector(other)
ol = Dyadic(0)
for i, v in enumerate(self.args):
for i2, v2 in enumerate(other.args):
# it looks this way because if we are in the same frame and
# use the enumerate function on the same frame in a nested
# fashion, then bad things happen
ol += Dyadic([(v[0][0] * v2[0][0], v[1].x, v2[1].x)])
ol += Dyadic([(v[0][0] * v2[0][1], v[1].x, v2[1].y)])
ol += Dyadic([(v[0][0] * v2[0][2], v[1].x, v2[1].z)])
ol += Dyadic([(v[0][1] * v2[0][0], v[1].y, v2[1].x)])
ol += Dyadic([(v[0][1] * v2[0][1], v[1].y, v2[1].y)])
ol += Dyadic([(v[0][1] * v2[0][2], v[1].y, v2[1].z)])
ol += Dyadic([(v[0][2] * v2[0][0], v[1].z, v2[1].x)])
ol += Dyadic([(v[0][2] * v2[0][1], v[1].z, v2[1].y)])
ol += Dyadic([(v[0][2] * v2[0][2], v[1].z, v2[1].z)])
return ol
def _latex(self, printer):
"""Latex Printing method. """
ar = self.args # just to shorten things
if len(ar) == 0:
return str(0)
ol = [] # output list, to be concatenated to a string
for i, v in enumerate(ar):
for j in 0, 1, 2:
# if the coef of the basis vector is 1, we skip the 1
if ar[i][0][j] == 1:
ol.append(' + ' + ar[i][1].latex_vecs[j])
# if the coef of the basis vector is -1, we skip the 1
elif ar[i][0][j] == -1:
ol.append(' - ' + ar[i][1].latex_vecs[j])
elif ar[i][0][j] != 0:
# If the coefficient of the basis vector is not 1 or -1;
# also, we might wrap it in parentheses, for readability.
arg_str = printer._print(ar[i][0][j])
if isinstance(ar[i][0][j], Add):
arg_str = "(%s)" % arg_str
if arg_str[0] == '-':
arg_str = arg_str[1:]
str_start = ' - '
else:
str_start = ' + '
ol.append(str_start + arg_str + ar[i][1].latex_vecs[j])
outstr = ''.join(ol)
if outstr.startswith(' + '):
outstr = outstr[3:]
elif outstr.startswith(' '):
outstr = outstr[1:]
return outstr
def _pretty(self, printer):
"""Pretty Printing method. """
from sympy.printing.pretty.stringpict import prettyForm
e = self
class Fake:
def render(self, *args, **kwargs):
ar = e.args # just to shorten things
if len(ar) == 0:
return str(0)
pforms = [] # output list, to be concatenated to a string
for i, v in enumerate(ar):
for j in 0, 1, 2:
# if the coef of the basis vector is 1, we skip the 1
if ar[i][0][j] == 1:
pform = printer._print(ar[i][1].pretty_vecs[j])
# if the coef of the basis vector is -1, we skip the 1
elif ar[i][0][j] == -1:
pform = printer._print(ar[i][1].pretty_vecs[j])
pform = prettyForm(*pform.left(" - "))
bin = prettyForm.NEG
pform = prettyForm(binding=bin, *pform)
elif ar[i][0][j] != 0:
# If the basis vector coeff is not 1 or -1,
# we might wrap it in parentheses, for readability.
pform = printer._print(ar[i][0][j])
if isinstance(ar[i][0][j], Add):
tmp = pform.parens()
pform = prettyForm(tmp[0], tmp[1])
pform = prettyForm(*pform.right(
" ", ar[i][1].pretty_vecs[j]))
else:
continue
pforms.append(pform)
pform = prettyForm.__add__(*pforms)
kwargs["wrap_line"] = kwargs.get("wrap_line")
kwargs["num_columns"] = kwargs.get("num_columns")
out_str = pform.render(*args, **kwargs)
mlines = [line.rstrip() for line in out_str.split("\n")]
return "\n".join(mlines)
return Fake()
def __ror__(self, other):
"""Outer product between two Vectors.
A rank increasing operation, which returns a Dyadic from two Vectors
Parameters
==========
other : Vector
The Vector to take the outer product with
Examples
========
>>> from sympy.physics.vector import ReferenceFrame, outer
>>> N = ReferenceFrame('N')
>>> outer(N.x, N.x)
(N.x|N.x)
"""
from sympy.physics.vector.dyadic import Dyadic
other = _check_vector(other)
ol = Dyadic(0)
for i, v in enumerate(other.args):
for i2, v2 in enumerate(self.args):
# it looks this way because if we are in the same frame and
# use the enumerate function on the same frame in a nested
# fashion, then bad things happen
ol += Dyadic([(v[0][0] * v2[0][0], v[1].x, v2[1].x)])
ol += Dyadic([(v[0][0] * v2[0][1], v[1].x, v2[1].y)])
ol += Dyadic([(v[0][0] * v2[0][2], v[1].x, v2[1].z)])
ol += Dyadic([(v[0][1] * v2[0][0], v[1].y, v2[1].x)])
ol += Dyadic([(v[0][1] * v2[0][1], v[1].y, v2[1].y)])
ol += Dyadic([(v[0][1] * v2[0][2], v[1].y, v2[1].z)])
ol += Dyadic([(v[0][2] * v2[0][0], v[1].z, v2[1].x)])
ol += Dyadic([(v[0][2] * v2[0][1], v[1].z, v2[1].y)])
ol += Dyadic([(v[0][2] * v2[0][2], v[1].z, v2[1].z)])
return ol
def __rsub__(self, other):
return (-1 * self) + other
def _sympystr(self, printer, order=True):
"""Printing method. """
if not order or len(self.args) == 1:
ar = list(self.args)
elif len(self.args) == 0:
return printer._print(0)
else:
d = {v[1]: v[0] for v in self.args}
keys = sorted(d.keys(), key=lambda x: x.index)
ar = []
for key in keys:
ar.append((d[key], key))
ol = [] # output list, to be concatenated to a string
for i, v in enumerate(ar):
for j in 0, 1, 2:
# if the coef of the basis vector is 1, we skip the 1
if ar[i][0][j] == 1:
ol.append(' + ' + ar[i][1].str_vecs[j])
# if the coef of the basis vector is -1, we skip the 1
elif ar[i][0][j] == -1:
ol.append(' - ' + ar[i][1].str_vecs[j])
elif ar[i][0][j] != 0:
# If the coefficient of the basis vector is not 1 or -1;
# also, we might wrap it in parentheses, for readability.
arg_str = printer._print(ar[i][0][j])
if isinstance(ar[i][0][j], Add):
arg_str = "(%s)" % arg_str
if arg_str[0] == '-':
arg_str = arg_str[1:]
str_start = ' - '
else:
str_start = ' + '
ol.append(str_start + arg_str + '*' + ar[i][1].str_vecs[j])
outstr = ''.join(ol)
if outstr.startswith(' + '):
outstr = outstr[3:]
elif outstr.startswith(' '):
outstr = outstr[1:]
return outstr
def __sub__(self, other):
"""The subtraction operator. """
return self.__add__(other * -1)
def __xor__(self, other):
"""The cross product operator for two Vectors.
Returns a Vector, expressed in the same ReferenceFrames as self.
Parameters
==========
other : Vector
The Vector which we are crossing with
Examples
========
>>> from sympy import symbols
>>> from sympy.physics.vector import ReferenceFrame, cross
>>> q1 = symbols('q1')
>>> N = ReferenceFrame('N')
>>> cross(N.x, N.y)
N.z
>>> A = ReferenceFrame('A')
>>> A.orient_axis(N, q1, N.x)
>>> cross(A.x, N.y)
N.z
>>> cross(N.y, A.x)
- sin(q1)*A.y - cos(q1)*A.z
"""
from sympy.physics.vector.dyadic import Dyadic
if isinstance(other, Dyadic):
return NotImplemented
other = _check_vector(other)
if other.args == []:
return Vector(0)
def _det(mat):
"""This is needed as a little method for to find the determinant
of a list in python; needs to work for a 3x3 list.
SymPy's Matrix will not take in Vector, so need a custom function.
You should not be calling this.
"""
return (mat[0][0] * (mat[1][1] * mat[2][2] - mat[1][2] * mat[2][1])
+ mat[0][1] * (mat[1][2] * mat[2][0] - mat[1][0] *
mat[2][2]) + mat[0][2] * (mat[1][0] * mat[2][1] -
mat[1][1] * mat[2][0]))
outlist = []
ar = other.args # For brevity
for i, v in enumerate(ar):
tempx = v[1].x
tempy = v[1].y
tempz = v[1].z
tempm = ([[tempx, tempy, tempz],
[self & tempx, self & tempy, self & tempz],
[Vector([ar[i]]) & tempx, Vector([ar[i]]) & tempy,
Vector([ar[i]]) & tempz]])
outlist += _det(tempm).args
return Vector(outlist)
__radd__ = __add__
__rand__ = __and__
__rmul__ = __mul__
def separate(self):
"""
The constituents of this vector in different reference frames,
as per its definition.
Returns a dict mapping each ReferenceFrame to the corresponding
constituent Vector.
Examples
========
>>> from sympy.physics.vector import ReferenceFrame
>>> R1 = ReferenceFrame('R1')
>>> R2 = ReferenceFrame('R2')
>>> v = R1.x + R2.x
>>> v.separate() == {R1: R1.x, R2: R2.x}
True
"""
components = {}
for x in self.args:
components[x[1]] = Vector([x])
return components
def dot(self, other):
return self & other
dot.__doc__ = __and__.__doc__
def cross(self, other):
return self ^ other
cross.__doc__ = __xor__.__doc__
def outer(self, other):
return self | other
outer.__doc__ = __or__.__doc__
def diff(self, var, frame, var_in_dcm=True):
"""Returns the partial derivative of the vector with respect to a
variable in the provided reference frame.
Parameters
==========
var : Symbol
What the partial derivative is taken with respect to.
frame : ReferenceFrame
The reference frame that the partial derivative is taken in.
var_in_dcm : boolean
If true, the differentiation algorithm assumes that the variable
may be present in any of the direction cosine matrices that relate
the frame to the frames of any component of the vector. But if it
is known that the variable is not present in the direction cosine
matrices, false can be set to skip full reexpression in the desired
frame.
Examples
========
>>> from sympy import Symbol
>>> from sympy.physics.vector import dynamicsymbols, ReferenceFrame
>>> from sympy.physics.vector import Vector
>>> from sympy.physics.vector import init_vprinting
>>> init_vprinting(pretty_print=False)
>>> Vector.simp = True
>>> t = Symbol('t')
>>> q1 = dynamicsymbols('q1')
>>> N = ReferenceFrame('N')
>>> A = N.orientnew('A', 'Axis', [q1, N.y])
>>> A.x.diff(t, N)
- sin(q1)*q1'*N.x - cos(q1)*q1'*N.z
>>> A.x.diff(t, N).express(A)
- q1'*A.z
>>> B = ReferenceFrame('B')
>>> u1, u2 = dynamicsymbols('u1, u2')
>>> v = u1 * A.x + u2 * B.y
>>> v.diff(u2, N, var_in_dcm=False)
B.y
"""
from sympy.physics.vector.frame import _check_frame
_check_frame(frame)
var = sympify(var)
inlist = []
for vector_component in self.args:
measure_number = vector_component[0]
component_frame = vector_component[1]
if component_frame == frame:
inlist += [(measure_number.diff(var), frame)]
else:
# If the direction cosine matrix relating the component frame
# with the derivative frame does not contain the variable.
if not var_in_dcm or (frame.dcm(component_frame).diff(var) ==
zeros(3, 3)):
inlist += [(measure_number.diff(var), component_frame)]
else: # else express in the frame
reexp_vec_comp = Vector([vector_component]).express(frame)
deriv = reexp_vec_comp.args[0][0].diff(var)
inlist += Vector([(deriv, frame)]).args
return Vector(inlist)
def express(self, otherframe, variables=False):
"""
Returns a Vector equivalent to this one, expressed in otherframe.
Uses the global express method.
Parameters
==========
otherframe : ReferenceFrame
The frame for this Vector to be described in
variables : boolean
If True, the coordinate symbols(if present) in this Vector
are re-expressed in terms otherframe
Examples
========
>>> from sympy.physics.vector import ReferenceFrame, dynamicsymbols
>>> from sympy.physics.vector import init_vprinting
>>> init_vprinting(pretty_print=False)
>>> q1 = dynamicsymbols('q1')
>>> N = ReferenceFrame('N')
>>> A = N.orientnew('A', 'Axis', [q1, N.y])
>>> A.x.express(N)
cos(q1)*N.x - sin(q1)*N.z
"""
from sympy.physics.vector import express
return express(self, otherframe, variables=variables)
def to_matrix(self, reference_frame):
"""Returns the matrix form of the vector with respect to the given
frame.
Parameters
----------
reference_frame : ReferenceFrame
The reference frame that the rows of the matrix correspond to.
Returns
-------
matrix : ImmutableMatrix, shape(3,1)
The matrix that gives the 1D vector.
Examples
========
>>> from sympy import symbols
>>> from sympy.physics.vector import ReferenceFrame
>>> a, b, c = symbols('a, b, c')
>>> N = ReferenceFrame('N')
>>> vector = a * N.x + b * N.y + c * N.z
>>> vector.to_matrix(N)
Matrix([
[a],
[b],
[c]])
>>> beta = symbols('beta')
>>> A = N.orientnew('A', 'Axis', (beta, N.x))
>>> vector.to_matrix(A)
Matrix([
[ a],
[ b*cos(beta) + c*sin(beta)],
[-b*sin(beta) + c*cos(beta)]])
"""
return Matrix([self.dot(unit_vec) for unit_vec in
reference_frame]).reshape(3, 1)
def doit(self, **hints):
"""Calls .doit() on each term in the Vector"""
d = {}
for v in self.args:
d[v[1]] = v[0].applyfunc(lambda x: x.doit(**hints))
return Vector(d)
def dt(self, otherframe):
"""
Returns a Vector which is the time derivative of
the self Vector, taken in frame otherframe.
Calls the global time_derivative method
Parameters
==========
otherframe : ReferenceFrame
The frame to calculate the time derivative in
"""
from sympy.physics.vector import time_derivative
return time_derivative(self, otherframe)
def simplify(self):
"""Returns a simplified Vector."""
d = {}
for v in self.args:
d[v[1]] = _simplify_matrix(v[0])
return Vector(d)
def subs(self, *args, **kwargs):
"""Substitution on the Vector.
Examples
========
>>> from sympy.physics.vector import ReferenceFrame
>>> from sympy import Symbol
>>> N = ReferenceFrame('N')
>>> s = Symbol('s')
>>> a = N.x * s
>>> a.subs({s: 2})
2*N.x
"""
d = {}
for v in self.args:
d[v[1]] = v[0].subs(*args, **kwargs)
return Vector(d)
def magnitude(self):
"""Returns the magnitude (Euclidean norm) of self.
Warnings
========
Python ignores the leading negative sign so that might
give wrong results.
``-A.x.magnitude()`` would be treated as ``-(A.x.magnitude())``,
instead of ``(-A.x).magnitude()``.
"""
return sqrt(self & self)
def normalize(self):
"""Returns a Vector of magnitude 1, codirectional with self."""
return Vector(self.args + []) / self.magnitude()
def applyfunc(self, f):
"""Apply a function to each component of a vector."""
if not callable(f):
raise TypeError("`f` must be callable.")
d = {}
for v in self.args:
d[v[1]] = v[0].applyfunc(f)
return Vector(d)
def angle_between(self, vec):
"""
Returns the smallest angle between Vector 'vec' and self.
Parameter
=========
vec : Vector
The Vector between which angle is needed.
Examples
========
>>> from sympy.physics.vector import ReferenceFrame
>>> A = ReferenceFrame("A")
>>> v1 = A.x
>>> v2 = A.y
>>> v1.angle_between(v2)
pi/2
>>> v3 = A.x + A.y + A.z
>>> v1.angle_between(v3)
acos(sqrt(3)/3)
Warnings
========
Python ignores the leading negative sign so that might give wrong
results. ``-A.x.angle_between()`` would be treated as
``-(A.x.angle_between())``, instead of ``(-A.x).angle_between()``.
"""
vec1 = self.normalize()
vec2 = vec.normalize()
angle = acos(vec1.dot(vec2))
return angle
def free_symbols(self, reference_frame):
"""Returns the free symbols in the measure numbers of the vector
expressed in the given reference frame.
Parameters
==========
reference_frame : ReferenceFrame
The frame with respect to which the free symbols of the given
vector is to be determined.
Returns
=======
set of Symbol
set of symbols present in the measure numbers of
``reference_frame``.
"""
return self.to_matrix(reference_frame).free_symbols
def free_dynamicsymbols(self, reference_frame):
"""Returns the free dynamic symbols (functions of time ``t``) in the
measure numbers of the vector expressed in the given reference frame.
Parameters
==========
reference_frame : ReferenceFrame
The frame with respect to which the free dynamic symbols of the
given vector is to be determined.
Returns
=======
set
Set of functions of time ``t``, e.g.
``Function('f')(me.dynamicsymbols._t)``.
"""
# TODO : Circular dependency if imported at top. Should move
# find_dynamicsymbols into physics.vector.functions.
from sympy.physics.mechanics.functions import find_dynamicsymbols
return find_dynamicsymbols(self, reference_frame=reference_frame)
def _eval_evalf(self, prec):
if not self.args:
return self
new_args = []
dps = prec_to_dps(prec)
for mat, frame in self.args:
new_args.append([mat.evalf(n=dps), frame])
return Vector(new_args)
def xreplace(self, rule):
"""Replace occurrences of objects within the measure numbers of the
vector.
Parameters
==========
rule : dict-like
Expresses a replacement rule.
Returns
=======
Vector
Result of the replacement.
Examples
========
>>> from sympy import symbols, pi
>>> from sympy.physics.vector import ReferenceFrame
>>> A = ReferenceFrame('A')
>>> x, y, z = symbols('x y z')
>>> ((1 + x*y) * A.x).xreplace({x: pi})
(pi*y + 1)*A.x
>>> ((1 + x*y) * A.x).xreplace({x: pi, y: 2})
(1 + 2*pi)*A.x
Replacements occur only if an entire node in the expression tree is
matched:
>>> ((x*y + z) * A.x).xreplace({x*y: pi})
(z + pi)*A.x
>>> ((x*y*z) * A.x).xreplace({x*y: pi})
x*y*z*A.x
"""
new_args = []
for mat, frame in self.args:
mat = mat.xreplace(rule)
new_args.append([mat, frame])
return Vector(new_args)
class VectorTypeError(TypeError):
def __init__(self, other, want):
msg = filldedent("Expected an instance of %s, but received object "
"'%s' of %s." % (type(want), other, type(other)))
super().__init__(msg)
def _check_vector(other):
if not isinstance(other, Vector):
raise TypeError('A Vector must be supplied')
return other
|
f6150ac2c33fe67a72f45b834877bd7a238b40b7e6659138f6b571c0484f4f65 | from .vector import Vector, _check_vector
from .frame import _check_frame
from warnings import warn
__all__ = ['Point']
class Point:
"""This object represents a point in a dynamic system.
It stores the: position, velocity, and acceleration of a point.
The position is a vector defined as the vector distance from a parent
point to this point.
Parameters
==========
name : string
The display name of the Point
Examples
========
>>> from sympy.physics.vector import Point, ReferenceFrame, dynamicsymbols
>>> from sympy.physics.vector import init_vprinting
>>> init_vprinting(pretty_print=False)
>>> N = ReferenceFrame('N')
>>> O = Point('O')
>>> P = Point('P')
>>> u1, u2, u3 = dynamicsymbols('u1 u2 u3')
>>> O.set_vel(N, u1 * N.x + u2 * N.y + u3 * N.z)
>>> O.acc(N)
u1'*N.x + u2'*N.y + u3'*N.z
``symbols()`` can be used to create multiple Points in a single step, for
example:
>>> from sympy.physics.vector import Point, ReferenceFrame, dynamicsymbols
>>> from sympy.physics.vector import init_vprinting
>>> init_vprinting(pretty_print=False)
>>> from sympy import symbols
>>> N = ReferenceFrame('N')
>>> u1, u2 = dynamicsymbols('u1 u2')
>>> A, B = symbols('A B', cls=Point)
>>> type(A)
<class 'sympy.physics.vector.point.Point'>
>>> A.set_vel(N, u1 * N.x + u2 * N.y)
>>> B.set_vel(N, u2 * N.x + u1 * N.y)
>>> A.acc(N) - B.acc(N)
(u1' - u2')*N.x + (-u1' + u2')*N.y
"""
def __init__(self, name):
"""Initialization of a Point object. """
self.name = name
self._pos_dict = {}
self._vel_dict = {}
self._acc_dict = {}
self._pdlist = [self._pos_dict, self._vel_dict, self._acc_dict]
def __str__(self):
return self.name
__repr__ = __str__
def _check_point(self, other):
if not isinstance(other, Point):
raise TypeError('A Point must be supplied')
def _pdict_list(self, other, num):
"""Returns a list of points that gives the shortest path with respect
to position, velocity, or acceleration from this point to the provided
point.
Parameters
==========
other : Point
A point that may be related to this point by position, velocity, or
acceleration.
num : integer
0 for searching the position tree, 1 for searching the velocity
tree, and 2 for searching the acceleration tree.
Returns
=======
list of Points
A sequence of points from self to other.
Notes
=====
It is not clear if num = 1 or num = 2 actually works because the keys
to ``_vel_dict`` and ``_acc_dict`` are :class:`ReferenceFrame` objects
which do not have the ``_pdlist`` attribute.
"""
outlist = [[self]]
oldlist = [[]]
while outlist != oldlist:
oldlist = outlist[:]
for i, v in enumerate(outlist):
templist = v[-1]._pdlist[num].keys()
for i2, v2 in enumerate(templist):
if not v.__contains__(v2):
littletemplist = v + [v2]
if not outlist.__contains__(littletemplist):
outlist.append(littletemplist)
for i, v in enumerate(oldlist):
if v[-1] != other:
outlist.remove(v)
outlist.sort(key=len)
if len(outlist) != 0:
return outlist[0]
raise ValueError('No Connecting Path found between ' + other.name +
' and ' + self.name)
def a1pt_theory(self, otherpoint, outframe, interframe):
"""Sets the acceleration of this point with the 1-point theory.
The 1-point theory for point acceleration looks like this:
^N a^P = ^B a^P + ^N a^O + ^N alpha^B x r^OP + ^N omega^B x (^N omega^B
x r^OP) + 2 ^N omega^B x ^B v^P
where O is a point fixed in B, P is a point moving in B, and B is
rotating in frame N.
Parameters
==========
otherpoint : Point
The first point of the 1-point theory (O)
outframe : ReferenceFrame
The frame we want this point's acceleration defined in (N)
fixedframe : ReferenceFrame
The intermediate frame in this calculation (B)
Examples
========
>>> from sympy.physics.vector import Point, ReferenceFrame
>>> from sympy.physics.vector import dynamicsymbols
>>> from sympy.physics.vector import init_vprinting
>>> init_vprinting(pretty_print=False)
>>> q = dynamicsymbols('q')
>>> q2 = dynamicsymbols('q2')
>>> qd = dynamicsymbols('q', 1)
>>> q2d = dynamicsymbols('q2', 1)
>>> N = ReferenceFrame('N')
>>> B = ReferenceFrame('B')
>>> B.set_ang_vel(N, 5 * B.y)
>>> O = Point('O')
>>> P = O.locatenew('P', q * B.x)
>>> P.set_vel(B, qd * B.x + q2d * B.y)
>>> O.set_vel(N, 0)
>>> P.a1pt_theory(O, N, B)
(-25*q + q'')*B.x + q2''*B.y - 10*q'*B.z
"""
_check_frame(outframe)
_check_frame(interframe)
self._check_point(otherpoint)
dist = self.pos_from(otherpoint)
v = self.vel(interframe)
a1 = otherpoint.acc(outframe)
a2 = self.acc(interframe)
omega = interframe.ang_vel_in(outframe)
alpha = interframe.ang_acc_in(outframe)
self.set_acc(outframe, a2 + 2 * (omega ^ v) + a1 + (alpha ^ dist) +
(omega ^ (omega ^ dist)))
return self.acc(outframe)
def a2pt_theory(self, otherpoint, outframe, fixedframe):
"""Sets the acceleration of this point with the 2-point theory.
The 2-point theory for point acceleration looks like this:
^N a^P = ^N a^O + ^N alpha^B x r^OP + ^N omega^B x (^N omega^B x r^OP)
where O and P are both points fixed in frame B, which is rotating in
frame N.
Parameters
==========
otherpoint : Point
The first point of the 2-point theory (O)
outframe : ReferenceFrame
The frame we want this point's acceleration defined in (N)
fixedframe : ReferenceFrame
The frame in which both points are fixed (B)
Examples
========
>>> from sympy.physics.vector import Point, ReferenceFrame, dynamicsymbols
>>> from sympy.physics.vector import init_vprinting
>>> init_vprinting(pretty_print=False)
>>> q = dynamicsymbols('q')
>>> qd = dynamicsymbols('q', 1)
>>> N = ReferenceFrame('N')
>>> B = N.orientnew('B', 'Axis', [q, N.z])
>>> O = Point('O')
>>> P = O.locatenew('P', 10 * B.x)
>>> O.set_vel(N, 5 * N.x)
>>> P.a2pt_theory(O, N, B)
- 10*q'**2*B.x + 10*q''*B.y
"""
_check_frame(outframe)
_check_frame(fixedframe)
self._check_point(otherpoint)
dist = self.pos_from(otherpoint)
a = otherpoint.acc(outframe)
omega = fixedframe.ang_vel_in(outframe)
alpha = fixedframe.ang_acc_in(outframe)
self.set_acc(outframe, a + (alpha ^ dist) + (omega ^ (omega ^ dist)))
return self.acc(outframe)
def acc(self, frame):
"""The acceleration Vector of this Point in a ReferenceFrame.
Parameters
==========
frame : ReferenceFrame
The frame in which the returned acceleration vector will be defined
in.
Examples
========
>>> from sympy.physics.vector import Point, ReferenceFrame
>>> N = ReferenceFrame('N')
>>> p1 = Point('p1')
>>> p1.set_acc(N, 10 * N.x)
>>> p1.acc(N)
10*N.x
"""
_check_frame(frame)
if not (frame in self._acc_dict):
if self.vel(frame) != 0:
return (self._vel_dict[frame]).dt(frame)
else:
return Vector(0)
return self._acc_dict[frame]
def locatenew(self, name, value):
"""Creates a new point with a position defined from this point.
Parameters
==========
name : str
The name for the new point
value : Vector
The position of the new point relative to this point
Examples
========
>>> from sympy.physics.vector import ReferenceFrame, Point
>>> N = ReferenceFrame('N')
>>> P1 = Point('P1')
>>> P2 = P1.locatenew('P2', 10 * N.x)
"""
if not isinstance(name, str):
raise TypeError('Must supply a valid name')
if value == 0:
value = Vector(0)
value = _check_vector(value)
p = Point(name)
p.set_pos(self, value)
self.set_pos(p, -value)
return p
def pos_from(self, otherpoint):
"""Returns a Vector distance between this Point and the other Point.
Parameters
==========
otherpoint : Point
The otherpoint we are locating this one relative to
Examples
========
>>> from sympy.physics.vector import Point, ReferenceFrame
>>> N = ReferenceFrame('N')
>>> p1 = Point('p1')
>>> p2 = Point('p2')
>>> p1.set_pos(p2, 10 * N.x)
>>> p1.pos_from(p2)
10*N.x
"""
outvec = Vector(0)
plist = self._pdict_list(otherpoint, 0)
for i in range(len(plist) - 1):
outvec += plist[i]._pos_dict[plist[i + 1]]
return outvec
def set_acc(self, frame, value):
"""Used to set the acceleration of this Point in a ReferenceFrame.
Parameters
==========
frame : ReferenceFrame
The frame in which this point's acceleration is defined
value : Vector
The vector value of this point's acceleration in the frame
Examples
========
>>> from sympy.physics.vector import Point, ReferenceFrame
>>> N = ReferenceFrame('N')
>>> p1 = Point('p1')
>>> p1.set_acc(N, 10 * N.x)
>>> p1.acc(N)
10*N.x
"""
if value == 0:
value = Vector(0)
value = _check_vector(value)
_check_frame(frame)
self._acc_dict.update({frame: value})
def set_pos(self, otherpoint, value):
"""Used to set the position of this point w.r.t. another point.
Parameters
==========
otherpoint : Point
The other point which this point's location is defined relative to
value : Vector
The vector which defines the location of this point
Examples
========
>>> from sympy.physics.vector import Point, ReferenceFrame
>>> N = ReferenceFrame('N')
>>> p1 = Point('p1')
>>> p2 = Point('p2')
>>> p1.set_pos(p2, 10 * N.x)
>>> p1.pos_from(p2)
10*N.x
"""
if value == 0:
value = Vector(0)
value = _check_vector(value)
self._check_point(otherpoint)
self._pos_dict.update({otherpoint: value})
otherpoint._pos_dict.update({self: -value})
def set_vel(self, frame, value):
"""Sets the velocity Vector of this Point in a ReferenceFrame.
Parameters
==========
frame : ReferenceFrame
The frame in which this point's velocity is defined
value : Vector
The vector value of this point's velocity in the frame
Examples
========
>>> from sympy.physics.vector import Point, ReferenceFrame
>>> N = ReferenceFrame('N')
>>> p1 = Point('p1')
>>> p1.set_vel(N, 10 * N.x)
>>> p1.vel(N)
10*N.x
"""
if value == 0:
value = Vector(0)
value = _check_vector(value)
_check_frame(frame)
self._vel_dict.update({frame: value})
def v1pt_theory(self, otherpoint, outframe, interframe):
"""Sets the velocity of this point with the 1-point theory.
The 1-point theory for point velocity looks like this:
^N v^P = ^B v^P + ^N v^O + ^N omega^B x r^OP
where O is a point fixed in B, P is a point moving in B, and B is
rotating in frame N.
Parameters
==========
otherpoint : Point
The first point of the 1-point theory (O)
outframe : ReferenceFrame
The frame we want this point's velocity defined in (N)
interframe : ReferenceFrame
The intermediate frame in this calculation (B)
Examples
========
>>> from sympy.physics.vector import Point, ReferenceFrame
>>> from sympy.physics.vector import dynamicsymbols
>>> from sympy.physics.vector import init_vprinting
>>> init_vprinting(pretty_print=False)
>>> q = dynamicsymbols('q')
>>> q2 = dynamicsymbols('q2')
>>> qd = dynamicsymbols('q', 1)
>>> q2d = dynamicsymbols('q2', 1)
>>> N = ReferenceFrame('N')
>>> B = ReferenceFrame('B')
>>> B.set_ang_vel(N, 5 * B.y)
>>> O = Point('O')
>>> P = O.locatenew('P', q * B.x)
>>> P.set_vel(B, qd * B.x + q2d * B.y)
>>> O.set_vel(N, 0)
>>> P.v1pt_theory(O, N, B)
q'*B.x + q2'*B.y - 5*q*B.z
"""
_check_frame(outframe)
_check_frame(interframe)
self._check_point(otherpoint)
dist = self.pos_from(otherpoint)
v1 = self.vel(interframe)
v2 = otherpoint.vel(outframe)
omega = interframe.ang_vel_in(outframe)
self.set_vel(outframe, v1 + v2 + (omega ^ dist))
return self.vel(outframe)
def v2pt_theory(self, otherpoint, outframe, fixedframe):
"""Sets the velocity of this point with the 2-point theory.
The 2-point theory for point velocity looks like this:
^N v^P = ^N v^O + ^N omega^B x r^OP
where O and P are both points fixed in frame B, which is rotating in
frame N.
Parameters
==========
otherpoint : Point
The first point of the 2-point theory (O)
outframe : ReferenceFrame
The frame we want this point's velocity defined in (N)
fixedframe : ReferenceFrame
The frame in which both points are fixed (B)
Examples
========
>>> from sympy.physics.vector import Point, ReferenceFrame, dynamicsymbols
>>> from sympy.physics.vector import init_vprinting
>>> init_vprinting(pretty_print=False)
>>> q = dynamicsymbols('q')
>>> qd = dynamicsymbols('q', 1)
>>> N = ReferenceFrame('N')
>>> B = N.orientnew('B', 'Axis', [q, N.z])
>>> O = Point('O')
>>> P = O.locatenew('P', 10 * B.x)
>>> O.set_vel(N, 5 * N.x)
>>> P.v2pt_theory(O, N, B)
5*N.x + 10*q'*B.y
"""
_check_frame(outframe)
_check_frame(fixedframe)
self._check_point(otherpoint)
dist = self.pos_from(otherpoint)
v = otherpoint.vel(outframe)
omega = fixedframe.ang_vel_in(outframe)
self.set_vel(outframe, v + (omega ^ dist))
return self.vel(outframe)
def vel(self, frame):
"""The velocity Vector of this Point in the ReferenceFrame.
Parameters
==========
frame : ReferenceFrame
The frame in which the returned velocity vector will be defined in
Examples
========
>>> from sympy.physics.vector import Point, ReferenceFrame, dynamicsymbols
>>> N = ReferenceFrame('N')
>>> p1 = Point('p1')
>>> p1.set_vel(N, 10 * N.x)
>>> p1.vel(N)
10*N.x
Velocities will be automatically calculated if possible, otherwise a
``ValueError`` will be returned. If it is possible to calculate
multiple different velocities from the relative points, the points
defined most directly relative to this point will be used. In the case
of inconsistent relative positions of points, incorrect velocities may
be returned. It is up to the user to define prior relative positions
and velocities of points in a self-consistent way.
>>> p = Point('p')
>>> q = dynamicsymbols('q')
>>> p.set_vel(N, 10 * N.x)
>>> p2 = Point('p2')
>>> p2.set_pos(p, q*N.x)
>>> p2.vel(N)
(Derivative(q(t), t) + 10)*N.x
"""
_check_frame(frame)
if not (frame in self._vel_dict):
valid_neighbor_found = False
is_cyclic = False
visited = []
queue = [self]
candidate_neighbor = []
while queue: # BFS to find nearest point
node = queue.pop(0)
if node not in visited:
visited.append(node)
for neighbor, neighbor_pos in node._pos_dict.items():
if neighbor in visited:
continue
try:
# Checks if pos vector is valid
neighbor_pos.express(frame)
except ValueError:
continue
if neighbor in queue:
is_cyclic = True
try:
# Checks if point has its vel defined in req frame
neighbor_velocity = neighbor._vel_dict[frame]
except KeyError:
queue.append(neighbor)
continue
candidate_neighbor.append(neighbor)
if not valid_neighbor_found:
self.set_vel(frame, self.pos_from(neighbor).dt(frame) + neighbor_velocity)
valid_neighbor_found = True
if is_cyclic:
warn('Kinematic loops are defined among the positions of '
'points. This is likely not desired and may cause errors '
'in your calculations.')
if len(candidate_neighbor) > 1:
warn('Velocity automatically calculated based on point ' +
candidate_neighbor[0].name +
' but it is also possible from points(s):' +
str(candidate_neighbor[1:]) +
'. Velocities from these points are not necessarily the '
'same. This may cause errors in your calculations.')
if valid_neighbor_found:
return self._vel_dict[frame]
else:
raise ValueError('Velocity of point ' + self.name +
' has not been'
' defined in ReferenceFrame ' + frame.name)
return self._vel_dict[frame]
def partial_velocity(self, frame, *gen_speeds):
"""Returns the partial velocities of the linear velocity vector of this
point in the given frame with respect to one or more provided
generalized speeds.
Parameters
==========
frame : ReferenceFrame
The frame with which the velocity is defined in.
gen_speeds : functions of time
The generalized speeds.
Returns
=======
partial_velocities : tuple of Vector
The partial velocity vectors corresponding to the provided
generalized speeds.
Examples
========
>>> from sympy.physics.vector import ReferenceFrame, Point
>>> from sympy.physics.vector import dynamicsymbols
>>> N = ReferenceFrame('N')
>>> A = ReferenceFrame('A')
>>> p = Point('p')
>>> u1, u2 = dynamicsymbols('u1, u2')
>>> p.set_vel(N, u1 * N.x + u2 * A.y)
>>> p.partial_velocity(N, u1)
N.x
>>> p.partial_velocity(N, u1, u2)
(N.x, A.y)
"""
partials = [self.vel(frame).diff(speed, frame, var_in_dcm=False) for
speed in gen_speeds]
if len(partials) == 1:
return partials[0]
else:
return tuple(partials)
|
0d6f2c8c95fe0e21432d8fb1f5824ad5859107def9fc55c29c4aba9449286650 | from sympy.core.backend import (diff, expand, sin, cos, sympify, eye, symbols,
ImmutableMatrix as Matrix, MatrixBase)
from sympy.core.symbol import (Dummy, Symbol)
from sympy.simplify.trigsimp import trigsimp
from sympy.solvers.solvers import solve
from sympy.physics.vector.vector import Vector, _check_vector
from sympy.utilities.misc import translate
from warnings import warn
__all__ = ['CoordinateSym', 'ReferenceFrame']
class CoordinateSym(Symbol):
"""
A coordinate symbol/base scalar associated wrt a Reference Frame.
Ideally, users should not instantiate this class. Instances of
this class must only be accessed through the corresponding frame
as 'frame[index]'.
CoordinateSyms having the same frame and index parameters are equal
(even though they may be instantiated separately).
Parameters
==========
name : string
The display name of the CoordinateSym
frame : ReferenceFrame
The reference frame this base scalar belongs to
index : 0, 1 or 2
The index of the dimension denoted by this coordinate variable
Examples
========
>>> from sympy.physics.vector import ReferenceFrame, CoordinateSym
>>> A = ReferenceFrame('A')
>>> A[1]
A_y
>>> type(A[0])
<class 'sympy.physics.vector.frame.CoordinateSym'>
>>> a_y = CoordinateSym('a_y', A, 1)
>>> a_y == A[1]
True
"""
def __new__(cls, name, frame, index):
# We can't use the cached Symbol.__new__ because this class depends on
# frame and index, which are not passed to Symbol.__xnew__.
assumptions = {}
super()._sanitize(assumptions, cls)
obj = super().__xnew__(cls, name, **assumptions)
_check_frame(frame)
if index not in range(0, 3):
raise ValueError("Invalid index specified")
obj._id = (frame, index)
return obj
@property
def frame(self):
return self._id[0]
def __eq__(self, other):
# Check if the other object is a CoordinateSym of the same frame and
# same index
if isinstance(other, CoordinateSym):
if other._id == self._id:
return True
return False
def __ne__(self, other):
return not self == other
def __hash__(self):
return tuple((self._id[0].__hash__(), self._id[1])).__hash__()
class ReferenceFrame:
"""A reference frame in classical mechanics.
ReferenceFrame is a class used to represent a reference frame in classical
mechanics. It has a standard basis of three unit vectors in the frame's
x, y, and z directions.
It also can have a rotation relative to a parent frame; this rotation is
defined by a direction cosine matrix relating this frame's basis vectors to
the parent frame's basis vectors. It can also have an angular velocity
vector, defined in another frame.
"""
_count = 0
def __init__(self, name, indices=None, latexs=None, variables=None):
"""ReferenceFrame initialization method.
A ReferenceFrame has a set of orthonormal basis vectors, along with
orientations relative to other ReferenceFrames and angular velocities
relative to other ReferenceFrames.
Parameters
==========
indices : tuple of str
Enables the reference frame's basis unit vectors to be accessed by
Python's square bracket indexing notation using the provided three
indice strings and alters the printing of the unit vectors to
reflect this choice.
latexs : tuple of str
Alters the LaTeX printing of the reference frame's basis unit
vectors to the provided three valid LaTeX strings.
Examples
========
>>> from sympy.physics.vector import ReferenceFrame, vlatex
>>> N = ReferenceFrame('N')
>>> N.x
N.x
>>> O = ReferenceFrame('O', indices=('1', '2', '3'))
>>> O.x
O['1']
>>> O['1']
O['1']
>>> P = ReferenceFrame('P', latexs=('A1', 'A2', 'A3'))
>>> vlatex(P.x)
'A1'
``symbols()`` can be used to create multiple Reference Frames in one
step, for example:
>>> from sympy.physics.vector import ReferenceFrame
>>> from sympy import symbols
>>> A, B, C = symbols('A B C', cls=ReferenceFrame)
>>> D, E = symbols('D E', cls=ReferenceFrame, indices=('1', '2', '3'))
>>> A[0]
A_x
>>> D.x
D['1']
>>> E.y
E['2']
>>> type(A) == type(D)
True
"""
if not isinstance(name, str):
raise TypeError('Need to supply a valid name')
# The if statements below are for custom printing of basis-vectors for
# each frame.
# First case, when custom indices are supplied
if indices is not None:
if not isinstance(indices, (tuple, list)):
raise TypeError('Supply the indices as a list')
if len(indices) != 3:
raise ValueError('Supply 3 indices')
for i in indices:
if not isinstance(i, str):
raise TypeError('Indices must be strings')
self.str_vecs = [(name + '[\'' + indices[0] + '\']'),
(name + '[\'' + indices[1] + '\']'),
(name + '[\'' + indices[2] + '\']')]
self.pretty_vecs = [(name.lower() + "_" + indices[0]),
(name.lower() + "_" + indices[1]),
(name.lower() + "_" + indices[2])]
self.latex_vecs = [(r"\mathbf{\hat{%s}_{%s}}" % (name.lower(),
indices[0])),
(r"\mathbf{\hat{%s}_{%s}}" % (name.lower(),
indices[1])),
(r"\mathbf{\hat{%s}_{%s}}" % (name.lower(),
indices[2]))]
self.indices = indices
# Second case, when no custom indices are supplied
else:
self.str_vecs = [(name + '.x'), (name + '.y'), (name + '.z')]
self.pretty_vecs = [name.lower() + "_x",
name.lower() + "_y",
name.lower() + "_z"]
self.latex_vecs = [(r"\mathbf{\hat{%s}_x}" % name.lower()),
(r"\mathbf{\hat{%s}_y}" % name.lower()),
(r"\mathbf{\hat{%s}_z}" % name.lower())]
self.indices = ['x', 'y', 'z']
# Different step, for custom latex basis vectors
if latexs is not None:
if not isinstance(latexs, (tuple, list)):
raise TypeError('Supply the indices as a list')
if len(latexs) != 3:
raise ValueError('Supply 3 indices')
for i in latexs:
if not isinstance(i, str):
raise TypeError('Latex entries must be strings')
self.latex_vecs = latexs
self.name = name
self._var_dict = {}
# The _dcm_dict dictionary will only store the dcms of adjacent
# parent-child relationships. The _dcm_cache dictionary will store
# calculated dcm along with all content of _dcm_dict for faster
# retrieval of dcms.
self._dcm_dict = {}
self._dcm_cache = {}
self._ang_vel_dict = {}
self._ang_acc_dict = {}
self._dlist = [self._dcm_dict, self._ang_vel_dict, self._ang_acc_dict]
self._cur = 0
self._x = Vector([(Matrix([1, 0, 0]), self)])
self._y = Vector([(Matrix([0, 1, 0]), self)])
self._z = Vector([(Matrix([0, 0, 1]), self)])
# Associate coordinate symbols wrt this frame
if variables is not None:
if not isinstance(variables, (tuple, list)):
raise TypeError('Supply the variable names as a list/tuple')
if len(variables) != 3:
raise ValueError('Supply 3 variable names')
for i in variables:
if not isinstance(i, str):
raise TypeError('Variable names must be strings')
else:
variables = [name + '_x', name + '_y', name + '_z']
self.varlist = (CoordinateSym(variables[0], self, 0),
CoordinateSym(variables[1], self, 1),
CoordinateSym(variables[2], self, 2))
ReferenceFrame._count += 1
self.index = ReferenceFrame._count
def __getitem__(self, ind):
"""
Returns basis vector for the provided index, if the index is a string.
If the index is a number, returns the coordinate variable correspon-
-ding to that index.
"""
if not isinstance(ind, str):
if ind < 3:
return self.varlist[ind]
else:
raise ValueError("Invalid index provided")
if self.indices[0] == ind:
return self.x
if self.indices[1] == ind:
return self.y
if self.indices[2] == ind:
return self.z
else:
raise ValueError('Not a defined index')
def __iter__(self):
return iter([self.x, self.y, self.z])
def __str__(self):
"""Returns the name of the frame. """
return self.name
__repr__ = __str__
def _dict_list(self, other, num):
"""Returns an inclusive list of reference frames that connect this
reference frame to the provided reference frame.
Parameters
==========
other : ReferenceFrame
The other reference frame to look for a connecting relationship to.
num : integer
``0``, ``1``, and ``2`` will look for orientation, angular
velocity, and angular acceleration relationships between the two
frames, respectively.
Returns
=======
list
Inclusive list of reference frames that connect this reference
frame to the other reference frame.
Examples
========
>>> from sympy.physics.vector import ReferenceFrame
>>> A = ReferenceFrame('A')
>>> B = ReferenceFrame('B')
>>> C = ReferenceFrame('C')
>>> D = ReferenceFrame('D')
>>> B.orient_axis(A, A.x, 1.0)
>>> C.orient_axis(B, B.x, 1.0)
>>> D.orient_axis(C, C.x, 1.0)
>>> D._dict_list(A, 0)
[D, C, B, A]
Raises
======
ValueError
When no path is found between the two reference frames or ``num``
is an incorrect value.
"""
connect_type = {0: 'orientation',
1: 'angular velocity',
2: 'angular acceleration'}
if num not in connect_type.keys():
raise ValueError('Valid values for num are 0, 1, or 2.')
possible_connecting_paths = [[self]]
oldlist = [[]]
while possible_connecting_paths != oldlist:
oldlist = possible_connecting_paths[:] # make a copy
for frame_list in possible_connecting_paths:
frames_adjacent_to_last = frame_list[-1]._dlist[num].keys()
for adjacent_frame in frames_adjacent_to_last:
if adjacent_frame not in frame_list:
connecting_path = frame_list + [adjacent_frame]
if connecting_path not in possible_connecting_paths:
possible_connecting_paths.append(connecting_path)
for connecting_path in oldlist:
if connecting_path[-1] != other:
possible_connecting_paths.remove(connecting_path)
possible_connecting_paths.sort(key=len)
if len(possible_connecting_paths) != 0:
return possible_connecting_paths[0] # selects the shortest path
msg = 'No connecting {} path found between {} and {}.'
raise ValueError(msg.format(connect_type[num], self.name, other.name))
def _w_diff_dcm(self, otherframe):
"""Angular velocity from time differentiating the DCM. """
from sympy.physics.vector.functions import dynamicsymbols
dcm2diff = otherframe.dcm(self)
diffed = dcm2diff.diff(dynamicsymbols._t)
angvelmat = diffed * dcm2diff.T
w1 = trigsimp(expand(angvelmat[7]), recursive=True)
w2 = trigsimp(expand(angvelmat[2]), recursive=True)
w3 = trigsimp(expand(angvelmat[3]), recursive=True)
return Vector([(Matrix([w1, w2, w3]), otherframe)])
def variable_map(self, otherframe):
"""
Returns a dictionary which expresses the coordinate variables
of this frame in terms of the variables of otherframe.
If Vector.simp is True, returns a simplified version of the mapped
values. Else, returns them without simplification.
Simplification of the expressions may take time.
Parameters
==========
otherframe : ReferenceFrame
The other frame to map the variables to
Examples
========
>>> from sympy.physics.vector import ReferenceFrame, dynamicsymbols
>>> A = ReferenceFrame('A')
>>> q = dynamicsymbols('q')
>>> B = A.orientnew('B', 'Axis', [q, A.z])
>>> A.variable_map(B)
{A_x: B_x*cos(q(t)) - B_y*sin(q(t)), A_y: B_x*sin(q(t)) + B_y*cos(q(t)), A_z: B_z}
"""
_check_frame(otherframe)
if (otherframe, Vector.simp) in self._var_dict:
return self._var_dict[(otherframe, Vector.simp)]
else:
vars_matrix = self.dcm(otherframe) * Matrix(otherframe.varlist)
mapping = {}
for i, x in enumerate(self):
if Vector.simp:
mapping[self.varlist[i]] = trigsimp(vars_matrix[i],
method='fu')
else:
mapping[self.varlist[i]] = vars_matrix[i]
self._var_dict[(otherframe, Vector.simp)] = mapping
return mapping
def ang_acc_in(self, otherframe):
"""Returns the angular acceleration Vector of the ReferenceFrame.
Effectively returns the Vector:
``N_alpha_B``
which represent the angular acceleration of B in N, where B is self,
and N is otherframe.
Parameters
==========
otherframe : ReferenceFrame
The ReferenceFrame which the angular acceleration is returned in.
Examples
========
>>> from sympy.physics.vector import ReferenceFrame
>>> N = ReferenceFrame('N')
>>> A = ReferenceFrame('A')
>>> V = 10 * N.x
>>> A.set_ang_acc(N, V)
>>> A.ang_acc_in(N)
10*N.x
"""
_check_frame(otherframe)
if otherframe in self._ang_acc_dict:
return self._ang_acc_dict[otherframe]
else:
return self.ang_vel_in(otherframe).dt(otherframe)
def ang_vel_in(self, otherframe):
"""Returns the angular velocity Vector of the ReferenceFrame.
Effectively returns the Vector:
^N omega ^B
which represent the angular velocity of B in N, where B is self, and
N is otherframe.
Parameters
==========
otherframe : ReferenceFrame
The ReferenceFrame which the angular velocity is returned in.
Examples
========
>>> from sympy.physics.vector import ReferenceFrame
>>> N = ReferenceFrame('N')
>>> A = ReferenceFrame('A')
>>> V = 10 * N.x
>>> A.set_ang_vel(N, V)
>>> A.ang_vel_in(N)
10*N.x
"""
_check_frame(otherframe)
flist = self._dict_list(otherframe, 1)
outvec = Vector(0)
for i in range(len(flist) - 1):
outvec += flist[i]._ang_vel_dict[flist[i + 1]]
return outvec
def dcm(self, otherframe):
r"""Returns the direction cosine matrix of this reference frame
relative to the provided reference frame.
The returned matrix can be used to express the orthogonal unit vectors
of this frame in terms of the orthogonal unit vectors of
``otherframe``.
Parameters
==========
otherframe : ReferenceFrame
The reference frame which the direction cosine matrix of this frame
is formed relative to.
Examples
========
The following example rotates the reference frame A relative to N by a
simple rotation and then calculates the direction cosine matrix of N
relative to A.
>>> from sympy import symbols, sin, cos
>>> from sympy.physics.vector import ReferenceFrame
>>> q1 = symbols('q1')
>>> N = ReferenceFrame('N')
>>> A = ReferenceFrame('A')
>>> A.orient_axis(N, q1, N.x)
>>> N.dcm(A)
Matrix([
[1, 0, 0],
[0, cos(q1), -sin(q1)],
[0, sin(q1), cos(q1)]])
The second row of the above direction cosine matrix represents the
``N.y`` unit vector in N expressed in A. Like so:
>>> Ny = 0*A.x + cos(q1)*A.y - sin(q1)*A.z
Thus, expressing ``N.y`` in A should return the same result:
>>> N.y.express(A)
cos(q1)*A.y - sin(q1)*A.z
Notes
=====
It is important to know what form of the direction cosine matrix is
returned. If ``B.dcm(A)`` is called, it means the "direction cosine
matrix of B rotated relative to A". This is the matrix
:math:`{}^B\mathbf{C}^A` shown in the following relationship:
.. math::
\begin{bmatrix}
\hat{\mathbf{b}}_1 \\
\hat{\mathbf{b}}_2 \\
\hat{\mathbf{b}}_3
\end{bmatrix}
=
{}^B\mathbf{C}^A
\begin{bmatrix}
\hat{\mathbf{a}}_1 \\
\hat{\mathbf{a}}_2 \\
\hat{\mathbf{a}}_3
\end{bmatrix}.
:math:`{}^B\mathbf{C}^A` is the matrix that expresses the B unit
vectors in terms of the A unit vectors.
"""
_check_frame(otherframe)
# Check if the dcm wrt that frame has already been calculated
if otherframe in self._dcm_cache:
return self._dcm_cache[otherframe]
flist = self._dict_list(otherframe, 0)
outdcm = eye(3)
for i in range(len(flist) - 1):
outdcm = outdcm * flist[i]._dcm_dict[flist[i + 1]]
# After calculation, store the dcm in dcm cache for faster future
# retrieval
self._dcm_cache[otherframe] = outdcm
otherframe._dcm_cache[self] = outdcm.T
return outdcm
def _dcm(self, parent, parent_orient):
# If parent.oreint(self) is already defined,then
# update the _dcm_dict of parent while over write
# all content of self._dcm_dict and self._dcm_cache
# with new dcm relation.
# Else update _dcm_cache and _dcm_dict of both
# self and parent.
frames = self._dcm_cache.keys()
dcm_dict_del = []
dcm_cache_del = []
if parent in frames:
for frame in frames:
if frame in self._dcm_dict:
dcm_dict_del += [frame]
dcm_cache_del += [frame]
# Reset the _dcm_cache of this frame, and remove it from the
# _dcm_caches of the frames it is linked to. Also remove it from
# the _dcm_dict of its parent
for frame in dcm_dict_del:
del frame._dcm_dict[self]
for frame in dcm_cache_del:
del frame._dcm_cache[self]
# Reset the _dcm_dict
self._dcm_dict = self._dlist[0] = {}
# Reset the _dcm_cache
self._dcm_cache = {}
else:
# Check for loops and raise warning accordingly.
visited = []
queue = list(frames)
cont = True # Flag to control queue loop.
while queue and cont:
node = queue.pop(0)
if node not in visited:
visited.append(node)
neighbors = node._dcm_dict.keys()
for neighbor in neighbors:
if neighbor == parent:
warn('Loops are defined among the orientation of '
'frames. This is likely not desired and may '
'cause errors in your calculations.')
cont = False
break
queue.append(neighbor)
# Add the dcm relationship to _dcm_dict
self._dcm_dict.update({parent: parent_orient.T})
parent._dcm_dict.update({self: parent_orient})
# Update the dcm cache
self._dcm_cache.update({parent: parent_orient.T})
parent._dcm_cache.update({self: parent_orient})
def orient_axis(self, parent, axis, angle):
"""Sets the orientation of this reference frame with respect to a
parent reference frame by rotating through an angle about an axis fixed
in the parent reference frame.
Parameters
==========
parent : ReferenceFrame
Reference frame that this reference frame will be rotated relative
to.
axis : Vector
Vector fixed in the parent frame about about which this frame is
rotated. It need not be a unit vector and the rotation follows the
right hand rule.
angle : sympifiable
Angle in radians by which it the frame is to be rotated.
Warns
======
UserWarning
If the orientation creates a kinematic loop.
Examples
========
Setup variables for the examples:
>>> from sympy import symbols
>>> from sympy.physics.vector import ReferenceFrame
>>> q1 = symbols('q1')
>>> N = ReferenceFrame('N')
>>> B = ReferenceFrame('B')
>>> B.orient_axis(N, N.x, q1)
The ``orient_axis()`` method generates a direction cosine matrix and
its transpose which defines the orientation of B relative to N and vice
versa. Once orient is called, ``dcm()`` outputs the appropriate
direction cosine matrix:
>>> B.dcm(N)
Matrix([
[1, 0, 0],
[0, cos(q1), sin(q1)],
[0, -sin(q1), cos(q1)]])
>>> N.dcm(B)
Matrix([
[1, 0, 0],
[0, cos(q1), -sin(q1)],
[0, sin(q1), cos(q1)]])
The following two lines show that the sense of the rotation can be
defined by negating the vector direction or the angle. Both lines
produce the same result.
>>> B.orient_axis(N, -N.x, q1)
>>> B.orient_axis(N, N.x, -q1)
"""
from sympy.physics.vector.functions import dynamicsymbols
_check_frame(parent)
if not isinstance(axis, Vector) and isinstance(angle, Vector):
axis, angle = angle, axis
axis = _check_vector(axis)
theta = sympify(angle)
parent_orient_axis = []
if not axis.dt(parent) == 0:
raise ValueError('Axis cannot be time-varying.')
unit_axis = axis.express(parent).normalize()
unit_col = unit_axis.args[0][0]
parent_orient_axis = (
(eye(3) - unit_col * unit_col.T) * cos(theta) +
Matrix([[0, -unit_col[2], unit_col[1]],
[unit_col[2], 0, -unit_col[0]],
[-unit_col[1], unit_col[0], 0]]) *
sin(theta) + unit_col * unit_col.T)
self._dcm(parent, parent_orient_axis)
thetad = (theta).diff(dynamicsymbols._t)
wvec = thetad*axis.express(parent).normalize()
self._ang_vel_dict.update({parent: wvec})
parent._ang_vel_dict.update({self: -wvec})
self._var_dict = {}
def orient_explicit(self, parent, dcm):
"""Sets the orientation of this reference frame relative to a parent
reference frame by explicitly setting the direction cosine matrix.
Parameters
==========
parent : ReferenceFrame
Reference frame that this reference frame will be rotated relative
to.
dcm : Matrix, shape(3, 3)
Direction cosine matrix that specifies the relative rotation
between the two reference frames.
Warns
======
UserWarning
If the orientation creates a kinematic loop.
Examples
========
Setup variables for the examples:
>>> from sympy import symbols, Matrix, sin, cos
>>> from sympy.physics.vector import ReferenceFrame
>>> q1 = symbols('q1')
>>> A = ReferenceFrame('A')
>>> B = ReferenceFrame('B')
>>> N = ReferenceFrame('N')
A simple rotation of ``A`` relative to ``N`` about ``N.x`` is defined
by the following direction cosine matrix:
>>> dcm = Matrix([[1, 0, 0],
... [0, cos(q1), -sin(q1)],
... [0, sin(q1), cos(q1)]])
>>> A.orient_explicit(N, dcm)
>>> A.dcm(N)
Matrix([
[1, 0, 0],
[0, cos(q1), sin(q1)],
[0, -sin(q1), cos(q1)]])
This is equivalent to using ``orient_axis()``:
>>> B.orient_axis(N, N.x, q1)
>>> B.dcm(N)
Matrix([
[1, 0, 0],
[0, cos(q1), sin(q1)],
[0, -sin(q1), cos(q1)]])
**Note carefully that** ``N.dcm(B)`` **(the transpose) would be passed
into** ``orient_explicit()`` **for** ``A.dcm(N)`` **to match**
``B.dcm(N)``:
>>> A.orient_explicit(N, N.dcm(B))
>>> A.dcm(N)
Matrix([
[1, 0, 0],
[0, cos(q1), sin(q1)],
[0, -sin(q1), cos(q1)]])
"""
_check_frame(parent)
# amounts must be a Matrix type object
# (e.g. sympy.matrices.dense.MutableDenseMatrix).
if not isinstance(dcm, MatrixBase):
raise TypeError("Amounts must be a SymPy Matrix type object.")
parent_orient_dcm = []
parent_orient_dcm = dcm
self._dcm(parent, parent_orient_dcm)
wvec = self._w_diff_dcm(parent)
self._ang_vel_dict.update({parent: wvec})
parent._ang_vel_dict.update({self: -wvec})
self._var_dict = {}
def _rot(self, axis, angle):
"""DCM for simple axis 1,2,or 3 rotations."""
if axis == 1:
return Matrix([[1, 0, 0],
[0, cos(angle), -sin(angle)],
[0, sin(angle), cos(angle)]])
elif axis == 2:
return Matrix([[cos(angle), 0, sin(angle)],
[0, 1, 0],
[-sin(angle), 0, cos(angle)]])
elif axis == 3:
return Matrix([[cos(angle), -sin(angle), 0],
[sin(angle), cos(angle), 0],
[0, 0, 1]])
def orient_body_fixed(self, parent, angles, rotation_order):
"""Rotates this reference frame relative to the parent reference frame
by right hand rotating through three successive body fixed simple axis
rotations. Each subsequent axis of rotation is about the "body fixed"
unit vectors of a new intermediate reference frame. This type of
rotation is also referred to rotating through the `Euler and Tait-Bryan
Angles`_.
.. _Euler and Tait-Bryan Angles: https://en.wikipedia.org/wiki/Euler_angles
Parameters
==========
parent : ReferenceFrame
Reference frame that this reference frame will be rotated relative
to.
angles : 3-tuple of sympifiable
Three angles in radians used for the successive rotations.
rotation_order : 3 character string or 3 digit integer
Order of the rotations about each intermediate reference frames'
unit vectors. The Euler rotation about the X, Z', X'' axes can be
specified by the strings ``'XZX'``, ``'131'``, or the integer
``131``. There are 12 unique valid rotation orders (6 Euler and 6
Tait-Bryan): zxz, xyx, yzy, zyz, xzx, yxy, xyz, yzx, zxy, xzy, zyx,
and yxz.
Warns
======
UserWarning
If the orientation creates a kinematic loop.
Examples
========
Setup variables for the examples:
>>> from sympy import symbols
>>> from sympy.physics.vector import ReferenceFrame
>>> q1, q2, q3 = symbols('q1, q2, q3')
>>> N = ReferenceFrame('N')
>>> B = ReferenceFrame('B')
>>> B1 = ReferenceFrame('B1')
>>> B2 = ReferenceFrame('B2')
>>> B3 = ReferenceFrame('B3')
For example, a classic Euler Angle rotation can be done by:
>>> B.orient_body_fixed(N, (q1, q2, q3), 'XYX')
>>> B.dcm(N)
Matrix([
[ cos(q2), sin(q1)*sin(q2), -sin(q2)*cos(q1)],
[sin(q2)*sin(q3), -sin(q1)*sin(q3)*cos(q2) + cos(q1)*cos(q3), sin(q1)*cos(q3) + sin(q3)*cos(q1)*cos(q2)],
[sin(q2)*cos(q3), -sin(q1)*cos(q2)*cos(q3) - sin(q3)*cos(q1), -sin(q1)*sin(q3) + cos(q1)*cos(q2)*cos(q3)]])
This rotates reference frame B relative to reference frame N through
``q1`` about ``N.x``, then rotates B again through ``q2`` about
``B.y``, and finally through ``q3`` about ``B.x``. It is equivalent to
three successive ``orient_axis()`` calls:
>>> B1.orient_axis(N, N.x, q1)
>>> B2.orient_axis(B1, B1.y, q2)
>>> B3.orient_axis(B2, B2.x, q3)
>>> B3.dcm(N)
Matrix([
[ cos(q2), sin(q1)*sin(q2), -sin(q2)*cos(q1)],
[sin(q2)*sin(q3), -sin(q1)*sin(q3)*cos(q2) + cos(q1)*cos(q3), sin(q1)*cos(q3) + sin(q3)*cos(q1)*cos(q2)],
[sin(q2)*cos(q3), -sin(q1)*cos(q2)*cos(q3) - sin(q3)*cos(q1), -sin(q1)*sin(q3) + cos(q1)*cos(q2)*cos(q3)]])
Acceptable rotation orders are of length 3, expressed in as a string
``'XYZ'`` or ``'123'`` or integer ``123``. Rotations about an axis
twice in a row are prohibited.
>>> B.orient_body_fixed(N, (q1, q2, 0), 'ZXZ')
>>> B.orient_body_fixed(N, (q1, q2, 0), '121')
>>> B.orient_body_fixed(N, (q1, q2, q3), 123)
"""
_check_frame(parent)
amounts = list(angles)
for i, v in enumerate(amounts):
if not isinstance(v, Vector):
amounts[i] = sympify(v)
approved_orders = ('123', '231', '312', '132', '213', '321', '121',
'131', '212', '232', '313', '323', '')
# make sure XYZ => 123
rot_order = translate(str(rotation_order), 'XYZxyz', '123123')
if rot_order not in approved_orders:
raise TypeError('The rotation order is not a valid order.')
parent_orient_body = []
if not (len(amounts) == 3 & len(rot_order) == 3):
raise TypeError('Body orientation takes 3 values & 3 orders')
a1 = int(rot_order[0])
a2 = int(rot_order[1])
a3 = int(rot_order[2])
parent_orient_body = (self._rot(a1, amounts[0]) *
self._rot(a2, amounts[1]) *
self._rot(a3, amounts[2]))
self._dcm(parent, parent_orient_body)
try:
from sympy.polys.polyerrors import CoercionFailed
from sympy.physics.vector.functions import kinematic_equations
q1, q2, q3 = amounts
u1, u2, u3 = symbols('u1, u2, u3', cls=Dummy)
templist = kinematic_equations([u1, u2, u3], [q1, q2, q3],
'body', rot_order)
templist = [expand(i) for i in templist]
td = solve(templist, [u1, u2, u3])
u1 = expand(td[u1])
u2 = expand(td[u2])
u3 = expand(td[u3])
wvec = u1 * self.x + u2 * self.y + u3 * self.z
# NOTE : SymPy 1.7 removed the call to simplify() that occured
# inside the solve() function, so this restores the pre-1.7
# behavior. See:
# https://github.com/sympy/sympy/issues/23140
# and
# https://github.com/sympy/sympy/issues/23130
wvec = wvec.simplify()
except (CoercionFailed, AssertionError):
wvec = self._w_diff_dcm(parent)
self._ang_vel_dict.update({parent: wvec})
parent._ang_vel_dict.update({self: -wvec})
self._var_dict = {}
def orient_space_fixed(self, parent, angles, rotation_order):
"""Rotates this reference frame relative to the parent reference frame
by right hand rotating through three successive space fixed simple axis
rotations. Each subsequent axis of rotation is about the "space fixed"
unit vectors of the parent reference frame.
Parameters
==========
parent : ReferenceFrame
Reference frame that this reference frame will be rotated relative
to.
angles : 3-tuple of sympifiable
Three angles in radians used for the successive rotations.
rotation_order : 3 character string or 3 digit integer
Order of the rotations about the parent reference frame's unit
vectors. The order can be specified by the strings ``'XZX'``,
``'131'``, or the integer ``131``. There are 12 unique valid
rotation orders.
Warns
======
UserWarning
If the orientation creates a kinematic loop.
Examples
========
Setup variables for the examples:
>>> from sympy import symbols
>>> from sympy.physics.vector import ReferenceFrame
>>> q1, q2, q3 = symbols('q1, q2, q3')
>>> N = ReferenceFrame('N')
>>> B = ReferenceFrame('B')
>>> B1 = ReferenceFrame('B1')
>>> B2 = ReferenceFrame('B2')
>>> B3 = ReferenceFrame('B3')
>>> B.orient_space_fixed(N, (q1, q2, q3), '312')
>>> B.dcm(N)
Matrix([
[ sin(q1)*sin(q2)*sin(q3) + cos(q1)*cos(q3), sin(q1)*cos(q2), sin(q1)*sin(q2)*cos(q3) - sin(q3)*cos(q1)],
[-sin(q1)*cos(q3) + sin(q2)*sin(q3)*cos(q1), cos(q1)*cos(q2), sin(q1)*sin(q3) + sin(q2)*cos(q1)*cos(q3)],
[ sin(q3)*cos(q2), -sin(q2), cos(q2)*cos(q3)]])
is equivalent to:
>>> B1.orient_axis(N, N.z, q1)
>>> B2.orient_axis(B1, N.x, q2)
>>> B3.orient_axis(B2, N.y, q3)
>>> B3.dcm(N).simplify()
Matrix([
[ sin(q1)*sin(q2)*sin(q3) + cos(q1)*cos(q3), sin(q1)*cos(q2), sin(q1)*sin(q2)*cos(q3) - sin(q3)*cos(q1)],
[-sin(q1)*cos(q3) + sin(q2)*sin(q3)*cos(q1), cos(q1)*cos(q2), sin(q1)*sin(q3) + sin(q2)*cos(q1)*cos(q3)],
[ sin(q3)*cos(q2), -sin(q2), cos(q2)*cos(q3)]])
It is worth noting that space-fixed and body-fixed rotations are
related by the order of the rotations, i.e. the reverse order of body
fixed will give space fixed and vice versa.
>>> B.orient_space_fixed(N, (q1, q2, q3), '231')
>>> B.dcm(N)
Matrix([
[cos(q1)*cos(q2), sin(q1)*sin(q3) + sin(q2)*cos(q1)*cos(q3), -sin(q1)*cos(q3) + sin(q2)*sin(q3)*cos(q1)],
[ -sin(q2), cos(q2)*cos(q3), sin(q3)*cos(q2)],
[sin(q1)*cos(q2), sin(q1)*sin(q2)*cos(q3) - sin(q3)*cos(q1), sin(q1)*sin(q2)*sin(q3) + cos(q1)*cos(q3)]])
>>> B.orient_body_fixed(N, (q3, q2, q1), '132')
>>> B.dcm(N)
Matrix([
[cos(q1)*cos(q2), sin(q1)*sin(q3) + sin(q2)*cos(q1)*cos(q3), -sin(q1)*cos(q3) + sin(q2)*sin(q3)*cos(q1)],
[ -sin(q2), cos(q2)*cos(q3), sin(q3)*cos(q2)],
[sin(q1)*cos(q2), sin(q1)*sin(q2)*cos(q3) - sin(q3)*cos(q1), sin(q1)*sin(q2)*sin(q3) + cos(q1)*cos(q3)]])
"""
_check_frame(parent)
amounts = list(angles)
for i, v in enumerate(amounts):
if not isinstance(v, Vector):
amounts[i] = sympify(v)
approved_orders = ('123', '231', '312', '132', '213', '321', '121',
'131', '212', '232', '313', '323', '')
# make sure XYZ => 123
rot_order = translate(str(rotation_order), 'XYZxyz', '123123')
if rot_order not in approved_orders:
raise TypeError('The supplied order is not an approved type')
parent_orient_space = []
if not (len(amounts) == 3 & len(rot_order) == 3):
raise TypeError('Space orientation takes 3 values & 3 orders')
a1 = int(rot_order[0])
a2 = int(rot_order[1])
a3 = int(rot_order[2])
parent_orient_space = (self._rot(a3, amounts[2]) *
self._rot(a2, amounts[1]) *
self._rot(a1, amounts[0]))
self._dcm(parent, parent_orient_space)
try:
from sympy.polys.polyerrors import CoercionFailed
from sympy.physics.vector.functions import kinematic_equations
q1, q2, q3 = amounts
u1, u2, u3 = symbols('u1, u2, u3', cls=Dummy)
templist = kinematic_equations([u1, u2, u3], [q1, q2, q3],
'space', rot_order)
templist = [expand(i) for i in templist]
td = solve(templist, [u1, u2, u3])
u1 = expand(td[u1])
u2 = expand(td[u2])
u3 = expand(td[u3])
wvec = u1 * self.x + u2 * self.y + u3 * self.z
except (CoercionFailed, AssertionError):
wvec = self._w_diff_dcm(parent)
self._ang_vel_dict.update({parent: wvec})
parent._ang_vel_dict.update({self: -wvec})
self._var_dict = {}
def orient_quaternion(self, parent, numbers):
"""Sets the orientation of this reference frame relative to a parent
reference frame via an orientation quaternion. An orientation
quaternion is defined as a finite rotation a unit vector, ``(lambda_x,
lambda_y, lambda_z)``, by an angle ``theta``. The orientation
quaternion is described by four parameters:
- ``q0 = cos(theta/2)``
- ``q1 = lambda_x*sin(theta/2)``
- ``q2 = lambda_y*sin(theta/2)``
- ``q3 = lambda_z*sin(theta/2)``
See `Quaternions and Spatial Rotation
<https://en.wikipedia.org/wiki/Quaternions_and_spatial_rotation>`_ on
Wikipedia for more information.
Parameters
==========
parent : ReferenceFrame
Reference frame that this reference frame will be rotated relative
to.
numbers : 4-tuple of sympifiable
The four quaternion scalar numbers as defined above: ``q0``,
``q1``, ``q2``, ``q3``.
Warns
======
UserWarning
If the orientation creates a kinematic loop.
Examples
========
Setup variables for the examples:
>>> from sympy import symbols
>>> from sympy.physics.vector import ReferenceFrame
>>> q0, q1, q2, q3 = symbols('q0 q1 q2 q3')
>>> N = ReferenceFrame('N')
>>> B = ReferenceFrame('B')
Set the orientation:
>>> B.orient_quaternion(N, (q0, q1, q2, q3))
>>> B.dcm(N)
Matrix([
[q0**2 + q1**2 - q2**2 - q3**2, 2*q0*q3 + 2*q1*q2, -2*q0*q2 + 2*q1*q3],
[ -2*q0*q3 + 2*q1*q2, q0**2 - q1**2 + q2**2 - q3**2, 2*q0*q1 + 2*q2*q3],
[ 2*q0*q2 + 2*q1*q3, -2*q0*q1 + 2*q2*q3, q0**2 - q1**2 - q2**2 + q3**2]])
"""
from sympy.physics.vector.functions import dynamicsymbols
_check_frame(parent)
numbers = list(numbers)
for i, v in enumerate(numbers):
if not isinstance(v, Vector):
numbers[i] = sympify(v)
parent_orient_quaternion = []
if not (isinstance(numbers, (list, tuple)) & (len(numbers) == 4)):
raise TypeError('Amounts are a list or tuple of length 4')
q0, q1, q2, q3 = numbers
parent_orient_quaternion = (
Matrix([[q0**2 + q1**2 - q2**2 - q3**2,
2 * (q1 * q2 - q0 * q3),
2 * (q0 * q2 + q1 * q3)],
[2 * (q1 * q2 + q0 * q3),
q0**2 - q1**2 + q2**2 - q3**2,
2 * (q2 * q3 - q0 * q1)],
[2 * (q1 * q3 - q0 * q2),
2 * (q0 * q1 + q2 * q3),
q0**2 - q1**2 - q2**2 + q3**2]]))
self._dcm(parent, parent_orient_quaternion)
t = dynamicsymbols._t
q0, q1, q2, q3 = numbers
q0d = diff(q0, t)
q1d = diff(q1, t)
q2d = diff(q2, t)
q3d = diff(q3, t)
w1 = 2 * (q1d * q0 + q2d * q3 - q3d * q2 - q0d * q1)
w2 = 2 * (q2d * q0 + q3d * q1 - q1d * q3 - q0d * q2)
w3 = 2 * (q3d * q0 + q1d * q2 - q2d * q1 - q0d * q3)
wvec = Vector([(Matrix([w1, w2, w3]), self)])
self._ang_vel_dict.update({parent: wvec})
parent._ang_vel_dict.update({self: -wvec})
self._var_dict = {}
def orient(self, parent, rot_type, amounts, rot_order=''):
"""Sets the orientation of this reference frame relative to another
(parent) reference frame.
.. note:: It is now recommended to use the ``.orient_axis,
.orient_body_fixed, .orient_space_fixed, .orient_quaternion``
methods for the different rotation types.
Parameters
==========
parent : ReferenceFrame
Reference frame that this reference frame will be rotated relative
to.
rot_type : str
The method used to generate the direction cosine matrix. Supported
methods are:
- ``'Axis'``: simple rotations about a single common axis
- ``'DCM'``: for setting the direction cosine matrix directly
- ``'Body'``: three successive rotations about new intermediate
axes, also called "Euler and Tait-Bryan angles"
- ``'Space'``: three successive rotations about the parent
frames' unit vectors
- ``'Quaternion'``: rotations defined by four parameters which
result in a singularity free direction cosine matrix
amounts :
Expressions defining the rotation angles or direction cosine
matrix. These must match the ``rot_type``. See examples below for
details. The input types are:
- ``'Axis'``: 2-tuple (expr/sym/func, Vector)
- ``'DCM'``: Matrix, shape(3,3)
- ``'Body'``: 3-tuple of expressions, symbols, or functions
- ``'Space'``: 3-tuple of expressions, symbols, or functions
- ``'Quaternion'``: 4-tuple of expressions, symbols, or
functions
rot_order : str or int, optional
If applicable, the order of the successive of rotations. The string
``'123'`` and integer ``123`` are equivalent, for example. Required
for ``'Body'`` and ``'Space'``.
Warns
======
UserWarning
If the orientation creates a kinematic loop.
"""
_check_frame(parent)
approved_orders = ('123', '231', '312', '132', '213', '321', '121',
'131', '212', '232', '313', '323', '')
rot_order = translate(str(rot_order), 'XYZxyz', '123123')
rot_type = rot_type.upper()
if rot_order not in approved_orders:
raise TypeError('The supplied order is not an approved type')
if rot_type == 'AXIS':
self.orient_axis(parent, amounts[1], amounts[0])
elif rot_type == 'DCM':
self.orient_explicit(parent, amounts)
elif rot_type == 'BODY':
self.orient_body_fixed(parent, amounts, rot_order)
elif rot_type == 'SPACE':
self.orient_space_fixed(parent, amounts, rot_order)
elif rot_type == 'QUATERNION':
self.orient_quaternion(parent, amounts)
else:
raise NotImplementedError('That is not an implemented rotation')
def orientnew(self, newname, rot_type, amounts, rot_order='',
variables=None, indices=None, latexs=None):
r"""Returns a new reference frame oriented with respect to this
reference frame.
See ``ReferenceFrame.orient()`` for detailed examples of how to orient
reference frames.
Parameters
==========
newname : str
Name for the new reference frame.
rot_type : str
The method used to generate the direction cosine matrix. Supported
methods are:
- ``'Axis'``: simple rotations about a single common axis
- ``'DCM'``: for setting the direction cosine matrix directly
- ``'Body'``: three successive rotations about new intermediate
axes, also called "Euler and Tait-Bryan angles"
- ``'Space'``: three successive rotations about the parent
frames' unit vectors
- ``'Quaternion'``: rotations defined by four parameters which
result in a singularity free direction cosine matrix
amounts :
Expressions defining the rotation angles or direction cosine
matrix. These must match the ``rot_type``. See examples below for
details. The input types are:
- ``'Axis'``: 2-tuple (expr/sym/func, Vector)
- ``'DCM'``: Matrix, shape(3,3)
- ``'Body'``: 3-tuple of expressions, symbols, or functions
- ``'Space'``: 3-tuple of expressions, symbols, or functions
- ``'Quaternion'``: 4-tuple of expressions, symbols, or
functions
rot_order : str or int, optional
If applicable, the order of the successive of rotations. The string
``'123'`` and integer ``123`` are equivalent, for example. Required
for ``'Body'`` and ``'Space'``.
indices : tuple of str
Enables the reference frame's basis unit vectors to be accessed by
Python's square bracket indexing notation using the provided three
indice strings and alters the printing of the unit vectors to
reflect this choice.
latexs : tuple of str
Alters the LaTeX printing of the reference frame's basis unit
vectors to the provided three valid LaTeX strings.
Examples
========
>>> from sympy import symbols
>>> from sympy.physics.vector import ReferenceFrame, vlatex
>>> q0, q1, q2, q3 = symbols('q0 q1 q2 q3')
>>> N = ReferenceFrame('N')
Create a new reference frame A rotated relative to N through a simple
rotation.
>>> A = N.orientnew('A', 'Axis', (q0, N.x))
Create a new reference frame B rotated relative to N through body-fixed
rotations.
>>> B = N.orientnew('B', 'Body', (q1, q2, q3), '123')
Create a new reference frame C rotated relative to N through a simple
rotation with unique indices and LaTeX printing.
>>> C = N.orientnew('C', 'Axis', (q0, N.x), indices=('1', '2', '3'),
... latexs=(r'\hat{\mathbf{c}}_1',r'\hat{\mathbf{c}}_2',
... r'\hat{\mathbf{c}}_3'))
>>> C['1']
C['1']
>>> print(vlatex(C['1']))
\hat{\mathbf{c}}_1
"""
newframe = self.__class__(newname, variables=variables,
indices=indices, latexs=latexs)
approved_orders = ('123', '231', '312', '132', '213', '321', '121',
'131', '212', '232', '313', '323', '')
rot_order = translate(str(rot_order), 'XYZxyz', '123123')
rot_type = rot_type.upper()
if rot_order not in approved_orders:
raise TypeError('The supplied order is not an approved type')
if rot_type == 'AXIS':
newframe.orient_axis(self, amounts[1], amounts[0])
elif rot_type == 'DCM':
newframe.orient_explicit(self, amounts)
elif rot_type == 'BODY':
newframe.orient_body_fixed(self, amounts, rot_order)
elif rot_type == 'SPACE':
newframe.orient_space_fixed(self, amounts, rot_order)
elif rot_type == 'QUATERNION':
newframe.orient_quaternion(self, amounts)
else:
raise NotImplementedError('That is not an implemented rotation')
return newframe
def set_ang_acc(self, otherframe, value):
"""Define the angular acceleration Vector in a ReferenceFrame.
Defines the angular acceleration of this ReferenceFrame, in another.
Angular acceleration can be defined with respect to multiple different
ReferenceFrames. Care must be taken to not create loops which are
inconsistent.
Parameters
==========
otherframe : ReferenceFrame
A ReferenceFrame to define the angular acceleration in
value : Vector
The Vector representing angular acceleration
Examples
========
>>> from sympy.physics.vector import ReferenceFrame
>>> N = ReferenceFrame('N')
>>> A = ReferenceFrame('A')
>>> V = 10 * N.x
>>> A.set_ang_acc(N, V)
>>> A.ang_acc_in(N)
10*N.x
"""
if value == 0:
value = Vector(0)
value = _check_vector(value)
_check_frame(otherframe)
self._ang_acc_dict.update({otherframe: value})
otherframe._ang_acc_dict.update({self: -value})
def set_ang_vel(self, otherframe, value):
"""Define the angular velocity vector in a ReferenceFrame.
Defines the angular velocity of this ReferenceFrame, in another.
Angular velocity can be defined with respect to multiple different
ReferenceFrames. Care must be taken to not create loops which are
inconsistent.
Parameters
==========
otherframe : ReferenceFrame
A ReferenceFrame to define the angular velocity in
value : Vector
The Vector representing angular velocity
Examples
========
>>> from sympy.physics.vector import ReferenceFrame
>>> N = ReferenceFrame('N')
>>> A = ReferenceFrame('A')
>>> V = 10 * N.x
>>> A.set_ang_vel(N, V)
>>> A.ang_vel_in(N)
10*N.x
"""
if value == 0:
value = Vector(0)
value = _check_vector(value)
_check_frame(otherframe)
self._ang_vel_dict.update({otherframe: value})
otherframe._ang_vel_dict.update({self: -value})
@property
def x(self):
"""The basis Vector for the ReferenceFrame, in the x direction. """
return self._x
@property
def y(self):
"""The basis Vector for the ReferenceFrame, in the y direction. """
return self._y
@property
def z(self):
"""The basis Vector for the ReferenceFrame, in the z direction. """
return self._z
def partial_velocity(self, frame, *gen_speeds):
"""Returns the partial angular velocities of this frame in the given
frame with respect to one or more provided generalized speeds.
Parameters
==========
frame : ReferenceFrame
The frame with which the angular velocity is defined in.
gen_speeds : functions of time
The generalized speeds.
Returns
=======
partial_velocities : tuple of Vector
The partial angular velocity vectors corresponding to the provided
generalized speeds.
Examples
========
>>> from sympy.physics.vector import ReferenceFrame, dynamicsymbols
>>> N = ReferenceFrame('N')
>>> A = ReferenceFrame('A')
>>> u1, u2 = dynamicsymbols('u1, u2')
>>> A.set_ang_vel(N, u1 * A.x + u2 * N.y)
>>> A.partial_velocity(N, u1)
A.x
>>> A.partial_velocity(N, u1, u2)
(A.x, N.y)
"""
partials = [self.ang_vel_in(frame).diff(speed, frame, var_in_dcm=False)
for speed in gen_speeds]
if len(partials) == 1:
return partials[0]
else:
return tuple(partials)
def _check_frame(other):
from .vector import VectorTypeError
if not isinstance(other, ReferenceFrame):
raise VectorTypeError(other, ReferenceFrame('A'))
|
554ba3c97e494c91f9a64650bb4f0bbdf5919279456dec491a2b4fae38a55db5 | from sympy.core.backend import sympify, Add, ImmutableMatrix as Matrix
from sympy.core.evalf import EvalfMixin
from sympy.printing.defaults import Printable
from mpmath.libmp.libmpf import prec_to_dps
__all__ = ['Dyadic']
class Dyadic(Printable, EvalfMixin):
"""A Dyadic object.
See:
https://en.wikipedia.org/wiki/Dyadic_tensor
Kane, T., Levinson, D. Dynamics Theory and Applications. 1985 McGraw-Hill
A more powerful way to represent a rigid body's inertia. While it is more
complex, by choosing Dyadic components to be in body fixed basis vectors,
the resulting matrix is equivalent to the inertia tensor.
"""
is_number = False
def __init__(self, inlist):
"""
Just like Vector's init, you should not call this unless creating a
zero dyadic.
zd = Dyadic(0)
Stores a Dyadic as a list of lists; the inner list has the measure
number and the two unit vectors; the outerlist holds each unique
unit vector pair.
"""
self.args = []
if inlist == 0:
inlist = []
while len(inlist) != 0:
added = 0
for i, v in enumerate(self.args):
if ((str(inlist[0][1]) == str(self.args[i][1])) and
(str(inlist[0][2]) == str(self.args[i][2]))):
self.args[i] = (self.args[i][0] + inlist[0][0],
inlist[0][1], inlist[0][2])
inlist.remove(inlist[0])
added = 1
break
if added != 1:
self.args.append(inlist[0])
inlist.remove(inlist[0])
i = 0
# This code is to remove empty parts from the list
while i < len(self.args):
if ((self.args[i][0] == 0) | (self.args[i][1] == 0) |
(self.args[i][2] == 0)):
self.args.remove(self.args[i])
i -= 1
i += 1
@property
def func(self):
"""Returns the class Dyadic. """
return Dyadic
def __add__(self, other):
"""The add operator for Dyadic. """
other = _check_dyadic(other)
return Dyadic(self.args + other.args)
def __and__(self, other):
"""The inner product operator for a Dyadic and a Dyadic or Vector.
Parameters
==========
other : Dyadic or Vector
The other Dyadic or Vector to take the inner product with
Examples
========
>>> from sympy.physics.vector import ReferenceFrame, outer
>>> N = ReferenceFrame('N')
>>> D1 = outer(N.x, N.y)
>>> D2 = outer(N.y, N.y)
>>> D1.dot(D2)
(N.x|N.y)
>>> D1.dot(N.y)
N.x
"""
from sympy.physics.vector.vector import Vector, _check_vector
if isinstance(other, Dyadic):
other = _check_dyadic(other)
ol = Dyadic(0)
for i, v in enumerate(self.args):
for i2, v2 in enumerate(other.args):
ol += v[0] * v2[0] * (v[2] & v2[1]) * (v[1] | v2[2])
else:
other = _check_vector(other)
ol = Vector(0)
for i, v in enumerate(self.args):
ol += v[0] * v[1] * (v[2] & other)
return ol
def __truediv__(self, other):
"""Divides the Dyadic by a sympifyable expression. """
return self.__mul__(1 / other)
def __eq__(self, other):
"""Tests for equality.
Is currently weak; needs stronger comparison testing
"""
if other == 0:
other = Dyadic(0)
other = _check_dyadic(other)
if (self.args == []) and (other.args == []):
return True
elif (self.args == []) or (other.args == []):
return False
return set(self.args) == set(other.args)
def __mul__(self, other):
"""Multiplies the Dyadic by a sympifyable expression.
Parameters
==========
other : Sympafiable
The scalar to multiply this Dyadic with
Examples
========
>>> from sympy.physics.vector import ReferenceFrame, outer
>>> N = ReferenceFrame('N')
>>> d = outer(N.x, N.x)
>>> 5 * d
5*(N.x|N.x)
"""
newlist = [v for v in self.args]
other = sympify(other)
for i, v in enumerate(newlist):
newlist[i] = (other * newlist[i][0], newlist[i][1],
newlist[i][2])
return Dyadic(newlist)
def __ne__(self, other):
return not self == other
def __neg__(self):
return self * -1
def _latex(self, printer):
ar = self.args # just to shorten things
if len(ar) == 0:
return str(0)
ol = [] # output list, to be concatenated to a string
for i, v in enumerate(ar):
# if the coef of the dyadic is 1, we skip the 1
if ar[i][0] == 1:
ol.append(' + ' + printer._print(ar[i][1]) + r"\otimes " +
printer._print(ar[i][2]))
# if the coef of the dyadic is -1, we skip the 1
elif ar[i][0] == -1:
ol.append(' - ' +
printer._print(ar[i][1]) +
r"\otimes " +
printer._print(ar[i][2]))
# If the coefficient of the dyadic is not 1 or -1,
# we might wrap it in parentheses, for readability.
elif ar[i][0] != 0:
arg_str = printer._print(ar[i][0])
if isinstance(ar[i][0], Add):
arg_str = '(%s)' % arg_str
if arg_str.startswith('-'):
arg_str = arg_str[1:]
str_start = ' - '
else:
str_start = ' + '
ol.append(str_start + arg_str + printer._print(ar[i][1]) +
r"\otimes " + printer._print(ar[i][2]))
outstr = ''.join(ol)
if outstr.startswith(' + '):
outstr = outstr[3:]
elif outstr.startswith(' '):
outstr = outstr[1:]
return outstr
def _pretty(self, printer):
e = self
class Fake:
baseline = 0
def render(self, *args, **kwargs):
ar = e.args # just to shorten things
mpp = printer
if len(ar) == 0:
return str(0)
bar = "\N{CIRCLED TIMES}" if printer._use_unicode else "|"
ol = [] # output list, to be concatenated to a string
for i, v in enumerate(ar):
# if the coef of the dyadic is 1, we skip the 1
if ar[i][0] == 1:
ol.extend([" + ",
mpp.doprint(ar[i][1]),
bar,
mpp.doprint(ar[i][2])])
# if the coef of the dyadic is -1, we skip the 1
elif ar[i][0] == -1:
ol.extend([" - ",
mpp.doprint(ar[i][1]),
bar,
mpp.doprint(ar[i][2])])
# If the coefficient of the dyadic is not 1 or -1,
# we might wrap it in parentheses, for readability.
elif ar[i][0] != 0:
if isinstance(ar[i][0], Add):
arg_str = mpp._print(
ar[i][0]).parens()[0]
else:
arg_str = mpp.doprint(ar[i][0])
if arg_str.startswith("-"):
arg_str = arg_str[1:]
str_start = " - "
else:
str_start = " + "
ol.extend([str_start, arg_str, " ",
mpp.doprint(ar[i][1]),
bar,
mpp.doprint(ar[i][2])])
outstr = "".join(ol)
if outstr.startswith(" + "):
outstr = outstr[3:]
elif outstr.startswith(" "):
outstr = outstr[1:]
return outstr
return Fake()
def __rand__(self, other):
"""The inner product operator for a Vector or Dyadic, and a Dyadic
This is for: Vector dot Dyadic
Parameters
==========
other : Vector
The vector we are dotting with
Examples
========
>>> from sympy.physics.vector import ReferenceFrame, dot, outer
>>> N = ReferenceFrame('N')
>>> d = outer(N.x, N.x)
>>> dot(N.x, d)
N.x
"""
from sympy.physics.vector.vector import Vector, _check_vector
other = _check_vector(other)
ol = Vector(0)
for i, v in enumerate(self.args):
ol += v[0] * v[2] * (v[1] & other)
return ol
def __rsub__(self, other):
return (-1 * self) + other
def __rxor__(self, other):
"""For a cross product in the form: Vector x Dyadic
Parameters
==========
other : Vector
The Vector that we are crossing this Dyadic with
Examples
========
>>> from sympy.physics.vector import ReferenceFrame, outer, cross
>>> N = ReferenceFrame('N')
>>> d = outer(N.x, N.x)
>>> cross(N.y, d)
- (N.z|N.x)
"""
from sympy.physics.vector.vector import _check_vector
other = _check_vector(other)
ol = Dyadic(0)
for i, v in enumerate(self.args):
ol += v[0] * ((other ^ v[1]) | v[2])
return ol
def _sympystr(self, printer):
"""Printing method. """
ar = self.args # just to shorten things
if len(ar) == 0:
return printer._print(0)
ol = [] # output list, to be concatenated to a string
for i, v in enumerate(ar):
# if the coef of the dyadic is 1, we skip the 1
if ar[i][0] == 1:
ol.append(' + (' + printer._print(ar[i][1]) + '|' +
printer._print(ar[i][2]) + ')')
# if the coef of the dyadic is -1, we skip the 1
elif ar[i][0] == -1:
ol.append(' - (' + printer._print(ar[i][1]) + '|' +
printer._print(ar[i][2]) + ')')
# If the coefficient of the dyadic is not 1 or -1,
# we might wrap it in parentheses, for readability.
elif ar[i][0] != 0:
arg_str = printer._print(ar[i][0])
if isinstance(ar[i][0], Add):
arg_str = "(%s)" % arg_str
if arg_str[0] == '-':
arg_str = arg_str[1:]
str_start = ' - '
else:
str_start = ' + '
ol.append(str_start + arg_str + '*(' +
printer._print(ar[i][1]) +
'|' + printer._print(ar[i][2]) + ')')
outstr = ''.join(ol)
if outstr.startswith(' + '):
outstr = outstr[3:]
elif outstr.startswith(' '):
outstr = outstr[1:]
return outstr
def __sub__(self, other):
"""The subtraction operator. """
return self.__add__(other * -1)
def __xor__(self, other):
"""For a cross product in the form: Dyadic x Vector.
Parameters
==========
other : Vector
The Vector that we are crossing this Dyadic with
Examples
========
>>> from sympy.physics.vector import ReferenceFrame, outer, cross
>>> N = ReferenceFrame('N')
>>> d = outer(N.x, N.x)
>>> cross(d, N.y)
(N.x|N.z)
"""
from sympy.physics.vector.vector import _check_vector
other = _check_vector(other)
ol = Dyadic(0)
for i, v in enumerate(self.args):
ol += v[0] * (v[1] | (v[2] ^ other))
return ol
__radd__ = __add__
__rmul__ = __mul__
def express(self, frame1, frame2=None):
"""Expresses this Dyadic in alternate frame(s)
The first frame is the list side expression, the second frame is the
right side; if Dyadic is in form A.x|B.y, you can express it in two
different frames. If no second frame is given, the Dyadic is
expressed in only one frame.
Calls the global express function
Parameters
==========
frame1 : ReferenceFrame
The frame to express the left side of the Dyadic in
frame2 : ReferenceFrame
If provided, the frame to express the right side of the Dyadic in
Examples
========
>>> from sympy.physics.vector import ReferenceFrame, outer, dynamicsymbols
>>> from sympy.physics.vector import init_vprinting
>>> init_vprinting(pretty_print=False)
>>> N = ReferenceFrame('N')
>>> q = dynamicsymbols('q')
>>> B = N.orientnew('B', 'Axis', [q, N.z])
>>> d = outer(N.x, N.x)
>>> d.express(B, N)
cos(q)*(B.x|N.x) - sin(q)*(B.y|N.x)
"""
from sympy.physics.vector.functions import express
return express(self, frame1, frame2)
def to_matrix(self, reference_frame, second_reference_frame=None):
"""Returns the matrix form of the dyadic with respect to one or two
reference frames.
Parameters
----------
reference_frame : ReferenceFrame
The reference frame that the rows and columns of the matrix
correspond to. If a second reference frame is provided, this
only corresponds to the rows of the matrix.
second_reference_frame : ReferenceFrame, optional, default=None
The reference frame that the columns of the matrix correspond
to.
Returns
-------
matrix : ImmutableMatrix, shape(3,3)
The matrix that gives the 2D tensor form.
Examples
========
>>> from sympy import symbols
>>> from sympy.physics.vector import ReferenceFrame, Vector
>>> Vector.simp = True
>>> from sympy.physics.mechanics import inertia
>>> Ixx, Iyy, Izz, Ixy, Iyz, Ixz = symbols('Ixx, Iyy, Izz, Ixy, Iyz, Ixz')
>>> N = ReferenceFrame('N')
>>> inertia_dyadic = inertia(N, Ixx, Iyy, Izz, Ixy, Iyz, Ixz)
>>> inertia_dyadic.to_matrix(N)
Matrix([
[Ixx, Ixy, Ixz],
[Ixy, Iyy, Iyz],
[Ixz, Iyz, Izz]])
>>> beta = symbols('beta')
>>> A = N.orientnew('A', 'Axis', (beta, N.x))
>>> inertia_dyadic.to_matrix(A)
Matrix([
[ Ixx, Ixy*cos(beta) + Ixz*sin(beta), -Ixy*sin(beta) + Ixz*cos(beta)],
[ Ixy*cos(beta) + Ixz*sin(beta), Iyy*cos(2*beta)/2 + Iyy/2 + Iyz*sin(2*beta) - Izz*cos(2*beta)/2 + Izz/2, -Iyy*sin(2*beta)/2 + Iyz*cos(2*beta) + Izz*sin(2*beta)/2],
[-Ixy*sin(beta) + Ixz*cos(beta), -Iyy*sin(2*beta)/2 + Iyz*cos(2*beta) + Izz*sin(2*beta)/2, -Iyy*cos(2*beta)/2 + Iyy/2 - Iyz*sin(2*beta) + Izz*cos(2*beta)/2 + Izz/2]])
"""
if second_reference_frame is None:
second_reference_frame = reference_frame
return Matrix([i.dot(self).dot(j) for i in reference_frame for j in
second_reference_frame]).reshape(3, 3)
def doit(self, **hints):
"""Calls .doit() on each term in the Dyadic"""
return sum([Dyadic([(v[0].doit(**hints), v[1], v[2])])
for v in self.args], Dyadic(0))
def dt(self, frame):
"""Take the time derivative of this Dyadic in a frame.
This function calls the global time_derivative method
Parameters
==========
frame : ReferenceFrame
The frame to take the time derivative in
Examples
========
>>> from sympy.physics.vector import ReferenceFrame, outer, dynamicsymbols
>>> from sympy.physics.vector import init_vprinting
>>> init_vprinting(pretty_print=False)
>>> N = ReferenceFrame('N')
>>> q = dynamicsymbols('q')
>>> B = N.orientnew('B', 'Axis', [q, N.z])
>>> d = outer(N.x, N.x)
>>> d.dt(B)
- q'*(N.y|N.x) - q'*(N.x|N.y)
"""
from sympy.physics.vector.functions import time_derivative
return time_derivative(self, frame)
def simplify(self):
"""Returns a simplified Dyadic."""
out = Dyadic(0)
for v in self.args:
out += Dyadic([(v[0].simplify(), v[1], v[2])])
return out
def subs(self, *args, **kwargs):
"""Substitution on the Dyadic.
Examples
========
>>> from sympy.physics.vector import ReferenceFrame
>>> from sympy import Symbol
>>> N = ReferenceFrame('N')
>>> s = Symbol('s')
>>> a = s*(N.x|N.x)
>>> a.subs({s: 2})
2*(N.x|N.x)
"""
return sum([Dyadic([(v[0].subs(*args, **kwargs), v[1], v[2])])
for v in self.args], Dyadic(0))
def applyfunc(self, f):
"""Apply a function to each component of a Dyadic."""
if not callable(f):
raise TypeError("`f` must be callable.")
out = Dyadic(0)
for a, b, c in self.args:
out += f(a) * (b | c)
return out
dot = __and__
cross = __xor__
def _eval_evalf(self, prec):
if not self.args:
return self
new_args = []
dps = prec_to_dps(prec)
for inlist in self.args:
new_inlist = list(inlist)
new_inlist[0] = inlist[0].evalf(n=dps)
new_args.append(tuple(new_inlist))
return Dyadic(new_args)
def xreplace(self, rule):
"""
Replace occurrences of objects within the measure numbers of the
Dyadic.
Parameters
==========
rule : dict-like
Expresses a replacement rule.
Returns
=======
Dyadic
Result of the replacement.
Examples
========
>>> from sympy import symbols, pi
>>> from sympy.physics.vector import ReferenceFrame, outer
>>> N = ReferenceFrame('N')
>>> D = outer(N.x, N.x)
>>> x, y, z = symbols('x y z')
>>> ((1 + x*y) * D).xreplace({x: pi})
(pi*y + 1)*(N.x|N.x)
>>> ((1 + x*y) * D).xreplace({x: pi, y: 2})
(1 + 2*pi)*(N.x|N.x)
Replacements occur only if an entire node in the expression tree is
matched:
>>> ((x*y + z) * D).xreplace({x*y: pi})
(z + pi)*(N.x|N.x)
>>> ((x*y*z) * D).xreplace({x*y: pi})
x*y*z*(N.x|N.x)
"""
new_args = []
for inlist in self.args:
new_inlist = list(inlist)
new_inlist[0] = new_inlist[0].xreplace(rule)
new_args.append(tuple(new_inlist))
return Dyadic(new_args)
def _check_dyadic(other):
if not isinstance(other, Dyadic):
raise TypeError('A Dyadic must be supplied')
return other
|
9a856b72c130fdaf1d6faf5db6ec04f9aaae6754c025cec9c47ba4ad89c9bb23 | __all__ = ['Beam',
'Truss']
from .beam import Beam
from .truss import Truss
|
605ba0c25c1f5459debf50e581baccdc24266795417e7c58ea6e607afffdabe0 | """
This module can be used to solve 2D beam bending problems with
singularity functions in mechanics.
"""
from sympy.core import S, Symbol, diff, symbols
from sympy.core.add import Add
from sympy.core.expr import Expr
from sympy.core.function import (Derivative, Function)
from sympy.core.mul import Mul
from sympy.core.relational import Eq
from sympy.core.sympify import sympify
from sympy.solvers import linsolve
from sympy.solvers.ode.ode import dsolve
from sympy.solvers.solvers import solve
from sympy.printing import sstr
from sympy.functions import SingularityFunction, Piecewise, factorial
from sympy.integrals import integrate
from sympy.series import limit
from sympy.plotting import plot, PlotGrid
from sympy.geometry.entity import GeometryEntity
from sympy.external import import_module
from sympy.sets.sets import Interval
from sympy.utilities.lambdify import lambdify
from sympy.utilities.decorator import doctest_depends_on
from sympy.utilities.iterables import iterable
numpy = import_module('numpy', import_kwargs={'fromlist':['arange']})
class Beam:
"""
A Beam is a structural element that is capable of withstanding load
primarily by resisting against bending. Beams are characterized by
their cross sectional profile(Second moment of area), their length
and their material.
.. note::
A consistent sign convention must be used while solving a beam
bending problem; the results will
automatically follow the chosen sign convention. However, the
chosen sign convention must respect the rule that, on the positive
side of beam's axis (in respect to current section), a loading force
giving positive shear yields a negative moment, as below (the
curved arrow shows the positive moment and rotation):
.. image:: allowed-sign-conventions.png
Examples
========
There is a beam of length 4 meters. A constant distributed load of 6 N/m
is applied from half of the beam till the end. There are two simple supports
below the beam, one at the starting point and another at the ending point
of the beam. The deflection of the beam at the end is restricted.
Using the sign convention of downwards forces being positive.
>>> from sympy.physics.continuum_mechanics.beam import Beam
>>> from sympy import symbols, Piecewise
>>> E, I = symbols('E, I')
>>> R1, R2 = symbols('R1, R2')
>>> b = Beam(4, E, I)
>>> b.apply_load(R1, 0, -1)
>>> b.apply_load(6, 2, 0)
>>> b.apply_load(R2, 4, -1)
>>> b.bc_deflection = [(0, 0), (4, 0)]
>>> b.boundary_conditions
{'deflection': [(0, 0), (4, 0)], 'slope': []}
>>> b.load
R1*SingularityFunction(x, 0, -1) + R2*SingularityFunction(x, 4, -1) + 6*SingularityFunction(x, 2, 0)
>>> b.solve_for_reaction_loads(R1, R2)
>>> b.load
-3*SingularityFunction(x, 0, -1) + 6*SingularityFunction(x, 2, 0) - 9*SingularityFunction(x, 4, -1)
>>> b.shear_force()
3*SingularityFunction(x, 0, 0) - 6*SingularityFunction(x, 2, 1) + 9*SingularityFunction(x, 4, 0)
>>> b.bending_moment()
3*SingularityFunction(x, 0, 1) - 3*SingularityFunction(x, 2, 2) + 9*SingularityFunction(x, 4, 1)
>>> b.slope()
(-3*SingularityFunction(x, 0, 2)/2 + SingularityFunction(x, 2, 3) - 9*SingularityFunction(x, 4, 2)/2 + 7)/(E*I)
>>> b.deflection()
(7*x - SingularityFunction(x, 0, 3)/2 + SingularityFunction(x, 2, 4)/4 - 3*SingularityFunction(x, 4, 3)/2)/(E*I)
>>> b.deflection().rewrite(Piecewise)
(7*x - Piecewise((x**3, x > 0), (0, True))/2
- 3*Piecewise(((x - 4)**3, x > 4), (0, True))/2
+ Piecewise(((x - 2)**4, x > 2), (0, True))/4)/(E*I)
"""
def __init__(self, length, elastic_modulus, second_moment, area=Symbol('A'), variable=Symbol('x'), base_char='C'):
"""Initializes the class.
Parameters
==========
length : Sympifyable
A Symbol or value representing the Beam's length.
elastic_modulus : Sympifyable
A SymPy expression representing the Beam's Modulus of Elasticity.
It is a measure of the stiffness of the Beam material. It can
also be a continuous function of position along the beam.
second_moment : Sympifyable or Geometry object
Describes the cross-section of the beam via a SymPy expression
representing the Beam's second moment of area. It is a geometrical
property of an area which reflects how its points are distributed
with respect to its neutral axis. It can also be a continuous
function of position along the beam. Alternatively ``second_moment``
can be a shape object such as a ``Polygon`` from the geometry module
representing the shape of the cross-section of the beam. In such cases,
it is assumed that the x-axis of the shape object is aligned with the
bending axis of the beam. The second moment of area will be computed
from the shape object internally.
area : Symbol/float
Represents the cross-section area of beam
variable : Symbol, optional
A Symbol object that will be used as the variable along the beam
while representing the load, shear, moment, slope and deflection
curve. By default, it is set to ``Symbol('x')``.
base_char : String, optional
A String that will be used as base character to generate sequential
symbols for integration constants in cases where boundary conditions
are not sufficient to solve them.
"""
self.length = length
self.elastic_modulus = elastic_modulus
if isinstance(second_moment, GeometryEntity):
self.cross_section = second_moment
else:
self.cross_section = None
self.second_moment = second_moment
self.variable = variable
self._base_char = base_char
self._boundary_conditions = {'deflection': [], 'slope': []}
self._load = 0
self.area = area
self._applied_supports = []
self._support_as_loads = []
self._applied_loads = []
self._reaction_loads = {}
self._ild_reactions = {}
self._ild_shear = 0
self._ild_moment = 0
# _original_load is a copy of _load equations with unsubstituted reaction
# forces. It is used for calculating reaction forces in case of I.L.D.
self._original_load = 0
self._composite_type = None
self._hinge_position = None
def __str__(self):
shape_description = self._cross_section if self._cross_section else self._second_moment
str_sol = 'Beam({}, {}, {})'.format(sstr(self._length), sstr(self._elastic_modulus), sstr(shape_description))
return str_sol
@property
def reaction_loads(self):
""" Returns the reaction forces in a dictionary."""
return self._reaction_loads
@property
def ild_shear(self):
""" Returns the I.L.D. shear equation."""
return self._ild_shear
@property
def ild_reactions(self):
""" Returns the I.L.D. reaction forces in a dictionary."""
return self._ild_reactions
@property
def ild_moment(self):
""" Returns the I.L.D. moment equation."""
return self._ild_moment
@property
def length(self):
"""Length of the Beam."""
return self._length
@length.setter
def length(self, l):
self._length = sympify(l)
@property
def area(self):
"""Cross-sectional area of the Beam. """
return self._area
@area.setter
def area(self, a):
self._area = sympify(a)
@property
def variable(self):
"""
A symbol that can be used as a variable along the length of the beam
while representing load distribution, shear force curve, bending
moment, slope curve and the deflection curve. By default, it is set
to ``Symbol('x')``, but this property is mutable.
Examples
========
>>> from sympy.physics.continuum_mechanics.beam import Beam
>>> from sympy import symbols
>>> E, I, A = symbols('E, I, A')
>>> x, y, z = symbols('x, y, z')
>>> b = Beam(4, E, I)
>>> b.variable
x
>>> b.variable = y
>>> b.variable
y
>>> b = Beam(4, E, I, A, z)
>>> b.variable
z
"""
return self._variable
@variable.setter
def variable(self, v):
if isinstance(v, Symbol):
self._variable = v
else:
raise TypeError("""The variable should be a Symbol object.""")
@property
def elastic_modulus(self):
"""Young's Modulus of the Beam. """
return self._elastic_modulus
@elastic_modulus.setter
def elastic_modulus(self, e):
self._elastic_modulus = sympify(e)
@property
def second_moment(self):
"""Second moment of area of the Beam. """
return self._second_moment
@second_moment.setter
def second_moment(self, i):
self._cross_section = None
if isinstance(i, GeometryEntity):
raise ValueError("To update cross-section geometry use `cross_section` attribute")
else:
self._second_moment = sympify(i)
@property
def cross_section(self):
"""Cross-section of the beam"""
return self._cross_section
@cross_section.setter
def cross_section(self, s):
if s:
self._second_moment = s.second_moment_of_area()[0]
self._cross_section = s
@property
def boundary_conditions(self):
"""
Returns a dictionary of boundary conditions applied on the beam.
The dictionary has three keywords namely moment, slope and deflection.
The value of each keyword is a list of tuple, where each tuple
contains location and value of a boundary condition in the format
(location, value).
Examples
========
There is a beam of length 4 meters. The bending moment at 0 should be 4
and at 4 it should be 0. The slope of the beam should be 1 at 0. The
deflection should be 2 at 0.
>>> from sympy.physics.continuum_mechanics.beam import Beam
>>> from sympy import symbols
>>> E, I = symbols('E, I')
>>> b = Beam(4, E, I)
>>> b.bc_deflection = [(0, 2)]
>>> b.bc_slope = [(0, 1)]
>>> b.boundary_conditions
{'deflection': [(0, 2)], 'slope': [(0, 1)]}
Here the deflection of the beam should be ``2`` at ``0``.
Similarly, the slope of the beam should be ``1`` at ``0``.
"""
return self._boundary_conditions
@property
def bc_slope(self):
return self._boundary_conditions['slope']
@bc_slope.setter
def bc_slope(self, s_bcs):
self._boundary_conditions['slope'] = s_bcs
@property
def bc_deflection(self):
return self._boundary_conditions['deflection']
@bc_deflection.setter
def bc_deflection(self, d_bcs):
self._boundary_conditions['deflection'] = d_bcs
def join(self, beam, via="fixed"):
"""
This method joins two beams to make a new composite beam system.
Passed Beam class instance is attached to the right end of calling
object. This method can be used to form beams having Discontinuous
values of Elastic modulus or Second moment.
Parameters
==========
beam : Beam class object
The Beam object which would be connected to the right of calling
object.
via : String
States the way two Beam object would get connected
- For axially fixed Beams, via="fixed"
- For Beams connected via hinge, via="hinge"
Examples
========
There is a cantilever beam of length 4 meters. For first 2 meters
its moment of inertia is `1.5*I` and `I` for the other end.
A pointload of magnitude 4 N is applied from the top at its free end.
>>> from sympy.physics.continuum_mechanics.beam import Beam
>>> from sympy import symbols
>>> E, I = symbols('E, I')
>>> R1, R2 = symbols('R1, R2')
>>> b1 = Beam(2, E, 1.5*I)
>>> b2 = Beam(2, E, I)
>>> b = b1.join(b2, "fixed")
>>> b.apply_load(20, 4, -1)
>>> b.apply_load(R1, 0, -1)
>>> b.apply_load(R2, 0, -2)
>>> b.bc_slope = [(0, 0)]
>>> b.bc_deflection = [(0, 0)]
>>> b.solve_for_reaction_loads(R1, R2)
>>> b.load
80*SingularityFunction(x, 0, -2) - 20*SingularityFunction(x, 0, -1) + 20*SingularityFunction(x, 4, -1)
>>> b.slope()
(-((-80*SingularityFunction(x, 0, 1) + 10*SingularityFunction(x, 0, 2) - 10*SingularityFunction(x, 4, 2))/I + 120/I)/E + 80.0/(E*I))*SingularityFunction(x, 2, 0)
- 0.666666666666667*(-80*SingularityFunction(x, 0, 1) + 10*SingularityFunction(x, 0, 2) - 10*SingularityFunction(x, 4, 2))*SingularityFunction(x, 0, 0)/(E*I)
+ 0.666666666666667*(-80*SingularityFunction(x, 0, 1) + 10*SingularityFunction(x, 0, 2) - 10*SingularityFunction(x, 4, 2))*SingularityFunction(x, 2, 0)/(E*I)
"""
x = self.variable
E = self.elastic_modulus
new_length = self.length + beam.length
if self.second_moment != beam.second_moment:
new_second_moment = Piecewise((self.second_moment, x<=self.length),
(beam.second_moment, x<=new_length))
else:
new_second_moment = self.second_moment
if via == "fixed":
new_beam = Beam(new_length, E, new_second_moment, x)
new_beam._composite_type = "fixed"
return new_beam
if via == "hinge":
new_beam = Beam(new_length, E, new_second_moment, x)
new_beam._composite_type = "hinge"
new_beam._hinge_position = self.length
return new_beam
def apply_support(self, loc, type="fixed"):
"""
This method applies support to a particular beam object.
Parameters
==========
loc : Sympifyable
Location of point at which support is applied.
type : String
Determines type of Beam support applied. To apply support structure
with
- zero degree of freedom, type = "fixed"
- one degree of freedom, type = "pin"
- two degrees of freedom, type = "roller"
Examples
========
There is a beam of length 30 meters. A moment of magnitude 120 Nm is
applied in the clockwise direction at the end of the beam. A pointload
of magnitude 8 N is applied from the top of the beam at the starting
point. There are two simple supports below the beam. One at the end
and another one at a distance of 10 meters from the start. The
deflection is restricted at both the supports.
Using the sign convention of upward forces and clockwise moment
being positive.
>>> from sympy.physics.continuum_mechanics.beam import Beam
>>> from sympy import symbols
>>> E, I = symbols('E, I')
>>> b = Beam(30, E, I)
>>> b.apply_support(10, 'roller')
>>> b.apply_support(30, 'roller')
>>> b.apply_load(-8, 0, -1)
>>> b.apply_load(120, 30, -2)
>>> R_10, R_30 = symbols('R_10, R_30')
>>> b.solve_for_reaction_loads(R_10, R_30)
>>> b.load
-8*SingularityFunction(x, 0, -1) + 6*SingularityFunction(x, 10, -1)
+ 120*SingularityFunction(x, 30, -2) + 2*SingularityFunction(x, 30, -1)
>>> b.slope()
(-4*SingularityFunction(x, 0, 2) + 3*SingularityFunction(x, 10, 2)
+ 120*SingularityFunction(x, 30, 1) + SingularityFunction(x, 30, 2) + 4000/3)/(E*I)
"""
loc = sympify(loc)
self._applied_supports.append((loc, type))
if type in ("pin", "roller"):
reaction_load = Symbol('R_'+str(loc))
self.apply_load(reaction_load, loc, -1)
self.bc_deflection.append((loc, 0))
else:
reaction_load = Symbol('R_'+str(loc))
reaction_moment = Symbol('M_'+str(loc))
self.apply_load(reaction_load, loc, -1)
self.apply_load(reaction_moment, loc, -2)
self.bc_deflection.append((loc, 0))
self.bc_slope.append((loc, 0))
self._support_as_loads.append((reaction_moment, loc, -2, None))
self._support_as_loads.append((reaction_load, loc, -1, None))
def apply_load(self, value, start, order, end=None):
"""
This method adds up the loads given to a particular beam object.
Parameters
==========
value : Sympifyable
The value inserted should have the units [Force/(Distance**(n+1)]
where n is the order of applied load.
Units for applied loads:
- For moments, unit = kN*m
- For point loads, unit = kN
- For constant distributed load, unit = kN/m
- For ramp loads, unit = kN/m/m
- For parabolic ramp loads, unit = kN/m/m/m
- ... so on.
start : Sympifyable
The starting point of the applied load. For point moments and
point forces this is the location of application.
order : Integer
The order of the applied load.
- For moments, order = -2
- For point loads, order =-1
- For constant distributed load, order = 0
- For ramp loads, order = 1
- For parabolic ramp loads, order = 2
- ... so on.
end : Sympifyable, optional
An optional argument that can be used if the load has an end point
within the length of the beam.
Examples
========
There is a beam of length 4 meters. A moment of magnitude 3 Nm is
applied in the clockwise direction at the starting point of the beam.
A point load of magnitude 4 N is applied from the top of the beam at
2 meters from the starting point and a parabolic ramp load of magnitude
2 N/m is applied below the beam starting from 2 meters to 3 meters
away from the starting point of the beam.
>>> from sympy.physics.continuum_mechanics.beam import Beam
>>> from sympy import symbols
>>> E, I = symbols('E, I')
>>> b = Beam(4, E, I)
>>> b.apply_load(-3, 0, -2)
>>> b.apply_load(4, 2, -1)
>>> b.apply_load(-2, 2, 2, end=3)
>>> b.load
-3*SingularityFunction(x, 0, -2) + 4*SingularityFunction(x, 2, -1) - 2*SingularityFunction(x, 2, 2) + 2*SingularityFunction(x, 3, 0) + 4*SingularityFunction(x, 3, 1) + 2*SingularityFunction(x, 3, 2)
"""
x = self.variable
value = sympify(value)
start = sympify(start)
order = sympify(order)
self._applied_loads.append((value, start, order, end))
self._load += value*SingularityFunction(x, start, order)
self._original_load += value*SingularityFunction(x, start, order)
if end:
# load has an end point within the length of the beam.
self._handle_end(x, value, start, order, end, type="apply")
def remove_load(self, value, start, order, end=None):
"""
This method removes a particular load present on the beam object.
Returns a ValueError if the load passed as an argument is not
present on the beam.
Parameters
==========
value : Sympifyable
The magnitude of an applied load.
start : Sympifyable
The starting point of the applied load. For point moments and
point forces this is the location of application.
order : Integer
The order of the applied load.
- For moments, order= -2
- For point loads, order=-1
- For constant distributed load, order=0
- For ramp loads, order=1
- For parabolic ramp loads, order=2
- ... so on.
end : Sympifyable, optional
An optional argument that can be used if the load has an end point
within the length of the beam.
Examples
========
There is a beam of length 4 meters. A moment of magnitude 3 Nm is
applied in the clockwise direction at the starting point of the beam.
A pointload of magnitude 4 N is applied from the top of the beam at
2 meters from the starting point and a parabolic ramp load of magnitude
2 N/m is applied below the beam starting from 2 meters to 3 meters
away from the starting point of the beam.
>>> from sympy.physics.continuum_mechanics.beam import Beam
>>> from sympy import symbols
>>> E, I = symbols('E, I')
>>> b = Beam(4, E, I)
>>> b.apply_load(-3, 0, -2)
>>> b.apply_load(4, 2, -1)
>>> b.apply_load(-2, 2, 2, end=3)
>>> b.load
-3*SingularityFunction(x, 0, -2) + 4*SingularityFunction(x, 2, -1) - 2*SingularityFunction(x, 2, 2) + 2*SingularityFunction(x, 3, 0) + 4*SingularityFunction(x, 3, 1) + 2*SingularityFunction(x, 3, 2)
>>> b.remove_load(-2, 2, 2, end = 3)
>>> b.load
-3*SingularityFunction(x, 0, -2) + 4*SingularityFunction(x, 2, -1)
"""
x = self.variable
value = sympify(value)
start = sympify(start)
order = sympify(order)
if (value, start, order, end) in self._applied_loads:
self._load -= value*SingularityFunction(x, start, order)
self._original_load -= value*SingularityFunction(x, start, order)
self._applied_loads.remove((value, start, order, end))
else:
msg = "No such load distribution exists on the beam object."
raise ValueError(msg)
if end:
# load has an end point within the length of the beam.
self._handle_end(x, value, start, order, end, type="remove")
def _handle_end(self, x, value, start, order, end, type):
"""
This functions handles the optional `end` value in the
`apply_load` and `remove_load` functions. When the value
of end is not NULL, this function will be executed.
"""
if order.is_negative:
msg = ("If 'end' is provided the 'order' of the load cannot "
"be negative, i.e. 'end' is only valid for distributed "
"loads.")
raise ValueError(msg)
# NOTE : A Taylor series can be used to define the summation of
# singularity functions that subtract from the load past the end
# point such that it evaluates to zero past 'end'.
f = value*x**order
if type == "apply":
# iterating for "apply_load" method
for i in range(0, order + 1):
self._load -= (f.diff(x, i).subs(x, end - start) *
SingularityFunction(x, end, i)/factorial(i))
self._original_load -= (f.diff(x, i).subs(x, end - start) *
SingularityFunction(x, end, i)/factorial(i))
elif type == "remove":
# iterating for "remove_load" method
for i in range(0, order + 1):
self._load += (f.diff(x, i).subs(x, end - start) *
SingularityFunction(x, end, i)/factorial(i))
self._original_load += (f.diff(x, i).subs(x, end - start) *
SingularityFunction(x, end, i)/factorial(i))
@property
def load(self):
"""
Returns a Singularity Function expression which represents
the load distribution curve of the Beam object.
Examples
========
There is a beam of length 4 meters. A moment of magnitude 3 Nm is
applied in the clockwise direction at the starting point of the beam.
A point load of magnitude 4 N is applied from the top of the beam at
2 meters from the starting point and a parabolic ramp load of magnitude
2 N/m is applied below the beam starting from 3 meters away from the
starting point of the beam.
>>> from sympy.physics.continuum_mechanics.beam import Beam
>>> from sympy import symbols
>>> E, I = symbols('E, I')
>>> b = Beam(4, E, I)
>>> b.apply_load(-3, 0, -2)
>>> b.apply_load(4, 2, -1)
>>> b.apply_load(-2, 3, 2)
>>> b.load
-3*SingularityFunction(x, 0, -2) + 4*SingularityFunction(x, 2, -1) - 2*SingularityFunction(x, 3, 2)
"""
return self._load
@property
def applied_loads(self):
"""
Returns a list of all loads applied on the beam object.
Each load in the list is a tuple of form (value, start, order, end).
Examples
========
There is a beam of length 4 meters. A moment of magnitude 3 Nm is
applied in the clockwise direction at the starting point of the beam.
A pointload of magnitude 4 N is applied from the top of the beam at
2 meters from the starting point. Another pointload of magnitude 5 N
is applied at same position.
>>> from sympy.physics.continuum_mechanics.beam import Beam
>>> from sympy import symbols
>>> E, I = symbols('E, I')
>>> b = Beam(4, E, I)
>>> b.apply_load(-3, 0, -2)
>>> b.apply_load(4, 2, -1)
>>> b.apply_load(5, 2, -1)
>>> b.load
-3*SingularityFunction(x, 0, -2) + 9*SingularityFunction(x, 2, -1)
>>> b.applied_loads
[(-3, 0, -2, None), (4, 2, -1, None), (5, 2, -1, None)]
"""
return self._applied_loads
def _solve_hinge_beams(self, *reactions):
"""Method to find integration constants and reactional variables in a
composite beam connected via hinge.
This method resolves the composite Beam into its sub-beams and then
equations of shear force, bending moment, slope and deflection are
evaluated for both of them separately. These equations are then solved
for unknown reactions and integration constants using the boundary
conditions applied on the Beam. Equal deflection of both sub-beams
at the hinge joint gives us another equation to solve the system.
Examples
========
A combined beam, with constant fkexural rigidity E*I, is formed by joining
a Beam of length 2*l to the right of another Beam of length l. The whole beam
is fixed at both of its both end. A point load of magnitude P is also applied
from the top at a distance of 2*l from starting point.
>>> from sympy.physics.continuum_mechanics.beam import Beam
>>> from sympy import symbols
>>> E, I = symbols('E, I')
>>> l=symbols('l', positive=True)
>>> b1=Beam(l, E, I)
>>> b2=Beam(2*l, E, I)
>>> b=b1.join(b2,"hinge")
>>> M1, A1, M2, A2, P = symbols('M1 A1 M2 A2 P')
>>> b.apply_load(A1,0,-1)
>>> b.apply_load(M1,0,-2)
>>> b.apply_load(P,2*l,-1)
>>> b.apply_load(A2,3*l,-1)
>>> b.apply_load(M2,3*l,-2)
>>> b.bc_slope=[(0,0), (3*l, 0)]
>>> b.bc_deflection=[(0,0), (3*l, 0)]
>>> b.solve_for_reaction_loads(M1, A1, M2, A2)
>>> b.reaction_loads
{A1: -5*P/18, A2: -13*P/18, M1: 5*P*l/18, M2: -4*P*l/9}
>>> b.slope()
(5*P*l*SingularityFunction(x, 0, 1)/18 - 5*P*SingularityFunction(x, 0, 2)/36 + 5*P*SingularityFunction(x, l, 2)/36)*SingularityFunction(x, 0, 0)/(E*I)
- (5*P*l*SingularityFunction(x, 0, 1)/18 - 5*P*SingularityFunction(x, 0, 2)/36 + 5*P*SingularityFunction(x, l, 2)/36)*SingularityFunction(x, l, 0)/(E*I)
+ (P*l**2/18 - 4*P*l*SingularityFunction(-l + x, 2*l, 1)/9 - 5*P*SingularityFunction(-l + x, 0, 2)/36 + P*SingularityFunction(-l + x, l, 2)/2
- 13*P*SingularityFunction(-l + x, 2*l, 2)/36)*SingularityFunction(x, l, 0)/(E*I)
>>> b.deflection()
(5*P*l*SingularityFunction(x, 0, 2)/36 - 5*P*SingularityFunction(x, 0, 3)/108 + 5*P*SingularityFunction(x, l, 3)/108)*SingularityFunction(x, 0, 0)/(E*I)
- (5*P*l*SingularityFunction(x, 0, 2)/36 - 5*P*SingularityFunction(x, 0, 3)/108 + 5*P*SingularityFunction(x, l, 3)/108)*SingularityFunction(x, l, 0)/(E*I)
+ (5*P*l**3/54 + P*l**2*(-l + x)/18 - 2*P*l*SingularityFunction(-l + x, 2*l, 2)/9 - 5*P*SingularityFunction(-l + x, 0, 3)/108 + P*SingularityFunction(-l + x, l, 3)/6
- 13*P*SingularityFunction(-l + x, 2*l, 3)/108)*SingularityFunction(x, l, 0)/(E*I)
"""
x = self.variable
l = self._hinge_position
E = self._elastic_modulus
I = self._second_moment
if isinstance(I, Piecewise):
I1 = I.args[0][0]
I2 = I.args[1][0]
else:
I1 = I2 = I
load_1 = 0 # Load equation on first segment of composite beam
load_2 = 0 # Load equation on second segment of composite beam
# Distributing load on both segments
for load in self.applied_loads:
if load[1] < l:
load_1 += load[0]*SingularityFunction(x, load[1], load[2])
if load[2] == 0:
load_1 -= load[0]*SingularityFunction(x, load[3], load[2])
elif load[2] > 0:
load_1 -= load[0]*SingularityFunction(x, load[3], load[2]) + load[0]*SingularityFunction(x, load[3], 0)
elif load[1] == l:
load_1 += load[0]*SingularityFunction(x, load[1], load[2])
load_2 += load[0]*SingularityFunction(x, load[1] - l, load[2])
elif load[1] > l:
load_2 += load[0]*SingularityFunction(x, load[1] - l, load[2])
if load[2] == 0:
load_2 -= load[0]*SingularityFunction(x, load[3] - l, load[2])
elif load[2] > 0:
load_2 -= load[0]*SingularityFunction(x, load[3] - l, load[2]) + load[0]*SingularityFunction(x, load[3] - l, 0)
h = Symbol('h') # Force due to hinge
load_1 += h*SingularityFunction(x, l, -1)
load_2 -= h*SingularityFunction(x, 0, -1)
eq = []
shear_1 = integrate(load_1, x)
shear_curve_1 = limit(shear_1, x, l)
eq.append(shear_curve_1)
bending_1 = integrate(shear_1, x)
moment_curve_1 = limit(bending_1, x, l)
eq.append(moment_curve_1)
shear_2 = integrate(load_2, x)
shear_curve_2 = limit(shear_2, x, self.length - l)
eq.append(shear_curve_2)
bending_2 = integrate(shear_2, x)
moment_curve_2 = limit(bending_2, x, self.length - l)
eq.append(moment_curve_2)
C1 = Symbol('C1')
C2 = Symbol('C2')
C3 = Symbol('C3')
C4 = Symbol('C4')
slope_1 = S.One/(E*I1)*(integrate(bending_1, x) + C1)
def_1 = S.One/(E*I1)*(integrate((E*I)*slope_1, x) + C1*x + C2)
slope_2 = S.One/(E*I2)*(integrate(integrate(integrate(load_2, x), x), x) + C3)
def_2 = S.One/(E*I2)*(integrate((E*I)*slope_2, x) + C4)
for position, value in self.bc_slope:
if position<l:
eq.append(slope_1.subs(x, position) - value)
else:
eq.append(slope_2.subs(x, position - l) - value)
for position, value in self.bc_deflection:
if position<l:
eq.append(def_1.subs(x, position) - value)
else:
eq.append(def_2.subs(x, position - l) - value)
eq.append(def_1.subs(x, l) - def_2.subs(x, 0)) # Deflection of both the segments at hinge would be equal
constants = list(linsolve(eq, C1, C2, C3, C4, h, *reactions))
reaction_values = list(constants[0])[5:]
self._reaction_loads = dict(zip(reactions, reaction_values))
self._load = self._load.subs(self._reaction_loads)
# Substituting constants and reactional load and moments with their corresponding values
slope_1 = slope_1.subs({C1: constants[0][0], h:constants[0][4]}).subs(self._reaction_loads)
def_1 = def_1.subs({C1: constants[0][0], C2: constants[0][1], h:constants[0][4]}).subs(self._reaction_loads)
slope_2 = slope_2.subs({x: x-l, C3: constants[0][2], h:constants[0][4]}).subs(self._reaction_loads)
def_2 = def_2.subs({x: x-l,C3: constants[0][2], C4: constants[0][3], h:constants[0][4]}).subs(self._reaction_loads)
self._hinge_beam_slope = slope_1*SingularityFunction(x, 0, 0) - slope_1*SingularityFunction(x, l, 0) + slope_2*SingularityFunction(x, l, 0)
self._hinge_beam_deflection = def_1*SingularityFunction(x, 0, 0) - def_1*SingularityFunction(x, l, 0) + def_2*SingularityFunction(x, l, 0)
def solve_for_reaction_loads(self, *reactions):
"""
Solves for the reaction forces.
Examples
========
There is a beam of length 30 meters. A moment of magnitude 120 Nm is
applied in the clockwise direction at the end of the beam. A pointload
of magnitude 8 N is applied from the top of the beam at the starting
point. There are two simple supports below the beam. One at the end
and another one at a distance of 10 meters from the start. The
deflection is restricted at both the supports.
Using the sign convention of upward forces and clockwise moment
being positive.
>>> from sympy.physics.continuum_mechanics.beam import Beam
>>> from sympy import symbols
>>> E, I = symbols('E, I')
>>> R1, R2 = symbols('R1, R2')
>>> b = Beam(30, E, I)
>>> b.apply_load(-8, 0, -1)
>>> b.apply_load(R1, 10, -1) # Reaction force at x = 10
>>> b.apply_load(R2, 30, -1) # Reaction force at x = 30
>>> b.apply_load(120, 30, -2)
>>> b.bc_deflection = [(10, 0), (30, 0)]
>>> b.load
R1*SingularityFunction(x, 10, -1) + R2*SingularityFunction(x, 30, -1)
- 8*SingularityFunction(x, 0, -1) + 120*SingularityFunction(x, 30, -2)
>>> b.solve_for_reaction_loads(R1, R2)
>>> b.reaction_loads
{R1: 6, R2: 2}
>>> b.load
-8*SingularityFunction(x, 0, -1) + 6*SingularityFunction(x, 10, -1)
+ 120*SingularityFunction(x, 30, -2) + 2*SingularityFunction(x, 30, -1)
"""
if self._composite_type == "hinge":
return self._solve_hinge_beams(*reactions)
x = self.variable
l = self.length
C3 = Symbol('C3')
C4 = Symbol('C4')
shear_curve = limit(self.shear_force(), x, l)
moment_curve = limit(self.bending_moment(), x, l)
slope_eqs = []
deflection_eqs = []
slope_curve = integrate(self.bending_moment(), x) + C3
for position, value in self._boundary_conditions['slope']:
eqs = slope_curve.subs(x, position) - value
slope_eqs.append(eqs)
deflection_curve = integrate(slope_curve, x) + C4
for position, value in self._boundary_conditions['deflection']:
eqs = deflection_curve.subs(x, position) - value
deflection_eqs.append(eqs)
solution = list((linsolve([shear_curve, moment_curve] + slope_eqs
+ deflection_eqs, (C3, C4) + reactions).args)[0])
solution = solution[2:]
self._reaction_loads = dict(zip(reactions, solution))
self._load = self._load.subs(self._reaction_loads)
def shear_force(self):
"""
Returns a Singularity Function expression which represents
the shear force curve of the Beam object.
Examples
========
There is a beam of length 30 meters. A moment of magnitude 120 Nm is
applied in the clockwise direction at the end of the beam. A pointload
of magnitude 8 N is applied from the top of the beam at the starting
point. There are two simple supports below the beam. One at the end
and another one at a distance of 10 meters from the start. The
deflection is restricted at both the supports.
Using the sign convention of upward forces and clockwise moment
being positive.
>>> from sympy.physics.continuum_mechanics.beam import Beam
>>> from sympy import symbols
>>> E, I = symbols('E, I')
>>> R1, R2 = symbols('R1, R2')
>>> b = Beam(30, E, I)
>>> b.apply_load(-8, 0, -1)
>>> b.apply_load(R1, 10, -1)
>>> b.apply_load(R2, 30, -1)
>>> b.apply_load(120, 30, -2)
>>> b.bc_deflection = [(10, 0), (30, 0)]
>>> b.solve_for_reaction_loads(R1, R2)
>>> b.shear_force()
8*SingularityFunction(x, 0, 0) - 6*SingularityFunction(x, 10, 0) - 120*SingularityFunction(x, 30, -1) - 2*SingularityFunction(x, 30, 0)
"""
x = self.variable
return -integrate(self.load, x)
def max_shear_force(self):
"""Returns maximum Shear force and its coordinate
in the Beam object."""
shear_curve = self.shear_force()
x = self.variable
terms = shear_curve.args
singularity = [] # Points at which shear function changes
for term in terms:
if isinstance(term, Mul):
term = term.args[-1] # SingularityFunction in the term
singularity.append(term.args[1])
singularity.sort()
singularity = list(set(singularity))
intervals = [] # List of Intervals with discrete value of shear force
shear_values = [] # List of values of shear force in each interval
for i, s in enumerate(singularity):
if s == 0:
continue
try:
shear_slope = Piecewise((float("nan"), x<=singularity[i-1]),(self._load.rewrite(Piecewise), x<s), (float("nan"), True))
points = solve(shear_slope, x)
val = []
for point in points:
val.append(abs(shear_curve.subs(x, point)))
points.extend([singularity[i-1], s])
val += [abs(limit(shear_curve, x, singularity[i-1], '+')), abs(limit(shear_curve, x, s, '-'))]
max_shear = max(val)
shear_values.append(max_shear)
intervals.append(points[val.index(max_shear)])
# If shear force in a particular Interval has zero or constant
# slope, then above block gives NotImplementedError as
# solve can't represent Interval solutions.
except NotImplementedError:
initial_shear = limit(shear_curve, x, singularity[i-1], '+')
final_shear = limit(shear_curve, x, s, '-')
# If shear_curve has a constant slope(it is a line).
if shear_curve.subs(x, (singularity[i-1] + s)/2) == (initial_shear + final_shear)/2 and initial_shear != final_shear:
shear_values.extend([initial_shear, final_shear])
intervals.extend([singularity[i-1], s])
else: # shear_curve has same value in whole Interval
shear_values.append(final_shear)
intervals.append(Interval(singularity[i-1], s))
shear_values = list(map(abs, shear_values))
maximum_shear = max(shear_values)
point = intervals[shear_values.index(maximum_shear)]
return (point, maximum_shear)
def bending_moment(self):
"""
Returns a Singularity Function expression which represents
the bending moment curve of the Beam object.
Examples
========
There is a beam of length 30 meters. A moment of magnitude 120 Nm is
applied in the clockwise direction at the end of the beam. A pointload
of magnitude 8 N is applied from the top of the beam at the starting
point. There are two simple supports below the beam. One at the end
and another one at a distance of 10 meters from the start. The
deflection is restricted at both the supports.
Using the sign convention of upward forces and clockwise moment
being positive.
>>> from sympy.physics.continuum_mechanics.beam import Beam
>>> from sympy import symbols
>>> E, I = symbols('E, I')
>>> R1, R2 = symbols('R1, R2')
>>> b = Beam(30, E, I)
>>> b.apply_load(-8, 0, -1)
>>> b.apply_load(R1, 10, -1)
>>> b.apply_load(R2, 30, -1)
>>> b.apply_load(120, 30, -2)
>>> b.bc_deflection = [(10, 0), (30, 0)]
>>> b.solve_for_reaction_loads(R1, R2)
>>> b.bending_moment()
8*SingularityFunction(x, 0, 1) - 6*SingularityFunction(x, 10, 1) - 120*SingularityFunction(x, 30, 0) - 2*SingularityFunction(x, 30, 1)
"""
x = self.variable
return integrate(self.shear_force(), x)
def max_bmoment(self):
"""Returns maximum Shear force and its coordinate
in the Beam object."""
bending_curve = self.bending_moment()
x = self.variable
terms = bending_curve.args
singularity = [] # Points at which bending moment changes
for term in terms:
if isinstance(term, Mul):
term = term.args[-1] # SingularityFunction in the term
singularity.append(term.args[1])
singularity.sort()
singularity = list(set(singularity))
intervals = [] # List of Intervals with discrete value of bending moment
moment_values = [] # List of values of bending moment in each interval
for i, s in enumerate(singularity):
if s == 0:
continue
try:
moment_slope = Piecewise((float("nan"), x<=singularity[i-1]),(self.shear_force().rewrite(Piecewise), x<s), (float("nan"), True))
points = solve(moment_slope, x)
val = []
for point in points:
val.append(abs(bending_curve.subs(x, point)))
points.extend([singularity[i-1], s])
val += [abs(limit(bending_curve, x, singularity[i-1], '+')), abs(limit(bending_curve, x, s, '-'))]
max_moment = max(val)
moment_values.append(max_moment)
intervals.append(points[val.index(max_moment)])
# If bending moment in a particular Interval has zero or constant
# slope, then above block gives NotImplementedError as solve
# can't represent Interval solutions.
except NotImplementedError:
initial_moment = limit(bending_curve, x, singularity[i-1], '+')
final_moment = limit(bending_curve, x, s, '-')
# If bending_curve has a constant slope(it is a line).
if bending_curve.subs(x, (singularity[i-1] + s)/2) == (initial_moment + final_moment)/2 and initial_moment != final_moment:
moment_values.extend([initial_moment, final_moment])
intervals.extend([singularity[i-1], s])
else: # bending_curve has same value in whole Interval
moment_values.append(final_moment)
intervals.append(Interval(singularity[i-1], s))
moment_values = list(map(abs, moment_values))
maximum_moment = max(moment_values)
point = intervals[moment_values.index(maximum_moment)]
return (point, maximum_moment)
def point_cflexure(self):
"""
Returns a Set of point(s) with zero bending moment and
where bending moment curve of the beam object changes
its sign from negative to positive or vice versa.
Examples
========
There is is 10 meter long overhanging beam. There are
two simple supports below the beam. One at the start
and another one at a distance of 6 meters from the start.
Point loads of magnitude 10KN and 20KN are applied at
2 meters and 4 meters from start respectively. A Uniformly
distribute load of magnitude of magnitude 3KN/m is also
applied on top starting from 6 meters away from starting
point till end.
Using the sign convention of upward forces and clockwise moment
being positive.
>>> from sympy.physics.continuum_mechanics.beam import Beam
>>> from sympy import symbols
>>> E, I = symbols('E, I')
>>> b = Beam(10, E, I)
>>> b.apply_load(-4, 0, -1)
>>> b.apply_load(-46, 6, -1)
>>> b.apply_load(10, 2, -1)
>>> b.apply_load(20, 4, -1)
>>> b.apply_load(3, 6, 0)
>>> b.point_cflexure()
[10/3]
"""
# To restrict the range within length of the Beam
moment_curve = Piecewise((float("nan"), self.variable<=0),
(self.bending_moment(), self.variable<self.length),
(float("nan"), True))
points = solve(moment_curve.rewrite(Piecewise), self.variable,
domain=S.Reals)
return points
def slope(self):
"""
Returns a Singularity Function expression which represents
the slope the elastic curve of the Beam object.
Examples
========
There is a beam of length 30 meters. A moment of magnitude 120 Nm is
applied in the clockwise direction at the end of the beam. A pointload
of magnitude 8 N is applied from the top of the beam at the starting
point. There are two simple supports below the beam. One at the end
and another one at a distance of 10 meters from the start. The
deflection is restricted at both the supports.
Using the sign convention of upward forces and clockwise moment
being positive.
>>> from sympy.physics.continuum_mechanics.beam import Beam
>>> from sympy import symbols
>>> E, I = symbols('E, I')
>>> R1, R2 = symbols('R1, R2')
>>> b = Beam(30, E, I)
>>> b.apply_load(-8, 0, -1)
>>> b.apply_load(R1, 10, -1)
>>> b.apply_load(R2, 30, -1)
>>> b.apply_load(120, 30, -2)
>>> b.bc_deflection = [(10, 0), (30, 0)]
>>> b.solve_for_reaction_loads(R1, R2)
>>> b.slope()
(-4*SingularityFunction(x, 0, 2) + 3*SingularityFunction(x, 10, 2)
+ 120*SingularityFunction(x, 30, 1) + SingularityFunction(x, 30, 2) + 4000/3)/(E*I)
"""
x = self.variable
E = self.elastic_modulus
I = self.second_moment
if self._composite_type == "hinge":
return self._hinge_beam_slope
if not self._boundary_conditions['slope']:
return diff(self.deflection(), x)
if isinstance(I, Piecewise) and self._composite_type == "fixed":
args = I.args
slope = 0
prev_slope = 0
prev_end = 0
for i in range(len(args)):
if i != 0:
prev_end = args[i-1][1].args[1]
slope_value = -S.One/E*integrate(self.bending_moment()/args[i][0], (x, prev_end, x))
if i != len(args) - 1:
slope += (prev_slope + slope_value)*SingularityFunction(x, prev_end, 0) - \
(prev_slope + slope_value)*SingularityFunction(x, args[i][1].args[1], 0)
else:
slope += (prev_slope + slope_value)*SingularityFunction(x, prev_end, 0)
prev_slope = slope_value.subs(x, args[i][1].args[1])
return slope
C3 = Symbol('C3')
slope_curve = -integrate(S.One/(E*I)*self.bending_moment(), x) + C3
bc_eqs = []
for position, value in self._boundary_conditions['slope']:
eqs = slope_curve.subs(x, position) - value
bc_eqs.append(eqs)
constants = list(linsolve(bc_eqs, C3))
slope_curve = slope_curve.subs({C3: constants[0][0]})
return slope_curve
def deflection(self):
"""
Returns a Singularity Function expression which represents
the elastic curve or deflection of the Beam object.
Examples
========
There is a beam of length 30 meters. A moment of magnitude 120 Nm is
applied in the clockwise direction at the end of the beam. A pointload
of magnitude 8 N is applied from the top of the beam at the starting
point. There are two simple supports below the beam. One at the end
and another one at a distance of 10 meters from the start. The
deflection is restricted at both the supports.
Using the sign convention of upward forces and clockwise moment
being positive.
>>> from sympy.physics.continuum_mechanics.beam import Beam
>>> from sympy import symbols
>>> E, I = symbols('E, I')
>>> R1, R2 = symbols('R1, R2')
>>> b = Beam(30, E, I)
>>> b.apply_load(-8, 0, -1)
>>> b.apply_load(R1, 10, -1)
>>> b.apply_load(R2, 30, -1)
>>> b.apply_load(120, 30, -2)
>>> b.bc_deflection = [(10, 0), (30, 0)]
>>> b.solve_for_reaction_loads(R1, R2)
>>> b.deflection()
(4000*x/3 - 4*SingularityFunction(x, 0, 3)/3 + SingularityFunction(x, 10, 3)
+ 60*SingularityFunction(x, 30, 2) + SingularityFunction(x, 30, 3)/3 - 12000)/(E*I)
"""
x = self.variable
E = self.elastic_modulus
I = self.second_moment
if self._composite_type == "hinge":
return self._hinge_beam_deflection
if not self._boundary_conditions['deflection'] and not self._boundary_conditions['slope']:
if isinstance(I, Piecewise) and self._composite_type == "fixed":
args = I.args
prev_slope = 0
prev_def = 0
prev_end = 0
deflection = 0
for i in range(len(args)):
if i != 0:
prev_end = args[i-1][1].args[1]
slope_value = -S.One/E*integrate(self.bending_moment()/args[i][0], (x, prev_end, x))
recent_segment_slope = prev_slope + slope_value
deflection_value = integrate(recent_segment_slope, (x, prev_end, x))
if i != len(args) - 1:
deflection += (prev_def + deflection_value)*SingularityFunction(x, prev_end, 0) \
- (prev_def + deflection_value)*SingularityFunction(x, args[i][1].args[1], 0)
else:
deflection += (prev_def + deflection_value)*SingularityFunction(x, prev_end, 0)
prev_slope = slope_value.subs(x, args[i][1].args[1])
prev_def = deflection_value.subs(x, args[i][1].args[1])
return deflection
base_char = self._base_char
constants = symbols(base_char + '3:5')
return S.One/(E*I)*integrate(-integrate(self.bending_moment(), x), x) + constants[0]*x + constants[1]
elif not self._boundary_conditions['deflection']:
base_char = self._base_char
constant = symbols(base_char + '4')
return integrate(self.slope(), x) + constant
elif not self._boundary_conditions['slope'] and self._boundary_conditions['deflection']:
if isinstance(I, Piecewise) and self._composite_type == "fixed":
args = I.args
prev_slope = 0
prev_def = 0
prev_end = 0
deflection = 0
for i in range(len(args)):
if i != 0:
prev_end = args[i-1][1].args[1]
slope_value = -S.One/E*integrate(self.bending_moment()/args[i][0], (x, prev_end, x))
recent_segment_slope = prev_slope + slope_value
deflection_value = integrate(recent_segment_slope, (x, prev_end, x))
if i != len(args) - 1:
deflection += (prev_def + deflection_value)*SingularityFunction(x, prev_end, 0) \
- (prev_def + deflection_value)*SingularityFunction(x, args[i][1].args[1], 0)
else:
deflection += (prev_def + deflection_value)*SingularityFunction(x, prev_end, 0)
prev_slope = slope_value.subs(x, args[i][1].args[1])
prev_def = deflection_value.subs(x, args[i][1].args[1])
return deflection
base_char = self._base_char
C3, C4 = symbols(base_char + '3:5') # Integration constants
slope_curve = -integrate(self.bending_moment(), x) + C3
deflection_curve = integrate(slope_curve, x) + C4
bc_eqs = []
for position, value in self._boundary_conditions['deflection']:
eqs = deflection_curve.subs(x, position) - value
bc_eqs.append(eqs)
constants = list(linsolve(bc_eqs, (C3, C4)))
deflection_curve = deflection_curve.subs({C3: constants[0][0], C4: constants[0][1]})
return S.One/(E*I)*deflection_curve
if isinstance(I, Piecewise) and self._composite_type == "fixed":
args = I.args
prev_slope = 0
prev_def = 0
prev_end = 0
deflection = 0
for i in range(len(args)):
if i != 0:
prev_end = args[i-1][1].args[1]
slope_value = S.One/E*integrate(self.bending_moment()/args[i][0], (x, prev_end, x))
recent_segment_slope = prev_slope + slope_value
deflection_value = integrate(recent_segment_slope, (x, prev_end, x))
if i != len(args) - 1:
deflection += (prev_def + deflection_value)*SingularityFunction(x, prev_end, 0) \
- (prev_def + deflection_value)*SingularityFunction(x, args[i][1].args[1], 0)
else:
deflection += (prev_def + deflection_value)*SingularityFunction(x, prev_end, 0)
prev_slope = slope_value.subs(x, args[i][1].args[1])
prev_def = deflection_value.subs(x, args[i][1].args[1])
return deflection
C4 = Symbol('C4')
deflection_curve = integrate(self.slope(), x) + C4
bc_eqs = []
for position, value in self._boundary_conditions['deflection']:
eqs = deflection_curve.subs(x, position) - value
bc_eqs.append(eqs)
constants = list(linsolve(bc_eqs, C4))
deflection_curve = deflection_curve.subs({C4: constants[0][0]})
return deflection_curve
def max_deflection(self):
"""
Returns point of max deflection and its corresponding deflection value
in a Beam object.
"""
# To restrict the range within length of the Beam
slope_curve = Piecewise((float("nan"), self.variable<=0),
(self.slope(), self.variable<self.length),
(float("nan"), True))
points = solve(slope_curve.rewrite(Piecewise), self.variable,
domain=S.Reals)
deflection_curve = self.deflection()
deflections = [deflection_curve.subs(self.variable, x) for x in points]
deflections = list(map(abs, deflections))
if len(deflections) != 0:
max_def = max(deflections)
return (points[deflections.index(max_def)], max_def)
else:
return None
def shear_stress(self):
"""
Returns an expression representing the Shear Stress
curve of the Beam object.
"""
return self.shear_force()/self._area
def plot_shear_stress(self, subs=None):
"""
Returns a plot of shear stress present in the beam object.
Parameters
==========
subs : dictionary
Python dictionary containing Symbols as key and their
corresponding values.
Examples
========
There is a beam of length 8 meters and area of cross section 2 square
meters. A constant distributed load of 10 KN/m is applied from half of
the beam till the end. There are two simple supports below the beam,
one at the starting point and another at the ending point of the beam.
A pointload of magnitude 5 KN is also applied from top of the
beam, at a distance of 4 meters from the starting point.
Take E = 200 GPa and I = 400*(10**-6) meter**4.
Using the sign convention of downwards forces being positive.
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> from sympy.physics.continuum_mechanics.beam import Beam
>>> from sympy import symbols
>>> R1, R2 = symbols('R1, R2')
>>> b = Beam(8, 200*(10**9), 400*(10**-6), 2)
>>> b.apply_load(5000, 2, -1)
>>> b.apply_load(R1, 0, -1)
>>> b.apply_load(R2, 8, -1)
>>> b.apply_load(10000, 4, 0, end=8)
>>> b.bc_deflection = [(0, 0), (8, 0)]
>>> b.solve_for_reaction_loads(R1, R2)
>>> b.plot_shear_stress()
Plot object containing:
[0]: cartesian line: 6875*SingularityFunction(x, 0, 0) - 2500*SingularityFunction(x, 2, 0)
- 5000*SingularityFunction(x, 4, 1) + 15625*SingularityFunction(x, 8, 0)
+ 5000*SingularityFunction(x, 8, 1) for x over (0.0, 8.0)
"""
shear_stress = self.shear_stress()
x = self.variable
length = self.length
if subs is None:
subs = {}
for sym in shear_stress.atoms(Symbol):
if sym != x and sym not in subs:
raise ValueError('value of %s was not passed.' %sym)
if length in subs:
length = subs[length]
# Returns Plot of Shear Stress
return plot (shear_stress.subs(subs), (x, 0, length),
title='Shear Stress', xlabel=r'$\mathrm{x}$', ylabel=r'$\tau$',
line_color='r')
def plot_shear_force(self, subs=None):
"""
Returns a plot for Shear force present in the Beam object.
Parameters
==========
subs : dictionary
Python dictionary containing Symbols as key and their
corresponding values.
Examples
========
There is a beam of length 8 meters. A constant distributed load of 10 KN/m
is applied from half of the beam till the end. There are two simple supports
below the beam, one at the starting point and another at the ending point
of the beam. A pointload of magnitude 5 KN is also applied from top of the
beam, at a distance of 4 meters from the starting point.
Take E = 200 GPa and I = 400*(10**-6) meter**4.
Using the sign convention of downwards forces being positive.
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> from sympy.physics.continuum_mechanics.beam import Beam
>>> from sympy import symbols
>>> R1, R2 = symbols('R1, R2')
>>> b = Beam(8, 200*(10**9), 400*(10**-6))
>>> b.apply_load(5000, 2, -1)
>>> b.apply_load(R1, 0, -1)
>>> b.apply_load(R2, 8, -1)
>>> b.apply_load(10000, 4, 0, end=8)
>>> b.bc_deflection = [(0, 0), (8, 0)]
>>> b.solve_for_reaction_loads(R1, R2)
>>> b.plot_shear_force()
Plot object containing:
[0]: cartesian line: 13750*SingularityFunction(x, 0, 0) - 5000*SingularityFunction(x, 2, 0)
- 10000*SingularityFunction(x, 4, 1) + 31250*SingularityFunction(x, 8, 0)
+ 10000*SingularityFunction(x, 8, 1) for x over (0.0, 8.0)
"""
shear_force = self.shear_force()
if subs is None:
subs = {}
for sym in shear_force.atoms(Symbol):
if sym == self.variable:
continue
if sym not in subs:
raise ValueError('Value of %s was not passed.' %sym)
if self.length in subs:
length = subs[self.length]
else:
length = self.length
return plot(shear_force.subs(subs), (self.variable, 0, length), title='Shear Force',
xlabel=r'$\mathrm{x}$', ylabel=r'$\mathrm{V}$', line_color='g')
def plot_bending_moment(self, subs=None):
"""
Returns a plot for Bending moment present in the Beam object.
Parameters
==========
subs : dictionary
Python dictionary containing Symbols as key and their
corresponding values.
Examples
========
There is a beam of length 8 meters. A constant distributed load of 10 KN/m
is applied from half of the beam till the end. There are two simple supports
below the beam, one at the starting point and another at the ending point
of the beam. A pointload of magnitude 5 KN is also applied from top of the
beam, at a distance of 4 meters from the starting point.
Take E = 200 GPa and I = 400*(10**-6) meter**4.
Using the sign convention of downwards forces being positive.
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> from sympy.physics.continuum_mechanics.beam import Beam
>>> from sympy import symbols
>>> R1, R2 = symbols('R1, R2')
>>> b = Beam(8, 200*(10**9), 400*(10**-6))
>>> b.apply_load(5000, 2, -1)
>>> b.apply_load(R1, 0, -1)
>>> b.apply_load(R2, 8, -1)
>>> b.apply_load(10000, 4, 0, end=8)
>>> b.bc_deflection = [(0, 0), (8, 0)]
>>> b.solve_for_reaction_loads(R1, R2)
>>> b.plot_bending_moment()
Plot object containing:
[0]: cartesian line: 13750*SingularityFunction(x, 0, 1) - 5000*SingularityFunction(x, 2, 1)
- 5000*SingularityFunction(x, 4, 2) + 31250*SingularityFunction(x, 8, 1)
+ 5000*SingularityFunction(x, 8, 2) for x over (0.0, 8.0)
"""
bending_moment = self.bending_moment()
if subs is None:
subs = {}
for sym in bending_moment.atoms(Symbol):
if sym == self.variable:
continue
if sym not in subs:
raise ValueError('Value of %s was not passed.' %sym)
if self.length in subs:
length = subs[self.length]
else:
length = self.length
return plot(bending_moment.subs(subs), (self.variable, 0, length), title='Bending Moment',
xlabel=r'$\mathrm{x}$', ylabel=r'$\mathrm{M}$', line_color='b')
def plot_slope(self, subs=None):
"""
Returns a plot for slope of deflection curve of the Beam object.
Parameters
==========
subs : dictionary
Python dictionary containing Symbols as key and their
corresponding values.
Examples
========
There is a beam of length 8 meters. A constant distributed load of 10 KN/m
is applied from half of the beam till the end. There are two simple supports
below the beam, one at the starting point and another at the ending point
of the beam. A pointload of magnitude 5 KN is also applied from top of the
beam, at a distance of 4 meters from the starting point.
Take E = 200 GPa and I = 400*(10**-6) meter**4.
Using the sign convention of downwards forces being positive.
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> from sympy.physics.continuum_mechanics.beam import Beam
>>> from sympy import symbols
>>> R1, R2 = symbols('R1, R2')
>>> b = Beam(8, 200*(10**9), 400*(10**-6))
>>> b.apply_load(5000, 2, -1)
>>> b.apply_load(R1, 0, -1)
>>> b.apply_load(R2, 8, -1)
>>> b.apply_load(10000, 4, 0, end=8)
>>> b.bc_deflection = [(0, 0), (8, 0)]
>>> b.solve_for_reaction_loads(R1, R2)
>>> b.plot_slope()
Plot object containing:
[0]: cartesian line: -8.59375e-5*SingularityFunction(x, 0, 2) + 3.125e-5*SingularityFunction(x, 2, 2)
+ 2.08333333333333e-5*SingularityFunction(x, 4, 3) - 0.0001953125*SingularityFunction(x, 8, 2)
- 2.08333333333333e-5*SingularityFunction(x, 8, 3) + 0.00138541666666667 for x over (0.0, 8.0)
"""
slope = self.slope()
if subs is None:
subs = {}
for sym in slope.atoms(Symbol):
if sym == self.variable:
continue
if sym not in subs:
raise ValueError('Value of %s was not passed.' %sym)
if self.length in subs:
length = subs[self.length]
else:
length = self.length
return plot(slope.subs(subs), (self.variable, 0, length), title='Slope',
xlabel=r'$\mathrm{x}$', ylabel=r'$\theta$', line_color='m')
def plot_deflection(self, subs=None):
"""
Returns a plot for deflection curve of the Beam object.
Parameters
==========
subs : dictionary
Python dictionary containing Symbols as key and their
corresponding values.
Examples
========
There is a beam of length 8 meters. A constant distributed load of 10 KN/m
is applied from half of the beam till the end. There are two simple supports
below the beam, one at the starting point and another at the ending point
of the beam. A pointload of magnitude 5 KN is also applied from top of the
beam, at a distance of 4 meters from the starting point.
Take E = 200 GPa and I = 400*(10**-6) meter**4.
Using the sign convention of downwards forces being positive.
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> from sympy.physics.continuum_mechanics.beam import Beam
>>> from sympy import symbols
>>> R1, R2 = symbols('R1, R2')
>>> b = Beam(8, 200*(10**9), 400*(10**-6))
>>> b.apply_load(5000, 2, -1)
>>> b.apply_load(R1, 0, -1)
>>> b.apply_load(R2, 8, -1)
>>> b.apply_load(10000, 4, 0, end=8)
>>> b.bc_deflection = [(0, 0), (8, 0)]
>>> b.solve_for_reaction_loads(R1, R2)
>>> b.plot_deflection()
Plot object containing:
[0]: cartesian line: 0.00138541666666667*x - 2.86458333333333e-5*SingularityFunction(x, 0, 3)
+ 1.04166666666667e-5*SingularityFunction(x, 2, 3) + 5.20833333333333e-6*SingularityFunction(x, 4, 4)
- 6.51041666666667e-5*SingularityFunction(x, 8, 3) - 5.20833333333333e-6*SingularityFunction(x, 8, 4)
for x over (0.0, 8.0)
"""
deflection = self.deflection()
if subs is None:
subs = {}
for sym in deflection.atoms(Symbol):
if sym == self.variable:
continue
if sym not in subs:
raise ValueError('Value of %s was not passed.' %sym)
if self.length in subs:
length = subs[self.length]
else:
length = self.length
return plot(deflection.subs(subs), (self.variable, 0, length),
title='Deflection', xlabel=r'$\mathrm{x}$', ylabel=r'$\delta$',
line_color='r')
def plot_loading_results(self, subs=None):
"""
Returns a subplot of Shear Force, Bending Moment,
Slope and Deflection of the Beam object.
Parameters
==========
subs : dictionary
Python dictionary containing Symbols as key and their
corresponding values.
Examples
========
There is a beam of length 8 meters. A constant distributed load of 10 KN/m
is applied from half of the beam till the end. There are two simple supports
below the beam, one at the starting point and another at the ending point
of the beam. A pointload of magnitude 5 KN is also applied from top of the
beam, at a distance of 4 meters from the starting point.
Take E = 200 GPa and I = 400*(10**-6) meter**4.
Using the sign convention of downwards forces being positive.
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> from sympy.physics.continuum_mechanics.beam import Beam
>>> from sympy import symbols
>>> R1, R2 = symbols('R1, R2')
>>> b = Beam(8, 200*(10**9), 400*(10**-6))
>>> b.apply_load(5000, 2, -1)
>>> b.apply_load(R1, 0, -1)
>>> b.apply_load(R2, 8, -1)
>>> b.apply_load(10000, 4, 0, end=8)
>>> b.bc_deflection = [(0, 0), (8, 0)]
>>> b.solve_for_reaction_loads(R1, R2)
>>> axes = b.plot_loading_results()
"""
length = self.length
variable = self.variable
if subs is None:
subs = {}
for sym in self.deflection().atoms(Symbol):
if sym == self.variable:
continue
if sym not in subs:
raise ValueError('Value of %s was not passed.' %sym)
if length in subs:
length = subs[length]
ax1 = plot(self.shear_force().subs(subs), (variable, 0, length),
title="Shear Force", xlabel=r'$\mathrm{x}$', ylabel=r'$\mathrm{V}$',
line_color='g', show=False)
ax2 = plot(self.bending_moment().subs(subs), (variable, 0, length),
title="Bending Moment", xlabel=r'$\mathrm{x}$', ylabel=r'$\mathrm{M}$',
line_color='b', show=False)
ax3 = plot(self.slope().subs(subs), (variable, 0, length),
title="Slope", xlabel=r'$\mathrm{x}$', ylabel=r'$\theta$',
line_color='m', show=False)
ax4 = plot(self.deflection().subs(subs), (variable, 0, length),
title="Deflection", xlabel=r'$\mathrm{x}$', ylabel=r'$\delta$',
line_color='r', show=False)
return PlotGrid(4, 1, ax1, ax2, ax3, ax4)
def _solve_for_ild_equations(self):
"""
Helper function for I.L.D. It takes the unsubstituted
copy of the load equation and uses it to calculate shear force and bending
moment equations.
"""
x = self.variable
shear_force = -integrate(self._original_load, x)
bending_moment = integrate(shear_force, x)
return shear_force, bending_moment
def solve_for_ild_reactions(self, value, *reactions):
"""
Determines the Influence Line Diagram equations for reaction
forces under the effect of a moving load.
Parameters
==========
value : Integer
Magnitude of moving load
reactions :
The reaction forces applied on the beam.
Examples
========
There is a beam of length 10 meters. There are two simple supports
below the beam, one at the starting point and another at the ending
point of the beam. Calculate the I.L.D. equations for reaction forces
under the effect of a moving load of magnitude 1kN.
.. image:: ildreaction.png
Using the sign convention of downwards forces being positive.
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> from sympy import symbols
>>> from sympy.physics.continuum_mechanics.beam import Beam
>>> E, I = symbols('E, I')
>>> R_0, R_10 = symbols('R_0, R_10')
>>> b = Beam(10, E, I)
>>> b.apply_support(0, 'roller')
>>> b.apply_support(10, 'roller')
>>> b.solve_for_ild_reactions(1,R_0,R_10)
>>> b.ild_reactions
{R_0: x/10 - 1, R_10: -x/10}
"""
shear_force, bending_moment = self._solve_for_ild_equations()
x = self.variable
l = self.length
C3 = Symbol('C3')
C4 = Symbol('C4')
shear_curve = limit(shear_force, x, l) - value
moment_curve = limit(bending_moment, x, l) - value*(l-x)
slope_eqs = []
deflection_eqs = []
slope_curve = integrate(bending_moment, x) + C3
for position, value in self._boundary_conditions['slope']:
eqs = slope_curve.subs(x, position) - value
slope_eqs.append(eqs)
deflection_curve = integrate(slope_curve, x) + C4
for position, value in self._boundary_conditions['deflection']:
eqs = deflection_curve.subs(x, position) - value
deflection_eqs.append(eqs)
solution = list((linsolve([shear_curve, moment_curve] + slope_eqs
+ deflection_eqs, (C3, C4) + reactions).args)[0])
solution = solution[2:]
# Determining the equations and solving them.
self._ild_reactions = dict(zip(reactions, solution))
def plot_ild_reactions(self, subs=None):
"""
Plots the Influence Line Diagram of Reaction Forces
under the effect of a moving load. This function
should be called after calling solve_for_ild_reactions().
Parameters
==========
subs : dictionary
Python dictionary containing Symbols as key and their
corresponding values.
Examples
========
There is a beam of length 10 meters. A point load of magnitude 5KN
is also applied from top of the beam, at a distance of 4 meters
from the starting point. There are two simple supports below the
beam, located at the starting point and at a distance of 7 meters
from the starting point. Plot the I.L.D. equations for reactions
at both support points under the effect of a moving load
of magnitude 1kN.
Using the sign convention of downwards forces being positive.
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> from sympy import symbols
>>> from sympy.physics.continuum_mechanics.beam import Beam
>>> E, I = symbols('E, I')
>>> R_0, R_7 = symbols('R_0, R_7')
>>> b = Beam(10, E, I)
>>> b.apply_support(0, 'roller')
>>> b.apply_support(7, 'roller')
>>> b.apply_load(5,4,-1)
>>> b.solve_for_ild_reactions(1,R_0,R_7)
>>> b.ild_reactions
{R_0: x/7 - 22/7, R_7: -x/7 - 20/7}
>>> b.plot_ild_reactions()
PlotGrid object containing:
Plot[0]:Plot object containing:
[0]: cartesian line: x/7 - 22/7 for x over (0.0, 10.0)
Plot[1]:Plot object containing:
[0]: cartesian line: -x/7 - 20/7 for x over (0.0, 10.0)
"""
if not self._ild_reactions:
raise ValueError("I.L.D. reaction equations not found. Please use solve_for_ild_reactions() to generate the I.L.D. reaction equations.")
x = self.variable
ildplots = []
if subs is None:
subs = {}
for reaction in self._ild_reactions:
for sym in self._ild_reactions[reaction].atoms(Symbol):
if sym != x and sym not in subs:
raise ValueError('Value of %s was not passed.' %sym)
for sym in self._length.atoms(Symbol):
if sym != x and sym not in subs:
raise ValueError('Value of %s was not passed.' %sym)
for reaction in self._ild_reactions:
ildplots.append(plot(self._ild_reactions[reaction].subs(subs),
(x, 0, self._length.subs(subs)), title='I.L.D. for Reactions',
xlabel=x, ylabel=reaction, line_color='blue', show=False))
return PlotGrid(len(ildplots), 1, *ildplots)
def solve_for_ild_shear(self, distance, value, *reactions):
"""
Determines the Influence Line Diagram equations for shear at a
specified point under the effect of a moving load.
Parameters
==========
distance : Integer
Distance of the point from the start of the beam
for which equations are to be determined
value : Integer
Magnitude of moving load
reactions :
The reaction forces applied on the beam.
Examples
========
There is a beam of length 12 meters. There are two simple supports
below the beam, one at the starting point and another at a distance
of 8 meters. Calculate the I.L.D. equations for Shear at a distance
of 4 meters under the effect of a moving load of magnitude 1kN.
.. image:: ildshear.png
Using the sign convention of downwards forces being positive.
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> from sympy import symbols
>>> from sympy.physics.continuum_mechanics.beam import Beam
>>> E, I = symbols('E, I')
>>> R_0, R_8 = symbols('R_0, R_8')
>>> b = Beam(12, E, I)
>>> b.apply_support(0, 'roller')
>>> b.apply_support(8, 'roller')
>>> b.solve_for_ild_reactions(1, R_0, R_8)
>>> b.solve_for_ild_shear(4, 1, R_0, R_8)
>>> b.ild_shear
Piecewise((x/8, x < 4), (x/8 - 1, x > 4))
"""
x = self.variable
l = self.length
shear_force, _ = self._solve_for_ild_equations()
shear_curve1 = value - limit(shear_force, x, distance)
shear_curve2 = (limit(shear_force, x, l) - limit(shear_force, x, distance)) - value
for reaction in reactions:
shear_curve1 = shear_curve1.subs(reaction,self._ild_reactions[reaction])
shear_curve2 = shear_curve2.subs(reaction,self._ild_reactions[reaction])
shear_eq = Piecewise((shear_curve1, x < distance), (shear_curve2, x > distance))
self._ild_shear = shear_eq
def plot_ild_shear(self,subs=None):
"""
Plots the Influence Line Diagram for Shear under the effect
of a moving load. This function should be called after
calling solve_for_ild_shear().
Parameters
==========
subs : dictionary
Python dictionary containing Symbols as key and their
corresponding values.
Examples
========
There is a beam of length 12 meters. There are two simple supports
below the beam, one at the starting point and another at a distance
of 8 meters. Plot the I.L.D. for Shear at a distance
of 4 meters under the effect of a moving load of magnitude 1kN.
.. image:: ildshear.png
Using the sign convention of downwards forces being positive.
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> from sympy import symbols
>>> from sympy.physics.continuum_mechanics.beam import Beam
>>> E, I = symbols('E, I')
>>> R_0, R_8 = symbols('R_0, R_8')
>>> b = Beam(12, E, I)
>>> b.apply_support(0, 'roller')
>>> b.apply_support(8, 'roller')
>>> b.solve_for_ild_reactions(1, R_0, R_8)
>>> b.solve_for_ild_shear(4, 1, R_0, R_8)
>>> b.ild_shear
Piecewise((x/8, x < 4), (x/8 - 1, x > 4))
>>> b.plot_ild_shear()
Plot object containing:
[0]: cartesian line: Piecewise((x/8, x < 4), (x/8 - 1, x > 4)) for x over (0.0, 12.0)
"""
if not self._ild_shear:
raise ValueError("I.L.D. shear equation not found. Please use solve_for_ild_shear() to generate the I.L.D. shear equations.")
x = self.variable
l = self._length
if subs is None:
subs = {}
for sym in self._ild_shear.atoms(Symbol):
if sym != x and sym not in subs:
raise ValueError('Value of %s was not passed.' %sym)
for sym in self._length.atoms(Symbol):
if sym != x and sym not in subs:
raise ValueError('Value of %s was not passed.' %sym)
return plot(self._ild_shear.subs(subs), (x, 0, l), title='I.L.D. for Shear',
xlabel=r'$\mathrm{X}$', ylabel=r'$\mathrm{V}$', line_color='blue',show=True)
def solve_for_ild_moment(self, distance, value, *reactions):
"""
Determines the Influence Line Diagram equations for moment at a
specified point under the effect of a moving load.
Parameters
==========
distance : Integer
Distance of the point from the start of the beam
for which equations are to be determined
value : Integer
Magnitude of moving load
reactions :
The reaction forces applied on the beam.
Examples
========
There is a beam of length 12 meters. There are two simple supports
below the beam, one at the starting point and another at a distance
of 8 meters. Calculate the I.L.D. equations for Moment at a distance
of 4 meters under the effect of a moving load of magnitude 1kN.
.. image:: ildshear.png
Using the sign convention of downwards forces being positive.
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> from sympy import symbols
>>> from sympy.physics.continuum_mechanics.beam import Beam
>>> E, I = symbols('E, I')
>>> R_0, R_8 = symbols('R_0, R_8')
>>> b = Beam(12, E, I)
>>> b.apply_support(0, 'roller')
>>> b.apply_support(8, 'roller')
>>> b.solve_for_ild_reactions(1, R_0, R_8)
>>> b.solve_for_ild_moment(4, 1, R_0, R_8)
>>> b.ild_moment
Piecewise((-x/2, x < 4), (x/2 - 4, x > 4))
"""
x = self.variable
l = self.length
_, moment = self._solve_for_ild_equations()
moment_curve1 = value*(distance-x) - limit(moment, x, distance)
moment_curve2= (limit(moment, x, l)-limit(moment, x, distance))-value*(l-x)
for reaction in reactions:
moment_curve1 = moment_curve1.subs(reaction, self._ild_reactions[reaction])
moment_curve2 = moment_curve2.subs(reaction, self._ild_reactions[reaction])
moment_eq = Piecewise((moment_curve1, x < distance), (moment_curve2, x > distance))
self._ild_moment = moment_eq
def plot_ild_moment(self,subs=None):
"""
Plots the Influence Line Diagram for Moment under the effect
of a moving load. This function should be called after
calling solve_for_ild_moment().
Parameters
==========
subs : dictionary
Python dictionary containing Symbols as key and their
corresponding values.
Examples
========
There is a beam of length 12 meters. There are two simple supports
below the beam, one at the starting point and another at a distance
of 8 meters. Plot the I.L.D. for Moment at a distance
of 4 meters under the effect of a moving load of magnitude 1kN.
.. image:: ildshear.png
Using the sign convention of downwards forces being positive.
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> from sympy import symbols
>>> from sympy.physics.continuum_mechanics.beam import Beam
>>> E, I = symbols('E, I')
>>> R_0, R_8 = symbols('R_0, R_8')
>>> b = Beam(12, E, I)
>>> b.apply_support(0, 'roller')
>>> b.apply_support(8, 'roller')
>>> b.solve_for_ild_reactions(1, R_0, R_8)
>>> b.solve_for_ild_moment(4, 1, R_0, R_8)
>>> b.ild_moment
Piecewise((-x/2, x < 4), (x/2 - 4, x > 4))
>>> b.plot_ild_moment()
Plot object containing:
[0]: cartesian line: Piecewise((-x/2, x < 4), (x/2 - 4, x > 4)) for x over (0.0, 12.0)
"""
if not self._ild_moment:
raise ValueError("I.L.D. moment equation not found. Please use solve_for_ild_moment() to generate the I.L.D. moment equations.")
x = self.variable
if subs is None:
subs = {}
for sym in self._ild_moment.atoms(Symbol):
if sym != x and sym not in subs:
raise ValueError('Value of %s was not passed.' %sym)
for sym in self._length.atoms(Symbol):
if sym != x and sym not in subs:
raise ValueError('Value of %s was not passed.' %sym)
return plot(self._ild_moment.subs(subs), (x, 0, self._length), title='I.L.D. for Moment',
xlabel=r'$\mathrm{X}$', ylabel=r'$\mathrm{M}$', line_color='blue', show=True)
@doctest_depends_on(modules=('numpy',))
def draw(self, pictorial=True):
"""
Returns a plot object representing the beam diagram of the beam.
.. note::
The user must be careful while entering load values.
The draw function assumes a sign convention which is used
for plotting loads.
Given a right handed coordinate system with XYZ coordinates,
the beam's length is assumed to be along the positive X axis.
The draw function recognizes positve loads(with n>-2) as loads
acting along negative Y direction and positve moments acting
along positive Z direction.
Parameters
==========
pictorial: Boolean (default=True)
Setting ``pictorial=True`` would simply create a pictorial (scaled) view
of the beam diagram not with the exact dimensions.
Although setting ``pictorial=False`` would create a beam diagram with
the exact dimensions on the plot
Examples
========
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> from sympy.physics.continuum_mechanics.beam import Beam
>>> from sympy import symbols
>>> R1, R2 = symbols('R1, R2')
>>> E, I = symbols('E, I')
>>> b = Beam(50, 20, 30)
>>> b.apply_load(10, 2, -1)
>>> b.apply_load(R1, 10, -1)
>>> b.apply_load(R2, 30, -1)
>>> b.apply_load(90, 5, 0, 23)
>>> b.apply_load(10, 30, 1, 50)
>>> b.apply_support(50, "pin")
>>> b.apply_support(0, "fixed")
>>> b.apply_support(20, "roller")
>>> p = b.draw()
>>> p
Plot object containing:
[0]: cartesian line: 25*SingularityFunction(x, 5, 0) - 25*SingularityFunction(x, 23, 0)
+ SingularityFunction(x, 30, 1) - 20*SingularityFunction(x, 50, 0)
- SingularityFunction(x, 50, 1) + 5 for x over (0.0, 50.0)
[1]: cartesian line: 5 for x over (0.0, 50.0)
>>> p.show()
"""
if not numpy:
raise ImportError("To use this function numpy module is required")
x = self.variable
# checking whether length is an expression in terms of any Symbol.
if isinstance(self.length, Expr):
l = list(self.length.atoms(Symbol))
# assigning every Symbol a default value of 10
l = {i:10 for i in l}
length = self.length.subs(l)
else:
l = {}
length = self.length
height = length/10
rectangles = []
rectangles.append({'xy':(0, 0), 'width':length, 'height': height, 'facecolor':"brown"})
annotations, markers, load_eq,load_eq1, fill = self._draw_load(pictorial, length, l)
support_markers, support_rectangles = self._draw_supports(length, l)
rectangles += support_rectangles
markers += support_markers
sing_plot = plot(height + load_eq, height + load_eq1, (x, 0, length),
xlim=(-height, length + height), ylim=(-length, 1.25*length), annotations=annotations,
markers=markers, rectangles=rectangles, line_color='brown', fill=fill, axis=False, show=False)
return sing_plot
def _draw_load(self, pictorial, length, l):
loads = list(set(self.applied_loads) - set(self._support_as_loads))
height = length/10
x = self.variable
annotations = []
markers = []
load_args = []
scaled_load = 0
load_args1 = []
scaled_load1 = 0
load_eq = 0 # For positive valued higher order loads
load_eq1 = 0 # For negative valued higher order loads
fill = None
plus = 0 # For positive valued higher order loads
minus = 0 # For negative valued higher order loads
for load in loads:
# check if the position of load is in terms of the beam length.
if l:
pos = load[1].subs(l)
else:
pos = load[1]
# point loads
if load[2] == -1:
if isinstance(load[0], Symbol) or load[0].is_negative:
annotations.append({'text':'', 'xy':(pos, 0), 'xytext':(pos, height - 4*height), 'arrowprops':dict(width= 1.5, headlength=5, headwidth=5, facecolor='black')})
else:
annotations.append({'text':'', 'xy':(pos, height), 'xytext':(pos, height*4), 'arrowprops':dict(width= 1.5, headlength=4, headwidth=4, facecolor='black')})
# moment loads
elif load[2] == -2:
if load[0].is_negative:
markers.append({'args':[[pos], [height/2]], 'marker': r'$\circlearrowright$', 'markersize':15})
else:
markers.append({'args':[[pos], [height/2]], 'marker': r'$\circlearrowleft$', 'markersize':15})
# higher order loads
elif load[2] >= 0:
# `fill` will be assigned only when higher order loads are present
value, start, order, end = load
# Positive loads have their seperate equations
if(value>0):
plus = 1
# if pictorial is True we remake the load equation again with
# some constant magnitude values.
if pictorial:
value = 10**(1-order) if order > 0 else length/2
scaled_load += value*SingularityFunction(x, start, order)
if end:
f2 = 10**(1-order)*x**order if order > 0 else length/2*x**order
for i in range(0, order + 1):
scaled_load -= (f2.diff(x, i).subs(x, end - start)*
SingularityFunction(x, end, i)/factorial(i))
if pictorial:
if isinstance(scaled_load, Add):
load_args = scaled_load.args
else:
# when the load equation consists of only a single term
load_args = (scaled_load,)
load_eq = [i.subs(l) for i in load_args]
else:
if isinstance(self.load, Add):
load_args = self.load.args
else:
load_args = (self.load,)
load_eq = [i.subs(l) for i in load_args if list(i.atoms(SingularityFunction))[0].args[2] >= 0]
load_eq = Add(*load_eq)
# filling higher order loads with colour
expr = height + load_eq.rewrite(Piecewise)
y1 = lambdify(x, expr, 'numpy')
# For loads with negative value
else:
minus = 1
# if pictorial is True we remake the load equation again with
# some constant magnitude values.
if pictorial:
value = 10**(1-order) if order > 0 else length/2
scaled_load1 += value*SingularityFunction(x, start, order)
if end:
f2 = 10**(1-order)*x**order if order > 0 else length/2*x**order
for i in range(0, order + 1):
scaled_load1 -= (f2.diff(x, i).subs(x, end - start)*
SingularityFunction(x, end, i)/factorial(i))
if pictorial:
if isinstance(scaled_load1, Add):
load_args1 = scaled_load1.args
else:
# when the load equation consists of only a single term
load_args1 = (scaled_load1,)
load_eq1 = [i.subs(l) for i in load_args1]
else:
if isinstance(self.load, Add):
load_args1 = self.load.args1
else:
load_args1 = (self.load,)
load_eq1 = [i.subs(l) for i in load_args if list(i.atoms(SingularityFunction))[0].args[2] >= 0]
load_eq1 = -Add(*load_eq1)-height
# filling higher order loads with colour
expr = height + load_eq1.rewrite(Piecewise)
y1_ = lambdify(x, expr, 'numpy')
y = numpy.arange(0, float(length), 0.001)
y2 = float(height)
if(plus == 1 and minus == 1):
fill = {'x': y, 'y1': y1(y), 'y2': y1_(y), 'color':'darkkhaki'}
elif(plus == 1):
fill = {'x': y, 'y1': y1(y), 'y2': y2, 'color':'darkkhaki'}
else:
fill = {'x': y, 'y1': y1_(y), 'y2': y2, 'color':'darkkhaki'}
return annotations, markers, load_eq, load_eq1, fill
def _draw_supports(self, length, l):
height = float(length/10)
support_markers = []
support_rectangles = []
for support in self._applied_supports:
if l:
pos = support[0].subs(l)
else:
pos = support[0]
if support[1] == "pin":
support_markers.append({'args':[pos, [0]], 'marker':6, 'markersize':13, 'color':"black"})
elif support[1] == "roller":
support_markers.append({'args':[pos, [-height/2.5]], 'marker':'o', 'markersize':11, 'color':"black"})
elif support[1] == "fixed":
if pos == 0:
support_rectangles.append({'xy':(0, -3*height), 'width':-length/20, 'height':6*height + height, 'fill':False, 'hatch':'/////'})
else:
support_rectangles.append({'xy':(length, -3*height), 'width':length/20, 'height': 6*height + height, 'fill':False, 'hatch':'/////'})
return support_markers, support_rectangles
class Beam3D(Beam):
"""
This class handles loads applied in any direction of a 3D space along
with unequal values of Second moment along different axes.
.. note::
A consistent sign convention must be used while solving a beam
bending problem; the results will
automatically follow the chosen sign convention.
This class assumes that any kind of distributed load/moment is
applied through out the span of a beam.
Examples
========
There is a beam of l meters long. A constant distributed load of magnitude q
is applied along y-axis from start till the end of beam. A constant distributed
moment of magnitude m is also applied along z-axis from start till the end of beam.
Beam is fixed at both of its end. So, deflection of the beam at the both ends
is restricted.
>>> from sympy.physics.continuum_mechanics.beam import Beam3D
>>> from sympy import symbols, simplify, collect, factor
>>> l, E, G, I, A = symbols('l, E, G, I, A')
>>> b = Beam3D(l, E, G, I, A)
>>> x, q, m = symbols('x, q, m')
>>> b.apply_load(q, 0, 0, dir="y")
>>> b.apply_moment_load(m, 0, -1, dir="z")
>>> b.shear_force()
[0, -q*x, 0]
>>> b.bending_moment()
[0, 0, -m*x + q*x**2/2]
>>> b.bc_slope = [(0, [0, 0, 0]), (l, [0, 0, 0])]
>>> b.bc_deflection = [(0, [0, 0, 0]), (l, [0, 0, 0])]
>>> b.solve_slope_deflection()
>>> factor(b.slope())
[0, 0, x*(-l + x)*(-A*G*l**3*q + 2*A*G*l**2*q*x - 12*E*I*l*q
- 72*E*I*m + 24*E*I*q*x)/(12*E*I*(A*G*l**2 + 12*E*I))]
>>> dx, dy, dz = b.deflection()
>>> dy = collect(simplify(dy), x)
>>> dx == dz == 0
True
>>> dy == (x*(12*E*I*l*(A*G*l**2*q - 2*A*G*l*m + 12*E*I*q)
... + x*(A*G*l*(3*l*(A*G*l**2*q - 2*A*G*l*m + 12*E*I*q) + x*(-2*A*G*l**2*q + 4*A*G*l*m - 24*E*I*q))
... + A*G*(A*G*l**2 + 12*E*I)*(-2*l**2*q + 6*l*m - 4*m*x + q*x**2)
... - 12*E*I*q*(A*G*l**2 + 12*E*I)))/(24*A*E*G*I*(A*G*l**2 + 12*E*I)))
True
References
==========
.. [1] http://homes.civil.aau.dk/jc/FemteSemester/Beams3D.pdf
"""
def __init__(self, length, elastic_modulus, shear_modulus, second_moment,
area, variable=Symbol('x')):
"""Initializes the class.
Parameters
==========
length : Sympifyable
A Symbol or value representing the Beam's length.
elastic_modulus : Sympifyable
A SymPy expression representing the Beam's Modulus of Elasticity.
It is a measure of the stiffness of the Beam material.
shear_modulus : Sympifyable
A SymPy expression representing the Beam's Modulus of rigidity.
It is a measure of rigidity of the Beam material.
second_moment : Sympifyable or list
A list of two elements having SymPy expression representing the
Beam's Second moment of area. First value represent Second moment
across y-axis and second across z-axis.
Single SymPy expression can be passed if both values are same
area : Sympifyable
A SymPy expression representing the Beam's cross-sectional area
in a plane prependicular to length of the Beam.
variable : Symbol, optional
A Symbol object that will be used as the variable along the beam
while representing the load, shear, moment, slope and deflection
curve. By default, it is set to ``Symbol('x')``.
"""
super().__init__(length, elastic_modulus, second_moment, variable)
self.shear_modulus = shear_modulus
self.area = area
self._load_vector = [0, 0, 0]
self._moment_load_vector = [0, 0, 0]
self._load_Singularity = [0, 0, 0]
self._slope = [0, 0, 0]
self._deflection = [0, 0, 0]
@property
def shear_modulus(self):
"""Young's Modulus of the Beam. """
return self._shear_modulus
@shear_modulus.setter
def shear_modulus(self, e):
self._shear_modulus = sympify(e)
@property
def second_moment(self):
"""Second moment of area of the Beam. """
return self._second_moment
@second_moment.setter
def second_moment(self, i):
if isinstance(i, list):
i = [sympify(x) for x in i]
self._second_moment = i
else:
self._second_moment = sympify(i)
@property
def area(self):
"""Cross-sectional area of the Beam. """
return self._area
@area.setter
def area(self, a):
self._area = sympify(a)
@property
def load_vector(self):
"""
Returns a three element list representing the load vector.
"""
return self._load_vector
@property
def moment_load_vector(self):
"""
Returns a three element list representing moment loads on Beam.
"""
return self._moment_load_vector
@property
def boundary_conditions(self):
"""
Returns a dictionary of boundary conditions applied on the beam.
The dictionary has two keywords namely slope and deflection.
The value of each keyword is a list of tuple, where each tuple
contains location and value of a boundary condition in the format
(location, value). Further each value is a list corresponding to
slope or deflection(s) values along three axes at that location.
Examples
========
There is a beam of length 4 meters. The slope at 0 should be 4 along
the x-axis and 0 along others. At the other end of beam, deflection
along all the three axes should be zero.
>>> from sympy.physics.continuum_mechanics.beam import Beam3D
>>> from sympy import symbols
>>> l, E, G, I, A, x = symbols('l, E, G, I, A, x')
>>> b = Beam3D(30, E, G, I, A, x)
>>> b.bc_slope = [(0, (4, 0, 0))]
>>> b.bc_deflection = [(4, [0, 0, 0])]
>>> b.boundary_conditions
{'deflection': [(4, [0, 0, 0])], 'slope': [(0, (4, 0, 0))]}
Here the deflection of the beam should be ``0`` along all the three axes at ``4``.
Similarly, the slope of the beam should be ``4`` along x-axis and ``0``
along y and z axis at ``0``.
"""
return self._boundary_conditions
def polar_moment(self):
"""
Returns the polar moment of area of the beam
about the X axis with respect to the centroid.
Examples
========
>>> from sympy.physics.continuum_mechanics.beam import Beam3D
>>> from sympy import symbols
>>> l, E, G, I, A = symbols('l, E, G, I, A')
>>> b = Beam3D(l, E, G, I, A)
>>> b.polar_moment()
2*I
>>> I1 = [9, 15]
>>> b = Beam3D(l, E, G, I1, A)
>>> b.polar_moment()
24
"""
if not iterable(self.second_moment):
return 2*self.second_moment
return sum(self.second_moment)
def apply_load(self, value, start, order, dir="y"):
"""
This method adds up the force load to a particular beam object.
Parameters
==========
value : Sympifyable
The magnitude of an applied load.
dir : String
Axis along which load is applied.
order : Integer
The order of the applied load.
- For point loads, order=-1
- For constant distributed load, order=0
- For ramp loads, order=1
- For parabolic ramp loads, order=2
- ... so on.
"""
x = self.variable
value = sympify(value)
start = sympify(start)
order = sympify(order)
if dir == "x":
if not order == -1:
self._load_vector[0] += value
self._load_Singularity[0] += value*SingularityFunction(x, start, order)
elif dir == "y":
if not order == -1:
self._load_vector[1] += value
self._load_Singularity[1] += value*SingularityFunction(x, start, order)
else:
if not order == -1:
self._load_vector[2] += value
self._load_Singularity[2] += value*SingularityFunction(x, start, order)
def apply_moment_load(self, value, start, order, dir="y"):
"""
This method adds up the moment loads to a particular beam object.
Parameters
==========
value : Sympifyable
The magnitude of an applied moment.
dir : String
Axis along which moment is applied.
order : Integer
The order of the applied load.
- For point moments, order=-2
- For constant distributed moment, order=-1
- For ramp moments, order=0
- For parabolic ramp moments, order=1
- ... so on.
"""
x = self.variable
value = sympify(value)
start = sympify(start)
order = sympify(order)
if dir == "x":
if not order == -2:
self._moment_load_vector[0] += value
self._load_Singularity[0] += value*SingularityFunction(x, start, order)
elif dir == "y":
if not order == -2:
self._moment_load_vector[1] += value
self._load_Singularity[0] += value*SingularityFunction(x, start, order)
else:
if not order == -2:
self._moment_load_vector[2] += value
self._load_Singularity[0] += value*SingularityFunction(x, start, order)
def apply_support(self, loc, type="fixed"):
if type in ("pin", "roller"):
reaction_load = Symbol('R_'+str(loc))
self._reaction_loads[reaction_load] = reaction_load
self.bc_deflection.append((loc, [0, 0, 0]))
else:
reaction_load = Symbol('R_'+str(loc))
reaction_moment = Symbol('M_'+str(loc))
self._reaction_loads[reaction_load] = [reaction_load, reaction_moment]
self.bc_deflection.append((loc, [0, 0, 0]))
self.bc_slope.append((loc, [0, 0, 0]))
def solve_for_reaction_loads(self, *reaction):
"""
Solves for the reaction forces.
Examples
========
There is a beam of length 30 meters. It it supported by rollers at
of its end. A constant distributed load of magnitude 8 N is applied
from start till its end along y-axis. Another linear load having
slope equal to 9 is applied along z-axis.
>>> from sympy.physics.continuum_mechanics.beam import Beam3D
>>> from sympy import symbols
>>> l, E, G, I, A, x = symbols('l, E, G, I, A, x')
>>> b = Beam3D(30, E, G, I, A, x)
>>> b.apply_load(8, start=0, order=0, dir="y")
>>> b.apply_load(9*x, start=0, order=0, dir="z")
>>> b.bc_deflection = [(0, [0, 0, 0]), (30, [0, 0, 0])]
>>> R1, R2, R3, R4 = symbols('R1, R2, R3, R4')
>>> b.apply_load(R1, start=0, order=-1, dir="y")
>>> b.apply_load(R2, start=30, order=-1, dir="y")
>>> b.apply_load(R3, start=0, order=-1, dir="z")
>>> b.apply_load(R4, start=30, order=-1, dir="z")
>>> b.solve_for_reaction_loads(R1, R2, R3, R4)
>>> b.reaction_loads
{R1: -120, R2: -120, R3: -1350, R4: -2700}
"""
x = self.variable
l = self.length
q = self._load_Singularity
shear_curves = [integrate(load, x) for load in q]
moment_curves = [integrate(shear, x) for shear in shear_curves]
for i in range(3):
react = [r for r in reaction if (shear_curves[i].has(r) or moment_curves[i].has(r))]
if len(react) == 0:
continue
shear_curve = limit(shear_curves[i], x, l)
moment_curve = limit(moment_curves[i], x, l)
sol = list((linsolve([shear_curve, moment_curve], react).args)[0])
sol_dict = dict(zip(react, sol))
reaction_loads = self._reaction_loads
# Check if any of the evaluated rection exists in another direction
# and if it exists then it should have same value.
for key in sol_dict:
if key in reaction_loads and sol_dict[key] != reaction_loads[key]:
raise ValueError("Ambiguous solution for %s in different directions." % key)
self._reaction_loads.update(sol_dict)
def shear_force(self):
"""
Returns a list of three expressions which represents the shear force
curve of the Beam object along all three axes.
"""
x = self.variable
q = self._load_vector
return [integrate(-q[0], x), integrate(-q[1], x), integrate(-q[2], x)]
def axial_force(self):
"""
Returns expression of Axial shear force present inside the Beam object.
"""
return self.shear_force()[0]
def shear_stress(self):
"""
Returns a list of three expressions which represents the shear stress
curve of the Beam object along all three axes.
"""
return [self.shear_force()[0]/self._area, self.shear_force()[1]/self._area, self.shear_force()[2]/self._area]
def axial_stress(self):
"""
Returns expression of Axial stress present inside the Beam object.
"""
return self.axial_force()/self._area
def bending_moment(self):
"""
Returns a list of three expressions which represents the bending moment
curve of the Beam object along all three axes.
"""
x = self.variable
m = self._moment_load_vector
shear = self.shear_force()
return [integrate(-m[0], x), integrate(-m[1] + shear[2], x),
integrate(-m[2] - shear[1], x) ]
def torsional_moment(self):
"""
Returns expression of Torsional moment present inside the Beam object.
"""
return self.bending_moment()[0]
def solve_slope_deflection(self):
x = self.variable
l = self.length
E = self.elastic_modulus
G = self.shear_modulus
I = self.second_moment
if isinstance(I, list):
I_y, I_z = I[0], I[1]
else:
I_y = I_z = I
A = self._area
load = self._load_vector
moment = self._moment_load_vector
defl = Function('defl')
theta = Function('theta')
# Finding deflection along x-axis(and corresponding slope value by differentiating it)
# Equation used: Derivative(E*A*Derivative(def_x(x), x), x) + load_x = 0
eq = Derivative(E*A*Derivative(defl(x), x), x) + load[0]
def_x = dsolve(Eq(eq, 0), defl(x)).args[1]
# Solving constants originated from dsolve
C1 = Symbol('C1')
C2 = Symbol('C2')
constants = list((linsolve([def_x.subs(x, 0), def_x.subs(x, l)], C1, C2).args)[0])
def_x = def_x.subs({C1:constants[0], C2:constants[1]})
slope_x = def_x.diff(x)
self._deflection[0] = def_x
self._slope[0] = slope_x
# Finding deflection along y-axis and slope across z-axis. System of equation involved:
# 1: Derivative(E*I_z*Derivative(theta_z(x), x), x) + G*A*(Derivative(defl_y(x), x) - theta_z(x)) + moment_z = 0
# 2: Derivative(G*A*(Derivative(defl_y(x), x) - theta_z(x)), x) + load_y = 0
C_i = Symbol('C_i')
# Substitute value of `G*A*(Derivative(defl_y(x), x) - theta_z(x))` from (2) in (1)
eq1 = Derivative(E*I_z*Derivative(theta(x), x), x) + (integrate(-load[1], x) + C_i) + moment[2]
slope_z = dsolve(Eq(eq1, 0)).args[1]
# Solve for constants originated from using dsolve on eq1
constants = list((linsolve([slope_z.subs(x, 0), slope_z.subs(x, l)], C1, C2).args)[0])
slope_z = slope_z.subs({C1:constants[0], C2:constants[1]})
# Put value of slope obtained back in (2) to solve for `C_i` and find deflection across y-axis
eq2 = G*A*(Derivative(defl(x), x)) + load[1]*x - C_i - G*A*slope_z
def_y = dsolve(Eq(eq2, 0), defl(x)).args[1]
# Solve for constants originated from using dsolve on eq2
constants = list((linsolve([def_y.subs(x, 0), def_y.subs(x, l)], C1, C_i).args)[0])
self._deflection[1] = def_y.subs({C1:constants[0], C_i:constants[1]})
self._slope[2] = slope_z.subs(C_i, constants[1])
# Finding deflection along z-axis and slope across y-axis. System of equation involved:
# 1: Derivative(E*I_y*Derivative(theta_y(x), x), x) - G*A*(Derivative(defl_z(x), x) + theta_y(x)) + moment_y = 0
# 2: Derivative(G*A*(Derivative(defl_z(x), x) + theta_y(x)), x) + load_z = 0
# Substitute value of `G*A*(Derivative(defl_y(x), x) + theta_z(x))` from (2) in (1)
eq1 = Derivative(E*I_y*Derivative(theta(x), x), x) + (integrate(load[2], x) - C_i) + moment[1]
slope_y = dsolve(Eq(eq1, 0)).args[1]
# Solve for constants originated from using dsolve on eq1
constants = list((linsolve([slope_y.subs(x, 0), slope_y.subs(x, l)], C1, C2).args)[0])
slope_y = slope_y.subs({C1:constants[0], C2:constants[1]})
# Put value of slope obtained back in (2) to solve for `C_i` and find deflection across z-axis
eq2 = G*A*(Derivative(defl(x), x)) + load[2]*x - C_i + G*A*slope_y
def_z = dsolve(Eq(eq2,0)).args[1]
# Solve for constants originated from using dsolve on eq2
constants = list((linsolve([def_z.subs(x, 0), def_z.subs(x, l)], C1, C_i).args)[0])
self._deflection[2] = def_z.subs({C1:constants[0], C_i:constants[1]})
self._slope[1] = slope_y.subs(C_i, constants[1])
def slope(self):
"""
Returns a three element list representing slope of deflection curve
along all the three axes.
"""
return self._slope
def deflection(self):
"""
Returns a three element list representing deflection curve along all
the three axes.
"""
return self._deflection
def _plot_shear_force(self, dir, subs=None):
shear_force = self.shear_force()
if dir == 'x':
dir_num = 0
color = 'r'
elif dir == 'y':
dir_num = 1
color = 'g'
elif dir == 'z':
dir_num = 2
color = 'b'
if subs is None:
subs = {}
for sym in shear_force[dir_num].atoms(Symbol):
if sym != self.variable and sym not in subs:
raise ValueError('Value of %s was not passed.' %sym)
if self.length in subs:
length = subs[self.length]
else:
length = self.length
return plot(shear_force[dir_num].subs(subs), (self.variable, 0, length), show = False, title='Shear Force along %c direction'%dir,
xlabel=r'$\mathrm{X}$', ylabel=r'$\mathrm{V(%c)}$'%dir, line_color=color)
def plot_shear_force(self, dir="all", subs=None):
"""
Returns a plot for Shear force along all three directions
present in the Beam object.
Parameters
==========
dir : string (default : "all")
Direction along which shear force plot is required.
If no direction is specified, all plots are displayed.
subs : dictionary
Python dictionary containing Symbols as key and their
corresponding values.
Examples
========
There is a beam of length 20 meters. It it supported by rollers
at of its end. A linear load having slope equal to 12 is applied
along y-axis. A constant distributed load of magnitude 15 N is
applied from start till its end along z-axis.
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> from sympy.physics.continuum_mechanics.beam import Beam3D
>>> from sympy import symbols
>>> l, E, G, I, A, x = symbols('l, E, G, I, A, x')
>>> b = Beam3D(20, E, G, I, A, x)
>>> b.apply_load(15, start=0, order=0, dir="z")
>>> b.apply_load(12*x, start=0, order=0, dir="y")
>>> b.bc_deflection = [(0, [0, 0, 0]), (20, [0, 0, 0])]
>>> R1, R2, R3, R4 = symbols('R1, R2, R3, R4')
>>> b.apply_load(R1, start=0, order=-1, dir="z")
>>> b.apply_load(R2, start=20, order=-1, dir="z")
>>> b.apply_load(R3, start=0, order=-1, dir="y")
>>> b.apply_load(R4, start=20, order=-1, dir="y")
>>> b.solve_for_reaction_loads(R1, R2, R3, R4)
>>> b.plot_shear_force()
PlotGrid object containing:
Plot[0]:Plot object containing:
[0]: cartesian line: 0 for x over (0.0, 20.0)
Plot[1]:Plot object containing:
[0]: cartesian line: -6*x**2 for x over (0.0, 20.0)
Plot[2]:Plot object containing:
[0]: cartesian line: -15*x for x over (0.0, 20.0)
"""
dir = dir.lower()
# For shear force along x direction
if dir == "x":
Px = self._plot_shear_force('x', subs)
return Px.show()
# For shear force along y direction
elif dir == "y":
Py = self._plot_shear_force('y', subs)
return Py.show()
# For shear force along z direction
elif dir == "z":
Pz = self._plot_shear_force('z', subs)
return Pz.show()
# For shear force along all direction
else:
Px = self._plot_shear_force('x', subs)
Py = self._plot_shear_force('y', subs)
Pz = self._plot_shear_force('z', subs)
return PlotGrid(3, 1, Px, Py, Pz)
def _plot_bending_moment(self, dir, subs=None):
bending_moment = self.bending_moment()
if dir == 'x':
dir_num = 0
color = 'g'
elif dir == 'y':
dir_num = 1
color = 'c'
elif dir == 'z':
dir_num = 2
color = 'm'
if subs is None:
subs = {}
for sym in bending_moment[dir_num].atoms(Symbol):
if sym != self.variable and sym not in subs:
raise ValueError('Value of %s was not passed.' %sym)
if self.length in subs:
length = subs[self.length]
else:
length = self.length
return plot(bending_moment[dir_num].subs(subs), (self.variable, 0, length), show = False, title='Bending Moment along %c direction'%dir,
xlabel=r'$\mathrm{X}$', ylabel=r'$\mathrm{M(%c)}$'%dir, line_color=color)
def plot_bending_moment(self, dir="all", subs=None):
"""
Returns a plot for bending moment along all three directions
present in the Beam object.
Parameters
==========
dir : string (default : "all")
Direction along which bending moment plot is required.
If no direction is specified, all plots are displayed.
subs : dictionary
Python dictionary containing Symbols as key and their
corresponding values.
Examples
========
There is a beam of length 20 meters. It it supported by rollers
at of its end. A linear load having slope equal to 12 is applied
along y-axis. A constant distributed load of magnitude 15 N is
applied from start till its end along z-axis.
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> from sympy.physics.continuum_mechanics.beam import Beam3D
>>> from sympy import symbols
>>> l, E, G, I, A, x = symbols('l, E, G, I, A, x')
>>> b = Beam3D(20, E, G, I, A, x)
>>> b.apply_load(15, start=0, order=0, dir="z")
>>> b.apply_load(12*x, start=0, order=0, dir="y")
>>> b.bc_deflection = [(0, [0, 0, 0]), (20, [0, 0, 0])]
>>> R1, R2, R3, R4 = symbols('R1, R2, R3, R4')
>>> b.apply_load(R1, start=0, order=-1, dir="z")
>>> b.apply_load(R2, start=20, order=-1, dir="z")
>>> b.apply_load(R3, start=0, order=-1, dir="y")
>>> b.apply_load(R4, start=20, order=-1, dir="y")
>>> b.solve_for_reaction_loads(R1, R2, R3, R4)
>>> b.plot_bending_moment()
PlotGrid object containing:
Plot[0]:Plot object containing:
[0]: cartesian line: 0 for x over (0.0, 20.0)
Plot[1]:Plot object containing:
[0]: cartesian line: -15*x**2/2 for x over (0.0, 20.0)
Plot[2]:Plot object containing:
[0]: cartesian line: 2*x**3 for x over (0.0, 20.0)
"""
dir = dir.lower()
# For bending moment along x direction
if dir == "x":
Px = self._plot_bending_moment('x', subs)
return Px.show()
# For bending moment along y direction
elif dir == "y":
Py = self._plot_bending_moment('y', subs)
return Py.show()
# For bending moment along z direction
elif dir == "z":
Pz = self._plot_bending_moment('z', subs)
return Pz.show()
# For bending moment along all direction
else:
Px = self._plot_bending_moment('x', subs)
Py = self._plot_bending_moment('y', subs)
Pz = self._plot_bending_moment('z', subs)
return PlotGrid(3, 1, Px, Py, Pz)
def _plot_slope(self, dir, subs=None):
slope = self.slope()
if dir == 'x':
dir_num = 0
color = 'b'
elif dir == 'y':
dir_num = 1
color = 'm'
elif dir == 'z':
dir_num = 2
color = 'g'
if subs is None:
subs = {}
for sym in slope[dir_num].atoms(Symbol):
if sym != self.variable and sym not in subs:
raise ValueError('Value of %s was not passed.' %sym)
if self.length in subs:
length = subs[self.length]
else:
length = self.length
return plot(slope[dir_num].subs(subs), (self.variable, 0, length), show = False, title='Slope along %c direction'%dir,
xlabel=r'$\mathrm{X}$', ylabel=r'$\mathrm{\theta(%c)}$'%dir, line_color=color)
def plot_slope(self, dir="all", subs=None):
"""
Returns a plot for Slope along all three directions
present in the Beam object.
Parameters
==========
dir : string (default : "all")
Direction along which Slope plot is required.
If no direction is specified, all plots are displayed.
subs : dictionary
Python dictionary containing Symbols as keys and their
corresponding values.
Examples
========
There is a beam of length 20 meters. It it supported by rollers
at of its end. A linear load having slope equal to 12 is applied
along y-axis. A constant distributed load of magnitude 15 N is
applied from start till its end along z-axis.
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> from sympy.physics.continuum_mechanics.beam import Beam3D
>>> from sympy import symbols
>>> l, E, G, I, A, x = symbols('l, E, G, I, A, x')
>>> b = Beam3D(20, 40, 21, 100, 25, x)
>>> b.apply_load(15, start=0, order=0, dir="z")
>>> b.apply_load(12*x, start=0, order=0, dir="y")
>>> b.bc_deflection = [(0, [0, 0, 0]), (20, [0, 0, 0])]
>>> R1, R2, R3, R4 = symbols('R1, R2, R3, R4')
>>> b.apply_load(R1, start=0, order=-1, dir="z")
>>> b.apply_load(R2, start=20, order=-1, dir="z")
>>> b.apply_load(R3, start=0, order=-1, dir="y")
>>> b.apply_load(R4, start=20, order=-1, dir="y")
>>> b.solve_for_reaction_loads(R1, R2, R3, R4)
>>> b.solve_slope_deflection()
>>> b.plot_slope()
PlotGrid object containing:
Plot[0]:Plot object containing:
[0]: cartesian line: 0 for x over (0.0, 20.0)
Plot[1]:Plot object containing:
[0]: cartesian line: -x**3/1600 + 3*x**2/160 - x/8 for x over (0.0, 20.0)
Plot[2]:Plot object containing:
[0]: cartesian line: x**4/8000 - 19*x**2/172 + 52*x/43 for x over (0.0, 20.0)
"""
dir = dir.lower()
# For Slope along x direction
if dir == "x":
Px = self._plot_slope('x', subs)
return Px.show()
# For Slope along y direction
elif dir == "y":
Py = self._plot_slope('y', subs)
return Py.show()
# For Slope along z direction
elif dir == "z":
Pz = self._plot_slope('z', subs)
return Pz.show()
# For Slope along all direction
else:
Px = self._plot_slope('x', subs)
Py = self._plot_slope('y', subs)
Pz = self._plot_slope('z', subs)
return PlotGrid(3, 1, Px, Py, Pz)
def _plot_deflection(self, dir, subs=None):
deflection = self.deflection()
if dir == 'x':
dir_num = 0
color = 'm'
elif dir == 'y':
dir_num = 1
color = 'r'
elif dir == 'z':
dir_num = 2
color = 'c'
if subs is None:
subs = {}
for sym in deflection[dir_num].atoms(Symbol):
if sym != self.variable and sym not in subs:
raise ValueError('Value of %s was not passed.' %sym)
if self.length in subs:
length = subs[self.length]
else:
length = self.length
return plot(deflection[dir_num].subs(subs), (self.variable, 0, length), show = False, title='Deflection along %c direction'%dir,
xlabel=r'$\mathrm{X}$', ylabel=r'$\mathrm{\delta(%c)}$'%dir, line_color=color)
def plot_deflection(self, dir="all", subs=None):
"""
Returns a plot for Deflection along all three directions
present in the Beam object.
Parameters
==========
dir : string (default : "all")
Direction along which deflection plot is required.
If no direction is specified, all plots are displayed.
subs : dictionary
Python dictionary containing Symbols as keys and their
corresponding values.
Examples
========
There is a beam of length 20 meters. It it supported by rollers
at of its end. A linear load having slope equal to 12 is applied
along y-axis. A constant distributed load of magnitude 15 N is
applied from start till its end along z-axis.
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> from sympy.physics.continuum_mechanics.beam import Beam3D
>>> from sympy import symbols
>>> l, E, G, I, A, x = symbols('l, E, G, I, A, x')
>>> b = Beam3D(20, 40, 21, 100, 25, x)
>>> b.apply_load(15, start=0, order=0, dir="z")
>>> b.apply_load(12*x, start=0, order=0, dir="y")
>>> b.bc_deflection = [(0, [0, 0, 0]), (20, [0, 0, 0])]
>>> R1, R2, R3, R4 = symbols('R1, R2, R3, R4')
>>> b.apply_load(R1, start=0, order=-1, dir="z")
>>> b.apply_load(R2, start=20, order=-1, dir="z")
>>> b.apply_load(R3, start=0, order=-1, dir="y")
>>> b.apply_load(R4, start=20, order=-1, dir="y")
>>> b.solve_for_reaction_loads(R1, R2, R3, R4)
>>> b.solve_slope_deflection()
>>> b.plot_deflection()
PlotGrid object containing:
Plot[0]:Plot object containing:
[0]: cartesian line: 0 for x over (0.0, 20.0)
Plot[1]:Plot object containing:
[0]: cartesian line: x**5/40000 - 4013*x**3/90300 + 26*x**2/43 + 1520*x/903 for x over (0.0, 20.0)
Plot[2]:Plot object containing:
[0]: cartesian line: x**4/6400 - x**3/160 + 27*x**2/560 + 2*x/7 for x over (0.0, 20.0)
"""
dir = dir.lower()
# For deflection along x direction
if dir == "x":
Px = self._plot_deflection('x', subs)
return Px.show()
# For deflection along y direction
elif dir == "y":
Py = self._plot_deflection('y', subs)
return Py.show()
# For deflection along z direction
elif dir == "z":
Pz = self._plot_deflection('z', subs)
return Pz.show()
# For deflection along all direction
else:
Px = self._plot_deflection('x', subs)
Py = self._plot_deflection('y', subs)
Pz = self._plot_deflection('z', subs)
return PlotGrid(3, 1, Px, Py, Pz)
def plot_loading_results(self, dir='x', subs=None):
"""
Returns a subplot of Shear Force, Bending Moment,
Slope and Deflection of the Beam object along the direction specified.
Parameters
==========
dir : string (default : "x")
Direction along which plots are required.
If no direction is specified, plots along x-axis are displayed.
subs : dictionary
Python dictionary containing Symbols as key and their
corresponding values.
Examples
========
There is a beam of length 20 meters. It it supported by rollers
at of its end. A linear load having slope equal to 12 is applied
along y-axis. A constant distributed load of magnitude 15 N is
applied from start till its end along z-axis.
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> from sympy.physics.continuum_mechanics.beam import Beam3D
>>> from sympy import symbols
>>> l, E, G, I, A, x = symbols('l, E, G, I, A, x')
>>> b = Beam3D(20, E, G, I, A, x)
>>> subs = {E:40, G:21, I:100, A:25}
>>> b.apply_load(15, start=0, order=0, dir="z")
>>> b.apply_load(12*x, start=0, order=0, dir="y")
>>> b.bc_deflection = [(0, [0, 0, 0]), (20, [0, 0, 0])]
>>> R1, R2, R3, R4 = symbols('R1, R2, R3, R4')
>>> b.apply_load(R1, start=0, order=-1, dir="z")
>>> b.apply_load(R2, start=20, order=-1, dir="z")
>>> b.apply_load(R3, start=0, order=-1, dir="y")
>>> b.apply_load(R4, start=20, order=-1, dir="y")
>>> b.solve_for_reaction_loads(R1, R2, R3, R4)
>>> b.solve_slope_deflection()
>>> b.plot_loading_results('y',subs)
PlotGrid object containing:
Plot[0]:Plot object containing:
[0]: cartesian line: -6*x**2 for x over (0.0, 20.0)
Plot[1]:Plot object containing:
[0]: cartesian line: -15*x**2/2 for x over (0.0, 20.0)
Plot[2]:Plot object containing:
[0]: cartesian line: -x**3/1600 + 3*x**2/160 - x/8 for x over (0.0, 20.0)
Plot[3]:Plot object containing:
[0]: cartesian line: x**5/40000 - 4013*x**3/90300 + 26*x**2/43 + 1520*x/903 for x over (0.0, 20.0)
"""
dir = dir.lower()
if subs is None:
subs = {}
ax1 = self._plot_shear_force(dir, subs)
ax2 = self._plot_bending_moment(dir, subs)
ax3 = self._plot_slope(dir, subs)
ax4 = self._plot_deflection(dir, subs)
return PlotGrid(4, 1, ax1, ax2, ax3, ax4)
def _plot_shear_stress(self, dir, subs=None):
shear_stress = self.shear_stress()
if dir == 'x':
dir_num = 0
color = 'r'
elif dir == 'y':
dir_num = 1
color = 'g'
elif dir == 'z':
dir_num = 2
color = 'b'
if subs is None:
subs = {}
for sym in shear_stress[dir_num].atoms(Symbol):
if sym != self.variable and sym not in subs:
raise ValueError('Value of %s was not passed.' %sym)
if self.length in subs:
length = subs[self.length]
else:
length = self.length
return plot(shear_stress[dir_num].subs(subs), (self.variable, 0, length), show = False, title='Shear stress along %c direction'%dir,
xlabel=r'$\mathrm{X}$', ylabel=r'$\tau(%c)$'%dir, line_color=color)
def plot_shear_stress(self, dir="all", subs=None):
"""
Returns a plot for Shear Stress along all three directions
present in the Beam object.
Parameters
==========
dir : string (default : "all")
Direction along which shear stress plot is required.
If no direction is specified, all plots are displayed.
subs : dictionary
Python dictionary containing Symbols as key and their
corresponding values.
Examples
========
There is a beam of length 20 meters and area of cross section 2 square
meters. It it supported by rollers at of its end. A linear load having
slope equal to 12 is applied along y-axis. A constant distributed load
of magnitude 15 N is applied from start till its end along z-axis.
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> from sympy.physics.continuum_mechanics.beam import Beam3D
>>> from sympy import symbols
>>> l, E, G, I, A, x = symbols('l, E, G, I, A, x')
>>> b = Beam3D(20, E, G, I, 2, x)
>>> b.apply_load(15, start=0, order=0, dir="z")
>>> b.apply_load(12*x, start=0, order=0, dir="y")
>>> b.bc_deflection = [(0, [0, 0, 0]), (20, [0, 0, 0])]
>>> R1, R2, R3, R4 = symbols('R1, R2, R3, R4')
>>> b.apply_load(R1, start=0, order=-1, dir="z")
>>> b.apply_load(R2, start=20, order=-1, dir="z")
>>> b.apply_load(R3, start=0, order=-1, dir="y")
>>> b.apply_load(R4, start=20, order=-1, dir="y")
>>> b.solve_for_reaction_loads(R1, R2, R3, R4)
>>> b.plot_shear_stress()
PlotGrid object containing:
Plot[0]:Plot object containing:
[0]: cartesian line: 0 for x over (0.0, 20.0)
Plot[1]:Plot object containing:
[0]: cartesian line: -3*x**2 for x over (0.0, 20.0)
Plot[2]:Plot object containing:
[0]: cartesian line: -15*x/2 for x over (0.0, 20.0)
"""
dir = dir.lower()
# For shear stress along x direction
if dir == "x":
Px = self._plot_shear_stress('x', subs)
return Px.show()
# For shear stress along y direction
elif dir == "y":
Py = self._plot_shear_stress('y', subs)
return Py.show()
# For shear stress along z direction
elif dir == "z":
Pz = self._plot_shear_stress('z', subs)
return Pz.show()
# For shear stress along all direction
else:
Px = self._plot_shear_stress('x', subs)
Py = self._plot_shear_stress('y', subs)
Pz = self._plot_shear_stress('z', subs)
return PlotGrid(3, 1, Px, Py, Pz)
def _max_shear_force(self, dir):
"""
Helper function for max_shear_force().
"""
dir = dir.lower()
if dir == 'x':
dir_num = 0
elif dir == 'y':
dir_num = 1
elif dir == 'z':
dir_num = 2
if not self.shear_force()[dir_num]:
return (0,0)
# To restrict the range within length of the Beam
load_curve = Piecewise((float("nan"), self.variable<=0),
(self._load_vector[dir_num], self.variable<self.length),
(float("nan"), True))
points = solve(load_curve.rewrite(Piecewise), self.variable,
domain=S.Reals)
points.append(0)
points.append(self.length)
shear_curve = self.shear_force()[dir_num]
shear_values = [shear_curve.subs(self.variable, x) for x in points]
shear_values = list(map(abs, shear_values))
max_shear = max(shear_values)
return (points[shear_values.index(max_shear)], max_shear)
def max_shear_force(self):
"""
Returns point of max shear force and its corresponding shear value
along all directions in a Beam object as a list.
solve_for_reaction_loads() must be called before using this function.
Examples
========
There is a beam of length 20 meters. It it supported by rollers
at of its end. A linear load having slope equal to 12 is applied
along y-axis. A constant distributed load of magnitude 15 N is
applied from start till its end along z-axis.
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> from sympy.physics.continuum_mechanics.beam import Beam3D
>>> from sympy import symbols
>>> l, E, G, I, A, x = symbols('l, E, G, I, A, x')
>>> b = Beam3D(20, 40, 21, 100, 25, x)
>>> b.apply_load(15, start=0, order=0, dir="z")
>>> b.apply_load(12*x, start=0, order=0, dir="y")
>>> b.bc_deflection = [(0, [0, 0, 0]), (20, [0, 0, 0])]
>>> R1, R2, R3, R4 = symbols('R1, R2, R3, R4')
>>> b.apply_load(R1, start=0, order=-1, dir="z")
>>> b.apply_load(R2, start=20, order=-1, dir="z")
>>> b.apply_load(R3, start=0, order=-1, dir="y")
>>> b.apply_load(R4, start=20, order=-1, dir="y")
>>> b.solve_for_reaction_loads(R1, R2, R3, R4)
>>> b.max_shear_force()
[(0, 0), (20, 2400), (20, 300)]
"""
max_shear = []
max_shear.append(self._max_shear_force('x'))
max_shear.append(self._max_shear_force('y'))
max_shear.append(self._max_shear_force('z'))
return max_shear
def _max_bending_moment(self, dir):
"""
Helper function for max_bending_moment().
"""
dir = dir.lower()
if dir == 'x':
dir_num = 0
elif dir == 'y':
dir_num = 1
elif dir == 'z':
dir_num = 2
if not self.bending_moment()[dir_num]:
return (0,0)
# To restrict the range within length of the Beam
shear_curve = Piecewise((float("nan"), self.variable<=0),
(self.shear_force()[dir_num], self.variable<self.length),
(float("nan"), True))
points = solve(shear_curve.rewrite(Piecewise), self.variable,
domain=S.Reals)
points.append(0)
points.append(self.length)
bending_moment_curve = self.bending_moment()[dir_num]
bending_moments = [bending_moment_curve.subs(self.variable, x) for x in points]
bending_moments = list(map(abs, bending_moments))
max_bending_moment = max(bending_moments)
return (points[bending_moments.index(max_bending_moment)], max_bending_moment)
def max_bending_moment(self):
"""
Returns point of max bending moment and its corresponding bending moment value
along all directions in a Beam object as a list.
solve_for_reaction_loads() must be called before using this function.
Examples
========
There is a beam of length 20 meters. It it supported by rollers
at of its end. A linear load having slope equal to 12 is applied
along y-axis. A constant distributed load of magnitude 15 N is
applied from start till its end along z-axis.
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> from sympy.physics.continuum_mechanics.beam import Beam3D
>>> from sympy import symbols
>>> l, E, G, I, A, x = symbols('l, E, G, I, A, x')
>>> b = Beam3D(20, 40, 21, 100, 25, x)
>>> b.apply_load(15, start=0, order=0, dir="z")
>>> b.apply_load(12*x, start=0, order=0, dir="y")
>>> b.bc_deflection = [(0, [0, 0, 0]), (20, [0, 0, 0])]
>>> R1, R2, R3, R4 = symbols('R1, R2, R3, R4')
>>> b.apply_load(R1, start=0, order=-1, dir="z")
>>> b.apply_load(R2, start=20, order=-1, dir="z")
>>> b.apply_load(R3, start=0, order=-1, dir="y")
>>> b.apply_load(R4, start=20, order=-1, dir="y")
>>> b.solve_for_reaction_loads(R1, R2, R3, R4)
>>> b.max_bending_moment()
[(0, 0), (20, 3000), (20, 16000)]
"""
max_bmoment = []
max_bmoment.append(self._max_bending_moment('x'))
max_bmoment.append(self._max_bending_moment('y'))
max_bmoment.append(self._max_bending_moment('z'))
return max_bmoment
max_bmoment = max_bending_moment
def _max_deflection(self, dir):
"""
Helper function for max_Deflection()
"""
dir = dir.lower()
if dir == 'x':
dir_num = 0
elif dir == 'y':
dir_num = 1
elif dir == 'z':
dir_num = 2
if not self.deflection()[dir_num]:
return (0,0)
# To restrict the range within length of the Beam
slope_curve = Piecewise((float("nan"), self.variable<=0),
(self.slope()[dir_num], self.variable<self.length),
(float("nan"), True))
points = solve(slope_curve.rewrite(Piecewise), self.variable,
domain=S.Reals)
points.append(0)
points.append(self._length)
deflection_curve = self.deflection()[dir_num]
deflections = [deflection_curve.subs(self.variable, x) for x in points]
deflections = list(map(abs, deflections))
max_def = max(deflections)
return (points[deflections.index(max_def)], max_def)
def max_deflection(self):
"""
Returns point of max deflection and its corresponding deflection value
along all directions in a Beam object as a list.
solve_for_reaction_loads() and solve_slope_deflection() must be called
before using this function.
Examples
========
There is a beam of length 20 meters. It it supported by rollers
at of its end. A linear load having slope equal to 12 is applied
along y-axis. A constant distributed load of magnitude 15 N is
applied from start till its end along z-axis.
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> from sympy.physics.continuum_mechanics.beam import Beam3D
>>> from sympy import symbols
>>> l, E, G, I, A, x = symbols('l, E, G, I, A, x')
>>> b = Beam3D(20, 40, 21, 100, 25, x)
>>> b.apply_load(15, start=0, order=0, dir="z")
>>> b.apply_load(12*x, start=0, order=0, dir="y")
>>> b.bc_deflection = [(0, [0, 0, 0]), (20, [0, 0, 0])]
>>> R1, R2, R3, R4 = symbols('R1, R2, R3, R4')
>>> b.apply_load(R1, start=0, order=-1, dir="z")
>>> b.apply_load(R2, start=20, order=-1, dir="z")
>>> b.apply_load(R3, start=0, order=-1, dir="y")
>>> b.apply_load(R4, start=20, order=-1, dir="y")
>>> b.solve_for_reaction_loads(R1, R2, R3, R4)
>>> b.solve_slope_deflection()
>>> b.max_deflection()
[(0, 0), (10, 495/14), (-10 + 10*sqrt(10793)/43, (10 - 10*sqrt(10793)/43)**3/160 - 20/7 + (10 - 10*sqrt(10793)/43)**4/6400 + 20*sqrt(10793)/301 + 27*(10 - 10*sqrt(10793)/43)**2/560)]
"""
max_def = []
max_def.append(self._max_deflection('x'))
max_def.append(self._max_deflection('y'))
max_def.append(self._max_deflection('z'))
return max_def
|
a5028680f73be67ddcb6f361ca0c2a4cb79f7e10c6403692d9d660da7c9a3159 | """
This module can be used to solve problems related
to 2D Trusses.
"""
from sympy.core.symbol import Symbol
from sympy.core.sympify import sympify
class Truss:
"""
A Truss is an assembly of members such as beams,
connected by nodes, that create a rigid structure.
In engineering, a truss is a structure that
consists of two-force members only.
Trusses are extremely important in engineering applications
and can be seen in numerous real-world applications like bridges.
Examples
========
There is a Truss consisting of four nodes and five
members connecting the nodes. A force P acts
downward on the node D and there also exist pinned
and roller joints on the nodes A and B respectively.
.. image:: truss_example.png
>>> from sympy.physics.continuum_mechanics.truss import Truss
>>> t = Truss()
>>> t.add_node("node_1", 0, 0)
>>> t.add_node("node_2", 6, 0)
>>> t.add_node("node_3", 2, 2)
>>> t.add_node("node_4", 2, 0)
>>> t.add_member("member_1", "node_1", "node_4")
>>> t.add_member("member_2", "node_2", "node_4")
>>> t.add_member("member_3", "node_1", "node_3")
>>> t.add_member("member_4", "node_2", "node_3")
>>> t.add_member("member_5", "node_3", "node_4")
>>> t.apply_load("node_4", magnitude=10, direction=270)
>>> t.apply_support("node_1", type="fixed")
>>> t.apply_support("node_2", type="roller")
"""
def __init__(self):
"""
Initializes the class
"""
self._nodes = []
self._members = {}
self._loads = {}
self._supports = {}
self._node_labels = []
self._node_positions = []
self._node_position_x = []
self._node_position_y = []
self._nodes_occupied = {}
self._reaction_loads = {}
self._internal_forces = {}
@property
def nodes(self):
"""
Returns the nodes of the truss along with their positions.
"""
return self._nodes
@property
def node_labels(self):
"""
Returns the node labels of the truss.
"""
return self._node_labels
@property
def node_positions(self):
"""
Returns the positions of the nodes of the truss.
"""
return self._node_positions
@property
def members(self):
"""
Returns the members of the truss along with the start and end points.
"""
return self._members
@property
def member_labels(self):
"""
Returns the members of the truss along with the start and end points.
"""
return self._member_labels
@property
def supports(self):
"""
Returns the nodes with provided supports along with the kind of support provided i.e.
pinned or roller.
"""
return self._supports
@property
def loads(self):
"""
Returns the loads acting on the truss.
"""
return self._loads
@property
def reaction_loads(self):
"""
Returns the reaction forces for all supports which are all initialized to 0.
"""
return self._reaction_loads
@property
def internal_forces(self):
"""
Returns the internal forces for all members which are all initialized to 0.
"""
return self._internal_forces
def add_node(self, label, x, y):
"""
This method adds a node to the truss along with its name/label and its location.
Parameters
==========
label: String or a Symbol
The label for a node. It is the only way to identify a particular node.
x: Sympifyable
The x-coordinate of the position of the node.
y: Sympifyable
The y-coordinate of the position of the node.
Examples
========
>>> from sympy.physics.continuum_mechanics.truss import Truss
>>> t = Truss()
>>> t.add_node('A', 0, 0)
>>> t.nodes
[('A', 0, 0)]
>>> t.add_node('B', 3, 0)
>>> t.nodes
[('A', 0, 0), ('B', 3, 0)]
"""
x = sympify(x)
y = sympify(y)
if label in self._node_labels:
raise ValueError("Node needs to have a unique label")
elif x in self._node_position_x and y in self._node_position_y and self._node_position_x.index(x)==self._node_position_y.index(y):
raise ValueError("A node already exists at the given position")
else :
self._nodes.append((label, x, y))
self._node_labels.append(label)
self._node_positions.append((x, y))
self._node_position_x.append(x)
self._node_position_y.append(y)
def remove_node(self, label):
"""
This method removes a node from the truss.
Parameters
==========
label: String or Symbol
The label of the node to be removed.
Examples
========
>>> from sympy.physics.continuum_mechanics.truss import Truss
>>> t = Truss()
>>> t.add_node('A', 0, 0)
>>> t.nodes
[('A', 0, 0)]
>>> t.add_node('B', 3, 0)
>>> t.nodes
[('A', 0, 0), ('B', 3, 0)]
>>> t.remove_node('A')
>>> t.nodes
[('B', 3, 0)]
"""
for i in range(len(self.nodes)):
if self._node_labels[i] == label:
x = self._node_position_x[i]
y = self._node_position_y[i]
if label not in self._node_labels:
raise ValueError("No such node exists in the truss")
else:
members_duplicate = self._members.copy()
for member in members_duplicate:
if label == self._members[member][0] or label == self._members[member][1]:
raise ValueError("The node given has members already attached to it")
self._nodes.remove((label, x, y))
self._node_labels.remove(label)
self._node_positions.remove((x, y))
self._node_position_x.remove(x)
self._node_position_y.remove(y)
if label in list(self._loads):
self._loads.pop(label)
if label in list(self._supports):
self._supports.pop(label)
def add_member(self, label, start, end):
"""
This method adds a member between any two nodes in the given truss.
Parameters
==========
label: String or Symbol
The label for a member. It is the only way to identify a particular member.
start: String or Symbol
The label of the starting point/node of the member.
end: String or Symbol
The label of the ending point/node of the member.
Examples
========
>>> from sympy.physics.continuum_mechanics.truss import Truss
>>> t = Truss()
>>> t.add_node('A', 0, 0)
>>> t.add_node('B', 3, 0)
>>> t.add_node('C', 2, 2)
>>> t.add_member('AB', 'A', 'B')
>>> t.members
{'AB': ['A', 'B']}
"""
if start not in self._node_labels or end not in self._node_labels or start==end:
raise ValueError("The start and end points of the member must be unique nodes")
elif label in list(self._members):
raise ValueError("A member with the same label already exists for the truss")
elif self._nodes_occupied.get(tuple([start, end])):
raise ValueError("A member already exists between the two nodes")
else:
self._members[label] = [start, end]
self._nodes_occupied[start, end] = True
self._nodes_occupied[end, start] = True
self._internal_forces[label] = 0
def remove_member(self, label):
"""
This method removes a member from the given truss.
Parameters
==========
label: String or Symbol
The label for the member to be removed.
Examples
========
>>> from sympy.physics.continuum_mechanics.truss import Truss
>>> t = Truss()
>>> t.add_node('A', 0, 0)
>>> t.add_node('B', 3, 0)
>>> t.add_node('C', 2, 2)
>>> t.add_member('AB', 'A', 'B')
>>> t.add_member('AC', 'A', 'C')
>>> t.add_member('BC', 'B', 'C')
>>> t.members
{'AB': ['A', 'B'], 'AC': ['A', 'C'], 'BC': ['B', 'C']}
>>> t.remove_member('AC')
>>> t.members
{'AB': ['A', 'B'], 'BC': ['B', 'C']}
"""
if label not in list(self._members):
raise ValueError("No such member exists in the Truss")
else:
self._nodes_occupied.pop(tuple([self._members[label][0], self._members[label][1]]))
self._nodes_occupied.pop(tuple([self._members[label][1], self._members[label][0]]))
self._members.pop(label)
self._internal_forces.pop(label)
def change_node_label(self, label, new_label):
"""
This method changes the label of a node.
Parameters
==========
label: String or Symbol
The label of the node for which the label has
to be changed.
new_label: String or Symbol
The new label of the node.
Examples
========
>>> from sympy.physics.continuum_mechanics.truss import Truss
>>> t = Truss()
>>> t.add_node('A', 0, 0)
>>> t.add_node('B', 3, 0)
>>> t.nodes
[('A', 0, 0), ('B', 3, 0)]
>>> t.change_node_label('A', 'C')
>>> t.nodes
[('C', 0, 0), ('B', 3, 0)]
"""
if label not in self._node_labels:
raise ValueError("No such node exists for the Truss")
elif new_label in self._node_labels:
raise ValueError("A node with the given label already exists")
else:
for node in self._nodes:
if node[0] == label:
self._nodes[self._nodes.index((label, node[1], node[2]))] = (new_label, node[1], node[2])
self._node_labels[self._node_labels.index(node[0])] = new_label
if node[0] in list(self._supports):
self._supports[new_label] = self._supports[node[0]]
self._supports.pop(node[0])
if new_label in list(self._supports):
if self._supports[new_label] == 'pinned':
if 'R_'+str(label)+'_x' in list(self._reaction_loads) and 'R_'+str(label)+'_y' in list(self._reaction_loads):
self._reaction_loads['R_'+str(new_label)+'_x'] = self._reaction_loads['R_'+str(label)+'_x']
self._reaction_loads['R_'+str(new_label)+'_y'] = self._reaction_loads['R_'+str(label)+'_y']
self._reaction_loads.pop('R_'+str(label)+'_x')
self._reaction_loads.pop('R_'+str(label)+'_y')
self._loads[new_label] = self._loads[label]
for load in self._loads[new_label]:
if load[1] == 90:
load[0] -= Symbol('R_'+str(label)+'_y')
if load[0] == 0:
self._loads[label].remove(load)
break
for load in self._loads[new_label]:
if load[1] == 0:
load[0] -= Symbol('R_'+str(label)+'_x')
if load[0] == 0:
self._loads[label].remove(load)
break
self.apply_load(new_label, Symbol('R_'+str(new_label)+'_x'), 0)
self.apply_load(new_label, Symbol('R_'+str(new_label)+'_y'), 90)
self._loads.pop(label)
elif self._supports[new_label] == 'roller':
self._loads[new_label] = self._loads[label]
for load in self._loads[label]:
if load[1] == 90:
load[0] -= Symbol('R_'+str(label)+'_y')
if load[0] == 0:
self._loads[label].remove(load)
break
self.apply_load(new_label, Symbol('R_'+str(new_label)+'_y'), 90)
self._loads.pop(label)
else:
if label in list(self._loads):
self._loads[new_label] = self._loads[label]
self._loads.pop(label)
for member in list(self._members):
if self._members[member][0] == node[0]:
self._members[member][0] = new_label
self._nodes_occupied[(new_label, self._members[member][1])] = True
self._nodes_occupied[(self._members[member][1], new_label)] = True
self._nodes_occupied.pop(tuple([label, self._members[member][1]]))
self._nodes_occupied.pop(tuple([self._members[member][1], label]))
elif self._members[member][1] == node[0]:
self._members[member][1] = new_label
self._nodes_occupied[(self._members[member][0], new_label)] = True
self._nodes_occupied[(new_label, self._members[member][0])] = True
self._nodes_occupied.pop(tuple([self._members[member][0], label]))
self._nodes_occupied.pop(tuple([label, self._members[member][0]]))
def change_member_label(self, label, new_label):
"""
This method changes the label of a member.
Parameters
==========
label: String or Symbol
The label of the member for which the label has
to be changed.
new_label: String or Symbol
The new label of the member.
Examples
========
>>> from sympy.physics.continuum_mechanics.truss import Truss
>>> t = Truss()
>>> t.add_node('A', 0, 0)
>>> t.add_node('B', 3, 0)
>>> t.nodes
[('A', 0, 0), ('B', 3, 0)]
>>> t.change_node_label('A', 'C')
>>> t.nodes
[('C', 0, 0), ('B', 3, 0)]
>>> t.add_member('BC', 'B', 'C')
>>> t.members
{'BC': ['B', 'C']}
>>> t.change_member_label('BC', 'BC_new')
>>> t.members
{'BC_new': ['B', 'C']}
"""
if label not in list(self._members):
raise ValueError("No such member exists for the Truss")
else:
members_duplicate = list(self._members).copy()
for member in members_duplicate:
if member == label:
self._members[new_label] = [self._members[member][0], self._members[member][1]]
self._members.pop(label)
self._internal_forces[new_label] = self._internal_forces[label]
self._internal_forces.pop(label)
def apply_load(self, location, magnitude, direction):
"""
This method applies an external load at a particular node
Parameters
==========
location: String or Symbol
Label of the Node at which load is applied.
magnitude: Sympifyable
Magnitude of the load applied. It must always be positive and any changes in
the direction of the load are not reflected here.
direction: Sympifyable
The angle, in degrees, that the load vector makes with the horizontal
in the counter-clockwise direction. It takes the values 0 to 360,
inclusive.
Examples
========
>>> from sympy.physics.continuum_mechanics.truss import Truss
>>> from sympy import symbols
>>> t = Truss()
>>> t.add_node('A', 0, 0)
>>> t.add_node('B', 3, 0)
>>> P = symbols('P')
>>> t.apply_load('A', P, 90)
>>> t.apply_load('A', P/2, 45)
>>> t.apply_load('A', P/4, 90)
>>> t.loads
{'A': [[P, 90], [P/2, 45], [P/4, 90]]}
"""
magnitude = sympify(magnitude)
direction = sympify(direction)
if location not in self.node_labels:
raise ValueError("Load must be applied at a known node")
else:
if location in list(self._loads):
self._loads[location].append([magnitude, direction])
else:
self._loads[location] = [[magnitude, direction]]
def remove_load(self, location, magnitude, direction):
"""
This method removes an already
present external load at a particular node
Parameters
==========
location: String or Symbol
Label of the Node at which load is applied and is to be removed.
magnitude: Sympifyable
Magnitude of the load applied.
direction: Sympifyable
The angle, in degrees, that the load vector makes with the horizontal
in the counter-clockwise direction. It takes the values 0 to 360,
inclusive.
Examples
========
>>> from sympy.physics.continuum_mechanics.truss import Truss
>>> from sympy import symbols
>>> t = Truss()
>>> t.add_node('A', 0, 0)
>>> t.add_node('B', 3, 0)
>>> P = symbols('P')
>>> t.apply_load('A', P, 90)
>>> t.apply_load('A', P/2, 45)
>>> t.apply_load('A', P/4, 90)
>>> t.loads
{'A': [[P, 90], [P/2, 45], [P/4, 90]]}
>>> t.remove_load('A', P/4, 90)
>>> t.loads
{'A': [[P, 90], [P/2, 45]]}
"""
magnitude = sympify(magnitude)
direction = sympify(direction)
if location not in self.node_labels:
raise ValueError("Load must be removed from a known node")
else:
if [magnitude, direction] not in self._loads[location]:
raise ValueError("No load of this magnitude and direction has been applied at this node")
else:
self._loads[location].remove([magnitude, direction])
if self._loads[location] == []:
self._loads.pop(location)
def apply_support(self, location, type):
"""
This method adds a pinned or roller support at a particular node
Parameters
==========
location: String or Symbol
Label of the Node at which support is added.
type: String
Type of the support being provided at the node.
Examples
========
>>> from sympy.physics.continuum_mechanics.truss import Truss
>>> t = Truss()
>>> t.add_node('A', 0, 0)
>>> t.add_node('B', 3, 0)
>>> t.apply_support('A', 'pinned')
>>> t.supports
{'A': 'pinned'}
"""
if location not in self._node_labels:
raise ValueError("Support must be added on a known node")
else:
if location not in list(self._supports):
if type == 'pinned':
self.apply_load(location, Symbol('R_'+str(location)+'_x'), 0)
self.apply_load(location, Symbol('R_'+str(location)+'_y'), 90)
elif type == 'roller':
self.apply_load(location, Symbol('R_'+str(location)+'_y'), 90)
elif self._supports[location] == 'pinned':
if type == 'roller':
self.remove_load(location, Symbol('R_'+str(location)+'_x'), 0)
elif self._supports[location] == 'roller':
if type == 'pinned':
self.apply_load(location, Symbol('R_'+str(location)+'_x'), 0)
self._supports[location] = type
def remove_support(self, location):
"""
This method removes support from a particular node
Parameters
==========
location: String or Symbol
Label of the Node at which support is to be removed.
Examples
========
>>> from sympy.physics.continuum_mechanics.truss import Truss
>>> t = Truss()
>>> t.add_node('A', 0, 0)
>>> t.add_node('B', 3, 0)
>>> t.apply_support('A', 'pinned')
>>> t.supports
{'A': 'pinned'}
>>> t.remove_support('A')
>>> t.supports
{}
"""
if location not in self._node_labels:
raise ValueError("No such node exists in the Truss")
elif location not in list(self._supports):
raise ValueError("No support has been added to the given node")
else:
if self._supports[location] == 'pinned':
self.remove_load(location, Symbol('R_'+str(location)+'_x'), 0)
self.remove_load(location, Symbol('R_'+str(location)+'_y'), 90)
elif self._supports[location] == 'roller':
self.remove_load(location, Symbol('R_'+str(location)+'_y'), 90)
self._supports.pop(location)
|
1034df288d3cc1a707b5814a7fb1de062e379acaaa02f30e85359ffbc449bb79 | from math import isclose
from sympy.core.numbers import I
from sympy.core.symbol import Dummy
from sympy.functions.elementary.complexes import (Abs, arg)
from sympy.functions.elementary.exponential import log
from sympy.abc import s, p, a
from sympy.external import import_module
from sympy.physics.control.control_plots import \
(pole_zero_numerical_data, pole_zero_plot, step_response_numerical_data,
step_response_plot, impulse_response_numerical_data,
impulse_response_plot, ramp_response_numerical_data,
ramp_response_plot, bode_magnitude_numerical_data,
bode_phase_numerical_data, bode_plot)
from sympy.physics.control.lti import (TransferFunction,
Series, Parallel, TransferFunctionMatrix)
from sympy.testing.pytest import raises, skip
matplotlib = import_module(
'matplotlib', import_kwargs={'fromlist': ['pyplot']},
catch=(RuntimeError,))
numpy = import_module('numpy')
tf1 = TransferFunction(1, p**2 + 0.5*p + 2, p)
tf2 = TransferFunction(p, 6*p**2 + 3*p + 1, p)
tf3 = TransferFunction(p, p**3 - 1, p)
tf4 = TransferFunction(10, p**3, p)
tf5 = TransferFunction(5, s**2 + 2*s + 10, s)
tf6 = TransferFunction(1, 1, s)
tf7 = TransferFunction(4*s*3 + 9*s**2 + 0.1*s + 11, 8*s**6 + 9*s**4 + 11, s)
tf8 = TransferFunction(5, s**2 + (2+I)*s + 10, s)
ser1 = Series(tf4, TransferFunction(1, p - 5, p))
ser2 = Series(tf3, TransferFunction(p, p + 2, p))
par1 = Parallel(tf1, tf2)
par2 = Parallel(tf1, tf2, tf3)
def _to_tuple(a, b):
return tuple(a), tuple(b)
def _trim_tuple(a, b):
a, b = _to_tuple(a, b)
return tuple(a[0: 2] + a[len(a)//2 : len(a)//2 + 1] + a[-2:]), \
tuple(b[0: 2] + b[len(b)//2 : len(b)//2 + 1] + b[-2:])
def y_coordinate_equality(plot_data_func, evalf_func, system):
"""Checks whether the y-coordinate value of the plotted
data point is equal to the value of the function at a
particular x."""
x, y = plot_data_func(system)
x, y = _trim_tuple(x, y)
y_exp = tuple(evalf_func(system, x_i) for x_i in x)
return all(Abs(y_exp_i - y_i) < 1e-8 for y_exp_i, y_i in zip(y_exp, y))
def test_errors():
if not matplotlib:
skip("Matplotlib not the default backend")
# Invalid `system` check
tfm = TransferFunctionMatrix([[tf6, tf5], [tf5, tf6]])
expr = 1/(s**2 - 1)
raises(NotImplementedError, lambda: pole_zero_plot(tfm))
raises(NotImplementedError, lambda: pole_zero_numerical_data(expr))
raises(NotImplementedError, lambda: impulse_response_plot(expr))
raises(NotImplementedError, lambda: impulse_response_numerical_data(tfm))
raises(NotImplementedError, lambda: step_response_plot(tfm))
raises(NotImplementedError, lambda: step_response_numerical_data(expr))
raises(NotImplementedError, lambda: ramp_response_plot(expr))
raises(NotImplementedError, lambda: ramp_response_numerical_data(tfm))
raises(NotImplementedError, lambda: bode_plot(tfm))
# More than 1 variables
tf_a = TransferFunction(a, s + 1, s)
raises(ValueError, lambda: pole_zero_plot(tf_a))
raises(ValueError, lambda: pole_zero_numerical_data(tf_a))
raises(ValueError, lambda: impulse_response_plot(tf_a))
raises(ValueError, lambda: impulse_response_numerical_data(tf_a))
raises(ValueError, lambda: step_response_plot(tf_a))
raises(ValueError, lambda: step_response_numerical_data(tf_a))
raises(ValueError, lambda: ramp_response_plot(tf_a))
raises(ValueError, lambda: ramp_response_numerical_data(tf_a))
raises(ValueError, lambda: bode_plot(tf_a))
# lower_limit > 0 for response plots
raises(ValueError, lambda: impulse_response_plot(tf1, lower_limit=-1))
raises(ValueError, lambda: step_response_plot(tf1, lower_limit=-0.1))
raises(ValueError, lambda: ramp_response_plot(tf1, lower_limit=-4/3))
# slope in ramp_response_plot() is negative
raises(ValueError, lambda: ramp_response_plot(tf1, slope=-0.1))
# incorrect frequency or phase unit
raises(ValueError, lambda: bode_plot(tf1,freq_unit = 'hz'))
raises(ValueError, lambda: bode_plot(tf1,phase_unit = 'degree'))
def test_pole_zero():
if not numpy:
skip("NumPy is required for this test")
def pz_tester(sys, expected_value):
z, p = pole_zero_numerical_data(sys)
z_check = numpy.allclose(z, expected_value[0])
p_check = numpy.allclose(p, expected_value[1])
return p_check and z_check
exp1 = [[], [-0.24999999999999994+1.3919410907075054j, -0.24999999999999994-1.3919410907075054j]]
exp2 = [[0.0], [-0.25+0.3227486121839514j, -0.25-0.3227486121839514j]]
exp3 = [[0.0], [-0.5000000000000004+0.8660254037844395j,
-0.5000000000000004-0.8660254037844395j, 0.9999999999999998+0j]]
exp4 = [[], [5.0, 0.0, 0.0, 0.0]]
exp5 = [[-5.645751311064592, -0.5000000000000008, -0.3542486889354093],
[-0.24999999999999986+1.3919410907075052j,
-0.24999999999999986-1.3919410907075052j, -0.2499999999999998+0.32274861218395134j,
-0.2499999999999998-0.32274861218395134j]]
exp6 = [[], [-1.1641600331447917-3.545808351896439j,
-0.8358399668552097+2.5458083518964383j]]
assert pz_tester(tf1, exp1)
assert pz_tester(tf2, exp2)
assert pz_tester(tf3, exp3)
assert pz_tester(ser1, exp4)
assert pz_tester(par1, exp5)
assert pz_tester(tf8, exp6)
def test_bode():
if not numpy:
skip("NumPy is required for this test")
def bode_phase_evalf(system, point):
expr = system.to_expr()
_w = Dummy("w", real=True)
w_expr = expr.subs({system.var: I*_w})
return arg(w_expr).subs({_w: point}).evalf()
def bode_mag_evalf(system, point):
expr = system.to_expr()
_w = Dummy("w", real=True)
w_expr = expr.subs({system.var: I*_w})
return 20*log(Abs(w_expr), 10).subs({_w: point}).evalf()
def test_bode_data(sys):
return y_coordinate_equality(bode_magnitude_numerical_data, bode_mag_evalf, sys) \
and y_coordinate_equality(bode_phase_numerical_data, bode_phase_evalf, sys)
assert test_bode_data(tf1)
assert test_bode_data(tf2)
assert test_bode_data(tf3)
assert test_bode_data(tf4)
assert test_bode_data(tf5)
def check_point_accuracy(a, b):
return all(isclose(a_i, b_i, rel_tol=10e-12) for \
a_i, b_i in zip(a, b))
def test_impulse_response():
if not numpy:
skip("NumPy is required for this test")
def impulse_res_tester(sys, expected_value):
x, y = _to_tuple(*impulse_response_numerical_data(sys,
adaptive=False, nb_of_points=10))
x_check = check_point_accuracy(x, expected_value[0])
y_check = check_point_accuracy(y, expected_value[1])
return x_check and y_check
exp1 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445,
5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0),
(0.0, 0.544019738507865, 0.01993849743234938, -0.31140243360893216, -0.022852779906491996, 0.1778306498155759,
0.01962941084328499, -0.1013115194573652, -0.014975541213105696, 0.0575789724730714))
exp2 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445, 5.555555555555555,
6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0), (0.1666666675, 0.08389223412935855,
0.02338051973475047, -0.014966807776379383, -0.034645954223054234, -0.040560075735512804,
-0.037658628907103885, -0.030149507719590022, -0.021162090730736834, -0.012721292737437523))
exp3 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445, 5.555555555555555,
6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0), (4.369893391586999e-09, 1.1750333000630964,
3.2922404058312473, 9.432290008148343, 28.37098083007151, 86.18577464367974, 261.90356653762115,
795.6538758627842, 2416.9920942096983, 7342.159505206647))
exp4 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445, 5.555555555555555,
6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0), (0.0, 6.17283950617284, 24.69135802469136,
55.555555555555564, 98.76543209876544, 154.320987654321, 222.22222222222226, 302.46913580246917,
395.0617283950618, 500.0))
exp5 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445, 5.555555555555555,
6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0), (0.0, -0.10455606138085417,
0.06757671513476461, -0.03234567568833768, 0.013582514927757873, -0.005273419510705473,
0.0019364083003354075, -0.000680070134067832, 0.00022969845960406913, -7.476094359583917e-05))
exp6 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445,
5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0),
(-6.016699583000218e-09, 0.35039802056107394, 3.3728423827689884, 12.119846079276684,
25.86101014293389, 29.352480635282088, -30.49475907497664, -273.8717189554019, -863.2381702029659,
-1747.0262164682233))
exp7 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335,
4.444444444444445, 5.555555555555555, 6.666666666666667, 7.777777777777779,
8.88888888888889, 10.0), (0.0, 18.934638095560974, 5346.93244680907, 1384609.8718249386,
358161126.65801865, 92645770015.70108, 23964739753087.42, 6198974342083139.0, 1.603492601616059e+18,
4.147764422869658e+20))
assert impulse_res_tester(tf1, exp1)
assert impulse_res_tester(tf2, exp2)
assert impulse_res_tester(tf3, exp3)
assert impulse_res_tester(tf4, exp4)
assert impulse_res_tester(tf5, exp5)
assert impulse_res_tester(tf7, exp6)
assert impulse_res_tester(ser1, exp7)
def test_step_response():
if not numpy:
skip("NumPy is required for this test")
def step_res_tester(sys, expected_value):
x, y = _to_tuple(*step_response_numerical_data(sys,
adaptive=False, nb_of_points=10))
x_check = check_point_accuracy(x, expected_value[0])
y_check = check_point_accuracy(y, expected_value[1])
return x_check and y_check
exp1 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445,
5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0),
(-1.9193285738516863e-08, 0.42283495488246126, 0.7840485977945262, 0.5546841805655717,
0.33903033806932087, 0.4627251747410237, 0.5909907598988051, 0.5247213989553071,
0.4486997874319281, 0.4839358435839171))
exp2 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445,
5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0),
(0.0, 0.13728409095645816, 0.19474559355325086, 0.1974909129243011, 0.16841657696573073,
0.12559777736159378, 0.08153828016664713, 0.04360471317348958, 0.015072994568868221,
-0.003636420058445484))
exp3 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445,
5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0),
(0.0, 0.6314542141914303, 2.9356520038101035, 9.37731009663807, 28.452300356688376,
86.25721933273988, 261.9236645044672, 795.6435410577224, 2416.9786984578764, 7342.154119725917))
exp4 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445,
5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0),
(0.0, 2.286236899862826, 18.28989519890261, 61.72839629629631, 146.31916159122088, 285.7796124828532,
493.8271703703705, 784.1792566529494, 1170.553292729767, 1666.6667))
exp5 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445,
5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0),
(-3.999999997894577e-09, 0.6720357068882895, 0.4429938256137113, 0.5182010838004518,
0.4944139147159695, 0.5016379853883338, 0.4995466896527733, 0.5001154784851325,
0.49997448824584123, 0.5000039745919259))
exp6 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445,
5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0),
(-1.5433688493882158e-09, 0.3428705539937336, 1.1253619102202777, 3.1849962651016517,
9.47532757182671, 28.727231099148135, 87.29426924860557, 265.2138681048606, 805.6636260007757,
2447.387582370878))
assert step_res_tester(tf1, exp1)
assert step_res_tester(tf2, exp2)
assert step_res_tester(tf3, exp3)
assert step_res_tester(tf4, exp4)
assert step_res_tester(tf5, exp5)
assert step_res_tester(ser2, exp6)
def test_ramp_response():
if not numpy:
skip("NumPy is required for this test")
def ramp_res_tester(sys, num_points, expected_value, slope=1):
x, y = _to_tuple(*ramp_response_numerical_data(sys,
slope=slope, adaptive=False, nb_of_points=num_points))
x_check = check_point_accuracy(x, expected_value[0])
y_check = check_point_accuracy(y, expected_value[1])
return x_check and y_check
exp1 = ((0.0, 2.0, 4.0, 6.0, 8.0, 10.0), (0.0, 0.7324667795033895, 1.9909720978650398,
2.7956587704217783, 3.9224897567931514, 4.85022655284895))
exp2 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445,
5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0),
(2.4360213402019326e-08, 0.10175320182493253, 0.33057612497658406, 0.5967937263298935,
0.8431511866718248, 1.0398805391471613, 1.1776043125035738, 1.2600994825747305, 1.2981042689274653,
1.304684417610106))
exp3 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445, 5.555555555555555,
6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0), (-3.9329040468771836e-08,
0.34686634635794555, 2.9998828170537903, 12.33303690737476, 40.993913948137795, 127.84145222317912,
391.41713691996, 1192.0006858708389, 3623.9808672503405, 11011.728034546572))
exp4 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445, 5.555555555555555,
6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0), (0.0, 1.9051973784484078, 30.483158055174524,
154.32098765432104, 487.7305288827924, 1190.7483615302544, 2469.1358024691367, 4574.3789056546275,
7803.688462124678, 12500.0))
exp5 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445, 5.555555555555555,
6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0), (0.0, 3.8844361856975635, 9.141792069209865,
14.096349157657231, 19.09783068994694, 24.10179770390321, 29.09907319114121, 34.10040420185154,
39.09983919254265, 44.10006013058409))
exp6 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445, 5.555555555555555,
6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0), (0.0, 1.1111111111111112, 2.2222222222222223,
3.3333333333333335, 4.444444444444445, 5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0))
assert ramp_res_tester(tf1, 6, exp1)
assert ramp_res_tester(tf2, 10, exp2, 1.2)
assert ramp_res_tester(tf3, 10, exp3, 1.5)
assert ramp_res_tester(tf4, 10, exp4, 3)
assert ramp_res_tester(tf5, 10, exp5, 9)
assert ramp_res_tester(tf6, 10, exp6)
|
0598ddad9f85d50872843a9f2b865cd551050498b53de88f8cca5f05c1de91fa | from math import prod
from sympy.core.numbers import Rational
from sympy.functions.elementary.exponential import exp
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.physics.quantum import Dagger, Commutator, qapply
from sympy.physics.quantum.boson import BosonOp
from sympy.physics.quantum.boson import (
BosonFockKet, BosonFockBra, BosonCoherentKet, BosonCoherentBra)
def test_bosonoperator():
a = BosonOp('a')
b = BosonOp('b')
assert isinstance(a, BosonOp)
assert isinstance(Dagger(a), BosonOp)
assert a.is_annihilation
assert not Dagger(a).is_annihilation
assert BosonOp("a") == BosonOp("a", True)
assert BosonOp("a") != BosonOp("c")
assert BosonOp("a", True) != BosonOp("a", False)
assert Commutator(a, Dagger(a)).doit() == 1
assert Commutator(a, Dagger(b)).doit() == a * Dagger(b) - Dagger(b) * a
assert Dagger(exp(a)) == exp(Dagger(a))
def test_boson_states():
a = BosonOp("a")
# Fock states
n = 3
assert (BosonFockBra(0) * BosonFockKet(1)).doit() == 0
assert (BosonFockBra(1) * BosonFockKet(1)).doit() == 1
assert qapply(BosonFockBra(n) * Dagger(a)**n * BosonFockKet(0)) \
== sqrt(prod(range(1, n+1)))
# Coherent states
alpha1, alpha2 = 1.2, 4.3
assert (BosonCoherentBra(alpha1) * BosonCoherentKet(alpha1)).doit() == 1
assert (BosonCoherentBra(alpha2) * BosonCoherentKet(alpha2)).doit() == 1
assert abs((BosonCoherentBra(alpha1) * BosonCoherentKet(alpha2)).doit() -
exp((alpha1 - alpha2) ** 2 * Rational(-1, 2))) < 1e-12
assert qapply(a * BosonCoherentKet(alpha1)) == \
alpha1 * BosonCoherentKet(alpha1)
|
66f3238a179605c79298833d2c738be5f885525e87b14a3ca6ea9dcf2c2b8647 | from sympy.physics.quantum.qasm import Qasm, flip_index, trim,\
get_index, nonblank, fullsplit, fixcommand, stripquotes, read_qasm
from sympy.physics.quantum.gate import X, Z, H, S, T
from sympy.physics.quantum.gate import CNOT, SWAP, CPHASE, CGate, CGateS
from sympy.physics.quantum.circuitplot import Mz
def test_qasm_readqasm():
qasm_lines = """\
qubit q_0
qubit q_1
h q_0
cnot q_0,q_1
"""
q = read_qasm(qasm_lines)
assert q.get_circuit() == CNOT(1,0)*H(1)
def test_qasm_ex1():
q = Qasm('qubit q0', 'qubit q1', 'h q0', 'cnot q0,q1')
assert q.get_circuit() == CNOT(1,0)*H(1)
def test_qasm_ex1_methodcalls():
q = Qasm()
q.qubit('q_0')
q.qubit('q_1')
q.h('q_0')
q.cnot('q_0', 'q_1')
assert q.get_circuit() == CNOT(1,0)*H(1)
def test_qasm_swap():
q = Qasm('qubit q0', 'qubit q1', 'cnot q0,q1', 'cnot q1,q0', 'cnot q0,q1')
assert q.get_circuit() == CNOT(1,0)*CNOT(0,1)*CNOT(1,0)
def test_qasm_ex2():
q = Qasm('qubit q_0', 'qubit q_1', 'qubit q_2', 'h q_1',
'cnot q_1,q_2', 'cnot q_0,q_1', 'h q_0',
'measure q_1', 'measure q_0',
'c-x q_1,q_2', 'c-z q_0,q_2')
assert q.get_circuit() == CGate(2,Z(0))*CGate(1,X(0))*Mz(2)*Mz(1)*H(2)*CNOT(2,1)*CNOT(1,0)*H(1)
def test_qasm_1q():
for symbol, gate in [('x', X), ('z', Z), ('h', H), ('s', S), ('t', T), ('measure', Mz)]:
q = Qasm('qubit q_0', '%s q_0' % symbol)
assert q.get_circuit() == gate(0)
def test_qasm_2q():
for symbol, gate in [('cnot', CNOT), ('swap', SWAP), ('cphase', CPHASE)]:
q = Qasm('qubit q_0', 'qubit q_1', '%s q_0,q_1' % symbol)
assert q.get_circuit() == gate(1,0)
def test_qasm_3q():
q = Qasm('qubit q0', 'qubit q1', 'qubit q2', 'toffoli q2,q1,q0')
assert q.get_circuit() == CGateS((0,1),X(2))
def test_qasm_flip_index():
assert flip_index(0, 2) == 1
assert flip_index(1, 2) == 0
def test_qasm_trim():
assert trim('nothing happens here') == 'nothing happens here'
assert trim("Something #happens here") == "Something "
def test_qasm_get_index():
assert get_index('q0', ['q0', 'q1']) == 1
assert get_index('q1', ['q0', 'q1']) == 0
def test_qasm_nonblank():
assert list(nonblank('abcd')) == list('abcd')
assert list(nonblank('abc ')) == list('abc')
def test_qasm_fullsplit():
assert fullsplit('g q0,q1,q2, q3') == ('g', ['q0', 'q1', 'q2', 'q3'])
def test_qasm_fixcommand():
assert fixcommand('foo') == 'foo'
assert fixcommand('def') == 'qdef'
def test_qasm_stripquotes():
assert stripquotes("'S'") == 'S'
assert stripquotes('"S"') == 'S'
assert stripquotes('S') == 'S'
def test_qasm_qdef():
# weaker test condition (str) since we don't have access to the actual class
q = Qasm("def Q,0,Q",'qubit q0','Q q0')
assert str(q.get_circuit()) == 'Q(0)'
q = Qasm("def CQ,1,Q", 'qubit q0', 'qubit q1', 'CQ q0,q1')
assert str(q.get_circuit()) == 'C((1),Q(0))'
|
6d04df4e5837bb9090e9232cff017030abaeed069eebb6a6a1c486b26aefd176 | from sympy.core.function import expand
from sympy.core.symbol import symbols
from sympy.functions.elementary.trigonometric import (cos, sin)
from sympy.matrices.dense import Matrix
from sympy.simplify.trigsimp import trigsimp
from sympy.physics.mechanics import (PinJoint, JointsMethod, Body, KanesMethod,
PrismaticJoint, LagrangesMethod, inertia)
from sympy.physics.vector import dynamicsymbols, ReferenceFrame
from sympy.testing.pytest import raises
from sympy.core.backend import zeros
from sympy.utilities.lambdify import lambdify
from sympy.solvers.solvers import solve
t = dynamicsymbols._t # type: ignore
def test_jointsmethod():
P = Body('P')
C = Body('C')
Pin = PinJoint('P1', P, C)
C_ixx, g = symbols('C_ixx g')
theta, omega = dynamicsymbols('theta_P1, omega_P1')
P.apply_force(g*P.y)
method = JointsMethod(P, Pin)
assert method.frame == P.frame
assert method.bodies == [C, P]
assert method.loads == [(P.masscenter, g*P.frame.y)]
assert method.q == [theta]
assert method.u == [omega]
assert method.kdes == [omega - theta.diff()]
soln = method.form_eoms()
assert soln == Matrix([[-C_ixx*omega.diff()]])
assert method.forcing_full == Matrix([[omega], [0]])
assert method.mass_matrix_full == Matrix([[1, 0], [0, C_ixx]])
assert isinstance(method.method, KanesMethod)
def test_jointmethod_duplicate_coordinates_speeds():
P = Body('P')
C = Body('C')
T = Body('T')
q, u = dynamicsymbols('q u')
P1 = PinJoint('P1', P, C, q)
P2 = PrismaticJoint('P2', C, T, q)
raises(ValueError, lambda: JointsMethod(P, P1, P2))
P1 = PinJoint('P1', P, C, speeds=u)
P2 = PrismaticJoint('P2', C, T, speeds=u)
raises(ValueError, lambda: JointsMethod(P, P1, P2))
P1 = PinJoint('P1', P, C, q, u)
P2 = PrismaticJoint('P2', C, T, q, u)
raises(ValueError, lambda: JointsMethod(P, P1, P2))
def test_complete_simple_double_pendulum():
q1, q2 = dynamicsymbols('q1 q2')
u1, u2 = dynamicsymbols('u1 u2')
m, l, g = symbols('m l g')
C = Body('C') # ceiling
PartP = Body('P', mass=m)
PartR = Body('R', mass=m)
J1 = PinJoint('J1', C, PartP, speeds=u1, coordinates=q1,
child_joint_pos=-l*PartP.x, parent_axis=C.z,
child_axis=PartP.z)
J2 = PinJoint('J2', PartP, PartR, speeds=u2, coordinates=q2,
child_joint_pos=-l*PartR.x, parent_axis=PartP.z,
child_axis=PartR.z)
PartP.apply_force(m*g*C.x)
PartR.apply_force(m*g*C.x)
method = JointsMethod(C, J1, J2)
method.form_eoms()
assert expand(method.mass_matrix_full) == Matrix([[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 2*l**2*m*cos(q2) + 3*l**2*m, l**2*m*cos(q2) + l**2*m],
[0, 0, l**2*m*cos(q2) + l**2*m, l**2*m]])
assert trigsimp(method.forcing_full) == trigsimp(Matrix([[u1], [u2], [-g*l*m*(sin(q1 + q2) + sin(q1)) -
g*l*m*sin(q1) + l**2*m*(2*u1 + u2)*u2*sin(q2)],
[-g*l*m*sin(q1 + q2) - l**2*m*u1**2*sin(q2)]]))
def test_two_dof_joints():
q1, q2, u1, u2 = dynamicsymbols('q1 q2 u1 u2')
m, c1, c2, k1, k2 = symbols('m c1 c2 k1 k2')
W = Body('W')
B1 = Body('B1', mass=m)
B2 = Body('B2', mass=m)
J1 = PrismaticJoint('J1', W, B1, coordinates=q1, speeds=u1)
J2 = PrismaticJoint('J2', B1, B2, coordinates=q2, speeds=u2)
W.apply_force(k1*q1*W.x, reaction_body=B1)
W.apply_force(c1*u1*W.x, reaction_body=B1)
B1.apply_force(k2*q2*W.x, reaction_body=B2)
B1.apply_force(c2*u2*W.x, reaction_body=B2)
method = JointsMethod(W, J1, J2)
method.form_eoms()
MM = method.mass_matrix
forcing = method.forcing
rhs = MM.LUsolve(forcing)
assert expand(rhs[0]) == expand((-k1 * q1 - c1 * u1 + k2 * q2 + c2 * u2)/m)
assert expand(rhs[1]) == expand((k1 * q1 + c1 * u1 - 2 * k2 * q2 - 2 *
c2 * u2) / m)
def test_simple_pedulum():
l, m, g = symbols('l m g')
C = Body('C')
b = Body('b', mass=m)
q = dynamicsymbols('q')
P = PinJoint('P', C, b, speeds=q.diff(t), coordinates=q, child_joint_pos = -l*b.x,
parent_axis=C.z, child_axis=b.z)
b.potential_energy = - m * g * l * cos(q)
method = JointsMethod(C, P)
method.form_eoms(LagrangesMethod)
rhs = method.rhs()
assert rhs[1] == -g*sin(q)/l
def test_chaos_pendulum():
#https://www.pydy.org/examples/chaos_pendulum.html
mA, mB, lA, lB, IAxx, IBxx, IByy, IBzz, g = symbols('mA, mB, lA, lB, IAxx, IBxx, IByy, IBzz, g')
theta, phi, omega, alpha = dynamicsymbols('theta phi omega alpha')
A = ReferenceFrame('A')
B = ReferenceFrame('B')
rod = Body('rod', mass=mA, frame=A, central_inertia=inertia(A, IAxx, IAxx, 0))
plate = Body('plate', mass=mB, frame=B, central_inertia=inertia(B, IBxx, IByy, IBzz))
C = Body('C')
J1 = PinJoint('J1', C, rod, coordinates=theta, speeds=omega,
child_joint_pos=-lA*rod.z, parent_axis=C.y, child_axis=rod.y)
J2 = PinJoint('J2', rod, plate, coordinates=phi, speeds=alpha,
parent_joint_pos=(lB-lA)*rod.z, parent_axis=rod.z, child_axis=plate.z)
rod.apply_force(mA*g*C.z)
plate.apply_force(mB*g*C.z)
method = JointsMethod(C, J1, J2)
method.form_eoms()
MM = method.mass_matrix
forcing = method.forcing
rhs = MM.LUsolve(forcing)
xd = (-2 * IBxx * alpha * omega * sin(phi) * cos(phi) + 2 * IByy * alpha * omega * sin(phi) *
cos(phi) - g * lA * mA * sin(theta) - g * lB * mB * sin(theta)) / (IAxx + IBxx *
sin(phi)**2 + IByy * cos(phi)**2 + lA**2 * mA + lB**2 * mB)
assert (rhs[0] - xd).simplify() == 0
xd = (IBxx - IByy) * omega**2 * sin(phi) * cos(phi) / IBzz
assert (rhs[1] - xd).simplify() == 0
def test_four_bar_linkage_with_manual_constraints():
q1, q2, q3, u1, u2, u3 = dynamicsymbols('q1:4, u1:4')
l1, l2, l3, l4, rho = symbols('l1:5, rho')
N = ReferenceFrame('N')
inertias = [inertia(N, 0, 0, rho * l ** 3 / 12) for l in (l1, l2, l3, l4)]
link1 = Body('Link1', frame=N, mass=rho * l1, central_inertia=inertias[0])
link2 = Body('Link2', mass=rho * l2, central_inertia=inertias[1])
link3 = Body('Link3', mass=rho * l3, central_inertia=inertias[2])
link4 = Body('Link4', mass=rho * l4, central_inertia=inertias[3])
joint1 = PinJoint('J1', link1, link2, coordinates=q1, speeds=u1,
parent_axis=link1.z, parent_joint_pos=l1 / 2 * link1.x,
child_axis=link2.z, child_joint_pos=-l2 / 2 * link2.x)
joint2 = PinJoint('J2', link2, link3, coordinates=q2, speeds=u2,
parent_axis=link2.z, parent_joint_pos=l2 / 2 * link2.x,
child_axis=link3.z, child_joint_pos=-l3 / 2 * link3.x)
joint3 = PinJoint('J3', link3, link4, coordinates=q3, speeds=u3,
parent_axis=link3.z, parent_joint_pos=l3 / 2 * link3.x,
child_axis=link4.z, child_joint_pos=-l4 / 2 * link4.x)
loop = link4.masscenter.pos_from(link1.masscenter) \
+ l1 / 2 * link1.x + l4 / 2 * link4.x
fh = Matrix([loop.dot(link1.x), loop.dot(link1.y)])
method = JointsMethod(link1, joint1, joint2, joint3)
t = dynamicsymbols._t
qdots = solve(method.kdes, [q1.diff(t), q2.diff(t), q3.diff(t)])
fhd = fh.diff(t).subs(qdots)
kane = KanesMethod(method.frame, q_ind=[q1], u_ind=[u1],
q_dependent=[q2, q3], u_dependent=[u2, u3],
kd_eqs=method.kdes, configuration_constraints=fh,
velocity_constraints=fhd, forcelist=method.loads,
bodies=method.bodies)
fr, frs = kane.kanes_equations()
assert fr == zeros(1)
# Numerically check the mass- and forcing-matrix
p = Matrix([l1, l2, l3, l4, rho])
q = Matrix([q1, q2, q3])
u = Matrix([u1, u2, u3])
eval_m = lambdify((q, p), kane.mass_matrix)
eval_f = lambdify((q, u, p), kane.forcing)
eval_fhd = lambdify((q, u, p), fhd)
p_vals = [0.13, 0.24, 0.21, 0.34, 997]
q_vals = [2.1, 0.6655470375077588, 2.527408138024188] # Satisfies fh
u_vals = [0.2, -0.17963733938852067, 0.1309060540601612] # Satisfies fhd
mass_check = Matrix([[3.452709815256506e+01, 7.003948798374735e+00,
-4.939690970641498e+00],
[-2.203792703880936e-14, 2.071702479957077e-01,
2.842917573033711e-01],
[-1.300000000000123e-01, -8.836934896046506e-03,
1.864891330060847e-01]])
forcing_check = Matrix([[-0.031211821321648],
[-0.00066022608181],
[0.001813559741243]])
eps = 1e-10
assert all(abs(x) < eps for x in eval_fhd(q_vals, u_vals, p_vals))
assert all(abs(x) < eps for x in
(Matrix(eval_m(q_vals, p_vals)) - mass_check))
assert all(abs(x) < eps for x in
(Matrix(eval_f(q_vals, u_vals, p_vals)) - forcing_check))
|
07a624ecafa8bb237e5415f2703255e2c398acfc857fc6bf43e62dc7bbead66a | from sympy.physics.vector import dynamicsymbols, Point, ReferenceFrame
from sympy.testing.pytest import raises, ignore_warnings
import warnings
def test_point_v1pt_theorys():
q, q2 = dynamicsymbols('q q2')
qd, q2d = dynamicsymbols('q q2', 1)
qdd, q2dd = dynamicsymbols('q q2', 2)
N = ReferenceFrame('N')
B = ReferenceFrame('B')
B.set_ang_vel(N, qd * B.z)
O = Point('O')
P = O.locatenew('P', B.x)
P.set_vel(B, 0)
O.set_vel(N, 0)
assert P.v1pt_theory(O, N, B) == qd * B.y
O.set_vel(N, N.x)
assert P.v1pt_theory(O, N, B) == N.x + qd * B.y
P.set_vel(B, B.z)
assert P.v1pt_theory(O, N, B) == B.z + N.x + qd * B.y
def test_point_a1pt_theorys():
q, q2 = dynamicsymbols('q q2')
qd, q2d = dynamicsymbols('q q2', 1)
qdd, q2dd = dynamicsymbols('q q2', 2)
N = ReferenceFrame('N')
B = ReferenceFrame('B')
B.set_ang_vel(N, qd * B.z)
O = Point('O')
P = O.locatenew('P', B.x)
P.set_vel(B, 0)
O.set_vel(N, 0)
assert P.a1pt_theory(O, N, B) == -(qd**2) * B.x + qdd * B.y
P.set_vel(B, q2d * B.z)
assert P.a1pt_theory(O, N, B) == -(qd**2) * B.x + qdd * B.y + q2dd * B.z
O.set_vel(N, q2d * B.x)
assert P.a1pt_theory(O, N, B) == ((q2dd - qd**2) * B.x + (q2d * qd + qdd) * B.y +
q2dd * B.z)
def test_point_v2pt_theorys():
q = dynamicsymbols('q')
qd = dynamicsymbols('q', 1)
N = ReferenceFrame('N')
B = N.orientnew('B', 'Axis', [q, N.z])
O = Point('O')
P = O.locatenew('P', 0)
O.set_vel(N, 0)
assert P.v2pt_theory(O, N, B) == 0
P = O.locatenew('P', B.x)
assert P.v2pt_theory(O, N, B) == (qd * B.z ^ B.x)
O.set_vel(N, N.x)
assert P.v2pt_theory(O, N, B) == N.x + qd * B.y
def test_point_a2pt_theorys():
q = dynamicsymbols('q')
qd = dynamicsymbols('q', 1)
qdd = dynamicsymbols('q', 2)
N = ReferenceFrame('N')
B = N.orientnew('B', 'Axis', [q, N.z])
O = Point('O')
P = O.locatenew('P', 0)
O.set_vel(N, 0)
assert P.a2pt_theory(O, N, B) == 0
P.set_pos(O, B.x)
assert P.a2pt_theory(O, N, B) == (-qd**2) * B.x + (qdd) * B.y
def test_point_funcs():
q, q2 = dynamicsymbols('q q2')
qd, q2d = dynamicsymbols('q q2', 1)
qdd, q2dd = dynamicsymbols('q q2', 2)
N = ReferenceFrame('N')
B = ReferenceFrame('B')
B.set_ang_vel(N, 5 * B.y)
O = Point('O')
P = O.locatenew('P', q * B.x)
assert P.pos_from(O) == q * B.x
P.set_vel(B, qd * B.x + q2d * B.y)
assert P.vel(B) == qd * B.x + q2d * B.y
O.set_vel(N, 0)
assert O.vel(N) == 0
assert P.a1pt_theory(O, N, B) == ((-25 * q + qdd) * B.x + (q2dd) * B.y +
(-10 * qd) * B.z)
B = N.orientnew('B', 'Axis', [q, N.z])
O = Point('O')
P = O.locatenew('P', 10 * B.x)
O.set_vel(N, 5 * N.x)
assert O.vel(N) == 5 * N.x
assert P.a2pt_theory(O, N, B) == (-10 * qd**2) * B.x + (10 * qdd) * B.y
B.set_ang_vel(N, 5 * B.y)
O = Point('O')
P = O.locatenew('P', q * B.x)
P.set_vel(B, qd * B.x + q2d * B.y)
O.set_vel(N, 0)
assert P.v1pt_theory(O, N, B) == qd * B.x + q2d * B.y - 5 * q * B.z
def test_point_pos():
q = dynamicsymbols('q')
N = ReferenceFrame('N')
B = N.orientnew('B', 'Axis', [q, N.z])
O = Point('O')
P = O.locatenew('P', 10 * N.x + 5 * B.x)
assert P.pos_from(O) == 10 * N.x + 5 * B.x
Q = P.locatenew('Q', 10 * N.y + 5 * B.y)
assert Q.pos_from(P) == 10 * N.y + 5 * B.y
assert Q.pos_from(O) == 10 * N.x + 10 * N.y + 5 * B.x + 5 * B.y
assert O.pos_from(Q) == -10 * N.x - 10 * N.y - 5 * B.x - 5 * B.y
def test_point_partial_velocity():
N = ReferenceFrame('N')
A = ReferenceFrame('A')
p = Point('p')
u1, u2 = dynamicsymbols('u1, u2')
p.set_vel(N, u1 * A.x + u2 * N.y)
assert p.partial_velocity(N, u1) == A.x
assert p.partial_velocity(N, u1, u2) == (A.x, N.y)
raises(ValueError, lambda: p.partial_velocity(A, u1))
def test_point_vel(): #Basic functionality
q1, q2 = dynamicsymbols('q1 q2')
N = ReferenceFrame('N')
B = ReferenceFrame('B')
Q = Point('Q')
O = Point('O')
Q.set_pos(O, q1 * N.x)
raises(ValueError , lambda: Q.vel(N)) # Velocity of O in N is not defined
O.set_vel(N, q2 * N.y)
assert O.vel(N) == q2 * N.y
raises(ValueError , lambda : O.vel(B)) #Velocity of O is not defined in B
def test_auto_point_vel():
t = dynamicsymbols._t
q1, q2 = dynamicsymbols('q1 q2')
N = ReferenceFrame('N')
B = ReferenceFrame('B')
O = Point('O')
Q = Point('Q')
Q.set_pos(O, q1 * N.x)
O.set_vel(N, q2 * N.y)
assert Q.vel(N) == q1.diff(t) * N.x + q2 * N.y # Velocity of Q using O
P1 = Point('P1')
P1.set_pos(O, q1 * B.x)
P2 = Point('P2')
P2.set_pos(P1, q2 * B.z)
raises(ValueError, lambda : P2.vel(B)) # O's velocity is defined in different frame, and no
#point in between has its velocity defined
raises(ValueError, lambda: P2.vel(N)) # Velocity of O not defined in N
def test_auto_point_vel_multiple_point_path():
t = dynamicsymbols._t
q1, q2 = dynamicsymbols('q1 q2')
B = ReferenceFrame('B')
P = Point('P')
P.set_vel(B, q1 * B.x)
P1 = Point('P1')
P1.set_pos(P, q2 * B.y)
P1.set_vel(B, q1 * B.z)
P2 = Point('P2')
P2.set_pos(P1, q1 * B.z)
P3 = Point('P3')
P3.set_pos(P2, 10 * q1 * B.y)
assert P3.vel(B) == 10 * q1.diff(t) * B.y + (q1 + q1.diff(t)) * B.z
def test_auto_vel_dont_overwrite():
t = dynamicsymbols._t
q1, q2, u1 = dynamicsymbols('q1, q2, u1')
N = ReferenceFrame('N')
P = Point('P1')
P.set_vel(N, u1 * N.x)
P1 = Point('P1')
P1.set_pos(P, q2 * N.y)
assert P1.vel(N) == q2.diff(t) * N.y + u1 * N.x
assert P.vel(N) == u1 * N.x
P1.set_vel(N, u1 * N.z)
assert P1.vel(N) == u1 * N.z
def test_auto_point_vel_if_tree_has_vel_but_inappropriate_pos_vector():
q1, q2 = dynamicsymbols('q1 q2')
B = ReferenceFrame('B')
S = ReferenceFrame('S')
P = Point('P')
P.set_vel(B, q1 * B.x)
P1 = Point('P1')
P1.set_pos(P, S.y)
raises(ValueError, lambda : P1.vel(B)) # P1.pos_from(P) can't be expressed in B
raises(ValueError, lambda : P1.vel(S)) # P.vel(S) not defined
def test_auto_point_vel_shortest_path():
t = dynamicsymbols._t
q1, q2, u1, u2 = dynamicsymbols('q1 q2 u1 u2')
B = ReferenceFrame('B')
P = Point('P')
P.set_vel(B, u1 * B.x)
P1 = Point('P1')
P1.set_pos(P, q2 * B.y)
P1.set_vel(B, q1 * B.z)
P2 = Point('P2')
P2.set_pos(P1, q1 * B.z)
P3 = Point('P3')
P3.set_pos(P2, 10 * q1 * B.y)
P4 = Point('P4')
P4.set_pos(P3, q1 * B.x)
O = Point('O')
O.set_vel(B, u2 * B.y)
O1 = Point('O1')
O1.set_pos(O, q2 * B.z)
P4.set_pos(O1, q1 * B.x + q2 * B.z)
with warnings.catch_warnings(): #There are two possible paths in this point tree, thus a warning is raised
warnings.simplefilter('error')
with ignore_warnings(UserWarning):
assert P4.vel(B) == q1.diff(t) * B.x + u2 * B.y + 2 * q2.diff(t) * B.z
def test_auto_point_vel_connected_frames():
t = dynamicsymbols._t
q, q1, q2, u = dynamicsymbols('q q1 q2 u')
N = ReferenceFrame('N')
B = ReferenceFrame('B')
O = Point('O')
O.set_vel(N, u * N.x)
P = Point('P')
P.set_pos(O, q1 * N.x + q2 * B.y)
raises(ValueError, lambda: P.vel(N))
N.orient(B, 'Axis', (q, B.x))
assert P.vel(N) == (u + q1.diff(t)) * N.x + q2.diff(t) * B.y - q2 * q.diff(t) * B.z
def test_auto_point_vel_multiple_paths_warning_arises():
q, u = dynamicsymbols('q u')
N = ReferenceFrame('N')
O = Point('O')
P = Point('P')
Q = Point('Q')
R = Point('R')
P.set_vel(N, u * N.x)
Q.set_vel(N, u *N.y)
R.set_vel(N, u * N.z)
O.set_pos(P, q * N.z)
O.set_pos(Q, q * N.y)
O.set_pos(R, q * N.x)
with warnings.catch_warnings(): #There are two possible paths in this point tree, thus a warning is raised
warnings.simplefilter("error")
raises(UserWarning ,lambda: O.vel(N))
def test_auto_vel_cyclic_warning_arises():
P = Point('P')
P1 = Point('P1')
P2 = Point('P2')
P3 = Point('P3')
N = ReferenceFrame('N')
P.set_vel(N, N.x)
P1.set_pos(P, N.x)
P2.set_pos(P1, N.y)
P3.set_pos(P2, N.z)
P1.set_pos(P3, N.x + N.y)
with warnings.catch_warnings(): #The path is cyclic at P1, thus a warning is raised
warnings.simplefilter("error")
raises(UserWarning ,lambda: P2.vel(N))
def test_auto_vel_cyclic_warning_msg():
P = Point('P')
P1 = Point('P1')
P2 = Point('P2')
P3 = Point('P3')
N = ReferenceFrame('N')
P.set_vel(N, N.x)
P1.set_pos(P, N.x)
P2.set_pos(P1, N.y)
P3.set_pos(P2, N.z)
P1.set_pos(P3, N.x + N.y)
with warnings.catch_warnings(record = True) as w: #The path is cyclic at P1, thus a warning is raised
warnings.simplefilter("always")
P2.vel(N)
assert issubclass(w[-1].category, UserWarning)
assert 'Kinematic loops are defined among the positions of points. This is likely not desired and may cause errors in your calculations.' in str(w[-1].message)
def test_auto_vel_multiple_path_warning_msg():
N = ReferenceFrame('N')
O = Point('O')
P = Point('P')
Q = Point('Q')
P.set_vel(N, N.x)
Q.set_vel(N, N.y)
O.set_pos(P, N.z)
O.set_pos(Q, N.y)
with warnings.catch_warnings(record = True) as w: #There are two possible paths in this point tree, thus a warning is raised
warnings.simplefilter("always")
O.vel(N)
assert issubclass(w[-1].category, UserWarning)
assert 'Velocity automatically calculated based on point' in str(w[-1].message)
assert 'Velocities from these points are not necessarily the same. This may cause errors in your calculations.' in str(w[-1].message)
def test_auto_vel_derivative():
q1, q2 = dynamicsymbols('q1:3')
u1, u2 = dynamicsymbols('u1:3', 1)
A = ReferenceFrame('A')
B = ReferenceFrame('B')
C = ReferenceFrame('C')
B.orient_axis(A, A.z, q1)
B.set_ang_vel(A, u1 * A.z)
C.orient_axis(B, B.z, q2)
C.set_ang_vel(B, u2 * B.z)
Am = Point('Am')
Am.set_vel(A, 0)
Bm = Point('Bm')
Bm.set_pos(Am, B.x)
Bm.set_vel(B, 0)
Bm.set_vel(C, 0)
Cm = Point('Cm')
Cm.set_pos(Bm, C.x)
Cm.set_vel(C, 0)
temp = Cm._vel_dict.copy()
assert Cm.vel(A) == (u1 * B.y + (u1 + u2) * C.y)
Cm._vel_dict = temp
Cm.v2pt_theory(Bm, B, C)
assert Cm.vel(A) == (u1 * B.y + (u1 + u2) * C.y)
def test_auto_point_acc_zero_vel():
N = ReferenceFrame('N')
O = Point('O')
O.set_vel(N, 0)
assert O.acc(N) == 0 * N.x
def test_auto_point_acc_compute_vel():
t = dynamicsymbols._t
q1 = dynamicsymbols('q1')
N = ReferenceFrame('N')
A = ReferenceFrame('A')
A.orient_axis(N, N.z, q1)
O = Point('O')
O.set_vel(N, 0)
P = Point('P')
P.set_pos(O, A.x)
assert P.acc(N) == -q1.diff(t) ** 2 * A.x + q1.diff(t, 2) * A.y
def test_auto_acc_derivative():
# Tests whether the Point.acc method gives the correct acceleration of the
# end point of two linkages in series, while getting minimal information.
q1, q2 = dynamicsymbols('q1:3')
u1, u2 = dynamicsymbols('q1:3', 1)
v1, v2 = dynamicsymbols('q1:3', 2)
A = ReferenceFrame('A')
B = ReferenceFrame('B')
C = ReferenceFrame('C')
B.orient_axis(A, A.z, q1)
C.orient_axis(B, B.z, q2)
Am = Point('Am')
Am.set_vel(A, 0)
Bm = Point('Bm')
Bm.set_pos(Am, B.x)
Bm.set_vel(B, 0)
Bm.set_vel(C, 0)
Cm = Point('Cm')
Cm.set_pos(Bm, C.x)
Cm.set_vel(C, 0)
# Copy dictionaries to later check the calculation using the 2pt_theories
Bm_vel_dict, Cm_vel_dict = Bm._vel_dict.copy(), Cm._vel_dict.copy()
Bm_acc_dict, Cm_acc_dict = Bm._acc_dict.copy(), Cm._acc_dict.copy()
check = -u1 ** 2 * B.x + v1 * B.y - (u1 + u2) ** 2 * C.x + (v1 + v2) * C.y
assert Cm.acc(A) == check
Bm._vel_dict, Cm._vel_dict = Bm_vel_dict, Cm_vel_dict
Bm._acc_dict, Cm._acc_dict = Bm_acc_dict, Cm_acc_dict
Bm.v2pt_theory(Am, A, B)
Cm.v2pt_theory(Bm, A, C)
Bm.a2pt_theory(Am, A, B)
assert Cm.a2pt_theory(Bm, A, C) == check
|
65f86d4e259a2a4b431ad8c84b84eeded4d3fd213bb4930c18770f63fd8304e9 | from sympy.core.symbol import Symbol, symbols
from sympy.physics.continuum_mechanics.truss import Truss
def test_truss():
A = Symbol('A')
B = Symbol('B')
C = Symbol('C')
AB, BC, AC = symbols('AB, BC, AC')
P = Symbol('P')
t = Truss()
assert t.nodes == []
assert t.node_labels == []
assert t.node_positions == []
assert t.members == {}
assert t.loads == {}
assert t.supports == {}
assert t.reaction_loads == {}
assert t.internal_forces == {}
# testing the add_node method
t.add_node(A, 0, 0)
t.add_node(B, 2, 2)
t.add_node(C, 3, 0)
assert t.nodes == [(A, 0, 0), (B, 2, 2), (C, 3, 0)]
assert t.node_labels == [A, B, C]
assert t.node_positions == [(0, 0), (2, 2), (3, 0)]
assert t.loads == {}
assert t.supports == {}
assert t.reaction_loads == {}
# testing the remove_node method
t.remove_node(C)
assert t.nodes == [(A, 0, 0), (B, 2, 2)]
assert t.node_labels == [A, B]
assert t.node_positions == [(0, 0), (2, 2)]
assert t.loads == {}
assert t.supports == {}
t.add_node(C, 3, 0)
# testing the add_member method
t.add_member(AB, A, B)
t.add_member(BC, B, C)
t.add_member(AC, A, C)
assert t.members == {AB: [A, B], BC: [B, C], AC: [A, C]}
assert t.internal_forces == {AB: 0, BC: 0, AC: 0}
# testing the remove_member method
t.remove_member(BC)
assert t.members == {AB: [A, B], AC: [A, C]}
assert t.internal_forces == {AB: 0, AC: 0}
t.add_member(BC, B, C)
D, CD = symbols('D, CD')
# testing the change_label methods
t.change_node_label(B, D)
assert t.nodes == [(A, 0, 0), (D, 2, 2), (C, 3, 0)]
assert t.node_labels == [A, D, C]
assert t.loads == {}
assert t.supports == {}
assert t.members == {AB: [A, D], BC: [D, C], AC: [A, C]}
t.change_member_label(BC, CD)
assert t.members == {AB: [A, D], CD: [D, C], AC: [A, C]}
assert t.internal_forces == {AB: 0, CD: 0, AC: 0}
# testing the apply_load method
t.apply_load(A, P, 90)
t.apply_load(A, P/4, 90)
t.apply_load(A, 2*P,45)
t.apply_load(D, P/2, 90)
assert t.loads == {A: [[P, 90], [P/4, 90], [2*P, 45]], D: [[P/2, 90]]}
assert t.loads[A] == [[P, 90], [P/4, 90], [2*P, 45]]
# testing the remove_load method
t.remove_load(A, P/4, 90)
assert t.loads == {A: [[P, 90], [2*P, 45]], D: [[P/2, 90]]}
assert t.loads[A] == [[P, 90], [2*P, 45]]
# testing the apply_support method
t.apply_support(A, "pinned")
t.apply_support(D, "roller")
assert t.supports == {A: 'pinned', D: 'roller'}
assert t.reaction_loads == {}
assert t.loads == {A: [[P, 90], [2*P, 45], [Symbol('R_A_x'), 0], [Symbol('R_A_y'), 90]], D: [[P/2, 90], [Symbol('R_D_y'), 90]]}
# testing the remove_support method
t.remove_support(A)
assert t.supports == {D: 'roller'}
assert t.reaction_loads == {}
assert t.loads == {A: [[P, 90], [2*P, 45]], D: [[P/2, 90], [Symbol('R_D_y'), 90]]}
|
d353d321b90019aab408371a23fd8ab1a327626d67c50f2c1408871dc73ffe0c | import functools, itertools
from sympy.core.sympify import _sympify, sympify
from sympy.core.expr import Expr
from sympy.core import Basic, Tuple
from sympy.tensor.array import ImmutableDenseNDimArray
from sympy.core.symbol import Symbol
from sympy.core.numbers import Integer
class ArrayComprehension(Basic):
"""
Generate a list comprehension.
Explanation
===========
If there is a symbolic dimension, for example, say [i for i in range(1, N)] where
N is a Symbol, then the expression will not be expanded to an array. Otherwise,
calling the doit() function will launch the expansion.
Examples
========
>>> from sympy.tensor.array import ArrayComprehension
>>> from sympy import symbols
>>> i, j, k = symbols('i j k')
>>> a = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, 3))
>>> a
ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, 3))
>>> a.doit()
[[11, 12, 13], [21, 22, 23], [31, 32, 33], [41, 42, 43]]
>>> b = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, k))
>>> b.doit()
ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, k))
"""
def __new__(cls, function, *symbols, **assumptions):
if any(len(l) != 3 or None for l in symbols):
raise ValueError('ArrayComprehension requires values lower and upper bound'
' for the expression')
arglist = [sympify(function)]
arglist.extend(cls._check_limits_validity(function, symbols))
obj = Basic.__new__(cls, *arglist, **assumptions)
obj._limits = obj._args[1:]
obj._shape = cls._calculate_shape_from_limits(obj._limits)
obj._rank = len(obj._shape)
obj._loop_size = cls._calculate_loop_size(obj._shape)
return obj
@property
def function(self):
"""The function applied across limits.
Examples
========
>>> from sympy.tensor.array import ArrayComprehension
>>> from sympy import symbols
>>> i, j = symbols('i j')
>>> a = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, 3))
>>> a.function
10*i + j
"""
return self._args[0]
@property
def limits(self):
"""
The list of limits that will be applied while expanding the array.
Examples
========
>>> from sympy.tensor.array import ArrayComprehension
>>> from sympy import symbols
>>> i, j = symbols('i j')
>>> a = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, 3))
>>> a.limits
((i, 1, 4), (j, 1, 3))
"""
return self._limits
@property
def free_symbols(self):
"""
The set of the free_symbols in the array.
Variables appeared in the bounds are supposed to be excluded
from the free symbol set.
Examples
========
>>> from sympy.tensor.array import ArrayComprehension
>>> from sympy import symbols
>>> i, j, k = symbols('i j k')
>>> a = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, 3))
>>> a.free_symbols
set()
>>> b = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, k+3))
>>> b.free_symbols
{k}
"""
expr_free_sym = self.function.free_symbols
for var, inf, sup in self._limits:
expr_free_sym.discard(var)
curr_free_syms = inf.free_symbols.union(sup.free_symbols)
expr_free_sym = expr_free_sym.union(curr_free_syms)
return expr_free_sym
@property
def variables(self):
"""The tuples of the variables in the limits.
Examples
========
>>> from sympy.tensor.array import ArrayComprehension
>>> from sympy import symbols
>>> i, j, k = symbols('i j k')
>>> a = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, 3))
>>> a.variables
[i, j]
"""
return [l[0] for l in self._limits]
@property
def bound_symbols(self):
"""The list of dummy variables.
Note
====
Note that all variables are dummy variables since a limit without
lower bound or upper bound is not accepted.
"""
return [l[0] for l in self._limits if len(l) != 1]
@property
def shape(self):
"""
The shape of the expanded array, which may have symbols.
Note
====
Both the lower and the upper bounds are included while
calculating the shape.
Examples
========
>>> from sympy.tensor.array import ArrayComprehension
>>> from sympy import symbols
>>> i, j, k = symbols('i j k')
>>> a = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, 3))
>>> a.shape
(4, 3)
>>> b = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, k+3))
>>> b.shape
(4, k + 3)
"""
return self._shape
@property
def is_shape_numeric(self):
"""
Test if the array is shape-numeric which means there is no symbolic
dimension.
Examples
========
>>> from sympy.tensor.array import ArrayComprehension
>>> from sympy import symbols
>>> i, j, k = symbols('i j k')
>>> a = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, 3))
>>> a.is_shape_numeric
True
>>> b = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, k+3))
>>> b.is_shape_numeric
False
"""
for _, inf, sup in self._limits:
if Basic(inf, sup).atoms(Symbol):
return False
return True
def rank(self):
"""The rank of the expanded array.
Examples
========
>>> from sympy.tensor.array import ArrayComprehension
>>> from sympy import symbols
>>> i, j, k = symbols('i j k')
>>> a = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, 3))
>>> a.rank()
2
"""
return self._rank
def __len__(self):
"""
The length of the expanded array which means the number
of elements in the array.
Raises
======
ValueError : When the length of the array is symbolic
Examples
========
>>> from sympy.tensor.array import ArrayComprehension
>>> from sympy import symbols
>>> i, j = symbols('i j')
>>> a = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, 3))
>>> len(a)
12
"""
if self._loop_size.free_symbols:
raise ValueError('Symbolic length is not supported')
return self._loop_size
@classmethod
def _check_limits_validity(cls, function, limits):
#limits = sympify(limits)
new_limits = []
for var, inf, sup in limits:
var = _sympify(var)
inf = _sympify(inf)
#since this is stored as an argument, it should be
#a Tuple
if isinstance(sup, list):
sup = Tuple(*sup)
else:
sup = _sympify(sup)
new_limits.append(Tuple(var, inf, sup))
if any((not isinstance(i, Expr)) or i.atoms(Symbol, Integer) != i.atoms()
for i in [inf, sup]):
raise TypeError('Bounds should be an Expression(combination of Integer and Symbol)')
if (inf > sup) == True:
raise ValueError('Lower bound should be inferior to upper bound')
if var in inf.free_symbols or var in sup.free_symbols:
raise ValueError('Variable should not be part of its bounds')
return new_limits
@classmethod
def _calculate_shape_from_limits(cls, limits):
return tuple([sup - inf + 1 for _, inf, sup in limits])
@classmethod
def _calculate_loop_size(cls, shape):
if not shape:
return 0
loop_size = 1
for l in shape:
loop_size = loop_size * l
return loop_size
def doit(self, **hints):
if not self.is_shape_numeric:
return self
return self._expand_array()
def _expand_array(self):
res = []
for values in itertools.product(*[range(inf, sup+1)
for var, inf, sup
in self._limits]):
res.append(self._get_element(values))
return ImmutableDenseNDimArray(res, self.shape)
def _get_element(self, values):
temp = self.function
for var, val in zip(self.variables, values):
temp = temp.subs(var, val)
return temp
def tolist(self):
"""Transform the expanded array to a list.
Raises
======
ValueError : When there is a symbolic dimension
Examples
========
>>> from sympy.tensor.array import ArrayComprehension
>>> from sympy import symbols
>>> i, j = symbols('i j')
>>> a = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, 3))
>>> a.tolist()
[[11, 12, 13], [21, 22, 23], [31, 32, 33], [41, 42, 43]]
"""
if self.is_shape_numeric:
return self._expand_array().tolist()
raise ValueError("A symbolic array cannot be expanded to a list")
def tomatrix(self):
"""Transform the expanded array to a matrix.
Raises
======
ValueError : When there is a symbolic dimension
ValueError : When the rank of the expanded array is not equal to 2
Examples
========
>>> from sympy.tensor.array import ArrayComprehension
>>> from sympy import symbols
>>> i, j = symbols('i j')
>>> a = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, 3))
>>> a.tomatrix()
Matrix([
[11, 12, 13],
[21, 22, 23],
[31, 32, 33],
[41, 42, 43]])
"""
from sympy.matrices import Matrix
if not self.is_shape_numeric:
raise ValueError("A symbolic array cannot be expanded to a matrix")
if self._rank != 2:
raise ValueError('Dimensions must be of size of 2')
return Matrix(self._expand_array().tomatrix())
def isLambda(v):
LAMBDA = lambda: 0
return isinstance(v, type(LAMBDA)) and v.__name__ == LAMBDA.__name__
class ArrayComprehensionMap(ArrayComprehension):
'''
A subclass of ArrayComprehension dedicated to map external function lambda.
Notes
=====
Only the lambda function is considered.
At most one argument in lambda function is accepted in order to avoid ambiguity
in value assignment.
Examples
========
>>> from sympy.tensor.array import ArrayComprehensionMap
>>> from sympy import symbols
>>> i, j, k = symbols('i j k')
>>> a = ArrayComprehensionMap(lambda: 1, (i, 1, 4))
>>> a.doit()
[1, 1, 1, 1]
>>> b = ArrayComprehensionMap(lambda a: a+1, (j, 1, 4))
>>> b.doit()
[2, 3, 4, 5]
'''
def __new__(cls, function, *symbols, **assumptions):
if any(len(l) != 3 or None for l in symbols):
raise ValueError('ArrayComprehension requires values lower and upper bound'
' for the expression')
if not isLambda(function):
raise ValueError('Data type not supported')
arglist = cls._check_limits_validity(function, symbols)
obj = Basic.__new__(cls, *arglist, **assumptions)
obj._limits = obj._args
obj._shape = cls._calculate_shape_from_limits(obj._limits)
obj._rank = len(obj._shape)
obj._loop_size = cls._calculate_loop_size(obj._shape)
obj._lambda = function
return obj
@property
def func(self):
class _(ArrayComprehensionMap):
def __new__(cls, *args, **kwargs):
return ArrayComprehensionMap(self._lambda, *args, **kwargs)
return _
def _get_element(self, values):
temp = self._lambda
if self._lambda.__code__.co_argcount == 0:
temp = temp()
elif self._lambda.__code__.co_argcount == 1:
temp = temp(functools.reduce(lambda a, b: a*b, values))
return temp
|
4ab03e01e41451a8018b3fea3722d390e9604426aaf0678eadb4a4857c3809eb | from sympy.core.basic import Basic
from sympy.core.containers import (Dict, Tuple)
from sympy.core.expr import Expr
from sympy.core.kind import Kind, NumberKind, UndefinedKind
from sympy.core.numbers import Integer
from sympy.core.singleton import S
from sympy.core.sympify import sympify
from sympy.external.gmpy import SYMPY_INTS
from sympy.printing.defaults import Printable
import itertools
from collections.abc import Iterable
class ArrayKind(Kind):
"""
Kind for N-dimensional array in SymPy.
This kind represents the multidimensional array that algebraic
operations are defined. Basic class for this kind is ``NDimArray``,
but any expression representing the array can have this.
Parameters
==========
element_kind : Kind
Kind of the element. Default is :obj:NumberKind `<sympy.core.kind.NumberKind>`,
which means that the array contains only numbers.
Examples
========
Any instance of array class has ``ArrayKind``.
>>> from sympy import NDimArray
>>> NDimArray([1,2,3]).kind
ArrayKind(NumberKind)
Although expressions representing an array may be not instance of
array class, it will have ``ArrayKind`` as well.
>>> from sympy import Integral
>>> from sympy.tensor.array import NDimArray
>>> from sympy.abc import x
>>> intA = Integral(NDimArray([1,2,3]), x)
>>> isinstance(intA, NDimArray)
False
>>> intA.kind
ArrayKind(NumberKind)
Use ``isinstance()`` to check for ``ArrayKind` without specifying
the element kind. Use ``is`` with specifying the element kind.
>>> from sympy.tensor.array import ArrayKind
>>> from sympy.core import NumberKind
>>> boolA = NDimArray([True, False])
>>> isinstance(boolA.kind, ArrayKind)
True
>>> boolA.kind is ArrayKind(NumberKind)
False
See Also
========
shape : Function to return the shape of objects with ``MatrixKind``.
"""
def __new__(cls, element_kind=NumberKind):
obj = super().__new__(cls, element_kind)
obj.element_kind = element_kind
return obj
def __repr__(self):
return "ArrayKind(%s)" % self.element_kind
@classmethod
def _union(cls, kinds) -> 'ArrayKind':
elem_kinds = set(e.kind for e in kinds)
if len(elem_kinds) == 1:
elemkind, = elem_kinds
else:
elemkind = UndefinedKind
return ArrayKind(elemkind)
class NDimArray(Printable):
"""
Examples
========
Create an N-dim array of zeros:
>>> from sympy import MutableDenseNDimArray
>>> a = MutableDenseNDimArray.zeros(2, 3, 4)
>>> a
[[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]]
Create an N-dim array from a list;
>>> a = MutableDenseNDimArray([[2, 3], [4, 5]])
>>> a
[[2, 3], [4, 5]]
>>> b = MutableDenseNDimArray([[[1, 2], [3, 4], [5, 6]], [[7, 8], [9, 10], [11, 12]]])
>>> b
[[[1, 2], [3, 4], [5, 6]], [[7, 8], [9, 10], [11, 12]]]
Create an N-dim array from a flat list with dimension shape:
>>> a = MutableDenseNDimArray([1, 2, 3, 4, 5, 6], (2, 3))
>>> a
[[1, 2, 3], [4, 5, 6]]
Create an N-dim array from a matrix:
>>> from sympy import Matrix
>>> a = Matrix([[1,2],[3,4]])
>>> a
Matrix([
[1, 2],
[3, 4]])
>>> b = MutableDenseNDimArray(a)
>>> b
[[1, 2], [3, 4]]
Arithmetic operations on N-dim arrays
>>> a = MutableDenseNDimArray([1, 1, 1, 1], (2, 2))
>>> b = MutableDenseNDimArray([4, 4, 4, 4], (2, 2))
>>> c = a + b
>>> c
[[5, 5], [5, 5]]
>>> a - b
[[-3, -3], [-3, -3]]
"""
_diff_wrt = True
is_scalar = False
def __new__(cls, iterable, shape=None, **kwargs):
from sympy.tensor.array import ImmutableDenseNDimArray
return ImmutableDenseNDimArray(iterable, shape, **kwargs)
def __getitem__(self, index):
raise NotImplementedError("A subclass of NDimArray should implement __getitem__")
def _parse_index(self, index):
if isinstance(index, (SYMPY_INTS, Integer)):
if index >= self._loop_size:
raise ValueError("Only a tuple index is accepted")
return index
if self._loop_size == 0:
raise ValueError("Index not valid with an empty array")
if len(index) != self._rank:
raise ValueError('Wrong number of array axes')
real_index = 0
# check if input index can exist in current indexing
for i in range(self._rank):
if (index[i] >= self.shape[i]) or (index[i] < -self.shape[i]):
raise ValueError('Index ' + str(index) + ' out of border')
if index[i] < 0:
real_index += 1
real_index = real_index*self.shape[i] + index[i]
return real_index
def _get_tuple_index(self, integer_index):
index = []
for i, sh in enumerate(reversed(self.shape)):
index.append(integer_index % sh)
integer_index //= sh
index.reverse()
return tuple(index)
def _check_symbolic_index(self, index):
# Check if any index is symbolic:
tuple_index = (index if isinstance(index, tuple) else (index,))
if any((isinstance(i, Expr) and (not i.is_number)) for i in tuple_index):
for i, nth_dim in zip(tuple_index, self.shape):
if ((i < 0) == True) or ((i >= nth_dim) == True):
raise ValueError("index out of range")
from sympy.tensor import Indexed
return Indexed(self, *tuple_index)
return None
def _setter_iterable_check(self, value):
from sympy.matrices.matrices import MatrixBase
if isinstance(value, (Iterable, MatrixBase, NDimArray)):
raise NotImplementedError
@classmethod
def _scan_iterable_shape(cls, iterable):
def f(pointer):
if not isinstance(pointer, Iterable):
return [pointer], ()
if len(pointer) == 0:
return [], (0,)
result = []
elems, shapes = zip(*[f(i) for i in pointer])
if len(set(shapes)) != 1:
raise ValueError("could not determine shape unambiguously")
for i in elems:
result.extend(i)
return result, (len(shapes),)+shapes[0]
return f(iterable)
@classmethod
def _handle_ndarray_creation_inputs(cls, iterable=None, shape=None, **kwargs):
from sympy.matrices.matrices import MatrixBase
from sympy.tensor.array import SparseNDimArray
if shape is None:
if iterable is None:
shape = ()
iterable = ()
# Construction of a sparse array from a sparse array
elif isinstance(iterable, SparseNDimArray):
return iterable._shape, iterable._sparse_array
# Construct N-dim array from another N-dim array:
elif isinstance(iterable, NDimArray):
shape = iterable.shape
# Construct N-dim array from an iterable (numpy arrays included):
elif isinstance(iterable, Iterable):
iterable, shape = cls._scan_iterable_shape(iterable)
# Construct N-dim array from a Matrix:
elif isinstance(iterable, MatrixBase):
shape = iterable.shape
else:
shape = ()
iterable = (iterable,)
if isinstance(iterable, (Dict, dict)) and shape is not None:
new_dict = iterable.copy()
for k, v in new_dict.items():
if isinstance(k, (tuple, Tuple)):
new_key = 0
for i, idx in enumerate(k):
new_key = new_key * shape[i] + idx
iterable[new_key] = iterable[k]
del iterable[k]
if isinstance(shape, (SYMPY_INTS, Integer)):
shape = (shape,)
if not all(isinstance(dim, (SYMPY_INTS, Integer)) for dim in shape):
raise TypeError("Shape should contain integers only.")
return tuple(shape), iterable
def __len__(self):
"""Overload common function len(). Returns number of elements in array.
Examples
========
>>> from sympy import MutableDenseNDimArray
>>> a = MutableDenseNDimArray.zeros(3, 3)
>>> a
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>> len(a)
9
"""
return self._loop_size
@property
def shape(self):
"""
Returns array shape (dimension).
Examples
========
>>> from sympy import MutableDenseNDimArray
>>> a = MutableDenseNDimArray.zeros(3, 3)
>>> a.shape
(3, 3)
"""
return self._shape
def rank(self):
"""
Returns rank of array.
Examples
========
>>> from sympy import MutableDenseNDimArray
>>> a = MutableDenseNDimArray.zeros(3,4,5,6,3)
>>> a.rank()
5
"""
return self._rank
def diff(self, *args, **kwargs):
"""
Calculate the derivative of each element in the array.
Examples
========
>>> from sympy import ImmutableDenseNDimArray
>>> from sympy.abc import x, y
>>> M = ImmutableDenseNDimArray([[x, y], [1, x*y]])
>>> M.diff(x)
[[1, 0], [0, y]]
"""
from sympy.tensor.array.array_derivatives import ArrayDerivative
kwargs.setdefault('evaluate', True)
return ArrayDerivative(self.as_immutable(), *args, **kwargs)
def _eval_derivative(self, base):
# Types are (base: scalar, self: array)
return self.applyfunc(lambda x: base.diff(x))
def _eval_derivative_n_times(self, s, n):
return Basic._eval_derivative_n_times(self, s, n)
def applyfunc(self, f):
"""Apply a function to each element of the N-dim array.
Examples
========
>>> from sympy import ImmutableDenseNDimArray
>>> m = ImmutableDenseNDimArray([i*2+j for i in range(2) for j in range(2)], (2, 2))
>>> m
[[0, 1], [2, 3]]
>>> m.applyfunc(lambda i: 2*i)
[[0, 2], [4, 6]]
"""
from sympy.tensor.array import SparseNDimArray
from sympy.tensor.array.arrayop import Flatten
if isinstance(self, SparseNDimArray) and f(S.Zero) == 0:
return type(self)({k: f(v) for k, v in self._sparse_array.items() if f(v) != 0}, self.shape)
return type(self)(map(f, Flatten(self)), self.shape)
def _sympystr(self, printer):
def f(sh, shape_left, i, j):
if len(shape_left) == 1:
return "["+", ".join([printer._print(self[self._get_tuple_index(e)]) for e in range(i, j)])+"]"
sh //= shape_left[0]
return "[" + ", ".join([f(sh, shape_left[1:], i+e*sh, i+(e+1)*sh) for e in range(shape_left[0])]) + "]" # + "\n"*len(shape_left)
if self.rank() == 0:
return printer._print(self[()])
return f(self._loop_size, self.shape, 0, self._loop_size)
def tolist(self):
"""
Converting MutableDenseNDimArray to one-dim list
Examples
========
>>> from sympy import MutableDenseNDimArray
>>> a = MutableDenseNDimArray([1, 2, 3, 4], (2, 2))
>>> a
[[1, 2], [3, 4]]
>>> b = a.tolist()
>>> b
[[1, 2], [3, 4]]
"""
def f(sh, shape_left, i, j):
if len(shape_left) == 1:
return [self[self._get_tuple_index(e)] for e in range(i, j)]
result = []
sh //= shape_left[0]
for e in range(shape_left[0]):
result.append(f(sh, shape_left[1:], i+e*sh, i+(e+1)*sh))
return result
return f(self._loop_size, self.shape, 0, self._loop_size)
def __add__(self, other):
from sympy.tensor.array.arrayop import Flatten
if not isinstance(other, NDimArray):
return NotImplemented
if self.shape != other.shape:
raise ValueError("array shape mismatch")
result_list = [i+j for i,j in zip(Flatten(self), Flatten(other))]
return type(self)(result_list, self.shape)
def __sub__(self, other):
from sympy.tensor.array.arrayop import Flatten
if not isinstance(other, NDimArray):
return NotImplemented
if self.shape != other.shape:
raise ValueError("array shape mismatch")
result_list = [i-j for i,j in zip(Flatten(self), Flatten(other))]
return type(self)(result_list, self.shape)
def __mul__(self, other):
from sympy.matrices.matrices import MatrixBase
from sympy.tensor.array import SparseNDimArray
from sympy.tensor.array.arrayop import Flatten
if isinstance(other, (Iterable, NDimArray, MatrixBase)):
raise ValueError("scalar expected, use tensorproduct(...) for tensorial product")
other = sympify(other)
if isinstance(self, SparseNDimArray):
if other.is_zero:
return type(self)({}, self.shape)
return type(self)({k: other*v for (k, v) in self._sparse_array.items()}, self.shape)
result_list = [i*other for i in Flatten(self)]
return type(self)(result_list, self.shape)
def __rmul__(self, other):
from sympy.matrices.matrices import MatrixBase
from sympy.tensor.array import SparseNDimArray
from sympy.tensor.array.arrayop import Flatten
if isinstance(other, (Iterable, NDimArray, MatrixBase)):
raise ValueError("scalar expected, use tensorproduct(...) for tensorial product")
other = sympify(other)
if isinstance(self, SparseNDimArray):
if other.is_zero:
return type(self)({}, self.shape)
return type(self)({k: other*v for (k, v) in self._sparse_array.items()}, self.shape)
result_list = [other*i for i in Flatten(self)]
return type(self)(result_list, self.shape)
def __truediv__(self, other):
from sympy.matrices.matrices import MatrixBase
from sympy.tensor.array import SparseNDimArray
from sympy.tensor.array.arrayop import Flatten
if isinstance(other, (Iterable, NDimArray, MatrixBase)):
raise ValueError("scalar expected")
other = sympify(other)
if isinstance(self, SparseNDimArray) and other != S.Zero:
return type(self)({k: v/other for (k, v) in self._sparse_array.items()}, self.shape)
result_list = [i/other for i in Flatten(self)]
return type(self)(result_list, self.shape)
def __rtruediv__(self, other):
raise NotImplementedError('unsupported operation on NDimArray')
def __neg__(self):
from sympy.tensor.array import SparseNDimArray
from sympy.tensor.array.arrayop import Flatten
if isinstance(self, SparseNDimArray):
return type(self)({k: -v for (k, v) in self._sparse_array.items()}, self.shape)
result_list = [-i for i in Flatten(self)]
return type(self)(result_list, self.shape)
def __iter__(self):
def iterator():
if self._shape:
for i in range(self._shape[0]):
yield self[i]
else:
yield self[()]
return iterator()
def __eq__(self, other):
"""
NDimArray instances can be compared to each other.
Instances equal if they have same shape and data.
Examples
========
>>> from sympy import MutableDenseNDimArray
>>> a = MutableDenseNDimArray.zeros(2, 3)
>>> b = MutableDenseNDimArray.zeros(2, 3)
>>> a == b
True
>>> c = a.reshape(3, 2)
>>> c == b
False
>>> a[0,0] = 1
>>> b[0,0] = 2
>>> a == b
False
"""
from sympy.tensor.array import SparseNDimArray
if not isinstance(other, NDimArray):
return False
if not self.shape == other.shape:
return False
if isinstance(self, SparseNDimArray) and isinstance(other, SparseNDimArray):
return dict(self._sparse_array) == dict(other._sparse_array)
return list(self) == list(other)
def __ne__(self, other):
return not self == other
def _eval_transpose(self):
if self.rank() != 2:
raise ValueError("array rank not 2")
from .arrayop import permutedims
return permutedims(self, (1, 0))
def transpose(self):
return self._eval_transpose()
def _eval_conjugate(self):
from sympy.tensor.array.arrayop import Flatten
return self.func([i.conjugate() for i in Flatten(self)], self.shape)
def conjugate(self):
return self._eval_conjugate()
def _eval_adjoint(self):
return self.transpose().conjugate()
def adjoint(self):
return self._eval_adjoint()
def _slice_expand(self, s, dim):
if not isinstance(s, slice):
return (s,)
start, stop, step = s.indices(dim)
return [start + i*step for i in range((stop-start)//step)]
def _get_slice_data_for_array_access(self, index):
sl_factors = [self._slice_expand(i, dim) for (i, dim) in zip(index, self.shape)]
eindices = itertools.product(*sl_factors)
return sl_factors, eindices
def _get_slice_data_for_array_assignment(self, index, value):
if not isinstance(value, NDimArray):
value = type(self)(value)
sl_factors, eindices = self._get_slice_data_for_array_access(index)
slice_offsets = [min(i) if isinstance(i, list) else None for i in sl_factors]
# TODO: add checks for dimensions for `value`?
return value, eindices, slice_offsets
@classmethod
def _check_special_bounds(cls, flat_list, shape):
if shape == () and len(flat_list) != 1:
raise ValueError("arrays without shape need one scalar value")
if shape == (0,) and len(flat_list) > 0:
raise ValueError("if array shape is (0,) there cannot be elements")
def _check_index_for_getitem(self, index):
if isinstance(index, (SYMPY_INTS, Integer, slice)):
index = (index,)
if len(index) < self.rank():
index = tuple(index) + \
tuple(slice(None) for i in range(len(index), self.rank()))
if len(index) > self.rank():
raise ValueError('Dimension of index greater than rank of array')
return index
class ImmutableNDimArray(NDimArray, Basic):
_op_priority = 11.0
def __hash__(self):
return Basic.__hash__(self)
def as_immutable(self):
return self
def as_mutable(self):
raise NotImplementedError("abstract method")
|
1dbb0572e9ce7a417a0cd358a6d555a5ea53e7448fff3706c1c90fbca287bdec | import collections.abc
import operator
from collections import defaultdict, Counter
from functools import reduce
import itertools
from itertools import accumulate
from typing import Optional, List, Dict as tDict, Tuple as tTuple
import typing
from sympy.core.numbers import Integer
from sympy.core.relational import Equality
from sympy.functions.special.tensor_functions import KroneckerDelta
from sympy.core.basic import Basic
from sympy.core.containers import Tuple
from sympy.core.expr import Expr
from sympy.core.function import (Function, Lambda)
from sympy.core.mul import Mul
from sympy.core.singleton import S
from sympy.core.sorting import default_sort_key
from sympy.core.symbol import (Dummy, Symbol)
from sympy.matrices.common import MatrixCommon
from sympy.matrices.expressions.diagonal import diagonalize_vector
from sympy.matrices.expressions.matexpr import MatrixExpr
from sympy.matrices.expressions.special import ZeroMatrix
from sympy.tensor.array.arrayop import (permutedims, tensorcontraction, tensordiagonal, tensorproduct)
from sympy.tensor.array.dense_ndim_array import ImmutableDenseNDimArray
from sympy.tensor.array.ndim_array import NDimArray
from sympy.tensor.indexed import (Indexed, IndexedBase)
from sympy.matrices.expressions.matexpr import MatrixElement
from sympy.tensor.array.expressions.utils import _apply_recursively_over_nested_lists, _sort_contraction_indices, \
_get_mapping_from_subranks, _build_push_indices_up_func_transformation, _get_contraction_links, \
_build_push_indices_down_func_transformation
from sympy.combinatorics import Permutation
from sympy.combinatorics.permutations import _af_invert
from sympy.core.sympify import _sympify
class _ArrayExpr(Expr):
shape: tTuple[Expr, ...]
def __getitem__(self, item):
if not isinstance(item, collections.abc.Iterable):
item = (item,)
ArrayElement._check_shape(self, item)
return self._get(item)
def _get(self, item):
return _get_array_element_or_slice(self, item)
class ArraySymbol(_ArrayExpr):
"""
Symbol representing an array expression
"""
def __new__(cls, symbol, shape: typing.Iterable) -> "ArraySymbol":
if isinstance(symbol, str):
symbol = Symbol(symbol)
# symbol = _sympify(symbol)
shape = Tuple(*map(_sympify, shape))
obj = Expr.__new__(cls, symbol, shape)
return obj
@property
def name(self):
return self._args[0]
@property
def shape(self):
return self._args[1]
def as_explicit(self):
if not all(i.is_Integer for i in self.shape):
raise ValueError("cannot express explicit array with symbolic shape")
data = [self[i] for i in itertools.product(*[range(j) for j in self.shape])]
return ImmutableDenseNDimArray(data).reshape(*self.shape)
class ArrayElement(Expr):
"""
An element of an array.
"""
_diff_wrt = True
is_symbol = True
is_commutative = True
def __new__(cls, name, indices):
if isinstance(name, str):
name = Symbol(name)
name = _sympify(name)
if not isinstance(indices, collections.abc.Iterable):
indices = (indices,)
indices = _sympify(tuple(indices))
cls._check_shape(name, indices)
obj = Expr.__new__(cls, name, indices)
return obj
@classmethod
def _check_shape(cls, name, indices):
indices = tuple(indices)
if hasattr(name, "shape"):
index_error = IndexError("number of indices does not match shape of the array")
if len(indices) != len(name.shape):
raise index_error
if any((i >= s) == True for i, s in zip(indices, name.shape)):
raise ValueError("shape is out of bounds")
if any((i < 0) == True for i in indices):
raise ValueError("shape contains negative values")
@property
def name(self):
return self._args[0]
@property
def indices(self):
return self._args[1]
def _eval_derivative(self, s):
if not isinstance(s, ArrayElement):
return S.Zero
if s == self:
return S.One
if s.name != self.name:
return S.Zero
return Mul.fromiter(KroneckerDelta(i, j) for i, j in zip(self.indices, s.indices))
class ZeroArray(_ArrayExpr):
"""
Symbolic array of zeros. Equivalent to ``ZeroMatrix`` for matrices.
"""
def __new__(cls, *shape):
if len(shape) == 0:
return S.Zero
shape = map(_sympify, shape)
obj = Expr.__new__(cls, *shape)
return obj
@property
def shape(self):
return self._args
def as_explicit(self):
if not all(i.is_Integer for i in self.shape):
raise ValueError("Cannot return explicit form for symbolic shape.")
return ImmutableDenseNDimArray.zeros(*self.shape)
def _get(self, item):
return S.Zero
class OneArray(_ArrayExpr):
"""
Symbolic array of ones.
"""
def __new__(cls, *shape):
if len(shape) == 0:
return S.One
shape = map(_sympify, shape)
obj = Expr.__new__(cls, *shape)
return obj
@property
def shape(self):
return self._args
def as_explicit(self):
if not all(i.is_Integer for i in self.shape):
raise ValueError("Cannot return explicit form for symbolic shape.")
return ImmutableDenseNDimArray([S.One for i in range(reduce(operator.mul, self.shape))]).reshape(*self.shape)
def _get(self, item):
return S.One
class _CodegenArrayAbstract(Basic):
@property
def subranks(self):
"""
Returns the ranks of the objects in the uppermost tensor product inside
the current object. In case no tensor products are contained, return
the atomic ranks.
Examples
========
>>> from sympy.tensor.array import tensorproduct, tensorcontraction
>>> from sympy import MatrixSymbol
>>> M = MatrixSymbol("M", 3, 3)
>>> N = MatrixSymbol("N", 3, 3)
>>> P = MatrixSymbol("P", 3, 3)
Important: do not confuse the rank of the matrix with the rank of an array.
>>> tp = tensorproduct(M, N, P)
>>> tp.subranks
[2, 2, 2]
>>> co = tensorcontraction(tp, (1, 2), (3, 4))
>>> co.subranks
[2, 2, 2]
"""
return self._subranks[:]
def subrank(self):
"""
The sum of ``subranks``.
"""
return sum(self.subranks)
@property
def shape(self):
return self._shape
def doit(self, **hints):
deep = hints.get("deep", True)
if deep:
return self.func(*[arg.doit(**hints) for arg in self.args])._canonicalize()
else:
return self._canonicalize()
class ArrayTensorProduct(_CodegenArrayAbstract):
r"""
Class to represent the tensor product of array-like objects.
"""
def __new__(cls, *args, **kwargs):
args = [_sympify(arg) for arg in args]
canonicalize = kwargs.pop("canonicalize", False)
ranks = [get_rank(arg) for arg in args]
obj = Basic.__new__(cls, *args)
obj._subranks = ranks
shapes = [get_shape(i) for i in args]
if any(i is None for i in shapes):
obj._shape = None
else:
obj._shape = tuple(j for i in shapes for j in i)
if canonicalize:
return obj._canonicalize()
return obj
def _canonicalize(self):
args = self.args
args = self._flatten(args)
ranks = [get_rank(arg) for arg in args]
# Check if there are nested permutation and lift them up:
permutation_cycles = []
for i, arg in enumerate(args):
if not isinstance(arg, PermuteDims):
continue
permutation_cycles.extend([[k + sum(ranks[:i]) for k in j] for j in arg.permutation.cyclic_form])
args[i] = arg.expr
if permutation_cycles:
return _permute_dims(_array_tensor_product(*args), Permutation(sum(ranks)-1)*Permutation(permutation_cycles))
if len(args) == 1:
return args[0]
# If any object is a ZeroArray, return a ZeroArray:
if any(isinstance(arg, (ZeroArray, ZeroMatrix)) for arg in args):
shapes = reduce(operator.add, [get_shape(i) for i in args], ())
return ZeroArray(*shapes)
# If there are contraction objects inside, transform the whole
# expression into `ArrayContraction`:
contractions = {i: arg for i, arg in enumerate(args) if isinstance(arg, ArrayContraction)}
if contractions:
ranks = [_get_subrank(arg) if isinstance(arg, ArrayContraction) else get_rank(arg) for arg in args]
cumulative_ranks = list(accumulate([0] + ranks))[:-1]
tp = _array_tensor_product(*[arg.expr if isinstance(arg, ArrayContraction) else arg for arg in args])
contraction_indices = [tuple(cumulative_ranks[i] + k for k in j) for i, arg in contractions.items() for j in arg.contraction_indices]
return _array_contraction(tp, *contraction_indices)
diagonals = {i: arg for i, arg in enumerate(args) if isinstance(arg, ArrayDiagonal)}
if diagonals:
inverse_permutation = []
last_perm = []
ranks = [get_rank(arg) for arg in args]
cumulative_ranks = list(accumulate([0] + ranks))[:-1]
for i, arg in enumerate(args):
if isinstance(arg, ArrayDiagonal):
i1 = get_rank(arg) - len(arg.diagonal_indices)
i2 = len(arg.diagonal_indices)
inverse_permutation.extend([cumulative_ranks[i] + j for j in range(i1)])
last_perm.extend([cumulative_ranks[i] + j for j in range(i1, i1 + i2)])
else:
inverse_permutation.extend([cumulative_ranks[i] + j for j in range(get_rank(arg))])
inverse_permutation.extend(last_perm)
tp = _array_tensor_product(*[arg.expr if isinstance(arg, ArrayDiagonal) else arg for arg in args])
ranks2 = [_get_subrank(arg) if isinstance(arg, ArrayDiagonal) else get_rank(arg) for arg in args]
cumulative_ranks2 = list(accumulate([0] + ranks2))[:-1]
diagonal_indices = [tuple(cumulative_ranks2[i] + k for k in j) for i, arg in diagonals.items() for j in arg.diagonal_indices]
return _permute_dims(_array_diagonal(tp, *diagonal_indices), _af_invert(inverse_permutation))
return self.func(*args, canonicalize=False)
@classmethod
def _flatten(cls, args):
args = [i for arg in args for i in (arg.args if isinstance(arg, cls) else [arg])]
return args
def as_explicit(self):
return tensorproduct(*[arg.as_explicit() if hasattr(arg, "as_explicit") else arg for arg in self.args])
class ArrayAdd(_CodegenArrayAbstract):
r"""
Class for elementwise array additions.
"""
def __new__(cls, *args, **kwargs):
args = [_sympify(arg) for arg in args]
ranks = [get_rank(arg) for arg in args]
ranks = list(set(ranks))
if len(ranks) != 1:
raise ValueError("summing arrays of different ranks")
shapes = [arg.shape for arg in args]
if len({i for i in shapes if i is not None}) > 1:
raise ValueError("mismatching shapes in addition")
canonicalize = kwargs.pop("canonicalize", False)
obj = Basic.__new__(cls, *args)
obj._subranks = ranks
if any(i is None for i in shapes):
obj._shape = None
else:
obj._shape = shapes[0]
if canonicalize:
return obj._canonicalize()
return obj
def _canonicalize(self):
args = self.args
# Flatten:
args = self._flatten_args(args)
shapes = [get_shape(arg) for arg in args]
args = [arg for arg in args if not isinstance(arg, (ZeroArray, ZeroMatrix))]
if len(args) == 0:
if any(i for i in shapes if i is None):
raise NotImplementedError("cannot handle addition of ZeroMatrix/ZeroArray and undefined shape object")
return ZeroArray(*shapes[0])
elif len(args) == 1:
return args[0]
return self.func(*args, canonicalize=False)
@classmethod
def _flatten_args(cls, args):
new_args = []
for arg in args:
if isinstance(arg, ArrayAdd):
new_args.extend(arg.args)
else:
new_args.append(arg)
return new_args
def as_explicit(self):
return reduce(
operator.add,
[arg.as_explicit() if hasattr(arg, "as_explicit") else arg for arg in self.args])
class PermuteDims(_CodegenArrayAbstract):
r"""
Class to represent permutation of axes of arrays.
Examples
========
>>> from sympy.tensor.array import permutedims
>>> from sympy import MatrixSymbol
>>> M = MatrixSymbol("M", 3, 3)
>>> cg = permutedims(M, [1, 0])
The object ``cg`` represents the transposition of ``M``, as the permutation
``[1, 0]`` will act on its indices by switching them:
`M_{ij} \Rightarrow M_{ji}`
This is evident when transforming back to matrix form:
>>> from sympy.tensor.array.expressions.conv_array_to_matrix import convert_array_to_matrix
>>> convert_array_to_matrix(cg)
M.T
>>> N = MatrixSymbol("N", 3, 2)
>>> cg = permutedims(N, [1, 0])
>>> cg.shape
(2, 3)
There are optional parameters that can be used as alternative to the permutation:
>>> from sympy.tensor.array.expressions import ArraySymbol, PermuteDims
>>> M = ArraySymbol("M", (1, 2, 3, 4, 5))
>>> expr = PermuteDims(M, index_order_old="ijklm", index_order_new="kijml")
>>> expr
PermuteDims(M, (0 2 1)(3 4))
>>> expr.shape
(3, 1, 2, 5, 4)
Permutations of tensor products are simplified in order to achieve a
standard form:
>>> from sympy.tensor.array import tensorproduct
>>> M = MatrixSymbol("M", 4, 5)
>>> tp = tensorproduct(M, N)
>>> tp.shape
(4, 5, 3, 2)
>>> perm1 = permutedims(tp, [2, 3, 1, 0])
The args ``(M, N)`` have been sorted and the permutation has been
simplified, the expression is equivalent:
>>> perm1.expr.args
(N, M)
>>> perm1.shape
(3, 2, 5, 4)
>>> perm1.permutation
(2 3)
The permutation in its array form has been simplified from
``[2, 3, 1, 0]`` to ``[0, 1, 3, 2]``, as the arguments of the tensor
product `M` and `N` have been switched:
>>> perm1.permutation.array_form
[0, 1, 3, 2]
We can nest a second permutation:
>>> perm2 = permutedims(perm1, [1, 0, 2, 3])
>>> perm2.shape
(2, 3, 5, 4)
>>> perm2.permutation.array_form
[1, 0, 3, 2]
"""
def __new__(cls, expr, permutation=None, index_order_old=None, index_order_new=None, **kwargs):
from sympy.combinatorics import Permutation
expr = _sympify(expr)
expr_rank = get_rank(expr)
permutation = cls._get_permutation_from_arguments(permutation, index_order_old, index_order_new, expr_rank)
permutation = Permutation(permutation)
permutation_size = permutation.size
if permutation_size != expr_rank:
raise ValueError("Permutation size must be the length of the shape of expr")
canonicalize = kwargs.pop("canonicalize", False)
obj = Basic.__new__(cls, expr, permutation)
obj._subranks = [get_rank(expr)]
shape = get_shape(expr)
if shape is None:
obj._shape = None
else:
obj._shape = tuple(shape[permutation(i)] for i in range(len(shape)))
if canonicalize:
return obj._canonicalize()
return obj
def _canonicalize(self):
expr = self.expr
permutation = self.permutation
if isinstance(expr, PermuteDims):
subexpr = expr.expr
subperm = expr.permutation
permutation = permutation * subperm
expr = subexpr
if isinstance(expr, ArrayContraction):
expr, permutation = self._PermuteDims_denestarg_ArrayContraction(expr, permutation)
if isinstance(expr, ArrayTensorProduct):
expr, permutation = self._PermuteDims_denestarg_ArrayTensorProduct(expr, permutation)
if isinstance(expr, (ZeroArray, ZeroMatrix)):
return ZeroArray(*[expr.shape[i] for i in permutation.array_form])
plist = permutation.array_form
if plist == sorted(plist):
return expr
return self.func(expr, permutation, canonicalize=False)
@property
def expr(self):
return self.args[0]
@property
def permutation(self):
return self.args[1]
@classmethod
def _PermuteDims_denestarg_ArrayTensorProduct(cls, expr, permutation):
# Get the permutation in its image-form:
perm_image_form = _af_invert(permutation.array_form)
args = list(expr.args)
# Starting index global position for every arg:
cumul = list(accumulate([0] + expr.subranks))
# Split `perm_image_form` into a list of list corresponding to the indices
# of every argument:
perm_image_form_in_components = [perm_image_form[cumul[i]:cumul[i+1]] for i in range(len(args))]
# Create an index, target-position-key array:
ps = [(i, sorted(comp)) for i, comp in enumerate(perm_image_form_in_components)]
# Sort the array according to the target-position-key:
# In this way, we define a canonical way to sort the arguments according
# to the permutation.
ps.sort(key=lambda x: x[1])
# Read the inverse-permutation (i.e. image-form) of the args:
perm_args_image_form = [i[0] for i in ps]
# Apply the args-permutation to the `args`:
args_sorted = [args[i] for i in perm_args_image_form]
# Apply the args-permutation to the array-form of the permutation of the axes (of `expr`):
perm_image_form_sorted_args = [perm_image_form_in_components[i] for i in perm_args_image_form]
new_permutation = Permutation(_af_invert([j for i in perm_image_form_sorted_args for j in i]))
return _array_tensor_product(*args_sorted), new_permutation
@classmethod
def _PermuteDims_denestarg_ArrayContraction(cls, expr, permutation):
if not isinstance(expr, ArrayContraction):
return expr, permutation
if not isinstance(expr.expr, ArrayTensorProduct):
return expr, permutation
args = expr.expr.args
subranks = [get_rank(arg) for arg in expr.expr.args]
contraction_indices = expr.contraction_indices
contraction_indices_flat = [j for i in contraction_indices for j in i]
cumul = list(accumulate([0] + subranks))
# Spread the permutation in its array form across the args in the corresponding
# tensor-product arguments with free indices:
permutation_array_blocks_up = []
image_form = _af_invert(permutation.array_form)
counter = 0
for i, e in enumerate(subranks):
current = []
for j in range(cumul[i], cumul[i+1]):
if j in contraction_indices_flat:
continue
current.append(image_form[counter])
counter += 1
permutation_array_blocks_up.append(current)
# Get the map of axis repositioning for every argument of tensor-product:
index_blocks = [[j for j in range(cumul[i], cumul[i+1])] for i, e in enumerate(expr.subranks)]
index_blocks_up = expr._push_indices_up(expr.contraction_indices, index_blocks)
inverse_permutation = permutation**(-1)
index_blocks_up_permuted = [[inverse_permutation(j) for j in i if j is not None] for i in index_blocks_up]
# Sorting key is a list of tuple, first element is the index of `args`, second element of
# the tuple is the sorting key to sort `args` of the tensor product:
sorting_keys = list(enumerate(index_blocks_up_permuted))
sorting_keys.sort(key=lambda x: x[1])
# Now we can get the permutation acting on the args in its image-form:
new_perm_image_form = [i[0] for i in sorting_keys]
# Apply the args-level permutation to various elements:
new_index_blocks = [index_blocks[i] for i in new_perm_image_form]
new_index_perm_array_form = _af_invert([j for i in new_index_blocks for j in i])
new_args = [args[i] for i in new_perm_image_form]
new_contraction_indices = [tuple(new_index_perm_array_form[j] for j in i) for i in contraction_indices]
new_expr = _array_contraction(_array_tensor_product(*new_args), *new_contraction_indices)
new_permutation = Permutation(_af_invert([j for i in [permutation_array_blocks_up[k] for k in new_perm_image_form] for j in i]))
return new_expr, new_permutation
@classmethod
def _check_permutation_mapping(cls, expr, permutation):
subranks = expr.subranks
index2arg = [i for i, arg in enumerate(expr.args) for j in range(expr.subranks[i])]
permuted_indices = [permutation(i) for i in range(expr.subrank())]
new_args = list(expr.args)
arg_candidate_index = index2arg[permuted_indices[0]]
current_indices = []
new_permutation = []
inserted_arg_cand_indices = set([])
for i, idx in enumerate(permuted_indices):
if index2arg[idx] != arg_candidate_index:
new_permutation.extend(current_indices)
current_indices = []
arg_candidate_index = index2arg[idx]
current_indices.append(idx)
arg_candidate_rank = subranks[arg_candidate_index]
if len(current_indices) == arg_candidate_rank:
new_permutation.extend(sorted(current_indices))
local_current_indices = [j - min(current_indices) for j in current_indices]
i1 = index2arg[i]
new_args[i1] = _permute_dims(new_args[i1], Permutation(local_current_indices))
inserted_arg_cand_indices.add(arg_candidate_index)
current_indices = []
new_permutation.extend(current_indices)
# TODO: swap args positions in order to simplify the expression:
# TODO: this should be in a function
args_positions = list(range(len(new_args)))
# Get possible shifts:
maps = {}
cumulative_subranks = [0] + list(accumulate(subranks))
for i in range(len(subranks)):
s = set([index2arg[new_permutation[j]] for j in range(cumulative_subranks[i], cumulative_subranks[i+1])])
if len(s) != 1:
continue
elem = next(iter(s))
if i != elem:
maps[i] = elem
# Find cycles in the map:
lines = []
current_line = []
while maps:
if len(current_line) == 0:
k, v = maps.popitem()
current_line.append(k)
else:
k = current_line[-1]
if k not in maps:
current_line = []
continue
v = maps.pop(k)
if v in current_line:
lines.append(current_line)
current_line = []
continue
current_line.append(v)
for line in lines:
for i, e in enumerate(line):
args_positions[line[(i + 1) % len(line)]] = e
# TODO: function in order to permute the args:
permutation_blocks = [[new_permutation[cumulative_subranks[i] + j] for j in range(e)] for i, e in enumerate(subranks)]
new_args = [new_args[i] for i in args_positions]
new_permutation_blocks = [permutation_blocks[i] for i in args_positions]
new_permutation2 = [j for i in new_permutation_blocks for j in i]
return _array_tensor_product(*new_args), Permutation(new_permutation2) # **(-1)
@classmethod
def _check_if_there_are_closed_cycles(cls, expr, permutation):
args = list(expr.args)
subranks = expr.subranks
cyclic_form = permutation.cyclic_form
cumulative_subranks = [0] + list(accumulate(subranks))
cyclic_min = [min(i) for i in cyclic_form]
cyclic_max = [max(i) for i in cyclic_form]
cyclic_keep = []
for i, cycle in enumerate(cyclic_form):
flag = True
for j in range(len(cumulative_subranks) - 1):
if cyclic_min[i] >= cumulative_subranks[j] and cyclic_max[i] < cumulative_subranks[j+1]:
# Found a sinkable cycle.
args[j] = _permute_dims(args[j], Permutation([[k - cumulative_subranks[j] for k in cyclic_form[i]]]))
flag = False
break
if flag:
cyclic_keep.append(cyclic_form[i])
return _array_tensor_product(*args), Permutation(cyclic_keep, size=permutation.size)
def nest_permutation(self):
r"""
DEPRECATED.
"""
ret = self._nest_permutation(self.expr, self.permutation)
if ret is None:
return self
return ret
@classmethod
def _nest_permutation(cls, expr, permutation):
if isinstance(expr, ArrayTensorProduct):
return _permute_dims(*cls._check_if_there_are_closed_cycles(expr, permutation))
elif isinstance(expr, ArrayContraction):
# Invert tree hierarchy: put the contraction above.
cycles = permutation.cyclic_form
newcycles = ArrayContraction._convert_outer_indices_to_inner_indices(expr, *cycles)
newpermutation = Permutation(newcycles)
new_contr_indices = [tuple(newpermutation(j) for j in i) for i in expr.contraction_indices]
return _array_contraction(PermuteDims(expr.expr, newpermutation), *new_contr_indices)
elif isinstance(expr, ArrayAdd):
return _array_add(*[PermuteDims(arg, permutation) for arg in expr.args])
return None
def as_explicit(self):
expr = self.expr
if hasattr(expr, "as_explicit"):
expr = expr.as_explicit()
return permutedims(expr, self.permutation)
@classmethod
def _get_permutation_from_arguments(cls, permutation, index_order_old, index_order_new, dim):
if permutation is None:
if index_order_new is None or index_order_old is None:
raise ValueError("Permutation not defined")
return PermuteDims._get_permutation_from_index_orders(index_order_old, index_order_new, dim)
else:
if index_order_new is not None:
raise ValueError("index_order_new cannot be defined with permutation")
if index_order_old is not None:
raise ValueError("index_order_old cannot be defined with permutation")
return permutation
@classmethod
def _get_permutation_from_index_orders(cls, index_order_old, index_order_new, dim):
if len(set(index_order_new)) != dim:
raise ValueError("wrong number of indices in index_order_new")
if len(set(index_order_old)) != dim:
raise ValueError("wrong number of indices in index_order_old")
if len(set.symmetric_difference(set(index_order_new), set(index_order_old))) > 0:
raise ValueError("index_order_new and index_order_old must have the same indices")
permutation = [index_order_old.index(i) for i in index_order_new]
return permutation
class ArrayDiagonal(_CodegenArrayAbstract):
r"""
Class to represent the diagonal operator.
Explanation
===========
In a 2-dimensional array it returns the diagonal, this looks like the
operation:
`A_{ij} \rightarrow A_{ii}`
The diagonal over axes 1 and 2 (the second and third) of the tensor product
of two 2-dimensional arrays `A \otimes B` is
`\Big[ A_{ab} B_{cd} \Big]_{abcd} \rightarrow \Big[ A_{ai} B_{id} \Big]_{adi}`
In this last example the array expression has been reduced from
4-dimensional to 3-dimensional. Notice that no contraction has occurred,
rather there is a new index `i` for the diagonal, contraction would have
reduced the array to 2 dimensions.
Notice that the diagonalized out dimensions are added as new dimensions at
the end of the indices.
"""
def __new__(cls, expr, *diagonal_indices, **kwargs):
expr = _sympify(expr)
diagonal_indices = [Tuple(*sorted(i)) for i in diagonal_indices]
canonicalize = kwargs.get("canonicalize", False)
shape = get_shape(expr)
if shape is not None:
cls._validate(expr, *diagonal_indices, **kwargs)
# Get new shape:
positions, shape = cls._get_positions_shape(shape, diagonal_indices)
else:
positions = None
if len(diagonal_indices) == 0:
return expr
obj = Basic.__new__(cls, expr, *diagonal_indices)
obj._positions = positions
obj._subranks = _get_subranks(expr)
obj._shape = shape
if canonicalize:
return obj._canonicalize()
return obj
def _canonicalize(self):
expr = self.expr
diagonal_indices = self.diagonal_indices
trivial_diags = [i for i in diagonal_indices if len(i) == 1]
if len(trivial_diags) > 0:
trivial_pos = {e[0]: i for i, e in enumerate(diagonal_indices) if len(e) == 1}
diag_pos = {e: i for i, e in enumerate(diagonal_indices) if len(e) > 1}
diagonal_indices_short = [i for i in diagonal_indices if len(i) > 1]
rank1 = get_rank(self)
rank2 = len(diagonal_indices)
rank3 = rank1 - rank2
inv_permutation = []
counter1: int = 0
indices_down = ArrayDiagonal._push_indices_down(diagonal_indices_short, list(range(rank1)), get_rank(expr))
for i in indices_down:
if i in trivial_pos:
inv_permutation.append(rank3 + trivial_pos[i])
elif isinstance(i, (Integer, int)):
inv_permutation.append(counter1)
counter1 += 1
else:
inv_permutation.append(rank3 + diag_pos[i])
permutation = _af_invert(inv_permutation)
if len(diagonal_indices_short) > 0:
return _permute_dims(_array_diagonal(expr, *diagonal_indices_short), permutation)
else:
return _permute_dims(expr, permutation)
if isinstance(expr, ArrayAdd):
return self._ArrayDiagonal_denest_ArrayAdd(expr, *diagonal_indices)
if isinstance(expr, ArrayDiagonal):
return self._ArrayDiagonal_denest_ArrayDiagonal(expr, *diagonal_indices)
if isinstance(expr, PermuteDims):
return self._ArrayDiagonal_denest_PermuteDims(expr, *diagonal_indices)
if isinstance(expr, (ZeroArray, ZeroMatrix)):
positions, shape = self._get_positions_shape(expr.shape, diagonal_indices)
return ZeroArray(*shape)
return self.func(expr, *diagonal_indices, canonicalize=False)
@staticmethod
def _validate(expr, *diagonal_indices, **kwargs):
# Check that no diagonalization happens on indices with mismatched
# dimensions:
shape = get_shape(expr)
for i in diagonal_indices:
if any(j >= len(shape) for j in i):
raise ValueError("index is larger than expression shape")
if len({shape[j] for j in i}) != 1:
raise ValueError("diagonalizing indices of different dimensions")
if not kwargs.get("allow_trivial_diags", False) and len(i) <= 1:
raise ValueError("need at least two axes to diagonalize")
if len(set(i)) != len(i):
raise ValueError("axis index cannot be repeated")
@staticmethod
def _remove_trivial_dimensions(shape, *diagonal_indices):
return [tuple(j for j in i) for i in diagonal_indices if shape[i[0]] != 1]
@property
def expr(self):
return self.args[0]
@property
def diagonal_indices(self):
return self.args[1:]
@staticmethod
def _flatten(expr, *outer_diagonal_indices):
inner_diagonal_indices = expr.diagonal_indices
all_inner = [j for i in inner_diagonal_indices for j in i]
all_inner.sort()
# TODO: add API for total rank and cumulative rank:
total_rank = _get_subrank(expr)
inner_rank = len(all_inner)
outer_rank = total_rank - inner_rank
shifts = [0 for i in range(outer_rank)]
counter = 0
pointer = 0
for i in range(outer_rank):
while pointer < inner_rank and counter >= all_inner[pointer]:
counter += 1
pointer += 1
shifts[i] += pointer
counter += 1
outer_diagonal_indices = tuple(tuple(shifts[j] + j for j in i) for i in outer_diagonal_indices)
diagonal_indices = inner_diagonal_indices + outer_diagonal_indices
return _array_diagonal(expr.expr, *diagonal_indices)
@classmethod
def _ArrayDiagonal_denest_ArrayAdd(cls, expr, *diagonal_indices):
return _array_add(*[_array_diagonal(arg, *diagonal_indices) for arg in expr.args])
@classmethod
def _ArrayDiagonal_denest_ArrayDiagonal(cls, expr, *diagonal_indices):
return cls._flatten(expr, *diagonal_indices)
@classmethod
def _ArrayDiagonal_denest_PermuteDims(cls, expr: PermuteDims, *diagonal_indices):
back_diagonal_indices = [[expr.permutation(j) for j in i] for i in diagonal_indices]
nondiag = [i for i in range(get_rank(expr)) if not any(i in j for j in diagonal_indices)]
back_nondiag = [expr.permutation(i) for i in nondiag]
remap = {e: i for i, e in enumerate(sorted(back_nondiag))}
new_permutation1 = [remap[i] for i in back_nondiag]
shift = len(new_permutation1)
diag_block_perm = [i + shift for i in range(len(back_diagonal_indices))]
new_permutation = new_permutation1 + diag_block_perm
return _permute_dims(
_array_diagonal(
expr.expr,
*back_diagonal_indices
),
new_permutation
)
def _push_indices_down_nonstatic(self, indices):
transform = lambda x: self._positions[x] if x < len(self._positions) else None
return _apply_recursively_over_nested_lists(transform, indices)
def _push_indices_up_nonstatic(self, indices):
def transform(x):
for i, e in enumerate(self._positions):
if (isinstance(e, int) and x == e) or (isinstance(e, tuple) and x in e):
return i
return _apply_recursively_over_nested_lists(transform, indices)
@classmethod
def _push_indices_down(cls, diagonal_indices, indices, rank):
positions, shape = cls._get_positions_shape(range(rank), diagonal_indices)
transform = lambda x: positions[x] if x < len(positions) else None
return _apply_recursively_over_nested_lists(transform, indices)
@classmethod
def _push_indices_up(cls, diagonal_indices, indices, rank):
positions, shape = cls._get_positions_shape(range(rank), diagonal_indices)
def transform(x):
for i, e in enumerate(positions):
if (isinstance(e, int) and x == e) or (isinstance(e, (tuple, Tuple)) and (x in e)):
return i
return _apply_recursively_over_nested_lists(transform, indices)
@classmethod
def _get_positions_shape(cls, shape, diagonal_indices):
data1 = tuple((i, shp) for i, shp in enumerate(shape) if not any(i in j for j in diagonal_indices))
pos1, shp1 = zip(*data1) if data1 else ((), ())
data2 = tuple((i, shape[i[0]]) for i in diagonal_indices)
pos2, shp2 = zip(*data2) if data2 else ((), ())
positions = pos1 + pos2
shape = shp1 + shp2
return positions, shape
def as_explicit(self):
expr = self.expr
if hasattr(expr, "as_explicit"):
expr = expr.as_explicit()
return tensordiagonal(expr, *self.diagonal_indices)
class ArrayElementwiseApplyFunc(_CodegenArrayAbstract):
def __new__(cls, function, element):
if not isinstance(function, Lambda):
d = Dummy('d')
function = Lambda(d, function(d))
obj = _CodegenArrayAbstract.__new__(cls, function, element)
obj._subranks = _get_subranks(element)
return obj
@property
def function(self):
return self.args[0]
@property
def expr(self):
return self.args[1]
@property
def shape(self):
return self.expr.shape
def _get_function_fdiff(self):
d = Dummy("d")
function = self.function(d)
fdiff = function.diff(d)
if isinstance(fdiff, Function):
fdiff = type(fdiff)
else:
fdiff = Lambda(d, fdiff)
return fdiff
def as_explicit(self):
expr = self.expr
if hasattr(expr, "as_explicit"):
expr = expr.as_explicit()
return expr.applyfunc(self.function)
class ArrayContraction(_CodegenArrayAbstract):
r"""
This class is meant to represent contractions of arrays in a form easily
processable by the code printers.
"""
def __new__(cls, expr, *contraction_indices, **kwargs):
contraction_indices = _sort_contraction_indices(contraction_indices)
expr = _sympify(expr)
canonicalize = kwargs.get("canonicalize", False)
obj = Basic.__new__(cls, expr, *contraction_indices)
obj._subranks = _get_subranks(expr)
obj._mapping = _get_mapping_from_subranks(obj._subranks)
free_indices_to_position = {i: i for i in range(sum(obj._subranks)) if all(i not in cind for cind in contraction_indices)}
obj._free_indices_to_position = free_indices_to_position
shape = get_shape(expr)
cls._validate(expr, *contraction_indices)
if shape:
shape = tuple(shp for i, shp in enumerate(shape) if not any(i in j for j in contraction_indices))
obj._shape = shape
if canonicalize:
return obj._canonicalize()
return obj
def _canonicalize(self):
expr = self.expr
contraction_indices = self.contraction_indices
if len(contraction_indices) == 0:
return expr
if isinstance(expr, ArrayContraction):
return self._ArrayContraction_denest_ArrayContraction(expr, *contraction_indices)
if isinstance(expr, (ZeroArray, ZeroMatrix)):
return self._ArrayContraction_denest_ZeroArray(expr, *contraction_indices)
if isinstance(expr, PermuteDims):
return self._ArrayContraction_denest_PermuteDims(expr, *contraction_indices)
if isinstance(expr, ArrayTensorProduct):
expr, contraction_indices = self._sort_fully_contracted_args(expr, contraction_indices)
expr, contraction_indices = self._lower_contraction_to_addends(expr, contraction_indices)
if len(contraction_indices) == 0:
return expr
if isinstance(expr, ArrayDiagonal):
return self._ArrayContraction_denest_ArrayDiagonal(expr, *contraction_indices)
if isinstance(expr, ArrayAdd):
return self._ArrayContraction_denest_ArrayAdd(expr, *contraction_indices)
# Check single index contractions on 1-dimensional axes:
contraction_indices = [i for i in contraction_indices if len(i) > 1 or get_shape(expr)[i[0]] != 1]
if len(contraction_indices) == 0:
return expr
return self.func(expr, *contraction_indices, canonicalize=False)
def __mul__(self, other):
if other == 1:
return self
else:
raise NotImplementedError("Product of N-dim arrays is not uniquely defined. Use another method.")
def __rmul__(self, other):
if other == 1:
return self
else:
raise NotImplementedError("Product of N-dim arrays is not uniquely defined. Use another method.")
@staticmethod
def _validate(expr, *contraction_indices):
shape = get_shape(expr)
if shape is None:
return
# Check that no contraction happens when the shape is mismatched:
for i in contraction_indices:
if len({shape[j] for j in i if shape[j] != -1}) != 1:
raise ValueError("contracting indices of different dimensions")
@classmethod
def _push_indices_down(cls, contraction_indices, indices):
flattened_contraction_indices = [j for i in contraction_indices for j in i]
flattened_contraction_indices.sort()
transform = _build_push_indices_down_func_transformation(flattened_contraction_indices)
return _apply_recursively_over_nested_lists(transform, indices)
@classmethod
def _push_indices_up(cls, contraction_indices, indices):
flattened_contraction_indices = [j for i in contraction_indices for j in i]
flattened_contraction_indices.sort()
transform = _build_push_indices_up_func_transformation(flattened_contraction_indices)
return _apply_recursively_over_nested_lists(transform, indices)
@classmethod
def _lower_contraction_to_addends(cls, expr, contraction_indices):
if isinstance(expr, ArrayAdd):
raise NotImplementedError()
if not isinstance(expr, ArrayTensorProduct):
return expr, contraction_indices
subranks = expr.subranks
cumranks = list(accumulate([0] + subranks))
contraction_indices_remaining = []
contraction_indices_args = [[] for i in expr.args]
backshift = set([])
for i, contraction_group in enumerate(contraction_indices):
for j in range(len(expr.args)):
if not isinstance(expr.args[j], ArrayAdd):
continue
if all(cumranks[j] <= k < cumranks[j+1] for k in contraction_group):
contraction_indices_args[j].append([k - cumranks[j] for k in contraction_group])
backshift.update(contraction_group)
break
else:
contraction_indices_remaining.append(contraction_group)
if len(contraction_indices_remaining) == len(contraction_indices):
return expr, contraction_indices
total_rank = get_rank(expr)
shifts = list(accumulate([1 if i in backshift else 0 for i in range(total_rank)]))
contraction_indices_remaining = [Tuple.fromiter(j - shifts[j] for j in i) for i in contraction_indices_remaining]
ret = _array_tensor_product(*[
_array_contraction(arg, *contr) for arg, contr in zip(expr.args, contraction_indices_args)
])
return ret, contraction_indices_remaining
def split_multiple_contractions(self):
"""
Recognize multiple contractions and attempt at rewriting them as paired-contractions.
This allows some contractions involving more than two indices to be
rewritten as multiple contractions involving two indices, thus allowing
the expression to be rewritten as a matrix multiplication line.
Examples:
* `A_ij b_j0 C_jk` ===> `A*DiagMatrix(b)*C`
Care for:
- matrix being diagonalized (i.e. `A_ii`)
- vectors being diagonalized (i.e. `a_i0`)
Multiple contractions can be split into matrix multiplications if
not more than two arguments are non-diagonals or non-vectors.
Vectors get diagonalized while diagonal matrices remain diagonal.
The non-diagonal matrices can be at the beginning or at the end
of the final matrix multiplication line.
"""
editor = _EditArrayContraction(self)
contraction_indices = self.contraction_indices
onearray_insert = []
for indl, links in enumerate(contraction_indices):
if len(links) <= 2:
continue
# Check multiple contractions:
#
# Examples:
#
# * `A_ij b_j0 C_jk` ===> `A*DiagMatrix(b)*C \otimes OneArray(1)` with permutation (1 2)
#
# Care for:
# - matrix being diagonalized (i.e. `A_ii`)
# - vectors being diagonalized (i.e. `a_i0`)
# Multiple contractions can be split into matrix multiplications if
# not more than three arguments are non-diagonals or non-vectors.
#
# Vectors get diagonalized while diagonal matrices remain diagonal.
# The non-diagonal matrices can be at the beginning or at the end
# of the final matrix multiplication line.
positions = editor.get_mapping_for_index(indl)
# Also consider the case of diagonal matrices being contracted:
current_dimension = self.expr.shape[links[0]]
not_vectors: tTuple[_ArgE, int] = []
vectors: tTuple[_ArgE, int] = []
for arg_ind, rel_ind in positions:
arg = editor.args_with_ind[arg_ind]
mat = arg.element
abs_arg_start, abs_arg_end = editor.get_absolute_range(arg)
other_arg_pos = 1-rel_ind
other_arg_abs = abs_arg_start + other_arg_pos
if ((1 not in mat.shape) or
((current_dimension == 1) is True and mat.shape != (1, 1)) or
any(other_arg_abs in l for li, l in enumerate(contraction_indices) if li != indl)
):
not_vectors.append((arg, rel_ind))
else:
vectors.append((arg, rel_ind))
if len(not_vectors) > 2:
# If more than two arguments in the multiple contraction are
# non-vectors and non-diagonal matrices, we cannot find a way
# to split this contraction into a matrix multiplication line:
continue
# Three cases to handle:
# - zero non-vectors
# - one non-vector
# - two non-vectors
for v, rel_ind in vectors:
v.element = diagonalize_vector(v.element)
vectors_to_loop = not_vectors[:1] + vectors + not_vectors[1:]
first_not_vector, rel_ind = vectors_to_loop[0]
new_index = first_not_vector.indices[rel_ind]
for v, rel_ind in vectors_to_loop[1:-1]:
v.indices[rel_ind] = new_index
new_index = editor.get_new_contraction_index()
assert v.indices.index(None) == 1 - rel_ind
v.indices[v.indices.index(None)] = new_index
onearray_insert.append(v)
last_vec, rel_ind = vectors_to_loop[-1]
last_vec.indices[rel_ind] = new_index
for v in onearray_insert:
editor.insert_after(v, _ArgE(OneArray(1), [None]))
return editor.to_array_contraction()
def flatten_contraction_of_diagonal(self):
if not isinstance(self.expr, ArrayDiagonal):
return self
contraction_down = self.expr._push_indices_down(self.expr.diagonal_indices, self.contraction_indices)
new_contraction_indices = []
diagonal_indices = self.expr.diagonal_indices[:]
for i in contraction_down:
contraction_group = list(i)
for j in i:
diagonal_with = [k for k in diagonal_indices if j in k]
contraction_group.extend([l for k in diagonal_with for l in k])
diagonal_indices = [k for k in diagonal_indices if k not in diagonal_with]
new_contraction_indices.append(sorted(set(contraction_group)))
new_contraction_indices = ArrayDiagonal._push_indices_up(diagonal_indices, new_contraction_indices)
return _array_contraction(
_array_diagonal(
self.expr.expr,
*diagonal_indices
),
*new_contraction_indices
)
@staticmethod
def _get_free_indices_to_position_map(free_indices, contraction_indices):
free_indices_to_position = {}
flattened_contraction_indices = [j for i in contraction_indices for j in i]
counter = 0
for ind in free_indices:
while counter in flattened_contraction_indices:
counter += 1
free_indices_to_position[ind] = counter
counter += 1
return free_indices_to_position
@staticmethod
def _get_index_shifts(expr):
"""
Get the mapping of indices at the positions before the contraction
occurs.
Examples
========
>>> from sympy.tensor.array import tensorproduct, tensorcontraction
>>> from sympy import MatrixSymbol
>>> M = MatrixSymbol("M", 3, 3)
>>> N = MatrixSymbol("N", 3, 3)
>>> cg = tensorcontraction(tensorproduct(M, N), [1, 2])
>>> cg._get_index_shifts(cg)
[0, 2]
Indeed, ``cg`` after the contraction has two dimensions, 0 and 1. They
need to be shifted by 0 and 2 to get the corresponding positions before
the contraction (that is, 0 and 3).
"""
inner_contraction_indices = expr.contraction_indices
all_inner = [j for i in inner_contraction_indices for j in i]
all_inner.sort()
# TODO: add API for total rank and cumulative rank:
total_rank = _get_subrank(expr)
inner_rank = len(all_inner)
outer_rank = total_rank - inner_rank
shifts = [0 for i in range(outer_rank)]
counter = 0
pointer = 0
for i in range(outer_rank):
while pointer < inner_rank and counter >= all_inner[pointer]:
counter += 1
pointer += 1
shifts[i] += pointer
counter += 1
return shifts
@staticmethod
def _convert_outer_indices_to_inner_indices(expr, *outer_contraction_indices):
shifts = ArrayContraction._get_index_shifts(expr)
outer_contraction_indices = tuple(tuple(shifts[j] + j for j in i) for i in outer_contraction_indices)
return outer_contraction_indices
@staticmethod
def _flatten(expr, *outer_contraction_indices):
inner_contraction_indices = expr.contraction_indices
outer_contraction_indices = ArrayContraction._convert_outer_indices_to_inner_indices(expr, *outer_contraction_indices)
contraction_indices = inner_contraction_indices + outer_contraction_indices
return _array_contraction(expr.expr, *contraction_indices)
@classmethod
def _ArrayContraction_denest_ArrayContraction(cls, expr, *contraction_indices):
return cls._flatten(expr, *contraction_indices)
@classmethod
def _ArrayContraction_denest_ZeroArray(cls, expr, *contraction_indices):
contraction_indices_flat = [j for i in contraction_indices for j in i]
shape = [e for i, e in enumerate(expr.shape) if i not in contraction_indices_flat]
return ZeroArray(*shape)
@classmethod
def _ArrayContraction_denest_ArrayAdd(cls, expr, *contraction_indices):
return _array_add(*[_array_contraction(i, *contraction_indices) for i in expr.args])
@classmethod
def _ArrayContraction_denest_PermuteDims(cls, expr, *contraction_indices):
permutation = expr.permutation
plist = permutation.array_form
new_contraction_indices = [tuple(permutation(j) for j in i) for i in contraction_indices]
new_plist = [i for i in plist if not any(i in j for j in new_contraction_indices)]
new_plist = cls._push_indices_up(new_contraction_indices, new_plist)
return _permute_dims(
_array_contraction(expr.expr, *new_contraction_indices),
Permutation(new_plist)
)
@classmethod
def _ArrayContraction_denest_ArrayDiagonal(cls, expr: 'ArrayDiagonal', *contraction_indices):
diagonal_indices = list(expr.diagonal_indices)
down_contraction_indices = expr._push_indices_down(expr.diagonal_indices, contraction_indices, get_rank(expr.expr))
# Flatten diagonally contracted indices:
down_contraction_indices = [[k for j in i for k in (j if isinstance(j, (tuple, Tuple)) else [j])] for i in down_contraction_indices]
new_contraction_indices = []
for contr_indgrp in down_contraction_indices:
ind = contr_indgrp[:]
for j, diag_indgrp in enumerate(diagonal_indices):
if diag_indgrp is None:
continue
if any(i in diag_indgrp for i in contr_indgrp):
ind.extend(diag_indgrp)
diagonal_indices[j] = None
new_contraction_indices.append(sorted(set(ind)))
new_diagonal_indices_down = [i for i in diagonal_indices if i is not None]
new_diagonal_indices = ArrayContraction._push_indices_up(new_contraction_indices, new_diagonal_indices_down)
return _array_diagonal(
_array_contraction(expr.expr, *new_contraction_indices),
*new_diagonal_indices
)
@classmethod
def _sort_fully_contracted_args(cls, expr, contraction_indices):
if expr.shape is None:
return expr, contraction_indices
cumul = list(accumulate([0] + expr.subranks))
index_blocks = [list(range(cumul[i], cumul[i+1])) for i in range(len(expr.args))]
contraction_indices_flat = {j for i in contraction_indices for j in i}
fully_contracted = [all(j in contraction_indices_flat for j in range(cumul[i], cumul[i+1])) for i, arg in enumerate(expr.args)]
new_pos = sorted(range(len(expr.args)), key=lambda x: (0, default_sort_key(expr.args[x])) if fully_contracted[x] else (1,))
new_args = [expr.args[i] for i in new_pos]
new_index_blocks_flat = [j for i in new_pos for j in index_blocks[i]]
index_permutation_array_form = _af_invert(new_index_blocks_flat)
new_contraction_indices = [tuple(index_permutation_array_form[j] for j in i) for i in contraction_indices]
new_contraction_indices = _sort_contraction_indices(new_contraction_indices)
return _array_tensor_product(*new_args), new_contraction_indices
def _get_contraction_tuples(self):
r"""
Return tuples containing the argument index and position within the
argument of the index position.
Examples
========
>>> from sympy import MatrixSymbol
>>> from sympy.abc import N
>>> from sympy.tensor.array import tensorproduct, tensorcontraction
>>> A = MatrixSymbol("A", N, N)
>>> B = MatrixSymbol("B", N, N)
>>> cg = tensorcontraction(tensorproduct(A, B), (1, 2))
>>> cg._get_contraction_tuples()
[[(0, 1), (1, 0)]]
Notes
=====
Here the contraction pair `(1, 2)` meaning that the 2nd and 3rd indices
of the tensor product `A\otimes B` are contracted, has been transformed
into `(0, 1)` and `(1, 0)`, identifying the same indices in a different
notation. `(0, 1)` is the second index (1) of the first argument (i.e.
0 or `A`). `(1, 0)` is the first index (i.e. 0) of the second
argument (i.e. 1 or `B`).
"""
mapping = self._mapping
return [[mapping[j] for j in i] for i in self.contraction_indices]
@staticmethod
def _contraction_tuples_to_contraction_indices(expr, contraction_tuples):
# TODO: check that `expr` has `.subranks`:
ranks = expr.subranks
cumulative_ranks = [0] + list(accumulate(ranks))
return [tuple(cumulative_ranks[j]+k for j, k in i) for i in contraction_tuples]
@property
def free_indices(self):
return self._free_indices[:]
@property
def free_indices_to_position(self):
return dict(self._free_indices_to_position)
@property
def expr(self):
return self.args[0]
@property
def contraction_indices(self):
return self.args[1:]
def _contraction_indices_to_components(self):
expr = self.expr
if not isinstance(expr, ArrayTensorProduct):
raise NotImplementedError("only for contractions of tensor products")
ranks = expr.subranks
mapping = {}
counter = 0
for i, rank in enumerate(ranks):
for j in range(rank):
mapping[counter] = (i, j)
counter += 1
return mapping
def sort_args_by_name(self):
"""
Sort arguments in the tensor product so that their order is lexicographical.
Examples
========
>>> from sympy.tensor.array.expressions.conv_matrix_to_array import convert_matrix_to_array
>>> from sympy import MatrixSymbol
>>> from sympy.abc import N
>>> A = MatrixSymbol("A", N, N)
>>> B = MatrixSymbol("B", N, N)
>>> C = MatrixSymbol("C", N, N)
>>> D = MatrixSymbol("D", N, N)
>>> cg = convert_matrix_to_array(C*D*A*B)
>>> cg
ArrayContraction(ArrayTensorProduct(A, D, C, B), (0, 3), (1, 6), (2, 5))
>>> cg.sort_args_by_name()
ArrayContraction(ArrayTensorProduct(A, D, B, C), (0, 3), (1, 4), (2, 7))
"""
expr = self.expr
if not isinstance(expr, ArrayTensorProduct):
return self
args = expr.args
sorted_data = sorted(enumerate(args), key=lambda x: default_sort_key(x[1]))
pos_sorted, args_sorted = zip(*sorted_data)
reordering_map = {i: pos_sorted.index(i) for i, arg in enumerate(args)}
contraction_tuples = self._get_contraction_tuples()
contraction_tuples = [[(reordering_map[j], k) for j, k in i] for i in contraction_tuples]
c_tp = _array_tensor_product(*args_sorted)
new_contr_indices = self._contraction_tuples_to_contraction_indices(
c_tp,
contraction_tuples
)
return _array_contraction(c_tp, *new_contr_indices)
def _get_contraction_links(self):
r"""
Returns a dictionary of links between arguments in the tensor product
being contracted.
See the example for an explanation of the values.
Examples
========
>>> from sympy import MatrixSymbol
>>> from sympy.abc import N
>>> from sympy.tensor.array.expressions.conv_matrix_to_array import convert_matrix_to_array
>>> A = MatrixSymbol("A", N, N)
>>> B = MatrixSymbol("B", N, N)
>>> C = MatrixSymbol("C", N, N)
>>> D = MatrixSymbol("D", N, N)
Matrix multiplications are pairwise contractions between neighboring
matrices:
`A_{ij} B_{jk} C_{kl} D_{lm}`
>>> cg = convert_matrix_to_array(A*B*C*D)
>>> cg
ArrayContraction(ArrayTensorProduct(B, C, A, D), (0, 5), (1, 2), (3, 6))
>>> cg._get_contraction_links()
{0: {0: (2, 1), 1: (1, 0)}, 1: {0: (0, 1), 1: (3, 0)}, 2: {1: (0, 0)}, 3: {0: (1, 1)}}
This dictionary is interpreted as follows: argument in position 0 (i.e.
matrix `A`) has its second index (i.e. 1) contracted to `(1, 0)`, that
is argument in position 1 (matrix `B`) on the first index slot of `B`,
this is the contraction provided by the index `j` from `A`.
The argument in position 1 (that is, matrix `B`) has two contractions,
the ones provided by the indices `j` and `k`, respectively the first
and second indices (0 and 1 in the sub-dict). The link `(0, 1)` and
`(2, 0)` respectively. `(0, 1)` is the index slot 1 (the 2nd) of
argument in position 0 (that is, `A_{\ldot j}`), and so on.
"""
args, dlinks = _get_contraction_links([self], self.subranks, *self.contraction_indices)
return dlinks
def as_explicit(self):
expr = self.expr
if hasattr(expr, "as_explicit"):
expr = expr.as_explicit()
return tensorcontraction(expr, *self.contraction_indices)
class Reshape(_CodegenArrayAbstract):
"""
Reshape the dimensions of an array expression.
Examples
========
>>> from sympy.tensor.array.expressions import ArraySymbol, Reshape
>>> A = ArraySymbol("A", (6,))
>>> A.shape
(6,)
>>> Reshape(A, (3, 2)).shape
(3, 2)
Check the component-explicit forms:
>>> A.as_explicit()
[A[0], A[1], A[2], A[3], A[4], A[5]]
>>> Reshape(A, (3, 2)).as_explicit()
[[A[0], A[1]], [A[2], A[3]], [A[4], A[5]]]
"""
def __new__(cls, expr, shape):
expr = _sympify(expr)
if not isinstance(shape, Tuple):
shape = Tuple(*shape)
if Equality(Mul.fromiter(expr.shape), Mul.fromiter(shape)) == False:
raise ValueError("shape mismatch")
obj = Expr.__new__(cls, expr, shape)
obj._shape = tuple(shape)
obj._expr = expr
return obj
@property
def shape(self):
return self._shape
@property
def expr(self):
return self._expr
def doit(self, *args, **kwargs):
if kwargs.get("deep", True):
expr = self.expr.doit(*args, **kwargs)
else:
expr = self.expr
if isinstance(expr, (MatrixCommon, NDimArray)):
return expr.reshape(*self.shape)
return Reshape(expr, self.shape)
def as_explicit(self):
ee = self.expr
if hasattr(ee, "as_explicit"):
ee = ee.as_explicit()
if isinstance(ee, MatrixCommon):
from sympy import Array
ee = Array(ee)
elif isinstance(ee, MatrixExpr):
return self
return ee.reshape(*self.shape)
class _ArgE:
"""
The ``_ArgE`` object contains references to the array expression
(``.element``) and a list containing the information about index
contractions (``.indices``).
Index contractions are numbered and contracted indices show the number of
the contraction. Uncontracted indices have ``None`` value.
For example:
``_ArgE(M, [None, 3])``
This object means that expression ``M`` is part of an array contraction
and has two indices, the first is not contracted (value ``None``),
the second index is contracted to the 4th (i.e. number ``3``) group of the
array contraction object.
"""
indices: List[Optional[int]]
def __init__(self, element, indices: Optional[List[Optional[int]]] = None):
self.element = element
if indices is None:
self.indices = [None for i in range(get_rank(element))]
else:
self.indices = indices
def __str__(self):
return "_ArgE(%s, %s)" % (self.element, self.indices)
__repr__ = __str__
class _IndPos:
"""
Index position, requiring two integers in the constructor:
- arg: the position of the argument in the tensor product,
- rel: the relative position of the index inside the argument.
"""
def __init__(self, arg: int, rel: int):
self.arg = arg
self.rel = rel
def __str__(self):
return "_IndPos(%i, %i)" % (self.arg, self.rel)
__repr__ = __str__
def __iter__(self):
yield from [self.arg, self.rel]
class _EditArrayContraction:
"""
Utility class to help manipulate array contraction objects.
This class takes as input an ``ArrayContraction`` object and turns it into
an editable object.
The field ``args_with_ind`` of this class is a list of ``_ArgE`` objects
which can be used to easily edit the contraction structure of the
expression.
Once editing is finished, the ``ArrayContraction`` object may be recreated
by calling the ``.to_array_contraction()`` method.
"""
def __init__(self, base_array: typing.Union[ArrayContraction, ArrayDiagonal, ArrayTensorProduct]):
expr: Basic
diagonalized: tTuple[tTuple[int, ...], ...]
contraction_indices: List[tTuple[int]]
if isinstance(base_array, ArrayContraction):
mapping = _get_mapping_from_subranks(base_array.subranks)
expr = base_array.expr
contraction_indices = base_array.contraction_indices
diagonalized = ()
elif isinstance(base_array, ArrayDiagonal):
if isinstance(base_array.expr, ArrayContraction):
mapping = _get_mapping_from_subranks(base_array.expr.subranks)
expr = base_array.expr.expr
diagonalized = ArrayContraction._push_indices_down(base_array.expr.contraction_indices, base_array.diagonal_indices)
contraction_indices = base_array.expr.contraction_indices
elif isinstance(base_array.expr, ArrayTensorProduct):
mapping = {}
expr = base_array.expr
diagonalized = base_array.diagonal_indices
contraction_indices = []
else:
mapping = {}
expr = base_array.expr
diagonalized = base_array.diagonal_indices
contraction_indices = []
elif isinstance(base_array, ArrayTensorProduct):
expr = base_array
contraction_indices = []
diagonalized = ()
else:
raise NotImplementedError()
if isinstance(expr, ArrayTensorProduct):
args = list(expr.args)
else:
args = [expr]
args_with_ind: List[_ArgE] = [_ArgE(arg) for arg in args]
for i, contraction_tuple in enumerate(contraction_indices):
for j in contraction_tuple:
arg_pos, rel_pos = mapping[j]
args_with_ind[arg_pos].indices[rel_pos] = i
self.args_with_ind: List[_ArgE] = args_with_ind
self.number_of_contraction_indices: int = len(contraction_indices)
self._track_permutation: Optional[List[List[int]]] = None
mapping = _get_mapping_from_subranks(base_array.subranks)
# Trick: add diagonalized indices as negative indices into the editor object:
for i, e in enumerate(diagonalized):
for j in e:
arg_pos, rel_pos = mapping[j]
self.args_with_ind[arg_pos].indices[rel_pos] = -1 - i
def insert_after(self, arg: _ArgE, new_arg: _ArgE):
pos = self.args_with_ind.index(arg)
self.args_with_ind.insert(pos + 1, new_arg)
def get_new_contraction_index(self):
self.number_of_contraction_indices += 1
return self.number_of_contraction_indices - 1
def refresh_indices(self):
updates: tDict[int, int] = {}
for arg_with_ind in self.args_with_ind:
updates.update({i: -1 for i in arg_with_ind.indices if i is not None})
for i, e in enumerate(sorted(updates)):
updates[e] = i
self.number_of_contraction_indices: int = len(updates)
for arg_with_ind in self.args_with_ind:
arg_with_ind.indices = [updates.get(i, None) for i in arg_with_ind.indices]
def merge_scalars(self):
scalars = []
for arg_with_ind in self.args_with_ind:
if len(arg_with_ind.indices) == 0:
scalars.append(arg_with_ind)
for i in scalars:
self.args_with_ind.remove(i)
scalar = Mul.fromiter([i.element for i in scalars])
if len(self.args_with_ind) == 0:
self.args_with_ind.append(_ArgE(scalar))
else:
from sympy.tensor.array.expressions.conv_array_to_matrix import _a2m_tensor_product
self.args_with_ind[0].element = _a2m_tensor_product(scalar, self.args_with_ind[0].element)
def to_array_contraction(self):
# Count the ranks of the arguments:
counter = 0
# Create a collector for the new diagonal indices:
diag_indices = defaultdict(list)
count_index_freq = Counter()
for arg_with_ind in self.args_with_ind:
count_index_freq.update(Counter(arg_with_ind.indices))
free_index_count = count_index_freq[None]
# Construct the inverse permutation:
inv_perm1 = []
inv_perm2 = []
# Keep track of which diagonal indices have already been processed:
done = set([])
# Counter for the diagonal indices:
counter4 = 0
for arg_with_ind in self.args_with_ind:
# If some diagonalization axes have been removed, they should be
# permuted in order to keep the permutation.
# Add permutation here
counter2 = 0 # counter for the indices
for i in arg_with_ind.indices:
if i is None:
inv_perm1.append(counter4)
counter2 += 1
counter4 += 1
continue
if i >= 0:
continue
# Reconstruct the diagonal indices:
diag_indices[-1 - i].append(counter + counter2)
if count_index_freq[i] == 1 and i not in done:
inv_perm1.append(free_index_count - 1 - i)
done.add(i)
elif i not in done:
inv_perm2.append(free_index_count - 1 - i)
done.add(i)
counter2 += 1
# Remove negative indices to restore a proper editor object:
arg_with_ind.indices = [i if i is not None and i >= 0 else None for i in arg_with_ind.indices]
counter += len([i for i in arg_with_ind.indices if i is None or i < 0])
inverse_permutation = inv_perm1 + inv_perm2
permutation = _af_invert(inverse_permutation)
# Get the diagonal indices after the detection of HadamardProduct in the expression:
diag_indices_filtered = [tuple(v) for v in diag_indices.values() if len(v) > 1]
self.merge_scalars()
self.refresh_indices()
args = [arg.element for arg in self.args_with_ind]
contraction_indices = self.get_contraction_indices()
expr = _array_contraction(_array_tensor_product(*args), *contraction_indices)
expr2 = _array_diagonal(expr, *diag_indices_filtered)
if self._track_permutation is not None:
permutation2 = _af_invert([j for i in self._track_permutation for j in i])
expr2 = _permute_dims(expr2, permutation2)
expr3 = _permute_dims(expr2, permutation)
return expr3
def get_contraction_indices(self) -> List[List[int]]:
contraction_indices: List[List[int]] = [[] for i in range(self.number_of_contraction_indices)]
current_position: int = 0
for i, arg_with_ind in enumerate(self.args_with_ind):
for j in arg_with_ind.indices:
if j is not None:
contraction_indices[j].append(current_position)
current_position += 1
return contraction_indices
def get_mapping_for_index(self, ind) -> List[_IndPos]:
if ind >= self.number_of_contraction_indices:
raise ValueError("index value exceeding the index range")
positions: List[_IndPos] = []
for i, arg_with_ind in enumerate(self.args_with_ind):
for j, arg_ind in enumerate(arg_with_ind.indices):
if ind == arg_ind:
positions.append(_IndPos(i, j))
return positions
def get_contraction_indices_to_ind_rel_pos(self) -> List[List[_IndPos]]:
contraction_indices: List[List[_IndPos]] = [[] for i in range(self.number_of_contraction_indices)]
for i, arg_with_ind in enumerate(self.args_with_ind):
for j, ind in enumerate(arg_with_ind.indices):
if ind is not None:
contraction_indices[ind].append(_IndPos(i, j))
return contraction_indices
def count_args_with_index(self, index: int) -> int:
"""
Count the number of arguments that have the given index.
"""
counter: int = 0
for arg_with_ind in self.args_with_ind:
if index in arg_with_ind.indices:
counter += 1
return counter
def get_args_with_index(self, index: int) -> List[_ArgE]:
"""
Get a list of arguments having the given index.
"""
ret: List[_ArgE] = [i for i in self.args_with_ind if index in i.indices]
return ret
@property
def number_of_diagonal_indices(self):
data = set([])
for arg in self.args_with_ind:
data.update({i for i in arg.indices if i is not None and i < 0})
return len(data)
def track_permutation_start(self):
permutation = []
perm_diag = []
counter: int = 0
counter2: int = -1
for arg_with_ind in self.args_with_ind:
perm = []
for i in arg_with_ind.indices:
if i is not None:
if i < 0:
perm_diag.append(counter2)
counter2 -= 1
continue
perm.append(counter)
counter += 1
permutation.append(perm)
max_ind = max([max(i) if i else -1 for i in permutation]) if permutation else -1
perm_diag = [max_ind - i for i in perm_diag]
self._track_permutation = permutation + [perm_diag]
def track_permutation_merge(self, destination: _ArgE, from_element: _ArgE):
index_destination = self.args_with_ind.index(destination)
index_element = self.args_with_ind.index(from_element)
self._track_permutation[index_destination].extend(self._track_permutation[index_element]) # type: ignore
self._track_permutation.pop(index_element) # type: ignore
def get_absolute_free_range(self, arg: _ArgE) -> typing.Tuple[int, int]:
"""
Return the range of the free indices of the arg as absolute positions
among all free indices.
"""
counter = 0
for arg_with_ind in self.args_with_ind:
number_free_indices = len([i for i in arg_with_ind.indices if i is None])
if arg_with_ind == arg:
return counter, counter + number_free_indices
counter += number_free_indices
raise IndexError("argument not found")
def get_absolute_range(self, arg: _ArgE) -> typing.Tuple[int, int]:
"""
Return the absolute range of indices for arg, disregarding dummy
indices.
"""
counter = 0
for arg_with_ind in self.args_with_ind:
number_indices = len(arg_with_ind.indices)
if arg_with_ind == arg:
return counter, counter + number_indices
counter += number_indices
raise IndexError("argument not found")
def get_rank(expr):
if isinstance(expr, (MatrixExpr, MatrixElement)):
return 2
if isinstance(expr, _CodegenArrayAbstract):
return len(expr.shape)
if isinstance(expr, NDimArray):
return expr.rank()
if isinstance(expr, Indexed):
return expr.rank
if isinstance(expr, IndexedBase):
shape = expr.shape
if shape is None:
return -1
else:
return len(shape)
if hasattr(expr, "shape"):
return len(expr.shape)
return 0
def _get_subrank(expr):
if isinstance(expr, _CodegenArrayAbstract):
return expr.subrank()
return get_rank(expr)
def _get_subranks(expr):
if isinstance(expr, _CodegenArrayAbstract):
return expr.subranks
else:
return [get_rank(expr)]
def get_shape(expr):
if hasattr(expr, "shape"):
return expr.shape
return ()
def nest_permutation(expr):
if isinstance(expr, PermuteDims):
return expr.nest_permutation()
else:
return expr
def _array_tensor_product(*args, **kwargs):
return ArrayTensorProduct(*args, canonicalize=True, **kwargs)
def _array_contraction(expr, *contraction_indices, **kwargs):
return ArrayContraction(expr, *contraction_indices, canonicalize=True, **kwargs)
def _array_diagonal(expr, *diagonal_indices, **kwargs):
return ArrayDiagonal(expr, *diagonal_indices, canonicalize=True, **kwargs)
def _permute_dims(expr, permutation, **kwargs):
return PermuteDims(expr, permutation, canonicalize=True, **kwargs)
def _array_add(*args, **kwargs):
return ArrayAdd(*args, canonicalize=True, **kwargs)
def _get_array_element_or_slice(expr, indices):
return ArrayElement(expr, indices)
|
51b0712638946aa05b40f6a2bedaefdd984d36e1c7754b09e54b36bf2f109b10 | """Implementation of DPLL algorithm
Features:
- Clause learning
- Watch literal scheme
- VSIDS heuristic
References:
- https://en.wikipedia.org/wiki/DPLL_algorithm
"""
from collections import defaultdict
from heapq import heappush, heappop
from sympy.core.sorting import ordered
from sympy.assumptions.cnf import EncodedCNF
def dpll_satisfiable(expr, all_models=False):
"""
Check satisfiability of a propositional sentence.
It returns a model rather than True when it succeeds.
Returns a generator of all models if all_models is True.
Examples
========
>>> from sympy.abc import A, B
>>> from sympy.logic.algorithms.dpll2 import dpll_satisfiable
>>> dpll_satisfiable(A & ~B)
{A: True, B: False}
>>> dpll_satisfiable(A & ~A)
False
"""
if not isinstance(expr, EncodedCNF):
exprs = EncodedCNF()
exprs.add_prop(expr)
expr = exprs
# Return UNSAT when False (encoded as 0) is present in the CNF
if {0} in expr.data:
if all_models:
return (f for f in [False])
return False
solver = SATSolver(expr.data, expr.variables, set(), expr.symbols)
models = solver._find_model()
if all_models:
return _all_models(models)
try:
return next(models)
except StopIteration:
return False
# Uncomment to confirm the solution is valid (hitting set for the clauses)
#else:
#for cls in clauses_int_repr:
#assert solver.var_settings.intersection(cls)
def _all_models(models):
satisfiable = False
try:
while True:
yield next(models)
satisfiable = True
except StopIteration:
if not satisfiable:
yield False
class SATSolver:
"""
Class for representing a SAT solver capable of
finding a model to a boolean theory in conjunctive
normal form.
"""
def __init__(self, clauses, variables, var_settings, symbols=None,
heuristic='vsids', clause_learning='none', INTERVAL=500):
self.var_settings = var_settings
self.heuristic = heuristic
self.is_unsatisfied = False
self._unit_prop_queue = []
self.update_functions = []
self.INTERVAL = INTERVAL
if symbols is None:
self.symbols = list(ordered(variables))
else:
self.symbols = symbols
self._initialize_variables(variables)
self._initialize_clauses(clauses)
if 'vsids' == heuristic:
self._vsids_init()
self.heur_calculate = self._vsids_calculate
self.heur_lit_assigned = self._vsids_lit_assigned
self.heur_lit_unset = self._vsids_lit_unset
self.heur_clause_added = self._vsids_clause_added
# Note: Uncomment this if/when clause learning is enabled
#self.update_functions.append(self._vsids_decay)
else:
raise NotImplementedError
if 'simple' == clause_learning:
self.add_learned_clause = self._simple_add_learned_clause
self.compute_conflict = self.simple_compute_conflict
self.update_functions.append(self.simple_clean_clauses)
elif 'none' == clause_learning:
self.add_learned_clause = lambda x: None
self.compute_conflict = lambda: None
else:
raise NotImplementedError
# Create the base level
self.levels = [Level(0)]
self._current_level.varsettings = var_settings
# Keep stats
self.num_decisions = 0
self.num_learned_clauses = 0
self.original_num_clauses = len(self.clauses)
def _initialize_variables(self, variables):
"""Set up the variable data structures needed."""
self.sentinels = defaultdict(set)
self.occurrence_count = defaultdict(int)
self.variable_set = [False] * (len(variables) + 1)
def _initialize_clauses(self, clauses):
"""Set up the clause data structures needed.
For each clause, the following changes are made:
- Unit clauses are queued for propagation right away.
- Non-unit clauses have their first and last literals set as sentinels.
- The number of clauses a literal appears in is computed.
"""
self.clauses = [list(clause) for clause in clauses]
for i, clause in enumerate(self.clauses):
# Handle the unit clauses
if 1 == len(clause):
self._unit_prop_queue.append(clause[0])
continue
self.sentinels[clause[0]].add(i)
self.sentinels[clause[-1]].add(i)
for lit in clause:
self.occurrence_count[lit] += 1
def _find_model(self):
"""
Main DPLL loop. Returns a generator of models.
Variables are chosen successively, and assigned to be either
True or False. If a solution is not found with this setting,
the opposite is chosen and the search continues. The solver
halts when every variable has a setting.
Examples
========
>>> from sympy.logic.algorithms.dpll2 import SATSolver
>>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
... {3, -2}], {1, 2, 3}, set())
>>> list(l._find_model())
[{1: True, 2: False, 3: False}, {1: True, 2: True, 3: True}]
>>> from sympy.abc import A, B, C
>>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
... {3, -2}], {1, 2, 3}, set(), [A, B, C])
>>> list(l._find_model())
[{A: True, B: False, C: False}, {A: True, B: True, C: True}]
"""
# We use this variable to keep track of if we should flip a
# variable setting in successive rounds
flip_var = False
# Check if unit prop says the theory is unsat right off the bat
self._simplify()
if self.is_unsatisfied:
return
# While the theory still has clauses remaining
while True:
# Perform cleanup / fixup at regular intervals
if self.num_decisions % self.INTERVAL == 0:
for func in self.update_functions:
func()
if flip_var:
# We have just backtracked and we are trying to opposite literal
flip_var = False
lit = self._current_level.decision
else:
# Pick a literal to set
lit = self.heur_calculate()
self.num_decisions += 1
# Stopping condition for a satisfying theory
if 0 == lit:
yield {self.symbols[abs(lit) - 1]:
lit > 0 for lit in self.var_settings}
while self._current_level.flipped:
self._undo()
if len(self.levels) == 1:
return
flip_lit = -self._current_level.decision
self._undo()
self.levels.append(Level(flip_lit, flipped=True))
flip_var = True
continue
# Start the new decision level
self.levels.append(Level(lit))
# Assign the literal, updating the clauses it satisfies
self._assign_literal(lit)
# _simplify the theory
self._simplify()
# Check if we've made the theory unsat
if self.is_unsatisfied:
self.is_unsatisfied = False
# We unroll all of the decisions until we can flip a literal
while self._current_level.flipped:
self._undo()
# If we've unrolled all the way, the theory is unsat
if 1 == len(self.levels):
return
# Detect and add a learned clause
self.add_learned_clause(self.compute_conflict())
# Try the opposite setting of the most recent decision
flip_lit = -self._current_level.decision
self._undo()
self.levels.append(Level(flip_lit, flipped=True))
flip_var = True
########################
# Helper Methods #
########################
@property
def _current_level(self):
"""The current decision level data structure
Examples
========
>>> from sympy.logic.algorithms.dpll2 import SATSolver
>>> l = SATSolver([{1}, {2}], {1, 2}, set())
>>> next(l._find_model())
{1: True, 2: True}
>>> l._current_level.decision
0
>>> l._current_level.flipped
False
>>> l._current_level.var_settings
{1, 2}
"""
return self.levels[-1]
def _clause_sat(self, cls):
"""Check if a clause is satisfied by the current variable setting.
Examples
========
>>> from sympy.logic.algorithms.dpll2 import SATSolver
>>> l = SATSolver([{1}, {-1}], {1}, set())
>>> try:
... next(l._find_model())
... except StopIteration:
... pass
>>> l._clause_sat(0)
False
>>> l._clause_sat(1)
True
"""
for lit in self.clauses[cls]:
if lit in self.var_settings:
return True
return False
def _is_sentinel(self, lit, cls):
"""Check if a literal is a sentinel of a given clause.
Examples
========
>>> from sympy.logic.algorithms.dpll2 import SATSolver
>>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
... {3, -2}], {1, 2, 3}, set())
>>> next(l._find_model())
{1: True, 2: False, 3: False}
>>> l._is_sentinel(2, 3)
True
>>> l._is_sentinel(-3, 1)
False
"""
return cls in self.sentinels[lit]
def _assign_literal(self, lit):
"""Make a literal assignment.
The literal assignment must be recorded as part of the current
decision level. Additionally, if the literal is marked as a
sentinel of any clause, then a new sentinel must be chosen. If
this is not possible, then unit propagation is triggered and
another literal is added to the queue to be set in the future.
Examples
========
>>> from sympy.logic.algorithms.dpll2 import SATSolver
>>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
... {3, -2}], {1, 2, 3}, set())
>>> next(l._find_model())
{1: True, 2: False, 3: False}
>>> l.var_settings
{-3, -2, 1}
>>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
... {3, -2}], {1, 2, 3}, set())
>>> l._assign_literal(-1)
>>> try:
... next(l._find_model())
... except StopIteration:
... pass
>>> l.var_settings
{-1}
"""
self.var_settings.add(lit)
self._current_level.var_settings.add(lit)
self.variable_set[abs(lit)] = True
self.heur_lit_assigned(lit)
sentinel_list = list(self.sentinels[-lit])
for cls in sentinel_list:
if not self._clause_sat(cls):
other_sentinel = None
for newlit in self.clauses[cls]:
if newlit != -lit:
if self._is_sentinel(newlit, cls):
other_sentinel = newlit
elif not self.variable_set[abs(newlit)]:
self.sentinels[-lit].remove(cls)
self.sentinels[newlit].add(cls)
other_sentinel = None
break
# Check if no sentinel update exists
if other_sentinel:
self._unit_prop_queue.append(other_sentinel)
def _undo(self):
"""
_undo the changes of the most recent decision level.
Examples
========
>>> from sympy.logic.algorithms.dpll2 import SATSolver
>>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
... {3, -2}], {1, 2, 3}, set())
>>> next(l._find_model())
{1: True, 2: False, 3: False}
>>> level = l._current_level
>>> level.decision, level.var_settings, level.flipped
(-3, {-3, -2}, False)
>>> l._undo()
>>> level = l._current_level
>>> level.decision, level.var_settings, level.flipped
(0, {1}, False)
"""
# Undo the variable settings
for lit in self._current_level.var_settings:
self.var_settings.remove(lit)
self.heur_lit_unset(lit)
self.variable_set[abs(lit)] = False
# Pop the level off the stack
self.levels.pop()
#########################
# Propagation #
#########################
"""
Propagation methods should attempt to soundly simplify the boolean
theory, and return True if any simplification occurred and False
otherwise.
"""
def _simplify(self):
"""Iterate over the various forms of propagation to simplify the theory.
Examples
========
>>> from sympy.logic.algorithms.dpll2 import SATSolver
>>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
... {3, -2}], {1, 2, 3}, set())
>>> l.variable_set
[False, False, False, False]
>>> l.sentinels
{-3: {0, 2}, -2: {3, 4}, 2: {0, 3}, 3: {2, 4}}
>>> l._simplify()
>>> l.variable_set
[False, True, False, False]
>>> l.sentinels
{-3: {0, 2}, -2: {3, 4}, -1: set(), 2: {0, 3},
...3: {2, 4}}
"""
changed = True
while changed:
changed = False
changed |= self._unit_prop()
changed |= self._pure_literal()
def _unit_prop(self):
"""Perform unit propagation on the current theory."""
result = len(self._unit_prop_queue) > 0
while self._unit_prop_queue:
next_lit = self._unit_prop_queue.pop()
if -next_lit in self.var_settings:
self.is_unsatisfied = True
self._unit_prop_queue = []
return False
else:
self._assign_literal(next_lit)
return result
def _pure_literal(self):
"""Look for pure literals and assign them when found."""
return False
#########################
# Heuristics #
#########################
def _vsids_init(self):
"""Initialize the data structures needed for the VSIDS heuristic."""
self.lit_heap = []
self.lit_scores = {}
for var in range(1, len(self.variable_set)):
self.lit_scores[var] = float(-self.occurrence_count[var])
self.lit_scores[-var] = float(-self.occurrence_count[-var])
heappush(self.lit_heap, (self.lit_scores[var], var))
heappush(self.lit_heap, (self.lit_scores[-var], -var))
def _vsids_decay(self):
"""Decay the VSIDS scores for every literal.
Examples
========
>>> from sympy.logic.algorithms.dpll2 import SATSolver
>>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
... {3, -2}], {1, 2, 3}, set())
>>> l.lit_scores
{-3: -2.0, -2: -2.0, -1: 0.0, 1: 0.0, 2: -2.0, 3: -2.0}
>>> l._vsids_decay()
>>> l.lit_scores
{-3: -1.0, -2: -1.0, -1: 0.0, 1: 0.0, 2: -1.0, 3: -1.0}
"""
# We divide every literal score by 2 for a decay factor
# Note: This doesn't change the heap property
for lit in self.lit_scores.keys():
self.lit_scores[lit] /= 2.0
def _vsids_calculate(self):
"""
VSIDS Heuristic Calculation
Examples
========
>>> from sympy.logic.algorithms.dpll2 import SATSolver
>>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
... {3, -2}], {1, 2, 3}, set())
>>> l.lit_heap
[(-2.0, -3), (-2.0, 2), (-2.0, -2), (0.0, 1), (-2.0, 3), (0.0, -1)]
>>> l._vsids_calculate()
-3
>>> l.lit_heap
[(-2.0, -2), (-2.0, 2), (0.0, -1), (0.0, 1), (-2.0, 3)]
"""
if len(self.lit_heap) == 0:
return 0
# Clean out the front of the heap as long the variables are set
while self.variable_set[abs(self.lit_heap[0][1])]:
heappop(self.lit_heap)
if len(self.lit_heap) == 0:
return 0
return heappop(self.lit_heap)[1]
def _vsids_lit_assigned(self, lit):
"""Handle the assignment of a literal for the VSIDS heuristic."""
pass
def _vsids_lit_unset(self, lit):
"""Handle the unsetting of a literal for the VSIDS heuristic.
Examples
========
>>> from sympy.logic.algorithms.dpll2 import SATSolver
>>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
... {3, -2}], {1, 2, 3}, set())
>>> l.lit_heap
[(-2.0, -3), (-2.0, 2), (-2.0, -2), (0.0, 1), (-2.0, 3), (0.0, -1)]
>>> l._vsids_lit_unset(2)
>>> l.lit_heap
[(-2.0, -3), (-2.0, -2), (-2.0, -2), (-2.0, 2), (-2.0, 3), (0.0, -1),
...(-2.0, 2), (0.0, 1)]
"""
var = abs(lit)
heappush(self.lit_heap, (self.lit_scores[var], var))
heappush(self.lit_heap, (self.lit_scores[-var], -var))
def _vsids_clause_added(self, cls):
"""Handle the addition of a new clause for the VSIDS heuristic.
Examples
========
>>> from sympy.logic.algorithms.dpll2 import SATSolver
>>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
... {3, -2}], {1, 2, 3}, set())
>>> l.num_learned_clauses
0
>>> l.lit_scores
{-3: -2.0, -2: -2.0, -1: 0.0, 1: 0.0, 2: -2.0, 3: -2.0}
>>> l._vsids_clause_added({2, -3})
>>> l.num_learned_clauses
1
>>> l.lit_scores
{-3: -1.0, -2: -2.0, -1: 0.0, 1: 0.0, 2: -1.0, 3: -2.0}
"""
self.num_learned_clauses += 1
for lit in cls:
self.lit_scores[lit] += 1
########################
# Clause Learning #
########################
def _simple_add_learned_clause(self, cls):
"""Add a new clause to the theory.
Examples
========
>>> from sympy.logic.algorithms.dpll2 import SATSolver
>>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
... {3, -2}], {1, 2, 3}, set())
>>> l.num_learned_clauses
0
>>> l.clauses
[[2, -3], [1], [3, -3], [2, -2], [3, -2]]
>>> l.sentinels
{-3: {0, 2}, -2: {3, 4}, 2: {0, 3}, 3: {2, 4}}
>>> l._simple_add_learned_clause([3])
>>> l.clauses
[[2, -3], [1], [3, -3], [2, -2], [3, -2], [3]]
>>> l.sentinels
{-3: {0, 2}, -2: {3, 4}, 2: {0, 3}, 3: {2, 4, 5}}
"""
cls_num = len(self.clauses)
self.clauses.append(cls)
for lit in cls:
self.occurrence_count[lit] += 1
self.sentinels[cls[0]].add(cls_num)
self.sentinels[cls[-1]].add(cls_num)
self.heur_clause_added(cls)
def _simple_compute_conflict(self):
""" Build a clause representing the fact that at least one decision made
so far is wrong.
Examples
========
>>> from sympy.logic.algorithms.dpll2 import SATSolver
>>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
... {3, -2}], {1, 2, 3}, set())
>>> next(l._find_model())
{1: True, 2: False, 3: False}
>>> l._simple_compute_conflict()
[3]
"""
return [-(level.decision) for level in self.levels[1:]]
def _simple_clean_clauses(self):
"""Clean up learned clauses."""
pass
class Level:
"""
Represents a single level in the DPLL algorithm, and contains
enough information for a sound backtracking procedure.
"""
def __init__(self, decision, flipped=False):
self.decision = decision
self.var_settings = set()
self.flipped = flipped
|
1f248431fe6ec1653955155d3a58ace75b0196a02a6b3076fdbdfe1785119061 | import random
import concurrent.futures
from collections.abc import Hashable
from sympy.core.add import Add
from sympy.core.function import (Function, diff, expand)
from sympy.core.numbers import (E, Float, I, Integer, Rational, nan, oo, pi)
from sympy.core.power import Pow
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 Abs
from sympy.functions.elementary.exponential import (exp, log)
from sympy.functions.elementary.miscellaneous import (Max, Min, sqrt)
from sympy.functions.elementary.trigonometric import (cos, sin, tan)
from sympy.integrals.integrals import integrate
from sympy.polys.polytools import (Poly, PurePoly)
from sympy.printing.str import sstr
from sympy.sets.sets import FiniteSet
from sympy.simplify.simplify import (signsimp, simplify)
from sympy.simplify.trigsimp import trigsimp
from sympy.matrices.matrices import (ShapeError, MatrixError,
NonSquareMatrixError, DeferredVector, _find_reasonable_pivot_naive,
_simplify)
from sympy.matrices import (
GramSchmidt, ImmutableMatrix, ImmutableSparseMatrix, Matrix,
SparseMatrix, casoratian, diag, eye, hessian,
matrix_multiply_elementwise, ones, randMatrix, rot_axis1, rot_axis2,
rot_axis3, wronskian, zeros, MutableDenseMatrix, ImmutableDenseMatrix,
MatrixSymbol, dotprodsimp)
from sympy.matrices.utilities import _dotprodsimp_state
from sympy.core import Tuple, Wild
from sympy.functions.special.tensor_functions import KroneckerDelta
from sympy.utilities.iterables import flatten, capture, iterable
from sympy.utilities.exceptions import ignore_warnings, SymPyDeprecationWarning
from sympy.testing.pytest import (raises, XFAIL, slow, skip,
warns_deprecated_sympy, warns)
from sympy.assumptions import Q
from sympy.tensor.array import Array
from sympy.matrices.expressions import MatPow
from sympy.external import import_module
from sympy.abc import a, b, c, d, x, y, z, t
pyodide_js = import_module('pyodide_js')
# don't re-order this list
classes = (Matrix, SparseMatrix, ImmutableMatrix, ImmutableSparseMatrix)
def test_args():
for n, cls in enumerate(classes):
m = cls.zeros(3, 2)
# all should give back the same type of arguments, e.g. ints for shape
assert m.shape == (3, 2) and all(type(i) is int for i in m.shape)
assert m.rows == 3 and type(m.rows) is int
assert m.cols == 2 and type(m.cols) is int
if not n % 2:
assert type(m.flat()) in (list, tuple, Tuple)
else:
assert type(m.todok()) is dict
def test_deprecated_mat_smat():
for cls in Matrix, ImmutableMatrix:
m = cls.zeros(3, 2)
with warns_deprecated_sympy():
mat = m._mat
assert mat == m.flat()
for cls in SparseMatrix, ImmutableSparseMatrix:
m = cls.zeros(3, 2)
with warns_deprecated_sympy():
smat = m._smat
assert smat == m.todok()
def test_division():
v = Matrix(1, 2, [x, y])
assert v/z == Matrix(1, 2, [x/z, y/z])
def test_sum():
m = Matrix([[1, 2, 3], [x, y, x], [2*y, -50, z*x]])
assert m + m == Matrix([[2, 4, 6], [2*x, 2*y, 2*x], [4*y, -100, 2*z*x]])
n = Matrix(1, 2, [1, 2])
raises(ShapeError, lambda: m + n)
def test_abs():
m = Matrix(1, 2, [-3, x])
n = Matrix(1, 2, [3, Abs(x)])
assert abs(m) == n
def test_addition():
a = Matrix((
(1, 2),
(3, 1),
))
b = Matrix((
(1, 2),
(3, 0),
))
assert a + b == a.add(b) == Matrix([[2, 4], [6, 1]])
def test_fancy_index_matrix():
for M in (Matrix, SparseMatrix):
a = M(3, 3, range(9))
assert a == a[:, :]
assert a[1, :] == Matrix(1, 3, [3, 4, 5])
assert a[:, 1] == Matrix([1, 4, 7])
assert a[[0, 1], :] == Matrix([[0, 1, 2], [3, 4, 5]])
assert a[[0, 1], 2] == a[[0, 1], [2]]
assert a[2, [0, 1]] == a[[2], [0, 1]]
assert a[:, [0, 1]] == Matrix([[0, 1], [3, 4], [6, 7]])
assert a[0, 0] == 0
assert a[0:2, :] == Matrix([[0, 1, 2], [3, 4, 5]])
assert a[:, 0:2] == Matrix([[0, 1], [3, 4], [6, 7]])
assert a[::2, 1] == a[[0, 2], 1]
assert a[1, ::2] == a[1, [0, 2]]
a = M(3, 3, range(9))
assert a[[0, 2, 1, 2, 1], :] == Matrix([
[0, 1, 2],
[6, 7, 8],
[3, 4, 5],
[6, 7, 8],
[3, 4, 5]])
assert a[:, [0,2,1,2,1]] == Matrix([
[0, 2, 1, 2, 1],
[3, 5, 4, 5, 4],
[6, 8, 7, 8, 7]])
a = SparseMatrix.zeros(3)
a[1, 2] = 2
a[0, 1] = 3
a[2, 0] = 4
assert a.extract([1, 1], [2]) == Matrix([
[2],
[2]])
assert a.extract([1, 0], [2, 2, 2]) == Matrix([
[2, 2, 2],
[0, 0, 0]])
assert a.extract([1, 0, 1, 2], [2, 0, 1, 0]) == Matrix([
[2, 0, 0, 0],
[0, 0, 3, 0],
[2, 0, 0, 0],
[0, 4, 0, 4]])
def test_multiplication():
a = Matrix((
(1, 2),
(3, 1),
(0, 6),
))
b = Matrix((
(1, 2),
(3, 0),
))
c = a*b
assert c[0, 0] == 7
assert c[0, 1] == 2
assert c[1, 0] == 6
assert c[1, 1] == 6
assert c[2, 0] == 18
assert c[2, 1] == 0
try:
eval('c = a @ b')
except SyntaxError:
pass
else:
assert c[0, 0] == 7
assert c[0, 1] == 2
assert c[1, 0] == 6
assert c[1, 1] == 6
assert c[2, 0] == 18
assert c[2, 1] == 0
h = matrix_multiply_elementwise(a, c)
assert h == a.multiply_elementwise(c)
assert h[0, 0] == 7
assert h[0, 1] == 4
assert h[1, 0] == 18
assert h[1, 1] == 6
assert h[2, 0] == 0
assert h[2, 1] == 0
raises(ShapeError, lambda: matrix_multiply_elementwise(a, b))
c = b * Symbol("x")
assert isinstance(c, Matrix)
assert c[0, 0] == x
assert c[0, 1] == 2*x
assert c[1, 0] == 3*x
assert c[1, 1] == 0
c2 = x * b
assert c == c2
c = 5 * b
assert isinstance(c, Matrix)
assert c[0, 0] == 5
assert c[0, 1] == 2*5
assert c[1, 0] == 3*5
assert c[1, 1] == 0
try:
eval('c = 5 @ b')
except SyntaxError:
pass
else:
assert isinstance(c, Matrix)
assert c[0, 0] == 5
assert c[0, 1] == 2*5
assert c[1, 0] == 3*5
assert c[1, 1] == 0
M = Matrix([[oo, 0], [0, oo]])
assert M ** 2 == M
M = Matrix([[oo, oo], [0, 0]])
assert M ** 2 == Matrix([[nan, nan], [nan, nan]])
def test_power():
raises(NonSquareMatrixError, lambda: Matrix((1, 2))**2)
R = Rational
A = Matrix([[2, 3], [4, 5]])
assert (A**-3)[:] == [R(-269)/8, R(153)/8, R(51)/2, R(-29)/2]
assert (A**5)[:] == [6140, 8097, 10796, 14237]
A = Matrix([[2, 1, 3], [4, 2, 4], [6, 12, 1]])
assert (A**3)[:] == [290, 262, 251, 448, 440, 368, 702, 954, 433]
assert A**0 == eye(3)
assert A**1 == A
assert (Matrix([[2]]) ** 100)[0, 0] == 2**100
assert eye(2)**10000000 == eye(2)
assert Matrix([[1, 2], [3, 4]])**Integer(2) == Matrix([[7, 10], [15, 22]])
A = Matrix([[33, 24], [48, 57]])
assert (A**S.Half)[:] == [5, 2, 4, 7]
A = Matrix([[0, 4], [-1, 5]])
assert (A**S.Half)**2 == A
assert Matrix([[1, 0], [1, 1]])**S.Half == Matrix([[1, 0], [S.Half, 1]])
assert Matrix([[1, 0], [1, 1]])**0.5 == Matrix([[1.0, 0], [0.5, 1.0]])
from sympy.abc import n
assert Matrix([[1, a], [0, 1]])**n == Matrix([[1, a*n], [0, 1]])
assert Matrix([[b, a], [0, b]])**n == Matrix([[b**n, a*b**(n-1)*n], [0, b**n]])
assert Matrix([
[a**n, a**(n - 1)*n, (a**n*n**2 - a**n*n)/(2*a**2)],
[ 0, a**n, a**(n - 1)*n],
[ 0, 0, a**n]])
assert Matrix([[a, 1, 0], [0, a, 0], [0, 0, b]])**n == Matrix([
[a**n, a**(n-1)*n, 0],
[0, a**n, 0],
[0, 0, b**n]])
A = Matrix([[1, 0], [1, 7]])
assert A._matrix_pow_by_jordan_blocks(S(3)) == A._eval_pow_by_recursion(3)
A = Matrix([[2]])
assert A**10 == Matrix([[2**10]]) == A._matrix_pow_by_jordan_blocks(S(10)) == \
A._eval_pow_by_recursion(10)
# testing a matrix that cannot be jordan blocked issue 11766
m = Matrix([[3, 0, 0, 0, -3], [0, -3, -3, 0, 3], [0, 3, 0, 3, 0], [0, 0, 3, 0, 3], [3, 0, 0, 3, 0]])
raises(MatrixError, lambda: m._matrix_pow_by_jordan_blocks(S(10)))
# test issue 11964
raises(MatrixError, lambda: Matrix([[1, 1], [3, 3]])._matrix_pow_by_jordan_blocks(S(-10)))
A = Matrix([[0, 1, 0], [0, 0, 1], [0, 0, 0]]) # Nilpotent jordan block size 3
assert A**10.0 == Matrix([[0, 0, 0], [0, 0, 0], [0, 0, 0]])
raises(ValueError, lambda: A**2.1)
raises(ValueError, lambda: A**Rational(3, 2))
A = Matrix([[8, 1], [3, 2]])
assert A**10.0 == Matrix([[1760744107, 272388050], [817164150, 126415807]])
A = Matrix([[0, 0, 1], [0, 0, 1], [0, 0, 1]]) # Nilpotent jordan block size 1
assert A**10.0 == Matrix([[0, 0, 1], [0, 0, 1], [0, 0, 1]])
A = Matrix([[0, 1, 0], [0, 0, 1], [0, 0, 1]]) # Nilpotent jordan block size 2
assert A**10.0 == Matrix([[0, 0, 1], [0, 0, 1], [0, 0, 1]])
n = Symbol('n', integer=True)
assert isinstance(A**n, MatPow)
n = Symbol('n', integer=True, negative=True)
raises(ValueError, lambda: A**n)
n = Symbol('n', integer=True, nonnegative=True)
assert A**n == Matrix([
[KroneckerDelta(0, n), KroneckerDelta(1, n), -KroneckerDelta(0, n) - KroneckerDelta(1, n) + 1],
[ 0, KroneckerDelta(0, n), 1 - KroneckerDelta(0, n)],
[ 0, 0, 1]])
assert A**(n + 2) == Matrix([[0, 0, 1], [0, 0, 1], [0, 0, 1]])
raises(ValueError, lambda: A**Rational(3, 2))
A = Matrix([[0, 0, 1], [3, 0, 1], [4, 3, 1]])
assert A**5.0 == Matrix([[168, 72, 89], [291, 144, 161], [572, 267, 329]])
assert A**5.0 == A**5
A = Matrix([[0, 1, 0],[-1, 0, 0],[0, 0, 0]])
n = Symbol("n")
An = A**n
assert An.subs(n, 2).doit() == A**2
raises(ValueError, lambda: An.subs(n, -2).doit())
assert An * An == A**(2*n)
# concretizing behavior for non-integer and complex powers
A = Matrix([[0,0,0],[0,0,0],[0,0,0]])
n = Symbol('n', integer=True, positive=True)
assert A**n == A
n = Symbol('n', integer=True, nonnegative=True)
assert A**n == diag(0**n, 0**n, 0**n)
assert (A**n).subs(n, 0) == eye(3)
assert (A**n).subs(n, 1) == zeros(3)
A = Matrix ([[2,0,0],[0,2,0],[0,0,2]])
assert A**2.1 == diag (2**2.1, 2**2.1, 2**2.1)
assert A**I == diag (2**I, 2**I, 2**I)
A = Matrix([[0, 1, 0], [0, 0, 1], [0, 0, 1]])
raises(ValueError, lambda: A**2.1)
raises(ValueError, lambda: A**I)
A = Matrix([[S.Half, S.Half], [S.Half, S.Half]])
assert A**S.Half == A
A = Matrix([[1, 1],[3, 3]])
assert A**S.Half == Matrix ([[S.Half, S.Half], [3*S.Half, 3*S.Half]])
def test_issue_17247_expression_blowup_1():
M = Matrix([[1+x, 1-x], [1-x, 1+x]])
with dotprodsimp(True):
assert M.exp().expand() == Matrix([
[ (exp(2*x) + exp(2))/2, (-exp(2*x) + exp(2))/2],
[(-exp(2*x) + exp(2))/2, (exp(2*x) + exp(2))/2]])
def test_issue_17247_expression_blowup_2():
M = Matrix([[1+x, 1-x], [1-x, 1+x]])
with dotprodsimp(True):
P, J = M.jordan_form ()
assert P*J*P.inv()
def test_issue_17247_expression_blowup_3():
M = Matrix([[1+x, 1-x], [1-x, 1+x]])
with dotprodsimp(True):
assert M**100 == Matrix([
[633825300114114700748351602688*x**100 + 633825300114114700748351602688, 633825300114114700748351602688 - 633825300114114700748351602688*x**100],
[633825300114114700748351602688 - 633825300114114700748351602688*x**100, 633825300114114700748351602688*x**100 + 633825300114114700748351602688]])
def test_issue_17247_expression_blowup_4():
# This matrix takes extremely long on current master even with intermediate simplification so an abbreviated version is used. It is left here for test in case of future optimizations.
# M = Matrix(S('''[
# [ -3/4, 45/32 - 37*I/16, 1/4 + I/2, -129/64 - 9*I/64, 1/4 - 5*I/16, 65/128 + 87*I/64, -9/32 - I/16, 183/256 - 97*I/128, 3/64 + 13*I/64, -23/32 - 59*I/256, 15/128 - 3*I/32, 19/256 + 551*I/1024],
# [-149/64 + 49*I/32, -177/128 - 1369*I/128, 125/64 + 87*I/64, -2063/256 + 541*I/128, 85/256 - 33*I/16, 805/128 + 2415*I/512, -219/128 + 115*I/256, 6301/4096 - 6609*I/1024, 119/128 + 143*I/128, -10879/2048 + 4343*I/4096, 129/256 - 549*I/512, 42533/16384 + 29103*I/8192],
# [ 1/2 - I, 9/4 + 55*I/16, -3/4, 45/32 - 37*I/16, 1/4 + I/2, -129/64 - 9*I/64, 1/4 - 5*I/16, 65/128 + 87*I/64, -9/32 - I/16, 183/256 - 97*I/128, 3/64 + 13*I/64, -23/32 - 59*I/256],
# [ -5/8 - 39*I/16, 2473/256 + 137*I/64, -149/64 + 49*I/32, -177/128 - 1369*I/128, 125/64 + 87*I/64, -2063/256 + 541*I/128, 85/256 - 33*I/16, 805/128 + 2415*I/512, -219/128 + 115*I/256, 6301/4096 - 6609*I/1024, 119/128 + 143*I/128, -10879/2048 + 4343*I/4096],
# [ 1 + I, -19/4 + 5*I/4, 1/2 - I, 9/4 + 55*I/16, -3/4, 45/32 - 37*I/16, 1/4 + I/2, -129/64 - 9*I/64, 1/4 - 5*I/16, 65/128 + 87*I/64, -9/32 - I/16, 183/256 - 97*I/128],
# [ 21/8 + I, -537/64 + 143*I/16, -5/8 - 39*I/16, 2473/256 + 137*I/64, -149/64 + 49*I/32, -177/128 - 1369*I/128, 125/64 + 87*I/64, -2063/256 + 541*I/128, 85/256 - 33*I/16, 805/128 + 2415*I/512, -219/128 + 115*I/256, 6301/4096 - 6609*I/1024],
# [ -2, 17/4 - 13*I/2, 1 + I, -19/4 + 5*I/4, 1/2 - I, 9/4 + 55*I/16, -3/4, 45/32 - 37*I/16, 1/4 + I/2, -129/64 - 9*I/64, 1/4 - 5*I/16, 65/128 + 87*I/64],
# [ 1/4 + 13*I/4, -825/64 - 147*I/32, 21/8 + I, -537/64 + 143*I/16, -5/8 - 39*I/16, 2473/256 + 137*I/64, -149/64 + 49*I/32, -177/128 - 1369*I/128, 125/64 + 87*I/64, -2063/256 + 541*I/128, 85/256 - 33*I/16, 805/128 + 2415*I/512],
# [ -4*I, 27/2 + 6*I, -2, 17/4 - 13*I/2, 1 + I, -19/4 + 5*I/4, 1/2 - I, 9/4 + 55*I/16, -3/4, 45/32 - 37*I/16, 1/4 + I/2, -129/64 - 9*I/64],
# [ 1/4 + 5*I/2, -23/8 - 57*I/16, 1/4 + 13*I/4, -825/64 - 147*I/32, 21/8 + I, -537/64 + 143*I/16, -5/8 - 39*I/16, 2473/256 + 137*I/64, -149/64 + 49*I/32, -177/128 - 1369*I/128, 125/64 + 87*I/64, -2063/256 + 541*I/128],
# [ -4, 9 - 5*I, -4*I, 27/2 + 6*I, -2, 17/4 - 13*I/2, 1 + I, -19/4 + 5*I/4, 1/2 - I, 9/4 + 55*I/16, -3/4, 45/32 - 37*I/16],
# [ -2*I, 119/8 + 29*I/4, 1/4 + 5*I/2, -23/8 - 57*I/16, 1/4 + 13*I/4, -825/64 - 147*I/32, 21/8 + I, -537/64 + 143*I/16, -5/8 - 39*I/16, 2473/256 + 137*I/64, -149/64 + 49*I/32, -177/128 - 1369*I/128]]'''))
# assert M**10 == Matrix([
# [ 7*(-221393644768594642173548179825793834595 - 1861633166167425978847110897013541127952*I)/9671406556917033397649408, 15*(31670992489131684885307005100073928751695 + 10329090958303458811115024718207404523808*I)/77371252455336267181195264, 7*(-3710978679372178839237291049477017392703 + 1377706064483132637295566581525806894169*I)/19342813113834066795298816, (9727707023582419994616144751727760051598 - 59261571067013123836477348473611225724433*I)/9671406556917033397649408, (31896723509506857062605551443641668183707 + 54643444538699269118869436271152084599580*I)/38685626227668133590597632, (-2024044860947539028275487595741003997397402 + 130959428791783397562960461903698670485863*I)/309485009821345068724781056, 3*(26190251453797590396533756519358368860907 - 27221191754180839338002754608545400941638*I)/77371252455336267181195264, (1154643595139959842768960128434994698330461 + 3385496216250226964322872072260446072295634*I)/618970019642690137449562112, 3*(-31849347263064464698310044805285774295286 - 11877437776464148281991240541742691164309*I)/77371252455336267181195264, (4661330392283532534549306589669150228040221 - 4171259766019818631067810706563064103956871*I)/1237940039285380274899124224, (9598353794289061833850770474812760144506 + 358027153990999990968244906482319780943983*I)/309485009821345068724781056, (-9755135335127734571547571921702373498554177 - 4837981372692695195747379349593041939686540*I)/2475880078570760549798248448],
# [(-379516731607474268954110071392894274962069 - 422272153179747548473724096872271700878296*I)/77371252455336267181195264, (41324748029613152354787280677832014263339501 - 12715121258662668420833935373453570749288074*I)/1237940039285380274899124224, (-339216903907423793947110742819264306542397 + 494174755147303922029979279454787373566517*I)/77371252455336267181195264, (-18121350839962855576667529908850640619878381 - 37413012454129786092962531597292531089199003*I)/1237940039285380274899124224, (2489661087330511608618880408199633556675926 + 1137821536550153872137379935240732287260863*I)/309485009821345068724781056, (-136644109701594123227587016790354220062972119 + 110130123468183660555391413889600443583585272*I)/4951760157141521099596496896, (1488043981274920070468141664150073426459593 - 9691968079933445130866371609614474474327650*I)/1237940039285380274899124224, 27*(4636797403026872518131756991410164760195942 + 3369103221138229204457272860484005850416533*I)/4951760157141521099596496896, (-8534279107365915284081669381642269800472363 + 2241118846262661434336333368511372725482742*I)/1237940039285380274899124224, (60923350128174260992536531692058086830950875 - 263673488093551053385865699805250505661590126*I)/9903520314283042199192993792, (18520943561240714459282253753348921824172569 + 24846649186468656345966986622110971925703604*I)/4951760157141521099596496896, (-232781130692604829085973604213529649638644431 + 35981505277760667933017117949103953338570617*I)/9903520314283042199192993792],
# [ (8742968295129404279528270438201520488950 + 3061473358639249112126847237482570858327*I)/4835703278458516698824704, (-245657313712011778432792959787098074935273 + 253113767861878869678042729088355086740856*I)/38685626227668133590597632, (1947031161734702327107371192008011621193 - 19462330079296259148177542369999791122762*I)/9671406556917033397649408, (552856485625209001527688949522750288619217 + 392928441196156725372494335248099016686580*I)/77371252455336267181195264, (-44542866621905323121630214897126343414629 + 3265340021421335059323962377647649632959*I)/19342813113834066795298816, (136272594005759723105646069956434264218730 - 330975364731707309489523680957584684763587*I)/38685626227668133590597632, (27392593965554149283318732469825168894401 + 75157071243800133880129376047131061115278*I)/38685626227668133590597632, 7*(-357821652913266734749960136017214096276154 - 45509144466378076475315751988405961498243*I)/309485009821345068724781056, (104485001373574280824835174390219397141149 - 99041000529599568255829489765415726168162*I)/77371252455336267181195264, (1198066993119982409323525798509037696321291 + 4249784165667887866939369628840569844519936*I)/618970019642690137449562112, (-114985392587849953209115599084503853611014 - 52510376847189529234864487459476242883449*I)/77371252455336267181195264, (6094620517051332877965959223269600650951573 - 4683469779240530439185019982269137976201163*I)/1237940039285380274899124224],
# [ (611292255597977285752123848828590587708323 - 216821743518546668382662964473055912169502*I)/77371252455336267181195264, (-1144023204575811464652692396337616594307487 + 12295317806312398617498029126807758490062855*I)/309485009821345068724781056, (-374093027769390002505693378578475235158281 - 573533923565898290299607461660384634333639*I)/77371252455336267181195264, (47405570632186659000138546955372796986832987 - 2837476058950808941605000274055970055096534*I)/1237940039285380274899124224, (-571573207393621076306216726219753090535121 + 533381457185823100878764749236639320783831*I)/77371252455336267181195264, (-7096548151856165056213543560958582513797519 - 24035731898756040059329175131592138642195366*I)/618970019642690137449562112, (2396762128833271142000266170154694033849225 + 1448501087375679588770230529017516492953051*I)/309485009821345068724781056, (-150609293845161968447166237242456473262037053 + 92581148080922977153207018003184520294188436*I)/4951760157141521099596496896, 5*(270278244730804315149356082977618054486347 - 1997830155222496880429743815321662710091562*I)/1237940039285380274899124224, (62978424789588828258068912690172109324360330 + 44803641177219298311493356929537007630129097*I)/2475880078570760549798248448, 19*(-451431106327656743945775812536216598712236 + 114924966793632084379437683991151177407937*I)/1237940039285380274899124224, (63417747628891221594106738815256002143915995 - 261508229397507037136324178612212080871150958*I)/9903520314283042199192993792],
# [ (-2144231934021288786200752920446633703357 + 2305614436009705803670842248131563850246*I)/1208925819614629174706176, (-90720949337459896266067589013987007078153 - 221951119475096403601562347412753844534569*I)/19342813113834066795298816, (11590973613116630788176337262688659880376 + 6514520676308992726483494976339330626159*I)/4835703278458516698824704, 3*(-131776217149000326618649542018343107657237 + 79095042939612668486212006406818285287004*I)/38685626227668133590597632, (10100577916793945997239221374025741184951 - 28631383488085522003281589065994018550748*I)/9671406556917033397649408, 67*(10090295594251078955008130473573667572549 + 10449901522697161049513326446427839676762*I)/77371252455336267181195264, (-54270981296988368730689531355811033930513 - 3413683117592637309471893510944045467443*I)/19342813113834066795298816, (440372322928679910536575560069973699181278 - 736603803202303189048085196176918214409081*I)/77371252455336267181195264, (33220374714789391132887731139763250155295 + 92055083048787219934030779066298919603554*I)/38685626227668133590597632, 5*(-594638554579967244348856981610805281527116 - 82309245323128933521987392165716076704057*I)/309485009821345068724781056, (128056368815300084550013708313312073721955 - 114619107488668120303579745393765245911404*I)/77371252455336267181195264, 21*(59839959255173222962789517794121843393573 + 241507883613676387255359616163487405826334*I)/618970019642690137449562112],
# [ (-13454485022325376674626653802541391955147 + 184471402121905621396582628515905949793486*I)/19342813113834066795298816, (-6158730123400322562149780662133074862437105 - 3416173052604643794120262081623703514107476*I)/154742504910672534362390528, (770558003844914708453618983120686116100419 - 127758381209767638635199674005029818518766*I)/77371252455336267181195264, (-4693005771813492267479835161596671660631703 + 12703585094750991389845384539501921531449948*I)/309485009821345068724781056, (-295028157441149027913545676461260860036601 - 841544569970643160358138082317324743450770*I)/77371252455336267181195264, (56716442796929448856312202561538574275502893 + 7216818824772560379753073185990186711454778*I)/1237940039285380274899124224, 15*(-87061038932753366532685677510172566368387 + 61306141156647596310941396434445461895538*I)/154742504910672534362390528, (-3455315109680781412178133042301025723909347 - 24969329563196972466388460746447646686670670*I)/618970019642690137449562112, (2453418854160886481106557323699250865361849 + 1497886802326243014471854112161398141242514*I)/309485009821345068724781056, (-151343224544252091980004429001205664193082173 + 90471883264187337053549090899816228846836628*I)/4951760157141521099596496896, (1652018205533026103358164026239417416432989 - 9959733619236515024261775397109724431400162*I)/1237940039285380274899124224, 3*(40676374242956907656984876692623172736522006 + 31023357083037817469535762230872667581366205*I)/4951760157141521099596496896],
# [ (-1226990509403328460274658603410696548387 - 4131739423109992672186585941938392788458*I)/1208925819614629174706176, (162392818524418973411975140074368079662703 + 23706194236915374831230612374344230400704*I)/9671406556917033397649408, (-3935678233089814180000602553655565621193 + 2283744757287145199688061892165659502483*I)/1208925819614629174706176, (-2400210250844254483454290806930306285131 - 315571356806370996069052930302295432758205*I)/19342813113834066795298816, (13365917938215281056563183751673390817910 + 15911483133819801118348625831132324863881*I)/4835703278458516698824704, 3*(-215950551370668982657516660700301003897855 + 51684341999223632631602864028309400489378*I)/38685626227668133590597632, (20886089946811765149439844691320027184765 - 30806277083146786592790625980769214361844*I)/9671406556917033397649408, (562180634592713285745940856221105667874855 + 1031543963988260765153550559766662245114916*I)/77371252455336267181195264, (-65820625814810177122941758625652476012867 - 12429918324787060890804395323920477537595*I)/19342813113834066795298816, (319147848192012911298771180196635859221089 - 402403304933906769233365689834404519960394*I)/38685626227668133590597632, (23035615120921026080284733394359587955057 + 115351677687031786114651452775242461310624*I)/38685626227668133590597632, (-3426830634881892756966440108592579264936130 - 1022954961164128745603407283836365128598559*I)/309485009821345068724781056],
# [ (-192574788060137531023716449082856117537757 - 69222967328876859586831013062387845780692*I)/19342813113834066795298816, (2736383768828013152914815341491629299773262 - 2773252698016291897599353862072533475408743*I)/77371252455336267181195264, (-23280005281223837717773057436155921656805 + 214784953368021840006305033048142888879224*I)/19342813113834066795298816, (-3035247484028969580570400133318947903462326 - 2195168903335435855621328554626336958674325*I)/77371252455336267181195264, (984552428291526892214541708637840971548653 - 64006622534521425620714598573494988589378*I)/77371252455336267181195264, (-3070650452470333005276715136041262898509903 + 7286424705750810474140953092161794621989080*I)/154742504910672534362390528, (-147848877109756404594659513386972921139270 - 416306113044186424749331418059456047650861*I)/38685626227668133590597632, (55272118474097814260289392337160619494260781 + 7494019668394781211907115583302403519488058*I)/1237940039285380274899124224, (-581537886583682322424771088996959213068864 + 542191617758465339135308203815256798407429*I)/77371252455336267181195264, (-6422548983676355789975736799494791970390991 - 23524183982209004826464749309156698827737702*I)/618970019642690137449562112, 7*(180747195387024536886923192475064903482083 + 84352527693562434817771649853047924991804*I)/154742504910672534362390528, (-135485179036717001055310712747643466592387031 + 102346575226653028836678855697782273460527608*I)/4951760157141521099596496896],
# [ (3384238362616083147067025892852431152105 + 156724444932584900214919898954874618256*I)/604462909807314587353088, (-59558300950677430189587207338385764871866 + 114427143574375271097298201388331237478857*I)/4835703278458516698824704, (-1356835789870635633517710130971800616227 - 7023484098542340388800213478357340875410*I)/1208925819614629174706176, (234884918567993750975181728413524549575881 + 79757294640629983786895695752733890213506*I)/9671406556917033397649408, (-7632732774935120473359202657160313866419 + 2905452608512927560554702228553291839465*I)/1208925819614629174706176, (52291747908702842344842889809762246649489 - 520996778817151392090736149644507525892649*I)/19342813113834066795298816, (17472406829219127839967951180375981717322 + 23464704213841582137898905375041819568669*I)/4835703278458516698824704, (-911026971811893092350229536132730760943307 + 150799318130900944080399439626714846752360*I)/38685626227668133590597632, (26234457233977042811089020440646443590687 - 45650293039576452023692126463683727692890*I)/9671406556917033397649408, 3*(288348388717468992528382586652654351121357 + 454526517721403048270274049572136109264668*I)/77371252455336267181195264, (-91583492367747094223295011999405657956347 - 12704691128268298435362255538069612411331*I)/19342813113834066795298816, (411208730251327843849027957710164064354221 - 569898526380691606955496789378230959965898*I)/38685626227668133590597632],
# [ (27127513117071487872628354831658811211795 - 37765296987901990355760582016892124833857*I)/4835703278458516698824704, (1741779916057680444272938534338833170625435 + 3083041729779495966997526404685535449810378*I)/77371252455336267181195264, 3*(-60642236251815783728374561836962709533401 - 24630301165439580049891518846174101510744*I)/19342813113834066795298816, 3*(445885207364591681637745678755008757483408 - 350948497734812895032502179455610024541643*I)/38685626227668133590597632, (-47373295621391195484367368282471381775684 + 219122969294089357477027867028071400054973*I)/19342813113834066795298816, (-2801565819673198722993348253876353741520438 - 2250142129822658548391697042460298703335701*I)/77371252455336267181195264, (801448252275607253266997552356128790317119 - 50890367688077858227059515894356594900558*I)/77371252455336267181195264, (-5082187758525931944557763799137987573501207 + 11610432359082071866576699236013484487676124*I)/309485009821345068724781056, (-328925127096560623794883760398247685166830 - 643447969697471610060622160899409680422019*I)/77371252455336267181195264, 15*(2954944669454003684028194956846659916299765 + 33434406416888505837444969347824812608566*I)/1237940039285380274899124224, (-415749104352001509942256567958449835766827 + 479330966144175743357171151440020955412219*I)/77371252455336267181195264, 3*(-4639987285852134369449873547637372282914255 - 11994411888966030153196659207284951579243273*I)/1237940039285380274899124224],
# [ (-478846096206269117345024348666145495601 + 1249092488629201351470551186322814883283*I)/302231454903657293676544, (-17749319421930878799354766626365926894989 - 18264580106418628161818752318217357231971*I)/1208925819614629174706176, (2801110795431528876849623279389579072819 + 363258850073786330770713557775566973248*I)/604462909807314587353088, (-59053496693129013745775512127095650616252 + 78143588734197260279248498898321500167517*I)/4835703278458516698824704, (-283186724922498212468162690097101115349 - 6443437753863179883794497936345437398276*I)/1208925819614629174706176, (188799118826748909206887165661384998787543 + 84274736720556630026311383931055307398820*I)/9671406556917033397649408, (-5482217151670072904078758141270295025989 + 1818284338672191024475557065444481298568*I)/1208925819614629174706176, (56564463395350195513805521309731217952281 - 360208541416798112109946262159695452898431*I)/19342813113834066795298816, 11*(1259539805728870739006416869463689438068 + 1409136581547898074455004171305324917387*I)/4835703278458516698824704, 5*(-123701190701414554945251071190688818343325 + 30997157322590424677294553832111902279712*I)/38685626227668133590597632, (16130917381301373033736295883982414239781 - 32752041297570919727145380131926943374516*I)/9671406556917033397649408, (650301385108223834347093740500375498354925 + 899526407681131828596801223402866051809258*I)/77371252455336267181195264],
# [ (9011388245256140876590294262420614839483 + 8167917972423946282513000869327525382672*I)/1208925819614629174706176, (-426393174084720190126376382194036323028924 + 180692224825757525982858693158209545430621*I)/9671406556917033397649408, (24588556702197802674765733448108154175535 - 45091766022876486566421953254051868331066*I)/4835703278458516698824704, (1872113939365285277373877183750416985089691 + 3030392393733212574744122057679633775773130*I)/77371252455336267181195264, (-222173405538046189185754954524429864167549 - 75193157893478637039381059488387511299116*I)/19342813113834066795298816, (2670821320766222522963689317316937579844558 - 2645837121493554383087981511645435472169191*I)/77371252455336267181195264, 5*(-2100110309556476773796963197283876204940 + 41957457246479840487980315496957337371937*I)/19342813113834066795298816, (-5733743755499084165382383818991531258980593 - 3328949988392698205198574824396695027195732*I)/154742504910672534362390528, (707827994365259025461378911159398206329247 - 265730616623227695108042528694302299777294*I)/77371252455336267181195264, (-1442501604682933002895864804409322823788319 + 11504137805563265043376405214378288793343879*I)/309485009821345068724781056, (-56130472299445561499538726459719629522285 - 61117552419727805035810982426639329818864*I)/9671406556917033397649408, (39053692321126079849054272431599539429908717 - 10209127700342570953247177602860848130710666*I)/1237940039285380274899124224]])
M = Matrix(S('''[
[ -3/4, 45/32 - 37*I/16, 1/4 + I/2, -129/64 - 9*I/64, 1/4 - 5*I/16, 65/128 + 87*I/64],
[-149/64 + 49*I/32, -177/128 - 1369*I/128, 125/64 + 87*I/64, -2063/256 + 541*I/128, 85/256 - 33*I/16, 805/128 + 2415*I/512],
[ 1/2 - I, 9/4 + 55*I/16, -3/4, 45/32 - 37*I/16, 1/4 + I/2, -129/64 - 9*I/64],
[ -5/8 - 39*I/16, 2473/256 + 137*I/64, -149/64 + 49*I/32, -177/128 - 1369*I/128, 125/64 + 87*I/64, -2063/256 + 541*I/128],
[ 1 + I, -19/4 + 5*I/4, 1/2 - I, 9/4 + 55*I/16, -3/4, 45/32 - 37*I/16],
[ 21/8 + I, -537/64 + 143*I/16, -5/8 - 39*I/16, 2473/256 + 137*I/64, -149/64 + 49*I/32, -177/128 - 1369*I/128]]'''))
with dotprodsimp(True):
assert M**10 == Matrix(S('''[
[ 7369525394972778926719607798014571861/604462909807314587353088 - 229284202061790301477392339912557559*I/151115727451828646838272, -19704281515163975949388435612632058035/1208925819614629174706176 + 14319858347987648723768698170712102887*I/302231454903657293676544, -3623281909451783042932142262164941211/604462909807314587353088 - 6039240602494288615094338643452320495*I/604462909807314587353088, 109260497799140408739847239685705357695/2417851639229258349412352 - 7427566006564572463236368211555511431*I/2417851639229258349412352, -16095803767674394244695716092817006641/2417851639229258349412352 + 10336681897356760057393429626719177583*I/1208925819614629174706176, -42207883340488041844332828574359769743/2417851639229258349412352 - 182332262671671273188016400290188468499*I/4835703278458516698824704],
[50566491050825573392726324995779608259/1208925819614629174706176 - 90047007594468146222002432884052362145*I/2417851639229258349412352, 74273703462900000967697427843983822011/1208925819614629174706176 + 265947522682943571171988741842776095421*I/1208925819614629174706176, -116900341394390200556829767923360888429/2417851639229258349412352 - 53153263356679268823910621474478756845*I/2417851639229258349412352, 195407378023867871243426523048612490249/1208925819614629174706176 - 1242417915995360200584837585002906728929*I/9671406556917033397649408, -863597594389821970177319682495878193/302231454903657293676544 + 476936100741548328800725360758734300481*I/9671406556917033397649408, -3154451590535653853562472176601754835575/19342813113834066795298816 - 232909875490506237386836489998407329215*I/2417851639229258349412352],
[ -1715444997702484578716037230949868543/302231454903657293676544 + 5009695651321306866158517287924120777*I/302231454903657293676544, -30551582497996879620371947949342101301/604462909807314587353088 - 7632518367986526187139161303331519629*I/151115727451828646838272, 312680739924495153190604170938220575/18889465931478580854784 - 108664334509328818765959789219208459*I/75557863725914323419136, -14693696966703036206178521686918865509/604462909807314587353088 + 72345386220900843930147151999899692401*I/1208925819614629174706176, -8218872496728882299722894680635296519/1208925819614629174706176 - 16776782833358893712645864791807664983*I/1208925819614629174706176, 143237839169380078671242929143670635137/2417851639229258349412352 + 2883817094806115974748882735218469447*I/2417851639229258349412352],
[ 3087979417831061365023111800749855987/151115727451828646838272 + 34441942370802869368851419102423997089*I/604462909807314587353088, -148309181940158040917731426845476175667/604462909807314587353088 - 263987151804109387844966835369350904919*I/9671406556917033397649408, 50259518594816377378747711930008883165/1208925819614629174706176 - 95713974916869240305450001443767979653*I/2417851639229258349412352, 153466447023875527996457943521467271119/2417851639229258349412352 + 517285524891117105834922278517084871349*I/2417851639229258349412352, -29184653615412989036678939366291205575/604462909807314587353088 - 27551322282526322041080173287022121083*I/1208925819614629174706176, 196404220110085511863671393922447671649/1208925819614629174706176 - 1204712019400186021982272049902206202145*I/9671406556917033397649408],
[ -2632581805949645784625606590600098779/151115727451828646838272 - 589957435912868015140272627522612771*I/37778931862957161709568, 26727850893953715274702844733506310247/302231454903657293676544 - 10825791956782128799168209600694020481*I/302231454903657293676544, -1036348763702366164044671908440791295/151115727451828646838272 + 3188624571414467767868303105288107375*I/151115727451828646838272, -36814959939970644875593411585393242449/604462909807314587353088 - 18457555789119782404850043842902832647*I/302231454903657293676544, 12454491297984637815063964572803058647/604462909807314587353088 - 340489532842249733975074349495329171*I/302231454903657293676544, -19547211751145597258386735573258916681/604462909807314587353088 + 87299583775782199663414539883938008933*I/1208925819614629174706176],
[ -40281994229560039213253423262678393183/604462909807314587353088 - 2939986850065527327299273003299736641*I/604462909807314587353088, 331940684638052085845743020267462794181/2417851639229258349412352 - 284574901963624403933361315517248458969*I/1208925819614629174706176, 6453843623051745485064693628073010961/302231454903657293676544 + 36062454107479732681350914931391590957*I/604462909807314587353088, -147665869053634695632880753646441962067/604462909807314587353088 - 305987938660447291246597544085345123927*I/9671406556917033397649408, 107821369195275772166593879711259469423/2417851639229258349412352 - 11645185518211204108659001435013326687*I/302231454903657293676544, 64121228424717666402009446088588091619/1208925819614629174706176 + 265557133337095047883844369272389762133*I/1208925819614629174706176]]'''))
def test_issue_17247_expression_blowup_5():
M = Matrix(6, 6, lambda i, j: 1 + (-1)**(i+j)*I)
with dotprodsimp(True):
assert M.charpoly('x') == PurePoly(x**6 + (-6 - 6*I)*x**5 + 36*I*x**4, x, domain='EX')
def test_issue_17247_expression_blowup_6():
M = Matrix(8, 8, [x+i for i in range (64)])
with dotprodsimp(True):
assert M.det('bareiss') == 0
def test_issue_17247_expression_blowup_7():
M = Matrix(6, 6, lambda i, j: 1 + (-1)**(i+j)*I)
with dotprodsimp(True):
assert M.det('berkowitz') == 0
def test_issue_17247_expression_blowup_8():
M = Matrix(8, 8, [x+i for i in range (64)])
with dotprodsimp(True):
assert M.det('lu') == 0
def test_issue_17247_expression_blowup_9():
M = Matrix(8, 8, [x+i for i in range (64)])
with dotprodsimp(True):
assert M.rref() == (Matrix([
[1, 0, -1, -2, -3, -4, -5, -6],
[0, 1, 2, 3, 4, 5, 6, 7],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0]]), (0, 1))
def test_issue_17247_expression_blowup_10():
M = Matrix(6, 6, lambda i, j: 1 + (-1)**(i+j)*I)
with dotprodsimp(True):
assert M.cofactor(0, 0) == 0
def test_issue_17247_expression_blowup_11():
M = Matrix(6, 6, lambda i, j: 1 + (-1)**(i+j)*I)
with dotprodsimp(True):
assert M.cofactor_matrix() == Matrix(6, 6, [0]*36)
def test_issue_17247_expression_blowup_12():
M = Matrix(6, 6, lambda i, j: 1 + (-1)**(i+j)*I)
with dotprodsimp(True):
assert M.eigenvals() == {6: 1, 6*I: 1, 0: 4}
def test_issue_17247_expression_blowup_13():
M = Matrix([
[ 0, 1 - x, x + 1, 1 - x],
[1 - x, x + 1, 0, x + 1],
[ 0, 1 - x, x + 1, 1 - x],
[ 0, 0, 1 - x, 0]])
ev = M.eigenvects()
assert ev[0] == (0, 2, [Matrix([0, -1, 0, 1])])
assert ev[1][0] == x - sqrt(2)*(x - 1) + 1
assert ev[1][1] == 1
assert ev[1][2][0].expand(deep=False, numer=True) == Matrix([
[(-x + sqrt(2)*(x - 1) - 1)/(x - 1)],
[-4*x/(x**2 - 2*x + 1) + (x + 1)*(x - sqrt(2)*(x - 1) + 1)/(x**2 - 2*x + 1)],
[(-x + sqrt(2)*(x - 1) - 1)/(x - 1)],
[1]
])
assert ev[2][0] == x + sqrt(2)*(x - 1) + 1
assert ev[2][1] == 1
assert ev[2][2][0].expand(deep=False, numer=True) == Matrix([
[(-x - sqrt(2)*(x - 1) - 1)/(x - 1)],
[-4*x/(x**2 - 2*x + 1) + (x + 1)*(x + sqrt(2)*(x - 1) + 1)/(x**2 - 2*x + 1)],
[(-x - sqrt(2)*(x - 1) - 1)/(x - 1)],
[1]
])
def test_issue_17247_expression_blowup_14():
M = Matrix(8, 8, ([1+x, 1-x]*4 + [1-x, 1+x]*4)*4)
with dotprodsimp(True):
assert M.echelon_form() == Matrix([
[x + 1, 1 - x, x + 1, 1 - x, x + 1, 1 - x, x + 1, 1 - x],
[ 0, 4*x, 0, 4*x, 0, 4*x, 0, 4*x],
[ 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0]])
def test_issue_17247_expression_blowup_15():
M = Matrix(8, 8, ([1+x, 1-x]*4 + [1-x, 1+x]*4)*4)
with dotprodsimp(True):
assert M.rowspace() == [Matrix([[x + 1, 1 - x, x + 1, 1 - x, x + 1, 1 - x, x + 1, 1 - x]]), Matrix([[0, 4*x, 0, 4*x, 0, 4*x, 0, 4*x]])]
def test_issue_17247_expression_blowup_16():
M = Matrix(8, 8, ([1+x, 1-x]*4 + [1-x, 1+x]*4)*4)
with dotprodsimp(True):
assert M.columnspace() == [Matrix([[x + 1],[1 - x],[x + 1],[1 - x],[x + 1],[1 - x],[x + 1],[1 - x]]), Matrix([[1 - x],[x + 1],[1 - x],[x + 1],[1 - x],[x + 1],[1 - x],[x + 1]])]
def test_issue_17247_expression_blowup_17():
M = Matrix(8, 8, [x+i for i in range (64)])
with dotprodsimp(True):
assert M.nullspace() == [
Matrix([[1],[-2],[1],[0],[0],[0],[0],[0]]),
Matrix([[2],[-3],[0],[1],[0],[0],[0],[0]]),
Matrix([[3],[-4],[0],[0],[1],[0],[0],[0]]),
Matrix([[4],[-5],[0],[0],[0],[1],[0],[0]]),
Matrix([[5],[-6],[0],[0],[0],[0],[1],[0]]),
Matrix([[6],[-7],[0],[0],[0],[0],[0],[1]])]
def test_issue_17247_expression_blowup_18():
M = Matrix(6, 6, ([1+x, 1-x]*3 + [1-x, 1+x]*3)*3)
with dotprodsimp(True):
assert not M.is_nilpotent()
def test_issue_17247_expression_blowup_19():
M = Matrix(S('''[
[ -3/4, 0, 1/4 + I/2, 0],
[ 0, -177/128 - 1369*I/128, 0, -2063/256 + 541*I/128],
[ 1/2 - I, 0, 0, 0],
[ 0, 0, 0, -177/128 - 1369*I/128]]'''))
with dotprodsimp(True):
assert not M.is_diagonalizable()
def test_issue_17247_expression_blowup_20():
M = Matrix([
[x + 1, 1 - x, 0, 0],
[1 - x, x + 1, 0, x + 1],
[ 0, 1 - x, x + 1, 0],
[ 0, 0, 0, x + 1]])
with dotprodsimp(True):
assert M.diagonalize() == (Matrix([
[1, 1, 0, (x + 1)/(x - 1)],
[1, -1, 0, 0],
[1, 1, 1, 0],
[0, 0, 0, 1]]),
Matrix([
[2, 0, 0, 0],
[0, 2*x, 0, 0],
[0, 0, x + 1, 0],
[0, 0, 0, x + 1]]))
def test_issue_17247_expression_blowup_21():
M = Matrix(S('''[
[ -3/4, 45/32 - 37*I/16, 0, 0],
[-149/64 + 49*I/32, -177/128 - 1369*I/128, 0, -2063/256 + 541*I/128],
[ 0, 9/4 + 55*I/16, 2473/256 + 137*I/64, 0],
[ 0, 0, 0, -177/128 - 1369*I/128]]'''))
with dotprodsimp(True):
assert M.inv(method='GE') == Matrix(S('''[
[-26194832/3470993 - 31733264*I/3470993, 156352/3470993 + 10325632*I/3470993, 0, -7741283181072/3306971225785 + 2999007604624*I/3306971225785],
[4408224/3470993 - 9675328*I/3470993, -2422272/3470993 + 1523712*I/3470993, 0, -1824666489984/3306971225785 - 1401091949952*I/3306971225785],
[-26406945676288/22270005630769 + 10245925485056*I/22270005630769, 7453523312640/22270005630769 + 1601616519168*I/22270005630769, 633088/6416033 - 140288*I/6416033, 872209227109521408/21217636514687010905 + 6066405081802389504*I/21217636514687010905],
[0, 0, 0, -11328/952745 + 87616*I/952745]]'''))
def test_issue_17247_expression_blowup_22():
M = Matrix(S('''[
[ -3/4, 45/32 - 37*I/16, 0, 0],
[-149/64 + 49*I/32, -177/128 - 1369*I/128, 0, -2063/256 + 541*I/128],
[ 0, 9/4 + 55*I/16, 2473/256 + 137*I/64, 0],
[ 0, 0, 0, -177/128 - 1369*I/128]]'''))
with dotprodsimp(True):
assert M.inv(method='LU') == Matrix(S('''[
[-26194832/3470993 - 31733264*I/3470993, 156352/3470993 + 10325632*I/3470993, 0, -7741283181072/3306971225785 + 2999007604624*I/3306971225785],
[4408224/3470993 - 9675328*I/3470993, -2422272/3470993 + 1523712*I/3470993, 0, -1824666489984/3306971225785 - 1401091949952*I/3306971225785],
[-26406945676288/22270005630769 + 10245925485056*I/22270005630769, 7453523312640/22270005630769 + 1601616519168*I/22270005630769, 633088/6416033 - 140288*I/6416033, 872209227109521408/21217636514687010905 + 6066405081802389504*I/21217636514687010905],
[0, 0, 0, -11328/952745 + 87616*I/952745]]'''))
def test_issue_17247_expression_blowup_23():
M = Matrix(S('''[
[ -3/4, 45/32 - 37*I/16, 0, 0],
[-149/64 + 49*I/32, -177/128 - 1369*I/128, 0, -2063/256 + 541*I/128],
[ 0, 9/4 + 55*I/16, 2473/256 + 137*I/64, 0],
[ 0, 0, 0, -177/128 - 1369*I/128]]'''))
with dotprodsimp(True):
assert M.inv(method='ADJ').expand() == Matrix(S('''[
[-26194832/3470993 - 31733264*I/3470993, 156352/3470993 + 10325632*I/3470993, 0, -7741283181072/3306971225785 + 2999007604624*I/3306971225785],
[4408224/3470993 - 9675328*I/3470993, -2422272/3470993 + 1523712*I/3470993, 0, -1824666489984/3306971225785 - 1401091949952*I/3306971225785],
[-26406945676288/22270005630769 + 10245925485056*I/22270005630769, 7453523312640/22270005630769 + 1601616519168*I/22270005630769, 633088/6416033 - 140288*I/6416033, 872209227109521408/21217636514687010905 + 6066405081802389504*I/21217636514687010905],
[0, 0, 0, -11328/952745 + 87616*I/952745]]'''))
def test_issue_17247_expression_blowup_24():
M = SparseMatrix(S('''[
[ -3/4, 45/32 - 37*I/16, 0, 0],
[-149/64 + 49*I/32, -177/128 - 1369*I/128, 0, -2063/256 + 541*I/128],
[ 0, 9/4 + 55*I/16, 2473/256 + 137*I/64, 0],
[ 0, 0, 0, -177/128 - 1369*I/128]]'''))
with dotprodsimp(True):
assert M.inv(method='CH') == Matrix(S('''[
[-26194832/3470993 - 31733264*I/3470993, 156352/3470993 + 10325632*I/3470993, 0, -7741283181072/3306971225785 + 2999007604624*I/3306971225785],
[4408224/3470993 - 9675328*I/3470993, -2422272/3470993 + 1523712*I/3470993, 0, -1824666489984/3306971225785 - 1401091949952*I/3306971225785],
[-26406945676288/22270005630769 + 10245925485056*I/22270005630769, 7453523312640/22270005630769 + 1601616519168*I/22270005630769, 633088/6416033 - 140288*I/6416033, 872209227109521408/21217636514687010905 + 6066405081802389504*I/21217636514687010905],
[0, 0, 0, -11328/952745 + 87616*I/952745]]'''))
def test_issue_17247_expression_blowup_25():
M = SparseMatrix(S('''[
[ -3/4, 45/32 - 37*I/16, 0, 0],
[-149/64 + 49*I/32, -177/128 - 1369*I/128, 0, -2063/256 + 541*I/128],
[ 0, 9/4 + 55*I/16, 2473/256 + 137*I/64, 0],
[ 0, 0, 0, -177/128 - 1369*I/128]]'''))
with dotprodsimp(True):
assert M.inv(method='LDL') == Matrix(S('''[
[-26194832/3470993 - 31733264*I/3470993, 156352/3470993 + 10325632*I/3470993, 0, -7741283181072/3306971225785 + 2999007604624*I/3306971225785],
[4408224/3470993 - 9675328*I/3470993, -2422272/3470993 + 1523712*I/3470993, 0, -1824666489984/3306971225785 - 1401091949952*I/3306971225785],
[-26406945676288/22270005630769 + 10245925485056*I/22270005630769, 7453523312640/22270005630769 + 1601616519168*I/22270005630769, 633088/6416033 - 140288*I/6416033, 872209227109521408/21217636514687010905 + 6066405081802389504*I/21217636514687010905],
[0, 0, 0, -11328/952745 + 87616*I/952745]]'''))
def test_issue_17247_expression_blowup_26():
M = Matrix(S('''[
[ -3/4, 45/32 - 37*I/16, 1/4 + I/2, -129/64 - 9*I/64, 1/4 - 5*I/16, 65/128 + 87*I/64, -9/32 - I/16, 183/256 - 97*I/128],
[-149/64 + 49*I/32, -177/128 - 1369*I/128, 125/64 + 87*I/64, -2063/256 + 541*I/128, 85/256 - 33*I/16, 805/128 + 2415*I/512, -219/128 + 115*I/256, 6301/4096 - 6609*I/1024],
[ 1/2 - I, 9/4 + 55*I/16, -3/4, 45/32 - 37*I/16, 1/4 + I/2, -129/64 - 9*I/64, 1/4 - 5*I/16, 65/128 + 87*I/64],
[ -5/8 - 39*I/16, 2473/256 + 137*I/64, -149/64 + 49*I/32, -177/128 - 1369*I/128, 125/64 + 87*I/64, -2063/256 + 541*I/128, 85/256 - 33*I/16, 805/128 + 2415*I/512],
[ 1 + I, -19/4 + 5*I/4, 1/2 - I, 9/4 + 55*I/16, -3/4, 45/32 - 37*I/16, 1/4 + I/2, -129/64 - 9*I/64],
[ 21/8 + I, -537/64 + 143*I/16, -5/8 - 39*I/16, 2473/256 + 137*I/64, -149/64 + 49*I/32, -177/128 - 1369*I/128, 125/64 + 87*I/64, -2063/256 + 541*I/128],
[ -2, 17/4 - 13*I/2, 1 + I, -19/4 + 5*I/4, 1/2 - I, 9/4 + 55*I/16, -3/4, 45/32 - 37*I/16],
[ 1/4 + 13*I/4, -825/64 - 147*I/32, 21/8 + I, -537/64 + 143*I/16, -5/8 - 39*I/16, 2473/256 + 137*I/64, -149/64 + 49*I/32, -177/128 - 1369*I/128]]'''))
with dotprodsimp(True):
assert M.rank() == 4
def test_issue_17247_expression_blowup_27():
M = Matrix([
[ 0, 1 - x, x + 1, 1 - x],
[1 - x, x + 1, 0, x + 1],
[ 0, 1 - x, x + 1, 1 - x],
[ 0, 0, 1 - x, 0]])
with dotprodsimp(True):
P, J = M.jordan_form()
assert P.expand() == Matrix(S('''[
[ 0, 4*x/(x**2 - 2*x + 1), -(-17*x**4 + 12*sqrt(2)*x**4 - 4*sqrt(2)*x**3 + 6*x**3 - 6*x - 4*sqrt(2)*x + 12*sqrt(2) + 17)/(-7*x**4 + 5*sqrt(2)*x**4 - 6*sqrt(2)*x**3 + 8*x**3 - 2*x**2 + 8*x + 6*sqrt(2)*x - 5*sqrt(2) - 7), -(12*sqrt(2)*x**4 + 17*x**4 - 6*x**3 - 4*sqrt(2)*x**3 - 4*sqrt(2)*x + 6*x - 17 + 12*sqrt(2))/(7*x**4 + 5*sqrt(2)*x**4 - 6*sqrt(2)*x**3 - 8*x**3 + 2*x**2 - 8*x + 6*sqrt(2)*x - 5*sqrt(2) + 7)],
[x - 1, x/(x - 1) + 1/(x - 1), (-7*x**3 + 5*sqrt(2)*x**3 - x**2 + sqrt(2)*x**2 - sqrt(2)*x - x - 5*sqrt(2) - 7)/(-3*x**3 + 2*sqrt(2)*x**3 - 2*sqrt(2)*x**2 + 3*x**2 + 2*sqrt(2)*x + 3*x - 3 - 2*sqrt(2)), (7*x**3 + 5*sqrt(2)*x**3 + x**2 + sqrt(2)*x**2 - sqrt(2)*x + x - 5*sqrt(2) + 7)/(2*sqrt(2)*x**3 + 3*x**3 - 3*x**2 - 2*sqrt(2)*x**2 - 3*x + 2*sqrt(2)*x - 2*sqrt(2) + 3)],
[ 0, 1, -(-3*x**2 + 2*sqrt(2)*x**2 + 2*x - 3 - 2*sqrt(2))/(-x**2 + sqrt(2)*x**2 - 2*sqrt(2)*x + 1 + sqrt(2)), -(2*sqrt(2)*x**2 + 3*x**2 - 2*x - 2*sqrt(2) + 3)/(x**2 + sqrt(2)*x**2 - 2*sqrt(2)*x - 1 + sqrt(2))],
[1 - x, 0, 1, 1]]''')).expand()
assert J == Matrix(S('''[
[0, 1, 0, 0],
[0, 0, 0, 0],
[0, 0, x - sqrt(2)*(x - 1) + 1, 0],
[0, 0, 0, x + sqrt(2)*(x - 1) + 1]]'''))
def test_issue_17247_expression_blowup_28():
M = Matrix(S('''[
[ -3/4, 45/32 - 37*I/16, 0, 0],
[-149/64 + 49*I/32, -177/128 - 1369*I/128, 0, -2063/256 + 541*I/128],
[ 0, 9/4 + 55*I/16, 2473/256 + 137*I/64, 0],
[ 0, 0, 0, -177/128 - 1369*I/128]]'''))
with dotprodsimp(True):
assert M.singular_values() == S('''[
sqrt(14609315/131072 + sqrt(64789115132571/2147483648 - 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3) + 76627253330829751075/(35184372088832*sqrt(64789115132571/4294967296 + 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)) + 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3))) - 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)))/2 + sqrt(64789115132571/4294967296 + 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)) + 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3))/2),
sqrt(14609315/131072 - sqrt(64789115132571/2147483648 - 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3) + 76627253330829751075/(35184372088832*sqrt(64789115132571/4294967296 + 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)) + 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3))) - 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)))/2 + sqrt(64789115132571/4294967296 + 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)) + 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3))/2),
sqrt(14609315/131072 - sqrt(64789115132571/4294967296 + 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)) + 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3))/2 + sqrt(64789115132571/2147483648 - 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3) - 76627253330829751075/(35184372088832*sqrt(64789115132571/4294967296 + 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)) + 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3))) - 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)))/2),
sqrt(14609315/131072 - sqrt(64789115132571/4294967296 + 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)) + 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3))/2 - sqrt(64789115132571/2147483648 - 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3) - 76627253330829751075/(35184372088832*sqrt(64789115132571/4294967296 + 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)) + 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3))) - 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)))/2)]''')
def test_issue_16823():
# This still needs to be fixed if not using dotprodsimp.
M = Matrix(S('''[
[1+I,-19/4+5/4*I,1/2-I,9/4+55/16*I,-3/4,45/32-37/16*I,1/4+1/2*I,-129/64-9/64*I,1/4-5/16*I,65/128+87/64*I,-9/32-1/16*I,183/256-97/128*I,3/64+13/64*I,-23/32-59/256*I,15/128-3/32*I,19/256+551/1024*I],
[21/8+I,-537/64+143/16*I,-5/8-39/16*I,2473/256+137/64*I,-149/64+49/32*I,-177/128-1369/128*I,125/64+87/64*I,-2063/256+541/128*I,85/256-33/16*I,805/128+2415/512*I,-219/128+115/256*I,6301/4096-6609/1024*I,119/128+143/128*I,-10879/2048+4343/4096*I,129/256-549/512*I,42533/16384+29103/8192*I],
[-2,17/4-13/2*I,1+I,-19/4+5/4*I,1/2-I,9/4+55/16*I,-3/4,45/32-37/16*I,1/4+1/2*I,-129/64-9/64*I,1/4-5/16*I,65/128+87/64*I,-9/32-1/16*I,183/256-97/128*I,3/64+13/64*I,-23/32-59/256*I],
[1/4+13/4*I,-825/64-147/32*I,21/8+I,-537/64+143/16*I,-5/8-39/16*I,2473/256+137/64*I,-149/64+49/32*I,-177/128-1369/128*I,125/64+87/64*I,-2063/256+541/128*I,85/256-33/16*I,805/128+2415/512*I,-219/128+115/256*I,6301/4096-6609/1024*I,119/128+143/128*I,-10879/2048+4343/4096*I],
[-4*I,27/2+6*I,-2,17/4-13/2*I,1+I,-19/4+5/4*I,1/2-I,9/4+55/16*I,-3/4,45/32-37/16*I,1/4+1/2*I,-129/64-9/64*I,1/4-5/16*I,65/128+87/64*I,-9/32-1/16*I,183/256-97/128*I],
[1/4+5/2*I,-23/8-57/16*I,1/4+13/4*I,-825/64-147/32*I,21/8+I,-537/64+143/16*I,-5/8-39/16*I,2473/256+137/64*I,-149/64+49/32*I,-177/128-1369/128*I,125/64+87/64*I,-2063/256+541/128*I,85/256-33/16*I,805/128+2415/512*I,-219/128+115/256*I,6301/4096-6609/1024*I],
[-4,9-5*I,-4*I,27/2+6*I,-2,17/4-13/2*I,1+I,-19/4+5/4*I,1/2-I,9/4+55/16*I,-3/4,45/32-37/16*I,1/4+1/2*I,-129/64-9/64*I,1/4-5/16*I,65/128+87/64*I],
[-2*I,119/8+29/4*I,1/4+5/2*I,-23/8-57/16*I,1/4+13/4*I,-825/64-147/32*I,21/8+I,-537/64+143/16*I,-5/8-39/16*I,2473/256+137/64*I,-149/64+49/32*I,-177/128-1369/128*I,125/64+87/64*I,-2063/256+541/128*I,85/256-33/16*I,805/128+2415/512*I],
[0,-6,-4,9-5*I,-4*I,27/2+6*I,-2,17/4-13/2*I,1+I,-19/4+5/4*I,1/2-I,9/4+55/16*I,-3/4,45/32-37/16*I,1/4+1/2*I,-129/64-9/64*I],
[1,-9/4+3*I,-2*I,119/8+29/4*I,1/4+5/2*I,-23/8-57/16*I,1/4+13/4*I,-825/64-147/32*I,21/8+I,-537/64+143/16*I,-5/8-39/16*I,2473/256+137/64*I,-149/64+49/32*I,-177/128-1369/128*I,125/64+87/64*I,-2063/256+541/128*I],
[0,-4*I,0,-6,-4,9-5*I,-4*I,27/2+6*I,-2,17/4-13/2*I,1+I,-19/4+5/4*I,1/2-I,9/4+55/16*I,-3/4,45/32-37/16*I],
[0,1/4+1/2*I,1,-9/4+3*I,-2*I,119/8+29/4*I,1/4+5/2*I,-23/8-57/16*I,1/4+13/4*I,-825/64-147/32*I,21/8+I,-537/64+143/16*I,-5/8-39/16*I,2473/256+137/64*I,-149/64+49/32*I,-177/128-1369/128*I]]'''))
with dotprodsimp(True):
assert M.rank() == 8
def test_issue_18531():
# solve_linear_system still needs fixing but the rref works.
M = Matrix([
[1, 1, 1, 1, 1, 0, 1, 0, 0],
[1 + sqrt(2), -1 + sqrt(2), 1 - sqrt(2), -sqrt(2) - 1, 1, 1, -1, 1, 1],
[-5 + 2*sqrt(2), -5 - 2*sqrt(2), -5 - 2*sqrt(2), -5 + 2*sqrt(2), -7, 2, -7, -2, 0],
[-3*sqrt(2) - 1, 1 - 3*sqrt(2), -1 + 3*sqrt(2), 1 + 3*sqrt(2), -7, -5, 7, -5, 3],
[7 - 4*sqrt(2), 4*sqrt(2) + 7, 4*sqrt(2) + 7, 7 - 4*sqrt(2), 7, -12, 7, 12, 0],
[-1 + 3*sqrt(2), 1 + 3*sqrt(2), -3*sqrt(2) - 1, 1 - 3*sqrt(2), 7, -5, -7, -5, 3],
[-3 + 2*sqrt(2), -3 - 2*sqrt(2), -3 - 2*sqrt(2), -3 + 2*sqrt(2), -1, 2, -1, -2, 0],
[1 - sqrt(2), -sqrt(2) - 1, 1 + sqrt(2), -1 + sqrt(2), -1, 1, 1, 1, 1]
])
with dotprodsimp(True):
assert M.rref() == (Matrix([
[1, 0, 0, 0, 0, 0, 0, 0, 1/2],
[0, 1, 0, 0, 0, 0, 0, 0, -1/2],
[0, 0, 1, 0, 0, 0, 0, 0, 1/2],
[0, 0, 0, 1, 0, 0, 0, 0, -1/2],
[0, 0, 0, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 0, 0, -1/2],
[0, 0, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 1, -1/2]]), (0, 1, 2, 3, 4, 5, 6, 7))
def test_creation():
raises(ValueError, lambda: Matrix(5, 5, range(20)))
raises(ValueError, lambda: Matrix(5, -1, []))
raises(IndexError, lambda: Matrix((1, 2))[2])
with raises(IndexError):
Matrix((1, 2))[3] = 5
assert Matrix() == Matrix([]) == Matrix([[]]) == Matrix(0, 0, [])
# anything used to be allowed in a matrix
with warns_deprecated_sympy():
assert Matrix([[[1], (2,)]]).tolist() == [[[1], (2,)]]
with warns_deprecated_sympy():
assert Matrix([[[1], (2,)]]).T.tolist() == [[[1]], [(2,)]]
M = Matrix([[0]])
with warns_deprecated_sympy():
M[0, 0] = S.EmptySet
a = Matrix([[x, 0], [0, 0]])
m = a
assert m.cols == m.rows
assert m.cols == 2
assert m[:] == [x, 0, 0, 0]
b = Matrix(2, 2, [x, 0, 0, 0])
m = b
assert m.cols == m.rows
assert m.cols == 2
assert m[:] == [x, 0, 0, 0]
assert a == b
assert Matrix(b) == b
c23 = Matrix(2, 3, range(1, 7))
c13 = Matrix(1, 3, range(7, 10))
c = Matrix([c23, c13])
assert c.cols == 3
assert c.rows == 3
assert c[:] == [1, 2, 3, 4, 5, 6, 7, 8, 9]
assert Matrix(eye(2)) == eye(2)
assert ImmutableMatrix(ImmutableMatrix(eye(2))) == ImmutableMatrix(eye(2))
assert ImmutableMatrix(c) == c.as_immutable()
assert Matrix(ImmutableMatrix(c)) == ImmutableMatrix(c).as_mutable()
assert c is not Matrix(c)
dat = [[ones(3,2), ones(3,3)*2], [ones(2,3)*3, ones(2,2)*4]]
M = Matrix(dat)
assert M == Matrix([
[1, 1, 2, 2, 2],
[1, 1, 2, 2, 2],
[1, 1, 2, 2, 2],
[3, 3, 3, 4, 4],
[3, 3, 3, 4, 4]])
assert M.tolist() != dat
# keep block form if evaluate=False
assert Matrix(dat, evaluate=False).tolist() == dat
A = MatrixSymbol("A", 2, 2)
dat = [ones(2), A]
assert Matrix(dat) == Matrix([
[ 1, 1],
[ 1, 1],
[A[0, 0], A[0, 1]],
[A[1, 0], A[1, 1]]])
with warns_deprecated_sympy():
assert Matrix(dat, evaluate=False).tolist() == [[i] for i in dat]
# 0-dim tolerance
assert Matrix([ones(2), ones(0)]) == Matrix([ones(2)])
raises(ValueError, lambda: Matrix([ones(2), ones(0, 3)]))
raises(ValueError, lambda: Matrix([ones(2), ones(3, 0)]))
# mix of Matrix and iterable
M = Matrix([[1, 2], [3, 4]])
M2 = Matrix([M, (5, 6)])
assert M2 == Matrix([[1, 2], [3, 4], [5, 6]])
def test_irregular_block():
assert Matrix.irregular(3, ones(2,1), ones(3,3)*2, ones(2,2)*3,
ones(1,1)*4, ones(2,2)*5, ones(1,2)*6, ones(1,2)*7) == Matrix([
[1, 2, 2, 2, 3, 3],
[1, 2, 2, 2, 3, 3],
[4, 2, 2, 2, 5, 5],
[6, 6, 7, 7, 5, 5]])
def test_tolist():
lst = [[S.One, S.Half, x*y, S.Zero], [x, y, z, x**2], [y, -S.One, z*x, 3]]
m = Matrix(lst)
assert m.tolist() == lst
def test_as_mutable():
assert zeros(0, 3).as_mutable() == zeros(0, 3)
assert zeros(0, 3).as_immutable() == ImmutableMatrix(zeros(0, 3))
assert zeros(3, 0).as_immutable() == ImmutableMatrix(zeros(3, 0))
def test_slicing():
m0 = eye(4)
assert m0[:3, :3] == eye(3)
assert m0[2:4, 0:2] == zeros(2)
m1 = Matrix(3, 3, lambda i, j: i + j)
assert m1[0, :] == Matrix(1, 3, (0, 1, 2))
assert m1[1:3, 1] == Matrix(2, 1, (2, 3))
m2 = Matrix([[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15]])
assert m2[:, -1] == Matrix(4, 1, [3, 7, 11, 15])
assert m2[-2:, :] == Matrix([[8, 9, 10, 11], [12, 13, 14, 15]])
def test_submatrix_assignment():
m = zeros(4)
m[2:4, 2:4] = eye(2)
assert m == Matrix(((0, 0, 0, 0),
(0, 0, 0, 0),
(0, 0, 1, 0),
(0, 0, 0, 1)))
m[:2, :2] = eye(2)
assert m == eye(4)
m[:, 0] = Matrix(4, 1, (1, 2, 3, 4))
assert m == Matrix(((1, 0, 0, 0),
(2, 1, 0, 0),
(3, 0, 1, 0),
(4, 0, 0, 1)))
m[:, :] = zeros(4)
assert m == zeros(4)
m[:, :] = [(1, 2, 3, 4), (5, 6, 7, 8), (9, 10, 11, 12), (13, 14, 15, 16)]
assert m == Matrix(((1, 2, 3, 4),
(5, 6, 7, 8),
(9, 10, 11, 12),
(13, 14, 15, 16)))
m[:2, 0] = [0, 0]
assert m == Matrix(((0, 2, 3, 4),
(0, 6, 7, 8),
(9, 10, 11, 12),
(13, 14, 15, 16)))
def test_extract():
m = Matrix(4, 3, lambda i, j: i*3 + j)
assert m.extract([0, 1, 3], [0, 1]) == Matrix(3, 2, [0, 1, 3, 4, 9, 10])
assert m.extract([0, 3], [0, 0, 2]) == Matrix(2, 3, [0, 0, 2, 9, 9, 11])
assert m.extract(range(4), range(3)) == m
raises(IndexError, lambda: m.extract([4], [0]))
raises(IndexError, lambda: m.extract([0], [3]))
def test_reshape():
m0 = eye(3)
assert m0.reshape(1, 9) == Matrix(1, 9, (1, 0, 0, 0, 1, 0, 0, 0, 1))
m1 = Matrix(3, 4, lambda i, j: i + j)
assert m1.reshape(
4, 3) == Matrix(((0, 1, 2), (3, 1, 2), (3, 4, 2), (3, 4, 5)))
assert m1.reshape(2, 6) == Matrix(((0, 1, 2, 3, 1, 2), (3, 4, 2, 3, 4, 5)))
def test_applyfunc():
m0 = eye(3)
assert m0.applyfunc(lambda x: 2*x) == eye(3)*2
assert m0.applyfunc(lambda x: 0) == zeros(3)
def test_expand():
m0 = Matrix([[x*(x + y), 2], [((x + y)*y)*x, x*(y + x*(x + y))]])
# Test if expand() returns a matrix
m1 = m0.expand()
assert m1 == Matrix(
[[x*y + x**2, 2], [x*y**2 + y*x**2, x*y + y*x**2 + x**3]])
a = Symbol('a', real=True)
assert Matrix([exp(I*a)]).expand(complex=True) == \
Matrix([cos(a) + I*sin(a)])
assert Matrix([[0, 1, 2], [0, 0, -1], [0, 0, 0]]).exp() == Matrix([
[1, 1, Rational(3, 2)],
[0, 1, -1],
[0, 0, 1]]
)
def test_refine():
m0 = Matrix([[Abs(x)**2, sqrt(x**2)],
[sqrt(x**2)*Abs(y)**2, sqrt(y**2)*Abs(x)**2]])
m1 = m0.refine(Q.real(x) & Q.real(y))
assert m1 == Matrix([[x**2, Abs(x)], [y**2*Abs(x), x**2*Abs(y)]])
m1 = m0.refine(Q.positive(x) & Q.positive(y))
assert m1 == Matrix([[x**2, x], [x*y**2, x**2*y]])
m1 = m0.refine(Q.negative(x) & Q.negative(y))
assert m1 == Matrix([[x**2, -x], [-x*y**2, -x**2*y]])
def test_random():
M = randMatrix(3, 3)
M = randMatrix(3, 3, seed=3)
assert M == randMatrix(3, 3, seed=3)
M = randMatrix(3, 4, 0, 150)
M = randMatrix(3, seed=4, symmetric=True)
assert M == randMatrix(3, seed=4, symmetric=True)
S = M.copy()
S.simplify()
assert S == M # doesn't fail when elements are Numbers, not int
rng = random.Random(4)
assert M == randMatrix(3, symmetric=True, prng=rng)
# Ensure symmetry
for size in (10, 11): # Test odd and even
for percent in (100, 70, 30):
M = randMatrix(size, symmetric=True, percent=percent, prng=rng)
assert M == M.T
M = randMatrix(10, min=1, percent=70)
zero_count = 0
for i in range(M.shape[0]):
for j in range(M.shape[1]):
if M[i, j] == 0:
zero_count += 1
assert zero_count == 30
def test_inverse():
A = eye(4)
assert A.inv() == eye(4)
assert A.inv(method="LU") == eye(4)
assert A.inv(method="ADJ") == eye(4)
assert A.inv(method="CH") == eye(4)
assert A.inv(method="LDL") == eye(4)
assert A.inv(method="QR") == eye(4)
A = Matrix([[2, 3, 5],
[3, 6, 2],
[8, 3, 6]])
Ainv = A.inv()
assert A*Ainv == eye(3)
assert A.inv(method="LU") == Ainv
assert A.inv(method="ADJ") == Ainv
assert A.inv(method="CH") == Ainv
assert A.inv(method="LDL") == Ainv
assert A.inv(method="QR") == Ainv
AA = Matrix([[0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0],
[1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0],
[1, 1, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1],
[1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0],
[1, 0, 0, 1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0],
[1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1],
[0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0],
[1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1],
[0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1],
[1, 0, 1, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0],
[0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0],
[1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 0],
[0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1],
[1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 0, 1, 1, 0],
[0, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0, 0],
[1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1],
[0, 1, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1],
[1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1],
[0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1],
[0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 1],
[0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 0],
[0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 0]])
assert AA.inv(method="BLOCK") * AA == eye(AA.shape[0])
# test that immutability is not a problem
cls = ImmutableMatrix
m = cls([[48, 49, 31],
[ 9, 71, 94],
[59, 28, 65]])
assert all(type(m.inv(s)) is cls for s in 'GE ADJ LU CH LDL QR'.split())
cls = ImmutableSparseMatrix
m = cls([[48, 49, 31],
[ 9, 71, 94],
[59, 28, 65]])
assert all(type(m.inv(s)) is cls for s in 'GE ADJ LU CH LDL QR'.split())
def test_matrix_inverse_mod():
A = Matrix(2, 1, [1, 0])
raises(NonSquareMatrixError, lambda: A.inv_mod(2))
A = Matrix(2, 2, [1, 0, 0, 0])
raises(ValueError, lambda: A.inv_mod(2))
A = Matrix(2, 2, [1, 2, 3, 4])
Ai = Matrix(2, 2, [1, 1, 0, 1])
assert A.inv_mod(3) == Ai
A = Matrix(2, 2, [1, 0, 0, 1])
assert A.inv_mod(2) == A
A = Matrix(3, 3, [1, 2, 3, 4, 5, 6, 7, 8, 9])
raises(ValueError, lambda: A.inv_mod(5))
A = Matrix(3, 3, [5, 1, 3, 2, 6, 0, 2, 1, 1])
Ai = Matrix(3, 3, [6, 8, 0, 1, 5, 6, 5, 6, 4])
assert A.inv_mod(9) == Ai
A = Matrix(3, 3, [1, 6, -3, 4, 1, -5, 3, -5, 5])
Ai = Matrix(3, 3, [4, 3, 3, 1, 2, 5, 1, 5, 1])
assert A.inv_mod(6) == Ai
A = Matrix(3, 3, [1, 6, 1, 4, 1, 5, 3, 2, 5])
Ai = Matrix(3, 3, [6, 0, 3, 6, 6, 4, 1, 6, 1])
assert A.inv_mod(7) == Ai
def test_jacobian_hessian():
L = Matrix(1, 2, [x**2*y, 2*y**2 + x*y])
syms = [x, y]
assert L.jacobian(syms) == Matrix([[2*x*y, x**2], [y, 4*y + x]])
L = Matrix(1, 2, [x, x**2*y**3])
assert L.jacobian(syms) == Matrix([[1, 0], [2*x*y**3, x**2*3*y**2]])
f = x**2*y
syms = [x, y]
assert hessian(f, syms) == Matrix([[2*y, 2*x], [2*x, 0]])
f = x**2*y**3
assert hessian(f, syms) == \
Matrix([[2*y**3, 6*x*y**2], [6*x*y**2, 6*x**2*y]])
f = z + x*y**2
g = x**2 + 2*y**3
ans = Matrix([[0, 2*y],
[2*y, 2*x]])
assert ans == hessian(f, Matrix([x, y]))
assert ans == hessian(f, Matrix([x, y]).T)
assert hessian(f, (y, x), [g]) == Matrix([
[ 0, 6*y**2, 2*x],
[6*y**2, 2*x, 2*y],
[ 2*x, 2*y, 0]])
def test_wronskian():
assert wronskian([cos(x), sin(x)], x) == cos(x)**2 + sin(x)**2
assert wronskian([exp(x), exp(2*x)], x) == exp(3*x)
assert wronskian([exp(x), x], x) == exp(x) - x*exp(x)
assert wronskian([1, x, x**2], x) == 2
w1 = -6*exp(x)*sin(x)*x + 6*cos(x)*exp(x)*x**2 - 6*exp(x)*cos(x)*x - \
exp(x)*cos(x)*x**3 + exp(x)*sin(x)*x**3
assert wronskian([exp(x), cos(x), x**3], x).expand() == w1
assert wronskian([exp(x), cos(x), x**3], x, method='berkowitz').expand() \
== w1
w2 = -x**3*cos(x)**2 - x**3*sin(x)**2 - 6*x*cos(x)**2 - 6*x*sin(x)**2
assert wronskian([sin(x), cos(x), x**3], x).expand() == w2
assert wronskian([sin(x), cos(x), x**3], x, method='berkowitz').expand() \
== w2
assert wronskian([], x) == 1
def test_subs():
assert Matrix([[1, x], [x, 4]]).subs(x, 5) == Matrix([[1, 5], [5, 4]])
assert Matrix([[x, 2], [x + y, 4]]).subs([[x, -1], [y, -2]]) == \
Matrix([[-1, 2], [-3, 4]])
assert Matrix([[x, 2], [x + y, 4]]).subs([(x, -1), (y, -2)]) == \
Matrix([[-1, 2], [-3, 4]])
assert Matrix([[x, 2], [x + y, 4]]).subs({x: -1, y: -2}) == \
Matrix([[-1, 2], [-3, 4]])
assert Matrix([x*y]).subs({x: y - 1, y: x - 1}, simultaneous=True) == \
Matrix([(x - 1)*(y - 1)])
for cls in classes:
assert Matrix([[2, 0], [0, 2]]) == cls.eye(2).subs(1, 2)
def test_xreplace():
assert Matrix([[1, x], [x, 4]]).xreplace({x: 5}) == \
Matrix([[1, 5], [5, 4]])
assert Matrix([[x, 2], [x + y, 4]]).xreplace({x: -1, y: -2}) == \
Matrix([[-1, 2], [-3, 4]])
for cls in classes:
assert Matrix([[2, 0], [0, 2]]) == cls.eye(2).xreplace({1: 2})
def test_simplify():
n = Symbol('n')
f = Function('f')
M = Matrix([[ 1/x + 1/y, (x + x*y) / x ],
[ (f(x) + y*f(x))/f(x), 2 * (1/n - cos(n * pi)/n) / pi ]])
M.simplify()
assert M == Matrix([[ (x + y)/(x * y), 1 + y ],
[ 1 + y, 2*((1 - 1*cos(pi*n))/(pi*n)) ]])
eq = (1 + x)**2
M = Matrix([[eq]])
M.simplify()
assert M == Matrix([[eq]])
M.simplify(ratio=oo)
assert M == Matrix([[eq.simplify(ratio=oo)]])
def test_transpose():
M = Matrix([[1, 2, 3, 4, 5, 6, 7, 8, 9, 0],
[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]])
assert M.T == Matrix( [ [1, 1],
[2, 2],
[3, 3],
[4, 4],
[5, 5],
[6, 6],
[7, 7],
[8, 8],
[9, 9],
[0, 0] ])
assert M.T.T == M
assert M.T == M.transpose()
def test_conjugate():
M = Matrix([[0, I, 5],
[1, 2, 0]])
assert M.T == Matrix([[0, 1],
[I, 2],
[5, 0]])
assert M.C == Matrix([[0, -I, 5],
[1, 2, 0]])
assert M.C == M.conjugate()
assert M.H == M.T.C
assert M.H == Matrix([[ 0, 1],
[-I, 2],
[ 5, 0]])
def test_conj_dirac():
raises(AttributeError, lambda: eye(3).D)
M = Matrix([[1, I, I, I],
[0, 1, I, I],
[0, 0, 1, I],
[0, 0, 0, 1]])
assert M.D == Matrix([[ 1, 0, 0, 0],
[-I, 1, 0, 0],
[-I, -I, -1, 0],
[-I, -I, I, -1]])
def test_trace():
M = Matrix([[1, 0, 0],
[0, 5, 0],
[0, 0, 8]])
assert M.trace() == 14
def test_shape():
M = Matrix([[x, 0, 0],
[0, y, 0]])
assert M.shape == (2, 3)
def test_col_row_op():
M = Matrix([[x, 0, 0],
[0, y, 0]])
M.row_op(1, lambda r, j: r + j + 1)
assert M == Matrix([[x, 0, 0],
[1, y + 2, 3]])
M.col_op(0, lambda c, j: c + y**j)
assert M == Matrix([[x + 1, 0, 0],
[1 + y, y + 2, 3]])
# neither row nor slice give copies that allow the original matrix to
# be changed
assert M.row(0) == Matrix([[x + 1, 0, 0]])
r1 = M.row(0)
r1[0] = 42
assert M[0, 0] == x + 1
r1 = M[0, :-1] # also testing negative slice
r1[0] = 42
assert M[0, 0] == x + 1
c1 = M.col(0)
assert c1 == Matrix([x + 1, 1 + y])
c1[0] = 0
assert M[0, 0] == x + 1
c1 = M[:, 0]
c1[0] = 42
assert M[0, 0] == x + 1
def test_zip_row_op():
for cls in classes[:2]: # XXX: immutable matrices don't support row ops
M = cls.eye(3)
M.zip_row_op(1, 0, lambda v, u: v + 2*u)
assert M == cls([[1, 0, 0],
[2, 1, 0],
[0, 0, 1]])
M = cls.eye(3)*2
M[0, 1] = -1
M.zip_row_op(1, 0, lambda v, u: v + 2*u); M
assert M == cls([[2, -1, 0],
[4, 0, 0],
[0, 0, 2]])
def test_issue_3950():
m = Matrix([1, 2, 3])
a = Matrix([1, 2, 3])
b = Matrix([2, 2, 3])
assert not (m in [])
assert not (m in [1])
assert m != 1
assert m == a
assert m != b
def test_issue_3981():
class Index1:
def __index__(self):
return 1
class Index2:
def __index__(self):
return 2
index1 = Index1()
index2 = Index2()
m = Matrix([1, 2, 3])
assert m[index2] == 3
m[index2] = 5
assert m[2] == 5
m = Matrix([[1, 2, 3], [4, 5, 6]])
assert m[index1, index2] == 6
assert m[1, index2] == 6
assert m[index1, 2] == 6
m[index1, index2] = 4
assert m[1, 2] == 4
m[1, index2] = 6
assert m[1, 2] == 6
m[index1, 2] = 8
assert m[1, 2] == 8
def test_evalf():
a = Matrix([sqrt(5), 6])
assert all(a.evalf()[i] == a[i].evalf() for i in range(2))
assert all(a.evalf(2)[i] == a[i].evalf(2) for i in range(2))
assert all(a.n(2)[i] == a[i].n(2) for i in range(2))
def test_is_symbolic():
a = Matrix([[x, x], [x, x]])
assert a.is_symbolic() is True
a = Matrix([[1, 2, 3, 4], [5, 6, 7, 8]])
assert a.is_symbolic() is False
a = Matrix([[1, 2, 3, 4], [5, 6, x, 8]])
assert a.is_symbolic() is True
a = Matrix([[1, x, 3]])
assert a.is_symbolic() is True
a = Matrix([[1, 2, 3]])
assert a.is_symbolic() is False
a = Matrix([[1], [x], [3]])
assert a.is_symbolic() is True
a = Matrix([[1], [2], [3]])
assert a.is_symbolic() is False
def test_is_upper():
a = Matrix([[1, 2, 3]])
assert a.is_upper is True
a = Matrix([[1], [2], [3]])
assert a.is_upper is False
a = zeros(4, 2)
assert a.is_upper is True
def test_is_lower():
a = Matrix([[1, 2, 3]])
assert a.is_lower is False
a = Matrix([[1], [2], [3]])
assert a.is_lower is True
def test_is_nilpotent():
a = Matrix(4, 4, [0, 2, 1, 6, 0, 0, 1, 2, 0, 0, 0, 3, 0, 0, 0, 0])
assert a.is_nilpotent()
a = Matrix([[1, 0], [0, 1]])
assert not a.is_nilpotent()
a = Matrix([])
assert a.is_nilpotent()
def test_zeros_ones_fill():
n, m = 3, 5
a = zeros(n, m)
a.fill( 5 )
b = 5 * ones(n, m)
assert a == b
assert a.rows == b.rows == 3
assert a.cols == b.cols == 5
assert a.shape == b.shape == (3, 5)
assert zeros(2) == zeros(2, 2)
assert ones(2) == ones(2, 2)
assert zeros(2, 3) == Matrix(2, 3, [0]*6)
assert ones(2, 3) == Matrix(2, 3, [1]*6)
a.fill(0)
assert a == zeros(n, m)
def test_empty_zeros():
a = zeros(0)
assert a == Matrix()
a = zeros(0, 2)
assert a.rows == 0
assert a.cols == 2
a = zeros(2, 0)
assert a.rows == 2
assert a.cols == 0
def test_issue_3749():
a = Matrix([[x**2, x*y], [x*sin(y), x*cos(y)]])
assert a.diff(x) == Matrix([[2*x, y], [sin(y), cos(y)]])
assert Matrix([
[x, -x, x**2],
[exp(x), 1/x - exp(-x), x + 1/x]]).limit(x, oo) == \
Matrix([[oo, -oo, oo], [oo, 0, oo]])
assert Matrix([
[(exp(x) - 1)/x, 2*x + y*x, x**x ],
[1/x, abs(x), abs(sin(x + 1))]]).limit(x, 0) == \
Matrix([[1, 0, 1], [oo, 0, sin(1)]])
assert a.integrate(x) == Matrix([
[Rational(1, 3)*x**3, y*x**2/2],
[x**2*sin(y)/2, x**2*cos(y)/2]])
def test_inv_iszerofunc():
A = eye(4)
A.col_swap(0, 1)
for method in "GE", "LU":
assert A.inv(method=method, iszerofunc=lambda x: x == 0) == \
A.inv(method="ADJ")
def test_jacobian_metrics():
rho, phi = symbols("rho,phi")
X = Matrix([rho*cos(phi), rho*sin(phi)])
Y = Matrix([rho, phi])
J = X.jacobian(Y)
assert J == X.jacobian(Y.T)
assert J == (X.T).jacobian(Y)
assert J == (X.T).jacobian(Y.T)
g = J.T*eye(J.shape[0])*J
g = g.applyfunc(trigsimp)
assert g == Matrix([[1, 0], [0, rho**2]])
def test_jacobian2():
rho, phi = symbols("rho,phi")
X = Matrix([rho*cos(phi), rho*sin(phi), rho**2])
Y = Matrix([rho, phi])
J = Matrix([
[cos(phi), -rho*sin(phi)],
[sin(phi), rho*cos(phi)],
[ 2*rho, 0],
])
assert X.jacobian(Y) == J
def test_issue_4564():
X = Matrix([exp(x + y + z), exp(x + y + z), exp(x + y + z)])
Y = Matrix([x, y, z])
for i in range(1, 3):
for j in range(1, 3):
X_slice = X[:i, :]
Y_slice = Y[:j, :]
J = X_slice.jacobian(Y_slice)
assert J.rows == i
assert J.cols == j
for k in range(j):
assert J[:, k] == X_slice
def test_nonvectorJacobian():
X = Matrix([[exp(x + y + z), exp(x + y + z)],
[exp(x + y + z), exp(x + y + z)]])
raises(TypeError, lambda: X.jacobian(Matrix([x, y, z])))
X = X[0, :]
Y = Matrix([[x, y], [x, z]])
raises(TypeError, lambda: X.jacobian(Y))
raises(TypeError, lambda: X.jacobian(Matrix([ [x, y], [x, z] ])))
def test_vec():
m = Matrix([[1, 3], [2, 4]])
m_vec = m.vec()
assert m_vec.cols == 1
for i in range(4):
assert m_vec[i] == i + 1
def test_vech():
m = Matrix([[1, 2], [2, 3]])
m_vech = m.vech()
assert m_vech.cols == 1
for i in range(3):
assert m_vech[i] == i + 1
m_vech = m.vech(diagonal=False)
assert m_vech[0] == 2
m = Matrix([[1, x*(x + y)], [y*x + x**2, 1]])
m_vech = m.vech(diagonal=False)
assert m_vech[0] == y*x + x**2
m = Matrix([[1, x*(x + y)], [y*x, 1]])
m_vech = m.vech(diagonal=False, check_symmetry=False)
assert m_vech[0] == y*x
raises(ShapeError, lambda: Matrix([[1, 3]]).vech())
raises(ValueError, lambda: Matrix([[1, 3], [2, 4]]).vech())
raises(ShapeError, lambda: Matrix([[1, 3]]).vech())
raises(ValueError, lambda: Matrix([[1, 3], [2, 4]]).vech())
def test_diag():
# mostly tested in testcommonmatrix.py
assert diag([1, 2, 3]) == Matrix([1, 2, 3])
m = [1, 2, [3]]
raises(ValueError, lambda: diag(m))
assert diag(m, strict=False) == Matrix([1, 2, 3])
def test_get_diag_blocks1():
a = Matrix([[1, 2], [2, 3]])
b = Matrix([[3, x], [y, 3]])
c = Matrix([[3, x, 3], [y, 3, z], [x, y, z]])
assert a.get_diag_blocks() == [a]
assert b.get_diag_blocks() == [b]
assert c.get_diag_blocks() == [c]
def test_get_diag_blocks2():
a = Matrix([[1, 2], [2, 3]])
b = Matrix([[3, x], [y, 3]])
c = Matrix([[3, x, 3], [y, 3, z], [x, y, z]])
assert diag(a, b, b).get_diag_blocks() == [a, b, b]
assert diag(a, b, c).get_diag_blocks() == [a, b, c]
assert diag(a, c, b).get_diag_blocks() == [a, c, b]
assert diag(c, c, b).get_diag_blocks() == [c, c, b]
def test_inv_block():
a = Matrix([[1, 2], [2, 3]])
b = Matrix([[3, x], [y, 3]])
c = Matrix([[3, x, 3], [y, 3, z], [x, y, z]])
A = diag(a, b, b)
assert A.inv(try_block_diag=True) == diag(a.inv(), b.inv(), b.inv())
A = diag(a, b, c)
assert A.inv(try_block_diag=True) == diag(a.inv(), b.inv(), c.inv())
A = diag(a, c, b)
assert A.inv(try_block_diag=True) == diag(a.inv(), c.inv(), b.inv())
A = diag(a, a, b, a, c, a)
assert A.inv(try_block_diag=True) == diag(
a.inv(), a.inv(), b.inv(), a.inv(), c.inv(), a.inv())
assert A.inv(try_block_diag=True, method="ADJ") == diag(
a.inv(method="ADJ"), a.inv(method="ADJ"), b.inv(method="ADJ"),
a.inv(method="ADJ"), c.inv(method="ADJ"), a.inv(method="ADJ"))
def test_creation_args():
"""
Check that matrix dimensions can be specified using any reasonable type
(see issue 4614).
"""
raises(ValueError, lambda: zeros(3, -1))
raises(TypeError, lambda: zeros(1, 2, 3, 4))
assert zeros(int(3)) == zeros(3)
assert zeros(Integer(3)) == zeros(3)
raises(ValueError, lambda: zeros(3.))
assert eye(int(3)) == eye(3)
assert eye(Integer(3)) == eye(3)
raises(ValueError, lambda: eye(3.))
assert ones(int(3), Integer(4)) == ones(3, 4)
raises(TypeError, lambda: Matrix(5))
raises(TypeError, lambda: Matrix(1, 2))
raises(ValueError, lambda: Matrix([1, [2]]))
def test_diagonal_symmetrical():
m = Matrix(2, 2, [0, 1, 1, 0])
assert not m.is_diagonal()
assert m.is_symmetric()
assert m.is_symmetric(simplify=False)
m = Matrix(2, 2, [1, 0, 0, 1])
assert m.is_diagonal()
m = diag(1, 2, 3)
assert m.is_diagonal()
assert m.is_symmetric()
m = Matrix(3, 3, [1, 0, 0, 0, 2, 0, 0, 0, 3])
assert m == diag(1, 2, 3)
m = Matrix(2, 3, zeros(2, 3))
assert not m.is_symmetric()
assert m.is_diagonal()
m = Matrix(((5, 0), (0, 6), (0, 0)))
assert m.is_diagonal()
m = Matrix(((5, 0, 0), (0, 6, 0)))
assert m.is_diagonal()
m = Matrix(3, 3, [1, x**2 + 2*x + 1, y, (x + 1)**2, 2, 0, y, 0, 3])
assert m.is_symmetric()
assert not m.is_symmetric(simplify=False)
assert m.expand().is_symmetric(simplify=False)
def test_diagonalization():
m = Matrix([[1, 2+I], [2-I, 3]])
assert m.is_diagonalizable()
m = Matrix(3, 2, [-3, 1, -3, 20, 3, 10])
assert not m.is_diagonalizable()
assert not m.is_symmetric()
raises(NonSquareMatrixError, lambda: m.diagonalize())
# diagonalizable
m = diag(1, 2, 3)
(P, D) = m.diagonalize()
assert P == eye(3)
assert D == m
m = Matrix(2, 2, [0, 1, 1, 0])
assert m.is_symmetric()
assert m.is_diagonalizable()
(P, D) = m.diagonalize()
assert P.inv() * m * P == D
m = Matrix(2, 2, [1, 0, 0, 3])
assert m.is_symmetric()
assert m.is_diagonalizable()
(P, D) = m.diagonalize()
assert P.inv() * m * P == D
assert P == eye(2)
assert D == m
m = Matrix(2, 2, [1, 1, 0, 0])
assert m.is_diagonalizable()
(P, D) = m.diagonalize()
assert P.inv() * m * P == D
m = Matrix(3, 3, [1, 2, 0, 0, 3, 0, 2, -4, 2])
assert m.is_diagonalizable()
(P, D) = m.diagonalize()
assert P.inv() * m * P == D
for i in P:
assert i.as_numer_denom()[1] == 1
m = Matrix(2, 2, [1, 0, 0, 0])
assert m.is_diagonal()
assert m.is_diagonalizable()
(P, D) = m.diagonalize()
assert P.inv() * m * P == D
assert P == Matrix([[0, 1], [1, 0]])
# diagonalizable, complex only
m = Matrix(2, 2, [0, 1, -1, 0])
assert not m.is_diagonalizable(True)
raises(MatrixError, lambda: m.diagonalize(True))
assert m.is_diagonalizable()
(P, D) = m.diagonalize()
assert P.inv() * m * P == D
# not diagonalizable
m = Matrix(2, 2, [0, 1, 0, 0])
assert not m.is_diagonalizable()
raises(MatrixError, lambda: m.diagonalize())
m = Matrix(3, 3, [-3, 1, -3, 20, 3, 10, 2, -2, 4])
assert not m.is_diagonalizable()
raises(MatrixError, lambda: m.diagonalize())
# symbolic
a, b, c, d = symbols('a b c d')
m = Matrix(2, 2, [a, c, c, b])
assert m.is_symmetric()
assert m.is_diagonalizable()
def test_issue_15887():
# Mutable matrix should not use cache
a = MutableDenseMatrix([[0, 1], [1, 0]])
assert a.is_diagonalizable() is True
a[1, 0] = 0
assert a.is_diagonalizable() is False
a = MutableDenseMatrix([[0, 1], [1, 0]])
a.diagonalize()
a[1, 0] = 0
raises(MatrixError, lambda: a.diagonalize())
# Test deprecated cache and kwargs
with warns_deprecated_sympy():
a.is_diagonalizable(clear_cache=True)
with warns_deprecated_sympy():
a.is_diagonalizable(clear_subproducts=True)
def test_jordan_form():
m = Matrix(3, 2, [-3, 1, -3, 20, 3, 10])
raises(NonSquareMatrixError, lambda: m.jordan_form())
# diagonalizable
m = Matrix(3, 3, [7, -12, 6, 10, -19, 10, 12, -24, 13])
Jmust = Matrix(3, 3, [-1, 0, 0, 0, 1, 0, 0, 0, 1])
P, J = m.jordan_form()
assert Jmust == J
assert Jmust == m.diagonalize()[1]
# m = Matrix(3, 3, [0, 6, 3, 1, 3, 1, -2, 2, 1])
# m.jordan_form() # very long
# m.jordan_form() #
# diagonalizable, complex only
# Jordan cells
# complexity: one of eigenvalues is zero
m = Matrix(3, 3, [0, 1, 0, -4, 4, 0, -2, 1, 2])
# The blocks are ordered according to the value of their eigenvalues,
# in order to make the matrix compatible with .diagonalize()
Jmust = Matrix(3, 3, [2, 1, 0, 0, 2, 0, 0, 0, 2])
P, J = m.jordan_form()
assert Jmust == J
# complexity: all of eigenvalues are equal
m = Matrix(3, 3, [2, 6, -15, 1, 1, -5, 1, 2, -6])
# Jmust = Matrix(3, 3, [-1, 0, 0, 0, -1, 1, 0, 0, -1])
# same here see 1456ff
Jmust = Matrix(3, 3, [-1, 1, 0, 0, -1, 0, 0, 0, -1])
P, J = m.jordan_form()
assert Jmust == J
# complexity: two of eigenvalues are zero
m = Matrix(3, 3, [4, -5, 2, 5, -7, 3, 6, -9, 4])
Jmust = Matrix(3, 3, [0, 1, 0, 0, 0, 0, 0, 0, 1])
P, J = m.jordan_form()
assert Jmust == J
m = Matrix(4, 4, [6, 5, -2, -3, -3, -1, 3, 3, 2, 1, -2, -3, -1, 1, 5, 5])
Jmust = Matrix(4, 4, [2, 1, 0, 0,
0, 2, 0, 0,
0, 0, 2, 1,
0, 0, 0, 2]
)
P, J = m.jordan_form()
assert Jmust == J
m = Matrix(4, 4, [6, 2, -8, -6, -3, 2, 9, 6, 2, -2, -8, -6, -1, 0, 3, 4])
# Jmust = Matrix(4, 4, [2, 0, 0, 0, 0, 2, 1, 0, 0, 0, 2, 0, 0, 0, 0, -2])
# same here see 1456ff
Jmust = Matrix(4, 4, [-2, 0, 0, 0,
0, 2, 1, 0,
0, 0, 2, 0,
0, 0, 0, 2])
P, J = m.jordan_form()
assert Jmust == J
m = Matrix(4, 4, [5, 4, 2, 1, 0, 1, -1, -1, -1, -1, 3, 0, 1, 1, -1, 2])
assert not m.is_diagonalizable()
Jmust = Matrix(4, 4, [1, 0, 0, 0, 0, 2, 0, 0, 0, 0, 4, 1, 0, 0, 0, 4])
P, J = m.jordan_form()
assert Jmust == J
# checking for maximum precision to remain unchanged
m = Matrix([[Float('1.0', precision=110), Float('2.0', precision=110)],
[Float('3.14159265358979323846264338327', precision=110), Float('4.0', precision=110)]])
P, J = m.jordan_form()
for term in J.values():
if isinstance(term, Float):
assert term._prec == 110
def test_jordan_form_complex_issue_9274():
A = Matrix([[ 2, 4, 1, 0],
[-4, 2, 0, 1],
[ 0, 0, 2, 4],
[ 0, 0, -4, 2]])
p = 2 - 4*I;
q = 2 + 4*I;
Jmust1 = Matrix([[p, 1, 0, 0],
[0, p, 0, 0],
[0, 0, q, 1],
[0, 0, 0, q]])
Jmust2 = Matrix([[q, 1, 0, 0],
[0, q, 0, 0],
[0, 0, p, 1],
[0, 0, 0, p]])
P, J = A.jordan_form()
assert J == Jmust1 or J == Jmust2
assert simplify(P*J*P.inv()) == A
def test_issue_10220():
# two non-orthogonal Jordan blocks with eigenvalue 1
M = Matrix([[1, 0, 0, 1],
[0, 1, 1, 0],
[0, 0, 1, 1],
[0, 0, 0, 1]])
P, J = M.jordan_form()
assert P == Matrix([[0, 1, 0, 1],
[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0]])
assert J == Matrix([
[1, 1, 0, 0],
[0, 1, 1, 0],
[0, 0, 1, 0],
[0, 0, 0, 1]])
def test_jordan_form_issue_15858():
A = Matrix([
[1, 1, 1, 0],
[-2, -1, 0, -1],
[0, 0, -1, -1],
[0, 0, 2, 1]])
(P, J) = A.jordan_form()
assert P.expand() == Matrix([
[ -I, -I/2, I, I/2],
[-1 + I, 0, -1 - I, 0],
[ 0, -S(1)/2 - I/2, 0, -S(1)/2 + I/2],
[ 0, 1, 0, 1]])
assert J == Matrix([
[-I, 1, 0, 0],
[0, -I, 0, 0],
[0, 0, I, 1],
[0, 0, 0, I]])
def test_Matrix_berkowitz_charpoly():
UA, K_i, K_w = symbols('UA K_i K_w')
A = Matrix([[-K_i - UA + K_i**2/(K_i + K_w), K_i*K_w/(K_i + K_w)],
[ K_i*K_w/(K_i + K_w), -K_w + K_w**2/(K_i + K_w)]])
charpoly = A.charpoly(x)
assert charpoly == \
Poly(x**2 + (K_i*UA + K_w*UA + 2*K_i*K_w)/(K_i + K_w)*x +
K_i*K_w*UA/(K_i + K_w), x, domain='ZZ(K_i,K_w,UA)')
assert type(charpoly) is PurePoly
A = Matrix([[1, 3], [2, 0]])
assert A.charpoly() == A.charpoly(x) == PurePoly(x**2 - x - 6)
A = Matrix([[1, 2], [x, 0]])
p = A.charpoly(x)
assert p.gen != x
assert p.as_expr().subs(p.gen, x) == x**2 - 3*x
def test_exp_jordan_block():
l = Symbol('lamda')
m = Matrix.jordan_block(1, l)
assert m._eval_matrix_exp_jblock() == Matrix([[exp(l)]])
m = Matrix.jordan_block(3, l)
assert m._eval_matrix_exp_jblock() == \
Matrix([
[exp(l), exp(l), exp(l)/2],
[0, exp(l), exp(l)],
[0, 0, exp(l)]])
def test_exp():
m = Matrix([[3, 4], [0, -2]])
m_exp = Matrix([[exp(3), -4*exp(-2)/5 + 4*exp(3)/5], [0, exp(-2)]])
assert m.exp() == m_exp
assert exp(m) == m_exp
m = Matrix([[1, 0], [0, 1]])
assert m.exp() == Matrix([[E, 0], [0, E]])
assert exp(m) == Matrix([[E, 0], [0, E]])
m = Matrix([[1, -1], [1, 1]])
assert m.exp() == Matrix([[E*cos(1), -E*sin(1)], [E*sin(1), E*cos(1)]])
def test_log():
l = Symbol('lamda')
m = Matrix.jordan_block(1, l)
assert m._eval_matrix_log_jblock() == Matrix([[log(l)]])
m = Matrix.jordan_block(4, l)
assert m._eval_matrix_log_jblock() == \
Matrix(
[
[log(l), 1/l, -1/(2*l**2), 1/(3*l**3)],
[0, log(l), 1/l, -1/(2*l**2)],
[0, 0, log(l), 1/l],
[0, 0, 0, log(l)]
]
)
m = Matrix(
[[0, 0, 1],
[0, 0, 0],
[-1, 0, 0]]
)
raises(MatrixError, lambda: m.log())
def test_has():
A = Matrix(((x, y), (2, 3)))
assert A.has(x)
assert not A.has(z)
assert A.has(Symbol)
A = A.subs(x, 2)
assert not A.has(x)
def test_find_reasonable_pivot_naive_finds_guaranteed_nonzero1():
# Test if matrices._find_reasonable_pivot_naive()
# finds a guaranteed non-zero pivot when the
# some of the candidate pivots are symbolic expressions.
# Keyword argument: simpfunc=None indicates that no simplifications
# should be performed during the search.
x = Symbol('x')
column = Matrix(3, 1, [x, cos(x)**2 + sin(x)**2, S.Half])
pivot_offset, pivot_val, pivot_assumed_nonzero, simplified =\
_find_reasonable_pivot_naive(column)
assert pivot_val == S.Half
def test_find_reasonable_pivot_naive_finds_guaranteed_nonzero2():
# Test if matrices._find_reasonable_pivot_naive()
# finds a guaranteed non-zero pivot when the
# some of the candidate pivots are symbolic expressions.
# Keyword argument: simpfunc=_simplify indicates that the search
# should attempt to simplify candidate pivots.
x = Symbol('x')
column = Matrix(3, 1,
[x,
cos(x)**2+sin(x)**2+x**2,
cos(x)**2+sin(x)**2])
pivot_offset, pivot_val, pivot_assumed_nonzero, simplified =\
_find_reasonable_pivot_naive(column, simpfunc=_simplify)
assert pivot_val == 1
def test_find_reasonable_pivot_naive_simplifies():
# Test if matrices._find_reasonable_pivot_naive()
# simplifies candidate pivots, and reports
# their offsets correctly.
x = Symbol('x')
column = Matrix(3, 1,
[x,
cos(x)**2+sin(x)**2+x,
cos(x)**2+sin(x)**2])
pivot_offset, pivot_val, pivot_assumed_nonzero, simplified =\
_find_reasonable_pivot_naive(column, simpfunc=_simplify)
assert len(simplified) == 2
assert simplified[0][0] == 1
assert simplified[0][1] == 1+x
assert simplified[1][0] == 2
assert simplified[1][1] == 1
def test_errors():
raises(ValueError, lambda: Matrix([[1, 2], [1]]))
raises(IndexError, lambda: Matrix([[1, 2]])[1.2, 5])
raises(IndexError, lambda: Matrix([[1, 2]])[1, 5.2])
raises(ValueError, lambda: randMatrix(3, c=4, symmetric=True))
raises(ValueError, lambda: Matrix([1, 2]).reshape(4, 6))
raises(ShapeError,
lambda: Matrix([[1, 2], [3, 4]]).copyin_matrix([1, 0], Matrix([1, 2])))
raises(TypeError, lambda: Matrix([[1, 2], [3, 4]]).copyin_list([0,
1], set()))
raises(NonSquareMatrixError, lambda: Matrix([[1, 2, 3], [2, 3, 0]]).inv())
raises(ShapeError,
lambda: Matrix(1, 2, [1, 2]).row_join(Matrix([[1, 2], [3, 4]])))
raises(
ShapeError, lambda: Matrix([1, 2]).col_join(Matrix([[1, 2], [3, 4]])))
raises(ShapeError, lambda: Matrix([1]).row_insert(1, Matrix([[1,
2], [3, 4]])))
raises(ShapeError, lambda: Matrix([1]).col_insert(1, Matrix([[1,
2], [3, 4]])))
raises(NonSquareMatrixError, lambda: Matrix([1, 2]).trace())
raises(TypeError, lambda: Matrix([1]).applyfunc(1))
raises(ValueError, lambda: Matrix([[1, 2], [3, 4]]).minor(4, 5))
raises(ValueError, lambda: Matrix([[1, 2], [3, 4]]).minor_submatrix(4, 5))
raises(TypeError, lambda: Matrix([1, 2, 3]).cross(1))
raises(TypeError, lambda: Matrix([1, 2, 3]).dot(1))
raises(ShapeError, lambda: Matrix([1, 2, 3]).dot(Matrix([1, 2])))
raises(ShapeError, lambda: Matrix([1, 2]).dot([]))
raises(TypeError, lambda: Matrix([1, 2]).dot('a'))
with warns_deprecated_sympy():
Matrix([[1, 2], [3, 4]]).dot(Matrix([[4, 3], [1, 2]]))
raises(ShapeError, lambda: Matrix([1, 2]).dot([1, 2, 3]))
raises(NonSquareMatrixError, lambda: Matrix([1, 2, 3]).exp())
raises(ShapeError, lambda: Matrix([[1, 2], [3, 4]]).normalized())
raises(ValueError, lambda: Matrix([1, 2]).inv(method='not a method'))
raises(NonSquareMatrixError, lambda: Matrix([1, 2]).inverse_GE())
raises(ValueError, lambda: Matrix([[1, 2], [1, 2]]).inverse_GE())
raises(NonSquareMatrixError, lambda: Matrix([1, 2]).inverse_ADJ())
raises(ValueError, lambda: Matrix([[1, 2], [1, 2]]).inverse_ADJ())
raises(NonSquareMatrixError, lambda: Matrix([1, 2]).inverse_LU())
raises(NonSquareMatrixError, lambda: Matrix([1, 2]).is_nilpotent())
raises(NonSquareMatrixError, lambda: Matrix([1, 2]).det())
raises(ValueError,
lambda: Matrix([[1, 2], [3, 4]]).det(method='Not a real method'))
raises(ValueError,
lambda: Matrix([[1, 2, 3, 4], [5, 6, 7, 8],
[9, 10, 11, 12], [13, 14, 15, 16]]).det(iszerofunc="Not function"))
raises(ValueError,
lambda: Matrix([[1, 2, 3, 4], [5, 6, 7, 8],
[9, 10, 11, 12], [13, 14, 15, 16]]).det(iszerofunc=False))
raises(ValueError,
lambda: hessian(Matrix([[1, 2], [3, 4]]), Matrix([[1, 2], [2, 1]])))
raises(ValueError, lambda: hessian(Matrix([[1, 2], [3, 4]]), []))
raises(ValueError, lambda: hessian(Symbol('x')**2, 'a'))
raises(IndexError, lambda: eye(3)[5, 2])
raises(IndexError, lambda: eye(3)[2, 5])
M = Matrix(((1, 2, 3, 4), (5, 6, 7, 8), (9, 10, 11, 12), (13, 14, 15, 16)))
raises(ValueError, lambda: M.det('method=LU_decomposition()'))
V = Matrix([[10, 10, 10]])
M = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
raises(ValueError, lambda: M.row_insert(4.7, V))
M = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
raises(ValueError, lambda: M.col_insert(-4.2, V))
def test_len():
assert len(Matrix()) == 0
assert len(Matrix([[1, 2]])) == len(Matrix([[1], [2]])) == 2
assert len(Matrix(0, 2, lambda i, j: 0)) == \
len(Matrix(2, 0, lambda i, j: 0)) == 0
assert len(Matrix([[0, 1, 2], [3, 4, 5]])) == 6
assert Matrix([1]) == Matrix([[1]])
assert not Matrix()
assert Matrix() == Matrix([])
def test_integrate():
A = Matrix(((1, 4, x), (y, 2, 4), (10, 5, x**2)))
assert A.integrate(x) == \
Matrix(((x, 4*x, x**2/2), (x*y, 2*x, 4*x), (10*x, 5*x, x**3/3)))
assert A.integrate(y) == \
Matrix(((y, 4*y, x*y), (y**2/2, 2*y, 4*y), (10*y, 5*y, y*x**2)))
def test_limit():
A = Matrix(((1, 4, sin(x)/x), (y, 2, 4), (10, 5, x**2 + 1)))
assert A.limit(x, 0) == Matrix(((1, 4, 1), (y, 2, 4), (10, 5, 1)))
def test_diff():
A = MutableDenseMatrix(((1, 4, x), (y, 2, 4), (10, 5, x**2 + 1)))
assert isinstance(A.diff(x), type(A))
assert A.diff(x) == MutableDenseMatrix(((0, 0, 1), (0, 0, 0), (0, 0, 2*x)))
assert A.diff(y) == MutableDenseMatrix(((0, 0, 0), (1, 0, 0), (0, 0, 0)))
assert diff(A, x) == MutableDenseMatrix(((0, 0, 1), (0, 0, 0), (0, 0, 2*x)))
assert diff(A, y) == MutableDenseMatrix(((0, 0, 0), (1, 0, 0), (0, 0, 0)))
A_imm = A.as_immutable()
assert isinstance(A_imm.diff(x), type(A_imm))
assert A_imm.diff(x) == ImmutableDenseMatrix(((0, 0, 1), (0, 0, 0), (0, 0, 2*x)))
assert A_imm.diff(y) == ImmutableDenseMatrix(((0, 0, 0), (1, 0, 0), (0, 0, 0)))
assert diff(A_imm, x) == ImmutableDenseMatrix(((0, 0, 1), (0, 0, 0), (0, 0, 2*x)))
assert diff(A_imm, y) == ImmutableDenseMatrix(((0, 0, 0), (1, 0, 0), (0, 0, 0)))
def test_diff_by_matrix():
# Derive matrix by matrix:
A = MutableDenseMatrix([[x, y], [z, t]])
assert A.diff(A) == Array([[[[1, 0], [0, 0]], [[0, 1], [0, 0]]], [[[0, 0], [1, 0]], [[0, 0], [0, 1]]]])
assert diff(A, A) == Array([[[[1, 0], [0, 0]], [[0, 1], [0, 0]]], [[[0, 0], [1, 0]], [[0, 0], [0, 1]]]])
A_imm = A.as_immutable()
assert A_imm.diff(A_imm) == Array([[[[1, 0], [0, 0]], [[0, 1], [0, 0]]], [[[0, 0], [1, 0]], [[0, 0], [0, 1]]]])
assert diff(A_imm, A_imm) == Array([[[[1, 0], [0, 0]], [[0, 1], [0, 0]]], [[[0, 0], [1, 0]], [[0, 0], [0, 1]]]])
# Derive a constant matrix:
assert A.diff(a) == MutableDenseMatrix([[0, 0], [0, 0]])
B = ImmutableDenseMatrix([a, b])
assert A.diff(B) == Array.zeros(2, 1, 2, 2)
assert A.diff(A) == Array([[[[1, 0], [0, 0]], [[0, 1], [0, 0]]], [[[0, 0], [1, 0]], [[0, 0], [0, 1]]]])
# Test diff with tuples:
dB = B.diff([[a, b]])
assert dB.shape == (2, 2, 1)
assert dB == Array([[[1], [0]], [[0], [1]]])
f = Function("f")
fxyz = f(x, y, z)
assert fxyz.diff([[x, y, z]]) == Array([fxyz.diff(x), fxyz.diff(y), fxyz.diff(z)])
assert fxyz.diff(([x, y, z], 2)) == Array([
[fxyz.diff(x, 2), fxyz.diff(x, y), fxyz.diff(x, z)],
[fxyz.diff(x, y), fxyz.diff(y, 2), fxyz.diff(y, z)],
[fxyz.diff(x, z), fxyz.diff(z, y), fxyz.diff(z, 2)],
])
expr = sin(x)*exp(y)
assert expr.diff([[x, y]]) == Array([cos(x)*exp(y), sin(x)*exp(y)])
assert expr.diff(y, ((x, y),)) == Array([cos(x)*exp(y), sin(x)*exp(y)])
assert expr.diff(x, ((x, y),)) == Array([-sin(x)*exp(y), cos(x)*exp(y)])
assert expr.diff(((y, x),), [[x, y]]) == Array([[cos(x)*exp(y), -sin(x)*exp(y)], [sin(x)*exp(y), cos(x)*exp(y)]])
# Test different notations:
assert fxyz.diff(x).diff(y).diff(x) == fxyz.diff(((x, y, z),), 3)[0, 1, 0]
assert fxyz.diff(z).diff(y).diff(x) == fxyz.diff(((x, y, z),), 3)[2, 1, 0]
assert fxyz.diff([[x, y, z]], ((z, y, x),)) == Array([[fxyz.diff(i).diff(j) for i in (x, y, z)] for j in (z, y, x)])
# Test scalar derived by matrix remains matrix:
res = x.diff(Matrix([[x, y]]))
assert isinstance(res, ImmutableDenseMatrix)
assert res == Matrix([[1, 0]])
res = (x**3).diff(Matrix([[x, y]]))
assert isinstance(res, ImmutableDenseMatrix)
assert res == Matrix([[3*x**2, 0]])
def test_getattr():
A = Matrix(((1, 4, x), (y, 2, 4), (10, 5, x**2 + 1)))
raises(AttributeError, lambda: A.nonexistantattribute)
assert getattr(A, 'diff')(x) == Matrix(((0, 0, 1), (0, 0, 0), (0, 0, 2*x)))
def test_hessenberg():
A = Matrix([[3, 4, 1], [2, 4, 5], [0, 1, 2]])
assert A.is_upper_hessenberg
A = A.T
assert A.is_lower_hessenberg
A[0, -1] = 1
assert A.is_lower_hessenberg is False
A = Matrix([[3, 4, 1], [2, 4, 5], [3, 1, 2]])
assert not A.is_upper_hessenberg
A = zeros(5, 2)
assert A.is_upper_hessenberg
def test_cholesky():
raises(NonSquareMatrixError, lambda: Matrix((1, 2)).cholesky())
raises(ValueError, lambda: Matrix(((1, 2), (3, 4))).cholesky())
raises(ValueError, lambda: Matrix(((5 + I, 0), (0, 1))).cholesky())
raises(ValueError, lambda: Matrix(((1, 5), (5, 1))).cholesky())
raises(ValueError, lambda: Matrix(((1, 2), (3, 4))).cholesky(hermitian=False))
assert Matrix(((5 + I, 0), (0, 1))).cholesky(hermitian=False) == Matrix([
[sqrt(5 + I), 0], [0, 1]])
A = Matrix(((1, 5), (5, 1)))
L = A.cholesky(hermitian=False)
assert L == Matrix([[1, 0], [5, 2*sqrt(6)*I]])
assert L*L.T == A
A = Matrix(((25, 15, -5), (15, 18, 0), (-5, 0, 11)))
L = A.cholesky()
assert L * L.T == A
assert L.is_lower
assert L == Matrix([[5, 0, 0], [3, 3, 0], [-1, 1, 3]])
A = Matrix(((4, -2*I, 2 + 2*I), (2*I, 2, -1 + I), (2 - 2*I, -1 - I, 11)))
assert A.cholesky().expand() == Matrix(((2, 0, 0), (I, 1, 0), (1 - I, 0, 3)))
raises(NonSquareMatrixError, lambda: SparseMatrix((1, 2)).cholesky())
raises(ValueError, lambda: SparseMatrix(((1, 2), (3, 4))).cholesky())
raises(ValueError, lambda: SparseMatrix(((5 + I, 0), (0, 1))).cholesky())
raises(ValueError, lambda: SparseMatrix(((1, 5), (5, 1))).cholesky())
raises(ValueError, lambda: SparseMatrix(((1, 2), (3, 4))).cholesky(hermitian=False))
assert SparseMatrix(((5 + I, 0), (0, 1))).cholesky(hermitian=False) == Matrix([
[sqrt(5 + I), 0], [0, 1]])
A = SparseMatrix(((1, 5), (5, 1)))
L = A.cholesky(hermitian=False)
assert L == Matrix([[1, 0], [5, 2*sqrt(6)*I]])
assert L*L.T == A
A = SparseMatrix(((25, 15, -5), (15, 18, 0), (-5, 0, 11)))
L = A.cholesky()
assert L * L.T == A
assert L.is_lower
assert L == Matrix([[5, 0, 0], [3, 3, 0], [-1, 1, 3]])
A = SparseMatrix(((4, -2*I, 2 + 2*I), (2*I, 2, -1 + I), (2 - 2*I, -1 - I, 11)))
assert A.cholesky() == Matrix(((2, 0, 0), (I, 1, 0), (1 - I, 0, 3)))
def test_matrix_norm():
# Vector Tests
# Test columns and symbols
x = Symbol('x', real=True)
v = Matrix([cos(x), sin(x)])
assert trigsimp(v.norm(2)) == 1
assert v.norm(10) == Pow(cos(x)**10 + sin(x)**10, Rational(1, 10))
# Test Rows
A = Matrix([[5, Rational(3, 2)]])
assert A.norm() == Pow(25 + Rational(9, 4), S.Half)
assert A.norm(oo) == max(A)
assert A.norm(-oo) == min(A)
# Matrix Tests
# Intuitive test
A = Matrix([[1, 1], [1, 1]])
assert A.norm(2) == 2
assert A.norm(-2) == 0
assert A.norm('frobenius') == 2
assert eye(10).norm(2) == eye(10).norm(-2) == 1
assert A.norm(oo) == 2
# Test with Symbols and more complex entries
A = Matrix([[3, y, y], [x, S.Half, -pi]])
assert (A.norm('fro')
== sqrt(Rational(37, 4) + 2*abs(y)**2 + pi**2 + x**2))
# Check non-square
A = Matrix([[1, 2, -3], [4, 5, Rational(13, 2)]])
assert A.norm(2) == sqrt(Rational(389, 8) + sqrt(78665)/8)
assert A.norm(-2) is S.Zero
assert A.norm('frobenius') == sqrt(389)/2
# Test properties of matrix norms
# https://en.wikipedia.org/wiki/Matrix_norm#Definition
# Two matrices
A = Matrix([[1, 2], [3, 4]])
B = Matrix([[5, 5], [-2, 2]])
C = Matrix([[0, -I], [I, 0]])
D = Matrix([[1, 0], [0, -1]])
L = [A, B, C, D]
alpha = Symbol('alpha', real=True)
for order in ['fro', 2, -2]:
# Zero Check
assert zeros(3).norm(order) is S.Zero
# Check Triangle Inequality for all Pairs of Matrices
for X in L:
for Y in L:
dif = (X.norm(order) + Y.norm(order) -
(X + Y).norm(order))
assert (dif >= 0)
# Scalar multiplication linearity
for M in [A, B, C, D]:
dif = simplify((alpha*M).norm(order) -
abs(alpha) * M.norm(order))
assert dif == 0
# Test Properties of Vector Norms
# https://en.wikipedia.org/wiki/Vector_norm
# Two column vectors
a = Matrix([1, 1 - 1*I, -3])
b = Matrix([S.Half, 1*I, 1])
c = Matrix([-1, -1, -1])
d = Matrix([3, 2, I])
e = Matrix([Integer(1e2), Rational(1, 1e2), 1])
L = [a, b, c, d, e]
alpha = Symbol('alpha', real=True)
for order in [1, 2, -1, -2, S.Infinity, S.NegativeInfinity, pi]:
# Zero Check
if order > 0:
assert Matrix([0, 0, 0]).norm(order) is S.Zero
# Triangle inequality on all pairs
if order >= 1: # Triangle InEq holds only for these norms
for X in L:
for Y in L:
dif = (X.norm(order) + Y.norm(order) -
(X + Y).norm(order))
assert simplify(dif >= 0) is S.true
# Linear to scalar multiplication
if order in [1, 2, -1, -2, S.Infinity, S.NegativeInfinity]:
for X in L:
dif = simplify((alpha*X).norm(order) -
(abs(alpha) * X.norm(order)))
assert dif == 0
# ord=1
M = Matrix(3, 3, [1, 3, 0, -2, -1, 0, 3, 9, 6])
assert M.norm(1) == 13
def test_condition_number():
x = Symbol('x', real=True)
A = eye(3)
A[0, 0] = 10
A[2, 2] = Rational(1, 10)
assert A.condition_number() == 100
A[1, 1] = x
assert A.condition_number() == Max(10, Abs(x)) / Min(Rational(1, 10), Abs(x))
M = Matrix([[cos(x), sin(x)], [-sin(x), cos(x)]])
Mc = M.condition_number()
assert all(Float(1.).epsilon_eq(Mc.subs(x, val).evalf()) for val in
[Rational(1, 5), S.Half, Rational(1, 10), pi/2, pi, pi*Rational(7, 4) ])
#issue 10782
assert Matrix([]).condition_number() == 0
def test_equality():
A = Matrix(((1, 2, 3), (4, 5, 6), (7, 8, 9)))
B = Matrix(((9, 8, 7), (6, 5, 4), (3, 2, 1)))
assert A == A[:, :]
assert not A != A[:, :]
assert not A == B
assert A != B
assert A != 10
assert not A == 10
# A SparseMatrix can be equal to a Matrix
C = SparseMatrix(((1, 0, 0), (0, 1, 0), (0, 0, 1)))
D = Matrix(((1, 0, 0), (0, 1, 0), (0, 0, 1)))
assert C == D
assert not C != D
def test_col_join():
assert eye(3).col_join(Matrix([[7, 7, 7]])) == \
Matrix([[1, 0, 0],
[0, 1, 0],
[0, 0, 1],
[7, 7, 7]])
def test_row_insert():
r4 = Matrix([[4, 4, 4]])
for i in range(-4, 5):
l = [1, 0, 0]
l.insert(i, 4)
assert flatten(eye(3).row_insert(i, r4).col(0).tolist()) == l
def test_col_insert():
c4 = Matrix([4, 4, 4])
for i in range(-4, 5):
l = [0, 0, 0]
l.insert(i, 4)
assert flatten(zeros(3).col_insert(i, c4).row(0).tolist()) == l
def test_normalized():
assert Matrix([3, 4]).normalized() == \
Matrix([Rational(3, 5), Rational(4, 5)])
# Zero vector trivial cases
assert Matrix([0, 0, 0]).normalized() == Matrix([0, 0, 0])
# Machine precision error truncation trivial cases
m = Matrix([0,0,1.e-100])
assert m.normalized(
iszerofunc=lambda x: x.evalf(n=10, chop=True).is_zero
) == Matrix([0, 0, 0])
def test_print_nonzero():
assert capture(lambda: eye(3).print_nonzero()) == \
'[X ]\n[ X ]\n[ X]\n'
assert capture(lambda: eye(3).print_nonzero('.')) == \
'[. ]\n[ . ]\n[ .]\n'
def test_zeros_eye():
assert Matrix.eye(3) == eye(3)
assert Matrix.zeros(3) == zeros(3)
assert ones(3, 4) == Matrix(3, 4, [1]*12)
i = Matrix([[1, 0], [0, 1]])
z = Matrix([[0, 0], [0, 0]])
for cls in classes:
m = cls.eye(2)
assert i == m # but m == i will fail if m is immutable
assert i == eye(2, cls=cls)
assert type(m) == cls
m = cls.zeros(2)
assert z == m
assert z == zeros(2, cls=cls)
assert type(m) == cls
def test_is_zero():
assert Matrix().is_zero_matrix
assert Matrix([[0, 0], [0, 0]]).is_zero_matrix
assert zeros(3, 4).is_zero_matrix
assert not eye(3).is_zero_matrix
assert Matrix([[x, 0], [0, 0]]).is_zero_matrix == None
assert SparseMatrix([[x, 0], [0, 0]]).is_zero_matrix == None
assert ImmutableMatrix([[x, 0], [0, 0]]).is_zero_matrix == None
assert ImmutableSparseMatrix([[x, 0], [0, 0]]).is_zero_matrix == None
assert Matrix([[x, 1], [0, 0]]).is_zero_matrix == False
a = Symbol('a', nonzero=True)
assert Matrix([[a, 0], [0, 0]]).is_zero_matrix == False
def test_rotation_matrices():
# This tests the rotation matrices by rotating about an axis and back.
theta = pi/3
r3_plus = rot_axis3(theta)
r3_minus = rot_axis3(-theta)
r2_plus = rot_axis2(theta)
r2_minus = rot_axis2(-theta)
r1_plus = rot_axis1(theta)
r1_minus = rot_axis1(-theta)
assert r3_minus*r3_plus*eye(3) == eye(3)
assert r2_minus*r2_plus*eye(3) == eye(3)
assert r1_minus*r1_plus*eye(3) == eye(3)
# Check the correctness of the trace of the rotation matrix
assert r1_plus.trace() == 1 + 2*cos(theta)
assert r2_plus.trace() == 1 + 2*cos(theta)
assert r3_plus.trace() == 1 + 2*cos(theta)
# Check that a rotation with zero angle doesn't change anything.
assert rot_axis1(0) == eye(3)
assert rot_axis2(0) == eye(3)
assert rot_axis3(0) == eye(3)
def test_DeferredVector():
assert str(DeferredVector("vector")[4]) == "vector[4]"
assert sympify(DeferredVector("d")) == DeferredVector("d")
raises(IndexError, lambda: DeferredVector("d")[-1])
assert str(DeferredVector("d")) == "d"
assert repr(DeferredVector("test")) == "DeferredVector('test')"
def test_DeferredVector_not_iterable():
assert not iterable(DeferredVector('X'))
def test_DeferredVector_Matrix():
raises(TypeError, lambda: Matrix(DeferredVector("V")))
def test_GramSchmidt():
R = Rational
m1 = Matrix(1, 2, [1, 2])
m2 = Matrix(1, 2, [2, 3])
assert GramSchmidt([m1, m2]) == \
[Matrix(1, 2, [1, 2]), Matrix(1, 2, [R(2)/5, R(-1)/5])]
assert GramSchmidt([m1.T, m2.T]) == \
[Matrix(2, 1, [1, 2]), Matrix(2, 1, [R(2)/5, R(-1)/5])]
# from wikipedia
assert GramSchmidt([Matrix([3, 1]), Matrix([2, 2])], True) == [
Matrix([3*sqrt(10)/10, sqrt(10)/10]),
Matrix([-sqrt(10)/10, 3*sqrt(10)/10])]
# https://github.com/sympy/sympy/issues/9488
L = FiniteSet(Matrix([1]))
assert GramSchmidt(L) == [Matrix([[1]])]
def test_casoratian():
assert casoratian([1, 2, 3, 4], 1) == 0
assert casoratian([1, 2, 3, 4], 1, zero=False) == 0
def test_zero_dimension_multiply():
assert (Matrix()*zeros(0, 3)).shape == (0, 3)
assert zeros(3, 0)*zeros(0, 3) == zeros(3, 3)
assert zeros(0, 3)*zeros(3, 0) == Matrix()
def test_slice_issue_2884():
m = Matrix(2, 2, range(4))
assert m[1, :] == Matrix([[2, 3]])
assert m[-1, :] == Matrix([[2, 3]])
assert m[:, 1] == Matrix([[1, 3]]).T
assert m[:, -1] == Matrix([[1, 3]]).T
raises(IndexError, lambda: m[2, :])
raises(IndexError, lambda: m[2, 2])
def test_slice_issue_3401():
assert zeros(0, 3)[:, -1].shape == (0, 1)
assert zeros(3, 0)[0, :] == Matrix(1, 0, [])
def test_copyin():
s = zeros(3, 3)
s[3] = 1
assert s[:, 0] == Matrix([0, 1, 0])
assert s[3] == 1
assert s[3: 4] == [1]
s[1, 1] = 42
assert s[1, 1] == 42
assert s[1, 1:] == Matrix([[42, 0]])
s[1, 1:] = Matrix([[5, 6]])
assert s[1, :] == Matrix([[1, 5, 6]])
s[1, 1:] = [[42, 43]]
assert s[1, :] == Matrix([[1, 42, 43]])
s[0, 0] = 17
assert s[:, :1] == Matrix([17, 1, 0])
s[0, 0] = [1, 1, 1]
assert s[:, 0] == Matrix([1, 1, 1])
s[0, 0] = Matrix([1, 1, 1])
assert s[:, 0] == Matrix([1, 1, 1])
s[0, 0] = SparseMatrix([1, 1, 1])
assert s[:, 0] == Matrix([1, 1, 1])
def test_invertible_check():
# sometimes a singular matrix will have a pivot vector shorter than
# the number of rows in a matrix...
assert Matrix([[1, 2], [1, 2]]).rref() == (Matrix([[1, 2], [0, 0]]), (0,))
raises(ValueError, lambda: Matrix([[1, 2], [1, 2]]).inv())
m = Matrix([
[-1, -1, 0],
[ x, 1, 1],
[ 1, x, -1],
])
assert len(m.rref()[1]) != m.rows
# in addition, unless simplify=True in the call to rref, the identity
# matrix will be returned even though m is not invertible
assert m.rref()[0] != eye(3)
assert m.rref(simplify=signsimp)[0] != eye(3)
raises(ValueError, lambda: m.inv(method="ADJ"))
raises(ValueError, lambda: m.inv(method="GE"))
raises(ValueError, lambda: m.inv(method="LU"))
def test_issue_3959():
x, y = symbols('x, y')
e = x*y
assert e.subs(x, Matrix([3, 5, 3])) == Matrix([3, 5, 3])*y
def test_issue_5964():
assert str(Matrix([[1, 2], [3, 4]])) == 'Matrix([[1, 2], [3, 4]])'
def test_issue_7604():
x, y = symbols("x y")
assert sstr(Matrix([[x, 2*y], [y**2, x + 3]])) == \
'Matrix([\n[ x, 2*y],\n[y**2, x + 3]])'
def test_is_Identity():
assert eye(3).is_Identity
assert eye(3).as_immutable().is_Identity
assert not zeros(3).is_Identity
assert not ones(3).is_Identity
# issue 6242
assert not Matrix([[1, 0, 0]]).is_Identity
# issue 8854
assert SparseMatrix(3,3, {(0,0):1, (1,1):1, (2,2):1}).is_Identity
assert not SparseMatrix(2,3, range(6)).is_Identity
assert not SparseMatrix(3,3, {(0,0):1, (1,1):1}).is_Identity
assert not SparseMatrix(3,3, {(0,0):1, (1,1):1, (2,2):1, (0,1):2, (0,2):3}).is_Identity
def test_dot():
assert ones(1, 3).dot(ones(3, 1)) == 3
assert ones(1, 3).dot([1, 1, 1]) == 3
assert Matrix([1, 2, 3]).dot(Matrix([1, 2, 3])) == 14
assert Matrix([1, 2, 3*I]).dot(Matrix([I, 2, 3*I])) == -5 + I
assert Matrix([1, 2, 3*I]).dot(Matrix([I, 2, 3*I]), hermitian=False) == -5 + I
assert Matrix([1, 2, 3*I]).dot(Matrix([I, 2, 3*I]), hermitian=True) == 13 + I
assert Matrix([1, 2, 3*I]).dot(Matrix([I, 2, 3*I]), hermitian=True, conjugate_convention="physics") == 13 - I
assert Matrix([1, 2, 3*I]).dot(Matrix([4, 5*I, 6]), hermitian=True, conjugate_convention="right") == 4 + 8*I
assert Matrix([1, 2, 3*I]).dot(Matrix([4, 5*I, 6]), hermitian=True, conjugate_convention="left") == 4 - 8*I
assert Matrix([I, 2*I]).dot(Matrix([I, 2*I]), hermitian=False, conjugate_convention="left") == -5
assert Matrix([I, 2*I]).dot(Matrix([I, 2*I]), conjugate_convention="left") == 5
raises(ValueError, lambda: Matrix([1, 2]).dot(Matrix([3, 4]), hermitian=True, conjugate_convention="test"))
with warns_deprecated_sympy():
A = Matrix([[1, 2], [3, 4]])
B = Matrix([[2, 3], [1, 2]])
assert A.dot(B) == [11, 7, 16, 10]
def test_dual():
B_x, B_y, B_z, E_x, E_y, E_z = symbols(
'B_x B_y B_z E_x E_y E_z', real=True)
F = Matrix((
( 0, E_x, E_y, E_z),
(-E_x, 0, B_z, -B_y),
(-E_y, -B_z, 0, B_x),
(-E_z, B_y, -B_x, 0)
))
Fd = Matrix((
( 0, -B_x, -B_y, -B_z),
(B_x, 0, E_z, -E_y),
(B_y, -E_z, 0, E_x),
(B_z, E_y, -E_x, 0)
))
assert F.dual().equals(Fd)
assert eye(3).dual().equals(zeros(3))
assert F.dual().dual().equals(-F)
def test_anti_symmetric():
assert Matrix([1, 2]).is_anti_symmetric() is False
m = Matrix(3, 3, [0, x**2 + 2*x + 1, y, -(x + 1)**2, 0, x*y, -y, -x*y, 0])
assert m.is_anti_symmetric() is True
assert m.is_anti_symmetric(simplify=False) is False
assert m.is_anti_symmetric(simplify=lambda x: x) is False
# tweak to fail
m[2, 1] = -m[2, 1]
assert m.is_anti_symmetric() is False
# untweak
m[2, 1] = -m[2, 1]
m = m.expand()
assert m.is_anti_symmetric(simplify=False) is True
m[0, 0] = 1
assert m.is_anti_symmetric() is False
def test_normalize_sort_diogonalization():
A = Matrix(((1, 2), (2, 1)))
P, Q = A.diagonalize(normalize=True)
assert P*P.T == P.T*P == eye(P.cols)
P, Q = A.diagonalize(normalize=True, sort=True)
assert P*P.T == P.T*P == eye(P.cols)
assert P*Q*P.inv() == A
def test_issue_5321():
raises(ValueError, lambda: Matrix([[1, 2, 3], Matrix(0, 1, [])]))
def test_issue_5320():
assert Matrix.hstack(eye(2), 2*eye(2)) == Matrix([
[1, 0, 2, 0],
[0, 1, 0, 2]
])
assert Matrix.vstack(eye(2), 2*eye(2)) == Matrix([
[1, 0],
[0, 1],
[2, 0],
[0, 2]
])
cls = SparseMatrix
assert cls.hstack(cls(eye(2)), cls(2*eye(2))) == Matrix([
[1, 0, 2, 0],
[0, 1, 0, 2]
])
def test_issue_11944():
A = Matrix([[1]])
AIm = sympify(A)
assert Matrix.hstack(AIm, A) == Matrix([[1, 1]])
assert Matrix.vstack(AIm, A) == Matrix([[1], [1]])
def test_cross():
a = [1, 2, 3]
b = [3, 4, 5]
col = Matrix([-2, 4, -2])
row = col.T
def test(M, ans):
assert ans == M
assert type(M) == cls
for cls in classes:
A = cls(a)
B = cls(b)
test(A.cross(B), col)
test(A.cross(B.T), col)
test(A.T.cross(B.T), row)
test(A.T.cross(B), row)
raises(ShapeError, lambda:
Matrix(1, 2, [1, 1]).cross(Matrix(1, 2, [1, 1])))
def test_hash():
for cls in classes[-2:]:
s = {cls.eye(1), cls.eye(1)}
assert len(s) == 1 and s.pop() == cls.eye(1)
# issue 3979
for cls in classes[:2]:
assert not isinstance(cls.eye(1), Hashable)
@XFAIL
def test_issue_3979():
# when this passes, delete this and change the [1:2]
# to [:2] in the test_hash above for issue 3979
cls = classes[0]
raises(AttributeError, lambda: hash(cls.eye(1)))
def test_adjoint():
dat = [[0, I], [1, 0]]
ans = Matrix([[0, 1], [-I, 0]])
for cls in classes:
assert ans == cls(dat).adjoint()
def test_simplify_immutable():
assert simplify(ImmutableMatrix([[sin(x)**2 + cos(x)**2]])) == \
ImmutableMatrix([[1]])
def test_replace():
F, G = symbols('F, G', cls=Function)
K = Matrix(2, 2, lambda i, j: G(i+j))
M = Matrix(2, 2, lambda i, j: F(i+j))
N = M.replace(F, G)
assert N == K
def test_replace_map():
F, G = symbols('F, G', cls=Function)
with warns_deprecated_sympy():
K = Matrix(2, 2, [(G(0), {F(0): G(0)}), (G(1), {F(1): G(1)}),
(G(1), {F(1): G(1)}), (G(2), {F(2): G(2)})])
M = Matrix(2, 2, lambda i, j: F(i+j))
with warns(SymPyDeprecationWarning, test_stacklevel=False):
N = M.replace(F, G, True)
assert N == K
def test_atoms():
m = Matrix([[1, 2], [x, 1 - 1/x]])
assert m.atoms() == {S.One,S(2),S.NegativeOne, x}
assert m.atoms(Symbol) == {x}
def test_pinv():
# Pseudoinverse of an invertible matrix is the inverse.
A1 = Matrix([[a, b], [c, d]])
assert simplify(A1.pinv(method="RD")) == simplify(A1.inv())
# Test the four properties of the pseudoinverse for various matrices.
As = [Matrix([[13, 104], [2212, 3], [-3, 5]]),
Matrix([[1, 7, 9], [11, 17, 19]]),
Matrix([a, b])]
for A in As:
A_pinv = A.pinv(method="RD")
AAp = A * A_pinv
ApA = A_pinv * A
assert simplify(AAp * A) == A
assert simplify(ApA * A_pinv) == A_pinv
assert AAp.H == AAp
assert ApA.H == ApA
# XXX Pinv with diagonalization makes expression too complicated.
for A in As:
A_pinv = simplify(A.pinv(method="ED"))
AAp = A * A_pinv
ApA = A_pinv * A
assert simplify(AAp * A) == A
assert simplify(ApA * A_pinv) == A_pinv
assert AAp.H == AAp
assert ApA.H == ApA
# XXX Computing pinv using diagonalization makes an expression that
# is too complicated to simplify.
# A1 = Matrix([[a, b], [c, d]])
# assert simplify(A1.pinv(method="ED")) == simplify(A1.inv())
# so this is tested numerically at a fixed random point
from sympy.core.numbers import comp
q = A1.pinv(method="ED")
w = A1.inv()
reps = {a: -73633, b: 11362, c: 55486, d: 62570}
assert all(
comp(i.n(), j.n())
for i, j in zip(q.subs(reps), w.subs(reps))
)
@slow
@XFAIL
def test_pinv_rank_deficient_when_diagonalization_fails():
# Test the four properties of the pseudoinverse for matrices when
# diagonalization of A.H*A fails.
As = [
Matrix([
[61, 89, 55, 20, 71, 0],
[62, 96, 85, 85, 16, 0],
[69, 56, 17, 4, 54, 0],
[10, 54, 91, 41, 71, 0],
[ 7, 30, 10, 48, 90, 0],
[0, 0, 0, 0, 0, 0]])
]
for A in As:
A_pinv = A.pinv(method="ED")
AAp = A * A_pinv
ApA = A_pinv * A
assert AAp.H == AAp
assert ApA.H == ApA
def test_issue_7201():
assert ones(0, 1) + ones(0, 1) == Matrix(0, 1, [])
assert ones(1, 0) + ones(1, 0) == Matrix(1, 0, [])
def test_free_symbols():
for M in ImmutableMatrix, ImmutableSparseMatrix, Matrix, SparseMatrix:
assert M([[x], [0]]).free_symbols == {x}
def test_from_ndarray():
"""See issue 7465."""
try:
from numpy import array
except ImportError:
skip('NumPy must be available to test creating matrices from ndarrays')
assert Matrix(array([1, 2, 3])) == Matrix([1, 2, 3])
assert Matrix(array([[1, 2, 3]])) == Matrix([[1, 2, 3]])
assert Matrix(array([[1, 2, 3], [4, 5, 6]])) == \
Matrix([[1, 2, 3], [4, 5, 6]])
assert Matrix(array([x, y, z])) == Matrix([x, y, z])
raises(NotImplementedError,
lambda: Matrix(array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])))
assert Matrix([array([1, 2]), array([3, 4])]) == Matrix([[1, 2], [3, 4]])
assert Matrix([array([1, 2]), [3, 4]]) == Matrix([[1, 2], [3, 4]])
assert Matrix([array([]), array([])]) == Matrix([])
def test_17522_numpy():
from sympy.matrices.common import _matrixify
try:
from numpy import array, matrix
except ImportError:
skip('NumPy must be available to test indexing matrixified NumPy ndarrays and matrices')
m = _matrixify(array([[1, 2], [3, 4]]))
assert m[3] == 4
assert list(m) == [1, 2, 3, 4]
with ignore_warnings(PendingDeprecationWarning):
m = _matrixify(matrix([[1, 2], [3, 4]]))
assert m[3] == 4
assert list(m) == [1, 2, 3, 4]
def test_17522_mpmath():
from sympy.matrices.common import _matrixify
try:
from mpmath import matrix
except ImportError:
skip('mpmath must be available to test indexing matrixified mpmath matrices')
m = _matrixify(matrix([[1, 2], [3, 4]]))
assert m[3] == 4
assert list(m) == [1, 2, 3, 4]
def test_17522_scipy():
from sympy.matrices.common import _matrixify
try:
from scipy.sparse import csr_matrix
except ImportError:
skip('SciPy must be available to test indexing matrixified SciPy sparse matrices')
m = _matrixify(csr_matrix([[1, 2], [3, 4]]))
assert m[3] == 4
assert list(m) == [1, 2, 3, 4]
def test_hermitian():
a = Matrix([[1, I], [-I, 1]])
assert a.is_hermitian
a[0, 0] = 2*I
assert a.is_hermitian is False
a[0, 0] = x
assert a.is_hermitian is None
a[0, 1] = a[1, 0]*I
assert a.is_hermitian is False
def test_doit():
a = Matrix([[Add(x,x, evaluate=False)]])
assert a[0] != 2*x
assert a.doit() == Matrix([[2*x]])
def test_issue_9457_9467_9876():
# for row_del(index)
M = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
M.row_del(1)
assert M == Matrix([[1, 2, 3], [3, 4, 5]])
N = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
N.row_del(-2)
assert N == Matrix([[1, 2, 3], [3, 4, 5]])
O = Matrix([[1, 2, 3], [5, 6, 7], [9, 10, 11]])
O.row_del(-1)
assert O == Matrix([[1, 2, 3], [5, 6, 7]])
P = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
raises(IndexError, lambda: P.row_del(10))
Q = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
raises(IndexError, lambda: Q.row_del(-10))
# for col_del(index)
M = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
M.col_del(1)
assert M == Matrix([[1, 3], [2, 4], [3, 5]])
N = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
N.col_del(-2)
assert N == Matrix([[1, 3], [2, 4], [3, 5]])
P = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
raises(IndexError, lambda: P.col_del(10))
Q = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
raises(IndexError, lambda: Q.col_del(-10))
def test_issue_9422():
x, y = symbols('x y', commutative=False)
a, b = symbols('a b')
M = eye(2)
M1 = Matrix(2, 2, [x, y, y, z])
assert y*x*M != x*y*M
assert b*a*M == a*b*M
assert x*M1 != M1*x
assert a*M1 == M1*a
assert y*x*M == Matrix([[y*x, 0], [0, y*x]])
def test_issue_10770():
M = Matrix([])
a = ['col_insert', 'row_join'], Matrix([9, 6, 3])
b = ['row_insert', 'col_join'], a[1].T
c = ['row_insert', 'col_insert'], Matrix([[1, 2], [3, 4]])
for ops, m in (a, b, c):
for op in ops:
f = getattr(M, op)
new = f(m) if 'join' in op else f(42, m)
assert new == m and id(new) != id(m)
def test_issue_10658():
A = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
assert A.extract([0, 1, 2], [True, True, False]) == \
Matrix([[1, 2], [4, 5], [7, 8]])
assert A.extract([0, 1, 2], [True, False, False]) == Matrix([[1], [4], [7]])
assert A.extract([True, False, False], [0, 1, 2]) == Matrix([[1, 2, 3]])
assert A.extract([True, False, True], [0, 1, 2]) == \
Matrix([[1, 2, 3], [7, 8, 9]])
assert A.extract([0, 1, 2], [False, False, False]) == Matrix(3, 0, [])
assert A.extract([False, False, False], [0, 1, 2]) == Matrix(0, 3, [])
assert A.extract([True, False, True], [False, True, False]) == \
Matrix([[2], [8]])
def test_opportunistic_simplification():
# this test relates to issue #10718, #9480, #11434
# issue #9480
m = Matrix([[-5 + 5*sqrt(2), -5], [-5*sqrt(2)/2 + 5, -5*sqrt(2)/2]])
assert m.rank() == 1
# issue #10781
m = Matrix([[3+3*sqrt(3)*I, -9],[4,-3+3*sqrt(3)*I]])
assert simplify(m.rref()[0] - Matrix([[1, -9/(3 + 3*sqrt(3)*I)], [0, 0]])) == zeros(2, 2)
# issue #11434
ax,ay,bx,by,cx,cy,dx,dy,ex,ey,t0,t1 = symbols('a_x a_y b_x b_y c_x c_y d_x d_y e_x e_y t_0 t_1')
m = Matrix([[ax,ay,ax*t0,ay*t0,0],[bx,by,bx*t0,by*t0,0],[cx,cy,cx*t0,cy*t0,1],[dx,dy,dx*t0,dy*t0,1],[ex,ey,2*ex*t1-ex*t0,2*ey*t1-ey*t0,0]])
assert m.rank() == 4
def test_partial_pivoting():
# example from https://en.wikipedia.org/wiki/Pivot_element
# partial pivoting with back substitution gives a perfect result
# naive pivoting give an error ~1e-13, so anything better than
# 1e-15 is good
mm=Matrix([[0.003, 59.14, 59.17], [5.291, -6.13, 46.78]])
assert (mm.rref()[0] - Matrix([[1.0, 0, 10.0],
[ 0, 1.0, 1.0]])).norm() < 1e-15
# issue #11549
m_mixed = Matrix([[6e-17, 1.0, 4],
[ -1.0, 0, 8],
[ 0, 0, 1]])
m_float = Matrix([[6e-17, 1.0, 4.],
[ -1.0, 0., 8.],
[ 0., 0., 1.]])
m_inv = Matrix([[ 0, -1.0, 8.0],
[1.0, 6.0e-17, -4.0],
[ 0, 0, 1]])
# this example is numerically unstable and involves a matrix with a norm >= 8,
# this comparing the difference of the results with 1e-15 is numerically sound.
assert (m_mixed.inv() - m_inv).norm() < 1e-15
assert (m_float.inv() - m_inv).norm() < 1e-15
def test_iszero_substitution():
""" When doing numerical computations, all elements that pass
the iszerofunc test should be set to numerically zero if they
aren't already. """
# Matrix from issue #9060
m = Matrix([[0.9, -0.1, -0.2, 0],[-0.8, 0.9, -0.4, 0],[-0.1, -0.8, 0.6, 0]])
m_rref = m.rref(iszerofunc=lambda x: abs(x)<6e-15)[0]
m_correct = Matrix([[1.0, 0, -0.301369863013699, 0],[ 0, 1.0, -0.712328767123288, 0],[ 0, 0, 0, 0]])
m_diff = m_rref - m_correct
assert m_diff.norm() < 1e-15
# if a zero-substitution wasn't made, this entry will be -1.11022302462516e-16
assert m_rref[2,2] == 0
def test_issue_11238():
from sympy.geometry.point import Point
xx = 8*tan(pi*Rational(13, 45))/(tan(pi*Rational(13, 45)) + sqrt(3))
yy = (-8*sqrt(3)*tan(pi*Rational(13, 45))**2 + 24*tan(pi*Rational(13, 45)))/(-3 + tan(pi*Rational(13, 45))**2)
p1 = Point(0, 0)
p2 = Point(1, -sqrt(3))
p0 = Point(xx,yy)
m1 = Matrix([p1 - simplify(p0), p2 - simplify(p0)])
m2 = Matrix([p1 - p0, p2 - p0])
m3 = Matrix([simplify(p1 - p0), simplify(p2 - p0)])
# This system has expressions which are zero and
# cannot be easily proved to be such, so without
# numerical testing, these assertions will fail.
Z = lambda x: abs(x.n()) < 1e-20
assert m1.rank(simplify=True, iszerofunc=Z) == 1
assert m2.rank(simplify=True, iszerofunc=Z) == 1
assert m3.rank(simplify=True, iszerofunc=Z) == 1
def test_as_real_imag():
m1 = Matrix(2,2,[1,2,3,4])
m2 = m1*S.ImaginaryUnit
m3 = m1 + m2
for kls in classes:
a,b = kls(m3).as_real_imag()
assert list(a) == list(m1)
assert list(b) == list(m1)
def test_deprecated():
# Maintain tests for deprecated functions. We must capture
# the deprecation warnings. When the deprecated functionality is
# removed, the corresponding tests should be removed.
m = Matrix(3, 3, [0, 1, 0, -4, 4, 0, -2, 1, 2])
P, Jcells = m.jordan_cells()
assert Jcells[1] == Matrix(1, 1, [2])
assert Jcells[0] == Matrix(2, 2, [2, 1, 0, 2])
with warns_deprecated_sympy():
assert Matrix([[1,2],[3,4]]).dot(Matrix([[1,3],[4,5]])) == [10, 19, 14, 28]
def test_issue_14489():
from sympy.core.mod import Mod
A = Matrix([-1, 1, 2])
B = Matrix([10, 20, -15])
assert Mod(A, 3) == Matrix([2, 1, 2])
assert Mod(B, 4) == Matrix([2, 0, 1])
def test_issue_14943():
# Test that __array__ accepts the optional dtype argument
try:
from numpy import array
except ImportError:
skip('NumPy must be available to test creating matrices from ndarrays')
M = Matrix([[1,2], [3,4]])
assert array(M, dtype=float).dtype.name == 'float64'
def test_case_6913():
m = MatrixSymbol('m', 1, 1)
a = Symbol("a")
a = m[0, 0]>0
assert str(a) == 'm[0, 0] > 0'
def test_issue_11948():
A = MatrixSymbol('A', 3, 3)
a = Wild('a')
assert A.match(a) == {a: A}
def test_gramschmidt_conjugate_dot():
vecs = [Matrix([1, I]), Matrix([1, -I])]
assert Matrix.orthogonalize(*vecs) == \
[Matrix([[1], [I]]), Matrix([[1], [-I]])]
vecs = [Matrix([1, I, 0]), Matrix([I, 0, -I])]
assert Matrix.orthogonalize(*vecs) == \
[Matrix([[1], [I], [0]]), Matrix([[I/2], [S(1)/2], [-I]])]
mat = Matrix([[1, I], [1, -I]])
Q, R = mat.QRdecomposition()
assert Q * Q.H == Matrix.eye(2)
def test_issue_8207():
a = Matrix(MatrixSymbol('a', 3, 1))
b = Matrix(MatrixSymbol('b', 3, 1))
c = a.dot(b)
d = diff(c, a[0, 0])
e = diff(d, a[0, 0])
assert d == b[0, 0]
assert e == 0
def test_func():
from sympy.simplify.simplify import nthroot
A = Matrix([[1, 2],[0, 3]])
assert A.analytic_func(sin(x*t), x) == Matrix([[sin(t), sin(3*t) - sin(t)], [0, sin(3*t)]])
A = Matrix([[2, 1],[1, 2]])
assert (pi * A / 6).analytic_func(cos(x), x) == Matrix([[sqrt(3)/4, -sqrt(3)/4], [-sqrt(3)/4, sqrt(3)/4]])
raises(ValueError, lambda : zeros(5).analytic_func(log(x), x))
raises(ValueError, lambda : (A*x).analytic_func(log(x), x))
A = Matrix([[0, -1, -2, 3], [0, -1, -2, 3], [0, 1, 0, -1], [0, 0, -1, 1]])
assert A.analytic_func(exp(x), x) == A.exp()
raises(ValueError, lambda : A.analytic_func(sqrt(x), x))
A = Matrix([[41, 12],[12, 34]])
assert simplify(A.analytic_func(sqrt(x), x)**2) == A
A = Matrix([[3, -12, 4], [-1, 0, -2], [-1, 5, -1]])
assert simplify(A.analytic_func(nthroot(x, 3), x)**3) == A
A = Matrix([[2, 0, 0, 0], [1, 2, 0, 0], [0, 1, 3, 0], [0, 0, 1, 3]])
assert A.analytic_func(exp(x), x) == A.exp()
A = Matrix([[0, 2, 1, 6], [0, 0, 1, 2], [0, 0, 0, 3], [0, 0, 0, 0]])
assert A.analytic_func(exp(x*t), x) == expand(simplify((A*t).exp()))
def test_issue_19809():
if pyodide_js:
skip("can't run on pyodide")
def f():
assert _dotprodsimp_state.state == None
m = Matrix([[1]])
m = m * m
return True
with dotprodsimp(True):
with concurrent.futures.ThreadPoolExecutor() as executor:
future = executor.submit(f)
assert future.result()
def test_deprecated_classof_a2idx():
with warns_deprecated_sympy():
from sympy.matrices.matrices import classof
M = Matrix([[1, 2], [3, 4]])
IM = ImmutableMatrix([[1, 2], [3, 4]])
assert classof(M, IM) == ImmutableDenseMatrix
with warns_deprecated_sympy():
from sympy.matrices.matrices import a2idx
assert a2idx(-1, 3) == 2
def test_issue_23276():
M = Matrix([x, y])
assert integrate(M, (x, 0, 1), (y, 0, 1)) == Matrix([
[1/2],
[1/2]])
|
c0581c30ea7ab9a919eb092417b981ec6c0cdf9192e521b35f3d4b09e25b7a61 | from sympy.core.expr import ExprBuilder
from sympy.core.function import (Function, FunctionClass, Lambda)
from sympy.core.symbol import Dummy
from sympy.core.sympify import sympify, _sympify
from sympy.matrices.expressions import MatrixExpr
from sympy.matrices.matrices import MatrixBase
class ElementwiseApplyFunction(MatrixExpr):
r"""
Apply function to a matrix elementwise without evaluating.
Examples
========
It can be created by calling ``.applyfunc(<function>)`` on a matrix
expression:
>>> from sympy import MatrixSymbol
>>> from sympy.matrices.expressions.applyfunc import ElementwiseApplyFunction
>>> from sympy import exp
>>> X = MatrixSymbol("X", 3, 3)
>>> X.applyfunc(exp)
Lambda(_d, exp(_d)).(X)
Otherwise using the class constructor:
>>> from sympy import eye
>>> expr = ElementwiseApplyFunction(exp, eye(3))
>>> expr
Lambda(_d, exp(_d)).(Matrix([
[1, 0, 0],
[0, 1, 0],
[0, 0, 1]]))
>>> expr.doit()
Matrix([
[E, 1, 1],
[1, E, 1],
[1, 1, E]])
Notice the difference with the real mathematical functions:
>>> exp(eye(3))
Matrix([
[E, 0, 0],
[0, E, 0],
[0, 0, E]])
"""
def __new__(cls, function, expr):
expr = _sympify(expr)
if not expr.is_Matrix:
raise ValueError("{} must be a matrix instance.".format(expr))
if expr.shape == (1, 1):
# Check if the function returns a matrix, in that case, just apply
# the function instead of creating an ElementwiseApplyFunc object:
ret = function(expr)
if isinstance(ret, MatrixExpr):
return ret
if not isinstance(function, (FunctionClass, Lambda)):
d = Dummy('d')
function = Lambda(d, function(d))
function = sympify(function)
if not isinstance(function, (FunctionClass, Lambda)):
raise ValueError(
"{} should be compatible with SymPy function classes."
.format(function))
if 1 not in function.nargs:
raise ValueError(
'{} should be able to accept 1 arguments.'.format(function))
if not isinstance(function, Lambda):
d = Dummy('d')
function = Lambda(d, function(d))
obj = MatrixExpr.__new__(cls, function, expr)
return obj
@property
def function(self):
return self.args[0]
@property
def expr(self):
return self.args[1]
@property
def shape(self):
return self.expr.shape
def doit(self, **hints):
deep = hints.get("deep", True)
expr = self.expr
if deep:
expr = expr.doit(**hints)
function = self.function
if isinstance(function, Lambda) and function.is_identity:
# This is a Lambda containing the identity function.
return expr
if isinstance(expr, MatrixBase):
return expr.applyfunc(self.function)
elif isinstance(expr, ElementwiseApplyFunction):
return ElementwiseApplyFunction(
lambda x: self.function(expr.function(x)),
expr.expr
).doit(**hints)
else:
return self
def _entry(self, i, j, **kwargs):
return self.function(self.expr._entry(i, j, **kwargs))
def _get_function_fdiff(self):
d = Dummy("d")
function = self.function(d)
fdiff = function.diff(d)
if isinstance(fdiff, Function):
fdiff = type(fdiff)
else:
fdiff = Lambda(d, fdiff)
return fdiff
def _eval_derivative(self, x):
from sympy.matrices.expressions.hadamard import hadamard_product
dexpr = self.expr.diff(x)
fdiff = self._get_function_fdiff()
return hadamard_product(
dexpr,
ElementwiseApplyFunction(fdiff, self.expr)
)
def _eval_derivative_matrix_lines(self, x):
from sympy.matrices.expressions.special import Identity
from sympy.tensor.array.expressions.array_expressions import ArrayContraction
from sympy.tensor.array.expressions.array_expressions import ArrayDiagonal
from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct
fdiff = self._get_function_fdiff()
lr = self.expr._eval_derivative_matrix_lines(x)
ewdiff = ElementwiseApplyFunction(fdiff, self.expr)
if 1 in x.shape:
# Vector:
iscolumn = self.shape[1] == 1
for i in lr:
if iscolumn:
ptr1 = i.first_pointer
ptr2 = Identity(self.shape[1])
else:
ptr1 = Identity(self.shape[0])
ptr2 = i.second_pointer
subexpr = ExprBuilder(
ArrayDiagonal,
[
ExprBuilder(
ArrayTensorProduct,
[
ewdiff,
ptr1,
ptr2,
]
),
(0, 2) if iscolumn else (1, 4)
],
validator=ArrayDiagonal._validate
)
i._lines = [subexpr]
i._first_pointer_parent = subexpr.args[0].args
i._first_pointer_index = 1
i._second_pointer_parent = subexpr.args[0].args
i._second_pointer_index = 2
else:
# Matrix case:
for i in lr:
ptr1 = i.first_pointer
ptr2 = i.second_pointer
newptr1 = Identity(ptr1.shape[1])
newptr2 = Identity(ptr2.shape[1])
subexpr = ExprBuilder(
ArrayContraction,
[
ExprBuilder(
ArrayTensorProduct,
[ptr1, newptr1, ewdiff, ptr2, newptr2]
),
(1, 2, 4),
(5, 7, 8),
],
validator=ArrayContraction._validate
)
i._first_pointer_parent = subexpr.args[0].args
i._first_pointer_index = 1
i._second_pointer_parent = subexpr.args[0].args
i._second_pointer_index = 4
i._lines = [subexpr]
return lr
def _eval_transpose(self):
from sympy.matrices.expressions.transpose import Transpose
return self.func(self.function, Transpose(self.expr).doit())
|
b1fd5178e9793d4bbc6dbb1b8afba9b94b6bd3260c02dbc3acc285128f2f1143 | from sympy.core.basic import Basic
from sympy.core.expr import Expr
from sympy.core.singleton import S
from sympy.core.sympify import sympify
from sympy.matrices.common import NonSquareMatrixError
class Determinant(Expr):
"""Matrix Determinant
Represents the determinant of a matrix expression.
Examples
========
>>> from sympy import MatrixSymbol, Determinant, eye
>>> A = MatrixSymbol('A', 3, 3)
>>> Determinant(A)
Determinant(A)
>>> Determinant(eye(3)).doit()
1
"""
is_commutative = True
def __new__(cls, mat):
mat = sympify(mat)
if not mat.is_Matrix:
raise TypeError("Input to Determinant, %s, not a matrix" % str(mat))
if not mat.is_square:
raise NonSquareMatrixError("Det of a non-square matrix")
return Basic.__new__(cls, mat)
@property
def arg(self):
return self.args[0]
@property
def kind(self):
return self.arg.kind.element_kind
def doit(self, expand=False, **hints):
try:
return self.arg._eval_determinant()
except (AttributeError, NotImplementedError):
return self
def det(matexpr):
""" Matrix Determinant
Examples
========
>>> from sympy import MatrixSymbol, det, eye
>>> A = MatrixSymbol('A', 3, 3)
>>> det(A)
Determinant(A)
>>> det(eye(3))
1
"""
return Determinant(matexpr).doit()
class Permanent(Expr):
"""Matrix Permanent
Represents the permanent of a matrix expression.
Examples
========
>>> from sympy import MatrixSymbol, Permanent, ones
>>> A = MatrixSymbol('A', 3, 3)
>>> Permanent(A)
Permanent(A)
>>> Permanent(ones(3, 3)).doit()
6
"""
def __new__(cls, mat):
mat = sympify(mat)
if not mat.is_Matrix:
raise TypeError("Input to Permanent, %s, not a matrix" % str(mat))
return Basic.__new__(cls, mat)
@property
def arg(self):
return self.args[0]
def doit(self, expand=False, **hints):
try:
return self.arg.per()
except (AttributeError, NotImplementedError):
return self
def per(matexpr):
""" Matrix Permanent
Examples
========
>>> from sympy import MatrixSymbol, Matrix, per, ones
>>> A = MatrixSymbol('A', 3, 3)
>>> per(A)
Permanent(A)
>>> per(ones(5, 5))
120
>>> M = Matrix([1, 2, 5])
>>> per(M)
8
"""
return Permanent(matexpr).doit()
from sympy.assumptions.ask import ask, Q
from sympy.assumptions.refine import handlers_dict
def refine_Determinant(expr, assumptions):
"""
>>> from sympy import MatrixSymbol, Q, assuming, refine, det
>>> X = MatrixSymbol('X', 2, 2)
>>> det(X)
Determinant(X)
>>> with assuming(Q.orthogonal(X)):
... print(refine(det(X)))
1
"""
if ask(Q.orthogonal(expr.arg), assumptions):
return S.One
elif ask(Q.singular(expr.arg), assumptions):
return S.Zero
elif ask(Q.unit_triangular(expr.arg), assumptions):
return S.One
return expr
handlers_dict['Determinant'] = refine_Determinant
|
d5f0fc6f7947da7dcc19f3f70cf418feccd51b5b1e7ae9bfd58dca986fce5b42 | from sympy.assumptions.ask import ask, Q
from sympy.assumptions.refine import handlers_dict
from sympy.core import Basic, sympify, S
from sympy.core.mul import mul, Mul
from sympy.core.numbers import Number, Integer
from sympy.core.symbol import Dummy
from sympy.functions import adjoint
from sympy.strategies import (rm_id, unpack, typed, flatten, exhaust,
do_one, new)
from sympy.matrices.common import ShapeError, NonInvertibleMatrixError
from sympy.matrices.matrices import MatrixBase
from sympy.utilities.exceptions import sympy_deprecation_warning
from .inverse import Inverse
from .matexpr import MatrixExpr
from .matpow import MatPow
from .transpose import transpose
from .permutation import PermutationMatrix
from .special import ZeroMatrix, Identity, GenericIdentity, OneMatrix
# XXX: MatMul should perhaps not subclass directly from Mul
class MatMul(MatrixExpr, Mul):
"""
A product of matrix expressions
Examples
========
>>> from sympy import MatMul, MatrixSymbol
>>> A = MatrixSymbol('A', 5, 4)
>>> B = MatrixSymbol('B', 4, 3)
>>> C = MatrixSymbol('C', 3, 6)
>>> MatMul(A, B, C)
A*B*C
"""
is_MatMul = True
identity = GenericIdentity()
def __new__(cls, *args, evaluate=False, check=None, _sympify=True):
if not args:
return cls.identity
# This must be removed aggressively in the constructor to avoid
# TypeErrors from GenericIdentity().shape
args = list(filter(lambda i: cls.identity != i, args))
if _sympify:
args = list(map(sympify, args))
obj = Basic.__new__(cls, *args)
factor, matrices = obj.as_coeff_matrices()
if check is not None:
sympy_deprecation_warning(
"Passing check to MatMul is deprecated and the check argument will be removed in a future version.",
deprecated_since_version="1.11",
active_deprecations_target='remove-check-argument-from-matrix-operations')
if check in (True, None):
validate(*matrices)
else:
sympy_deprecation_warning(
"Passing check=False to MatMul is deprecated and the check argument will be removed in a future version.",
deprecated_since_version="1.11",
active_deprecations_target='remove-check-argument-from-matrix-operations')
if not matrices:
# Should it be
#
# return Basic.__neq__(cls, factor, GenericIdentity()) ?
return factor
if evaluate:
return cls._evaluate(obj)
return obj
@classmethod
def _evaluate(cls, expr):
return canonicalize(expr)
@property
def shape(self):
matrices = [arg for arg in self.args if arg.is_Matrix]
return (matrices[0].rows, matrices[-1].cols)
def _entry(self, i, j, expand=True, **kwargs):
# Avoid cyclic imports
from sympy.concrete.summations import Sum
from sympy.matrices.immutable import ImmutableMatrix
coeff, matrices = self.as_coeff_matrices()
if len(matrices) == 1: # situation like 2*X, matmul is just X
return coeff * matrices[0][i, j]
indices = [None]*(len(matrices) + 1)
ind_ranges = [None]*(len(matrices) - 1)
indices[0] = i
indices[-1] = j
def f():
counter = 1
while True:
yield Dummy("i_%i" % counter)
counter += 1
dummy_generator = kwargs.get("dummy_generator", f())
for i in range(1, len(matrices)):
indices[i] = next(dummy_generator)
for i, arg in enumerate(matrices[:-1]):
ind_ranges[i] = arg.shape[1] - 1
matrices = [arg._entry(indices[i], indices[i+1], dummy_generator=dummy_generator) for i, arg in enumerate(matrices)]
expr_in_sum = Mul.fromiter(matrices)
if any(v.has(ImmutableMatrix) for v in matrices):
expand = True
result = coeff*Sum(
expr_in_sum,
*zip(indices[1:-1], [0]*len(ind_ranges), ind_ranges)
)
# Don't waste time in result.doit() if the sum bounds are symbolic
if not any(isinstance(v, (Integer, int)) for v in ind_ranges):
expand = False
return result.doit() if expand else result
def as_coeff_matrices(self):
scalars = [x for x in self.args if not x.is_Matrix]
matrices = [x for x in self.args if x.is_Matrix]
coeff = Mul(*scalars)
if coeff.is_commutative is False:
raise NotImplementedError("noncommutative scalars in MatMul are not supported.")
return coeff, matrices
def as_coeff_mmul(self):
coeff, matrices = self.as_coeff_matrices()
return coeff, MatMul(*matrices)
def expand(self, **kwargs):
expanded = super(MatMul, self).expand(**kwargs)
return self._evaluate(expanded)
def _eval_transpose(self):
"""Transposition of matrix multiplication.
Notes
=====
The following rules are applied.
Transposition for matrix multiplied with another matrix:
`\\left(A B\\right)^{T} = B^{T} A^{T}`
Transposition for matrix multiplied with scalar:
`\\left(c A\\right)^{T} = c A^{T}`
References
==========
.. [1] https://en.wikipedia.org/wiki/Transpose
"""
coeff, matrices = self.as_coeff_matrices()
return MatMul(
coeff, *[transpose(arg) for arg in matrices[::-1]]).doit()
def _eval_adjoint(self):
return MatMul(*[adjoint(arg) for arg in self.args[::-1]]).doit()
def _eval_trace(self):
factor, mmul = self.as_coeff_mmul()
if factor != 1:
from .trace import trace
return factor * trace(mmul.doit())
else:
raise NotImplementedError("Can't simplify any further")
def _eval_determinant(self):
from sympy.matrices.expressions.determinant import Determinant
factor, matrices = self.as_coeff_matrices()
square_matrices = only_squares(*matrices)
return factor**self.rows * Mul(*list(map(Determinant, square_matrices)))
def _eval_inverse(self):
try:
return MatMul(*[
arg.inverse() if isinstance(arg, MatrixExpr) else arg**-1
for arg in self.args[::-1]]).doit()
except ShapeError:
return Inverse(self)
def doit(self, **hints):
deep = hints.get('deep', True)
if deep:
args = [arg.doit(**hints) for arg in self.args]
else:
args = self.args
# treat scalar*MatrixSymbol or scalar*MatPow separately
expr = canonicalize(MatMul(*args))
return expr
# Needed for partial compatibility with Mul
def args_cnc(self, cset=False, warn=True, **kwargs):
coeff_c = [x for x in self.args if x.is_commutative]
coeff_nc = [x for x in self.args if not x.is_commutative]
if cset:
clen = len(coeff_c)
coeff_c = set(coeff_c)
if clen and warn and len(coeff_c) != clen:
raise ValueError('repeated commutative arguments: %s' %
[ci for ci in coeff_c if list(self.args).count(ci) > 1])
return [coeff_c, coeff_nc]
def _eval_derivative_matrix_lines(self, x):
from .transpose import Transpose
with_x_ind = [i for i, arg in enumerate(self.args) if arg.has(x)]
lines = []
for ind in with_x_ind:
left_args = self.args[:ind]
right_args = self.args[ind+1:]
if right_args:
right_mat = MatMul.fromiter(right_args)
else:
right_mat = Identity(self.shape[1])
if left_args:
left_rev = MatMul.fromiter([Transpose(i).doit() if i.is_Matrix else i for i in reversed(left_args)])
else:
left_rev = Identity(self.shape[0])
d = self.args[ind]._eval_derivative_matrix_lines(x)
for i in d:
i.append_first(left_rev)
i.append_second(right_mat)
lines.append(i)
return lines
mul.register_handlerclass((Mul, MatMul), MatMul)
def validate(*matrices):
""" Checks for valid shapes for args of MatMul """
for i in range(len(matrices)-1):
A, B = matrices[i:i+2]
if A.cols != B.rows:
raise ShapeError("Matrices %s and %s are not aligned"%(A, B))
# Rules
def newmul(*args):
if args[0] == 1:
args = args[1:]
return new(MatMul, *args)
def any_zeros(mul):
if any(arg.is_zero or (arg.is_Matrix and arg.is_ZeroMatrix)
for arg in mul.args):
matrices = [arg for arg in mul.args if arg.is_Matrix]
return ZeroMatrix(matrices[0].rows, matrices[-1].cols)
return mul
def merge_explicit(matmul):
""" Merge explicit MatrixBase arguments
>>> from sympy import MatrixSymbol, Matrix, MatMul, pprint
>>> from sympy.matrices.expressions.matmul import merge_explicit
>>> A = MatrixSymbol('A', 2, 2)
>>> B = Matrix([[1, 1], [1, 1]])
>>> C = Matrix([[1, 2], [3, 4]])
>>> X = MatMul(A, B, C)
>>> pprint(X)
[1 1] [1 2]
A*[ ]*[ ]
[1 1] [3 4]
>>> pprint(merge_explicit(X))
[4 6]
A*[ ]
[4 6]
>>> X = MatMul(B, A, C)
>>> pprint(X)
[1 1] [1 2]
[ ]*A*[ ]
[1 1] [3 4]
>>> pprint(merge_explicit(X))
[1 1] [1 2]
[ ]*A*[ ]
[1 1] [3 4]
"""
if not any(isinstance(arg, MatrixBase) for arg in matmul.args):
return matmul
newargs = []
last = matmul.args[0]
for arg in matmul.args[1:]:
if isinstance(arg, (MatrixBase, Number)) and isinstance(last, (MatrixBase, Number)):
last = last * arg
else:
newargs.append(last)
last = arg
newargs.append(last)
return MatMul(*newargs)
def remove_ids(mul):
""" Remove Identities from a MatMul
This is a modified version of sympy.strategies.rm_id.
This is necesssary because MatMul may contain both MatrixExprs and Exprs
as args.
See Also
========
sympy.strategies.rm_id
"""
# Separate Exprs from MatrixExprs in args
factor, mmul = mul.as_coeff_mmul()
# Apply standard rm_id for MatMuls
result = rm_id(lambda x: x.is_Identity is True)(mmul)
if result != mmul:
return newmul(factor, *result.args) # Recombine and return
else:
return mul
def factor_in_front(mul):
factor, matrices = mul.as_coeff_matrices()
if factor != 1:
return newmul(factor, *matrices)
return mul
def combine_powers(mul):
r"""Combine consecutive powers with the same base into one, e.g.
$$A \times A^2 \Rightarrow A^3$$
This also cancels out the possible matrix inverses using the
knowledgebase of :class:`~.Inverse`, e.g.,
$$ Y \times X \times X^{-1} \Rightarrow Y $$
"""
factor, args = mul.as_coeff_matrices()
new_args = [args[0]]
for i in range(1, len(args)):
A = new_args[-1]
B = args[i]
if isinstance(B, Inverse) and isinstance(B.arg, MatMul):
Bargs = B.arg.args
l = len(Bargs)
if list(Bargs) == new_args[-l:]:
new_args = new_args[:-l] + [Identity(B.shape[0])]
continue
if isinstance(A, Inverse) and isinstance(A.arg, MatMul):
Aargs = A.arg.args
l = len(Aargs)
if list(Aargs) == args[i:i+l]:
identity = Identity(A.shape[0])
new_args[-1] = identity
for j in range(i, i+l):
args[j] = identity
continue
if A.is_square == False or B.is_square == False:
new_args.append(B)
continue
if isinstance(A, MatPow):
A_base, A_exp = A.args
else:
A_base, A_exp = A, S.One
if isinstance(B, MatPow):
B_base, B_exp = B.args
else:
B_base, B_exp = B, S.One
if A_base == B_base:
new_exp = A_exp + B_exp
new_args[-1] = MatPow(A_base, new_exp).doit(deep=False)
continue
elif not isinstance(B_base, MatrixBase):
try:
B_base_inv = B_base.inverse()
except NonInvertibleMatrixError:
B_base_inv = None
if B_base_inv is not None and A_base == B_base_inv:
new_exp = A_exp - B_exp
new_args[-1] = MatPow(A_base, new_exp).doit(deep=False)
continue
new_args.append(B)
return newmul(factor, *new_args)
def combine_permutations(mul):
"""Refine products of permutation matrices as the products of cycles.
"""
args = mul.args
l = len(args)
if l < 2:
return mul
result = [args[0]]
for i in range(1, l):
A = result[-1]
B = args[i]
if isinstance(A, PermutationMatrix) and \
isinstance(B, PermutationMatrix):
cycle_1 = A.args[0]
cycle_2 = B.args[0]
result[-1] = PermutationMatrix(cycle_1 * cycle_2)
else:
result.append(B)
return MatMul(*result)
def combine_one_matrices(mul):
"""
Combine products of OneMatrix
e.g. OneMatrix(2, 3) * OneMatrix(3, 4) -> 3 * OneMatrix(2, 4)
"""
factor, args = mul.as_coeff_matrices()
new_args = [args[0]]
for B in args[1:]:
A = new_args[-1]
if not isinstance(A, OneMatrix) or not isinstance(B, OneMatrix):
new_args.append(B)
continue
new_args.pop()
new_args.append(OneMatrix(A.shape[0], B.shape[1]))
factor *= A.shape[1]
return newmul(factor, *new_args)
def distribute_monom(mul):
"""
Simplify MatMul expressions but distributing
rational term to MatMul.
e.g. 2*(A+B) -> 2*A + 2*B
"""
args = mul.args
if len(args) == 2:
from .matadd import MatAdd
if args[0].is_MatAdd and args[1].is_Rational:
return MatAdd(*[MatMul(mat, args[1]).doit() for mat in args[0].args])
if args[1].is_MatAdd and args[0].is_Rational:
return MatAdd(*[MatMul(args[0], mat).doit() for mat in args[1].args])
return mul
rules = (
distribute_monom, any_zeros, remove_ids, combine_one_matrices, combine_powers, unpack, rm_id(lambda x: x == 1),
merge_explicit, factor_in_front, flatten, combine_permutations)
canonicalize = exhaust(typed({MatMul: do_one(*rules)}))
def only_squares(*matrices):
"""factor matrices only if they are square"""
if matrices[0].rows != matrices[-1].cols:
raise RuntimeError("Invalid matrices being multiplied")
out = []
start = 0
for i, M in enumerate(matrices):
if M.cols == matrices[start].rows:
out.append(MatMul(*matrices[start:i+1]).doit())
start = i+1
return out
def refine_MatMul(expr, assumptions):
"""
>>> from sympy import MatrixSymbol, Q, assuming, refine
>>> X = MatrixSymbol('X', 2, 2)
>>> expr = X * X.T
>>> print(expr)
X*X.T
>>> with assuming(Q.orthogonal(X)):
... print(refine(expr))
I
"""
newargs = []
exprargs = []
for args in expr.args:
if args.is_Matrix:
exprargs.append(args)
else:
newargs.append(args)
last = exprargs[0]
for arg in exprargs[1:]:
if arg == last.T and ask(Q.orthogonal(arg), assumptions):
last = Identity(arg.shape[0])
elif arg == last.conjugate() and ask(Q.unitary(arg), assumptions):
last = Identity(arg.shape[0])
else:
newargs.append(last)
last = arg
newargs.append(last)
return MatMul(*newargs)
handlers_dict['MatMul'] = refine_MatMul
|
aced867051086fd0330f1e655e4a2b481caa4f0585770a4900aa0e7570735b46 | from sympy.matrices.common import NonSquareMatrixError
from .matexpr import MatrixExpr
from .special import Identity
from sympy.core import S
from sympy.core.expr import ExprBuilder
from sympy.core.cache import cacheit
from sympy.core.power import Pow
from sympy.core.sympify import _sympify
from sympy.matrices import MatrixBase
class MatPow(MatrixExpr):
def __new__(cls, base, exp, evaluate=False, **options):
base = _sympify(base)
if not base.is_Matrix:
raise TypeError("MatPow base should be a matrix")
if not base.is_square:
raise NonSquareMatrixError("Power of non-square matrix %s" % base)
exp = _sympify(exp)
obj = super().__new__(cls, base, exp)
if evaluate:
obj = obj.doit(deep=False)
return obj
@property
def base(self):
return self.args[0]
@property
def exp(self):
return self.args[1]
@property
def shape(self):
return self.base.shape
@cacheit
def _get_explicit_matrix(self):
return self.base.as_explicit()**self.exp
def _entry(self, i, j, **kwargs):
from sympy.matrices.expressions import MatMul
A = self.doit()
if isinstance(A, MatPow):
# We still have a MatPow, make an explicit MatMul out of it.
if A.exp.is_Integer and A.exp.is_positive:
A = MatMul(*[A.base for k in range(A.exp)])
elif not self._is_shape_symbolic():
return A._get_explicit_matrix()[i, j]
else:
# Leave the expression unevaluated:
from sympy.matrices.expressions.matexpr import MatrixElement
return MatrixElement(self, i, j)
return A[i, j]
def doit(self, **hints):
if hints.get('deep', True):
base, exp = [arg.doit(**hints) for arg in self.args]
else:
base, exp = self.args
# combine all powers, e.g. (A ** 2) ** 3 -> A ** 6
while isinstance(base, MatPow):
exp *= base.args[1]
base = base.args[0]
if isinstance(base, MatrixBase):
# Delegate
return base ** exp
# Handle simple cases so that _eval_power() in MatrixExpr sub-classes can ignore them
if exp == S.One:
return base
if exp == S.Zero:
return Identity(base.rows)
if exp == S.NegativeOne:
from sympy.matrices.expressions import Inverse
return Inverse(base).doit(**hints)
eval_power = getattr(base, '_eval_power', None)
if eval_power is not None:
return eval_power(exp)
return MatPow(base, exp)
def _eval_transpose(self):
base, exp = self.args
return MatPow(base.T, exp)
def _eval_derivative(self, x):
return Pow._eval_derivative(self, x)
def _eval_derivative_matrix_lines(self, x):
from sympy.tensor.array.expressions.array_expressions import ArrayContraction
from ...tensor.array.expressions.array_expressions import ArrayTensorProduct
from .matmul import MatMul
from .inverse import Inverse
exp = self.exp
if self.base.shape == (1, 1) and not exp.has(x):
lr = self.base._eval_derivative_matrix_lines(x)
for i in lr:
subexpr = ExprBuilder(
ArrayContraction,
[
ExprBuilder(
ArrayTensorProduct,
[
Identity(1),
i._lines[0],
exp*self.base**(exp-1),
i._lines[1],
Identity(1),
]
),
(0, 3, 4), (5, 7, 8)
],
validator=ArrayContraction._validate
)
i._first_pointer_parent = subexpr.args[0].args
i._first_pointer_index = 0
i._second_pointer_parent = subexpr.args[0].args
i._second_pointer_index = 4
i._lines = [subexpr]
return lr
if (exp > 0) == True:
newexpr = MatMul.fromiter([self.base for i in range(exp)])
elif (exp == -1) == True:
return Inverse(self.base)._eval_derivative_matrix_lines(x)
elif (exp < 0) == True:
newexpr = MatMul.fromiter([Inverse(self.base) for i in range(-exp)])
elif (exp == 0) == True:
return self.doit()._eval_derivative_matrix_lines(x)
else:
raise NotImplementedError("cannot evaluate %s derived by %s" % (self, x))
return newexpr._eval_derivative_matrix_lines(x)
def _eval_inverse(self):
return MatPow(self.base, -self.exp)
|
806221b7e248d735b2673ed53ef9b94b501eda2f8fd16500265ddeb8b4575ad3 | from sympy.core import S
from sympy.core.sympify import _sympify
from sympy.functions import KroneckerDelta
from .matexpr import MatrixExpr
from .special import ZeroMatrix, Identity, OneMatrix
class PermutationMatrix(MatrixExpr):
"""A Permutation Matrix
Parameters
==========
perm : Permutation
The permutation the matrix uses.
The size of the permutation determines the matrix size.
See the documentation of
:class:`sympy.combinatorics.permutations.Permutation` for
the further information of how to create a permutation object.
Examples
========
>>> from sympy import Matrix, PermutationMatrix
>>> from sympy.combinatorics import Permutation
Creating a permutation matrix:
>>> p = Permutation(1, 2, 0)
>>> P = PermutationMatrix(p)
>>> P = P.as_explicit()
>>> P
Matrix([
[0, 1, 0],
[0, 0, 1],
[1, 0, 0]])
Permuting a matrix row and column:
>>> M = Matrix([0, 1, 2])
>>> Matrix(P*M)
Matrix([
[1],
[2],
[0]])
>>> Matrix(M.T*P)
Matrix([[2, 0, 1]])
See Also
========
sympy.combinatorics.permutations.Permutation
"""
def __new__(cls, perm):
from sympy.combinatorics.permutations import Permutation
perm = _sympify(perm)
if not isinstance(perm, Permutation):
raise ValueError(
"{} must be a SymPy Permutation instance.".format(perm))
return super().__new__(cls, perm)
@property
def shape(self):
size = self.args[0].size
return (size, size)
@property
def is_Identity(self):
return self.args[0].is_Identity
def doit(self, **hints):
if self.is_Identity:
return Identity(self.rows)
return self
def _entry(self, i, j, **kwargs):
perm = self.args[0]
return KroneckerDelta(perm.apply(i), j)
def _eval_power(self, exp):
return PermutationMatrix(self.args[0] ** exp).doit()
def _eval_inverse(self):
return PermutationMatrix(self.args[0] ** -1)
_eval_transpose = _eval_adjoint = _eval_inverse
def _eval_determinant(self):
sign = self.args[0].signature()
if sign == 1:
return S.One
elif sign == -1:
return S.NegativeOne
raise NotImplementedError
def _eval_rewrite_as_BlockDiagMatrix(self, *args, **kwargs):
from sympy.combinatorics.permutations import Permutation
from .blockmatrix import BlockDiagMatrix
perm = self.args[0]
full_cyclic_form = perm.full_cyclic_form
cycles_picks = []
# Stage 1. Decompose the cycles into the blockable form.
a, b, c = 0, 0, 0
flag = False
for cycle in full_cyclic_form:
l = len(cycle)
m = max(cycle)
if not flag:
if m + 1 > a + l:
flag = True
temp = [cycle]
b = m
c = l
else:
cycles_picks.append([cycle])
a += l
else:
if m > b:
if m + 1 == a + c + l:
temp.append(cycle)
cycles_picks.append(temp)
flag = False
a = m+1
else:
b = m
temp.append(cycle)
c += l
else:
if b + 1 == a + c + l:
temp.append(cycle)
cycles_picks.append(temp)
flag = False
a = b+1
else:
temp.append(cycle)
c += l
# Stage 2. Normalize each decomposed cycles and build matrix.
p = 0
args = []
for pick in cycles_picks:
new_cycles = []
l = 0
for cycle in pick:
new_cycle = [i - p for i in cycle]
new_cycles.append(new_cycle)
l += len(cycle)
p += l
perm = Permutation(new_cycles)
mat = PermutationMatrix(perm)
args.append(mat)
return BlockDiagMatrix(*args)
class MatrixPermute(MatrixExpr):
r"""Symbolic representation for permuting matrix rows or columns.
Parameters
==========
perm : Permutation, PermutationMatrix
The permutation to use for permuting the matrix.
The permutation can be resized to the suitable one,
axis : 0 or 1
The axis to permute alongside.
If `0`, it will permute the matrix rows.
If `1`, it will permute the matrix columns.
Notes
=====
This follows the same notation used in
:meth:`sympy.matrices.common.MatrixCommon.permute`.
Examples
========
>>> from sympy import Matrix, MatrixPermute
>>> from sympy.combinatorics import Permutation
Permuting the matrix rows:
>>> p = Permutation(1, 2, 0)
>>> A = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
>>> B = MatrixPermute(A, p, axis=0)
>>> B.as_explicit()
Matrix([
[4, 5, 6],
[7, 8, 9],
[1, 2, 3]])
Permuting the matrix columns:
>>> B = MatrixPermute(A, p, axis=1)
>>> B.as_explicit()
Matrix([
[2, 3, 1],
[5, 6, 4],
[8, 9, 7]])
See Also
========
sympy.matrices.common.MatrixCommon.permute
"""
def __new__(cls, mat, perm, axis=S.Zero):
from sympy.combinatorics.permutations import Permutation
mat = _sympify(mat)
if not mat.is_Matrix:
raise ValueError(
"{} must be a SymPy matrix instance.".format(perm))
perm = _sympify(perm)
if isinstance(perm, PermutationMatrix):
perm = perm.args[0]
if not isinstance(perm, Permutation):
raise ValueError(
"{} must be a SymPy Permutation or a PermutationMatrix " \
"instance".format(perm))
axis = _sympify(axis)
if axis not in (0, 1):
raise ValueError("The axis must be 0 or 1.")
mat_size = mat.shape[axis]
if mat_size != perm.size:
try:
perm = perm.resize(mat_size)
except ValueError:
raise ValueError(
"Size does not match between the permutation {} "
"and the matrix {} threaded over the axis {} "
"and cannot be converted."
.format(perm, mat, axis))
return super().__new__(cls, mat, perm, axis)
def doit(self, deep=True, **hints):
mat, perm, axis = self.args
if deep:
mat = mat.doit(deep=deep, **hints)
perm = perm.doit(deep=deep, **hints)
if perm.is_Identity:
return mat
if mat.is_Identity:
if axis is S.Zero:
return PermutationMatrix(perm)
elif axis is S.One:
return PermutationMatrix(perm**-1)
if isinstance(mat, (ZeroMatrix, OneMatrix)):
return mat
if isinstance(mat, MatrixPermute) and mat.args[2] == axis:
return MatrixPermute(mat.args[0], perm * mat.args[1], axis)
return self
@property
def shape(self):
return self.args[0].shape
def _entry(self, i, j, **kwargs):
mat, perm, axis = self.args
if axis == 0:
return mat[perm.apply(i), j]
elif axis == 1:
return mat[i, perm.apply(j)]
def _eval_rewrite_as_MatMul(self, *args, **kwargs):
from .matmul import MatMul
mat, perm, axis = self.args
deep = kwargs.get("deep", True)
if deep:
mat = mat.rewrite(MatMul)
if axis == 0:
return MatMul(PermutationMatrix(perm), mat)
elif axis == 1:
return MatMul(mat, PermutationMatrix(perm**-1))
|
e7e43560ef084118ae55aca9815584e20239697b520655660e3dee247b3f3d8c | from sympy.assumptions.ask import ask, Q
from sympy.core.relational import Eq
from sympy.core.singleton import S
from sympy.core.sympify import _sympify
from sympy.functions.special.tensor_functions import KroneckerDelta
from sympy.matrices.common import NonInvertibleMatrixError
from .matexpr import MatrixExpr
class ZeroMatrix(MatrixExpr):
"""The Matrix Zero 0 - additive identity
Examples
========
>>> from sympy import MatrixSymbol, ZeroMatrix
>>> A = MatrixSymbol('A', 3, 5)
>>> Z = ZeroMatrix(3, 5)
>>> A + Z
A
>>> Z*A.T
0
"""
is_ZeroMatrix = True
def __new__(cls, m, n):
m, n = _sympify(m), _sympify(n)
cls._check_dim(m)
cls._check_dim(n)
return super().__new__(cls, m, n)
@property
def shape(self):
return (self.args[0], self.args[1])
def _eval_power(self, exp):
# exp = -1, 0, 1 are already handled at this stage
if (exp < 0) == True:
raise NonInvertibleMatrixError("Matrix det == 0; not invertible")
return self
def _eval_transpose(self):
return ZeroMatrix(self.cols, self.rows)
def _eval_adjoint(self):
return ZeroMatrix(self.cols, self.rows)
def _eval_trace(self):
return S.Zero
def _eval_determinant(self):
return S.Zero
def _eval_inverse(self):
raise NonInvertibleMatrixError("Matrix det == 0; not invertible.")
def _eval_as_real_imag(self):
return (self, self)
def _eval_conjugate(self):
return self
def _entry(self, i, j, **kwargs):
return S.Zero
class GenericZeroMatrix(ZeroMatrix):
"""
A zero matrix without a specified shape
This exists primarily so MatAdd() with no arguments can return something
meaningful.
"""
def __new__(cls):
# super(ZeroMatrix, cls) instead of super(GenericZeroMatrix, cls)
# because ZeroMatrix.__new__ doesn't have the same signature
return super(ZeroMatrix, cls).__new__(cls)
@property
def rows(self):
raise TypeError("GenericZeroMatrix does not have a specified shape")
@property
def cols(self):
raise TypeError("GenericZeroMatrix does not have a specified shape")
@property
def shape(self):
raise TypeError("GenericZeroMatrix does not have a specified shape")
# Avoid Matrix.__eq__ which might call .shape
def __eq__(self, other):
return isinstance(other, GenericZeroMatrix)
def __ne__(self, other):
return not (self == other)
def __hash__(self):
return super().__hash__()
class Identity(MatrixExpr):
"""The Matrix Identity I - multiplicative identity
Examples
========
>>> from sympy import Identity, MatrixSymbol
>>> A = MatrixSymbol('A', 3, 5)
>>> I = Identity(3)
>>> I*A
A
"""
is_Identity = True
def __new__(cls, n):
n = _sympify(n)
cls._check_dim(n)
return super().__new__(cls, n)
@property
def rows(self):
return self.args[0]
@property
def cols(self):
return self.args[0]
@property
def shape(self):
return (self.args[0], self.args[0])
@property
def is_square(self):
return True
def _eval_transpose(self):
return self
def _eval_trace(self):
return self.rows
def _eval_inverse(self):
return self
def _eval_as_real_imag(self):
return (self, ZeroMatrix(*self.shape))
def _eval_conjugate(self):
return self
def _eval_adjoint(self):
return self
def _entry(self, i, j, **kwargs):
eq = Eq(i, j)
if eq is S.true:
return S.One
elif eq is S.false:
return S.Zero
return KroneckerDelta(i, j, (0, self.cols-1))
def _eval_determinant(self):
return S.One
def _eval_power(self, exp):
return self
class GenericIdentity(Identity):
"""
An identity matrix without a specified shape
This exists primarily so MatMul() with no arguments can return something
meaningful.
"""
def __new__(cls):
# super(Identity, cls) instead of super(GenericIdentity, cls) because
# Identity.__new__ doesn't have the same signature
return super(Identity, cls).__new__(cls)
@property
def rows(self):
raise TypeError("GenericIdentity does not have a specified shape")
@property
def cols(self):
raise TypeError("GenericIdentity does not have a specified shape")
@property
def shape(self):
raise TypeError("GenericIdentity does not have a specified shape")
# Avoid Matrix.__eq__ which might call .shape
def __eq__(self, other):
return isinstance(other, GenericIdentity)
def __ne__(self, other):
return not (self == other)
def __hash__(self):
return super().__hash__()
class OneMatrix(MatrixExpr):
"""
Matrix whose all entries are ones.
"""
def __new__(cls, m, n, evaluate=False):
m, n = _sympify(m), _sympify(n)
cls._check_dim(m)
cls._check_dim(n)
if evaluate:
condition = Eq(m, 1) & Eq(n, 1)
if condition == True:
return Identity(1)
obj = super().__new__(cls, m, n)
return obj
@property
def shape(self):
return self._args
@property
def is_Identity(self):
return self._is_1x1() == True
def as_explicit(self):
from sympy.matrices.immutable import ImmutableDenseMatrix
return ImmutableDenseMatrix.ones(*self.shape)
def doit(self, **hints):
args = self.args
if hints.get('deep', True):
args = [a.doit(**hints) for a in args]
return self.func(*args, evaluate=True)
def _eval_power(self, exp):
# exp = -1, 0, 1 are already handled at this stage
if self._is_1x1() == True:
return Identity(1)
if (exp < 0) == True:
raise NonInvertibleMatrixError("Matrix det == 0; not invertible")
if ask(Q.integer(exp)):
return self.shape[0] ** (exp - 1) * OneMatrix(*self.shape)
return super()._eval_power(exp)
def _eval_transpose(self):
return OneMatrix(self.cols, self.rows)
def _eval_adjoint(self):
return OneMatrix(self.cols, self.rows)
def _eval_trace(self):
return S.One*self.rows
def _is_1x1(self):
"""Returns true if the matrix is known to be 1x1"""
shape = self.shape
return Eq(shape[0], 1) & Eq(shape[1], 1)
def _eval_determinant(self):
condition = self._is_1x1()
if condition == True:
return S.One
elif condition == False:
return S.Zero
else:
from sympy.matrices.expressions.determinant import Determinant
return Determinant(self)
def _eval_inverse(self):
condition = self._is_1x1()
if condition == True:
return Identity(1)
elif condition == False:
raise NonInvertibleMatrixError("Matrix det == 0; not invertible.")
else:
from .inverse import Inverse
return Inverse(self)
def _eval_as_real_imag(self):
return (self, ZeroMatrix(*self.shape))
def _eval_conjugate(self):
return self
def _entry(self, i, j, **kwargs):
return S.One
|
2839e772d39c49c4288f6afd08cc05ebc27217812d0136f41ea7f0550392960a | from typing import Tuple as tTuple
from functools import wraps
from sympy.core import S, Integer, Basic, Mul, Add
from sympy.core.assumptions import check_assumptions
from sympy.core.decorators import call_highest_priority
from sympy.core.expr import Expr, ExprBuilder
from sympy.core.logic import FuzzyBool
from sympy.core.symbol import Str, Dummy, symbols, Symbol
from sympy.core.sympify import SympifyError, _sympify
from sympy.external.gmpy import SYMPY_INTS
from sympy.functions import conjugate, adjoint
from sympy.functions.special.tensor_functions import KroneckerDelta
from sympy.matrices.common import NonSquareMatrixError
from sympy.matrices.matrices import MatrixKind, MatrixBase
from sympy.multipledispatch import dispatch
from sympy.utilities.misc import filldedent
def _sympifyit(arg, retval=None):
# This version of _sympifyit sympifies MutableMatrix objects
def deco(func):
@wraps(func)
def __sympifyit_wrapper(a, b):
try:
b = _sympify(b)
return func(a, b)
except SympifyError:
return retval
return __sympifyit_wrapper
return deco
class MatrixExpr(Expr):
"""Superclass for Matrix Expressions
MatrixExprs represent abstract matrices, linear transformations represented
within a particular basis.
Examples
========
>>> from sympy import MatrixSymbol
>>> A = MatrixSymbol('A', 3, 3)
>>> y = MatrixSymbol('y', 3, 1)
>>> x = (A.T*A).I * A * y
See Also
========
MatrixSymbol, MatAdd, MatMul, Transpose, Inverse
"""
__slots__ = () # type: tTuple[str, ...]
# Should not be considered iterable by the
# sympy.utilities.iterables.iterable function. Subclass that actually are
# iterable (i.e., explicit matrices) should set this to True.
_iterable = False
_op_priority = 11.0
is_Matrix = True # type: bool
is_MatrixExpr = True # type: bool
is_Identity = None # type: FuzzyBool
is_Inverse = False
is_Transpose = False
is_ZeroMatrix = False
is_MatAdd = False
is_MatMul = False
is_commutative = False
is_number = False
is_symbol = False
is_scalar = False
kind: MatrixKind = MatrixKind()
def __new__(cls, *args, **kwargs):
args = map(_sympify, args)
return Basic.__new__(cls, *args, **kwargs)
# The following is adapted from the core Expr object
@property
def shape(self) -> tTuple[Expr, Expr]:
raise NotImplementedError
@property
def _add_handler(self):
return MatAdd
@property
def _mul_handler(self):
return MatMul
def __neg__(self):
return MatMul(S.NegativeOne, self).doit()
def __abs__(self):
raise NotImplementedError
@_sympifyit('other', NotImplemented)
@call_highest_priority('__radd__')
def __add__(self, other):
return MatAdd(self, other).doit()
@_sympifyit('other', NotImplemented)
@call_highest_priority('__add__')
def __radd__(self, other):
return MatAdd(other, self).doit()
@_sympifyit('other', NotImplemented)
@call_highest_priority('__rsub__')
def __sub__(self, other):
return MatAdd(self, -other).doit()
@_sympifyit('other', NotImplemented)
@call_highest_priority('__sub__')
def __rsub__(self, other):
return MatAdd(other, -self).doit()
@_sympifyit('other', NotImplemented)
@call_highest_priority('__rmul__')
def __mul__(self, other):
return MatMul(self, other).doit()
@_sympifyit('other', NotImplemented)
@call_highest_priority('__rmul__')
def __matmul__(self, other):
return MatMul(self, other).doit()
@_sympifyit('other', NotImplemented)
@call_highest_priority('__mul__')
def __rmul__(self, other):
return MatMul(other, self).doit()
@_sympifyit('other', NotImplemented)
@call_highest_priority('__mul__')
def __rmatmul__(self, other):
return MatMul(other, self).doit()
@_sympifyit('other', NotImplemented)
@call_highest_priority('__rpow__')
def __pow__(self, other):
return MatPow(self, other).doit()
@_sympifyit('other', NotImplemented)
@call_highest_priority('__pow__')
def __rpow__(self, other):
raise NotImplementedError("Matrix Power not defined")
@_sympifyit('other', NotImplemented)
@call_highest_priority('__rtruediv__')
def __truediv__(self, other):
return self * other**S.NegativeOne
@_sympifyit('other', NotImplemented)
@call_highest_priority('__truediv__')
def __rtruediv__(self, other):
raise NotImplementedError()
#return MatMul(other, Pow(self, S.NegativeOne))
@property
def rows(self):
return self.shape[0]
@property
def cols(self):
return self.shape[1]
@property
def is_square(self):
return self.rows == self.cols
def _eval_conjugate(self):
from sympy.matrices.expressions.adjoint import Adjoint
return Adjoint(Transpose(self))
def as_real_imag(self, deep=True, **hints):
return self._eval_as_real_imag()
def _eval_as_real_imag(self):
real = S.Half * (self + self._eval_conjugate())
im = (self - self._eval_conjugate())/(2*S.ImaginaryUnit)
return (real, im)
def _eval_inverse(self):
return Inverse(self)
def _eval_determinant(self):
return Determinant(self)
def _eval_transpose(self):
return Transpose(self)
def _eval_power(self, exp):
"""
Override this in sub-classes to implement simplification of powers. The cases where the exponent
is -1, 0, 1 are already covered in MatPow.doit(), so implementations can exclude these cases.
"""
return MatPow(self, exp)
def _eval_simplify(self, **kwargs):
if self.is_Atom:
return self
else:
from sympy.simplify import simplify
return self.func(*[simplify(x, **kwargs) for x in self.args])
def _eval_adjoint(self):
from sympy.matrices.expressions.adjoint import Adjoint
return Adjoint(self)
def _eval_derivative_n_times(self, x, n):
return Basic._eval_derivative_n_times(self, x, n)
def _eval_derivative(self, x):
# `x` is a scalar:
if self.has(x):
# See if there are other methods using it:
return super()._eval_derivative(x)
else:
return ZeroMatrix(*self.shape)
@classmethod
def _check_dim(cls, dim):
"""Helper function to check invalid matrix dimensions"""
ok = check_assumptions(dim, integer=True, nonnegative=True)
if ok is False:
raise ValueError(
"The dimension specification {} should be "
"a nonnegative integer.".format(dim))
def _entry(self, i, j, **kwargs):
raise NotImplementedError(
"Indexing not implemented for %s" % self.__class__.__name__)
def adjoint(self):
return adjoint(self)
def as_coeff_Mul(self, rational=False):
"""Efficiently extract the coefficient of a product. """
return S.One, self
def conjugate(self):
return conjugate(self)
def transpose(self):
from sympy.matrices.expressions.transpose import transpose
return transpose(self)
@property
def T(self):
'''Matrix transposition'''
return self.transpose()
def inverse(self):
if not self.is_square:
raise NonSquareMatrixError('Inverse of non-square matrix')
return self._eval_inverse()
def inv(self):
return self.inverse()
def det(self):
from sympy.matrices.expressions.determinant import det
return det(self)
@property
def I(self):
return self.inverse()
def valid_index(self, i, j):
def is_valid(idx):
return isinstance(idx, (int, Integer, Symbol, Expr))
return (is_valid(i) and is_valid(j) and
(self.rows is None or
(i >= -self.rows) != False and (i < self.rows) != False) and
(j >= -self.cols) != False and (j < self.cols) != False)
def __getitem__(self, key):
if not isinstance(key, tuple) and isinstance(key, slice):
from sympy.matrices.expressions.slice import MatrixSlice
return MatrixSlice(self, key, (0, None, 1))
if isinstance(key, tuple) and len(key) == 2:
i, j = key
if isinstance(i, slice) or isinstance(j, slice):
from sympy.matrices.expressions.slice import MatrixSlice
return MatrixSlice(self, i, j)
i, j = _sympify(i), _sympify(j)
if self.valid_index(i, j) != False:
return self._entry(i, j)
else:
raise IndexError("Invalid indices (%s, %s)" % (i, j))
elif isinstance(key, (SYMPY_INTS, Integer)):
# row-wise decomposition of matrix
rows, cols = self.shape
# allow single indexing if number of columns is known
if not isinstance(cols, Integer):
raise IndexError(filldedent('''
Single indexing is only supported when the number
of columns is known.'''))
key = _sympify(key)
i = key // cols
j = key % cols
if self.valid_index(i, j) != False:
return self._entry(i, j)
else:
raise IndexError("Invalid index %s" % key)
elif isinstance(key, (Symbol, Expr)):
raise IndexError(filldedent('''
Only integers may be used when addressing the matrix
with a single index.'''))
raise IndexError("Invalid index, wanted %s[i,j]" % self)
def _is_shape_symbolic(self) -> bool:
return (not isinstance(self.rows, (SYMPY_INTS, Integer))
or not isinstance(self.cols, (SYMPY_INTS, Integer)))
def as_explicit(self):
"""
Returns a dense Matrix with elements represented explicitly
Returns an object of type ImmutableDenseMatrix.
Examples
========
>>> from sympy import Identity
>>> I = Identity(3)
>>> I
I
>>> I.as_explicit()
Matrix([
[1, 0, 0],
[0, 1, 0],
[0, 0, 1]])
See Also
========
as_mutable: returns mutable Matrix type
"""
if self._is_shape_symbolic():
raise ValueError(
'Matrix with symbolic shape '
'cannot be represented explicitly.')
from sympy.matrices.immutable import ImmutableDenseMatrix
return ImmutableDenseMatrix([[self[i, j]
for j in range(self.cols)]
for i in range(self.rows)])
def as_mutable(self):
"""
Returns a dense, mutable matrix with elements represented explicitly
Examples
========
>>> from sympy import Identity
>>> I = Identity(3)
>>> I
I
>>> I.shape
(3, 3)
>>> I.as_mutable()
Matrix([
[1, 0, 0],
[0, 1, 0],
[0, 0, 1]])
See Also
========
as_explicit: returns ImmutableDenseMatrix
"""
return self.as_explicit().as_mutable()
def __array__(self):
from numpy import empty
a = empty(self.shape, dtype=object)
for i in range(self.rows):
for j in range(self.cols):
a[i, j] = self[i, j]
return a
def equals(self, other):
"""
Test elementwise equality between matrices, potentially of different
types
>>> from sympy import Identity, eye
>>> Identity(3).equals(eye(3))
True
"""
return self.as_explicit().equals(other)
def canonicalize(self):
return self
def as_coeff_mmul(self):
return S.One, MatMul(self)
@staticmethod
def from_index_summation(expr, first_index=None, last_index=None, dimensions=None):
r"""
Parse expression of matrices with explicitly summed indices into a
matrix expression without indices, if possible.
This transformation expressed in mathematical notation:
`\sum_{j=0}^{N-1} A_{i,j} B_{j,k} \Longrightarrow \mathbf{A}\cdot \mathbf{B}`
Optional parameter ``first_index``: specify which free index to use as
the index starting the expression.
Examples
========
>>> from sympy import MatrixSymbol, MatrixExpr, Sum
>>> from sympy.abc import i, j, k, l, N
>>> A = MatrixSymbol("A", N, N)
>>> B = MatrixSymbol("B", N, N)
>>> expr = Sum(A[i, j]*B[j, k], (j, 0, N-1))
>>> MatrixExpr.from_index_summation(expr)
A*B
Transposition is detected:
>>> expr = Sum(A[j, i]*B[j, k], (j, 0, N-1))
>>> MatrixExpr.from_index_summation(expr)
A.T*B
Detect the trace:
>>> expr = Sum(A[i, i], (i, 0, N-1))
>>> MatrixExpr.from_index_summation(expr)
Trace(A)
More complicated expressions:
>>> expr = Sum(A[i, j]*B[k, j]*A[l, k], (j, 0, N-1), (k, 0, N-1))
>>> MatrixExpr.from_index_summation(expr)
A*B.T*A.T
"""
from sympy.tensor.array.expressions.conv_indexed_to_array import convert_indexed_to_array
from sympy.tensor.array.expressions.conv_array_to_matrix import convert_array_to_matrix
first_indices = []
if first_index is not None:
first_indices.append(first_index)
if last_index is not None:
first_indices.append(last_index)
arr = convert_indexed_to_array(expr, first_indices=first_indices)
return convert_array_to_matrix(arr)
def applyfunc(self, func):
from .applyfunc import ElementwiseApplyFunction
return ElementwiseApplyFunction(func, self)
@dispatch(MatrixExpr, Expr)
def _eval_is_eq(lhs, rhs): # noqa:F811
return False
@dispatch(MatrixExpr, MatrixExpr) # type: ignore
def _eval_is_eq(lhs, rhs): # noqa:F811
if lhs.shape != rhs.shape:
return False
if (lhs - rhs).is_ZeroMatrix:
return True
def get_postprocessor(cls):
def _postprocessor(expr):
# To avoid circular imports, we can't have MatMul/MatAdd on the top level
mat_class = {Mul: MatMul, Add: MatAdd}[cls]
nonmatrices = []
matrices = []
for term in expr.args:
if isinstance(term, MatrixExpr):
matrices.append(term)
else:
nonmatrices.append(term)
if not matrices:
return cls._from_args(nonmatrices)
if nonmatrices:
if cls == Mul:
for i in range(len(matrices)):
if not matrices[i].is_MatrixExpr:
# If one of the matrices explicit, absorb the scalar into it
# (doit will combine all explicit matrices into one, so it
# doesn't matter which)
matrices[i] = matrices[i].__mul__(cls._from_args(nonmatrices))
nonmatrices = []
break
else:
# Maintain the ability to create Add(scalar, matrix) without
# raising an exception. That way different algorithms can
# replace matrix expressions with non-commutative symbols to
# manipulate them like non-commutative scalars.
return cls._from_args(nonmatrices + [mat_class(*matrices).doit(deep=False)])
if mat_class == MatAdd:
return mat_class(*matrices).doit(deep=False)
return mat_class(cls._from_args(nonmatrices), *matrices).doit(deep=False)
return _postprocessor
Basic._constructor_postprocessor_mapping[MatrixExpr] = {
"Mul": [get_postprocessor(Mul)],
"Add": [get_postprocessor(Add)],
}
def _matrix_derivative(expr, x, old_algorithm=False):
if isinstance(expr, MatrixBase) or isinstance(x, MatrixBase):
# Do not use array expressions for explicit matrices:
old_algorithm = True
if old_algorithm:
return _matrix_derivative_old_algorithm(expr, x)
from sympy.tensor.array.expressions.conv_matrix_to_array import convert_matrix_to_array
from sympy.tensor.array.expressions.arrayexpr_derivatives import array_derive
from sympy.tensor.array.expressions.conv_array_to_matrix import convert_array_to_matrix
array_expr = convert_matrix_to_array(expr)
diff_array_expr = array_derive(array_expr, x)
diff_matrix_expr = convert_array_to_matrix(diff_array_expr)
return diff_matrix_expr
def _matrix_derivative_old_algorithm(expr, x):
from sympy.tensor.array.array_derivatives import ArrayDerivative
lines = expr._eval_derivative_matrix_lines(x)
parts = [i.build() for i in lines]
from sympy.tensor.array.expressions.conv_array_to_matrix import convert_array_to_matrix
parts = [[convert_array_to_matrix(j) for j in i] for i in parts]
def _get_shape(elem):
if isinstance(elem, MatrixExpr):
return elem.shape
return 1, 1
def get_rank(parts):
return sum([j not in (1, None) for i in parts for j in _get_shape(i)])
ranks = [get_rank(i) for i in parts]
rank = ranks[0]
def contract_one_dims(parts):
if len(parts) == 1:
return parts[0]
else:
p1, p2 = parts[:2]
if p2.is_Matrix:
p2 = p2.T
if p1 == Identity(1):
pbase = p2
elif p2 == Identity(1):
pbase = p1
else:
pbase = p1*p2
if len(parts) == 2:
return pbase
else: # len(parts) > 2
if pbase.is_Matrix:
raise ValueError("")
return pbase*Mul.fromiter(parts[2:])
if rank <= 2:
return Add.fromiter([contract_one_dims(i) for i in parts])
return ArrayDerivative(expr, x)
class MatrixElement(Expr):
parent = property(lambda self: self.args[0])
i = property(lambda self: self.args[1])
j = property(lambda self: self.args[2])
_diff_wrt = True
is_symbol = True
is_commutative = True
def __new__(cls, name, n, m):
n, m = map(_sympify, (n, m))
from sympy.matrices.matrices import MatrixBase
if isinstance(name, str):
name = Symbol(name)
else:
if isinstance(name, MatrixBase):
if n.is_Integer and m.is_Integer:
return name[n, m]
name = _sympify(name) # change mutable into immutable
else:
name = _sympify(name)
if not isinstance(name.kind, MatrixKind):
raise TypeError("First argument of MatrixElement should be a matrix")
if not getattr(name, 'valid_index', lambda n, m: True)(n, m):
raise IndexError('indices out of range')
obj = Expr.__new__(cls, name, n, m)
return obj
@property
def symbol(self):
return self.args[0]
def doit(self, **hints):
deep = hints.get('deep', True)
if deep:
args = [arg.doit(**hints) for arg in self.args]
else:
args = self.args
return args[0][args[1], args[2]]
@property
def indices(self):
return self.args[1:]
def _eval_derivative(self, v):
if not isinstance(v, MatrixElement):
from sympy.matrices.matrices import MatrixBase
if isinstance(self.parent, MatrixBase):
return self.parent.diff(v)[self.i, self.j]
return S.Zero
M = self.args[0]
m, n = self.parent.shape
if M == v.args[0]:
return KroneckerDelta(self.args[1], v.args[1], (0, m-1)) * \
KroneckerDelta(self.args[2], v.args[2], (0, n-1))
if isinstance(M, Inverse):
from sympy.concrete.summations import Sum
i, j = self.args[1:]
i1, i2 = symbols("z1, z2", cls=Dummy)
Y = M.args[0]
r1, r2 = Y.shape
return -Sum(M[i, i1]*Y[i1, i2].diff(v)*M[i2, j], (i1, 0, r1-1), (i2, 0, r2-1))
if self.has(v.args[0]):
return None
return S.Zero
class MatrixSymbol(MatrixExpr):
"""Symbolic representation of a Matrix object
Creates a SymPy Symbol to represent a Matrix. This matrix has a shape and
can be included in Matrix Expressions
Examples
========
>>> from sympy import MatrixSymbol, Identity
>>> A = MatrixSymbol('A', 3, 4) # A 3 by 4 Matrix
>>> B = MatrixSymbol('B', 4, 3) # A 4 by 3 Matrix
>>> A.shape
(3, 4)
>>> 2*A*B + Identity(3)
I + 2*A*B
"""
is_commutative = False
is_symbol = True
_diff_wrt = True
def __new__(cls, name, n, m):
n, m = _sympify(n), _sympify(m)
cls._check_dim(m)
cls._check_dim(n)
if isinstance(name, str):
name = Str(name)
obj = Basic.__new__(cls, name, n, m)
return obj
@property
def shape(self):
return self.args[1], self.args[2]
@property
def name(self):
return self.args[0].name
def _entry(self, i, j, **kwargs):
return MatrixElement(self, i, j)
@property
def free_symbols(self):
return {self}
def _eval_simplify(self, **kwargs):
return self
def _eval_derivative(self, x):
# x is a scalar:
return ZeroMatrix(self.shape[0], self.shape[1])
def _eval_derivative_matrix_lines(self, x):
if self != x:
first = ZeroMatrix(x.shape[0], self.shape[0]) if self.shape[0] != 1 else S.Zero
second = ZeroMatrix(x.shape[1], self.shape[1]) if self.shape[1] != 1 else S.Zero
return [_LeftRightArgs(
[first, second],
)]
else:
first = Identity(self.shape[0]) if self.shape[0] != 1 else S.One
second = Identity(self.shape[1]) if self.shape[1] != 1 else S.One
return [_LeftRightArgs(
[first, second],
)]
def matrix_symbols(expr):
return [sym for sym in expr.free_symbols if sym.is_Matrix]
class _LeftRightArgs:
r"""
Helper class to compute matrix derivatives.
The logic: when an expression is derived by a matrix `X_{mn}`, two lines of
matrix multiplications are created: the one contracted to `m` (first line),
and the one contracted to `n` (second line).
Transposition flips the side by which new matrices are connected to the
lines.
The trace connects the end of the two lines.
"""
def __init__(self, lines, higher=S.One):
self._lines = [i for i in lines]
self._first_pointer_parent = self._lines
self._first_pointer_index = 0
self._first_line_index = 0
self._second_pointer_parent = self._lines
self._second_pointer_index = 1
self._second_line_index = 1
self.higher = higher
@property
def first_pointer(self):
return self._first_pointer_parent[self._first_pointer_index]
@first_pointer.setter
def first_pointer(self, value):
self._first_pointer_parent[self._first_pointer_index] = value
@property
def second_pointer(self):
return self._second_pointer_parent[self._second_pointer_index]
@second_pointer.setter
def second_pointer(self, value):
self._second_pointer_parent[self._second_pointer_index] = value
def __repr__(self):
built = [self._build(i) for i in self._lines]
return "_LeftRightArgs(lines=%s, higher=%s)" % (
built,
self.higher,
)
def transpose(self):
self._first_pointer_parent, self._second_pointer_parent = self._second_pointer_parent, self._first_pointer_parent
self._first_pointer_index, self._second_pointer_index = self._second_pointer_index, self._first_pointer_index
self._first_line_index, self._second_line_index = self._second_line_index, self._first_line_index
return self
@staticmethod
def _build(expr):
if isinstance(expr, ExprBuilder):
return expr.build()
if isinstance(expr, list):
if len(expr) == 1:
return expr[0]
else:
return expr[0](*[_LeftRightArgs._build(i) for i in expr[1]])
else:
return expr
def build(self):
data = [self._build(i) for i in self._lines]
if self.higher != 1:
data += [self._build(self.higher)]
data = [i for i in data]
return data
def matrix_form(self):
if self.first != 1 and self.higher != 1:
raise ValueError("higher dimensional array cannot be represented")
def _get_shape(elem):
if isinstance(elem, MatrixExpr):
return elem.shape
return (None, None)
if _get_shape(self.first)[1] != _get_shape(self.second)[1]:
# Remove one-dimensional identity matrices:
# (this is needed by `a.diff(a)` where `a` is a vector)
if _get_shape(self.second) == (1, 1):
return self.first*self.second[0, 0]
if _get_shape(self.first) == (1, 1):
return self.first[1, 1]*self.second.T
raise ValueError("incompatible shapes")
if self.first != 1:
return self.first*self.second.T
else:
return self.higher
def rank(self):
"""
Number of dimensions different from trivial (warning: not related to
matrix rank).
"""
rank = 0
if self.first != 1:
rank += sum([i != 1 for i in self.first.shape])
if self.second != 1:
rank += sum([i != 1 for i in self.second.shape])
if self.higher != 1:
rank += 2
return rank
def _multiply_pointer(self, pointer, other):
from ...tensor.array.expressions.array_expressions import ArrayTensorProduct
from ...tensor.array.expressions.array_expressions import ArrayContraction
subexpr = ExprBuilder(
ArrayContraction,
[
ExprBuilder(
ArrayTensorProduct,
[
pointer,
other
]
),
(1, 2)
],
validator=ArrayContraction._validate
)
return subexpr
def append_first(self, other):
self.first_pointer *= other
def append_second(self, other):
self.second_pointer *= other
def _make_matrix(x):
from sympy.matrices.immutable import ImmutableDenseMatrix
if isinstance(x, MatrixExpr):
return x
return ImmutableDenseMatrix([[x]])
from .matmul import MatMul
from .matadd import MatAdd
from .matpow import MatPow
from .transpose import Transpose
from .inverse import Inverse
from .special import ZeroMatrix, Identity
from .determinant import Determinant
|
b0a75487054a4c1dcb12f77cc4cc020dec4da10d43cf8dc3098b269b7530156c | from sympy.core import Basic, Expr
from sympy.core.sympify import _sympify
from sympy.matrices.expressions.transpose import transpose
class DotProduct(Expr):
"""
Dot product of vector matrices
The input should be two 1 x n or n x 1 matrices. The output represents the
scalar dotproduct.
This is similar to using MatrixElement and MatMul, except DotProduct does
not require that one vector to be a row vector and the other vector to be
a column vector.
>>> from sympy import MatrixSymbol, DotProduct
>>> A = MatrixSymbol('A', 1, 3)
>>> B = MatrixSymbol('B', 1, 3)
>>> DotProduct(A, B)
DotProduct(A, B)
>>> DotProduct(A, B).doit()
A[0, 0]*B[0, 0] + A[0, 1]*B[0, 1] + A[0, 2]*B[0, 2]
"""
def __new__(cls, arg1, arg2):
arg1, arg2 = _sympify((arg1, arg2))
if not arg1.is_Matrix:
raise TypeError("Argument 1 of DotProduct is not a matrix")
if not arg2.is_Matrix:
raise TypeError("Argument 2 of DotProduct is not a matrix")
if not (1 in arg1.shape):
raise TypeError("Argument 1 of DotProduct is not a vector")
if not (1 in arg2.shape):
raise TypeError("Argument 2 of DotProduct is not a vector")
if set(arg1.shape) != set(arg2.shape):
raise TypeError("DotProduct arguments are not the same length")
return Basic.__new__(cls, arg1, arg2)
def doit(self, expand=False, **hints):
if self.args[0].shape == self.args[1].shape:
if self.args[0].shape[0] == 1:
mul = self.args[0]*transpose(self.args[1])
else:
mul = transpose(self.args[0])*self.args[1]
else:
if self.args[0].shape[0] == 1:
mul = self.args[0]*self.args[1]
else:
mul = transpose(self.args[0])*transpose(self.args[1])
return mul[0]
|
49f458ea8e930c95cd4ce7d169c8018a493d626dea842a4cc89f08dd1546b822 | """Implementation of the Kronecker product"""
from functools import reduce
from math import prod
from sympy.core import Mul, sympify
from sympy.functions import adjoint
from sympy.matrices.common import ShapeError
from sympy.matrices.expressions.matexpr import MatrixExpr
from sympy.matrices.expressions.transpose import transpose
from sympy.matrices.expressions.special import Identity
from sympy.matrices.matrices import MatrixBase
from sympy.strategies import (
canon, condition, distribute, do_one, exhaust, flatten, typed, unpack)
from sympy.strategies.traverse import bottom_up
from sympy.utilities import sift
from .matadd import MatAdd
from .matmul import MatMul
from .matpow import MatPow
def kronecker_product(*matrices):
"""
The Kronecker product of two or more arguments.
This computes the explicit Kronecker product for subclasses of
``MatrixBase`` i.e. explicit matrices. Otherwise, a symbolic
``KroneckerProduct`` object is returned.
Examples
========
For ``MatrixSymbol`` arguments a ``KroneckerProduct`` object is returned.
Elements of this matrix can be obtained by indexing, or for MatrixSymbols
with known dimension the explicit matrix can be obtained with
``.as_explicit()``
>>> from sympy import kronecker_product, MatrixSymbol
>>> A = MatrixSymbol('A', 2, 2)
>>> B = MatrixSymbol('B', 2, 2)
>>> kronecker_product(A)
A
>>> kronecker_product(A, B)
KroneckerProduct(A, B)
>>> kronecker_product(A, B)[0, 1]
A[0, 0]*B[0, 1]
>>> kronecker_product(A, B).as_explicit()
Matrix([
[A[0, 0]*B[0, 0], A[0, 0]*B[0, 1], A[0, 1]*B[0, 0], A[0, 1]*B[0, 1]],
[A[0, 0]*B[1, 0], A[0, 0]*B[1, 1], A[0, 1]*B[1, 0], A[0, 1]*B[1, 1]],
[A[1, 0]*B[0, 0], A[1, 0]*B[0, 1], A[1, 1]*B[0, 0], A[1, 1]*B[0, 1]],
[A[1, 0]*B[1, 0], A[1, 0]*B[1, 1], A[1, 1]*B[1, 0], A[1, 1]*B[1, 1]]])
For explicit matrices the Kronecker product is returned as a Matrix
>>> from sympy import Matrix, kronecker_product
>>> sigma_x = Matrix([
... [0, 1],
... [1, 0]])
...
>>> Isigma_y = Matrix([
... [0, 1],
... [-1, 0]])
...
>>> kronecker_product(sigma_x, Isigma_y)
Matrix([
[ 0, 0, 0, 1],
[ 0, 0, -1, 0],
[ 0, 1, 0, 0],
[-1, 0, 0, 0]])
See Also
========
KroneckerProduct
"""
if not matrices:
raise TypeError("Empty Kronecker product is undefined")
validate(*matrices)
if len(matrices) == 1:
return matrices[0]
else:
return KroneckerProduct(*matrices).doit()
class KroneckerProduct(MatrixExpr):
"""
The Kronecker product of two or more arguments.
The Kronecker product is a non-commutative product of matrices.
Given two matrices of dimension (m, n) and (s, t) it produces a matrix
of dimension (m s, n t).
This is a symbolic object that simply stores its argument without
evaluating it. To actually compute the product, use the function
``kronecker_product()`` or call the ``.doit()`` or ``.as_explicit()``
methods.
>>> from sympy import KroneckerProduct, MatrixSymbol
>>> A = MatrixSymbol('A', 5, 5)
>>> B = MatrixSymbol('B', 5, 5)
>>> isinstance(KroneckerProduct(A, B), KroneckerProduct)
True
"""
is_KroneckerProduct = True
def __new__(cls, *args, check=True):
args = list(map(sympify, args))
if all(a.is_Identity for a in args):
ret = Identity(prod(a.rows for a in args))
if all(isinstance(a, MatrixBase) for a in args):
return ret.as_explicit()
else:
return ret
if check:
validate(*args)
return super().__new__(cls, *args)
@property
def shape(self):
rows, cols = self.args[0].shape
for mat in self.args[1:]:
rows *= mat.rows
cols *= mat.cols
return (rows, cols)
def _entry(self, i, j, **kwargs):
result = 1
for mat in reversed(self.args):
i, m = divmod(i, mat.rows)
j, n = divmod(j, mat.cols)
result *= mat[m, n]
return result
def _eval_adjoint(self):
return KroneckerProduct(*list(map(adjoint, self.args))).doit()
def _eval_conjugate(self):
return KroneckerProduct(*[a.conjugate() for a in self.args]).doit()
def _eval_transpose(self):
return KroneckerProduct(*list(map(transpose, self.args))).doit()
def _eval_trace(self):
from .trace import trace
return Mul(*[trace(a) for a in self.args])
def _eval_determinant(self):
from .determinant import det, Determinant
if not all(a.is_square for a in self.args):
return Determinant(self)
m = self.rows
return Mul(*[det(a)**(m/a.rows) for a in self.args])
def _eval_inverse(self):
try:
return KroneckerProduct(*[a.inverse() for a in self.args])
except ShapeError:
from sympy.matrices.expressions.inverse import Inverse
return Inverse(self)
def structurally_equal(self, other):
'''Determine whether two matrices have the same Kronecker product structure
Examples
========
>>> from sympy import KroneckerProduct, MatrixSymbol, symbols
>>> m, n = symbols(r'm, n', integer=True)
>>> A = MatrixSymbol('A', m, m)
>>> B = MatrixSymbol('B', n, n)
>>> C = MatrixSymbol('C', m, m)
>>> D = MatrixSymbol('D', n, n)
>>> KroneckerProduct(A, B).structurally_equal(KroneckerProduct(C, D))
True
>>> KroneckerProduct(A, B).structurally_equal(KroneckerProduct(D, C))
False
>>> KroneckerProduct(A, B).structurally_equal(C)
False
'''
# Inspired by BlockMatrix
return (isinstance(other, KroneckerProduct)
and self.shape == other.shape
and len(self.args) == len(other.args)
and all(a.shape == b.shape for (a, b) in zip(self.args, other.args)))
def has_matching_shape(self, other):
'''Determine whether two matrices have the appropriate structure to bring matrix
multiplication inside the KroneckerProdut
Examples
========
>>> from sympy import KroneckerProduct, MatrixSymbol, symbols
>>> m, n = symbols(r'm, n', integer=True)
>>> A = MatrixSymbol('A', m, n)
>>> B = MatrixSymbol('B', n, m)
>>> KroneckerProduct(A, B).has_matching_shape(KroneckerProduct(B, A))
True
>>> KroneckerProduct(A, B).has_matching_shape(KroneckerProduct(A, B))
False
>>> KroneckerProduct(A, B).has_matching_shape(A)
False
'''
return (isinstance(other, KroneckerProduct)
and self.cols == other.rows
and len(self.args) == len(other.args)
and all(a.cols == b.rows for (a, b) in zip(self.args, other.args)))
def _eval_expand_kroneckerproduct(self, **hints):
return flatten(canon(typed({KroneckerProduct: distribute(KroneckerProduct, MatAdd)}))(self))
def _kronecker_add(self, other):
if self.structurally_equal(other):
return self.__class__(*[a + b for (a, b) in zip(self.args, other.args)])
else:
return self + other
def _kronecker_mul(self, other):
if self.has_matching_shape(other):
return self.__class__(*[a*b for (a, b) in zip(self.args, other.args)])
else:
return self * other
def doit(self, **hints):
deep = hints.get('deep', True)
if deep:
args = [arg.doit(**hints) for arg in self.args]
else:
args = self.args
return canonicalize(KroneckerProduct(*args))
def validate(*args):
if not all(arg.is_Matrix for arg in args):
raise TypeError("Mix of Matrix and Scalar symbols")
# rules
def extract_commutative(kron):
c_part = []
nc_part = []
for arg in kron.args:
c, nc = arg.args_cnc()
c_part.extend(c)
nc_part.append(Mul._from_args(nc))
c_part = Mul(*c_part)
if c_part != 1:
return c_part*KroneckerProduct(*nc_part)
return kron
def matrix_kronecker_product(*matrices):
"""Compute the Kronecker product of a sequence of SymPy Matrices.
This is the standard Kronecker product of matrices [1].
Parameters
==========
matrices : tuple of MatrixBase instances
The matrices to take the Kronecker product of.
Returns
=======
matrix : MatrixBase
The Kronecker product matrix.
Examples
========
>>> from sympy import Matrix
>>> from sympy.matrices.expressions.kronecker import (
... matrix_kronecker_product)
>>> m1 = Matrix([[1,2],[3,4]])
>>> m2 = Matrix([[1,0],[0,1]])
>>> matrix_kronecker_product(m1, m2)
Matrix([
[1, 0, 2, 0],
[0, 1, 0, 2],
[3, 0, 4, 0],
[0, 3, 0, 4]])
>>> matrix_kronecker_product(m2, m1)
Matrix([
[1, 2, 0, 0],
[3, 4, 0, 0],
[0, 0, 1, 2],
[0, 0, 3, 4]])
References
==========
.. [1] https://en.wikipedia.org/wiki/Kronecker_product
"""
# Make sure we have a sequence of Matrices
if not all(isinstance(m, MatrixBase) for m in matrices):
raise TypeError(
'Sequence of Matrices expected, got: %s' % repr(matrices)
)
# Pull out the first element in the product.
matrix_expansion = matrices[-1]
# Do the kronecker product working from right to left.
for mat in reversed(matrices[:-1]):
rows = mat.rows
cols = mat.cols
# Go through each row appending kronecker product to.
# running matrix_expansion.
for i in range(rows):
start = matrix_expansion*mat[i*cols]
# Go through each column joining each item
for j in range(cols - 1):
start = start.row_join(
matrix_expansion*mat[i*cols + j + 1]
)
# If this is the first element, make it the start of the
# new row.
if i == 0:
next = start
else:
next = next.col_join(start)
matrix_expansion = next
MatrixClass = max(matrices, key=lambda M: M._class_priority).__class__
if isinstance(matrix_expansion, MatrixClass):
return matrix_expansion
else:
return MatrixClass(matrix_expansion)
def explicit_kronecker_product(kron):
# Make sure we have a sequence of Matrices
if not all(isinstance(m, MatrixBase) for m in kron.args):
return kron
return matrix_kronecker_product(*kron.args)
rules = (unpack,
explicit_kronecker_product,
flatten,
extract_commutative)
canonicalize = exhaust(condition(lambda x: isinstance(x, KroneckerProduct),
do_one(*rules)))
def _kronecker_dims_key(expr):
if isinstance(expr, KroneckerProduct):
return tuple(a.shape for a in expr.args)
else:
return (0,)
def kronecker_mat_add(expr):
args = sift(expr.args, _kronecker_dims_key)
nonkrons = args.pop((0,), None)
if not args:
return expr
krons = [reduce(lambda x, y: x._kronecker_add(y), group)
for group in args.values()]
if not nonkrons:
return MatAdd(*krons)
else:
return MatAdd(*krons) + nonkrons
def kronecker_mat_mul(expr):
# modified from block matrix code
factor, matrices = expr.as_coeff_matrices()
i = 0
while i < len(matrices) - 1:
A, B = matrices[i:i+2]
if isinstance(A, KroneckerProduct) and isinstance(B, KroneckerProduct):
matrices[i] = A._kronecker_mul(B)
matrices.pop(i+1)
else:
i += 1
return factor*MatMul(*matrices)
def kronecker_mat_pow(expr):
if isinstance(expr.base, KroneckerProduct) and all(a.is_square for a in expr.base.args):
return KroneckerProduct(*[MatPow(a, expr.exp) for a in expr.base.args])
else:
return expr
def combine_kronecker(expr):
"""Combine KronekeckerProduct with expression.
If possible write operations on KroneckerProducts of compatible shapes
as a single KroneckerProduct.
Examples
========
>>> from sympy.matrices.expressions import combine_kronecker
>>> from sympy import MatrixSymbol, KroneckerProduct, symbols
>>> m, n = symbols(r'm, n', integer=True)
>>> A = MatrixSymbol('A', m, n)
>>> B = MatrixSymbol('B', n, m)
>>> combine_kronecker(KroneckerProduct(A, B)*KroneckerProduct(B, A))
KroneckerProduct(A*B, B*A)
>>> combine_kronecker(KroneckerProduct(A, B)+KroneckerProduct(B.T, A.T))
KroneckerProduct(A + B.T, B + A.T)
>>> C = MatrixSymbol('C', n, n)
>>> D = MatrixSymbol('D', m, m)
>>> combine_kronecker(KroneckerProduct(C, D)**m)
KroneckerProduct(C**m, D**m)
"""
def haskron(expr):
return isinstance(expr, MatrixExpr) and expr.has(KroneckerProduct)
rule = exhaust(
bottom_up(exhaust(condition(haskron, typed(
{MatAdd: kronecker_mat_add,
MatMul: kronecker_mat_mul,
MatPow: kronecker_mat_pow})))))
result = rule(expr)
doit = getattr(result, 'doit', None)
if doit is not None:
return doit()
else:
return result
|
fb019484237dd1b7930f2f8ba67c60cbfa9dc2546c5a5136ff07c113539e1671 | from sympy.core.basic import Basic
from sympy.core.expr import Expr, ExprBuilder
from sympy.core.singleton import S
from sympy.core.sorting import default_sort_key
from sympy.core.symbol import uniquely_named_symbol
from sympy.core.sympify import sympify
from sympy.matrices.matrices import MatrixBase
from sympy.matrices.common import NonSquareMatrixError
class Trace(Expr):
"""Matrix Trace
Represents the trace of a matrix expression.
Examples
========
>>> from sympy import MatrixSymbol, Trace, eye
>>> A = MatrixSymbol('A', 3, 3)
>>> Trace(A)
Trace(A)
>>> Trace(eye(3))
Trace(Matrix([
[1, 0, 0],
[0, 1, 0],
[0, 0, 1]]))
>>> Trace(eye(3)).simplify()
3
"""
is_Trace = True
is_commutative = True
def __new__(cls, mat):
mat = sympify(mat)
if not mat.is_Matrix:
raise TypeError("input to Trace, %s, is not a matrix" % str(mat))
if not mat.is_square:
raise NonSquareMatrixError("Trace of a non-square matrix")
return Basic.__new__(cls, mat)
def _eval_transpose(self):
return self
def _eval_derivative(self, v):
from sympy.concrete.summations import Sum
from .matexpr import MatrixElement
if isinstance(v, MatrixElement):
return self.rewrite(Sum).diff(v)
expr = self.doit()
if isinstance(expr, Trace):
# Avoid looping infinitely:
raise NotImplementedError
return expr._eval_derivative(v)
def _eval_derivative_matrix_lines(self, x):
from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct, ArrayContraction
r = self.args[0]._eval_derivative_matrix_lines(x)
for lr in r:
if lr.higher == 1:
lr.higher = ExprBuilder(
ArrayContraction,
[
ExprBuilder(
ArrayTensorProduct,
[
lr._lines[0],
lr._lines[1],
]
),
(1, 3),
],
validator=ArrayContraction._validate
)
else:
# This is not a matrix line:
lr.higher = ExprBuilder(
ArrayContraction,
[
ExprBuilder(
ArrayTensorProduct,
[
lr._lines[0],
lr._lines[1],
lr.higher,
]
),
(1, 3), (0, 2)
]
)
lr._lines = [S.One, S.One]
lr._first_pointer_parent = lr._lines
lr._second_pointer_parent = lr._lines
lr._first_pointer_index = 0
lr._second_pointer_index = 1
return r
@property
def arg(self):
return self.args[0]
def doit(self, **hints):
if hints.get('deep', True):
arg = self.arg.doit(**hints)
try:
return arg._eval_trace()
except (AttributeError, NotImplementedError):
return Trace(arg)
else:
# _eval_trace would go too deep here
if isinstance(self.arg, MatrixBase):
return trace(self.arg)
else:
return Trace(self.arg)
def as_explicit(self):
return Trace(self.arg.as_explicit()).doit()
def _normalize(self):
# Normalization of trace of matrix products. Use transposition and
# cyclic properties of traces to make sure the arguments of the matrix
# product are sorted and the first argument is not a trasposition.
from sympy.matrices.expressions.matmul import MatMul
from sympy.matrices.expressions.transpose import Transpose
trace_arg = self.arg
if isinstance(trace_arg, MatMul):
def get_arg_key(x):
a = trace_arg.args[x]
if isinstance(a, Transpose):
a = a.arg
return default_sort_key(a)
indmin = min(range(len(trace_arg.args)), key=get_arg_key)
if isinstance(trace_arg.args[indmin], Transpose):
trace_arg = Transpose(trace_arg).doit()
indmin = min(range(len(trace_arg.args)), key=lambda x: default_sort_key(trace_arg.args[x]))
trace_arg = MatMul.fromiter(trace_arg.args[indmin:] + trace_arg.args[:indmin])
return Trace(trace_arg)
return self
def _eval_rewrite_as_Sum(self, expr, **kwargs):
from sympy.concrete.summations import Sum
i = uniquely_named_symbol('i', expr)
s = Sum(self.arg[i, i], (i, 0, self.arg.rows - 1))
return s.doit()
def trace(expr):
"""Trace of a Matrix. Sum of the diagonal elements.
Examples
========
>>> from sympy import trace, Symbol, MatrixSymbol, eye
>>> n = Symbol('n')
>>> X = MatrixSymbol('X', n, n) # A square matrix
>>> trace(2*X)
2*Trace(X)
>>> trace(eye(3))
3
"""
return Trace(expr).doit()
|
7117a16d878c12aab473c4bcd2bb9c04769ea1a279f73c3d36a94c8f79151c24 | from collections import Counter
from sympy.core import Mul, sympify
from sympy.core.add import Add
from sympy.core.expr import ExprBuilder
from sympy.core.sorting import default_sort_key
from sympy.functions.elementary.exponential import log
from sympy.matrices.common import ShapeError
from sympy.matrices.expressions.matexpr import MatrixExpr
from sympy.matrices.expressions.special import ZeroMatrix, OneMatrix
from sympy.strategies import (
unpack, flatten, condition, exhaust, rm_id, sort
)
from sympy.utilities.exceptions import sympy_deprecation_warning
def hadamard_product(*matrices):
"""
Return the elementwise (aka Hadamard) product of matrices.
Examples
========
>>> from sympy import hadamard_product, MatrixSymbol
>>> A = MatrixSymbol('A', 2, 3)
>>> B = MatrixSymbol('B', 2, 3)
>>> hadamard_product(A)
A
>>> hadamard_product(A, B)
HadamardProduct(A, B)
>>> hadamard_product(A, B)[0, 1]
A[0, 1]*B[0, 1]
"""
if not matrices:
raise TypeError("Empty Hadamard product is undefined")
validate(*matrices)
if len(matrices) == 1:
return matrices[0]
else:
matrices = [i for i in matrices if not i.is_Identity]
return HadamardProduct(*matrices).doit()
class HadamardProduct(MatrixExpr):
"""
Elementwise product of matrix expressions
Examples
========
Hadamard product for matrix symbols:
>>> from sympy import hadamard_product, HadamardProduct, MatrixSymbol
>>> A = MatrixSymbol('A', 5, 5)
>>> B = MatrixSymbol('B', 5, 5)
>>> isinstance(hadamard_product(A, B), HadamardProduct)
True
Notes
=====
This is a symbolic object that simply stores its argument without
evaluating it. To actually compute the product, use the function
``hadamard_product()`` or ``HadamardProduct.doit``
"""
is_HadamardProduct = True
def __new__(cls, *args, evaluate=False, check=None):
args = list(map(sympify, args))
if check is not None:
sympy_deprecation_warning(
"Passing check to HadamardProduct is deprecated and the check argument will be removed in a future version.",
deprecated_since_version="1.11",
active_deprecations_target='remove-check-argument-from-matrix-operations')
if check in (True, None):
validate(*args)
else:
sympy_deprecation_warning(
"Passing check=False to HadamardProduct is deprecated and the check argument will be removed in a future version.",
deprecated_since_version="1.11",
active_deprecations_target='remove-check-argument-from-matrix-operations')
obj = super().__new__(cls, *args)
if evaluate:
obj = obj.doit(deep=False)
return obj
@property
def shape(self):
return self.args[0].shape
def _entry(self, i, j, **kwargs):
return Mul(*[arg._entry(i, j, **kwargs) for arg in self.args])
def _eval_transpose(self):
from sympy.matrices.expressions.transpose import transpose
return HadamardProduct(*list(map(transpose, self.args)))
def doit(self, **hints):
expr = self.func(*[i.doit(**hints) for i in self.args])
# Check for explicit matrices:
from sympy.matrices.matrices import MatrixBase
from sympy.matrices.immutable import ImmutableMatrix
explicit = [i for i in expr.args if isinstance(i, MatrixBase)]
if explicit:
remainder = [i for i in expr.args if i not in explicit]
expl_mat = ImmutableMatrix([
Mul.fromiter(i) for i in zip(*explicit)
]).reshape(*self.shape)
expr = HadamardProduct(*([expl_mat] + remainder))
return canonicalize(expr)
def _eval_derivative(self, x):
terms = []
args = list(self.args)
for i in range(len(args)):
factors = args[:i] + [args[i].diff(x)] + args[i+1:]
terms.append(hadamard_product(*factors))
return Add.fromiter(terms)
def _eval_derivative_matrix_lines(self, x):
from sympy.tensor.array.expressions.array_expressions import ArrayDiagonal
from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct
from sympy.matrices.expressions.matexpr import _make_matrix
with_x_ind = [i for i, arg in enumerate(self.args) if arg.has(x)]
lines = []
for ind in with_x_ind:
left_args = self.args[:ind]
right_args = self.args[ind+1:]
d = self.args[ind]._eval_derivative_matrix_lines(x)
hadam = hadamard_product(*(right_args + left_args))
diagonal = [(0, 2), (3, 4)]
diagonal = [e for j, e in enumerate(diagonal) if self.shape[j] != 1]
for i in d:
l1 = i._lines[i._first_line_index]
l2 = i._lines[i._second_line_index]
subexpr = ExprBuilder(
ArrayDiagonal,
[
ExprBuilder(
ArrayTensorProduct,
[
ExprBuilder(_make_matrix, [l1]),
hadam,
ExprBuilder(_make_matrix, [l2]),
]
),
*diagonal],
)
i._first_pointer_parent = subexpr.args[0].args[0].args
i._first_pointer_index = 0
i._second_pointer_parent = subexpr.args[0].args[2].args
i._second_pointer_index = 0
i._lines = [subexpr]
lines.append(i)
return lines
def validate(*args):
if not all(arg.is_Matrix for arg in args):
raise TypeError("Mix of Matrix and Scalar symbols")
A = args[0]
for B in args[1:]:
if A.shape != B.shape:
raise ShapeError("Matrices %s and %s are not aligned" % (A, B))
# TODO Implement algorithm for rewriting Hadamard product as diagonal matrix
# if matmul identy matrix is multiplied.
def canonicalize(x):
"""Canonicalize the Hadamard product ``x`` with mathematical properties.
Examples
========
>>> from sympy import MatrixSymbol, HadamardProduct
>>> from sympy import OneMatrix, ZeroMatrix
>>> from sympy.matrices.expressions.hadamard import canonicalize
>>> from sympy import init_printing
>>> init_printing(use_unicode=False)
>>> A = MatrixSymbol('A', 2, 2)
>>> B = MatrixSymbol('B', 2, 2)
>>> C = MatrixSymbol('C', 2, 2)
Hadamard product associativity:
>>> X = HadamardProduct(A, HadamardProduct(B, C))
>>> X
A.*(B.*C)
>>> canonicalize(X)
A.*B.*C
Hadamard product commutativity:
>>> X = HadamardProduct(A, B)
>>> Y = HadamardProduct(B, A)
>>> X
A.*B
>>> Y
B.*A
>>> canonicalize(X)
A.*B
>>> canonicalize(Y)
A.*B
Hadamard product identity:
>>> X = HadamardProduct(A, OneMatrix(2, 2))
>>> X
A.*1
>>> canonicalize(X)
A
Absorbing element of Hadamard product:
>>> X = HadamardProduct(A, ZeroMatrix(2, 2))
>>> X
A.*0
>>> canonicalize(X)
0
Rewriting to Hadamard Power
>>> X = HadamardProduct(A, A, A)
>>> X
A.*A.*A
>>> canonicalize(X)
.3
A
Notes
=====
As the Hadamard product is associative, nested products can be flattened.
The Hadamard product is commutative so that factors can be sorted for
canonical form.
A matrix of only ones is an identity for Hadamard product,
so every matrices of only ones can be removed.
Any zero matrix will make the whole product a zero matrix.
Duplicate elements can be collected and rewritten as HadamardPower
References
==========
.. [1] https://en.wikipedia.org/wiki/Hadamard_product_(matrices)
"""
# Associativity
rule = condition(
lambda x: isinstance(x, HadamardProduct),
flatten
)
fun = exhaust(rule)
x = fun(x)
# Identity
fun = condition(
lambda x: isinstance(x, HadamardProduct),
rm_id(lambda x: isinstance(x, OneMatrix))
)
x = fun(x)
# Absorbing by Zero Matrix
def absorb(x):
if any(isinstance(c, ZeroMatrix) for c in x.args):
return ZeroMatrix(*x.shape)
else:
return x
fun = condition(
lambda x: isinstance(x, HadamardProduct),
absorb
)
x = fun(x)
# Rewriting with HadamardPower
if isinstance(x, HadamardProduct):
tally = Counter(x.args)
new_arg = []
for base, exp in tally.items():
if exp == 1:
new_arg.append(base)
else:
new_arg.append(HadamardPower(base, exp))
x = HadamardProduct(*new_arg)
# Commutativity
fun = condition(
lambda x: isinstance(x, HadamardProduct),
sort(default_sort_key)
)
x = fun(x)
# Unpacking
x = unpack(x)
return x
def hadamard_power(base, exp):
base = sympify(base)
exp = sympify(exp)
if exp == 1:
return base
if not base.is_Matrix:
return base**exp
if exp.is_Matrix:
raise ValueError("cannot raise expression to a matrix")
return HadamardPower(base, exp)
class HadamardPower(MatrixExpr):
r"""
Elementwise power of matrix expressions
Parameters
==========
base : scalar or matrix
exp : scalar or matrix
Notes
=====
There are four definitions for the hadamard power which can be used.
Let's consider `A, B` as `(m, n)` matrices, and `a, b` as scalars.
Matrix raised to a scalar exponent:
.. math::
A^{\circ b} = \begin{bmatrix}
A_{0, 0}^b & A_{0, 1}^b & \cdots & A_{0, n-1}^b \\
A_{1, 0}^b & A_{1, 1}^b & \cdots & A_{1, n-1}^b \\
\vdots & \vdots & \ddots & \vdots \\
A_{m-1, 0}^b & A_{m-1, 1}^b & \cdots & A_{m-1, n-1}^b
\end{bmatrix}
Scalar raised to a matrix exponent:
.. math::
a^{\circ B} = \begin{bmatrix}
a^{B_{0, 0}} & a^{B_{0, 1}} & \cdots & a^{B_{0, n-1}} \\
a^{B_{1, 0}} & a^{B_{1, 1}} & \cdots & a^{B_{1, n-1}} \\
\vdots & \vdots & \ddots & \vdots \\
a^{B_{m-1, 0}} & a^{B_{m-1, 1}} & \cdots & a^{B_{m-1, n-1}}
\end{bmatrix}
Matrix raised to a matrix exponent:
.. math::
A^{\circ B} = \begin{bmatrix}
A_{0, 0}^{B_{0, 0}} & A_{0, 1}^{B_{0, 1}} &
\cdots & A_{0, n-1}^{B_{0, n-1}} \\
A_{1, 0}^{B_{1, 0}} & A_{1, 1}^{B_{1, 1}} &
\cdots & A_{1, n-1}^{B_{1, n-1}} \\
\vdots & \vdots &
\ddots & \vdots \\
A_{m-1, 0}^{B_{m-1, 0}} & A_{m-1, 1}^{B_{m-1, 1}} &
\cdots & A_{m-1, n-1}^{B_{m-1, n-1}}
\end{bmatrix}
Scalar raised to a scalar exponent:
.. math::
a^{\circ b} = a^b
"""
def __new__(cls, base, exp):
base = sympify(base)
exp = sympify(exp)
if base.is_scalar and exp.is_scalar:
return base ** exp
if base.is_Matrix and exp.is_Matrix and base.shape != exp.shape:
raise ValueError(
'The shape of the base {} and '
'the shape of the exponent {} do not match.'
.format(base.shape, exp.shape)
)
obj = super().__new__(cls, base, exp)
return obj
@property
def base(self):
return self._args[0]
@property
def exp(self):
return self._args[1]
@property
def shape(self):
if self.base.is_Matrix:
return self.base.shape
return self.exp.shape
def _entry(self, i, j, **kwargs):
base = self.base
exp = self.exp
if base.is_Matrix:
a = base._entry(i, j, **kwargs)
elif base.is_scalar:
a = base
else:
raise ValueError(
'The base {} must be a scalar or a matrix.'.format(base))
if exp.is_Matrix:
b = exp._entry(i, j, **kwargs)
elif exp.is_scalar:
b = exp
else:
raise ValueError(
'The exponent {} must be a scalar or a matrix.'.format(exp))
return a ** b
def _eval_transpose(self):
from sympy.matrices.expressions.transpose import transpose
return HadamardPower(transpose(self.base), self.exp)
def _eval_derivative(self, x):
dexp = self.exp.diff(x)
logbase = self.base.applyfunc(log)
dlbase = logbase.diff(x)
return hadamard_product(
dexp*logbase + self.exp*dlbase,
self
)
def _eval_derivative_matrix_lines(self, x):
from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct
from sympy.tensor.array.expressions.array_expressions import ArrayDiagonal
from sympy.matrices.expressions.matexpr import _make_matrix
lr = self.base._eval_derivative_matrix_lines(x)
for i in lr:
diagonal = [(1, 2), (3, 4)]
diagonal = [e for j, e in enumerate(diagonal) if self.base.shape[j] != 1]
l1 = i._lines[i._first_line_index]
l2 = i._lines[i._second_line_index]
subexpr = ExprBuilder(
ArrayDiagonal,
[
ExprBuilder(
ArrayTensorProduct,
[
ExprBuilder(_make_matrix, [l1]),
self.exp*hadamard_power(self.base, self.exp-1),
ExprBuilder(_make_matrix, [l2]),
]
),
*diagonal],
validator=ArrayDiagonal._validate
)
i._first_pointer_parent = subexpr.args[0].args[0].args
i._first_pointer_index = 0
i._first_line_index = 0
i._second_pointer_parent = subexpr.args[0].args[2].args
i._second_pointer_index = 0
i._second_line_index = 0
i._lines = [subexpr]
return lr
|
78a4381a5566e3fea2d9b6a1ed3f79aad25d5d62c9276f32af2dbb6a31867c8a | from sympy.assumptions.ask import (Q, ask)
from sympy.core import Basic, Add, Mul, S
from sympy.core.sympify import _sympify
from sympy.functions import adjoint
from sympy.functions.elementary.complexes import re, im
from sympy.strategies import typed, exhaust, condition, do_one, unpack
from sympy.strategies.traverse import bottom_up
from sympy.utilities.iterables import is_sequence, sift
from sympy.utilities.misc import filldedent
from sympy.matrices import Matrix, ShapeError
from sympy.matrices.common import NonInvertibleMatrixError
from sympy.matrices.expressions.determinant import det, Determinant
from sympy.matrices.expressions.inverse import Inverse
from sympy.matrices.expressions.matadd import MatAdd
from sympy.matrices.expressions.matexpr import MatrixExpr, MatrixElement
from sympy.matrices.expressions.matmul import MatMul
from sympy.matrices.expressions.matpow import MatPow
from sympy.matrices.expressions.slice import MatrixSlice
from sympy.matrices.expressions.special import ZeroMatrix, Identity
from sympy.matrices.expressions.trace import trace
from sympy.matrices.expressions.transpose import Transpose, transpose
class BlockMatrix(MatrixExpr):
"""A BlockMatrix is a Matrix comprised of other matrices.
The submatrices are stored in a SymPy Matrix object but accessed as part of
a Matrix Expression
>>> from sympy import (MatrixSymbol, BlockMatrix, symbols,
... Identity, ZeroMatrix, block_collapse)
>>> n,m,l = symbols('n m l')
>>> X = MatrixSymbol('X', n, n)
>>> Y = MatrixSymbol('Y', m, m)
>>> Z = MatrixSymbol('Z', n, m)
>>> B = BlockMatrix([[X, Z], [ZeroMatrix(m,n), Y]])
>>> print(B)
Matrix([
[X, Z],
[0, Y]])
>>> C = BlockMatrix([[Identity(n), Z]])
>>> print(C)
Matrix([[I, Z]])
>>> print(block_collapse(C*B))
Matrix([[X, Z + Z*Y]])
Some matrices might be comprised of rows of blocks with
the matrices in each row having the same height and the
rows all having the same total number of columns but
not having the same number of columns for each matrix
in each row. In this case, the matrix is not a block
matrix and should be instantiated by Matrix.
>>> from sympy import ones, Matrix
>>> dat = [
... [ones(3,2), ones(3,3)*2],
... [ones(2,3)*3, ones(2,2)*4]]
...
>>> BlockMatrix(dat)
Traceback (most recent call last):
...
ValueError:
Although this matrix is comprised of blocks, the blocks do not fill
the matrix in a size-symmetric fashion. To create a full matrix from
these arguments, pass them directly to Matrix.
>>> Matrix(dat)
Matrix([
[1, 1, 2, 2, 2],
[1, 1, 2, 2, 2],
[1, 1, 2, 2, 2],
[3, 3, 3, 4, 4],
[3, 3, 3, 4, 4]])
See Also
========
sympy.matrices.matrices.MatrixBase.irregular
"""
def __new__(cls, *args, **kwargs):
from sympy.matrices.immutable import ImmutableDenseMatrix
isMat = lambda i: getattr(i, 'is_Matrix', False)
if len(args) != 1 or \
not is_sequence(args[0]) or \
len({isMat(r) for r in args[0]}) != 1:
raise ValueError(filldedent('''
expecting a sequence of 1 or more rows
containing Matrices.'''))
rows = args[0] if args else []
if not isMat(rows):
if rows and isMat(rows[0]):
rows = [rows] # rows is not list of lists or []
# regularity check
# same number of matrices in each row
blocky = ok = len({len(r) for r in rows}) == 1
if ok:
# same number of rows for each matrix in a row
for r in rows:
ok = len({i.rows for i in r}) == 1
if not ok:
break
blocky = ok
if ok:
# same number of cols for each matrix in each col
for c in range(len(rows[0])):
ok = len({rows[i][c].cols
for i in range(len(rows))}) == 1
if not ok:
break
if not ok:
# same total cols in each row
ok = len({
sum([i.cols for i in r]) for r in rows}) == 1
if blocky and ok:
raise ValueError(filldedent('''
Although this matrix is comprised of blocks,
the blocks do not fill the matrix in a
size-symmetric fashion. To create a full matrix
from these arguments, pass them directly to
Matrix.'''))
raise ValueError(filldedent('''
When there are not the same number of rows in each
row's matrices or there are not the same number of
total columns in each row, the matrix is not a
block matrix. If this matrix is known to consist of
blocks fully filling a 2-D space then see
Matrix.irregular.'''))
mat = ImmutableDenseMatrix(rows, evaluate=False)
obj = Basic.__new__(cls, mat)
return obj
@property
def shape(self):
numrows = numcols = 0
M = self.blocks
for i in range(M.shape[0]):
numrows += M[i, 0].shape[0]
for i in range(M.shape[1]):
numcols += M[0, i].shape[1]
return (numrows, numcols)
@property
def blockshape(self):
return self.blocks.shape
@property
def blocks(self):
return self.args[0]
@property
def rowblocksizes(self):
return [self.blocks[i, 0].rows for i in range(self.blockshape[0])]
@property
def colblocksizes(self):
return [self.blocks[0, i].cols for i in range(self.blockshape[1])]
def structurally_equal(self, other):
return (isinstance(other, BlockMatrix)
and self.shape == other.shape
and self.blockshape == other.blockshape
and self.rowblocksizes == other.rowblocksizes
and self.colblocksizes == other.colblocksizes)
def _blockmul(self, other):
if (isinstance(other, BlockMatrix) and
self.colblocksizes == other.rowblocksizes):
return BlockMatrix(self.blocks*other.blocks)
return self * other
def _blockadd(self, other):
if (isinstance(other, BlockMatrix)
and self.structurally_equal(other)):
return BlockMatrix(self.blocks + other.blocks)
return self + other
def _eval_transpose(self):
# Flip all the individual matrices
matrices = [transpose(matrix) for matrix in self.blocks]
# Make a copy
M = Matrix(self.blockshape[0], self.blockshape[1], matrices)
# Transpose the block structure
M = M.transpose()
return BlockMatrix(M)
def _eval_adjoint(self):
# Adjoint all the individual matrices
matrices = [adjoint(matrix) for matrix in self.blocks]
# Make a copy
M = Matrix(self.blockshape[0], self.blockshape[1], matrices)
# Transpose the block structure
M = M.transpose()
return BlockMatrix(M)
def _eval_trace(self):
if self.rowblocksizes == self.colblocksizes:
return Add(*[trace(self.blocks[i, i])
for i in range(self.blockshape[0])])
raise NotImplementedError(
"Can't perform trace of irregular blockshape")
def _eval_determinant(self):
if self.blockshape == (1, 1):
return det(self.blocks[0, 0])
if self.blockshape == (2, 2):
[[A, B],
[C, D]] = self.blocks.tolist()
if ask(Q.invertible(A)):
return det(A)*det(D - C*A.I*B)
elif ask(Q.invertible(D)):
return det(D)*det(A - B*D.I*C)
return Determinant(self)
def _eval_as_real_imag(self):
real_matrices = [re(matrix) for matrix in self.blocks]
real_matrices = Matrix(self.blockshape[0], self.blockshape[1], real_matrices)
im_matrices = [im(matrix) for matrix in self.blocks]
im_matrices = Matrix(self.blockshape[0], self.blockshape[1], im_matrices)
return (BlockMatrix(real_matrices), BlockMatrix(im_matrices))
def transpose(self):
"""Return transpose of matrix.
Examples
========
>>> from sympy import MatrixSymbol, BlockMatrix, ZeroMatrix
>>> from sympy.abc import m, n
>>> X = MatrixSymbol('X', n, n)
>>> Y = MatrixSymbol('Y', m, m)
>>> Z = MatrixSymbol('Z', n, m)
>>> B = BlockMatrix([[X, Z], [ZeroMatrix(m,n), Y]])
>>> B.transpose()
Matrix([
[X.T, 0],
[Z.T, Y.T]])
>>> _.transpose()
Matrix([
[X, Z],
[0, Y]])
"""
return self._eval_transpose()
def schur(self, mat = 'A', generalized = False):
"""Return the Schur Complement of the 2x2 BlockMatrix
Parameters
==========
mat : String, optional
The matrix with respect to which the
Schur Complement is calculated. 'A' is
used by default
generalized : bool, optional
If True, returns the generalized Schur
Component which uses Moore-Penrose Inverse
Examples
========
>>> from sympy import symbols, MatrixSymbol, BlockMatrix
>>> m, n = symbols('m n')
>>> A = MatrixSymbol('A', n, n)
>>> B = MatrixSymbol('B', n, m)
>>> C = MatrixSymbol('C', m, n)
>>> D = MatrixSymbol('D', m, m)
>>> X = BlockMatrix([[A, B], [C, D]])
The default Schur Complement is evaluated with "A"
>>> X.schur()
-C*A**(-1)*B + D
>>> X.schur('D')
A - B*D**(-1)*C
Schur complement with non-invertible matrices is not
defined. Instead, the generalized Schur complement can
be calculated which uses the Moore-Penrose Inverse. To
achieve this, `generalized` must be set to `True`
>>> X.schur('B', generalized=True)
C - D*(B.T*B)**(-1)*B.T*A
>>> X.schur('C', generalized=True)
-A*(C.T*C)**(-1)*C.T*D + B
Returns
=======
M : Matrix
The Schur Complement Matrix
Raises
======
ShapeError
If the block matrix is not a 2x2 matrix
NonInvertibleMatrixError
If given matrix is non-invertible
References
==========
.. [1] Wikipedia Article on Schur Component : https://en.wikipedia.org/wiki/Schur_complement
See Also
========
sympy.matrices.matrices.MatrixBase.pinv
"""
if self.blockshape == (2, 2):
[[A, B],
[C, D]] = self.blocks.tolist()
d={'A' : A, 'B' : B, 'C' : C, 'D' : D}
try:
inv = (d[mat].T*d[mat]).inv()*d[mat].T if generalized else d[mat].inv()
if mat == 'A':
return D - C * inv * B
elif mat == 'B':
return C - D * inv * A
elif mat == 'C':
return B - A * inv * D
elif mat == 'D':
return A - B * inv * C
#For matrices where no sub-matrix is square
return self
except NonInvertibleMatrixError:
raise NonInvertibleMatrixError('The given matrix is not invertible. Please set generalized=True \
to compute the generalized Schur Complement which uses Moore-Penrose Inverse')
else:
raise ShapeError('Schur Complement can only be calculated for 2x2 block matrices')
def LDUdecomposition(self):
"""Returns the Block LDU decomposition of
a 2x2 Block Matrix
Returns
=======
(L, D, U) : Matrices
L : Lower Diagonal Matrix
D : Diagonal Matrix
U : Upper Diagonal Matrix
Examples
========
>>> from sympy import symbols, MatrixSymbol, BlockMatrix, block_collapse
>>> m, n = symbols('m n')
>>> A = MatrixSymbol('A', n, n)
>>> B = MatrixSymbol('B', n, m)
>>> C = MatrixSymbol('C', m, n)
>>> D = MatrixSymbol('D', m, m)
>>> X = BlockMatrix([[A, B], [C, D]])
>>> L, D, U = X.LDUdecomposition()
>>> block_collapse(L*D*U)
Matrix([
[A, B],
[C, D]])
Raises
======
ShapeError
If the block matrix is not a 2x2 matrix
NonInvertibleMatrixError
If the matrix "A" is non-invertible
See Also
========
sympy.matrices.expressions.blockmatrix.BlockMatrix.UDLdecomposition
sympy.matrices.expressions.blockmatrix.BlockMatrix.LUdecomposition
"""
if self.blockshape == (2,2):
[[A, B],
[C, D]] = self.blocks.tolist()
try:
AI = A.I
except NonInvertibleMatrixError:
raise NonInvertibleMatrixError('Block LDU decomposition cannot be calculated when\
"A" is singular')
Ip = Identity(B.shape[0])
Iq = Identity(B.shape[1])
Z = ZeroMatrix(*B.shape)
L = BlockMatrix([[Ip, Z], [C*AI, Iq]])
D = BlockDiagMatrix(A, self.schur())
U = BlockMatrix([[Ip, AI*B],[Z.T, Iq]])
return L, D, U
else:
raise ShapeError("Block LDU decomposition is supported only for 2x2 block matrices")
def UDLdecomposition(self):
"""Returns the Block UDL decomposition of
a 2x2 Block Matrix
Returns
=======
(U, D, L) : Matrices
U : Upper Diagonal Matrix
D : Diagonal Matrix
L : Lower Diagonal Matrix
Examples
========
>>> from sympy import symbols, MatrixSymbol, BlockMatrix, block_collapse
>>> m, n = symbols('m n')
>>> A = MatrixSymbol('A', n, n)
>>> B = MatrixSymbol('B', n, m)
>>> C = MatrixSymbol('C', m, n)
>>> D = MatrixSymbol('D', m, m)
>>> X = BlockMatrix([[A, B], [C, D]])
>>> U, D, L = X.UDLdecomposition()
>>> block_collapse(U*D*L)
Matrix([
[A, B],
[C, D]])
Raises
======
ShapeError
If the block matrix is not a 2x2 matrix
NonInvertibleMatrixError
If the matrix "D" is non-invertible
See Also
========
sympy.matrices.expressions.blockmatrix.BlockMatrix.LDUdecomposition
sympy.matrices.expressions.blockmatrix.BlockMatrix.LUdecomposition
"""
if self.blockshape == (2,2):
[[A, B],
[C, D]] = self.blocks.tolist()
try:
DI = D.I
except NonInvertibleMatrixError:
raise NonInvertibleMatrixError('Block UDL decomposition cannot be calculated when\
"D" is singular')
Ip = Identity(A.shape[0])
Iq = Identity(B.shape[1])
Z = ZeroMatrix(*B.shape)
U = BlockMatrix([[Ip, B*DI], [Z.T, Iq]])
D = BlockDiagMatrix(self.schur('D'), D)
L = BlockMatrix([[Ip, Z],[DI*C, Iq]])
return U, D, L
else:
raise ShapeError("Block UDL decomposition is supported only for 2x2 block matrices")
def LUdecomposition(self):
"""Returns the Block LU decomposition of
a 2x2 Block Matrix
Returns
=======
(L, U) : Matrices
L : Lower Diagonal Matrix
U : Upper Diagonal Matrix
Examples
========
>>> from sympy import symbols, MatrixSymbol, BlockMatrix, block_collapse
>>> m, n = symbols('m n')
>>> A = MatrixSymbol('A', n, n)
>>> B = MatrixSymbol('B', n, m)
>>> C = MatrixSymbol('C', m, n)
>>> D = MatrixSymbol('D', m, m)
>>> X = BlockMatrix([[A, B], [C, D]])
>>> L, U = X.LUdecomposition()
>>> block_collapse(L*U)
Matrix([
[A, B],
[C, D]])
Raises
======
ShapeError
If the block matrix is not a 2x2 matrix
NonInvertibleMatrixError
If the matrix "A" is non-invertible
See Also
========
sympy.matrices.expressions.blockmatrix.BlockMatrix.UDLdecomposition
sympy.matrices.expressions.blockmatrix.BlockMatrix.LDUdecomposition
"""
if self.blockshape == (2,2):
[[A, B],
[C, D]] = self.blocks.tolist()
try:
A = A**0.5
AI = A.I
except NonInvertibleMatrixError:
raise NonInvertibleMatrixError('Block LU decomposition cannot be calculated when\
"A" is singular')
Z = ZeroMatrix(*B.shape)
Q = self.schur()**0.5
L = BlockMatrix([[A, Z], [C*AI, Q]])
U = BlockMatrix([[A, AI*B],[Z.T, Q]])
return L, U
else:
raise ShapeError("Block LU decomposition is supported only for 2x2 block matrices")
def _entry(self, i, j, **kwargs):
# Find row entry
orig_i, orig_j = i, j
for row_block, numrows in enumerate(self.rowblocksizes):
cmp = i < numrows
if cmp == True:
break
elif cmp == False:
i -= numrows
elif row_block < self.blockshape[0] - 1:
# Can't tell which block and it's not the last one, return unevaluated
return MatrixElement(self, orig_i, orig_j)
for col_block, numcols in enumerate(self.colblocksizes):
cmp = j < numcols
if cmp == True:
break
elif cmp == False:
j -= numcols
elif col_block < self.blockshape[1] - 1:
return MatrixElement(self, orig_i, orig_j)
return self.blocks[row_block, col_block][i, j]
@property
def is_Identity(self):
if self.blockshape[0] != self.blockshape[1]:
return False
for i in range(self.blockshape[0]):
for j in range(self.blockshape[1]):
if i==j and not self.blocks[i, j].is_Identity:
return False
if i!=j and not self.blocks[i, j].is_ZeroMatrix:
return False
return True
@property
def is_structurally_symmetric(self):
return self.rowblocksizes == self.colblocksizes
def equals(self, other):
if self == other:
return True
if (isinstance(other, BlockMatrix) and self.blocks == other.blocks):
return True
return super().equals(other)
class BlockDiagMatrix(BlockMatrix):
"""A sparse matrix with block matrices along its diagonals
Examples
========
>>> from sympy import MatrixSymbol, BlockDiagMatrix, symbols
>>> n, m, l = symbols('n m l')
>>> X = MatrixSymbol('X', n, n)
>>> Y = MatrixSymbol('Y', m, m)
>>> BlockDiagMatrix(X, Y)
Matrix([
[X, 0],
[0, Y]])
Notes
=====
If you want to get the individual diagonal blocks, use
:meth:`get_diag_blocks`.
See Also
========
sympy.matrices.dense.diag
"""
def __new__(cls, *mats):
return Basic.__new__(BlockDiagMatrix, *[_sympify(m) for m in mats])
@property
def diag(self):
return self.args
@property
def blocks(self):
from sympy.matrices.immutable import ImmutableDenseMatrix
mats = self.args
data = [[mats[i] if i == j else ZeroMatrix(mats[i].rows, mats[j].cols)
for j in range(len(mats))]
for i in range(len(mats))]
return ImmutableDenseMatrix(data, evaluate=False)
@property
def shape(self):
return (sum(block.rows for block in self.args),
sum(block.cols for block in self.args))
@property
def blockshape(self):
n = len(self.args)
return (n, n)
@property
def rowblocksizes(self):
return [block.rows for block in self.args]
@property
def colblocksizes(self):
return [block.cols for block in self.args]
def _all_square_blocks(self):
"""Returns true if all blocks are square"""
return all(mat.is_square for mat in self.args)
def _eval_determinant(self):
if self._all_square_blocks():
return Mul(*[det(mat) for mat in self.args])
# At least one block is non-square. Since the entire matrix must be square we know there must
# be at least two blocks in this matrix, in which case the entire matrix is necessarily rank-deficient
return S.Zero
def _eval_inverse(self, expand='ignored'):
if self._all_square_blocks():
return BlockDiagMatrix(*[mat.inverse() for mat in self.args])
# See comment in _eval_determinant()
raise NonInvertibleMatrixError('Matrix det == 0; not invertible.')
def _eval_transpose(self):
return BlockDiagMatrix(*[mat.transpose() for mat in self.args])
def _blockmul(self, other):
if (isinstance(other, BlockDiagMatrix) and
self.colblocksizes == other.rowblocksizes):
return BlockDiagMatrix(*[a*b for a, b in zip(self.args, other.args)])
else:
return BlockMatrix._blockmul(self, other)
def _blockadd(self, other):
if (isinstance(other, BlockDiagMatrix) and
self.blockshape == other.blockshape and
self.rowblocksizes == other.rowblocksizes and
self.colblocksizes == other.colblocksizes):
return BlockDiagMatrix(*[a + b for a, b in zip(self.args, other.args)])
else:
return BlockMatrix._blockadd(self, other)
def get_diag_blocks(self):
"""Return the list of diagonal blocks of the matrix.
Examples
========
>>> from sympy import BlockDiagMatrix, Matrix
>>> A = Matrix([[1, 2], [3, 4]])
>>> B = Matrix([[5, 6], [7, 8]])
>>> M = BlockDiagMatrix(A, B)
How to get diagonal blocks from the block diagonal matrix:
>>> diag_blocks = M.get_diag_blocks()
>>> diag_blocks[0]
Matrix([
[1, 2],
[3, 4]])
>>> diag_blocks[1]
Matrix([
[5, 6],
[7, 8]])
"""
return self.args
def block_collapse(expr):
"""Evaluates a block matrix expression
>>> from sympy import MatrixSymbol, BlockMatrix, symbols, Identity, ZeroMatrix, block_collapse
>>> n,m,l = symbols('n m l')
>>> X = MatrixSymbol('X', n, n)
>>> Y = MatrixSymbol('Y', m, m)
>>> Z = MatrixSymbol('Z', n, m)
>>> B = BlockMatrix([[X, Z], [ZeroMatrix(m, n), Y]])
>>> print(B)
Matrix([
[X, Z],
[0, Y]])
>>> C = BlockMatrix([[Identity(n), Z]])
>>> print(C)
Matrix([[I, Z]])
>>> print(block_collapse(C*B))
Matrix([[X, Z + Z*Y]])
"""
from sympy.strategies.util import expr_fns
hasbm = lambda expr: isinstance(expr, MatrixExpr) and expr.has(BlockMatrix)
conditioned_rl = condition(
hasbm,
typed(
{MatAdd: do_one(bc_matadd, bc_block_plus_ident),
MatMul: do_one(bc_matmul, bc_dist),
MatPow: bc_matmul,
Transpose: bc_transpose,
Inverse: bc_inverse,
BlockMatrix: do_one(bc_unpack, deblock)}
)
)
rule = exhaust(
bottom_up(
exhaust(conditioned_rl),
fns=expr_fns
)
)
result = rule(expr)
doit = getattr(result, 'doit', None)
if doit is not None:
return doit()
else:
return result
def bc_unpack(expr):
if expr.blockshape == (1, 1):
return expr.blocks[0, 0]
return expr
def bc_matadd(expr):
args = sift(expr.args, lambda M: isinstance(M, BlockMatrix))
blocks = args[True]
if not blocks:
return expr
nonblocks = args[False]
block = blocks[0]
for b in blocks[1:]:
block = block._blockadd(b)
if nonblocks:
return MatAdd(*nonblocks) + block
else:
return block
def bc_block_plus_ident(expr):
idents = [arg for arg in expr.args if arg.is_Identity]
if not idents:
return expr
blocks = [arg for arg in expr.args if isinstance(arg, BlockMatrix)]
if (blocks and all(b.structurally_equal(blocks[0]) for b in blocks)
and blocks[0].is_structurally_symmetric):
block_id = BlockDiagMatrix(*[Identity(k)
for k in blocks[0].rowblocksizes])
rest = [arg for arg in expr.args if not arg.is_Identity and not isinstance(arg, BlockMatrix)]
return MatAdd(block_id * len(idents), *blocks, *rest).doit()
return expr
def bc_dist(expr):
""" Turn a*[X, Y] into [a*X, a*Y] """
factor, mat = expr.as_coeff_mmul()
if factor == 1:
return expr
unpacked = unpack(mat)
if isinstance(unpacked, BlockDiagMatrix):
B = unpacked.diag
new_B = [factor * mat for mat in B]
return BlockDiagMatrix(*new_B)
elif isinstance(unpacked, BlockMatrix):
B = unpacked.blocks
new_B = [
[factor * B[i, j] for j in range(B.cols)] for i in range(B.rows)]
return BlockMatrix(new_B)
return expr
def bc_matmul(expr):
if isinstance(expr, MatPow):
if expr.args[1].is_Integer:
factor, matrices = (1, [expr.args[0]]*expr.args[1])
else:
return expr
else:
factor, matrices = expr.as_coeff_matrices()
i = 0
while (i+1 < len(matrices)):
A, B = matrices[i:i+2]
if isinstance(A, BlockMatrix) and isinstance(B, BlockMatrix):
matrices[i] = A._blockmul(B)
matrices.pop(i+1)
elif isinstance(A, BlockMatrix):
matrices[i] = A._blockmul(BlockMatrix([[B]]))
matrices.pop(i+1)
elif isinstance(B, BlockMatrix):
matrices[i] = BlockMatrix([[A]])._blockmul(B)
matrices.pop(i+1)
else:
i+=1
return MatMul(factor, *matrices).doit()
def bc_transpose(expr):
collapse = block_collapse(expr.arg)
return collapse._eval_transpose()
def bc_inverse(expr):
if isinstance(expr.arg, BlockDiagMatrix):
return expr.inverse()
expr2 = blockinverse_1x1(expr)
if expr != expr2:
return expr2
return blockinverse_2x2(Inverse(reblock_2x2(expr.arg)))
def blockinverse_1x1(expr):
if isinstance(expr.arg, BlockMatrix) and expr.arg.blockshape == (1, 1):
mat = Matrix([[expr.arg.blocks[0].inverse()]])
return BlockMatrix(mat)
return expr
def blockinverse_2x2(expr):
if isinstance(expr.arg, BlockMatrix) and expr.arg.blockshape == (2, 2):
# See: Inverses of 2x2 Block Matrices, Tzon-Tzer Lu and Sheng-Hua Shiou
[[A, B],
[C, D]] = expr.arg.blocks.tolist()
formula = _choose_2x2_inversion_formula(A, B, C, D)
if formula != None:
MI = expr.arg.schur(formula).I
if formula == 'A':
AI = A.I
return BlockMatrix([[AI + AI * B * MI * C * AI, -AI * B * MI], [-MI * C * AI, MI]])
if formula == 'B':
BI = B.I
return BlockMatrix([[-MI * D * BI, MI], [BI + BI * A * MI * D * BI, -BI * A * MI]])
if formula == 'C':
CI = C.I
return BlockMatrix([[-CI * D * MI, CI + CI * D * MI * A * CI], [MI, -MI * A * CI]])
if formula == 'D':
DI = D.I
return BlockMatrix([[MI, -MI * B * DI], [-DI * C * MI, DI + DI * C * MI * B * DI]])
return expr
def _choose_2x2_inversion_formula(A, B, C, D):
"""
Assuming [[A, B], [C, D]] would form a valid square block matrix, find
which of the classical 2x2 block matrix inversion formulas would be
best suited.
Returns 'A', 'B', 'C', 'D' to represent the algorithm involving inversion
of the given argument or None if the matrix cannot be inverted using
any of those formulas.
"""
# Try to find a known invertible matrix. Note that the Schur complement
# is currently not being considered for this
A_inv = ask(Q.invertible(A))
if A_inv == True:
return 'A'
B_inv = ask(Q.invertible(B))
if B_inv == True:
return 'B'
C_inv = ask(Q.invertible(C))
if C_inv == True:
return 'C'
D_inv = ask(Q.invertible(D))
if D_inv == True:
return 'D'
# Otherwise try to find a matrix that isn't known to be non-invertible
if A_inv != False:
return 'A'
if B_inv != False:
return 'B'
if C_inv != False:
return 'C'
if D_inv != False:
return 'D'
return None
def deblock(B):
""" Flatten a BlockMatrix of BlockMatrices """
if not isinstance(B, BlockMatrix) or not B.blocks.has(BlockMatrix):
return B
wrap = lambda x: x if isinstance(x, BlockMatrix) else BlockMatrix([[x]])
bb = B.blocks.applyfunc(wrap) # everything is a block
try:
MM = Matrix(0, sum(bb[0, i].blocks.shape[1] for i in range(bb.shape[1])), [])
for row in range(0, bb.shape[0]):
M = Matrix(bb[row, 0].blocks)
for col in range(1, bb.shape[1]):
M = M.row_join(bb[row, col].blocks)
MM = MM.col_join(M)
return BlockMatrix(MM)
except ShapeError:
return B
def reblock_2x2(expr):
"""
Reblock a BlockMatrix so that it has 2x2 blocks of block matrices. If
possible in such a way that the matrix continues to be invertible using the
classical 2x2 block inversion formulas.
"""
if not isinstance(expr, BlockMatrix) or not all(d > 2 for d in expr.blockshape):
return expr
BM = BlockMatrix # for brevity's sake
rowblocks, colblocks = expr.blockshape
blocks = expr.blocks
for i in range(1, rowblocks):
for j in range(1, colblocks):
# try to split rows at i and cols at j
A = bc_unpack(BM(blocks[:i, :j]))
B = bc_unpack(BM(blocks[:i, j:]))
C = bc_unpack(BM(blocks[i:, :j]))
D = bc_unpack(BM(blocks[i:, j:]))
formula = _choose_2x2_inversion_formula(A, B, C, D)
if formula is not None:
return BlockMatrix([[A, B], [C, D]])
# else: nothing worked, just split upper left corner
return BM([[blocks[0, 0], BM(blocks[0, 1:])],
[BM(blocks[1:, 0]), BM(blocks[1:, 1:])]])
def bounds(sizes):
""" Convert sequence of numbers into pairs of low-high pairs
>>> from sympy.matrices.expressions.blockmatrix import bounds
>>> bounds((1, 10, 50))
[(0, 1), (1, 11), (11, 61)]
"""
low = 0
rv = []
for size in sizes:
rv.append((low, low + size))
low += size
return rv
def blockcut(expr, rowsizes, colsizes):
""" Cut a matrix expression into Blocks
>>> from sympy import ImmutableMatrix, blockcut
>>> M = ImmutableMatrix(4, 4, range(16))
>>> B = blockcut(M, (1, 3), (1, 3))
>>> type(B).__name__
'BlockMatrix'
>>> ImmutableMatrix(B.blocks[0, 1])
Matrix([[1, 2, 3]])
"""
rowbounds = bounds(rowsizes)
colbounds = bounds(colsizes)
return BlockMatrix([[MatrixSlice(expr, rowbound, colbound)
for colbound in colbounds]
for rowbound in rowbounds])
|
Subsets and Splits