hash
stringlengths
64
64
content
stringlengths
0
1.51M
577dd3f6e8221b15188983f377f530b823dd582157d754b0476efdb773b52cac
""" This module mainly implements special orthogonal polynomials. See also functions.combinatorial.numbers which contains some combinatorial polynomials. """ from sympy.core import Rational from sympy.core.function import Function, ArgumentIndexError from sympy.core.singleton import S from sympy.core.symbol import Dummy from sympy.functions.combinatorial.factorials import binomial, factorial, RisingFactorial from sympy.functions.elementary.complexes import re from sympy.functions.elementary.exponential import exp from sympy.functions.elementary.integers import floor from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import cos, sec from sympy.functions.special.gamma_functions import gamma from sympy.functions.special.hyper import hyper from sympy.polys.orthopolys import (chebyshevt_poly, chebyshevu_poly, gegenbauer_poly, hermite_poly, jacobi_poly, laguerre_poly, legendre_poly) _x = Dummy('x') class OrthogonalPolynomial(Function): """Base class for orthogonal polynomials. """ @classmethod def _eval_at_order(cls, n, x): if n.is_integer and n >= 0: return cls._ortho_poly(int(n), _x).subs(_x, x) def _eval_conjugate(self): return self.func(self.args[0], self.args[1].conjugate()) #---------------------------------------------------------------------------- # Jacobi polynomials # class jacobi(OrthogonalPolynomial): r""" Jacobi polynomial $P_n^{\left(\alpha, \beta\right)}(x)$. Explanation =========== ``jacobi(n, alpha, beta, x)`` gives the $n$th Jacobi polynomial in $x$, $P_n^{\left(\alpha, \beta\right)}(x)$. The Jacobi polynomials are orthogonal on $[-1, 1]$ with respect to the weight $\left(1-x\right)^\alpha \left(1+x\right)^\beta$. Examples ======== >>> from sympy import jacobi, S, conjugate, diff >>> from sympy.abc import a, b, n, x >>> jacobi(0, a, b, x) 1 >>> jacobi(1, a, b, x) a/2 - b/2 + x*(a/2 + b/2 + 1) >>> jacobi(2, a, b, x) a**2/8 - a*b/4 - a/8 + b**2/8 - b/8 + x**2*(a**2/8 + a*b/4 + 7*a/8 + b**2/8 + 7*b/8 + 3/2) + x*(a**2/4 + 3*a/4 - b**2/4 - 3*b/4) - 1/2 >>> jacobi(n, a, b, x) jacobi(n, a, b, x) >>> jacobi(n, a, a, x) RisingFactorial(a + 1, n)*gegenbauer(n, a + 1/2, x)/RisingFactorial(2*a + 1, n) >>> jacobi(n, 0, 0, x) legendre(n, x) >>> jacobi(n, S(1)/2, S(1)/2, x) RisingFactorial(3/2, n)*chebyshevu(n, x)/factorial(n + 1) >>> jacobi(n, -S(1)/2, -S(1)/2, x) RisingFactorial(1/2, n)*chebyshevt(n, x)/factorial(n) >>> jacobi(n, a, b, -x) (-1)**n*jacobi(n, b, a, x) >>> jacobi(n, a, b, 0) gamma(a + n + 1)*hyper((-b - n, -n), (a + 1,), -1)/(2**n*factorial(n)*gamma(a + 1)) >>> jacobi(n, a, b, 1) RisingFactorial(a + 1, n)/factorial(n) >>> conjugate(jacobi(n, a, b, x)) jacobi(n, conjugate(a), conjugate(b), conjugate(x)) >>> diff(jacobi(n,a,b,x), x) (a/2 + b/2 + n/2 + 1/2)*jacobi(n - 1, a + 1, b + 1, x) See Also ======== gegenbauer, chebyshevt_root, chebyshevu, chebyshevu_root, legendre, assoc_legendre, hermite, laguerre, assoc_laguerre, sympy.polys.orthopolys.jacobi_poly, sympy.polys.orthopolys.gegenbauer_poly sympy.polys.orthopolys.chebyshevt_poly sympy.polys.orthopolys.chebyshevu_poly sympy.polys.orthopolys.hermite_poly sympy.polys.orthopolys.legendre_poly sympy.polys.orthopolys.laguerre_poly References ========== .. [1] https://en.wikipedia.org/wiki/Jacobi_polynomials .. [2] http://mathworld.wolfram.com/JacobiPolynomial.html .. [3] http://functions.wolfram.com/Polynomials/JacobiP/ """ @classmethod def eval(cls, n, a, b, x): # Simplify to other polynomials # P^{a, a}_n(x) if a == b: if a == Rational(-1, 2): return RisingFactorial(S.Half, n) / factorial(n) * chebyshevt(n, x) elif a.is_zero: return legendre(n, x) elif a == S.Half: return RisingFactorial(3*S.Half, n) / factorial(n + 1) * chebyshevu(n, x) else: return RisingFactorial(a + 1, n) / RisingFactorial(2*a + 1, n) * gegenbauer(n, a + S.Half, x) elif b == -a: # P^{a, -a}_n(x) return gamma(n + a + 1) / gamma(n + 1) * (1 + x)**(a/2) / (1 - x)**(a/2) * assoc_legendre(n, -a, x) if not n.is_Number: # Symbolic result P^{a,b}_n(x) # P^{a,b}_n(-x) ---> (-1)**n * P^{b,a}_n(-x) if x.could_extract_minus_sign(): return S.NegativeOne**n * jacobi(n, b, a, -x) # We can evaluate for some special values of x if x.is_zero: return (2**(-n) * gamma(a + n + 1) / (gamma(a + 1) * factorial(n)) * hyper([-b - n, -n], [a + 1], -1)) if x == S.One: return RisingFactorial(a + 1, n) / factorial(n) elif x is S.Infinity: if n.is_positive: # Make sure a+b+2*n \notin Z if (a + b + 2*n).is_integer: raise ValueError("Error. a + b + 2*n should not be an integer.") return RisingFactorial(a + b + n + 1, n) * S.Infinity else: # n is a given fixed integer, evaluate into polynomial return jacobi_poly(n, a, b, x) def fdiff(self, argindex=4): from sympy.concrete.summations import Sum if argindex == 1: # Diff wrt n raise ArgumentIndexError(self, argindex) elif argindex == 2: # Diff wrt a n, a, b, x = self.args k = Dummy("k") f1 = 1 / (a + b + n + k + 1) f2 = ((a + b + 2*k + 1) * RisingFactorial(b + k + 1, n - k) / ((n - k) * RisingFactorial(a + b + k + 1, n - k))) return Sum(f1 * (jacobi(n, a, b, x) + f2*jacobi(k, a, b, x)), (k, 0, n - 1)) elif argindex == 3: # Diff wrt b n, a, b, x = self.args k = Dummy("k") f1 = 1 / (a + b + n + k + 1) f2 = (-1)**(n - k) * ((a + b + 2*k + 1) * RisingFactorial(a + k + 1, n - k) / ((n - k) * RisingFactorial(a + b + k + 1, n - k))) return Sum(f1 * (jacobi(n, a, b, x) + f2*jacobi(k, a, b, x)), (k, 0, n - 1)) elif argindex == 4: # Diff wrt x n, a, b, x = self.args return S.Half * (a + b + n + 1) * jacobi(n - 1, a + 1, b + 1, x) else: raise ArgumentIndexError(self, argindex) def _eval_rewrite_as_polynomial(self, n, a, b, x, **kwargs): from sympy.concrete.summations import Sum # Make sure n \in N if n.is_negative or n.is_integer is False: raise ValueError("Error: n should be a non-negative integer.") k = Dummy("k") kern = (RisingFactorial(-n, k) * RisingFactorial(a + b + n + 1, k) * RisingFactorial(a + k + 1, n - k) / factorial(k) * ((1 - x)/2)**k) return 1 / factorial(n) * Sum(kern, (k, 0, n)) def _eval_conjugate(self): n, a, b, x = self.args return self.func(n, a.conjugate(), b.conjugate(), x.conjugate()) def jacobi_normalized(n, a, b, x): r""" Jacobi polynomial $P_n^{\left(\alpha, \beta\right)}(x)$. Explanation =========== ``jacobi_normalized(n, alpha, beta, x)`` gives the $n$th Jacobi polynomial in $x$, $P_n^{\left(\alpha, \beta\right)}(x)$. The Jacobi polynomials are orthogonal on $[-1, 1]$ with respect to the weight $\left(1-x\right)^\alpha \left(1+x\right)^\beta$. This functions returns the polynomials normilzed: .. math:: \int_{-1}^{1} P_m^{\left(\alpha, \beta\right)}(x) P_n^{\left(\alpha, \beta\right)}(x) (1-x)^{\alpha} (1+x)^{\beta} \mathrm{d}x = \delta_{m,n} Examples ======== >>> from sympy import jacobi_normalized >>> from sympy.abc import n,a,b,x >>> jacobi_normalized(n, a, b, x) jacobi(n, a, b, x)/sqrt(2**(a + b + 1)*gamma(a + n + 1)*gamma(b + n + 1)/((a + b + 2*n + 1)*factorial(n)*gamma(a + b + n + 1))) Parameters ========== n : integer degree of polynomial a : alpha value b : beta value x : symbol See Also ======== gegenbauer, chebyshevt_root, chebyshevu, chebyshevu_root, legendre, assoc_legendre, hermite, laguerre, assoc_laguerre, sympy.polys.orthopolys.jacobi_poly, sympy.polys.orthopolys.gegenbauer_poly sympy.polys.orthopolys.chebyshevt_poly sympy.polys.orthopolys.chebyshevu_poly sympy.polys.orthopolys.hermite_poly sympy.polys.orthopolys.legendre_poly sympy.polys.orthopolys.laguerre_poly References ========== .. [1] https://en.wikipedia.org/wiki/Jacobi_polynomials .. [2] http://mathworld.wolfram.com/JacobiPolynomial.html .. [3] http://functions.wolfram.com/Polynomials/JacobiP/ """ nfactor = (S(2)**(a + b + 1) * (gamma(n + a + 1) * gamma(n + b + 1)) / (2*n + a + b + 1) / (factorial(n) * gamma(n + a + b + 1))) return jacobi(n, a, b, x) / sqrt(nfactor) #---------------------------------------------------------------------------- # Gegenbauer polynomials # class gegenbauer(OrthogonalPolynomial): r""" Gegenbauer polynomial $C_n^{\left(\alpha\right)}(x)$. Explanation =========== ``gegenbauer(n, alpha, x)`` gives the $n$th Gegenbauer polynomial in $x$, $C_n^{\left(\alpha\right)}(x)$. The Gegenbauer polynomials are orthogonal on $[-1, 1]$ with respect to the weight $\left(1-x^2\right)^{\alpha-\frac{1}{2}}$. Examples ======== >>> from sympy import gegenbauer, conjugate, diff >>> from sympy.abc import n,a,x >>> gegenbauer(0, a, x) 1 >>> gegenbauer(1, a, x) 2*a*x >>> gegenbauer(2, a, x) -a + x**2*(2*a**2 + 2*a) >>> gegenbauer(3, a, x) x**3*(4*a**3/3 + 4*a**2 + 8*a/3) + x*(-2*a**2 - 2*a) >>> gegenbauer(n, a, x) gegenbauer(n, a, x) >>> gegenbauer(n, a, -x) (-1)**n*gegenbauer(n, a, x) >>> gegenbauer(n, a, 0) 2**n*sqrt(pi)*gamma(a + n/2)/(gamma(a)*gamma(1/2 - n/2)*gamma(n + 1)) >>> gegenbauer(n, a, 1) gamma(2*a + n)/(gamma(2*a)*gamma(n + 1)) >>> conjugate(gegenbauer(n, a, x)) gegenbauer(n, conjugate(a), conjugate(x)) >>> diff(gegenbauer(n, a, x), x) 2*a*gegenbauer(n - 1, a + 1, x) See Also ======== jacobi, chebyshevt_root, chebyshevu, chebyshevu_root, legendre, assoc_legendre, hermite, laguerre, assoc_laguerre, sympy.polys.orthopolys.jacobi_poly sympy.polys.orthopolys.gegenbauer_poly sympy.polys.orthopolys.chebyshevt_poly sympy.polys.orthopolys.chebyshevu_poly sympy.polys.orthopolys.hermite_poly sympy.polys.orthopolys.legendre_poly sympy.polys.orthopolys.laguerre_poly References ========== .. [1] https://en.wikipedia.org/wiki/Gegenbauer_polynomials .. [2] http://mathworld.wolfram.com/GegenbauerPolynomial.html .. [3] http://functions.wolfram.com/Polynomials/GegenbauerC3/ """ @classmethod def eval(cls, n, a, x): # For negative n the polynomials vanish # See http://functions.wolfram.com/Polynomials/GegenbauerC3/03/01/03/0012/ if n.is_negative: return S.Zero # Some special values for fixed a if a == S.Half: return legendre(n, x) elif a == S.One: return chebyshevu(n, x) elif a == S.NegativeOne: return S.Zero if not n.is_Number: # Handle this before the general sign extraction rule if x == S.NegativeOne: if (re(a) > S.Half) == True: return S.ComplexInfinity else: return (cos(S.Pi*(a+n)) * sec(S.Pi*a) * gamma(2*a+n) / (gamma(2*a) * gamma(n+1))) # Symbolic result C^a_n(x) # C^a_n(-x) ---> (-1)**n * C^a_n(x) if x.could_extract_minus_sign(): return S.NegativeOne**n * gegenbauer(n, a, -x) # We can evaluate for some special values of x if x.is_zero: return (2**n * sqrt(S.Pi) * gamma(a + S.Half*n) / (gamma((1 - n)/2) * gamma(n + 1) * gamma(a)) ) if x == S.One: return gamma(2*a + n) / (gamma(2*a) * gamma(n + 1)) elif x is S.Infinity: if n.is_positive: return RisingFactorial(a, n) * S.Infinity else: # n is a given fixed integer, evaluate into polynomial return gegenbauer_poly(n, a, x) def fdiff(self, argindex=3): from sympy.concrete.summations import Sum if argindex == 1: # Diff wrt n raise ArgumentIndexError(self, argindex) elif argindex == 2: # Diff wrt a n, a, x = self.args k = Dummy("k") factor1 = 2 * (1 + (-1)**(n - k)) * (k + a) / ((k + n + 2*a) * (n - k)) factor2 = 2*(k + 1) / ((k + 2*a) * (2*k + 2*a + 1)) + \ 2 / (k + n + 2*a) kern = factor1*gegenbauer(k, a, x) + factor2*gegenbauer(n, a, x) return Sum(kern, (k, 0, n - 1)) elif argindex == 3: # Diff wrt x n, a, x = self.args return 2*a*gegenbauer(n - 1, a + 1, x) else: raise ArgumentIndexError(self, argindex) def _eval_rewrite_as_polynomial(self, n, a, x, **kwargs): from sympy.concrete.summations import Sum k = Dummy("k") kern = ((-1)**k * RisingFactorial(a, n - k) * (2*x)**(n - 2*k) / (factorial(k) * factorial(n - 2*k))) return Sum(kern, (k, 0, floor(n/2))) def _eval_conjugate(self): n, a, x = self.args return self.func(n, a.conjugate(), x.conjugate()) #---------------------------------------------------------------------------- # Chebyshev polynomials of first and second kind # class chebyshevt(OrthogonalPolynomial): r""" Chebyshev polynomial of the first kind, $T_n(x)$. Explanation =========== ``chebyshevt(n, x)`` gives the $n$th Chebyshev polynomial (of the first kind) in $x$, $T_n(x)$. The Chebyshev polynomials of the first kind are orthogonal on $[-1, 1]$ with respect to the weight $\frac{1}{\sqrt{1-x^2}}$. Examples ======== >>> from sympy import chebyshevt, diff >>> from sympy.abc import n,x >>> chebyshevt(0, x) 1 >>> chebyshevt(1, x) x >>> chebyshevt(2, x) 2*x**2 - 1 >>> chebyshevt(n, x) chebyshevt(n, x) >>> chebyshevt(n, -x) (-1)**n*chebyshevt(n, x) >>> chebyshevt(-n, x) chebyshevt(n, x) >>> chebyshevt(n, 0) cos(pi*n/2) >>> chebyshevt(n, -1) (-1)**n >>> diff(chebyshevt(n, x), x) n*chebyshevu(n - 1, x) See Also ======== jacobi, gegenbauer, chebyshevt_root, chebyshevu, chebyshevu_root, legendre, assoc_legendre, hermite, laguerre, assoc_laguerre, sympy.polys.orthopolys.jacobi_poly sympy.polys.orthopolys.gegenbauer_poly sympy.polys.orthopolys.chebyshevt_poly sympy.polys.orthopolys.chebyshevu_poly sympy.polys.orthopolys.hermite_poly sympy.polys.orthopolys.legendre_poly sympy.polys.orthopolys.laguerre_poly References ========== .. [1] https://en.wikipedia.org/wiki/Chebyshev_polynomial .. [2] http://mathworld.wolfram.com/ChebyshevPolynomialoftheFirstKind.html .. [3] http://mathworld.wolfram.com/ChebyshevPolynomialoftheSecondKind.html .. [4] http://functions.wolfram.com/Polynomials/ChebyshevT/ .. [5] http://functions.wolfram.com/Polynomials/ChebyshevU/ """ _ortho_poly = staticmethod(chebyshevt_poly) @classmethod def eval(cls, n, x): if not n.is_Number: # Symbolic result T_n(x) # T_n(-x) ---> (-1)**n * T_n(x) if x.could_extract_minus_sign(): return S.NegativeOne**n * chebyshevt(n, -x) # T_{-n}(x) ---> T_n(x) if n.could_extract_minus_sign(): return chebyshevt(-n, x) # We can evaluate for some special values of x if x.is_zero: return cos(S.Half * S.Pi * n) if x == S.One: return S.One elif x is S.Infinity: return S.Infinity else: # n is a given fixed integer, evaluate into polynomial if n.is_negative: # T_{-n}(x) == T_n(x) return cls._eval_at_order(-n, x) else: return cls._eval_at_order(n, x) def fdiff(self, argindex=2): if argindex == 1: # Diff wrt n raise ArgumentIndexError(self, argindex) elif argindex == 2: # Diff wrt x n, x = self.args return n * chebyshevu(n - 1, x) else: raise ArgumentIndexError(self, argindex) def _eval_rewrite_as_polynomial(self, n, x, **kwargs): from sympy.concrete.summations import Sum k = Dummy("k") kern = binomial(n, 2*k) * (x**2 - 1)**k * x**(n - 2*k) return Sum(kern, (k, 0, floor(n/2))) class chebyshevu(OrthogonalPolynomial): r""" Chebyshev polynomial of the second kind, $U_n(x)$. Explanation =========== ``chebyshevu(n, x)`` gives the $n$th Chebyshev polynomial of the second kind in x, $U_n(x)$. The Chebyshev polynomials of the second kind are orthogonal on $[-1, 1]$ with respect to the weight $\sqrt{1-x^2}$. Examples ======== >>> from sympy import chebyshevu, diff >>> from sympy.abc import n,x >>> chebyshevu(0, x) 1 >>> chebyshevu(1, x) 2*x >>> chebyshevu(2, x) 4*x**2 - 1 >>> chebyshevu(n, x) chebyshevu(n, x) >>> chebyshevu(n, -x) (-1)**n*chebyshevu(n, x) >>> chebyshevu(-n, x) -chebyshevu(n - 2, x) >>> chebyshevu(n, 0) cos(pi*n/2) >>> chebyshevu(n, 1) n + 1 >>> diff(chebyshevu(n, x), x) (-x*chebyshevu(n, x) + (n + 1)*chebyshevt(n + 1, x))/(x**2 - 1) See Also ======== jacobi, gegenbauer, chebyshevt, chebyshevt_root, chebyshevu_root, legendre, assoc_legendre, hermite, laguerre, assoc_laguerre, sympy.polys.orthopolys.jacobi_poly sympy.polys.orthopolys.gegenbauer_poly sympy.polys.orthopolys.chebyshevt_poly sympy.polys.orthopolys.chebyshevu_poly sympy.polys.orthopolys.hermite_poly sympy.polys.orthopolys.legendre_poly sympy.polys.orthopolys.laguerre_poly References ========== .. [1] https://en.wikipedia.org/wiki/Chebyshev_polynomial .. [2] http://mathworld.wolfram.com/ChebyshevPolynomialoftheFirstKind.html .. [3] http://mathworld.wolfram.com/ChebyshevPolynomialoftheSecondKind.html .. [4] http://functions.wolfram.com/Polynomials/ChebyshevT/ .. [5] http://functions.wolfram.com/Polynomials/ChebyshevU/ """ _ortho_poly = staticmethod(chebyshevu_poly) @classmethod def eval(cls, n, x): if not n.is_Number: # Symbolic result U_n(x) # U_n(-x) ---> (-1)**n * U_n(x) if x.could_extract_minus_sign(): return S.NegativeOne**n * chebyshevu(n, -x) # U_{-n}(x) ---> -U_{n-2}(x) if n.could_extract_minus_sign(): if n == S.NegativeOne: # n can not be -1 here return S.Zero elif not (-n - 2).could_extract_minus_sign(): return -chebyshevu(-n - 2, x) # We can evaluate for some special values of x if x.is_zero: return cos(S.Half * S.Pi * n) if x == S.One: return S.One + n elif x is S.Infinity: return S.Infinity else: # n is a given fixed integer, evaluate into polynomial if n.is_negative: # U_{-n}(x) ---> -U_{n-2}(x) if n == S.NegativeOne: return S.Zero else: return -cls._eval_at_order(-n - 2, x) else: return cls._eval_at_order(n, x) def fdiff(self, argindex=2): if argindex == 1: # Diff wrt n raise ArgumentIndexError(self, argindex) elif argindex == 2: # Diff wrt x n, x = self.args return ((n + 1) * chebyshevt(n + 1, x) - x * chebyshevu(n, x)) / (x**2 - 1) else: raise ArgumentIndexError(self, argindex) def _eval_rewrite_as_polynomial(self, n, x, **kwargs): from sympy.concrete.summations import Sum k = Dummy("k") kern = S.NegativeOne**k * factorial( n - k) * (2*x)**(n - 2*k) / (factorial(k) * factorial(n - 2*k)) return Sum(kern, (k, 0, floor(n/2))) class chebyshevt_root(Function): r""" ``chebyshev_root(n, k)`` returns the $k$th root (indexed from zero) of the $n$th Chebyshev polynomial of the first kind; that is, if $0 \le k < n$, ``chebyshevt(n, chebyshevt_root(n, k)) == 0``. Examples ======== >>> from sympy import chebyshevt, chebyshevt_root >>> chebyshevt_root(3, 2) -sqrt(3)/2 >>> chebyshevt(3, chebyshevt_root(3, 2)) 0 See Also ======== jacobi, gegenbauer, chebyshevt, chebyshevu, chebyshevu_root, legendre, assoc_legendre, hermite, laguerre, assoc_laguerre, sympy.polys.orthopolys.jacobi_poly sympy.polys.orthopolys.gegenbauer_poly sympy.polys.orthopolys.chebyshevt_poly sympy.polys.orthopolys.chebyshevu_poly sympy.polys.orthopolys.hermite_poly sympy.polys.orthopolys.legendre_poly sympy.polys.orthopolys.laguerre_poly """ @classmethod def eval(cls, n, k): if not ((0 <= k) and (k < n)): raise ValueError("must have 0 <= k < n, " "got k = %s and n = %s" % (k, n)) return cos(S.Pi*(2*k + 1)/(2*n)) class chebyshevu_root(Function): r""" ``chebyshevu_root(n, k)`` returns the $k$th root (indexed from zero) of the $n$th Chebyshev polynomial of the second kind; that is, if $0 \le k < n$, ``chebyshevu(n, chebyshevu_root(n, k)) == 0``. Examples ======== >>> from sympy import chebyshevu, chebyshevu_root >>> chebyshevu_root(3, 2) -sqrt(2)/2 >>> chebyshevu(3, chebyshevu_root(3, 2)) 0 See Also ======== chebyshevt, chebyshevt_root, chebyshevu, legendre, assoc_legendre, hermite, laguerre, assoc_laguerre, sympy.polys.orthopolys.jacobi_poly sympy.polys.orthopolys.gegenbauer_poly sympy.polys.orthopolys.chebyshevt_poly sympy.polys.orthopolys.chebyshevu_poly sympy.polys.orthopolys.hermite_poly sympy.polys.orthopolys.legendre_poly sympy.polys.orthopolys.laguerre_poly """ @classmethod def eval(cls, n, k): if not ((0 <= k) and (k < n)): raise ValueError("must have 0 <= k < n, " "got k = %s and n = %s" % (k, n)) return cos(S.Pi*(k + 1)/(n + 1)) #---------------------------------------------------------------------------- # Legendre polynomials and Associated Legendre polynomials # class legendre(OrthogonalPolynomial): r""" ``legendre(n, x)`` gives the $n$th Legendre polynomial of $x$, $P_n(x)$ Explanation =========== The Legendre polynomials are orthogonal on $[-1, 1]$ with respect to the constant weight 1. They satisfy $P_n(1) = 1$ for all $n$; further, $P_n$ is odd for odd $n$ and even for even $n$. Examples ======== >>> from sympy import legendre, diff >>> from sympy.abc import x, n >>> legendre(0, x) 1 >>> legendre(1, x) x >>> legendre(2, x) 3*x**2/2 - 1/2 >>> legendre(n, x) legendre(n, x) >>> diff(legendre(n,x), x) n*(x*legendre(n, x) - legendre(n - 1, x))/(x**2 - 1) See Also ======== jacobi, gegenbauer, chebyshevt, chebyshevt_root, chebyshevu, chebyshevu_root, assoc_legendre, hermite, laguerre, assoc_laguerre, sympy.polys.orthopolys.jacobi_poly sympy.polys.orthopolys.gegenbauer_poly sympy.polys.orthopolys.chebyshevt_poly sympy.polys.orthopolys.chebyshevu_poly sympy.polys.orthopolys.hermite_poly sympy.polys.orthopolys.legendre_poly sympy.polys.orthopolys.laguerre_poly References ========== .. [1] https://en.wikipedia.org/wiki/Legendre_polynomial .. [2] http://mathworld.wolfram.com/LegendrePolynomial.html .. [3] http://functions.wolfram.com/Polynomials/LegendreP/ .. [4] http://functions.wolfram.com/Polynomials/LegendreP2/ """ _ortho_poly = staticmethod(legendre_poly) @classmethod def eval(cls, n, x): if not n.is_Number: # Symbolic result L_n(x) # L_n(-x) ---> (-1)**n * L_n(x) if x.could_extract_minus_sign(): return S.NegativeOne**n * legendre(n, -x) # L_{-n}(x) ---> L_{n-1}(x) if n.could_extract_minus_sign() and not(-n - 1).could_extract_minus_sign(): return legendre(-n - S.One, x) # We can evaluate for some special values of x if x.is_zero: return sqrt(S.Pi)/(gamma(S.Half - n/2)*gamma(S.One + n/2)) elif x == S.One: return S.One elif x is S.Infinity: return S.Infinity else: # n is a given fixed integer, evaluate into polynomial; # L_{-n}(x) ---> L_{n-1}(x) if n.is_negative: n = -n - S.One return cls._eval_at_order(n, x) def fdiff(self, argindex=2): if argindex == 1: # Diff wrt n raise ArgumentIndexError(self, argindex) elif argindex == 2: # Diff wrt x # Find better formula, this is unsuitable for x = +/-1 # http://www.autodiff.org/ad16/Oral/Buecker_Legendre.pdf says # at x = 1: # n*(n + 1)/2 , m = 0 # oo , m = 1 # -(n-1)*n*(n+1)*(n+2)/4 , m = 2 # 0 , m = 3, 4, ..., n # # at x = -1 # (-1)**(n+1)*n*(n + 1)/2 , m = 0 # (-1)**n*oo , m = 1 # (-1)**n*(n-1)*n*(n+1)*(n+2)/4 , m = 2 # 0 , m = 3, 4, ..., n n, x = self.args return n/(x**2 - 1)*(x*legendre(n, x) - legendre(n - 1, x)) else: raise ArgumentIndexError(self, argindex) def _eval_rewrite_as_polynomial(self, n, x, **kwargs): from sympy.concrete.summations import Sum k = Dummy("k") kern = S.NegativeOne**k*binomial(n, k)**2*((1 + x)/2)**(n - k)*((1 - x)/2)**k return Sum(kern, (k, 0, n)) class assoc_legendre(Function): r""" ``assoc_legendre(n, m, x)`` gives $P_n^m(x)$, where $n$ and $m$ are the degree and order or an expression which is related to the nth order Legendre polynomial, $P_n(x)$ in the following manner: .. math:: P_n^m(x) = (-1)^m (1 - x^2)^{\frac{m}{2}} \frac{\mathrm{d}^m P_n(x)}{\mathrm{d} x^m} Explanation =========== Associated Legendre polynomials are orthogonal on $[-1, 1]$ with: - weight $= 1$ for the same $m$ and different $n$. - weight $= \frac{1}{1-x^2}$ for the same $n$ and different $m$. Examples ======== >>> from sympy import assoc_legendre >>> from sympy.abc import x, m, n >>> assoc_legendre(0,0, x) 1 >>> assoc_legendre(1,0, x) x >>> assoc_legendre(1,1, x) -sqrt(1 - x**2) >>> assoc_legendre(n,m,x) assoc_legendre(n, m, x) See Also ======== jacobi, gegenbauer, chebyshevt, chebyshevt_root, chebyshevu, chebyshevu_root, legendre, hermite, laguerre, assoc_laguerre, sympy.polys.orthopolys.jacobi_poly sympy.polys.orthopolys.gegenbauer_poly sympy.polys.orthopolys.chebyshevt_poly sympy.polys.orthopolys.chebyshevu_poly sympy.polys.orthopolys.hermite_poly sympy.polys.orthopolys.legendre_poly sympy.polys.orthopolys.laguerre_poly References ========== .. [1] https://en.wikipedia.org/wiki/Associated_Legendre_polynomials .. [2] http://mathworld.wolfram.com/LegendrePolynomial.html .. [3] http://functions.wolfram.com/Polynomials/LegendreP/ .. [4] http://functions.wolfram.com/Polynomials/LegendreP2/ """ @classmethod def _eval_at_order(cls, n, m): P = legendre_poly(n, _x, polys=True).diff((_x, m)) return S.NegativeOne**m * (1 - _x**2)**Rational(m, 2) * P.as_expr() @classmethod def eval(cls, n, m, x): if m.could_extract_minus_sign(): # P^{-m}_n ---> F * P^m_n return S.NegativeOne**(-m) * (factorial(m + n)/factorial(n - m)) * assoc_legendre(n, -m, x) if m == 0: # P^0_n ---> L_n return legendre(n, x) if x == 0: return 2**m*sqrt(S.Pi) / (gamma((1 - m - n)/2)*gamma(1 - (m - n)/2)) if n.is_Number and m.is_Number and n.is_integer and m.is_integer: if n.is_negative: raise ValueError("%s : 1st index must be nonnegative integer (got %r)" % (cls, n)) if abs(m) > n: raise ValueError("%s : abs('2nd index') must be <= '1st index' (got %r, %r)" % (cls, n, m)) return cls._eval_at_order(int(n), abs(int(m))).subs(_x, x) def fdiff(self, argindex=3): if argindex == 1: # Diff wrt n raise ArgumentIndexError(self, argindex) elif argindex == 2: # Diff wrt m raise ArgumentIndexError(self, argindex) elif argindex == 3: # Diff wrt x # Find better formula, this is unsuitable for x = 1 n, m, x = self.args return 1/(x**2 - 1)*(x*n*assoc_legendre(n, m, x) - (m + n)*assoc_legendre(n - 1, m, x)) else: raise ArgumentIndexError(self, argindex) def _eval_rewrite_as_polynomial(self, n, m, x, **kwargs): from sympy.concrete.summations import Sum k = Dummy("k") kern = factorial(2*n - 2*k)/(2**n*factorial(n - k)*factorial( k)*factorial(n - 2*k - m))*S.NegativeOne**k*x**(n - m - 2*k) return (1 - x**2)**(m/2) * Sum(kern, (k, 0, floor((n - m)*S.Half))) def _eval_conjugate(self): n, m, x = self.args return self.func(n, m.conjugate(), x.conjugate()) #---------------------------------------------------------------------------- # Hermite polynomials # class hermite(OrthogonalPolynomial): r""" ``hermite(n, x)`` gives the $n$th Hermite polynomial in $x$, $H_n(x)$ Explanation =========== The Hermite polynomials are orthogonal on $(-\infty, \infty)$ with respect to the weight $\exp\left(-x^2\right)$. Examples ======== >>> from sympy import hermite, diff >>> from sympy.abc import x, n >>> hermite(0, x) 1 >>> hermite(1, x) 2*x >>> hermite(2, x) 4*x**2 - 2 >>> hermite(n, x) hermite(n, x) >>> diff(hermite(n,x), x) 2*n*hermite(n - 1, x) >>> hermite(n, -x) (-1)**n*hermite(n, x) See Also ======== jacobi, gegenbauer, chebyshevt, chebyshevt_root, chebyshevu, chebyshevu_root, legendre, assoc_legendre, laguerre, assoc_laguerre, sympy.polys.orthopolys.jacobi_poly sympy.polys.orthopolys.gegenbauer_poly sympy.polys.orthopolys.chebyshevt_poly sympy.polys.orthopolys.chebyshevu_poly sympy.polys.orthopolys.hermite_poly sympy.polys.orthopolys.legendre_poly sympy.polys.orthopolys.laguerre_poly References ========== .. [1] https://en.wikipedia.org/wiki/Hermite_polynomial .. [2] http://mathworld.wolfram.com/HermitePolynomial.html .. [3] http://functions.wolfram.com/Polynomials/HermiteH/ """ _ortho_poly = staticmethod(hermite_poly) @classmethod def eval(cls, n, x): if not n.is_Number: # Symbolic result H_n(x) # H_n(-x) ---> (-1)**n * H_n(x) if x.could_extract_minus_sign(): return S.NegativeOne**n * hermite(n, -x) # We can evaluate for some special values of x if x.is_zero: return 2**n * sqrt(S.Pi) / gamma((S.One - n)/2) elif x is S.Infinity: return S.Infinity else: # n is a given fixed integer, evaluate into polynomial if n.is_negative: raise ValueError( "The index n must be nonnegative integer (got %r)" % n) else: return cls._eval_at_order(n, x) def fdiff(self, argindex=2): if argindex == 1: # Diff wrt n raise ArgumentIndexError(self, argindex) elif argindex == 2: # Diff wrt x n, x = self.args return 2*n*hermite(n - 1, x) else: raise ArgumentIndexError(self, argindex) def _eval_rewrite_as_polynomial(self, n, x, **kwargs): from sympy.concrete.summations import Sum k = Dummy("k") kern = S.NegativeOne**k / (factorial(k)*factorial(n - 2*k)) * (2*x)**(n - 2*k) return factorial(n)*Sum(kern, (k, 0, floor(n/2))) #---------------------------------------------------------------------------- # Laguerre polynomials # class laguerre(OrthogonalPolynomial): r""" Returns the $n$th Laguerre polynomial in $x$, $L_n(x)$. Examples ======== >>> from sympy import laguerre, diff >>> from sympy.abc import x, n >>> laguerre(0, x) 1 >>> laguerre(1, x) 1 - x >>> laguerre(2, x) x**2/2 - 2*x + 1 >>> laguerre(3, x) -x**3/6 + 3*x**2/2 - 3*x + 1 >>> laguerre(n, x) laguerre(n, x) >>> diff(laguerre(n, x), x) -assoc_laguerre(n - 1, 1, x) Parameters ========== n : int Degree of Laguerre polynomial. Must be `n \ge 0`. See Also ======== jacobi, gegenbauer, chebyshevt, chebyshevt_root, chebyshevu, chebyshevu_root, legendre, assoc_legendre, hermite, assoc_laguerre, sympy.polys.orthopolys.jacobi_poly sympy.polys.orthopolys.gegenbauer_poly sympy.polys.orthopolys.chebyshevt_poly sympy.polys.orthopolys.chebyshevu_poly sympy.polys.orthopolys.hermite_poly sympy.polys.orthopolys.legendre_poly sympy.polys.orthopolys.laguerre_poly References ========== .. [1] https://en.wikipedia.org/wiki/Laguerre_polynomial .. [2] http://mathworld.wolfram.com/LaguerrePolynomial.html .. [3] http://functions.wolfram.com/Polynomials/LaguerreL/ .. [4] http://functions.wolfram.com/Polynomials/LaguerreL3/ """ _ortho_poly = staticmethod(laguerre_poly) @classmethod def eval(cls, n, x): if n.is_integer is False: raise ValueError("Error: n should be an integer.") if not n.is_Number: # Symbolic result L_n(x) # L_{n}(-x) ---> exp(-x) * L_{-n-1}(x) # L_{-n}(x) ---> exp(x) * L_{n-1}(-x) if n.could_extract_minus_sign() and not(-n - 1).could_extract_minus_sign(): return exp(x)*laguerre(-n - 1, -x) # We can evaluate for some special values of x if x.is_zero: return S.One elif x is S.NegativeInfinity: return S.Infinity elif x is S.Infinity: return S.NegativeOne**n * S.Infinity else: if n.is_negative: return exp(x)*laguerre(-n - 1, -x) else: return cls._eval_at_order(n, x) def fdiff(self, argindex=2): if argindex == 1: # Diff wrt n raise ArgumentIndexError(self, argindex) elif argindex == 2: # Diff wrt x n, x = self.args return -assoc_laguerre(n - 1, 1, x) else: raise ArgumentIndexError(self, argindex) def _eval_rewrite_as_polynomial(self, n, x, **kwargs): from sympy.concrete.summations import Sum # Make sure n \in N_0 if n.is_negative: return exp(x) * self._eval_rewrite_as_polynomial(-n - 1, -x, **kwargs) if n.is_integer is False: raise ValueError("Error: n should be an integer.") k = Dummy("k") kern = RisingFactorial(-n, k) / factorial(k)**2 * x**k return Sum(kern, (k, 0, n)) class assoc_laguerre(OrthogonalPolynomial): r""" Returns the $n$th generalized Laguerre polynomial in $x$, $L_n(x)$. Examples ======== >>> from sympy import assoc_laguerre, diff >>> from sympy.abc import x, n, a >>> assoc_laguerre(0, a, x) 1 >>> assoc_laguerre(1, a, x) a - x + 1 >>> assoc_laguerre(2, a, x) a**2/2 + 3*a/2 + x**2/2 + x*(-a - 2) + 1 >>> assoc_laguerre(3, a, x) a**3/6 + a**2 + 11*a/6 - x**3/6 + x**2*(a/2 + 3/2) + x*(-a**2/2 - 5*a/2 - 3) + 1 >>> assoc_laguerre(n, a, 0) binomial(a + n, a) >>> assoc_laguerre(n, a, x) assoc_laguerre(n, a, x) >>> assoc_laguerre(n, 0, x) laguerre(n, x) >>> diff(assoc_laguerre(n, a, x), x) -assoc_laguerre(n - 1, a + 1, x) >>> diff(assoc_laguerre(n, a, x), a) Sum(assoc_laguerre(_k, a, x)/(-a + n), (_k, 0, n - 1)) Parameters ========== n : int Degree of Laguerre polynomial. Must be `n \ge 0`. alpha : Expr Arbitrary expression. For ``alpha=0`` regular Laguerre polynomials will be generated. See Also ======== jacobi, gegenbauer, chebyshevt, chebyshevt_root, chebyshevu, chebyshevu_root, legendre, assoc_legendre, hermite, laguerre, sympy.polys.orthopolys.jacobi_poly sympy.polys.orthopolys.gegenbauer_poly sympy.polys.orthopolys.chebyshevt_poly sympy.polys.orthopolys.chebyshevu_poly sympy.polys.orthopolys.hermite_poly sympy.polys.orthopolys.legendre_poly sympy.polys.orthopolys.laguerre_poly References ========== .. [1] https://en.wikipedia.org/wiki/Laguerre_polynomial#Generalized_Laguerre_polynomials .. [2] http://mathworld.wolfram.com/AssociatedLaguerrePolynomial.html .. [3] http://functions.wolfram.com/Polynomials/LaguerreL/ .. [4] http://functions.wolfram.com/Polynomials/LaguerreL3/ """ @classmethod def eval(cls, n, alpha, x): # L_{n}^{0}(x) ---> L_{n}(x) if alpha.is_zero: return laguerre(n, x) if not n.is_Number: # We can evaluate for some special values of x if x.is_zero: return binomial(n + alpha, alpha) elif x is S.Infinity and n > 0: return S.NegativeOne**n * S.Infinity elif x is S.NegativeInfinity and n > 0: return S.Infinity else: # n is a given fixed integer, evaluate into polynomial if n.is_negative: raise ValueError( "The index n must be nonnegative integer (got %r)" % n) else: return laguerre_poly(n, x, alpha) def fdiff(self, argindex=3): from sympy.concrete.summations import Sum if argindex == 1: # Diff wrt n raise ArgumentIndexError(self, argindex) elif argindex == 2: # Diff wrt alpha n, alpha, x = self.args k = Dummy("k") return Sum(assoc_laguerre(k, alpha, x) / (n - alpha), (k, 0, n - 1)) elif argindex == 3: # Diff wrt x n, alpha, x = self.args return -assoc_laguerre(n - 1, alpha + 1, x) else: raise ArgumentIndexError(self, argindex) def _eval_rewrite_as_polynomial(self, n, alpha, x, **kwargs): from sympy.concrete.summations import Sum # Make sure n \in N_0 if n.is_negative or n.is_integer is False: raise ValueError("Error: n should be a non-negative integer.") k = Dummy("k") kern = RisingFactorial( -n, k) / (gamma(k + alpha + 1) * factorial(k)) * x**k return gamma(n + alpha + 1) / factorial(n) * Sum(kern, (k, 0, n)) def _eval_conjugate(self): n, alpha, x = self.args return self.func(n, alpha.conjugate(), x.conjugate())
5ba76ce32e3c5e3d7a77e3562a46fc58145d82862eb4b78a807d6d47acdf5e6f
from sympy.assumptions.refine import refine from sympy.calculus.accumulationbounds import AccumBounds from sympy.concrete.products import Product from sympy.concrete.summations import Sum from sympy.core.function import expand_log from sympy.core.numbers import (E, Float, I, Rational, nan, oo, pi, zoo) from sympy.core.power import Pow from sympy.core.singleton import S from sympy.core.symbol import (Symbol, symbols) from sympy.functions.elementary.complexes import (adjoint, conjugate, re, sign, transpose) from sympy.functions.elementary.exponential import (LambertW, exp, exp_polar, log) from sympy.functions.elementary.hyperbolic import (cosh, sinh, tanh) from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import (cos, sin, tan) from sympy.matrices.expressions.matexpr import MatrixSymbol from sympy.polys.polytools import gcd from sympy.series.order import O from sympy.simplify.simplify import simplify from sympy.core.parameters import global_parameters from sympy.functions.elementary.exponential import match_real_imag from sympy.abc import x, y, z from sympy.core.expr import unchanged from sympy.core.function import ArgumentIndexError from sympy.testing.pytest import raises, XFAIL, _both_exp_pow @_both_exp_pow def test_exp_values(): if global_parameters.exp_is_pow: assert type(exp(x)) is Pow else: assert type(exp(x)) is exp k = Symbol('k', integer=True) assert exp(nan) is nan assert exp(oo) is oo assert exp(-oo) == 0 assert exp(0) == 1 assert exp(1) == E assert exp(-1 + x).as_base_exp() == (S.Exp1, x - 1) assert exp(1 + x).as_base_exp() == (S.Exp1, x + 1) assert exp(pi*I/2) == I assert exp(pi*I) == -1 assert exp(pi*I*Rational(3, 2)) == -I assert exp(2*pi*I) == 1 assert refine(exp(pi*I*2*k)) == 1 assert refine(exp(pi*I*2*(k + S.Half))) == -1 assert refine(exp(pi*I*2*(k + Rational(1, 4)))) == I assert refine(exp(pi*I*2*(k + Rational(3, 4)))) == -I assert exp(log(x)) == x assert exp(2*log(x)) == x**2 assert exp(pi*log(x)) == x**pi assert exp(17*log(x) + E*log(y)) == x**17 * y**E assert exp(x*log(x)) != x**x assert exp(sin(x)*log(x)) != x assert exp(3*log(x) + oo*x) == exp(oo*x) * x**3 assert exp(4*log(x)*log(y) + 3*log(x)) == x**3 * exp(4*log(x)*log(y)) assert exp(-oo, evaluate=False).is_finite is True assert exp(oo, evaluate=False).is_finite is False @_both_exp_pow def test_exp_period(): assert exp(I*pi*Rational(9, 4)) == exp(I*pi/4) assert exp(I*pi*Rational(46, 18)) == exp(I*pi*Rational(5, 9)) assert exp(I*pi*Rational(25, 7)) == exp(I*pi*Rational(-3, 7)) assert exp(I*pi*Rational(-19, 3)) == exp(-I*pi/3) assert exp(I*pi*Rational(37, 8)) - exp(I*pi*Rational(-11, 8)) == 0 assert exp(I*pi*Rational(-5, 3)) / exp(I*pi*Rational(11, 5)) * exp(I*pi*Rational(148, 15)) == 1 assert exp(2 - I*pi*Rational(17, 5)) == exp(2 + I*pi*Rational(3, 5)) assert exp(log(3) + I*pi*Rational(29, 9)) == 3 * exp(I*pi*Rational(-7, 9)) n = Symbol('n', integer=True) e = Symbol('e', even=True) assert exp(e*I*pi) == 1 assert exp((e + 1)*I*pi) == -1 assert exp((1 + 4*n)*I*pi/2) == I assert exp((-1 + 4*n)*I*pi/2) == -I @_both_exp_pow def test_exp_log(): x = Symbol("x", real=True) assert log(exp(x)) == x assert exp(log(x)) == x if not global_parameters.exp_is_pow: assert log(x).inverse() == exp assert exp(x).inverse() == log y = Symbol("y", polar=True) assert log(exp_polar(z)) == z assert exp(log(y)) == y @_both_exp_pow def test_exp_expand(): e = exp(log(Rational(2))*(1 + x) - log(Rational(2))*x) assert e.expand() == 2 assert exp(x + y) != exp(x)*exp(y) assert exp(x + y).expand() == exp(x)*exp(y) @_both_exp_pow def test_exp__as_base_exp(): assert exp(x).as_base_exp() == (E, x) assert exp(2*x).as_base_exp() == (E, 2*x) assert exp(x*y).as_base_exp() == (E, x*y) assert exp(-x).as_base_exp() == (E, -x) # Pow( *expr.as_base_exp() ) == expr invariant should hold assert E**x == exp(x) assert E**(2*x) == exp(2*x) assert E**(x*y) == exp(x*y) assert exp(x).base is S.Exp1 assert exp(x).exp == x @_both_exp_pow def test_exp_infinity(): assert exp(I*y) != nan assert refine(exp(I*oo)) is nan assert refine(exp(-I*oo)) is nan assert exp(y*I*oo) != nan assert exp(zoo) is nan x = Symbol('x', extended_real=True, finite=False) assert exp(x).is_complex is None @_both_exp_pow def test_exp_subs(): x = Symbol('x') e = (exp(3*log(x), evaluate=False)) # evaluates to x**3 assert e.subs(x**3, y**3) == e assert e.subs(x**2, 5) == e assert (x**3).subs(x**2, y) != y**Rational(3, 2) assert exp(exp(x) + exp(x**2)).subs(exp(exp(x)), y) == y * exp(exp(x**2)) assert exp(x).subs(E, y) == y**x x = symbols('x', real=True) assert exp(5*x).subs(exp(7*x), y) == y**Rational(5, 7) assert exp(2*x + 7).subs(exp(3*x), y) == y**Rational(2, 3) * exp(7) x = symbols('x', positive=True) assert exp(3*log(x)).subs(x**2, y) == y**Rational(3, 2) # differentiate between E and exp assert exp(exp(x + E)).subs(exp, 3) == 3**(3**(x + E)) assert exp(exp(x + E)).subs(exp, sin) == sin(sin(x + E)) assert exp(exp(x + E)).subs(E, 3) == 3**(3**(x + 3)) assert exp(3).subs(E, sin) == sin(3) def test_exp_adjoint(): assert adjoint(exp(x)) == exp(adjoint(x)) def test_exp_conjugate(): assert conjugate(exp(x)) == exp(conjugate(x)) @_both_exp_pow def test_exp_transpose(): assert transpose(exp(x)) == exp(transpose(x)) @_both_exp_pow def test_exp_rewrite(): assert exp(x).rewrite(sin) == sinh(x) + cosh(x) assert exp(x*I).rewrite(cos) == cos(x) + I*sin(x) assert exp(1).rewrite(cos) == sinh(1) + cosh(1) assert exp(1).rewrite(sin) == sinh(1) + cosh(1) assert exp(1).rewrite(sin) == sinh(1) + cosh(1) assert exp(x).rewrite(tanh) == (1 + tanh(x/2))/(1 - tanh(x/2)) assert exp(pi*I/4).rewrite(sqrt) == sqrt(2)/2 + sqrt(2)*I/2 assert exp(pi*I/3).rewrite(sqrt) == S.Half + sqrt(3)*I/2 if not global_parameters.exp_is_pow: assert exp(x*log(y)).rewrite(Pow) == y**x assert exp(log(x)*log(y)).rewrite(Pow) in [x**log(y), y**log(x)] assert exp(log(log(x))*y).rewrite(Pow) == log(x)**y n = Symbol('n', integer=True) assert Sum((exp(pi*I/2)/2)**n, (n, 0, oo)).rewrite(sqrt).doit() == Rational(4, 5) + I*2/5 assert Sum((exp(pi*I/4)/2)**n, (n, 0, oo)).rewrite(sqrt).doit() == 1/(1 - sqrt(2)*(1 + I)/4) assert (Sum((exp(pi*I/3)/2)**n, (n, 0, oo)).rewrite(sqrt).doit().cancel() == 4*I/(sqrt(3) + 3*I)) @_both_exp_pow def test_exp_leading_term(): assert exp(x).as_leading_term(x) == 1 assert exp(2 + x).as_leading_term(x) == exp(2) assert exp((2*x + 3) / (x+1)).as_leading_term(x) == exp(3) # The following tests are commented, since now SymPy returns the # original function when the leading term in the series expansion does # not exist. # raises(NotImplementedError, lambda: exp(1/x).as_leading_term(x)) # raises(NotImplementedError, lambda: exp((x + 1) / x**2).as_leading_term(x)) # raises(NotImplementedError, lambda: exp(x + 1/x).as_leading_term(x)) @_both_exp_pow def test_exp_taylor_term(): x = symbols('x') assert exp(x).taylor_term(1, x) == x assert exp(x).taylor_term(3, x) == x**3/6 assert exp(x).taylor_term(4, x) == x**4/24 assert exp(x).taylor_term(-1, x) is S.Zero def test_exp_MatrixSymbol(): A = MatrixSymbol("A", 2, 2) assert exp(A).has(exp) def test_exp_fdiff(): x = Symbol('x') raises(ArgumentIndexError, lambda: exp(x).fdiff(2)) def test_log_values(): assert log(nan) is nan assert log(oo) is oo assert log(-oo) is oo assert log(zoo) is zoo assert log(-zoo) is zoo assert log(0) is zoo assert log(1) == 0 assert log(-1) == I*pi assert log(E) == 1 assert log(-E).expand() == 1 + I*pi assert unchanged(log, pi) assert log(-pi).expand() == log(pi) + I*pi assert unchanged(log, 17) assert log(-17) == log(17) + I*pi assert log(I) == I*pi/2 assert log(-I) == -I*pi/2 assert log(17*I) == I*pi/2 + log(17) assert log(-17*I).expand() == -I*pi/2 + log(17) assert log(oo*I) is oo assert log(-oo*I) is oo assert log(0, 2) is zoo assert log(0, 5) is zoo assert exp(-log(3))**(-1) == 3 assert log(S.Half) == -log(2) assert log(2*3).func is log assert log(2*3**2).func is log def test_match_real_imag(): x, y = symbols('x,y', real=True) i = Symbol('i', imaginary=True) assert match_real_imag(S.One) == (1, 0) assert match_real_imag(I) == (0, 1) assert match_real_imag(3 - 5*I) == (3, -5) assert match_real_imag(-sqrt(3) + S.Half*I) == (-sqrt(3), S.Half) assert match_real_imag(x + y*I) == (x, y) assert match_real_imag(x*I + y*I) == (0, x + y) assert match_real_imag((x + y)*I) == (0, x + y) assert match_real_imag(Rational(-2, 3)*i*I) == (None, None) assert match_real_imag(1 - 2*i) == (None, None) assert match_real_imag(sqrt(2)*(3 - 5*I)) == (None, None) def test_log_exact(): # check for pi/2, pi/3, pi/4, pi/6, pi/8, pi/12; pi/5, pi/10: for n in range(-23, 24): if gcd(n, 24) != 1: assert log(exp(n*I*pi/24).rewrite(sqrt)) == n*I*pi/24 for n in range(-9, 10): assert log(exp(n*I*pi/10).rewrite(sqrt)) == n*I*pi/10 assert log(S.Half - I*sqrt(3)/2) == -I*pi/3 assert log(Rational(-1, 2) + I*sqrt(3)/2) == I*pi*Rational(2, 3) assert log(-sqrt(2)/2 - I*sqrt(2)/2) == -I*pi*Rational(3, 4) assert log(-sqrt(3)/2 - I*S.Half) == -I*pi*Rational(5, 6) assert log(Rational(-1, 4) + sqrt(5)/4 - I*sqrt(sqrt(5)/8 + Rational(5, 8))) == -I*pi*Rational(2, 5) assert log(sqrt(Rational(5, 8) - sqrt(5)/8) + I*(Rational(1, 4) + sqrt(5)/4)) == I*pi*Rational(3, 10) assert log(-sqrt(sqrt(2)/4 + S.Half) + I*sqrt(S.Half - sqrt(2)/4)) == I*pi*Rational(7, 8) assert log(-sqrt(6)/4 - sqrt(2)/4 + I*(-sqrt(6)/4 + sqrt(2)/4)) == -I*pi*Rational(11, 12) assert log(-1 + I*sqrt(3)) == log(2) + I*pi*Rational(2, 3) assert log(5 + 5*I) == log(5*sqrt(2)) + I*pi/4 assert log(sqrt(-12)) == log(2*sqrt(3)) + I*pi/2 assert log(-sqrt(6) + sqrt(2) - I*sqrt(6) - I*sqrt(2)) == log(4) - I*pi*Rational(7, 12) assert log(-sqrt(6-3*sqrt(2)) - I*sqrt(6+3*sqrt(2))) == log(2*sqrt(3)) - I*pi*Rational(5, 8) assert log(1 + I*sqrt(2-sqrt(2))/sqrt(2+sqrt(2))) == log(2/sqrt(sqrt(2) + 2)) + I*pi/8 assert log(cos(pi*Rational(7, 12)) + I*sin(pi*Rational(7, 12))) == I*pi*Rational(7, 12) assert log(cos(pi*Rational(6, 5)) + I*sin(pi*Rational(6, 5))) == I*pi*Rational(-4, 5) assert log(5*(1 + I)/sqrt(2)) == log(5) + I*pi/4 assert log(sqrt(2)*(-sqrt(3) + 1 - sqrt(3)*I - I)) == log(4) - I*pi*Rational(7, 12) assert log(-sqrt(2)*(1 - I*sqrt(3))) == log(2*sqrt(2)) + I*pi*Rational(2, 3) assert log(sqrt(3)*I*(-sqrt(6 - 3*sqrt(2)) - I*sqrt(3*sqrt(2) + 6))) == log(6) - I*pi/8 zero = (1 + sqrt(2))**2 - 3 - 2*sqrt(2) assert log(zero - I*sqrt(3)) == log(sqrt(3)) - I*pi/2 assert unchanged(log, zero + I*zero) or log(zero + zero*I) is zoo # bail quickly if no obvious simplification is possible: assert unchanged(log, (sqrt(2)-1/sqrt(sqrt(3)+I))**1000) # beware of non-real coefficients assert unchanged(log, sqrt(2-sqrt(5))*(1 + I)) def test_log_base(): assert log(1, 2) == 0 assert log(2, 2) == 1 assert log(3, 2) == log(3)/log(2) assert log(6, 2) == 1 + log(3)/log(2) assert log(6, 3) == 1 + log(2)/log(3) assert log(2**3, 2) == 3 assert log(3**3, 3) == 3 assert log(5, 1) is zoo assert log(1, 1) is nan assert log(Rational(2, 3), 10) == log(Rational(2, 3))/log(10) assert log(Rational(2, 3), Rational(1, 3)) == -log(2)/log(3) + 1 assert log(Rational(2, 3), Rational(2, 5)) == \ log(Rational(2, 3))/log(Rational(2, 5)) # issue 17148 assert log(Rational(8, 3), 2) == -log(3)/log(2) + 3 def test_log_symbolic(): assert log(x, exp(1)) == log(x) assert log(exp(x)) != x assert log(x, exp(1)) == log(x) assert log(x*y) != log(x) + log(y) assert log(x/y).expand() != log(x) - log(y) assert log(x/y).expand(force=True) == log(x) - log(y) assert log(x**y).expand() != y*log(x) assert log(x**y).expand(force=True) == y*log(x) assert log(x, 2) == log(x)/log(2) assert log(E, 2) == 1/log(2) p, q = symbols('p,q', positive=True) r = Symbol('r', real=True) assert log(p**2) != 2*log(p) assert log(p**2).expand() == 2*log(p) assert log(x**2).expand() != 2*log(x) assert log(p**q) != q*log(p) assert log(exp(p)) == p assert log(p*q) != log(p) + log(q) assert log(p*q).expand() == log(p) + log(q) assert log(-sqrt(3)) == log(sqrt(3)) + I*pi assert log(-exp(p)) != p + I*pi assert log(-exp(x)).expand() != x + I*pi assert log(-exp(r)).expand() == r + I*pi assert log(x**y) != y*log(x) assert (log(x**-5)**-1).expand() != -1/log(x)/5 assert (log(p**-5)**-1).expand() == -1/log(p)/5 assert log(-x).func is log and log(-x).args[0] == -x assert log(-p).func is log and log(-p).args[0] == -p def test_log_exp(): assert log(exp(4*I*pi)) == 0 # exp evaluates assert log(exp(-5*I*pi)) == I*pi # exp evaluates assert log(exp(I*pi*Rational(19, 4))) == I*pi*Rational(3, 4) assert log(exp(I*pi*Rational(25, 7))) == I*pi*Rational(-3, 7) assert log(exp(-5*I)) == -5*I + 2*I*pi @_both_exp_pow def test_exp_assumptions(): r = Symbol('r', real=True) i = Symbol('i', imaginary=True) for e in exp, exp_polar: assert e(x).is_real is None assert e(x).is_imaginary is None assert e(i).is_real is None assert e(i).is_imaginary is None assert e(r).is_real is True assert e(r).is_imaginary is False assert e(re(x)).is_extended_real is True assert e(re(x)).is_imaginary is False assert Pow(E, I*pi, evaluate=False).is_imaginary == False assert Pow(E, 2*I*pi, evaluate=False).is_imaginary == False assert Pow(E, I*pi/2, evaluate=False).is_imaginary == True assert Pow(E, I*pi/3, evaluate=False).is_imaginary is None assert exp(0, evaluate=False).is_algebraic a = Symbol('a', algebraic=True) an = Symbol('an', algebraic=True, nonzero=True) r = Symbol('r', rational=True) rn = Symbol('rn', rational=True, nonzero=True) assert exp(a).is_algebraic is None assert exp(an).is_algebraic is False assert exp(pi*r).is_algebraic is None assert exp(pi*rn).is_algebraic is False assert exp(0, evaluate=False).is_algebraic is True assert exp(I*pi/3, evaluate=False).is_algebraic is True assert exp(I*pi*r, evaluate=False).is_algebraic is True @_both_exp_pow def test_exp_AccumBounds(): assert exp(AccumBounds(1, 2)) == AccumBounds(E, E**2) def test_log_assumptions(): p = symbols('p', positive=True) n = symbols('n', negative=True) z = symbols('z', zero=True) x = symbols('x', infinite=True, extended_positive=True) assert log(z).is_positive is False assert log(x).is_extended_positive is True assert log(2) > 0 assert log(1, evaluate=False).is_zero assert log(1 + z).is_zero assert log(p).is_zero is None assert log(n).is_zero is False assert log(0.5).is_negative is True assert log(exp(p) + 1).is_positive assert log(1, evaluate=False).is_algebraic assert log(42, evaluate=False).is_algebraic is False assert log(1 + z).is_rational def test_log_hashing(): assert x != log(log(x)) assert hash(x) != hash(log(log(x))) assert log(x) != log(log(log(x))) e = 1/log(log(x) + log(log(x))) assert e.base.func is log e = 1/log(log(x) + log(log(log(x)))) assert e.base.func is log e = log(log(x)) assert e.func is log assert x.func is not log assert hash(log(log(x))) != hash(x) assert e != x def test_log_sign(): assert sign(log(2)) == 1 def test_log_expand_complex(): assert log(1 + I).expand(complex=True) == log(2)/2 + I*pi/4 assert log(1 - sqrt(2)).expand(complex=True) == log(sqrt(2) - 1) + I*pi def test_log_apply_evalf(): value = (log(3)/log(2) - 1).evalf() assert value.epsilon_eq(Float("0.58496250072115618145373")) def test_log_nseries(): assert log(x - 1)._eval_nseries(x, 4, None, I) == I*pi - x - x**2/2 - x**3/3 + O(x**4) assert log(x - 1)._eval_nseries(x, 4, None, -I) == -I*pi - x - x**2/2 - x**3/3 + O(x**4) assert log(I*x + I*x**3 - 1)._eval_nseries(x, 3, None, 1) == I*pi - I*x + x**2/2 + O(x**3) assert log(I*x + I*x**3 - 1)._eval_nseries(x, 3, None, -1) == -I*pi - I*x + x**2/2 + O(x**3) assert log(I*x**2 + I*x**3 - 1)._eval_nseries(x, 3, None, 1) == I*pi - I*x**2 + O(x**3) assert log(I*x**2 + I*x**3 - 1)._eval_nseries(x, 3, None, -1) == I*pi - I*x**2 + O(x**3) def test_log_expand(): w = Symbol("w", positive=True) e = log(w**(log(5)/log(3))) assert e.expand() == log(5)/log(3) * log(w) x, y, z = symbols('x,y,z', positive=True) assert log(x*(y + z)).expand(mul=False) == log(x) + log(y + z) assert log(log(x**2)*log(y*z)).expand() in [log(2*log(x)*log(y) + 2*log(x)*log(z)), log(log(x)*log(z) + log(y)*log(x)) + log(2), log((log(y) + log(z))*log(x)) + log(2)] assert log(x**log(x**2)).expand(deep=False) == log(x)*log(x**2) assert log(x**log(x**2)).expand() == 2*log(x)**2 x, y = symbols('x,y') assert log(x*y).expand(force=True) == log(x) + log(y) assert log(x**y).expand(force=True) == y*log(x) assert log(exp(x)).expand(force=True) == x # there's generally no need to expand out logs since this requires # factoring and if simplification is sought, it's cheaper to put # logs together than it is to take them apart. assert log(2*3**2).expand() != 2*log(3) + log(2) @XFAIL def test_log_expand_fail(): x, y, z = symbols('x,y,z', positive=True) assert (log(x*(y + z))*(x + y)).expand(mul=True, log=True) == y*log( x) + y*log(y + z) + z*log(x) + z*log(y + z) def test_log_simplify(): x = Symbol("x", positive=True) assert log(x**2).expand() == 2*log(x) assert expand_log(log(x**(2 + log(2)))) == (2 + log(2))*log(x) z = Symbol('z') assert log(sqrt(z)).expand() == log(z)/2 assert expand_log(log(z**(log(2) - 1))) == (log(2) - 1)*log(z) assert log(z**(-1)).expand() != -log(z) assert log(z**(x/(x+1))).expand() == x*log(z)/(x + 1) def test_log_AccumBounds(): assert log(AccumBounds(1, E)) == AccumBounds(0, 1) assert log(AccumBounds(0, E)) == AccumBounds(-oo, 1) assert log(AccumBounds(-1, E)) == S.NaN assert log(AccumBounds(0, oo)) == AccumBounds(-oo, oo) assert log(AccumBounds(-oo, 0)) == S.NaN assert log(AccumBounds(-oo, oo)) == S.NaN @_both_exp_pow def test_lambertw(): k = Symbol('k') assert LambertW(x, 0) == LambertW(x) assert LambertW(x, 0, evaluate=False) != LambertW(x) assert LambertW(0) == 0 assert LambertW(E) == 1 assert LambertW(-1/E) == -1 assert LambertW(-log(2)/2) == -log(2) assert LambertW(oo) is oo assert LambertW(0, 1) is -oo assert LambertW(0, 42) is -oo assert LambertW(-pi/2, -1) == -I*pi/2 assert LambertW(-1/E, -1) == -1 assert LambertW(-2*exp(-2), -1) == -2 assert LambertW(2*log(2)) == log(2) assert LambertW(-pi/2) == I*pi/2 assert LambertW(exp(1 + E)) == E assert LambertW(x**2).diff(x) == 2*LambertW(x**2)/x/(1 + LambertW(x**2)) assert LambertW(x, k).diff(x) == LambertW(x, k)/x/(1 + LambertW(x, k)) assert LambertW(sqrt(2)).evalf(30).epsilon_eq( Float("0.701338383413663009202120278965", 30), 1e-29) assert re(LambertW(2, -1)).evalf().epsilon_eq(Float("-0.834310366631110")) assert LambertW(-1).is_real is False # issue 5215 assert LambertW(2, evaluate=False).is_real p = Symbol('p', positive=True) assert LambertW(p, evaluate=False).is_real assert LambertW(p - 1, evaluate=False).is_real is None assert LambertW(-p - 2/S.Exp1, evaluate=False).is_real is False assert LambertW(S.Half, -1, evaluate=False).is_real is False assert LambertW(Rational(-1, 10), -1, evaluate=False).is_real assert LambertW(-10, -1, evaluate=False).is_real is False assert LambertW(-2, 2, evaluate=False).is_real is False assert LambertW(0, evaluate=False).is_algebraic na = Symbol('na', nonzero=True, algebraic=True) assert LambertW(na).is_algebraic is False assert LambertW(p).is_zero is False n = Symbol('n', negative=True) assert LambertW(n).is_zero is False def test_issue_5673(): e = LambertW(-1) assert e.is_comparable is False assert e.is_positive is not True e2 = 1 - 1/(1 - exp(-1000)) assert e2.is_positive is not True e3 = -2 + exp(exp(LambertW(log(2)))*LambertW(log(2))) assert e3.is_nonzero is not True def test_log_fdiff(): x = Symbol('x') raises(ArgumentIndexError, lambda: log(x).fdiff(2)) def test_log_taylor_term(): x = symbols('x') assert log(x).taylor_term(0, x) == x assert log(x).taylor_term(1, x) == -x**2/2 assert log(x).taylor_term(4, x) == x**5/5 assert log(x).taylor_term(-1, x) is S.Zero def test_exp_expand_NC(): A, B, C = symbols('A,B,C', commutative=False) assert exp(A + B).expand() == exp(A + B) assert exp(A + B + C).expand() == exp(A + B + C) assert exp(x + y).expand() == exp(x)*exp(y) assert exp(x + y + z).expand() == exp(x)*exp(y)*exp(z) @_both_exp_pow def test_as_numer_denom(): n = symbols('n', negative=True) assert exp(x).as_numer_denom() == (exp(x), 1) assert exp(-x).as_numer_denom() == (1, exp(x)) assert exp(-2*x).as_numer_denom() == (1, exp(2*x)) assert exp(-2).as_numer_denom() == (1, exp(2)) assert exp(n).as_numer_denom() == (1, exp(-n)) assert exp(-n).as_numer_denom() == (exp(-n), 1) assert exp(-I*x).as_numer_denom() == (1, exp(I*x)) assert exp(-I*n).as_numer_denom() == (1, exp(I*n)) assert exp(-n).as_numer_denom() == (exp(-n), 1) @_both_exp_pow def test_polar(): x, y = symbols('x y', polar=True) assert abs(exp_polar(I*4)) == 1 assert abs(exp_polar(0)) == 1 assert abs(exp_polar(2 + 3*I)) == exp(2) assert exp_polar(I*10).n() == exp_polar(I*10) assert log(exp_polar(z)) == z assert log(x*y).expand() == log(x) + log(y) assert log(x**z).expand() == z*log(x) assert exp_polar(3).exp == 3 # Compare exp(1.0*pi*I). assert (exp_polar(1.0*pi*I).n(n=5)).as_real_imag()[1] >= 0 assert exp_polar(0).is_rational is True # issue 8008 def test_exp_summation(): w = symbols("w") m, n, i, j = symbols("m n i j") expr = exp(Sum(w*i, (i, 0, n), (j, 0, m))) assert expr.expand() == Product(exp(w*i), (i, 0, n), (j, 0, m)) def test_log_product(): from sympy.abc import n, m i, j = symbols('i,j', positive=True, integer=True) x, y = symbols('x,y', positive=True) z = symbols('z', real=True) w = symbols('w') expr = log(Product(x**i, (i, 1, n))) assert simplify(expr) == expr assert expr.expand() == Sum(i*log(x), (i, 1, n)) expr = log(Product(x**i*y**j, (i, 1, n), (j, 1, m))) assert simplify(expr) == expr assert expr.expand() == Sum(i*log(x) + j*log(y), (i, 1, n), (j, 1, m)) expr = log(Product(-2, (n, 0, 4))) assert simplify(expr) == expr assert expr.expand() == expr assert expr.expand(force=True) == Sum(log(-2), (n, 0, 4)) expr = log(Product(exp(z*i), (i, 0, n))) assert expr.expand() == Sum(z*i, (i, 0, n)) expr = log(Product(exp(w*i), (i, 0, n))) assert expr.expand() == expr assert expr.expand(force=True) == Sum(w*i, (i, 0, n)) expr = log(Product(i**2*abs(j), (i, 1, n), (j, 1, m))) assert expr.expand() == Sum(2*log(i) + log(j), (i, 1, n), (j, 1, m)) @XFAIL def test_log_product_simplify_to_sum(): from sympy.abc import n, m i, j = symbols('i,j', positive=True, integer=True) x, y = symbols('x,y', positive=True) assert simplify(log(Product(x**i, (i, 1, n)))) == Sum(i*log(x), (i, 1, n)) assert simplify(log(Product(x**i*y**j, (i, 1, n), (j, 1, m)))) == \ Sum(i*log(x) + j*log(y), (i, 1, n), (j, 1, m)) def test_issue_8866(): assert simplify(log(x, 10, evaluate=False)) == simplify(log(x, 10)) assert expand_log(log(x, 10, evaluate=False)) == expand_log(log(x, 10)) y = Symbol('y', positive=True) l1 = log(exp(y), exp(10)) b1 = log(exp(y), exp(5)) l2 = log(exp(y), exp(10), evaluate=False) b2 = log(exp(y), exp(5), evaluate=False) assert simplify(log(l1, b1)) == simplify(log(l2, b2)) assert expand_log(log(l1, b1)) == expand_log(log(l2, b2)) def test_log_expand_factor(): assert (log(18)/log(3) - 2).expand(factor=True) == log(2)/log(3) assert (log(12)/log(2)).expand(factor=True) == log(3)/log(2) + 2 assert (log(15)/log(3)).expand(factor=True) == 1 + log(5)/log(3) assert (log(2)/(-log(12) + log(24))).expand(factor=True) == 1 assert expand_log(log(12), factor=True) == log(3) + 2*log(2) assert expand_log(log(21)/log(7), factor=False) == log(3)/log(7) + 1 assert expand_log(log(45)/log(5) + log(20), factor=False) == \ 1 + 2*log(3)/log(5) + log(20) assert expand_log(log(45)/log(5) + log(26), factor=True) == \ log(2) + log(13) + (log(5) + 2*log(3))/log(5) def test_issue_9116(): n = Symbol('n', positive=True, integer=True) assert log(n).is_nonnegative is True def test_issue_18473(): assert exp(x*log(cos(1/x))).as_leading_term(x) == S.NaN assert exp(x*log(tan(1/x))).as_leading_term(x) == S.NaN assert log(cos(1/x)).as_leading_term(x) == S.NaN assert log(tan(1/x)).as_leading_term(x) == S.NaN assert log(cos(1/x) + 2).as_leading_term(x) == AccumBounds(0, log(3)) assert exp(x*log(cos(1/x) + 2)).as_leading_term(x) == 1 assert log(cos(1/x) - 2).as_leading_term(x) == S.NaN assert exp(x*log(cos(1/x) - 2)).as_leading_term(x) == S.NaN assert log(cos(1/x) + 1).as_leading_term(x) == AccumBounds(-oo, log(2)) assert exp(x*log(cos(1/x) + 1)).as_leading_term(x) == AccumBounds(0, 1) assert log(sin(1/x)**2).as_leading_term(x) == AccumBounds(-oo, 0) assert exp(x*log(sin(1/x)**2)).as_leading_term(x) == AccumBounds(0, 1) assert log(tan(1/x)**2).as_leading_term(x) == AccumBounds(-oo, oo) assert exp(2*x*(log(tan(1/x)**2))).as_leading_term(x) == AccumBounds(0, oo)
016a69904dac35d1574976523635d1ca5fe3f8e2a03b0f417f5211bd4497f646
from sympy.calculus.accumulationbounds import AccumBounds from sympy.core.add import Add from sympy.core.function import (Lambda, diff) from sympy.core.mul import Mul from sympy.core.numbers import (E, Float, I, Rational, nan, oo, pi, zoo) from sympy.core.power import Pow from sympy.core.singleton import S from sympy.core.symbol import (Symbol, symbols) from sympy.functions.elementary.complexes import (arg, conjugate, im, re) from sympy.functions.elementary.exponential import (exp, log) from sympy.functions.elementary.hyperbolic import (acoth, asinh, atanh, cosh, coth, sinh, tanh) from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import (acos, acot, acsc, asec, asin, atan, atan2, cos, cot, csc, sec, sin, sinc, tan) from sympy.functions.special.bessel import (besselj, jn) from sympy.functions.special.delta_functions import Heaviside from sympy.matrices.dense import Matrix from sympy.polys.polytools import (cancel, gcd) from sympy.series.limits import limit from sympy.series.order import O from sympy.series.series import series from sympy.sets.fancysets import ImageSet from sympy.sets.sets import (FiniteSet, Interval) from sympy.simplify.simplify import simplify from sympy.core.expr import unchanged from sympy.core.function import ArgumentIndexError from sympy.core.relational import Ne, Eq from sympy.functions.elementary.piecewise import Piecewise from sympy.sets.setexpr import SetExpr from sympy.testing.pytest import XFAIL, slow, raises x, y, z = symbols('x y z') r = Symbol('r', real=True) k, m = symbols('k m', integer=True) p = Symbol('p', positive=True) n = Symbol('n', negative=True) np = Symbol('p', nonpositive=True) nn = Symbol('n', nonnegative=True) nz = Symbol('nz', nonzero=True) ep = Symbol('ep', extended_positive=True) en = Symbol('en', extended_negative=True) enp = Symbol('ep', extended_nonpositive=True) enn = Symbol('en', extended_nonnegative=True) enz = Symbol('enz', extended_nonzero=True) a = Symbol('a', algebraic=True) na = Symbol('na', nonzero=True, algebraic=True) def test_sin(): x, y = symbols('x y') assert sin.nargs == FiniteSet(1) assert sin(nan) is nan assert sin(zoo) is nan assert sin(oo) == AccumBounds(-1, 1) assert sin(oo) - sin(oo) == AccumBounds(-2, 2) assert sin(oo*I) == oo*I assert sin(-oo*I) == -oo*I assert 0*sin(oo) is S.Zero assert 0/sin(oo) is S.Zero assert 0 + sin(oo) == AccumBounds(-1, 1) assert 5 + sin(oo) == AccumBounds(4, 6) assert sin(0) == 0 assert sin(asin(x)) == x assert sin(atan(x)) == x / sqrt(1 + x**2) assert sin(acos(x)) == sqrt(1 - x**2) assert sin(acot(x)) == 1 / (sqrt(1 + 1 / x**2) * x) assert sin(acsc(x)) == 1 / x assert sin(asec(x)) == sqrt(1 - 1 / x**2) assert sin(atan2(y, x)) == y / sqrt(x**2 + y**2) assert sin(pi*I) == sinh(pi)*I assert sin(-pi*I) == -sinh(pi)*I assert sin(-2*I) == -sinh(2)*I assert sin(pi) == 0 assert sin(-pi) == 0 assert sin(2*pi) == 0 assert sin(-2*pi) == 0 assert sin(-3*10**73*pi) == 0 assert sin(7*10**103*pi) == 0 assert sin(pi/2) == 1 assert sin(-pi/2) == -1 assert sin(pi*Rational(5, 2)) == 1 assert sin(pi*Rational(7, 2)) == -1 ne = symbols('ne', integer=True, even=False) e = symbols('e', even=True) assert sin(pi*ne/2) == (-1)**(ne/2 - S.Half) assert sin(pi*k/2).func == sin assert sin(pi*e/2) == 0 assert sin(pi*k) == 0 assert sin(pi*k).subs(k, 3) == sin(pi*k/2).subs(k, 6) # issue 8298 assert sin(pi/3) == S.Half*sqrt(3) assert sin(pi*Rational(-2, 3)) == Rational(-1, 2)*sqrt(3) assert sin(pi/4) == S.Half*sqrt(2) assert sin(-pi/4) == Rational(-1, 2)*sqrt(2) assert sin(pi*Rational(17, 4)) == S.Half*sqrt(2) assert sin(pi*Rational(-3, 4)) == Rational(-1, 2)*sqrt(2) assert sin(pi/6) == S.Half assert sin(-pi/6) == Rational(-1, 2) assert sin(pi*Rational(7, 6)) == Rational(-1, 2) assert sin(pi*Rational(-5, 6)) == Rational(-1, 2) assert sin(pi*Rational(1, 5)) == sqrt((5 - sqrt(5)) / 8) assert sin(pi*Rational(2, 5)) == sqrt((5 + sqrt(5)) / 8) assert sin(pi*Rational(3, 5)) == sin(pi*Rational(2, 5)) assert sin(pi*Rational(4, 5)) == sin(pi*Rational(1, 5)) assert sin(pi*Rational(6, 5)) == -sin(pi*Rational(1, 5)) assert sin(pi*Rational(8, 5)) == -sin(pi*Rational(2, 5)) assert sin(pi*Rational(-1273, 5)) == -sin(pi*Rational(2, 5)) assert sin(pi/8) == sqrt((2 - sqrt(2))/4) assert sin(pi/10) == Rational(-1, 4) + sqrt(5)/4 assert sin(pi/12) == -sqrt(2)/4 + sqrt(6)/4 assert sin(pi*Rational(5, 12)) == sqrt(2)/4 + sqrt(6)/4 assert sin(pi*Rational(-7, 12)) == -sqrt(2)/4 - sqrt(6)/4 assert sin(pi*Rational(-11, 12)) == sqrt(2)/4 - sqrt(6)/4 assert sin(pi*Rational(104, 105)) == sin(pi/105) assert sin(pi*Rational(106, 105)) == -sin(pi/105) assert sin(pi*Rational(-104, 105)) == -sin(pi/105) assert sin(pi*Rational(-106, 105)) == sin(pi/105) assert sin(x*I) == sinh(x)*I assert sin(k*pi) == 0 assert sin(17*k*pi) == 0 assert sin(2*k*pi + 4) == sin(4) assert sin(2*k*pi + m*pi + 1) == (-1)**(m + 2*k)*sin(1) assert sin(k*pi*I) == sinh(k*pi)*I assert sin(r).is_real is True assert sin(0, evaluate=False).is_algebraic assert sin(a).is_algebraic is None assert sin(na).is_algebraic is False q = Symbol('q', rational=True) assert sin(pi*q).is_algebraic qn = Symbol('qn', rational=True, nonzero=True) assert sin(qn).is_rational is False assert sin(q).is_rational is None # issue 8653 assert isinstance(sin( re(x) - im(y)), sin) is True assert isinstance(sin(-re(x) + im(y)), sin) is False assert sin(SetExpr(Interval(0, 1))) == SetExpr(ImageSet(Lambda(x, sin(x)), Interval(0, 1))) for d in list(range(1, 22)) + [60, 85]: for n in range(0, d*2 + 1): x = n*pi/d e = abs( float(sin(x)) - sin(float(x)) ) assert e < 1e-12 assert sin(0, evaluate=False).is_zero is True assert sin(k*pi, evaluate=False).is_zero is True assert sin(Add(1, -1, evaluate=False), evaluate=False).is_zero is True def test_sin_cos(): for d in [1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 24, 30, 40, 60, 120]: # list is not exhaustive... for n in range(-2*d, d*2): x = n*pi/d assert sin(x + pi/2) == cos(x), "fails for %d*pi/%d" % (n, d) assert sin(x - pi/2) == -cos(x), "fails for %d*pi/%d" % (n, d) assert sin(x) == cos(x - pi/2), "fails for %d*pi/%d" % (n, d) assert -sin(x) == cos(x + pi/2), "fails for %d*pi/%d" % (n, d) def test_sin_series(): assert sin(x).series(x, 0, 9) == \ x - x**3/6 + x**5/120 - x**7/5040 + O(x**9) def test_sin_rewrite(): assert sin(x).rewrite(exp) == -I*(exp(I*x) - exp(-I*x))/2 assert sin(x).rewrite(tan) == 2*tan(x/2)/(1 + tan(x/2)**2) assert sin(x).rewrite(cot) == 2*cot(x/2)/(1 + cot(x/2)**2) assert sin(sinh(x)).rewrite( exp).subs(x, 3).n() == sin(x).rewrite(exp).subs(x, sinh(3)).n() assert sin(cosh(x)).rewrite( exp).subs(x, 3).n() == sin(x).rewrite(exp).subs(x, cosh(3)).n() assert sin(tanh(x)).rewrite( exp).subs(x, 3).n() == sin(x).rewrite(exp).subs(x, tanh(3)).n() assert sin(coth(x)).rewrite( exp).subs(x, 3).n() == sin(x).rewrite(exp).subs(x, coth(3)).n() assert sin(sin(x)).rewrite( exp).subs(x, 3).n() == sin(x).rewrite(exp).subs(x, sin(3)).n() assert sin(cos(x)).rewrite( exp).subs(x, 3).n() == sin(x).rewrite(exp).subs(x, cos(3)).n() assert sin(tan(x)).rewrite( exp).subs(x, 3).n() == sin(x).rewrite(exp).subs(x, tan(3)).n() assert sin(cot(x)).rewrite( exp).subs(x, 3).n() == sin(x).rewrite(exp).subs(x, cot(3)).n() assert sin(log(x)).rewrite(Pow) == I*x**-I / 2 - I*x**I /2 assert sin(x).rewrite(csc) == 1/csc(x) assert sin(x).rewrite(cos) == cos(x - pi / 2, evaluate=False) assert sin(x).rewrite(sec) == 1 / sec(x - pi / 2, evaluate=False) assert sin(cos(x)).rewrite(Pow) == sin(cos(x)) def _test_extrig(f, i, e): from sympy.core.function import expand_trig assert unchanged(f, i) assert expand_trig(f(i)) == f(i) # testing directly instead of with .expand(trig=True) # because the other expansions undo the unevaluated Mul assert expand_trig(f(Mul(i, 1, evaluate=False))) == e assert abs(f(i) - e).n() < 1e-10 def test_sin_expansion(): # Note: these formulas are not unique. The ones here come from the # Chebyshev formulas. assert sin(x + y).expand(trig=True) == sin(x)*cos(y) + cos(x)*sin(y) assert sin(x - y).expand(trig=True) == sin(x)*cos(y) - cos(x)*sin(y) assert sin(y - x).expand(trig=True) == cos(x)*sin(y) - sin(x)*cos(y) assert sin(2*x).expand(trig=True) == 2*sin(x)*cos(x) assert sin(3*x).expand(trig=True) == -4*sin(x)**3 + 3*sin(x) assert sin(4*x).expand(trig=True) == -8*sin(x)**3*cos(x) + 4*sin(x)*cos(x) _test_extrig(sin, 2, 2*sin(1)*cos(1)) _test_extrig(sin, 3, -4*sin(1)**3 + 3*sin(1)) def test_sin_AccumBounds(): assert sin(AccumBounds(-oo, oo)) == AccumBounds(-1, 1) assert sin(AccumBounds(0, oo)) == AccumBounds(-1, 1) assert sin(AccumBounds(-oo, 0)) == AccumBounds(-1, 1) assert sin(AccumBounds(0, 2*S.Pi)) == AccumBounds(-1, 1) assert sin(AccumBounds(0, S.Pi*Rational(3, 4))) == AccumBounds(0, 1) assert sin(AccumBounds(S.Pi*Rational(3, 4), S.Pi*Rational(7, 4))) == AccumBounds(-1, sin(S.Pi*Rational(3, 4))) assert sin(AccumBounds(S.Pi/4, S.Pi/3)) == AccumBounds(sin(S.Pi/4), sin(S.Pi/3)) assert sin(AccumBounds(S.Pi*Rational(3, 4), S.Pi*Rational(5, 6))) == AccumBounds(sin(S.Pi*Rational(5, 6)), sin(S.Pi*Rational(3, 4))) def test_sin_fdiff(): assert sin(x).fdiff() == cos(x) raises(ArgumentIndexError, lambda: sin(x).fdiff(2)) def test_trig_symmetry(): assert sin(-x) == -sin(x) assert cos(-x) == cos(x) assert tan(-x) == -tan(x) assert cot(-x) == -cot(x) assert sin(x + pi) == -sin(x) assert sin(x + 2*pi) == sin(x) assert sin(x + 3*pi) == -sin(x) assert sin(x + 4*pi) == sin(x) assert sin(x - 5*pi) == -sin(x) assert cos(x + pi) == -cos(x) assert cos(x + 2*pi) == cos(x) assert cos(x + 3*pi) == -cos(x) assert cos(x + 4*pi) == cos(x) assert cos(x - 5*pi) == -cos(x) assert tan(x + pi) == tan(x) assert tan(x - 3*pi) == tan(x) assert cot(x + pi) == cot(x) assert cot(x - 3*pi) == cot(x) assert sin(pi/2 - x) == cos(x) assert sin(pi*Rational(3, 2) - x) == -cos(x) assert sin(pi*Rational(5, 2) - x) == cos(x) assert cos(pi/2 - x) == sin(x) assert cos(pi*Rational(3, 2) - x) == -sin(x) assert cos(pi*Rational(5, 2) - x) == sin(x) assert tan(pi/2 - x) == cot(x) assert tan(pi*Rational(3, 2) - x) == cot(x) assert tan(pi*Rational(5, 2) - x) == cot(x) assert cot(pi/2 - x) == tan(x) assert cot(pi*Rational(3, 2) - x) == tan(x) assert cot(pi*Rational(5, 2) - x) == tan(x) assert sin(pi/2 + x) == cos(x) assert cos(pi/2 + x) == -sin(x) assert tan(pi/2 + x) == -cot(x) assert cot(pi/2 + x) == -tan(x) def test_cos(): x, y = symbols('x y') assert cos.nargs == FiniteSet(1) assert cos(nan) is nan assert cos(oo) == AccumBounds(-1, 1) assert cos(oo) - cos(oo) == AccumBounds(-2, 2) assert cos(oo*I) is oo assert cos(-oo*I) is oo assert cos(zoo) is nan assert cos(0) == 1 assert cos(acos(x)) == x assert cos(atan(x)) == 1 / sqrt(1 + x**2) assert cos(asin(x)) == sqrt(1 - x**2) assert cos(acot(x)) == 1 / sqrt(1 + 1 / x**2) assert cos(acsc(x)) == sqrt(1 - 1 / x**2) assert cos(asec(x)) == 1 / x assert cos(atan2(y, x)) == x / sqrt(x**2 + y**2) assert cos(pi*I) == cosh(pi) assert cos(-pi*I) == cosh(pi) assert cos(-2*I) == cosh(2) assert cos(pi/2) == 0 assert cos(-pi/2) == 0 assert cos(pi/2) == 0 assert cos(-pi/2) == 0 assert cos((-3*10**73 + 1)*pi/2) == 0 assert cos((7*10**103 + 1)*pi/2) == 0 n = symbols('n', integer=True, even=False) e = symbols('e', even=True) assert cos(pi*n/2) == 0 assert cos(pi*e/2) == (-1)**(e/2) assert cos(pi) == -1 assert cos(-pi) == -1 assert cos(2*pi) == 1 assert cos(5*pi) == -1 assert cos(8*pi) == 1 assert cos(pi/3) == S.Half assert cos(pi*Rational(-2, 3)) == Rational(-1, 2) assert cos(pi/4) == S.Half*sqrt(2) assert cos(-pi/4) == S.Half*sqrt(2) assert cos(pi*Rational(11, 4)) == Rational(-1, 2)*sqrt(2) assert cos(pi*Rational(-3, 4)) == Rational(-1, 2)*sqrt(2) assert cos(pi/6) == S.Half*sqrt(3) assert cos(-pi/6) == S.Half*sqrt(3) assert cos(pi*Rational(7, 6)) == Rational(-1, 2)*sqrt(3) assert cos(pi*Rational(-5, 6)) == Rational(-1, 2)*sqrt(3) assert cos(pi*Rational(1, 5)) == (sqrt(5) + 1)/4 assert cos(pi*Rational(2, 5)) == (sqrt(5) - 1)/4 assert cos(pi*Rational(3, 5)) == -cos(pi*Rational(2, 5)) assert cos(pi*Rational(4, 5)) == -cos(pi*Rational(1, 5)) assert cos(pi*Rational(6, 5)) == -cos(pi*Rational(1, 5)) assert cos(pi*Rational(8, 5)) == cos(pi*Rational(2, 5)) assert cos(pi*Rational(-1273, 5)) == -cos(pi*Rational(2, 5)) assert cos(pi/8) == sqrt((2 + sqrt(2))/4) assert cos(pi/12) == sqrt(2)/4 + sqrt(6)/4 assert cos(pi*Rational(5, 12)) == -sqrt(2)/4 + sqrt(6)/4 assert cos(pi*Rational(7, 12)) == sqrt(2)/4 - sqrt(6)/4 assert cos(pi*Rational(11, 12)) == -sqrt(2)/4 - sqrt(6)/4 assert cos(pi*Rational(104, 105)) == -cos(pi/105) assert cos(pi*Rational(106, 105)) == -cos(pi/105) assert cos(pi*Rational(-104, 105)) == -cos(pi/105) assert cos(pi*Rational(-106, 105)) == -cos(pi/105) assert cos(x*I) == cosh(x) assert cos(k*pi*I) == cosh(k*pi) assert cos(r).is_real is True assert cos(0, evaluate=False).is_algebraic assert cos(a).is_algebraic is None assert cos(na).is_algebraic is False q = Symbol('q', rational=True) assert cos(pi*q).is_algebraic assert cos(pi*Rational(2, 7)).is_algebraic assert cos(k*pi) == (-1)**k assert cos(2*k*pi) == 1 for d in list(range(1, 22)) + [60, 85]: for n in range(0, 2*d + 1): x = n*pi/d e = abs( float(cos(x)) - cos(float(x)) ) assert e < 1e-12 def test_issue_6190(): c = Float('123456789012345678901234567890.25', '') for cls in [sin, cos, tan, cot]: assert cls(c*pi) == cls(pi/4) assert cls(4.125*pi) == cls(pi/8) assert cls(4.7*pi) == cls((4.7 % 2)*pi) def test_cos_series(): assert cos(x).series(x, 0, 9) == \ 1 - x**2/2 + x**4/24 - x**6/720 + x**8/40320 + O(x**9) def test_cos_rewrite(): assert cos(x).rewrite(exp) == exp(I*x)/2 + exp(-I*x)/2 assert cos(x).rewrite(tan) == (1 - tan(x/2)**2)/(1 + tan(x/2)**2) assert cos(x).rewrite(cot) == -(1 - cot(x/2)**2)/(1 + cot(x/2)**2) assert cos(sinh(x)).rewrite( exp).subs(x, 3).n() == cos(x).rewrite(exp).subs(x, sinh(3)).n() assert cos(cosh(x)).rewrite( exp).subs(x, 3).n() == cos(x).rewrite(exp).subs(x, cosh(3)).n() assert cos(tanh(x)).rewrite( exp).subs(x, 3).n() == cos(x).rewrite(exp).subs(x, tanh(3)).n() assert cos(coth(x)).rewrite( exp).subs(x, 3).n() == cos(x).rewrite(exp).subs(x, coth(3)).n() assert cos(sin(x)).rewrite( exp).subs(x, 3).n() == cos(x).rewrite(exp).subs(x, sin(3)).n() assert cos(cos(x)).rewrite( exp).subs(x, 3).n() == cos(x).rewrite(exp).subs(x, cos(3)).n() assert cos(tan(x)).rewrite( exp).subs(x, 3).n() == cos(x).rewrite(exp).subs(x, tan(3)).n() assert cos(cot(x)).rewrite( exp).subs(x, 3).n() == cos(x).rewrite(exp).subs(x, cot(3)).n() assert cos(log(x)).rewrite(Pow) == x**I/2 + x**-I/2 assert cos(x).rewrite(sec) == 1/sec(x) assert cos(x).rewrite(sin) == sin(x + pi/2, evaluate=False) assert cos(x).rewrite(csc) == 1/csc(-x + pi/2, evaluate=False) assert cos(sin(x)).rewrite(Pow) == cos(sin(x)) def test_cos_expansion(): assert cos(x + y).expand(trig=True) == cos(x)*cos(y) - sin(x)*sin(y) assert cos(x - y).expand(trig=True) == cos(x)*cos(y) + sin(x)*sin(y) assert cos(y - x).expand(trig=True) == cos(x)*cos(y) + sin(x)*sin(y) assert cos(2*x).expand(trig=True) == 2*cos(x)**2 - 1 assert cos(3*x).expand(trig=True) == 4*cos(x)**3 - 3*cos(x) assert cos(4*x).expand(trig=True) == 8*cos(x)**4 - 8*cos(x)**2 + 1 _test_extrig(cos, 2, 2*cos(1)**2 - 1) _test_extrig(cos, 3, 4*cos(1)**3 - 3*cos(1)) def test_cos_AccumBounds(): assert cos(AccumBounds(-oo, oo)) == AccumBounds(-1, 1) assert cos(AccumBounds(0, oo)) == AccumBounds(-1, 1) assert cos(AccumBounds(-oo, 0)) == AccumBounds(-1, 1) assert cos(AccumBounds(0, 2*S.Pi)) == AccumBounds(-1, 1) assert cos(AccumBounds(-S.Pi/3, S.Pi/4)) == AccumBounds(cos(-S.Pi/3), 1) assert cos(AccumBounds(S.Pi*Rational(3, 4), S.Pi*Rational(5, 4))) == AccumBounds(-1, cos(S.Pi*Rational(3, 4))) assert cos(AccumBounds(S.Pi*Rational(5, 4), S.Pi*Rational(4, 3))) == AccumBounds(cos(S.Pi*Rational(5, 4)), cos(S.Pi*Rational(4, 3))) assert cos(AccumBounds(S.Pi/4, S.Pi/3)) == AccumBounds(cos(S.Pi/3), cos(S.Pi/4)) def test_cos_fdiff(): assert cos(x).fdiff() == -sin(x) raises(ArgumentIndexError, lambda: cos(x).fdiff(2)) def test_tan(): assert tan(nan) is nan assert tan(zoo) is nan assert tan(oo) == AccumBounds(-oo, oo) assert tan(oo) - tan(oo) == AccumBounds(-oo, oo) assert tan.nargs == FiniteSet(1) assert tan(oo*I) == I assert tan(-oo*I) == -I assert tan(0) == 0 assert tan(atan(x)) == x assert tan(asin(x)) == x / sqrt(1 - x**2) assert tan(acos(x)) == sqrt(1 - x**2) / x assert tan(acot(x)) == 1 / x assert tan(acsc(x)) == 1 / (sqrt(1 - 1 / x**2) * x) assert tan(asec(x)) == sqrt(1 - 1 / x**2) * x assert tan(atan2(y, x)) == y/x assert tan(pi*I) == tanh(pi)*I assert tan(-pi*I) == -tanh(pi)*I assert tan(-2*I) == -tanh(2)*I assert tan(pi) == 0 assert tan(-pi) == 0 assert tan(2*pi) == 0 assert tan(-2*pi) == 0 assert tan(-3*10**73*pi) == 0 assert tan(pi/2) is zoo assert tan(pi*Rational(3, 2)) is zoo assert tan(pi/3) == sqrt(3) assert tan(pi*Rational(-2, 3)) == sqrt(3) assert tan(pi/4) is S.One assert tan(-pi/4) is S.NegativeOne assert tan(pi*Rational(17, 4)) is S.One assert tan(pi*Rational(-3, 4)) is S.One assert tan(pi/5) == sqrt(5 - 2*sqrt(5)) assert tan(pi*Rational(2, 5)) == sqrt(5 + 2*sqrt(5)) assert tan(pi*Rational(18, 5)) == -sqrt(5 + 2*sqrt(5)) assert tan(pi*Rational(-16, 5)) == -sqrt(5 - 2*sqrt(5)) assert tan(pi/6) == 1/sqrt(3) assert tan(-pi/6) == -1/sqrt(3) assert tan(pi*Rational(7, 6)) == 1/sqrt(3) assert tan(pi*Rational(-5, 6)) == 1/sqrt(3) assert tan(pi/8) == -1 + sqrt(2) assert tan(pi*Rational(3, 8)) == 1 + sqrt(2) # issue 15959 assert tan(pi*Rational(5, 8)) == -1 - sqrt(2) assert tan(pi*Rational(7, 8)) == 1 - sqrt(2) assert tan(pi/10) == sqrt(1 - 2*sqrt(5)/5) assert tan(pi*Rational(3, 10)) == sqrt(1 + 2*sqrt(5)/5) assert tan(pi*Rational(17, 10)) == -sqrt(1 + 2*sqrt(5)/5) assert tan(pi*Rational(-31, 10)) == -sqrt(1 - 2*sqrt(5)/5) assert tan(pi/12) == -sqrt(3) + 2 assert tan(pi*Rational(5, 12)) == sqrt(3) + 2 assert tan(pi*Rational(7, 12)) == -sqrt(3) - 2 assert tan(pi*Rational(11, 12)) == sqrt(3) - 2 assert tan(pi/24).radsimp() == -2 - sqrt(3) + sqrt(2) + sqrt(6) assert tan(pi*Rational(5, 24)).radsimp() == -2 + sqrt(3) - sqrt(2) + sqrt(6) assert tan(pi*Rational(7, 24)).radsimp() == 2 - sqrt(3) - sqrt(2) + sqrt(6) assert tan(pi*Rational(11, 24)).radsimp() == 2 + sqrt(3) + sqrt(2) + sqrt(6) assert tan(pi*Rational(13, 24)).radsimp() == -2 - sqrt(3) - sqrt(2) - sqrt(6) assert tan(pi*Rational(17, 24)).radsimp() == -2 + sqrt(3) + sqrt(2) - sqrt(6) assert tan(pi*Rational(19, 24)).radsimp() == 2 - sqrt(3) + sqrt(2) - sqrt(6) assert tan(pi*Rational(23, 24)).radsimp() == 2 + sqrt(3) - sqrt(2) - sqrt(6) assert tan(x*I) == tanh(x)*I assert tan(k*pi) == 0 assert tan(17*k*pi) == 0 assert tan(k*pi*I) == tanh(k*pi)*I assert tan(r).is_real is None assert tan(r).is_extended_real is True assert tan(0, evaluate=False).is_algebraic assert tan(a).is_algebraic is None assert tan(na).is_algebraic is False assert tan(pi*Rational(10, 7)) == tan(pi*Rational(3, 7)) assert tan(pi*Rational(11, 7)) == -tan(pi*Rational(3, 7)) assert tan(pi*Rational(-11, 7)) == tan(pi*Rational(3, 7)) assert tan(pi*Rational(15, 14)) == tan(pi/14) assert tan(pi*Rational(-15, 14)) == -tan(pi/14) assert tan(r).is_finite is None assert tan(I*r).is_finite is True # https://github.com/sympy/sympy/issues/21177 f = tan(pi*(x + S(3)/2))/(3*x) assert f.as_leading_term(x) == -1/(3*pi*x**2) def test_tan_series(): assert tan(x).series(x, 0, 9) == \ x + x**3/3 + 2*x**5/15 + 17*x**7/315 + O(x**9) def test_tan_rewrite(): neg_exp, pos_exp = exp(-x*I), exp(x*I) assert tan(x).rewrite(exp) == I*(neg_exp - pos_exp)/(neg_exp + pos_exp) assert tan(x).rewrite(sin) == 2*sin(x)**2/sin(2*x) assert tan(x).rewrite(cos) == cos(x - S.Pi/2, evaluate=False)/cos(x) assert tan(x).rewrite(cot) == 1/cot(x) assert tan(sinh(x)).rewrite( exp).subs(x, 3).n() == tan(x).rewrite(exp).subs(x, sinh(3)).n() assert tan(cosh(x)).rewrite( exp).subs(x, 3).n() == tan(x).rewrite(exp).subs(x, cosh(3)).n() assert tan(tanh(x)).rewrite( exp).subs(x, 3).n() == tan(x).rewrite(exp).subs(x, tanh(3)).n() assert tan(coth(x)).rewrite( exp).subs(x, 3).n() == tan(x).rewrite(exp).subs(x, coth(3)).n() assert tan(sin(x)).rewrite( exp).subs(x, 3).n() == tan(x).rewrite(exp).subs(x, sin(3)).n() assert tan(cos(x)).rewrite( exp).subs(x, 3).n() == tan(x).rewrite(exp).subs(x, cos(3)).n() assert tan(tan(x)).rewrite( exp).subs(x, 3).n() == tan(x).rewrite(exp).subs(x, tan(3)).n() assert tan(cot(x)).rewrite( exp).subs(x, 3).n() == tan(x).rewrite(exp).subs(x, cot(3)).n() assert tan(log(x)).rewrite(Pow) == I*(x**-I - x**I)/(x**-I + x**I) assert 0 == (cos(pi/34)*tan(pi/34) - sin(pi/34)).rewrite(pow) assert 0 == (cos(pi/17)*tan(pi/17) - sin(pi/17)).rewrite(pow) assert tan(pi/19).rewrite(pow) == tan(pi/19) assert tan(pi*Rational(8, 19)).rewrite(sqrt) == tan(pi*Rational(8, 19)) assert tan(x).rewrite(sec) == sec(x)/sec(x - pi/2, evaluate=False) assert tan(x).rewrite(csc) == csc(-x + pi/2, evaluate=False)/csc(x) assert tan(sin(x)).rewrite(Pow) == tan(sin(x)) assert tan(pi*Rational(2, 5), evaluate=False).rewrite(sqrt) == sqrt(sqrt(5)/8 + Rational(5, 8))/(Rational(-1, 4) + sqrt(5)/4) def test_tan_subs(): assert tan(x).subs(tan(x), y) == y assert tan(x).subs(x, y) == tan(y) assert tan(x).subs(x, S.Pi/2) is zoo assert tan(x).subs(x, S.Pi*Rational(3, 2)) is zoo def test_tan_expansion(): assert tan(x + y).expand(trig=True) == ((tan(x) + tan(y))/(1 - tan(x)*tan(y))).expand() assert tan(x - y).expand(trig=True) == ((tan(x) - tan(y))/(1 + tan(x)*tan(y))).expand() assert tan(x + y + z).expand(trig=True) == ( (tan(x) + tan(y) + tan(z) - tan(x)*tan(y)*tan(z))/ (1 - tan(x)*tan(y) - tan(x)*tan(z) - tan(y)*tan(z))).expand() assert 0 == tan(2*x).expand(trig=True).rewrite(tan).subs([(tan(x), Rational(1, 7))])*24 - 7 assert 0 == tan(3*x).expand(trig=True).rewrite(tan).subs([(tan(x), Rational(1, 5))])*55 - 37 assert 0 == tan(4*x - pi/4).expand(trig=True).rewrite(tan).subs([(tan(x), Rational(1, 5))])*239 - 1 _test_extrig(tan, 2, 2*tan(1)/(1 - tan(1)**2)) _test_extrig(tan, 3, (-tan(1)**3 + 3*tan(1))/(1 - 3*tan(1)**2)) def test_tan_AccumBounds(): assert tan(AccumBounds(-oo, oo)) == AccumBounds(-oo, oo) assert tan(AccumBounds(S.Pi/3, S.Pi*Rational(2, 3))) == AccumBounds(-oo, oo) assert tan(AccumBounds(S.Pi/6, S.Pi/3)) == AccumBounds(tan(S.Pi/6), tan(S.Pi/3)) def test_tan_fdiff(): assert tan(x).fdiff() == tan(x)**2 + 1 raises(ArgumentIndexError, lambda: tan(x).fdiff(2)) def test_cot(): assert cot(nan) is nan assert cot.nargs == FiniteSet(1) assert cot(oo*I) == -I assert cot(-oo*I) == I assert cot(zoo) is nan assert cot(0) is zoo assert cot(2*pi) is zoo assert cot(acot(x)) == x assert cot(atan(x)) == 1 / x assert cot(asin(x)) == sqrt(1 - x**2) / x assert cot(acos(x)) == x / sqrt(1 - x**2) assert cot(acsc(x)) == sqrt(1 - 1 / x**2) * x assert cot(asec(x)) == 1 / (sqrt(1 - 1 / x**2) * x) assert cot(atan2(y, x)) == x/y assert cot(pi*I) == -coth(pi)*I assert cot(-pi*I) == coth(pi)*I assert cot(-2*I) == coth(2)*I assert cot(pi) == cot(2*pi) == cot(3*pi) assert cot(-pi) == cot(-2*pi) == cot(-3*pi) assert cot(pi/2) == 0 assert cot(-pi/2) == 0 assert cot(pi*Rational(5, 2)) == 0 assert cot(pi*Rational(7, 2)) == 0 assert cot(pi/3) == 1/sqrt(3) assert cot(pi*Rational(-2, 3)) == 1/sqrt(3) assert cot(pi/4) is S.One assert cot(-pi/4) is S.NegativeOne assert cot(pi*Rational(17, 4)) is S.One assert cot(pi*Rational(-3, 4)) is S.One assert cot(pi/6) == sqrt(3) assert cot(-pi/6) == -sqrt(3) assert cot(pi*Rational(7, 6)) == sqrt(3) assert cot(pi*Rational(-5, 6)) == sqrt(3) assert cot(pi/8) == 1 + sqrt(2) assert cot(pi*Rational(3, 8)) == -1 + sqrt(2) assert cot(pi*Rational(5, 8)) == 1 - sqrt(2) assert cot(pi*Rational(7, 8)) == -1 - sqrt(2) assert cot(pi/12) == sqrt(3) + 2 assert cot(pi*Rational(5, 12)) == -sqrt(3) + 2 assert cot(pi*Rational(7, 12)) == sqrt(3) - 2 assert cot(pi*Rational(11, 12)) == -sqrt(3) - 2 assert cot(pi/24).radsimp() == sqrt(2) + sqrt(3) + 2 + sqrt(6) assert cot(pi*Rational(5, 24)).radsimp() == -sqrt(2) - sqrt(3) + 2 + sqrt(6) assert cot(pi*Rational(7, 24)).radsimp() == -sqrt(2) + sqrt(3) - 2 + sqrt(6) assert cot(pi*Rational(11, 24)).radsimp() == sqrt(2) - sqrt(3) - 2 + sqrt(6) assert cot(pi*Rational(13, 24)).radsimp() == -sqrt(2) + sqrt(3) + 2 - sqrt(6) assert cot(pi*Rational(17, 24)).radsimp() == sqrt(2) - sqrt(3) + 2 - sqrt(6) assert cot(pi*Rational(19, 24)).radsimp() == sqrt(2) + sqrt(3) - 2 - sqrt(6) assert cot(pi*Rational(23, 24)).radsimp() == -sqrt(2) - sqrt(3) - 2 - sqrt(6) assert cot(x*I) == -coth(x)*I assert cot(k*pi*I) == -coth(k*pi)*I assert cot(r).is_real is None assert cot(r).is_extended_real is True assert cot(a).is_algebraic is None assert cot(na).is_algebraic is False assert cot(pi*Rational(10, 7)) == cot(pi*Rational(3, 7)) assert cot(pi*Rational(11, 7)) == -cot(pi*Rational(3, 7)) assert cot(pi*Rational(-11, 7)) == cot(pi*Rational(3, 7)) assert cot(pi*Rational(39, 34)) == cot(pi*Rational(5, 34)) assert cot(pi*Rational(-41, 34)) == -cot(pi*Rational(7, 34)) assert cot(x).is_finite is None assert cot(r).is_finite is None i = Symbol('i', imaginary=True) assert cot(i).is_finite is True assert cot(x).subs(x, 3*pi) is zoo # https://github.com/sympy/sympy/issues/21177 f = cot(pi*(x + 4))/(3*x) assert f.as_leading_term(x) == 1/(3*pi*x**2) def test_tan_cot_sin_cos_evalf(): assert abs((tan(pi*Rational(8, 15))*cos(pi*Rational(8, 15))/sin(pi*Rational(8, 15)) - 1).evalf()) < 1e-14 assert abs((cot(pi*Rational(4, 15))*sin(pi*Rational(4, 15))/cos(pi*Rational(4, 15)) - 1).evalf()) < 1e-14 @XFAIL def test_tan_cot_sin_cos_ratsimp(): assert 1 == (tan(pi*Rational(8, 15))*cos(pi*Rational(8, 15))/sin(pi*Rational(8, 15))).ratsimp() assert 1 == (cot(pi*Rational(4, 15))*sin(pi*Rational(4, 15))/cos(pi*Rational(4, 15))).ratsimp() def test_cot_series(): assert cot(x).series(x, 0, 9) == \ 1/x - x/3 - x**3/45 - 2*x**5/945 - x**7/4725 + O(x**9) # issue 6210 assert cot(x**4 + x**5).series(x, 0, 1) == \ x**(-4) - 1/x**3 + x**(-2) - 1/x + 1 + O(x) assert cot(pi*(1-x)).series(x, 0, 3) == -1/(pi*x) + pi*x/3 + O(x**3) assert cot(x).taylor_term(0, x) == 1/x assert cot(x).taylor_term(2, x) is S.Zero assert cot(x).taylor_term(3, x) == -x**3/45 def test_cot_rewrite(): neg_exp, pos_exp = exp(-x*I), exp(x*I) assert cot(x).rewrite(exp) == I*(pos_exp + neg_exp)/(pos_exp - neg_exp) assert cot(x).rewrite(sin) == sin(2*x)/(2*(sin(x)**2)) assert cot(x).rewrite(cos) == cos(x)/cos(x - pi/2, evaluate=False) assert cot(x).rewrite(tan) == 1/tan(x) def check(func): z = cot(func(x)).rewrite(exp ) - cot(x).rewrite(exp).subs(x, func(x)) assert z.rewrite(exp).expand() == 0 check(sinh) check(cosh) check(tanh) check(coth) check(sin) check(cos) check(tan) assert cot(log(x)).rewrite(Pow) == -I*(x**-I + x**I)/(x**-I - x**I) assert cot(pi*Rational(4, 34)).rewrite(pow).ratsimp() == (cos(pi*Rational(4, 34))/sin(pi*Rational(4, 34))).rewrite(pow).ratsimp() assert cot(pi*Rational(4, 17)).rewrite(pow) == (cos(pi*Rational(4, 17))/sin(pi*Rational(4, 17))).rewrite(pow) assert cot(pi/19).rewrite(pow) == cot(pi/19) assert cot(pi/19).rewrite(sqrt) == cot(pi/19) assert cot(x).rewrite(sec) == sec(x - pi / 2, evaluate=False) / sec(x) assert cot(x).rewrite(csc) == csc(x) / csc(- x + pi / 2, evaluate=False) assert cot(sin(x)).rewrite(Pow) == cot(sin(x)) assert cot(pi*Rational(2, 5), evaluate=False).rewrite(sqrt) == (Rational(-1, 4) + sqrt(5)/4)/\ sqrt(sqrt(5)/8 + Rational(5, 8)) def test_cot_subs(): assert cot(x).subs(cot(x), y) == y assert cot(x).subs(x, y) == cot(y) assert cot(x).subs(x, 0) is zoo assert cot(x).subs(x, S.Pi) is zoo def test_cot_expansion(): assert cot(x + y).expand(trig=True).together() == ( (cot(x)*cot(y) - 1)/(cot(x) + cot(y))) assert cot(x - y).expand(trig=True).together() == ( cot(x)*cot(-y) - 1)/(cot(x) + cot(-y)) assert cot(x + y + z).expand(trig=True).together() == ( (cot(x)*cot(y)*cot(z) - cot(x) - cot(y) - cot(z))/ (-1 + cot(x)*cot(y) + cot(x)*cot(z) + cot(y)*cot(z))) assert cot(3*x).expand(trig=True).together() == ( (cot(x)**2 - 3)*cot(x)/(3*cot(x)**2 - 1)) assert cot(2*x).expand(trig=True) == cot(x)/2 - 1/(2*cot(x)) assert cot(3*x).expand(trig=True).together() == ( cot(x)**2 - 3)*cot(x)/(3*cot(x)**2 - 1) assert cot(4*x - pi/4).expand(trig=True).cancel() == ( -tan(x)**4 + 4*tan(x)**3 + 6*tan(x)**2 - 4*tan(x) - 1 )/(tan(x)**4 + 4*tan(x)**3 - 6*tan(x)**2 - 4*tan(x) + 1) _test_extrig(cot, 2, (-1 + cot(1)**2)/(2*cot(1))) _test_extrig(cot, 3, (-3*cot(1) + cot(1)**3)/(-1 + 3*cot(1)**2)) def test_cot_AccumBounds(): assert cot(AccumBounds(-oo, oo)) == AccumBounds(-oo, oo) assert cot(AccumBounds(-S.Pi/3, S.Pi/3)) == AccumBounds(-oo, oo) assert cot(AccumBounds(S.Pi/6, S.Pi/3)) == AccumBounds(cot(S.Pi/3), cot(S.Pi/6)) def test_cot_fdiff(): assert cot(x).fdiff() == -cot(x)**2 - 1 raises(ArgumentIndexError, lambda: cot(x).fdiff(2)) def test_sinc(): assert isinstance(sinc(x), sinc) s = Symbol('s', zero=True) assert sinc(s) is S.One assert sinc(S.Infinity) is S.Zero assert sinc(S.NegativeInfinity) is S.Zero assert sinc(S.NaN) is S.NaN assert sinc(S.ComplexInfinity) is S.NaN n = Symbol('n', integer=True, nonzero=True) assert sinc(n*pi) is S.Zero assert sinc(-n*pi) is S.Zero assert sinc(pi/2) == 2 / pi assert sinc(-pi/2) == 2 / pi assert sinc(pi*Rational(5, 2)) == 2 / (5*pi) assert sinc(pi*Rational(7, 2)) == -2 / (7*pi) assert sinc(-x) == sinc(x) assert sinc(x).diff(x) == cos(x)/x - sin(x)/x**2 assert sinc(x).diff(x) == (sin(x)/x).diff(x) assert sinc(x).diff(x, x) == (-sin(x) - 2*cos(x)/x + 2*sin(x)/x**2)/x assert sinc(x).diff(x, x) == (sin(x)/x).diff(x, x) assert limit(sinc(x).diff(x), x, 0) == 0 assert limit(sinc(x).diff(x, x), x, 0) == -S(1)/3 # https://github.com/sympy/sympy/issues/11402 # # assert sinc(x).diff(x) == Piecewise(((x*cos(x) - sin(x)) / x**2, Ne(x, 0)), (0, True)) # # assert sinc(x).diff(x).equals(sinc(x).rewrite(sin).diff(x)) # # assert sinc(x).diff(x).subs(x, 0) is S.Zero assert sinc(x).series() == 1 - x**2/6 + x**4/120 + O(x**6) assert sinc(x).rewrite(jn) == jn(0, x) assert sinc(x).rewrite(sin) == Piecewise((sin(x)/x, Ne(x, 0)), (1, True)) assert sinc(pi, evaluate=False).is_zero is True assert sinc(0, evaluate=False).is_zero is False assert sinc(n*pi, evaluate=False).is_zero is True assert sinc(x).is_zero is None xr = Symbol('xr', real=True, nonzero=True) assert sinc(x).is_real is None assert sinc(xr).is_real is True assert sinc(I*xr).is_real is True assert sinc(I*100).is_real is True assert sinc(x).is_finite is None assert sinc(xr).is_finite is True def test_asin(): assert asin(nan) is nan assert asin.nargs == FiniteSet(1) assert asin(oo) == -I*oo assert asin(-oo) == I*oo assert asin(zoo) is zoo # Note: asin(-x) = - asin(x) assert asin(0) == 0 assert asin(1) == pi/2 assert asin(-1) == -pi/2 assert asin(sqrt(3)/2) == pi/3 assert asin(-sqrt(3)/2) == -pi/3 assert asin(sqrt(2)/2) == pi/4 assert asin(-sqrt(2)/2) == -pi/4 assert asin(sqrt((5 - sqrt(5))/8)) == pi/5 assert asin(-sqrt((5 - sqrt(5))/8)) == -pi/5 assert asin(S.Half) == pi/6 assert asin(Rational(-1, 2)) == -pi/6 assert asin((sqrt(2 - sqrt(2)))/2) == pi/8 assert asin(-(sqrt(2 - sqrt(2)))/2) == -pi/8 assert asin((sqrt(5) - 1)/4) == pi/10 assert asin(-(sqrt(5) - 1)/4) == -pi/10 assert asin((sqrt(3) - 1)/sqrt(2**3)) == pi/12 assert asin(-(sqrt(3) - 1)/sqrt(2**3)) == -pi/12 # check round-trip for exact values: for d in [5, 6, 8, 10, 12]: for n in range(-(d//2), d//2 + 1): if gcd(n, d) == 1: assert asin(sin(n*pi/d)) == n*pi/d assert asin(x).diff(x) == 1/sqrt(1 - x**2) assert asin(1/x).as_leading_term(x) == I*log(1/x) assert asin(0.2, evaluate=False).is_real is True assert asin(-2).is_real is False assert asin(r).is_real is None assert asin(-2*I) == -I*asinh(2) assert asin(Rational(1, 7), evaluate=False).is_positive is True assert asin(Rational(-1, 7), evaluate=False).is_positive is False assert asin(p).is_positive is None assert asin(sin(Rational(7, 2))) == Rational(-7, 2) + pi assert asin(sin(Rational(-7, 4))) == Rational(7, 4) - pi assert unchanged(asin, cos(x)) def test_asin_series(): assert asin(x).series(x, 0, 9) == \ x + x**3/6 + 3*x**5/40 + 5*x**7/112 + O(x**9) t5 = asin(x).taylor_term(5, x) assert t5 == 3*x**5/40 assert asin(x).taylor_term(7, x, t5, 0) == 5*x**7/112 def test_asin_rewrite(): assert asin(x).rewrite(log) == -I*log(I*x + sqrt(1 - x**2)) assert asin(x).rewrite(atan) == 2*atan(x/(1 + sqrt(1 - x**2))) assert asin(x).rewrite(acos) == S.Pi/2 - acos(x) assert asin(x).rewrite(acot) == 2*acot((sqrt(-x**2 + 1) + 1)/x) assert asin(x).rewrite(asec) == -asec(1/x) + pi/2 assert asin(x).rewrite(acsc) == acsc(1/x) def test_asin_fdiff(): assert asin(x).fdiff() == 1/sqrt(1 - x**2) raises(ArgumentIndexError, lambda: asin(x).fdiff(2)) def test_acos(): assert acos(nan) is nan assert acos(zoo) is zoo assert acos.nargs == FiniteSet(1) assert acos(oo) == I*oo assert acos(-oo) == -I*oo # Note: acos(-x) = pi - acos(x) assert acos(0) == pi/2 assert acos(S.Half) == pi/3 assert acos(Rational(-1, 2)) == pi*Rational(2, 3) assert acos(1) == 0 assert acos(-1) == pi assert acos(sqrt(2)/2) == pi/4 assert acos(-sqrt(2)/2) == pi*Rational(3, 4) # check round-trip for exact values: for d in [5, 6, 8, 10, 12]: for num in range(d): if gcd(num, d) == 1: assert acos(cos(num*pi/d)) == num*pi/d assert acos(2*I) == pi/2 - asin(2*I) assert acos(x).diff(x) == -1/sqrt(1 - x**2) assert acos(1/x).as_leading_term(x) == I*log(1/x) assert acos(0.2).is_real is True assert acos(-2).is_real is False assert acos(r).is_real is None assert acos(Rational(1, 7), evaluate=False).is_positive is True assert acos(Rational(-1, 7), evaluate=False).is_positive is True assert acos(Rational(3, 2), evaluate=False).is_positive is False assert acos(p).is_positive is None assert acos(2 + p).conjugate() != acos(10 + p) assert acos(-3 + n).conjugate() != acos(-3 + n) assert acos(Rational(1, 3)).conjugate() == acos(Rational(1, 3)) assert acos(Rational(-1, 3)).conjugate() == acos(Rational(-1, 3)) assert acos(p + n*I).conjugate() == acos(p - n*I) assert acos(z).conjugate() != acos(conjugate(z)) def test_acos_series(): assert acos(x).series(x, 0, 8) == \ pi/2 - x - x**3/6 - 3*x**5/40 - 5*x**7/112 + O(x**8) assert acos(x).series(x, 0, 8) == pi/2 - asin(x).series(x, 0, 8) t5 = acos(x).taylor_term(5, x) assert t5 == -3*x**5/40 assert acos(x).taylor_term(7, x, t5, 0) == -5*x**7/112 assert acos(x).taylor_term(0, x) == pi/2 assert acos(x).taylor_term(2, x) is S.Zero def test_acos_rewrite(): assert acos(x).rewrite(log) == pi/2 + I*log(I*x + sqrt(1 - x**2)) assert acos(x).rewrite(atan) == \ atan(sqrt(1 - x**2)/x) + (pi/2)*(1 - x*sqrt(1/x**2)) assert acos(0).rewrite(atan) == S.Pi/2 assert acos(0.5).rewrite(atan) == acos(0.5).rewrite(log) assert acos(x).rewrite(asin) == S.Pi/2 - asin(x) assert acos(x).rewrite(acot) == -2*acot((sqrt(-x**2 + 1) + 1)/x) + pi/2 assert acos(x).rewrite(asec) == asec(1/x) assert acos(x).rewrite(acsc) == -acsc(1/x) + pi/2 def test_acos_fdiff(): assert acos(x).fdiff() == -1/sqrt(1 - x**2) raises(ArgumentIndexError, lambda: acos(x).fdiff(2)) def test_atan(): assert atan(nan) is nan assert atan.nargs == FiniteSet(1) assert atan(oo) == pi/2 assert atan(-oo) == -pi/2 assert atan(zoo) == AccumBounds(-pi/2, pi/2) assert atan(0) == 0 assert atan(1) == pi/4 assert atan(sqrt(3)) == pi/3 assert atan(-(1 + sqrt(2))) == pi*Rational(-3, 8) assert atan(sqrt(5 - 2 * sqrt(5))) == pi/5 assert atan(-sqrt(1 - 2 * sqrt(5)/ 5)) == -pi/10 assert atan(sqrt(1 + 2 * sqrt(5) / 5)) == pi*Rational(3, 10) assert atan(-2 + sqrt(3)) == -pi/12 assert atan(2 + sqrt(3)) == pi*Rational(5, 12) assert atan(-2 - sqrt(3)) == pi*Rational(-5, 12) # check round-trip for exact values: for d in [5, 6, 8, 10, 12]: for num in range(-(d//2), d//2 + 1): if gcd(num, d) == 1: assert atan(tan(num*pi/d)) == num*pi/d assert atan(oo) == pi/2 assert atan(x).diff(x) == 1/(1 + x**2) assert atan(1/x).as_leading_term(x) == pi/2 assert atan(r).is_real is True assert atan(-2*I) == -I*atanh(2) assert unchanged(atan, cot(x)) assert atan(cot(Rational(1, 4))) == Rational(-1, 4) + pi/2 assert acot(Rational(1, 4)).is_rational is False for s in (x, p, n, np, nn, nz, ep, en, enp, enn, enz): if s.is_real or s.is_extended_real is None: assert s.is_nonzero is atan(s).is_nonzero assert s.is_positive is atan(s).is_positive assert s.is_negative is atan(s).is_negative assert s.is_nonpositive is atan(s).is_nonpositive assert s.is_nonnegative is atan(s).is_nonnegative else: assert s.is_extended_nonzero is atan(s).is_nonzero assert s.is_extended_positive is atan(s).is_positive assert s.is_extended_negative is atan(s).is_negative assert s.is_extended_nonpositive is atan(s).is_nonpositive assert s.is_extended_nonnegative is atan(s).is_nonnegative assert s.is_extended_nonzero is atan(s).is_extended_nonzero assert s.is_extended_positive is atan(s).is_extended_positive assert s.is_extended_negative is atan(s).is_extended_negative assert s.is_extended_nonpositive is atan(s).is_extended_nonpositive assert s.is_extended_nonnegative is atan(s).is_extended_nonnegative def test_atan_rewrite(): assert atan(x).rewrite(log) == I*(log(1 - I*x)-log(1 + I*x))/2 assert atan(x).rewrite(asin) == (-asin(1/sqrt(x**2 + 1)) + pi/2)*sqrt(x**2)/x assert atan(x).rewrite(acos) == sqrt(x**2)*acos(1/sqrt(x**2 + 1))/x assert atan(x).rewrite(acot) == acot(1/x) assert atan(x).rewrite(asec) == sqrt(x**2)*asec(sqrt(x**2 + 1))/x assert atan(x).rewrite(acsc) == (-acsc(sqrt(x**2 + 1)) + pi/2)*sqrt(x**2)/x assert atan(-5*I).evalf() == atan(x).rewrite(log).evalf(subs={x:-5*I}) assert atan(5*I).evalf() == atan(x).rewrite(log).evalf(subs={x:5*I}) def test_atan_fdiff(): assert atan(x).fdiff() == 1/(x**2 + 1) raises(ArgumentIndexError, lambda: atan(x).fdiff(2)) def test_atan2(): assert atan2.nargs == FiniteSet(2) assert atan2(0, 0) is S.NaN assert atan2(0, 1) == 0 assert atan2(1, 1) == pi/4 assert atan2(1, 0) == pi/2 assert atan2(1, -1) == pi*Rational(3, 4) assert atan2(0, -1) == pi assert atan2(-1, -1) == pi*Rational(-3, 4) assert atan2(-1, 0) == -pi/2 assert atan2(-1, 1) == -pi/4 i = symbols('i', imaginary=True) r = symbols('r', real=True) eq = atan2(r, i) ans = -I*log((i + I*r)/sqrt(i**2 + r**2)) reps = ((r, 2), (i, I)) assert eq.subs(reps) == ans.subs(reps) x = Symbol('x', negative=True) y = Symbol('y', negative=True) assert atan2(y, x) == atan(y/x) - pi y = Symbol('y', nonnegative=True) assert atan2(y, x) == atan(y/x) + pi y = Symbol('y') assert atan2(y, x) == atan2(y, x, evaluate=False) u = Symbol("u", positive=True) assert atan2(0, u) == 0 u = Symbol("u", negative=True) assert atan2(0, u) == pi assert atan2(y, oo) == 0 assert atan2(y, -oo)== 2*pi*Heaviside(re(y), S.Half) - pi assert atan2(y, x).rewrite(log) == -I*log((x + I*y)/sqrt(x**2 + y**2)) assert atan2(0, 0) is S.NaN ex = atan2(y, x) - arg(x + I*y) assert ex.subs({x:2, y:3}).rewrite(arg) == 0 assert ex.subs({x:2, y:3*I}).rewrite(arg) == -pi - I*log(sqrt(5)*I/5) assert ex.subs({x:2*I, y:3}).rewrite(arg) == -pi/2 - I*log(sqrt(5)*I) assert ex.subs({x:2*I, y:3*I}).rewrite(arg) == -pi + atan(Rational(2, 3)) + atan(Rational(3, 2)) i = symbols('i', imaginary=True) r = symbols('r', real=True) e = atan2(i, r) rewrite = e.rewrite(arg) reps = {i: I, r: -2} assert rewrite == -I*log(abs(I*i + r)/sqrt(abs(i**2 + r**2))) + arg((I*i + r)/sqrt(i**2 + r**2)) assert (e - rewrite).subs(reps).equals(0) assert atan2(0, x).rewrite(atan) == Piecewise((pi, re(x) < 0), (0, Ne(x, 0)), (nan, True)) assert atan2(0, r).rewrite(atan) == Piecewise((pi, r < 0), (0, Ne(r, 0)), (S.NaN, True)) assert atan2(0, i),rewrite(atan) == 0 assert atan2(0, r + i).rewrite(atan) == Piecewise((pi, r < 0), (0, True)) assert atan2(y, x).rewrite(atan) == Piecewise( (2*atan(y/(x + sqrt(x**2 + y**2))), Ne(y, 0)), (pi, re(x) < 0), (0, (re(x) > 0) | Ne(im(x), 0)), (nan, True)) assert conjugate(atan2(x, y)) == atan2(conjugate(x), conjugate(y)) assert diff(atan2(y, x), x) == -y/(x**2 + y**2) assert diff(atan2(y, x), y) == x/(x**2 + y**2) assert simplify(diff(atan2(y, x).rewrite(log), x)) == -y/(x**2 + y**2) assert simplify(diff(atan2(y, x).rewrite(log), y)) == x/(x**2 + y**2) assert str(atan2(1, 2).evalf(5)) == '0.46365' raises(ArgumentIndexError, lambda: atan2(x, y).fdiff(3)) def test_issue_17461(): class A(Symbol): is_extended_real = True def _eval_evalf(self, prec): return Float(5.0) x = A('X') y = A('Y') assert abs(atan2(x, y).evalf() - 0.785398163397448) <= 1e-10 def test_acot(): assert acot(nan) is nan assert acot.nargs == FiniteSet(1) assert acot(-oo) == 0 assert acot(oo) == 0 assert acot(zoo) == 0 assert acot(1) == pi/4 assert acot(0) == pi/2 assert acot(sqrt(3)/3) == pi/3 assert acot(1/sqrt(3)) == pi/3 assert acot(-1/sqrt(3)) == -pi/3 assert acot(x).diff(x) == -1/(1 + x**2) assert acot(1/x).as_leading_term(x) == x assert acot(r).is_extended_real is True assert acot(I*pi) == -I*acoth(pi) assert acot(-2*I) == I*acoth(2) assert acot(x).is_positive is None assert acot(n).is_positive is False assert acot(p).is_positive is True assert acot(I).is_positive is False assert acot(Rational(1, 4)).is_rational is False assert unchanged(acot, cot(x)) assert unchanged(acot, tan(x)) assert acot(cot(Rational(1, 4))) == Rational(1, 4) assert acot(tan(Rational(-1, 4))) == Rational(1, 4) - pi/2 def test_acot_rewrite(): assert acot(x).rewrite(log) == I*(log(1 - I/x)-log(1 + I/x))/2 assert acot(x).rewrite(asin) == x*(-asin(sqrt(-x**2)/sqrt(-x**2 - 1)) + pi/2)*sqrt(x**(-2)) assert acot(x).rewrite(acos) == x*sqrt(x**(-2))*acos(sqrt(-x**2)/sqrt(-x**2 - 1)) assert acot(x).rewrite(atan) == atan(1/x) assert acot(x).rewrite(asec) == x*sqrt(x**(-2))*asec(sqrt((x**2 + 1)/x**2)) assert acot(x).rewrite(acsc) == x*(-acsc(sqrt((x**2 + 1)/x**2)) + pi/2)*sqrt(x**(-2)) assert acot(-I/5).evalf() == acot(x).rewrite(log).evalf(subs={x:-I/5}) assert acot(I/5).evalf() == acot(x).rewrite(log).evalf(subs={x:I/5}) def test_acot_fdiff(): assert acot(x).fdiff() == -1/(x**2 + 1) raises(ArgumentIndexError, lambda: acot(x).fdiff(2)) def test_attributes(): assert sin(x).args == (x,) def test_sincos_rewrite(): assert sin(pi/2 - x) == cos(x) assert sin(pi - x) == sin(x) assert cos(pi/2 - x) == sin(x) assert cos(pi - x) == -cos(x) def _check_even_rewrite(func, arg): """Checks that the expr has been rewritten using f(-x) -> f(x) arg : -x """ return func(arg).args[0] == -arg def _check_odd_rewrite(func, arg): """Checks that the expr has been rewritten using f(-x) -> -f(x) arg : -x """ return func(arg).func.is_Mul def _check_no_rewrite(func, arg): """Checks that the expr is not rewritten""" return func(arg).args[0] == arg def test_evenodd_rewrite(): a = cos(2) # negative b = sin(1) # positive even = [cos] odd = [sin, tan, cot, asin, atan, acot] with_minus = [-1, -2**1024 * E, -pi/105, -x*y, -x - y] for func in even: for expr in with_minus: assert _check_even_rewrite(func, expr) assert _check_no_rewrite(func, a*b) assert func( x - y) == func(y - x) # it doesn't matter which form is canonical for func in odd: for expr in with_minus: assert _check_odd_rewrite(func, expr) assert _check_no_rewrite(func, a*b) assert func( x - y) == -func(y - x) # it doesn't matter which form is canonical def test_issue_4547(): assert sin(x).rewrite(cot) == 2*cot(x/2)/(1 + cot(x/2)**2) assert cos(x).rewrite(cot) == -(1 - cot(x/2)**2)/(1 + cot(x/2)**2) assert tan(x).rewrite(cot) == 1/cot(x) assert cot(x).fdiff() == -1 - cot(x)**2 def test_as_leading_term_issue_5272(): assert sin(x).as_leading_term(x) == x assert cos(x).as_leading_term(x) == 1 assert tan(x).as_leading_term(x) == x assert cot(x).as_leading_term(x) == 1/x assert asin(x).as_leading_term(x) == x assert acos(x).as_leading_term(x) == pi/2 assert atan(x).as_leading_term(x) == x assert acot(x).as_leading_term(x) == pi/2 def test_leading_terms(): assert sin(1/x).as_leading_term(x) == AccumBounds(-1, 1) assert sin(S.Half).as_leading_term(x) == sin(S.Half) assert cos(1/x).as_leading_term(x) == AccumBounds(-1, 1) assert cos(S.Half).as_leading_term(x) == cos(S.Half) assert sec(1/x).as_leading_term(x) == AccumBounds(S.NegativeInfinity, S.Infinity) assert csc(1/x).as_leading_term(x) == AccumBounds(S.NegativeInfinity, S.Infinity) assert tan(1/x).as_leading_term(x) == AccumBounds(S.NegativeInfinity, S.Infinity) assert cot(1/x).as_leading_term(x) == AccumBounds(S.NegativeInfinity, S.Infinity) # https://github.com/sympy/sympy/issues/21038 f = sin(pi*(x + 4))/(3*x) assert f.as_leading_term(x) == pi/3 def test_atan2_expansion(): assert cancel(atan2(x**2, x + 1).diff(x) - atan(x**2/(x + 1)).diff(x)) == 0 assert cancel(atan(y/x).series(y, 0, 5) - atan2(y, x).series(y, 0, 5) + atan2(0, x) - atan(0)) == O(y**5) assert cancel(atan(y/x).series(x, 1, 4) - atan2(y, x).series(x, 1, 4) + atan2(y, 1) - atan(y)) == O((x - 1)**4, (x, 1)) assert cancel(atan((y + x)/x).series(x, 1, 3) - atan2(y + x, x).series(x, 1, 3) + atan2(1 + y, 1) - atan(1 + y)) == O((x - 1)**3, (x, 1)) assert Matrix([atan2(y, x)]).jacobian([y, x]) == \ Matrix([[x/(y**2 + x**2), -y/(y**2 + x**2)]]) def test_aseries(): def t(n, v, d, e): assert abs( n(1/v).evalf() - n(1/x).series(x, dir=d).removeO().subs(x, v)) < e t(atan, 0.1, '+', 1e-5) t(atan, -0.1, '-', 1e-5) t(acot, 0.1, '+', 1e-5) t(acot, -0.1, '-', 1e-5) def test_issue_4420(): i = Symbol('i', integer=True) e = Symbol('e', even=True) o = Symbol('o', odd=True) # unknown parity for variable assert cos(4*i*pi) == 1 assert sin(4*i*pi) == 0 assert tan(4*i*pi) == 0 assert cot(4*i*pi) is zoo assert cos(3*i*pi) == cos(pi*i) # +/-1 assert sin(3*i*pi) == 0 assert tan(3*i*pi) == 0 assert cot(3*i*pi) is zoo assert cos(4.0*i*pi) == 1 assert sin(4.0*i*pi) == 0 assert tan(4.0*i*pi) == 0 assert cot(4.0*i*pi) is zoo assert cos(3.0*i*pi) == cos(pi*i) # +/-1 assert sin(3.0*i*pi) == 0 assert tan(3.0*i*pi) == 0 assert cot(3.0*i*pi) is zoo assert cos(4.5*i*pi) == cos(0.5*pi*i) assert sin(4.5*i*pi) == sin(0.5*pi*i) assert tan(4.5*i*pi) == tan(0.5*pi*i) assert cot(4.5*i*pi) == cot(0.5*pi*i) # parity of variable is known assert cos(4*e*pi) == 1 assert sin(4*e*pi) == 0 assert tan(4*e*pi) == 0 assert cot(4*e*pi) is zoo assert cos(3*e*pi) == 1 assert sin(3*e*pi) == 0 assert tan(3*e*pi) == 0 assert cot(3*e*pi) is zoo assert cos(4.0*e*pi) == 1 assert sin(4.0*e*pi) == 0 assert tan(4.0*e*pi) == 0 assert cot(4.0*e*pi) is zoo assert cos(3.0*e*pi) == 1 assert sin(3.0*e*pi) == 0 assert tan(3.0*e*pi) == 0 assert cot(3.0*e*pi) is zoo assert cos(4.5*e*pi) == cos(0.5*pi*e) assert sin(4.5*e*pi) == sin(0.5*pi*e) assert tan(4.5*e*pi) == tan(0.5*pi*e) assert cot(4.5*e*pi) == cot(0.5*pi*e) assert cos(4*o*pi) == 1 assert sin(4*o*pi) == 0 assert tan(4*o*pi) == 0 assert cot(4*o*pi) is zoo assert cos(3*o*pi) == -1 assert sin(3*o*pi) == 0 assert tan(3*o*pi) == 0 assert cot(3*o*pi) is zoo assert cos(4.0*o*pi) == 1 assert sin(4.0*o*pi) == 0 assert tan(4.0*o*pi) == 0 assert cot(4.0*o*pi) is zoo assert cos(3.0*o*pi) == -1 assert sin(3.0*o*pi) == 0 assert tan(3.0*o*pi) == 0 assert cot(3.0*o*pi) is zoo assert cos(4.5*o*pi) == cos(0.5*pi*o) assert sin(4.5*o*pi) == sin(0.5*pi*o) assert tan(4.5*o*pi) == tan(0.5*pi*o) assert cot(4.5*o*pi) == cot(0.5*pi*o) # x could be imaginary assert cos(4*x*pi) == cos(4*pi*x) assert sin(4*x*pi) == sin(4*pi*x) assert tan(4*x*pi) == tan(4*pi*x) assert cot(4*x*pi) == cot(4*pi*x) assert cos(3*x*pi) == cos(3*pi*x) assert sin(3*x*pi) == sin(3*pi*x) assert tan(3*x*pi) == tan(3*pi*x) assert cot(3*x*pi) == cot(3*pi*x) assert cos(4.0*x*pi) == cos(4.0*pi*x) assert sin(4.0*x*pi) == sin(4.0*pi*x) assert tan(4.0*x*pi) == tan(4.0*pi*x) assert cot(4.0*x*pi) == cot(4.0*pi*x) assert cos(3.0*x*pi) == cos(3.0*pi*x) assert sin(3.0*x*pi) == sin(3.0*pi*x) assert tan(3.0*x*pi) == tan(3.0*pi*x) assert cot(3.0*x*pi) == cot(3.0*pi*x) assert cos(4.5*x*pi) == cos(4.5*pi*x) assert sin(4.5*x*pi) == sin(4.5*pi*x) assert tan(4.5*x*pi) == tan(4.5*pi*x) assert cot(4.5*x*pi) == cot(4.5*pi*x) def test_inverses(): raises(AttributeError, lambda: sin(x).inverse()) raises(AttributeError, lambda: cos(x).inverse()) assert tan(x).inverse() == atan assert cot(x).inverse() == acot raises(AttributeError, lambda: csc(x).inverse()) raises(AttributeError, lambda: sec(x).inverse()) assert asin(x).inverse() == sin assert acos(x).inverse() == cos assert atan(x).inverse() == tan assert acot(x).inverse() == cot def test_real_imag(): a, b = symbols('a b', real=True) z = a + b*I for deep in [True, False]: assert sin( z).as_real_imag(deep=deep) == (sin(a)*cosh(b), cos(a)*sinh(b)) assert cos( z).as_real_imag(deep=deep) == (cos(a)*cosh(b), -sin(a)*sinh(b)) assert tan(z).as_real_imag(deep=deep) == (sin(2*a)/(cos(2*a) + cosh(2*b)), sinh(2*b)/(cos(2*a) + cosh(2*b))) assert cot(z).as_real_imag(deep=deep) == (-sin(2*a)/(cos(2*a) - cosh(2*b)), sinh(2*b)/(cos(2*a) - cosh(2*b))) assert sin(a).as_real_imag(deep=deep) == (sin(a), 0) assert cos(a).as_real_imag(deep=deep) == (cos(a), 0) assert tan(a).as_real_imag(deep=deep) == (tan(a), 0) assert cot(a).as_real_imag(deep=deep) == (cot(a), 0) @XFAIL def test_sin_cos_with_infinity(): # Test for issue 5196 # https://github.com/sympy/sympy/issues/5196 assert sin(oo) is S.NaN assert cos(oo) is S.NaN @slow def test_sincos_rewrite_sqrt(): # equivalent to testing rewrite(pow) for p in [1, 3, 5, 17]: for t in [1, 8]: n = t*p # The vertices `exp(i*pi/n)` of a regular `n`-gon can # be expressed by means of nested square roots if and # only if `n` is a product of Fermat primes, `p`, and # powers of 2, `t'. The code aims to check all vertices # not belonging to an `m`-gon for `m < n`(`gcd(i, n) == 1`). # For large `n` this makes the test too slow, therefore # the vertices are limited to those of index `i < 10`. for i in range(1, min((n + 1)//2 + 1, 10)): if 1 == gcd(i, n): x = i*pi/n s1 = sin(x).rewrite(sqrt) c1 = cos(x).rewrite(sqrt) assert not s1.has(cos, sin), "fails for %d*pi/%d" % (i, n) assert not c1.has(cos, sin), "fails for %d*pi/%d" % (i, n) assert 1e-3 > abs(sin(x.evalf(5)) - s1.evalf(2)), "fails for %d*pi/%d" % (i, n) assert 1e-3 > abs(cos(x.evalf(5)) - c1.evalf(2)), "fails for %d*pi/%d" % (i, n) assert cos(pi/14).rewrite(sqrt) == sqrt(cos(pi/7)/2 + S.Half) assert cos(pi/257).rewrite(sqrt).evalf(64) == cos(pi/257).evalf(64) assert cos(pi*Rational(-15, 2)/11, evaluate=False).rewrite( sqrt) == -sqrt(-cos(pi*Rational(4, 11))/2 + S.Half) assert cos(Mul(2, pi, S.Half, evaluate=False), evaluate=False).rewrite( sqrt) == -1 e = cos(pi/3/17) # don't use pi/15 since that is caught at instantiation a = ( -3*sqrt(-sqrt(17) + 17)*sqrt(sqrt(17) + 17)/64 - 3*sqrt(34)*sqrt(sqrt(17) + 17)/128 - sqrt(sqrt(17) + 17)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) + 17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/64 - sqrt(-sqrt(17) + 17)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) + 17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/128 - Rational(1, 32) + sqrt(2)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) + 17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/64 + 3*sqrt(2)*sqrt(sqrt(17) + 17)/128 + sqrt(34)*sqrt(-sqrt(17) + 17)/128 + 13*sqrt(2)*sqrt(-sqrt(17) + 17)/128 + sqrt(17)*sqrt(-sqrt(17) + 17)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) + 17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/128 + 5*sqrt(17)/32 + sqrt(3)*sqrt(-sqrt(2)*sqrt(sqrt(17) + 17)*sqrt(sqrt(17)/32 + sqrt(2)*sqrt(-sqrt(17) + 17)/32 + sqrt(2)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) + 17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/32 + Rational(15, 32))/8 - 5*sqrt(2)*sqrt(sqrt(17)/32 + sqrt(2)*sqrt(-sqrt(17) + 17)/32 + sqrt(2)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) + 17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/32 + Rational(15, 32))*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) + 17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/64 - 3*sqrt(2)*sqrt(-sqrt(17) + 17)*sqrt(sqrt(17)/32 + sqrt(2)*sqrt(-sqrt(17) + 17)/32 + sqrt(2)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) + 17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/32 + Rational(15, 32))/32 + sqrt(34)*sqrt(sqrt(17)/32 + sqrt(2)*sqrt(-sqrt(17) + 17)/32 + sqrt(2)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) + 17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/32 + Rational(15, 32))*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) + 17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/64 + sqrt(sqrt(17)/32 + sqrt(2)*sqrt(-sqrt(17) + 17)/32 + sqrt(2)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) + 17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/32 + Rational(15, 32))/2 + S.Half + sqrt(-sqrt(17) + 17)*sqrt(sqrt(17)/32 + sqrt(2)*sqrt(-sqrt(17) + 17)/32 + sqrt(2)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) + 17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/32 + Rational(15, 32))*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) + 17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/32 + sqrt(34)*sqrt(-sqrt(17) + 17)*sqrt(sqrt(17)/32 + sqrt(2)*sqrt(-sqrt(17) + 17)/32 + sqrt(2)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) + 17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/32 + Rational(15, 32))/32)/2) assert e.rewrite(sqrt) == a assert e.n() == a.n() # coverage of fermatCoords: multiplicity > 1; the following could be # different but that portion of the code should be tested in some way assert cos(pi/9/17).rewrite(sqrt) == \ sin(pi/9)*sin(pi*Rational(2, 17)) + cos(pi/9)*cos(pi*Rational(2, 17)) @slow def test_tancot_rewrite_sqrt(): # equivalent to testing rewrite(pow) for p in [1, 3, 5, 17]: for t in [1, 8]: n = t*p for i in range(1, min((n + 1)//2 + 1, 10)): if 1 == gcd(i, n): x = i*pi/n if 2*i != n and 3*i != 2*n: t1 = tan(x).rewrite(sqrt) assert not t1.has(cot, tan), "fails for %d*pi/%d" % (i, n) assert 1e-3 > abs( tan(x.evalf(7)) - t1.evalf(4) ), "fails for %d*pi/%d" % (i, n) if i != 0 and i != n: c1 = cot(x).rewrite(sqrt) assert not c1.has(cot, tan), "fails for %d*pi/%d" % (i, n) assert 1e-3 > abs( cot(x.evalf(7)) - c1.evalf(4) ), "fails for %d*pi/%d" % (i, n) def test_sec(): x = symbols('x', real=True) z = symbols('z') assert sec.nargs == FiniteSet(1) assert sec(zoo) is nan assert sec(0) == 1 assert sec(pi) == -1 assert sec(pi/2) is zoo assert sec(-pi/2) is zoo assert sec(pi/6) == 2*sqrt(3)/3 assert sec(pi/3) == 2 assert sec(pi*Rational(5, 2)) is zoo assert sec(pi*Rational(9, 7)) == -sec(pi*Rational(2, 7)) assert sec(pi*Rational(3, 4)) == -sqrt(2) # issue 8421 assert sec(I) == 1/cosh(1) assert sec(x*I) == 1/cosh(x) assert sec(-x) == sec(x) assert sec(asec(x)) == x assert sec(z).conjugate() == sec(conjugate(z)) assert (sec(z).as_real_imag() == (cos(re(z))*cosh(im(z))/(sin(re(z))**2*sinh(im(z))**2 + cos(re(z))**2*cosh(im(z))**2), sin(re(z))*sinh(im(z))/(sin(re(z))**2*sinh(im(z))**2 + cos(re(z))**2*cosh(im(z))**2))) assert sec(x).expand(trig=True) == 1/cos(x) assert sec(2*x).expand(trig=True) == 1/(2*cos(x)**2 - 1) assert sec(x).is_extended_real == True assert sec(z).is_real == None assert sec(a).is_algebraic is None assert sec(na).is_algebraic is False assert sec(x).as_leading_term() == sec(x) assert sec(0, evaluate=False).is_finite == True assert sec(x).is_finite == None assert sec(pi/2, evaluate=False).is_finite == False assert series(sec(x), x, x0=0, n=6) == 1 + x**2/2 + 5*x**4/24 + O(x**6) # https://github.com/sympy/sympy/issues/7166 assert series(sqrt(sec(x))) == 1 + x**2/4 + 7*x**4/96 + O(x**6) # https://github.com/sympy/sympy/issues/7167 assert (series(sqrt(sec(x)), x, x0=pi*3/2, n=4) == 1/sqrt(x - pi*Rational(3, 2)) + (x - pi*Rational(3, 2))**Rational(3, 2)/12 + (x - pi*Rational(3, 2))**Rational(7, 2)/160 + O((x - pi*Rational(3, 2))**4, (x, pi*Rational(3, 2)))) assert sec(x).diff(x) == tan(x)*sec(x) # Taylor Term checks assert sec(z).taylor_term(4, z) == 5*z**4/24 assert sec(z).taylor_term(6, z) == 61*z**6/720 assert sec(z).taylor_term(5, z) == 0 def test_sec_rewrite(): assert sec(x).rewrite(exp) == 1/(exp(I*x)/2 + exp(-I*x)/2) assert sec(x).rewrite(cos) == 1/cos(x) assert sec(x).rewrite(tan) == (tan(x/2)**2 + 1)/(-tan(x/2)**2 + 1) assert sec(x).rewrite(pow) == sec(x) assert sec(x).rewrite(sqrt) == sec(x) assert sec(z).rewrite(cot) == (cot(z/2)**2 + 1)/(cot(z/2)**2 - 1) assert sec(x).rewrite(sin) == 1 / sin(x + pi / 2, evaluate=False) assert sec(x).rewrite(tan) == (tan(x / 2)**2 + 1) / (-tan(x / 2)**2 + 1) assert sec(x).rewrite(csc) == csc(-x + pi/2, evaluate=False) def test_sec_fdiff(): assert sec(x).fdiff() == tan(x)*sec(x) raises(ArgumentIndexError, lambda: sec(x).fdiff(2)) def test_csc(): x = symbols('x', real=True) z = symbols('z') # https://github.com/sympy/sympy/issues/6707 cosecant = csc('x') alternate = 1/sin('x') assert cosecant.equals(alternate) == True assert alternate.equals(cosecant) == True assert csc.nargs == FiniteSet(1) assert csc(0) is zoo assert csc(pi) is zoo assert csc(zoo) is nan assert csc(pi/2) == 1 assert csc(-pi/2) == -1 assert csc(pi/6) == 2 assert csc(pi/3) == 2*sqrt(3)/3 assert csc(pi*Rational(5, 2)) == 1 assert csc(pi*Rational(9, 7)) == -csc(pi*Rational(2, 7)) assert csc(pi*Rational(3, 4)) == sqrt(2) # issue 8421 assert csc(I) == -I/sinh(1) assert csc(x*I) == -I/sinh(x) assert csc(-x) == -csc(x) assert csc(acsc(x)) == x assert csc(z).conjugate() == csc(conjugate(z)) assert (csc(z).as_real_imag() == (sin(re(z))*cosh(im(z))/(sin(re(z))**2*cosh(im(z))**2 + cos(re(z))**2*sinh(im(z))**2), -cos(re(z))*sinh(im(z))/(sin(re(z))**2*cosh(im(z))**2 + cos(re(z))**2*sinh(im(z))**2))) assert csc(x).expand(trig=True) == 1/sin(x) assert csc(2*x).expand(trig=True) == 1/(2*sin(x)*cos(x)) assert csc(x).is_extended_real == True assert csc(z).is_real == None assert csc(a).is_algebraic is None assert csc(na).is_algebraic is False assert csc(x).as_leading_term() == csc(x) assert csc(0, evaluate=False).is_finite == False assert csc(x).is_finite == None assert csc(pi/2, evaluate=False).is_finite == True assert series(csc(x), x, x0=pi/2, n=6) == \ 1 + (x - pi/2)**2/2 + 5*(x - pi/2)**4/24 + O((x - pi/2)**6, (x, pi/2)) assert series(csc(x), x, x0=0, n=6) == \ 1/x + x/6 + 7*x**3/360 + 31*x**5/15120 + O(x**6) assert csc(x).diff(x) == -cot(x)*csc(x) assert csc(x).taylor_term(2, x) == 0 assert csc(x).taylor_term(3, x) == 7*x**3/360 assert csc(x).taylor_term(5, x) == 31*x**5/15120 raises(ArgumentIndexError, lambda: csc(x).fdiff(2)) def test_asec(): z = Symbol('z', zero=True) assert asec(z) is zoo assert asec(nan) is nan assert asec(1) == 0 assert asec(-1) == pi assert asec(oo) == pi/2 assert asec(-oo) == pi/2 assert asec(zoo) == pi/2 assert asec(sec(pi*Rational(13, 4))) == pi*Rational(3, 4) assert asec(1 + sqrt(5)) == pi*Rational(2, 5) assert asec(2/sqrt(3)) == pi/6 assert asec(sqrt(4 - 2*sqrt(2))) == pi/8 assert asec(-sqrt(4 + 2*sqrt(2))) == pi*Rational(5, 8) assert asec(sqrt(2 + 2*sqrt(5)/5)) == pi*Rational(3, 10) assert asec(-sqrt(2 + 2*sqrt(5)/5)) == pi*Rational(7, 10) assert asec(sqrt(2) - sqrt(6)) == pi*Rational(11, 12) assert asec(x).diff(x) == 1/(x**2*sqrt(1 - 1/x**2)) assert asec(x).as_leading_term(x) == I*log(x) assert asec(x).rewrite(log) == I*log(sqrt(1 - 1/x**2) + I/x) + pi/2 assert asec(x).rewrite(asin) == -asin(1/x) + pi/2 assert asec(x).rewrite(acos) == acos(1/x) assert asec(x).rewrite(atan) == (2*atan(x + sqrt(x**2 - 1)) - pi/2)*sqrt(x**2)/x assert asec(x).rewrite(acot) == (2*acot(x - sqrt(x**2 - 1)) - pi/2)*sqrt(x**2)/x assert asec(x).rewrite(acsc) == -acsc(x) + pi/2 raises(ArgumentIndexError, lambda: asec(x).fdiff(2)) def test_asec_is_real(): assert asec(S.Half).is_real is False n = Symbol('n', positive=True, integer=True) assert asec(n).is_extended_real is True assert asec(x).is_real is None assert asec(r).is_real is None t = Symbol('t', real=False, finite=True) assert asec(t).is_real is False def test_acsc(): assert acsc(nan) is nan assert acsc(1) == pi/2 assert acsc(-1) == -pi/2 assert acsc(oo) == 0 assert acsc(-oo) == 0 assert acsc(zoo) == 0 assert acsc(0) is zoo assert acsc(csc(3)) == -3 + pi assert acsc(csc(4)) == -4 + pi assert acsc(csc(6)) == 6 - 2*pi assert unchanged(acsc, csc(x)) assert unchanged(acsc, sec(x)) assert acsc(2/sqrt(3)) == pi/3 assert acsc(csc(pi*Rational(13, 4))) == -pi/4 assert acsc(sqrt(2 + 2*sqrt(5)/5)) == pi/5 assert acsc(-sqrt(2 + 2*sqrt(5)/5)) == -pi/5 assert acsc(-2) == -pi/6 assert acsc(-sqrt(4 + 2*sqrt(2))) == -pi/8 assert acsc(sqrt(4 - 2*sqrt(2))) == pi*Rational(3, 8) assert acsc(1 + sqrt(5)) == pi/10 assert acsc(sqrt(2) - sqrt(6)) == pi*Rational(-5, 12) assert acsc(x).diff(x) == -1/(x**2*sqrt(1 - 1/x**2)) assert acsc(x).as_leading_term(x) == I*log(x) assert acsc(x).rewrite(log) == -I*log(sqrt(1 - 1/x**2) + I/x) assert acsc(x).rewrite(asin) == asin(1/x) assert acsc(x).rewrite(acos) == -acos(1/x) + pi/2 assert acsc(x).rewrite(atan) == (-atan(sqrt(x**2 - 1)) + pi/2)*sqrt(x**2)/x assert acsc(x).rewrite(acot) == (-acot(1/sqrt(x**2 - 1)) + pi/2)*sqrt(x**2)/x assert acsc(x).rewrite(asec) == -asec(x) + pi/2 raises(ArgumentIndexError, lambda: acsc(x).fdiff(2)) def test_csc_rewrite(): assert csc(x).rewrite(pow) == csc(x) assert csc(x).rewrite(sqrt) == csc(x) assert csc(x).rewrite(exp) == 2*I/(exp(I*x) - exp(-I*x)) assert csc(x).rewrite(sin) == 1/sin(x) assert csc(x).rewrite(tan) == (tan(x/2)**2 + 1)/(2*tan(x/2)) assert csc(x).rewrite(cot) == (cot(x/2)**2 + 1)/(2*cot(x/2)) assert csc(x).rewrite(cos) == 1/cos(x - pi/2, evaluate=False) assert csc(x).rewrite(sec) == sec(-x + pi/2, evaluate=False) # issue 17349 assert csc(1 - exp(-besselj(I, I))).rewrite(cos) == \ -1/cos(-pi/2 - 1 + cos(I*besselj(I, I)) + I*cos(-pi/2 + I*besselj(I, I), evaluate=False), evaluate=False) def test_inverses_nseries(): assert asin(x + 2)._eval_nseries(x, 4, None, I) == -asin(2) + pi + sqrt(3)*I*x/3 - sqrt(3)*I*x**2/9 + \ sqrt(3)*I*x**3/18 + O(x**4) assert asin(x + 2)._eval_nseries(x, 4, None, -I) == asin(2) - sqrt(3)*I*x/3 + sqrt(3)*I*x**2/9 - sqrt(3)*I*x**3/18 + O(x**4) assert asin(x - 2)._eval_nseries(x, 4, None, I) == -asin(2) - sqrt(3)*I*x/3 - sqrt(3)*I*x**2/9 - sqrt(3)*I*x**3/18 + O(x**4) assert asin(x - 2)._eval_nseries(x, 4, None, -I) == asin(2) - pi + sqrt(3)*I*x/3 + sqrt(3)*I*x**2/9 + \ sqrt(3)*I*x**3/18 + O(x**4) assert asin(I*x + I*x**3 + 2)._eval_nseries(x, 3, None, 1) == -asin(2) + pi - sqrt(3)*x/3 + sqrt(3)*I*x**2/9 + O(x**3) assert asin(I*x + I*x**3 + 2)._eval_nseries(x, 3, None, -1) == asin(2) + sqrt(3)*x/3 - sqrt(3)*I*x**2/9 + O(x**3) assert asin(I*x + I*x**3 - 2)._eval_nseries(x, 3, None, 1) == -asin(2) + sqrt(3)*x/3 + sqrt(3)*I*x**2/9 + O(x**3) assert asin(I*x + I*x**3 - 2)._eval_nseries(x, 3, None, -1) == asin(2) - pi - sqrt(3)*x/3 - sqrt(3)*I*x**2/9 + O(x**3) assert asin(I*x**2 + I*x**3 + 2)._eval_nseries(x, 3, None, 1) == -asin(2) + pi - sqrt(3)*x**2/3 + O(x**3) assert asin(I*x**2 + I*x**3 + 2)._eval_nseries(x, 3, None, -1) == -asin(2) + pi - sqrt(3)*x**2/3 + O(x**3) assert asin(I*x**2 + I*x**3 - 2)._eval_nseries(x, 3, None, 1) == -asin(2) + sqrt(3)*x**2/3 + O(x**3) assert asin(I*x**2 + I*x**3 - 2)._eval_nseries(x, 3, None, -1) == -asin(2) + sqrt(3)*x**2/3 + O(x**3) assert asin(1 + x)._eval_nseries(x, 3, None) == pi/2 - sqrt(2)*sqrt(-x) - \ sqrt(2)*(-x)**(S(3)/2)/12 - 3*sqrt(2)*(-x)**(S(5)/2)/160 + O(x**3) assert asin(-1 + x)._eval_nseries(x, 3, None) == -pi/2 + sqrt(2)*sqrt(x) + \ sqrt(2)*x**(S(3)/2)/12 + 3*sqrt(2)*x**(S(5)/2)/160 + O(x**3) assert asin(exp(x))._eval_nseries(x, 3, None) == pi/2 - sqrt(2)*sqrt(-x) + \ sqrt(2)*(-x)**(S(3)/2)/6 - sqrt(2)*(-x)**(S(5)/2)/120 + O(x**3) assert asin(-exp(x))._eval_nseries(x, 3, None) == -pi/2 + sqrt(2)*sqrt(-x) - \ sqrt(2)*(-x)**(S(3)/2)/6 + sqrt(2)*(-x)**(S(5)/2)/120 + O(x**3) assert acos(x + 2)._eval_nseries(x, 4, None, I) == -acos(2) - sqrt(3)*I*x/3 + sqrt(3)*I*x**2/9 - sqrt(3)*I*x**3/18 + O(x**4) assert acos(x + 2)._eval_nseries(x, 4, None, -I) == acos(2) + sqrt(3)*I*x/3 - sqrt(3)*I*x**2/9 + sqrt(3)*I*x**3/18 + O(x**4) assert acos(x - 2)._eval_nseries(x, 4, None, I) == acos(-2) + sqrt(3)*I*x/3 + sqrt(3)*I*x**2/9 + sqrt(3)*I*x**3/18 + O(x**4) assert acos(x - 2)._eval_nseries(x, 4, None, -I) == -acos(-2) + 2*pi - sqrt(3)*I*x/3 - \ sqrt(3)*I*x**2/9 - sqrt(3)*I*x**3/18 + O(x**4) # assert acos(I*x + I*x**3 + 2)._eval_nseries(x, 3, None, 1) == -acos(2) + sqrt(3)*x/3 - sqrt(3)*I*x**2/9 + O(x**3) # assert acos(I*x + I*x**3 + 2)._eval_nseries(x, 3, None, -1) == acos(2) - sqrt(3)*x/3 + sqrt(3)*I*x**2/9 + O(x**3) # assert acos(I*x + I*x**3 - 2)._eval_nseries(x, 3, None, 1) == acos(-2) - sqrt(3)*x/3 - sqrt(3)*I*x**2/9 + O(x**3) # assert acos(I*x + I*x**3 - 2)._eval_nseries(x, 3, None, -1) == -acos(-2) + 2*pi + sqrt(3)*x/3 + sqrt(3)*I*x**2/9 + O(x**3) # assert acos(I*x**2 + I*x**3 + 2)._eval_nseries(x, 3, None, 1) == -acos(2) + sqrt(3)*x**2/3 + O(x**3) # assert acos(I*x**2 + I*x**3 + 2)._eval_nseries(x, 3, None, -1) == -acos(2) + sqrt(3)*x**2/3 + O(x**3) # assert acos(I*x**2 + I*x**3 - 2)._eval_nseries(x, 3, None, 1) == acos(-2) - sqrt(3)*x**2/3 + O(x**3) # assert acos(I*x**2 + I*x**3 - 2)._eval_nseries(x, 3, None, -1) == acos(-2) - sqrt(3)*x**2/3 + O(x**3) # assert acos(1 + x)._eval_nseries(x, 3, None) == sqrt(2)*sqrt(-x) + sqrt(2)*(-x)**(S(3)/2)/12 + 3*sqrt(2)*(-x)**(S(5)/2)/160 + O(x**3) # assert acos(-1 + x)._eval_nseries(x, 3, None) == pi - sqrt(2)*sqrt(x) - sqrt(2)*x**(S(3)/2)/12 - 3*sqrt(2)*x**(S(5)/2)/160 + O(x**3) # assert acos(exp(x))._eval_nseries(x, 3, None) == sqrt(2)*sqrt(-x) - sqrt(2)*(-x)**(S(3)/2)/6 + sqrt(2)*(-x)**(S(5)/2)/120 + O(x**3) # assert acos(-exp(x))._eval_nseries(x, 3, None) == pi - sqrt(2)*sqrt(-x) + sqrt(2)*(-x)**(S(3)/2)/6 - sqrt(2)*(-x)**(S(5)/2)/120 + O(x**3) assert atan(x + 2*I)._eval_nseries(x, 4, None, 1) == I*atanh(2) - x/3 - 2*I*x**2/9 + 13*x**3/81 + O(x**4) assert atan(x + 2*I)._eval_nseries(x, 4, None, -1) == I*atanh(2) - pi - x/3 - 2*I*x**2/9 + 13*x**3/81 + O(x**4) assert atan(x - 2*I)._eval_nseries(x, 4, None, 1) == -I*atanh(2) + pi - x/3 + 2*I*x**2/9 + 13*x**3/81 + O(x**4) assert atan(x - 2*I)._eval_nseries(x, 4, None, -1) == -I*atanh(2) - x/3 + 2*I*x**2/9 + 13*x**3/81 + O(x**4) # assert atan(x**2 + 2*I)._eval_nseries(x, 3, None, 1) == I*atanh(2) - x**2/3 + O(x**3) # assert atan(x**2 + 2*I)._eval_nseries(x, 3, None, -1) == I*atanh(2) - x**2/3 + O(x**3) # assert atan(x**2 - 2*I)._eval_nseries(x, 3, None, 1) == -I*atanh(2) + pi - x**2/3 + O(x**3) # assert atan(x**2 - 2*I)._eval_nseries(x, 3, None, -1) == -I*atanh(2) + pi - x**2/3 + O(x**3) assert atan(1/x)._eval_nseries(x, 2, None, 1) == pi/2 - x + O(x**2) assert atan(1/x)._eval_nseries(x, 2, None, -1) == -pi/2 - x + O(x**2) assert acot(x + S(1)/2*I)._eval_nseries(x, 4, None, 1) == -I*acoth(S(1)/2) + pi - 4*x/3 + 8*I*x**2/9 + 112*x**3/81 + O(x**4) assert acot(x + S(1)/2*I)._eval_nseries(x, 4, None, -1) == -I*acoth(S(1)/2) - 4*x/3 + 8*I*x**2/9 + 112*x**3/81 + O(x**4) assert acot(x - S(1)/2*I)._eval_nseries(x, 4, None, 1) == I*acoth(S(1)/2) - 4*x/3 - 8*I*x**2/9 + 112*x**3/81 + O(x**4) assert acot(x - S(1)/2*I)._eval_nseries(x, 4, None, -1) == I*acoth(S(1)/2) - pi - 4*x/3 - 8*I*x**2/9 + 112*x**3/81 + O(x**4) # assert acot(x**2 + S(1)/2*I)._eval_nseries(x, 3, None, 1) == -I*acoth(S(1)/2) + pi - 4*x**2/3 + O(x**3) # assert acot(x**2 + S(1)/2*I)._eval_nseries(x, 3, None, -1) == -I*acoth(S(1)/2) + pi - 4*x**2/3 + O(x**3) # assert acot(x**2 - S(1)/2*I)._eval_nseries(x, 3, None, 1) == I*acoth(S(1)/2) - 4*x**2/3 + O(x**3) # assert acot(x**2 - S(1)/2*I)._eval_nseries(x, 3, None, -1) == I*acoth(S(1)/2) - 4*x**2/3 + O(x**3) # assert acot(x)._eval_nseries(x, 2, None, 1) == pi/2 - x + O(x**2) # assert acot(x)._eval_nseries(x, 2, None, -1) == -pi/2 - x + O(x**2) assert asec(x + S(1)/2)._eval_nseries(x, 4, None, I) == asec(S(1)/2) - 4*sqrt(3)*I*x/3 + \ 8*sqrt(3)*I*x**2/9 - 16*sqrt(3)*I*x**3/9 + O(x**4) assert asec(x + S(1)/2)._eval_nseries(x, 4, None, -I) == -asec(S(1)/2) + 4*sqrt(3)*I*x/3 - \ 8*sqrt(3)*I*x**2/9 + 16*sqrt(3)*I*x**3/9 + O(x**4) assert asec(x - S(1)/2)._eval_nseries(x, 4, None, I) == -asec(-S(1)/2) + 2*pi + 4*sqrt(3)*I*x/3 + \ 8*sqrt(3)*I*x**2/9 + 16*sqrt(3)*I*x**3/9 + O(x**4) assert asec(x - S(1)/2)._eval_nseries(x, 4, None, -I) == asec(-S(1)/2) - 4*sqrt(3)*I*x/3 - \ 8*sqrt(3)*I*x**2/9 - 16*sqrt(3)*I*x**3/9 + O(x**4) # assert asec(I*x + I*x**3 + S(1)/2)._eval_nseries(x, 3, None, 1) == asec(S(1)/2) + 4*sqrt(3)*x/3 - 8*sqrt(3)*I*x**2/9 + O(x**3) # assert asec(I*x + I*x**3 + S(1)/2)._eval_nseries(x, 3, None, -1) == -asec(S(1)/2) - 4*sqrt(3)*x/3 + 8*sqrt(3)*I*x**2/9 + O(x**3) # assert asec(I*x + I*x**3 - S(1)/2)._eval_nseries(x, 3, None, 1) == -asec(-S(1)/2) + 2*pi - 4*sqrt(3)*x/3 - 8*sqrt(3)*I*x**2/9 + O(x**3) # assert asec(I*x + I*x**3 - S(1)/2)._eval_nseries(x, 3, None, -1) == asec(-S(1)/2) + 4*sqrt(3)*x/3 + 8*sqrt(3)*I*x**2/9 + O(x**3) # assert asec(I*x**2 + I*x**3 + S(1)/2)._eval_nseries(x, 3, None, 1) == asec(S(1)/2) + 4*sqrt(3)*x**2/3 + O(x**3) # assert asec(I*x**2 + I*x**3 + S(1)/2)._eval_nseries(x, 3, None, -1) == asec(S(1)/2) + 4*sqrt(3)*x**2/3 + O(x**3) # assert asec(I*x**2 + I*x**3 - S(1)/2)._eval_nseries(x, 3, None, 1) == -asec(-S(1)/2) + 2*pi - 4*sqrt(3)*x**2/3 + O(x**3) # assert asec(I*x**2 + I*x**3 - S(1)/2)._eval_nseries(x, 3, None, -1) == -asec(-S(1)/2) + 2*pi - 4*sqrt(3)*x**2/3 + O(x**3) # assert asec(1 + x)._eval_nseries(x, 3, None) == sqrt(2)*sqrt(x) - 5*sqrt(2)*x**(S(3)/2)/12 + 43*sqrt(2)*x**(S(5)/2)/160 + O(x**3) # assert asec(-1 + x)._eval_nseries(x, 3, None) == pi - sqrt(2)*sqrt(-x) + 5*sqrt(2)*(-x)**(S(3)/2)/12 - 43*sqrt(2)*(-x)**(S(5)/2)/160 + O(x**3) # assert asec(exp(x))._eval_nseries(x, 3, None) == sqrt(2)*sqrt(x) - sqrt(2)*x**(S(3)/2)/6 + sqrt(2)*x**(S(5)/2)/120 + O(x**3) # assert asec(-exp(x))._eval_nseries(x, 3, None) == pi - sqrt(2)*sqrt(x) + sqrt(2)*x**(S(3)/2)/6 - sqrt(2)*x**(S(5)/2)/120 + O(x**3) assert acsc(x + S(1)/2)._eval_nseries(x, 4, None, I) == acsc(S(1)/2) + 4*sqrt(3)*I*x/3 - \ 8*sqrt(3)*I*x**2/9 + 16*sqrt(3)*I*x**3/9 + O(x**4) assert acsc(x + S(1)/2)._eval_nseries(x, 4, None, -I) == -acsc(S(1)/2) + pi - 4*sqrt(3)*I*x/3 + \ 8*sqrt(3)*I*x**2/9 - 16*sqrt(3)*I*x**3/9 + O(x**4) assert acsc(x - S(1)/2)._eval_nseries(x, 4, None, I) == acsc(S(1)/2) - pi - 4*sqrt(3)*I*x/3 - \ 8*sqrt(3)*I*x**2/9 - 16*sqrt(3)*I*x**3/9 + O(x**4) assert acsc(x - S(1)/2)._eval_nseries(x, 4, None, -I) == -acsc(S(1)/2) + 4*sqrt(3)*I*x/3 + \ 8*sqrt(3)*I*x**2/9 + 16*sqrt(3)*I*x**3/9 + O(x**4) # assert acsc(I*x + I*x**3 + S(1)/2)._eval_nseries(x, 3, None, 1) == acsc(S(1)/2) - 4*sqrt(3)*x/3 + 8*sqrt(3)*I*x**2/9 + O(x**3) # assert acsc(I*x + I*x**3 + S(1)/2)._eval_nseries(x, 3, None, -1) == -acsc(S(1)/2) + pi + 4*sqrt(3)*x/3 - 8*sqrt(3)*I*x**2/9 + O(x**3) # assert acsc(I*x + I*x**3 - S(1)/2)._eval_nseries(x, 3, None, 1) == acsc(S(1)/2) - pi + 4*sqrt(3)*x/3 + 8*sqrt(3)*I*x**2/9 + O(x**3) # assert acsc(I*x + I*x**3 - S(1)/2)._eval_nseries(x, 3, None, -1) == -acsc(S(1)/2) - 4*sqrt(3)*x/3 - 8*sqrt(3)*I*x**2/9 + O(x**3) # assert acsc(I*x**2 + I*x**3 + S(1)/2)._eval_nseries(x, 3, None, 1) == acsc(S(1)/2) - 4*sqrt(3)*x**2/3 + O(x**3) # assert acsc(I*x**2 + I*x**3 + S(1)/2)._eval_nseries(x, 3, None, -1) == acsc(S(1)/2) - 4*sqrt(3)*x**2/3 + O(x**3) # assert acsc(I*x**2 + I*x**3 - S(1)/2)._eval_nseries(x, 3, None, 1) == acsc(S(1)/2) - pi + 4*sqrt(3)*x**2/3 + O(x**3) # assert acsc(I*x**2 + I*x**3 - S(1)/2)._eval_nseries(x, 3, None, -1) == acsc(S(1)/2) - pi + 4*sqrt(3)*x**2/3 + O(x**3) # assert acsc(1 + x)._eval_nseries(x, 3, None) == pi/2 - sqrt(2)*sqrt(x) + 5*sqrt(2)*x**(S(3)/2)/12 - 43*sqrt(2)*x**(S(5)/2)/160 + O(x**3) # assert acsc(-1 + x)._eval_nseries(x, 3, None) == -pi/2 + sqrt(2)*sqrt(-x) - 5*sqrt(2)*(-x)**(S(3)/2)/12 + 43*sqrt(2)*(-x)**(S(5)/2)/160 + O(x**3) # assert acsc(exp(x))._eval_nseries(x, 3, None) == pi/2 - sqrt(2)*sqrt(x) + sqrt(2)*x**(S(3)/2)/6 - sqrt(2)*x**(S(5)/2)/120 + O(x**3) # assert acsc(-exp(x))._eval_nseries(x, 3, None) == -pi/2 + sqrt(2)*sqrt(x) - sqrt(2)*x**(S(3)/2)/6 + sqrt(2)*x**(S(5)/2)/120 + O(x**3) def test_issue_8653(): n = Symbol('n', integer=True) assert sin(n).is_irrational is None assert cos(n).is_irrational is None assert tan(n).is_irrational is None def test_issue_9157(): n = Symbol('n', integer=True, positive=True) assert atan(n - 1).is_nonnegative is True def test_trig_period(): x, y = symbols('x, y') assert sin(x).period() == 2*pi assert cos(x).period() == 2*pi assert tan(x).period() == pi assert cot(x).period() == pi assert sec(x).period() == 2*pi assert csc(x).period() == 2*pi assert sin(2*x).period() == pi assert cot(4*x - 6).period() == pi/4 assert cos((-3)*x).period() == pi*Rational(2, 3) assert cos(x*y).period(x) == 2*pi/abs(y) assert sin(3*x*y + 2*pi).period(y) == 2*pi/abs(3*x) assert tan(3*x).period(y) is S.Zero raises(NotImplementedError, lambda: sin(x**2).period(x)) def test_issue_7171(): assert sin(x).rewrite(sqrt) == sin(x) assert sin(x).rewrite(pow) == sin(x) def test_issue_11864(): w, k = symbols('w, k', real=True) F = Piecewise((1, Eq(2*pi*k, 0)), (sin(pi*k)/(pi*k), True)) soln = Piecewise((1, Eq(2*pi*k, 0)), (sinc(pi*k), True)) assert F.rewrite(sinc) == soln def test_real_assumptions(): z = Symbol('z', real=False, finite=True) assert sin(z).is_real is None assert cos(z).is_real is None assert tan(z).is_real is False assert sec(z).is_real is None assert csc(z).is_real is None assert cot(z).is_real is False assert asin(p).is_real is None assert asin(n).is_real is None assert asec(p).is_real is None assert asec(n).is_real is None assert acos(p).is_real is None assert acos(n).is_real is None assert acsc(p).is_real is None assert acsc(n).is_real is None assert atan(p).is_positive is True assert atan(n).is_negative is True assert acot(p).is_positive is True assert acot(n).is_negative is True def test_issue_14320(): assert asin(sin(2)) == -2 + pi and (-pi/2 <= -2 + pi <= pi/2) and sin(2) == sin(-2 + pi) assert asin(cos(2)) == -2 + pi/2 and (-pi/2 <= -2 + pi/2 <= pi/2) and cos(2) == sin(-2 + pi/2) assert acos(sin(2)) == -pi/2 + 2 and (0 <= -pi/2 + 2 <= pi) and sin(2) == cos(-pi/2 + 2) assert acos(cos(20)) == -6*pi + 20 and (0 <= -6*pi + 20 <= pi) and cos(20) == cos(-6*pi + 20) assert acos(cos(30)) == -30 + 10*pi and (0 <= -30 + 10*pi <= pi) and cos(30) == cos(-30 + 10*pi) assert atan(tan(17)) == -5*pi + 17 and (-pi/2 < -5*pi + 17 < pi/2) and tan(17) == tan(-5*pi + 17) assert atan(tan(15)) == -5*pi + 15 and (-pi/2 < -5*pi + 15 < pi/2) and tan(15) == tan(-5*pi + 15) assert atan(cot(12)) == -12 + pi*Rational(7, 2) and (-pi/2 < -12 + pi*Rational(7, 2) < pi/2) and cot(12) == tan(-12 + pi*Rational(7, 2)) assert acot(cot(15)) == -5*pi + 15 and (-pi/2 < -5*pi + 15 <= pi/2) and cot(15) == cot(-5*pi + 15) assert acot(tan(19)) == -19 + pi*Rational(13, 2) and (-pi/2 < -19 + pi*Rational(13, 2) <= pi/2) and tan(19) == cot(-19 + pi*Rational(13, 2)) assert asec(sec(11)) == -11 + 4*pi and (0 <= -11 + 4*pi <= pi) and cos(11) == cos(-11 + 4*pi) assert asec(csc(13)) == -13 + pi*Rational(9, 2) and (0 <= -13 + pi*Rational(9, 2) <= pi) and sin(13) == cos(-13 + pi*Rational(9, 2)) assert acsc(csc(14)) == -4*pi + 14 and (-pi/2 <= -4*pi + 14 <= pi/2) and sin(14) == sin(-4*pi + 14) assert acsc(sec(10)) == pi*Rational(-7, 2) + 10 and (-pi/2 <= pi*Rational(-7, 2) + 10 <= pi/2) and cos(10) == sin(pi*Rational(-7, 2) + 10) def test_issue_14543(): assert sec(2*pi + 11) == sec(11) assert sec(2*pi - 11) == sec(11) assert sec(pi + 11) == -sec(11) assert sec(pi - 11) == -sec(11) assert csc(2*pi + 17) == csc(17) assert csc(2*pi - 17) == -csc(17) assert csc(pi + 17) == -csc(17) assert csc(pi - 17) == csc(17) x = Symbol('x') assert csc(pi/2 + x) == sec(x) assert csc(pi/2 - x) == sec(x) assert csc(pi*Rational(3, 2) + x) == -sec(x) assert csc(pi*Rational(3, 2) - x) == -sec(x) assert sec(pi/2 - x) == csc(x) assert sec(pi/2 + x) == -csc(x) assert sec(pi*Rational(3, 2) + x) == csc(x) assert sec(pi*Rational(3, 2) - x) == -csc(x) def test_as_real_imag(): # This is for https://github.com/sympy/sympy/issues/17142 # If it start failing again in irrelevant builds or in the master # please open up the issue again. expr = atan(I/(I + I*tan(1))) assert expr.as_real_imag() == (expr, 0) def test_issue_18746(): e3 = cos(S.Pi*(x/4 + 1/4)) assert e3.period() == 8
1e4221c675a5ac3af8364a1f1e7e54799f69055bdd00abbcd1fef936eb416540
from sympy.core.numbers import (I, nan, oo, pi) from sympy.core.relational import (Eq, Ne) from sympy.core.singleton import S from sympy.core.symbol import (Symbol, symbols) from sympy.functions.elementary.complexes import (adjoint, conjugate, sign, transpose) from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.piecewise import Piecewise from sympy.functions.special.delta_functions import (DiracDelta, Heaviside) from sympy.functions.special.singularity_functions import SingularityFunction from sympy.simplify.simplify import signsimp from sympy.testing.pytest import raises from sympy.core.expr import unchanged from sympy.core.function import ArgumentIndexError x, y = symbols('x y') i = symbols('t', nonzero=True) j = symbols('j', positive=True) k = symbols('k', negative=True) def test_DiracDelta(): assert DiracDelta(1) == 0 assert DiracDelta(5.1) == 0 assert DiracDelta(-pi) == 0 assert DiracDelta(5, 7) == 0 assert DiracDelta(i) == 0 assert DiracDelta(j) == 0 assert DiracDelta(k) == 0 assert DiracDelta(nan) is nan assert DiracDelta(0).func is DiracDelta assert DiracDelta(x).func is DiracDelta # FIXME: this is generally undefined @ x=0 # But then limit(Delta(c)*Heaviside(x),x,-oo) # need's to be implemented. # assert 0*DiracDelta(x) == 0 assert adjoint(DiracDelta(x)) == DiracDelta(x) assert adjoint(DiracDelta(x - y)) == DiracDelta(x - y) assert conjugate(DiracDelta(x)) == DiracDelta(x) assert conjugate(DiracDelta(x - y)) == DiracDelta(x - y) assert transpose(DiracDelta(x)) == DiracDelta(x) assert transpose(DiracDelta(x - y)) == DiracDelta(x - y) assert DiracDelta(x).diff(x) == DiracDelta(x, 1) assert DiracDelta(x, 1).diff(x) == DiracDelta(x, 2) assert DiracDelta(x).is_simple(x) is True assert DiracDelta(3*x).is_simple(x) is True assert DiracDelta(x**2).is_simple(x) is False assert DiracDelta(sqrt(x)).is_simple(x) is False assert DiracDelta(x).is_simple(y) is False assert DiracDelta(x*y).expand(diracdelta=True, wrt=x) == DiracDelta(x)/abs(y) assert DiracDelta(x*y).expand(diracdelta=True, wrt=y) == DiracDelta(y)/abs(x) assert DiracDelta(x**2*y).expand(diracdelta=True, wrt=x) == DiracDelta(x**2*y) assert DiracDelta(y).expand(diracdelta=True, wrt=x) == DiracDelta(y) assert DiracDelta((x - 1)*(x - 2)*(x - 3)).expand(diracdelta=True, wrt=x) == ( DiracDelta(x - 3)/2 + DiracDelta(x - 2) + DiracDelta(x - 1)/2) assert DiracDelta(2*x) != DiracDelta(x) # scaling property assert DiracDelta(x) == DiracDelta(-x) # even function assert DiracDelta(-x, 2) == DiracDelta(x, 2) assert DiracDelta(-x, 1) == -DiracDelta(x, 1) # odd deriv is odd assert DiracDelta(-oo*x) == DiracDelta(oo*x) assert DiracDelta(x - y) != DiracDelta(y - x) assert signsimp(DiracDelta(x - y) - DiracDelta(y - x)) == 0 assert DiracDelta(x*y).expand(diracdelta=True, wrt=x) == DiracDelta(x)/abs(y) assert DiracDelta(x*y).expand(diracdelta=True, wrt=y) == DiracDelta(y)/abs(x) assert DiracDelta(x**2*y).expand(diracdelta=True, wrt=x) == DiracDelta(x**2*y) assert DiracDelta(y).expand(diracdelta=True, wrt=x) == DiracDelta(y) assert DiracDelta((x - 1)*(x - 2)*(x - 3)).expand(diracdelta=True) == ( DiracDelta(x - 3)/2 + DiracDelta(x - 2) + DiracDelta(x - 1)/2) raises(ArgumentIndexError, lambda: DiracDelta(x).fdiff(2)) raises(ValueError, lambda: DiracDelta(x, -1)) raises(ValueError, lambda: DiracDelta(I)) raises(ValueError, lambda: DiracDelta(2 + 3*I)) def test_heaviside(): assert Heaviside(-5) == 0 assert Heaviside(1) == 1 assert Heaviside(0) == S.Half assert Heaviside(0, x) == x assert unchanged(Heaviside,x, nan) assert Heaviside(0, nan) == nan h0 = Heaviside(x, 0) h12 = Heaviside(x, S.Half) h1 = Heaviside(x, 1) assert h0.args == h0.pargs == (x, 0) assert h1.args == h1.pargs == (x, 1) assert h12.args == (x, S.Half) assert h12.pargs == (x,) # default 1/2 suppressed assert adjoint(Heaviside(x)) == Heaviside(x) assert adjoint(Heaviside(x - y)) == Heaviside(x - y) assert conjugate(Heaviside(x)) == Heaviside(x) assert conjugate(Heaviside(x - y)) == Heaviside(x - y) assert transpose(Heaviside(x)) == Heaviside(x) assert transpose(Heaviside(x - y)) == Heaviside(x - y) assert Heaviside(x).diff(x) == DiracDelta(x) assert Heaviside(x + I).is_Function is True assert Heaviside(I*x).is_Function is True raises(ArgumentIndexError, lambda: Heaviside(x).fdiff(2)) raises(ValueError, lambda: Heaviside(I)) raises(ValueError, lambda: Heaviside(2 + 3*I)) def test_rewrite(): x, y = Symbol('x', real=True), Symbol('y') assert Heaviside(x).rewrite(Piecewise) == ( Piecewise((0, x < 0), (Heaviside(0), Eq(x, 0)), (1, x > 0))) assert Heaviside(y).rewrite(Piecewise) == ( Piecewise((0, y < 0), (Heaviside(0), Eq(y, 0)), (1, y > 0))) assert Heaviside(x, y).rewrite(Piecewise) == ( Piecewise((0, x < 0), (y, Eq(x, 0)), (1, x > 0))) assert Heaviside(x, 0).rewrite(Piecewise) == ( Piecewise((0, x <= 0), (1, x > 0))) assert Heaviside(x, 1).rewrite(Piecewise) == ( Piecewise((0, x < 0), (1, x >= 0))) assert Heaviside(x, nan).rewrite(Piecewise) == ( Piecewise((0, x < 0), (nan, Eq(x, 0)), (1, x > 0))) assert Heaviside(x).rewrite(sign) == \ Heaviside(x, H0=Heaviside(0)).rewrite(sign) == \ Piecewise( (sign(x)/2 + S(1)/2, Eq(Heaviside(0), S(1)/2)), (Piecewise( (sign(x)/2 + S(1)/2, Ne(x, 0)), (Heaviside(0), True)), True) ) assert Heaviside(y).rewrite(sign) == Heaviside(y) assert Heaviside(x, S.Half).rewrite(sign) == (sign(x)+1)/2 assert Heaviside(x, y).rewrite(sign) == \ Piecewise( (sign(x)/2 + S(1)/2, Eq(y, S(1)/2)), (Piecewise( (sign(x)/2 + S(1)/2, Ne(x, 0)), (y, True)), True) ) assert DiracDelta(y).rewrite(Piecewise) == Piecewise((DiracDelta(0), Eq(y, 0)), (0, True)) assert DiracDelta(y, 1).rewrite(Piecewise) == DiracDelta(y, 1) assert DiracDelta(x - 5).rewrite(Piecewise) == ( Piecewise((DiracDelta(0), Eq(x - 5, 0)), (0, True))) assert (x*DiracDelta(x - 10)).rewrite(SingularityFunction) == x*SingularityFunction(x, 10, -1) assert 5*x*y*DiracDelta(y, 1).rewrite(SingularityFunction) == 5*x*y*SingularityFunction(y, 0, -2) assert DiracDelta(0).rewrite(SingularityFunction) == SingularityFunction(0, 0, -1) assert DiracDelta(0, 1).rewrite(SingularityFunction) == SingularityFunction(0, 0, -2) assert Heaviside(x).rewrite(SingularityFunction) == SingularityFunction(x, 0, 0) assert 5*x*y*Heaviside(y + 1).rewrite(SingularityFunction) == 5*x*y*SingularityFunction(y, -1, 0) assert ((x - 3)**3*Heaviside(x - 3)).rewrite(SingularityFunction) == (x - 3)**3*SingularityFunction(x, 3, 0) assert Heaviside(0).rewrite(SingularityFunction) == S.Half
87b8d5043fd305381272adc27e054e0c7b9145fe144c0aed0b094250d07b4d53
from itertools import product from sympy.concrete.summations import Sum from sympy.core.function import (diff, expand_func) from sympy.core.numbers import (I, Rational, oo, pi) from sympy.core.singleton import S from sympy.core.symbol import (Symbol, symbols) from sympy.functions.elementary.complexes import (conjugate, polar_lift) from sympy.functions.elementary.exponential import (exp, exp_polar, log) from sympy.functions.elementary.hyperbolic import (cosh, sinh) from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import (cos, sin) from sympy.functions.special.bessel import (besseli, besselj, besselk, bessely, hankel1, hankel2, hn1, hn2, jn, jn_zeros, yn) from sympy.functions.special.gamma_functions import (gamma, uppergamma) from sympy.functions.special.hyper import hyper from sympy.integrals.integrals import Integral from sympy.series.order import O from sympy.series.series import series from sympy.functions.special.bessel import (airyai, airybi, airyaiprime, airybiprime, marcumq) from sympy.core.random import (random_complex_number as randcplx, verify_numerically as tn, test_derivative_numerically as td, _randint) from sympy.simplify import besselsimp from sympy.testing.pytest import raises, slow from sympy.abc import z, n, k, x randint = _randint() def test_bessel_rand(): for f in [besselj, bessely, besseli, besselk, hankel1, hankel2]: assert td(f(randcplx(), z), z) for f in [jn, yn, hn1, hn2]: assert td(f(randint(-10, 10), z), z) def test_bessel_twoinputs(): for f in [besselj, bessely, besseli, besselk, hankel1, hankel2, jn, yn]: raises(TypeError, lambda: f(1)) raises(TypeError, lambda: f(1, 2, 3)) def test_besselj_leading_term(): assert besselj(0, x).as_leading_term(x) == 1 assert besselj(1, sin(x)).as_leading_term(x) == x/2 assert besselj(1, 2*sqrt(x)).as_leading_term(x) == sqrt(x) # https://github.com/sympy/sympy/issues/21701 assert (besselj(z, x)/x**z).as_leading_term(x) == 1/(2**z*gamma(z + 1)) def test_bessely_leading_term(): assert bessely(0, x).as_leading_term(x) == (2*log(x) - 2*log(2))/pi assert bessely(1, sin(x)).as_leading_term(x) == (x*log(x) - x*log(2))/pi assert bessely(1, 2*sqrt(x)).as_leading_term(x) == sqrt(x)*log(x)/pi def test_besselj_series(): assert besselj(0, x).series(x) == 1 - x**2/4 + x**4/64 + O(x**6) assert besselj(0, x**(1.1)).series(x) == 1 + x**4.4/64 - x**2.2/4 + O(x**6) assert besselj(0, x**2 + x).series(x) == 1 - x**2/4 - x**3/2\ - 15*x**4/64 + x**5/16 + O(x**6) assert besselj(0, sqrt(x) + x).series(x, n=4) == 1 - x/4 - 15*x**2/64\ + 215*x**3/2304 - x**Rational(3, 2)/2 + x**Rational(5, 2)/16\ + 23*x**Rational(7, 2)/384 + O(x**4) assert besselj(0, x/(1 - x)).series(x) == 1 - x**2/4 - x**3/2 - 47*x**4/64\ - 15*x**5/16 + O(x**6) assert besselj(0, log(1 + x)).series(x) == 1 - x**2/4 + x**3/4\ - 41*x**4/192 + 17*x**5/96 + O(x**6) assert besselj(1, sin(x)).series(x) == x/2 - 7*x**3/48 + 73*x**5/1920 + O(x**6) assert besselj(1, 2*sqrt(x)).series(x) == sqrt(x) - x**Rational(3, 2)/2\ + x**Rational(5, 2)/12 - x**Rational(7, 2)/144 + x**Rational(9, 2)/2880\ - x**Rational(11, 2)/86400 + O(x**6) assert besselj(-2, sin(x)).series(x, n=4) == besselj(2, sin(x)).series(x, n=4) def test_bessely_series(): const = 2*S.EulerGamma/pi - 2*log(2)/pi + 2*log(x)/pi assert bessely(0, x).series(x, n=4) == const + x**2*(-log(x)/(2*pi)\ + (2 - 2*S.EulerGamma)/(4*pi) + log(2)/(2*pi)) + O(x**4*log(x)) assert bessely(0, x**(1.1)).series(x, n=4) == 2*S.EulerGamma/pi\ - 2*log(2)/pi + 2.2*log(x)/pi + x**2.2*(-0.55*log(x)/pi\ + (2 - 2*S.EulerGamma)/(4*pi) + log(2)/(2*pi)) + O(x**4*log(x)) assert bessely(0, x**2 + x).series(x, n=4) == \ const - (2 - 2*S.EulerGamma)*(-x**3/(2*pi) - x**2/(4*pi)) + 2*x/pi\ + x**2*(-log(x)/(2*pi) - 1/pi + log(2)/(2*pi))\ + x**3*(-log(x)/pi + 1/(6*pi) + log(2)/pi) + O(x**4*log(x)) assert bessely(0, x/(1 - x)).series(x, n=3) == const\ + 2*x/pi + x**2*(-log(x)/(2*pi) + (2 - 2*S.EulerGamma)/(4*pi)\ + log(2)/(2*pi) + 1/pi) + O(x**3*log(x)) assert bessely(0, log(1 + x)).series(x, n=3) == const\ - x/pi + x**2*(-log(x)/(2*pi) + (2 - 2*S.EulerGamma)/(4*pi)\ + log(2)/(2*pi) + 5/(12*pi)) + O(x**3*log(x)) assert bessely(1, sin(x)).series(x, n=4) == -(1/pi)*(1 - 2*S.EulerGamma)\ * (-x**3/12 + x/2) + x*(log(x)/pi - log(2)/pi) + x**3*(-7*log(x)\ / (24*pi) - 1/(6*pi) + (Rational(5, 2) - 2*S.EulerGamma)/(16*pi)\ + 7*log(2)/(24*pi)) + O(x**4*log(x)) assert bessely(1, 2*sqrt(x)).series(x, n=3) == sqrt(x)*(log(x)/pi \ - (1 - 2*S.EulerGamma)/pi) + x**Rational(3, 2)*(-log(x)/(2*pi)\ + (Rational(5, 2) - 2*S.EulerGamma)/(2*pi))\ + x**Rational(5, 2)*(log(x)/(12*pi)\ - (Rational(10, 3) - 2*S.EulerGamma)/(12*pi)) + O(x**3*log(x)) assert bessely(-2, sin(x)).series(x, n=4) == bessely(2, sin(x)).series(x, n=4) def test_diff(): assert besselj(n, z).diff(z) == besselj(n - 1, z)/2 - besselj(n + 1, z)/2 assert bessely(n, z).diff(z) == bessely(n - 1, z)/2 - bessely(n + 1, z)/2 assert besseli(n, z).diff(z) == besseli(n - 1, z)/2 + besseli(n + 1, z)/2 assert besselk(n, z).diff(z) == -besselk(n - 1, z)/2 - besselk(n + 1, z)/2 assert hankel1(n, z).diff(z) == hankel1(n - 1, z)/2 - hankel1(n + 1, z)/2 assert hankel2(n, z).diff(z) == hankel2(n - 1, z)/2 - hankel2(n + 1, z)/2 def test_rewrite(): assert besselj(n, z).rewrite(jn) == sqrt(2*z/pi)*jn(n - S.Half, z) assert bessely(n, z).rewrite(yn) == sqrt(2*z/pi)*yn(n - S.Half, z) assert besseli(n, z).rewrite(besselj) == \ exp(-I*n*pi/2)*besselj(n, polar_lift(I)*z) assert besselj(n, z).rewrite(besseli) == \ exp(I*n*pi/2)*besseli(n, polar_lift(-I)*z) nu = randcplx() assert tn(besselj(nu, z), besselj(nu, z).rewrite(besseli), z) assert tn(besselj(nu, z), besselj(nu, z).rewrite(bessely), z) assert tn(besseli(nu, z), besseli(nu, z).rewrite(besselj), z) assert tn(besseli(nu, z), besseli(nu, z).rewrite(bessely), z) assert tn(bessely(nu, z), bessely(nu, z).rewrite(besselj), z) assert tn(bessely(nu, z), bessely(nu, z).rewrite(besseli), z) assert tn(besselk(nu, z), besselk(nu, z).rewrite(besselj), z) assert tn(besselk(nu, z), besselk(nu, z).rewrite(besseli), z) assert tn(besselk(nu, z), besselk(nu, z).rewrite(bessely), z) # check that a rewrite was triggered, when the order is set to a generic # symbol 'nu' assert yn(nu, z) != yn(nu, z).rewrite(jn) assert hn1(nu, z) != hn1(nu, z).rewrite(jn) assert hn2(nu, z) != hn2(nu, z).rewrite(jn) assert jn(nu, z) != jn(nu, z).rewrite(yn) assert hn1(nu, z) != hn1(nu, z).rewrite(yn) assert hn2(nu, z) != hn2(nu, z).rewrite(yn) # rewriting spherical bessel functions (SBFs) w.r.t. besselj, bessely is # not allowed if a generic symbol 'nu' is used as the order of the SBFs # to avoid inconsistencies (the order of bessel[jy] is allowed to be # complex-valued, whereas SBFs are defined only for integer orders) order = nu for f in (besselj, bessely): assert hn1(order, z) == hn1(order, z).rewrite(f) assert hn2(order, z) == hn2(order, z).rewrite(f) assert jn(order, z).rewrite(besselj) == sqrt(2)*sqrt(pi)*sqrt(1/z)*besselj(order + S.Half, z)/2 assert jn(order, z).rewrite(bessely) == (-1)**nu*sqrt(2)*sqrt(pi)*sqrt(1/z)*bessely(-order - S.Half, z)/2 # for integral orders rewriting SBFs w.r.t bessel[jy] is allowed N = Symbol('n', integer=True) ri = randint(-11, 10) for order in (ri, N): for f in (besselj, bessely): assert yn(order, z) != yn(order, z).rewrite(f) assert jn(order, z) != jn(order, z).rewrite(f) assert hn1(order, z) != hn1(order, z).rewrite(f) assert hn2(order, z) != hn2(order, z).rewrite(f) for func, refunc in product((yn, jn, hn1, hn2), (jn, yn, besselj, bessely)): assert tn(func(ri, z), func(ri, z).rewrite(refunc), z) def test_expand(): assert expand_func(besselj(S.Half, z).rewrite(jn)) == \ sqrt(2)*sin(z)/(sqrt(pi)*sqrt(z)) assert expand_func(bessely(S.Half, z).rewrite(yn)) == \ -sqrt(2)*cos(z)/(sqrt(pi)*sqrt(z)) # XXX: teach sin/cos to work around arguments like # x*exp_polar(I*pi*n/2). Then change besselsimp -> expand_func assert besselsimp(besselj(S.Half, z)) == sqrt(2)*sin(z)/(sqrt(pi)*sqrt(z)) assert besselsimp(besselj(Rational(-1, 2), z)) == sqrt(2)*cos(z)/(sqrt(pi)*sqrt(z)) assert besselsimp(besselj(Rational(5, 2), z)) == \ -sqrt(2)*(z**2*sin(z) + 3*z*cos(z) - 3*sin(z))/(sqrt(pi)*z**Rational(5, 2)) assert besselsimp(besselj(Rational(-5, 2), z)) == \ -sqrt(2)*(z**2*cos(z) - 3*z*sin(z) - 3*cos(z))/(sqrt(pi)*z**Rational(5, 2)) assert besselsimp(bessely(S.Half, z)) == \ -(sqrt(2)*cos(z))/(sqrt(pi)*sqrt(z)) assert besselsimp(bessely(Rational(-1, 2), z)) == sqrt(2)*sin(z)/(sqrt(pi)*sqrt(z)) assert besselsimp(bessely(Rational(5, 2), z)) == \ sqrt(2)*(z**2*cos(z) - 3*z*sin(z) - 3*cos(z))/(sqrt(pi)*z**Rational(5, 2)) assert besselsimp(bessely(Rational(-5, 2), z)) == \ -sqrt(2)*(z**2*sin(z) + 3*z*cos(z) - 3*sin(z))/(sqrt(pi)*z**Rational(5, 2)) assert besselsimp(besseli(S.Half, z)) == sqrt(2)*sinh(z)/(sqrt(pi)*sqrt(z)) assert besselsimp(besseli(Rational(-1, 2), z)) == \ sqrt(2)*cosh(z)/(sqrt(pi)*sqrt(z)) assert besselsimp(besseli(Rational(5, 2), z)) == \ sqrt(2)*(z**2*sinh(z) - 3*z*cosh(z) + 3*sinh(z))/(sqrt(pi)*z**Rational(5, 2)) assert besselsimp(besseli(Rational(-5, 2), z)) == \ sqrt(2)*(z**2*cosh(z) - 3*z*sinh(z) + 3*cosh(z))/(sqrt(pi)*z**Rational(5, 2)) assert besselsimp(besselk(S.Half, z)) == \ besselsimp(besselk(Rational(-1, 2), z)) == sqrt(pi)*exp(-z)/(sqrt(2)*sqrt(z)) assert besselsimp(besselk(Rational(5, 2), z)) == \ besselsimp(besselk(Rational(-5, 2), z)) == \ sqrt(2)*sqrt(pi)*(z**2 + 3*z + 3)*exp(-z)/(2*z**Rational(5, 2)) n = Symbol('n', integer=True, positive=True) assert expand_func(besseli(n + 2, z)) == \ besseli(n, z) + (-2*n - 2)*(-2*n*besseli(n, z)/z + besseli(n - 1, z))/z assert expand_func(besselj(n + 2, z)) == \ -besselj(n, z) + (2*n + 2)*(2*n*besselj(n, z)/z - besselj(n - 1, z))/z assert expand_func(besselk(n + 2, z)) == \ besselk(n, z) + (2*n + 2)*(2*n*besselk(n, z)/z + besselk(n - 1, z))/z assert expand_func(bessely(n + 2, z)) == \ -bessely(n, z) + (2*n + 2)*(2*n*bessely(n, z)/z - bessely(n - 1, z))/z assert expand_func(besseli(n + S.Half, z).rewrite(jn)) == \ (sqrt(2)*sqrt(z)*exp(-I*pi*(n + S.Half)/2) * exp_polar(I*pi/4)*jn(n, z*exp_polar(I*pi/2))/sqrt(pi)) assert expand_func(besselj(n + S.Half, z).rewrite(jn)) == \ sqrt(2)*sqrt(z)*jn(n, z)/sqrt(pi) r = Symbol('r', real=True) p = Symbol('p', positive=True) i = Symbol('i', integer=True) for besselx in [besselj, bessely, besseli, besselk]: assert besselx(i, p).is_extended_real is True assert besselx(i, x).is_extended_real is None assert besselx(x, z).is_extended_real is None for besselx in [besselj, besseli]: assert besselx(i, r).is_extended_real is True for besselx in [bessely, besselk]: assert besselx(i, r).is_extended_real is None for besselx in [besselj, bessely, besseli, besselk]: assert expand_func(besselx(oo, x)) == besselx(oo, x, evaluate=False) assert expand_func(besselx(-oo, x)) == besselx(-oo, x, evaluate=False) # Quite varying time, but often really slow @slow def test_slow_expand(): def check(eq, ans): return tn(eq, ans) and eq == ans rn = randcplx(a=1, b=0, d=0, c=2) for besselx in [besselj, bessely, besseli, besselk]: ri = S(2*randint(-11, 10) + 1) / 2 # half integer in [-21/2, 21/2] assert tn(besselsimp(besselx(ri, z)), besselx(ri, z)) assert check(expand_func(besseli(rn, x)), besseli(rn - 2, x) - 2*(rn - 1)*besseli(rn - 1, x)/x) assert check(expand_func(besseli(-rn, x)), besseli(-rn + 2, x) + 2*(-rn + 1)*besseli(-rn + 1, x)/x) assert check(expand_func(besselj(rn, x)), -besselj(rn - 2, x) + 2*(rn - 1)*besselj(rn - 1, x)/x) assert check(expand_func(besselj(-rn, x)), -besselj(-rn + 2, x) + 2*(-rn + 1)*besselj(-rn + 1, x)/x) assert check(expand_func(besselk(rn, x)), besselk(rn - 2, x) + 2*(rn - 1)*besselk(rn - 1, x)/x) assert check(expand_func(besselk(-rn, x)), besselk(-rn + 2, x) - 2*(-rn + 1)*besselk(-rn + 1, x)/x) assert check(expand_func(bessely(rn, x)), -bessely(rn - 2, x) + 2*(rn - 1)*bessely(rn - 1, x)/x) assert check(expand_func(bessely(-rn, x)), -bessely(-rn + 2, x) + 2*(-rn + 1)*bessely(-rn + 1, x)/x) def mjn(n, z): return expand_func(jn(n, z)) def myn(n, z): return expand_func(yn(n, z)) def test_jn(): z = symbols("z") assert jn(0, 0) == 1 assert jn(1, 0) == 0 assert jn(-1, 0) == S.ComplexInfinity assert jn(z, 0) == jn(z, 0, evaluate=False) assert jn(0, oo) == 0 assert jn(0, -oo) == 0 assert mjn(0, z) == sin(z)/z assert mjn(1, z) == sin(z)/z**2 - cos(z)/z assert mjn(2, z) == (3/z**3 - 1/z)*sin(z) - (3/z**2) * cos(z) assert mjn(3, z) == (15/z**4 - 6/z**2)*sin(z) + (1/z - 15/z**3)*cos(z) assert mjn(4, z) == (1/z + 105/z**5 - 45/z**3)*sin(z) + \ (-105/z**4 + 10/z**2)*cos(z) assert mjn(5, z) == (945/z**6 - 420/z**4 + 15/z**2)*sin(z) + \ (-1/z - 945/z**5 + 105/z**3)*cos(z) assert mjn(6, z) == (-1/z + 10395/z**7 - 4725/z**5 + 210/z**3)*sin(z) + \ (-10395/z**6 + 1260/z**4 - 21/z**2)*cos(z) assert expand_func(jn(n, z)) == jn(n, z) # SBFs not defined for complex-valued orders assert jn(2+3j, 5.2+0.3j).evalf() == jn(2+3j, 5.2+0.3j) assert eq([jn(2, 5.2+0.3j).evalf(10)], [0.09941975672 - 0.05452508024*I]) def test_yn(): z = symbols("z") assert myn(0, z) == -cos(z)/z assert myn(1, z) == -cos(z)/z**2 - sin(z)/z assert myn(2, z) == -((3/z**3 - 1/z)*cos(z) + (3/z**2)*sin(z)) assert expand_func(yn(n, z)) == yn(n, z) # SBFs not defined for complex-valued orders assert yn(2+3j, 5.2+0.3j).evalf() == yn(2+3j, 5.2+0.3j) assert eq([yn(2, 5.2+0.3j).evalf(10)], [0.185250342 + 0.01489557397*I]) def test_sympify_yn(): assert S(15) in myn(3, pi).atoms() assert myn(3, pi) == 15/pi**4 - 6/pi**2 def eq(a, b, tol=1e-6): for u, v in zip(a, b): if not (abs(u - v) < tol): return False return True def test_jn_zeros(): assert eq(jn_zeros(0, 4), [3.141592, 6.283185, 9.424777, 12.566370]) assert eq(jn_zeros(1, 4), [4.493409, 7.725251, 10.904121, 14.066193]) assert eq(jn_zeros(2, 4), [5.763459, 9.095011, 12.322940, 15.514603]) assert eq(jn_zeros(3, 4), [6.987932, 10.417118, 13.698023, 16.923621]) assert eq(jn_zeros(4, 4), [8.182561, 11.704907, 15.039664, 18.301255]) def test_bessel_eval(): n, m, k = Symbol('n', integer=True), Symbol('m'), Symbol('k', integer=True, zero=False) for f in [besselj, besseli]: assert f(0, 0) is S.One assert f(2.1, 0) is S.Zero assert f(-3, 0) is S.Zero assert f(-10.2, 0) is S.ComplexInfinity assert f(1 + 3*I, 0) is S.Zero assert f(-3 + I, 0) is S.ComplexInfinity assert f(-2*I, 0) is S.NaN assert f(n, 0) != S.One and f(n, 0) != S.Zero assert f(m, 0) != S.One and f(m, 0) != S.Zero assert f(k, 0) is S.Zero assert bessely(0, 0) is S.NegativeInfinity assert besselk(0, 0) is S.Infinity for f in [bessely, besselk]: assert f(1 + I, 0) is S.ComplexInfinity assert f(I, 0) is S.NaN for f in [besselj, bessely]: assert f(m, S.Infinity) is S.Zero assert f(m, S.NegativeInfinity) is S.Zero for f in [besseli, besselk]: assert f(m, I*S.Infinity) is S.Zero assert f(m, I*S.NegativeInfinity) is S.Zero for f in [besseli, besselk]: assert f(-4, z) == f(4, z) assert f(-3, z) == f(3, z) assert f(-n, z) == f(n, z) assert f(-m, z) != f(m, z) for f in [besselj, bessely]: assert f(-4, z) == f(4, z) assert f(-3, z) == -f(3, z) assert f(-n, z) == (-1)**n*f(n, z) assert f(-m, z) != (-1)**m*f(m, z) for f in [besselj, besseli]: assert f(m, -z) == (-z)**m*z**(-m)*f(m, z) assert besseli(2, -z) == besseli(2, z) assert besseli(3, -z) == -besseli(3, z) assert besselj(0, -z) == besselj(0, z) assert besselj(1, -z) == -besselj(1, z) assert besseli(0, I*z) == besselj(0, z) assert besseli(1, I*z) == I*besselj(1, z) assert besselj(3, I*z) == -I*besseli(3, z) def test_bessel_nan(): # FIXME: could have these return NaN; for now just fix infinite recursion for f in [besselj, bessely, besseli, besselk, hankel1, hankel2, yn, jn]: assert f(1, S.NaN) == f(1, S.NaN, evaluate=False) def test_meromorphic(): assert besselj(2, x).is_meromorphic(x, 1) == True assert besselj(2, x).is_meromorphic(x, 0) == True assert besselj(2, x).is_meromorphic(x, oo) == False assert besselj(S(2)/3, x).is_meromorphic(x, 1) == True assert besselj(S(2)/3, x).is_meromorphic(x, 0) == False assert besselj(S(2)/3, x).is_meromorphic(x, oo) == False assert besselj(x, 2*x).is_meromorphic(x, 2) == False assert besselk(0, x).is_meromorphic(x, 1) == True assert besselk(2, x).is_meromorphic(x, 0) == True assert besseli(0, x).is_meromorphic(x, 1) == True assert besseli(2, x).is_meromorphic(x, 0) == True assert bessely(0, x).is_meromorphic(x, 1) == True assert bessely(0, x).is_meromorphic(x, 0) == False assert bessely(2, x).is_meromorphic(x, 0) == True assert hankel1(3, x**2 + 2*x).is_meromorphic(x, 1) == True assert hankel1(0, x).is_meromorphic(x, 0) == False assert hankel2(11, 4).is_meromorphic(x, 5) == True assert hn1(6, 7*x**3 + 4).is_meromorphic(x, 7) == True assert hn2(3, 2*x).is_meromorphic(x, 9) == True assert jn(5, 2*x + 7).is_meromorphic(x, 4) == True assert yn(8, x**2 + 11).is_meromorphic(x, 6) == True def test_conjugate(): n = Symbol('n') z = Symbol('z', extended_real=False) x = Symbol('x', extended_real=True) y = Symbol('y', positive=True) t = Symbol('t', negative=True) for f in [besseli, besselj, besselk, bessely, hankel1, hankel2]: assert f(n, -1).conjugate() != f(conjugate(n), -1) assert f(n, x).conjugate() != f(conjugate(n), x) assert f(n, t).conjugate() != f(conjugate(n), t) rz = randcplx(b=0.5) for f in [besseli, besselj, besselk, bessely]: assert f(n, 1 + I).conjugate() == f(conjugate(n), 1 - I) assert f(n, 0).conjugate() == f(conjugate(n), 0) assert f(n, 1).conjugate() == f(conjugate(n), 1) assert f(n, z).conjugate() == f(conjugate(n), conjugate(z)) assert f(n, y).conjugate() == f(conjugate(n), y) assert tn(f(n, rz).conjugate(), f(conjugate(n), conjugate(rz))) assert hankel1(n, 1 + I).conjugate() == hankel2(conjugate(n), 1 - I) assert hankel1(n, 0).conjugate() == hankel2(conjugate(n), 0) assert hankel1(n, 1).conjugate() == hankel2(conjugate(n), 1) assert hankel1(n, y).conjugate() == hankel2(conjugate(n), y) assert hankel1(n, z).conjugate() == hankel2(conjugate(n), conjugate(z)) assert tn(hankel1(n, rz).conjugate(), hankel2(conjugate(n), conjugate(rz))) assert hankel2(n, 1 + I).conjugate() == hankel1(conjugate(n), 1 - I) assert hankel2(n, 0).conjugate() == hankel1(conjugate(n), 0) assert hankel2(n, 1).conjugate() == hankel1(conjugate(n), 1) assert hankel2(n, y).conjugate() == hankel1(conjugate(n), y) assert hankel2(n, z).conjugate() == hankel1(conjugate(n), conjugate(z)) assert tn(hankel2(n, rz).conjugate(), hankel1(conjugate(n), conjugate(rz))) def test_branching(): assert besselj(polar_lift(k), x) == besselj(k, x) assert besseli(polar_lift(k), x) == besseli(k, x) n = Symbol('n', integer=True) assert besselj(n, exp_polar(2*pi*I)*x) == besselj(n, x) assert besselj(n, polar_lift(x)) == besselj(n, x) assert besseli(n, exp_polar(2*pi*I)*x) == besseli(n, x) assert besseli(n, polar_lift(x)) == besseli(n, x) def tn(func, s): from sympy.core.random import uniform c = uniform(1, 5) expr = func(s, c*exp_polar(I*pi)) - func(s, c*exp_polar(-I*pi)) eps = 1e-15 expr2 = func(s + eps, -c + eps*I) - func(s + eps, -c - eps*I) return abs(expr.n() - expr2.n()).n() < 1e-10 nu = Symbol('nu') assert besselj(nu, exp_polar(2*pi*I)*x) == exp(2*pi*I*nu)*besselj(nu, x) assert besseli(nu, exp_polar(2*pi*I)*x) == exp(2*pi*I*nu)*besseli(nu, x) assert tn(besselj, 2) assert tn(besselj, pi) assert tn(besselj, I) assert tn(besseli, 2) assert tn(besseli, pi) assert tn(besseli, I) def test_airy_base(): z = Symbol('z') x = Symbol('x', real=True) y = Symbol('y', real=True) assert conjugate(airyai(z)) == airyai(conjugate(z)) assert airyai(x).is_extended_real assert airyai(x+I*y).as_real_imag() == ( airyai(x - I*y)/2 + airyai(x + I*y)/2, I*(airyai(x - I*y) - airyai(x + I*y))/2) def test_airyai(): z = Symbol('z', real=False) t = Symbol('t', negative=True) p = Symbol('p', positive=True) assert isinstance(airyai(z), airyai) assert airyai(0) == 3**Rational(1, 3)/(3*gamma(Rational(2, 3))) assert airyai(oo) == 0 assert airyai(-oo) == 0 assert diff(airyai(z), z) == airyaiprime(z) assert series(airyai(z), z, 0, 3) == ( 3**Rational(5, 6)*gamma(Rational(1, 3))/(6*pi) - 3**Rational(1, 6)*z*gamma(Rational(2, 3))/(2*pi) + O(z**3)) assert airyai(z).rewrite(hyper) == ( -3**Rational(2, 3)*z*hyper((), (Rational(4, 3),), z**3/9)/(3*gamma(Rational(1, 3))) + 3**Rational(1, 3)*hyper((), (Rational(2, 3),), z**3/9)/(3*gamma(Rational(2, 3)))) assert isinstance(airyai(z).rewrite(besselj), airyai) assert airyai(t).rewrite(besselj) == ( sqrt(-t)*(besselj(Rational(-1, 3), 2*(-t)**Rational(3, 2)/3) + besselj(Rational(1, 3), 2*(-t)**Rational(3, 2)/3))/3) assert airyai(z).rewrite(besseli) == ( -z*besseli(Rational(1, 3), 2*z**Rational(3, 2)/3)/(3*(z**Rational(3, 2))**Rational(1, 3)) + (z**Rational(3, 2))**Rational(1, 3)*besseli(Rational(-1, 3), 2*z**Rational(3, 2)/3)/3) assert airyai(p).rewrite(besseli) == ( sqrt(p)*(besseli(Rational(-1, 3), 2*p**Rational(3, 2)/3) - besseli(Rational(1, 3), 2*p**Rational(3, 2)/3))/3) assert expand_func(airyai(2*(3*z**5)**Rational(1, 3))) == ( -sqrt(3)*(-1 + (z**5)**Rational(1, 3)/z**Rational(5, 3))*airybi(2*3**Rational(1, 3)*z**Rational(5, 3))/6 + (1 + (z**5)**Rational(1, 3)/z**Rational(5, 3))*airyai(2*3**Rational(1, 3)*z**Rational(5, 3))/2) def test_airybi(): z = Symbol('z', real=False) t = Symbol('t', negative=True) p = Symbol('p', positive=True) assert isinstance(airybi(z), airybi) assert airybi(0) == 3**Rational(5, 6)/(3*gamma(Rational(2, 3))) assert airybi(oo) is oo assert airybi(-oo) == 0 assert diff(airybi(z), z) == airybiprime(z) assert series(airybi(z), z, 0, 3) == ( 3**Rational(1, 3)*gamma(Rational(1, 3))/(2*pi) + 3**Rational(2, 3)*z*gamma(Rational(2, 3))/(2*pi) + O(z**3)) assert airybi(z).rewrite(hyper) == ( 3**Rational(1, 6)*z*hyper((), (Rational(4, 3),), z**3/9)/gamma(Rational(1, 3)) + 3**Rational(5, 6)*hyper((), (Rational(2, 3),), z**3/9)/(3*gamma(Rational(2, 3)))) assert isinstance(airybi(z).rewrite(besselj), airybi) assert airyai(t).rewrite(besselj) == ( sqrt(-t)*(besselj(Rational(-1, 3), 2*(-t)**Rational(3, 2)/3) + besselj(Rational(1, 3), 2*(-t)**Rational(3, 2)/3))/3) assert airybi(z).rewrite(besseli) == ( sqrt(3)*(z*besseli(Rational(1, 3), 2*z**Rational(3, 2)/3)/(z**Rational(3, 2))**Rational(1, 3) + (z**Rational(3, 2))**Rational(1, 3)*besseli(Rational(-1, 3), 2*z**Rational(3, 2)/3))/3) assert airybi(p).rewrite(besseli) == ( sqrt(3)*sqrt(p)*(besseli(Rational(-1, 3), 2*p**Rational(3, 2)/3) + besseli(Rational(1, 3), 2*p**Rational(3, 2)/3))/3) assert expand_func(airybi(2*(3*z**5)**Rational(1, 3))) == ( sqrt(3)*(1 - (z**5)**Rational(1, 3)/z**Rational(5, 3))*airyai(2*3**Rational(1, 3)*z**Rational(5, 3))/2 + (1 + (z**5)**Rational(1, 3)/z**Rational(5, 3))*airybi(2*3**Rational(1, 3)*z**Rational(5, 3))/2) def test_airyaiprime(): z = Symbol('z', real=False) t = Symbol('t', negative=True) p = Symbol('p', positive=True) assert isinstance(airyaiprime(z), airyaiprime) assert airyaiprime(0) == -3**Rational(2, 3)/(3*gamma(Rational(1, 3))) assert airyaiprime(oo) == 0 assert diff(airyaiprime(z), z) == z*airyai(z) assert series(airyaiprime(z), z, 0, 3) == ( -3**Rational(2, 3)/(3*gamma(Rational(1, 3))) + 3**Rational(1, 3)*z**2/(6*gamma(Rational(2, 3))) + O(z**3)) assert airyaiprime(z).rewrite(hyper) == ( 3**Rational(1, 3)*z**2*hyper((), (Rational(5, 3),), z**3/9)/(6*gamma(Rational(2, 3))) - 3**Rational(2, 3)*hyper((), (Rational(1, 3),), z**3/9)/(3*gamma(Rational(1, 3)))) assert isinstance(airyaiprime(z).rewrite(besselj), airyaiprime) assert airyai(t).rewrite(besselj) == ( sqrt(-t)*(besselj(Rational(-1, 3), 2*(-t)**Rational(3, 2)/3) + besselj(Rational(1, 3), 2*(-t)**Rational(3, 2)/3))/3) assert airyaiprime(z).rewrite(besseli) == ( z**2*besseli(Rational(2, 3), 2*z**Rational(3, 2)/3)/(3*(z**Rational(3, 2))**Rational(2, 3)) - (z**Rational(3, 2))**Rational(2, 3)*besseli(Rational(-1, 3), 2*z**Rational(3, 2)/3)/3) assert airyaiprime(p).rewrite(besseli) == ( p*(-besseli(Rational(-2, 3), 2*p**Rational(3, 2)/3) + besseli(Rational(2, 3), 2*p**Rational(3, 2)/3))/3) assert expand_func(airyaiprime(2*(3*z**5)**Rational(1, 3))) == ( sqrt(3)*(z**Rational(5, 3)/(z**5)**Rational(1, 3) - 1)*airybiprime(2*3**Rational(1, 3)*z**Rational(5, 3))/6 + (z**Rational(5, 3)/(z**5)**Rational(1, 3) + 1)*airyaiprime(2*3**Rational(1, 3)*z**Rational(5, 3))/2) def test_airybiprime(): z = Symbol('z', real=False) t = Symbol('t', negative=True) p = Symbol('p', positive=True) assert isinstance(airybiprime(z), airybiprime) assert airybiprime(0) == 3**Rational(1, 6)/gamma(Rational(1, 3)) assert airybiprime(oo) is oo assert airybiprime(-oo) == 0 assert diff(airybiprime(z), z) == z*airybi(z) assert series(airybiprime(z), z, 0, 3) == ( 3**Rational(1, 6)/gamma(Rational(1, 3)) + 3**Rational(5, 6)*z**2/(6*gamma(Rational(2, 3))) + O(z**3)) assert airybiprime(z).rewrite(hyper) == ( 3**Rational(5, 6)*z**2*hyper((), (Rational(5, 3),), z**3/9)/(6*gamma(Rational(2, 3))) + 3**Rational(1, 6)*hyper((), (Rational(1, 3),), z**3/9)/gamma(Rational(1, 3))) assert isinstance(airybiprime(z).rewrite(besselj), airybiprime) assert airyai(t).rewrite(besselj) == ( sqrt(-t)*(besselj(Rational(-1, 3), 2*(-t)**Rational(3, 2)/3) + besselj(Rational(1, 3), 2*(-t)**Rational(3, 2)/3))/3) assert airybiprime(z).rewrite(besseli) == ( sqrt(3)*(z**2*besseli(Rational(2, 3), 2*z**Rational(3, 2)/3)/(z**Rational(3, 2))**Rational(2, 3) + (z**Rational(3, 2))**Rational(2, 3)*besseli(Rational(-2, 3), 2*z**Rational(3, 2)/3))/3) assert airybiprime(p).rewrite(besseli) == ( sqrt(3)*p*(besseli(Rational(-2, 3), 2*p**Rational(3, 2)/3) + besseli(Rational(2, 3), 2*p**Rational(3, 2)/3))/3) assert expand_func(airybiprime(2*(3*z**5)**Rational(1, 3))) == ( sqrt(3)*(z**Rational(5, 3)/(z**5)**Rational(1, 3) - 1)*airyaiprime(2*3**Rational(1, 3)*z**Rational(5, 3))/2 + (z**Rational(5, 3)/(z**5)**Rational(1, 3) + 1)*airybiprime(2*3**Rational(1, 3)*z**Rational(5, 3))/2) def test_marcumq(): m = Symbol('m') a = Symbol('a') b = Symbol('b') assert marcumq(0, 0, 0) == 0 assert marcumq(m, 0, b) == uppergamma(m, b**2/2)/gamma(m) assert marcumq(2, 0, 5) == 27*exp(Rational(-25, 2))/2 assert marcumq(0, a, 0) == 1 - exp(-a**2/2) assert marcumq(0, pi, 0) == 1 - exp(-pi**2/2) assert marcumq(1, a, a) == S.Half + exp(-a**2)*besseli(0, a**2)/2 assert marcumq(2, a, a) == S.Half + exp(-a**2)*besseli(0, a**2)/2 + exp(-a**2)*besseli(1, a**2) assert diff(marcumq(1, a, 3), a) == a*(-marcumq(1, a, 3) + marcumq(2, a, 3)) assert diff(marcumq(2, 3, b), b) == -b**2*exp(-b**2/2 - Rational(9, 2))*besseli(1, 3*b)/3 x = Symbol('x') assert marcumq(2, 3, 4).rewrite(Integral, x=x) == \ Integral(x**2*exp(-x**2/2 - Rational(9, 2))*besseli(1, 3*x), (x, 4, oo))/3 assert eq([marcumq(5, -2, 3).rewrite(Integral).evalf(10)], [0.7905769565]) k = Symbol('k') assert marcumq(-3, -5, -7).rewrite(Sum, k=k) == \ exp(-37)*Sum((Rational(5, 7))**k*besseli(k, 35), (k, 4, oo)) assert eq([marcumq(1, 3, 1).rewrite(Sum).evalf(10)], [0.9891705502]) assert marcumq(1, a, a, evaluate=False).rewrite(besseli) == S.Half + exp(-a**2)*besseli(0, a**2)/2 assert marcumq(2, a, a, evaluate=False).rewrite(besseli) == S.Half + exp(-a**2)*besseli(0, a**2)/2 + \ exp(-a**2)*besseli(1, a**2) assert marcumq(3, a, a).rewrite(besseli) == (besseli(1, a**2) + besseli(2, a**2))*exp(-a**2) + \ S.Half + exp(-a**2)*besseli(0, a**2)/2 assert marcumq(5, 8, 8).rewrite(besseli) == exp(-64)*besseli(0, 64)/2 + \ (besseli(4, 64) + besseli(3, 64) + besseli(2, 64) + besseli(1, 64))*exp(-64) + S.Half assert marcumq(m, a, a).rewrite(besseli) == marcumq(m, a, a) x = Symbol('x', integer=True) assert marcumq(x, a, a).rewrite(besseli) == marcumq(x, a, a)
4b8940b8ca2094320c186f43104fbdfbc8299c47c72048e574c5d9b5d2f19dbb
from sympy.core.add import Add from sympy.core.assumptions import check_assumptions from sympy.core.containers import Tuple from sympy.core.exprtools import factor_terms from sympy.core.function import _mexpand from sympy.core.mul import Mul from sympy.core.numbers import Rational from sympy.core.numbers import igcdex, ilcm, igcd from sympy.core.power import integer_nthroot, isqrt from sympy.core.relational import Eq from sympy.core.singleton import S from sympy.core.sorting import default_sort_key, ordered from sympy.core.symbol import Symbol, symbols from sympy.core.sympify import _sympify from sympy.functions.elementary.complexes import sign from sympy.functions.elementary.integers import floor from sympy.functions.elementary.miscellaneous import sqrt from sympy.matrices.dense import MutableDenseMatrix as Matrix from sympy.ntheory.factor_ import ( divisors, factorint, multiplicity, perfect_power) from sympy.ntheory.generate import nextprime from sympy.ntheory.primetest import is_square, isprime from sympy.ntheory.residue_ntheory import sqrt_mod from sympy.polys.polyerrors import GeneratorsNeeded from sympy.polys.polytools import Poly, factor_list from sympy.simplify.simplify import signsimp from sympy.solvers.solveset import solveset_real from sympy.utilities import numbered_symbols from sympy.utilities.misc import as_int, filldedent from sympy.utilities.iterables import (is_sequence, subsets, permute_signs, signed_permutations, ordered_partitions) # these are imported with 'from sympy.solvers.diophantine import * __all__ = ['diophantine', 'classify_diop'] class DiophantineSolutionSet(set): """ Container for a set of solutions to a particular diophantine equation. The base representation is a set of tuples representing each of the solutions. Parameters ========== symbols : list List of free symbols in the original equation. parameters: list List of parameters to be used in the solution. Examples ======== Adding solutions: >>> from sympy.solvers.diophantine.diophantine import DiophantineSolutionSet >>> from sympy.abc import x, y, t, u >>> s1 = DiophantineSolutionSet([x, y], [t, u]) >>> s1 set() >>> s1.add((2, 3)) >>> s1.add((-1, u)) >>> s1 {(-1, u), (2, 3)} >>> s2 = DiophantineSolutionSet([x, y], [t, u]) >>> s2.add((3, 4)) >>> s1.update(*s2) >>> s1 {(-1, u), (2, 3), (3, 4)} Conversion of solutions into dicts: >>> list(s1.dict_iterator()) [{x: -1, y: u}, {x: 2, y: 3}, {x: 3, y: 4}] Substituting values: >>> s3 = DiophantineSolutionSet([x, y], [t, u]) >>> s3.add((t**2, t + u)) >>> s3 {(t**2, t + u)} >>> s3.subs({t: 2, u: 3}) {(4, 5)} >>> s3.subs(t, -1) {(1, u - 1)} >>> s3.subs(t, 3) {(9, u + 3)} Evaluation at specific values. Positional arguments are given in the same order as the parameters: >>> s3(-2, 3) {(4, 1)} >>> s3(5) {(25, u + 5)} >>> s3(None, 2) {(t**2, t + 2)} """ def __init__(self, symbols_seq, parameters): super().__init__() if not is_sequence(symbols_seq): raise ValueError("Symbols must be given as a sequence.") if not is_sequence(parameters): raise ValueError("Parameters must be given as a sequence.") self.symbols = tuple(symbols_seq) self.parameters = tuple(parameters) def add(self, solution): if len(solution) != len(self.symbols): raise ValueError("Solution should have a length of %s, not %s" % (len(self.symbols), len(solution))) super().add(Tuple(*solution)) def update(self, *solutions): for solution in solutions: self.add(solution) def dict_iterator(self): for solution in ordered(self): yield dict(zip(self.symbols, solution)) def subs(self, *args, **kwargs): result = DiophantineSolutionSet(self.symbols, self.parameters) for solution in self: result.add(solution.subs(*args, **kwargs)) return result def __call__(self, *args): if len(args) > len(self.parameters): raise ValueError("Evaluation should have at most %s values, not %s" % (len(self.parameters), len(args))) return self.subs(list(zip(self.parameters, args))) class DiophantineEquationType: """ Internal representation of a particular diophantine equation type. Parameters ========== equation : The diophantine equation that is being solved. free_symbols : list (optional) The symbols being solved for. Attributes ========== total_degree : The maximum of the degrees of all terms in the equation homogeneous : Does the equation contain a term of degree 0 homogeneous_order : Does the equation contain any coefficient that is in the symbols being solved for dimension : The number of symbols being solved for """ name = None # type: str def __init__(self, equation, free_symbols=None): self.equation = _sympify(equation).expand(force=True) if free_symbols is not None: self.free_symbols = free_symbols else: self.free_symbols = list(self.equation.free_symbols) self.free_symbols.sort(key=default_sort_key) if not self.free_symbols: raise ValueError('equation should have 1 or more free symbols') self.coeff = self.equation.as_coefficients_dict() if not all(_is_int(c) for c in self.coeff.values()): raise TypeError("Coefficients should be Integers") self.total_degree = Poly(self.equation).total_degree() self.homogeneous = 1 not in self.coeff self.homogeneous_order = not (set(self.coeff) & set(self.free_symbols)) self.dimension = len(self.free_symbols) self._parameters = None def matches(self): """ Determine whether the given equation can be matched to the particular equation type. """ return False @property def n_parameters(self): return self.dimension @property def parameters(self): if self._parameters is None: self._parameters = symbols('t_:%i' % (self.n_parameters,), integer=True) return self._parameters def solve(self, parameters=None, limit=None) -> DiophantineSolutionSet: raise NotImplementedError('No solver has been written for %s.' % self.name) def pre_solve(self, parameters=None): if not self.matches(): raise ValueError("This equation does not match the %s equation type." % self.name) if parameters is not None: if len(parameters) != self.n_parameters: raise ValueError("Expected %s parameter(s) but got %s" % (self.n_parameters, len(parameters))) self._parameters = parameters class Univariate(DiophantineEquationType): """ Representation of a univariate diophantine equation. A univariate diophantine equation is an equation of the form `a_{0} + a_{1}x + a_{2}x^2 + .. + a_{n}x^n = 0` where `a_{1}, a_{2}, ..a_{n}` are integer constants and `x` is an integer variable. Examples ======== >>> from sympy.solvers.diophantine.diophantine import Univariate >>> from sympy.abc import x >>> Univariate((x - 2)*(x - 3)**2).solve() # solves equation (x - 2)*(x - 3)**2 == 0 {(2,), (3,)} """ name = 'univariate' def matches(self): return self.dimension == 1 def solve(self, parameters=None, limit=None): self.pre_solve(parameters) result = DiophantineSolutionSet(self.free_symbols, parameters=self.parameters) for i in solveset_real(self.equation, self.free_symbols[0]).intersect(S.Integers): result.add((i,)) return result class Linear(DiophantineEquationType): """ Representation of a linear diophantine equation. A linear diophantine equation is an equation of the form `a_{1}x_{1} + a_{2}x_{2} + .. + a_{n}x_{n} = 0` where `a_{1}, a_{2}, ..a_{n}` are integer constants and `x_{1}, x_{2}, ..x_{n}` are integer variables. Examples ======== >>> from sympy.solvers.diophantine.diophantine import Linear >>> from sympy.abc import x, y, z >>> l1 = Linear(2*x - 3*y - 5) >>> l1.matches() # is this equation linear True >>> l1.solve() # solves equation 2*x - 3*y - 5 == 0 {(3*t_0 - 5, 2*t_0 - 5)} Here x = -3*t_0 - 5 and y = -2*t_0 - 5 >>> Linear(2*x - 3*y - 4*z -3).solve() {(t_0, 2*t_0 + 4*t_1 + 3, -t_0 - 3*t_1 - 3)} """ name = 'linear' def matches(self): return self.total_degree == 1 def solve(self, parameters=None, limit=None): self.pre_solve(parameters) coeff = self.coeff var = self.free_symbols if 1 in coeff: # negate coeff[] because input is of the form: ax + by + c == 0 # but is used as: ax + by == -c c = -coeff[1] else: c = 0 result = DiophantineSolutionSet(var, parameters=self.parameters) params = result.parameters if len(var) == 1: q, r = divmod(c, coeff[var[0]]) if not r: result.add((q,)) return result else: return result ''' base_solution_linear() can solve diophantine equations of the form: a*x + b*y == c We break down multivariate linear diophantine equations into a series of bivariate linear diophantine equations which can then be solved individually by base_solution_linear(). Consider the following: a_0*x_0 + a_1*x_1 + a_2*x_2 == c which can be re-written as: a_0*x_0 + g_0*y_0 == c where g_0 == gcd(a_1, a_2) and y == (a_1*x_1)/g_0 + (a_2*x_2)/g_0 This leaves us with two binary linear diophantine equations. For the first equation: a == a_0 b == g_0 c == c For the second: a == a_1/g_0 b == a_2/g_0 c == the solution we find for y_0 in the first equation. The arrays A and B are the arrays of integers used for 'a' and 'b' in each of the n-1 bivariate equations we solve. ''' A = [coeff[v] for v in var] B = [] if len(var) > 2: B.append(igcd(A[-2], A[-1])) A[-2] = A[-2] // B[0] A[-1] = A[-1] // B[0] for i in range(len(A) - 3, 0, -1): gcd = igcd(B[0], A[i]) B[0] = B[0] // gcd A[i] = A[i] // gcd B.insert(0, gcd) B.append(A[-1]) ''' Consider the trivariate linear equation: 4*x_0 + 6*x_1 + 3*x_2 == 2 This can be re-written as: 4*x_0 + 3*y_0 == 2 where y_0 == 2*x_1 + x_2 (Note that gcd(3, 6) == 3) The complete integral solution to this equation is: x_0 == 2 + 3*t_0 y_0 == -2 - 4*t_0 where 't_0' is any integer. Now that we have a solution for 'x_0', find 'x_1' and 'x_2': 2*x_1 + x_2 == -2 - 4*t_0 We can then solve for '-2' and '-4' independently, and combine the results: 2*x_1a + x_2a == -2 x_1a == 0 + t_0 x_2a == -2 - 2*t_0 2*x_1b + x_2b == -4*t_0 x_1b == 0*t_0 + t_1 x_2b == -4*t_0 - 2*t_1 ==> x_1 == t_0 + t_1 x_2 == -2 - 6*t_0 - 2*t_1 where 't_0' and 't_1' are any integers. Note that: 4*(2 + 3*t_0) + 6*(t_0 + t_1) + 3*(-2 - 6*t_0 - 2*t_1) == 2 for any integral values of 't_0', 't_1'; as required. This method is generalised for many variables, below. ''' solutions = [] for i in range(len(B)): tot_x, tot_y = [], [] for j, arg in enumerate(Add.make_args(c)): if arg.is_Integer: # example: 5 -> k = 5 k, p = arg, S.One pnew = params[0] else: # arg is a Mul or Symbol # example: 3*t_1 -> k = 3 # example: t_0 -> k = 1 k, p = arg.as_coeff_Mul() pnew = params[params.index(p) + 1] sol = sol_x, sol_y = base_solution_linear(k, A[i], B[i], pnew) if p is S.One: if None in sol: return result else: # convert a + b*pnew -> a*p + b*pnew if isinstance(sol_x, Add): sol_x = sol_x.args[0]*p + sol_x.args[1] if isinstance(sol_y, Add): sol_y = sol_y.args[0]*p + sol_y.args[1] tot_x.append(sol_x) tot_y.append(sol_y) solutions.append(Add(*tot_x)) c = Add(*tot_y) solutions.append(c) result.add(solutions) return result class BinaryQuadratic(DiophantineEquationType): """ Representation of a binary quadratic diophantine equation. A binary quadratic diophantine equation is an equation of the form `Ax^2 + Bxy + Cy^2 + Dx + Ey + F = 0`, where `A, B, C, D, E, F` are integer constants and `x` and `y` are integer variables. Examples ======== >>> from sympy.abc import x, y >>> from sympy.solvers.diophantine.diophantine import BinaryQuadratic >>> b1 = BinaryQuadratic(x**3 + y**2 + 1) >>> b1.matches() False >>> b2 = BinaryQuadratic(x**2 + y**2 + 2*x + 2*y + 2) >>> b2.matches() True >>> b2.solve() {(-1, -1)} References ========== .. [1] Methods to solve Ax^2 + Bxy + Cy^2 + Dx + Ey + F = 0, [online], Available: http://www.alpertron.com.ar/METHODS.HTM .. [2] Solving the equation ax^2+ bxy + cy^2 + dx + ey + f= 0, [online], Available: https://web.archive.org/web/20160323033111/http://www.jpr2718.org/ax2p.pdf """ name = 'binary_quadratic' def matches(self): return self.total_degree == 2 and self.dimension == 2 def solve(self, parameters=None, limit=None) -> DiophantineSolutionSet: self.pre_solve(parameters) var = self.free_symbols coeff = self.coeff x, y = var A = coeff[x**2] B = coeff[x*y] C = coeff[y**2] D = coeff[x] E = coeff[y] F = coeff[S.One] A, B, C, D, E, F = [as_int(i) for i in _remove_gcd(A, B, C, D, E, F)] # (1) Simple-Hyperbolic case: A = C = 0, B != 0 # In this case equation can be converted to (Bx + E)(By + D) = DE - BF # We consider two cases; DE - BF = 0 and DE - BF != 0 # More details, http://www.alpertron.com.ar/METHODS.HTM#SHyperb result = DiophantineSolutionSet(var, self.parameters) t, u = result.parameters discr = B**2 - 4*A*C if A == 0 and C == 0 and B != 0: if D*E - B*F == 0: q, r = divmod(E, B) if not r: result.add((-q, t)) q, r = divmod(D, B) if not r: result.add((t, -q)) else: div = divisors(D*E - B*F) div = div + [-term for term in div] for d in div: x0, r = divmod(d - E, B) if not r: q, r = divmod(D*E - B*F, d) if not r: y0, r = divmod(q - D, B) if not r: result.add((x0, y0)) # (2) Parabolic case: B**2 - 4*A*C = 0 # There are two subcases to be considered in this case. # sqrt(c)D - sqrt(a)E = 0 and sqrt(c)D - sqrt(a)E != 0 # More Details, http://www.alpertron.com.ar/METHODS.HTM#Parabol elif discr == 0: if A == 0: s = BinaryQuadratic(self.equation, free_symbols=[y, x]).solve(parameters=[t, u]) for soln in s: result.add((soln[1], soln[0])) else: g = sign(A)*igcd(A, C) a = A // g c = C // g e = sign(B / A) sqa = isqrt(a) sqc = isqrt(c) _c = e*sqc*D - sqa*E if not _c: z = symbols("z", real=True) eq = sqa*g*z**2 + D*z + sqa*F roots = solveset_real(eq, z).intersect(S.Integers) for root in roots: ans = diop_solve(sqa*x + e*sqc*y - root) result.add((ans[0], ans[1])) elif _is_int(c): solve_x = lambda u: -e*sqc*g*_c*t**2 - (E + 2*e*sqc*g*u)*t \ - (e*sqc*g*u**2 + E*u + e*sqc*F) // _c solve_y = lambda u: sqa*g*_c*t**2 + (D + 2*sqa*g*u)*t \ + (sqa*g*u**2 + D*u + sqa*F) // _c for z0 in range(0, abs(_c)): # Check if the coefficients of y and x obtained are integers or not if (divisible(sqa*g*z0**2 + D*z0 + sqa*F, _c) and divisible(e*sqc*g*z0**2 + E*z0 + e*sqc*F, _c)): result.add((solve_x(z0), solve_y(z0))) # (3) Method used when B**2 - 4*A*C is a square, is described in p. 6 of the below paper # by John P. Robertson. # https://web.archive.org/web/20160323033111/http://www.jpr2718.org/ax2p.pdf elif is_square(discr): if A != 0: r = sqrt(discr) u, v = symbols("u, v", integer=True) eq = _mexpand( 4*A*r*u*v + 4*A*D*(B*v + r*u + r*v - B*u) + 2*A*4*A*E*(u - v) + 4*A*r*4*A*F) solution = diop_solve(eq, t) for s0, t0 in solution: num = B*t0 + r*s0 + r*t0 - B*s0 x_0 = S(num) / (4*A*r) y_0 = S(s0 - t0) / (2*r) if isinstance(s0, Symbol) or isinstance(t0, Symbol): if len(check_param(x_0, y_0, 4*A*r, parameters)) > 0: ans = check_param(x_0, y_0, 4*A*r, parameters) result.update(*ans) elif x_0.is_Integer and y_0.is_Integer: if is_solution_quad(var, coeff, x_0, y_0): result.add((x_0, y_0)) else: s = BinaryQuadratic(self.equation, free_symbols=var[::-1]).solve(parameters=[t, u]) # Interchange x and y while s: result.add(s.pop()[::-1]) # and solution <--------+ # (4) B**2 - 4*A*C > 0 and B**2 - 4*A*C not a square or B**2 - 4*A*C < 0 else: P, Q = _transformation_to_DN(var, coeff) D, N = _find_DN(var, coeff) solns_pell = diop_DN(D, N) if D < 0: for x0, y0 in solns_pell: for x in [-x0, x0]: for y in [-y0, y0]: s = P*Matrix([x, y]) + Q try: result.add([as_int(_) for _ in s]) except ValueError: pass else: # In this case equation can be transformed into a Pell equation solns_pell = set(solns_pell) for X, Y in list(solns_pell): solns_pell.add((-X, -Y)) a = diop_DN(D, 1) T = a[0][0] U = a[0][1] if all(_is_int(_) for _ in P[:4] + Q[:2]): for r, s in solns_pell: _a = (r + s*sqrt(D))*(T + U*sqrt(D))**t _b = (r - s*sqrt(D))*(T - U*sqrt(D))**t x_n = _mexpand(S(_a + _b) / 2) y_n = _mexpand(S(_a - _b) / (2*sqrt(D))) s = P*Matrix([x_n, y_n]) + Q result.add(s) else: L = ilcm(*[_.q for _ in P[:4] + Q[:2]]) k = 1 T_k = T U_k = U while (T_k - 1) % L != 0 or U_k % L != 0: T_k, U_k = T_k*T + D*U_k*U, T_k*U + U_k*T k += 1 for X, Y in solns_pell: for i in range(k): if all(_is_int(_) for _ in P*Matrix([X, Y]) + Q): _a = (X + sqrt(D)*Y)*(T_k + sqrt(D)*U_k)**t _b = (X - sqrt(D)*Y)*(T_k - sqrt(D)*U_k)**t Xt = S(_a + _b) / 2 Yt = S(_a - _b) / (2*sqrt(D)) s = P*Matrix([Xt, Yt]) + Q result.add(s) X, Y = X*T + D*U*Y, X*U + Y*T return result class InhomogeneousTernaryQuadratic(DiophantineEquationType): """ Representation of an inhomogeneous ternary quadratic. No solver is currently implemented for this equation type. """ name = 'inhomogeneous_ternary_quadratic' def matches(self): if not (self.total_degree == 2 and self.dimension == 3): return False if not self.homogeneous: return False return not self.homogeneous_order class HomogeneousTernaryQuadraticNormal(DiophantineEquationType): """ Representation of a homogeneous ternary quadratic normal diophantine equation. Examples ======== >>> from sympy.abc import x, y, z >>> from sympy.solvers.diophantine.diophantine import HomogeneousTernaryQuadraticNormal >>> HomogeneousTernaryQuadraticNormal(4*x**2 - 5*y**2 + z**2).solve() {(1, 2, 4)} """ name = 'homogeneous_ternary_quadratic_normal' def matches(self): if not (self.total_degree == 2 and self.dimension == 3): return False if not self.homogeneous: return False if not self.homogeneous_order: return False nonzero = [k for k in self.coeff if self.coeff[k]] return len(nonzero) == 3 and all(i**2 in nonzero for i in self.free_symbols) def solve(self, parameters=None, limit=None) -> DiophantineSolutionSet: self.pre_solve(parameters) var = self.free_symbols coeff = self.coeff x, y, z = var a = coeff[x**2] b = coeff[y**2] c = coeff[z**2] (sqf_of_a, sqf_of_b, sqf_of_c), (a_1, b_1, c_1), (a_2, b_2, c_2) = \ sqf_normal(a, b, c, steps=True) A = -a_2*c_2 B = -b_2*c_2 result = DiophantineSolutionSet(var, parameters=self.parameters) # If following two conditions are satisfied then there are no solutions if A < 0 and B < 0: return result if ( sqrt_mod(-b_2*c_2, a_2) is None or sqrt_mod(-c_2*a_2, b_2) is None or sqrt_mod(-a_2*b_2, c_2) is None): return result z_0, x_0, y_0 = descent(A, B) z_0, q = _rational_pq(z_0, abs(c_2)) x_0 *= q y_0 *= q x_0, y_0, z_0 = _remove_gcd(x_0, y_0, z_0) # Holzer reduction if sign(a) == sign(b): x_0, y_0, z_0 = holzer(x_0, y_0, z_0, abs(a_2), abs(b_2), abs(c_2)) elif sign(a) == sign(c): x_0, z_0, y_0 = holzer(x_0, z_0, y_0, abs(a_2), abs(c_2), abs(b_2)) else: y_0, z_0, x_0 = holzer(y_0, z_0, x_0, abs(b_2), abs(c_2), abs(a_2)) x_0 = reconstruct(b_1, c_1, x_0) y_0 = reconstruct(a_1, c_1, y_0) z_0 = reconstruct(a_1, b_1, z_0) sq_lcm = ilcm(sqf_of_a, sqf_of_b, sqf_of_c) x_0 = abs(x_0*sq_lcm // sqf_of_a) y_0 = abs(y_0*sq_lcm // sqf_of_b) z_0 = abs(z_0*sq_lcm // sqf_of_c) result.add(_remove_gcd(x_0, y_0, z_0)) return result class HomogeneousTernaryQuadratic(DiophantineEquationType): """ Representation of a homogeneous ternary quadratic diophantine equation. Examples ======== >>> from sympy.abc import x, y, z >>> from sympy.solvers.diophantine.diophantine import HomogeneousTernaryQuadratic >>> HomogeneousTernaryQuadratic(x**2 + y**2 - 3*z**2 + x*y).solve() {(-1, 2, 1)} >>> HomogeneousTernaryQuadratic(3*x**2 + y**2 - 3*z**2 + 5*x*y + y*z).solve() {(3, 12, 13)} """ name = 'homogeneous_ternary_quadratic' def matches(self): if not (self.total_degree == 2 and self.dimension == 3): return False if not self.homogeneous: return False if not self.homogeneous_order: return False nonzero = [k for k in self.coeff if self.coeff[k]] return not (len(nonzero) == 3 and all(i**2 in nonzero for i in self.free_symbols)) def solve(self, parameters=None, limit=None): self.pre_solve(parameters) _var = self.free_symbols coeff = self.coeff x, y, z = _var var = [x, y, z] # Equations of the form B*x*y + C*z*x + E*y*z = 0 and At least two of the # coefficients A, B, C are non-zero. # There are infinitely many solutions for the equation. # Ex: (0, 0, t), (0, t, 0), (t, 0, 0) # Equation can be re-written as y*(B*x + E*z) = -C*x*z and we can find rather # unobvious solutions. Set y = -C and B*x + E*z = x*z. The latter can be solved by # using methods for binary quadratic diophantine equations. Let's select the # solution which minimizes |x| + |z| result = DiophantineSolutionSet(var, parameters=self.parameters) def unpack_sol(sol): if len(sol) > 0: return list(sol)[0] return None, None, None if not any(coeff[i**2] for i in var): if coeff[x*z]: sols = diophantine(coeff[x*y]*x + coeff[y*z]*z - x*z) s = sols.pop() min_sum = abs(s[0]) + abs(s[1]) for r in sols: m = abs(r[0]) + abs(r[1]) if m < min_sum: s = r min_sum = m result.add(_remove_gcd(s[0], -coeff[x*z], s[1])) return result else: var[0], var[1] = _var[1], _var[0] y_0, x_0, z_0 = unpack_sol(_diop_ternary_quadratic(var, coeff)) if x_0 is not None: result.add((x_0, y_0, z_0)) return result if coeff[x**2] == 0: # If the coefficient of x is zero change the variables if coeff[y**2] == 0: var[0], var[2] = _var[2], _var[0] z_0, y_0, x_0 = unpack_sol(_diop_ternary_quadratic(var, coeff)) else: var[0], var[1] = _var[1], _var[0] y_0, x_0, z_0 = unpack_sol(_diop_ternary_quadratic(var, coeff)) else: if coeff[x*y] or coeff[x*z]: # Apply the transformation x --> X - (B*y + C*z)/(2*A) A = coeff[x**2] B = coeff[x*y] C = coeff[x*z] D = coeff[y**2] E = coeff[y*z] F = coeff[z**2] _coeff = dict() _coeff[x**2] = 4*A**2 _coeff[y**2] = 4*A*D - B**2 _coeff[z**2] = 4*A*F - C**2 _coeff[y*z] = 4*A*E - 2*B*C _coeff[x*y] = 0 _coeff[x*z] = 0 x_0, y_0, z_0 = unpack_sol(_diop_ternary_quadratic(var, _coeff)) if x_0 is None: return result p, q = _rational_pq(B*y_0 + C*z_0, 2*A) x_0, y_0, z_0 = x_0*q - p, y_0*q, z_0*q elif coeff[z*y] != 0: if coeff[y**2] == 0: if coeff[z**2] == 0: # Equations of the form A*x**2 + E*yz = 0. A = coeff[x**2] E = coeff[y*z] b, a = _rational_pq(-E, A) x_0, y_0, z_0 = b, a, b else: # Ax**2 + E*y*z + F*z**2 = 0 var[0], var[2] = _var[2], _var[0] z_0, y_0, x_0 = unpack_sol(_diop_ternary_quadratic(var, coeff)) else: # A*x**2 + D*y**2 + E*y*z + F*z**2 = 0, C may be zero var[0], var[1] = _var[1], _var[0] y_0, x_0, z_0 = unpack_sol(_diop_ternary_quadratic(var, coeff)) else: # Ax**2 + D*y**2 + F*z**2 = 0, C may be zero x_0, y_0, z_0 = unpack_sol(_diop_ternary_quadratic_normal(var, coeff)) if x_0 is None: return result result.add(_remove_gcd(x_0, y_0, z_0)) return result class InhomogeneousGeneralQuadratic(DiophantineEquationType): """ Representation of an inhomogeneous general quadratic. No solver is currently implemented for this equation type. """ name = 'inhomogeneous_general_quadratic' def matches(self): if not (self.total_degree == 2 and self.dimension >= 3): return False if not self.homogeneous_order: return True else: # there may be Pow keys like x**2 or Mul keys like x*y if any(k.is_Mul for k in self.coeff): # cross terms return not self.homogeneous return False class HomogeneousGeneralQuadratic(DiophantineEquationType): """ Representation of a homogeneous general quadratic. No solver is currently implemented for this equation type. """ name = 'homogeneous_general_quadratic' def matches(self): if not (self.total_degree == 2 and self.dimension >= 3): return False if not self.homogeneous_order: return False else: # there may be Pow keys like x**2 or Mul keys like x*y if any(k.is_Mul for k in self.coeff): # cross terms return self.homogeneous return False class GeneralSumOfSquares(DiophantineEquationType): r""" Representation of the diophantine equation `x_{1}^2 + x_{2}^2 + . . . + x_{n}^2 - k = 0`. Details ======= When `n = 3` if `k = 4^a(8m + 7)` for some `a, m \in Z` then there will be no solutions. Refer [1]_ for more details. Examples ======== >>> from sympy.solvers.diophantine.diophantine import GeneralSumOfSquares >>> from sympy.abc import a, b, c, d, e >>> GeneralSumOfSquares(a**2 + b**2 + c**2 + d**2 + e**2 - 2345).solve() {(15, 22, 22, 24, 24)} By default only 1 solution is returned. Use the `limit` keyword for more: >>> sorted(GeneralSumOfSquares(a**2 + b**2 + c**2 + d**2 + e**2 - 2345).solve(limit=3)) [(15, 22, 22, 24, 24), (16, 19, 24, 24, 24), (16, 20, 22, 23, 26)] References ========== .. [1] Representing an integer as a sum of three squares, [online], Available: http://www.proofwiki.org/wiki/Integer_as_Sum_of_Three_Squares """ name = 'general_sum_of_squares' def matches(self): if not (self.total_degree == 2 and self.dimension >= 3): return False if not self.homogeneous_order: return False if any(k.is_Mul for k in self.coeff): return False return all(self.coeff[k] == 1 for k in self.coeff if k != 1) def solve(self, parameters=None, limit=1): self.pre_solve(parameters) var = self.free_symbols k = -int(self.coeff[1]) n = self.dimension result = DiophantineSolutionSet(var, parameters=self.parameters) if k < 0 or limit < 1: return result signs = [-1 if x.is_nonpositive else 1 for x in var] negs = signs.count(-1) != 0 took = 0 for t in sum_of_squares(k, n, zeros=True): if negs: result.add([signs[i]*j for i, j in enumerate(t)]) else: result.add(t) took += 1 if took == limit: break return result class GeneralPythagorean(DiophantineEquationType): """ Representation of the general pythagorean equation, `a_{1}^2x_{1}^2 + a_{2}^2x_{2}^2 + . . . + a_{n}^2x_{n}^2 - a_{n + 1}^2x_{n + 1}^2 = 0`. Examples ======== >>> from sympy.solvers.diophantine.diophantine import GeneralPythagorean >>> from sympy.abc import a, b, c, d, e, x, y, z, t >>> GeneralPythagorean(a**2 + b**2 + c**2 - d**2).solve() {(t_0**2 + t_1**2 - t_2**2, 2*t_0*t_2, 2*t_1*t_2, t_0**2 + t_1**2 + t_2**2)} >>> GeneralPythagorean(9*a**2 - 4*b**2 + 16*c**2 + 25*d**2 + e**2).solve(parameters=[x, y, z, t]) {(-10*t**2 + 10*x**2 + 10*y**2 + 10*z**2, 15*t**2 + 15*x**2 + 15*y**2 + 15*z**2, 15*t*x, 12*t*y, 60*t*z)} """ name = 'general_pythagorean' def matches(self): if not (self.total_degree == 2 and self.dimension >= 3): return False if not self.homogeneous_order: return False if any(k.is_Mul for k in self.coeff): return False if all(self.coeff[k] == 1 for k in self.coeff if k != 1): return False if not all(is_square(abs(self.coeff[k])) for k in self.coeff): return False # all but one has the same sign # e.g. 4*x**2 + y**2 - 4*z**2 return abs(sum(sign(self.coeff[k]) for k in self.coeff)) == self.dimension - 2 @property def n_parameters(self): return self.dimension - 1 def solve(self, parameters=None, limit=1): self.pre_solve(parameters) coeff = self.coeff var = self.free_symbols n = self.dimension if sign(coeff[var[0] ** 2]) + sign(coeff[var[1] ** 2]) + sign(coeff[var[2] ** 2]) < 0: for key in coeff.keys(): coeff[key] = -coeff[key] result = DiophantineSolutionSet(var, parameters=self.parameters) index = 0 for i, v in enumerate(var): if sign(coeff[v ** 2]) == -1: index = i m = result.parameters ith = sum(m_i ** 2 for m_i in m) L = [ith - 2 * m[n - 2] ** 2] L.extend([2 * m[i] * m[n - 2] for i in range(n - 2)]) sol = L[:index] + [ith] + L[index:] lcm = 1 for i, v in enumerate(var): if i == index or (index > 0 and i == 0) or (index == 0 and i == 1): lcm = ilcm(lcm, sqrt(abs(coeff[v ** 2]))) else: s = sqrt(coeff[v ** 2]) lcm = ilcm(lcm, s if _odd(s) else s // 2) for i, v in enumerate(var): sol[i] = (lcm * sol[i]) / sqrt(abs(coeff[v ** 2])) result.add(sol) return result class CubicThue(DiophantineEquationType): """ Representation of a cubic Thue diophantine equation. A cubic Thue diophantine equation is a polynomial of the form `f(x, y) = r` of degree 3, where `x` and `y` are integers and `r` is a rational number. No solver is currently implemented for this equation type. Examples ======== >>> from sympy.abc import x, y >>> from sympy.solvers.diophantine.diophantine import CubicThue >>> c1 = CubicThue(x**3 + y**2 + 1) >>> c1.matches() True """ name = 'cubic_thue' def matches(self): return self.total_degree == 3 and self.dimension == 2 class GeneralSumOfEvenPowers(DiophantineEquationType): """ Representation of the diophantine equation `x_{1}^e + x_{2}^e + . . . + x_{n}^e - k = 0` where `e` is an even, integer power. Examples ======== >>> from sympy.solvers.diophantine.diophantine import GeneralSumOfEvenPowers >>> from sympy.abc import a, b >>> GeneralSumOfEvenPowers(a**4 + b**4 - (2**4 + 3**4)).solve() {(2, 3)} """ name = 'general_sum_of_even_powers' def matches(self): if not self.total_degree > 3: return False if self.total_degree % 2 != 0: return False if not all(k.is_Pow and k.exp == self.total_degree for k in self.coeff if k != 1): return False return all(self.coeff[k] == 1 for k in self.coeff if k != 1) def solve(self, parameters=None, limit=1): self.pre_solve(parameters) var = self.free_symbols coeff = self.coeff p = None for q in coeff.keys(): if q.is_Pow and coeff[q]: p = q.exp k = len(var) n = -coeff[1] result = DiophantineSolutionSet(var, parameters=self.parameters) if n < 0 or limit < 1: return result sign = [-1 if x.is_nonpositive else 1 for x in var] negs = sign.count(-1) != 0 took = 0 for t in power_representation(n, p, k): if negs: result.add([sign[i]*j for i, j in enumerate(t)]) else: result.add(t) took += 1 if took == limit: break return result # these types are known (but not necessarily handled) # note that order is important here (in the current solver state) all_diop_classes = [ Linear, Univariate, BinaryQuadratic, InhomogeneousTernaryQuadratic, HomogeneousTernaryQuadraticNormal, HomogeneousTernaryQuadratic, InhomogeneousGeneralQuadratic, HomogeneousGeneralQuadratic, GeneralSumOfSquares, GeneralPythagorean, CubicThue, GeneralSumOfEvenPowers, ] diop_known = {diop_class.name for diop_class in all_diop_classes} def _is_int(i): try: as_int(i) return True except ValueError: pass def _sorted_tuple(*i): return tuple(sorted(i)) def _remove_gcd(*x): try: g = igcd(*x) except ValueError: fx = list(filter(None, x)) if len(fx) < 2: return x g = igcd(*[i.as_content_primitive()[0] for i in fx]) except TypeError: raise TypeError('_remove_gcd(a,b,c) or _remove_gcd(*container)') if g == 1: return x return tuple([i//g for i in x]) def _rational_pq(a, b): # return `(numer, denom)` for a/b; sign in numer and gcd removed return _remove_gcd(sign(b)*a, abs(b)) def _nint_or_floor(p, q): # return nearest int to p/q; in case of tie return floor(p/q) w, r = divmod(p, q) if abs(r) <= abs(q)//2: return w return w + 1 def _odd(i): return i % 2 != 0 def _even(i): return i % 2 == 0 def diophantine(eq, param=symbols("t", integer=True), syms=None, permute=False): """ Simplify the solution procedure of diophantine equation ``eq`` by converting it into a product of terms which should equal zero. Explanation =========== For example, when solving, `x^2 - y^2 = 0` this is treated as `(x + y)(x - y) = 0` and `x + y = 0` and `x - y = 0` are solved independently and combined. Each term is solved by calling ``diop_solve()``. (Although it is possible to call ``diop_solve()`` directly, one must be careful to pass an equation in the correct form and to interpret the output correctly; ``diophantine()`` is the public-facing function to use in general.) Output of ``diophantine()`` is a set of tuples. The elements of the tuple are the solutions for each variable in the equation and are arranged according to the alphabetic ordering of the variables. e.g. For an equation with two variables, `a` and `b`, the first element of the tuple is the solution for `a` and the second for `b`. Usage ===== ``diophantine(eq, t, syms)``: Solve the diophantine equation ``eq``. ``t`` is the optional parameter to be used by ``diop_solve()``. ``syms`` is an optional list of symbols which determines the order of the elements in the returned tuple. By default, only the base solution is returned. If ``permute`` is set to True then permutations of the base solution and/or permutations of the signs of the values will be returned when applicable. Examples ======== >>> from sympy import diophantine >>> from sympy.abc import a, b >>> eq = a**4 + b**4 - (2**4 + 3**4) >>> diophantine(eq) {(2, 3)} >>> diophantine(eq, permute=True) {(-3, -2), (-3, 2), (-2, -3), (-2, 3), (2, -3), (2, 3), (3, -2), (3, 2)} Details ======= ``eq`` should be an expression which is assumed to be zero. ``t`` is the parameter to be used in the solution. Examples ======== >>> from sympy.abc import x, y, z >>> diophantine(x**2 - y**2) {(t_0, -t_0), (t_0, t_0)} >>> diophantine(x*(2*x + 3*y - z)) {(0, n1, n2), (t_0, t_1, 2*t_0 + 3*t_1)} >>> diophantine(x**2 + 3*x*y + 4*x) {(0, n1), (3*t_0 - 4, -t_0)} See Also ======== diop_solve() sympy.utilities.iterables.permute_signs sympy.utilities.iterables.signed_permutations """ eq = _sympify(eq) if isinstance(eq, Eq): eq = eq.lhs - eq.rhs try: var = list(eq.expand(force=True).free_symbols) var.sort(key=default_sort_key) if syms: if not is_sequence(syms): raise TypeError( 'syms should be given as a sequence, e.g. a list') syms = [i for i in syms if i in var] if syms != var: dict_sym_index = dict(zip(syms, range(len(syms)))) return {tuple([t[dict_sym_index[i]] for i in var]) for t in diophantine(eq, param, permute=permute)} n, d = eq.as_numer_denom() if n.is_number: return set() if not d.is_number: dsol = diophantine(d) good = diophantine(n) - dsol return {s for s in good if _mexpand(d.subs(zip(var, s)))} else: eq = n eq = factor_terms(eq) assert not eq.is_number eq = eq.as_independent(*var, as_Add=False)[1] p = Poly(eq) assert not any(g.is_number for g in p.gens) eq = p.as_expr() assert eq.is_polynomial() except (GeneratorsNeeded, AssertionError): raise TypeError(filldedent(''' Equation should be a polynomial with Rational coefficients.''')) # permute only sign do_permute_signs = False # permute sign and values do_permute_signs_var = False # permute few signs permute_few_signs = False try: # if we know that factoring should not be attempted, skip # the factoring step v, c, t = classify_diop(eq) # check for permute sign if permute: len_var = len(v) permute_signs_for = [ GeneralSumOfSquares.name, GeneralSumOfEvenPowers.name] permute_signs_check = [ HomogeneousTernaryQuadratic.name, HomogeneousTernaryQuadraticNormal.name, BinaryQuadratic.name] if t in permute_signs_for: do_permute_signs_var = True elif t in permute_signs_check: # if all the variables in eq have even powers # then do_permute_sign = True if len_var == 3: var_mul = list(subsets(v, 2)) # here var_mul is like [(x, y), (x, z), (y, z)] xy_coeff = True x_coeff = True var1_mul_var2 = map(lambda a: a[0]*a[1], var_mul) # if coeff(y*z), coeff(y*x), coeff(x*z) is not 0 then # `xy_coeff` => True and do_permute_sign => False. # Means no permuted solution. for v1_mul_v2 in var1_mul_var2: try: coeff = c[v1_mul_v2] except KeyError: coeff = 0 xy_coeff = bool(xy_coeff) and bool(coeff) var_mul = list(subsets(v, 1)) # here var_mul is like [(x,), (y, )] for v1 in var_mul: try: coeff = c[v1[0]] except KeyError: coeff = 0 x_coeff = bool(x_coeff) and bool(coeff) if not any((xy_coeff, x_coeff)): # means only x**2, y**2, z**2, const is present do_permute_signs = True elif not x_coeff: permute_few_signs = True elif len_var == 2: var_mul = list(subsets(v, 2)) # here var_mul is like [(x, y)] xy_coeff = True x_coeff = True var1_mul_var2 = map(lambda x: x[0]*x[1], var_mul) for v1_mul_v2 in var1_mul_var2: try: coeff = c[v1_mul_v2] except KeyError: coeff = 0 xy_coeff = bool(xy_coeff) and bool(coeff) var_mul = list(subsets(v, 1)) # here var_mul is like [(x,), (y, )] for v1 in var_mul: try: coeff = c[v1[0]] except KeyError: coeff = 0 x_coeff = bool(x_coeff) and bool(coeff) if not any((xy_coeff, x_coeff)): # means only x**2, y**2 and const is present # so we can get more soln by permuting this soln. do_permute_signs = True elif not x_coeff: # when coeff(x), coeff(y) is not present then signs of # x, y can be permuted such that their sign are same # as sign of x*y. # e.g 1. (x_val,y_val)=> (x_val,y_val), (-x_val,-y_val) # 2. (-x_vall, y_val)=> (-x_val,y_val), (x_val,-y_val) permute_few_signs = True if t == 'general_sum_of_squares': # trying to factor such expressions will sometimes hang terms = [(eq, 1)] else: raise TypeError except (TypeError, NotImplementedError): fl = factor_list(eq) if fl[0].is_Rational and fl[0] != 1: return diophantine(eq/fl[0], param=param, syms=syms, permute=permute) terms = fl[1] sols = set() for term in terms: base, _ = term var_t, _, eq_type = classify_diop(base, _dict=False) _, base = signsimp(base, evaluate=False).as_coeff_Mul() solution = diop_solve(base, param) if eq_type in [ Linear.name, HomogeneousTernaryQuadratic.name, HomogeneousTernaryQuadraticNormal.name, GeneralPythagorean.name]: sols.add(merge_solution(var, var_t, solution)) elif eq_type in [ BinaryQuadratic.name, GeneralSumOfSquares.name, GeneralSumOfEvenPowers.name, Univariate.name]: for sol in solution: sols.add(merge_solution(var, var_t, sol)) else: raise NotImplementedError('unhandled type: %s' % eq_type) # remove null merge results if () in sols: sols.remove(()) null = tuple([0]*len(var)) # if there is no solution, return trivial solution if not sols and eq.subs(zip(var, null)).is_zero: sols.add(null) final_soln = set() for sol in sols: if all(_is_int(s) for s in sol): if do_permute_signs: permuted_sign = set(permute_signs(sol)) final_soln.update(permuted_sign) elif permute_few_signs: lst = list(permute_signs(sol)) lst = list(filter(lambda x: x[0]*x[1] == sol[1]*sol[0], lst)) permuted_sign = set(lst) final_soln.update(permuted_sign) elif do_permute_signs_var: permuted_sign_var = set(signed_permutations(sol)) final_soln.update(permuted_sign_var) else: final_soln.add(sol) else: final_soln.add(sol) return final_soln def merge_solution(var, var_t, solution): """ This is used to construct the full solution from the solutions of sub equations. Explanation =========== For example when solving the equation `(x - y)(x^2 + y^2 - z^2) = 0`, solutions for each of the equations `x - y = 0` and `x^2 + y^2 - z^2` are found independently. Solutions for `x - y = 0` are `(x, y) = (t, t)`. But we should introduce a value for z when we output the solution for the original equation. This function converts `(t, t)` into `(t, t, n_{1})` where `n_{1}` is an integer parameter. """ sol = [] if None in solution: return () solution = iter(solution) params = numbered_symbols("n", integer=True, start=1) for v in var: if v in var_t: sol.append(next(solution)) else: sol.append(next(params)) for val, symb in zip(sol, var): if check_assumptions(val, **symb.assumptions0) is False: return tuple() return tuple(sol) def _diop_solve(eq, params=None): for diop_type in all_diop_classes: if diop_type(eq).matches(): return diop_type(eq).solve(parameters=params) def diop_solve(eq, param=symbols("t", integer=True)): """ Solves the diophantine equation ``eq``. Explanation =========== Unlike ``diophantine()``, factoring of ``eq`` is not attempted. Uses ``classify_diop()`` to determine the type of the equation and calls the appropriate solver function. Use of ``diophantine()`` is recommended over other helper functions. ``diop_solve()`` can return either a set or a tuple depending on the nature of the equation. Usage ===== ``diop_solve(eq, t)``: Solve diophantine equation, ``eq`` using ``t`` as a parameter if needed. Details ======= ``eq`` should be an expression which is assumed to be zero. ``t`` is a parameter to be used in the solution. Examples ======== >>> from sympy.solvers.diophantine import diop_solve >>> from sympy.abc import x, y, z, w >>> diop_solve(2*x + 3*y - 5) (3*t_0 - 5, 5 - 2*t_0) >>> diop_solve(4*x + 3*y - 4*z + 5) (t_0, 8*t_0 + 4*t_1 + 5, 7*t_0 + 3*t_1 + 5) >>> diop_solve(x + 3*y - 4*z + w - 6) (t_0, t_0 + t_1, 6*t_0 + 5*t_1 + 4*t_2 - 6, 5*t_0 + 4*t_1 + 3*t_2 - 6) >>> diop_solve(x**2 + y**2 - 5) {(-2, -1), (-2, 1), (-1, -2), (-1, 2), (1, -2), (1, 2), (2, -1), (2, 1)} See Also ======== diophantine() """ var, coeff, eq_type = classify_diop(eq, _dict=False) if eq_type == Linear.name: return diop_linear(eq, param) elif eq_type == BinaryQuadratic.name: return diop_quadratic(eq, param) elif eq_type == HomogeneousTernaryQuadratic.name: return diop_ternary_quadratic(eq, parameterize=True) elif eq_type == HomogeneousTernaryQuadraticNormal.name: return diop_ternary_quadratic_normal(eq, parameterize=True) elif eq_type == GeneralPythagorean.name: return diop_general_pythagorean(eq, param) elif eq_type == Univariate.name: return diop_univariate(eq) elif eq_type == GeneralSumOfSquares.name: return diop_general_sum_of_squares(eq, limit=S.Infinity) elif eq_type == GeneralSumOfEvenPowers.name: return diop_general_sum_of_even_powers(eq, limit=S.Infinity) if eq_type is not None and eq_type not in diop_known: raise ValueError(filldedent(''' Alhough this type of equation was identified, it is not yet handled. It should, however, be listed in `diop_known` at the top of this file. Developers should see comments at the end of `classify_diop`. ''')) # pragma: no cover else: raise NotImplementedError( 'No solver has been written for %s.' % eq_type) def classify_diop(eq, _dict=True): # docstring supplied externally matched = False diop_type = None for diop_class in all_diop_classes: diop_type = diop_class(eq) if diop_type.matches(): matched = True break if matched: return diop_type.free_symbols, dict(diop_type.coeff) if _dict else diop_type.coeff, diop_type.name # new diop type instructions # -------------------------- # if this error raises and the equation *can* be classified, # * it should be identified in the if-block above # * the type should be added to the diop_known # if a solver can be written for it, # * a dedicated handler should be written (e.g. diop_linear) # * it should be passed to that handler in diop_solve raise NotImplementedError(filldedent(''' This equation is not yet recognized or else has not been simplified sufficiently to put it in a form recognized by diop_classify().''')) classify_diop.func_doc = ( # type: ignore ''' Helper routine used by diop_solve() to find information about ``eq``. Explanation =========== Returns a tuple containing the type of the diophantine equation along with the variables (free symbols) and their coefficients. Variables are returned as a list and coefficients are returned as a dict with the key being the respective term and the constant term is keyed to 1. The type is one of the following: * %s Usage ===== ``classify_diop(eq)``: Return variables, coefficients and type of the ``eq``. Details ======= ``eq`` should be an expression which is assumed to be zero. ``_dict`` is for internal use: when True (default) a dict is returned, otherwise a defaultdict which supplies 0 for missing keys is returned. Examples ======== >>> from sympy.solvers.diophantine import classify_diop >>> from sympy.abc import x, y, z, w, t >>> classify_diop(4*x + 6*y - 4) ([x, y], {1: -4, x: 4, y: 6}, 'linear') >>> classify_diop(x + 3*y -4*z + 5) ([x, y, z], {1: 5, x: 1, y: 3, z: -4}, 'linear') >>> classify_diop(x**2 + y**2 - x*y + x + 5) ([x, y], {1: 5, x: 1, x**2: 1, y**2: 1, x*y: -1}, 'binary_quadratic') ''' % ('\n * '.join(sorted(diop_known)))) def diop_linear(eq, param=symbols("t", integer=True)): """ Solves linear diophantine equations. A linear diophantine equation is an equation of the form `a_{1}x_{1} + a_{2}x_{2} + .. + a_{n}x_{n} = 0` where `a_{1}, a_{2}, ..a_{n}` are integer constants and `x_{1}, x_{2}, ..x_{n}` are integer variables. Usage ===== ``diop_linear(eq)``: Returns a tuple containing solutions to the diophantine equation ``eq``. Values in the tuple is arranged in the same order as the sorted variables. Details ======= ``eq`` is a linear diophantine equation which is assumed to be zero. ``param`` is the parameter to be used in the solution. Examples ======== >>> from sympy.solvers.diophantine.diophantine import diop_linear >>> from sympy.abc import x, y, z >>> diop_linear(2*x - 3*y - 5) # solves equation 2*x - 3*y - 5 == 0 (3*t_0 - 5, 2*t_0 - 5) Here x = -3*t_0 - 5 and y = -2*t_0 - 5 >>> diop_linear(2*x - 3*y - 4*z -3) (t_0, 2*t_0 + 4*t_1 + 3, -t_0 - 3*t_1 - 3) See Also ======== diop_quadratic(), diop_ternary_quadratic(), diop_general_pythagorean(), diop_general_sum_of_squares() """ var, coeff, diop_type = classify_diop(eq, _dict=False) if diop_type == Linear.name: parameters = None if param is not None: parameters = symbols('%s_0:%i' % (param, len(var)), integer=True) result = Linear(eq).solve(parameters=parameters) if param is None: result = result(*[0]*len(result.parameters)) if len(result) > 0: return list(result)[0] else: return tuple([None]*len(result.parameters)) def base_solution_linear(c, a, b, t=None): """ Return the base solution for the linear equation, `ax + by = c`. Explanation =========== Used by ``diop_linear()`` to find the base solution of a linear Diophantine equation. If ``t`` is given then the parametrized solution is returned. Usage ===== ``base_solution_linear(c, a, b, t)``: ``a``, ``b``, ``c`` are coefficients in `ax + by = c` and ``t`` is the parameter to be used in the solution. Examples ======== >>> from sympy.solvers.diophantine.diophantine import base_solution_linear >>> from sympy.abc import t >>> base_solution_linear(5, 2, 3) # equation 2*x + 3*y = 5 (-5, 5) >>> base_solution_linear(0, 5, 7) # equation 5*x + 7*y = 0 (0, 0) >>> base_solution_linear(5, 2, 3, t) # equation 2*x + 3*y = 5 (3*t - 5, 5 - 2*t) >>> base_solution_linear(0, 5, 7, t) # equation 5*x + 7*y = 0 (7*t, -5*t) """ a, b, c = _remove_gcd(a, b, c) if c == 0: if t is not None: if b < 0: t = -t return (b*t, -a*t) else: return (0, 0) else: x0, y0, d = igcdex(abs(a), abs(b)) x0 *= sign(a) y0 *= sign(b) if divisible(c, d): if t is not None: if b < 0: t = -t return (c*x0 + b*t, c*y0 - a*t) else: return (c*x0, c*y0) else: return (None, None) def diop_univariate(eq): """ Solves a univariate diophantine equations. Explanation =========== A univariate diophantine equation is an equation of the form `a_{0} + a_{1}x + a_{2}x^2 + .. + a_{n}x^n = 0` where `a_{1}, a_{2}, ..a_{n}` are integer constants and `x` is an integer variable. Usage ===== ``diop_univariate(eq)``: Returns a set containing solutions to the diophantine equation ``eq``. Details ======= ``eq`` is a univariate diophantine equation which is assumed to be zero. Examples ======== >>> from sympy.solvers.diophantine.diophantine import diop_univariate >>> from sympy.abc import x >>> diop_univariate((x - 2)*(x - 3)**2) # solves equation (x - 2)*(x - 3)**2 == 0 {(2,), (3,)} """ var, coeff, diop_type = classify_diop(eq, _dict=False) if diop_type == Univariate.name: return {(int(i),) for i in solveset_real( eq, var[0]).intersect(S.Integers)} def divisible(a, b): """ Returns `True` if ``a`` is divisible by ``b`` and `False` otherwise. """ return not a % b def diop_quadratic(eq, param=symbols("t", integer=True)): """ Solves quadratic diophantine equations. i.e. equations of the form `Ax^2 + Bxy + Cy^2 + Dx + Ey + F = 0`. Returns a set containing the tuples `(x, y)` which contains the solutions. If there are no solutions then `(None, None)` is returned. Usage ===== ``diop_quadratic(eq, param)``: ``eq`` is a quadratic binary diophantine equation. ``param`` is used to indicate the parameter to be used in the solution. Details ======= ``eq`` should be an expression which is assumed to be zero. ``param`` is a parameter to be used in the solution. Examples ======== >>> from sympy.abc import x, y, t >>> from sympy.solvers.diophantine.diophantine import diop_quadratic >>> diop_quadratic(x**2 + y**2 + 2*x + 2*y + 2, t) {(-1, -1)} References ========== .. [1] Methods to solve Ax^2 + Bxy + Cy^2 + Dx + Ey + F = 0, [online], Available: http://www.alpertron.com.ar/METHODS.HTM .. [2] Solving the equation ax^2+ bxy + cy^2 + dx + ey + f= 0, [online], Available: https://web.archive.org/web/20160323033111/http://www.jpr2718.org/ax2p.pdf See Also ======== diop_linear(), diop_ternary_quadratic(), diop_general_sum_of_squares(), diop_general_pythagorean() """ var, coeff, diop_type = classify_diop(eq, _dict=False) if diop_type == BinaryQuadratic.name: if param is not None: parameters = [param, Symbol("u", integer=True)] else: parameters = None return set(BinaryQuadratic(eq).solve(parameters=parameters)) def is_solution_quad(var, coeff, u, v): """ Check whether `(u, v)` is solution to the quadratic binary diophantine equation with the variable list ``var`` and coefficient dictionary ``coeff``. Not intended for use by normal users. """ reps = dict(zip(var, (u, v))) eq = Add(*[j*i.xreplace(reps) for i, j in coeff.items()]) return _mexpand(eq) == 0 def diop_DN(D, N, t=symbols("t", integer=True)): """ Solves the equation `x^2 - Dy^2 = N`. Explanation =========== Mainly concerned with the case `D > 0, D` is not a perfect square, which is the same as the generalized Pell equation. The LMM algorithm [1]_ is used to solve this equation. Returns one solution tuple, (`x, y)` for each class of the solutions. Other solutions of the class can be constructed according to the values of ``D`` and ``N``. Usage ===== ``diop_DN(D, N, t)``: D and N are integers as in `x^2 - Dy^2 = N` and ``t`` is the parameter to be used in the solutions. Details ======= ``D`` and ``N`` correspond to D and N in the equation. ``t`` is the parameter to be used in the solutions. Examples ======== >>> from sympy.solvers.diophantine.diophantine import diop_DN >>> diop_DN(13, -4) # Solves equation x**2 - 13*y**2 = -4 [(3, 1), (393, 109), (36, 10)] The output can be interpreted as follows: There are three fundamental solutions to the equation `x^2 - 13y^2 = -4` given by (3, 1), (393, 109) and (36, 10). Each tuple is in the form (x, y), i.e. solution (3, 1) means that `x = 3` and `y = 1`. >>> diop_DN(986, 1) # Solves equation x**2 - 986*y**2 = 1 [(49299, 1570)] See Also ======== find_DN(), diop_bf_DN() References ========== .. [1] Solving the generalized Pell equation x**2 - D*y**2 = N, John P. Robertson, July 31, 2004, Pages 16 - 17. [online], Available: https://web.archive.org/web/20160323033128/http://www.jpr2718.org/pell.pdf """ if D < 0: if N == 0: return [(0, 0)] elif N < 0: return [] elif N > 0: sol = [] for d in divisors(square_factor(N)): sols = cornacchia(1, -D, N // d**2) if sols: for x, y in sols: sol.append((d*x, d*y)) if D == -1: sol.append((d*y, d*x)) return sol elif D == 0: if N < 0: return [] if N == 0: return [(0, t)] sN, _exact = integer_nthroot(N, 2) if _exact: return [(sN, t)] else: return [] else: # D > 0 sD, _exact = integer_nthroot(D, 2) if _exact: if N == 0: return [(sD*t, t)] else: sol = [] for y in range(floor(sign(N)*(N - 1)/(2*sD)) + 1): try: sq, _exact = integer_nthroot(D*y**2 + N, 2) except ValueError: _exact = False if _exact: sol.append((sq, y)) return sol elif 1 < N**2 < D: # It is much faster to call `_special_diop_DN`. return _special_diop_DN(D, N) else: if N == 0: return [(0, 0)] elif abs(N) == 1: pqa = PQa(0, 1, D) j = 0 G = [] B = [] for i in pqa: a = i[2] G.append(i[5]) B.append(i[4]) if j != 0 and a == 2*sD: break j = j + 1 if _odd(j): if N == -1: x = G[j - 1] y = B[j - 1] else: count = j while count < 2*j - 1: i = next(pqa) G.append(i[5]) B.append(i[4]) count += 1 x = G[count] y = B[count] else: if N == 1: x = G[j - 1] y = B[j - 1] else: return [] return [(x, y)] else: fs = [] sol = [] div = divisors(N) for d in div: if divisible(N, d**2): fs.append(d) for f in fs: m = N // f**2 zs = sqrt_mod(D, abs(m), all_roots=True) zs = [i for i in zs if i <= abs(m) // 2 ] if abs(m) != 2: zs = zs + [-i for i in zs if i] # omit dupl 0 for z in zs: pqa = PQa(z, abs(m), D) j = 0 G = [] B = [] for i in pqa: G.append(i[5]) B.append(i[4]) if j != 0 and abs(i[1]) == 1: r = G[j-1] s = B[j-1] if r**2 - D*s**2 == m: sol.append((f*r, f*s)) elif diop_DN(D, -1) != []: a = diop_DN(D, -1) sol.append((f*(r*a[0][0] + a[0][1]*s*D), f*(r*a[0][1] + s*a[0][0]))) break j = j + 1 if j == length(z, abs(m), D): break return sol def _special_diop_DN(D, N): """ Solves the equation `x^2 - Dy^2 = N` for the special case where `1 < N**2 < D` and `D` is not a perfect square. It is better to call `diop_DN` rather than this function, as the former checks the condition `1 < N**2 < D`, and calls the latter only if appropriate. Usage ===== WARNING: Internal method. Do not call directly! ``_special_diop_DN(D, N)``: D and N are integers as in `x^2 - Dy^2 = N`. Details ======= ``D`` and ``N`` correspond to D and N in the equation. Examples ======== >>> from sympy.solvers.diophantine.diophantine import _special_diop_DN >>> _special_diop_DN(13, -3) # Solves equation x**2 - 13*y**2 = -3 [(7, 2), (137, 38)] The output can be interpreted as follows: There are two fundamental solutions to the equation `x^2 - 13y^2 = -3` given by (7, 2) and (137, 38). Each tuple is in the form (x, y), i.e. solution (7, 2) means that `x = 7` and `y = 2`. >>> _special_diop_DN(2445, -20) # Solves equation x**2 - 2445*y**2 = -20 [(445, 9), (17625560, 356454), (698095554475, 14118073569)] See Also ======== diop_DN() References ========== .. [1] Section 4.4.4 of the following book: Quadratic Diophantine Equations, T. Andreescu and D. Andrica, Springer, 2015. """ # The following assertion was removed for efficiency, with the understanding # that this method is not called directly. The parent method, `diop_DN` # is responsible for performing the appropriate checks. # # assert (1 < N**2 < D) and (not integer_nthroot(D, 2)[1]) sqrt_D = sqrt(D) F = [(N, 1)] f = 2 while True: f2 = f**2 if f2 > abs(N): break n, r = divmod(N, f2) if r == 0: F.append((n, f)) f += 1 P = 0 Q = 1 G0, G1 = 0, 1 B0, B1 = 1, 0 solutions = [] i = 0 while True: a = floor((P + sqrt_D) / Q) P = a*Q - P Q = (D - P**2) // Q G2 = a*G1 + G0 B2 = a*B1 + B0 for n, f in F: if G2**2 - D*B2**2 == n: solutions.append((f*G2, f*B2)) i += 1 if Q == 1 and i % 2 == 0: break G0, G1 = G1, G2 B0, B1 = B1, B2 return solutions def cornacchia(a, b, m): r""" Solves `ax^2 + by^2 = m` where `\gcd(a, b) = 1 = gcd(a, m)` and `a, b > 0`. Explanation =========== Uses the algorithm due to Cornacchia. The method only finds primitive solutions, i.e. ones with `\gcd(x, y) = 1`. So this method cannot be used to find the solutions of `x^2 + y^2 = 20` since the only solution to former is `(x, y) = (4, 2)` and it is not primitive. When `a = b`, only the solutions with `x \leq y` are found. For more details, see the References. Examples ======== >>> from sympy.solvers.diophantine.diophantine import cornacchia >>> cornacchia(2, 3, 35) # equation 2x**2 + 3y**2 = 35 {(2, 3), (4, 1)} >>> cornacchia(1, 1, 25) # equation x**2 + y**2 = 25 {(4, 3)} References =========== .. [1] A. Nitaj, "L'algorithme de Cornacchia" .. [2] Solving the diophantine equation ax**2 + by**2 = m by Cornacchia's method, [online], Available: http://www.numbertheory.org/php/cornacchia.html See Also ======== sympy.utilities.iterables.signed_permutations """ sols = set() a1 = igcdex(a, m)[0] v = sqrt_mod(-b*a1, m, all_roots=True) if not v: return None for t in v: if t < m // 2: continue u, r = t, m while True: u, r = r, u % r if a*r**2 < m: break m1 = m - a*r**2 if m1 % b == 0: m1 = m1 // b s, _exact = integer_nthroot(m1, 2) if _exact: if a == b and r < s: r, s = s, r sols.add((int(r), int(s))) return sols def PQa(P_0, Q_0, D): r""" Returns useful information needed to solve the Pell equation. Explanation =========== There are six sequences of integers defined related to the continued fraction representation of `\\frac{P + \sqrt{D}}{Q}`, namely {`P_{i}`}, {`Q_{i}`}, {`a_{i}`},{`A_{i}`}, {`B_{i}`}, {`G_{i}`}. ``PQa()`` Returns these values as a 6-tuple in the same order as mentioned above. Refer [1]_ for more detailed information. Usage ===== ``PQa(P_0, Q_0, D)``: ``P_0``, ``Q_0`` and ``D`` are integers corresponding to `P_{0}`, `Q_{0}` and `D` in the continued fraction `\\frac{P_{0} + \sqrt{D}}{Q_{0}}`. Also it's assumed that `P_{0}^2 == D mod(|Q_{0}|)` and `D` is square free. Examples ======== >>> from sympy.solvers.diophantine.diophantine import PQa >>> pqa = PQa(13, 4, 5) # (13 + sqrt(5))/4 >>> next(pqa) # (P_0, Q_0, a_0, A_0, B_0, G_0) (13, 4, 3, 3, 1, -1) >>> next(pqa) # (P_1, Q_1, a_1, A_1, B_1, G_1) (-1, 1, 1, 4, 1, 3) References ========== .. [1] Solving the generalized Pell equation x^2 - Dy^2 = N, John P. Robertson, July 31, 2004, Pages 4 - 8. https://web.archive.org/web/20160323033128/http://www.jpr2718.org/pell.pdf """ A_i_2 = B_i_1 = 0 A_i_1 = B_i_2 = 1 G_i_2 = -P_0 G_i_1 = Q_0 P_i = P_0 Q_i = Q_0 while True: a_i = floor((P_i + sqrt(D))/Q_i) A_i = a_i*A_i_1 + A_i_2 B_i = a_i*B_i_1 + B_i_2 G_i = a_i*G_i_1 + G_i_2 yield P_i, Q_i, a_i, A_i, B_i, G_i A_i_1, A_i_2 = A_i, A_i_1 B_i_1, B_i_2 = B_i, B_i_1 G_i_1, G_i_2 = G_i, G_i_1 P_i = a_i*Q_i - P_i Q_i = (D - P_i**2)/Q_i def diop_bf_DN(D, N, t=symbols("t", integer=True)): r""" Uses brute force to solve the equation, `x^2 - Dy^2 = N`. Explanation =========== Mainly concerned with the generalized Pell equation which is the case when `D > 0, D` is not a perfect square. For more information on the case refer [1]_. Let `(t, u)` be the minimal positive solution of the equation `x^2 - Dy^2 = 1`. Then this method requires `\sqrt{\\frac{\mid N \mid (t \pm 1)}{2D}}` to be small. Usage ===== ``diop_bf_DN(D, N, t)``: ``D`` and ``N`` are coefficients in `x^2 - Dy^2 = N` and ``t`` is the parameter to be used in the solutions. Details ======= ``D`` and ``N`` correspond to D and N in the equation. ``t`` is the parameter to be used in the solutions. Examples ======== >>> from sympy.solvers.diophantine.diophantine import diop_bf_DN >>> diop_bf_DN(13, -4) [(3, 1), (-3, 1), (36, 10)] >>> diop_bf_DN(986, 1) [(49299, 1570)] See Also ======== diop_DN() References ========== .. [1] Solving the generalized Pell equation x**2 - D*y**2 = N, John P. Robertson, July 31, 2004, Page 15. https://web.archive.org/web/20160323033128/http://www.jpr2718.org/pell.pdf """ D = as_int(D) N = as_int(N) sol = [] a = diop_DN(D, 1) u = a[0][0] if abs(N) == 1: return diop_DN(D, N) elif N > 1: L1 = 0 L2 = integer_nthroot(int(N*(u - 1)/(2*D)), 2)[0] + 1 elif N < -1: L1, _exact = integer_nthroot(-int(N/D), 2) if not _exact: L1 += 1 L2 = integer_nthroot(-int(N*(u + 1)/(2*D)), 2)[0] + 1 else: # N = 0 if D < 0: return [(0, 0)] elif D == 0: return [(0, t)] else: sD, _exact = integer_nthroot(D, 2) if _exact: return [(sD*t, t), (-sD*t, t)] else: return [(0, 0)] for y in range(L1, L2): try: x, _exact = integer_nthroot(N + D*y**2, 2) except ValueError: _exact = False if _exact: sol.append((x, y)) if not equivalent(x, y, -x, y, D, N): sol.append((-x, y)) return sol def equivalent(u, v, r, s, D, N): """ Returns True if two solutions `(u, v)` and `(r, s)` of `x^2 - Dy^2 = N` belongs to the same equivalence class and False otherwise. Explanation =========== Two solutions `(u, v)` and `(r, s)` to the above equation fall to the same equivalence class iff both `(ur - Dvs)` and `(us - vr)` are divisible by `N`. See reference [1]_. No test is performed to test whether `(u, v)` and `(r, s)` are actually solutions to the equation. User should take care of this. Usage ===== ``equivalent(u, v, r, s, D, N)``: `(u, v)` and `(r, s)` are two solutions of the equation `x^2 - Dy^2 = N` and all parameters involved are integers. Examples ======== >>> from sympy.solvers.diophantine.diophantine import equivalent >>> equivalent(18, 5, -18, -5, 13, -1) True >>> equivalent(3, 1, -18, 393, 109, -4) False References ========== .. [1] Solving the generalized Pell equation x**2 - D*y**2 = N, John P. Robertson, July 31, 2004, Page 12. https://web.archive.org/web/20160323033128/http://www.jpr2718.org/pell.pdf """ return divisible(u*r - D*v*s, N) and divisible(u*s - v*r, N) def length(P, Q, D): r""" Returns the (length of aperiodic part + length of periodic part) of continued fraction representation of `\\frac{P + \sqrt{D}}{Q}`. It is important to remember that this does NOT return the length of the periodic part but the sum of the lengths of the two parts as mentioned above. Usage ===== ``length(P, Q, D)``: ``P``, ``Q`` and ``D`` are integers corresponding to the continued fraction `\\frac{P + \sqrt{D}}{Q}`. Details ======= ``P``, ``D`` and ``Q`` corresponds to P, D and Q in the continued fraction, `\\frac{P + \sqrt{D}}{Q}`. Examples ======== >>> from sympy.solvers.diophantine.diophantine import length >>> length(-2, 4, 5) # (-2 + sqrt(5))/4 3 >>> length(-5, 4, 17) # (-5 + sqrt(17))/4 4 See Also ======== sympy.ntheory.continued_fraction.continued_fraction_periodic """ from sympy.ntheory.continued_fraction import continued_fraction_periodic v = continued_fraction_periodic(P, Q, D) if isinstance(v[-1], list): rpt = len(v[-1]) nonrpt = len(v) - 1 else: rpt = 0 nonrpt = len(v) return rpt + nonrpt def transformation_to_DN(eq): """ This function transforms general quadratic, `ax^2 + bxy + cy^2 + dx + ey + f = 0` to more easy to deal with `X^2 - DY^2 = N` form. Explanation =========== This is used to solve the general quadratic equation by transforming it to the latter form. Refer to [1]_ for more detailed information on the transformation. This function returns a tuple (A, B) where A is a 2 X 2 matrix and B is a 2 X 1 matrix such that, Transpose([x y]) = A * Transpose([X Y]) + B Usage ===== ``transformation_to_DN(eq)``: where ``eq`` is the quadratic to be transformed. Examples ======== >>> from sympy.abc import x, y >>> from sympy.solvers.diophantine.diophantine import transformation_to_DN >>> A, B = transformation_to_DN(x**2 - 3*x*y - y**2 - 2*y + 1) >>> A Matrix([ [1/26, 3/26], [ 0, 1/13]]) >>> B Matrix([ [-6/13], [-4/13]]) A, B returned are such that Transpose((x y)) = A * Transpose((X Y)) + B. Substituting these values for `x` and `y` and a bit of simplifying work will give an equation of the form `x^2 - Dy^2 = N`. >>> from sympy.abc import X, Y >>> from sympy import Matrix, simplify >>> u = (A*Matrix([X, Y]) + B)[0] # Transformation for x >>> u X/26 + 3*Y/26 - 6/13 >>> v = (A*Matrix([X, Y]) + B)[1] # Transformation for y >>> v Y/13 - 4/13 Next we will substitute these formulas for `x` and `y` and do ``simplify()``. >>> eq = simplify((x**2 - 3*x*y - y**2 - 2*y + 1).subs(zip((x, y), (u, v)))) >>> eq X**2/676 - Y**2/52 + 17/13 By multiplying the denominator appropriately, we can get a Pell equation in the standard form. >>> eq * 676 X**2 - 13*Y**2 + 884 If only the final equation is needed, ``find_DN()`` can be used. See Also ======== find_DN() References ========== .. [1] Solving the equation ax^2 + bxy + cy^2 + dx + ey + f = 0, John P.Robertson, May 8, 2003, Page 7 - 11. https://web.archive.org/web/20160323033111/http://www.jpr2718.org/ax2p.pdf """ var, coeff, diop_type = classify_diop(eq, _dict=False) if diop_type == BinaryQuadratic.name: return _transformation_to_DN(var, coeff) def _transformation_to_DN(var, coeff): x, y = var a = coeff[x**2] b = coeff[x*y] c = coeff[y**2] d = coeff[x] e = coeff[y] f = coeff[1] a, b, c, d, e, f = [as_int(i) for i in _remove_gcd(a, b, c, d, e, f)] X, Y = symbols("X, Y", integer=True) if b: B, C = _rational_pq(2*a, b) A, T = _rational_pq(a, B**2) # eq_1 = A*B*X**2 + B*(c*T - A*C**2)*Y**2 + d*T*X + (B*e*T - d*T*C)*Y + f*T*B coeff = {X**2: A*B, X*Y: 0, Y**2: B*(c*T - A*C**2), X: d*T, Y: B*e*T - d*T*C, 1: f*T*B} A_0, B_0 = _transformation_to_DN([X, Y], coeff) return Matrix(2, 2, [S.One/B, -S(C)/B, 0, 1])*A_0, Matrix(2, 2, [S.One/B, -S(C)/B, 0, 1])*B_0 else: if d: B, C = _rational_pq(2*a, d) A, T = _rational_pq(a, B**2) # eq_2 = A*X**2 + c*T*Y**2 + e*T*Y + f*T - A*C**2 coeff = {X**2: A, X*Y: 0, Y**2: c*T, X: 0, Y: e*T, 1: f*T - A*C**2} A_0, B_0 = _transformation_to_DN([X, Y], coeff) return Matrix(2, 2, [S.One/B, 0, 0, 1])*A_0, Matrix(2, 2, [S.One/B, 0, 0, 1])*B_0 + Matrix([-S(C)/B, 0]) else: if e: B, C = _rational_pq(2*c, e) A, T = _rational_pq(c, B**2) # eq_3 = a*T*X**2 + A*Y**2 + f*T - A*C**2 coeff = {X**2: a*T, X*Y: 0, Y**2: A, X: 0, Y: 0, 1: f*T - A*C**2} A_0, B_0 = _transformation_to_DN([X, Y], coeff) return Matrix(2, 2, [1, 0, 0, S.One/B])*A_0, Matrix(2, 2, [1, 0, 0, S.One/B])*B_0 + Matrix([0, -S(C)/B]) else: # TODO: pre-simplification: Not necessary but may simplify # the equation. return Matrix(2, 2, [S.One/a, 0, 0, 1]), Matrix([0, 0]) def find_DN(eq): """ This function returns a tuple, `(D, N)` of the simplified form, `x^2 - Dy^2 = N`, corresponding to the general quadratic, `ax^2 + bxy + cy^2 + dx + ey + f = 0`. Solving the general quadratic is then equivalent to solving the equation `X^2 - DY^2 = N` and transforming the solutions by using the transformation matrices returned by ``transformation_to_DN()``. Usage ===== ``find_DN(eq)``: where ``eq`` is the quadratic to be transformed. Examples ======== >>> from sympy.abc import x, y >>> from sympy.solvers.diophantine.diophantine import find_DN >>> find_DN(x**2 - 3*x*y - y**2 - 2*y + 1) (13, -884) Interpretation of the output is that we get `X^2 -13Y^2 = -884` after transforming `x^2 - 3xy - y^2 - 2y + 1` using the transformation returned by ``transformation_to_DN()``. See Also ======== transformation_to_DN() References ========== .. [1] Solving the equation ax^2 + bxy + cy^2 + dx + ey + f = 0, John P.Robertson, May 8, 2003, Page 7 - 11. https://web.archive.org/web/20160323033111/http://www.jpr2718.org/ax2p.pdf """ var, coeff, diop_type = classify_diop(eq, _dict=False) if diop_type == BinaryQuadratic.name: return _find_DN(var, coeff) def _find_DN(var, coeff): x, y = var X, Y = symbols("X, Y", integer=True) A, B = _transformation_to_DN(var, coeff) u = (A*Matrix([X, Y]) + B)[0] v = (A*Matrix([X, Y]) + B)[1] eq = x**2*coeff[x**2] + x*y*coeff[x*y] + y**2*coeff[y**2] + x*coeff[x] + y*coeff[y] + coeff[1] simplified = _mexpand(eq.subs(zip((x, y), (u, v)))) coeff = simplified.as_coefficients_dict() return -coeff[Y**2]/coeff[X**2], -coeff[1]/coeff[X**2] def check_param(x, y, a, params): """ If there is a number modulo ``a`` such that ``x`` and ``y`` are both integers, then return a parametric representation for ``x`` and ``y`` else return (None, None). Here ``x`` and ``y`` are functions of ``t``. """ from sympy.simplify.simplify import clear_coefficients if x.is_number and not x.is_Integer: return DiophantineSolutionSet([x, y], parameters=params) if y.is_number and not y.is_Integer: return DiophantineSolutionSet([x, y], parameters=params) m, n = symbols("m, n", integer=True) c, p = (m*x + n*y).as_content_primitive() if a % c.q: return DiophantineSolutionSet([x, y], parameters=params) # clear_coefficients(mx + b, R)[1] -> (R - b)/m eq = clear_coefficients(x, m)[1] - clear_coefficients(y, n)[1] junk, eq = eq.as_content_primitive() return _diop_solve(eq, params=params) def diop_ternary_quadratic(eq, parameterize=False): """ Solves the general quadratic ternary form, `ax^2 + by^2 + cz^2 + fxy + gyz + hxz = 0`. Returns a tuple `(x, y, z)` which is a base solution for the above equation. If there are no solutions, `(None, None, None)` is returned. Usage ===== ``diop_ternary_quadratic(eq)``: Return a tuple containing a basic solution to ``eq``. Details ======= ``eq`` should be an homogeneous expression of degree two in three variables and it is assumed to be zero. Examples ======== >>> from sympy.abc import x, y, z >>> from sympy.solvers.diophantine.diophantine import diop_ternary_quadratic >>> diop_ternary_quadratic(x**2 + 3*y**2 - z**2) (1, 0, 1) >>> diop_ternary_quadratic(4*x**2 + 5*y**2 - z**2) (1, 0, 2) >>> diop_ternary_quadratic(45*x**2 - 7*y**2 - 8*x*y - z**2) (28, 45, 105) >>> diop_ternary_quadratic(x**2 - 49*y**2 - z**2 + 13*z*y -8*x*y) (9, 1, 5) """ var, coeff, diop_type = classify_diop(eq, _dict=False) if diop_type in ( HomogeneousTernaryQuadratic.name, HomogeneousTernaryQuadraticNormal.name): sol = _diop_ternary_quadratic(var, coeff) if len(sol) > 0: x_0, y_0, z_0 = list(sol)[0] else: x_0, y_0, z_0 = None, None, None if parameterize: return _parametrize_ternary_quadratic( (x_0, y_0, z_0), var, coeff) return x_0, y_0, z_0 def _diop_ternary_quadratic(_var, coeff): eq = sum([i*coeff[i] for i in coeff]) if HomogeneousTernaryQuadratic(eq).matches(): return HomogeneousTernaryQuadratic(eq, free_symbols=_var).solve() elif HomogeneousTernaryQuadraticNormal(eq).matches(): return HomogeneousTernaryQuadraticNormal(eq, free_symbols=_var).solve() def transformation_to_normal(eq): """ Returns the transformation Matrix that converts a general ternary quadratic equation ``eq`` (`ax^2 + by^2 + cz^2 + dxy + eyz + fxz`) to a form without cross terms: `ax^2 + by^2 + cz^2 = 0`. This is not used in solving ternary quadratics; it is only implemented for the sake of completeness. """ var, coeff, diop_type = classify_diop(eq, _dict=False) if diop_type in ( "homogeneous_ternary_quadratic", "homogeneous_ternary_quadratic_normal"): return _transformation_to_normal(var, coeff) def _transformation_to_normal(var, coeff): _var = list(var) # copy x, y, z = var if not any(coeff[i**2] for i in var): # https://math.stackexchange.com/questions/448051/transform-quadratic-ternary-form-to-normal-form/448065#448065 a = coeff[x*y] b = coeff[y*z] c = coeff[x*z] swap = False if not a: # b can't be 0 or else there aren't 3 vars swap = True a, b = b, a T = Matrix(((1, 1, -b/a), (1, -1, -c/a), (0, 0, 1))) if swap: T.row_swap(0, 1) T.col_swap(0, 1) return T if coeff[x**2] == 0: # If the coefficient of x is zero change the variables if coeff[y**2] == 0: _var[0], _var[2] = var[2], var[0] T = _transformation_to_normal(_var, coeff) T.row_swap(0, 2) T.col_swap(0, 2) return T else: _var[0], _var[1] = var[1], var[0] T = _transformation_to_normal(_var, coeff) T.row_swap(0, 1) T.col_swap(0, 1) return T # Apply the transformation x --> X - (B*Y + C*Z)/(2*A) if coeff[x*y] != 0 or coeff[x*z] != 0: A = coeff[x**2] B = coeff[x*y] C = coeff[x*z] D = coeff[y**2] E = coeff[y*z] F = coeff[z**2] _coeff = dict() _coeff[x**2] = 4*A**2 _coeff[y**2] = 4*A*D - B**2 _coeff[z**2] = 4*A*F - C**2 _coeff[y*z] = 4*A*E - 2*B*C _coeff[x*y] = 0 _coeff[x*z] = 0 T_0 = _transformation_to_normal(_var, _coeff) return Matrix(3, 3, [1, S(-B)/(2*A), S(-C)/(2*A), 0, 1, 0, 0, 0, 1])*T_0 elif coeff[y*z] != 0: if coeff[y**2] == 0: if coeff[z**2] == 0: # Equations of the form A*x**2 + E*yz = 0. # Apply transformation y -> Y + Z ans z -> Y - Z return Matrix(3, 3, [1, 0, 0, 0, 1, 1, 0, 1, -1]) else: # Ax**2 + E*y*z + F*z**2 = 0 _var[0], _var[2] = var[2], var[0] T = _transformation_to_normal(_var, coeff) T.row_swap(0, 2) T.col_swap(0, 2) return T else: # A*x**2 + D*y**2 + E*y*z + F*z**2 = 0, F may be zero _var[0], _var[1] = var[1], var[0] T = _transformation_to_normal(_var, coeff) T.row_swap(0, 1) T.col_swap(0, 1) return T else: return Matrix.eye(3) def parametrize_ternary_quadratic(eq): """ Returns the parametrized general solution for the ternary quadratic equation ``eq`` which has the form `ax^2 + by^2 + cz^2 + fxy + gyz + hxz = 0`. Examples ======== >>> from sympy import Tuple, ordered >>> from sympy.abc import x, y, z >>> from sympy.solvers.diophantine.diophantine import parametrize_ternary_quadratic The parametrized solution may be returned with three parameters: >>> parametrize_ternary_quadratic(2*x**2 + y**2 - 2*z**2) (p**2 - 2*q**2, -2*p**2 + 4*p*q - 4*p*r - 4*q**2, p**2 - 4*p*q + 2*q**2 - 4*q*r) There might also be only two parameters: >>> parametrize_ternary_quadratic(4*x**2 + 2*y**2 - 3*z**2) (2*p**2 - 3*q**2, -4*p**2 + 12*p*q - 6*q**2, 4*p**2 - 8*p*q + 6*q**2) Notes ===== Consider ``p`` and ``q`` in the previous 2-parameter solution and observe that more than one solution can be represented by a given pair of parameters. If `p` and ``q`` are not coprime, this is trivially true since the common factor will also be a common factor of the solution values. But it may also be true even when ``p`` and ``q`` are coprime: >>> sol = Tuple(*_) >>> p, q = ordered(sol.free_symbols) >>> sol.subs([(p, 3), (q, 2)]) (6, 12, 12) >>> sol.subs([(q, 1), (p, 1)]) (-1, 2, 2) >>> sol.subs([(q, 0), (p, 1)]) (2, -4, 4) >>> sol.subs([(q, 1), (p, 0)]) (-3, -6, 6) Except for sign and a common factor, these are equivalent to the solution of (1, 2, 2). References ========== .. [1] The algorithmic resolution of Diophantine equations, Nigel P. Smart, London Mathematical Society Student Texts 41, Cambridge University Press, Cambridge, 1998. """ var, coeff, diop_type = classify_diop(eq, _dict=False) if diop_type in ( "homogeneous_ternary_quadratic", "homogeneous_ternary_quadratic_normal"): x_0, y_0, z_0 = list(_diop_ternary_quadratic(var, coeff))[0] return _parametrize_ternary_quadratic( (x_0, y_0, z_0), var, coeff) def _parametrize_ternary_quadratic(solution, _var, coeff): # called for a*x**2 + b*y**2 + c*z**2 + d*x*y + e*y*z + f*x*z = 0 assert 1 not in coeff x_0, y_0, z_0 = solution v = list(_var) # copy if x_0 is None: return (None, None, None) if solution.count(0) >= 2: # if there are 2 zeros the equation reduces # to k*X**2 == 0 where X is x, y, or z so X must # be zero, too. So there is only the trivial # solution. return (None, None, None) if x_0 == 0: v[0], v[1] = v[1], v[0] y_p, x_p, z_p = _parametrize_ternary_quadratic( (y_0, x_0, z_0), v, coeff) return x_p, y_p, z_p x, y, z = v r, p, q = symbols("r, p, q", integer=True) eq = sum(k*v for k, v in coeff.items()) eq_1 = _mexpand(eq.subs(zip( (x, y, z), (r*x_0, r*y_0 + p, r*z_0 + q)))) A, B = eq_1.as_independent(r, as_Add=True) x = A*x_0 y = (A*y_0 - _mexpand(B/r*p)) z = (A*z_0 - _mexpand(B/r*q)) return _remove_gcd(x, y, z) def diop_ternary_quadratic_normal(eq, parameterize=False): """ Solves the quadratic ternary diophantine equation, `ax^2 + by^2 + cz^2 = 0`. Explanation =========== Here the coefficients `a`, `b`, and `c` should be non zero. Otherwise the equation will be a quadratic binary or univariate equation. If solvable, returns a tuple `(x, y, z)` that satisfies the given equation. If the equation does not have integer solutions, `(None, None, None)` is returned. Usage ===== ``diop_ternary_quadratic_normal(eq)``: where ``eq`` is an equation of the form `ax^2 + by^2 + cz^2 = 0`. Examples ======== >>> from sympy.abc import x, y, z >>> from sympy.solvers.diophantine.diophantine import diop_ternary_quadratic_normal >>> diop_ternary_quadratic_normal(x**2 + 3*y**2 - z**2) (1, 0, 1) >>> diop_ternary_quadratic_normal(4*x**2 + 5*y**2 - z**2) (1, 0, 2) >>> diop_ternary_quadratic_normal(34*x**2 - 3*y**2 - 301*z**2) (4, 9, 1) """ var, coeff, diop_type = classify_diop(eq, _dict=False) if diop_type == HomogeneousTernaryQuadraticNormal.name: sol = _diop_ternary_quadratic_normal(var, coeff) if len(sol) > 0: x_0, y_0, z_0 = list(sol)[0] else: x_0, y_0, z_0 = None, None, None if parameterize: return _parametrize_ternary_quadratic( (x_0, y_0, z_0), var, coeff) return x_0, y_0, z_0 def _diop_ternary_quadratic_normal(var, coeff): eq = sum([i * coeff[i] for i in coeff]) return HomogeneousTernaryQuadraticNormal(eq, free_symbols=var).solve() def sqf_normal(a, b, c, steps=False): """ Return `a', b', c'`, the coefficients of the square-free normal form of `ax^2 + by^2 + cz^2 = 0`, where `a', b', c'` are pairwise prime. If `steps` is True then also return three tuples: `sq`, `sqf`, and `(a', b', c')` where `sq` contains the square factors of `a`, `b` and `c` after removing the `gcd(a, b, c)`; `sqf` contains the values of `a`, `b` and `c` after removing both the `gcd(a, b, c)` and the square factors. The solutions for `ax^2 + by^2 + cz^2 = 0` can be recovered from the solutions of `a'x^2 + b'y^2 + c'z^2 = 0`. Examples ======== >>> from sympy.solvers.diophantine.diophantine import sqf_normal >>> sqf_normal(2 * 3**2 * 5, 2 * 5 * 11, 2 * 7**2 * 11) (11, 1, 5) >>> sqf_normal(2 * 3**2 * 5, 2 * 5 * 11, 2 * 7**2 * 11, True) ((3, 1, 7), (5, 55, 11), (11, 1, 5)) References ========== .. [1] Legendre's Theorem, Legrange's Descent, http://public.csusm.edu/aitken_html/notes/legendre.pdf See Also ======== reconstruct() """ ABC = _remove_gcd(a, b, c) sq = tuple(square_factor(i) for i in ABC) sqf = A, B, C = tuple([i//j**2 for i,j in zip(ABC, sq)]) pc = igcd(A, B) A /= pc B /= pc pa = igcd(B, C) B /= pa C /= pa pb = igcd(A, C) A /= pb B /= pb A *= pa B *= pb C *= pc if steps: return (sq, sqf, (A, B, C)) else: return A, B, C def square_factor(a): r""" Returns an integer `c` s.t. `a = c^2k, \ c,k \in Z`. Here `k` is square free. `a` can be given as an integer or a dictionary of factors. Examples ======== >>> from sympy.solvers.diophantine.diophantine import square_factor >>> square_factor(24) 2 >>> square_factor(-36*3) 6 >>> square_factor(1) 1 >>> square_factor({3: 2, 2: 1, -1: 1}) # -18 3 See Also ======== sympy.ntheory.factor_.core """ f = a if isinstance(a, dict) else factorint(a) return Mul(*[p**(e//2) for p, e in f.items()]) def reconstruct(A, B, z): """ Reconstruct the `z` value of an equivalent solution of `ax^2 + by^2 + cz^2` from the `z` value of a solution of the square-free normal form of the equation, `a'*x^2 + b'*y^2 + c'*z^2`, where `a'`, `b'` and `c'` are square free and `gcd(a', b', c') == 1`. """ f = factorint(igcd(A, B)) for p, e in f.items(): if e != 1: raise ValueError('a and b should be square-free') z *= p return z def ldescent(A, B): """ Return a non-trivial solution to `w^2 = Ax^2 + By^2` using Lagrange's method; return None if there is no such solution. . Here, `A \\neq 0` and `B \\neq 0` and `A` and `B` are square free. Output a tuple `(w_0, x_0, y_0)` which is a solution to the above equation. Examples ======== >>> from sympy.solvers.diophantine.diophantine import ldescent >>> ldescent(1, 1) # w^2 = x^2 + y^2 (1, 1, 0) >>> ldescent(4, -7) # w^2 = 4x^2 - 7y^2 (2, -1, 0) This means that `x = -1, y = 0` and `w = 2` is a solution to the equation `w^2 = 4x^2 - 7y^2` >>> ldescent(5, -1) # w^2 = 5x^2 - y^2 (2, 1, -1) References ========== .. [1] The algorithmic resolution of Diophantine equations, Nigel P. Smart, London Mathematical Society Student Texts 41, Cambridge University Press, Cambridge, 1998. .. [2] Efficient Solution of Rational Conices, J. E. Cremona and D. Rusin, [online], Available: http://eprints.nottingham.ac.uk/60/1/kvxefz87.pdf """ if abs(A) > abs(B): w, y, x = ldescent(B, A) return w, x, y if A == 1: return (1, 1, 0) if B == 1: return (1, 0, 1) if B == -1: # and A == -1 return r = sqrt_mod(A, B) Q = (r**2 - A) // B if Q == 0: B_0 = 1 d = 0 else: div = divisors(Q) B_0 = None for i in div: sQ, _exact = integer_nthroot(abs(Q) // i, 2) if _exact: B_0, d = sign(Q)*i, sQ break if B_0 is not None: W, X, Y = ldescent(A, B_0) return _remove_gcd((-A*X + r*W), (r*X - W), Y*(B_0*d)) def descent(A, B): """ Returns a non-trivial solution, (x, y, z), to `x^2 = Ay^2 + Bz^2` using Lagrange's descent method with lattice-reduction. `A` and `B` are assumed to be valid for such a solution to exist. This is faster than the normal Lagrange's descent algorithm because the Gaussian reduction is used. Examples ======== >>> from sympy.solvers.diophantine.diophantine import descent >>> descent(3, 1) # x**2 = 3*y**2 + z**2 (1, 0, 1) `(x, y, z) = (1, 0, 1)` is a solution to the above equation. >>> descent(41, -113) (-16, -3, 1) References ========== .. [1] Efficient Solution of Rational Conices, J. E. Cremona and D. Rusin, Mathematics of Computation, Volume 00, Number 0. """ if abs(A) > abs(B): x, y, z = descent(B, A) return x, z, y if B == 1: return (1, 0, 1) if A == 1: return (1, 1, 0) if B == -A: return (0, 1, 1) if B == A: x, z, y = descent(-1, A) return (A*y, z, x) w = sqrt_mod(A, B) x_0, z_0 = gaussian_reduce(w, A, B) t = (x_0**2 - A*z_0**2) // B t_2 = square_factor(t) t_1 = t // t_2**2 x_1, z_1, y_1 = descent(A, t_1) return _remove_gcd(x_0*x_1 + A*z_0*z_1, z_0*x_1 + x_0*z_1, t_1*t_2*y_1) def gaussian_reduce(w, a, b): r""" Returns a reduced solution `(x, z)` to the congruence `X^2 - aZ^2 \equiv 0 \ (mod \ b)` so that `x^2 + |a|z^2` is minimal. Details ======= Here ``w`` is a solution of the congruence `x^2 \equiv a \ (mod \ b)` References ========== .. [1] Gaussian lattice Reduction [online]. Available: http://home.ie.cuhk.edu.hk/~wkshum/wordpress/?p=404 .. [2] Efficient Solution of Rational Conices, J. E. Cremona and D. Rusin, Mathematics of Computation, Volume 00, Number 0. """ u = (0, 1) v = (1, 0) if dot(u, v, w, a, b) < 0: v = (-v[0], -v[1]) if norm(u, w, a, b) < norm(v, w, a, b): u, v = v, u while norm(u, w, a, b) > norm(v, w, a, b): k = dot(u, v, w, a, b) // dot(v, v, w, a, b) u, v = v, (u[0]- k*v[0], u[1]- k*v[1]) u, v = v, u if dot(u, v, w, a, b) < dot(v, v, w, a, b)/2 or norm((u[0]-v[0], u[1]-v[1]), w, a, b) > norm(v, w, a, b): c = v else: c = (u[0] - v[0], u[1] - v[1]) return c[0]*w + b*c[1], c[0] def dot(u, v, w, a, b): r""" Returns a special dot product of the vectors `u = (u_{1}, u_{2})` and `v = (v_{1}, v_{2})` which is defined in order to reduce solution of the congruence equation `X^2 - aZ^2 \equiv 0 \ (mod \ b)`. """ u_1, u_2 = u v_1, v_2 = v return (w*u_1 + b*u_2)*(w*v_1 + b*v_2) + abs(a)*u_1*v_1 def norm(u, w, a, b): r""" Returns the norm of the vector `u = (u_{1}, u_{2})` under the dot product defined by `u \cdot v = (wu_{1} + bu_{2})(w*v_{1} + bv_{2}) + |a|*u_{1}*v_{1}` where `u = (u_{1}, u_{2})` and `v = (v_{1}, v_{2})`. """ u_1, u_2 = u return sqrt(dot((u_1, u_2), (u_1, u_2), w, a, b)) def holzer(x, y, z, a, b, c): r""" Simplify the solution `(x, y, z)` of the equation `ax^2 + by^2 = cz^2` with `a, b, c > 0` and `z^2 \geq \mid ab \mid` to a new reduced solution `(x', y', z')` such that `z'^2 \leq \mid ab \mid`. The algorithm is an interpretation of Mordell's reduction as described on page 8 of Cremona and Rusin's paper [1]_ and the work of Mordell in reference [2]_. References ========== .. [1] Efficient Solution of Rational Conices, J. E. Cremona and D. Rusin, Mathematics of Computation, Volume 00, Number 0. .. [2] Diophantine Equations, L. J. Mordell, page 48. """ if _odd(c): k = 2*c else: k = c//2 small = a*b*c step = 0 while True: t1, t2, t3 = a*x**2, b*y**2, c*z**2 # check that it's a solution if t1 + t2 != t3: if step == 0: raise ValueError('bad starting solution') break x_0, y_0, z_0 = x, y, z if max(t1, t2, t3) <= small: # Holzer condition break uv = u, v = base_solution_linear(k, y_0, -x_0) if None in uv: break p, q = -(a*u*x_0 + b*v*y_0), c*z_0 r = Rational(p, q) if _even(c): w = _nint_or_floor(p, q) assert abs(w - r) <= S.Half else: w = p//q # floor if _odd(a*u + b*v + c*w): w += 1 assert abs(w - r) <= S.One A = (a*u**2 + b*v**2 + c*w**2) B = (a*u*x_0 + b*v*y_0 + c*w*z_0) x = Rational(x_0*A - 2*u*B, k) y = Rational(y_0*A - 2*v*B, k) z = Rational(z_0*A - 2*w*B, k) assert all(i.is_Integer for i in (x, y, z)) step += 1 return tuple([int(i) for i in (x_0, y_0, z_0)]) def diop_general_pythagorean(eq, param=symbols("m", integer=True)): """ Solves the general pythagorean equation, `a_{1}^2x_{1}^2 + a_{2}^2x_{2}^2 + . . . + a_{n}^2x_{n}^2 - a_{n + 1}^2x_{n + 1}^2 = 0`. Returns a tuple which contains a parametrized solution to the equation, sorted in the same order as the input variables. Usage ===== ``diop_general_pythagorean(eq, param)``: where ``eq`` is a general pythagorean equation which is assumed to be zero and ``param`` is the base parameter used to construct other parameters by subscripting. Examples ======== >>> from sympy.solvers.diophantine.diophantine import diop_general_pythagorean >>> from sympy.abc import a, b, c, d, e >>> diop_general_pythagorean(a**2 + b**2 + c**2 - d**2) (m1**2 + m2**2 - m3**2, 2*m1*m3, 2*m2*m3, m1**2 + m2**2 + m3**2) >>> diop_general_pythagorean(9*a**2 - 4*b**2 + 16*c**2 + 25*d**2 + e**2) (10*m1**2 + 10*m2**2 + 10*m3**2 - 10*m4**2, 15*m1**2 + 15*m2**2 + 15*m3**2 + 15*m4**2, 15*m1*m4, 12*m2*m4, 60*m3*m4) """ var, coeff, diop_type = classify_diop(eq, _dict=False) if diop_type == GeneralPythagorean.name: if param is None: params = None else: params = symbols('%s1:%i' % (param, len(var)), integer=True) return list(GeneralPythagorean(eq).solve(parameters=params))[0] def diop_general_sum_of_squares(eq, limit=1): r""" Solves the equation `x_{1}^2 + x_{2}^2 + . . . + x_{n}^2 - k = 0`. Returns at most ``limit`` number of solutions. Usage ===== ``general_sum_of_squares(eq, limit)`` : Here ``eq`` is an expression which is assumed to be zero. Also, ``eq`` should be in the form, `x_{1}^2 + x_{2}^2 + . . . + x_{n}^2 - k = 0`. Details ======= When `n = 3` if `k = 4^a(8m + 7)` for some `a, m \in Z` then there will be no solutions. Refer to [1]_ for more details. Examples ======== >>> from sympy.solvers.diophantine.diophantine import diop_general_sum_of_squares >>> from sympy.abc import a, b, c, d, e >>> diop_general_sum_of_squares(a**2 + b**2 + c**2 + d**2 + e**2 - 2345) {(15, 22, 22, 24, 24)} Reference ========= .. [1] Representing an integer as a sum of three squares, [online], Available: http://www.proofwiki.org/wiki/Integer_as_Sum_of_Three_Squares """ var, coeff, diop_type = classify_diop(eq, _dict=False) if diop_type == GeneralSumOfSquares.name: return set(GeneralSumOfSquares(eq).solve(limit=limit)) def diop_general_sum_of_even_powers(eq, limit=1): """ Solves the equation `x_{1}^e + x_{2}^e + . . . + x_{n}^e - k = 0` where `e` is an even, integer power. Returns at most ``limit`` number of solutions. Usage ===== ``general_sum_of_even_powers(eq, limit)`` : Here ``eq`` is an expression which is assumed to be zero. Also, ``eq`` should be in the form, `x_{1}^e + x_{2}^e + . . . + x_{n}^e - k = 0`. Examples ======== >>> from sympy.solvers.diophantine.diophantine import diop_general_sum_of_even_powers >>> from sympy.abc import a, b >>> diop_general_sum_of_even_powers(a**4 + b**4 - (2**4 + 3**4)) {(2, 3)} See Also ======== power_representation """ var, coeff, diop_type = classify_diop(eq, _dict=False) if diop_type == GeneralSumOfEvenPowers.name: return set(GeneralSumOfEvenPowers(eq).solve(limit=limit)) ## Functions below this comment can be more suitably grouped under ## an Additive number theory module rather than the Diophantine ## equation module. def partition(n, k=None, zeros=False): """ Returns a generator that can be used to generate partitions of an integer `n`. Explanation =========== A partition of `n` is a set of positive integers which add up to `n`. For example, partitions of 3 are 3, 1 + 2, 1 + 1 + 1. A partition is returned as a tuple. If ``k`` equals None, then all possible partitions are returned irrespective of their size, otherwise only the partitions of size ``k`` are returned. If the ``zero`` parameter is set to True then a suitable number of zeros are added at the end of every partition of size less than ``k``. ``zero`` parameter is considered only if ``k`` is not None. When the partitions are over, the last `next()` call throws the ``StopIteration`` exception, so this function should always be used inside a try - except block. Details ======= ``partition(n, k)``: Here ``n`` is a positive integer and ``k`` is the size of the partition which is also positive integer. Examples ======== >>> from sympy.solvers.diophantine.diophantine import partition >>> f = partition(5) >>> next(f) (1, 1, 1, 1, 1) >>> next(f) (1, 1, 1, 2) >>> g = partition(5, 3) >>> next(g) (1, 1, 3) >>> next(g) (1, 2, 2) >>> g = partition(5, 3, zeros=True) >>> next(g) (0, 0, 5) """ if not zeros or k is None: for i in ordered_partitions(n, k): yield tuple(i) else: for m in range(1, k + 1): for i in ordered_partitions(n, m): i = tuple(i) yield (0,)*(k - len(i)) + i def prime_as_sum_of_two_squares(p): """ Represent a prime `p` as a unique sum of two squares; this can only be done if the prime is congruent to 1 mod 4. Examples ======== >>> from sympy.solvers.diophantine.diophantine import prime_as_sum_of_two_squares >>> prime_as_sum_of_two_squares(7) # can't be done >>> prime_as_sum_of_two_squares(5) (1, 2) Reference ========= .. [1] Representing a number as a sum of four squares, [online], Available: http://schorn.ch/lagrange.html See Also ======== sum_of_squares() """ if not p % 4 == 1: return if p % 8 == 5: b = 2 else: b = 3 while pow(b, (p - 1) // 2, p) == 1: b = nextprime(b) b = pow(b, (p - 1) // 4, p) a = p while b**2 > p: a, b = b, a % b return (int(a % b), int(b)) # convert from long def sum_of_three_squares(n): r""" Returns a 3-tuple $(a, b, c)$ such that $a^2 + b^2 + c^2 = n$ and $a, b, c \geq 0$. Returns None if $n = 4^a(8m + 7)$ for some `a, m \in \mathbb{Z}`. See [1]_ for more details. Usage ===== ``sum_of_three_squares(n)``: Here ``n`` is a non-negative integer. Examples ======== >>> from sympy.solvers.diophantine.diophantine import sum_of_three_squares >>> sum_of_three_squares(44542) (18, 37, 207) References ========== .. [1] Representing a number as a sum of three squares, [online], Available: http://schorn.ch/lagrange.html See Also ======== sum_of_squares() """ special = {1:(1, 0, 0), 2:(1, 1, 0), 3:(1, 1, 1), 10: (1, 3, 0), 34: (3, 3, 4), 58:(3, 7, 0), 85:(6, 7, 0), 130:(3, 11, 0), 214:(3, 6, 13), 226:(8, 9, 9), 370:(8, 9, 15), 526:(6, 7, 21), 706:(15, 15, 16), 730:(1, 27, 0), 1414:(6, 17, 33), 1906:(13, 21, 36), 2986: (21, 32, 39), 9634: (56, 57, 57)} v = 0 if n == 0: return (0, 0, 0) v = multiplicity(4, n) n //= 4**v if n % 8 == 7: return if n in special.keys(): x, y, z = special[n] return _sorted_tuple(2**v*x, 2**v*y, 2**v*z) s, _exact = integer_nthroot(n, 2) if _exact: return (2**v*s, 0, 0) x = None if n % 8 == 3: s = s if _odd(s) else s - 1 for x in range(s, -1, -2): N = (n - x**2) // 2 if isprime(N): y, z = prime_as_sum_of_two_squares(N) return _sorted_tuple(2**v*x, 2**v*(y + z), 2**v*abs(y - z)) return if n % 8 in (2, 6): s = s if _odd(s) else s - 1 else: s = s - 1 if _odd(s) else s for x in range(s, -1, -2): N = n - x**2 if isprime(N): y, z = prime_as_sum_of_two_squares(N) return _sorted_tuple(2**v*x, 2**v*y, 2**v*z) def sum_of_four_squares(n): r""" Returns a 4-tuple `(a, b, c, d)` such that `a^2 + b^2 + c^2 + d^2 = n`. Here `a, b, c, d \geq 0`. Usage ===== ``sum_of_four_squares(n)``: Here ``n`` is a non-negative integer. Examples ======== >>> from sympy.solvers.diophantine.diophantine import sum_of_four_squares >>> sum_of_four_squares(3456) (8, 8, 32, 48) >>> sum_of_four_squares(1294585930293) (0, 1234, 2161, 1137796) References ========== .. [1] Representing a number as a sum of four squares, [online], Available: http://schorn.ch/lagrange.html See Also ======== sum_of_squares() """ if n == 0: return (0, 0, 0, 0) v = multiplicity(4, n) n //= 4**v if n % 8 == 7: d = 2 n = n - 4 elif n % 8 in (2, 6): d = 1 n = n - 1 else: d = 0 x, y, z = sum_of_three_squares(n) return _sorted_tuple(2**v*d, 2**v*x, 2**v*y, 2**v*z) def power_representation(n, p, k, zeros=False): r""" Returns a generator for finding k-tuples of integers, `(n_{1}, n_{2}, . . . n_{k})`, such that `n = n_{1}^p + n_{2}^p + . . . n_{k}^p`. Usage ===== ``power_representation(n, p, k, zeros)``: Represent non-negative number ``n`` as a sum of ``k`` ``p``\ th powers. If ``zeros`` is true, then the solutions is allowed to contain zeros. Examples ======== >>> from sympy.solvers.diophantine.diophantine import power_representation Represent 1729 as a sum of two cubes: >>> f = power_representation(1729, 3, 2) >>> next(f) (9, 10) >>> next(f) (1, 12) If the flag `zeros` is True, the solution may contain tuples with zeros; any such solutions will be generated after the solutions without zeros: >>> list(power_representation(125, 2, 3, zeros=True)) [(5, 6, 8), (3, 4, 10), (0, 5, 10), (0, 2, 11)] For even `p` the `permute_sign` function can be used to get all signed values: >>> from sympy.utilities.iterables import permute_signs >>> list(permute_signs((1, 12))) [(1, 12), (-1, 12), (1, -12), (-1, -12)] All possible signed permutations can also be obtained: >>> from sympy.utilities.iterables import signed_permutations >>> list(signed_permutations((1, 12))) [(1, 12), (-1, 12), (1, -12), (-1, -12), (12, 1), (-12, 1), (12, -1), (-12, -1)] """ n, p, k = [as_int(i) for i in (n, p, k)] if n < 0: if p % 2: for t in power_representation(-n, p, k, zeros): yield tuple(-i for i in t) return if p < 1 or k < 1: raise ValueError(filldedent(''' Expecting positive integers for `(p, k)`, but got `(%s, %s)`''' % (p, k))) if n == 0: if zeros: yield (0,)*k return if k == 1: if p == 1: yield (n,) else: be = perfect_power(n) if be: b, e = be d, r = divmod(e, p) if not r: yield (b**d,) return if p == 1: for t in partition(n, k, zeros=zeros): yield t return if p == 2: feasible = _can_do_sum_of_squares(n, k) if not feasible: return if not zeros and n > 33 and k >= 5 and k <= n and n - k in ( 13, 10, 7, 5, 4, 2, 1): '''Todd G. Will, "When Is n^2 a Sum of k Squares?", [online]. Available: https://www.maa.org/sites/default/files/Will-MMz-201037918.pdf''' return if feasible is not True: # it's prime and k == 2 yield prime_as_sum_of_two_squares(n) return if k == 2 and p > 2: be = perfect_power(n) if be and be[1] % p == 0: return # Fermat: a**n + b**n = c**n has no solution for n > 2 if n >= k: a = integer_nthroot(n - (k - 1), p)[0] for t in pow_rep_recursive(a, k, n, [], p): yield tuple(reversed(t)) if zeros: a = integer_nthroot(n, p)[0] for i in range(1, k): for t in pow_rep_recursive(a, i, n, [], p): yield tuple(reversed(t + (0,)*(k - i))) sum_of_powers = power_representation def pow_rep_recursive(n_i, k, n_remaining, terms, p): if k == 0 and n_remaining == 0: yield tuple(terms) else: if n_i >= 1 and k > 0: yield from pow_rep_recursive(n_i - 1, k, n_remaining, terms, p) residual = n_remaining - pow(n_i, p) if residual >= 0: yield from pow_rep_recursive(n_i, k - 1, residual, terms + [n_i], p) def sum_of_squares(n, k, zeros=False): """Return a generator that yields the k-tuples of nonnegative values, the squares of which sum to n. If zeros is False (default) then the solution will not contain zeros. The nonnegative elements of a tuple are sorted. * If k == 1 and n is square, (n,) is returned. * If k == 2 then n can only be written as a sum of squares if every prime in the factorization of n that has the form 4*k + 3 has an even multiplicity. If n is prime then it can only be written as a sum of two squares if it is in the form 4*k + 1. * if k == 3 then n can be written as a sum of squares if it does not have the form 4**m*(8*k + 7). * all integers can be written as the sum of 4 squares. * if k > 4 then n can be partitioned and each partition can be written as a sum of 4 squares; if n is not evenly divisible by 4 then n can be written as a sum of squares only if the an additional partition can be written as sum of squares. For example, if k = 6 then n is partitioned into two parts, the first being written as a sum of 4 squares and the second being written as a sum of 2 squares -- which can only be done if the condition above for k = 2 can be met, so this will automatically reject certain partitions of n. Examples ======== >>> from sympy.solvers.diophantine.diophantine import sum_of_squares >>> list(sum_of_squares(25, 2)) [(3, 4)] >>> list(sum_of_squares(25, 2, True)) [(3, 4), (0, 5)] >>> list(sum_of_squares(25, 4)) [(1, 2, 2, 4)] See Also ======== sympy.utilities.iterables.signed_permutations """ yield from power_representation(n, 2, k, zeros) def _can_do_sum_of_squares(n, k): """Return True if n can be written as the sum of k squares, False if it cannot, or 1 if ``k == 2`` and ``n`` is prime (in which case it *can* be written as a sum of two squares). A False is returned only if it cannot be written as ``k``-squares, even if 0s are allowed. """ if k < 1: return False if n < 0: return False if n == 0: return True if k == 1: return is_square(n) if k == 2: if n in (1, 2): return True if isprime(n): if n % 4 == 1: return 1 # signal that it was prime return False else: f = factorint(n) for p, m in f.items(): # we can proceed iff no prime factor in the form 4*k + 3 # has an odd multiplicity if (p % 4 == 3) and m % 2: return False return True if k == 3: if (n//4**multiplicity(4, n)) % 8 == 7: return False # every number can be written as a sum of 4 squares; for k > 4 partitions # can be 0 return True
17d1a09741606d589f24d3171c2d6e1a47cdcf101e5acb2035b83d9f6d64d053
r""" This module contains :py:meth:`~sympy.solvers.ode.dsolve` and different helper functions that it uses. :py:meth:`~sympy.solvers.ode.dsolve` solves ordinary differential equations. See the docstring on the various functions for their uses. Note that partial differential equations support is in ``pde.py``. Note that hint functions have docstrings describing their various methods, but they are intended for internal use. Use ``dsolve(ode, func, hint=hint)`` to solve an ODE using a specific hint. See also the docstring on :py:meth:`~sympy.solvers.ode.dsolve`. **Functions in this module** These are the user functions in this module: - :py:meth:`~sympy.solvers.ode.dsolve` - Solves ODEs. - :py:meth:`~sympy.solvers.ode.classify_ode` - Classifies ODEs into possible hints for :py:meth:`~sympy.solvers.ode.dsolve`. - :py:meth:`~sympy.solvers.ode.checkodesol` - Checks if an equation is the solution to an ODE. - :py:meth:`~sympy.solvers.ode.homogeneous_order` - Returns the homogeneous order of an expression. - :py:meth:`~sympy.solvers.ode.infinitesimals` - Returns the infinitesimals of the Lie group of point transformations of an ODE, such that it is invariant. - :py:meth:`~sympy.solvers.ode.checkinfsol` - Checks if the given infinitesimals are the actual infinitesimals of a first order ODE. These are the non-solver helper functions that are for internal use. The user should use the various options to :py:meth:`~sympy.solvers.ode.dsolve` to obtain the functionality provided by these functions: - :py:meth:`~sympy.solvers.ode.ode.odesimp` - Does all forms of ODE simplification. - :py:meth:`~sympy.solvers.ode.ode.ode_sol_simplicity` - A key function for comparing solutions by simplicity. - :py:meth:`~sympy.solvers.ode.constantsimp` - Simplifies arbitrary constants. - :py:meth:`~sympy.solvers.ode.ode.constant_renumber` - Renumber arbitrary constants. - :py:meth:`~sympy.solvers.ode.ode._handle_Integral` - Evaluate unevaluated Integrals. See also the docstrings of these functions. **Currently implemented solver methods** The following methods are implemented for solving ordinary differential equations. See the docstrings of the various hint functions for more information on each (run ``help(ode)``): - 1st order separable differential equations. - 1st order differential equations whose coefficients or `dx` and `dy` are functions homogeneous of the same order. - 1st order exact differential equations. - 1st order linear differential equations. - 1st order Bernoulli differential equations. - Power series solutions for first order differential equations. - Lie Group method of solving first order differential equations. - 2nd order Liouville differential equations. - Power series solutions for second order differential equations at ordinary and regular singular points. - `n`\th order differential equation that can be solved with algebraic rearrangement and integration. - `n`\th order linear homogeneous differential equation with constant coefficients. - `n`\th order linear inhomogeneous differential equation with constant coefficients using the method of undetermined coefficients. - `n`\th order linear inhomogeneous differential equation with constant coefficients using the method of variation of parameters. **Philosophy behind this module** This module is designed to make it easy to add new ODE solving methods without having to mess with the solving code for other methods. The idea is that there is a :py:meth:`~sympy.solvers.ode.classify_ode` function, which takes in an ODE and tells you what hints, if any, will solve the ODE. It does this without attempting to solve the ODE, so it is fast. Each solving method is a hint, and it has its own function, named ``ode_<hint>``. That function takes in the ODE and any match expression gathered by :py:meth:`~sympy.solvers.ode.classify_ode` and returns a solved result. If this result has any integrals in it, the hint function will return an unevaluated :py:class:`~sympy.integrals.integrals.Integral` class. :py:meth:`~sympy.solvers.ode.dsolve`, which is the user wrapper function around all of this, will then call :py:meth:`~sympy.solvers.ode.ode.odesimp` on the result, which, among other things, will attempt to solve the equation for the dependent variable (the function we are solving for), simplify the arbitrary constants in the expression, and evaluate any integrals, if the hint allows it. **How to add new solution methods** If you have an ODE that you want :py:meth:`~sympy.solvers.ode.dsolve` to be able to solve, try to avoid adding special case code here. Instead, try finding a general method that will solve your ODE, as well as others. This way, the :py:mod:`~sympy.solvers.ode` module will become more robust, and unhindered by special case hacks. WolphramAlpha and Maple's DETools[odeadvisor] function are two resources you can use to classify a specific ODE. It is also better for a method to work with an `n`\th order ODE instead of only with specific orders, if possible. To add a new method, there are a few things that you need to do. First, you need a hint name for your method. Try to name your hint so that it is unambiguous with all other methods, including ones that may not be implemented yet. If your method uses integrals, also include a ``hint_Integral`` hint. If there is more than one way to solve ODEs with your method, include a hint for each one, as well as a ``<hint>_best`` hint. Your ``ode_<hint>_best()`` function should choose the best using min with ``ode_sol_simplicity`` as the key argument. See :obj:`~sympy.solvers.ode.single.HomogeneousCoeffBest`, for example. The function that uses your method will be called ``ode_<hint>()``, so the hint must only use characters that are allowed in a Python function name (alphanumeric characters and the underscore '``_``' character). Include a function for every hint, except for ``_Integral`` hints (:py:meth:`~sympy.solvers.ode.dsolve` takes care of those automatically). Hint names should be all lowercase, unless a word is commonly capitalized (such as Integral or Bernoulli). If you have a hint that you do not want to run with ``all_Integral`` that does not have an ``_Integral`` counterpart (such as a best hint that would defeat the purpose of ``all_Integral``), you will need to remove it manually in the :py:meth:`~sympy.solvers.ode.dsolve` code. See also the :py:meth:`~sympy.solvers.ode.classify_ode` docstring for guidelines on writing a hint name. Determine *in general* how the solutions returned by your method compare with other methods that can potentially solve the same ODEs. Then, put your hints in the :py:data:`~sympy.solvers.ode.allhints` tuple in the order that they should be called. The ordering of this tuple determines which hints are default. Note that exceptions are ok, because it is easy for the user to choose individual hints with :py:meth:`~sympy.solvers.ode.dsolve`. In general, ``_Integral`` variants should go at the end of the list, and ``_best`` variants should go before the various hints they apply to. For example, the ``undetermined_coefficients`` hint comes before the ``variation_of_parameters`` hint because, even though variation of parameters is more general than undetermined coefficients, undetermined coefficients generally returns cleaner results for the ODEs that it can solve than variation of parameters does, and it does not require integration, so it is much faster. Next, you need to have a match expression or a function that matches the type of the ODE, which you should put in :py:meth:`~sympy.solvers.ode.classify_ode` (if the match function is more than just a few lines. It should match the ODE without solving for it as much as possible, so that :py:meth:`~sympy.solvers.ode.classify_ode` remains fast and is not hindered by bugs in solving code. Be sure to consider corner cases. For example, if your solution method involves dividing by something, make sure you exclude the case where that division will be 0. In most cases, the matching of the ODE will also give you the various parts that you need to solve it. You should put that in a dictionary (``.match()`` will do this for you), and add that as ``matching_hints['hint'] = matchdict`` in the relevant part of :py:meth:`~sympy.solvers.ode.classify_ode`. :py:meth:`~sympy.solvers.ode.classify_ode` will then send this to :py:meth:`~sympy.solvers.ode.dsolve`, which will send it to your function as the ``match`` argument. Your function should be named ``ode_<hint>(eq, func, order, match)`. If you need to send more information, put it in the ``match`` dictionary. For example, if you had to substitute in a dummy variable in :py:meth:`~sympy.solvers.ode.classify_ode` to match the ODE, you will need to pass it to your function using the `match` dict to access it. You can access the independent variable using ``func.args[0]``, and the dependent variable (the function you are trying to solve for) as ``func.func``. If, while trying to solve the ODE, you find that you cannot, raise ``NotImplementedError``. :py:meth:`~sympy.solvers.ode.dsolve` will catch this error with the ``all`` meta-hint, rather than causing the whole routine to fail. Add a docstring to your function that describes the method employed. Like with anything else in SymPy, you will need to add a doctest to the docstring, in addition to real tests in ``test_ode.py``. Try to maintain consistency with the other hint functions' docstrings. Add your method to the list at the top of this docstring. Also, add your method to ``ode.rst`` in the ``docs/src`` directory, so that the Sphinx docs will pull its docstring into the main SymPy documentation. Be sure to make the Sphinx documentation by running ``make html`` from within the doc directory to verify that the docstring formats correctly. If your solution method involves integrating, use :py:obj:`~.Integral` instead of :py:meth:`~sympy.core.expr.Expr.integrate`. This allows the user to bypass hard/slow integration by using the ``_Integral`` variant of your hint. In most cases, calling :py:meth:`sympy.core.basic.Basic.doit` will integrate your solution. If this is not the case, you will need to write special code in :py:meth:`~sympy.solvers.ode.ode._handle_Integral`. Arbitrary constants should be symbols named ``C1``, ``C2``, and so on. All solution methods should return an equality instance. If you need an arbitrary number of arbitrary constants, you can use ``constants = numbered_symbols(prefix='C', cls=Symbol, start=1)``. If it is possible to solve for the dependent function in a general way, do so. Otherwise, do as best as you can, but do not call solve in your ``ode_<hint>()`` function. :py:meth:`~sympy.solvers.ode.ode.odesimp` will attempt to solve the solution for you, so you do not need to do that. Lastly, if your ODE has a common simplification that can be applied to your solutions, you can add a special case in :py:meth:`~sympy.solvers.ode.ode.odesimp` for it. For example, solutions returned from the ``1st_homogeneous_coeff`` hints often have many :obj:`~sympy.functions.elementary.exponential.log` terms, so :py:meth:`~sympy.solvers.ode.ode.odesimp` calls :py:meth:`~sympy.simplify.simplify.logcombine` on them (it also helps to write the arbitrary constant as ``log(C1)`` instead of ``C1`` in this case). Also consider common ways that you can rearrange your solution to have :py:meth:`~sympy.solvers.ode.constantsimp` take better advantage of it. It is better to put simplification in :py:meth:`~sympy.solvers.ode.ode.odesimp` than in your method, because it can then be turned off with the simplify flag in :py:meth:`~sympy.solvers.ode.dsolve`. If you have any extraneous simplification in your function, be sure to only run it using ``if match.get('simplify', True):``, especially if it can be slow or if it can reduce the domain of the solution. Finally, as with every contribution to SymPy, your method will need to be tested. Add a test for each method in ``test_ode.py``. Follow the conventions there, i.e., test the solver using ``dsolve(eq, f(x), hint=your_hint)``, and also test the solution using :py:meth:`~sympy.solvers.ode.checkodesol` (you can put these in a separate tests and skip/XFAIL if it runs too slow/does not work). Be sure to call your hint specifically in :py:meth:`~sympy.solvers.ode.dsolve`, that way the test will not be broken simply by the introduction of another matching hint. If your method works for higher order (>1) ODEs, you will need to run ``sol = constant_renumber(sol, 'C', 1, order)`` for each solution, where ``order`` is the order of the ODE. This is because ``constant_renumber`` renumbers the arbitrary constants by printing order, which is platform dependent. Try to test every corner case of your solver, including a range of orders if it is a `n`\th order solver, but if your solver is slow, such as if it involves hard integration, try to keep the test run time down. Feel free to refactor existing hints to avoid duplicating code or creating inconsistencies. If you can show that your method exactly duplicates an existing method, including in the simplicity and speed of obtaining the solutions, then you can remove the old, less general method. The existing code is tested extensively in ``test_ode.py``, so if anything is broken, one of those tests will surely fail. """ from sympy.core import Add, S, Mul, Pow, oo from sympy.core.containers import Tuple from sympy.core.expr import AtomicExpr, Expr from sympy.core.function import (Function, Derivative, AppliedUndef, diff, expand, expand_mul, Subs) from sympy.core.multidimensional import vectorize from sympy.core.numbers import nan, zoo, Number from sympy.core.relational import Equality, Eq from sympy.core.sorting import default_sort_key, ordered from sympy.core.symbol import Symbol, Wild, Dummy, symbols from sympy.core.sympify import sympify from sympy.core.traversal import preorder_traversal from sympy.logic.boolalg import (BooleanAtom, BooleanTrue, BooleanFalse) from sympy.functions import exp, log, sqrt from sympy.functions.combinatorial.factorials import factorial from sympy.integrals.integrals import Integral from sympy.polys import (Poly, terms_gcd, PolynomialError, lcm) from sympy.polys.polytools import cancel from sympy.series import Order from sympy.series.series import series from sympy.simplify import (collect, logcombine, powsimp, # type: ignore separatevars, simplify, cse) from sympy.simplify.radsimp import collect_const from sympy.solvers import checksol, solve from sympy.utilities import numbered_symbols from sympy.utilities.iterables import uniq, sift, iterable from sympy.solvers.deutils import _preprocess, ode_order, _desolve #: This is a list of hints in the order that they should be preferred by #: :py:meth:`~sympy.solvers.ode.classify_ode`. In general, hints earlier in the #: list should produce simpler solutions than those later in the list (for #: ODEs that fit both). For now, the order of this list is based on empirical #: observations by the developers of SymPy. #: #: The hint used by :py:meth:`~sympy.solvers.ode.dsolve` for a specific ODE #: can be overridden (see the docstring). #: #: In general, ``_Integral`` hints are grouped at the end of the list, unless #: there is a method that returns an unevaluable integral most of the time #: (which go near the end of the list anyway). ``default``, ``all``, #: ``best``, and ``all_Integral`` meta-hints should not be included in this #: list, but ``_best`` and ``_Integral`` hints should be included. allhints = ( "factorable", "nth_algebraic", "separable", "1st_exact", "1st_linear", "Bernoulli", "1st_rational_riccati", "Riccati_special_minus2", "1st_homogeneous_coeff_best", "1st_homogeneous_coeff_subs_indep_div_dep", "1st_homogeneous_coeff_subs_dep_div_indep", "almost_linear", "linear_coefficients", "separable_reduced", "1st_power_series", "lie_group", "nth_linear_constant_coeff_homogeneous", "nth_linear_euler_eq_homogeneous", "nth_linear_constant_coeff_undetermined_coefficients", "nth_linear_euler_eq_nonhomogeneous_undetermined_coefficients", "nth_linear_constant_coeff_variation_of_parameters", "nth_linear_euler_eq_nonhomogeneous_variation_of_parameters", "Liouville", "2nd_linear_airy", "2nd_linear_bessel", "2nd_hypergeometric", "2nd_hypergeometric_Integral", "nth_order_reducible", "2nd_power_series_ordinary", "2nd_power_series_regular", "nth_algebraic_Integral", "separable_Integral", "1st_exact_Integral", "1st_linear_Integral", "Bernoulli_Integral", "1st_homogeneous_coeff_subs_indep_div_dep_Integral", "1st_homogeneous_coeff_subs_dep_div_indep_Integral", "almost_linear_Integral", "linear_coefficients_Integral", "separable_reduced_Integral", "nth_linear_constant_coeff_variation_of_parameters_Integral", "nth_linear_euler_eq_nonhomogeneous_variation_of_parameters_Integral", "Liouville_Integral", "2nd_nonlinear_autonomous_conserved", "2nd_nonlinear_autonomous_conserved_Integral", ) def get_numbered_constants(eq, num=1, start=1, prefix='C'): """ Returns a list of constants that do not occur in eq already. """ ncs = iter_numbered_constants(eq, start, prefix) Cs = [next(ncs) for i in range(num)] return (Cs[0] if num == 1 else tuple(Cs)) def iter_numbered_constants(eq, start=1, prefix='C'): """ Returns an iterator of constants that do not occur in eq already. """ if isinstance(eq, (Expr, Eq)): eq = [eq] elif not iterable(eq): raise ValueError("Expected Expr or iterable but got %s" % eq) atom_set = set().union(*[i.free_symbols for i in eq]) func_set = set().union(*[i.atoms(Function) for i in eq]) if func_set: atom_set |= {Symbol(str(f.func)) for f in func_set} return numbered_symbols(start=start, prefix=prefix, exclude=atom_set) def dsolve(eq, func=None, hint="default", simplify=True, ics= None, xi=None, eta=None, x0=0, n=6, **kwargs): r""" Solves any (supported) kind of ordinary differential equation and system of ordinary differential equations. For single ordinary differential equation ========================================= It is classified under this when number of equation in ``eq`` is one. **Usage** ``dsolve(eq, f(x), hint)`` -> Solve ordinary differential equation ``eq`` for function ``f(x)``, using method ``hint``. **Details** ``eq`` can be any supported ordinary differential equation (see the :py:mod:`~sympy.solvers.ode` docstring for supported methods). This can either be an :py:class:`~sympy.core.relational.Equality`, or an expression, which is assumed to be equal to ``0``. ``f(x)`` is a function of one variable whose derivatives in that variable make up the ordinary differential equation ``eq``. In many cases it is not necessary to provide this; it will be autodetected (and an error raised if it could not be detected). ``hint`` is the solving method that you want dsolve to use. Use ``classify_ode(eq, f(x))`` to get all of the possible hints for an ODE. The default hint, ``default``, will use whatever hint is returned first by :py:meth:`~sympy.solvers.ode.classify_ode`. See Hints below for more options that you can use for hint. ``simplify`` enables simplification by :py:meth:`~sympy.solvers.ode.ode.odesimp`. See its docstring for more information. Turn this off, for example, to disable solving of solutions for ``func`` or simplification of arbitrary constants. It will still integrate with this hint. Note that the solution may contain more arbitrary constants than the order of the ODE with this option enabled. ``xi`` and ``eta`` are the infinitesimal functions of an ordinary differential equation. They are the infinitesimals of the Lie group of point transformations for which the differential equation is invariant. The user can specify values for the infinitesimals. If nothing is specified, ``xi`` and ``eta`` are calculated using :py:meth:`~sympy.solvers.ode.infinitesimals` with the help of various heuristics. ``ics`` is the set of initial/boundary conditions for the differential equation. It should be given in the form of ``{f(x0): x1, f(x).diff(x).subs(x, x2): x3}`` and so on. For power series solutions, if no initial conditions are specified ``f(0)`` is assumed to be ``C0`` and the power series solution is calculated about 0. ``x0`` is the point about which the power series solution of a differential equation is to be evaluated. ``n`` gives the exponent of the dependent variable up to which the power series solution of a differential equation is to be evaluated. **Hints** Aside from the various solving methods, there are also some meta-hints that you can pass to :py:meth:`~sympy.solvers.ode.dsolve`: ``default``: This uses whatever hint is returned first by :py:meth:`~sympy.solvers.ode.classify_ode`. This is the default argument to :py:meth:`~sympy.solvers.ode.dsolve`. ``all``: To make :py:meth:`~sympy.solvers.ode.dsolve` apply all relevant classification hints, use ``dsolve(ODE, func, hint="all")``. This will return a dictionary of ``hint:solution`` terms. If a hint causes dsolve to raise the ``NotImplementedError``, value of that hint's key will be the exception object raised. The dictionary will also include some special keys: - ``order``: The order of the ODE. See also :py:meth:`~sympy.solvers.deutils.ode_order` in ``deutils.py``. - ``best``: The simplest hint; what would be returned by ``best`` below. - ``best_hint``: The hint that would produce the solution given by ``best``. If more than one hint produces the best solution, the first one in the tuple returned by :py:meth:`~sympy.solvers.ode.classify_ode` is chosen. - ``default``: The solution that would be returned by default. This is the one produced by the hint that appears first in the tuple returned by :py:meth:`~sympy.solvers.ode.classify_ode`. ``all_Integral``: This is the same as ``all``, except if a hint also has a corresponding ``_Integral`` hint, it only returns the ``_Integral`` hint. This is useful if ``all`` causes :py:meth:`~sympy.solvers.ode.dsolve` to hang because of a difficult or impossible integral. This meta-hint will also be much faster than ``all``, because :py:meth:`~sympy.core.expr.Expr.integrate` is an expensive routine. ``best``: To have :py:meth:`~sympy.solvers.ode.dsolve` try all methods and return the simplest one. This takes into account whether the solution is solvable in the function, whether it contains any Integral classes (i.e. unevaluatable integrals), and which one is the shortest in size. See also the :py:meth:`~sympy.solvers.ode.classify_ode` docstring for more info on hints, and the :py:mod:`~sympy.solvers.ode` docstring for a list of all supported hints. **Tips** - You can declare the derivative of an unknown function this way: >>> from sympy import Function, Derivative >>> from sympy.abc import x # x is the independent variable >>> f = Function("f")(x) # f is a function of x >>> # f_ will be the derivative of f with respect to x >>> f_ = Derivative(f, x) - See ``test_ode.py`` for many tests, which serves also as a set of examples for how to use :py:meth:`~sympy.solvers.ode.dsolve`. - :py:meth:`~sympy.solvers.ode.dsolve` always returns an :py:class:`~sympy.core.relational.Equality` class (except for the case when the hint is ``all`` or ``all_Integral``). If possible, it solves the solution explicitly for the function being solved for. Otherwise, it returns an implicit solution. - Arbitrary constants are symbols named ``C1``, ``C2``, and so on. - Because all solutions should be mathematically equivalent, some hints may return the exact same result for an ODE. Often, though, two different hints will return the same solution formatted differently. The two should be equivalent. Also note that sometimes the values of the arbitrary constants in two different solutions may not be the same, because one constant may have "absorbed" other constants into it. - Do ``help(ode.ode_<hintname>)`` to get help more information on a specific hint, where ``<hintname>`` is the name of a hint without ``_Integral``. For system of ordinary differential equations ============================================= **Usage** ``dsolve(eq, func)`` -> Solve a system of ordinary differential equations ``eq`` for ``func`` being list of functions including `x(t)`, `y(t)`, `z(t)` where number of functions in the list depends upon the number of equations provided in ``eq``. **Details** ``eq`` can be any supported system of ordinary differential equations This can either be an :py:class:`~sympy.core.relational.Equality`, or an expression, which is assumed to be equal to ``0``. ``func`` holds ``x(t)`` and ``y(t)`` being functions of one variable which together with some of their derivatives make up the system of ordinary differential equation ``eq``. It is not necessary to provide this; it will be autodetected (and an error raised if it could not be detected). **Hints** The hints are formed by parameters returned by classify_sysode, combining them give hints name used later for forming method name. Examples ======== >>> from sympy import Function, dsolve, Eq, Derivative, sin, cos, symbols >>> from sympy.abc import x >>> f = Function('f') >>> dsolve(Derivative(f(x), x, x) + 9*f(x), f(x)) Eq(f(x), C1*sin(3*x) + C2*cos(3*x)) >>> eq = sin(x)*cos(f(x)) + cos(x)*sin(f(x))*f(x).diff(x) >>> dsolve(eq, hint='1st_exact') [Eq(f(x), -acos(C1/cos(x)) + 2*pi), Eq(f(x), acos(C1/cos(x)))] >>> dsolve(eq, hint='almost_linear') [Eq(f(x), -acos(C1/cos(x)) + 2*pi), Eq(f(x), acos(C1/cos(x)))] >>> t = symbols('t') >>> x, y = symbols('x, y', cls=Function) >>> eq = (Eq(Derivative(x(t),t), 12*t*x(t) + 8*y(t)), Eq(Derivative(y(t),t), 21*x(t) + 7*t*y(t))) >>> dsolve(eq) [Eq(x(t), C1*x0(t) + C2*x0(t)*Integral(8*exp(Integral(7*t, t))*exp(Integral(12*t, t))/x0(t)**2, t)), Eq(y(t), C1*y0(t) + C2*(y0(t)*Integral(8*exp(Integral(7*t, t))*exp(Integral(12*t, t))/x0(t)**2, t) + exp(Integral(7*t, t))*exp(Integral(12*t, t))/x0(t)))] >>> eq = (Eq(Derivative(x(t),t),x(t)*y(t)*sin(t)), Eq(Derivative(y(t),t),y(t)**2*sin(t))) >>> dsolve(eq) {Eq(x(t), -exp(C1)/(C2*exp(C1) - cos(t))), Eq(y(t), -1/(C1 - cos(t)))} """ if iterable(eq): from sympy.solvers.ode.systems import dsolve_system # This may have to be changed in future # when we have weakly and strongly # connected components. This have to # changed to show the systems that haven't # been solved. try: sol = dsolve_system(eq, funcs=func, ics=ics, doit=True) return sol[0] if len(sol) == 1 else sol except NotImplementedError: pass match = classify_sysode(eq, func) eq = match['eq'] order = match['order'] func = match['func'] t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0] # keep highest order term coefficient positive for i in range(len(eq)): for func_ in func: if isinstance(func_, list): pass else: if eq[i].coeff(diff(func[i],t,ode_order(eq[i], func[i]))).is_negative: eq[i] = -eq[i] match['eq'] = eq if len(set(order.values()))!=1: raise ValueError("It solves only those systems of equations whose orders are equal") match['order'] = list(order.values())[0] def recur_len(l): return sum(recur_len(item) if isinstance(item,list) else 1 for item in l) if recur_len(func) != len(eq): raise ValueError("dsolve() and classify_sysode() work with " "number of functions being equal to number of equations") if match['type_of_equation'] is None: raise NotImplementedError else: if match['is_linear'] == True: solvefunc = globals()['sysode_linear_%(no_of_equation)seq_order%(order)s' % match] else: solvefunc = globals()['sysode_nonlinear_%(no_of_equation)seq_order%(order)s' % match] sols = solvefunc(match) if ics: constants = Tuple(*sols).free_symbols - Tuple(*eq).free_symbols solved_constants = solve_ics(sols, func, constants, ics) return [sol.subs(solved_constants) for sol in sols] return sols else: given_hint = hint # hint given by the user # See the docstring of _desolve for more details. hints = _desolve(eq, func=func, hint=hint, simplify=True, xi=xi, eta=eta, type='ode', ics=ics, x0=x0, n=n, **kwargs) eq = hints.pop('eq', eq) all_ = hints.pop('all', False) if all_: retdict = {} failed_hints = {} gethints = classify_ode(eq, dict=True, hint='all') orderedhints = gethints['ordered_hints'] for hint in hints: try: rv = _helper_simplify(eq, hint, hints[hint], simplify) except NotImplementedError as detail: failed_hints[hint] = detail else: retdict[hint] = rv func = hints[hint]['func'] retdict['best'] = min(list(retdict.values()), key=lambda x: ode_sol_simplicity(x, func, trysolving=not simplify)) if given_hint == 'best': return retdict['best'] for i in orderedhints: if retdict['best'] == retdict.get(i, None): retdict['best_hint'] = i break retdict['default'] = gethints['default'] retdict['order'] = gethints['order'] retdict.update(failed_hints) return retdict else: # The key 'hint' stores the hint needed to be solved for. hint = hints['hint'] return _helper_simplify(eq, hint, hints, simplify, ics=ics) def _helper_simplify(eq, hint, match, simplify=True, ics=None, **kwargs): r""" Helper function of dsolve that calls the respective :py:mod:`~sympy.solvers.ode` functions to solve for the ordinary differential equations. This minimizes the computation in calling :py:meth:`~sympy.solvers.deutils._desolve` multiple times. """ r = match func = r['func'] order = r['order'] match = r[hint] if isinstance(match, SingleODESolver): solvefunc = match elif hint.endswith('_Integral'): solvefunc = globals()['ode_' + hint[:-len('_Integral')]] else: solvefunc = globals()['ode_' + hint] free = eq.free_symbols cons = lambda s: s.free_symbols.difference(free) if simplify: # odesimp() will attempt to integrate, if necessary, apply constantsimp(), # attempt to solve for func, and apply any other hint specific # simplifications if isinstance(solvefunc, SingleODESolver): sols = solvefunc.get_general_solution() else: sols = solvefunc(eq, func, order, match) if iterable(sols): rv = [odesimp(eq, s, func, hint) for s in sols] else: rv = odesimp(eq, sols, func, hint) else: # We still want to integrate (you can disable it separately with the hint) if isinstance(solvefunc, SingleODESolver): exprs = solvefunc.get_general_solution(simplify=False) else: match['simplify'] = False # Some hints can take advantage of this option exprs = solvefunc(eq, func, order, match) if isinstance(exprs, list): rv = [_handle_Integral(expr, func, hint) for expr in exprs] else: rv = _handle_Integral(exprs, func, hint) if isinstance(rv, list): if simplify: rv = _remove_redundant_solutions(eq, rv, order, func.args[0]) if len(rv) == 1: rv = rv[0] if ics and 'power_series' not in hint: if isinstance(rv, (Expr, Eq)): solved_constants = solve_ics([rv], [r['func']], cons(rv), ics) rv = rv.subs(solved_constants) else: rv1 = [] for s in rv: try: solved_constants = solve_ics([s], [r['func']], cons(s), ics) except ValueError: continue rv1.append(s.subs(solved_constants)) if len(rv1) == 1: return rv1[0] rv = rv1 return rv def solve_ics(sols, funcs, constants, ics): """ Solve for the constants given initial conditions ``sols`` is a list of solutions. ``funcs`` is a list of functions. ``constants`` is a list of constants. ``ics`` is the set of initial/boundary conditions for the differential equation. It should be given in the form of ``{f(x0): x1, f(x).diff(x).subs(x, x2): x3}`` and so on. Returns a dictionary mapping constants to values. ``solution.subs(constants)`` will replace the constants in ``solution``. Example ======= >>> # From dsolve(f(x).diff(x) - f(x), f(x)) >>> from sympy import symbols, Eq, exp, Function >>> from sympy.solvers.ode.ode import solve_ics >>> f = Function('f') >>> x, C1 = symbols('x C1') >>> sols = [Eq(f(x), C1*exp(x))] >>> funcs = [f(x)] >>> constants = [C1] >>> ics = {f(0): 2} >>> solved_constants = solve_ics(sols, funcs, constants, ics) >>> solved_constants {C1: 2} >>> sols[0].subs(solved_constants) Eq(f(x), 2*exp(x)) """ # Assume ics are of the form f(x0): value or Subs(diff(f(x), x, n), (x, # x0)): value (currently checked by classify_ode). To solve, replace x # with x0, f(x0) with value, then solve for constants. For f^(n)(x0), # differentiate the solution n times, so that f^(n)(x) appears. x = funcs[0].args[0] diff_sols = [] subs_sols = [] diff_variables = set() for funcarg, value in ics.items(): if isinstance(funcarg, AppliedUndef): x0 = funcarg.args[0] matching_func = [f for f in funcs if f.func == funcarg.func][0] S = sols elif isinstance(funcarg, (Subs, Derivative)): if isinstance(funcarg, Subs): # Make sure it stays a subs. Otherwise subs below will produce # a different looking term. funcarg = funcarg.doit() if isinstance(funcarg, Subs): deriv = funcarg.expr x0 = funcarg.point[0] variables = funcarg.expr.variables matching_func = deriv elif isinstance(funcarg, Derivative): deriv = funcarg x0 = funcarg.variables[0] variables = (x,)*len(funcarg.variables) matching_func = deriv.subs(x0, x) for sol in sols: if sol.has(deriv.expr.func): diff_sols.append(Eq(sol.lhs.diff(*variables), sol.rhs.diff(*variables))) diff_variables.add(variables) S = diff_sols else: raise NotImplementedError("Unrecognized initial condition") for sol in S: if sol.has(matching_func): sol2 = sol sol2 = sol2.subs(x, x0) sol2 = sol2.subs(funcarg, value) # This check is necessary because of issue #15724 if not isinstance(sol2, BooleanAtom) or not subs_sols: subs_sols = [s for s in subs_sols if not isinstance(s, BooleanAtom)] subs_sols.append(sol2) # TODO: Use solveset here try: solved_constants = solve(subs_sols, constants, dict=True) except NotImplementedError: solved_constants = [] # XXX: We can't differentiate between the solution not existing because of # invalid initial conditions, and not existing because solve is not smart # enough. If we could use solveset, this might be improvable, but for now, # we use NotImplementedError in this case. if not solved_constants: raise ValueError("Couldn't solve for initial conditions") if solved_constants == True: raise ValueError("Initial conditions did not produce any solutions for constants. Perhaps they are degenerate.") if len(solved_constants) > 1: raise NotImplementedError("Initial conditions produced too many solutions for constants") return solved_constants[0] def classify_ode(eq, func=None, dict=False, ics=None, *, prep=True, xi=None, eta=None, n=None, **kwargs): r""" Returns a tuple of possible :py:meth:`~sympy.solvers.ode.dsolve` classifications for an ODE. The tuple is ordered so that first item is the classification that :py:meth:`~sympy.solvers.ode.dsolve` uses to solve the ODE by default. In general, classifications at the near the beginning of the list will produce better solutions faster than those near the end, thought there are always exceptions. To make :py:meth:`~sympy.solvers.ode.dsolve` use a different classification, use ``dsolve(ODE, func, hint=<classification>)``. See also the :py:meth:`~sympy.solvers.ode.dsolve` docstring for different meta-hints you can use. If ``dict`` is true, :py:meth:`~sympy.solvers.ode.classify_ode` will return a dictionary of ``hint:match`` expression terms. This is intended for internal use by :py:meth:`~sympy.solvers.ode.dsolve`. Note that because dictionaries are ordered arbitrarily, this will most likely not be in the same order as the tuple. You can get help on different hints by executing ``help(ode.ode_hintname)``, where ``hintname`` is the name of the hint without ``_Integral``. See :py:data:`~sympy.solvers.ode.allhints` or the :py:mod:`~sympy.solvers.ode` docstring for a list of all supported hints that can be returned from :py:meth:`~sympy.solvers.ode.classify_ode`. Notes ===== These are remarks on hint names. ``_Integral`` If a classification has ``_Integral`` at the end, it will return the expression with an unevaluated :py:class:`~.Integral` class in it. Note that a hint may do this anyway if :py:meth:`~sympy.core.expr.Expr.integrate` cannot do the integral, though just using an ``_Integral`` will do so much faster. Indeed, an ``_Integral`` hint will always be faster than its corresponding hint without ``_Integral`` because :py:meth:`~sympy.core.expr.Expr.integrate` is an expensive routine. If :py:meth:`~sympy.solvers.ode.dsolve` hangs, it is probably because :py:meth:`~sympy.core.expr.Expr.integrate` is hanging on a tough or impossible integral. Try using an ``_Integral`` hint or ``all_Integral`` to get it return something. Note that some hints do not have ``_Integral`` counterparts. This is because :py:func:`~sympy.integrals.integrals.integrate` is not used in solving the ODE for those method. For example, `n`\th order linear homogeneous ODEs with constant coefficients do not require integration to solve, so there is no ``nth_linear_homogeneous_constant_coeff_Integrate`` hint. You can easily evaluate any unevaluated :py:class:`~sympy.integrals.integrals.Integral`\s in an expression by doing ``expr.doit()``. Ordinals Some hints contain an ordinal such as ``1st_linear``. This is to help differentiate them from other hints, as well as from other methods that may not be implemented yet. If a hint has ``nth`` in it, such as the ``nth_linear`` hints, this means that the method used to applies to ODEs of any order. ``indep`` and ``dep`` Some hints contain the words ``indep`` or ``dep``. These reference the independent variable and the dependent function, respectively. For example, if an ODE is in terms of `f(x)`, then ``indep`` will refer to `x` and ``dep`` will refer to `f`. ``subs`` If a hints has the word ``subs`` in it, it means that the ODE is solved by substituting the expression given after the word ``subs`` for a single dummy variable. This is usually in terms of ``indep`` and ``dep`` as above. The substituted expression will be written only in characters allowed for names of Python objects, meaning operators will be spelled out. For example, ``indep``/``dep`` will be written as ``indep_div_dep``. ``coeff`` The word ``coeff`` in a hint refers to the coefficients of something in the ODE, usually of the derivative terms. See the docstring for the individual methods for more info (``help(ode)``). This is contrast to ``coefficients``, as in ``undetermined_coefficients``, which refers to the common name of a method. ``_best`` Methods that have more than one fundamental way to solve will have a hint for each sub-method and a ``_best`` meta-classification. This will evaluate all hints and return the best, using the same considerations as the normal ``best`` meta-hint. Examples ======== >>> from sympy import Function, classify_ode, Eq >>> from sympy.abc import x >>> f = Function('f') >>> classify_ode(Eq(f(x).diff(x), 0), f(x)) ('nth_algebraic', 'separable', '1st_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') >>> classify_ode(f(x).diff(x, 2) + 3*f(x).diff(x) + 2*f(x) - 4) ('factorable', 'nth_linear_constant_coeff_undetermined_coefficients', 'nth_linear_constant_coeff_variation_of_parameters', 'nth_linear_constant_coeff_variation_of_parameters_Integral') """ ics = sympify(ics) if func and len(func.args) != 1: raise ValueError("dsolve() and classify_ode() only " "work with functions of one variable, not %s" % func) if isinstance(eq, Equality): eq = eq.lhs - eq.rhs # Some methods want the unprocessed equation eq_orig = eq if prep or func is None: eq, func_ = _preprocess(eq, func) if func is None: func = func_ x = func.args[0] f = func.func y = Dummy('y') terms = 5 if n is None else n order = ode_order(eq, f(x)) # hint:matchdict or hint:(tuple of matchdicts) # Also will contain "default":<default hint> and "order":order items. matching_hints = {"order": order} df = f(x).diff(x) a = Wild('a', exclude=[f(x)]) d = Wild('d', exclude=[df, f(x).diff(x, 2)]) e = Wild('e', exclude=[df]) n = Wild('n', exclude=[x, f(x), df]) c1 = Wild('c1', exclude=[x]) a3 = Wild('a3', exclude=[f(x), df, f(x).diff(x, 2)]) b3 = Wild('b3', exclude=[f(x), df, f(x).diff(x, 2)]) c3 = Wild('c3', exclude=[f(x), df, f(x).diff(x, 2)]) boundary = {} # Used to extract initial conditions C1 = Symbol("C1") # Preprocessing to get the initial conditions out if ics is not None: for funcarg in ics: # Separating derivatives if isinstance(funcarg, (Subs, Derivative)): # f(x).diff(x).subs(x, 0) is a Subs, but f(x).diff(x).subs(x, # y) is a Derivative if isinstance(funcarg, Subs): deriv = funcarg.expr old = funcarg.variables[0] new = funcarg.point[0] elif isinstance(funcarg, Derivative): deriv = funcarg # No information on this. Just assume it was x old = x new = funcarg.variables[0] if (isinstance(deriv, Derivative) and isinstance(deriv.args[0], AppliedUndef) and deriv.args[0].func == f and len(deriv.args[0].args) == 1 and old == x and not new.has(x) and all(i == deriv.variables[0] for i in deriv.variables) and not ics[funcarg].has(f)): dorder = ode_order(deriv, x) temp = 'f' + str(dorder) boundary.update({temp: new, temp + 'val': ics[funcarg]}) else: raise ValueError("Enter valid boundary conditions for Derivatives") # Separating functions elif isinstance(funcarg, AppliedUndef): if (funcarg.func == f and len(funcarg.args) == 1 and not funcarg.args[0].has(x) and not ics[funcarg].has(f)): boundary.update({'f0': funcarg.args[0], 'f0val': ics[funcarg]}) else: raise ValueError("Enter valid boundary conditions for Function") else: raise ValueError("Enter boundary conditions of the form ics={f(point): value, f(x).diff(x, order).subs(x, point): value}") ode = SingleODEProblem(eq_orig, func, x, prep=prep, xi=xi, eta=eta) user_hint = kwargs.get('hint', 'default') # Used when dsolve is called without an explicit hint. # We exit early to return the first valid match early_exit = (user_hint=='default') if user_hint.endswith('_Integral'): user_hint = user_hint[:-len('_Integral')] user_map = solver_map # An explicit hint has been given to dsolve # Skip matching code for other hints if user_hint not in ['default', 'all', 'all_Integral', 'best'] and user_hint in solver_map: user_map = {user_hint: solver_map[user_hint]} for hint in user_map: solver = user_map[hint](ode) if solver.matches(): matching_hints[hint] = solver if user_map[hint].has_integral: matching_hints[hint + "_Integral"] = solver if dict and early_exit: matching_hints["default"] = hint return matching_hints eq = expand(eq) # Precondition to try remove f(x) from highest order derivative reduced_eq = None if eq.is_Add: deriv_coef = eq.coeff(f(x).diff(x, order)) if deriv_coef not in (1, 0): r = deriv_coef.match(a*f(x)**c1) if r and r[c1]: den = f(x)**r[c1] reduced_eq = Add(*[arg/den for arg in eq.args]) if not reduced_eq: reduced_eq = eq if order == 1: # NON-REDUCED FORM OF EQUATION matches r = collect(eq, df, exact=True).match(d + e * df) if r: r['d'] = d r['e'] = e r['y'] = y r[d] = r[d].subs(f(x), y) r[e] = r[e].subs(f(x), y) # FIRST ORDER POWER SERIES WHICH NEEDS INITIAL CONDITIONS # TODO: Hint first order series should match only if d/e is analytic. # For now, only d/e and (d/e).diff(arg) is checked for existence at # at a given point. # This is currently done internally in ode_1st_power_series. point = boundary.get('f0', 0) value = boundary.get('f0val', C1) check = cancel(r[d]/r[e]) check1 = check.subs({x: point, y: value}) if not check1.has(oo) and not check1.has(zoo) and \ not check1.has(nan) and not check1.has(-oo): check2 = (check1.diff(x)).subs({x: point, y: value}) if not check2.has(oo) and not check2.has(zoo) and \ not check2.has(nan) and not check2.has(-oo): rseries = r.copy() rseries.update({'terms': terms, 'f0': point, 'f0val': value}) matching_hints["1st_power_series"] = rseries elif order == 2: # Homogeneous second order differential equation of the form # a3*f(x).diff(x, 2) + b3*f(x).diff(x) + c3 # It has a definite power series solution at point x0 if, b3/a3 and c3/a3 # are analytic at x0. deq = a3*(f(x).diff(x, 2)) + b3*df + c3*f(x) r = collect(reduced_eq, [f(x).diff(x, 2), f(x).diff(x), f(x)]).match(deq) ordinary = False if r: if not all(r[key].is_polynomial() for key in r): n, d = reduced_eq.as_numer_denom() reduced_eq = expand(n) r = collect(reduced_eq, [f(x).diff(x, 2), f(x).diff(x), f(x)]).match(deq) if r and r[a3] != 0: p = cancel(r[b3]/r[a3]) # Used below q = cancel(r[c3]/r[a3]) # Used below point = kwargs.get('x0', 0) check = p.subs(x, point) if not check.has(oo, nan, zoo, -oo): check = q.subs(x, point) if not check.has(oo, nan, zoo, -oo): ordinary = True r.update({'a3': a3, 'b3': b3, 'c3': c3, 'x0': point, 'terms': terms}) matching_hints["2nd_power_series_ordinary"] = r # Checking if the differential equation has a regular singular point # at x0. It has a regular singular point at x0, if (b3/a3)*(x - x0) # and (c3/a3)*((x - x0)**2) are analytic at x0. if not ordinary: p = cancel((x - point)*p) check = p.subs(x, point) if not check.has(oo, nan, zoo, -oo): q = cancel(((x - point)**2)*q) check = q.subs(x, point) if not check.has(oo, nan, zoo, -oo): coeff_dict = {'p': p, 'q': q, 'x0': point, 'terms': terms} matching_hints["2nd_power_series_regular"] = coeff_dict # Order keys based on allhints. retlist = [i for i in allhints if i in matching_hints] if dict: # Dictionaries are ordered arbitrarily, so make note of which # hint would come first for dsolve(). Use an ordered dict in Py 3. matching_hints["default"] = retlist[0] if retlist else None matching_hints["ordered_hints"] = tuple(retlist) return matching_hints else: return tuple(retlist) def classify_sysode(eq, funcs=None, **kwargs): r""" Returns a dictionary of parameter names and values that define the system of ordinary differential equations in ``eq``. The parameters are further used in :py:meth:`~sympy.solvers.ode.dsolve` for solving that system. Some parameter names and values are: 'is_linear' (boolean), which tells whether the given system is linear. Note that "linear" here refers to the operator: terms such as ``x*diff(x,t)`` are nonlinear, whereas terms like ``sin(t)*diff(x,t)`` are still linear operators. 'func' (list) contains the :py:class:`~sympy.core.function.Function`s that appear with a derivative in the ODE, i.e. those that we are trying to solve the ODE for. 'order' (dict) with the maximum derivative for each element of the 'func' parameter. 'func_coeff' (dict or Matrix) with the coefficient for each triple ``(equation number, function, order)```. The coefficients are those subexpressions that do not appear in 'func', and hence can be considered constant for purposes of ODE solving. The value of this parameter can also be a Matrix if the system of ODEs are linear first order of the form X' = AX where X is the vector of dependent variables. Here, this function returns the coefficient matrix A. 'eq' (list) with the equations from ``eq``, sympified and transformed into expressions (we are solving for these expressions to be zero). 'no_of_equations' (int) is the number of equations (same as ``len(eq)``). 'type_of_equation' (string) is an internal classification of the type of ODE. 'is_constant' (boolean), which tells if the system of ODEs is constant coefficient or not. This key is temporary addition for now and is in the match dict only when the system of ODEs is linear first order constant coefficient homogeneous. So, this key's value is True for now if it is available else it does not exist. 'is_homogeneous' (boolean), which tells if the system of ODEs is homogeneous. Like the key 'is_constant', this key is a temporary addition and it is True since this key value is available only when the system is linear first order constant coefficient homogeneous. References ========== -http://eqworld.ipmnet.ru/en/solutions/sysode/sode-toc1.htm -A. D. Polyanin and A. V. Manzhirov, Handbook of Mathematics for Engineers and Scientists Examples ======== >>> from sympy import Function, Eq, symbols, diff >>> from sympy.solvers.ode.ode import classify_sysode >>> from sympy.abc import t >>> f, x, y = symbols('f, x, y', cls=Function) >>> k, l, m, n = symbols('k, l, m, n', Integer=True) >>> x1 = diff(x(t), t) ; y1 = diff(y(t), t) >>> x2 = diff(x(t), t, t) ; y2 = diff(y(t), t, t) >>> eq = (Eq(x1, 12*x(t) - 6*y(t)), Eq(y1, 11*x(t) + 3*y(t))) >>> classify_sysode(eq) {'eq': [-12*x(t) + 6*y(t) + Derivative(x(t), t), -11*x(t) - 3*y(t) + Derivative(y(t), t)], 'func': [x(t), y(t)], 'func_coeff': {(0, x(t), 0): -12, (0, x(t), 1): 1, (0, y(t), 0): 6, (0, y(t), 1): 0, (1, x(t), 0): -11, (1, x(t), 1): 0, (1, y(t), 0): -3, (1, y(t), 1): 1}, 'is_linear': True, 'no_of_equation': 2, 'order': {x(t): 1, y(t): 1}, 'type_of_equation': None} >>> eq = (Eq(diff(x(t),t), 5*t*x(t) + t**2*y(t) + 2), Eq(diff(y(t),t), -t**2*x(t) + 5*t*y(t))) >>> classify_sysode(eq) {'eq': [-t**2*y(t) - 5*t*x(t) + Derivative(x(t), t) - 2, t**2*x(t) - 5*t*y(t) + Derivative(y(t), t)], 'func': [x(t), y(t)], 'func_coeff': {(0, x(t), 0): -5*t, (0, x(t), 1): 1, (0, y(t), 0): -t**2, (0, y(t), 1): 0, (1, x(t), 0): t**2, (1, x(t), 1): 0, (1, y(t), 0): -5*t, (1, y(t), 1): 1}, 'is_linear': True, 'no_of_equation': 2, 'order': {x(t): 1, y(t): 1}, 'type_of_equation': None} """ # Sympify equations and convert iterables of equations into # a list of equations def _sympify(eq): return list(map(sympify, eq if iterable(eq) else [eq])) eq, funcs = (_sympify(w) for w in [eq, funcs]) for i, fi in enumerate(eq): if isinstance(fi, Equality): eq[i] = fi.lhs - fi.rhs t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0] matching_hints = {"no_of_equation":i+1} matching_hints['eq'] = eq if i==0: raise ValueError("classify_sysode() works for systems of ODEs. " "For scalar ODEs, classify_ode should be used") # find all the functions if not given order = dict() if funcs==[None]: funcs = _extract_funcs(eq) funcs = list(set(funcs)) if len(funcs) != len(eq): raise ValueError("Number of functions given is not equal to the number of equations %s" % funcs) # This logic of list of lists in funcs to # be replaced later. func_dict = dict() for func in funcs: if not order.get(func, False): max_order = 0 for i, eqs_ in enumerate(eq): order_ = ode_order(eqs_,func) if max_order < order_: max_order = order_ eq_no = i if eq_no in func_dict: func_dict[eq_no] = [func_dict[eq_no], func] else: func_dict[eq_no] = func order[func] = max_order funcs = [func_dict[i] for i in range(len(func_dict))] matching_hints['func'] = funcs for func in funcs: if isinstance(func, list): for func_elem in func: if len(func_elem.args) != 1: raise ValueError("dsolve() and classify_sysode() work with " "functions of one variable only, not %s" % func) else: if func and len(func.args) != 1: raise ValueError("dsolve() and classify_sysode() work with " "functions of one variable only, not %s" % func) # find the order of all equation in system of odes matching_hints["order"] = order # find coefficients of terms f(t), diff(f(t),t) and higher derivatives # and similarly for other functions g(t), diff(g(t),t) in all equations. # Here j denotes the equation number, funcs[l] denotes the function about # which we are talking about and k denotes the order of function funcs[l] # whose coefficient we are calculating. def linearity_check(eqs, j, func, is_linear_): for k in range(order[func] + 1): func_coef[j, func, k] = collect(eqs.expand(), [diff(func, t, k)]).coeff(diff(func, t, k)) if is_linear_ == True: if func_coef[j, func, k] == 0: if k == 0: coef = eqs.as_independent(func, as_Add=True)[1] for xr in range(1, ode_order(eqs,func) + 1): coef -= eqs.as_independent(diff(func, t, xr), as_Add=True)[1] if coef != 0: is_linear_ = False else: if eqs.as_independent(diff(func, t, k), as_Add=True)[1]: is_linear_ = False else: for func_ in funcs: if isinstance(func_, list): for elem_func_ in func_: dep = func_coef[j, func, k].as_independent(elem_func_, as_Add=True)[1] if dep != 0: is_linear_ = False else: dep = func_coef[j, func, k].as_independent(func_, as_Add=True)[1] if dep != 0: is_linear_ = False return is_linear_ func_coef = {} is_linear = True for j, eqs in enumerate(eq): for func in funcs: if isinstance(func, list): for func_elem in func: is_linear = linearity_check(eqs, j, func_elem, is_linear) else: is_linear = linearity_check(eqs, j, func, is_linear) matching_hints['func_coeff'] = func_coef matching_hints['is_linear'] = is_linear if len(set(order.values())) == 1: order_eq = list(matching_hints['order'].values())[0] if matching_hints['is_linear'] == True: if matching_hints['no_of_equation'] == 2: if order_eq == 1: type_of_equation = check_linear_2eq_order1(eq, funcs, func_coef) else: type_of_equation = None # If the equation does not match up with any of the # general case solvers in systems.py and the number # of equations is greater than 2, then NotImplementedError # should be raised. else: type_of_equation = None else: if matching_hints['no_of_equation'] == 2: if order_eq == 1: type_of_equation = check_nonlinear_2eq_order1(eq, funcs, func_coef) else: type_of_equation = None elif matching_hints['no_of_equation'] == 3: if order_eq == 1: type_of_equation = check_nonlinear_3eq_order1(eq, funcs, func_coef) else: type_of_equation = None else: type_of_equation = None else: type_of_equation = None matching_hints['type_of_equation'] = type_of_equation return matching_hints def check_linear_2eq_order1(eq, func, func_coef): x = func[0].func y = func[1].func fc = func_coef t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0] r = dict() # for equations Eq(a1*diff(x(t),t), b1*x(t) + c1*y(t) + d1) # and Eq(a2*diff(y(t),t), b2*x(t) + c2*y(t) + d2) r['a1'] = fc[0,x(t),1] ; r['a2'] = fc[1,y(t),1] r['b1'] = -fc[0,x(t),0]/fc[0,x(t),1] ; r['b2'] = -fc[1,x(t),0]/fc[1,y(t),1] r['c1'] = -fc[0,y(t),0]/fc[0,x(t),1] ; r['c2'] = -fc[1,y(t),0]/fc[1,y(t),1] forcing = [S.Zero,S.Zero] for i in range(2): for j in Add.make_args(eq[i]): if not j.has(x(t), y(t)): forcing[i] += j if not (forcing[0].has(t) or forcing[1].has(t)): # We can handle homogeneous case and simple constant forcings r['d1'] = forcing[0] r['d2'] = forcing[1] else: # Issue #9244: nonhomogeneous linear systems are not supported return None # Conditions to check for type 6 whose equations are Eq(diff(x(t),t), f(t)*x(t) + g(t)*y(t)) and # Eq(diff(y(t),t), a*[f(t) + a*h(t)]x(t) + a*[g(t) - h(t)]*y(t)) p = 0 q = 0 p1 = cancel(r['b2']/(cancel(r['b2']/r['c2']).as_numer_denom()[0])) p2 = cancel(r['b1']/(cancel(r['b1']/r['c1']).as_numer_denom()[0])) for n, i in enumerate([p1, p2]): for j in Mul.make_args(collect_const(i)): if not j.has(t): q = j if q and n==0: if ((r['b2']/j - r['b1'])/(r['c1'] - r['c2']/j)) == j: p = 1 elif q and n==1: if ((r['b1']/j - r['b2'])/(r['c2'] - r['c1']/j)) == j: p = 2 # End of condition for type 6 if r['d1']!=0 or r['d2']!=0: return None else: if not any(r[k].has(t) for k in 'a1 a2 b1 b2 c1 c2'.split()): return None else: r['b1'] = r['b1']/r['a1'] ; r['b2'] = r['b2']/r['a2'] r['c1'] = r['c1']/r['a1'] ; r['c2'] = r['c2']/r['a2'] if p: return "type6" else: # Equations for type 7 are Eq(diff(x(t),t), f(t)*x(t) + g(t)*y(t)) and Eq(diff(y(t),t), h(t)*x(t) + p(t)*y(t)) return "type7" def check_nonlinear_2eq_order1(eq, func, func_coef): t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0] f = Wild('f') g = Wild('g') u, v = symbols('u, v', cls=Dummy) def check_type(x, y): r1 = eq[0].match(t*diff(x(t),t) - x(t) + f) r2 = eq[1].match(t*diff(y(t),t) - y(t) + g) if not (r1 and r2): r1 = eq[0].match(diff(x(t),t) - x(t)/t + f/t) r2 = eq[1].match(diff(y(t),t) - y(t)/t + g/t) if not (r1 and r2): r1 = (-eq[0]).match(t*diff(x(t),t) - x(t) + f) r2 = (-eq[1]).match(t*diff(y(t),t) - y(t) + g) if not (r1 and r2): r1 = (-eq[0]).match(diff(x(t),t) - x(t)/t + f/t) r2 = (-eq[1]).match(diff(y(t),t) - y(t)/t + g/t) if r1 and r2 and not (r1[f].subs(diff(x(t),t),u).subs(diff(y(t),t),v).has(t) \ or r2[g].subs(diff(x(t),t),u).subs(diff(y(t),t),v).has(t)): return 'type5' else: return None for func_ in func: if isinstance(func_, list): x = func[0][0].func y = func[0][1].func eq_type = check_type(x, y) if not eq_type: eq_type = check_type(y, x) return eq_type x = func[0].func y = func[1].func fc = func_coef n = Wild('n', exclude=[x(t),y(t)]) f1 = Wild('f1', exclude=[v,t]) f2 = Wild('f2', exclude=[v,t]) g1 = Wild('g1', exclude=[u,t]) g2 = Wild('g2', exclude=[u,t]) for i in range(2): eqs = 0 for terms in Add.make_args(eq[i]): eqs += terms/fc[i,func[i],1] eq[i] = eqs r = eq[0].match(diff(x(t),t) - x(t)**n*f) if r: g = (diff(y(t),t) - eq[1])/r[f] if r and not (g.has(x(t)) or g.subs(y(t),v).has(t) or r[f].subs(x(t),u).subs(y(t),v).has(t)): return 'type1' r = eq[0].match(diff(x(t),t) - exp(n*x(t))*f) if r: g = (diff(y(t),t) - eq[1])/r[f] if r and not (g.has(x(t)) or g.subs(y(t),v).has(t) or r[f].subs(x(t),u).subs(y(t),v).has(t)): return 'type2' g = Wild('g') r1 = eq[0].match(diff(x(t),t) - f) r2 = eq[1].match(diff(y(t),t) - g) if r1 and r2 and not (r1[f].subs(x(t),u).subs(y(t),v).has(t) or \ r2[g].subs(x(t),u).subs(y(t),v).has(t)): return 'type3' r1 = eq[0].match(diff(x(t),t) - f) r2 = eq[1].match(diff(y(t),t) - g) num, den = ( (r1[f].subs(x(t),u).subs(y(t),v))/ (r2[g].subs(x(t),u).subs(y(t),v))).as_numer_denom() R1 = num.match(f1*g1) R2 = den.match(f2*g2) # phi = (r1[f].subs(x(t),u).subs(y(t),v))/num if R1 and R2: return 'type4' return None def check_nonlinear_2eq_order2(eq, func, func_coef): return None def check_nonlinear_3eq_order1(eq, func, func_coef): x = func[0].func y = func[1].func z = func[2].func fc = func_coef t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0] u, v, w = symbols('u, v, w', cls=Dummy) a = Wild('a', exclude=[x(t), y(t), z(t), t]) b = Wild('b', exclude=[x(t), y(t), z(t), t]) c = Wild('c', exclude=[x(t), y(t), z(t), t]) f = Wild('f') F1 = Wild('F1') F2 = Wild('F2') F3 = Wild('F3') for i in range(3): eqs = 0 for terms in Add.make_args(eq[i]): eqs += terms/fc[i,func[i],1] eq[i] = eqs r1 = eq[0].match(diff(x(t),t) - a*y(t)*z(t)) r2 = eq[1].match(diff(y(t),t) - b*z(t)*x(t)) r3 = eq[2].match(diff(z(t),t) - c*x(t)*y(t)) if r1 and r2 and r3: num1, den1 = r1[a].as_numer_denom() num2, den2 = r2[b].as_numer_denom() num3, den3 = r3[c].as_numer_denom() if solve([num1*u-den1*(v-w), num2*v-den2*(w-u), num3*w-den3*(u-v)],[u, v]): return 'type1' r = eq[0].match(diff(x(t),t) - y(t)*z(t)*f) if r: r1 = collect_const(r[f]).match(a*f) r2 = ((diff(y(t),t) - eq[1])/r1[f]).match(b*z(t)*x(t)) r3 = ((diff(z(t),t) - eq[2])/r1[f]).match(c*x(t)*y(t)) if r1 and r2 and r3: num1, den1 = r1[a].as_numer_denom() num2, den2 = r2[b].as_numer_denom() num3, den3 = r3[c].as_numer_denom() if solve([num1*u-den1*(v-w), num2*v-den2*(w-u), num3*w-den3*(u-v)],[u, v]): return 'type2' r = eq[0].match(diff(x(t),t) - (F2-F3)) if r: r1 = collect_const(r[F2]).match(c*F2) r1.update(collect_const(r[F3]).match(b*F3)) if r1: if eq[1].has(r1[F2]) and not eq[1].has(r1[F3]): r1[F2], r1[F3] = r1[F3], r1[F2] r1[c], r1[b] = -r1[b], -r1[c] r2 = eq[1].match(diff(y(t),t) - a*r1[F3] + r1[c]*F1) if r2: r3 = (eq[2] == diff(z(t),t) - r1[b]*r2[F1] + r2[a]*r1[F2]) if r1 and r2 and r3: return 'type3' r = eq[0].match(diff(x(t),t) - z(t)*F2 + y(t)*F3) if r: r1 = collect_const(r[F2]).match(c*F2) r1.update(collect_const(r[F3]).match(b*F3)) if r1: if eq[1].has(r1[F2]) and not eq[1].has(r1[F3]): r1[F2], r1[F3] = r1[F3], r1[F2] r1[c], r1[b] = -r1[b], -r1[c] r2 = (diff(y(t),t) - eq[1]).match(a*x(t)*r1[F3] - r1[c]*z(t)*F1) if r2: r3 = (diff(z(t),t) - eq[2] == r1[b]*y(t)*r2[F1] - r2[a]*x(t)*r1[F2]) if r1 and r2 and r3: return 'type4' r = (diff(x(t),t) - eq[0]).match(x(t)*(F2 - F3)) if r: r1 = collect_const(r[F2]).match(c*F2) r1.update(collect_const(r[F3]).match(b*F3)) if r1: if eq[1].has(r1[F2]) and not eq[1].has(r1[F3]): r1[F2], r1[F3] = r1[F3], r1[F2] r1[c], r1[b] = -r1[b], -r1[c] r2 = (diff(y(t),t) - eq[1]).match(y(t)*(a*r1[F3] - r1[c]*F1)) if r2: r3 = (diff(z(t),t) - eq[2] == z(t)*(r1[b]*r2[F1] - r2[a]*r1[F2])) if r1 and r2 and r3: return 'type5' return None def check_nonlinear_3eq_order2(eq, func, func_coef): return None @vectorize(0) def odesimp(ode, eq, func, hint): r""" Simplifies solutions of ODEs, including trying to solve for ``func`` and running :py:meth:`~sympy.solvers.ode.constantsimp`. It may use knowledge of the type of solution that the hint returns to apply additional simplifications. It also attempts to integrate any :py:class:`~sympy.integrals.integrals.Integral`\s in the expression, if the hint is not an ``_Integral`` hint. This function should have no effect on expressions returned by :py:meth:`~sympy.solvers.ode.dsolve`, as :py:meth:`~sympy.solvers.ode.dsolve` already calls :py:meth:`~sympy.solvers.ode.ode.odesimp`, but the individual hint functions do not call :py:meth:`~sympy.solvers.ode.ode.odesimp` (because the :py:meth:`~sympy.solvers.ode.dsolve` wrapper does). Therefore, this function is designed for mainly internal use. Examples ======== >>> from sympy import sin, symbols, dsolve, pprint, Function >>> from sympy.solvers.ode.ode import odesimp >>> x, u2, C1= symbols('x,u2,C1') >>> f = Function('f') >>> eq = dsolve(x*f(x).diff(x) - f(x) - x*sin(f(x)/x), f(x), ... hint='1st_homogeneous_coeff_subs_indep_div_dep_Integral', ... simplify=False) >>> pprint(eq, wrap_line=False) x ---- f(x) / | | / 1 \ | -|u1 + -------| | | /1 \| | | sin|--|| | \ \u1// log(f(x)) = log(C1) + | ---------------- d(u1) | 2 | u1 | / >>> pprint(odesimp(eq, f(x), 1, {C1}, ... hint='1st_homogeneous_coeff_subs_indep_div_dep' ... )) #doctest: +SKIP x --------- = C1 /f(x)\ tan|----| \2*x / """ x = func.args[0] f = func.func C1 = get_numbered_constants(eq, num=1) constants = eq.free_symbols - ode.free_symbols # First, integrate if the hint allows it. eq = _handle_Integral(eq, func, hint) if hint.startswith("nth_linear_euler_eq_nonhomogeneous"): eq = simplify(eq) if not isinstance(eq, Equality): raise TypeError("eq should be an instance of Equality") # Second, clean up the arbitrary constants. # Right now, nth linear hints can put as many as 2*order constants in an # expression. If that number grows with another hint, the third argument # here should be raised accordingly, or constantsimp() rewritten to handle # an arbitrary number of constants. eq = constantsimp(eq, constants) # Lastly, now that we have cleaned up the expression, try solving for func. # When CRootOf is implemented in solve(), we will want to return a CRootOf # every time instead of an Equality. # Get the f(x) on the left if possible. if eq.rhs == func and not eq.lhs.has(func): eq = [Eq(eq.rhs, eq.lhs)] # make sure we are working with lists of solutions in simplified form. if eq.lhs == func and not eq.rhs.has(func): # The solution is already solved eq = [eq] else: # The solution is not solved, so try to solve it try: floats = any(i.is_Float for i in eq.atoms(Number)) eqsol = solve(eq, func, force=True, rational=False if floats else None) if not eqsol: raise NotImplementedError except (NotImplementedError, PolynomialError): eq = [eq] else: def _expand(expr): numer, denom = expr.as_numer_denom() if denom.is_Add: return expr else: return powsimp(expr.expand(), combine='exp', deep=True) # XXX: the rest of odesimp() expects each ``t`` to be in a # specific normal form: rational expression with numerator # expanded, but with combined exponential functions (at # least in this setup all tests pass). eq = [Eq(f(x), _expand(t)) for t in eqsol] # special simplification of the lhs. if hint.startswith("1st_homogeneous_coeff"): for j, eqi in enumerate(eq): newi = logcombine(eqi, force=True) if isinstance(newi.lhs, log) and newi.rhs == 0: newi = Eq(newi.lhs.args[0]/C1, C1) eq[j] = newi # We cleaned up the constants before solving to help the solve engine with # a simpler expression, but the solved expression could have introduced # things like -C1, so rerun constantsimp() one last time before returning. for i, eqi in enumerate(eq): eq[i] = constantsimp(eqi, constants) eq[i] = constant_renumber(eq[i], ode.free_symbols) # If there is only 1 solution, return it; # otherwise return the list of solutions. if len(eq) == 1: eq = eq[0] return eq def ode_sol_simplicity(sol, func, trysolving=True): r""" Returns an extended integer representing how simple a solution to an ODE is. The following things are considered, in order from most simple to least: - ``sol`` is solved for ``func``. - ``sol`` is not solved for ``func``, but can be if passed to solve (e.g., a solution returned by ``dsolve(ode, func, simplify=False``). - If ``sol`` is not solved for ``func``, then base the result on the length of ``sol``, as computed by ``len(str(sol))``. - If ``sol`` has any unevaluated :py:class:`~sympy.integrals.integrals.Integral`\s, this will automatically be considered less simple than any of the above. This function returns an integer such that if solution A is simpler than solution B by above metric, then ``ode_sol_simplicity(sola, func) < ode_sol_simplicity(solb, func)``. Currently, the following are the numbers returned, but if the heuristic is ever improved, this may change. Only the ordering is guaranteed. +----------------------------------------------+-------------------+ | Simplicity | Return | +==============================================+===================+ | ``sol`` solved for ``func`` | ``-2`` | +----------------------------------------------+-------------------+ | ``sol`` not solved for ``func`` but can be | ``-1`` | +----------------------------------------------+-------------------+ | ``sol`` is not solved nor solvable for | ``len(str(sol))`` | | ``func`` | | +----------------------------------------------+-------------------+ | ``sol`` contains an | ``oo`` | | :obj:`~sympy.integrals.integrals.Integral` | | +----------------------------------------------+-------------------+ ``oo`` here means the SymPy infinity, which should compare greater than any integer. If you already know :py:meth:`~sympy.solvers.solvers.solve` cannot solve ``sol``, you can use ``trysolving=False`` to skip that step, which is the only potentially slow step. For example, :py:meth:`~sympy.solvers.ode.dsolve` with the ``simplify=False`` flag should do this. If ``sol`` is a list of solutions, if the worst solution in the list returns ``oo`` it returns that, otherwise it returns ``len(str(sol))``, that is, the length of the string representation of the whole list. Examples ======== This function is designed to be passed to ``min`` as the key argument, such as ``min(listofsolutions, key=lambda i: ode_sol_simplicity(i, f(x)))``. >>> from sympy import symbols, Function, Eq, tan, Integral >>> from sympy.solvers.ode.ode import ode_sol_simplicity >>> x, C1, C2 = symbols('x, C1, C2') >>> f = Function('f') >>> ode_sol_simplicity(Eq(f(x), C1*x**2), f(x)) -2 >>> ode_sol_simplicity(Eq(x**2 + f(x), C1), f(x)) -1 >>> ode_sol_simplicity(Eq(f(x), C1*Integral(2*x, x)), f(x)) oo >>> eq1 = Eq(f(x)/tan(f(x)/(2*x)), C1) >>> eq2 = Eq(f(x)/tan(f(x)/(2*x) + f(x)), C2) >>> [ode_sol_simplicity(eq, f(x)) for eq in [eq1, eq2]] [28, 35] >>> min([eq1, eq2], key=lambda i: ode_sol_simplicity(i, f(x))) Eq(f(x)/tan(f(x)/(2*x)), C1) """ # TODO: if two solutions are solved for f(x), we still want to be # able to get the simpler of the two # See the docstring for the coercion rules. We check easier (faster) # things here first, to save time. if iterable(sol): # See if there are Integrals for i in sol: if ode_sol_simplicity(i, func, trysolving=trysolving) == oo: return oo return len(str(sol)) if sol.has(Integral): return oo # Next, try to solve for func. This code will change slightly when CRootOf # is implemented in solve(). Probably a CRootOf solution should fall # somewhere between a normal solution and an unsolvable expression. # First, see if they are already solved if sol.lhs == func and not sol.rhs.has(func) or \ sol.rhs == func and not sol.lhs.has(func): return -2 # We are not so lucky, try solving manually if trysolving: try: sols = solve(sol, func) if not sols: raise NotImplementedError except NotImplementedError: pass else: return -1 # Finally, a naive computation based on the length of the string version # of the expression. This may favor combined fractions because they # will not have duplicate denominators, and may slightly favor expressions # with fewer additions and subtractions, as those are separated by spaces # by the printer. # Additional ideas for simplicity heuristics are welcome, like maybe # checking if a equation has a larger domain, or if constantsimp has # introduced arbitrary constants numbered higher than the order of a # given ODE that sol is a solution of. return len(str(sol)) def _extract_funcs(eqs): funcs = [] for eq in eqs: derivs = [node for node in preorder_traversal(eq) if isinstance(node, Derivative)] func = [] for d in derivs: func += list(d.atoms(AppliedUndef)) for func_ in func: funcs.append(func_) funcs = list(uniq(funcs)) return funcs def _get_constant_subexpressions(expr, Cs): Cs = set(Cs) Ces = [] def _recursive_walk(expr): expr_syms = expr.free_symbols if expr_syms and expr_syms.issubset(Cs): Ces.append(expr) else: if expr.func == exp: expr = expr.expand(mul=True) if expr.func in (Add, Mul): d = sift(expr.args, lambda i : i.free_symbols.issubset(Cs)) if len(d[True]) > 1: x = expr.func(*d[True]) if not x.is_number: Ces.append(x) elif isinstance(expr, Integral): if expr.free_symbols.issubset(Cs) and \ all(len(x) == 3 for x in expr.limits): Ces.append(expr) for i in expr.args: _recursive_walk(i) return _recursive_walk(expr) return Ces def __remove_linear_redundancies(expr, Cs): cnts = {i: expr.count(i) for i in Cs} Cs = [i for i in Cs if cnts[i] > 0] def _linear(expr): if isinstance(expr, Add): xs = [i for i in Cs if expr.count(i)==cnts[i] \ and 0 == expr.diff(i, 2)] d = {} for x in xs: y = expr.diff(x) if y not in d: d[y]=[] d[y].append(x) for y in d: if len(d[y]) > 1: d[y].sort(key=str) for x in d[y][1:]: expr = expr.subs(x, 0) return expr def _recursive_walk(expr): if len(expr.args) != 0: expr = expr.func(*[_recursive_walk(i) for i in expr.args]) expr = _linear(expr) return expr if isinstance(expr, Equality): lhs, rhs = [_recursive_walk(i) for i in expr.args] f = lambda i: isinstance(i, Number) or i in Cs if isinstance(lhs, Symbol) and lhs in Cs: rhs, lhs = lhs, rhs if lhs.func in (Add, Symbol) and rhs.func in (Add, Symbol): dlhs = sift([lhs] if isinstance(lhs, AtomicExpr) else lhs.args, f) drhs = sift([rhs] if isinstance(rhs, AtomicExpr) else rhs.args, f) for i in [True, False]: for hs in [dlhs, drhs]: if i not in hs: hs[i] = [0] # this calculation can be simplified lhs = Add(*dlhs[False]) - Add(*drhs[False]) rhs = Add(*drhs[True]) - Add(*dlhs[True]) elif lhs.func in (Mul, Symbol) and rhs.func in (Mul, Symbol): dlhs = sift([lhs] if isinstance(lhs, AtomicExpr) else lhs.args, f) if True in dlhs: if False not in dlhs: dlhs[False] = [1] lhs = Mul(*dlhs[False]) rhs = rhs/Mul(*dlhs[True]) return Eq(lhs, rhs) else: return _recursive_walk(expr) @vectorize(0) def constantsimp(expr, constants): r""" Simplifies an expression with arbitrary constants in it. This function is written specifically to work with :py:meth:`~sympy.solvers.ode.dsolve`, and is not intended for general use. Simplification is done by "absorbing" the arbitrary constants into other arbitrary constants, numbers, and symbols that they are not independent of. The symbols must all have the same name with numbers after it, for example, ``C1``, ``C2``, ``C3``. The ``symbolname`` here would be '``C``', the ``startnumber`` would be 1, and the ``endnumber`` would be 3. If the arbitrary constants are independent of the variable ``x``, then the independent symbol would be ``x``. There is no need to specify the dependent function, such as ``f(x)``, because it already has the independent symbol, ``x``, in it. Because terms are "absorbed" into arbitrary constants and because constants are renumbered after simplifying, the arbitrary constants in expr are not necessarily equal to the ones of the same name in the returned result. If two or more arbitrary constants are added, multiplied, or raised to the power of each other, they are first absorbed together into a single arbitrary constant. Then the new constant is combined into other terms if necessary. Absorption of constants is done with limited assistance: 1. terms of :py:class:`~sympy.core.add.Add`\s are collected to try join constants so `e^x (C_1 \cos(x) + C_2 \cos(x))` will simplify to `e^x C_1 \cos(x)`; 2. powers with exponents that are :py:class:`~sympy.core.add.Add`\s are expanded so `e^{C_1 + x}` will be simplified to `C_1 e^x`. Use :py:meth:`~sympy.solvers.ode.ode.constant_renumber` to renumber constants after simplification or else arbitrary numbers on constants may appear, e.g. `C_1 + C_3 x`. In rare cases, a single constant can be "simplified" into two constants. Every differential equation solution should have as many arbitrary constants as the order of the differential equation. The result here will be technically correct, but it may, for example, have `C_1` and `C_2` in an expression, when `C_1` is actually equal to `C_2`. Use your discretion in such situations, and also take advantage of the ability to use hints in :py:meth:`~sympy.solvers.ode.dsolve`. Examples ======== >>> from sympy import symbols >>> from sympy.solvers.ode.ode import constantsimp >>> C1, C2, C3, x, y = symbols('C1, C2, C3, x, y') >>> constantsimp(2*C1*x, {C1, C2, C3}) C1*x >>> constantsimp(C1 + 2 + x, {C1, C2, C3}) C1 + x >>> constantsimp(C1*C2 + 2 + C2 + C3*x, {C1, C2, C3}) C1 + C3*x """ # This function works recursively. The idea is that, for Mul, # Add, Pow, and Function, if the class has a constant in it, then # we can simplify it, which we do by recursing down and # simplifying up. Otherwise, we can skip that part of the # expression. Cs = constants orig_expr = expr constant_subexprs = _get_constant_subexpressions(expr, Cs) for xe in constant_subexprs: xes = list(xe.free_symbols) if not xes: continue if all(expr.count(c) == xe.count(c) for c in xes): xes.sort(key=str) expr = expr.subs(xe, xes[0]) # try to perform common sub-expression elimination of constant terms try: commons, rexpr = cse(expr) commons.reverse() rexpr = rexpr[0] for s in commons: cs = list(s[1].atoms(Symbol)) if len(cs) == 1 and cs[0] in Cs and \ cs[0] not in rexpr.atoms(Symbol) and \ not any(cs[0] in ex for ex in commons if ex != s): rexpr = rexpr.subs(s[0], cs[0]) else: rexpr = rexpr.subs(*s) expr = rexpr except IndexError: pass expr = __remove_linear_redundancies(expr, Cs) def _conditional_term_factoring(expr): new_expr = terms_gcd(expr, clear=False, deep=True, expand=False) # we do not want to factor exponentials, so handle this separately if new_expr.is_Mul: infac = False asfac = False for m in new_expr.args: if isinstance(m, exp): asfac = True elif m.is_Add: infac = any(isinstance(fi, exp) for t in m.args for fi in Mul.make_args(t)) if asfac and infac: new_expr = expr break return new_expr expr = _conditional_term_factoring(expr) # call recursively if more simplification is possible if orig_expr != expr: return constantsimp(expr, Cs) return expr def constant_renumber(expr, variables=None, newconstants=None): r""" Renumber arbitrary constants in ``expr`` to use the symbol names as given in ``newconstants``. In the process, this reorders expression terms in a standard way. If ``newconstants`` is not provided then the new constant names will be ``C1``, ``C2`` etc. Otherwise ``newconstants`` should be an iterable giving the new symbols to use for the constants in order. The ``variables`` argument is a list of non-constant symbols. All other free symbols found in ``expr`` are assumed to be constants and will be renumbered. If ``variables`` is not given then any numbered symbol beginning with ``C`` (e.g. ``C1``) is assumed to be a constant. Symbols are renumbered based on ``.sort_key()``, so they should be numbered roughly in the order that they appear in the final, printed expression. Note that this ordering is based in part on hashes, so it can produce different results on different machines. The structure of this function is very similar to that of :py:meth:`~sympy.solvers.ode.constantsimp`. Examples ======== >>> from sympy import symbols >>> from sympy.solvers.ode.ode import constant_renumber >>> x, C1, C2, C3 = symbols('x,C1:4') >>> expr = C3 + C2*x + C1*x**2 >>> expr C1*x**2 + C2*x + C3 >>> constant_renumber(expr) C1 + C2*x + C3*x**2 The ``variables`` argument specifies which are constants so that the other symbols will not be renumbered: >>> constant_renumber(expr, [C1, x]) C1*x**2 + C2 + C3*x The ``newconstants`` argument is used to specify what symbols to use when replacing the constants: >>> constant_renumber(expr, [x], newconstants=symbols('E1:4')) E1 + E2*x + E3*x**2 """ # System of expressions if isinstance(expr, (set, list, tuple)): return type(expr)(constant_renumber(Tuple(*expr), variables=variables, newconstants=newconstants)) # Symbols in solution but not ODE are constants if variables is not None: variables = set(variables) free_symbols = expr.free_symbols constantsymbols = list(free_symbols - variables) # Any Cn is a constant... else: variables = set() isconstant = lambda s: s.startswith('C') and s[1:].isdigit() constantsymbols = [sym for sym in expr.free_symbols if isconstant(sym.name)] # Find new constants checking that they aren't already in the ODE if newconstants is None: iter_constants = numbered_symbols(start=1, prefix='C', exclude=variables) else: iter_constants = (sym for sym in newconstants if sym not in variables) constants_found = [] # make a mapping to send all constantsymbols to S.One and use # that to make sure that term ordering is not dependent on # the indexed value of C C_1 = [(ci, S.One) for ci in constantsymbols] sort_key=lambda arg: default_sort_key(arg.subs(C_1)) def _constant_renumber(expr): r""" We need to have an internal recursive function """ # For system of expressions if isinstance(expr, Tuple): renumbered = [_constant_renumber(e) for e in expr] return Tuple(*renumbered) if isinstance(expr, Equality): return Eq( _constant_renumber(expr.lhs), _constant_renumber(expr.rhs)) if type(expr) not in (Mul, Add, Pow) and not expr.is_Function and \ not expr.has(*constantsymbols): # Base case, as above. Hope there aren't constants inside # of some other class, because they won't be renumbered. return expr elif expr.is_Piecewise: return expr elif expr in constantsymbols: if expr not in constants_found: constants_found.append(expr) return expr elif expr.is_Function or expr.is_Pow: return expr.func( *[_constant_renumber(x) for x in expr.args]) else: sortedargs = list(expr.args) sortedargs.sort(key=sort_key) return expr.func(*[_constant_renumber(x) for x in sortedargs]) expr = _constant_renumber(expr) # Don't renumber symbols present in the ODE. constants_found = [c for c in constants_found if c not in variables] # Renumbering happens here subs_dict = {var: cons for var, cons in zip(constants_found, iter_constants)} expr = expr.subs(subs_dict, simultaneous=True) return expr def _handle_Integral(expr, func, hint): r""" Converts a solution with Integrals in it into an actual solution. For most hints, this simply runs ``expr.doit()``. """ if hint == "nth_linear_constant_coeff_homogeneous": sol = expr elif not hint.endswith("_Integral"): sol = expr.doit() else: sol = expr return sol # XXX: Should this function maybe go somewhere else? def homogeneous_order(eq, *symbols): r""" Returns the order `n` if `g` is homogeneous and ``None`` if it is not homogeneous. Determines if a function is homogeneous and if so of what order. A function `f(x, y, \cdots)` is homogeneous of order `n` if `f(t x, t y, \cdots) = t^n f(x, y, \cdots)`. If the function is of two variables, `F(x, y)`, then `f` being homogeneous of any order is equivalent to being able to rewrite `F(x, y)` as `G(x/y)` or `H(y/x)`. This fact is used to solve 1st order ordinary differential equations whose coefficients are homogeneous of the same order (see the docstrings of :obj:`~sympy.solvers.ode.single.HomogeneousCoeffSubsDepDivIndep` and :obj:`~sympy.solvers.ode.single.HomogeneousCoeffSubsIndepDivDep`). Symbols can be functions, but every argument of the function must be a symbol, and the arguments of the function that appear in the expression must match those given in the list of symbols. If a declared function appears with different arguments than given in the list of symbols, ``None`` is returned. Examples ======== >>> from sympy import Function, homogeneous_order, sqrt >>> from sympy.abc import x, y >>> f = Function('f') >>> homogeneous_order(f(x), f(x)) is None True >>> homogeneous_order(f(x,y), f(y, x), x, y) is None True >>> homogeneous_order(f(x), f(x), x) 1 >>> homogeneous_order(x**2*f(x)/sqrt(x**2+f(x)**2), x, f(x)) 2 >>> homogeneous_order(x**2+f(x), x, f(x)) is None True """ if not symbols: raise ValueError("homogeneous_order: no symbols were given.") symset = set(symbols) eq = sympify(eq) # The following are not supported if eq.has(Order, Derivative): return None # These are all constants if (eq.is_Number or eq.is_NumberSymbol or eq.is_number ): return S.Zero # Replace all functions with dummy variables dum = numbered_symbols(prefix='d', cls=Dummy) newsyms = set() for i in [j for j in symset if getattr(j, 'is_Function')]: iargs = set(i.args) if iargs.difference(symset): return None else: dummyvar = next(dum) eq = eq.subs(i, dummyvar) symset.remove(i) newsyms.add(dummyvar) symset.update(newsyms) if not eq.free_symbols & symset: return None # assuming order of a nested function can only be equal to zero if isinstance(eq, Function): return None if homogeneous_order( eq.args[0], *tuple(symset)) != 0 else S.Zero # make the replacement of x with x*t and see if t can be factored out t = Dummy('t', positive=True) # It is sufficient that t > 0 eqs = separatevars(eq.subs([(i, t*i) for i in symset]), [t], dict=True)[t] if eqs is S.One: return S.Zero # there was no term with only t i, d = eqs.as_independent(t, as_Add=False) b, e = d.as_base_exp() if b == t: return e def ode_2nd_power_series_ordinary(eq, func, order, match): r""" Gives a power series solution to a second order homogeneous differential equation with polynomial coefficients at an ordinary point. A homogeneous differential equation is of the form .. math :: P(x)\frac{d^2y}{dx^2} + Q(x)\frac{dy}{dx} + R(x) y(x) = 0 For simplicity it is assumed that `P(x)`, `Q(x)` and `R(x)` are polynomials, it is sufficient that `\frac{Q(x)}{P(x)}` and `\frac{R(x)}{P(x)}` exists at `x_{0}`. A recurrence relation is obtained by substituting `y` as `\sum_{n=0}^\infty a_{n}x^{n}`, in the differential equation, and equating the nth term. Using this relation various terms can be generated. Examples ======== >>> from sympy import dsolve, Function, pprint >>> from sympy.abc import x >>> f = Function("f") >>> eq = f(x).diff(x, 2) + f(x) >>> pprint(dsolve(eq, hint='2nd_power_series_ordinary')) / 4 2 \ / 2\ |x x | | x | / 6\ f(x) = C2*|-- - -- + 1| + C1*x*|1 - --| + O\x / \24 2 / \ 6 / References ========== - http://tutorial.math.lamar.edu/Classes/DE/SeriesSolutions.aspx - George E. Simmons, "Differential Equations with Applications and Historical Notes", p.p 176 - 184 """ x = func.args[0] f = func.func C0, C1 = get_numbered_constants(eq, num=2) n = Dummy("n", integer=True) s = Wild("s") k = Wild("k", exclude=[x]) x0 = match['x0'] terms = match['terms'] p = match[match['a3']] q = match[match['b3']] r = match[match['c3']] seriesdict = {} recurr = Function("r") # Generating the recurrence relation which works this way: # for the second order term the summation begins at n = 2. The coefficients # p is multiplied with an*(n - 1)*(n - 2)*x**n-2 and a substitution is made such that # the exponent of x becomes n. # For example, if p is x, then the second degree recurrence term is # an*(n - 1)*(n - 2)*x**n-1, substituting (n - 1) as n, it transforms to # an+1*n*(n - 1)*x**n. # A similar process is done with the first order and zeroth order term. coefflist = [(recurr(n), r), (n*recurr(n), q), (n*(n - 1)*recurr(n), p)] for index, coeff in enumerate(coefflist): if coeff[1]: f2 = powsimp(expand((coeff[1]*(x - x0)**(n - index)).subs(x, x + x0))) if f2.is_Add: addargs = f2.args else: addargs = [f2] for arg in addargs: powm = arg.match(s*x**k) term = coeff[0]*powm[s] if not powm[k].is_Symbol: term = term.subs(n, n - powm[k].as_independent(n)[0]) startind = powm[k].subs(n, index) # Seeing if the startterm can be reduced further. # If it vanishes for n lesser than startind, it is # equal to summation from n. if startind: for i in reversed(range(startind)): if not term.subs(n, i): seriesdict[term] = i else: seriesdict[term] = i + 1 break else: seriesdict[term] = S.Zero # Stripping of terms so that the sum starts with the same number. teq = S.Zero suminit = seriesdict.values() rkeys = seriesdict.keys() req = Add(*rkeys) if any(suminit): maxval = max(suminit) for term in seriesdict: val = seriesdict[term] if val != maxval: for i in range(val, maxval): teq += term.subs(n, val) finaldict = {} if teq: fargs = teq.atoms(AppliedUndef) if len(fargs) == 1: finaldict[fargs.pop()] = 0 else: maxf = max(fargs, key = lambda x: x.args[0]) sol = solve(teq, maxf) if isinstance(sol, list): sol = sol[0] finaldict[maxf] = sol # Finding the recurrence relation in terms of the largest term. fargs = req.atoms(AppliedUndef) maxf = max(fargs, key = lambda x: x.args[0]) minf = min(fargs, key = lambda x: x.args[0]) if minf.args[0].is_Symbol: startiter = 0 else: startiter = -minf.args[0].as_independent(n)[0] lhs = maxf rhs = solve(req, maxf) if isinstance(rhs, list): rhs = rhs[0] # Checking how many values are already present tcounter = len([t for t in finaldict.values() if t]) for _ in range(tcounter, terms - 3): # Assuming c0 and c1 to be arbitrary check = rhs.subs(n, startiter) nlhs = lhs.subs(n, startiter) nrhs = check.subs(finaldict) finaldict[nlhs] = nrhs startiter += 1 # Post processing series = C0 + C1*(x - x0) for term in finaldict: if finaldict[term]: fact = term.args[0] series += (finaldict[term].subs([(recurr(0), C0), (recurr(1), C1)])*( x - x0)**fact) series = collect(expand_mul(series), [C0, C1]) + Order(x**terms) return Eq(f(x), series) def ode_2nd_power_series_regular(eq, func, order, match): r""" Gives a power series solution to a second order homogeneous differential equation with polynomial coefficients at a regular point. A second order homogeneous differential equation is of the form .. math :: P(x)\frac{d^2y}{dx^2} + Q(x)\frac{dy}{dx} + R(x) y(x) = 0 A point is said to regular singular at `x0` if `x - x0\frac{Q(x)}{P(x)}` and `(x - x0)^{2}\frac{R(x)}{P(x)}` are analytic at `x0`. For simplicity `P(x)`, `Q(x)` and `R(x)` are assumed to be polynomials. The algorithm for finding the power series solutions is: 1. Try expressing `(x - x0)P(x)` and `((x - x0)^{2})Q(x)` as power series solutions about x0. Find `p0` and `q0` which are the constants of the power series expansions. 2. Solve the indicial equation `f(m) = m(m - 1) + m*p0 + q0`, to obtain the roots `m1` and `m2` of the indicial equation. 3. If `m1 - m2` is a non integer there exists two series solutions. If `m1 = m2`, there exists only one solution. If `m1 - m2` is an integer, then the existence of one solution is confirmed. The other solution may or may not exist. The power series solution is of the form `x^{m}\sum_{n=0}^\infty a_{n}x^{n}`. The coefficients are determined by the following recurrence relation. `a_{n} = -\frac{\sum_{k=0}^{n-1} q_{n-k} + (m + k)p_{n-k}}{f(m + n)}`. For the case in which `m1 - m2` is an integer, it can be seen from the recurrence relation that for the lower root `m`, when `n` equals the difference of both the roots, the denominator becomes zero. So if the numerator is not equal to zero, a second series solution exists. Examples ======== >>> from sympy import dsolve, Function, pprint >>> from sympy.abc import x >>> f = Function("f") >>> eq = x*(f(x).diff(x, 2)) + 2*(f(x).diff(x)) + x*f(x) >>> pprint(dsolve(eq, hint='2nd_power_series_regular')) / 6 4 2 \ | x x x | / 4 2 \ C1*|- --- + -- - -- + 1| | x x | \ 720 24 2 / / 6\ f(x) = C2*|--- - -- + 1| + ------------------------ + O\x / \120 6 / x References ========== - George E. Simmons, "Differential Equations with Applications and Historical Notes", p.p 176 - 184 """ x = func.args[0] f = func.func C0, C1 = get_numbered_constants(eq, num=2) m = Dummy("m") # for solving the indicial equation x0 = match['x0'] terms = match['terms'] p = match['p'] q = match['q'] # Generating the indicial equation indicial = [] for term in [p, q]: if not term.has(x): indicial.append(term) else: term = series(term, x=x, n=1, x0=x0) if isinstance(term, Order): indicial.append(S.Zero) else: for arg in term.args: if not arg.has(x): indicial.append(arg) break p0, q0 = indicial sollist = solve(m*(m - 1) + m*p0 + q0, m) if sollist and isinstance(sollist, list) and all( sol.is_real for sol in sollist): serdict1 = {} serdict2 = {} if len(sollist) == 1: # Only one series solution exists in this case. m1 = m2 = sollist.pop() if terms-m1-1 <= 0: return Eq(f(x), Order(terms)) serdict1 = _frobenius(terms-m1-1, m1, p0, q0, p, q, x0, x, C0) else: m1 = sollist[0] m2 = sollist[1] if m1 < m2: m1, m2 = m2, m1 # Irrespective of whether m1 - m2 is an integer or not, one # Frobenius series solution exists. serdict1 = _frobenius(terms-m1-1, m1, p0, q0, p, q, x0, x, C0) if not (m1 - m2).is_integer: # Second frobenius series solution exists. serdict2 = _frobenius(terms-m2-1, m2, p0, q0, p, q, x0, x, C1) else: # Check if second frobenius series solution exists. serdict2 = _frobenius(terms-m2-1, m2, p0, q0, p, q, x0, x, C1, check=m1) if serdict1: finalseries1 = C0 for key in serdict1: power = int(key.name[1:]) finalseries1 += serdict1[key]*(x - x0)**power finalseries1 = (x - x0)**m1*finalseries1 finalseries2 = S.Zero if serdict2: for key in serdict2: power = int(key.name[1:]) finalseries2 += serdict2[key]*(x - x0)**power finalseries2 += C1 finalseries2 = (x - x0)**m2*finalseries2 return Eq(f(x), collect(finalseries1 + finalseries2, [C0, C1]) + Order(x**terms)) def _frobenius(n, m, p0, q0, p, q, x0, x, c, check=None): r""" Returns a dict with keys as coefficients and values as their values in terms of C0 """ n = int(n) # In cases where m1 - m2 is not an integer m2 = check d = Dummy("d") numsyms = numbered_symbols("C", start=0) numsyms = [next(numsyms) for i in range(n + 1)] serlist = [] for ser in [p, q]: # Order term not present if ser.is_polynomial(x) and Poly(ser, x).degree() <= n: if x0: ser = ser.subs(x, x + x0) dict_ = Poly(ser, x).as_dict() # Order term present else: tseries = series(ser, x=x0, n=n+1) # Removing order dict_ = Poly(list(ordered(tseries.args))[: -1], x).as_dict() # Fill in with zeros, if coefficients are zero. for i in range(n + 1): if (i,) not in dict_: dict_[(i,)] = S.Zero serlist.append(dict_) pseries = serlist[0] qseries = serlist[1] indicial = d*(d - 1) + d*p0 + q0 frobdict = {} for i in range(1, n + 1): num = c*(m*pseries[(i,)] + qseries[(i,)]) for j in range(1, i): sym = Symbol("C" + str(j)) num += frobdict[sym]*((m + j)*pseries[(i - j,)] + qseries[(i - j,)]) # Checking for cases when m1 - m2 is an integer. If num equals zero # then a second Frobenius series solution cannot be found. If num is not zero # then set constant as zero and proceed. if m2 is not None and i == m2 - m: if num: return False else: frobdict[numsyms[i]] = S.Zero else: frobdict[numsyms[i]] = -num/(indicial.subs(d, m+i)) return frobdict def _remove_redundant_solutions(eq, solns, order, var): r""" Remove redundant solutions from the set of solutions. This function is needed because otherwise dsolve can return redundant solutions. As an example consider: eq = Eq((f(x).diff(x, 2))*f(x).diff(x), 0) There are two ways to find solutions to eq. The first is to solve f(x).diff(x, 2) = 0 leading to solution f(x)=C1 + C2*x. The second is to solve the equation f(x).diff(x) = 0 leading to the solution f(x) = C1. In this particular case we then see that the second solution is a special case of the first and we do not want to return it. This does not always happen. If we have eq = Eq((f(x)**2-4)*(f(x).diff(x)-4), 0) then we get the algebraic solution f(x) = [-2, 2] and the integral solution f(x) = x + C1 and in this case the two solutions are not equivalent wrt initial conditions so both should be returned. """ def is_special_case_of(soln1, soln2): return _is_special_case_of(soln1, soln2, eq, order, var) unique_solns = [] for soln1 in solns: for soln2 in unique_solns[:]: if is_special_case_of(soln1, soln2): break elif is_special_case_of(soln2, soln1): unique_solns.remove(soln2) else: unique_solns.append(soln1) return unique_solns def _is_special_case_of(soln1, soln2, eq, order, var): r""" True if soln1 is found to be a special case of soln2 wrt some value of the constants that appear in soln2. False otherwise. """ # The solutions returned by dsolve may be given explicitly or implicitly. # We will equate the sol1=(soln1.rhs - soln1.lhs), sol2=(soln2.rhs - soln2.lhs) # of the two solutions. # # Since this is supposed to hold for all x it also holds for derivatives. # For an order n ode we should be able to differentiate # each solution n times to get n+1 equations. # # We then try to solve those n+1 equations for the integrations constants # in sol2. If we can find a solution that does not depend on x then it # means that some value of the constants in sol1 is a special case of # sol2 corresponding to a particular choice of the integration constants. # In case the solution is in implicit form we subtract the sides soln1 = soln1.rhs - soln1.lhs soln2 = soln2.rhs - soln2.lhs # Work for the series solution if soln1.has(Order) and soln2.has(Order): if soln1.getO() == soln2.getO(): soln1 = soln1.removeO() soln2 = soln2.removeO() else: return False elif soln1.has(Order) or soln2.has(Order): return False constants1 = soln1.free_symbols.difference(eq.free_symbols) constants2 = soln2.free_symbols.difference(eq.free_symbols) constants1_new = get_numbered_constants(Tuple(soln1, soln2), len(constants1)) if len(constants1) == 1: constants1_new = {constants1_new} for c_old, c_new in zip(constants1, constants1_new): soln1 = soln1.subs(c_old, c_new) # n equations for sol1 = sol2, sol1'=sol2', ... lhs = soln1 rhs = soln2 eqns = [Eq(lhs, rhs)] for n in range(1, order): lhs = lhs.diff(var) rhs = rhs.diff(var) eq = Eq(lhs, rhs) eqns.append(eq) # BooleanTrue/False awkwardly show up for trivial equations if any(isinstance(eq, BooleanFalse) for eq in eqns): return False eqns = [eq for eq in eqns if not isinstance(eq, BooleanTrue)] try: constant_solns = solve(eqns, constants2) except NotImplementedError: return False # Sometimes returns a dict and sometimes a list of dicts if isinstance(constant_solns, dict): constant_solns = [constant_solns] # after solving the issue 17418, maybe we don't need the following checksol code. for constant_soln in constant_solns: for eq in eqns: eq=eq.rhs-eq.lhs if checksol(eq, constant_soln) is not True: return False # If any solution gives all constants as expressions that don't depend on # x then there exists constants for soln2 that give soln1 for constant_soln in constant_solns: if not any(c.has(var) for c in constant_soln.values()): return True return False def ode_1st_power_series(eq, func, order, match): r""" The power series solution is a method which gives the Taylor series expansion to the solution of a differential equation. For a first order differential equation `\frac{dy}{dx} = h(x, y)`, a power series solution exists at a point `x = x_{0}` if `h(x, y)` is analytic at `x_{0}`. The solution is given by .. math:: y(x) = y(x_{0}) + \sum_{n = 1}^{\infty} \frac{F_{n}(x_{0},b)(x - x_{0})^n}{n!}, where `y(x_{0}) = b` is the value of y at the initial value of `x_{0}`. To compute the values of the `F_{n}(x_{0},b)` the following algorithm is followed, until the required number of terms are generated. 1. `F_1 = h(x_{0}, b)` 2. `F_{n+1} = \frac{\partial F_{n}}{\partial x} + \frac{\partial F_{n}}{\partial y}F_{1}` Examples ======== >>> from sympy import Function, pprint, exp, dsolve >>> from sympy.abc import x >>> f = Function('f') >>> eq = exp(x)*(f(x).diff(x)) - f(x) >>> pprint(dsolve(eq, hint='1st_power_series')) 3 4 5 C1*x C1*x C1*x / 6\ f(x) = C1 + C1*x - ----- + ----- + ----- + O\x / 6 24 60 References ========== - Travis W. Walker, Analytic power series technique for solving first-order differential equations, p.p 17, 18 """ x = func.args[0] y = match['y'] f = func.func h = -match[match['d']]/match[match['e']] point = match['f0'] value = match['f0val'] terms = match['terms'] # First term F = h if not h: return Eq(f(x), value) # Initialization series = value if terms > 1: hc = h.subs({x: point, y: value}) if hc.has(oo) or hc.has(nan) or hc.has(zoo): # Derivative does not exist, not analytic return Eq(f(x), oo) elif hc: series += hc*(x - point) for factcount in range(2, terms): Fnew = F.diff(x) + F.diff(y)*h Fnewc = Fnew.subs({x: point, y: value}) # Same logic as above if Fnewc.has(oo) or Fnewc.has(nan) or Fnewc.has(-oo) or Fnewc.has(zoo): return Eq(f(x), oo) series += Fnewc*((x - point)**factcount)/factorial(factcount) F = Fnew series += Order(x**terms) return Eq(f(x), series) def checkinfsol(eq, infinitesimals, func=None, order=None): r""" This function is used to check if the given infinitesimals are the actual infinitesimals of the given first order differential equation. This method is specific to the Lie Group Solver of ODEs. As of now, it simply checks, by substituting the infinitesimals in the partial differential equation. .. math:: \frac{\partial \eta}{\partial x} + \left(\frac{\partial \eta}{\partial y} - \frac{\partial \xi}{\partial x}\right)*h - \frac{\partial \xi}{\partial y}*h^{2} - \xi\frac{\partial h}{\partial x} - \eta\frac{\partial h}{\partial y} = 0 where `\eta`, and `\xi` are the infinitesimals and `h(x,y) = \frac{dy}{dx}` The infinitesimals should be given in the form of a list of dicts ``[{xi(x, y): inf, eta(x, y): inf}]``, corresponding to the output of the function infinitesimals. It returns a list of values of the form ``[(True/False, sol)]`` where ``sol`` is the value obtained after substituting the infinitesimals in the PDE. If it is ``True``, then ``sol`` would be 0. """ if isinstance(eq, Equality): eq = eq.lhs - eq.rhs if not func: eq, func = _preprocess(eq) variables = func.args if len(variables) != 1: raise ValueError("ODE's have only one independent variable") else: x = variables[0] if not order: order = ode_order(eq, func) if order != 1: raise NotImplementedError("Lie groups solver has been implemented " "only for first order differential equations") else: df = func.diff(x) a = Wild('a', exclude = [df]) b = Wild('b', exclude = [df]) match = collect(expand(eq), df).match(a*df + b) if match: h = -simplify(match[b]/match[a]) else: try: sol = solve(eq, df) except NotImplementedError: raise NotImplementedError("Infinitesimals for the " "first order ODE could not be found") else: h = sol[0] # Find infinitesimals for one solution y = Dummy('y') h = h.subs(func, y) xi = Function('xi')(x, y) eta = Function('eta')(x, y) dxi = Function('xi')(x, func) deta = Function('eta')(x, func) pde = (eta.diff(x) + (eta.diff(y) - xi.diff(x))*h - (xi.diff(y))*h**2 - xi*(h.diff(x)) - eta*(h.diff(y))) soltup = [] for sol in infinitesimals: tsol = {xi: S(sol[dxi]).subs(func, y), eta: S(sol[deta]).subs(func, y)} sol = simplify(pde.subs(tsol).doit()) if sol: soltup.append((False, sol.subs(y, func))) else: soltup.append((True, 0)) return soltup def sysode_linear_2eq_order1(match_): x = match_['func'][0].func y = match_['func'][1].func func = match_['func'] fc = match_['func_coeff'] eq = match_['eq'] r = dict() t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0] for i in range(2): eqs = 0 for terms in Add.make_args(eq[i]): eqs += terms/fc[i,func[i],1] eq[i] = eqs # for equations Eq(a1*diff(x(t),t), a*x(t) + b*y(t) + k1) # and Eq(a2*diff(x(t),t), c*x(t) + d*y(t) + k2) r['a'] = -fc[0,x(t),0]/fc[0,x(t),1] r['c'] = -fc[1,x(t),0]/fc[1,y(t),1] r['b'] = -fc[0,y(t),0]/fc[0,x(t),1] r['d'] = -fc[1,y(t),0]/fc[1,y(t),1] forcing = [S.Zero,S.Zero] for i in range(2): for j in Add.make_args(eq[i]): if not j.has(x(t), y(t)): forcing[i] += j if not (forcing[0].has(t) or forcing[1].has(t)): r['k1'] = forcing[0] r['k2'] = forcing[1] else: raise NotImplementedError("Only homogeneous problems are supported" + " (and constant inhomogeneity)") if match_['type_of_equation'] == 'type6': sol = _linear_2eq_order1_type6(x, y, t, r, eq) if match_['type_of_equation'] == 'type7': sol = _linear_2eq_order1_type7(x, y, t, r, eq) return sol def _linear_2eq_order1_type6(x, y, t, r, eq): r""" The equations of this type of ode are . .. math:: x' = f(t) x + g(t) y .. math:: y' = a [f(t) + a h(t)] x + a [g(t) - h(t)] y This is solved by first multiplying the first equation by `-a` and adding it to the second equation to obtain .. math:: y' - a x' = -a h(t) (y - a x) Setting `U = y - ax` and integrating the equation we arrive at .. math:: y - ax = C_1 e^{-a \int h(t) \,dt} and on substituting the value of y in first equation give rise to first order ODEs. After solving for `x`, we can obtain `y` by substituting the value of `x` in second equation. """ C1, C2, C3, C4 = get_numbered_constants(eq, num=4) p = 0 q = 0 p1 = cancel(r['c']/cancel(r['c']/r['d']).as_numer_denom()[0]) p2 = cancel(r['a']/cancel(r['a']/r['b']).as_numer_denom()[0]) for n, i in enumerate([p1, p2]): for j in Mul.make_args(collect_const(i)): if not j.has(t): q = j if q!=0 and n==0: if ((r['c']/j - r['a'])/(r['b'] - r['d']/j)) == j: p = 1 s = j break if q!=0 and n==1: if ((r['a']/j - r['c'])/(r['d'] - r['b']/j)) == j: p = 2 s = j break if p == 1: equ = diff(x(t),t) - r['a']*x(t) - r['b']*(s*x(t) + C1*exp(-s*Integral(r['b'] - r['d']/s, t))) hint1 = classify_ode(equ)[1] sol1 = dsolve(equ, hint=hint1+'_Integral').rhs sol2 = s*sol1 + C1*exp(-s*Integral(r['b'] - r['d']/s, t)) elif p ==2: equ = diff(y(t),t) - r['c']*y(t) - r['d']*s*y(t) + C1*exp(-s*Integral(r['d'] - r['b']/s, t)) hint1 = classify_ode(equ)[1] sol2 = dsolve(equ, hint=hint1+'_Integral').rhs sol1 = s*sol2 + C1*exp(-s*Integral(r['d'] - r['b']/s, t)) return [Eq(x(t), sol1), Eq(y(t), sol2)] def _linear_2eq_order1_type7(x, y, t, r, eq): r""" The equations of this type of ode are . .. math:: x' = f(t) x + g(t) y .. math:: y' = h(t) x + p(t) y Differentiating the first equation and substituting the value of `y` from second equation will give a second-order linear equation .. math:: g x'' - (fg + gp + g') x' + (fgp - g^{2} h + f g' - f' g) x = 0 This above equation can be easily integrated if following conditions are satisfied. 1. `fgp - g^{2} h + f g' - f' g = 0` 2. `fgp - g^{2} h + f g' - f' g = ag, fg + gp + g' = bg` If first condition is satisfied then it is solved by current dsolve solver and in second case it becomes a constant coefficient differential equation which is also solved by current solver. Otherwise if the above condition fails then, a particular solution is assumed as `x = x_0(t)` and `y = y_0(t)` Then the general solution is expressed as .. math:: x = C_1 x_0(t) + C_2 x_0(t) \int \frac{g(t) F(t) P(t)}{x_0^{2}(t)} \,dt .. math:: y = C_1 y_0(t) + C_2 [\frac{F(t) P(t)}{x_0(t)} + y_0(t) \int \frac{g(t) F(t) P(t)}{x_0^{2}(t)} \,dt] where C1 and C2 are arbitrary constants and .. math:: F(t) = e^{\int f(t) \,dt}, P(t) = e^{\int p(t) \,dt} """ C1, C2, C3, C4 = get_numbered_constants(eq, num=4) e1 = r['a']*r['b']*r['c'] - r['b']**2*r['c'] + r['a']*diff(r['b'],t) - diff(r['a'],t)*r['b'] e2 = r['a']*r['c']*r['d'] - r['b']*r['c']**2 + diff(r['c'],t)*r['d'] - r['c']*diff(r['d'],t) m1 = r['a']*r['b'] + r['b']*r['d'] + diff(r['b'],t) m2 = r['a']*r['c'] + r['c']*r['d'] + diff(r['c'],t) if e1 == 0: sol1 = dsolve(r['b']*diff(x(t),t,t) - m1*diff(x(t),t)).rhs sol2 = dsolve(diff(y(t),t) - r['c']*sol1 - r['d']*y(t)).rhs elif e2 == 0: sol2 = dsolve(r['c']*diff(y(t),t,t) - m2*diff(y(t),t)).rhs sol1 = dsolve(diff(x(t),t) - r['a']*x(t) - r['b']*sol2).rhs elif not (e1/r['b']).has(t) and not (m1/r['b']).has(t): sol1 = dsolve(diff(x(t),t,t) - (m1/r['b'])*diff(x(t),t) - (e1/r['b'])*x(t)).rhs sol2 = dsolve(diff(y(t),t) - r['c']*sol1 - r['d']*y(t)).rhs elif not (e2/r['c']).has(t) and not (m2/r['c']).has(t): sol2 = dsolve(diff(y(t),t,t) - (m2/r['c'])*diff(y(t),t) - (e2/r['c'])*y(t)).rhs sol1 = dsolve(diff(x(t),t) - r['a']*x(t) - r['b']*sol2).rhs else: x0 = Function('x0')(t) # x0 and y0 being particular solutions y0 = Function('y0')(t) F = exp(Integral(r['a'],t)) P = exp(Integral(r['d'],t)) sol1 = C1*x0 + C2*x0*Integral(r['b']*F*P/x0**2, t) sol2 = C1*y0 + C2*(F*P/x0 + y0*Integral(r['b']*F*P/x0**2, t)) return [Eq(x(t), sol1), Eq(y(t), sol2)] def sysode_nonlinear_2eq_order1(match_): func = match_['func'] eq = match_['eq'] fc = match_['func_coeff'] t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0] if match_['type_of_equation'] == 'type5': sol = _nonlinear_2eq_order1_type5(func, t, eq) return sol x = func[0].func y = func[1].func for i in range(2): eqs = 0 for terms in Add.make_args(eq[i]): eqs += terms/fc[i,func[i],1] eq[i] = eqs if match_['type_of_equation'] == 'type1': sol = _nonlinear_2eq_order1_type1(x, y, t, eq) elif match_['type_of_equation'] == 'type2': sol = _nonlinear_2eq_order1_type2(x, y, t, eq) elif match_['type_of_equation'] == 'type3': sol = _nonlinear_2eq_order1_type3(x, y, t, eq) elif match_['type_of_equation'] == 'type4': sol = _nonlinear_2eq_order1_type4(x, y, t, eq) return sol def _nonlinear_2eq_order1_type1(x, y, t, eq): r""" Equations: .. math:: x' = x^n F(x,y) .. math:: y' = g(y) F(x,y) Solution: .. math:: x = \varphi(y), \int \frac{1}{g(y) F(\varphi(y),y)} \,dy = t + C_2 where if `n \neq 1` .. math:: \varphi = [C_1 + (1-n) \int \frac{1}{g(y)} \,dy]^{\frac{1}{1-n}} if `n = 1` .. math:: \varphi = C_1 e^{\int \frac{1}{g(y)} \,dy} where `C_1` and `C_2` are arbitrary constants. """ C1, C2 = get_numbered_constants(eq, num=2) n = Wild('n', exclude=[x(t),y(t)]) f = Wild('f') u, v = symbols('u, v') r = eq[0].match(diff(x(t),t) - x(t)**n*f) g = ((diff(y(t),t) - eq[1])/r[f]).subs(y(t),v) F = r[f].subs(x(t),u).subs(y(t),v) n = r[n] if n!=1: phi = (C1 + (1-n)*Integral(1/g, v))**(1/(1-n)) else: phi = C1*exp(Integral(1/g, v)) phi = phi.doit() sol2 = solve(Integral(1/(g*F.subs(u,phi)), v).doit() - t - C2, v) sol = [] for sols in sol2: sol.append(Eq(x(t),phi.subs(v, sols))) sol.append(Eq(y(t), sols)) return sol def _nonlinear_2eq_order1_type2(x, y, t, eq): r""" Equations: .. math:: x' = e^{\lambda x} F(x,y) .. math:: y' = g(y) F(x,y) Solution: .. math:: x = \varphi(y), \int \frac{1}{g(y) F(\varphi(y),y)} \,dy = t + C_2 where if `\lambda \neq 0` .. math:: \varphi = -\frac{1}{\lambda} log(C_1 - \lambda \int \frac{1}{g(y)} \,dy) if `\lambda = 0` .. math:: \varphi = C_1 + \int \frac{1}{g(y)} \,dy where `C_1` and `C_2` are arbitrary constants. """ C1, C2 = get_numbered_constants(eq, num=2) n = Wild('n', exclude=[x(t),y(t)]) f = Wild('f') u, v = symbols('u, v') r = eq[0].match(diff(x(t),t) - exp(n*x(t))*f) g = ((diff(y(t),t) - eq[1])/r[f]).subs(y(t),v) F = r[f].subs(x(t),u).subs(y(t),v) n = r[n] if n: phi = -1/n*log(C1 - n*Integral(1/g, v)) else: phi = C1 + Integral(1/g, v) phi = phi.doit() sol2 = solve(Integral(1/(g*F.subs(u,phi)), v).doit() - t - C2, v) sol = [] for sols in sol2: sol.append(Eq(x(t),phi.subs(v, sols))) sol.append(Eq(y(t), sols)) return sol def _nonlinear_2eq_order1_type3(x, y, t, eq): r""" Autonomous system of general form .. math:: x' = F(x,y) .. math:: y' = G(x,y) Assuming `y = y(x, C_1)` where `C_1` is an arbitrary constant is the general solution of the first-order equation .. math:: F(x,y) y'_x = G(x,y) Then the general solution of the original system of equations has the form .. math:: \int \frac{1}{F(x,y(x,C_1))} \,dx = t + C_1 """ C1, C2, C3, C4 = get_numbered_constants(eq, num=4) v = Function('v') u = Symbol('u') f = Wild('f') g = Wild('g') r1 = eq[0].match(diff(x(t),t) - f) r2 = eq[1].match(diff(y(t),t) - g) F = r1[f].subs(x(t), u).subs(y(t), v(u)) G = r2[g].subs(x(t), u).subs(y(t), v(u)) sol2r = dsolve(Eq(diff(v(u), u), G/F)) if isinstance(sol2r, Equality): sol2r = [sol2r] for sol2s in sol2r: sol1 = solve(Integral(1/F.subs(v(u), sol2s.rhs), u).doit() - t - C2, u) sol = [] for sols in sol1: sol.append(Eq(x(t), sols)) sol.append(Eq(y(t), (sol2s.rhs).subs(u, sols))) return sol def _nonlinear_2eq_order1_type4(x, y, t, eq): r""" Equation: .. math:: x' = f_1(x) g_1(y) \phi(x,y,t) .. math:: y' = f_2(x) g_2(y) \phi(x,y,t) First integral: .. math:: \int \frac{f_2(x)}{f_1(x)} \,dx - \int \frac{g_1(y)}{g_2(y)} \,dy = C where `C` is an arbitrary constant. On solving the first integral for `x` (resp., `y` ) and on substituting the resulting expression into either equation of the original solution, one arrives at a first-order equation for determining `y` (resp., `x` ). """ C1, C2 = get_numbered_constants(eq, num=2) u, v = symbols('u, v') U, V = symbols('U, V', cls=Function) f = Wild('f') g = Wild('g') f1 = Wild('f1', exclude=[v,t]) f2 = Wild('f2', exclude=[v,t]) g1 = Wild('g1', exclude=[u,t]) g2 = Wild('g2', exclude=[u,t]) r1 = eq[0].match(diff(x(t),t) - f) r2 = eq[1].match(diff(y(t),t) - g) num, den = ( (r1[f].subs(x(t),u).subs(y(t),v))/ (r2[g].subs(x(t),u).subs(y(t),v))).as_numer_denom() R1 = num.match(f1*g1) R2 = den.match(f2*g2) phi = (r1[f].subs(x(t),u).subs(y(t),v))/num F1 = R1[f1]; F2 = R2[f2] G1 = R1[g1]; G2 = R2[g2] sol1r = solve(Integral(F2/F1, u).doit() - Integral(G1/G2,v).doit() - C1, u) sol2r = solve(Integral(F2/F1, u).doit() - Integral(G1/G2,v).doit() - C1, v) sol = [] for sols in sol1r: sol.append(Eq(y(t), dsolve(diff(V(t),t) - F2.subs(u,sols).subs(v,V(t))*G2.subs(v,V(t))*phi.subs(u,sols).subs(v,V(t))).rhs)) for sols in sol2r: sol.append(Eq(x(t), dsolve(diff(U(t),t) - F1.subs(u,U(t))*G1.subs(v,sols).subs(u,U(t))*phi.subs(v,sols).subs(u,U(t))).rhs)) return set(sol) def _nonlinear_2eq_order1_type5(func, t, eq): r""" Clairaut system of ODEs .. math:: x = t x' + F(x',y') .. math:: y = t y' + G(x',y') The following are solutions of the system `(i)` straight lines: .. math:: x = C_1 t + F(C_1, C_2), y = C_2 t + G(C_1, C_2) where `C_1` and `C_2` are arbitrary constants; `(ii)` envelopes of the above lines; `(iii)` continuously differentiable lines made up from segments of the lines `(i)` and `(ii)`. """ C1, C2 = get_numbered_constants(eq, num=2) f = Wild('f') g = Wild('g') def check_type(x, y): r1 = eq[0].match(t*diff(x(t),t) - x(t) + f) r2 = eq[1].match(t*diff(y(t),t) - y(t) + g) if not (r1 and r2): r1 = eq[0].match(diff(x(t),t) - x(t)/t + f/t) r2 = eq[1].match(diff(y(t),t) - y(t)/t + g/t) if not (r1 and r2): r1 = (-eq[0]).match(t*diff(x(t),t) - x(t) + f) r2 = (-eq[1]).match(t*diff(y(t),t) - y(t) + g) if not (r1 and r2): r1 = (-eq[0]).match(diff(x(t),t) - x(t)/t + f/t) r2 = (-eq[1]).match(diff(y(t),t) - y(t)/t + g/t) return [r1, r2] for func_ in func: if isinstance(func_, list): x = func[0][0].func y = func[0][1].func [r1, r2] = check_type(x, y) if not (r1 and r2): [r1, r2] = check_type(y, x) x, y = y, x x1 = diff(x(t),t); y1 = diff(y(t),t) return {Eq(x(t), C1*t + r1[f].subs(x1,C1).subs(y1,C2)), Eq(y(t), C2*t + r2[g].subs(x1,C1).subs(y1,C2))} def sysode_nonlinear_3eq_order1(match_): x = match_['func'][0].func y = match_['func'][1].func z = match_['func'][2].func eq = match_['eq'] t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0] if match_['type_of_equation'] == 'type1': sol = _nonlinear_3eq_order1_type1(x, y, z, t, eq) if match_['type_of_equation'] == 'type2': sol = _nonlinear_3eq_order1_type2(x, y, z, t, eq) if match_['type_of_equation'] == 'type3': sol = _nonlinear_3eq_order1_type3(x, y, z, t, eq) if match_['type_of_equation'] == 'type4': sol = _nonlinear_3eq_order1_type4(x, y, z, t, eq) if match_['type_of_equation'] == 'type5': sol = _nonlinear_3eq_order1_type5(x, y, z, t, eq) return sol def _nonlinear_3eq_order1_type1(x, y, z, t, eq): r""" Equations: .. math:: a x' = (b - c) y z, \enspace b y' = (c - a) z x, \enspace c z' = (a - b) x y First Integrals: .. math:: a x^{2} + b y^{2} + c z^{2} = C_1 .. math:: a^{2} x^{2} + b^{2} y^{2} + c^{2} z^{2} = C_2 where `C_1` and `C_2` are arbitrary constants. On solving the integrals for `y` and `z` and on substituting the resulting expressions into the first equation of the system, we arrives at a separable first-order equation on `x`. Similarly doing that for other two equations, we will arrive at first order equation on `y` and `z` too. References ========== -http://eqworld.ipmnet.ru/en/solutions/sysode/sode0401.pdf """ C1, C2 = get_numbered_constants(eq, num=2) u, v, w = symbols('u, v, w') p = Wild('p', exclude=[x(t), y(t), z(t), t]) q = Wild('q', exclude=[x(t), y(t), z(t), t]) s = Wild('s', exclude=[x(t), y(t), z(t), t]) r = (diff(x(t),t) - eq[0]).match(p*y(t)*z(t)) r.update((diff(y(t),t) - eq[1]).match(q*z(t)*x(t))) r.update((diff(z(t),t) - eq[2]).match(s*x(t)*y(t))) n1, d1 = r[p].as_numer_denom() n2, d2 = r[q].as_numer_denom() n3, d3 = r[s].as_numer_denom() val = solve([n1*u-d1*v+d1*w, d2*u+n2*v-d2*w, d3*u-d3*v-n3*w],[u,v]) vals = [val[v], val[u]] c = lcm(vals[0].as_numer_denom()[1], vals[1].as_numer_denom()[1]) b = vals[0].subs(w, c) a = vals[1].subs(w, c) y_x = sqrt(((c*C1-C2) - a*(c-a)*x(t)**2)/(b*(c-b))) z_x = sqrt(((b*C1-C2) - a*(b-a)*x(t)**2)/(c*(b-c))) z_y = sqrt(((a*C1-C2) - b*(a-b)*y(t)**2)/(c*(a-c))) x_y = sqrt(((c*C1-C2) - b*(c-b)*y(t)**2)/(a*(c-a))) x_z = sqrt(((b*C1-C2) - c*(b-c)*z(t)**2)/(a*(b-a))) y_z = sqrt(((a*C1-C2) - c*(a-c)*z(t)**2)/(b*(a-b))) sol1 = dsolve(a*diff(x(t),t) - (b-c)*y_x*z_x) sol2 = dsolve(b*diff(y(t),t) - (c-a)*z_y*x_y) sol3 = dsolve(c*diff(z(t),t) - (a-b)*x_z*y_z) return [sol1, sol2, sol3] def _nonlinear_3eq_order1_type2(x, y, z, t, eq): r""" Equations: .. math:: a x' = (b - c) y z f(x, y, z, t) .. math:: b y' = (c - a) z x f(x, y, z, t) .. math:: c z' = (a - b) x y f(x, y, z, t) First Integrals: .. math:: a x^{2} + b y^{2} + c z^{2} = C_1 .. math:: a^{2} x^{2} + b^{2} y^{2} + c^{2} z^{2} = C_2 where `C_1` and `C_2` are arbitrary constants. On solving the integrals for `y` and `z` and on substituting the resulting expressions into the first equation of the system, we arrives at a first-order differential equations on `x`. Similarly doing that for other two equations we will arrive at first order equation on `y` and `z`. References ========== -http://eqworld.ipmnet.ru/en/solutions/sysode/sode0402.pdf """ C1, C2 = get_numbered_constants(eq, num=2) u, v, w = symbols('u, v, w') p = Wild('p', exclude=[x(t), y(t), z(t), t]) q = Wild('q', exclude=[x(t), y(t), z(t), t]) s = Wild('s', exclude=[x(t), y(t), z(t), t]) f = Wild('f') r1 = (diff(x(t),t) - eq[0]).match(y(t)*z(t)*f) r = collect_const(r1[f]).match(p*f) r.update(((diff(y(t),t) - eq[1])/r[f]).match(q*z(t)*x(t))) r.update(((diff(z(t),t) - eq[2])/r[f]).match(s*x(t)*y(t))) n1, d1 = r[p].as_numer_denom() n2, d2 = r[q].as_numer_denom() n3, d3 = r[s].as_numer_denom() val = solve([n1*u-d1*v+d1*w, d2*u+n2*v-d2*w, -d3*u+d3*v+n3*w],[u,v]) vals = [val[v], val[u]] c = lcm(vals[0].as_numer_denom()[1], vals[1].as_numer_denom()[1]) a = vals[0].subs(w, c) b = vals[1].subs(w, c) y_x = sqrt(((c*C1-C2) - a*(c-a)*x(t)**2)/(b*(c-b))) z_x = sqrt(((b*C1-C2) - a*(b-a)*x(t)**2)/(c*(b-c))) z_y = sqrt(((a*C1-C2) - b*(a-b)*y(t)**2)/(c*(a-c))) x_y = sqrt(((c*C1-C2) - b*(c-b)*y(t)**2)/(a*(c-a))) x_z = sqrt(((b*C1-C2) - c*(b-c)*z(t)**2)/(a*(b-a))) y_z = sqrt(((a*C1-C2) - c*(a-c)*z(t)**2)/(b*(a-b))) sol1 = dsolve(a*diff(x(t),t) - (b-c)*y_x*z_x*r[f]) sol2 = dsolve(b*diff(y(t),t) - (c-a)*z_y*x_y*r[f]) sol3 = dsolve(c*diff(z(t),t) - (a-b)*x_z*y_z*r[f]) return [sol1, sol2, sol3] def _nonlinear_3eq_order1_type3(x, y, z, t, eq): r""" Equations: .. math:: x' = c F_2 - b F_3, \enspace y' = a F_3 - c F_1, \enspace z' = b F_1 - a F_2 where `F_n = F_n(x, y, z, t)`. 1. First Integral: .. math:: a x + b y + c z = C_1, where C is an arbitrary constant. 2. If we assume function `F_n` to be independent of `t`,i.e, `F_n` = `F_n (x, y, z)` Then, on eliminating `t` and `z` from the first two equation of the system, one arrives at the first-order equation .. math:: \frac{dy}{dx} = \frac{a F_3 (x, y, z) - c F_1 (x, y, z)}{c F_2 (x, y, z) - b F_3 (x, y, z)} where `z = \frac{1}{c} (C_1 - a x - b y)` References ========== -http://eqworld.ipmnet.ru/en/solutions/sysode/sode0404.pdf """ C1 = get_numbered_constants(eq, num=1) u, v, w = symbols('u, v, w') fu, fv, fw = symbols('u, v, w', cls=Function) p = Wild('p', exclude=[x(t), y(t), z(t), t]) q = Wild('q', exclude=[x(t), y(t), z(t), t]) s = Wild('s', exclude=[x(t), y(t), z(t), t]) F1, F2, F3 = symbols('F1, F2, F3', cls=Wild) r1 = (diff(x(t), t) - eq[0]).match(F2-F3) r = collect_const(r1[F2]).match(s*F2) r.update(collect_const(r1[F3]).match(q*F3)) if eq[1].has(r[F2]) and not eq[1].has(r[F3]): r[F2], r[F3] = r[F3], r[F2] r[s], r[q] = -r[q], -r[s] r.update((diff(y(t), t) - eq[1]).match(p*r[F3] - r[s]*F1)) a = r[p]; b = r[q]; c = r[s] F1 = r[F1].subs(x(t), u).subs(y(t),v).subs(z(t), w) F2 = r[F2].subs(x(t), u).subs(y(t),v).subs(z(t), w) F3 = r[F3].subs(x(t), u).subs(y(t),v).subs(z(t), w) z_xy = (C1-a*u-b*v)/c y_zx = (C1-a*u-c*w)/b x_yz = (C1-b*v-c*w)/a y_x = dsolve(diff(fv(u),u) - ((a*F3-c*F1)/(c*F2-b*F3)).subs(w,z_xy).subs(v,fv(u))).rhs z_x = dsolve(diff(fw(u),u) - ((b*F1-a*F2)/(c*F2-b*F3)).subs(v,y_zx).subs(w,fw(u))).rhs z_y = dsolve(diff(fw(v),v) - ((b*F1-a*F2)/(a*F3-c*F1)).subs(u,x_yz).subs(w,fw(v))).rhs x_y = dsolve(diff(fu(v),v) - ((c*F2-b*F3)/(a*F3-c*F1)).subs(w,z_xy).subs(u,fu(v))).rhs y_z = dsolve(diff(fv(w),w) - ((a*F3-c*F1)/(b*F1-a*F2)).subs(u,x_yz).subs(v,fv(w))).rhs x_z = dsolve(diff(fu(w),w) - ((c*F2-b*F3)/(b*F1-a*F2)).subs(v,y_zx).subs(u,fu(w))).rhs sol1 = dsolve(diff(fu(t),t) - (c*F2 - b*F3).subs(v,y_x).subs(w,z_x).subs(u,fu(t))).rhs sol2 = dsolve(diff(fv(t),t) - (a*F3 - c*F1).subs(u,x_y).subs(w,z_y).subs(v,fv(t))).rhs sol3 = dsolve(diff(fw(t),t) - (b*F1 - a*F2).subs(u,x_z).subs(v,y_z).subs(w,fw(t))).rhs return [sol1, sol2, sol3] def _nonlinear_3eq_order1_type4(x, y, z, t, eq): r""" Equations: .. math:: x' = c z F_2 - b y F_3, \enspace y' = a x F_3 - c z F_1, \enspace z' = b y F_1 - a x F_2 where `F_n = F_n (x, y, z, t)` 1. First integral: .. math:: a x^{2} + b y^{2} + c z^{2} = C_1 where `C` is an arbitrary constant. 2. Assuming the function `F_n` is independent of `t`: `F_n = F_n (x, y, z)`. Then on eliminating `t` and `z` from the first two equations of the system, one arrives at the first-order equation .. math:: \frac{dy}{dx} = \frac{a x F_3 (x, y, z) - c z F_1 (x, y, z)} {c z F_2 (x, y, z) - b y F_3 (x, y, z)} where `z = \pm \sqrt{\frac{1}{c} (C_1 - a x^{2} - b y^{2})}` References ========== -http://eqworld.ipmnet.ru/en/solutions/sysode/sode0405.pdf """ C1 = get_numbered_constants(eq, num=1) u, v, w = symbols('u, v, w') p = Wild('p', exclude=[x(t), y(t), z(t), t]) q = Wild('q', exclude=[x(t), y(t), z(t), t]) s = Wild('s', exclude=[x(t), y(t), z(t), t]) F1, F2, F3 = symbols('F1, F2, F3', cls=Wild) r1 = eq[0].match(diff(x(t),t) - z(t)*F2 + y(t)*F3) r = collect_const(r1[F2]).match(s*F2) r.update(collect_const(r1[F3]).match(q*F3)) if eq[1].has(r[F2]) and not eq[1].has(r[F3]): r[F2], r[F3] = r[F3], r[F2] r[s], r[q] = -r[q], -r[s] r.update((diff(y(t),t) - eq[1]).match(p*x(t)*r[F3] - r[s]*z(t)*F1)) a = r[p]; b = r[q]; c = r[s] F1 = r[F1].subs(x(t),u).subs(y(t),v).subs(z(t),w) F2 = r[F2].subs(x(t),u).subs(y(t),v).subs(z(t),w) F3 = r[F3].subs(x(t),u).subs(y(t),v).subs(z(t),w) x_yz = sqrt((C1 - b*v**2 - c*w**2)/a) y_zx = sqrt((C1 - c*w**2 - a*u**2)/b) z_xy = sqrt((C1 - a*u**2 - b*v**2)/c) y_x = dsolve(diff(v(u),u) - ((a*u*F3-c*w*F1)/(c*w*F2-b*v*F3)).subs(w,z_xy).subs(v,v(u))).rhs z_x = dsolve(diff(w(u),u) - ((b*v*F1-a*u*F2)/(c*w*F2-b*v*F3)).subs(v,y_zx).subs(w,w(u))).rhs z_y = dsolve(diff(w(v),v) - ((b*v*F1-a*u*F2)/(a*u*F3-c*w*F1)).subs(u,x_yz).subs(w,w(v))).rhs x_y = dsolve(diff(u(v),v) - ((c*w*F2-b*v*F3)/(a*u*F3-c*w*F1)).subs(w,z_xy).subs(u,u(v))).rhs y_z = dsolve(diff(v(w),w) - ((a*u*F3-c*w*F1)/(b*v*F1-a*u*F2)).subs(u,x_yz).subs(v,v(w))).rhs x_z = dsolve(diff(u(w),w) - ((c*w*F2-b*v*F3)/(b*v*F1-a*u*F2)).subs(v,y_zx).subs(u,u(w))).rhs sol1 = dsolve(diff(u(t),t) - (c*w*F2 - b*v*F3).subs(v,y_x).subs(w,z_x).subs(u,u(t))).rhs sol2 = dsolve(diff(v(t),t) - (a*u*F3 - c*w*F1).subs(u,x_y).subs(w,z_y).subs(v,v(t))).rhs sol3 = dsolve(diff(w(t),t) - (b*v*F1 - a*u*F2).subs(u,x_z).subs(v,y_z).subs(w,w(t))).rhs return [sol1, sol2, sol3] def _nonlinear_3eq_order1_type5(x, y, z, t, eq): r""" .. math:: x' = x (c F_2 - b F_3), \enspace y' = y (a F_3 - c F_1), \enspace z' = z (b F_1 - a F_2) where `F_n = F_n (x, y, z, t)` and are arbitrary functions. First Integral: .. math:: \left|x\right|^{a} \left|y\right|^{b} \left|z\right|^{c} = C_1 where `C` is an arbitrary constant. If the function `F_n` is independent of `t`, then, by eliminating `t` and `z` from the first two equations of the system, one arrives at a first-order equation. References ========== -http://eqworld.ipmnet.ru/en/solutions/sysode/sode0406.pdf """ C1 = get_numbered_constants(eq, num=1) u, v, w = symbols('u, v, w') fu, fv, fw = symbols('u, v, w', cls=Function) p = Wild('p', exclude=[x(t), y(t), z(t), t]) q = Wild('q', exclude=[x(t), y(t), z(t), t]) s = Wild('s', exclude=[x(t), y(t), z(t), t]) F1, F2, F3 = symbols('F1, F2, F3', cls=Wild) r1 = eq[0].match(diff(x(t), t) - x(t)*F2 + x(t)*F3) r = collect_const(r1[F2]).match(s*F2) r.update(collect_const(r1[F3]).match(q*F3)) if eq[1].has(r[F2]) and not eq[1].has(r[F3]): r[F2], r[F3] = r[F3], r[F2] r[s], r[q] = -r[q], -r[s] r.update((diff(y(t), t) - eq[1]).match(y(t)*(p*r[F3] - r[s]*F1))) a = r[p]; b = r[q]; c = r[s] F1 = r[F1].subs(x(t), u).subs(y(t), v).subs(z(t), w) F2 = r[F2].subs(x(t), u).subs(y(t), v).subs(z(t), w) F3 = r[F3].subs(x(t), u).subs(y(t), v).subs(z(t), w) x_yz = (C1*v**-b*w**-c)**-a y_zx = (C1*w**-c*u**-a)**-b z_xy = (C1*u**-a*v**-b)**-c y_x = dsolve(diff(fv(u), u) - ((v*(a*F3 - c*F1))/(u*(c*F2 - b*F3))).subs(w, z_xy).subs(v, fv(u))).rhs z_x = dsolve(diff(fw(u), u) - ((w*(b*F1 - a*F2))/(u*(c*F2 - b*F3))).subs(v, y_zx).subs(w, fw(u))).rhs z_y = dsolve(diff(fw(v), v) - ((w*(b*F1 - a*F2))/(v*(a*F3 - c*F1))).subs(u, x_yz).subs(w, fw(v))).rhs x_y = dsolve(diff(fu(v), v) - ((u*(c*F2 - b*F3))/(v*(a*F3 - c*F1))).subs(w, z_xy).subs(u, fu(v))).rhs y_z = dsolve(diff(fv(w), w) - ((v*(a*F3 - c*F1))/(w*(b*F1 - a*F2))).subs(u, x_yz).subs(v, fv(w))).rhs x_z = dsolve(diff(fu(w), w) - ((u*(c*F2 - b*F3))/(w*(b*F1 - a*F2))).subs(v, y_zx).subs(u, fu(w))).rhs sol1 = dsolve(diff(fu(t), t) - (u*(c*F2 - b*F3)).subs(v, y_x).subs(w, z_x).subs(u, fu(t))).rhs sol2 = dsolve(diff(fv(t), t) - (v*(a*F3 - c*F1)).subs(u, x_y).subs(w, z_y).subs(v, fv(t))).rhs sol3 = dsolve(diff(fw(t), t) - (w*(b*F1 - a*F2)).subs(u, x_z).subs(v, y_z).subs(w, fw(t))).rhs return [sol1, sol2, sol3] #This import is written at the bottom to avoid circular imports. from .single import SingleODEProblem, SingleODESolver, solver_map
dfcb576a50f707f9ca82bcefc838fd7e918577c2b97656eb479f362f7df6bc80
# # This is the module for ODE solver classes for single ODEs. # import typing if typing.TYPE_CHECKING: from typing import ClassVar from typing import Dict as tDict, Type, Iterator, List, Optional from .riccati import match_riccati, solve_riccati from sympy.core import Add, S, Pow, Rational from sympy.core.exprtools import factor_terms from sympy.core.expr import Expr from sympy.core.function import AppliedUndef, Derivative, diff, Function, expand, Subs, _mexpand from sympy.core.numbers import zoo from sympy.core.relational import Equality, Eq from sympy.core.symbol import Symbol, Dummy, Wild from sympy.core.mul import Mul from sympy.functions import exp, tan, log, sqrt, besselj, bessely, cbrt, airyai, airybi from sympy.integrals import Integral from sympy.polys import Poly from sympy.polys.polytools import cancel, factor, degree from sympy.simplify import collect, simplify, separatevars, logcombine, posify # type: ignore from sympy.simplify.radsimp import fraction from sympy.utilities import numbered_symbols from sympy.solvers.solvers import solve from sympy.solvers.deutils import ode_order, _preprocess from sympy.polys.matrices.linsolve import _lin_eq2dict from sympy.polys.solvers import PolyNonlinearError from .hypergeometric import equivalence_hypergeometric, match_2nd_2F1_hypergeometric, \ get_sol_2F1_hypergeometric, match_2nd_hypergeometric from .nonhomogeneous import _get_euler_characteristic_eq_sols, _get_const_characteristic_eq_sols, \ _solve_undetermined_coefficients, _solve_variation_of_parameters, _test_term, _undetermined_coefficients_match, \ _get_simplified_sol from .lie_group import _ode_lie_group class ODEMatchError(NotImplementedError): """Raised if a SingleODESolver is asked to solve an ODE it does not match""" pass def cached_property(func): '''Decorator to cache property method''' attrname = '_' + func.__name__ def propfunc(self): val = getattr(self, attrname, None) if val is None: val = func(self) setattr(self, attrname, val) return val return property(propfunc) class SingleODEProblem: """Represents an ordinary differential equation (ODE) This class is used internally in the by dsolve and related functions/classes so that properties of an ODE can be computed efficiently. Examples ======== This class is used internally by dsolve. To instantiate an instance directly first define an ODE problem: >>> from sympy import Function, Symbol >>> x = Symbol('x') >>> f = Function('f') >>> eq = f(x).diff(x, 2) Now you can create a SingleODEProblem instance and query its properties: >>> from sympy.solvers.ode.single import SingleODEProblem >>> problem = SingleODEProblem(f(x).diff(x), f(x), x) >>> problem.eq Derivative(f(x), x) >>> problem.func f(x) >>> problem.sym x """ # Instance attributes: eq = None # type: Expr func = None # type: AppliedUndef sym = None # type: Symbol _order = None # type: int _eq_expanded = None # type: Expr _eq_preprocessed = None # type: Expr _eq_high_order_free = None def __init__(self, eq, func, sym, prep=True, **kwargs): assert isinstance(eq, Expr) assert isinstance(func, AppliedUndef) assert isinstance(sym, Symbol) assert isinstance(prep, bool) self.eq = eq self.func = func self.sym = sym self.prep = prep self.params = kwargs @cached_property def order(self) -> int: return ode_order(self.eq, self.func) @cached_property def eq_preprocessed(self) -> Expr: return self._get_eq_preprocessed() @cached_property def eq_high_order_free(self) -> Expr: a = Wild('a', exclude=[self.func]) c1 = Wild('c1', exclude=[self.sym]) # Precondition to try remove f(x) from highest order derivative reduced_eq = None if self.eq.is_Add: deriv_coef = self.eq.coeff(self.func.diff(self.sym, self.order)) if deriv_coef not in (1, 0): r = deriv_coef.match(a*self.func**c1) if r and r[c1]: den = self.func**r[c1] reduced_eq = Add(*[arg/den for arg in self.eq.args]) if not reduced_eq: reduced_eq = expand(self.eq) return reduced_eq @cached_property def eq_expanded(self) -> Expr: return expand(self.eq_preprocessed) def _get_eq_preprocessed(self) -> Expr: if self.prep: process_eq, process_func = _preprocess(self.eq, self.func) if process_func != self.func: raise ValueError else: process_eq = self.eq return process_eq def get_numbered_constants(self, num=1, start=1, prefix='C') -> List[Symbol]: """ Returns a list of constants that do not occur in eq already. """ ncs = self.iter_numbered_constants(start, prefix) Cs = [next(ncs) for i in range(num)] return Cs def iter_numbered_constants(self, start=1, prefix='C') -> Iterator[Symbol]: """ Returns an iterator of constants that do not occur in eq already. """ atom_set = self.eq.free_symbols func_set = self.eq.atoms(Function) if func_set: atom_set |= {Symbol(str(f.func)) for f in func_set} return numbered_symbols(start=start, prefix=prefix, exclude=atom_set) @cached_property def is_autonomous(self): u = Dummy('u') x = self.sym syms = self.eq.subs(self.func, u).free_symbols return x not in syms def get_linear_coefficients(self, eq, func, order): r""" Matches a differential equation to the linear form: .. math:: a_n(x) y^{(n)} + \cdots + a_1(x)y' + a_0(x) y + B(x) = 0 Returns a dict of order:coeff terms, where order is the order of the derivative on each term, and coeff is the coefficient of that derivative. The key ``-1`` holds the function `B(x)`. Returns ``None`` if the ODE is not linear. This function assumes that ``func`` has already been checked to be good. Examples ======== >>> from sympy import Function, cos, sin >>> from sympy.abc import x >>> from sympy.solvers.ode.single import SingleODEProblem >>> f = Function('f') >>> eq = f(x).diff(x, 3) + 2*f(x).diff(x) + \ ... x*f(x).diff(x, 2) + cos(x)*f(x).diff(x) + x - f(x) - \ ... sin(x) >>> obj = SingleODEProblem(eq, f(x), x) >>> obj.get_linear_coefficients(eq, f(x), 3) {-1: x - sin(x), 0: -1, 1: cos(x) + 2, 2: x, 3: 1} >>> eq = f(x).diff(x, 3) + 2*f(x).diff(x) + \ ... x*f(x).diff(x, 2) + cos(x)*f(x).diff(x) + x - f(x) - \ ... sin(f(x)) >>> obj = SingleODEProblem(eq, f(x), x) >>> obj.get_linear_coefficients(eq, f(x), 3) == None True """ f = func.func x = func.args[0] symset = {Derivative(f(x), x, i) for i in range(order+1)} try: rhs, lhs_terms = _lin_eq2dict(eq, symset) except PolyNonlinearError: return None if rhs.has(func) or any(c.has(func) for c in lhs_terms.values()): return None terms = {i: lhs_terms.get(f(x).diff(x, i), S.Zero) for i in range(order+1)} terms[-1] = rhs return terms # TODO: Add methods that can be used by many ODE solvers: # order # is_linear() # get_linear_coefficients() # eq_prepared (the ODE in prepared form) class SingleODESolver: """ Base class for Single ODE solvers. Subclasses should implement the _matches and _get_general_solution methods. This class is not intended to be instantiated directly but its subclasses are as part of dsolve. Examples ======== You can use a subclass of SingleODEProblem to solve a particular type of ODE. We first define a particular ODE problem: >>> from sympy import Function, Symbol >>> x = Symbol('x') >>> f = Function('f') >>> eq = f(x).diff(x, 2) Now we solve this problem using the NthAlgebraic solver which is a subclass of SingleODESolver: >>> from sympy.solvers.ode.single import NthAlgebraic, SingleODEProblem >>> problem = SingleODEProblem(eq, f(x), x) >>> solver = NthAlgebraic(problem) >>> solver.get_general_solution() [Eq(f(x), _C*x + _C)] The normal way to solve an ODE is to use dsolve (which would use NthAlgebraic and other solvers internally). When using dsolve a number of other things are done such as evaluating integrals, simplifying the solution and renumbering the constants: >>> from sympy import dsolve >>> dsolve(eq, hint='nth_algebraic') Eq(f(x), C1 + C2*x) """ # Subclasses should store the hint name (the argument to dsolve) in this # attribute hint = None # type: ClassVar[str] # Subclasses should define this to indicate if they support an _Integral # hint. has_integral = None # type: ClassVar[bool] # The ODE to be solved ode_problem = None # type: SingleODEProblem # Cache whether or not the equation has matched the method _matched = None # type: Optional[bool] # Subclasses should store in this attribute the list of order(s) of ODE # that subclass can solve or leave it to None if not specific to any order order = None # type: Optional[list] def __init__(self, ode_problem): self.ode_problem = ode_problem def matches(self) -> bool: if self.order is not None and self.ode_problem.order not in self.order: self._matched = False return self._matched if self._matched is None: self._matched = self._matches() return self._matched def get_general_solution(self, *, simplify: bool = True) -> List[Equality]: if not self.matches(): msg = "%s solver cannot solve:\n%s" raise ODEMatchError(msg % (self.hint, self.ode_problem.eq)) return self._get_general_solution(simplify_flag=simplify) def _matches(self) -> bool: msg = "Subclasses of SingleODESolver should implement matches." raise NotImplementedError(msg) def _get_general_solution(self, *, simplify_flag: bool = True) -> List[Equality]: msg = "Subclasses of SingleODESolver should implement get_general_solution." raise NotImplementedError(msg) class SinglePatternODESolver(SingleODESolver): '''Superclass for ODE solvers based on pattern matching''' def wilds(self): prob = self.ode_problem f = prob.func.func x = prob.sym order = prob.order return self._wilds(f, x, order) def wilds_match(self): match = self._wilds_match return [match.get(w, S.Zero) for w in self.wilds()] def _matches(self): eq = self.ode_problem.eq_expanded f = self.ode_problem.func.func x = self.ode_problem.sym order = self.ode_problem.order df = f(x).diff(x, order) if order not in [1, 2]: return False pattern = self._equation(f(x), x, order) if not pattern.coeff(df).has(Wild): eq = expand(eq / eq.coeff(df)) eq = eq.collect([f(x).diff(x), f(x)], func = cancel) self._wilds_match = match = eq.match(pattern) if match is not None: return self._verify(f(x)) return False def _verify(self, fx) -> bool: return True def _wilds(self, f, x, order): msg = "Subclasses of SingleODESolver should implement _wilds" raise NotImplementedError(msg) def _equation(self, fx, x, order): msg = "Subclasses of SingleODESolver should implement _equation" raise NotImplementedError(msg) class NthAlgebraic(SingleODESolver): r""" Solves an `n`\th order ordinary differential equation using algebra and integrals. There is no general form for the kind of equation that this can solve. The the equation is solved algebraically treating differentiation as an invertible algebraic function. Examples ======== >>> from sympy import Function, dsolve, Eq >>> from sympy.abc import x >>> f = Function('f') >>> eq = Eq(f(x) * (f(x).diff(x)**2 - 1), 0) >>> dsolve(eq, f(x), hint='nth_algebraic') [Eq(f(x), 0), Eq(f(x), C1 - x), Eq(f(x), C1 + x)] Note that this solver can return algebraic solutions that do not have any integration constants (f(x) = 0 in the above example). """ hint = 'nth_algebraic' has_integral = True # nth_algebraic_Integral hint def _matches(self): r""" Matches any differential equation that nth_algebraic can solve. Uses `sympy.solve` but teaches it how to integrate derivatives. This involves calling `sympy.solve` and does most of the work of finding a solution (apart from evaluating the integrals). """ eq = self.ode_problem.eq func = self.ode_problem.func var = self.ode_problem.sym # Derivative that solve can handle: diffx = self._get_diffx(var) # Replace derivatives wrt the independent variable with diffx def replace(eq, var): def expand_diffx(*args): differand, diffs = args[0], args[1:] toreplace = differand for v, n in diffs: for _ in range(n): if v == var: toreplace = diffx(toreplace) else: toreplace = Derivative(toreplace, v) return toreplace return eq.replace(Derivative, expand_diffx) # Restore derivatives in solution afterwards def unreplace(eq, var): return eq.replace(diffx, lambda e: Derivative(e, var)) subs_eqn = replace(eq, var) try: # turn off simplification to protect Integrals that have # _t instead of fx in them and would otherwise factor # as t_*Integral(1, x) solns = solve(subs_eqn, func, simplify=False) except NotImplementedError: solns = [] solns = [simplify(unreplace(soln, var)) for soln in solns] solns = [Equality(func, soln) for soln in solns] self.solutions = solns return len(solns) != 0 def _get_general_solution(self, *, simplify_flag: bool = True): return self.solutions # This needs to produce an invertible function but the inverse depends # which variable we are integrating with respect to. Since the class can # be stored in cached results we need to ensure that we always get the # same class back for each particular integration variable so we store these # classes in a global dict: _diffx_stored = {} # type: tDict[Symbol, Type[Function]] @staticmethod def _get_diffx(var): diffcls = NthAlgebraic._diffx_stored.get(var, None) if diffcls is None: # A class that behaves like Derivative wrt var but is "invertible". class diffx(Function): def inverse(self): # don't use integrate here because fx has been replaced by _t # in the equation; integrals will not be correct while solve # is at work. return lambda expr: Integral(expr, var) + Dummy('C') diffcls = NthAlgebraic._diffx_stored.setdefault(var, diffx) return diffcls class FirstExact(SinglePatternODESolver): r""" Solves 1st order exact ordinary differential equations. A 1st order differential equation is called exact if it is the total differential of a function. That is, the differential equation .. math:: P(x, y) \,\partial{}x + Q(x, y) \,\partial{}y = 0 is exact if there is some function `F(x, y)` such that `P(x, y) = \partial{}F/\partial{}x` and `Q(x, y) = \partial{}F/\partial{}y`. It can be shown that a necessary and sufficient condition for a first order ODE to be exact is that `\partial{}P/\partial{}y = \partial{}Q/\partial{}x`. Then, the solution will be as given below:: >>> from sympy import Function, Eq, Integral, symbols, pprint >>> x, y, t, x0, y0, C1= symbols('x,y,t,x0,y0,C1') >>> P, Q, F= map(Function, ['P', 'Q', 'F']) >>> pprint(Eq(Eq(F(x, y), Integral(P(t, y), (t, x0, x)) + ... Integral(Q(x0, t), (t, y0, y))), C1)) x y / / | | F(x, y) = | P(t, y) dt + | Q(x0, t) dt = C1 | | / / x0 y0 Where the first partials of `P` and `Q` exist and are continuous in a simply connected region. A note: SymPy currently has no way to represent inert substitution on an expression, so the hint ``1st_exact_Integral`` will return an integral with `dy`. This is supposed to represent the function that you are solving for. Examples ======== >>> from sympy import Function, dsolve, cos, sin >>> from sympy.abc import x >>> f = Function('f') >>> dsolve(cos(f(x)) - (x*sin(f(x)) - f(x)**2)*f(x).diff(x), ... f(x), hint='1st_exact') Eq(x*cos(f(x)) + f(x)**3/3, C1) References ========== - https://en.wikipedia.org/wiki/Exact_differential_equation - M. Tenenbaum & H. Pollard, "Ordinary Differential Equations", Dover 1963, pp. 73 # indirect doctest """ hint = "1st_exact" has_integral = True order = [1] def _wilds(self, f, x, order): P = Wild('P', exclude=[f(x).diff(x)]) Q = Wild('Q', exclude=[f(x).diff(x)]) return P, Q def _equation(self, fx, x, order): P, Q = self.wilds() return P + Q*fx.diff(x) def _verify(self, fx) -> bool: P, Q = self.wilds() x = self.ode_problem.sym y = Dummy('y') m, n = self.wilds_match() m = m.subs(fx, y) n = n.subs(fx, y) numerator = cancel(m.diff(y) - n.diff(x)) if numerator.is_zero: # Is exact return True else: # The following few conditions try to convert a non-exact # differential equation into an exact one. # References: # 1. Differential equations with applications # and historical notes - George E. Simmons # 2. https://math.okstate.edu/people/binegar/2233-S99/2233-l12.pdf factor_n = cancel(numerator/n) factor_m = cancel(-numerator/m) if y not in factor_n.free_symbols: # If (dP/dy - dQ/dx) / Q = f(x) # then exp(integral(f(x))*equation becomes exact factor = factor_n integration_variable = x elif x not in factor_m.free_symbols: # If (dP/dy - dQ/dx) / -P = f(y) # then exp(integral(f(y))*equation becomes exact factor = factor_m integration_variable = y else: # Couldn't convert to exact return False factor = exp(Integral(factor, integration_variable)) m *= factor n *= factor self._wilds_match[P] = m.subs(y, fx) self._wilds_match[Q] = n.subs(y, fx) return True def _get_general_solution(self, *, simplify_flag: bool = True): m, n = self.wilds_match() fx = self.ode_problem.func x = self.ode_problem.sym (C1,) = self.ode_problem.get_numbered_constants(num=1) y = Dummy('y') m = m.subs(fx, y) n = n.subs(fx, y) gen_sol = Eq(Subs(Integral(m, x) + Integral(n - Integral(m, x).diff(y), y), y, fx), C1) return [gen_sol] class FirstLinear(SinglePatternODESolver): r""" Solves 1st order linear differential equations. These are differential equations of the form .. math:: dy/dx + P(x) y = Q(x)\text{.} These kinds of differential equations can be solved in a general way. The integrating factor `e^{\int P(x) \,dx}` will turn the equation into a separable equation. The general solution is:: >>> from sympy import Function, dsolve, Eq, pprint, diff, sin >>> from sympy.abc import x >>> f, P, Q = map(Function, ['f', 'P', 'Q']) >>> genform = Eq(f(x).diff(x) + P(x)*f(x), Q(x)) >>> pprint(genform) d P(x)*f(x) + --(f(x)) = Q(x) dx >>> pprint(dsolve(genform, f(x), hint='1st_linear_Integral')) / / \ | | | | | / | / | | | | | | | | P(x) dx | - | P(x) dx | | | | | | | / | / f(x) = |C1 + | Q(x)*e dx|*e | | | \ / / Examples ======== >>> f = Function('f') >>> pprint(dsolve(Eq(x*diff(f(x), x) - f(x), x**2*sin(x)), ... f(x), '1st_linear')) f(x) = x*(C1 - cos(x)) References ========== - https://en.wikipedia.org/wiki/Linear_differential_equation#First_order_equation - M. Tenenbaum & H. Pollard, "Ordinary Differential Equations", Dover 1963, pp. 92 # indirect doctest """ hint = '1st_linear' has_integral = True order = [1] def _wilds(self, f, x, order): P = Wild('P', exclude=[f(x)]) Q = Wild('Q', exclude=[f(x), f(x).diff(x)]) return P, Q def _equation(self, fx, x, order): P, Q = self.wilds() return fx.diff(x) + P*fx - Q def _get_general_solution(self, *, simplify_flag: bool = True): P, Q = self.wilds_match() fx = self.ode_problem.func x = self.ode_problem.sym (C1,) = self.ode_problem.get_numbered_constants(num=1) gensol = Eq(fx, ((C1 + Integral(Q*exp(Integral(P, x)), x)) * exp(-Integral(P, x)))) return [gensol] class AlmostLinear(SinglePatternODESolver): r""" Solves an almost-linear differential equation. The general form of an almost linear differential equation is .. math:: a(x) g'(f(x)) f'(x) + b(x) g(f(x)) + c(x) Here `f(x)` is the function to be solved for (the dependent variable). The substitution `g(f(x)) = u(x)` leads to a linear differential equation for `u(x)` of the form `a(x) u' + b(x) u + c(x) = 0`. This can be solved for `u(x)` by the `first_linear` hint and then `f(x)` is found by solving `g(f(x)) = u(x)`. See Also ======== :obj:`sympy.solvers.ode.single.FirstLinear` Examples ======== >>> from sympy import dsolve, Function, pprint, sin, cos >>> from sympy.abc import x >>> f = Function('f') >>> d = f(x).diff(x) >>> eq = x*d + x*f(x) + 1 >>> dsolve(eq, f(x), hint='almost_linear') Eq(f(x), (C1 - Ei(x))*exp(-x)) >>> pprint(dsolve(eq, f(x), hint='almost_linear')) -x f(x) = (C1 - Ei(x))*e >>> example = cos(f(x))*f(x).diff(x) + sin(f(x)) + 1 >>> pprint(example) d sin(f(x)) + cos(f(x))*--(f(x)) + 1 dx >>> pprint(dsolve(example, f(x), hint='almost_linear')) / -x \ / -x \ [f(x) = pi - asin\C1*e - 1/, f(x) = asin\C1*e - 1/] References ========== - Joel Moses, "Symbolic Integration - The Stormy Decade", Communications of the ACM, Volume 14, Number 8, August 1971, pp. 558 """ hint = "almost_linear" has_integral = True order = [1] def _wilds(self, f, x, order): P = Wild('P', exclude=[f(x).diff(x)]) Q = Wild('Q', exclude=[f(x).diff(x)]) return P, Q def _equation(self, fx, x, order): P, Q = self.wilds() return P*fx.diff(x) + Q def _verify(self, fx): a, b = self.wilds_match() c, b = b.as_independent(fx) if b.is_Add else (S.Zero, b) # a, b and c are the function a(x), b(x) and c(x) respectively. # c(x) is obtained by separating out b as terms with and without fx i.e, l(y) # The following conditions checks if the given equation is an almost-linear differential equation using the fact that # a(x)*(l(y))' / l(y)' is independent of l(y) if b.diff(fx) != 0 and not simplify(b.diff(fx)/a).has(fx): self.ly = factor_terms(b).as_independent(fx, as_Add=False)[1] # Gives the term containing fx i.e., l(y) self.ax = a / self.ly.diff(fx) self.cx = -c # cx is taken as -c(x) to simplify expression in the solution integral self.bx = factor_terms(b) / self.ly return True return False def _get_general_solution(self, *, simplify_flag: bool = True): x = self.ode_problem.sym (C1,) = self.ode_problem.get_numbered_constants(num=1) gensol = Eq(self.ly, ((C1 + Integral((self.cx/self.ax)*exp(Integral(self.bx/self.ax, x)), x)) * exp(-Integral(self.bx/self.ax, x)))) return [gensol] class Bernoulli(SinglePatternODESolver): r""" Solves Bernoulli differential equations. These are equations of the form .. math:: dy/dx + P(x) y = Q(x) y^n\text{, }n \ne 1`\text{.} The substitution `w = 1/y^{1-n}` will transform an equation of this form into one that is linear (see the docstring of :obj:`~sympy.solvers.ode.single.FirstLinear`). The general solution is:: >>> from sympy import Function, dsolve, Eq, pprint >>> from sympy.abc import x, n >>> f, P, Q = map(Function, ['f', 'P', 'Q']) >>> genform = Eq(f(x).diff(x) + P(x)*f(x), Q(x)*f(x)**n) >>> pprint(genform) d n P(x)*f(x) + --(f(x)) = Q(x)*f (x) dx >>> pprint(dsolve(genform, f(x), hint='Bernoulli_Integral'), num_columns=110) -1 ----- n - 1 // / / \ \ || | | | | || | / | / | / | || | | | | | | | || | -(n - 1)* | P(x) dx | -(n - 1)* | P(x) dx | (n - 1)* | P(x) dx| || | | | | | | | || | / | / | / | f(x) = ||C1 - n* | Q(x)*e dx + | Q(x)*e dx|*e | || | | | | \\ / / / / Note that the equation is separable when `n = 1` (see the docstring of :obj:`~sympy.solvers.ode.single.Separable`). >>> pprint(dsolve(Eq(f(x).diff(x) + P(x)*f(x), Q(x)*f(x)), f(x), ... hint='separable_Integral')) f(x) / | / | 1 | | - dy = C1 + | (-P(x) + Q(x)) dx | y | | / / Examples ======== >>> from sympy import Function, dsolve, Eq, pprint, log >>> from sympy.abc import x >>> f = Function('f') >>> pprint(dsolve(Eq(x*f(x).diff(x) + f(x), log(x)*f(x)**2), ... f(x), hint='Bernoulli')) 1 f(x) = ----------------- C1*x + log(x) + 1 References ========== - https://en.wikipedia.org/wiki/Bernoulli_differential_equation - M. Tenenbaum & H. Pollard, "Ordinary Differential Equations", Dover 1963, pp. 95 # indirect doctest """ hint = "Bernoulli" has_integral = True order = [1] def _wilds(self, f, x, order): P = Wild('P', exclude=[f(x)]) Q = Wild('Q', exclude=[f(x)]) n = Wild('n', exclude=[x, f(x), f(x).diff(x)]) return P, Q, n def _equation(self, fx, x, order): P, Q, n = self.wilds() return fx.diff(x) + P*fx - Q*fx**n def _get_general_solution(self, *, simplify_flag: bool = True): P, Q, n = self.wilds_match() fx = self.ode_problem.func x = self.ode_problem.sym (C1,) = self.ode_problem.get_numbered_constants(num=1) if n==1: gensol = Eq(log(fx), ( C1 + Integral((-P + Q), x) )) else: gensol = Eq(fx**(1-n), ( (C1 - (n - 1) * Integral(Q*exp(-n*Integral(P, x)) * exp(Integral(P, x)), x) ) * exp(-(1 - n)*Integral(P, x))) ) return [gensol] class Factorable(SingleODESolver): r""" Solves equations having a solvable factor. This function is used to solve the equation having factors. Factors may be of type algebraic or ode. It will try to solve each factor independently. Factors will be solved by calling dsolve. We will return the list of solutions. Examples ======== >>> from sympy import Function, dsolve, pprint >>> from sympy.abc import x >>> f = Function('f') >>> eq = (f(x)**2-4)*(f(x).diff(x)+f(x)) >>> pprint(dsolve(eq, f(x))) -x [f(x) = 2, f(x) = -2, f(x) = C1*e ] """ hint = "factorable" has_integral = False def _matches(self): eq_orig = self.ode_problem.eq f = self.ode_problem.func.func x = self.ode_problem.sym df = f(x).diff(x) self.eqs = [] eq = eq_orig.collect(f(x), func = cancel) eq = fraction(factor(eq))[0] factors = Mul.make_args(factor(eq)) roots = [fac.as_base_exp() for fac in factors if len(fac.args)!=0] if len(roots)>1 or roots[0][1]>1: for base, expo in roots: if base.has(f(x)): self.eqs.append(base) if len(self.eqs)>0: return True roots = solve(eq, df) if len(roots)>0: self.eqs = [(df - root) for root in roots] # Avoid infinite recursion matches = self.eqs != [eq_orig] return matches for i in factors: if i.has(f(x)): self.eqs.append(i) return len(self.eqs)>0 and len(factors)>1 def _get_general_solution(self, *, simplify_flag: bool = True): func = self.ode_problem.func.func x = self.ode_problem.sym eqns = self.eqs sols = [] for eq in eqns: try: sol = dsolve(eq, func(x)) except NotImplementedError: continue else: if isinstance(sol, list): sols.extend(sol) else: sols.append(sol) if sols == []: raise NotImplementedError("The given ODE " + str(eq) + " cannot be solved by" + " the factorable group method") return sols class RiccatiSpecial(SinglePatternODESolver): r""" The general Riccati equation has the form .. math:: dy/dx = f(x) y^2 + g(x) y + h(x)\text{.} While it does not have a general solution [1], the "special" form, `dy/dx = a y^2 - b x^c`, does have solutions in many cases [2]. This routine returns a solution for `a(dy/dx) = b y^2 + c y/x + d/x^2` that is obtained by using a suitable change of variables to reduce it to the special form and is valid when neither `a` nor `b` are zero and either `c` or `d` is zero. >>> from sympy.abc import x, a, b, c, d >>> from sympy import dsolve, checkodesol, pprint, Function >>> f = Function('f') >>> y = f(x) >>> genform = a*y.diff(x) - (b*y**2 + c*y/x + d/x**2) >>> sol = dsolve(genform, y, hint="Riccati_special_minus2") >>> pprint(sol, wrap_line=False) / / __________________ \\ | __________________ | / 2 || | / 2 | \/ 4*b*d - (a + c) *log(x)|| -|a + c - \/ 4*b*d - (a + c) *tan|C1 + ----------------------------|| \ \ 2*a // f(x) = ------------------------------------------------------------------------ 2*b*x >>> checkodesol(genform, sol, order=1)[0] True References ========== - http://www.maplesoft.com/support/help/Maple/view.aspx?path=odeadvisor/Riccati - http://eqworld.ipmnet.ru/en/solutions/ode/ode0106.pdf - http://eqworld.ipmnet.ru/en/solutions/ode/ode0123.pdf """ hint = "Riccati_special_minus2" has_integral = False order = [1] def _wilds(self, f, x, order): a = Wild('a', exclude=[x, f(x), f(x).diff(x), 0]) b = Wild('b', exclude=[x, f(x), f(x).diff(x), 0]) c = Wild('c', exclude=[x, f(x), f(x).diff(x)]) d = Wild('d', exclude=[x, f(x), f(x).diff(x)]) return a, b, c, d def _equation(self, fx, x, order): a, b, c, d = self.wilds() return a*fx.diff(x) + b*fx**2 + c*fx/x + d/x**2 def _get_general_solution(self, *, simplify_flag: bool = True): a, b, c, d = self.wilds_match() fx = self.ode_problem.func x = self.ode_problem.sym (C1,) = self.ode_problem.get_numbered_constants(num=1) mu = sqrt(4*d*b - (a - c)**2) gensol = Eq(fx, (a - c - mu*tan(mu/(2*a)*log(x) + C1))/(2*b*x)) return [gensol] class RationalRiccati(SinglePatternODESolver): r""" Gives general solutions to the first order Riccati differential equations that have atleast one rational particular solution. .. math :: y' = b_0(x) + b_1(x) y + b_2(x) y^2 where `b_0`, `b_1` and `b_2` are rational functions of `x` with `b_2 \ne 0` (`b_2 = 0` would make it a Bernoulli equation). Examples ======== >>> from sympy import Symbol, Function, dsolve, checkodesol >>> f = Function('f') >>> x = Symbol('x') >>> eq = -x**4*f(x)**2 + x**3*f(x).diff(x) + x**2*f(x) + 20 >>> sol = dsolve(eq, hint="1st_rational_riccati") >>> sol Eq(f(x), (4*C1 - 5*x**9 - 4)/(x**2*(C1 + x**9 - 1))) >>> checkodesol(eq, sol) (True, 0) References ========== - Riccati ODE: https://en.wikipedia.org/wiki/Riccati_equation - N. Thieu Vo - Rational and Algebraic Solutions of First-Order Algebraic ODEs: Algorithm 11, pp. 78 - https://www3.risc.jku.at/publications/download/risc_5387/PhDThesisThieu.pdf """ has_integral = False hint = "1st_rational_riccati" order = [1] def _wilds(self, f, x, order): b0 = Wild('b0', exclude=[f(x), f(x).diff(x)]) b1 = Wild('b1', exclude=[f(x), f(x).diff(x)]) b2 = Wild('b2', exclude=[f(x), f(x).diff(x)]) return (b0, b1, b2) def _equation(self, fx, x, order): b0, b1, b2 = self.wilds() return fx.diff(x) - b0 - b1*fx - b2*fx**2 def _matches(self): eq = self.ode_problem.eq_expanded f = self.ode_problem.func.func x = self.ode_problem.sym order = self.ode_problem.order if order != 1: return False match, funcs = match_riccati(eq, f, x) if not match: return False _b0, _b1, _b2 = funcs b0, b1, b2 = self.wilds() self._wilds_match = match = {b0: _b0, b1: _b1, b2: _b2} return True def _get_general_solution(self, *, simplify_flag: bool = True): # Match the equation b0, b1, b2 = self.wilds_match() fx = self.ode_problem.func x = self.ode_problem.sym return solve_riccati(fx, x, b0, b1, b2, gensol=True) class SecondNonlinearAutonomousConserved(SinglePatternODESolver): r""" Gives solution for the autonomous second order nonlinear differential equation of the form .. math :: f''(x) = g(f(x)) The solution for this differential equation can be computed by multiplying by `f'(x)` and integrating on both sides, converting it into a first order differential equation. Examples ======== >>> from sympy import Function, symbols, dsolve >>> f, g = symbols('f g', cls=Function) >>> x = symbols('x') >>> eq = f(x).diff(x, 2) - g(f(x)) >>> dsolve(eq, simplify=False) [Eq(Integral(1/sqrt(C1 + 2*Integral(g(_u), _u)), (_u, f(x))), C2 + x), Eq(Integral(1/sqrt(C1 + 2*Integral(g(_u), _u)), (_u, f(x))), C2 - x)] >>> from sympy import exp, log >>> eq = f(x).diff(x, 2) - exp(f(x)) + log(f(x)) >>> dsolve(eq, simplify=False) [Eq(Integral(1/sqrt(-2*_u*log(_u) + 2*_u + C1 + 2*exp(_u)), (_u, f(x))), C2 + x), Eq(Integral(1/sqrt(-2*_u*log(_u) + 2*_u + C1 + 2*exp(_u)), (_u, f(x))), C2 - x)] References ========== - http://eqworld.ipmnet.ru/en/solutions/ode/ode0301.pdf """ hint = "2nd_nonlinear_autonomous_conserved" has_integral = True order = [2] def _wilds(self, f, x, order): fy = Wild('fy', exclude=[0, f(x).diff(x), f(x).diff(x, 2)]) return (fy, ) def _equation(self, fx, x, order): fy = self.wilds()[0] return fx.diff(x, 2) + fy def _verify(self, fx): return self.ode_problem.is_autonomous def _get_general_solution(self, *, simplify_flag: bool = True): g = self.wilds_match()[0] fx = self.ode_problem.func x = self.ode_problem.sym u = Dummy('u') g = g.subs(fx, u) C1, C2 = self.ode_problem.get_numbered_constants(num=2) inside = -2*Integral(g, u) + C1 lhs = Integral(1/sqrt(inside), (u, fx)) return [Eq(lhs, C2 + x), Eq(lhs, C2 - x)] class Liouville(SinglePatternODESolver): r""" Solves 2nd order Liouville differential equations. The general form of a Liouville ODE is .. math:: \frac{d^2 y}{dx^2} + g(y) \left(\! \frac{dy}{dx}\!\right)^2 + h(x) \frac{dy}{dx}\text{.} The general solution is: >>> from sympy import Function, dsolve, Eq, pprint, diff >>> from sympy.abc import x >>> f, g, h = map(Function, ['f', 'g', 'h']) >>> genform = Eq(diff(f(x),x,x) + g(f(x))*diff(f(x),x)**2 + ... h(x)*diff(f(x),x), 0) >>> pprint(genform) 2 2 /d \ d d g(f(x))*|--(f(x))| + h(x)*--(f(x)) + ---(f(x)) = 0 \dx / dx 2 dx >>> pprint(dsolve(genform, f(x), hint='Liouville_Integral')) f(x) / / | | | / | / | | | | | - | h(x) dx | | g(y) dy | | | | | / | / C1 + C2* | e dx + | e dy = 0 | | / / Examples ======== >>> from sympy import Function, dsolve, Eq, pprint >>> from sympy.abc import x >>> f = Function('f') >>> pprint(dsolve(diff(f(x), x, x) + diff(f(x), x)**2/f(x) + ... diff(f(x), x)/x, f(x), hint='Liouville')) ________________ ________________ [f(x) = -\/ C1 + C2*log(x) , f(x) = \/ C1 + C2*log(x) ] References ========== - Goldstein and Braun, "Advanced Methods for the Solution of Differential Equations", pp. 98 - http://www.maplesoft.com/support/help/Maple/view.aspx?path=odeadvisor/Liouville # indirect doctest """ hint = "Liouville" has_integral = True order = [2] def _wilds(self, f, x, order): d = Wild('d', exclude=[f(x).diff(x), f(x).diff(x, 2)]) e = Wild('e', exclude=[f(x).diff(x)]) k = Wild('k', exclude=[f(x).diff(x)]) return d, e, k def _equation(self, fx, x, order): # Liouville ODE in the form # f(x).diff(x, 2) + g(f(x))*(f(x).diff(x))**2 + h(x)*f(x).diff(x) # See Goldstein and Braun, "Advanced Methods for the Solution of # Differential Equations", pg. 98 d, e, k = self.wilds() return d*fx.diff(x, 2) + e*fx.diff(x)**2 + k*fx.diff(x) def _verify(self, fx): d, e, k = self.wilds_match() self.y = Dummy('y') x = self.ode_problem.sym self.g = simplify(e/d).subs(fx, self.y) self.h = simplify(k/d).subs(fx, self.y) if self.y in self.h.free_symbols or x in self.g.free_symbols: return False return True def _get_general_solution(self, *, simplify_flag: bool = True): d, e, k = self.wilds_match() fx = self.ode_problem.func x = self.ode_problem.sym C1, C2 = self.ode_problem.get_numbered_constants(num=2) int = Integral(exp(Integral(self.g, self.y)), (self.y, None, fx)) gen_sol = Eq(int + C1*Integral(exp(-Integral(self.h, x)), x) + C2, 0) return [gen_sol] class Separable(SinglePatternODESolver): r""" Solves separable 1st order differential equations. This is any differential equation that can be written as `P(y) \tfrac{dy}{dx} = Q(x)`. The solution can then just be found by rearranging terms and integrating: `\int P(y) \,dy = \int Q(x) \,dx`. This hint uses :py:meth:`sympy.simplify.simplify.separatevars` as its back end, so if a separable equation is not caught by this solver, it is most likely the fault of that function. :py:meth:`~sympy.simplify.simplify.separatevars` is smart enough to do most expansion and factoring necessary to convert a separable equation `F(x, y)` into the proper form `P(x)\cdot{}Q(y)`. The general solution is:: >>> from sympy import Function, dsolve, Eq, pprint >>> from sympy.abc import x >>> a, b, c, d, f = map(Function, ['a', 'b', 'c', 'd', 'f']) >>> genform = Eq(a(x)*b(f(x))*f(x).diff(x), c(x)*d(f(x))) >>> pprint(genform) d a(x)*b(f(x))*--(f(x)) = c(x)*d(f(x)) dx >>> pprint(dsolve(genform, f(x), hint='separable_Integral')) f(x) / / | | | b(y) | c(x) | ---- dy = C1 + | ---- dx | d(y) | a(x) | | / / Examples ======== >>> from sympy import Function, dsolve, Eq >>> from sympy.abc import x >>> f = Function('f') >>> pprint(dsolve(Eq(f(x)*f(x).diff(x) + x, 3*x*f(x)**2), f(x), ... hint='separable', simplify=False)) / 2 \ 2 log\3*f (x) - 1/ x ---------------- = C1 + -- 6 2 References ========== - M. Tenenbaum & H. Pollard, "Ordinary Differential Equations", Dover 1963, pp. 52 # indirect doctest """ hint = "separable" has_integral = True order = [1] def _wilds(self, f, x, order): d = Wild('d', exclude=[f(x).diff(x), f(x).diff(x, 2)]) e = Wild('e', exclude=[f(x).diff(x)]) return d, e def _equation(self, fx, x, order): d, e = self.wilds() return d + e*fx.diff(x) def _verify(self, fx): d, e = self.wilds_match() self.y = Dummy('y') x = self.ode_problem.sym d = separatevars(d.subs(fx, self.y)) e = separatevars(e.subs(fx, self.y)) # m1[coeff]*m1[x]*m1[y] + m2[coeff]*m2[x]*m2[y]*y' self.m1 = separatevars(d, dict=True, symbols=(x, self.y)) self.m2 = separatevars(e, dict=True, symbols=(x, self.y)) if self.m1 and self.m2: return True return False def _get_match_object(self): fx = self.ode_problem.func x = self.ode_problem.sym return self.m1, self.m2, x, fx def _get_general_solution(self, *, simplify_flag: bool = True): m1, m2, x, fx = self._get_match_object() (C1,) = self.ode_problem.get_numbered_constants(num=1) int = Integral(m2['coeff']*m2[self.y]/m1[self.y], (self.y, None, fx)) gen_sol = Eq(int, Integral(-m1['coeff']*m1[x]/ m2[x], x) + C1) return [gen_sol] class SeparableReduced(Separable): r""" Solves a differential equation that can be reduced to the separable form. The general form of this equation is .. math:: y' + (y/x) H(x^n y) = 0\text{}. This can be solved by substituting `u(y) = x^n y`. The equation then reduces to the separable form `\frac{u'}{u (\mathrm{power} - H(u))} - \frac{1}{x} = 0`. The general solution is: >>> from sympy import Function, dsolve, pprint >>> from sympy.abc import x, n >>> f, g = map(Function, ['f', 'g']) >>> genform = f(x).diff(x) + (f(x)/x)*g(x**n*f(x)) >>> pprint(genform) / n \ d f(x)*g\x *f(x)/ --(f(x)) + --------------- dx x >>> pprint(dsolve(genform, hint='separable_reduced')) n x *f(x) / | | 1 | ------------ dy = C1 + log(x) | y*(n - g(y)) | / See Also ======== :obj:`sympy.solvers.ode.single.Separable` Examples ======== >>> from sympy import dsolve, Function, pprint >>> from sympy.abc import x >>> f = Function('f') >>> d = f(x).diff(x) >>> eq = (x - x**2*f(x))*d - f(x) >>> dsolve(eq, hint='separable_reduced') [Eq(f(x), (1 - sqrt(C1*x**2 + 1))/x), Eq(f(x), (sqrt(C1*x**2 + 1) + 1)/x)] >>> pprint(dsolve(eq, hint='separable_reduced')) ___________ ___________ / 2 / 2 1 - \/ C1*x + 1 \/ C1*x + 1 + 1 [f(x) = ------------------, f(x) = ------------------] x x References ========== - Joel Moses, "Symbolic Integration - The Stormy Decade", Communications of the ACM, Volume 14, Number 8, August 1971, pp. 558 """ hint = "separable_reduced" has_integral = True order = [1] def _degree(self, expr, x): # Made this function to calculate the degree of # x in an expression. If expr will be of form # x**p*y, (wheare p can be variables/rationals) then it # will return p. for val in expr: if val.has(x): if isinstance(val, Pow) and val.as_base_exp()[0] == x: return (val.as_base_exp()[1]) elif val == x: return (val.as_base_exp()[1]) else: return self._degree(val.args, x) return 0 def _powers(self, expr): # this function will return all the different relative power of x w.r.t f(x). # expr = x**p * f(x)**q then it will return {p/q}. pows = set() fx = self.ode_problem.func x = self.ode_problem.sym self.y = Dummy('y') if isinstance(expr, Add): exprs = expr.atoms(Add) elif isinstance(expr, Mul): exprs = expr.atoms(Mul) elif isinstance(expr, Pow): exprs = expr.atoms(Pow) else: exprs = {expr} for arg in exprs: if arg.has(x): _, u = arg.as_independent(x, fx) pow = self._degree((u.subs(fx, self.y), ), x)/self._degree((u.subs(fx, self.y), ), self.y) pows.add(pow) return pows def _verify(self, fx): num, den = self.wilds_match() x = self.ode_problem.sym factor = simplify(x/fx*num/den) # Try representing factor in terms of x^n*y # where n is lowest power of x in factor; # first remove terms like sqrt(2)*3 from factor.atoms(Mul) num, dem = factor.as_numer_denom() num = expand(num) dem = expand(dem) pows = self._powers(num) pows.update(self._powers(dem)) pows = list(pows) if(len(pows)==1) and pows[0]!=zoo: self.t = Dummy('t') self.r2 = {'t': self.t} num = num.subs(x**pows[0]*fx, self.t) dem = dem.subs(x**pows[0]*fx, self.t) test = num/dem free = test.free_symbols if len(free) == 1 and free.pop() == self.t: self.r2.update({'power' : pows[0], 'u' : test}) return True return False return False def _get_match_object(self): fx = self.ode_problem.func x = self.ode_problem.sym u = self.r2['u'].subs(self.r2['t'], self.y) ycoeff = 1/(self.y*(self.r2['power'] - u)) m1 = {self.y: 1, x: -1/x, 'coeff': 1} m2 = {self.y: ycoeff, x: 1, 'coeff': 1} return m1, m2, x, x**self.r2['power']*fx class HomogeneousCoeffSubsDepDivIndep(SinglePatternODESolver): r""" Solves a 1st order differential equation with homogeneous coefficients using the substitution `u_1 = \frac{\text{<dependent variable>}}{\text{<independent variable>}}`. This is a differential equation .. math:: P(x, y) + Q(x, y) dy/dx = 0 such that `P` and `Q` are homogeneous and of the same order. A function `F(x, y)` is homogeneous of order `n` if `F(x t, y t) = t^n F(x, y)`. Equivalently, `F(x, y)` can be rewritten as `G(y/x)` or `H(x/y)`. See also the docstring of :py:meth:`~sympy.solvers.ode.homogeneous_order`. If the coefficients `P` and `Q` in the differential equation above are homogeneous functions of the same order, then it can be shown that the substitution `y = u_1 x` (i.e. `u_1 = y/x`) will turn the differential equation into an equation separable in the variables `x` and `u`. If `h(u_1)` is the function that results from making the substitution `u_1 = f(x)/x` on `P(x, f(x))` and `g(u_2)` is the function that results from the substitution on `Q(x, f(x))` in the differential equation `P(x, f(x)) + Q(x, f(x)) f'(x) = 0`, then the general solution is:: >>> from sympy import Function, dsolve, pprint >>> from sympy.abc import x >>> f, g, h = map(Function, ['f', 'g', 'h']) >>> genform = g(f(x)/x) + h(f(x)/x)*f(x).diff(x) >>> pprint(genform) /f(x)\ /f(x)\ d g|----| + h|----|*--(f(x)) \ x / \ x / dx >>> pprint(dsolve(genform, f(x), ... hint='1st_homogeneous_coeff_subs_dep_div_indep_Integral')) f(x) ---- x / | | -h(u1) log(x) = C1 + | ---------------- d(u1) | u1*h(u1) + g(u1) | / Where `u_1 h(u_1) + g(u_1) \ne 0` and `x \ne 0`. See also the docstrings of :obj:`~sympy.solvers.ode.single.HomogeneousCoeffBest` and :obj:`~sympy.solvers.ode.single.HomogeneousCoeffSubsIndepDivDep`. Examples ======== >>> from sympy import Function, dsolve >>> from sympy.abc import x >>> f = Function('f') >>> pprint(dsolve(2*x*f(x) + (x**2 + f(x)**2)*f(x).diff(x), f(x), ... hint='1st_homogeneous_coeff_subs_dep_div_indep', simplify=False)) / 3 \ |3*f(x) f (x)| log|------ + -----| | x 3 | \ x / log(x) = log(C1) - ------------------- 3 References ========== - https://en.wikipedia.org/wiki/Homogeneous_differential_equation - M. Tenenbaum & H. Pollard, "Ordinary Differential Equations", Dover 1963, pp. 59 # indirect doctest """ hint = "1st_homogeneous_coeff_subs_dep_div_indep" has_integral = True order = [1] def _wilds(self, f, x, order): d = Wild('d', exclude=[f(x).diff(x), f(x).diff(x, 2)]) e = Wild('e', exclude=[f(x).diff(x)]) return d, e def _equation(self, fx, x, order): d, e = self.wilds() return d + e*fx.diff(x) def _verify(self, fx): self.d, self.e = self.wilds_match() self.y = Dummy('y') x = self.ode_problem.sym self.d = separatevars(self.d.subs(fx, self.y)) self.e = separatevars(self.e.subs(fx, self.y)) ordera = homogeneous_order(self.d, x, self.y) orderb = homogeneous_order(self.e, x, self.y) if ordera == orderb and ordera is not None: self.u = Dummy('u') if simplify((self.d + self.u*self.e).subs({x: 1, self.y: self.u})) != 0: return True return False return False def _get_match_object(self): fx = self.ode_problem.func x = self.ode_problem.sym self.u1 = Dummy('u1') xarg = 0 yarg = 0 return [self.d, self.e, fx, x, self.u, self.u1, self.y, xarg, yarg] def _get_general_solution(self, *, simplify_flag: bool = True): d, e, fx, x, u, u1, y, xarg, yarg = self._get_match_object() (C1,) = self.ode_problem.get_numbered_constants(num=1) int = Integral( (-e/(d + u1*e)).subs({x: 1, y: u1}), (u1, None, fx/x)) sol = logcombine(Eq(log(x), int + log(C1)), force=True) gen_sol = sol.subs(fx, u).subs(((u, u - yarg), (x, x - xarg), (u, fx))) return [gen_sol] class HomogeneousCoeffSubsIndepDivDep(SinglePatternODESolver): r""" Solves a 1st order differential equation with homogeneous coefficients using the substitution `u_2 = \frac{\text{<independent variable>}}{\text{<dependent variable>}}`. This is a differential equation .. math:: P(x, y) + Q(x, y) dy/dx = 0 such that `P` and `Q` are homogeneous and of the same order. A function `F(x, y)` is homogeneous of order `n` if `F(x t, y t) = t^n F(x, y)`. Equivalently, `F(x, y)` can be rewritten as `G(y/x)` or `H(x/y)`. See also the docstring of :py:meth:`~sympy.solvers.ode.homogeneous_order`. If the coefficients `P` and `Q` in the differential equation above are homogeneous functions of the same order, then it can be shown that the substitution `x = u_2 y` (i.e. `u_2 = x/y`) will turn the differential equation into an equation separable in the variables `y` and `u_2`. If `h(u_2)` is the function that results from making the substitution `u_2 = x/f(x)` on `P(x, f(x))` and `g(u_2)` is the function that results from the substitution on `Q(x, f(x))` in the differential equation `P(x, f(x)) + Q(x, f(x)) f'(x) = 0`, then the general solution is: >>> from sympy import Function, dsolve, pprint >>> from sympy.abc import x >>> f, g, h = map(Function, ['f', 'g', 'h']) >>> genform = g(x/f(x)) + h(x/f(x))*f(x).diff(x) >>> pprint(genform) / x \ / x \ d g|----| + h|----|*--(f(x)) \f(x)/ \f(x)/ dx >>> pprint(dsolve(genform, f(x), ... hint='1st_homogeneous_coeff_subs_indep_div_dep_Integral')) x ---- f(x) / | | -g(u1) | ---------------- d(u1) | u1*g(u1) + h(u1) | / <BLANKLINE> f(x) = C1*e Where `u_1 g(u_1) + h(u_1) \ne 0` and `f(x) \ne 0`. See also the docstrings of :obj:`~sympy.solvers.ode.single.HomogeneousCoeffBest` and :obj:`~sympy.solvers.ode.single.HomogeneousCoeffSubsDepDivIndep`. Examples ======== >>> from sympy import Function, pprint, dsolve >>> from sympy.abc import x >>> f = Function('f') >>> pprint(dsolve(2*x*f(x) + (x**2 + f(x)**2)*f(x).diff(x), f(x), ... hint='1st_homogeneous_coeff_subs_indep_div_dep', ... simplify=False)) / 2 \ | 3*x | log|----- + 1| | 2 | \f (x) / log(f(x)) = log(C1) - -------------- 3 References ========== - https://en.wikipedia.org/wiki/Homogeneous_differential_equation - M. Tenenbaum & H. Pollard, "Ordinary Differential Equations", Dover 1963, pp. 59 # indirect doctest """ hint = "1st_homogeneous_coeff_subs_indep_div_dep" has_integral = True order = [1] def _wilds(self, f, x, order): d = Wild('d', exclude=[f(x).diff(x), f(x).diff(x, 2)]) e = Wild('e', exclude=[f(x).diff(x)]) return d, e def _equation(self, fx, x, order): d, e = self.wilds() return d + e*fx.diff(x) def _verify(self, fx): self.d, self.e = self.wilds_match() self.y = Dummy('y') x = self.ode_problem.sym self.d = separatevars(self.d.subs(fx, self.y)) self.e = separatevars(self.e.subs(fx, self.y)) ordera = homogeneous_order(self.d, x, self.y) orderb = homogeneous_order(self.e, x, self.y) if ordera == orderb and ordera is not None: self.u = Dummy('u') if simplify((self.e + self.u*self.d).subs({x: self.u, self.y: 1})) != 0: return True return False return False def _get_match_object(self): fx = self.ode_problem.func x = self.ode_problem.sym self.u1 = Dummy('u1') xarg = 0 yarg = 0 return [self.d, self.e, fx, x, self.u, self.u1, self.y, xarg, yarg] def _get_general_solution(self, *, simplify_flag: bool = True): d, e, fx, x, u, u1, y, xarg, yarg = self._get_match_object() (C1,) = self.ode_problem.get_numbered_constants(num=1) int = Integral(simplify((-d/(e + u1*d)).subs({x: u1, y: 1})), (u1, None, x/fx)) # type: ignore sol = logcombine(Eq(log(fx), int + log(C1)), force=True) gen_sol = sol.subs(fx, u).subs(((u, u - yarg), (x, x - xarg), (u, fx))) return [gen_sol] class HomogeneousCoeffBest(HomogeneousCoeffSubsIndepDivDep, HomogeneousCoeffSubsDepDivIndep): r""" Returns the best solution to an ODE from the two hints ``1st_homogeneous_coeff_subs_dep_div_indep`` and ``1st_homogeneous_coeff_subs_indep_div_dep``. This is as determined by :py:meth:`~sympy.solvers.ode.ode.ode_sol_simplicity`. See the :obj:`~sympy.solvers.ode.single.HomogeneousCoeffSubsIndepDivDep` and :obj:`~sympy.solvers.ode.single.HomogeneousCoeffSubsDepDivIndep` docstrings for more information on these hints. Note that there is no ``ode_1st_homogeneous_coeff_best_Integral`` hint. Examples ======== >>> from sympy import Function, dsolve, pprint >>> from sympy.abc import x >>> f = Function('f') >>> pprint(dsolve(2*x*f(x) + (x**2 + f(x)**2)*f(x).diff(x), f(x), ... hint='1st_homogeneous_coeff_best', simplify=False)) / 2 \ | 3*x | log|----- + 1| | 2 | \f (x) / log(f(x)) = log(C1) - -------------- 3 References ========== - https://en.wikipedia.org/wiki/Homogeneous_differential_equation - M. Tenenbaum & H. Pollard, "Ordinary Differential Equations", Dover 1963, pp. 59 # indirect doctest """ hint = "1st_homogeneous_coeff_best" has_integral = False order = [1] def _verify(self, fx): if HomogeneousCoeffSubsIndepDivDep._verify(self, fx) and HomogeneousCoeffSubsDepDivIndep._verify(self, fx): return True return False def _get_general_solution(self, *, simplify_flag: bool = True): # There are two substitutions that solve the equation, u1=y/x and u2=x/y # # They produce different integrals, so try them both and see which # # one is easier sol1 = HomogeneousCoeffSubsIndepDivDep._get_general_solution(self) sol2 = HomogeneousCoeffSubsDepDivIndep._get_general_solution(self) fx = self.ode_problem.func if simplify_flag: sol1 = odesimp(self.ode_problem.eq, *sol1, fx, "1st_homogeneous_coeff_subs_indep_div_dep") sol2 = odesimp(self.ode_problem.eq, *sol2, fx, "1st_homogeneous_coeff_subs_dep_div_indep") return min([sol1, sol2], key=lambda x: ode_sol_simplicity(x, fx, trysolving=not simplify)) class LinearCoefficients(HomogeneousCoeffBest): r""" Solves a differential equation with linear coefficients. The general form of a differential equation with linear coefficients is .. math:: y' + F\left(\!\frac{a_1 x + b_1 y + c_1}{a_2 x + b_2 y + c_2}\!\right) = 0\text{,} where `a_1`, `b_1`, `c_1`, `a_2`, `b_2`, `c_2` are constants and `a_1 b_2 - a_2 b_1 \ne 0`. This can be solved by substituting: .. math:: x = x' + \frac{b_2 c_1 - b_1 c_2}{a_2 b_1 - a_1 b_2} y = y' + \frac{a_1 c_2 - a_2 c_1}{a_2 b_1 - a_1 b_2}\text{.} This substitution reduces the equation to a homogeneous differential equation. See Also ======== :obj:`sympy.solvers.ode.single.HomogeneousCoeffBest` :obj:`sympy.solvers.ode.single.HomogeneousCoeffSubsIndepDivDep` :obj:`sympy.solvers.ode.single.HomogeneousCoeffSubsDepDivIndep` Examples ======== >>> from sympy import dsolve, Function, pprint >>> from sympy.abc import x >>> f = Function('f') >>> df = f(x).diff(x) >>> eq = (x + f(x) + 1)*df + (f(x) - 6*x + 1) >>> dsolve(eq, hint='linear_coefficients') [Eq(f(x), -x - sqrt(C1 + 7*x**2) - 1), Eq(f(x), -x + sqrt(C1 + 7*x**2) - 1)] >>> pprint(dsolve(eq, hint='linear_coefficients')) ___________ ___________ / 2 / 2 [f(x) = -x - \/ C1 + 7*x - 1, f(x) = -x + \/ C1 + 7*x - 1] References ========== - Joel Moses, "Symbolic Integration - The Stormy Decade", Communications of the ACM, Volume 14, Number 8, August 1971, pp. 558 """ hint = "linear_coefficients" has_integral = True order = [1] def _wilds(self, f, x, order): d = Wild('d', exclude=[f(x).diff(x), f(x).diff(x, 2)]) e = Wild('e', exclude=[f(x).diff(x)]) return d, e def _equation(self, fx, x, order): d, e = self.wilds() return d + e*fx.diff(x) def _verify(self, fx): self.d, self.e = self.wilds_match() a, b = self.wilds() F = self.d/self.e x = self.ode_problem.sym params = self._linear_coeff_match(F, fx) if params: self.xarg, self.yarg = params u = Dummy('u') t = Dummy('t') self.y = Dummy('y') # Dummy substitution for df and f(x). dummy_eq = self.ode_problem.eq.subs(((fx.diff(x), t), (fx, u))) reps = ((x, x + self.xarg), (u, u + self.yarg), (t, fx.diff(x)), (u, fx)) dummy_eq = simplify(dummy_eq.subs(reps)) # get the re-cast values for e and d r2 = collect(expand(dummy_eq), [fx.diff(x), fx]).match(a*fx.diff(x) + b) if r2: self.d, self.e = r2[b], r2[a] orderd = homogeneous_order(self.d, x, fx) ordere = homogeneous_order(self.e, x, fx) if orderd == ordere and orderd is not None: self.d = self.d.subs(fx, self.y) self.e = self.e.subs(fx, self.y) return True return False return False def _linear_coeff_match(self, expr, func): r""" Helper function to match hint ``linear_coefficients``. Matches the expression to the form `(a_1 x + b_1 f(x) + c_1)/(a_2 x + b_2 f(x) + c_2)` where the following conditions hold: 1. `a_1`, `b_1`, `c_1`, `a_2`, `b_2`, `c_2` are Rationals; 2. `c_1` or `c_2` are not equal to zero; 3. `a_2 b_1 - a_1 b_2` is not equal to zero. Return ``xarg``, ``yarg`` where 1. ``xarg`` = `(b_2 c_1 - b_1 c_2)/(a_2 b_1 - a_1 b_2)` 2. ``yarg`` = `(a_1 c_2 - a_2 c_1)/(a_2 b_1 - a_1 b_2)` Examples ======== >>> from sympy import Function, sin >>> from sympy.abc import x >>> from sympy.solvers.ode.single import LinearCoefficients >>> f = Function('f') >>> eq = (-25*f(x) - 8*x + 62)/(4*f(x) + 11*x - 11) >>> obj = LinearCoefficients(eq) >>> obj._linear_coeff_match(eq, f(x)) (1/9, 22/9) >>> eq = sin((-5*f(x) - 8*x + 6)/(4*f(x) + x - 1)) >>> obj = LinearCoefficients(eq) >>> obj._linear_coeff_match(eq, f(x)) (19/27, 2/27) >>> eq = sin(f(x)/x) >>> obj = LinearCoefficients(eq) >>> obj._linear_coeff_match(eq, f(x)) """ f = func.func x = func.args[0] def abc(eq): r''' Internal function of _linear_coeff_match that returns Rationals a, b, c if eq is a*x + b*f(x) + c, else None. ''' eq = _mexpand(eq) c = eq.as_independent(x, f(x), as_Add=True)[0] if not c.is_Rational: return a = eq.coeff(x) if not a.is_Rational: return b = eq.coeff(f(x)) if not b.is_Rational: return if eq == a*x + b*f(x) + c: return a, b, c def match(arg): r''' Internal function of _linear_coeff_match that returns Rationals a1, b1, c1, a2, b2, c2 and a2*b1 - a1*b2 of the expression (a1*x + b1*f(x) + c1)/(a2*x + b2*f(x) + c2) if one of c1 or c2 and a2*b1 - a1*b2 is non-zero, else None. ''' n, d = arg.together().as_numer_denom() m = abc(n) if m is not None: a1, b1, c1 = m m = abc(d) if m is not None: a2, b2, c2 = m d = a2*b1 - a1*b2 if (c1 or c2) and d: return a1, b1, c1, a2, b2, c2, d m = [fi.args[0] for fi in expr.atoms(Function) if fi.func != f and len(fi.args) == 1 and not fi.args[0].is_Function] or {expr} m1 = match(m.pop()) if m1 and all(match(mi) == m1 for mi in m): a1, b1, c1, a2, b2, c2, denom = m1 return (b2*c1 - b1*c2)/denom, (a1*c2 - a2*c1)/denom def _get_match_object(self): fx = self.ode_problem.func x = self.ode_problem.sym self.u1 = Dummy('u1') u = Dummy('u') return [self.d, self.e, fx, x, u, self.u1, self.y, self.xarg, self.yarg] class NthOrderReducible(SingleODESolver): r""" Solves ODEs that only involve derivatives of the dependent variable using a substitution of the form `f^n(x) = g(x)`. For example any second order ODE of the form `f''(x) = h(f'(x), x)` can be transformed into a pair of 1st order ODEs `g'(x) = h(g(x), x)` and `f'(x) = g(x)`. Usually the 1st order ODE for `g` is easier to solve. If that gives an explicit solution for `g` then `f` is found simply by integration. Examples ======== >>> from sympy import Function, dsolve, Eq >>> from sympy.abc import x >>> f = Function('f') >>> eq = Eq(x*f(x).diff(x)**2 + f(x).diff(x, 2), 0) >>> dsolve(eq, f(x), hint='nth_order_reducible') ... # doctest: +NORMALIZE_WHITESPACE Eq(f(x), C1 - sqrt(-1/C2)*log(-C2*sqrt(-1/C2) + x) + sqrt(-1/C2)*log(C2*sqrt(-1/C2) + x)) """ hint = "nth_order_reducible" has_integral = False def _matches(self): # Any ODE that can be solved with a substitution and # repeated integration e.g.: # `d^2/dx^2(y) + x*d/dx(y) = constant #f'(x) must be finite for this to work eq = self.ode_problem.eq_preprocessed func = self.ode_problem.func x = self.ode_problem.sym r""" Matches any differential equation that can be rewritten with a smaller order. Only derivatives of ``func`` alone, wrt a single variable, are considered, and only in them should ``func`` appear. """ # ODE only handles functions of 1 variable so this affirms that state assert len(func.args) == 1 vc = [d.variable_count[0] for d in eq.atoms(Derivative) if d.expr == func and len(d.variable_count) == 1] ords = [c for v, c in vc if v == x] if len(ords) < 2: return False self.smallest = min(ords) # make sure func does not appear outside of derivatives D = Dummy() if eq.subs(func.diff(x, self.smallest), D).has(func): return False return True def _get_general_solution(self, *, simplify_flag: bool = True): eq = self.ode_problem.eq f = self.ode_problem.func.func x = self.ode_problem.sym n = self.smallest # get a unique function name for g names = [a.name for a in eq.atoms(AppliedUndef)] while True: name = Dummy().name if name not in names: g = Function(name) break w = f(x).diff(x, n) geq = eq.subs(w, g(x)) gsol = dsolve(geq, g(x)) if not isinstance(gsol, list): gsol = [gsol] # Might be multiple solutions to the reduced ODE: fsol = [] for gsoli in gsol: fsoli = dsolve(gsoli.subs(g(x), w), f(x)) # or do integration n times fsol.append(fsoli) return fsol class SecondHypergeometric(SingleODESolver): r""" Solves 2nd order linear differential equations. It computes special function solutions which can be expressed using the 2F1, 1F1 or 0F1 hypergeometric functions. .. math:: y'' + A(x) y' + B(x) y = 0\text{,} where `A` and `B` are rational functions. These kinds of differential equations have solution of non-Liouvillian form. Given linear ODE can be obtained from 2F1 given by .. math:: (x^2 - x) y'' + ((a + b + 1) x - c) y' + b a y = 0\text{,} where {a, b, c} are arbitrary constants. Notes ===== The algorithm should find any solution of the form .. math:: y = P(x) _pF_q(..; ..;\frac{\alpha x^k + \beta}{\gamma x^k + \delta})\text{,} where pFq is any of 2F1, 1F1 or 0F1 and `P` is an "arbitrary function". Currently only the 2F1 case is implemented in SymPy but the other cases are described in the paper and could be implemented in future (contributions welcome!). Examples ======== >>> from sympy import Function, dsolve, pprint >>> from sympy.abc import x >>> f = Function('f') >>> eq = (x*x - x)*f(x).diff(x,2) + (5*x - 1)*f(x).diff(x) + 4*f(x) >>> pprint(dsolve(eq, f(x), '2nd_hypergeometric')) _ / / 4 \\ |_ /-1, -1 | \ |C1 + C2*|log(x) + -----||* | | | x| \ \ x + 1// 2 1 \ 1 | / f(x) = -------------------------------------------- 3 (x - 1) References ========== - "Non-Liouvillian solutions for second order linear ODEs" by L. Chan, E.S. Cheb-Terrab """ hint = "2nd_hypergeometric" has_integral = True def _matches(self): eq = self.ode_problem.eq_preprocessed func = self.ode_problem.func r = match_2nd_hypergeometric(eq, func) self.match_object = None if r: A, B = r d = equivalence_hypergeometric(A, B, func) if d: if d['type'] == "2F1": self.match_object = match_2nd_2F1_hypergeometric(d['I0'], d['k'], d['sing_point'], func) if self.match_object is not None: self.match_object.update({'A':A, 'B':B}) # We can extend it for 1F1 and 0F1 type also. return self.match_object is not None def _get_general_solution(self, *, simplify_flag: bool = True): eq = self.ode_problem.eq func = self.ode_problem.func if self.match_object['type'] == "2F1": sol = get_sol_2F1_hypergeometric(eq, func, self.match_object) if sol is None: raise NotImplementedError("The given ODE " + str(eq) + " cannot be solved by" + " the hypergeometric method") return [sol] class NthLinearConstantCoeffHomogeneous(SingleODESolver): r""" Solves an `n`\th order linear homogeneous differential equation with constant coefficients. This is an equation of the form .. math:: a_n f^{(n)}(x) + a_{n-1} f^{(n-1)}(x) + \cdots + a_1 f'(x) + a_0 f(x) = 0\text{.} These equations can be solved in a general manner, by taking the roots of the characteristic equation `a_n m^n + a_{n-1} m^{n-1} + \cdots + a_1 m + a_0 = 0`. The solution will then be the sum of `C_n x^i e^{r x}` terms, for each where `C_n` is an arbitrary constant, `r` is a root of the characteristic equation and `i` is one of each from 0 to the multiplicity of the root - 1 (for example, a root 3 of multiplicity 2 would create the terms `C_1 e^{3 x} + C_2 x e^{3 x}`). The exponential is usually expanded for complex roots using Euler's equation `e^{I x} = \cos(x) + I \sin(x)`. Complex roots always come in conjugate pairs in polynomials with real coefficients, so the two roots will be represented (after simplifying the constants) as `e^{a x} \left(C_1 \cos(b x) + C_2 \sin(b x)\right)`. If SymPy cannot find exact roots to the characteristic equation, a :py:class:`~sympy.polys.rootoftools.ComplexRootOf` instance will be return instead. >>> from sympy import Function, dsolve >>> from sympy.abc import x >>> f = Function('f') >>> dsolve(f(x).diff(x, 5) + 10*f(x).diff(x) - 2*f(x), f(x), ... hint='nth_linear_constant_coeff_homogeneous') ... # doctest: +NORMALIZE_WHITESPACE Eq(f(x), C5*exp(x*CRootOf(_x**5 + 10*_x - 2, 0)) + (C1*sin(x*im(CRootOf(_x**5 + 10*_x - 2, 1))) + C2*cos(x*im(CRootOf(_x**5 + 10*_x - 2, 1))))*exp(x*re(CRootOf(_x**5 + 10*_x - 2, 1))) + (C3*sin(x*im(CRootOf(_x**5 + 10*_x - 2, 3))) + C4*cos(x*im(CRootOf(_x**5 + 10*_x - 2, 3))))*exp(x*re(CRootOf(_x**5 + 10*_x - 2, 3)))) Note that because this method does not involve integration, there is no ``nth_linear_constant_coeff_homogeneous_Integral`` hint. Examples ======== >>> from sympy import Function, dsolve, pprint >>> from sympy.abc import x >>> f = Function('f') >>> pprint(dsolve(f(x).diff(x, 4) + 2*f(x).diff(x, 3) - ... 2*f(x).diff(x, 2) - 6*f(x).diff(x) + 5*f(x), f(x), ... hint='nth_linear_constant_coeff_homogeneous')) x -2*x f(x) = (C1 + C2*x)*e + (C3*sin(x) + C4*cos(x))*e References ========== - https://en.wikipedia.org/wiki/Linear_differential_equation section: Nonhomogeneous_equation_with_constant_coefficients - M. Tenenbaum & H. Pollard, "Ordinary Differential Equations", Dover 1963, pp. 211 # indirect doctest """ hint = "nth_linear_constant_coeff_homogeneous" has_integral = False def _matches(self): eq = self.ode_problem.eq_high_order_free func = self.ode_problem.func order = self.ode_problem.order x = self.ode_problem.sym self.r = self.ode_problem.get_linear_coefficients(eq, func, order) if order and self.r and not any(self.r[i].has(x) for i in self.r if i >= 0): if not self.r[-1]: return True else: return False return False def _get_general_solution(self, *, simplify_flag: bool = True): fx = self.ode_problem.func order = self.ode_problem.order roots, collectterms = _get_const_characteristic_eq_sols(self.r, fx, order) # A generator of constants constants = self.ode_problem.get_numbered_constants(num=len(roots)) gsol = Add(*[i*j for (i, j) in zip(constants, roots)]) gsol = Eq(fx, gsol) if simplify_flag: gsol = _get_simplified_sol([gsol], fx, collectterms) return [gsol] class NthLinearConstantCoeffVariationOfParameters(SingleODESolver): r""" Solves an `n`\th order linear differential equation with constant coefficients using the method of variation of parameters. This method works on any differential equations of the form .. math:: f^{(n)}(x) + a_{n-1} f^{(n-1)}(x) + \cdots + a_1 f'(x) + a_0 f(x) = P(x)\text{.} This method works by assuming that the particular solution takes the form .. math:: \sum_{x=1}^{n} c_i(x) y_i(x)\text{,} where `y_i` is the `i`\th solution to the homogeneous equation. The solution is then solved using Wronskian's and Cramer's Rule. The particular solution is given by .. math:: \sum_{x=1}^n \left( \int \frac{W_i(x)}{W(x)} \,dx \right) y_i(x) \text{,} where `W(x)` is the Wronskian of the fundamental system (the system of `n` linearly independent solutions to the homogeneous equation), and `W_i(x)` is the Wronskian of the fundamental system with the `i`\th column replaced with `[0, 0, \cdots, 0, P(x)]`. This method is general enough to solve any `n`\th order inhomogeneous linear differential equation with constant coefficients, but sometimes SymPy cannot simplify the Wronskian well enough to integrate it. If this method hangs, try using the ``nth_linear_constant_coeff_variation_of_parameters_Integral`` hint and simplifying the integrals manually. Also, prefer using ``nth_linear_constant_coeff_undetermined_coefficients`` when it applies, because it does not use integration, making it faster and more reliable. Warning, using simplify=False with 'nth_linear_constant_coeff_variation_of_parameters' in :py:meth:`~sympy.solvers.ode.dsolve` may cause it to hang, because it will not attempt to simplify the Wronskian before integrating. It is recommended that you only use simplify=False with 'nth_linear_constant_coeff_variation_of_parameters_Integral' for this method, especially if the solution to the homogeneous equation has trigonometric functions in it. Examples ======== >>> from sympy import Function, dsolve, pprint, exp, log >>> from sympy.abc import x >>> f = Function('f') >>> pprint(dsolve(f(x).diff(x, 3) - 3*f(x).diff(x, 2) + ... 3*f(x).diff(x) - f(x) - exp(x)*log(x), f(x), ... hint='nth_linear_constant_coeff_variation_of_parameters')) / / / x*log(x) 11*x\\\ x f(x) = |C1 + x*|C2 + x*|C3 + -------- - ----|||*e \ \ \ 6 36 /// References ========== - https://en.wikipedia.org/wiki/Variation_of_parameters - http://planetmath.org/VariationOfParameters - M. Tenenbaum & H. Pollard, "Ordinary Differential Equations", Dover 1963, pp. 233 # indirect doctest """ hint = "nth_linear_constant_coeff_variation_of_parameters" has_integral = True def _matches(self): eq = self.ode_problem.eq_high_order_free func = self.ode_problem.func order = self.ode_problem.order x = self.ode_problem.sym self.r = self.ode_problem.get_linear_coefficients(eq, func, order) if order and self.r and not any(self.r[i].has(x) for i in self.r if i >= 0): if self.r[-1]: return True else: return False return False def _get_general_solution(self, *, simplify_flag: bool = True): eq = self.ode_problem.eq_high_order_free f = self.ode_problem.func.func x = self.ode_problem.sym order = self.ode_problem.order roots, collectterms = _get_const_characteristic_eq_sols(self.r, f(x), order) # A generator of constants constants = self.ode_problem.get_numbered_constants(num=len(roots)) homogen_sol = Add(*[i*j for (i, j) in zip(constants, roots)]) homogen_sol = Eq(f(x), homogen_sol) homogen_sol = _solve_variation_of_parameters(eq, f(x), roots, homogen_sol, order, self.r, simplify_flag) if simplify_flag: homogen_sol = _get_simplified_sol([homogen_sol], f(x), collectterms) return [homogen_sol] class NthLinearConstantCoeffUndeterminedCoefficients(SingleODESolver): r""" Solves an `n`\th order linear differential equation with constant coefficients using the method of undetermined coefficients. This method works on differential equations of the form .. math:: a_n f^{(n)}(x) + a_{n-1} f^{(n-1)}(x) + \cdots + a_1 f'(x) + a_0 f(x) = P(x)\text{,} where `P(x)` is a function that has a finite number of linearly independent derivatives. Functions that fit this requirement are finite sums functions of the form `a x^i e^{b x} \sin(c x + d)` or `a x^i e^{b x} \cos(c x + d)`, where `i` is a non-negative integer and `a`, `b`, `c`, and `d` are constants. For example any polynomial in `x`, functions like `x^2 e^{2 x}`, `x \sin(x)`, and `e^x \cos(x)` can all be used. Products of `\sin`'s and `\cos`'s have a finite number of derivatives, because they can be expanded into `\sin(a x)` and `\cos(b x)` terms. However, SymPy currently cannot do that expansion, so you will need to manually rewrite the expression in terms of the above to use this method. So, for example, you will need to manually convert `\sin^2(x)` into `(1 + \cos(2 x))/2` to properly apply the method of undetermined coefficients on it. This method works by creating a trial function from the expression and all of its linear independent derivatives and substituting them into the original ODE. The coefficients for each term will be a system of linear equations, which are be solved for and substituted, giving the solution. If any of the trial functions are linearly dependent on the solution to the homogeneous equation, they are multiplied by sufficient `x` to make them linearly independent. Examples ======== >>> from sympy import Function, dsolve, pprint, exp, cos >>> from sympy.abc import x >>> f = Function('f') >>> pprint(dsolve(f(x).diff(x, 2) + 2*f(x).diff(x) + f(x) - ... 4*exp(-x)*x**2 + cos(2*x), f(x), ... hint='nth_linear_constant_coeff_undetermined_coefficients')) / / 3\\ | | x || -x 4*sin(2*x) 3*cos(2*x) f(x) = |C1 + x*|C2 + --||*e - ---------- + ---------- \ \ 3 // 25 25 References ========== - https://en.wikipedia.org/wiki/Method_of_undetermined_coefficients - M. Tenenbaum & H. Pollard, "Ordinary Differential Equations", Dover 1963, pp. 221 # indirect doctest """ hint = "nth_linear_constant_coeff_undetermined_coefficients" has_integral = False def _matches(self): eq = self.ode_problem.eq_high_order_free func = self.ode_problem.func order = self.ode_problem.order x = self.ode_problem.sym self.r = self.ode_problem.get_linear_coefficients(eq, func, order) does_match = False if order and self.r and not any(self.r[i].has(x) for i in self.r if i >= 0): if self.r[-1]: eq_homogeneous = Add(eq, -self.r[-1]) undetcoeff = _undetermined_coefficients_match(self.r[-1], x, func, eq_homogeneous) if undetcoeff['test']: self.trialset = undetcoeff['trialset'] does_match = True return does_match def _get_general_solution(self, *, simplify_flag: bool = True): eq = self.ode_problem.eq f = self.ode_problem.func.func x = self.ode_problem.sym order = self.ode_problem.order roots, collectterms = _get_const_characteristic_eq_sols(self.r, f(x), order) # A generator of constants constants = self.ode_problem.get_numbered_constants(num=len(roots)) homogen_sol = Add(*[i*j for (i, j) in zip(constants, roots)]) homogen_sol = Eq(f(x), homogen_sol) self.r.update({'list': roots, 'sol': homogen_sol, 'simpliy_flag': simplify_flag}) gsol = _solve_undetermined_coefficients(eq, f(x), order, self.r, self.trialset) if simplify_flag: gsol = _get_simplified_sol([gsol], f(x), collectterms) return [gsol] class NthLinearEulerEqHomogeneous(SingleODESolver): r""" Solves an `n`\th order linear homogeneous variable-coefficient Cauchy-Euler equidimensional ordinary differential equation. This is an equation with form `0 = a_0 f(x) + a_1 x f'(x) + a_2 x^2 f''(x) \cdots`. These equations can be solved in a general manner, by substituting solutions of the form `f(x) = x^r`, and deriving a characteristic equation for `r`. When there are repeated roots, we include extra terms of the form `C_{r k} \ln^k(x) x^r`, where `C_{r k}` is an arbitrary integration constant, `r` is a root of the characteristic equation, and `k` ranges over the multiplicity of `r`. In the cases where the roots are complex, solutions of the form `C_1 x^a \sin(b \log(x)) + C_2 x^a \cos(b \log(x))` are returned, based on expansions with Euler's formula. The general solution is the sum of the terms found. If SymPy cannot find exact roots to the characteristic equation, a :py:obj:`~.ComplexRootOf` instance will be returned instead. >>> from sympy import Function, dsolve >>> from sympy.abc import x >>> f = Function('f') >>> dsolve(4*x**2*f(x).diff(x, 2) + f(x), f(x), ... hint='nth_linear_euler_eq_homogeneous') ... # doctest: +NORMALIZE_WHITESPACE Eq(f(x), sqrt(x)*(C1 + C2*log(x))) Note that because this method does not involve integration, there is no ``nth_linear_euler_eq_homogeneous_Integral`` hint. The following is for internal use: - ``returns = 'sol'`` returns the solution to the ODE. - ``returns = 'list'`` returns a list of linearly independent solutions, corresponding to the fundamental solution set, for use with non homogeneous solution methods like variation of parameters and undetermined coefficients. Note that, though the solutions should be linearly independent, this function does not explicitly check that. You can do ``assert simplify(wronskian(sollist)) != 0`` to check for linear independence. Also, ``assert len(sollist) == order`` will need to pass. - ``returns = 'both'``, return a dictionary ``{'sol': <solution to ODE>, 'list': <list of linearly independent solutions>}``. Examples ======== >>> from sympy import Function, dsolve, pprint >>> from sympy.abc import x >>> f = Function('f') >>> eq = f(x).diff(x, 2)*x**2 - 4*f(x).diff(x)*x + 6*f(x) >>> pprint(dsolve(eq, f(x), ... hint='nth_linear_euler_eq_homogeneous')) 2 f(x) = x *(C1 + C2*x) References ========== - https://en.wikipedia.org/wiki/Cauchy%E2%80%93Euler_equation - C. Bender & S. Orszag, "Advanced Mathematical Methods for Scientists and Engineers", Springer 1999, pp. 12 # indirect doctest """ hint = "nth_linear_euler_eq_homogeneous" has_integral = False def _matches(self): eq = self.ode_problem.eq_preprocessed f = self.ode_problem.func.func order = self.ode_problem.order x = self.ode_problem.sym match = self.ode_problem.get_linear_coefficients(eq, f(x), order) self.r = None does_match = False if order and match: coeff = match[order] factor = x**order / coeff self.r = {i: factor*match[i] for i in match} if self.r and all(_test_term(self.r[i], f(x), i) for i in self.r if i >= 0): if not self.r[-1]: does_match = True return does_match def _get_general_solution(self, *, simplify_flag: bool = True): fx = self.ode_problem.func eq = self.ode_problem.eq homogen_sol = _get_euler_characteristic_eq_sols(eq, fx, self.r)[0] return [homogen_sol] class NthLinearEulerEqNonhomogeneousVariationOfParameters(SingleODESolver): r""" Solves an `n`\th order linear non homogeneous Cauchy-Euler equidimensional ordinary differential equation using variation of parameters. This is an equation with form `g(x) = a_0 f(x) + a_1 x f'(x) + a_2 x^2 f''(x) \cdots`. This method works by assuming that the particular solution takes the form .. math:: \sum_{x=1}^{n} c_i(x) y_i(x) {a_n} {x^n} \text{, } where `y_i` is the `i`\th solution to the homogeneous equation. The solution is then solved using Wronskian's and Cramer's Rule. The particular solution is given by multiplying eq given below with `a_n x^{n}` .. math:: \sum_{x=1}^n \left( \int \frac{W_i(x)}{W(x)} \, dx \right) y_i(x) \text{, } where `W(x)` is the Wronskian of the fundamental system (the system of `n` linearly independent solutions to the homogeneous equation), and `W_i(x)` is the Wronskian of the fundamental system with the `i`\th column replaced with `[0, 0, \cdots, 0, \frac{x^{- n}}{a_n} g{\left(x \right)}]`. This method is general enough to solve any `n`\th order inhomogeneous linear differential equation, but sometimes SymPy cannot simplify the Wronskian well enough to integrate it. If this method hangs, try using the ``nth_linear_constant_coeff_variation_of_parameters_Integral`` hint and simplifying the integrals manually. Also, prefer using ``nth_linear_constant_coeff_undetermined_coefficients`` when it applies, because it does not use integration, making it faster and more reliable. Warning, using simplify=False with 'nth_linear_constant_coeff_variation_of_parameters' in :py:meth:`~sympy.solvers.ode.dsolve` may cause it to hang, because it will not attempt to simplify the Wronskian before integrating. It is recommended that you only use simplify=False with 'nth_linear_constant_coeff_variation_of_parameters_Integral' for this method, especially if the solution to the homogeneous equation has trigonometric functions in it. Examples ======== >>> from sympy import Function, dsolve, Derivative >>> from sympy.abc import x >>> f = Function('f') >>> eq = x**2*Derivative(f(x), x, x) - 2*x*Derivative(f(x), x) + 2*f(x) - x**4 >>> dsolve(eq, f(x), ... hint='nth_linear_euler_eq_nonhomogeneous_variation_of_parameters').expand() Eq(f(x), C1*x + C2*x**2 + x**4/6) """ hint = "nth_linear_euler_eq_nonhomogeneous_variation_of_parameters" has_integral = True def _matches(self): eq = self.ode_problem.eq_preprocessed f = self.ode_problem.func.func order = self.ode_problem.order x = self.ode_problem.sym match = self.ode_problem.get_linear_coefficients(eq, f(x), order) self.r = None does_match = False if order and match: coeff = match[order] factor = x**order / coeff self.r = {i: factor*match[i] for i in match} if self.r and all(_test_term(self.r[i], f(x), i) for i in self.r if i >= 0): if self.r[-1]: does_match = True return does_match def _get_general_solution(self, *, simplify_flag: bool = True): eq = self.ode_problem.eq f = self.ode_problem.func.func x = self.ode_problem.sym order = self.ode_problem.order homogen_sol, roots = _get_euler_characteristic_eq_sols(eq, f(x), self.r) self.r[-1] = self.r[-1]/self.r[order] sol = _solve_variation_of_parameters(eq, f(x), roots, homogen_sol, order, self.r, simplify_flag) return [Eq(f(x), homogen_sol.rhs + (sol.rhs - homogen_sol.rhs)*self.r[order])] class NthLinearEulerEqNonhomogeneousUndeterminedCoefficients(SingleODESolver): r""" Solves an `n`\th order linear non homogeneous Cauchy-Euler equidimensional ordinary differential equation using undetermined coefficients. This is an equation with form `g(x) = a_0 f(x) + a_1 x f'(x) + a_2 x^2 f''(x) \cdots`. These equations can be solved in a general manner, by substituting solutions of the form `x = exp(t)`, and deriving a characteristic equation of form `g(exp(t)) = b_0 f(t) + b_1 f'(t) + b_2 f''(t) \cdots` which can be then solved by nth_linear_constant_coeff_undetermined_coefficients if g(exp(t)) has finite number of linearly independent derivatives. Functions that fit this requirement are finite sums functions of the form `a x^i e^{b x} \sin(c x + d)` or `a x^i e^{b x} \cos(c x + d)`, where `i` is a non-negative integer and `a`, `b`, `c`, and `d` are constants. For example any polynomial in `x`, functions like `x^2 e^{2 x}`, `x \sin(x)`, and `e^x \cos(x)` can all be used. Products of `\sin`'s and `\cos`'s have a finite number of derivatives, because they can be expanded into `\sin(a x)` and `\cos(b x)` terms. However, SymPy currently cannot do that expansion, so you will need to manually rewrite the expression in terms of the above to use this method. So, for example, you will need to manually convert `\sin^2(x)` into `(1 + \cos(2 x))/2` to properly apply the method of undetermined coefficients on it. After replacement of x by exp(t), this method works by creating a trial function from the expression and all of its linear independent derivatives and substituting them into the original ODE. The coefficients for each term will be a system of linear equations, which are be solved for and substituted, giving the solution. If any of the trial functions are linearly dependent on the solution to the homogeneous equation, they are multiplied by sufficient `x` to make them linearly independent. Examples ======== >>> from sympy import dsolve, Function, Derivative, log >>> from sympy.abc import x >>> f = Function('f') >>> eq = x**2*Derivative(f(x), x, x) - 2*x*Derivative(f(x), x) + 2*f(x) - log(x) >>> dsolve(eq, f(x), ... hint='nth_linear_euler_eq_nonhomogeneous_undetermined_coefficients').expand() Eq(f(x), C1*x + C2*x**2 + log(x)/2 + 3/4) """ hint = "nth_linear_euler_eq_nonhomogeneous_undetermined_coefficients" has_integral = False def _matches(self): eq = self.ode_problem.eq_high_order_free f = self.ode_problem.func.func order = self.ode_problem.order x = self.ode_problem.sym match = self.ode_problem.get_linear_coefficients(eq, f(x), order) self.r = None does_match = False if order and match: coeff = match[order] factor = x**order / coeff self.r = {i: factor*match[i] for i in match} if self.r and all(_test_term(self.r[i], f(x), i) for i in self.r if i >= 0): if self.r[-1]: e, re = posify(self.r[-1].subs(x, exp(x))) undetcoeff = _undetermined_coefficients_match(e.subs(re), x) if undetcoeff['test']: does_match = True return does_match def _get_general_solution(self, *, simplify_flag: bool = True): f = self.ode_problem.func.func x = self.ode_problem.sym chareq, eq, symbol = S.Zero, S.Zero, Dummy('x') for i in self.r.keys(): if i >= 0: chareq += (self.r[i]*diff(x**symbol, x, i)*x**-symbol).expand() for i in range(1, degree(Poly(chareq, symbol))+1): eq += chareq.coeff(symbol**i)*diff(f(x), x, i) if chareq.as_coeff_add(symbol)[0]: eq += chareq.as_coeff_add(symbol)[0]*f(x) e, re = posify(self.r[-1].subs(x, exp(x))) eq += e.subs(re) self.const_undet_instance = NthLinearConstantCoeffUndeterminedCoefficients(SingleODEProblem(eq, f(x), x)) sol = self.const_undet_instance.get_general_solution(simplify = simplify_flag)[0] sol = sol.subs(x, log(x)) sol = sol.subs(f(log(x)), f(x)).expand() return [sol] class SecondLinearBessel(SingleODESolver): r""" Gives solution of the Bessel differential equation .. math :: x^2 \frac{d^2y}{dx^2} + x \frac{dy}{dx} y(x) + (x^2-n^2) y(x) if `n` is integer then the solution is of the form ``Eq(f(x), C0 besselj(n,x) + C1 bessely(n,x))`` as both the solutions are linearly independent else if `n` is a fraction then the solution is of the form ``Eq(f(x), C0 besselj(n,x) + C1 besselj(-n,x))`` which can also transform into ``Eq(f(x), C0 besselj(n,x) + C1 bessely(n,x))``. Examples ======== >>> from sympy.abc import x >>> from sympy import Symbol >>> v = Symbol('v', positive=True) >>> from sympy import dsolve, Function >>> f = Function('f') >>> y = f(x) >>> genform = x**2*y.diff(x, 2) + x*y.diff(x) + (x**2 - v**2)*y >>> dsolve(genform) Eq(f(x), C1*besselj(v, x) + C2*bessely(v, x)) References ========== https://www.math24.net/bessel-differential-equation/ """ hint = "2nd_linear_bessel" has_integral = False def _matches(self): eq = self.ode_problem.eq_high_order_free f = self.ode_problem.func order = self.ode_problem.order x = self.ode_problem.sym df = f.diff(x) a = Wild('a', exclude=[f,df]) b = Wild('b', exclude=[x, f,df]) a4 = Wild('a4', exclude=[x,f,df]) b4 = Wild('b4', exclude=[x,f,df]) c4 = Wild('c4', exclude=[x,f,df]) d4 = Wild('d4', exclude=[x,f,df]) a3 = Wild('a3', exclude=[f, df, f.diff(x, 2)]) b3 = Wild('b3', exclude=[f, df, f.diff(x, 2)]) c3 = Wild('c3', exclude=[f, df, f.diff(x, 2)]) deq = a3*(f.diff(x, 2)) + b3*df + c3*f r = collect(eq, [f.diff(x, 2), df, f]).match(deq) if order == 2 and r: if not all(r[key].is_polynomial() for key in r): n, d = eq.as_numer_denom() eq = expand(n) r = collect(eq, [f.diff(x, 2), df, f]).match(deq) if r and r[a3] != 0: # leading coeff of f(x).diff(x, 2) coeff = factor(r[a3]).match(a4*(x-b)**b4) if coeff: # if coeff[b4] = 0 means constant coefficient if coeff[b4] == 0: return False point = coeff[b] else: return False if point: r[a3] = simplify(r[a3].subs(x, x+point)) r[b3] = simplify(r[b3].subs(x, x+point)) r[c3] = simplify(r[c3].subs(x, x+point)) # making a3 in the form of x**2 r[a3] = cancel(r[a3]/(coeff[a4]*(x)**(-2+coeff[b4]))) r[b3] = cancel(r[b3]/(coeff[a4]*(x)**(-2+coeff[b4]))) r[c3] = cancel(r[c3]/(coeff[a4]*(x)**(-2+coeff[b4]))) # checking if b3 is of form c*(x-b) coeff1 = factor(r[b3]).match(a4*(x)) if coeff1 is None: return False # c3 maybe of very complex form so I am simply checking (a - b) form # if yes later I will match with the standerd form of bessel in a and b # a, b are wild variable defined above. _coeff2 = r[c3].match(a - b) if _coeff2 is None: return False # matching with standerd form for c3 coeff2 = factor(_coeff2[a]).match(c4**2*(x)**(2*a4)) if coeff2 is None: return False if _coeff2[b] == 0: coeff2[d4] = 0 else: coeff2[d4] = factor(_coeff2[b]).match(d4**2)[d4] self.rn = {'n':coeff2[d4], 'a4':coeff2[c4], 'd4':coeff2[a4]} self.rn['c4'] = coeff1[a4] self.rn['b4'] = point return True return False def _get_general_solution(self, *, simplify_flag: bool = True): f = self.ode_problem.func.func x = self.ode_problem.sym n = self.rn['n'] a4 = self.rn['a4'] c4 = self.rn['c4'] d4 = self.rn['d4'] b4 = self.rn['b4'] n = sqrt(n**2 + Rational(1, 4)*(c4 - 1)**2) (C1, C2) = self.ode_problem.get_numbered_constants(num=2) return [Eq(f(x), ((x**(Rational(1-c4,2)))*(C1*besselj(n/d4,a4*x**d4/d4) + C2*bessely(n/d4,a4*x**d4/d4))).subs(x, x-b4))] class SecondLinearAiry(SingleODESolver): r""" Gives solution of the Airy differential equation .. math :: \frac{d^2y}{dx^2} + (a + b x) y(x) = 0 in terms of Airy special functions airyai and airybi. Examples ======== >>> from sympy import dsolve, Function >>> from sympy.abc import x >>> f = Function("f") >>> eq = f(x).diff(x, 2) - x*f(x) >>> dsolve(eq) Eq(f(x), C1*airyai(x) + C2*airybi(x)) """ hint = "2nd_linear_airy" has_integral = False def _matches(self): eq = self.ode_problem.eq_high_order_free f = self.ode_problem.func order = self.ode_problem.order x = self.ode_problem.sym df = f.diff(x) a4 = Wild('a4', exclude=[x,f,df]) b4 = Wild('b4', exclude=[x,f,df]) match = self.ode_problem.get_linear_coefficients(eq, f, order) does_match = False if order == 2 and match and match[2] != 0: if match[1].is_zero: self.rn = cancel(match[0]/match[2]).match(a4+b4*x) if self.rn and self.rn[b4] != 0: self.rn = {'b':self.rn[a4],'m':self.rn[b4]} does_match = True return does_match def _get_general_solution(self, *, simplify_flag: bool = True): f = self.ode_problem.func.func x = self.ode_problem.sym (C1, C2) = self.ode_problem.get_numbered_constants(num=2) b = self.rn['b'] m = self.rn['m'] if m.is_positive: arg = - b/cbrt(m)**2 - cbrt(m)*x elif m.is_negative: arg = - b/cbrt(-m)**2 + cbrt(-m)*x else: arg = - b/cbrt(-m)**2 + cbrt(-m)*x return [Eq(f(x), C1*airyai(arg) + C2*airybi(arg))] class LieGroup(SingleODESolver): r""" This hint implements the Lie group method of solving first order differential equations. The aim is to convert the given differential equation from the given coordinate system into another coordinate system where it becomes invariant under the one-parameter Lie group of translations. The converted ODE can be easily solved by quadrature. It makes use of the :py:meth:`sympy.solvers.ode.infinitesimals` function which returns the infinitesimals of the transformation. The coordinates `r` and `s` can be found by solving the following Partial Differential Equations. .. math :: \xi\frac{\partial r}{\partial x} + \eta\frac{\partial r}{\partial y} = 0 .. math :: \xi\frac{\partial s}{\partial x} + \eta\frac{\partial s}{\partial y} = 1 The differential equation becomes separable in the new coordinate system .. math :: \frac{ds}{dr} = \frac{\frac{\partial s}{\partial x} + h(x, y)\frac{\partial s}{\partial y}}{ \frac{\partial r}{\partial x} + h(x, y)\frac{\partial r}{\partial y}} After finding the solution by integration, it is then converted back to the original coordinate system by substituting `r` and `s` in terms of `x` and `y` again. Examples ======== >>> from sympy import Function, dsolve, exp, pprint >>> from sympy.abc import x >>> f = Function('f') >>> pprint(dsolve(f(x).diff(x) + 2*x*f(x) - x*exp(-x**2), f(x), ... hint='lie_group')) / 2\ 2 | x | -x f(x) = |C1 + --|*e \ 2 / References ========== - Solving differential equations by Symmetry Groups, John Starrett, pp. 1 - pp. 14 """ hint = "lie_group" has_integral = False def _has_additional_params(self): return 'xi' in self.ode_problem.params and 'eta' in self.ode_problem.params def _matches(self): eq = self.ode_problem.eq f = self.ode_problem.func.func order = self.ode_problem.order x = self.ode_problem.sym df = f(x).diff(x) y = Dummy('y') d = Wild('d', exclude=[df, f(x).diff(x, 2)]) e = Wild('e', exclude=[df]) does_match = False if self._has_additional_params() and order == 1: xi = self.ode_problem.params['xi'] eta = self.ode_problem.params['eta'] self.r3 = {'xi': xi, 'eta': eta} r = collect(eq, df, exact=True).match(d + e * df) if r: r['d'] = d r['e'] = e r['y'] = y r[d] = r[d].subs(f(x), y) r[e] = r[e].subs(f(x), y) self.r3.update(r) does_match = True return does_match def _get_general_solution(self, *, simplify_flag: bool = True): eq = self.ode_problem.eq x = self.ode_problem.sym func = self.ode_problem.func order = self.ode_problem.order df = func.diff(x) try: eqsol = solve(eq, df) except NotImplementedError: eqsol = [] desols = [] for s in eqsol: sol = _ode_lie_group(s, func, order, match=self.r3) if sol: desols.extend(sol) if desols == []: raise NotImplementedError("The given ODE " + str(eq) + " cannot be solved by" + " the lie group method") return desols solver_map = { 'factorable': Factorable, 'nth_linear_constant_coeff_homogeneous': NthLinearConstantCoeffHomogeneous, 'nth_linear_euler_eq_homogeneous': NthLinearEulerEqHomogeneous, 'nth_linear_constant_coeff_undetermined_coefficients': NthLinearConstantCoeffUndeterminedCoefficients, 'nth_linear_euler_eq_nonhomogeneous_undetermined_coefficients': NthLinearEulerEqNonhomogeneousUndeterminedCoefficients, 'separable': Separable, '1st_exact': FirstExact, '1st_linear': FirstLinear, 'Bernoulli': Bernoulli, 'Riccati_special_minus2': RiccatiSpecial, '1st_rational_riccati': RationalRiccati, '1st_homogeneous_coeff_best': HomogeneousCoeffBest, '1st_homogeneous_coeff_subs_indep_div_dep': HomogeneousCoeffSubsIndepDivDep, '1st_homogeneous_coeff_subs_dep_div_indep': HomogeneousCoeffSubsDepDivIndep, 'almost_linear': AlmostLinear, 'linear_coefficients': LinearCoefficients, 'separable_reduced': SeparableReduced, 'nth_linear_constant_coeff_variation_of_parameters': NthLinearConstantCoeffVariationOfParameters, 'nth_linear_euler_eq_nonhomogeneous_variation_of_parameters': NthLinearEulerEqNonhomogeneousVariationOfParameters, 'Liouville': Liouville, '2nd_linear_airy': SecondLinearAiry, '2nd_linear_bessel': SecondLinearBessel, '2nd_hypergeometric': SecondHypergeometric, 'nth_order_reducible': NthOrderReducible, '2nd_nonlinear_autonomous_conserved': SecondNonlinearAutonomousConserved, 'nth_algebraic': NthAlgebraic, 'lie_group': LieGroup, } # Avoid circular import: from .ode import dsolve, ode_sol_simplicity, odesimp, homogeneous_order
368c1f81d4d5f17f4880ab030de75efc62d9cd369371ba9e37e78f1c33267960
from sympy.core import Add, Mul, S from sympy.core.containers import Tuple from sympy.core.exprtools import factor_terms from sympy.core.numbers import I from sympy.core.relational import Eq, Equality from sympy.core.sorting import default_sort_key, ordered from sympy.core.symbol import Dummy, Symbol from sympy.core.function import (expand_mul, expand, Derivative, AppliedUndef, Function, Subs) from sympy.functions import (exp, im, cos, sin, re, Piecewise, piecewise_fold, sqrt, log) from sympy.functions.combinatorial.factorials import factorial from sympy.matrices import zeros, Matrix, NonSquareMatrixError, MatrixBase, eye from sympy.polys import Poly, together from sympy.simplify import collect, radsimp, signsimp # type: ignore from sympy.simplify.powsimp import powdenest, powsimp from sympy.simplify.ratsimp import ratsimp from sympy.simplify.simplify import simplify from sympy.sets.sets import FiniteSet from sympy.solvers.deutils import ode_order from sympy.solvers.solveset import NonlinearError, solveset from sympy.utilities.iterables import (connected_components, iterable, strongly_connected_components) from sympy.utilities.misc import filldedent from sympy.integrals.integrals import Integral, integrate def _get_func_order(eqs, funcs): return {func: max(ode_order(eq, func) for eq in eqs) for func in funcs} class ODEOrderError(ValueError): """Raised by linear_ode_to_matrix if the system has the wrong order""" pass class ODENonlinearError(NonlinearError): """Raised by linear_ode_to_matrix if the system is nonlinear""" pass def _simpsol(soleq): lhs = soleq.lhs sol = soleq.rhs sol = powsimp(sol) gens = list(sol.atoms(exp)) p = Poly(sol, *gens, expand=False) gens = [factor_terms(g) for g in gens] if not gens: gens = p.gens syms = [Symbol('C1'), Symbol('C2')] terms = [] for coeff, monom in zip(p.coeffs(), p.monoms()): coeff = piecewise_fold(coeff) if isinstance(coeff, Piecewise): coeff = Piecewise(*((ratsimp(coef).collect(syms), cond) for coef, cond in coeff.args)) else: coeff = ratsimp(coeff).collect(syms) monom = Mul(*(g ** i for g, i in zip(gens, monom))) terms.append(coeff * monom) return Eq(lhs, Add(*terms)) def _solsimp(e, t): no_t, has_t = powsimp(expand_mul(e)).as_independent(t) no_t = ratsimp(no_t) has_t = has_t.replace(exp, lambda a: exp(factor_terms(a))) return no_t + has_t def simpsol(sol, wrt1, wrt2, doit=True): """Simplify solutions from dsolve_system.""" # The parameter sol is the solution as returned by dsolve (list of Eq). # # The parameters wrt1 and wrt2 are lists of symbols to be collected for # with those in wrt1 being collected for first. This allows for collecting # on any factors involving the independent variable before collecting on # the integration constants or vice versa using e.g.: # # sol = simpsol(sol, [t], [C1, C2]) # t first, constants after # sol = simpsol(sol, [C1, C2], [t]) # constants first, t after # # If doit=True (default) then simpsol will begin by evaluating any # unevaluated integrals. Since many integrals will appear multiple times # in the solutions this is done intelligently by computing each integral # only once. # # The strategy is to first perform simple cancellation with factor_terms # and then multiply out all brackets with expand_mul. This gives an Add # with many terms. # # We split each term into two multiplicative factors dep and coeff where # all factors that involve wrt1 are in dep and any constant factors are in # coeff e.g. # sqrt(2)*C1*exp(t) -> ( exp(t), sqrt(2)*C1 ) # # The dep factors are simplified using powsimp to combine expanded # exponential factors e.g. # exp(a*t)*exp(b*t) -> exp(t*(a+b)) # # We then collect coefficients for all terms having the same (simplified) # dep. The coefficients are then simplified using together and ratsimp and # lastly by recursively applying the same transformation to the # coefficients to collect on wrt2. # # Finally the result is recombined into an Add and signsimp is used to # normalise any minus signs. def simprhs(rhs, rep, wrt1, wrt2): """Simplify the rhs of an ODE solution""" if rep: rhs = rhs.subs(rep) rhs = factor_terms(rhs) rhs = simp_coeff_dep(rhs, wrt1, wrt2) rhs = signsimp(rhs) return rhs def simp_coeff_dep(expr, wrt1, wrt2=None): """Split rhs into terms, split terms into dep and coeff and collect on dep""" add_dep_terms = lambda e: e.is_Add and e.has(*wrt1) expandable = lambda e: e.is_Mul and any(map(add_dep_terms, e.args)) expand_func = lambda e: expand_mul(e, deep=False) expand_mul_mod = lambda e: e.replace(expandable, expand_func) terms = Add.make_args(expand_mul_mod(expr)) dc = {} for term in terms: coeff, dep = term.as_independent(*wrt1, as_Add=False) # Collect together the coefficients for terms that have the same # dependence on wrt1 (after dep is normalised using simpdep). dep = simpdep(dep, wrt1) # See if the dependence on t cancels out... if dep is not S.One: dep2 = factor_terms(dep) if not dep2.has(*wrt1): coeff *= dep2 dep = S.One if dep not in dc: dc[dep] = coeff else: dc[dep] += coeff # Apply the method recursively to the coefficients but this time # collecting on wrt2 rather than wrt2. termpairs = ((simpcoeff(c, wrt2), d) for d, c in dc.items()) if wrt2 is not None: termpairs = ((simp_coeff_dep(c, wrt2), d) for c, d in termpairs) return Add(*(c * d for c, d in termpairs)) def simpdep(term, wrt1): """Normalise factors involving t with powsimp and recombine exp""" def canonicalise(a): # Using factor_terms here isn't quite right because it leads to things # like exp(t*(1+t)) that we don't want. We do want to cancel factors # and pull out a common denominator but ideally the numerator would be # expressed as a standard form polynomial in t so we expand_mul # and collect afterwards. a = factor_terms(a) num, den = a.as_numer_denom() num = expand_mul(num) num = collect(num, wrt1) return num / den term = powsimp(term) rep = {e: exp(canonicalise(e.args[0])) for e in term.atoms(exp)} term = term.subs(rep) return term def simpcoeff(coeff, wrt2): """Bring to a common fraction and cancel with ratsimp""" coeff = together(coeff) if coeff.is_polynomial(): # Calling ratsimp can be expensive. The main reason is to simplify # sums of terms with irrational denominators so we limit ourselves # to the case where the expression is polynomial in any symbols. # Maybe there's a better approach... coeff = ratsimp(radsimp(coeff)) # collect on secondary variables first and any remaining symbols after if wrt2 is not None: syms = list(wrt2) + list(ordered(coeff.free_symbols - set(wrt2))) else: syms = list(ordered(coeff.free_symbols)) coeff = collect(coeff, syms) coeff = together(coeff) return coeff # There are often repeated integrals. Collect unique integrals and # evaluate each once and then substitute into the final result to replace # all occurrences in each of the solution equations. if doit: integrals = set().union(*(s.atoms(Integral) for s in sol)) rep = {i: factor_terms(i).doit() for i in integrals} else: rep = {} sol = [Eq(s.lhs, simprhs(s.rhs, rep, wrt1, wrt2)) for s in sol] return sol def linodesolve_type(A, t, b=None): r""" Helper function that determines the type of the system of ODEs for solving with :obj:`sympy.solvers.ode.systems.linodesolve()` Explanation =========== This function takes in the coefficient matrix and/or the non-homogeneous term and returns the type of the equation that can be solved by :obj:`sympy.solvers.ode.systems.linodesolve()`. If the system is constant coefficient homogeneous, then "type1" is returned If the system is constant coefficient non-homogeneous, then "type2" is returned If the system is non-constant coefficient homogeneous, then "type3" is returned If the system is non-constant coefficient non-homogeneous, then "type4" is returned If the system has a non-constant coefficient matrix which can be factorized into constant coefficient matrix, then "type5" or "type6" is returned for when the system is homogeneous or non-homogeneous respectively. Note that, if the system of ODEs is of "type3" or "type4", then along with the type, the commutative antiderivative of the coefficient matrix is also returned. If the system cannot be solved by :obj:`sympy.solvers.ode.systems.linodesolve()`, then NotImplementedError is raised. Parameters ========== A : Matrix Coefficient matrix of the system of ODEs b : Matrix or None Non-homogeneous term of the system. The default value is None. If this argument is None, then the system is assumed to be homogeneous. Examples ======== >>> from sympy import symbols, Matrix >>> from sympy.solvers.ode.systems import linodesolve_type >>> t = symbols("t") >>> A = Matrix([[1, 1], [2, 3]]) >>> b = Matrix([t, 1]) >>> linodesolve_type(A, t) {'antiderivative': None, 'type_of_equation': 'type1'} >>> linodesolve_type(A, t, b=b) {'antiderivative': None, 'type_of_equation': 'type2'} >>> A_t = Matrix([[1, t], [-t, 1]]) >>> linodesolve_type(A_t, t) {'antiderivative': Matrix([ [ t, t**2/2], [-t**2/2, t]]), 'type_of_equation': 'type3'} >>> linodesolve_type(A_t, t, b=b) {'antiderivative': Matrix([ [ t, t**2/2], [-t**2/2, t]]), 'type_of_equation': 'type4'} >>> A_non_commutative = Matrix([[1, t], [t, -1]]) >>> linodesolve_type(A_non_commutative, t) Traceback (most recent call last): ... NotImplementedError: The system does not have a commutative antiderivative, it cannot be solved by linodesolve. Returns ======= Dict Raises ====== NotImplementedError When the coefficient matrix does not have a commutative antiderivative See Also ======== linodesolve: Function for which linodesolve_type gets the information """ match = {} is_non_constant = not _matrix_is_constant(A, t) is_non_homogeneous = not (b is None or b.is_zero_matrix) type = "type{}".format(int("{}{}".format(int(is_non_constant), int(is_non_homogeneous)), 2) + 1) B = None match.update({"type_of_equation": type, "antiderivative": B}) if is_non_constant: B, is_commuting = _is_commutative_anti_derivative(A, t) if not is_commuting: raise NotImplementedError(filldedent(''' The system does not have a commutative antiderivative, it cannot be solved by linodesolve. ''')) match['antiderivative'] = B match.update(_first_order_type5_6_subs(A, t, b=b)) return match def _first_order_type5_6_subs(A, t, b=None): match = {} factor_terms = _factor_matrix(A, t) is_homogeneous = b is None or b.is_zero_matrix if factor_terms is not None: t_ = Symbol("{}_".format(t)) F_t = integrate(factor_terms[0], t) inverse = solveset(Eq(t_, F_t), t) # Note: A simple way to check if a function is invertible # or not. if isinstance(inverse, FiniteSet) and not inverse.has(Piecewise)\ and len(inverse) == 1: A = factor_terms[1] if not is_homogeneous: b = b / factor_terms[0] b = b.subs(t, list(inverse)[0]) type = "type{}".format(5 + (not is_homogeneous)) match.update({'func_coeff': A, 'tau': F_t, 't_': t_, 'type_of_equation': type, 'rhs': b}) return match def linear_ode_to_matrix(eqs, funcs, t, order): r""" Convert a linear system of ODEs to matrix form Explanation =========== Express a system of linear ordinary differential equations as a single matrix differential equation [1]. For example the system $x' = x + y + 1$ and $y' = x - y$ can be represented as .. math:: A_1 X' = A_0 X + b where $A_1$ and $A_0$ are $2 \times 2$ matrices and $b$, $X$ and $X'$ are $2 \times 1$ matrices with $X = [x, y]^T$. Higher-order systems are represented with additional matrices e.g. a second-order system would look like .. math:: A_2 X'' = A_1 X' + A_0 X + b Examples ======== >>> from sympy import Function, Symbol, Matrix, Eq >>> from sympy.solvers.ode.systems import linear_ode_to_matrix >>> t = Symbol('t') >>> x = Function('x') >>> y = Function('y') We can create a system of linear ODEs like >>> eqs = [ ... Eq(x(t).diff(t), x(t) + y(t) + 1), ... Eq(y(t).diff(t), x(t) - y(t)), ... ] >>> funcs = [x(t), y(t)] >>> order = 1 # 1st order system Now ``linear_ode_to_matrix`` can represent this as a matrix differential equation. >>> (A1, A0), b = linear_ode_to_matrix(eqs, funcs, t, order) >>> A1 Matrix([ [1, 0], [0, 1]]) >>> A0 Matrix([ [1, 1], [1, -1]]) >>> b Matrix([ [1], [0]]) The original equations can be recovered from these matrices: >>> eqs_mat = Matrix([eq.lhs - eq.rhs for eq in eqs]) >>> X = Matrix(funcs) >>> A1 * X.diff(t) - A0 * X - b == eqs_mat True If the system of equations has a maximum order greater than the order of the system specified, a ODEOrderError exception is raised. >>> eqs = [Eq(x(t).diff(t, 2), x(t).diff(t) + x(t)), Eq(y(t).diff(t), y(t) + x(t))] >>> linear_ode_to_matrix(eqs, funcs, t, 1) Traceback (most recent call last): ... ODEOrderError: Cannot represent system in 1-order form If the system of equations is nonlinear, then ODENonlinearError is raised. >>> eqs = [Eq(x(t).diff(t), x(t) + y(t)), Eq(y(t).diff(t), y(t)**2 + x(t))] >>> linear_ode_to_matrix(eqs, funcs, t, 1) Traceback (most recent call last): ... ODENonlinearError: The system of ODEs is nonlinear. Parameters ========== eqs : list of SymPy expressions or equalities The equations as expressions (assumed equal to zero). funcs : list of applied functions The dependent variables of the system of ODEs. t : symbol The independent variable. order : int The order of the system of ODEs. Returns ======= The tuple ``(As, b)`` where ``As`` is a tuple of matrices and ``b`` is the the matrix representing the rhs of the matrix equation. Raises ====== ODEOrderError When the system of ODEs have an order greater than what was specified ODENonlinearError When the system of ODEs is nonlinear See Also ======== linear_eq_to_matrix: for systems of linear algebraic equations. References ========== .. [1] https://en.wikipedia.org/wiki/Matrix_differential_equation """ from sympy.solvers.solveset import linear_eq_to_matrix if any(ode_order(eq, func) > order for eq in eqs for func in funcs): msg = "Cannot represent system in {}-order form" raise ODEOrderError(msg.format(order)) As = [] for o in range(order, -1, -1): # Work from the highest derivative down funcs_deriv = [func.diff(t, o) for func in funcs] # linear_eq_to_matrix expects a proper symbol so substitute e.g. # Derivative(x(t), t) for a Dummy. rep = {func_deriv: Dummy() for func_deriv in funcs_deriv} eqs = [eq.subs(rep) for eq in eqs] syms = [rep[func_deriv] for func_deriv in funcs_deriv] # Ai is the matrix for X(t).diff(t, o) # eqs is minus the remainder of the equations. try: Ai, b = linear_eq_to_matrix(eqs, syms) except NonlinearError: raise ODENonlinearError("The system of ODEs is nonlinear.") Ai = Ai.applyfunc(expand_mul) As.append(Ai if o == order else -Ai) if o: eqs = [-eq for eq in b] else: rhs = b return As, rhs def matrix_exp(A, t): r""" Matrix exponential $\exp(A*t)$ for the matrix ``A`` and scalar ``t``. Explanation =========== This functions returns the $\exp(A*t)$ by doing a simple matrix multiplication: .. math:: \exp(A*t) = P * expJ * P^{-1} where $expJ$ is $\exp(J*t)$. $J$ is the Jordan normal form of $A$ and $P$ is matrix such that: .. math:: A = P * J * P^{-1} The matrix exponential $\exp(A*t)$ appears in the solution of linear differential equations. For example if $x$ is a vector and $A$ is a matrix then the initial value problem .. math:: \frac{dx(t)}{dt} = A \times x(t), x(0) = x0 has the unique solution .. math:: x(t) = \exp(A t) x0 Examples ======== >>> from sympy import Symbol, Matrix, pprint >>> from sympy.solvers.ode.systems import matrix_exp >>> t = Symbol('t') We will consider a 2x2 matrix for comupting the exponential >>> A = Matrix([[2, -5], [2, -4]]) >>> pprint(A) [2 -5] [ ] [2 -4] Now, exp(A*t) is given as follows: >>> pprint(matrix_exp(A, t)) [ -t -t -t ] [3*e *sin(t) + e *cos(t) -5*e *sin(t) ] [ ] [ -t -t -t ] [ 2*e *sin(t) - 3*e *sin(t) + e *cos(t)] Parameters ========== A : Matrix The matrix $A$ in the expression $\exp(A*t)$ t : Symbol The independent variable See Also ======== matrix_exp_jordan_form: For exponential of Jordan normal form References ========== .. [1] https://en.wikipedia.org/wiki/Jordan_normal_form .. [2] https://en.wikipedia.org/wiki/Matrix_exponential """ P, expJ = matrix_exp_jordan_form(A, t) return P * expJ * P.inv() def matrix_exp_jordan_form(A, t): r""" Matrix exponential $\exp(A*t)$ for the matrix *A* and scalar *t*. Explanation =========== Returns the Jordan form of the $\exp(A*t)$ along with the matrix $P$ such that: .. math:: \exp(A*t) = P * expJ * P^{-1} Examples ======== >>> from sympy import Matrix, Symbol >>> from sympy.solvers.ode.systems import matrix_exp, matrix_exp_jordan_form >>> t = Symbol('t') We will consider a 2x2 defective matrix. This shows that our method works even for defective matrices. >>> A = Matrix([[1, 1], [0, 1]]) It can be observed that this function gives us the Jordan normal form and the required invertible matrix P. >>> P, expJ = matrix_exp_jordan_form(A, t) Here, it is shown that P and expJ returned by this function is correct as they satisfy the formula: P * expJ * P_inverse = exp(A*t). >>> P * expJ * P.inv() == matrix_exp(A, t) True Parameters ========== A : Matrix The matrix $A$ in the expression $\exp(A*t)$ t : Symbol The independent variable References ========== .. [1] https://en.wikipedia.org/wiki/Defective_matrix .. [2] https://en.wikipedia.org/wiki/Jordan_matrix .. [3] https://en.wikipedia.org/wiki/Jordan_normal_form """ N, M = A.shape if N != M: raise ValueError('Needed square matrix but got shape (%s, %s)' % (N, M)) elif A.has(t): raise ValueError('Matrix A should not depend on t') def jordan_chains(A): '''Chains from Jordan normal form analogous to M.eigenvects(). Returns a dict with eignevalues as keys like: {e1: [[v111,v112,...], [v121, v122,...]], e2:...} where vijk is the kth vector in the jth chain for eigenvalue i. ''' P, blocks = A.jordan_cells() basis = [P[:,i] for i in range(P.shape[1])] n = 0 chains = {} for b in blocks: eigval = b[0, 0] size = b.shape[0] if eigval not in chains: chains[eigval] = [] chains[eigval].append(basis[n:n+size]) n += size return chains eigenchains = jordan_chains(A) # Needed for consistency across Python versions eigenchains_iter = sorted(eigenchains.items(), key=default_sort_key) isreal = not A.has(I) blocks = [] vectors = [] seen_conjugate = set() for e, chains in eigenchains_iter: for chain in chains: n = len(chain) if isreal and e != e.conjugate() and e.conjugate() in eigenchains: if e in seen_conjugate: continue seen_conjugate.add(e.conjugate()) exprt = exp(re(e) * t) imrt = im(e) * t imblock = Matrix([[cos(imrt), sin(imrt)], [-sin(imrt), cos(imrt)]]) expJblock2 = Matrix(n, n, lambda i,j: imblock * t**(j-i) / factorial(j-i) if j >= i else zeros(2, 2)) expJblock = Matrix(2*n, 2*n, lambda i,j: expJblock2[i//2,j//2][i%2,j%2]) blocks.append(exprt * expJblock) for i in range(n): vectors.append(re(chain[i])) vectors.append(im(chain[i])) else: vectors.extend(chain) fun = lambda i,j: t**(j-i)/factorial(j-i) if j >= i else 0 expJblock = Matrix(n, n, fun) blocks.append(exp(e * t) * expJblock) expJ = Matrix.diag(*blocks) P = Matrix(N, N, lambda i,j: vectors[j][i]) return P, expJ # Note: To add a docstring example with tau def linodesolve(A, t, b=None, B=None, type="auto", doit=False, tau=None): r""" System of n equations linear first-order differential equations Explanation =========== This solver solves the system of ODEs of the follwing form: .. math:: X'(t) = A(t) X(t) + b(t) Here, $A(t)$ is the coefficient matrix, $X(t)$ is the vector of n independent variables, $b(t)$ is the non-homogeneous term and $X'(t)$ is the derivative of $X(t)$ Depending on the properties of $A(t)$ and $b(t)$, this solver evaluates the solution differently. When $A(t)$ is constant coefficient matrix and $b(t)$ is zero vector i.e. system is homogeneous, the system is "type1". The solution is: .. math:: X(t) = \exp(A t) C Here, $C$ is a vector of constants and $A$ is the constant coefficient matrix. When $A(t)$ is constant coefficient matrix and $b(t)$ is non-zero i.e. system is non-homogeneous, the system is "type2". The solution is: .. math:: X(t) = e^{A t} ( \int e^{- A t} b \,dt + C) When $A(t)$ is coefficient matrix such that its commutative with its antiderivative $B(t)$ and $b(t)$ is a zero vector i.e. system is homogeneous, the system is "type3". The solution is: .. math:: X(t) = \exp(B(t)) C When $A(t)$ is commutative with its antiderivative $B(t)$ and $b(t)$ is non-zero i.e. system is non-homogeneous, the system is "type4". The solution is: .. math:: X(t) = e^{B(t)} ( \int e^{-B(t)} b(t) \,dt + C) When $A(t)$ is a coefficient matrix such that it can be factorized into a scalar and a constant coefficient matrix: .. math:: A(t) = f(t) * A Where $f(t)$ is a scalar expression in the independent variable $t$ and $A$ is a constant matrix, then we can do the following substitutions: .. math:: tau = \int f(t) dt, X(t) = Y(tau), b(t) = b(f^{-1}(tau)) Here, the substitution for the non-homogeneous term is done only when its non-zero. Using these substitutions, our original system becomes: .. math:: Y'(tau) = A * Y(tau) + b(tau)/f(tau) The above system can be easily solved using the solution for "type1" or "type2" depending on the homogeneity of the system. After we get the solution for $Y(tau)$, we substitute the solution for $tau$ as $t$ to get back $X(t)$ .. math:: X(t) = Y(tau) Systems of "type5" and "type6" have a commutative antiderivative but we use this solution because its faster to compute. The final solution is the general solution for all the four equations since a constant coefficient matrix is always commutative with its antidervative. An additional feature of this function is, if someone wants to substitute for value of the independent variable, they can pass the substitution `tau` and the solution will have the independent variable substituted with the passed expression(`tau`). Parameters ========== A : Matrix Coefficient matrix of the system of linear first order ODEs. t : Symbol Independent variable in the system of ODEs. b : Matrix or None Non-homogeneous term in the system of ODEs. If None is passed, a homogeneous system of ODEs is assumed. B : Matrix or None Antiderivative of the coefficient matrix. If the antiderivative is not passed and the solution requires the term, then the solver would compute it internally. type : String Type of the system of ODEs passed. Depending on the type, the solution is evaluated. The type values allowed and the corresponding system it solves are: "type1" for constant coefficient homogeneous "type2" for constant coefficient non-homogeneous, "type3" for non-constant coefficient homogeneous, "type4" for non-constant coefficient non-homogeneous, "type5" and "type6" for non-constant coefficient homogeneous and non-homogeneous systems respectively where the coefficient matrix can be factorized to a constant coefficient matrix. The default value is "auto" which will let the solver decide the correct type of the system passed. doit : Boolean Evaluate the solution if True, default value is False tau: Expression Used to substitute for the value of `t` after we get the solution of the system. Examples ======== To solve the system of ODEs using this function directly, several things must be done in the right order. Wrong inputs to the function will lead to incorrect results. >>> from sympy import symbols, Function, Eq >>> from sympy.solvers.ode.systems import canonical_odes, linear_ode_to_matrix, linodesolve, linodesolve_type >>> from sympy.solvers.ode.subscheck import checkodesol >>> f, g = symbols("f, g", cls=Function) >>> x, a = symbols("x, a") >>> funcs = [f(x), g(x)] >>> eqs = [Eq(f(x).diff(x) - f(x), a*g(x) + 1), Eq(g(x).diff(x) + g(x), a*f(x))] Here, it is important to note that before we derive the coefficient matrix, it is important to get the system of ODEs into the desired form. For that we will use :obj:`sympy.solvers.ode.systems.canonical_odes()`. >>> eqs = canonical_odes(eqs, funcs, x) >>> eqs [[Eq(Derivative(f(x), x), a*g(x) + f(x) + 1), Eq(Derivative(g(x), x), a*f(x) - g(x))]] Now, we will use :obj:`sympy.solvers.ode.systems.linear_ode_to_matrix()` to get the coefficient matrix and the non-homogeneous term if it is there. >>> eqs = eqs[0] >>> (A1, A0), b = linear_ode_to_matrix(eqs, funcs, x, 1) >>> A = A0 We have the coefficient matrices and the non-homogeneous term ready. Now, we can use :obj:`sympy.solvers.ode.systems.linodesolve_type()` to get the information for the system of ODEs to finally pass it to the solver. >>> system_info = linodesolve_type(A, x, b=b) >>> sol_vector = linodesolve(A, x, b=b, B=system_info['antiderivative'], type=system_info['type_of_equation']) Now, we can prove if the solution is correct or not by using :obj:`sympy.solvers.ode.checkodesol()` >>> sol = [Eq(f, s) for f, s in zip(funcs, sol_vector)] >>> checkodesol(eqs, sol) (True, [0, 0]) We can also use the doit method to evaluate the solutions passed by the function. >>> sol_vector_evaluated = linodesolve(A, x, b=b, type="type2", doit=True) Now, we will look at a system of ODEs which is non-constant. >>> eqs = [Eq(f(x).diff(x), f(x) + x*g(x)), Eq(g(x).diff(x), -x*f(x) + g(x))] The system defined above is already in the desired form, so we do not have to convert it. >>> (A1, A0), b = linear_ode_to_matrix(eqs, funcs, x, 1) >>> A = A0 A user can also pass the commutative antiderivative required for type3 and type4 system of ODEs. Passing an incorrect one will lead to incorrect results. If the coefficient matrix is not commutative with its antiderivative, then :obj:`sympy.solvers.ode.systems.linodesolve_type()` raises a NotImplementedError. If it does have a commutative antiderivative, then the function just returns the information about the system. >>> system_info = linodesolve_type(A, x, b=b) Now, we can pass the antiderivative as an argument to get the solution. If the system information is not passed, then the solver will compute the required arguments internally. >>> sol_vector = linodesolve(A, x, b=b) Once again, we can verify the solution obtained. >>> sol = [Eq(f, s) for f, s in zip(funcs, sol_vector)] >>> checkodesol(eqs, sol) (True, [0, 0]) Returns ======= List Raises ====== ValueError This error is raised when the coefficient matrix, non-homogeneous term or the antiderivative, if passed, are not a matrix or do not have correct dimensions NonSquareMatrixError When the coefficient matrix or its antiderivative, if passed is not a square matrix NotImplementedError If the coefficient matrix does not have a commutative antiderivative See Also ======== linear_ode_to_matrix: Coefficient matrix computation function canonical_odes: System of ODEs representation change linodesolve_type: Getting information about systems of ODEs to pass in this solver """ if not isinstance(A, MatrixBase): raise ValueError(filldedent('''\ The coefficients of the system of ODEs should be of type Matrix ''')) if not A.is_square: raise NonSquareMatrixError(filldedent('''\ The coefficient matrix must be a square ''')) if b is not None: if not isinstance(b, MatrixBase): raise ValueError(filldedent('''\ The non-homogeneous terms of the system of ODEs should be of type Matrix ''')) if A.rows != b.rows: raise ValueError(filldedent('''\ The system of ODEs should have the same number of non-homogeneous terms and the number of equations ''')) if B is not None: if not isinstance(B, MatrixBase): raise ValueError(filldedent('''\ The antiderivative of coefficients of the system of ODEs should be of type Matrix ''')) if not B.is_square: raise NonSquareMatrixError(filldedent('''\ The antiderivative of the coefficient matrix must be a square ''')) if A.rows != B.rows: raise ValueError(filldedent('''\ The coefficient matrix and its antiderivative should have same dimensions ''')) if not any(type == "type{}".format(i) for i in range(1, 7)) and not type == "auto": raise ValueError(filldedent('''\ The input type should be a valid one ''')) n = A.rows # constants = numbered_symbols(prefix='C', cls=Dummy, start=const_idx+1) Cvect = Matrix(list(Dummy() for _ in range(n))) if any(type == typ for typ in ["type2", "type4", "type6"]) and b is None: b = zeros(n, 1) is_transformed = tau is not None passed_type = type if type == "auto": system_info = linodesolve_type(A, t, b=b) type = system_info["type_of_equation"] B = system_info["antiderivative"] if type in ("type5", "type6"): is_transformed = True if passed_type != "auto": if tau is None: system_info = _first_order_type5_6_subs(A, t, b=b) if not system_info: raise ValueError(filldedent(''' The system passed isn't {}. '''.format(type))) tau = system_info['tau'] t = system_info['t_'] A = system_info['A'] b = system_info['b'] if type in ("type1", "type2", "type5", "type6"): P, J = matrix_exp_jordan_form(A, t) P = simplify(P) if type in ("type1", "type5"): sol_vector = P * (J * Cvect) else: Jinv = J.subs(t, -t) sol_vector = P * J * ((Jinv * P.inv() * b).applyfunc(lambda x: Integral(x, t)) + Cvect) else: if B is None: B, _ = _is_commutative_anti_derivative(A, t) if type == "type3": sol_vector = B.exp() * Cvect else: sol_vector = B.exp() * (((-B).exp() * b).applyfunc(lambda x: Integral(x, t)) + Cvect) if is_transformed: sol_vector = sol_vector.subs(t, tau) gens = sol_vector.atoms(exp) if type != "type1": sol_vector = [expand_mul(s) for s in sol_vector] sol_vector = [collect(s, ordered(gens), exact=True) for s in sol_vector] if doit: sol_vector = [s.doit() for s in sol_vector] return sol_vector def _matrix_is_constant(M, t): """Checks if the matrix M is independent of t or not.""" return all(coef.as_independent(t, as_Add=True)[1] == 0 for coef in M) def canonical_odes(eqs, funcs, t): r""" Function that solves for highest order derivatives in a system Explanation =========== This function inputs a system of ODEs and based on the system, the dependent variables and their highest order, returns the system in the following form: .. math:: X'(t) = A(t) X(t) + b(t) Here, $X(t)$ is the vector of dependent variables of lower order, $A(t)$ is the coefficient matrix, $b(t)$ is the non-homogeneous term and $X'(t)$ is the vector of dependent variables in their respective highest order. We use the term canonical form to imply the system of ODEs which is of the above form. If the system passed has a non-linear term with multiple solutions, then a list of systems is returned in its canonical form. Parameters ========== eqs : List List of the ODEs funcs : List List of dependent variables t : Symbol Independent variable Examples ======== >>> from sympy import symbols, Function, Eq, Derivative >>> from sympy.solvers.ode.systems import canonical_odes >>> f, g = symbols("f g", cls=Function) >>> x, y = symbols("x y") >>> funcs = [f(x), g(x)] >>> eqs = [Eq(f(x).diff(x) - 7*f(x), 12*g(x)), Eq(g(x).diff(x) + g(x), 20*f(x))] >>> canonical_eqs = canonical_odes(eqs, funcs, x) >>> canonical_eqs [[Eq(Derivative(f(x), x), 7*f(x) + 12*g(x)), Eq(Derivative(g(x), x), 20*f(x) - g(x))]] >>> system = [Eq(Derivative(f(x), x)**2 - 2*Derivative(f(x), x) + 1, 4), Eq(-y*f(x) + Derivative(g(x), x), 0)] >>> canonical_system = canonical_odes(system, funcs, x) >>> canonical_system [[Eq(Derivative(f(x), x), -1), Eq(Derivative(g(x), x), y*f(x))], [Eq(Derivative(f(x), x), 3), Eq(Derivative(g(x), x), y*f(x))]] Returns ======= List """ from sympy.solvers.solvers import solve order = _get_func_order(eqs, funcs) canon_eqs = solve(eqs, *[func.diff(t, order[func]) for func in funcs], dict=True) systems = [] for eq in canon_eqs: system = [Eq(func.diff(t, order[func]), eq[func.diff(t, order[func])]) for func in funcs] systems.append(system) return systems def _is_commutative_anti_derivative(A, t): r""" Helper function for determining if the Matrix passed is commutative with its antiderivative Explanation =========== This function checks if the Matrix $A$ passed is commutative with its antiderivative with respect to the independent variable $t$. .. math:: B(t) = \int A(t) dt The function outputs two values, first one being the antiderivative $B(t)$, second one being a boolean value, if True, then the matrix $A(t)$ passed is commutative with $B(t)$, else the matrix passed isn't commutative with $B(t)$. Parameters ========== A : Matrix The matrix which has to be checked t : Symbol Independent variable Examples ======== >>> from sympy import symbols, Matrix >>> from sympy.solvers.ode.systems import _is_commutative_anti_derivative >>> t = symbols("t") >>> A = Matrix([[1, t], [-t, 1]]) >>> B, is_commuting = _is_commutative_anti_derivative(A, t) >>> is_commuting True Returns ======= Matrix, Boolean """ B = integrate(A, t) is_commuting = (B*A - A*B).applyfunc(expand).applyfunc(factor_terms).is_zero_matrix is_commuting = False if is_commuting is None else is_commuting return B, is_commuting def _factor_matrix(A, t): term = None for element in A: temp_term = element.as_independent(t)[1] if temp_term.has(t): term = temp_term break if term is not None: A_factored = (A/term).applyfunc(ratsimp) can_factor = _matrix_is_constant(A_factored, t) term = (term, A_factored) if can_factor else None return term def _is_second_order_type2(A, t): term = _factor_matrix(A, t) is_type2 = False if term is not None: term = 1/term[0] is_type2 = term.is_polynomial() if is_type2: poly = Poly(term.expand(), t) monoms = poly.monoms() if monoms[0][0] in (2, 4): cs = _get_poly_coeffs(poly, 4) a, b, c, d, e = cs a1 = powdenest(sqrt(a), force=True) c1 = powdenest(sqrt(e), force=True) b1 = powdenest(sqrt(c - 2*a1*c1), force=True) is_type2 = (b == 2*a1*b1) and (d == 2*b1*c1) term = a1*t**2 + b1*t + c1 else: is_type2 = False return is_type2, term def _get_poly_coeffs(poly, order): cs = [0 for _ in range(order+1)] for c, m in zip(poly.coeffs(), poly.monoms()): cs[-1-m[0]] = c return cs def _match_second_order_type(A1, A0, t, b=None): r""" Works only for second order system in its canonical form. Type 0: Constant coefficient matrix, can be simply solved by introducing dummy variables. Type 1: When the substitution: $U = t*X' - X$ works for reducing the second order system to first order system. Type 2: When the system is of the form: $poly * X'' = A*X$ where $poly$ is square of a quadratic polynomial with respect to *t* and $A$ is a constant coefficient matrix. """ match = {"type_of_equation": "type0"} n = A1.shape[0] if _matrix_is_constant(A1, t) and _matrix_is_constant(A0, t): return match if (A1 + A0*t).applyfunc(expand_mul).is_zero_matrix: match.update({"type_of_equation": "type1", "A1": A1}) elif A1.is_zero_matrix and (b is None or b.is_zero_matrix): is_type2, term = _is_second_order_type2(A0, t) if is_type2: a, b, c = _get_poly_coeffs(Poly(term, t), 2) A = (A0*(term**2).expand()).applyfunc(ratsimp) + (b**2/4 - a*c)*eye(n, n) tau = integrate(1/term, t) t_ = Symbol("{}_".format(t)) match.update({"type_of_equation": "type2", "A0": A, "g(t)": sqrt(term), "tau": tau, "is_transformed": True, "t_": t_}) return match def _second_order_subs_type1(A, b, funcs, t): r""" For a linear, second order system of ODEs, a particular substitution. A system of the below form can be reduced to a linear first order system of ODEs: .. math:: X'' = A(t) * (t*X' - X) + b(t) By substituting: .. math:: U = t*X' - X To get the system: .. math:: U' = t*(A(t)*U + b(t)) Where $U$ is the vector of dependent variables, $X$ is the vector of dependent variables in `funcs` and $X'$ is the first order derivative of $X$ with respect to $t$. It may or may not reduce the system into linear first order system of ODEs. Then a check is made to determine if the system passed can be reduced or not, if this substitution works, then the system is reduced and its solved for the new substitution. After we get the solution for $U$: .. math:: U = a(t) We substitute and return the reduced system: .. math:: a(t) = t*X' - X Parameters ========== A: Matrix Coefficient matrix($A(t)*t$) of the second order system of this form. b: Matrix Non-homogeneous term($b(t)$) of the system of ODEs. funcs: List List of dependent variables t: Symbol Independent variable of the system of ODEs. Returns ======= List """ U = Matrix([t*func.diff(t) - func for func in funcs]) sol = linodesolve(A, t, t*b) reduced_eqs = [Eq(u, s) for s, u in zip(sol, U)] reduced_eqs = canonical_odes(reduced_eqs, funcs, t)[0] return reduced_eqs def _second_order_subs_type2(A, funcs, t_): r""" Returns a second order system based on the coefficient matrix passed. Explanation =========== This function returns a system of second order ODE of the following form: .. math:: X'' = A * X Here, $X$ is the vector of dependent variables, but a bit modified, $A$ is the coefficient matrix passed. Along with returning the second order system, this function also returns the new dependent variables with the new independent variable `t_` passed. Parameters ========== A: Matrix Coefficient matrix of the system funcs: List List of old dependent variables t_: Symbol New independent variable Returns ======= List, List """ func_names = [func.func.__name__ for func in funcs] new_funcs = [Function(Dummy("{}_".format(name)))(t_) for name in func_names] rhss = A * Matrix(new_funcs) new_eqs = [Eq(func.diff(t_, 2), rhs) for func, rhs in zip(new_funcs, rhss)] return new_eqs, new_funcs def _is_euler_system(As, t): return all(_matrix_is_constant((A*t**i).applyfunc(ratsimp), t) for i, A in enumerate(As)) def _classify_linear_system(eqs, funcs, t, is_canon=False): r""" Returns a dictionary with details of the eqs if the system passed is linear and can be classified by this function else returns None Explanation =========== This function takes the eqs, converts it into a form Ax = b where x is a vector of terms containing dependent variables and their derivatives till their maximum order. If it is possible to convert eqs into Ax = b, then all the equations in eqs are linear otherwise they are non-linear. To check if the equations are constant coefficient, we need to check if all the terms in A obtained above are constant or not. To check if the equations are homogeneous or not, we need to check if b is a zero matrix or not. Parameters ========== eqs: List List of ODEs funcs: List List of dependent variables t: Symbol Independent variable of the equations in eqs is_canon: Boolean If True, then this function will not try to get the system in canonical form. Default value is False Returns ======= match = { 'no_of_equation': len(eqs), 'eq': eqs, 'func': funcs, 'order': order, 'is_linear': is_linear, 'is_constant': is_constant, 'is_homogeneous': is_homogeneous, } Dict or list of Dicts or None Dict with values for keys: 1. no_of_equation: Number of equations 2. eq: The set of equations 3. func: List of dependent variables 4. order: A dictionary that gives the order of the dependent variable in eqs 5. is_linear: Boolean value indicating if the set of equations are linear or not. 6. is_constant: Boolean value indicating if the set of equations have constant coefficients or not. 7. is_homogeneous: Boolean value indicating if the set of equations are homogeneous or not. 8. commutative_antiderivative: Antiderivative of the coefficient matrix if the coefficient matrix is non-constant and commutative with its antiderivative. This key may or may not exist. 9. is_general: Boolean value indicating if the system of ODEs is solvable using one of the general case solvers or not. 10. rhs: rhs of the non-homogeneous system of ODEs in Matrix form. This key may or may not exist. 11. is_higher_order: True if the system passed has an order greater than 1. This key may or may not exist. 12. is_second_order: True if the system passed is a second order ODE. This key may or may not exist. This Dict is the answer returned if the eqs are linear and constant coefficient. Otherwise, None is returned. """ # Error for i == 0 can be added but isn't for now # Check for len(funcs) == len(eqs) if len(funcs) != len(eqs): raise ValueError("Number of functions given is not equal to the number of equations %s" % funcs) # ValueError when functions have more than one arguments for func in funcs: if len(func.args) != 1: raise ValueError("dsolve() and classify_sysode() work with " "functions of one variable only, not %s" % func) # Getting the func_dict and order using the helper # function order = _get_func_order(eqs, funcs) system_order = max(order[func] for func in funcs) is_higher_order = system_order > 1 is_second_order = system_order == 2 and all(order[func] == 2 for func in funcs) # Not adding the check if the len(func.args) for # every func in funcs is 1 # Linearity check try: canon_eqs = canonical_odes(eqs, funcs, t) if not is_canon else [eqs] if len(canon_eqs) == 1: As, b = linear_ode_to_matrix(canon_eqs[0], funcs, t, system_order) else: match = { 'is_implicit': True, 'canon_eqs': canon_eqs } return match # When the system of ODEs is non-linear, an ODENonlinearError is raised. # This function catches the error and None is returned. except ODENonlinearError: return None is_linear = True # Homogeneous check is_homogeneous = True if b.is_zero_matrix else False # Is general key is used to identify if the system of ODEs can be solved by # one of the general case solvers or not. match = { 'no_of_equation': len(eqs), 'eq': eqs, 'func': funcs, 'order': order, 'is_linear': is_linear, 'is_homogeneous': is_homogeneous, 'is_general': True } if not is_homogeneous: match['rhs'] = b is_constant = all(_matrix_is_constant(A_, t) for A_ in As) # The match['is_linear'] check will be added in the future when this # function becomes ready to deal with non-linear systems of ODEs if not is_higher_order: A = As[1] match['func_coeff'] = A # Constant coefficient check is_constant = _matrix_is_constant(A, t) match['is_constant'] = is_constant try: system_info = linodesolve_type(A, t, b=b) except NotImplementedError: return None match.update(system_info) antiderivative = match.pop("antiderivative") if not is_constant: match['commutative_antiderivative'] = antiderivative return match else: match['type_of_equation'] = "type0" if is_second_order: A1, A0 = As[1:] match_second_order = _match_second_order_type(A1, A0, t) match.update(match_second_order) match['is_second_order'] = True # If system is constant, then no need to check if its in euler # form or not. It will be easier and faster to directly proceed # to solve it. if match['type_of_equation'] == "type0" and not is_constant: is_euler = _is_euler_system(As, t) if is_euler: t_ = Symbol('{}_'.format(t)) match.update({'is_transformed': True, 'type_of_equation': 'type1', 't_': t_}) else: is_jordan = lambda M: M == Matrix.jordan_block(M.shape[0], M[0, 0]) terms = _factor_matrix(As[-1], t) if all(A.is_zero_matrix for A in As[1:-1]) and terms is not None and not is_jordan(terms[1]): P, J = terms[1].jordan_form() match.update({'type_of_equation': 'type2', 'J': J, 'f(t)': terms[0], 'P': P, 'is_transformed': True}) if match['type_of_equation'] != 'type0' and is_second_order: match.pop('is_second_order', None) match['is_higher_order'] = is_higher_order return match def _preprocess_eqs(eqs): processed_eqs = [] for eq in eqs: processed_eqs.append(eq if isinstance(eq, Equality) else Eq(eq, 0)) return processed_eqs def _eqs2dict(eqs, funcs): eqsorig = {} eqsmap = {} funcset = set(funcs) for eq in eqs: f1, = eq.lhs.atoms(AppliedUndef) f2s = (eq.rhs.atoms(AppliedUndef) - {f1}) & funcset eqsmap[f1] = f2s eqsorig[f1] = eq return eqsmap, eqsorig def _dict2graph(d): nodes = list(d) edges = [(f1, f2) for f1, f2s in d.items() for f2 in f2s] G = (nodes, edges) return G def _is_type1(scc, t): eqs, funcs = scc try: (A1, A0), b = linear_ode_to_matrix(eqs, funcs, t, 1) except (ODENonlinearError, ODEOrderError): return False if _matrix_is_constant(A0, t) and b.is_zero_matrix: return True return False def _combine_type1_subsystems(subsystem, funcs, t): indices = [i for i, sys in enumerate(zip(subsystem, funcs)) if _is_type1(sys, t)] remove = set() for ip, i in enumerate(indices): for j in indices[ip+1:]: if any(eq2.has(funcs[i]) for eq2 in subsystem[j]): subsystem[j] = subsystem[i] + subsystem[j] remove.add(i) subsystem = [sys for i, sys in enumerate(subsystem) if i not in remove] return subsystem def _component_division(eqs, funcs, t): # Assuming that each eq in eqs is in canonical form, # that is, [f(x).diff(x) = .., g(x).diff(x) = .., etc] # and that the system passed is in its first order eqsmap, eqsorig = _eqs2dict(eqs, funcs) subsystems = [] for cc in connected_components(_dict2graph(eqsmap)): eqsmap_c = {f: eqsmap[f] for f in cc} sccs = strongly_connected_components(_dict2graph(eqsmap_c)) subsystem = [[eqsorig[f] for f in scc] for scc in sccs] subsystem = _combine_type1_subsystems(subsystem, sccs, t) subsystems.append(subsystem) return subsystems # Returns: List of equations def _linear_ode_solver(match): t = match['t'] funcs = match['func'] rhs = match.get('rhs', None) tau = match.get('tau', None) t = match['t_'] if 't_' in match else t A = match['func_coeff'] # Note: To make B None when the matrix has constant # coefficient B = match.get('commutative_antiderivative', None) type = match['type_of_equation'] sol_vector = linodesolve(A, t, b=rhs, B=B, type=type, tau=tau) sol = [Eq(f, s) for f, s in zip(funcs, sol_vector)] return sol def _select_equations(eqs, funcs, key=lambda x: x): eq_dict = {e.lhs: e.rhs for e in eqs} return [Eq(f, eq_dict[key(f)]) for f in funcs] def _higher_order_ode_solver(match): eqs = match["eq"] funcs = match["func"] t = match["t"] sysorder = match['order'] type = match.get('type_of_equation', "type0") is_second_order = match.get('is_second_order', False) is_transformed = match.get('is_transformed', False) is_euler = is_transformed and type == "type1" is_higher_order_type2 = is_transformed and type == "type2" and 'P' in match if is_second_order: new_eqs, new_funcs = _second_order_to_first_order(eqs, funcs, t, A1=match.get("A1", None), A0=match.get("A0", None), b=match.get("rhs", None), type=type, t_=match.get("t_", None)) else: new_eqs, new_funcs = _higher_order_to_first_order(eqs, sysorder, t, funcs=funcs, type=type, J=match.get('J', None), f_t=match.get('f(t)', None), P=match.get('P', None), b=match.get('rhs', None)) if is_transformed: t = match.get('t_', t) if not is_higher_order_type2: new_eqs = _select_equations(new_eqs, [f.diff(t) for f in new_funcs]) sol = None # NotImplementedError may be raised when the system may be actually # solvable if it can be just divided into sub-systems try: if not is_higher_order_type2: sol = _strong_component_solver(new_eqs, new_funcs, t) except NotImplementedError: sol = None # Dividing the system only when it becomes essential if sol is None: try: sol = _component_solver(new_eqs, new_funcs, t) except NotImplementedError: sol = None if sol is None: return sol is_second_order_type2 = is_second_order and type == "type2" underscores = '__' if is_transformed else '_' sol = _select_equations(sol, funcs, key=lambda x: Function(Dummy('{}{}0'.format(x.func.__name__, underscores)))(t)) if match.get("is_transformed", False): if is_second_order_type2: g_t = match["g(t)"] tau = match["tau"] sol = [Eq(s.lhs, s.rhs.subs(t, tau) * g_t) for s in sol] elif is_euler: t = match['t'] tau = match['t_'] sol = [s.subs(tau, log(t)) for s in sol] elif is_higher_order_type2: P = match['P'] sol_vector = P * Matrix([s.rhs for s in sol]) sol = [Eq(f, s) for f, s in zip(funcs, sol_vector)] return sol # Returns: List of equations or None # If None is returned by this solver, then the system # of ODEs cannot be solved directly by dsolve_system. def _strong_component_solver(eqs, funcs, t): from sympy.solvers.ode.ode import dsolve, constant_renumber match = _classify_linear_system(eqs, funcs, t, is_canon=True) sol = None # Assuming that we can't get an implicit system # since we are already canonical equations from # dsolve_system if match: match['t'] = t if match.get('is_higher_order', False): sol = _higher_order_ode_solver(match) elif match.get('is_linear', False): sol = _linear_ode_solver(match) # Note: For now, only linear systems are handled by this function # hence, the match condition is added. This can be removed later. if sol is None and len(eqs) == 1: sol = dsolve(eqs[0], func=funcs[0]) variables = Tuple(eqs[0]).free_symbols new_constants = [Dummy() for _ in range(ode_order(eqs[0], funcs[0]))] sol = constant_renumber(sol, variables=variables, newconstants=new_constants) sol = [sol] # To add non-linear case here in future return sol def _get_funcs_from_canon(eqs): return [eq.lhs.args[0] for eq in eqs] # Returns: List of Equations(a solution) def _weak_component_solver(wcc, t): # We will divide the systems into sccs # only when the wcc cannot be solved as # a whole eqs = [] for scc in wcc: eqs += scc funcs = _get_funcs_from_canon(eqs) sol = _strong_component_solver(eqs, funcs, t) if sol: return sol sol = [] for j, scc in enumerate(wcc): eqs = scc funcs = _get_funcs_from_canon(eqs) # Substituting solutions for the dependent # variables solved in previous SCC, if any solved. comp_eqs = [eq.subs({s.lhs: s.rhs for s in sol}) for eq in eqs] scc_sol = _strong_component_solver(comp_eqs, funcs, t) if scc_sol is None: raise NotImplementedError(filldedent(''' The system of ODEs passed cannot be solved by dsolve_system. ''')) # scc_sol: List of equations # scc_sol is a solution sol += scc_sol return sol # Returns: List of Equations(a solution) def _component_solver(eqs, funcs, t): components = _component_division(eqs, funcs, t) sol = [] for wcc in components: # wcc_sol: List of Equations sol += _weak_component_solver(wcc, t) # sol: List of Equations return sol def _second_order_to_first_order(eqs, funcs, t, type="auto", A1=None, A0=None, b=None, t_=None): r""" Expects the system to be in second order and in canonical form Explanation =========== Reduces a second order system into a first order one depending on the type of second order system. 1. "type0": If this is passed, then the system will be reduced to first order by introducing dummy variables. 2. "type1": If this is passed, then a particular substitution will be used to reduce the the system into first order. 3. "type2": If this is passed, then the system will be transformed with new dependent variables and independent variables. This transformation is a part of solving the corresponding system of ODEs. `A1` and `A0` are the coefficient matrices from the system and it is assumed that the second order system has the form given below: .. math:: A2 * X'' = A1 * X' + A0 * X + b Here, $A2$ is the coefficient matrix for the vector $X''$ and $b$ is the non-homogeneous term. Default value for `b` is None but if `A1` and `A0` are passed and `b` is not passed, then the system will be assumed homogeneous. """ is_a1 = A1 is None is_a0 = A0 is None if (type == "type1" and is_a1) or (type == "type2" and is_a0)\ or (type == "auto" and (is_a1 or is_a0)): (A2, A1, A0), b = linear_ode_to_matrix(eqs, funcs, t, 2) if not A2.is_Identity: raise ValueError(filldedent(''' The system must be in its canonical form. ''')) if type == "auto": match = _match_second_order_type(A1, A0, t) type = match["type_of_equation"] A1 = match.get("A1", None) A0 = match.get("A0", None) sys_order = {func: 2 for func in funcs} if type == "type1": if b is None: b = zeros(len(eqs)) eqs = _second_order_subs_type1(A1, b, funcs, t) sys_order = {func: 1 for func in funcs} if type == "type2": if t_ is None: t_ = Symbol("{}_".format(t)) t = t_ eqs, funcs = _second_order_subs_type2(A0, funcs, t_) sys_order = {func: 2 for func in funcs} return _higher_order_to_first_order(eqs, sys_order, t, funcs=funcs) def _higher_order_type2_to_sub_systems(J, f_t, funcs, t, max_order, b=None, P=None): # Note: To add a test for this ValueError if J is None or f_t is None or not _matrix_is_constant(J, t): raise ValueError(filldedent(''' Correctly input for args 'A' and 'f_t' for Linear, Higher Order, Type 2 ''')) if P is None and b is not None and not b.is_zero_matrix: raise ValueError(filldedent(''' Provide the keyword 'P' for matrix P in A = P * J * P-1. ''')) new_funcs = Matrix([Function(Dummy('{}__0'.format(f.func.__name__)))(t) for f in funcs]) new_eqs = new_funcs.diff(t, max_order) - f_t * J * new_funcs if b is not None and not b.is_zero_matrix: new_eqs -= P.inv() * b new_eqs = canonical_odes(new_eqs, new_funcs, t)[0] return new_eqs, new_funcs def _higher_order_to_first_order(eqs, sys_order, t, funcs=None, type="type0", **kwargs): if funcs is None: funcs = sys_order.keys() # Standard Cauchy Euler system if type == "type1": t_ = Symbol('{}_'.format(t)) new_funcs = [Function(Dummy('{}_'.format(f.func.__name__)))(t_) for f in funcs] max_order = max(sys_order[func] for func in funcs) subs_dict = {func: new_func for func, new_func in zip(funcs, new_funcs)} subs_dict[t] = exp(t_) free_function = Function(Dummy()) def _get_coeffs_from_subs_expression(expr): if isinstance(expr, Subs): free_symbol = expr.args[1][0] term = expr.args[0] return {ode_order(term, free_symbol): 1} if isinstance(expr, Mul): coeff = expr.args[0] order = list(_get_coeffs_from_subs_expression(expr.args[1]).keys())[0] return {order: coeff} if isinstance(expr, Add): coeffs = {} for arg in expr.args: if isinstance(arg, Mul): coeffs.update(_get_coeffs_from_subs_expression(arg)) else: order = list(_get_coeffs_from_subs_expression(arg).keys())[0] coeffs[order] = 1 return coeffs for o in range(1, max_order + 1): expr = free_function(log(t_)).diff(t_, o)*t_**o coeff_dict = _get_coeffs_from_subs_expression(expr) coeffs = [coeff_dict[order] if order in coeff_dict else 0 for order in range(o + 1)] expr_to_subs = sum(free_function(t_).diff(t_, i) * c for i, c in enumerate(coeffs)) / t**o subs_dict.update({f.diff(t, o): expr_to_subs.subs(free_function(t_), nf) for f, nf in zip(funcs, new_funcs)}) new_eqs = [eq.subs(subs_dict) for eq in eqs] new_sys_order = {nf: sys_order[f] for f, nf in zip(funcs, new_funcs)} new_eqs = canonical_odes(new_eqs, new_funcs, t_)[0] return _higher_order_to_first_order(new_eqs, new_sys_order, t_, funcs=new_funcs) # Systems of the form: X(n)(t) = f(t)*A*X + b # where X(n)(t) is the nth derivative of the vector of dependent variables # with respect to the independent variable and A is a constant matrix. if type == "type2": J = kwargs.get('J', None) f_t = kwargs.get('f_t', None) b = kwargs.get('b', None) P = kwargs.get('P', None) max_order = max(sys_order[func] for func in funcs) return _higher_order_type2_to_sub_systems(J, f_t, funcs, t, max_order, P=P, b=b) # Note: To be changed to this after doit option is disabled for default cases # new_sysorder = _get_func_order(new_eqs, new_funcs) # # return _higher_order_to_first_order(new_eqs, new_sysorder, t, funcs=new_funcs) new_funcs = [] for prev_func in funcs: func_name = prev_func.func.__name__ func = Function(Dummy('{}_0'.format(func_name)))(t) new_funcs.append(func) subs_dict = {prev_func: func} new_eqs = [] for i in range(1, sys_order[prev_func]): new_func = Function(Dummy('{}_{}'.format(func_name, i)))(t) subs_dict[prev_func.diff(t, i)] = new_func new_funcs.append(new_func) prev_f = subs_dict[prev_func.diff(t, i-1)] new_eq = Eq(prev_f.diff(t), new_func) new_eqs.append(new_eq) eqs = [eq.subs(subs_dict) for eq in eqs] + new_eqs return eqs, new_funcs def dsolve_system(eqs, funcs=None, t=None, ics=None, doit=False, simplify=True): r""" Solves any(supported) system of Ordinary Differential Equations Explanation =========== This function takes a system of ODEs as an input, determines if the it is solvable by this function, and returns the solution if found any. This function can handle: 1. Linear, First Order, Constant coefficient homogeneous system of ODEs 2. Linear, First Order, Constant coefficient non-homogeneous system of ODEs 3. Linear, First Order, non-constant coefficient homogeneous system of ODEs 4. Linear, First Order, non-constant coefficient non-homogeneous system of ODEs 5. Any implicit system which can be divided into system of ODEs which is of the above 4 forms 6. Any higher order linear system of ODEs that can be reduced to one of the 5 forms of systems described above. The types of systems described above are not limited by the number of equations, i.e. this function can solve the above types irrespective of the number of equations in the system passed. But, the bigger the system, the more time it will take to solve the system. This function returns a list of solutions. Each solution is a list of equations where LHS is the dependent variable and RHS is an expression in terms of the independent variable. Among the non constant coefficient types, not all the systems are solvable by this function. Only those which have either a coefficient matrix with a commutative antiderivative or those systems which may be divided further so that the divided systems may have coefficient matrix with commutative antiderivative. Parameters ========== eqs : List system of ODEs to be solved funcs : List or None List of dependent variables that make up the system of ODEs t : Symbol or None Independent variable in the system of ODEs ics : Dict or None Set of initial boundary/conditions for the system of ODEs doit : Boolean Evaluate the solutions if True. Default value is True. Can be set to false if the integral evaluation takes too much time and/or is not required. simplify: Boolean Simplify the solutions for the systems. Default value is True. Can be set to false if simplification takes too much time and/or is not required. Examples ======== >>> from sympy import symbols, Eq, Function >>> from sympy.solvers.ode.systems import dsolve_system >>> f, g = symbols("f g", cls=Function) >>> x = symbols("x") >>> eqs = [Eq(f(x).diff(x), g(x)), Eq(g(x).diff(x), f(x))] >>> dsolve_system(eqs) [[Eq(f(x), -C1*exp(-x) + C2*exp(x)), Eq(g(x), C1*exp(-x) + C2*exp(x))]] You can also pass the initial conditions for the system of ODEs: >>> dsolve_system(eqs, ics={f(0): 1, g(0): 0}) [[Eq(f(x), exp(x)/2 + exp(-x)/2), Eq(g(x), exp(x)/2 - exp(-x)/2)]] Optionally, you can pass the dependent variables and the independent variable for which the system is to be solved: >>> funcs = [f(x), g(x)] >>> dsolve_system(eqs, funcs=funcs, t=x) [[Eq(f(x), -C1*exp(-x) + C2*exp(x)), Eq(g(x), C1*exp(-x) + C2*exp(x))]] Lets look at an implicit system of ODEs: >>> eqs = [Eq(f(x).diff(x)**2, g(x)**2), Eq(g(x).diff(x), g(x))] >>> dsolve_system(eqs) [[Eq(f(x), C1 - C2*exp(x)), Eq(g(x), C2*exp(x))], [Eq(f(x), C1 + C2*exp(x)), Eq(g(x), C2*exp(x))]] Returns ======= List of List of Equations Raises ====== NotImplementedError When the system of ODEs is not solvable by this function. ValueError When the parameters passed are not in the required form. """ from sympy.solvers.ode.ode import solve_ics, _extract_funcs, constant_renumber if not iterable(eqs): raise ValueError(filldedent(''' List of equations should be passed. The input is not valid. ''')) eqs = _preprocess_eqs(eqs) if funcs is not None and not isinstance(funcs, list): raise ValueError(filldedent(''' Input to the funcs should be a list of functions. ''')) if funcs is None: funcs = _extract_funcs(eqs) if any(len(func.args) != 1 for func in funcs): raise ValueError(filldedent(''' dsolve_system can solve a system of ODEs with only one independent variable. ''')) if len(eqs) != len(funcs): raise ValueError(filldedent(''' Number of equations and number of functions do not match ''')) if t is not None and not isinstance(t, Symbol): raise ValueError(filldedent(''' The indepedent variable must be of type Symbol ''')) if t is None: t = list(list(eqs[0].atoms(Derivative))[0].atoms(Symbol))[0] sols = [] canon_eqs = canonical_odes(eqs, funcs, t) for canon_eq in canon_eqs: try: sol = _strong_component_solver(canon_eq, funcs, t) except NotImplementedError: sol = None if sol is None: sol = _component_solver(canon_eq, funcs, t) sols.append(sol) if sols: final_sols = [] variables = Tuple(*eqs).free_symbols for sol in sols: sol = _select_equations(sol, funcs) sol = constant_renumber(sol, variables=variables) if ics: constants = Tuple(*sol).free_symbols - variables solved_constants = solve_ics(sol, funcs, constants, ics) sol = [s.subs(solved_constants) for s in sol] if simplify: constants = Tuple(*sol).free_symbols - variables sol = simpsol(sol, [t], constants, doit=doit) final_sols.append(sol) sols = final_sols return sols
c58eae4734eb19b1860488b5f997807b3c1e9151bc29cab8298a3cca4219bee4
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 = {y: S.Zero, x: S.Zero} assert solve((x - y, x + y), x, y ) == solution assert solve((x - y, x + y), (x, y)) == solution assert solve((x - y, x + y), [x, y]) == solution assert set(solve(x**3 - 15*x - 4, x)) == { -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, z: t*(-n-1)/n, y: 0} 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 @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)))] 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_22717(): assert solve((-y**2 + log(y**2/x) + 2, -2*x*y + 2*x/y)) == [ {y: -1, x: E}, {y: 1, x: E}]
ec652c0d0419b586d920ad29d14c6c3ae34427112de081de392b1e9bf93e9345
from sympy.solvers.decompogen import decompogen, compogen from sympy.core.symbol import symbols from sympy.functions.elementary.complexes import Abs from sympy.functions.elementary.exponential import exp from sympy.functions.elementary.miscellaneous import sqrt, Max from sympy.functions.elementary.trigonometric import (cos, sin) from sympy.testing.pytest import XFAIL, raises x, y = symbols('x y') def test_decompogen(): assert decompogen(sin(cos(x)), x) == [sin(x), cos(x)] assert decompogen(sin(x)**2 + sin(x) + 1, x) == [x**2 + x + 1, sin(x)] assert decompogen(sqrt(6*x**2 - 5), x) == [sqrt(x), 6*x**2 - 5] assert decompogen(sin(sqrt(cos(x**2 + 1))), x) == [sin(x), sqrt(x), cos(x), x**2 + 1] assert decompogen(Abs(cos(x)**2 + 3*cos(x) - 4), x) == [Abs(x), x**2 + 3*x - 4, cos(x)] assert decompogen(sin(x)**2 + sin(x) - sqrt(3)/2, x) == [x**2 + x - sqrt(3)/2, sin(x)] assert decompogen(Abs(cos(y)**2 + 3*cos(x) - 4), x) == [Abs(x), 3*x + cos(y)**2 - 4, cos(x)] assert decompogen(x, y) == [x] assert decompogen(1, x) == [1] assert decompogen(Max(3, x), x) == [Max(3, x)] raises(TypeError, lambda: decompogen(x < 5, x)) u = 2*x + 3 assert decompogen(Max(sqrt(u),(u)**2), x) == [Max(sqrt(x), x**2), u] assert decompogen(Max(u, u**2, y), x) == [Max(x, x**2, y), u] assert decompogen(Max(sin(x), u), x) == [Max(2*x + 3, sin(x))] def test_decompogen_poly(): assert decompogen(x**4 + 2*x**2 + 1, x) == [x**2 + 2*x + 1, x**2] assert decompogen(x**4 + 2*x**3 - x - 1, x) == [x**2 - x - 1, x**2 + x] @XFAIL def test_decompogen_fails(): A = lambda x: x**2 + 2*x + 3 B = lambda x: 4*x**2 + 5*x + 6 assert decompogen(A(x*exp(x)), x) == [x**2 + 2*x + 3, x*exp(x)] assert decompogen(A(B(x)), x) == [x**2 + 2*x + 3, 4*x**2 + 5*x + 6] assert decompogen(A(1/x + 1/x**2), x) == [x**2 + 2*x + 3, 1/x + 1/x**2] assert decompogen(A(1/x + 2/(x + 1)), x) == [x**2 + 2*x + 3, 1/x + 2/(x + 1)] def test_compogen(): assert compogen([sin(x), cos(x)], x) == sin(cos(x)) assert compogen([x**2 + x + 1, sin(x)], x) == sin(x)**2 + sin(x) + 1 assert compogen([sqrt(x), 6*x**2 - 5], x) == sqrt(6*x**2 - 5) assert compogen([sin(x), sqrt(x), cos(x), x**2 + 1], x) == sin(sqrt( cos(x**2 + 1))) assert compogen([Abs(x), x**2 + 3*x - 4, cos(x)], x) == Abs(cos(x)**2 + 3*cos(x) - 4) assert compogen([x**2 + x - sqrt(3)/2, sin(x)], x) == (sin(x)**2 + sin(x) - sqrt(3)/2) assert compogen([Abs(x), 3*x + cos(y)**2 - 4, cos(x)], x) == \ Abs(3*cos(x) + cos(y)**2 - 4) assert compogen([x**2 + 2*x + 1, x**2], x) == x**4 + 2*x**2 + 1 # the result is in unsimplified form assert compogen([x**2 - x - 1, x**2 + x], x) == -x**2 - x + (x**2 + x)**2 - 1
f2d002b72696277ab1fbea30b71276899edf64b09c1734db161b8781713ba202
# # 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 (acosh, 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(C1*sqrt(-1/C1)*(C2 + x)) - 1))), Eq(f(x), log(C1/(cos(C1*sqrt(-1/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(log(x), C1 - log(f(x)/x) + acosh(f(x)/x))], }, } } 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
4b9fd81065b4cfbc73ced85286b4ac836c009b313d991e2ee0d773bb3c3f1b1f
from sympy.core.numbers import (E, I, Rational, oo, pi) from sympy.core.singleton import S from sympy.core.symbol import (Symbol, symbols) from sympy.functions.elementary.complexes import (Abs, re) 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 (cos, cot, csc, sec, sin, tan) from sympy.functions.special.error_functions import expint from sympy.matrices.expressions.matexpr import MatrixSymbol from sympy.simplify.simplify import simplify from sympy.calculus.util import (function_range, continuous_domain, not_empty_in, periodicity, lcim, is_convex, stationary_points, minimum, maximum) from sympy.sets.sets import (Interval, FiniteSet, Complement, Union) from sympy.testing.pytest import raises, _both_exp_pow from sympy.abc import x a = Symbol('a', real=True) def test_function_range(): x, y, a, b = symbols('x y a b') assert function_range(sin(x), x, Interval(-pi/2, pi/2) ) == Interval(-1, 1) assert function_range(sin(x), x, Interval(0, pi) ) == Interval(0, 1) assert function_range(tan(x), x, Interval(0, pi) ) == Interval(-oo, oo) assert function_range(tan(x), x, Interval(pi/2, pi) ) == Interval(-oo, 0) assert function_range((x + 3)/(x - 2), x, Interval(-5, 5) ) == Union(Interval(-oo, Rational(2, 7)), Interval(Rational(8, 3), oo)) assert function_range(1/(x**2), x, Interval(-1, 1) ) == Interval(1, oo) assert function_range(exp(x), x, Interval(-1, 1) ) == Interval(exp(-1), exp(1)) assert function_range(log(x) - x, x, S.Reals ) == Interval(-oo, -1) assert function_range(sqrt(3*x - 1), x, Interval(0, 2) ) == Interval(0, sqrt(5)) assert function_range(x*(x - 1) - (x**2 - x), x, S.Reals ) == FiniteSet(0) assert function_range(x*(x - 1) - (x**2 - x) + y, x, S.Reals ) == FiniteSet(y) assert function_range(sin(x), x, Union(Interval(-5, -3), FiniteSet(4)) ) == Union(Interval(-sin(3), 1), FiniteSet(sin(4))) assert function_range(cos(x), x, Interval(-oo, -4) ) == Interval(-1, 1) assert function_range(cos(x), x, S.EmptySet) == S.EmptySet assert function_range(x/sqrt(x**2+1), x, S.Reals) == Interval.open(-1,1) raises(NotImplementedError, lambda : function_range( exp(x)*(sin(x) - cos(x))/2 - x, x, S.Reals)) raises(NotImplementedError, lambda : function_range( sin(x) + x, x, S.Reals)) # issue 13273 raises(NotImplementedError, lambda : function_range( log(x), x, S.Integers)) raises(NotImplementedError, lambda : function_range( sin(x)/2, x, S.Naturals)) def test_continuous_domain(): x = Symbol('x') assert continuous_domain(sin(x), x, Interval(0, 2*pi)) == Interval(0, 2*pi) assert continuous_domain(tan(x), x, Interval(0, 2*pi)) == \ Union(Interval(0, pi/2, False, True), Interval(pi/2, pi*Rational(3, 2), True, True), Interval(pi*Rational(3, 2), 2*pi, True, False)) assert continuous_domain((x - 1)/((x - 1)**2), x, S.Reals) == \ Union(Interval(-oo, 1, True, True), Interval(1, oo, True, True)) assert continuous_domain(log(x) + log(4*x - 1), x, S.Reals) == \ Interval(Rational(1, 4), oo, True, True) assert continuous_domain(1/sqrt(x - 3), x, S.Reals) == Interval(3, oo, True, True) assert continuous_domain(1/x - 2, x, S.Reals) == \ Union(Interval.open(-oo, 0), Interval.open(0, oo)) assert continuous_domain(1/(x**2 - 4) + 2, x, S.Reals) == \ Union(Interval.open(-oo, -2), Interval.open(-2, 2), Interval.open(2, oo)) domain = continuous_domain(log(tan(x)**2 + 1), x, S.Reals) assert not domain.contains(3*pi/2) assert domain.contains(5) d = Symbol('d', even=True, zero=False) assert continuous_domain(x**(1/d), x, S.Reals) == Interval(0, oo) def test_not_empty_in(): assert not_empty_in(FiniteSet(x, 2*x).intersect(Interval(1, 2, True, False)), x) == \ Interval(S.Half, 2, True, False) assert not_empty_in(FiniteSet(x, x**2).intersect(Interval(1, 2)), x) == \ Union(Interval(-sqrt(2), -1), Interval(1, 2)) assert not_empty_in(FiniteSet(x**2 + x, x).intersect(Interval(2, 4)), x) == \ Union(Interval(-sqrt(17)/2 - S.Half, -2), Interval(1, Rational(-1, 2) + sqrt(17)/2), Interval(2, 4)) assert not_empty_in(FiniteSet(x/(x - 1)).intersect(S.Reals), x) == \ Complement(S.Reals, FiniteSet(1)) assert not_empty_in(FiniteSet(a/(a - 1)).intersect(S.Reals), a) == \ Complement(S.Reals, FiniteSet(1)) assert not_empty_in(FiniteSet((x**2 - 3*x + 2)/(x - 1)).intersect(S.Reals), x) == \ Complement(S.Reals, FiniteSet(1)) assert not_empty_in(FiniteSet(3, 4, x/(x - 1)).intersect(Interval(2, 3)), x) == \ Interval(-oo, oo) assert not_empty_in(FiniteSet(4, x/(x - 1)).intersect(Interval(2, 3)), x) == \ Interval(S(3)/2, 2) assert not_empty_in(FiniteSet(x/(x**2 - 1)).intersect(S.Reals), x) == \ Complement(S.Reals, FiniteSet(-1, 1)) assert not_empty_in(FiniteSet(x, x**2).intersect(Union(Interval(1, 3, True, True), Interval(4, 5))), x) == \ Union(Interval(-sqrt(5), -2), Interval(-sqrt(3), -1, True, True), Interval(1, 3, True, True), Interval(4, 5)) assert not_empty_in(FiniteSet(1).intersect(Interval(3, 4)), x) == S.EmptySet assert not_empty_in(FiniteSet(x**2/(x + 2)).intersect(Interval(1, oo)), x) == \ Union(Interval(-2, -1, True, False), Interval(2, oo)) raises(ValueError, lambda: not_empty_in(x)) raises(ValueError, lambda: not_empty_in(Interval(0, 1), x)) raises(NotImplementedError, lambda: not_empty_in(FiniteSet(x).intersect(S.Reals), x, a)) @_both_exp_pow def test_periodicity(): x = Symbol('x') y = Symbol('y') z = Symbol('z', real=True) assert periodicity(sin(2*x), x) == pi assert periodicity((-2)*tan(4*x), x) == pi/4 assert periodicity(sin(x)**2, x) == 2*pi assert periodicity(3**tan(3*x), x) == pi/3 assert periodicity(tan(x)*cos(x), x) == 2*pi assert periodicity(sin(x)**(tan(x)), x) == 2*pi assert periodicity(tan(x)*sec(x), x) == 2*pi assert periodicity(sin(2*x)*cos(2*x) - y, x) == pi/2 assert periodicity(tan(x) + cot(x), x) == pi assert periodicity(sin(x) - cos(2*x), x) == 2*pi assert periodicity(sin(x) - 1, x) == 2*pi assert periodicity(sin(4*x) + sin(x)*cos(x), x) == pi assert periodicity(exp(sin(x)), x) == 2*pi assert periodicity(log(cot(2*x)) - sin(cos(2*x)), x) == pi assert periodicity(sin(2*x)*exp(tan(x) - csc(2*x)), x) == pi assert periodicity(cos(sec(x) - csc(2*x)), x) == 2*pi assert periodicity(tan(sin(2*x)), x) == pi assert periodicity(2*tan(x)**2, x) == pi assert periodicity(sin(x%4), x) == 4 assert periodicity(sin(x)%4, x) == 2*pi assert periodicity(tan((3*x-2)%4), x) == Rational(4, 3) assert periodicity((sqrt(2)*(x+1)+x) % 3, x) == 3 / (sqrt(2)+1) assert periodicity((x**2+1) % x, x) is None assert periodicity(sin(re(x)), x) == 2*pi assert periodicity(sin(x)**2 + cos(x)**2, x) is S.Zero assert periodicity(tan(x), y) is S.Zero assert periodicity(sin(x) + I*cos(x), x) == 2*pi assert periodicity(x - sin(2*y), y) == pi assert periodicity(exp(x), x) is None assert periodicity(exp(I*x), x) == 2*pi assert periodicity(exp(I*z), z) == 2*pi assert periodicity(exp(z), z) is None assert periodicity(exp(log(sin(z) + I*cos(2*z)), evaluate=False), z) == 2*pi assert periodicity(exp(log(sin(2*z) + I*cos(z)), evaluate=False), z) == 2*pi assert periodicity(exp(sin(z)), z) == 2*pi assert periodicity(exp(2*I*z), z) == pi assert periodicity(exp(z + I*sin(z)), z) is None assert periodicity(exp(cos(z/2) + sin(z)), z) == 4*pi assert periodicity(log(x), x) is None assert periodicity(exp(x)**sin(x), x) is None assert periodicity(sin(x)**y, y) is None assert periodicity(Abs(sin(Abs(sin(x)))), x) == pi assert all(periodicity(Abs(f(x)), x) == pi for f in ( cos, sin, sec, csc, tan, cot)) assert periodicity(Abs(sin(tan(x))), x) == pi assert periodicity(Abs(sin(sin(x) + tan(x))), x) == 2*pi assert periodicity(sin(x) > S.Half, x) == 2*pi assert periodicity(x > 2, x) is None assert periodicity(x**3 - x**2 + 1, x) is None assert periodicity(Abs(x), x) is None assert periodicity(Abs(x**2 - 1), x) is None assert periodicity((x**2 + 4)%2, x) is None assert periodicity((E**x)%3, x) is None assert periodicity(sin(expint(1, x))/expint(1, x), x) is None # returning `None` for any Piecewise p = Piecewise((0, x < -1), (x**2, x <= 1), (log(x), True)) assert periodicity(p, x) is None m = MatrixSymbol('m', 3, 3) raises(NotImplementedError, lambda: periodicity(sin(m), m)) raises(NotImplementedError, lambda: periodicity(sin(m[0, 0]), m)) raises(NotImplementedError, lambda: periodicity(sin(m), m[0, 0])) raises(NotImplementedError, lambda: periodicity(sin(m[0, 0]), m[0, 0])) def test_periodicity_check(): x = Symbol('x') y = Symbol('y') assert periodicity(tan(x), x, check=True) == pi assert periodicity(sin(x) + cos(x), x, check=True) == 2*pi assert periodicity(sec(x), x) == 2*pi assert periodicity(sin(x*y), x) == 2*pi/abs(y) assert periodicity(Abs(sec(sec(x))), x) == pi def test_lcim(): assert lcim([S.Half, S(2), S(3)]) == 6 assert lcim([pi/2, pi/4, pi]) == pi assert lcim([2*pi, pi/2]) == 2*pi assert lcim([S.One, 2*pi]) is None assert lcim([S(2) + 2*E, E/3 + Rational(1, 3), S.One + E]) == S(2) + 2*E def test_is_convex(): assert is_convex(1/x, x, domain=Interval.open(0, oo)) == True assert is_convex(1/x, x, domain=Interval(-oo, 0)) == False assert is_convex(x**2, x, domain=Interval(0, oo)) == True assert is_convex(1/x**3, x, domain=Interval.Lopen(0, oo)) == True assert is_convex(-1/x**3, x, domain=Interval.Ropen(-oo, 0)) == True assert is_convex(log(x), x) == False raises(NotImplementedError, lambda: is_convex(log(x), x, a)) def test_stationary_points(): x, y = symbols('x y') assert stationary_points(sin(x), x, Interval(-pi/2, pi/2) ) == {-pi/2, pi/2} assert stationary_points(sin(x), x, Interval.Ropen(0, pi/4) ) is S.EmptySet assert stationary_points(tan(x), x, ) is S.EmptySet assert stationary_points(sin(x)*cos(x), x, Interval(0, pi) ) == {pi/4, pi*Rational(3, 4)} assert stationary_points(sec(x), x, Interval(0, pi) ) == {0, pi} assert stationary_points((x+3)*(x-2), x ) == FiniteSet(Rational(-1, 2)) assert stationary_points((x + 3)/(x - 2), x, Interval(-5, 5) ) is S.EmptySet assert stationary_points((x**2+3)/(x-2), x ) == {2 - sqrt(7), 2 + sqrt(7)} assert stationary_points((x**2+3)/(x-2), x, Interval(0, 5) ) == {2 + sqrt(7)} assert stationary_points(x**4 + x**3 - 5*x**2, x, S.Reals ) == FiniteSet(-2, 0, Rational(5, 4)) assert stationary_points(exp(x), x ) is S.EmptySet assert stationary_points(log(x) - x, x, S.Reals ) == {1} assert stationary_points(cos(x), x, Union(Interval(0, 5), Interval(-6, -3)) ) == {0, -pi, pi} assert stationary_points(y, x, S.Reals ) == S.Reals assert stationary_points(y, x, S.EmptySet) == S.EmptySet def test_maximum(): x, y = symbols('x y') assert maximum(sin(x), x) is S.One assert maximum(sin(x), x, Interval(0, 1)) == sin(1) assert maximum(tan(x), x) is oo assert maximum(tan(x), x, Interval(-pi/4, pi/4)) is S.One assert maximum(sin(x)*cos(x), x, S.Reals) == S.Half assert simplify(maximum(sin(x)*cos(x), x, Interval(pi*Rational(3, 8), pi*Rational(5, 8))) ) == sqrt(2)/4 assert maximum((x+3)*(x-2), x) is oo assert maximum((x+3)*(x-2), x, Interval(-5, 0)) == S(14) assert maximum((x+3)/(x-2), x, Interval(-5, 0)) == Rational(2, 7) assert simplify(maximum(-x**4-x**3+x**2+10, x) ) == 41*sqrt(41)/512 + Rational(5419, 512) assert maximum(exp(x), x, Interval(-oo, 2)) == exp(2) assert maximum(log(x) - x, x, S.Reals) is S.NegativeOne assert maximum(cos(x), x, Union(Interval(0, 5), Interval(-6, -3)) ) is S.One assert maximum(cos(x)-sin(x), x, S.Reals) == sqrt(2) assert maximum(y, x, S.Reals) == y assert maximum(abs(a**3 + a), a, Interval(0, 2)) == 10 assert maximum(abs(60*a**3 + 24*a), a, Interval(0, 2)) == 528 assert maximum(abs(12*a*(5*a**2 + 2)), a, Interval(0, 2)) == 528 assert maximum(x/sqrt(x**2+1), x, S.Reals) == 1 raises(ValueError, lambda : maximum(sin(x), x, S.EmptySet)) raises(ValueError, lambda : maximum(log(cos(x)), x, S.EmptySet)) raises(ValueError, lambda : maximum(1/(x**2 + y**2 + 1), x, S.EmptySet)) raises(ValueError, lambda : maximum(sin(x), sin(x))) raises(ValueError, lambda : maximum(sin(x), x*y, S.EmptySet)) raises(ValueError, lambda : maximum(sin(x), S.One)) def test_minimum(): x, y = symbols('x y') assert minimum(sin(x), x) is S.NegativeOne assert minimum(sin(x), x, Interval(1, 4)) == sin(4) assert minimum(tan(x), x) is -oo assert minimum(tan(x), x, Interval(-pi/4, pi/4)) is S.NegativeOne assert minimum(sin(x)*cos(x), x, S.Reals) == Rational(-1, 2) assert simplify(minimum(sin(x)*cos(x), x, Interval(pi*Rational(3, 8), pi*Rational(5, 8))) ) == -sqrt(2)/4 assert minimum((x+3)*(x-2), x) == Rational(-25, 4) assert minimum((x+3)/(x-2), x, Interval(-5, 0)) == Rational(-3, 2) assert minimum(x**4-x**3+x**2+10, x) == S(10) assert minimum(exp(x), x, Interval(-2, oo)) == exp(-2) assert minimum(log(x) - x, x, S.Reals) is -oo assert minimum(cos(x), x, Union(Interval(0, 5), Interval(-6, -3)) ) is S.NegativeOne assert minimum(cos(x)-sin(x), x, S.Reals) == -sqrt(2) assert minimum(y, x, S.Reals) == y assert minimum(x/sqrt(x**2+1), x, S.Reals) == -1 raises(ValueError, lambda : minimum(sin(x), x, S.EmptySet)) raises(ValueError, lambda : minimum(log(cos(x)), x, S.EmptySet)) raises(ValueError, lambda : minimum(1/(x**2 + y**2 + 1), x, S.EmptySet)) raises(ValueError, lambda : minimum(sin(x), sin(x))) raises(ValueError, lambda : minimum(sin(x), x*y, S.EmptySet)) raises(ValueError, lambda : minimum(sin(x), S.One)) def test_issue_19869(): t = symbols('t') assert (maximum(sqrt(3)*(t - 1)/(3*sqrt(t**2 + 1)), t) ) == sqrt(3)/3 def test_issue_16469(): x = Symbol("x", real=True) f = abs(x) assert function_range(f, x, S.Reals) == Interval(0, oo, False, True) @_both_exp_pow def test_issue_18747(): assert periodicity(exp(pi*I*(x/4+S.Half/2)), x) == 8
579dae34336f6ab70afc55e75ab3d98e27c5311593cbfd87e25b77166bc0e16e
from itertools import product from sympy.core.function import (Function, diff) from sympy.core.numbers import Rational from sympy.core.singleton import S from sympy.core.symbol import symbols from sympy.functions.elementary.exponential import exp from sympy.calculus.finite_diff import ( apply_finite_diff, differentiate_finite, finite_diff_weights, _as_finite_diff ) from sympy.testing.pytest import raises, warns_deprecated_sympy def test_apply_finite_diff(): x, h = symbols('x h') f = Function('f') assert (apply_finite_diff(1, [x-h, x+h], [f(x-h), f(x+h)], x) - (f(x+h)-f(x-h))/(2*h)).simplify() == 0 assert (apply_finite_diff(1, [5, 6, 7], [f(5), f(6), f(7)], 5) - (Rational(-3, 2)*f(5) + 2*f(6) - S.Half*f(7))).simplify() == 0 raises(ValueError, lambda: apply_finite_diff(1, [x, h], [f(x)])) def test_finite_diff_weights(): d = finite_diff_weights(1, [5, 6, 7], 5) assert d[1][2] == [Rational(-3, 2), 2, Rational(-1, 2)] # Table 1, p. 702 in doi:10.1090/S0025-5718-1988-0935077-0 # -------------------------------------------------------- xl = [0, 1, -1, 2, -2, 3, -3, 4, -4] # d holds all coefficients d = finite_diff_weights(4, xl, S.Zero) # Zeroeth derivative for i in range(5): assert d[0][i] == [S.One] + [S.Zero]*8 # First derivative assert d[1][0] == [S.Zero]*9 assert d[1][2] == [S.Zero, S.Half, Rational(-1, 2)] + [S.Zero]*6 assert d[1][4] == [S.Zero, Rational(2, 3), Rational(-2, 3), Rational(-1, 12), Rational(1, 12)] + [S.Zero]*4 assert d[1][6] == [S.Zero, Rational(3, 4), Rational(-3, 4), Rational(-3, 20), Rational(3, 20), Rational(1, 60), Rational(-1, 60)] + [S.Zero]*2 assert d[1][8] == [S.Zero, Rational(4, 5), Rational(-4, 5), Rational(-1, 5), Rational(1, 5), Rational(4, 105), Rational(-4, 105), Rational(-1, 280), Rational(1, 280)] # Second derivative for i in range(2): assert d[2][i] == [S.Zero]*9 assert d[2][2] == [-S(2), S.One, S.One] + [S.Zero]*6 assert d[2][4] == [Rational(-5, 2), Rational(4, 3), Rational(4, 3), Rational(-1, 12), Rational(-1, 12)] + [S.Zero]*4 assert d[2][6] == [Rational(-49, 18), Rational(3, 2), Rational(3, 2), Rational(-3, 20), Rational(-3, 20), Rational(1, 90), Rational(1, 90)] + [S.Zero]*2 assert d[2][8] == [Rational(-205, 72), Rational(8, 5), Rational(8, 5), Rational(-1, 5), Rational(-1, 5), Rational(8, 315), Rational(8, 315), Rational(-1, 560), Rational(-1, 560)] # Third derivative for i in range(3): assert d[3][i] == [S.Zero]*9 assert d[3][4] == [S.Zero, -S.One, S.One, S.Half, Rational(-1, 2)] + [S.Zero]*4 assert d[3][6] == [S.Zero, Rational(-13, 8), Rational(13, 8), S.One, -S.One, Rational(-1, 8), Rational(1, 8)] + [S.Zero]*2 assert d[3][8] == [S.Zero, Rational(-61, 30), Rational(61, 30), Rational(169, 120), Rational(-169, 120), Rational(-3, 10), Rational(3, 10), Rational(7, 240), Rational(-7, 240)] # Fourth derivative for i in range(4): assert d[4][i] == [S.Zero]*9 assert d[4][4] == [S(6), -S(4), -S(4), S.One, S.One] + [S.Zero]*4 assert d[4][6] == [Rational(28, 3), Rational(-13, 2), Rational(-13, 2), S(2), S(2), Rational(-1, 6), Rational(-1, 6)] + [S.Zero]*2 assert d[4][8] == [Rational(91, 8), Rational(-122, 15), Rational(-122, 15), Rational(169, 60), Rational(169, 60), Rational(-2, 5), Rational(-2, 5), Rational(7, 240), Rational(7, 240)] # Table 2, p. 703 in doi:10.1090/S0025-5718-1988-0935077-0 # -------------------------------------------------------- xl = [[j/S(2) for j in list(range(-i*2+1, 0, 2))+list(range(1, i*2+1, 2))] for i in range(1, 5)] # d holds all coefficients d = [finite_diff_weights({0: 1, 1: 2, 2: 4, 3: 4}[i], xl[i], 0) for i in range(4)] # Zeroth derivative assert d[0][0][1] == [S.Half, S.Half] assert d[1][0][3] == [Rational(-1, 16), Rational(9, 16), Rational(9, 16), Rational(-1, 16)] assert d[2][0][5] == [Rational(3, 256), Rational(-25, 256), Rational(75, 128), Rational(75, 128), Rational(-25, 256), Rational(3, 256)] assert d[3][0][7] == [Rational(-5, 2048), Rational(49, 2048), Rational(-245, 2048), Rational(1225, 2048), Rational(1225, 2048), Rational(-245, 2048), Rational(49, 2048), Rational(-5, 2048)] # First derivative assert d[0][1][1] == [-S.One, S.One] assert d[1][1][3] == [Rational(1, 24), Rational(-9, 8), Rational(9, 8), Rational(-1, 24)] assert d[2][1][5] == [Rational(-3, 640), Rational(25, 384), Rational(-75, 64), Rational(75, 64), Rational(-25, 384), Rational(3, 640)] assert d[3][1][7] == [Rational(5, 7168), Rational(-49, 5120), Rational(245, 3072), Rational(-1225, 1024), Rational(1225, 1024), Rational(-245, 3072), Rational(49, 5120), Rational(-5, 7168)] # Reasonably the rest of the table is also correct... (testing of that # deemed excessive at the moment) raises(ValueError, lambda: finite_diff_weights(-1, [1, 2])) raises(ValueError, lambda: finite_diff_weights(1.2, [1, 2])) x = symbols('x') raises(ValueError, lambda: finite_diff_weights(x, [1, 2])) def test_as_finite_diff(): x = symbols('x') f = Function('f') dx = Function('dx') _as_finite_diff(f(x).diff(x), [x-2, x-1, x, x+1, x+2]) # Use of undefined functions in ``points`` df_true = -f(x+dx(x)/2-dx(x+dx(x)/2)/2) / dx(x+dx(x)/2) \ + f(x+dx(x)/2+dx(x+dx(x)/2)/2) / dx(x+dx(x)/2) df_test = diff(f(x), x).as_finite_difference(points=dx(x), x0=x+dx(x)/2) assert (df_test - df_true).simplify() == 0 def test_differentiate_finite(): x, y, h = symbols('x y h') f = Function('f') with warns_deprecated_sympy(): res0 = differentiate_finite(f(x, y) + exp(42), x, y, evaluate=True) xm, xp, ym, yp = [v + sign*S.Half for v, sign in product([x, y], [-1, 1])] ref0 = f(xm, ym) + f(xp, yp) - f(xm, yp) - f(xp, ym) assert (res0 - ref0).simplify() == 0 g = Function('g') with warns_deprecated_sympy(): res1 = differentiate_finite(f(x)*g(x) + 42, x, evaluate=True) ref1 = (-f(x - S.Half) + f(x + S.Half))*g(x) + \ (-g(x - S.Half) + g(x + S.Half))*f(x) assert (res1 - ref1).simplify() == 0 res2 = differentiate_finite(f(x) + x**3 + 42, x, points=[x-1, x+1]) ref2 = (f(x + 1) + (x + 1)**3 - f(x - 1) - (x - 1)**3)/2 assert (res2 - ref2).simplify() == 0 raises(TypeError, lambda: differentiate_finite(f(x)*g(x), x, pints=[x-1, x+1])) res3 = differentiate_finite(f(x)*g(x).diff(x), x) ref3 = (-g(x) + g(x + 1))*f(x + S.Half) - (g(x) - g(x - 1))*f(x - S.Half) assert res3 == ref3 res4 = differentiate_finite(f(x)*g(x).diff(x).diff(x), x) ref4 = -((g(x - Rational(3, 2)) - 2*g(x - S.Half) + g(x + S.Half))*f(x - S.Half)) \ + (g(x - S.Half) - 2*g(x + S.Half) + g(x + Rational(3, 2)))*f(x + S.Half) assert res4 == ref4 res5_expr = f(x).diff(x)*g(x).diff(x) res5 = differentiate_finite(res5_expr, points=[x-h, x, x+h]) ref5 = (-2*f(x)/h + f(-h + x)/(2*h) + 3*f(h + x)/(2*h))*(-2*g(x)/h + g(-h + x)/(2*h) \ + 3*g(h + x)/(2*h))/(2*h) - (2*f(x)/h - 3*f(-h + x)/(2*h) - \ f(h + x)/(2*h))*(2*g(x)/h - 3*g(-h + x)/(2*h) - g(h + x)/(2*h))/(2*h) assert res5 == ref5 res6 = res5.limit(h, 0).doit() ref6 = diff(res5_expr, x) assert res6 == ref6
f82efcf5efb93a72e924abd093ebd8eefebc3841bbc21a2b7d7dbc03c8ec0230
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 from sympy.utilities.misc import (translate, replace, ordinal, rawlines, strlines, as_int, find_executable) 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(): 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')
7547c37c87687ca62e7f0c36f6357c9954268255350271b6b84c91129358ed5d
import pickle from sympy.core.relational import (Eq, Ne) from sympy.core.singleton import S from sympy.core.symbol import symbols from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import (cos, sin) from sympy.external import import_module from sympy.testing.pytest import skip from sympy.utilities.matchpy_connector import WildDot, WildPlus, WildStar, Replacer matchpy = import_module("matchpy") x, y, z = symbols("x y z") def _get_first_match(expr, pattern): from matchpy import ManyToOneMatcher, Pattern matcher = ManyToOneMatcher() matcher.add(Pattern(pattern)) return next(iter(matcher.match(expr))) def test_matchpy_connector(): if matchpy is None: skip("matchpy not installed") from multiset import Multiset from matchpy import Pattern, Substitution w_ = WildDot("w_") w__ = WildPlus("w__") w___ = WildStar("w___") expr = x + y pattern = x + w_ p, subst = _get_first_match(expr, pattern) assert p == Pattern(pattern) assert subst == Substitution({'w_': y}) expr = x + y + z pattern = x + w__ p, subst = _get_first_match(expr, pattern) assert p == Pattern(pattern) assert subst == Substitution({'w__': Multiset([y, z])}) expr = x + y + z pattern = x + y + z + w___ p, subst = _get_first_match(expr, pattern) assert p == Pattern(pattern) assert subst == Substitution({'w___': Multiset()}) def test_matchpy_optional(): if matchpy is None: skip("matchpy not installed") from matchpy import Pattern, Substitution from matchpy import ManyToOneReplacer, ReplacementRule p = WildDot("p", optional=1) q = WildDot("q", optional=0) pattern = p*x + q expr1 = 2*x pa, subst = _get_first_match(expr1, pattern) assert pa == Pattern(pattern) assert subst == Substitution({'p': 2, 'q': 0}) expr2 = x + 3 pa, subst = _get_first_match(expr2, pattern) assert pa == Pattern(pattern) assert subst == Substitution({'p': 1, 'q': 3}) expr3 = x pa, subst = _get_first_match(expr3, pattern) assert pa == Pattern(pattern) assert subst == Substitution({'p': 1, 'q': 0}) expr4 = x*y + z pa, subst = _get_first_match(expr4, pattern) assert pa == Pattern(pattern) assert subst == Substitution({'p': y, 'q': z}) replacer = ManyToOneReplacer() replacer.add(ReplacementRule(Pattern(pattern), lambda p, q: sin(p)*cos(q))) assert replacer.replace(expr1) == sin(2)*cos(0) assert replacer.replace(expr2) == sin(1)*cos(3) assert replacer.replace(expr3) == sin(1)*cos(0) assert replacer.replace(expr4) == sin(y)*cos(z) def test_replacer(): if matchpy is None: skip("matchpy not installed") x1_ = WildDot("x1_") x2_ = WildDot("x2_") a_ = WildDot("a_", optional=S.One) b_ = WildDot("b_", optional=S.One) c_ = WildDot("c_", optional=S.Zero) replacer = Replacer(common_constraints=[ matchpy.CustomConstraint(lambda a_: not a_.has(x)), matchpy.CustomConstraint(lambda b_: not b_.has(x)), matchpy.CustomConstraint(lambda c_: not c_.has(x)), ]) # Rewrite the equation into implicit form, unless it's already solved: replacer.add(Eq(x1_, x2_), Eq(x1_ - x2_, 0), conditions_nonfalse=[Ne(x2_, 0), Ne(x1_, 0), Ne(x1_, x), Ne(x2_, x)]) # Simple equation solver for real numbers: replacer.add(Eq(a_*x + b_, 0), Eq(x, -b_/a_)) disc = b_**2 - 4*a_*c_ replacer.add( Eq(a_*x**2 + b_*x + c_, 0), Eq(x, (-b_ - sqrt(disc))/(2*a_)) | Eq(x, (-b_ + sqrt(disc))/(2*a_)), conditions_nonfalse=[disc >= 0] ) replacer.add( Eq(a_*x**2 + c_, 0), Eq(x, sqrt(-c_/a_)) | Eq(x, -sqrt(-c_/a_)), conditions_nonfalse=[-c_*a_ > 0] ) assert replacer.replace(Eq(3*x, y)) == Eq(x, y/3) assert replacer.replace(Eq(x**2 + 1, 0)) == Eq(x**2 + 1, 0) assert replacer.replace(Eq(x**2, 4)) == (Eq(x, 2) | Eq(x, -2)) assert replacer.replace(Eq(x**2 + 4*y*x + 4*y**2, 0)) == Eq(x, -2*y) def test_matchpy_object_pickle(): if matchpy is None: return a1 = WildDot("a") a2 = pickle.loads(pickle.dumps(a1)) assert a1 == a2 a1 = WildDot("a", S(1)) a2 = pickle.loads(pickle.dumps(a1)) assert a1 == a2 a1 = WildPlus("a", S(1)) a2 = pickle.loads(pickle.dumps(a1)) assert a1 == a2 a1 = WildStar("a", S(1)) a2 = pickle.loads(pickle.dumps(a1)) assert a1 == a2
f3815f789ce843d25bc8c593b60ce598e635f4f3517395c29cfaf04e211036ca
import inspect import copy import pickle from sympy.physics.units import meter from sympy.testing.pytest import XFAIL, raises from sympy.core.basic import Atom, Basic from sympy.core.core import BasicMeta from sympy.core.singleton import SingletonRegistry from sympy.core.symbol import Str, Dummy, Symbol, Wild from sympy.core.numbers import (E, I, pi, oo, zoo, nan, Integer, Rational, Float, AlgebraicNumber) from sympy.core.relational import (Equality, GreaterThan, LessThan, Relational, StrictGreaterThan, StrictLessThan, Unequality) from sympy.core.add import Add from sympy.core.mul import Mul from sympy.core.power import Pow from sympy.core.function import Derivative, Function, FunctionClass, Lambda, \ WildFunction from sympy.sets.sets import Interval from sympy.core.multidimensional import vectorize from sympy.external.gmpy import HAS_GMPY from sympy.utilities.exceptions import SymPyDeprecationWarning from sympy.core.singleton import S from sympy.core.symbol import symbols from sympy.external import import_module cloudpickle = import_module('cloudpickle') excluded_attrs = { '_assumptions', # This is a local cache that isn't automatically filled on creation '_mhash', # Cached after __hash__ is called but set to None after creation 'is_EmptySet', # Deprecated from SymPy 1.5. This can be removed when is_EmptySet is removed. 'expr_free_symbols', # Deprecated from SymPy 1.9. This can be removed when exr_free_symbols is removed. '_mat', # Deprecated from SymPy 1.9. This can be removed when Matrix._mat is removed '_smat', # Deprecated from SymPy 1.9. This can be removed when SparseMatrix._smat is removed } def check(a, exclude=[], check_attr=True): """ Check that pickling and copying round-trips. """ # Pickling with protocols 0 and 1 is disabled for Basic instances: if isinstance(a, Basic): for protocol in [0, 1]: raises(NotImplementedError, lambda: pickle.dumps(a, protocol)) protocols = [2, copy.copy, copy.deepcopy, 3, 4] if cloudpickle: protocols.extend([cloudpickle]) for protocol in protocols: if protocol in exclude: continue if callable(protocol): if isinstance(a, BasicMeta): # Classes can't be copied, but that's okay. continue b = protocol(a) elif inspect.ismodule(protocol): b = protocol.loads(protocol.dumps(a)) else: b = pickle.loads(pickle.dumps(a, protocol)) d1 = dir(a) d2 = dir(b) assert set(d1) == set(d2) if not check_attr: continue def c(a, b, d): for i in d: if i in excluded_attrs: continue if not hasattr(a, i): continue attr = getattr(a, i) if not hasattr(attr, "__call__"): assert hasattr(b, i), i assert getattr(b, i) == attr, "%s != %s, protocol: %s" % (getattr(b, i), attr, protocol) c(a, b, d1) c(b, a, d2) #================== core ========================= def test_core_basic(): for c in (Atom, Atom(), Basic, Basic(), # XXX: dynamically created types are not picklable # BasicMeta, BasicMeta("test", (), {}), SingletonRegistry, S): check(c) def test_core_Str(): check(Str('x')) def test_core_symbol(): # make the Symbol a unique name that doesn't class with any other # testing variable in this file since after this test the symbol # having the same name will be cached as noncommutative for c in (Dummy, Dummy("x", commutative=False), Symbol, Symbol("_issue_3130", commutative=False), Wild, Wild("x")): check(c) def test_core_numbers(): for c in (Integer(2), Rational(2, 3), Float("1.2")): check(c) for c in (AlgebraicNumber, AlgebraicNumber(sqrt(3))): check(c, check_attr=False) def test_core_float_copy(): # See gh-7457 y = Symbol("x") + 1.0 check(y) # does not raise TypeError ("argument is not an mpz") def test_core_relational(): x = Symbol("x") y = Symbol("y") for c in (Equality, Equality(x, y), GreaterThan, GreaterThan(x, y), LessThan, LessThan(x, y), Relational, Relational(x, y), StrictGreaterThan, StrictGreaterThan(x, y), StrictLessThan, StrictLessThan(x, y), Unequality, Unequality(x, y)): check(c) def test_core_add(): x = Symbol("x") for c in (Add, Add(x, 4)): check(c) def test_core_mul(): x = Symbol("x") for c in (Mul, Mul(x, 4)): check(c) def test_core_power(): x = Symbol("x") for c in (Pow, Pow(x, 4)): check(c) def test_core_function(): x = Symbol("x") for f in (Derivative, Derivative(x), Function, FunctionClass, Lambda, WildFunction): check(f) def test_core_undefinedfunctions(): f = Function("f") # Full XFAILed test below exclude = list(range(5)) # https://github.com/cloudpipe/cloudpickle/issues/65 # https://github.com/cloudpipe/cloudpickle/issues/190 exclude.append(cloudpickle) check(f, exclude=exclude) @XFAIL def test_core_undefinedfunctions_fail(): # This fails because f is assumed to be a class at sympy.basic.function.f f = Function("f") check(f) def test_core_interval(): for c in (Interval, Interval(0, 2)): check(c) def test_core_multidimensional(): for c in (vectorize, vectorize(0)): check(c) def test_Singletons(): protocols = [0, 1, 2, 3, 4] copiers = [copy.copy, copy.deepcopy] copiers += [lambda x: pickle.loads(pickle.dumps(x, proto)) for proto in protocols] if cloudpickle: copiers += [lambda x: cloudpickle.loads(cloudpickle.dumps(x))] for obj in (Integer(-1), Integer(0), Integer(1), Rational(1, 2), pi, E, I, oo, -oo, zoo, nan, S.GoldenRatio, S.TribonacciConstant, S.EulerGamma, S.Catalan, S.EmptySet, S.IdentityFunction): for func in copiers: assert func(obj) is obj #================== functions =================== from sympy.functions import (Piecewise, lowergamma, acosh, chebyshevu, chebyshevt, ln, chebyshevt_root, legendre, Heaviside, bernoulli, coth, tanh, assoc_legendre, sign, arg, asin, DiracDelta, re, rf, Abs, uppergamma, binomial, sinh, cos, cot, acos, acot, gamma, bell, hermite, harmonic, LambertW, zeta, log, factorial, asinh, acoth, cosh, dirichlet_eta, Eijk, loggamma, erf, ceiling, im, fibonacci, tribonacci, conjugate, tan, chebyshevu_root, floor, atanh, sqrt, sin, atan, ff, lucas, atan2, polygamma, exp) def test_functions(): one_var = (acosh, ln, Heaviside, factorial, bernoulli, coth, tanh, sign, arg, asin, DiracDelta, re, Abs, sinh, cos, cot, acos, acot, gamma, bell, harmonic, LambertW, zeta, log, factorial, asinh, acoth, cosh, dirichlet_eta, loggamma, erf, ceiling, im, fibonacci, tribonacci, conjugate, tan, floor, atanh, sin, atan, lucas, exp) two_var = (rf, ff, lowergamma, chebyshevu, chebyshevt, binomial, atan2, polygamma, hermite, legendre, uppergamma) x, y, z = symbols("x,y,z") others = (chebyshevt_root, chebyshevu_root, Eijk(x, y, z), Piecewise( (0, x < -1), (x**2, x <= 1), (x**3, True)), assoc_legendre) for cls in one_var: check(cls) c = cls(x) check(c) for cls in two_var: check(cls) c = cls(x, y) check(c) for cls in others: check(cls) #================== geometry ==================== from sympy.geometry.entity import GeometryEntity from sympy.geometry.point import Point from sympy.geometry.ellipse import Circle, Ellipse from sympy.geometry.line import Line, LinearEntity, Ray, Segment from sympy.geometry.polygon import Polygon, RegularPolygon, Triangle def test_geometry(): p1 = Point(1, 2) p2 = Point(2, 3) p3 = Point(0, 0) p4 = Point(0, 1) for c in ( GeometryEntity, GeometryEntity(), Point, p1, Circle, Circle(p1, 2), Ellipse, Ellipse(p1, 3, 4), Line, Line(p1, p2), LinearEntity, LinearEntity(p1, p2), Ray, Ray(p1, p2), Segment, Segment(p1, p2), Polygon, Polygon(p1, p2, p3, p4), RegularPolygon, RegularPolygon(p1, 4, 5), Triangle, Triangle(p1, p2, p3)): check(c, check_attr=False) #================== integrals ==================== from sympy.integrals.integrals import Integral def test_integrals(): x = Symbol("x") for c in (Integral, Integral(x)): check(c) #==================== logic ===================== from sympy.core.logic import Logic def test_logic(): for c in (Logic, Logic(1)): check(c) #================== matrices ==================== from sympy.matrices import Matrix, SparseMatrix def test_matrices(): for c in (Matrix, Matrix([1, 2, 3]), SparseMatrix, SparseMatrix([[1, 2], [3, 4]])): check(c) #================== ntheory ===================== from sympy.ntheory.generate import Sieve def test_ntheory(): for c in (Sieve, Sieve()): check(c) #================== physics ===================== from sympy.physics.paulialgebra import Pauli from sympy.physics.units import Unit def test_physics(): for c in (Unit, meter, Pauli, Pauli(1)): check(c) #================== plotting ==================== # XXX: These tests are not complete, so XFAIL them @XFAIL def test_plotting(): from sympy.plotting.pygletplot.color_scheme import ColorGradient, ColorScheme from sympy.plotting.pygletplot.managed_window import ManagedWindow from sympy.plotting.plot import Plot, ScreenShot from sympy.plotting.pygletplot.plot_axes import PlotAxes, PlotAxesBase, PlotAxesFrame, PlotAxesOrdinate from sympy.plotting.pygletplot.plot_camera import PlotCamera from sympy.plotting.pygletplot.plot_controller import PlotController from sympy.plotting.pygletplot.plot_curve import PlotCurve from sympy.plotting.pygletplot.plot_interval import PlotInterval from sympy.plotting.pygletplot.plot_mode import PlotMode from sympy.plotting.pygletplot.plot_modes import Cartesian2D, Cartesian3D, Cylindrical, \ ParametricCurve2D, ParametricCurve3D, ParametricSurface, Polar, Spherical from sympy.plotting.pygletplot.plot_object import PlotObject from sympy.plotting.pygletplot.plot_surface import PlotSurface from sympy.plotting.pygletplot.plot_window import PlotWindow for c in ( ColorGradient, ColorGradient(0.2, 0.4), ColorScheme, ManagedWindow, ManagedWindow, Plot, ScreenShot, PlotAxes, PlotAxesBase, PlotAxesFrame, PlotAxesOrdinate, PlotCamera, PlotController, PlotCurve, PlotInterval, PlotMode, Cartesian2D, Cartesian3D, Cylindrical, ParametricCurve2D, ParametricCurve3D, ParametricSurface, Polar, Spherical, PlotObject, PlotSurface, PlotWindow): check(c) @XFAIL def test_plotting2(): #from sympy.plotting.color_scheme import ColorGradient from sympy.plotting.pygletplot.color_scheme import ColorScheme #from sympy.plotting.managed_window import ManagedWindow from sympy.plotting.plot import Plot #from sympy.plotting.plot import ScreenShot from sympy.plotting.pygletplot.plot_axes import PlotAxes #from sympy.plotting.plot_axes import PlotAxesBase, PlotAxesFrame, PlotAxesOrdinate #from sympy.plotting.plot_camera import PlotCamera #from sympy.plotting.plot_controller import PlotController #from sympy.plotting.plot_curve import PlotCurve #from sympy.plotting.plot_interval import PlotInterval #from sympy.plotting.plot_mode import PlotMode #from sympy.plotting.plot_modes import Cartesian2D, Cartesian3D, Cylindrical, \ # ParametricCurve2D, ParametricCurve3D, ParametricSurface, Polar, Spherical #from sympy.plotting.plot_object import PlotObject #from sympy.plotting.plot_surface import PlotSurface # from sympy.plotting.plot_window import PlotWindow check(ColorScheme("rainbow")) check(Plot(1, visible=False)) check(PlotAxes()) #================== polys ======================= from sympy.polys.domains.integerring import ZZ from sympy.polys.domains.rationalfield import QQ from sympy.polys.orderings import lex from sympy.polys.polytools import Poly def test_pickling_polys_polytools(): from sympy.polys.polytools import PurePoly # from sympy.polys.polytools import GroebnerBasis x = Symbol('x') for c in (Poly, Poly(x, x)): check(c) for c in (PurePoly, PurePoly(x)): check(c) # TODO: fix pickling of Options class (see GroebnerBasis._options) # for c in (GroebnerBasis, GroebnerBasis([x**2 - 1], x, order=lex)): # check(c) def test_pickling_polys_polyclasses(): from sympy.polys.polyclasses import DMP, DMF, ANP for c in (DMP, DMP([[ZZ(1)], [ZZ(2)], [ZZ(3)]], ZZ)): check(c) for c in (DMF, DMF(([ZZ(1), ZZ(2)], [ZZ(1), ZZ(3)]), ZZ)): check(c) for c in (ANP, ANP([QQ(1), QQ(2)], [QQ(1), QQ(2), QQ(3)], QQ)): check(c) @XFAIL def test_pickling_polys_rings(): # NOTE: can't use protocols < 2 because we have to execute __new__ to # make sure caching of rings works properly. from sympy.polys.rings import PolyRing ring = PolyRing("x,y,z", ZZ, lex) for c in (PolyRing, ring): check(c, exclude=[0, 1]) for c in (ring.dtype, ring.one): check(c, exclude=[0, 1], check_attr=False) # TODO: Py3k def test_pickling_polys_fields(): pass # NOTE: can't use protocols < 2 because we have to execute __new__ to # make sure caching of fields works properly. # from sympy.polys.fields import FracField # field = FracField("x,y,z", ZZ, lex) # TODO: AssertionError: assert id(obj) not in self.memo # for c in (FracField, field): # check(c, exclude=[0, 1]) # TODO: AssertionError: assert id(obj) not in self.memo # for c in (field.dtype, field.one): # check(c, exclude=[0, 1]) def test_pickling_polys_elements(): from sympy.polys.domains.pythonrational import PythonRational #from sympy.polys.domains.pythonfinitefield import PythonFiniteField #from sympy.polys.domains.mpelements import MPContext for c in (PythonRational, PythonRational(1, 7)): check(c) #gf = PythonFiniteField(17) # TODO: fix pickling of ModularInteger # for c in (gf.dtype, gf(5)): # check(c) #mp = MPContext() # TODO: fix pickling of RealElement # for c in (mp.mpf, mp.mpf(1.0)): # check(c) # TODO: fix pickling of ComplexElement # for c in (mp.mpc, mp.mpc(1.0, -1.5)): # check(c) def test_pickling_polys_domains(): # from sympy.polys.domains.pythonfinitefield import PythonFiniteField from sympy.polys.domains.pythonintegerring import PythonIntegerRing from sympy.polys.domains.pythonrationalfield import PythonRationalField # TODO: fix pickling of ModularInteger # for c in (PythonFiniteField, PythonFiniteField(17)): # check(c) for c in (PythonIntegerRing, PythonIntegerRing()): check(c, check_attr=False) for c in (PythonRationalField, PythonRationalField()): check(c, check_attr=False) if HAS_GMPY: # from sympy.polys.domains.gmpyfinitefield import GMPYFiniteField from sympy.polys.domains.gmpyintegerring import GMPYIntegerRing from sympy.polys.domains.gmpyrationalfield import GMPYRationalField # TODO: fix pickling of ModularInteger # for c in (GMPYFiniteField, GMPYFiniteField(17)): # check(c) for c in (GMPYIntegerRing, GMPYIntegerRing()): check(c, check_attr=False) for c in (GMPYRationalField, GMPYRationalField()): check(c, check_attr=False) #from sympy.polys.domains.realfield import RealField #from sympy.polys.domains.complexfield import ComplexField from sympy.polys.domains.algebraicfield import AlgebraicField #from sympy.polys.domains.polynomialring import PolynomialRing #from sympy.polys.domains.fractionfield import FractionField from sympy.polys.domains.expressiondomain import ExpressionDomain # TODO: fix pickling of RealElement # for c in (RealField, RealField(100)): # check(c) # TODO: fix pickling of ComplexElement # for c in (ComplexField, ComplexField(100)): # check(c) for c in (AlgebraicField, AlgebraicField(QQ, sqrt(3))): check(c, check_attr=False) # TODO: AssertionError # for c in (PolynomialRing, PolynomialRing(ZZ, "x,y,z")): # check(c) # TODO: AttributeError: 'PolyElement' object has no attribute 'ring' # for c in (FractionField, FractionField(ZZ, "x,y,z")): # check(c) for c in (ExpressionDomain, ExpressionDomain()): check(c, check_attr=False) def test_pickling_polys_orderings(): from sympy.polys.orderings import (LexOrder, GradedLexOrder, ReversedGradedLexOrder, InverseOrder) # from sympy.polys.orderings import ProductOrder for c in (LexOrder, LexOrder()): check(c) for c in (GradedLexOrder, GradedLexOrder()): check(c) for c in (ReversedGradedLexOrder, ReversedGradedLexOrder()): check(c) # TODO: Argh, Python is so naive. No lambdas nor inner function support in # pickling module. Maybe someone could figure out what to do with this. # # for c in (ProductOrder, ProductOrder((LexOrder(), lambda m: m[:2]), # (GradedLexOrder(), lambda m: m[2:]))): # check(c) for c in (InverseOrder, InverseOrder(LexOrder())): check(c) def test_pickling_polys_monomials(): from sympy.polys.monomials import MonomialOps, Monomial x, y, z = symbols("x,y,z") for c in (MonomialOps, MonomialOps(3)): check(c) for c in (Monomial, Monomial((1, 2, 3), (x, y, z))): check(c) def test_pickling_polys_errors(): from sympy.polys.polyerrors import (HeuristicGCDFailed, HomomorphismFailed, IsomorphismFailed, ExtraneousFactors, EvaluationFailed, RefinementFailed, CoercionFailed, NotInvertible, NotReversible, NotAlgebraic, DomainError, PolynomialError, UnificationFailed, GeneratorsError, GeneratorsNeeded, UnivariatePolynomialError, MultivariatePolynomialError, OptionError, FlagError) # from sympy.polys.polyerrors import (ExactQuotientFailed, # OperationNotSupported, ComputationFailed, PolificationFailed) # x = Symbol('x') # TODO: TypeError: __init__() takes at least 3 arguments (1 given) # for c in (ExactQuotientFailed, ExactQuotientFailed(x, 3*x, ZZ)): # check(c) # TODO: TypeError: can't pickle instancemethod objects # for c in (OperationNotSupported, OperationNotSupported(Poly(x), Poly.gcd)): # check(c) for c in (HeuristicGCDFailed, HeuristicGCDFailed()): check(c) for c in (HomomorphismFailed, HomomorphismFailed()): check(c) for c in (IsomorphismFailed, IsomorphismFailed()): check(c) for c in (ExtraneousFactors, ExtraneousFactors()): check(c) for c in (EvaluationFailed, EvaluationFailed()): check(c) for c in (RefinementFailed, RefinementFailed()): check(c) for c in (CoercionFailed, CoercionFailed()): check(c) for c in (NotInvertible, NotInvertible()): check(c) for c in (NotReversible, NotReversible()): check(c) for c in (NotAlgebraic, NotAlgebraic()): check(c) for c in (DomainError, DomainError()): check(c) for c in (PolynomialError, PolynomialError()): check(c) for c in (UnificationFailed, UnificationFailed()): check(c) for c in (GeneratorsError, GeneratorsError()): check(c) for c in (GeneratorsNeeded, GeneratorsNeeded()): check(c) # TODO: PicklingError: Can't pickle <function <lambda> at 0x38578c0>: it's not found as __main__.<lambda> # for c in (ComputationFailed, ComputationFailed(lambda t: t, 3, None)): # check(c) for c in (UnivariatePolynomialError, UnivariatePolynomialError()): check(c) for c in (MultivariatePolynomialError, MultivariatePolynomialError()): check(c) # TODO: TypeError: __init__() takes at least 3 arguments (1 given) # for c in (PolificationFailed, PolificationFailed({}, x, x, False)): # check(c) for c in (OptionError, OptionError()): check(c) for c in (FlagError, FlagError()): check(c) #def test_pickling_polys_options(): #from sympy.polys.polyoptions import Options # TODO: fix pickling of `symbols' flag # for c in (Options, Options((), dict(domain='ZZ', polys=False))): # check(c) # TODO: def test_pickling_polys_rootisolation(): # RealInterval # ComplexInterval def test_pickling_polys_rootoftools(): from sympy.polys.rootoftools import CRootOf, RootSum x = Symbol('x') f = x**3 + x + 3 for c in (CRootOf, CRootOf(f, 0)): check(c) for c in (RootSum, RootSum(f, exp)): check(c) #================== printing ==================== from sympy.printing.latex import LatexPrinter from sympy.printing.mathml import MathMLContentPrinter, MathMLPresentationPrinter from sympy.printing.pretty.pretty import PrettyPrinter from sympy.printing.pretty.stringpict import prettyForm, stringPict from sympy.printing.printer import Printer from sympy.printing.python import PythonPrinter def test_printing(): for c in (LatexPrinter, LatexPrinter(), MathMLContentPrinter, MathMLPresentationPrinter, PrettyPrinter, prettyForm, stringPict, stringPict("a"), Printer, Printer(), PythonPrinter, PythonPrinter()): check(c) @XFAIL def test_printing1(): check(MathMLContentPrinter()) @XFAIL def test_printing2(): check(MathMLPresentationPrinter()) @XFAIL def test_printing3(): check(PrettyPrinter()) #================== series ====================== from sympy.series.limits import Limit from sympy.series.order import Order def test_series(): e = Symbol("e") x = Symbol("x") for c in (Limit, Limit(e, x, 1), Order, Order(e)): check(c) #================== concrete ================== from sympy.concrete.products import Product from sympy.concrete.summations import Sum def test_concrete(): x = Symbol("x") for c in (Product, Product(x, (x, 2, 4)), Sum, Sum(x, (x, 2, 4))): check(c) def test_deprecation_warning(): w = SymPyDeprecationWarning("message", deprecated_since_version='1.0', active_deprecations_target="active-deprecations") check(w) def test_issue_18438(): assert pickle.loads(pickle.dumps(S.Half)) == 1/2 #================= old pickles ================= def test_unpickle_from_older_versions(): data = ( b'\x80\x04\x95^\x00\x00\x00\x00\x00\x00\x00\x8c\x10sympy.core.power' b'\x94\x8c\x03Pow\x94\x93\x94\x8c\x12sympy.core.numbers\x94\x8c' b'\x07Integer\x94\x93\x94K\x02\x85\x94R\x94}\x94bh\x03\x8c\x04Half' b'\x94\x93\x94)R\x94}\x94b\x86\x94R\x94}\x94b.' ) assert pickle.loads(data) == sqrt(2)
e4feeab8ca11ad8fcc60ceda14563ba566faa746d63a0596dc08aff69a9efbb5
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 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, 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.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') 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(): import warnings if not numexpr: skip("numexpr not installed.") func_numexpr = lambdify((x,y,z), Piecewise((y, x >= 0), (z, x > -1)), numexpr) assert func_numexpr(1, 24, 42) == 24 with warnings.catch_warnings(): warnings.simplefilter("ignore", RuntimeWarning) assert str(func_numexpr(-1, 24, 42)) == 'nan' 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(): 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(): # 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']) 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) # 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_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_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)
c59f976908b7dd8b4ca0e95ec56899690b32debd4e2a053da7cca9f3adb6f9e1
from textwrap import dedent from itertools import islice, product from sympy.core.basic import Basic from sympy.core.numbers import Integer from sympy.core.sorting import ordered from sympy.core.symbol import (Dummy, symbols) from sympy.functions.combinatorial.factorials import factorial from sympy.matrices.dense import Matrix from sympy.combinatorics import RGS_enum, RGS_unrank, Permutation from sympy.utilities.iterables import ( _partition, _set_partitions, binary_partitions, bracelets, capture, cartes, common_prefix, common_suffix, connected_components, dict_merge, filter_symbols, flatten, generate_bell, generate_derangements, generate_involutions, generate_oriented_forest, group, has_dups, ibin, iproduct, kbins, minlex, multiset, multiset_combinations, multiset_partitions, multiset_permutations, necklaces, numbered_symbols, partitions, permutations, postfixes, prefixes, reshape, rotate_left, rotate_right, runs, sift, strongly_connected_components, subsets, take, topological_sort, unflatten, uniq, variations, ordered_partitions, rotations, is_palindromic, iterable, NotIterable, multiset_derangements) from sympy.utilities.enumerative import ( factoring_visitor, multiset_partitions_taocp ) from sympy.core.singleton import S from sympy.testing.pytest import raises, warns_deprecated_sympy w, x, y, z = symbols('w,x,y,z') def test_deprecated_iterables(): from sympy.utilities.iterables import default_sort_key, ordered with warns_deprecated_sympy(): assert list(ordered([y, x])) == [x, y] with warns_deprecated_sympy(): assert sorted([y, x], key=default_sort_key) == [x, y] def test_is_palindromic(): assert is_palindromic('') assert is_palindromic('x') assert is_palindromic('xx') assert is_palindromic('xyx') assert not is_palindromic('xy') assert not is_palindromic('xyzx') assert is_palindromic('xxyzzyx', 1) assert not is_palindromic('xxyzzyx', 2) assert is_palindromic('xxyzzyx', 2, -1) assert is_palindromic('xxyzzyx', 2, 6) assert is_palindromic('xxyzyx', 1) assert not is_palindromic('xxyzyx', 2) assert is_palindromic('xxyzyx', 2, 2 + 3) def test_flatten(): assert flatten((1, (1,))) == [1, 1] assert flatten((x, (x,))) == [x, x] ls = [[(-2, -1), (1, 2)], [(0, 0)]] assert flatten(ls, levels=0) == ls assert flatten(ls, levels=1) == [(-2, -1), (1, 2), (0, 0)] assert flatten(ls, levels=2) == [-2, -1, 1, 2, 0, 0] assert flatten(ls, levels=3) == [-2, -1, 1, 2, 0, 0] raises(ValueError, lambda: flatten(ls, levels=-1)) class MyOp(Basic): pass assert flatten([MyOp(x, y), z]) == [MyOp(x, y), z] assert flatten([MyOp(x, y), z], cls=MyOp) == [x, y, z] assert flatten({1, 11, 2}) == list({1, 11, 2}) def test_iproduct(): assert list(iproduct()) == [()] assert list(iproduct([])) == [] assert list(iproduct([1,2,3])) == [(1,),(2,),(3,)] assert sorted(iproduct([1, 2], [3, 4, 5])) == [ (1,3),(1,4),(1,5),(2,3),(2,4),(2,5)] assert sorted(iproduct([0,1],[0,1],[0,1])) == [ (0,0,0),(0,0,1),(0,1,0),(0,1,1),(1,0,0),(1,0,1),(1,1,0),(1,1,1)] assert iterable(iproduct(S.Integers)) is True assert iterable(iproduct(S.Integers, S.Integers)) is True assert (3,) in iproduct(S.Integers) assert (4, 5) in iproduct(S.Integers, S.Integers) assert (1, 2, 3) in iproduct(S.Integers, S.Integers, S.Integers) triples = set(islice(iproduct(S.Integers, S.Integers, S.Integers), 1000)) for n1, n2, n3 in triples: assert isinstance(n1, Integer) assert isinstance(n2, Integer) assert isinstance(n3, Integer) for t in set(product(*([range(-2, 3)]*3))): assert t in iproduct(S.Integers, S.Integers, S.Integers) def test_group(): assert group([]) == [] assert group([], multiple=False) == [] assert group([1]) == [[1]] assert group([1], multiple=False) == [(1, 1)] assert group([1, 1]) == [[1, 1]] assert group([1, 1], multiple=False) == [(1, 2)] assert group([1, 1, 1]) == [[1, 1, 1]] assert group([1, 1, 1], multiple=False) == [(1, 3)] assert group([1, 2, 1]) == [[1], [2], [1]] assert group([1, 2, 1], multiple=False) == [(1, 1), (2, 1), (1, 1)] assert group([1, 1, 2, 2, 2, 1, 3, 3]) == [[1, 1], [2, 2, 2], [1], [3, 3]] assert group([1, 1, 2, 2, 2, 1, 3, 3], multiple=False) == [(1, 2), (2, 3), (1, 1), (3, 2)] def test_subsets(): # combinations assert list(subsets([1, 2, 3], 0)) == [()] assert list(subsets([1, 2, 3], 1)) == [(1,), (2,), (3,)] assert list(subsets([1, 2, 3], 2)) == [(1, 2), (1, 3), (2, 3)] assert list(subsets([1, 2, 3], 3)) == [(1, 2, 3)] l = list(range(4)) assert list(subsets(l, 0, repetition=True)) == [()] assert list(subsets(l, 1, repetition=True)) == [(0,), (1,), (2,), (3,)] assert list(subsets(l, 2, repetition=True)) == [(0, 0), (0, 1), (0, 2), (0, 3), (1, 1), (1, 2), (1, 3), (2, 2), (2, 3), (3, 3)] assert list(subsets(l, 3, repetition=True)) == [(0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 0, 3), (0, 1, 1), (0, 1, 2), (0, 1, 3), (0, 2, 2), (0, 2, 3), (0, 3, 3), (1, 1, 1), (1, 1, 2), (1, 1, 3), (1, 2, 2), (1, 2, 3), (1, 3, 3), (2, 2, 2), (2, 2, 3), (2, 3, 3), (3, 3, 3)] assert len(list(subsets(l, 4, repetition=True))) == 35 assert list(subsets(l[:2], 3, repetition=False)) == [] assert list(subsets(l[:2], 3, repetition=True)) == [(0, 0, 0), (0, 0, 1), (0, 1, 1), (1, 1, 1)] assert list(subsets([1, 2], repetition=True)) == \ [(), (1,), (2,), (1, 1), (1, 2), (2, 2)] assert list(subsets([1, 2], repetition=False)) == \ [(), (1,), (2,), (1, 2)] assert list(subsets([1, 2, 3], 2)) == \ [(1, 2), (1, 3), (2, 3)] assert list(subsets([1, 2, 3], 2, repetition=True)) == \ [(1, 1), (1, 2), (1, 3), (2, 2), (2, 3), (3, 3)] def test_variations(): # permutations l = list(range(4)) assert list(variations(l, 0, repetition=False)) == [()] assert list(variations(l, 1, repetition=False)) == [(0,), (1,), (2,), (3,)] assert list(variations(l, 2, repetition=False)) == [(0, 1), (0, 2), (0, 3), (1, 0), (1, 2), (1, 3), (2, 0), (2, 1), (2, 3), (3, 0), (3, 1), (3, 2)] assert list(variations(l, 3, repetition=False)) == [(0, 1, 2), (0, 1, 3), (0, 2, 1), (0, 2, 3), (0, 3, 1), (0, 3, 2), (1, 0, 2), (1, 0, 3), (1, 2, 0), (1, 2, 3), (1, 3, 0), (1, 3, 2), (2, 0, 1), (2, 0, 3), (2, 1, 0), (2, 1, 3), (2, 3, 0), (2, 3, 1), (3, 0, 1), (3, 0, 2), (3, 1, 0), (3, 1, 2), (3, 2, 0), (3, 2, 1)] assert list(variations(l, 0, repetition=True)) == [()] assert list(variations(l, 1, repetition=True)) == [(0,), (1,), (2,), (3,)] assert list(variations(l, 2, repetition=True)) == [(0, 0), (0, 1), (0, 2), (0, 3), (1, 0), (1, 1), (1, 2), (1, 3), (2, 0), (2, 1), (2, 2), (2, 3), (3, 0), (3, 1), (3, 2), (3, 3)] assert len(list(variations(l, 3, repetition=True))) == 64 assert len(list(variations(l, 4, repetition=True))) == 256 assert list(variations(l[:2], 3, repetition=False)) == [] assert list(variations(l[:2], 3, repetition=True)) == [ (0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1) ] def test_cartes(): assert list(cartes([1, 2], [3, 4, 5])) == \ [(1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5)] assert list(cartes()) == [()] assert list(cartes('a')) == [('a',)] assert list(cartes('a', repeat=2)) == [('a', 'a')] assert list(cartes(list(range(2)))) == [(0,), (1,)] def test_filter_symbols(): s = numbered_symbols() filtered = filter_symbols(s, symbols("x0 x2 x3")) assert take(filtered, 3) == list(symbols("x1 x4 x5")) def test_numbered_symbols(): s = numbered_symbols(cls=Dummy) assert isinstance(next(s), Dummy) assert next(numbered_symbols('C', start=1, exclude=[symbols('C1')])) == \ symbols('C2') def test_sift(): assert sift(list(range(5)), lambda _: _ % 2) == {1: [1, 3], 0: [0, 2, 4]} assert sift([x, y], lambda _: _.has(x)) == {False: [y], True: [x]} assert sift([S.One], lambda _: _.has(x)) == {False: [1]} assert sift([0, 1, 2, 3], lambda x: x % 2, binary=True) == ( [1, 3], [0, 2]) assert sift([0, 1, 2, 3], lambda x: x % 3 == 1, binary=True) == ( [1], [0, 2, 3]) raises(ValueError, lambda: sift([0, 1, 2, 3], lambda x: x % 3, binary=True)) def test_take(): X = numbered_symbols() assert take(X, 5) == list(symbols('x0:5')) assert take(X, 5) == list(symbols('x5:10')) assert take([1, 2, 3, 4, 5], 5) == [1, 2, 3, 4, 5] def test_dict_merge(): assert dict_merge({}, {1: x, y: z}) == {1: x, y: z} assert dict_merge({1: x, y: z}, {}) == {1: x, y: z} assert dict_merge({2: z}, {1: x, y: z}) == {1: x, 2: z, y: z} assert dict_merge({1: x, y: z}, {2: z}) == {1: x, 2: z, y: z} assert dict_merge({1: y, 2: z}, {1: x, y: z}) == {1: x, 2: z, y: z} assert dict_merge({1: x, y: z}, {1: y, 2: z}) == {1: y, 2: z, y: z} def test_prefixes(): assert list(prefixes([])) == [] assert list(prefixes([1])) == [[1]] assert list(prefixes([1, 2])) == [[1], [1, 2]] assert list(prefixes([1, 2, 3, 4, 5])) == \ [[1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5]] def test_postfixes(): assert list(postfixes([])) == [] assert list(postfixes([1])) == [[1]] assert list(postfixes([1, 2])) == [[2], [1, 2]] assert list(postfixes([1, 2, 3, 4, 5])) == \ [[5], [4, 5], [3, 4, 5], [2, 3, 4, 5], [1, 2, 3, 4, 5]] def test_topological_sort(): V = [2, 3, 5, 7, 8, 9, 10, 11] E = [(7, 11), (7, 8), (5, 11), (3, 8), (3, 10), (11, 2), (11, 9), (11, 10), (8, 9)] assert topological_sort((V, E)) == [3, 5, 7, 8, 11, 2, 9, 10] assert topological_sort((V, E), key=lambda v: -v) == \ [7, 5, 11, 3, 10, 8, 9, 2] raises(ValueError, lambda: topological_sort((V, E + [(10, 7)]))) def test_strongly_connected_components(): assert strongly_connected_components(([], [])) == [] assert strongly_connected_components(([1, 2, 3], [])) == [[1], [2], [3]] V = [1, 2, 3] E = [(1, 2), (1, 3), (2, 1), (2, 3), (3, 1)] assert strongly_connected_components((V, E)) == [[1, 2, 3]] V = [1, 2, 3, 4] E = [(1, 2), (2, 3), (3, 2), (3, 4)] assert strongly_connected_components((V, E)) == [[4], [2, 3], [1]] V = [1, 2, 3, 4] E = [(1, 2), (2, 1), (3, 4), (4, 3)] assert strongly_connected_components((V, E)) == [[1, 2], [3, 4]] def test_connected_components(): assert connected_components(([], [])) == [] assert connected_components(([1, 2, 3], [])) == [[1], [2], [3]] V = [1, 2, 3] E = [(1, 2), (1, 3), (2, 1), (2, 3), (3, 1)] assert connected_components((V, E)) == [[1, 2, 3]] V = [1, 2, 3, 4] E = [(1, 2), (2, 3), (3, 2), (3, 4)] assert connected_components((V, E)) == [[1, 2, 3, 4]] V = [1, 2, 3, 4] E = [(1, 2), (3, 4)] assert connected_components((V, E)) == [[1, 2], [3, 4]] def test_rotate(): A = [0, 1, 2, 3, 4] assert rotate_left(A, 2) == [2, 3, 4, 0, 1] assert rotate_right(A, 1) == [4, 0, 1, 2, 3] A = [] B = rotate_right(A, 1) assert B == [] B.append(1) assert A == [] B = rotate_left(A, 1) assert B == [] B.append(1) assert A == [] def test_multiset_partitions(): A = [0, 1, 2, 3, 4] assert list(multiset_partitions(A, 5)) == [[[0], [1], [2], [3], [4]]] assert len(list(multiset_partitions(A, 4))) == 10 assert len(list(multiset_partitions(A, 3))) == 25 assert list(multiset_partitions([1, 1, 1, 2, 2], 2)) == [ [[1, 1, 1, 2], [2]], [[1, 1, 1], [2, 2]], [[1, 1, 2, 2], [1]], [[1, 1, 2], [1, 2]], [[1, 1], [1, 2, 2]]] assert list(multiset_partitions([1, 1, 2, 2], 2)) == [ [[1, 1, 2], [2]], [[1, 1], [2, 2]], [[1, 2, 2], [1]], [[1, 2], [1, 2]]] assert list(multiset_partitions([1, 2, 3, 4], 2)) == [ [[1, 2, 3], [4]], [[1, 2, 4], [3]], [[1, 2], [3, 4]], [[1, 3, 4], [2]], [[1, 3], [2, 4]], [[1, 4], [2, 3]], [[1], [2, 3, 4]]] assert list(multiset_partitions([1, 2, 2], 2)) == [ [[1, 2], [2]], [[1], [2, 2]]] assert list(multiset_partitions(3)) == [ [[0, 1, 2]], [[0, 1], [2]], [[0, 2], [1]], [[0], [1, 2]], [[0], [1], [2]]] assert list(multiset_partitions(3, 2)) == [ [[0, 1], [2]], [[0, 2], [1]], [[0], [1, 2]]] assert list(multiset_partitions([1] * 3, 2)) == [[[1], [1, 1]]] assert list(multiset_partitions([1] * 3)) == [ [[1, 1, 1]], [[1], [1, 1]], [[1], [1], [1]]] a = [3, 2, 1] assert list(multiset_partitions(a)) == \ list(multiset_partitions(sorted(a))) assert list(multiset_partitions(a, 5)) == [] assert list(multiset_partitions(a, 1)) == [[[1, 2, 3]]] assert list(multiset_partitions(a + [4], 5)) == [] assert list(multiset_partitions(a + [4], 1)) == [[[1, 2, 3, 4]]] assert list(multiset_partitions(2, 5)) == [] assert list(multiset_partitions(2, 1)) == [[[0, 1]]] assert list(multiset_partitions('a')) == [[['a']]] assert list(multiset_partitions('a', 2)) == [] assert list(multiset_partitions('ab')) == [[['a', 'b']], [['a'], ['b']]] assert list(multiset_partitions('ab', 1)) == [[['a', 'b']]] assert list(multiset_partitions('aaa', 1)) == [['aaa']] assert list(multiset_partitions([1, 1], 1)) == [[[1, 1]]] ans = [('mpsyy',), ('mpsy', 'y'), ('mps', 'yy'), ('mps', 'y', 'y'), ('mpyy', 's'), ('mpy', 'sy'), ('mpy', 's', 'y'), ('mp', 'syy'), ('mp', 'sy', 'y'), ('mp', 's', 'yy'), ('mp', 's', 'y', 'y'), ('msyy', 'p'), ('msy', 'py'), ('msy', 'p', 'y'), ('ms', 'pyy'), ('ms', 'py', 'y'), ('ms', 'p', 'yy'), ('ms', 'p', 'y', 'y'), ('myy', 'ps'), ('myy', 'p', 's'), ('my', 'psy'), ('my', 'ps', 'y'), ('my', 'py', 's'), ('my', 'p', 'sy'), ('my', 'p', 's', 'y'), ('m', 'psyy'), ('m', 'psy', 'y'), ('m', 'ps', 'yy'), ('m', 'ps', 'y', 'y'), ('m', 'pyy', 's'), ('m', 'py', 'sy'), ('m', 'py', 's', 'y'), ('m', 'p', 'syy'), ('m', 'p', 'sy', 'y'), ('m', 'p', 's', 'yy'), ('m', 'p', 's', 'y', 'y')] assert list(tuple("".join(part) for part in p) for p in multiset_partitions('sympy')) == ans factorings = [[24], [8, 3], [12, 2], [4, 6], [4, 2, 3], [6, 2, 2], [2, 2, 2, 3]] assert list(factoring_visitor(p, [2,3]) for p in multiset_partitions_taocp([3, 1])) == factorings def test_multiset_combinations(): ans = ['iii', 'iim', 'iip', 'iis', 'imp', 'ims', 'ipp', 'ips', 'iss', 'mpp', 'mps', 'mss', 'pps', 'pss', 'sss'] assert [''.join(i) for i in list(multiset_combinations('mississippi', 3))] == ans M = multiset('mississippi') assert [''.join(i) for i in list(multiset_combinations(M, 3))] == ans assert [''.join(i) for i in multiset_combinations(M, 30)] == [] assert list(multiset_combinations([[1], [2, 3]], 2)) == [[[1], [2, 3]]] assert len(list(multiset_combinations('a', 3))) == 0 assert len(list(multiset_combinations('a', 0))) == 1 assert list(multiset_combinations('abc', 1)) == [['a'], ['b'], ['c']] raises(ValueError, lambda: list(multiset_combinations({0: 3, 1: -1}, 2))) def test_multiset_permutations(): ans = ['abby', 'abyb', 'aybb', 'baby', 'bayb', 'bbay', 'bbya', 'byab', 'byba', 'yabb', 'ybab', 'ybba'] assert [''.join(i) for i in multiset_permutations('baby')] == ans assert [''.join(i) for i in multiset_permutations(multiset('baby'))] == ans assert list(multiset_permutations([0, 0, 0], 2)) == [[0, 0]] assert list(multiset_permutations([0, 2, 1], 2)) == [ [0, 1], [0, 2], [1, 0], [1, 2], [2, 0], [2, 1]] assert len(list(multiset_permutations('a', 0))) == 1 assert len(list(multiset_permutations('a', 3))) == 0 for nul in ([], {}, ''): assert list(multiset_permutations(nul)) == [[]] assert list(multiset_permutations(nul, 0)) == [[]] # impossible requests give no result assert list(multiset_permutations(nul, 1)) == [] assert list(multiset_permutations(nul, -1)) == [] def test(): for i in range(1, 7): print(i) for p in multiset_permutations([0, 0, 1, 0, 1], i): print(p) assert capture(lambda: test()) == dedent('''\ 1 [0] [1] 2 [0, 0] [0, 1] [1, 0] [1, 1] 3 [0, 0, 0] [0, 0, 1] [0, 1, 0] [0, 1, 1] [1, 0, 0] [1, 0, 1] [1, 1, 0] 4 [0, 0, 0, 1] [0, 0, 1, 0] [0, 0, 1, 1] [0, 1, 0, 0] [0, 1, 0, 1] [0, 1, 1, 0] [1, 0, 0, 0] [1, 0, 0, 1] [1, 0, 1, 0] [1, 1, 0, 0] 5 [0, 0, 0, 1, 1] [0, 0, 1, 0, 1] [0, 0, 1, 1, 0] [0, 1, 0, 0, 1] [0, 1, 0, 1, 0] [0, 1, 1, 0, 0] [1, 0, 0, 0, 1] [1, 0, 0, 1, 0] [1, 0, 1, 0, 0] [1, 1, 0, 0, 0] 6\n''') raises(ValueError, lambda: list(multiset_permutations({0: 3, 1: -1}))) def test_partitions(): ans = [[{}], [(0, {})]] for i in range(2): assert list(partitions(0, size=i)) == ans[i] assert list(partitions(1, 0, size=i)) == ans[i] assert list(partitions(6, 2, 2, size=i)) == ans[i] assert list(partitions(6, 2, None, size=i)) != ans[i] assert list(partitions(6, None, 2, size=i)) != ans[i] assert list(partitions(6, 2, 0, size=i)) == ans[i] assert [p for p in partitions(6, k=2)] == [ {2: 3}, {1: 2, 2: 2}, {1: 4, 2: 1}, {1: 6}] assert [p for p in partitions(6, k=3)] == [ {3: 2}, {1: 1, 2: 1, 3: 1}, {1: 3, 3: 1}, {2: 3}, {1: 2, 2: 2}, {1: 4, 2: 1}, {1: 6}] assert [p for p in partitions(8, k=4, m=3)] == [ {4: 2}, {1: 1, 3: 1, 4: 1}, {2: 2, 4: 1}, {2: 1, 3: 2}] == [ i for i in partitions(8, k=4, m=3) if all(k <= 4 for k in i) and sum(i.values()) <=3] assert [p for p in partitions(S(3), m=2)] == [ {3: 1}, {1: 1, 2: 1}] assert [i for i in partitions(4, k=3)] == [ {1: 1, 3: 1}, {2: 2}, {1: 2, 2: 1}, {1: 4}] == [ i for i in partitions(4) if all(k <= 3 for k in i)] # Consistency check on output of _partitions and RGS_unrank. # This provides a sanity test on both routines. Also verifies that # the total number of partitions is the same in each case. # (from pkrathmann2) for n in range(2, 6): i = 0 for m, q in _set_partitions(n): assert q == RGS_unrank(i, n) i += 1 assert i == RGS_enum(n) def test_binary_partitions(): assert [i[:] for i in binary_partitions(10)] == [[8, 2], [8, 1, 1], [4, 4, 2], [4, 4, 1, 1], [4, 2, 2, 2], [4, 2, 2, 1, 1], [4, 2, 1, 1, 1, 1], [4, 1, 1, 1, 1, 1, 1], [2, 2, 2, 2, 2], [2, 2, 2, 2, 1, 1], [2, 2, 2, 1, 1, 1, 1], [2, 2, 1, 1, 1, 1, 1, 1], [2, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] assert len([j[:] for j in binary_partitions(16)]) == 36 def test_bell_perm(): assert [len(set(generate_bell(i))) for i in range(1, 7)] == [ factorial(i) for i in range(1, 7)] assert list(generate_bell(3)) == [ (0, 1, 2), (0, 2, 1), (2, 0, 1), (2, 1, 0), (1, 2, 0), (1, 0, 2)] # generate_bell and trotterjohnson are advertised to return the same # permutations; this is not technically necessary so this test could # be removed for n in range(1, 5): p = Permutation(range(n)) b = generate_bell(n) for bi in b: assert bi == tuple(p.array_form) p = p.next_trotterjohnson() raises(ValueError, lambda: list(generate_bell(0))) # XXX is this consistent with other permutation algorithms? def test_involutions(): lengths = [1, 2, 4, 10, 26, 76] for n, N in enumerate(lengths): i = list(generate_involutions(n + 1)) assert len(i) == N assert len({Permutation(j)**2 for j in i}) == 1 def test_derangements(): assert len(list(generate_derangements(list(range(6))))) == 265 assert ''.join(''.join(i) for i in generate_derangements('abcde')) == ( 'badecbaecdbcaedbcdeabceadbdaecbdeacbdecabeacdbedacbedcacabedcadebcaebd' 'cdaebcdbeacdeabcdebaceabdcebadcedabcedbadabecdaebcdaecbdcaebdcbeadceab' 'dcebadeabcdeacbdebacdebcaeabcdeadbceadcbecabdecbadecdabecdbaedabcedacb' 'edbacedbca') assert list(generate_derangements([0, 1, 2, 3])) == [ [1, 0, 3, 2], [1, 2, 3, 0], [1, 3, 0, 2], [2, 0, 3, 1], [2, 3, 0, 1], [2, 3, 1, 0], [3, 0, 1, 2], [3, 2, 0, 1], [3, 2, 1, 0]] assert list(generate_derangements([0, 1, 2, 2])) == [ [2, 2, 0, 1], [2, 2, 1, 0]] assert list(generate_derangements('ba')) == [list('ab')] # multiset_derangements D = multiset_derangements assert list(D('abb')) == [] assert [''.join(i) for i in D('ab')] == ['ba'] assert [''.join(i) for i in D('abc')] == ['bca', 'cab'] assert [''.join(i) for i in D('aabb')] == ['bbaa'] assert [''.join(i) for i in D('aabbcccc')] == [ 'ccccaabb', 'ccccabab', 'ccccabba', 'ccccbaab', 'ccccbaba', 'ccccbbaa'] assert [''.join(i) for i in D('aabbccc')] == [ 'cccabba', 'cccabab', 'cccaabb', 'ccacbba', 'ccacbab', 'ccacabb', 'cbccbaa', 'cbccaba', 'cbccaab', 'bcccbaa', 'bcccaba', 'bcccaab'] assert [''.join(i) for i in D('books')] == ['kbsoo', 'ksboo', 'sbkoo', 'skboo', 'oksbo', 'oskbo', 'okbso', 'obkso', 'oskob', 'oksob', 'osbok', 'obsok'] assert list(generate_derangements([[3], [2], [2], [1]])) == [ [[2], [1], [3], [2]], [[2], [3], [1], [2]]] def test_necklaces(): def count(n, k, f): return len(list(necklaces(n, k, f))) m = [] for i in range(1, 8): m.append(( i, count(i, 2, 0), count(i, 2, 1), count(i, 3, 1))) assert Matrix(m) == Matrix([ [1, 2, 2, 3], [2, 3, 3, 6], [3, 4, 4, 10], [4, 6, 6, 21], [5, 8, 8, 39], [6, 14, 13, 92], [7, 20, 18, 198]]) def test_bracelets(): bc = [i for i in bracelets(2, 4)] assert Matrix(bc) == Matrix([ [0, 0], [0, 1], [0, 2], [0, 3], [1, 1], [1, 2], [1, 3], [2, 2], [2, 3], [3, 3] ]) bc = [i for i in bracelets(4, 2)] assert Matrix(bc) == Matrix([ [0, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 1], [0, 1, 0, 1], [0, 1, 1, 1], [1, 1, 1, 1] ]) def test_generate_oriented_forest(): assert list(generate_oriented_forest(5)) == [[0, 1, 2, 3, 4], [0, 1, 2, 3, 3], [0, 1, 2, 3, 2], [0, 1, 2, 3, 1], [0, 1, 2, 3, 0], [0, 1, 2, 2, 2], [0, 1, 2, 2, 1], [0, 1, 2, 2, 0], [0, 1, 2, 1, 2], [0, 1, 2, 1, 1], [0, 1, 2, 1, 0], [0, 1, 2, 0, 1], [0, 1, 2, 0, 0], [0, 1, 1, 1, 1], [0, 1, 1, 1, 0], [0, 1, 1, 0, 1], [0, 1, 1, 0, 0], [0, 1, 0, 1, 0], [0, 1, 0, 0, 0], [0, 0, 0, 0, 0]] assert len(list(generate_oriented_forest(10))) == 1842 def test_unflatten(): r = list(range(10)) assert unflatten(r) == list(zip(r[::2], r[1::2])) assert unflatten(r, 5) == [tuple(r[:5]), tuple(r[5:])] raises(ValueError, lambda: unflatten(list(range(10)), 3)) raises(ValueError, lambda: unflatten(list(range(10)), -2)) def test_common_prefix_suffix(): assert common_prefix([], [1]) == [] assert common_prefix(list(range(3))) == [0, 1, 2] assert common_prefix(list(range(3)), list(range(4))) == [0, 1, 2] assert common_prefix([1, 2, 3], [1, 2, 5]) == [1, 2] assert common_prefix([1, 2, 3], [1, 3, 5]) == [1] assert common_suffix([], [1]) == [] assert common_suffix(list(range(3))) == [0, 1, 2] assert common_suffix(list(range(3)), list(range(3))) == [0, 1, 2] assert common_suffix(list(range(3)), list(range(4))) == [] assert common_suffix([1, 2, 3], [9, 2, 3]) == [2, 3] assert common_suffix([1, 2, 3], [9, 7, 3]) == [3] def test_minlex(): assert minlex([1, 2, 0]) == (0, 1, 2) assert minlex((1, 2, 0)) == (0, 1, 2) assert minlex((1, 0, 2)) == (0, 2, 1) assert minlex((1, 0, 2), directed=False) == (0, 1, 2) assert minlex('aba') == 'aab' assert minlex(('bb', 'aaa', 'c', 'a'), key=len) == ('c', 'a', 'bb', 'aaa') def test_ordered(): assert list(ordered((x, y), hash, default=False)) in [[x, y], [y, x]] assert list(ordered((x, y), hash, default=False)) == \ list(ordered((y, x), hash, default=False)) assert list(ordered((x, y))) == [x, y] seq, keys = [[[1, 2, 1], [0, 3, 1], [1, 1, 3], [2], [1]], (lambda x: len(x), lambda x: sum(x))] assert list(ordered(seq, keys, default=False, warn=False)) == \ [[1], [2], [1, 2, 1], [0, 3, 1], [1, 1, 3]] raises(ValueError, lambda: list(ordered(seq, keys, default=False, warn=True))) def test_runs(): assert runs([]) == [] assert runs([1]) == [[1]] assert runs([1, 1]) == [[1], [1]] assert runs([1, 1, 2]) == [[1], [1, 2]] assert runs([1, 2, 1]) == [[1, 2], [1]] assert runs([2, 1, 1]) == [[2], [1], [1]] from operator import lt assert runs([2, 1, 1], lt) == [[2, 1], [1]] def test_reshape(): seq = list(range(1, 9)) assert reshape(seq, [4]) == \ [[1, 2, 3, 4], [5, 6, 7, 8]] assert reshape(seq, (4,)) == \ [(1, 2, 3, 4), (5, 6, 7, 8)] assert reshape(seq, (2, 2)) == \ [(1, 2, 3, 4), (5, 6, 7, 8)] assert reshape(seq, (2, [2])) == \ [(1, 2, [3, 4]), (5, 6, [7, 8])] assert reshape(seq, ((2,), [2])) == \ [((1, 2), [3, 4]), ((5, 6), [7, 8])] assert reshape(seq, (1, [2], 1)) == \ [(1, [2, 3], 4), (5, [6, 7], 8)] assert reshape(tuple(seq), ([[1], 1, (2,)],)) == \ (([[1], 2, (3, 4)],), ([[5], 6, (7, 8)],)) assert reshape(tuple(seq), ([1], 1, (2,))) == \ (([1], 2, (3, 4)), ([5], 6, (7, 8))) assert reshape(list(range(12)), [2, [3], {2}, (1, (3,), 1)]) == \ [[0, 1, [2, 3, 4], {5, 6}, (7, (8, 9, 10), 11)]] raises(ValueError, lambda: reshape([0, 1], [-1])) raises(ValueError, lambda: reshape([0, 1], [3])) def test_uniq(): assert list(uniq(p for p in partitions(4))) == \ [{4: 1}, {1: 1, 3: 1}, {2: 2}, {1: 2, 2: 1}, {1: 4}] assert list(uniq(x % 2 for x in range(5))) == [0, 1] assert list(uniq('a')) == ['a'] assert list(uniq('ababc')) == list('abc') assert list(uniq([[1], [2, 1], [1]])) == [[1], [2, 1]] assert list(uniq(permutations(i for i in [[1], 2, 2]))) == \ [([1], 2, 2), (2, [1], 2), (2, 2, [1])] assert list(uniq([2, 3, 2, 4, [2], [1], [2], [3], [1]])) == \ [2, 3, 4, [2], [1], [3]] f = [1] raises(RuntimeError, lambda: [f.remove(i) for i in uniq(f)]) f = [[1]] raises(RuntimeError, lambda: [f.remove(i) for i in uniq(f)]) def test_kbins(): assert len(list(kbins('1123', 2, ordered=1))) == 24 assert len(list(kbins('1123', 2, ordered=11))) == 36 assert len(list(kbins('1123', 2, ordered=10))) == 10 assert len(list(kbins('1123', 2, ordered=0))) == 5 assert len(list(kbins('1123', 2, ordered=None))) == 3 def test1(): for orderedval in [None, 0, 1, 10, 11]: print('ordered =', orderedval) for p in kbins([0, 0, 1], 2, ordered=orderedval): print(' ', p) assert capture(lambda : test1()) == dedent('''\ ordered = None [[0], [0, 1]] [[0, 0], [1]] ordered = 0 [[0, 0], [1]] [[0, 1], [0]] ordered = 1 [[0], [0, 1]] [[0], [1, 0]] [[1], [0, 0]] ordered = 10 [[0, 0], [1]] [[1], [0, 0]] [[0, 1], [0]] [[0], [0, 1]] ordered = 11 [[0], [0, 1]] [[0, 0], [1]] [[0], [1, 0]] [[0, 1], [0]] [[1], [0, 0]] [[1, 0], [0]]\n''') def test2(): for orderedval in [None, 0, 1, 10, 11]: print('ordered =', orderedval) for p in kbins(list(range(3)), 2, ordered=orderedval): print(' ', p) assert capture(lambda : test2()) == dedent('''\ ordered = None [[0], [1, 2]] [[0, 1], [2]] ordered = 0 [[0, 1], [2]] [[0, 2], [1]] [[0], [1, 2]] ordered = 1 [[0], [1, 2]] [[0], [2, 1]] [[1], [0, 2]] [[1], [2, 0]] [[2], [0, 1]] [[2], [1, 0]] ordered = 10 [[0, 1], [2]] [[2], [0, 1]] [[0, 2], [1]] [[1], [0, 2]] [[0], [1, 2]] [[1, 2], [0]] ordered = 11 [[0], [1, 2]] [[0, 1], [2]] [[0], [2, 1]] [[0, 2], [1]] [[1], [0, 2]] [[1, 0], [2]] [[1], [2, 0]] [[1, 2], [0]] [[2], [0, 1]] [[2, 0], [1]] [[2], [1, 0]] [[2, 1], [0]]\n''') def test_has_dups(): assert has_dups(set()) is False assert has_dups(list(range(3))) is False assert has_dups([1, 2, 1]) is True assert has_dups([[1], [1]]) is True assert has_dups([[1], [2]]) is False def test__partition(): assert _partition('abcde', [1, 0, 1, 2, 0]) == [ ['b', 'e'], ['a', 'c'], ['d']] assert _partition('abcde', [1, 0, 1, 2, 0], 3) == [ ['b', 'e'], ['a', 'c'], ['d']] output = (3, [1, 0, 1, 2, 0]) assert _partition('abcde', *output) == [['b', 'e'], ['a', 'c'], ['d']] def test_ordered_partitions(): from sympy.functions.combinatorial.numbers import nT f = ordered_partitions assert list(f(0, 1)) == [[]] assert list(f(1, 0)) == [[]] for i in range(1, 7): for j in [None] + list(range(1, i)): assert ( sum(1 for p in f(i, j, 1)) == sum(1 for p in f(i, j, 0)) == nT(i, j)) def test_rotations(): assert list(rotations('ab')) == [['a', 'b'], ['b', 'a']] assert list(rotations(range(3))) == [[0, 1, 2], [1, 2, 0], [2, 0, 1]] assert list(rotations(range(3), dir=-1)) == [[0, 1, 2], [2, 0, 1], [1, 2, 0]] def test_ibin(): assert ibin(3) == [1, 1] assert ibin(3, 3) == [0, 1, 1] assert ibin(3, str=True) == '11' assert ibin(3, 3, str=True) == '011' assert list(ibin(2, 'all')) == [(0, 0), (0, 1), (1, 0), (1, 1)] assert list(ibin(2, '', str=True)) == ['00', '01', '10', '11'] raises(ValueError, lambda: ibin(-.5)) raises(ValueError, lambda: ibin(2, 1)) def test_iterable(): assert iterable(0) is False assert iterable(1) is False assert iterable(None) is False class Test1(NotIterable): pass assert iterable(Test1()) is False class Test2(NotIterable): _iterable = True assert iterable(Test2()) is True class Test3: pass assert iterable(Test3()) is False class Test4: _iterable = True assert iterable(Test4()) is True class Test5: def __iter__(self): yield 1 assert iterable(Test5()) is True class Test6(Test5): _iterable = False assert iterable(Test6()) is False
38a45adb2b8732d9d57278acbbec5c69e762d912ac1fd42b814f5ec60a0e2b7d
from sympy.testing.pytest import raises from sympy.utilities.exceptions import sympy_deprecation_warning # Only test exceptions here because the other cases are tested in the # warns_deprecated_sympy tests def test_sympy_deprecation_warning(): raises(TypeError, lambda: sympy_deprecation_warning('test', deprecated_since_version=1.10, active_deprecations_target='active-deprecations')) raises(ValueError, lambda: sympy_deprecation_warning('test', deprecated_since_version="1.10", active_deprecations_target='(active-deprecations)='))
55852fcd4ad523b23b30ad186712cb12612ee2957976a681d422c427c39c6afe
from functools import wraps from sympy.utilities.decorator import threaded, xthreaded, memoize_property, deprecated from sympy.testing.pytest import warns_deprecated_sympy from sympy.core.basic import Basic from sympy.core.relational import Eq from sympy.matrices.dense import Matrix from sympy.abc import x, y def test_threaded(): @threaded def function(expr, *args): return 2*expr + sum(args) assert function(Matrix([[x, y], [1, x]]), 1, 2) == \ Matrix([[2*x + 3, 2*y + 3], [5, 2*x + 3]]) assert function(Eq(x, y), 1, 2) == Eq(2*x + 3, 2*y + 3) assert function([x, y], 1, 2) == [2*x + 3, 2*y + 3] assert function((x, y), 1, 2) == (2*x + 3, 2*y + 3) assert function({x, y}, 1, 2) == {2*x + 3, 2*y + 3} @threaded def function(expr, n): return expr**n assert function(x + y, 2) == x**2 + y**2 assert function(x, 2) == x**2 def test_xthreaded(): @xthreaded def function(expr, n): return expr**n assert function(x + y, 2) == (x + y)**2 def test_wraps(): def my_func(x): """My function. """ my_func.is_my_func = True new_my_func = threaded(my_func) new_my_func = wraps(my_func)(new_my_func) assert new_my_func.__name__ == 'my_func' assert new_my_func.__doc__ == 'My function. ' assert hasattr(new_my_func, 'is_my_func') assert new_my_func.is_my_func is True def test_memoize_property(): class TestMemoize(Basic): @memoize_property def prop(self): return Basic() member = TestMemoize() obj1 = member.prop obj2 = member.prop assert obj1 is obj2 def test_deprecated(): @deprecated('deprecated_function is deprecated', deprecated_since_version='1.10', # This is the target at the top of the file, which will never # go away. active_deprecations_target='active-deprecations') def deprecated_function(x): return x with warns_deprecated_sympy(): assert deprecated_function(1) == 1 @deprecated('deprecated_class is deprecated', deprecated_since_version='1.10', active_deprecations_target='active-deprecations') class deprecated_class: pass with warns_deprecated_sympy(): assert isinstance(deprecated_class(), deprecated_class) # Ensure the class decorator works even when the class never returns # itself @deprecated('deprecated_class_new is deprecated', deprecated_since_version='1.10', active_deprecations_target='active-deprecations') class deprecated_class_new: def __new__(cls, arg): return arg with warns_deprecated_sympy(): assert deprecated_class_new(1) == 1 @deprecated('deprecated_class_init is deprecated', deprecated_since_version='1.10', active_deprecations_target='active-deprecations') class deprecated_class_init: def __init__(self, arg): self.arg = 1 with warns_deprecated_sympy(): assert deprecated_class_init(1).arg == 1 @deprecated('deprecated_class_new_init is deprecated', deprecated_since_version='1.10', active_deprecations_target='active-deprecations') class deprecated_class_new_init: def __new__(cls, arg): if arg == 0: return arg return object.__new__(cls) def __init__(self, arg): self.arg = 1 with warns_deprecated_sympy(): assert deprecated_class_new_init(0) == 0 with warns_deprecated_sympy(): assert deprecated_class_new_init(1).arg == 1
632884d4db230ce62b222a12b0840ff95ad6a7c452550cf0dde5d935efe665b2
import itertools from sympy.core import S from sympy.core.add import Add from sympy.core.containers import Tuple from sympy.core.function import Function from sympy.core.mul import Mul from sympy.core.numbers import Number, Rational from sympy.core.power import Pow from sympy.core.sorting import default_sort_key from sympy.core.symbol import Symbol from sympy.core.sympify import SympifyError from sympy.printing.conventions import requires_partial from sympy.printing.precedence import PRECEDENCE, precedence, precedence_traditional from sympy.printing.printer import Printer, print_function from sympy.printing.str import sstr from sympy.utilities.iterables import has_variety from sympy.utilities.exceptions import sympy_deprecation_warning from sympy.printing.pretty.stringpict import prettyForm, stringPict from sympy.printing.pretty.pretty_symbology import hobj, vobj, xobj, \ xsym, pretty_symbol, pretty_atom, pretty_use_unicode, greek_unicode, U, \ pretty_try_use_unicode, annotated # rename for usage from outside pprint_use_unicode = pretty_use_unicode pprint_try_use_unicode = pretty_try_use_unicode class PrettyPrinter(Printer): """Printer, which converts an expression into 2D ASCII-art figure.""" printmethod = "_pretty" _default_settings = { "order": None, "full_prec": "auto", "use_unicode": None, "wrap_line": True, "num_columns": None, "use_unicode_sqrt_char": True, "root_notation": True, "mat_symbol_style": "plain", "imaginary_unit": "i", "perm_cyclic": True } def __init__(self, settings=None): Printer.__init__(self, settings) if not isinstance(self._settings['imaginary_unit'], str): raise TypeError("'imaginary_unit' must a string, not {}".format(self._settings['imaginary_unit'])) elif self._settings['imaginary_unit'] not in ("i", "j"): raise ValueError("'imaginary_unit' must be either 'i' or 'j', not '{}'".format(self._settings['imaginary_unit'])) def emptyPrinter(self, expr): return prettyForm(str(expr)) @property def _use_unicode(self): if self._settings['use_unicode']: return True else: return pretty_use_unicode() def doprint(self, expr): return self._print(expr).render(**self._settings) # empty op so _print(stringPict) returns the same def _print_stringPict(self, e): return e def _print_basestring(self, e): return prettyForm(e) def _print_atan2(self, e): pform = prettyForm(*self._print_seq(e.args).parens()) pform = prettyForm(*pform.left('atan2')) return pform def _print_Symbol(self, e, bold_name=False): symb = pretty_symbol(e.name, bold_name) return prettyForm(symb) _print_RandomSymbol = _print_Symbol def _print_MatrixSymbol(self, e): return self._print_Symbol(e, self._settings['mat_symbol_style'] == "bold") def _print_Float(self, e): # we will use StrPrinter's Float printer, but we need to handle the # full_prec ourselves, according to the self._print_level full_prec = self._settings["full_prec"] if full_prec == "auto": full_prec = self._print_level == 1 return prettyForm(sstr(e, full_prec=full_prec)) def _print_Cross(self, e): vec1 = e._expr1 vec2 = e._expr2 pform = self._print(vec2) pform = prettyForm(*pform.left('(')) pform = prettyForm(*pform.right(')')) pform = prettyForm(*pform.left(self._print(U('MULTIPLICATION SIGN')))) pform = prettyForm(*pform.left(')')) pform = prettyForm(*pform.left(self._print(vec1))) pform = prettyForm(*pform.left('(')) return pform def _print_Curl(self, e): vec = e._expr pform = self._print(vec) pform = prettyForm(*pform.left('(')) pform = prettyForm(*pform.right(')')) pform = prettyForm(*pform.left(self._print(U('MULTIPLICATION SIGN')))) pform = prettyForm(*pform.left(self._print(U('NABLA')))) return pform def _print_Divergence(self, e): vec = e._expr pform = self._print(vec) pform = prettyForm(*pform.left('(')) pform = prettyForm(*pform.right(')')) pform = prettyForm(*pform.left(self._print(U('DOT OPERATOR')))) pform = prettyForm(*pform.left(self._print(U('NABLA')))) return pform def _print_Dot(self, e): vec1 = e._expr1 vec2 = e._expr2 pform = self._print(vec2) pform = prettyForm(*pform.left('(')) pform = prettyForm(*pform.right(')')) pform = prettyForm(*pform.left(self._print(U('DOT OPERATOR')))) pform = prettyForm(*pform.left(')')) pform = prettyForm(*pform.left(self._print(vec1))) pform = prettyForm(*pform.left('(')) return pform def _print_Gradient(self, e): func = e._expr pform = self._print(func) pform = prettyForm(*pform.left('(')) pform = prettyForm(*pform.right(')')) pform = prettyForm(*pform.left(self._print(U('NABLA')))) return pform def _print_Laplacian(self, e): func = e._expr pform = self._print(func) pform = prettyForm(*pform.left('(')) pform = prettyForm(*pform.right(')')) pform = prettyForm(*pform.left(self._print(U('INCREMENT')))) return pform def _print_Atom(self, e): try: # print atoms like Exp1 or Pi return prettyForm(pretty_atom(e.__class__.__name__, printer=self)) except KeyError: return self.emptyPrinter(e) # Infinity inherits from Number, so we have to override _print_XXX order _print_Infinity = _print_Atom _print_NegativeInfinity = _print_Atom _print_EmptySet = _print_Atom _print_Naturals = _print_Atom _print_Naturals0 = _print_Atom _print_Integers = _print_Atom _print_Rationals = _print_Atom _print_Complexes = _print_Atom _print_EmptySequence = _print_Atom def _print_Reals(self, e): if self._use_unicode: return self._print_Atom(e) else: inf_list = ['-oo', 'oo'] return self._print_seq(inf_list, '(', ')') def _print_subfactorial(self, e): x = e.args[0] pform = self._print(x) # Add parentheses if needed if not ((x.is_Integer and x.is_nonnegative) or x.is_Symbol): pform = prettyForm(*pform.parens()) pform = prettyForm(*pform.left('!')) return pform def _print_factorial(self, e): x = e.args[0] pform = self._print(x) # Add parentheses if needed if not ((x.is_Integer and x.is_nonnegative) or x.is_Symbol): pform = prettyForm(*pform.parens()) pform = prettyForm(*pform.right('!')) return pform def _print_factorial2(self, e): x = e.args[0] pform = self._print(x) # Add parentheses if needed if not ((x.is_Integer and x.is_nonnegative) or x.is_Symbol): pform = prettyForm(*pform.parens()) pform = prettyForm(*pform.right('!!')) return pform def _print_binomial(self, e): n, k = e.args n_pform = self._print(n) k_pform = self._print(k) bar = ' '*max(n_pform.width(), k_pform.width()) pform = prettyForm(*k_pform.above(bar)) pform = prettyForm(*pform.above(n_pform)) pform = prettyForm(*pform.parens('(', ')')) pform.baseline = (pform.baseline + 1)//2 return pform def _print_Relational(self, e): op = prettyForm(' ' + xsym(e.rel_op) + ' ') l = self._print(e.lhs) r = self._print(e.rhs) pform = prettyForm(*stringPict.next(l, op, r), binding=prettyForm.OPEN) return pform def _print_Not(self, e): from sympy.logic.boolalg import (Equivalent, Implies) if self._use_unicode: arg = e.args[0] pform = self._print(arg) if isinstance(arg, Equivalent): return self._print_Equivalent(arg, altchar="\N{LEFT RIGHT DOUBLE ARROW WITH STROKE}") if isinstance(arg, Implies): return self._print_Implies(arg, altchar="\N{RIGHTWARDS ARROW WITH STROKE}") if arg.is_Boolean and not arg.is_Not: pform = prettyForm(*pform.parens()) return prettyForm(*pform.left("\N{NOT SIGN}")) else: return self._print_Function(e) def __print_Boolean(self, e, char, sort=True): args = e.args if sort: args = sorted(e.args, key=default_sort_key) arg = args[0] pform = self._print(arg) if arg.is_Boolean and not arg.is_Not: pform = prettyForm(*pform.parens()) for arg in args[1:]: pform_arg = self._print(arg) if arg.is_Boolean and not arg.is_Not: pform_arg = prettyForm(*pform_arg.parens()) pform = prettyForm(*pform.right(' %s ' % char)) pform = prettyForm(*pform.right(pform_arg)) return pform def _print_And(self, e): if self._use_unicode: return self.__print_Boolean(e, "\N{LOGICAL AND}") else: return self._print_Function(e, sort=True) def _print_Or(self, e): if self._use_unicode: return self.__print_Boolean(e, "\N{LOGICAL OR}") else: return self._print_Function(e, sort=True) def _print_Xor(self, e): if self._use_unicode: return self.__print_Boolean(e, "\N{XOR}") else: return self._print_Function(e, sort=True) def _print_Nand(self, e): if self._use_unicode: return self.__print_Boolean(e, "\N{NAND}") else: return self._print_Function(e, sort=True) def _print_Nor(self, e): if self._use_unicode: return self.__print_Boolean(e, "\N{NOR}") else: return self._print_Function(e, sort=True) def _print_Implies(self, e, altchar=None): if self._use_unicode: return self.__print_Boolean(e, altchar or "\N{RIGHTWARDS ARROW}", sort=False) else: return self._print_Function(e) def _print_Equivalent(self, e, altchar=None): if self._use_unicode: return self.__print_Boolean(e, altchar or "\N{LEFT RIGHT DOUBLE ARROW}") else: return self._print_Function(e, sort=True) def _print_conjugate(self, e): pform = self._print(e.args[0]) return prettyForm( *pform.above( hobj('_', pform.width())) ) def _print_Abs(self, e): pform = self._print(e.args[0]) pform = prettyForm(*pform.parens('|', '|')) return pform _print_Determinant = _print_Abs def _print_floor(self, e): if self._use_unicode: pform = self._print(e.args[0]) pform = prettyForm(*pform.parens('lfloor', 'rfloor')) return pform else: return self._print_Function(e) def _print_ceiling(self, e): if self._use_unicode: pform = self._print(e.args[0]) pform = prettyForm(*pform.parens('lceil', 'rceil')) return pform else: return self._print_Function(e) def _print_Derivative(self, deriv): if requires_partial(deriv.expr) and self._use_unicode: deriv_symbol = U('PARTIAL DIFFERENTIAL') else: deriv_symbol = r'd' x = None count_total_deriv = 0 for sym, num in reversed(deriv.variable_count): s = self._print(sym) ds = prettyForm(*s.left(deriv_symbol)) count_total_deriv += num if (not num.is_Integer) or (num > 1): ds = ds**prettyForm(str(num)) if x is None: x = ds else: x = prettyForm(*x.right(' ')) x = prettyForm(*x.right(ds)) f = prettyForm( binding=prettyForm.FUNC, *self._print(deriv.expr).parens()) pform = prettyForm(deriv_symbol) if (count_total_deriv > 1) != False: pform = pform**prettyForm(str(count_total_deriv)) pform = prettyForm(*pform.below(stringPict.LINE, x)) pform.baseline = pform.baseline + 1 pform = prettyForm(*stringPict.next(pform, f)) pform.binding = prettyForm.MUL return pform def _print_Cycle(self, dc): from sympy.combinatorics.permutations import Permutation, Cycle # for Empty Cycle if dc == Cycle(): cyc = stringPict('') return prettyForm(*cyc.parens()) dc_list = Permutation(dc.list()).cyclic_form # for Identity Cycle if dc_list == []: cyc = self._print(dc.size - 1) return prettyForm(*cyc.parens()) cyc = stringPict('') for i in dc_list: l = self._print(str(tuple(i)).replace(',', '')) cyc = prettyForm(*cyc.right(l)) return cyc def _print_Permutation(self, expr): from sympy.combinatorics.permutations import Permutation, Cycle perm_cyclic = Permutation.print_cyclic if perm_cyclic is not None: sympy_deprecation_warning( f""" Setting Permutation.print_cyclic is deprecated. Instead use init_printing(perm_cyclic={perm_cyclic}). """, deprecated_since_version="1.6", active_deprecations_target="deprecated-permutation-print_cyclic", stacklevel=7, ) else: perm_cyclic = self._settings.get("perm_cyclic", True) if perm_cyclic: return self._print_Cycle(Cycle(expr)) lower = expr.array_form upper = list(range(len(lower))) result = stringPict('') first = True for u, l in zip(upper, lower): s1 = self._print(u) s2 = self._print(l) col = prettyForm(*s1.below(s2)) if first: first = False else: col = prettyForm(*col.left(" ")) result = prettyForm(*result.right(col)) return prettyForm(*result.parens()) def _print_Integral(self, integral): f = integral.function # Add parentheses if arg involves addition of terms and # create a pretty form for the argument prettyF = self._print(f) # XXX generalize parens if f.is_Add: prettyF = prettyForm(*prettyF.parens()) # dx dy dz ... arg = prettyF for x in integral.limits: prettyArg = self._print(x[0]) # XXX qparens (parens if needs-parens) if prettyArg.width() > 1: prettyArg = prettyForm(*prettyArg.parens()) arg = prettyForm(*arg.right(' d', prettyArg)) # \int \int \int ... firstterm = True s = None for lim in integral.limits: # Create bar based on the height of the argument h = arg.height() H = h + 2 # XXX hack! ascii_mode = not self._use_unicode if ascii_mode: H += 2 vint = vobj('int', H) # Construct the pretty form with the integral sign and the argument pform = prettyForm(vint) pform.baseline = arg.baseline + ( H - h)//2 # covering the whole argument if len(lim) > 1: # Create pretty forms for endpoints, if definite integral. # Do not print empty endpoints. if len(lim) == 2: prettyA = prettyForm("") prettyB = self._print(lim[1]) if len(lim) == 3: prettyA = self._print(lim[1]) prettyB = self._print(lim[2]) if ascii_mode: # XXX hack # Add spacing so that endpoint can more easily be # identified with the correct integral sign spc = max(1, 3 - prettyB.width()) prettyB = prettyForm(*prettyB.left(' ' * spc)) spc = max(1, 4 - prettyA.width()) prettyA = prettyForm(*prettyA.right(' ' * spc)) pform = prettyForm(*pform.above(prettyB)) pform = prettyForm(*pform.below(prettyA)) if not ascii_mode: # XXX hack pform = prettyForm(*pform.right(' ')) if firstterm: s = pform # first term firstterm = False else: s = prettyForm(*s.left(pform)) pform = prettyForm(*arg.left(s)) pform.binding = prettyForm.MUL return pform def _print_Product(self, expr): func = expr.term pretty_func = self._print(func) horizontal_chr = xobj('_', 1) corner_chr = xobj('_', 1) vertical_chr = xobj('|', 1) if self._use_unicode: # use unicode corners horizontal_chr = xobj('-', 1) corner_chr = '\N{BOX DRAWINGS LIGHT DOWN AND HORIZONTAL}' func_height = pretty_func.height() first = True max_upper = 0 sign_height = 0 for lim in expr.limits: pretty_lower, pretty_upper = self.__print_SumProduct_Limits(lim) width = (func_height + 2) * 5 // 3 - 2 sign_lines = [horizontal_chr + corner_chr + (horizontal_chr * (width-2)) + corner_chr + horizontal_chr] for _ in range(func_height + 1): sign_lines.append(' ' + vertical_chr + (' ' * (width-2)) + vertical_chr + ' ') pretty_sign = stringPict('') pretty_sign = prettyForm(*pretty_sign.stack(*sign_lines)) max_upper = max(max_upper, pretty_upper.height()) if first: sign_height = pretty_sign.height() pretty_sign = prettyForm(*pretty_sign.above(pretty_upper)) pretty_sign = prettyForm(*pretty_sign.below(pretty_lower)) if first: pretty_func.baseline = 0 first = False height = pretty_sign.height() padding = stringPict('') padding = prettyForm(*padding.stack(*[' ']*(height - 1))) pretty_sign = prettyForm(*pretty_sign.right(padding)) pretty_func = prettyForm(*pretty_sign.right(pretty_func)) pretty_func.baseline = max_upper + sign_height//2 pretty_func.binding = prettyForm.MUL return pretty_func def __print_SumProduct_Limits(self, lim): def print_start(lhs, rhs): op = prettyForm(' ' + xsym("==") + ' ') l = self._print(lhs) r = self._print(rhs) pform = prettyForm(*stringPict.next(l, op, r)) return pform prettyUpper = self._print(lim[2]) prettyLower = print_start(lim[0], lim[1]) return prettyLower, prettyUpper def _print_Sum(self, expr): ascii_mode = not self._use_unicode def asum(hrequired, lower, upper, use_ascii): def adjust(s, wid=None, how='<^>'): if not wid or len(s) > wid: return s need = wid - len(s) if how in ('<^>', "<") or how not in list('<^>'): return s + ' '*need half = need//2 lead = ' '*half if how == ">": return " "*need + s return lead + s + ' '*(need - len(lead)) h = max(hrequired, 2) d = h//2 w = d + 1 more = hrequired % 2 lines = [] if use_ascii: lines.append("_"*(w) + ' ') lines.append(r"\%s`" % (' '*(w - 1))) for i in range(1, d): lines.append('%s\\%s' % (' '*i, ' '*(w - i))) if more: lines.append('%s)%s' % (' '*(d), ' '*(w - d))) for i in reversed(range(1, d)): lines.append('%s/%s' % (' '*i, ' '*(w - i))) lines.append("/" + "_"*(w - 1) + ',') return d, h + more, lines, more else: w = w + more d = d + more vsum = vobj('sum', 4) lines.append("_"*(w)) for i in range(0, d): lines.append('%s%s%s' % (' '*i, vsum[2], ' '*(w - i - 1))) for i in reversed(range(0, d)): lines.append('%s%s%s' % (' '*i, vsum[4], ' '*(w - i - 1))) lines.append(vsum[8]*(w)) return d, h + 2*more, lines, more f = expr.function prettyF = self._print(f) if f.is_Add: # add parens prettyF = prettyForm(*prettyF.parens()) H = prettyF.height() + 2 # \sum \sum \sum ... first = True max_upper = 0 sign_height = 0 for lim in expr.limits: prettyLower, prettyUpper = self.__print_SumProduct_Limits(lim) max_upper = max(max_upper, prettyUpper.height()) # Create sum sign based on the height of the argument d, h, slines, adjustment = asum( H, prettyLower.width(), prettyUpper.width(), ascii_mode) prettySign = stringPict('') prettySign = prettyForm(*prettySign.stack(*slines)) if first: sign_height = prettySign.height() prettySign = prettyForm(*prettySign.above(prettyUpper)) prettySign = prettyForm(*prettySign.below(prettyLower)) if first: # change F baseline so it centers on the sign prettyF.baseline -= d - (prettyF.height()//2 - prettyF.baseline) first = False # put padding to the right pad = stringPict('') pad = prettyForm(*pad.stack(*[' ']*h)) prettySign = prettyForm(*prettySign.right(pad)) # put the present prettyF to the right prettyF = prettyForm(*prettySign.right(prettyF)) # adjust baseline of ascii mode sigma with an odd height so that it is # exactly through the center ascii_adjustment = ascii_mode if not adjustment else 0 prettyF.baseline = max_upper + sign_height//2 + ascii_adjustment prettyF.binding = prettyForm.MUL return prettyF def _print_Limit(self, l): e, z, z0, dir = l.args E = self._print(e) if precedence(e) <= PRECEDENCE["Mul"]: E = prettyForm(*E.parens('(', ')')) Lim = prettyForm('lim') LimArg = self._print(z) if self._use_unicode: LimArg = prettyForm(*LimArg.right('\N{BOX DRAWINGS LIGHT HORIZONTAL}\N{RIGHTWARDS ARROW}')) else: LimArg = prettyForm(*LimArg.right('->')) LimArg = prettyForm(*LimArg.right(self._print(z0))) if str(dir) == '+-' or z0 in (S.Infinity, S.NegativeInfinity): dir = "" else: if self._use_unicode: dir = '\N{SUPERSCRIPT PLUS SIGN}' if str(dir) == "+" else '\N{SUPERSCRIPT MINUS}' LimArg = prettyForm(*LimArg.right(self._print(dir))) Lim = prettyForm(*Lim.below(LimArg)) Lim = prettyForm(*Lim.right(E), binding=prettyForm.MUL) return Lim def _print_matrix_contents(self, e): """ This method factors out what is essentially grid printing. """ M = e # matrix Ms = {} # i,j -> pretty(M[i,j]) for i in range(M.rows): for j in range(M.cols): Ms[i, j] = self._print(M[i, j]) # h- and v- spacers hsep = 2 vsep = 1 # max width for columns maxw = [-1] * M.cols for j in range(M.cols): maxw[j] = max([Ms[i, j].width() for i in range(M.rows)] or [0]) # drawing result D = None for i in range(M.rows): D_row = None for j in range(M.cols): s = Ms[i, j] # reshape s to maxw # XXX this should be generalized, and go to stringPict.reshape ? assert s.width() <= maxw[j] # hcenter it, +0.5 to the right 2 # ( it's better to align formula starts for say 0 and r ) # XXX this is not good in all cases -- maybe introduce vbaseline? wdelta = maxw[j] - s.width() wleft = wdelta // 2 wright = wdelta - wleft s = prettyForm(*s.right(' '*wright)) s = prettyForm(*s.left(' '*wleft)) # we don't need vcenter cells -- this is automatically done in # a pretty way because when their baselines are taking into # account in .right() if D_row is None: D_row = s # first box in a row continue D_row = prettyForm(*D_row.right(' '*hsep)) # h-spacer D_row = prettyForm(*D_row.right(s)) if D is None: D = D_row # first row in a picture continue # v-spacer for _ in range(vsep): D = prettyForm(*D.below(' ')) D = prettyForm(*D.below(D_row)) if D is None: D = prettyForm('') # Empty Matrix return D def _print_MatrixBase(self, e): D = self._print_matrix_contents(e) D.baseline = D.height()//2 D = prettyForm(*D.parens('[', ']')) return D def _print_TensorProduct(self, expr): # This should somehow share the code with _print_WedgeProduct: if self._use_unicode: circled_times = "\u2297" else: circled_times = ".*" return self._print_seq(expr.args, None, None, circled_times, parenthesize=lambda x: precedence_traditional(x) <= PRECEDENCE["Mul"]) def _print_WedgeProduct(self, expr): # This should somehow share the code with _print_TensorProduct: if self._use_unicode: wedge_symbol = "\u2227" else: wedge_symbol = '/\\' return self._print_seq(expr.args, None, None, wedge_symbol, parenthesize=lambda x: precedence_traditional(x) <= PRECEDENCE["Mul"]) def _print_Trace(self, e): D = self._print(e.arg) D = prettyForm(*D.parens('(',')')) D.baseline = D.height()//2 D = prettyForm(*D.left('\n'*(0) + 'tr')) return D def _print_MatrixElement(self, expr): from sympy.matrices import MatrixSymbol if (isinstance(expr.parent, MatrixSymbol) and expr.i.is_number and expr.j.is_number): return self._print( Symbol(expr.parent.name + '_%d%d' % (expr.i, expr.j))) else: prettyFunc = self._print(expr.parent) prettyFunc = prettyForm(*prettyFunc.parens()) prettyIndices = self._print_seq((expr.i, expr.j), delimiter=', ' ).parens(left='[', right=']')[0] pform = prettyForm(binding=prettyForm.FUNC, *stringPict.next(prettyFunc, prettyIndices)) # store pform parts so it can be reassembled e.g. when powered pform.prettyFunc = prettyFunc pform.prettyArgs = prettyIndices return pform def _print_MatrixSlice(self, m): # XXX works only for applied functions from sympy.matrices import MatrixSymbol prettyFunc = self._print(m.parent) if not isinstance(m.parent, MatrixSymbol): prettyFunc = prettyForm(*prettyFunc.parens()) def ppslice(x, dim): x = list(x) if x[2] == 1: del x[2] if x[0] == 0: x[0] = '' if x[1] == dim: x[1] = '' return prettyForm(*self._print_seq(x, delimiter=':')) prettyArgs = self._print_seq((ppslice(m.rowslice, m.parent.rows), ppslice(m.colslice, m.parent.cols)), delimiter=', ').parens(left='[', right=']')[0] pform = prettyForm( binding=prettyForm.FUNC, *stringPict.next(prettyFunc, prettyArgs)) # store pform parts so it can be reassembled e.g. when powered pform.prettyFunc = prettyFunc pform.prettyArgs = prettyArgs return pform def _print_Transpose(self, expr): pform = self._print(expr.arg) from sympy.matrices import MatrixSymbol if not isinstance(expr.arg, MatrixSymbol) and expr.arg.is_MatrixExpr: pform = prettyForm(*pform.parens()) pform = pform**(prettyForm('T')) return pform def _print_Adjoint(self, expr): pform = self._print(expr.arg) if self._use_unicode: dag = prettyForm('\N{DAGGER}') else: dag = prettyForm('+') from sympy.matrices import MatrixSymbol if not isinstance(expr.arg, MatrixSymbol) and expr.arg.is_MatrixExpr: pform = prettyForm(*pform.parens()) pform = pform**dag return pform def _print_BlockMatrix(self, B): if B.blocks.shape == (1, 1): return self._print(B.blocks[0, 0]) return self._print(B.blocks) def _print_MatAdd(self, expr): s = None for item in expr.args: pform = self._print(item) if s is None: s = pform # First element else: coeff = item.as_coeff_mmul()[0] if S(coeff).could_extract_minus_sign(): s = prettyForm(*stringPict.next(s, ' ')) pform = self._print(item) else: s = prettyForm(*stringPict.next(s, ' + ')) s = prettyForm(*stringPict.next(s, pform)) return s def _print_MatMul(self, expr): args = list(expr.args) from sympy.matrices.expressions.hadamard import HadamardProduct from sympy.matrices.expressions.kronecker import KroneckerProduct from sympy.matrices.expressions.matadd import MatAdd for i, a in enumerate(args): if (isinstance(a, (Add, MatAdd, HadamardProduct, KroneckerProduct)) and len(expr.args) > 1): args[i] = prettyForm(*self._print(a).parens()) else: args[i] = self._print(a) return prettyForm.__mul__(*args) def _print_Identity(self, expr): if self._use_unicode: return prettyForm('\N{MATHEMATICAL DOUBLE-STRUCK CAPITAL I}') else: return prettyForm('I') def _print_ZeroMatrix(self, expr): if self._use_unicode: return prettyForm('\N{MATHEMATICAL DOUBLE-STRUCK DIGIT ZERO}') else: return prettyForm('0') def _print_OneMatrix(self, expr): if self._use_unicode: return prettyForm('\N{MATHEMATICAL DOUBLE-STRUCK DIGIT ONE}') else: return prettyForm('1') def _print_DotProduct(self, expr): args = list(expr.args) for i, a in enumerate(args): args[i] = self._print(a) return prettyForm.__mul__(*args) def _print_MatPow(self, expr): pform = self._print(expr.base) from sympy.matrices import MatrixSymbol if not isinstance(expr.base, MatrixSymbol): pform = prettyForm(*pform.parens()) pform = pform**(self._print(expr.exp)) return pform def _print_HadamardProduct(self, expr): from sympy.matrices.expressions.hadamard import HadamardProduct from sympy.matrices.expressions.matadd import MatAdd from sympy.matrices.expressions.matmul import MatMul if self._use_unicode: delim = pretty_atom('Ring') else: delim = '.*' return self._print_seq(expr.args, None, None, delim, parenthesize=lambda x: isinstance(x, (MatAdd, MatMul, HadamardProduct))) def _print_HadamardPower(self, expr): # from sympy import MatAdd, MatMul if self._use_unicode: circ = pretty_atom('Ring') else: circ = self._print('.') pretty_base = self._print(expr.base) pretty_exp = self._print(expr.exp) if precedence(expr.exp) < PRECEDENCE["Mul"]: pretty_exp = prettyForm(*pretty_exp.parens()) pretty_circ_exp = prettyForm( binding=prettyForm.LINE, *stringPict.next(circ, pretty_exp) ) return pretty_base**pretty_circ_exp def _print_KroneckerProduct(self, expr): from sympy.matrices.expressions.matadd import MatAdd from sympy.matrices.expressions.matmul import MatMul if self._use_unicode: delim = ' \N{N-ARY CIRCLED TIMES OPERATOR} ' else: delim = ' x ' return self._print_seq(expr.args, None, None, delim, parenthesize=lambda x: isinstance(x, (MatAdd, MatMul))) def _print_FunctionMatrix(self, X): D = self._print(X.lamda.expr) D = prettyForm(*D.parens('[', ']')) return D def _print_TransferFunction(self, expr): if not expr.num == 1: num, den = expr.num, expr.den res = Mul(num, Pow(den, -1, evaluate=False), evaluate=False) return self._print_Mul(res) else: return self._print(1)/self._print(expr.den) def _print_Series(self, expr): args = list(expr.args) for i, a in enumerate(expr.args): args[i] = prettyForm(*self._print(a).parens()) return prettyForm.__mul__(*args) def _print_MIMOSeries(self, expr): from sympy.physics.control.lti import MIMOParallel args = list(expr.args) pretty_args = [] for i, a in enumerate(reversed(args)): if (isinstance(a, MIMOParallel) and len(expr.args) > 1): expression = self._print(a) expression.baseline = expression.height()//2 pretty_args.append(prettyForm(*expression.parens())) else: expression = self._print(a) expression.baseline = expression.height()//2 pretty_args.append(expression) return prettyForm.__mul__(*pretty_args) def _print_Parallel(self, expr): s = None for item in expr.args: pform = self._print(item) if s is None: s = pform # First element else: s = prettyForm(*stringPict.next(s)) s.baseline = s.height()//2 s = prettyForm(*stringPict.next(s, ' + ')) s = prettyForm(*stringPict.next(s, pform)) return s def _print_MIMOParallel(self, expr): from sympy.physics.control.lti import TransferFunctionMatrix s = None for item in expr.args: pform = self._print(item) if s is None: s = pform # First element else: s = prettyForm(*stringPict.next(s)) s.baseline = s.height()//2 s = prettyForm(*stringPict.next(s, ' + ')) if isinstance(item, TransferFunctionMatrix): s.baseline = s.height() - 1 s = prettyForm(*stringPict.next(s, pform)) # s.baseline = s.height()//2 return s def _print_Feedback(self, expr): from sympy.physics.control import TransferFunction, Series num, tf = expr.sys1, TransferFunction(1, 1, expr.var) num_arg_list = list(num.args) if isinstance(num, Series) else [num] den_arg_list = list(expr.sys2.args) if \ isinstance(expr.sys2, Series) else [expr.sys2] if isinstance(num, Series) and isinstance(expr.sys2, Series): den = Series(*num_arg_list, *den_arg_list) elif isinstance(num, Series) and isinstance(expr.sys2, TransferFunction): if expr.sys2 == tf: den = Series(*num_arg_list) else: den = Series(*num_arg_list, expr.sys2) elif isinstance(num, TransferFunction) and isinstance(expr.sys2, Series): if num == tf: den = Series(*den_arg_list) else: den = Series(num, *den_arg_list) else: if num == tf: den = Series(*den_arg_list) elif expr.sys2 == tf: den = Series(*num_arg_list) else: den = Series(*num_arg_list, *den_arg_list) denom = prettyForm(*stringPict.next(self._print(tf))) denom.baseline = denom.height()//2 denom = prettyForm(*stringPict.next(denom, ' + ')) if expr.sign == -1 \ else prettyForm(*stringPict.next(denom, ' - ')) denom = prettyForm(*stringPict.next(denom, self._print(den))) return self._print(num)/denom def _print_MIMOFeedback(self, expr): from sympy.physics.control import MIMOSeries, TransferFunctionMatrix inv_mat = self._print(MIMOSeries(expr.sys2, expr.sys1)) plant = self._print(expr.sys1) _feedback = prettyForm(*stringPict.next(inv_mat)) _feedback = prettyForm(*stringPict.right("I + ", _feedback)) if expr.sign == -1 \ else prettyForm(*stringPict.right("I - ", _feedback)) _feedback = prettyForm(*stringPict.parens(_feedback)) _feedback.baseline = 0 _feedback = prettyForm(*stringPict.right(_feedback, '-1 ')) _feedback.baseline = _feedback.height()//2 _feedback = prettyForm.__mul__(_feedback, prettyForm(" ")) if isinstance(expr.sys1, TransferFunctionMatrix): _feedback.baseline = _feedback.height() - 1 _feedback = prettyForm(*stringPict.next(_feedback, plant)) return _feedback def _print_TransferFunctionMatrix(self, expr): mat = self._print(expr._expr_mat) mat.baseline = mat.height() - 1 subscript = greek_unicode['tau'] if self._use_unicode else r'{t}' mat = prettyForm(*mat.right(subscript)) return mat def _print_BasisDependent(self, expr): from sympy.vector import Vector if not self._use_unicode: raise NotImplementedError("ASCII pretty printing of BasisDependent is not implemented") if expr == expr.zero: return prettyForm(expr.zero._pretty_form) o1 = [] vectstrs = [] if isinstance(expr, Vector): items = expr.separate().items() else: items = [(0, expr)] for system, vect in items: inneritems = list(vect.components.items()) inneritems.sort(key = lambda x: x[0].__str__()) for k, v in inneritems: #if the coef of the basis vector is 1 #we skip the 1 if v == 1: o1.append("" + k._pretty_form) #Same for -1 elif v == -1: o1.append("(-1) " + k._pretty_form) #For a general expr else: #We always wrap the measure numbers in #parentheses arg_str = self._print( v).parens()[0] o1.append(arg_str + ' ' + k._pretty_form) vectstrs.append(k._pretty_form) #outstr = u("").join(o1) if o1[0].startswith(" + "): o1[0] = o1[0][3:] elif o1[0].startswith(" "): o1[0] = o1[0][1:] #Fixing the newlines lengths = [] strs = [''] flag = [] for i, partstr in enumerate(o1): flag.append(0) # XXX: What is this hack? if '\n' in partstr: tempstr = partstr tempstr = tempstr.replace(vectstrs[i], '') if '\N{RIGHT PARENTHESIS EXTENSION}' in tempstr: # If scalar is a fraction for paren in range(len(tempstr)): flag[i] = 1 if tempstr[paren] == '\N{RIGHT PARENTHESIS EXTENSION}' and tempstr[paren + 1] == '\n': # We want to place the vector string after all the right parentheses, because # otherwise, the vector will be in the middle of the string tempstr = tempstr[:paren] + '\N{RIGHT PARENTHESIS EXTENSION}'\ + ' ' + vectstrs[i] + tempstr[paren + 1:] break elif '\N{RIGHT PARENTHESIS LOWER HOOK}' in tempstr: # We want to place the vector string after all the right parentheses, because # otherwise, the vector will be in the middle of the string. For this reason, # we insert the vector string at the rightmost index. index = tempstr.rfind('\N{RIGHT PARENTHESIS LOWER HOOK}') if index != -1: # then this character was found in this string flag[i] = 1 tempstr = tempstr[:index] + '\N{RIGHT PARENTHESIS LOWER HOOK}'\ + ' ' + vectstrs[i] + tempstr[index + 1:] o1[i] = tempstr o1 = [x.split('\n') for x in o1] n_newlines = max([len(x) for x in o1]) # Width of part in its pretty form if 1 in flag: # If there was a fractional scalar for i, parts in enumerate(o1): if len(parts) == 1: # If part has no newline parts.insert(0, ' ' * (len(parts[0]))) flag[i] = 1 for i, parts in enumerate(o1): lengths.append(len(parts[flag[i]])) for j in range(n_newlines): if j+1 <= len(parts): if j >= len(strs): strs.append(' ' * (sum(lengths[:-1]) + 3*(len(lengths)-1))) if j == flag[i]: strs[flag[i]] += parts[flag[i]] + ' + ' else: strs[j] += parts[j] + ' '*(lengths[-1] - len(parts[j])+ 3) else: if j >= len(strs): strs.append(' ' * (sum(lengths[:-1]) + 3*(len(lengths)-1))) strs[j] += ' '*(lengths[-1]+3) return prettyForm('\n'.join([s[:-3] for s in strs])) def _print_NDimArray(self, expr): from sympy.matrices.immutable import ImmutableMatrix if expr.rank() == 0: return self._print(expr[()]) level_str = [[]] + [[] for i in range(expr.rank())] shape_ranges = [list(range(i)) for i in expr.shape] # leave eventual matrix elements unflattened mat = lambda x: ImmutableMatrix(x, evaluate=False) for outer_i in itertools.product(*shape_ranges): level_str[-1].append(expr[outer_i]) even = True for back_outer_i in range(expr.rank()-1, -1, -1): if len(level_str[back_outer_i+1]) < expr.shape[back_outer_i]: break if even: level_str[back_outer_i].append(level_str[back_outer_i+1]) else: level_str[back_outer_i].append(mat( level_str[back_outer_i+1])) if len(level_str[back_outer_i + 1]) == 1: level_str[back_outer_i][-1] = mat( [[level_str[back_outer_i][-1]]]) even = not even level_str[back_outer_i+1] = [] out_expr = level_str[0][0] if expr.rank() % 2 == 1: out_expr = mat([out_expr]) return self._print(out_expr) def _printer_tensor_indices(self, name, indices, index_map={}): center = stringPict(name) top = stringPict(" "*center.width()) bot = stringPict(" "*center.width()) last_valence = None prev_map = None for i, index in enumerate(indices): indpic = self._print(index.args[0]) if ((index in index_map) or prev_map) and last_valence == index.is_up: if index.is_up: top = prettyForm(*stringPict.next(top, ",")) else: bot = prettyForm(*stringPict.next(bot, ",")) if index in index_map: indpic = prettyForm(*stringPict.next(indpic, "=")) indpic = prettyForm(*stringPict.next(indpic, self._print(index_map[index]))) prev_map = True else: prev_map = False if index.is_up: top = stringPict(*top.right(indpic)) center = stringPict(*center.right(" "*indpic.width())) bot = stringPict(*bot.right(" "*indpic.width())) else: bot = stringPict(*bot.right(indpic)) center = stringPict(*center.right(" "*indpic.width())) top = stringPict(*top.right(" "*indpic.width())) last_valence = index.is_up pict = prettyForm(*center.above(top)) pict = prettyForm(*pict.below(bot)) return pict def _print_Tensor(self, expr): name = expr.args[0].name indices = expr.get_indices() return self._printer_tensor_indices(name, indices) def _print_TensorElement(self, expr): name = expr.expr.args[0].name indices = expr.expr.get_indices() index_map = expr.index_map return self._printer_tensor_indices(name, indices, index_map) def _print_TensMul(self, expr): sign, args = expr._get_args_for_traditional_printer() args = [ prettyForm(*self._print(i).parens()) if precedence_traditional(i) < PRECEDENCE["Mul"] else self._print(i) for i in args ] pform = prettyForm.__mul__(*args) if sign: return prettyForm(*pform.left(sign)) else: return pform def _print_TensAdd(self, expr): args = [ prettyForm(*self._print(i).parens()) if precedence_traditional(i) < PRECEDENCE["Mul"] else self._print(i) for i in expr.args ] return prettyForm.__add__(*args) def _print_TensorIndex(self, expr): sym = expr.args[0] if not expr.is_up: sym = -sym return self._print(sym) def _print_PartialDerivative(self, deriv): if self._use_unicode: deriv_symbol = U('PARTIAL DIFFERENTIAL') else: deriv_symbol = r'd' x = None for variable in reversed(deriv.variables): s = self._print(variable) ds = prettyForm(*s.left(deriv_symbol)) if x is None: x = ds else: x = prettyForm(*x.right(' ')) x = prettyForm(*x.right(ds)) f = prettyForm( binding=prettyForm.FUNC, *self._print(deriv.expr).parens()) pform = prettyForm(deriv_symbol) if len(deriv.variables) > 1: pform = pform**self._print(len(deriv.variables)) pform = prettyForm(*pform.below(stringPict.LINE, x)) pform.baseline = pform.baseline + 1 pform = prettyForm(*stringPict.next(pform, f)) pform.binding = prettyForm.MUL return pform def _print_Piecewise(self, pexpr): P = {} for n, ec in enumerate(pexpr.args): P[n, 0] = self._print(ec.expr) if ec.cond == True: P[n, 1] = prettyForm('otherwise') else: P[n, 1] = prettyForm( *prettyForm('for ').right(self._print(ec.cond))) hsep = 2 vsep = 1 len_args = len(pexpr.args) # max widths maxw = [max([P[i, j].width() for i in range(len_args)]) for j in range(2)] # FIXME: Refactor this code and matrix into some tabular environment. # drawing result D = None for i in range(len_args): D_row = None for j in range(2): p = P[i, j] assert p.width() <= maxw[j] wdelta = maxw[j] - p.width() wleft = wdelta // 2 wright = wdelta - wleft p = prettyForm(*p.right(' '*wright)) p = prettyForm(*p.left(' '*wleft)) if D_row is None: D_row = p continue D_row = prettyForm(*D_row.right(' '*hsep)) # h-spacer D_row = prettyForm(*D_row.right(p)) if D is None: D = D_row # first row in a picture continue # v-spacer for _ in range(vsep): D = prettyForm(*D.below(' ')) D = prettyForm(*D.below(D_row)) D = prettyForm(*D.parens('{', '')) D.baseline = D.height()//2 D.binding = prettyForm.OPEN return D def _print_ITE(self, ite): from sympy.functions.elementary.piecewise import Piecewise return self._print(ite.rewrite(Piecewise)) def _hprint_vec(self, v): D = None for a in v: p = a if D is None: D = p else: D = prettyForm(*D.right(', ')) D = prettyForm(*D.right(p)) if D is None: D = stringPict(' ') return D def _hprint_vseparator(self, p1, p2, left=None, right=None, delimiter='', ifascii_nougly=False): if ifascii_nougly and not self._use_unicode: return self._print_seq((p1, '|', p2), left=left, right=right, delimiter=delimiter, ifascii_nougly=True) tmp = self._print_seq((p1, p2,), left=left, right=right, delimiter=delimiter) sep = stringPict(vobj('|', tmp.height()), baseline=tmp.baseline) return self._print_seq((p1, sep, p2), left=left, right=right, delimiter=delimiter) def _print_hyper(self, e): # FIXME refactor Matrix, Piecewise, and this into a tabular environment ap = [self._print(a) for a in e.ap] bq = [self._print(b) for b in e.bq] P = self._print(e.argument) P.baseline = P.height()//2 # Drawing result - first create the ap, bq vectors D = None for v in [ap, bq]: D_row = self._hprint_vec(v) if D is None: D = D_row # first row in a picture else: D = prettyForm(*D.below(' ')) D = prettyForm(*D.below(D_row)) # make sure that the argument `z' is centred vertically D.baseline = D.height()//2 # insert horizontal separator P = prettyForm(*P.left(' ')) D = prettyForm(*D.right(' ')) # insert separating `|` D = self._hprint_vseparator(D, P) # add parens D = prettyForm(*D.parens('(', ')')) # create the F symbol above = D.height()//2 - 1 below = D.height() - above - 1 sz, t, b, add, img = annotated('F') F = prettyForm('\n' * (above - t) + img + '\n' * (below - b), baseline=above + sz) add = (sz + 1)//2 F = prettyForm(*F.left(self._print(len(e.ap)))) F = prettyForm(*F.right(self._print(len(e.bq)))) F.baseline = above + add D = prettyForm(*F.right(' ', D)) return D def _print_meijerg(self, e): # FIXME refactor Matrix, Piecewise, and this into a tabular environment v = {} v[(0, 0)] = [self._print(a) for a in e.an] v[(0, 1)] = [self._print(a) for a in e.aother] v[(1, 0)] = [self._print(b) for b in e.bm] v[(1, 1)] = [self._print(b) for b in e.bother] P = self._print(e.argument) P.baseline = P.height()//2 vp = {} for idx in v: vp[idx] = self._hprint_vec(v[idx]) for i in range(2): maxw = max(vp[(0, i)].width(), vp[(1, i)].width()) for j in range(2): s = vp[(j, i)] left = (maxw - s.width()) // 2 right = maxw - left - s.width() s = prettyForm(*s.left(' ' * left)) s = prettyForm(*s.right(' ' * right)) vp[(j, i)] = s D1 = prettyForm(*vp[(0, 0)].right(' ', vp[(0, 1)])) D1 = prettyForm(*D1.below(' ')) D2 = prettyForm(*vp[(1, 0)].right(' ', vp[(1, 1)])) D = prettyForm(*D1.below(D2)) # make sure that the argument `z' is centred vertically D.baseline = D.height()//2 # insert horizontal separator P = prettyForm(*P.left(' ')) D = prettyForm(*D.right(' ')) # insert separating `|` D = self._hprint_vseparator(D, P) # add parens D = prettyForm(*D.parens('(', ')')) # create the G symbol above = D.height()//2 - 1 below = D.height() - above - 1 sz, t, b, add, img = annotated('G') F = prettyForm('\n' * (above - t) + img + '\n' * (below - b), baseline=above + sz) pp = self._print(len(e.ap)) pq = self._print(len(e.bq)) pm = self._print(len(e.bm)) pn = self._print(len(e.an)) def adjust(p1, p2): diff = p1.width() - p2.width() if diff == 0: return p1, p2 elif diff > 0: return p1, prettyForm(*p2.left(' '*diff)) else: return prettyForm(*p1.left(' '*-diff)), p2 pp, pm = adjust(pp, pm) pq, pn = adjust(pq, pn) pu = prettyForm(*pm.right(', ', pn)) pl = prettyForm(*pp.right(', ', pq)) ht = F.baseline - above - 2 if ht > 0: pu = prettyForm(*pu.below('\n'*ht)) p = prettyForm(*pu.below(pl)) F.baseline = above F = prettyForm(*F.right(p)) F.baseline = above + add D = prettyForm(*F.right(' ', D)) return D def _print_ExpBase(self, e): # TODO should exp_polar be printed differently? # what about exp_polar(0), exp_polar(1)? base = prettyForm(pretty_atom('Exp1', 'e')) return base ** self._print(e.args[0]) def _print_Exp1(self, e): return prettyForm(pretty_atom('Exp1', 'e')) def _print_Function(self, e, sort=False, func_name=None, left='(', right=')'): # optional argument func_name for supplying custom names # XXX works only for applied functions return self._helper_print_function(e.func, e.args, sort=sort, func_name=func_name, left=left, right=right) def _print_mathieuc(self, e): return self._print_Function(e, func_name='C') def _print_mathieus(self, e): return self._print_Function(e, func_name='S') def _print_mathieucprime(self, e): return self._print_Function(e, func_name="C'") def _print_mathieusprime(self, e): return self._print_Function(e, func_name="S'") def _helper_print_function(self, func, args, sort=False, func_name=None, delimiter=', ', elementwise=False, left='(', right=')'): if sort: args = sorted(args, key=default_sort_key) if not func_name and hasattr(func, "__name__"): func_name = func.__name__ if func_name: prettyFunc = self._print(Symbol(func_name)) else: prettyFunc = prettyForm(*self._print(func).parens()) if elementwise: if self._use_unicode: circ = pretty_atom('Modifier Letter Low Ring') else: circ = '.' circ = self._print(circ) prettyFunc = prettyForm( binding=prettyForm.LINE, *stringPict.next(prettyFunc, circ) ) prettyArgs = prettyForm(*self._print_seq(args, delimiter=delimiter).parens( left=left, right=right)) pform = prettyForm( binding=prettyForm.FUNC, *stringPict.next(prettyFunc, prettyArgs)) # store pform parts so it can be reassembled e.g. when powered pform.prettyFunc = prettyFunc pform.prettyArgs = prettyArgs return pform def _print_ElementwiseApplyFunction(self, e): func = e.function arg = e.expr args = [arg] return self._helper_print_function(func, args, delimiter="", elementwise=True) @property def _special_function_classes(self): from sympy.functions.special.tensor_functions import KroneckerDelta from sympy.functions.special.gamma_functions import gamma, lowergamma from sympy.functions.special.zeta_functions import lerchphi from sympy.functions.special.beta_functions import beta from sympy.functions.special.delta_functions import DiracDelta from sympy.functions.special.error_functions import Chi return {KroneckerDelta: [greek_unicode['delta'], 'delta'], gamma: [greek_unicode['Gamma'], 'Gamma'], lerchphi: [greek_unicode['Phi'], 'lerchphi'], lowergamma: [greek_unicode['gamma'], 'gamma'], beta: [greek_unicode['Beta'], 'B'], DiracDelta: [greek_unicode['delta'], 'delta'], Chi: ['Chi', 'Chi']} def _print_FunctionClass(self, expr): for cls in self._special_function_classes: if issubclass(expr, cls) and expr.__name__ == cls.__name__: if self._use_unicode: return prettyForm(self._special_function_classes[cls][0]) else: return prettyForm(self._special_function_classes[cls][1]) func_name = expr.__name__ return prettyForm(pretty_symbol(func_name)) def _print_GeometryEntity(self, expr): # GeometryEntity is based on Tuple but should not print like a Tuple return self.emptyPrinter(expr) def _print_lerchphi(self, e): func_name = greek_unicode['Phi'] if self._use_unicode else 'lerchphi' return self._print_Function(e, func_name=func_name) def _print_dirichlet_eta(self, e): func_name = greek_unicode['eta'] if self._use_unicode else 'dirichlet_eta' return self._print_Function(e, func_name=func_name) def _print_Heaviside(self, e): func_name = greek_unicode['theta'] if self._use_unicode else 'Heaviside' if e.args[1]==1/2: pform = prettyForm(*self._print(e.args[0]).parens()) pform = prettyForm(*pform.left(func_name)) return pform else: return self._print_Function(e, func_name=func_name) def _print_fresnels(self, e): return self._print_Function(e, func_name="S") def _print_fresnelc(self, e): return self._print_Function(e, func_name="C") def _print_airyai(self, e): return self._print_Function(e, func_name="Ai") def _print_airybi(self, e): return self._print_Function(e, func_name="Bi") def _print_airyaiprime(self, e): return self._print_Function(e, func_name="Ai'") def _print_airybiprime(self, e): return self._print_Function(e, func_name="Bi'") def _print_LambertW(self, e): return self._print_Function(e, func_name="W") def _print_Covariance(self, e): return self._print_Function(e, func_name="Cov") def _print_Variance(self, e): return self._print_Function(e, func_name="Var") def _print_Probability(self, e): return self._print_Function(e, func_name="P") def _print_Expectation(self, e): return self._print_Function(e, func_name="E", left='[', right=']') def _print_Lambda(self, e): expr = e.expr sig = e.signature if self._use_unicode: arrow = " \N{RIGHTWARDS ARROW FROM BAR} " else: arrow = " -> " if len(sig) == 1 and sig[0].is_symbol: sig = sig[0] var_form = self._print(sig) return prettyForm(*stringPict.next(var_form, arrow, self._print(expr)), binding=8) def _print_Order(self, expr): pform = self._print(expr.expr) if (expr.point and any(p != S.Zero for p in expr.point)) or \ len(expr.variables) > 1: pform = prettyForm(*pform.right("; ")) if len(expr.variables) > 1: pform = prettyForm(*pform.right(self._print(expr.variables))) elif len(expr.variables): pform = prettyForm(*pform.right(self._print(expr.variables[0]))) if self._use_unicode: pform = prettyForm(*pform.right(" \N{RIGHTWARDS ARROW} ")) else: pform = prettyForm(*pform.right(" -> ")) if len(expr.point) > 1: pform = prettyForm(*pform.right(self._print(expr.point))) else: pform = prettyForm(*pform.right(self._print(expr.point[0]))) pform = prettyForm(*pform.parens()) pform = prettyForm(*pform.left("O")) return pform def _print_SingularityFunction(self, e): if self._use_unicode: shift = self._print(e.args[0]-e.args[1]) n = self._print(e.args[2]) base = prettyForm("<") base = prettyForm(*base.right(shift)) base = prettyForm(*base.right(">")) pform = base**n return pform else: n = self._print(e.args[2]) shift = self._print(e.args[0]-e.args[1]) base = self._print_seq(shift, "<", ">", ' ') return base**n def _print_beta(self, e): func_name = greek_unicode['Beta'] if self._use_unicode else 'B' return self._print_Function(e, func_name=func_name) def _print_betainc(self, e): func_name = "B'" return self._print_Function(e, func_name=func_name) def _print_betainc_regularized(self, e): func_name = 'I' return self._print_Function(e, func_name=func_name) def _print_gamma(self, e): func_name = greek_unicode['Gamma'] if self._use_unicode else 'Gamma' return self._print_Function(e, func_name=func_name) def _print_uppergamma(self, e): func_name = greek_unicode['Gamma'] if self._use_unicode else 'Gamma' return self._print_Function(e, func_name=func_name) def _print_lowergamma(self, e): func_name = greek_unicode['gamma'] if self._use_unicode else 'lowergamma' return self._print_Function(e, func_name=func_name) def _print_DiracDelta(self, e): if self._use_unicode: if len(e.args) == 2: a = prettyForm(greek_unicode['delta']) b = self._print(e.args[1]) b = prettyForm(*b.parens()) c = self._print(e.args[0]) c = prettyForm(*c.parens()) pform = a**b pform = prettyForm(*pform.right(' ')) pform = prettyForm(*pform.right(c)) return pform pform = self._print(e.args[0]) pform = prettyForm(*pform.parens()) pform = prettyForm(*pform.left(greek_unicode['delta'])) return pform else: return self._print_Function(e) def _print_expint(self, e): if e.args[0].is_Integer and self._use_unicode: return self._print_Function(Function('E_%s' % e.args[0])(e.args[1])) return self._print_Function(e) def _print_Chi(self, e): # This needs a special case since otherwise it comes out as greek # letter chi... prettyFunc = prettyForm("Chi") prettyArgs = prettyForm(*self._print_seq(e.args).parens()) pform = prettyForm( binding=prettyForm.FUNC, *stringPict.next(prettyFunc, prettyArgs)) # store pform parts so it can be reassembled e.g. when powered pform.prettyFunc = prettyFunc pform.prettyArgs = prettyArgs return pform def _print_elliptic_e(self, e): pforma0 = self._print(e.args[0]) if len(e.args) == 1: pform = pforma0 else: pforma1 = self._print(e.args[1]) pform = self._hprint_vseparator(pforma0, pforma1) pform = prettyForm(*pform.parens()) pform = prettyForm(*pform.left('E')) return pform def _print_elliptic_k(self, e): pform = self._print(e.args[0]) pform = prettyForm(*pform.parens()) pform = prettyForm(*pform.left('K')) return pform def _print_elliptic_f(self, e): pforma0 = self._print(e.args[0]) pforma1 = self._print(e.args[1]) pform = self._hprint_vseparator(pforma0, pforma1) pform = prettyForm(*pform.parens()) pform = prettyForm(*pform.left('F')) return pform def _print_elliptic_pi(self, e): name = greek_unicode['Pi'] if self._use_unicode else 'Pi' pforma0 = self._print(e.args[0]) pforma1 = self._print(e.args[1]) if len(e.args) == 2: pform = self._hprint_vseparator(pforma0, pforma1) else: pforma2 = self._print(e.args[2]) pforma = self._hprint_vseparator(pforma1, pforma2, ifascii_nougly=False) pforma = prettyForm(*pforma.left('; ')) pform = prettyForm(*pforma.left(pforma0)) pform = prettyForm(*pform.parens()) pform = prettyForm(*pform.left(name)) return pform def _print_GoldenRatio(self, expr): if self._use_unicode: return prettyForm(pretty_symbol('phi')) return self._print(Symbol("GoldenRatio")) def _print_EulerGamma(self, expr): if self._use_unicode: return prettyForm(pretty_symbol('gamma')) return self._print(Symbol("EulerGamma")) def _print_Catalan(self, expr): return self._print(Symbol("G")) def _print_Mod(self, expr): pform = self._print(expr.args[0]) if pform.binding > prettyForm.MUL: pform = prettyForm(*pform.parens()) pform = prettyForm(*pform.right(' mod ')) pform = prettyForm(*pform.right(self._print(expr.args[1]))) pform.binding = prettyForm.OPEN return pform def _print_Add(self, expr, order=None): terms = self._as_ordered_terms(expr, order=order) pforms, indices = [], [] def pretty_negative(pform, index): """Prepend a minus sign to a pretty form. """ #TODO: Move this code to prettyForm if index == 0: if pform.height() > 1: pform_neg = '- ' else: pform_neg = '-' else: pform_neg = ' - ' if (pform.binding > prettyForm.NEG or pform.binding == prettyForm.ADD): p = stringPict(*pform.parens()) else: p = pform p = stringPict.next(pform_neg, p) # Lower the binding to NEG, even if it was higher. Otherwise, it # will print as a + ( - (b)), instead of a - (b). return prettyForm(binding=prettyForm.NEG, *p) for i, term in enumerate(terms): if term.is_Mul and term.could_extract_minus_sign(): coeff, other = term.as_coeff_mul(rational=False) if coeff == -1: negterm = Mul(*other, evaluate=False) else: negterm = Mul(-coeff, *other, evaluate=False) pform = self._print(negterm) pforms.append(pretty_negative(pform, i)) elif term.is_Rational and term.q > 1: pforms.append(None) indices.append(i) elif term.is_Number and term < 0: pform = self._print(-term) pforms.append(pretty_negative(pform, i)) elif term.is_Relational: pforms.append(prettyForm(*self._print(term).parens())) else: pforms.append(self._print(term)) if indices: large = True for pform in pforms: if pform is not None and pform.height() > 1: break else: large = False for i in indices: term, negative = terms[i], False if term < 0: term, negative = -term, True if large: pform = prettyForm(str(term.p))/prettyForm(str(term.q)) else: pform = self._print(term) if negative: pform = pretty_negative(pform, i) pforms[i] = pform return prettyForm.__add__(*pforms) def _print_Mul(self, product): from sympy.physics.units import Quantity # Check for unevaluated Mul. In this case we need to make sure the # identities are visible, multiple Rational factors are not combined # etc so we display in a straight-forward form that fully preserves all # args and their order. args = product.args if args[0] is S.One or any(isinstance(arg, Number) for arg in args[1:]): strargs = list(map(self._print, args)) # XXX: This is a hack to work around the fact that # prettyForm.__mul__ absorbs a leading -1 in the args. Probably it # would be better to fix this in prettyForm.__mul__ instead. negone = strargs[0] == '-1' if negone: strargs[0] = prettyForm('1', 0, 0) obj = prettyForm.__mul__(*strargs) if negone: obj = prettyForm('-' + obj.s, obj.baseline, obj.binding) return obj a = [] # items in the numerator b = [] # items that are in the denominator (if any) if self.order not in ('old', 'none'): args = product.as_ordered_factors() else: args = list(product.args) # If quantities are present append them at the back args = sorted(args, key=lambda x: isinstance(x, Quantity) or (isinstance(x, Pow) and isinstance(x.base, Quantity))) # Gather terms for numerator/denominator for item in args: if item.is_commutative and item.is_Pow and item.exp.is_Rational and item.exp.is_negative: if item.exp != -1: b.append(Pow(item.base, -item.exp, evaluate=False)) else: b.append(Pow(item.base, -item.exp)) elif item.is_Rational and item is not S.Infinity: if item.p != 1: a.append( Rational(item.p) ) if item.q != 1: b.append( Rational(item.q) ) else: a.append(item) # Convert to pretty forms. Parentheses are added by `__mul__`. a = [self._print(ai) for ai in a] b = [self._print(bi) for bi in b] # Construct a pretty form if len(b) == 0: return prettyForm.__mul__(*a) else: if len(a) == 0: a.append( self._print(S.One) ) return prettyForm.__mul__(*a)/prettyForm.__mul__(*b) # A helper function for _print_Pow to print x**(1/n) def _print_nth_root(self, base, root): bpretty = self._print(base) # In very simple cases, use a single-char root sign if (self._settings['use_unicode_sqrt_char'] and self._use_unicode and root == 2 and bpretty.height() == 1 and (bpretty.width() == 1 or (base.is_Integer and base.is_nonnegative))): return prettyForm(*bpretty.left('\N{SQUARE ROOT}')) # Construct root sign, start with the \/ shape _zZ = xobj('/', 1) rootsign = xobj('\\', 1) + _zZ # Constructing the number to put on root rpretty = self._print(root) # roots look bad if they are not a single line if rpretty.height() != 1: return self._print(base)**self._print(1/root) # If power is half, no number should appear on top of root sign exp = '' if root == 2 else str(rpretty).ljust(2) if len(exp) > 2: rootsign = ' '*(len(exp) - 2) + rootsign # Stack the exponent rootsign = stringPict(exp + '\n' + rootsign) rootsign.baseline = 0 # Diagonal: length is one less than height of base linelength = bpretty.height() - 1 diagonal = stringPict('\n'.join( ' '*(linelength - i - 1) + _zZ + ' '*i for i in range(linelength) )) # Put baseline just below lowest line: next to exp diagonal.baseline = linelength - 1 # Make the root symbol rootsign = prettyForm(*rootsign.right(diagonal)) # Det the baseline to match contents to fix the height # but if the height of bpretty is one, the rootsign must be one higher rootsign.baseline = max(1, bpretty.baseline) #build result s = prettyForm(hobj('_', 2 + bpretty.width())) s = prettyForm(*bpretty.above(s)) s = prettyForm(*s.left(rootsign)) return s def _print_Pow(self, power): from sympy.simplify.simplify import fraction b, e = power.as_base_exp() if power.is_commutative: if e is S.NegativeOne: return prettyForm("1")/self._print(b) n, d = fraction(e) if n is S.One and d.is_Atom and not e.is_Integer and (e.is_Rational or d.is_Symbol) \ and self._settings['root_notation']: return self._print_nth_root(b, d) if e.is_Rational and e < 0: return prettyForm("1")/self._print(Pow(b, -e, evaluate=False)) if b.is_Relational: return prettyForm(*self._print(b).parens()).__pow__(self._print(e)) return self._print(b)**self._print(e) def _print_UnevaluatedExpr(self, expr): return self._print(expr.args[0]) def __print_numer_denom(self, p, q): if q == 1: if p < 0: return prettyForm(str(p), binding=prettyForm.NEG) else: return prettyForm(str(p)) elif abs(p) >= 10 and abs(q) >= 10: # If more than one digit in numer and denom, print larger fraction if p < 0: return prettyForm(str(p), binding=prettyForm.NEG)/prettyForm(str(q)) # Old printing method: #pform = prettyForm(str(-p))/prettyForm(str(q)) #return prettyForm(binding=prettyForm.NEG, *pform.left('- ')) else: return prettyForm(str(p))/prettyForm(str(q)) else: return None def _print_Rational(self, expr): result = self.__print_numer_denom(expr.p, expr.q) if result is not None: return result else: return self.emptyPrinter(expr) def _print_Fraction(self, expr): result = self.__print_numer_denom(expr.numerator, expr.denominator) if result is not None: return result else: return self.emptyPrinter(expr) def _print_ProductSet(self, p): if len(p.sets) >= 1 and not has_variety(p.sets): return self._print(p.sets[0]) ** self._print(len(p.sets)) else: prod_char = "\N{MULTIPLICATION SIGN}" if self._use_unicode else 'x' return self._print_seq(p.sets, None, None, ' %s ' % prod_char, parenthesize=lambda set: set.is_Union or set.is_Intersection or set.is_ProductSet) def _print_FiniteSet(self, s): items = sorted(s.args, key=default_sort_key) return self._print_seq(items, '{', '}', ', ' ) def _print_Range(self, s): if self._use_unicode: dots = "\N{HORIZONTAL ELLIPSIS}" else: dots = '...' if s.start.is_infinite and s.stop.is_infinite: if s.step.is_positive: printset = dots, -1, 0, 1, dots else: printset = dots, 1, 0, -1, dots elif s.start.is_infinite: printset = dots, s[-1] - s.step, s[-1] elif s.stop.is_infinite: it = iter(s) printset = next(it), next(it), dots elif len(s) > 4: it = iter(s) printset = next(it), next(it), dots, s[-1] else: printset = tuple(s) return self._print_seq(printset, '{', '}', ', ' ) def _print_Interval(self, i): if i.start == i.end: return self._print_seq(i.args[:1], '{', '}') else: if i.left_open: left = '(' else: left = '[' if i.right_open: right = ')' else: right = ']' return self._print_seq(i.args[:2], left, right) def _print_AccumulationBounds(self, i): left = '<' right = '>' return self._print_seq(i.args[:2], left, right) def _print_Intersection(self, u): delimiter = ' %s ' % pretty_atom('Intersection', 'n') return self._print_seq(u.args, None, None, delimiter, parenthesize=lambda set: set.is_ProductSet or set.is_Union or set.is_Complement) def _print_Union(self, u): union_delimiter = ' %s ' % pretty_atom('Union', 'U') return self._print_seq(u.args, None, None, union_delimiter, parenthesize=lambda set: set.is_ProductSet or set.is_Intersection or set.is_Complement) def _print_SymmetricDifference(self, u): if not self._use_unicode: raise NotImplementedError("ASCII pretty printing of SymmetricDifference is not implemented") sym_delimeter = ' %s ' % pretty_atom('SymmetricDifference') return self._print_seq(u.args, None, None, sym_delimeter) def _print_Complement(self, u): delimiter = r' \ ' return self._print_seq(u.args, None, None, delimiter, parenthesize=lambda set: set.is_ProductSet or set.is_Intersection or set.is_Union) def _print_ImageSet(self, ts): if self._use_unicode: inn = "\N{SMALL ELEMENT OF}" else: inn = 'in' fun = ts.lamda sets = ts.base_sets signature = fun.signature expr = self._print(fun.expr) # TODO: the stuff to the left of the | and the stuff to the right of # the | should have independent baselines, that way something like # ImageSet(Lambda(x, 1/x**2), S.Naturals) prints the "x in N" part # centered on the right instead of aligned with the fraction bar on # the left. The same also applies to ConditionSet and ComplexRegion if len(signature) == 1: S = self._print_seq((signature[0], inn, sets[0]), delimiter=' ') return self._hprint_vseparator(expr, S, left='{', right='}', ifascii_nougly=True, delimiter=' ') else: pargs = tuple(j for var, setv in zip(signature, sets) for j in (var, ' ', inn, ' ', setv, ", ")) S = self._print_seq(pargs[:-1], delimiter='') return self._hprint_vseparator(expr, S, left='{', right='}', ifascii_nougly=True, delimiter=' ') def _print_ConditionSet(self, ts): if self._use_unicode: inn = "\N{SMALL ELEMENT OF}" # using _and because and is a keyword and it is bad practice to # overwrite them _and = "\N{LOGICAL AND}" else: inn = 'in' _and = 'and' variables = self._print_seq(Tuple(ts.sym)) as_expr = getattr(ts.condition, 'as_expr', None) if as_expr is not None: cond = self._print(ts.condition.as_expr()) else: cond = self._print(ts.condition) if self._use_unicode: cond = self._print(cond) cond = prettyForm(*cond.parens()) if ts.base_set is S.UniversalSet: return self._hprint_vseparator(variables, cond, left="{", right="}", ifascii_nougly=True, delimiter=' ') base = self._print(ts.base_set) C = self._print_seq((variables, inn, base, _and, cond), delimiter=' ') return self._hprint_vseparator(variables, C, left="{", right="}", ifascii_nougly=True, delimiter=' ') def _print_ComplexRegion(self, ts): if self._use_unicode: inn = "\N{SMALL ELEMENT OF}" else: inn = 'in' variables = self._print_seq(ts.variables) expr = self._print(ts.expr) prodsets = self._print(ts.sets) C = self._print_seq((variables, inn, prodsets), delimiter=' ') return self._hprint_vseparator(expr, C, left="{", right="}", ifascii_nougly=True, delimiter=' ') def _print_Contains(self, e): var, set = e.args if self._use_unicode: el = " \N{ELEMENT OF} " return prettyForm(*stringPict.next(self._print(var), el, self._print(set)), binding=8) else: return prettyForm(sstr(e)) def _print_FourierSeries(self, s): if s.an.formula is S.Zero and s.bn.formula is S.Zero: return self._print(s.a0) if self._use_unicode: dots = "\N{HORIZONTAL ELLIPSIS}" else: dots = '...' return self._print_Add(s.truncate()) + self._print(dots) def _print_FormalPowerSeries(self, s): return self._print_Add(s.infinite) def _print_SetExpr(self, se): pretty_set = prettyForm(*self._print(se.set).parens()) pretty_name = self._print(Symbol("SetExpr")) return prettyForm(*pretty_name.right(pretty_set)) def _print_SeqFormula(self, s): if self._use_unicode: dots = "\N{HORIZONTAL ELLIPSIS}" else: dots = '...' if len(s.start.free_symbols) > 0 or len(s.stop.free_symbols) > 0: raise NotImplementedError("Pretty printing of sequences with symbolic bound not implemented") if s.start is S.NegativeInfinity: stop = s.stop printset = (dots, s.coeff(stop - 3), s.coeff(stop - 2), s.coeff(stop - 1), s.coeff(stop)) elif s.stop is S.Infinity or s.length > 4: printset = s[:4] printset.append(dots) printset = tuple(printset) else: printset = tuple(s) return self._print_list(printset) _print_SeqPer = _print_SeqFormula _print_SeqAdd = _print_SeqFormula _print_SeqMul = _print_SeqFormula def _print_seq(self, seq, left=None, right=None, delimiter=', ', parenthesize=lambda x: False, ifascii_nougly=True): try: pforms = [] for item in seq: pform = self._print(item) if parenthesize(item): pform = prettyForm(*pform.parens()) if pforms: pforms.append(delimiter) pforms.append(pform) if not pforms: s = stringPict('') else: s = prettyForm(*stringPict.next(*pforms)) # XXX: Under the tests from #15686 the above raises: # AttributeError: 'Fake' object has no attribute 'baseline' # This is caught below but that is not the right way to # fix it. except AttributeError: s = None for item in seq: pform = self.doprint(item) if parenthesize(item): pform = prettyForm(*pform.parens()) if s is None: # first element s = pform else : s = prettyForm(*stringPict.next(s, delimiter)) s = prettyForm(*stringPict.next(s, pform)) if s is None: s = stringPict('') s = prettyForm(*s.parens(left, right, ifascii_nougly=ifascii_nougly)) return s def join(self, delimiter, args): pform = None for arg in args: if pform is None: pform = arg else: pform = prettyForm(*pform.right(delimiter)) pform = prettyForm(*pform.right(arg)) if pform is None: return prettyForm("") else: return pform def _print_list(self, l): return self._print_seq(l, '[', ']') def _print_tuple(self, t): if len(t) == 1: ptuple = prettyForm(*stringPict.next(self._print(t[0]), ',')) return prettyForm(*ptuple.parens('(', ')', ifascii_nougly=True)) else: return self._print_seq(t, '(', ')') def _print_Tuple(self, expr): return self._print_tuple(expr) def _print_dict(self, d): keys = sorted(d.keys(), key=default_sort_key) items = [] for k in keys: K = self._print(k) V = self._print(d[k]) s = prettyForm(*stringPict.next(K, ': ', V)) items.append(s) return self._print_seq(items, '{', '}') def _print_Dict(self, d): return self._print_dict(d) def _print_set(self, s): if not s: return prettyForm('set()') items = sorted(s, key=default_sort_key) pretty = self._print_seq(items) pretty = prettyForm(*pretty.parens('{', '}', ifascii_nougly=True)) return pretty def _print_frozenset(self, s): if not s: return prettyForm('frozenset()') items = sorted(s, key=default_sort_key) pretty = self._print_seq(items) pretty = prettyForm(*pretty.parens('{', '}', ifascii_nougly=True)) pretty = prettyForm(*pretty.parens('(', ')', ifascii_nougly=True)) pretty = prettyForm(*stringPict.next(type(s).__name__, pretty)) return pretty def _print_UniversalSet(self, s): if self._use_unicode: return prettyForm("\N{MATHEMATICAL DOUBLE-STRUCK CAPITAL U}") else: return prettyForm('UniversalSet') def _print_PolyRing(self, ring): return prettyForm(sstr(ring)) def _print_FracField(self, field): return prettyForm(sstr(field)) def _print_FreeGroupElement(self, elm): return prettyForm(str(elm)) def _print_PolyElement(self, poly): return prettyForm(sstr(poly)) def _print_FracElement(self, frac): return prettyForm(sstr(frac)) def _print_AlgebraicNumber(self, expr): if expr.is_aliased: return self._print(expr.as_poly().as_expr()) else: return self._print(expr.as_expr()) def _print_ComplexRootOf(self, expr): args = [self._print_Add(expr.expr, order='lex'), expr.index] pform = prettyForm(*self._print_seq(args).parens()) pform = prettyForm(*pform.left('CRootOf')) return pform def _print_RootSum(self, expr): args = [self._print_Add(expr.expr, order='lex')] if expr.fun is not S.IdentityFunction: args.append(self._print(expr.fun)) pform = prettyForm(*self._print_seq(args).parens()) pform = prettyForm(*pform.left('RootSum')) return pform def _print_FiniteField(self, expr): if self._use_unicode: form = '\N{DOUBLE-STRUCK CAPITAL Z}_%d' else: form = 'GF(%d)' return prettyForm(pretty_symbol(form % expr.mod)) def _print_IntegerRing(self, expr): if self._use_unicode: return prettyForm('\N{DOUBLE-STRUCK CAPITAL Z}') else: return prettyForm('ZZ') def _print_RationalField(self, expr): if self._use_unicode: return prettyForm('\N{DOUBLE-STRUCK CAPITAL Q}') else: return prettyForm('QQ') def _print_RealField(self, domain): if self._use_unicode: prefix = '\N{DOUBLE-STRUCK CAPITAL R}' else: prefix = 'RR' if domain.has_default_precision: return prettyForm(prefix) else: return self._print(pretty_symbol(prefix + "_" + str(domain.precision))) def _print_ComplexField(self, domain): if self._use_unicode: prefix = '\N{DOUBLE-STRUCK CAPITAL C}' else: prefix = 'CC' if domain.has_default_precision: return prettyForm(prefix) else: return self._print(pretty_symbol(prefix + "_" + str(domain.precision))) def _print_PolynomialRing(self, expr): args = list(expr.symbols) if not expr.order.is_default: order = prettyForm(*prettyForm("order=").right(self._print(expr.order))) args.append(order) pform = self._print_seq(args, '[', ']') pform = prettyForm(*pform.left(self._print(expr.domain))) return pform def _print_FractionField(self, expr): args = list(expr.symbols) if not expr.order.is_default: order = prettyForm(*prettyForm("order=").right(self._print(expr.order))) args.append(order) pform = self._print_seq(args, '(', ')') pform = prettyForm(*pform.left(self._print(expr.domain))) return pform def _print_PolynomialRingBase(self, expr): g = expr.symbols if str(expr.order) != str(expr.default_order): g = g + ("order=" + str(expr.order),) pform = self._print_seq(g, '[', ']') pform = prettyForm(*pform.left(self._print(expr.domain))) return pform def _print_GroebnerBasis(self, basis): exprs = [ self._print_Add(arg, order=basis.order) for arg in basis.exprs ] exprs = prettyForm(*self.join(", ", exprs).parens(left="[", right="]")) gens = [ self._print(gen) for gen in basis.gens ] domain = prettyForm( *prettyForm("domain=").right(self._print(basis.domain))) order = prettyForm( *prettyForm("order=").right(self._print(basis.order))) pform = self.join(", ", [exprs] + gens + [domain, order]) pform = prettyForm(*pform.parens()) pform = prettyForm(*pform.left(basis.__class__.__name__)) return pform def _print_Subs(self, e): pform = self._print(e.expr) pform = prettyForm(*pform.parens()) h = pform.height() if pform.height() > 1 else 2 rvert = stringPict(vobj('|', h), baseline=pform.baseline) pform = prettyForm(*pform.right(rvert)) b = pform.baseline pform.baseline = pform.height() - 1 pform = prettyForm(*pform.right(self._print_seq([ self._print_seq((self._print(v[0]), xsym('=='), self._print(v[1])), delimiter='') for v in zip(e.variables, e.point) ]))) pform.baseline = b return pform def _print_number_function(self, e, name): # Print name_arg[0] for one argument or name_arg[0](arg[1]) # for more than one argument pform = prettyForm(name) arg = self._print(e.args[0]) pform_arg = prettyForm(" "*arg.width()) pform_arg = prettyForm(*pform_arg.below(arg)) pform = prettyForm(*pform.right(pform_arg)) if len(e.args) == 1: return pform m, x = e.args # TODO: copy-pasted from _print_Function: can we do better? prettyFunc = pform prettyArgs = prettyForm(*self._print_seq([x]).parens()) pform = prettyForm( binding=prettyForm.FUNC, *stringPict.next(prettyFunc, prettyArgs)) pform.prettyFunc = prettyFunc pform.prettyArgs = prettyArgs return pform def _print_euler(self, e): return self._print_number_function(e, "E") def _print_catalan(self, e): return self._print_number_function(e, "C") def _print_bernoulli(self, e): return self._print_number_function(e, "B") _print_bell = _print_bernoulli def _print_lucas(self, e): return self._print_number_function(e, "L") def _print_fibonacci(self, e): return self._print_number_function(e, "F") def _print_tribonacci(self, e): return self._print_number_function(e, "T") def _print_stieltjes(self, e): if self._use_unicode: return self._print_number_function(e, '\N{GREEK SMALL LETTER GAMMA}') else: return self._print_number_function(e, "stieltjes") def _print_KroneckerDelta(self, e): pform = self._print(e.args[0]) pform = prettyForm(*pform.right(prettyForm(','))) pform = prettyForm(*pform.right(self._print(e.args[1]))) if self._use_unicode: a = stringPict(pretty_symbol('delta')) else: a = stringPict('d') b = pform top = stringPict(*b.left(' '*a.width())) bot = stringPict(*a.right(' '*b.width())) return prettyForm(binding=prettyForm.POW, *bot.below(top)) def _print_RandomDomain(self, d): if hasattr(d, 'as_boolean'): pform = self._print('Domain: ') pform = prettyForm(*pform.right(self._print(d.as_boolean()))) return pform elif hasattr(d, 'set'): pform = self._print('Domain: ') pform = prettyForm(*pform.right(self._print(d.symbols))) pform = prettyForm(*pform.right(self._print(' in '))) pform = prettyForm(*pform.right(self._print(d.set))) return pform elif hasattr(d, 'symbols'): pform = self._print('Domain on ') pform = prettyForm(*pform.right(self._print(d.symbols))) return pform else: return self._print(None) def _print_DMP(self, p): try: if p.ring is not None: # TODO incorporate order return self._print(p.ring.to_sympy(p)) except SympifyError: pass return self._print(repr(p)) def _print_DMF(self, p): return self._print_DMP(p) def _print_Object(self, object): return self._print(pretty_symbol(object.name)) def _print_Morphism(self, morphism): arrow = xsym("-->") domain = self._print(morphism.domain) codomain = self._print(morphism.codomain) tail = domain.right(arrow, codomain)[0] return prettyForm(tail) def _print_NamedMorphism(self, morphism): pretty_name = self._print(pretty_symbol(morphism.name)) pretty_morphism = self._print_Morphism(morphism) return prettyForm(pretty_name.right(":", pretty_morphism)[0]) def _print_IdentityMorphism(self, morphism): from sympy.categories import NamedMorphism return self._print_NamedMorphism( NamedMorphism(morphism.domain, morphism.codomain, "id")) def _print_CompositeMorphism(self, morphism): circle = xsym(".") # All components of the morphism have names and it is thus # possible to build the name of the composite. component_names_list = [pretty_symbol(component.name) for component in morphism.components] component_names_list.reverse() component_names = circle.join(component_names_list) + ":" pretty_name = self._print(component_names) pretty_morphism = self._print_Morphism(morphism) return prettyForm(pretty_name.right(pretty_morphism)[0]) def _print_Category(self, category): return self._print(pretty_symbol(category.name)) def _print_Diagram(self, diagram): if not diagram.premises: # This is an empty diagram. return self._print(S.EmptySet) pretty_result = self._print(diagram.premises) if diagram.conclusions: results_arrow = " %s " % xsym("==>") pretty_conclusions = self._print(diagram.conclusions)[0] pretty_result = pretty_result.right( results_arrow, pretty_conclusions) return prettyForm(pretty_result[0]) def _print_DiagramGrid(self, grid): from sympy.matrices import Matrix matrix = Matrix([[grid[i, j] if grid[i, j] else Symbol(" ") for j in range(grid.width)] for i in range(grid.height)]) return self._print_matrix_contents(matrix) def _print_FreeModuleElement(self, m): # Print as row vector for convenience, for now. return self._print_seq(m, '[', ']') def _print_SubModule(self, M): return self._print_seq(M.gens, '<', '>') def _print_FreeModule(self, M): return self._print(M.ring)**self._print(M.rank) def _print_ModuleImplementedIdeal(self, M): return self._print_seq([x for [x] in M._module.gens], '<', '>') def _print_QuotientRing(self, R): return self._print(R.ring) / self._print(R.base_ideal) def _print_QuotientRingElement(self, R): return self._print(R.data) + self._print(R.ring.base_ideal) def _print_QuotientModuleElement(self, m): return self._print(m.data) + self._print(m.module.killed_module) def _print_QuotientModule(self, M): return self._print(M.base) / self._print(M.killed_module) def _print_MatrixHomomorphism(self, h): matrix = self._print(h._sympy_matrix()) matrix.baseline = matrix.height() // 2 pform = prettyForm(*matrix.right(' : ', self._print(h.domain), ' %s> ' % hobj('-', 2), self._print(h.codomain))) return pform def _print_Manifold(self, manifold): return self._print(manifold.name) def _print_Patch(self, patch): return self._print(patch.name) def _print_CoordSystem(self, coords): return self._print(coords.name) def _print_BaseScalarField(self, field): string = field._coord_sys.symbols[field._index].name return self._print(pretty_symbol(string)) def _print_BaseVectorField(self, field): s = U('PARTIAL DIFFERENTIAL') + '_' + field._coord_sys.symbols[field._index].name return self._print(pretty_symbol(s)) def _print_Differential(self, diff): if self._use_unicode: d = '\N{DOUBLE-STRUCK ITALIC SMALL D}' else: d = 'd' field = diff._form_field if hasattr(field, '_coord_sys'): string = field._coord_sys.symbols[field._index].name return self._print(d + ' ' + pretty_symbol(string)) else: pform = self._print(field) pform = prettyForm(*pform.parens()) return prettyForm(*pform.left(d)) def _print_Tr(self, p): #TODO: Handle indices pform = self._print(p.args[0]) pform = prettyForm(*pform.left('%s(' % (p.__class__.__name__))) pform = prettyForm(*pform.right(')')) return pform def _print_primenu(self, e): pform = self._print(e.args[0]) pform = prettyForm(*pform.parens()) if self._use_unicode: pform = prettyForm(*pform.left(greek_unicode['nu'])) else: pform = prettyForm(*pform.left('nu')) return pform def _print_primeomega(self, e): pform = self._print(e.args[0]) pform = prettyForm(*pform.parens()) if self._use_unicode: pform = prettyForm(*pform.left(greek_unicode['Omega'])) else: pform = prettyForm(*pform.left('Omega')) return pform def _print_Quantity(self, e): if e.name.name == 'degree': pform = self._print("\N{DEGREE SIGN}") return pform else: return self.emptyPrinter(e) def _print_AssignmentBase(self, e): op = prettyForm(' ' + xsym(e.op) + ' ') l = self._print(e.lhs) r = self._print(e.rhs) pform = prettyForm(*stringPict.next(l, op, r)) return pform def _print_Str(self, s): return self._print(s.name) @print_function(PrettyPrinter) def pretty(expr, **settings): """Returns a string containing the prettified form of expr. For information on keyword arguments see pretty_print function. """ pp = PrettyPrinter(settings) # XXX: this is an ugly hack, but at least it works use_unicode = pp._settings['use_unicode'] uflag = pretty_use_unicode(use_unicode) try: return pp.doprint(expr) finally: pretty_use_unicode(uflag) def pretty_print(expr, **kwargs): """Prints expr in pretty form. pprint is just a shortcut for this function. Parameters ========== expr : expression The expression to print. wrap_line : bool, optional (default=True) Line wrapping enabled/disabled. num_columns : int or None, optional (default=None) Number of columns before line breaking (default to None which reads the terminal width), useful when using SymPy without terminal. use_unicode : bool or None, optional (default=None) Use unicode characters, such as the Greek letter pi instead of the string pi. full_prec : bool or string, optional (default="auto") Use full precision. order : bool or string, optional (default=None) Set to 'none' for long expressions if slow; default is None. use_unicode_sqrt_char : bool, optional (default=True) Use compact single-character square root symbol (when unambiguous). root_notation : bool, optional (default=True) Set to 'False' for printing exponents of the form 1/n in fractional form. By default exponent is printed in root form. mat_symbol_style : string, optional (default="plain") Set to "bold" for printing MatrixSymbols using a bold mathematical symbol face. By default the standard face is used. imaginary_unit : string, optional (default="i") Letter to use for imaginary unit when use_unicode is True. Can be "i" (default) or "j". """ print(pretty(expr, **kwargs)) pprint = pretty_print def pager_print(expr, **settings): """Prints expr using the pager, in pretty form. This invokes a pager command using pydoc. Lines are not wrapped automatically. This routine is meant to be used with a pager that allows sideways scrolling, like ``less -S``. Parameters are the same as for ``pretty_print``. If you wish to wrap lines, pass ``num_columns=None`` to auto-detect the width of the terminal. """ from pydoc import pager from locale import getpreferredencoding if 'num_columns' not in settings: settings['num_columns'] = 500000 # disable line wrap pager(pretty(expr, **settings).encode(getpreferredencoding()))
9df048f9c2d82c13fd56e6716fb0d25ad148837be00e984d7d5fae06d1433081
"""Symbolic primitives + unicode/ASCII abstraction for pretty.py""" import sys import warnings from string import ascii_lowercase, ascii_uppercase import unicodedata unicode_warnings = '' def U(name): """ Get a unicode character by name or, None if not found. This exists because older versions of Python use older unicode databases. """ try: return unicodedata.lookup(name) except KeyError: global unicode_warnings unicode_warnings += 'No \'%s\' in unicodedata\n' % name return None from sympy.printing.conventions import split_super_sub from sympy.core.alphabets import greeks from sympy.utilities.exceptions import sympy_deprecation_warning # prefix conventions when constructing tables # L - LATIN i # G - GREEK beta # D - DIGIT 0 # S - SYMBOL + __all__ = ['greek_unicode', 'sub', 'sup', 'xsym', 'vobj', 'hobj', 'pretty_symbol', 'annotated'] _use_unicode = False def pretty_use_unicode(flag=None): """Set whether pretty-printer should use unicode by default""" global _use_unicode global unicode_warnings if flag is None: return _use_unicode if flag and unicode_warnings: # print warnings (if any) on first unicode usage warnings.warn(unicode_warnings) unicode_warnings = '' use_unicode_prev = _use_unicode _use_unicode = flag return use_unicode_prev def pretty_try_use_unicode(): """See if unicode output is available and leverage it if possible""" encoding = getattr(sys.stdout, 'encoding', None) # this happens when e.g. stdout is redirected through a pipe, or is # e.g. a cStringIO.StringO if encoding is None: return # sys.stdout has no encoding symbols = [] # see if we can represent greek alphabet symbols += greek_unicode.values() # and atoms symbols += atoms_table.values() for s in symbols: if s is None: return # common symbols not present! try: s.encode(encoding) except UnicodeEncodeError: return # all the characters were present and encodable pretty_use_unicode(True) def xstr(*args): sympy_deprecation_warning( """ The sympy.printing.pretty.pretty_symbology.xstr() function is deprecated. Use str() instead. """, deprecated_since_version="1.7", active_deprecations_target="deprecated-pretty-printing-functions" ) return str(*args) # GREEK g = lambda l: U('GREEK SMALL LETTER %s' % l.upper()) G = lambda l: U('GREEK CAPITAL LETTER %s' % l.upper()) greek_letters = list(greeks) # make a copy # deal with Unicode's funny spelling of lambda greek_letters[greek_letters.index('lambda')] = 'lamda' # {} greek letter -> (g,G) greek_unicode = {L: g(L) for L in greek_letters} greek_unicode.update((L[0].upper() + L[1:], G(L)) for L in greek_letters) # aliases greek_unicode['lambda'] = greek_unicode['lamda'] greek_unicode['Lambda'] = greek_unicode['Lamda'] greek_unicode['varsigma'] = '\N{GREEK SMALL LETTER FINAL SIGMA}' # BOLD b = lambda l: U('MATHEMATICAL BOLD SMALL %s' % l.upper()) B = lambda l: U('MATHEMATICAL BOLD CAPITAL %s' % l.upper()) bold_unicode = {l: b(l) for l in ascii_lowercase} bold_unicode.update((L, B(L)) for L in ascii_uppercase) # GREEK BOLD gb = lambda l: U('MATHEMATICAL BOLD SMALL %s' % l.upper()) GB = lambda l: U('MATHEMATICAL BOLD CAPITAL %s' % l.upper()) greek_bold_letters = list(greeks) # make a copy, not strictly required here # deal with Unicode's funny spelling of lambda greek_bold_letters[greek_bold_letters.index('lambda')] = 'lamda' # {} greek letter -> (g,G) greek_bold_unicode = {L: g(L) for L in greek_bold_letters} greek_bold_unicode.update((L[0].upper() + L[1:], G(L)) for L in greek_bold_letters) greek_bold_unicode['lambda'] = greek_unicode['lamda'] greek_bold_unicode['Lambda'] = greek_unicode['Lamda'] greek_bold_unicode['varsigma'] = '\N{MATHEMATICAL BOLD SMALL FINAL SIGMA}' digit_2txt = { '0': 'ZERO', '1': 'ONE', '2': 'TWO', '3': 'THREE', '4': 'FOUR', '5': 'FIVE', '6': 'SIX', '7': 'SEVEN', '8': 'EIGHT', '9': 'NINE', } symb_2txt = { '+': 'PLUS SIGN', '-': 'MINUS', '=': 'EQUALS SIGN', '(': 'LEFT PARENTHESIS', ')': 'RIGHT PARENTHESIS', '[': 'LEFT SQUARE BRACKET', ']': 'RIGHT SQUARE BRACKET', '{': 'LEFT CURLY BRACKET', '}': 'RIGHT CURLY BRACKET', # non-std '{}': 'CURLY BRACKET', 'sum': 'SUMMATION', 'int': 'INTEGRAL', } # SUBSCRIPT & SUPERSCRIPT LSUB = lambda letter: U('LATIN SUBSCRIPT SMALL LETTER %s' % letter.upper()) GSUB = lambda letter: U('GREEK SUBSCRIPT SMALL LETTER %s' % letter.upper()) DSUB = lambda digit: U('SUBSCRIPT %s' % digit_2txt[digit]) SSUB = lambda symb: U('SUBSCRIPT %s' % symb_2txt[symb]) LSUP = lambda letter: U('SUPERSCRIPT LATIN SMALL LETTER %s' % letter.upper()) DSUP = lambda digit: U('SUPERSCRIPT %s' % digit_2txt[digit]) SSUP = lambda symb: U('SUPERSCRIPT %s' % symb_2txt[symb]) sub = {} # symb -> subscript symbol sup = {} # symb -> superscript symbol # latin subscripts for l in 'aeioruvxhklmnpst': sub[l] = LSUB(l) for l in 'in': sup[l] = LSUP(l) for gl in ['beta', 'gamma', 'rho', 'phi', 'chi']: sub[gl] = GSUB(gl) for d in [str(i) for i in range(10)]: sub[d] = DSUB(d) sup[d] = DSUP(d) for s in '+-=()': sub[s] = SSUB(s) sup[s] = SSUP(s) # Variable modifiers # TODO: Make brackets adjust to height of contents modifier_dict = { # Accents 'mathring': lambda s: center_accent(s, '\N{COMBINING RING ABOVE}'), 'ddddot': lambda s: center_accent(s, '\N{COMBINING FOUR DOTS ABOVE}'), 'dddot': lambda s: center_accent(s, '\N{COMBINING THREE DOTS ABOVE}'), 'ddot': lambda s: center_accent(s, '\N{COMBINING DIAERESIS}'), 'dot': lambda s: center_accent(s, '\N{COMBINING DOT ABOVE}'), 'check': lambda s: center_accent(s, '\N{COMBINING CARON}'), 'breve': lambda s: center_accent(s, '\N{COMBINING BREVE}'), 'acute': lambda s: center_accent(s, '\N{COMBINING ACUTE ACCENT}'), 'grave': lambda s: center_accent(s, '\N{COMBINING GRAVE ACCENT}'), 'tilde': lambda s: center_accent(s, '\N{COMBINING TILDE}'), 'hat': lambda s: center_accent(s, '\N{COMBINING CIRCUMFLEX ACCENT}'), 'bar': lambda s: center_accent(s, '\N{COMBINING OVERLINE}'), 'vec': lambda s: center_accent(s, '\N{COMBINING RIGHT ARROW ABOVE}'), 'prime': lambda s: s+'\N{PRIME}', 'prm': lambda s: s+'\N{PRIME}', # # Faces -- these are here for some compatibility with latex printing # 'bold': lambda s: s, # 'bm': lambda s: s, # 'cal': lambda s: s, # 'scr': lambda s: s, # 'frak': lambda s: s, # Brackets 'norm': lambda s: '\N{DOUBLE VERTICAL LINE}'+s+'\N{DOUBLE VERTICAL LINE}', 'avg': lambda s: '\N{MATHEMATICAL LEFT ANGLE BRACKET}'+s+'\N{MATHEMATICAL RIGHT ANGLE BRACKET}', 'abs': lambda s: '\N{VERTICAL LINE}'+s+'\N{VERTICAL LINE}', 'mag': lambda s: '\N{VERTICAL LINE}'+s+'\N{VERTICAL LINE}', } # VERTICAL OBJECTS HUP = lambda symb: U('%s UPPER HOOK' % symb_2txt[symb]) CUP = lambda symb: U('%s UPPER CORNER' % symb_2txt[symb]) MID = lambda symb: U('%s MIDDLE PIECE' % symb_2txt[symb]) EXT = lambda symb: U('%s EXTENSION' % symb_2txt[symb]) HLO = lambda symb: U('%s LOWER HOOK' % symb_2txt[symb]) CLO = lambda symb: U('%s LOWER CORNER' % symb_2txt[symb]) TOP = lambda symb: U('%s TOP' % symb_2txt[symb]) BOT = lambda symb: U('%s BOTTOM' % symb_2txt[symb]) # {} '(' -> (extension, start, end, middle) 1-character _xobj_unicode = { # vertical symbols # (( ext, top, bot, mid ), c1) '(': (( EXT('('), HUP('('), HLO('(') ), '('), ')': (( EXT(')'), HUP(')'), HLO(')') ), ')'), '[': (( EXT('['), CUP('['), CLO('[') ), '['), ']': (( EXT(']'), CUP(']'), CLO(']') ), ']'), '{': (( EXT('{}'), HUP('{'), HLO('{'), MID('{') ), '{'), '}': (( EXT('{}'), HUP('}'), HLO('}'), MID('}') ), '}'), '|': U('BOX DRAWINGS LIGHT VERTICAL'), '<': ((U('BOX DRAWINGS LIGHT VERTICAL'), U('BOX DRAWINGS LIGHT DIAGONAL UPPER RIGHT TO LOWER LEFT'), U('BOX DRAWINGS LIGHT DIAGONAL UPPER LEFT TO LOWER RIGHT')), '<'), '>': ((U('BOX DRAWINGS LIGHT VERTICAL'), U('BOX DRAWINGS LIGHT DIAGONAL UPPER LEFT TO LOWER RIGHT'), U('BOX DRAWINGS LIGHT DIAGONAL UPPER RIGHT TO LOWER LEFT')), '>'), 'lfloor': (( EXT('['), EXT('['), CLO('[') ), U('LEFT FLOOR')), 'rfloor': (( EXT(']'), EXT(']'), CLO(']') ), U('RIGHT FLOOR')), 'lceil': (( EXT('['), CUP('['), EXT('[') ), U('LEFT CEILING')), 'rceil': (( EXT(']'), CUP(']'), EXT(']') ), U('RIGHT CEILING')), 'int': (( EXT('int'), U('TOP HALF INTEGRAL'), U('BOTTOM HALF INTEGRAL') ), U('INTEGRAL')), 'sum': (( U('BOX DRAWINGS LIGHT DIAGONAL UPPER LEFT TO LOWER RIGHT'), '_', U('OVERLINE'), U('BOX DRAWINGS LIGHT DIAGONAL UPPER RIGHT TO LOWER LEFT')), U('N-ARY SUMMATION')), # horizontal objects #'-': '-', '-': U('BOX DRAWINGS LIGHT HORIZONTAL'), '_': U('LOW LINE'), # We used to use this, but LOW LINE looks better for roots, as it's a # little lower (i.e., it lines up with the / perfectly. But perhaps this # one would still be wanted for some cases? # '_': U('HORIZONTAL SCAN LINE-9'), # diagonal objects '\' & '/' ? '/': U('BOX DRAWINGS LIGHT DIAGONAL UPPER RIGHT TO LOWER LEFT'), '\\': U('BOX DRAWINGS LIGHT DIAGONAL UPPER LEFT TO LOWER RIGHT'), } _xobj_ascii = { # vertical symbols # (( ext, top, bot, mid ), c1) '(': (( '|', '/', '\\' ), '('), ')': (( '|', '\\', '/' ), ')'), # XXX this looks ugly # '[': (( '|', '-', '-' ), '['), # ']': (( '|', '-', '-' ), ']'), # XXX not so ugly :( '[': (( '[', '[', '[' ), '['), ']': (( ']', ']', ']' ), ']'), '{': (( '|', '/', '\\', '<' ), '{'), '}': (( '|', '\\', '/', '>' ), '}'), '|': '|', '<': (( '|', '/', '\\' ), '<'), '>': (( '|', '\\', '/' ), '>'), 'int': ( ' | ', ' /', '/ ' ), # horizontal objects '-': '-', '_': '_', # diagonal objects '\' & '/' ? '/': '/', '\\': '\\', } def xobj(symb, length): """Construct spatial object of given length. return: [] of equal-length strings """ if length <= 0: raise ValueError("Length should be greater than 0") # TODO robustify when no unicodedat available if _use_unicode: _xobj = _xobj_unicode else: _xobj = _xobj_ascii vinfo = _xobj[symb] c1 = top = bot = mid = None if not isinstance(vinfo, tuple): # 1 entry ext = vinfo else: if isinstance(vinfo[0], tuple): # (vlong), c1 vlong = vinfo[0] c1 = vinfo[1] else: # (vlong), c1 vlong = vinfo ext = vlong[0] try: top = vlong[1] bot = vlong[2] mid = vlong[3] except IndexError: pass if c1 is None: c1 = ext if top is None: top = ext if bot is None: bot = ext if mid is not None: if (length % 2) == 0: # even height, but we have to print it somehow anyway... # XXX is it ok? length += 1 else: mid = ext if length == 1: return c1 res = [] next = (length - 2)//2 nmid = (length - 2) - next*2 res += [top] res += [ext]*next res += [mid]*nmid res += [ext]*next res += [bot] return res def vobj(symb, height): """Construct vertical object of a given height see: xobj """ return '\n'.join( xobj(symb, height) ) def hobj(symb, width): """Construct horizontal object of a given width see: xobj """ return ''.join( xobj(symb, width) ) # RADICAL # n -> symbol root = { 2: U('SQUARE ROOT'), # U('RADICAL SYMBOL BOTTOM') 3: U('CUBE ROOT'), 4: U('FOURTH ROOT'), } # RATIONAL VF = lambda txt: U('VULGAR FRACTION %s' % txt) # (p,q) -> symbol frac = { (1, 2): VF('ONE HALF'), (1, 3): VF('ONE THIRD'), (2, 3): VF('TWO THIRDS'), (1, 4): VF('ONE QUARTER'), (3, 4): VF('THREE QUARTERS'), (1, 5): VF('ONE FIFTH'), (2, 5): VF('TWO FIFTHS'), (3, 5): VF('THREE FIFTHS'), (4, 5): VF('FOUR FIFTHS'), (1, 6): VF('ONE SIXTH'), (5, 6): VF('FIVE SIXTHS'), (1, 8): VF('ONE EIGHTH'), (3, 8): VF('THREE EIGHTHS'), (5, 8): VF('FIVE EIGHTHS'), (7, 8): VF('SEVEN EIGHTHS'), } # atom symbols _xsym = { '==': ('=', '='), '<': ('<', '<'), '>': ('>', '>'), '<=': ('<=', U('LESS-THAN OR EQUAL TO')), '>=': ('>=', U('GREATER-THAN OR EQUAL TO')), '!=': ('!=', U('NOT EQUAL TO')), ':=': (':=', ':='), '+=': ('+=', '+='), '-=': ('-=', '-='), '*=': ('*=', '*='), '/=': ('/=', '/='), '%=': ('%=', '%='), '*': ('*', U('DOT OPERATOR')), '-->': ('-->', U('EM DASH') + U('EM DASH') + U('BLACK RIGHT-POINTING TRIANGLE') if U('EM DASH') and U('BLACK RIGHT-POINTING TRIANGLE') else None), '==>': ('==>', U('BOX DRAWINGS DOUBLE HORIZONTAL') + U('BOX DRAWINGS DOUBLE HORIZONTAL') + U('BLACK RIGHT-POINTING TRIANGLE') if U('BOX DRAWINGS DOUBLE HORIZONTAL') and U('BOX DRAWINGS DOUBLE HORIZONTAL') and U('BLACK RIGHT-POINTING TRIANGLE') else None), '.': ('*', U('RING OPERATOR')), } def xsym(sym): """get symbology for a 'character'""" op = _xsym[sym] if _use_unicode: return op[1] else: return op[0] # SYMBOLS atoms_table = { # class how-to-display 'Exp1': U('SCRIPT SMALL E'), 'Pi': U('GREEK SMALL LETTER PI'), 'Infinity': U('INFINITY'), 'NegativeInfinity': U('INFINITY') and ('-' + U('INFINITY')), # XXX what to do here #'ImaginaryUnit': U('GREEK SMALL LETTER IOTA'), #'ImaginaryUnit': U('MATHEMATICAL ITALIC SMALL I'), 'ImaginaryUnit': U('DOUBLE-STRUCK ITALIC SMALL I'), 'EmptySet': U('EMPTY SET'), 'Naturals': U('DOUBLE-STRUCK CAPITAL N'), 'Naturals0': (U('DOUBLE-STRUCK CAPITAL N') and (U('DOUBLE-STRUCK CAPITAL N') + U('SUBSCRIPT ZERO'))), 'Integers': U('DOUBLE-STRUCK CAPITAL Z'), 'Rationals': U('DOUBLE-STRUCK CAPITAL Q'), 'Reals': U('DOUBLE-STRUCK CAPITAL R'), 'Complexes': U('DOUBLE-STRUCK CAPITAL C'), 'Union': U('UNION'), 'SymmetricDifference': U('INCREMENT'), 'Intersection': U('INTERSECTION'), 'Ring': U('RING OPERATOR'), 'Modifier Letter Low Ring':U('Modifier Letter Low Ring'), 'EmptySequence': 'EmptySequence', } def pretty_atom(atom_name, default=None, printer=None): """return pretty representation of an atom""" if _use_unicode: if printer is not None and atom_name == 'ImaginaryUnit' and printer._settings['imaginary_unit'] == 'j': return U('DOUBLE-STRUCK ITALIC SMALL J') else: return atoms_table[atom_name] else: if default is not None: return default raise KeyError('only unicode') # send it default printer def pretty_symbol(symb_name, bold_name=False): """return pretty representation of a symbol""" # let's split symb_name into symbol + index # UC: beta1 # UC: f_beta if not _use_unicode: return symb_name name, sups, subs = split_super_sub(symb_name) def translate(s, bold_name) : if bold_name: gG = greek_bold_unicode.get(s) else: gG = greek_unicode.get(s) if gG is not None: return gG for key in sorted(modifier_dict.keys(), key=lambda k:len(k), reverse=True) : if s.lower().endswith(key) and len(s)>len(key): return modifier_dict[key](translate(s[:-len(key)], bold_name)) if bold_name: return ''.join([bold_unicode[c] for c in s]) return s name = translate(name, bold_name) # Let's prettify sups/subs. If it fails at one of them, pretty sups/subs are # not used at all. def pretty_list(l, mapping): result = [] for s in l: pretty = mapping.get(s) if pretty is None: try: # match by separate characters pretty = ''.join([mapping[c] for c in s]) except (TypeError, KeyError): return None result.append(pretty) return result pretty_sups = pretty_list(sups, sup) if pretty_sups is not None: pretty_subs = pretty_list(subs, sub) else: pretty_subs = None # glue the results into one string if pretty_subs is None: # nice formatting of sups/subs did not work if subs: name += '_'+'_'.join([translate(s, bold_name) for s in subs]) if sups: name += '__'+'__'.join([translate(s, bold_name) for s in sups]) return name else: sups_result = ' '.join(pretty_sups) subs_result = ' '.join(pretty_subs) return ''.join([name, sups_result, subs_result]) def annotated(letter): """ Return a stylised drawing of the letter ``letter``, together with information on how to put annotations (super- and subscripts to the left and to the right) on it. See pretty.py functions _print_meijerg, _print_hyper on how to use this information. """ ucode_pics = { 'F': (2, 0, 2, 0, '\N{BOX DRAWINGS LIGHT DOWN AND RIGHT}\N{BOX DRAWINGS LIGHT HORIZONTAL}\n' '\N{BOX DRAWINGS LIGHT VERTICAL AND RIGHT}\N{BOX DRAWINGS LIGHT HORIZONTAL}\n' '\N{BOX DRAWINGS LIGHT UP}'), 'G': (3, 0, 3, 1, '\N{BOX DRAWINGS LIGHT ARC DOWN AND RIGHT}\N{BOX DRAWINGS LIGHT HORIZONTAL}\N{BOX DRAWINGS LIGHT ARC DOWN AND LEFT}\n' '\N{BOX DRAWINGS LIGHT VERTICAL}\N{BOX DRAWINGS LIGHT RIGHT}\N{BOX DRAWINGS LIGHT DOWN AND LEFT}\n' '\N{BOX DRAWINGS LIGHT ARC UP AND RIGHT}\N{BOX DRAWINGS LIGHT HORIZONTAL}\N{BOX DRAWINGS LIGHT ARC UP AND LEFT}') } ascii_pics = { 'F': (3, 0, 3, 0, ' _\n|_\n|\n'), 'G': (3, 0, 3, 1, ' __\n/__\n\\_|') } if _use_unicode: return ucode_pics[letter] else: return ascii_pics[letter] _remove_combining = dict.fromkeys(list(range(ord('\N{COMBINING GRAVE ACCENT}'), ord('\N{COMBINING LATIN SMALL LETTER X}'))) + list(range(ord('\N{COMBINING LEFT HARPOON ABOVE}'), ord('\N{COMBINING ASTERISK ABOVE}')))) def is_combining(sym): """Check whether symbol is a unicode modifier. """ return ord(sym) in _remove_combining def center_accent(string, accent): """ Returns a string with accent inserted on the middle character. Useful to put combining accents on symbol names, including multi-character names. Parameters ========== string : string The string to place the accent in. accent : string The combining accent to insert References ========== .. [1] https://en.wikipedia.org/wiki/Combining_character .. [2] https://en.wikipedia.org/wiki/Combining_Diacritical_Marks """ # Accent is placed on the previous character, although it may not always look # like that depending on console midpoint = len(string) // 2 + 1 firstpart = string[:midpoint] secondpart = string[midpoint:] return firstpart + accent + secondpart def line_width(line): """Unicode combining symbols (modifiers) are not ever displayed as separate symbols and thus should not be counted """ return len(line.translate(_remove_combining))
d14504476e9c94f25760706a01cb9195744e1778d78ccf321da7669b944eae4e
"""Prettyprinter by Jurjen Bos. (I hate spammers: mail me at pietjepuk314 at the reverse of ku.oc.oohay). All objects have a method that create a "stringPict", that can be used in the str method for pretty printing. Updates by Jason Gedge (email <my last name> at cs mun ca) - terminal_string() method - minor fixes and changes (mostly to prettyForm) TODO: - Allow left/center/right alignment options for above/below and top/center/bottom alignment options for left/right """ from .pretty_symbology import hobj, vobj, xsym, xobj, pretty_use_unicode, line_width from sympy.utilities.exceptions import sympy_deprecation_warning class stringPict: """An ASCII picture. The pictures are represented as a list of equal length strings. """ #special value for stringPict.below LINE = 'line' def __init__(self, s, baseline=0): """Initialize from string. Multiline strings are centered. """ self.s = s #picture is a string that just can be printed self.picture = stringPict.equalLengths(s.splitlines()) #baseline is the line number of the "base line" self.baseline = baseline self.binding = None @staticmethod def equalLengths(lines): # empty lines if not lines: return [''] width = max(line_width(line) for line in lines) return [line.center(width) for line in lines] def height(self): """The height of the picture in characters.""" return len(self.picture) def width(self): """The width of the picture in characters.""" return line_width(self.picture[0]) @staticmethod def next(*args): """Put a string of stringPicts next to each other. Returns string, baseline arguments for stringPict. """ #convert everything to stringPicts objects = [] for arg in args: if isinstance(arg, str): arg = stringPict(arg) objects.append(arg) #make a list of pictures, with equal height and baseline newBaseline = max(obj.baseline for obj in objects) newHeightBelowBaseline = max( obj.height() - obj.baseline for obj in objects) newHeight = newBaseline + newHeightBelowBaseline pictures = [] for obj in objects: oneEmptyLine = [' '*obj.width()] basePadding = newBaseline - obj.baseline totalPadding = newHeight - obj.height() pictures.append( oneEmptyLine * basePadding + obj.picture + oneEmptyLine * (totalPadding - basePadding)) result = [''.join(lines) for lines in zip(*pictures)] return '\n'.join(result), newBaseline def right(self, *args): r"""Put pictures next to this one. Returns string, baseline arguments for stringPict. (Multiline) strings are allowed, and are given a baseline of 0. Examples ======== >>> from sympy.printing.pretty.stringpict import stringPict >>> print(stringPict("10").right(" + ",stringPict("1\r-\r2",1))[0]) 1 10 + - 2 """ return stringPict.next(self, *args) def left(self, *args): """Put pictures (left to right) at left. Returns string, baseline arguments for stringPict. """ return stringPict.next(*(args + (self,))) @staticmethod def stack(*args): """Put pictures on top of each other, from top to bottom. Returns string, baseline arguments for stringPict. The baseline is the baseline of the second picture. Everything is centered. Baseline is the baseline of the second picture. Strings are allowed. The special value stringPict.LINE is a row of '-' extended to the width. """ #convert everything to stringPicts; keep LINE objects = [] for arg in args: if arg is not stringPict.LINE and isinstance(arg, str): arg = stringPict(arg) objects.append(arg) #compute new width newWidth = max( obj.width() for obj in objects if obj is not stringPict.LINE) lineObj = stringPict(hobj('-', newWidth)) #replace LINE with proper lines for i, obj in enumerate(objects): if obj is stringPict.LINE: objects[i] = lineObj #stack the pictures, and center the result newPicture = [] for obj in objects: newPicture.extend(obj.picture) newPicture = [line.center(newWidth) for line in newPicture] newBaseline = objects[0].height() + objects[1].baseline return '\n'.join(newPicture), newBaseline def below(self, *args): """Put pictures under this picture. Returns string, baseline arguments for stringPict. Baseline is baseline of top picture Examples ======== >>> from sympy.printing.pretty.stringpict import stringPict >>> print(stringPict("x+3").below( ... stringPict.LINE, '3')[0]) #doctest: +NORMALIZE_WHITESPACE x+3 --- 3 """ s, baseline = stringPict.stack(self, *args) return s, self.baseline def above(self, *args): """Put pictures above this picture. Returns string, baseline arguments for stringPict. Baseline is baseline of bottom picture. """ string, baseline = stringPict.stack(*(args + (self,))) baseline = len(string.splitlines()) - self.height() + self.baseline return string, baseline def parens(self, left='(', right=')', ifascii_nougly=False): """Put parentheses around self. Returns string, baseline arguments for stringPict. left or right can be None or empty string which means 'no paren from that side' """ h = self.height() b = self.baseline # XXX this is a hack -- ascii parens are ugly! if ifascii_nougly and not pretty_use_unicode(): h = 1 b = 0 res = self if left: lparen = stringPict(vobj(left, h), baseline=b) res = stringPict(*lparen.right(self)) if right: rparen = stringPict(vobj(right, h), baseline=b) res = stringPict(*res.right(rparen)) return ('\n'.join(res.picture), res.baseline) def leftslash(self): """Precede object by a slash of the proper size. """ # XXX not used anywhere ? height = max( self.baseline, self.height() - 1 - self.baseline)*2 + 1 slash = '\n'.join( ' '*(height - i - 1) + xobj('/', 1) + ' '*i for i in range(height) ) return self.left(stringPict(slash, height//2)) def root(self, n=None): """Produce a nice root symbol. Produces ugly results for big n inserts. """ # XXX not used anywhere # XXX duplicate of root drawing in pretty.py #put line over expression result = self.above('_'*self.width()) #construct right half of root symbol height = self.height() slash = '\n'.join( ' ' * (height - i - 1) + '/' + ' ' * i for i in range(height) ) slash = stringPict(slash, height - 1) #left half of root symbol if height > 2: downline = stringPict('\\ \n \\', 1) else: downline = stringPict('\\') #put n on top, as low as possible if n is not None and n.width() > downline.width(): downline = downline.left(' '*(n.width() - downline.width())) downline = downline.above(n) #build root symbol root = downline.right(slash) #glue it on at the proper height #normally, the root symbel is as high as self #which is one less than result #this moves the root symbol one down #if the root became higher, the baseline has to grow too root.baseline = result.baseline - result.height() + root.height() return result.left(root) def render(self, * args, **kwargs): """Return the string form of self. Unless the argument line_break is set to False, it will break the expression in a form that can be printed on the terminal without being broken up. """ if kwargs["wrap_line"] is False: return "\n".join(self.picture) if kwargs["num_columns"] is not None: # Read the argument num_columns if it is not None ncols = kwargs["num_columns"] else: # Attempt to get a terminal width ncols = self.terminal_width() ncols -= 2 if ncols <= 0: ncols = 78 # If smaller than the terminal width, no need to correct if self.width() <= ncols: return type(self.picture[0])(self) # for one-line pictures we don't need v-spacers. on the other hand, for # multiline-pictures, we need v-spacers between blocks, compare: # # 2 2 3 | a*c*e + a*c*f + a*d | a*c*e + a*c*f + a*d | 3.14159265358979323 # 6*x *y + 4*x*y + | | *e + a*d*f + b*c*e | 84626433832795 # | *e + a*d*f + b*c*e | + b*c*f + b*d*e + b | # 3 4 4 | | *d*f | # 4*y*x + x + y | + b*c*f + b*d*e + b | | # | | | # | *d*f i = 0 svals = [] do_vspacers = (self.height() > 1) while i < self.width(): svals.extend([ sval[i:i + ncols] for sval in self.picture ]) if do_vspacers: svals.append("") # a vertical spacer i += ncols if svals[-1] == '': del svals[-1] # Get rid of the last spacer return "\n".join(svals) def terminal_width(self): """Return the terminal width if possible, otherwise return 0. """ ncols = 0 try: import curses import io try: curses.setupterm() ncols = curses.tigetnum('cols') except AttributeError: # windows curses doesn't implement setupterm or tigetnum # code below from # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440694 from ctypes import windll, create_string_buffer # stdin handle is -10 # stdout handle is -11 # stderr handle is -12 h = windll.kernel32.GetStdHandle(-12) csbi = create_string_buffer(22) res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi) if res: import struct (bufx, bufy, curx, cury, wattr, left, top, right, bottom, maxx, maxy) = struct.unpack("hhhhHhhhhhh", csbi.raw) ncols = right - left + 1 except curses.error: pass except io.UnsupportedOperation: pass except (ImportError, TypeError): pass return ncols def __eq__(self, o): if isinstance(o, str): return '\n'.join(self.picture) == o elif isinstance(o, stringPict): return o.picture == self.picture return False def __hash__(self): return super().__hash__() def __str__(self): return '\n'.join(self.picture) def __repr__(self): return "stringPict(%r,%d)" % ('\n'.join(self.picture), self.baseline) def __getitem__(self, index): return self.picture[index] def __len__(self): return len(self.s) class prettyForm(stringPict): """ Extension of the stringPict class that knows about basic math applications, optimizing double minus signs. "Binding" is interpreted as follows:: ATOM this is an atom: never needs to be parenthesized FUNC this is a function application: parenthesize if added (?) DIV this is a division: make wider division if divided POW this is a power: only parenthesize if exponent MUL this is a multiplication: parenthesize if powered ADD this is an addition: parenthesize if multiplied or powered NEG this is a negative number: optimize if added, parenthesize if multiplied or powered OPEN this is an open object: parenthesize if added, multiplied, or powered (example: Piecewise) """ ATOM, FUNC, DIV, POW, MUL, ADD, NEG, OPEN = range(8) def __init__(self, s, baseline=0, binding=0, unicode=None): """Initialize from stringPict and binding power.""" stringPict.__init__(self, s, baseline) self.binding = binding if unicode is not None: sympy_deprecation_warning( """ The unicode argument to prettyForm is deprecated. Only the s argument (the first positional argument) should be passed. """, deprecated_since_version="1.7", active_deprecations_target="deprecated-pretty-printing-functions") self._unicode = unicode or s @property def unicode(self): sympy_deprecation_warning( """ The prettyForm.unicode attribute is deprecated. Use the prettyForm.s attribute instead. """, deprecated_since_version="1.7", active_deprecations_target="deprecated-pretty-printing-functions") return self._unicode # Note: code to handle subtraction is in _print_Add def __add__(self, *others): """Make a pretty addition. Addition of negative numbers is simplified. """ arg = self if arg.binding > prettyForm.NEG: arg = stringPict(*arg.parens()) result = [arg] for arg in others: #add parentheses for weak binders if arg.binding > prettyForm.NEG: arg = stringPict(*arg.parens()) #use existing minus sign if available if arg.binding != prettyForm.NEG: result.append(' + ') result.append(arg) return prettyForm(binding=prettyForm.ADD, *stringPict.next(*result)) def __truediv__(self, den, slashed=False): """Make a pretty division; stacked or slashed. """ if slashed: raise NotImplementedError("Can't do slashed fraction yet") num = self if num.binding == prettyForm.DIV: num = stringPict(*num.parens()) if den.binding == prettyForm.DIV: den = stringPict(*den.parens()) if num.binding==prettyForm.NEG: num = num.right(" ")[0] return prettyForm(binding=prettyForm.DIV, *stringPict.stack( num, stringPict.LINE, den)) def __mul__(self, *others): """Make a pretty multiplication. Parentheses are needed around +, - and neg. """ quantity = { 'degree': "\N{DEGREE SIGN}" } if len(others) == 0: return self # We aren't actually multiplying... So nothing to do here. # add parens on args that need them arg = self if arg.binding > prettyForm.MUL and arg.binding != prettyForm.NEG: arg = stringPict(*arg.parens()) result = [arg] for arg in others: if arg.picture[0] not in quantity.values(): result.append(xsym('*')) #add parentheses for weak binders if arg.binding > prettyForm.MUL and arg.binding != prettyForm.NEG: arg = stringPict(*arg.parens()) result.append(arg) len_res = len(result) for i in range(len_res): if i < len_res - 1 and result[i] == '-1' and result[i + 1] == xsym('*'): # substitute -1 by -, like in -1*x -> -x result.pop(i) result.pop(i) result.insert(i, '-') if result[0][0] == '-': # if there is a - sign in front of all # This test was failing to catch a prettyForm.__mul__(prettyForm("-1", 0, 6)) being negative bin = prettyForm.NEG if result[0] == '-': right = result[1] if right.picture[right.baseline][0] == '-': result[0] = '- ' else: bin = prettyForm.MUL return prettyForm(binding=bin, *stringPict.next(*result)) def __repr__(self): return "prettyForm(%r,%d,%d)" % ( '\n'.join(self.picture), self.baseline, self.binding) def __pow__(self, b): """Make a pretty power. """ a = self use_inline_func_form = False if b.binding == prettyForm.POW: b = stringPict(*b.parens()) if a.binding > prettyForm.FUNC: a = stringPict(*a.parens()) elif a.binding == prettyForm.FUNC: # heuristic for when to use inline power if b.height() > 1: a = stringPict(*a.parens()) else: use_inline_func_form = True if use_inline_func_form: # 2 # sin + + (x) b.baseline = a.prettyFunc.baseline + b.height() func = stringPict(*a.prettyFunc.right(b)) return prettyForm(*func.right(a.prettyArgs)) else: # 2 <-- top # (x+y) <-- bot top = stringPict(*b.left(' '*a.width())) bot = stringPict(*a.right(' '*b.width())) return prettyForm(binding=prettyForm.POW, *bot.above(top)) simpleFunctions = ["sin", "cos", "tan"] @staticmethod def apply(function, *args): """Functions of one or more variables. """ if function in prettyForm.simpleFunctions: #simple function: use only space if possible assert len( args) == 1, "Simple function %s must have 1 argument" % function arg = args[0].__pretty__() if arg.binding <= prettyForm.DIV: #optimization: no parentheses necessary return prettyForm(binding=prettyForm.FUNC, *arg.left(function + ' ')) argumentList = [] for arg in args: argumentList.append(',') argumentList.append(arg.__pretty__()) argumentList = stringPict(*stringPict.next(*argumentList[1:])) argumentList = stringPict(*argumentList.parens()) return prettyForm(binding=prettyForm.ATOM, *argumentList.left(function))
a3b9d0b64505607d9078de18fc88614effb9123b3288e149fcc4a8c164c2b8e5
from typing import Any, Dict as tDict from sympy.testing.pytest import raises, warns_deprecated_sympy from sympy.assumptions.ask import Q from sympy.core.function import (Function, WildFunction) from sympy.core.numbers import (AlgebraicNumber, Float, Integer, Rational) from sympy.core.singleton import S from sympy.core.symbol import (Dummy, Symbol, Wild, symbols) from sympy.core.sympify import sympify from sympy.functions.elementary.complexes import Abs from sympy.functions.elementary.miscellaneous import (root, sqrt) from sympy.functions.elementary.trigonometric import sin from sympy.functions.special.delta_functions import Heaviside from sympy.logic.boolalg import (false, true) from sympy.matrices.dense import (Matrix, ones) from sympy.matrices.expressions.matexpr import MatrixSymbol from sympy.matrices.immutable import ImmutableDenseMatrix from sympy.combinatorics import Cycle, Permutation from sympy.core.symbol import Str from sympy.geometry import Point, Ellipse from sympy.printing import srepr from sympy.polys import ring, field, ZZ, QQ, lex, grlex, Poly from sympy.polys.polyclasses import DMP from sympy.polys.agca.extensions import FiniteExtension x, y = symbols('x,y') # eval(srepr(expr)) == expr has to succeed in the right environment. The right # environment is the scope of "from sympy import *" for most cases. ENV = {"Str": Str} # type: tDict[str, Any] exec("from sympy import *", ENV) def sT(expr, string, import_stmt=None, **kwargs): """ sT := sreprTest Tests that srepr delivers the expected string and that the condition eval(srepr(expr))==expr holds. """ if import_stmt is None: ENV2 = ENV else: ENV2 = ENV.copy() exec(import_stmt, ENV2) assert srepr(expr, **kwargs) == string assert eval(string, ENV2) == expr def test_printmethod(): class R(Abs): def _sympyrepr(self, printer): return "foo(%s)" % printer._print(self.args[0]) assert srepr(R(x)) == "foo(Symbol('x'))" def test_Add(): sT(x + y, "Add(Symbol('x'), Symbol('y'))") assert srepr(x**2 + 1, order='lex') == "Add(Pow(Symbol('x'), Integer(2)), Integer(1))" assert srepr(x**2 + 1, order='old') == "Add(Integer(1), Pow(Symbol('x'), Integer(2)))" assert srepr(sympify('x + 3 - 2', evaluate=False), order='none') == "Add(Symbol('x'), Integer(3), Mul(Integer(-1), Integer(2)))" def test_more_than_255_args_issue_10259(): from sympy.core.add import Add from sympy.core.mul import Mul for op in (Add, Mul): expr = op(*symbols('x:256')) assert eval(srepr(expr)) == expr def test_Function(): sT(Function("f")(x), "Function('f')(Symbol('x'))") # test unapplied Function sT(Function('f'), "Function('f')") sT(sin(x), "sin(Symbol('x'))") sT(sin, "sin") def test_Heaviside(): sT(Heaviside(x), "Heaviside(Symbol('x'))") sT(Heaviside(x, 1), "Heaviside(Symbol('x'), Integer(1))") def test_Geometry(): sT(Point(0, 0), "Point2D(Integer(0), Integer(0))") sT(Ellipse(Point(0, 0), 5, 1), "Ellipse(Point2D(Integer(0), Integer(0)), Integer(5), Integer(1))") # TODO more tests def test_Singletons(): sT(S.Catalan, 'Catalan') sT(S.ComplexInfinity, 'zoo') sT(S.EulerGamma, 'EulerGamma') sT(S.Exp1, 'E') sT(S.GoldenRatio, 'GoldenRatio') sT(S.TribonacciConstant, 'TribonacciConstant') sT(S.Half, 'Rational(1, 2)') sT(S.ImaginaryUnit, 'I') sT(S.Infinity, 'oo') sT(S.NaN, 'nan') sT(S.NegativeInfinity, '-oo') sT(S.NegativeOne, 'Integer(-1)') sT(S.One, 'Integer(1)') sT(S.Pi, 'pi') sT(S.Zero, 'Integer(0)') sT(S.Complexes, 'Complexes') sT(S.EmptySequence, 'EmptySequence') sT(S.EmptySet, 'EmptySet') # sT(S.IdentityFunction, 'Lambda(_x, _x)') sT(S.Naturals, 'Naturals') sT(S.Naturals0, 'Naturals0') sT(S.Rationals, 'Rationals') sT(S.Reals, 'Reals') sT(S.UniversalSet, 'UniversalSet') def test_Integer(): sT(Integer(4), "Integer(4)") def test_list(): sT([x, Integer(4)], "[Symbol('x'), Integer(4)]") def test_Matrix(): for cls, name in [(Matrix, "MutableDenseMatrix"), (ImmutableDenseMatrix, "ImmutableDenseMatrix")]: sT(cls([[x**+1, 1], [y, x + y]]), "%s([[Symbol('x'), Integer(1)], [Symbol('y'), Add(Symbol('x'), Symbol('y'))]])" % name) sT(cls(), "%s([])" % name) sT(cls([[x**+1, 1], [y, x + y]]), "%s([[Symbol('x'), Integer(1)], [Symbol('y'), Add(Symbol('x'), Symbol('y'))]])" % name) def test_empty_Matrix(): sT(ones(0, 3), "MutableDenseMatrix(0, 3, [])") sT(ones(4, 0), "MutableDenseMatrix(4, 0, [])") sT(ones(0, 0), "MutableDenseMatrix([])") def test_Rational(): sT(Rational(1, 3), "Rational(1, 3)") sT(Rational(-1, 3), "Rational(-1, 3)") def test_Float(): sT(Float('1.23', dps=3), "Float('1.22998', precision=13)") sT(Float('1.23456789', dps=9), "Float('1.23456788994', precision=33)") sT(Float('1.234567890123456789', dps=19), "Float('1.234567890123456789013', precision=66)") sT(Float('0.60038617995049726', dps=15), "Float('0.60038617995049726', precision=53)") sT(Float('1.23', precision=13), "Float('1.22998', precision=13)") sT(Float('1.23456789', precision=33), "Float('1.23456788994', precision=33)") sT(Float('1.234567890123456789', precision=66), "Float('1.234567890123456789013', precision=66)") sT(Float('0.60038617995049726', precision=53), "Float('0.60038617995049726', precision=53)") sT(Float('0.60038617995049726', 15), "Float('0.60038617995049726', precision=53)") def test_Symbol(): sT(x, "Symbol('x')") sT(y, "Symbol('y')") sT(Symbol('x', negative=True), "Symbol('x', negative=True)") def test_Symbol_two_assumptions(): x = Symbol('x', negative=0, integer=1) # order could vary s1 = "Symbol('x', integer=True, negative=False)" s2 = "Symbol('x', negative=False, integer=True)" assert srepr(x) in (s1, s2) assert eval(srepr(x), ENV) == x def test_Symbol_no_special_commutative_treatment(): sT(Symbol('x'), "Symbol('x')") sT(Symbol('x', commutative=False), "Symbol('x', commutative=False)") sT(Symbol('x', commutative=0), "Symbol('x', commutative=False)") sT(Symbol('x', commutative=True), "Symbol('x', commutative=True)") sT(Symbol('x', commutative=1), "Symbol('x', commutative=True)") def test_Wild(): sT(Wild('x', even=True), "Wild('x', even=True)") def test_Dummy(): d = Dummy('d') sT(d, "Dummy('d', dummy_index=%s)" % str(d.dummy_index)) def test_Dummy_assumption(): d = Dummy('d', nonzero=True) assert d == eval(srepr(d)) s1 = "Dummy('d', dummy_index=%s, nonzero=True)" % str(d.dummy_index) s2 = "Dummy('d', nonzero=True, dummy_index=%s)" % str(d.dummy_index) assert srepr(d) in (s1, s2) def test_Dummy_from_Symbol(): # should not get the full dictionary of assumptions n = Symbol('n', integer=True) d = n.as_dummy() assert srepr(d ) == "Dummy('n', dummy_index=%s)" % str(d.dummy_index) def test_tuple(): sT((x,), "(Symbol('x'),)") sT((x, y), "(Symbol('x'), Symbol('y'))") def test_WildFunction(): sT(WildFunction('w'), "WildFunction('w')") def test_settins(): raises(TypeError, lambda: srepr(x, method="garbage")) def test_Mul(): sT(3*x**3*y, "Mul(Integer(3), Pow(Symbol('x'), Integer(3)), Symbol('y'))") assert srepr(3*x**3*y, order='old') == "Mul(Integer(3), Symbol('y'), Pow(Symbol('x'), Integer(3)))" assert srepr(sympify('(x+4)*2*x*7', evaluate=False), order='none') == "Mul(Add(Symbol('x'), Integer(4)), Integer(2), Symbol('x'), Integer(7))" def test_AlgebraicNumber(): a = AlgebraicNumber(sqrt(2)) sT(a, "AlgebraicNumber(Pow(Integer(2), Rational(1, 2)), [Integer(1), Integer(0)])") a = AlgebraicNumber(root(-2, 3)) sT(a, "AlgebraicNumber(Pow(Integer(-2), Rational(1, 3)), [Integer(1), Integer(0)])") def test_PolyRing(): assert srepr(ring("x", ZZ, lex)[0]) == "PolyRing((Symbol('x'),), ZZ, lex)" assert srepr(ring("x,y", QQ, grlex)[0]) == "PolyRing((Symbol('x'), Symbol('y')), QQ, grlex)" assert srepr(ring("x,y,z", ZZ["t"], lex)[0]) == "PolyRing((Symbol('x'), Symbol('y'), Symbol('z')), ZZ[t], lex)" def test_FracField(): assert srepr(field("x", ZZ, lex)[0]) == "FracField((Symbol('x'),), ZZ, lex)" assert srepr(field("x,y", QQ, grlex)[0]) == "FracField((Symbol('x'), Symbol('y')), QQ, grlex)" assert srepr(field("x,y,z", ZZ["t"], lex)[0]) == "FracField((Symbol('x'), Symbol('y'), Symbol('z')), ZZ[t], lex)" def test_PolyElement(): R, x, y = ring("x,y", ZZ) assert srepr(3*x**2*y + 1) == "PolyElement(PolyRing((Symbol('x'), Symbol('y')), ZZ, lex), [((2, 1), 3), ((0, 0), 1)])" def test_FracElement(): F, x, y = field("x,y", ZZ) assert srepr((3*x**2*y + 1)/(x - y**2)) == "FracElement(FracField((Symbol('x'), Symbol('y')), ZZ, lex), [((2, 1), 3), ((0, 0), 1)], [((1, 0), 1), ((0, 2), -1)])" def test_FractionField(): assert srepr(QQ.frac_field(x)) == \ "FractionField(FracField((Symbol('x'),), QQ, lex))" assert srepr(QQ.frac_field(x, y, order=grlex)) == \ "FractionField(FracField((Symbol('x'), Symbol('y')), QQ, grlex))" def test_PolynomialRingBase(): assert srepr(ZZ.old_poly_ring(x)) == \ "GlobalPolynomialRing(ZZ, Symbol('x'))" assert srepr(ZZ[x].old_poly_ring(y)) == \ "GlobalPolynomialRing(ZZ[x], Symbol('y'))" assert srepr(QQ.frac_field(x).old_poly_ring(y)) == \ "GlobalPolynomialRing(FractionField(FracField((Symbol('x'),), QQ, lex)), Symbol('y'))" def test_DMP(): assert srepr(DMP([1, 2], ZZ)) == 'DMP([1, 2], ZZ)' assert srepr(ZZ.old_poly_ring(x)([1, 2])) == \ "DMP([1, 2], ZZ, ring=GlobalPolynomialRing(ZZ, Symbol('x')))" def test_FiniteExtension(): assert srepr(FiniteExtension(Poly(x**2 + 1, x))) == \ "FiniteExtension(Poly(x**2 + 1, x, domain='ZZ'))" def test_ExtensionElement(): A = FiniteExtension(Poly(x**2 + 1, x)) assert srepr(A.generator) == \ "ExtElem(DMP([1, 0], ZZ, ring=GlobalPolynomialRing(ZZ, Symbol('x'))), FiniteExtension(Poly(x**2 + 1, x, domain='ZZ')))" def test_BooleanAtom(): assert srepr(true) == "true" assert srepr(false) == "false" def test_Integers(): sT(S.Integers, "Integers") def test_Naturals(): sT(S.Naturals, "Naturals") def test_Naturals0(): sT(S.Naturals0, "Naturals0") def test_Reals(): sT(S.Reals, "Reals") def test_matrix_expressions(): n = symbols('n', integer=True) A = MatrixSymbol("A", n, n) B = MatrixSymbol("B", n, n) sT(A, "MatrixSymbol(Str('A'), Symbol('n', integer=True), Symbol('n', integer=True))") sT(A*B, "MatMul(MatrixSymbol(Str('A'), Symbol('n', integer=True), Symbol('n', integer=True)), MatrixSymbol(Str('B'), Symbol('n', integer=True), Symbol('n', integer=True)))") sT(A + B, "MatAdd(MatrixSymbol(Str('A'), Symbol('n', integer=True), Symbol('n', integer=True)), MatrixSymbol(Str('B'), Symbol('n', integer=True), Symbol('n', integer=True)))") def test_Cycle(): # FIXME: sT fails because Cycle is not immutable and calling srepr(Cycle(1, 2)) # adds keys to the Cycle dict (GH-17661) #import_stmt = "from sympy.combinatorics import Cycle" #sT(Cycle(1, 2), "Cycle(1, 2)", import_stmt) assert srepr(Cycle(1, 2)) == "Cycle(1, 2)" def test_Permutation(): import_stmt = "from sympy.combinatorics import Permutation" sT(Permutation(1, 2)(3, 4), "Permutation([0, 2, 1, 4, 3])", import_stmt, perm_cyclic=False) sT(Permutation(1, 2)(3, 4), "Permutation(1, 2)(3, 4)", import_stmt, perm_cyclic=True) with warns_deprecated_sympy(): old_print_cyclic = Permutation.print_cyclic Permutation.print_cyclic = False sT(Permutation(1, 2)(3, 4), "Permutation([0, 2, 1, 4, 3])", import_stmt) Permutation.print_cyclic = old_print_cyclic def test_dict(): from sympy.abc import x, y, z d = {} assert srepr(d) == "{}" d = {x: y} assert srepr(d) == "{Symbol('x'): Symbol('y')}" d = {x: y, y: z} assert srepr(d) in ( "{Symbol('x'): Symbol('y'), Symbol('y'): Symbol('z')}", "{Symbol('y'): Symbol('z'), Symbol('x'): Symbol('y')}", ) d = {x: {y: z}} assert srepr(d) == "{Symbol('x'): {Symbol('y'): Symbol('z')}}" def test_set(): from sympy.abc import x, y s = set() assert srepr(s) == "set()" s = {x, y} assert srepr(s) in ("{Symbol('x'), Symbol('y')}", "{Symbol('y'), Symbol('x')}") def test_Predicate(): sT(Q.even, "Q.even") def test_AppliedPredicate(): sT(Q.even(Symbol('z')), "AppliedPredicate(Q.even, Symbol('z'))")
99e15ed8479bae29d4a82f4c794189de0b2244019d503a01139bae7386c97126
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 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 from sympy.parsing.latex import parse_latex 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 not prntr.module_imports assert prntr.doprint(pi) == 'math.pi' assert prntr.module_imports == {'math': {'pi'}} assert prntr.doprint(x**Rational(1, 2)) == 'math.sqrt(x)' assert prntr.doprint(sqrt(x)) == 'math.sqrt(x)' assert prntr.module_imports == {'math': {'pi', 'sqrt'}} assert prntr.doprint(acos(x)) == 'math.acos(x)' assert prntr.doprint(Assignment(x, 2)) == 'x = 2' assert prntr.doprint(Piecewise((1, Eq(x, 0)), (2, x>6))) == '((1) if (x == 0) else (2) if (x > 6) else None)' assert prntr.doprint(Piecewise((2, Le(x, 0)), (3, Gt(x, 0)), evaluate=False)) == '((2) if (x <= 0) else'\ ' (3) if (x > 0) else None)' assert prntr.doprint(sign(x)) == '(0.0 if x == 0 else math.copysign(1, x))' assert prntr.doprint(p[0, 1]) == 'p[0, 1]' assert prntr.doprint(KroneckerDelta(x,y)) == '(1 if x == y else 0)' 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(): antlr4 = import_module("antlr4") if not antlr4: skip('antlr not installed.') # Make sure pycode removes curly braces from subscripted variables expr = parse_latex(r'a_b \cdot b') assert pycode(expr) == 'a_b*b' expr = parse_latex(r'a_{11} \cdot 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'
bd5046fc736db61c4e1e2fe407225eb4b1a5999b456a99a68edae647513dba75
from sympy.algebras.quaternion import Quaternion from sympy.assumptions.ask import Q from sympy.calculus.accumulationbounds import AccumBounds from sympy.combinatorics.partitions import Partition from sympy.concrete.summations import (Sum, summation) from sympy.core.add import Add from sympy.core.containers import (Dict, Tuple) from sympy.core.expr import UnevaluatedExpr, Expr from sympy.core.function import (Derivative, Function, Lambda, Subs, WildFunction) from sympy.core.mul import Mul from sympy.core import (Catalan, EulerGamma, GoldenRatio, TribonacciConstant) from sympy.core.numbers import (E, Float, I, Integer, Rational, nan, oo, pi, zoo) from sympy.core.parameters import _exp_is_pow from sympy.core.power import Pow from sympy.core.relational import (Eq, Rel, Ne) from sympy.core.singleton import S from sympy.core.symbol import (Dummy, Symbol, Wild, symbols) from sympy.functions.combinatorial.factorials import (factorial, factorial2, subfactorial) from sympy.functions.elementary.complexes import Abs from sympy.functions.elementary.exponential import exp from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import (cos, sin) from sympy.functions.special.delta_functions import Heaviside from sympy.functions.special.zeta_functions import zeta from sympy.integrals.integrals import Integral from sympy.logic.boolalg import (Equivalent, false, true, Xor) from sympy.matrices.dense import Matrix from sympy.matrices.expressions.matexpr import MatrixSymbol from sympy.matrices.expressions.slice import MatrixSlice from sympy.matrices import SparseMatrix from sympy.polys.polytools import factor from sympy.series.limits import Limit from sympy.series.order import O from sympy.sets.sets import (Complement, FiniteSet, Interval, SymmetricDifference) from sympy.external import import_module from sympy.physics.control.lti import TransferFunction, Series, Parallel, \ Feedback, TransferFunctionMatrix, MIMOSeries, MIMOParallel, MIMOFeedback from sympy.physics.units import second, joule from sympy.polys import (Poly, rootof, RootSum, groebner, ring, field, ZZ, QQ, ZZ_I, QQ_I, lex, grlex) from sympy.geometry import Point, Circle, Polygon, Ellipse, Triangle from sympy.tensor import NDimArray from sympy.tensor.array.expressions.array_expressions import ArraySymbol, ArrayElement from sympy.testing.pytest import raises, warns_deprecated_sympy from sympy.printing import sstr, sstrrepr, StrPrinter from sympy.physics.quantum.trace import Tr x, y, z, w, t = symbols('x,y,z,w,t') d = Dummy('d') def test_printmethod(): class R(Abs): def _sympystr(self, printer): return "foo(%s)" % printer._print(self.args[0]) assert sstr(R(x)) == "foo(x)" class R(Abs): def _sympystr(self, printer): return "foo" assert sstr(R(x)) == "foo" def test_Abs(): assert str(Abs(x)) == "Abs(x)" assert str(Abs(Rational(1, 6))) == "1/6" assert str(Abs(Rational(-1, 6))) == "1/6" def test_Add(): assert str(x + y) == "x + y" assert str(x + 1) == "x + 1" assert str(x + x**2) == "x**2 + x" assert str(Add(0, 1, evaluate=False)) == "0 + 1" assert str(Add(0, 0, 1, evaluate=False)) == "0 + 0 + 1" assert str(1.0*x) == "1.0*x" assert str(5 + x + y + x*y + x**2 + y**2) == "x**2 + x*y + x + y**2 + y + 5" assert str(1 + x + x**2/2 + x**3/3) == "x**3/3 + x**2/2 + x + 1" assert str(2*x - 7*x**2 + 2 + 3*y) == "-7*x**2 + 2*x + 3*y + 2" assert str(x - y) == "x - y" assert str(2 - x) == "2 - x" assert str(x - 2) == "x - 2" assert str(x - y - z - w) == "-w + x - y - z" assert str(x - z*y**2*z*w) == "-w*y**2*z**2 + x" assert str(x - 1*y*x*y) == "-x*y**2 + x" assert str(sin(x).series(x, 0, 15)) == "x - x**3/6 + x**5/120 - x**7/5040 + x**9/362880 - x**11/39916800 + x**13/6227020800 + O(x**15)" def test_Catalan(): assert str(Catalan) == "Catalan" def test_ComplexInfinity(): assert str(zoo) == "zoo" def test_Derivative(): assert str(Derivative(x, y)) == "Derivative(x, y)" assert str(Derivative(x**2, x, evaluate=False)) == "Derivative(x**2, x)" assert str(Derivative( x**2/y, x, y, evaluate=False)) == "Derivative(x**2/y, x, y)" def test_dict(): assert str({1: 1 + x}) == sstr({1: 1 + x}) == "{1: x + 1}" assert str({1: x**2, 2: y*x}) in ("{1: x**2, 2: x*y}", "{2: x*y, 1: x**2}") assert sstr({1: x**2, 2: y*x}) == "{1: x**2, 2: x*y}" def test_Dict(): assert str(Dict({1: 1 + x})) == sstr({1: 1 + x}) == "{1: x + 1}" assert str(Dict({1: x**2, 2: y*x})) in ( "{1: x**2, 2: x*y}", "{2: x*y, 1: x**2}") assert sstr(Dict({1: x**2, 2: y*x})) == "{1: x**2, 2: x*y}" def test_Dummy(): assert str(d) == "_d" assert str(d + x) == "_d + x" def test_EulerGamma(): assert str(EulerGamma) == "EulerGamma" def test_Exp(): assert str(E) == "E" with _exp_is_pow(True): assert str(exp(x)) == "E**x" def test_factorial(): n = Symbol('n', integer=True) assert str(factorial(-2)) == "zoo" assert str(factorial(0)) == "1" assert str(factorial(7)) == "5040" assert str(factorial(n)) == "factorial(n)" assert str(factorial(2*n)) == "factorial(2*n)" assert str(factorial(factorial(n))) == 'factorial(factorial(n))' assert str(factorial(factorial2(n))) == 'factorial(factorial2(n))' assert str(factorial2(factorial(n))) == 'factorial2(factorial(n))' assert str(factorial2(factorial2(n))) == 'factorial2(factorial2(n))' assert str(subfactorial(3)) == "2" assert str(subfactorial(n)) == "subfactorial(n)" assert str(subfactorial(2*n)) == "subfactorial(2*n)" def test_Function(): f = Function('f') fx = f(x) w = WildFunction('w') assert str(f) == "f" assert str(fx) == "f(x)" assert str(w) == "w_" def test_Geometry(): assert sstr(Point(0, 0)) == 'Point2D(0, 0)' assert sstr(Circle(Point(0, 0), 3)) == 'Circle(Point2D(0, 0), 3)' assert sstr(Ellipse(Point(1, 2), 3, 4)) == 'Ellipse(Point2D(1, 2), 3, 4)' assert sstr(Triangle(Point(1, 1), Point(7, 8), Point(0, -1))) == \ 'Triangle(Point2D(1, 1), Point2D(7, 8), Point2D(0, -1))' assert sstr(Polygon(Point(5, 6), Point(-2, -3), Point(0, 0), Point(4, 7))) == \ 'Polygon(Point2D(5, 6), Point2D(-2, -3), Point2D(0, 0), Point2D(4, 7))' assert sstr(Triangle(Point(0, 0), Point(1, 0), Point(0, 1)), sympy_integers=True) == \ 'Triangle(Point2D(S(0), S(0)), Point2D(S(1), S(0)), Point2D(S(0), S(1)))' assert sstr(Ellipse(Point(1, 2), 3, 4), sympy_integers=True) == \ 'Ellipse(Point2D(S(1), S(2)), S(3), S(4))' def test_GoldenRatio(): assert str(GoldenRatio) == "GoldenRatio" def test_Heaviside(): assert str(Heaviside(x)) == str(Heaviside(x, S.Half)) == "Heaviside(x)" assert str(Heaviside(x, 1)) == "Heaviside(x, 1)" def test_TribonacciConstant(): assert str(TribonacciConstant) == "TribonacciConstant" def test_ImaginaryUnit(): assert str(I) == "I" def test_Infinity(): assert str(oo) == "oo" assert str(oo*I) == "oo*I" def test_Integer(): assert str(Integer(-1)) == "-1" assert str(Integer(1)) == "1" assert str(Integer(-3)) == "-3" assert str(Integer(0)) == "0" assert str(Integer(25)) == "25" def test_Integral(): assert str(Integral(sin(x), y)) == "Integral(sin(x), y)" assert str(Integral(sin(x), (y, 0, 1))) == "Integral(sin(x), (y, 0, 1))" def test_Interval(): n = (S.NegativeInfinity, 1, 2, S.Infinity) for i in range(len(n)): for j in range(i + 1, len(n)): for l in (True, False): for r in (True, False): ival = Interval(n[i], n[j], l, r) assert S(str(ival)) == ival def test_AccumBounds(): a = Symbol('a', real=True) assert str(AccumBounds(0, a)) == "AccumBounds(0, a)" assert str(AccumBounds(0, 1)) == "AccumBounds(0, 1)" def test_Lambda(): assert str(Lambda(d, d**2)) == "Lambda(_d, _d**2)" # issue 2908 assert str(Lambda((), 1)) == "Lambda((), 1)" assert str(Lambda((), x)) == "Lambda((), x)" assert str(Lambda((x, y), x+y)) == "Lambda((x, y), x + y)" assert str(Lambda(((x, y),), x+y)) == "Lambda(((x, y),), x + y)" def test_Limit(): assert str(Limit(sin(x)/x, x, y)) == "Limit(sin(x)/x, x, y)" assert str(Limit(1/x, x, 0)) == "Limit(1/x, x, 0)" assert str( Limit(sin(x)/x, x, y, dir="-")) == "Limit(sin(x)/x, x, y, dir='-')" def test_list(): assert str([x]) == sstr([x]) == "[x]" assert str([x**2, x*y + 1]) == sstr([x**2, x*y + 1]) == "[x**2, x*y + 1]" assert str([x**2, [y + x]]) == sstr([x**2, [y + x]]) == "[x**2, [x + y]]" def test_Matrix_str(): M = Matrix([[x**+1, 1], [y, x + y]]) assert str(M) == "Matrix([[x, 1], [y, x + y]])" assert sstr(M) == "Matrix([\n[x, 1],\n[y, x + y]])" M = Matrix([[1]]) assert str(M) == sstr(M) == "Matrix([[1]])" M = Matrix([[1, 2]]) assert str(M) == sstr(M) == "Matrix([[1, 2]])" M = Matrix() assert str(M) == sstr(M) == "Matrix(0, 0, [])" M = Matrix(0, 1, lambda i, j: 0) assert str(M) == sstr(M) == "Matrix(0, 1, [])" def test_Mul(): assert str(x/y) == "x/y" assert str(y/x) == "y/x" assert str(x/y/z) == "x/(y*z)" assert str((x + 1)/(y + 2)) == "(x + 1)/(y + 2)" assert str(2*x/3) == '2*x/3' assert str(-2*x/3) == '-2*x/3' assert str(-1.0*x) == '-1.0*x' assert str(1.0*x) == '1.0*x' assert str(Mul(0, 1, evaluate=False)) == '0*1' assert str(Mul(1, 0, evaluate=False)) == '1*0' assert str(Mul(1, 1, evaluate=False)) == '1*1' assert str(Mul(1, 1, 1, evaluate=False)) == '1*1*1' assert str(Mul(1, 2, evaluate=False)) == '1*2' assert str(Mul(1, S.Half, evaluate=False)) == '1*(1/2)' assert str(Mul(1, 1, S.Half, evaluate=False)) == '1*1*(1/2)' assert str(Mul(1, 1, 2, 3, x, evaluate=False)) == '1*1*2*3*x' assert str(Mul(1, -1, evaluate=False)) == '1*(-1)' assert str(Mul(-1, 1, evaluate=False)) == '-1*1' assert str(Mul(4, 3, 2, 1, 0, y, x, evaluate=False)) == '4*3*2*1*0*y*x' assert str(Mul(4, 3, 2, 1+z, 0, y, x, evaluate=False)) == '4*3*2*(z + 1)*0*y*x' assert str(Mul(Rational(2, 3), Rational(5, 7), evaluate=False)) == '(2/3)*(5/7)' # For issue 14160 assert str(Mul(-2, x, Pow(Mul(y,y,evaluate=False), -1, evaluate=False), evaluate=False)) == '-2*x/(y*y)' # issue 21537 assert str(Mul(x, Pow(1/y, -1, evaluate=False), evaluate=False)) == 'x/(1/y)' class CustomClass1(Expr): is_commutative = True class CustomClass2(Expr): is_commutative = True cc1 = CustomClass1() cc2 = CustomClass2() assert str(Rational(2)*cc1) == '2*CustomClass1()' assert str(cc1*Rational(2)) == '2*CustomClass1()' assert str(cc1*Float("1.5")) == '1.5*CustomClass1()' assert str(cc2*Rational(2)) == '2*CustomClass2()' assert str(cc2*Rational(2)*cc1) == '2*CustomClass1()*CustomClass2()' assert str(cc1*Rational(2)*cc2) == '2*CustomClass1()*CustomClass2()' def test_NaN(): assert str(nan) == "nan" def test_NegativeInfinity(): assert str(-oo) == "-oo" def test_Order(): assert str(O(x)) == "O(x)" assert str(O(x**2)) == "O(x**2)" assert str(O(x*y)) == "O(x*y, x, y)" assert str(O(x, x)) == "O(x)" assert str(O(x, (x, 0))) == "O(x)" assert str(O(x, (x, oo))) == "O(x, (x, oo))" assert str(O(x, x, y)) == "O(x, x, y)" assert str(O(x, x, y)) == "O(x, x, y)" assert str(O(x, (x, oo), (y, oo))) == "O(x, (x, oo), (y, oo))" def test_Permutation_Cycle(): from sympy.combinatorics import Permutation, Cycle # general principle: economically, canonically show all moved elements # and the size of the permutation. for p, s in [ (Cycle(), '()'), (Cycle(2), '(2)'), (Cycle(2, 1), '(1 2)'), (Cycle(1, 2)(5)(6, 7)(10), '(1 2)(6 7)(10)'), (Cycle(3, 4)(1, 2)(3, 4), '(1 2)(4)'), ]: assert sstr(p) == s for p, s in [ (Permutation([]), 'Permutation([])'), (Permutation([], size=1), 'Permutation([0])'), (Permutation([], size=2), 'Permutation([0, 1])'), (Permutation([], size=10), 'Permutation([], size=10)'), (Permutation([1, 0, 2]), 'Permutation([1, 0, 2])'), (Permutation([1, 0, 2, 3, 4, 5]), 'Permutation([1, 0], size=6)'), (Permutation([1, 0, 2, 3, 4, 5], size=10), 'Permutation([1, 0], size=10)'), ]: assert sstr(p, perm_cyclic=False) == s for p, s in [ (Permutation([]), '()'), (Permutation([], size=1), '(0)'), (Permutation([], size=2), '(1)'), (Permutation([], size=10), '(9)'), (Permutation([1, 0, 2]), '(2)(0 1)'), (Permutation([1, 0, 2, 3, 4, 5]), '(5)(0 1)'), (Permutation([1, 0, 2, 3, 4, 5], size=10), '(9)(0 1)'), (Permutation([0, 1, 3, 2, 4, 5], size=10), '(9)(2 3)'), ]: assert sstr(p) == s with warns_deprecated_sympy(): old_print_cyclic = Permutation.print_cyclic Permutation.print_cyclic = False assert sstr(Permutation([1, 0, 2])) == 'Permutation([1, 0, 2])' Permutation.print_cyclic = old_print_cyclic def test_Pi(): assert str(pi) == "pi" def test_Poly(): assert str(Poly(0, x)) == "Poly(0, x, domain='ZZ')" assert str(Poly(1, x)) == "Poly(1, x, domain='ZZ')" assert str(Poly(x, x)) == "Poly(x, x, domain='ZZ')" assert str(Poly(2*x + 1, x)) == "Poly(2*x + 1, x, domain='ZZ')" assert str(Poly(2*x - 1, x)) == "Poly(2*x - 1, x, domain='ZZ')" assert str(Poly(-1, x)) == "Poly(-1, x, domain='ZZ')" assert str(Poly(-x, x)) == "Poly(-x, x, domain='ZZ')" assert str(Poly(-2*x + 1, x)) == "Poly(-2*x + 1, x, domain='ZZ')" assert str(Poly(-2*x - 1, x)) == "Poly(-2*x - 1, x, domain='ZZ')" assert str(Poly(x - 1, x)) == "Poly(x - 1, x, domain='ZZ')" assert str(Poly(2*x + x**5, x)) == "Poly(x**5 + 2*x, x, domain='ZZ')" assert str(Poly(3**(2*x), 3**x)) == "Poly((3**x)**2, 3**x, domain='ZZ')" assert str(Poly((x**2)**x)) == "Poly(((x**2)**x), (x**2)**x, domain='ZZ')" assert str(Poly((x + y)**3, (x + y), expand=False) ) == "Poly((x + y)**3, x + y, domain='ZZ')" assert str(Poly((x - 1)**2, (x - 1), expand=False) ) == "Poly((x - 1)**2, x - 1, domain='ZZ')" assert str( Poly(x**2 + 1 + y, x)) == "Poly(x**2 + y + 1, x, domain='ZZ[y]')" assert str( Poly(x**2 - 1 + y, x)) == "Poly(x**2 + y - 1, x, domain='ZZ[y]')" assert str(Poly(x**2 + I*x, x)) == "Poly(x**2 + I*x, x, domain='ZZ_I')" assert str(Poly(x**2 - I*x, x)) == "Poly(x**2 - I*x, x, domain='ZZ_I')" assert str(Poly(-x*y*z + x*y - 1, x, y, z) ) == "Poly(-x*y*z + x*y - 1, x, y, z, domain='ZZ')" assert str(Poly(-w*x**21*y**7*z + (1 + w)*z**3 - 2*x*z + 1, x, y, z)) == \ "Poly(-w*x**21*y**7*z - 2*x*z + (w + 1)*z**3 + 1, x, y, z, domain='ZZ[w]')" assert str(Poly(x**2 + 1, x, modulus=2)) == "Poly(x**2 + 1, x, modulus=2)" assert str(Poly(2*x**2 + 3*x + 4, x, modulus=17)) == "Poly(2*x**2 + 3*x + 4, x, modulus=17)" def test_PolyRing(): assert str(ring("x", ZZ, lex)[0]) == "Polynomial ring in x over ZZ with lex order" assert str(ring("x,y", QQ, grlex)[0]) == "Polynomial ring in x, y over QQ with grlex order" assert str(ring("x,y,z", ZZ["t"], lex)[0]) == "Polynomial ring in x, y, z over ZZ[t] with lex order" def test_FracField(): assert str(field("x", ZZ, lex)[0]) == "Rational function field in x over ZZ with lex order" assert str(field("x,y", QQ, grlex)[0]) == "Rational function field in x, y over QQ with grlex order" assert str(field("x,y,z", ZZ["t"], lex)[0]) == "Rational function field in x, y, z over ZZ[t] with lex order" def test_PolyElement(): Ruv, u,v = ring("u,v", ZZ) Rxyz, x,y,z = ring("x,y,z", Ruv) Rx_zzi, xz = ring("x", ZZ_I) assert str(x - x) == "0" assert str(x - 1) == "x - 1" assert str(x + 1) == "x + 1" assert str(x**2) == "x**2" assert str(x**(-2)) == "x**(-2)" assert str(x**QQ(1, 2)) == "x**(1/2)" assert str((u**2 + 3*u*v + 1)*x**2*y + u + 1) == "(u**2 + 3*u*v + 1)*x**2*y + u + 1" assert str((u**2 + 3*u*v + 1)*x**2*y + (u + 1)*x) == "(u**2 + 3*u*v + 1)*x**2*y + (u + 1)*x" assert str((u**2 + 3*u*v + 1)*x**2*y + (u + 1)*x + 1) == "(u**2 + 3*u*v + 1)*x**2*y + (u + 1)*x + 1" assert str((-u**2 + 3*u*v - 1)*x**2*y - (u + 1)*x - 1) == "-(u**2 - 3*u*v + 1)*x**2*y - (u + 1)*x - 1" assert str(-(v**2 + v + 1)*x + 3*u*v + 1) == "-(v**2 + v + 1)*x + 3*u*v + 1" assert str(-(v**2 + v + 1)*x - 3*u*v + 1) == "-(v**2 + v + 1)*x - 3*u*v + 1" assert str((1+I)*xz + 2) == "(1 + 1*I)*x + (2 + 0*I)" def test_FracElement(): Fuv, u,v = field("u,v", ZZ) Fxyzt, x,y,z,t = field("x,y,z,t", Fuv) Rx_zzi, xz = field("x", QQ_I) i = QQ_I(0, 1) assert str(x - x) == "0" assert str(x - 1) == "x - 1" assert str(x + 1) == "x + 1" assert str(x/3) == "x/3" assert str(x/z) == "x/z" assert str(x*y/z) == "x*y/z" assert str(x/(z*t)) == "x/(z*t)" assert str(x*y/(z*t)) == "x*y/(z*t)" assert str((x - 1)/y) == "(x - 1)/y" assert str((x + 1)/y) == "(x + 1)/y" assert str((-x - 1)/y) == "(-x - 1)/y" assert str((x + 1)/(y*z)) == "(x + 1)/(y*z)" assert str(-y/(x + 1)) == "-y/(x + 1)" assert str(y*z/(x + 1)) == "y*z/(x + 1)" assert str(((u + 1)*x*y + 1)/((v - 1)*z - 1)) == "((u + 1)*x*y + 1)/((v - 1)*z - 1)" assert str(((u + 1)*x*y + 1)/((v - 1)*z - t*u*v - 1)) == "((u + 1)*x*y + 1)/((v - 1)*z - u*v*t - 1)" assert str((1+i)/xz) == "(1 + 1*I)/x" assert str(((1+i)*xz - i)/xz) == "((1 + 1*I)*x + (0 + -1*I))/x" def test_GaussianInteger(): assert str(ZZ_I(1, 0)) == "1" assert str(ZZ_I(-1, 0)) == "-1" assert str(ZZ_I(0, 1)) == "I" assert str(ZZ_I(0, -1)) == "-I" assert str(ZZ_I(0, 2)) == "2*I" assert str(ZZ_I(0, -2)) == "-2*I" assert str(ZZ_I(1, 1)) == "1 + I" assert str(ZZ_I(-1, -1)) == "-1 - I" assert str(ZZ_I(-1, -2)) == "-1 - 2*I" def test_GaussianRational(): assert str(QQ_I(1, 0)) == "1" assert str(QQ_I(QQ(2, 3), 0)) == "2/3" assert str(QQ_I(0, QQ(2, 3))) == "2*I/3" assert str(QQ_I(QQ(1, 2), QQ(-2, 3))) == "1/2 - 2*I/3" def test_Pow(): assert str(x**-1) == "1/x" assert str(x**-2) == "x**(-2)" assert str(x**2) == "x**2" assert str((x + y)**-1) == "1/(x + y)" assert str((x + y)**-2) == "(x + y)**(-2)" assert str((x + y)**2) == "(x + y)**2" assert str((x + y)**(1 + x)) == "(x + y)**(x + 1)" assert str(x**Rational(1, 3)) == "x**(1/3)" assert str(1/x**Rational(1, 3)) == "x**(-1/3)" assert str(sqrt(sqrt(x))) == "x**(1/4)" # not the same as x**-1 assert str(x**-1.0) == 'x**(-1.0)' # see issue #2860 assert str(Pow(S(2), -1.0, evaluate=False)) == '2**(-1.0)' def test_sqrt(): assert str(sqrt(x)) == "sqrt(x)" assert str(sqrt(x**2)) == "sqrt(x**2)" assert str(1/sqrt(x)) == "1/sqrt(x)" assert str(1/sqrt(x**2)) == "1/sqrt(x**2)" assert str(y/sqrt(x)) == "y/sqrt(x)" assert str(x**0.5) == "x**0.5" assert str(1/x**0.5) == "x**(-0.5)" def test_Rational(): n1 = Rational(1, 4) n2 = Rational(1, 3) n3 = Rational(2, 4) n4 = Rational(2, -4) n5 = Rational(0) n7 = Rational(3) n8 = Rational(-3) assert str(n1*n2) == "1/12" assert str(n1*n2) == "1/12" assert str(n3) == "1/2" assert str(n1*n3) == "1/8" assert str(n1 + n3) == "3/4" assert str(n1 + n2) == "7/12" assert str(n1 + n4) == "-1/4" assert str(n4*n4) == "1/4" assert str(n4 + n2) == "-1/6" assert str(n4 + n5) == "-1/2" assert str(n4*n5) == "0" assert str(n3 + n4) == "0" assert str(n1**n7) == "1/64" assert str(n2**n7) == "1/27" assert str(n2**n8) == "27" assert str(n7**n8) == "1/27" assert str(Rational("-25")) == "-25" assert str(Rational("1.25")) == "5/4" assert str(Rational("-2.6e-2")) == "-13/500" assert str(S("25/7")) == "25/7" assert str(S("-123/569")) == "-123/569" assert str(S("0.1[23]", rational=1)) == "61/495" assert str(S("5.1[666]", rational=1)) == "31/6" assert str(S("-5.1[666]", rational=1)) == "-31/6" assert str(S("0.[9]", rational=1)) == "1" assert str(S("-0.[9]", rational=1)) == "-1" assert str(sqrt(Rational(1, 4))) == "1/2" assert str(sqrt(Rational(1, 36))) == "1/6" assert str((123**25) ** Rational(1, 25)) == "123" assert str((123**25 + 1)**Rational(1, 25)) != "123" assert str((123**25 - 1)**Rational(1, 25)) != "123" assert str((123**25 - 1)**Rational(1, 25)) != "122" assert str(sqrt(Rational(81, 36))**3) == "27/8" assert str(1/sqrt(Rational(81, 36))**3) == "8/27" assert str(sqrt(-4)) == str(2*I) assert str(2**Rational(1, 10**10)) == "2**(1/10000000000)" assert sstr(Rational(2, 3), sympy_integers=True) == "S(2)/3" x = Symbol("x") assert sstr(x**Rational(2, 3), sympy_integers=True) == "x**(S(2)/3)" assert sstr(Eq(x, Rational(2, 3)), sympy_integers=True) == "Eq(x, S(2)/3)" assert sstr(Limit(x, x, Rational(7, 2)), sympy_integers=True) == \ "Limit(x, x, S(7)/2)" def test_Float(): # NOTE dps is the whole number of decimal digits assert str(Float('1.23', dps=1 + 2)) == '1.23' assert str(Float('1.23456789', dps=1 + 8)) == '1.23456789' assert str( Float('1.234567890123456789', dps=1 + 18)) == '1.234567890123456789' assert str(pi.evalf(1 + 2)) == '3.14' assert str(pi.evalf(1 + 14)) == '3.14159265358979' assert str(pi.evalf(1 + 64)) == ('3.141592653589793238462643383279' '5028841971693993751058209749445923') assert str(pi.round(-1)) == '0.0' assert str((pi**400 - (pi**400).round(1)).n(2)) == '-0.e+88' assert sstr(Float("100"), full_prec=False, min=-2, max=2) == '1.0e+2' assert sstr(Float("100"), full_prec=False, min=-2, max=3) == '100.0' assert sstr(Float("0.1"), full_prec=False, min=-2, max=3) == '0.1' assert sstr(Float("0.099"), min=-2, max=3) == '9.90000000000000e-2' def test_Relational(): assert str(Rel(x, y, "<")) == "x < y" assert str(Rel(x + y, y, "==")) == "Eq(x + y, y)" assert str(Rel(x, y, "!=")) == "Ne(x, y)" assert str(Eq(x, 1) | Eq(x, 2)) == "Eq(x, 1) | Eq(x, 2)" assert str(Ne(x, 1) & Ne(x, 2)) == "Ne(x, 1) & Ne(x, 2)" def test_AppliedBinaryRelation(): assert str(Q.eq(x, y)) == "Q.eq(x, y)" assert str(Q.ne(x, y)) == "Q.ne(x, y)" def test_CRootOf(): assert str(rootof(x**5 + 2*x - 1, 0)) == "CRootOf(x**5 + 2*x - 1, 0)" def test_RootSum(): f = x**5 + 2*x - 1 assert str( RootSum(f, Lambda(z, z), auto=False)) == "RootSum(x**5 + 2*x - 1)" assert str(RootSum(f, Lambda( z, z**2), auto=False)) == "RootSum(x**5 + 2*x - 1, Lambda(z, z**2))" def test_GroebnerBasis(): assert str(groebner( [], x, y)) == "GroebnerBasis([], x, y, domain='ZZ', order='lex')" F = [x**2 - 3*y - x + 1, y**2 - 2*x + y - 1] assert str(groebner(F, order='grlex')) == \ "GroebnerBasis([x**2 - x - 3*y + 1, y**2 - 2*x + y - 1], x, y, domain='ZZ', order='grlex')" assert str(groebner(F, order='lex')) == \ "GroebnerBasis([2*x - y**2 - y + 1, y**4 + 2*y**3 - 3*y**2 - 16*y + 7], x, y, domain='ZZ', order='lex')" def test_set(): assert sstr(set()) == 'set()' assert sstr(frozenset()) == 'frozenset()' assert sstr({1}) == '{1}' assert sstr(frozenset([1])) == 'frozenset({1})' assert sstr({1, 2, 3}) == '{1, 2, 3}' assert sstr(frozenset([1, 2, 3])) == 'frozenset({1, 2, 3})' assert sstr( {1, x, x**2, x**3, x**4}) == '{1, x, x**2, x**3, x**4}' assert sstr( frozenset([1, x, x**2, x**3, x**4])) == 'frozenset({1, x, x**2, x**3, x**4})' def test_SparseMatrix(): M = SparseMatrix([[x**+1, 1], [y, x + y]]) assert str(M) == "Matrix([[x, 1], [y, x + y]])" assert sstr(M) == "Matrix([\n[x, 1],\n[y, x + y]])" def test_Sum(): assert str(summation(cos(3*z), (z, x, y))) == "Sum(cos(3*z), (z, x, y))" assert str(Sum(x*y**2, (x, -2, 2), (y, -5, 5))) == \ "Sum(x*y**2, (x, -2, 2), (y, -5, 5))" def test_Symbol(): assert str(y) == "y" assert str(x) == "x" e = x assert str(e) == "x" def test_tuple(): assert str((x,)) == sstr((x,)) == "(x,)" assert str((x + y, 1 + x)) == sstr((x + y, 1 + x)) == "(x + y, x + 1)" assert str((x + y, ( 1 + x, x**2))) == sstr((x + y, (1 + x, x**2))) == "(x + y, (x + 1, x**2))" def test_Series_str(): 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 str(Series(tf1, tf2)) == \ "Series(TransferFunction(x*y**2 - z, -t**3 + y**3, y), TransferFunction(x - y, x + y, y))" assert str(Series(tf1, tf2, tf3)) == \ "Series(TransferFunction(x*y**2 - z, -t**3 + y**3, y), TransferFunction(x - y, x + y, y), TransferFunction(t*x**2 - t**w*x + w, t - y, y))" assert str(Series(-tf2, tf1)) == \ "Series(TransferFunction(-x + y, x + y, y), TransferFunction(x*y**2 - z, -t**3 + y**3, y))" def test_MIMOSeries_str(): tf1 = TransferFunction(x*y**2 - z, y**3 - t**3, y) tf2 = TransferFunction(x - y, x + y, y) tfm_1 = TransferFunctionMatrix([[tf1, tf2], [tf2, tf1]]) tfm_2 = TransferFunctionMatrix([[tf2, tf1], [tf1, tf2]]) assert str(MIMOSeries(tfm_1, tfm_2)) == \ "MIMOSeries(TransferFunctionMatrix(((TransferFunction(x*y**2 - z, -t**3 + y**3, y), TransferFunction(x - y, x + y, y)), "\ "(TransferFunction(x - y, x + y, y), TransferFunction(x*y**2 - z, -t**3 + y**3, y)))), "\ "TransferFunctionMatrix(((TransferFunction(x - y, x + y, y), TransferFunction(x*y**2 - z, -t**3 + y**3, y)), "\ "(TransferFunction(x*y**2 - z, -t**3 + y**3, y), TransferFunction(x - y, x + y, y)))))" def test_TransferFunction_str(): tf1 = TransferFunction(x - 1, x + 1, x) assert str(tf1) == "TransferFunction(x - 1, x + 1, x)" tf2 = TransferFunction(x + 1, 2 - y, x) assert str(tf2) == "TransferFunction(x + 1, 2 - y, x)" tf3 = TransferFunction(y, y**2 + 2*y + 3, y) assert str(tf3) == "TransferFunction(y, y**2 + 2*y + 3, y)" def test_Parallel_str(): 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 str(Parallel(tf1, tf2)) == \ "Parallel(TransferFunction(x*y**2 - z, -t**3 + y**3, y), TransferFunction(x - y, x + y, y))" assert str(Parallel(tf1, tf2, tf3)) == \ "Parallel(TransferFunction(x*y**2 - z, -t**3 + y**3, y), TransferFunction(x - y, x + y, y), TransferFunction(t*x**2 - t**w*x + w, t - y, y))" assert str(Parallel(-tf2, tf1)) == \ "Parallel(TransferFunction(-x + y, x + y, y), TransferFunction(x*y**2 - z, -t**3 + y**3, y))" def test_MIMOParallel_str(): tf1 = TransferFunction(x*y**2 - z, y**3 - t**3, y) tf2 = TransferFunction(x - y, x + y, y) tfm_1 = TransferFunctionMatrix([[tf1, tf2], [tf2, tf1]]) tfm_2 = TransferFunctionMatrix([[tf2, tf1], [tf1, tf2]]) assert str(MIMOParallel(tfm_1, tfm_2)) == \ "MIMOParallel(TransferFunctionMatrix(((TransferFunction(x*y**2 - z, -t**3 + y**3, y), TransferFunction(x - y, x + y, y)), "\ "(TransferFunction(x - y, x + y, y), TransferFunction(x*y**2 - z, -t**3 + y**3, y)))), "\ "TransferFunctionMatrix(((TransferFunction(x - y, x + y, y), TransferFunction(x*y**2 - z, -t**3 + y**3, y)), "\ "(TransferFunction(x*y**2 - z, -t**3 + y**3, y), TransferFunction(x - y, x + y, y)))))" def test_Feedback_str(): 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 str(Feedback(tf1*tf2, tf3)) == \ "Feedback(Series(TransferFunction(x*y**2 - z, -t**3 + y**3, y), TransferFunction(x - y, x + y, y)), " \ "TransferFunction(t*x**2 - t**w*x + w, t - y, y), -1)" assert str(Feedback(tf1, TransferFunction(1, 1, y), 1)) == \ "Feedback(TransferFunction(x*y**2 - z, -t**3 + y**3, y), TransferFunction(1, 1, y), 1)" def test_MIMOFeedback_str(): tf1 = TransferFunction(x**2 - y**3, y - z, x) tf2 = TransferFunction(y - x, z + y, x) tfm_1 = TransferFunctionMatrix([[tf2, tf1], [tf1, tf2]]) tfm_2 = TransferFunctionMatrix([[tf1, tf2], [tf2, tf1]]) assert (str(MIMOFeedback(tfm_1, tfm_2)) \ == "MIMOFeedback(TransferFunctionMatrix(((TransferFunction(-x + y, y + z, x), TransferFunction(x**2 - y**3, y - z, x))," \ " (TransferFunction(x**2 - y**3, y - z, x), TransferFunction(-x + y, y + z, x)))), " \ "TransferFunctionMatrix(((TransferFunction(x**2 - y**3, y - z, x), " \ "TransferFunction(-x + y, y + z, x)), (TransferFunction(-x + y, y + z, x), TransferFunction(x**2 - y**3, y - z, x)))), -1)") assert (str(MIMOFeedback(tfm_1, tfm_2, 1)) \ == "MIMOFeedback(TransferFunctionMatrix(((TransferFunction(-x + y, y + z, x), TransferFunction(x**2 - y**3, y - z, x)), " \ "(TransferFunction(x**2 - y**3, y - z, x), TransferFunction(-x + y, y + z, x)))), " \ "TransferFunctionMatrix(((TransferFunction(x**2 - y**3, y - z, x), TransferFunction(-x + y, y + z, x)), "\ "(TransferFunction(-x + y, y + z, x), TransferFunction(x**2 - y**3, y - z, x)))), 1)") def test_TransferFunctionMatrix_str(): 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 str(TransferFunctionMatrix([[tf1], [tf2]])) == \ "TransferFunctionMatrix(((TransferFunction(x*y**2 - z, -t**3 + y**3, y),), (TransferFunction(x - y, x + y, y),)))" assert str(TransferFunctionMatrix([[tf1, tf2], [tf3, tf2]])) == \ "TransferFunctionMatrix(((TransferFunction(x*y**2 - z, -t**3 + y**3, y), TransferFunction(x - y, x + y, y)), (TransferFunction(t*x**2 - t**w*x + w, t - y, y), TransferFunction(x - y, x + y, y))))" def test_Quaternion_str_printer(): q = Quaternion(x, y, z, t) assert str(q) == "x + y*i + z*j + t*k" q = Quaternion(x,y,z,x*t) assert str(q) == "x + y*i + z*j + t*x*k" q = Quaternion(x,y,z,x+t) assert str(q) == "x + y*i + z*j + (t + x)*k" def test_Quantity_str(): assert sstr(second, abbrev=True) == "s" assert sstr(joule, abbrev=True) == "J" assert str(second) == "second" assert str(joule) == "joule" def test_wild_str(): # Check expressions containing Wild not causing infinite recursion w = Wild('x') assert str(w + 1) == 'x_ + 1' assert str(exp(2**w) + 5) == 'exp(2**x_) + 5' assert str(3*w + 1) == '3*x_ + 1' assert str(1/w + 1) == '1 + 1/x_' assert str(w**2 + 1) == 'x_**2 + 1' assert str(1/(1 - w)) == '1/(1 - x_)' def test_wild_matchpy(): from sympy.utilities.matchpy_connector import WildDot, WildPlus, WildStar matchpy = import_module("matchpy") if matchpy is None: return wd = WildDot('w_') wp = WildPlus('w__') ws = WildStar('w___') assert str(wd) == 'w_' assert str(wp) == 'w__' assert str(ws) == 'w___' assert str(wp/ws + 2**wd) == '2**w_ + w__/w___' assert str(sin(wd)*cos(wp)*sqrt(ws)) == 'sqrt(w___)*sin(w_)*cos(w__)' def test_zeta(): assert str(zeta(3)) == "zeta(3)" def test_issue_3101(): e = x - y a = str(e) b = str(e) assert a == b def test_issue_3103(): e = -2*sqrt(x) - y/sqrt(x)/2 assert str(e) not in ["(-2)*x**1/2(-1/2)*x**(-1/2)*y", "-2*x**1/2(-1/2)*x**(-1/2)*y", "-2*x**1/2-1/2*x**-1/2*w"] assert str(e) == "-2*sqrt(x) - y/(2*sqrt(x))" def test_issue_4021(): e = Integral(x, x) + 1 assert str(e) == 'Integral(x, x) + 1' def test_sstrrepr(): assert sstr('abc') == 'abc' assert sstrrepr('abc') == "'abc'" e = ['a', 'b', 'c', x] assert sstr(e) == "[a, b, c, x]" assert sstrrepr(e) == "['a', 'b', 'c', x]" def test_infinity(): assert sstr(oo*I) == "oo*I" def test_full_prec(): assert sstr(S("0.3"), full_prec=True) == "0.300000000000000" assert sstr(S("0.3"), full_prec="auto") == "0.300000000000000" assert sstr(S("0.3"), full_prec=False) == "0.3" assert sstr(S("0.3")*x, full_prec=True) in [ "0.300000000000000*x", "x*0.300000000000000" ] assert sstr(S("0.3")*x, full_prec="auto") in [ "0.3*x", "x*0.3" ] assert sstr(S("0.3")*x, full_prec=False) in [ "0.3*x", "x*0.3" ] def test_noncommutative(): A, B, C = symbols('A,B,C', commutative=False) assert sstr(A*B*C**-1) == "A*B*C**(-1)" assert sstr(C**-1*A*B) == "C**(-1)*A*B" assert sstr(A*C**-1*B) == "A*C**(-1)*B" assert sstr(sqrt(A)) == "sqrt(A)" assert sstr(1/sqrt(A)) == "A**(-1/2)" def test_empty_printer(): str_printer = StrPrinter() assert str_printer.emptyPrinter("foo") == "foo" assert str_printer.emptyPrinter(x*y) == "x*y" assert str_printer.emptyPrinter(32) == "32" def test_settings(): raises(TypeError, lambda: sstr(S(4), method="garbage")) def test_RandomDomain(): from sympy.stats import Normal, Die, Exponential, pspace, where X = Normal('x1', 0, 1) assert str(where(X > 0)) == "Domain: (0 < x1) & (x1 < oo)" D = Die('d1', 6) assert str(where(D > 4)) == "Domain: Eq(d1, 5) | Eq(d1, 6)" A = Exponential('a', 1) B = Exponential('b', 1) assert str(pspace(Tuple(A, B)).domain) == "Domain: (0 <= a) & (0 <= b) & (a < oo) & (b < oo)" def test_FiniteSet(): assert str(FiniteSet(*range(1, 51))) == ( '{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,' ' 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34,' ' 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50}' ) assert str(FiniteSet(*range(1, 6))) == '{1, 2, 3, 4, 5}' assert str(FiniteSet(*[x*y, x**2])) == '{x**2, x*y}' assert str(FiniteSet(FiniteSet(FiniteSet(x, y), 5), FiniteSet(x,y), 5) ) == 'FiniteSet(5, FiniteSet(5, {x, y}), {x, y})' def test_Partition(): assert str(Partition(FiniteSet(x, y), {z})) == 'Partition({z}, {x, y})' def test_UniversalSet(): assert str(S.UniversalSet) == 'UniversalSet' def test_PrettyPoly(): F = QQ.frac_field(x, y) R = QQ[x, y] assert sstr(F.convert(x/(x + y))) == sstr(x/(x + y)) assert sstr(R.convert(x + y)) == sstr(x + y) def test_categories(): from sympy.categories import (Object, NamedMorphism, IdentityMorphism, Category) A = Object("A") B = Object("B") f = NamedMorphism(A, B, "f") id_A = IdentityMorphism(A) K = Category("K") assert str(A) == 'Object("A")' assert str(f) == 'NamedMorphism(Object("A"), Object("B"), "f")' assert str(id_A) == 'IdentityMorphism(Object("A"))' assert str(K) == 'Category("K")' def test_Tr(): A, B = symbols('A B', commutative=False) t = Tr(A*B) assert str(t) == 'Tr(A*B)' def test_issue_6387(): assert str(factor(-3.0*z + 3)) == '-3.0*(1.0*z - 1.0)' def test_MatMul_MatAdd(): X, Y = MatrixSymbol("X", 2, 2), MatrixSymbol("Y", 2, 2) assert str(2*(X + Y)) == "2*X + 2*Y" assert str(I*X) == "I*X" assert str(-I*X) == "-I*X" assert str((1 + I)*X) == '(1 + I)*X' assert str(-(1 + I)*X) == '(-1 - I)*X' def test_MatrixSlice(): n = Symbol('n', integer=True) X = MatrixSymbol('X', n, n) Y = MatrixSymbol('Y', 10, 10) Z = MatrixSymbol('Z', 10, 10) assert str(MatrixSlice(X, (None, None, None), (None, None, None))) == 'X[:, :]' assert str(X[x:x + 1, y:y + 1]) == 'X[x:x + 1, y:y + 1]' assert str(X[x:x + 1:2, y:y + 1:2]) == 'X[x:x + 1:2, y:y + 1:2]' assert str(X[:x, y:]) == 'X[:x, y:]' assert str(X[:x, y:]) == 'X[:x, y:]' assert str(X[x:, :y]) == 'X[x:, :y]' assert str(X[x:y, z:w]) == 'X[x:y, z:w]' assert str(X[x:y:t, w:t:x]) == 'X[x:y:t, w:t:x]' assert str(X[x::y, t::w]) == 'X[x::y, t::w]' assert str(X[:x:y, :t:w]) == 'X[:x:y, :t:w]' assert str(X[::x, ::y]) == 'X[::x, ::y]' assert str(MatrixSlice(X, (0, None, None), (0, None, None))) == 'X[:, :]' assert str(MatrixSlice(X, (None, n, None), (None, n, None))) == 'X[:, :]' assert str(MatrixSlice(X, (0, n, None), (0, n, None))) == 'X[:, :]' assert str(MatrixSlice(X, (0, n, 2), (0, n, 2))) == 'X[::2, ::2]' assert str(X[1:2:3, 4:5:6]) == 'X[1:2:3, 4:5:6]' assert str(X[1:3:5, 4:6:8]) == 'X[1:3:5, 4:6:8]' assert str(X[1:10:2]) == 'X[1:10:2, :]' assert str(Y[:5, 1:9:2]) == 'Y[:5, 1:9:2]' assert str(Y[:5, 1:10:2]) == 'Y[:5, 1::2]' assert str(Y[5, :5:2]) == 'Y[5:6, :5:2]' assert str(X[0:1, 0:1]) == 'X[:1, :1]' assert str(X[0:1:2, 0:1:2]) == 'X[:1:2, :1:2]' assert str((Y + Z)[2:, 2:]) == '(Y + Z)[2:, 2:]' def test_true_false(): assert str(true) == repr(true) == sstr(true) == "True" assert str(false) == repr(false) == sstr(false) == "False" def test_Equivalent(): assert str(Equivalent(y, x)) == "Equivalent(x, y)" def test_Xor(): assert str(Xor(y, x, evaluate=False)) == "x ^ y" def test_Complement(): assert str(Complement(S.Reals, S.Naturals)) == 'Complement(Reals, Naturals)' def test_SymmetricDifference(): assert str(SymmetricDifference(Interval(2, 3), Interval(3, 4),evaluate=False)) == \ 'SymmetricDifference(Interval(2, 3), Interval(3, 4))' def test_UnevaluatedExpr(): a, b = symbols("a b") expr1 = 2*UnevaluatedExpr(a+b) assert str(expr1) == "2*(a + b)" def test_MatrixElement_printing(): # test cases for issue #11821 A = MatrixSymbol("A", 1, 3) B = MatrixSymbol("B", 1, 3) C = MatrixSymbol("C", 1, 3) assert(str(A[0, 0]) == "A[0, 0]") assert(str(3 * A[0, 0]) == "3*A[0, 0]") F = C[0, 0].subs(C, A - B) assert str(F) == "(A - B)[0, 0]" def test_MatrixSymbol_printing(): A = MatrixSymbol("A", 3, 3) B = MatrixSymbol("B", 3, 3) assert str(A - A*B - B) == "A - A*B - B" assert str(A*B - (A+B)) == "-A + A*B - B" assert str(A**(-1)) == "A**(-1)" assert str(A**3) == "A**3" def test_MatrixExpressions(): n = Symbol('n', integer=True) X = MatrixSymbol('X', n, n) assert str(X) == "X" # Apply function elementwise (`ElementwiseApplyFunc`): expr = (X.T*X).applyfunc(sin) assert str(expr) == 'Lambda(_d, sin(_d)).(X.T*X)' lamda = Lambda(x, 1/x) expr = (n*X).applyfunc(lamda) assert str(expr) == 'Lambda(x, 1/x).(n*X)' def test_Subs_printing(): assert str(Subs(x, (x,), (1,))) == 'Subs(x, x, 1)' assert str(Subs(x + y, (x, y), (1, 2))) == 'Subs(x + y, (x, y), (1, 2))' def test_issue_15716(): e = Integral(factorial(x), (x, -oo, oo)) assert e.as_terms() == ([(e, ((1.0, 0.0), (1,), ()))], [e]) def test_str_special_matrices(): from sympy.matrices import Identity, ZeroMatrix, OneMatrix assert str(Identity(4)) == 'I' assert str(ZeroMatrix(2, 2)) == '0' assert str(OneMatrix(2, 2)) == '1' def test_issue_14567(): assert factorial(Sum(-1, (x, 0, 0))) + y # doesn't raise an error def test_issue_21823(): assert str(Partition([1, 2])) == 'Partition({1, 2})' assert str(Partition({1, 2})) == 'Partition({1, 2})' def test_issue_22689(): assert str(Mul(Pow(x,-2, evaluate=False), Pow(3,-1,evaluate=False), evaluate=False)) == "1/(x**2*3)" def test_issue_21119_21460(): ss = lambda x: str(S(x, evaluate=False)) assert ss('4/2') == '4/2' assert ss('4/-2') == '4/(-2)' assert ss('-4/2') == '-4/2' assert ss('-4/-2') == '-4/(-2)' assert ss('-2*3/-1') == '-2*3/(-1)' assert ss('-2*3/-1/2') == '-2*3/(-1*2)' assert ss('4/2/1') == '4/(2*1)' assert ss('-2/-1/2') == '-2/(-1*2)' assert ss('2*3*4**(-2*3)') == '2*3/4**(2*3)' assert ss('2*3*1*4**(-2*3)') == '2*3*1/4**(2*3)' def test_Str(): from sympy.core.symbol import Str assert str(Str('x')) == 'x' assert sstrrepr(Str('x')) == "Str('x')" def test_diffgeom(): from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseScalarField x,y = symbols('x y', real=True) m = Manifold('M', 2) assert str(m) == "M" p = Patch('P', m) assert str(p) == "P" rect = CoordSystem('rect', p, [x, y]) assert str(rect) == "rect" b = BaseScalarField(rect, 0) assert str(b) == "x" def test_NDimArray(): assert sstr(NDimArray(1.0), full_prec=True) == '1.00000000000000' assert sstr(NDimArray(1.0), full_prec=False) == '1.0' assert sstr(NDimArray([1.0, 2.0]), full_prec=True) == '[1.00000000000000, 2.00000000000000]' assert sstr(NDimArray([1.0, 2.0]), full_prec=False) == '[1.0, 2.0]' def test_Predicate(): assert sstr(Q.even) == 'Q.even' def test_AppliedPredicate(): assert sstr(Q.even(x)) == 'Q.even(x)' def test_printing_str_array_expressions(): assert sstr(ArraySymbol("A", (2, 3, 4))) == "A" assert sstr(ArrayElement("A", (2, 1/(1-x), 0))) == "A[2, 1/(1 - x), 0]" M = MatrixSymbol("M", 3, 3) N = MatrixSymbol("N", 3, 3) assert sstr(ArrayElement(M*N, [x, 0])) == "(M*N)[x, 0]"
041b9869382141ed48afce3e536abd2e8272d5e076187863386aed3949d3a2dc
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)]) print("") print(NumExprPrinter().doprint(func_def)) expected = "def foo(x):\n"\ " y = numexpr.evaluate('x', truediv=True)\n"\ " return numexpr.evaluate('y**2', truediv=True)" print(expected) 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)"
411e6bf211f0e2e74e74cec6c19863bc543158611204d79fb8ee3e673f2f43a3
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, microgram, second 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" 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"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^{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" a1 = Function('a_1') assert latex(a1) == r"\operatorname{a_{1}}" assert latex(a1(x)) == r"\operatorname{a_{1}}{\left(x \right)}" # issue 5868 omega1 = Function('omega1') assert latex(omega1) == r"\omega_{1}" assert latex(omega1(x)) == r"\omega_{1}{\left(x \right)}" assert latex(sin(x)) == r"\sin{\left(x \right)}" assert latex(sin(x), fold_func_brackets=True) == r"\sin {x}" assert latex(sin(2*x**2), fold_func_brackets=True) == \ r"\sin {2 x^{2}}" assert latex(sin(x**2), fold_func_brackets=True) == \ r"\sin {x^{2}}" assert latex(asin(x)**2) == r"\operatorname{asin}^{2}{\left(x \right)}" assert latex(asin(x)**2, inv_trig_style="full") == \ r"\arcsin^{2}{\left(x \right)}" assert latex(asin(x)**2, inv_trig_style="power") == \ r"\sin^{-1}{\left(x \right)}^{2}" assert latex(asin(x**2), inv_trig_style="power", fold_func_brackets=True) == \ r"\sin^{-1} {x^{2}}" assert latex(acsc(x), inv_trig_style="full") == \ r"\operatorname{arccsc}{\left(x \right)}" assert latex(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) l = LatexPrinter() assert l._print(C - 2*B) in [r'- 2 B + C', r'C -2 B'] assert l._print(C + 2*B) in [r'2 B + C', r'C + 2 B'] assert l._print(B - 2*C) in [r'B - 2 C', r'- 2 C + B'] assert l._print(B + 2*C) in [r'B + 2 C', r'2 C + B'] def test_matMul(): A = MatrixSymbol('A', 5, 5) B = MatrixSymbol('B', 5, 5) x = Symbol('x') lp = LatexPrinter() assert lp._print_MatMul(2*A) == r'2 A' assert lp._print_MatMul(2*x*A) == r'2 x A' assert lp._print_MatMul(-2*A) == r'- 2 A' assert lp._print_MatMul(1.5*A) == r'1.5 A' assert lp._print_MatMul(sqrt(2)*A) == r'\sqrt{2} A' assert lp._print_MatMul(-sqrt(2)*A) == r'- \sqrt{2} A' assert lp._print_MatMul(2*sqrt(2)*x*A) == r'2 \sqrt{2} x A' assert lp._print_MatMul(-2*A*(A + 2*B)) in [r'- 2 A \left(A + 2 B\right)', r'- 2 A \left(2 B + A\right)'] def test_latex_MatrixSlice(): 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_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}' # 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}' # 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'A' assert latex(s(x)) == r'A{\left(x \right)}' s = Function('Beta') assert latex(s) == r'B' s = Function('Eta') assert latex(s) == r'H' assert latex(s(x)) == r'H{\left(x \right)}' # bug because sympy.core.numbers.Pi is special p = Function('Pi') # assert latex(p(x)) == r'\Pi{\left(x \right)}' assert latex(p) == r'\Pi' # bug because not all greeks are included c = Function('chi') assert latex(c(x)) == r'\chi{\left(x \right)}' assert latex(c) == r'\chi' def test_translate(): s = 'Alpha' assert translate(s) == r'A' s = 'Beta' assert translate(s) == r'B' s = 'Eta' assert translate(s) == r'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'A' assert latex(Symbol('Beta')) == r'B' assert latex(Symbol('Gamma')) == r'\Gamma' assert latex(Symbol('Delta')) == r'\Delta' assert latex(Symbol('Epsilon')) == r'E' assert latex(Symbol('Zeta')) == r'Z' assert latex(Symbol('Eta')) == r'H' assert latex(Symbol('Theta')) == r'\Theta' assert latex(Symbol('Iota')) == r'I' assert latex(Symbol('Kappa')) == r'K' assert latex(Symbol('Lambda')) == r'\Lambda' assert latex(Symbol('Mu')) == r'M' assert latex(Symbol('Nu')) == r'N' assert latex(Symbol('Xi')) == r'\Xi' assert latex(Symbol('Omicron')) == r'O' assert latex(Symbol('Pi')) == r'\Pi' assert latex(Symbol('Rho')) == r'P' assert latex(Symbol('Sigma')) == r'\Sigma' assert latex(Symbol('Tau')) == r'T' assert latex(Symbol('Upsilon')) == r'\Upsilon' assert latex(Symbol('Phi')) == r'\Phi' assert latex(Symbol('Chi')) == r'X' assert latex(Symbol('Psi')) == r'\Psi' assert latex(Symbol('Omega')) == r'\Omega' assert latex(Symbol('varepsilon')) == r'\varepsilon' assert latex(Symbol('varkappa')) == r'\varkappa' assert latex(Symbol('varphi')) == r'\varphi' assert latex(Symbol('varpi')) == r'\varpi' assert latex(Symbol('varrho')) == r'\varrho' assert latex(Symbol('varsigma')) == r'\varsigma' assert latex(Symbol('vartheta')) == r'\vartheta' def test_fancyset_symbols(): assert latex(S.Rationals) == 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"- x 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}}' 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}}"
4d8908cf20bd3144ce59c06cce1a3cecd36b0724222264687c6b8bc4ea37b84d
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') 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-22 def test_log1p(): if not np: skip("NumPy not installed") f = lambdify((a,), log1p(a), 'numpy') assert abs(f(1e-99) - 1e-99) < 1e-100 def test_hypot(): if not np: skip("NumPy not installed") assert abs(lambdify((a, b), hypot(a, b), 'numpy')(3, 4) - 5) < 1e-16 def test_log10(): if not np: skip("NumPy not installed") assert abs(lambdify((a,), log10(a), 'numpy')(100) - 2) < 1e-16 def test_exp2(): if not np: skip("NumPy not installed") assert abs(lambdify((a,), exp2(a), 'numpy')(5) - 32) < 1e-16 def test_log2(): if not np: skip("NumPy not installed") assert abs(lambdify((a,), log2(a), 'numpy')(256) - 8) < 1e-16 def test_Sqrt(): if not np: skip("NumPy not installed") assert abs(lambdify((a,), Sqrt(a), 'numpy')(4) - 2) < 1e-16 def test_sqrt(): if not np: skip("NumPy not installed") assert abs(lambdify((a,), sqrt(a), 'numpy')(4) - 2) < 1e-16 def test_matsolve(): if not np: skip("NumPy not installed") M = MatrixSymbol("M", 3, 3) x = MatrixSymbol("x", 3, 1) expr = M**(-1) * x + x matsolve_expr = MatrixSolve(M, x) + x f = lambdify((M, x), expr) f_matsolve = lambdify((M, x), matsolve_expr) m0 = np.array([[1, 2, 3], [3, 2, 5], [5, 6, 7]]) assert np.linalg.matrix_rank(m0) == 3 x0 = np.array([3, 4, 5]) assert np.allclose(f_matsolve(m0, x0), f(m0, x0)) def test_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')
7dc4368287cafc8b5cf73b785e7ef78e4b66804fd2c2d4c728bb35e08e556df6
# -*- coding: utf-8 -*- from sympy.concrete.products import Product 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 (Derivative, Function, Lambda, Subs) from sympy.core.mul import Mul from sympy.core import (EulerGamma, GoldenRatio, Catalan) from sympy.core.numbers import (I, Rational, oo, pi) from sympy.core.power import Pow from sympy.core.relational import (Eq, Ge, Gt, Le, Lt, Ne) from sympy.core.singleton import S from sympy.core.symbol import (Symbol, symbols) from sympy.functions.elementary.complexes import conjugate from sympy.functions.elementary.exponential import LambertW from sympy.functions.special.bessel import (airyai, airyaiprime, airybi, airybiprime) from sympy.functions.special.delta_functions import Heaviside from sympy.functions.special.error_functions import (fresnelc, fresnels) from sympy.functions.special.singularity_functions import SingularityFunction from sympy.functions.special.zeta_functions import dirichlet_eta from sympy.geometry.line import (Ray, Segment) from sympy.integrals.integrals import Integral from sympy.logic.boolalg import (And, Equivalent, ITE, Implies, Nand, Nor, Not, Or, Xor) from sympy.matrices.dense import (Matrix, diag) from sympy.matrices.expressions.slice import MatrixSlice from sympy.matrices.expressions.trace import Trace from sympy.polys.domains.finitefield import FF from sympy.polys.domains.integerring import ZZ from sympy.polys.domains.rationalfield import QQ from sympy.polys.domains.realfield import RR from sympy.polys.orderings import (grlex, ilex) from sympy.polys.polytools import groebner 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 O from sympy.series.sequences import (SeqAdd, SeqFormula, SeqMul, SeqPer) from sympy.sets.contains import Contains from sympy.sets.fancysets import Range from sympy.sets.sets import (Complement, FiniteSet, Intersection, Interval, Union) from sympy.codegen.ast import (Assignment, AddAugmentedAssignment, SubAugmentedAssignment, MulAugmentedAssignment, DivAugmentedAssignment, ModAugmentedAssignment) from sympy.core.expr import UnevaluatedExpr from sympy.physics.quantum.trace import Tr from sympy.functions import (Abs, Chi, Ci, Ei, KroneckerDelta, Piecewise, Shi, Si, atan2, beta, binomial, catalan, ceiling, cos, euler, exp, expint, factorial, factorial2, floor, gamma, hyper, log, meijerg, sin, sqrt, subfactorial, tan, uppergamma, lerchphi, elliptic_k, elliptic_f, elliptic_e, elliptic_pi, DiracDelta, bell, bernoulli, fibonacci, tribonacci, lucas, stieltjes, mathieuc, mathieus, mathieusprime, mathieucprime) from sympy.matrices import Adjoint, Inverse, MatrixSymbol, Transpose, KroneckerProduct from sympy.matrices.expressions import hadamard_power from sympy.physics import mechanics from sympy.physics.control.lti import (TransferFunction, Feedback, TransferFunctionMatrix, Series, Parallel, MIMOSeries, MIMOParallel, MIMOFeedback) from sympy.physics.units import joule, degree from sympy.printing.pretty import pprint, pretty as xpretty from sympy.printing.pretty.pretty_symbology import center_accent, is_combining from sympy.sets.conditionset import ConditionSet from sympy.sets import ImageSet, 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, MutableDenseNDimArray, MutableSparseNDimArray, tensorproduct) from sympy.tensor.functions import TensorProduct from sympy.tensor.tensor import (TensorIndexType, tensor_indices, TensorHead, TensorElement, tensor_heads) from sympy.testing.pytest import raises, _both_exp_pow, warns_deprecated_sympy from sympy.vector import CoordSys3D, Gradient, Curl, Divergence, Dot, Cross, Laplacian import sympy as sym class lowergamma(sym.lowergamma): pass # testing notation inheritance by a subclass with same name a, b, c, d, x, y, z, k, n, s, p = symbols('a,b,c,d,x,y,z,k,n,s,p') f = Function("f") th = Symbol('theta') ph = Symbol('phi') """ Expressions whose pretty-printing is tested here: (A '#' to the right of an expression indicates that its various acceptable orderings are accounted for by the tests.) BASIC EXPRESSIONS: oo (x**2) 1/x y*x**-2 x**Rational(-5,2) (-2)**x Pow(3, 1, evaluate=False) (x**2 + x + 1) # 1-x # 1-2*x # x/y -x/y (x+2)/y # (1+x)*y #3 -5*x/(x+10) # correct placement of negative sign 1 - Rational(3,2)*(x+1) -(-x + 5)*(-x - 2*sqrt(2) + 5) - (-y + 5)*(-y + 5) # issue 5524 ORDERING: x**2 + x + 1 1 - x 1 - 2*x 2*x**4 + y**2 - x**2 + y**3 RELATIONAL: Eq(x, y) Lt(x, y) Gt(x, y) Le(x, y) Ge(x, y) Ne(x/(y+1), y**2) # RATIONAL NUMBERS: y*x**-2 y**Rational(3,2) * x**Rational(-5,2) sin(x)**3/tan(x)**2 FUNCTIONS (ABS, CONJ, EXP, FUNCTION BRACES, FACTORIAL, FLOOR, CEILING): (2*x + exp(x)) # Abs(x) Abs(x/(x**2+1)) # Abs(1 / (y - Abs(x))) factorial(n) factorial(2*n) subfactorial(n) subfactorial(2*n) factorial(factorial(factorial(n))) factorial(n+1) # conjugate(x) conjugate(f(x+1)) # f(x) f(x, y) f(x/(y+1), y) # f(x**x**x**x**x**x) sin(x)**2 conjugate(a+b*I) conjugate(exp(a+b*I)) conjugate( f(1 + conjugate(f(x))) ) # f(x/(y+1), y) # denom of first arg floor(1 / (y - floor(x))) ceiling(1 / (y - ceiling(x))) SQRT: sqrt(2) 2**Rational(1,3) 2**Rational(1,1000) sqrt(x**2 + 1) (1 + sqrt(5))**Rational(1,3) 2**(1/x) sqrt(2+pi) (2+(1+x**2)/(2+x))**Rational(1,4)+(1+x**Rational(1,1000))/sqrt(3+x**2) DERIVATIVES: Derivative(log(x), x, evaluate=False) Derivative(log(x), x, evaluate=False) + x # Derivative(log(x) + x**2, x, y, evaluate=False) Derivative(2*x*y, y, x, evaluate=False) + x**2 # beta(alpha).diff(alpha) INTEGRALS: Integral(log(x), x) Integral(x**2, x) Integral((sin(x))**2 / (tan(x))**2) Integral(x**(2**x), x) Integral(x**2, (x,1,2)) Integral(x**2, (x,Rational(1,2),10)) Integral(x**2*y**2, x,y) Integral(x**2, (x, None, 1)) Integral(x**2, (x, 1, None)) Integral(sin(th)/cos(ph), (th,0,pi), (ph, 0, 2*pi)) MATRICES: Matrix([[x**2+1, 1], [y, x+y]]) # Matrix([[x/y, y, th], [0, exp(I*k*ph), 1]]) PIECEWISE: Piecewise((x,x<1),(x**2,True)) ITE: ITE(x, y, z) SEQUENCES (TUPLES, LISTS, DICTIONARIES): () [] {} (1/x,) [x**2, 1/x, x, y, sin(th)**2/cos(ph)**2] (x**2, 1/x, x, y, sin(th)**2/cos(ph)**2) {x: sin(x)} {1/x: 1/y, x: sin(x)**2} # [x**2] (x**2,) {x**2: 1} LIMITS: Limit(x, x, oo) Limit(x**2, x, 0) Limit(1/x, x, 0) Limit(sin(x)/x, x, 0) UNITS: joule => kg*m**2/s SUBS: Subs(f(x), x, ph**2) Subs(f(x).diff(x), x, 0) Subs(f(x).diff(x)/y, (x, y), (0, Rational(1, 2))) ORDER: O(1) O(1/x) O(x**2 + y**2) """ def pretty(expr, order=None): """ASCII pretty-printing""" return xpretty(expr, order=order, use_unicode=False, wrap_line=False) def upretty(expr, order=None): """Unicode pretty-printing""" return xpretty(expr, order=order, use_unicode=True, wrap_line=False) def test_pretty_ascii_str(): assert pretty( 'xxx' ) == 'xxx' assert pretty( "xxx" ) == 'xxx' assert pretty( 'xxx\'xxx' ) == 'xxx\'xxx' assert pretty( 'xxx"xxx' ) == 'xxx\"xxx' assert pretty( 'xxx\"xxx' ) == 'xxx\"xxx' assert pretty( "xxx'xxx" ) == 'xxx\'xxx' assert pretty( "xxx\'xxx" ) == 'xxx\'xxx' assert pretty( "xxx\"xxx" ) == 'xxx\"xxx' assert pretty( "xxx\"xxx\'xxx" ) == 'xxx"xxx\'xxx' assert pretty( "xxx\nxxx" ) == 'xxx\nxxx' def test_pretty_unicode_str(): assert pretty( 'xxx' ) == 'xxx' assert pretty( 'xxx' ) == 'xxx' assert pretty( 'xxx\'xxx' ) == 'xxx\'xxx' assert pretty( 'xxx"xxx' ) == 'xxx\"xxx' assert pretty( 'xxx\"xxx' ) == 'xxx\"xxx' assert pretty( "xxx'xxx" ) == 'xxx\'xxx' assert pretty( "xxx\'xxx" ) == 'xxx\'xxx' assert pretty( "xxx\"xxx" ) == 'xxx\"xxx' assert pretty( "xxx\"xxx\'xxx" ) == 'xxx"xxx\'xxx' assert pretty( "xxx\nxxx" ) == 'xxx\nxxx' def test_upretty_greek(): assert upretty( oo ) == '∞' assert upretty( Symbol('alpha^+_1') ) == 'α⁺₁' assert upretty( Symbol('beta') ) == 'β' assert upretty(Symbol('lambda')) == 'λ' def test_upretty_multiindex(): assert upretty( Symbol('beta12') ) == 'β₁₂' assert upretty( Symbol('Y00') ) == 'Y₀₀' assert upretty( Symbol('Y_00') ) == 'Y₀₀' assert upretty( Symbol('F^+-') ) == 'F⁺⁻' def test_upretty_sub_super(): assert upretty( Symbol('beta_1_2') ) == 'β₁ ₂' assert upretty( Symbol('beta^1^2') ) == 'β¹ ²' assert upretty( Symbol('beta_1^2') ) == 'β²₁' assert upretty( Symbol('beta_10_20') ) == 'β₁₀ ₂₀' assert upretty( Symbol('beta_ax_gamma^i') ) == 'βⁱₐₓ ᵧ' assert upretty( Symbol("F^1^2_3_4") ) == 'F¹ ²₃ ₄' assert upretty( Symbol("F_1_2^3^4") ) == 'F³ ⁴₁ ₂' assert upretty( Symbol("F_1_2_3_4") ) == 'F₁ ₂ ₃ ₄' assert upretty( Symbol("F^1^2^3^4") ) == 'F¹ ² ³ ⁴' def test_upretty_subs_missing_in_24(): assert upretty( Symbol('F_beta') ) == 'Fᵦ' assert upretty( Symbol('F_gamma') ) == 'Fᵧ' assert upretty( Symbol('F_rho') ) == 'Fᵨ' assert upretty( Symbol('F_phi') ) == 'Fᵩ' assert upretty( Symbol('F_chi') ) == 'Fᵪ' assert upretty( Symbol('F_a') ) == 'Fₐ' assert upretty( Symbol('F_e') ) == 'Fₑ' assert upretty( Symbol('F_i') ) == 'Fᵢ' assert upretty( Symbol('F_o') ) == 'Fₒ' assert upretty( Symbol('F_u') ) == 'Fᵤ' assert upretty( Symbol('F_r') ) == 'Fᵣ' assert upretty( Symbol('F_v') ) == 'Fᵥ' assert upretty( Symbol('F_x') ) == 'Fₓ' def test_missing_in_2X_issue_9047(): assert upretty( Symbol('F_h') ) == 'Fₕ' assert upretty( Symbol('F_k') ) == 'Fₖ' assert upretty( Symbol('F_l') ) == 'Fₗ' assert upretty( Symbol('F_m') ) == 'Fₘ' assert upretty( Symbol('F_n') ) == 'Fₙ' assert upretty( Symbol('F_p') ) == 'Fₚ' assert upretty( Symbol('F_s') ) == 'Fₛ' assert upretty( Symbol('F_t') ) == 'Fₜ' def test_upretty_modifiers(): # Accents assert upretty( Symbol('Fmathring') ) == 'F̊' assert upretty( Symbol('Fddddot') ) == 'F⃜' assert upretty( Symbol('Fdddot') ) == 'F⃛' assert upretty( Symbol('Fddot') ) == 'F̈' assert upretty( Symbol('Fdot') ) == 'Ḟ' assert upretty( Symbol('Fcheck') ) == 'F̌' assert upretty( Symbol('Fbreve') ) == 'F̆' assert upretty( Symbol('Facute') ) == 'F́' assert upretty( Symbol('Fgrave') ) == 'F̀' assert upretty( Symbol('Ftilde') ) == 'F̃' assert upretty( Symbol('Fhat') ) == 'F̂' assert upretty( Symbol('Fbar') ) == 'F̅' assert upretty( Symbol('Fvec') ) == 'F⃗' assert upretty( Symbol('Fprime') ) == 'F′' assert upretty( Symbol('Fprm') ) == 'F′' # No faces are actually implemented, but test to make sure the modifiers are stripped assert upretty( Symbol('Fbold') ) == 'Fbold' assert upretty( Symbol('Fbm') ) == 'Fbm' assert upretty( Symbol('Fcal') ) == 'Fcal' assert upretty( Symbol('Fscr') ) == 'Fscr' assert upretty( Symbol('Ffrak') ) == 'Ffrak' # Brackets assert upretty( Symbol('Fnorm') ) == '‖F‖' assert upretty( Symbol('Favg') ) == '⟨F⟩' assert upretty( Symbol('Fabs') ) == '|F|' assert upretty( Symbol('Fmag') ) == '|F|' # Combinations assert upretty( Symbol('xvecdot') ) == 'x⃗̇' assert upretty( Symbol('xDotVec') ) == 'ẋ⃗' assert upretty( Symbol('xHATNorm') ) == '‖x̂‖' assert upretty( Symbol('xMathring_yCheckPRM__zbreveAbs') ) == 'x̊_y̌′__|z̆|' assert upretty( Symbol('alphadothat_nVECDOT__tTildePrime') ) == 'α̇̂_n⃗̇__t̃′' assert upretty( Symbol('x_dot') ) == 'x_dot' assert upretty( Symbol('x__dot') ) == 'x__dot' def test_pretty_Cycle(): from sympy.combinatorics.permutations import Cycle assert pretty(Cycle(1, 2)) == '(1 2)' assert pretty(Cycle(2)) == '(2)' assert pretty(Cycle(1, 3)(4, 5)) == '(1 3)(4 5)' assert pretty(Cycle()) == '()' def test_pretty_Permutation(): from sympy.combinatorics.permutations import Permutation p1 = Permutation(1, 2)(3, 4) assert xpretty(p1, perm_cyclic=True, use_unicode=True) == "(1 2)(3 4)" assert xpretty(p1, perm_cyclic=True, use_unicode=False) == "(1 2)(3 4)" assert xpretty(p1, perm_cyclic=False, use_unicode=True) == \ '⎛0 1 2 3 4⎞\n'\ '⎝0 2 1 4 3⎠' assert xpretty(p1, perm_cyclic=False, use_unicode=False) == \ "/0 1 2 3 4\\\n"\ "\\0 2 1 4 3/" with warns_deprecated_sympy(): old_print_cyclic = Permutation.print_cyclic Permutation.print_cyclic = False assert xpretty(p1, use_unicode=True) == \ '⎛0 1 2 3 4⎞\n'\ '⎝0 2 1 4 3⎠' assert xpretty(p1, use_unicode=False) == \ "/0 1 2 3 4\\\n"\ "\\0 2 1 4 3/" Permutation.print_cyclic = old_print_cyclic def test_pretty_basic(): assert pretty( -Rational(1)/2 ) == '-1/2' assert pretty( -Rational(13)/22 ) == \ """\ -13 \n\ ----\n\ 22 \ """ expr = oo ascii_str = \ """\ oo\ """ ucode_str = \ """\ ∞\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = (x**2) ascii_str = \ """\ 2\n\ x \ """ ucode_str = \ """\ 2\n\ x \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = 1/x ascii_str = \ """\ 1\n\ -\n\ x\ """ ucode_str = \ """\ 1\n\ ─\n\ x\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str # not the same as 1/x expr = x**-1.0 ascii_str = \ """\ -1.0\n\ x \ """ ucode_str = \ """\ -1.0\n\ x \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str # see issue #2860 expr = Pow(S(2), -1.0, evaluate=False) ascii_str = \ """\ -1.0\n\ 2 \ """ ucode_str = \ """\ -1.0\n\ 2 \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = y*x**-2 ascii_str = \ """\ y \n\ --\n\ 2\n\ x \ """ ucode_str = \ """\ y \n\ ──\n\ 2\n\ x \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str #see issue #14033 expr = x**Rational(1, 3) ascii_str = \ """\ 1/3\n\ x \ """ ucode_str = \ """\ 1/3\n\ x \ """ assert xpretty(expr, use_unicode=False, wrap_line=False,\ root_notation = False) == ascii_str assert xpretty(expr, use_unicode=True, wrap_line=False,\ root_notation = False) == ucode_str expr = x**Rational(-5, 2) ascii_str = \ """\ 1 \n\ ----\n\ 5/2\n\ x \ """ ucode_str = \ """\ 1 \n\ ────\n\ 5/2\n\ x \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = (-2)**x ascii_str = \ """\ x\n\ (-2) \ """ ucode_str = \ """\ x\n\ (-2) \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str # See issue 4923 expr = Pow(3, 1, evaluate=False) ascii_str = \ """\ 1\n\ 3 \ """ ucode_str = \ """\ 1\n\ 3 \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = (x**2 + x + 1) ascii_str_1 = \ """\ 2\n\ 1 + x + x \ """ ascii_str_2 = \ """\ 2 \n\ x + x + 1\ """ ascii_str_3 = \ """\ 2 \n\ x + 1 + x\ """ ucode_str_1 = \ """\ 2\n\ 1 + x + x \ """ ucode_str_2 = \ """\ 2 \n\ x + x + 1\ """ ucode_str_3 = \ """\ 2 \n\ x + 1 + x\ """ assert pretty(expr) in [ascii_str_1, ascii_str_2, ascii_str_3] assert upretty(expr) in [ucode_str_1, ucode_str_2, ucode_str_3] expr = 1 - x ascii_str_1 = \ """\ 1 - x\ """ ascii_str_2 = \ """\ -x + 1\ """ ucode_str_1 = \ """\ 1 - x\ """ ucode_str_2 = \ """\ -x + 1\ """ assert pretty(expr) in [ascii_str_1, ascii_str_2] assert upretty(expr) in [ucode_str_1, ucode_str_2] expr = 1 - 2*x ascii_str_1 = \ """\ 1 - 2*x\ """ ascii_str_2 = \ """\ -2*x + 1\ """ ucode_str_1 = \ """\ 1 - 2⋅x\ """ ucode_str_2 = \ """\ -2⋅x + 1\ """ assert pretty(expr) in [ascii_str_1, ascii_str_2] assert upretty(expr) in [ucode_str_1, ucode_str_2] expr = x/y ascii_str = \ """\ x\n\ -\n\ y\ """ ucode_str = \ """\ x\n\ ─\n\ y\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = -x/y ascii_str = \ """\ -x \n\ ---\n\ y \ """ ucode_str = \ """\ -x \n\ ───\n\ y \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = (x + 2)/y ascii_str_1 = \ """\ 2 + x\n\ -----\n\ y \ """ ascii_str_2 = \ """\ x + 2\n\ -----\n\ y \ """ ucode_str_1 = \ """\ 2 + x\n\ ─────\n\ y \ """ ucode_str_2 = \ """\ x + 2\n\ ─────\n\ y \ """ assert pretty(expr) in [ascii_str_1, ascii_str_2] assert upretty(expr) in [ucode_str_1, ucode_str_2] expr = (1 + x)*y ascii_str_1 = \ """\ y*(1 + x)\ """ ascii_str_2 = \ """\ (1 + x)*y\ """ ascii_str_3 = \ """\ y*(x + 1)\ """ ucode_str_1 = \ """\ y⋅(1 + x)\ """ ucode_str_2 = \ """\ (1 + x)⋅y\ """ ucode_str_3 = \ """\ y⋅(x + 1)\ """ assert pretty(expr) in [ascii_str_1, ascii_str_2, ascii_str_3] assert upretty(expr) in [ucode_str_1, ucode_str_2, ucode_str_3] # Test for correct placement of the negative sign expr = -5*x/(x + 10) ascii_str_1 = \ """\ -5*x \n\ ------\n\ 10 + x\ """ ascii_str_2 = \ """\ -5*x \n\ ------\n\ x + 10\ """ ucode_str_1 = \ """\ -5⋅x \n\ ──────\n\ 10 + x\ """ ucode_str_2 = \ """\ -5⋅x \n\ ──────\n\ x + 10\ """ assert pretty(expr) in [ascii_str_1, ascii_str_2] assert upretty(expr) in [ucode_str_1, ucode_str_2] expr = -S.Half - 3*x ascii_str = \ """\ -3*x - 1/2\ """ ucode_str = \ """\ -3⋅x - 1/2\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = S.Half - 3*x ascii_str = \ """\ 1/2 - 3*x\ """ ucode_str = \ """\ 1/2 - 3⋅x\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = -S.Half - 3*x/2 ascii_str = \ """\ 3*x 1\n\ - --- - -\n\ 2 2\ """ ucode_str = \ """\ 3⋅x 1\n\ - ─── - ─\n\ 2 2\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = S.Half - 3*x/2 ascii_str = \ """\ 1 3*x\n\ - - ---\n\ 2 2 \ """ ucode_str = \ """\ 1 3⋅x\n\ ─ - ───\n\ 2 2 \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_negative_fractions(): expr = -x/y ascii_str =\ """\ -x \n\ ---\n\ y \ """ ucode_str =\ """\ -x \n\ ───\n\ y \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = -x*z/y ascii_str =\ """\ -x*z \n\ -----\n\ y \ """ ucode_str =\ """\ -x⋅z \n\ ─────\n\ y \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = x**2/y ascii_str =\ """\ 2\n\ x \n\ --\n\ y \ """ ucode_str =\ """\ 2\n\ x \n\ ──\n\ y \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = -x**2/y ascii_str =\ """\ 2 \n\ -x \n\ ----\n\ y \ """ ucode_str =\ """\ 2 \n\ -x \n\ ────\n\ y \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = -x/(y*z) ascii_str =\ """\ -x \n\ ---\n\ y*z\ """ ucode_str =\ """\ -x \n\ ───\n\ y⋅z\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = -a/y**2 ascii_str =\ """\ -a \n\ ---\n\ 2\n\ y \ """ ucode_str =\ """\ -a \n\ ───\n\ 2\n\ y \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = y**(-a/b) ascii_str =\ """\ -a \n\ ---\n\ b \n\ y \ """ ucode_str =\ """\ -a \n\ ───\n\ b \n\ y \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = -1/y**2 ascii_str =\ """\ -1 \n\ ---\n\ 2\n\ y \ """ ucode_str =\ """\ -1 \n\ ───\n\ 2\n\ y \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = -10/b**2 ascii_str =\ """\ -10 \n\ ----\n\ 2 \n\ b \ """ ucode_str =\ """\ -10 \n\ ────\n\ 2 \n\ b \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Rational(-200, 37) ascii_str =\ """\ -200 \n\ -----\n\ 37 \ """ ucode_str =\ """\ -200 \n\ ─────\n\ 37 \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_Mul(): expr = Mul(0, 1, evaluate=False) assert pretty(expr) == "0*1" assert upretty(expr) == "0⋅1" expr = Mul(1, 0, evaluate=False) assert pretty(expr) == "1*0" assert upretty(expr) == "1⋅0" expr = Mul(1, 1, evaluate=False) assert pretty(expr) == "1*1" assert upretty(expr) == "1⋅1" expr = Mul(1, 1, 1, evaluate=False) assert pretty(expr) == "1*1*1" assert upretty(expr) == "1⋅1⋅1" expr = Mul(1, 2, evaluate=False) assert pretty(expr) == "1*2" assert upretty(expr) == "1⋅2" expr = Add(0, 1, evaluate=False) assert pretty(expr) == "0 + 1" assert upretty(expr) == "0 + 1" expr = Mul(1, 1, 2, evaluate=False) assert pretty(expr) == "1*1*2" assert upretty(expr) == "1⋅1⋅2" expr = Add(0, 0, 1, evaluate=False) assert pretty(expr) == "0 + 0 + 1" assert upretty(expr) == "0 + 0 + 1" expr = Mul(1, -1, evaluate=False) assert pretty(expr) == "1*-1" assert upretty(expr) == "1⋅-1" expr = Mul(1.0, x, evaluate=False) assert pretty(expr) == "1.0*x" assert upretty(expr) == "1.0⋅x" expr = Mul(1, 1, 2, 3, x, evaluate=False) assert pretty(expr) == "1*1*2*3*x" assert upretty(expr) == "1⋅1⋅2⋅3⋅x" expr = Mul(-1, 1, evaluate=False) assert pretty(expr) == "-1*1" assert upretty(expr) == "-1⋅1" expr = Mul(4, 3, 2, 1, 0, y, x, evaluate=False) assert pretty(expr) == "4*3*2*1*0*y*x" assert upretty(expr) == "4⋅3⋅2⋅1⋅0⋅y⋅x" expr = Mul(4, 3, 2, 1+z, 0, y, x, evaluate=False) assert pretty(expr) == "4*3*2*(z + 1)*0*y*x" assert upretty(expr) == "4⋅3⋅2⋅(z + 1)⋅0⋅y⋅x" expr = Mul(Rational(2, 3), Rational(5, 7), evaluate=False) assert pretty(expr) == "2/3*5/7" assert upretty(expr) == "2/3⋅5/7" expr = Mul(x + y, Rational(1, 2), evaluate=False) assert pretty(expr) == "(x + y)*1/2" assert upretty(expr) == "(x + y)⋅1/2" expr = Mul(Rational(1, 2), x + y, evaluate=False) assert pretty(expr) == "x + y\n-----\n 2 " assert upretty(expr) == "x + y\n─────\n 2 " expr = Mul(S.One, x + y, evaluate=False) assert pretty(expr) == "1*(x + y)" assert upretty(expr) == "1⋅(x + y)" expr = Mul(x - y, S.One, evaluate=False) assert pretty(expr) == "(x - y)*1" assert upretty(expr) == "(x - y)⋅1" expr = Mul(Rational(1, 2), x - y, S.One, x + y, evaluate=False) assert pretty(expr) == "1/2*(x - y)*1*(x + y)" assert upretty(expr) == "1/2⋅(x - y)⋅1⋅(x + y)" expr = Mul(x + y, Rational(3, 4), S.One, y - z, evaluate=False) assert pretty(expr) == "(x + y)*3/4*1*(y - z)" assert upretty(expr) == "(x + y)⋅3/4⋅1⋅(y - z)" expr = Mul(x + y, Rational(1, 1), Rational(3, 4), Rational(5, 6),evaluate=False) assert pretty(expr) == "(x + y)*1*3/4*5/6" assert upretty(expr) == "(x + y)⋅1⋅3/4⋅5/6" expr = Mul(Rational(3, 4), x + y, S.One, y - z, evaluate=False) assert pretty(expr) == "3/4*(x + y)*1*(y - z)" assert upretty(expr) == "3/4⋅(x + y)⋅1⋅(y - z)" def test_issue_5524(): assert pretty(-(-x + 5)*(-x - 2*sqrt(2) + 5) - (-y + 5)*(-y + 5)) == \ """\ 2 / ___ \\\n\ - (5 - y) + (x - 5)*\\-x - 2*\\/ 2 + 5/\ """ assert upretty(-(-x + 5)*(-x - 2*sqrt(2) + 5) - (-y + 5)*(-y + 5)) == \ """\ 2 \n\ - (5 - y) + (x - 5)⋅(-x - 2⋅√2 + 5)\ """ def test_pretty_ordering(): assert pretty(x**2 + x + 1, order='lex') == \ """\ 2 \n\ x + x + 1\ """ assert pretty(x**2 + x + 1, order='rev-lex') == \ """\ 2\n\ 1 + x + x \ """ assert pretty(1 - x, order='lex') == '-x + 1' assert pretty(1 - x, order='rev-lex') == '1 - x' assert pretty(1 - 2*x, order='lex') == '-2*x + 1' assert pretty(1 - 2*x, order='rev-lex') == '1 - 2*x' f = 2*x**4 + y**2 - x**2 + y**3 assert pretty(f, order=None) == \ """\ 4 2 3 2\n\ 2*x - x + y + y \ """ assert pretty(f, order='lex') == \ """\ 4 2 3 2\n\ 2*x - x + y + y \ """ assert pretty(f, order='rev-lex') == \ """\ 2 3 2 4\n\ y + y - x + 2*x \ """ expr = x - x**3/6 + x**5/120 + O(x**6) ascii_str = \ """\ 3 5 \n\ x x / 6\\\n\ x - -- + --- + O\\x /\n\ 6 120 \ """ ucode_str = \ """\ 3 5 \n\ x x ⎛ 6⎞\n\ x - ── + ─── + O⎝x ⎠\n\ 6 120 \ """ assert pretty(expr, order=None) == ascii_str assert upretty(expr, order=None) == ucode_str assert pretty(expr, order='lex') == ascii_str assert upretty(expr, order='lex') == ucode_str assert pretty(expr, order='rev-lex') == ascii_str assert upretty(expr, order='rev-lex') == ucode_str def test_EulerGamma(): assert pretty(EulerGamma) == str(EulerGamma) == "EulerGamma" assert upretty(EulerGamma) == "γ" def test_GoldenRatio(): assert pretty(GoldenRatio) == str(GoldenRatio) == "GoldenRatio" assert upretty(GoldenRatio) == "φ" def test_Catalan(): assert pretty(Catalan) == upretty(Catalan) == "G" def test_pretty_relational(): expr = Eq(x, y) ascii_str = \ """\ x = y\ """ ucode_str = \ """\ x = y\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Lt(x, y) ascii_str = \ """\ x < y\ """ ucode_str = \ """\ x < y\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Gt(x, y) ascii_str = \ """\ x > y\ """ ucode_str = \ """\ x > y\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Le(x, y) ascii_str = \ """\ x <= y\ """ ucode_str = \ """\ x ≤ y\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Ge(x, y) ascii_str = \ """\ x >= y\ """ ucode_str = \ """\ x ≥ y\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Ne(x/(y + 1), y**2) ascii_str_1 = \ """\ x 2\n\ ----- != y \n\ 1 + y \ """ ascii_str_2 = \ """\ x 2\n\ ----- != y \n\ y + 1 \ """ ucode_str_1 = \ """\ x 2\n\ ───── ≠ y \n\ 1 + y \ """ ucode_str_2 = \ """\ x 2\n\ ───── ≠ y \n\ y + 1 \ """ assert pretty(expr) in [ascii_str_1, ascii_str_2] assert upretty(expr) in [ucode_str_1, ucode_str_2] def test_Assignment(): expr = Assignment(x, y) ascii_str = \ """\ x := y\ """ ucode_str = \ """\ x := y\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_AugmentedAssignment(): expr = AddAugmentedAssignment(x, y) ascii_str = \ """\ x += y\ """ ucode_str = \ """\ x += y\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = SubAugmentedAssignment(x, y) ascii_str = \ """\ x -= y\ """ ucode_str = \ """\ x -= y\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = MulAugmentedAssignment(x, y) ascii_str = \ """\ x *= y\ """ ucode_str = \ """\ x *= y\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = DivAugmentedAssignment(x, y) ascii_str = \ """\ x /= y\ """ ucode_str = \ """\ x /= y\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = ModAugmentedAssignment(x, y) ascii_str = \ """\ x %= y\ """ ucode_str = \ """\ x %= y\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_pretty_rational(): expr = y*x**-2 ascii_str = \ """\ y \n\ --\n\ 2\n\ x \ """ ucode_str = \ """\ y \n\ ──\n\ 2\n\ x \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = y**Rational(3, 2) * x**Rational(-5, 2) ascii_str = \ """\ 3/2\n\ y \n\ ----\n\ 5/2\n\ x \ """ ucode_str = \ """\ 3/2\n\ y \n\ ────\n\ 5/2\n\ x \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = sin(x)**3/tan(x)**2 ascii_str = \ """\ 3 \n\ sin (x)\n\ -------\n\ 2 \n\ tan (x)\ """ ucode_str = \ """\ 3 \n\ sin (x)\n\ ───────\n\ 2 \n\ tan (x)\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str @_both_exp_pow def test_pretty_functions(): """Tests for Abs, conjugate, exp, function braces, and factorial.""" expr = (2*x + exp(x)) ascii_str_1 = \ """\ x\n\ 2*x + e \ """ ascii_str_2 = \ """\ x \n\ e + 2*x\ """ ucode_str_1 = \ """\ x\n\ 2⋅x + ℯ \ """ ucode_str_2 = \ """\ x \n\ ℯ + 2⋅x\ """ ucode_str_3 = \ """\ x \n\ ℯ + 2⋅x\ """ assert pretty(expr) in [ascii_str_1, ascii_str_2] assert upretty(expr) in [ucode_str_1, ucode_str_2, ucode_str_3] expr = Abs(x) ascii_str = \ """\ |x|\ """ ucode_str = \ """\ │x│\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Abs(x/(x**2 + 1)) ascii_str_1 = \ """\ | x |\n\ |------|\n\ | 2|\n\ |1 + x |\ """ ascii_str_2 = \ """\ | x |\n\ |------|\n\ | 2 |\n\ |x + 1|\ """ ucode_str_1 = \ """\ │ x │\n\ │──────│\n\ │ 2│\n\ │1 + x │\ """ ucode_str_2 = \ """\ │ x │\n\ │──────│\n\ │ 2 │\n\ │x + 1│\ """ assert pretty(expr) in [ascii_str_1, ascii_str_2] assert upretty(expr) in [ucode_str_1, ucode_str_2] expr = Abs(1 / (y - Abs(x))) ascii_str = \ """\ 1 \n\ ---------\n\ |y - |x||\ """ ucode_str = \ """\ 1 \n\ ─────────\n\ │y - │x││\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str n = Symbol('n', integer=True) expr = factorial(n) ascii_str = \ """\ n!\ """ ucode_str = \ """\ n!\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = factorial(2*n) ascii_str = \ """\ (2*n)!\ """ ucode_str = \ """\ (2⋅n)!\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = factorial(factorial(factorial(n))) ascii_str = \ """\ ((n!)!)!\ """ ucode_str = \ """\ ((n!)!)!\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = factorial(n + 1) ascii_str_1 = \ """\ (1 + n)!\ """ ascii_str_2 = \ """\ (n + 1)!\ """ ucode_str_1 = \ """\ (1 + n)!\ """ ucode_str_2 = \ """\ (n + 1)!\ """ assert pretty(expr) in [ascii_str_1, ascii_str_2] assert upretty(expr) in [ucode_str_1, ucode_str_2] expr = subfactorial(n) ascii_str = \ """\ !n\ """ ucode_str = \ """\ !n\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = subfactorial(2*n) ascii_str = \ """\ !(2*n)\ """ ucode_str = \ """\ !(2⋅n)\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str n = Symbol('n', integer=True) expr = factorial2(n) ascii_str = \ """\ n!!\ """ ucode_str = \ """\ n!!\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = factorial2(2*n) ascii_str = \ """\ (2*n)!!\ """ ucode_str = \ """\ (2⋅n)!!\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = factorial2(factorial2(factorial2(n))) ascii_str = \ """\ ((n!!)!!)!!\ """ ucode_str = \ """\ ((n!!)!!)!!\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = factorial2(n + 1) ascii_str_1 = \ """\ (1 + n)!!\ """ ascii_str_2 = \ """\ (n + 1)!!\ """ ucode_str_1 = \ """\ (1 + n)!!\ """ ucode_str_2 = \ """\ (n + 1)!!\ """ assert pretty(expr) in [ascii_str_1, ascii_str_2] assert upretty(expr) in [ucode_str_1, ucode_str_2] expr = 2*binomial(n, k) ascii_str = \ """\ /n\\\n\ 2*| |\n\ \\k/\ """ ucode_str = \ """\ ⎛n⎞\n\ 2⋅⎜ ⎟\n\ ⎝k⎠\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = 2*binomial(2*n, k) ascii_str = \ """\ /2*n\\\n\ 2*| |\n\ \\ k /\ """ ucode_str = \ """\ ⎛2⋅n⎞\n\ 2⋅⎜ ⎟\n\ ⎝ k ⎠\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = 2*binomial(n**2, k) ascii_str = \ """\ / 2\\\n\ |n |\n\ 2*| |\n\ \\k /\ """ ucode_str = \ """\ ⎛ 2⎞\n\ ⎜n ⎟\n\ 2⋅⎜ ⎟\n\ ⎝k ⎠\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = catalan(n) ascii_str = \ """\ C \n\ n\ """ ucode_str = \ """\ C \n\ n\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = catalan(n) ascii_str = \ """\ C \n\ n\ """ ucode_str = \ """\ C \n\ n\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = bell(n) ascii_str = \ """\ B \n\ n\ """ ucode_str = \ """\ B \n\ n\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = bernoulli(n) ascii_str = \ """\ B \n\ n\ """ ucode_str = \ """\ B \n\ n\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = bernoulli(n, x) ascii_str = \ """\ B (x)\n\ n \ """ ucode_str = \ """\ B (x)\n\ n \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = fibonacci(n) ascii_str = \ """\ F \n\ n\ """ ucode_str = \ """\ F \n\ n\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = lucas(n) ascii_str = \ """\ L \n\ n\ """ ucode_str = \ """\ L \n\ n\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = tribonacci(n) ascii_str = \ """\ T \n\ n\ """ ucode_str = \ """\ T \n\ n\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = stieltjes(n) ascii_str = \ """\ stieltjes \n\ n\ """ ucode_str = \ """\ γ \n\ n\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = stieltjes(n, x) ascii_str = \ """\ stieltjes (x)\n\ n \ """ ucode_str = \ """\ γ (x)\n\ n \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = mathieuc(x, y, z) ascii_str = 'C(x, y, z)' ucode_str = 'C(x, y, z)' assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = mathieus(x, y, z) ascii_str = 'S(x, y, z)' ucode_str = 'S(x, y, z)' assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = mathieucprime(x, y, z) ascii_str = "C'(x, y, z)" ucode_str = "C'(x, y, z)" assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = mathieusprime(x, y, z) ascii_str = "S'(x, y, z)" ucode_str = "S'(x, y, z)" assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = conjugate(x) ascii_str = \ """\ _\n\ x\ """ ucode_str = \ """\ _\n\ x\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str f = Function('f') expr = conjugate(f(x + 1)) ascii_str_1 = \ """\ ________\n\ f(1 + x)\ """ ascii_str_2 = \ """\ ________\n\ f(x + 1)\ """ ucode_str_1 = \ """\ ________\n\ f(1 + x)\ """ ucode_str_2 = \ """\ ________\n\ f(x + 1)\ """ assert pretty(expr) in [ascii_str_1, ascii_str_2] assert upretty(expr) in [ucode_str_1, ucode_str_2] expr = f(x) ascii_str = \ """\ f(x)\ """ ucode_str = \ """\ f(x)\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = f(x, y) ascii_str = \ """\ f(x, y)\ """ ucode_str = \ """\ f(x, y)\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = f(x/(y + 1), y) ascii_str_1 = \ """\ / x \\\n\ f|-----, y|\n\ \\1 + y /\ """ ascii_str_2 = \ """\ / x \\\n\ f|-----, y|\n\ \\y + 1 /\ """ ucode_str_1 = \ """\ ⎛ x ⎞\n\ f⎜─────, y⎟\n\ ⎝1 + y ⎠\ """ ucode_str_2 = \ """\ ⎛ x ⎞\n\ f⎜─────, y⎟\n\ ⎝y + 1 ⎠\ """ assert pretty(expr) in [ascii_str_1, ascii_str_2] assert upretty(expr) in [ucode_str_1, ucode_str_2] expr = f(x**x**x**x**x**x) ascii_str = \ """\ / / / / / x\\\\\\\\\\ | | | | \\x /|||| | | | \\x /||| | | \\x /|| | \\x /| f\\x /\ """ ucode_str = \ """\ ⎛ ⎛ ⎛ ⎛ ⎛ x⎞⎞⎞⎞⎞ ⎜ ⎜ ⎜ ⎜ ⎝x ⎠⎟⎟⎟⎟ ⎜ ⎜ ⎜ ⎝x ⎠⎟⎟⎟ ⎜ ⎜ ⎝x ⎠⎟⎟ ⎜ ⎝x ⎠⎟ f⎝x ⎠\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = sin(x)**2 ascii_str = \ """\ 2 \n\ sin (x)\ """ ucode_str = \ """\ 2 \n\ sin (x)\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = conjugate(a + b*I) ascii_str = \ """\ _ _\n\ a - I*b\ """ ucode_str = \ """\ _ _\n\ a - ⅈ⋅b\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = conjugate(exp(a + b*I)) ascii_str = \ """\ _ _\n\ a - I*b\n\ e \ """ ucode_str = \ """\ _ _\n\ a - ⅈ⋅b\n\ ℯ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = conjugate( f(1 + conjugate(f(x))) ) ascii_str_1 = \ """\ ___________\n\ / ____\\\n\ f\\1 + f(x)/\ """ ascii_str_2 = \ """\ ___________\n\ /____ \\\n\ f\\f(x) + 1/\ """ ucode_str_1 = \ """\ ___________\n\ ⎛ ____⎞\n\ f⎝1 + f(x)⎠\ """ ucode_str_2 = \ """\ ___________\n\ ⎛____ ⎞\n\ f⎝f(x) + 1⎠\ """ assert pretty(expr) in [ascii_str_1, ascii_str_2] assert upretty(expr) in [ucode_str_1, ucode_str_2] expr = f(x/(y + 1), y) ascii_str_1 = \ """\ / x \\\n\ f|-----, y|\n\ \\1 + y /\ """ ascii_str_2 = \ """\ / x \\\n\ f|-----, y|\n\ \\y + 1 /\ """ ucode_str_1 = \ """\ ⎛ x ⎞\n\ f⎜─────, y⎟\n\ ⎝1 + y ⎠\ """ ucode_str_2 = \ """\ ⎛ x ⎞\n\ f⎜─────, y⎟\n\ ⎝y + 1 ⎠\ """ assert pretty(expr) in [ascii_str_1, ascii_str_2] assert upretty(expr) in [ucode_str_1, ucode_str_2] expr = floor(1 / (y - floor(x))) ascii_str = \ """\ / 1 \\\n\ floor|------------|\n\ \\y - floor(x)/\ """ ucode_str = \ """\ ⎢ 1 ⎥\n\ ⎢───────⎥\n\ ⎣y - ⌊x⌋⎦\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = ceiling(1 / (y - ceiling(x))) ascii_str = \ """\ / 1 \\\n\ ceiling|--------------|\n\ \\y - ceiling(x)/\ """ ucode_str = \ """\ ⎡ 1 ⎤\n\ ⎢───────⎥\n\ ⎢y - ⌈x⌉⎥\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = euler(n) ascii_str = \ """\ E \n\ n\ """ ucode_str = \ """\ E \n\ n\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = euler(1/(1 + 1/(1 + 1/n))) ascii_str = \ """\ E \n\ 1 \n\ ---------\n\ 1 \n\ 1 + -----\n\ 1\n\ 1 + -\n\ n\ """ ucode_str = \ """\ E \n\ 1 \n\ ─────────\n\ 1 \n\ 1 + ─────\n\ 1\n\ 1 + ─\n\ n\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = euler(n, x) ascii_str = \ """\ E (x)\n\ n \ """ ucode_str = \ """\ E (x)\n\ n \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = euler(n, x/2) ascii_str = \ """\ /x\\\n\ E |-|\n\ n\\2/\ """ ucode_str = \ """\ ⎛x⎞\n\ E ⎜─⎟\n\ n⎝2⎠\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_pretty_sqrt(): expr = sqrt(2) ascii_str = \ """\ ___\n\ \\/ 2 \ """ ucode_str = \ "√2" assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = 2**Rational(1, 3) ascii_str = \ """\ 3 ___\n\ \\/ 2 \ """ ucode_str = \ """\ 3 ___\n\ ╲╱ 2 \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = 2**Rational(1, 1000) ascii_str = \ """\ 1000___\n\ \\/ 2 \ """ ucode_str = \ """\ 1000___\n\ ╲╱ 2 \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = sqrt(x**2 + 1) ascii_str = \ """\ ________\n\ / 2 \n\ \\/ x + 1 \ """ ucode_str = \ """\ ________\n\ ╱ 2 \n\ ╲╱ x + 1 \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = (1 + sqrt(5))**Rational(1, 3) ascii_str = \ """\ ___________\n\ 3 / ___ \n\ \\/ 1 + \\/ 5 \ """ ucode_str = \ """\ 3 ________\n\ ╲╱ 1 + √5 \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = 2**(1/x) ascii_str = \ """\ x ___\n\ \\/ 2 \ """ ucode_str = \ """\ x ___\n\ ╲╱ 2 \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = sqrt(2 + pi) ascii_str = \ """\ ________\n\ \\/ 2 + pi \ """ ucode_str = \ """\ _______\n\ ╲╱ 2 + π \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = (2 + ( 1 + x**2)/(2 + x))**Rational(1, 4) + (1 + x**Rational(1, 1000))/sqrt(3 + x**2) ascii_str = \ """\ ____________ \n\ / 2 1000___ \n\ / x + 1 \\/ x + 1\n\ 4 / 2 + ------ + -----------\n\ \\/ x + 2 ________\n\ / 2 \n\ \\/ x + 3 \ """ ucode_str = \ """\ ____________ \n\ ╱ 2 1000___ \n\ ╱ x + 1 ╲╱ x + 1\n\ 4 ╱ 2 + ────── + ───────────\n\ ╲╱ x + 2 ________\n\ ╱ 2 \n\ ╲╱ x + 3 \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_pretty_sqrt_char_knob(): # See PR #9234. expr = sqrt(2) ucode_str1 = \ """\ ___\n\ ╲╱ 2 \ """ ucode_str2 = \ "√2" assert xpretty(expr, use_unicode=True, use_unicode_sqrt_char=False) == ucode_str1 assert xpretty(expr, use_unicode=True, use_unicode_sqrt_char=True) == ucode_str2 def test_pretty_sqrt_longsymbol_no_sqrt_char(): # Do not use unicode sqrt char for long symbols (see PR #9234). expr = sqrt(Symbol('C1')) ucode_str = \ """\ ____\n\ ╲╱ C₁ \ """ assert upretty(expr) == ucode_str def test_pretty_KroneckerDelta(): x, y = symbols("x, y") expr = KroneckerDelta(x, y) ascii_str = \ """\ d \n\ x,y\ """ ucode_str = \ """\ δ \n\ x,y\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_pretty_product(): n, m, k, l = symbols('n m k l') f = symbols('f', cls=Function) expr = Product(f((n/3)**2), (n, k**2, l)) unicode_str = \ """\ l \n\ ─┬──────┬─ \n\ │ │ ⎛ 2⎞\n\ │ │ ⎜n ⎟\n\ │ │ f⎜──⎟\n\ │ │ ⎝9 ⎠\n\ │ │ \n\ 2 \n\ n = k """ ascii_str = \ """\ l \n\ __________ \n\ | | / 2\\\n\ | | |n |\n\ | | f|--|\n\ | | \\9 /\n\ | | \n\ 2 \n\ n = k """ expr = Product(f((n/3)**2), (n, k**2, l), (l, 1, m)) unicode_str = \ """\ m l \n\ ─┬──────┬─ ─┬──────┬─ \n\ │ │ │ │ ⎛ 2⎞\n\ │ │ │ │ ⎜n ⎟\n\ │ │ │ │ f⎜──⎟\n\ │ │ │ │ ⎝9 ⎠\n\ │ │ │ │ \n\ l = 1 2 \n\ n = k """ ascii_str = \ """\ m l \n\ __________ __________ \n\ | | | | / 2\\\n\ | | | | |n |\n\ | | | | f|--|\n\ | | | | \\9 /\n\ | | | | \n\ l = 1 2 \n\ n = k """ assert pretty(expr) == ascii_str assert upretty(expr) == unicode_str def test_pretty_Lambda(): # S.IdentityFunction is a special case expr = Lambda(y, y) assert pretty(expr) == "x -> x" assert upretty(expr) == "x ↦ x" expr = Lambda(x, x+1) assert pretty(expr) == "x -> x + 1" assert upretty(expr) == "x ↦ x + 1" expr = Lambda(x, x**2) ascii_str = \ """\ 2\n\ x -> x \ """ ucode_str = \ """\ 2\n\ x ↦ x \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Lambda(x, x**2)**2 ascii_str = \ """\ 2 / 2\\ \n\ \\x -> x / \ """ ucode_str = \ """\ 2 ⎛ 2⎞ \n\ ⎝x ↦ x ⎠ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Lambda((x, y), x) ascii_str = "(x, y) -> x" ucode_str = "(x, y) ↦ x" assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Lambda((x, y), x**2) ascii_str = \ """\ 2\n\ (x, y) -> x \ """ ucode_str = \ """\ 2\n\ (x, y) ↦ x \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Lambda(((x, y),), x**2) ascii_str = \ """\ 2\n\ ((x, y),) -> x \ """ ucode_str = \ """\ 2\n\ ((x, y),) ↦ x \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_pretty_TransferFunction(): tf1 = TransferFunction(s - 1, s + 1, s) assert upretty(tf1) == "s - 1\n─────\ns + 1" tf2 = TransferFunction(2*s + 1, 3 - p, s) assert upretty(tf2) == "2⋅s + 1\n───────\n 3 - p " tf3 = TransferFunction(p, p + 1, p) assert upretty(tf3) == " p \n─────\np + 1" def test_pretty_Series(): tf1 = TransferFunction(x + y, x - 2*y, y) tf2 = TransferFunction(x - y, x + y, y) tf3 = TransferFunction(x**2 + y, y - x, y) tf4 = TransferFunction(2, 3, y) tfm1 = TransferFunctionMatrix([[tf1, tf2], [tf3, tf4]]) tfm2 = TransferFunctionMatrix([[tf3], [-tf4]]) tfm3 = TransferFunctionMatrix([[tf1, -tf2, -tf3], [tf3, -tf4, tf2]]) tfm4 = TransferFunctionMatrix([[tf1, tf2], [tf3, -tf4], [-tf2, -tf1]]) tfm5 = TransferFunctionMatrix([[-tf2, -tf1], [tf4, -tf3], [tf1, tf2]]) expected1 = \ """\ ⎛ 2 ⎞\n\ ⎛ x + y ⎞ ⎜x + y⎟\n\ ⎜───────⎟⋅⎜──────⎟\n\ ⎝x - 2⋅y⎠ ⎝-x + y⎠\ """ expected2 = \ """\ ⎛-x + y⎞ ⎛ -x - y⎞\n\ ⎜──────⎟⋅⎜───────⎟\n\ ⎝x + y ⎠ ⎝x - 2⋅y⎠\ """ expected3 = \ """\ ⎛ 2 ⎞ \n\ ⎜x + y⎟ ⎛ x + y ⎞ ⎛ -x - y x - y⎞\n\ ⎜──────⎟⋅⎜───────⎟⋅⎜─────── + ─────⎟\n\ ⎝-x + y⎠ ⎝x - 2⋅y⎠ ⎝x - 2⋅y x + y⎠\ """ expected4 = \ """\ ⎛ 2 ⎞\n\ ⎛ x + y x - y⎞ ⎜x - y x + y⎟\n\ ⎜─────── + ─────⎟⋅⎜───── + ──────⎟\n\ ⎝x - 2⋅y x + y⎠ ⎝x + y -x + y⎠\ """ expected5 = \ """\ ⎡ x + y x - y⎤ ⎡ 2 ⎤ \n\ ⎢─────── ─────⎥ ⎢x + y⎥ \n\ ⎢x - 2⋅y x + y⎥ ⎢──────⎥ \n\ ⎢ ⎥ ⎢-x + y⎥ \n\ ⎢ 2 ⎥ ⋅⎢ ⎥ \n\ ⎢x + y 2 ⎥ ⎢ -2 ⎥ \n\ ⎢────── ─ ⎥ ⎢ ─── ⎥ \n\ ⎣-x + y 3 ⎦τ ⎣ 3 ⎦τ\ """ expected6 = \ """\ ⎛⎡ x + y x - y ⎤ ⎡ x - y x + y ⎤ ⎞\n\ ⎜⎢─────── ───── ⎥ ⎢ ───── ───────⎥ ⎟\n\ ⎡ x + y x - y⎤ ⎡ 2 ⎤ ⎜⎢x - 2⋅y x + y ⎥ ⎢ x + y x - 2⋅y⎥ ⎟\n\ ⎢─────── ─────⎥ ⎢ x + y -x + y - x - y⎥ ⎜⎢ ⎥ ⎢ ⎥ ⎟\n\ ⎢x - 2⋅y x + y⎥ ⎢─────── ────── ────────⎥ ⎜⎢ 2 ⎥ ⎢ 2 ⎥ ⎟\n\ ⎢ ⎥ ⎢x - 2⋅y x + y -x + y ⎥ ⎜⎢x + y -2 ⎥ ⎢ -2 x + y ⎥ ⎟\n\ ⎢ 2 ⎥ ⋅⎢ ⎥ ⋅⎜⎢────── ─── ⎥ + ⎢ ─── ────── ⎥ ⎟\n\ ⎢x + y 2 ⎥ ⎢ 2 ⎥ ⎜⎢-x + y 3 ⎥ ⎢ 3 -x + y ⎥ ⎟\n\ ⎢────── ─ ⎥ ⎢x + y -2 x - y ⎥ ⎜⎢ ⎥ ⎢ ⎥ ⎟\n\ ⎣-x + y 3 ⎦τ ⎢────── ─── ───── ⎥ ⎜⎢-x + y -x - y⎥ ⎢ -x - y -x + y ⎥ ⎟\n\ ⎣-x + y 3 x + y ⎦τ ⎜⎢────── ───────⎥ ⎢─────── ────── ⎥ ⎟\n\ ⎝⎣x + y x - 2⋅y⎦τ ⎣x - 2⋅y x + y ⎦τ⎠\ """ assert upretty(Series(tf1, tf3)) == expected1 assert upretty(Series(-tf2, -tf1)) == expected2 assert upretty(Series(tf3, tf1, Parallel(-tf1, tf2))) == expected3 assert upretty(Series(Parallel(tf1, tf2), Parallel(tf2, tf3))) == expected4 assert upretty(MIMOSeries(tfm2, tfm1)) == expected5 assert upretty(MIMOSeries(MIMOParallel(tfm4, -tfm5), tfm3, tfm1)) == expected6 def test_pretty_Parallel(): tf1 = TransferFunction(x + y, x - 2*y, y) tf2 = TransferFunction(x - y, x + y, y) tf3 = TransferFunction(x**2 + y, y - x, y) tf4 = TransferFunction(y**2 - x, x**3 + x, y) tfm1 = TransferFunctionMatrix([[tf1, tf2], [tf3, -tf4], [-tf2, -tf1]]) tfm2 = TransferFunctionMatrix([[-tf2, -tf1], [tf4, -tf3], [tf1, tf2]]) tfm3 = TransferFunctionMatrix([[-tf1, tf2], [-tf3, tf4], [tf2, tf1]]) tfm4 = TransferFunctionMatrix([[-tf1, -tf2], [-tf3, -tf4]]) expected1 = \ """\ x + y x - y\n\ ─────── + ─────\n\ x - 2⋅y x + y\ """ expected2 = \ """\ -x + y -x - y\n\ ────── + ───────\n\ x + y x - 2⋅y\ """ expected3 = \ """\ 2 \n\ x + y x + y ⎛ -x - y⎞ ⎛x - y⎞\n\ ────── + ─────── + ⎜───────⎟⋅⎜─────⎟\n\ -x + y x - 2⋅y ⎝x - 2⋅y⎠ ⎝x + y⎠\ """ expected4 = \ """\ ⎛ 2 ⎞\n\ ⎛ x + y ⎞ ⎛x - y⎞ ⎛x - y⎞ ⎜x + y⎟\n\ ⎜───────⎟⋅⎜─────⎟ + ⎜─────⎟⋅⎜──────⎟\n\ ⎝x - 2⋅y⎠ ⎝x + y⎠ ⎝x + y⎠ ⎝-x + y⎠\ """ expected5 = \ """\ ⎡ x + y -x + y ⎤ ⎡ x - y x + y ⎤ ⎡ x + y x - y ⎤ \n\ ⎢─────── ────── ⎥ ⎢ ───── ───────⎥ ⎢─────── ───── ⎥ \n\ ⎢x - 2⋅y x + y ⎥ ⎢ x + y x - 2⋅y⎥ ⎢x - 2⋅y x + y ⎥ \n\ ⎢ ⎥ ⎢ ⎥ ⎢ ⎥ \n\ ⎢ 2 2 ⎥ ⎢ 2 2 ⎥ ⎢ 2 2 ⎥ \n\ ⎢x + y x - y ⎥ ⎢x - y x + y ⎥ ⎢x + y x - y ⎥ \n\ ⎢────── ────── ⎥ + ⎢────── ────── ⎥ + ⎢────── ────── ⎥ \n\ ⎢-x + y 3 ⎥ ⎢ 3 -x + y ⎥ ⎢-x + y 3 ⎥ \n\ ⎢ x + x ⎥ ⎢x + x ⎥ ⎢ x + x ⎥ \n\ ⎢ ⎥ ⎢ ⎥ ⎢ ⎥ \n\ ⎢-x + y -x - y⎥ ⎢ -x - y -x + y ⎥ ⎢-x + y -x - y⎥ \n\ ⎢────── ───────⎥ ⎢─────── ────── ⎥ ⎢────── ───────⎥ \n\ ⎣x + y x - 2⋅y⎦τ ⎣x - 2⋅y x + y ⎦τ ⎣x + y x - 2⋅y⎦τ\ """ expected6 = \ """\ ⎡ x - y x + y ⎤ ⎡-x + y -x - y ⎤ \n\ ⎢ ───── ───────⎥ ⎢────── ─────── ⎥ \n\ ⎢ x + y x - 2⋅y⎥ ⎡ -x - y -x + y⎤ ⎢x + y x - 2⋅y ⎥ \n\ ⎢ ⎥ ⎢─────── ──────⎥ ⎢ ⎥ \n\ ⎢ 2 2 ⎥ ⎢x - 2⋅y x + y ⎥ ⎢ 2 2 ⎥ \n\ ⎢x - y x + y ⎥ ⎢ ⎥ ⎢-x + y - x - y⎥ \n\ ⎢────── ────── ⎥ ⋅⎢ 2 2⎥ + ⎢─────── ────────⎥ \n\ ⎢ 3 -x + y ⎥ ⎢- x - y x - y ⎥ ⎢ 3 -x + y ⎥ \n\ ⎢x + x ⎥ ⎢──────── ──────⎥ ⎢ x + x ⎥ \n\ ⎢ ⎥ ⎢ -x + y 3 ⎥ ⎢ ⎥ \n\ ⎢ -x - y -x + y ⎥ ⎣ x + x⎦τ ⎢ x + y x - y ⎥ \n\ ⎢─────── ────── ⎥ ⎢─────── ───── ⎥ \n\ ⎣x - 2⋅y x + y ⎦τ ⎣x - 2⋅y x + y ⎦τ\ """ assert upretty(Parallel(tf1, tf2)) == expected1 assert upretty(Parallel(-tf2, -tf1)) == expected2 assert upretty(Parallel(tf3, tf1, Series(-tf1, tf2))) == expected3 assert upretty(Parallel(Series(tf1, tf2), Series(tf2, tf3))) == expected4 assert upretty(MIMOParallel(-tfm3, -tfm2, tfm1)) == expected5 assert upretty(MIMOParallel(MIMOSeries(tfm4, -tfm2), tfm2)) == expected6 def test_pretty_Feedback(): tf = TransferFunction(1, 1, y) tf1 = TransferFunction(x + y, x - 2*y, y) tf2 = TransferFunction(x - y, x + y, y) tf3 = TransferFunction(y**2 - 2*y + 1, y + 5, y) tf4 = TransferFunction(x - 2*y**3, x + y, x) tf5 = TransferFunction(1 - x, x - y, y) tf6 = TransferFunction(2, 2, x) expected1 = \ """\ ⎛1⎞ \n\ ⎜─⎟ \n\ ⎝1⎠ \n\ ─────────────\n\ 1 ⎛ x + y ⎞\n\ ─ + ⎜───────⎟\n\ 1 ⎝x - 2⋅y⎠\ """ expected2 = \ """\ ⎛1⎞ \n\ ⎜─⎟ \n\ ⎝1⎠ \n\ ────────────────────────────────────\n\ ⎛ 2 ⎞\n\ 1 ⎛x - y⎞ ⎛ x + y ⎞ ⎜y - 2⋅y + 1⎟\n\ ─ + ⎜─────⎟⋅⎜───────⎟⋅⎜────────────⎟\n\ 1 ⎝x + y⎠ ⎝x - 2⋅y⎠ ⎝ y + 5 ⎠\ """ expected3 = \ """\ ⎛ x + y ⎞ \n\ ⎜───────⎟ \n\ ⎝x - 2⋅y⎠ \n\ ────────────────────────────────────────────\n\ ⎛ 2 ⎞ \n\ 1 ⎛ x + y ⎞ ⎛x - y⎞ ⎜y - 2⋅y + 1⎟ ⎛1 - x⎞\n\ ─ + ⎜───────⎟⋅⎜─────⎟⋅⎜────────────⎟⋅⎜─────⎟\n\ 1 ⎝x - 2⋅y⎠ ⎝x + y⎠ ⎝ y + 5 ⎠ ⎝x - y⎠\ """ expected4 = \ """\ ⎛ x + y ⎞ ⎛x - y⎞ \n\ ⎜───────⎟⋅⎜─────⎟ \n\ ⎝x - 2⋅y⎠ ⎝x + y⎠ \n\ ─────────────────────\n\ 1 ⎛ x + y ⎞ ⎛x - y⎞\n\ ─ + ⎜───────⎟⋅⎜─────⎟\n\ 1 ⎝x - 2⋅y⎠ ⎝x + y⎠\ """ expected5 = \ """\ ⎛ x + y ⎞ ⎛x - y⎞ \n\ ⎜───────⎟⋅⎜─────⎟ \n\ ⎝x - 2⋅y⎠ ⎝x + y⎠ \n\ ─────────────────────────────\n\ 1 ⎛ x + y ⎞ ⎛x - y⎞ ⎛1 - x⎞\n\ ─ + ⎜───────⎟⋅⎜─────⎟⋅⎜─────⎟\n\ 1 ⎝x - 2⋅y⎠ ⎝x + y⎠ ⎝x - y⎠\ """ expected6 = \ """\ ⎛ 2 ⎞ \n\ ⎜y - 2⋅y + 1⎟ ⎛1 - x⎞ \n\ ⎜────────────⎟⋅⎜─────⎟ \n\ ⎝ y + 5 ⎠ ⎝x - y⎠ \n\ ────────────────────────────────────────────\n\ ⎛ 2 ⎞ \n\ 1 ⎜y - 2⋅y + 1⎟ ⎛1 - x⎞ ⎛x - y⎞ ⎛ x + y ⎞\n\ ─ + ⎜────────────⎟⋅⎜─────⎟⋅⎜─────⎟⋅⎜───────⎟\n\ 1 ⎝ y + 5 ⎠ ⎝x - y⎠ ⎝x + y⎠ ⎝x - 2⋅y⎠\ """ expected7 = \ """\ ⎛ 3⎞ \n\ ⎜x - 2⋅y ⎟ \n\ ⎜────────⎟ \n\ ⎝ x + y ⎠ \n\ ──────────────────\n\ ⎛ 3⎞ \n\ 1 ⎜x - 2⋅y ⎟ ⎛2⎞\n\ ─ + ⎜────────⎟⋅⎜─⎟\n\ 1 ⎝ x + y ⎠ ⎝2⎠\ """ expected8 = \ """\ ⎛1 - x⎞ \n\ ⎜─────⎟ \n\ ⎝x - y⎠ \n\ ───────────\n\ 1 ⎛1 - x⎞\n\ ─ + ⎜─────⎟\n\ 1 ⎝x - y⎠\ """ expected9 = \ """\ ⎛ x + y ⎞ ⎛x - y⎞ \n\ ⎜───────⎟⋅⎜─────⎟ \n\ ⎝x - 2⋅y⎠ ⎝x + y⎠ \n\ ─────────────────────────────\n\ 1 ⎛ x + y ⎞ ⎛x - y⎞ ⎛1 - x⎞\n\ ─ - ⎜───────⎟⋅⎜─────⎟⋅⎜─────⎟\n\ 1 ⎝x - 2⋅y⎠ ⎝x + y⎠ ⎝x - y⎠\ """ expected10 = \ """\ ⎛1 - x⎞ \n\ ⎜─────⎟ \n\ ⎝x - y⎠ \n\ ───────────\n\ 1 ⎛1 - x⎞\n\ ─ - ⎜─────⎟\n\ 1 ⎝x - y⎠\ """ assert upretty(Feedback(tf, tf1)) == expected1 assert upretty(Feedback(tf, tf2*tf1*tf3)) == expected2 assert upretty(Feedback(tf1, tf2*tf3*tf5)) == expected3 assert upretty(Feedback(tf1*tf2, tf)) == expected4 assert upretty(Feedback(tf1*tf2, tf5)) == expected5 assert upretty(Feedback(tf3*tf5, tf2*tf1)) == expected6 assert upretty(Feedback(tf4, tf6)) == expected7 assert upretty(Feedback(tf5, tf)) == expected8 assert upretty(Feedback(tf1*tf2, tf5, 1)) == expected9 assert upretty(Feedback(tf5, tf, 1)) == expected10 def test_pretty_MIMOFeedback(): tf1 = TransferFunction(x + y, x - 2*y, y) tf2 = TransferFunction(x - y, x + y, y) tfm_1 = TransferFunctionMatrix([[tf1, tf2], [tf2, tf1]]) tfm_2 = TransferFunctionMatrix([[tf2, tf1], [tf1, tf2]]) tfm_3 = TransferFunctionMatrix([[tf1, tf1], [tf2, tf2]]) expected1 = \ """\ ⎛ ⎡ x + y x - y ⎤ ⎡ x - y x + y ⎤ ⎞-1 ⎡ x + y x - y ⎤ \n\ ⎜ ⎢─────── ───── ⎥ ⎢ ───── ───────⎥ ⎟ ⎢─────── ───── ⎥ \n\ ⎜ ⎢x - 2⋅y x + y ⎥ ⎢ x + y x - 2⋅y⎥ ⎟ ⎢x - 2⋅y x + y ⎥ \n\ ⎜I - ⎢ ⎥ ⋅⎢ ⎥ ⎟ ⋅ ⎢ ⎥ \n\ ⎜ ⎢ x - y x + y ⎥ ⎢ x + y x - y ⎥ ⎟ ⎢ x - y x + y ⎥ \n\ ⎜ ⎢ ───── ───────⎥ ⎢─────── ───── ⎥ ⎟ ⎢ ───── ───────⎥ \n\ ⎝ ⎣ x + y x - 2⋅y⎦τ ⎣x - 2⋅y x + y ⎦τ⎠ ⎣ x + y x - 2⋅y⎦τ\ """ expected2 = \ """\ ⎛ ⎡ x + y x - y ⎤ ⎡ x - y x + y ⎤ ⎡ x + y x + y ⎤ ⎞-1 ⎡ x + y x - y ⎤ ⎡ x - y x + y ⎤ \n\ ⎜ ⎢─────── ───── ⎥ ⎢ ───── ───────⎥ ⎢─────── ───────⎥ ⎟ ⎢─────── ───── ⎥ ⎢ ───── ───────⎥ \n\ ⎜ ⎢x - 2⋅y x + y ⎥ ⎢ x + y x - 2⋅y⎥ ⎢x - 2⋅y x - 2⋅y⎥ ⎟ ⎢x - 2⋅y x + y ⎥ ⎢ x + y x - 2⋅y⎥ \n\ ⎜I + ⎢ ⎥ ⋅⎢ ⎥ ⋅⎢ ⎥ ⎟ ⋅ ⎢ ⎥ ⋅⎢ ⎥ \n\ ⎜ ⎢ x - y x + y ⎥ ⎢ x + y x - y ⎥ ⎢ x - y x - y ⎥ ⎟ ⎢ x - y x + y ⎥ ⎢ x + y x - y ⎥ \n\ ⎜ ⎢ ───── ───────⎥ ⎢─────── ───── ⎥ ⎢ ───── ───── ⎥ ⎟ ⎢ ───── ───────⎥ ⎢─────── ───── ⎥ \n\ ⎝ ⎣ x + y x - 2⋅y⎦τ ⎣x - 2⋅y x + y ⎦τ ⎣ x + y x + y ⎦τ⎠ ⎣ x + y x - 2⋅y⎦τ ⎣x - 2⋅y x + y ⎦τ\ """ assert upretty(MIMOFeedback(tfm_1, tfm_2, 1)) == \ expected1 # Positive MIMOFeedback assert upretty(MIMOFeedback(tfm_1*tfm_2, tfm_3)) == \ expected2 # Negative MIMOFeedback (Default) def test_pretty_TransferFunctionMatrix(): tf1 = TransferFunction(x + y, x - 2*y, y) tf2 = TransferFunction(x - y, x + y, y) tf3 = TransferFunction(y**2 - 2*y + 1, y + 5, y) tf4 = TransferFunction(y, x**2 + x + 1, y) tf5 = TransferFunction(1 - x, x - y, y) tf6 = TransferFunction(2, 2, y) expected1 = \ """\ ⎡ x + y ⎤ \n\ ⎢───────⎥ \n\ ⎢x - 2⋅y⎥ \n\ ⎢ ⎥ \n\ ⎢ x - y ⎥ \n\ ⎢ ───── ⎥ \n\ ⎣ x + y ⎦τ\ """ expected2 = \ """\ ⎡ x + y ⎤ \n\ ⎢ ─────── ⎥ \n\ ⎢ x - 2⋅y ⎥ \n\ ⎢ ⎥ \n\ ⎢ x - y ⎥ \n\ ⎢ ───── ⎥ \n\ ⎢ x + y ⎥ \n\ ⎢ ⎥ \n\ ⎢ 2 ⎥ \n\ ⎢- y + 2⋅y - 1⎥ \n\ ⎢──────────────⎥ \n\ ⎣ y + 5 ⎦τ\ """ expected3 = \ """\ ⎡ x + y x - y ⎤ \n\ ⎢ ─────── ───── ⎥ \n\ ⎢ x - 2⋅y x + y ⎥ \n\ ⎢ ⎥ \n\ ⎢ 2 ⎥ \n\ ⎢y - 2⋅y + 1 y ⎥ \n\ ⎢──────────── ──────────⎥ \n\ ⎢ y + 5 2 ⎥ \n\ ⎢ x + x + 1⎥ \n\ ⎢ ⎥ \n\ ⎢ 1 - x 2 ⎥ \n\ ⎢ ───── ─ ⎥ \n\ ⎣ x - y 2 ⎦τ\ """ expected4 = \ """\ ⎡ x - y x + y y ⎤ \n\ ⎢ ───── ─────── ──────────⎥ \n\ ⎢ x + y x - 2⋅y 2 ⎥ \n\ ⎢ x + x + 1⎥ \n\ ⎢ ⎥ \n\ ⎢ 2 ⎥ \n\ ⎢- y + 2⋅y - 1 x - 1 -2 ⎥ \n\ ⎢────────────── ───── ─── ⎥ \n\ ⎣ y + 5 x - y 2 ⎦τ\ """ expected5 = \ """\ ⎡ x + y x - y x + y y ⎤ \n\ ⎢───────⋅───── ─────── ──────────⎥ \n\ ⎢x - 2⋅y x + y x - 2⋅y 2 ⎥ \n\ ⎢ x + x + 1⎥ \n\ ⎢ ⎥ \n\ ⎢ 1 - x 2 x + y -2 ⎥ \n\ ⎢ ───── + ─ ─────── ─── ⎥ \n\ ⎣ x - y 2 x - 2⋅y 2 ⎦τ\ """ assert upretty(TransferFunctionMatrix([[tf1], [tf2]])) == expected1 assert upretty(TransferFunctionMatrix([[tf1], [tf2], [-tf3]])) == expected2 assert upretty(TransferFunctionMatrix([[tf1, tf2], [tf3, tf4], [tf5, tf6]])) == expected3 assert upretty(TransferFunctionMatrix([[tf2, tf1, tf4], [-tf3, -tf5, -tf6]])) == expected4 assert upretty(TransferFunctionMatrix([[Series(tf2, tf1), tf1, tf4], [Parallel(tf6, tf5), tf1, -tf6]])) == \ expected5 def test_pretty_order(): expr = O(1) ascii_str = \ """\ O(1)\ """ ucode_str = \ """\ O(1)\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = O(1/x) ascii_str = \ """\ /1\\\n\ O|-|\n\ \\x/\ """ ucode_str = \ """\ ⎛1⎞\n\ O⎜─⎟\n\ ⎝x⎠\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = O(x**2 + y**2) ascii_str = \ """\ / 2 2 \\\n\ O\\x + y ; (x, y) -> (0, 0)/\ """ ucode_str = \ """\ ⎛ 2 2 ⎞\n\ O⎝x + y ; (x, y) → (0, 0)⎠\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = O(1, (x, oo)) ascii_str = \ """\ O(1; x -> oo)\ """ ucode_str = \ """\ O(1; x → ∞)\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = O(1/x, (x, oo)) ascii_str = \ """\ /1 \\\n\ O|-; x -> oo|\n\ \\x /\ """ ucode_str = \ """\ ⎛1 ⎞\n\ O⎜─; x → ∞⎟\n\ ⎝x ⎠\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = O(x**2 + y**2, (x, oo), (y, oo)) ascii_str = \ """\ / 2 2 \\\n\ O\\x + y ; (x, y) -> (oo, oo)/\ """ ucode_str = \ """\ ⎛ 2 2 ⎞\n\ O⎝x + y ; (x, y) → (∞, ∞)⎠\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_pretty_derivatives(): # Simple expr = Derivative(log(x), x, evaluate=False) ascii_str = \ """\ d \n\ --(log(x))\n\ dx \ """ ucode_str = \ """\ d \n\ ──(log(x))\n\ dx \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Derivative(log(x), x, evaluate=False) + x ascii_str_1 = \ """\ d \n\ x + --(log(x))\n\ dx \ """ ascii_str_2 = \ """\ d \n\ --(log(x)) + x\n\ dx \ """ ucode_str_1 = \ """\ d \n\ x + ──(log(x))\n\ dx \ """ ucode_str_2 = \ """\ d \n\ ──(log(x)) + x\n\ dx \ """ assert pretty(expr) in [ascii_str_1, ascii_str_2] assert upretty(expr) in [ucode_str_1, ucode_str_2] # basic partial derivatives expr = Derivative(log(x + y) + x, x) ascii_str_1 = \ """\ d \n\ --(log(x + y) + x)\n\ dx \ """ ascii_str_2 = \ """\ d \n\ --(x + log(x + y))\n\ dx \ """ ucode_str_1 = \ """\ ∂ \n\ ──(log(x + y) + x)\n\ ∂x \ """ ucode_str_2 = \ """\ ∂ \n\ ──(x + log(x + y))\n\ ∂x \ """ assert pretty(expr) in [ascii_str_1, ascii_str_2] assert upretty(expr) in [ucode_str_1, ucode_str_2], upretty(expr) # Multiple symbols expr = Derivative(log(x) + x**2, x, y) ascii_str_1 = \ """\ 2 \n\ d / 2\\\n\ -----\\log(x) + x /\n\ dy dx \ """ ascii_str_2 = \ """\ 2 \n\ d / 2 \\\n\ -----\\x + log(x)/\n\ dy dx \ """ ucode_str_1 = \ """\ 2 \n\ d ⎛ 2⎞\n\ ─────⎝log(x) + x ⎠\n\ dy dx \ """ ucode_str_2 = \ """\ 2 \n\ d ⎛ 2 ⎞\n\ ─────⎝x + log(x)⎠\n\ dy dx \ """ assert pretty(expr) in [ascii_str_1, ascii_str_2] assert upretty(expr) in [ucode_str_1, ucode_str_2] expr = Derivative(2*x*y, y, x) + x**2 ascii_str_1 = \ """\ 2 \n\ d 2\n\ -----(2*x*y) + x \n\ dx dy \ """ ascii_str_2 = \ """\ 2 \n\ 2 d \n\ x + -----(2*x*y)\n\ dx dy \ """ ucode_str_1 = \ """\ 2 \n\ ∂ 2\n\ ─────(2⋅x⋅y) + x \n\ ∂x ∂y \ """ ucode_str_2 = \ """\ 2 \n\ 2 ∂ \n\ x + ─────(2⋅x⋅y)\n\ ∂x ∂y \ """ assert pretty(expr) in [ascii_str_1, ascii_str_2] assert upretty(expr) in [ucode_str_1, ucode_str_2] expr = Derivative(2*x*y, x, x) ascii_str = \ """\ 2 \n\ d \n\ ---(2*x*y)\n\ 2 \n\ dx \ """ ucode_str = \ """\ 2 \n\ ∂ \n\ ───(2⋅x⋅y)\n\ 2 \n\ ∂x \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Derivative(2*x*y, x, 17) ascii_str = \ """\ 17 \n\ d \n\ ----(2*x*y)\n\ 17 \n\ dx \ """ ucode_str = \ """\ 17 \n\ ∂ \n\ ────(2⋅x⋅y)\n\ 17 \n\ ∂x \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Derivative(2*x*y, x, x, y) ascii_str = \ """\ 3 \n\ d \n\ ------(2*x*y)\n\ 2 \n\ dy dx \ """ ucode_str = \ """\ 3 \n\ ∂ \n\ ──────(2⋅x⋅y)\n\ 2 \n\ ∂y ∂x \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str # Greek letters alpha = Symbol('alpha') beta = Function('beta') expr = beta(alpha).diff(alpha) ascii_str = \ """\ d \n\ ------(beta(alpha))\n\ dalpha \ """ ucode_str = \ """\ d \n\ ──(β(α))\n\ dα \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Derivative(f(x), (x, n)) ascii_str = \ """\ n \n\ d \n\ ---(f(x))\n\ n \n\ dx \ """ ucode_str = \ """\ n \n\ d \n\ ───(f(x))\n\ n \n\ dx \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_pretty_integrals(): expr = Integral(log(x), x) ascii_str = \ """\ / \n\ | \n\ | log(x) dx\n\ | \n\ / \ """ ucode_str = \ """\ ⌠ \n\ ⎮ log(x) dx\n\ ⌡ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Integral(x**2, x) ascii_str = \ """\ / \n\ | \n\ | 2 \n\ | x dx\n\ | \n\ / \ """ ucode_str = \ """\ ⌠ \n\ ⎮ 2 \n\ ⎮ x dx\n\ ⌡ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Integral((sin(x))**2 / (tan(x))**2) ascii_str = \ """\ / \n\ | \n\ | 2 \n\ | sin (x) \n\ | ------- dx\n\ | 2 \n\ | tan (x) \n\ | \n\ / \ """ ucode_str = \ """\ ⌠ \n\ ⎮ 2 \n\ ⎮ sin (x) \n\ ⎮ ─────── dx\n\ ⎮ 2 \n\ ⎮ tan (x) \n\ ⌡ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Integral(x**(2**x), x) ascii_str = \ """\ / \n\ | \n\ | / x\\ \n\ | \\2 / \n\ | x dx\n\ | \n\ / \ """ ucode_str = \ """\ ⌠ \n\ ⎮ ⎛ x⎞ \n\ ⎮ ⎝2 ⎠ \n\ ⎮ x dx\n\ ⌡ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Integral(x**2, (x, 1, 2)) ascii_str = \ """\ 2 \n\ / \n\ | \n\ | 2 \n\ | x dx\n\ | \n\ / \n\ 1 \ """ ucode_str = \ """\ 2 \n\ ⌠ \n\ ⎮ 2 \n\ ⎮ x dx\n\ ⌡ \n\ 1 \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Integral(x**2, (x, Rational(1, 2), 10)) ascii_str = \ """\ 10 \n\ / \n\ | \n\ | 2 \n\ | x dx\n\ | \n\ / \n\ 1/2 \ """ ucode_str = \ """\ 10 \n\ ⌠ \n\ ⎮ 2 \n\ ⎮ x dx\n\ ⌡ \n\ 1/2 \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Integral(x**2*y**2, x, y) ascii_str = \ """\ / / \n\ | | \n\ | | 2 2 \n\ | | x *y dx dy\n\ | | \n\ / / \ """ ucode_str = \ """\ ⌠ ⌠ \n\ ⎮ ⎮ 2 2 \n\ ⎮ ⎮ x ⋅y dx dy\n\ ⌡ ⌡ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Integral(sin(th)/cos(ph), (th, 0, pi), (ph, 0, 2*pi)) ascii_str = \ """\ 2*pi pi \n\ / / \n\ | | \n\ | | sin(theta) \n\ | | ---------- d(theta) d(phi)\n\ | | cos(phi) \n\ | | \n\ / / \n\ 0 0 \ """ ucode_str = \ """\ 2⋅π π \n\ ⌠ ⌠ \n\ ⎮ ⎮ sin(θ) \n\ ⎮ ⎮ ────── dθ dφ\n\ ⎮ ⎮ cos(φ) \n\ ⌡ ⌡ \n\ 0 0 \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_pretty_matrix(): # Empty Matrix expr = Matrix() ascii_str = "[]" unicode_str = "[]" assert pretty(expr) == ascii_str assert upretty(expr) == unicode_str expr = Matrix(2, 0, lambda i, j: 0) ascii_str = "[]" unicode_str = "[]" assert pretty(expr) == ascii_str assert upretty(expr) == unicode_str expr = Matrix(0, 2, lambda i, j: 0) ascii_str = "[]" unicode_str = "[]" assert pretty(expr) == ascii_str assert upretty(expr) == unicode_str expr = Matrix([[x**2 + 1, 1], [y, x + y]]) ascii_str_1 = \ """\ [ 2 ] [1 + x 1 ] [ ] [ y x + y]\ """ ascii_str_2 = \ """\ [ 2 ] [x + 1 1 ] [ ] [ y x + y]\ """ ucode_str_1 = \ """\ ⎡ 2 ⎤ ⎢1 + x 1 ⎥ ⎢ ⎥ ⎣ y x + y⎦\ """ ucode_str_2 = \ """\ ⎡ 2 ⎤ ⎢x + 1 1 ⎥ ⎢ ⎥ ⎣ y x + y⎦\ """ assert pretty(expr) in [ascii_str_1, ascii_str_2] assert upretty(expr) in [ucode_str_1, ucode_str_2] expr = Matrix([[x/y, y, th], [0, exp(I*k*ph), 1]]) ascii_str = \ """\ [x ] [- y theta] [y ] [ ] [ I*k*phi ] [0 e 1 ]\ """ ucode_str = \ """\ ⎡x ⎤ ⎢─ y θ⎥ ⎢y ⎥ ⎢ ⎥ ⎢ ⅈ⋅k⋅φ ⎥ ⎣0 ℯ 1⎦\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str unicode_str = \ """\ ⎡v̇_msc_00 0 0 ⎤ ⎢ ⎥ ⎢ 0 v̇_msc_01 0 ⎥ ⎢ ⎥ ⎣ 0 0 v̇_msc_02⎦\ """ expr = diag(*MatrixSymbol('vdot_msc',1,3)) assert upretty(expr) == unicode_str def test_pretty_ndim_arrays(): x, y, z, w = symbols("x y z w") for ArrayType in (ImmutableDenseNDimArray, ImmutableSparseNDimArray, MutableDenseNDimArray, MutableSparseNDimArray): # Basic: scalar array M = ArrayType(x) assert pretty(M) == "x" assert upretty(M) == "x" M = ArrayType([[1/x, y], [z, w]]) M1 = ArrayType([1/x, y, z]) M2 = tensorproduct(M1, M) M3 = tensorproduct(M, M) ascii_str = \ """\ [1 ]\n\ [- y]\n\ [x ]\n\ [ ]\n\ [z w]\ """ ucode_str = \ """\ ⎡1 ⎤\n\ ⎢─ y⎥\n\ ⎢x ⎥\n\ ⎢ ⎥\n\ ⎣z w⎦\ """ assert pretty(M) == ascii_str assert upretty(M) == ucode_str ascii_str = \ """\ [1 ]\n\ [- y z]\n\ [x ]\ """ ucode_str = \ """\ ⎡1 ⎤\n\ ⎢─ y z⎥\n\ ⎣x ⎦\ """ assert pretty(M1) == ascii_str assert upretty(M1) == ucode_str ascii_str = \ """\ [[1 y] ]\n\ [[-- -] [z ]]\n\ [[ 2 x] [ y 2 ] [- y*z]]\n\ [[x ] [ - y ] [x ]]\n\ [[ ] [ x ] [ ]]\n\ [[z w] [ ] [ 2 ]]\n\ [[- -] [y*z w*y] [z w*z]]\n\ [[x x] ]\ """ ucode_str = \ """\ ⎡⎡1 y⎤ ⎤\n\ ⎢⎢── ─⎥ ⎡z ⎤⎥\n\ ⎢⎢ 2 x⎥ ⎡ y 2 ⎤ ⎢─ y⋅z⎥⎥\n\ ⎢⎢x ⎥ ⎢ ─ y ⎥ ⎢x ⎥⎥\n\ ⎢⎢ ⎥ ⎢ x ⎥ ⎢ ⎥⎥\n\ ⎢⎢z w⎥ ⎢ ⎥ ⎢ 2 ⎥⎥\n\ ⎢⎢─ ─⎥ ⎣y⋅z w⋅y⎦ ⎣z w⋅z⎦⎥\n\ ⎣⎣x x⎦ ⎦\ """ assert pretty(M2) == ascii_str assert upretty(M2) == ucode_str ascii_str = \ """\ [ [1 y] ]\n\ [ [-- -] ]\n\ [ [ 2 x] [ y 2 ]]\n\ [ [x ] [ - y ]]\n\ [ [ ] [ x ]]\n\ [ [z w] [ ]]\n\ [ [- -] [y*z w*y]]\n\ [ [x x] ]\n\ [ ]\n\ [[z ] [ w ]]\n\ [[- y*z] [ - w*y]]\n\ [[x ] [ x ]]\n\ [[ ] [ ]]\n\ [[ 2 ] [ 2 ]]\n\ [[z w*z] [w*z w ]]\ """ ucode_str = \ """\ ⎡ ⎡1 y⎤ ⎤\n\ ⎢ ⎢── ─⎥ ⎥\n\ ⎢ ⎢ 2 x⎥ ⎡ y 2 ⎤⎥\n\ ⎢ ⎢x ⎥ ⎢ ─ y ⎥⎥\n\ ⎢ ⎢ ⎥ ⎢ x ⎥⎥\n\ ⎢ ⎢z w⎥ ⎢ ⎥⎥\n\ ⎢ ⎢─ ─⎥ ⎣y⋅z w⋅y⎦⎥\n\ ⎢ ⎣x x⎦ ⎥\n\ ⎢ ⎥\n\ ⎢⎡z ⎤ ⎡ w ⎤⎥\n\ ⎢⎢─ y⋅z⎥ ⎢ ─ w⋅y⎥⎥\n\ ⎢⎢x ⎥ ⎢ x ⎥⎥\n\ ⎢⎢ ⎥ ⎢ ⎥⎥\n\ ⎢⎢ 2 ⎥ ⎢ 2 ⎥⎥\n\ ⎣⎣z w⋅z⎦ ⎣w⋅z w ⎦⎦\ """ assert pretty(M3) == ascii_str assert upretty(M3) == ucode_str Mrow = ArrayType([[x, y, 1 / z]]) Mcolumn = ArrayType([[x], [y], [1 / z]]) Mcol2 = ArrayType([Mcolumn.tolist()]) ascii_str = \ """\ [[ 1]]\n\ [[x y -]]\n\ [[ z]]\ """ ucode_str = \ """\ ⎡⎡ 1⎤⎤\n\ ⎢⎢x y ─⎥⎥\n\ ⎣⎣ z⎦⎦\ """ assert pretty(Mrow) == ascii_str assert upretty(Mrow) == ucode_str ascii_str = \ """\ [x]\n\ [ ]\n\ [y]\n\ [ ]\n\ [1]\n\ [-]\n\ [z]\ """ ucode_str = \ """\ ⎡x⎤\n\ ⎢ ⎥\n\ ⎢y⎥\n\ ⎢ ⎥\n\ ⎢1⎥\n\ ⎢─⎥\n\ ⎣z⎦\ """ assert pretty(Mcolumn) == ascii_str assert upretty(Mcolumn) == ucode_str ascii_str = \ """\ [[x]]\n\ [[ ]]\n\ [[y]]\n\ [[ ]]\n\ [[1]]\n\ [[-]]\n\ [[z]]\ """ ucode_str = \ """\ ⎡⎡x⎤⎤\n\ ⎢⎢ ⎥⎥\n\ ⎢⎢y⎥⎥\n\ ⎢⎢ ⎥⎥\n\ ⎢⎢1⎥⎥\n\ ⎢⎢─⎥⎥\n\ ⎣⎣z⎦⎦\ """ assert pretty(Mcol2) == ascii_str assert upretty(Mcol2) == ucode_str def test_tensor_TensorProduct(): A = MatrixSymbol("A", 3, 3) B = MatrixSymbol("B", 3, 3) assert upretty(TensorProduct(A, B)) == "A\u2297B" assert upretty(TensorProduct(A, B, A)) == "A\u2297B\u2297A" def test_diffgeom_print_WedgeProduct(): from sympy.diffgeom.rn import R2 from sympy.diffgeom import WedgeProduct wp = WedgeProduct(R2.dx, R2.dy) assert upretty(wp) == "ⅆ x∧ⅆ y" assert pretty(wp) == r"d x/\d y" def test_Adjoint(): X = MatrixSymbol('X', 2, 2) Y = MatrixSymbol('Y', 2, 2) assert pretty(Adjoint(X)) == " +\nX " assert pretty(Adjoint(X + Y)) == " +\n(X + Y) " assert pretty(Adjoint(X) + Adjoint(Y)) == " + +\nX + Y " assert pretty(Adjoint(X*Y)) == " +\n(X*Y) " assert pretty(Adjoint(Y)*Adjoint(X)) == " + +\nY *X " assert pretty(Adjoint(X**2)) == " +\n/ 2\\ \n\\X / " assert pretty(Adjoint(X)**2) == " 2\n/ +\\ \n\\X / " assert pretty(Adjoint(Inverse(X))) == " +\n/ -1\\ \n\\X / " assert pretty(Inverse(Adjoint(X))) == " -1\n/ +\\ \n\\X / " assert pretty(Adjoint(Transpose(X))) == " +\n/ T\\ \n\\X / " assert pretty(Transpose(Adjoint(X))) == " T\n/ +\\ \n\\X / " assert upretty(Adjoint(X)) == " †\nX " assert upretty(Adjoint(X + Y)) == " †\n(X + Y) " assert upretty(Adjoint(X) + Adjoint(Y)) == " † †\nX + Y " assert upretty(Adjoint(X*Y)) == " †\n(X⋅Y) " assert upretty(Adjoint(Y)*Adjoint(X)) == " † †\nY ⋅X " assert upretty(Adjoint(X**2)) == \ " †\n⎛ 2⎞ \n⎝X ⎠ " assert upretty(Adjoint(X)**2) == \ " 2\n⎛ †⎞ \n⎝X ⎠ " assert upretty(Adjoint(Inverse(X))) == \ " †\n⎛ -1⎞ \n⎝X ⎠ " assert upretty(Inverse(Adjoint(X))) == \ " -1\n⎛ †⎞ \n⎝X ⎠ " assert upretty(Adjoint(Transpose(X))) == \ " †\n⎛ T⎞ \n⎝X ⎠ " assert upretty(Transpose(Adjoint(X))) == \ " T\n⎛ †⎞ \n⎝X ⎠ " m = Matrix(((1, 2), (3, 4))) assert upretty(Adjoint(m)) == \ ' †\n'\ '⎡1 2⎤ \n'\ '⎢ ⎥ \n'\ '⎣3 4⎦ ' assert upretty(Adjoint(m+X)) == \ ' †\n'\ '⎛⎡1 2⎤ ⎞ \n'\ '⎜⎢ ⎥ + X⎟ \n'\ '⎝⎣3 4⎦ ⎠ ' def test_pretty_Trace_issue_9044(): X = Matrix([[1, 2], [3, 4]]) Y = Matrix([[2, 4], [6, 8]]) ascii_str_1 = \ """\ /[1 2]\\ tr|[ ]| \\[3 4]/\ """ ucode_str_1 = \ """\ ⎛⎡1 2⎤⎞ tr⎜⎢ ⎥⎟ ⎝⎣3 4⎦⎠\ """ ascii_str_2 = \ """\ /[1 2]\\ /[2 4]\\ tr|[ ]| + tr|[ ]| \\[3 4]/ \\[6 8]/\ """ ucode_str_2 = \ """\ ⎛⎡1 2⎤⎞ ⎛⎡2 4⎤⎞ tr⎜⎢ ⎥⎟ + tr⎜⎢ ⎥⎟ ⎝⎣3 4⎦⎠ ⎝⎣6 8⎦⎠\ """ assert pretty(Trace(X)) == ascii_str_1 assert upretty(Trace(X)) == ucode_str_1 assert pretty(Trace(X) + Trace(Y)) == ascii_str_2 assert upretty(Trace(X) + Trace(Y)) == ucode_str_2 def test_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) expr = MatrixSlice(X, (None, None, None), (None, None, None)) assert pretty(expr) == upretty(expr) == 'X[:, :]' expr = X[x:x + 1, y:y + 1] assert pretty(expr) == upretty(expr) == 'X[x:x + 1, y:y + 1]' expr = X[x:x + 1:2, y:y + 1:2] assert pretty(expr) == upretty(expr) == 'X[x:x + 1:2, y:y + 1:2]' expr = X[:x, y:] assert pretty(expr) == upretty(expr) == 'X[:x, y:]' expr = X[:x, y:] assert pretty(expr) == upretty(expr) == 'X[:x, y:]' expr = X[x:, :y] assert pretty(expr) == upretty(expr) == 'X[x:, :y]' expr = X[x:y, z:w] assert pretty(expr) == upretty(expr) == 'X[x:y, z:w]' expr = X[x:y:t, w:t:x] assert pretty(expr) == upretty(expr) == 'X[x:y:t, w:t:x]' expr = X[x::y, t::w] assert pretty(expr) == upretty(expr) == 'X[x::y, t::w]' expr = X[:x:y, :t:w] assert pretty(expr) == upretty(expr) == 'X[:x:y, :t:w]' expr = X[::x, ::y] assert pretty(expr) == upretty(expr) == 'X[::x, ::y]' expr = MatrixSlice(X, (0, None, None), (0, None, None)) assert pretty(expr) == upretty(expr) == 'X[:, :]' expr = MatrixSlice(X, (None, n, None), (None, n, None)) assert pretty(expr) == upretty(expr) == 'X[:, :]' expr = MatrixSlice(X, (0, n, None), (0, n, None)) assert pretty(expr) == upretty(expr) == 'X[:, :]' expr = MatrixSlice(X, (0, n, 2), (0, n, 2)) assert pretty(expr) == upretty(expr) == 'X[::2, ::2]' expr = X[1:2:3, 4:5:6] assert pretty(expr) == upretty(expr) == 'X[1:2:3, 4:5:6]' expr = X[1:3:5, 4:6:8] assert pretty(expr) == upretty(expr) == 'X[1:3:5, 4:6:8]' expr = X[1:10:2] assert pretty(expr) == upretty(expr) == 'X[1:10:2, :]' expr = Y[:5, 1:9:2] assert pretty(expr) == upretty(expr) == 'Y[:5, 1:9:2]' expr = Y[:5, 1:10:2] assert pretty(expr) == upretty(expr) == 'Y[:5, 1::2]' expr = Y[5, :5:2] assert pretty(expr) == upretty(expr) == 'Y[5:6, :5:2]' expr = X[0:1, 0:1] assert pretty(expr) == upretty(expr) == 'X[:1, :1]' expr = X[0:1:2, 0:1:2] assert pretty(expr) == upretty(expr) == 'X[:1:2, :1:2]' expr = (Y + Z)[2:, 2:] assert pretty(expr) == upretty(expr) == '(Y + Z)[2:, 2:]' def test_MatrixExpressions(): n = Symbol('n', integer=True) X = MatrixSymbol('X', n, n) assert pretty(X) == upretty(X) == "X" # Apply function elementwise (`ElementwiseApplyFunc`): expr = (X.T*X).applyfunc(sin) ascii_str = """\ / T \\\n\ (d -> sin(d)).\\X *X/\ """ ucode_str = """\ ⎛ T ⎞\n\ (d ↦ sin(d))˳⎝X ⋅X⎠\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str lamda = Lambda(x, 1/x) expr = (n*X).applyfunc(lamda) ascii_str = """\ / 1\\ \n\ |x -> -|.(n*X)\n\ \\ x/ \ """ ucode_str = """\ ⎛ 1⎞ \n\ ⎜x ↦ ─⎟˳(n⋅X)\n\ ⎝ x⎠ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_pretty_dotproduct(): from sympy.matrices.expressions.dotproduct import DotProduct n = symbols("n", integer=True) A = MatrixSymbol('A', n, 1) B = MatrixSymbol('B', n, 1) C = Matrix(1, 3, [1, 2, 3]) D = Matrix(1, 3, [1, 3, 4]) assert pretty(DotProduct(A, B)) == "A*B" assert pretty(DotProduct(C, D)) == "[1 2 3]*[1 3 4]" assert upretty(DotProduct(A, B)) == "A⋅B" assert upretty(DotProduct(C, D)) == "[1 2 3]⋅[1 3 4]" def test_pretty_piecewise(): expr = Piecewise((x, x < 1), (x**2, True)) ascii_str = \ """\ /x for x < 1\n\ | \n\ < 2 \n\ |x otherwise\n\ \\ \ """ ucode_str = \ """\ ⎧x for x < 1\n\ ⎪ \n\ ⎨ 2 \n\ ⎪x otherwise\n\ ⎩ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = -Piecewise((x, x < 1), (x**2, True)) ascii_str = \ """\ //x for x < 1\\\n\ || |\n\ -|< 2 |\n\ ||x otherwise|\n\ \\\\ /\ """ ucode_str = \ """\ ⎛⎧x for x < 1⎞\n\ ⎜⎪ ⎟\n\ -⎜⎨ 2 ⎟\n\ ⎜⎪x otherwise⎟\n\ ⎝⎩ ⎠\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = x + Piecewise((x, x > 0), (y, True)) + Piecewise((x/y, x < 2), (y**2, x > 2), (1, True)) + 1 ascii_str = \ """\ //x \\ \n\ ||- for x < 2| \n\ ||y | \n\ //x for x > 0\\ || | \n\ x + |< | + |< 2 | + 1\n\ \\\\y otherwise/ ||y for x > 2| \n\ || | \n\ ||1 otherwise| \n\ \\\\ / \ """ ucode_str = \ """\ ⎛⎧x ⎞ \n\ ⎜⎪─ for x < 2⎟ \n\ ⎜⎪y ⎟ \n\ ⎛⎧x for x > 0⎞ ⎜⎪ ⎟ \n\ x + ⎜⎨ ⎟ + ⎜⎨ 2 ⎟ + 1\n\ ⎝⎩y otherwise⎠ ⎜⎪y for x > 2⎟ \n\ ⎜⎪ ⎟ \n\ ⎜⎪1 otherwise⎟ \n\ ⎝⎩ ⎠ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = x - Piecewise((x, x > 0), (y, True)) + Piecewise((x/y, x < 2), (y**2, x > 2), (1, True)) + 1 ascii_str = \ """\ //x \\ \n\ ||- for x < 2| \n\ ||y | \n\ //x for x > 0\\ || | \n\ x - |< | + |< 2 | + 1\n\ \\\\y otherwise/ ||y for x > 2| \n\ || | \n\ ||1 otherwise| \n\ \\\\ / \ """ ucode_str = \ """\ ⎛⎧x ⎞ \n\ ⎜⎪─ for x < 2⎟ \n\ ⎜⎪y ⎟ \n\ ⎛⎧x for x > 0⎞ ⎜⎪ ⎟ \n\ x - ⎜⎨ ⎟ + ⎜⎨ 2 ⎟ + 1\n\ ⎝⎩y otherwise⎠ ⎜⎪y for x > 2⎟ \n\ ⎜⎪ ⎟ \n\ ⎜⎪1 otherwise⎟ \n\ ⎝⎩ ⎠ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = x*Piecewise((x, x > 0), (y, True)) ascii_str = \ """\ //x for x > 0\\\n\ x*|< |\n\ \\\\y otherwise/\ """ ucode_str = \ """\ ⎛⎧x for x > 0⎞\n\ x⋅⎜⎨ ⎟\n\ ⎝⎩y otherwise⎠\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Piecewise((x, x > 0), (y, True))*Piecewise((x/y, x < 2), (y**2, x > 2), (1, True)) ascii_str = \ """\ //x \\\n\ ||- for x < 2|\n\ ||y |\n\ //x for x > 0\\ || |\n\ |< |*|< 2 |\n\ \\\\y otherwise/ ||y for x > 2|\n\ || |\n\ ||1 otherwise|\n\ \\\\ /\ """ ucode_str = \ """\ ⎛⎧x ⎞\n\ ⎜⎪─ for x < 2⎟\n\ ⎜⎪y ⎟\n\ ⎛⎧x for x > 0⎞ ⎜⎪ ⎟\n\ ⎜⎨ ⎟⋅⎜⎨ 2 ⎟\n\ ⎝⎩y otherwise⎠ ⎜⎪y for x > 2⎟\n\ ⎜⎪ ⎟\n\ ⎜⎪1 otherwise⎟\n\ ⎝⎩ ⎠\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = -Piecewise((x, x > 0), (y, True))*Piecewise((x/y, x < 2), (y**2, x > 2), (1, True)) ascii_str = \ """\ //x \\\n\ ||- for x < 2|\n\ ||y |\n\ //x for x > 0\\ || |\n\ -|< |*|< 2 |\n\ \\\\y otherwise/ ||y for x > 2|\n\ || |\n\ ||1 otherwise|\n\ \\\\ /\ """ ucode_str = \ """\ ⎛⎧x ⎞\n\ ⎜⎪─ for x < 2⎟\n\ ⎜⎪y ⎟\n\ ⎛⎧x for x > 0⎞ ⎜⎪ ⎟\n\ -⎜⎨ ⎟⋅⎜⎨ 2 ⎟\n\ ⎝⎩y otherwise⎠ ⎜⎪y for x > 2⎟\n\ ⎜⎪ ⎟\n\ ⎜⎪1 otherwise⎟\n\ ⎝⎩ ⎠\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Piecewise((0, Abs(1/y) < 1), (1, Abs(y) < 1), (y*meijerg(((2, 1), ()), ((), (1, 0)), 1/y), True)) ascii_str = \ """\ / 1 \n\ | 0 for --- < 1\n\ | |y| \n\ | \n\ < 1 for |y| < 1\n\ | \n\ | __0, 2 /2, 1 | 1\\ \n\ |y*/__ | | -| otherwise \n\ \\ \\_|2, 2 \\ 1, 0 | y/ \ """ ucode_str = \ """\ ⎧ 1 \n\ ⎪ 0 for ─── < 1\n\ ⎪ │y│ \n\ ⎪ \n\ ⎨ 1 for │y│ < 1\n\ ⎪ \n\ ⎪ ╭─╮0, 2 ⎛2, 1 │ 1⎞ \n\ ⎪y⋅│╶┐ ⎜ │ ─⎟ otherwise \n\ ⎩ ╰─╯2, 2 ⎝ 1, 0 │ y⎠ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str # XXX: We have to use evaluate=False here because Piecewise._eval_power # denests the power. expr = Pow(Piecewise((x, x > 0), (y, True)), 2, evaluate=False) ascii_str = \ """\ 2\n\ //x for x > 0\\ \n\ |< | \n\ \\\\y otherwise/ \ """ ucode_str = \ """\ 2\n\ ⎛⎧x for x > 0⎞ \n\ ⎜⎨ ⎟ \n\ ⎝⎩y otherwise⎠ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_pretty_ITE(): expr = ITE(x, y, z) assert pretty(expr) == ( '/y for x \n' '< \n' '\\z otherwise' ) assert upretty(expr) == """\ ⎧y for x \n\ ⎨ \n\ ⎩z otherwise\ """ def test_pretty_seq(): expr = () ascii_str = \ """\ ()\ """ ucode_str = \ """\ ()\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = [] ascii_str = \ """\ []\ """ ucode_str = \ """\ []\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = {} expr_2 = {} ascii_str = \ """\ {}\ """ ucode_str = \ """\ {}\ """ assert pretty(expr) == ascii_str assert pretty(expr_2) == ascii_str assert upretty(expr) == ucode_str assert upretty(expr_2) == ucode_str expr = (1/x,) ascii_str = \ """\ 1 \n\ (-,)\n\ x \ """ ucode_str = \ """\ ⎛1 ⎞\n\ ⎜─,⎟\n\ ⎝x ⎠\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = [x**2, 1/x, x, y, sin(th)**2/cos(ph)**2] ascii_str = \ """\ 2 \n\ 2 1 sin (theta) \n\ [x , -, x, y, -----------]\n\ x 2 \n\ cos (phi) \ """ ucode_str = \ """\ ⎡ 2 ⎤\n\ ⎢ 2 1 sin (θ)⎥\n\ ⎢x , ─, x, y, ───────⎥\n\ ⎢ x 2 ⎥\n\ ⎣ cos (φ)⎦\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = (x**2, 1/x, x, y, sin(th)**2/cos(ph)**2) ascii_str = \ """\ 2 \n\ 2 1 sin (theta) \n\ (x , -, x, y, -----------)\n\ x 2 \n\ cos (phi) \ """ ucode_str = \ """\ ⎛ 2 ⎞\n\ ⎜ 2 1 sin (θ)⎟\n\ ⎜x , ─, x, y, ───────⎟\n\ ⎜ x 2 ⎟\n\ ⎝ cos (φ)⎠\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Tuple(x**2, 1/x, x, y, sin(th)**2/cos(ph)**2) ascii_str = \ """\ 2 \n\ 2 1 sin (theta) \n\ (x , -, x, y, -----------)\n\ x 2 \n\ cos (phi) \ """ ucode_str = \ """\ ⎛ 2 ⎞\n\ ⎜ 2 1 sin (θ)⎟\n\ ⎜x , ─, x, y, ───────⎟\n\ ⎜ x 2 ⎟\n\ ⎝ cos (φ)⎠\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = {x: sin(x)} expr_2 = Dict({x: sin(x)}) ascii_str = \ """\ {x: sin(x)}\ """ ucode_str = \ """\ {x: sin(x)}\ """ assert pretty(expr) == ascii_str assert pretty(expr_2) == ascii_str assert upretty(expr) == ucode_str assert upretty(expr_2) == ucode_str expr = {1/x: 1/y, x: sin(x)**2} expr_2 = Dict({1/x: 1/y, x: sin(x)**2}) ascii_str = \ """\ 1 1 2 \n\ {-: -, x: sin (x)}\n\ x y \ """ ucode_str = \ """\ ⎧1 1 2 ⎫\n\ ⎨─: ─, x: sin (x)⎬\n\ ⎩x y ⎭\ """ assert pretty(expr) == ascii_str assert pretty(expr_2) == ascii_str assert upretty(expr) == ucode_str assert upretty(expr_2) == ucode_str # There used to be a bug with pretty-printing sequences of even height. expr = [x**2] ascii_str = \ """\ 2 \n\ [x ]\ """ ucode_str = \ """\ ⎡ 2⎤\n\ ⎣x ⎦\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = (x**2,) ascii_str = \ """\ 2 \n\ (x ,)\ """ ucode_str = \ """\ ⎛ 2 ⎞\n\ ⎝x ,⎠\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Tuple(x**2) ascii_str = \ """\ 2 \n\ (x ,)\ """ ucode_str = \ """\ ⎛ 2 ⎞\n\ ⎝x ,⎠\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = {x**2: 1} expr_2 = Dict({x**2: 1}) ascii_str = \ """\ 2 \n\ {x : 1}\ """ ucode_str = \ """\ ⎧ 2 ⎫\n\ ⎨x : 1⎬\n\ ⎩ ⎭\ """ assert pretty(expr) == ascii_str assert pretty(expr_2) == ascii_str assert upretty(expr) == ucode_str assert upretty(expr_2) == ucode_str def test_any_object_in_sequence(): # Cf. issue 5306 b1 = Basic() b2 = Basic(Basic()) expr = [b2, b1] assert pretty(expr) == "[Basic(Basic()), Basic()]" assert upretty(expr) == "[Basic(Basic()), Basic()]" expr = {b2, b1} assert pretty(expr) == "{Basic(), Basic(Basic())}" assert upretty(expr) == "{Basic(), Basic(Basic())}" expr = {b2: b1, b1: b2} expr2 = Dict({b2: b1, b1: b2}) assert pretty(expr) == "{Basic(): Basic(Basic()), Basic(Basic()): Basic()}" assert pretty( expr2) == "{Basic(): Basic(Basic()), Basic(Basic()): Basic()}" assert upretty( expr) == "{Basic(): Basic(Basic()), Basic(Basic()): Basic()}" assert upretty( expr2) == "{Basic(): Basic(Basic()), Basic(Basic()): Basic()}" def test_print_builtin_set(): assert pretty(set()) == 'set()' assert upretty(set()) == 'set()' assert pretty(frozenset()) == 'frozenset()' assert upretty(frozenset()) == 'frozenset()' s1 = {1/x, x} s2 = frozenset(s1) assert pretty(s1) == \ """\ 1 \n\ {-, x} x \ """ assert upretty(s1) == \ """\ ⎧1 ⎫ ⎨─, x⎬ ⎩x ⎭\ """ assert pretty(s2) == \ """\ 1 \n\ frozenset({-, x}) x \ """ assert upretty(s2) == \ """\ ⎛⎧1 ⎫⎞ frozenset⎜⎨─, x⎬⎟ ⎝⎩x ⎭⎠\ """ def test_pretty_sets(): s = FiniteSet assert pretty(s(*[x*y, x**2])) == \ """\ 2 \n\ {x , x*y}\ """ assert pretty(s(*range(1, 6))) == "{1, 2, 3, 4, 5}" assert pretty(s(*range(1, 13))) == "{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}" assert pretty({x*y, x**2}) == \ """\ 2 \n\ {x , x*y}\ """ assert pretty(set(range(1, 6))) == "{1, 2, 3, 4, 5}" assert pretty(set(range(1, 13))) == \ "{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}" assert pretty(frozenset([x*y, x**2])) == \ """\ 2 \n\ frozenset({x , x*y})\ """ assert pretty(frozenset(range(1, 6))) == "frozenset({1, 2, 3, 4, 5})" assert pretty(frozenset(range(1, 13))) == \ "frozenset({1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12})" assert pretty(Range(0, 3, 1)) == '{0, 1, 2}' ascii_str = '{0, 1, ..., 29}' ucode_str = '{0, 1, …, 29}' assert pretty(Range(0, 30, 1)) == ascii_str assert upretty(Range(0, 30, 1)) == ucode_str ascii_str = '{30, 29, ..., 2}' ucode_str = '{30, 29, …, 2}' assert pretty(Range(30, 1, -1)) == ascii_str assert upretty(Range(30, 1, -1)) == ucode_str ascii_str = '{0, 2, ...}' ucode_str = '{0, 2, …}' assert pretty(Range(0, oo, 2)) == ascii_str assert upretty(Range(0, oo, 2)) == ucode_str ascii_str = '{..., 2, 0}' ucode_str = '{…, 2, 0}' assert pretty(Range(oo, -2, -2)) == ascii_str assert upretty(Range(oo, -2, -2)) == ucode_str ascii_str = '{-2, -3, ...}' ucode_str = '{-2, -3, …}' assert pretty(Range(-2, -oo, -1)) == ascii_str assert upretty(Range(-2, -oo, -1)) == ucode_str def test_pretty_SetExpr(): iv = Interval(1, 3) se = SetExpr(iv) ascii_str = "SetExpr([1, 3])" ucode_str = "SetExpr([1, 3])" assert pretty(se) == ascii_str assert upretty(se) == ucode_str def test_pretty_ImageSet(): imgset = ImageSet(Lambda((x, y), x + y), {1, 2, 3}, {3, 4}) ascii_str = '{x + y | x in {1, 2, 3}, y in {3, 4}}' ucode_str = '{x + y │ x ∊ {1, 2, 3}, y ∊ {3, 4}}' assert pretty(imgset) == ascii_str assert upretty(imgset) == ucode_str imgset = ImageSet(Lambda(((x, y),), x + y), ProductSet({1, 2, 3}, {3, 4})) ascii_str = '{x + y | (x, y) in {1, 2, 3} x {3, 4}}' ucode_str = '{x + y │ (x, y) ∊ {1, 2, 3} × {3, 4}}' assert pretty(imgset) == ascii_str assert upretty(imgset) == ucode_str imgset = ImageSet(Lambda(x, x**2), S.Naturals) ascii_str = '''\ 2 \n\ {x | x in Naturals}''' ucode_str = '''\ ⎧ 2 │ ⎫\n\ ⎨x │ x ∊ ℕ⎬\n\ ⎩ │ ⎭''' assert pretty(imgset) == ascii_str assert upretty(imgset) == ucode_str # TODO: The "x in N" parts below should be centered independently of the # 1/x**2 fraction imgset = ImageSet(Lambda(x, 1/x**2), S.Naturals) ascii_str = '''\ 1 \n\ {-- | x in Naturals} 2 \n\ x ''' ucode_str = '''\ ⎧1 │ ⎫\n\ ⎪── │ x ∊ ℕ⎪\n\ ⎨ 2 │ ⎬\n\ ⎪x │ ⎪\n\ ⎩ │ ⎭''' assert pretty(imgset) == ascii_str assert upretty(imgset) == ucode_str imgset = ImageSet(Lambda((x, y), 1/(x + y)**2), S.Naturals, S.Naturals) ascii_str = '''\ 1 \n\ {-------- | x in Naturals, y in Naturals} 2 \n\ (x + y) ''' ucode_str = '''\ ⎧ 1 │ ⎫ ⎪──────── │ x ∊ ℕ, y ∊ ℕ⎪ ⎨ 2 │ ⎬ ⎪(x + y) │ ⎪ ⎩ │ ⎭''' assert pretty(imgset) == ascii_str assert upretty(imgset) == ucode_str def test_pretty_ConditionSet(): ascii_str = '{x | x in (-oo, oo) and sin(x) = 0}' ucode_str = '{x │ x ∊ ℝ ∧ (sin(x) = 0)}' assert pretty(ConditionSet(x, Eq(sin(x), 0), S.Reals)) == ascii_str assert upretty(ConditionSet(x, Eq(sin(x), 0), S.Reals)) == ucode_str assert pretty(ConditionSet(x, Contains(x, S.Reals, evaluate=False), FiniteSet(1))) == '{1}' assert upretty(ConditionSet(x, Contains(x, S.Reals, evaluate=False), FiniteSet(1))) == '{1}' assert pretty(ConditionSet(x, And(x > 1, x < -1), FiniteSet(1, 2, 3))) == "EmptySet" assert upretty(ConditionSet(x, And(x > 1, x < -1), FiniteSet(1, 2, 3))) == "∅" assert pretty(ConditionSet(x, Or(x > 1, x < -1), FiniteSet(1, 2))) == '{2}' assert upretty(ConditionSet(x, Or(x > 1, x < -1), FiniteSet(1, 2))) == '{2}' condset = ConditionSet(x, 1/x**2 > 0) ascii_str = '''\ 1 \n\ {x | -- > 0} 2 \n\ x ''' ucode_str = '''\ ⎧ │ ⎛1 ⎞⎫ ⎪x │ ⎜── > 0⎟⎪ ⎨ │ ⎜ 2 ⎟⎬ ⎪ │ ⎝x ⎠⎪ ⎩ │ ⎭''' assert pretty(condset) == ascii_str assert upretty(condset) == ucode_str condset = ConditionSet(x, 1/x**2 > 0, S.Reals) ascii_str = '''\ 1 \n\ {x | x in (-oo, oo) and -- > 0} 2 \n\ x ''' ucode_str = '''\ ⎧ │ ⎛1 ⎞⎫ ⎪x │ x ∊ ℝ ∧ ⎜── > 0⎟⎪ ⎨ │ ⎜ 2 ⎟⎬ ⎪ │ ⎝x ⎠⎪ ⎩ │ ⎭''' assert pretty(condset) == ascii_str assert upretty(condset) == ucode_str def test_pretty_ComplexRegion(): from sympy.sets.fancysets import ComplexRegion cregion = ComplexRegion(Interval(3, 5)*Interval(4, 6)) ascii_str = '{x + y*I | x, y in [3, 5] x [4, 6]}' ucode_str = '{x + y⋅ⅈ │ x, y ∊ [3, 5] × [4, 6]}' assert pretty(cregion) == ascii_str assert upretty(cregion) == ucode_str cregion = ComplexRegion(Interval(0, 1)*Interval(0, 2*pi), polar=True) ascii_str = '{r*(I*sin(theta) + cos(theta)) | r, theta in [0, 1] x [0, 2*pi)}' ucode_str = '{r⋅(ⅈ⋅sin(θ) + cos(θ)) │ r, θ ∊ [0, 1] × [0, 2⋅π)}' assert pretty(cregion) == ascii_str assert upretty(cregion) == ucode_str cregion = ComplexRegion(Interval(3, 1/a**2)*Interval(4, 6)) ascii_str = '''\ 1 \n\ {x + y*I | x, y in [3, --] x [4, 6]} 2 \n\ a ''' ucode_str = '''\ ⎧ │ ⎡ 1 ⎤ ⎫ ⎪x + y⋅ⅈ │ x, y ∊ ⎢3, ──⎥ × [4, 6]⎪ ⎨ │ ⎢ 2⎥ ⎬ ⎪ │ ⎣ a ⎦ ⎪ ⎩ │ ⎭''' assert pretty(cregion) == ascii_str assert upretty(cregion) == ucode_str cregion = ComplexRegion(Interval(0, 1/a**2)*Interval(0, 2*pi), polar=True) ascii_str = '''\ 1 \n\ {r*(I*sin(theta) + cos(theta)) | r, theta in [0, --] x [0, 2*pi)} 2 \n\ a ''' ucode_str = '''\ ⎧ │ ⎡ 1 ⎤ ⎫ ⎪r⋅(ⅈ⋅sin(θ) + cos(θ)) │ r, θ ∊ ⎢0, ──⎥ × [0, 2⋅π)⎪ ⎨ │ ⎢ 2⎥ ⎬ ⎪ │ ⎣ a ⎦ ⎪ ⎩ │ ⎭''' assert pretty(cregion) == ascii_str assert upretty(cregion) == ucode_str def test_pretty_Union_issue_10414(): a, b = Interval(2, 3), Interval(4, 7) ucode_str = '[2, 3] ∪ [4, 7]' ascii_str = '[2, 3] U [4, 7]' assert upretty(Union(a, b)) == ucode_str assert pretty(Union(a, b)) == ascii_str def test_pretty_Intersection_issue_10414(): x, y, z, w = symbols('x, y, z, w') a, b = Interval(x, y), Interval(z, w) ucode_str = '[x, y] ∩ [z, w]' ascii_str = '[x, y] n [z, w]' assert upretty(Intersection(a, b)) == ucode_str assert pretty(Intersection(a, b)) == ascii_str def test_ProductSet_exponent(): ucode_str = ' 1\n[0, 1] ' assert upretty(Interval(0, 1)**1) == ucode_str ucode_str = ' 2\n[0, 1] ' assert upretty(Interval(0, 1)**2) == ucode_str def test_ProductSet_parenthesis(): ucode_str = '([4, 7] × {1, 2}) ∪ ([2, 3] × [4, 7])' a, b = Interval(2, 3), Interval(4, 7) assert upretty(Union(a*b, b*FiniteSet(1, 2))) == ucode_str def test_ProductSet_prod_char_issue_10413(): ascii_str = '[2, 3] x [4, 7]' ucode_str = '[2, 3] × [4, 7]' a, b = Interval(2, 3), Interval(4, 7) assert pretty(a*b) == ascii_str assert upretty(a*b) == ucode_str def test_pretty_sequences(): s1 = SeqFormula(a**2, (0, oo)) s2 = SeqPer((1, 2)) ascii_str = '[0, 1, 4, 9, ...]' ucode_str = '[0, 1, 4, 9, …]' assert pretty(s1) == ascii_str assert upretty(s1) == ucode_str ascii_str = '[1, 2, 1, 2, ...]' ucode_str = '[1, 2, 1, 2, …]' assert pretty(s2) == ascii_str assert upretty(s2) == ucode_str s3 = SeqFormula(a**2, (0, 2)) s4 = SeqPer((1, 2), (0, 2)) ascii_str = '[0, 1, 4]' ucode_str = '[0, 1, 4]' assert pretty(s3) == ascii_str assert upretty(s3) == ucode_str ascii_str = '[1, 2, 1]' ucode_str = '[1, 2, 1]' assert pretty(s4) == ascii_str assert upretty(s4) == ucode_str s5 = SeqFormula(a**2, (-oo, 0)) s6 = SeqPer((1, 2), (-oo, 0)) ascii_str = '[..., 9, 4, 1, 0]' ucode_str = '[…, 9, 4, 1, 0]' assert pretty(s5) == ascii_str assert upretty(s5) == ucode_str ascii_str = '[..., 2, 1, 2, 1]' ucode_str = '[…, 2, 1, 2, 1]' assert pretty(s6) == ascii_str assert upretty(s6) == ucode_str ascii_str = '[1, 3, 5, 11, ...]' ucode_str = '[1, 3, 5, 11, …]' assert pretty(SeqAdd(s1, s2)) == ascii_str assert upretty(SeqAdd(s1, s2)) == ucode_str ascii_str = '[1, 3, 5]' ucode_str = '[1, 3, 5]' assert pretty(SeqAdd(s3, s4)) == ascii_str assert upretty(SeqAdd(s3, s4)) == ucode_str ascii_str = '[..., 11, 5, 3, 1]' ucode_str = '[…, 11, 5, 3, 1]' assert pretty(SeqAdd(s5, s6)) == ascii_str assert upretty(SeqAdd(s5, s6)) == ucode_str ascii_str = '[0, 2, 4, 18, ...]' ucode_str = '[0, 2, 4, 18, …]' assert pretty(SeqMul(s1, s2)) == ascii_str assert upretty(SeqMul(s1, s2)) == ucode_str ascii_str = '[0, 2, 4]' ucode_str = '[0, 2, 4]' assert pretty(SeqMul(s3, s4)) == ascii_str assert upretty(SeqMul(s3, s4)) == ucode_str ascii_str = '[..., 18, 4, 2, 0]' ucode_str = '[…, 18, 4, 2, 0]' assert pretty(SeqMul(s5, s6)) == ascii_str assert upretty(SeqMul(s5, s6)) == ucode_str # Sequences with symbolic limits, issue 12629 s7 = SeqFormula(a**2, (a, 0, x)) raises(NotImplementedError, lambda: pretty(s7)) raises(NotImplementedError, lambda: upretty(s7)) b = Symbol('b') s8 = SeqFormula(b*a**2, (a, 0, 2)) ascii_str = '[0, b, 4*b]' ucode_str = '[0, b, 4⋅b]' assert pretty(s8) == ascii_str assert upretty(s8) == ucode_str def test_pretty_FourierSeries(): f = fourier_series(x, (x, -pi, pi)) ascii_str = \ """\ 2*sin(3*x) \n\ 2*sin(x) - sin(2*x) + ---------- + ...\n\ 3 \ """ ucode_str = \ """\ 2⋅sin(3⋅x) \n\ 2⋅sin(x) - sin(2⋅x) + ────────── + …\n\ 3 \ """ assert pretty(f) == ascii_str assert upretty(f) == ucode_str def test_pretty_FormalPowerSeries(): f = fps(log(1 + x)) ascii_str = \ """\ oo \n\ ____ \n\ \\ ` \n\ \\ -k k \n\ \\ -(-1) *x \n\ / -----------\n\ / k \n\ /___, \n\ k = 1 \ """ ucode_str = \ """\ ∞ \n\ ____ \n\ ╲ \n\ ╲ -k k \n\ ╲ -(-1) ⋅x \n\ ╱ ───────────\n\ ╱ k \n\ ╱ \n\ ‾‾‾‾ \n\ k = 1 \ """ assert pretty(f) == ascii_str assert upretty(f) == ucode_str def test_pretty_limits(): expr = Limit(x, x, oo) ascii_str = \ """\ lim x\n\ x->oo \ """ ucode_str = \ """\ lim x\n\ x─→∞ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Limit(x**2, x, 0) ascii_str = \ """\ 2\n\ lim x \n\ x->0+ \ """ ucode_str = \ """\ 2\n\ lim x \n\ x─→0⁺ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Limit(1/x, x, 0) ascii_str = \ """\ 1\n\ lim -\n\ x->0+x\ """ ucode_str = \ """\ 1\n\ lim ─\n\ x─→0⁺x\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Limit(sin(x)/x, x, 0) ascii_str = \ """\ /sin(x)\\\n\ lim |------|\n\ x->0+\\ x /\ """ ucode_str = \ """\ ⎛sin(x)⎞\n\ lim ⎜──────⎟\n\ x─→0⁺⎝ x ⎠\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Limit(sin(x)/x, x, 0, "-") ascii_str = \ """\ /sin(x)\\\n\ lim |------|\n\ x->0-\\ x /\ """ ucode_str = \ """\ ⎛sin(x)⎞\n\ lim ⎜──────⎟\n\ x─→0⁻⎝ x ⎠\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Limit(x + sin(x), x, 0) ascii_str = \ """\ lim (x + sin(x))\n\ x->0+ \ """ ucode_str = \ """\ lim (x + sin(x))\n\ x─→0⁺ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Limit(x, x, 0)**2 ascii_str = \ """\ 2\n\ / lim x\\ \n\ \\x->0+ / \ """ ucode_str = \ """\ 2\n\ ⎛ lim x⎞ \n\ ⎝x─→0⁺ ⎠ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Limit(x*Limit(y/2,y,0), x, 0) ascii_str = \ """\ / /y\\\\\n\ lim |x* lim |-||\n\ x->0+\\ y->0+\\2//\ """ ucode_str = \ """\ ⎛ ⎛y⎞⎞\n\ lim ⎜x⋅ lim ⎜─⎟⎟\n\ x─→0⁺⎝ y─→0⁺⎝2⎠⎠\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = 2*Limit(x*Limit(y/2,y,0), x, 0) ascii_str = \ """\ / /y\\\\\n\ 2* lim |x* lim |-||\n\ x->0+\\ y->0+\\2//\ """ ucode_str = \ """\ ⎛ ⎛y⎞⎞\n\ 2⋅ lim ⎜x⋅ lim ⎜─⎟⎟\n\ x─→0⁺⎝ y─→0⁺⎝2⎠⎠\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Limit(sin(x), x, 0, dir='+-') ascii_str = \ """\ lim sin(x)\n\ x->0 \ """ ucode_str = \ """\ lim sin(x)\n\ x─→0 \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_pretty_ComplexRootOf(): expr = rootof(x**5 + 11*x - 2, 0) ascii_str = \ """\ / 5 \\\n\ CRootOf\\x + 11*x - 2, 0/\ """ ucode_str = \ """\ ⎛ 5 ⎞\n\ CRootOf⎝x + 11⋅x - 2, 0⎠\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_pretty_RootSum(): expr = RootSum(x**5 + 11*x - 2, auto=False) ascii_str = \ """\ / 5 \\\n\ RootSum\\x + 11*x - 2/\ """ ucode_str = \ """\ ⎛ 5 ⎞\n\ RootSum⎝x + 11⋅x - 2⎠\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = RootSum(x**5 + 11*x - 2, Lambda(z, exp(z))) ascii_str = \ """\ / 5 z\\\n\ RootSum\\x + 11*x - 2, z -> e /\ """ ucode_str = \ """\ ⎛ 5 z⎞\n\ RootSum⎝x + 11⋅x - 2, z ↦ ℯ ⎠\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_GroebnerBasis(): expr = groebner([], x, y) ascii_str = \ """\ GroebnerBasis([], x, y, domain=ZZ, order=lex)\ """ ucode_str = \ """\ GroebnerBasis([], x, y, domain=ℤ, order=lex)\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str F = [x**2 - 3*y - x + 1, y**2 - 2*x + y - 1] expr = groebner(F, x, y, order='grlex') ascii_str = \ """\ /[ 2 2 ] \\\n\ GroebnerBasis\\[x - x - 3*y + 1, y - 2*x + y - 1], x, y, domain=ZZ, order=grlex/\ """ ucode_str = \ """\ ⎛⎡ 2 2 ⎤ ⎞\n\ GroebnerBasis⎝⎣x - x - 3⋅y + 1, y - 2⋅x + y - 1⎦, x, y, domain=ℤ, order=grlex⎠\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = expr.fglm('lex') ascii_str = \ """\ /[ 2 4 3 2 ] \\\n\ GroebnerBasis\\[2*x - y - y + 1, y + 2*y - 3*y - 16*y + 7], x, y, domain=ZZ, order=lex/\ """ ucode_str = \ """\ ⎛⎡ 2 4 3 2 ⎤ ⎞\n\ GroebnerBasis⎝⎣2⋅x - y - y + 1, y + 2⋅y - 3⋅y - 16⋅y + 7⎦, x, y, domain=ℤ, order=lex⎠\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_pretty_UniversalSet(): assert pretty(S.UniversalSet) == "UniversalSet" assert upretty(S.UniversalSet) == '𝕌' def test_pretty_Boolean(): expr = Not(x, evaluate=False) assert pretty(expr) == "Not(x)" assert upretty(expr) == "¬x" expr = And(x, y) assert pretty(expr) == "And(x, y)" assert upretty(expr) == "x ∧ y" expr = Or(x, y) assert pretty(expr) == "Or(x, y)" assert upretty(expr) == "x ∨ y" syms = symbols('a:f') expr = And(*syms) assert pretty(expr) == "And(a, b, c, d, e, f)" assert upretty(expr) == "a ∧ b ∧ c ∧ d ∧ e ∧ f" expr = Or(*syms) assert pretty(expr) == "Or(a, b, c, d, e, f)" assert upretty(expr) == "a ∨ b ∨ c ∨ d ∨ e ∨ f" expr = Xor(x, y, evaluate=False) assert pretty(expr) == "Xor(x, y)" assert upretty(expr) == "x ⊻ y" expr = Nand(x, y, evaluate=False) assert pretty(expr) == "Nand(x, y)" assert upretty(expr) == "x ⊼ y" expr = Nor(x, y, evaluate=False) assert pretty(expr) == "Nor(x, y)" assert upretty(expr) == "x ⊽ y" expr = Implies(x, y, evaluate=False) assert pretty(expr) == "Implies(x, y)" assert upretty(expr) == "x → y" # don't sort args expr = Implies(y, x, evaluate=False) assert pretty(expr) == "Implies(y, x)" assert upretty(expr) == "y → x" expr = Equivalent(x, y, evaluate=False) assert pretty(expr) == "Equivalent(x, y)" assert upretty(expr) == "x ⇔ y" expr = Equivalent(y, x, evaluate=False) assert pretty(expr) == "Equivalent(x, y)" assert upretty(expr) == "x ⇔ y" def test_pretty_Domain(): expr = FF(23) assert pretty(expr) == "GF(23)" assert upretty(expr) == "ℤ₂₃" expr = ZZ assert pretty(expr) == "ZZ" assert upretty(expr) == "ℤ" expr = QQ assert pretty(expr) == "QQ" assert upretty(expr) == "ℚ" expr = RR assert pretty(expr) == "RR" assert upretty(expr) == "ℝ" expr = QQ[x] assert pretty(expr) == "QQ[x]" assert upretty(expr) == "ℚ[x]" expr = QQ[x, y] assert pretty(expr) == "QQ[x, y]" assert upretty(expr) == "ℚ[x, y]" expr = ZZ.frac_field(x) assert pretty(expr) == "ZZ(x)" assert upretty(expr) == "ℤ(x)" expr = ZZ.frac_field(x, y) assert pretty(expr) == "ZZ(x, y)" assert upretty(expr) == "ℤ(x, y)" expr = QQ.poly_ring(x, y, order=grlex) assert pretty(expr) == "QQ[x, y, order=grlex]" assert upretty(expr) == "ℚ[x, y, order=grlex]" expr = QQ.poly_ring(x, y, order=ilex) assert pretty(expr) == "QQ[x, y, order=ilex]" assert upretty(expr) == "ℚ[x, y, order=ilex]" def test_pretty_prec(): assert xpretty(S("0.3"), full_prec=True, wrap_line=False) == "0.300000000000000" assert xpretty(S("0.3"), full_prec="auto", wrap_line=False) == "0.300000000000000" assert xpretty(S("0.3"), full_prec=False, wrap_line=False) == "0.3" assert xpretty(S("0.3")*x, full_prec=True, use_unicode=False, wrap_line=False) in [ "0.300000000000000*x", "x*0.300000000000000" ] assert xpretty(S("0.3")*x, full_prec="auto", use_unicode=False, wrap_line=False) in [ "0.3*x", "x*0.3" ] assert xpretty(S("0.3")*x, full_prec=False, use_unicode=False, wrap_line=False) in [ "0.3*x", "x*0.3" ] def test_pprint(): import sys from io import StringIO fd = StringIO() sso = sys.stdout sys.stdout = fd try: pprint(pi, use_unicode=False, wrap_line=False) finally: sys.stdout = sso assert fd.getvalue() == 'pi\n' def test_pretty_class(): """Test that the printer dispatcher correctly handles classes.""" class C: pass # C has no .__class__ and this was causing problems class D: pass assert pretty( C ) == str( C ) assert pretty( D ) == str( D ) def test_pretty_no_wrap_line(): huge_expr = 0 for i in range(20): huge_expr += i*sin(i + x) assert xpretty(huge_expr ).find('\n') != -1 assert xpretty(huge_expr, wrap_line=False).find('\n') == -1 def test_settings(): raises(TypeError, lambda: pretty(S(4), method="garbage")) def test_pretty_sum(): from sympy.abc import x, a, b, k, m, n expr = Sum(k**k, (k, 0, n)) ascii_str = \ """\ n \n\ ___ \n\ \\ ` \n\ \\ k\n\ / k \n\ /__, \n\ k = 0 \ """ ucode_str = \ """\ n \n\ ___ \n\ ╲ \n\ ╲ k\n\ ╱ k \n\ ╱ \n\ ‾‾‾ \n\ k = 0 \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Sum(k**k, (k, oo, n)) ascii_str = \ """\ n \n\ ___ \n\ \\ ` \n\ \\ k\n\ / k \n\ /__, \n\ k = oo \ """ ucode_str = \ """\ n \n\ ___ \n\ ╲ \n\ ╲ k\n\ ╱ k \n\ ╱ \n\ ‾‾‾ \n\ k = ∞ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Sum(k**(Integral(x**n, (x, -oo, oo))), (k, 0, n**n)) ascii_str = \ """\ n \n\ n \n\ ______ \n\ \\ ` \n\ \\ oo \n\ \\ / \n\ \\ | \n\ \\ | n \n\ ) | x dx\n\ / | \n\ / / \n\ / -oo \n\ / k \n\ /_____, \n\ k = 0 \ """ ucode_str = \ """\ n \n\ n \n\ ______ \n\ ╲ \n\ ╲ \n\ ╲ ∞ \n\ ╲ ⌠ \n\ ╲ ⎮ n \n\ ╱ ⎮ x dx\n\ ╱ ⌡ \n\ ╱ -∞ \n\ ╱ k \n\ ╱ \n\ ‾‾‾‾‾‾ \n\ k = 0 \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Sum(k**( Integral(x**n, (x, -oo, oo))), (k, 0, Integral(x**x, (x, -oo, oo)))) ascii_str = \ """\ oo \n\ / \n\ | \n\ | x \n\ | x dx \n\ | \n\ / \n\ -oo \n\ ______ \n\ \\ ` \n\ \\ oo \n\ \\ / \n\ \\ | \n\ \\ | n \n\ ) | x dx\n\ / | \n\ / / \n\ / -oo \n\ / k \n\ /_____, \n\ k = 0 \ """ ucode_str = \ """\ ∞ \n\ ⌠ \n\ ⎮ x \n\ ⎮ x dx \n\ ⌡ \n\ -∞ \n\ ______ \n\ ╲ \n\ ╲ \n\ ╲ ∞ \n\ ╲ ⌠ \n\ ╲ ⎮ n \n\ ╱ ⎮ x dx\n\ ╱ ⌡ \n\ ╱ -∞ \n\ ╱ k \n\ ╱ \n\ ‾‾‾‾‾‾ \n\ k = 0 \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Sum(k**(Integral(x**n, (x, -oo, oo))), ( k, x + n + x**2 + n**2 + (x/n) + (1/x), Integral(x**x, (x, -oo, oo)))) ascii_str = \ """\ oo \n\ / \n\ | \n\ | x \n\ | x dx \n\ | \n\ / \n\ -oo \n\ ______ \n\ \\ ` \n\ \\ oo \n\ \\ / \n\ \\ | \n\ \\ | n \n\ ) | x dx\n\ / | \n\ / / \n\ / -oo \n\ / k \n\ /_____, \n\ 2 2 1 x \n\ k = n + n + x + x + - + - \n\ x n \ """ ucode_str = \ """\ ∞ \n\ ⌠ \n\ ⎮ x \n\ ⎮ x dx \n\ ⌡ \n\ -∞ \n\ ______ \n\ ╲ \n\ ╲ \n\ ╲ ∞ \n\ ╲ ⌠ \n\ ╲ ⎮ n \n\ ╱ ⎮ x dx\n\ ╱ ⌡ \n\ ╱ -∞ \n\ ╱ k \n\ ╱ \n\ ‾‾‾‾‾‾ \n\ 2 2 1 x \n\ k = n + n + x + x + ─ + ─ \n\ x n \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Sum(k**( Integral(x**n, (x, -oo, oo))), (k, 0, x + n + x**2 + n**2 + (x/n) + (1/x))) ascii_str = \ """\ 2 2 1 x \n\ n + n + x + x + - + - \n\ x n \n\ ______ \n\ \\ ` \n\ \\ oo \n\ \\ / \n\ \\ | \n\ \\ | n \n\ ) | x dx\n\ / | \n\ / / \n\ / -oo \n\ / k \n\ /_____, \n\ k = 0 \ """ ucode_str = \ """\ 2 2 1 x \n\ n + n + x + x + ─ + ─ \n\ x n \n\ ______ \n\ ╲ \n\ ╲ \n\ ╲ ∞ \n\ ╲ ⌠ \n\ ╲ ⎮ n \n\ ╱ ⎮ x dx\n\ ╱ ⌡ \n\ ╱ -∞ \n\ ╱ k \n\ ╱ \n\ ‾‾‾‾‾‾ \n\ k = 0 \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Sum(x, (x, 0, oo)) ascii_str = \ """\ oo \n\ __ \n\ \\ ` \n\ ) x\n\ /_, \n\ x = 0 \ """ ucode_str = \ """\ ∞ \n\ ___ \n\ ╲ \n\ ╲ \n\ ╱ x\n\ ╱ \n\ ‾‾‾ \n\ x = 0 \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Sum(x**2, (x, 0, oo)) ascii_str = \ """\ oo \n\ ___ \n\ \\ ` \n\ \\ 2\n\ / x \n\ /__, \n\ x = 0 \ """ ucode_str = \ """\ ∞ \n\ ___ \n\ ╲ \n\ ╲ 2\n\ ╱ x \n\ ╱ \n\ ‾‾‾ \n\ x = 0 \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Sum(x/2, (x, 0, oo)) ascii_str = \ """\ oo \n\ ___ \n\ \\ ` \n\ \\ x\n\ ) -\n\ / 2\n\ /__, \n\ x = 0 \ """ ucode_str = \ """\ ∞ \n\ ____ \n\ ╲ \n\ ╲ \n\ ╲ x\n\ ╱ ─\n\ ╱ 2\n\ ╱ \n\ ‾‾‾‾ \n\ x = 0 \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Sum(x**3/2, (x, 0, oo)) ascii_str = \ """\ oo \n\ ____ \n\ \\ ` \n\ \\ 3\n\ \\ x \n\ / --\n\ / 2 \n\ /___, \n\ x = 0 \ """ ucode_str = \ """\ ∞ \n\ ____ \n\ ╲ \n\ ╲ 3\n\ ╲ x \n\ ╱ ──\n\ ╱ 2 \n\ ╱ \n\ ‾‾‾‾ \n\ x = 0 \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Sum((x**3*y**(x/2))**n, (x, 0, oo)) ascii_str = \ """\ oo \n\ ____ \n\ \\ ` \n\ \\ n\n\ \\ / x\\ \n\ ) | -| \n\ / | 3 2| \n\ / \\x *y / \n\ /___, \n\ x = 0 \ """ ucode_str = \ """\ ∞ \n\ _____ \n\ ╲ \n\ ╲ \n\ ╲ n\n\ ╲ ⎛ x⎞ \n\ ╱ ⎜ ─⎟ \n\ ╱ ⎜ 3 2⎟ \n\ ╱ ⎝x ⋅y ⎠ \n\ ╱ \n\ ‾‾‾‾‾ \n\ x = 0 \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Sum(1/x**2, (x, 0, oo)) ascii_str = \ """\ oo \n\ ____ \n\ \\ ` \n\ \\ 1 \n\ \\ --\n\ / 2\n\ / x \n\ /___, \n\ x = 0 \ """ ucode_str = \ """\ ∞ \n\ ____ \n\ ╲ \n\ ╲ 1 \n\ ╲ ──\n\ ╱ 2\n\ ╱ x \n\ ╱ \n\ ‾‾‾‾ \n\ x = 0 \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Sum(1/y**(a/b), (x, 0, oo)) ascii_str = \ """\ oo \n\ ____ \n\ \\ ` \n\ \\ -a \n\ \\ ---\n\ / b \n\ / y \n\ /___, \n\ x = 0 \ """ ucode_str = \ """\ ∞ \n\ ____ \n\ ╲ \n\ ╲ -a \n\ ╲ ───\n\ ╱ b \n\ ╱ y \n\ ╱ \n\ ‾‾‾‾ \n\ x = 0 \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Sum(1/y**(a/b), (x, 0, oo), (y, 1, 2)) ascii_str = \ """\ 2 oo \n\ ____ ____ \n\ \\ ` \\ ` \n\ \\ \\ -a\n\ \\ \\ --\n\ / / b \n\ / / y \n\ /___, /___, \n\ y = 1 x = 0 \ """ ucode_str = \ """\ 2 ∞ \n\ ____ ____ \n\ ╲ ╲ \n\ ╲ ╲ -a\n\ ╲ ╲ ──\n\ ╱ ╱ b \n\ ╱ ╱ y \n\ ╱ ╱ \n\ ‾‾‾‾ ‾‾‾‾ \n\ y = 1 x = 0 \ """ expr = Sum(1/(1 + 1/( 1 + 1/k)) + 1, (k, 111, 1 + 1/n), (k, 1/(1 + m), oo)) + 1/(1 + 1/k) ascii_str = \ """\ 1 \n\ 1 + - \n\ oo n \n\ _____ _____ \n\ \\ ` \\ ` \n\ \\ \\ / 1 \\ \n\ \\ \\ |1 + ---------| \n\ \\ \\ | 1 | 1 \n\ ) ) | 1 + -----| + -----\n\ / / | 1| 1\n\ / / | 1 + -| 1 + -\n\ / / \\ k/ k\n\ /____, /____, \n\ 1 k = 111 \n\ k = ----- \n\ m + 1 \ """ ucode_str = \ """\ 1 \n\ 1 + ─ \n\ ∞ n \n\ ______ ______ \n\ ╲ ╲ \n\ ╲ ╲ \n\ ╲ ╲ ⎛ 1 ⎞ \n\ ╲ ╲ ⎜1 + ─────────⎟ \n\ ╲ ╲ ⎜ 1 ⎟ 1 \n\ ╱ ╱ ⎜ 1 + ─────⎟ + ─────\n\ ╱ ╱ ⎜ 1⎟ 1\n\ ╱ ╱ ⎜ 1 + ─⎟ 1 + ─\n\ ╱ ╱ ⎝ k⎠ k\n\ ╱ ╱ \n\ ‾‾‾‾‾‾ ‾‾‾‾‾‾ \n\ 1 k = 111 \n\ k = ───── \n\ m + 1 \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_units(): expr = joule ascii_str1 = \ """\ 2\n\ kilogram*meter \n\ ---------------\n\ 2 \n\ second \ """ unicode_str1 = \ """\ 2\n\ kilogram⋅meter \n\ ───────────────\n\ 2 \n\ second \ """ ascii_str2 = \ """\ 2\n\ 3*x*y*kilogram*meter \n\ ---------------------\n\ 2 \n\ second \ """ unicode_str2 = \ """\ 2\n\ 3⋅x⋅y⋅kilogram⋅meter \n\ ─────────────────────\n\ 2 \n\ second \ """ from sympy.physics.units import kg, m, s assert upretty(expr) == "joule" assert pretty(expr) == "joule" assert upretty(expr.convert_to(kg*m**2/s**2)) == unicode_str1 assert pretty(expr.convert_to(kg*m**2/s**2)) == ascii_str1 assert upretty(3*kg*x*m**2*y/s**2) == unicode_str2 assert pretty(3*kg*x*m**2*y/s**2) == ascii_str2 def test_pretty_Subs(): f = Function('f') expr = Subs(f(x), x, ph**2) ascii_str = \ """\ (f(x))| 2\n\ |x=phi \ """ unicode_str = \ """\ (f(x))│ 2\n\ │x=φ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == unicode_str expr = Subs(f(x).diff(x), x, 0) ascii_str = \ """\ /d \\| \n\ |--(f(x))|| \n\ \\dx /|x=0\ """ unicode_str = \ """\ ⎛d ⎞│ \n\ ⎜──(f(x))⎟│ \n\ ⎝dx ⎠│x=0\ """ assert pretty(expr) == ascii_str assert upretty(expr) == unicode_str expr = Subs(f(x).diff(x)/y, (x, y), (0, Rational(1, 2))) ascii_str = \ """\ /d \\| \n\ |--(f(x))|| \n\ |dx || \n\ |--------|| \n\ \\ y /|x=0, y=1/2\ """ unicode_str = \ """\ ⎛d ⎞│ \n\ ⎜──(f(x))⎟│ \n\ ⎜dx ⎟│ \n\ ⎜────────⎟│ \n\ ⎝ y ⎠│x=0, y=1/2\ """ assert pretty(expr) == ascii_str assert upretty(expr) == unicode_str def test_gammas(): assert upretty(lowergamma(x, y)) == "γ(x, y)" assert upretty(uppergamma(x, y)) == "Γ(x, y)" assert xpretty(gamma(x), use_unicode=True) == 'Γ(x)' assert xpretty(gamma, use_unicode=True) == 'Γ' assert xpretty(symbols('gamma', cls=Function)(x), use_unicode=True) == 'γ(x)' assert xpretty(symbols('gamma', cls=Function), use_unicode=True) == 'γ' def test_beta(): assert xpretty(beta(x,y), use_unicode=True) == 'Β(x, y)' assert xpretty(beta(x,y), use_unicode=False) == 'B(x, y)' assert xpretty(beta, use_unicode=True) == 'Β' assert xpretty(beta, use_unicode=False) == 'B' mybeta = Function('beta') assert xpretty(mybeta(x), use_unicode=True) == 'β(x)' assert xpretty(mybeta(x, y, z), use_unicode=False) == 'beta(x, y, z)' assert xpretty(mybeta, use_unicode=True) == 'β' # test that notation passes to subclasses of the same name only def test_function_subclass_different_name(): class mygamma(gamma): pass assert xpretty(mygamma, use_unicode=True) == r"mygamma" assert xpretty(mygamma(x), use_unicode=True) == r"mygamma(x)" def test_SingularityFunction(): assert xpretty(SingularityFunction(x, 0, n), use_unicode=True) == ( """\ n\n\ <x> \ """) assert xpretty(SingularityFunction(x, 1, n), use_unicode=True) == ( """\ n\n\ <x - 1> \ """) assert xpretty(SingularityFunction(x, -1, n), use_unicode=True) == ( """\ n\n\ <x + 1> \ """) assert xpretty(SingularityFunction(x, a, n), use_unicode=True) == ( """\ n\n\ <-a + x> \ """) assert xpretty(SingularityFunction(x, y, n), use_unicode=True) == ( """\ n\n\ <x - y> \ """) assert xpretty(SingularityFunction(x, 0, n), use_unicode=False) == ( """\ n\n\ <x> \ """) assert xpretty(SingularityFunction(x, 1, n), use_unicode=False) == ( """\ n\n\ <x - 1> \ """) assert xpretty(SingularityFunction(x, -1, n), use_unicode=False) == ( """\ n\n\ <x + 1> \ """) assert xpretty(SingularityFunction(x, a, n), use_unicode=False) == ( """\ n\n\ <-a + x> \ """) assert xpretty(SingularityFunction(x, y, n), use_unicode=False) == ( """\ n\n\ <x - y> \ """) def test_deltas(): assert xpretty(DiracDelta(x), use_unicode=True) == 'δ(x)' assert xpretty(DiracDelta(x, 1), use_unicode=True) == \ """\ (1) \n\ δ (x)\ """ assert xpretty(x*DiracDelta(x, 1), use_unicode=True) == \ """\ (1) \n\ x⋅δ (x)\ """ def test_hyper(): expr = hyper((), (), z) ucode_str = \ """\ ┌─ ⎛ │ ⎞\n\ ├─ ⎜ │ z⎟\n\ 0╵ 0 ⎝ │ ⎠\ """ ascii_str = \ """\ _ \n\ |_ / | \\\n\ | | | z|\n\ 0 0 \\ | /\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = hyper((), (1,), x) ucode_str = \ """\ ┌─ ⎛ │ ⎞\n\ ├─ ⎜ │ x⎟\n\ 0╵ 1 ⎝1 │ ⎠\ """ ascii_str = \ """\ _ \n\ |_ / | \\\n\ | | | x|\n\ 0 1 \\1 | /\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = hyper([2], [1], x) ucode_str = \ """\ ┌─ ⎛2 │ ⎞\n\ ├─ ⎜ │ x⎟\n\ 1╵ 1 ⎝1 │ ⎠\ """ ascii_str = \ """\ _ \n\ |_ /2 | \\\n\ | | | x|\n\ 1 1 \\1 | /\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = hyper((pi/3, -2*k), (3, 4, 5, -3), x) ucode_str = \ """\ ⎛ π │ ⎞\n\ ┌─ ⎜ ─, -2⋅k │ ⎟\n\ ├─ ⎜ 3 │ x⎟\n\ 2╵ 4 ⎜ │ ⎟\n\ ⎝3, 4, 5, -3 │ ⎠\ """ ascii_str = \ """\ \n\ _ / pi | \\\n\ |_ | --, -2*k | |\n\ | | 3 | x|\n\ 2 4 | | |\n\ \\3, 4, 5, -3 | /\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = hyper((pi, S('2/3'), -2*k), (3, 4, 5, -3), x**2) ucode_str = \ """\ ┌─ ⎛π, 2/3, -2⋅k │ 2⎞\n\ ├─ ⎜ │ x ⎟\n\ 3╵ 4 ⎝3, 4, 5, -3 │ ⎠\ """ ascii_str = \ """\ _ \n\ |_ /pi, 2/3, -2*k | 2\\\n\ | | | x |\n\ 3 4 \\ 3, 4, 5, -3 | /\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = hyper([1, 2], [3, 4], 1/(1/(1/(1/x + 1) + 1) + 1)) ucode_str = \ """\ ⎛ │ 1 ⎞\n\ ⎜ │ ─────────────⎟\n\ ⎜ │ 1 ⎟\n\ ┌─ ⎜1, 2 │ 1 + ─────────⎟\n\ ├─ ⎜ │ 1 ⎟\n\ 2╵ 2 ⎜3, 4 │ 1 + ─────⎟\n\ ⎜ │ 1⎟\n\ ⎜ │ 1 + ─⎟\n\ ⎝ │ x⎠\ """ ascii_str = \ """\ \n\ / | 1 \\\n\ | | -------------|\n\ _ | | 1 |\n\ |_ |1, 2 | 1 + ---------|\n\ | | | 1 |\n\ 2 2 |3, 4 | 1 + -----|\n\ | | 1|\n\ | | 1 + -|\n\ \\ | x/\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_meijerg(): expr = meijerg([pi, pi, x], [1], [0, 1], [1, 2, 3], z) ucode_str = \ """\ ╭─╮2, 3 ⎛π, π, x 1 │ ⎞\n\ │╶┐ ⎜ │ z⎟\n\ ╰─╯4, 5 ⎝ 0, 1 1, 2, 3 │ ⎠\ """ ascii_str = \ """\ __2, 3 /pi, pi, x 1 | \\\n\ /__ | | z|\n\ \\_|4, 5 \\ 0, 1 1, 2, 3 | /\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = meijerg([1, pi/7], [2, pi, 5], [], [], z**2) ucode_str = \ """\ ⎛ π │ ⎞\n\ ╭─╮0, 2 ⎜1, ─ 2, π, 5 │ 2⎟\n\ │╶┐ ⎜ 7 │ z ⎟\n\ ╰─╯5, 0 ⎜ │ ⎟\n\ ⎝ │ ⎠\ """ ascii_str = \ """\ / pi | \\\n\ __0, 2 |1, -- 2, pi, 5 | 2|\n\ /__ | 7 | z |\n\ \\_|5, 0 | | |\n\ \\ | /\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str ucode_str = \ """\ ╭─╮ 1, 10 ⎛1, 1, 1, 1, 1, 1, 1, 1, 1, 1 1 │ ⎞\n\ │╶┐ ⎜ │ z⎟\n\ ╰─╯11, 2 ⎝ 1 1 │ ⎠\ """ ascii_str = \ """\ __ 1, 10 /1, 1, 1, 1, 1, 1, 1, 1, 1, 1 1 | \\\n\ /__ | | z|\n\ \\_|11, 2 \\ 1 1 | /\ """ expr = meijerg([1]*10, [1], [1], [1], z) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = meijerg([1, 2, ], [4, 3], [3], [4, 5], 1/(1/(1/(1/x + 1) + 1) + 1)) ucode_str = \ """\ ⎛ │ 1 ⎞\n\ ⎜ │ ─────────────⎟\n\ ⎜ │ 1 ⎟\n\ ╭─╮1, 2 ⎜1, 2 4, 3 │ 1 + ─────────⎟\n\ │╶┐ ⎜ │ 1 ⎟\n\ ╰─╯4, 3 ⎜ 3 4, 5 │ 1 + ─────⎟\n\ ⎜ │ 1⎟\n\ ⎜ │ 1 + ─⎟\n\ ⎝ │ x⎠\ """ ascii_str = \ """\ / | 1 \\\n\ | | -------------|\n\ | | 1 |\n\ __1, 2 |1, 2 4, 3 | 1 + ---------|\n\ /__ | | 1 |\n\ \\_|4, 3 | 3 4, 5 | 1 + -----|\n\ | | 1|\n\ | | 1 + -|\n\ \\ | x/\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = Integral(expr, x) ucode_str = \ """\ ⌠ \n\ ⎮ ⎛ │ 1 ⎞ \n\ ⎮ ⎜ │ ─────────────⎟ \n\ ⎮ ⎜ │ 1 ⎟ \n\ ⎮ ╭─╮1, 2 ⎜1, 2 4, 3 │ 1 + ─────────⎟ \n\ ⎮ │╶┐ ⎜ │ 1 ⎟ dx\n\ ⎮ ╰─╯4, 3 ⎜ 3 4, 5 │ 1 + ─────⎟ \n\ ⎮ ⎜ │ 1⎟ \n\ ⎮ ⎜ │ 1 + ─⎟ \n\ ⎮ ⎝ │ x⎠ \n\ ⌡ \ """ ascii_str = \ """\ / \n\ | \n\ | / | 1 \\ \n\ | | | -------------| \n\ | | | 1 | \n\ | __1, 2 |1, 2 4, 3 | 1 + ---------| \n\ | /__ | | 1 | dx\n\ | \\_|4, 3 | 3 4, 5 | 1 + -----| \n\ | | | 1| \n\ | | | 1 + -| \n\ | \\ | x/ \n\ | \n\ / \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_noncommutative(): A, B, C = symbols('A,B,C', commutative=False) expr = A*B*C**-1 ascii_str = \ """\ -1\n\ A*B*C \ """ ucode_str = \ """\ -1\n\ A⋅B⋅C \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = C**-1*A*B ascii_str = \ """\ -1 \n\ C *A*B\ """ ucode_str = \ """\ -1 \n\ C ⋅A⋅B\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = A*C**-1*B ascii_str = \ """\ -1 \n\ A*C *B\ """ ucode_str = \ """\ -1 \n\ A⋅C ⋅B\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = A*C**-1*B/x ascii_str = \ """\ -1 \n\ A*C *B\n\ -------\n\ x \ """ ucode_str = \ """\ -1 \n\ A⋅C ⋅B\n\ ───────\n\ x \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_pretty_special_functions(): x, y = symbols("x y") # atan2 expr = atan2(y/sqrt(200), sqrt(x)) ascii_str = \ """\ / ___ \\\n\ |\\/ 2 *y ___|\n\ atan2|-------, \\/ x |\n\ \\ 20 /\ """ ucode_str = \ """\ ⎛√2⋅y ⎞\n\ atan2⎜────, √x⎟\n\ ⎝ 20 ⎠\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_pretty_geometry(): e = Segment((0, 1), (0, 2)) assert pretty(e) == 'Segment2D(Point2D(0, 1), Point2D(0, 2))' e = Ray((1, 1), angle=4.02*pi) assert pretty(e) == 'Ray2D(Point2D(1, 1), Point2D(2, tan(pi/50) + 1))' def test_expint(): expr = Ei(x) string = 'Ei(x)' assert pretty(expr) == string assert upretty(expr) == string expr = expint(1, z) ucode_str = "E₁(z)" ascii_str = "expint(1, z)" assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str assert pretty(Shi(x)) == 'Shi(x)' assert pretty(Si(x)) == 'Si(x)' assert pretty(Ci(x)) == 'Ci(x)' assert pretty(Chi(x)) == 'Chi(x)' assert upretty(Shi(x)) == 'Shi(x)' assert upretty(Si(x)) == 'Si(x)' assert upretty(Ci(x)) == 'Ci(x)' assert upretty(Chi(x)) == 'Chi(x)' def test_elliptic_functions(): ascii_str = \ """\ / 1 \\\n\ K|-----|\n\ \\z + 1/\ """ ucode_str = \ """\ ⎛ 1 ⎞\n\ K⎜─────⎟\n\ ⎝z + 1⎠\ """ expr = elliptic_k(1/(z + 1)) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str ascii_str = \ """\ / | 1 \\\n\ F|1|-----|\n\ \\ |z + 1/\ """ ucode_str = \ """\ ⎛ │ 1 ⎞\n\ F⎜1│─────⎟\n\ ⎝ │z + 1⎠\ """ expr = elliptic_f(1, 1/(1 + z)) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str ascii_str = \ """\ / 1 \\\n\ E|-----|\n\ \\z + 1/\ """ ucode_str = \ """\ ⎛ 1 ⎞\n\ E⎜─────⎟\n\ ⎝z + 1⎠\ """ expr = elliptic_e(1/(z + 1)) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str ascii_str = \ """\ / | 1 \\\n\ E|1|-----|\n\ \\ |z + 1/\ """ ucode_str = \ """\ ⎛ │ 1 ⎞\n\ E⎜1│─────⎟\n\ ⎝ │z + 1⎠\ """ expr = elliptic_e(1, 1/(1 + z)) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str ascii_str = \ """\ / |4\\\n\ Pi|3|-|\n\ \\ |x/\ """ ucode_str = \ """\ ⎛ │4⎞\n\ Π⎜3│─⎟\n\ ⎝ │x⎠\ """ expr = elliptic_pi(3, 4/x) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str ascii_str = \ """\ / 4| \\\n\ Pi|3; -|6|\n\ \\ x| /\ """ ucode_str = \ """\ ⎛ 4│ ⎞\n\ Π⎜3; ─│6⎟\n\ ⎝ x│ ⎠\ """ expr = elliptic_pi(3, 4/x, 6) assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_RandomDomain(): from sympy.stats import Normal, Die, Exponential, pspace, where X = Normal('x1', 0, 1) assert upretty(where(X > 0)) == "Domain: 0 < x₁ ∧ x₁ < ∞" D = Die('d1', 6) assert upretty(where(D > 4)) == 'Domain: d₁ = 5 ∨ d₁ = 6' A = Exponential('a', 1) B = Exponential('b', 1) assert upretty(pspace(Tuple(A, B)).domain) == \ 'Domain: 0 ≤ a ∧ 0 ≤ b ∧ a < ∞ ∧ b < ∞' def test_PrettyPoly(): F = QQ.frac_field(x, y) R = QQ.poly_ring(x, y) expr = F.convert(x/(x + y)) assert pretty(expr) == "x/(x + y)" assert upretty(expr) == "x/(x + y)" expr = R.convert(x + y) assert pretty(expr) == "x + y" assert upretty(expr) == "x + y" def test_issue_6285(): assert pretty(Pow(2, -5, evaluate=False)) == '1 \n--\n 5\n2 ' assert pretty(Pow(x, (1/pi))) == \ ' 1 \n'\ ' --\n'\ ' pi\n'\ 'x ' def test_issue_6359(): assert pretty(Integral(x**2, x)**2) == \ """\ 2 / / \\ \n\ | | | \n\ | | 2 | \n\ | | x dx| \n\ | | | \n\ \\/ / \ """ assert upretty(Integral(x**2, x)**2) == \ """\ 2 ⎛⌠ ⎞ \n\ ⎜⎮ 2 ⎟ \n\ ⎜⎮ x dx⎟ \n\ ⎝⌡ ⎠ \ """ assert pretty(Sum(x**2, (x, 0, 1))**2) == \ """\ 2 / 1 \\ \n\ | ___ | \n\ | \\ ` | \n\ | \\ 2| \n\ | / x | \n\ | /__, | \n\ \\x = 0 / \ """ assert upretty(Sum(x**2, (x, 0, 1))**2) == \ """\ 2 ⎛ 1 ⎞ \n\ ⎜ ___ ⎟ \n\ ⎜ ╲ ⎟ \n\ ⎜ ╲ 2⎟ \n\ ⎜ ╱ x ⎟ \n\ ⎜ ╱ ⎟ \n\ ⎜ ‾‾‾ ⎟ \n\ ⎝x = 0 ⎠ \ """ assert pretty(Product(x**2, (x, 1, 2))**2) == \ """\ 2 / 2 \\ \n\ |______ | \n\ | | | 2| \n\ | | | x | \n\ | | | | \n\ \\x = 1 / \ """ assert upretty(Product(x**2, (x, 1, 2))**2) == \ """\ 2 ⎛ 2 ⎞ \n\ ⎜─┬──┬─ ⎟ \n\ ⎜ │ │ 2⎟ \n\ ⎜ │ │ x ⎟ \n\ ⎜ │ │ ⎟ \n\ ⎝x = 1 ⎠ \ """ f = Function('f') assert pretty(Derivative(f(x), x)**2) == \ """\ 2 /d \\ \n\ |--(f(x))| \n\ \\dx / \ """ assert upretty(Derivative(f(x), x)**2) == \ """\ 2 ⎛d ⎞ \n\ ⎜──(f(x))⎟ \n\ ⎝dx ⎠ \ """ def test_issue_6739(): ascii_str = \ """\ 1 \n\ -----\n\ ___\n\ \\/ x \ """ ucode_str = \ """\ 1 \n\ ──\n\ √x\ """ assert pretty(1/sqrt(x)) == ascii_str assert upretty(1/sqrt(x)) == ucode_str def test_complicated_symbol_unchanged(): for symb_name in ["dexpr2_d1tau", "dexpr2^d1tau"]: assert pretty(Symbol(symb_name)) == symb_name def test_categories(): from sympy.categories import (Object, IdentityMorphism, NamedMorphism, Category, Diagram, DiagramGrid) A1 = Object("A1") A2 = Object("A2") A3 = Object("A3") f1 = NamedMorphism(A1, A2, "f1") f2 = NamedMorphism(A2, A3, "f2") id_A1 = IdentityMorphism(A1) K1 = Category("K1") assert pretty(A1) == "A1" assert upretty(A1) == "A₁" assert pretty(f1) == "f1:A1-->A2" assert upretty(f1) == "f₁:A₁——▶A₂" assert pretty(id_A1) == "id:A1-->A1" assert upretty(id_A1) == "id:A₁——▶A₁" assert pretty(f2*f1) == "f2*f1:A1-->A3" assert upretty(f2*f1) == "f₂∘f₁:A₁——▶A₃" assert pretty(K1) == "K1" assert upretty(K1) == "K₁" # Test how diagrams are printed. d = Diagram() assert pretty(d) == "EmptySet" assert upretty(d) == "∅" d = Diagram({f1: "unique", f2: S.EmptySet}) assert pretty(d) == "{f2*f1:A1-->A3: EmptySet, id:A1-->A1: " \ "EmptySet, id:A2-->A2: EmptySet, id:A3-->A3: " \ "EmptySet, f1:A1-->A2: {unique}, f2:A2-->A3: EmptySet}" assert upretty(d) == "{f₂∘f₁:A₁——▶A₃: ∅, id:A₁——▶A₁: ∅, " \ "id:A₂——▶A₂: ∅, id:A₃——▶A₃: ∅, f₁:A₁——▶A₂: {unique}, f₂:A₂——▶A₃: ∅}" d = Diagram({f1: "unique", f2: S.EmptySet}, {f2 * f1: "unique"}) assert pretty(d) == "{f2*f1:A1-->A3: EmptySet, id:A1-->A1: " \ "EmptySet, id:A2-->A2: EmptySet, id:A3-->A3: " \ "EmptySet, f1:A1-->A2: {unique}, f2:A2-->A3: EmptySet}" \ " ==> {f2*f1:A1-->A3: {unique}}" assert upretty(d) == "{f₂∘f₁:A₁——▶A₃: ∅, id:A₁——▶A₁: ∅, id:A₂——▶A₂: " \ "∅, id:A₃——▶A₃: ∅, f₁:A₁——▶A₂: {unique}, f₂:A₂——▶A₃: ∅}" \ " ══▶ {f₂∘f₁:A₁——▶A₃: {unique}}" grid = DiagramGrid(d) assert pretty(grid) == "A1 A2\n \nA3 " assert upretty(grid) == "A₁ A₂\n \nA₃ " def test_PrettyModules(): R = QQ.old_poly_ring(x, y) F = R.free_module(2) M = F.submodule([x, y], [1, x**2]) ucode_str = \ """\ 2\n\ ℚ[x, y] \ """ ascii_str = \ """\ 2\n\ QQ[x, y] \ """ assert upretty(F) == ucode_str assert pretty(F) == ascii_str ucode_str = \ """\ ╱ ⎡ 2⎤╲\n\ ╲[x, y], ⎣1, x ⎦╱\ """ ascii_str = \ """\ 2 \n\ <[x, y], [1, x ]>\ """ assert upretty(M) == ucode_str assert pretty(M) == ascii_str I = R.ideal(x**2, y) ucode_str = \ """\ ╱ 2 ╲\n\ ╲x , y╱\ """ ascii_str = \ """\ 2 \n\ <x , y>\ """ assert upretty(I) == ucode_str assert pretty(I) == ascii_str Q = F / M ucode_str = \ """\ 2 \n\ ℚ[x, y] \n\ ─────────────────\n\ ╱ ⎡ 2⎤╲\n\ ╲[x, y], ⎣1, x ⎦╱\ """ ascii_str = \ """\ 2 \n\ QQ[x, y] \n\ -----------------\n\ 2 \n\ <[x, y], [1, x ]>\ """ assert upretty(Q) == ucode_str assert pretty(Q) == ascii_str ucode_str = \ """\ ╱⎡ 3⎤ ╲\n\ │⎢ x ⎥ ╱ ⎡ 2⎤╲ ╱ ⎡ 2⎤╲│\n\ │⎢1, ──⎥ + ╲[x, y], ⎣1, x ⎦╱, [2, y] + ╲[x, y], ⎣1, x ⎦╱│\n\ ╲⎣ 2 ⎦ ╱\ """ ascii_str = \ """\ 3 \n\ x 2 2 \n\ <[1, --] + <[x, y], [1, x ]>, [2, y] + <[x, y], [1, x ]>>\n\ 2 \ """ def test_QuotientRing(): R = QQ.old_poly_ring(x)/[x**2 + 1] ucode_str = \ """\ ℚ[x] \n\ ────────\n\ ╱ 2 ╲\n\ ╲x + 1╱\ """ ascii_str = \ """\ QQ[x] \n\ --------\n\ 2 \n\ <x + 1>\ """ assert upretty(R) == ucode_str assert pretty(R) == ascii_str ucode_str = \ """\ ╱ 2 ╲\n\ 1 + ╲x + 1╱\ """ ascii_str = \ """\ 2 \n\ 1 + <x + 1>\ """ assert upretty(R.one) == ucode_str assert pretty(R.one) == ascii_str def test_Homomorphism(): from sympy.polys.agca import homomorphism R = QQ.old_poly_ring(x) expr = homomorphism(R.free_module(1), R.free_module(1), [0]) ucode_str = \ """\ 1 1\n\ [0] : ℚ[x] ──> ℚ[x] \ """ ascii_str = \ """\ 1 1\n\ [0] : QQ[x] --> QQ[x] \ """ assert upretty(expr) == ucode_str assert pretty(expr) == ascii_str expr = homomorphism(R.free_module(2), R.free_module(2), [0, 0]) ucode_str = \ """\ ⎡0 0⎤ 2 2\n\ ⎢ ⎥ : ℚ[x] ──> ℚ[x] \n\ ⎣0 0⎦ \ """ ascii_str = \ """\ [0 0] 2 2\n\ [ ] : QQ[x] --> QQ[x] \n\ [0 0] \ """ assert upretty(expr) == ucode_str assert pretty(expr) == ascii_str expr = homomorphism(R.free_module(1), R.free_module(1) / [[x]], [0]) ucode_str = \ """\ 1\n\ 1 ℚ[x] \n\ [0] : ℚ[x] ──> ─────\n\ <[x]>\ """ ascii_str = \ """\ 1\n\ 1 QQ[x] \n\ [0] : QQ[x] --> ------\n\ <[x]> \ """ assert upretty(expr) == ucode_str assert pretty(expr) == ascii_str def test_Tr(): A, B = symbols('A B', commutative=False) t = Tr(A*B) assert pretty(t) == r'Tr(A*B)' assert upretty(t) == 'Tr(A⋅B)' def test_pretty_Add(): eq = Mul(-2, x - 2, evaluate=False) + 5 assert pretty(eq) == '5 - 2*(x - 2)' def test_issue_7179(): assert upretty(Not(Equivalent(x, y))) == 'x ⇎ y' assert upretty(Not(Implies(x, y))) == 'x ↛ y' def test_issue_7180(): assert upretty(Equivalent(x, y)) == 'x ⇔ y' def test_pretty_Complement(): assert pretty(S.Reals - S.Naturals) == '(-oo, oo) \\ Naturals' assert upretty(S.Reals - S.Naturals) == 'ℝ \\ ℕ' assert pretty(S.Reals - S.Naturals0) == '(-oo, oo) \\ Naturals0' assert upretty(S.Reals - S.Naturals0) == 'ℝ \\ ℕ₀' def test_pretty_SymmetricDifference(): from sympy.sets.sets import SymmetricDifference assert upretty(SymmetricDifference(Interval(2,3), Interval(3,5), \ evaluate = False)) == '[2, 3] ∆ [3, 5]' with raises(NotImplementedError): pretty(SymmetricDifference(Interval(2,3), Interval(3,5), evaluate = False)) def test_pretty_Contains(): assert pretty(Contains(x, S.Integers)) == 'Contains(x, Integers)' assert upretty(Contains(x, S.Integers)) == 'x ∈ ℤ' def test_issue_8292(): from sympy.core import sympify e = sympify('((x+x**4)/(x-1))-(2*(x-1)**4/(x-1)**4)', evaluate=False) ucode_str = \ """\ 4 4 \n\ 2⋅(x - 1) x + x\n\ - ────────── + ──────\n\ 4 x - 1 \n\ (x - 1) \ """ ascii_str = \ """\ 4 4 \n\ 2*(x - 1) x + x\n\ - ---------- + ------\n\ 4 x - 1 \n\ (x - 1) \ """ assert pretty(e) == ascii_str assert upretty(e) == ucode_str def test_issue_4335(): y = Function('y') expr = -y(x).diff(x) ucode_str = \ """\ d \n\ -──(y(x))\n\ dx \ """ ascii_str = \ """\ d \n\ - --(y(x))\n\ dx \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_issue_8344(): from sympy.core import sympify e = sympify('2*x*y**2/1**2 + 1', evaluate=False) ucode_str = \ """\ 2 \n\ 2⋅x⋅y \n\ ────── + 1\n\ 2 \n\ 1 \ """ assert upretty(e) == ucode_str def test_issue_6324(): x = Pow(2, 3, evaluate=False) y = Pow(10, -2, evaluate=False) e = Mul(x, y, evaluate=False) ucode_str = \ """\ 3\n\ 2 \n\ ───\n\ 2\n\ 10 \ """ assert upretty(e) == ucode_str def test_issue_7927(): e = sin(x/2)**cos(x/2) ucode_str = \ """\ ⎛x⎞\n\ cos⎜─⎟\n\ ⎝2⎠\n\ ⎛ ⎛x⎞⎞ \n\ ⎜sin⎜─⎟⎟ \n\ ⎝ ⎝2⎠⎠ \ """ assert upretty(e) == ucode_str e = sin(x)**(S(11)/13) ucode_str = \ """\ 11\n\ ──\n\ 13\n\ (sin(x)) \ """ assert upretty(e) == ucode_str def test_issue_6134(): from sympy.abc import lamda, t phi = Function('phi') e = lamda*x*Integral(phi(t)*pi*sin(pi*t), (t, 0, 1)) + lamda*x**2*Integral(phi(t)*2*pi*sin(2*pi*t), (t, 0, 1)) ucode_str = \ """\ 1 1 \n\ 2 ⌠ ⌠ \n\ λ⋅x ⋅⎮ 2⋅π⋅φ(t)⋅sin(2⋅π⋅t) dt + λ⋅x⋅⎮ π⋅φ(t)⋅sin(π⋅t) dt\n\ ⌡ ⌡ \n\ 0 0 \ """ assert upretty(e) == ucode_str def test_issue_9877(): ucode_str1 = '(2, 3) ∪ ([1, 2] \\ {x})' a, b, c = Interval(2, 3, True, True), Interval(1, 2), FiniteSet(x) assert upretty(Union(a, Complement(b, c))) == ucode_str1 ucode_str2 = '{x} ∩ {y} ∩ ({z} \\ [1, 2])' d, e, f, g = FiniteSet(x), FiniteSet(y), FiniteSet(z), Interval(1, 2) assert upretty(Intersection(d, e, Complement(f, g))) == ucode_str2 def test_issue_13651(): expr1 = c + Mul(-1, a + b, evaluate=False) assert pretty(expr1) == 'c - (a + b)' expr2 = c + Mul(-1, a - b + d, evaluate=False) assert pretty(expr2) == 'c - (a - b + d)' def test_pretty_primenu(): from sympy.ntheory.factor_ import primenu ascii_str1 = "nu(n)" ucode_str1 = "ν(n)" n = symbols('n', integer=True) assert pretty(primenu(n)) == ascii_str1 assert upretty(primenu(n)) == ucode_str1 def test_pretty_primeomega(): from sympy.ntheory.factor_ import primeomega ascii_str1 = "Omega(n)" ucode_str1 = "Ω(n)" n = symbols('n', integer=True) assert pretty(primeomega(n)) == ascii_str1 assert upretty(primeomega(n)) == ucode_str1 def test_pretty_Mod(): from sympy.core import Mod ascii_str1 = "x mod 7" ucode_str1 = "x mod 7" ascii_str2 = "(x + 1) mod 7" ucode_str2 = "(x + 1) mod 7" ascii_str3 = "2*x mod 7" ucode_str3 = "2⋅x mod 7" ascii_str4 = "(x mod 7) + 1" ucode_str4 = "(x mod 7) + 1" ascii_str5 = "2*(x mod 7)" ucode_str5 = "2⋅(x mod 7)" x = symbols('x', integer=True) assert pretty(Mod(x, 7)) == ascii_str1 assert upretty(Mod(x, 7)) == ucode_str1 assert pretty(Mod(x + 1, 7)) == ascii_str2 assert upretty(Mod(x + 1, 7)) == ucode_str2 assert pretty(Mod(2 * x, 7)) == ascii_str3 assert upretty(Mod(2 * x, 7)) == ucode_str3 assert pretty(Mod(x, 7) + 1) == ascii_str4 assert upretty(Mod(x, 7) + 1) == ucode_str4 assert pretty(2 * Mod(x, 7)) == ascii_str5 assert upretty(2 * Mod(x, 7)) == ucode_str5 def test_issue_11801(): assert pretty(Symbol("")) == "" assert upretty(Symbol("")) == "" def test_pretty_UnevaluatedExpr(): x = symbols('x') he = UnevaluatedExpr(1/x) ucode_str = \ """\ 1\n\ ─\n\ x\ """ assert upretty(he) == ucode_str ucode_str = \ """\ 2\n\ ⎛1⎞ \n\ ⎜─⎟ \n\ ⎝x⎠ \ """ assert upretty(he**2) == ucode_str ucode_str = \ """\ 1\n\ 1 + ─\n\ x\ """ assert upretty(he + 1) == ucode_str ucode_str = \ ('''\ 1\n\ x⋅─\n\ x\ ''') assert upretty(x*he) == ucode_str def test_issue_10472(): M = (Matrix([[0, 0], [0, 0]]), Matrix([0, 0])) ucode_str = \ """\ ⎛⎡0 0⎤ ⎡0⎤⎞ ⎜⎢ ⎥, ⎢ ⎥⎟ ⎝⎣0 0⎦ ⎣0⎦⎠\ """ assert upretty(M) == ucode_str def test_MatrixElement_printing(): # test cases for issue #11821 A = MatrixSymbol("A", 1, 3) B = MatrixSymbol("B", 1, 3) C = MatrixSymbol("C", 1, 3) ascii_str1 = "A_00" ucode_str1 = "A₀₀" assert pretty(A[0, 0]) == ascii_str1 assert upretty(A[0, 0]) == ucode_str1 ascii_str1 = "3*A_00" ucode_str1 = "3⋅A₀₀" assert pretty(3*A[0, 0]) == ascii_str1 assert upretty(3*A[0, 0]) == ucode_str1 ascii_str1 = "(-B + A)[0, 0]" ucode_str1 = "(-B + A)[0, 0]" F = C[0, 0].subs(C, A - B) assert pretty(F) == ascii_str1 assert upretty(F) == ucode_str1 def test_issue_12675(): x, y, t, j = symbols('x y t j') e = CoordSys3D('e') ucode_str = \ """\ ⎛ t⎞ \n\ ⎜⎛x⎞ ⎟ j_e\n\ ⎜⎜─⎟ ⎟ \n\ ⎝⎝y⎠ ⎠ \ """ assert upretty((x/y)**t*e.j) == ucode_str ucode_str = \ """\ ⎛1⎞ \n\ ⎜─⎟ j_e\n\ ⎝y⎠ \ """ assert upretty((1/y)*e.j) == ucode_str def test_MatrixSymbol_printing(): # test cases for issue #14237 A = MatrixSymbol("A", 3, 3) B = MatrixSymbol("B", 3, 3) C = MatrixSymbol("C", 3, 3) assert pretty(-A*B*C) == "-A*B*C" assert pretty(A - B) == "-B + A" assert pretty(A*B*C - A*B - B*C) == "-A*B -B*C + A*B*C" # issue #14814 x = MatrixSymbol('x', n, n) y = MatrixSymbol('y*', n, n) assert pretty(x + y) == "x + y*" ascii_str = \ """\ 2 \n\ -2*y* -a*x\ """ assert pretty(-a*x + -2*y*y) == ascii_str def test_degree_printing(): expr1 = 90*degree assert pretty(expr1) == '90°' expr2 = x*degree assert pretty(expr2) == 'x°' expr3 = cos(x*degree + 90*degree) assert pretty(expr3) == 'cos(x° + 90°)' def test_vector_expr_pretty_printing(): A = CoordSys3D('A') assert upretty(Cross(A.i, A.x*A.i+3*A.y*A.j)) == "(i_A)×((x_A) i_A + (3⋅y_A) j_A)" assert upretty(x*Cross(A.i, A.j)) == 'x⋅(i_A)×(j_A)' assert upretty(Curl(A.x*A.i + 3*A.y*A.j)) == "∇×((x_A) i_A + (3⋅y_A) j_A)" assert upretty(Divergence(A.x*A.i + 3*A.y*A.j)) == "∇⋅((x_A) i_A + (3⋅y_A) j_A)" assert upretty(Dot(A.i, A.x*A.i+3*A.y*A.j)) == "(i_A)⋅((x_A) i_A + (3⋅y_A) j_A)" assert upretty(Gradient(A.x+3*A.y)) == "∇(x_A + 3⋅y_A)" assert upretty(Laplacian(A.x+3*A.y)) == "∆(x_A + 3⋅y_A)" # TODO: add support for ASCII pretty. def test_pretty_print_tensor_expr(): L = TensorIndexType("L") i, j, k = tensor_indices("i j k", L) i0 = tensor_indices("i_0", L) A, B, C, D = tensor_heads("A B C D", [L]) H = TensorHead("H", [L, L]) expr = -i ascii_str = \ """\ -i\ """ ucode_str = \ """\ -i\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = A(i) ascii_str = \ """\ i\n\ A \n\ \ """ ucode_str = \ """\ i\n\ A \n\ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = A(i0) ascii_str = \ """\ i_0\n\ A \n\ \ """ ucode_str = \ """\ i₀\n\ A \n\ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = A(-i) ascii_str = \ """\ \n\ A \n\ i\ """ ucode_str = \ """\ \n\ A \n\ i\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = -3*A(-i) ascii_str = \ """\ \n\ -3*A \n\ i\ """ ucode_str = \ """\ \n\ -3⋅A \n\ i\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = H(i, -j) ascii_str = \ """\ i \n\ H \n\ j\ """ ucode_str = \ """\ i \n\ H \n\ j\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = H(i, -i) ascii_str = \ """\ L_0 \n\ H \n\ L_0\ """ ucode_str = \ """\ L₀ \n\ H \n\ L₀\ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = H(i, -j)*A(j)*B(k) ascii_str = \ """\ i L_0 k\n\ H *A *B \n\ L_0 \ """ ucode_str = \ """\ i L₀ k\n\ H ⋅A ⋅B \n\ L₀ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = (1+x)*A(i) ascii_str = \ """\ i\n\ (x + 1)*A \n\ \ """ ucode_str = \ """\ i\n\ (x + 1)⋅A \n\ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = A(i) + 3*B(i) ascii_str = \ """\ i i\n\ 3*B + A \n\ \ """ ucode_str = \ """\ i i\n\ 3⋅B + A \n\ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_pretty_print_tensor_partial_deriv(): from sympy.tensor.toperators import PartialDerivative L = TensorIndexType("L") i, j, k = tensor_indices("i j k", L) A, B, C, D = tensor_heads("A B C D", [L]) H = TensorHead("H", [L, L]) expr = PartialDerivative(A(i), A(j)) ascii_str = \ """\ d / i\\\n\ ---|A |\n\ j\\ /\n\ dA \n\ \ """ ucode_str = \ """\ ∂ ⎛ i⎞\n\ ───⎜A ⎟\n\ j⎝ ⎠\n\ ∂A \n\ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = A(i)*PartialDerivative(H(k, -i), A(j)) ascii_str = \ """\ L_0 d / k \\\n\ A *---|H |\n\ j\\ L_0/\n\ dA \n\ \ """ ucode_str = \ """\ L₀ ∂ ⎛ k ⎞\n\ A ⋅───⎜H ⎟\n\ j⎝ L₀⎠\n\ ∂A \n\ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = A(i)*PartialDerivative(B(k)*C(-i) + 3*H(k, -i), A(j)) ascii_str = \ """\ L_0 d / k k \\\n\ A *---|3*H + B *C |\n\ j\\ L_0 L_0/\n\ dA \n\ \ """ ucode_str = \ """\ L₀ ∂ ⎛ k k ⎞\n\ A ⋅───⎜3⋅H + B ⋅C ⎟\n\ j⎝ L₀ L₀⎠\n\ ∂A \n\ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = (A(i) + B(i))*PartialDerivative(C(j), D(j)) ascii_str = \ """\ / i i\\ d / L_0\\\n\ |A + B |*-----|C |\n\ \\ / L_0\\ /\n\ dD \n\ \ """ ucode_str = \ """\ ⎛ i i⎞ ∂ ⎛ L₀⎞\n\ ⎜A + B ⎟⋅────⎜C ⎟\n\ ⎝ ⎠ L₀⎝ ⎠\n\ ∂D \n\ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = (A(i) + B(i))*PartialDerivative(C(-i), D(j)) ascii_str = \ """\ / L_0 L_0\\ d / \\\n\ |A + B |*---|C |\n\ \\ / j\\ L_0/\n\ dD \n\ \ """ ucode_str = \ """\ ⎛ L₀ L₀⎞ ∂ ⎛ ⎞\n\ ⎜A + B ⎟⋅───⎜C ⎟\n\ ⎝ ⎠ j⎝ L₀⎠\n\ ∂D \n\ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = PartialDerivative(B(-i) + A(-i), A(-j), A(-n)) ucode_str = """\ 2 \n\ ∂ ⎛ ⎞\n\ ───────⎜A + B ⎟\n\ ⎝ i i⎠\n\ ∂A ∂A \n\ n j \ """ assert upretty(expr) == ucode_str expr = PartialDerivative(3*A(-i), A(-j), A(-n)) ucode_str = """\ 2 \n\ ∂ ⎛ ⎞\n\ ───────⎜3⋅A ⎟\n\ ⎝ i⎠\n\ ∂A ∂A \n\ n j \ """ assert upretty(expr) == ucode_str expr = TensorElement(H(i, j), {i:1}) ascii_str = \ """\ i=1,j\n\ H \n\ \ """ ucode_str = ascii_str assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = TensorElement(H(i, j), {i: 1, j: 1}) ascii_str = \ """\ i=1,j=1\n\ H \n\ \ """ ucode_str = ascii_str assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = TensorElement(H(i, j), {j: 1}) ascii_str = \ """\ i,j=1\n\ H \n\ \ """ ucode_str = ascii_str expr = TensorElement(H(-i, j), {-i: 1}) ascii_str = \ """\ j\n\ H \n\ i=1 \ """ ucode_str = ascii_str assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_issue_15560(): a = MatrixSymbol('a', 1, 1) e = pretty(a*(KroneckerProduct(a, a))) result = 'a*(a x a)' assert e == result def test_print_lerchphi(): # Part of issue 6013 a = Symbol('a') pretty(lerchphi(a, 1, 2)) uresult = 'Φ(a, 1, 2)' aresult = 'lerchphi(a, 1, 2)' assert pretty(lerchphi(a, 1, 2)) == aresult assert upretty(lerchphi(a, 1, 2)) == uresult def test_issue_15583(): N = mechanics.ReferenceFrame('N') result = '(n_x, n_y, n_z)' e = pretty((N.x, N.y, N.z)) assert e == result def test_matrixSymbolBold(): # Issue 15871 def boldpretty(expr): return xpretty(expr, use_unicode=True, wrap_line=False, mat_symbol_style="bold") from sympy.matrices.expressions.trace import trace A = MatrixSymbol("A", 2, 2) assert boldpretty(trace(A)) == 'tr(𝐀)' A = MatrixSymbol("A", 3, 3) B = MatrixSymbol("B", 3, 3) C = MatrixSymbol("C", 3, 3) assert boldpretty(-A) == '-𝐀' assert boldpretty(A - A*B - B) == '-𝐁 -𝐀⋅𝐁 + 𝐀' assert boldpretty(-A*B - A*B*C - B) == '-𝐁 -𝐀⋅𝐁 -𝐀⋅𝐁⋅𝐂' A = MatrixSymbol("Addot", 3, 3) assert boldpretty(A) == '𝐀̈' omega = MatrixSymbol("omega", 3, 3) assert boldpretty(omega) == 'ω' omega = MatrixSymbol("omeganorm", 3, 3) assert boldpretty(omega) == '‖ω‖' a = Symbol('alpha') b = Symbol('b') c = MatrixSymbol("c", 3, 1) d = MatrixSymbol("d", 3, 1) assert boldpretty(a*B*c+b*d) == 'b⋅𝐝 + α⋅𝐁⋅𝐜' d = MatrixSymbol("delta", 3, 1) B = MatrixSymbol("Beta", 3, 3) assert boldpretty(a*B*c+b*d) == 'b⋅δ + α⋅Β⋅𝐜' A = MatrixSymbol("A_2", 3, 3) assert boldpretty(A) == '𝐀₂' def test_center_accent(): assert center_accent('a', '\N{COMBINING TILDE}') == 'ã' assert center_accent('aa', '\N{COMBINING TILDE}') == 'aã' assert center_accent('aaa', '\N{COMBINING TILDE}') == 'aãa' assert center_accent('aaaa', '\N{COMBINING TILDE}') == 'aaãa' assert center_accent('aaaaa', '\N{COMBINING TILDE}') == 'aaãaa' assert center_accent('abcdefg', '\N{COMBINING FOUR DOTS ABOVE}') == 'abcd⃜efg' def test_imaginary_unit(): from sympy.printing.pretty import pretty # b/c it was redefined above assert pretty(1 + I, use_unicode=False) == '1 + I' assert pretty(1 + I, use_unicode=True) == '1 + ⅈ' assert pretty(1 + I, use_unicode=False, imaginary_unit='j') == '1 + I' assert pretty(1 + I, use_unicode=True, imaginary_unit='j') == '1 + ⅉ' raises(TypeError, lambda: pretty(I, imaginary_unit=I)) raises(ValueError, lambda: pretty(I, imaginary_unit="kkk")) def test_str_special_matrices(): from sympy.matrices import Identity, ZeroMatrix, OneMatrix assert pretty(Identity(4)) == 'I' assert upretty(Identity(4)) == '𝕀' assert pretty(ZeroMatrix(2, 2)) == '0' assert upretty(ZeroMatrix(2, 2)) == '𝟘' assert pretty(OneMatrix(2, 2)) == '1' assert upretty(OneMatrix(2, 2)) == '𝟙' def test_pretty_misc_functions(): assert pretty(LambertW(x)) == 'W(x)' assert upretty(LambertW(x)) == 'W(x)' assert pretty(LambertW(x, y)) == 'W(x, y)' assert upretty(LambertW(x, y)) == 'W(x, y)' assert pretty(airyai(x)) == 'Ai(x)' assert upretty(airyai(x)) == 'Ai(x)' assert pretty(airybi(x)) == 'Bi(x)' assert upretty(airybi(x)) == 'Bi(x)' assert pretty(airyaiprime(x)) == "Ai'(x)" assert upretty(airyaiprime(x)) == "Ai'(x)" assert pretty(airybiprime(x)) == "Bi'(x)" assert upretty(airybiprime(x)) == "Bi'(x)" assert pretty(fresnelc(x)) == 'C(x)' assert upretty(fresnelc(x)) == 'C(x)' assert pretty(fresnels(x)) == 'S(x)' assert upretty(fresnels(x)) == 'S(x)' assert pretty(Heaviside(x)) == 'Heaviside(x)' assert upretty(Heaviside(x)) == 'θ(x)' assert pretty(Heaviside(x, y)) == 'Heaviside(x, y)' assert upretty(Heaviside(x, y)) == 'θ(x, y)' assert pretty(dirichlet_eta(x)) == 'dirichlet_eta(x)' assert upretty(dirichlet_eta(x)) == 'η(x)' def test_hadamard_power(): m, n, p = symbols('m, n, p', integer=True) A = MatrixSymbol('A', m, n) B = MatrixSymbol('B', m, n) # Testing printer: expr = hadamard_power(A, n) ascii_str = \ """\ .n\n\ A \ """ ucode_str = \ """\ ∘n\n\ A \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = hadamard_power(A, 1+n) ascii_str = \ """\ .(n + 1)\n\ A \ """ ucode_str = \ """\ ∘(n + 1)\n\ A \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str expr = hadamard_power(A*B.T, 1+n) ascii_str = \ """\ .(n + 1)\n\ / T\\ \n\ \\A*B / \ """ ucode_str = \ """\ ∘(n + 1)\n\ ⎛ T⎞ \n\ ⎝A⋅B ⎠ \ """ assert pretty(expr) == ascii_str assert upretty(expr) == ucode_str def test_issue_17258(): n = Symbol('n', integer=True) assert pretty(Sum(n, (n, -oo, 1))) == \ ' 1 \n'\ ' __ \n'\ ' \\ ` \n'\ ' ) n\n'\ ' /_, \n'\ 'n = -oo ' assert upretty(Sum(n, (n, -oo, 1))) == \ """\ 1 \n\ ___ \n\ ╲ \n\ ╲ \n\ ╱ n\n\ ╱ \n\ ‾‾‾ \n\ n = -∞ \ """ def test_is_combining(): line = "v̇_m" assert [is_combining(sym) for sym in line] == \ [False, True, False, False] def test_issue_17616(): assert pretty(pi**(1/exp(1))) == \ ' / -1\\\n'\ ' \\e /\n'\ 'pi ' assert upretty(pi**(1/exp(1))) == \ ' ⎛ -1⎞\n'\ ' ⎝ℯ ⎠\n'\ 'π ' assert pretty(pi**(1/pi)) == \ ' 1 \n'\ ' --\n'\ ' pi\n'\ 'pi ' assert upretty(pi**(1/pi)) == \ ' 1\n'\ ' ─\n'\ ' π\n'\ 'π ' assert pretty(pi**(1/EulerGamma)) == \ ' 1 \n'\ ' ----------\n'\ ' EulerGamma\n'\ 'pi ' assert upretty(pi**(1/EulerGamma)) == \ ' 1\n'\ ' ─\n'\ ' γ\n'\ 'π ' z = Symbol("x_17") assert upretty(7**(1/z)) == \ 'x₁₇___\n'\ ' ╲╱ 7 ' assert pretty(7**(1/z)) == \ 'x_17___\n'\ ' \\/ 7 ' def test_issue_17857(): assert pretty(Range(-oo, oo)) == '{..., -1, 0, 1, ...}' assert pretty(Range(oo, -oo, -1)) == '{..., 1, 0, -1, ...}' def test_issue_18272(): x = Symbol('x') n = Symbol('n') assert upretty(ConditionSet(x, Eq(-x + exp(x), 0), S.Complexes)) == \ '⎧ │ ⎛ x ⎞⎫\n'\ '⎨x │ x ∊ ℂ ∧ ⎝-x + ℯ = 0⎠⎬\n'\ '⎩ │ ⎭' assert upretty(ConditionSet(x, Contains(n/2, Interval(0, oo)), FiniteSet(-n/2, n/2))) == \ '⎧ │ ⎧-n n⎫ ⎛n ⎞⎫\n'\ '⎨x │ x ∊ ⎨───, ─⎬ ∧ ⎜─ ∈ [0, ∞)⎟⎬\n'\ '⎩ │ ⎩ 2 2⎭ ⎝2 ⎠⎭' assert upretty(ConditionSet(x, Eq(Piecewise((1, x >= 3), (x/2 - 1/2, x >= 2), (1/2, x >= 1), (x/2, True)) - 1/2, 0), Interval(0, 3))) == \ '⎧ │ ⎛⎛⎧ 1 for x ≥ 3⎞ ⎞⎫\n'\ '⎪ │ ⎜⎜⎪ ⎟ ⎟⎪\n'\ '⎪ │ ⎜⎜⎪x ⎟ ⎟⎪\n'\ '⎪ │ ⎜⎜⎪─ - 0.5 for x ≥ 2⎟ ⎟⎪\n'\ '⎪ │ ⎜⎜⎪2 ⎟ ⎟⎪\n'\ '⎨x │ x ∊ [0, 3] ∧ ⎜⎜⎨ ⎟ - 0.5 = 0⎟⎬\n'\ '⎪ │ ⎜⎜⎪ 0.5 for x ≥ 1⎟ ⎟⎪\n'\ '⎪ │ ⎜⎜⎪ ⎟ ⎟⎪\n'\ '⎪ │ ⎜⎜⎪ x ⎟ ⎟⎪\n'\ '⎪ │ ⎜⎜⎪ ─ otherwise⎟ ⎟⎪\n'\ '⎩ │ ⎝⎝⎩ 2 ⎠ ⎠⎭' def test_Str(): from sympy.core.symbol import Str assert pretty(Str('x')) == 'x' def test_symbolic_probability(): mu = symbols("mu") sigma = symbols("sigma", positive=True) X = Normal("X", mu, sigma) assert pretty(Expectation(X)) == r'E[X]' assert pretty(Variance(X)) == r'Var(X)' assert pretty(Probability(X > 0)) == r'P(X > 0)' Y = Normal("Y", mu, sigma) assert pretty(Covariance(X, Y)) == 'Cov(X, Y)' 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 upretty(piecewise_fold(fo)) == \ '⎧ 2⋅sin(3⋅x) \n'\ '⎪2⋅sin(x) - sin(2⋅x) + ────────── + … for n > -∞ ∧ n < ∞ ∧ n ≠ 0\n'\ '⎨ 3 \n'\ '⎪ \n'\ '⎩ 0 otherwise ' assert pretty(FourierSeries(x, (x, -pi, pi), (0, SeqFormula(0, (k, 1, oo)), SeqFormula(0, (n, 1, oo))))) == '0' def test_diffgeom(): from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseScalarField x,y = symbols('x y', real=True) m = Manifold('M', 2) assert pretty(m) == 'M' p = Patch('P', m) assert pretty(p) == "P" rect = CoordSystem('rect', p, [x, y]) assert pretty(rect) == "rect" b = BaseScalarField(rect, 0) assert pretty(b) == "x" def test_deprecated_prettyForm(): with warns_deprecated_sympy(): from sympy.printing.pretty.pretty_symbology import xstr assert xstr(1) == '1' with warns_deprecated_sympy(): from sympy.printing.pretty.stringpict import prettyForm p = prettyForm('s', unicode='s') with warns_deprecated_sympy(): assert p.unicode == p.s == 's'
d95789d70fba878a93d7f94845d2714d6d1a7777fa434423712ce41800e941d2
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) 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, sinh, tanh) 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) from sympy.functions.special.delta_functions import DiracDelta 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, a, t, x_1, x_2, z, s, b = symbols('x y a t x_1 x_2 z s b') n = Symbol('n', integer=True) f = Function('f') def NS(e, n=15, **options): return sstr(sympify(e).evalf(n, **options), full_prec=True) def test_poly_deprecated(): p = Poly(2*x, x) assert p.integrate(x) == Poly(x**2, x, domain='QQ') # 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)) 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) == \ -z**2*acosh(x/z)/2 + x*sqrt(x**2 - z**2)/2 x = Symbol('x', real=True) y = Symbol('y', positive=True) assert integrate(1/(x**2 + y**2)**S('3/2'), x) == \ x/(y**2*sqrt(x**2 + y**2)) # If y is real and nonzero, we get x*Abs(y)/(y**3*sqrt(x**2 + y**2)), # which results from sqrt(1 + x**2/y**2) = sqrt(x**2 + y**2)/|y|. def test_issue_4403_2(): assert integrate(sqrt(-x**2 - 4), x) == \ -2*atan(x/sqrt(-4 - x**2)) + x*sqrt(-4 - x**2)/2 def test_issue_4100(): R = Symbol('R', positive=True) assert integrate(sqrt(R**2 - x**2), (x, 0, R)) == pi*R**2/4 def test_issue_5167(): from sympy.abc import w, x, y, z f = Function('f') assert Integral(Integral(f(x), x), x) == Integral(f(x), x, x) assert Integral(f(x)).args == (f(x), Tuple(x)) assert Integral(Integral(f(x))).args == (f(x), Tuple(x), Tuple(x)) assert Integral(Integral(f(x)), y).args == (f(x), Tuple(x), Tuple(y)) assert Integral(Integral(f(x), z), y).args == (f(x), Tuple(z), Tuple(y)) assert Integral(Integral(Integral(f(x), x), y), z).args == \ (f(x), Tuple(x), Tuple(y), Tuple(z)) assert integrate(Integral(f(x), x), x) == Integral(f(x), x, x) assert integrate(Integral(f(x), y), x) == y*Integral(f(x), x) assert integrate(Integral(f(x), x), y) in [Integral(y*f(x), x), y*Integral(f(x), x)] assert integrate(Integral(2, x), x) == x**2 assert integrate(Integral(2, x), y) == 2*x*y # don't re-order given limits assert Integral(1, x, y).args != Integral(1, y, x).args # do as many as possible assert Integral(f(x), y, x, y, x).doit() == y**2*Integral(f(x), x, x)/2 assert Integral(f(x), (x, 1, 2), (w, 1, x), (z, 1, y)).doit() == \ y*(x - 1)*Integral(f(x), (x, 1, 2)) - (x - 1)*Integral(f(x), (x, 1, 2)) def test_issue_4890(): z = Symbol('z', positive=True) assert integrate(exp(-log(x)**2), x) == \ sqrt(pi)*exp(Rational(1, 4))*erf(log(x) - S.Half)/2 assert integrate(exp(log(x)**2), x) == \ sqrt(pi)*exp(Rational(-1, 4))*erfi(log(x)+S.Half)/2 assert integrate(exp(-z*log(x)**2), x) == \ sqrt(pi)*exp(1/(4*z))*erf(sqrt(z)*log(x) - 1/(2*sqrt(z)))/(2*sqrt(z)) def test_issue_4551(): assert not integrate(1/(x*sqrt(1 - x**2)), x).has(Integral) def test_issue_4376(): n = Symbol('n', integer=True, positive=True) assert simplify(integrate(n*(x**(1/n) - 1), (x, 0, S.Half)) - (n**2 - 2**(1/n)*n**2 - n*2**(1/n))/(2**(1 + 1/n) + n*2**(1 + 1/n))) == 0 def test_issue_4517(): assert integrate((sqrt(x) - x**3)/x**Rational(1, 3), x) == \ 6*x**Rational(7, 6)/7 - 3*x**Rational(11, 3)/11 def test_issue_4527(): k, m = symbols('k m', integer=True) assert integrate(sin(k*x)*sin(m*x), (x, 0, pi)).simplify() == \ Piecewise((0, Eq(k, 0) | Eq(m, 0)), (-pi/2, Eq(k, -m) | (Eq(k, 0) & Eq(m, 0))), (pi/2, Eq(k, m) | (Eq(k, 0) & Eq(m, 0))), (0, True)) # Should be possible to further simplify to: # Piecewise( # (0, Eq(k, 0) | Eq(m, 0)), # (-pi/2, Eq(k, -m)), # (pi/2, Eq(k, m)), # (0, True)) assert integrate(sin(k*x)*sin(m*x), (x,)) == Piecewise( (0, And(Eq(k, 0), Eq(m, 0))), (-x*sin(m*x)**2/2 - x*cos(m*x)**2/2 + sin(m*x)*cos(m*x)/(2*m), Eq(k, -m)), (x*sin(m*x)**2/2 + x*cos(m*x)**2/2 - sin(m*x)*cos(m*x)/(2*m), Eq(k, m)), (m*sin(k*x)*cos(m*x)/(k**2 - m**2) - k*sin(m*x)*cos(k*x)/(k**2 - m**2), True)) def test_issue_4199(): ypos = Symbol('y', positive=True) # TODO: Remove conds='none' below, let the assumption take care of it. assert integrate(exp(-I*2*pi*ypos*x)*x, (x, -oo, oo), conds='none') == \ Integral(exp(-I*2*pi*ypos*x)*x, (x, -oo, oo)) 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_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(-1 + 1/sqrt(exp(x) + 1)) - log(1 + 1/sqrt(exp(x) + 1)) def test_issue_14877(): f = exp(1 - exp(x**2)*x + 2*x**2)*(2*x**3 + x)/(1 - exp(x**2)*x)**2 assert integrate(f, x) == \ -exp(2*x**2 - x*exp(x**2) + 1)/(x*exp(3*x**2) - exp(2*x**2)) def test_issue_14782(): f = sqrt(-x**2 + 1)*(-x**2 + x) assert integrate(f, [x, -1, 1]) == - pi / 8 @slow def test_issue_14782_slow(): f = sqrt(-x**2 + 1)*(-x**2 + x) assert integrate(f, [x, 0, 1]) == S.One / 3 - pi / 16 def test_issue_12081(): f = x**(Rational(-3, 2))*exp(-x) assert integrate(f, [x, 0, oo]) is oo def test_issue_15285(): y = 1/x - 1 f = 4*y*exp(-2*y)/x**2 assert integrate(f, [x, 0, 1]) == 1 def test_issue_15432(): assert integrate(x**n * exp(-x) * log(x), (x, 0, oo)).gammasimp() == Piecewise( (gamma(n + 1)*polygamma(0, n) + gamma(n + 1)/n, re(n) + 1 > 0), (Integral(x**n*exp(-x)*log(x), (x, 0, oo)), True)) def test_issue_15124(): omega = IndexedBase('omega') m, p = symbols('m p', cls=Idx) assert integrate(exp(x*I*(omega[m] + omega[p])), x, conds='none') == \ -I*exp(I*x*omega[m])*exp(I*x*omega[p])/(omega[m] + omega[p]) def test_issue_15218(): with warns_deprecated_sympy(): Integral(Eq(x, y)) with warns_deprecated_sympy(): assert Integral(Eq(x, y), x) == Eq(Integral(x, x), Integral(y, x)) with warns_deprecated_sympy(): assert Integral(Eq(x, y), x).doit() == Eq(x**2/2, x*y) with warns(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 @slow 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]) == -2*log(3)/9 - EulerGamma/9 def test_issue_2975(): w = Symbol('w') C = Symbol('C') y = Symbol('y') assert integrate(1/(y**2+C)**(S(3)/2), (y, -w/2, w/2)) == w/(C**(S(3)/2)*sqrt(1 + w**2/(4*C))) def test_issue_7827(): x, n, M = symbols('x n M') N = Symbol('N', integer=True) assert integrate(summation(x*n, (n, 1, N)), x) == x**2*(N**2/4 + N/4) assert integrate(summation(x*sin(n), (n,1,N)), x) == \ Sum(x**2*sin(n)/2, (n, 1, N)) assert integrate(summation(sin(n*x), (n,1,N)), x) == \ Sum(Piecewise((-cos(n*x)/n, Ne(n, 0)), (0, True)), (n, 1, N)) assert integrate(integrate(summation(sin(n*x), (n,1,N)), x), x) == \ Piecewise((Sum(Piecewise((-sin(n*x)/n**2, Ne(n, 0)), (-x/n, True)), (n, 1, N)), (n > -oo) & (n < oo) & Ne(n, 0)), (0, True)) assert integrate(Sum(x, (n, 1, M)), x) == M*x**2/2 raises(ValueError, lambda: integrate(Sum(x, (x, y, n)), y)) raises(ValueError, lambda: integrate(Sum(x, (x, 1, n)), n)) raises(ValueError, lambda: integrate(Sum(x, (x, 1, y)), x)) def test_issue_4231(): f = (1 + 2*x + sqrt(x + log(x))*(1 + 3*x) + x**2)/(x*(x + sqrt(x + log(x)))*sqrt(x + log(x))) assert integrate(f, x) == 2*sqrt(x + log(x)) + 2*log(x + sqrt(x + log(x))) def test_issue_17841(): f = diff(1/(x**2+x+I), x) assert integrate(f, x) == 1/(x**2 + x + I) 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_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)
72682f316f06f8b676d195f2fb0839573e68808fe8ab6a766c94b0332f48305d
from sympy.core.basic import Basic from sympy.core.containers import Tuple from sympy.core.sorting import default_sort_key from sympy.core.symbol import symbols from sympy.core.singleton import S from sympy.core.function import expand, Function from sympy.core.numbers import I from sympy.integrals.integrals import Integral from sympy.polys.polytools import factor from sympy.core.traversal import preorder_traversal, use, postorder_traversal, iterargs, iterfreeargs from sympy.functions.elementary.piecewise import ExprCondPair, Piecewise from sympy.testing.pytest import warns_deprecated_sympy from sympy.utilities.iterables import capture b1 = Basic() b2 = Basic(b1) b3 = Basic(b2) b21 = Basic(b2, b1) def test_preorder_traversal(): expr = Basic(b21, b3) assert list( preorder_traversal(expr)) == [expr, b21, b2, b1, b1, b3, b2, b1] assert list(preorder_traversal(('abc', ('d', 'ef')))) == [ ('abc', ('d', 'ef')), 'abc', ('d', 'ef'), 'd', 'ef'] result = [] pt = preorder_traversal(expr) for i in pt: result.append(i) if i == b2: pt.skip() assert result == [expr, b21, b2, b1, b3, b2] w, x, y, z = symbols('w:z') expr = z + w*(x + y) assert list(preorder_traversal([expr], keys=default_sort_key)) == \ [[w*(x + y) + z], w*(x + y) + z, z, w*(x + y), w, x + y, x, y] assert list(preorder_traversal((x + y)*z, keys=True)) == \ [z*(x + y), z, x + y, x, y] def test_use(): x, y = symbols('x y') assert use(0, expand) == 0 f = (x + y)**2*x + 1 assert use(f, expand, level=0) == x**3 + 2*x**2*y + x*y**2 + + 1 assert use(f, expand, level=1) == x**3 + 2*x**2*y + x*y**2 + + 1 assert use(f, expand, level=2) == 1 + x*(2*x*y + x**2 + y**2) assert use(f, expand, level=3) == (x + y)**2*x + 1 f = (x**2 + 1)**2 - 1 kwargs = {'gaussian': True} assert use(f, factor, level=0, kwargs=kwargs) == x**2*(x**2 + 2) assert use(f, factor, level=1, kwargs=kwargs) == (x + I)**2*(x - I)**2 - 1 assert use(f, factor, level=2, kwargs=kwargs) == (x + I)**2*(x - I)**2 - 1 assert use(f, factor, level=3, kwargs=kwargs) == (x**2 + 1)**2 - 1 def test_postorder_traversal(): x, y, z, w = symbols('x y z w') expr = z + w*(x + y) expected = [z, w, x, y, x + y, w*(x + y), w*(x + y) + z] assert list(postorder_traversal(expr, keys=default_sort_key)) == expected assert list(postorder_traversal(expr, keys=True)) == expected expr = Piecewise((x, x < 1), (x**2, True)) expected = [ x, 1, x, x < 1, ExprCondPair(x, x < 1), 2, x, x**2, S.true, ExprCondPair(x**2, True), Piecewise((x, x < 1), (x**2, True)) ] assert list(postorder_traversal(expr, keys=default_sort_key)) == expected assert list(postorder_traversal( [expr], keys=default_sort_key)) == expected + [[expr]] assert list(postorder_traversal(Integral(x**2, (x, 0, 1)), keys=default_sort_key)) == [ 2, x, x**2, 0, 1, x, Tuple(x, 0, 1), Integral(x**2, Tuple(x, 0, 1)) ] assert list(postorder_traversal(('abc', ('d', 'ef')))) == [ 'abc', 'd', 'ef', ('d', 'ef'), ('abc', ('d', 'ef'))] def test_iterargs(): f = Function('f') x = symbols('x') assert list(iterfreeargs(Integral(f(x), (f(x), 1)))) == [ Integral(f(x), (f(x), 1)), 1] assert list(iterargs(Integral(f(x), (f(x), 1)))) == [ Integral(f(x), (f(x), 1)), f(x), (f(x), 1), x, f(x), 1, x] def test_deprecated_imports(): x = symbols('x') with warns_deprecated_sympy(): from sympy.core.basic import preorder_traversal preorder_traversal(x) with warns_deprecated_sympy(): from sympy.simplify.simplify import bottom_up bottom_up(x, lambda x: x) with warns_deprecated_sympy(): from sympy.simplify.simplify import walk walk(x, lambda x: x) with warns_deprecated_sympy(): from sympy.simplify.traversaltools import use use(x, lambda x: x) with warns_deprecated_sympy(): from sympy.utilities.iterables import postorder_traversal postorder_traversal(x) with warns_deprecated_sympy(): from sympy.utilities.iterables import interactive_traversal capture(lambda: interactive_traversal(x))
9e04b0f59d7c9d5cfeef46d11186cae99c9e02018a627cf1ac1457c551f8a53c
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 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)
ee9bcd504188711adf5a5ddda2a1e59b701d3641a570284eebd828b37164d3d0
from sympy.testing.pytest import warns_deprecated_sympy def test_compatibility_submodule(): # Test the sympy.core.compatibility deprecation warning with warns_deprecated_sympy(): import sympy.core.compatibility # noqa:F401
6b3d875df5a07683268ca94189de44db0261155e4d7ef4dcba240b9021b43c45
"""Test whether all elements of cls.args are instances of Basic. """ # NOTE: keep tests sorted by (module, class name) key. If a class can't # be instantiated, add it here anyway with @SKIP("abstract class) (see # e.g. Function). import os import re from sympy.assumptions.ask import Q from sympy.core.basic import Basic from sympy.core.function import (Function, Lambda) 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.functions.elementary.exponential import (exp, log) from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import sin from sympy.testing.pytest import SKIP a, b, c, x, y, z = symbols('a,b,c,x,y,z') whitelist = [ "sympy.assumptions.predicates", # tested by test_predicates() "sympy.assumptions.relation.equality", # tested by test_predicates() ] def test_all_classes_are_tested(): this = os.path.split(__file__)[0] path = os.path.join(this, os.pardir, os.pardir) sympy_path = os.path.abspath(path) prefix = os.path.split(sympy_path)[0] + os.sep re_cls = re.compile(r"^class ([A-Za-z][A-Za-z0-9_]*)\s*\(", re.MULTILINE) modules = {} for root, dirs, files in os.walk(sympy_path): module = root.replace(prefix, "").replace(os.sep, ".") for file in files: if file.startswith(("_", "test_", "bench_")): continue if not file.endswith(".py"): continue with open(os.path.join(root, file), encoding='utf-8') as f: text = f.read() submodule = module + '.' + file[:-3] if any(submodule.startswith(wpath) for wpath in whitelist): continue names = re_cls.findall(text) if not names: continue try: mod = __import__(submodule, fromlist=names) except ImportError: continue def is_Basic(name): cls = getattr(mod, name) if hasattr(cls, '_sympy_deprecated_func'): cls = cls._sympy_deprecated_func if not isinstance(cls, type): # check instance of singleton class with same name cls = type(cls) return issubclass(cls, Basic) names = list(filter(is_Basic, names)) if names: modules[submodule] = names ns = globals() failed = [] for module, names in modules.items(): mod = module.replace('.', '__') for name in names: test = 'test_' + mod + '__' + name if test not in ns: failed.append(module + '.' + name) assert not failed, "Missing classes: %s. Please add tests for these to sympy/core/tests/test_args.py." % ", ".join(failed) def _test_args(obj): all_basic = all(isinstance(arg, Basic) for arg in obj.args) # Ideally obj.func(*obj.args) would always recreate the object, but for # now, we only require it for objects with non-empty .args recreatable = not obj.args or obj.func(*obj.args) == obj return all_basic and recreatable def test_sympy__algebras__quaternion__Quaternion(): from sympy.algebras.quaternion import Quaternion assert _test_args(Quaternion(x, 1, 2, 3)) def test_sympy__assumptions__assume__AppliedPredicate(): from sympy.assumptions.assume import AppliedPredicate, Predicate assert _test_args(AppliedPredicate(Predicate("test"), 2)) assert _test_args(Q.is_true(True)) @SKIP("abstract class") def test_sympy__assumptions__assume__Predicate(): pass def test_predicates(): predicates = [ getattr(Q, attr) for attr in Q.__class__.__dict__ if not attr.startswith('__')] for p in predicates: assert _test_args(p) def test_sympy__assumptions__assume__UndefinedPredicate(): from sympy.assumptions.assume import Predicate assert _test_args(Predicate("test")) @SKIP('abstract class') def test_sympy__assumptions__relation__binrel__BinaryRelation(): pass def test_sympy__assumptions__relation__binrel__AppliedBinaryRelation(): assert _test_args(Q.eq(1, 2)) def test_sympy__assumptions__wrapper__AssumptionsWrapper(): from sympy.assumptions.wrapper import AssumptionsWrapper assert _test_args(AssumptionsWrapper(x, Q.positive(x))) @SKIP("abstract Class") def test_sympy__codegen__ast__CodegenAST(): from sympy.codegen.ast import CodegenAST assert _test_args(CodegenAST()) @SKIP("abstract Class") def test_sympy__codegen__ast__AssignmentBase(): from sympy.codegen.ast import AssignmentBase assert _test_args(AssignmentBase(x, 1)) @SKIP("abstract Class") def test_sympy__codegen__ast__AugmentedAssignment(): from sympy.codegen.ast import AugmentedAssignment assert _test_args(AugmentedAssignment(x, 1)) def test_sympy__codegen__ast__AddAugmentedAssignment(): from sympy.codegen.ast import AddAugmentedAssignment assert _test_args(AddAugmentedAssignment(x, 1)) def test_sympy__codegen__ast__SubAugmentedAssignment(): from sympy.codegen.ast import SubAugmentedAssignment assert _test_args(SubAugmentedAssignment(x, 1)) def test_sympy__codegen__ast__MulAugmentedAssignment(): from sympy.codegen.ast import MulAugmentedAssignment assert _test_args(MulAugmentedAssignment(x, 1)) def test_sympy__codegen__ast__DivAugmentedAssignment(): from sympy.codegen.ast import DivAugmentedAssignment assert _test_args(DivAugmentedAssignment(x, 1)) def test_sympy__codegen__ast__ModAugmentedAssignment(): from sympy.codegen.ast import ModAugmentedAssignment assert _test_args(ModAugmentedAssignment(x, 1)) def test_sympy__codegen__ast__CodeBlock(): from sympy.codegen.ast import CodeBlock, Assignment assert _test_args(CodeBlock(Assignment(x, 1), Assignment(y, 2))) def test_sympy__codegen__ast__For(): from sympy.codegen.ast import For, CodeBlock, AddAugmentedAssignment from sympy.sets import Range assert _test_args(For(x, Range(10), CodeBlock(AddAugmentedAssignment(y, 1)))) def test_sympy__codegen__ast__Token(): from sympy.codegen.ast import Token assert _test_args(Token()) def test_sympy__codegen__ast__ContinueToken(): from sympy.codegen.ast import ContinueToken assert _test_args(ContinueToken()) def test_sympy__codegen__ast__BreakToken(): from sympy.codegen.ast import BreakToken assert _test_args(BreakToken()) def test_sympy__codegen__ast__NoneToken(): from sympy.codegen.ast import NoneToken assert _test_args(NoneToken()) def test_sympy__codegen__ast__String(): from sympy.codegen.ast import String assert _test_args(String('foobar')) def test_sympy__codegen__ast__QuotedString(): from sympy.codegen.ast import QuotedString assert _test_args(QuotedString('foobar')) def test_sympy__codegen__ast__Comment(): from sympy.codegen.ast import Comment assert _test_args(Comment('this is a comment')) def test_sympy__codegen__ast__Node(): from sympy.codegen.ast import Node assert _test_args(Node()) assert _test_args(Node(attrs={1, 2, 3})) def test_sympy__codegen__ast__Type(): from sympy.codegen.ast import Type assert _test_args(Type('float128')) def test_sympy__codegen__ast__IntBaseType(): from sympy.codegen.ast import IntBaseType assert _test_args(IntBaseType('bigint')) def test_sympy__codegen__ast___SizedIntType(): from sympy.codegen.ast import _SizedIntType assert _test_args(_SizedIntType('int128', 128)) def test_sympy__codegen__ast__SignedIntType(): from sympy.codegen.ast import SignedIntType assert _test_args(SignedIntType('int128_with_sign', 128)) def test_sympy__codegen__ast__UnsignedIntType(): from sympy.codegen.ast import UnsignedIntType assert _test_args(UnsignedIntType('unt128', 128)) def test_sympy__codegen__ast__FloatBaseType(): from sympy.codegen.ast import FloatBaseType assert _test_args(FloatBaseType('positive_real')) def test_sympy__codegen__ast__FloatType(): from sympy.codegen.ast import FloatType assert _test_args(FloatType('float242', 242, nmant=142, nexp=99)) def test_sympy__codegen__ast__ComplexBaseType(): from sympy.codegen.ast import ComplexBaseType assert _test_args(ComplexBaseType('positive_cmplx')) def test_sympy__codegen__ast__ComplexType(): from sympy.codegen.ast import ComplexType assert _test_args(ComplexType('complex42', 42, nmant=15, nexp=5)) def test_sympy__codegen__ast__Attribute(): from sympy.codegen.ast import Attribute assert _test_args(Attribute('noexcept')) def test_sympy__codegen__ast__Variable(): from sympy.codegen.ast import Variable, Type, value_const assert _test_args(Variable(x)) assert _test_args(Variable(y, Type('float32'), {value_const})) assert _test_args(Variable(z, type=Type('float64'))) def test_sympy__codegen__ast__Pointer(): from sympy.codegen.ast import Pointer, Type, pointer_const assert _test_args(Pointer(x)) assert _test_args(Pointer(y, type=Type('float32'))) assert _test_args(Pointer(z, Type('float64'), {pointer_const})) def test_sympy__codegen__ast__Declaration(): from sympy.codegen.ast import Declaration, Variable, Type vx = Variable(x, type=Type('float')) assert _test_args(Declaration(vx)) def test_sympy__codegen__ast__While(): from sympy.codegen.ast import While, AddAugmentedAssignment assert _test_args(While(abs(x) < 1, [AddAugmentedAssignment(x, -1)])) def test_sympy__codegen__ast__Scope(): from sympy.codegen.ast import Scope, AddAugmentedAssignment assert _test_args(Scope([AddAugmentedAssignment(x, -1)])) def test_sympy__codegen__ast__Stream(): from sympy.codegen.ast import Stream assert _test_args(Stream('stdin')) def test_sympy__codegen__ast__Print(): from sympy.codegen.ast import Print assert _test_args(Print([x, y])) assert _test_args(Print([x, y], "%d %d")) def test_sympy__codegen__ast__FunctionPrototype(): from sympy.codegen.ast import FunctionPrototype, real, Declaration, Variable inp_x = Declaration(Variable(x, type=real)) assert _test_args(FunctionPrototype(real, 'pwer', [inp_x])) def test_sympy__codegen__ast__FunctionDefinition(): from sympy.codegen.ast import FunctionDefinition, real, Declaration, Variable, Assignment inp_x = Declaration(Variable(x, type=real)) assert _test_args(FunctionDefinition(real, 'pwer', [inp_x], [Assignment(x, x**2)])) def test_sympy__codegen__ast__Return(): from sympy.codegen.ast import Return assert _test_args(Return(x)) def test_sympy__codegen__ast__FunctionCall(): from sympy.codegen.ast import FunctionCall assert _test_args(FunctionCall('pwer', [x])) def test_sympy__codegen__ast__Element(): from sympy.codegen.ast import Element assert _test_args(Element('x', range(3))) def test_sympy__codegen__cnodes__CommaOperator(): from sympy.codegen.cnodes import CommaOperator assert _test_args(CommaOperator(1, 2)) def test_sympy__codegen__cnodes__goto(): from sympy.codegen.cnodes import goto assert _test_args(goto('early_exit')) def test_sympy__codegen__cnodes__Label(): from sympy.codegen.cnodes import Label assert _test_args(Label('early_exit')) def test_sympy__codegen__cnodes__PreDecrement(): from sympy.codegen.cnodes import PreDecrement assert _test_args(PreDecrement(x)) def test_sympy__codegen__cnodes__PostDecrement(): from sympy.codegen.cnodes import PostDecrement assert _test_args(PostDecrement(x)) def test_sympy__codegen__cnodes__PreIncrement(): from sympy.codegen.cnodes import PreIncrement assert _test_args(PreIncrement(x)) def test_sympy__codegen__cnodes__PostIncrement(): from sympy.codegen.cnodes import PostIncrement assert _test_args(PostIncrement(x)) def test_sympy__codegen__cnodes__struct(): from sympy.codegen.ast import real, Variable from sympy.codegen.cnodes import struct assert _test_args(struct(declarations=[ Variable(x, type=real), Variable(y, type=real) ])) def test_sympy__codegen__cnodes__union(): from sympy.codegen.ast import float32, int32, Variable from sympy.codegen.cnodes import union assert _test_args(union(declarations=[ Variable(x, type=float32), Variable(y, type=int32) ])) def test_sympy__codegen__cxxnodes__using(): from sympy.codegen.cxxnodes import using assert _test_args(using('std::vector')) assert _test_args(using('std::vector', 'vec')) def test_sympy__codegen__fnodes__Program(): from sympy.codegen.fnodes import Program assert _test_args(Program('foobar', [])) def test_sympy__codegen__fnodes__Module(): from sympy.codegen.fnodes import Module assert _test_args(Module('foobar', [], [])) def test_sympy__codegen__fnodes__Subroutine(): from sympy.codegen.fnodes import Subroutine x = symbols('x', real=True) assert _test_args(Subroutine('foo', [x], [])) def test_sympy__codegen__fnodes__GoTo(): from sympy.codegen.fnodes import GoTo assert _test_args(GoTo([10])) assert _test_args(GoTo([10, 20], x > 1)) def test_sympy__codegen__fnodes__FortranReturn(): from sympy.codegen.fnodes import FortranReturn assert _test_args(FortranReturn(10)) def test_sympy__codegen__fnodes__Extent(): from sympy.codegen.fnodes import Extent assert _test_args(Extent()) assert _test_args(Extent(None)) assert _test_args(Extent(':')) assert _test_args(Extent(-3, 4)) assert _test_args(Extent(x, y)) def test_sympy__codegen__fnodes__use_rename(): from sympy.codegen.fnodes import use_rename assert _test_args(use_rename('loc', 'glob')) def test_sympy__codegen__fnodes__use(): from sympy.codegen.fnodes import use assert _test_args(use('modfoo', only='bar')) def test_sympy__codegen__fnodes__SubroutineCall(): from sympy.codegen.fnodes import SubroutineCall assert _test_args(SubroutineCall('foo', ['bar', 'baz'])) def test_sympy__codegen__fnodes__Do(): from sympy.codegen.fnodes import Do assert _test_args(Do([], 'i', 1, 42)) def test_sympy__codegen__fnodes__ImpliedDoLoop(): from sympy.codegen.fnodes import ImpliedDoLoop assert _test_args(ImpliedDoLoop('i', 'i', 1, 42)) def test_sympy__codegen__fnodes__ArrayConstructor(): from sympy.codegen.fnodes import ArrayConstructor assert _test_args(ArrayConstructor([1, 2, 3])) from sympy.codegen.fnodes import ImpliedDoLoop idl = ImpliedDoLoop('i', 'i', 1, 42) assert _test_args(ArrayConstructor([1, idl, 3])) def test_sympy__codegen__fnodes__sum_(): from sympy.codegen.fnodes import sum_ assert _test_args(sum_('arr')) def test_sympy__codegen__fnodes__product_(): from sympy.codegen.fnodes import product_ assert _test_args(product_('arr')) def test_sympy__codegen__numpy_nodes__logaddexp(): from sympy.codegen.numpy_nodes import logaddexp assert _test_args(logaddexp(x, y)) def test_sympy__codegen__numpy_nodes__logaddexp2(): from sympy.codegen.numpy_nodes import logaddexp2 assert _test_args(logaddexp2(x, y)) def test_sympy__codegen__pynodes__List(): from sympy.codegen.pynodes import List assert _test_args(List(1, 2, 3)) def test_sympy__codegen__pynodes__NumExprEvaluate(): from sympy.codegen.pynodes import NumExprEvaluate assert _test_args(NumExprEvaluate(x)) def test_sympy__codegen__scipy_nodes__cosm1(): from sympy.codegen.scipy_nodes import cosm1 assert _test_args(cosm1(x)) def test_sympy__codegen__abstract_nodes__List(): from sympy.codegen.abstract_nodes import List assert _test_args(List(1, 2, 3)) def test_sympy__combinatorics__graycode__GrayCode(): from sympy.combinatorics.graycode import GrayCode # an integer is given and returned from GrayCode as the arg assert _test_args(GrayCode(3, start='100')) assert _test_args(GrayCode(3, rank=1)) def test_sympy__combinatorics__permutations__Permutation(): from sympy.combinatorics.permutations import Permutation assert _test_args(Permutation([0, 1, 2, 3])) def test_sympy__combinatorics__permutations__AppliedPermutation(): from sympy.combinatorics.permutations import Permutation from sympy.combinatorics.permutations import AppliedPermutation p = Permutation([0, 1, 2, 3]) assert _test_args(AppliedPermutation(p, x)) def test_sympy__combinatorics__perm_groups__PermutationGroup(): from sympy.combinatorics.permutations import Permutation from sympy.combinatorics.perm_groups import PermutationGroup assert _test_args(PermutationGroup([Permutation([0, 1])])) def test_sympy__combinatorics__polyhedron__Polyhedron(): from sympy.combinatorics.permutations import Permutation from sympy.combinatorics.polyhedron import Polyhedron from sympy.abc import w, x, y, z pgroup = [Permutation([[0, 1, 2], [3]]), Permutation([[0, 1, 3], [2]]), Permutation([[0, 2, 3], [1]]), Permutation([[1, 2, 3], [0]]), Permutation([[0, 1], [2, 3]]), Permutation([[0, 2], [1, 3]]), Permutation([[0, 3], [1, 2]]), Permutation([[0, 1, 2, 3]])] corners = [w, x, y, z] faces = [(w, x, y), (w, y, z), (w, z, x), (x, y, z)] assert _test_args(Polyhedron(corners, faces, pgroup)) def test_sympy__combinatorics__prufer__Prufer(): from sympy.combinatorics.prufer import Prufer assert _test_args(Prufer([[0, 1], [0, 2], [0, 3]], 4)) def test_sympy__combinatorics__partitions__Partition(): from sympy.combinatorics.partitions import Partition assert _test_args(Partition([1])) def test_sympy__combinatorics__partitions__IntegerPartition(): from sympy.combinatorics.partitions import IntegerPartition assert _test_args(IntegerPartition([1])) def test_sympy__concrete__products__Product(): from sympy.concrete.products import Product assert _test_args(Product(x, (x, 0, 10))) assert _test_args(Product(x, (x, 0, y), (y, 0, 10))) @SKIP("abstract Class") def test_sympy__concrete__expr_with_limits__ExprWithLimits(): from sympy.concrete.expr_with_limits import ExprWithLimits assert _test_args(ExprWithLimits(x, (x, 0, 10))) assert _test_args(ExprWithLimits(x*y, (x, 0, 10.),(y,1.,3))) @SKIP("abstract Class") def test_sympy__concrete__expr_with_limits__AddWithLimits(): from sympy.concrete.expr_with_limits import AddWithLimits assert _test_args(AddWithLimits(x, (x, 0, 10))) assert _test_args(AddWithLimits(x*y, (x, 0, 10),(y,1,3))) @SKIP("abstract Class") def test_sympy__concrete__expr_with_intlimits__ExprWithIntLimits(): from sympy.concrete.expr_with_intlimits import ExprWithIntLimits assert _test_args(ExprWithIntLimits(x, (x, 0, 10))) assert _test_args(ExprWithIntLimits(x*y, (x, 0, 10),(y,1,3))) def test_sympy__concrete__summations__Sum(): from sympy.concrete.summations import Sum assert _test_args(Sum(x, (x, 0, 10))) assert _test_args(Sum(x, (x, 0, y), (y, 0, 10))) def test_sympy__core__add__Add(): from sympy.core.add import Add assert _test_args(Add(x, y, z, 2)) def test_sympy__core__basic__Atom(): from sympy.core.basic import Atom assert _test_args(Atom()) def test_sympy__core__basic__Basic(): from sympy.core.basic import Basic assert _test_args(Basic()) def test_sympy__core__containers__Dict(): from sympy.core.containers import Dict assert _test_args(Dict({x: y, y: z})) def test_sympy__core__containers__Tuple(): from sympy.core.containers import Tuple assert _test_args(Tuple(x, y, z, 2)) def test_sympy__core__expr__AtomicExpr(): from sympy.core.expr import AtomicExpr assert _test_args(AtomicExpr()) def test_sympy__core__expr__Expr(): from sympy.core.expr import Expr assert _test_args(Expr()) def test_sympy__core__expr__UnevaluatedExpr(): from sympy.core.expr import UnevaluatedExpr from sympy.abc import x assert _test_args(UnevaluatedExpr(x)) def test_sympy__core__function__Application(): from sympy.core.function import Application assert _test_args(Application(1, 2, 3)) def test_sympy__core__function__AppliedUndef(): from sympy.core.function import AppliedUndef assert _test_args(AppliedUndef(1, 2, 3)) def test_sympy__core__function__Derivative(): from sympy.core.function import Derivative assert _test_args(Derivative(2, x, y, 3)) @SKIP("abstract class") def test_sympy__core__function__Function(): pass def test_sympy__core__function__Lambda(): assert _test_args(Lambda((x, y), x + y + z)) def test_sympy__core__function__Subs(): from sympy.core.function import Subs assert _test_args(Subs(x + y, x, 2)) def test_sympy__core__function__WildFunction(): from sympy.core.function import WildFunction assert _test_args(WildFunction('f')) def test_sympy__core__mod__Mod(): from sympy.core.mod import Mod assert _test_args(Mod(x, 2)) def test_sympy__core__mul__Mul(): from sympy.core.mul import Mul assert _test_args(Mul(2, x, y, z)) def test_sympy__core__numbers__Catalan(): from sympy.core.numbers import Catalan assert _test_args(Catalan()) def test_sympy__core__numbers__ComplexInfinity(): from sympy.core.numbers import ComplexInfinity assert _test_args(ComplexInfinity()) def test_sympy__core__numbers__EulerGamma(): from sympy.core.numbers import EulerGamma assert _test_args(EulerGamma()) def test_sympy__core__numbers__Exp1(): from sympy.core.numbers import Exp1 assert _test_args(Exp1()) def test_sympy__core__numbers__Float(): from sympy.core.numbers import Float assert _test_args(Float(1.23)) def test_sympy__core__numbers__GoldenRatio(): from sympy.core.numbers import GoldenRatio assert _test_args(GoldenRatio()) def test_sympy__core__numbers__TribonacciConstant(): from sympy.core.numbers import TribonacciConstant assert _test_args(TribonacciConstant()) def test_sympy__core__numbers__Half(): from sympy.core.numbers import Half assert _test_args(Half()) def test_sympy__core__numbers__ImaginaryUnit(): from sympy.core.numbers import ImaginaryUnit assert _test_args(ImaginaryUnit()) def test_sympy__core__numbers__Infinity(): from sympy.core.numbers import Infinity assert _test_args(Infinity()) def test_sympy__core__numbers__Integer(): from sympy.core.numbers import Integer assert _test_args(Integer(7)) @SKIP("abstract class") def test_sympy__core__numbers__IntegerConstant(): pass def test_sympy__core__numbers__NaN(): from sympy.core.numbers import NaN assert _test_args(NaN()) def test_sympy__core__numbers__NegativeInfinity(): from sympy.core.numbers import NegativeInfinity assert _test_args(NegativeInfinity()) def test_sympy__core__numbers__NegativeOne(): from sympy.core.numbers import NegativeOne assert _test_args(NegativeOne()) def test_sympy__core__numbers__Number(): from sympy.core.numbers import Number assert _test_args(Number(1, 7)) def test_sympy__core__numbers__NumberSymbol(): from sympy.core.numbers import NumberSymbol assert _test_args(NumberSymbol()) def test_sympy__core__numbers__One(): from sympy.core.numbers import One assert _test_args(One()) def test_sympy__core__numbers__Pi(): from sympy.core.numbers import Pi assert _test_args(Pi()) def test_sympy__core__numbers__Rational(): from sympy.core.numbers import Rational assert _test_args(Rational(1, 7)) @SKIP("abstract class") def test_sympy__core__numbers__RationalConstant(): pass def test_sympy__core__numbers__Zero(): from sympy.core.numbers import Zero assert _test_args(Zero()) @SKIP("abstract class") def test_sympy__core__operations__AssocOp(): pass @SKIP("abstract class") def test_sympy__core__operations__LatticeOp(): pass def test_sympy__core__power__Pow(): from sympy.core.power import Pow assert _test_args(Pow(x, 2)) def test_sympy__core__relational__Equality(): from sympy.core.relational import Equality assert _test_args(Equality(x, 2)) def test_sympy__core__relational__GreaterThan(): from sympy.core.relational import GreaterThan assert _test_args(GreaterThan(x, 2)) def test_sympy__core__relational__LessThan(): from sympy.core.relational import LessThan assert _test_args(LessThan(x, 2)) @SKIP("abstract class") def test_sympy__core__relational__Relational(): pass def test_sympy__core__relational__StrictGreaterThan(): from sympy.core.relational import StrictGreaterThan assert _test_args(StrictGreaterThan(x, 2)) def test_sympy__core__relational__StrictLessThan(): from sympy.core.relational import StrictLessThan assert _test_args(StrictLessThan(x, 2)) def test_sympy__core__relational__Unequality(): from sympy.core.relational import Unequality assert _test_args(Unequality(x, 2)) def test_sympy__sandbox__indexed_integrals__IndexedIntegral(): from sympy.tensor import IndexedBase, Idx from sympy.sandbox.indexed_integrals import IndexedIntegral A = IndexedBase('A') i, j = symbols('i j', integer=True) a1, a2 = symbols('a1:3', cls=Idx) assert _test_args(IndexedIntegral(A[a1], A[a2])) assert _test_args(IndexedIntegral(A[i], A[j])) def test_sympy__calculus__accumulationbounds__AccumulationBounds(): from sympy.calculus.accumulationbounds import AccumulationBounds assert _test_args(AccumulationBounds(0, 1)) def test_sympy__sets__ordinals__OmegaPower(): from sympy.sets.ordinals import OmegaPower assert _test_args(OmegaPower(1, 1)) def test_sympy__sets__ordinals__Ordinal(): from sympy.sets.ordinals import Ordinal, OmegaPower assert _test_args(Ordinal(OmegaPower(2, 1))) def test_sympy__sets__ordinals__OrdinalOmega(): from sympy.sets.ordinals import OrdinalOmega assert _test_args(OrdinalOmega()) def test_sympy__sets__ordinals__OrdinalZero(): from sympy.sets.ordinals import OrdinalZero assert _test_args(OrdinalZero()) def test_sympy__sets__powerset__PowerSet(): from sympy.sets.powerset import PowerSet from sympy.core.singleton import S assert _test_args(PowerSet(S.EmptySet)) def test_sympy__sets__sets__EmptySet(): from sympy.sets.sets import EmptySet assert _test_args(EmptySet()) def test_sympy__sets__sets__UniversalSet(): from sympy.sets.sets import UniversalSet assert _test_args(UniversalSet()) def test_sympy__sets__sets__FiniteSet(): from sympy.sets.sets import FiniteSet assert _test_args(FiniteSet(x, y, z)) def test_sympy__sets__sets__Interval(): from sympy.sets.sets import Interval assert _test_args(Interval(0, 1)) def test_sympy__sets__sets__ProductSet(): from sympy.sets.sets import ProductSet, Interval assert _test_args(ProductSet(Interval(0, 1), Interval(0, 1))) @SKIP("does it make sense to test this?") def test_sympy__sets__sets__Set(): from sympy.sets.sets import Set assert _test_args(Set()) def test_sympy__sets__sets__Intersection(): from sympy.sets.sets import Intersection, Interval from sympy.core.symbol import Symbol x = Symbol('x') y = Symbol('y') S = Intersection(Interval(0, x), Interval(y, 1)) assert isinstance(S, Intersection) assert _test_args(S) def test_sympy__sets__sets__Union(): from sympy.sets.sets import Union, Interval assert _test_args(Union(Interval(0, 1), Interval(2, 3))) def test_sympy__sets__sets__Complement(): from sympy.sets.sets import Complement, Interval assert _test_args(Complement(Interval(0, 2), Interval(0, 1))) def test_sympy__sets__sets__SymmetricDifference(): from sympy.sets.sets import FiniteSet, SymmetricDifference assert _test_args(SymmetricDifference(FiniteSet(1, 2, 3), \ FiniteSet(2, 3, 4))) def test_sympy__sets__sets__DisjointUnion(): from sympy.sets.sets import FiniteSet, DisjointUnion assert _test_args(DisjointUnion(FiniteSet(1, 2, 3), \ FiniteSet(2, 3, 4))) def test_sympy__physics__quantum__trace__Tr(): from sympy.physics.quantum.trace import Tr a, b = symbols('a b', commutative=False) assert _test_args(Tr(a + b)) def test_sympy__sets__setexpr__SetExpr(): from sympy.sets.setexpr import SetExpr from sympy.sets.sets import Interval assert _test_args(SetExpr(Interval(0, 1))) def test_sympy__sets__fancysets__Rationals(): from sympy.sets.fancysets import Rationals assert _test_args(Rationals()) def test_sympy__sets__fancysets__Naturals(): from sympy.sets.fancysets import Naturals assert _test_args(Naturals()) def test_sympy__sets__fancysets__Naturals0(): from sympy.sets.fancysets import Naturals0 assert _test_args(Naturals0()) def test_sympy__sets__fancysets__Integers(): from sympy.sets.fancysets import Integers assert _test_args(Integers()) def test_sympy__sets__fancysets__Reals(): from sympy.sets.fancysets import Reals assert _test_args(Reals()) def test_sympy__sets__fancysets__Complexes(): from sympy.sets.fancysets import Complexes assert _test_args(Complexes()) def test_sympy__sets__fancysets__ComplexRegion(): from sympy.sets.fancysets import ComplexRegion from sympy.core.singleton import S from sympy.sets import Interval a = Interval(0, 1) b = Interval(2, 3) theta = Interval(0, 2*S.Pi) assert _test_args(ComplexRegion(a*b)) assert _test_args(ComplexRegion(a*theta, polar=True)) def test_sympy__sets__fancysets__CartesianComplexRegion(): from sympy.sets.fancysets import CartesianComplexRegion from sympy.sets import Interval a = Interval(0, 1) b = Interval(2, 3) assert _test_args(CartesianComplexRegion(a*b)) def test_sympy__sets__fancysets__PolarComplexRegion(): from sympy.sets.fancysets import PolarComplexRegion from sympy.core.singleton import S from sympy.sets import Interval a = Interval(0, 1) theta = Interval(0, 2*S.Pi) assert _test_args(PolarComplexRegion(a*theta)) def test_sympy__sets__fancysets__ImageSet(): from sympy.sets.fancysets import ImageSet from sympy.core.singleton import S from sympy.core.symbol import Symbol x = Symbol('x') assert _test_args(ImageSet(Lambda(x, x**2), S.Naturals)) def test_sympy__sets__fancysets__Range(): from sympy.sets.fancysets import Range assert _test_args(Range(1, 5, 1)) def test_sympy__sets__conditionset__ConditionSet(): from sympy.sets.conditionset import ConditionSet from sympy.core.singleton import S from sympy.core.symbol import Symbol x = Symbol('x') assert _test_args(ConditionSet(x, Eq(x**2, 1), S.Reals)) def test_sympy__sets__contains__Contains(): from sympy.sets.fancysets import Range from sympy.sets.contains import Contains assert _test_args(Contains(x, Range(0, 10, 2))) # STATS from sympy.stats.crv_types import NormalDistribution nd = NormalDistribution(0, 1) from sympy.stats.frv_types import DieDistribution die = DieDistribution(6) def test_sympy__stats__crv__ContinuousDomain(): from sympy.sets.sets import Interval from sympy.stats.crv import ContinuousDomain assert _test_args(ContinuousDomain({x}, Interval(-oo, oo))) def test_sympy__stats__crv__SingleContinuousDomain(): from sympy.sets.sets import Interval from sympy.stats.crv import SingleContinuousDomain assert _test_args(SingleContinuousDomain(x, Interval(-oo, oo))) def test_sympy__stats__crv__ProductContinuousDomain(): from sympy.sets.sets import Interval from sympy.stats.crv import SingleContinuousDomain, ProductContinuousDomain D = SingleContinuousDomain(x, Interval(-oo, oo)) E = SingleContinuousDomain(y, Interval(0, oo)) assert _test_args(ProductContinuousDomain(D, E)) def test_sympy__stats__crv__ConditionalContinuousDomain(): from sympy.sets.sets import Interval from sympy.stats.crv import (SingleContinuousDomain, ConditionalContinuousDomain) D = SingleContinuousDomain(x, Interval(-oo, oo)) assert _test_args(ConditionalContinuousDomain(D, x > 0)) def test_sympy__stats__crv__ContinuousPSpace(): from sympy.sets.sets import Interval from sympy.stats.crv import ContinuousPSpace, SingleContinuousDomain D = SingleContinuousDomain(x, Interval(-oo, oo)) assert _test_args(ContinuousPSpace(D, nd)) def test_sympy__stats__crv__SingleContinuousPSpace(): from sympy.stats.crv import SingleContinuousPSpace assert _test_args(SingleContinuousPSpace(x, nd)) @SKIP("abstract class") def test_sympy__stats__rv__Distribution(): pass @SKIP("abstract class") def test_sympy__stats__crv__SingleContinuousDistribution(): pass def test_sympy__stats__drv__SingleDiscreteDomain(): from sympy.stats.drv import SingleDiscreteDomain assert _test_args(SingleDiscreteDomain(x, S.Naturals)) def test_sympy__stats__drv__ProductDiscreteDomain(): from sympy.stats.drv import SingleDiscreteDomain, ProductDiscreteDomain X = SingleDiscreteDomain(x, S.Naturals) Y = SingleDiscreteDomain(y, S.Integers) assert _test_args(ProductDiscreteDomain(X, Y)) def test_sympy__stats__drv__SingleDiscretePSpace(): from sympy.stats.drv import SingleDiscretePSpace from sympy.stats.drv_types import PoissonDistribution assert _test_args(SingleDiscretePSpace(x, PoissonDistribution(1))) def test_sympy__stats__drv__DiscretePSpace(): from sympy.stats.drv import DiscretePSpace, SingleDiscreteDomain density = Lambda(x, 2**(-x)) domain = SingleDiscreteDomain(x, S.Naturals) assert _test_args(DiscretePSpace(domain, density)) def test_sympy__stats__drv__ConditionalDiscreteDomain(): from sympy.stats.drv import ConditionalDiscreteDomain, SingleDiscreteDomain X = SingleDiscreteDomain(x, S.Naturals0) assert _test_args(ConditionalDiscreteDomain(X, x > 2)) def test_sympy__stats__joint_rv__JointPSpace(): from sympy.stats.joint_rv import JointPSpace, JointDistribution assert _test_args(JointPSpace('X', JointDistribution(1))) def test_sympy__stats__joint_rv__JointRandomSymbol(): from sympy.stats.joint_rv import JointRandomSymbol assert _test_args(JointRandomSymbol(x)) def test_sympy__stats__joint_rv_types__JointDistributionHandmade(): from sympy.tensor.indexed import Indexed from sympy.stats.joint_rv_types import JointDistributionHandmade x1, x2 = (Indexed('x', i) for i in (1, 2)) assert _test_args(JointDistributionHandmade(x1 + x2, S.Reals**2)) def test_sympy__stats__joint_rv__MarginalDistribution(): from sympy.stats.rv import RandomSymbol from sympy.stats.joint_rv import MarginalDistribution r = RandomSymbol(S('r')) assert _test_args(MarginalDistribution(r, (r,))) def test_sympy__stats__compound_rv__CompoundDistribution(): from sympy.stats.compound_rv import CompoundDistribution from sympy.stats.drv_types import PoissonDistribution, Poisson r = Poisson('r', 10) assert _test_args(CompoundDistribution(PoissonDistribution(r))) def test_sympy__stats__compound_rv__CompoundPSpace(): from sympy.stats.compound_rv import CompoundPSpace, CompoundDistribution from sympy.stats.drv_types import PoissonDistribution, Poisson r = Poisson('r', 5) C = CompoundDistribution(PoissonDistribution(r)) assert _test_args(CompoundPSpace('C', C)) @SKIP("abstract class") def test_sympy__stats__drv__SingleDiscreteDistribution(): pass @SKIP("abstract class") def test_sympy__stats__drv__DiscreteDistribution(): pass @SKIP("abstract class") def test_sympy__stats__drv__DiscreteDomain(): pass def test_sympy__stats__rv__RandomDomain(): from sympy.stats.rv import RandomDomain from sympy.sets.sets import FiniteSet assert _test_args(RandomDomain(FiniteSet(x), FiniteSet(1, 2, 3))) def test_sympy__stats__rv__SingleDomain(): from sympy.stats.rv import SingleDomain from sympy.sets.sets import FiniteSet assert _test_args(SingleDomain(x, FiniteSet(1, 2, 3))) def test_sympy__stats__rv__ConditionalDomain(): from sympy.stats.rv import ConditionalDomain, RandomDomain from sympy.sets.sets import FiniteSet D = RandomDomain(FiniteSet(x), FiniteSet(1, 2)) assert _test_args(ConditionalDomain(D, x > 1)) def test_sympy__stats__rv__MatrixDomain(): from sympy.stats.rv import MatrixDomain from sympy.matrices import MatrixSet from sympy.core.singleton import S assert _test_args(MatrixDomain(x, MatrixSet(2, 2, S.Reals))) def test_sympy__stats__rv__PSpace(): from sympy.stats.rv import PSpace, RandomDomain from sympy.sets.sets import FiniteSet D = RandomDomain(FiniteSet(x), FiniteSet(1, 2, 3, 4, 5, 6)) assert _test_args(PSpace(D, die)) @SKIP("abstract Class") def test_sympy__stats__rv__SinglePSpace(): pass def test_sympy__stats__rv__RandomSymbol(): from sympy.stats.rv import RandomSymbol from sympy.stats.crv import SingleContinuousPSpace A = SingleContinuousPSpace(x, nd) assert _test_args(RandomSymbol(x, A)) @SKIP("abstract Class") def test_sympy__stats__rv__ProductPSpace(): pass def test_sympy__stats__rv__IndependentProductPSpace(): from sympy.stats.rv import IndependentProductPSpace from sympy.stats.crv import SingleContinuousPSpace A = SingleContinuousPSpace(x, nd) B = SingleContinuousPSpace(y, nd) assert _test_args(IndependentProductPSpace(A, B)) def test_sympy__stats__rv__ProductDomain(): from sympy.sets.sets import Interval from sympy.stats.rv import ProductDomain, SingleDomain D = SingleDomain(x, Interval(-oo, oo)) E = SingleDomain(y, Interval(0, oo)) assert _test_args(ProductDomain(D, E)) def test_sympy__stats__symbolic_probability__Probability(): from sympy.stats.symbolic_probability import Probability from sympy.stats import Normal X = Normal('X', 0, 1) assert _test_args(Probability(X > 0)) def test_sympy__stats__symbolic_probability__Expectation(): from sympy.stats.symbolic_probability import Expectation from sympy.stats import Normal X = Normal('X', 0, 1) assert _test_args(Expectation(X > 0)) def test_sympy__stats__symbolic_probability__Covariance(): from sympy.stats.symbolic_probability import Covariance from sympy.stats import Normal X = Normal('X', 0, 1) Y = Normal('Y', 0, 3) assert _test_args(Covariance(X, Y)) def test_sympy__stats__symbolic_probability__Variance(): from sympy.stats.symbolic_probability import Variance from sympy.stats import Normal X = Normal('X', 0, 1) assert _test_args(Variance(X)) def test_sympy__stats__symbolic_probability__Moment(): from sympy.stats.symbolic_probability import Moment from sympy.stats import Normal X = Normal('X', 0, 1) assert _test_args(Moment(X, 3, 2, X > 3)) def test_sympy__stats__symbolic_probability__CentralMoment(): from sympy.stats.symbolic_probability import CentralMoment from sympy.stats import Normal X = Normal('X', 0, 1) assert _test_args(CentralMoment(X, 2, X > 1)) def test_sympy__stats__frv_types__DiscreteUniformDistribution(): from sympy.stats.frv_types import DiscreteUniformDistribution from sympy.core.containers import Tuple assert _test_args(DiscreteUniformDistribution(Tuple(*list(range(6))))) def test_sympy__stats__frv_types__DieDistribution(): assert _test_args(die) def test_sympy__stats__frv_types__BernoulliDistribution(): from sympy.stats.frv_types import BernoulliDistribution assert _test_args(BernoulliDistribution(S.Half, 0, 1)) def test_sympy__stats__frv_types__BinomialDistribution(): from sympy.stats.frv_types import BinomialDistribution assert _test_args(BinomialDistribution(5, S.Half, 1, 0)) def test_sympy__stats__frv_types__BetaBinomialDistribution(): from sympy.stats.frv_types import BetaBinomialDistribution assert _test_args(BetaBinomialDistribution(5, 1, 1)) def test_sympy__stats__frv_types__HypergeometricDistribution(): from sympy.stats.frv_types import HypergeometricDistribution assert _test_args(HypergeometricDistribution(10, 5, 3)) def test_sympy__stats__frv_types__RademacherDistribution(): from sympy.stats.frv_types import RademacherDistribution assert _test_args(RademacherDistribution()) def test_sympy__stats__frv_types__IdealSolitonDistribution(): from sympy.stats.frv_types import IdealSolitonDistribution assert _test_args(IdealSolitonDistribution(10)) def test_sympy__stats__frv_types__RobustSolitonDistribution(): from sympy.stats.frv_types import RobustSolitonDistribution assert _test_args(RobustSolitonDistribution(1000, 0.5, 0.1)) def test_sympy__stats__frv__FiniteDomain(): from sympy.stats.frv import FiniteDomain assert _test_args(FiniteDomain({(x, 1), (x, 2)})) # x can be 1 or 2 def test_sympy__stats__frv__SingleFiniteDomain(): from sympy.stats.frv import SingleFiniteDomain assert _test_args(SingleFiniteDomain(x, {1, 2})) # x can be 1 or 2 def test_sympy__stats__frv__ProductFiniteDomain(): from sympy.stats.frv import SingleFiniteDomain, ProductFiniteDomain xd = SingleFiniteDomain(x, {1, 2}) yd = SingleFiniteDomain(y, {1, 2}) assert _test_args(ProductFiniteDomain(xd, yd)) def test_sympy__stats__frv__ConditionalFiniteDomain(): from sympy.stats.frv import SingleFiniteDomain, ConditionalFiniteDomain xd = SingleFiniteDomain(x, {1, 2}) assert _test_args(ConditionalFiniteDomain(xd, x > 1)) def test_sympy__stats__frv__FinitePSpace(): from sympy.stats.frv import FinitePSpace, SingleFiniteDomain xd = SingleFiniteDomain(x, {1, 2, 3, 4, 5, 6}) assert _test_args(FinitePSpace(xd, {(x, 1): S.Half, (x, 2): S.Half})) xd = SingleFiniteDomain(x, {1, 2}) assert _test_args(FinitePSpace(xd, {(x, 1): S.Half, (x, 2): S.Half})) def test_sympy__stats__frv__SingleFinitePSpace(): from sympy.stats.frv import SingleFinitePSpace from sympy.core.symbol import Symbol assert _test_args(SingleFinitePSpace(Symbol('x'), die)) def test_sympy__stats__frv__ProductFinitePSpace(): from sympy.stats.frv import SingleFinitePSpace, ProductFinitePSpace from sympy.core.symbol import Symbol xp = SingleFinitePSpace(Symbol('x'), die) yp = SingleFinitePSpace(Symbol('y'), die) assert _test_args(ProductFinitePSpace(xp, yp)) @SKIP("abstract class") def test_sympy__stats__frv__SingleFiniteDistribution(): pass @SKIP("abstract class") def test_sympy__stats__crv__ContinuousDistribution(): pass def test_sympy__stats__frv_types__FiniteDistributionHandmade(): from sympy.stats.frv_types import FiniteDistributionHandmade from sympy.core.containers import Dict assert _test_args(FiniteDistributionHandmade(Dict({1: 1}))) def test_sympy__stats__crv_types__ContinuousDistributionHandmade(): from sympy.stats.crv_types import ContinuousDistributionHandmade from sympy.core.function import Lambda from sympy.sets.sets import Interval from sympy.abc import x assert _test_args(ContinuousDistributionHandmade(Lambda(x, 2*x), Interval(0, 1))) def test_sympy__stats__drv_types__DiscreteDistributionHandmade(): from sympy.stats.drv_types import DiscreteDistributionHandmade from sympy.core.function import Lambda from sympy.sets.sets import FiniteSet from sympy.abc import x assert _test_args(DiscreteDistributionHandmade(Lambda(x, Rational(1, 10)), FiniteSet(*range(10)))) def test_sympy__stats__rv__Density(): from sympy.stats.rv import Density from sympy.stats.crv_types import Normal assert _test_args(Density(Normal('x', 0, 1))) def test_sympy__stats__crv_types__ArcsinDistribution(): from sympy.stats.crv_types import ArcsinDistribution assert _test_args(ArcsinDistribution(0, 1)) def test_sympy__stats__crv_types__BeniniDistribution(): from sympy.stats.crv_types import BeniniDistribution assert _test_args(BeniniDistribution(1, 1, 1)) def test_sympy__stats__crv_types__BetaDistribution(): from sympy.stats.crv_types import BetaDistribution assert _test_args(BetaDistribution(1, 1)) def test_sympy__stats__crv_types__BetaNoncentralDistribution(): from sympy.stats.crv_types import BetaNoncentralDistribution assert _test_args(BetaNoncentralDistribution(1, 1, 1)) def test_sympy__stats__crv_types__BetaPrimeDistribution(): from sympy.stats.crv_types import BetaPrimeDistribution assert _test_args(BetaPrimeDistribution(1, 1)) def test_sympy__stats__crv_types__BoundedParetoDistribution(): from sympy.stats.crv_types import BoundedParetoDistribution assert _test_args(BoundedParetoDistribution(1, 1, 2)) def test_sympy__stats__crv_types__CauchyDistribution(): from sympy.stats.crv_types import CauchyDistribution assert _test_args(CauchyDistribution(0, 1)) def test_sympy__stats__crv_types__ChiDistribution(): from sympy.stats.crv_types import ChiDistribution assert _test_args(ChiDistribution(1)) def test_sympy__stats__crv_types__ChiNoncentralDistribution(): from sympy.stats.crv_types import ChiNoncentralDistribution assert _test_args(ChiNoncentralDistribution(1,1)) def test_sympy__stats__crv_types__ChiSquaredDistribution(): from sympy.stats.crv_types import ChiSquaredDistribution assert _test_args(ChiSquaredDistribution(1)) def test_sympy__stats__crv_types__DagumDistribution(): from sympy.stats.crv_types import DagumDistribution assert _test_args(DagumDistribution(1, 1, 1)) def test_sympy__stats__crv_types__ExGaussianDistribution(): from sympy.stats.crv_types import ExGaussianDistribution assert _test_args(ExGaussianDistribution(1, 1, 1)) def test_sympy__stats__crv_types__ExponentialDistribution(): from sympy.stats.crv_types import ExponentialDistribution assert _test_args(ExponentialDistribution(1)) def test_sympy__stats__crv_types__ExponentialPowerDistribution(): from sympy.stats.crv_types import ExponentialPowerDistribution assert _test_args(ExponentialPowerDistribution(0, 1, 1)) def test_sympy__stats__crv_types__FDistributionDistribution(): from sympy.stats.crv_types import FDistributionDistribution assert _test_args(FDistributionDistribution(1, 1)) def test_sympy__stats__crv_types__FisherZDistribution(): from sympy.stats.crv_types import FisherZDistribution assert _test_args(FisherZDistribution(1, 1)) def test_sympy__stats__crv_types__FrechetDistribution(): from sympy.stats.crv_types import FrechetDistribution assert _test_args(FrechetDistribution(1, 1, 1)) def test_sympy__stats__crv_types__GammaInverseDistribution(): from sympy.stats.crv_types import GammaInverseDistribution assert _test_args(GammaInverseDistribution(1, 1)) def test_sympy__stats__crv_types__GammaDistribution(): from sympy.stats.crv_types import GammaDistribution assert _test_args(GammaDistribution(1, 1)) def test_sympy__stats__crv_types__GumbelDistribution(): from sympy.stats.crv_types import GumbelDistribution assert _test_args(GumbelDistribution(1, 1, False)) def test_sympy__stats__crv_types__GompertzDistribution(): from sympy.stats.crv_types import GompertzDistribution assert _test_args(GompertzDistribution(1, 1)) def test_sympy__stats__crv_types__KumaraswamyDistribution(): from sympy.stats.crv_types import KumaraswamyDistribution assert _test_args(KumaraswamyDistribution(1, 1)) def test_sympy__stats__crv_types__LaplaceDistribution(): from sympy.stats.crv_types import LaplaceDistribution assert _test_args(LaplaceDistribution(0, 1)) def test_sympy__stats__crv_types__LevyDistribution(): from sympy.stats.crv_types import LevyDistribution assert _test_args(LevyDistribution(0, 1)) def test_sympy__stats__crv_types__LogCauchyDistribution(): from sympy.stats.crv_types import LogCauchyDistribution assert _test_args(LogCauchyDistribution(0, 1)) def test_sympy__stats__crv_types__LogisticDistribution(): from sympy.stats.crv_types import LogisticDistribution assert _test_args(LogisticDistribution(0, 1)) def test_sympy__stats__crv_types__LogLogisticDistribution(): from sympy.stats.crv_types import LogLogisticDistribution assert _test_args(LogLogisticDistribution(1, 1)) def test_sympy__stats__crv_types__LogitNormalDistribution(): from sympy.stats.crv_types import LogitNormalDistribution assert _test_args(LogitNormalDistribution(0, 1)) def test_sympy__stats__crv_types__LogNormalDistribution(): from sympy.stats.crv_types import LogNormalDistribution assert _test_args(LogNormalDistribution(0, 1)) def test_sympy__stats__crv_types__LomaxDistribution(): from sympy.stats.crv_types import LomaxDistribution assert _test_args(LomaxDistribution(1, 2)) def test_sympy__stats__crv_types__MaxwellDistribution(): from sympy.stats.crv_types import MaxwellDistribution assert _test_args(MaxwellDistribution(1)) def test_sympy__stats__crv_types__MoyalDistribution(): from sympy.stats.crv_types import MoyalDistribution assert _test_args(MoyalDistribution(1,2)) def test_sympy__stats__crv_types__NakagamiDistribution(): from sympy.stats.crv_types import NakagamiDistribution assert _test_args(NakagamiDistribution(1, 1)) def test_sympy__stats__crv_types__NormalDistribution(): from sympy.stats.crv_types import NormalDistribution assert _test_args(NormalDistribution(0, 1)) def test_sympy__stats__crv_types__GaussianInverseDistribution(): from sympy.stats.crv_types import GaussianInverseDistribution assert _test_args(GaussianInverseDistribution(1, 1)) def test_sympy__stats__crv_types__ParetoDistribution(): from sympy.stats.crv_types import ParetoDistribution assert _test_args(ParetoDistribution(1, 1)) def test_sympy__stats__crv_types__PowerFunctionDistribution(): from sympy.stats.crv_types import PowerFunctionDistribution assert _test_args(PowerFunctionDistribution(2,0,1)) def test_sympy__stats__crv_types__QuadraticUDistribution(): from sympy.stats.crv_types import QuadraticUDistribution assert _test_args(QuadraticUDistribution(1, 2)) def test_sympy__stats__crv_types__RaisedCosineDistribution(): from sympy.stats.crv_types import RaisedCosineDistribution assert _test_args(RaisedCosineDistribution(1, 1)) def test_sympy__stats__crv_types__RayleighDistribution(): from sympy.stats.crv_types import RayleighDistribution assert _test_args(RayleighDistribution(1)) def test_sympy__stats__crv_types__ReciprocalDistribution(): from sympy.stats.crv_types import ReciprocalDistribution assert _test_args(ReciprocalDistribution(5, 30)) def test_sympy__stats__crv_types__ShiftedGompertzDistribution(): from sympy.stats.crv_types import ShiftedGompertzDistribution assert _test_args(ShiftedGompertzDistribution(1, 1)) def test_sympy__stats__crv_types__StudentTDistribution(): from sympy.stats.crv_types import StudentTDistribution assert _test_args(StudentTDistribution(1)) def test_sympy__stats__crv_types__TrapezoidalDistribution(): from sympy.stats.crv_types import TrapezoidalDistribution assert _test_args(TrapezoidalDistribution(1, 2, 3, 4)) def test_sympy__stats__crv_types__TriangularDistribution(): from sympy.stats.crv_types import TriangularDistribution assert _test_args(TriangularDistribution(-1, 0, 1)) def test_sympy__stats__crv_types__UniformDistribution(): from sympy.stats.crv_types import UniformDistribution assert _test_args(UniformDistribution(0, 1)) def test_sympy__stats__crv_types__UniformSumDistribution(): from sympy.stats.crv_types import UniformSumDistribution assert _test_args(UniformSumDistribution(1)) def test_sympy__stats__crv_types__VonMisesDistribution(): from sympy.stats.crv_types import VonMisesDistribution assert _test_args(VonMisesDistribution(1, 1)) def test_sympy__stats__crv_types__WeibullDistribution(): from sympy.stats.crv_types import WeibullDistribution assert _test_args(WeibullDistribution(1, 1)) def test_sympy__stats__crv_types__WignerSemicircleDistribution(): from sympy.stats.crv_types import WignerSemicircleDistribution assert _test_args(WignerSemicircleDistribution(1)) def test_sympy__stats__drv_types__GeometricDistribution(): from sympy.stats.drv_types import GeometricDistribution assert _test_args(GeometricDistribution(.5)) def test_sympy__stats__drv_types__HermiteDistribution(): from sympy.stats.drv_types import HermiteDistribution assert _test_args(HermiteDistribution(1, 2)) def test_sympy__stats__drv_types__LogarithmicDistribution(): from sympy.stats.drv_types import LogarithmicDistribution assert _test_args(LogarithmicDistribution(.5)) def test_sympy__stats__drv_types__NegativeBinomialDistribution(): from sympy.stats.drv_types import NegativeBinomialDistribution assert _test_args(NegativeBinomialDistribution(.5, .5)) def test_sympy__stats__drv_types__FlorySchulzDistribution(): from sympy.stats.drv_types import FlorySchulzDistribution assert _test_args(FlorySchulzDistribution(.5)) def test_sympy__stats__drv_types__PoissonDistribution(): from sympy.stats.drv_types import PoissonDistribution assert _test_args(PoissonDistribution(1)) def test_sympy__stats__drv_types__SkellamDistribution(): from sympy.stats.drv_types import SkellamDistribution assert _test_args(SkellamDistribution(1, 1)) def test_sympy__stats__drv_types__YuleSimonDistribution(): from sympy.stats.drv_types import YuleSimonDistribution assert _test_args(YuleSimonDistribution(.5)) def test_sympy__stats__drv_types__ZetaDistribution(): from sympy.stats.drv_types import ZetaDistribution assert _test_args(ZetaDistribution(1.5)) def test_sympy__stats__joint_rv__JointDistribution(): from sympy.stats.joint_rv import JointDistribution assert _test_args(JointDistribution(1, 2, 3, 4)) def test_sympy__stats__joint_rv_types__MultivariateNormalDistribution(): from sympy.stats.joint_rv_types import MultivariateNormalDistribution assert _test_args( MultivariateNormalDistribution([0, 1], [[1, 0],[0, 1]])) def test_sympy__stats__joint_rv_types__MultivariateLaplaceDistribution(): from sympy.stats.joint_rv_types import MultivariateLaplaceDistribution assert _test_args(MultivariateLaplaceDistribution([0, 1], [[1, 0],[0, 1]])) def test_sympy__stats__joint_rv_types__MultivariateTDistribution(): from sympy.stats.joint_rv_types import MultivariateTDistribution assert _test_args(MultivariateTDistribution([0, 1], [[1, 0],[0, 1]], 1)) def test_sympy__stats__joint_rv_types__NormalGammaDistribution(): from sympy.stats.joint_rv_types import NormalGammaDistribution assert _test_args(NormalGammaDistribution(1, 2, 3, 4)) def test_sympy__stats__joint_rv_types__GeneralizedMultivariateLogGammaDistribution(): from sympy.stats.joint_rv_types import GeneralizedMultivariateLogGammaDistribution v, l, mu = (4, [1, 2, 3, 4], [1, 2, 3, 4]) assert _test_args(GeneralizedMultivariateLogGammaDistribution(S.Half, v, l, mu)) def test_sympy__stats__joint_rv_types__MultivariateBetaDistribution(): from sympy.stats.joint_rv_types import MultivariateBetaDistribution assert _test_args(MultivariateBetaDistribution([1, 2, 3])) def test_sympy__stats__joint_rv_types__MultivariateEwensDistribution(): from sympy.stats.joint_rv_types import MultivariateEwensDistribution assert _test_args(MultivariateEwensDistribution(5, 1)) def test_sympy__stats__joint_rv_types__MultinomialDistribution(): from sympy.stats.joint_rv_types import MultinomialDistribution assert _test_args(MultinomialDistribution(5, [0.5, 0.1, 0.3])) def test_sympy__stats__joint_rv_types__NegativeMultinomialDistribution(): from sympy.stats.joint_rv_types import NegativeMultinomialDistribution assert _test_args(NegativeMultinomialDistribution(5, [0.5, 0.1, 0.3])) def test_sympy__stats__rv__RandomIndexedSymbol(): from sympy.stats.rv import RandomIndexedSymbol, pspace from sympy.stats.stochastic_process_types import DiscreteMarkovChain X = DiscreteMarkovChain("X") assert _test_args(RandomIndexedSymbol(X[0].symbol, pspace(X[0]))) def test_sympy__stats__rv__RandomMatrixSymbol(): from sympy.stats.rv import RandomMatrixSymbol from sympy.stats.random_matrix import RandomMatrixPSpace pspace = RandomMatrixPSpace('P') assert _test_args(RandomMatrixSymbol('M', 3, 3, pspace)) def test_sympy__stats__stochastic_process__StochasticPSpace(): from sympy.stats.stochastic_process import StochasticPSpace from sympy.stats.stochastic_process_types import StochasticProcess from sympy.stats.frv_types import BernoulliDistribution assert _test_args(StochasticPSpace("Y", StochasticProcess("Y", [1, 2, 3]), BernoulliDistribution(S.Half, 1, 0))) def test_sympy__stats__stochastic_process_types__StochasticProcess(): from sympy.stats.stochastic_process_types import StochasticProcess assert _test_args(StochasticProcess("Y", [1, 2, 3])) def test_sympy__stats__stochastic_process_types__MarkovProcess(): from sympy.stats.stochastic_process_types import MarkovProcess assert _test_args(MarkovProcess("Y", [1, 2, 3])) def test_sympy__stats__stochastic_process_types__DiscreteTimeStochasticProcess(): from sympy.stats.stochastic_process_types import DiscreteTimeStochasticProcess assert _test_args(DiscreteTimeStochasticProcess("Y", [1, 2, 3])) def test_sympy__stats__stochastic_process_types__ContinuousTimeStochasticProcess(): from sympy.stats.stochastic_process_types import ContinuousTimeStochasticProcess assert _test_args(ContinuousTimeStochasticProcess("Y", [1, 2, 3])) def test_sympy__stats__stochastic_process_types__TransitionMatrixOf(): from sympy.stats.stochastic_process_types import TransitionMatrixOf, DiscreteMarkovChain from sympy.matrices.expressions.matexpr import MatrixSymbol DMC = DiscreteMarkovChain("Y") assert _test_args(TransitionMatrixOf(DMC, MatrixSymbol('T', 3, 3))) def test_sympy__stats__stochastic_process_types__GeneratorMatrixOf(): from sympy.stats.stochastic_process_types import GeneratorMatrixOf, ContinuousMarkovChain from sympy.matrices.expressions.matexpr import MatrixSymbol DMC = ContinuousMarkovChain("Y") assert _test_args(GeneratorMatrixOf(DMC, MatrixSymbol('T', 3, 3))) def test_sympy__stats__stochastic_process_types__StochasticStateSpaceOf(): from sympy.stats.stochastic_process_types import StochasticStateSpaceOf, DiscreteMarkovChain DMC = DiscreteMarkovChain("Y") assert _test_args(StochasticStateSpaceOf(DMC, [0, 1, 2])) def test_sympy__stats__stochastic_process_types__DiscreteMarkovChain(): from sympy.stats.stochastic_process_types import DiscreteMarkovChain from sympy.matrices.expressions.matexpr import MatrixSymbol assert _test_args(DiscreteMarkovChain("Y", [0, 1, 2], MatrixSymbol('T', 3, 3))) def test_sympy__stats__stochastic_process_types__ContinuousMarkovChain(): from sympy.stats.stochastic_process_types import ContinuousMarkovChain from sympy.matrices.expressions.matexpr import MatrixSymbol assert _test_args(ContinuousMarkovChain("Y", [0, 1, 2], MatrixSymbol('T', 3, 3))) def test_sympy__stats__stochastic_process_types__BernoulliProcess(): from sympy.stats.stochastic_process_types import BernoulliProcess assert _test_args(BernoulliProcess("B", 0.5, 1, 0)) def test_sympy__stats__stochastic_process_types__CountingProcess(): from sympy.stats.stochastic_process_types import CountingProcess assert _test_args(CountingProcess("C")) def test_sympy__stats__stochastic_process_types__PoissonProcess(): from sympy.stats.stochastic_process_types import PoissonProcess assert _test_args(PoissonProcess("X", 2)) def test_sympy__stats__stochastic_process_types__WienerProcess(): from sympy.stats.stochastic_process_types import WienerProcess assert _test_args(WienerProcess("X")) def test_sympy__stats__stochastic_process_types__GammaProcess(): from sympy.stats.stochastic_process_types import GammaProcess assert _test_args(GammaProcess("X", 1, 2)) def test_sympy__stats__random_matrix__RandomMatrixPSpace(): from sympy.stats.random_matrix import RandomMatrixPSpace from sympy.stats.random_matrix_models import RandomMatrixEnsembleModel model = RandomMatrixEnsembleModel('R', 3) assert _test_args(RandomMatrixPSpace('P', model=model)) def test_sympy__stats__random_matrix_models__RandomMatrixEnsembleModel(): from sympy.stats.random_matrix_models import RandomMatrixEnsembleModel assert _test_args(RandomMatrixEnsembleModel('R', 3)) def test_sympy__stats__random_matrix_models__GaussianEnsembleModel(): from sympy.stats.random_matrix_models import GaussianEnsembleModel assert _test_args(GaussianEnsembleModel('G', 3)) def test_sympy__stats__random_matrix_models__GaussianUnitaryEnsembleModel(): from sympy.stats.random_matrix_models import GaussianUnitaryEnsembleModel assert _test_args(GaussianUnitaryEnsembleModel('U', 3)) def test_sympy__stats__random_matrix_models__GaussianOrthogonalEnsembleModel(): from sympy.stats.random_matrix_models import GaussianOrthogonalEnsembleModel assert _test_args(GaussianOrthogonalEnsembleModel('U', 3)) def test_sympy__stats__random_matrix_models__GaussianSymplecticEnsembleModel(): from sympy.stats.random_matrix_models import GaussianSymplecticEnsembleModel assert _test_args(GaussianSymplecticEnsembleModel('U', 3)) def test_sympy__stats__random_matrix_models__CircularEnsembleModel(): from sympy.stats.random_matrix_models import CircularEnsembleModel assert _test_args(CircularEnsembleModel('C', 3)) def test_sympy__stats__random_matrix_models__CircularUnitaryEnsembleModel(): from sympy.stats.random_matrix_models import CircularUnitaryEnsembleModel assert _test_args(CircularUnitaryEnsembleModel('U', 3)) def test_sympy__stats__random_matrix_models__CircularOrthogonalEnsembleModel(): from sympy.stats.random_matrix_models import CircularOrthogonalEnsembleModel assert _test_args(CircularOrthogonalEnsembleModel('O', 3)) def test_sympy__stats__random_matrix_models__CircularSymplecticEnsembleModel(): from sympy.stats.random_matrix_models import CircularSymplecticEnsembleModel assert _test_args(CircularSymplecticEnsembleModel('S', 3)) def test_sympy__stats__symbolic_multivariate_probability__ExpectationMatrix(): from sympy.stats import ExpectationMatrix from sympy.stats.rv import RandomMatrixSymbol assert _test_args(ExpectationMatrix(RandomMatrixSymbol('R', 2, 1))) def test_sympy__stats__symbolic_multivariate_probability__VarianceMatrix(): from sympy.stats import VarianceMatrix from sympy.stats.rv import RandomMatrixSymbol assert _test_args(VarianceMatrix(RandomMatrixSymbol('R', 3, 1))) def test_sympy__stats__symbolic_multivariate_probability__CrossCovarianceMatrix(): from sympy.stats import CrossCovarianceMatrix from sympy.stats.rv import RandomMatrixSymbol assert _test_args(CrossCovarianceMatrix(RandomMatrixSymbol('R', 3, 1), RandomMatrixSymbol('X', 3, 1))) def test_sympy__stats__matrix_distributions__MatrixPSpace(): from sympy.stats.matrix_distributions import MatrixDistribution, MatrixPSpace from sympy.matrices.dense import Matrix M = MatrixDistribution(1, Matrix([[1, 0], [0, 1]])) assert _test_args(MatrixPSpace('M', M, 2, 2)) def test_sympy__stats__matrix_distributions__MatrixDistribution(): from sympy.stats.matrix_distributions import MatrixDistribution from sympy.matrices.dense import Matrix assert _test_args(MatrixDistribution(1, Matrix([[1, 0], [0, 1]]))) def test_sympy__stats__matrix_distributions__MatrixGammaDistribution(): from sympy.stats.matrix_distributions import MatrixGammaDistribution from sympy.matrices.dense import Matrix assert _test_args(MatrixGammaDistribution(3, 4, Matrix([[1, 0], [0, 1]]))) def test_sympy__stats__matrix_distributions__WishartDistribution(): from sympy.stats.matrix_distributions import WishartDistribution from sympy.matrices.dense import Matrix assert _test_args(WishartDistribution(3, Matrix([[1, 0], [0, 1]]))) def test_sympy__stats__matrix_distributions__MatrixNormalDistribution(): from sympy.stats.matrix_distributions import MatrixNormalDistribution from sympy.matrices.expressions.matexpr import MatrixSymbol L = MatrixSymbol('L', 1, 2) S1 = MatrixSymbol('S1', 1, 1) S2 = MatrixSymbol('S2', 2, 2) assert _test_args(MatrixNormalDistribution(L, S1, S2)) def test_sympy__stats__matrix_distributions__MatrixStudentTDistribution(): from sympy.stats.matrix_distributions import MatrixStudentTDistribution from sympy.matrices.expressions.matexpr import MatrixSymbol v = symbols('v', positive=True) Omega = MatrixSymbol('Omega', 3, 3) Sigma = MatrixSymbol('Sigma', 1, 1) Location = MatrixSymbol('Location', 1, 3) assert _test_args(MatrixStudentTDistribution(v, Location, Omega, Sigma)) def test_sympy__utilities__matchpy_connector__WildDot(): from sympy.utilities.matchpy_connector import WildDot assert _test_args(WildDot("w_")) def test_sympy__utilities__matchpy_connector__WildPlus(): from sympy.utilities.matchpy_connector import WildPlus assert _test_args(WildPlus("w__")) def test_sympy__utilities__matchpy_connector__WildStar(): from sympy.utilities.matchpy_connector import WildStar assert _test_args(WildStar("w___")) def test_sympy__core__symbol__Str(): from sympy.core.symbol import Str assert _test_args(Str('t')) def test_sympy__core__symbol__Dummy(): from sympy.core.symbol import Dummy assert _test_args(Dummy('t')) def test_sympy__core__symbol__Symbol(): from sympy.core.symbol import Symbol assert _test_args(Symbol('t')) def test_sympy__core__symbol__Wild(): from sympy.core.symbol import Wild assert _test_args(Wild('x', exclude=[x])) @SKIP("abstract class") def test_sympy__functions__combinatorial__factorials__CombinatorialFunction(): pass def test_sympy__functions__combinatorial__factorials__FallingFactorial(): from sympy.functions.combinatorial.factorials import FallingFactorial assert _test_args(FallingFactorial(2, x)) def test_sympy__functions__combinatorial__factorials__MultiFactorial(): from sympy.functions.combinatorial.factorials import MultiFactorial assert _test_args(MultiFactorial(x)) def test_sympy__functions__combinatorial__factorials__RisingFactorial(): from sympy.functions.combinatorial.factorials import RisingFactorial assert _test_args(RisingFactorial(2, x)) def test_sympy__functions__combinatorial__factorials__binomial(): from sympy.functions.combinatorial.factorials import binomial assert _test_args(binomial(2, x)) def test_sympy__functions__combinatorial__factorials__subfactorial(): from sympy.functions.combinatorial.factorials import subfactorial assert _test_args(subfactorial(x)) def test_sympy__functions__combinatorial__factorials__factorial(): from sympy.functions.combinatorial.factorials import factorial assert _test_args(factorial(x)) def test_sympy__functions__combinatorial__factorials__factorial2(): from sympy.functions.combinatorial.factorials import factorial2 assert _test_args(factorial2(x)) def test_sympy__functions__combinatorial__numbers__bell(): from sympy.functions.combinatorial.numbers import bell assert _test_args(bell(x, y)) def test_sympy__functions__combinatorial__numbers__bernoulli(): from sympy.functions.combinatorial.numbers import bernoulli assert _test_args(bernoulli(x)) def test_sympy__functions__combinatorial__numbers__catalan(): from sympy.functions.combinatorial.numbers import catalan assert _test_args(catalan(x)) def test_sympy__functions__combinatorial__numbers__genocchi(): from sympy.functions.combinatorial.numbers import genocchi assert _test_args(genocchi(x)) def test_sympy__functions__combinatorial__numbers__euler(): from sympy.functions.combinatorial.numbers import euler assert _test_args(euler(x)) def test_sympy__functions__combinatorial__numbers__carmichael(): from sympy.functions.combinatorial.numbers import carmichael assert _test_args(carmichael(x)) def test_sympy__functions__combinatorial__numbers__motzkin(): from sympy.functions.combinatorial.numbers import motzkin assert _test_args(motzkin(5)) def test_sympy__functions__combinatorial__numbers__fibonacci(): from sympy.functions.combinatorial.numbers import fibonacci assert _test_args(fibonacci(x)) def test_sympy__functions__combinatorial__numbers__tribonacci(): from sympy.functions.combinatorial.numbers import tribonacci assert _test_args(tribonacci(x)) def test_sympy__functions__combinatorial__numbers__harmonic(): from sympy.functions.combinatorial.numbers import harmonic assert _test_args(harmonic(x, 2)) def test_sympy__functions__combinatorial__numbers__lucas(): from sympy.functions.combinatorial.numbers import lucas assert _test_args(lucas(x)) def test_sympy__functions__combinatorial__numbers__partition(): from sympy.core.symbol import Symbol from sympy.functions.combinatorial.numbers import partition assert _test_args(partition(Symbol('a', integer=True))) def test_sympy__functions__elementary__complexes__Abs(): from sympy.functions.elementary.complexes import Abs assert _test_args(Abs(x)) def test_sympy__functions__elementary__complexes__adjoint(): from sympy.functions.elementary.complexes import adjoint assert _test_args(adjoint(x)) def test_sympy__functions__elementary__complexes__arg(): from sympy.functions.elementary.complexes import arg assert _test_args(arg(x)) def test_sympy__functions__elementary__complexes__conjugate(): from sympy.functions.elementary.complexes import conjugate assert _test_args(conjugate(x)) def test_sympy__functions__elementary__complexes__im(): from sympy.functions.elementary.complexes import im assert _test_args(im(x)) def test_sympy__functions__elementary__complexes__re(): from sympy.functions.elementary.complexes import re assert _test_args(re(x)) def test_sympy__functions__elementary__complexes__sign(): from sympy.functions.elementary.complexes import sign assert _test_args(sign(x)) def test_sympy__functions__elementary__complexes__polar_lift(): from sympy.functions.elementary.complexes import polar_lift assert _test_args(polar_lift(x)) def test_sympy__functions__elementary__complexes__periodic_argument(): from sympy.functions.elementary.complexes import periodic_argument assert _test_args(periodic_argument(x, y)) def test_sympy__functions__elementary__complexes__principal_branch(): from sympy.functions.elementary.complexes import principal_branch assert _test_args(principal_branch(x, y)) def test_sympy__functions__elementary__complexes__transpose(): from sympy.functions.elementary.complexes import transpose assert _test_args(transpose(x)) def test_sympy__functions__elementary__exponential__LambertW(): from sympy.functions.elementary.exponential import LambertW assert _test_args(LambertW(2)) @SKIP("abstract class") def test_sympy__functions__elementary__exponential__ExpBase(): pass def test_sympy__functions__elementary__exponential__exp(): from sympy.functions.elementary.exponential import exp assert _test_args(exp(2)) def test_sympy__functions__elementary__exponential__exp_polar(): from sympy.functions.elementary.exponential import exp_polar assert _test_args(exp_polar(2)) def test_sympy__functions__elementary__exponential__log(): from sympy.functions.elementary.exponential import log assert _test_args(log(2)) @SKIP("abstract class") def test_sympy__functions__elementary__hyperbolic__HyperbolicFunction(): pass @SKIP("abstract class") def test_sympy__functions__elementary__hyperbolic__ReciprocalHyperbolicFunction(): pass @SKIP("abstract class") def test_sympy__functions__elementary__hyperbolic__InverseHyperbolicFunction(): pass def test_sympy__functions__elementary__hyperbolic__acosh(): from sympy.functions.elementary.hyperbolic import acosh assert _test_args(acosh(2)) def test_sympy__functions__elementary__hyperbolic__acoth(): from sympy.functions.elementary.hyperbolic import acoth assert _test_args(acoth(2)) def test_sympy__functions__elementary__hyperbolic__asinh(): from sympy.functions.elementary.hyperbolic import asinh assert _test_args(asinh(2)) def test_sympy__functions__elementary__hyperbolic__atanh(): from sympy.functions.elementary.hyperbolic import atanh assert _test_args(atanh(2)) def test_sympy__functions__elementary__hyperbolic__asech(): from sympy.functions.elementary.hyperbolic import asech assert _test_args(asech(x)) def test_sympy__functions__elementary__hyperbolic__acsch(): from sympy.functions.elementary.hyperbolic import acsch assert _test_args(acsch(x)) def test_sympy__functions__elementary__hyperbolic__cosh(): from sympy.functions.elementary.hyperbolic import cosh assert _test_args(cosh(2)) def test_sympy__functions__elementary__hyperbolic__coth(): from sympy.functions.elementary.hyperbolic import coth assert _test_args(coth(2)) def test_sympy__functions__elementary__hyperbolic__csch(): from sympy.functions.elementary.hyperbolic import csch assert _test_args(csch(2)) def test_sympy__functions__elementary__hyperbolic__sech(): from sympy.functions.elementary.hyperbolic import sech assert _test_args(sech(2)) def test_sympy__functions__elementary__hyperbolic__sinh(): from sympy.functions.elementary.hyperbolic import sinh assert _test_args(sinh(2)) def test_sympy__functions__elementary__hyperbolic__tanh(): from sympy.functions.elementary.hyperbolic import tanh assert _test_args(tanh(2)) @SKIP("abstract class") def test_sympy__functions__elementary__integers__RoundFunction(): pass def test_sympy__functions__elementary__integers__ceiling(): from sympy.functions.elementary.integers import ceiling assert _test_args(ceiling(x)) def test_sympy__functions__elementary__integers__floor(): from sympy.functions.elementary.integers import floor assert _test_args(floor(x)) def test_sympy__functions__elementary__integers__frac(): from sympy.functions.elementary.integers import frac assert _test_args(frac(x)) def test_sympy__functions__elementary__miscellaneous__IdentityFunction(): from sympy.functions.elementary.miscellaneous import IdentityFunction assert _test_args(IdentityFunction()) def test_sympy__functions__elementary__miscellaneous__Max(): from sympy.functions.elementary.miscellaneous import Max assert _test_args(Max(x, 2)) def test_sympy__functions__elementary__miscellaneous__Min(): from sympy.functions.elementary.miscellaneous import Min assert _test_args(Min(x, 2)) @SKIP("abstract class") def test_sympy__functions__elementary__miscellaneous__MinMaxBase(): pass def test_sympy__functions__elementary__miscellaneous__Rem(): from sympy.functions.elementary.miscellaneous import Rem assert _test_args(Rem(x, 2)) def test_sympy__functions__elementary__piecewise__ExprCondPair(): from sympy.functions.elementary.piecewise import ExprCondPair assert _test_args(ExprCondPair(1, True)) def test_sympy__functions__elementary__piecewise__Piecewise(): from sympy.functions.elementary.piecewise import Piecewise assert _test_args(Piecewise((1, x >= 0), (0, True))) @SKIP("abstract class") def test_sympy__functions__elementary__trigonometric__TrigonometricFunction(): pass @SKIP("abstract class") def test_sympy__functions__elementary__trigonometric__ReciprocalTrigonometricFunction(): pass @SKIP("abstract class") def test_sympy__functions__elementary__trigonometric__InverseTrigonometricFunction(): pass def test_sympy__functions__elementary__trigonometric__acos(): from sympy.functions.elementary.trigonometric import acos assert _test_args(acos(2)) def test_sympy__functions__elementary__trigonometric__acot(): from sympy.functions.elementary.trigonometric import acot assert _test_args(acot(2)) def test_sympy__functions__elementary__trigonometric__asin(): from sympy.functions.elementary.trigonometric import asin assert _test_args(asin(2)) def test_sympy__functions__elementary__trigonometric__asec(): from sympy.functions.elementary.trigonometric import asec assert _test_args(asec(x)) def test_sympy__functions__elementary__trigonometric__acsc(): from sympy.functions.elementary.trigonometric import acsc assert _test_args(acsc(x)) def test_sympy__functions__elementary__trigonometric__atan(): from sympy.functions.elementary.trigonometric import atan assert _test_args(atan(2)) def test_sympy__functions__elementary__trigonometric__atan2(): from sympy.functions.elementary.trigonometric import atan2 assert _test_args(atan2(2, 3)) def test_sympy__functions__elementary__trigonometric__cos(): from sympy.functions.elementary.trigonometric import cos assert _test_args(cos(2)) def test_sympy__functions__elementary__trigonometric__csc(): from sympy.functions.elementary.trigonometric import csc assert _test_args(csc(2)) def test_sympy__functions__elementary__trigonometric__cot(): from sympy.functions.elementary.trigonometric import cot assert _test_args(cot(2)) def test_sympy__functions__elementary__trigonometric__sin(): assert _test_args(sin(2)) def test_sympy__functions__elementary__trigonometric__sinc(): from sympy.functions.elementary.trigonometric import sinc assert _test_args(sinc(2)) def test_sympy__functions__elementary__trigonometric__sec(): from sympy.functions.elementary.trigonometric import sec assert _test_args(sec(2)) def test_sympy__functions__elementary__trigonometric__tan(): from sympy.functions.elementary.trigonometric import tan assert _test_args(tan(2)) @SKIP("abstract class") def test_sympy__functions__special__bessel__BesselBase(): pass @SKIP("abstract class") def test_sympy__functions__special__bessel__SphericalBesselBase(): pass @SKIP("abstract class") def test_sympy__functions__special__bessel__SphericalHankelBase(): pass def test_sympy__functions__special__bessel__besseli(): from sympy.functions.special.bessel import besseli assert _test_args(besseli(x, 1)) def test_sympy__functions__special__bessel__besselj(): from sympy.functions.special.bessel import besselj assert _test_args(besselj(x, 1)) def test_sympy__functions__special__bessel__besselk(): from sympy.functions.special.bessel import besselk assert _test_args(besselk(x, 1)) def test_sympy__functions__special__bessel__bessely(): from sympy.functions.special.bessel import bessely assert _test_args(bessely(x, 1)) def test_sympy__functions__special__bessel__hankel1(): from sympy.functions.special.bessel import hankel1 assert _test_args(hankel1(x, 1)) def test_sympy__functions__special__bessel__hankel2(): from sympy.functions.special.bessel import hankel2 assert _test_args(hankel2(x, 1)) def test_sympy__functions__special__bessel__jn(): from sympy.functions.special.bessel import jn assert _test_args(jn(0, x)) def test_sympy__functions__special__bessel__yn(): from sympy.functions.special.bessel import yn assert _test_args(yn(0, x)) def test_sympy__functions__special__bessel__hn1(): from sympy.functions.special.bessel import hn1 assert _test_args(hn1(0, x)) def test_sympy__functions__special__bessel__hn2(): from sympy.functions.special.bessel import hn2 assert _test_args(hn2(0, x)) def test_sympy__functions__special__bessel__AiryBase(): pass def test_sympy__functions__special__bessel__airyai(): from sympy.functions.special.bessel import airyai assert _test_args(airyai(2)) def test_sympy__functions__special__bessel__airybi(): from sympy.functions.special.bessel import airybi assert _test_args(airybi(2)) def test_sympy__functions__special__bessel__airyaiprime(): from sympy.functions.special.bessel import airyaiprime assert _test_args(airyaiprime(2)) def test_sympy__functions__special__bessel__airybiprime(): from sympy.functions.special.bessel import airybiprime assert _test_args(airybiprime(2)) def test_sympy__functions__special__bessel__marcumq(): from sympy.functions.special.bessel import marcumq assert _test_args(marcumq(x, y, z)) def test_sympy__functions__special__elliptic_integrals__elliptic_k(): from sympy.functions.special.elliptic_integrals import elliptic_k as K assert _test_args(K(x)) def test_sympy__functions__special__elliptic_integrals__elliptic_f(): from sympy.functions.special.elliptic_integrals import elliptic_f as F assert _test_args(F(x, y)) def test_sympy__functions__special__elliptic_integrals__elliptic_e(): from sympy.functions.special.elliptic_integrals import elliptic_e as E assert _test_args(E(x)) assert _test_args(E(x, y)) def test_sympy__functions__special__elliptic_integrals__elliptic_pi(): from sympy.functions.special.elliptic_integrals import elliptic_pi as P assert _test_args(P(x, y)) assert _test_args(P(x, y, z)) def test_sympy__functions__special__delta_functions__DiracDelta(): from sympy.functions.special.delta_functions import DiracDelta assert _test_args(DiracDelta(x, 1)) def test_sympy__functions__special__singularity_functions__SingularityFunction(): from sympy.functions.special.singularity_functions import SingularityFunction assert _test_args(SingularityFunction(x, y, z)) def test_sympy__functions__special__delta_functions__Heaviside(): from sympy.functions.special.delta_functions import Heaviside assert _test_args(Heaviside(x)) def test_sympy__functions__special__error_functions__erf(): from sympy.functions.special.error_functions import erf assert _test_args(erf(2)) def test_sympy__functions__special__error_functions__erfc(): from sympy.functions.special.error_functions import erfc assert _test_args(erfc(2)) def test_sympy__functions__special__error_functions__erfi(): from sympy.functions.special.error_functions import erfi assert _test_args(erfi(2)) def test_sympy__functions__special__error_functions__erf2(): from sympy.functions.special.error_functions import erf2 assert _test_args(erf2(2, 3)) def test_sympy__functions__special__error_functions__erfinv(): from sympy.functions.special.error_functions import erfinv assert _test_args(erfinv(2)) def test_sympy__functions__special__error_functions__erfcinv(): from sympy.functions.special.error_functions import erfcinv assert _test_args(erfcinv(2)) def test_sympy__functions__special__error_functions__erf2inv(): from sympy.functions.special.error_functions import erf2inv assert _test_args(erf2inv(2, 3)) @SKIP("abstract class") def test_sympy__functions__special__error_functions__FresnelIntegral(): pass def test_sympy__functions__special__error_functions__fresnels(): from sympy.functions.special.error_functions import fresnels assert _test_args(fresnels(2)) def test_sympy__functions__special__error_functions__fresnelc(): from sympy.functions.special.error_functions import fresnelc assert _test_args(fresnelc(2)) def test_sympy__functions__special__error_functions__erfs(): from sympy.functions.special.error_functions import _erfs assert _test_args(_erfs(2)) def test_sympy__functions__special__error_functions__Ei(): from sympy.functions.special.error_functions import Ei assert _test_args(Ei(2)) def test_sympy__functions__special__error_functions__li(): from sympy.functions.special.error_functions import li assert _test_args(li(2)) def test_sympy__functions__special__error_functions__Li(): from sympy.functions.special.error_functions import Li assert _test_args(Li(5)) @SKIP("abstract class") def test_sympy__functions__special__error_functions__TrigonometricIntegral(): pass def test_sympy__functions__special__error_functions__Si(): from sympy.functions.special.error_functions import Si assert _test_args(Si(2)) def test_sympy__functions__special__error_functions__Ci(): from sympy.functions.special.error_functions import Ci assert _test_args(Ci(2)) def test_sympy__functions__special__error_functions__Shi(): from sympy.functions.special.error_functions import Shi assert _test_args(Shi(2)) def test_sympy__functions__special__error_functions__Chi(): from sympy.functions.special.error_functions import Chi assert _test_args(Chi(2)) def test_sympy__functions__special__error_functions__expint(): from sympy.functions.special.error_functions import expint assert _test_args(expint(y, x)) def test_sympy__functions__special__gamma_functions__gamma(): from sympy.functions.special.gamma_functions import gamma assert _test_args(gamma(x)) def test_sympy__functions__special__gamma_functions__loggamma(): from sympy.functions.special.gamma_functions import loggamma assert _test_args(loggamma(x)) def test_sympy__functions__special__gamma_functions__lowergamma(): from sympy.functions.special.gamma_functions import lowergamma assert _test_args(lowergamma(x, 2)) def test_sympy__functions__special__gamma_functions__polygamma(): from sympy.functions.special.gamma_functions import polygamma assert _test_args(polygamma(x, 2)) def test_sympy__functions__special__gamma_functions__digamma(): from sympy.functions.special.gamma_functions import digamma assert _test_args(digamma(x)) def test_sympy__functions__special__gamma_functions__trigamma(): from sympy.functions.special.gamma_functions import trigamma assert _test_args(trigamma(x)) def test_sympy__functions__special__gamma_functions__uppergamma(): from sympy.functions.special.gamma_functions import uppergamma assert _test_args(uppergamma(x, 2)) def test_sympy__functions__special__gamma_functions__multigamma(): from sympy.functions.special.gamma_functions import multigamma assert _test_args(multigamma(x, 1)) def test_sympy__functions__special__beta_functions__beta(): from sympy.functions.special.beta_functions import beta assert _test_args(beta(x)) assert _test_args(beta(x, x)) def test_sympy__functions__special__beta_functions__betainc(): from sympy.functions.special.beta_functions import betainc assert _test_args(betainc(a, b, x, y)) def test_sympy__functions__special__beta_functions__betainc_regularized(): from sympy.functions.special.beta_functions import betainc_regularized assert _test_args(betainc_regularized(a, b, x, y)) def test_sympy__functions__special__mathieu_functions__MathieuBase(): pass def test_sympy__functions__special__mathieu_functions__mathieus(): from sympy.functions.special.mathieu_functions import mathieus assert _test_args(mathieus(1, 1, 1)) def test_sympy__functions__special__mathieu_functions__mathieuc(): from sympy.functions.special.mathieu_functions import mathieuc assert _test_args(mathieuc(1, 1, 1)) def test_sympy__functions__special__mathieu_functions__mathieusprime(): from sympy.functions.special.mathieu_functions import mathieusprime assert _test_args(mathieusprime(1, 1, 1)) def test_sympy__functions__special__mathieu_functions__mathieucprime(): from sympy.functions.special.mathieu_functions import mathieucprime assert _test_args(mathieucprime(1, 1, 1)) @SKIP("abstract class") def test_sympy__functions__special__hyper__TupleParametersBase(): pass @SKIP("abstract class") def test_sympy__functions__special__hyper__TupleArg(): pass def test_sympy__functions__special__hyper__hyper(): from sympy.functions.special.hyper import hyper assert _test_args(hyper([1, 2, 3], [4, 5], x)) def test_sympy__functions__special__hyper__meijerg(): from sympy.functions.special.hyper import meijerg assert _test_args(meijerg([1, 2, 3], [4, 5], [6], [], x)) @SKIP("abstract class") def test_sympy__functions__special__hyper__HyperRep(): pass def test_sympy__functions__special__hyper__HyperRep_power1(): from sympy.functions.special.hyper import HyperRep_power1 assert _test_args(HyperRep_power1(x, y)) def test_sympy__functions__special__hyper__HyperRep_power2(): from sympy.functions.special.hyper import HyperRep_power2 assert _test_args(HyperRep_power2(x, y)) def test_sympy__functions__special__hyper__HyperRep_log1(): from sympy.functions.special.hyper import HyperRep_log1 assert _test_args(HyperRep_log1(x)) def test_sympy__functions__special__hyper__HyperRep_atanh(): from sympy.functions.special.hyper import HyperRep_atanh assert _test_args(HyperRep_atanh(x)) def test_sympy__functions__special__hyper__HyperRep_asin1(): from sympy.functions.special.hyper import HyperRep_asin1 assert _test_args(HyperRep_asin1(x)) def test_sympy__functions__special__hyper__HyperRep_asin2(): from sympy.functions.special.hyper import HyperRep_asin2 assert _test_args(HyperRep_asin2(x)) def test_sympy__functions__special__hyper__HyperRep_sqrts1(): from sympy.functions.special.hyper import HyperRep_sqrts1 assert _test_args(HyperRep_sqrts1(x, y)) def test_sympy__functions__special__hyper__HyperRep_sqrts2(): from sympy.functions.special.hyper import HyperRep_sqrts2 assert _test_args(HyperRep_sqrts2(x, y)) def test_sympy__functions__special__hyper__HyperRep_log2(): from sympy.functions.special.hyper import HyperRep_log2 assert _test_args(HyperRep_log2(x)) def test_sympy__functions__special__hyper__HyperRep_cosasin(): from sympy.functions.special.hyper import HyperRep_cosasin assert _test_args(HyperRep_cosasin(x, y)) def test_sympy__functions__special__hyper__HyperRep_sinasin(): from sympy.functions.special.hyper import HyperRep_sinasin assert _test_args(HyperRep_sinasin(x, y)) def test_sympy__functions__special__hyper__appellf1(): from sympy.functions.special.hyper import appellf1 a, b1, b2, c, x, y = symbols('a b1 b2 c x y') assert _test_args(appellf1(a, b1, b2, c, x, y)) @SKIP("abstract class") def test_sympy__functions__special__polynomials__OrthogonalPolynomial(): pass def test_sympy__functions__special__polynomials__jacobi(): from sympy.functions.special.polynomials import jacobi assert _test_args(jacobi(x, y, 2, 2)) def test_sympy__functions__special__polynomials__gegenbauer(): from sympy.functions.special.polynomials import gegenbauer assert _test_args(gegenbauer(x, 2, 2)) def test_sympy__functions__special__polynomials__chebyshevt(): from sympy.functions.special.polynomials import chebyshevt assert _test_args(chebyshevt(x, 2)) def test_sympy__functions__special__polynomials__chebyshevt_root(): from sympy.functions.special.polynomials import chebyshevt_root assert _test_args(chebyshevt_root(3, 2)) def test_sympy__functions__special__polynomials__chebyshevu(): from sympy.functions.special.polynomials import chebyshevu assert _test_args(chebyshevu(x, 2)) def test_sympy__functions__special__polynomials__chebyshevu_root(): from sympy.functions.special.polynomials import chebyshevu_root assert _test_args(chebyshevu_root(3, 2)) def test_sympy__functions__special__polynomials__hermite(): from sympy.functions.special.polynomials import hermite assert _test_args(hermite(x, 2)) def test_sympy__functions__special__polynomials__legendre(): from sympy.functions.special.polynomials import legendre assert _test_args(legendre(x, 2)) def test_sympy__functions__special__polynomials__assoc_legendre(): from sympy.functions.special.polynomials import assoc_legendre assert _test_args(assoc_legendre(x, 0, y)) def test_sympy__functions__special__polynomials__laguerre(): from sympy.functions.special.polynomials import laguerre assert _test_args(laguerre(x, 2)) def test_sympy__functions__special__polynomials__assoc_laguerre(): from sympy.functions.special.polynomials import assoc_laguerre assert _test_args(assoc_laguerre(x, 0, y)) def test_sympy__functions__special__spherical_harmonics__Ynm(): from sympy.functions.special.spherical_harmonics import Ynm assert _test_args(Ynm(1, 1, x, y)) def test_sympy__functions__special__spherical_harmonics__Znm(): from sympy.functions.special.spherical_harmonics import Znm assert _test_args(Znm(x, y, 1, 1)) def test_sympy__functions__special__tensor_functions__LeviCivita(): from sympy.functions.special.tensor_functions import LeviCivita assert _test_args(LeviCivita(x, y, 2)) def test_sympy__functions__special__tensor_functions__KroneckerDelta(): from sympy.functions.special.tensor_functions import KroneckerDelta assert _test_args(KroneckerDelta(x, y)) def test_sympy__functions__special__zeta_functions__dirichlet_eta(): from sympy.functions.special.zeta_functions import dirichlet_eta assert _test_args(dirichlet_eta(x)) def test_sympy__functions__special__zeta_functions__riemann_xi(): from sympy.functions.special.zeta_functions import riemann_xi assert _test_args(riemann_xi(x)) def test_sympy__functions__special__zeta_functions__zeta(): from sympy.functions.special.zeta_functions import zeta assert _test_args(zeta(101)) def test_sympy__functions__special__zeta_functions__lerchphi(): from sympy.functions.special.zeta_functions import lerchphi assert _test_args(lerchphi(x, y, z)) def test_sympy__functions__special__zeta_functions__polylog(): from sympy.functions.special.zeta_functions import polylog assert _test_args(polylog(x, y)) def test_sympy__functions__special__zeta_functions__stieltjes(): from sympy.functions.special.zeta_functions import stieltjes assert _test_args(stieltjes(x, y)) def test_sympy__integrals__integrals__Integral(): from sympy.integrals.integrals import Integral assert _test_args(Integral(2, (x, 0, 1))) def test_sympy__integrals__risch__NonElementaryIntegral(): from sympy.integrals.risch import NonElementaryIntegral assert _test_args(NonElementaryIntegral(exp(-x**2), x)) @SKIP("abstract class") def test_sympy__integrals__transforms__IntegralTransform(): pass def test_sympy__integrals__transforms__MellinTransform(): from sympy.integrals.transforms import MellinTransform assert _test_args(MellinTransform(2, x, y)) def test_sympy__integrals__transforms__InverseMellinTransform(): from sympy.integrals.transforms import InverseMellinTransform assert _test_args(InverseMellinTransform(2, x, y, 0, 1)) def test_sympy__integrals__transforms__LaplaceTransform(): from sympy.integrals.transforms import LaplaceTransform assert _test_args(LaplaceTransform(2, x, y)) def test_sympy__integrals__transforms__InverseLaplaceTransform(): from sympy.integrals.transforms import InverseLaplaceTransform assert _test_args(InverseLaplaceTransform(2, x, y, 0)) @SKIP("abstract class") def test_sympy__integrals__transforms__FourierTypeTransform(): pass def test_sympy__integrals__transforms__InverseFourierTransform(): from sympy.integrals.transforms import InverseFourierTransform assert _test_args(InverseFourierTransform(2, x, y)) def test_sympy__integrals__transforms__FourierTransform(): from sympy.integrals.transforms import FourierTransform assert _test_args(FourierTransform(2, x, y)) @SKIP("abstract class") def test_sympy__integrals__transforms__SineCosineTypeTransform(): pass def test_sympy__integrals__transforms__InverseSineTransform(): from sympy.integrals.transforms import InverseSineTransform assert _test_args(InverseSineTransform(2, x, y)) def test_sympy__integrals__transforms__SineTransform(): from sympy.integrals.transforms import SineTransform assert _test_args(SineTransform(2, x, y)) def test_sympy__integrals__transforms__InverseCosineTransform(): from sympy.integrals.transforms import InverseCosineTransform assert _test_args(InverseCosineTransform(2, x, y)) def test_sympy__integrals__transforms__CosineTransform(): from sympy.integrals.transforms import CosineTransform assert _test_args(CosineTransform(2, x, y)) @SKIP("abstract class") def test_sympy__integrals__transforms__HankelTypeTransform(): pass def test_sympy__integrals__transforms__InverseHankelTransform(): from sympy.integrals.transforms import InverseHankelTransform assert _test_args(InverseHankelTransform(2, x, y, 0)) def test_sympy__integrals__transforms__HankelTransform(): from sympy.integrals.transforms import HankelTransform assert _test_args(HankelTransform(2, x, y, 0)) def test_sympy__liealgebras__cartan_type__Standard_Cartan(): from sympy.liealgebras.cartan_type import Standard_Cartan assert _test_args(Standard_Cartan("A", 2)) def test_sympy__liealgebras__weyl_group__WeylGroup(): from sympy.liealgebras.weyl_group import WeylGroup assert _test_args(WeylGroup("B4")) def test_sympy__liealgebras__root_system__RootSystem(): from sympy.liealgebras.root_system import RootSystem assert _test_args(RootSystem("A2")) def test_sympy__liealgebras__type_a__TypeA(): from sympy.liealgebras.type_a import TypeA assert _test_args(TypeA(2)) def test_sympy__liealgebras__type_b__TypeB(): from sympy.liealgebras.type_b import TypeB assert _test_args(TypeB(4)) def test_sympy__liealgebras__type_c__TypeC(): from sympy.liealgebras.type_c import TypeC assert _test_args(TypeC(4)) def test_sympy__liealgebras__type_d__TypeD(): from sympy.liealgebras.type_d import TypeD assert _test_args(TypeD(4)) def test_sympy__liealgebras__type_e__TypeE(): from sympy.liealgebras.type_e import TypeE assert _test_args(TypeE(6)) def test_sympy__liealgebras__type_f__TypeF(): from sympy.liealgebras.type_f import TypeF assert _test_args(TypeF(4)) def test_sympy__liealgebras__type_g__TypeG(): from sympy.liealgebras.type_g import TypeG assert _test_args(TypeG(2)) def test_sympy__logic__boolalg__And(): from sympy.logic.boolalg import And assert _test_args(And(x, y, 1)) @SKIP("abstract class") def test_sympy__logic__boolalg__Boolean(): pass def test_sympy__logic__boolalg__BooleanFunction(): from sympy.logic.boolalg import BooleanFunction assert _test_args(BooleanFunction(1, 2, 3)) @SKIP("abstract class") def test_sympy__logic__boolalg__BooleanAtom(): pass def test_sympy__logic__boolalg__BooleanTrue(): from sympy.logic.boolalg import true assert _test_args(true) def test_sympy__logic__boolalg__BooleanFalse(): from sympy.logic.boolalg import false assert _test_args(false) def test_sympy__logic__boolalg__Equivalent(): from sympy.logic.boolalg import Equivalent assert _test_args(Equivalent(x, 2)) def test_sympy__logic__boolalg__ITE(): from sympy.logic.boolalg import ITE assert _test_args(ITE(x, y, 1)) def test_sympy__logic__boolalg__Implies(): from sympy.logic.boolalg import Implies assert _test_args(Implies(x, y)) def test_sympy__logic__boolalg__Nand(): from sympy.logic.boolalg import Nand assert _test_args(Nand(x, y, 1)) def test_sympy__logic__boolalg__Nor(): from sympy.logic.boolalg import Nor assert _test_args(Nor(x, y)) def test_sympy__logic__boolalg__Not(): from sympy.logic.boolalg import Not assert _test_args(Not(x)) def test_sympy__logic__boolalg__Or(): from sympy.logic.boolalg import Or assert _test_args(Or(x, y)) def test_sympy__logic__boolalg__Xor(): from sympy.logic.boolalg import Xor assert _test_args(Xor(x, y, 2)) def test_sympy__logic__boolalg__Xnor(): from sympy.logic.boolalg import Xnor assert _test_args(Xnor(x, y, 2)) def test_sympy__logic__boolalg__Exclusive(): from sympy.logic.boolalg import Exclusive assert _test_args(Exclusive(x, y, z)) def test_sympy__matrices__matrices__DeferredVector(): from sympy.matrices.matrices import DeferredVector assert _test_args(DeferredVector("X")) @SKIP("abstract class") def test_sympy__matrices__expressions__matexpr__MatrixBase(): pass @SKIP("abstract class") def test_sympy__matrices__immutable__ImmutableRepMatrix(): pass def test_sympy__matrices__immutable__ImmutableDenseMatrix(): from sympy.matrices.immutable import ImmutableDenseMatrix m = ImmutableDenseMatrix([[1, 2], [3, 4]]) assert _test_args(m) assert _test_args(Basic(*list(m))) m = ImmutableDenseMatrix(1, 1, [1]) assert _test_args(m) assert _test_args(Basic(*list(m))) m = ImmutableDenseMatrix(2, 2, lambda i, j: 1) assert m[0, 0] is S.One m = ImmutableDenseMatrix(2, 2, lambda i, j: 1/(1 + i) + 1/(1 + j)) assert m[1, 1] is S.One # true div. will give 1.0 if i,j not sympified assert _test_args(m) assert _test_args(Basic(*list(m))) def test_sympy__matrices__immutable__ImmutableSparseMatrix(): from sympy.matrices.immutable import ImmutableSparseMatrix m = ImmutableSparseMatrix([[1, 2], [3, 4]]) assert _test_args(m) assert _test_args(Basic(*list(m))) m = ImmutableSparseMatrix(1, 1, {(0, 0): 1}) assert _test_args(m) assert _test_args(Basic(*list(m))) m = ImmutableSparseMatrix(1, 1, [1]) assert _test_args(m) assert _test_args(Basic(*list(m))) m = ImmutableSparseMatrix(2, 2, lambda i, j: 1) assert m[0, 0] is S.One m = ImmutableSparseMatrix(2, 2, lambda i, j: 1/(1 + i) + 1/(1 + j)) assert m[1, 1] is S.One # true div. will give 1.0 if i,j not sympified assert _test_args(m) assert _test_args(Basic(*list(m))) def test_sympy__matrices__expressions__slice__MatrixSlice(): from sympy.matrices.expressions.slice import MatrixSlice from sympy.matrices.expressions import MatrixSymbol X = MatrixSymbol('X', 4, 4) assert _test_args(MatrixSlice(X, (0, 2), (0, 2))) def test_sympy__matrices__expressions__applyfunc__ElementwiseApplyFunction(): from sympy.matrices.expressions.applyfunc import ElementwiseApplyFunction from sympy.matrices.expressions import MatrixSymbol X = MatrixSymbol("X", x, x) func = Lambda(x, x**2) assert _test_args(ElementwiseApplyFunction(func, X)) def test_sympy__matrices__expressions__blockmatrix__BlockDiagMatrix(): from sympy.matrices.expressions.blockmatrix import BlockDiagMatrix from sympy.matrices.expressions import MatrixSymbol X = MatrixSymbol('X', x, x) Y = MatrixSymbol('Y', y, y) assert _test_args(BlockDiagMatrix(X, Y)) def test_sympy__matrices__expressions__blockmatrix__BlockMatrix(): from sympy.matrices.expressions.blockmatrix import BlockMatrix from sympy.matrices.expressions import MatrixSymbol, ZeroMatrix X = MatrixSymbol('X', x, x) Y = MatrixSymbol('Y', y, y) Z = MatrixSymbol('Z', x, y) O = ZeroMatrix(y, x) assert _test_args(BlockMatrix([[X, Z], [O, Y]])) def test_sympy__matrices__expressions__inverse__Inverse(): from sympy.matrices.expressions.inverse import Inverse from sympy.matrices.expressions import MatrixSymbol assert _test_args(Inverse(MatrixSymbol('A', 3, 3))) def test_sympy__matrices__expressions__matadd__MatAdd(): from sympy.matrices.expressions.matadd import MatAdd from sympy.matrices.expressions import MatrixSymbol X = MatrixSymbol('X', x, y) Y = MatrixSymbol('Y', x, y) assert _test_args(MatAdd(X, Y)) @SKIP("abstract class") def test_sympy__matrices__expressions__matexpr__MatrixExpr(): pass def test_sympy__matrices__expressions__matexpr__MatrixElement(): from sympy.matrices.expressions.matexpr import MatrixSymbol, MatrixElement from sympy.core.singleton import S assert _test_args(MatrixElement(MatrixSymbol('A', 3, 5), S(2), S(3))) def test_sympy__matrices__expressions__matexpr__MatrixSymbol(): from sympy.matrices.expressions.matexpr import MatrixSymbol assert _test_args(MatrixSymbol('A', 3, 5)) def test_sympy__matrices__expressions__special__OneMatrix(): from sympy.matrices.expressions.special import OneMatrix assert _test_args(OneMatrix(3, 5)) def test_sympy__matrices__expressions__special__ZeroMatrix(): from sympy.matrices.expressions.special import ZeroMatrix assert _test_args(ZeroMatrix(3, 5)) def test_sympy__matrices__expressions__special__GenericZeroMatrix(): from sympy.matrices.expressions.special import GenericZeroMatrix assert _test_args(GenericZeroMatrix()) def test_sympy__matrices__expressions__special__Identity(): from sympy.matrices.expressions.special import Identity assert _test_args(Identity(3)) def test_sympy__matrices__expressions__special__GenericIdentity(): from sympy.matrices.expressions.special import GenericIdentity assert _test_args(GenericIdentity()) def test_sympy__matrices__expressions__sets__MatrixSet(): from sympy.matrices.expressions.sets import MatrixSet from sympy.core.singleton import S assert _test_args(MatrixSet(2, 2, S.Reals)) def test_sympy__matrices__expressions__matmul__MatMul(): from sympy.matrices.expressions.matmul import MatMul from sympy.matrices.expressions import MatrixSymbol X = MatrixSymbol('X', x, y) Y = MatrixSymbol('Y', y, x) assert _test_args(MatMul(X, Y)) def test_sympy__matrices__expressions__dotproduct__DotProduct(): from sympy.matrices.expressions.dotproduct import DotProduct from sympy.matrices.expressions import MatrixSymbol X = MatrixSymbol('X', x, 1) Y = MatrixSymbol('Y', x, 1) assert _test_args(DotProduct(X, Y)) def test_sympy__matrices__expressions__diagonal__DiagonalMatrix(): from sympy.matrices.expressions.diagonal import DiagonalMatrix from sympy.matrices.expressions import MatrixSymbol x = MatrixSymbol('x', 10, 1) assert _test_args(DiagonalMatrix(x)) def test_sympy__matrices__expressions__diagonal__DiagonalOf(): from sympy.matrices.expressions.diagonal import DiagonalOf from sympy.matrices.expressions import MatrixSymbol X = MatrixSymbol('x', 10, 10) assert _test_args(DiagonalOf(X)) def test_sympy__matrices__expressions__diagonal__DiagMatrix(): from sympy.matrices.expressions.diagonal import DiagMatrix from sympy.matrices.expressions import MatrixSymbol x = MatrixSymbol('x', 10, 1) assert _test_args(DiagMatrix(x)) def test_sympy__matrices__expressions__hadamard__HadamardProduct(): from sympy.matrices.expressions.hadamard import HadamardProduct from sympy.matrices.expressions import MatrixSymbol X = MatrixSymbol('X', x, y) Y = MatrixSymbol('Y', x, y) assert _test_args(HadamardProduct(X, Y)) def test_sympy__matrices__expressions__hadamard__HadamardPower(): from sympy.matrices.expressions.hadamard import HadamardPower from sympy.matrices.expressions import MatrixSymbol from sympy.core.symbol import Symbol X = MatrixSymbol('X', x, y) n = Symbol("n") assert _test_args(HadamardPower(X, n)) def test_sympy__matrices__expressions__kronecker__KroneckerProduct(): from sympy.matrices.expressions.kronecker import KroneckerProduct from sympy.matrices.expressions import MatrixSymbol X = MatrixSymbol('X', x, y) Y = MatrixSymbol('Y', x, y) assert _test_args(KroneckerProduct(X, Y)) def test_sympy__matrices__expressions__matpow__MatPow(): from sympy.matrices.expressions.matpow import MatPow from sympy.matrices.expressions import MatrixSymbol X = MatrixSymbol('X', x, x) assert _test_args(MatPow(X, 2)) def test_sympy__matrices__expressions__transpose__Transpose(): from sympy.matrices.expressions.transpose import Transpose from sympy.matrices.expressions import MatrixSymbol assert _test_args(Transpose(MatrixSymbol('A', 3, 5))) def test_sympy__matrices__expressions__adjoint__Adjoint(): from sympy.matrices.expressions.adjoint import Adjoint from sympy.matrices.expressions import MatrixSymbol assert _test_args(Adjoint(MatrixSymbol('A', 3, 5))) def test_sympy__matrices__expressions__trace__Trace(): from sympy.matrices.expressions.trace import Trace from sympy.matrices.expressions import MatrixSymbol assert _test_args(Trace(MatrixSymbol('A', 3, 3))) def test_sympy__matrices__expressions__determinant__Determinant(): from sympy.matrices.expressions.determinant import Determinant from sympy.matrices.expressions import MatrixSymbol assert _test_args(Determinant(MatrixSymbol('A', 3, 3))) def test_sympy__matrices__expressions__determinant__Permanent(): from sympy.matrices.expressions.determinant import Permanent from sympy.matrices.expressions import MatrixSymbol assert _test_args(Permanent(MatrixSymbol('A', 3, 4))) def test_sympy__matrices__expressions__funcmatrix__FunctionMatrix(): from sympy.matrices.expressions.funcmatrix import FunctionMatrix from sympy.core.symbol import symbols i, j = symbols('i,j') assert _test_args(FunctionMatrix(3, 3, Lambda((i, j), i - j) )) def test_sympy__matrices__expressions__fourier__DFT(): from sympy.matrices.expressions.fourier import DFT from sympy.core.singleton import S assert _test_args(DFT(S(2))) def test_sympy__matrices__expressions__fourier__IDFT(): from sympy.matrices.expressions.fourier import IDFT from sympy.core.singleton import S assert _test_args(IDFT(S(2))) from sympy.matrices.expressions import MatrixSymbol X = MatrixSymbol('X', 10, 10) def test_sympy__matrices__expressions__factorizations__LofLU(): from sympy.matrices.expressions.factorizations import LofLU assert _test_args(LofLU(X)) def test_sympy__matrices__expressions__factorizations__UofLU(): from sympy.matrices.expressions.factorizations import UofLU assert _test_args(UofLU(X)) def test_sympy__matrices__expressions__factorizations__QofQR(): from sympy.matrices.expressions.factorizations import QofQR assert _test_args(QofQR(X)) def test_sympy__matrices__expressions__factorizations__RofQR(): from sympy.matrices.expressions.factorizations import RofQR assert _test_args(RofQR(X)) def test_sympy__matrices__expressions__factorizations__LofCholesky(): from sympy.matrices.expressions.factorizations import LofCholesky assert _test_args(LofCholesky(X)) def test_sympy__matrices__expressions__factorizations__UofCholesky(): from sympy.matrices.expressions.factorizations import UofCholesky assert _test_args(UofCholesky(X)) def test_sympy__matrices__expressions__factorizations__EigenVectors(): from sympy.matrices.expressions.factorizations import EigenVectors assert _test_args(EigenVectors(X)) def test_sympy__matrices__expressions__factorizations__EigenValues(): from sympy.matrices.expressions.factorizations import EigenValues assert _test_args(EigenValues(X)) def test_sympy__matrices__expressions__factorizations__UofSVD(): from sympy.matrices.expressions.factorizations import UofSVD assert _test_args(UofSVD(X)) def test_sympy__matrices__expressions__factorizations__VofSVD(): from sympy.matrices.expressions.factorizations import VofSVD assert _test_args(VofSVD(X)) def test_sympy__matrices__expressions__factorizations__SofSVD(): from sympy.matrices.expressions.factorizations import SofSVD assert _test_args(SofSVD(X)) @SKIP("abstract class") def test_sympy__matrices__expressions__factorizations__Factorization(): pass def test_sympy__matrices__expressions__permutation__PermutationMatrix(): from sympy.combinatorics import Permutation from sympy.matrices.expressions.permutation import PermutationMatrix assert _test_args(PermutationMatrix(Permutation([2, 0, 1]))) def test_sympy__matrices__expressions__permutation__MatrixPermute(): from sympy.combinatorics import Permutation from sympy.matrices.expressions.matexpr import MatrixSymbol from sympy.matrices.expressions.permutation import MatrixPermute A = MatrixSymbol('A', 3, 3) assert _test_args(MatrixPermute(A, Permutation([2, 0, 1]))) def test_sympy__matrices__expressions__companion__CompanionMatrix(): from sympy.core.symbol import Symbol from sympy.matrices.expressions.companion import CompanionMatrix from sympy.polys.polytools import Poly x = Symbol('x') p = Poly([1, 2, 3], x) assert _test_args(CompanionMatrix(p)) def test_sympy__physics__vector__frame__CoordinateSym(): from sympy.physics.vector import CoordinateSym from sympy.physics.vector import ReferenceFrame assert _test_args(CoordinateSym('R_x', ReferenceFrame('R'), 0)) def test_sympy__physics__paulialgebra__Pauli(): from sympy.physics.paulialgebra import Pauli assert _test_args(Pauli(1)) def test_sympy__physics__quantum__anticommutator__AntiCommutator(): from sympy.physics.quantum.anticommutator import AntiCommutator assert _test_args(AntiCommutator(x, y)) def test_sympy__physics__quantum__cartesian__PositionBra3D(): from sympy.physics.quantum.cartesian import PositionBra3D assert _test_args(PositionBra3D(x, y, z)) def test_sympy__physics__quantum__cartesian__PositionKet3D(): from sympy.physics.quantum.cartesian import PositionKet3D assert _test_args(PositionKet3D(x, y, z)) def test_sympy__physics__quantum__cartesian__PositionState3D(): from sympy.physics.quantum.cartesian import PositionState3D assert _test_args(PositionState3D(x, y, z)) def test_sympy__physics__quantum__cartesian__PxBra(): from sympy.physics.quantum.cartesian import PxBra assert _test_args(PxBra(x, y, z)) def test_sympy__physics__quantum__cartesian__PxKet(): from sympy.physics.quantum.cartesian import PxKet assert _test_args(PxKet(x, y, z)) def test_sympy__physics__quantum__cartesian__PxOp(): from sympy.physics.quantum.cartesian import PxOp assert _test_args(PxOp(x, y, z)) def test_sympy__physics__quantum__cartesian__XBra(): from sympy.physics.quantum.cartesian import XBra assert _test_args(XBra(x)) def test_sympy__physics__quantum__cartesian__XKet(): from sympy.physics.quantum.cartesian import XKet assert _test_args(XKet(x)) def test_sympy__physics__quantum__cartesian__XOp(): from sympy.physics.quantum.cartesian import XOp assert _test_args(XOp(x)) def test_sympy__physics__quantum__cartesian__YOp(): from sympy.physics.quantum.cartesian import YOp assert _test_args(YOp(x)) def test_sympy__physics__quantum__cartesian__ZOp(): from sympy.physics.quantum.cartesian import ZOp assert _test_args(ZOp(x)) def test_sympy__physics__quantum__cg__CG(): from sympy.physics.quantum.cg import CG from sympy.core.singleton import S assert _test_args(CG(Rational(3, 2), Rational(3, 2), S.Half, Rational(-1, 2), 1, 1)) def test_sympy__physics__quantum__cg__Wigner3j(): from sympy.physics.quantum.cg import Wigner3j assert _test_args(Wigner3j(6, 0, 4, 0, 2, 0)) def test_sympy__physics__quantum__cg__Wigner6j(): from sympy.physics.quantum.cg import Wigner6j assert _test_args(Wigner6j(1, 2, 3, 2, 1, 2)) def test_sympy__physics__quantum__cg__Wigner9j(): from sympy.physics.quantum.cg import Wigner9j assert _test_args(Wigner9j(2, 1, 1, Rational(3, 2), S.Half, 1, S.Half, S.Half, 0)) def test_sympy__physics__quantum__circuitplot__Mz(): from sympy.physics.quantum.circuitplot import Mz assert _test_args(Mz(0)) def test_sympy__physics__quantum__circuitplot__Mx(): from sympy.physics.quantum.circuitplot import Mx assert _test_args(Mx(0)) def test_sympy__physics__quantum__commutator__Commutator(): from sympy.physics.quantum.commutator import Commutator A, B = symbols('A,B', commutative=False) assert _test_args(Commutator(A, B)) def test_sympy__physics__quantum__constants__HBar(): from sympy.physics.quantum.constants import HBar assert _test_args(HBar()) def test_sympy__physics__quantum__dagger__Dagger(): from sympy.physics.quantum.dagger import Dagger from sympy.physics.quantum.state import Ket assert _test_args(Dagger(Dagger(Ket('psi')))) def test_sympy__physics__quantum__gate__CGate(): from sympy.physics.quantum.gate import CGate, Gate assert _test_args(CGate((0, 1), Gate(2))) def test_sympy__physics__quantum__gate__CGateS(): from sympy.physics.quantum.gate import CGateS, Gate assert _test_args(CGateS((0, 1), Gate(2))) def test_sympy__physics__quantum__gate__CNotGate(): from sympy.physics.quantum.gate import CNotGate assert _test_args(CNotGate(0, 1)) def test_sympy__physics__quantum__gate__Gate(): from sympy.physics.quantum.gate import Gate assert _test_args(Gate(0)) def test_sympy__physics__quantum__gate__HadamardGate(): from sympy.physics.quantum.gate import HadamardGate assert _test_args(HadamardGate(0)) def test_sympy__physics__quantum__gate__IdentityGate(): from sympy.physics.quantum.gate import IdentityGate assert _test_args(IdentityGate(0)) def test_sympy__physics__quantum__gate__OneQubitGate(): from sympy.physics.quantum.gate import OneQubitGate assert _test_args(OneQubitGate(0)) def test_sympy__physics__quantum__gate__PhaseGate(): from sympy.physics.quantum.gate import PhaseGate assert _test_args(PhaseGate(0)) def test_sympy__physics__quantum__gate__SwapGate(): from sympy.physics.quantum.gate import SwapGate assert _test_args(SwapGate(0, 1)) def test_sympy__physics__quantum__gate__TGate(): from sympy.physics.quantum.gate import TGate assert _test_args(TGate(0)) def test_sympy__physics__quantum__gate__TwoQubitGate(): from sympy.physics.quantum.gate import TwoQubitGate assert _test_args(TwoQubitGate(0)) def test_sympy__physics__quantum__gate__UGate(): from sympy.physics.quantum.gate import UGate from sympy.matrices.immutable import ImmutableDenseMatrix from sympy.core.containers import Tuple from sympy.core.numbers import Integer assert _test_args( UGate(Tuple(Integer(1)), ImmutableDenseMatrix([[1, 0], [0, 2]]))) def test_sympy__physics__quantum__gate__XGate(): from sympy.physics.quantum.gate import XGate assert _test_args(XGate(0)) def test_sympy__physics__quantum__gate__YGate(): from sympy.physics.quantum.gate import YGate assert _test_args(YGate(0)) def test_sympy__physics__quantum__gate__ZGate(): from sympy.physics.quantum.gate import ZGate assert _test_args(ZGate(0)) def test_sympy__physics__quantum__grover__OracleGateFunction(): from sympy.physics.quantum.grover import OracleGateFunction @OracleGateFunction def f(qubit): return assert _test_args(f) def test_sympy__physics__quantum__grover__OracleGate(): from sympy.physics.quantum.grover import OracleGate def f(qubit): return assert _test_args(OracleGate(1,f)) def test_sympy__physics__quantum__grover__WGate(): from sympy.physics.quantum.grover import WGate assert _test_args(WGate(1)) def test_sympy__physics__quantum__hilbert__ComplexSpace(): from sympy.physics.quantum.hilbert import ComplexSpace assert _test_args(ComplexSpace(x)) def test_sympy__physics__quantum__hilbert__DirectSumHilbertSpace(): from sympy.physics.quantum.hilbert import DirectSumHilbertSpace, ComplexSpace, FockSpace c = ComplexSpace(2) f = FockSpace() assert _test_args(DirectSumHilbertSpace(c, f)) def test_sympy__physics__quantum__hilbert__FockSpace(): from sympy.physics.quantum.hilbert import FockSpace assert _test_args(FockSpace()) def test_sympy__physics__quantum__hilbert__HilbertSpace(): from sympy.physics.quantum.hilbert import HilbertSpace assert _test_args(HilbertSpace()) def test_sympy__physics__quantum__hilbert__L2(): from sympy.physics.quantum.hilbert import L2 from sympy.core.numbers import oo from sympy.sets.sets import Interval assert _test_args(L2(Interval(0, oo))) def test_sympy__physics__quantum__hilbert__TensorPowerHilbertSpace(): from sympy.physics.quantum.hilbert import TensorPowerHilbertSpace, FockSpace f = FockSpace() assert _test_args(TensorPowerHilbertSpace(f, 2)) def test_sympy__physics__quantum__hilbert__TensorProductHilbertSpace(): from sympy.physics.quantum.hilbert import TensorProductHilbertSpace, FockSpace, ComplexSpace c = ComplexSpace(2) f = FockSpace() assert _test_args(TensorProductHilbertSpace(f, c)) def test_sympy__physics__quantum__innerproduct__InnerProduct(): from sympy.physics.quantum import Bra, Ket, InnerProduct b = Bra('b') k = Ket('k') assert _test_args(InnerProduct(b, k)) def test_sympy__physics__quantum__operator__DifferentialOperator(): from sympy.physics.quantum.operator import DifferentialOperator from sympy.core.function import (Derivative, Function) f = Function('f') assert _test_args(DifferentialOperator(1/x*Derivative(f(x), x), f(x))) def test_sympy__physics__quantum__operator__HermitianOperator(): from sympy.physics.quantum.operator import HermitianOperator assert _test_args(HermitianOperator('H')) def test_sympy__physics__quantum__operator__IdentityOperator(): from sympy.physics.quantum.operator import IdentityOperator assert _test_args(IdentityOperator(5)) def test_sympy__physics__quantum__operator__Operator(): from sympy.physics.quantum.operator import Operator assert _test_args(Operator('A')) def test_sympy__physics__quantum__operator__OuterProduct(): from sympy.physics.quantum.operator import OuterProduct from sympy.physics.quantum import Ket, Bra b = Bra('b') k = Ket('k') assert _test_args(OuterProduct(k, b)) def test_sympy__physics__quantum__operator__UnitaryOperator(): from sympy.physics.quantum.operator import UnitaryOperator assert _test_args(UnitaryOperator('U')) def test_sympy__physics__quantum__piab__PIABBra(): from sympy.physics.quantum.piab import PIABBra assert _test_args(PIABBra('B')) def test_sympy__physics__quantum__boson__BosonOp(): from sympy.physics.quantum.boson import BosonOp assert _test_args(BosonOp('a')) assert _test_args(BosonOp('a', False)) def test_sympy__physics__quantum__boson__BosonFockKet(): from sympy.physics.quantum.boson import BosonFockKet assert _test_args(BosonFockKet(1)) def test_sympy__physics__quantum__boson__BosonFockBra(): from sympy.physics.quantum.boson import BosonFockBra assert _test_args(BosonFockBra(1)) def test_sympy__physics__quantum__boson__BosonCoherentKet(): from sympy.physics.quantum.boson import BosonCoherentKet assert _test_args(BosonCoherentKet(1)) def test_sympy__physics__quantum__boson__BosonCoherentBra(): from sympy.physics.quantum.boson import BosonCoherentBra assert _test_args(BosonCoherentBra(1)) def test_sympy__physics__quantum__fermion__FermionOp(): from sympy.physics.quantum.fermion import FermionOp assert _test_args(FermionOp('c')) assert _test_args(FermionOp('c', False)) def test_sympy__physics__quantum__fermion__FermionFockKet(): from sympy.physics.quantum.fermion import FermionFockKet assert _test_args(FermionFockKet(1)) def test_sympy__physics__quantum__fermion__FermionFockBra(): from sympy.physics.quantum.fermion import FermionFockBra assert _test_args(FermionFockBra(1)) def test_sympy__physics__quantum__pauli__SigmaOpBase(): from sympy.physics.quantum.pauli import SigmaOpBase assert _test_args(SigmaOpBase()) def test_sympy__physics__quantum__pauli__SigmaX(): from sympy.physics.quantum.pauli import SigmaX assert _test_args(SigmaX()) def test_sympy__physics__quantum__pauli__SigmaY(): from sympy.physics.quantum.pauli import SigmaY assert _test_args(SigmaY()) def test_sympy__physics__quantum__pauli__SigmaZ(): from sympy.physics.quantum.pauli import SigmaZ assert _test_args(SigmaZ()) def test_sympy__physics__quantum__pauli__SigmaMinus(): from sympy.physics.quantum.pauli import SigmaMinus assert _test_args(SigmaMinus()) def test_sympy__physics__quantum__pauli__SigmaPlus(): from sympy.physics.quantum.pauli import SigmaPlus assert _test_args(SigmaPlus()) def test_sympy__physics__quantum__pauli__SigmaZKet(): from sympy.physics.quantum.pauli import SigmaZKet assert _test_args(SigmaZKet(0)) def test_sympy__physics__quantum__pauli__SigmaZBra(): from sympy.physics.quantum.pauli import SigmaZBra assert _test_args(SigmaZBra(0)) def test_sympy__physics__quantum__piab__PIABHamiltonian(): from sympy.physics.quantum.piab import PIABHamiltonian assert _test_args(PIABHamiltonian('P')) def test_sympy__physics__quantum__piab__PIABKet(): from sympy.physics.quantum.piab import PIABKet assert _test_args(PIABKet('K')) def test_sympy__physics__quantum__qexpr__QExpr(): from sympy.physics.quantum.qexpr import QExpr assert _test_args(QExpr(0)) def test_sympy__physics__quantum__qft__Fourier(): from sympy.physics.quantum.qft import Fourier assert _test_args(Fourier(0, 1)) def test_sympy__physics__quantum__qft__IQFT(): from sympy.physics.quantum.qft import IQFT assert _test_args(IQFT(0, 1)) def test_sympy__physics__quantum__qft__QFT(): from sympy.physics.quantum.qft import QFT assert _test_args(QFT(0, 1)) def test_sympy__physics__quantum__qft__RkGate(): from sympy.physics.quantum.qft import RkGate assert _test_args(RkGate(0, 1)) def test_sympy__physics__quantum__qubit__IntQubit(): from sympy.physics.quantum.qubit import IntQubit assert _test_args(IntQubit(0)) def test_sympy__physics__quantum__qubit__IntQubitBra(): from sympy.physics.quantum.qubit import IntQubitBra assert _test_args(IntQubitBra(0)) def test_sympy__physics__quantum__qubit__IntQubitState(): from sympy.physics.quantum.qubit import IntQubitState, QubitState assert _test_args(IntQubitState(QubitState(0, 1))) def test_sympy__physics__quantum__qubit__Qubit(): from sympy.physics.quantum.qubit import Qubit assert _test_args(Qubit(0, 0, 0)) def test_sympy__physics__quantum__qubit__QubitBra(): from sympy.physics.quantum.qubit import QubitBra assert _test_args(QubitBra('1', 0)) def test_sympy__physics__quantum__qubit__QubitState(): from sympy.physics.quantum.qubit import QubitState assert _test_args(QubitState(0, 1)) def test_sympy__physics__quantum__density__Density(): from sympy.physics.quantum.density import Density from sympy.physics.quantum.state import Ket assert _test_args(Density([Ket(0), 0.5], [Ket(1), 0.5])) @SKIP("TODO: sympy.physics.quantum.shor: Cmod Not Implemented") def test_sympy__physics__quantum__shor__CMod(): from sympy.physics.quantum.shor import CMod assert _test_args(CMod()) def test_sympy__physics__quantum__spin__CoupledSpinState(): from sympy.physics.quantum.spin import CoupledSpinState assert _test_args(CoupledSpinState(1, 0, (1, 1))) assert _test_args(CoupledSpinState(1, 0, (1, S.Half, S.Half))) assert _test_args(CoupledSpinState( 1, 0, (1, S.Half, S.Half), ((2, 3, S.Half), (1, 2, 1)) )) j, m, j1, j2, j3, j12, x = symbols('j m j1:4 j12 x') assert CoupledSpinState( j, m, (j1, j2, j3)).subs(j2, x) == CoupledSpinState(j, m, (j1, x, j3)) assert CoupledSpinState(j, m, (j1, j2, j3), ((1, 3, j12), (1, 2, j)) ).subs(j12, x) == \ CoupledSpinState(j, m, (j1, j2, j3), ((1, 3, x), (1, 2, j)) ) def test_sympy__physics__quantum__spin__J2Op(): from sympy.physics.quantum.spin import J2Op assert _test_args(J2Op('J')) def test_sympy__physics__quantum__spin__JminusOp(): from sympy.physics.quantum.spin import JminusOp assert _test_args(JminusOp('J')) def test_sympy__physics__quantum__spin__JplusOp(): from sympy.physics.quantum.spin import JplusOp assert _test_args(JplusOp('J')) def test_sympy__physics__quantum__spin__JxBra(): from sympy.physics.quantum.spin import JxBra assert _test_args(JxBra(1, 0)) def test_sympy__physics__quantum__spin__JxBraCoupled(): from sympy.physics.quantum.spin import JxBraCoupled assert _test_args(JxBraCoupled(1, 0, (1, 1))) def test_sympy__physics__quantum__spin__JxKet(): from sympy.physics.quantum.spin import JxKet assert _test_args(JxKet(1, 0)) def test_sympy__physics__quantum__spin__JxKetCoupled(): from sympy.physics.quantum.spin import JxKetCoupled assert _test_args(JxKetCoupled(1, 0, (1, 1))) def test_sympy__physics__quantum__spin__JxOp(): from sympy.physics.quantum.spin import JxOp assert _test_args(JxOp('J')) def test_sympy__physics__quantum__spin__JyBra(): from sympy.physics.quantum.spin import JyBra assert _test_args(JyBra(1, 0)) def test_sympy__physics__quantum__spin__JyBraCoupled(): from sympy.physics.quantum.spin import JyBraCoupled assert _test_args(JyBraCoupled(1, 0, (1, 1))) def test_sympy__physics__quantum__spin__JyKet(): from sympy.physics.quantum.spin import JyKet assert _test_args(JyKet(1, 0)) def test_sympy__physics__quantum__spin__JyKetCoupled(): from sympy.physics.quantum.spin import JyKetCoupled assert _test_args(JyKetCoupled(1, 0, (1, 1))) def test_sympy__physics__quantum__spin__JyOp(): from sympy.physics.quantum.spin import JyOp assert _test_args(JyOp('J')) def test_sympy__physics__quantum__spin__JzBra(): from sympy.physics.quantum.spin import JzBra assert _test_args(JzBra(1, 0)) def test_sympy__physics__quantum__spin__JzBraCoupled(): from sympy.physics.quantum.spin import JzBraCoupled assert _test_args(JzBraCoupled(1, 0, (1, 1))) def test_sympy__physics__quantum__spin__JzKet(): from sympy.physics.quantum.spin import JzKet assert _test_args(JzKet(1, 0)) def test_sympy__physics__quantum__spin__JzKetCoupled(): from sympy.physics.quantum.spin import JzKetCoupled assert _test_args(JzKetCoupled(1, 0, (1, 1))) def test_sympy__physics__quantum__spin__JzOp(): from sympy.physics.quantum.spin import JzOp assert _test_args(JzOp('J')) def test_sympy__physics__quantum__spin__Rotation(): from sympy.physics.quantum.spin import Rotation assert _test_args(Rotation(pi, 0, pi/2)) def test_sympy__physics__quantum__spin__SpinState(): from sympy.physics.quantum.spin import SpinState assert _test_args(SpinState(1, 0)) def test_sympy__physics__quantum__spin__WignerD(): from sympy.physics.quantum.spin import WignerD assert _test_args(WignerD(0, 1, 2, 3, 4, 5)) def test_sympy__physics__quantum__state__Bra(): from sympy.physics.quantum.state import Bra assert _test_args(Bra(0)) def test_sympy__physics__quantum__state__BraBase(): from sympy.physics.quantum.state import BraBase assert _test_args(BraBase(0)) def test_sympy__physics__quantum__state__Ket(): from sympy.physics.quantum.state import Ket assert _test_args(Ket(0)) def test_sympy__physics__quantum__state__KetBase(): from sympy.physics.quantum.state import KetBase assert _test_args(KetBase(0)) def test_sympy__physics__quantum__state__State(): from sympy.physics.quantum.state import State assert _test_args(State(0)) def test_sympy__physics__quantum__state__StateBase(): from sympy.physics.quantum.state import StateBase assert _test_args(StateBase(0)) def test_sympy__physics__quantum__state__OrthogonalBra(): from sympy.physics.quantum.state import OrthogonalBra assert _test_args(OrthogonalBra(0)) def test_sympy__physics__quantum__state__OrthogonalKet(): from sympy.physics.quantum.state import OrthogonalKet assert _test_args(OrthogonalKet(0)) def test_sympy__physics__quantum__state__OrthogonalState(): from sympy.physics.quantum.state import OrthogonalState assert _test_args(OrthogonalState(0)) def test_sympy__physics__quantum__state__TimeDepBra(): from sympy.physics.quantum.state import TimeDepBra assert _test_args(TimeDepBra('psi', 't')) def test_sympy__physics__quantum__state__TimeDepKet(): from sympy.physics.quantum.state import TimeDepKet assert _test_args(TimeDepKet('psi', 't')) def test_sympy__physics__quantum__state__TimeDepState(): from sympy.physics.quantum.state import TimeDepState assert _test_args(TimeDepState('psi', 't')) def test_sympy__physics__quantum__state__Wavefunction(): from sympy.physics.quantum.state import Wavefunction from sympy.functions import sin from sympy.functions.elementary.piecewise import Piecewise n = 1 L = 1 g = Piecewise((0, x < 0), (0, x > L), (sqrt(2//L)*sin(n*pi*x/L), True)) assert _test_args(Wavefunction(g, x)) def test_sympy__physics__quantum__tensorproduct__TensorProduct(): from sympy.physics.quantum.tensorproduct import TensorProduct x, y = symbols("x y", commutative=False) assert _test_args(TensorProduct(x, y)) def test_sympy__physics__quantum__identitysearch__GateIdentity(): from sympy.physics.quantum.gate import X from sympy.physics.quantum.identitysearch import GateIdentity assert _test_args(GateIdentity(X(0), X(0))) def test_sympy__physics__quantum__sho1d__SHOOp(): from sympy.physics.quantum.sho1d import SHOOp assert _test_args(SHOOp('a')) def test_sympy__physics__quantum__sho1d__RaisingOp(): from sympy.physics.quantum.sho1d import RaisingOp assert _test_args(RaisingOp('a')) def test_sympy__physics__quantum__sho1d__LoweringOp(): from sympy.physics.quantum.sho1d import LoweringOp assert _test_args(LoweringOp('a')) def test_sympy__physics__quantum__sho1d__NumberOp(): from sympy.physics.quantum.sho1d import NumberOp assert _test_args(NumberOp('N')) def test_sympy__physics__quantum__sho1d__Hamiltonian(): from sympy.physics.quantum.sho1d import Hamiltonian assert _test_args(Hamiltonian('H')) def test_sympy__physics__quantum__sho1d__SHOState(): from sympy.physics.quantum.sho1d import SHOState assert _test_args(SHOState(0)) def test_sympy__physics__quantum__sho1d__SHOKet(): from sympy.physics.quantum.sho1d import SHOKet assert _test_args(SHOKet(0)) def test_sympy__physics__quantum__sho1d__SHOBra(): from sympy.physics.quantum.sho1d import SHOBra assert _test_args(SHOBra(0)) def test_sympy__physics__secondquant__AnnihilateBoson(): from sympy.physics.secondquant import AnnihilateBoson assert _test_args(AnnihilateBoson(0)) def test_sympy__physics__secondquant__AnnihilateFermion(): from sympy.physics.secondquant import AnnihilateFermion assert _test_args(AnnihilateFermion(0)) @SKIP("abstract class") def test_sympy__physics__secondquant__Annihilator(): pass def test_sympy__physics__secondquant__AntiSymmetricTensor(): from sympy.physics.secondquant import AntiSymmetricTensor i, j = symbols('i j', below_fermi=True) a, b = symbols('a b', above_fermi=True) assert _test_args(AntiSymmetricTensor('v', (a, i), (b, j))) def test_sympy__physics__secondquant__BosonState(): from sympy.physics.secondquant import BosonState assert _test_args(BosonState((0, 1))) @SKIP("abstract class") def test_sympy__physics__secondquant__BosonicOperator(): pass def test_sympy__physics__secondquant__Commutator(): from sympy.physics.secondquant import Commutator x, y = symbols('x y', commutative=False) assert _test_args(Commutator(x, y)) def test_sympy__physics__secondquant__CreateBoson(): from sympy.physics.secondquant import CreateBoson assert _test_args(CreateBoson(0)) def test_sympy__physics__secondquant__CreateFermion(): from sympy.physics.secondquant import CreateFermion assert _test_args(CreateFermion(0)) @SKIP("abstract class") def test_sympy__physics__secondquant__Creator(): pass def test_sympy__physics__secondquant__Dagger(): from sympy.physics.secondquant import Dagger assert _test_args(Dagger(x)) def test_sympy__physics__secondquant__FermionState(): from sympy.physics.secondquant import FermionState assert _test_args(FermionState((0, 1))) def test_sympy__physics__secondquant__FermionicOperator(): from sympy.physics.secondquant import FermionicOperator assert _test_args(FermionicOperator(0)) def test_sympy__physics__secondquant__FockState(): from sympy.physics.secondquant import FockState assert _test_args(FockState((0, 1))) def test_sympy__physics__secondquant__FockStateBosonBra(): from sympy.physics.secondquant import FockStateBosonBra assert _test_args(FockStateBosonBra((0, 1))) def test_sympy__physics__secondquant__FockStateBosonKet(): from sympy.physics.secondquant import FockStateBosonKet assert _test_args(FockStateBosonKet((0, 1))) def test_sympy__physics__secondquant__FockStateBra(): from sympy.physics.secondquant import FockStateBra assert _test_args(FockStateBra((0, 1))) def test_sympy__physics__secondquant__FockStateFermionBra(): from sympy.physics.secondquant import FockStateFermionBra assert _test_args(FockStateFermionBra((0, 1))) def test_sympy__physics__secondquant__FockStateFermionKet(): from sympy.physics.secondquant import FockStateFermionKet assert _test_args(FockStateFermionKet((0, 1))) def test_sympy__physics__secondquant__FockStateKet(): from sympy.physics.secondquant import FockStateKet assert _test_args(FockStateKet((0, 1))) def test_sympy__physics__secondquant__InnerProduct(): from sympy.physics.secondquant import InnerProduct from sympy.physics.secondquant import FockStateKet, FockStateBra assert _test_args(InnerProduct(FockStateBra((0, 1)), FockStateKet((0, 1)))) def test_sympy__physics__secondquant__NO(): from sympy.physics.secondquant import NO, F, Fd assert _test_args(NO(Fd(x)*F(y))) def test_sympy__physics__secondquant__PermutationOperator(): from sympy.physics.secondquant import PermutationOperator assert _test_args(PermutationOperator(0, 1)) def test_sympy__physics__secondquant__SqOperator(): from sympy.physics.secondquant import SqOperator assert _test_args(SqOperator(0)) def test_sympy__physics__secondquant__TensorSymbol(): from sympy.physics.secondquant import TensorSymbol assert _test_args(TensorSymbol(x)) def test_sympy__physics__control__lti__LinearTimeInvariant(): # Direct instances of LinearTimeInvariant class are not allowed. # func(*args) tests for its derived classes (TransferFunction, # Series, Parallel and TransferFunctionMatrix) should pass. pass def test_sympy__physics__control__lti__SISOLinearTimeInvariant(): # Direct instances of SISOLinearTimeInvariant class are not allowed. pass def test_sympy__physics__control__lti__MIMOLinearTimeInvariant(): # Direct instances of MIMOLinearTimeInvariant class are not allowed. pass def test_sympy__physics__control__lti__TransferFunction(): from sympy.physics.control.lti import TransferFunction assert _test_args(TransferFunction(2, 3, x)) def test_sympy__physics__control__lti__Series(): from sympy.physics.control import Series, TransferFunction tf1 = TransferFunction(x**2 - y**3, y - z, x) tf2 = TransferFunction(y - x, z + y, x) assert _test_args(Series(tf1, tf2)) def test_sympy__physics__control__lti__MIMOSeries(): from sympy.physics.control import MIMOSeries, TransferFunction, TransferFunctionMatrix tf1 = TransferFunction(x**2 - y**3, y - z, x) tf2 = TransferFunction(y - x, z + y, x) tfm_1 = TransferFunctionMatrix([[tf2, tf1]]) tfm_2 = TransferFunctionMatrix([[tf1, tf2], [tf2, tf1]]) tfm_3 = TransferFunctionMatrix([[tf1], [tf2]]) assert _test_args(MIMOSeries(tfm_3, tfm_2, tfm_1)) def test_sympy__physics__control__lti__Parallel(): from sympy.physics.control import Parallel, TransferFunction tf1 = TransferFunction(x**2 - y**3, y - z, x) tf2 = TransferFunction(y - x, z + y, x) assert _test_args(Parallel(tf1, tf2)) def test_sympy__physics__control__lti__MIMOParallel(): from sympy.physics.control import MIMOParallel, TransferFunction, TransferFunctionMatrix tf1 = TransferFunction(x**2 - y**3, y - z, x) tf2 = TransferFunction(y - x, z + y, x) tfm_1 = TransferFunctionMatrix([[tf1, tf2], [tf2, tf1]]) tfm_2 = TransferFunctionMatrix([[tf2, tf1], [tf1, tf2]]) assert _test_args(MIMOParallel(tfm_1, tfm_2)) def test_sympy__physics__control__lti__Feedback(): from sympy.physics.control import TransferFunction, Feedback tf1 = TransferFunction(x**2 - y**3, y - z, x) tf2 = TransferFunction(y - x, z + y, x) assert _test_args(Feedback(tf1, tf2)) assert _test_args(Feedback(tf1, tf2, 1)) def test_sympy__physics__control__lti__MIMOFeedback(): from sympy.physics.control import TransferFunction, MIMOFeedback, TransferFunctionMatrix tf1 = TransferFunction(x**2 - y**3, y - z, x) tf2 = TransferFunction(y - x, z + y, x) tfm_1 = TransferFunctionMatrix([[tf2, tf1], [tf1, tf2]]) tfm_2 = TransferFunctionMatrix([[tf1, tf2], [tf2, tf1]]) assert _test_args(MIMOFeedback(tfm_1, tfm_2)) assert _test_args(MIMOFeedback(tfm_1, tfm_2, 1)) def test_sympy__physics__control__lti__TransferFunctionMatrix(): from sympy.physics.control import TransferFunction, TransferFunctionMatrix tf1 = TransferFunction(x**2 - y**3, y - z, x) tf2 = TransferFunction(y - x, z + y, x) assert _test_args(TransferFunctionMatrix([[tf1, tf2]])) def test_sympy__physics__units__dimensions__Dimension(): from sympy.physics.units.dimensions import Dimension assert _test_args(Dimension("length", "L")) def test_sympy__physics__units__dimensions__DimensionSystem(): from sympy.physics.units.dimensions import DimensionSystem from sympy.physics.units.definitions.dimension_definitions import length, time, velocity assert _test_args(DimensionSystem((length, time), (velocity,))) def test_sympy__physics__units__quantities__Quantity(): from sympy.physics.units.quantities import Quantity assert _test_args(Quantity("dam")) def test_sympy__physics__units__prefixes__Prefix(): from sympy.physics.units.prefixes import Prefix assert _test_args(Prefix('kilo', 'k', 3)) def test_sympy__core__numbers__AlgebraicNumber(): from sympy.core.numbers import AlgebraicNumber assert _test_args(AlgebraicNumber(sqrt(2), [1, 2, 3])) def test_sympy__polys__polytools__GroebnerBasis(): from sympy.polys.polytools import GroebnerBasis assert _test_args(GroebnerBasis([x, y, z], x, y, z)) def test_sympy__polys__polytools__Poly(): from sympy.polys.polytools import Poly assert _test_args(Poly(2, x, y)) def test_sympy__polys__polytools__PurePoly(): from sympy.polys.polytools import PurePoly assert _test_args(PurePoly(2, x, y)) @SKIP('abstract class') def test_sympy__polys__rootoftools__RootOf(): pass def test_sympy__polys__rootoftools__ComplexRootOf(): from sympy.polys.rootoftools import ComplexRootOf assert _test_args(ComplexRootOf(x**3 + x + 1, 0)) def test_sympy__polys__rootoftools__RootSum(): from sympy.polys.rootoftools import RootSum assert _test_args(RootSum(x**3 + x + 1, sin)) def test_sympy__series__limits__Limit(): from sympy.series.limits import Limit assert _test_args(Limit(x, x, 0, dir='-')) def test_sympy__series__order__Order(): from sympy.series.order import Order assert _test_args(Order(1, x, y)) @SKIP('Abstract Class') def test_sympy__series__sequences__SeqBase(): pass def test_sympy__series__sequences__EmptySequence(): # Need to imort the instance from series not the class from # series.sequence from sympy.series import EmptySequence assert _test_args(EmptySequence) @SKIP('Abstract Class') def test_sympy__series__sequences__SeqExpr(): pass def test_sympy__series__sequences__SeqPer(): from sympy.series.sequences import SeqPer assert _test_args(SeqPer((1, 2, 3), (0, 10))) def test_sympy__series__sequences__SeqFormula(): from sympy.series.sequences import SeqFormula assert _test_args(SeqFormula(x**2, (0, 10))) def test_sympy__series__sequences__RecursiveSeq(): from sympy.series.sequences import RecursiveSeq y = Function("y") n = symbols("n") assert _test_args(RecursiveSeq(y(n - 1) + y(n - 2), y(n), n, (0, 1))) assert _test_args(RecursiveSeq(y(n - 1) + y(n - 2), y(n), n)) def test_sympy__series__sequences__SeqExprOp(): from sympy.series.sequences import SeqExprOp, sequence s1 = sequence((1, 2, 3)) s2 = sequence(x**2) assert _test_args(SeqExprOp(s1, s2)) def test_sympy__series__sequences__SeqAdd(): from sympy.series.sequences import SeqAdd, sequence s1 = sequence((1, 2, 3)) s2 = sequence(x**2) assert _test_args(SeqAdd(s1, s2)) def test_sympy__series__sequences__SeqMul(): from sympy.series.sequences import SeqMul, sequence s1 = sequence((1, 2, 3)) s2 = sequence(x**2) assert _test_args(SeqMul(s1, s2)) @SKIP('Abstract Class') def test_sympy__series__series_class__SeriesBase(): pass def test_sympy__series__fourier__FourierSeries(): from sympy.series.fourier import fourier_series assert _test_args(fourier_series(x, (x, -pi, pi))) def test_sympy__series__fourier__FiniteFourierSeries(): from sympy.series.fourier import fourier_series assert _test_args(fourier_series(sin(pi*x), (x, -1, 1))) def test_sympy__series__formal__FormalPowerSeries(): from sympy.series.formal import fps assert _test_args(fps(log(1 + x), x)) def test_sympy__series__formal__Coeff(): from sympy.series.formal import fps assert _test_args(fps(x**2 + x + 1, x)) @SKIP('Abstract Class') def test_sympy__series__formal__FiniteFormalPowerSeries(): pass def test_sympy__series__formal__FormalPowerSeriesProduct(): from sympy.series.formal import fps f1, f2 = fps(sin(x)), fps(exp(x)) assert _test_args(f1.product(f2, x)) def test_sympy__series__formal__FormalPowerSeriesCompose(): from sympy.series.formal import fps f1, f2 = fps(exp(x)), fps(sin(x)) assert _test_args(f1.compose(f2, x)) def test_sympy__series__formal__FormalPowerSeriesInverse(): from sympy.series.formal import fps f1 = fps(exp(x)) assert _test_args(f1.inverse(x)) def test_sympy__simplify__hyperexpand__Hyper_Function(): from sympy.simplify.hyperexpand import Hyper_Function assert _test_args(Hyper_Function([2], [1])) def test_sympy__simplify__hyperexpand__G_Function(): from sympy.simplify.hyperexpand import G_Function assert _test_args(G_Function([2], [1], [], [])) @SKIP("abstract class") def test_sympy__tensor__array__ndim_array__ImmutableNDimArray(): pass def test_sympy__tensor__array__dense_ndim_array__ImmutableDenseNDimArray(): from sympy.tensor.array.dense_ndim_array import ImmutableDenseNDimArray densarr = ImmutableDenseNDimArray(range(10, 34), (2, 3, 4)) assert _test_args(densarr) def test_sympy__tensor__array__sparse_ndim_array__ImmutableSparseNDimArray(): from sympy.tensor.array.sparse_ndim_array import ImmutableSparseNDimArray sparr = ImmutableSparseNDimArray(range(10, 34), (2, 3, 4)) assert _test_args(sparr) def test_sympy__tensor__array__array_comprehension__ArrayComprehension(): from sympy.tensor.array.array_comprehension import ArrayComprehension arrcom = ArrayComprehension(x, (x, 1, 5)) assert _test_args(arrcom) def test_sympy__tensor__array__array_comprehension__ArrayComprehensionMap(): from sympy.tensor.array.array_comprehension import ArrayComprehensionMap arrcomma = ArrayComprehensionMap(lambda: 0, (x, 1, 5)) assert _test_args(arrcomma) def test_sympy__tensor__array__array_derivatives__ArrayDerivative(): from sympy.tensor.array.array_derivatives import ArrayDerivative A = MatrixSymbol("A", 2, 2) arrder = ArrayDerivative(A, A, evaluate=False) assert _test_args(arrder) def test_sympy__tensor__array__expressions__array_expressions__ArraySymbol(): from sympy.tensor.array.expressions.array_expressions import ArraySymbol m, n, k = symbols("m n k") array = ArraySymbol("A", (m, n, k, 2)) assert _test_args(array) def test_sympy__tensor__array__expressions__array_expressions__ArrayElement(): from sympy.tensor.array.expressions.array_expressions import ArrayElement m, n, k = symbols("m n k") ae = ArrayElement("A", (m, n, k, 2)) assert _test_args(ae) def test_sympy__tensor__array__expressions__array_expressions__ZeroArray(): from sympy.tensor.array.expressions.array_expressions import ZeroArray m, n, k = symbols("m n k") za = ZeroArray(m, n, k, 2) assert _test_args(za) def test_sympy__tensor__array__expressions__array_expressions__OneArray(): from sympy.tensor.array.expressions.array_expressions import OneArray m, n, k = symbols("m n k") za = OneArray(m, n, k, 2) assert _test_args(za) def test_sympy__tensor__functions__TensorProduct(): from sympy.tensor.functions import TensorProduct A = MatrixSymbol('A', 3, 3) B = MatrixSymbol('B', 3, 3) tp = TensorProduct(A, B) assert _test_args(tp) def test_sympy__tensor__indexed__Idx(): from sympy.tensor.indexed import Idx assert _test_args(Idx('test')) assert _test_args(Idx('test', (0, 10))) assert _test_args(Idx('test', 2)) assert _test_args(Idx('test', x)) def test_sympy__tensor__indexed__Indexed(): from sympy.tensor.indexed import Indexed, Idx assert _test_args(Indexed('A', Idx('i'), Idx('j'))) def test_sympy__tensor__indexed__IndexedBase(): from sympy.tensor.indexed import IndexedBase assert _test_args(IndexedBase('A', shape=(x, y))) assert _test_args(IndexedBase('A', 1)) assert _test_args(IndexedBase('A')[0, 1]) def test_sympy__tensor__tensor__TensorIndexType(): from sympy.tensor.tensor import TensorIndexType assert _test_args(TensorIndexType('Lorentz')) @SKIP("deprecated class") def test_sympy__tensor__tensor__TensorType(): pass def test_sympy__tensor__tensor__TensorSymmetry(): from sympy.tensor.tensor import TensorSymmetry, get_symmetric_group_sgs assert _test_args(TensorSymmetry(get_symmetric_group_sgs(2))) def test_sympy__tensor__tensor__TensorHead(): from sympy.tensor.tensor import TensorIndexType, TensorSymmetry, get_symmetric_group_sgs, TensorHead Lorentz = TensorIndexType('Lorentz', dummy_name='L') sym = TensorSymmetry(get_symmetric_group_sgs(1)) assert _test_args(TensorHead('p', [Lorentz], sym, 0)) def test_sympy__tensor__tensor__TensorIndex(): from sympy.tensor.tensor import TensorIndexType, TensorIndex Lorentz = TensorIndexType('Lorentz', dummy_name='L') assert _test_args(TensorIndex('i', Lorentz)) @SKIP("abstract class") def test_sympy__tensor__tensor__TensExpr(): pass def test_sympy__tensor__tensor__TensAdd(): from sympy.tensor.tensor import TensorIndexType, TensorSymmetry, get_symmetric_group_sgs, tensor_indices, TensAdd, tensor_heads Lorentz = TensorIndexType('Lorentz', dummy_name='L') a, b = tensor_indices('a,b', Lorentz) sym = TensorSymmetry(get_symmetric_group_sgs(1)) p, q = tensor_heads('p,q', [Lorentz], sym) t1 = p(a) t2 = q(a) assert _test_args(TensAdd(t1, t2)) def test_sympy__tensor__tensor__Tensor(): from sympy.tensor.tensor import TensorIndexType, TensorSymmetry, get_symmetric_group_sgs, tensor_indices, TensorHead Lorentz = TensorIndexType('Lorentz', dummy_name='L') a, b = tensor_indices('a,b', Lorentz) sym = TensorSymmetry(get_symmetric_group_sgs(1)) p = TensorHead('p', [Lorentz], sym) assert _test_args(p(a)) def test_sympy__tensor__tensor__TensMul(): from sympy.tensor.tensor import TensorIndexType, TensorSymmetry, get_symmetric_group_sgs, tensor_indices, tensor_heads Lorentz = TensorIndexType('Lorentz', dummy_name='L') a, b = tensor_indices('a,b', Lorentz) sym = TensorSymmetry(get_symmetric_group_sgs(1)) p, q = tensor_heads('p, q', [Lorentz], sym) assert _test_args(3*p(a)*q(b)) def test_sympy__tensor__tensor__TensorElement(): from sympy.tensor.tensor import TensorIndexType, TensorHead, TensorElement L = TensorIndexType("L") A = TensorHead("A", [L, L]) telem = TensorElement(A(x, y), {x: 1}) assert _test_args(telem) def test_sympy__tensor__toperators__PartialDerivative(): from sympy.tensor.tensor import TensorIndexType, tensor_indices, TensorHead from sympy.tensor.toperators import PartialDerivative Lorentz = TensorIndexType('Lorentz', dummy_name='L') a, b = tensor_indices('a,b', Lorentz) A = TensorHead("A", [Lorentz]) assert _test_args(PartialDerivative(A(a), A(b))) def test_as_coeff_add(): assert (7, (3*x, 4*x**2)) == (7 + 3*x + 4*x**2).as_coeff_add() def test_sympy__geometry__curve__Curve(): from sympy.geometry.curve import Curve assert _test_args(Curve((x, 1), (x, 0, 1))) def test_sympy__geometry__point__Point(): from sympy.geometry.point import Point assert _test_args(Point(0, 1)) def test_sympy__geometry__point__Point2D(): from sympy.geometry.point import Point2D assert _test_args(Point2D(0, 1)) def test_sympy__geometry__point__Point3D(): from sympy.geometry.point import Point3D assert _test_args(Point3D(0, 1, 2)) def test_sympy__geometry__ellipse__Ellipse(): from sympy.geometry.ellipse import Ellipse assert _test_args(Ellipse((0, 1), 2, 3)) def test_sympy__geometry__ellipse__Circle(): from sympy.geometry.ellipse import Circle assert _test_args(Circle((0, 1), 2)) def test_sympy__geometry__parabola__Parabola(): from sympy.geometry.parabola import Parabola from sympy.geometry.line import Line assert _test_args(Parabola((0, 0), Line((2, 3), (4, 3)))) @SKIP("abstract class") def test_sympy__geometry__line__LinearEntity(): pass def test_sympy__geometry__line__Line(): from sympy.geometry.line import Line assert _test_args(Line((0, 1), (2, 3))) def test_sympy__geometry__line__Ray(): from sympy.geometry.line import Ray assert _test_args(Ray((0, 1), (2, 3))) def test_sympy__geometry__line__Segment(): from sympy.geometry.line import Segment assert _test_args(Segment((0, 1), (2, 3))) @SKIP("abstract class") def test_sympy__geometry__line__LinearEntity2D(): pass def test_sympy__geometry__line__Line2D(): from sympy.geometry.line import Line2D assert _test_args(Line2D((0, 1), (2, 3))) def test_sympy__geometry__line__Ray2D(): from sympy.geometry.line import Ray2D assert _test_args(Ray2D((0, 1), (2, 3))) def test_sympy__geometry__line__Segment2D(): from sympy.geometry.line import Segment2D assert _test_args(Segment2D((0, 1), (2, 3))) @SKIP("abstract class") def test_sympy__geometry__line__LinearEntity3D(): pass def test_sympy__geometry__line__Line3D(): from sympy.geometry.line import Line3D assert _test_args(Line3D((0, 1, 1), (2, 3, 4))) def test_sympy__geometry__line__Segment3D(): from sympy.geometry.line import Segment3D assert _test_args(Segment3D((0, 1, 1), (2, 3, 4))) def test_sympy__geometry__line__Ray3D(): from sympy.geometry.line import Ray3D assert _test_args(Ray3D((0, 1, 1), (2, 3, 4))) def test_sympy__geometry__plane__Plane(): from sympy.geometry.plane import Plane assert _test_args(Plane((1, 1, 1), (-3, 4, -2), (1, 2, 3))) def test_sympy__geometry__polygon__Polygon(): from sympy.geometry.polygon import Polygon assert _test_args(Polygon((0, 1), (2, 3), (4, 5), (6, 7))) def test_sympy__geometry__polygon__RegularPolygon(): from sympy.geometry.polygon import RegularPolygon assert _test_args(RegularPolygon((0, 1), 2, 3, 4)) def test_sympy__geometry__polygon__Triangle(): from sympy.geometry.polygon import Triangle assert _test_args(Triangle((0, 1), (2, 3), (4, 5))) def test_sympy__geometry__entity__GeometryEntity(): from sympy.geometry.entity import GeometryEntity from sympy.geometry.point import Point assert _test_args(GeometryEntity(Point(1, 0), 1, [1, 2])) @SKIP("abstract class") def test_sympy__geometry__entity__GeometrySet(): pass def test_sympy__diffgeom__diffgeom__Manifold(): from sympy.diffgeom import Manifold assert _test_args(Manifold('name', 3)) def test_sympy__diffgeom__diffgeom__Patch(): from sympy.diffgeom import Manifold, Patch assert _test_args(Patch('name', Manifold('name', 3))) def test_sympy__diffgeom__diffgeom__CoordSystem(): from sympy.diffgeom import Manifold, Patch, CoordSystem assert _test_args(CoordSystem('name', Patch('name', Manifold('name', 3)))) assert _test_args(CoordSystem('name', Patch('name', Manifold('name', 3)), [a, b, c])) def test_sympy__diffgeom__diffgeom__CoordinateSymbol(): from sympy.diffgeom import Manifold, Patch, CoordSystem, CoordinateSymbol assert _test_args(CoordinateSymbol(CoordSystem('name', Patch('name', Manifold('name', 3)), [a, b, c]), 0)) def test_sympy__diffgeom__diffgeom__Point(): from sympy.diffgeom import Manifold, Patch, CoordSystem, Point assert _test_args(Point( CoordSystem('name', Patch('name', Manifold('name', 3)), [a, b, c]), [x, y])) def test_sympy__diffgeom__diffgeom__BaseScalarField(): from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseScalarField cs = CoordSystem('name', Patch('name', Manifold('name', 3)), [a, b, c]) assert _test_args(BaseScalarField(cs, 0)) def test_sympy__diffgeom__diffgeom__BaseVectorField(): from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseVectorField cs = CoordSystem('name', Patch('name', Manifold('name', 3)), [a, b, c]) assert _test_args(BaseVectorField(cs, 0)) def test_sympy__diffgeom__diffgeom__Differential(): from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseScalarField, Differential cs = CoordSystem('name', Patch('name', Manifold('name', 3)), [a, b, c]) assert _test_args(Differential(BaseScalarField(cs, 0))) def test_sympy__diffgeom__diffgeom__Commutator(): from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseVectorField, Commutator cs = CoordSystem('name', Patch('name', Manifold('name', 3)), [a, b, c]) cs1 = CoordSystem('name1', Patch('name', Manifold('name', 3)), [a, b, c]) v = BaseVectorField(cs, 0) v1 = BaseVectorField(cs1, 0) assert _test_args(Commutator(v, v1)) def test_sympy__diffgeom__diffgeom__TensorProduct(): from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseScalarField, Differential, TensorProduct cs = CoordSystem('name', Patch('name', Manifold('name', 3)), [a, b, c]) d = Differential(BaseScalarField(cs, 0)) assert _test_args(TensorProduct(d, d)) def test_sympy__diffgeom__diffgeom__WedgeProduct(): from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseScalarField, Differential, WedgeProduct cs = CoordSystem('name', Patch('name', Manifold('name', 3)), [a, b, c]) d = Differential(BaseScalarField(cs, 0)) d1 = Differential(BaseScalarField(cs, 1)) assert _test_args(WedgeProduct(d, d1)) def test_sympy__diffgeom__diffgeom__LieDerivative(): from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseScalarField, Differential, BaseVectorField, LieDerivative cs = CoordSystem('name', Patch('name', Manifold('name', 3)), [a, b, c]) d = Differential(BaseScalarField(cs, 0)) v = BaseVectorField(cs, 0) assert _test_args(LieDerivative(v, d)) def test_sympy__diffgeom__diffgeom__BaseCovarDerivativeOp(): from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseCovarDerivativeOp cs = CoordSystem('name', Patch('name', Manifold('name', 3)), [a, b, c]) assert _test_args(BaseCovarDerivativeOp(cs, 0, [[[0, ]*3, ]*3, ]*3)) def test_sympy__diffgeom__diffgeom__CovarDerivativeOp(): from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseVectorField, CovarDerivativeOp cs = CoordSystem('name', Patch('name', Manifold('name', 3)), [a, b, c]) v = BaseVectorField(cs, 0) _test_args(CovarDerivativeOp(v, [[[0, ]*3, ]*3, ]*3)) def test_sympy__categories__baseclasses__Class(): from sympy.categories.baseclasses import Class assert _test_args(Class()) def test_sympy__categories__baseclasses__Object(): from sympy.categories import Object assert _test_args(Object("A")) @SKIP("abstract class") def test_sympy__categories__baseclasses__Morphism(): pass def test_sympy__categories__baseclasses__IdentityMorphism(): from sympy.categories import Object, IdentityMorphism assert _test_args(IdentityMorphism(Object("A"))) def test_sympy__categories__baseclasses__NamedMorphism(): from sympy.categories import Object, NamedMorphism assert _test_args(NamedMorphism(Object("A"), Object("B"), "f")) def test_sympy__categories__baseclasses__CompositeMorphism(): from sympy.categories import Object, NamedMorphism, CompositeMorphism A = Object("A") B = Object("B") C = Object("C") f = NamedMorphism(A, B, "f") g = NamedMorphism(B, C, "g") assert _test_args(CompositeMorphism(f, g)) def test_sympy__categories__baseclasses__Diagram(): from sympy.categories import Object, NamedMorphism, Diagram A = Object("A") B = Object("B") f = NamedMorphism(A, B, "f") d = Diagram([f]) assert _test_args(d) def test_sympy__categories__baseclasses__Category(): from sympy.categories import Object, NamedMorphism, Diagram, Category A = Object("A") B = Object("B") C = Object("C") f = NamedMorphism(A, B, "f") g = NamedMorphism(B, C, "g") d1 = Diagram([f, g]) d2 = Diagram([f]) K = Category("K", commutative_diagrams=[d1, d2]) assert _test_args(K) def test_sympy__ntheory__factor___totient(): from sympy.ntheory.factor_ import totient k = symbols('k', integer=True) t = totient(k) assert _test_args(t) def test_sympy__ntheory__factor___reduced_totient(): from sympy.ntheory.factor_ import reduced_totient k = symbols('k', integer=True) t = reduced_totient(k) assert _test_args(t) def test_sympy__ntheory__factor___divisor_sigma(): from sympy.ntheory.factor_ import divisor_sigma k = symbols('k', integer=True) n = symbols('n', integer=True) t = divisor_sigma(n, k) assert _test_args(t) def test_sympy__ntheory__factor___udivisor_sigma(): from sympy.ntheory.factor_ import udivisor_sigma k = symbols('k', integer=True) n = symbols('n', integer=True) t = udivisor_sigma(n, k) assert _test_args(t) def test_sympy__ntheory__factor___primenu(): from sympy.ntheory.factor_ import primenu n = symbols('n', integer=True) t = primenu(n) assert _test_args(t) def test_sympy__ntheory__factor___primeomega(): from sympy.ntheory.factor_ import primeomega n = symbols('n', integer=True) t = primeomega(n) assert _test_args(t) def test_sympy__ntheory__residue_ntheory__mobius(): from sympy.ntheory import mobius assert _test_args(mobius(2)) def test_sympy__ntheory__generate__primepi(): from sympy.ntheory import primepi n = symbols('n') t = primepi(n) assert _test_args(t) def test_sympy__physics__optics__waves__TWave(): from sympy.physics.optics import TWave A, f, phi = symbols('A, f, phi') assert _test_args(TWave(A, f, phi)) def test_sympy__physics__optics__gaussopt__BeamParameter(): from sympy.physics.optics import BeamParameter assert _test_args(BeamParameter(530e-9, 1, w=1e-3, n=1)) def test_sympy__physics__optics__medium__Medium(): from sympy.physics.optics import Medium assert _test_args(Medium('m')) def test_sympy__physics__optics__medium__MediumN(): from sympy.physics.optics.medium import Medium assert _test_args(Medium('m', n=2)) def test_sympy__physics__optics__medium__MediumPP(): from sympy.physics.optics.medium import Medium assert _test_args(Medium('m', permittivity=2, permeability=2)) def test_sympy__tensor__array__expressions__array_expressions__ArrayContraction(): from sympy.tensor.array.expressions.array_expressions import ArrayContraction from sympy.tensor.indexed import IndexedBase A = symbols("A", cls=IndexedBase) assert _test_args(ArrayContraction(A, (0, 1))) def test_sympy__tensor__array__expressions__array_expressions__ArrayDiagonal(): from sympy.tensor.array.expressions.array_expressions import ArrayDiagonal from sympy.tensor.indexed import IndexedBase A = symbols("A", cls=IndexedBase) assert _test_args(ArrayDiagonal(A, (0, 1))) def test_sympy__tensor__array__expressions__array_expressions__ArrayTensorProduct(): from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct from sympy.tensor.indexed import IndexedBase A, B = symbols("A B", cls=IndexedBase) assert _test_args(ArrayTensorProduct(A, B)) def test_sympy__tensor__array__expressions__array_expressions__ArrayAdd(): from sympy.tensor.array.expressions.array_expressions import ArrayAdd from sympy.tensor.indexed import IndexedBase A, B = symbols("A B", cls=IndexedBase) assert _test_args(ArrayAdd(A, B)) def test_sympy__tensor__array__expressions__array_expressions__PermuteDims(): from sympy.tensor.array.expressions.array_expressions import PermuteDims A = MatrixSymbol("A", 4, 4) assert _test_args(PermuteDims(A, (1, 0))) def test_sympy__tensor__array__expressions__array_expressions__ArrayElementwiseApplyFunc(): from sympy.tensor.array.expressions.array_expressions import ArraySymbol, ArrayElementwiseApplyFunc A = ArraySymbol("A", (4,)) assert _test_args(ArrayElementwiseApplyFunc(exp, A)) def test_sympy__tensor__array__expressions__array_expressions__Reshape(): from sympy.tensor.array.expressions.array_expressions import ArraySymbol, Reshape A = ArraySymbol("A", (4,)) assert _test_args(Reshape(A, (2, 2))) def test_sympy__codegen__ast__Assignment(): from sympy.codegen.ast import Assignment assert _test_args(Assignment(x, y)) def test_sympy__codegen__cfunctions__expm1(): from sympy.codegen.cfunctions import expm1 assert _test_args(expm1(x)) def test_sympy__codegen__cfunctions__log1p(): from sympy.codegen.cfunctions import log1p assert _test_args(log1p(x)) def test_sympy__codegen__cfunctions__exp2(): from sympy.codegen.cfunctions import exp2 assert _test_args(exp2(x)) def test_sympy__codegen__cfunctions__log2(): from sympy.codegen.cfunctions import log2 assert _test_args(log2(x)) def test_sympy__codegen__cfunctions__fma(): from sympy.codegen.cfunctions import fma assert _test_args(fma(x, y, z)) def test_sympy__codegen__cfunctions__log10(): from sympy.codegen.cfunctions import log10 assert _test_args(log10(x)) def test_sympy__codegen__cfunctions__Sqrt(): from sympy.codegen.cfunctions import Sqrt assert _test_args(Sqrt(x)) def test_sympy__codegen__cfunctions__Cbrt(): from sympy.codegen.cfunctions import Cbrt assert _test_args(Cbrt(x)) def test_sympy__codegen__cfunctions__hypot(): from sympy.codegen.cfunctions import hypot assert _test_args(hypot(x, y)) def test_sympy__codegen__fnodes__FFunction(): from sympy.codegen.fnodes import FFunction assert _test_args(FFunction('f')) def test_sympy__codegen__fnodes__F95Function(): from sympy.codegen.fnodes import F95Function assert _test_args(F95Function('f')) def test_sympy__codegen__fnodes__isign(): from sympy.codegen.fnodes import isign assert _test_args(isign(1, x)) def test_sympy__codegen__fnodes__dsign(): from sympy.codegen.fnodes import dsign assert _test_args(dsign(1, x)) def test_sympy__codegen__fnodes__cmplx(): from sympy.codegen.fnodes import cmplx assert _test_args(cmplx(x, y)) def test_sympy__codegen__fnodes__kind(): from sympy.codegen.fnodes import kind assert _test_args(kind(x)) def test_sympy__codegen__fnodes__merge(): from sympy.codegen.fnodes import merge assert _test_args(merge(1, 2, Eq(x, 0))) def test_sympy__codegen__fnodes___literal(): from sympy.codegen.fnodes import _literal assert _test_args(_literal(1)) def test_sympy__codegen__fnodes__literal_sp(): from sympy.codegen.fnodes import literal_sp assert _test_args(literal_sp(1)) def test_sympy__codegen__fnodes__literal_dp(): from sympy.codegen.fnodes import literal_dp assert _test_args(literal_dp(1)) def test_sympy__codegen__matrix_nodes__MatrixSolve(): from sympy.matrices import MatrixSymbol from sympy.codegen.matrix_nodes import MatrixSolve A = MatrixSymbol('A', 3, 3) v = MatrixSymbol('x', 3, 1) assert _test_args(MatrixSolve(A, v)) def test_sympy__vector__coordsysrect__CoordSys3D(): from sympy.vector.coordsysrect import CoordSys3D assert _test_args(CoordSys3D('C')) def test_sympy__vector__point__Point(): from sympy.vector.point import Point assert _test_args(Point('P')) def test_sympy__vector__basisdependent__BasisDependent(): #from sympy.vector.basisdependent import BasisDependent #These classes have been created to maintain an OOP hierarchy #for Vectors and Dyadics. Are NOT meant to be initialized pass def test_sympy__vector__basisdependent__BasisDependentMul(): #from sympy.vector.basisdependent import BasisDependentMul #These classes have been created to maintain an OOP hierarchy #for Vectors and Dyadics. Are NOT meant to be initialized pass def test_sympy__vector__basisdependent__BasisDependentAdd(): #from sympy.vector.basisdependent import BasisDependentAdd #These classes have been created to maintain an OOP hierarchy #for Vectors and Dyadics. Are NOT meant to be initialized pass def test_sympy__vector__basisdependent__BasisDependentZero(): #from sympy.vector.basisdependent import BasisDependentZero #These classes have been created to maintain an OOP hierarchy #for Vectors and Dyadics. Are NOT meant to be initialized pass def test_sympy__vector__vector__BaseVector(): from sympy.vector.vector import BaseVector from sympy.vector.coordsysrect import CoordSys3D C = CoordSys3D('C') assert _test_args(BaseVector(0, C, ' ', ' ')) def test_sympy__vector__vector__VectorAdd(): from sympy.vector.vector import VectorAdd, VectorMul from sympy.vector.coordsysrect import CoordSys3D C = CoordSys3D('C') from sympy.abc import a, b, c, x, y, z v1 = a*C.i + b*C.j + c*C.k v2 = x*C.i + y*C.j + z*C.k assert _test_args(VectorAdd(v1, v2)) assert _test_args(VectorMul(x, v1)) def test_sympy__vector__vector__VectorMul(): from sympy.vector.vector import VectorMul from sympy.vector.coordsysrect import CoordSys3D C = CoordSys3D('C') from sympy.abc import a assert _test_args(VectorMul(a, C.i)) def test_sympy__vector__vector__VectorZero(): from sympy.vector.vector import VectorZero assert _test_args(VectorZero()) def test_sympy__vector__vector__Vector(): #from sympy.vector.vector import Vector #Vector is never to be initialized using args pass def test_sympy__vector__vector__Cross(): from sympy.vector.vector import Cross from sympy.vector.coordsysrect import CoordSys3D C = CoordSys3D('C') _test_args(Cross(C.i, C.j)) def test_sympy__vector__vector__Dot(): from sympy.vector.vector import Dot from sympy.vector.coordsysrect import CoordSys3D C = CoordSys3D('C') _test_args(Dot(C.i, C.j)) def test_sympy__vector__dyadic__Dyadic(): #from sympy.vector.dyadic import Dyadic #Dyadic is never to be initialized using args pass def test_sympy__vector__dyadic__BaseDyadic(): from sympy.vector.dyadic import BaseDyadic from sympy.vector.coordsysrect import CoordSys3D C = CoordSys3D('C') assert _test_args(BaseDyadic(C.i, C.j)) def test_sympy__vector__dyadic__DyadicMul(): from sympy.vector.dyadic import BaseDyadic, DyadicMul from sympy.vector.coordsysrect import CoordSys3D C = CoordSys3D('C') assert _test_args(DyadicMul(3, BaseDyadic(C.i, C.j))) def test_sympy__vector__dyadic__DyadicAdd(): from sympy.vector.dyadic import BaseDyadic, DyadicAdd from sympy.vector.coordsysrect import CoordSys3D C = CoordSys3D('C') assert _test_args(2 * DyadicAdd(BaseDyadic(C.i, C.i), BaseDyadic(C.i, C.j))) def test_sympy__vector__dyadic__DyadicZero(): from sympy.vector.dyadic import DyadicZero assert _test_args(DyadicZero()) def test_sympy__vector__deloperator__Del(): from sympy.vector.deloperator import Del assert _test_args(Del()) def test_sympy__vector__implicitregion__ImplicitRegion(): from sympy.vector.implicitregion import ImplicitRegion from sympy.abc import x, y assert _test_args(ImplicitRegion((x, y), y**3 - 4*x)) def test_sympy__vector__integrals__ParametricIntegral(): from sympy.vector.integrals import ParametricIntegral from sympy.vector.parametricregion import ParametricRegion from sympy.vector.coordsysrect import CoordSys3D C = CoordSys3D('C') assert _test_args(ParametricIntegral(C.y*C.i - 10*C.j,\ ParametricRegion((x, y), (x, 1, 3), (y, -2, 2)))) def test_sympy__vector__operators__Curl(): from sympy.vector.operators import Curl from sympy.vector.coordsysrect import CoordSys3D C = CoordSys3D('C') assert _test_args(Curl(C.i)) def test_sympy__vector__operators__Laplacian(): from sympy.vector.operators import Laplacian from sympy.vector.coordsysrect import CoordSys3D C = CoordSys3D('C') assert _test_args(Laplacian(C.i)) def test_sympy__vector__operators__Divergence(): from sympy.vector.operators import Divergence from sympy.vector.coordsysrect import CoordSys3D C = CoordSys3D('C') assert _test_args(Divergence(C.i)) def test_sympy__vector__operators__Gradient(): from sympy.vector.operators import Gradient from sympy.vector.coordsysrect import CoordSys3D C = CoordSys3D('C') assert _test_args(Gradient(C.x)) def test_sympy__vector__orienters__Orienter(): #from sympy.vector.orienters import Orienter #Not to be initialized pass def test_sympy__vector__orienters__ThreeAngleOrienter(): #from sympy.vector.orienters import ThreeAngleOrienter #Not to be initialized pass def test_sympy__vector__orienters__AxisOrienter(): from sympy.vector.orienters import AxisOrienter from sympy.vector.coordsysrect import CoordSys3D C = CoordSys3D('C') assert _test_args(AxisOrienter(x, C.i)) def test_sympy__vector__orienters__BodyOrienter(): from sympy.vector.orienters import BodyOrienter assert _test_args(BodyOrienter(x, y, z, '123')) def test_sympy__vector__orienters__SpaceOrienter(): from sympy.vector.orienters import SpaceOrienter assert _test_args(SpaceOrienter(x, y, z, '123')) def test_sympy__vector__orienters__QuaternionOrienter(): from sympy.vector.orienters import QuaternionOrienter a, b, c, d = symbols('a b c d') assert _test_args(QuaternionOrienter(a, b, c, d)) def test_sympy__vector__parametricregion__ParametricRegion(): from sympy.abc import t from sympy.vector.parametricregion import ParametricRegion assert _test_args(ParametricRegion((t, t**3), (t, 0, 2))) def test_sympy__vector__scalar__BaseScalar(): from sympy.vector.scalar import BaseScalar from sympy.vector.coordsysrect import CoordSys3D C = CoordSys3D('C') assert _test_args(BaseScalar(0, C, ' ', ' ')) def test_sympy__physics__wigner__Wigner3j(): from sympy.physics.wigner import Wigner3j assert _test_args(Wigner3j(0, 0, 0, 0, 0, 0)) def test_sympy__integrals__rubi__symbol__matchpyWC(): from sympy.integrals.rubi.symbol import matchpyWC assert _test_args(matchpyWC(1, True, 'a')) def test_sympy__integrals__rubi__utility_function__rubi_unevaluated_expr(): from sympy.integrals.rubi.utility_function import rubi_unevaluated_expr a = symbols('a') assert _test_args(rubi_unevaluated_expr(a)) def test_sympy__integrals__rubi__utility_function__rubi_exp(): from sympy.integrals.rubi.utility_function import rubi_exp assert _test_args(rubi_exp(5)) def test_sympy__integrals__rubi__utility_function__rubi_log(): from sympy.integrals.rubi.utility_function import rubi_log assert _test_args(rubi_log(5)) def test_sympy__integrals__rubi__utility_function__Int(): from sympy.integrals.rubi.utility_function import Int assert _test_args(Int(5, x)) def test_sympy__integrals__rubi__utility_function__Util_Coefficient(): from sympy.integrals.rubi.utility_function import Util_Coefficient a, x = symbols('a x') assert _test_args(Util_Coefficient(a, x)) def test_sympy__integrals__rubi__utility_function__Gamma(): from sympy.integrals.rubi.utility_function import Gamma assert _test_args(Gamma(x)) def test_sympy__integrals__rubi__utility_function__Util_Part(): from sympy.integrals.rubi.utility_function import Util_Part a, b = symbols('a b') assert _test_args(Util_Part(a + b, 0)) def test_sympy__integrals__rubi__utility_function__PolyGamma(): from sympy.integrals.rubi.utility_function import PolyGamma assert _test_args(PolyGamma(1, x)) def test_sympy__integrals__rubi__utility_function__ProductLog(): from sympy.integrals.rubi.utility_function import ProductLog assert _test_args(ProductLog(1)) def test_sympy__combinatorics__schur_number__SchurNumber(): from sympy.combinatorics.schur_number import SchurNumber assert _test_args(SchurNumber(x)) def test_sympy__combinatorics__perm_groups__SymmetricPermutationGroup(): from sympy.combinatorics.perm_groups import SymmetricPermutationGroup assert _test_args(SymmetricPermutationGroup(5)) def test_sympy__combinatorics__perm_groups__Coset(): from sympy.combinatorics.permutations import Permutation from sympy.combinatorics.perm_groups import PermutationGroup, Coset a = Permutation(1, 2) b = Permutation(0, 1) G = PermutationGroup([a, b]) assert _test_args(Coset(a, G))
9d117e679ead093f1a9e7ffa11a9a9d3bd5bd03a42df0c522ec82731145c5861
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)) # 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'))
2cdf38bb676faf5788be522609cdc8bc1c2ed13f4b7dc55118223263e150c785
from sympy.concrete.summations import Sum from sympy.core.basic import Basic, _aresame from sympy.core.cache import clear_cache from sympy.core.containers import Dict, Tuple from sympy.core.expr import Expr, unchanged from sympy.core.function import (Subs, Function, diff, Lambda, expand, nfloat, Derivative) from sympy.core.numbers import E, Float, zoo, Rational, pi, I, oo, nan from sympy.core.power import Pow from sympy.core.relational import Eq from sympy.core.singleton import S from sympy.core.symbol import symbols, Dummy, Symbol from sympy.functions.elementary.complexes import im, re from sympy.functions.elementary.exponential import log, exp from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.piecewise import Piecewise from sympy.functions.elementary.trigonometric import sin, cos, acos from sympy.functions.special.error_functions import expint from sympy.functions.special.gamma_functions import loggamma, polygamma from sympy.matrices.dense import Matrix from sympy.printing.str import sstr from sympy.series.order import O from sympy.tensor.indexed import Indexed from sympy.core.function import (PoleError, _mexpand, arity, BadSignatureError, BadArgumentsError) from sympy.core.parameters import _exp_is_pow from sympy.core.sympify import sympify from sympy.matrices import MutableMatrix, ImmutableMatrix from sympy.sets.sets import FiniteSet from sympy.solvers.solveset import solveset from sympy.tensor.array import NDimArray from sympy.utilities.iterables import subsets, variations from sympy.testing.pytest import XFAIL, raises, warns_deprecated_sympy, _both_exp_pow from sympy.abc import t, w, x, y, z f, g, h = symbols('f g h', cls=Function) _xi_1, _xi_2, _xi_3 = [Dummy() for i in range(3)] def test_f_expand_complex(): x = Symbol('x', real=True) assert f(x).expand(complex=True) == I*im(f(x)) + re(f(x)) assert exp(x).expand(complex=True) == exp(x) assert exp(I*x).expand(complex=True) == cos(x) + I*sin(x) assert exp(z).expand(complex=True) == cos(im(z))*exp(re(z)) + \ I*sin(im(z))*exp(re(z)) def test_bug1(): e = sqrt(-log(w)) assert e.subs(log(w), -x) == sqrt(x) e = sqrt(-5*log(w)) assert e.subs(log(w), -x) == sqrt(5*x) def test_general_function(): nu = Function('nu') e = nu(x) edx = e.diff(x) edy = e.diff(y) edxdx = e.diff(x).diff(x) edxdy = e.diff(x).diff(y) assert e == nu(x) assert edx != nu(x) assert edx == diff(nu(x), x) assert edy == 0 assert edxdx == diff(diff(nu(x), x), x) assert edxdy == 0 def test_general_function_nullary(): nu = Function('nu') e = nu() edx = e.diff(x) edxdx = e.diff(x).diff(x) assert e == nu() assert edx != nu() assert edx == 0 assert edxdx == 0 def test_derivative_subs_bug(): e = diff(g(x), x) assert e.subs(g(x), f(x)) != e assert e.subs(g(x), f(x)) == Derivative(f(x), x) assert e.subs(g(x), -f(x)) == Derivative(-f(x), x) assert e.subs(x, y) == Derivative(g(y), y) def test_derivative_subs_self_bug(): d = diff(f(x), x) assert d.subs(d, y) == y def test_derivative_linearity(): assert diff(-f(x), x) == -diff(f(x), x) assert diff(8*f(x), x) == 8*diff(f(x), x) assert diff(8*f(x), x) != 7*diff(f(x), x) assert diff(8*f(x)*x, x) == 8*f(x) + 8*x*diff(f(x), x) assert diff(8*f(x)*y*x, x).expand() == 8*y*f(x) + 8*y*x*diff(f(x), x) def test_derivative_evaluate(): assert Derivative(sin(x), x) != diff(sin(x), x) assert Derivative(sin(x), x).doit() == diff(sin(x), x) assert Derivative(Derivative(f(x), x), x) == diff(f(x), x, x) assert Derivative(sin(x), x, 0) == sin(x) assert Derivative(sin(x), (x, y), (x, -y)) == sin(x) def test_diff_symbols(): assert diff(f(x, y, z), x, y, z) == Derivative(f(x, y, z), x, y, z) assert diff(f(x, y, z), x, x, x) == Derivative(f(x, y, z), x, x, x) == Derivative(f(x, y, z), (x, 3)) assert diff(f(x, y, z), x, 3) == Derivative(f(x, y, z), x, 3) # issue 5028 assert [diff(-z + x/y, sym) for sym in (z, x, y)] == [-1, 1/y, -x/y**2] assert diff(f(x, y, z), x, y, z, 2) == Derivative(f(x, y, z), x, y, z, z) assert diff(f(x, y, z), x, y, z, 2, evaluate=False) == \ Derivative(f(x, y, z), x, y, z, z) assert Derivative(f(x, y, z), x, y, z)._eval_derivative(z) == \ Derivative(f(x, y, z), x, y, z, z) assert Derivative(Derivative(f(x, y, z), x), y)._eval_derivative(z) == \ Derivative(f(x, y, z), x, y, z) raises(TypeError, lambda: cos(x).diff((x, y)).variables) assert cos(x).diff((x, y))._wrt_variables == [x] # issue 23222 assert sympify("a*x+b").diff("x") == sympify("a") def test_Function(): class myfunc(Function): @classmethod def eval(cls): # zero args return assert myfunc.nargs == FiniteSet(0) assert myfunc().nargs == FiniteSet(0) raises(TypeError, lambda: myfunc(x).nargs) class myfunc(Function): @classmethod def eval(cls, x): # one arg return assert myfunc.nargs == FiniteSet(1) assert myfunc(x).nargs == FiniteSet(1) raises(TypeError, lambda: myfunc(x, y).nargs) class myfunc(Function): @classmethod def eval(cls, *x): # star args return assert myfunc.nargs == S.Naturals0 assert myfunc(x).nargs == S.Naturals0 def test_nargs(): f = Function('f') assert f.nargs == S.Naturals0 assert f(1).nargs == S.Naturals0 assert Function('f', nargs=2)(1, 2).nargs == FiniteSet(2) assert sin.nargs == FiniteSet(1) assert sin(2).nargs == FiniteSet(1) assert log.nargs == FiniteSet(1, 2) assert log(2).nargs == FiniteSet(1, 2) assert Function('f', nargs=2).nargs == FiniteSet(2) assert Function('f', nargs=0).nargs == FiniteSet(0) assert Function('f', nargs=(0, 1)).nargs == FiniteSet(0, 1) assert Function('f', nargs=None).nargs == S.Naturals0 raises(ValueError, lambda: Function('f', nargs=())) def test_nargs_inheritance(): class f1(Function): nargs = 2 class f2(f1): pass class f3(f2): pass class f4(f3): nargs = 1,2 class f5(f4): pass class f6(f5): pass class f7(f6): nargs=None class f8(f7): pass class f9(f8): pass class f10(f9): nargs = 1 class f11(f10): pass assert f1.nargs == FiniteSet(2) assert f2.nargs == FiniteSet(2) assert f3.nargs == FiniteSet(2) assert f4.nargs == FiniteSet(1, 2) assert f5.nargs == FiniteSet(1, 2) assert f6.nargs == FiniteSet(1, 2) assert f7.nargs == S.Naturals0 assert f8.nargs == S.Naturals0 assert f9.nargs == S.Naturals0 assert f10.nargs == FiniteSet(1) assert f11.nargs == FiniteSet(1) def test_arity(): f = lambda x, y: 1 assert arity(f) == 2 def f(x, y, z=None): pass assert arity(f) == (2, 3) assert arity(lambda *x: x) is None assert arity(log) == (1, 2) def test_Lambda(): e = Lambda(x, x**2) assert e(4) == 16 assert e(x) == x**2 assert e(y) == y**2 assert Lambda((), 42)() == 42 assert unchanged(Lambda, (), 42) assert Lambda((), 42) != Lambda((), 43) assert Lambda((), f(x))() == f(x) assert Lambda((), 42).nargs == FiniteSet(0) assert unchanged(Lambda, (x,), x**2) assert Lambda(x, x**2) == Lambda((x,), x**2) assert Lambda(x, x**2) != Lambda(x, x**2 + 1) assert Lambda((x, y), x**y) != Lambda((y, x), y**x) assert Lambda((x, y), x**y) != Lambda((x, y), y**x) assert Lambda((x, y), x**y)(x, y) == x**y assert Lambda((x, y), x**y)(3, 3) == 3**3 assert Lambda((x, y), x**y)(x, 3) == x**3 assert Lambda((x, y), x**y)(3, y) == 3**y assert Lambda(x, f(x))(x) == f(x) assert Lambda(x, x**2)(e(x)) == x**4 assert e(e(x)) == x**4 x1, x2 = (Indexed('x', i) for i in (1, 2)) assert Lambda((x1, x2), x1 + x2)(x, y) == x + y assert Lambda((x, y), x + y).nargs == FiniteSet(2) p = x, y, z, t assert Lambda(p, t*(x + y + z))(*p) == t * (x + y + z) eq = Lambda(x, 2*x) + Lambda(y, 2*y) assert eq != 2*Lambda(x, 2*x) assert eq.as_dummy() == 2*Lambda(x, 2*x).as_dummy() assert Lambda(x, 2*x) not in [ Lambda(x, x) ] raises(BadSignatureError, lambda: Lambda(1, x)) assert Lambda(x, 1)(1) is S.One raises(BadSignatureError, lambda: Lambda((x, x), x + 2)) raises(BadSignatureError, lambda: Lambda(((x, x), y), x)) raises(BadSignatureError, lambda: Lambda(((y, x), x), x)) raises(BadSignatureError, lambda: Lambda(((y, 1), 2), x)) with warns_deprecated_sympy(): assert Lambda([x, y], x+y) == Lambda((x, y), x+y) flam = Lambda(((x, y),), x + y) assert flam((2, 3)) == 5 flam = Lambda(((x, y), z), x + y + z) assert flam((2, 3), 1) == 6 flam = Lambda((((x, y), z),), x + y + z) assert flam(((2, 3), 1)) == 6 raises(BadArgumentsError, lambda: flam(1, 2, 3)) flam = Lambda( (x,), (x, x)) assert flam(1,) == (1, 1) assert flam((1,)) == ((1,), (1,)) flam = Lambda( ((x,),), (x, x)) raises(BadArgumentsError, lambda: flam(1)) assert flam((1,)) == (1, 1) # Previously TypeError was raised so this is potentially needed for # backwards compatibility. assert issubclass(BadSignatureError, TypeError) assert issubclass(BadArgumentsError, TypeError) # These are tested to see they don't raise: hash(Lambda(x, 2*x)) hash(Lambda(x, x)) # IdentityFunction subclass def test_IdentityFunction(): assert Lambda(x, x) is Lambda(y, y) is S.IdentityFunction assert Lambda(x, 2*x) is not S.IdentityFunction assert Lambda((x, y), x) is not S.IdentityFunction def test_Lambda_symbols(): assert Lambda(x, 2*x).free_symbols == set() assert Lambda(x, x*y).free_symbols == {y} assert Lambda((), 42).free_symbols == set() assert Lambda((), x*y).free_symbols == {x,y} def test_functionclas_symbols(): assert f.free_symbols == set() def test_Lambda_arguments(): raises(TypeError, lambda: Lambda(x, 2*x)(x, y)) raises(TypeError, lambda: Lambda((x, y), x + y)(x)) raises(TypeError, lambda: Lambda((), 42)(x)) def test_Lambda_equality(): assert Lambda((x, y), 2*x) == Lambda((x, y), 2*x) # these, of course, should never be equal assert Lambda(x, 2*x) != Lambda((x, y), 2*x) assert Lambda(x, 2*x) != 2*x # But it is tempting to want expressions that differ only # in bound symbols to compare the same. But this is not what # Python's `==` is intended to do; two objects that compare # as equal means that they are indistibguishable and cache to the # same value. We wouldn't want to expression that are # mathematically the same but written in different variables to be # interchanged else what is the point of allowing for different # variable names? assert Lambda(x, 2*x) != Lambda(y, 2*y) def test_Subs(): assert Subs(1, (), ()) is S.One # check null subs influence on hashing assert Subs(x, y, z) != Subs(x, y, 1) # neutral subs works assert Subs(x, x, 1).subs(x, y).has(y) # self mapping var/point assert Subs(Derivative(f(x), (x, 2)), x, x).doit() == f(x).diff(x, x) assert Subs(x, x, 0).has(x) # it's a structural answer assert not Subs(x, x, 0).free_symbols assert Subs(Subs(x + y, x, 2), y, 1) == Subs(x + y, (x, y), (2, 1)) assert Subs(x, (x,), (0,)) == Subs(x, x, 0) assert Subs(x, x, 0) == Subs(y, y, 0) assert Subs(x, x, 0).subs(x, 1) == Subs(x, x, 0) assert Subs(y, x, 0).subs(y, 1) == Subs(1, x, 0) assert Subs(f(x), x, 0).doit() == f(0) assert Subs(f(x**2), x**2, 0).doit() == f(0) assert Subs(f(x, y, z), (x, y, z), (0, 1, 1)) != \ Subs(f(x, y, z), (x, y, z), (0, 0, 1)) assert Subs(x, y, 2).subs(x, y).doit() == 2 assert Subs(f(x, y), (x, y, z), (0, 1, 1)) != \ Subs(f(x, y) + z, (x, y, z), (0, 1, 0)) assert Subs(f(x, y), (x, y), (0, 1)).doit() == f(0, 1) assert Subs(Subs(f(x, y), x, 0), y, 1).doit() == f(0, 1) raises(ValueError, lambda: Subs(f(x, y), (x, y), (0, 0, 1))) raises(ValueError, lambda: Subs(f(x, y), (x, x, y), (0, 0, 1))) assert len(Subs(f(x, y), (x, y), (0, 1)).variables) == 2 assert Subs(f(x, y), (x, y), (0, 1)).point == Tuple(0, 1) assert Subs(f(x), x, 0) == Subs(f(y), y, 0) assert Subs(f(x, y), (x, y), (0, 1)) == Subs(f(x, y), (y, x), (1, 0)) assert Subs(f(x)*y, (x, y), (0, 1)) == Subs(f(y)*x, (y, x), (0, 1)) assert Subs(f(x)*y, (x, y), (1, 1)) == Subs(f(y)*x, (x, y), (1, 1)) assert Subs(f(x), x, 0).subs(x, 1).doit() == f(0) assert Subs(f(x), x, y).subs(y, 0) == Subs(f(x), x, 0) assert Subs(y*f(x), x, y).subs(y, 2) == Subs(2*f(x), x, 2) assert (2 * Subs(f(x), x, 0)).subs(Subs(f(x), x, 0), y) == 2*y assert Subs(f(x), x, 0).free_symbols == set() assert Subs(f(x, y), x, z).free_symbols == {y, z} assert Subs(f(x).diff(x), x, 0).doit(), Subs(f(x).diff(x), x, 0) assert Subs(1 + f(x).diff(x), x, 0).doit(), 1 + Subs(f(x).diff(x), x, 0) assert Subs(y*f(x, y).diff(x), (x, y), (0, 2)).doit() == \ 2*Subs(Derivative(f(x, 2), x), x, 0) assert Subs(y**2*f(x), x, 0).diff(y) == 2*y*f(0) e = Subs(y**2*f(x), x, y) assert e.diff(y) == e.doit().diff(y) == y**2*Derivative(f(y), y) + 2*y*f(y) assert Subs(f(x), x, 0) + Subs(f(x), x, 0) == 2*Subs(f(x), x, 0) e1 = Subs(z*f(x), x, 1) e2 = Subs(z*f(y), y, 1) assert e1 + e2 == 2*e1 assert e1.__hash__() == e2.__hash__() assert Subs(z*f(x + 1), x, 1) not in [ e1, e2 ] assert Derivative(f(x), x).subs(x, g(x)) == Derivative(f(g(x)), g(x)) assert Derivative(f(x), x).subs(x, x + y) == Subs(Derivative(f(x), x), x, x + y) assert Subs(f(x)*cos(y) + z, (x, y), (0, pi/3)).n(2) == \ Subs(f(x)*cos(y) + z, (x, y), (0, pi/3)).evalf(2) == \ z + Rational('1/2').n(2)*f(0) assert f(x).diff(x).subs(x, 0).subs(x, y) == f(x).diff(x).subs(x, 0) assert (x*f(x).diff(x).subs(x, 0)).subs(x, y) == y*f(x).diff(x).subs(x, 0) assert Subs(Derivative(g(x)**2, g(x), x), g(x), exp(x) ).doit() == 2*exp(x) assert Subs(Derivative(g(x)**2, g(x), x), g(x), exp(x) ).doit(deep=False) == 2*Derivative(exp(x), x) assert Derivative(f(x, g(x)), x).doit() == Derivative( f(x, g(x)), g(x))*Derivative(g(x), x) + Subs(Derivative( f(y, g(x)), y), y, x) def test_doitdoit(): done = Derivative(f(x, g(x)), x, g(x)).doit() assert done == done.doit() @XFAIL def test_Subs2(): # this reflects a limitation of subs(), probably won't fix assert Subs(f(x), x**2, x).doit() == f(sqrt(x)) def test_expand_function(): assert expand(x + y) == x + y assert expand(x + y, complex=True) == I*im(x) + I*im(y) + re(x) + re(y) assert expand((x + y)**11, modulus=11) == x**11 + y**11 def test_function_comparable(): assert sin(x).is_comparable is False assert cos(x).is_comparable is False assert sin(Float('0.1')).is_comparable is True assert cos(Float('0.1')).is_comparable is True assert sin(E).is_comparable is True assert cos(E).is_comparable is True assert sin(Rational(1, 3)).is_comparable is True assert cos(Rational(1, 3)).is_comparable is True def test_function_comparable_infinities(): assert sin(oo).is_comparable is False assert sin(-oo).is_comparable is False assert sin(zoo).is_comparable is False assert sin(nan).is_comparable is False def test_deriv1(): # These all require derivatives evaluated at a point (issue 4719) to work. # See issue 4624 assert f(2*x).diff(x) == 2*Subs(Derivative(f(x), x), x, 2*x) assert (f(x)**3).diff(x) == 3*f(x)**2*f(x).diff(x) assert (f(2*x)**3).diff(x) == 6*f(2*x)**2*Subs( Derivative(f(x), x), x, 2*x) assert f(2 + x).diff(x) == Subs(Derivative(f(x), x), x, x + 2) assert f(2 + 3*x).diff(x) == 3*Subs( Derivative(f(x), x), x, 3*x + 2) assert f(3*sin(x)).diff(x) == 3*cos(x)*Subs( Derivative(f(x), x), x, 3*sin(x)) # See issue 8510 assert f(x, x + z).diff(x) == ( Subs(Derivative(f(y, x + z), y), y, x) + Subs(Derivative(f(x, y), y), y, x + z)) assert f(x, x**2).diff(x) == ( 2*x*Subs(Derivative(f(x, y), y), y, x**2) + Subs(Derivative(f(y, x**2), y), y, x)) # but Subs is not always necessary assert f(x, g(y)).diff(g(y)) == Derivative(f(x, g(y)), g(y)) def test_deriv2(): assert (x**3).diff(x) == 3*x**2 assert (x**3).diff(x, evaluate=False) != 3*x**2 assert (x**3).diff(x, evaluate=False) == Derivative(x**3, x) assert diff(x**3, x) == 3*x**2 assert diff(x**3, x, evaluate=False) != 3*x**2 assert diff(x**3, x, evaluate=False) == Derivative(x**3, x) def test_func_deriv(): assert f(x).diff(x) == Derivative(f(x), x) # issue 4534 assert f(x, y).diff(x, y) - f(x, y).diff(y, x) == 0 assert Derivative(f(x, y), x, y).args[1:] == ((x, 1), (y, 1)) assert Derivative(f(x, y), y, x).args[1:] == ((y, 1), (x, 1)) assert (Derivative(f(x, y), x, y) - Derivative(f(x, y), y, x)).doit() == 0 def test_suppressed_evaluation(): a = sin(0, evaluate=False) assert a != 0 assert a.func is sin assert a.args == (0,) def test_function_evalf(): def eq(a, b, eps): return abs(a - b) < eps assert eq(sin(1).evalf(15), Float("0.841470984807897"), 1e-13) assert eq( sin(2).evalf(25), Float("0.9092974268256816953960199", 25), 1e-23) assert eq(sin(1 + I).evalf( 15), Float("1.29845758141598") + Float("0.634963914784736")*I, 1e-13) assert eq(exp(1 + I).evalf(15), Float( "1.46869393991588") + Float("2.28735528717884239")*I, 1e-13) assert eq(exp(-0.5 + 1.5*I).evalf(15), Float( "0.0429042815937374") + Float("0.605011292285002")*I, 1e-13) assert eq(log(pi + sqrt(2)*I).evalf( 15), Float("1.23699044022052") + Float("0.422985442737893")*I, 1e-13) assert eq(cos(100).evalf(15), Float("0.86231887228768"), 1e-13) def test_extensibility_eval(): class MyFunc(Function): @classmethod def eval(cls, *args): return (0, 0, 0) assert MyFunc(0) == (0, 0, 0) @_both_exp_pow def test_function_non_commutative(): x = Symbol('x', commutative=False) assert f(x).is_commutative is False assert sin(x).is_commutative is False assert exp(x).is_commutative is False assert log(x).is_commutative is False assert f(x).is_complex is False assert sin(x).is_complex is False assert exp(x).is_complex is False assert log(x).is_complex is False def test_function_complex(): x = Symbol('x', complex=True) xzf = Symbol('x', complex=True, zero=False) assert f(x).is_commutative is True assert sin(x).is_commutative is True assert exp(x).is_commutative is True assert log(x).is_commutative is True assert f(x).is_complex is None assert sin(x).is_complex is True assert exp(x).is_complex is True assert log(x).is_complex is None assert log(xzf).is_complex is True def test_function__eval_nseries(): n = Symbol('n') assert sin(x)._eval_nseries(x, 2, None) == x + O(x**2) assert sin(x + 1)._eval_nseries(x, 2, None) == x*cos(1) + sin(1) + O(x**2) assert sin(pi*(1 - x))._eval_nseries(x, 2, None) == pi*x + O(x**2) assert acos(1 - x**2)._eval_nseries(x, 2, None) == sqrt(2)*sqrt(x**2) + O(x**2) assert polygamma(n, x + 1)._eval_nseries(x, 2, None) == \ polygamma(n, 1) + polygamma(n + 1, 1)*x + O(x**2) raises(PoleError, lambda: sin(1/x)._eval_nseries(x, 2, None)) assert acos(1 - x)._eval_nseries(x, 2, None) == sqrt(2)*sqrt(x) + sqrt(2)*x**(S(3)/2)/12 + O(x**2) assert acos(1 + x)._eval_nseries(x, 2, None) == sqrt(2)*sqrt(-x) + sqrt(2)*(-x)**(S(3)/2)/12 + O(x**2) assert loggamma(1/x)._eval_nseries(x, 0, None) == \ log(x)/2 - log(x)/x - 1/x + O(1, x) assert loggamma(log(1/x)).nseries(x, n=1, logx=y) == loggamma(-y) # issue 6725: assert expint(Rational(3, 2), -x)._eval_nseries(x, 5, None) == \ 2 - 2*sqrt(pi)*sqrt(-x) - 2*x + x**2 + x**3/3 + x**4/12 + 4*I*x**(S(3)/2)*sqrt(-x)/3 + \ 2*I*x**(S(5)/2)*sqrt(-x)/5 + 2*I*x**(S(7)/2)*sqrt(-x)/21 + O(x**5) assert sin(sqrt(x))._eval_nseries(x, 3, None) == \ sqrt(x) - x**Rational(3, 2)/6 + x**Rational(5, 2)/120 + O(x**3) # issue 19065: s1 = f(x,y).series(y, n=2) assert {i.name for i in s1.atoms(Symbol)} == {'x', 'xi', 'y'} xi = Symbol('xi') s2 = f(xi, y).series(y, n=2) assert {i.name for i in s2.atoms(Symbol)} == {'xi', 'xi0', 'y'} def test_doit(): n = Symbol('n', integer=True) f = Sum(2 * n * x, (n, 1, 3)) d = Derivative(f, x) assert d.doit() == 12 assert d.doit(deep=False) == Sum(2*n, (n, 1, 3)) def test_evalf_default(): from sympy.functions.special.gamma_functions import polygamma assert type(sin(4.0)) == Float assert type(re(sin(I + 1.0))) == Float assert type(im(sin(I + 1.0))) == Float assert type(sin(4)) == sin assert type(polygamma(2.0, 4.0)) == Float assert type(sin(Rational(1, 4))) == sin def test_issue_5399(): args = [x, y, S(2), S.Half] def ok(a): """Return True if the input args for diff are ok""" if not a: return False if a[0].is_Symbol is False: return False s_at = [i for i in range(len(a)) if a[i].is_Symbol] n_at = [i for i in range(len(a)) if not a[i].is_Symbol] # every symbol is followed by symbol or int # every number is followed by a symbol return (all(a[i + 1].is_Symbol or a[i + 1].is_Integer for i in s_at if i + 1 < len(a)) and all(a[i + 1].is_Symbol for i in n_at if i + 1 < len(a))) eq = x**10*y**8 for a in subsets(args): for v in variations(a, len(a)): if ok(v): eq.diff(*v) # does not raise else: raises(ValueError, lambda: eq.diff(*v)) def test_derivative_numerically(): z0 = x._random() assert abs(Derivative(sin(x), x).doit_numerically(z0) - cos(z0)) < 1e-15 def test_fdiff_argument_index_error(): from sympy.core.function import ArgumentIndexError class myfunc(Function): nargs = 1 # define since there is no eval routine def fdiff(self, idx): raise ArgumentIndexError mf = myfunc(x) assert mf.diff(x) == Derivative(mf, x) raises(TypeError, lambda: myfunc(x, x)) def test_deriv_wrt_function(): x = f(t) xd = diff(x, t) xdd = diff(xd, t) y = g(t) yd = diff(y, t) assert diff(x, t) == xd assert diff(2 * x + 4, t) == 2 * xd assert diff(2 * x + 4 + y, t) == 2 * xd + yd assert diff(2 * x + 4 + y * x, t) == 2 * xd + x * yd + xd * y assert diff(2 * x + 4 + y * x, x) == 2 + y assert (diff(4 * x**2 + 3 * x + x * y, t) == 3 * xd + x * yd + xd * y + 8 * x * xd) assert (diff(4 * x**2 + 3 * xd + x * y, t) == 3 * xdd + x * yd + xd * y + 8 * x * xd) assert diff(4 * x**2 + 3 * xd + x * y, xd) == 3 assert diff(4 * x**2 + 3 * xd + x * y, xdd) == 0 assert diff(sin(x), t) == xd * cos(x) assert diff(exp(x), t) == xd * exp(x) assert diff(sqrt(x), t) == xd / (2 * sqrt(x)) def test_diff_wrt_value(): assert Expr()._diff_wrt is False assert x._diff_wrt is True assert f(x)._diff_wrt is True assert Derivative(f(x), x)._diff_wrt is True assert Derivative(x**2, x)._diff_wrt is False def test_diff_wrt(): fx = f(x) dfx = diff(f(x), x) ddfx = diff(f(x), x, x) assert diff(sin(fx) + fx**2, fx) == cos(fx) + 2*fx assert diff(sin(dfx) + dfx**2, dfx) == cos(dfx) + 2*dfx assert diff(sin(ddfx) + ddfx**2, ddfx) == cos(ddfx) + 2*ddfx assert diff(fx**2, dfx) == 0 assert diff(fx**2, ddfx) == 0 assert diff(dfx**2, fx) == 0 assert diff(dfx**2, ddfx) == 0 assert diff(ddfx**2, dfx) == 0 assert diff(fx*dfx*ddfx, fx) == dfx*ddfx assert diff(fx*dfx*ddfx, dfx) == fx*ddfx assert diff(fx*dfx*ddfx, ddfx) == fx*dfx assert diff(f(x), x).diff(f(x)) == 0 assert (sin(f(x)) - cos(diff(f(x), x))).diff(f(x)) == cos(f(x)) assert diff(sin(fx), fx, x) == diff(sin(fx), x, fx) # Chain rule cases assert f(g(x)).diff(x) == \ Derivative(g(x), x)*Derivative(f(g(x)), g(x)) assert diff(f(g(x), h(y)), x) == \ Derivative(g(x), x)*Derivative(f(g(x), h(y)), g(x)) assert diff(f(g(x), h(x)), x) == ( Derivative(f(g(x), h(x)), g(x))*Derivative(g(x), x) + Derivative(f(g(x), h(x)), h(x))*Derivative(h(x), x)) assert f( sin(x)).diff(x) == cos(x)*Subs(Derivative(f(x), x), x, sin(x)) assert diff(f(g(x)), g(x)) == Derivative(f(g(x)), g(x)) def test_diff_wrt_func_subs(): assert f(g(x)).diff(x).subs(g, Lambda(x, 2*x)).doit() == f(2*x).diff(x) def test_subs_in_derivative(): expr = sin(x*exp(y)) u = Function('u') v = Function('v') assert Derivative(expr, y).subs(expr, y) == Derivative(y, y) assert Derivative(expr, y).subs(y, x).doit() == \ Derivative(expr, y).doit().subs(y, x) assert Derivative(f(x, y), y).subs(y, x) == Subs(Derivative(f(x, y), y), y, x) assert Derivative(f(x, y), y).subs(x, y) == Subs(Derivative(f(x, y), y), x, y) assert Derivative(f(x, y), y).subs(y, g(x, y)) == Subs(Derivative(f(x, y), y), y, g(x, y)).doit() assert Derivative(f(x, y), y).subs(x, g(x, y)) == Subs(Derivative(f(x, y), y), x, g(x, y)) assert Derivative(f(x, y), g(y)).subs(x, g(x, y)) == Derivative(f(g(x, y), y), g(y)) assert Derivative(f(u(x), h(y)), h(y)).subs(h(y), g(x, y)) == \ Subs(Derivative(f(u(x), h(y)), h(y)), h(y), g(x, y)).doit() assert Derivative(f(x, y), y).subs(y, z) == Derivative(f(x, z), z) assert Derivative(f(x, y), y).subs(y, g(y)) == Derivative(f(x, g(y)), g(y)) assert Derivative(f(g(x), h(y)), h(y)).subs(h(y), u(y)) == \ Derivative(f(g(x), u(y)), u(y)) assert Derivative(f(x, f(x, x)), f(x, x)).subs( f, Lambda((x, y), x + y)) == Subs( Derivative(z + x, z), z, 2*x) assert Subs(Derivative(f(f(x)), x), f, cos).doit() == sin(x)*sin(cos(x)) assert Subs(Derivative(f(f(x)), f(x)), f, cos).doit() == -sin(cos(x)) # Issue 13791. No comparison (it's a long formula) but this used to raise an exception. assert isinstance(v(x, y, u(x, y)).diff(y).diff(x).diff(y), Expr) # This is also related to issues 13791 and 13795; issue 15190 F = Lambda((x, y), exp(2*x + 3*y)) abstract = f(x, f(x, x)).diff(x, 2) concrete = F(x, F(x, x)).diff(x, 2) assert (abstract.subs(f, F).doit() - concrete).simplify() == 0 # don't introduce a new symbol if not necessary assert x in f(x).diff(x).subs(x, 0).atoms() # case (4) assert Derivative(f(x,f(x,y)), x, y).subs(x, g(y) ) == Subs(Derivative(f(x, f(x, y)), x, y), x, g(y)) assert Derivative(f(x, x), x).subs(x, 0 ) == Subs(Derivative(f(x, x), x), x, 0) # issue 15194 assert Derivative(f(y, g(x)), (x, z)).subs(z, x ) == Derivative(f(y, g(x)), (x, x)) df = f(x).diff(x) assert df.subs(df, 1) is S.One assert df.diff(df) is S.One dxy = Derivative(f(x, y), x, y) dyx = Derivative(f(x, y), y, x) assert dxy.subs(Derivative(f(x, y), y, x), 1) is S.One assert dxy.diff(dyx) is S.One assert Derivative(f(x, y), x, 2, y, 3).subs( dyx, g(x, y)) == Derivative(g(x, y), x, 1, y, 2) assert Derivative(f(x, x - y), y).subs(x, x + y) == Subs( Derivative(f(x, x - y), y), x, x + y) def test_diff_wrt_not_allowed(): # issue 7027 included for wrt in ( cos(x), re(x), x**2, x*y, 1 + x, Derivative(cos(x), x), Derivative(f(f(x)), x)): raises(ValueError, lambda: diff(f(x), wrt)) # if we don't differentiate wrt then don't raise error assert diff(exp(x*y), x*y, 0) == exp(x*y) def test_diff_wrt_intlike(): class Two: def __int__(self): return 2 assert cos(x).diff(x, Two()) == -cos(x) def test_klein_gordon_lagrangian(): m = Symbol('m') phi = f(x, t) L = -(diff(phi, t)**2 - diff(phi, x)**2 - m**2*phi**2)/2 eqna = Eq( diff(L, phi) - diff(L, diff(phi, x), x) - diff(L, diff(phi, t), t), 0) eqnb = Eq(diff(phi, t, t) - diff(phi, x, x) + m**2*phi, 0) assert eqna == eqnb def test_sho_lagrangian(): m = Symbol('m') k = Symbol('k') x = f(t) L = m*diff(x, t)**2/2 - k*x**2/2 eqna = Eq(diff(L, x), diff(L, diff(x, t), t)) eqnb = Eq(-k*x, m*diff(x, t, t)) assert eqna == eqnb assert diff(L, x, t) == diff(L, t, x) assert diff(L, diff(x, t), t) == m*diff(x, t, 2) assert diff(L, t, diff(x, t)) == -k*x + m*diff(x, t, 2) def test_straight_line(): F = f(x) Fd = F.diff(x) L = sqrt(1 + Fd**2) assert diff(L, F) == 0 assert diff(L, Fd) == Fd/sqrt(1 + Fd**2) def test_sort_variable(): vsort = Derivative._sort_variable_count def vsort0(*v, reverse=False): return [i[0] for i in vsort([(i, 0) for i in ( reversed(v) if reverse else v)])] for R in range(2): assert vsort0(y, x, reverse=R) == [x, y] assert vsort0(f(x), x, reverse=R) == [x, f(x)] assert vsort0(f(y), f(x), reverse=R) == [f(x), f(y)] assert vsort0(g(x), f(y), reverse=R) == [f(y), g(x)] assert vsort0(f(x, y), f(x), reverse=R) == [f(x), f(x, y)] fx = f(x).diff(x) assert vsort0(fx, y, reverse=R) == [y, fx] fy = f(y).diff(y) assert vsort0(fy, fx, reverse=R) == [fx, fy] fxx = fx.diff(x) assert vsort0(fxx, fx, reverse=R) == [fx, fxx] assert vsort0(Basic(x), f(x), reverse=R) == [f(x), Basic(x)] assert vsort0(Basic(y), Basic(x), reverse=R) == [Basic(x), Basic(y)] assert vsort0(Basic(y, z), Basic(x), reverse=R) == [ Basic(x), Basic(y, z)] assert vsort0(fx, x, reverse=R) == [ x, fx] if R else [fx, x] assert vsort0(Basic(x), x, reverse=R) == [ x, Basic(x)] if R else [Basic(x), x] assert vsort0(Basic(f(x)), f(x), reverse=R) == [ f(x), Basic(f(x))] if R else [Basic(f(x)), f(x)] assert vsort0(Basic(x, z), Basic(x), reverse=R) == [ Basic(x), Basic(x, z)] if R else [Basic(x, z), Basic(x)] assert vsort([]) == [] assert _aresame(vsort([(x, 1)]), [Tuple(x, 1)]) assert vsort([(x, y), (x, z)]) == [(x, y + z)] assert vsort([(y, 1), (x, 1 + y)]) == [(x, 1 + y), (y, 1)] # coverage complete; legacy tests below assert vsort([(x, 3), (y, 2), (z, 1)]) == [(x, 3), (y, 2), (z, 1)] assert vsort([(h(x), 1), (g(x), 1), (f(x), 1)]) == [ (f(x), 1), (g(x), 1), (h(x), 1)] assert vsort([(z, 1), (y, 2), (x, 3), (h(x), 1), (g(x), 1), (f(x), 1)]) == [(x, 3), (y, 2), (z, 1), (f(x), 1), (g(x), 1), (h(x), 1)] assert vsort([(x, 1), (f(x), 1), (y, 1), (f(y), 1)]) == [(x, 1), (y, 1), (f(x), 1), (f(y), 1)] assert vsort([(y, 1), (x, 2), (g(x), 1), (f(x), 1), (z, 1), (h(x), 1), (y, 2), (x, 1)]) == [(x, 3), (y, 3), (z, 1), (f(x), 1), (g(x), 1), (h(x), 1)] assert vsort([(z, 1), (y, 1), (f(x), 1), (x, 1), (f(x), 1), (g(x), 1)]) == [(x, 1), (y, 1), (z, 1), (f(x), 2), (g(x), 1)] assert vsort([(z, 1), (y, 2), (f(x), 1), (x, 2), (f(x), 2), (g(x), 1), (z, 2), (z, 1), (y, 1), (x, 1)]) == [(x, 3), (y, 3), (z, 4), (f(x), 3), (g(x), 1)] assert vsort(((y, 2), (x, 1), (y, 1), (x, 1))) == [(x, 2), (y, 3)] assert isinstance(vsort([(x, 3), (y, 2), (z, 1)])[0], Tuple) assert vsort([(x, 1), (f(x), 1), (x, 1)]) == [(x, 2), (f(x), 1)] assert vsort([(y, 2), (x, 3), (z, 1)]) == [(x, 3), (y, 2), (z, 1)] assert vsort([(h(y), 1), (g(x), 1), (f(x), 1)]) == [ (f(x), 1), (g(x), 1), (h(y), 1)] assert vsort([(x, 1), (y, 1), (x, 1)]) == [(x, 2), (y, 1)] assert vsort([(f(x), 1), (f(y), 1), (f(x), 1)]) == [ (f(x), 2), (f(y), 1)] dfx = f(x).diff(x) self = [(dfx, 1), (x, 1)] assert vsort(self) == self assert vsort([ (dfx, 1), (y, 1), (f(x), 1), (x, 1), (f(y), 1), (x, 1)]) == [ (y, 1), (f(x), 1), (f(y), 1), (dfx, 1), (x, 2)] dfy = f(y).diff(y) assert vsort([(dfy, 1), (dfx, 1)]) == [(dfx, 1), (dfy, 1)] d2fx = dfx.diff(x) assert vsort([(d2fx, 1), (dfx, 1)]) == [(dfx, 1), (d2fx, 1)] def test_multiple_derivative(): # Issue #15007 assert f(x, y).diff(y, y, x, y, x ) == Derivative(f(x, y), (x, 2), (y, 3)) def test_unhandled(): class MyExpr(Expr): def _eval_derivative(self, s): if not s.name.startswith('xi'): return self else: return None eq = MyExpr(f(x), y, z) assert diff(eq, x, y, f(x), z) == Derivative(eq, f(x)) assert diff(eq, f(x), x) == Derivative(eq, f(x)) assert f(x, y).diff(x,(y, z)) == Derivative(f(x, y), x, (y, z)) assert f(x, y).diff(x,(y, 0)) == Derivative(f(x, y), x) def test_nfloat(): from sympy.core.basic import _aresame from sympy.polys.rootoftools import rootof x = Symbol("x") eq = x**Rational(4, 3) + 4*x**(S.One/3)/3 assert _aresame(nfloat(eq), x**Rational(4, 3) + (4.0/3)*x**(S.One/3)) assert _aresame(nfloat(eq, exponent=True), x**(4.0/3) + (4.0/3)*x**(1.0/3)) eq = x**Rational(4, 3) + 4*x**(x/3)/3 assert _aresame(nfloat(eq), x**Rational(4, 3) + (4.0/3)*x**(x/3)) big = 12345678901234567890 # specify precision to match value used in nfloat Float_big = Float(big, 15) assert _aresame(nfloat(big), Float_big) assert _aresame(nfloat(big*x), Float_big*x) assert _aresame(nfloat(x**big, exponent=True), x**Float_big) assert nfloat(cos(x + sqrt(2))) == cos(x + nfloat(sqrt(2))) # issue 6342 f = S('x*lamda + lamda**3*(x/2 + 1/2) + lamda**2 + 1/4') assert not any(a.free_symbols for a in solveset(f.subs(x, -0.139))) # issue 6632 assert nfloat(-100000*sqrt(2500000001) + 5000000001) == \ 9.99999999800000e-11 # issue 7122 eq = cos(3*x**4 + y)*rootof(x**5 + 3*x**3 + 1, 0) assert str(nfloat(eq, exponent=False, n=1)) == '-0.7*cos(3.0*x**4 + y)' # issue 10933 for ti in (dict, Dict): d = ti({S.Half: S.Half}) n = nfloat(d) assert isinstance(n, ti) assert _aresame(list(n.items()).pop(), (S.Half, Float(.5))) for ti in (dict, Dict): d = ti({S.Half: S.Half}) n = nfloat(d, dkeys=True) assert isinstance(n, ti) assert _aresame(list(n.items()).pop(), (Float(.5), Float(.5))) d = [S.Half] n = nfloat(d) assert type(n) is list assert _aresame(n[0], Float(.5)) assert _aresame(nfloat(Eq(x, S.Half)).rhs, Float(.5)) assert _aresame(nfloat(S(True)), S(True)) assert _aresame(nfloat(Tuple(S.Half))[0], Float(.5)) assert nfloat(Eq((3 - I)**2/2 + I, 0)) == S.false # pass along kwargs assert nfloat([{S.Half: x}], dkeys=True) == [{Float(0.5): x}] # Issue 17706 A = MutableMatrix([[1, 2], [3, 4]]) B = MutableMatrix( [[Float('1.0', precision=53), Float('2.0', precision=53)], [Float('3.0', precision=53), Float('4.0', precision=53)]]) assert _aresame(nfloat(A), B) A = ImmutableMatrix([[1, 2], [3, 4]]) B = ImmutableMatrix( [[Float('1.0', precision=53), Float('2.0', precision=53)], [Float('3.0', precision=53), Float('4.0', precision=53)]]) assert _aresame(nfloat(A), B) # issue 22524 f = Function('f') assert not nfloat(f(2)).atoms(Float) def test_issue_7068(): from sympy.abc import a, b f = Function('f') y1 = Dummy('y') y2 = Dummy('y') func1 = f(a + y1 * b) func2 = f(a + y2 * b) func1_y = func1.diff(y1) func2_y = func2.diff(y2) assert func1_y != func2_y z1 = Subs(f(a), a, y1) z2 = Subs(f(a), a, y2) assert z1 != z2 def test_issue_7231(): from sympy.abc import a ans1 = f(x).series(x, a) res = (f(a) + (-a + x)*Subs(Derivative(f(y), y), y, a) + (-a + x)**2*Subs(Derivative(f(y), y, y), y, a)/2 + (-a + x)**3*Subs(Derivative(f(y), y, y, y), y, a)/6 + (-a + x)**4*Subs(Derivative(f(y), y, y, y, y), y, a)/24 + (-a + x)**5*Subs(Derivative(f(y), y, y, y, y, y), y, a)/120 + O((-a + x)**6, (x, a))) assert res == ans1 ans2 = f(x).series(x, a) assert res == ans2 def test_issue_7687(): from sympy.core.function import Function from sympy.abc import x f = Function('f')(x) ff = Function('f')(x) match_with_cache = ff.matches(f) assert isinstance(f, type(ff)) clear_cache() ff = Function('f')(x) assert isinstance(f, type(ff)) assert match_with_cache == ff.matches(f) def test_issue_7688(): from sympy.core.function import Function, UndefinedFunction f = Function('f') # actually an UndefinedFunction clear_cache() class A(UndefinedFunction): pass a = A('f') assert isinstance(a, type(f)) def test_mexpand(): from sympy.abc import x assert _mexpand(None) is None assert _mexpand(1) is S.One assert _mexpand(x*(x + 1)**2) == (x*(x + 1)**2).expand() def test_issue_8469(): # This should not take forever to run N = 40 def g(w, theta): return 1/(1+exp(w-theta)) ws = symbols(['w%i'%i for i in range(N)]) import functools expr = functools.reduce(g, ws) assert isinstance(expr, Pow) def test_issue_12996(): # foo=True imitates the sort of arguments that Derivative can get # from Integral when it passes doit to the expression assert Derivative(im(x), x).doit(foo=True) == Derivative(im(x), x) def test_should_evalf(): # This should not take forever to run (see #8506) assert isinstance(sin((1.0 + 1.0*I)**10000 + 1), sin) def test_Derivative_as_finite_difference(): # Central 1st derivative at gridpoint x, h = symbols('x h', real=True) dfdx = f(x).diff(x) assert (dfdx.as_finite_difference([x-2, x-1, x, x+1, x+2]) - (S.One/12*(f(x-2)-f(x+2)) + Rational(2, 3)*(f(x+1)-f(x-1)))).simplify() == 0 # Central 1st derivative "half-way" assert (dfdx.as_finite_difference() - (f(x + S.Half)-f(x - S.Half))).simplify() == 0 assert (dfdx.as_finite_difference(h) - (f(x + h/S(2))-f(x - h/S(2)))/h).simplify() == 0 assert (dfdx.as_finite_difference([x - 3*h, x-h, x+h, x + 3*h]) - (S(9)/(8*2*h)*(f(x+h) - f(x-h)) + S.One/(24*2*h)*(f(x - 3*h) - f(x + 3*h)))).simplify() == 0 # One sided 1st derivative at gridpoint assert (dfdx.as_finite_difference([0, 1, 2], 0) - (Rational(-3, 2)*f(0) + 2*f(1) - f(2)/2)).simplify() == 0 assert (dfdx.as_finite_difference([x, x+h], x) - (f(x+h) - f(x))/h).simplify() == 0 assert (dfdx.as_finite_difference([x-h, x, x+h], x-h) - (-S(3)/(2*h)*f(x-h) + 2/h*f(x) - S.One/(2*h)*f(x+h))).simplify() == 0 # One sided 1st derivative "half-way" assert (dfdx.as_finite_difference([x-h, x+h, x + 3*h, x + 5*h, x + 7*h]) - 1/(2*h)*(-S(11)/(12)*f(x-h) + S(17)/(24)*f(x+h) + Rational(3, 8)*f(x + 3*h) - Rational(5, 24)*f(x + 5*h) + S.One/24*f(x + 7*h))).simplify() == 0 d2fdx2 = f(x).diff(x, 2) # Central 2nd derivative at gridpoint assert (d2fdx2.as_finite_difference([x-h, x, x+h]) - h**-2 * (f(x-h) + f(x+h) - 2*f(x))).simplify() == 0 assert (d2fdx2.as_finite_difference([x - 2*h, x-h, x, x+h, x + 2*h]) - h**-2 * (Rational(-1, 12)*(f(x - 2*h) + f(x + 2*h)) + Rational(4, 3)*(f(x+h) + f(x-h)) - Rational(5, 2)*f(x))).simplify() == 0 # Central 2nd derivative "half-way" assert (d2fdx2.as_finite_difference([x - 3*h, x-h, x+h, x + 3*h]) - (2*h)**-2 * (S.Half*(f(x - 3*h) + f(x + 3*h)) - S.Half*(f(x+h) + f(x-h)))).simplify() == 0 # One sided 2nd derivative at gridpoint assert (d2fdx2.as_finite_difference([x, x+h, x + 2*h, x + 3*h]) - h**-2 * (2*f(x) - 5*f(x+h) + 4*f(x+2*h) - f(x+3*h))).simplify() == 0 # One sided 2nd derivative at "half-way" assert (d2fdx2.as_finite_difference([x-h, x+h, x + 3*h, x + 5*h]) - (2*h)**-2 * (Rational(3, 2)*f(x-h) - Rational(7, 2)*f(x+h) + Rational(5, 2)*f(x + 3*h) - S.Half*f(x + 5*h))).simplify() == 0 d3fdx3 = f(x).diff(x, 3) # Central 3rd derivative at gridpoint assert (d3fdx3.as_finite_difference() - (-f(x - Rational(3, 2)) + 3*f(x - S.Half) - 3*f(x + S.Half) + f(x + Rational(3, 2)))).simplify() == 0 assert (d3fdx3.as_finite_difference( [x - 3*h, x - 2*h, x-h, x, x+h, x + 2*h, x + 3*h]) - h**-3 * (S.One/8*(f(x - 3*h) - f(x + 3*h)) - f(x - 2*h) + f(x + 2*h) + Rational(13, 8)*(f(x-h) - f(x+h)))).simplify() == 0 # Central 3rd derivative at "half-way" assert (d3fdx3.as_finite_difference([x - 3*h, x-h, x+h, x + 3*h]) - (2*h)**-3 * (f(x + 3*h)-f(x - 3*h) + 3*(f(x-h)-f(x+h)))).simplify() == 0 # One sided 3rd derivative at gridpoint assert (d3fdx3.as_finite_difference([x, x+h, x + 2*h, x + 3*h]) - h**-3 * (f(x + 3*h)-f(x) + 3*(f(x+h)-f(x + 2*h)))).simplify() == 0 # One sided 3rd derivative at "half-way" assert (d3fdx3.as_finite_difference([x-h, x+h, x + 3*h, x + 5*h]) - (2*h)**-3 * (f(x + 5*h)-f(x-h) + 3*(f(x+h)-f(x + 3*h)))).simplify() == 0 # issue 11007 y = Symbol('y', real=True) d2fdxdy = f(x, y).diff(x, y) ref0 = Derivative(f(x + S.Half, y), y) - Derivative(f(x - S.Half, y), y) assert (d2fdxdy.as_finite_difference(wrt=x) - ref0).simplify() == 0 half = S.Half xm, xp, ym, yp = x-half, x+half, y-half, y+half ref2 = f(xm, ym) + f(xp, yp) - f(xp, ym) - f(xm, yp) assert (d2fdxdy.as_finite_difference() - ref2).simplify() == 0 def test_issue_11159(): # Tests Application._eval_subs with _exp_is_pow(False): expr1 = E expr0 = expr1 * expr1 expr1 = expr0.subs(expr1,expr0) assert expr0 == expr1 with _exp_is_pow(True): expr1 = E expr0 = expr1 * expr1 expr2 = expr0.subs(expr1, expr0) assert expr2 == E ** 4 def test_issue_12005(): e1 = Subs(Derivative(f(x), x), x, x) assert e1.diff(x) == Derivative(f(x), x, x) e2 = Subs(Derivative(f(x), x), x, x**2 + 1) assert e2.diff(x) == 2*x*Subs(Derivative(f(x), x, x), x, x**2 + 1) e3 = Subs(Derivative(f(x) + y**2 - y, y), y, y**2) assert e3.diff(y) == 4*y e4 = Subs(Derivative(f(x + y), y), y, (x**2)) assert e4.diff(y) is S.Zero e5 = Subs(Derivative(f(x), x), (y, z), (y, z)) assert e5.diff(x) == Derivative(f(x), x, x) assert f(g(x)).diff(g(x), g(x)) == Derivative(f(g(x)), g(x), g(x)) def test_issue_13843(): x = symbols('x') f = Function('f') m, n = symbols('m n', integer=True) assert Derivative(Derivative(f(x), (x, m)), (x, n)) == Derivative(f(x), (x, m + n)) assert Derivative(Derivative(f(x), (x, m+5)), (x, n+3)) == Derivative(f(x), (x, m + n + 8)) assert Derivative(f(x), (x, n)).doit() == Derivative(f(x), (x, n)) def test_order_could_be_zero(): x, y = symbols('x, y') n = symbols('n', integer=True, nonnegative=True) m = symbols('m', integer=True, positive=True) assert diff(y, (x, n)) == Piecewise((y, Eq(n, 0)), (0, True)) assert diff(y, (x, n + 1)) is S.Zero assert diff(y, (x, m)) is S.Zero def test_undefined_function_eq(): f = Function('f') f2 = Function('f') g = Function('g') f_real = Function('f', is_real=True) # This test may only be meaningful if the cache is turned off assert f == f2 assert hash(f) == hash(f2) assert f == f assert f != g assert f != f_real def test_function_assumptions(): x = Symbol('x') f = Function('f') f_real = Function('f', real=True) f_real1 = Function('f', real=1) f_real_inherit = Function(Symbol('f', real=True)) assert f_real == f_real1 # assumptions are sanitized assert f != f_real assert f(x) != f_real(x) assert f(x).is_real is None assert f_real(x).is_real is True assert f_real_inherit(x).is_real is True and f_real_inherit.name == 'f' # Can also do it this way, but it won't be equal to f_real because of the # way UndefinedFunction.__new__ works. Any non-recognized assumptions # are just added literally as something which is used in the hash f_real2 = Function('f', is_real=True) assert f_real2(x).is_real is True def test_undef_fcn_float_issue_6938(): f = Function('ceil') assert not f(0.3).is_number f = Function('sin') assert not f(0.3).is_number assert not f(pi).evalf().is_number x = Symbol('x') assert not f(x).evalf(subs={x:1.2}).is_number def test_undefined_function_eval(): # Issue 15170. Make sure UndefinedFunction with eval defined works # properly. The issue there was that the hash was determined before _nargs # was set, which is included in the hash, hence changing the hash. The # class is added to sympy.core.core.all_classes before the hash is # changed, meaning "temp in all_classes" would fail, causing sympify(temp(t)) # to give a new class. We will eventually remove all_classes, but make # sure this continues to work. fdiff = lambda self, argindex=1: cos(self.args[argindex - 1]) eval = classmethod(lambda cls, t: None) _imp_ = classmethod(lambda cls, t: sin(t)) temp = Function('temp', fdiff=fdiff, eval=eval, _imp_=_imp_) expr = temp(t) assert sympify(expr) == expr assert type(sympify(expr)).fdiff.__name__ == "<lambda>" assert expr.diff(t) == cos(t) def test_issue_15241(): F = f(x) Fx = F.diff(x) assert (F + x*Fx).diff(x, Fx) == 2 assert (F + x*Fx).diff(Fx, x) == 1 assert (x*F + x*Fx*F).diff(F, x) == x*Fx.diff(x) + Fx + 1 assert (x*F + x*Fx*F).diff(x, F) == x*Fx.diff(x) + Fx + 1 y = f(x) G = f(y) Gy = G.diff(y) assert (G + y*Gy).diff(y, Gy) == 2 assert (G + y*Gy).diff(Gy, y) == 1 assert (y*G + y*Gy*G).diff(G, y) == y*Gy.diff(y) + Gy + 1 assert (y*G + y*Gy*G).diff(y, G) == y*Gy.diff(y) + Gy + 1 def test_issue_15226(): assert Subs(Derivative(f(y), x, y), y, g(x)).doit() != 0 def test_issue_7027(): for wrt in (cos(x), re(x), Derivative(cos(x), x)): raises(ValueError, lambda: diff(f(x), wrt)) def test_derivative_quick_exit(): assert f(x).diff(y) == 0 assert f(x).diff(y, f(x)) == 0 assert f(x).diff(x, f(y)) == 0 assert f(f(x)).diff(x, f(x), f(y)) == 0 assert f(f(x)).diff(x, f(x), y) == 0 assert f(x).diff(g(x)) == 0 assert f(x).diff(x, f(x).diff(x)) == 1 df = f(x).diff(x) assert f(x).diff(df) == 0 dg = g(x).diff(x) assert dg.diff(df).doit() == 0 def test_issue_15084_13166(): eq = f(x, g(x)) assert eq.diff((g(x), y)) == Derivative(f(x, g(x)), (g(x), y)) # issue 13166 assert eq.diff(x, 2).doit() == ( (Derivative(f(x, g(x)), (g(x), 2))*Derivative(g(x), x) + Subs(Derivative(f(x, _xi_2), _xi_2, x), _xi_2, g(x)))*Derivative(g(x), x) + Derivative(f(x, g(x)), g(x))*Derivative(g(x), (x, 2)) + Derivative(g(x), x)*Subs(Derivative(f(_xi_1, g(x)), _xi_1, g(x)), _xi_1, x) + Subs(Derivative(f(_xi_1, g(x)), (_xi_1, 2)), _xi_1, x)) # issue 6681 assert diff(f(x, t, g(x, t)), x).doit() == ( Derivative(f(x, t, g(x, t)), g(x, t))*Derivative(g(x, t), x) + Subs(Derivative(f(_xi_1, t, g(x, t)), _xi_1), _xi_1, x)) # make sure the order doesn't matter when using diff assert eq.diff(x, g(x)) == eq.diff(g(x), x) def test_negative_counts(): # issue 13873 raises(ValueError, lambda: sin(x).diff(x, -1)) def test_Derivative__new__(): raises(TypeError, lambda: f(x).diff((x, 2), 0)) assert f(x, y).diff([(x, y), 0]) == f(x, y) assert f(x, y).diff([(x, y), 1]) == NDimArray([ Derivative(f(x, y), x), Derivative(f(x, y), y)]) assert f(x,y).diff(y, (x, z), y, x) == Derivative( f(x, y), (x, z + 1), (y, 2)) assert Matrix([x]).diff(x, 2) == Matrix([0]) # is_zero exit def test_issue_14719_10150(): class V(Expr): _diff_wrt = True is_scalar = False assert V().diff(V()) == Derivative(V(), V()) assert (2*V()).diff(V()) == 2*Derivative(V(), V()) class X(Expr): _diff_wrt = True assert X().diff(X()) == 1 assert (2*X()).diff(X()) == 2 def test_noncommutative_issue_15131(): x = Symbol('x', commutative=False) t = Symbol('t', commutative=False) fx = Function('Fx', commutative=False)(x) ft = Function('Ft', commutative=False)(t) A = Symbol('A', commutative=False) eq = fx * A * ft eqdt = eq.diff(t) assert eqdt.args[-1] == ft.diff(t) def test_Subs_Derivative(): a = Derivative(f(g(x), h(x)), g(x), h(x),x) b = Derivative(Derivative(f(g(x), h(x)), g(x), h(x)),x) c = f(g(x), h(x)).diff(g(x), h(x), x) d = f(g(x), h(x)).diff(g(x), h(x)).diff(x) e = Derivative(f(g(x), h(x)), x) eqs = (a, b, c, d, e) subs = lambda arg: arg.subs(f, Lambda((x, y), exp(x + y)) ).subs(g(x), 1/x).subs(h(x), x**3) ans = 3*x**2*exp(1/x)*exp(x**3) - exp(1/x)*exp(x**3)/x**2 assert all(subs(i).doit().expand() == ans for i in eqs) assert all(subs(i.doit()).doit().expand() == ans for i in eqs) def test_issue_15360(): f = Function('f') assert f.name == 'f' def test_issue_15947(): assert f._diff_wrt is False raises(TypeError, lambda: f(f)) raises(TypeError, lambda: f(x).diff(f)) def test_Derivative_free_symbols(): f = Function('f') n = Symbol('n', integer=True, positive=True) assert diff(f(x), (x, n)).free_symbols == {n, x} def test_issue_20683(): x = Symbol('x') y = Symbol('y') z = Symbol('z') y = Derivative(z, x).subs(x,0) assert y.doit() == 0 y = Derivative(8, x).subs(x,0) assert y.doit() == 0 def test_issue_10503(): f = exp(x**3)*cos(x**6) assert f.series(x, 0, 14) == 1 + x**3 + x**6/2 + x**9/6 - 11*x**12/24 + O(x**14) def test_issue_17382(): # copied from sympy/core/tests/test_evalf.py def NS(e, n=15, **options): return sstr(sympify(e).evalf(n, **options), full_prec=True) x = Symbol('x') expr = solveset(2 * cos(x) * cos(2 * x) - 1, x, S.Reals) expected = "Union(" \ "ImageSet(Lambda(_n, 6.28318530717959*_n + 5.79812359592087), Integers), " \ "ImageSet(Lambda(_n, 6.28318530717959*_n + 0.485061711258717), Integers))" assert NS(expr) == expected
14bb633466d47ad237063d1e90740f2896be12ea890c8ddb8bcb06b1e7e98019
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 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(1)/3)*exp(-2*I*pi/3) - \ (-1)**(S(5)/6)*x*exp(-2*I*pi/3)/3 + (-1)**(S(1)/3)*x**2*exp(-2*I*pi/3)/9 + \ 5*(-1)**(S(5)/6)*x**3*exp(-2*I*pi/3)/81 + O(x**4) assert (1 / (exp(-1/x) + 1/x))._eval_nseries(x, 2, None) == x + O(x**2) 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) assert sqrt((p - p**2*I)**2) == p - p**2*I assert sqrt((p**2*I - p)**2) == p**2*I - p # XXX ok? 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_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)
df837fb9cae41f754849aafb7ace4a1f4fbe807c93fbdae92d50112b3510c17b
from collections import defaultdict from sympy.core.basic import Basic from sympy.core.containers import (Dict, Tuple) from sympy.core.numbers import Integer from sympy.core.kind import NumberKind from sympy.matrices.common import MatrixKind from sympy.core.singleton import S from sympy.core.symbol import symbols from sympy.core.sympify import sympify from sympy.matrices.dense import Matrix from sympy.sets.sets import FiniteSet from sympy.core.containers import tuple_wrapper, TupleKind from sympy.core.expr import unchanged from sympy.core.function import Function, Lambda from sympy.core.relational import Eq from sympy.testing.pytest import raises from sympy.utilities.iterables import is_sequence, iterable from sympy.abc import x, y def test_Tuple(): t = (1, 2, 3, 4) st = Tuple(*t) assert set(sympify(t)) == set(st) assert len(t) == len(st) assert set(sympify(t[:2])) == set(st[:2]) assert isinstance(st[:], Tuple) assert st == Tuple(1, 2, 3, 4) assert st.func(*st.args) == st p, q, r, s = symbols('p q r s') t2 = (p, q, r, s) st2 = Tuple(*t2) assert st2.atoms() == set(t2) assert st == st2.subs({p: 1, q: 2, r: 3, s: 4}) # issue 5505 assert all(isinstance(arg, Basic) for arg in st.args) assert Tuple(p, 1).subs(p, 0) == Tuple(0, 1) assert Tuple(p, Tuple(p, 1)).subs(p, 0) == Tuple(0, Tuple(0, 1)) assert Tuple(t2) == Tuple(Tuple(*t2)) assert Tuple.fromiter(t2) == Tuple(*t2) assert Tuple.fromiter(x for x in range(4)) == Tuple(0, 1, 2, 3) assert st2.fromiter(st2.args) == st2 def test_Tuple_contains(): t1, t2 = Tuple(1), Tuple(2) assert t1 in Tuple(1, 2, 3, t1, Tuple(t2)) assert t2 not in Tuple(1, 2, 3, t1, Tuple(t2)) def test_Tuple_concatenation(): assert Tuple(1, 2) + Tuple(3, 4) == Tuple(1, 2, 3, 4) assert (1, 2) + Tuple(3, 4) == Tuple(1, 2, 3, 4) assert Tuple(1, 2) + (3, 4) == Tuple(1, 2, 3, 4) raises(TypeError, lambda: Tuple(1, 2) + 3) raises(TypeError, lambda: 1 + Tuple(2, 3)) #the Tuple case in __radd__ is only reached when a subclass is involved class Tuple2(Tuple): def __radd__(self, other): return Tuple.__radd__(self, other + other) assert Tuple(1, 2) + Tuple2(3, 4) == Tuple(1, 2, 1, 2, 3, 4) assert Tuple2(1, 2) + Tuple(3, 4) == Tuple(1, 2, 3, 4) def test_Tuple_equality(): assert not isinstance(Tuple(1, 2), tuple) assert (Tuple(1, 2) == (1, 2)) is True assert (Tuple(1, 2) != (1, 2)) is False assert (Tuple(1, 2) == (1, 3)) is False assert (Tuple(1, 2) != (1, 3)) is True assert (Tuple(1, 2) == Tuple(1, 2)) is True assert (Tuple(1, 2) != Tuple(1, 2)) is False assert (Tuple(1, 2) == Tuple(1, 3)) is False assert (Tuple(1, 2) != Tuple(1, 3)) is True def test_Tuple_Eq(): assert Eq(Tuple(), Tuple()) is S.true assert Eq(Tuple(1), 1) is S.false assert Eq(Tuple(1, 2), Tuple(1)) is S.false assert Eq(Tuple(1), Tuple(1)) is S.true assert Eq(Tuple(1, 2), Tuple(1, 3)) is S.false assert Eq(Tuple(1, 2), Tuple(1, 2)) is S.true assert unchanged(Eq, Tuple(1, x), Tuple(1, 2)) assert Eq(Tuple(1, x), Tuple(1, 2)).subs(x, 2) is S.true assert unchanged(Eq, Tuple(1, 2), x) f = Function('f') assert unchanged(Eq, Tuple(1), f(x)) assert Eq(Tuple(1), f(x)).subs(x, 1).subs(f, Lambda(y, (y,))) is S.true def test_Tuple_comparision(): assert (Tuple(1, 3) >= Tuple(-10, 30)) is S.true assert (Tuple(1, 3) <= Tuple(-10, 30)) is S.false assert (Tuple(1, 3) >= Tuple(1, 3)) is S.true assert (Tuple(1, 3) <= Tuple(1, 3)) is S.true def test_Tuple_tuple_count(): assert Tuple(0, 1, 2, 3).tuple_count(4) == 0 assert Tuple(0, 4, 1, 2, 3).tuple_count(4) == 1 assert Tuple(0, 4, 1, 4, 2, 3).tuple_count(4) == 2 assert Tuple(0, 4, 1, 4, 2, 4, 3).tuple_count(4) == 3 def test_Tuple_index(): assert Tuple(4, 0, 1, 2, 3).index(4) == 0 assert Tuple(0, 4, 1, 2, 3).index(4) == 1 assert Tuple(0, 1, 4, 2, 3).index(4) == 2 assert Tuple(0, 1, 2, 4, 3).index(4) == 3 assert Tuple(0, 1, 2, 3, 4).index(4) == 4 raises(ValueError, lambda: Tuple(0, 1, 2, 3).index(4)) raises(ValueError, lambda: Tuple(4, 0, 1, 2, 3).index(4, 1)) raises(ValueError, lambda: Tuple(0, 1, 2, 3, 4).index(4, 1, 4)) def test_Tuple_mul(): assert Tuple(1, 2, 3)*2 == Tuple(1, 2, 3, 1, 2, 3) assert 2*Tuple(1, 2, 3) == Tuple(1, 2, 3, 1, 2, 3) assert Tuple(1, 2, 3)*Integer(2) == Tuple(1, 2, 3, 1, 2, 3) assert Integer(2)*Tuple(1, 2, 3) == Tuple(1, 2, 3, 1, 2, 3) raises(TypeError, lambda: Tuple(1, 2, 3)*S.Half) raises(TypeError, lambda: S.Half*Tuple(1, 2, 3)) def test_tuple_wrapper(): @tuple_wrapper def wrap_tuples_and_return(*t): return t p = symbols('p') assert wrap_tuples_and_return(p, 1) == (p, 1) assert wrap_tuples_and_return((p, 1)) == (Tuple(p, 1),) assert wrap_tuples_and_return(1, (p, 2), 3) == (1, Tuple(p, 2), 3) def test_iterable_is_sequence(): ordered = [list(), tuple(), Tuple(), Matrix([[]])] unordered = [set()] not_sympy_iterable = [{}, '', ''] assert all(is_sequence(i) for i in ordered) assert all(not is_sequence(i) for i in unordered) assert all(iterable(i) for i in ordered + unordered) assert all(not iterable(i) for i in not_sympy_iterable) assert all(iterable(i, exclude=None) for i in not_sympy_iterable) def test_TupleKind(): kind = TupleKind(NumberKind, MatrixKind(NumberKind)) assert Tuple(1, Matrix([1, 2])).kind is kind assert Tuple(1, 2).kind is TupleKind(NumberKind, NumberKind) assert Tuple(1, 2).kind.element_kind == (NumberKind, NumberKind) def test_Dict(): x, y, z = symbols('x y z') d = Dict({x: 1, y: 2, z: 3}) assert d[x] == 1 assert d[y] == 2 raises(KeyError, lambda: d[2]) raises(KeyError, lambda: d['2']) assert len(d) == 3 assert set(d.keys()) == {x, y, z} assert set(d.values()) == {S.One, S(2), S(3)} assert d.get(5, 'default') == 'default' assert d.get('5', 'default') == 'default' assert x in d and z in d and 5 not in d and '5' not in d assert d.has(x) and d.has(1) # SymPy Basic .has method # Test input types # input - a Python dict # input - items as args - SymPy style assert (Dict({x: 1, y: 2, z: 3}) == Dict((x, 1), (y, 2), (z, 3))) raises(TypeError, lambda: Dict(((x, 1), (y, 2), (z, 3)))) with raises(NotImplementedError): d[5] = 6 # assert immutability assert set( d.items()) == {Tuple(x, S.One), Tuple(y, S(2)), Tuple(z, S(3))} assert set(d) == {x, y, z} assert str(d) == '{x: 1, y: 2, z: 3}' assert d.__repr__() == '{x: 1, y: 2, z: 3}' # Test creating a Dict from a Dict. d = Dict({x: 1, y: 2, z: 3}) assert d == Dict(d) # Test for supporting defaultdict d = defaultdict(int) assert d[x] == 0 assert d[y] == 0 assert d[z] == 0 assert Dict(d) d = Dict(d) assert len(d) == 3 assert set(d.keys()) == {x, y, z} assert set(d.values()) == {S.Zero, S.Zero, S.Zero} def test_issue_5788(): args = [(1, 2), (2, 1)] for o in [Dict, Tuple, FiniteSet]: # __eq__ and arg handling if o != Tuple: assert o(*args) == o(*reversed(args)) pair = [o(*args), o(*reversed(args))] assert sorted(pair) == sorted(reversed(pair)) assert set(o(*args)) # doesn't fail
6e8e814d7b197b755b83b7b36d5d8257f5fb0b0d752272f91c8c2f6a2c9976d4
import math from sympy.concrete.products import (Product, product) from sympy.concrete.summations import Sum from sympy.core.add import Add from sympy.core.evalf import N from sympy.core.function import (Function, nfloat) from sympy.core.mul import Mul from sympy.core import (GoldenRatio) from sympy.core.numbers import (AlgebraicNumber, E, Float, I, Rational, oo, zoo, nan, pi) from sympy.core.power import Pow from sympy.core.relational import Eq from sympy.core.singleton import S from sympy.core.symbol import Symbol from sympy.core.sympify import sympify from sympy.functions.combinatorial.factorials import factorial from sympy.functions.combinatorial.numbers import fibonacci from sympy.functions.elementary.complexes import (Abs, re, im) from sympy.functions.elementary.exponential import (exp, log) from sympy.functions.elementary.hyperbolic import (acosh, cosh) from sympy.functions.elementary.integers import (ceiling, floor) from sympy.functions.elementary.miscellaneous import (Max, sqrt) from sympy.functions.elementary.trigonometric import (acos, atan, cos, sin, tan) from sympy.integrals.integrals import (Integral, integrate) from sympy.polys.polytools import factor from sympy.polys.rootoftools import CRootOf from sympy.polys.specialpolys import cyclotomic_poly from sympy.printing import srepr from sympy.printing.str import sstr from sympy.simplify.simplify import simplify from sympy.core.numbers import comp from sympy.core.evalf import (complex_accuracy, PrecisionExhausted, scaled_zero, get_integer_part, as_mpmath, evalf, _evalf_with_bounded_error) from mpmath import inf, ninf, make_mpc from mpmath.libmp.libmpf import from_float, fzero from sympy.core.expr import unchanged from sympy.testing.pytest import raises, XFAIL from sympy.abc import n, x, y def NS(e, n=15, **options): return sstr(sympify(e).evalf(n, **options), full_prec=True) def test_evalf_helpers(): from mpmath.libmp import finf assert complex_accuracy((from_float(2.0), None, 35, None)) == 35 assert complex_accuracy((from_float(2.0), from_float(10.0), 35, 100)) == 37 assert complex_accuracy( (from_float(2.0), from_float(1000.0), 35, 100)) == 43 assert complex_accuracy((from_float(2.0), from_float(10.0), 100, 35)) == 35 assert complex_accuracy( (from_float(2.0), from_float(1000.0), 100, 35)) == 35 assert complex_accuracy(finf) == math.inf assert complex_accuracy(zoo) == math.inf raises(ValueError, lambda: get_integer_part(zoo, 1, {})) def test_evalf_basic(): assert NS('pi', 15) == '3.14159265358979' assert NS('2/3', 10) == '0.6666666667' assert NS('355/113-pi', 6) == '2.66764e-7' assert NS('16*atan(1/5)-4*atan(1/239)', 15) == '3.14159265358979' def test_cancellation(): assert NS(Add(pi, Rational(1, 10**1000), -pi, evaluate=False), 15, maxn=1200) == '1.00000000000000e-1000' def test_evalf_powers(): assert NS('pi**(10**20)', 10) == '1.339148777e+49714987269413385435' assert NS(pi**(10**100), 10) == ('4.946362032e+4971498726941338543512682882' '9089887365167832438044244613405349992494711208' '95526746555473864642912223') assert NS('2**(1/10**50)', 15) == '1.00000000000000' assert NS('2**(1/10**50)-1', 15) == '6.93147180559945e-51' # Evaluation of Rump's ill-conditioned polynomial def test_evalf_rump(): a = 1335*y**6/4 + x**2*(11*x**2*y**2 - y**6 - 121*y**4 - 2) + 11*y**8/2 + x/(2*y) assert NS(a, 15, subs={x: 77617, y: 33096}) == '-0.827396059946821' def test_evalf_complex(): assert NS('2*sqrt(pi)*I', 10) == '3.544907702*I' assert NS('3+3*I', 15) == '3.00000000000000 + 3.00000000000000*I' assert NS('E+pi*I', 15) == '2.71828182845905 + 3.14159265358979*I' assert NS('pi * (3+4*I)', 15) == '9.42477796076938 + 12.5663706143592*I' assert NS('I*(2+I)', 15) == '-1.00000000000000 + 2.00000000000000*I' @XFAIL def test_evalf_complex_bug(): assert NS('(pi+E*I)*(E+pi*I)', 15) in ('0.e-15 + 17.25866050002*I', '0.e-17 + 17.25866050002*I', '-0.e-17 + 17.25866050002*I') def test_evalf_complex_powers(): assert NS('(E+pi*I)**100000000000000000') == \ '-3.58896782867793e+61850354284995199 + 4.58581754997159e+61850354284995199*I' # XXX: rewrite if a+a*I simplification introduced in SymPy #assert NS('(pi + pi*I)**2') in ('0.e-15 + 19.7392088021787*I', '0.e-16 + 19.7392088021787*I') assert NS('(pi + pi*I)**2', chop=True) == '19.7392088021787*I' assert NS( '(pi + 1/10**8 + pi*I)**2') == '6.2831853e-8 + 19.7392088650106*I' assert NS('(pi + 1/10**12 + pi*I)**2') == '6.283e-12 + 19.7392088021850*I' assert NS('(pi + pi*I)**4', chop=True) == '-389.636364136010' assert NS( '(pi + 1/10**8 + pi*I)**4') == '-389.636366616512 + 2.4805021e-6*I' assert NS('(pi + 1/10**12 + pi*I)**4') == '-389.636364136258 + 2.481e-10*I' assert NS( '(10000*pi + 10000*pi*I)**4', chop=True) == '-3.89636364136010e+18' @XFAIL def test_evalf_complex_powers_bug(): assert NS('(pi + pi*I)**4') == '-389.63636413601 + 0.e-14*I' def test_evalf_exponentiation(): assert NS(sqrt(-pi)) == '1.77245385090552*I' assert NS(Pow(pi*I, Rational( 1, 2), evaluate=False)) == '1.25331413731550 + 1.25331413731550*I' assert NS(pi**I) == '0.413292116101594 + 0.910598499212615*I' assert NS(pi**(E + I/3)) == '20.8438653991931 + 8.36343473930031*I' assert NS((pi + I/3)**(E + I/3)) == '17.2442906093590 + 13.6839376767037*I' assert NS(exp(pi)) == '23.1406926327793' assert NS(exp(pi + E*I)) == '-21.0981542849657 + 9.50576358282422*I' assert NS(pi**pi) == '36.4621596072079' assert NS((-pi)**pi) == '-32.9138577418939 - 15.6897116534332*I' assert NS((-pi)**(-pi)) == '-0.0247567717232697 + 0.0118013091280262*I' # An example from Smith, "Multiple Precision Complex Arithmetic and Functions" def test_evalf_complex_cancellation(): A = Rational('63287/100000') B = Rational('52498/100000') C = Rational('69301/100000') D = Rational('83542/100000') F = Rational('2231321613/2500000000') # XXX: the number of returned mantissa digits in the real part could # change with the implementation. What matters is that the returned digits are # correct; those that are showing now are correct. # >>> ((A+B*I)*(C+D*I)).expand() # 64471/10000000000 + 2231321613*I/2500000000 # >>> 2231321613*4 # 8925286452L assert NS((A + B*I)*(C + D*I), 6) == '6.44710e-6 + 0.892529*I' assert NS((A + B*I)*(C + D*I), 10) == '6.447100000e-6 + 0.8925286452*I' assert NS((A + B*I)*( C + D*I) - F*I, 5) in ('6.4471e-6 + 0.e-14*I', '6.4471e-6 - 0.e-14*I') def test_evalf_logs(): assert NS("log(3+pi*I)", 15) == '1.46877619736226 + 0.808448792630022*I' assert NS("log(pi*I)", 15) == '1.14472988584940 + 1.57079632679490*I' assert NS('log(-1 + 0.00001)', 2) == '-1.0e-5 + 3.1*I' assert NS('log(100, 10, evaluate=False)', 15) == '2.00000000000000' assert NS('-2*I*log(-(-1)**(S(1)/9))', 15) == '-5.58505360638185' def test_evalf_trig(): assert NS('sin(1)', 15) == '0.841470984807897' assert NS('cos(1)', 15) == '0.540302305868140' assert NS('sin(10**-6)', 15) == '9.99999999999833e-7' assert NS('cos(10**-6)', 15) == '0.999999999999500' assert NS('sin(E*10**100)', 15) == '0.409160531722613' # Some input near roots assert NS(sin(exp(pi*sqrt(163))*pi), 15) == '-2.35596641936785e-12' assert NS(sin(pi*10**100 + Rational(7, 10**5), evaluate=False), 15, maxn=120) == \ '6.99999999428333e-5' assert NS(sin(Rational(7, 10**5), evaluate=False), 15) == \ '6.99999999428333e-5' # Check detection of various false identities def test_evalf_near_integers(): # Binet's formula f = lambda n: ((1 + sqrt(5))**n)/(2**n * sqrt(5)) assert NS(f(5000) - fibonacci(5000), 10, maxn=1500) == '5.156009964e-1046' # Some near-integer identities from # http://mathworld.wolfram.com/AlmostInteger.html assert NS('sin(2017*2**(1/5))', 15) == '-1.00000000000000' assert NS('sin(2017*2**(1/5))', 20) == '-0.99999999999999997857' assert NS('1+sin(2017*2**(1/5))', 15) == '2.14322287389390e-17' assert NS('45 - 613*E/37 + 35/991', 15) == '6.03764498766326e-11' def test_evalf_ramanujan(): assert NS(exp(pi*sqrt(163)) - 640320**3 - 744, 10) == '-7.499274028e-13' # A related identity A = 262537412640768744*exp(-pi*sqrt(163)) B = 196884*exp(-2*pi*sqrt(163)) C = 103378831900730205293632*exp(-3*pi*sqrt(163)) assert NS(1 - A - B + C, 10) == '1.613679005e-59' # Input that for various reasons have failed at some point def test_evalf_bugs(): assert NS(sin(1) + exp(-10**10), 10) == NS(sin(1), 10) assert NS(exp(10**10) + sin(1), 10) == NS(exp(10**10), 10) assert NS('expand_log(log(1+1/10**50))', 20) == '1.0000000000000000000e-50' assert NS('log(10**100,10)', 10) == '100.0000000' assert NS('log(2)', 10) == '0.6931471806' assert NS( '(sin(x)-x)/x**3', 15, subs={x: '1/10**50'}) == '-0.166666666666667' assert NS(sin(1) + Rational( 1, 10**100)*I, 15) == '0.841470984807897 + 1.00000000000000e-100*I' assert x.evalf() == x assert NS((1 + I)**2*I, 6) == '-2.00000' d = {n: ( -1)**Rational(6, 7), y: (-1)**Rational(4, 7), x: (-1)**Rational(2, 7)} assert NS((x*(1 + y*(1 + n))).subs(d).evalf(), 6) == '0.346011 + 0.433884*I' assert NS(((-I - sqrt(2)*I)**2).evalf()) == '-5.82842712474619' assert NS((1 + I)**2*I, 15) == '-2.00000000000000' # issue 4758 (1/2): assert NS(pi.evalf(69) - pi) == '-4.43863937855894e-71' # issue 4758 (2/2): With the bug present, this still only fails if the # terms are in the order given here. This is not generally the case, # because the order depends on the hashes of the terms. assert NS(20 - 5008329267844*n**25 - 477638700*n**37 - 19*n, subs={n: .01}) == '19.8100000000000' assert NS(((x - 1)*(1 - x)**1000).n() ) == '(1.00000000000000 - x)**1000*(x - 1.00000000000000)' assert NS((-x).n()) == '-x' assert NS((-2*x).n()) == '-2.00000000000000*x' assert NS((-2*x*y).n()) == '-2.00000000000000*x*y' assert cos(x).n(subs={x: 1+I}) == cos(x).subs(x, 1+I).n() # issue 6660. Also NaN != mpmath.nan # In this order: # 0*nan, 0/nan, 0*inf, 0/inf # 0+nan, 0-nan, 0+inf, 0-inf # >>> n = Some Number # n*nan, n/nan, n*inf, n/inf # n+nan, n-nan, n+inf, n-inf assert (0*E**(oo)).n() is S.NaN assert (0/E**(oo)).n() is S.Zero assert (0+E**(oo)).n() is S.Infinity assert (0-E**(oo)).n() is S.NegativeInfinity assert (5*E**(oo)).n() is S.Infinity assert (5/E**(oo)).n() is S.Zero assert (5+E**(oo)).n() is S.Infinity assert (5-E**(oo)).n() is S.NegativeInfinity #issue 7416 assert as_mpmath(0.0, 10, {'chop': True}) == 0 #issue 5412 assert ((oo*I).n() == S.Infinity*I) assert ((oo+oo*I).n() == S.Infinity + S.Infinity*I) #issue 11518 assert NS(2*x**2.5, 5) == '2.0000*x**2.5000' #issue 13076 assert NS(Mul(Max(0, y), x, evaluate=False).evalf()) == 'x*Max(0, y)' #issue 18516 assert NS(log(S(3273390607896141870013189696827599152216642046043064789483291368096133796404674554883270092325904157150886684127560071009217256545885393053328527589376)/36360291795869936842385267079543319118023385026001623040346035832580600191583895484198508262979388783308179702534403855752855931517013066142992430916562025780021771247847643450125342836565813209972590371590152578728008385990139795377610001).evalf(15, chop=True)) == '-oo' def test_evalf_integer_parts(): a = floor(log(8)/log(2) - exp(-1000), evaluate=False) b = floor(log(8)/log(2), evaluate=False) assert a.evalf() == 3 assert b.evalf() == 3 # equals, as a fallback, can still fail but it might succeed as here assert ceiling(10*(sin(1)**2 + cos(1)**2)) == 10 assert int(floor(factorial(50)/E, evaluate=False).evalf(70)) == \ int(11188719610782480504630258070757734324011354208865721592720336800) assert int(ceiling(factorial(50)/E, evaluate=False).evalf(70)) == \ int(11188719610782480504630258070757734324011354208865721592720336801) assert int(floor(GoldenRatio**999 / sqrt(5) + S.Half) .evalf(1000)) == fibonacci(999) assert int(floor(GoldenRatio**1000 / sqrt(5) + S.Half) .evalf(1000)) == fibonacci(1000) assert ceiling(x).evalf(subs={x: 3}) == 3 assert ceiling(x).evalf(subs={x: 3*I}) == 3.0*I assert ceiling(x).evalf(subs={x: 2 + 3*I}) == 2.0 + 3.0*I assert ceiling(x).evalf(subs={x: 3.}) == 3 assert ceiling(x).evalf(subs={x: 3.*I}) == 3.0*I assert ceiling(x).evalf(subs={x: 2. + 3*I}) == 2.0 + 3.0*I assert float((floor(1.5, evaluate=False)+1/9).evalf()) == 1 + 1/9 assert float((floor(0.5, evaluate=False)+20).evalf()) == 20 # issue 19991 n = 1169809367327212570704813632106852886389036911 r = 744723773141314414542111064094745678855643068 assert floor(n / (pi / 2)) == r assert floor(80782 * sqrt(2)) == 114242 # issue 20076 assert 260515 - floor(260515/pi + 1/2) * pi == atan(tan(260515)) def test_evalf_trig_zero_detection(): a = sin(160*pi, evaluate=False) t = a.evalf(maxn=100) assert abs(t) < 1e-100 assert t._prec < 2 assert a.evalf(chop=True) == 0 raises(PrecisionExhausted, lambda: a.evalf(strict=True)) def test_evalf_sum(): assert Sum(n,(n,1,2)).evalf() == 3. assert Sum(n,(n,1,2)).doit().evalf() == 3. # the next test should return instantly assert Sum(1/n,(n,1,2)).evalf() == 1.5 # issue 8219 assert Sum(E/factorial(n), (n, 0, oo)).evalf() == (E*E).evalf() # issue 8254 assert Sum(2**n*n/factorial(n), (n, 0, oo)).evalf() == (2*E*E).evalf() # issue 8411 s = Sum(1/x**2, (x, 100, oo)) assert s.n() == s.doit().n() def test_evalf_divergent_series(): raises(ValueError, lambda: Sum(1/n, (n, 1, oo)).evalf()) raises(ValueError, lambda: Sum(n/(n**2 + 1), (n, 1, oo)).evalf()) raises(ValueError, lambda: Sum((-1)**n, (n, 1, oo)).evalf()) raises(ValueError, lambda: Sum((-1)**n, (n, 1, oo)).evalf()) raises(ValueError, lambda: Sum(n**2, (n, 1, oo)).evalf()) raises(ValueError, lambda: Sum(2**n, (n, 1, oo)).evalf()) raises(ValueError, lambda: Sum((-2)**n, (n, 1, oo)).evalf()) raises(ValueError, lambda: Sum((2*n + 3)/(3*n**2 + 4), (n, 0, oo)).evalf()) raises(ValueError, lambda: Sum((0.5*n**3)/(n**4 + 1), (n, 0, oo)).evalf()) def test_evalf_product(): assert Product(n, (n, 1, 10)).evalf() == 3628800. assert comp(Product(1 - S.Half**2/n**2, (n, 1, oo)).n(5), 0.63662) assert Product(n, (n, -1, 3)).evalf() == 0 def test_evalf_py_methods(): assert abs(float(pi + 1) - 4.1415926535897932) < 1e-10 assert abs(complex(pi + 1) - 4.1415926535897932) < 1e-10 assert abs( complex(pi + E*I) - (3.1415926535897931 + 2.7182818284590451j)) < 1e-10 raises(TypeError, lambda: float(pi + x)) def test_evalf_power_subs_bugs(): assert (x**2).evalf(subs={x: 0}) == 0 assert sqrt(x).evalf(subs={x: 0}) == 0 assert (x**Rational(2, 3)).evalf(subs={x: 0}) == 0 assert (x**x).evalf(subs={x: 0}) == 1 assert (3**x).evalf(subs={x: 0}) == 1 assert exp(x).evalf(subs={x: 0}) == 1 assert ((2 + I)**x).evalf(subs={x: 0}) == 1 assert (0**x).evalf(subs={x: 0}) == 1 def test_evalf_arguments(): raises(TypeError, lambda: pi.evalf(method="garbage")) def test_implemented_function_evalf(): from sympy.utilities.lambdify import implemented_function f = Function('f') f = implemented_function(f, lambda x: x + 1) assert str(f(x)) == "f(x)" assert str(f(2)) == "f(2)" assert f(2).evalf() == 3 assert f(x).evalf() == f(x) f = implemented_function(Function('sin'), lambda x: x + 1) assert f(2).evalf() != sin(2) del f._imp_ # XXX: due to caching _imp_ would influence all other tests def test_evaluate_false(): for no in [0, False]: assert Add(3, 2, evaluate=no).is_Add assert Mul(3, 2, evaluate=no).is_Mul assert Pow(3, 2, evaluate=no).is_Pow assert Pow(y, 2, evaluate=True) - Pow(y, 2, evaluate=True) == 0 def test_evalf_relational(): assert Eq(x/5, y/10).evalf() == Eq(0.2*x, 0.1*y) # if this first assertion fails it should be replaced with # one that doesn't assert unchanged(Eq, (3 - I)**2/2 + I, 0) assert Eq((3 - I)**2/2 + I, 0).n() is S.false assert nfloat(Eq((3 - I)**2 + I, 0)) == S.false def test_issue_5486(): assert not cos(sqrt(0.5 + I)).n().is_Function def test_issue_5486_bug(): from sympy.core.expr import Expr from sympy.core.numbers import I assert abs(Expr._from_mpmath(I._to_mpmath(15), 15) - I) < 1.0e-15 def test_bugs(): from sympy.functions.elementary.complexes import (polar_lift, re) assert abs(re((1 + I)**2)) < 1e-15 # anything that evalf's to 0 will do in place of polar_lift assert abs(polar_lift(0)).n() == 0 def test_subs(): assert NS('besseli(-x, y) - besseli(x, y)', subs={x: 3.5, y: 20.0}) == \ '-4.92535585957223e-10' assert NS('Piecewise((x, x>0)) + Piecewise((1-x, x>0))', subs={x: 0.1}) == \ '1.00000000000000' raises(TypeError, lambda: x.evalf(subs=(x, 1))) def test_issue_4956_5204(): # issue 4956 v = S('''(-27*12**(1/3)*sqrt(31)*I + 27*2**(2/3)*3**(1/3)*sqrt(31)*I)/(-2511*2**(2/3)*3**(1/3) + (29*18**(1/3) + 9*2**(1/3)*3**(2/3)*sqrt(31)*I + 87*2**(1/3)*3**(1/6)*I)**2)''') assert NS(v, 1) == '0.e-118 - 0.e-118*I' # issue 5204 v = S('''-(357587765856 + 18873261792*249**(1/2) + 56619785376*I*83**(1/2) + 108755765856*I*3**(1/2) + 41281887168*6**(1/3)*(1422 + 54*249**(1/2))**(1/3) - 1239810624*6**(1/3)*249**(1/2)*(1422 + 54*249**(1/2))**(1/3) - 3110400000*I*6**(1/3)*83**(1/2)*(1422 + 54*249**(1/2))**(1/3) + 13478400000*I*3**(1/2)*6**(1/3)*(1422 + 54*249**(1/2))**(1/3) + 1274950152*6**(2/3)*(1422 + 54*249**(1/2))**(2/3) + 32347944*6**(2/3)*249**(1/2)*(1422 + 54*249**(1/2))**(2/3) - 1758790152*I*3**(1/2)*6**(2/3)*(1422 + 54*249**(1/2))**(2/3) - 304403832*I*6**(2/3)*83**(1/2)*(1422 + 4*249**(1/2))**(2/3))/(175732658352 + (1106028 + 25596*249**(1/2) + 76788*I*83**(1/2))**2)''') assert NS(v, 5) == '0.077284 + 1.1104*I' assert NS(v, 1) == '0.08 + 1.*I' def test_old_docstring(): a = (E + pi*I)*(E - pi*I) assert NS(a) == '17.2586605000200' assert a.n() == 17.25866050002001 def test_issue_4806(): assert integrate(atan(x)**2, (x, -1, 1)).evalf().round(1) == 0.5 assert atan(0, evaluate=False).n() == 0 def test_evalf_mul(): # SymPy should not try to expand this; it should be handled term-wise # in evalf through mpmath assert NS(product(1 + sqrt(n)*I, (n, 1, 500)), 1) == '5.e+567 + 2.e+568*I' def test_scaled_zero(): a, b = (([0], 1, 100, 1), -1) assert scaled_zero(100) == (a, b) assert scaled_zero(a) == (0, 1, 100, 1) a, b = (([1], 1, 100, 1), -1) assert scaled_zero(100, -1) == (a, b) assert scaled_zero(a) == (1, 1, 100, 1) raises(ValueError, lambda: scaled_zero(scaled_zero(100))) raises(ValueError, lambda: scaled_zero(100, 2)) raises(ValueError, lambda: scaled_zero(100, 0)) raises(ValueError, lambda: scaled_zero((1, 5, 1, 3))) def test_chop_value(): for i in range(-27, 28): assert (Pow(10, i)*2).n(chop=10**i) and not (Pow(10, i)).n(chop=10**i) def test_infinities(): assert oo.evalf(chop=True) == inf assert (-oo).evalf(chop=True) == ninf def test_to_mpmath(): assert sqrt(3)._to_mpmath(20)._mpf_ == (0, int(908093), -19, 20) assert S(3.2)._to_mpmath(20)._mpf_ == (0, int(838861), -18, 20) def test_issue_6632_evalf(): add = (-100000*sqrt(2500000001) + 5000000001) assert add.n() == 9.999999998e-11 assert (add*add).n() == 9.999999996e-21 def test_issue_4945(): from sympy.abc import H assert (H/0).evalf(subs={H:1}) == zoo def test_evalf_integral(): # test that workprec has to increase in order to get a result other than 0 eps = Rational(1, 1000000) assert Integral(sin(x), (x, -pi, pi + eps)).n(2)._prec == 10 def test_issue_8821_highprec_from_str(): s = str(pi.evalf(128)) p = N(s) assert Abs(sin(p)) < 1e-15 p = N(s, 64) assert Abs(sin(p)) < 1e-64 def test_issue_8853(): p = Symbol('x', even=True, positive=True) assert floor(-p - S.Half).is_even == False assert floor(-p + S.Half).is_even == True assert ceiling(p - S.Half).is_even == True assert ceiling(p + S.Half).is_even == False assert get_integer_part(S.Half, -1, {}, True) == (0, 0) assert get_integer_part(S.Half, 1, {}, True) == (1, 0) assert get_integer_part(Rational(-1, 2), -1, {}, True) == (-1, 0) assert get_integer_part(Rational(-1, 2), 1, {}, True) == (0, 0) def test_issue_17681(): class identity_func(Function): def _eval_evalf(self, *args, **kwargs): return self.args[0].evalf(*args, **kwargs) assert floor(identity_func(S(0))) == 0 assert get_integer_part(S(0), 1, {}, True) == (0, 0) def test_issue_9326(): from sympy.core.symbol import Dummy d1 = Dummy('d') d2 = Dummy('d') e = d1 + d2 assert e.evalf(subs = {d1: 1, d2: 2}) == 3 def test_issue_10323(): assert ceiling(sqrt(2**30 + 1)) == 2**15 + 1 def test_AssocOp_Function(): # the first arg of Min is not comparable in the imaginary part raises(ValueError, lambda: S(''' Min(-sqrt(3)*cos(pi/18)/6 + re(1/((-1/2 - sqrt(3)*I/2)*(1/6 + sqrt(3)*I/18)**(1/3)))/3 + sin(pi/18)/2 + 2 + I*(-cos(pi/18)/2 - sqrt(3)*sin(pi/18)/6 + im(1/((-1/2 - sqrt(3)*I/2)*(1/6 + sqrt(3)*I/18)**(1/3)))/3), re(1/((-1/2 + sqrt(3)*I/2)*(1/6 + sqrt(3)*I/18)**(1/3)))/3 - sqrt(3)*cos(pi/18)/6 - sin(pi/18)/2 + 2 + I*(im(1/((-1/2 + sqrt(3)*I/2)*(1/6 + sqrt(3)*I/18)**(1/3)))/3 - sqrt(3)*sin(pi/18)/6 + cos(pi/18)/2))''')) # if that is changed so a non-comparable number remains as # an arg, then the Min/Max instantiation needs to be changed # to watch out for non-comparable args when making simplifications # and the following test should be added instead (with e being # the sympified expression above): # raises(ValueError, lambda: e._eval_evalf(2)) def test_issue_10395(): eq = x*Max(0, y) assert nfloat(eq) == eq eq = x*Max(y, -1.1) assert nfloat(eq) == eq assert Max(y, 4).n() == Max(4.0, y) def test_issue_13098(): assert floor(log(S('9.'+'9'*20), 10)) == 0 assert ceiling(log(S('9.'+'9'*20), 10)) == 1 assert floor(log(20 - S('9.'+'9'*20), 10)) == 1 assert ceiling(log(20 - S('9.'+'9'*20), 10)) == 2 def test_issue_14601(): e = 5*x*y/2 - y*(35*(x**3)/2 - 15*x/2) subst = {x:0.0, y:0.0} e2 = e.evalf(subs=subst) assert float(e2) == 0.0 assert float((x + x*(x**2 + x)).evalf(subs={x: 0.0})) == 0.0 def test_issue_11151(): z = S.Zero e = Sum(z, (x, 1, 2)) assert e != z # it shouldn't evaluate # when it does evaluate, this is what it should give assert evalf(e, 15, {}) == \ evalf(z, 15, {}) == (None, None, 15, None) # so this shouldn't fail assert (e/2).n() == 0 # this was where the issue appeared expr0 = Sum(x**2 + x, (x, 1, 2)) expr1 = Sum(0, (x, 1, 2)) expr2 = expr1/expr0 assert simplify(factor(expr2) - expr2) == 0 def test_issue_13425(): assert N('2**.5', 30) == N('sqrt(2)', 30) assert N('x - x', 30) == 0 assert abs((N('pi*.1', 22)*10 - pi).n()) < 1e-22 def test_issue_17421(): assert N(acos(-I + acosh(cosh(cosh(1) + I)))) == 1.0*I def test_issue_20291(): from sympy.sets import EmptySet, Reals from sympy.sets.sets import (Complement, FiniteSet, Intersection) a = Symbol('a') b = Symbol('b') A = FiniteSet(a, b) assert A.evalf(subs={a: 1, b: 2}) == FiniteSet(1.0, 2.0) B = FiniteSet(a-b, 1) assert B.evalf(subs={a: 1, b: 2}) == FiniteSet(-1.0, 1.0) sol = Complement(Intersection(FiniteSet(-b/2 - sqrt(b**2-4*pi)/2), Reals), FiniteSet(0)) assert sol.evalf(subs={b: 1}) == EmptySet def test_evalf_with_zoo(): assert (1/x).evalf(subs={x: 0}) == zoo # issue 8242 assert (-1/x).evalf(subs={x: 0}) == zoo # PR 16150 assert (0 ** x).evalf(subs={x: -1}) == zoo # PR 16150 assert (0 ** x).evalf(subs={x: -1 + I}) == nan assert Mul(2, Pow(0, -1, evaluate=False), evaluate=False).evalf() == zoo # issue 21147 assert Mul(x, 1/x, evaluate=False).evalf(subs={x: 0}) == Mul(x, 1/x, evaluate=False).subs(x, 0) == nan assert Mul(1/x, 1/x, evaluate=False).evalf(subs={x: 0}) == zoo assert Mul(1/x, Abs(1/x), evaluate=False).evalf(subs={x: 0}) == zoo assert Abs(zoo, evaluate=False).evalf() == oo assert re(zoo, evaluate=False).evalf() == nan assert im(zoo, evaluate=False).evalf() == nan assert Add(zoo, zoo, evaluate=False).evalf() == nan assert Add(oo, zoo, evaluate=False).evalf() == nan assert Pow(zoo, -1, evaluate=False).evalf() == 0 assert Pow(zoo, Rational(-1, 3), evaluate=False).evalf() == 0 assert Pow(zoo, Rational(1, 3), evaluate=False).evalf() == zoo assert Pow(zoo, S.Half, evaluate=False).evalf() == zoo assert Pow(zoo, 2, evaluate=False).evalf() == zoo assert Pow(0, zoo, evaluate=False).evalf() == nan assert log(zoo, evaluate=False).evalf() == zoo assert zoo.evalf(chop=True) == zoo assert x.evalf(subs={x: zoo}) == zoo def test_evalf_with_bounded_error(): cases = [ # zero (Rational(0), None, 1), # zero im part (pi, None, 10), # zero real part (pi*I, None, 10), # re and im nonzero (2-3*I, None, 5), # similar tests again, but using eps instead of m (Rational(0), Rational(1, 2), None), (pi, Rational(1, 1000), None), (pi * I, Rational(1, 1000), None), (2 - 3 * I, Rational(1, 1000), None), # very large eps (2 - 3 * I, Rational(1000), None), # case where x already small, hence some cancelation in p = m + n - 1 (Rational(1234, 10**8), Rational(1, 10**12), None), ] for x0, eps, m in cases: a, b, _, _ = evalf(x0, 53, {}) c, d, _, _ = _evalf_with_bounded_error(x0, eps, m) if eps is None: eps = 2**(-m) z = make_mpc((a or fzero, b or fzero)) w = make_mpc((c or fzero, d or fzero)) assert abs(w - z) < eps # eps must be positive raises(ValueError, lambda: _evalf_with_bounded_error(pi, Rational(0))) raises(ValueError, lambda: _evalf_with_bounded_error(pi, -pi)) raises(ValueError, lambda: _evalf_with_bounded_error(pi, I)) def test_issue_22849(): a = -8 + 3 * sqrt(3) x = AlgebraicNumber(a) assert evalf(a, 1, {}) == evalf(x, 1, {}) def test_evalf_real_alg_num(): # This test demonstrates why the entry for `AlgebraicNumber` in # `sympy.core.evalf._create_evalf_table()` has to use `x.to_root()`, # instead of `x.as_expr()`. If the latter is used, then `z` will be # a complex number with `0.e-20` for imaginary part, even though `a5` # is a real number. zeta = Symbol('zeta') a5 = AlgebraicNumber(CRootOf(cyclotomic_poly(5), -1), [-1, -1, 0, 0], alias=zeta) z = a5.evalf() assert isinstance(z, Float) assert not hasattr(z, '_mpc_') assert hasattr(z, '_mpf_') def test_issue_20733(): expr = 1/((x - 9)*(x - 8)*(x - 7)*(x - 4)**2*(x - 3)**3*(x - 2)) assert str(expr.evalf(1, subs={x:1})) == '-4.e-5' assert str(expr.evalf(2, subs={x:1})) == '-4.1e-5' assert str(expr.evalf(11, subs={x:1})) == '-4.1335978836e-5' assert str(expr.evalf(20, subs={x:1})) == '-0.000041335978835978835979' expr = Mul(*((x - i) for i in range(2, 1000))) assert srepr(expr.evalf(2, subs={x: 1})) == "Float('4.0271e+2561', precision=10)" assert srepr(expr.evalf(10, subs={x: 1})) == "Float('4.02790050126e+2561', precision=37)" assert srepr(expr.evalf(53, subs={x: 1})) == "Float('4.0279005012722099453824067459760158730668154575647110393e+2561', precision=179)"
4e57c347f1cf49fd58307ea8a6df665100696a9c50c4258f7dc883d9ce11a727
from sympy.core.add import Add from sympy.core.basic import Basic from sympy.core.mod import Mod from sympy.core.mul import Mul from sympy.core.numbers import (Float, I, Integer, Rational, comp, nan, oo, pi, zoo) from sympy.core.power import Pow from sympy.core.singleton import S from sympy.core.symbol import (Dummy, Symbol, symbols) from sympy.core.sympify import sympify from sympy.functions.combinatorial.factorials import factorial from sympy.functions.elementary.complexes import (im, re, sign) from sympy.functions.elementary.exponential import (exp, log) from sympy.functions.elementary.integers import floor from sympy.functions.elementary.miscellaneous import (Max, sqrt) from sympy.functions.elementary.trigonometric import (atan, cos, sin) from sympy.polys.polytools import Poly from sympy.sets.sets import FiniteSet from sympy.core.parameters import distribute from sympy.core.expr import unchanged from sympy.utilities.iterables import permutations from sympy.testing.pytest import XFAIL, raises, warns from sympy.utilities.exceptions import SymPyDeprecationWarning from sympy.core.random import verify_numerically from sympy.functions.elementary.trigonometric import asin from itertools import product a, c, x, y, z = symbols('a,c,x,y,z') b = Symbol("b", positive=True) def same_and_same_prec(a, b): # stricter matching for Floats return a == b and a._prec == b._prec def test_bug1(): assert re(x) != x x.series(x, 0, 1) assert re(x) != x def test_Symbol(): e = a*b assert e == a*b assert a*b*b == a*b**2 assert a*b*b + c == c + a*b**2 assert a*b*b - c == -c + a*b**2 x = Symbol('x', complex=True, real=False) assert x.is_imaginary is None # could be I or 1 + I x = Symbol('x', complex=True, imaginary=False) assert x.is_real is None # could be 1 or 1 + I x = Symbol('x', real=True) assert x.is_complex x = Symbol('x', imaginary=True) assert x.is_complex x = Symbol('x', real=False, imaginary=False) assert x.is_complex is None # might be a non-number def test_arit0(): p = Rational(5) e = a*b assert e == a*b e = a*b + b*a assert e == 2*a*b e = a*b + b*a + a*b + p*b*a assert e == 8*a*b e = a*b + b*a + a*b + p*b*a + a assert e == a + 8*a*b e = a + a assert e == 2*a e = a + b + a assert e == b + 2*a e = a + b*b + a + b*b assert e == 2*a + 2*b**2 e = a + Rational(2) + b*b + a + b*b + p assert e == 7 + 2*a + 2*b**2 e = (a + b*b + a + b*b)*p assert e == 5*(2*a + 2*b**2) e = (a*b*c + c*b*a + b*a*c)*p assert e == 15*a*b*c e = (a*b*c + c*b*a + b*a*c)*p - Rational(15)*a*b*c assert e == Rational(0) e = Rational(50)*(a - a) assert e == Rational(0) e = b*a - b - a*b + b assert e == Rational(0) e = a*b + c**p assert e == a*b + c**5 e = a/b assert e == a*b**(-1) e = a*2*2 assert e == 4*a e = 2 + a*2/2 assert e == 2 + a e = 2 - a - 2 assert e == -a e = 2*a*2 assert e == 4*a e = 2/a/2 assert e == a**(-1) e = 2**a**2 assert e == 2**(a**2) e = -(1 + a) assert e == -1 - a e = S.Half*(1 + a) assert e == S.Half + a/2 def test_div(): e = a/b assert e == a*b**(-1) e = a/b + c/2 assert e == a*b**(-1) + Rational(1)/2*c e = (1 - b)/(b - 1) assert e == (1 + -b)*((-1) + b)**(-1) def test_pow(): n1 = Rational(1) n2 = Rational(2) n5 = Rational(5) e = a*a assert e == a**2 e = a*a*a assert e == a**3 e = a*a*a*a**Rational(6) assert e == a**9 e = a*a*a*a**Rational(6) - a**Rational(9) assert e == Rational(0) e = a**(b - b) assert e == Rational(1) e = (a + Rational(1) - a)**b assert e == Rational(1) e = (a + b + c)**n2 assert e == (a + b + c)**2 assert e.expand() == 2*b*c + 2*a*c + 2*a*b + a**2 + c**2 + b**2 e = (a + b)**n2 assert e == (a + b)**2 assert e.expand() == 2*a*b + a**2 + b**2 e = (a + b)**(n1/n2) assert e == sqrt(a + b) assert e.expand() == sqrt(a + b) n = n5**(n1/n2) assert n == sqrt(5) e = n*a*b - n*b*a assert e == Rational(0) e = n*a*b + n*b*a assert e == 2*a*b*sqrt(5) assert e.diff(a) == 2*b*sqrt(5) assert e.diff(a) == 2*b*sqrt(5) e = a/b**2 assert e == a*b**(-2) assert sqrt(2*(1 + sqrt(2))) == (2*(1 + 2**S.Half))**S.Half x = Symbol('x') y = Symbol('y') assert ((x*y)**3).expand() == y**3 * x**3 assert ((x*y)**-3).expand() == y**-3 * x**-3 assert (x**5*(3*x)**(3)).expand() == 27 * x**8 assert (x**5*(-3*x)**(3)).expand() == -27 * x**8 assert (x**5*(3*x)**(-3)).expand() == x**2 * Rational(1, 27) assert (x**5*(-3*x)**(-3)).expand() == x**2 * Rational(-1, 27) # expand_power_exp assert (x**(y**(x + exp(x + y)) + z)).expand(deep=False) == \ x**z*x**(y**(x + exp(x + y))) assert (x**(y**(x + exp(x + y)) + z)).expand() == \ x**z*x**(y**x*y**(exp(x)*exp(y))) n = Symbol('n', even=False) k = Symbol('k', even=True) o = Symbol('o', odd=True) assert unchanged(Pow, -1, x) assert unchanged(Pow, -1, n) assert (-2)**k == 2**k assert (-1)**k == 1 assert (-1)**o == -1 def test_pow2(): # x**(2*y) is always (x**y)**2 but is only (x**2)**y if # x.is_positive or y.is_integer # let x = 1 to see why the following are not true. assert (-x)**Rational(2, 3) != x**Rational(2, 3) assert (-x)**Rational(5, 7) != -x**Rational(5, 7) assert ((-x)**2)**Rational(1, 3) != ((-x)**Rational(1, 3))**2 assert sqrt(x**2) != x def test_pow3(): assert sqrt(2)**3 == 2 * sqrt(2) assert sqrt(2)**3 == sqrt(8) def test_mod_pow(): for s, t, u, v in [(4, 13, 497, 445), (4, -3, 497, 365), (3.2, 2.1, 1.9, 0.1031015682350942), (S(3)/2, 5, S(5)/6, S(3)/32)]: assert pow(S(s), t, u) == v assert pow(S(s), S(t), u) == v assert pow(S(s), t, S(u)) == v assert pow(S(s), S(t), S(u)) == v assert pow(S(2), S(10000000000), S(3)) == 1 assert pow(x, y, z) == x**y%z raises(TypeError, lambda: pow(S(4), "13", 497)) raises(TypeError, lambda: pow(S(4), 13, "497")) def test_pow_E(): assert 2**(y/log(2)) == S.Exp1**y assert 2**(y/log(2)/3) == S.Exp1**(y/3) assert 3**(1/log(-3)) != S.Exp1 assert (3 + 2*I)**(1/(log(-3 - 2*I) + I*pi)) == S.Exp1 assert (4 + 2*I)**(1/(log(-4 - 2*I) + I*pi)) == S.Exp1 assert (3 + 2*I)**(1/(log(-3 - 2*I, 3)/2 + I*pi/log(3)/2)) == 9 assert (3 + 2*I)**(1/(log(3 + 2*I, 3)/2)) == 9 # every time tests are run they will affirm with a different random # value that this identity holds while 1: b = x._random() r, i = b.as_real_imag() if i: break assert verify_numerically(b**(1/(log(-b) + sign(i)*I*pi).n()), S.Exp1) def test_pow_issue_3516(): assert 4**Rational(1, 4) == sqrt(2) def test_pow_im(): for m in (-2, -1, 2): for d in (3, 4, 5): b = m*I for i in range(1, 4*d + 1): e = Rational(i, d) assert (b**e - b.n()**e.n()).n(2, chop=1e-10) == 0 e = Rational(7, 3) assert (2*x*I)**e == 4*2**Rational(1, 3)*(I*x)**e # same as Wolfram Alpha im = symbols('im', imaginary=True) assert (2*im*I)**e == 4*2**Rational(1, 3)*(I*im)**e args = [I, I, I, I, 2] e = Rational(1, 3) ans = 2**e assert Mul(*args, evaluate=False)**e == ans assert Mul(*args)**e == ans args = [I, I, I, 2] e = Rational(1, 3) ans = 2**e*(-I)**e assert Mul(*args, evaluate=False)**e == ans assert Mul(*args)**e == ans args.append(-3) ans = (6*I)**e assert Mul(*args, evaluate=False)**e == ans assert Mul(*args)**e == ans args.append(-1) ans = (-6*I)**e assert Mul(*args, evaluate=False)**e == ans assert Mul(*args)**e == ans args = [I, I, 2] e = Rational(1, 3) ans = (-2)**e assert Mul(*args, evaluate=False)**e == ans assert Mul(*args)**e == ans args.append(-3) ans = (6)**e assert Mul(*args, evaluate=False)**e == ans assert Mul(*args)**e == ans args.append(-1) ans = (-6)**e assert Mul(*args, evaluate=False)**e == ans assert Mul(*args)**e == ans assert Mul(Pow(-1, Rational(3, 2), evaluate=False), I, I) == I assert Mul(I*Pow(I, S.Half, evaluate=False)) == sqrt(I)*I def test_real_mul(): assert Float(0) * pi * x == 0 assert set((Float(1) * pi * x).args) == {Float(1), pi, x} def test_ncmul(): A = Symbol("A", commutative=False) B = Symbol("B", commutative=False) C = Symbol("C", commutative=False) assert A*B != B*A assert A*B*C != C*B*A assert A*b*B*3*C == 3*b*A*B*C assert A*b*B*3*C != 3*b*B*A*C assert A*b*B*3*C == 3*A*B*C*b assert A + B == B + A assert (A + B)*C != C*(A + B) assert C*(A + B)*C != C*C*(A + B) assert A*A == A**2 assert (A + B)*(A + B) == (A + B)**2 assert A**-1 * A == 1 assert A/A == 1 assert A/(A**2) == 1/A assert A/(1 + A) == A/(1 + A) assert set((A + B + 2*(A + B)).args) == \ {A, B, 2*(A + B)} def test_mul_add_identity(): m = Mul(1, 2) assert isinstance(m, Rational) and m.p == 2 and m.q == 1 m = Mul(1, 2, evaluate=False) assert isinstance(m, Mul) and m.args == (1, 2) m = Mul(0, 1) assert m is S.Zero m = Mul(0, 1, evaluate=False) assert isinstance(m, Mul) and m.args == (0, 1) m = Add(0, 1) assert m is S.One m = Add(0, 1, evaluate=False) assert isinstance(m, Add) and m.args == (0, 1) def test_ncpow(): x = Symbol('x', commutative=False) y = Symbol('y', commutative=False) z = Symbol('z', commutative=False) a = Symbol('a') b = Symbol('b') c = Symbol('c') assert (x**2)*(y**2) != (y**2)*(x**2) assert (x**-2)*y != y*(x**2) assert 2**x*2**y != 2**(x + y) assert 2**x*2**y*2**z != 2**(x + y + z) assert 2**x*2**(2*x) == 2**(3*x) assert 2**x*2**(2*x)*2**x == 2**(4*x) assert exp(x)*exp(y) != exp(y)*exp(x) assert exp(x)*exp(y)*exp(z) != exp(y)*exp(x)*exp(z) assert exp(x)*exp(y)*exp(z) != exp(x + y + z) assert x**a*x**b != x**(a + b) assert x**a*x**b*x**c != x**(a + b + c) assert x**3*x**4 == x**7 assert x**3*x**4*x**2 == x**9 assert x**a*x**(4*a) == x**(5*a) assert x**a*x**(4*a)*x**a == x**(6*a) def test_powerbug(): x = Symbol("x") assert x**1 != (-x)**1 assert x**2 == (-x)**2 assert x**3 != (-x)**3 assert x**4 == (-x)**4 assert x**5 != (-x)**5 assert x**6 == (-x)**6 assert x**128 == (-x)**128 assert x**129 != (-x)**129 assert (2*x)**2 == (-2*x)**2 def test_Mul_doesnt_expand_exp(): x = Symbol('x') y = Symbol('y') assert unchanged(Mul, exp(x), exp(y)) assert unchanged(Mul, 2**x, 2**y) assert x**2*x**3 == x**5 assert 2**x*3**x == 6**x assert x**(y)*x**(2*y) == x**(3*y) assert sqrt(2)*sqrt(2) == 2 assert 2**x*2**(2*x) == 2**(3*x) assert sqrt(2)*2**Rational(1, 4)*5**Rational(3, 4) == 10**Rational(3, 4) assert (x**(-log(5)/log(3))*x)/(x*x**( - log(5)/log(3))) == sympify(1) def test_Mul_is_integer(): k = Symbol('k', integer=True) n = Symbol('n', integer=True) nr = Symbol('nr', rational=False) nz = Symbol('nz', integer=True, zero=False) e = Symbol('e', even=True) o = Symbol('o', odd=True) i2 = Symbol('2', prime=True, even=True) assert (k/3).is_integer is None assert (nz/3).is_integer is None assert (nr/3).is_integer is False assert (x*k*n).is_integer is None assert (e/2).is_integer is True assert (e**2/2).is_integer is True assert (2/k).is_integer is None assert (2/k**2).is_integer is None assert ((-1)**k*n).is_integer is True assert (3*k*e/2).is_integer is True assert (2*k*e/3).is_integer is None assert (e/o).is_integer is None assert (o/e).is_integer is False assert (o/i2).is_integer is False assert Mul(k, 1/k, evaluate=False).is_integer is None assert Mul(2., S.Half, evaluate=False).is_integer is None assert (2*sqrt(k)).is_integer is None assert (2*k**n).is_integer is None s = 2**2**2**Pow(2, 1000, evaluate=False) m = Mul(s, s, evaluate=False) assert m.is_integer # broken in 1.6 and before, see #20161 xq = Symbol('xq', rational=True) yq = Symbol('yq', rational=True) assert (xq*yq).is_integer is None e_20161 = Mul(-1,Mul(1,Pow(2,-1,evaluate=False),evaluate=False),evaluate=False) assert e_20161.is_integer is not True # expand(e_20161) -> -1/2, but no need to see that in the assumption without evaluation def test_Add_Mul_is_integer(): x = Symbol('x') k = Symbol('k', integer=True) n = Symbol('n', integer=True) nk = Symbol('nk', integer=False) nr = Symbol('nr', rational=False) nz = Symbol('nz', integer=True, zero=False) assert (-nk).is_integer is None assert (-nr).is_integer is False assert (2*k).is_integer is True assert (-k).is_integer is True assert (k + nk).is_integer is False assert (k + n).is_integer is True assert (k + x).is_integer is None assert (k + n*x).is_integer is None assert (k + n/3).is_integer is None assert (k + nz/3).is_integer is None assert (k + nr/3).is_integer is False assert ((1 + sqrt(3))*(-sqrt(3) + 1)).is_integer is not False assert (1 + (1 + sqrt(3))*(-sqrt(3) + 1)).is_integer is not False def test_Add_Mul_is_finite(): x = Symbol('x', extended_real=True, finite=False) assert sin(x).is_finite is True assert (x*sin(x)).is_finite is None assert (x*atan(x)).is_finite is False assert (1024*sin(x)).is_finite is True assert (sin(x)*exp(x)).is_finite is None assert (sin(x)*cos(x)).is_finite is True assert (x*sin(x)*exp(x)).is_finite is None assert (sin(x) - 67).is_finite is True assert (sin(x) + exp(x)).is_finite is not True assert (1 + x).is_finite is False assert (1 + x**2 + (1 + x)*(1 - x)).is_finite is None assert (sqrt(2)*(1 + x)).is_finite is False assert (sqrt(2)*(1 + x)*(1 - x)).is_finite is False def test_Mul_is_even_odd(): x = Symbol('x', integer=True) y = Symbol('y', integer=True) k = Symbol('k', odd=True) n = Symbol('n', odd=True) m = Symbol('m', even=True) assert (2*x).is_even is True assert (2*x).is_odd is False assert (3*x).is_even is None assert (3*x).is_odd is None assert (k/3).is_integer is None assert (k/3).is_even is None assert (k/3).is_odd is None assert (2*n).is_even is True assert (2*n).is_odd is False assert (2*m).is_even is True assert (2*m).is_odd is False assert (-n).is_even is False assert (-n).is_odd is True assert (k*n).is_even is False assert (k*n).is_odd is True assert (k*m).is_even is True assert (k*m).is_odd is False assert (k*n*m).is_even is True assert (k*n*m).is_odd is False assert (k*m*x).is_even is True assert (k*m*x).is_odd is False # issue 6791: assert (x/2).is_integer is None assert (k/2).is_integer is False assert (m/2).is_integer is True assert (x*y).is_even is None assert (x*x).is_even is None assert (x*(x + k)).is_even is True assert (x*(x + m)).is_even is None assert (x*y).is_odd is None assert (x*x).is_odd is None assert (x*(x + k)).is_odd is False assert (x*(x + m)).is_odd is None # issue 8648 assert (m**2/2).is_even assert (m**2/3).is_even is False assert (2/m**2).is_odd is False assert (2/m).is_odd is None @XFAIL def test_evenness_in_ternary_integer_product_with_odd(): # Tests that oddness inference is independent of term ordering. # Term ordering at the point of testing depends on SymPy's symbol order, so # we try to force a different order by modifying symbol names. x = Symbol('x', integer=True) y = Symbol('y', integer=True) k = Symbol('k', odd=True) assert (x*y*(y + k)).is_even is True assert (y*x*(x + k)).is_even is True def test_evenness_in_ternary_integer_product_with_even(): x = Symbol('x', integer=True) y = Symbol('y', integer=True) m = Symbol('m', even=True) assert (x*y*(y + m)).is_even is None @XFAIL def test_oddness_in_ternary_integer_product_with_odd(): # Tests that oddness inference is independent of term ordering. # Term ordering at the point of testing depends on SymPy's symbol order, so # we try to force a different order by modifying symbol names. x = Symbol('x', integer=True) y = Symbol('y', integer=True) k = Symbol('k', odd=True) assert (x*y*(y + k)).is_odd is False assert (y*x*(x + k)).is_odd is False def test_oddness_in_ternary_integer_product_with_even(): x = Symbol('x', integer=True) y = Symbol('y', integer=True) m = Symbol('m', even=True) assert (x*y*(y + m)).is_odd is None def test_Mul_is_rational(): x = Symbol('x') n = Symbol('n', integer=True) m = Symbol('m', integer=True, nonzero=True) assert (n/m).is_rational is True assert (x/pi).is_rational is None assert (x/n).is_rational is None assert (m/pi).is_rational is False r = Symbol('r', rational=True) assert (pi*r).is_rational is None # issue 8008 z = Symbol('z', zero=True) i = Symbol('i', imaginary=True) assert (z*i).is_rational is True bi = Symbol('i', imaginary=True, finite=True) assert (z*bi).is_zero is True def test_Add_is_rational(): x = Symbol('x') n = Symbol('n', rational=True) m = Symbol('m', rational=True) assert (n + m).is_rational is True assert (x + pi).is_rational is None assert (x + n).is_rational is None assert (n + pi).is_rational is False def test_Add_is_even_odd(): x = Symbol('x', integer=True) k = Symbol('k', odd=True) n = Symbol('n', odd=True) m = Symbol('m', even=True) assert (k + 7).is_even is True assert (k + 7).is_odd is False assert (-k + 7).is_even is True assert (-k + 7).is_odd is False assert (k - 12).is_even is False assert (k - 12).is_odd is True assert (-k - 12).is_even is False assert (-k - 12).is_odd is True assert (k + n).is_even is True assert (k + n).is_odd is False assert (k + m).is_even is False assert (k + m).is_odd is True assert (k + n + m).is_even is True assert (k + n + m).is_odd is False assert (k + n + x + m).is_even is None assert (k + n + x + m).is_odd is None def test_Mul_is_negative_positive(): x = Symbol('x', real=True) y = Symbol('y', extended_real=False, complex=True) z = Symbol('z', zero=True) e = 2*z assert e.is_Mul and e.is_positive is False and e.is_negative is False neg = Symbol('neg', negative=True) pos = Symbol('pos', positive=True) nneg = Symbol('nneg', nonnegative=True) npos = Symbol('npos', nonpositive=True) assert neg.is_negative is True assert (-neg).is_negative is False assert (2*neg).is_negative is True assert (2*pos)._eval_is_extended_negative() is False assert (2*pos).is_negative is False assert pos.is_negative is False assert (-pos).is_negative is True assert (2*pos).is_negative is False assert (pos*neg).is_negative is True assert (2*pos*neg).is_negative is True assert (-pos*neg).is_negative is False assert (pos*neg*y).is_negative is False # y.is_real=F; !real -> !neg assert nneg.is_negative is False assert (-nneg).is_negative is None assert (2*nneg).is_negative is False assert npos.is_negative is None assert (-npos).is_negative is False assert (2*npos).is_negative is None assert (nneg*npos).is_negative is None assert (neg*nneg).is_negative is None assert (neg*npos).is_negative is False assert (pos*nneg).is_negative is False assert (pos*npos).is_negative is None assert (npos*neg*nneg).is_negative is False assert (npos*pos*nneg).is_negative is None assert (-npos*neg*nneg).is_negative is None assert (-npos*pos*nneg).is_negative is False assert (17*npos*neg*nneg).is_negative is False assert (17*npos*pos*nneg).is_negative is None assert (neg*npos*pos*nneg).is_negative is False assert (x*neg).is_negative is None assert (nneg*npos*pos*x*neg).is_negative is None assert neg.is_positive is False assert (-neg).is_positive is True assert (2*neg).is_positive is False assert pos.is_positive is True assert (-pos).is_positive is False assert (2*pos).is_positive is True assert (pos*neg).is_positive is False assert (2*pos*neg).is_positive is False assert (-pos*neg).is_positive is True assert (-pos*neg*y).is_positive is False # y.is_real=F; !real -> !neg assert nneg.is_positive is None assert (-nneg).is_positive is False assert (2*nneg).is_positive is None assert npos.is_positive is False assert (-npos).is_positive is None assert (2*npos).is_positive is False assert (nneg*npos).is_positive is False assert (neg*nneg).is_positive is False assert (neg*npos).is_positive is None assert (pos*nneg).is_positive is None assert (pos*npos).is_positive is False assert (npos*neg*nneg).is_positive is None assert (npos*pos*nneg).is_positive is False assert (-npos*neg*nneg).is_positive is False assert (-npos*pos*nneg).is_positive is None assert (17*npos*neg*nneg).is_positive is None assert (17*npos*pos*nneg).is_positive is False assert (neg*npos*pos*nneg).is_positive is None assert (x*neg).is_positive is None assert (nneg*npos*pos*x*neg).is_positive is None def test_Mul_is_negative_positive_2(): a = Symbol('a', nonnegative=True) b = Symbol('b', nonnegative=True) c = Symbol('c', nonpositive=True) d = Symbol('d', nonpositive=True) assert (a*b).is_nonnegative is True assert (a*b).is_negative is False assert (a*b).is_zero is None assert (a*b).is_positive is None assert (c*d).is_nonnegative is True assert (c*d).is_negative is False assert (c*d).is_zero is None assert (c*d).is_positive is None assert (a*c).is_nonpositive is True assert (a*c).is_positive is False assert (a*c).is_zero is None assert (a*c).is_negative is None def test_Mul_is_nonpositive_nonnegative(): x = Symbol('x', real=True) k = Symbol('k', negative=True) n = Symbol('n', positive=True) u = Symbol('u', nonnegative=True) v = Symbol('v', nonpositive=True) assert k.is_nonpositive is True assert (-k).is_nonpositive is False assert (2*k).is_nonpositive is True assert n.is_nonpositive is False assert (-n).is_nonpositive is True assert (2*n).is_nonpositive is False assert (n*k).is_nonpositive is True assert (2*n*k).is_nonpositive is True assert (-n*k).is_nonpositive is False assert u.is_nonpositive is None assert (-u).is_nonpositive is True assert (2*u).is_nonpositive is None assert v.is_nonpositive is True assert (-v).is_nonpositive is None assert (2*v).is_nonpositive is True assert (u*v).is_nonpositive is True assert (k*u).is_nonpositive is True assert (k*v).is_nonpositive is None assert (n*u).is_nonpositive is None assert (n*v).is_nonpositive is True assert (v*k*u).is_nonpositive is None assert (v*n*u).is_nonpositive is True assert (-v*k*u).is_nonpositive is True assert (-v*n*u).is_nonpositive is None assert (17*v*k*u).is_nonpositive is None assert (17*v*n*u).is_nonpositive is True assert (k*v*n*u).is_nonpositive is None assert (x*k).is_nonpositive is None assert (u*v*n*x*k).is_nonpositive is None assert k.is_nonnegative is False assert (-k).is_nonnegative is True assert (2*k).is_nonnegative is False assert n.is_nonnegative is True assert (-n).is_nonnegative is False assert (2*n).is_nonnegative is True assert (n*k).is_nonnegative is False assert (2*n*k).is_nonnegative is False assert (-n*k).is_nonnegative is True assert u.is_nonnegative is True assert (-u).is_nonnegative is None assert (2*u).is_nonnegative is True assert v.is_nonnegative is None assert (-v).is_nonnegative is True assert (2*v).is_nonnegative is None assert (u*v).is_nonnegative is None assert (k*u).is_nonnegative is None assert (k*v).is_nonnegative is True assert (n*u).is_nonnegative is True assert (n*v).is_nonnegative is None assert (v*k*u).is_nonnegative is True assert (v*n*u).is_nonnegative is None assert (-v*k*u).is_nonnegative is None assert (-v*n*u).is_nonnegative is True assert (17*v*k*u).is_nonnegative is True assert (17*v*n*u).is_nonnegative is None assert (k*v*n*u).is_nonnegative is True assert (x*k).is_nonnegative is None assert (u*v*n*x*k).is_nonnegative is None def test_Add_is_negative_positive(): x = Symbol('x', real=True) k = Symbol('k', negative=True) n = Symbol('n', positive=True) u = Symbol('u', nonnegative=True) v = Symbol('v', nonpositive=True) assert (k - 2).is_negative is True assert (k + 17).is_negative is None assert (-k - 5).is_negative is None assert (-k + 123).is_negative is False assert (k - n).is_negative is True assert (k + n).is_negative is None assert (-k - n).is_negative is None assert (-k + n).is_negative is False assert (k - n - 2).is_negative is True assert (k + n + 17).is_negative is None assert (-k - n - 5).is_negative is None assert (-k + n + 123).is_negative is False assert (-2*k + 123*n + 17).is_negative is False assert (k + u).is_negative is None assert (k + v).is_negative is True assert (n + u).is_negative is False assert (n + v).is_negative is None assert (u - v).is_negative is False assert (u + v).is_negative is None assert (-u - v).is_negative is None assert (-u + v).is_negative is None assert (u - v + n + 2).is_negative is False assert (u + v + n + 2).is_negative is None assert (-u - v + n + 2).is_negative is None assert (-u + v + n + 2).is_negative is None assert (k + x).is_negative is None assert (k + x - n).is_negative is None assert (k - 2).is_positive is False assert (k + 17).is_positive is None assert (-k - 5).is_positive is None assert (-k + 123).is_positive is True assert (k - n).is_positive is False assert (k + n).is_positive is None assert (-k - n).is_positive is None assert (-k + n).is_positive is True assert (k - n - 2).is_positive is False assert (k + n + 17).is_positive is None assert (-k - n - 5).is_positive is None assert (-k + n + 123).is_positive is True assert (-2*k + 123*n + 17).is_positive is True assert (k + u).is_positive is None assert (k + v).is_positive is False assert (n + u).is_positive is True assert (n + v).is_positive is None assert (u - v).is_positive is None assert (u + v).is_positive is None assert (-u - v).is_positive is None assert (-u + v).is_positive is False assert (u - v - n - 2).is_positive is None assert (u + v - n - 2).is_positive is None assert (-u - v - n - 2).is_positive is None assert (-u + v - n - 2).is_positive is False assert (n + x).is_positive is None assert (n + x - k).is_positive is None z = (-3 - sqrt(5) + (-sqrt(10)/2 - sqrt(2)/2)**2) assert z.is_zero z = sqrt(1 + sqrt(3)) + sqrt(3 + 3*sqrt(3)) - sqrt(10 + 6*sqrt(3)) assert z.is_zero def test_Add_is_nonpositive_nonnegative(): x = Symbol('x', real=True) k = Symbol('k', negative=True) n = Symbol('n', positive=True) u = Symbol('u', nonnegative=True) v = Symbol('v', nonpositive=True) assert (u - 2).is_nonpositive is None assert (u + 17).is_nonpositive is False assert (-u - 5).is_nonpositive is True assert (-u + 123).is_nonpositive is None assert (u - v).is_nonpositive is None assert (u + v).is_nonpositive is None assert (-u - v).is_nonpositive is None assert (-u + v).is_nonpositive is True assert (u - v - 2).is_nonpositive is None assert (u + v + 17).is_nonpositive is None assert (-u - v - 5).is_nonpositive is None assert (-u + v - 123).is_nonpositive is True assert (-2*u + 123*v - 17).is_nonpositive is True assert (k + u).is_nonpositive is None assert (k + v).is_nonpositive is True assert (n + u).is_nonpositive is False assert (n + v).is_nonpositive is None assert (k - n).is_nonpositive is True assert (k + n).is_nonpositive is None assert (-k - n).is_nonpositive is None assert (-k + n).is_nonpositive is False assert (k - n + u + 2).is_nonpositive is None assert (k + n + u + 2).is_nonpositive is None assert (-k - n + u + 2).is_nonpositive is None assert (-k + n + u + 2).is_nonpositive is False assert (u + x).is_nonpositive is None assert (v - x - n).is_nonpositive is None assert (u - 2).is_nonnegative is None assert (u + 17).is_nonnegative is True assert (-u - 5).is_nonnegative is False assert (-u + 123).is_nonnegative is None assert (u - v).is_nonnegative is True assert (u + v).is_nonnegative is None assert (-u - v).is_nonnegative is None assert (-u + v).is_nonnegative is None assert (u - v + 2).is_nonnegative is True assert (u + v + 17).is_nonnegative is None assert (-u - v - 5).is_nonnegative is None assert (-u + v - 123).is_nonnegative is False assert (2*u - 123*v + 17).is_nonnegative is True assert (k + u).is_nonnegative is None assert (k + v).is_nonnegative is False assert (n + u).is_nonnegative is True assert (n + v).is_nonnegative is None assert (k - n).is_nonnegative is False assert (k + n).is_nonnegative is None assert (-k - n).is_nonnegative is None assert (-k + n).is_nonnegative is True assert (k - n - u - 2).is_nonnegative is False assert (k + n - u - 2).is_nonnegative is None assert (-k - n - u - 2).is_nonnegative is None assert (-k + n - u - 2).is_nonnegative is None assert (u - x).is_nonnegative is None assert (v + x + n).is_nonnegative is None def test_Pow_is_integer(): x = Symbol('x') k = Symbol('k', integer=True) n = Symbol('n', integer=True, nonnegative=True) m = Symbol('m', integer=True, positive=True) assert (k**2).is_integer is True assert (k**(-2)).is_integer is None assert ((m + 1)**(-2)).is_integer is False assert (m**(-1)).is_integer is None # issue 8580 assert (2**k).is_integer is None assert (2**(-k)).is_integer is None assert (2**n).is_integer is True assert (2**(-n)).is_integer is None assert (2**m).is_integer is True assert (2**(-m)).is_integer is False assert (x**2).is_integer is None assert (2**x).is_integer is None assert (k**n).is_integer is True assert (k**(-n)).is_integer is None assert (k**x).is_integer is None assert (x**k).is_integer is None assert (k**(n*m)).is_integer is True assert (k**(-n*m)).is_integer is None assert sqrt(3).is_integer is False assert sqrt(.3).is_integer is False assert Pow(3, 2, evaluate=False).is_integer is True assert Pow(3, 0, evaluate=False).is_integer is True assert Pow(3, -2, evaluate=False).is_integer is False assert Pow(S.Half, 3, evaluate=False).is_integer is False # decided by re-evaluating assert Pow(3, S.Half, evaluate=False).is_integer is False assert Pow(3, S.Half, evaluate=False).is_integer is False assert Pow(4, S.Half, evaluate=False).is_integer is True assert Pow(S.Half, -2, evaluate=False).is_integer is True assert ((-1)**k).is_integer # issue 8641 x = Symbol('x', real=True, integer=False) assert (x**2).is_integer is None # issue 10458 x = Symbol('x', positive=True) assert (1/(x + 1)).is_integer is False assert (1/(-x - 1)).is_integer is False assert (-1/(x + 1)).is_integer is False # issue 8648-like k = Symbol('k', even=True) assert (k**3/2).is_integer assert (k**3/8).is_integer assert (k**3/16).is_integer is None assert (2/k).is_integer is None assert (2/k**2).is_integer is False o = Symbol('o', odd=True) assert (k/o).is_integer is None o = Symbol('o', odd=True, prime=True) assert (k/o).is_integer is False def test_Pow_is_real(): x = Symbol('x', real=True) y = Symbol('y', positive=True) assert (x**2).is_real is True assert (x**3).is_real is True assert (x**x).is_real is None assert (y**x).is_real is True assert (x**Rational(1, 3)).is_real is None assert (y**Rational(1, 3)).is_real is True assert sqrt(-1 - sqrt(2)).is_real is False i = Symbol('i', imaginary=True) assert (i**i).is_real is None assert (I**i).is_extended_real is True assert ((-I)**i).is_extended_real is True assert (2**i).is_real is None # (2**(pi/log(2) * I)) is real, 2**I is not assert (2**I).is_real is False assert (2**-I).is_real is False assert (i**2).is_extended_real is True assert (i**3).is_extended_real is False assert (i**x).is_real is None # could be (-I)**(2/3) e = Symbol('e', even=True) o = Symbol('o', odd=True) k = Symbol('k', integer=True) assert (i**e).is_extended_real is True assert (i**o).is_extended_real is False assert (i**k).is_real is None assert (i**(4*k)).is_extended_real is True x = Symbol("x", nonnegative=True) y = Symbol("y", nonnegative=True) assert im(x**y).expand(complex=True) is S.Zero assert (x**y).is_real is True i = Symbol('i', imaginary=True) assert (exp(i)**I).is_extended_real is True assert log(exp(i)).is_imaginary is None # i could be 2*pi*I c = Symbol('c', complex=True) assert log(c).is_real is None # c could be 0 or 2, too assert log(exp(c)).is_real is None # log(0), log(E), ... n = Symbol('n', negative=False) assert log(n).is_real is None n = Symbol('n', nonnegative=True) assert log(n).is_real is None assert sqrt(-I).is_real is False # issue 7843 i = Symbol('i', integer=True) assert (1/(i-1)).is_real is None assert (1/(i-1)).is_extended_real is None # test issue 20715 from sympy.core.parameters import evaluate x = S(-1) with evaluate(False): assert x.is_negative is True f = Pow(x, -1) with evaluate(False): assert f.is_imaginary is False def test_real_Pow(): k = Symbol('k', integer=True, nonzero=True) assert (k**(I*pi/log(k))).is_real def test_Pow_is_finite(): xe = Symbol('xe', extended_real=True) xr = Symbol('xr', real=True) p = Symbol('p', positive=True) n = Symbol('n', negative=True) i = Symbol('i', integer=True) assert (xe**2).is_finite is None # xe could be oo assert (xr**2).is_finite is True assert (xe**xe).is_finite is None assert (xr**xe).is_finite is None assert (xe**xr).is_finite is None # FIXME: The line below should be True rather than None # assert (xr**xr).is_finite is True assert (xr**xr).is_finite is None assert (p**xe).is_finite is None assert (p**xr).is_finite is True assert (n**xe).is_finite is None assert (n**xr).is_finite is True assert (sin(xe)**2).is_finite is True assert (sin(xr)**2).is_finite is True assert (sin(xe)**xe).is_finite is None # xe, xr could be -pi assert (sin(xr)**xr).is_finite is None # FIXME: Should the line below be True rather than None? assert (sin(xe)**exp(xe)).is_finite is None assert (sin(xr)**exp(xr)).is_finite is True assert (1/sin(xe)).is_finite is None # if zero, no, otherwise yes assert (1/sin(xr)).is_finite is None assert (1/exp(xe)).is_finite is None # xe could be -oo assert (1/exp(xr)).is_finite is True assert (1/S.Pi).is_finite is True assert (1/(i-1)).is_finite is None def test_Pow_is_even_odd(): x = Symbol('x') k = Symbol('k', even=True) n = Symbol('n', odd=True) m = Symbol('m', integer=True, nonnegative=True) p = Symbol('p', integer=True, positive=True) assert ((-1)**n).is_odd assert ((-1)**k).is_odd assert ((-1)**(m - p)).is_odd assert (k**2).is_even is True assert (n**2).is_even is False assert (2**k).is_even is None assert (x**2).is_even is None assert (k**m).is_even is None assert (n**m).is_even is False assert (k**p).is_even is True assert (n**p).is_even is False assert (m**k).is_even is None assert (p**k).is_even is None assert (m**n).is_even is None assert (p**n).is_even is None assert (k**x).is_even is None assert (n**x).is_even is None assert (k**2).is_odd is False assert (n**2).is_odd is True assert (3**k).is_odd is None assert (k**m).is_odd is None assert (n**m).is_odd is True assert (k**p).is_odd is False assert (n**p).is_odd is True assert (m**k).is_odd is None assert (p**k).is_odd is None assert (m**n).is_odd is None assert (p**n).is_odd is None assert (k**x).is_odd is None assert (n**x).is_odd is None def test_Pow_is_negative_positive(): r = Symbol('r', real=True) k = Symbol('k', integer=True, positive=True) n = Symbol('n', even=True) m = Symbol('m', odd=True) x = Symbol('x') assert (2**r).is_positive is True assert ((-2)**r).is_positive is None assert ((-2)**n).is_positive is True assert ((-2)**m).is_positive is False assert (k**2).is_positive is True assert (k**(-2)).is_positive is True assert (k**r).is_positive is True assert ((-k)**r).is_positive is None assert ((-k)**n).is_positive is True assert ((-k)**m).is_positive is False assert (2**r).is_negative is False assert ((-2)**r).is_negative is None assert ((-2)**n).is_negative is False assert ((-2)**m).is_negative is True assert (k**2).is_negative is False assert (k**(-2)).is_negative is False assert (k**r).is_negative is False assert ((-k)**r).is_negative is None assert ((-k)**n).is_negative is False assert ((-k)**m).is_negative is True assert (2**x).is_positive is None assert (2**x).is_negative is None def test_Pow_is_zero(): z = Symbol('z', zero=True) e = z**2 assert e.is_zero assert e.is_positive is False assert e.is_negative is False assert Pow(0, 0, evaluate=False).is_zero is False assert Pow(0, 3, evaluate=False).is_zero assert Pow(0, oo, evaluate=False).is_zero assert Pow(0, -3, evaluate=False).is_zero is False assert Pow(0, -oo, evaluate=False).is_zero is False assert Pow(2, 2, evaluate=False).is_zero is False a = Symbol('a', zero=False) assert Pow(a, 3).is_zero is False # issue 7965 assert Pow(2, oo, evaluate=False).is_zero is False assert Pow(2, -oo, evaluate=False).is_zero assert Pow(S.Half, oo, evaluate=False).is_zero assert Pow(S.Half, -oo, evaluate=False).is_zero is False # All combinations of real/complex base/exponent h = S.Half T = True F = False N = None pow_iszero = [ ['**', 0, h, 1, 2, -h, -1,-2,-2*I,-I/2,I/2,1+I,oo,-oo,zoo], [ 0, F, T, T, T, F, F, F, F, F, F, N, T, F, N], [ h, F, F, F, F, F, F, F, F, F, F, F, T, F, N], [ 1, F, F, F, F, F, F, F, F, F, F, F, F, F, N], [ 2, F, F, F, F, F, F, F, F, F, F, F, F, T, N], [ -h, F, F, F, F, F, F, F, F, F, F, F, T, F, N], [ -1, F, F, F, F, F, F, F, F, F, F, F, F, F, N], [ -2, F, F, F, F, F, F, F, F, F, F, F, F, T, N], [-2*I, F, F, F, F, F, F, F, F, F, F, F, F, T, N], [-I/2, F, F, F, F, F, F, F, F, F, F, F, T, F, N], [ I/2, F, F, F, F, F, F, F, F, F, F, F, T, F, N], [ 1+I, F, F, F, F, F, F, F, F, F, F, F, F, T, N], [ oo, F, F, F, F, T, T, T, F, F, F, F, F, T, N], [ -oo, F, F, F, F, T, T, T, F, F, F, F, F, T, N], [ zoo, F, F, F, F, T, T, T, N, N, N, N, F, T, N] ] def test_table(table): n = len(table[0]) for row in range(1, n): base = table[row][0] for col in range(1, n): exp = table[0][col] is_zero = table[row][col] # The actual test here: assert Pow(base, exp, evaluate=False).is_zero is is_zero test_table(pow_iszero) # A zero symbol... zo, zo2 = symbols('zo, zo2', zero=True) # All combinations of finite symbols zf, zf2 = symbols('zf, zf2', finite=True) wf, wf2 = symbols('wf, wf2', nonzero=True) xf, xf2 = symbols('xf, xf2', real=True) yf, yf2 = symbols('yf, yf2', nonzero=True) af, af2 = symbols('af, af2', positive=True) bf, bf2 = symbols('bf, bf2', nonnegative=True) cf, cf2 = symbols('cf, cf2', negative=True) df, df2 = symbols('df, df2', nonpositive=True) # Without finiteness: zi, zi2 = symbols('zi, zi2') wi, wi2 = symbols('wi, wi2', zero=False) xi, xi2 = symbols('xi, xi2', extended_real=True) yi, yi2 = symbols('yi, yi2', zero=False, extended_real=True) ai, ai2 = symbols('ai, ai2', extended_positive=True) bi, bi2 = symbols('bi, bi2', extended_nonnegative=True) ci, ci2 = symbols('ci, ci2', extended_negative=True) di, di2 = symbols('di, di2', extended_nonpositive=True) pow_iszero_sym = [ ['**',zo,wf,yf,af,cf,zf,xf,bf,df,zi,wi,xi,yi,ai,bi,ci,di], [ zo2, F, N, N, T, F, N, N, N, F, N, N, N, N, T, N, F, F], [ wf2, F, F, F, F, F, F, F, F, F, N, N, N, N, N, N, N, N], [ yf2, F, F, F, F, F, F, F, F, F, N, N, N, N, N, N, N, N], [ af2, F, F, F, F, F, F, F, F, F, N, N, N, N, N, N, N, N], [ cf2, F, F, F, F, F, F, F, F, F, N, N, N, N, N, N, N, N], [ zf2, N, N, N, N, F, N, N, N, N, N, N, N, N, N, N, N, N], [ xf2, N, N, N, N, F, N, N, N, N, N, N, N, N, N, N, N, N], [ bf2, N, N, N, N, F, N, N, N, N, N, N, N, N, N, N, N, N], [ df2, N, N, N, N, F, N, N, N, N, N, N, N, N, N, N, N, N], [ zi2, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N], [ wi2, F, N, N, F, N, N, N, F, N, N, N, N, N, N, N, N, N], [ xi2, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N], [ yi2, F, N, N, F, N, N, N, F, N, N, N, N, N, N, N, N, N], [ ai2, F, N, N, F, N, N, N, F, N, N, N, N, N, N, N, N, N], [ bi2, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N], [ ci2, F, N, N, F, N, N, N, F, N, N, N, N, N, N, N, N, N], [ di2, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N] ] test_table(pow_iszero_sym) # In some cases (x**x).is_zero is different from (x**y).is_zero even if y # has the same assumptions as x. assert (zo ** zo).is_zero is False assert (wf ** wf).is_zero is False assert (yf ** yf).is_zero is False assert (af ** af).is_zero is False assert (cf ** cf).is_zero is False assert (zf ** zf).is_zero is None assert (xf ** xf).is_zero is None assert (bf ** bf).is_zero is False # None in table assert (df ** df).is_zero is None assert (zi ** zi).is_zero is None assert (wi ** wi).is_zero is None assert (xi ** xi).is_zero is None assert (yi ** yi).is_zero is None assert (ai ** ai).is_zero is False # None in table assert (bi ** bi).is_zero is False # None in table assert (ci ** ci).is_zero is None assert (di ** di).is_zero is None def test_Pow_is_nonpositive_nonnegative(): x = Symbol('x', real=True) k = Symbol('k', integer=True, nonnegative=True) l = Symbol('l', integer=True, positive=True) n = Symbol('n', even=True) m = Symbol('m', odd=True) assert (x**(4*k)).is_nonnegative is True assert (2**x).is_nonnegative is True assert ((-2)**x).is_nonnegative is None assert ((-2)**n).is_nonnegative is True assert ((-2)**m).is_nonnegative is False assert (k**2).is_nonnegative is True assert (k**(-2)).is_nonnegative is None assert (k**k).is_nonnegative is True assert (k**x).is_nonnegative is None # NOTE (0**x).is_real = U assert (l**x).is_nonnegative is True assert (l**x).is_positive is True assert ((-k)**x).is_nonnegative is None assert ((-k)**m).is_nonnegative is None assert (2**x).is_nonpositive is False assert ((-2)**x).is_nonpositive is None assert ((-2)**n).is_nonpositive is False assert ((-2)**m).is_nonpositive is True assert (k**2).is_nonpositive is None assert (k**(-2)).is_nonpositive is None assert (k**x).is_nonpositive is None assert ((-k)**x).is_nonpositive is None assert ((-k)**n).is_nonpositive is None assert (x**2).is_nonnegative is True i = symbols('i', imaginary=True) assert (i**2).is_nonpositive is True assert (i**4).is_nonpositive is False assert (i**3).is_nonpositive is False assert (I**i).is_nonnegative is True assert (exp(I)**i).is_nonnegative is True assert ((-l)**n).is_nonnegative is True assert ((-l)**m).is_nonpositive is True assert ((-k)**n).is_nonnegative is None assert ((-k)**m).is_nonpositive is None def test_Mul_is_imaginary_real(): r = Symbol('r', real=True) p = Symbol('p', positive=True) i1 = Symbol('i1', imaginary=True) i2 = Symbol('i2', imaginary=True) x = Symbol('x') assert I.is_imaginary is True assert I.is_real is False assert (-I).is_imaginary is True assert (-I).is_real is False assert (3*I).is_imaginary is True assert (3*I).is_real is False assert (I*I).is_imaginary is False assert (I*I).is_real is True e = (p + p*I) j = Symbol('j', integer=True, zero=False) assert (e**j).is_real is None assert (e**(2*j)).is_real is None assert (e**j).is_imaginary is None assert (e**(2*j)).is_imaginary is None assert (e**-1).is_imaginary is False assert (e**2).is_imaginary assert (e**3).is_imaginary is False assert (e**4).is_imaginary is False assert (e**5).is_imaginary is False assert (e**-1).is_real is False assert (e**2).is_real is False assert (e**3).is_real is False assert (e**4).is_real is True assert (e**5).is_real is False assert (e**3).is_complex assert (r*i1).is_imaginary is None assert (r*i1).is_real is None assert (x*i1).is_imaginary is None assert (x*i1).is_real is None assert (i1*i2).is_imaginary is False assert (i1*i2).is_real is True assert (r*i1*i2).is_imaginary is False assert (r*i1*i2).is_real is True # Github's issue 5874: nr = Symbol('nr', real=False, complex=True) # e.g. I or 1 + I a = Symbol('a', real=True, nonzero=True) b = Symbol('b', real=True) assert (i1*nr).is_real is None assert (a*nr).is_real is False assert (b*nr).is_real is None ni = Symbol('ni', imaginary=False, complex=True) # e.g. 2 or 1 + I a = Symbol('a', real=True, nonzero=True) b = Symbol('b', real=True) assert (i1*ni).is_real is False assert (a*ni).is_real is None assert (b*ni).is_real is None def test_Mul_hermitian_antihermitian(): a = Symbol('a', hermitian=True, zero=False) b = Symbol('b', hermitian=True) c = Symbol('c', hermitian=False) d = Symbol('d', antihermitian=True) e1 = Mul(a, b, c, evaluate=False) e2 = Mul(b, a, c, evaluate=False) e3 = Mul(a, b, c, d, evaluate=False) e4 = Mul(b, a, c, d, evaluate=False) e5 = Mul(a, c, evaluate=False) e6 = Mul(a, c, d, evaluate=False) assert e1.is_hermitian is None assert e2.is_hermitian is None assert e1.is_antihermitian is None assert e2.is_antihermitian is None assert e3.is_antihermitian is None assert e4.is_antihermitian is None assert e5.is_antihermitian is None assert e6.is_antihermitian is None def test_Add_is_comparable(): assert (x + y).is_comparable is False assert (x + 1).is_comparable is False assert (Rational(1, 3) - sqrt(8)).is_comparable is True def test_Mul_is_comparable(): assert (x*y).is_comparable is False assert (x*2).is_comparable is False assert (sqrt(2)*Rational(1, 3)).is_comparable is True def test_Pow_is_comparable(): assert (x**y).is_comparable is False assert (x**2).is_comparable is False assert (sqrt(Rational(1, 3))).is_comparable is True def test_Add_is_positive_2(): e = Rational(1, 3) - sqrt(8) assert e.is_positive is False assert e.is_negative is True e = pi - 1 assert e.is_positive is True assert e.is_negative is False def test_Add_is_irrational(): i = Symbol('i', irrational=True) assert i.is_irrational is True assert i.is_rational is False assert (i + 1).is_irrational is True assert (i + 1).is_rational is False def test_Mul_is_irrational(): expr = Mul(1, 2, 3, evaluate=False) assert expr.is_irrational is False expr = Mul(1, I, I, evaluate=False) assert expr.is_rational is None # I * I = -1 but *no evaluation allowed* # sqrt(2) * I * I = -sqrt(2) is irrational but # this can't be determined without evaluating the # expression and the eval_is routines shouldn't do that expr = Mul(sqrt(2), I, I, evaluate=False) assert expr.is_irrational is None def test_issue_3531(): # https://github.com/sympy/sympy/issues/3531 # https://github.com/sympy/sympy/pull/18116 class MightyNumeric(tuple): def __rtruediv__(self, other): return "something" assert sympify(1)/MightyNumeric((1, 2)) == "something" def test_issue_3531b(): class Foo: def __init__(self): self.field = 1.0 def __mul__(self, other): self.field = self.field * other def __rmul__(self, other): self.field = other * self.field f = Foo() x = Symbol("x") assert f*x == x*f def test_bug3(): a = Symbol("a") b = Symbol("b", positive=True) e = 2*a + b f = b + 2*a assert e == f def test_suppressed_evaluation(): a = Add(0, 3, 2, evaluate=False) b = Mul(1, 3, 2, evaluate=False) c = Pow(3, 2, evaluate=False) assert a != 6 assert a.func is Add assert a.args == (0, 3, 2) assert b != 6 assert b.func is Mul assert b.args == (1, 3, 2) assert c != 9 assert c.func is Pow assert c.args == (3, 2) def test_AssocOp_doit(): a = Add(x,x, evaluate=False) b = Mul(y,y, evaluate=False) c = Add(b,b, evaluate=False) d = Mul(a,a, evaluate=False) assert c.doit(deep=False).func == Mul assert c.doit(deep=False).args == (2,y,y) assert c.doit().func == Mul assert c.doit().args == (2, Pow(y,2)) assert d.doit(deep=False).func == Pow assert d.doit(deep=False).args == (a, 2*S.One) assert d.doit().func == Mul assert d.doit().args == (4*S.One, Pow(x,2)) def test_Add_Mul_Expr_args(): nonexpr = [Basic(), Poly(x, x), FiniteSet(x)] for typ in [Add, Mul]: for obj in nonexpr: # The cache can mess with the stacklevel check with warns(SymPyDeprecationWarning, test_stacklevel=False): typ(obj, 1) def test_Add_as_coeff_mul(): # issue 5524. These should all be (1, self) assert (x + 1).as_coeff_mul() == (1, (x + 1,)) assert (x + 2).as_coeff_mul() == (1, (x + 2,)) assert (x + 3).as_coeff_mul() == (1, (x + 3,)) assert (x - 1).as_coeff_mul() == (1, (x - 1,)) assert (x - 2).as_coeff_mul() == (1, (x - 2,)) assert (x - 3).as_coeff_mul() == (1, (x - 3,)) n = Symbol('n', integer=True) assert (n + 1).as_coeff_mul() == (1, (n + 1,)) assert (n + 2).as_coeff_mul() == (1, (n + 2,)) assert (n + 3).as_coeff_mul() == (1, (n + 3,)) assert (n - 1).as_coeff_mul() == (1, (n - 1,)) assert (n - 2).as_coeff_mul() == (1, (n - 2,)) assert (n - 3).as_coeff_mul() == (1, (n - 3,)) def test_Pow_as_coeff_mul_doesnt_expand(): assert exp(x + y).as_coeff_mul() == (1, (exp(x + y),)) assert exp(x + exp(x + y)) != exp(x + exp(x)*exp(y)) def test_issue_3514_18626(): assert sqrt(S.Half) * sqrt(6) == 2 * sqrt(3)/2 assert S.Half*sqrt(6)*sqrt(2) == sqrt(3) assert sqrt(6)/2*sqrt(2) == sqrt(3) assert sqrt(6)*sqrt(2)/2 == sqrt(3) assert sqrt(8)**Rational(2, 3) == 2 def test_make_args(): assert Add.make_args(x) == (x,) assert Mul.make_args(x) == (x,) assert Add.make_args(x*y*z) == (x*y*z,) assert Mul.make_args(x*y*z) == (x*y*z).args assert Add.make_args(x + y + z) == (x + y + z).args assert Mul.make_args(x + y + z) == (x + y + z,) assert Add.make_args((x + y)**z) == ((x + y)**z,) assert Mul.make_args((x + y)**z) == ((x + y)**z,) def test_issue_5126(): assert (-2)**x*(-3)**x != 6**x i = Symbol('i', integer=1) assert (-2)**i*(-3)**i == 6**i def test_Rational_as_content_primitive(): c, p = S.One, S.Zero assert (c*p).as_content_primitive() == (c, p) c, p = S.Half, S.One assert (c*p).as_content_primitive() == (c, p) def test_Add_as_content_primitive(): assert (x + 2).as_content_primitive() == (1, x + 2) assert (3*x + 2).as_content_primitive() == (1, 3*x + 2) assert (3*x + 3).as_content_primitive() == (3, x + 1) assert (3*x + 6).as_content_primitive() == (3, x + 2) assert (3*x + 2*y).as_content_primitive() == (1, 3*x + 2*y) assert (3*x + 3*y).as_content_primitive() == (3, x + y) assert (3*x + 6*y).as_content_primitive() == (3, x + 2*y) assert (3/x + 2*x*y*z**2).as_content_primitive() == (1, 3/x + 2*x*y*z**2) assert (3/x + 3*x*y*z**2).as_content_primitive() == (3, 1/x + x*y*z**2) assert (3/x + 6*x*y*z**2).as_content_primitive() == (3, 1/x + 2*x*y*z**2) assert (2*x/3 + 4*y/9).as_content_primitive() == \ (Rational(2, 9), 3*x + 2*y) assert (2*x/3 + 2.5*y).as_content_primitive() == \ (Rational(1, 3), 2*x + 7.5*y) # the coefficient may sort to a position other than 0 p = 3 + x + y assert (2*p).expand().as_content_primitive() == (2, p) assert (2.0*p).expand().as_content_primitive() == (1, 2.*p) p *= -1 assert (2*p).expand().as_content_primitive() == (2, p) def test_Mul_as_content_primitive(): assert (2*x).as_content_primitive() == (2, x) assert (x*(2 + 2*x)).as_content_primitive() == (2, x*(1 + x)) assert (x*(2 + 2*y)*(3*x + 3)**2).as_content_primitive() == \ (18, x*(1 + y)*(x + 1)**2) assert ((2 + 2*x)**2*(3 + 6*x) + S.Half).as_content_primitive() == \ (S.Half, 24*(x + 1)**2*(2*x + 1) + 1) def test_Pow_as_content_primitive(): assert (x**y).as_content_primitive() == (1, x**y) assert ((2*x + 2)**y).as_content_primitive() == \ (1, (Mul(2, (x + 1), evaluate=False))**y) assert ((2*x + 2)**3).as_content_primitive() == (8, (x + 1)**3) def test_issue_5460(): u = Mul(2, (1 + x), evaluate=False) assert (2 + u).args == (2, u) def test_product_irrational(): assert (I*pi).is_irrational is False # The following used to be deduced from the above bug: assert (I*pi).is_positive is False def test_issue_5919(): assert (x/(y*(1 + y))).expand() == x/(y**2 + y) def test_Mod(): assert Mod(x, 1).func is Mod assert pi % pi is S.Zero assert Mod(5, 3) == 2 assert Mod(-5, 3) == 1 assert Mod(5, -3) == -1 assert Mod(-5, -3) == -2 assert type(Mod(3.2, 2, evaluate=False)) == Mod assert 5 % x == Mod(5, x) assert x % 5 == Mod(x, 5) assert x % y == Mod(x, y) assert (x % y).subs({x: 5, y: 3}) == 2 assert Mod(nan, 1) is nan assert Mod(1, nan) is nan assert Mod(nan, nan) is nan assert Mod(0, x) == 0 with raises(ZeroDivisionError): Mod(x, 0) k = Symbol('k', integer=True) m = Symbol('m', integer=True, positive=True) assert (x**m % x).func is Mod assert (k**(-m) % k).func is Mod assert k**m % k == 0 assert (-2*k)**m % k == 0 # Float handling point3 = Float(3.3) % 1 assert (x - 3.3) % 1 == Mod(1.*x + 1 - point3, 1) assert Mod(-3.3, 1) == 1 - point3 assert Mod(0.7, 1) == Float(0.7) e = Mod(1.3, 1) assert comp(e, .3) and e.is_Float e = Mod(1.3, .7) assert comp(e, .6) and e.is_Float e = Mod(1.3, Rational(7, 10)) assert comp(e, .6) and e.is_Float e = Mod(Rational(13, 10), 0.7) assert comp(e, .6) and e.is_Float e = Mod(Rational(13, 10), Rational(7, 10)) assert comp(e, .6) and e.is_Rational # check that sign is right r2 = sqrt(2) r3 = sqrt(3) for i in [-r3, -r2, r2, r3]: for j in [-r3, -r2, r2, r3]: assert verify_numerically(i % j, i.n() % j.n()) for _x in range(4): for _y in range(9): reps = [(x, _x), (y, _y)] assert Mod(3*x + y, 9).subs(reps) == (3*_x + _y) % 9 # denesting t = Symbol('t', real=True) assert Mod(Mod(x, t), t) == Mod(x, t) assert Mod(-Mod(x, t), t) == Mod(-x, t) assert Mod(Mod(x, 2*t), t) == Mod(x, t) assert Mod(-Mod(x, 2*t), t) == Mod(-x, t) assert Mod(Mod(x, t), 2*t) == Mod(x, t) assert Mod(-Mod(x, t), -2*t) == -Mod(x, t) for i in [-4, -2, 2, 4]: for j in [-4, -2, 2, 4]: for k in range(4): assert Mod(Mod(x, i), j).subs({x: k}) == (k % i) % j assert Mod(-Mod(x, i), j).subs({x: k}) == -(k % i) % j # known difference assert Mod(5*sqrt(2), sqrt(5)) == 5*sqrt(2) - 3*sqrt(5) p = symbols('p', positive=True) assert Mod(2, p + 3) == 2 assert Mod(-2, p + 3) == p + 1 assert Mod(2, -p - 3) == -p - 1 assert Mod(-2, -p - 3) == -2 assert Mod(p + 5, p + 3) == 2 assert Mod(-p - 5, p + 3) == p + 1 assert Mod(p + 5, -p - 3) == -p - 1 assert Mod(-p - 5, -p - 3) == -2 assert Mod(p + 1, p - 1).func is Mod # handling sums assert (x + 3) % 1 == Mod(x, 1) assert (x + 3.0) % 1 == Mod(1.*x, 1) assert (x - S(33)/10) % 1 == Mod(x + S(7)/10, 1) a = Mod(.6*x + y, .3*y) b = Mod(0.1*y + 0.6*x, 0.3*y) # Test that a, b are equal, with 1e-14 accuracy in coefficients eps = 1e-14 assert abs((a.args[0] - b.args[0]).subs({x: 1, y: 1})) < eps assert abs((a.args[1] - b.args[1]).subs({x: 1, y: 1})) < eps assert (x + 1) % x == 1 % x assert (x + y) % x == y % x assert (x + y + 2) % x == (y + 2) % x assert (a + 3*x + 1) % (2*x) == Mod(a + x + 1, 2*x) assert (12*x + 18*y) % (3*x) == 3*Mod(6*y, x) # gcd extraction assert (-3*x) % (-2*y) == -Mod(3*x, 2*y) assert (.6*pi) % (.3*x*pi) == 0.3*pi*Mod(2, x) assert (.6*pi) % (.31*x*pi) == pi*Mod(0.6, 0.31*x) assert (6*pi) % (.3*x*pi) == 0.3*pi*Mod(20, x) assert (6*pi) % (.31*x*pi) == pi*Mod(6, 0.31*x) assert (6*pi) % (.42*x*pi) == pi*Mod(6, 0.42*x) assert (12*x) % (2*y) == 2*Mod(6*x, y) assert (12*x) % (3*5*y) == 3*Mod(4*x, 5*y) assert (12*x) % (15*x*y) == 3*x*Mod(4, 5*y) assert (-2*pi) % (3*pi) == pi assert (2*x + 2) % (x + 1) == 0 assert (x*(x + 1)) % (x + 1) == (x + 1)*Mod(x, 1) assert Mod(5.0*x, 0.1*y) == 0.1*Mod(50*x, y) i = Symbol('i', integer=True) assert (3*i*x) % (2*i*y) == i*Mod(3*x, 2*y) assert Mod(4*i, 4) == 0 # issue 8677 n = Symbol('n', integer=True, positive=True) assert factorial(n) % n == 0 assert factorial(n + 2) % n == 0 assert (factorial(n + 4) % (n + 5)).func is Mod # Wilson's theorem assert factorial(18042, evaluate=False) % 18043 == 18042 p = Symbol('n', prime=True) assert factorial(p - 1) % p == p - 1 assert factorial(p - 1) % -p == -1 assert (factorial(3, evaluate=False) % 4).doit() == 2 n = Symbol('n', composite=True, odd=True) assert factorial(n - 1) % n == 0 # symbolic with known parity n = Symbol('n', even=True) assert Mod(n, 2) == 0 n = Symbol('n', odd=True) assert Mod(n, 2) == 1 # issue 10963 assert (x**6000%400).args[1] == 400 #issue 13543 assert Mod(Mod(x + 1, 2) + 1, 2) == Mod(x, 2) assert Mod(Mod(x + 2, 4)*(x + 4), 4) == Mod(x*(x + 2), 4) assert Mod(Mod(x + 2, 4)*4, 4) == 0 # issue 15493 i, j = symbols('i j', integer=True, positive=True) assert Mod(3*i, 2) == Mod(i, 2) assert Mod(8*i/j, 4) == 4*Mod(2*i/j, 1) assert Mod(8*i, 4) == 0 # rewrite assert Mod(x, y).rewrite(floor) == x - y*floor(x/y) assert ((x - Mod(x, y))/y).rewrite(floor) == floor(x/y) # issue 21373 from sympy.functions.elementary.hyperbolic import sinh from sympy.functions.elementary.piecewise import Piecewise x_r, y_r = symbols('x_r y_r', real=True) assert (Piecewise((x_r, y_r > x_r), (y_r, True)) / z) % 1 expr = exp(sinh(Piecewise((x_r, y_r > x_r), (y_r, True)) / z)) expr.subs({1: 1.0}) sinh(Piecewise((x_r, y_r > x_r), (y_r, True)) * z ** -1.0).is_zero def test_Mod_Pow(): # modular exponentiation assert isinstance(Mod(Pow(2, 2, evaluate=False), 3), Integer) assert Mod(Pow(4, 13, evaluate=False), 497) == Mod(Pow(4, 13), 497) assert Mod(Pow(2, 10000000000, evaluate=False), 3) == 1 assert Mod(Pow(32131231232, 9**10**6, evaluate=False),10**12) == \ pow(32131231232,9**10**6,10**12) assert Mod(Pow(33284959323, 123**999, evaluate=False),11**13) == \ pow(33284959323,123**999,11**13) assert Mod(Pow(78789849597, 333**555, evaluate=False),12**9) == \ pow(78789849597,333**555,12**9) # modular nested exponentiation expr = Pow(2, 2, evaluate=False) expr = Pow(2, expr, evaluate=False) assert Mod(expr, 3**10) == 16 expr = Pow(2, expr, evaluate=False) assert Mod(expr, 3**10) == 6487 expr = Pow(2, expr, evaluate=False) assert Mod(expr, 3**10) == 32191 expr = Pow(2, expr, evaluate=False) assert Mod(expr, 3**10) == 18016 expr = Pow(2, expr, evaluate=False) assert Mod(expr, 3**10) == 5137 expr = Pow(2, 2, evaluate=False) expr = Pow(expr, 2, evaluate=False) assert Mod(expr, 3**10) == 16 expr = Pow(expr, 2, evaluate=False) assert Mod(expr, 3**10) == 256 expr = Pow(expr, 2, evaluate=False) assert Mod(expr, 3**10) == 6487 expr = Pow(expr, 2, evaluate=False) assert Mod(expr, 3**10) == 38281 expr = Pow(expr, 2, evaluate=False) assert Mod(expr, 3**10) == 15928 expr = Pow(2, 2, evaluate=False) expr = Pow(expr, expr, evaluate=False) assert Mod(expr, 3**10) == 256 expr = Pow(expr, expr, evaluate=False) assert Mod(expr, 3**10) == 9229 expr = Pow(expr, expr, evaluate=False) assert Mod(expr, 3**10) == 25708 expr = Pow(expr, expr, evaluate=False) assert Mod(expr, 3**10) == 26608 expr = Pow(expr, expr, evaluate=False) # XXX This used to fail in a nondeterministic way because of overflow # error. assert Mod(expr, 3**10) == 1966 def test_Mod_is_integer(): p = Symbol('p', integer=True) q1 = Symbol('q1', integer=True) q2 = Symbol('q2', integer=True, nonzero=True) assert Mod(x, y).is_integer is None assert Mod(p, q1).is_integer is None assert Mod(x, q2).is_integer is None assert Mod(p, q2).is_integer def test_Mod_is_nonposneg(): n = Symbol('n', integer=True) k = Symbol('k', integer=True, positive=True) assert (n%3).is_nonnegative assert Mod(n, -3).is_nonpositive assert Mod(n, k).is_nonnegative assert Mod(n, -k).is_nonpositive assert Mod(k, n).is_nonnegative is None def test_issue_6001(): A = Symbol("A", commutative=False) eq = A + A**2 # it doesn't matter whether it's True or False; they should # just all be the same assert ( eq.is_commutative == (eq + 1).is_commutative == (A + 1).is_commutative) B = Symbol("B", commutative=False) # Although commutative terms could cancel we return True # meaning "there are non-commutative symbols; aftersubstitution # that definition can change, e.g. (A*B).subs(B,A**-1) -> 1 assert (sqrt(2)*A).is_commutative is False assert (sqrt(2)*A*B).is_commutative is False def test_polar(): from sympy.functions.elementary.complexes import polar_lift p = Symbol('p', polar=True) x = Symbol('x') assert p.is_polar assert x.is_polar is None assert S.One.is_polar is None assert (p**x).is_polar is True assert (x**p).is_polar is None assert ((2*p)**x).is_polar is True assert (2*p).is_polar is True assert (-2*p).is_polar is not True assert (polar_lift(-2)*p).is_polar is True q = Symbol('q', polar=True) assert (p*q)**2 == p**2 * q**2 assert (2*q)**2 == 4 * q**2 assert ((p*q)**x).expand() == p**x * q**x def test_issue_6040(): a, b = Pow(1, 2, evaluate=False), S.One assert a != b assert b != a assert not (a == b) assert not (b == a) def test_issue_6082(): # Comparison is symmetric assert Basic.compare(Max(x, 1), Max(x, 2)) == \ - Basic.compare(Max(x, 2), Max(x, 1)) # Equal expressions compare equal assert Basic.compare(Max(x, 1), Max(x, 1)) == 0 # Basic subtypes (such as Max) compare different than standard types assert Basic.compare(Max(1, x), frozenset((1, x))) != 0 def test_issue_6077(): assert x**2.0/x == x**1.0 assert x/x**2.0 == x**-1.0 assert x*x**2.0 == x**3.0 assert x**1.5*x**2.5 == x**4.0 assert 2**(2.0*x)/2**x == 2**(1.0*x) assert 2**x/2**(2.0*x) == 2**(-1.0*x) assert 2**x*2**(2.0*x) == 2**(3.0*x) assert 2**(1.5*x)*2**(2.5*x) == 2**(4.0*x) def test_mul_flatten_oo(): p = symbols('p', positive=True) n, m = symbols('n,m', negative=True) x_im = symbols('x_im', imaginary=True) assert n*oo is -oo assert n*m*oo is oo assert p*oo is oo assert x_im*oo != I*oo # i could be +/- 3*I -> +/-oo def test_add_flatten(): # see https://github.com/sympy/sympy/issues/2633#issuecomment-29545524 a = oo + I*oo b = oo - I*oo assert a + b is nan assert a - b is nan # FIXME: This evaluates as: # >>> 1/a # 0*(oo + oo*I) # which should not simplify to 0. Should be fixed in Pow.eval #assert (1/a).simplify() == (1/b).simplify() == 0 a = Pow(2, 3, evaluate=False) assert a + a == 16 def test_issue_5160_6087_6089_6090(): # issue 6087 assert ((-2*x*y**y)**3.2).n(2) == (2**3.2*(-x*y**y)**3.2).n(2) # issue 6089 A, B, C = symbols('A,B,C', commutative=False) assert (2.*B*C)**3 == 8.0*(B*C)**3 assert (-2.*B*C)**3 == -8.0*(B*C)**3 assert (-2*B*C)**2 == 4*(B*C)**2 # issue 5160 assert sqrt(-1.0*x) == 1.0*sqrt(-x) assert sqrt(1.0*x) == 1.0*sqrt(x) # issue 6090 assert (-2*x*y*A*B)**2 == 4*x**2*y**2*(A*B)**2 def test_float_int_round(): assert int(float(sqrt(10))) == int(sqrt(10)) assert int(pi**1000) % 10 == 2 assert int(Float('1.123456789012345678901234567890e20', '')) == \ int(112345678901234567890) assert int(Float('1.123456789012345678901234567890e25', '')) == \ int(11234567890123456789012345) # decimal forces float so it's not an exact integer ending in 000000 assert int(Float('1.123456789012345678901234567890e35', '')) == \ 112345678901234567890123456789000192 assert int(Float('123456789012345678901234567890e5', '')) == \ 12345678901234567890123456789000000 assert Integer(Float('1.123456789012345678901234567890e20', '')) == \ 112345678901234567890 assert Integer(Float('1.123456789012345678901234567890e25', '')) == \ 11234567890123456789012345 # decimal forces float so it's not an exact integer ending in 000000 assert Integer(Float('1.123456789012345678901234567890e35', '')) == \ 112345678901234567890123456789000192 assert Integer(Float('123456789012345678901234567890e5', '')) == \ 12345678901234567890123456789000000 assert same_and_same_prec(Float('123000e-2',''), Float('1230.00', '')) assert same_and_same_prec(Float('123000e2',''), Float('12300000', '')) assert int(1 + Rational('.9999999999999999999999999')) == 1 assert int(pi/1e20) == 0 assert int(1 + pi/1e20) == 1 assert int(Add(1.2, -2, evaluate=False)) == int(1.2 - 2) assert int(Add(1.2, +2, evaluate=False)) == int(1.2 + 2) assert int(Add(1 + Float('.99999999999999999', ''), evaluate=False)) == 1 raises(TypeError, lambda: float(x)) raises(TypeError, lambda: float(sqrt(-1))) assert int(12345678901234567890 + cos(1)**2 + sin(1)**2) == \ 12345678901234567891 def test_issue_6611a(): assert Mul.flatten([3**Rational(1, 3), Pow(-Rational(1, 9), Rational(2, 3), evaluate=False)]) == \ ([Rational(1, 3), (-1)**Rational(2, 3)], [], None) def test_denest_add_mul(): # when working with evaluated expressions make sure they denest eq = x + 1 eq = Add(eq, 2, evaluate=False) eq = Add(eq, 2, evaluate=False) assert Add(*eq.args) == x + 5 eq = x*2 eq = Mul(eq, 2, evaluate=False) eq = Mul(eq, 2, evaluate=False) assert Mul(*eq.args) == 8*x # but don't let them denest unecessarily eq = Mul(-2, x - 2, evaluate=False) assert 2*eq == Mul(-4, x - 2, evaluate=False) assert -eq == Mul(2, x - 2, evaluate=False) def test_mul_coeff(): # It is important that all Numbers be removed from the seq; # This can be tricky when powers combine to produce those numbers p = exp(I*pi/3) assert p**2*x*p*y*p*x*p**2 == x**2*y def test_mul_zero_detection(): nz = Dummy(real=True, zero=False) r = Dummy(extended_real=True) c = Dummy(real=False, complex=True) c2 = Dummy(real=False, complex=True) i = Dummy(imaginary=True) e = nz*r*c assert e.is_imaginary is None assert e.is_extended_real is None e = nz*c assert e.is_imaginary is None assert e.is_extended_real is False e = nz*i*c assert e.is_imaginary is False assert e.is_extended_real is None # check for more than one complex; it is important to use # uniquely named Symbols to ensure that two factors appear # e.g. if the symbols have the same name they just become # a single factor, a power. e = nz*i*c*c2 assert e.is_imaginary is None assert e.is_extended_real is None # _eval_is_extended_real and _eval_is_zero both employ trapping of the # zero value so args should be tested in both directions and # TO AVOID GETTING THE CACHED RESULT, Dummy MUST BE USED # real is unknown def test(z, b, e): if z.is_zero and b.is_finite: assert e.is_extended_real and e.is_zero else: assert e.is_extended_real is None if b.is_finite: if z.is_zero: assert e.is_zero else: assert e.is_zero is None elif b.is_finite is False: if z.is_zero is None: assert e.is_zero is None else: assert e.is_zero is False for iz, ib in product(*[[True, False, None]]*2): z = Dummy('z', nonzero=iz) b = Dummy('f', finite=ib) e = Mul(z, b, evaluate=False) test(z, b, e) z = Dummy('nz', nonzero=iz) b = Dummy('f', finite=ib) e = Mul(b, z, evaluate=False) test(z, b, e) # real is True def test(z, b, e): if z.is_zero and not b.is_finite: assert e.is_extended_real is None else: assert e.is_extended_real is True for iz, ib in product(*[[True, False, None]]*2): z = Dummy('z', nonzero=iz, extended_real=True) b = Dummy('b', finite=ib, extended_real=True) e = Mul(z, b, evaluate=False) test(z, b, e) z = Dummy('z', nonzero=iz, extended_real=True) b = Dummy('b', finite=ib, extended_real=True) e = Mul(b, z, evaluate=False) test(z, b, e) def test_Mul_with_zero_infinite(): zer = Dummy(zero=True) inf = Dummy(finite=False) e = Mul(zer, inf, evaluate=False) assert e.is_extended_positive is None assert e.is_hermitian is None e = Mul(inf, zer, evaluate=False) assert e.is_extended_positive is None assert e.is_hermitian is None def test_Mul_does_not_cancel_infinities(): a, b = symbols('a b') assert ((zoo + 3*a)/(3*a + zoo)) is nan assert ((b - oo)/(b - oo)) is nan # issue 13904 expr = (1/(a+b) + 1/(a-b))/(1/(a+b) - 1/(a-b)) assert expr.subs(b, a) is nan def test_Mul_does_not_distribute_infinity(): a, b = symbols('a b') assert ((1 + I)*oo).is_Mul assert ((a + b)*(-oo)).is_Mul assert ((a + 1)*zoo).is_Mul assert ((1 + I)*oo).is_finite is False z = (1 + I)*oo assert ((1 - I)*z).expand() is oo def test_issue_8247_8354(): from sympy.functions.elementary.trigonometric import tan z = sqrt(1 + sqrt(3)) + sqrt(3 + 3*sqrt(3)) - sqrt(10 + 6*sqrt(3)) assert z.is_positive is False # it's 0 z = S('''-2**(1/3)*(3*sqrt(93) + 29)**2 - 4*(3*sqrt(93) + 29)**(4/3) + 12*sqrt(93)*(3*sqrt(93) + 29)**(1/3) + 116*(3*sqrt(93) + 29)**(1/3) + 174*2**(1/3)*sqrt(93) + 1678*2**(1/3)''') assert z.is_positive is False # it's 0 z = 2*(-3*tan(19*pi/90) + sqrt(3))*cos(11*pi/90)*cos(19*pi/90) - \ sqrt(3)*(-3 + 4*cos(19*pi/90)**2) assert z.is_positive is not True # it's zero and it shouldn't hang z = S('''9*(3*sqrt(93) + 29)**(2/3)*((3*sqrt(93) + 29)**(1/3)*(-2**(2/3)*(3*sqrt(93) + 29)**(1/3) - 2) - 2*2**(1/3))**3 + 72*(3*sqrt(93) + 29)**(2/3)*(81*sqrt(93) + 783) + (162*sqrt(93) + 1566)*((3*sqrt(93) + 29)**(1/3)*(-2**(2/3)*(3*sqrt(93) + 29)**(1/3) - 2) - 2*2**(1/3))**2''') assert z.is_positive is False # it's 0 (and a single _mexpand isn't enough) def test_Add_is_zero(): x, y = symbols('x y', zero=True) assert (x + y).is_zero # Issue 15873 e = -2*I + (1 + I)**2 assert e.is_zero is None def test_issue_14392(): assert (sin(zoo)**2).as_real_imag() == (nan, nan) def test_divmod(): assert divmod(x, y) == (x//y, x % y) assert divmod(x, 3) == (x//3, x % 3) assert divmod(3, x) == (3//x, 3 % x) def test__neg__(): assert -(x*y) == -x*y assert -(-x*y) == x*y assert -(1.*x) == -1.*x assert -(-1.*x) == 1.*x assert -(2.*x) == -2.*x assert -(-2.*x) == 2.*x with distribute(False): eq = -(x + y) assert eq.is_Mul and eq.args == (-1, x + y) def test_issue_18507(): assert Mul(zoo, zoo, 0) is nan def test_issue_17130(): e = Add(b, -b, I, -I, evaluate=False) assert e.is_zero is None # ideally this would be True def test_issue_21034(): e = -I*log((re(asin(5)) + I*im(asin(5)))/sqrt(re(asin(5))**2 + im(asin(5))**2))/pi assert e.round(2) def test_issue_22021(): from sympy.calculus.accumulationbounds import AccumBounds # these objects are special cases in Mul from sympy.tensor.tensor import TensorIndexType, tensor_indices, tensor_heads L = TensorIndexType("L") i = tensor_indices("i", L) A, B = tensor_heads("A B", [L]) e = A(i) + B(i) assert -e == -1*e e = zoo + x assert -e == -1*e a = AccumBounds(1, 2) e = a + x assert -e == -1*e for args in permutations((zoo, a, x)): e = Add(*args, evaluate=False) assert -e == -1*e assert 2*Add(1, x, x, evaluate=False) == 4*x + 2 def test_issue_22244(): assert -(zoo*x) == zoo*x def test_issue_22453(): from sympy.utilities.iterables import cartes e = Symbol('e', extended_positive=True) for a, b in cartes(*[[oo, -oo, 3]]*2): if a == b == 3: continue i = a + I*b assert i**(1 + e) is S.ComplexInfinity assert i**-e is S.Zero assert unchanged(Pow, i, e) assert 1/(oo + I*oo) is S.Zero r, i = [Dummy(infinite=True, extended_real=True) for _ in range(2)] assert 1/(r + I*i) is S.Zero assert 1/(3 + I*i) is S.Zero assert 1/(r + I*3) is S.Zero def test_issue_22613(): assert (0**(x - 2)).as_content_primitive() == (1, 0**(x - 2)) assert (0**(x + 2)).as_content_primitive() == (1, 0**(x + 2))
22b1be333bff565080984fa1989547fddefb4ebb1fc9a1867c956653c145be56
"""Trait for implementing domain elements. """ from sympy.utilities import public @public class DomainElement: """ Represents an element of a domain. Mix in this trait into a class whose instances should be recognized as elements of a domain. Method ``parent()`` gives that domain. """ __slots__ = () def parent(self): """Get the domain associated with ``self`` Examples ======== >>> from sympy import ZZ, symbols >>> x, y = symbols('x, y') >>> K = ZZ[x,y] >>> p = K(x)**2 + K(y)**2 >>> p x**2 + y**2 >>> p.parent() ZZ[x,y] Notes ===== This is used by :py:meth:`~.Domain.convert` to identify the domain associated with a domain element. """ raise NotImplementedError("abstract method")
69e2d16da0076c09022960c543db4abea8a849bba6dede9d161d5bac7225f781
"""Implementation of :class:`Domain` class. """ from typing import Any, Optional, Type from sympy.core.numbers import AlgebraicNumber from sympy.core import Basic, sympify from sympy.core.sorting import default_sort_key, ordered from sympy.external.gmpy import HAS_GMPY from sympy.polys.domains.domainelement import DomainElement from sympy.polys.orderings import lex from sympy.polys.polyerrors import UnificationFailed, CoercionFailed, DomainError from sympy.polys.polyutils import _unify_gens, _not_a_coeff from sympy.utilities import public from sympy.utilities.iterables import is_sequence @public class Domain: """Superclass for all domains in the polys domains system. See :ref:`polys-domainsintro` for an introductory explanation of the domains system. The :py:class:`~.Domain` class is an abstract base class for all of the concrete domain types. There are many different :py:class:`~.Domain` subclasses each of which has an associated ``dtype`` which is a class representing the elements of the domain. The coefficients of a :py:class:`~.Poly` are elements of a domain which must be a subclass of :py:class:`~.Domain`. Examples ======== The most common example domains are the integers :ref:`ZZ` and the rationals :ref:`QQ`. >>> from sympy import Poly, symbols, Domain >>> x, y = symbols('x, y') >>> p = Poly(x**2 + y) >>> p Poly(x**2 + y, x, y, domain='ZZ') >>> p.domain ZZ >>> isinstance(p.domain, Domain) True >>> Poly(x**2 + y/2) Poly(x**2 + 1/2*y, x, y, domain='QQ') The domains can be used directly in which case the domain object e.g. (:ref:`ZZ` or :ref:`QQ`) can be used as a constructor for elements of ``dtype``. >>> from sympy import ZZ, QQ >>> ZZ(2) 2 >>> ZZ.dtype # doctest: +SKIP <class 'int'> >>> type(ZZ(2)) # doctest: +SKIP <class 'int'> >>> QQ(1, 2) 1/2 >>> type(QQ(1, 2)) # doctest: +SKIP <class 'sympy.polys.domains.pythonrational.PythonRational'> The corresponding domain elements can be used with the arithmetic operations ``+,-,*,**`` and depending on the domain some combination of ``/,//,%`` might be usable. For example in :ref:`ZZ` both ``//`` (floor division) and ``%`` (modulo division) can be used but ``/`` (true division) cannot. Since :ref:`QQ` is a :py:class:`~.Field` its elements can be used with ``/`` but ``//`` and ``%`` should not be used. Some domains have a :py:meth:`~.Domain.gcd` method. >>> ZZ(2) + ZZ(3) 5 >>> ZZ(5) // ZZ(2) 2 >>> ZZ(5) % ZZ(2) 1 >>> QQ(1, 2) / QQ(2, 3) 3/4 >>> ZZ.gcd(ZZ(4), ZZ(2)) 2 >>> QQ.gcd(QQ(2,7), QQ(5,3)) 1/21 >>> ZZ.is_Field False >>> QQ.is_Field True There are also many other domains including: 1. :ref:`GF(p)` for finite fields of prime order. 2. :ref:`RR` for real (floating point) numbers. 3. :ref:`CC` for complex (floating point) numbers. 4. :ref:`QQ(a)` for algebraic number fields. 5. :ref:`K[x]` for polynomial rings. 6. :ref:`K(x)` for rational function fields. 7. :ref:`EX` for arbitrary expressions. Each domain is represented by a domain object and also an implementation class (``dtype``) for the elements of the domain. For example the :ref:`K[x]` domains are represented by a domain object which is an instance of :py:class:`~.PolynomialRing` and the elements are always instances of :py:class:`~.PolyElement`. The implementation class represents particular types of mathematical expressions in a way that is more efficient than a normal SymPy expression which is of type :py:class:`~.Expr`. The domain methods :py:meth:`~.Domain.from_sympy` and :py:meth:`~.Domain.to_sympy` are used to convert from :py:class:`~.Expr` to a domain element and vice versa. >>> from sympy import Symbol, ZZ, Expr >>> x = Symbol('x') >>> K = ZZ[x] # polynomial ring domain >>> K ZZ[x] >>> type(K) # class of the domain <class 'sympy.polys.domains.polynomialring.PolynomialRing'> >>> K.dtype # class of the elements <class 'sympy.polys.rings.PolyElement'> >>> p_expr = x**2 + 1 # Expr >>> p_expr x**2 + 1 >>> type(p_expr) <class 'sympy.core.add.Add'> >>> isinstance(p_expr, Expr) True >>> p_domain = K.from_sympy(p_expr) >>> p_domain # domain element x**2 + 1 >>> type(p_domain) <class 'sympy.polys.rings.PolyElement'> >>> K.to_sympy(p_domain) == p_expr True The :py:meth:`~.Domain.convert_from` method is used to convert domain elements from one domain to another. >>> from sympy import ZZ, QQ >>> ez = ZZ(2) >>> eq = QQ.convert_from(ez, ZZ) >>> type(ez) # doctest: +SKIP <class 'int'> >>> type(eq) # doctest: +SKIP <class 'sympy.polys.domains.pythonrational.PythonRational'> Elements from different domains should not be mixed in arithmetic or other operations: they should be converted to a common domain first. The domain method :py:meth:`~.Domain.unify` is used to find a domain that can represent all the elements of two given domains. >>> from sympy import ZZ, QQ, symbols >>> x, y = symbols('x, y') >>> ZZ.unify(QQ) QQ >>> ZZ[x].unify(QQ) QQ[x] >>> ZZ[x].unify(QQ[y]) QQ[x,y] If a domain is a :py:class:`~.Ring` then is might have an associated :py:class:`~.Field` and vice versa. The :py:meth:`~.Domain.get_field` and :py:meth:`~.Domain.get_ring` methods will find or create the associated domain. >>> from sympy import ZZ, QQ, Symbol >>> x = Symbol('x') >>> ZZ.has_assoc_Field True >>> ZZ.get_field() QQ >>> QQ.has_assoc_Ring True >>> QQ.get_ring() ZZ >>> K = QQ[x] >>> K QQ[x] >>> K.get_field() QQ(x) See also ======== DomainElement: abstract base class for domain elements construct_domain: construct a minimal domain for some expressions """ dtype = None # type: Optional[Type] """The type (class) of the elements of this :py:class:`~.Domain`: >>> from sympy import ZZ, QQ, Symbol >>> ZZ.dtype <class 'int'> >>> z = ZZ(2) >>> z 2 >>> type(z) <class 'int'> >>> type(z) == ZZ.dtype True Every domain has an associated **dtype** ("datatype") which is the class of the associated domain elements. See also ======== of_type """ zero = None # type: Optional[Any] """The zero element of the :py:class:`~.Domain`: >>> from sympy import QQ >>> QQ.zero 0 >>> QQ.of_type(QQ.zero) True See also ======== of_type one """ one = None # type: Optional[Any] """The one element of the :py:class:`~.Domain`: >>> from sympy import QQ >>> QQ.one 1 >>> QQ.of_type(QQ.one) True See also ======== of_type zero """ is_Ring = False """Boolean flag indicating if the domain is a :py:class:`~.Ring`. >>> from sympy import ZZ >>> ZZ.is_Ring True Basically every :py:class:`~.Domain` represents a ring so this flag is not that useful. See also ======== is_PID is_Field get_ring has_assoc_Ring """ is_Field = False """Boolean flag indicating if the domain is a :py:class:`~.Field`. >>> from sympy import ZZ, QQ >>> ZZ.is_Field False >>> QQ.is_Field True See also ======== is_PID is_Ring get_field has_assoc_Field """ has_assoc_Ring = False """Boolean flag indicating if the domain has an associated :py:class:`~.Ring`. >>> from sympy import QQ >>> QQ.has_assoc_Ring True >>> QQ.get_ring() ZZ See also ======== is_Field get_ring """ has_assoc_Field = False """Boolean flag indicating if the domain has an associated :py:class:`~.Field`. >>> from sympy import ZZ >>> ZZ.has_assoc_Field True >>> ZZ.get_field() QQ See also ======== is_Field get_field """ is_FiniteField = is_FF = False is_IntegerRing = is_ZZ = False is_RationalField = is_QQ = False is_GaussianRing = is_ZZ_I = False is_GaussianField = is_QQ_I = False is_RealField = is_RR = False is_ComplexField = is_CC = False is_AlgebraicField = is_Algebraic = False is_PolynomialRing = is_Poly = False is_FractionField = is_Frac = False is_SymbolicDomain = is_EX = False is_SymbolicRawDomain = is_EXRAW = False is_FiniteExtension = False is_Exact = True is_Numerical = False is_Simple = False is_Composite = False is_PID = False """Boolean flag indicating if the domain is a `principal ideal domain`_. >>> from sympy import ZZ >>> ZZ.has_assoc_Field True >>> ZZ.get_field() QQ .. _principal ideal domain: https://en.wikipedia.org/wiki/Principal_ideal_domain See also ======== is_Field get_field """ has_CharacteristicZero = False rep = None # type: Optional[str] alias = None # type: Optional[str] def __init__(self): raise NotImplementedError def __str__(self): return self.rep def __repr__(self): return str(self) def __hash__(self): return hash((self.__class__.__name__, self.dtype)) def new(self, *args): return self.dtype(*args) @property def tp(self): """Alias for :py:attr:`~.Domain.dtype`""" return self.dtype def __call__(self, *args): """Construct an element of ``self`` domain from ``args``. """ return self.new(*args) def normal(self, *args): return self.dtype(*args) def convert_from(self, element, base): """Convert ``element`` to ``self.dtype`` given the base domain. """ if base.alias is not None: method = "from_" + base.alias else: method = "from_" + base.__class__.__name__ _convert = getattr(self, method) if _convert is not None: result = _convert(element, base) if result is not None: return result raise CoercionFailed("Cannot convert %s of type %s from %s to %s" % (element, type(element), base, self)) def convert(self, element, base=None): """Convert ``element`` to ``self.dtype``. """ if base is not None: if _not_a_coeff(element): raise CoercionFailed('%s is not in any domain' % element) return self.convert_from(element, base) if self.of_type(element): return element if _not_a_coeff(element): raise CoercionFailed('%s is not in any domain' % element) from sympy.polys.domains import ZZ, QQ, RealField, ComplexField if ZZ.of_type(element): return self.convert_from(element, ZZ) if isinstance(element, int): return self.convert_from(ZZ(element), ZZ) if HAS_GMPY: integers = ZZ if isinstance(element, integers.tp): return self.convert_from(element, integers) rationals = QQ if isinstance(element, rationals.tp): return self.convert_from(element, rationals) if isinstance(element, float): parent = RealField(tol=False) return self.convert_from(parent(element), parent) if isinstance(element, complex): parent = ComplexField(tol=False) return self.convert_from(parent(element), parent) if isinstance(element, DomainElement): return self.convert_from(element, element.parent()) # TODO: implement this in from_ methods if self.is_Numerical and getattr(element, 'is_ground', False): return self.convert(element.LC()) if isinstance(element, Basic): try: return self.from_sympy(element) except (TypeError, ValueError): pass else: # TODO: remove this branch if not is_sequence(element): try: element = sympify(element, strict=True) if isinstance(element, Basic): return self.from_sympy(element) except (TypeError, ValueError): pass raise CoercionFailed("Cannot convert %s of type %s to %s" % (element, type(element), self)) def of_type(self, element): """Check if ``a`` is of type ``dtype``. """ return isinstance(element, self.tp) # XXX: this isn't correct, e.g. PolyElement def __contains__(self, a): """Check if ``a`` belongs to this domain. """ try: if _not_a_coeff(a): raise CoercionFailed self.convert(a) # this might raise, too except CoercionFailed: return False return True def to_sympy(self, a): """Convert domain element *a* to a SymPy expression (Expr). Explanation =========== Convert a :py:class:`~.Domain` element *a* to :py:class:`~.Expr`. Most public SymPy functions work with objects of type :py:class:`~.Expr`. The elements of a :py:class:`~.Domain` have a different internal representation. It is not possible to mix domain elements with :py:class:`~.Expr` so each domain has :py:meth:`~.Domain.to_sympy` and :py:meth:`~.Domain.from_sympy` methods to convert its domain elements to and from :py:class:`~.Expr`. Parameters ========== a: domain element An element of this :py:class:`~.Domain`. Returns ======= expr: Expr A normal SymPy expression of type :py:class:`~.Expr`. Examples ======== Construct an element of the :ref:`QQ` domain and then convert it to :py:class:`~.Expr`. >>> from sympy import QQ, Expr >>> q_domain = QQ(2) >>> q_domain 2 >>> q_expr = QQ.to_sympy(q_domain) >>> q_expr 2 Although the printed forms look similar these objects are not of the same type. >>> isinstance(q_domain, Expr) False >>> isinstance(q_expr, Expr) True Construct an element of :ref:`K[x]` and convert to :py:class:`~.Expr`. >>> from sympy import Symbol >>> x = Symbol('x') >>> K = QQ[x] >>> x_domain = K.gens[0] # generator x as a domain element >>> p_domain = x_domain**2/3 + 1 >>> p_domain 1/3*x**2 + 1 >>> p_expr = K.to_sympy(p_domain) >>> p_expr x**2/3 + 1 The :py:meth:`~.Domain.from_sympy` method is used for the opposite conversion from a normal SymPy expression to a domain element. >>> p_domain == p_expr False >>> K.from_sympy(p_expr) == p_domain True >>> K.to_sympy(p_domain) == p_expr True >>> K.from_sympy(K.to_sympy(p_domain)) == p_domain True >>> K.to_sympy(K.from_sympy(p_expr)) == p_expr True The :py:meth:`~.Domain.from_sympy` method makes it easier to construct domain elements interactively. >>> from sympy import Symbol >>> x = Symbol('x') >>> K = QQ[x] >>> K.from_sympy(x**2/3 + 1) 1/3*x**2 + 1 See also ======== from_sympy convert_from """ raise NotImplementedError def from_sympy(self, a): """Convert a SymPy expression to an element of this domain. Explanation =========== See :py:meth:`~.Domain.to_sympy` for explanation and examples. Parameters ========== expr: Expr A normal SymPy expression of type :py:class:`~.Expr`. Returns ======= a: domain element An element of this :py:class:`~.Domain`. See also ======== to_sympy convert_from """ raise NotImplementedError def sum(self, args): return sum(args) def from_FF(K1, a, K0): """Convert ``ModularInteger(int)`` to ``dtype``. """ return None def from_FF_python(K1, a, K0): """Convert ``ModularInteger(int)`` to ``dtype``. """ return None def from_ZZ_python(K1, a, K0): """Convert a Python ``int`` object to ``dtype``. """ return None def from_QQ_python(K1, a, K0): """Convert a Python ``Fraction`` object to ``dtype``. """ return None def from_FF_gmpy(K1, a, K0): """Convert ``ModularInteger(mpz)`` to ``dtype``. """ return None def from_ZZ_gmpy(K1, a, K0): """Convert a GMPY ``mpz`` object to ``dtype``. """ return None def from_QQ_gmpy(K1, a, K0): """Convert a GMPY ``mpq`` object to ``dtype``. """ return None def from_RealField(K1, a, K0): """Convert a real element object to ``dtype``. """ return None def from_ComplexField(K1, a, K0): """Convert a complex element to ``dtype``. """ return None def from_AlgebraicField(K1, a, K0): """Convert an algebraic number to ``dtype``. """ return None def from_PolynomialRing(K1, a, K0): """Convert a polynomial to ``dtype``. """ if a.is_ground: return K1.convert(a.LC, K0.dom) def from_FractionField(K1, a, K0): """Convert a rational function to ``dtype``. """ return None def from_MonogenicFiniteExtension(K1, a, K0): """Convert an ``ExtensionElement`` to ``dtype``. """ return K1.convert_from(a.rep, K0.ring) def from_ExpressionDomain(K1, a, K0): """Convert a ``EX`` object to ``dtype``. """ return K1.from_sympy(a.ex) def from_ExpressionRawDomain(K1, a, K0): """Convert a ``EX`` object to ``dtype``. """ return K1.from_sympy(a) def from_GlobalPolynomialRing(K1, a, K0): """Convert a polynomial to ``dtype``. """ if a.degree() <= 0: return K1.convert(a.LC(), K0.dom) def from_GeneralizedPolynomialRing(K1, a, K0): return K1.from_FractionField(a, K0) def unify_with_symbols(K0, K1, symbols): if (K0.is_Composite and (set(K0.symbols) & set(symbols))) or (K1.is_Composite and (set(K1.symbols) & set(symbols))): raise UnificationFailed("Cannot unify %s with %s, given %s generators" % (K0, K1, tuple(symbols))) return K0.unify(K1) def unify(K0, K1, symbols=None): """ Construct a minimal domain that contains elements of ``K0`` and ``K1``. Known domains (from smallest to largest): - ``GF(p)`` - ``ZZ`` - ``QQ`` - ``RR(prec, tol)`` - ``CC(prec, tol)`` - ``ALG(a, b, c)`` - ``K[x, y, z]`` - ``K(x, y, z)`` - ``EX`` """ if symbols is not None: return K0.unify_with_symbols(K1, symbols) if K0 == K1: return K0 if K0.is_EXRAW: return K0 if K1.is_EXRAW: return K1 if K0.is_EX: return K0 if K1.is_EX: return K1 if K0.is_FiniteExtension or K1.is_FiniteExtension: if K1.is_FiniteExtension: K0, K1 = K1, K0 if K1.is_FiniteExtension: # Unifying two extensions. # Try to ensure that K0.unify(K1) == K1.unify(K0) if list(ordered([K0.modulus, K1.modulus]))[1] == K0.modulus: K0, K1 = K1, K0 return K1.set_domain(K0) else: # Drop the generator from other and unify with the base domain K1 = K1.drop(K0.symbol) K1 = K0.domain.unify(K1) return K0.set_domain(K1) if K0.is_Composite or K1.is_Composite: K0_ground = K0.dom if K0.is_Composite else K0 K1_ground = K1.dom if K1.is_Composite else K1 K0_symbols = K0.symbols if K0.is_Composite else () K1_symbols = K1.symbols if K1.is_Composite else () domain = K0_ground.unify(K1_ground) symbols = _unify_gens(K0_symbols, K1_symbols) order = K0.order if K0.is_Composite else K1.order if ((K0.is_FractionField and K1.is_PolynomialRing or K1.is_FractionField and K0.is_PolynomialRing) and (not K0_ground.is_Field or not K1_ground.is_Field) and domain.is_Field and domain.has_assoc_Ring): domain = domain.get_ring() if K0.is_Composite and (not K1.is_Composite or K0.is_FractionField or K1.is_PolynomialRing): cls = K0.__class__ else: cls = K1.__class__ from sympy.polys.domains.old_polynomialring import GlobalPolynomialRing if cls == GlobalPolynomialRing: return cls(domain, symbols) return cls(domain, symbols, order) def mkinexact(cls, K0, K1): prec = max(K0.precision, K1.precision) tol = max(K0.tolerance, K1.tolerance) return cls(prec=prec, tol=tol) if K1.is_ComplexField: K0, K1 = K1, K0 if K0.is_ComplexField: if K1.is_ComplexField or K1.is_RealField: return mkinexact(K0.__class__, K0, K1) else: return K0 if K1.is_RealField: K0, K1 = K1, K0 if K0.is_RealField: if K1.is_RealField: return mkinexact(K0.__class__, K0, K1) elif K1.is_GaussianRing or K1.is_GaussianField: from sympy.polys.domains.complexfield import ComplexField return ComplexField(prec=K0.precision, tol=K0.tolerance) else: return K0 if K1.is_AlgebraicField: K0, K1 = K1, K0 if K0.is_AlgebraicField: if K1.is_GaussianRing: K1 = K1.get_field() if K1.is_GaussianField: K1 = K1.as_AlgebraicField() if K1.is_AlgebraicField: return K0.__class__(K0.dom.unify(K1.dom), *_unify_gens(K0.orig_ext, K1.orig_ext)) else: return K0 if K0.is_GaussianField: return K0 if K1.is_GaussianField: return K1 if K0.is_GaussianRing: if K1.is_RationalField: K0 = K0.get_field() return K0 if K1.is_GaussianRing: if K0.is_RationalField: K1 = K1.get_field() return K1 if K0.is_RationalField: return K0 if K1.is_RationalField: return K1 if K0.is_IntegerRing: return K0 if K1.is_IntegerRing: return K1 if K0.is_FiniteField and K1.is_FiniteField: return K0.__class__(max(K0.mod, K1.mod, key=default_sort_key)) from sympy.polys.domains import EX return EX def __eq__(self, other): """Returns ``True`` if two domains are equivalent. """ return isinstance(other, Domain) and self.dtype == other.dtype def __ne__(self, other): """Returns ``False`` if two domains are equivalent. """ return not self == other def map(self, seq): """Rersively apply ``self`` to all elements of ``seq``. """ result = [] for elt in seq: if isinstance(elt, list): result.append(self.map(elt)) else: result.append(self(elt)) return result def get_ring(self): """Returns a ring associated with ``self``. """ raise DomainError('there is no ring associated with %s' % self) def get_field(self): """Returns a field associated with ``self``. """ raise DomainError('there is no field associated with %s' % self) def get_exact(self): """Returns an exact domain associated with ``self``. """ return self def __getitem__(self, symbols): """The mathematical way to make a polynomial ring. """ if hasattr(symbols, '__iter__'): return self.poly_ring(*symbols) else: return self.poly_ring(symbols) def poly_ring(self, *symbols, order=lex): """Returns a polynomial ring, i.e. `K[X]`. """ from sympy.polys.domains.polynomialring import PolynomialRing return PolynomialRing(self, symbols, order) def frac_field(self, *symbols, order=lex): """Returns a fraction field, i.e. `K(X)`. """ from sympy.polys.domains.fractionfield import FractionField return FractionField(self, symbols, order) def old_poly_ring(self, *symbols, **kwargs): """Returns a polynomial ring, i.e. `K[X]`. """ from sympy.polys.domains.old_polynomialring import PolynomialRing return PolynomialRing(self, *symbols, **kwargs) def old_frac_field(self, *symbols, **kwargs): """Returns a fraction field, i.e. `K(X)`. """ from sympy.polys.domains.old_fractionfield import FractionField return FractionField(self, *symbols, **kwargs) def algebraic_field(self, *extension): r"""Returns an algebraic field, i.e. `K(\alpha, \ldots)`. """ raise DomainError("Cannot create algebraic field over %s" % self) def alg_field_from_poly(self, poly, alias=None, root_index=-1): r""" Convenience method to construct an algebraic extension on a root of a polynomial, chosen by root index. Parameters ========== poly : :py:class:`~.Poly` The polynomial whose root generates the extension. alias : str, optional (default=None) Symbol name for the generator of the extension. E.g. "alpha" or "theta". root_index : int, optional (default=-1) Specifies which root of the polynomial is desired. The ordering is as defined by the :py:class:`~.ComplexRootOf` class. The default of ``-1`` selects the most natural choice in the common cases of quadratic and cyclotomic fields (the square root on the positive real or imaginary axis, resp. $\mathrm{e}^{2\pi i/n}$). Examples ======== >>> from sympy import QQ, Poly >>> from sympy.abc import x >>> f = Poly(x**2 - 2) >>> K = QQ.alg_field_from_poly(f) >>> K.ext.minpoly == f True >>> g = Poly(8*x**3 - 6*x - 1) >>> L = QQ.alg_field_from_poly(g, "alpha") >>> L.ext.minpoly == g True >>> L.to_sympy(L([1, 1, 1])) alpha**2 + alpha + 1 """ from sympy.polys.rootoftools import CRootOf root = CRootOf(poly, root_index) alpha = AlgebraicNumber(root, alias=alias) return self.algebraic_field(alpha) def cyclotomic_field(self, n, ss=False, alias="zeta", gen=None, root_index=-1): r""" Convenience method to construct a cyclotomic field. Parameters ========== n : int Construct the nth cyclotomic field. ss : boolean, optional (default=False) If True, append *n* as a subscript on the alias string. alias : str, optional (default="zeta") Symbol name for the generator. gen : :py:class:`~.Symbol`, optional (default=None) Desired variable for the cyclotomic polynomial that defines the field. If ``None``, a dummy variable will be used. root_index : int, optional (default=-1) Specifies which root of the polynomial is desired. The ordering is as defined by the :py:class:`~.ComplexRootOf` class. The default of ``-1`` selects the root $\mathrm{e}^{2\pi i/n}$. Examples ======== >>> from sympy import QQ, latex >>> K = QQ.cyclotomic_field(5) >>> K.to_sympy(K([-1, 1])) 1 - zeta >>> L = QQ.cyclotomic_field(7, True) >>> a = L.to_sympy(L([-1, 1])) >>> print(a) 1 - zeta7 >>> print(latex(a)) 1 - \zeta_{7} """ from sympy.polys.specialpolys import cyclotomic_poly if ss: alias += str(n) return self.alg_field_from_poly(cyclotomic_poly(n, gen), alias=alias, root_index=root_index) def inject(self, *symbols): """Inject generators into this domain. """ raise NotImplementedError def drop(self, *symbols): """Drop generators from this domain. """ if self.is_Simple: return self raise NotImplementedError # pragma: no cover def is_zero(self, a): """Returns True if ``a`` is zero. """ return not a def is_one(self, a): """Returns True if ``a`` is one. """ return a == self.one def is_positive(self, a): """Returns True if ``a`` is positive. """ return a > 0 def is_negative(self, a): """Returns True if ``a`` is negative. """ return a < 0 def is_nonpositive(self, a): """Returns True if ``a`` is non-positive. """ return a <= 0 def is_nonnegative(self, a): """Returns True if ``a`` is non-negative. """ return a >= 0 def canonical_unit(self, a): if self.is_negative(a): return -self.one else: return self.one def abs(self, a): """Absolute value of ``a``, implies ``__abs__``. """ return abs(a) def neg(self, a): """Returns ``a`` negated, implies ``__neg__``. """ return -a def pos(self, a): """Returns ``a`` positive, implies ``__pos__``. """ return +a def add(self, a, b): """Sum of ``a`` and ``b``, implies ``__add__``. """ return a + b def sub(self, a, b): """Difference of ``a`` and ``b``, implies ``__sub__``. """ return a - b def mul(self, a, b): """Product of ``a`` and ``b``, implies ``__mul__``. """ return a * b def pow(self, a, b): """Raise ``a`` to power ``b``, implies ``__pow__``. """ return a ** b def exquo(self, a, b): """Exact quotient of *a* and *b*. Analogue of ``a / b``. Explanation =========== This is essentially the same as ``a / b`` except that an error will be raised if the division is inexact (if there is any remainder) and the result will always be a domain element. When working in a :py:class:`~.Domain` that is not a :py:class:`~.Field` (e.g. :ref:`ZZ` or :ref:`K[x]`) ``exquo`` should be used instead of ``/``. The key invariant is that if ``q = K.exquo(a, b)`` (and ``exquo`` does not raise an exception) then ``a == b*q``. Examples ======== We can use ``K.exquo`` instead of ``/`` for exact division. >>> from sympy import ZZ >>> ZZ.exquo(ZZ(4), ZZ(2)) 2 >>> ZZ.exquo(ZZ(5), ZZ(2)) Traceback (most recent call last): ... ExactQuotientFailed: 2 does not divide 5 in ZZ Over a :py:class:`~.Field` such as :ref:`QQ`, division (with nonzero divisor) is always exact so in that case ``/`` can be used instead of :py:meth:`~.Domain.exquo`. >>> from sympy import QQ >>> QQ.exquo(QQ(5), QQ(2)) 5/2 >>> QQ(5) / QQ(2) 5/2 Parameters ========== a: domain element The dividend b: domain element The divisor Returns ======= q: domain element The exact quotient Raises ====== ExactQuotientFailed: if exact division is not possible. ZeroDivisionError: when the divisor is zero. See also ======== quo: Analogue of ``a // b`` rem: Analogue of ``a % b`` div: Analogue of ``divmod(a, b)`` Notes ===== Since the default :py:attr:`~.Domain.dtype` for :ref:`ZZ` is ``int`` (or ``mpz``) division as ``a / b`` should not be used as it would give a ``float``. >>> ZZ(4) / ZZ(2) 2.0 >>> ZZ(5) / ZZ(2) 2.5 Using ``/`` with :ref:`ZZ` will lead to incorrect results so :py:meth:`~.Domain.exquo` should be used instead. """ raise NotImplementedError def quo(self, a, b): """Quotient of *a* and *b*. Analogue of ``a // b``. ``K.quo(a, b)`` is equivalent to ``K.div(a, b)[0]``. See :py:meth:`~.Domain.div` for more explanation. See also ======== rem: Analogue of ``a % b`` div: Analogue of ``divmod(a, b)`` exquo: Analogue of ``a / b`` """ raise NotImplementedError def rem(self, a, b): """Modulo division of *a* and *b*. Analogue of ``a % b``. ``K.rem(a, b)`` is equivalent to ``K.div(a, b)[1]``. See :py:meth:`~.Domain.div` for more explanation. See also ======== quo: Analogue of ``a // b`` div: Analogue of ``divmod(a, b)`` exquo: Analogue of ``a / b`` """ raise NotImplementedError def div(self, a, b): """Quotient and remainder for *a* and *b*. Analogue of ``divmod(a, b)`` Explanation =========== This is essentially the same as ``divmod(a, b)`` except that is more consistent when working over some :py:class:`~.Field` domains such as :ref:`QQ`. When working over an arbitrary :py:class:`~.Domain` the :py:meth:`~.Domain.div` method should be used instead of ``divmod``. The key invariant is that if ``q, r = K.div(a, b)`` then ``a == b*q + r``. The result of ``K.div(a, b)`` is the same as the tuple ``(K.quo(a, b), K.rem(a, b))`` except that if both quotient and remainder are needed then it is more efficient to use :py:meth:`~.Domain.div`. Examples ======== We can use ``K.div`` instead of ``divmod`` for floor division and remainder. >>> from sympy import ZZ, QQ >>> ZZ.div(ZZ(5), ZZ(2)) (2, 1) If ``K`` is a :py:class:`~.Field` then the division is always exact with a remainder of :py:attr:`~.Domain.zero`. >>> QQ.div(QQ(5), QQ(2)) (5/2, 0) Parameters ========== a: domain element The dividend b: domain element The divisor Returns ======= (q, r): tuple of domain elements The quotient and remainder Raises ====== ZeroDivisionError: when the divisor is zero. See also ======== quo: Analogue of ``a // b`` rem: Analogue of ``a % b`` exquo: Analogue of ``a / b`` Notes ===== If ``gmpy`` is installed then the ``gmpy.mpq`` type will be used as the :py:attr:`~.Domain.dtype` for :ref:`QQ`. The ``gmpy.mpq`` type defines ``divmod`` in a way that is undesirable so :py:meth:`~.Domain.div` should be used instead of ``divmod``. >>> a = QQ(1) >>> b = QQ(3, 2) >>> a # doctest: +SKIP mpq(1,1) >>> b # doctest: +SKIP mpq(3,2) >>> divmod(a, b) # doctest: +SKIP (mpz(0), mpq(1,1)) >>> QQ.div(a, b) # doctest: +SKIP (mpq(2,3), mpq(0,1)) Using ``//`` or ``%`` with :ref:`QQ` will lead to incorrect results so :py:meth:`~.Domain.div` should be used instead. """ raise NotImplementedError def invert(self, a, b): """Returns inversion of ``a mod b``, implies something. """ raise NotImplementedError def revert(self, a): """Returns ``a**(-1)`` if possible. """ raise NotImplementedError def numer(self, a): """Returns numerator of ``a``. """ raise NotImplementedError def denom(self, a): """Returns denominator of ``a``. """ raise NotImplementedError def half_gcdex(self, a, b): """Half extended GCD of ``a`` and ``b``. """ s, t, h = self.gcdex(a, b) return s, h def gcdex(self, a, b): """Extended GCD of ``a`` and ``b``. """ raise NotImplementedError def cofactors(self, a, b): """Returns GCD and cofactors of ``a`` and ``b``. """ gcd = self.gcd(a, b) cfa = self.quo(a, gcd) cfb = self.quo(b, gcd) return gcd, cfa, cfb def gcd(self, a, b): """Returns GCD of ``a`` and ``b``. """ raise NotImplementedError def lcm(self, a, b): """Returns LCM of ``a`` and ``b``. """ raise NotImplementedError def log(self, a, b): """Returns b-base logarithm of ``a``. """ raise NotImplementedError def sqrt(self, a): """Returns square root of ``a``. """ raise NotImplementedError def evalf(self, a, prec=None, **options): """Returns numerical approximation of ``a``. """ return self.to_sympy(a).evalf(prec, **options) n = evalf def real(self, a): return a def imag(self, a): return self.zero def almosteq(self, a, b, tolerance=None): """Check if ``a`` and ``b`` are almost equal. """ return a == b def characteristic(self): """Return the characteristic of this domain. """ raise NotImplementedError('characteristic()') __all__ = ['Domain']
04360cb7f4687be0cd59d4d627d9eb08f47dee3692c96c0656a2adb1bc35ffe2
from sympy.polys.domains import QQ, EX, RR from sympy.polys.rings import ring from sympy.polys.ring_series import (_invert_monoms, rs_integrate, rs_trunc, rs_mul, rs_square, rs_pow, _has_constant_term, rs_hadamard_exp, rs_series_from_list, rs_exp, rs_log, rs_newton, rs_series_inversion, rs_compose_add, rs_asin, rs_atan, rs_atanh, rs_tan, rs_cot, rs_sin, rs_cos, rs_cos_sin, rs_sinh, rs_cosh, rs_tanh, _tan1, rs_fun, rs_nth_root, rs_LambertW, rs_series_reversion, rs_is_puiseux, rs_series) from sympy.testing.pytest import raises, slow from sympy.core.symbol import symbols from sympy.functions import (sin, cos, exp, tan, cot, atan, atanh, tanh, log, sqrt) from sympy.core.numbers import Rational from sympy.core import expand, S def is_close(a, b): tol = 10**(-10) assert abs(a - b) < tol def test_ring_series1(): R, x = ring('x', QQ) p = x**4 + 2*x**3 + 3*x + 4 assert _invert_monoms(p) == 4*x**4 + 3*x**3 + 2*x + 1 assert rs_hadamard_exp(p) == x**4/24 + x**3/3 + 3*x + 4 R, x = ring('x', QQ) p = x**4 + 2*x**3 + 3*x + 4 assert rs_integrate(p, x) == x**5/5 + x**4/2 + 3*x**2/2 + 4*x R, x, y = ring('x, y', QQ) p = x**2*y**2 + x + 1 assert rs_integrate(p, x) == x**3*y**2/3 + x**2/2 + x assert rs_integrate(p, y) == x**2*y**3/3 + x*y + y def test_trunc(): R, x, y, t = ring('x, y, t', QQ) p = (y + t*x)**4 p1 = rs_trunc(p, x, 3) assert p1 == y**4 + 4*y**3*t*x + 6*y**2*t**2*x**2 def test_mul_trunc(): R, x, y, t = ring('x, y, t', QQ) p = 1 + t*x + t*y for i in range(2): p = rs_mul(p, p, t, 3) assert p == 6*x**2*t**2 + 12*x*y*t**2 + 6*y**2*t**2 + 4*x*t + 4*y*t + 1 p = 1 + t*x + t*y + t**2*x*y p1 = rs_mul(p, p, t, 2) assert p1 == 1 + 2*t*x + 2*t*y R1, z = ring('z', QQ) raises(ValueError, lambda: rs_mul(p, z, x, 2)) p1 = 2 + 2*x + 3*x**2 p2 = 3 + x**2 assert rs_mul(p1, p2, x, 4) == 2*x**3 + 11*x**2 + 6*x + 6 def test_square_trunc(): R, x, y, t = ring('x, y, t', QQ) p = (1 + t*x + t*y)*2 p1 = rs_mul(p, p, x, 3) p2 = rs_square(p, x, 3) assert p1 == p2 p = 1 + x + x**2 + x**3 assert rs_square(p, x, 4) == 4*x**3 + 3*x**2 + 2*x + 1 def test_pow_trunc(): R, x, y, z = ring('x, y, z', QQ) p0 = y + x*z p = p0**16 for xx in (x, y, z): p1 = rs_trunc(p, xx, 8) p2 = rs_pow(p0, 16, xx, 8) assert p1 == p2 p = 1 + x p1 = rs_pow(p, 3, x, 2) assert p1 == 1 + 3*x assert rs_pow(p, 0, x, 2) == 1 assert rs_pow(p, -2, x, 2) == 1 - 2*x p = x + y assert rs_pow(p, 3, y, 3) == x**3 + 3*x**2*y + 3*x*y**2 assert rs_pow(1 + x, Rational(2, 3), x, 4) == 4*x**3/81 - x**2/9 + x*Rational(2, 3) + 1 def test_has_constant_term(): R, x, y, z = ring('x, y, z', QQ) p = y + x*z assert _has_constant_term(p, x) p = x + x**4 assert not _has_constant_term(p, x) p = 1 + x + x**4 assert _has_constant_term(p, x) p = x + y + x*z def test_inversion(): R, x = ring('x', QQ) p = 2 + x + 2*x**2 n = 5 p1 = rs_series_inversion(p, x, n) assert rs_trunc(p*p1, x, n) == 1 R, x, y = ring('x, y', QQ) p = 2 + x + 2*x**2 + y*x + x**2*y p1 = rs_series_inversion(p, x, n) assert rs_trunc(p*p1, x, n) == 1 R, x, y = ring('x, y', QQ) p = 1 + x + y raises(NotImplementedError, lambda: rs_series_inversion(p, x, 4)) p = R.zero raises(ZeroDivisionError, lambda: rs_series_inversion(p, x, 3)) def test_series_reversion(): R, x, y = ring('x, y', QQ) p = rs_tan(x, x, 10) assert rs_series_reversion(p, x, 8, y) == rs_atan(y, y, 8) p = rs_sin(x, x, 10) assert rs_series_reversion(p, x, 8, y) == 5*y**7/112 + 3*y**5/40 + \ y**3/6 + y def test_series_from_list(): R, x = ring('x', QQ) p = 1 + 2*x + x**2 + 3*x**3 c = [1, 2, 0, 4, 4] r = rs_series_from_list(p, c, x, 5) pc = R.from_list(list(reversed(c))) r1 = rs_trunc(pc.compose(x, p), x, 5) assert r == r1 R, x, y = ring('x, y', QQ) c = [1, 3, 5, 7] p1 = rs_series_from_list(x + y, c, x, 3, concur=0) p2 = rs_trunc((1 + 3*(x+y) + 5*(x+y)**2 + 7*(x+y)**3), x, 3) assert p1 == p2 R, x = ring('x', QQ) h = 25 p = rs_exp(x, x, h) - 1 p1 = rs_series_from_list(p, c, x, h) p2 = 0 for i, cx in enumerate(c): p2 += cx*rs_pow(p, i, x, h) assert p1 == p2 def test_log(): R, x = ring('x', QQ) p = 1 + x p1 = rs_log(p, x, 4)/x**2 assert p1 == Rational(1, 3)*x - S.Half + x**(-1) p = 1 + x +2*x**2/3 p1 = rs_log(p, x, 9) assert p1 == -17*x**8/648 + 13*x**7/189 - 11*x**6/162 - x**5/45 + \ 7*x**4/36 - x**3/3 + x**2/6 + x p2 = rs_series_inversion(p, x, 9) p3 = rs_log(p2, x, 9) assert p3 == -p1 R, x, y = ring('x, y', QQ) p = 1 + x + 2*y*x**2 p1 = rs_log(p, x, 6) assert p1 == (4*x**5*y**2 - 2*x**5*y - 2*x**4*y**2 + x**5/5 + 2*x**4*y - x**4/4 - 2*x**3*y + x**3/3 + 2*x**2*y - x**2/2 + x) # Constant term in series a = symbols('a') R, x, y = ring('x, y', EX) assert rs_log(x + a, x, 5) == -EX(1/(4*a**4))*x**4 + EX(1/(3*a**3))*x**3 \ - EX(1/(2*a**2))*x**2 + EX(1/a)*x + EX(log(a)) assert rs_log(x + x**2*y + a, x, 4) == -EX(a**(-2))*x**3*y + \ EX(1/(3*a**3))*x**3 + EX(1/a)*x**2*y - EX(1/(2*a**2))*x**2 + \ EX(1/a)*x + EX(log(a)) p = x + x**2 + 3 assert rs_log(p, x, 10).compose(x, 5) == EX(log(3) + Rational(19281291595, 9920232)) def test_exp(): R, x = ring('x', QQ) p = x + x**4 for h in [10, 30]: q = rs_series_inversion(1 + p, x, h) - 1 p1 = rs_exp(q, x, h) q1 = rs_log(p1, x, h) assert q1 == q p1 = rs_exp(p, x, 30) assert p1.coeff(x**29) == QQ(74274246775059676726972369, 353670479749588078181744640000) prec = 21 p = rs_log(1 + x, x, prec) p1 = rs_exp(p, x, prec) assert p1 == x + 1 # Constant term in series a = symbols('a') R, x, y = ring('x, y', QQ[exp(a), a]) assert rs_exp(x + a, x, 5) == exp(a)*x**4/24 + exp(a)*x**3/6 + \ exp(a)*x**2/2 + exp(a)*x + exp(a) assert rs_exp(x + x**2*y + a, x, 5) == exp(a)*x**4*y**2/2 + \ exp(a)*x**4*y/2 + exp(a)*x**4/24 + exp(a)*x**3*y + \ exp(a)*x**3/6 + exp(a)*x**2*y + exp(a)*x**2/2 + exp(a)*x + exp(a) R, x, y = ring('x, y', EX) assert rs_exp(x + a, x, 5) == EX(exp(a)/24)*x**4 + EX(exp(a)/6)*x**3 + \ EX(exp(a)/2)*x**2 + EX(exp(a))*x + EX(exp(a)) assert rs_exp(x + x**2*y + a, x, 5) == EX(exp(a)/2)*x**4*y**2 + \ EX(exp(a)/2)*x**4*y + EX(exp(a)/24)*x**4 + EX(exp(a))*x**3*y + \ EX(exp(a)/6)*x**3 + EX(exp(a))*x**2*y + EX(exp(a)/2)*x**2 + \ EX(exp(a))*x + EX(exp(a)) def test_newton(): R, x = ring('x', QQ) p = x**2 - 2 r = rs_newton(p, x, 4) assert r == 8*x**4 + 4*x**2 + 2 def test_compose_add(): R, x = ring('x', QQ) p1 = x**3 - 1 p2 = x**2 - 2 assert rs_compose_add(p1, p2) == x**6 - 6*x**4 - 2*x**3 + 12*x**2 - 12*x - 7 def test_fun(): R, x, y = ring('x, y', QQ) p = x*y + x**2*y**3 + x**5*y assert rs_fun(p, rs_tan, x, 10) == rs_tan(p, x, 10) assert rs_fun(p, _tan1, x, 10) == _tan1(p, x, 10) def test_nth_root(): R, x, y = ring('x, y', QQ) assert rs_nth_root(1 + x**2*y, 4, x, 10) == -77*x**8*y**4/2048 + \ 7*x**6*y**3/128 - 3*x**4*y**2/32 + x**2*y/4 + 1 assert rs_nth_root(1 + x*y + x**2*y**3, 3, x, 5) == -x**4*y**6/9 + \ 5*x**4*y**5/27 - 10*x**4*y**4/243 - 2*x**3*y**4/9 + 5*x**3*y**3/81 + \ x**2*y**3/3 - x**2*y**2/9 + x*y/3 + 1 assert rs_nth_root(8*x, 3, x, 3) == 2*x**QQ(1, 3) assert rs_nth_root(8*x + x**2 + x**3, 3, x, 3) == x**QQ(4,3)/12 + 2*x**QQ(1,3) r = rs_nth_root(8*x + x**2*y + x**3, 3, x, 4) assert r == -x**QQ(7,3)*y**2/288 + x**QQ(7,3)/12 + x**QQ(4,3)*y/12 + 2*x**QQ(1,3) # Constant term in series a = symbols('a') R, x, y = ring('x, y', EX) assert rs_nth_root(x + a, 3, x, 4) == EX(5/(81*a**QQ(8, 3)))*x**3 - \ EX(1/(9*a**QQ(5, 3)))*x**2 + EX(1/(3*a**QQ(2, 3)))*x + EX(a**QQ(1, 3)) assert rs_nth_root(x**QQ(2, 3) + x**2*y + 5, 2, x, 3) == -EX(sqrt(5)/100)*\ x**QQ(8, 3)*y - EX(sqrt(5)/16000)*x**QQ(8, 3) + EX(sqrt(5)/10)*x**2*y + \ EX(sqrt(5)/2000)*x**2 - EX(sqrt(5)/200)*x**QQ(4, 3) + \ EX(sqrt(5)/10)*x**QQ(2, 3) + EX(sqrt(5)) def test_atan(): R, x, y = ring('x, y', QQ) assert rs_atan(x, x, 9) == -x**7/7 + x**5/5 - x**3/3 + x assert rs_atan(x*y + x**2*y**3, x, 9) == 2*x**8*y**11 - x**8*y**9 + \ 2*x**7*y**9 - x**7*y**7/7 - x**6*y**9/3 + x**6*y**7 - x**5*y**7 + \ x**5*y**5/5 - x**4*y**5 - x**3*y**3/3 + x**2*y**3 + x*y # Constant term in series a = symbols('a') R, x, y = ring('x, y', EX) assert rs_atan(x + a, x, 5) == -EX((a**3 - a)/(a**8 + 4*a**6 + 6*a**4 + \ 4*a**2 + 1))*x**4 + EX((3*a**2 - 1)/(3*a**6 + 9*a**4 + \ 9*a**2 + 3))*x**3 - EX(a/(a**4 + 2*a**2 + 1))*x**2 + \ EX(1/(a**2 + 1))*x + EX(atan(a)) assert rs_atan(x + x**2*y + a, x, 4) == -EX(2*a/(a**4 + 2*a**2 + 1)) \ *x**3*y + EX((3*a**2 - 1)/(3*a**6 + 9*a**4 + 9*a**2 + 3))*x**3 + \ EX(1/(a**2 + 1))*x**2*y - EX(a/(a**4 + 2*a**2 + 1))*x**2 + EX(1/(a**2 \ + 1))*x + EX(atan(a)) def test_asin(): R, x, y = ring('x, y', QQ) assert rs_asin(x + x*y, x, 5) == x**3*y**3/6 + x**3*y**2/2 + x**3*y/2 + \ x**3/6 + x*y + x assert rs_asin(x*y + x**2*y**3, x, 6) == x**5*y**7/2 + 3*x**5*y**5/40 + \ x**4*y**5/2 + x**3*y**3/6 + x**2*y**3 + x*y def test_tan(): R, x, y = ring('x, y', QQ) assert rs_tan(x, x, 9)/x**5 == \ Rational(17, 315)*x**2 + Rational(2, 15) + Rational(1, 3)*x**(-2) + x**(-4) assert rs_tan(x*y + x**2*y**3, x, 9) == 4*x**8*y**11/3 + 17*x**8*y**9/45 + \ 4*x**7*y**9/3 + 17*x**7*y**7/315 + x**6*y**9/3 + 2*x**6*y**7/3 + \ x**5*y**7 + 2*x**5*y**5/15 + x**4*y**5 + x**3*y**3/3 + x**2*y**3 + x*y # Constant term in series a = symbols('a') R, x, y = ring('x, y', QQ[tan(a), a]) assert rs_tan(x + a, x, 5) == (tan(a)**5 + 5*tan(a)**3/3 + 2*tan(a)/3)*x**4 + (tan(a)**4 + 4*tan(a)**2/3 + Rational(1, 3))*x**3 + \ (tan(a)**3 + tan(a))*x**2 + (tan(a)**2 + 1)*x + tan(a) assert rs_tan(x + x**2*y + a, x, 4) == (2*tan(a)**3 + 2*tan(a))*x**3*y + \ (tan(a)**4 + Rational(4, 3)*tan(a)**2 + Rational(1, 3))*x**3 + (tan(a)**2 + 1)*x**2*y + \ (tan(a)**3 + tan(a))*x**2 + (tan(a)**2 + 1)*x + tan(a) R, x, y = ring('x, y', EX) assert rs_tan(x + a, x, 5) == EX(tan(a)**5 + 5*tan(a)**3/3 + 2*tan(a)/3)*x**4 + EX(tan(a)**4 + 4*tan(a)**2/3 + EX(1)/3)*x**3 + \ EX(tan(a)**3 + tan(a))*x**2 + EX(tan(a)**2 + 1)*x + EX(tan(a)) assert rs_tan(x + x**2*y + a, x, 4) == EX(2*tan(a)**3 + 2*tan(a))*x**3*y + EX(tan(a)**4 + 4*tan(a)**2/3 + EX(1)/3)*x**3 + \ EX(tan(a)**2 + 1)*x**2*y + EX(tan(a)**3 + tan(a))*x**2 + \ EX(tan(a)**2 + 1)*x + EX(tan(a)) p = x + x**2 + 5 assert rs_atan(p, x, 10).compose(x, 10) == EX(atan(5) + S(67701870330562640) / \ 668083460499) def test_cot(): R, x, y = ring('x, y', QQ) assert rs_cot(x**6 + x**7, x, 8) == x**(-6) - x**(-5) + x**(-4) - \ x**(-3) + x**(-2) - x**(-1) + 1 - x + x**2 - x**3 + x**4 - x**5 + \ 2*x**6/3 - 4*x**7/3 assert rs_cot(x + x**2*y, x, 5) == -x**4*y**5 - x**4*y/15 + x**3*y**4 - \ x**3/45 - x**2*y**3 - x**2*y/3 + x*y**2 - x/3 - y + x**(-1) def test_sin(): R, x, y = ring('x, y', QQ) assert rs_sin(x, x, 9)/x**5 == \ Rational(-1, 5040)*x**2 + Rational(1, 120) - Rational(1, 6)*x**(-2) + x**(-4) assert rs_sin(x*y + x**2*y**3, x, 9) == x**8*y**11/12 - \ x**8*y**9/720 + x**7*y**9/12 - x**7*y**7/5040 - x**6*y**9/6 + \ x**6*y**7/24 - x**5*y**7/2 + x**5*y**5/120 - x**4*y**5/2 - \ x**3*y**3/6 + x**2*y**3 + x*y # Constant term in series a = symbols('a') R, x, y = ring('x, y', QQ[sin(a), cos(a), a]) assert rs_sin(x + a, x, 5) == sin(a)*x**4/24 - cos(a)*x**3/6 - \ sin(a)*x**2/2 + cos(a)*x + sin(a) assert rs_sin(x + x**2*y + a, x, 5) == -sin(a)*x**4*y**2/2 - \ cos(a)*x**4*y/2 + sin(a)*x**4/24 - sin(a)*x**3*y - cos(a)*x**3/6 + \ cos(a)*x**2*y - sin(a)*x**2/2 + cos(a)*x + sin(a) R, x, y = ring('x, y', EX) assert rs_sin(x + a, x, 5) == EX(sin(a)/24)*x**4 - EX(cos(a)/6)*x**3 - \ EX(sin(a)/2)*x**2 + EX(cos(a))*x + EX(sin(a)) assert rs_sin(x + x**2*y + a, x, 5) == -EX(sin(a)/2)*x**4*y**2 - \ EX(cos(a)/2)*x**4*y + EX(sin(a)/24)*x**4 - EX(sin(a))*x**3*y - \ EX(cos(a)/6)*x**3 + EX(cos(a))*x**2*y - EX(sin(a)/2)*x**2 + \ EX(cos(a))*x + EX(sin(a)) def test_cos(): R, x, y = ring('x, y', QQ) assert rs_cos(x, x, 9)/x**5 == \ Rational(1, 40320)*x**3 - Rational(1, 720)*x + Rational(1, 24)*x**(-1) - S.Half*x**(-3) + x**(-5) assert rs_cos(x*y + x**2*y**3, x, 9) == x**8*y**12/24 - \ x**8*y**10/48 + x**8*y**8/40320 + x**7*y**10/6 - \ x**7*y**8/120 + x**6*y**8/4 - x**6*y**6/720 + x**5*y**6/6 - \ x**4*y**6/2 + x**4*y**4/24 - x**3*y**4 - x**2*y**2/2 + 1 # Constant term in series a = symbols('a') R, x, y = ring('x, y', QQ[sin(a), cos(a), a]) assert rs_cos(x + a, x, 5) == cos(a)*x**4/24 + sin(a)*x**3/6 - \ cos(a)*x**2/2 - sin(a)*x + cos(a) assert rs_cos(x + x**2*y + a, x, 5) == -cos(a)*x**4*y**2/2 + \ sin(a)*x**4*y/2 + cos(a)*x**4/24 - cos(a)*x**3*y + sin(a)*x**3/6 - \ sin(a)*x**2*y - cos(a)*x**2/2 - sin(a)*x + cos(a) R, x, y = ring('x, y', EX) assert rs_cos(x + a, x, 5) == EX(cos(a)/24)*x**4 + EX(sin(a)/6)*x**3 - \ EX(cos(a)/2)*x**2 - EX(sin(a))*x + EX(cos(a)) assert rs_cos(x + x**2*y + a, x, 5) == -EX(cos(a)/2)*x**4*y**2 + \ EX(sin(a)/2)*x**4*y + EX(cos(a)/24)*x**4 - EX(cos(a))*x**3*y + \ EX(sin(a)/6)*x**3 - EX(sin(a))*x**2*y - EX(cos(a)/2)*x**2 - \ EX(sin(a))*x + EX(cos(a)) def test_cos_sin(): R, x, y = ring('x, y', QQ) cos, sin = rs_cos_sin(x, x, 9) assert cos == rs_cos(x, x, 9) assert sin == rs_sin(x, x, 9) cos, sin = rs_cos_sin(x + x*y, x, 5) assert cos == rs_cos(x + x*y, x, 5) assert sin == rs_sin(x + x*y, x, 5) def test_atanh(): R, x, y = ring('x, y', QQ) assert rs_atanh(x, x, 9)/x**5 == Rational(1, 7)*x**2 + Rational(1, 5) + Rational(1, 3)*x**(-2) + x**(-4) assert rs_atanh(x*y + x**2*y**3, x, 9) == 2*x**8*y**11 + x**8*y**9 + \ 2*x**7*y**9 + x**7*y**7/7 + x**6*y**9/3 + x**6*y**7 + x**5*y**7 + \ x**5*y**5/5 + x**4*y**5 + x**3*y**3/3 + x**2*y**3 + x*y # Constant term in series a = symbols('a') R, x, y = ring('x, y', EX) assert rs_atanh(x + a, x, 5) == EX((a**3 + a)/(a**8 - 4*a**6 + 6*a**4 - \ 4*a**2 + 1))*x**4 - EX((3*a**2 + 1)/(3*a**6 - 9*a**4 + \ 9*a**2 - 3))*x**3 + EX(a/(a**4 - 2*a**2 + 1))*x**2 - EX(1/(a**2 - \ 1))*x + EX(atanh(a)) assert rs_atanh(x + x**2*y + a, x, 4) == EX(2*a/(a**4 - 2*a**2 + \ 1))*x**3*y - EX((3*a**2 + 1)/(3*a**6 - 9*a**4 + 9*a**2 - 3))*x**3 - \ EX(1/(a**2 - 1))*x**2*y + EX(a/(a**4 - 2*a**2 + 1))*x**2 - \ EX(1/(a**2 - 1))*x + EX(atanh(a)) p = x + x**2 + 5 assert rs_atanh(p, x, 10).compose(x, 10) == EX(Rational(-733442653682135, 5079158784) \ + atanh(5)) def test_sinh(): R, x, y = ring('x, y', QQ) assert rs_sinh(x, x, 9)/x**5 == Rational(1, 5040)*x**2 + Rational(1, 120) + Rational(1, 6)*x**(-2) + x**(-4) assert rs_sinh(x*y + x**2*y**3, x, 9) == x**8*y**11/12 + \ x**8*y**9/720 + x**7*y**9/12 + x**7*y**7/5040 + x**6*y**9/6 + \ x**6*y**7/24 + x**5*y**7/2 + x**5*y**5/120 + x**4*y**5/2 + \ x**3*y**3/6 + x**2*y**3 + x*y def test_cosh(): R, x, y = ring('x, y', QQ) assert rs_cosh(x, x, 9)/x**5 == Rational(1, 40320)*x**3 + Rational(1, 720)*x + Rational(1, 24)*x**(-1) + \ S.Half*x**(-3) + x**(-5) assert rs_cosh(x*y + x**2*y**3, x, 9) == x**8*y**12/24 + \ x**8*y**10/48 + x**8*y**8/40320 + x**7*y**10/6 + \ x**7*y**8/120 + x**6*y**8/4 + x**6*y**6/720 + x**5*y**6/6 + \ x**4*y**6/2 + x**4*y**4/24 + x**3*y**4 + x**2*y**2/2 + 1 def test_tanh(): R, x, y = ring('x, y', QQ) assert rs_tanh(x, x, 9)/x**5 == Rational(-17, 315)*x**2 + Rational(2, 15) - Rational(1, 3)*x**(-2) + x**(-4) assert rs_tanh(x*y + x**2*y**3, x, 9) == 4*x**8*y**11/3 - \ 17*x**8*y**9/45 + 4*x**7*y**9/3 - 17*x**7*y**7/315 - x**6*y**9/3 + \ 2*x**6*y**7/3 - x**5*y**7 + 2*x**5*y**5/15 - x**4*y**5 - \ x**3*y**3/3 + x**2*y**3 + x*y # Constant term in series a = symbols('a') R, x, y = ring('x, y', EX) assert rs_tanh(x + a, x, 5) == EX(tanh(a)**5 - 5*tanh(a)**3/3 + 2*tanh(a)/3)*x**4 + EX(-tanh(a)**4 + 4*tanh(a)**2/3 - QQ(1, 3))*x**3 + \ EX(tanh(a)**3 - tanh(a))*x**2 + EX(-tanh(a)**2 + 1)*x + EX(tanh(a)) p = rs_tanh(x + x**2*y + a, x, 4) assert (p.compose(x, 10)).compose(y, 5) == EX(-1000*tanh(a)**4 + \ 10100*tanh(a)**3 + 2470*tanh(a)**2/3 - 10099*tanh(a) + QQ(530, 3)) def test_RR(): rs_funcs = [rs_sin, rs_cos, rs_tan, rs_cot, rs_atan, rs_tanh] sympy_funcs = [sin, cos, tan, cot, atan, tanh] R, x, y = ring('x, y', RR) a = symbols('a') for rs_func, sympy_func in zip(rs_funcs, sympy_funcs): p = rs_func(2 + x, x, 5).compose(x, 5) q = sympy_func(2 + a).series(a, 0, 5).removeO() is_close(p.as_expr(), q.subs(a, 5).n()) p = rs_nth_root(2 + x, 5, x, 5).compose(x, 5) q = ((2 + a)**QQ(1, 5)).series(a, 0, 5).removeO() is_close(p.as_expr(), q.subs(a, 5).n()) def test_is_regular(): R, x, y = ring('x, y', QQ) p = 1 + 2*x + x**2 + 3*x**3 assert not rs_is_puiseux(p, x) p = x + x**QQ(1,5)*y assert rs_is_puiseux(p, x) assert not rs_is_puiseux(p, y) p = x + x**2*y**QQ(1,5)*y assert not rs_is_puiseux(p, x) def test_puiseux(): R, x, y = ring('x, y', QQ) p = x**QQ(2,5) + x**QQ(2,3) + x r = rs_series_inversion(p, x, 1) r1 = -x**QQ(14,15) + x**QQ(4,5) - 3*x**QQ(11,15) + x**QQ(2,3) + \ 2*x**QQ(7,15) - x**QQ(2,5) - x**QQ(1,5) + x**QQ(2,15) - x**QQ(-2,15) \ + x**QQ(-2,5) assert r == r1 r = rs_nth_root(1 + p, 3, x, 1) assert r == -x**QQ(4,5)/9 + x**QQ(2,3)/3 + x**QQ(2,5)/3 + 1 r = rs_log(1 + p, x, 1) assert r == -x**QQ(4,5)/2 + x**QQ(2,3) + x**QQ(2,5) r = rs_LambertW(p, x, 1) assert r == -x**QQ(4,5) + x**QQ(2,3) + x**QQ(2,5) p1 = x + x**QQ(1,5)*y r = rs_exp(p1, x, 1) assert r == x**QQ(4,5)*y**4/24 + x**QQ(3,5)*y**3/6 + x**QQ(2,5)*y**2/2 + \ x**QQ(1,5)*y + 1 r = rs_atan(p, x, 2) assert r == -x**QQ(9,5) - x**QQ(26,15) - x**QQ(22,15) - x**QQ(6,5)/3 + \ x + x**QQ(2,3) + x**QQ(2,5) r = rs_atan(p1, x, 2) assert r == x**QQ(9,5)*y**9/9 + x**QQ(9,5)*y**4 - x**QQ(7,5)*y**7/7 - \ x**QQ(7,5)*y**2 + x*y**5/5 + x - x**QQ(3,5)*y**3/3 + x**QQ(1,5)*y r = rs_asin(p, x, 2) assert r == x**QQ(9,5)/2 + x**QQ(26,15)/2 + x**QQ(22,15)/2 + \ x**QQ(6,5)/6 + x + x**QQ(2,3) + x**QQ(2,5) r = rs_cot(p, x, 1) assert r == -x**QQ(14,15) + x**QQ(4,5) - 3*x**QQ(11,15) + \ 2*x**QQ(2,3)/3 + 2*x**QQ(7,15) - 4*x**QQ(2,5)/3 - x**QQ(1,5) + \ x**QQ(2,15) - x**QQ(-2,15) + x**QQ(-2,5) r = rs_cos_sin(p, x, 2) assert r[0] == x**QQ(28,15)/6 - x**QQ(5,3) + x**QQ(8,5)/24 - x**QQ(7,5) - \ x**QQ(4,3)/2 - x**QQ(16,15) - x**QQ(4,5)/2 + 1 assert r[1] == -x**QQ(9,5)/2 - x**QQ(26,15)/2 - x**QQ(22,15)/2 - \ x**QQ(6,5)/6 + x + x**QQ(2,3) + x**QQ(2,5) r = rs_atanh(p, x, 2) assert r == x**QQ(9,5) + x**QQ(26,15) + x**QQ(22,15) + x**QQ(6,5)/3 + x + \ x**QQ(2,3) + x**QQ(2,5) r = rs_sinh(p, x, 2) assert r == x**QQ(9,5)/2 + x**QQ(26,15)/2 + x**QQ(22,15)/2 + \ x**QQ(6,5)/6 + x + x**QQ(2,3) + x**QQ(2,5) r = rs_cosh(p, x, 2) assert r == x**QQ(28,15)/6 + x**QQ(5,3) + x**QQ(8,5)/24 + x**QQ(7,5) + \ x**QQ(4,3)/2 + x**QQ(16,15) + x**QQ(4,5)/2 + 1 r = rs_tanh(p, x, 2) assert r == -x**QQ(9,5) - x**QQ(26,15) - x**QQ(22,15) - x**QQ(6,5)/3 + \ x + x**QQ(2,3) + x**QQ(2,5) def test1(): R, x = ring('x', QQ) r = rs_sin(x, x, 15)*x**(-5) assert r == x**8/6227020800 - x**6/39916800 + x**4/362880 - x**2/5040 + \ QQ(1,120) - x**-2/6 + x**-4 p = rs_sin(x, x, 10) r = rs_nth_root(p, 2, x, 10) assert r == -67*x**QQ(17,2)/29030400 - x**QQ(13,2)/24192 + \ x**QQ(9,2)/1440 - x**QQ(5,2)/12 + x**QQ(1,2) p = rs_sin(x, x, 10) r = rs_nth_root(p, 7, x, 10) r = rs_pow(r, 5, x, 10) assert r == -97*x**QQ(61,7)/124467840 - x**QQ(47,7)/16464 + \ 11*x**QQ(33,7)/3528 - 5*x**QQ(19,7)/42 + x**QQ(5,7) r = rs_exp(x**QQ(1,2), x, 10) assert r == x**QQ(19,2)/121645100408832000 + x**9/6402373705728000 + \ x**QQ(17,2)/355687428096000 + x**8/20922789888000 + \ x**QQ(15,2)/1307674368000 + x**7/87178291200 + \ x**QQ(13,2)/6227020800 + x**6/479001600 + x**QQ(11,2)/39916800 + \ x**5/3628800 + x**QQ(9,2)/362880 + x**4/40320 + x**QQ(7,2)/5040 + \ x**3/720 + x**QQ(5,2)/120 + x**2/24 + x**QQ(3,2)/6 + x/2 + \ x**QQ(1,2) + 1 def test_puiseux2(): R, y = ring('y', QQ) S, x = ring('x', R) p = x + x**QQ(1,5)*y r = rs_atan(p, x, 3) assert r == (y**13/13 + y**8 + 2*y**3)*x**QQ(13,5) - (y**11/11 + y**6 + y)*x**QQ(11,5) + (y**9/9 + y**4)*x**QQ(9,5) - (y**7/7 + y**2)*x**QQ(7,5) + (y**5/5 + 1)*x - y**3*x**QQ(3,5)/3 + y*x**QQ(1,5) @slow def test_rs_series(): x, a, b, c = symbols('x, a, b, c') assert rs_series(a, a, 5).as_expr() == a assert rs_series(sin(a), a, 5).as_expr() == (sin(a).series(a, 0, 5)).removeO() assert rs_series(sin(a) + cos(a), a, 5).as_expr() == ((sin(a) + cos(a)).series(a, 0, 5)).removeO() assert rs_series(sin(a)*cos(a), a, 5).as_expr() == ((sin(a)* cos(a)).series(a, 0, 5)).removeO() p = (sin(a) - a)*(cos(a**2) + a**4/2) assert expand(rs_series(p, a, 10).as_expr()) == expand(p.series(a, 0, 10).removeO()) p = sin(a**2/2 + a/3) + cos(a/5)*sin(a/2)**3 assert expand(rs_series(p, a, 5).as_expr()) == expand(p.series(a, 0, 5).removeO()) p = sin(x**2 + a)*(cos(x**3 - 1) - a - a**2) assert expand(rs_series(p, a, 5).as_expr()) == expand(p.series(a, 0, 5).removeO()) p = sin(a**2 - a/3 + 2)**5*exp(a**3 - a/2) assert expand(rs_series(p, a, 10).as_expr()) == expand(p.series(a, 0, 10).removeO()) p = sin(a + b + c) assert expand(rs_series(p, a, 5).as_expr()) == expand(p.series(a, 0, 5).removeO()) p = tan(sin(a**2 + 4) + b + c) assert expand(rs_series(p, a, 6).as_expr()) == expand(p.series(a, 0, 6).removeO()) p = a**QQ(2,5) + a**QQ(2,3) + a r = rs_series(tan(p), a, 2) assert r.as_expr() == a**QQ(9,5) + a**QQ(26,15) + a**QQ(22,15) + a**QQ(6,5)/3 + \ a + a**QQ(2,3) + a**QQ(2,5) r = rs_series(exp(p), a, 1) assert r.as_expr() == a**QQ(4,5)/2 + a**QQ(2,3) + a**QQ(2,5) + 1 r = rs_series(sin(p), a, 2) assert r.as_expr() == -a**QQ(9,5)/2 - a**QQ(26,15)/2 - a**QQ(22,15)/2 - \ a**QQ(6,5)/6 + a + a**QQ(2,3) + a**QQ(2,5) r = rs_series(cos(p), a, 2) assert r.as_expr() == a**QQ(28,15)/6 - a**QQ(5,3) + a**QQ(8,5)/24 - a**QQ(7,5) - \ a**QQ(4,3)/2 - a**QQ(16,15) - a**QQ(4,5)/2 + 1 assert rs_series(sin(a)/7, a, 5).as_expr() == (sin(a)/7).series(a, 0, 5).removeO() assert rs_series(log(1 + x), x, 5).as_expr() == -x**4/4 + x**3/3 - \ x**2/2 + x assert rs_series(log(1 + 4*x), x, 5).as_expr() == -64*x**4 + 64*x**3/3 - \ 8*x**2 + 4*x assert rs_series(log(1 + x + x**2), x, 10).as_expr() == -2*x**9/9 + \ x**8/8 + x**7/7 - x**6/3 + x**5/5 + x**4/4 - 2*x**3/3 + \ x**2/2 + x assert rs_series(log(1 + x*a**2), x, 7).as_expr() == -x**6*a**12/6 + \ x**5*a**10/5 - x**4*a**8/4 + x**3*a**6/3 - \ x**2*a**4/2 + x*a**2
d580661094ed3d15a3e25dfd1cc9050fa7df914f21de922cee5cfe93ff571989
"""Tests for dense recursive polynomials' arithmetics. """ from sympy.polys.densebasic import ( dup_normal, dmp_normal, ) from sympy.polys.densearith import ( dup_add_term, dmp_add_term, dup_sub_term, dmp_sub_term, dup_mul_term, dmp_mul_term, dup_add_ground, dmp_add_ground, dup_sub_ground, dmp_sub_ground, dup_mul_ground, dmp_mul_ground, dup_quo_ground, dmp_quo_ground, dup_exquo_ground, dmp_exquo_ground, dup_lshift, dup_rshift, dup_abs, dmp_abs, dup_neg, dmp_neg, dup_add, dmp_add, dup_sub, dmp_sub, dup_mul, dmp_mul, dup_sqr, dmp_sqr, dup_pow, dmp_pow, dup_add_mul, dmp_add_mul, dup_sub_mul, dmp_sub_mul, dup_pdiv, dup_prem, dup_pquo, dup_pexquo, dmp_pdiv, dmp_prem, dmp_pquo, dmp_pexquo, dup_rr_div, dmp_rr_div, dup_ff_div, dmp_ff_div, dup_div, dup_rem, dup_quo, dup_exquo, dmp_div, dmp_rem, dmp_quo, dmp_exquo, dup_max_norm, dmp_max_norm, dup_l1_norm, dmp_l1_norm, dup_l2_norm_squared, dmp_l2_norm_squared, dup_expand, dmp_expand, ) from sympy.polys.polyerrors import ( ExactQuotientFailed, ) from sympy.polys.specialpolys import f_polys from sympy.polys.domains import FF, ZZ, QQ from sympy.testing.pytest import raises f_0, f_1, f_2, f_3, f_4, f_5, f_6 = [ f.to_dense() for f in f_polys() ] F_0 = dmp_mul_ground(dmp_normal(f_0, 2, QQ), QQ(1, 7), 2, QQ) def test_dup_add_term(): f = dup_normal([], ZZ) assert dup_add_term(f, ZZ(0), 0, ZZ) == dup_normal([], ZZ) assert dup_add_term(f, ZZ(1), 0, ZZ) == dup_normal([1], ZZ) assert dup_add_term(f, ZZ(1), 1, ZZ) == dup_normal([1, 0], ZZ) assert dup_add_term(f, ZZ(1), 2, ZZ) == dup_normal([1, 0, 0], ZZ) f = dup_normal([1, 1, 1], ZZ) assert dup_add_term(f, ZZ(1), 0, ZZ) == dup_normal([1, 1, 2], ZZ) assert dup_add_term(f, ZZ(1), 1, ZZ) == dup_normal([1, 2, 1], ZZ) assert dup_add_term(f, ZZ(1), 2, ZZ) == dup_normal([2, 1, 1], ZZ) assert dup_add_term(f, ZZ(1), 3, ZZ) == dup_normal([1, 1, 1, 1], ZZ) assert dup_add_term(f, ZZ(1), 4, ZZ) == dup_normal([1, 0, 1, 1, 1], ZZ) assert dup_add_term(f, ZZ(1), 5, ZZ) == dup_normal([1, 0, 0, 1, 1, 1], ZZ) assert dup_add_term( f, ZZ(1), 6, ZZ) == dup_normal([1, 0, 0, 0, 1, 1, 1], ZZ) assert dup_add_term(f, ZZ(-1), 2, ZZ) == dup_normal([1, 1], ZZ) def test_dmp_add_term(): assert dmp_add_term([ZZ(1), ZZ(1), ZZ(1)], ZZ(1), 2, 0, ZZ) == \ dup_add_term([ZZ(1), ZZ(1), ZZ(1)], ZZ(1), 2, ZZ) assert dmp_add_term(f_0, [[]], 3, 2, ZZ) == f_0 assert dmp_add_term(F_0, [[]], 3, 2, QQ) == F_0 def test_dup_sub_term(): f = dup_normal([], ZZ) assert dup_sub_term(f, ZZ(0), 0, ZZ) == dup_normal([], ZZ) assert dup_sub_term(f, ZZ(1), 0, ZZ) == dup_normal([-1], ZZ) assert dup_sub_term(f, ZZ(1), 1, ZZ) == dup_normal([-1, 0], ZZ) assert dup_sub_term(f, ZZ(1), 2, ZZ) == dup_normal([-1, 0, 0], ZZ) f = dup_normal([1, 1, 1], ZZ) assert dup_sub_term(f, ZZ(2), 0, ZZ) == dup_normal([ 1, 1, -1], ZZ) assert dup_sub_term(f, ZZ(2), 1, ZZ) == dup_normal([ 1, -1, 1], ZZ) assert dup_sub_term(f, ZZ(2), 2, ZZ) == dup_normal([-1, 1, 1], ZZ) assert dup_sub_term(f, ZZ(1), 3, ZZ) == dup_normal([-1, 1, 1, 1], ZZ) assert dup_sub_term(f, ZZ(1), 4, ZZ) == dup_normal([-1, 0, 1, 1, 1], ZZ) assert dup_sub_term(f, ZZ(1), 5, ZZ) == dup_normal([-1, 0, 0, 1, 1, 1], ZZ) assert dup_sub_term( f, ZZ(1), 6, ZZ) == dup_normal([-1, 0, 0, 0, 1, 1, 1], ZZ) assert dup_sub_term(f, ZZ(1), 2, ZZ) == dup_normal([1, 1], ZZ) def test_dmp_sub_term(): assert dmp_sub_term([ZZ(1), ZZ(1), ZZ(1)], ZZ(1), 2, 0, ZZ) == \ dup_sub_term([ZZ(1), ZZ(1), ZZ(1)], ZZ(1), 2, ZZ) assert dmp_sub_term(f_0, [[]], 3, 2, ZZ) == f_0 assert dmp_sub_term(F_0, [[]], 3, 2, QQ) == F_0 def test_dup_mul_term(): f = dup_normal([], ZZ) assert dup_mul_term(f, ZZ(2), 3, ZZ) == dup_normal([], ZZ) f = dup_normal([1, 1], ZZ) assert dup_mul_term(f, ZZ(0), 3, ZZ) == dup_normal([], ZZ) f = dup_normal([1, 2, 3], ZZ) assert dup_mul_term(f, ZZ(2), 0, ZZ) == dup_normal([2, 4, 6], ZZ) assert dup_mul_term(f, ZZ(2), 1, ZZ) == dup_normal([2, 4, 6, 0], ZZ) assert dup_mul_term(f, ZZ(2), 2, ZZ) == dup_normal([2, 4, 6, 0, 0], ZZ) assert dup_mul_term(f, ZZ(2), 3, ZZ) == dup_normal([2, 4, 6, 0, 0, 0], ZZ) def test_dmp_mul_term(): assert dmp_mul_term([ZZ(1), ZZ(2), ZZ(3)], ZZ(2), 1, 0, ZZ) == \ dup_mul_term([ZZ(1), ZZ(2), ZZ(3)], ZZ(2), 1, ZZ) assert dmp_mul_term([[]], [ZZ(2)], 3, 1, ZZ) == [[]] assert dmp_mul_term([[ZZ(1)]], [], 3, 1, ZZ) == [[]] assert dmp_mul_term([[ZZ(1), ZZ(2)], [ZZ(3)]], [ZZ(2)], 2, 1, ZZ) == \ [[ZZ(2), ZZ(4)], [ZZ(6)], [], []] assert dmp_mul_term([[]], [QQ(2, 3)], 3, 1, QQ) == [[]] assert dmp_mul_term([[QQ(1, 2)]], [], 3, 1, QQ) == [[]] assert dmp_mul_term([[QQ(1, 5), QQ(2, 5)], [QQ(3, 5)]], [QQ(2, 3)], 2, 1, QQ) == \ [[QQ(2, 15), QQ(4, 15)], [QQ(6, 15)], [], []] def test_dup_add_ground(): f = ZZ.map([1, 2, 3, 4]) g = ZZ.map([1, 2, 3, 8]) assert dup_add_ground(f, ZZ(4), ZZ) == g def test_dmp_add_ground(): f = ZZ.map([[1], [2], [3], [4]]) g = ZZ.map([[1], [2], [3], [8]]) assert dmp_add_ground(f, ZZ(4), 1, ZZ) == g def test_dup_sub_ground(): f = ZZ.map([1, 2, 3, 4]) g = ZZ.map([1, 2, 3, 0]) assert dup_sub_ground(f, ZZ(4), ZZ) == g def test_dmp_sub_ground(): f = ZZ.map([[1], [2], [3], [4]]) g = ZZ.map([[1], [2], [3], []]) assert dmp_sub_ground(f, ZZ(4), 1, ZZ) == g def test_dup_mul_ground(): f = dup_normal([], ZZ) assert dup_mul_ground(f, ZZ(2), ZZ) == dup_normal([], ZZ) f = dup_normal([1, 2, 3], ZZ) assert dup_mul_ground(f, ZZ(0), ZZ) == dup_normal([], ZZ) assert dup_mul_ground(f, ZZ(2), ZZ) == dup_normal([2, 4, 6], ZZ) def test_dmp_mul_ground(): assert dmp_mul_ground(f_0, ZZ(2), 2, ZZ) == [ [[ZZ(2), ZZ(4), ZZ(6)], [ZZ(4)]], [[ZZ(6)]], [[ZZ(8), ZZ(10), ZZ(12)], [ZZ(2), ZZ(4), ZZ(2)], [ZZ(2)]] ] assert dmp_mul_ground(F_0, QQ(1, 2), 2, QQ) == [ [[QQ(1, 14), QQ(2, 14), QQ(3, 14)], [QQ(2, 14)]], [[QQ(3, 14)]], [[QQ(4, 14), QQ(5, 14), QQ(6, 14)], [QQ(1, 14), QQ(2, 14), QQ(1, 14)], [QQ(1, 14)]] ] def test_dup_quo_ground(): raises(ZeroDivisionError, lambda: dup_quo_ground(dup_normal([1, 2, 3], ZZ), ZZ(0), ZZ)) f = dup_normal([], ZZ) assert dup_quo_ground(f, ZZ(3), ZZ) == dup_normal([], ZZ) f = dup_normal([6, 2, 8], ZZ) assert dup_quo_ground(f, ZZ(1), ZZ) == f assert dup_quo_ground(f, ZZ(2), ZZ) == dup_normal([3, 1, 4], ZZ) assert dup_quo_ground(f, ZZ(3), ZZ) == dup_normal([2, 0, 2], ZZ) f = dup_normal([6, 2, 8], QQ) assert dup_quo_ground(f, QQ(1), QQ) == f assert dup_quo_ground(f, QQ(2), QQ) == [QQ(3), QQ(1), QQ(4)] assert dup_quo_ground(f, QQ(7), QQ) == [QQ(6, 7), QQ(2, 7), QQ(8, 7)] def test_dup_exquo_ground(): raises(ZeroDivisionError, lambda: dup_exquo_ground(dup_normal([1, 2, 3], ZZ), ZZ(0), ZZ)) raises(ExactQuotientFailed, lambda: dup_exquo_ground(dup_normal([1, 2, 3], ZZ), ZZ(3), ZZ)) f = dup_normal([], ZZ) assert dup_exquo_ground(f, ZZ(3), ZZ) == dup_normal([], ZZ) f = dup_normal([6, 2, 8], ZZ) assert dup_exquo_ground(f, ZZ(1), ZZ) == f assert dup_exquo_ground(f, ZZ(2), ZZ) == dup_normal([3, 1, 4], ZZ) f = dup_normal([6, 2, 8], QQ) assert dup_exquo_ground(f, QQ(1), QQ) == f assert dup_exquo_ground(f, QQ(2), QQ) == [QQ(3), QQ(1), QQ(4)] assert dup_exquo_ground(f, QQ(7), QQ) == [QQ(6, 7), QQ(2, 7), QQ(8, 7)] def test_dmp_quo_ground(): f = dmp_normal([[6], [2], [8]], 1, ZZ) assert dmp_quo_ground(f, ZZ(1), 1, ZZ) == f assert dmp_quo_ground( f, ZZ(2), 1, ZZ) == dmp_normal([[3], [1], [4]], 1, ZZ) assert dmp_normal(dmp_quo_ground( f, ZZ(3), 1, ZZ), 1, ZZ) == dmp_normal([[2], [], [2]], 1, ZZ) def test_dmp_exquo_ground(): f = dmp_normal([[6], [2], [8]], 1, ZZ) assert dmp_exquo_ground(f, ZZ(1), 1, ZZ) == f assert dmp_exquo_ground( f, ZZ(2), 1, ZZ) == dmp_normal([[3], [1], [4]], 1, ZZ) def test_dup_lshift(): assert dup_lshift([], 3, ZZ) == [] assert dup_lshift([1], 3, ZZ) == [1, 0, 0, 0] def test_dup_rshift(): assert dup_rshift([], 3, ZZ) == [] assert dup_rshift([1, 0, 0, 0], 3, ZZ) == [1] def test_dup_abs(): assert dup_abs([], ZZ) == [] assert dup_abs([ZZ( 1)], ZZ) == [ZZ(1)] assert dup_abs([ZZ(-7)], ZZ) == [ZZ(7)] assert dup_abs([ZZ(-1), ZZ(2), ZZ(3)], ZZ) == [ZZ(1), ZZ(2), ZZ(3)] assert dup_abs([], QQ) == [] assert dup_abs([QQ( 1, 2)], QQ) == [QQ(1, 2)] assert dup_abs([QQ(-7, 3)], QQ) == [QQ(7, 3)] assert dup_abs( [QQ(-1, 7), QQ(2, 7), QQ(3, 7)], QQ) == [QQ(1, 7), QQ(2, 7), QQ(3, 7)] def test_dmp_abs(): assert dmp_abs([ZZ(-1)], 0, ZZ) == [ZZ(1)] assert dmp_abs([QQ(-1, 2)], 0, QQ) == [QQ(1, 2)] assert dmp_abs([[[]]], 2, ZZ) == [[[]]] assert dmp_abs([[[ZZ(1)]]], 2, ZZ) == [[[ZZ(1)]]] assert dmp_abs([[[ZZ(-7)]]], 2, ZZ) == [[[ZZ(7)]]] assert dmp_abs([[[]]], 2, QQ) == [[[]]] assert dmp_abs([[[QQ(1, 2)]]], 2, QQ) == [[[QQ(1, 2)]]] assert dmp_abs([[[QQ(-7, 9)]]], 2, QQ) == [[[QQ(7, 9)]]] def test_dup_neg(): assert dup_neg([], ZZ) == [] assert dup_neg([ZZ(1)], ZZ) == [ZZ(-1)] assert dup_neg([ZZ(-7)], ZZ) == [ZZ(7)] assert dup_neg([ZZ(-1), ZZ(2), ZZ(3)], ZZ) == [ZZ(1), ZZ(-2), ZZ(-3)] assert dup_neg([], QQ) == [] assert dup_neg([QQ(1, 2)], QQ) == [QQ(-1, 2)] assert dup_neg([QQ(-7, 9)], QQ) == [QQ(7, 9)] assert dup_neg([QQ( -1, 7), QQ(2, 7), QQ(3, 7)], QQ) == [QQ(1, 7), QQ(-2, 7), QQ(-3, 7)] def test_dmp_neg(): assert dmp_neg([ZZ(-1)], 0, ZZ) == [ZZ(1)] assert dmp_neg([QQ(-1, 2)], 0, QQ) == [QQ(1, 2)] assert dmp_neg([[[]]], 2, ZZ) == [[[]]] assert dmp_neg([[[ZZ(1)]]], 2, ZZ) == [[[ZZ(-1)]]] assert dmp_neg([[[ZZ(-7)]]], 2, ZZ) == [[[ZZ(7)]]] assert dmp_neg([[[]]], 2, QQ) == [[[]]] assert dmp_neg([[[QQ(1, 9)]]], 2, QQ) == [[[QQ(-1, 9)]]] assert dmp_neg([[[QQ(-7, 9)]]], 2, QQ) == [[[QQ(7, 9)]]] def test_dup_add(): assert dup_add([], [], ZZ) == [] assert dup_add([ZZ(1)], [], ZZ) == [ZZ(1)] assert dup_add([], [ZZ(1)], ZZ) == [ZZ(1)] assert dup_add([ZZ(1)], [ZZ(1)], ZZ) == [ZZ(2)] assert dup_add([ZZ(1)], [ZZ(2)], ZZ) == [ZZ(3)] assert dup_add([ZZ(1), ZZ(2)], [ZZ(1)], ZZ) == [ZZ(1), ZZ(3)] assert dup_add([ZZ(1)], [ZZ(1), ZZ(2)], ZZ) == [ZZ(1), ZZ(3)] assert dup_add([ZZ(1), ZZ( 2), ZZ(3)], [ZZ(8), ZZ(9), ZZ(10)], ZZ) == [ZZ(9), ZZ(11), ZZ(13)] assert dup_add([], [], QQ) == [] assert dup_add([QQ(1, 2)], [], QQ) == [QQ(1, 2)] assert dup_add([], [QQ(1, 2)], QQ) == [QQ(1, 2)] assert dup_add([QQ(1, 4)], [QQ(1, 4)], QQ) == [QQ(1, 2)] assert dup_add([QQ(1, 4)], [QQ(1, 2)], QQ) == [QQ(3, 4)] assert dup_add([QQ(1, 2), QQ(2, 3)], [QQ(1)], QQ) == [QQ(1, 2), QQ(5, 3)] assert dup_add([QQ(1)], [QQ(1, 2), QQ(2, 3)], QQ) == [QQ(1, 2), QQ(5, 3)] assert dup_add([QQ(1, 7), QQ(2, 7), QQ(3, 7)], [QQ( 8, 7), QQ(9, 7), QQ(10, 7)], QQ) == [QQ(9, 7), QQ(11, 7), QQ(13, 7)] def test_dmp_add(): assert dmp_add([ZZ(1), ZZ(2)], [ZZ(1)], 0, ZZ) == \ dup_add([ZZ(1), ZZ(2)], [ZZ(1)], ZZ) assert dmp_add([QQ(1, 2), QQ(2, 3)], [QQ(1)], 0, QQ) == \ dup_add([QQ(1, 2), QQ(2, 3)], [QQ(1)], QQ) assert dmp_add([[[]]], [[[]]], 2, ZZ) == [[[]]] assert dmp_add([[[ZZ(1)]]], [[[]]], 2, ZZ) == [[[ZZ(1)]]] assert dmp_add([[[]]], [[[ZZ(1)]]], 2, ZZ) == [[[ZZ(1)]]] assert dmp_add([[[ZZ(2)]]], [[[ZZ(1)]]], 2, ZZ) == [[[ZZ(3)]]] assert dmp_add([[[ZZ(1)]]], [[[ZZ(2)]]], 2, ZZ) == [[[ZZ(3)]]] assert dmp_add([[[]]], [[[]]], 2, QQ) == [[[]]] assert dmp_add([[[QQ(1, 2)]]], [[[]]], 2, QQ) == [[[QQ(1, 2)]]] assert dmp_add([[[]]], [[[QQ(1, 2)]]], 2, QQ) == [[[QQ(1, 2)]]] assert dmp_add([[[QQ(2, 7)]]], [[[QQ(1, 7)]]], 2, QQ) == [[[QQ(3, 7)]]] assert dmp_add([[[QQ(1, 7)]]], [[[QQ(2, 7)]]], 2, QQ) == [[[QQ(3, 7)]]] def test_dup_sub(): assert dup_sub([], [], ZZ) == [] assert dup_sub([ZZ(1)], [], ZZ) == [ZZ(1)] assert dup_sub([], [ZZ(1)], ZZ) == [ZZ(-1)] assert dup_sub([ZZ(1)], [ZZ(1)], ZZ) == [] assert dup_sub([ZZ(1)], [ZZ(2)], ZZ) == [ZZ(-1)] assert dup_sub([ZZ(1), ZZ(2)], [ZZ(1)], ZZ) == [ZZ(1), ZZ(1)] assert dup_sub([ZZ(1)], [ZZ(1), ZZ(2)], ZZ) == [ZZ(-1), ZZ(-1)] assert dup_sub([ZZ(3), ZZ( 2), ZZ(1)], [ZZ(8), ZZ(9), ZZ(10)], ZZ) == [ZZ(-5), ZZ(-7), ZZ(-9)] assert dup_sub([], [], QQ) == [] assert dup_sub([QQ(1, 2)], [], QQ) == [QQ(1, 2)] assert dup_sub([], [QQ(1, 2)], QQ) == [QQ(-1, 2)] assert dup_sub([QQ(1, 3)], [QQ(1, 3)], QQ) == [] assert dup_sub([QQ(1, 3)], [QQ(2, 3)], QQ) == [QQ(-1, 3)] assert dup_sub([QQ(1, 7), QQ(2, 7)], [QQ(1)], QQ) == [QQ(1, 7), QQ(-5, 7)] assert dup_sub([QQ(1)], [QQ(1, 7), QQ(2, 7)], QQ) == [QQ(-1, 7), QQ(5, 7)] assert dup_sub([QQ(3, 7), QQ(2, 7), QQ(1, 7)], [QQ( 8, 7), QQ(9, 7), QQ(10, 7)], QQ) == [QQ(-5, 7), QQ(-7, 7), QQ(-9, 7)] def test_dmp_sub(): assert dmp_sub([ZZ(1), ZZ(2)], [ZZ(1)], 0, ZZ) == \ dup_sub([ZZ(1), ZZ(2)], [ZZ(1)], ZZ) assert dmp_sub([QQ(1, 2), QQ(2, 3)], [QQ(1)], 0, QQ) == \ dup_sub([QQ(1, 2), QQ(2, 3)], [QQ(1)], QQ) assert dmp_sub([[[]]], [[[]]], 2, ZZ) == [[[]]] assert dmp_sub([[[ZZ(1)]]], [[[]]], 2, ZZ) == [[[ZZ(1)]]] assert dmp_sub([[[]]], [[[ZZ(1)]]], 2, ZZ) == [[[ZZ(-1)]]] assert dmp_sub([[[ZZ(2)]]], [[[ZZ(1)]]], 2, ZZ) == [[[ZZ(1)]]] assert dmp_sub([[[ZZ(1)]]], [[[ZZ(2)]]], 2, ZZ) == [[[ZZ(-1)]]] assert dmp_sub([[[]]], [[[]]], 2, QQ) == [[[]]] assert dmp_sub([[[QQ(1, 2)]]], [[[]]], 2, QQ) == [[[QQ(1, 2)]]] assert dmp_sub([[[]]], [[[QQ(1, 2)]]], 2, QQ) == [[[QQ(-1, 2)]]] assert dmp_sub([[[QQ(2, 7)]]], [[[QQ(1, 7)]]], 2, QQ) == [[[QQ(1, 7)]]] assert dmp_sub([[[QQ(1, 7)]]], [[[QQ(2, 7)]]], 2, QQ) == [[[QQ(-1, 7)]]] def test_dup_add_mul(): assert dup_add_mul([ZZ(1), ZZ(2), ZZ(3)], [ZZ(3), ZZ(2), ZZ(1)], [ZZ(1), ZZ(2)], ZZ) == [ZZ(3), ZZ(9), ZZ(7), ZZ(5)] assert dmp_add_mul([[ZZ(1), ZZ(2)], [ZZ(3)]], [[ZZ(3)], [ZZ(2), ZZ(1)]], [[ZZ(1)], [ZZ(2)]], 1, ZZ) == [[ZZ(3)], [ZZ(3), ZZ(9)], [ZZ(4), ZZ(5)]] def test_dup_sub_mul(): assert dup_sub_mul([ZZ(1), ZZ(2), ZZ(3)], [ZZ(3), ZZ(2), ZZ(1)], [ZZ(1), ZZ(2)], ZZ) == [ZZ(-3), ZZ(-7), ZZ(-3), ZZ(1)] assert dmp_sub_mul([[ZZ(1), ZZ(2)], [ZZ(3)]], [[ZZ(3)], [ZZ(2), ZZ(1)]], [[ZZ(1)], [ZZ(2)]], 1, ZZ) == [[ZZ(-3)], [ZZ(-1), ZZ(-5)], [ZZ(-4), ZZ(1)]] def test_dup_mul(): assert dup_mul([], [], ZZ) == [] assert dup_mul([], [ZZ(1)], ZZ) == [] assert dup_mul([ZZ(1)], [], ZZ) == [] assert dup_mul([ZZ(1)], [ZZ(1)], ZZ) == [ZZ(1)] assert dup_mul([ZZ(5)], [ZZ(7)], ZZ) == [ZZ(35)] assert dup_mul([], [], QQ) == [] assert dup_mul([], [QQ(1, 2)], QQ) == [] assert dup_mul([QQ(1, 2)], [], QQ) == [] assert dup_mul([QQ(1, 2)], [QQ(4, 7)], QQ) == [QQ(2, 7)] assert dup_mul([QQ(5, 7)], [QQ(3, 7)], QQ) == [QQ(15, 49)] f = dup_normal([3, 0, 0, 6, 1, 2], ZZ) g = dup_normal([4, 0, 1, 0], ZZ) h = dup_normal([12, 0, 3, 24, 4, 14, 1, 2, 0], ZZ) assert dup_mul(f, g, ZZ) == h assert dup_mul(g, f, ZZ) == h f = dup_normal([2, 0, 0, 1, 7], ZZ) h = dup_normal([4, 0, 0, 4, 28, 0, 1, 14, 49], ZZ) assert dup_mul(f, f, ZZ) == h K = FF(6) assert dup_mul([K(2), K(1)], [K(3), K(4)], K) == [K(5), K(4)] p1 = dup_normal([79, -1, 78, -94, -10, 11, 32, -19, 78, 2, -89, 30, 73, 42, 85, 77, 83, -30, -34, -2, 95, -81, 37, -49, -46, -58, -16, 37, 35, -11, -57, -15, -31, 67, -20, 27, 76, 2, 70, 67, -65, 65, -26, -93, -44, -12, -92, 57, -90, -57, -11, -67, -98, -69, 97, -41, 89, 33, 89, -50, 81, -31, 60, -27, 43, 29, -77, 44, 21, -91, 32, -57, 33, 3, 53, -51, -38, -99, -84, 23, -50, 66, -100, 1, -75, -25, 27, -60, 98, -51, -87, 6, 8, 78, -28, -95, -88, 12, -35, 26, -9, 16, -92, 55, -7, -86, 68, -39, -46, 84, 94, 45, 60, 92, 68, -75, -74, -19, 8, 75, 78, 91, 57, 34, 14, -3, -49, 65, 78, -18, 6, -29, -80, -98, 17, 13, 58, 21, 20, 9, 37, 7, -30, -53, -20, 34, 67, -42, 89, -22, 73, 43, -6, 5, 51, -8, -15, -52, -22, -58, -72, -3, 43, -92, 82, 83, -2, -13, -23, -60, 16, -94, -8, -28, -95, -72, 63, -90, 76, 6, -43, -100, -59, 76, 3, 3, 46, -85, 75, 62, -71, -76, 88, 97, -72, -1, 30, -64, 72, -48, 14, -78, 58, 63, -91, 24, -87, -27, -80, -100, -44, 98, 70, 100, -29, -38, 11, 77, 100, 52, 86, 65, -5, -42, -81, -38, -42, 43, -2, -70, -63, -52], ZZ) p2 = dup_normal([65, -19, -47, 1, 90, 81, -15, -34, 25, -75, 9, -83, 50, -5, -44, 31, 1, 70, -7, 78, 74, 80, 85, 65, 21, 41, 66, 19, -40, 63, -21, -27, 32, 69, 83, 34, -35, 14, 81, 57, -75, 32, -67, -89, -100, -61, 46, 84, -78, -29, -50, -94, -24, -32, -68, -16, 100, -7, -72, -89, 35, 82, 58, 81, -92, 62, 5, -47, -39, -58, -72, -13, 84, 44, 55, -25, 48, -54, -31, -56, -11, -50, -84, 10, 67, 17, 13, -14, 61, 76, -64, -44, -40, -96, 11, -11, -94, 2, 6, 27, -6, 68, -54, 66, -74, -14, -1, -24, -73, 96, 89, -11, -89, 56, -53, 72, -43, 96, 25, 63, -31, 29, 68, 83, 91, -93, -19, -38, -40, 40, -12, -19, -79, 44, 100, -66, -29, -77, 62, 39, -8, 11, -97, 14, 87, 64, 21, -18, 13, 15, -59, -75, -99, -88, 57, 54, 56, -67, 6, -63, -59, -14, 28, 87, -20, -39, 84, -91, -2, 49, -75, 11, -24, -95, 36, 66, 5, 25, -72, -40, 86, 90, 37, -33, 57, -35, 29, -18, 4, -79, 64, -17, -27, 21, 29, -5, -44, -87, -24, 52, 78, 11, -23, -53, 36, 42, 21, -68, 94, -91, -51, -21, 51, -76, 72, 31, 24, -48, -80, -9, 37, -47, -6, -8, -63, -91, 79, -79, -100, 38, -20, 38, 100, 83, -90, 87, 63, -36, 82, -19, 18, -98, -38, 26, 98, -70, 79, 92, 12, 12, 70, 74, 36, 48, -13, 31, 31, -47, -71, -12, -64, 36, -42, 32, -86, 60, 83, 70, 55, 0, 1, 29, -35, 8, -82, 8, -73, -46, -50, 43, 48, -5, -86, -72, 44, -90, 19, 19, 5, -20, 97, -13, -66, -5, 5, -69, 64, -30, 41, 51, 36, 13, -99, -61, 94, -12, 74, 98, 68, 24, 46, -97, -87, -6, -27, 82, 62, -11, -77, 86, 66, -47, -49, -50, 13, 18, 89, -89, 46, -80, 13, 98, -35, -36, -25, 12, 20, 26, -52, 79, 27, 79, 100, 8, 62, -58, -28, 37], ZZ) res = dup_normal([5135, -1566, 1376, -7466, 4579, 11710, 8001, -7183, -3737, -7439, 345, -10084, 24522, -1201, 1070, -10245, 9582, 9264, 1903, 23312, 18953, 10037, -15268, -5450, 6442, -6243, -3777, 5110, 10936, -16649, -6022, 16255, 31300, 24818, 31922, 32760, 7854, 27080, 15766, 29596, 7139, 31945, -19810, 465, -38026, -3971, 9641, 465, -19375, 5524, -30112, -11960, -12813, 13535, 30670, 5925, -43725, -14089, 11503, -22782, 6371, 43881, 37465, -33529, -33590, -39798, -37854, -18466, -7908, -35825, -26020, -36923, -11332, -5699, 25166, -3147, 19885, 12962, -20659, -1642, 27723, -56331, -24580, -11010, -20206, 20087, -23772, -16038, 38580, 20901, -50731, 32037, -4299, 26508, 18038, -28357, 31846, -7405, -20172, -15894, 2096, 25110, -45786, 45918, -55333, -31928, -49428, -29824, -58796, -24609, -15408, 69, -35415, -18439, 10123, -20360, -65949, 33356, -20333, 26476, -32073, 33621, 930, 28803, -42791, 44716, 38164, 12302, -1739, 11421, 73385, -7613, 14297, 38155, -414, 77587, 24338, -21415, 29367, 42639, 13901, -288, 51027, -11827, 91260, 43407, 88521, -15186, 70572, -12049, 5090, -12208, -56374, 15520, -623, -7742, 50825, 11199, -14894, 40892, 59591, -31356, -28696, -57842, -87751, -33744, -28436, -28945, -40287, 37957, -35638, 33401, -61534, 14870, 40292, 70366, -10803, 102290, -71719, -85251, 7902, -22409, 75009, 99927, 35298, -1175, -762, -34744, -10587, -47574, -62629, -19581, -43659, -54369, -32250, -39545, 15225, -24454, 11241, -67308, -30148, 39929, 37639, 14383, -73475, -77636, -81048, -35992, 41601, -90143, 76937, -8112, 56588, 9124, -40094, -32340, 13253, 10898, -51639, 36390, 12086, -1885, 100714, -28561, -23784, -18735, 18916, 16286, 10742, -87360, -13697, 10689, -19477, -29770, 5060, 20189, -8297, 112407, 47071, 47743, 45519, -4109, 17468, -68831, 78325, -6481, -21641, -19459, 30919, 96115, 8607, 53341, 32105, -16211, 23538, 57259, -76272, -40583, 62093, 38511, -34255, -40665, -40604, -37606, -15274, 33156, -13885, 103636, 118678, -14101, -92682, -100791, 2634, 63791, 98266, 19286, -34590, -21067, -71130, 25380, -40839, -27614, -26060, 52358, -15537, 27138, -6749, 36269, -33306, 13207, -91084, -5540, -57116, 69548, 44169, -57742, -41234, -103327, -62904, -8566, 41149, -12866, 71188, 23980, 1838, 58230, 73950, 5594, 43113, -8159, -15925, 6911, 85598, -75016, -16214, -62726, -39016, 8618, -63882, -4299, 23182, 49959, 49342, -3238, -24913, -37138, 78361, 32451, 6337, -11438, -36241, -37737, 8169, -3077, -24829, 57953, 53016, -31511, -91168, 12599, -41849, 41576, 55275, -62539, 47814, -62319, 12300, -32076, -55137, -84881, -27546, 4312, -3433, -54382, 113288, -30157, 74469, 18219, 79880, -2124, 98911, 17655, -33499, -32861, 47242, -37393, 99765, 14831, -44483, 10800, -31617, -52710, 37406, 22105, 29704, -20050, 13778, 43683, 36628, 8494, 60964, -22644, 31550, -17693, 33805, -124879, -12302, 19343, 20400, -30937, -21574, -34037, -33380, 56539, -24993, -75513, -1527, 53563, 65407, -101, 53577, 37991, 18717, -23795, -8090, -47987, -94717, 41967, 5170, -14815, -94311, 17896, -17734, -57718, -774, -38410, 24830, 29682, 76480, 58802, -46416, -20348, -61353, -68225, -68306, 23822, -31598, 42972, 36327, 28968, -65638, -21638, 24354, -8356, 26777, 52982, -11783, -44051, -26467, -44721, -28435, -53265, -25574, -2669, 44155, 22946, -18454, -30718, -11252, 58420, 8711, 67447, 4425, 41749, 67543, 43162, 11793, -41907, 20477, -13080, 6559, -6104, -13244, 42853, 42935, 29793, 36730, -28087, 28657, 17946, 7503, 7204, 21491, -27450, -24241, -98156, -18082, -42613, -24928, 10775, -14842, -44127, 55910, 14777, 31151, -2194, 39206, -2100, -4211, 11827, -8918, -19471, 72567, 36447, -65590, -34861, -17147, -45303, 9025, -7333, -35473, 11101, 11638, 3441, 6626, -41800, 9416, 13679, 33508, 40502, -60542, 16358, 8392, -43242, -35864, -34127, -48721, 35878, 30598, 28630, 20279, -19983, -14638, -24455, -1851, -11344, 45150, 42051, 26034, -28889, -32382, -3527, -14532, 22564, -22346, 477, 11706, 28338, -25972, -9185, -22867, -12522, 32120, -4424, 11339, -33913, -7184, 5101, -23552, -17115, -31401, -6104, 21906, 25708, 8406, 6317, -7525, 5014, 20750, 20179, 22724, 11692, 13297, 2493, -253, -16841, -17339, -6753, -4808, 2976, -10881, -10228, -13816, -12686, 1385, 2316, 2190, -875, -1924], ZZ) assert dup_mul(p1, p2, ZZ) == res p1 = dup_normal([83, -61, -86, -24, 12, 43, -88, -9, 42, 55, -66, 74, 95, -25, -12, 68, -99, 4, 45, 6, -15, -19, 78, 65, -55, 47, -13, 17, 86, 81, -58, -27, 50, -40, -24, 39, -41, -92, 75, 90, -1, 40, -15, -27, -35, 68, 70, -64, -40, 78, -88, -58, -39, 69, 46, 12, 28, -94, -37, -50, -80, -96, -61, 25, 1, 71, 4, 12, 48, 4, 34, -47, -75, 5, 48, 82, 88, 23, 98, 35, 17, -10, 48, -61, -95, 47, 65, -19, -66, -57, -6, -51, -42, -89, 66, -13, 18, 37, 90, -23, 72, 96, -53, 0, 40, -73, -52, -68, 32, -25, -53, 79, -52, 18, 44, 73, -81, 31, -90, 70, 3, 36, 48, 76, -24, -44, 23, 98, -4, 73, 69, 88, -70, 14, -68, 94, -78, -15, -64, -97, -70, -35, 65, 88, 49, -53, -7, 12, -45, -7, 59, -94, 99, -2, 67, -60, -71, 29, -62, -77, 1, 51, 17, 80, -20, -47, -19, 24, -9, 39, -23, 21, -84, 10, 84, 56, -17, -21, -66, 85, 70, 46, -51, -22, -95, 78, -60, -96, -97, -45, 72, 35, 30, -61, -92, -93, -60, -61, 4, -4, -81, -73, 46, 53, -11, 26, 94, 45, 14, -78, 55, 84, -68, 98, 60, 23, 100, -63, 68, 96, -16, 3, 56, 21, -58, 62, -67, 66, 85, 41, -79, -22, 97, -67, 82, 82, -96, -20, -7, 48, -67, 48, -9, -39, 78], ZZ) p2 = dup_normal([52, 88, 76, 66, 9, -64, 46, -20, -28, 69, 60, 96, -36, -92, -30, -11, -35, 35, 55, 63, -92, -7, 25, -58, 74, 55, -6, 4, 47, -92, -65, 67, -45, 74, -76, 59, -6, 69, 39, 24, -71, -7, 39, -45, 60, -68, 98, 97, -79, 17, 4, 94, -64, 68, -100, -96, -2, 3, 22, 96, 54, -77, -86, 67, 6, 57, 37, 40, 89, -78, 64, -94, -45, -92, 57, 87, -26, 36, 19, 97, 25, 77, -87, 24, 43, -5, 35, 57, 83, 71, 35, 63, 61, 96, -22, 8, -1, 96, 43, 45, 94, -93, 36, 71, -41, -99, 85, -48, 59, 52, -17, 5, 87, -16, -68, -54, 76, -18, 100, 91, -42, -70, -66, -88, -12, 1, 95, -82, 52, 43, -29, 3, 12, 72, -99, -43, -32, -93, -51, 16, -20, -12, -11, 5, 33, -38, 93, -5, -74, 25, 74, -58, 93, 59, -63, -86, 63, -20, -4, -74, -73, -95, 29, -28, 93, -91, -2, -38, -62, 77, -58, -85, -28, 95, 38, 19, -69, 86, 94, 25, -2, -4, 47, 34, -59, 35, -48, 29, -63, -53, 34, 29, 66, 73, 6, 92, -84, 89, 15, 81, 93, 97, 51, -72, -78, 25, 60, 90, -45, 39, 67, -84, -62, 57, 26, -32, -56, -14, -83, 76, 5, -2, 99, -100, 28, 46, 94, -7, 53, -25, 16, -23, -36, 89, -78, -63, 31, 1, 84, -99, -52, 76, 48, 90, -76, 44, -19, 54, -36, -9, -73, -100, -69, 31, 42, 25, -39, 76, -26, -8, -14, 51, 3, 37, 45, 2, -54, 13, -34, -92, 17, -25, -65, 53, -63, 30, 4, -70, -67, 90, 52, 51, 18, -3, 31, -45, -9, 59, 63, -87, 22, -32, 29, -38, 21, 36, -82, 27, -11], ZZ) res = dup_normal([4316, 4132, -3532, -7974, -11303, -10069, 5484, -3330, -5874, 7734, 4673, 11327, -9884, -8031, 17343, 21035, -10570, -9285, 15893, 3780, -14083, 8819, 17592, 10159, 7174, -11587, 8598, -16479, 3602, 25596, 9781, 12163, 150, 18749, -21782, -12307, 27578, -2757, -12573, 12565, 6345, -18956, 19503, -15617, 1443, -16778, 36851, 23588, -28474, 5749, 40695, -7521, -53669, -2497, -18530, 6770, 57038, 3926, -6927, -15399, 1848, -64649, -27728, 3644, 49608, 15187, -8902, -9480, -7398, -40425, 4824, 23767, -7594, -6905, 33089, 18786, 12192, 24670, 31114, 35334, -4501, -14676, 7107, -59018, -21352, 20777, 19661, 20653, 33754, -885, -43758, 6269, 51897, -28719, -97488, -9527, 13746, 11644, 17644, -21720, 23782, -10481, 47867, 20752, 33810, -1875, 39918, -7710, -40840, 19808, -47075, 23066, 46616, 25201, 9287, 35436, -1602, 9645, -11978, 13273, 15544, 33465, 20063, 44539, 11687, 27314, -6538, -37467, 14031, 32970, -27086, 41323, 29551, 65910, -39027, -37800, -22232, 8212, 46316, -28981, -55282, 50417, -44929, -44062, 73879, 37573, -2596, -10877, -21893, -133218, -33707, -25753, -9531, 17530, 61126, 2748, -56235, 43874, -10872, -90459, -30387, 115267, -7264, -44452, 122626, 14839, -599, 10337, 57166, -67467, -54957, 63669, 1202, 18488, 52594, 7205, -97822, 612, 78069, -5403, -63562, 47236, 36873, -154827, -26188, 82427, -39521, 5628, 7416, 5276, -53095, 47050, 26121, -42207, 79021, -13035, 2499, -66943, 29040, -72355, -23480, 23416, -12885, -44225, -42688, -4224, 19858, 55299, 15735, 11465, 101876, -39169, 51786, 14723, 43280, -68697, 16410, 92295, 56767, 7183, 111850, 4550, 115451, -38443, -19642, -35058, 10230, 93829, 8925, 63047, 3146, 29250, 8530, 5255, -98117, -115517, -76817, -8724, 41044, 1312, -35974, 79333, -28567, 7547, -10580, -24559, -16238, 10794, -3867, 24848, 57770, -51536, -35040, 71033, 29853, 62029, -7125, -125585, -32169, -47907, 156811, -65176, -58006, -15757, -57861, 11963, 30225, -41901, -41681, 31310, 27982, 18613, 61760, 60746, -59096, 33499, 30097, -17997, 24032, 56442, -83042, 23747, -20931, -21978, -158752, -9883, -73598, -7987, -7333, -125403, -116329, 30585, 53281, 51018, -29193, 88575, 8264, -40147, -16289, 113088, 12810, -6508, 101552, -13037, 34440, -41840, 101643, 24263, 80532, 61748, 65574, 6423, -20672, 6591, -10834, -71716, 86919, -92626, 39161, 28490, 81319, 46676, 106720, 43530, 26998, 57456, -8862, 60989, 13982, 3119, -2224, 14743, 55415, -49093, -29303, 28999, 1789, 55953, -84043, -7780, -65013, 57129, -47251, 61484, 61994, -78361, -82778, 22487, -26894, 9756, -74637, -15519, -4360, 30115, 42433, 35475, 15286, 69768, 21509, -20214, 78675, -21163, 13596, 11443, -10698, -53621, -53867, -24155, 64500, -42784, -33077, -16500, 873, -52788, 14546, -38011, 36974, -39849, -34029, -94311, 83068, -50437, -26169, -46746, 59185, 42259, -101379, -12943, 30089, -59086, 36271, 22723, -30253, -52472, -70826, -23289, 3331, -31687, 14183, -857, -28627, 35246, -51284, 5636, -6933, 66539, 36654, 50927, 24783, 3457, 33276, 45281, 45650, -4938, -9968, -22590, 47995, 69229, 5214, -58365, -17907, -14651, 18668, 18009, 12649, -11851, -13387, 20339, 52472, -1087, -21458, -68647, 52295, 15849, 40608, 15323, 25164, -29368, 10352, -7055, 7159, 21695, -5373, -54849, 101103, -24963, -10511, 33227, 7659, 41042, -69588, 26718, -20515, 6441, 38135, -63, 24088, -35364, -12785, -18709, 47843, 48533, -48575, 17251, -19394, 32878, -9010, -9050, 504, -12407, 28076, -3429, 25324, -4210, -26119, 752, -29203, 28251, -11324, -32140, -3366, -25135, 18702, -31588, -7047, -24267, 49987, -14975, -33169, 37744, -7720, -9035, 16964, -2807, -421, 14114, -17097, -13662, 40628, -12139, -9427, 5369, 17551, -13232, -16211, 9804, -7422, 2677, 28635, -8280, -4906, 2908, -22558, 5604, 12459, 8756, -3980, -4745, -18525, 7913, 5970, -16457, 20230, -6247, -13812, 2505, 11899, 1409, -15094, 22540, -18863, 137, 11123, -4516, 2290, -8594, 12150, -10380, 3005, 5235, -7350, 2535, -858], ZZ) assert dup_mul(p1, p2, ZZ) == res def test_dmp_mul(): assert dmp_mul([ZZ(5)], [ZZ(7)], 0, ZZ) == \ dup_mul([ZZ(5)], [ZZ(7)], ZZ) assert dmp_mul([QQ(5, 7)], [QQ(3, 7)], 0, QQ) == \ dup_mul([QQ(5, 7)], [QQ(3, 7)], QQ) assert dmp_mul([[[]]], [[[]]], 2, ZZ) == [[[]]] assert dmp_mul([[[ZZ(1)]]], [[[]]], 2, ZZ) == [[[]]] assert dmp_mul([[[]]], [[[ZZ(1)]]], 2, ZZ) == [[[]]] assert dmp_mul([[[ZZ(2)]]], [[[ZZ(1)]]], 2, ZZ) == [[[ZZ(2)]]] assert dmp_mul([[[ZZ(1)]]], [[[ZZ(2)]]], 2, ZZ) == [[[ZZ(2)]]] assert dmp_mul([[[]]], [[[]]], 2, QQ) == [[[]]] assert dmp_mul([[[QQ(1, 2)]]], [[[]]], 2, QQ) == [[[]]] assert dmp_mul([[[]]], [[[QQ(1, 2)]]], 2, QQ) == [[[]]] assert dmp_mul([[[QQ(2, 7)]]], [[[QQ(1, 3)]]], 2, QQ) == [[[QQ(2, 21)]]] assert dmp_mul([[[QQ(1, 7)]]], [[[QQ(2, 3)]]], 2, QQ) == [[[QQ(2, 21)]]] K = FF(6) assert dmp_mul( [[K(2)], [K(1)]], [[K(3)], [K(4)]], 1, K) == [[K(5)], [K(4)]] def test_dup_sqr(): assert dup_sqr([], ZZ) == [] assert dup_sqr([ZZ(2)], ZZ) == [ZZ(4)] assert dup_sqr([ZZ(1), ZZ(2)], ZZ) == [ZZ(1), ZZ(4), ZZ(4)] assert dup_sqr([], QQ) == [] assert dup_sqr([QQ(2, 3)], QQ) == [QQ(4, 9)] assert dup_sqr([QQ(1, 3), QQ(2, 3)], QQ) == [QQ(1, 9), QQ(4, 9), QQ(4, 9)] f = dup_normal([2, 0, 0, 1, 7], ZZ) assert dup_sqr(f, ZZ) == dup_normal([4, 0, 0, 4, 28, 0, 1, 14, 49], ZZ) K = FF(9) assert dup_sqr([K(3), K(4)], K) == [K(6), K(7)] def test_dmp_sqr(): assert dmp_sqr([ZZ(1), ZZ(2)], 0, ZZ) == \ dup_sqr([ZZ(1), ZZ(2)], ZZ) assert dmp_sqr([[[]]], 2, ZZ) == [[[]]] assert dmp_sqr([[[ZZ(2)]]], 2, ZZ) == [[[ZZ(4)]]] assert dmp_sqr([[[]]], 2, QQ) == [[[]]] assert dmp_sqr([[[QQ(2, 3)]]], 2, QQ) == [[[QQ(4, 9)]]] K = FF(9) assert dmp_sqr([[K(3)], [K(4)]], 1, K) == [[K(6)], [K(7)]] def test_dup_pow(): assert dup_pow([], 0, ZZ) == [ZZ(1)] assert dup_pow([], 0, QQ) == [QQ(1)] assert dup_pow([], 1, ZZ) == [] assert dup_pow([], 7, ZZ) == [] assert dup_pow([ZZ(1)], 0, ZZ) == [ZZ(1)] assert dup_pow([ZZ(1)], 1, ZZ) == [ZZ(1)] assert dup_pow([ZZ(1)], 7, ZZ) == [ZZ(1)] assert dup_pow([ZZ(3)], 0, ZZ) == [ZZ(1)] assert dup_pow([ZZ(3)], 1, ZZ) == [ZZ(3)] assert dup_pow([ZZ(3)], 7, ZZ) == [ZZ(2187)] assert dup_pow([QQ(1, 1)], 0, QQ) == [QQ(1, 1)] assert dup_pow([QQ(1, 1)], 1, QQ) == [QQ(1, 1)] assert dup_pow([QQ(1, 1)], 7, QQ) == [QQ(1, 1)] assert dup_pow([QQ(3, 7)], 0, QQ) == [QQ(1, 1)] assert dup_pow([QQ(3, 7)], 1, QQ) == [QQ(3, 7)] assert dup_pow([QQ(3, 7)], 7, QQ) == [QQ(2187, 823543)] f = dup_normal([2, 0, 0, 1, 7], ZZ) assert dup_pow(f, 0, ZZ) == dup_normal([1], ZZ) assert dup_pow(f, 1, ZZ) == dup_normal([2, 0, 0, 1, 7], ZZ) assert dup_pow(f, 2, ZZ) == dup_normal([4, 0, 0, 4, 28, 0, 1, 14, 49], ZZ) assert dup_pow(f, 3, ZZ) == dup_normal( [8, 0, 0, 12, 84, 0, 6, 84, 294, 1, 21, 147, 343], ZZ) def test_dmp_pow(): assert dmp_pow([[]], 0, 1, ZZ) == [[ZZ(1)]] assert dmp_pow([[]], 0, 1, QQ) == [[QQ(1)]] assert dmp_pow([[]], 1, 1, ZZ) == [[]] assert dmp_pow([[]], 7, 1, ZZ) == [[]] assert dmp_pow([[ZZ(1)]], 0, 1, ZZ) == [[ZZ(1)]] assert dmp_pow([[ZZ(1)]], 1, 1, ZZ) == [[ZZ(1)]] assert dmp_pow([[ZZ(1)]], 7, 1, ZZ) == [[ZZ(1)]] assert dmp_pow([[QQ(3, 7)]], 0, 1, QQ) == [[QQ(1, 1)]] assert dmp_pow([[QQ(3, 7)]], 1, 1, QQ) == [[QQ(3, 7)]] assert dmp_pow([[QQ(3, 7)]], 7, 1, QQ) == [[QQ(2187, 823543)]] f = dup_normal([2, 0, 0, 1, 7], ZZ) assert dmp_pow(f, 2, 0, ZZ) == dup_pow(f, 2, ZZ) def test_dup_pdiv(): f = dup_normal([3, 1, 1, 5], ZZ) g = dup_normal([5, -3, 1], ZZ) q = dup_normal([15, 14], ZZ) r = dup_normal([52, 111], ZZ) assert dup_pdiv(f, g, ZZ) == (q, r) assert dup_pquo(f, g, ZZ) == q assert dup_prem(f, g, ZZ) == r raises(ExactQuotientFailed, lambda: dup_pexquo(f, g, ZZ)) f = dup_normal([3, 1, 1, 5], QQ) g = dup_normal([5, -3, 1], QQ) q = dup_normal([15, 14], QQ) r = dup_normal([52, 111], QQ) assert dup_pdiv(f, g, QQ) == (q, r) assert dup_pquo(f, g, QQ) == q assert dup_prem(f, g, QQ) == r raises(ExactQuotientFailed, lambda: dup_pexquo(f, g, QQ)) def test_dmp_pdiv(): f = dmp_normal([[1], [], [1, 0, 0]], 1, ZZ) g = dmp_normal([[1], [-1, 0]], 1, ZZ) q = dmp_normal([[1], [1, 0]], 1, ZZ) r = dmp_normal([[2, 0, 0]], 1, ZZ) assert dmp_pdiv(f, g, 1, ZZ) == (q, r) assert dmp_pquo(f, g, 1, ZZ) == q assert dmp_prem(f, g, 1, ZZ) == r raises(ExactQuotientFailed, lambda: dmp_pexquo(f, g, 1, ZZ)) f = dmp_normal([[1], [], [1, 0, 0]], 1, ZZ) g = dmp_normal([[2], [-2, 0]], 1, ZZ) q = dmp_normal([[2], [2, 0]], 1, ZZ) r = dmp_normal([[8, 0, 0]], 1, ZZ) assert dmp_pdiv(f, g, 1, ZZ) == (q, r) assert dmp_pquo(f, g, 1, ZZ) == q assert dmp_prem(f, g, 1, ZZ) == r raises(ExactQuotientFailed, lambda: dmp_pexquo(f, g, 1, ZZ)) def test_dup_rr_div(): raises(ZeroDivisionError, lambda: dup_rr_div([1, 2, 3], [], ZZ)) f = dup_normal([3, 1, 1, 5], ZZ) g = dup_normal([5, -3, 1], ZZ) q, r = [], f assert dup_rr_div(f, g, ZZ) == (q, r) def test_dmp_rr_div(): raises(ZeroDivisionError, lambda: dmp_rr_div([[1, 2], [3]], [[]], 1, ZZ)) f = dmp_normal([[1], [], [1, 0, 0]], 1, ZZ) g = dmp_normal([[1], [-1, 0]], 1, ZZ) q = dmp_normal([[1], [1, 0]], 1, ZZ) r = dmp_normal([[2, 0, 0]], 1, ZZ) assert dmp_rr_div(f, g, 1, ZZ) == (q, r) f = dmp_normal([[1], [], [1, 0, 0]], 1, ZZ) g = dmp_normal([[-1], [1, 0]], 1, ZZ) q = dmp_normal([[-1], [-1, 0]], 1, ZZ) r = dmp_normal([[2, 0, 0]], 1, ZZ) assert dmp_rr_div(f, g, 1, ZZ) == (q, r) f = dmp_normal([[1], [], [1, 0, 0]], 1, ZZ) g = dmp_normal([[2], [-2, 0]], 1, ZZ) q, r = [[]], f assert dmp_rr_div(f, g, 1, ZZ) == (q, r) def test_dup_ff_div(): raises(ZeroDivisionError, lambda: dup_ff_div([1, 2, 3], [], QQ)) f = dup_normal([3, 1, 1, 5], QQ) g = dup_normal([5, -3, 1], QQ) q = [QQ(3, 5), QQ(14, 25)] r = [QQ(52, 25), QQ(111, 25)] assert dup_ff_div(f, g, QQ) == (q, r) def test_dup_ff_div_gmpy2(): try: from gmpy2 import mpq except ImportError: return from sympy.polys.domains import GMPYRationalField K = GMPYRationalField() f = [mpq(1,3), mpq(3,2)] g = [mpq(2,1)] assert dmp_ff_div(f, g, 0, K) == ([mpq(1,6), mpq(3,4)], []) f = [mpq(1,2), mpq(1,3), mpq(1,4), mpq(1,5)] g = [mpq(-1,1), mpq(1,1), mpq(-1,1)] assert dmp_ff_div(f, g, 0, K) == ([mpq(-1,2), mpq(-5,6)], [mpq(7,12), mpq(-19,30)]) def test_dmp_ff_div(): raises(ZeroDivisionError, lambda: dmp_ff_div([[1, 2], [3]], [[]], 1, QQ)) f = dmp_normal([[1], [], [1, 0, 0]], 1, QQ) g = dmp_normal([[1], [-1, 0]], 1, QQ) q = [[QQ(1, 1)], [QQ(1, 1), QQ(0, 1)]] r = [[QQ(2, 1), QQ(0, 1), QQ(0, 1)]] assert dmp_ff_div(f, g, 1, QQ) == (q, r) f = dmp_normal([[1], [], [1, 0, 0]], 1, QQ) g = dmp_normal([[-1], [1, 0]], 1, QQ) q = [[QQ(-1, 1)], [QQ(-1, 1), QQ(0, 1)]] r = [[QQ(2, 1), QQ(0, 1), QQ(0, 1)]] assert dmp_ff_div(f, g, 1, QQ) == (q, r) f = dmp_normal([[1], [], [1, 0, 0]], 1, QQ) g = dmp_normal([[2], [-2, 0]], 1, QQ) q = [[QQ(1, 2)], [QQ(1, 2), QQ(0, 1)]] r = [[QQ(2, 1), QQ(0, 1), QQ(0, 1)]] assert dmp_ff_div(f, g, 1, QQ) == (q, r) def test_dup_div(): f, g, q, r = [5, 4, 3, 2, 1], [1, 2, 3], [5, -6, 0], [20, 1] assert dup_div(f, g, ZZ) == (q, r) assert dup_quo(f, g, ZZ) == q assert dup_rem(f, g, ZZ) == r raises(ExactQuotientFailed, lambda: dup_exquo(f, g, ZZ)) f, g, q, r = [5, 4, 3, 2, 1, 0], [1, 2, 0, 0, 9], [5, -6], [15, 2, -44, 54] assert dup_div(f, g, ZZ) == (q, r) assert dup_quo(f, g, ZZ) == q assert dup_rem(f, g, ZZ) == r raises(ExactQuotientFailed, lambda: dup_exquo(f, g, ZZ)) def test_dmp_div(): f, g, q, r = [5, 4, 3, 2, 1], [1, 2, 3], [5, -6, 0], [20, 1] assert dmp_div(f, g, 0, ZZ) == (q, r) assert dmp_quo(f, g, 0, ZZ) == q assert dmp_rem(f, g, 0, ZZ) == r raises(ExactQuotientFailed, lambda: dmp_exquo(f, g, 0, ZZ)) f, g, q, r = [[[1]]], [[[2]], [1]], [[[]]], [[[1]]] assert dmp_div(f, g, 2, ZZ) == (q, r) assert dmp_quo(f, g, 2, ZZ) == q assert dmp_rem(f, g, 2, ZZ) == r raises(ExactQuotientFailed, lambda: dmp_exquo(f, g, 2, ZZ)) def test_dup_max_norm(): assert dup_max_norm([], ZZ) == 0 assert dup_max_norm([1], ZZ) == 1 assert dup_max_norm([1, 4, 2, 3], ZZ) == 4 def test_dmp_max_norm(): assert dmp_max_norm([[[]]], 2, ZZ) == 0 assert dmp_max_norm([[[1]]], 2, ZZ) == 1 assert dmp_max_norm(f_0, 2, ZZ) == 6 def test_dup_l1_norm(): assert dup_l1_norm([], ZZ) == 0 assert dup_l1_norm([1], ZZ) == 1 assert dup_l1_norm([1, 4, 2, 3], ZZ) == 10 def test_dmp_l1_norm(): assert dmp_l1_norm([[[]]], 2, ZZ) == 0 assert dmp_l1_norm([[[1]]], 2, ZZ) == 1 assert dmp_l1_norm(f_0, 2, ZZ) == 31 def test_dup_l2_norm_squared(): assert dup_l2_norm_squared([], ZZ) == 0 assert dup_l2_norm_squared([1], ZZ) == 1 assert dup_l2_norm_squared([1, 4, 2, 3], ZZ) == 30 def test_dmp_l2_norm_squared(): assert dmp_l2_norm_squared([[[]]], 2, ZZ) == 0 assert dmp_l2_norm_squared([[[1]]], 2, ZZ) == 1 assert dmp_l2_norm_squared(f_0, 2, ZZ) == 111 def test_dup_expand(): assert dup_expand((), ZZ) == [1] assert dup_expand(([1, 2, 3], [1, 2], [7, 5, 4, 3]), ZZ) == \ dup_mul([1, 2, 3], dup_mul([1, 2], [7, 5, 4, 3], ZZ), ZZ) def test_dmp_expand(): assert dmp_expand((), 1, ZZ) == [[1]] assert dmp_expand(([[1], [2], [3]], [[1], [2]], [[7], [5], [4], [3]]), 1, ZZ) == \ dmp_mul([[1], [2], [3]], dmp_mul([[1], [2]], [[7], [5], [ 4], [3]], 1, ZZ), 1, ZZ)
c7fc4af2392f1a1f021a1c9248fd1ca1d09fedbd4ab78c28d25e28bf8464a416
"""Tests for user-friendly public interface to polynomial functions. """ import pickle from sympy.polys.polytools import ( Poly, PurePoly, poly, parallel_poly_from_expr, degree, degree_list, total_degree, LC, LM, LT, pdiv, prem, pquo, pexquo, div, rem, quo, exquo, half_gcdex, gcdex, invert, subresultants, resultant, discriminant, terms_gcd, cofactors, gcd, gcd_list, lcm, lcm_list, trunc, monic, content, primitive, compose, decompose, sturm, gff_list, gff, sqf_norm, sqf_part, sqf_list, sqf, factor_list, factor, intervals, refine_root, count_roots, real_roots, nroots, ground_roots, nth_power_roots_poly, cancel, reduced, groebner, GroebnerBasis, is_zero_dimensional, _torational_factor_list, to_rational_coeffs) from sympy.polys.polyerrors import ( MultivariatePolynomialError, ExactQuotientFailed, PolificationFailed, ComputationFailed, UnificationFailed, RefinementFailed, GeneratorsNeeded, GeneratorsError, PolynomialError, CoercionFailed, DomainError, OptionError, FlagError) from sympy.polys.polyclasses import DMP from sympy.polys.fields import field from sympy.polys.domains import FF, ZZ, QQ, ZZ_I, QQ_I, RR, EX from sympy.polys.domains.realfield import RealField from sympy.polys.domains.complexfield import ComplexField from sympy.polys.orderings import lex, grlex, grevlex from sympy.core.add import Add from sympy.core.basic import _aresame from sympy.core.containers import Tuple from sympy.core.expr import Expr from sympy.core.function import (Derivative, diff, expand) from sympy.core.mul import _keep_coeff, Mul from sympy.core.numbers import (Float, I, Integer, Rational, oo, pi) from sympy.core.power import Pow from sympy.core.relational import Eq from sympy.core.singleton import S from sympy.core.symbol import Symbol from sympy.functions.elementary.complexes import (im, re) from sympy.functions.elementary.exponential import exp from sympy.functions.elementary.hyperbolic import tanh 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 Matrix from sympy.matrices.expressions.matexpr import MatrixSymbol from sympy.polys.rootoftools import rootof from sympy.simplify.simplify import signsimp from sympy.utilities.iterables import iterable from sympy.utilities.exceptions import SymPyDeprecationWarning from sympy.testing.pytest import raises, warns_deprecated_sympy, warns from sympy.abc import a, b, c, d, p, q, t, w, x, y, z def _epsilon_eq(a, b): for u, v in zip(a, b): if abs(u - v) > 1e-10: return False return True def _strict_eq(a, b): if type(a) == type(b): if iterable(a): if len(a) == len(b): return all(_strict_eq(c, d) for c, d in zip(a, b)) else: return False else: return isinstance(a, Poly) and a.eq(b, strict=True) else: return False def test_Poly_mixed_operations(): p = Poly(x, x) with warns_deprecated_sympy(): p * exp(x) with warns_deprecated_sympy(): p + exp(x) with warns_deprecated_sympy(): p - exp(x) def test_Poly_from_dict(): K = FF(3) assert Poly.from_dict( {0: 1, 1: 2}, gens=x, domain=K).rep == DMP([K(2), K(1)], K) assert Poly.from_dict( {0: 1, 1: 5}, gens=x, domain=K).rep == DMP([K(2), K(1)], K) assert Poly.from_dict( {(0,): 1, (1,): 2}, gens=x, domain=K).rep == DMP([K(2), K(1)], K) assert Poly.from_dict( {(0,): 1, (1,): 5}, gens=x, domain=K).rep == DMP([K(2), K(1)], K) assert Poly.from_dict({(0, 0): 1, (1, 1): 2}, gens=( x, y), domain=K).rep == DMP([[K(2), K(0)], [K(1)]], K) assert Poly.from_dict({0: 1, 1: 2}, gens=x).rep == DMP([ZZ(2), ZZ(1)], ZZ) assert Poly.from_dict( {0: 1, 1: 2}, gens=x, field=True).rep == DMP([QQ(2), QQ(1)], QQ) assert Poly.from_dict( {0: 1, 1: 2}, gens=x, domain=ZZ).rep == DMP([ZZ(2), ZZ(1)], ZZ) assert Poly.from_dict( {0: 1, 1: 2}, gens=x, domain=QQ).rep == DMP([QQ(2), QQ(1)], QQ) assert Poly.from_dict( {(0,): 1, (1,): 2}, gens=x).rep == DMP([ZZ(2), ZZ(1)], ZZ) assert Poly.from_dict( {(0,): 1, (1,): 2}, gens=x, field=True).rep == DMP([QQ(2), QQ(1)], QQ) assert Poly.from_dict( {(0,): 1, (1,): 2}, gens=x, domain=ZZ).rep == DMP([ZZ(2), ZZ(1)], ZZ) assert Poly.from_dict( {(0,): 1, (1,): 2}, gens=x, domain=QQ).rep == DMP([QQ(2), QQ(1)], QQ) assert Poly.from_dict({(1,): sin(y)}, gens=x, composite=False) == \ Poly(sin(y)*x, x, domain='EX') assert Poly.from_dict({(1,): y}, gens=x, composite=False) == \ Poly(y*x, x, domain='EX') assert Poly.from_dict({(1, 1): 1}, gens=(x, y), composite=False) == \ Poly(x*y, x, y, domain='ZZ') assert Poly.from_dict({(1, 0): y}, gens=(x, z), composite=False) == \ Poly(y*x, x, z, domain='EX') def test_Poly_from_list(): K = FF(3) assert Poly.from_list([2, 1], gens=x, domain=K).rep == DMP([K(2), K(1)], K) assert Poly.from_list([5, 1], gens=x, domain=K).rep == DMP([K(2), K(1)], K) assert Poly.from_list([2, 1], gens=x).rep == DMP([ZZ(2), ZZ(1)], ZZ) assert Poly.from_list([2, 1], gens=x, field=True).rep == DMP([QQ(2), QQ(1)], QQ) assert Poly.from_list([2, 1], gens=x, domain=ZZ).rep == DMP([ZZ(2), ZZ(1)], ZZ) assert Poly.from_list([2, 1], gens=x, domain=QQ).rep == DMP([QQ(2), QQ(1)], QQ) assert Poly.from_list([0, 1.0], gens=x).rep == DMP([RR(1.0)], RR) assert Poly.from_list([1.0, 0], gens=x).rep == DMP([RR(1.0), RR(0.0)], RR) raises(MultivariatePolynomialError, lambda: Poly.from_list([[]], gens=(x, y))) def test_Poly_from_poly(): f = Poly(x + 7, x, domain=ZZ) g = Poly(x + 2, x, modulus=3) h = Poly(x + y, x, y, domain=ZZ) K = FF(3) assert Poly.from_poly(f) == f assert Poly.from_poly(f, domain=K).rep == DMP([K(1), K(1)], K) assert Poly.from_poly(f, domain=ZZ).rep == DMP([1, 7], ZZ) assert Poly.from_poly(f, domain=QQ).rep == DMP([1, 7], QQ) assert Poly.from_poly(f, gens=x) == f assert Poly.from_poly(f, gens=x, domain=K).rep == DMP([K(1), K(1)], K) assert Poly.from_poly(f, gens=x, domain=ZZ).rep == DMP([1, 7], ZZ) assert Poly.from_poly(f, gens=x, domain=QQ).rep == DMP([1, 7], QQ) assert Poly.from_poly(f, gens=y) == Poly(x + 7, y, domain='ZZ[x]') raises(CoercionFailed, lambda: Poly.from_poly(f, gens=y, domain=K)) raises(CoercionFailed, lambda: Poly.from_poly(f, gens=y, domain=ZZ)) raises(CoercionFailed, lambda: Poly.from_poly(f, gens=y, domain=QQ)) assert Poly.from_poly(f, gens=(x, y)) == Poly(x + 7, x, y, domain='ZZ') assert Poly.from_poly( f, gens=(x, y), domain=ZZ) == Poly(x + 7, x, y, domain='ZZ') assert Poly.from_poly( f, gens=(x, y), domain=QQ) == Poly(x + 7, x, y, domain='QQ') assert Poly.from_poly( f, gens=(x, y), modulus=3) == Poly(x + 7, x, y, domain='FF(3)') K = FF(2) assert Poly.from_poly(g) == g assert Poly.from_poly(g, domain=ZZ).rep == DMP([1, -1], ZZ) raises(CoercionFailed, lambda: Poly.from_poly(g, domain=QQ)) assert Poly.from_poly(g, domain=K).rep == DMP([K(1), K(0)], K) assert Poly.from_poly(g, gens=x) == g assert Poly.from_poly(g, gens=x, domain=ZZ).rep == DMP([1, -1], ZZ) raises(CoercionFailed, lambda: Poly.from_poly(g, gens=x, domain=QQ)) assert Poly.from_poly(g, gens=x, domain=K).rep == DMP([K(1), K(0)], K) K = FF(3) assert Poly.from_poly(h) == h assert Poly.from_poly( h, domain=ZZ).rep == DMP([[ZZ(1)], [ZZ(1), ZZ(0)]], ZZ) assert Poly.from_poly( h, domain=QQ).rep == DMP([[QQ(1)], [QQ(1), QQ(0)]], QQ) assert Poly.from_poly(h, domain=K).rep == DMP([[K(1)], [K(1), K(0)]], K) assert Poly.from_poly(h, gens=x) == Poly(x + y, x, domain=ZZ[y]) raises(CoercionFailed, lambda: Poly.from_poly(h, gens=x, domain=ZZ)) assert Poly.from_poly( h, gens=x, domain=ZZ[y]) == Poly(x + y, x, domain=ZZ[y]) raises(CoercionFailed, lambda: Poly.from_poly(h, gens=x, domain=QQ)) assert Poly.from_poly( h, gens=x, domain=QQ[y]) == Poly(x + y, x, domain=QQ[y]) raises(CoercionFailed, lambda: Poly.from_poly(h, gens=x, modulus=3)) assert Poly.from_poly(h, gens=y) == Poly(x + y, y, domain=ZZ[x]) raises(CoercionFailed, lambda: Poly.from_poly(h, gens=y, domain=ZZ)) assert Poly.from_poly( h, gens=y, domain=ZZ[x]) == Poly(x + y, y, domain=ZZ[x]) raises(CoercionFailed, lambda: Poly.from_poly(h, gens=y, domain=QQ)) assert Poly.from_poly( h, gens=y, domain=QQ[x]) == Poly(x + y, y, domain=QQ[x]) raises(CoercionFailed, lambda: Poly.from_poly(h, gens=y, modulus=3)) assert Poly.from_poly(h, gens=(x, y)) == h assert Poly.from_poly( h, gens=(x, y), domain=ZZ).rep == DMP([[ZZ(1)], [ZZ(1), ZZ(0)]], ZZ) assert Poly.from_poly( h, gens=(x, y), domain=QQ).rep == DMP([[QQ(1)], [QQ(1), QQ(0)]], QQ) assert Poly.from_poly( h, gens=(x, y), domain=K).rep == DMP([[K(1)], [K(1), K(0)]], K) assert Poly.from_poly( h, gens=(y, x)).rep == DMP([[ZZ(1)], [ZZ(1), ZZ(0)]], ZZ) assert Poly.from_poly( h, gens=(y, x), domain=ZZ).rep == DMP([[ZZ(1)], [ZZ(1), ZZ(0)]], ZZ) assert Poly.from_poly( h, gens=(y, x), domain=QQ).rep == DMP([[QQ(1)], [QQ(1), QQ(0)]], QQ) assert Poly.from_poly( h, gens=(y, x), domain=K).rep == DMP([[K(1)], [K(1), K(0)]], K) assert Poly.from_poly( h, gens=(x, y), field=True).rep == DMP([[QQ(1)], [QQ(1), QQ(0)]], QQ) assert Poly.from_poly( h, gens=(x, y), field=True).rep == DMP([[QQ(1)], [QQ(1), QQ(0)]], QQ) def test_Poly_from_expr(): raises(GeneratorsNeeded, lambda: Poly.from_expr(S.Zero)) raises(GeneratorsNeeded, lambda: Poly.from_expr(S(7))) F3 = FF(3) assert Poly.from_expr(x + 5, domain=F3).rep == DMP([F3(1), F3(2)], F3) assert Poly.from_expr(y + 5, domain=F3).rep == DMP([F3(1), F3(2)], F3) assert Poly.from_expr(x + 5, x, domain=F3).rep == DMP([F3(1), F3(2)], F3) assert Poly.from_expr(y + 5, y, domain=F3).rep == DMP([F3(1), F3(2)], F3) assert Poly.from_expr(x + y, domain=F3).rep == DMP([[F3(1)], [F3(1), F3(0)]], F3) assert Poly.from_expr(x + y, x, y, domain=F3).rep == DMP([[F3(1)], [F3(1), F3(0)]], F3) assert Poly.from_expr(x + 5).rep == DMP([1, 5], ZZ) assert Poly.from_expr(y + 5).rep == DMP([1, 5], ZZ) assert Poly.from_expr(x + 5, x).rep == DMP([1, 5], ZZ) assert Poly.from_expr(y + 5, y).rep == DMP([1, 5], ZZ) assert Poly.from_expr(x + 5, domain=ZZ).rep == DMP([1, 5], ZZ) assert Poly.from_expr(y + 5, domain=ZZ).rep == DMP([1, 5], ZZ) assert Poly.from_expr(x + 5, x, domain=ZZ).rep == DMP([1, 5], ZZ) assert Poly.from_expr(y + 5, y, domain=ZZ).rep == DMP([1, 5], ZZ) assert Poly.from_expr(x + 5, x, y, domain=ZZ).rep == DMP([[1], [5]], ZZ) assert Poly.from_expr(y + 5, x, y, domain=ZZ).rep == DMP([[1, 5]], ZZ) def test_poly_from_domain_element(): dom = ZZ[x] assert Poly(dom(x+1), y, domain=dom).rep == DMP([dom(x+1)], dom) dom = dom.get_field() assert Poly(dom(x+1), y, domain=dom).rep == DMP([dom(x+1)], dom) dom = QQ[x] assert Poly(dom(x+1), y, domain=dom).rep == DMP([dom(x+1)], dom) dom = dom.get_field() assert Poly(dom(x+1), y, domain=dom).rep == DMP([dom(x+1)], dom) dom = ZZ.old_poly_ring(x) assert Poly(dom([1, 1]), y, domain=dom).rep == DMP([dom([1, 1])], dom) dom = dom.get_field() assert Poly(dom([1, 1]), y, domain=dom).rep == DMP([dom([1, 1])], dom) dom = QQ.old_poly_ring(x) assert Poly(dom([1, 1]), y, domain=dom).rep == DMP([dom([1, 1])], dom) dom = dom.get_field() assert Poly(dom([1, 1]), y, domain=dom).rep == DMP([dom([1, 1])], dom) dom = QQ.algebraic_field(I) assert Poly(dom([1, 1]), x, domain=dom).rep == DMP([dom([1, 1])], dom) def test_Poly__new__(): raises(GeneratorsError, lambda: Poly(x + 1, x, x)) raises(GeneratorsError, lambda: Poly(x + y, x, y, domain=ZZ[x])) raises(GeneratorsError, lambda: Poly(x + y, x, y, domain=ZZ[y])) raises(OptionError, lambda: Poly(x, x, symmetric=True)) raises(OptionError, lambda: Poly(x + 2, x, modulus=3, domain=QQ)) raises(OptionError, lambda: Poly(x + 2, x, domain=ZZ, gaussian=True)) raises(OptionError, lambda: Poly(x + 2, x, modulus=3, gaussian=True)) raises(OptionError, lambda: Poly(x + 2, x, domain=ZZ, extension=[sqrt(3)])) raises(OptionError, lambda: Poly(x + 2, x, modulus=3, extension=[sqrt(3)])) raises(OptionError, lambda: Poly(x + 2, x, domain=ZZ, extension=True)) raises(OptionError, lambda: Poly(x + 2, x, modulus=3, extension=True)) raises(OptionError, lambda: Poly(x + 2, x, domain=ZZ, greedy=True)) raises(OptionError, lambda: Poly(x + 2, x, domain=QQ, field=True)) raises(OptionError, lambda: Poly(x + 2, x, domain=ZZ, greedy=False)) raises(OptionError, lambda: Poly(x + 2, x, domain=QQ, field=False)) raises(NotImplementedError, lambda: Poly(x + 1, x, modulus=3, order='grlex')) raises(NotImplementedError, lambda: Poly(x + 1, x, order='grlex')) raises(GeneratorsNeeded, lambda: Poly({1: 2, 0: 1})) raises(GeneratorsNeeded, lambda: Poly([2, 1])) raises(GeneratorsNeeded, lambda: Poly((2, 1))) raises(GeneratorsNeeded, lambda: Poly(1)) f = a*x**2 + b*x + c assert Poly({2: a, 1: b, 0: c}, x) == f assert Poly(iter([a, b, c]), x) == f assert Poly([a, b, c], x) == f assert Poly((a, b, c), x) == f f = Poly({}, x, y, z) assert f.gens == (x, y, z) and f.as_expr() == 0 assert Poly(Poly(a*x + b*y, x, y), x) == Poly(a*x + b*y, x) assert Poly(3*x**2 + 2*x + 1, domain='ZZ').all_coeffs() == [3, 2, 1] assert Poly(3*x**2 + 2*x + 1, domain='QQ').all_coeffs() == [3, 2, 1] assert Poly(3*x**2 + 2*x + 1, domain='RR').all_coeffs() == [3.0, 2.0, 1.0] raises(CoercionFailed, lambda: Poly(3*x**2/5 + x*Rational(2, 5) + 1, domain='ZZ')) assert Poly( 3*x**2/5 + x*Rational(2, 5) + 1, domain='QQ').all_coeffs() == [Rational(3, 5), Rational(2, 5), 1] assert _epsilon_eq( Poly(3*x**2/5 + x*Rational(2, 5) + 1, domain='RR').all_coeffs(), [0.6, 0.4, 1.0]) assert Poly(3.0*x**2 + 2.0*x + 1, domain='ZZ').all_coeffs() == [3, 2, 1] assert Poly(3.0*x**2 + 2.0*x + 1, domain='QQ').all_coeffs() == [3, 2, 1] assert Poly( 3.0*x**2 + 2.0*x + 1, domain='RR').all_coeffs() == [3.0, 2.0, 1.0] raises(CoercionFailed, lambda: Poly(3.1*x**2 + 2.1*x + 1, domain='ZZ')) assert Poly(3.1*x**2 + 2.1*x + 1, domain='QQ').all_coeffs() == [Rational(31, 10), Rational(21, 10), 1] assert Poly(3.1*x**2 + 2.1*x + 1, domain='RR').all_coeffs() == [3.1, 2.1, 1.0] assert Poly({(2, 1): 1, (1, 2): 2, (1, 1): 3}, x, y) == \ Poly(x**2*y + 2*x*y**2 + 3*x*y, x, y) assert Poly(x**2 + 1, extension=I).get_domain() == QQ.algebraic_field(I) f = 3*x**5 - x**4 + x**3 - x** 2 + 65538 assert Poly(f, x, modulus=65537, symmetric=True) == \ Poly(3*x**5 - x**4 + x**3 - x** 2 + 1, x, modulus=65537, symmetric=True) assert Poly(f, x, modulus=65537, symmetric=False) == \ Poly(3*x**5 + 65536*x**4 + x**3 + 65536*x** 2 + 1, x, modulus=65537, symmetric=False) assert isinstance(Poly(x**2 + x + 1.0).get_domain(), RealField) assert isinstance(Poly(x**2 + x + I + 1.0).get_domain(), ComplexField) def test_Poly__args(): assert Poly(x**2 + 1).args == (x**2 + 1, x) def test_Poly__gens(): assert Poly((x - p)*(x - q), x).gens == (x,) assert Poly((x - p)*(x - q), p).gens == (p,) assert Poly((x - p)*(x - q), q).gens == (q,) assert Poly((x - p)*(x - q), x, p).gens == (x, p) assert Poly((x - p)*(x - q), x, q).gens == (x, q) assert Poly((x - p)*(x - q), x, p, q).gens == (x, p, q) assert Poly((x - p)*(x - q), p, x, q).gens == (p, x, q) assert Poly((x - p)*(x - q), p, q, x).gens == (p, q, x) assert Poly((x - p)*(x - q)).gens == (x, p, q) assert Poly((x - p)*(x - q), sort='x > p > q').gens == (x, p, q) assert Poly((x - p)*(x - q), sort='p > x > q').gens == (p, x, q) assert Poly((x - p)*(x - q), sort='p > q > x').gens == (p, q, x) assert Poly((x - p)*(x - q), x, p, q, sort='p > q > x').gens == (x, p, q) assert Poly((x - p)*(x - q), wrt='x').gens == (x, p, q) assert Poly((x - p)*(x - q), wrt='p').gens == (p, x, q) assert Poly((x - p)*(x - q), wrt='q').gens == (q, x, p) assert Poly((x - p)*(x - q), wrt=x).gens == (x, p, q) assert Poly((x - p)*(x - q), wrt=p).gens == (p, x, q) assert Poly((x - p)*(x - q), wrt=q).gens == (q, x, p) assert Poly((x - p)*(x - q), x, p, q, wrt='p').gens == (x, p, q) assert Poly((x - p)*(x - q), wrt='p', sort='q > x').gens == (p, q, x) assert Poly((x - p)*(x - q), wrt='q', sort='p > x').gens == (q, p, x) def test_Poly_zero(): assert Poly(x).zero == Poly(0, x, domain=ZZ) assert Poly(x/2).zero == Poly(0, x, domain=QQ) def test_Poly_one(): assert Poly(x).one == Poly(1, x, domain=ZZ) assert Poly(x/2).one == Poly(1, x, domain=QQ) def test_Poly__unify(): raises(UnificationFailed, lambda: Poly(x)._unify(y)) F3 = FF(3) F5 = FF(5) assert Poly(x, x, modulus=3)._unify(Poly(y, y, modulus=3))[2:] == ( DMP([[F3(1)], []], F3), DMP([[F3(1), F3(0)]], F3)) assert Poly(x, x, modulus=3)._unify(Poly(y, y, modulus=5))[2:] == ( DMP([[F5(1)], []], F5), DMP([[F5(1), F5(0)]], F5)) assert Poly(y, x, y)._unify(Poly(x, x, modulus=3))[2:] == (DMP([[F3(1), F3(0)]], F3), DMP([[F3(1)], []], F3)) assert Poly(x, x, modulus=3)._unify(Poly(y, x, y))[2:] == (DMP([[F3(1)], []], F3), DMP([[F3(1), F3(0)]], F3)) assert Poly(x + 1, x)._unify(Poly(x + 2, x))[2:] == (DMP([1, 1], ZZ), DMP([1, 2], ZZ)) assert Poly(x + 1, x, domain='QQ')._unify(Poly(x + 2, x))[2:] == (DMP([1, 1], QQ), DMP([1, 2], QQ)) assert Poly(x + 1, x)._unify(Poly(x + 2, x, domain='QQ'))[2:] == (DMP([1, 1], QQ), DMP([1, 2], QQ)) assert Poly(x + 1, x)._unify(Poly(x + 2, x, y))[2:] == (DMP([[1], [1]], ZZ), DMP([[1], [2]], ZZ)) assert Poly(x + 1, x, domain='QQ')._unify(Poly(x + 2, x, y))[2:] == (DMP([[1], [1]], QQ), DMP([[1], [2]], QQ)) assert Poly(x + 1, x)._unify(Poly(x + 2, x, y, domain='QQ'))[2:] == (DMP([[1], [1]], QQ), DMP([[1], [2]], QQ)) assert Poly(x + 1, x, y)._unify(Poly(x + 2, x))[2:] == (DMP([[1], [1]], ZZ), DMP([[1], [2]], ZZ)) assert Poly(x + 1, x, y, domain='QQ')._unify(Poly(x + 2, x))[2:] == (DMP([[1], [1]], QQ), DMP([[1], [2]], QQ)) assert Poly(x + 1, x, y)._unify(Poly(x + 2, x, domain='QQ'))[2:] == (DMP([[1], [1]], QQ), DMP([[1], [2]], QQ)) assert Poly(x + 1, x, y)._unify(Poly(x + 2, x, y))[2:] == (DMP([[1], [1]], ZZ), DMP([[1], [2]], ZZ)) assert Poly(x + 1, x, y, domain='QQ')._unify(Poly(x + 2, x, y))[2:] == (DMP([[1], [1]], QQ), DMP([[1], [2]], QQ)) assert Poly(x + 1, x, y)._unify(Poly(x + 2, x, y, domain='QQ'))[2:] == (DMP([[1], [1]], QQ), DMP([[1], [2]], QQ)) assert Poly(x + 1, x)._unify(Poly(x + 2, y, x))[2:] == (DMP([[1, 1]], ZZ), DMP([[1, 2]], ZZ)) assert Poly(x + 1, x, domain='QQ')._unify(Poly(x + 2, y, x))[2:] == (DMP([[1, 1]], QQ), DMP([[1, 2]], QQ)) assert Poly(x + 1, x)._unify(Poly(x + 2, y, x, domain='QQ'))[2:] == (DMP([[1, 1]], QQ), DMP([[1, 2]], QQ)) assert Poly(x + 1, y, x)._unify(Poly(x + 2, x))[2:] == (DMP([[1, 1]], ZZ), DMP([[1, 2]], ZZ)) assert Poly(x + 1, y, x, domain='QQ')._unify(Poly(x + 2, x))[2:] == (DMP([[1, 1]], QQ), DMP([[1, 2]], QQ)) assert Poly(x + 1, y, x)._unify(Poly(x + 2, x, domain='QQ'))[2:] == (DMP([[1, 1]], QQ), DMP([[1, 2]], QQ)) assert Poly(x + 1, x, y)._unify(Poly(x + 2, y, x))[2:] == (DMP([[1], [1]], ZZ), DMP([[1], [2]], ZZ)) assert Poly(x + 1, x, y, domain='QQ')._unify(Poly(x + 2, y, x))[2:] == (DMP([[1], [1]], QQ), DMP([[1], [2]], QQ)) assert Poly(x + 1, x, y)._unify(Poly(x + 2, y, x, domain='QQ'))[2:] == (DMP([[1], [1]], QQ), DMP([[1], [2]], QQ)) assert Poly(x + 1, y, x)._unify(Poly(x + 2, x, y))[2:] == (DMP([[1, 1]], ZZ), DMP([[1, 2]], ZZ)) assert Poly(x + 1, y, x, domain='QQ')._unify(Poly(x + 2, x, y))[2:] == (DMP([[1, 1]], QQ), DMP([[1, 2]], QQ)) assert Poly(x + 1, y, x)._unify(Poly(x + 2, x, y, domain='QQ'))[2:] == (DMP([[1, 1]], QQ), DMP([[1, 2]], QQ)) assert Poly(x**2 + I, x, domain=ZZ_I).unify(Poly(x**2 + sqrt(2), x, extension=True)) == \ (Poly(x**2 + I, x, domain='QQ<sqrt(2) + I>'), Poly(x**2 + sqrt(2), x, domain='QQ<sqrt(2) + I>')) F, A, B = field("a,b", ZZ) assert Poly(a*x, x, domain='ZZ[a]')._unify(Poly(a*b*x, x, domain='ZZ(a,b)'))[2:] == \ (DMP([A, F(0)], F.to_domain()), DMP([A*B, F(0)], F.to_domain())) assert Poly(a*x, x, domain='ZZ(a)')._unify(Poly(a*b*x, x, domain='ZZ(a,b)'))[2:] == \ (DMP([A, F(0)], F.to_domain()), DMP([A*B, F(0)], F.to_domain())) raises(CoercionFailed, lambda: Poly(Poly(x**2 + x**2*z, y, field=True), domain='ZZ(x)')) f = Poly(t**2 + t/3 + x, t, domain='QQ(x)') g = Poly(t**2 + t/3 + x, t, domain='QQ[x]') assert f._unify(g)[2:] == (f.rep, f.rep) def test_Poly_free_symbols(): assert Poly(x**2 + 1).free_symbols == {x} assert Poly(x**2 + y*z).free_symbols == {x, y, z} assert Poly(x**2 + y*z, x).free_symbols == {x, y, z} assert Poly(x**2 + sin(y*z)).free_symbols == {x, y, z} assert Poly(x**2 + sin(y*z), x).free_symbols == {x, y, z} assert Poly(x**2 + sin(y*z), x, domain=EX).free_symbols == {x, y, z} assert Poly(1 + x + x**2, x, y, z).free_symbols == {x} assert Poly(x + sin(y), z).free_symbols == {x, y} def test_PurePoly_free_symbols(): assert PurePoly(x**2 + 1).free_symbols == set() assert PurePoly(x**2 + y*z).free_symbols == set() assert PurePoly(x**2 + y*z, x).free_symbols == {y, z} assert PurePoly(x**2 + sin(y*z)).free_symbols == set() assert PurePoly(x**2 + sin(y*z), x).free_symbols == {y, z} assert PurePoly(x**2 + sin(y*z), x, domain=EX).free_symbols == {y, z} def test_Poly__eq__(): assert (Poly(x, x) == Poly(x, x)) is True assert (Poly(x, x, domain=QQ) == Poly(x, x)) is False assert (Poly(x, x) == Poly(x, x, domain=QQ)) is False assert (Poly(x, x, domain=ZZ[a]) == Poly(x, x)) is False assert (Poly(x, x) == Poly(x, x, domain=ZZ[a])) is False assert (Poly(x*y, x, y) == Poly(x, x)) is False assert (Poly(x, x, y) == Poly(x, x)) is False assert (Poly(x, x) == Poly(x, x, y)) is False assert (Poly(x**2 + 1, x) == Poly(y**2 + 1, y)) is False assert (Poly(y**2 + 1, y) == Poly(x**2 + 1, x)) is False f = Poly(x, x, domain=ZZ) g = Poly(x, x, domain=QQ) assert f.eq(g) is False assert f.ne(g) is True assert f.eq(g, strict=True) is False assert f.ne(g, strict=True) is True t0 = Symbol('t0') f = Poly((t0/2 + x**2)*t**2 - x**2*t, t, domain='QQ[x,t0]') g = Poly((t0/2 + x**2)*t**2 - x**2*t, t, domain='ZZ(x,t0)') assert (f == g) is False def test_PurePoly__eq__(): assert (PurePoly(x, x) == PurePoly(x, x)) is True assert (PurePoly(x, x, domain=QQ) == PurePoly(x, x)) is True assert (PurePoly(x, x) == PurePoly(x, x, domain=QQ)) is True assert (PurePoly(x, x, domain=ZZ[a]) == PurePoly(x, x)) is True assert (PurePoly(x, x) == PurePoly(x, x, domain=ZZ[a])) is True assert (PurePoly(x*y, x, y) == PurePoly(x, x)) is False assert (PurePoly(x, x, y) == PurePoly(x, x)) is False assert (PurePoly(x, x) == PurePoly(x, x, y)) is False assert (PurePoly(x**2 + 1, x) == PurePoly(y**2 + 1, y)) is True assert (PurePoly(y**2 + 1, y) == PurePoly(x**2 + 1, x)) is True f = PurePoly(x, x, domain=ZZ) g = PurePoly(x, x, domain=QQ) assert f.eq(g) is True assert f.ne(g) is False assert f.eq(g, strict=True) is False assert f.ne(g, strict=True) is True f = PurePoly(x, x, domain=ZZ) g = PurePoly(y, y, domain=QQ) assert f.eq(g) is True assert f.ne(g) is False assert f.eq(g, strict=True) is False assert f.ne(g, strict=True) is True def test_PurePoly_Poly(): assert isinstance(PurePoly(Poly(x**2 + 1)), PurePoly) is True assert isinstance(Poly(PurePoly(x**2 + 1)), Poly) is True def test_Poly_get_domain(): assert Poly(2*x).get_domain() == ZZ assert Poly(2*x, domain='ZZ').get_domain() == ZZ assert Poly(2*x, domain='QQ').get_domain() == QQ assert Poly(x/2).get_domain() == QQ raises(CoercionFailed, lambda: Poly(x/2, domain='ZZ')) assert Poly(x/2, domain='QQ').get_domain() == QQ assert isinstance(Poly(0.2*x).get_domain(), RealField) def test_Poly_set_domain(): assert Poly(2*x + 1).set_domain(ZZ) == Poly(2*x + 1) assert Poly(2*x + 1).set_domain('ZZ') == Poly(2*x + 1) assert Poly(2*x + 1).set_domain(QQ) == Poly(2*x + 1, domain='QQ') assert Poly(2*x + 1).set_domain('QQ') == Poly(2*x + 1, domain='QQ') assert Poly(Rational(2, 10)*x + Rational(1, 10)).set_domain('RR') == Poly(0.2*x + 0.1) assert Poly(0.2*x + 0.1).set_domain('QQ') == Poly(Rational(2, 10)*x + Rational(1, 10)) raises(CoercionFailed, lambda: Poly(x/2 + 1).set_domain(ZZ)) raises(CoercionFailed, lambda: Poly(x + 1, modulus=2).set_domain(QQ)) raises(GeneratorsError, lambda: Poly(x*y, x, y).set_domain(ZZ[y])) def test_Poly_get_modulus(): assert Poly(x**2 + 1, modulus=2).get_modulus() == 2 raises(PolynomialError, lambda: Poly(x**2 + 1).get_modulus()) def test_Poly_set_modulus(): assert Poly( x**2 + 1, modulus=2).set_modulus(7) == Poly(x**2 + 1, modulus=7) assert Poly( x**2 + 5, modulus=7).set_modulus(2) == Poly(x**2 + 1, modulus=2) assert Poly(x**2 + 1).set_modulus(2) == Poly(x**2 + 1, modulus=2) raises(CoercionFailed, lambda: Poly(x/2 + 1).set_modulus(2)) def test_Poly_add_ground(): assert Poly(x + 1).add_ground(2) == Poly(x + 3) def test_Poly_sub_ground(): assert Poly(x + 1).sub_ground(2) == Poly(x - 1) def test_Poly_mul_ground(): assert Poly(x + 1).mul_ground(2) == Poly(2*x + 2) def test_Poly_quo_ground(): assert Poly(2*x + 4).quo_ground(2) == Poly(x + 2) assert Poly(2*x + 3).quo_ground(2) == Poly(x + 1) def test_Poly_exquo_ground(): assert Poly(2*x + 4).exquo_ground(2) == Poly(x + 2) raises(ExactQuotientFailed, lambda: Poly(2*x + 3).exquo_ground(2)) def test_Poly_abs(): assert Poly(-x + 1, x).abs() == abs(Poly(-x + 1, x)) == Poly(x + 1, x) def test_Poly_neg(): assert Poly(-x + 1, x).neg() == -Poly(-x + 1, x) == Poly(x - 1, x) def test_Poly_add(): assert Poly(0, x).add(Poly(0, x)) == Poly(0, x) assert Poly(0, x) + Poly(0, x) == Poly(0, x) assert Poly(1, x).add(Poly(0, x)) == Poly(1, x) assert Poly(1, x, y) + Poly(0, x) == Poly(1, x, y) assert Poly(0, x).add(Poly(1, x, y)) == Poly(1, x, y) assert Poly(0, x, y) + Poly(1, x, y) == Poly(1, x, y) assert Poly(1, x) + x == Poly(x + 1, x) with warns_deprecated_sympy(): Poly(1, x) + sin(x) assert Poly(x, x) + 1 == Poly(x + 1, x) assert 1 + Poly(x, x) == Poly(x + 1, x) def test_Poly_sub(): assert Poly(0, x).sub(Poly(0, x)) == Poly(0, x) assert Poly(0, x) - Poly(0, x) == Poly(0, x) assert Poly(1, x).sub(Poly(0, x)) == Poly(1, x) assert Poly(1, x, y) - Poly(0, x) == Poly(1, x, y) assert Poly(0, x).sub(Poly(1, x, y)) == Poly(-1, x, y) assert Poly(0, x, y) - Poly(1, x, y) == Poly(-1, x, y) assert Poly(1, x) - x == Poly(1 - x, x) with warns_deprecated_sympy(): Poly(1, x) - sin(x) assert Poly(x, x) - 1 == Poly(x - 1, x) assert 1 - Poly(x, x) == Poly(1 - x, x) def test_Poly_mul(): assert Poly(0, x).mul(Poly(0, x)) == Poly(0, x) assert Poly(0, x) * Poly(0, x) == Poly(0, x) assert Poly(2, x).mul(Poly(4, x)) == Poly(8, x) assert Poly(2, x, y) * Poly(4, x) == Poly(8, x, y) assert Poly(4, x).mul(Poly(2, x, y)) == Poly(8, x, y) assert Poly(4, x, y) * Poly(2, x, y) == Poly(8, x, y) assert Poly(1, x) * x == Poly(x, x) with warns_deprecated_sympy(): Poly(1, x) * sin(x) assert Poly(x, x) * 2 == Poly(2*x, x) assert 2 * Poly(x, x) == Poly(2*x, x) def test_issue_13079(): assert Poly(x)*x == Poly(x**2, x, domain='ZZ') assert x*Poly(x) == Poly(x**2, x, domain='ZZ') assert -2*Poly(x) == Poly(-2*x, x, domain='ZZ') assert S(-2)*Poly(x) == Poly(-2*x, x, domain='ZZ') assert Poly(x)*S(-2) == Poly(-2*x, x, domain='ZZ') def test_Poly_sqr(): assert Poly(x*y, x, y).sqr() == Poly(x**2*y**2, x, y) def test_Poly_pow(): assert Poly(x, x).pow(10) == Poly(x**10, x) assert Poly(x, x).pow(Integer(10)) == Poly(x**10, x) assert Poly(2*y, x, y).pow(4) == Poly(16*y**4, x, y) assert Poly(2*y, x, y).pow(Integer(4)) == Poly(16*y**4, x, y) assert Poly(7*x*y, x, y)**3 == Poly(343*x**3*y**3, x, y) raises(TypeError, lambda: Poly(x*y + 1, x, y)**(-1)) raises(TypeError, lambda: Poly(x*y + 1, x, y)**x) def test_Poly_divmod(): f, g = Poly(x**2), Poly(x) q, r = g, Poly(0, x) assert divmod(f, g) == (q, r) assert f // g == q assert f % g == r assert divmod(f, x) == (q, r) assert f // x == q assert f % x == r q, r = Poly(0, x), Poly(2, x) assert divmod(2, g) == (q, r) assert 2 // g == q assert 2 % g == r assert Poly(x)/Poly(x) == 1 assert Poly(x**2)/Poly(x) == x assert Poly(x)/Poly(x**2) == 1/x def test_Poly_eq_ne(): assert (Poly(x + y, x, y) == Poly(x + y, x, y)) is True assert (Poly(x + y, x) == Poly(x + y, x, y)) is False assert (Poly(x + y, x, y) == Poly(x + y, x)) is False assert (Poly(x + y, x) == Poly(x + y, x)) is True assert (Poly(x + y, y) == Poly(x + y, y)) is True assert (Poly(x + y, x, y) == x + y) is True assert (Poly(x + y, x) == x + y) is True assert (Poly(x + y, x, y) == x + y) is True assert (Poly(x + y, x) == x + y) is True assert (Poly(x + y, y) == x + y) is True assert (Poly(x + y, x, y) != Poly(x + y, x, y)) is False assert (Poly(x + y, x) != Poly(x + y, x, y)) is True assert (Poly(x + y, x, y) != Poly(x + y, x)) is True assert (Poly(x + y, x) != Poly(x + y, x)) is False assert (Poly(x + y, y) != Poly(x + y, y)) is False assert (Poly(x + y, x, y) != x + y) is False assert (Poly(x + y, x) != x + y) is False assert (Poly(x + y, x, y) != x + y) is False assert (Poly(x + y, x) != x + y) is False assert (Poly(x + y, y) != x + y) is False assert (Poly(x, x) == sin(x)) is False assert (Poly(x, x) != sin(x)) is True def test_Poly_nonzero(): assert not bool(Poly(0, x)) is True assert not bool(Poly(1, x)) is False def test_Poly_properties(): assert Poly(0, x).is_zero is True assert Poly(1, x).is_zero is False assert Poly(1, x).is_one is True assert Poly(2, x).is_one is False assert Poly(x - 1, x).is_sqf is True assert Poly((x - 1)**2, x).is_sqf is False assert Poly(x - 1, x).is_monic is True assert Poly(2*x - 1, x).is_monic is False assert Poly(3*x + 2, x).is_primitive is True assert Poly(4*x + 2, x).is_primitive is False assert Poly(1, x).is_ground is True assert Poly(x, x).is_ground is False assert Poly(x + y + z + 1).is_linear is True assert Poly(x*y*z + 1).is_linear is False assert Poly(x*y + z + 1).is_quadratic is True assert Poly(x*y*z + 1).is_quadratic is False assert Poly(x*y).is_monomial is True assert Poly(x*y + 1).is_monomial is False assert Poly(x**2 + x*y).is_homogeneous is True assert Poly(x**3 + x*y).is_homogeneous is False assert Poly(x).is_univariate is True assert Poly(x*y).is_univariate is False assert Poly(x*y).is_multivariate is True assert Poly(x).is_multivariate is False assert Poly( x**16 + x**14 - x**10 + x**8 - x**6 + x**2 + 1).is_cyclotomic is False assert Poly( x**16 + x**14 - x**10 - x**8 - x**6 + x**2 + 1).is_cyclotomic is True def test_Poly_is_irreducible(): assert Poly(x**2 + x + 1).is_irreducible is True assert Poly(x**2 + 2*x + 1).is_irreducible is False assert Poly(7*x + 3, modulus=11).is_irreducible is True assert Poly(7*x**2 + 3*x + 1, modulus=11).is_irreducible is False def test_Poly_subs(): assert Poly(x + 1).subs(x, 0) == 1 assert Poly(x + 1).subs(x, x) == Poly(x + 1) assert Poly(x + 1).subs(x, y) == Poly(y + 1) assert Poly(x*y, x).subs(y, x) == x**2 assert Poly(x*y, x).subs(x, y) == y**2 def test_Poly_replace(): assert Poly(x + 1).replace(x) == Poly(x + 1) assert Poly(x + 1).replace(y) == Poly(y + 1) raises(PolynomialError, lambda: Poly(x + y).replace(z)) assert Poly(x + 1).replace(x, x) == Poly(x + 1) assert Poly(x + 1).replace(x, y) == Poly(y + 1) assert Poly(x + y).replace(x, x) == Poly(x + y) assert Poly(x + y).replace(x, z) == Poly(z + y, z, y) assert Poly(x + y).replace(y, y) == Poly(x + y) assert Poly(x + y).replace(y, z) == Poly(x + z, x, z) assert Poly(x + y).replace(z, t) == Poly(x + y) raises(PolynomialError, lambda: Poly(x + y).replace(x, y)) assert Poly(x + y, x).replace(x, z) == Poly(z + y, z) assert Poly(x + y, y).replace(y, z) == Poly(x + z, z) raises(PolynomialError, lambda: Poly(x + y, x).replace(x, y)) raises(PolynomialError, lambda: Poly(x + y, y).replace(y, x)) def test_Poly_reorder(): raises(PolynomialError, lambda: Poly(x + y).reorder(x, z)) assert Poly(x + y, x, y).reorder(x, y) == Poly(x + y, x, y) assert Poly(x + y, x, y).reorder(y, x) == Poly(x + y, y, x) assert Poly(x + y, y, x).reorder(x, y) == Poly(x + y, x, y) assert Poly(x + y, y, x).reorder(y, x) == Poly(x + y, y, x) assert Poly(x + y, x, y).reorder(wrt=x) == Poly(x + y, x, y) assert Poly(x + y, x, y).reorder(wrt=y) == Poly(x + y, y, x) def test_Poly_ltrim(): f = Poly(y**2 + y*z**2, x, y, z).ltrim(y) assert f.as_expr() == y**2 + y*z**2 and f.gens == (y, z) assert Poly(x*y - x, z, x, y).ltrim(1) == Poly(x*y - x, x, y) raises(PolynomialError, lambda: Poly(x*y**2 + y**2, x, y).ltrim(y)) raises(PolynomialError, lambda: Poly(x*y - x, x, y).ltrim(-1)) def test_Poly_has_only_gens(): assert Poly(x*y + 1, x, y, z).has_only_gens(x, y) is True assert Poly(x*y + z, x, y, z).has_only_gens(x, y) is False raises(GeneratorsError, lambda: Poly(x*y**2 + y**2, x, y).has_only_gens(t)) def test_Poly_to_ring(): assert Poly(2*x + 1, domain='ZZ').to_ring() == Poly(2*x + 1, domain='ZZ') assert Poly(2*x + 1, domain='QQ').to_ring() == Poly(2*x + 1, domain='ZZ') raises(CoercionFailed, lambda: Poly(x/2 + 1).to_ring()) raises(DomainError, lambda: Poly(2*x + 1, modulus=3).to_ring()) def test_Poly_to_field(): assert Poly(2*x + 1, domain='ZZ').to_field() == Poly(2*x + 1, domain='QQ') assert Poly(2*x + 1, domain='QQ').to_field() == Poly(2*x + 1, domain='QQ') assert Poly(x/2 + 1, domain='QQ').to_field() == Poly(x/2 + 1, domain='QQ') assert Poly(2*x + 1, modulus=3).to_field() == Poly(2*x + 1, modulus=3) assert Poly(2.0*x + 1.0).to_field() == Poly(2.0*x + 1.0) def test_Poly_to_exact(): assert Poly(2*x).to_exact() == Poly(2*x) assert Poly(x/2).to_exact() == Poly(x/2) assert Poly(0.1*x).to_exact() == Poly(x/10) def test_Poly_retract(): f = Poly(x**2 + 1, x, domain=QQ[y]) assert f.retract() == Poly(x**2 + 1, x, domain='ZZ') assert f.retract(field=True) == Poly(x**2 + 1, x, domain='QQ') assert Poly(0, x, y).retract() == Poly(0, x, y) def test_Poly_slice(): f = Poly(x**3 + 2*x**2 + 3*x + 4) assert f.slice(0, 0) == Poly(0, x) assert f.slice(0, 1) == Poly(4, x) assert f.slice(0, 2) == Poly(3*x + 4, x) assert f.slice(0, 3) == Poly(2*x**2 + 3*x + 4, x) assert f.slice(0, 4) == Poly(x**3 + 2*x**2 + 3*x + 4, x) assert f.slice(x, 0, 0) == Poly(0, x) assert f.slice(x, 0, 1) == Poly(4, x) assert f.slice(x, 0, 2) == Poly(3*x + 4, x) assert f.slice(x, 0, 3) == Poly(2*x**2 + 3*x + 4, x) assert f.slice(x, 0, 4) == Poly(x**3 + 2*x**2 + 3*x + 4, x) def test_Poly_coeffs(): assert Poly(0, x).coeffs() == [0] assert Poly(1, x).coeffs() == [1] assert Poly(2*x + 1, x).coeffs() == [2, 1] assert Poly(7*x**2 + 2*x + 1, x).coeffs() == [7, 2, 1] assert Poly(7*x**4 + 2*x + 1, x).coeffs() == [7, 2, 1] assert Poly(x*y**7 + 2*x**2*y**3).coeffs('lex') == [2, 1] assert Poly(x*y**7 + 2*x**2*y**3).coeffs('grlex') == [1, 2] def test_Poly_monoms(): assert Poly(0, x).monoms() == [(0,)] assert Poly(1, x).monoms() == [(0,)] assert Poly(2*x + 1, x).monoms() == [(1,), (0,)] assert Poly(7*x**2 + 2*x + 1, x).monoms() == [(2,), (1,), (0,)] assert Poly(7*x**4 + 2*x + 1, x).monoms() == [(4,), (1,), (0,)] assert Poly(x*y**7 + 2*x**2*y**3).monoms('lex') == [(2, 3), (1, 7)] assert Poly(x*y**7 + 2*x**2*y**3).monoms('grlex') == [(1, 7), (2, 3)] def test_Poly_terms(): assert Poly(0, x).terms() == [((0,), 0)] assert Poly(1, x).terms() == [((0,), 1)] assert Poly(2*x + 1, x).terms() == [((1,), 2), ((0,), 1)] assert Poly(7*x**2 + 2*x + 1, x).terms() == [((2,), 7), ((1,), 2), ((0,), 1)] assert Poly(7*x**4 + 2*x + 1, x).terms() == [((4,), 7), ((1,), 2), ((0,), 1)] assert Poly( x*y**7 + 2*x**2*y**3).terms('lex') == [((2, 3), 2), ((1, 7), 1)] assert Poly( x*y**7 + 2*x**2*y**3).terms('grlex') == [((1, 7), 1), ((2, 3), 2)] def test_Poly_all_coeffs(): assert Poly(0, x).all_coeffs() == [0] assert Poly(1, x).all_coeffs() == [1] assert Poly(2*x + 1, x).all_coeffs() == [2, 1] assert Poly(7*x**2 + 2*x + 1, x).all_coeffs() == [7, 2, 1] assert Poly(7*x**4 + 2*x + 1, x).all_coeffs() == [7, 0, 0, 2, 1] def test_Poly_all_monoms(): assert Poly(0, x).all_monoms() == [(0,)] assert Poly(1, x).all_monoms() == [(0,)] assert Poly(2*x + 1, x).all_monoms() == [(1,), (0,)] assert Poly(7*x**2 + 2*x + 1, x).all_monoms() == [(2,), (1,), (0,)] assert Poly(7*x**4 + 2*x + 1, x).all_monoms() == [(4,), (3,), (2,), (1,), (0,)] def test_Poly_all_terms(): assert Poly(0, x).all_terms() == [((0,), 0)] assert Poly(1, x).all_terms() == [((0,), 1)] assert Poly(2*x + 1, x).all_terms() == [((1,), 2), ((0,), 1)] assert Poly(7*x**2 + 2*x + 1, x).all_terms() == \ [((2,), 7), ((1,), 2), ((0,), 1)] assert Poly(7*x**4 + 2*x + 1, x).all_terms() == \ [((4,), 7), ((3,), 0), ((2,), 0), ((1,), 2), ((0,), 1)] def test_Poly_termwise(): f = Poly(x**2 + 20*x + 400) g = Poly(x**2 + 2*x + 4) def func(monom, coeff): (k,) = monom return coeff//10**(2 - k) assert f.termwise(func) == g def func(monom, coeff): (k,) = monom return (k,), coeff//10**(2 - k) assert f.termwise(func) == g def test_Poly_length(): assert Poly(0, x).length() == 0 assert Poly(1, x).length() == 1 assert Poly(x, x).length() == 1 assert Poly(x + 1, x).length() == 2 assert Poly(x**2 + 1, x).length() == 2 assert Poly(x**2 + x + 1, x).length() == 3 def test_Poly_as_dict(): assert Poly(0, x).as_dict() == {} assert Poly(0, x, y, z).as_dict() == {} assert Poly(1, x).as_dict() == {(0,): 1} assert Poly(1, x, y, z).as_dict() == {(0, 0, 0): 1} assert Poly(x**2 + 3, x).as_dict() == {(2,): 1, (0,): 3} assert Poly(x**2 + 3, x, y, z).as_dict() == {(2, 0, 0): 1, (0, 0, 0): 3} assert Poly(3*x**2*y*z**3 + 4*x*y + 5*x*z).as_dict() == {(2, 1, 3): 3, (1, 1, 0): 4, (1, 0, 1): 5} def test_Poly_as_expr(): assert Poly(0, x).as_expr() == 0 assert Poly(0, x, y, z).as_expr() == 0 assert Poly(1, x).as_expr() == 1 assert Poly(1, x, y, z).as_expr() == 1 assert Poly(x**2 + 3, x).as_expr() == x**2 + 3 assert Poly(x**2 + 3, x, y, z).as_expr() == x**2 + 3 assert Poly( 3*x**2*y*z**3 + 4*x*y + 5*x*z).as_expr() == 3*x**2*y*z**3 + 4*x*y + 5*x*z f = Poly(x**2 + 2*x*y**2 - y, x, y) assert f.as_expr() == -y + x**2 + 2*x*y**2 assert f.as_expr({x: 5}) == 25 - y + 10*y**2 assert f.as_expr({y: 6}) == -6 + 72*x + x**2 assert f.as_expr({x: 5, y: 6}) == 379 assert f.as_expr(5, 6) == 379 raises(GeneratorsError, lambda: f.as_expr({z: 7})) def test_Poly_lift(): assert Poly(x**4 - I*x + 17*I, x, gaussian=True).lift() == \ Poly(x**16 + 2*x**10 + 578*x**8 + x**4 - 578*x**2 + 83521, x, domain='QQ') def test_Poly_deflate(): assert Poly(0, x).deflate() == ((1,), Poly(0, x)) assert Poly(1, x).deflate() == ((1,), Poly(1, x)) assert Poly(x, x).deflate() == ((1,), Poly(x, x)) assert Poly(x**2, x).deflate() == ((2,), Poly(x, x)) assert Poly(x**17, x).deflate() == ((17,), Poly(x, x)) assert Poly( x**2*y*z**11 + x**4*z**11).deflate() == ((2, 1, 11), Poly(x*y*z + x**2*z)) def test_Poly_inject(): f = Poly(x**2*y + x*y**3 + x*y + 1, x) assert f.inject() == Poly(x**2*y + x*y**3 + x*y + 1, x, y) assert f.inject(front=True) == Poly(y**3*x + y*x**2 + y*x + 1, y, x) def test_Poly_eject(): f = Poly(x**2*y + x*y**3 + x*y + 1, x, y) assert f.eject(x) == Poly(x*y**3 + (x**2 + x)*y + 1, y, domain='ZZ[x]') assert f.eject(y) == Poly(y*x**2 + (y**3 + y)*x + 1, x, domain='ZZ[y]') ex = x + y + z + t + w g = Poly(ex, x, y, z, t, w) assert g.eject(x) == Poly(ex, y, z, t, w, domain='ZZ[x]') assert g.eject(x, y) == Poly(ex, z, t, w, domain='ZZ[x, y]') assert g.eject(x, y, z) == Poly(ex, t, w, domain='ZZ[x, y, z]') assert g.eject(w) == Poly(ex, x, y, z, t, domain='ZZ[w]') assert g.eject(t, w) == Poly(ex, x, y, z, domain='ZZ[t, w]') assert g.eject(z, t, w) == Poly(ex, x, y, domain='ZZ[z, t, w]') raises(DomainError, lambda: Poly(x*y, x, y, domain=ZZ[z]).eject(y)) raises(NotImplementedError, lambda: Poly(x*y, x, y, z).eject(y)) def test_Poly_exclude(): assert Poly(x, x, y).exclude() == Poly(x, x) assert Poly(x*y, x, y).exclude() == Poly(x*y, x, y) assert Poly(1, x, y).exclude() == Poly(1, x, y) def test_Poly__gen_to_level(): assert Poly(1, x, y)._gen_to_level(-2) == 0 assert Poly(1, x, y)._gen_to_level(-1) == 1 assert Poly(1, x, y)._gen_to_level( 0) == 0 assert Poly(1, x, y)._gen_to_level( 1) == 1 raises(PolynomialError, lambda: Poly(1, x, y)._gen_to_level(-3)) raises(PolynomialError, lambda: Poly(1, x, y)._gen_to_level( 2)) assert Poly(1, x, y)._gen_to_level(x) == 0 assert Poly(1, x, y)._gen_to_level(y) == 1 assert Poly(1, x, y)._gen_to_level('x') == 0 assert Poly(1, x, y)._gen_to_level('y') == 1 raises(PolynomialError, lambda: Poly(1, x, y)._gen_to_level(z)) raises(PolynomialError, lambda: Poly(1, x, y)._gen_to_level('z')) def test_Poly_degree(): assert Poly(0, x).degree() is -oo assert Poly(1, x).degree() == 0 assert Poly(x, x).degree() == 1 assert Poly(0, x).degree(gen=0) is -oo assert Poly(1, x).degree(gen=0) == 0 assert Poly(x, x).degree(gen=0) == 1 assert Poly(0, x).degree(gen=x) is -oo assert Poly(1, x).degree(gen=x) == 0 assert Poly(x, x).degree(gen=x) == 1 assert Poly(0, x).degree(gen='x') is -oo assert Poly(1, x).degree(gen='x') == 0 assert Poly(x, x).degree(gen='x') == 1 raises(PolynomialError, lambda: Poly(1, x).degree(gen=1)) raises(PolynomialError, lambda: Poly(1, x).degree(gen=y)) raises(PolynomialError, lambda: Poly(1, x).degree(gen='y')) assert Poly(1, x, y).degree() == 0 assert Poly(2*y, x, y).degree() == 0 assert Poly(x*y, x, y).degree() == 1 assert Poly(1, x, y).degree(gen=x) == 0 assert Poly(2*y, x, y).degree(gen=x) == 0 assert Poly(x*y, x, y).degree(gen=x) == 1 assert Poly(1, x, y).degree(gen=y) == 0 assert Poly(2*y, x, y).degree(gen=y) == 1 assert Poly(x*y, x, y).degree(gen=y) == 1 assert degree(0, x) is -oo assert degree(1, x) == 0 assert degree(x, x) == 1 assert degree(x*y**2, x) == 1 assert degree(x*y**2, y) == 2 assert degree(x*y**2, z) == 0 assert degree(pi) == 1 raises(TypeError, lambda: degree(y**2 + x**3)) raises(TypeError, lambda: degree(y**2 + x**3, 1)) raises(PolynomialError, lambda: degree(x, 1.1)) raises(PolynomialError, lambda: degree(x**2/(x**3 + 1), x)) assert degree(Poly(0,x),z) is -oo assert degree(Poly(1,x),z) == 0 assert degree(Poly(x**2+y**3,y)) == 3 assert degree(Poly(y**2 + x**3, y, x), 1) == 3 assert degree(Poly(y**2 + x**3, x), z) == 0 assert degree(Poly(y**2 + x**3 + z**4, x), z) == 4 def test_Poly_degree_list(): assert Poly(0, x).degree_list() == (-oo,) assert Poly(0, x, y).degree_list() == (-oo, -oo) assert Poly(0, x, y, z).degree_list() == (-oo, -oo, -oo) assert Poly(1, x).degree_list() == (0,) assert Poly(1, x, y).degree_list() == (0, 0) assert Poly(1, x, y, z).degree_list() == (0, 0, 0) assert Poly(x**2*y + x**3*z**2 + 1).degree_list() == (3, 1, 2) assert degree_list(1, x) == (0,) assert degree_list(x, x) == (1,) assert degree_list(x*y**2) == (1, 2) raises(ComputationFailed, lambda: degree_list(1)) def test_Poly_total_degree(): assert Poly(x**2*y + x**3*z**2 + 1).total_degree() == 5 assert Poly(x**2 + z**3).total_degree() == 3 assert Poly(x*y*z + z**4).total_degree() == 4 assert Poly(x**3 + x + 1).total_degree() == 3 assert total_degree(x*y + z**3) == 3 assert total_degree(x*y + z**3, x, y) == 2 assert total_degree(1) == 0 assert total_degree(Poly(y**2 + x**3 + z**4)) == 4 assert total_degree(Poly(y**2 + x**3 + z**4, x)) == 3 assert total_degree(Poly(y**2 + x**3 + z**4, x), z) == 4 assert total_degree(Poly(x**9 + x*z*y + x**3*z**2 + z**7,x), z) == 7 def test_Poly_homogenize(): assert Poly(x**2+y).homogenize(z) == Poly(x**2+y*z) assert Poly(x+y).homogenize(z) == Poly(x+y, x, y, z) assert Poly(x+y**2).homogenize(y) == Poly(x*y+y**2) def test_Poly_homogeneous_order(): assert Poly(0, x, y).homogeneous_order() is -oo assert Poly(1, x, y).homogeneous_order() == 0 assert Poly(x, x, y).homogeneous_order() == 1 assert Poly(x*y, x, y).homogeneous_order() == 2 assert Poly(x + 1, x, y).homogeneous_order() is None assert Poly(x*y + x, x, y).homogeneous_order() is None assert Poly(x**5 + 2*x**3*y**2 + 9*x*y**4).homogeneous_order() == 5 assert Poly(x**5 + 2*x**3*y**3 + 9*x*y**4).homogeneous_order() is None def test_Poly_LC(): assert Poly(0, x).LC() == 0 assert Poly(1, x).LC() == 1 assert Poly(2*x**2 + x, x).LC() == 2 assert Poly(x*y**7 + 2*x**2*y**3).LC('lex') == 2 assert Poly(x*y**7 + 2*x**2*y**3).LC('grlex') == 1 assert LC(x*y**7 + 2*x**2*y**3, order='lex') == 2 assert LC(x*y**7 + 2*x**2*y**3, order='grlex') == 1 def test_Poly_TC(): assert Poly(0, x).TC() == 0 assert Poly(1, x).TC() == 1 assert Poly(2*x**2 + x, x).TC() == 0 def test_Poly_EC(): assert Poly(0, x).EC() == 0 assert Poly(1, x).EC() == 1 assert Poly(2*x**2 + x, x).EC() == 1 assert Poly(x*y**7 + 2*x**2*y**3).EC('lex') == 1 assert Poly(x*y**7 + 2*x**2*y**3).EC('grlex') == 2 def test_Poly_coeff(): assert Poly(0, x).coeff_monomial(1) == 0 assert Poly(0, x).coeff_monomial(x) == 0 assert Poly(1, x).coeff_monomial(1) == 1 assert Poly(1, x).coeff_monomial(x) == 0 assert Poly(x**8, x).coeff_monomial(1) == 0 assert Poly(x**8, x).coeff_monomial(x**7) == 0 assert Poly(x**8, x).coeff_monomial(x**8) == 1 assert Poly(x**8, x).coeff_monomial(x**9) == 0 assert Poly(3*x*y**2 + 1, x, y).coeff_monomial(1) == 1 assert Poly(3*x*y**2 + 1, x, y).coeff_monomial(x*y**2) == 3 p = Poly(24*x*y*exp(8) + 23*x, x, y) assert p.coeff_monomial(x) == 23 assert p.coeff_monomial(y) == 0 assert p.coeff_monomial(x*y) == 24*exp(8) assert p.as_expr().coeff(x) == 24*y*exp(8) + 23 raises(NotImplementedError, lambda: p.coeff(x)) raises(ValueError, lambda: Poly(x + 1).coeff_monomial(0)) raises(ValueError, lambda: Poly(x + 1).coeff_monomial(3*x)) raises(ValueError, lambda: Poly(x + 1).coeff_monomial(3*x*y)) def test_Poly_nth(): assert Poly(0, x).nth(0) == 0 assert Poly(0, x).nth(1) == 0 assert Poly(1, x).nth(0) == 1 assert Poly(1, x).nth(1) == 0 assert Poly(x**8, x).nth(0) == 0 assert Poly(x**8, x).nth(7) == 0 assert Poly(x**8, x).nth(8) == 1 assert Poly(x**8, x).nth(9) == 0 assert Poly(3*x*y**2 + 1, x, y).nth(0, 0) == 1 assert Poly(3*x*y**2 + 1, x, y).nth(1, 2) == 3 raises(ValueError, lambda: Poly(x*y + 1, x, y).nth(1)) def test_Poly_LM(): assert Poly(0, x).LM() == (0,) assert Poly(1, x).LM() == (0,) assert Poly(2*x**2 + x, x).LM() == (2,) assert Poly(x*y**7 + 2*x**2*y**3).LM('lex') == (2, 3) assert Poly(x*y**7 + 2*x**2*y**3).LM('grlex') == (1, 7) assert LM(x*y**7 + 2*x**2*y**3, order='lex') == x**2*y**3 assert LM(x*y**7 + 2*x**2*y**3, order='grlex') == x*y**7 def test_Poly_LM_custom_order(): f = Poly(x**2*y**3*z + x**2*y*z**3 + x*y*z + 1) rev_lex = lambda monom: tuple(reversed(monom)) assert f.LM(order='lex') == (2, 3, 1) assert f.LM(order=rev_lex) == (2, 1, 3) def test_Poly_EM(): assert Poly(0, x).EM() == (0,) assert Poly(1, x).EM() == (0,) assert Poly(2*x**2 + x, x).EM() == (1,) assert Poly(x*y**7 + 2*x**2*y**3).EM('lex') == (1, 7) assert Poly(x*y**7 + 2*x**2*y**3).EM('grlex') == (2, 3) def test_Poly_LT(): assert Poly(0, x).LT() == ((0,), 0) assert Poly(1, x).LT() == ((0,), 1) assert Poly(2*x**2 + x, x).LT() == ((2,), 2) assert Poly(x*y**7 + 2*x**2*y**3).LT('lex') == ((2, 3), 2) assert Poly(x*y**7 + 2*x**2*y**3).LT('grlex') == ((1, 7), 1) assert LT(x*y**7 + 2*x**2*y**3, order='lex') == 2*x**2*y**3 assert LT(x*y**7 + 2*x**2*y**3, order='grlex') == x*y**7 def test_Poly_ET(): assert Poly(0, x).ET() == ((0,), 0) assert Poly(1, x).ET() == ((0,), 1) assert Poly(2*x**2 + x, x).ET() == ((1,), 1) assert Poly(x*y**7 + 2*x**2*y**3).ET('lex') == ((1, 7), 1) assert Poly(x*y**7 + 2*x**2*y**3).ET('grlex') == ((2, 3), 2) def test_Poly_max_norm(): assert Poly(-1, x).max_norm() == 1 assert Poly( 0, x).max_norm() == 0 assert Poly( 1, x).max_norm() == 1 def test_Poly_l1_norm(): assert Poly(-1, x).l1_norm() == 1 assert Poly( 0, x).l1_norm() == 0 assert Poly( 1, x).l1_norm() == 1 def test_Poly_clear_denoms(): coeff, poly = Poly(x + 2, x).clear_denoms() assert coeff == 1 and poly == Poly( x + 2, x, domain='ZZ') and poly.get_domain() == ZZ coeff, poly = Poly(x/2 + 1, x).clear_denoms() assert coeff == 2 and poly == Poly( x + 2, x, domain='QQ') and poly.get_domain() == QQ coeff, poly = Poly(x/2 + 1, x).clear_denoms(convert=True) assert coeff == 2 and poly == Poly( x + 2, x, domain='ZZ') and poly.get_domain() == ZZ coeff, poly = Poly(x/y + 1, x).clear_denoms(convert=True) assert coeff == y and poly == Poly( x + y, x, domain='ZZ[y]') and poly.get_domain() == ZZ[y] coeff, poly = Poly(x/3 + sqrt(2), x, domain='EX').clear_denoms() assert coeff == 3 and poly == Poly( x + 3*sqrt(2), x, domain='EX') and poly.get_domain() == EX coeff, poly = Poly( x/3 + sqrt(2), x, domain='EX').clear_denoms(convert=True) assert coeff == 3 and poly == Poly( x + 3*sqrt(2), x, domain='EX') and poly.get_domain() == EX def test_Poly_rat_clear_denoms(): f = Poly(x**2/y + 1, x) g = Poly(x**3 + y, x) assert f.rat_clear_denoms(g) == \ (Poly(x**2 + y, x), Poly(y*x**3 + y**2, x)) f = f.set_domain(EX) g = g.set_domain(EX) assert f.rat_clear_denoms(g) == (f, g) def test_issue_20427(): f = Poly(-117968192370600*18**(S(1)/3)/(217603955769048*(24201 + 253*sqrt(9165))**(S(1)/3) + 2273005839412*sqrt(9165)*(24201 + 253*sqrt(9165))**(S(1)/3)) - 15720318185*2**(S(2)/3)*3**(S(1)/3)*(24201 + 253*sqrt(9165))**(S(2)/3)/(217603955769048*(24201 + 253*sqrt(9165))** (S(1)/3) + 2273005839412*sqrt(9165)*(24201 + 253*sqrt(9165))**(S(1)/3)) + 15720318185*12**(S(1)/3)*(24201 + 253*sqrt(9165))**(S(2)/3)/( 217603955769048*(24201 + 253*sqrt(9165))**(S(1)/3) + 2273005839412* sqrt(9165)*(24201 + 253*sqrt(9165))**(S(1)/3)) + 117968192370600*2**( S(1)/3)*3**(S(2)/3)/(217603955769048*(24201 + 253*sqrt(9165))**(S(1)/3) + 2273005839412*sqrt(9165)*(24201 + 253*sqrt(9165))**(S(1)/3)), x) assert f == Poly(0, x, domain='EX') def test_Poly_integrate(): assert Poly(x + 1).integrate() == Poly(x**2/2 + x) assert Poly(x + 1).integrate(x) == Poly(x**2/2 + x) assert Poly(x + 1).integrate((x, 1)) == Poly(x**2/2 + x) assert Poly(x*y + 1).integrate(x) == Poly(x**2*y/2 + x) assert Poly(x*y + 1).integrate(y) == Poly(x*y**2/2 + y) assert Poly(x*y + 1).integrate(x, x) == Poly(x**3*y/6 + x**2/2) assert Poly(x*y + 1).integrate(y, y) == Poly(x*y**3/6 + y**2/2) assert Poly(x*y + 1).integrate((x, 2)) == Poly(x**3*y/6 + x**2/2) assert Poly(x*y + 1).integrate((y, 2)) == Poly(x*y**3/6 + y**2/2) assert Poly(x*y + 1).integrate(x, y) == Poly(x**2*y**2/4 + x*y) assert Poly(x*y + 1).integrate(y, x) == Poly(x**2*y**2/4 + x*y) def test_Poly_diff(): assert Poly(x**2 + x).diff() == Poly(2*x + 1) assert Poly(x**2 + x).diff(x) == Poly(2*x + 1) assert Poly(x**2 + x).diff((x, 1)) == Poly(2*x + 1) assert Poly(x**2*y**2 + x*y).diff(x) == Poly(2*x*y**2 + y) assert Poly(x**2*y**2 + x*y).diff(y) == Poly(2*x**2*y + x) assert Poly(x**2*y**2 + x*y).diff(x, x) == Poly(2*y**2, x, y) assert Poly(x**2*y**2 + x*y).diff(y, y) == Poly(2*x**2, x, y) assert Poly(x**2*y**2 + x*y).diff((x, 2)) == Poly(2*y**2, x, y) assert Poly(x**2*y**2 + x*y).diff((y, 2)) == Poly(2*x**2, x, y) assert Poly(x**2*y**2 + x*y).diff(x, y) == Poly(4*x*y + 1) assert Poly(x**2*y**2 + x*y).diff(y, x) == Poly(4*x*y + 1) def test_issue_9585(): assert diff(Poly(x**2 + x)) == Poly(2*x + 1) assert diff(Poly(x**2 + x), x, evaluate=False) == \ Derivative(Poly(x**2 + x), x) assert Derivative(Poly(x**2 + x), x).doit() == Poly(2*x + 1) def test_Poly_eval(): assert Poly(0, x).eval(7) == 0 assert Poly(1, x).eval(7) == 1 assert Poly(x, x).eval(7) == 7 assert Poly(0, x).eval(0, 7) == 0 assert Poly(1, x).eval(0, 7) == 1 assert Poly(x, x).eval(0, 7) == 7 assert Poly(0, x).eval(x, 7) == 0 assert Poly(1, x).eval(x, 7) == 1 assert Poly(x, x).eval(x, 7) == 7 assert Poly(0, x).eval('x', 7) == 0 assert Poly(1, x).eval('x', 7) == 1 assert Poly(x, x).eval('x', 7) == 7 raises(PolynomialError, lambda: Poly(1, x).eval(1, 7)) raises(PolynomialError, lambda: Poly(1, x).eval(y, 7)) raises(PolynomialError, lambda: Poly(1, x).eval('y', 7)) assert Poly(123, x, y).eval(7) == Poly(123, y) assert Poly(2*y, x, y).eval(7) == Poly(2*y, y) assert Poly(x*y, x, y).eval(7) == Poly(7*y, y) assert Poly(123, x, y).eval(x, 7) == Poly(123, y) assert Poly(2*y, x, y).eval(x, 7) == Poly(2*y, y) assert Poly(x*y, x, y).eval(x, 7) == Poly(7*y, y) assert Poly(123, x, y).eval(y, 7) == Poly(123, x) assert Poly(2*y, x, y).eval(y, 7) == Poly(14, x) assert Poly(x*y, x, y).eval(y, 7) == Poly(7*x, x) assert Poly(x*y + y, x, y).eval({x: 7}) == Poly(8*y, y) assert Poly(x*y + y, x, y).eval({y: 7}) == Poly(7*x + 7, x) assert Poly(x*y + y, x, y).eval({x: 6, y: 7}) == 49 assert Poly(x*y + y, x, y).eval({x: 7, y: 6}) == 48 assert Poly(x*y + y, x, y).eval((6, 7)) == 49 assert Poly(x*y + y, x, y).eval([6, 7]) == 49 assert Poly(x + 1, domain='ZZ').eval(S.Half) == Rational(3, 2) assert Poly(x + 1, domain='ZZ').eval(sqrt(2)) == sqrt(2) + 1 raises(ValueError, lambda: Poly(x*y + y, x, y).eval((6, 7, 8))) raises(DomainError, lambda: Poly(x + 1, domain='ZZ').eval(S.Half, auto=False)) # issue 6344 alpha = Symbol('alpha') result = (2*alpha*z - 2*alpha + z**2 + 3)/(z**2 - 2*z + 1) f = Poly(x**2 + (alpha - 1)*x - alpha + 1, x, domain='ZZ[alpha]') assert f.eval((z + 1)/(z - 1)) == result g = Poly(x**2 + (alpha - 1)*x - alpha + 1, x, y, domain='ZZ[alpha]') assert g.eval((z + 1)/(z - 1)) == Poly(result, y, domain='ZZ(alpha,z)') def test_Poly___call__(): f = Poly(2*x*y + 3*x + y + 2*z) assert f(2) == Poly(5*y + 2*z + 6) assert f(2, 5) == Poly(2*z + 31) assert f(2, 5, 7) == 45 def test_parallel_poly_from_expr(): assert parallel_poly_from_expr( [x - 1, x**2 - 1], x)[0] == [Poly(x - 1, x), Poly(x**2 - 1, x)] assert parallel_poly_from_expr( [Poly(x - 1, x), x**2 - 1], x)[0] == [Poly(x - 1, x), Poly(x**2 - 1, x)] assert parallel_poly_from_expr( [x - 1, Poly(x**2 - 1, x)], x)[0] == [Poly(x - 1, x), Poly(x**2 - 1, x)] assert parallel_poly_from_expr([Poly( x - 1, x), Poly(x**2 - 1, x)], x)[0] == [Poly(x - 1, x), Poly(x**2 - 1, x)] assert parallel_poly_from_expr( [x - 1, x**2 - 1], x, y)[0] == [Poly(x - 1, x, y), Poly(x**2 - 1, x, y)] assert parallel_poly_from_expr([Poly( x - 1, x), x**2 - 1], x, y)[0] == [Poly(x - 1, x, y), Poly(x**2 - 1, x, y)] assert parallel_poly_from_expr([x - 1, Poly( x**2 - 1, x)], x, y)[0] == [Poly(x - 1, x, y), Poly(x**2 - 1, x, y)] assert parallel_poly_from_expr([Poly(x - 1, x), Poly( x**2 - 1, x)], x, y)[0] == [Poly(x - 1, x, y), Poly(x**2 - 1, x, y)] assert parallel_poly_from_expr( [x - 1, x**2 - 1])[0] == [Poly(x - 1, x), Poly(x**2 - 1, x)] assert parallel_poly_from_expr( [Poly(x - 1, x), x**2 - 1])[0] == [Poly(x - 1, x), Poly(x**2 - 1, x)] assert parallel_poly_from_expr( [x - 1, Poly(x**2 - 1, x)])[0] == [Poly(x - 1, x), Poly(x**2 - 1, x)] assert parallel_poly_from_expr( [Poly(x - 1, x), Poly(x**2 - 1, x)])[0] == [Poly(x - 1, x), Poly(x**2 - 1, x)] assert parallel_poly_from_expr( [1, x**2 - 1])[0] == [Poly(1, x), Poly(x**2 - 1, x)] assert parallel_poly_from_expr( [1, x**2 - 1])[0] == [Poly(1, x), Poly(x**2 - 1, x)] assert parallel_poly_from_expr( [1, Poly(x**2 - 1, x)])[0] == [Poly(1, x), Poly(x**2 - 1, x)] assert parallel_poly_from_expr( [1, Poly(x**2 - 1, x)])[0] == [Poly(1, x), Poly(x**2 - 1, x)] assert parallel_poly_from_expr( [x**2 - 1, 1])[0] == [Poly(x**2 - 1, x), Poly(1, x)] assert parallel_poly_from_expr( [x**2 - 1, 1])[0] == [Poly(x**2 - 1, x), Poly(1, x)] assert parallel_poly_from_expr( [Poly(x**2 - 1, x), 1])[0] == [Poly(x**2 - 1, x), Poly(1, x)] assert parallel_poly_from_expr( [Poly(x**2 - 1, x), 1])[0] == [Poly(x**2 - 1, x), Poly(1, x)] assert parallel_poly_from_expr([Poly(x, x, y), Poly(y, x, y)], x, y, order='lex')[0] == \ [Poly(x, x, y, domain='ZZ'), Poly(y, x, y, domain='ZZ')] raises(PolificationFailed, lambda: parallel_poly_from_expr([0, 1])) def test_pdiv(): f, g = x**2 - y**2, x - y q, r = x + y, 0 F, G, Q, R = [ Poly(h, x, y) for h in (f, g, q, r) ] assert F.pdiv(G) == (Q, R) assert F.prem(G) == R assert F.pquo(G) == Q assert F.pexquo(G) == Q assert pdiv(f, g) == (q, r) assert prem(f, g) == r assert pquo(f, g) == q assert pexquo(f, g) == q assert pdiv(f, g, x, y) == (q, r) assert prem(f, g, x, y) == r assert pquo(f, g, x, y) == q assert pexquo(f, g, x, y) == q assert pdiv(f, g, (x, y)) == (q, r) assert prem(f, g, (x, y)) == r assert pquo(f, g, (x, y)) == q assert pexquo(f, g, (x, y)) == q assert pdiv(F, G) == (Q, R) assert prem(F, G) == R assert pquo(F, G) == Q assert pexquo(F, G) == Q assert pdiv(f, g, polys=True) == (Q, R) assert prem(f, g, polys=True) == R assert pquo(f, g, polys=True) == Q assert pexquo(f, g, polys=True) == Q assert pdiv(F, G, polys=False) == (q, r) assert prem(F, G, polys=False) == r assert pquo(F, G, polys=False) == q assert pexquo(F, G, polys=False) == q raises(ComputationFailed, lambda: pdiv(4, 2)) raises(ComputationFailed, lambda: prem(4, 2)) raises(ComputationFailed, lambda: pquo(4, 2)) raises(ComputationFailed, lambda: pexquo(4, 2)) def test_div(): f, g = x**2 - y**2, x - y q, r = x + y, 0 F, G, Q, R = [ Poly(h, x, y) for h in (f, g, q, r) ] assert F.div(G) == (Q, R) assert F.rem(G) == R assert F.quo(G) == Q assert F.exquo(G) == Q assert div(f, g) == (q, r) assert rem(f, g) == r assert quo(f, g) == q assert exquo(f, g) == q assert div(f, g, x, y) == (q, r) assert rem(f, g, x, y) == r assert quo(f, g, x, y) == q assert exquo(f, g, x, y) == q assert div(f, g, (x, y)) == (q, r) assert rem(f, g, (x, y)) == r assert quo(f, g, (x, y)) == q assert exquo(f, g, (x, y)) == q assert div(F, G) == (Q, R) assert rem(F, G) == R assert quo(F, G) == Q assert exquo(F, G) == Q assert div(f, g, polys=True) == (Q, R) assert rem(f, g, polys=True) == R assert quo(f, g, polys=True) == Q assert exquo(f, g, polys=True) == Q assert div(F, G, polys=False) == (q, r) assert rem(F, G, polys=False) == r assert quo(F, G, polys=False) == q assert exquo(F, G, polys=False) == q raises(ComputationFailed, lambda: div(4, 2)) raises(ComputationFailed, lambda: rem(4, 2)) raises(ComputationFailed, lambda: quo(4, 2)) raises(ComputationFailed, lambda: exquo(4, 2)) f, g = x**2 + 1, 2*x - 4 qz, rz = 0, x**2 + 1 qq, rq = x/2 + 1, 5 assert div(f, g) == (qq, rq) assert div(f, g, auto=True) == (qq, rq) assert div(f, g, auto=False) == (qz, rz) assert div(f, g, domain=ZZ) == (qz, rz) assert div(f, g, domain=QQ) == (qq, rq) assert div(f, g, domain=ZZ, auto=True) == (qq, rq) assert div(f, g, domain=ZZ, auto=False) == (qz, rz) assert div(f, g, domain=QQ, auto=True) == (qq, rq) assert div(f, g, domain=QQ, auto=False) == (qq, rq) assert rem(f, g) == rq assert rem(f, g, auto=True) == rq assert rem(f, g, auto=False) == rz assert rem(f, g, domain=ZZ) == rz assert rem(f, g, domain=QQ) == rq assert rem(f, g, domain=ZZ, auto=True) == rq assert rem(f, g, domain=ZZ, auto=False) == rz assert rem(f, g, domain=QQ, auto=True) == rq assert rem(f, g, domain=QQ, auto=False) == rq assert quo(f, g) == qq assert quo(f, g, auto=True) == qq assert quo(f, g, auto=False) == qz assert quo(f, g, domain=ZZ) == qz assert quo(f, g, domain=QQ) == qq assert quo(f, g, domain=ZZ, auto=True) == qq assert quo(f, g, domain=ZZ, auto=False) == qz assert quo(f, g, domain=QQ, auto=True) == qq assert quo(f, g, domain=QQ, auto=False) == qq f, g, q = x**2, 2*x, x/2 assert exquo(f, g) == q assert exquo(f, g, auto=True) == q raises(ExactQuotientFailed, lambda: exquo(f, g, auto=False)) raises(ExactQuotientFailed, lambda: exquo(f, g, domain=ZZ)) assert exquo(f, g, domain=QQ) == q assert exquo(f, g, domain=ZZ, auto=True) == q raises(ExactQuotientFailed, lambda: exquo(f, g, domain=ZZ, auto=False)) assert exquo(f, g, domain=QQ, auto=True) == q assert exquo(f, g, domain=QQ, auto=False) == q f, g = Poly(x**2), Poly(x) q, r = f.div(g) assert q.get_domain().is_ZZ and r.get_domain().is_ZZ r = f.rem(g) assert r.get_domain().is_ZZ q = f.quo(g) assert q.get_domain().is_ZZ q = f.exquo(g) assert q.get_domain().is_ZZ f, g = Poly(x+y, x), Poly(2*x+y, x) q, r = f.div(g) assert q.get_domain().is_Frac and r.get_domain().is_Frac # https://github.com/sympy/sympy/issues/19579 p = Poly(2+3*I, x, domain=ZZ_I) q = Poly(1-I, x, domain=ZZ_I) assert p.div(q, auto=False) == \ (Poly(0, x, domain='ZZ_I'), Poly(2 + 3*I, x, domain='ZZ_I')) assert p.div(q, auto=True) == \ (Poly(-S(1)/2 + 5*I/2, x, domain='QQ_I'), Poly(0, x, domain='QQ_I')) def test_issue_7864(): q, r = div(a, .408248290463863*a) assert abs(q - 2.44948974278318) < 1e-14 assert r == 0 def test_gcdex(): f, g = 2*x, x**2 - 16 s, t, h = x/32, Rational(-1, 16), 1 F, G, S, T, H = [ Poly(u, x, domain='QQ') for u in (f, g, s, t, h) ] assert F.half_gcdex(G) == (S, H) assert F.gcdex(G) == (S, T, H) assert F.invert(G) == S assert half_gcdex(f, g) == (s, h) assert gcdex(f, g) == (s, t, h) assert invert(f, g) == s assert half_gcdex(f, g, x) == (s, h) assert gcdex(f, g, x) == (s, t, h) assert invert(f, g, x) == s assert half_gcdex(f, g, (x,)) == (s, h) assert gcdex(f, g, (x,)) == (s, t, h) assert invert(f, g, (x,)) == s assert half_gcdex(F, G) == (S, H) assert gcdex(F, G) == (S, T, H) assert invert(F, G) == S assert half_gcdex(f, g, polys=True) == (S, H) assert gcdex(f, g, polys=True) == (S, T, H) assert invert(f, g, polys=True) == S assert half_gcdex(F, G, polys=False) == (s, h) assert gcdex(F, G, polys=False) == (s, t, h) assert invert(F, G, polys=False) == s assert half_gcdex(100, 2004) == (-20, 4) assert gcdex(100, 2004) == (-20, 1, 4) assert invert(3, 7) == 5 raises(DomainError, lambda: half_gcdex(x + 1, 2*x + 1, auto=False)) raises(DomainError, lambda: gcdex(x + 1, 2*x + 1, auto=False)) raises(DomainError, lambda: invert(x + 1, 2*x + 1, auto=False)) def test_revert(): f = Poly(1 - x**2/2 + x**4/24 - x**6/720) g = Poly(61*x**6/720 + 5*x**4/24 + x**2/2 + 1) assert f.revert(8) == g def test_subresultants(): f, g, h = x**2 - 2*x + 1, x**2 - 1, 2*x - 2 F, G, H = Poly(f), Poly(g), Poly(h) assert F.subresultants(G) == [F, G, H] assert subresultants(f, g) == [f, g, h] assert subresultants(f, g, x) == [f, g, h] assert subresultants(f, g, (x,)) == [f, g, h] assert subresultants(F, G) == [F, G, H] assert subresultants(f, g, polys=True) == [F, G, H] assert subresultants(F, G, polys=False) == [f, g, h] raises(ComputationFailed, lambda: subresultants(4, 2)) def test_resultant(): f, g, h = x**2 - 2*x + 1, x**2 - 1, 0 F, G = Poly(f), Poly(g) assert F.resultant(G) == h assert resultant(f, g) == h assert resultant(f, g, x) == h assert resultant(f, g, (x,)) == h assert resultant(F, G) == h assert resultant(f, g, polys=True) == h assert resultant(F, G, polys=False) == h assert resultant(f, g, includePRS=True) == (h, [f, g, 2*x - 2]) f, g, h = x - a, x - b, a - b F, G, H = Poly(f), Poly(g), Poly(h) assert F.resultant(G) == H assert resultant(f, g) == h assert resultant(f, g, x) == h assert resultant(f, g, (x,)) == h assert resultant(F, G) == H assert resultant(f, g, polys=True) == H assert resultant(F, G, polys=False) == h raises(ComputationFailed, lambda: resultant(4, 2)) def test_discriminant(): f, g = x**3 + 3*x**2 + 9*x - 13, -11664 F = Poly(f) assert F.discriminant() == g assert discriminant(f) == g assert discriminant(f, x) == g assert discriminant(f, (x,)) == g assert discriminant(F) == g assert discriminant(f, polys=True) == g assert discriminant(F, polys=False) == g f, g = a*x**2 + b*x + c, b**2 - 4*a*c F, G = Poly(f), Poly(g) assert F.discriminant() == G assert discriminant(f) == g assert discriminant(f, x, a, b, c) == g assert discriminant(f, (x, a, b, c)) == g assert discriminant(F) == G assert discriminant(f, polys=True) == G assert discriminant(F, polys=False) == g raises(ComputationFailed, lambda: discriminant(4)) def test_dispersion(): # We test only the API here. For more mathematical # tests see the dedicated test file. fp = poly((x + 1)*(x + 2), x) assert sorted(fp.dispersionset()) == [0, 1] assert fp.dispersion() == 1 fp = poly(x**4 - 3*x**2 + 1, x) gp = fp.shift(-3) assert sorted(fp.dispersionset(gp)) == [2, 3, 4] assert fp.dispersion(gp) == 4 def test_gcd_list(): F = [x**3 - 1, x**2 - 1, x**2 - 3*x + 2] assert gcd_list(F) == x - 1 assert gcd_list(F, polys=True) == Poly(x - 1) assert gcd_list([]) == 0 assert gcd_list([1, 2]) == 1 assert gcd_list([4, 6, 8]) == 2 assert gcd_list([x*(y + 42) - x*y - x*42]) == 0 gcd = gcd_list([], x) assert gcd.is_Number and gcd is S.Zero gcd = gcd_list([], x, polys=True) assert gcd.is_Poly and gcd.is_zero a = sqrt(2) assert gcd_list([a, -a]) == gcd_list([-a, a]) == a raises(ComputationFailed, lambda: gcd_list([], polys=True)) def test_lcm_list(): F = [x**3 - 1, x**2 - 1, x**2 - 3*x + 2] assert lcm_list(F) == x**5 - x**4 - 2*x**3 - x**2 + x + 2 assert lcm_list(F, polys=True) == Poly(x**5 - x**4 - 2*x**3 - x**2 + x + 2) assert lcm_list([]) == 1 assert lcm_list([1, 2]) == 2 assert lcm_list([4, 6, 8]) == 24 assert lcm_list([x*(y + 42) - x*y - x*42]) == 0 lcm = lcm_list([], x) assert lcm.is_Number and lcm is S.One lcm = lcm_list([], x, polys=True) assert lcm.is_Poly and lcm.is_one raises(ComputationFailed, lambda: lcm_list([], polys=True)) def test_gcd(): f, g = x**3 - 1, x**2 - 1 s, t = x**2 + x + 1, x + 1 h, r = x - 1, x**4 + x**3 - x - 1 F, G, S, T, H, R = [ Poly(u) for u in (f, g, s, t, h, r) ] assert F.cofactors(G) == (H, S, T) assert F.gcd(G) == H assert F.lcm(G) == R assert cofactors(f, g) == (h, s, t) assert gcd(f, g) == h assert lcm(f, g) == r assert cofactors(f, g, x) == (h, s, t) assert gcd(f, g, x) == h assert lcm(f, g, x) == r assert cofactors(f, g, (x,)) == (h, s, t) assert gcd(f, g, (x,)) == h assert lcm(f, g, (x,)) == r assert cofactors(F, G) == (H, S, T) assert gcd(F, G) == H assert lcm(F, G) == R assert cofactors(f, g, polys=True) == (H, S, T) assert gcd(f, g, polys=True) == H assert lcm(f, g, polys=True) == R assert cofactors(F, G, polys=False) == (h, s, t) assert gcd(F, G, polys=False) == h assert lcm(F, G, polys=False) == r f, g = 1.0*x**2 - 1.0, 1.0*x - 1.0 h, s, t = g, 1.0*x + 1.0, 1.0 assert cofactors(f, g) == (h, s, t) assert gcd(f, g) == h assert lcm(f, g) == f f, g = 1.0*x**2 - 1.0, 1.0*x - 1.0 h, s, t = g, 1.0*x + 1.0, 1.0 assert cofactors(f, g) == (h, s, t) assert gcd(f, g) == h assert lcm(f, g) == f assert cofactors(8, 6) == (2, 4, 3) assert gcd(8, 6) == 2 assert lcm(8, 6) == 24 f, g = x**2 - 3*x - 4, x**3 - 4*x**2 + x - 4 l = x**4 - 3*x**3 - 3*x**2 - 3*x - 4 h, s, t = x - 4, x + 1, x**2 + 1 assert cofactors(f, g, modulus=11) == (h, s, t) assert gcd(f, g, modulus=11) == h assert lcm(f, g, modulus=11) == l f, g = x**2 + 8*x + 7, x**3 + 7*x**2 + x + 7 l = x**4 + 8*x**3 + 8*x**2 + 8*x + 7 h, s, t = x + 7, x + 1, x**2 + 1 assert cofactors(f, g, modulus=11, symmetric=False) == (h, s, t) assert gcd(f, g, modulus=11, symmetric=False) == h assert lcm(f, g, modulus=11, symmetric=False) == l a, b = sqrt(2), -sqrt(2) assert gcd(a, b) == gcd(b, a) == sqrt(2) a, b = sqrt(-2), -sqrt(-2) assert gcd(a, b) == gcd(b, a) == sqrt(2) assert gcd(Poly(x - 2, x), Poly(I*x, x)) == Poly(1, x, domain=ZZ_I) raises(TypeError, lambda: gcd(x)) raises(TypeError, lambda: lcm(x)) def test_gcd_numbers_vs_polys(): assert isinstance(gcd(3, 9), Integer) assert isinstance(gcd(3*x, 9), Integer) assert gcd(3, 9) == 3 assert gcd(3*x, 9) == 3 assert isinstance(gcd(Rational(3, 2), Rational(9, 4)), Rational) assert isinstance(gcd(Rational(3, 2)*x, Rational(9, 4)), Rational) assert gcd(Rational(3, 2), Rational(9, 4)) == Rational(3, 4) assert gcd(Rational(3, 2)*x, Rational(9, 4)) == 1 assert isinstance(gcd(3.0, 9.0), Float) assert isinstance(gcd(3.0*x, 9.0), Float) assert gcd(3.0, 9.0) == 1.0 assert gcd(3.0*x, 9.0) == 1.0 # partial fix of 20597 assert gcd(Mul(2, 3, evaluate=False), 2) == 2 def test_terms_gcd(): assert terms_gcd(1) == 1 assert terms_gcd(1, x) == 1 assert terms_gcd(x - 1) == x - 1 assert terms_gcd(-x - 1) == -x - 1 assert terms_gcd(2*x + 3) == 2*x + 3 assert terms_gcd(6*x + 4) == Mul(2, 3*x + 2, evaluate=False) assert terms_gcd(x**3*y + x*y**3) == x*y*(x**2 + y**2) assert terms_gcd(2*x**3*y + 2*x*y**3) == 2*x*y*(x**2 + y**2) assert terms_gcd(x**3*y/2 + x*y**3/2) == x*y/2*(x**2 + y**2) assert terms_gcd(x**3*y + 2*x*y**3) == x*y*(x**2 + 2*y**2) assert terms_gcd(2*x**3*y + 4*x*y**3) == 2*x*y*(x**2 + 2*y**2) assert terms_gcd(2*x**3*y/3 + 4*x*y**3/5) == x*y*Rational(2, 15)*(5*x**2 + 6*y**2) assert terms_gcd(2.0*x**3*y + 4.1*x*y**3) == x*y*(2.0*x**2 + 4.1*y**2) assert _aresame(terms_gcd(2.0*x + 3), 2.0*x + 3) assert terms_gcd((3 + 3*x)*(x + x*y), expand=False) == \ (3*x + 3)*(x*y + x) assert terms_gcd((3 + 3*x)*(x + x*sin(3 + 3*y)), expand=False, deep=True) == \ 3*x*(x + 1)*(sin(Mul(3, y + 1, evaluate=False)) + 1) assert terms_gcd(sin(x + x*y), deep=True) == \ sin(x*(y + 1)) eq = Eq(2*x, 2*y + 2*z*y) assert terms_gcd(eq) == Eq(2*x, 2*y*(z + 1)) assert terms_gcd(eq, deep=True) == Eq(2*x, 2*y*(z + 1)) raises(TypeError, lambda: terms_gcd(x < 2)) def test_trunc(): f, g = x**5 + 2*x**4 + 3*x**3 + 4*x**2 + 5*x + 6, x**5 - x**4 + x**2 - x F, G = Poly(f), Poly(g) assert F.trunc(3) == G assert trunc(f, 3) == g assert trunc(f, 3, x) == g assert trunc(f, 3, (x,)) == g assert trunc(F, 3) == G assert trunc(f, 3, polys=True) == G assert trunc(F, 3, polys=False) == g f, g = 6*x**5 + 5*x**4 + 4*x**3 + 3*x**2 + 2*x + 1, -x**4 + x**3 - x + 1 F, G = Poly(f), Poly(g) assert F.trunc(3) == G assert trunc(f, 3) == g assert trunc(f, 3, x) == g assert trunc(f, 3, (x,)) == g assert trunc(F, 3) == G assert trunc(f, 3, polys=True) == G assert trunc(F, 3, polys=False) == g f = Poly(x**2 + 2*x + 3, modulus=5) assert f.trunc(2) == Poly(x**2 + 1, modulus=5) def test_monic(): f, g = 2*x - 1, x - S.Half F, G = Poly(f, domain='QQ'), Poly(g) assert F.monic() == G assert monic(f) == g assert monic(f, x) == g assert monic(f, (x,)) == g assert monic(F) == G assert monic(f, polys=True) == G assert monic(F, polys=False) == g raises(ComputationFailed, lambda: monic(4)) assert monic(2*x**2 + 6*x + 4, auto=False) == x**2 + 3*x + 2 raises(ExactQuotientFailed, lambda: monic(2*x + 6*x + 1, auto=False)) assert monic(2.0*x**2 + 6.0*x + 4.0) == 1.0*x**2 + 3.0*x + 2.0 assert monic(2*x**2 + 3*x + 4, modulus=5) == x**2 - x + 2 def test_content(): f, F = 4*x + 2, Poly(4*x + 2) assert F.content() == 2 assert content(f) == 2 raises(ComputationFailed, lambda: content(4)) f = Poly(2*x, modulus=3) assert f.content() == 1 def test_primitive(): f, g = 4*x + 2, 2*x + 1 F, G = Poly(f), Poly(g) assert F.primitive() == (2, G) assert primitive(f) == (2, g) assert primitive(f, x) == (2, g) assert primitive(f, (x,)) == (2, g) assert primitive(F) == (2, G) assert primitive(f, polys=True) == (2, G) assert primitive(F, polys=False) == (2, g) raises(ComputationFailed, lambda: primitive(4)) f = Poly(2*x, modulus=3) g = Poly(2.0*x, domain=RR) assert f.primitive() == (1, f) assert g.primitive() == (1.0, g) assert primitive(S('-3*x/4 + y + 11/8')) == \ S('(1/8, -6*x + 8*y + 11)') def test_compose(): f = x**12 + 20*x**10 + 150*x**8 + 500*x**6 + 625*x**4 - 2*x**3 - 10*x + 9 g = x**4 - 2*x + 9 h = x**3 + 5*x F, G, H = map(Poly, (f, g, h)) assert G.compose(H) == F assert compose(g, h) == f assert compose(g, h, x) == f assert compose(g, h, (x,)) == f assert compose(G, H) == F assert compose(g, h, polys=True) == F assert compose(G, H, polys=False) == f assert F.decompose() == [G, H] assert decompose(f) == [g, h] assert decompose(f, x) == [g, h] assert decompose(f, (x,)) == [g, h] assert decompose(F) == [G, H] assert decompose(f, polys=True) == [G, H] assert decompose(F, polys=False) == [g, h] raises(ComputationFailed, lambda: compose(4, 2)) raises(ComputationFailed, lambda: decompose(4)) assert compose(x**2 - y**2, x - y, x, y) == x**2 - 2*x*y assert compose(x**2 - y**2, x - y, y, x) == -y**2 + 2*x*y def test_shift(): assert Poly(x**2 - 2*x + 1, x).shift(2) == Poly(x**2 + 2*x + 1, x) def test_transform(): # Also test that 3-way unification is done correctly assert Poly(x**2 - 2*x + 1, x).transform(Poly(x + 1), Poly(x - 1)) == \ Poly(4, x) == \ cancel((x - 1)**2*(x**2 - 2*x + 1).subs(x, (x + 1)/(x - 1))) assert Poly(x**2 - x/2 + 1, x).transform(Poly(x + 1), Poly(x - 1)) == \ Poly(3*x**2/2 + Rational(5, 2), x) == \ cancel((x - 1)**2*(x**2 - x/2 + 1).subs(x, (x + 1)/(x - 1))) assert Poly(x**2 - 2*x + 1, x).transform(Poly(x + S.Half), Poly(x - 1)) == \ Poly(Rational(9, 4), x) == \ cancel((x - 1)**2*(x**2 - 2*x + 1).subs(x, (x + S.Half)/(x - 1))) assert Poly(x**2 - 2*x + 1, x).transform(Poly(x + 1), Poly(x - S.Half)) == \ Poly(Rational(9, 4), x) == \ cancel((x - S.Half)**2*(x**2 - 2*x + 1).subs(x, (x + 1)/(x - S.Half))) # Unify ZZ, QQ, and RR assert Poly(x**2 - 2*x + 1, x).transform(Poly(x + 1.0), Poly(x - S.Half)) == \ Poly(Rational(9, 4), x, domain='RR') == \ cancel((x - S.Half)**2*(x**2 - 2*x + 1).subs(x, (x + 1.0)/(x - S.Half))) raises(ValueError, lambda: Poly(x*y).transform(Poly(x + 1), Poly(x - 1))) raises(ValueError, lambda: Poly(x).transform(Poly(y + 1), Poly(x - 1))) raises(ValueError, lambda: Poly(x).transform(Poly(x + 1), Poly(y - 1))) raises(ValueError, lambda: Poly(x).transform(Poly(x*y + 1), Poly(x - 1))) raises(ValueError, lambda: Poly(x).transform(Poly(x + 1), Poly(x*y - 1))) def test_sturm(): f, F = x, Poly(x, domain='QQ') g, G = 1, Poly(1, x, domain='QQ') assert F.sturm() == [F, G] assert sturm(f) == [f, g] assert sturm(f, x) == [f, g] assert sturm(f, (x,)) == [f, g] assert sturm(F) == [F, G] assert sturm(f, polys=True) == [F, G] assert sturm(F, polys=False) == [f, g] raises(ComputationFailed, lambda: sturm(4)) raises(DomainError, lambda: sturm(f, auto=False)) f = Poly(S(1024)/(15625*pi**8)*x**5 - S(4096)/(625*pi**8)*x**4 + S(32)/(15625*pi**4)*x**3 - S(128)/(625*pi**4)*x**2 + Rational(1, 62500)*x - Rational(1, 625), x, domain='ZZ(pi)') assert sturm(f) == \ [Poly(x**3 - 100*x**2 + pi**4/64*x - 25*pi**4/16, x, domain='ZZ(pi)'), Poly(3*x**2 - 200*x + pi**4/64, x, domain='ZZ(pi)'), Poly((Rational(20000, 9) - pi**4/96)*x + 25*pi**4/18, x, domain='ZZ(pi)'), Poly((-3686400000000*pi**4 - 11520000*pi**8 - 9*pi**12)/(26214400000000 - 245760000*pi**4 + 576*pi**8), x, domain='ZZ(pi)')] def test_gff(): f = x**5 + 2*x**4 - x**3 - 2*x**2 assert Poly(f).gff_list() == [(Poly(x), 1), (Poly(x + 2), 4)] assert gff_list(f) == [(x, 1), (x + 2, 4)] raises(NotImplementedError, lambda: gff(f)) f = x*(x - 1)**3*(x - 2)**2*(x - 4)**2*(x - 5) assert Poly(f).gff_list() == [( Poly(x**2 - 5*x + 4), 1), (Poly(x**2 - 5*x + 4), 2), (Poly(x), 3)] assert gff_list(f) == [(x**2 - 5*x + 4, 1), (x**2 - 5*x + 4, 2), (x, 3)] raises(NotImplementedError, lambda: gff(f)) def test_norm(): a, b = sqrt(2), sqrt(3) f = Poly(a*x + b*y, x, y, extension=(a, b)) assert f.norm() == Poly(4*x**4 - 12*x**2*y**2 + 9*y**4, x, y, domain='QQ') def test_sqf_norm(): assert sqf_norm(x**2 - 2, extension=sqrt(3)) == \ (1, x**2 - 2*sqrt(3)*x + 1, x**4 - 10*x**2 + 1) assert sqf_norm(x**2 - 3, extension=sqrt(2)) == \ (1, x**2 - 2*sqrt(2)*x - 1, x**4 - 10*x**2 + 1) assert Poly(x**2 - 2, extension=sqrt(3)).sqf_norm() == \ (1, Poly(x**2 - 2*sqrt(3)*x + 1, x, extension=sqrt(3)), Poly(x**4 - 10*x**2 + 1, x, domain='QQ')) assert Poly(x**2 - 3, extension=sqrt(2)).sqf_norm() == \ (1, Poly(x**2 - 2*sqrt(2)*x - 1, x, extension=sqrt(2)), Poly(x**4 - 10*x**2 + 1, x, domain='QQ')) def test_sqf(): f = x**5 - x**3 - x**2 + 1 g = x**3 + 2*x**2 + 2*x + 1 h = x - 1 p = x**4 + x**3 - x - 1 F, G, H, P = map(Poly, (f, g, h, p)) assert F.sqf_part() == P assert sqf_part(f) == p assert sqf_part(f, x) == p assert sqf_part(f, (x,)) == p assert sqf_part(F) == P assert sqf_part(f, polys=True) == P assert sqf_part(F, polys=False) == p assert F.sqf_list() == (1, [(G, 1), (H, 2)]) assert sqf_list(f) == (1, [(g, 1), (h, 2)]) assert sqf_list(f, x) == (1, [(g, 1), (h, 2)]) assert sqf_list(f, (x,)) == (1, [(g, 1), (h, 2)]) assert sqf_list(F) == (1, [(G, 1), (H, 2)]) assert sqf_list(f, polys=True) == (1, [(G, 1), (H, 2)]) assert sqf_list(F, polys=False) == (1, [(g, 1), (h, 2)]) assert F.sqf_list_include() == [(G, 1), (H, 2)] raises(ComputationFailed, lambda: sqf_part(4)) assert sqf(1) == 1 assert sqf_list(1) == (1, []) assert sqf((2*x**2 + 2)**7) == 128*(x**2 + 1)**7 assert sqf(f) == g*h**2 assert sqf(f, x) == g*h**2 assert sqf(f, (x,)) == g*h**2 d = x**2 + y**2 assert sqf(f/d) == (g*h**2)/d assert sqf(f/d, x) == (g*h**2)/d assert sqf(f/d, (x,)) == (g*h**2)/d assert sqf(x - 1) == x - 1 assert sqf(-x - 1) == -x - 1 assert sqf(x - 1) == x - 1 assert sqf(6*x - 10) == Mul(2, 3*x - 5, evaluate=False) assert sqf((6*x - 10)/(3*x - 6)) == Rational(2, 3)*((3*x - 5)/(x - 2)) assert sqf(Poly(x**2 - 2*x + 1)) == (x - 1)**2 f = 3 + x - x*(1 + x) + x**2 assert sqf(f) == 3 f = (x**2 + 2*x + 1)**20000000000 assert sqf(f) == (x + 1)**40000000000 assert sqf_list(f) == (1, [(x + 1, 40000000000)]) def test_factor(): f = x**5 - x**3 - x**2 + 1 u = x + 1 v = x - 1 w = x**2 + x + 1 F, U, V, W = map(Poly, (f, u, v, w)) assert F.factor_list() == (1, [(U, 1), (V, 2), (W, 1)]) assert factor_list(f) == (1, [(u, 1), (v, 2), (w, 1)]) assert factor_list(f, x) == (1, [(u, 1), (v, 2), (w, 1)]) assert factor_list(f, (x,)) == (1, [(u, 1), (v, 2), (w, 1)]) assert factor_list(F) == (1, [(U, 1), (V, 2), (W, 1)]) assert factor_list(f, polys=True) == (1, [(U, 1), (V, 2), (W, 1)]) assert factor_list(F, polys=False) == (1, [(u, 1), (v, 2), (w, 1)]) assert F.factor_list_include() == [(U, 1), (V, 2), (W, 1)] assert factor_list(1) == (1, []) assert factor_list(6) == (6, []) assert factor_list(sqrt(3), x) == (sqrt(3), []) assert factor_list((-1)**x, x) == (1, [(-1, x)]) assert factor_list((2*x)**y, x) == (1, [(2, y), (x, y)]) assert factor_list(sqrt(x*y), x) == (1, [(x*y, S.Half)]) assert factor(6) == 6 and factor(6).is_Integer assert factor_list(3*x) == (3, [(x, 1)]) assert factor_list(3*x**2) == (3, [(x, 2)]) assert factor(3*x) == 3*x assert factor(3*x**2) == 3*x**2 assert factor((2*x**2 + 2)**7) == 128*(x**2 + 1)**7 assert factor(f) == u*v**2*w assert factor(f, x) == u*v**2*w assert factor(f, (x,)) == u*v**2*w g, p, q, r = x**2 - y**2, x - y, x + y, x**2 + 1 assert factor(f/g) == (u*v**2*w)/(p*q) assert factor(f/g, x) == (u*v**2*w)/(p*q) assert factor(f/g, (x,)) == (u*v**2*w)/(p*q) p = Symbol('p', positive=True) i = Symbol('i', integer=True) r = Symbol('r', real=True) assert factor(sqrt(x*y)).is_Pow is True assert factor(sqrt(3*x**2 - 3)) == sqrt(3)*sqrt((x - 1)*(x + 1)) assert factor(sqrt(3*x**2 + 3)) == sqrt(3)*sqrt(x**2 + 1) assert factor((y*x**2 - y)**i) == y**i*(x - 1)**i*(x + 1)**i assert factor((y*x**2 + y)**i) == y**i*(x**2 + 1)**i assert factor((y*x**2 - y)**t) == (y*(x - 1)*(x + 1))**t assert factor((y*x**2 + y)**t) == (y*(x**2 + 1))**t f = sqrt(expand((r**2 + 1)*(p + 1)*(p - 1)*(p - 2)**3)) g = sqrt((p - 2)**3*(p - 1))*sqrt(p + 1)*sqrt(r**2 + 1) assert factor(f) == g assert factor(g) == g g = (x - 1)**5*(r**2 + 1) f = sqrt(expand(g)) assert factor(f) == sqrt(g) f = Poly(sin(1)*x + 1, x, domain=EX) assert f.factor_list() == (1, [(f, 1)]) f = x**4 + 1 assert factor(f) == f assert factor(f, extension=I) == (x**2 - I)*(x**2 + I) assert factor(f, gaussian=True) == (x**2 - I)*(x**2 + I) assert factor( f, extension=sqrt(2)) == (x**2 + sqrt(2)*x + 1)*(x**2 - sqrt(2)*x + 1) assert factor(x**2 + 4*I*x - 4) == (x + 2*I)**2 f = x**2 + 2*I*x - 4 assert factor(f) == f f = 8192*x**2 + x*(22656 + 175232*I) - 921416 + 242313*I f_zzi = I*(x*(64 - 64*I) + 773 + 596*I)**2 f_qqi = 8192*(x + S(177)/128 + 1369*I/128)**2 assert factor(f) == f_zzi assert factor(f, domain=ZZ_I) == f_zzi assert factor(f, domain=QQ_I) == f_qqi f = x**2 + 2*sqrt(2)*x + 2 assert factor(f, extension=sqrt(2)) == (x + sqrt(2))**2 assert factor(f**3, extension=sqrt(2)) == (x + sqrt(2))**6 assert factor(x**2 - 2*y**2, extension=sqrt(2)) == \ (x + sqrt(2)*y)*(x - sqrt(2)*y) assert factor(2*x**2 - 4*y**2, extension=sqrt(2)) == \ 2*((x + sqrt(2)*y)*(x - sqrt(2)*y)) assert factor(x - 1) == x - 1 assert factor(-x - 1) == -x - 1 assert factor(x - 1) == x - 1 assert factor(6*x - 10) == Mul(2, 3*x - 5, evaluate=False) assert factor(x**11 + x + 1, modulus=65537, symmetric=True) == \ (x**2 + x + 1)*(x**9 - x**8 + x**6 - x**5 + x**3 - x** 2 + 1) assert factor(x**11 + x + 1, modulus=65537, symmetric=False) == \ (x**2 + x + 1)*(x**9 + 65536*x**8 + x**6 + 65536*x**5 + x**3 + 65536*x** 2 + 1) f = x/pi + x*sin(x)/pi g = y/(pi**2 + 2*pi + 1) + y*sin(x)/(pi**2 + 2*pi + 1) assert factor(f) == x*(sin(x) + 1)/pi assert factor(g) == y*(sin(x) + 1)/(pi + 1)**2 assert factor(Eq( x**2 + 2*x + 1, x**3 + 1)) == Eq((x + 1)**2, (x + 1)*(x**2 - x + 1)) f = (x**2 - 1)/(x**2 + 4*x + 4) assert factor(f) == (x + 1)*(x - 1)/(x + 2)**2 assert factor(f, x) == (x + 1)*(x - 1)/(x + 2)**2 f = 3 + x - x*(1 + x) + x**2 assert factor(f) == 3 assert factor(f, x) == 3 assert factor(1/(x**2 + 2*x + 1/x) - 1) == -((1 - x + 2*x**2 + x**3)/(1 + 2*x**2 + x**3)) assert factor(f, expand=False) == f raises(PolynomialError, lambda: factor(f, x, expand=False)) raises(FlagError, lambda: factor(x**2 - 1, polys=True)) assert factor([x, Eq(x**2 - y**2, Tuple(x**2 - z**2, 1/x + 1/y))]) == \ [x, Eq((x - y)*(x + y), Tuple((x - z)*(x + z), (x + y)/x/y))] assert not isinstance( Poly(x**3 + x + 1).factor_list()[1][0][0], PurePoly) is True assert isinstance( PurePoly(x**3 + x + 1).factor_list()[1][0][0], PurePoly) is True assert factor(sqrt(-x)) == sqrt(-x) # issue 5917 e = (-2*x*(-x + 1)*(x - 1)*(-x*(-x + 1)*(x - 1) - x*(x - 1)**2)*(x**2*(x - 1) - x*(x - 1) - x) - (-2*x**2*(x - 1)**2 - x*(-x + 1)*(-x*(-x + 1) + x*(x - 1)))*(x**2*(x - 1)**4 - x*(-x*(-x + 1)*(x - 1) - x*(x - 1)**2))) assert factor(e) == 0 # deep option assert factor(sin(x**2 + x) + x, deep=True) == sin(x*(x + 1)) + x assert factor(sin(x**2 + x)*x, deep=True) == sin(x*(x + 1))*x assert factor(sqrt(x**2)) == sqrt(x**2) # issue 13149 assert factor(expand((0.5*x+1)*(0.5*y+1))) == Mul(1.0, 0.5*x + 1.0, 0.5*y + 1.0, evaluate = False) assert factor(expand((0.5*x+0.5)**2)) == 0.25*(1.0*x + 1.0)**2 eq = x**2*y**2 + 11*x**2*y + 30*x**2 + 7*x*y**2 + 77*x*y + 210*x + 12*y**2 + 132*y + 360 assert factor(eq, x) == (x + 3)*(x + 4)*(y**2 + 11*y + 30) assert factor(eq, x, deep=True) == (x + 3)*(x + 4)*(y**2 + 11*y + 30) assert factor(eq, y, deep=True) == (y + 5)*(y + 6)*(x**2 + 7*x + 12) # fraction option f = 5*x + 3*exp(2 - 7*x) assert factor(f, deep=True) == factor(f, deep=True, fraction=True) assert factor(f, deep=True, fraction=False) == 5*x + 3*exp(2)*exp(-7*x) assert factor_list(x**3 - x*y**2, t, w, x) == ( 1, [(x, 1), (x - y, 1), (x + y, 1)]) def test_factor_large(): f = (x**2 + 4*x + 4)**10000000*(x**2 + 1)*(x**2 + 2*x + 1)**1234567 g = ((x**2 + 2*x + 1)**3000*y**2 + (x**2 + 2*x + 1)**3000*2*y + ( x**2 + 2*x + 1)**3000) assert factor(f) == (x + 2)**20000000*(x**2 + 1)*(x + 1)**2469134 assert factor(g) == (x + 1)**6000*(y + 1)**2 assert factor_list( f) == (1, [(x + 1, 2469134), (x + 2, 20000000), (x**2 + 1, 1)]) assert factor_list(g) == (1, [(y + 1, 2), (x + 1, 6000)]) f = (x**2 - y**2)**200000*(x**7 + 1) g = (x**2 + y**2)**200000*(x**7 + 1) assert factor(f) == \ (x + 1)*(x - y)**200000*(x + y)**200000*(x**6 - x**5 + x**4 - x**3 + x**2 - x + 1) assert factor(g, gaussian=True) == \ (x + 1)*(x - I*y)**200000*(x + I*y)**200000*(x**6 - x**5 + x**4 - x**3 + x**2 - x + 1) assert factor_list(f) == \ (1, [(x + 1, 1), (x - y, 200000), (x + y, 200000), (x**6 - x**5 + x**4 - x**3 + x**2 - x + 1, 1)]) assert factor_list(g, gaussian=True) == \ (1, [(x + 1, 1), (x - I*y, 200000), (x + I*y, 200000), ( x**6 - x**5 + x**4 - x**3 + x**2 - x + 1, 1)]) def test_factor_noeval(): assert factor(6*x - 10) == Mul(2, 3*x - 5, evaluate=False) assert factor((6*x - 10)/(3*x - 6)) == Mul(Rational(2, 3), 3*x - 5, 1/(x - 2)) def test_intervals(): assert intervals(0) == [] assert intervals(1) == [] assert intervals(x, sqf=True) == [(0, 0)] assert intervals(x) == [((0, 0), 1)] assert intervals(x**128) == [((0, 0), 128)] assert intervals([x**2, x**4]) == [((0, 0), {0: 2, 1: 4})] f = Poly((x*Rational(2, 5) - Rational(17, 3))*(4*x + Rational(1, 257))) assert f.intervals(sqf=True) == [(-1, 0), (14, 15)] assert f.intervals() == [((-1, 0), 1), ((14, 15), 1)] assert f.intervals(fast=True, sqf=True) == [(-1, 0), (14, 15)] assert f.intervals(fast=True) == [((-1, 0), 1), ((14, 15), 1)] assert f.intervals(eps=Rational(1, 10)) == f.intervals(eps=0.1) == \ [((Rational(-1, 258), 0), 1), ((Rational(85, 6), Rational(85, 6)), 1)] assert f.intervals(eps=Rational(1, 100)) == f.intervals(eps=0.01) == \ [((Rational(-1, 258), 0), 1), ((Rational(85, 6), Rational(85, 6)), 1)] assert f.intervals(eps=Rational(1, 1000)) == f.intervals(eps=0.001) == \ [((Rational(-1, 1002), 0), 1), ((Rational(85, 6), Rational(85, 6)), 1)] assert f.intervals(eps=Rational(1, 10000)) == f.intervals(eps=0.0001) == \ [((Rational(-1, 1028), Rational(-1, 1028)), 1), ((Rational(85, 6), Rational(85, 6)), 1)] f = (x*Rational(2, 5) - Rational(17, 3))*(4*x + Rational(1, 257)) assert intervals(f, sqf=True) == [(-1, 0), (14, 15)] assert intervals(f) == [((-1, 0), 1), ((14, 15), 1)] assert intervals(f, eps=Rational(1, 10)) == intervals(f, eps=0.1) == \ [((Rational(-1, 258), 0), 1), ((Rational(85, 6), Rational(85, 6)), 1)] assert intervals(f, eps=Rational(1, 100)) == intervals(f, eps=0.01) == \ [((Rational(-1, 258), 0), 1), ((Rational(85, 6), Rational(85, 6)), 1)] assert intervals(f, eps=Rational(1, 1000)) == intervals(f, eps=0.001) == \ [((Rational(-1, 1002), 0), 1), ((Rational(85, 6), Rational(85, 6)), 1)] assert intervals(f, eps=Rational(1, 10000)) == intervals(f, eps=0.0001) == \ [((Rational(-1, 1028), Rational(-1, 1028)), 1), ((Rational(85, 6), Rational(85, 6)), 1)] f = Poly((x**2 - 2)*(x**2 - 3)**7*(x + 1)*(7*x + 3)**3) assert f.intervals() == \ [((-2, Rational(-3, 2)), 7), ((Rational(-3, 2), -1), 1), ((-1, -1), 1), ((-1, 0), 3), ((1, Rational(3, 2)), 1), ((Rational(3, 2), 2), 7)] assert intervals([x**5 - 200, x**5 - 201]) == \ [((Rational(75, 26), Rational(101, 35)), {0: 1}), ((Rational(309, 107), Rational(26, 9)), {1: 1})] assert intervals([x**5 - 200, x**5 - 201], fast=True) == \ [((Rational(75, 26), Rational(101, 35)), {0: 1}), ((Rational(309, 107), Rational(26, 9)), {1: 1})] assert intervals([x**2 - 200, x**2 - 201]) == \ [((Rational(-71, 5), Rational(-85, 6)), {1: 1}), ((Rational(-85, 6), -14), {0: 1}), ((14, Rational(85, 6)), {0: 1}), ((Rational(85, 6), Rational(71, 5)), {1: 1})] assert intervals([x + 1, x + 2, x - 1, x + 1, 1, x - 1, x - 1, (x - 2)**2]) == \ [((-2, -2), {1: 1}), ((-1, -1), {0: 1, 3: 1}), ((1, 1), {2: 1, 5: 1, 6: 1}), ((2, 2), {7: 2})] f, g, h = x**2 - 2, x**4 - 4*x**2 + 4, x - 1 assert intervals(f, inf=Rational(7, 4), sqf=True) == [] assert intervals(f, inf=Rational(7, 5), sqf=True) == [(Rational(7, 5), Rational(3, 2))] assert intervals(f, sup=Rational(7, 4), sqf=True) == [(-2, -1), (1, Rational(3, 2))] assert intervals(f, sup=Rational(7, 5), sqf=True) == [(-2, -1)] assert intervals(g, inf=Rational(7, 4)) == [] assert intervals(g, inf=Rational(7, 5)) == [((Rational(7, 5), Rational(3, 2)), 2)] assert intervals(g, sup=Rational(7, 4)) == [((-2, -1), 2), ((1, Rational(3, 2)), 2)] assert intervals(g, sup=Rational(7, 5)) == [((-2, -1), 2)] assert intervals([g, h], inf=Rational(7, 4)) == [] assert intervals([g, h], inf=Rational(7, 5)) == [((Rational(7, 5), Rational(3, 2)), {0: 2})] assert intervals([g, h], sup=S( 7)/4) == [((-2, -1), {0: 2}), ((1, 1), {1: 1}), ((1, Rational(3, 2)), {0: 2})] assert intervals( [g, h], sup=Rational(7, 5)) == [((-2, -1), {0: 2}), ((1, 1), {1: 1})] assert intervals([x + 2, x**2 - 2]) == \ [((-2, -2), {0: 1}), ((-2, -1), {1: 1}), ((1, 2), {1: 1})] assert intervals([x + 2, x**2 - 2], strict=True) == \ [((-2, -2), {0: 1}), ((Rational(-3, 2), -1), {1: 1}), ((1, 2), {1: 1})] f = 7*z**4 - 19*z**3 + 20*z**2 + 17*z + 20 assert intervals(f) == [] real_part, complex_part = intervals(f, all=True, sqf=True) assert real_part == [] assert all(re(a) < re(r) < re(b) and im( a) < im(r) < im(b) for (a, b), r in zip(complex_part, nroots(f))) assert complex_part == [(Rational(-40, 7) - I*40/7, 0), (Rational(-40, 7), I*40/7), (I*Rational(-40, 7), Rational(40, 7)), (0, Rational(40, 7) + I*40/7)] real_part, complex_part = intervals(f, all=True, sqf=True, eps=Rational(1, 10)) assert real_part == [] assert all(re(a) < re(r) < re(b) and im( a) < im(r) < im(b) for (a, b), r in zip(complex_part, nroots(f))) raises(ValueError, lambda: intervals(x**2 - 2, eps=10**-100000)) raises(ValueError, lambda: Poly(x**2 - 2).intervals(eps=10**-100000)) raises( ValueError, lambda: intervals([x**2 - 2, x**2 - 3], eps=10**-100000)) def test_refine_root(): f = Poly(x**2 - 2) assert f.refine_root(1, 2, steps=0) == (1, 2) assert f.refine_root(-2, -1, steps=0) == (-2, -1) assert f.refine_root(1, 2, steps=None) == (1, Rational(3, 2)) assert f.refine_root(-2, -1, steps=None) == (Rational(-3, 2), -1) assert f.refine_root(1, 2, steps=1) == (1, Rational(3, 2)) assert f.refine_root(-2, -1, steps=1) == (Rational(-3, 2), -1) assert f.refine_root(1, 2, steps=1, fast=True) == (1, Rational(3, 2)) assert f.refine_root(-2, -1, steps=1, fast=True) == (Rational(-3, 2), -1) assert f.refine_root(1, 2, eps=Rational(1, 100)) == (Rational(24, 17), Rational(17, 12)) assert f.refine_root(1, 2, eps=1e-2) == (Rational(24, 17), Rational(17, 12)) raises(PolynomialError, lambda: (f**2).refine_root(1, 2, check_sqf=True)) raises(RefinementFailed, lambda: (f**2).refine_root(1, 2)) raises(RefinementFailed, lambda: (f**2).refine_root(2, 3)) f = x**2 - 2 assert refine_root(f, 1, 2, steps=1) == (1, Rational(3, 2)) assert refine_root(f, -2, -1, steps=1) == (Rational(-3, 2), -1) assert refine_root(f, 1, 2, steps=1, fast=True) == (1, Rational(3, 2)) assert refine_root(f, -2, -1, steps=1, fast=True) == (Rational(-3, 2), -1) assert refine_root(f, 1, 2, eps=Rational(1, 100)) == (Rational(24, 17), Rational(17, 12)) assert refine_root(f, 1, 2, eps=1e-2) == (Rational(24, 17), Rational(17, 12)) raises(PolynomialError, lambda: refine_root(1, 7, 8, eps=Rational(1, 100))) raises(ValueError, lambda: Poly(f).refine_root(1, 2, eps=10**-100000)) raises(ValueError, lambda: refine_root(f, 1, 2, eps=10**-100000)) def test_count_roots(): assert count_roots(x**2 - 2) == 2 assert count_roots(x**2 - 2, inf=-oo) == 2 assert count_roots(x**2 - 2, sup=+oo) == 2 assert count_roots(x**2 - 2, inf=-oo, sup=+oo) == 2 assert count_roots(x**2 - 2, inf=-2) == 2 assert count_roots(x**2 - 2, inf=-1) == 1 assert count_roots(x**2 - 2, sup=1) == 1 assert count_roots(x**2 - 2, sup=2) == 2 assert count_roots(x**2 - 2, inf=-1, sup=1) == 0 assert count_roots(x**2 - 2, inf=-2, sup=2) == 2 assert count_roots(x**2 - 2, inf=-1, sup=1) == 0 assert count_roots(x**2 - 2, inf=-2, sup=2) == 2 assert count_roots(x**2 + 2) == 0 assert count_roots(x**2 + 2, inf=-2*I) == 2 assert count_roots(x**2 + 2, sup=+2*I) == 2 assert count_roots(x**2 + 2, inf=-2*I, sup=+2*I) == 2 assert count_roots(x**2 + 2, inf=0) == 0 assert count_roots(x**2 + 2, sup=0) == 0 assert count_roots(x**2 + 2, inf=-I) == 1 assert count_roots(x**2 + 2, sup=+I) == 1 assert count_roots(x**2 + 2, inf=+I/2, sup=+I) == 0 assert count_roots(x**2 + 2, inf=-I, sup=-I/2) == 0 raises(PolynomialError, lambda: count_roots(1)) def test_Poly_root(): f = Poly(2*x**3 - 7*x**2 + 4*x + 4) assert f.root(0) == Rational(-1, 2) assert f.root(1) == 2 assert f.root(2) == 2 raises(IndexError, lambda: f.root(3)) assert Poly(x**5 + x + 1).root(0) == rootof(x**3 - x**2 + 1, 0) def test_real_roots(): assert real_roots(x) == [0] assert real_roots(x, multiple=False) == [(0, 1)] assert real_roots(x**3) == [0, 0, 0] assert real_roots(x**3, multiple=False) == [(0, 3)] assert real_roots(x*(x**3 + x + 3)) == [rootof(x**3 + x + 3, 0), 0] assert real_roots(x*(x**3 + x + 3), multiple=False) == [(rootof( x**3 + x + 3, 0), 1), (0, 1)] assert real_roots( x**3*(x**3 + x + 3)) == [rootof(x**3 + x + 3, 0), 0, 0, 0] assert real_roots(x**3*(x**3 + x + 3), multiple=False) == [(rootof( x**3 + x + 3, 0), 1), (0, 3)] f = 2*x**3 - 7*x**2 + 4*x + 4 g = x**3 + x + 1 assert Poly(f).real_roots() == [Rational(-1, 2), 2, 2] assert Poly(g).real_roots() == [rootof(g, 0)] def test_all_roots(): f = 2*x**3 - 7*x**2 + 4*x + 4 g = x**3 + x + 1 assert Poly(f).all_roots() == [Rational(-1, 2), 2, 2] assert Poly(g).all_roots() == [rootof(g, 0), rootof(g, 1), rootof(g, 2)] def test_nroots(): assert Poly(0, x).nroots() == [] assert Poly(1, x).nroots() == [] assert Poly(x**2 - 1, x).nroots() == [-1.0, 1.0] assert Poly(x**2 + 1, x).nroots() == [-1.0*I, 1.0*I] roots = Poly(x**2 - 1, x).nroots() assert roots == [-1.0, 1.0] roots = Poly(x**2 + 1, x).nroots() assert roots == [-1.0*I, 1.0*I] roots = Poly(x**2/3 - Rational(1, 3), x).nroots() assert roots == [-1.0, 1.0] roots = Poly(x**2/3 + Rational(1, 3), x).nroots() assert roots == [-1.0*I, 1.0*I] assert Poly(x**2 + 2*I, x).nroots() == [-1.0 + 1.0*I, 1.0 - 1.0*I] assert Poly( x**2 + 2*I, x, extension=I).nroots() == [-1.0 + 1.0*I, 1.0 - 1.0*I] assert Poly(0.2*x + 0.1).nroots() == [-0.5] roots = nroots(x**5 + x + 1, n=5) eps = Float("1e-5") assert re(roots[0]).epsilon_eq(-0.75487, eps) is S.true assert im(roots[0]) == 0.0 assert re(roots[1]) == -0.5 assert im(roots[1]).epsilon_eq(-0.86602, eps) is S.true assert re(roots[2]) == -0.5 assert im(roots[2]).epsilon_eq(+0.86602, eps) is S.true assert re(roots[3]).epsilon_eq(+0.87743, eps) is S.true assert im(roots[3]).epsilon_eq(-0.74486, eps) is S.true assert re(roots[4]).epsilon_eq(+0.87743, eps) is S.true assert im(roots[4]).epsilon_eq(+0.74486, eps) is S.true eps = Float("1e-6") assert re(roots[0]).epsilon_eq(-0.75487, eps) is S.false assert im(roots[0]) == 0.0 assert re(roots[1]) == -0.5 assert im(roots[1]).epsilon_eq(-0.86602, eps) is S.false assert re(roots[2]) == -0.5 assert im(roots[2]).epsilon_eq(+0.86602, eps) is S.false assert re(roots[3]).epsilon_eq(+0.87743, eps) is S.false assert im(roots[3]).epsilon_eq(-0.74486, eps) is S.false assert re(roots[4]).epsilon_eq(+0.87743, eps) is S.false assert im(roots[4]).epsilon_eq(+0.74486, eps) is S.false raises(DomainError, lambda: Poly(x + y, x).nroots()) raises(MultivariatePolynomialError, lambda: Poly(x + y).nroots()) assert nroots(x**2 - 1) == [-1.0, 1.0] roots = nroots(x**2 - 1) assert roots == [-1.0, 1.0] assert nroots(x + I) == [-1.0*I] assert nroots(x + 2*I) == [-2.0*I] raises(PolynomialError, lambda: nroots(0)) # issue 8296 f = Poly(x**4 - 1) assert f.nroots(2) == [w.n(2) for w in f.all_roots()] assert str(Poly(x**16 + 32*x**14 + 508*x**12 + 5440*x**10 + 39510*x**8 + 204320*x**6 + 755548*x**4 + 1434496*x**2 + 877969).nroots(2)) == ('[-1.7 - 1.9*I, -1.7 + 1.9*I, -1.7 ' '- 2.5*I, -1.7 + 2.5*I, -1.0*I, 1.0*I, -1.7*I, 1.7*I, -2.8*I, ' '2.8*I, -3.4*I, 3.4*I, 1.7 - 1.9*I, 1.7 + 1.9*I, 1.7 - 2.5*I, ' '1.7 + 2.5*I]') assert str(Poly(1e-15*x**2 -1).nroots()) == ('[-31622776.6016838, 31622776.6016838]') def test_ground_roots(): f = x**6 - 4*x**4 + 4*x**3 - x**2 assert Poly(f).ground_roots() == {S.One: 2, S.Zero: 2} assert ground_roots(f) == {S.One: 2, S.Zero: 2} def test_nth_power_roots_poly(): f = x**4 - x**2 + 1 f_2 = (x**2 - x + 1)**2 f_3 = (x**2 + 1)**2 f_4 = (x**2 + x + 1)**2 f_12 = (x - 1)**4 assert nth_power_roots_poly(f, 1) == f raises(ValueError, lambda: nth_power_roots_poly(f, 0)) raises(ValueError, lambda: nth_power_roots_poly(f, x)) assert factor(nth_power_roots_poly(f, 2)) == f_2 assert factor(nth_power_roots_poly(f, 3)) == f_3 assert factor(nth_power_roots_poly(f, 4)) == f_4 assert factor(nth_power_roots_poly(f, 12)) == f_12 raises(MultivariatePolynomialError, lambda: nth_power_roots_poly( x + y, 2, x, y)) def test_same_root(): f = Poly(x**4 + x**3 + x**2 + x + 1) eq = f.same_root r0 = exp(2 * I * pi / 5) assert [i for i, r in enumerate(f.all_roots()) if eq(r, r0)] == [3] raises(PolynomialError, lambda: Poly(x + 1, domain=QQ).same_root(0, 0)) raises(DomainError, lambda: Poly(x**2 + 1, domain=FF(7)).same_root(0, 0)) raises(DomainError, lambda: Poly(x ** 2 + 1, domain=ZZ_I).same_root(0, 0)) raises(DomainError, lambda: Poly(y * x**2 + 1, domain=ZZ[y]).same_root(0, 0)) raises(MultivariatePolynomialError, lambda: Poly(x * y + 1, domain=ZZ).same_root(0, 0)) def test_torational_factor_list(): p = expand(((x**2-1)*(x-2)).subs({x:x*(1 + sqrt(2))})) assert _torational_factor_list(p, x) == (-2, [ (-x*(1 + sqrt(2))/2 + 1, 1), (-x*(1 + sqrt(2)) - 1, 1), (-x*(1 + sqrt(2)) + 1, 1)]) p = expand(((x**2-1)*(x-2)).subs({x:x*(1 + 2**Rational(1, 4))})) assert _torational_factor_list(p, x) is None def test_cancel(): assert cancel(0) == 0 assert cancel(7) == 7 assert cancel(x) == x assert cancel(oo) is oo assert cancel((2, 3)) == (1, 2, 3) assert cancel((1, 0), x) == (1, 1, 0) assert cancel((0, 1), x) == (1, 0, 1) f, g, p, q = 4*x**2 - 4, 2*x - 2, 2*x + 2, 1 F, G, P, Q = [ Poly(u, x) for u in (f, g, p, q) ] assert F.cancel(G) == (1, P, Q) assert cancel((f, g)) == (1, p, q) assert cancel((f, g), x) == (1, p, q) assert cancel((f, g), (x,)) == (1, p, q) assert cancel((F, G)) == (1, P, Q) assert cancel((f, g), polys=True) == (1, P, Q) assert cancel((F, G), polys=False) == (1, p, q) f = (x**2 - 2)/(x + sqrt(2)) assert cancel(f) == f assert cancel(f, greedy=False) == x - sqrt(2) f = (x**2 - 2)/(x - sqrt(2)) assert cancel(f) == f assert cancel(f, greedy=False) == x + sqrt(2) assert cancel((x**2/4 - 1, x/2 - 1)) == (1, x + 2, 2) # assert cancel((x**2/4 - 1, x/2 - 1)) == (S.Half, x + 2, 1) assert cancel((x**2 - y)/(x - y)) == 1/(x - y)*(x**2 - y) assert cancel((x**2 - y**2)/(x - y), x) == x + y assert cancel((x**2 - y**2)/(x - y), y) == x + y assert cancel((x**2 - y**2)/(x - y)) == x + y assert cancel((x**3 - 1)/(x**2 - 1)) == (x**2 + x + 1)/(x + 1) assert cancel((x**3/2 - S.Half)/(x**2 - 1)) == (x**2 + x + 1)/(2*x + 2) assert cancel((exp(2*x) + 2*exp(x) + 1)/(exp(x) + 1)) == exp(x) + 1 f = Poly(x**2 - a**2, x) g = Poly(x - a, x) F = Poly(x + a, x, domain='ZZ[a]') G = Poly(1, x, domain='ZZ[a]') assert cancel((f, g)) == (1, F, G) f = x**3 + (sqrt(2) - 2)*x**2 - (2*sqrt(2) + 3)*x - 3*sqrt(2) g = x**2 - 2 assert cancel((f, g), extension=True) == (1, x**2 - 2*x - 3, x - sqrt(2)) f = Poly(-2*x + 3, x) g = Poly(-x**9 + x**8 + x**6 - x**5 + 2*x**2 - 3*x + 1, x) assert cancel((f, g)) == (1, -f, -g) f = Poly(y, y, domain='ZZ(x)') g = Poly(1, y, domain='ZZ[x]') assert f.cancel( g) == (1, Poly(y, y, domain='ZZ(x)'), Poly(1, y, domain='ZZ(x)')) assert f.cancel(g, include=True) == ( Poly(y, y, domain='ZZ(x)'), Poly(1, y, domain='ZZ(x)')) f = Poly(5*x*y + x, y, domain='ZZ(x)') g = Poly(2*x**2*y, y, domain='ZZ(x)') assert f.cancel(g, include=True) == ( Poly(5*y + 1, y, domain='ZZ(x)'), Poly(2*x*y, y, domain='ZZ(x)')) f = -(-2*x - 4*y + 0.005*(z - y)**2)/((z - y)*(-z + y + 2)) assert cancel(f).is_Mul == True P = tanh(x - 3.0) Q = tanh(x + 3.0) f = ((-2*P**2 + 2)*(-P**2 + 1)*Q**2/2 + (-2*P**2 + 2)*(-2*Q**2 + 2)*P*Q - (-2*P**2 + 2)*P**2*Q**2 + (-2*Q**2 + 2)*(-Q**2 + 1)*P**2/2 - (-2*Q**2 + 2)*P**2*Q**2)/(2*sqrt(P**2*Q**2 + 0.0001)) \ + (-(-2*P**2 + 2)*P*Q**2/2 - (-2*Q**2 + 2)*P**2*Q/2)*((-2*P**2 + 2)*P*Q**2/2 + (-2*Q**2 + 2)*P**2*Q/2)/(2*(P**2*Q**2 + 0.0001)**Rational(3, 2)) assert cancel(f).is_Mul == True # issue 7022 A = Symbol('A', commutative=False) p1 = Piecewise((A*(x**2 - 1)/(x + 1), x > 1), ((x + 2)/(x**2 + 2*x), True)) p2 = Piecewise((A*(x - 1), x > 1), (1/x, True)) assert cancel(p1) == p2 assert cancel(2*p1) == 2*p2 assert cancel(1 + p1) == 1 + p2 assert cancel((x**2 - 1)/(x + 1)*p1) == (x - 1)*p2 assert cancel((x**2 - 1)/(x + 1) + p1) == (x - 1) + p2 p3 = Piecewise(((x**2 - 1)/(x + 1), x > 1), ((x + 2)/(x**2 + 2*x), True)) p4 = Piecewise(((x - 1), x > 1), (1/x, True)) assert cancel(p3) == p4 assert cancel(2*p3) == 2*p4 assert cancel(1 + p3) == 1 + p4 assert cancel((x**2 - 1)/(x + 1)*p3) == (x - 1)*p4 assert cancel((x**2 - 1)/(x + 1) + p3) == (x - 1) + p4 # issue 4077 q = S('''(2*1*(x - 1/x)/(x*(2*x - (-x + 1/x)/(x**2*(x - 1/x)**2) - 1/(x**2*(x - 1/x)) - 2/x)) - 2*1*((x - 1/x)/((x*(x - 1/x)**2)) - 1/(x*(x - 1/x)))*((-x + 1/x)*((x - 1/x)/((x*(x - 1/x)**2)) - 1/(x*(x - 1/x)))/(2*x - (-x + 1/x)/(x**2*(x - 1/x)**2) - 1/(x**2*(x - 1/x)) - 2/x) + 1)*((x - 1/x)/((x - 1/x)**2) - ((x - 1/x)/((x*(x - 1/x)**2)) - 1/(x*(x - 1/x)))**2/(2*x - (-x + 1/x)/(x**2*(x - 1/x)**2) - 1/(x**2*(x - 1/x)) - 2/x) - 1/(x - 1/x))*(2*x - (-x + 1/x)/(x**2*(x - 1/x)**2) - 1/(x**2*(x - 1/x)) - 2/x)/x - 1/x)*(((-x + 1/x)/((x*(x - 1/x)**2)) + 1/(x*(x - 1/x)))*((-(x - 1/x)/(x*(x - 1/x)) - 1/x)*((x - 1/x)/((x*(x - 1/x)**2)) - 1/(x*(x - 1/x)))/(2*x - (-x + 1/x)/(x**2*(x - 1/x)**2) - 1/(x**2*(x - 1/x)) - 2/x) - 1 + (x - 1/x)/(x - 1/x))/((x*((x - 1/x)/((x - 1/x)**2) - ((x - 1/x)/((x*(x - 1/x)**2)) - 1/(x*(x - 1/x)))**2/(2*x - (-x + 1/x)/(x**2*(x - 1/x)**2) - 1/(x**2*(x - 1/x)) - 2/x) - 1/(x - 1/x))*(2*x - (-x + 1/x)/(x**2*(x - 1/x)**2) - 1/(x**2*(x - 1/x)) - 2/x))) + ((x - 1/x)/((x*(x - 1/x))) + 1/x)/((x*(2*x - (-x + 1/x)/(x**2*(x - 1/x)**2) - 1/(x**2*(x - 1/x)) - 2/x))) + 1/x)/(2*x + 2*((x - 1/x)/((x*(x - 1/x)**2)) - 1/(x*(x - 1/x)))*((-(x - 1/x)/(x*(x - 1/x)) - 1/x)*((x - 1/x)/((x*(x - 1/x)**2)) - 1/(x*(x - 1/x)))/(2*x - (-x + 1/x)/(x**2*(x - 1/x)**2) - 1/(x**2*(x - 1/x)) - 2/x) - 1 + (x - 1/x)/(x - 1/x))/((x*((x - 1/x)/((x - 1/x)**2) - ((x - 1/x)/((x*(x - 1/x)**2)) - 1/(x*(x - 1/x)))**2/(2*x - (-x + 1/x)/(x**2*(x - 1/x)**2) - 1/(x**2*(x - 1/x)) - 2/x) - 1/(x - 1/x))*(2*x - (-x + 1/x)/(x**2*(x - 1/x)**2) - 1/(x**2*(x - 1/x)) - 2/x))) - 2*((x - 1/x)/((x*(x - 1/x))) + 1/x)/(x*(2*x - (-x + 1/x)/(x**2*(x - 1/x)**2) - 1/(x**2*(x - 1/x)) - 2/x)) - 2/x) - ((x - 1/x)/((x*(x - 1/x)**2)) - 1/(x*(x - 1/x)))*((-x + 1/x)*((x - 1/x)/((x*(x - 1/x)**2)) - 1/(x*(x - 1/x)))/(2*x - (-x + 1/x)/(x**2*(x - 1/x)**2) - 1/(x**2*(x - 1/x)) - 2/x) + 1)/(x*((x - 1/x)/((x - 1/x)**2) - ((x - 1/x)/((x*(x - 1/x)**2)) - 1/(x*(x - 1/x)))**2/(2*x - (-x + 1/x)/(x**2*(x - 1/x)**2) - 1/(x**2*(x - 1/x)) - 2/x) - 1/(x - 1/x))*(2*x - (-x + 1/x)/(x**2*(x - 1/x)**2) - 1/(x**2*(x - 1/x)) - 2/x)) + (x - 1/x)/((x*(2*x - (-x + 1/x)/(x**2*(x - 1/x)**2) - 1/(x**2*(x - 1/x)) - 2/x))) - 1/x''', evaluate=False) assert cancel(q, _signsimp=False) is S.NaN assert q.subs(x, 2) is S.NaN assert signsimp(q) is S.NaN # issue 9363 M = MatrixSymbol('M', 5, 5) assert cancel(M[0,0] + 7) == M[0,0] + 7 expr = sin(M[1, 4] + M[2, 1] * 5 * M[4, 0]) - 5 * M[1, 2] / z assert cancel(expr) == (z*sin(M[1, 4] + M[2, 1] * 5 * M[4, 0]) - 5 * M[1, 2]) / z assert cancel((x**2 + 1)/(x - I)) == x + I def test_reduced(): f = 2*x**4 + y**2 - x**2 + y**3 G = [x**3 - x, y**3 - y] Q = [2*x, 1] r = x**2 + y**2 + y assert reduced(f, G) == (Q, r) assert reduced(f, G, x, y) == (Q, r) H = groebner(G) assert H.reduce(f) == (Q, r) Q = [Poly(2*x, x, y), Poly(1, x, y)] r = Poly(x**2 + y**2 + y, x, y) assert _strict_eq(reduced(f, G, polys=True), (Q, r)) assert _strict_eq(reduced(f, G, x, y, polys=True), (Q, r)) H = groebner(G, polys=True) assert _strict_eq(H.reduce(f), (Q, r)) f = 2*x**3 + y**3 + 3*y G = groebner([x**2 + y**2 - 1, x*y - 2]) Q = [x**2 - x*y**3/2 + x*y/2 + y**6/4 - y**4/2 + y**2/4, -y**5/4 + y**3/2 + y*Rational(3, 4)] r = 0 assert reduced(f, G) == (Q, r) assert G.reduce(f) == (Q, r) assert reduced(f, G, auto=False)[1] != 0 assert G.reduce(f, auto=False)[1] != 0 assert G.contains(f) is True assert G.contains(f + 1) is False assert reduced(1, [1], x) == ([1], 0) raises(ComputationFailed, lambda: reduced(1, [1])) def test_groebner(): assert groebner([], x, y, z) == [] assert groebner([x**2 + 1, y**4*x + x**3], x, y, order='lex') == [1 + x**2, -1 + y**4] assert groebner([x**2 + 1, y**4*x + x**3, x*y*z**3], x, y, z, order='grevlex') == [-1 + y**4, z**3, 1 + x**2] assert groebner([x**2 + 1, y**4*x + x**3], x, y, order='lex', polys=True) == \ [Poly(1 + x**2, x, y), Poly(-1 + y**4, x, y)] assert groebner([x**2 + 1, y**4*x + x**3, x*y*z**3], x, y, z, order='grevlex', polys=True) == \ [Poly(-1 + y**4, x, y, z), Poly(z**3, x, y, z), Poly(1 + x**2, x, y, z)] assert groebner([x**3 - 1, x**2 - 1]) == [x - 1] assert groebner([Eq(x**3, 1), Eq(x**2, 1)]) == [x - 1] F = [3*x**2 + y*z - 5*x - 1, 2*x + 3*x*y + y**2, x - 3*y + x*z - 2*z**2] f = z**9 - x**2*y**3 - 3*x*y**2*z + 11*y*z**2 + x**2*z**2 - 5 G = groebner(F, x, y, z, modulus=7, symmetric=False) assert G == [1 + x + y + 3*z + 2*z**2 + 2*z**3 + 6*z**4 + z**5, 1 + 3*y + y**2 + 6*z**2 + 3*z**3 + 3*z**4 + 3*z**5 + 4*z**6, 1 + 4*y + 4*z + y*z + 4*z**3 + z**4 + z**6, 6 + 6*z + z**2 + 4*z**3 + 3*z**4 + 6*z**5 + 3*z**6 + z**7] Q, r = reduced(f, G, x, y, z, modulus=7, symmetric=False, polys=True) assert sum([ q*g for q, g in zip(Q, G.polys)], r) == Poly(f, modulus=7) F = [x*y - 2*y, 2*y**2 - x**2] assert groebner(F, x, y, order='grevlex') == \ [y**3 - 2*y, x**2 - 2*y**2, x*y - 2*y] assert groebner(F, y, x, order='grevlex') == \ [x**3 - 2*x**2, -x**2 + 2*y**2, x*y - 2*y] assert groebner(F, order='grevlex', field=True) == \ [y**3 - 2*y, x**2 - 2*y**2, x*y - 2*y] assert groebner([1], x) == [1] assert groebner([x**2 + 2.0*y], x, y) == [1.0*x**2 + 2.0*y] raises(ComputationFailed, lambda: groebner([1])) assert groebner([x**2 - 1, x**3 + 1], method='buchberger') == [x + 1] assert groebner([x**2 - 1, x**3 + 1], method='f5b') == [x + 1] raises(ValueError, lambda: groebner([x, y], method='unknown')) def test_fglm(): F = [a + b + c + d, a*b + a*d + b*c + b*d, a*b*c + a*b*d + a*c*d + b*c*d, a*b*c*d - 1] G = groebner(F, a, b, c, d, order=grlex) B = [ 4*a + 3*d**9 - 4*d**5 - 3*d, 4*b + 4*c - 3*d**9 + 4*d**5 + 7*d, 4*c**2 + 3*d**10 - 4*d**6 - 3*d**2, 4*c*d**4 + 4*c - d**9 + 4*d**5 + 5*d, d**12 - d**8 - d**4 + 1, ] assert groebner(F, a, b, c, d, order=lex) == B assert G.fglm(lex) == B F = [9*x**8 + 36*x**7 - 32*x**6 - 252*x**5 - 78*x**4 + 468*x**3 + 288*x**2 - 108*x + 9, -72*t*x**7 - 252*t*x**6 + 192*t*x**5 + 1260*t*x**4 + 312*t*x**3 - 404*t*x**2 - 576*t*x + \ 108*t - 72*x**7 - 256*x**6 + 192*x**5 + 1280*x**4 + 312*x**3 - 576*x + 96] G = groebner(F, t, x, order=grlex) B = [ 203577793572507451707*t + 627982239411707112*x**7 - 666924143779443762*x**6 - \ 10874593056632447619*x**5 + 5119998792707079562*x**4 + 72917161949456066376*x**3 + \ 20362663855832380362*x**2 - 142079311455258371571*x + 183756699868981873194, 9*x**8 + 36*x**7 - 32*x**6 - 252*x**5 - 78*x**4 + 468*x**3 + 288*x**2 - 108*x + 9, ] assert groebner(F, t, x, order=lex) == B assert G.fglm(lex) == B F = [x**2 - x - 3*y + 1, -2*x + y**2 + y - 1] G = groebner(F, x, y, order=lex) B = [ x**2 - x - 3*y + 1, y**2 - 2*x + y - 1, ] assert groebner(F, x, y, order=grlex) == B assert G.fglm(grlex) == B def test_is_zero_dimensional(): assert is_zero_dimensional([x, y], x, y) is True assert is_zero_dimensional([x**3 + y**2], x, y) is False assert is_zero_dimensional([x, y, z], x, y, z) is True assert is_zero_dimensional([x, y, z], x, y, z, t) is False F = [x*y - z, y*z - x, x*y - y] assert is_zero_dimensional(F, x, y, z) is True F = [x**2 - 2*x*z + 5, x*y**2 + y*z**3, 3*y**2 - 8*z**2] assert is_zero_dimensional(F, x, y, z) is True def test_GroebnerBasis(): F = [x*y - 2*y, 2*y**2 - x**2] G = groebner(F, x, y, order='grevlex') H = [y**3 - 2*y, x**2 - 2*y**2, x*y - 2*y] P = [ Poly(h, x, y) for h in H ] assert groebner(F + [0], x, y, order='grevlex') == G assert isinstance(G, GroebnerBasis) is True assert len(G) == 3 assert G[0] == H[0] and not G[0].is_Poly assert G[1] == H[1] and not G[1].is_Poly assert G[2] == H[2] and not G[2].is_Poly assert G[1:] == H[1:] and not any(g.is_Poly for g in G[1:]) assert G[:2] == H[:2] and not any(g.is_Poly for g in G[1:]) assert G.exprs == H assert G.polys == P assert G.gens == (x, y) assert G.domain == ZZ assert G.order == grevlex assert G == H assert G == tuple(H) assert G == P assert G == tuple(P) assert G != [] G = groebner(F, x, y, order='grevlex', polys=True) assert G[0] == P[0] and G[0].is_Poly assert G[1] == P[1] and G[1].is_Poly assert G[2] == P[2] and G[2].is_Poly assert G[1:] == P[1:] and all(g.is_Poly for g in G[1:]) assert G[:2] == P[:2] and all(g.is_Poly for g in G[1:]) def test_poly(): assert poly(x) == Poly(x, x) assert poly(y) == Poly(y, y) assert poly(x + y) == Poly(x + y, x, y) assert poly(x + sin(x)) == Poly(x + sin(x), x, sin(x)) assert poly(x + y, wrt=y) == Poly(x + y, y, x) assert poly(x + sin(x), wrt=sin(x)) == Poly(x + sin(x), sin(x), x) assert poly(x*y + 2*x*z**2 + 17) == Poly(x*y + 2*x*z**2 + 17, x, y, z) assert poly(2*(y + z)**2 - 1) == Poly(2*y**2 + 4*y*z + 2*z**2 - 1, y, z) assert poly( x*(y + z)**2 - 1) == Poly(x*y**2 + 2*x*y*z + x*z**2 - 1, x, y, z) assert poly(2*x*( y + z)**2 - 1) == Poly(2*x*y**2 + 4*x*y*z + 2*x*z**2 - 1, x, y, z) assert poly(2*( y + z)**2 - x - 1) == Poly(2*y**2 + 4*y*z + 2*z**2 - x - 1, x, y, z) assert poly(x*( y + z)**2 - x - 1) == Poly(x*y**2 + 2*x*y*z + x*z**2 - x - 1, x, y, z) assert poly(2*x*(y + z)**2 - x - 1) == Poly(2*x*y**2 + 4*x*y*z + 2* x*z**2 - x - 1, x, y, z) assert poly(x*y + (x + y)**2 + (x + z)**2) == \ Poly(2*x*z + 3*x*y + y**2 + z**2 + 2*x**2, x, y, z) assert poly(x*y*(x + y)*(x + z)**2) == \ Poly(x**3*y**2 + x*y**2*z**2 + y*x**2*z**2 + 2*z*x**2* y**2 + 2*y*z*x**3 + y*x**4, x, y, z) assert poly(Poly(x + y + z, y, x, z)) == Poly(x + y + z, y, x, z) assert poly((x + y)**2, x) == Poly(x**2 + 2*x*y + y**2, x, domain=ZZ[y]) assert poly((x + y)**2, y) == Poly(x**2 + 2*x*y + y**2, y, domain=ZZ[x]) assert poly(1, x) == Poly(1, x) raises(GeneratorsNeeded, lambda: poly(1)) # issue 6184 assert poly(x + y, x, y) == Poly(x + y, x, y) assert poly(x + y, y, x) == Poly(x + y, y, x) def test_keep_coeff(): u = Mul(2, x + 1, evaluate=False) assert _keep_coeff(S.One, x) == x assert _keep_coeff(S.NegativeOne, x) == -x assert _keep_coeff(S(1.0), x) == 1.0*x assert _keep_coeff(S(-1.0), x) == -1.0*x assert _keep_coeff(S.One, 2*x) == 2*x assert _keep_coeff(S(2), x/2) == x assert _keep_coeff(S(2), sin(x)) == 2*sin(x) assert _keep_coeff(S(2), x + 1) == u assert _keep_coeff(x, 1/x) == 1 assert _keep_coeff(x + 1, S(2)) == u assert _keep_coeff(S.Half, S.One) == S.Half p = Pow(2, 3, evaluate=False) assert _keep_coeff(S(-1), p) == Mul(-1, p, evaluate=False) a = Add(2, p, evaluate=False) assert _keep_coeff(S.Half, a, clear=True ) == Mul(S.Half, a, evaluate=False) assert _keep_coeff(S.Half, a, clear=False ) == Add(1, Mul(S.Half, p, evaluate=False), evaluate=False) def test_poly_matching_consistency(): # Test for this issue: # https://github.com/sympy/sympy/issues/5514 assert I * Poly(x, x) == Poly(I*x, x) assert Poly(x, x) * I == Poly(I*x, x) def test_issue_5786(): assert expand(factor(expand( (x - I*y)*(z - I*t)), extension=[I])) == -I*t*x - t*y + x*z - I*y*z def test_noncommutative(): class foo(Expr): is_commutative=False e = x/(x + x*y) c = 1/( 1 + y) assert cancel(foo(e)) == foo(c) assert cancel(e + foo(e)) == c + foo(c) assert cancel(e*foo(c)) == c*foo(c) def test_to_rational_coeffs(): assert to_rational_coeffs( Poly(x**3 + y*x**2 + sqrt(y), x, domain='EX')) is None # issue 21268 assert to_rational_coeffs( Poly(y**3 + sqrt(2)*y**2*sin(x) + 1, y)) is None assert to_rational_coeffs(Poly(x, y)) is None assert to_rational_coeffs(Poly(sqrt(2)*y)) is None def test_factor_terms(): # issue 7067 assert factor_list(x*(x + y)) == (1, [(x, 1), (x + y, 1)]) assert sqf_list(x*(x + y)) == (1, [(x**2 + x*y, 1)]) def test_as_list(): # issue 14496 assert Poly(x**3 + 2, x, domain='ZZ').as_list() == [1, 0, 0, 2] assert Poly(x**2 + y + 1, x, y, domain='ZZ').as_list() == [[1], [], [1, 1]] assert Poly(x**2 + y + 1, x, y, z, domain='ZZ').as_list() == \ [[[1]], [[]], [[1], [1]]] def test_issue_11198(): assert factor_list(sqrt(2)*x) == (sqrt(2), [(x, 1)]) assert factor_list(sqrt(2)*sin(x), sin(x)) == (sqrt(2), [(sin(x), 1)]) def test_Poly_precision(): # Make sure Poly doesn't lose precision p = Poly(pi.evalf(100)*x) assert p.as_expr() == pi.evalf(100)*x def test_issue_12400(): # Correction of check for negative exponents assert poly(1/(1+sqrt(2)), x) == \ Poly(1/(1+sqrt(2)), x, domain='EX') def test_issue_14364(): assert gcd(S(6)*(1 + sqrt(3))/5, S(3)*(1 + sqrt(3))/10) == Rational(3, 10) * (1 + sqrt(3)) assert gcd(sqrt(5)*Rational(4, 7), sqrt(5)*Rational(2, 3)) == sqrt(5)*Rational(2, 21) assert lcm(Rational(2, 3)*sqrt(3), Rational(5, 6)*sqrt(3)) == S(10)*sqrt(3)/3 assert lcm(3*sqrt(3), 4/sqrt(3)) == 12*sqrt(3) assert lcm(S(5)*(1 + 2**Rational(1, 3))/6, S(3)*(1 + 2**Rational(1, 3))/8) == Rational(15, 2) * (1 + 2**Rational(1, 3)) assert gcd(Rational(2, 3)*sqrt(3), Rational(5, 6)/sqrt(3)) == sqrt(3)/18 assert gcd(S(4)*sqrt(13)/7, S(3)*sqrt(13)/14) == sqrt(13)/14 # gcd_list and lcm_list assert gcd([S(2)*sqrt(47)/7, S(6)*sqrt(47)/5, S(8)*sqrt(47)/5]) == sqrt(47)*Rational(2, 35) assert gcd([S(6)*(1 + sqrt(7))/5, S(2)*(1 + sqrt(7))/7, S(4)*(1 + sqrt(7))/13]) == (1 + sqrt(7))*Rational(2, 455) assert lcm((Rational(7, 2)/sqrt(15), Rational(5, 6)/sqrt(15), Rational(5, 8)/sqrt(15))) == Rational(35, 2)/sqrt(15) assert lcm([S(5)*(2 + 2**Rational(5, 7))/6, S(7)*(2 + 2**Rational(5, 7))/2, S(13)*(2 + 2**Rational(5, 7))/4]) == Rational(455, 2) * (2 + 2**Rational(5, 7)) def test_issue_15669(): x = Symbol("x", positive=True) expr = (16*x**3/(-x**2 + sqrt(8*x**2 + (x**2 - 2)**2) + 2)**2 - 2*2**Rational(4, 5)*x*(-x**2 + sqrt(8*x**2 + (x**2 - 2)**2) + 2)**Rational(3, 5) + 10*x) assert factor(expr, deep=True) == x*(x**2 + 2) def test_issue_17988(): x = Symbol('x') p = poly(x - 1) with warns_deprecated_sympy(): M = Matrix([[poly(x + 1), poly(x + 1)]]) with warns(SymPyDeprecationWarning, test_stacklevel=False): assert p * M == M * p == Matrix([[poly(x**2 - 1), poly(x**2 - 1)]]) def test_issue_18205(): assert cancel((2 + I)*(3 - I)) == 7 + I assert cancel((2 + I)*(2 - I)) == 5 def test_issue_8695(): p = (x**2 + 1) * (x - 1)**2 * (x - 2)**3 * (x - 3)**3 result = (1, [(x**2 + 1, 1), (x - 1, 2), (x**2 - 5*x + 6, 3)]) assert sqf_list(p) == result def test_issue_19113(): eq = sin(x)**3 - sin(x) + 1 raises(PolynomialError, lambda: refine_root(eq, 1, 2, 1e-2)) raises(PolynomialError, lambda: count_roots(eq, -1, 1)) raises(PolynomialError, lambda: real_roots(eq)) raises(PolynomialError, lambda: nroots(eq)) raises(PolynomialError, lambda: ground_roots(eq)) raises(PolynomialError, lambda: nth_power_roots_poly(eq, 2)) def test_issue_19360(): f = 2*x**2 - 2*sqrt(2)*x*y + y**2 assert factor(f, extension=sqrt(2)) == 2*(x - (sqrt(2)*y/2))**2 f = -I*t*x - t*y + x*z - I*y*z assert factor(f, extension=I) == (x - I*y)*(-I*t + z) def test_poly_copy_equals_original(): poly = Poly(x + y, x, y, z) copy = poly.copy() assert poly == copy, ( "Copied polynomial not equal to original.") assert poly.gens == copy.gens, ( "Copied polynomial has different generators than original.") def test_deserialized_poly_equals_original(): poly = Poly(x + y, x, y, z) deserialized = pickle.loads(pickle.dumps(poly)) assert poly == deserialized, ( "Deserialized polynomial not equal to original.") assert poly.gens == deserialized.gens, ( "Deserialized polynomial has different generators than original.") def test_issue_20389(): result = degree(x * (x + 1) - x ** 2 - x, x) assert result == -oo def test_issue_20985(): from sympy.core.symbol import symbols w, R = symbols('w R') poly = Poly(1.0 + I*w/R, w, 1/R) assert poly.degree() == S(1)
6ed2916aa7248efc863a10af21fc0bb510d51b6422c28e824e7a0f5bc8784bd1
from sympy.polys.galoistools import ( gf_crt, gf_crt1, gf_crt2, gf_int, gf_degree, gf_strip, gf_trunc, gf_normal, gf_from_dict, gf_to_dict, gf_from_int_poly, gf_to_int_poly, gf_neg, gf_add_ground, gf_sub_ground, gf_mul_ground, gf_add, gf_sub, gf_add_mul, gf_sub_mul, gf_mul, gf_sqr, gf_div, gf_rem, gf_quo, gf_exquo, gf_lshift, gf_rshift, gf_expand, gf_pow, gf_pow_mod, gf_gcdex, gf_gcd, gf_lcm, gf_cofactors, gf_LC, gf_TC, gf_monic, gf_eval, gf_multi_eval, gf_compose, gf_compose_mod, gf_trace_map, gf_diff, gf_irreducible, gf_irreducible_p, gf_irred_p_ben_or, gf_irred_p_rabin, gf_sqf_list, gf_sqf_part, gf_sqf_p, gf_Qmatrix, gf_Qbasis, gf_ddf_zassenhaus, gf_ddf_shoup, gf_edf_zassenhaus, gf_edf_shoup, gf_berlekamp, gf_factor_sqf, gf_factor, gf_value, linear_congruence, csolve_prime, gf_csolve, gf_frobenius_map, gf_frobenius_monomial_base ) from sympy.polys.polyerrors import ( ExactQuotientFailed, ) from sympy.polys import polyconfig as config from sympy.polys.domains import ZZ from sympy.core.numbers import pi from sympy.ntheory.generate import nextprime from sympy.testing.pytest import raises def test_gf_crt(): U = [49, 76, 65] M = [99, 97, 95] p = 912285 u = 639985 assert gf_crt(U, M, ZZ) == u E = [9215, 9405, 9603] S = [62, 24, 12] assert gf_crt1(M, ZZ) == (p, E, S) assert gf_crt2(U, M, p, E, S, ZZ) == u def test_gf_int(): assert gf_int(0, 5) == 0 assert gf_int(1, 5) == 1 assert gf_int(2, 5) == 2 assert gf_int(3, 5) == -2 assert gf_int(4, 5) == -1 assert gf_int(5, 5) == 0 def test_gf_degree(): assert gf_degree([]) == -1 assert gf_degree([1]) == 0 assert gf_degree([1, 0]) == 1 assert gf_degree([1, 0, 0, 0, 1]) == 4 def test_gf_strip(): assert gf_strip([]) == [] assert gf_strip([0]) == [] assert gf_strip([0, 0, 0]) == [] assert gf_strip([1]) == [1] assert gf_strip([0, 1]) == [1] assert gf_strip([0, 0, 0, 1]) == [1] assert gf_strip([1, 2, 0]) == [1, 2, 0] assert gf_strip([0, 1, 2, 0]) == [1, 2, 0] assert gf_strip([0, 0, 0, 1, 2, 0]) == [1, 2, 0] def test_gf_trunc(): assert gf_trunc([], 11) == [] assert gf_trunc([1], 11) == [1] assert gf_trunc([22], 11) == [] assert gf_trunc([12], 11) == [1] assert gf_trunc([11, 22, 17, 1, 0], 11) == [6, 1, 0] assert gf_trunc([12, 23, 17, 1, 0], 11) == [1, 1, 6, 1, 0] def test_gf_normal(): assert gf_normal([11, 22, 17, 1, 0], 11, ZZ) == [6, 1, 0] def test_gf_from_to_dict(): f = {11: 12, 6: 2, 0: 25} F = {11: 1, 6: 2, 0: 3} g = [1, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 3] assert gf_from_dict(f, 11, ZZ) == g assert gf_to_dict(g, 11) == F f = {11: -5, 4: 0, 3: 1, 0: 12} F = {11: -5, 3: 1, 0: 1} g = [6, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1] assert gf_from_dict(f, 11, ZZ) == g assert gf_to_dict(g, 11) == F assert gf_to_dict([10], 11, symmetric=True) == {0: -1} assert gf_to_dict([10], 11, symmetric=False) == {0: 10} def test_gf_from_to_int_poly(): assert gf_from_int_poly([1, 0, 7, 2, 20], 5) == [1, 0, 2, 2, 0] assert gf_to_int_poly([1, 0, 4, 2, 3], 5) == [1, 0, -1, 2, -2] assert gf_to_int_poly([10], 11, symmetric=True) == [-1] assert gf_to_int_poly([10], 11, symmetric=False) == [10] def test_gf_LC(): assert gf_LC([], ZZ) == 0 assert gf_LC([1], ZZ) == 1 assert gf_LC([1, 2], ZZ) == 1 def test_gf_TC(): assert gf_TC([], ZZ) == 0 assert gf_TC([1], ZZ) == 1 assert gf_TC([1, 2], ZZ) == 2 def test_gf_monic(): assert gf_monic(ZZ.map([]), 11, ZZ) == (0, []) assert gf_monic(ZZ.map([1]), 11, ZZ) == (1, [1]) assert gf_monic(ZZ.map([2]), 11, ZZ) == (2, [1]) assert gf_monic(ZZ.map([1, 2, 3, 4]), 11, ZZ) == (1, [1, 2, 3, 4]) assert gf_monic(ZZ.map([2, 3, 4, 5]), 11, ZZ) == (2, [1, 7, 2, 8]) def test_gf_arith(): assert gf_neg([], 11, ZZ) == [] assert gf_neg([1], 11, ZZ) == [10] assert gf_neg([1, 2, 3], 11, ZZ) == [10, 9, 8] assert gf_add_ground([], 0, 11, ZZ) == [] assert gf_sub_ground([], 0, 11, ZZ) == [] assert gf_add_ground([], 3, 11, ZZ) == [3] assert gf_sub_ground([], 3, 11, ZZ) == [8] assert gf_add_ground([1], 3, 11, ZZ) == [4] assert gf_sub_ground([1], 3, 11, ZZ) == [9] assert gf_add_ground([8], 3, 11, ZZ) == [] assert gf_sub_ground([3], 3, 11, ZZ) == [] assert gf_add_ground([1, 2, 3], 3, 11, ZZ) == [1, 2, 6] assert gf_sub_ground([1, 2, 3], 3, 11, ZZ) == [1, 2, 0] assert gf_mul_ground([], 0, 11, ZZ) == [] assert gf_mul_ground([], 1, 11, ZZ) == [] assert gf_mul_ground([1], 0, 11, ZZ) == [] assert gf_mul_ground([1], 1, 11, ZZ) == [1] assert gf_mul_ground([1, 2, 3], 0, 11, ZZ) == [] assert gf_mul_ground([1, 2, 3], 1, 11, ZZ) == [1, 2, 3] assert gf_mul_ground([1, 2, 3], 7, 11, ZZ) == [7, 3, 10] assert gf_add([], [], 11, ZZ) == [] assert gf_add([1], [], 11, ZZ) == [1] assert gf_add([], [1], 11, ZZ) == [1] assert gf_add([1], [1], 11, ZZ) == [2] assert gf_add([1], [2], 11, ZZ) == [3] assert gf_add([1, 2], [1], 11, ZZ) == [1, 3] assert gf_add([1], [1, 2], 11, ZZ) == [1, 3] assert gf_add([1, 2, 3], [8, 9, 10], 11, ZZ) == [9, 0, 2] assert gf_sub([], [], 11, ZZ) == [] assert gf_sub([1], [], 11, ZZ) == [1] assert gf_sub([], [1], 11, ZZ) == [10] assert gf_sub([1], [1], 11, ZZ) == [] assert gf_sub([1], [2], 11, ZZ) == [10] assert gf_sub([1, 2], [1], 11, ZZ) == [1, 1] assert gf_sub([1], [1, 2], 11, ZZ) == [10, 10] assert gf_sub([3, 2, 1], [8, 9, 10], 11, ZZ) == [6, 4, 2] assert gf_add_mul( [1, 5, 6], [7, 3], [8, 0, 6, 1], 11, ZZ) == [1, 2, 10, 8, 9] assert gf_sub_mul( [1, 5, 6], [7, 3], [8, 0, 6, 1], 11, ZZ) == [10, 9, 3, 2, 3] assert gf_mul([], [], 11, ZZ) == [] assert gf_mul([], [1], 11, ZZ) == [] assert gf_mul([1], [], 11, ZZ) == [] assert gf_mul([1], [1], 11, ZZ) == [1] assert gf_mul([5], [7], 11, ZZ) == [2] assert gf_mul([3, 0, 0, 6, 1, 2], [4, 0, 1, 0], 11, ZZ) == [1, 0, 3, 2, 4, 3, 1, 2, 0] assert gf_mul([4, 0, 1, 0], [3, 0, 0, 6, 1, 2], 11, ZZ) == [1, 0, 3, 2, 4, 3, 1, 2, 0] assert gf_mul([2, 0, 0, 1, 7], [2, 0, 0, 1, 7], 11, ZZ) == [4, 0, 0, 4, 6, 0, 1, 3, 5] assert gf_sqr([], 11, ZZ) == [] assert gf_sqr([2], 11, ZZ) == [4] assert gf_sqr([1, 2], 11, ZZ) == [1, 4, 4] assert gf_sqr([2, 0, 0, 1, 7], 11, ZZ) == [4, 0, 0, 4, 6, 0, 1, 3, 5] def test_gf_division(): raises(ZeroDivisionError, lambda: gf_div([1, 2, 3], [], 11, ZZ)) raises(ZeroDivisionError, lambda: gf_rem([1, 2, 3], [], 11, ZZ)) raises(ZeroDivisionError, lambda: gf_quo([1, 2, 3], [], 11, ZZ)) raises(ZeroDivisionError, lambda: gf_quo([1, 2, 3], [], 11, ZZ)) assert gf_div([1], [1, 2, 3], 7, ZZ) == ([], [1]) assert gf_rem([1], [1, 2, 3], 7, ZZ) == [1] assert gf_quo([1], [1, 2, 3], 7, ZZ) == [] f = ZZ.map([5, 4, 3, 2, 1, 0]) g = ZZ.map([1, 2, 3]) q = [5, 1, 0, 6] r = [3, 3] assert gf_div(f, g, 7, ZZ) == (q, r) assert gf_rem(f, g, 7, ZZ) == r assert gf_quo(f, g, 7, ZZ) == q raises(ExactQuotientFailed, lambda: gf_exquo(f, g, 7, ZZ)) f = ZZ.map([5, 4, 3, 2, 1, 0]) g = ZZ.map([1, 2, 3, 0]) q = [5, 1, 0] r = [6, 1, 0] assert gf_div(f, g, 7, ZZ) == (q, r) assert gf_rem(f, g, 7, ZZ) == r assert gf_quo(f, g, 7, ZZ) == q raises(ExactQuotientFailed, lambda: gf_exquo(f, g, 7, ZZ)) assert gf_quo(ZZ.map([1, 2, 1]), ZZ.map([1, 1]), 11, ZZ) == [1, 1] def test_gf_shift(): f = [1, 2, 3, 4, 5] assert gf_lshift([], 5, ZZ) == [] assert gf_rshift([], 5, ZZ) == ([], []) assert gf_lshift(f, 1, ZZ) == [1, 2, 3, 4, 5, 0] assert gf_lshift(f, 2, ZZ) == [1, 2, 3, 4, 5, 0, 0] assert gf_rshift(f, 0, ZZ) == (f, []) assert gf_rshift(f, 1, ZZ) == ([1, 2, 3, 4], [5]) assert gf_rshift(f, 3, ZZ) == ([1, 2], [3, 4, 5]) assert gf_rshift(f, 5, ZZ) == ([], f) def test_gf_expand(): F = [([1, 1], 2), ([1, 2], 3)] assert gf_expand(F, 11, ZZ) == [1, 8, 3, 5, 6, 8] assert gf_expand((4, F), 11, ZZ) == [4, 10, 1, 9, 2, 10] def test_gf_powering(): assert gf_pow([1, 0, 0, 1, 8], 0, 11, ZZ) == [1] assert gf_pow([1, 0, 0, 1, 8], 1, 11, ZZ) == [1, 0, 0, 1, 8] assert gf_pow([1, 0, 0, 1, 8], 2, 11, ZZ) == [1, 0, 0, 2, 5, 0, 1, 5, 9] assert gf_pow([1, 0, 0, 1, 8], 5, 11, ZZ) == \ [1, 0, 0, 5, 7, 0, 10, 6, 2, 10, 9, 6, 10, 6, 6, 0, 5, 2, 5, 9, 10] assert gf_pow([1, 0, 0, 1, 8], 8, 11, ZZ) == \ [1, 0, 0, 8, 9, 0, 6, 8, 10, 1, 2, 5, 10, 7, 7, 9, 1, 2, 0, 0, 6, 2, 5, 2, 5, 7, 7, 9, 10, 10, 7, 5, 5] assert gf_pow([1, 0, 0, 1, 8], 45, 11, ZZ) == \ [ 1, 0, 0, 1, 8, 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, 4, 0, 0, 4, 10, 0, 0, 0, 0, 0, 0, 10, 0, 0, 10, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 6, 4, 0, 0, 0, 0, 0, 0, 8, 0, 0, 8, 9, 0, 0, 0, 0, 0, 0, 10, 0, 0, 10, 3, 0, 0, 0, 0, 0, 0, 4, 0, 0, 4, 10, 0, 0, 0, 0, 0, 0, 8, 0, 0, 8, 9, 0, 0, 0, 0, 0, 0, 9, 0, 0, 9, 6, 0, 0, 0, 0, 0, 0, 3, 0, 0, 3, 2, 0, 0, 0, 0, 0, 0, 10, 0, 0, 10, 3, 0, 0, 0, 0, 0, 0, 10, 0, 0, 10, 3, 0, 0, 0, 0, 0, 0, 2, 0, 0, 2, 5, 0, 0, 0, 0, 0, 0, 4, 0, 0, 4, 10] assert gf_pow_mod(ZZ.map([1, 0, 0, 1, 8]), 0, ZZ.map([2, 0, 7]), 11, ZZ) == [1] assert gf_pow_mod(ZZ.map([1, 0, 0, 1, 8]), 1, ZZ.map([2, 0, 7]), 11, ZZ) == [1, 1] assert gf_pow_mod(ZZ.map([1, 0, 0, 1, 8]), 2, ZZ.map([2, 0, 7]), 11, ZZ) == [2, 3] assert gf_pow_mod(ZZ.map([1, 0, 0, 1, 8]), 5, ZZ.map([2, 0, 7]), 11, ZZ) == [7, 8] assert gf_pow_mod(ZZ.map([1, 0, 0, 1, 8]), 8, ZZ.map([2, 0, 7]), 11, ZZ) == [1, 5] assert gf_pow_mod(ZZ.map([1, 0, 0, 1, 8]), 45, ZZ.map([2, 0, 7]), 11, ZZ) == [5, 4] def test_gf_gcdex(): assert gf_gcdex(ZZ.map([]), ZZ.map([]), 11, ZZ) == ([1], [], []) assert gf_gcdex(ZZ.map([2]), ZZ.map([]), 11, ZZ) == ([6], [], [1]) assert gf_gcdex(ZZ.map([]), ZZ.map([2]), 11, ZZ) == ([], [6], [1]) assert gf_gcdex(ZZ.map([2]), ZZ.map([2]), 11, ZZ) == ([], [6], [1]) assert gf_gcdex(ZZ.map([]), ZZ.map([3, 0]), 11, ZZ) == ([], [4], [1, 0]) assert gf_gcdex(ZZ.map([3, 0]), ZZ.map([]), 11, ZZ) == ([4], [], [1, 0]) assert gf_gcdex(ZZ.map([3, 0]), ZZ.map([3, 0]), 11, ZZ) == ([], [4], [1, 0]) assert gf_gcdex(ZZ.map([1, 8, 7]), ZZ.map([1, 7, 1, 7]), 11, ZZ) == ([5, 6], [6], [1, 7]) def test_gf_gcd(): assert gf_gcd(ZZ.map([]), ZZ.map([]), 11, ZZ) == [] assert gf_gcd(ZZ.map([2]), ZZ.map([]), 11, ZZ) == [1] assert gf_gcd(ZZ.map([]), ZZ.map([2]), 11, ZZ) == [1] assert gf_gcd(ZZ.map([2]), ZZ.map([2]), 11, ZZ) == [1] assert gf_gcd(ZZ.map([]), ZZ.map([1, 0]), 11, ZZ) == [1, 0] assert gf_gcd(ZZ.map([1, 0]), ZZ.map([]), 11, ZZ) == [1, 0] assert gf_gcd(ZZ.map([3, 0]), ZZ.map([3, 0]), 11, ZZ) == [1, 0] assert gf_gcd(ZZ.map([1, 8, 7]), ZZ.map([1, 7, 1, 7]), 11, ZZ) == [1, 7] def test_gf_lcm(): assert gf_lcm(ZZ.map([]), ZZ.map([]), 11, ZZ) == [] assert gf_lcm(ZZ.map([2]), ZZ.map([]), 11, ZZ) == [] assert gf_lcm(ZZ.map([]), ZZ.map([2]), 11, ZZ) == [] assert gf_lcm(ZZ.map([2]), ZZ.map([2]), 11, ZZ) == [1] assert gf_lcm(ZZ.map([]), ZZ.map([1, 0]), 11, ZZ) == [] assert gf_lcm(ZZ.map([1, 0]), ZZ.map([]), 11, ZZ) == [] assert gf_lcm(ZZ.map([3, 0]), ZZ.map([3, 0]), 11, ZZ) == [1, 0] assert gf_lcm(ZZ.map([1, 8, 7]), ZZ.map([1, 7, 1, 7]), 11, ZZ) == [1, 8, 8, 8, 7] def test_gf_cofactors(): assert gf_cofactors(ZZ.map([]), ZZ.map([]), 11, ZZ) == ([], [], []) assert gf_cofactors(ZZ.map([2]), ZZ.map([]), 11, ZZ) == ([1], [2], []) assert gf_cofactors(ZZ.map([]), ZZ.map([2]), 11, ZZ) == ([1], [], [2]) assert gf_cofactors(ZZ.map([2]), ZZ.map([2]), 11, ZZ) == ([1], [2], [2]) assert gf_cofactors(ZZ.map([]), ZZ.map([1, 0]), 11, ZZ) == ([1, 0], [], [1]) assert gf_cofactors(ZZ.map([1, 0]), ZZ.map([]), 11, ZZ) == ([1, 0], [1], []) assert gf_cofactors(ZZ.map([3, 0]), ZZ.map([3, 0]), 11, ZZ) == ( [1, 0], [3], [3]) assert gf_cofactors(ZZ.map([1, 8, 7]), ZZ.map([1, 7, 1, 7]), 11, ZZ) == ( ([1, 7], [1, 1], [1, 0, 1])) def test_gf_diff(): assert gf_diff([], 11, ZZ) == [] assert gf_diff([7], 11, ZZ) == [] assert gf_diff([7, 3], 11, ZZ) == [7] assert gf_diff([7, 3, 1], 11, ZZ) == [3, 3] assert gf_diff([1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], 11, ZZ) == [] def test_gf_eval(): assert gf_eval([], 4, 11, ZZ) == 0 assert gf_eval([], 27, 11, ZZ) == 0 assert gf_eval([7], 4, 11, ZZ) == 7 assert gf_eval([7], 27, 11, ZZ) == 7 assert gf_eval([1, 0, 3, 2, 4, 3, 1, 2, 0], 0, 11, ZZ) == 0 assert gf_eval([1, 0, 3, 2, 4, 3, 1, 2, 0], 4, 11, ZZ) == 9 assert gf_eval([1, 0, 3, 2, 4, 3, 1, 2, 0], 27, 11, ZZ) == 5 assert gf_eval([4, 0, 0, 4, 6, 0, 1, 3, 5], 0, 11, ZZ) == 5 assert gf_eval([4, 0, 0, 4, 6, 0, 1, 3, 5], 4, 11, ZZ) == 3 assert gf_eval([4, 0, 0, 4, 6, 0, 1, 3, 5], 27, 11, ZZ) == 9 assert gf_multi_eval([3, 2, 1], [0, 1, 2, 3], 11, ZZ) == [1, 6, 6, 1] def test_gf_compose(): assert gf_compose([], [1, 0], 11, ZZ) == [] assert gf_compose_mod([], [1, 0], [1, 0], 11, ZZ) == [] assert gf_compose([1], [], 11, ZZ) == [1] assert gf_compose([1, 0], [], 11, ZZ) == [] assert gf_compose([1, 0], [1, 0], 11, ZZ) == [1, 0] f = ZZ.map([1, 1, 4, 9, 1]) g = ZZ.map([1, 1, 1]) h = ZZ.map([1, 0, 0, 2]) assert gf_compose(g, h, 11, ZZ) == [1, 0, 0, 5, 0, 0, 7] assert gf_compose_mod(g, h, f, 11, ZZ) == [3, 9, 6, 10] def test_gf_trace_map(): f = ZZ.map([1, 1, 4, 9, 1]) a = [1, 1, 1] c = ZZ.map([1, 0]) b = gf_pow_mod(c, 11, f, 11, ZZ) assert gf_trace_map(a, b, c, 0, f, 11, ZZ) == \ ([1, 1, 1], [1, 1, 1]) assert gf_trace_map(a, b, c, 1, f, 11, ZZ) == \ ([5, 2, 10, 3], [5, 3, 0, 4]) assert gf_trace_map(a, b, c, 2, f, 11, ZZ) == \ ([5, 9, 5, 3], [10, 1, 5, 7]) assert gf_trace_map(a, b, c, 3, f, 11, ZZ) == \ ([1, 10, 6, 0], [7]) assert gf_trace_map(a, b, c, 4, f, 11, ZZ) == \ ([1, 1, 1], [1, 1, 8]) assert gf_trace_map(a, b, c, 5, f, 11, ZZ) == \ ([5, 2, 10, 3], [5, 3, 0, 0]) assert gf_trace_map(a, b, c, 11, f, 11, ZZ) == \ ([1, 10, 6, 0], [10]) def test_gf_irreducible(): assert gf_irreducible_p(gf_irreducible(1, 11, ZZ), 11, ZZ) is True assert gf_irreducible_p(gf_irreducible(2, 11, ZZ), 11, ZZ) is True assert gf_irreducible_p(gf_irreducible(3, 11, ZZ), 11, ZZ) is True assert gf_irreducible_p(gf_irreducible(4, 11, ZZ), 11, ZZ) is True assert gf_irreducible_p(gf_irreducible(5, 11, ZZ), 11, ZZ) is True assert gf_irreducible_p(gf_irreducible(6, 11, ZZ), 11, ZZ) is True assert gf_irreducible_p(gf_irreducible(7, 11, ZZ), 11, ZZ) is True def test_gf_irreducible_p(): assert gf_irred_p_ben_or(ZZ.map([7]), 11, ZZ) is True assert gf_irred_p_ben_or(ZZ.map([7, 3]), 11, ZZ) is True assert gf_irred_p_ben_or(ZZ.map([7, 3, 1]), 11, ZZ) is False assert gf_irred_p_rabin(ZZ.map([7]), 11, ZZ) is True assert gf_irred_p_rabin(ZZ.map([7, 3]), 11, ZZ) is True assert gf_irred_p_rabin(ZZ.map([7, 3, 1]), 11, ZZ) is False config.setup('GF_IRRED_METHOD', 'ben-or') assert gf_irreducible_p(ZZ.map([7]), 11, ZZ) is True assert gf_irreducible_p(ZZ.map([7, 3]), 11, ZZ) is True assert gf_irreducible_p(ZZ.map([7, 3, 1]), 11, ZZ) is False config.setup('GF_IRRED_METHOD', 'rabin') assert gf_irreducible_p(ZZ.map([7]), 11, ZZ) is True assert gf_irreducible_p(ZZ.map([7, 3]), 11, ZZ) is True assert gf_irreducible_p(ZZ.map([7, 3, 1]), 11, ZZ) is False config.setup('GF_IRRED_METHOD', 'other') raises(KeyError, lambda: gf_irreducible_p([7], 11, ZZ)) config.setup('GF_IRRED_METHOD') f = ZZ.map([1, 9, 9, 13, 16, 15, 6, 7, 7, 7, 10]) g = ZZ.map([1, 7, 16, 7, 15, 13, 13, 11, 16, 10, 9]) h = gf_mul(f, g, 17, ZZ) assert gf_irred_p_ben_or(f, 17, ZZ) is True assert gf_irred_p_ben_or(g, 17, ZZ) is True assert gf_irred_p_ben_or(h, 17, ZZ) is False assert gf_irred_p_rabin(f, 17, ZZ) is True assert gf_irred_p_rabin(g, 17, ZZ) is True assert gf_irred_p_rabin(h, 17, ZZ) is False def test_gf_squarefree(): assert gf_sqf_list([], 11, ZZ) == (0, []) assert gf_sqf_list([1], 11, ZZ) == (1, []) assert gf_sqf_list([1, 1], 11, ZZ) == (1, [([1, 1], 1)]) assert gf_sqf_p([], 11, ZZ) is True assert gf_sqf_p([1], 11, ZZ) is True assert gf_sqf_p([1, 1], 11, ZZ) is True f = gf_from_dict({11: 1, 0: 1}, 11, ZZ) assert gf_sqf_p(f, 11, ZZ) is False assert gf_sqf_list(f, 11, ZZ) == \ (1, [([1, 1], 11)]) f = [1, 5, 8, 4] assert gf_sqf_p(f, 11, ZZ) is False assert gf_sqf_list(f, 11, ZZ) == \ (1, [([1, 1], 1), ([1, 2], 2)]) assert gf_sqf_part(f, 11, ZZ) == [1, 3, 2] f = [1, 0, 0, 2, 0, 0, 2, 0, 0, 1, 0] assert gf_sqf_list(f, 3, ZZ) == \ (1, [([1, 0], 1), ([1, 1], 3), ([1, 2], 6)]) def test_gf_frobenius_map(): f = ZZ.map([2, 0, 1, 0, 2, 2, 0, 2, 2, 2]) g = ZZ.map([1,1,0,2,0,1,0,2,0,1]) p = 3 b = gf_frobenius_monomial_base(g, p, ZZ) h = gf_frobenius_map(f, g, b, p, ZZ) h1 = gf_pow_mod(f, p, g, p, ZZ) assert h == h1 def test_gf_berlekamp(): f = gf_from_int_poly([1, -3, 1, -3, -1, -3, 1], 11) Q = [[1, 0, 0, 0, 0, 0], [3, 5, 8, 8, 6, 5], [3, 6, 6, 1, 10, 0], [9, 4, 10, 3, 7, 9], [7, 8, 10, 0, 0, 8], [8, 10, 7, 8, 10, 8]] V = [[1, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 0], [0, 0, 7, 9, 0, 1]] assert gf_Qmatrix(f, 11, ZZ) == Q assert gf_Qbasis(Q, 11, ZZ) == V assert gf_berlekamp(f, 11, ZZ) == \ [[1, 1], [1, 5, 3], [1, 2, 3, 4]] f = ZZ.map([1, 0, 1, 0, 10, 10, 8, 2, 8]) Q = ZZ.map([[1, 0, 0, 0, 0, 0, 0, 0], [2, 1, 7, 11, 10, 12, 5, 11], [3, 6, 4, 3, 0, 4, 7, 2], [4, 3, 6, 5, 1, 6, 2, 3], [2, 11, 8, 8, 3, 1, 3, 11], [6, 11, 8, 6, 2, 7, 10, 9], [5, 11, 7, 10, 0, 11, 7, 12], [3, 3, 12, 5, 0, 11, 9, 12]]) V = [[1, 0, 0, 0, 0, 0, 0, 0], [0, 5, 5, 0, 9, 5, 1, 0], [0, 9, 11, 9, 10, 12, 0, 1]] assert gf_Qmatrix(f, 13, ZZ) == Q assert gf_Qbasis(Q, 13, ZZ) == V assert gf_berlekamp(f, 13, ZZ) == \ [[1, 3], [1, 8, 4, 12], [1, 2, 3, 4, 6]] def test_gf_ddf(): f = gf_from_dict({15: ZZ(1), 0: ZZ(-1)}, 11, ZZ) g = [([1, 0, 0, 0, 0, 10], 1), ([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1], 2)] assert gf_ddf_zassenhaus(f, 11, ZZ) == g assert gf_ddf_shoup(f, 11, ZZ) == g f = gf_from_dict({63: ZZ(1), 0: ZZ(1)}, 2, ZZ) g = [([1, 1], 1), ([1, 1, 1], 2), ([1, 1, 1, 1, 1, 1, 1], 3), ([1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1], 6)] assert gf_ddf_zassenhaus(f, 2, ZZ) == g assert gf_ddf_shoup(f, 2, ZZ) == g f = gf_from_dict({6: ZZ(1), 5: ZZ(-1), 4: ZZ(1), 3: ZZ(1), 1: ZZ(-1)}, 3, ZZ) g = [([1, 1, 0], 1), ([1, 1, 0, 1, 2], 2)] assert gf_ddf_zassenhaus(f, 3, ZZ) == g assert gf_ddf_shoup(f, 3, ZZ) == g f = ZZ.map([1, 2, 5, 26, 677, 436, 791, 325, 456, 24, 577]) g = [([1, 701], 1), ([1, 110, 559, 532, 694, 151, 110, 70, 735, 122], 9)] assert gf_ddf_zassenhaus(f, 809, ZZ) == g assert gf_ddf_shoup(f, 809, ZZ) == g p = ZZ(nextprime(int((2**15 * pi).evalf()))) f = gf_from_dict({15: 1, 1: 1, 0: 1}, p, ZZ) g = [([1, 22730, 68144], 2), ([1, 64876, 83977, 10787, 12561, 68608, 52650, 88001, 84356], 4), ([1, 15347, 95022, 84569, 94508, 92335], 5)] assert gf_ddf_zassenhaus(f, p, ZZ) == g assert gf_ddf_shoup(f, p, ZZ) == g def test_gf_edf(): f = ZZ.map([1, 1, 0, 1, 2]) g = ZZ.map([[1, 0, 1], [1, 1, 2]]) assert gf_edf_zassenhaus(f, 2, 3, ZZ) == g assert gf_edf_shoup(f, 2, 3, ZZ) == g def test_issue_23174(): f = ZZ.map([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]) g = ZZ.map([[1, 0, 0, 1, 1, 1, 0, 0, 1], [1, 1, 1, 0, 1, 0, 1, 1, 1]]) assert gf_edf_zassenhaus(f, 8, 2, ZZ) == g def test_gf_factor(): assert gf_factor([], 11, ZZ) == (0, []) assert gf_factor([1], 11, ZZ) == (1, []) assert gf_factor([1, 1], 11, ZZ) == (1, [([1, 1], 1)]) assert gf_factor_sqf([], 11, ZZ) == (0, []) assert gf_factor_sqf([1], 11, ZZ) == (1, []) assert gf_factor_sqf([1, 1], 11, ZZ) == (1, [[1, 1]]) config.setup('GF_FACTOR_METHOD', 'berlekamp') assert gf_factor_sqf([], 11, ZZ) == (0, []) assert gf_factor_sqf([1], 11, ZZ) == (1, []) assert gf_factor_sqf([1, 1], 11, ZZ) == (1, [[1, 1]]) config.setup('GF_FACTOR_METHOD', 'zassenhaus') assert gf_factor_sqf([], 11, ZZ) == (0, []) assert gf_factor_sqf([1], 11, ZZ) == (1, []) assert gf_factor_sqf([1, 1], 11, ZZ) == (1, [[1, 1]]) config.setup('GF_FACTOR_METHOD', 'shoup') assert gf_factor_sqf(ZZ.map([]), 11, ZZ) == (0, []) assert gf_factor_sqf(ZZ.map([1]), 11, ZZ) == (1, []) assert gf_factor_sqf(ZZ.map([1, 1]), 11, ZZ) == (1, [[1, 1]]) f, p = ZZ.map([1, 0, 0, 1, 0]), 2 g = (1, [([1, 0], 1), ([1, 1], 1), ([1, 1, 1], 1)]) config.setup('GF_FACTOR_METHOD', 'berlekamp') assert gf_factor(f, p, ZZ) == g config.setup('GF_FACTOR_METHOD', 'zassenhaus') assert gf_factor(f, p, ZZ) == g config.setup('GF_FACTOR_METHOD', 'shoup') assert gf_factor(f, p, ZZ) == g g = (1, [[1, 0], [1, 1], [1, 1, 1]]) config.setup('GF_FACTOR_METHOD', 'berlekamp') assert gf_factor_sqf(f, p, ZZ) == g config.setup('GF_FACTOR_METHOD', 'zassenhaus') assert gf_factor_sqf(f, p, ZZ) == g config.setup('GF_FACTOR_METHOD', 'shoup') assert gf_factor_sqf(f, p, ZZ) == g f, p = gf_from_int_poly([1, -3, 1, -3, -1, -3, 1], 11), 11 g = (1, [([1, 1], 1), ([1, 5, 3], 1), ([1, 2, 3, 4], 1)]) config.setup('GF_FACTOR_METHOD', 'berlekamp') assert gf_factor(f, p, ZZ) == g config.setup('GF_FACTOR_METHOD', 'zassenhaus') assert gf_factor(f, p, ZZ) == g config.setup('GF_FACTOR_METHOD', 'shoup') assert gf_factor(f, p, ZZ) == g f, p = [1, 5, 8, 4], 11 g = (1, [([1, 1], 1), ([1, 2], 2)]) config.setup('GF_FACTOR_METHOD', 'berlekamp') assert gf_factor(f, p, ZZ) == g config.setup('GF_FACTOR_METHOD', 'zassenhaus') assert gf_factor(f, p, ZZ) == g config.setup('GF_FACTOR_METHOD', 'shoup') assert gf_factor(f, p, ZZ) == g f, p = [1, 1, 10, 1, 0, 10, 10, 10, 0, 0], 11 g = (1, [([1, 0], 2), ([1, 9, 5], 1), ([1, 3, 0, 8, 5, 2], 1)]) config.setup('GF_FACTOR_METHOD', 'berlekamp') assert gf_factor(f, p, ZZ) == g config.setup('GF_FACTOR_METHOD', 'zassenhaus') assert gf_factor(f, p, ZZ) == g config.setup('GF_FACTOR_METHOD', 'shoup') assert gf_factor(f, p, ZZ) == g f, p = gf_from_dict({32: 1, 0: 1}, 11, ZZ), 11 g = (1, [([1, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 10], 1), ([1, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0, 10], 1)]) config.setup('GF_FACTOR_METHOD', 'berlekamp') assert gf_factor(f, p, ZZ) == g config.setup('GF_FACTOR_METHOD', 'zassenhaus') assert gf_factor(f, p, ZZ) == g config.setup('GF_FACTOR_METHOD', 'shoup') assert gf_factor(f, p, ZZ) == g f, p = gf_from_dict({32: ZZ(8), 0: ZZ(5)}, 11, ZZ), 11 g = (8, [([1, 3], 1), ([1, 8], 1), ([1, 0, 9], 1), ([1, 2, 2], 1), ([1, 9, 2], 1), ([1, 0, 5, 0, 7], 1), ([1, 0, 6, 0, 7], 1), ([1, 0, 0, 0, 1, 0, 0, 0, 6], 1), ([1, 0, 0, 0, 10, 0, 0, 0, 6], 1)]) config.setup('GF_FACTOR_METHOD', 'berlekamp') assert gf_factor(f, p, ZZ) == g config.setup('GF_FACTOR_METHOD', 'zassenhaus') assert gf_factor(f, p, ZZ) == g config.setup('GF_FACTOR_METHOD', 'shoup') assert gf_factor(f, p, ZZ) == g f, p = gf_from_dict({63: ZZ(8), 0: ZZ(5)}, 11, ZZ), 11 g = (8, [([1, 7], 1), ([1, 4, 5], 1), ([1, 6, 8, 2], 1), ([1, 9, 9, 2], 1), ([1, 0, 0, 9, 0, 0, 4], 1), ([1, 2, 0, 8, 4, 6, 4], 1), ([1, 2, 3, 8, 0, 6, 4], 1), ([1, 2, 6, 0, 8, 4, 4], 1), ([1, 3, 3, 1, 6, 8, 4], 1), ([1, 5, 6, 0, 8, 6, 4], 1), ([1, 6, 2, 7, 9, 8, 4], 1), ([1, 10, 4, 7, 10, 7, 4], 1), ([1, 10, 10, 1, 4, 9, 4], 1)]) config.setup('GF_FACTOR_METHOD', 'berlekamp') assert gf_factor(f, p, ZZ) == g config.setup('GF_FACTOR_METHOD', 'zassenhaus') assert gf_factor(f, p, ZZ) == g config.setup('GF_FACTOR_METHOD', 'shoup') assert gf_factor(f, p, ZZ) == g # Gathen polynomials: x**n + x + 1 (mod p > 2**n * pi) p = ZZ(nextprime(int((2**15 * pi).evalf()))) f = gf_from_dict({15: 1, 1: 1, 0: 1}, p, ZZ) assert gf_sqf_p(f, p, ZZ) is True g = (1, [([1, 22730, 68144], 1), ([1, 81553, 77449, 86810, 4724], 1), ([1, 86276, 56779, 14859, 31575], 1), ([1, 15347, 95022, 84569, 94508, 92335], 1)]) config.setup('GF_FACTOR_METHOD', 'zassenhaus') assert gf_factor(f, p, ZZ) == g config.setup('GF_FACTOR_METHOD', 'shoup') assert gf_factor(f, p, ZZ) == g g = (1, [[1, 22730, 68144], [1, 81553, 77449, 86810, 4724], [1, 86276, 56779, 14859, 31575], [1, 15347, 95022, 84569, 94508, 92335]]) config.setup('GF_FACTOR_METHOD', 'zassenhaus') assert gf_factor_sqf(f, p, ZZ) == g config.setup('GF_FACTOR_METHOD', 'shoup') assert gf_factor_sqf(f, p, ZZ) == g # Shoup polynomials: f = a_0 x**n + a_1 x**(n-1) + ... + a_n # (mod p > 2**(n-2) * pi), where a_n = a_{n-1}**2 + 1, a_0 = 1 p = ZZ(nextprime(int((2**4 * pi).evalf()))) f = ZZ.map([1, 2, 5, 26, 41, 39, 38]) assert gf_sqf_p(f, p, ZZ) is True g = (1, [([1, 44, 26], 1), ([1, 11, 25, 18, 30], 1)]) config.setup('GF_FACTOR_METHOD', 'zassenhaus') assert gf_factor(f, p, ZZ) == g config.setup('GF_FACTOR_METHOD', 'shoup') assert gf_factor(f, p, ZZ) == g g = (1, [[1, 44, 26], [1, 11, 25, 18, 30]]) config.setup('GF_FACTOR_METHOD', 'zassenhaus') assert gf_factor_sqf(f, p, ZZ) == g config.setup('GF_FACTOR_METHOD', 'shoup') assert gf_factor_sqf(f, p, ZZ) == g config.setup('GF_FACTOR_METHOD', 'other') raises(KeyError, lambda: gf_factor([1, 1], 11, ZZ)) config.setup('GF_FACTOR_METHOD') def test_gf_csolve(): assert gf_value([1, 7, 2, 4], 11) == 2204 assert linear_congruence(4, 3, 5) == [2] assert linear_congruence(0, 3, 5) == [] assert linear_congruence(6, 1, 4) == [] assert linear_congruence(0, 5, 5) == [0, 1, 2, 3, 4] assert linear_congruence(3, 12, 15) == [4, 9, 14] assert linear_congruence(6, 0, 18) == [0, 3, 6, 9, 12, 15] # with power = 1 assert csolve_prime([1, 3, 2, 17], 7) == [3] assert csolve_prime([1, 3, 1, 5], 5) == [0, 1] assert csolve_prime([3, 6, 9, 3], 3) == [0, 1, 2] # with power > 1 assert csolve_prime( [1, 1, 223], 3, 4) == [4, 13, 22, 31, 40, 49, 58, 67, 76] assert csolve_prime([3, 5, 2, 25], 5, 3) == [16, 50, 99] assert csolve_prime([3, 2, 2, 49], 7, 3) == [147, 190, 234] assert gf_csolve([1, 1, 7], 189) == [13, 49, 76, 112, 139, 175] assert gf_csolve([1, 3, 4, 1, 30], 60) == [10, 30] assert gf_csolve([1, 1, 7], 15) == []
c7e9fe4fe0a89fef2985e94d6b4e413ecce40bf5025b50b4c803b0cfae7c23ad
"""Tests for real and complex root isolation and refinement algorithms. """ from sympy.polys.rings import ring from sympy.polys.domains import ZZ, QQ, ZZ_I, EX from sympy.polys.polyerrors import DomainError, RefinementFailed, PolynomialError from sympy.polys.rootisolation import ( dup_cauchy_upper_bound, dup_cauchy_lower_bound, dup_mignotte_sep_bound_squared, ) from sympy.testing.pytest import raises def test_dup_sturm(): R, x = ring("x", QQ) assert R.dup_sturm(5) == [1] assert R.dup_sturm(x) == [x, 1] f = x**3 - 2*x**2 + 3*x - 5 assert R.dup_sturm(f) == [f, 3*x**2 - 4*x + 3, -QQ(10,9)*x + QQ(13,3), -QQ(3303,100)] def test_dup_cauchy_upper_bound(): raises(PolynomialError, lambda: dup_cauchy_upper_bound([], QQ)) raises(PolynomialError, lambda: dup_cauchy_upper_bound([QQ(1)], QQ)) raises(DomainError, lambda: dup_cauchy_upper_bound([ZZ_I(1), ZZ_I(1)], ZZ_I)) assert dup_cauchy_upper_bound([QQ(1), QQ(0), QQ(0)], QQ) == QQ.zero assert dup_cauchy_upper_bound([QQ(1), QQ(0), QQ(-2)], QQ) == QQ(3) def test_dup_cauchy_lower_bound(): raises(PolynomialError, lambda: dup_cauchy_lower_bound([], QQ)) raises(PolynomialError, lambda: dup_cauchy_lower_bound([QQ(1)], QQ)) raises(PolynomialError, lambda: dup_cauchy_lower_bound([QQ(1), QQ(0), QQ(0)], QQ)) raises(DomainError, lambda: dup_cauchy_lower_bound([ZZ_I(1), ZZ_I(1)], ZZ_I)) assert dup_cauchy_lower_bound([QQ(1), QQ(0), QQ(-2)], QQ) == QQ(2, 3) def test_dup_mignotte_sep_bound_squared(): raises(PolynomialError, lambda: dup_mignotte_sep_bound_squared([], QQ)) raises(PolynomialError, lambda: dup_mignotte_sep_bound_squared([QQ(1)], QQ)) assert dup_mignotte_sep_bound_squared([QQ(1), QQ(0), QQ(-2)], QQ) == QQ(3, 5) def test_dup_refine_real_root(): R, x = ring("x", ZZ) f = x**2 - 2 assert R.dup_refine_real_root(f, QQ(1), QQ(1), steps=1) == (QQ(1), QQ(1)) assert R.dup_refine_real_root(f, QQ(1), QQ(1), steps=9) == (QQ(1), QQ(1)) raises(ValueError, lambda: R.dup_refine_real_root(f, QQ(-2), QQ(2))) s, t = QQ(1, 1), QQ(2, 1) assert R.dup_refine_real_root(f, s, t, steps=0) == (QQ(1, 1), QQ(2, 1)) assert R.dup_refine_real_root(f, s, t, steps=1) == (QQ(1, 1), QQ(3, 2)) assert R.dup_refine_real_root(f, s, t, steps=2) == (QQ(4, 3), QQ(3, 2)) assert R.dup_refine_real_root(f, s, t, steps=3) == (QQ(7, 5), QQ(3, 2)) assert R.dup_refine_real_root(f, s, t, steps=4) == (QQ(7, 5), QQ(10, 7)) s, t = QQ(1, 1), QQ(3, 2) assert R.dup_refine_real_root(f, s, t, steps=0) == (QQ(1, 1), QQ(3, 2)) assert R.dup_refine_real_root(f, s, t, steps=1) == (QQ(4, 3), QQ(3, 2)) assert R.dup_refine_real_root(f, s, t, steps=2) == (QQ(7, 5), QQ(3, 2)) assert R.dup_refine_real_root(f, s, t, steps=3) == (QQ(7, 5), QQ(10, 7)) assert R.dup_refine_real_root(f, s, t, steps=4) == (QQ(7, 5), QQ(17, 12)) s, t = QQ(1, 1), QQ(5, 3) assert R.dup_refine_real_root(f, s, t, steps=0) == (QQ(1, 1), QQ(5, 3)) assert R.dup_refine_real_root(f, s, t, steps=1) == (QQ(1, 1), QQ(3, 2)) assert R.dup_refine_real_root(f, s, t, steps=2) == (QQ(7, 5), QQ(3, 2)) assert R.dup_refine_real_root(f, s, t, steps=3) == (QQ(7, 5), QQ(13, 9)) assert R.dup_refine_real_root(f, s, t, steps=4) == (QQ(7, 5), QQ(27, 19)) s, t = QQ(-1, 1), QQ(-2, 1) assert R.dup_refine_real_root(f, s, t, steps=0) == (-QQ(2, 1), -QQ(1, 1)) assert R.dup_refine_real_root(f, s, t, steps=1) == (-QQ(3, 2), -QQ(1, 1)) assert R.dup_refine_real_root(f, s, t, steps=2) == (-QQ(3, 2), -QQ(4, 3)) assert R.dup_refine_real_root(f, s, t, steps=3) == (-QQ(3, 2), -QQ(7, 5)) assert R.dup_refine_real_root(f, s, t, steps=4) == (-QQ(10, 7), -QQ(7, 5)) raises(RefinementFailed, lambda: R.dup_refine_real_root(f, QQ(0), QQ(1))) s, t, u, v, w = QQ(1), QQ(2), QQ(24, 17), QQ(17, 12), QQ(7, 5) assert R.dup_refine_real_root(f, s, t, eps=QQ(1, 100)) == (u, v) assert R.dup_refine_real_root(f, s, t, steps=6) == (u, v) assert R.dup_refine_real_root(f, s, t, eps=QQ(1, 100), steps=5) == (w, v) assert R.dup_refine_real_root(f, s, t, eps=QQ(1, 100), steps=6) == (u, v) assert R.dup_refine_real_root(f, s, t, eps=QQ(1, 100), steps=7) == (u, v) s, t, u, v = QQ(-2), QQ(-1), QQ(-3, 2), QQ(-4, 3) assert R.dup_refine_real_root(f, s, t, disjoint=QQ(-5)) == (s, t) assert R.dup_refine_real_root(f, s, t, disjoint=-v) == (s, t) assert R.dup_refine_real_root(f, s, t, disjoint=v) == (u, v) s, t, u, v = QQ(1), QQ(2), QQ(4, 3), QQ(3, 2) assert R.dup_refine_real_root(f, s, t, disjoint=QQ(5)) == (s, t) assert R.dup_refine_real_root(f, s, t, disjoint=-u) == (s, t) assert R.dup_refine_real_root(f, s, t, disjoint=u) == (u, v) def test_dup_isolate_real_roots_sqf(): R, x = ring("x", ZZ) assert R.dup_isolate_real_roots_sqf(0) == [] assert R.dup_isolate_real_roots_sqf(5) == [] assert R.dup_isolate_real_roots_sqf(x**2 + x) == [(-1, -1), (0, 0)] assert R.dup_isolate_real_roots_sqf(x**2 - x) == [( 0, 0), (1, 1)] assert R.dup_isolate_real_roots_sqf(x**4 + x + 1) == [] I = [(-2, -1), (1, 2)] assert R.dup_isolate_real_roots_sqf(x**2 - 2) == I assert R.dup_isolate_real_roots_sqf(-x**2 + 2) == I assert R.dup_isolate_real_roots_sqf(x - 1) == \ [(1, 1)] assert R.dup_isolate_real_roots_sqf(x**2 - 3*x + 2) == \ [(1, 1), (2, 2)] assert R.dup_isolate_real_roots_sqf(x**3 - 6*x**2 + 11*x - 6) == \ [(1, 1), (2, 2), (3, 3)] assert R.dup_isolate_real_roots_sqf(x**4 - 10*x**3 + 35*x**2 - 50*x + 24) == \ [(1, 1), (2, 2), (3, 3), (4, 4)] assert R.dup_isolate_real_roots_sqf(x**5 - 15*x**4 + 85*x**3 - 225*x**2 + 274*x - 120) == \ [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5)] assert R.dup_isolate_real_roots_sqf(x - 10) == \ [(10, 10)] assert R.dup_isolate_real_roots_sqf(x**2 - 30*x + 200) == \ [(10, 10), (20, 20)] assert R.dup_isolate_real_roots_sqf(x**3 - 60*x**2 + 1100*x - 6000) == \ [(10, 10), (20, 20), (30, 30)] assert R.dup_isolate_real_roots_sqf(x**4 - 100*x**3 + 3500*x**2 - 50000*x + 240000) == \ [(10, 10), (20, 20), (30, 30), (40, 40)] assert R.dup_isolate_real_roots_sqf(x**5 - 150*x**4 + 8500*x**3 - 225000*x**2 + 2740000*x - 12000000) == \ [(10, 10), (20, 20), (30, 30), (40, 40), (50, 50)] assert R.dup_isolate_real_roots_sqf(x + 1) == \ [(-1, -1)] assert R.dup_isolate_real_roots_sqf(x**2 + 3*x + 2) == \ [(-2, -2), (-1, -1)] assert R.dup_isolate_real_roots_sqf(x**3 + 6*x**2 + 11*x + 6) == \ [(-3, -3), (-2, -2), (-1, -1)] assert R.dup_isolate_real_roots_sqf(x**4 + 10*x**3 + 35*x**2 + 50*x + 24) == \ [(-4, -4), (-3, -3), (-2, -2), (-1, -1)] assert R.dup_isolate_real_roots_sqf(x**5 + 15*x**4 + 85*x**3 + 225*x**2 + 274*x + 120) == \ [(-5, -5), (-4, -4), (-3, -3), (-2, -2), (-1, -1)] assert R.dup_isolate_real_roots_sqf(x + 10) == \ [(-10, -10)] assert R.dup_isolate_real_roots_sqf(x**2 + 30*x + 200) == \ [(-20, -20), (-10, -10)] assert R.dup_isolate_real_roots_sqf(x**3 + 60*x**2 + 1100*x + 6000) == \ [(-30, -30), (-20, -20), (-10, -10)] assert R.dup_isolate_real_roots_sqf(x**4 + 100*x**3 + 3500*x**2 + 50000*x + 240000) == \ [(-40, -40), (-30, -30), (-20, -20), (-10, -10)] assert R.dup_isolate_real_roots_sqf(x**5 + 150*x**4 + 8500*x**3 + 225000*x**2 + 2740000*x + 12000000) == \ [(-50, -50), (-40, -40), (-30, -30), (-20, -20), (-10, -10)] assert R.dup_isolate_real_roots_sqf(x**2 - 5) == [(-3, -2), (2, 3)] assert R.dup_isolate_real_roots_sqf(x**3 - 5) == [(1, 2)] assert R.dup_isolate_real_roots_sqf(x**4 - 5) == [(-2, -1), (1, 2)] assert R.dup_isolate_real_roots_sqf(x**5 - 5) == [(1, 2)] assert R.dup_isolate_real_roots_sqf(x**6 - 5) == [(-2, -1), (1, 2)] assert R.dup_isolate_real_roots_sqf(x**7 - 5) == [(1, 2)] assert R.dup_isolate_real_roots_sqf(x**8 - 5) == [(-2, -1), (1, 2)] assert R.dup_isolate_real_roots_sqf(x**9 - 5) == [(1, 2)] assert R.dup_isolate_real_roots_sqf(x**2 - 1) == \ [(-1, -1), (1, 1)] assert R.dup_isolate_real_roots_sqf(x**3 + 2*x**2 - x - 2) == \ [(-2, -2), (-1, -1), (1, 1)] assert R.dup_isolate_real_roots_sqf(x**4 - 5*x**2 + 4) == \ [(-2, -2), (-1, -1), (1, 1), (2, 2)] assert R.dup_isolate_real_roots_sqf(x**5 + 3*x**4 - 5*x**3 - 15*x**2 + 4*x + 12) == \ [(-3, -3), (-2, -2), (-1, -1), (1, 1), (2, 2)] assert R.dup_isolate_real_roots_sqf(x**6 - 14*x**4 + 49*x**2 - 36) == \ [(-3, -3), (-2, -2), (-1, -1), (1, 1), (2, 2), (3, 3)] assert R.dup_isolate_real_roots_sqf(2*x**7 + x**6 - 28*x**5 - 14*x**4 + 98*x**3 + 49*x**2 - 72*x - 36) == \ [(-3, -3), (-2, -2), (-1, -1), (-1, 0), (1, 1), (2, 2), (3, 3)] assert R.dup_isolate_real_roots_sqf(4*x**8 - 57*x**6 + 210*x**4 - 193*x**2 + 36) == \ [(-3, -3), (-2, -2), (-1, -1), (-1, 0), (0, 1), (1, 1), (2, 2), (3, 3)] f = 9*x**2 - 2 assert R.dup_isolate_real_roots_sqf(f) == \ [(-1, 0), (0, 1)] assert R.dup_isolate_real_roots_sqf(f, eps=QQ(1, 10)) == \ [(QQ(-1, 2), QQ(-3, 7)), (QQ(3, 7), QQ(1, 2))] assert R.dup_isolate_real_roots_sqf(f, eps=QQ(1, 100)) == \ [(QQ(-9, 19), QQ(-8, 17)), (QQ(8, 17), QQ(9, 19))] assert R.dup_isolate_real_roots_sqf(f, eps=QQ(1, 1000)) == \ [(QQ(-33, 70), QQ(-8, 17)), (QQ(8, 17), QQ(33, 70))] assert R.dup_isolate_real_roots_sqf(f, eps=QQ(1, 10000)) == \ [(QQ(-33, 70), QQ(-107, 227)), (QQ(107, 227), QQ(33, 70))] assert R.dup_isolate_real_roots_sqf(f, eps=QQ(1, 100000)) == \ [(QQ(-305, 647), QQ(-272, 577)), (QQ(272, 577), QQ(305, 647))] assert R.dup_isolate_real_roots_sqf(f, eps=QQ(1, 1000000)) == \ [(QQ(-1121, 2378), QQ(-272, 577)), (QQ(272, 577), QQ(1121, 2378))] f = 200100012*x**5 - 700390052*x**4 + 700490079*x**3 - 200240054*x**2 + 40017*x - 2 assert R.dup_isolate_real_roots_sqf(f) == \ [(QQ(0), QQ(1, 10002)), (QQ(1, 10002), QQ(1, 10002)), (QQ(1, 2), QQ(1, 2)), (QQ(1), QQ(1)), (QQ(2), QQ(2))] assert R.dup_isolate_real_roots_sqf(f, eps=QQ(1, 100000)) == \ [(QQ(1, 10003), QQ(1, 10003)), (QQ(1, 10002), QQ(1, 10002)), (QQ(1, 2), QQ(1, 2)), (QQ(1), QQ(1)), (QQ(2), QQ(2))] a, b, c, d = 10000090000001, 2000100003, 10000300007, 10000005000008 f = 20001600074001600021*x**4 \ + 1700135866278935491773999857*x**3 \ - 2000179008931031182161141026995283662899200197*x**2 \ - 800027600594323913802305066986600025*x \ + 100000950000540000725000008 assert R.dup_isolate_real_roots_sqf(f) == \ [(-a, -a), (-1, 0), (0, 1), (d, d)] assert R.dup_isolate_real_roots_sqf(f, eps=QQ(1, 100000000000)) == \ [(-QQ(a), -QQ(a)), (-QQ(1, b), -QQ(1, b)), (QQ(1, c), QQ(1, c)), (QQ(d), QQ(d))] (u, v), B, C, (s, t) = R.dup_isolate_real_roots_sqf(f, fast=True) assert u < -a < v and B == (-QQ(1), QQ(0)) and C == (QQ(0), QQ(1)) and s < d < t assert R.dup_isolate_real_roots_sqf(f, fast=True, eps=QQ(1, 100000000000000000000000000000)) == \ [(-QQ(a), -QQ(a)), (-QQ(1, b), -QQ(1, b)), (QQ(1, c), QQ(1, c)), (QQ(d), QQ(d))] f = -10*x**4 + 8*x**3 + 80*x**2 - 32*x - 160 assert R.dup_isolate_real_roots_sqf(f) == \ [(-2, -2), (-2, -1), (2, 2), (2, 3)] assert R.dup_isolate_real_roots_sqf(f, eps=QQ(1, 100)) == \ [(-QQ(2), -QQ(2)), (-QQ(23, 14), -QQ(18, 11)), (QQ(2), QQ(2)), (QQ(39, 16), QQ(22, 9))] f = x - 1 assert R.dup_isolate_real_roots_sqf(f, inf=2) == [] assert R.dup_isolate_real_roots_sqf(f, sup=0) == [] assert R.dup_isolate_real_roots_sqf(f) == [(1, 1)] assert R.dup_isolate_real_roots_sqf(f, inf=1) == [(1, 1)] assert R.dup_isolate_real_roots_sqf(f, sup=1) == [(1, 1)] assert R.dup_isolate_real_roots_sqf(f, inf=1, sup=1) == [(1, 1)] f = x**2 - 2 assert R.dup_isolate_real_roots_sqf(f, inf=QQ(7, 4)) == [] assert R.dup_isolate_real_roots_sqf(f, inf=QQ(7, 5)) == [(QQ(7, 5), QQ(3, 2))] assert R.dup_isolate_real_roots_sqf(f, sup=QQ(7, 5)) == [(-2, -1)] assert R.dup_isolate_real_roots_sqf(f, sup=QQ(7, 4)) == [(-2, -1), (1, QQ(3, 2))] assert R.dup_isolate_real_roots_sqf(f, sup=-QQ(7, 4)) == [] assert R.dup_isolate_real_roots_sqf(f, sup=-QQ(7, 5)) == [(-QQ(3, 2), -QQ(7, 5))] assert R.dup_isolate_real_roots_sqf(f, inf=-QQ(7, 5)) == [(1, 2)] assert R.dup_isolate_real_roots_sqf(f, inf=-QQ(7, 4)) == [(-QQ(3, 2), -1), (1, 2)] I = [(-2, -1), (1, 2)] assert R.dup_isolate_real_roots_sqf(f, inf=-2) == I assert R.dup_isolate_real_roots_sqf(f, sup=+2) == I assert R.dup_isolate_real_roots_sqf(f, inf=-2, sup=2) == I R, x = ring("x", QQ) f = QQ(8, 5)*x**2 - QQ(87374, 3855)*x - QQ(17, 771) assert R.dup_isolate_real_roots_sqf(f) == [(-1, 0), (14, 15)] R, x = ring("x", EX) raises(DomainError, lambda: R.dup_isolate_real_roots_sqf(x + 3)) def test_dup_isolate_real_roots(): R, x = ring("x", ZZ) assert R.dup_isolate_real_roots(0) == [] assert R.dup_isolate_real_roots(3) == [] assert R.dup_isolate_real_roots(5*x) == [((0, 0), 1)] assert R.dup_isolate_real_roots(7*x**4) == [((0, 0), 4)] assert R.dup_isolate_real_roots(x**2 + x) == [((-1, -1), 1), ((0, 0), 1)] assert R.dup_isolate_real_roots(x**2 - x) == [((0, 0), 1), ((1, 1), 1)] assert R.dup_isolate_real_roots(x**4 + x + 1) == [] I = [((-2, -1), 1), ((1, 2), 1)] assert R.dup_isolate_real_roots(x**2 - 2) == I assert R.dup_isolate_real_roots(-x**2 + 2) == I f = 16*x**14 - 96*x**13 + 24*x**12 + 936*x**11 - 1599*x**10 - 2880*x**9 + 9196*x**8 \ + 552*x**7 - 21831*x**6 + 13968*x**5 + 21690*x**4 - 26784*x**3 - 2916*x**2 + 15552*x - 5832 g = R.dup_sqf_part(f) assert R.dup_isolate_real_roots(f) == \ [((-QQ(2), -QQ(3, 2)), 2), ((-QQ(3, 2), -QQ(1, 1)), 3), ((QQ(1), QQ(3, 2)), 3), ((QQ(3, 2), QQ(3, 2)), 4), ((QQ(5, 3), QQ(2)), 2)] assert R.dup_isolate_real_roots_sqf(g) == \ [(-QQ(2), -QQ(3, 2)), (-QQ(3, 2), -QQ(1, 1)), (QQ(1), QQ(3, 2)), (QQ(3, 2), QQ(3, 2)), (QQ(3, 2), QQ(2))] assert R.dup_isolate_real_roots(g) == \ [((-QQ(2), -QQ(3, 2)), 1), ((-QQ(3, 2), -QQ(1, 1)), 1), ((QQ(1), QQ(3, 2)), 1), ((QQ(3, 2), QQ(3, 2)), 1), ((QQ(3, 2), QQ(2)), 1)] f = x - 1 assert R.dup_isolate_real_roots(f, inf=2) == [] assert R.dup_isolate_real_roots(f, sup=0) == [] assert R.dup_isolate_real_roots(f) == [((1, 1), 1)] assert R.dup_isolate_real_roots(f, inf=1) == [((1, 1), 1)] assert R.dup_isolate_real_roots(f, sup=1) == [((1, 1), 1)] assert R.dup_isolate_real_roots(f, inf=1, sup=1) == [((1, 1), 1)] f = x**4 - 4*x**2 + 4 assert R.dup_isolate_real_roots(f, inf=QQ(7, 4)) == [] assert R.dup_isolate_real_roots(f, inf=QQ(7, 5)) == [((QQ(7, 5), QQ(3, 2)), 2)] assert R.dup_isolate_real_roots(f, sup=QQ(7, 5)) == [((-2, -1), 2)] assert R.dup_isolate_real_roots(f, sup=QQ(7, 4)) == [((-2, -1), 2), ((1, QQ(3, 2)), 2)] assert R.dup_isolate_real_roots(f, sup=-QQ(7, 4)) == [] assert R.dup_isolate_real_roots(f, sup=-QQ(7, 5)) == [((-QQ(3, 2), -QQ(7, 5)), 2)] assert R.dup_isolate_real_roots(f, inf=-QQ(7, 5)) == [((1, 2), 2)] assert R.dup_isolate_real_roots(f, inf=-QQ(7, 4)) == [((-QQ(3, 2), -1), 2), ((1, 2), 2)] I = [((-2, -1), 2), ((1, 2), 2)] assert R.dup_isolate_real_roots(f, inf=-2) == I assert R.dup_isolate_real_roots(f, sup=+2) == I assert R.dup_isolate_real_roots(f, inf=-2, sup=2) == I f = x**11 - 3*x**10 - x**9 + 11*x**8 - 8*x**7 - 8*x**6 + 12*x**5 - 4*x**4 assert R.dup_isolate_real_roots(f, basis=False) == \ [((-2, -1), 2), ((0, 0), 4), ((1, 1), 3), ((1, 2), 2)] assert R.dup_isolate_real_roots(f, basis=True) == \ [((-2, -1), 2, [1, 0, -2]), ((0, 0), 4, [1, 0]), ((1, 1), 3, [1, -1]), ((1, 2), 2, [1, 0, -2])] f = (x**45 - 45*x**44 + 990*x**43 - 1) g = (x**46 - 15180*x**43 + 9366819*x**40 - 53524680*x**39 + 260932815*x**38 - 1101716330*x**37 + 4076350421*x**36 - 13340783196*x**35 + 38910617655*x**34 - 101766230790*x**33 + 239877544005*x**32 - 511738760544*x**31 + 991493848554*x**30 - 1749695026860*x**29 + 2818953098830*x**28 - 4154246671960*x**27 + 5608233007146*x**26 - 6943526580276*x**25 + 7890371113950*x**24 - 8233430727600*x**23 + 7890371113950*x**22 - 6943526580276*x**21 + 5608233007146*x**20 - 4154246671960*x**19 + 2818953098830*x**18 - 1749695026860*x**17 + 991493848554*x**16 - 511738760544*x**15 + 239877544005*x**14 - 101766230790*x**13 + 38910617655*x**12 - 13340783196*x**11 + 4076350421*x**10 - 1101716330*x**9 + 260932815*x**8 - 53524680*x**7 + 9366819*x**6 - 1370754*x**5 + 163185*x**4 - 15180*x**3 + 1035*x**2 - 47*x + 1) assert R.dup_isolate_real_roots(f*g) == \ [((0, QQ(1, 2)), 1), ((QQ(2, 3), QQ(3, 4)), 1), ((QQ(3, 4), 1), 1), ((6, 7), 1), ((24, 25), 1)] R, x = ring("x", EX) raises(DomainError, lambda: R.dup_isolate_real_roots(x + 3)) def test_dup_isolate_real_roots_list(): R, x = ring("x", ZZ) assert R.dup_isolate_real_roots_list([x**2 + x, x]) == \ [((-1, -1), {0: 1}), ((0, 0), {0: 1, 1: 1})] assert R.dup_isolate_real_roots_list([x**2 - x, x]) == \ [((0, 0), {0: 1, 1: 1}), ((1, 1), {0: 1})] assert R.dup_isolate_real_roots_list([x + 1, x + 2, x - 1, x + 1, x - 1, x - 1]) == \ [((-QQ(2), -QQ(2)), {1: 1}), ((-QQ(1), -QQ(1)), {0: 1, 3: 1}), ((QQ(1), QQ(1)), {2: 1, 4: 1, 5: 1})] assert R.dup_isolate_real_roots_list([x + 1, x + 2, x - 1, x + 1, x - 1, x + 2]) == \ [((-QQ(2), -QQ(2)), {1: 1, 5: 1}), ((-QQ(1), -QQ(1)), {0: 1, 3: 1}), ((QQ(1), QQ(1)), {2: 1, 4: 1})] f, g = x**4 - 4*x**2 + 4, x - 1 assert R.dup_isolate_real_roots_list([f, g], inf=QQ(7, 4)) == [] assert R.dup_isolate_real_roots_list([f, g], inf=QQ(7, 5)) == \ [((QQ(7, 5), QQ(3, 2)), {0: 2})] assert R.dup_isolate_real_roots_list([f, g], sup=QQ(7, 5)) == \ [((-2, -1), {0: 2}), ((1, 1), {1: 1})] assert R.dup_isolate_real_roots_list([f, g], sup=QQ(7, 4)) == \ [((-2, -1), {0: 2}), ((1, 1), {1: 1}), ((1, QQ(3, 2)), {0: 2})] assert R.dup_isolate_real_roots_list([f, g], sup=-QQ(7, 4)) == [] assert R.dup_isolate_real_roots_list([f, g], sup=-QQ(7, 5)) == \ [((-QQ(3, 2), -QQ(7, 5)), {0: 2})] assert R.dup_isolate_real_roots_list([f, g], inf=-QQ(7, 5)) == \ [((1, 1), {1: 1}), ((1, 2), {0: 2})] assert R.dup_isolate_real_roots_list([f, g], inf=-QQ(7, 4)) == \ [((-QQ(3, 2), -1), {0: 2}), ((1, 1), {1: 1}), ((1, 2), {0: 2})] f, g = 2*x**2 - 1, x**2 - 2 assert R.dup_isolate_real_roots_list([f, g]) == \ [((-QQ(2), -QQ(1)), {1: 1}), ((-QQ(1), QQ(0)), {0: 1}), ((QQ(0), QQ(1)), {0: 1}), ((QQ(1), QQ(2)), {1: 1})] assert R.dup_isolate_real_roots_list([f, g], strict=True) == \ [((-QQ(3, 2), -QQ(4, 3)), {1: 1}), ((-QQ(1), -QQ(2, 3)), {0: 1}), ((QQ(2, 3), QQ(1)), {0: 1}), ((QQ(4, 3), QQ(3, 2)), {1: 1})] f, g = x**2 - 2, x**3 - x**2 - 2*x + 2 assert R.dup_isolate_real_roots_list([f, g]) == \ [((-QQ(2), -QQ(1)), {1: 1, 0: 1}), ((QQ(1), QQ(1)), {1: 1}), ((QQ(1), QQ(2)), {1: 1, 0: 1})] f, g = x**3 - 2*x, x**5 - x**4 - 2*x**3 + 2*x**2 assert R.dup_isolate_real_roots_list([f, g]) == \ [((-QQ(2), -QQ(1)), {1: 1, 0: 1}), ((QQ(0), QQ(0)), {0: 1, 1: 2}), ((QQ(1), QQ(1)), {1: 1}), ((QQ(1), QQ(2)), {1: 1, 0: 1})] f, g = x**9 - 3*x**8 - x**7 + 11*x**6 - 8*x**5 - 8*x**4 + 12*x**3 - 4*x**2, x**5 - 2*x**4 + 3*x**3 - 4*x**2 + 2*x assert R.dup_isolate_real_roots_list([f, g], basis=False) == \ [((-2, -1), {0: 2}), ((0, 0), {0: 2, 1: 1}), ((1, 1), {0: 3, 1: 2}), ((1, 2), {0: 2})] assert R.dup_isolate_real_roots_list([f, g], basis=True) == \ [((-2, -1), {0: 2}, [1, 0, -2]), ((0, 0), {0: 2, 1: 1}, [1, 0]), ((1, 1), {0: 3, 1: 2}, [1, -1]), ((1, 2), {0: 2}, [1, 0, -2])] R, x = ring("x", EX) raises(DomainError, lambda: R.dup_isolate_real_roots_list([x + 3])) def test_dup_isolate_real_roots_list_QQ(): R, x = ring("x", ZZ) f = x**5 - 200 g = x**5 - 201 assert R.dup_isolate_real_roots_list([f, g]) == \ [((QQ(75, 26), QQ(101, 35)), {0: 1}), ((QQ(309, 107), QQ(26, 9)), {1: 1})] R, x = ring("x", QQ) f = -QQ(1, 200)*x**5 + 1 g = -QQ(1, 201)*x**5 + 1 assert R.dup_isolate_real_roots_list([f, g]) == \ [((QQ(75, 26), QQ(101, 35)), {0: 1}), ((QQ(309, 107), QQ(26, 9)), {1: 1})] def test_dup_count_real_roots(): R, x = ring("x", ZZ) assert R.dup_count_real_roots(0) == 0 assert R.dup_count_real_roots(7) == 0 f = x - 1 assert R.dup_count_real_roots(f) == 1 assert R.dup_count_real_roots(f, inf=1) == 1 assert R.dup_count_real_roots(f, sup=0) == 0 assert R.dup_count_real_roots(f, sup=1) == 1 assert R.dup_count_real_roots(f, inf=0, sup=1) == 1 assert R.dup_count_real_roots(f, inf=0, sup=2) == 1 assert R.dup_count_real_roots(f, inf=1, sup=2) == 1 f = x**2 - 2 assert R.dup_count_real_roots(f) == 2 assert R.dup_count_real_roots(f, sup=0) == 1 assert R.dup_count_real_roots(f, inf=-1, sup=1) == 0 # parameters for test_dup_count_complex_roots_n(): n = 1..8 a, b = (-QQ(1), -QQ(1)), (QQ(1), QQ(1)) c, d = ( QQ(0), QQ(0)), (QQ(1), QQ(1)) def test_dup_count_complex_roots_1(): R, x = ring("x", ZZ) # z-1 f = x - 1 assert R.dup_count_complex_roots(f, a, b) == 1 assert R.dup_count_complex_roots(f, c, d) == 1 # z+1 f = x + 1 assert R.dup_count_complex_roots(f, a, b) == 1 assert R.dup_count_complex_roots(f, c, d) == 0 def test_dup_count_complex_roots_2(): R, x = ring("x", ZZ) # (z-1)*(z) f = x**2 - x assert R.dup_count_complex_roots(f, a, b) == 2 assert R.dup_count_complex_roots(f, c, d) == 2 # (z-1)*(-z) f = -x**2 + x assert R.dup_count_complex_roots(f, a, b) == 2 assert R.dup_count_complex_roots(f, c, d) == 2 # (z+1)*(z) f = x**2 + x assert R.dup_count_complex_roots(f, a, b) == 2 assert R.dup_count_complex_roots(f, c, d) == 1 # (z+1)*(-z) f = -x**2 - x assert R.dup_count_complex_roots(f, a, b) == 2 assert R.dup_count_complex_roots(f, c, d) == 1 def test_dup_count_complex_roots_3(): R, x = ring("x", ZZ) # (z-1)*(z+1) f = x**2 - 1 assert R.dup_count_complex_roots(f, a, b) == 2 assert R.dup_count_complex_roots(f, c, d) == 1 # (z-1)*(z+1)*(z) f = x**3 - x assert R.dup_count_complex_roots(f, a, b) == 3 assert R.dup_count_complex_roots(f, c, d) == 2 # (z-1)*(z+1)*(-z) f = -x**3 + x assert R.dup_count_complex_roots(f, a, b) == 3 assert R.dup_count_complex_roots(f, c, d) == 2 def test_dup_count_complex_roots_4(): R, x = ring("x", ZZ) # (z-I)*(z+I) f = x**2 + 1 assert R.dup_count_complex_roots(f, a, b) == 2 assert R.dup_count_complex_roots(f, c, d) == 1 # (z-I)*(z+I)*(z) f = x**3 + x assert R.dup_count_complex_roots(f, a, b) == 3 assert R.dup_count_complex_roots(f, c, d) == 2 # (z-I)*(z+I)*(-z) f = -x**3 - x assert R.dup_count_complex_roots(f, a, b) == 3 assert R.dup_count_complex_roots(f, c, d) == 2 # (z-I)*(z+I)*(z-1) f = x**3 - x**2 + x - 1 assert R.dup_count_complex_roots(f, a, b) == 3 assert R.dup_count_complex_roots(f, c, d) == 2 # (z-I)*(z+I)*(z-1)*(z) f = x**4 - x**3 + x**2 - x assert R.dup_count_complex_roots(f, a, b) == 4 assert R.dup_count_complex_roots(f, c, d) == 3 # (z-I)*(z+I)*(z-1)*(-z) f = -x**4 + x**3 - x**2 + x assert R.dup_count_complex_roots(f, a, b) == 4 assert R.dup_count_complex_roots(f, c, d) == 3 # (z-I)*(z+I)*(z-1)*(z+1) f = x**4 - 1 assert R.dup_count_complex_roots(f, a, b) == 4 assert R.dup_count_complex_roots(f, c, d) == 2 # (z-I)*(z+I)*(z-1)*(z+1)*(z) f = x**5 - x assert R.dup_count_complex_roots(f, a, b) == 5 assert R.dup_count_complex_roots(f, c, d) == 3 # (z-I)*(z+I)*(z-1)*(z+1)*(-z) f = -x**5 + x assert R.dup_count_complex_roots(f, a, b) == 5 assert R.dup_count_complex_roots(f, c, d) == 3 def test_dup_count_complex_roots_5(): R, x = ring("x", ZZ) # (z-I+1)*(z+I+1) f = x**2 + 2*x + 2 assert R.dup_count_complex_roots(f, a, b) == 2 assert R.dup_count_complex_roots(f, c, d) == 0 # (z-I+1)*(z+I+1)*(z-1) f = x**3 + x**2 - 2 assert R.dup_count_complex_roots(f, a, b) == 3 assert R.dup_count_complex_roots(f, c, d) == 1 # (z-I+1)*(z+I+1)*(z-1)*z f = x**4 + x**3 - 2*x assert R.dup_count_complex_roots(f, a, b) == 4 assert R.dup_count_complex_roots(f, c, d) == 2 # (z-I+1)*(z+I+1)*(z+1) f = x**3 + 3*x**2 + 4*x + 2 assert R.dup_count_complex_roots(f, a, b) == 3 assert R.dup_count_complex_roots(f, c, d) == 0 # (z-I+1)*(z+I+1)*(z+1)*z f = x**4 + 3*x**3 + 4*x**2 + 2*x assert R.dup_count_complex_roots(f, a, b) == 4 assert R.dup_count_complex_roots(f, c, d) == 1 # (z-I+1)*(z+I+1)*(z-1)*(z+1) f = x**4 + 2*x**3 + x**2 - 2*x - 2 assert R.dup_count_complex_roots(f, a, b) == 4 assert R.dup_count_complex_roots(f, c, d) == 1 # (z-I+1)*(z+I+1)*(z-1)*(z+1)*z f = x**5 + 2*x**4 + x**3 - 2*x**2 - 2*x assert R.dup_count_complex_roots(f, a, b) == 5 assert R.dup_count_complex_roots(f, c, d) == 2 def test_dup_count_complex_roots_6(): R, x = ring("x", ZZ) # (z-I-1)*(z+I-1) f = x**2 - 2*x + 2 assert R.dup_count_complex_roots(f, a, b) == 2 assert R.dup_count_complex_roots(f, c, d) == 1 # (z-I-1)*(z+I-1)*(z-1) f = x**3 - 3*x**2 + 4*x - 2 assert R.dup_count_complex_roots(f, a, b) == 3 assert R.dup_count_complex_roots(f, c, d) == 2 # (z-I-1)*(z+I-1)*(z-1)*z f = x**4 - 3*x**3 + 4*x**2 - 2*x assert R.dup_count_complex_roots(f, a, b) == 4 assert R.dup_count_complex_roots(f, c, d) == 3 # (z-I-1)*(z+I-1)*(z+1) f = x**3 - x**2 + 2 assert R.dup_count_complex_roots(f, a, b) == 3 assert R.dup_count_complex_roots(f, c, d) == 1 # (z-I-1)*(z+I-1)*(z+1)*z f = x**4 - x**3 + 2*x assert R.dup_count_complex_roots(f, a, b) == 4 assert R.dup_count_complex_roots(f, c, d) == 2 # (z-I-1)*(z+I-1)*(z-1)*(z+1) f = x**4 - 2*x**3 + x**2 + 2*x - 2 assert R.dup_count_complex_roots(f, a, b) == 4 assert R.dup_count_complex_roots(f, c, d) == 2 # (z-I-1)*(z+I-1)*(z-1)*(z+1)*z f = x**5 - 2*x**4 + x**3 + 2*x**2 - 2*x assert R.dup_count_complex_roots(f, a, b) == 5 assert R.dup_count_complex_roots(f, c, d) == 3 def test_dup_count_complex_roots_7(): R, x = ring("x", ZZ) # (z-I-1)*(z+I-1)*(z-I+1)*(z+I+1) f = x**4 + 4 assert R.dup_count_complex_roots(f, a, b) == 4 assert R.dup_count_complex_roots(f, c, d) == 1 # (z-I-1)*(z+I-1)*(z-I+1)*(z+I+1)*(z-2) f = x**5 - 2*x**4 + 4*x - 8 assert R.dup_count_complex_roots(f, a, b) == 4 assert R.dup_count_complex_roots(f, c, d) == 1 # (z-I-1)*(z+I-1)*(z-I+1)*(z+I+1)*(z**2-2) f = x**6 - 2*x**4 + 4*x**2 - 8 assert R.dup_count_complex_roots(f, a, b) == 4 assert R.dup_count_complex_roots(f, c, d) == 1 # (z-I-1)*(z+I-1)*(z-I+1)*(z+I+1)*(z-1) f = x**5 - x**4 + 4*x - 4 assert R.dup_count_complex_roots(f, a, b) == 5 assert R.dup_count_complex_roots(f, c, d) == 2 # (z-I-1)*(z+I-1)*(z-I+1)*(z+I+1)*(z-1)*z f = x**6 - x**5 + 4*x**2 - 4*x assert R.dup_count_complex_roots(f, a, b) == 6 assert R.dup_count_complex_roots(f, c, d) == 3 # (z-I-1)*(z+I-1)*(z-I+1)*(z+I+1)*(z+1) f = x**5 + x**4 + 4*x + 4 assert R.dup_count_complex_roots(f, a, b) == 5 assert R.dup_count_complex_roots(f, c, d) == 1 # (z-I-1)*(z+I-1)*(z-I+1)*(z+I+1)*(z+1)*z f = x**6 + x**5 + 4*x**2 + 4*x assert R.dup_count_complex_roots(f, a, b) == 6 assert R.dup_count_complex_roots(f, c, d) == 2 # (z-I-1)*(z+I-1)*(z-I+1)*(z+I+1)*(z-1)*(z+1) f = x**6 - x**4 + 4*x**2 - 4 assert R.dup_count_complex_roots(f, a, b) == 6 assert R.dup_count_complex_roots(f, c, d) == 2 # (z-I-1)*(z+I-1)*(z-I+1)*(z+I+1)*(z-1)*(z+1)*z f = x**7 - x**5 + 4*x**3 - 4*x assert R.dup_count_complex_roots(f, a, b) == 7 assert R.dup_count_complex_roots(f, c, d) == 3 # (z-I-1)*(z+I-1)*(z-I+1)*(z+I+1)*(z-1)*(z+1)*(z-I)*(z+I) f = x**8 + 3*x**4 - 4 assert R.dup_count_complex_roots(f, a, b) == 8 assert R.dup_count_complex_roots(f, c, d) == 3 def test_dup_count_complex_roots_8(): R, x = ring("x", ZZ) # (z-I-1)*(z+I-1)*(z-I+1)*(z+I+1)*(z-1)*(z+1)*(z-I)*(z+I)*z f = x**9 + 3*x**5 - 4*x assert R.dup_count_complex_roots(f, a, b) == 9 assert R.dup_count_complex_roots(f, c, d) == 4 # (z-I-1)*(z+I-1)*(z-I+1)*(z+I+1)*(z-1)*(z+1)*(z-I)*(z+I)*(z**2-2)*z f = x**11 - 2*x**9 + 3*x**7 - 6*x**5 - 4*x**3 + 8*x assert R.dup_count_complex_roots(f, a, b) == 9 assert R.dup_count_complex_roots(f, c, d) == 4 def test_dup_count_complex_roots_implicit(): R, x = ring("x", ZZ) # z*(z-1)*(z+1)*(z-I)*(z+I) f = x**5 - x assert R.dup_count_complex_roots(f) == 5 assert R.dup_count_complex_roots(f, sup=(0, 0)) == 3 assert R.dup_count_complex_roots(f, inf=(0, 0)) == 3 def test_dup_count_complex_roots_exclude(): R, x = ring("x", ZZ) # z*(z-1)*(z+1)*(z-I)*(z+I) f = x**5 - x a, b = (-QQ(1), QQ(0)), (QQ(1), QQ(1)) assert R.dup_count_complex_roots(f, a, b) == 4 assert R.dup_count_complex_roots(f, a, b, exclude=['S']) == 3 assert R.dup_count_complex_roots(f, a, b, exclude=['N']) == 3 assert R.dup_count_complex_roots(f, a, b, exclude=['S', 'N']) == 2 assert R.dup_count_complex_roots(f, a, b, exclude=['E']) == 4 assert R.dup_count_complex_roots(f, a, b, exclude=['W']) == 4 assert R.dup_count_complex_roots(f, a, b, exclude=['E', 'W']) == 4 assert R.dup_count_complex_roots(f, a, b, exclude=['N', 'S', 'E', 'W']) == 2 assert R.dup_count_complex_roots(f, a, b, exclude=['SW']) == 3 assert R.dup_count_complex_roots(f, a, b, exclude=['SE']) == 3 assert R.dup_count_complex_roots(f, a, b, exclude=['SW', 'SE']) == 2 assert R.dup_count_complex_roots(f, a, b, exclude=['SW', 'SE', 'S']) == 1 assert R.dup_count_complex_roots(f, a, b, exclude=['SW', 'SE', 'S', 'N']) == 0 a, b = (QQ(0), QQ(0)), (QQ(1), QQ(1)) assert R.dup_count_complex_roots(f, a, b, exclude=True) == 1 def test_dup_isolate_complex_roots_sqf(): R, x = ring("x", ZZ) f = x**2 - 2*x + 3 assert R.dup_isolate_complex_roots_sqf(f) == \ [((0, -6), (6, 0)), ((0, 0), (6, 6))] assert [ r.as_tuple() for r in R.dup_isolate_complex_roots_sqf(f, blackbox=True) ] == \ [((0, -6), (6, 0)), ((0, 0), (6, 6))] assert R.dup_isolate_complex_roots_sqf(f, eps=QQ(1, 10)) == \ [((QQ(15, 16), -QQ(3, 2)), (QQ(33, 32), -QQ(45, 32))), ((QQ(15, 16), QQ(45, 32)), (QQ(33, 32), QQ(3, 2)))] assert R.dup_isolate_complex_roots_sqf(f, eps=QQ(1, 100)) == \ [((QQ(255, 256), -QQ(363, 256)), (QQ(513, 512), -QQ(723, 512))), ((QQ(255, 256), QQ(723, 512)), (QQ(513, 512), QQ(363, 256)))] f = 7*x**4 - 19*x**3 + 20*x**2 + 17*x + 20 assert R.dup_isolate_complex_roots_sqf(f) == \ [((-QQ(40, 7), -QQ(40, 7)), (0, 0)), ((-QQ(40, 7), 0), (0, QQ(40, 7))), ((0, -QQ(40, 7)), (QQ(40, 7), 0)), ((0, 0), (QQ(40, 7), QQ(40, 7)))] def test_dup_isolate_all_roots_sqf(): R, x = ring("x", ZZ) f = 4*x**4 - x**3 + 2*x**2 + 5*x assert R.dup_isolate_all_roots_sqf(f) == \ ([(-1, 0), (0, 0)], [((0, -QQ(5, 2)), (QQ(5, 2), 0)), ((0, 0), (QQ(5, 2), QQ(5, 2)))]) assert R.dup_isolate_all_roots_sqf(f, eps=QQ(1, 10)) == \ ([(QQ(-7, 8), QQ(-6, 7)), (0, 0)], [((QQ(35, 64), -QQ(35, 32)), (QQ(5, 8), -QQ(65, 64))), ((QQ(35, 64), QQ(65, 64)), (QQ(5, 8), QQ(35, 32)))]) def test_dup_isolate_all_roots(): R, x = ring("x", ZZ) f = 4*x**4 - x**3 + 2*x**2 + 5*x assert R.dup_isolate_all_roots(f) == \ ([((-1, 0), 1), ((0, 0), 1)], [(((0, -QQ(5, 2)), (QQ(5, 2), 0)), 1), (((0, 0), (QQ(5, 2), QQ(5, 2))), 1)]) assert R.dup_isolate_all_roots(f, eps=QQ(1, 10)) == \ ([((QQ(-7, 8), QQ(-6, 7)), 1), ((0, 0), 1)], [(((QQ(35, 64), -QQ(35, 32)), (QQ(5, 8), -QQ(65, 64))), 1), (((QQ(35, 64), QQ(65, 64)), (QQ(5, 8), QQ(35, 32))), 1)]) f = x**5 + x**4 - 2*x**3 - 2*x**2 + x + 1 raises(NotImplementedError, lambda: R.dup_isolate_all_roots(f))
5ae6ab0397d2f3ec7680f0a9642583731e1cc938402aaea82cc6a3440ae30afc
"""Prime ideals in number fields. """ from sympy.core.expr import Expr from sympy.polys.polytools import Poly from sympy.polys.domains.finitefield import FF from sympy.polys.domains.rationalfield import QQ from sympy.polys.domains.integerring import ZZ from sympy.polys.matrices.domainmatrix import DomainMatrix from sympy.polys.polyerrors import CoercionFailed, GeneratorsNeeded from sympy.polys.polyutils import IntegerPowerable from sympy.utilities.decorator import public from .basis import round_two, nilradical_mod_p from .exceptions import StructureError from .modules import ModuleEndomorphism, find_min_poly from .utilities import coeff_search, supplement_a_subspace def _check_formal_conditions_for_maximal_order(submodule): r""" Several functions in this module accept an argument which is to be a :py:class:`~.Submodule` representing the maximal order in a number field, such as returned by the :py:func:`~sympy.polys.numberfields.basis.round_two` algorithm. We do not attempt to check that the given ``Submodule`` actually represents a maximal order, but we do check a basic set of formal conditions that the ``Submodule`` must satisfy, at a minimum. The purpose is to catch an obviously ill-formed argument. """ prefix = 'The submodule representing the maximal order should ' cond = None if not submodule.is_power_basis_submodule(): cond = 'be a direct submodule of a power basis.' elif not submodule.starts_with_unity(): cond = 'have 1 as its first generator.' elif not submodule.is_sq_maxrank_HNF(): cond = 'have square matrix, of maximal rank, in Hermite Normal Form.' if cond is not None: raise StructureError(prefix + cond) class PrimeIdeal(IntegerPowerable): r""" A prime ideal in a ring of algebraic integers. """ def __init__(self, ZK, p, alpha, f, e=None): """ Parameters ========== ZK : :py:class:`~.Submodule` The maximal order where this ideal lives. p : int The rational prime this ideal divides. alpha : :py:class:`~.PowerBasisElement` Such that the ideal is equal to ``p*ZK + alpha*ZK``. f : int The inertia degree. e : int, ``None``, optional The ramification index, if already known. If ``None``, we will compute it here. """ _check_formal_conditions_for_maximal_order(ZK) self.ZK = ZK self.p = p self.alpha = alpha self.f = f self._test_factor = None self.e = e if e is not None else self.valuation(p * ZK) def pretty(self, field_gen=None, just_gens=False): """ Print a representation of this prime ideal. Examples ======== >>> from sympy import cyclotomic_poly, QQ >>> from sympy.abc import x, zeta >>> T = cyclotomic_poly(7, x) >>> K = QQ.algebraic_field((T, zeta)) >>> P = K.primes_above(11) >>> print(P[0].pretty()) [ (11, x**3 + 5*x**2 + 4*x - 1) e=1, f=3 ] >>> print(P[0].pretty(field_gen=zeta)) [ (11, zeta**3 + 5*zeta**2 + 4*zeta - 1) e=1, f=3 ] >>> print(P[0].pretty(field_gen=zeta, just_gens=True)) (11, zeta**3 + 5*zeta**2 + 4*zeta - 1) Parameters ========== field_gen : :py:class:`~.Symbol`, ``None``, optional (default=None) The symbol to use for the generator of the field. This will appear in our representation of ``self.alpha``. If ``None``, we use the variable of the defining polynomial of ``self.ZK``. just_gens : bool, optional (default=False) If ``True``, just print the "(p, alpha)" part, showing "just the generators" of the prime ideal. Otherwise, print a string of the form "[ (p, alpha) e=..., f=... ]", giving the ramification index and inertia degree, along with the generators. """ field_gen = field_gen or self.ZK.parent.T.gen p, alpha, e, f = self.p, self.alpha, self.e, self.f alpha_rep = str(alpha.numerator(x=field_gen).as_expr()) if alpha.denom > 1: alpha_rep = f'({alpha_rep})/{alpha.denom}' gens = f'({p}, {alpha_rep})' if just_gens: return gens return f'[ {gens} e={e}, f={f} ]' def __repr__(self): return self.pretty() def as_submodule(self): r""" Represent this prime ideal as a :py:class:`~.Submodule`. Explanation =========== The :py:class:`~.PrimeIdeal` class serves to bundle information about a prime ideal, such as its inertia degree, ramification index, and two-generator representation, as well as to offer helpful methods like :py:meth:`~.PrimeIdeal.valuation` and :py:meth:`~.PrimeIdeal.test_factor`. However, in order to be added and multiplied by other ideals or rational numbers, it must first be converted into a :py:class:`~.Submodule`, which is a class that supports these operations. In many cases, the user need not perform this conversion deliberately, since it is automatically performed by the arithmetic operator methods :py:meth:`~.PrimeIdeal.__add__` and :py:meth:`~.PrimeIdeal.__mul__`. Raising a :py:class:`~.PrimeIdeal` to a non-negative integer power is also supported. Examples ======== >>> from sympy import Poly, cyclotomic_poly, prime_decomp >>> T = Poly(cyclotomic_poly(7)) >>> P0 = prime_decomp(7, T)[0] >>> print(P0**6 == 7*P0.ZK) True Note that, on both sides of the equation above, we had a :py:class:`~.Submodule`. In the next equation we recall that adding ideals yields their GCD. This time, we need a deliberate conversion to :py:class:`~.Submodule` on the right: >>> print(P0 + 7*P0.ZK == P0.as_submodule()) True Returns ======= :py:class:`~.Submodule` Will be equal to ``self.p * self.ZK + self.alpha * self.ZK``. See Also ======== __add__ __mul__ """ M = self.p * self.ZK + self.alpha * self.ZK # Pre-set expensive boolean properties whose value we already know: M._starts_with_unity = False M._is_sq_maxrank_HNF = True return M def __eq__(self, other): if isinstance(other, PrimeIdeal): return self.as_submodule() == other.as_submodule() return NotImplemented def __add__(self, other): """ Convert to a :py:class:`~.Submodule` and add to another :py:class:`~.Submodule`. See Also ======== as_submodule """ return self.as_submodule() + other __radd__ = __add__ def __mul__(self, other): """ Convert to a :py:class:`~.Submodule` and multiply by another :py:class:`~.Submodule` or a rational number. See Also ======== as_submodule """ return self.as_submodule() * other __rmul__ = __mul__ def _zeroth_power(self): return self.ZK def _first_power(self): return self def test_factor(self): r""" Compute a test factor for this prime ideal. Explanation =========== Write $\mathfrak{p}$ for this prime ideal, $p$ for the rational prime it divides. Then, for computing $\mathfrak{p}$-adic valuations it is useful to have a number $\beta \in \mathbb{Z}_K$ such that $p/\mathfrak{p} = p \mathbb{Z}_K + \beta \mathbb{Z}_K$. Essentially, this is the same as the number $\Psi$ (or the "reagent") from Kummer's 1847 paper (*Ueber die Zerlegung...*, Crelle vol. 35) in which ideal divisors were invented. """ if self._test_factor is None: self._test_factor = _compute_test_factor(self.p, [self.alpha], self.ZK) return self._test_factor def valuation(self, I): r""" Compute the $\mathfrak{p}$-adic valuation of integral ideal I at this prime ideal. Parameters ========== I : :py:class:`~.Submodule` See Also ======== prime_valuation """ return prime_valuation(I, self) def reduce_poly(self, f, gen=None): r""" Reduce a univariate :py:class:`~.Poly` *f*, or an :py:class:`~.Expr` expressing the same, modulo this :py:class:`~.PrimeIdeal`. Explanation =========== If our second generator $\alpha$ is zero, then we simply reduce the coefficients of *f* mod the rational prime $p$ lying under this ideal. Otherwise we first reduce *f* mod $\alpha$ (as a polynomial in the same variable as *f*), and then mod $p$. Examples ======== >>> from sympy import QQ, cyclotomic_poly, symbols >>> zeta = symbols('zeta') >>> Phi = cyclotomic_poly(7, zeta) >>> k = QQ.algebraic_field((Phi, zeta)) >>> P = k.primes_above(11) >>> frp = P[0] >>> B = k.integral_basis(fmt='sympy') >>> print([frp.reduce_poly(b, zeta) for b in B]) [1, zeta, zeta**2, -5*zeta**2 - 4*zeta + 1, -zeta**2 - zeta - 5, 4*zeta**2 - zeta - 1] Parameters ========== f : :py:class:`~.Poly`, :py:class:`~.Expr` The univariate polynomial to be reduced. gen : :py:class:`~.Symbol`, None, optional (default=None) Symbol to use as the variable in the polynomials. If *f* is a :py:class:`~.Poly` or a non-constant :py:class:`~.Expr`, this replaces its variable. If *f* is a constant :py:class:`~.Expr`, then *gen* must be supplied. Returns ======= :py:class:`~.Poly`, :py:class:`~.Expr` Type is same as that of given *f*. If returning a :py:class:`~.Poly`, its domain will be the finite field $\mathbb{F}_p$. Raises ====== GeneratorsNeeded If *f* is a constant :py:class:`~.Expr` and *gen* is ``None``. NotImplementedError If *f* is other than :py:class:`~.Poly` or :py:class:`~.Expr`, or is not univariate. """ if isinstance(f, Expr): try: g = Poly(f) except GeneratorsNeeded as e: if gen is None: raise e from None g = Poly(f, gen) return self.reduce_poly(g).as_expr() if isinstance(f, Poly) and f.is_univariate: a = self.alpha.poly(f.gen) if a != 0: f = f.rem(a) return f.set_modulus(self.p) raise NotImplementedError def _compute_test_factor(p, gens, ZK): r""" Compute the test factor for a :py:class:`~.PrimeIdeal` $\mathfrak{p}$. Parameters ========== p : int The rational prime $\mathfrak{p}$ divides gens : list of :py:class:`PowerBasisElement` A complete set of generators for $\mathfrak{p}$ over *ZK*, EXCEPT that an element equivalent to rational *p* can and should be omitted (since it has no effect except to waste time). ZK : :py:class:`~.Submodule` The maximal order where the prime ideal $\mathfrak{p}$ lives. Returns ======= :py:class:`~.PowerBasisElement` References ========== .. [1] Cohen, H. *A Course in Computational Algebraic Number Theory.* (See Proposition 4.8.15.) """ _check_formal_conditions_for_maximal_order(ZK) E = ZK.endomorphism_ring() matrices = [E.inner_endomorphism(g).matrix(modulus=p) for g in gens] B = DomainMatrix.zeros((0, ZK.n), FF(p)).vstack(*matrices) # A nonzero element of the nullspace of B will represent a # lin comb over the omegas which (i) is not a multiple of p # (since it is nonzero over FF(p)), while (ii) is such that # its product with each g in gens _is_ a multiple of p (since # B represents multiplication by these generators). Theory # predicts that such an element must exist, so nullspace should # be non-trivial. x = B.nullspace()[0, :].transpose() beta = ZK.parent(ZK.matrix * x, denom=ZK.denom) return beta @public def prime_valuation(I, P): r""" Compute the *P*-adic valuation for an integral ideal *I*. Examples ======== >>> from sympy import QQ >>> from sympy.polys.numberfields import prime_valuation >>> K = QQ.cyclotomic_field(5) >>> P = K.primes_above(5) >>> ZK = K.maximal_order() >>> print(prime_valuation(25*ZK, P[0])) 8 Parameters ========== I : :py:class:`~.Submodule` An integral ideal whose valuation is desired. P : :py:class:`~.PrimeIdeal` The prime at which to compute the valuation. Returns ======= int See Also ======== .PrimeIdeal.valuation References ========== .. [1] Cohen, H. *A Course in Computational Algebraic Number Theory.* (See Algorithm 4.8.17.) """ p, ZK = P.p, P.ZK n, W, d = ZK.n, ZK.matrix, ZK.denom A = W.convert_to(QQ).inv() * I.matrix * d / I.denom # Although A must have integer entries, given that I is an integral ideal, # as a DomainMatrix it will still be over QQ, so we convert back: A = A.convert_to(ZZ) D = A.det() if D % p != 0: return 0 beta = P.test_factor() f = d ** n // W.det() need_complete_test = (f % p == 0) v = 0 while True: # Entering the loop, the cols of A represent lin combs of omegas. # Turn them into lin combs of thetas: A = W * A # And then one column at a time... for j in range(n): c = ZK.parent(A[:, j], denom=d) c *= beta # ...turn back into lin combs of omegas, after multiplying by beta: c = ZK.represent(c).flat() for i in range(n): A[i, j] = c[i] if A[n - 1, n - 1].element % p != 0: break A = A / p # As noted above, domain converts to QQ even when division goes evenly. # So must convert back, even when we don't "need_complete_test". if need_complete_test: # In this case, having a non-integer entry is actually just our # halting condition. try: A = A.convert_to(ZZ) except CoercionFailed: break else: # In this case theory says we should not have any non-integer entries. A = A.convert_to(ZZ) v += 1 return v def _two_elt_rep(gens, ZK, p, f=None, Np=None): r""" Given a set of *ZK*-generators of a prime ideal, compute a set of just two *ZK*-generators for the same ideal, one of which is *p* itself. Parameters ========== gens : list of :py:class:`PowerBasisElement` Generators for the prime ideal over *ZK*, the ring of integers of the field $K$. ZK : :py:class:`~.Submodule` The maximal order in $K$. p : int The rational prime divided by the prime ideal. f : int, optional The inertia degree of the prime ideal, if known. Np : int, optional The norm $p^f$ of the prime ideal, if known. NOTE: There is no reason to supply both *f* and *Np*. Either one will save us from having to compute the norm *Np* ourselves. If both are known, *Np* is preferred since it saves one exponentiation. Returns ======= :py:class:`~.PowerBasisElement` representing a single algebraic integer alpha such that the prime ideal is equal to ``p*ZK + alpha*ZK``. References ========== .. [1] Cohen, H. *A Course in Computational Algebraic Number Theory.* (See Algorithm 4.7.10.) """ _check_formal_conditions_for_maximal_order(ZK) pb = ZK.parent T = pb.T # Detect the special cases in which either (a) all generators are multiples # of p, or (b) there are no generators (so `all` is vacuously true): if all((g % p).equiv(0) for g in gens): return pb.zero() if Np is None: if f is not None: Np = p**f else: Np = abs(pb.submodule_from_gens(gens).matrix.det()) omega = ZK.basis_element_pullbacks() beta = [p*om for om in omega[1:]] # note: we omit omega[0] == 1 beta += gens search = coeff_search(len(beta), 1) for c in search: alpha = sum(ci*betai for ci, betai in zip(c, beta)) # Note: It may be tempting to reduce alpha mod p here, to try to work # with smaller numbers, but must not do that, as it can result in an # infinite loop! E.g. try factoring 2 in Q(sqrt(-7)). n = alpha.norm(T) // Np if n % p != 0: # Now can reduce alpha mod p. return alpha % p def _prime_decomp_easy_case(p, ZK): r""" Compute the decomposition of rational prime *p* in the ring of integers *ZK* (given as a :py:class:`~.Submodule`), in the "easy case", i.e. the case where *p* does not divide the index of $\theta$ in *ZK*, where $\theta$ is the generator of the ``PowerBasis`` of which *ZK* is a ``Submodule``. """ T = ZK.parent.T T_bar = Poly(T, modulus=p) lc, fl = T_bar.factor_list() return [PrimeIdeal(ZK, p, ZK.parent.element_from_poly(Poly(t, domain=ZZ)), t.degree(), e) for t, e in fl] def _prime_decomp_compute_kernel(I, p, ZK): r""" Parameters ========== I : :py:class:`~.Module` An ideal of ``ZK/pZK``. p : int The rational prime being factored. ZK : :py:class:`~.Submodule` The maximal order. Returns ======= Pair ``(N, G)``, where: ``N`` is a :py:class:`~.Module` representing the kernel of the map ``a |--> a**p - a`` on ``(O/pO)/I``, guaranteed to be a module with unity. ``G`` is a :py:class:`~.Module` representing a basis for the separable algebra ``A = O/I`` (see Cohen). """ W = I.matrix n, r = W.shape # Want to take the Fp-basis given by the columns of I, adjoin (1, 0, ..., 0) # (which we know is not already in there since I is a basis for a prime ideal) # and then supplement this with additional columns to make an invertible n x n # matrix. This will then represent a full basis for ZK, whose first r columns # are pullbacks of the basis for I. if r == 0: B = W.eye(n, ZZ) else: B = W.hstack(W.eye(n, ZZ)[:, 0]) if B.shape[1] < n: B = supplement_a_subspace(B.convert_to(FF(p))).convert_to(ZZ) G = ZK.submodule_from_matrix(B) # Must compute G's multiplication table _before_ discarding the first r # columns. (See Step 9 in Alg 6.2.9 in Cohen, where the betas are actually # needed in order to represent each product of gammas. However, once we've # found the representations, then we can ignore the betas.) G.compute_mult_tab() G = G.discard_before(r) phi = ModuleEndomorphism(G, lambda x: x**p - x) N = phi.kernel(modulus=p) assert N.starts_with_unity() return N, G def _prime_decomp_maximal_ideal(I, p, ZK): r""" We have reached the case where we have a maximal (hence prime) ideal *I*, which we know because the quotient ``O/I`` is a field. Parameters ========== I : :py:class:`~.Module` An ideal of ``O/pO``. p : int The rational prime being factored. ZK : :py:class:`~.Submodule` The maximal order. Returns ======= :py:class:`~.PrimeIdeal` instance representing this prime """ m, n = I.matrix.shape f = m - n G = ZK.matrix * I.matrix gens = [ZK.parent(G[:, j], denom=ZK.denom) for j in range(G.shape[1])] alpha = _two_elt_rep(gens, ZK, p, f=f) return PrimeIdeal(ZK, p, alpha, f) def _prime_decomp_split_ideal(I, p, N, G, ZK): r""" Perform the step in the prime decomposition algorithm where we have determined the the quotient ``ZK/I`` is _not_ a field, and we want to perform a non-trivial factorization of *I* by locating an idempotent element of ``ZK/I``. """ assert I.parent == ZK and G.parent is ZK and N.parent is G # Since ZK/I is not a field, the kernel computed in the previous step contains # more than just the prime field Fp, and our basis N for the nullspace therefore # contains at least a second column (which represents an element outside Fp). # Let alpha be such an element: alpha = N(1).to_parent() assert alpha.module is G alpha_powers = [] m = find_min_poly(alpha, FF(p), powers=alpha_powers) # TODO (future work): # We don't actually need full factorization, so might use a faster method # to just break off a single non-constant factor m1? lc, fl = m.factor_list() m1 = fl[0][0] m2 = m.quo(m1) U, V, g = m1.gcdex(m2) # Sanity check: theory says m is squarefree, so m1, m2 should be coprime: assert g == 1 E = list(reversed(Poly(U * m1, domain=ZZ).rep.rep)) eps1 = sum(E[i]*alpha_powers[i] for i in range(len(E))) eps2 = 1 - eps1 idemps = [eps1, eps2] factors = [] for eps in idemps: e = eps.to_parent() assert e.module is ZK D = I.matrix.convert_to(FF(p)).hstack(*[ (e * om).column(domain=FF(p)) for om in ZK.basis_elements() ]) W = D.columnspace().convert_to(ZZ) H = ZK.submodule_from_matrix(W) factors.append(H) return factors @public def prime_decomp(p, T=None, ZK=None, dK=None, radical=None): r""" Compute the decomposition of rational prime *p* in a number field. Explanation =========== Ordinarily this should be accessed through the :py:meth:`~.AlgebraicField.primes_above` method of an :py:class:`~.AlgebraicField`. Examples ======== >>> from sympy import Poly, QQ >>> from sympy.abc import x, theta >>> T = Poly(x ** 3 + x ** 2 - 2 * x + 8) >>> K = QQ.algebraic_field((T, theta)) >>> print(K.primes_above(2)) [[ (2, x**2 + 1) e=1, f=1 ], [ (2, (x**2 + 3*x + 2)/2) e=1, f=1 ], [ (2, (3*x**2 + 3*x)/2) e=1, f=1 ]] Parameters ========== p : int The rational prime whose decomposition is desired. T : :py:class:`~.Poly`, optional Monic irreducible polynomial defining the number field $K$ in which to factor. NOTE: at least one of *T* or *ZK* must be provided. ZK : :py:class:`~.Submodule`, optional The maximal order for $K$, if already known. NOTE: at least one of *T* or *ZK* must be provided. dK : int, optional The discriminant of the field $K$, if already known. radical : :py:class:`~.Submodule`, optional The nilradical mod *p* in the integers of $K$, if already known. Returns ======= List of :py:class:`~.PrimeIdeal` instances. References ========== .. [1] Cohen, H. *A Course in Computational Algebraic Number Theory.* (See Algorithm 6.2.9.) """ if T is None and ZK is None: raise ValueError('At least one of T or ZK must be provided.') if ZK is not None: _check_formal_conditions_for_maximal_order(ZK) if T is None: T = ZK.parent.T radicals = {} if dK is None or ZK is None: ZK, dK = round_two(T, radicals=radicals) dT = T.discriminant() f_squared = dT // dK if f_squared % p != 0: return _prime_decomp_easy_case(p, ZK) radical = radical or radicals.get(p) or nilradical_mod_p(ZK, p) stack = [radical] primes = [] while stack: I = stack.pop() N, G = _prime_decomp_compute_kernel(I, p, ZK) if N.n == 1: P = _prime_decomp_maximal_ideal(I, p, ZK) primes.append(P) else: I1, I2 = _prime_decomp_split_ideal(I, p, N, G, ZK) stack.extend([I1, I2]) return primes
66a381c3435541bbea7b3e59233d9bc1674c4c83f662b6b3254f55426de3fe2b
"""Computing integral bases for number fields. """ from sympy.polys.polytools import Poly from sympy.polys.domains.integerring import ZZ from sympy.polys.domains.rationalfield import QQ from sympy.polys.polyerrors import CoercionFailed from sympy.utilities.decorator import public from .modules import ModuleEndomorphism, ModuleHomomorphism, PowerBasis from .utilities import extract_fundamental_discriminant def _apply_Dedekind_criterion(T, p): r""" Apply the "Dedekind criterion" to test whether the order needs to be enlarged relative to a given prime *p*. """ x = T.gen T_bar = Poly(T, modulus=p) lc, fl = T_bar.factor_list() assert lc == 1 g_bar = Poly(1, x, modulus=p) for ti_bar, _ in fl: g_bar *= ti_bar h_bar = T_bar // g_bar g = Poly(g_bar, domain=ZZ) h = Poly(h_bar, domain=ZZ) f = (g * h - T) // p f_bar = Poly(f, modulus=p) Z_bar = f_bar for b in [g_bar, h_bar]: Z_bar = Z_bar.gcd(b) U_bar = T_bar // Z_bar m = Z_bar.degree() return U_bar, m def nilradical_mod_p(H, p, q=None): r""" Compute the nilradical mod *p* for a given order *H*, and prime *p*. Explanation =========== This is the ideal $I$ in $H/pH$ consisting of all elements some positive power of which is zero in this quotient ring, i.e. is a multiple of *p*. Parameters ========== H : :py:class:`~.Submodule` The given order. p : int The rational prime. q : int, optional If known, the smallest power of *p* that is $>=$ the dimension of *H*. If not provided, we compute it here. Returns ======= :py:class:`~.Module` representing the nilradical mod *p* in *H*. References ========== .. [1] Cohen, H. *A Course in Computational Algebraic Number Theory*. (See Lemma 6.1.6.) """ n = H.n if q is None: q = p while q < n: q *= p phi = ModuleEndomorphism(H, lambda x: x**q) return phi.kernel(modulus=p) def _second_enlargement(H, p, q): r""" Perform the second enlargement in the Round Two algorithm. """ Ip = nilradical_mod_p(H, p, q=q) B = H.parent.submodule_from_matrix(H.matrix * Ip.matrix, denom=H.denom) C = B + p*H E = C.endomorphism_ring() phi = ModuleHomomorphism(H, E, lambda x: E.inner_endomorphism(x)) gamma = phi.kernel(modulus=p) G = H.parent.submodule_from_matrix(H.matrix * gamma.matrix, denom=H.denom * p) H1 = G + H return H1, Ip @public def round_two(T, radicals=None): r""" Zassenhaus's "Round 2" algorithm. Explanation =========== Carry out Zassenhaus's "Round 2" algorithm on a monic irreducible polynomial *T* over :ref:`ZZ`. This computes an integral basis and the discriminant for the field $K = \mathbb{Q}[x]/(T(x))$. Ordinarily this function need not be called directly, as one can instead access the :py:meth:`~.AlgebraicField.maximal_order`, :py:meth:`~.AlgebraicField.integral_basis`, and :py:meth:`~.AlgebraicField.discriminant` methods of an :py:class:`~.AlgebraicField`. Examples ======== Working through an AlgebraicField: >>> from sympy import Poly, QQ >>> from sympy.abc import x >>> T = Poly(x ** 3 + x ** 2 - 2 * x + 8) >>> K = QQ.alg_field_from_poly(T, "theta") >>> print(K.maximal_order()) Submodule[[2, 0, 0], [0, 2, 0], [0, 1, 1]]/2 >>> print(K.discriminant()) -503 >>> print(K.integral_basis(fmt='sympy')) [1, theta, theta/2 + theta**2/2] Calling directly: >>> from sympy import Poly >>> from sympy.abc import x >>> from sympy.polys.numberfields.basis import round_two >>> T = Poly(x ** 3 + x ** 2 - 2 * x + 8) >>> print(round_two(T)) (Submodule[[2, 0, 0], [0, 2, 0], [0, 1, 1]]/2, -503) The nilradicals mod $p$ that are sometimes computed during the Round Two algorithm may be useful in further calculations. Pass a dictionary under `radicals` to receive these: >>> T = Poly(x**3 + 3*x**2 + 5) >>> rad = {} >>> ZK, dK = round_two(T, radicals=rad) >>> print(rad) {3: Submodule[[-1, 1, 0], [-1, 0, 1]]} Parameters ========== T : :py:class:`~.Poly` The irreducible monic polynomial over :ref:`ZZ` defining the number field. radicals : dict, optional This is a way for any $p$-radicals (if computed) to be returned by reference. If desired, pass an empty dictionary. If the algorithm reaches the point where it computes the nilradical mod $p$ of the ring of integers $Z_K$, then an $\mathbb{F}_p$-basis for this ideal will be stored in this dictionary under the key ``p``. This can be useful for other algorithms, such as prime decomposition. Returns ======= Pair ``(ZK, dK)``, where: ``ZK`` is a :py:class:`~sympy.polys.numberfields.modules.Submodule` representing the maximal order. ``dK`` is the discriminant of the field $K = \mathbb{Q}[x]/(T(x))$. See Also ======== .AlgebraicField.maximal_order .AlgebraicField.integral_basis .AlgebraicField.discriminant References ========== .. [1] Cohen, H. *A Course in Computational Algebraic Number Theory.* """ if T.domain == QQ: try: T = Poly(T, domain=ZZ) except CoercionFailed: pass # Let the error be raised by the next clause. if ( not T.is_univariate or not T.is_irreducible or not T.is_monic or not T.domain == ZZ): raise ValueError('Round 2 requires a monic irreducible univariate polynomial over ZZ.') n = T.degree() D = T.discriminant() D_modulus = ZZ.from_sympy(abs(D)) # D must be 0 or 1 mod 4 (see Cohen Sec 4.4), which ensures we can write # it in the form D = D_0 * F**2, where D_0 is 1 or a fundamental discriminant. _, F = extract_fundamental_discriminant(D) Ztheta = PowerBasis(T) H = Ztheta.whole_submodule() nilrad = None while F: # Next prime: p, e = F.popitem() U_bar, m = _apply_Dedekind_criterion(T, p) if m == 0: continue # For a given prime p, the first enlargement of the order spanned by # the current basis can be done in a simple way: U = Ztheta.element_from_poly(Poly(U_bar, domain=ZZ)) # TODO: # Theory says only first m columns of the U//p*H term below are needed. # Could be slightly more efficient to use only those. Maybe `Submodule` # class should support a slice operator? H = H.add(U // p * H, hnf_modulus=D_modulus) if e <= m: continue # A second, and possibly more, enlargements for p will be needed. # These enlargements require a more involved procedure. q = p while q < n: q *= p H1, nilrad = _second_enlargement(H, p, q) while H1 != H: H = H1 H1, nilrad = _second_enlargement(H, p, q) # Note: We do not store all nilradicals mod p, only the very last. This is # because, unless computed against the entire integral basis, it might not # be accurate. (In other words, if H was not already equal to ZK when we # passed it to `_second_enlargement`, then we can't trust the nilradical # so computed.) Example: if T(x) = x ** 3 + 15 * x ** 2 - 9 * x + 13, then # F is divisible by 2, 3, and 7, and the nilradical mod 2 as computed above # will not be accurate for the full, maximal order ZK. if nilrad is not None and isinstance(radicals, dict): radicals[p] = nilrad ZK = H # Pre-set expensive boolean properties which we already know to be true: ZK._starts_with_unity = True ZK._is_sq_maxrank_HNF = True dK = (D * ZK.matrix.det() ** 2) // ZK.denom ** (2 * n) return ZK, dK
f1faf7fda5eaf8b39f920c5393755aa959c48e765a0a7abf867090e76170eb3e
"""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 xv = {x:v if not v.is_number else v.n(prec1)} fe = [f.as_expr().xreplace(xv) for f in factors] # 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)
0055d01f3c0c3ce9de933befd55ee6f05debaa946b6d524ff9dcbba233f9b079
r""" Functions in ``polys.numberfields.subfield`` solve the "Subfield Problem" and allied problems, for algebraic number fields. Following Cohen (see [Cohen93]_ Section 4.5), we can define the main problem as follows: * **Subfield Problem:** Given two number fields $\mathbb{Q}(\alpha)$, $\mathbb{Q}(\beta)$ via the minimal polynomials for their generators $\alpha$ and $\beta$, decide whether one field is isomorphic to a subfield of the other. From a solution to this problem flow solutions to the following problems as well: * **Primitive Element Problem:** Given several algebraic numbers $\alpha_1, \ldots, \alpha_m$, compute a single algebraic number $\theta$ such that $\mathbb{Q}(\alpha_1, \ldots, \alpha_m) = \mathbb{Q}(\theta)$. * **Field Isomorphism Problem:** Decide whether two number fields $\mathbb{Q}(\alpha)$, $\mathbb{Q}(\beta)$ are isomorphic. * **Field Membership Problem:** Given two algebraic numbers $\alpha$, $\beta$, decide whether $\alpha \in \mathbb{Q}(\beta)$, and if so write $\alpha = f(\beta)$ for some $f(x) \in \mathbb{Q}[x]$. """ from sympy.core.add import Add from sympy.core.numbers import AlgebraicNumber from sympy.core.singleton import S from sympy.core.symbol import Dummy from sympy.core.sympify import sympify, _sympify from sympy.ntheory import sieve from sympy.polys.densetools import dup_eval from sympy.polys.domains import QQ from sympy.polys.numberfields.minpoly import _choose_factor, minimal_polynomial from sympy.polys.polyerrors import IsomorphismFailed from sympy.polys.polytools import Poly, PurePoly, factor_list from sympy.utilities import public from mpmath import MPContext def is_isomorphism_possible(a, b): """Necessary but not sufficient test for isomorphism. """ n = a.minpoly.degree() m = b.minpoly.degree() if m % n != 0: return False if n == m: return True da = a.minpoly.discriminant() db = b.minpoly.discriminant() i, k, half = 1, m//n, db//2 while True: p = sieve[i] P = p**k if P > half: break if ((da % p) % 2) and not (db % P): return False i += 1 return True def field_isomorphism_pslq(a, b): """Construct field isomorphism using PSLQ algorithm. """ if not a.root.is_real or not b.root.is_real: raise NotImplementedError("PSLQ doesn't support complex coefficients") f = a.minpoly g = b.minpoly.replace(f.gen) n, m, prev = 100, b.minpoly.degree(), None ctx = MPContext() for i in range(1, 5): A = a.root.evalf(n) B = b.root.evalf(n) basis = [1, B] + [ B**i for i in range(2, m) ] + [-A] ctx.dps = n coeffs = ctx.pslq(basis, maxcoeff=10**10, maxsteps=1000) if coeffs is None: # PSLQ can't find an integer linear combination. Give up. break if coeffs != prev: prev = coeffs else: # Increasing precision didn't produce anything new. Give up. break # We have # c0 + c1*B + c2*B^2 + ... + cm-1*B^(m-1) - cm*A ~ 0. # So bring cm*A to the other side, and divide through by cm, # for an approximate representation of A as a polynomial in B. # (We know cm != 0 since `b.minpoly` is irreducible.) coeffs = [S(c)/coeffs[-1] for c in coeffs[:-1]] # Throw away leading zeros. while not coeffs[-1]: coeffs.pop() coeffs = list(reversed(coeffs)) h = Poly(coeffs, f.gen, domain='QQ') # We only have A ~ h(B). We must check whether the relation is exact. if f.compose(h).rem(g).is_zero: # Now we know that h(b) is in fact equal to _some conjugate of_ a. # But from the very precise approximation A ~ h(B) we can assume # the conjugate is a itself. return coeffs else: n *= 2 return None def field_isomorphism_factor(a, b): """Construct field isomorphism via factorization. """ _, factors = factor_list(a.minpoly, extension=b) for f, _ in factors: if f.degree() == 1: # Any linear factor f(x) represents some conjugate of a in QQ(b). # We want to know whether this linear factor represents a itself. # Let f = x - c c = -f.rep.TC() # Write c as polynomial in b coeffs = c.to_sympy_list() d, terms = len(coeffs) - 1, [] for i, coeff in enumerate(coeffs): terms.append(coeff*b.root**(d - i)) r = Add(*terms) # Check whether we got the number a if a.minpoly.same_root(r, a): return coeffs # If none of the linear factors represented a in QQ(b), then in fact a is # not an element of QQ(b). return None @public def field_isomorphism(a, b, *, fast=True): r""" Find an embedding of one number field into another. Explanation =========== This function looks for an isomorphism from $\mathbb{Q}(a)$ onto some subfield of $\mathbb{Q}(b)$. Thus, it solves the Subfield Problem. Examples ======== >>> from sympy import sqrt, field_isomorphism, I >>> print(field_isomorphism(3, sqrt(2))) # doctest: +SKIP [3] >>> print(field_isomorphism( I*sqrt(3), I*sqrt(3)/2)) # doctest: +SKIP [2, 0] Parameters ========== a : :py:class:`~.Expr` Any expression representing an algebraic number. b : :py:class:`~.Expr` Any expression representing an algebraic number. fast : boolean, optional (default=True) If ``True``, we first attempt a potentially faster way of computing the isomorphism, falling back on a slower method if this fails. If ``False``, we go directly to the slower method, which is guaranteed to return a result. Returns ======= List of rational numbers, or None If $\mathbb{Q}(a)$ is not isomorphic to some subfield of $\mathbb{Q}(b)$, then return ``None``. Otherwise, return a list of rational numbers representing an element of $\mathbb{Q}(b)$ to which $a$ may be mapped, in order to define a monomorphism, i.e. an isomorphism from $\mathbb{Q}(a)$ to some subfield of $\mathbb{Q}(b)$. The elements of the list are the coefficients of falling powers of $b$. """ a, b = sympify(a), sympify(b) if not a.is_AlgebraicNumber: a = AlgebraicNumber(a) if not b.is_AlgebraicNumber: b = AlgebraicNumber(b) a = a.to_primitive_element() b = b.to_primitive_element() if a == b: return a.coeffs() n = a.minpoly.degree() m = b.minpoly.degree() if n == 1: return [a.root] if m % n != 0: return None if fast: try: result = field_isomorphism_pslq(a, b) if result is not None: return result except NotImplementedError: pass return field_isomorphism_factor(a, b) def _switch_domain(g, K): # An algebraic relation f(a, b) = 0 over Q can also be written # g(b) = 0 where g is in Q(a)[x] and h(a) = 0 where h is in Q(b)[x]. # This function transforms g into h where Q(b) = K. frep = g.rep.inject() hrep = frep.eject(K, front=True) return g.new(hrep, g.gens[0]) def _linsolve(p): # Compute root of linear polynomial. c, d = p.rep.rep return -d/c @public def primitive_element(extension, x=None, *, ex=False, polys=False): r""" Find a single generator for a number field given by several generators. Explanation =========== The basic problem is this: Given several algebraic numbers $\alpha_1, \alpha_2, \ldots, \alpha_n$, find a single algebraic number $\theta$ such that $\mathbb{Q}(\alpha_1, \alpha_2, \ldots, \alpha_n) = \mathbb{Q}(\theta)$. This function actually guarantees that $\theta$ will be a linear combination of the $\alpha_i$, with non-negative integer coefficients. Furthermore, if desired, this function will tell you how to express each $\alpha_i$ as a $\mathbb{Q}$-linear combination of the powers of $\theta$. Examples ======== >>> from sympy import primitive_element, sqrt, S, minpoly, simplify >>> from sympy.abc import x >>> f, lincomb, reps = primitive_element([sqrt(2), sqrt(3)], x, ex=True) Then ``lincomb`` tells us the primitive element as a linear combination of the given generators ``sqrt(2)`` and ``sqrt(3)``. >>> print(lincomb) [1, 1] This means the primtiive element is $\sqrt{2} + \sqrt{3}$. Meanwhile ``f`` is the minimal polynomial for this primitive element. >>> print(f) x**4 - 10*x**2 + 1 >>> print(minpoly(sqrt(2) + sqrt(3), x)) x**4 - 10*x**2 + 1 Finally, ``reps`` (which was returned only because we set keyword arg ``ex=True``) tells us how to recover each of the generators $\sqrt{2}$ and $\sqrt{3}$ as $\mathbb{Q}$-linear combinations of the powers of the primitive element $\sqrt{2} + \sqrt{3}$. >>> print([S(r) for r in reps[0]]) [1/2, 0, -9/2, 0] >>> theta = sqrt(2) + sqrt(3) >>> print(simplify(theta**3/2 - 9*theta/2)) sqrt(2) >>> print([S(r) for r in reps[1]]) [-1/2, 0, 11/2, 0] >>> print(simplify(-theta**3/2 + 11*theta/2)) sqrt(3) Parameters ========== extension : list of :py:class:`~.Expr` Each expression must represent an algebraic number $\alpha_i$. x : :py:class:`~.Symbol`, optional (default=None) The desired symbol to appear in the computed minimal polynomial for the primitive element $\theta$. If ``None``, we use a dummy symbol. ex : boolean, optional (default=False) If and only if ``True``, compute the representation of each $\alpha_i$ as a $\mathbb{Q}$-linear combination over the powers of $\theta$. polys : boolean, optional (default=False) If ``True``, return the minimal polynomial as a :py:class:`~.Poly`. Otherwise return it as an :py:class:`~.Expr`. Returns ======= Pair (f, coeffs) or triple (f, coeffs, reps), where: ``f`` is the minimal polynomial for the primitive element. ``coeffs`` gives the primitive element as a linear combination of the given generators. ``reps`` is present if and only if argument ``ex=True`` was passed, and is a list of lists of rational numbers. Each list gives the coefficients of falling powers of the primitive element, to recover one of the original, given generators. """ if not extension: raise ValueError("Cannot compute primitive element for empty extension") extension = [_sympify(ext) for ext in extension] if x is not None: x, cls = sympify(x), Poly else: x, cls = Dummy('x'), PurePoly if not ex: gen, coeffs = extension[0], [1] g = minimal_polynomial(gen, x, polys=True) for ext in extension[1:]: if ext.is_Rational: coeffs.append(0) continue _, factors = factor_list(g, extension=ext) g = _choose_factor(factors, x, gen) s, _, g = g.sqf_norm() gen += s*ext coeffs.append(s) if not polys: return g.as_expr(), coeffs else: return cls(g), coeffs gen, coeffs = extension[0], [1] f = minimal_polynomial(gen, x, polys=True) K = QQ.algebraic_field((f, gen)) # incrementally constructed field reps = [K.unit] # representations of extension elements in K for ext in extension[1:]: if ext.is_Rational: coeffs.append(0) # rational ext is not included in the expression of a primitive element reps.append(K.convert(ext)) # but it is included in reps continue p = minimal_polynomial(ext, x, polys=True) L = QQ.algebraic_field((p, ext)) _, factors = factor_list(f, domain=L) f = _choose_factor(factors, x, gen) s, g, f = f.sqf_norm() gen += s*ext coeffs.append(s) K = QQ.algebraic_field((f, gen)) h = _switch_domain(g, K) erep = _linsolve(h.gcd(p)) # ext as element of K ogen = K.unit - s*erep # old gen as element of K reps = [dup_eval(_.rep, ogen, K) for _ in reps] + [erep] if K.ext.root.is_Rational: # all extensions are rational H = [K.convert(_).rep for _ in extension] coeffs = [0]*len(extension) f = cls(x, domain=QQ) else: H = [_.rep for _ in reps] if not polys: return f.as_expr(), coeffs, H else: return f, coeffs, H @public def to_number_field(extension, theta=None, *, gen=None): r""" Express one algebraic number in the field generated by another. Explanation =========== Given two algebraic numbers $\eta, \theta$, this function either expresses $\eta$ as an element of $\mathbb{Q}(\theta)$, or else raises an exception if $\eta \not\in \mathbb{Q}(\theta)$. This function is essentially just a convenience, utilizing :py:func:`~.field_isomorphism` (our solution of the Subfield Problem) to solve this, the Field Membership Problem. As an additional convenience, this function allows you to pass a list of algebraic numbers $\alpha_1, \alpha_2, \ldots, \alpha_n$ instead of $\eta$. It then computes $\eta$ for you, as a solution of the Primitive Element Problem, using :py:func:`~.primitive_element` on the list of $\alpha_i$. Examples ======== >>> from sympy import sqrt, to_number_field >>> eta = sqrt(2) >>> theta = sqrt(2) + sqrt(3) >>> a = to_number_field(eta, theta) >>> print(type(a)) <class 'sympy.core.numbers.AlgebraicNumber'> >>> a.root sqrt(2) + sqrt(3) >>> print(a) sqrt(2) >>> a.coeffs() [1/2, 0, -9/2, 0] We get an :py:class:`~.AlgebraicNumber`, whose ``.root`` is $\theta$, whose value is $\eta$, and whose ``.coeffs()`` show how to write $\eta$ as a $\mathbb{Q}$-linear combination in falling powers of $\theta$. Parameters ========== extension : :py:class:`~.Expr` or list of :py:class:`~.Expr` Either the algebraic number that is to be expressed in the other field, or else a list of algebraic numbers, a primitive element for which is to be expressed in the other field. theta : :py:class:`~.Expr`, None, optional (default=None) If an :py:class:`~.Expr` representing an algebraic number, behavior is as described under **Explanation**. If ``None``, then this function reduces to a shorthand for calling :py:func:`~.primitive_element` on ``extension`` and turning the computed primitive element into an :py:class:`~.AlgebraicNumber`. gen : :py:class:`~.Symbol`, None, optional (default=None) If provided, this will be used as the generator symbol for the returned :py:class:`~.AlgebraicNumber`. Returns ======= AlgebraicNumber Belonging to $\mathbb{Q}(\theta)$ and equaling $\eta$. Raises ====== IsomorphismFailed If $\eta \not\in \mathbb{Q}(\theta)$. See Also ======== field_isomorphism primitive_element """ if hasattr(extension, '__iter__'): extension = list(extension) else: extension = [extension] if len(extension) == 1 and isinstance(extension[0], tuple): return AlgebraicNumber(extension[0]) minpoly, coeffs = primitive_element(extension, gen, polys=True) root = sum([ coeff*ext for coeff, ext in zip(coeffs, extension) ]) if theta is None: return AlgebraicNumber((minpoly, root)) else: theta = sympify(theta) if not theta.is_AlgebraicNumber: theta = AlgebraicNumber(theta, gen=gen) coeffs = field_isomorphism(root, theta) if coeffs is not None: return AlgebraicNumber(theta, coeffs) else: raise IsomorphismFailed( "%s is not in a subfield of %s" % (root, theta.root))
a0a89780213df03b1663ae13e6753ad90fe25eaac852d84730cf6ad12d533da7
"""Tests for classes defining properties of ground domains, e.g. ZZ, QQ, ZZ[x] ... """ from sympy.core.numbers import (E, Float, I, Integer, Rational, oo, pi, _illegal) from sympy.core.singleton import S from sympy.functions.elementary.exponential import exp from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import sin from sympy.polys.polytools import Poly from sympy.abc import x, y, z from sympy.external.gmpy import HAS_GMPY from sympy.polys.domains import (ZZ, QQ, RR, CC, FF, GF, EX, EXRAW, ZZ_gmpy, ZZ_python, QQ_gmpy, QQ_python) from sympy.polys.domains.algebraicfield import AlgebraicField from sympy.polys.domains.gaussiandomains import ZZ_I, QQ_I from sympy.polys.domains.polynomialring import PolynomialRing from sympy.polys.domains.realfield import RealField from sympy.polys.numberfields.subfield import field_isomorphism from sympy.polys.rings import ring from sympy.polys.specialpolys import cyclotomic_poly from sympy.polys.fields import field from sympy.polys.agca.extensions import FiniteExtension from sympy.polys.polyerrors import ( UnificationFailed, GeneratorsError, CoercionFailed, NotInvertible, DomainError) from sympy.testing.pytest import raises from itertools import product ALG = QQ.algebraic_field(sqrt(2), sqrt(3)) def unify(K0, K1): return K0.unify(K1) def test_Domain_unify(): F3 = GF(3) assert unify(F3, F3) == F3 assert unify(F3, ZZ) == ZZ assert unify(F3, QQ) == QQ assert unify(F3, ALG) == ALG assert unify(F3, RR) == RR assert unify(F3, CC) == CC assert unify(F3, ZZ[x]) == ZZ[x] assert unify(F3, ZZ.frac_field(x)) == ZZ.frac_field(x) assert unify(F3, EX) == EX assert unify(ZZ, F3) == ZZ assert unify(ZZ, ZZ) == ZZ assert unify(ZZ, QQ) == QQ assert unify(ZZ, ALG) == ALG assert unify(ZZ, RR) == RR assert unify(ZZ, CC) == CC assert unify(ZZ, ZZ[x]) == ZZ[x] assert unify(ZZ, ZZ.frac_field(x)) == ZZ.frac_field(x) assert unify(ZZ, EX) == EX assert unify(QQ, F3) == QQ assert unify(QQ, ZZ) == QQ assert unify(QQ, QQ) == QQ assert unify(QQ, ALG) == ALG assert unify(QQ, RR) == RR assert unify(QQ, CC) == CC assert unify(QQ, ZZ[x]) == QQ[x] assert unify(QQ, ZZ.frac_field(x)) == QQ.frac_field(x) assert unify(QQ, EX) == EX assert unify(ZZ_I, F3) == ZZ_I assert unify(ZZ_I, ZZ) == ZZ_I assert unify(ZZ_I, ZZ_I) == ZZ_I assert unify(ZZ_I, QQ) == QQ_I assert unify(ZZ_I, ALG) == QQ.algebraic_field(I, sqrt(2), sqrt(3)) assert unify(ZZ_I, RR) == CC assert unify(ZZ_I, CC) == CC assert unify(ZZ_I, ZZ[x]) == ZZ_I[x] assert unify(ZZ_I, ZZ_I[x]) == ZZ_I[x] assert unify(ZZ_I, ZZ.frac_field(x)) == ZZ_I.frac_field(x) assert unify(ZZ_I, ZZ_I.frac_field(x)) == ZZ_I.frac_field(x) assert unify(ZZ_I, EX) == EX assert unify(QQ_I, F3) == QQ_I assert unify(QQ_I, ZZ) == QQ_I assert unify(QQ_I, ZZ_I) == QQ_I assert unify(QQ_I, QQ) == QQ_I assert unify(QQ_I, ALG) == QQ.algebraic_field(I, sqrt(2), sqrt(3)) assert unify(QQ_I, RR) == CC assert unify(QQ_I, CC) == CC assert unify(QQ_I, ZZ[x]) == QQ_I[x] assert unify(QQ_I, ZZ_I[x]) == QQ_I[x] assert unify(QQ_I, QQ[x]) == QQ_I[x] assert unify(QQ_I, QQ_I[x]) == QQ_I[x] assert unify(QQ_I, ZZ.frac_field(x)) == QQ_I.frac_field(x) assert unify(QQ_I, ZZ_I.frac_field(x)) == QQ_I.frac_field(x) assert unify(QQ_I, QQ.frac_field(x)) == QQ_I.frac_field(x) assert unify(QQ_I, QQ_I.frac_field(x)) == QQ_I.frac_field(x) assert unify(QQ_I, EX) == EX assert unify(RR, F3) == RR assert unify(RR, ZZ) == RR assert unify(RR, QQ) == RR assert unify(RR, ALG) == RR assert unify(RR, RR) == RR assert unify(RR, CC) == CC assert unify(RR, ZZ[x]) == RR[x] assert unify(RR, ZZ.frac_field(x)) == RR.frac_field(x) assert unify(RR, EX) == EX assert RR[x].unify(ZZ.frac_field(y)) == RR.frac_field(x, y) assert unify(CC, F3) == CC assert unify(CC, ZZ) == CC assert unify(CC, QQ) == CC assert unify(CC, ALG) == CC assert unify(CC, RR) == CC assert unify(CC, CC) == CC assert unify(CC, ZZ[x]) == CC[x] assert unify(CC, ZZ.frac_field(x)) == CC.frac_field(x) assert unify(CC, EX) == EX assert unify(ZZ[x], F3) == ZZ[x] assert unify(ZZ[x], ZZ) == ZZ[x] assert unify(ZZ[x], QQ) == QQ[x] assert unify(ZZ[x], ALG) == ALG[x] assert unify(ZZ[x], RR) == RR[x] assert unify(ZZ[x], CC) == CC[x] assert unify(ZZ[x], ZZ[x]) == ZZ[x] assert unify(ZZ[x], ZZ.frac_field(x)) == ZZ.frac_field(x) assert unify(ZZ[x], EX) == EX assert unify(ZZ.frac_field(x), F3) == ZZ.frac_field(x) assert unify(ZZ.frac_field(x), ZZ) == ZZ.frac_field(x) assert unify(ZZ.frac_field(x), QQ) == QQ.frac_field(x) assert unify(ZZ.frac_field(x), ALG) == ALG.frac_field(x) assert unify(ZZ.frac_field(x), RR) == RR.frac_field(x) assert unify(ZZ.frac_field(x), CC) == CC.frac_field(x) assert unify(ZZ.frac_field(x), ZZ[x]) == ZZ.frac_field(x) assert unify(ZZ.frac_field(x), ZZ.frac_field(x)) == ZZ.frac_field(x) assert unify(ZZ.frac_field(x), EX) == EX assert unify(EX, F3) == EX assert unify(EX, ZZ) == EX assert unify(EX, QQ) == EX assert unify(EX, ALG) == EX assert unify(EX, RR) == EX assert unify(EX, CC) == EX assert unify(EX, ZZ[x]) == EX assert unify(EX, ZZ.frac_field(x)) == EX assert unify(EX, EX) == EX def test_Domain_unify_composite(): assert unify(ZZ.poly_ring(x), ZZ) == ZZ.poly_ring(x) assert unify(ZZ.poly_ring(x), QQ) == QQ.poly_ring(x) assert unify(QQ.poly_ring(x), ZZ) == QQ.poly_ring(x) assert unify(QQ.poly_ring(x), QQ) == QQ.poly_ring(x) assert unify(ZZ, ZZ.poly_ring(x)) == ZZ.poly_ring(x) assert unify(QQ, ZZ.poly_ring(x)) == QQ.poly_ring(x) assert unify(ZZ, QQ.poly_ring(x)) == QQ.poly_ring(x) assert unify(QQ, QQ.poly_ring(x)) == QQ.poly_ring(x) assert unify(ZZ.poly_ring(x, y), ZZ) == ZZ.poly_ring(x, y) assert unify(ZZ.poly_ring(x, y), QQ) == QQ.poly_ring(x, y) assert unify(QQ.poly_ring(x, y), ZZ) == QQ.poly_ring(x, y) assert unify(QQ.poly_ring(x, y), QQ) == QQ.poly_ring(x, y) assert unify(ZZ, ZZ.poly_ring(x, y)) == ZZ.poly_ring(x, y) assert unify(QQ, ZZ.poly_ring(x, y)) == QQ.poly_ring(x, y) assert unify(ZZ, QQ.poly_ring(x, y)) == QQ.poly_ring(x, y) assert unify(QQ, QQ.poly_ring(x, y)) == QQ.poly_ring(x, y) assert unify(ZZ.frac_field(x), ZZ) == ZZ.frac_field(x) assert unify(ZZ.frac_field(x), QQ) == QQ.frac_field(x) assert unify(QQ.frac_field(x), ZZ) == QQ.frac_field(x) assert unify(QQ.frac_field(x), QQ) == QQ.frac_field(x) assert unify(ZZ, ZZ.frac_field(x)) == ZZ.frac_field(x) assert unify(QQ, ZZ.frac_field(x)) == QQ.frac_field(x) assert unify(ZZ, QQ.frac_field(x)) == QQ.frac_field(x) assert unify(QQ, QQ.frac_field(x)) == QQ.frac_field(x) assert unify(ZZ.frac_field(x, y), ZZ) == ZZ.frac_field(x, y) assert unify(ZZ.frac_field(x, y), QQ) == QQ.frac_field(x, y) assert unify(QQ.frac_field(x, y), ZZ) == QQ.frac_field(x, y) assert unify(QQ.frac_field(x, y), QQ) == QQ.frac_field(x, y) assert unify(ZZ, ZZ.frac_field(x, y)) == ZZ.frac_field(x, y) assert unify(QQ, ZZ.frac_field(x, y)) == QQ.frac_field(x, y) assert unify(ZZ, QQ.frac_field(x, y)) == QQ.frac_field(x, y) assert unify(QQ, QQ.frac_field(x, y)) == QQ.frac_field(x, y) assert unify(ZZ.poly_ring(x), ZZ.poly_ring(x)) == ZZ.poly_ring(x) assert unify(ZZ.poly_ring(x), QQ.poly_ring(x)) == QQ.poly_ring(x) assert unify(QQ.poly_ring(x), ZZ.poly_ring(x)) == QQ.poly_ring(x) assert unify(QQ.poly_ring(x), QQ.poly_ring(x)) == QQ.poly_ring(x) assert unify(ZZ.poly_ring(x, y), ZZ.poly_ring(x)) == ZZ.poly_ring(x, y) assert unify(ZZ.poly_ring(x, y), QQ.poly_ring(x)) == QQ.poly_ring(x, y) assert unify(QQ.poly_ring(x, y), ZZ.poly_ring(x)) == QQ.poly_ring(x, y) assert unify(QQ.poly_ring(x, y), QQ.poly_ring(x)) == QQ.poly_ring(x, y) assert unify(ZZ.poly_ring(x), ZZ.poly_ring(x, y)) == ZZ.poly_ring(x, y) assert unify(ZZ.poly_ring(x), QQ.poly_ring(x, y)) == QQ.poly_ring(x, y) assert unify(QQ.poly_ring(x), ZZ.poly_ring(x, y)) == QQ.poly_ring(x, y) assert unify(QQ.poly_ring(x), QQ.poly_ring(x, y)) == QQ.poly_ring(x, y) assert unify(ZZ.poly_ring(x, y), ZZ.poly_ring(x, z)) == ZZ.poly_ring(x, y, z) assert unify(ZZ.poly_ring(x, y), QQ.poly_ring(x, z)) == QQ.poly_ring(x, y, z) assert unify(QQ.poly_ring(x, y), ZZ.poly_ring(x, z)) == QQ.poly_ring(x, y, z) assert unify(QQ.poly_ring(x, y), QQ.poly_ring(x, z)) == QQ.poly_ring(x, y, z) assert unify(ZZ.frac_field(x), ZZ.frac_field(x)) == ZZ.frac_field(x) assert unify(ZZ.frac_field(x), QQ.frac_field(x)) == QQ.frac_field(x) assert unify(QQ.frac_field(x), ZZ.frac_field(x)) == QQ.frac_field(x) assert unify(QQ.frac_field(x), QQ.frac_field(x)) == QQ.frac_field(x) assert unify(ZZ.frac_field(x, y), ZZ.frac_field(x)) == ZZ.frac_field(x, y) assert unify(ZZ.frac_field(x, y), QQ.frac_field(x)) == QQ.frac_field(x, y) assert unify(QQ.frac_field(x, y), ZZ.frac_field(x)) == QQ.frac_field(x, y) assert unify(QQ.frac_field(x, y), QQ.frac_field(x)) == QQ.frac_field(x, y) assert unify(ZZ.frac_field(x), ZZ.frac_field(x, y)) == ZZ.frac_field(x, y) assert unify(ZZ.frac_field(x), QQ.frac_field(x, y)) == QQ.frac_field(x, y) assert unify(QQ.frac_field(x), ZZ.frac_field(x, y)) == QQ.frac_field(x, y) assert unify(QQ.frac_field(x), QQ.frac_field(x, y)) == QQ.frac_field(x, y) assert unify(ZZ.frac_field(x, y), ZZ.frac_field(x, z)) == ZZ.frac_field(x, y, z) assert unify(ZZ.frac_field(x, y), QQ.frac_field(x, z)) == QQ.frac_field(x, y, z) assert unify(QQ.frac_field(x, y), ZZ.frac_field(x, z)) == QQ.frac_field(x, y, z) assert unify(QQ.frac_field(x, y), QQ.frac_field(x, z)) == QQ.frac_field(x, y, z) assert unify(ZZ.poly_ring(x), ZZ.frac_field(x)) == ZZ.frac_field(x) assert unify(ZZ.poly_ring(x), QQ.frac_field(x)) == ZZ.frac_field(x) assert unify(QQ.poly_ring(x), ZZ.frac_field(x)) == ZZ.frac_field(x) assert unify(QQ.poly_ring(x), QQ.frac_field(x)) == QQ.frac_field(x) assert unify(ZZ.poly_ring(x, y), ZZ.frac_field(x)) == ZZ.frac_field(x, y) assert unify(ZZ.poly_ring(x, y), QQ.frac_field(x)) == ZZ.frac_field(x, y) assert unify(QQ.poly_ring(x, y), ZZ.frac_field(x)) == ZZ.frac_field(x, y) assert unify(QQ.poly_ring(x, y), QQ.frac_field(x)) == QQ.frac_field(x, y) assert unify(ZZ.poly_ring(x), ZZ.frac_field(x, y)) == ZZ.frac_field(x, y) assert unify(ZZ.poly_ring(x), QQ.frac_field(x, y)) == ZZ.frac_field(x, y) assert unify(QQ.poly_ring(x), ZZ.frac_field(x, y)) == ZZ.frac_field(x, y) assert unify(QQ.poly_ring(x), QQ.frac_field(x, y)) == QQ.frac_field(x, y) assert unify(ZZ.poly_ring(x, y), ZZ.frac_field(x, z)) == ZZ.frac_field(x, y, z) assert unify(ZZ.poly_ring(x, y), QQ.frac_field(x, z)) == ZZ.frac_field(x, y, z) assert unify(QQ.poly_ring(x, y), ZZ.frac_field(x, z)) == ZZ.frac_field(x, y, z) assert unify(QQ.poly_ring(x, y), QQ.frac_field(x, z)) == QQ.frac_field(x, y, z) assert unify(ZZ.frac_field(x), ZZ.poly_ring(x)) == ZZ.frac_field(x) assert unify(ZZ.frac_field(x), QQ.poly_ring(x)) == ZZ.frac_field(x) assert unify(QQ.frac_field(x), ZZ.poly_ring(x)) == ZZ.frac_field(x) assert unify(QQ.frac_field(x), QQ.poly_ring(x)) == QQ.frac_field(x) assert unify(ZZ.frac_field(x, y), ZZ.poly_ring(x)) == ZZ.frac_field(x, y) assert unify(ZZ.frac_field(x, y), QQ.poly_ring(x)) == ZZ.frac_field(x, y) assert unify(QQ.frac_field(x, y), ZZ.poly_ring(x)) == ZZ.frac_field(x, y) assert unify(QQ.frac_field(x, y), QQ.poly_ring(x)) == QQ.frac_field(x, y) assert unify(ZZ.frac_field(x), ZZ.poly_ring(x, y)) == ZZ.frac_field(x, y) assert unify(ZZ.frac_field(x), QQ.poly_ring(x, y)) == ZZ.frac_field(x, y) assert unify(QQ.frac_field(x), ZZ.poly_ring(x, y)) == ZZ.frac_field(x, y) assert unify(QQ.frac_field(x), QQ.poly_ring(x, y)) == QQ.frac_field(x, y) assert unify(ZZ.frac_field(x, y), ZZ.poly_ring(x, z)) == ZZ.frac_field(x, y, z) assert unify(ZZ.frac_field(x, y), QQ.poly_ring(x, z)) == ZZ.frac_field(x, y, z) assert unify(QQ.frac_field(x, y), ZZ.poly_ring(x, z)) == ZZ.frac_field(x, y, z) assert unify(QQ.frac_field(x, y), QQ.poly_ring(x, z)) == QQ.frac_field(x, y, z) def test_Domain_unify_algebraic(): sqrt5 = QQ.algebraic_field(sqrt(5)) sqrt7 = QQ.algebraic_field(sqrt(7)) sqrt57 = QQ.algebraic_field(sqrt(5), sqrt(7)) assert sqrt5.unify(sqrt7) == sqrt57 assert sqrt5.unify(sqrt5[x, y]) == sqrt5[x, y] assert sqrt5[x, y].unify(sqrt5) == sqrt5[x, y] assert sqrt5.unify(sqrt5.frac_field(x, y)) == sqrt5.frac_field(x, y) assert sqrt5.frac_field(x, y).unify(sqrt5) == sqrt5.frac_field(x, y) assert sqrt5.unify(sqrt7[x, y]) == sqrt57[x, y] assert sqrt5[x, y].unify(sqrt7) == sqrt57[x, y] assert sqrt5.unify(sqrt7.frac_field(x, y)) == sqrt57.frac_field(x, y) assert sqrt5.frac_field(x, y).unify(sqrt7) == sqrt57.frac_field(x, y) def test_Domain_unify_FiniteExtension(): KxZZ = FiniteExtension(Poly(x**2 - 2, x, domain=ZZ)) KxQQ = FiniteExtension(Poly(x**2 - 2, x, domain=QQ)) KxZZy = FiniteExtension(Poly(x**2 - 2, x, domain=ZZ[y])) KxQQy = FiniteExtension(Poly(x**2 - 2, x, domain=QQ[y])) assert KxZZ.unify(KxZZ) == KxZZ assert KxQQ.unify(KxQQ) == KxQQ assert KxZZy.unify(KxZZy) == KxZZy assert KxQQy.unify(KxQQy) == KxQQy assert KxZZ.unify(ZZ) == KxZZ assert KxZZ.unify(QQ) == KxQQ assert KxQQ.unify(ZZ) == KxQQ assert KxQQ.unify(QQ) == KxQQ assert KxZZ.unify(ZZ[y]) == KxZZy assert KxZZ.unify(QQ[y]) == KxQQy assert KxQQ.unify(ZZ[y]) == KxQQy assert KxQQ.unify(QQ[y]) == KxQQy assert KxZZy.unify(ZZ) == KxZZy assert KxZZy.unify(QQ) == KxQQy assert KxQQy.unify(ZZ) == KxQQy assert KxQQy.unify(QQ) == KxQQy assert KxZZy.unify(ZZ[y]) == KxZZy assert KxZZy.unify(QQ[y]) == KxQQy assert KxQQy.unify(ZZ[y]) == KxQQy assert KxQQy.unify(QQ[y]) == KxQQy K = FiniteExtension(Poly(x**2 - 2, x, domain=ZZ[y])) assert K.unify(ZZ) == K assert K.unify(ZZ[x]) == K assert K.unify(ZZ[y]) == K assert K.unify(ZZ[x, y]) == K Kz = FiniteExtension(Poly(x**2 - 2, x, domain=ZZ[y, z])) assert K.unify(ZZ[z]) == Kz assert K.unify(ZZ[x, z]) == Kz assert K.unify(ZZ[y, z]) == Kz assert K.unify(ZZ[x, y, z]) == Kz Kx = FiniteExtension(Poly(x**2 - 2, x, domain=ZZ)) Ky = FiniteExtension(Poly(y**2 - 2, y, domain=ZZ)) Kxy = FiniteExtension(Poly(y**2 - 2, y, domain=Kx)) assert Kx.unify(Kx) == Kx assert Ky.unify(Ky) == Ky assert Kx.unify(Ky) == Kxy assert Ky.unify(Kx) == Kxy def test_Domain_unify_with_symbols(): raises(UnificationFailed, lambda: ZZ[x, y].unify_with_symbols(ZZ, (y, z))) raises(UnificationFailed, lambda: ZZ.unify_with_symbols(ZZ[x, y], (y, z))) def test_Domain__contains__(): assert (0 in EX) is True assert (0 in ZZ) is True assert (0 in QQ) is True assert (0 in RR) is True assert (0 in CC) is True assert (0 in ALG) is True assert (0 in ZZ[x, y]) is True assert (0 in QQ[x, y]) is True assert (0 in RR[x, y]) is True assert (-7 in EX) is True assert (-7 in ZZ) is True assert (-7 in QQ) is True assert (-7 in RR) is True assert (-7 in CC) is True assert (-7 in ALG) is True assert (-7 in ZZ[x, y]) is True assert (-7 in QQ[x, y]) is True assert (-7 in RR[x, y]) is True assert (17 in EX) is True assert (17 in ZZ) is True assert (17 in QQ) is True assert (17 in RR) is True assert (17 in CC) is True assert (17 in ALG) is True assert (17 in ZZ[x, y]) is True assert (17 in QQ[x, y]) is True assert (17 in RR[x, y]) is True assert (Rational(-1, 7) in EX) is True assert (Rational(-1, 7) in ZZ) is False assert (Rational(-1, 7) in QQ) is True assert (Rational(-1, 7) in RR) is True assert (Rational(-1, 7) in CC) is True assert (Rational(-1, 7) in ALG) is True assert (Rational(-1, 7) in ZZ[x, y]) is False assert (Rational(-1, 7) in QQ[x, y]) is True assert (Rational(-1, 7) in RR[x, y]) is True assert (Rational(3, 5) in EX) is True assert (Rational(3, 5) in ZZ) is False assert (Rational(3, 5) in QQ) is True assert (Rational(3, 5) in RR) is True assert (Rational(3, 5) in CC) is True assert (Rational(3, 5) in ALG) is True assert (Rational(3, 5) in ZZ[x, y]) is False assert (Rational(3, 5) in QQ[x, y]) is True assert (Rational(3, 5) in RR[x, y]) is True assert (3.0 in EX) is True assert (3.0 in ZZ) is True assert (3.0 in QQ) is True assert (3.0 in RR) is True assert (3.0 in CC) is True assert (3.0 in ALG) is True assert (3.0 in ZZ[x, y]) is True assert (3.0 in QQ[x, y]) is True assert (3.0 in RR[x, y]) is True assert (3.14 in EX) is True assert (3.14 in ZZ) is False assert (3.14 in QQ) is True assert (3.14 in RR) is True assert (3.14 in CC) is True assert (3.14 in ALG) is True assert (3.14 in ZZ[x, y]) is False assert (3.14 in QQ[x, y]) is True assert (3.14 in RR[x, y]) is True assert (oo in ALG) is False assert (oo in ZZ[x, y]) is False assert (oo in QQ[x, y]) is False assert (-oo in ZZ) is False assert (-oo in QQ) is False assert (-oo in ALG) is False assert (-oo in ZZ[x, y]) is False assert (-oo in QQ[x, y]) is False assert (sqrt(7) in EX) is True assert (sqrt(7) in ZZ) is False assert (sqrt(7) in QQ) is False assert (sqrt(7) in RR) is True assert (sqrt(7) in CC) is True assert (sqrt(7) in ALG) is False assert (sqrt(7) in ZZ[x, y]) is False assert (sqrt(7) in QQ[x, y]) is False assert (sqrt(7) in RR[x, y]) is True assert (2*sqrt(3) + 1 in EX) is True assert (2*sqrt(3) + 1 in ZZ) is False assert (2*sqrt(3) + 1 in QQ) is False assert (2*sqrt(3) + 1 in RR) is True assert (2*sqrt(3) + 1 in CC) is True assert (2*sqrt(3) + 1 in ALG) is True assert (2*sqrt(3) + 1 in ZZ[x, y]) is False assert (2*sqrt(3) + 1 in QQ[x, y]) is False assert (2*sqrt(3) + 1 in RR[x, y]) is True assert (sin(1) in EX) is True assert (sin(1) in ZZ) is False assert (sin(1) in QQ) is False assert (sin(1) in RR) is True assert (sin(1) in CC) is True assert (sin(1) in ALG) is False assert (sin(1) in ZZ[x, y]) is False assert (sin(1) in QQ[x, y]) is False assert (sin(1) in RR[x, y]) is True assert (x**2 + 1 in EX) is True assert (x**2 + 1 in ZZ) is False assert (x**2 + 1 in QQ) is False assert (x**2 + 1 in RR) is False assert (x**2 + 1 in CC) is False assert (x**2 + 1 in ALG) is False assert (x**2 + 1 in ZZ[x]) is True assert (x**2 + 1 in QQ[x]) is True assert (x**2 + 1 in RR[x]) is True assert (x**2 + 1 in ZZ[x, y]) is True assert (x**2 + 1 in QQ[x, y]) is True assert (x**2 + 1 in RR[x, y]) is True assert (x**2 + y**2 in EX) is True assert (x**2 + y**2 in ZZ) is False assert (x**2 + y**2 in QQ) is False assert (x**2 + y**2 in RR) is False assert (x**2 + y**2 in CC) is False assert (x**2 + y**2 in ALG) is False assert (x**2 + y**2 in ZZ[x]) is False assert (x**2 + y**2 in QQ[x]) is False assert (x**2 + y**2 in RR[x]) is False assert (x**2 + y**2 in ZZ[x, y]) is True assert (x**2 + y**2 in QQ[x, y]) is True assert (x**2 + y**2 in RR[x, y]) is True assert (Rational(3, 2)*x/(y + 1) - z in QQ[x, y, z]) is False def test_issue_14433(): assert (Rational(2, 3)*x in QQ.frac_field(1/x)) is True assert (1/x in QQ.frac_field(x)) is True assert ((x**2 + y**2) in QQ.frac_field(1/x, 1/y)) is True assert ((x + y) in QQ.frac_field(1/x, y)) is True assert ((x - y) in QQ.frac_field(x, 1/y)) is True def test_Domain_get_ring(): assert ZZ.has_assoc_Ring is True assert QQ.has_assoc_Ring is True assert ZZ[x].has_assoc_Ring is True assert QQ[x].has_assoc_Ring is True assert ZZ[x, y].has_assoc_Ring is True assert QQ[x, y].has_assoc_Ring is True assert ZZ.frac_field(x).has_assoc_Ring is True assert QQ.frac_field(x).has_assoc_Ring is True assert ZZ.frac_field(x, y).has_assoc_Ring is True assert QQ.frac_field(x, y).has_assoc_Ring is True assert EX.has_assoc_Ring is False assert RR.has_assoc_Ring is False assert ALG.has_assoc_Ring is False assert ZZ.get_ring() == ZZ assert QQ.get_ring() == ZZ assert ZZ[x].get_ring() == ZZ[x] assert QQ[x].get_ring() == QQ[x] assert ZZ[x, y].get_ring() == ZZ[x, y] assert QQ[x, y].get_ring() == QQ[x, y] assert ZZ.frac_field(x).get_ring() == ZZ[x] assert QQ.frac_field(x).get_ring() == QQ[x] assert ZZ.frac_field(x, y).get_ring() == ZZ[x, y] assert QQ.frac_field(x, y).get_ring() == QQ[x, y] assert EX.get_ring() == EX assert RR.get_ring() == RR # XXX: This should also be like RR raises(DomainError, lambda: ALG.get_ring()) def test_Domain_get_field(): assert EX.has_assoc_Field is True assert ZZ.has_assoc_Field is True assert QQ.has_assoc_Field is True assert RR.has_assoc_Field is True assert ALG.has_assoc_Field is True assert ZZ[x].has_assoc_Field is True assert QQ[x].has_assoc_Field is True assert ZZ[x, y].has_assoc_Field is True assert QQ[x, y].has_assoc_Field is True assert EX.get_field() == EX assert ZZ.get_field() == QQ assert QQ.get_field() == QQ assert RR.get_field() == RR assert ALG.get_field() == ALG assert ZZ[x].get_field() == ZZ.frac_field(x) assert QQ[x].get_field() == QQ.frac_field(x) assert ZZ[x, y].get_field() == ZZ.frac_field(x, y) assert QQ[x, y].get_field() == QQ.frac_field(x, y) def test_Domain_get_exact(): assert EX.get_exact() == EX assert ZZ.get_exact() == ZZ assert QQ.get_exact() == QQ assert RR.get_exact() == QQ assert ALG.get_exact() == ALG assert ZZ[x].get_exact() == ZZ[x] assert QQ[x].get_exact() == QQ[x] assert ZZ[x, y].get_exact() == ZZ[x, y] assert QQ[x, y].get_exact() == QQ[x, y] assert ZZ.frac_field(x).get_exact() == ZZ.frac_field(x) assert QQ.frac_field(x).get_exact() == QQ.frac_field(x) assert ZZ.frac_field(x, y).get_exact() == ZZ.frac_field(x, y) assert QQ.frac_field(x, y).get_exact() == QQ.frac_field(x, y) def test_Domain_is_unit(): nums = [-2, -1, 0, 1, 2] invring = [False, True, False, True, False] invfield = [True, True, False, True, True] ZZx, QQx, QQxf = ZZ[x], QQ[x], QQ.frac_field(x) assert [ZZ.is_unit(ZZ(n)) for n in nums] == invring assert [QQ.is_unit(QQ(n)) for n in nums] == invfield assert [ZZx.is_unit(ZZx(n)) for n in nums] == invring assert [QQx.is_unit(QQx(n)) for n in nums] == invfield assert [QQxf.is_unit(QQxf(n)) for n in nums] == invfield assert ZZx.is_unit(ZZx(x)) is False assert QQx.is_unit(QQx(x)) is False assert QQxf.is_unit(QQxf(x)) is True def test_Domain_convert(): def check_element(e1, e2, K1, K2, K3): assert type(e1) is type(e2), '%s, %s: %s %s -> %s' % (e1, e2, K1, K2, K3) assert e1 == e2, '%s, %s: %s %s -> %s' % (e1, e2, K1, K2, K3) def check_domains(K1, K2): K3 = K1.unify(K2) check_element(K3.convert_from( K1.one, K1), K3.one, K1, K2, K3) check_element(K3.convert_from( K2.one, K2), K3.one, K1, K2, K3) check_element(K3.convert_from(K1.zero, K1), K3.zero, K1, K2, K3) check_element(K3.convert_from(K2.zero, K2), K3.zero, K1, K2, K3) def composite_domains(K): domains = [ K, K[y], K[z], K[y, z], K.frac_field(y), K.frac_field(z), K.frac_field(y, z), # XXX: These should be tested and made to work... # K.old_poly_ring(y), K.old_frac_field(y), ] return domains QQ2 = QQ.algebraic_field(sqrt(2)) QQ3 = QQ.algebraic_field(sqrt(3)) doms = [ZZ, QQ, QQ2, QQ3, QQ_I, ZZ_I, RR, CC] for i, K1 in enumerate(doms): for K2 in doms[i:]: for K3 in composite_domains(K1): for K4 in composite_domains(K2): check_domains(K3, K4) assert QQ.convert(10e-52) == QQ(1684996666696915, 1684996666696914987166688442938726917102321526408785780068975640576) R, xr = ring("x", ZZ) assert ZZ.convert(xr - xr) == 0 assert ZZ.convert(xr - xr, R.to_domain()) == 0 assert CC.convert(ZZ_I(1, 2)) == CC(1, 2) assert CC.convert(QQ_I(1, 2)) == CC(1, 2) K1 = QQ.frac_field(x) K2 = ZZ.frac_field(x) K3 = QQ[x] K4 = ZZ[x] Ks = [K1, K2, K3, K4] for Ka, Kb in product(Ks, Ks): assert Ka.convert_from(Kb.from_sympy(x), Kb) == Ka.from_sympy(x) assert K2.convert_from(QQ(1, 2), QQ) == K2(QQ(1, 2)) def test_GlobalPolynomialRing_convert(): K1 = QQ.old_poly_ring(x) K2 = QQ[x] assert K1.convert(x) == K1.convert(K2.convert(x), K2) assert K2.convert(x) == K2.convert(K1.convert(x), K1) K1 = QQ.old_poly_ring(x, y) K2 = QQ[x] assert K1.convert(x) == K1.convert(K2.convert(x), K2) #assert K2.convert(x) == K2.convert(K1.convert(x), K1) K1 = ZZ.old_poly_ring(x, y) K2 = QQ[x] assert K1.convert(x) == K1.convert(K2.convert(x), K2) #assert K2.convert(x) == K2.convert(K1.convert(x), K1) def test_PolynomialRing__init(): R, = ring("", ZZ) assert ZZ.poly_ring() == R.to_domain() def test_FractionField__init(): F, = field("", ZZ) assert ZZ.frac_field() == F.to_domain() def test_FractionField_convert(): K = QQ.frac_field(x) assert K.convert(QQ(2, 3), QQ) == K.from_sympy(Rational(2, 3)) K = QQ.frac_field(x) assert K.convert(ZZ(2), ZZ) == K.from_sympy(Integer(2)) def test_inject(): assert ZZ.inject(x, y, z) == ZZ[x, y, z] assert ZZ[x].inject(y, z) == ZZ[x, y, z] assert ZZ.frac_field(x).inject(y, z) == ZZ.frac_field(x, y, z) raises(GeneratorsError, lambda: ZZ[x].inject(x)) def test_drop(): assert ZZ.drop(x) == ZZ assert ZZ[x].drop(x) == ZZ assert ZZ[x, y].drop(x) == ZZ[y] assert ZZ.frac_field(x).drop(x) == ZZ assert ZZ.frac_field(x, y).drop(x) == ZZ.frac_field(y) assert ZZ[x][y].drop(y) == ZZ[x] assert ZZ[x][y].drop(x) == ZZ[y] assert ZZ.frac_field(x)[y].drop(x) == ZZ[y] assert ZZ.frac_field(x)[y].drop(y) == ZZ.frac_field(x) Ky = FiniteExtension(Poly(x**2-1, x, domain=ZZ[y])) K = FiniteExtension(Poly(x**2-1, x, domain=ZZ)) assert Ky.drop(y) == K raises(GeneratorsError, lambda: Ky.drop(x)) def test_Domain_map(): seq = ZZ.map([1, 2, 3, 4]) assert all(ZZ.of_type(elt) for elt in seq) seq = ZZ.map([[1, 2, 3, 4]]) assert all(ZZ.of_type(elt) for elt in seq[0]) and len(seq) == 1 def test_Domain___eq__(): assert (ZZ[x, y] == ZZ[x, y]) is True assert (QQ[x, y] == QQ[x, y]) is True assert (ZZ[x, y] == QQ[x, y]) is False assert (QQ[x, y] == ZZ[x, y]) is False assert (ZZ.frac_field(x, y) == ZZ.frac_field(x, y)) is True assert (QQ.frac_field(x, y) == QQ.frac_field(x, y)) is True assert (ZZ.frac_field(x, y) == QQ.frac_field(x, y)) is False assert (QQ.frac_field(x, y) == ZZ.frac_field(x, y)) is False assert RealField()[x] == RR[x] def test_Domain__algebraic_field(): alg = ZZ.algebraic_field(sqrt(2)) assert alg.ext.minpoly == Poly(x**2 - 2) assert alg.dom == QQ alg = QQ.algebraic_field(sqrt(2)) assert alg.ext.minpoly == Poly(x**2 - 2) assert alg.dom == QQ alg = alg.algebraic_field(sqrt(3)) assert alg.ext.minpoly == Poly(x**4 - 10*x**2 + 1) assert alg.dom == QQ def test_Domain_alg_field_from_poly(): f = Poly(x**2 - 2) g = Poly(x**2 - 3) h = Poly(x**4 - 10*x**2 + 1) alg = ZZ.alg_field_from_poly(f) assert alg.ext.minpoly == f assert alg.dom == QQ alg = QQ.alg_field_from_poly(f) assert alg.ext.minpoly == f assert alg.dom == QQ alg = alg.alg_field_from_poly(g) assert alg.ext.minpoly == h assert alg.dom == QQ def test_Domain_cyclotomic_field(): K = ZZ.cyclotomic_field(12) assert K.ext.minpoly == Poly(cyclotomic_poly(12)) assert K.dom == QQ F = QQ.cyclotomic_field(3) assert F.ext.minpoly == Poly(cyclotomic_poly(3)) assert F.dom == QQ E = F.cyclotomic_field(4) assert field_isomorphism(E.ext, K.ext) is not None assert E.dom == QQ def test_PolynomialRing_from_FractionField(): F, x,y = field("x,y", ZZ) R, X,Y = ring("x,y", ZZ) f = (x**2 + y**2)/(x + 1) g = (x**2 + y**2)/4 h = x**2 + y**2 assert R.to_domain().from_FractionField(f, F.to_domain()) is None assert R.to_domain().from_FractionField(g, F.to_domain()) == X**2/4 + Y**2/4 assert R.to_domain().from_FractionField(h, F.to_domain()) == X**2 + Y**2 F, x,y = field("x,y", QQ) R, X,Y = ring("x,y", QQ) f = (x**2 + y**2)/(x + 1) g = (x**2 + y**2)/4 h = x**2 + y**2 assert R.to_domain().from_FractionField(f, F.to_domain()) is None assert R.to_domain().from_FractionField(g, F.to_domain()) == X**2/4 + Y**2/4 assert R.to_domain().from_FractionField(h, F.to_domain()) == X**2 + Y**2 def test_FractionField_from_PolynomialRing(): R, x,y = ring("x,y", QQ) F, X,Y = field("x,y", ZZ) f = 3*x**2 + 5*y**2 g = x**2/3 + y**2/5 assert F.to_domain().from_PolynomialRing(f, R.to_domain()) == 3*X**2 + 5*Y**2 assert F.to_domain().from_PolynomialRing(g, R.to_domain()) == (5*X**2 + 3*Y**2)/15 def test_FF_of_type(): assert FF(3).of_type(FF(3)(1)) is True assert FF(5).of_type(FF(5)(3)) is True assert FF(5).of_type(FF(7)(3)) is False def test___eq__(): assert not QQ[x] == ZZ[x] assert not QQ.frac_field(x) == ZZ.frac_field(x) def test_RealField_from_sympy(): assert RR.convert(S.Zero) == RR.dtype(0) assert RR.convert(S(0.0)) == RR.dtype(0.0) assert RR.convert(S.One) == RR.dtype(1) assert RR.convert(S(1.0)) == RR.dtype(1.0) assert RR.convert(sin(1)) == RR.dtype(sin(1).evalf()) def test_not_in_any_domain(): check = list(_illegal) + [x] + [ float(i) for i in _illegal[:3]] for dom in (ZZ, QQ, RR, CC, EX): for i in check: if i == x and dom == EX: continue assert i not in dom, (i, dom) raises(CoercionFailed, lambda: dom.convert(i)) def test_ModularInteger(): F3 = FF(3) a = F3(0) assert isinstance(a, F3.dtype) and a == 0 a = F3(1) assert isinstance(a, F3.dtype) and a == 1 a = F3(2) assert isinstance(a, F3.dtype) and a == 2 a = F3(3) assert isinstance(a, F3.dtype) and a == 0 a = F3(4) assert isinstance(a, F3.dtype) and a == 1 a = F3(F3(0)) assert isinstance(a, F3.dtype) and a == 0 a = F3(F3(1)) assert isinstance(a, F3.dtype) and a == 1 a = F3(F3(2)) assert isinstance(a, F3.dtype) and a == 2 a = F3(F3(3)) assert isinstance(a, F3.dtype) and a == 0 a = F3(F3(4)) assert isinstance(a, F3.dtype) and a == 1 a = -F3(1) assert isinstance(a, F3.dtype) and a == 2 a = -F3(2) assert isinstance(a, F3.dtype) and a == 1 a = 2 + F3(2) assert isinstance(a, F3.dtype) and a == 1 a = F3(2) + 2 assert isinstance(a, F3.dtype) and a == 1 a = F3(2) + F3(2) assert isinstance(a, F3.dtype) and a == 1 a = F3(2) + F3(2) assert isinstance(a, F3.dtype) and a == 1 a = 3 - F3(2) assert isinstance(a, F3.dtype) and a == 1 a = F3(3) - 2 assert isinstance(a, F3.dtype) and a == 1 a = F3(3) - F3(2) assert isinstance(a, F3.dtype) and a == 1 a = F3(3) - F3(2) assert isinstance(a, F3.dtype) and a == 1 a = 2*F3(2) assert isinstance(a, F3.dtype) and a == 1 a = F3(2)*2 assert isinstance(a, F3.dtype) and a == 1 a = F3(2)*F3(2) assert isinstance(a, F3.dtype) and a == 1 a = F3(2)*F3(2) assert isinstance(a, F3.dtype) and a == 1 a = 2/F3(2) assert isinstance(a, F3.dtype) and a == 1 a = F3(2)/2 assert isinstance(a, F3.dtype) and a == 1 a = F3(2)/F3(2) assert isinstance(a, F3.dtype) and a == 1 a = F3(2)/F3(2) assert isinstance(a, F3.dtype) and a == 1 a = 1 % F3(2) assert isinstance(a, F3.dtype) and a == 1 a = F3(1) % 2 assert isinstance(a, F3.dtype) and a == 1 a = F3(1) % F3(2) assert isinstance(a, F3.dtype) and a == 1 a = F3(1) % F3(2) assert isinstance(a, F3.dtype) and a == 1 a = F3(2)**0 assert isinstance(a, F3.dtype) and a == 1 a = F3(2)**1 assert isinstance(a, F3.dtype) and a == 2 a = F3(2)**2 assert isinstance(a, F3.dtype) and a == 1 F7 = FF(7) a = F7(3)**100000000000 assert isinstance(a, F7.dtype) and a == 4 a = F7(3)**-100000000000 assert isinstance(a, F7.dtype) and a == 2 a = F7(3)**S(2) assert isinstance(a, F7.dtype) and a == 2 assert bool(F3(3)) is False assert bool(F3(4)) is True F5 = FF(5) a = F5(1)**(-1) assert isinstance(a, F5.dtype) and a == 1 a = F5(2)**(-1) assert isinstance(a, F5.dtype) and a == 3 a = F5(3)**(-1) assert isinstance(a, F5.dtype) and a == 2 a = F5(4)**(-1) assert isinstance(a, F5.dtype) and a == 4 assert (F5(1) < F5(2)) is True assert (F5(1) <= F5(2)) is True assert (F5(1) > F5(2)) is False assert (F5(1) >= F5(2)) is False assert (F5(3) < F5(2)) is False assert (F5(3) <= F5(2)) is False assert (F5(3) > F5(2)) is True assert (F5(3) >= F5(2)) is True assert (F5(1) < F5(7)) is True assert (F5(1) <= F5(7)) is True assert (F5(1) > F5(7)) is False assert (F5(1) >= F5(7)) is False assert (F5(3) < F5(7)) is False assert (F5(3) <= F5(7)) is False assert (F5(3) > F5(7)) is True assert (F5(3) >= F5(7)) is True assert (F5(1) < 2) is True assert (F5(1) <= 2) is True assert (F5(1) > 2) is False assert (F5(1) >= 2) is False assert (F5(3) < 2) is False assert (F5(3) <= 2) is False assert (F5(3) > 2) is True assert (F5(3) >= 2) is True assert (F5(1) < 7) is True assert (F5(1) <= 7) is True assert (F5(1) > 7) is False assert (F5(1) >= 7) is False assert (F5(3) < 7) is False assert (F5(3) <= 7) is False assert (F5(3) > 7) is True assert (F5(3) >= 7) is True raises(NotInvertible, lambda: F5(0)**(-1)) raises(NotInvertible, lambda: F5(5)**(-1)) raises(ValueError, lambda: FF(0)) raises(ValueError, lambda: FF(2.1)) def test_QQ_int(): assert int(QQ(2**2000, 3**1250)) == 455431 assert int(QQ(2**100, 3)) == 422550200076076467165567735125 def test_RR_double(): assert RR(3.14) > 1e-50 assert RR(1e-13) > 1e-50 assert RR(1e-14) > 1e-50 assert RR(1e-15) > 1e-50 assert RR(1e-20) > 1e-50 assert RR(1e-40) > 1e-50 def test_RR_Float(): f1 = Float("1.01") f2 = Float("1.0000000000000000000001") assert f1._prec == 53 assert f2._prec == 80 assert RR(f1)-1 > 1e-50 assert RR(f2)-1 < 1e-50 # RR's precision is lower than f2's RR2 = RealField(prec=f2._prec) assert RR2(f1)-1 > 1e-50 assert RR2(f2)-1 > 1e-50 # RR's precision is equal to f2's def test_CC_double(): assert CC(3.14).real > 1e-50 assert CC(1e-13).real > 1e-50 assert CC(1e-14).real > 1e-50 assert CC(1e-15).real > 1e-50 assert CC(1e-20).real > 1e-50 assert CC(1e-40).real > 1e-50 assert CC(3.14j).imag > 1e-50 assert CC(1e-13j).imag > 1e-50 assert CC(1e-14j).imag > 1e-50 assert CC(1e-15j).imag > 1e-50 assert CC(1e-20j).imag > 1e-50 assert CC(1e-40j).imag > 1e-50 def test_gaussian_domains(): I = S.ImaginaryUnit a, b, c, d = [ZZ_I.convert(x) for x in (5, 2 + I, 3 - I, 5 - 5*I)] assert ZZ_I.gcd(a, b) == b assert ZZ_I.gcd(a, c) == b assert ZZ_I.lcm(a, b) == a assert ZZ_I.lcm(a, c) == d assert ZZ_I(3, 4) != QQ_I(3, 4) # XXX is this right or should QQ->ZZ if possible? assert ZZ_I(3, 0) != 3 # and should this go to Integer? assert QQ_I(S(3)/4, 0) != S(3)/4 # and this to Rational? assert ZZ_I(0, 0).quadrant() == 0 assert ZZ_I(-1, 0).quadrant() == 2 assert QQ_I.convert(QQ(3, 2)) == QQ_I(QQ(3, 2), QQ(0)) assert QQ_I.convert(QQ(3, 2), QQ) == QQ_I(QQ(3, 2), QQ(0)) for G in (QQ_I, ZZ_I): q = G(3, 4) assert str(q) == '3 + 4*I' assert q.parent() == G assert q._get_xy(pi) == (None, None) assert q._get_xy(2) == (2, 0) assert q._get_xy(2*I) == (0, 2) assert hash(q) == hash((3, 4)) assert G(1, 2) == G(1, 2) assert G(1, 2) != G(1, 3) assert G(3, 0) == G(3) assert q + q == G(6, 8) assert q - q == G(0, 0) assert 3 - q == -q + 3 == G(0, -4) assert 3 + q == q + 3 == G(6, 4) assert q * q == G(-7, 24) assert 3 * q == q * 3 == G(9, 12) assert q ** 0 == G(1, 0) assert q ** 1 == q assert q ** 2 == q * q == G(-7, 24) assert q ** 3 == q * q * q == G(-117, 44) assert 1 / q == q ** -1 == QQ_I(S(3)/25, - S(4)/25) assert q / 1 == QQ_I(3, 4) assert q / 2 == QQ_I(S(3)/2, 2) assert q/3 == QQ_I(1, S(4)/3) assert 3/q == QQ_I(S(9)/25, -S(12)/25) i, r = divmod(q, 2) assert 2*i + r == q i, r = divmod(2, q) assert q*i + r == G(2, 0) raises(ZeroDivisionError, lambda: q % 0) raises(ZeroDivisionError, lambda: q / 0) raises(ZeroDivisionError, lambda: q // 0) raises(ZeroDivisionError, lambda: divmod(q, 0)) raises(ZeroDivisionError, lambda: divmod(q, 0)) raises(TypeError, lambda: q + x) raises(TypeError, lambda: q - x) raises(TypeError, lambda: x + q) raises(TypeError, lambda: x - q) raises(TypeError, lambda: q * x) raises(TypeError, lambda: x * q) raises(TypeError, lambda: q / x) raises(TypeError, lambda: x / q) raises(TypeError, lambda: q // x) raises(TypeError, lambda: x // q) assert G.from_sympy(S(2)) == G(2, 0) assert G.to_sympy(G(2, 0)) == S(2) raises(CoercionFailed, lambda: G.from_sympy(pi)) PR = G.inject(x) assert isinstance(PR, PolynomialRing) assert PR.domain == G assert len(PR.gens) == 1 and PR.gens[0].as_expr() == x if G is QQ_I: AF = G.as_AlgebraicField() assert isinstance(AF, AlgebraicField) assert AF.domain == QQ assert AF.ext.args[0] == I for qi in [G(-1, 0), G(1, 0), G(0, -1), G(0, 1)]: assert G.is_negative(qi) is False assert G.is_positive(qi) is False assert G.is_nonnegative(qi) is False assert G.is_nonpositive(qi) is False domains = [ZZ_python(), QQ_python(), AlgebraicField(QQ, I)] if HAS_GMPY: domains += [ZZ_gmpy(), QQ_gmpy()] for K in domains: assert G.convert(K(2)) == G(2, 0) assert G.convert(K(2), K) == G(2, 0) for K in ZZ_I, QQ_I: assert G.convert(K(1, 1)) == G(1, 1) assert G.convert(K(1, 1), K) == G(1, 1) if G == ZZ_I: assert repr(q) == 'ZZ_I(3, 4)' assert q//3 == G(1, 1) assert 12//q == G(1, -2) assert 12 % q == G(1, 2) assert q % 2 == G(-1, 0) assert i == G(0, 0) assert r == G(2, 0) assert G.get_ring() == G assert G.get_field() == QQ_I else: assert repr(q) == 'QQ_I(3, 4)' assert G.get_ring() == ZZ_I assert G.get_field() == G assert q//3 == G(1, S(4)/3) assert 12//q == G(S(36)/25, -S(48)/25) assert 12 % q == G(0, 0) assert q % 2 == G(0, 0) assert i == G(S(6)/25, -S(8)/25), (G,i) assert r == G(0, 0) q2 = G(S(3)/2, S(5)/3) assert G.numer(q2) == ZZ_I(9, 10) assert G.denom(q2) == ZZ_I(6) def test_EX_EXRAW(): assert EXRAW.zero is S.Zero assert EXRAW.one is S.One assert EX(1) == EX.Expression(1) assert EX(1).ex is S.One assert EXRAW(1) is S.One # EX has cancelling but EXRAW does not assert 2*EX((x + y*x)/x) == EX(2 + 2*y) != 2*((x + y*x)/x) assert 2*EXRAW((x + y*x)/x) == 2*((x + y*x)/x) != (1 + y) assert EXRAW.convert_from(EX(1), EX) is EXRAW.one assert EX.convert_from(EXRAW(1), EXRAW) == EX.one assert EXRAW.from_sympy(S.One) is S.One assert EXRAW.to_sympy(EXRAW.one) is S.One raises(CoercionFailed, lambda: EXRAW.from_sympy([])) assert EXRAW.get_field() == EXRAW assert EXRAW.unify(EX) == EXRAW assert EX.unify(EXRAW) == EXRAW def test_canonical_unit(): for K in [ZZ, QQ, RR]: # CC? assert K.canonical_unit(K(2)) == K(1) assert K.canonical_unit(K(-2)) == K(-1) for K in [ZZ_I, QQ_I]: i = K.from_sympy(I) assert K.canonical_unit(K(2)) == K(1) assert K.canonical_unit(K(2)*i) == -i assert K.canonical_unit(-K(2)) == K(-1) assert K.canonical_unit(-K(2)*i) == i K = ZZ[x] assert K.canonical_unit(K(x + 1)) == K(1) assert K.canonical_unit(K(-x + 1)) == K(-1) K = ZZ_I[x] assert K.canonical_unit(K.from_sympy(I*x)) == ZZ_I(0, -1) K = ZZ_I.frac_field(x, y) i = K.from_sympy(I) assert i / i == K.one assert (K.one + i)/(i - K.one) == -i def test_issue_18278(): assert str(RR(2).parent()) == 'RR' assert str(CC(2).parent()) == 'CC' def test_Domain_is_negative(): I = S.ImaginaryUnit a, b = [CC.convert(x) for x in (2 + I, 5)] assert CC.is_negative(a) == False assert CC.is_negative(b) == False def test_Domain_is_positive(): I = S.ImaginaryUnit a, b = [CC.convert(x) for x in (2 + I, 5)] assert CC.is_positive(a) == False assert CC.is_positive(b) == False def test_Domain_is_nonnegative(): I = S.ImaginaryUnit a, b = [CC.convert(x) for x in (2 + I, 5)] assert CC.is_nonnegative(a) == False assert CC.is_nonnegative(b) == False def test_Domain_is_nonpositive(): I = S.ImaginaryUnit a, b = [CC.convert(x) for x in (2 + I, 5)] assert CC.is_nonpositive(a) == False assert CC.is_nonpositive(b) == False def test_exponential_domain(): K = ZZ[E] eK = K.from_sympy(E) assert K.from_sympy(exp(3)) == eK ** 3 assert K.convert(exp(3)) == eK ** 3
f07306c7604d9667327bd032c812204c1dc04479e8c6e0ecf48c54f7f536fcd0
from sympy.abc import x from sympy.core import S from sympy.core.numbers import AlgebraicNumber from sympy.functions.elementary.miscellaneous import sqrt from sympy.polys import Poly, cyclotomic_poly from sympy.polys.domains import QQ from sympy.polys.matrices import DomainMatrix, DM from sympy.polys.numberfields.basis import round_two from sympy.testing.pytest import raises def test_round_two(): # Poly must be monic, irreducible, and over ZZ: raises(ValueError, lambda: round_two(Poly(3 * x ** 2 + 1))) raises(ValueError, lambda: round_two(Poly(x ** 2 - 1))) raises(ValueError, lambda: round_two(Poly(x ** 2 + QQ(1, 2)))) # Test on many fields: cases = ( # A couple of cyclotomic fields: (cyclotomic_poly(5), DomainMatrix.eye(4, QQ), 125), (cyclotomic_poly(7), DomainMatrix.eye(6, QQ), -16807), # A couple of quadratic fields (one 1 mod 4, one 3 mod 4): (x ** 2 - 5, DM([[1, (1, 2)], [0, (1, 2)]], QQ), 5), (x ** 2 - 7, DM([[1, 0], [0, 1]], QQ), 28), # Dedekind's example of a field with 2 as essential disc divisor: (x ** 3 + x ** 2 - 2 * x + 8, DM([[1, 0, 0], [0, 1, 0], [0, (1, 2), (1, 2)]], QQ).transpose(), -503), # A bunch of cubics with various forms for F -- all of these require # second or third enlargements. (Five of them require a third, while the rest require just a second.) # F = 2^2 (x**3 + 3 * x**2 - 4 * x + 4, DM([((1, 2), (1, 4), (1, 4)), (0, (1, 2), (1, 2)), (0, 0, 1)], QQ).transpose(), -83), # F = 2^2 * 3 (x**3 + 3 * x**2 + 3 * x - 3, DM([((1, 2), 0, (1, 2)), (0, 1, 0), (0, 0, 1)], QQ).transpose(), -108), # F = 2^3 (x**3 + 5 * x**2 - x + 3, DM([((1, 4), 0, (3, 4)), (0, (1, 2), (1, 2)), (0, 0, 1)], QQ).transpose(), -31), # F = 2^2 * 5 (x**3 + 5 * x**2 - 5 * x - 5, DM([((1, 2), 0, (1, 2)), (0, 1, 0), (0, 0, 1)], QQ).transpose(), 1300), # F = 3^2 (x**3 + 3 * x**2 + 5, DM([((1, 3), (1, 3), (1, 3)), (0, 1, 0), (0, 0, 1)], QQ).transpose(), -135), # F = 3^3 (x**3 + 6 * x**2 + 3 * x - 1, DM([((1, 3), (1, 3), (1, 3)), (0, 1, 0), (0, 0, 1)], QQ).transpose(), 81), # F = 2^2 * 3^2 (x**3 + 6 * x**2 + 4, DM([((1, 3), (2, 3), (1, 3)), (0, 1, 0), (0, 0, (1, 2))], QQ).transpose(), -108), # F = 2^3 * 7 (x**3 + 7 * x**2 + 7 * x - 7, DM([((1, 4), 0, (3, 4)), (0, (1, 2), (1, 2)), (0, 0, 1)], QQ).transpose(), 49), # F = 2^2 * 13 (x**3 + 7 * x**2 - x + 5, DM([((1, 2), 0, (1, 2)), (0, 1, 0), (0, 0, 1)], QQ).transpose(), -2028), # F = 2^4 (x**3 + 7 * x**2 - 5 * x + 5, DM([((1, 4), 0, (3, 4)), (0, (1, 2), (1, 2)), (0, 0, 1)], QQ).transpose(), -140), # F = 5^2 (x**3 + 4 * x**2 - 3 * x + 7, DM([((1, 5), (4, 5), (4, 5)), (0, 1, 0), (0, 0, 1)], QQ).transpose(), -175), # F = 7^2 (x**3 + 8 * x**2 + 5 * x - 1, DM([((1, 7), (6, 7), (2, 7)), (0, 1, 0), (0, 0, 1)], QQ).transpose(), 49), # F = 2 * 5 * 7 (x**3 + 8 * x**2 - 2 * x + 6, DM([(1, 0, 0), (0, 1, 0), (0, 0, 1)], QQ).transpose(), -14700), # F = 2^2 * 3 * 5 (x**3 + 6 * x**2 - 3 * x + 8, DM([(1, 0, 0), (0, (1, 4), (1, 4)), (0, 0, 1)], QQ).transpose(), -675), # F = 2 * 3^2 * 7 (x**3 + 9 * x**2 + 6 * x - 8, DM([(1, 0, 0), (0, (1, 2), (1, 2)), (0, 0, 1)], QQ).transpose(), 3969), # F = 2^2 * 3^2 * 7 (x**3 + 15 * x**2 - 9 * x + 13, DM([((1, 6), (1, 3), (1, 6)), (0, 1, 0), (0, 0, 1)], QQ).transpose(), -5292), ) for f, B_exp, d_exp in cases: K = QQ.alg_field_from_poly(f) B = K.maximal_order().QQ_matrix d = K.discriminant() assert d == d_exp # The computed basis need not equal the expected one, but their quotient # must be unimodular: assert (B.inv()*B_exp).det()**2 == 1 def test_AlgebraicField_integral_basis(): alpha = AlgebraicNumber(sqrt(5), alias='alpha') k = QQ.algebraic_field(alpha) B0 = k.integral_basis() B1 = k.integral_basis(fmt='sympy') B2 = k.integral_basis(fmt='alg') assert B0 == [k([1]), k([S.Half, S.Half])] assert B1 == [1, S.Half + alpha/2] assert B2 == [alpha.field_element([1]), alpha.field_element([S.Half, S.Half])]
fda09bbee92b6a1bfe4320b0353ec4a53602d6ee77c9494c85f1aa5791b35b76
"""Tests for the subfield problem and allied problems. """ from sympy.core.numbers import (AlgebraicNumber, I, pi, Rational) from sympy.core.singleton import S from sympy.functions.elementary.exponential import exp from sympy.functions.elementary.miscellaneous import sqrt from sympy.external.gmpy import MPQ from sympy.polys.numberfields.subfield import ( is_isomorphism_possible, field_isomorphism_pslq, field_isomorphism, primitive_element, to_number_field, ) from sympy.polys.polyerrors import IsomorphismFailed from sympy.polys.polytools import Poly from sympy.polys.rootoftools import CRootOf from sympy.testing.pytest import raises from sympy.abc import x Q = Rational def test_field_isomorphism_pslq(): a = AlgebraicNumber(I) b = AlgebraicNumber(I*sqrt(3)) raises(NotImplementedError, lambda: field_isomorphism_pslq(a, b)) a = AlgebraicNumber(sqrt(2)) b = AlgebraicNumber(sqrt(3)) c = AlgebraicNumber(sqrt(7)) d = AlgebraicNumber(sqrt(2) + sqrt(3)) e = AlgebraicNumber(sqrt(2) + sqrt(3) + sqrt(7)) assert field_isomorphism_pslq(a, a) == [1, 0] assert field_isomorphism_pslq(a, b) is None assert field_isomorphism_pslq(a, c) is None assert field_isomorphism_pslq(a, d) == [Q(1, 2), 0, -Q(9, 2), 0] assert field_isomorphism_pslq( a, e) == [Q(1, 80), 0, -Q(1, 2), 0, Q(59, 20), 0] assert field_isomorphism_pslq(b, a) is None assert field_isomorphism_pslq(b, b) == [1, 0] assert field_isomorphism_pslq(b, c) is None assert field_isomorphism_pslq(b, d) == [-Q(1, 2), 0, Q(11, 2), 0] assert field_isomorphism_pslq(b, e) == [-Q( 3, 640), 0, Q(67, 320), 0, -Q(297, 160), 0, Q(313, 80), 0] assert field_isomorphism_pslq(c, a) is None assert field_isomorphism_pslq(c, b) is None assert field_isomorphism_pslq(c, c) == [1, 0] assert field_isomorphism_pslq(c, d) is None assert field_isomorphism_pslq(c, e) == [Q( 3, 640), 0, -Q(71, 320), 0, Q(377, 160), 0, -Q(469, 80), 0] assert field_isomorphism_pslq(d, a) is None assert field_isomorphism_pslq(d, b) is None assert field_isomorphism_pslq(d, c) is None assert field_isomorphism_pslq(d, d) == [1, 0] assert field_isomorphism_pslq(d, e) == [-Q( 3, 640), 0, Q(71, 320), 0, -Q(377, 160), 0, Q(549, 80), 0] assert field_isomorphism_pslq(e, a) is None assert field_isomorphism_pslq(e, b) is None assert field_isomorphism_pslq(e, c) is None assert field_isomorphism_pslq(e, d) is None assert field_isomorphism_pslq(e, e) == [1, 0] f = AlgebraicNumber(3*sqrt(2) + 8*sqrt(7) - 5) assert field_isomorphism_pslq( f, e) == [Q(3, 80), 0, -Q(139, 80), 0, Q(347, 20), 0, -Q(761, 20), -5] def test_field_isomorphism(): assert field_isomorphism(3, sqrt(2)) == [3] assert field_isomorphism( I*sqrt(3), I*sqrt(3)/2) == [ 2, 0] assert field_isomorphism(-I*sqrt(3), I*sqrt(3)/2) == [-2, 0] assert field_isomorphism( I*sqrt(3), -I*sqrt(3)/2) == [-2, 0] assert field_isomorphism(-I*sqrt(3), -I*sqrt(3)/2) == [ 2, 0] assert field_isomorphism( 2*I*sqrt(3)/7, 5*I*sqrt(3)/3) == [ Rational(6, 35), 0] assert field_isomorphism(-2*I*sqrt(3)/7, 5*I*sqrt(3)/3) == [Rational(-6, 35), 0] assert field_isomorphism( 2*I*sqrt(3)/7, -5*I*sqrt(3)/3) == [Rational(-6, 35), 0] assert field_isomorphism(-2*I*sqrt(3)/7, -5*I*sqrt(3)/3) == [ Rational(6, 35), 0] assert field_isomorphism( 2*I*sqrt(3)/7 + 27, 5*I*sqrt(3)/3) == [ Rational(6, 35), 27] assert field_isomorphism( -2*I*sqrt(3)/7 + 27, 5*I*sqrt(3)/3) == [Rational(-6, 35), 27] assert field_isomorphism( 2*I*sqrt(3)/7 + 27, -5*I*sqrt(3)/3) == [Rational(-6, 35), 27] assert field_isomorphism( -2*I*sqrt(3)/7 + 27, -5*I*sqrt(3)/3) == [ Rational(6, 35), 27] p = AlgebraicNumber( sqrt(2) + sqrt(3)) q = AlgebraicNumber(-sqrt(2) + sqrt(3)) r = AlgebraicNumber( sqrt(2) - sqrt(3)) s = AlgebraicNumber(-sqrt(2) - sqrt(3)) pos_coeffs = [ S.Half, S.Zero, Rational(-9, 2), S.Zero] neg_coeffs = [Rational(-1, 2), S.Zero, Rational(9, 2), S.Zero] a = AlgebraicNumber(sqrt(2)) assert is_isomorphism_possible(a, p) is True assert is_isomorphism_possible(a, q) is True assert is_isomorphism_possible(a, r) is True assert is_isomorphism_possible(a, s) is True assert field_isomorphism(a, p, fast=True) == pos_coeffs assert field_isomorphism(a, q, fast=True) == neg_coeffs assert field_isomorphism(a, r, fast=True) == pos_coeffs assert field_isomorphism(a, s, fast=True) == neg_coeffs assert field_isomorphism(a, p, fast=False) == pos_coeffs assert field_isomorphism(a, q, fast=False) == neg_coeffs assert field_isomorphism(a, r, fast=False) == pos_coeffs assert field_isomorphism(a, s, fast=False) == neg_coeffs a = AlgebraicNumber(-sqrt(2)) assert is_isomorphism_possible(a, p) is True assert is_isomorphism_possible(a, q) is True assert is_isomorphism_possible(a, r) is True assert is_isomorphism_possible(a, s) is True assert field_isomorphism(a, p, fast=True) == neg_coeffs assert field_isomorphism(a, q, fast=True) == pos_coeffs assert field_isomorphism(a, r, fast=True) == neg_coeffs assert field_isomorphism(a, s, fast=True) == pos_coeffs assert field_isomorphism(a, p, fast=False) == neg_coeffs assert field_isomorphism(a, q, fast=False) == pos_coeffs assert field_isomorphism(a, r, fast=False) == neg_coeffs assert field_isomorphism(a, s, fast=False) == pos_coeffs pos_coeffs = [ S.Half, S.Zero, Rational(-11, 2), S.Zero] neg_coeffs = [Rational(-1, 2), S.Zero, Rational(11, 2), S.Zero] a = AlgebraicNumber(sqrt(3)) assert is_isomorphism_possible(a, p) is True assert is_isomorphism_possible(a, q) is True assert is_isomorphism_possible(a, r) is True assert is_isomorphism_possible(a, s) is True assert field_isomorphism(a, p, fast=True) == neg_coeffs assert field_isomorphism(a, q, fast=True) == neg_coeffs assert field_isomorphism(a, r, fast=True) == pos_coeffs assert field_isomorphism(a, s, fast=True) == pos_coeffs assert field_isomorphism(a, p, fast=False) == neg_coeffs assert field_isomorphism(a, q, fast=False) == neg_coeffs assert field_isomorphism(a, r, fast=False) == pos_coeffs assert field_isomorphism(a, s, fast=False) == pos_coeffs a = AlgebraicNumber(-sqrt(3)) assert is_isomorphism_possible(a, p) is True assert is_isomorphism_possible(a, q) is True assert is_isomorphism_possible(a, r) is True assert is_isomorphism_possible(a, s) is True assert field_isomorphism(a, p, fast=True) == pos_coeffs assert field_isomorphism(a, q, fast=True) == pos_coeffs assert field_isomorphism(a, r, fast=True) == neg_coeffs assert field_isomorphism(a, s, fast=True) == neg_coeffs assert field_isomorphism(a, p, fast=False) == pos_coeffs assert field_isomorphism(a, q, fast=False) == pos_coeffs assert field_isomorphism(a, r, fast=False) == neg_coeffs assert field_isomorphism(a, s, fast=False) == neg_coeffs pos_coeffs = [ Rational(3, 2), S.Zero, Rational(-33, 2), -S(8)] neg_coeffs = [Rational(-3, 2), S.Zero, Rational(33, 2), -S(8)] a = AlgebraicNumber(3*sqrt(3) - 8) assert is_isomorphism_possible(a, p) is True assert is_isomorphism_possible(a, q) is True assert is_isomorphism_possible(a, r) is True assert is_isomorphism_possible(a, s) is True assert field_isomorphism(a, p, fast=True) == neg_coeffs assert field_isomorphism(a, q, fast=True) == neg_coeffs assert field_isomorphism(a, r, fast=True) == pos_coeffs assert field_isomorphism(a, s, fast=True) == pos_coeffs assert field_isomorphism(a, p, fast=False) == neg_coeffs assert field_isomorphism(a, q, fast=False) == neg_coeffs assert field_isomorphism(a, r, fast=False) == pos_coeffs assert field_isomorphism(a, s, fast=False) == pos_coeffs a = AlgebraicNumber(3*sqrt(2) + 2*sqrt(3) + 1) pos_1_coeffs = [ S.Half, S.Zero, Rational(-5, 2), S.One] neg_5_coeffs = [Rational(-5, 2), S.Zero, Rational(49, 2), S.One] pos_5_coeffs = [ Rational(5, 2), S.Zero, Rational(-49, 2), S.One] neg_1_coeffs = [Rational(-1, 2), S.Zero, Rational(5, 2), S.One] assert is_isomorphism_possible(a, p) is True assert is_isomorphism_possible(a, q) is True assert is_isomorphism_possible(a, r) is True assert is_isomorphism_possible(a, s) is True assert field_isomorphism(a, p, fast=True) == pos_1_coeffs assert field_isomorphism(a, q, fast=True) == neg_5_coeffs assert field_isomorphism(a, r, fast=True) == pos_5_coeffs assert field_isomorphism(a, s, fast=True) == neg_1_coeffs assert field_isomorphism(a, p, fast=False) == pos_1_coeffs assert field_isomorphism(a, q, fast=False) == neg_5_coeffs assert field_isomorphism(a, r, fast=False) == pos_5_coeffs assert field_isomorphism(a, s, fast=False) == neg_1_coeffs a = AlgebraicNumber(sqrt(2)) b = AlgebraicNumber(sqrt(3)) c = AlgebraicNumber(sqrt(7)) assert is_isomorphism_possible(a, b) is True assert is_isomorphism_possible(b, a) is True assert is_isomorphism_possible(c, p) is False assert field_isomorphism(sqrt(2), sqrt(3), fast=True) is None assert field_isomorphism(sqrt(3), sqrt(2), fast=True) is None assert field_isomorphism(sqrt(2), sqrt(3), fast=False) is None assert field_isomorphism(sqrt(3), sqrt(2), fast=False) is None a = AlgebraicNumber(sqrt(2)) b = AlgebraicNumber(2 ** (S(1) / 3)) assert is_isomorphism_possible(a, b) is False assert field_isomorphism(a, b) is None def test_primitive_element(): assert primitive_element([sqrt(2)], x) == (x**2 - 2, [1]) assert primitive_element( [sqrt(2), sqrt(3)], x) == (x**4 - 10*x**2 + 1, [1, 1]) assert primitive_element([sqrt(2)], x, polys=True) == (Poly(x**2 - 2, domain='QQ'), [1]) assert primitive_element([sqrt( 2), sqrt(3)], x, polys=True) == (Poly(x**4 - 10*x**2 + 1, domain='QQ'), [1, 1]) assert primitive_element( [sqrt(2)], x, ex=True) == (x**2 - 2, [1], [[1, 0]]) assert primitive_element([sqrt(2), sqrt(3)], x, ex=True) == \ (x**4 - 10*x**2 + 1, [1, 1], [[Q(1, 2), 0, -Q(9, 2), 0], [- Q(1, 2), 0, Q(11, 2), 0]]) assert primitive_element( [sqrt(2)], x, ex=True, polys=True) == (Poly(x**2 - 2, domain='QQ'), [1], [[1, 0]]) assert primitive_element([sqrt(2), sqrt(3)], x, ex=True, polys=True) == \ (Poly(x**4 - 10*x**2 + 1, domain='QQ'), [1, 1], [[Q(1, 2), 0, -Q(9, 2), 0], [-Q(1, 2), 0, Q(11, 2), 0]]) assert primitive_element([sqrt(2)], polys=True) == (Poly(x**2 - 2), [1]) raises(ValueError, lambda: primitive_element([], x, ex=False)) raises(ValueError, lambda: primitive_element([], x, ex=True)) # Issue 14117 a, b = I*sqrt(2*sqrt(2) + 3), I*sqrt(-2*sqrt(2) + 3) assert primitive_element([a, b, I], x) == (x**4 + 6*x**2 + 1, [1, 0, 0]) assert primitive_element([sqrt(2), 0], x) == (x**2 - 2, [1, 0]) assert primitive_element([0, sqrt(2)], x) == (x**2 - 2, [1, 1]) assert primitive_element([sqrt(2), 0], x, ex=True) == (x**2 - 2, [1, 0], [[MPQ(1,1), MPQ(0,1)], []]) assert primitive_element([0, sqrt(2)], x, ex=True) == (x**2 - 2, [1, 1], [[], [MPQ(1,1), MPQ(0,1)]]) def test_to_number_field(): assert to_number_field(sqrt(2)) == AlgebraicNumber(sqrt(2)) assert to_number_field( [sqrt(2), sqrt(3)]) == AlgebraicNumber(sqrt(2) + sqrt(3)) a = AlgebraicNumber(sqrt(2) + sqrt(3), [S.Half, S.Zero, Rational(-9, 2), S.Zero]) assert to_number_field(sqrt(2), sqrt(2) + sqrt(3)) == a assert to_number_field(sqrt(2), AlgebraicNumber(sqrt(2) + sqrt(3))) == a raises(IsomorphismFailed, lambda: to_number_field(sqrt(2), sqrt(3))) def test_issue_22561(): a = to_number_field(sqrt(2), sqrt(2) + sqrt(3)) b = to_number_field(sqrt(2), sqrt(2) + sqrt(5)) assert field_isomorphism(a, b) == [1, 0] def test_issue_22736(): a = CRootOf(x**4 + x**3 + x**2 + x + 1, -1) a._reset() b = exp(2*I*pi/5) assert field_isomorphism(a, b) == [1, 0]
8862b8750a713cd1c90234412f963c97b54a1a8aebf6ea3a18e3b9e9bdee8a5e
from sympy import QQ, ZZ, S from sympy.abc import x, theta from sympy.core.mul import prod 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 from sympy.polys.numberfields.primes import ( prime_decomp, _two_elt_rep, _check_formal_conditions_for_maximal_order, ) from sympy.polys.polyerrors import GeneratorsNeeded 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.pretty()})') print("I: ", I) print("J: ", J) print(f'Equal: {I == J}') ''' 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 #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_pretty_printing(): d = -7 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)) assert repr(P[0]) == '[ (2, (3*x + 1)/2) e=1, f=1 ]' assert P[0].pretty(field_gen=theta) == '[ (2, (3*theta + 1)/2) e=1, f=1 ]' assert P[0].pretty(field_gen=theta, just_gens=True) == '(2, (3*theta + 1)/2)' def test_PrimeIdeal_reduce_poly(): T = Poly(cyclotomic_poly(7, x)) k = QQ.algebraic_field((T, x)) P = k.primes_above(11) frp = P[0] B = k.integral_basis(fmt='sympy') assert [frp.reduce_poly(b, x) for b in B] == [ 1, x, x ** 2, -5 * x ** 2 - 4 * x + 1, -x ** 2 - x - 5, 4 * x ** 2 - x - 1] Q = k.primes_above(19) frq = Q[0] assert frq.alpha.equiv(0) assert frq.reduce_poly(20*x**2 + 10) == x**2 - 9 raises(GeneratorsNeeded, lambda: frp.reduce_poly(S(1))) raises(NotImplementedError, lambda: frp.reduce_poly(1))
88a3b5d13bee6b55de9ba6b6d88587e120eba457ebf9b33ead7c74dfd51aed80
import warnings from sympy.testing.pytest import (raises, warns, ignore_warnings, warns_deprecated_sympy, Failed) from sympy.utilities.exceptions import sympy_deprecation_warning # Test callables def test_expected_exception_is_silent_callable(): def f(): raise ValueError() raises(ValueError, f) # Under pytest raises will raise Failed rather than AssertionError def test_lack_of_exception_triggers_AssertionError_callable(): try: raises(Exception, lambda: 1 + 1) assert False except Failed as e: assert "DID NOT RAISE" in str(e) def test_unexpected_exception_is_passed_through_callable(): def f(): raise ValueError("some error message") try: raises(TypeError, f) assert False except ValueError as e: assert str(e) == "some error message" # Test with statement def test_expected_exception_is_silent_with(): with raises(ValueError): raise ValueError() def test_lack_of_exception_triggers_AssertionError_with(): try: with raises(Exception): 1 + 1 assert False except Failed as e: assert "DID NOT RAISE" in str(e) def test_unexpected_exception_is_passed_through_with(): try: with raises(TypeError): raise ValueError("some error message") assert False except ValueError as e: assert str(e) == "some error message" # Now we can use raises() instead of try/catch # to test that a specific exception class is raised def test_second_argument_should_be_callable_or_string(): raises(TypeError, lambda: raises("irrelevant", 42)) def test_warns_catches_warning(): with warnings.catch_warnings(record=True) as w: with warns(UserWarning): warnings.warn('this is the warning message') assert len(w) == 0 def test_warns_raises_without_warning(): with raises(Failed): with warns(UserWarning): pass def test_warns_hides_other_warnings(): with raises(RuntimeWarning): with warns(UserWarning): warnings.warn('this is the warning message', UserWarning) warnings.warn('this is the other message', RuntimeWarning) def test_warns_continues_after_warning(): with warnings.catch_warnings(record=True) as w: finished = False with warns(UserWarning): warnings.warn('this is the warning message') finished = True assert finished assert len(w) == 0 def test_warns_many_warnings(): with warns(UserWarning): warnings.warn('this is the warning message', UserWarning) warnings.warn('this is the other warning message', UserWarning) def test_warns_match_matching(): with warnings.catch_warnings(record=True) as w: with warns(UserWarning, match='this is the warning message'): warnings.warn('this is the warning message', UserWarning) assert len(w) == 0 def test_warns_match_non_matching(): with warnings.catch_warnings(record=True) as w: with raises(Failed): with warns(UserWarning, match='this is the warning message'): warnings.warn('this is not the expected warning message', UserWarning) assert len(w) == 0 def _warn_sympy_deprecation(stacklevel=3): sympy_deprecation_warning( "feature", active_deprecations_target="active-deprecations", deprecated_since_version="0.0.0", stacklevel=stacklevel, ) def test_warns_deprecated_sympy_catches_warning(): with warnings.catch_warnings(record=True) as w: with warns_deprecated_sympy(): _warn_sympy_deprecation() assert len(w) == 0 def test_warns_deprecated_sympy_raises_without_warning(): with raises(Failed): with warns_deprecated_sympy(): pass def test_warns_deprecated_sympy_wrong_stacklevel(): with raises(Failed): with warns_deprecated_sympy(): _warn_sympy_deprecation(stacklevel=1) def test_warns_deprecated_sympy_doesnt_hide_other_warnings(): # Unlike pytest's deprecated_call, we should not hide other warnings. with raises(RuntimeWarning): with warns_deprecated_sympy(): _warn_sympy_deprecation() warnings.warn('this is the other message', RuntimeWarning) def test_warns_deprecated_sympy_continues_after_warning(): with warnings.catch_warnings(record=True) as w: finished = False with warns_deprecated_sympy(): _warn_sympy_deprecation() finished = True assert finished assert len(w) == 0 def test_ignore_ignores_warning(): with warnings.catch_warnings(record=True) as w: with ignore_warnings(UserWarning): warnings.warn('this is the warning message') assert len(w) == 0 def test_ignore_does_not_raise_without_warning(): with warnings.catch_warnings(record=True) as w: with ignore_warnings(UserWarning): pass assert len(w) == 0 def test_ignore_allows_other_warnings(): with warnings.catch_warnings(record=True) as w: # This is needed when pytest is run as -Werror # the setting is reverted at the end of the catch_Warnings block. warnings.simplefilter("always") with ignore_warnings(UserWarning): warnings.warn('this is the warning message', UserWarning) warnings.warn('this is the other message', RuntimeWarning) assert len(w) == 1 assert isinstance(w[0].message, RuntimeWarning) assert str(w[0].message) == 'this is the other message' def test_ignore_continues_after_warning(): with warnings.catch_warnings(record=True) as w: finished = False with ignore_warnings(UserWarning): warnings.warn('this is the warning message') finished = True assert finished assert len(w) == 0 def test_ignore_many_warnings(): with warnings.catch_warnings(record=True) as w: # This is needed when pytest is run as -Werror # the setting is reverted at the end of the catch_Warnings block. warnings.simplefilter("always") with ignore_warnings(UserWarning): warnings.warn('this is the warning message', UserWarning) warnings.warn('this is the other message', RuntimeWarning) warnings.warn('this is the warning message', UserWarning) warnings.warn('this is the other message', RuntimeWarning) warnings.warn('this is the other message', RuntimeWarning) assert len(w) == 3 for wi in w: assert isinstance(wi.message, RuntimeWarning) assert str(wi.message) == 'this is the other message'
c10647b38c0336e2b87e568a28bb095ba5d132dad58ccbffe6b50fdd6b2980f0
from sympy.testing.pytest import warns_deprecated_sympy def test_deprecated_testing_randtest(): with warns_deprecated_sympy(): import sympy.testing.randtest # noqa:F401
328f3c2609b2dc2b92433db95921f7e049d94acfc9058ec4f8e28f3b64a384f7
from sympy.core import Rational, S from sympy.simplify import simplify, trigsimp from sympy.core.function import (Derivative, Function, diff) from sympy.core.numbers import pi from sympy.core.symbol import symbols from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import (cos, sin) from sympy.integrals.integrals import Integral from sympy.matrices.immutable import ImmutableDenseMatrix as Matrix from sympy.vector.vector import Vector, BaseVector, VectorAdd, \ VectorMul, VectorZero from sympy.vector.coordsysrect import CoordSys3D from sympy.vector.vector import Cross, Dot, cross from sympy.testing.pytest import raises C = CoordSys3D('C') i, j, k = C.base_vectors() a, b, c = symbols('a b c') def test_cross(): v1 = C.x * i + C.z * C.z * j v2 = C.x * i + C.y * j + C.z * k assert Cross(v1, v2) == Cross(C.x*C.i + C.z**2*C.j, C.x*C.i + C.y*C.j + C.z*C.k) assert Cross(v1, v2).doit() == C.z**3*C.i + (-C.x*C.z)*C.j + (C.x*C.y - C.x*C.z**2)*C.k assert cross(v1, v2) == C.z**3*C.i + (-C.x*C.z)*C.j + (C.x*C.y - C.x*C.z**2)*C.k assert Cross(v1, v2) == -Cross(v2, v1) assert Cross(v1, v2) + Cross(v2, v1) == Vector.zero def test_dot(): v1 = C.x * i + C.z * C.z * j v2 = C.x * i + C.y * j + C.z * k assert Dot(v1, v2) == Dot(C.x*C.i + C.z**2*C.j, C.x*C.i + C.y*C.j + C.z*C.k) assert Dot(v1, v2).doit() == C.x**2 + C.y*C.z**2 assert Dot(v1, v2).doit() == C.x**2 + C.y*C.z**2 assert Dot(v1, v2) == Dot(v2, v1) def test_vector_sympy(): """ Test whether the Vector framework confirms to the hashing and equality testing properties of SymPy. """ v1 = 3*j assert v1 == j*3 assert v1.components == {j: 3} v2 = 3*i + 4*j + 5*k v3 = 2*i + 4*j + i + 4*k + k assert v3 == v2 assert v3.__hash__() == v2.__hash__() def test_vector(): assert isinstance(i, BaseVector) assert i != j assert j != k assert k != i assert i - i == Vector.zero assert i + Vector.zero == i assert i - Vector.zero == i assert Vector.zero != 0 assert -Vector.zero == Vector.zero v1 = a*i + b*j + c*k v2 = a**2*i + b**2*j + c**2*k v3 = v1 + v2 v4 = 2 * v1 v5 = a * i assert isinstance(v1, VectorAdd) assert v1 - v1 == Vector.zero assert v1 + Vector.zero == v1 assert v1.dot(i) == a assert v1.dot(j) == b assert v1.dot(k) == c assert i.dot(v2) == a**2 assert j.dot(v2) == b**2 assert k.dot(v2) == c**2 assert v3.dot(i) == a**2 + a assert v3.dot(j) == b**2 + b assert v3.dot(k) == c**2 + c assert v1 + v2 == v2 + v1 assert v1 - v2 == -1 * (v2 - v1) assert a * v1 == v1 * a assert isinstance(v5, VectorMul) assert v5.base_vector == i assert v5.measure_number == a assert isinstance(v4, Vector) assert isinstance(v4, VectorAdd) assert isinstance(v4, Vector) assert isinstance(Vector.zero, VectorZero) assert isinstance(Vector.zero, Vector) assert isinstance(v1 * 0, VectorZero) assert v1.to_matrix(C) == Matrix([[a], [b], [c]]) assert i.components == {i: 1} assert v5.components == {i: a} assert v1.components == {i: a, j: b, k: c} assert VectorAdd(v1, Vector.zero) == v1 assert VectorMul(a, v1) == v1*a assert VectorMul(1, i) == i assert VectorAdd(v1, Vector.zero) == v1 assert VectorMul(0, Vector.zero) == Vector.zero raises(TypeError, lambda: v1.outer(1)) raises(TypeError, lambda: v1.dot(1)) def test_vector_magnitude_normalize(): assert Vector.zero.magnitude() == 0 assert Vector.zero.normalize() == Vector.zero assert i.magnitude() == 1 assert j.magnitude() == 1 assert k.magnitude() == 1 assert i.normalize() == i assert j.normalize() == j assert k.normalize() == k v1 = a * i assert v1.normalize() == (a/sqrt(a**2))*i assert v1.magnitude() == sqrt(a**2) v2 = a*i + b*j + c*k assert v2.magnitude() == sqrt(a**2 + b**2 + c**2) assert v2.normalize() == v2 / v2.magnitude() v3 = i + j assert v3.normalize() == (sqrt(2)/2)*C.i + (sqrt(2)/2)*C.j def test_vector_simplify(): A, s, k, m = symbols('A, s, k, m') test1 = (1 / a + 1 / b) * i assert (test1 & i) != (a + b) / (a * b) test1 = simplify(test1) assert (test1 & i) == (a + b) / (a * b) assert test1.simplify() == simplify(test1) test2 = (A**2 * s**4 / (4 * pi * k * m**3)) * i test2 = simplify(test2) assert (test2 & i) == (A**2 * s**4 / (4 * pi * k * m**3)) test3 = ((4 + 4 * a - 2 * (2 + 2 * a)) / (2 + 2 * a)) * i test3 = simplify(test3) assert (test3 & i) == 0 test4 = ((-4 * a * b**2 - 2 * b**3 - 2 * a**2 * b) / (a + b)**2) * i test4 = simplify(test4) assert (test4 & i) == -2 * b v = (sin(a)+cos(a))**2*i - j assert trigsimp(v) == (2*sin(a + pi/4)**2)*i + (-1)*j assert trigsimp(v) == v.trigsimp() assert simplify(Vector.zero) == Vector.zero def test_vector_dot(): assert i.dot(Vector.zero) == 0 assert Vector.zero.dot(i) == 0 assert i & Vector.zero == 0 assert i.dot(i) == 1 assert i.dot(j) == 0 assert i.dot(k) == 0 assert i & i == 1 assert i & j == 0 assert i & k == 0 assert j.dot(i) == 0 assert j.dot(j) == 1 assert j.dot(k) == 0 assert j & i == 0 assert j & j == 1 assert j & k == 0 assert k.dot(i) == 0 assert k.dot(j) == 0 assert k.dot(k) == 1 assert k & i == 0 assert k & j == 0 assert k & k == 1 raises(TypeError, lambda: k.dot(1)) def test_vector_cross(): assert i.cross(Vector.zero) == Vector.zero assert Vector.zero.cross(i) == Vector.zero assert i.cross(i) == Vector.zero assert i.cross(j) == k assert i.cross(k) == -j assert i ^ i == Vector.zero assert i ^ j == k assert i ^ k == -j assert j.cross(i) == -k assert j.cross(j) == Vector.zero assert j.cross(k) == i assert j ^ i == -k assert j ^ j == Vector.zero assert j ^ k == i assert k.cross(i) == j assert k.cross(j) == -i assert k.cross(k) == Vector.zero assert k ^ i == j assert k ^ j == -i assert k ^ k == Vector.zero assert k.cross(1) == Cross(k, 1) def test_projection(): v1 = i + j + k v2 = 3*i + 4*j v3 = 0*i + 0*j assert v1.projection(v1) == i + j + k assert v1.projection(v2) == Rational(7, 3)*C.i + Rational(7, 3)*C.j + Rational(7, 3)*C.k assert v1.projection(v1, scalar=True) == S.One assert v1.projection(v2, scalar=True) == Rational(7, 3) assert v3.projection(v1) == Vector.zero assert v3.projection(v1, scalar=True) == S.Zero def test_vector_diff_integrate(): f = Function('f') v = f(a)*C.i + a**2*C.j - C.k assert Derivative(v, a) == Derivative((f(a))*C.i + a**2*C.j + (-1)*C.k, a) assert (diff(v, a) == v.diff(a) == Derivative(v, a).doit() == (Derivative(f(a), a))*C.i + 2*a*C.j) assert (Integral(v, a) == (Integral(f(a), a))*C.i + (Integral(a**2, a))*C.j + (Integral(-1, a))*C.k) def test_vector_args(): raises(ValueError, lambda: BaseVector(3, C)) raises(TypeError, lambda: BaseVector(0, Vector.zero)) def test_srepr(): from sympy.printing.repr import srepr res = "CoordSys3D(Str('C'), Tuple(ImmutableDenseMatrix([[Integer(1), "\ "Integer(0), Integer(0)], [Integer(0), Integer(1), Integer(0)], "\ "[Integer(0), Integer(0), Integer(1)]]), VectorZero())).i" assert srepr(C.i) == res def test_scalar(): from sympy.vector import CoordSys3D C = CoordSys3D('C') v1 = 3*C.i + 4*C.j + 5*C.k v2 = 3*C.i - 4*C.j + 5*C.k assert v1.is_Vector is True assert v1.is_scalar is False assert (v1.dot(v2)).is_scalar is True assert (v1.cross(v2)).is_scalar is False
abd9fd3881bf0a90f8290376d1dcf0459217a0cbfb552829f1f1e65679197ebd
from sympy.testing.pytest import raises from sympy.vector.coordsysrect import CoordSys3D from sympy.vector.scalar import BaseScalar from sympy.core.function import expand from sympy.core.numbers import pi from sympy.core.symbol import symbols from sympy.functions.elementary.hyperbolic import (cosh, sinh) from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import (acos, atan2, cos, sin) from sympy.matrices.dense import zeros from sympy.matrices.immutable import ImmutableDenseMatrix as Matrix from sympy.simplify.simplify import simplify from sympy.vector.functions import express from sympy.vector.point import Point from sympy.vector.vector import Vector from sympy.vector.orienters import (AxisOrienter, BodyOrienter, SpaceOrienter, QuaternionOrienter) x, y, z = symbols('x y z') a, b, c, q = symbols('a b c q') q1, q2, q3, q4 = symbols('q1 q2 q3 q4') def test_func_args(): A = CoordSys3D('A') assert A.x.func(*A.x.args) == A.x expr = 3*A.x + 4*A.y assert expr.func(*expr.args) == expr assert A.i.func(*A.i.args) == A.i v = A.x*A.i + A.y*A.j + A.z*A.k assert v.func(*v.args) == v assert A.origin.func(*A.origin.args) == A.origin def test_coordsys3d_equivalence(): A = CoordSys3D('A') A1 = CoordSys3D('A') assert A1 == A B = CoordSys3D('B') assert A != B def test_orienters(): A = CoordSys3D('A') axis_orienter = AxisOrienter(a, A.k) body_orienter = BodyOrienter(a, b, c, '123') space_orienter = SpaceOrienter(a, b, c, '123') q_orienter = QuaternionOrienter(q1, q2, q3, q4) assert axis_orienter.rotation_matrix(A) == Matrix([ [ cos(a), sin(a), 0], [-sin(a), cos(a), 0], [ 0, 0, 1]]) assert body_orienter.rotation_matrix() == Matrix([ [ cos(b)*cos(c), sin(a)*sin(b)*cos(c) + sin(c)*cos(a), sin(a)*sin(c) - sin(b)*cos(a)*cos(c)], [-sin(c)*cos(b), -sin(a)*sin(b)*sin(c) + cos(a)*cos(c), sin(a)*cos(c) + sin(b)*sin(c)*cos(a)], [ sin(b), -sin(a)*cos(b), cos(a)*cos(b)]]) assert space_orienter.rotation_matrix() == Matrix([ [cos(b)*cos(c), sin(c)*cos(b), -sin(b)], [sin(a)*sin(b)*cos(c) - sin(c)*cos(a), sin(a)*sin(b)*sin(c) + cos(a)*cos(c), sin(a)*cos(b)], [sin(a)*sin(c) + sin(b)*cos(a)*cos(c), -sin(a)*cos(c) + sin(b)*sin(c)*cos(a), cos(a)*cos(b)]]) assert q_orienter.rotation_matrix() == Matrix([ [q1**2 + q2**2 - q3**2 - q4**2, 2*q1*q4 + 2*q2*q3, -2*q1*q3 + 2*q2*q4], [-2*q1*q4 + 2*q2*q3, q1**2 - q2**2 + q3**2 - q4**2, 2*q1*q2 + 2*q3*q4], [2*q1*q3 + 2*q2*q4, -2*q1*q2 + 2*q3*q4, q1**2 - q2**2 - q3**2 + q4**2]]) def test_coordinate_vars(): """ Tests the coordinate variables functionality with respect to reorientation of coordinate systems. """ A = CoordSys3D('A') # Note that the name given on the lhs is different from A.x._name assert BaseScalar(0, A, 'A_x', r'\mathbf{{x}_{A}}') == A.x assert BaseScalar(1, A, 'A_y', r'\mathbf{{y}_{A}}') == A.y assert BaseScalar(2, A, 'A_z', r'\mathbf{{z}_{A}}') == A.z assert BaseScalar(0, A, 'A_x', r'\mathbf{{x}_{A}}').__hash__() == A.x.__hash__() assert isinstance(A.x, BaseScalar) and \ isinstance(A.y, BaseScalar) and \ isinstance(A.z, BaseScalar) assert A.x*A.y == A.y*A.x assert A.scalar_map(A) == {A.x: A.x, A.y: A.y, A.z: A.z} assert A.x.system == A assert A.x.diff(A.x) == 1 B = A.orient_new_axis('B', q, A.k) assert B.scalar_map(A) == {B.z: A.z, B.y: -A.x*sin(q) + A.y*cos(q), B.x: A.x*cos(q) + A.y*sin(q)} assert A.scalar_map(B) == {A.x: B.x*cos(q) - B.y*sin(q), A.y: B.x*sin(q) + B.y*cos(q), A.z: B.z} assert express(B.x, A, variables=True) == A.x*cos(q) + A.y*sin(q) assert express(B.y, A, variables=True) == -A.x*sin(q) + A.y*cos(q) assert express(B.z, A, variables=True) == A.z assert expand(express(B.x*B.y*B.z, A, variables=True)) == \ expand(A.z*(-A.x*sin(q) + A.y*cos(q))*(A.x*cos(q) + A.y*sin(q))) assert express(B.x*B.i + B.y*B.j + B.z*B.k, A) == \ (B.x*cos(q) - B.y*sin(q))*A.i + (B.x*sin(q) + \ B.y*cos(q))*A.j + B.z*A.k assert simplify(express(B.x*B.i + B.y*B.j + B.z*B.k, A, \ variables=True)) == \ A.x*A.i + A.y*A.j + A.z*A.k assert express(A.x*A.i + A.y*A.j + A.z*A.k, B) == \ (A.x*cos(q) + A.y*sin(q))*B.i + \ (-A.x*sin(q) + A.y*cos(q))*B.j + A.z*B.k assert simplify(express(A.x*A.i + A.y*A.j + A.z*A.k, B, \ variables=True)) == \ B.x*B.i + B.y*B.j + B.z*B.k N = B.orient_new_axis('N', -q, B.k) assert N.scalar_map(A) == \ {N.x: A.x, N.z: A.z, N.y: A.y} C = A.orient_new_axis('C', q, A.i + A.j + A.k) mapping = A.scalar_map(C) assert mapping[A.x].equals(C.x*(2*cos(q) + 1)/3 + C.y*(-2*sin(q + pi/6) + 1)/3 + C.z*(-2*cos(q + pi/3) + 1)/3) assert mapping[A.y].equals(C.x*(-2*cos(q + pi/3) + 1)/3 + C.y*(2*cos(q) + 1)/3 + C.z*(-2*sin(q + pi/6) + 1)/3) assert mapping[A.z].equals(C.x*(-2*sin(q + pi/6) + 1)/3 + C.y*(-2*cos(q + pi/3) + 1)/3 + C.z*(2*cos(q) + 1)/3) D = A.locate_new('D', a*A.i + b*A.j + c*A.k) assert D.scalar_map(A) == {D.z: A.z - c, D.x: A.x - a, D.y: A.y - b} E = A.orient_new_axis('E', a, A.k, a*A.i + b*A.j + c*A.k) assert A.scalar_map(E) == {A.z: E.z + c, A.x: E.x*cos(a) - E.y*sin(a) + a, A.y: E.x*sin(a) + E.y*cos(a) + b} assert E.scalar_map(A) == {E.x: (A.x - a)*cos(a) + (A.y - b)*sin(a), E.y: (-A.x + a)*sin(a) + (A.y - b)*cos(a), E.z: A.z - c} F = A.locate_new('F', Vector.zero) assert A.scalar_map(F) == {A.z: F.z, A.x: F.x, A.y: F.y} def test_rotation_matrix(): N = CoordSys3D('N') A = N.orient_new_axis('A', q1, N.k) B = A.orient_new_axis('B', q2, A.i) C = B.orient_new_axis('C', q3, B.j) D = N.orient_new_axis('D', q4, N.j) E = N.orient_new_space('E', q1, q2, q3, '123') F = N.orient_new_quaternion('F', q1, q2, q3, q4) G = N.orient_new_body('G', q1, q2, q3, '123') assert N.rotation_matrix(C) == 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)]]) test_mat = D.rotation_matrix(C) - Matrix( [[cos(q1) * cos(q3) * cos(q4) - sin(q3) * (- sin(q4) * cos(q2) + sin(q1) * sin(q2) * cos(q4)), - sin(q2) * sin(q4) - sin(q1) * cos(q2) * cos(q4), sin(q3) * cos(q1) * cos(q4) + cos(q3) * \ (- sin(q4) * cos(q2) + sin(q1) * sin(q2) * cos(q4))], \ [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(q4) * cos(q1) * cos(q3) - sin(q3) * (cos(q2) * cos(q4) + \ sin(q1) * sin(q2) * \ sin(q4)), sin(q2) * cos(q4) - sin(q1) * sin(q4) * cos(q2), sin(q3) * \ sin(q4) * cos(q1) + cos(q3) * (cos(q2) * cos(q4) + \ sin(q1) * sin(q2) * sin(q4))]]) assert test_mat.expand() == zeros(3, 3) assert E.rotation_matrix(N) == Matrix( [[cos(q2)*cos(q3), sin(q3)*cos(q2), -sin(q2)], [sin(q1)*sin(q2)*cos(q3) - sin(q3)*cos(q1), \ sin(q1)*sin(q2)*sin(q3) + cos(q1)*cos(q3), sin(q1)*cos(q2)], \ [sin(q1)*sin(q3) + sin(q2)*cos(q1)*cos(q3), - \ sin(q1)*cos(q3) + sin(q2)*sin(q3)*cos(q1), cos(q1)*cos(q2)]]) assert F.rotation_matrix(N) == Matrix([[ q1**2 + q2**2 - q3**2 - q4**2, 2*q1*q4 + 2*q2*q3, -2*q1*q3 + 2*q2*q4],[ -2*q1*q4 + 2*q2*q3, q1**2 - q2**2 + q3**2 - q4**2, 2*q1*q2 + 2*q3*q4], [2*q1*q3 + 2*q2*q4, -2*q1*q2 + 2*q3*q4, q1**2 - q2**2 - q3**2 + q4**2]]) assert G.rotation_matrix(N) == Matrix([[ cos(q2)*cos(q3), sin(q1)*sin(q2)*cos(q3) + sin(q3)*cos(q1), sin(q1)*sin(q3) - sin(q2)*cos(q1)*cos(q3)], [ -sin(q3)*cos(q2), -sin(q1)*sin(q2)*sin(q3) + cos(q1)*cos(q3), sin(q1)*cos(q3) + sin(q2)*sin(q3)*cos(q1)],[ sin(q2), -sin(q1)*cos(q2), cos(q1)*cos(q2)]]) def test_vector_with_orientation(): """ Tests the effects of orientation of coordinate systems on basic vector operations. """ N = CoordSys3D('N') A = N.orient_new_axis('A', q1, N.k) B = A.orient_new_axis('B', q2, A.i) C = B.orient_new_axis('C', q3, B.j) # Test to_matrix v1 = a*N.i + b*N.j + c*N.k assert v1.to_matrix(A) == Matrix([[ a*cos(q1) + b*sin(q1)], [-a*sin(q1) + b*cos(q1)], [ c]]) # Test dot assert N.i.dot(A.i) == cos(q1) assert N.i.dot(A.j) == -sin(q1) assert N.i.dot(A.k) == 0 assert N.j.dot(A.i) == sin(q1) assert N.j.dot(A.j) == cos(q1) assert N.j.dot(A.k) == 0 assert N.k.dot(A.i) == 0 assert N.k.dot(A.j) == 0 assert N.k.dot(A.k) == 1 assert N.i.dot(A.i + A.j) == -sin(q1) + cos(q1) == \ (A.i + A.j).dot(N.i) assert A.i.dot(C.i) == cos(q3) assert A.i.dot(C.j) == 0 assert A.i.dot(C.k) == sin(q3) assert A.j.dot(C.i) == sin(q2)*sin(q3) assert A.j.dot(C.j) == cos(q2) assert A.j.dot(C.k) == -sin(q2)*cos(q3) assert A.k.dot(C.i) == -cos(q2)*sin(q3) assert A.k.dot(C.j) == sin(q2) assert A.k.dot(C.k) == cos(q2)*cos(q3) # Test cross assert N.i.cross(A.i) == sin(q1)*A.k assert N.i.cross(A.j) == cos(q1)*A.k assert N.i.cross(A.k) == -sin(q1)*A.i - cos(q1)*A.j assert N.j.cross(A.i) == -cos(q1)*A.k assert N.j.cross(A.j) == sin(q1)*A.k assert N.j.cross(A.k) == cos(q1)*A.i - sin(q1)*A.j assert N.k.cross(A.i) == A.j assert N.k.cross(A.j) == -A.i assert N.k.cross(A.k) == Vector.zero assert N.i.cross(A.i) == sin(q1)*A.k assert N.i.cross(A.j) == cos(q1)*A.k assert N.i.cross(A.i + A.j) == sin(q1)*A.k + cos(q1)*A.k assert (A.i + A.j).cross(N.i) == (-sin(q1) - cos(q1))*N.k assert A.i.cross(C.i) == sin(q3)*C.j assert A.i.cross(C.j) == -sin(q3)*C.i + cos(q3)*C.k assert A.i.cross(C.k) == -cos(q3)*C.j assert C.i.cross(A.i) == (-sin(q3)*cos(q2))*A.j + \ (-sin(q2)*sin(q3))*A.k assert C.j.cross(A.i) == (sin(q2))*A.j + (-cos(q2))*A.k assert express(C.k.cross(A.i), C).trigsimp() == cos(q3)*C.j def test_orient_new_methods(): N = CoordSys3D('N') orienter1 = AxisOrienter(q4, N.j) orienter2 = SpaceOrienter(q1, q2, q3, '123') orienter3 = QuaternionOrienter(q1, q2, q3, q4) orienter4 = BodyOrienter(q1, q2, q3, '123') D = N.orient_new('D', (orienter1, )) E = N.orient_new('E', (orienter2, )) F = N.orient_new('F', (orienter3, )) G = N.orient_new('G', (orienter4, )) assert D == N.orient_new_axis('D', q4, N.j) assert E == N.orient_new_space('E', q1, q2, q3, '123') assert F == N.orient_new_quaternion('F', q1, q2, q3, q4) assert G == N.orient_new_body('G', q1, q2, q3, '123') def test_locatenew_point(): """ Tests Point class, and locate_new method in CoordSys3D. """ A = CoordSys3D('A') assert isinstance(A.origin, Point) v = a*A.i + b*A.j + c*A.k C = A.locate_new('C', v) assert C.origin.position_wrt(A) == \ C.position_wrt(A) == \ C.origin.position_wrt(A.origin) == v assert A.origin.position_wrt(C) == \ A.position_wrt(C) == \ A.origin.position_wrt(C.origin) == -v assert A.origin.express_coordinates(C) == (-a, -b, -c) p = A.origin.locate_new('p', -v) assert p.express_coordinates(A) == (-a, -b, -c) assert p.position_wrt(C.origin) == p.position_wrt(C) == \ -2 * v p1 = p.locate_new('p1', 2*v) assert p1.position_wrt(C.origin) == Vector.zero assert p1.express_coordinates(C) == (0, 0, 0) p2 = p.locate_new('p2', A.i) assert p1.position_wrt(p2) == 2*v - A.i assert p2.express_coordinates(C) == (-2*a + 1, -2*b, -2*c) def test_create_new(): a = CoordSys3D('a') c = a.create_new('c', transformation='spherical') assert c._parent == a assert c.transformation_to_parent() == \ (c.r*sin(c.theta)*cos(c.phi), c.r*sin(c.theta)*sin(c.phi), c.r*cos(c.theta)) assert c.transformation_from_parent() == \ (sqrt(a.x**2 + a.y**2 + a.z**2), acos(a.z/sqrt(a.x**2 + a.y**2 + a.z**2)), atan2(a.y, a.x)) def test_evalf(): A = CoordSys3D('A') v = 3*A.i + 4*A.j + a*A.k assert v.n() == v.evalf() assert v.evalf(subs={a:1}) == v.subs(a, 1).evalf() def test_lame_coefficients(): a = CoordSys3D('a', 'spherical') assert a.lame_coefficients() == (1, a.r, sin(a.theta)*a.r) a = CoordSys3D('a') assert a.lame_coefficients() == (1, 1, 1) a = CoordSys3D('a', 'cartesian') assert a.lame_coefficients() == (1, 1, 1) a = CoordSys3D('a', 'cylindrical') assert a.lame_coefficients() == (1, a.r, 1) def test_transformation_equations(): x, y, z = symbols('x y z') # Str a = CoordSys3D('a', transformation='spherical', variable_names=["r", "theta", "phi"]) r, theta, phi = a.base_scalars() assert r == a.r assert theta == a.theta assert phi == a.phi raises(AttributeError, lambda: a.x) raises(AttributeError, lambda: a.y) raises(AttributeError, lambda: a.z) assert a.transformation_to_parent() == ( r*sin(theta)*cos(phi), r*sin(theta)*sin(phi), r*cos(theta) ) assert a.lame_coefficients() == (1, r, r*sin(theta)) assert a.transformation_from_parent_function()(x, y, z) == ( sqrt(x ** 2 + y ** 2 + z ** 2), acos((z) / sqrt(x**2 + y**2 + z**2)), atan2(y, x) ) a = CoordSys3D('a', transformation='cylindrical', variable_names=["r", "theta", "z"]) r, theta, z = a.base_scalars() assert a.transformation_to_parent() == ( r*cos(theta), r*sin(theta), z ) assert a.lame_coefficients() == (1, a.r, 1) assert a.transformation_from_parent_function()(x, y, z) == (sqrt(x**2 + y**2), atan2(y, x), z) a = CoordSys3D('a', 'cartesian') assert a.transformation_to_parent() == (a.x, a.y, a.z) assert a.lame_coefficients() == (1, 1, 1) assert a.transformation_from_parent_function()(x, y, z) == (x, y, z) # Variables and expressions # Cartesian with equation tuple: x, y, z = symbols('x y z') a = CoordSys3D('a', ((x, y, z), (x, y, z))) a._calculate_inv_trans_equations() assert a.transformation_to_parent() == (a.x1, a.x2, a.x3) assert a.lame_coefficients() == (1, 1, 1) assert a.transformation_from_parent_function()(x, y, z) == (x, y, z) r, theta, z = symbols("r theta z") # Cylindrical with equation tuple: a = CoordSys3D('a', [(r, theta, z), (r*cos(theta), r*sin(theta), z)], variable_names=["r", "theta", "z"]) r, theta, z = a.base_scalars() assert a.transformation_to_parent() == ( r*cos(theta), r*sin(theta), z ) assert a.lame_coefficients() == ( sqrt(sin(theta)**2 + cos(theta)**2), sqrt(r**2*sin(theta)**2 + r**2*cos(theta)**2), 1 ) # ==> this should simplify to (1, r, 1), tests are too slow with `simplify`. # Definitions with `lambda`: # Cartesian with `lambda` a = CoordSys3D('a', lambda x, y, z: (x, y, z)) assert a.transformation_to_parent() == (a.x1, a.x2, a.x3) assert a.lame_coefficients() == (1, 1, 1) a._calculate_inv_trans_equations() assert a.transformation_from_parent_function()(x, y, z) == (x, y, z) # Spherical with `lambda` a = CoordSys3D('a', lambda r, theta, phi: (r*sin(theta)*cos(phi), r*sin(theta)*sin(phi), r*cos(theta)), variable_names=["r", "theta", "phi"]) r, theta, phi = a.base_scalars() assert a.transformation_to_parent() == ( r*sin(theta)*cos(phi), r*sin(phi)*sin(theta), r*cos(theta) ) assert a.lame_coefficients() == ( sqrt(sin(phi)**2*sin(theta)**2 + sin(theta)**2*cos(phi)**2 + cos(theta)**2), sqrt(r**2*sin(phi)**2*cos(theta)**2 + r**2*sin(theta)**2 + r**2*cos(phi)**2*cos(theta)**2), sqrt(r**2*sin(phi)**2*sin(theta)**2 + r**2*sin(theta)**2*cos(phi)**2) ) # ==> this should simplify to (1, r, sin(theta)*r), `simplify` is too slow. # Cylindrical with `lambda` a = CoordSys3D('a', lambda r, theta, z: (r*cos(theta), r*sin(theta), z), variable_names=["r", "theta", "z"] ) r, theta, z = a.base_scalars() assert a.transformation_to_parent() == (r*cos(theta), r*sin(theta), z) assert a.lame_coefficients() == ( sqrt(sin(theta)**2 + cos(theta)**2), sqrt(r**2*sin(theta)**2 + r**2*cos(theta)**2), 1 ) # ==> this should simplify to (1, a.x, 1) raises(TypeError, lambda: CoordSys3D('a', transformation={ x: x*sin(y)*cos(z), y:x*sin(y)*sin(z), z: x*cos(y)})) def test_check_orthogonality(): x, y, z = symbols('x y z') u,v = symbols('u, v') a = CoordSys3D('a', transformation=((x, y, z), (x*sin(y)*cos(z), x*sin(y)*sin(z), x*cos(y)))) assert a._check_orthogonality(a._transformation) is True a = CoordSys3D('a', transformation=((x, y, z), (x * cos(y), x * sin(y), z))) assert a._check_orthogonality(a._transformation) is True a = CoordSys3D('a', transformation=((u, v, z), (cosh(u) * cos(v), sinh(u) * sin(v), z))) assert a._check_orthogonality(a._transformation) is True raises(ValueError, lambda: CoordSys3D('a', transformation=((x, y, z), (x, x, z)))) raises(ValueError, lambda: CoordSys3D('a', transformation=( (x, y, z), (x*sin(y/2)*cos(z), x*sin(y)*sin(z), x*cos(y))))) def test_rotation_trans_equations(): a = CoordSys3D('a') from sympy.core.symbol import symbols q0 = symbols('q0') assert a._rotation_trans_equations(a._parent_rotation_matrix, a.base_scalars()) == (a.x, a.y, a.z) assert a._rotation_trans_equations(a._inverse_rotation_matrix(), a.base_scalars()) == (a.x, a.y, a.z) b = a.orient_new_axis('b', 0, -a.k) assert b._rotation_trans_equations(b._parent_rotation_matrix, b.base_scalars()) == (b.x, b.y, b.z) assert b._rotation_trans_equations(b._inverse_rotation_matrix(), b.base_scalars()) == (b.x, b.y, b.z) c = a.orient_new_axis('c', q0, -a.k) assert c._rotation_trans_equations(c._parent_rotation_matrix, c.base_scalars()) == \ (-sin(q0) * c.y + cos(q0) * c.x, sin(q0) * c.x + cos(q0) * c.y, c.z) assert c._rotation_trans_equations(c._inverse_rotation_matrix(), c.base_scalars()) == \ (sin(q0) * c.y + cos(q0) * c.x, -sin(q0) * c.x + cos(q0) * c.y, c.z)
dc1796e79890e2a5dd7c34c5aa9b44dae7c93c92013b375f218571f389ff1300
# -*- coding: utf-8 -*- from sympy.core.function import Function from sympy.integrals.integrals import Integral from sympy.printing.latex import latex from sympy.printing.pretty import pretty as xpretty from sympy.vector import CoordSys3D, Del, Vector, express from sympy.abc import a, b, c from sympy.testing.pytest import XFAIL def pretty(expr): """ASCII pretty-printing""" return xpretty(expr, use_unicode=False, wrap_line=False) def upretty(expr): """Unicode pretty-printing""" return xpretty(expr, use_unicode=True, wrap_line=False) # Initialize the basic and tedious vector/dyadic expressions # needed for testing. # Some of the pretty forms shown denote how the expressions just # above them should look with pretty printing. N = CoordSys3D('N') C = N.orient_new_axis('C', a, N.k) # type: ignore v = [] d = [] v.append(Vector.zero) v.append(N.i) # type: ignore v.append(-N.i) # type: ignore v.append(N.i + N.j) # type: ignore v.append(a*N.i) # type: ignore v.append(a*N.i - b*N.j) # type: ignore v.append((a**2 + N.x)*N.i + N.k) # type: ignore v.append((a**2 + b)*N.i + 3*(C.y - c)*N.k) # type: ignore f = Function('f') v.append(N.j - (Integral(f(b)) - C.x**2)*N.k) # type: ignore upretty_v_8 = """\ ⎛ 2 ⌠ ⎞ \n\ j_N + ⎜x_C - ⎮ f(b) db⎟ k_N\n\ ⎝ ⌡ ⎠ \ """ pretty_v_8 = """\ j_N + / / \\\n\ | 2 | |\n\ |x_C - | f(b) db|\n\ | | |\n\ \\ / / \ """ v.append(N.i + C.k) # type: ignore v.append(express(N.i, C)) # type: ignore v.append((a**2 + b)*N.i + (Integral(f(b)))*N.k) # type: ignore upretty_v_11 = """\ ⎛ 2 ⎞ ⎛⌠ ⎞ \n\ ⎝a + b⎠ i_N + ⎜⎮ f(b) db⎟ k_N\n\ ⎝⌡ ⎠ \ """ pretty_v_11 = """\ / 2 \\ + / / \\\n\ \\a + b/ i_N| | |\n\ | | f(b) db|\n\ | | |\n\ \\/ / \ """ for x in v: d.append(x | N.k) # type: ignore s = 3*N.x**2*C.y # type: ignore upretty_s = """\ 2\n\ 3⋅y_C⋅x_N \ """ pretty_s = """\ 2\n\ 3*y_C*x_N \ """ # This is the pretty form for ((a**2 + b)*N.i + 3*(C.y - c)*N.k) | N.k upretty_d_7 = """\ ⎛ 2 ⎞ \n\ ⎝a + b⎠ (i_N|k_N) + (3⋅y_C - 3⋅c) (k_N|k_N)\ """ pretty_d_7 = """\ / 2 \\ (i_N|k_N) + (3*y_C - 3*c) (k_N|k_N)\n\ \\a + b/ \ """ def test_str_printing(): assert str(v[0]) == '0' assert str(v[1]) == 'N.i' assert str(v[2]) == '(-1)*N.i' assert str(v[3]) == 'N.i + N.j' assert str(v[8]) == 'N.j + (C.x**2 - Integral(f(b), b))*N.k' assert str(v[9]) == 'C.k + N.i' assert str(s) == '3*C.y*N.x**2' assert str(d[0]) == '0' assert str(d[1]) == '(N.i|N.k)' assert str(d[4]) == 'a*(N.i|N.k)' assert str(d[5]) == 'a*(N.i|N.k) + (-b)*(N.j|N.k)' assert str(d[8]) == ('(N.j|N.k) + (C.x**2 - ' + 'Integral(f(b), b))*(N.k|N.k)') @XFAIL def test_pretty_printing_ascii(): assert pretty(v[0]) == '0' assert pretty(v[1]) == 'i_N' assert pretty(v[5]) == '(a) i_N + (-b) j_N' assert pretty(v[8]) == pretty_v_8 assert pretty(v[2]) == '(-1) i_N' assert pretty(v[11]) == pretty_v_11 assert pretty(s) == pretty_s assert pretty(d[0]) == '(0|0)' assert pretty(d[5]) == '(a) (i_N|k_N) + (-b) (j_N|k_N)' assert pretty(d[7]) == pretty_d_7 assert pretty(d[10]) == '(cos(a)) (i_C|k_N) + (-sin(a)) (j_C|k_N)' def test_pretty_print_unicode_v(): assert upretty(v[0]) == '0' assert upretty(v[1]) == 'i_N' assert upretty(v[5]) == '(a) i_N + (-b) j_N' # Make sure the printing works in other objects assert upretty(v[5].args) == '((a) i_N, (-b) j_N)' assert upretty(v[8]) == upretty_v_8 assert upretty(v[2]) == '(-1) i_N' assert upretty(v[11]) == upretty_v_11 assert upretty(s) == upretty_s assert upretty(d[0]) == '(0|0)' assert upretty(d[5]) == '(a) (i_N|k_N) + (-b) (j_N|k_N)' assert upretty(d[7]) == upretty_d_7 assert upretty(d[10]) == '(cos(a)) (i_C|k_N) + (-sin(a)) (j_C|k_N)' def test_latex_printing(): assert latex(v[0]) == '\\mathbf{\\hat{0}}' assert latex(v[1]) == '\\mathbf{\\hat{i}_{N}}' assert latex(v[2]) == '- \\mathbf{\\hat{i}_{N}}' assert latex(v[5]) == ('\\left(a\\right)\\mathbf{\\hat{i}_{N}} + ' + '\\left(- b\\right)\\mathbf{\\hat{j}_{N}}') assert latex(v[6]) == ('\\left(\\mathbf{{x}_{N}} + a^{2}\\right)\\mathbf{\\hat{i}_' + '{N}} + \\mathbf{\\hat{k}_{N}}') assert latex(v[8]) == ('\\mathbf{\\hat{j}_{N}} + \\left(\\mathbf{{x}_' + '{C}}^{2} - \\int f{\\left(b \\right)}\\,' + ' db\\right)\\mathbf{\\hat{k}_{N}}') assert latex(s) == '3 \\mathbf{{y}_{C}} \\mathbf{{x}_{N}}^{2}' assert latex(d[0]) == '(\\mathbf{\\hat{0}}|\\mathbf{\\hat{0}})' assert latex(d[4]) == ('\\left(a\\right)\\left(\\mathbf{\\hat{i}_{N}}{\\middle|}' + '\\mathbf{\\hat{k}_{N}}\\right)') assert latex(d[9]) == ('\\left(\\mathbf{\\hat{k}_{C}}{\\middle|}' + '\\mathbf{\\hat{k}_{N}}\\right) + \\left(' + '\\mathbf{\\hat{i}_{N}}{\\middle|}\\mathbf{' + '\\hat{k}_{N}}\\right)') assert latex(d[11]) == ('\\left(a^{2} + b\\right)\\left(\\mathbf{\\hat{i}_{N}}' + '{\\middle|}\\mathbf{\\hat{k}_{N}}\\right) + ' + '\\left(\\int f{\\left(b \\right)}\\, db\\right)\\left(' + '\\mathbf{\\hat{k}_{N}}{\\middle|}\\mathbf{' + '\\hat{k}_{N}}\\right)') def test_issue_23058(): from sympy import symbols, sin, cos, pi, UnevaluatedExpr delop = Del() CC_ = CoordSys3D("C") y = CC_.y xhat = CC_.i t = symbols("t") ten = symbols("10", positive=True) eps, mu = 4*pi*ten**(-11), ten**(-5) Bx = 2 * ten**(-4) * cos(ten**5 * t) * sin(ten**(-3) * y) vecB = Bx * xhat vecE = (1/eps) * Integral(delop.cross(vecB/mu).doit(), t) vecE = vecE.doit() vecB_str = """\ ⎛ ⎛y_C⎞ ⎛ 5 ⎞⎞ \n\ ⎜2⋅sin⎜───⎟⋅cos⎝10 ⋅t⎠⎟ i_C\n\ ⎜ ⎜ 3⎟ ⎟ \n\ ⎜ ⎝10 ⎠ ⎟ \n\ ⎜─────────────────────⎟ \n\ ⎜ 4 ⎟ \n\ ⎝ 10 ⎠ \ """ vecE_str = """\ ⎛ 4 ⎛ 5 ⎞ ⎛y_C⎞ ⎞ \n\ ⎜-10 ⋅sin⎝10 ⋅t⎠⋅cos⎜───⎟ ⎟ k_C\n\ ⎜ ⎜ 3⎟ ⎟ \n\ ⎜ ⎝10 ⎠ ⎟ \n\ ⎜─────────────────────────⎟ \n\ ⎝ 2⋅π ⎠ \ """ assert upretty(vecB) == vecB_str assert upretty(vecE) == vecE_str ten = UnevaluatedExpr(10) eps, mu = 4*pi*ten**(-11), ten**(-5) Bx = 2 * ten**(-4) * cos(ten**5 * t) * sin(ten**(-3) * y) vecB = Bx * xhat vecB_str = """\ ⎛ -4 ⎛ 5⎞ ⎛ -3⎞⎞ \n\ ⎝2⋅10 ⋅cos⎝t⋅10 ⎠⋅sin⎝y_C⋅10 ⎠⎠ i_C \ """ assert upretty(vecB) == vecB_str def test_custom_names(): A = CoordSys3D('A', vector_names=['x', 'y', 'z'], variable_names=['i', 'j', 'k']) assert A.i.__str__() == 'A.i' assert A.x.__str__() == 'A.x' assert A.i._pretty_form == 'i_A' assert A.x._pretty_form == 'x_A' assert A.i._latex_form == r'\mathbf{{i}_{A}}' assert A.x._latex_form == r"\mathbf{\hat{x}_{A}}"
712c7fc95b45a30495441d8ab86c9e35fb19e9cb0490798b9193765a641c434d
from sympy.core.numbers import (Float, Rational, oo, pi) from sympy.core.relational import Eq from sympy.core.singleton import S from sympy.core.symbol import (Symbol, symbols) from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import (acos, cos, sin) from sympy.sets import EmptySet from sympy.simplify.simplify import simplify from sympy.functions.elementary.trigonometric import tan from sympy.geometry import (Circle, GeometryError, Line, Point, Ray, Segment, Triangle, intersection, Point3D, Line3D, Ray3D, Segment3D, Point2D, Line2D) from sympy.geometry.line import Undecidable from sympy.geometry.polygon import _asa as asa from sympy.utilities.iterables import cartes from sympy.testing.pytest import raises, warns, warns_deprecated_sympy x = Symbol('x', real=True) y = Symbol('y', real=True) z = Symbol('z', real=True) k = Symbol('k', real=True) x1 = Symbol('x1', real=True) y1 = Symbol('y1', real=True) t = Symbol('t', real=True) a, b = symbols('a,b', real=True) m = symbols('m', real=True) def test_object_from_equation(): from sympy.abc import x, y, a, b assert Line(3*x + y + 18) == Line2D(Point2D(0, -18), Point2D(1, -21)) assert Line(3*x + 5 * y + 1) == Line2D( Point2D(0, Rational(-1, 5)), Point2D(1, Rational(-4, 5))) assert Line(3*a + b + 18, x="a", y="b") == Line2D( Point2D(0, -18), Point2D(1, -21)) assert Line(3*x + y) == Line2D(Point2D(0, 0), Point2D(1, -3)) assert Line(x + y) == Line2D(Point2D(0, 0), Point2D(1, -1)) assert Line(Eq(3*a + b, -18), x="a", y=b) == Line2D( Point2D(0, -18), Point2D(1, -21)) # issue 22361 assert Line(x - 1) == Line2D(Point2D(1, 0), Point2D(1, 1)) assert Line(2*x - 2, y=x) == Line2D(Point2D(0, 1), Point2D(1, 1)) assert Line(y) == Line2D(Point2D(0, 0), Point2D(1, 0)) assert Line(2*y, x=y) == Line2D(Point2D(0, 0), Point2D(0, 1)) assert Line(y, x=y) == Line2D(Point2D(0, 0), Point2D(0, 1)) raises(ValueError, lambda: Line(x / y)) raises(ValueError, lambda: Line(a / b, x='a', y='b')) raises(ValueError, lambda: Line(y / x)) raises(ValueError, lambda: Line(b / a, x='a', y='b')) raises(ValueError, lambda: Line((x + 1)**2 + y)) def feq(a, b): """Test if two floating point values are 'equal'.""" t_float = Float("1.0E-10") return -t_float < a - b < t_float def test_angle_between(): a = Point(1, 2, 3, 4) b = a.orthogonal_direction o = a.origin assert feq(Line.angle_between(Line(Point(0, 0), Point(1, 1)), Line(Point(0, 0), Point(5, 0))).evalf(), pi.evalf() / 4) assert Line(a, o).angle_between(Line(b, o)) == pi / 2 z = Point3D(0, 0, 0) assert Line3D.angle_between(Line3D(z, Point3D(1, 1, 1)), Line3D(z, Point3D(5, 0, 0))) == acos(sqrt(3) / 3) # direction of points is used to determine angle assert Line3D.angle_between(Line3D(z, Point3D(1, 1, 1)), Line3D(Point3D(5, 0, 0), z)) == acos(-sqrt(3) / 3) def test_closing_angle(): a = Ray((0, 0), angle=0) b = Ray((1, 2), angle=pi/2) assert a.closing_angle(b) == -pi/2 assert b.closing_angle(a) == pi/2 assert a.closing_angle(a) == 0 def test_smallest_angle(): a = Line(Point(1, 1), Point(1, 2)) b = Line(Point(1, 1),Point(2, 3)) assert a.smallest_angle_between(b) == acos(2*sqrt(5)/5) def test_svg(): a = Line(Point(1, 1),Point(1, 2)) assert a._svg() == '<path fill-rule="evenodd" fill="#66cc99" stroke="#555555" stroke-width="2.0" opacity="0.6" d="M 1.00000000000000,1.00000000000000 L 1.00000000000000,2.00000000000000" marker-start="url(#markerReverseArrow)" marker-end="url(#markerArrow)"/>' a = Segment(Point(1, 0),Point(1, 1)) assert a._svg() == '<path fill-rule="evenodd" fill="#66cc99" stroke="#555555" stroke-width="2.0" opacity="0.6" d="M 1.00000000000000,0 L 1.00000000000000,1.00000000000000" />' a = Ray(Point(2, 3), Point(3, 5)) assert a._svg() == '<path fill-rule="evenodd" fill="#66cc99" stroke="#555555" stroke-width="2.0" opacity="0.6" d="M 2.00000000000000,3.00000000000000 L 3.00000000000000,5.00000000000000" marker-start="url(#markerCircle)" marker-end="url(#markerArrow)"/>' def test_arbitrary_point(): l1 = Line3D(Point3D(0, 0, 0), Point3D(1, 1, 1)) l2 = Line(Point(x1, x1), Point(y1, y1)) assert l2.arbitrary_point() in l2 assert Ray((1, 1), angle=pi / 4).arbitrary_point() == \ Point(t + 1, t + 1) assert Segment((1, 1), (2, 3)).arbitrary_point() == Point(1 + t, 1 + 2 * t) assert l1.perpendicular_segment(l1.arbitrary_point()) == l1.arbitrary_point() assert Ray3D((1, 1, 1), direction_ratio=[1, 2, 3]).arbitrary_point() == \ Point3D(t + 1, 2 * t + 1, 3 * t + 1) assert Segment3D(Point3D(0, 0, 0), Point3D(1, 1, 1)).midpoint == \ Point3D(S.Half, S.Half, S.Half) assert Segment3D(Point3D(x1, x1, x1), Point3D(y1, y1, y1)).length == sqrt(3) * sqrt((x1 - y1) ** 2) assert Segment3D((1, 1, 1), (2, 3, 4)).arbitrary_point() == \ Point3D(t + 1, 2 * t + 1, 3 * t + 1) raises(ValueError, (lambda: Line((x, 1), (2, 3)).arbitrary_point(x))) def test_are_concurrent_2d(): l1 = Line(Point(0, 0), Point(1, 1)) l2 = Line(Point(x1, x1), Point(x1, 1 + x1)) assert Line.are_concurrent(l1) is False assert Line.are_concurrent(l1, l2) assert Line.are_concurrent(l1, l1, l1, l2) assert Line.are_concurrent(l1, l2, Line(Point(5, x1), Point(Rational(-3, 5), x1))) assert Line.are_concurrent(l1, Line(Point(0, 0), Point(-x1, x1)), l2) is False def test_are_concurrent_3d(): p1 = Point3D(0, 0, 0) l1 = Line(p1, Point3D(1, 1, 1)) parallel_1 = Line3D(Point3D(0, 0, 0), Point3D(1, 0, 0)) parallel_2 = Line3D(Point3D(0, 1, 0), Point3D(1, 1, 0)) assert Line3D.are_concurrent(l1) is False assert Line3D.are_concurrent(l1, Line(Point3D(x1, x1, x1), Point3D(y1, y1, y1))) is False assert Line3D.are_concurrent(l1, Line3D(p1, Point3D(x1, x1, x1)), Line(Point3D(x1, x1, x1), Point3D(x1, 1 + x1, 1))) is True assert Line3D.are_concurrent(parallel_1, parallel_2) is False def test_arguments(): """Functions accepting `Point` objects in `geometry` should also accept tuples, lists, and generators and automatically convert them to points.""" from sympy.utilities.iterables import subsets singles2d = ((1, 2), [1, 3], Point(1, 5)) doubles2d = subsets(singles2d, 2) l2d = Line(Point2D(1, 2), Point2D(2, 3)) singles3d = ((1, 2, 3), [1, 2, 4], Point(1, 2, 6)) doubles3d = subsets(singles3d, 2) l3d = Line(Point3D(1, 2, 3), Point3D(1, 1, 2)) singles4d = ((1, 2, 3, 4), [1, 2, 3, 5], Point(1, 2, 3, 7)) doubles4d = subsets(singles4d, 2) l4d = Line(Point(1, 2, 3, 4), Point(2, 2, 2, 2)) # test 2D test_single = ['contains', 'distance', 'equals', 'parallel_line', 'perpendicular_line', 'perpendicular_segment', 'projection', 'intersection'] for p in doubles2d: Line2D(*p) for func in test_single: for p in singles2d: getattr(l2d, func)(p) # test 3D for p in doubles3d: Line3D(*p) for func in test_single: for p in singles3d: getattr(l3d, func)(p) # test 4D for p in doubles4d: Line(*p) for func in test_single: for p in singles4d: getattr(l4d, func)(p) def test_basic_properties_2d(): p1 = Point(0, 0) p2 = Point(1, 1) p10 = Point(2000, 2000) p_r3 = Ray(p1, p2).random_point() p_r4 = Ray(p2, p1).random_point() l1 = Line(p1, p2) l3 = Line(Point(x1, x1), Point(x1, 1 + x1)) l4 = Line(p1, Point(1, 0)) r1 = Ray(p1, Point(0, 1)) r2 = Ray(Point(0, 1), p1) s1 = Segment(p1, p10) p_s1 = s1.random_point() assert Line((1, 1), slope=1) == Line((1, 1), (2, 2)) assert Line((1, 1), slope=oo) == Line((1, 1), (1, 2)) assert Line((1, 1), slope=oo).bounds == (1, 1, 1, 2) assert Line((1, 1), slope=-oo) == Line((1, 1), (1, 2)) assert Line(p1, p2).scale(2, 1) == Line(p1, Point(2, 1)) assert Line(p1, p2) == Line(p1, p2) assert Line(p1, p2) != Line(p2, p1) assert l1 != Line(Point(x1, x1), Point(y1, y1)) assert l1 != l3 assert Line(p1, p10) != Line(p10, p1) assert Line(p1, p10) != p1 assert p1 in l1 # is p1 on the line l1? assert p1 not in l3 assert s1 in Line(p1, p10) assert Ray(Point(0, 0), Point(0, 1)) in Ray(Point(0, 0), Point(0, 2)) assert Ray(Point(0, 0), Point(0, 2)) in Ray(Point(0, 0), Point(0, 1)) assert Ray(Point(0, 0), Point(0, 2)).xdirection == S.Zero assert Ray(Point(0, 0), Point(1, 2)).xdirection == S.Infinity assert Ray(Point(0, 0), Point(-1, 2)).xdirection == S.NegativeInfinity assert Ray(Point(0, 0), Point(2, 0)).ydirection == S.Zero assert Ray(Point(0, 0), Point(2, 2)).ydirection == S.Infinity assert Ray(Point(0, 0), Point(2, -2)).ydirection == S.NegativeInfinity assert (r1 in s1) is False assert Segment(p1, p2) in s1 assert Ray(Point(x1, x1), Point(x1, 1 + x1)) != Ray(p1, Point(-1, 5)) assert Segment(p1, p2).midpoint == Point(S.Half, S.Half) assert Segment(p1, Point(-x1, x1)).length == sqrt(2 * (x1 ** 2)) assert l1.slope == 1 assert l3.slope is oo assert l4.slope == 0 assert Line(p1, Point(0, 1)).slope is oo assert Line(r1.source, r1.random_point()).slope == r1.slope assert Line(r2.source, r2.random_point()).slope == r2.slope assert Segment(Point(0, -1), Segment(p1, Point(0, 1)).random_point()).slope == Segment(p1, Point(0, 1)).slope assert l4.coefficients == (0, 1, 0) assert Line((-x, x), (-x + 1, x - 1)).coefficients == (1, 1, 0) assert Line(p1, Point(0, 1)).coefficients == (1, 0, 0) # issue 7963 r = Ray((0, 0), angle=x) assert r.subs(x, 3 * pi / 4) == Ray((0, 0), (-1, 1)) assert r.subs(x, 5 * pi / 4) == Ray((0, 0), (-1, -1)) assert r.subs(x, -pi / 4) == Ray((0, 0), (1, -1)) assert r.subs(x, pi / 2) == Ray((0, 0), (0, 1)) assert r.subs(x, -pi / 2) == Ray((0, 0), (0, -1)) for ind in range(0, 5): assert l3.random_point() in l3 assert p_r3.x >= p1.x and p_r3.y >= p1.y assert p_r4.x <= p2.x and p_r4.y <= p2.y assert p1.x <= p_s1.x <= p10.x and p1.y <= p_s1.y <= p10.y assert hash(s1) != hash(Segment(p10, p1)) assert s1.plot_interval() == [t, 0, 1] assert Line(p1, p10).plot_interval() == [t, -5, 5] assert Ray((0, 0), angle=pi / 4).plot_interval() == [t, 0, 10] def test_basic_properties_3d(): p1 = Point3D(0, 0, 0) p2 = Point3D(1, 1, 1) p3 = Point3D(x1, x1, x1) p5 = Point3D(x1, 1 + x1, 1) l1 = Line3D(p1, p2) l3 = Line3D(p3, p5) r1 = Ray3D(p1, Point3D(-1, 5, 0)) r3 = Ray3D(p1, p2) s1 = Segment3D(p1, p2) assert Line3D((1, 1, 1), direction_ratio=[2, 3, 4]) == Line3D(Point3D(1, 1, 1), Point3D(3, 4, 5)) assert Line3D((1, 1, 1), direction_ratio=[1, 5, 7]) == Line3D(Point3D(1, 1, 1), Point3D(2, 6, 8)) assert Line3D((1, 1, 1), direction_ratio=[1, 2, 3]) == Line3D(Point3D(1, 1, 1), Point3D(2, 3, 4)) assert Line3D(Point3D(0, 0, 0), Point3D(1, 0, 0)).direction_cosine == [1, 0, 0] assert Line3D(Line3D(p1, Point3D(0, 1, 0))) == Line3D(p1, Point3D(0, 1, 0)) assert Ray3D(Line3D(Point3D(0, 0, 0), Point3D(1, 0, 0))) == Ray3D(p1, Point3D(1, 0, 0)) assert Line3D(p1, p2) != Line3D(p2, p1) assert l1 != l3 assert l1 != Line3D(p3, Point3D(y1, y1, y1)) assert r3 != r1 assert Ray3D(Point3D(0, 0, 0), Point3D(1, 1, 1)) in Ray3D(Point3D(0, 0, 0), Point3D(2, 2, 2)) assert Ray3D(Point3D(0, 0, 0), Point3D(2, 2, 2)) in Ray3D(Point3D(0, 0, 0), Point3D(1, 1, 1)) assert Ray3D(Point3D(0, 0, 0), Point3D(2, 2, 2)).xdirection == S.Infinity assert Ray3D(Point3D(0, 0, 0), Point3D(2, 2, 2)).ydirection == S.Infinity assert Ray3D(Point3D(0, 0, 0), Point3D(2, 2, 2)).zdirection == S.Infinity assert Ray3D(Point3D(0, 0, 0), Point3D(-2, 2, 2)).xdirection == S.NegativeInfinity assert Ray3D(Point3D(0, 0, 0), Point3D(2, -2, 2)).ydirection == S.NegativeInfinity assert Ray3D(Point3D(0, 0, 0), Point3D(2, 2, -2)).zdirection == S.NegativeInfinity assert Ray3D(Point3D(0, 0, 0), Point3D(0, 2, 2)).xdirection == S.Zero assert Ray3D(Point3D(0, 0, 0), Point3D(2, 0, 2)).ydirection == S.Zero assert Ray3D(Point3D(0, 0, 0), Point3D(2, 2, 0)).zdirection == S.Zero assert p1 in l1 assert p1 not in l3 assert l1.direction_ratio == [1, 1, 1] assert s1.midpoint == Point3D(S.Half, S.Half, S.Half) # Test zdirection assert Ray3D(p1, Point3D(0, 0, -1)).zdirection is S.NegativeInfinity def test_contains(): p1 = Point(0, 0) r = Ray(p1, Point(4, 4)) r1 = Ray3D(p1, Point3D(0, 0, -1)) r2 = Ray3D(p1, Point3D(0, 1, 0)) r3 = Ray3D(p1, Point3D(0, 0, 1)) l = Line(Point(0, 1), Point(3, 4)) # Segment contains assert Point(0, (a + b) / 2) in Segment((0, a), (0, b)) assert Point((a + b) / 2, 0) in Segment((a, 0), (b, 0)) assert Point3D(0, 1, 0) in Segment3D((0, 1, 0), (0, 1, 0)) assert Point3D(1, 0, 0) in Segment3D((1, 0, 0), (1, 0, 0)) assert Segment3D(Point3D(0, 0, 0), Point3D(1, 0, 0)).contains([]) is True assert Segment3D(Point3D(0, 0, 0), Point3D(1, 0, 0)).contains( Segment3D(Point3D(2, 2, 2), Point3D(3, 2, 2))) is False # Line contains assert l.contains(Point(0, 1)) is True assert l.contains((0, 1)) is True assert l.contains((0, 0)) is False # Ray contains assert r.contains(p1) is True assert r.contains((1, 1)) is True assert r.contains((1, 3)) is False assert r.contains(Segment((1, 1), (2, 2))) is True assert r.contains(Segment((1, 2), (2, 5))) is False assert r.contains(Ray((2, 2), (3, 3))) is True assert r.contains(Ray((2, 2), (3, 5))) is False assert r1.contains(Segment3D(p1, Point3D(0, 0, -10))) is True assert r1.contains(Segment3D(Point3D(1, 1, 1), Point3D(2, 2, 2))) is False assert r2.contains(Point3D(0, 0, 0)) is True assert r3.contains(Point3D(0, 0, 0)) is True assert Ray3D(Point3D(1, 1, 1), Point3D(1, 0, 0)).contains([]) is False assert Line3D((0, 0, 0), (x, y, z)).contains((2 * x, 2 * y, 2 * z)) with warns(UserWarning, test_stacklevel=False): assert Line3D(p1, Point3D(0, 1, 0)).contains(Point(1.0, 1.0)) is False with warns(UserWarning, test_stacklevel=False): assert r3.contains(Point(1.0, 1.0)) is False def test_contains_nonreal_symbols(): u, v, w, z = symbols('u, v, w, z') l = Segment(Point(u, w), Point(v, z)) p = Point(u*Rational(2, 3) + v/3, w*Rational(2, 3) + z/3) assert l.contains(p) def test_distance_2d(): p1 = Point(0, 0) p2 = Point(1, 1) half = S.Half s1 = Segment(Point(0, 0), Point(1, 1)) s2 = Segment(Point(half, half), Point(1, 0)) r = Ray(p1, p2) assert s1.distance(Point(0, 0)) == 0 assert s1.distance((0, 0)) == 0 assert s2.distance(Point(0, 0)) == 2 ** half / 2 assert s2.distance(Point(Rational(3) / 2, Rational(3) / 2)) == 2 ** half assert Line(p1, p2).distance(Point(-1, 1)) == sqrt(2) assert Line(p1, p2).distance(Point(1, -1)) == sqrt(2) assert Line(p1, p2).distance(Point(2, 2)) == 0 assert Line(p1, p2).distance((-1, 1)) == sqrt(2) assert Line((0, 0), (0, 1)).distance(p1) == 0 assert Line((0, 0), (0, 1)).distance(p2) == 1 assert Line((0, 0), (1, 0)).distance(p1) == 0 assert Line((0, 0), (1, 0)).distance(p2) == 1 assert r.distance(Point(-1, -1)) == sqrt(2) assert r.distance(Point(1, 1)) == 0 assert r.distance(Point(-1, 1)) == sqrt(2) assert Ray((1, 1), (2, 2)).distance(Point(1.5, 3)) == 3 * sqrt(2) / 4 assert r.distance((1, 1)) == 0 def test_dimension_normalization(): with warns(UserWarning, test_stacklevel=False): assert Ray((1, 1), (2, 1, 2)) == Ray((1, 1, 0), (2, 1, 2)) def test_distance_3d(): p1, p2 = Point3D(0, 0, 0), Point3D(1, 1, 1) p3 = Point3D(Rational(3) / 2, Rational(3) / 2, Rational(3) / 2) s1 = Segment3D(Point3D(0, 0, 0), Point3D(1, 1, 1)) s2 = Segment3D(Point3D(S.Half, S.Half, S.Half), Point3D(1, 0, 1)) r = Ray3D(p1, p2) assert s1.distance(p1) == 0 assert s2.distance(p1) == sqrt(3) / 2 assert s2.distance(p3) == 2 * sqrt(6) / 3 assert s1.distance((0, 0, 0)) == 0 assert s2.distance((0, 0, 0)) == sqrt(3) / 2 assert s1.distance(p1) == 0 assert s2.distance(p1) == sqrt(3) / 2 assert s2.distance(p3) == 2 * sqrt(6) / 3 assert s1.distance((0, 0, 0)) == 0 assert s2.distance((0, 0, 0)) == sqrt(3) / 2 # Line to point assert Line3D(p1, p2).distance(Point3D(-1, 1, 1)) == 2 * sqrt(6) / 3 assert Line3D(p1, p2).distance(Point3D(1, -1, 1)) == 2 * sqrt(6) / 3 assert Line3D(p1, p2).distance(Point3D(2, 2, 2)) == 0 assert Line3D(p1, p2).distance((2, 2, 2)) == 0 assert Line3D(p1, p2).distance((1, -1, 1)) == 2 * sqrt(6) / 3 assert Line3D((0, 0, 0), (0, 1, 0)).distance(p1) == 0 assert Line3D((0, 0, 0), (0, 1, 0)).distance(p2) == sqrt(2) assert Line3D((0, 0, 0), (1, 0, 0)).distance(p1) == 0 assert Line3D((0, 0, 0), (1, 0, 0)).distance(p2) == sqrt(2) # Ray to point assert r.distance(Point3D(-1, -1, -1)) == sqrt(3) assert r.distance(Point3D(1, 1, 1)) == 0 assert r.distance((-1, -1, -1)) == sqrt(3) assert r.distance((1, 1, 1)) == 0 assert Ray3D((0, 0, 0), (1, 1, 2)).distance((-1, -1, 2)) == 4 * sqrt(3) / 3 assert Ray3D((1, 1, 1), (2, 2, 2)).distance(Point3D(1.5, -3, -1)) == Rational(9) / 2 assert Ray3D((1, 1, 1), (2, 2, 2)).distance(Point3D(1.5, 3, 1)) == sqrt(78) / 6 def test_equals(): p1 = Point(0, 0) p2 = Point(1, 1) l1 = Line(p1, p2) l2 = Line((0, 5), slope=m) l3 = Line(Point(x1, x1), Point(x1, 1 + x1)) assert l1.perpendicular_line(p1.args).equals(Line(Point(0, 0), Point(1, -1))) assert l1.perpendicular_line(p1).equals(Line(Point(0, 0), Point(1, -1))) assert Line(Point(x1, x1), Point(y1, y1)).parallel_line(Point(-x1, x1)). \ equals(Line(Point(-x1, x1), Point(-y1, 2 * x1 - y1))) assert l3.parallel_line(p1.args).equals(Line(Point(0, 0), Point(0, -1))) assert l3.parallel_line(p1).equals(Line(Point(0, 0), Point(0, -1))) assert (l2.distance(Point(2, 3)) - 2 * abs(m + 1) / sqrt(m ** 2 + 1)).equals(0) assert Line3D(p1, Point3D(0, 1, 0)).equals(Point(1.0, 1.0)) is False assert Line3D(Point3D(0, 0, 0), Point3D(1, 0, 0)).equals(Line3D(Point3D(-5, 0, 0), Point3D(-1, 0, 0))) is True assert Line3D(Point3D(0, 0, 0), Point3D(1, 0, 0)).equals(Line3D(p1, Point3D(0, 1, 0))) is False assert Ray3D(p1, Point3D(0, 0, -1)).equals(Point(1.0, 1.0)) is False assert Ray3D(p1, Point3D(0, 0, -1)).equals(Ray3D(p1, Point3D(0, 0, -1))) is True assert Line3D((0, 0), (t, t)).perpendicular_line(Point(0, 1, 0)).equals( Line3D(Point3D(0, 1, 0), Point3D(S.Half, S.Half, 0))) assert Line3D((0, 0), (t, t)).perpendicular_segment(Point(0, 1, 0)).equals(Segment3D((0, 1), (S.Half, S.Half))) assert Line3D(p1, Point3D(0, 1, 0)).equals(Point(1.0, 1.0)) is False def test_equation(): p1 = Point(0, 0) p2 = Point(1, 1) l1 = Line(p1, p2) l3 = Line(Point(x1, x1), Point(x1, 1 + x1)) assert simplify(l1.equation()) in (x - y, y - x) assert simplify(l3.equation()) in (x - x1, x1 - x) assert simplify(l1.equation()) in (x - y, y - x) assert simplify(l3.equation()) in (x - x1, x1 - x) assert Line(p1, Point(1, 0)).equation(x=x, y=y) == y assert Line(p1, Point(0, 1)).equation() == x assert Line(Point(2, 0), Point(2, 1)).equation() == x - 2 assert Line(p2, Point(2, 1)).equation() == y - 1 assert Line3D(Point(x1, x1, x1), Point(y1, y1, y1) ).equation() == (-x + y, -x + z) assert Line3D(Point(1, 2, 3), Point(2, 3, 4) ).equation() == (-x + y - 1, -x + z - 2) assert Line3D(Point(1, 2, 3), Point(1, 3, 4) ).equation() == (x - 1, -y + z - 1) assert Line3D(Point(1, 2, 3), Point(2, 2, 4) ).equation() == (y - 2, -x + z - 2) assert Line3D(Point(1, 2, 3), Point(2, 3, 3) ).equation() == (-x + y - 1, z - 3) assert Line3D(Point(1, 2, 3), Point(1, 2, 4) ).equation() == (x - 1, y - 2) assert Line3D(Point(1, 2, 3), Point(1, 3, 3) ).equation() == (x - 1, z - 3) assert Line3D(Point(1, 2, 3), Point(2, 2, 3) ).equation() == (y - 2, z - 3) with warns_deprecated_sympy(): assert Line3D(Point(1, 2, 3), Point(2, 2, 3) ).equation(k='k') == (y - 2, z - 3) def test_intersection_2d(): p1 = Point(0, 0) p2 = Point(1, 1) p3 = Point(x1, x1) p4 = Point(y1, y1) l1 = Line(p1, p2) l3 = Line(Point(0, 0), Point(3, 4)) r1 = Ray(Point(1, 1), Point(2, 2)) r2 = Ray(Point(0, 0), Point(3, 4)) r4 = Ray(p1, p2) r6 = Ray(Point(0, 1), Point(1, 2)) r7 = Ray(Point(0.5, 0.5), Point(1, 1)) s1 = Segment(p1, p2) s2 = Segment(Point(0.25, 0.25), Point(0.5, 0.5)) s3 = Segment(Point(0, 0), Point(3, 4)) assert intersection(l1, p1) == [p1] assert intersection(l1, Point(x1, 1 + x1)) == [] assert intersection(l1, Line(p3, p4)) in [[l1], [Line(p3, p4)]] assert intersection(l1, l1.parallel_line(Point(x1, 1 + x1))) == [] assert intersection(l3, l3) == [l3] assert intersection(l3, r2) == [r2] assert intersection(l3, s3) == [s3] assert intersection(s3, l3) == [s3] assert intersection(Segment(Point(-10, 10), Point(10, 10)), Segment(Point(-5, -5), Point(-5, 5))) == [] assert intersection(r2, l3) == [r2] assert intersection(r1, Ray(Point(2, 2), Point(0, 0))) == [Segment(Point(1, 1), Point(2, 2))] assert intersection(r1, Ray(Point(1, 1), Point(-1, -1))) == [Point(1, 1)] assert intersection(r1, Segment(Point(0, 0), Point(2, 2))) == [Segment(Point(1, 1), Point(2, 2))] assert r4.intersection(s2) == [s2] assert r4.intersection(Segment(Point(2, 3), Point(3, 4))) == [] assert r4.intersection(Segment(Point(-1, -1), Point(0.5, 0.5))) == [Segment(p1, Point(0.5, 0.5))] assert r4.intersection(Ray(p2, p1)) == [s1] assert Ray(p2, p1).intersection(r6) == [] assert r4.intersection(r7) == r7.intersection(r4) == [r7] assert Ray3D((0, 0), (3, 0)).intersection(Ray3D((1, 0), (3, 0))) == [Ray3D((1, 0), (3, 0))] assert Ray3D((1, 0), (3, 0)).intersection(Ray3D((0, 0), (3, 0))) == [Ray3D((1, 0), (3, 0))] assert Ray(Point(0, 0), Point(0, 4)).intersection(Ray(Point(0, 1), Point(0, -1))) == \ [Segment(Point(0, 0), Point(0, 1))] assert Segment3D((0, 0), (3, 0)).intersection( Segment3D((1, 0), (2, 0))) == [Segment3D((1, 0), (2, 0))] assert Segment3D((1, 0), (2, 0)).intersection( Segment3D((0, 0), (3, 0))) == [Segment3D((1, 0), (2, 0))] assert Segment3D((0, 0), (3, 0)).intersection( Segment3D((3, 0), (4, 0))) == [Point3D((3, 0))] assert Segment3D((0, 0), (3, 0)).intersection( Segment3D((2, 0), (5, 0))) == [Segment3D((2, 0), (3, 0))] assert Segment3D((0, 0), (3, 0)).intersection( Segment3D((-2, 0), (1, 0))) == [Segment3D((0, 0), (1, 0))] assert Segment3D((0, 0), (3, 0)).intersection( Segment3D((-2, 0), (0, 0))) == [Point3D(0, 0)] assert s1.intersection(Segment(Point(1, 1), Point(2, 2))) == [Point(1, 1)] assert s1.intersection(Segment(Point(0.5, 0.5), Point(1.5, 1.5))) == [Segment(Point(0.5, 0.5), p2)] assert s1.intersection(Segment(Point(4, 4), Point(5, 5))) == [] assert s1.intersection(Segment(Point(-1, -1), p1)) == [p1] assert s1.intersection(Segment(Point(-1, -1), Point(0.5, 0.5))) == [Segment(p1, Point(0.5, 0.5))] assert s1.intersection(Line(Point(1, 0), Point(2, 1))) == [] assert s1.intersection(s2) == [s2] assert s2.intersection(s1) == [s2] assert asa(120, 8, 52) == \ Triangle( Point(0, 0), Point(8, 0), Point(-4 * cos(19 * pi / 90) / sin(2 * pi / 45), 4 * sqrt(3) * cos(19 * pi / 90) / sin(2 * pi / 45))) assert Line((0, 0), (1, 1)).intersection(Ray((1, 0), (1, 2))) == [Point(1, 1)] assert Line((0, 0), (1, 1)).intersection(Segment((1, 0), (1, 2))) == [Point(1, 1)] assert Ray((0, 0), (1, 1)).intersection(Ray((1, 0), (1, 2))) == [Point(1, 1)] assert Ray((0, 0), (1, 1)).intersection(Segment((1, 0), (1, 2))) == [Point(1, 1)] assert Ray((0, 0), (10, 10)).contains(Segment((1, 1), (2, 2))) is True assert Segment((1, 1), (2, 2)) in Line((0, 0), (10, 10)) assert s1.intersection(Ray((1, 1), (4, 4))) == [Point(1, 1)] # This test is disabled because it hangs after rref changes which simplify # intermediate results and return a different representation from when the # test was written. # # 16628 - this should be fast # p0 = Point2D(Rational(249, 5), Rational(497999, 10000)) # p1 = Point2D((-58977084786*sqrt(405639795226) + 2030690077184193 + # 20112207807*sqrt(630547164901) + 99600*sqrt(255775022850776494562626)) # /(2000*sqrt(255775022850776494562626) + 1991998000*sqrt(405639795226) # + 1991998000*sqrt(630547164901) + 1622561172902000), # (-498000*sqrt(255775022850776494562626) - 995999*sqrt(630547164901) + # 90004251917891999 + # 496005510002*sqrt(405639795226))/(10000*sqrt(255775022850776494562626) # + 9959990000*sqrt(405639795226) + 9959990000*sqrt(630547164901) + # 8112805864510000)) # p2 = Point2D(Rational(497, 10), Rational(-497, 10)) # p3 = Point2D(Rational(-497, 10), Rational(-497, 10)) # l = Line(p0, p1) # s = Segment(p2, p3) # n = (-52673223862*sqrt(405639795226) - 15764156209307469 - # 9803028531*sqrt(630547164901) + # 33200*sqrt(255775022850776494562626)) # d = sqrt(405639795226) + 315274080450 + 498000*sqrt( # 630547164901) + sqrt(255775022850776494562626) # assert intersection(l, s) == [ # Point2D(n/d*Rational(3, 2000), Rational(-497, 10))] def test_line_intersection(): # see also test_issue_11238 in test_matrices.py x0 = tan(pi*Rational(13, 45)) x1 = sqrt(3) x2 = x0**2 x, y = [8*x0/(x0 + x1), (24*x0 - 8*x1*x2)/(x2 - 3)] assert Line(Point(0, 0), Point(1, -sqrt(3))).contains(Point(x, y)) is True def test_intersection_3d(): p1 = Point3D(0, 0, 0) p2 = Point3D(1, 1, 1) l1 = Line3D(p1, p2) l2 = Line3D(Point3D(0, 0, 0), Point3D(3, 4, 0)) r1 = Ray3D(Point3D(1, 1, 1), Point3D(2, 2, 2)) r2 = Ray3D(Point3D(0, 0, 0), Point3D(3, 4, 0)) s1 = Segment3D(Point3D(0, 0, 0), Point3D(3, 4, 0)) assert intersection(l1, p1) == [p1] assert intersection(l1, Point3D(x1, 1 + x1, 1)) == [] assert intersection(l1, l1.parallel_line(p1)) == [Line3D(Point3D(0, 0, 0), Point3D(1, 1, 1))] assert intersection(l2, r2) == [r2] assert intersection(l2, s1) == [s1] assert intersection(r2, l2) == [r2] assert intersection(r1, Ray3D(Point3D(1, 1, 1), Point3D(-1, -1, -1))) == [Point3D(1, 1, 1)] assert intersection(r1, Segment3D(Point3D(0, 0, 0), Point3D(2, 2, 2))) == [ Segment3D(Point3D(1, 1, 1), Point3D(2, 2, 2))] assert intersection(Ray3D(Point3D(1, 0, 0), Point3D(-1, 0, 0)), Ray3D(Point3D(0, 1, 0), Point3D(0, -1, 0))) \ == [Point3D(0, 0, 0)] assert intersection(r1, Ray3D(Point3D(2, 2, 2), Point3D(0, 0, 0))) == \ [Segment3D(Point3D(1, 1, 1), Point3D(2, 2, 2))] assert intersection(s1, r2) == [s1] assert Line3D(Point3D(4, 0, 1), Point3D(0, 4, 1)).intersection(Line3D(Point3D(0, 0, 1), Point3D(4, 4, 1))) == \ [Point3D(2, 2, 1)] assert Line3D((0, 1, 2), (0, 2, 3)).intersection(Line3D((0, 1, 2), (0, 1, 1))) == [Point3D(0, 1, 2)] assert Line3D((0, 0), (t, t)).intersection(Line3D((0, 1), (t, t))) == \ [Point3D(t, t)] assert Ray3D(Point3D(0, 0, 0), Point3D(0, 4, 0)).intersection(Ray3D(Point3D(0, 1, 1), Point3D(0, -1, 1))) == [] def test_is_parallel(): p1 = Point3D(0, 0, 0) p2 = Point3D(1, 1, 1) p3 = Point3D(x1, x1, x1) l2 = Line(Point(x1, x1), Point(y1, y1)) l2_1 = Line(Point(x1, x1), Point(x1, 1 + x1)) assert Line.is_parallel(Line(Point(0, 0), Point(1, 1)), l2) assert Line.is_parallel(l2, Line(Point(x1, x1), Point(x1, 1 + x1))) is False assert Line.is_parallel(l2, l2.parallel_line(Point(-x1, x1))) assert Line.is_parallel(l2_1, l2_1.parallel_line(Point(0, 0))) assert Line3D(p1, p2).is_parallel(Line3D(p1, p2)) # same as in 2D assert Line3D(Point3D(4, 0, 1), Point3D(0, 4, 1)).is_parallel(Line3D(Point3D(0, 0, 1), Point3D(4, 4, 1))) is False assert Line3D(p1, p2).parallel_line(p3) == Line3D(Point3D(x1, x1, x1), Point3D(x1 + 1, x1 + 1, x1 + 1)) assert Line3D(p1, p2).parallel_line(p3.args) == \ Line3D(Point3D(x1, x1, x1), Point3D(x1 + 1, x1 + 1, x1 + 1)) assert Line3D(Point3D(4, 0, 1), Point3D(0, 4, 1)).is_parallel(Line3D(Point3D(0, 0, 1), Point3D(4, 4, 1))) is False def test_is_perpendicular(): p1 = Point(0, 0) p2 = Point(1, 1) l1 = Line(p1, p2) l2 = Line(Point(x1, x1), Point(y1, y1)) l1_1 = Line(p1, Point(-x1, x1)) # 2D assert Line.is_perpendicular(l1, l1_1) assert Line.is_perpendicular(l1, l2) is False p = l1.random_point() assert l1.perpendicular_segment(p) == p # 3D assert Line3D.is_perpendicular(Line3D(Point3D(0, 0, 0), Point3D(1, 0, 0)), Line3D(Point3D(0, 0, 0), Point3D(0, 1, 0))) is True assert Line3D.is_perpendicular(Line3D(Point3D(0, 0, 0), Point3D(1, 0, 0)), Line3D(Point3D(0, 1, 0), Point3D(1, 1, 0))) is False assert Line3D.is_perpendicular(Line3D(Point3D(0, 0, 0), Point3D(1, 1, 1)), Line3D(Point3D(x1, x1, x1), Point3D(y1, y1, y1))) is False def test_is_similar(): p1 = Point(2000, 2000) p2 = p1.scale(2, 2) r1 = Ray3D(Point3D(1, 1, 1), Point3D(1, 0, 0)) r2 = Ray(Point(0, 0), Point(0, 1)) s1 = Segment(Point(0, 0), p1) assert s1.is_similar(Segment(p1, p2)) assert s1.is_similar(r2) is False assert r1.is_similar(Line3D(Point3D(1, 1, 1), Point3D(1, 0, 0))) is True assert r1.is_similar(Line3D(Point3D(0, 0, 0), Point3D(0, 1, 0))) is False def test_length(): s2 = Segment3D(Point3D(x1, x1, x1), Point3D(y1, y1, y1)) assert Line(Point(0, 0), Point(1, 1)).length is oo assert s2.length == sqrt(3) * sqrt((x1 - y1) ** 2) assert Line3D(Point3D(0, 0, 0), Point3D(1, 1, 1)).length is oo def test_projection(): p1 = Point(0, 0) p2 = Point3D(0, 0, 0) p3 = Point(-x1, x1) l1 = Line(p1, Point(1, 1)) l2 = Line3D(Point3D(0, 0, 0), Point3D(1, 0, 0)) l3 = Line3D(p2, Point3D(1, 1, 1)) r1 = Ray(Point(1, 1), Point(2, 2)) s1 = Segment(Point2D(0, 0), Point2D(0, 1)) s2 = Segment(Point2D(1, 0), Point2D(2, 1/2)) assert Line(Point(x1, x1), Point(y1, y1)).projection(Point(y1, y1)) == Point(y1, y1) assert Line(Point(x1, x1), Point(x1, 1 + x1)).projection(Point(1, 1)) == Point(x1, 1) assert Segment(Point(-2, 2), Point(0, 4)).projection(r1) == Segment(Point(-1, 3), Point(0, 4)) assert Segment(Point(0, 4), Point(-2, 2)).projection(r1) == Segment(Point(0, 4), Point(-1, 3)) assert s2.projection(s1) == EmptySet assert l1.projection(p3) == p1 assert l1.projection(Ray(p1, Point(-1, 5))) == Ray(Point(0, 0), Point(2, 2)) assert l1.projection(Ray(p1, Point(-1, 1))) == p1 assert r1.projection(Ray(Point(1, 1), Point(-1, -1))) == Point(1, 1) assert r1.projection(Ray(Point(0, 4), Point(-1, -5))) == Segment(Point(1, 1), Point(2, 2)) assert r1.projection(Segment(Point(-1, 5), Point(-5, -10))) == Segment(Point(1, 1), Point(2, 2)) assert r1.projection(Ray(Point(1, 1), Point(-1, -1))) == Point(1, 1) assert r1.projection(Ray(Point(0, 4), Point(-1, -5))) == Segment(Point(1, 1), Point(2, 2)) assert r1.projection(Segment(Point(-1, 5), Point(-5, -10))) == Segment(Point(1, 1), Point(2, 2)) assert l3.projection(Ray3D(p2, Point3D(-1, 5, 0))) == Ray3D(Point3D(0, 0, 0), Point3D(Rational(4, 3), Rational(4, 3), Rational(4, 3))) assert l3.projection(Ray3D(p2, Point3D(-1, 1, 1))) == Ray3D(Point3D(0, 0, 0), Point3D(Rational(1, 3), Rational(1, 3), Rational(1, 3))) assert l2.projection(Point3D(5, 5, 0)) == Point3D(5, 0) assert l2.projection(Line3D(Point3D(0, 1, 0), Point3D(1, 1, 0))).equals(l2) def test_perpendicular_line(): # 3d - requires a particular orthogonal to be selected p1, p2, p3 = Point(0, 0, 0), Point(2, 3, 4), Point(-2, 2, 0) l = Line(p1, p2) p = l.perpendicular_line(p3) assert p.p1 == p3 assert p.p2 in l # 2d - does not require special selection p1, p2, p3 = Point(0, 0), Point(2, 3), Point(-2, 2) l = Line(p1, p2) p = l.perpendicular_line(p3) assert p.p1 == p3 # p is directed from l to p3 assert p.direction.unit == (p3 - l.projection(p3)).unit def test_perpendicular_bisector(): s1 = Segment(Point(0, 0), Point(1, 1)) aline = Line(Point(S.Half, S.Half), Point(Rational(3, 2), Rational(-1, 2))) on_line = Segment(Point(S.Half, S.Half), Point(Rational(3, 2), Rational(-1, 2))).midpoint assert s1.perpendicular_bisector().equals(aline) assert s1.perpendicular_bisector(on_line).equals(Segment(s1.midpoint, on_line)) assert s1.perpendicular_bisector(on_line + (1, 0)).equals(aline) def test_raises(): d, e = symbols('a,b', real=True) s = Segment((d, 0), (e, 0)) raises(TypeError, lambda: Line((1, 1), 1)) raises(ValueError, lambda: Line(Point(0, 0), Point(0, 0))) raises(Undecidable, lambda: Point(2 * d, 0) in s) raises(ValueError, lambda: Ray3D(Point(1.0, 1.0))) raises(ValueError, lambda: Line3D(Point3D(0, 0, 0), Point3D(0, 0, 0))) raises(TypeError, lambda: Line3D((1, 1), 1)) raises(ValueError, lambda: Line3D(Point3D(0, 0, 0))) raises(TypeError, lambda: Ray((1, 1), 1)) raises(GeometryError, lambda: Line(Point(0, 0), Point(1, 0)) .projection(Circle(Point(0, 0), 1))) def test_ray_generation(): assert Ray((1, 1), angle=pi / 4) == Ray((1, 1), (2, 2)) assert Ray((1, 1), angle=pi / 2) == Ray((1, 1), (1, 2)) assert Ray((1, 1), angle=-pi / 2) == Ray((1, 1), (1, 0)) assert Ray((1, 1), angle=-3 * pi / 2) == Ray((1, 1), (1, 2)) assert Ray((1, 1), angle=5 * pi / 2) == Ray((1, 1), (1, 2)) assert Ray((1, 1), angle=5.0 * pi / 2) == Ray((1, 1), (1, 2)) assert Ray((1, 1), angle=pi) == Ray((1, 1), (0, 1)) assert Ray((1, 1), angle=3.0 * pi) == Ray((1, 1), (0, 1)) assert Ray((1, 1), angle=4.0 * pi) == Ray((1, 1), (2, 1)) assert Ray((1, 1), angle=0) == Ray((1, 1), (2, 1)) assert Ray((1, 1), angle=4.05 * pi) == Ray(Point(1, 1), Point(2, -sqrt(5) * sqrt(2 * sqrt(5) + 10) / 4 - sqrt( 2 * sqrt(5) + 10) / 4 + 2 + sqrt(5))) assert Ray((1, 1), angle=4.02 * pi) == Ray(Point(1, 1), Point(2, 1 + tan(4.02 * pi))) assert Ray((1, 1), angle=5) == Ray((1, 1), (2, 1 + tan(5))) assert Ray3D((1, 1, 1), direction_ratio=[4, 4, 4]) == Ray3D(Point3D(1, 1, 1), Point3D(5, 5, 5)) assert Ray3D((1, 1, 1), direction_ratio=[1, 2, 3]) == Ray3D(Point3D(1, 1, 1), Point3D(2, 3, 4)) assert Ray3D((1, 1, 1), direction_ratio=[1, 1, 1]) == Ray3D(Point3D(1, 1, 1), Point3D(2, 2, 2)) def test_symbolic_intersect(): # Issue 7814. circle = Circle(Point(x, 0), y) line = Line(Point(k, z), slope=0) assert line.intersection(circle) == [Point(x + sqrt((y - z) * (y + z)), z), Point(x - sqrt((y - z) * (y + z)), z)] def test_issue_2941(): def _check(): for f, g in cartes(*[(Line, Ray, Segment)] * 2): l1 = f(a, b) l2 = g(c, d) assert l1.intersection(l2) == l2.intersection(l1) # intersect at end point c, d = (-2, -2), (-2, 0) a, b = (0, 0), (1, 1) _check() # midline intersection c, d = (-2, -3), (-2, 0) _check() def test_parameter_value(): t = Symbol('t') p1, p2 = Point(0, 1), Point(5, 6) l = Line(p1, p2) assert l.parameter_value((5, 6), t) == {t: 1} raises(ValueError, lambda: l.parameter_value((0, 0), t)) def test_bisectors(): r1 = Line3D(Point3D(0, 0, 0), Point3D(1, 0, 0)) r2 = Line3D(Point3D(0, 0, 0), Point3D(0, 1, 0)) bisections = r1.bisectors(r2) assert bisections == [Line3D(Point3D(0, 0, 0), Point3D(1, 1, 0)), Line3D(Point3D(0, 0, 0), Point3D(1, -1, 0))] ans = [Line3D(Point3D(0, 0, 0), Point3D(1, 0, 1)), Line3D(Point3D(0, 0, 0), Point3D(-1, 0, 1))] l1 = (0, 0, 0), (0, 0, 1) l2 = (0, 0), (1, 0) for a, b in cartes((Line, Segment, Ray), repeat=2): assert a(*l1).bisectors(b(*l2)) == ans def test_issue_8615(): a = Line3D(Point3D(6, 5, 0), Point3D(6, -6, 0)) b = Line3D(Point3D(6, -1, 19/10), Point3D(6, -1, 0)) assert a.intersection(b) == [Point3D(6, -1, 0)] def test_issue_12598(): r1 = Ray(Point(0, 1), Point(0.98, 0.79).n(2)) r2 = Ray(Point(0, 0), Point(0.71, 0.71).n(2)) assert str(r1.intersection(r2)[0]) == 'Point2D(0.82, 0.82)' l1 = Line((0, 0), (1, 1)) l2 = Segment((-1, 1), (0, -1)).n(2) assert str(l1.intersection(l2)[0]) == 'Point2D(-0.33, -0.33)' l2 = Segment((-1, 1), (-1/2, 1/2)).n(2) assert not l1.intersection(l2)
69db29c50f447680904f0a7904563d612fa986e6843690042307fef62c366155
from sympy.core.basic import Basic from sympy.core.numbers import (I, Rational, pi) from sympy.core.parameters import evaluate from sympy.core.singleton import S from sympy.core.symbol import Symbol from sympy.core.sympify import sympify from sympy.functions.elementary.miscellaneous import sqrt from sympy.geometry import Line, Point, Point2D, Point3D, Line3D, Plane from sympy.geometry.entity import rotate, scale, translate, GeometryEntity from sympy.matrices import Matrix from sympy.utilities.iterables import subsets, permutations, cartes from sympy.utilities.misc import Undecidable from sympy.testing.pytest import raises, warns def test_point(): x = Symbol('x', real=True) y = Symbol('y', real=True) x1 = Symbol('x1', real=True) x2 = Symbol('x2', real=True) y1 = Symbol('y1', real=True) y2 = Symbol('y2', real=True) half = S.Half p1 = Point(x1, x2) p2 = Point(y1, y2) p3 = Point(0, 0) p4 = Point(1, 1) p5 = Point(0, 1) line = Line(Point(1, 0), slope=1) assert p1 in p1 assert p1 not in p2 assert p2.y == y2 assert (p3 + p4) == p4 assert (p2 - p1) == Point(y1 - x1, y2 - x2) assert -p2 == Point(-y1, -y2) raises(TypeError, lambda: Point(1)) raises(ValueError, lambda: Point([1])) raises(ValueError, lambda: Point(3, I)) raises(ValueError, lambda: Point(2*I, I)) raises(ValueError, lambda: Point(3 + I, I)) assert Point(34.05, sqrt(3)) == Point(Rational(681, 20), sqrt(3)) assert Point.midpoint(p3, p4) == Point(half, half) assert Point.midpoint(p1, p4) == Point(half + half*x1, half + half*x2) assert Point.midpoint(p2, p2) == p2 assert p2.midpoint(p2) == p2 assert p1.origin == Point(0, 0) assert Point.distance(p3, p4) == sqrt(2) assert Point.distance(p1, p1) == 0 assert Point.distance(p3, p2) == sqrt(p2.x**2 + p2.y**2) raises(TypeError, lambda: Point.distance(p1, 0)) raises(TypeError, lambda: Point.distance(p1, GeometryEntity())) # distance should be symmetric assert p1.distance(line) == line.distance(p1) assert p4.distance(line) == line.distance(p4) assert Point.taxicab_distance(p4, p3) == 2 assert Point.canberra_distance(p4, p5) == 1 raises(ValueError, lambda: Point.canberra_distance(p3, p3)) p1_1 = Point(x1, x1) p1_2 = Point(y2, y2) p1_3 = Point(x1 + 1, x1) assert Point.is_collinear(p3) with warns(UserWarning, test_stacklevel=False): assert Point.is_collinear(p3, Point(p3, dim=4)) assert p3.is_collinear() assert Point.is_collinear(p3, p4) assert Point.is_collinear(p3, p4, p1_1, p1_2) assert Point.is_collinear(p3, p4, p1_1, p1_3) is False assert Point.is_collinear(p3, p3, p4, p5) is False raises(TypeError, lambda: Point.is_collinear(line)) raises(TypeError, lambda: p1_1.is_collinear(line)) assert p3.intersection(Point(0, 0)) == [p3] assert p3.intersection(p4) == [] assert p3.intersection(line) == [] with warns(UserWarning, test_stacklevel=False): assert Point.intersection(Point(0, 0, 0), Point(0, 0)) == [Point(0, 0, 0)] x_pos = Symbol('x', positive=True) p2_1 = Point(x_pos, 0) p2_2 = Point(0, x_pos) p2_3 = Point(-x_pos, 0) p2_4 = Point(0, -x_pos) p2_5 = Point(x_pos, 5) assert Point.is_concyclic(p2_1) assert Point.is_concyclic(p2_1, p2_2) assert Point.is_concyclic(p2_1, p2_2, p2_3, p2_4) for pts in permutations((p2_1, p2_2, p2_3, p2_5)): assert Point.is_concyclic(*pts) is False assert Point.is_concyclic(p4, p4 * 2, p4 * 3) is False assert Point(0, 0).is_concyclic((1, 1), (2, 2), (2, 1)) is False assert Point.is_concyclic(Point(0, 0, 0, 0), Point(1, 0, 0, 0), Point(1, 1, 0, 0), Point(1, 1, 1, 0)) is False assert p1.is_scalar_multiple(p1) assert p1.is_scalar_multiple(2*p1) assert not p1.is_scalar_multiple(p2) assert Point.is_scalar_multiple(Point(1, 1), (-1, -1)) assert Point.is_scalar_multiple(Point(0, 0), (0, -1)) # test when is_scalar_multiple can't be determined raises(Undecidable, lambda: Point.is_scalar_multiple(Point(sympify("x1%y1"), sympify("x2%y2")), Point(0, 1))) assert Point(0, 1).orthogonal_direction == Point(1, 0) assert Point(1, 0).orthogonal_direction == Point(0, 1) assert p1.is_zero is None assert p3.is_zero assert p4.is_zero is False assert p1.is_nonzero is None assert p3.is_nonzero is False assert p4.is_nonzero assert p4.scale(2, 3) == Point(2, 3) assert p3.scale(2, 3) == p3 assert p4.rotate(pi, Point(0.5, 0.5)) == p3 assert p1.__radd__(p2) == p1.midpoint(p2).scale(2, 2) assert (-p3).__rsub__(p4) == p3.midpoint(p4).scale(2, 2) assert p4 * 5 == Point(5, 5) assert p4 / 5 == Point(0.2, 0.2) assert 5 * p4 == Point(5, 5) raises(ValueError, lambda: Point(0, 0) + 10) # Point differences should be simplified assert Point(x*(x - 1), y) - Point(x**2 - x, y + 1) == Point(0, -1) a, b = S.Half, Rational(1, 3) assert Point(a, b).evalf(2) == \ Point(a.n(2), b.n(2), evaluate=False) raises(ValueError, lambda: Point(1, 2) + 1) # test project assert Point.project((0, 1), (1, 0)) == Point(0, 0) assert Point.project((1, 1), (1, 0)) == Point(1, 0) raises(ValueError, lambda: Point.project(p1, Point(0, 0))) # test transformations p = Point(1, 0) assert p.rotate(pi/2) == Point(0, 1) assert p.rotate(pi/2, p) == p p = Point(1, 1) assert p.scale(2, 3) == Point(2, 3) assert p.translate(1, 2) == Point(2, 3) assert p.translate(1) == Point(2, 1) assert p.translate(y=1) == Point(1, 2) assert p.translate(*p.args) == Point(2, 2) # Check invalid input for transform raises(ValueError, lambda: p3.transform(p3)) raises(ValueError, lambda: p.transform(Matrix([[1, 0], [0, 1]]))) # test __contains__ assert 0 in Point(0, 0, 0, 0) assert 1 not in Point(0, 0, 0, 0) # test affine_rank assert Point.affine_rank() == -1 def test_point3D(): x = Symbol('x', real=True) y = Symbol('y', real=True) x1 = Symbol('x1', real=True) x2 = Symbol('x2', real=True) x3 = Symbol('x3', real=True) y1 = Symbol('y1', real=True) y2 = Symbol('y2', real=True) y3 = Symbol('y3', real=True) half = S.Half p1 = Point3D(x1, x2, x3) p2 = Point3D(y1, y2, y3) p3 = Point3D(0, 0, 0) p4 = Point3D(1, 1, 1) p5 = Point3D(0, 1, 2) assert p1 in p1 assert p1 not in p2 assert p2.y == y2 assert (p3 + p4) == p4 assert (p2 - p1) == Point3D(y1 - x1, y2 - x2, y3 - x3) assert -p2 == Point3D(-y1, -y2, -y3) assert Point(34.05, sqrt(3)) == Point(Rational(681, 20), sqrt(3)) assert Point3D.midpoint(p3, p4) == Point3D(half, half, half) assert Point3D.midpoint(p1, p4) == Point3D(half + half*x1, half + half*x2, half + half*x3) assert Point3D.midpoint(p2, p2) == p2 assert p2.midpoint(p2) == p2 assert Point3D.distance(p3, p4) == sqrt(3) assert Point3D.distance(p1, p1) == 0 assert Point3D.distance(p3, p2) == sqrt(p2.x**2 + p2.y**2 + p2.z**2) p1_1 = Point3D(x1, x1, x1) p1_2 = Point3D(y2, y2, y2) p1_3 = Point3D(x1 + 1, x1, x1) Point3D.are_collinear(p3) assert Point3D.are_collinear(p3, p4) assert Point3D.are_collinear(p3, p4, p1_1, p1_2) assert Point3D.are_collinear(p3, p4, p1_1, p1_3) is False assert Point3D.are_collinear(p3, p3, p4, p5) is False assert p3.intersection(Point3D(0, 0, 0)) == [p3] assert p3.intersection(p4) == [] assert p4 * 5 == Point3D(5, 5, 5) assert p4 / 5 == Point3D(0.2, 0.2, 0.2) assert 5 * p4 == Point3D(5, 5, 5) raises(ValueError, lambda: Point3D(0, 0, 0) + 10) # Test coordinate properties assert p1.coordinates == (x1, x2, x3) assert p2.coordinates == (y1, y2, y3) assert p3.coordinates == (0, 0, 0) assert p4.coordinates == (1, 1, 1) assert p5.coordinates == (0, 1, 2) assert p5.x == 0 assert p5.y == 1 assert p5.z == 2 # Point differences should be simplified assert Point3D(x*(x - 1), y, 2) - Point3D(x**2 - x, y + 1, 1) == \ Point3D(0, -1, 1) a, b, c = S.Half, Rational(1, 3), Rational(1, 4) assert Point3D(a, b, c).evalf(2) == \ Point(a.n(2), b.n(2), c.n(2), evaluate=False) raises(ValueError, lambda: Point3D(1, 2, 3) + 1) # test transformations p = Point3D(1, 1, 1) assert p.scale(2, 3) == Point3D(2, 3, 1) assert p.translate(1, 2) == Point3D(2, 3, 1) assert p.translate(1) == Point3D(2, 1, 1) assert p.translate(z=1) == Point3D(1, 1, 2) assert p.translate(*p.args) == Point3D(2, 2, 2) # Test __new__ assert Point3D(0.1, 0.2, evaluate=False, on_morph='ignore').args[0].is_Float # Test length property returns correctly assert p.length == 0 assert p1_1.length == 0 assert p1_2.length == 0 # Test are_colinear type error raises(TypeError, lambda: Point3D.are_collinear(p, x)) # Test are_coplanar assert Point.are_coplanar() assert Point.are_coplanar((1, 2, 0), (1, 2, 0), (1, 3, 0)) assert Point.are_coplanar((1, 2, 0), (1, 2, 3)) with warns(UserWarning, test_stacklevel=False): raises(ValueError, lambda: Point2D.are_coplanar((1, 2), (1, 2, 3))) assert Point3D.are_coplanar((1, 2, 0), (1, 2, 3)) assert Point.are_coplanar((0, 0, 0), (1, 1, 0), (1, 1, 1), (1, 2, 1)) is False planar2 = Point3D(1, -1, 1) planar3 = Point3D(-1, 1, 1) assert Point3D.are_coplanar(p, planar2, planar3) == True assert Point3D.are_coplanar(p, planar2, planar3, p3) == False assert Point.are_coplanar(p, planar2) planar2 = Point3D(1, 1, 2) planar3 = Point3D(1, 1, 3) assert Point3D.are_coplanar(p, planar2, planar3) # line, not plane plane = Plane((1, 2, 1), (2, 1, 0), (3, 1, 2)) assert Point.are_coplanar(*[plane.projection(((-1)**i, i)) for i in range(4)]) # all 2D points are coplanar assert Point.are_coplanar(Point(x, y), Point(x, x + y), Point(y, x + 2)) is True # Test Intersection assert planar2.intersection(Line3D(p, planar3)) == [Point3D(1, 1, 2)] # Test Scale assert planar2.scale(1, 1, 1) == planar2 assert planar2.scale(2, 2, 2, planar3) == Point3D(1, 1, 1) assert planar2.scale(1, 1, 1, p3) == planar2 # Test Transform identity = Matrix([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]) assert p.transform(identity) == p trans = Matrix([[1, 0, 0, 1], [0, 1, 0, 1], [0, 0, 1, 1], [0, 0, 0, 1]]) assert p.transform(trans) == Point3D(2, 2, 2) raises(ValueError, lambda: p.transform(p)) raises(ValueError, lambda: p.transform(Matrix([[1, 0], [0, 1]]))) # Test Equals assert p.equals(x1) == False # Test __sub__ p_4d = Point(0, 0, 0, 1) with warns(UserWarning, test_stacklevel=False): assert p - p_4d == Point(1, 1, 1, -1) p_4d3d = Point(0, 0, 1, 0) with warns(UserWarning, test_stacklevel=False): assert p - p_4d3d == Point(1, 1, 0, 0) def test_Point2D(): # Test Distance p1 = Point2D(1, 5) p2 = Point2D(4, 2.5) p3 = (6, 3) assert p1.distance(p2) == sqrt(61)/2 assert p2.distance(p3) == sqrt(17)/2 # Test coordinates assert p1.x == 1 assert p1.y == 5 assert p2.x == 4 assert p2.y == 2.5 assert p1.coordinates == (1, 5) assert p2.coordinates == (4, 2.5) # test bounds assert p1.bounds == (1, 5, 1, 5) def test_issue_9214(): p1 = Point3D(4, -2, 6) p2 = Point3D(1, 2, 3) p3 = Point3D(7, 2, 3) assert Point3D.are_collinear(p1, p2, p3) is False def test_issue_11617(): p1 = Point3D(1,0,2) p2 = Point2D(2,0) with warns(UserWarning, test_stacklevel=False): assert p1.distance(p2) == sqrt(5) def test_transform(): p = Point(1, 1) assert p.transform(rotate(pi/2)) == Point(-1, 1) assert p.transform(scale(3, 2)) == Point(3, 2) assert p.transform(translate(1, 2)) == Point(2, 3) assert Point(1, 1).scale(2, 3, (4, 5)) == \ Point(-2, -7) assert Point(1, 1).translate(4, 5) == \ Point(5, 6) def test_concyclic_doctest_bug(): p1, p2 = Point(-1, 0), Point(1, 0) p3, p4 = Point(0, 1), Point(-1, 2) assert Point.is_concyclic(p1, p2, p3) assert not Point.is_concyclic(p1, p2, p3, p4) def test_arguments(): """Functions accepting `Point` objects in `geometry` should also accept tuples and lists and automatically convert them to points.""" singles2d = ((1,2), [1,2], Point(1,2)) singles2d2 = ((1,3), [1,3], Point(1,3)) doubles2d = cartes(singles2d, singles2d2) p2d = Point2D(1,2) singles3d = ((1,2,3), [1,2,3], Point(1,2,3)) doubles3d = subsets(singles3d, 2) p3d = Point3D(1,2,3) singles4d = ((1,2,3,4), [1,2,3,4], Point(1,2,3,4)) doubles4d = subsets(singles4d, 2) p4d = Point(1,2,3,4) # test 2D test_single = ['distance', 'is_scalar_multiple', 'taxicab_distance', 'midpoint', 'intersection', 'dot', 'equals', '__add__', '__sub__'] test_double = ['is_concyclic', 'is_collinear'] for p in singles2d: Point2D(p) for func in test_single: for p in singles2d: getattr(p2d, func)(p) for func in test_double: for p in doubles2d: getattr(p2d, func)(*p) # test 3D test_double = ['is_collinear'] for p in singles3d: Point3D(p) for func in test_single: for p in singles3d: getattr(p3d, func)(p) for func in test_double: for p in doubles3d: getattr(p3d, func)(*p) # test 4D test_double = ['is_collinear'] for p in singles4d: Point(p) for func in test_single: for p in singles4d: getattr(p4d, func)(p) for func in test_double: for p in doubles4d: getattr(p4d, func)(*p) # test evaluate=False for ops x = Symbol('x') a = Point(0, 1) assert a + (0.1, x) == Point(0.1, 1 + x, evaluate=False) a = Point(0, 1) assert a/10.0 == Point(0, 0.1, evaluate=False) a = Point(0, 1) assert a*10.0 == Point(0.0, 10.0, evaluate=False) # test evaluate=False when changing dimensions u = Point(.1, .2, evaluate=False) u4 = Point(u, dim=4, on_morph='ignore') assert u4.args == (.1, .2, 0, 0) assert all(i.is_Float for i in u4.args[:2]) # and even when *not* changing dimensions assert all(i.is_Float for i in Point(u).args) # never raise error if creating an origin assert Point(dim=3, on_morph='error') # raise error with unmatched dimension raises(ValueError, lambda: Point(1, 1, dim=3, on_morph='error')) # test unknown on_morph raises(ValueError, lambda: Point(1, 1, dim=3, on_morph='unknown')) # test invalid expressions raises(TypeError, lambda: Point(Basic(), Basic())) def test_unit(): assert Point(1, 1).unit == Point(sqrt(2)/2, sqrt(2)/2) def test_dot(): raises(TypeError, lambda: Point(1, 2).dot(Line((0, 0), (1, 1)))) def test__normalize_dimension(): assert Point._normalize_dimension(Point(1, 2), Point(3, 4)) == [ Point(1, 2), Point(3, 4)] assert Point._normalize_dimension( Point(1, 2), Point(3, 4, 0), on_morph='ignore') == [ Point(1, 2, 0), Point(3, 4, 0)] def test_issue_22684(): # Used to give an error with evaluate(False): Point(1, 2) def test_direction_cosine(): p1 = Point3D(0, 0, 0) p2 = Point3D(1, 1, 1) assert p1.direction_cosine(Point3D(1, 0, 0)) == [1, 0, 0] assert p1.direction_cosine(Point3D(0, 1, 0)) == [0, 1, 0] assert p1.direction_cosine(Point3D(0, 0, pi)) == [0, 0, 1] assert p1.direction_cosine(Point3D(5, 0, 0)) == [1, 0, 0] assert p1.direction_cosine(Point3D(0, sqrt(3), 0)) == [0, 1, 0] assert p1.direction_cosine(Point3D(0, 0, 5)) == [0, 0, 1] assert p1.direction_cosine(Point3D(2.4, 2.4, 0)) == [sqrt(2)/2, sqrt(2)/2, 0] assert p1.direction_cosine(Point3D(1, 1, 1)) == [sqrt(3) / 3, sqrt(3) / 3, sqrt(3) / 3] assert p1.direction_cosine(Point3D(-12, 0 -15)) == [-4*sqrt(41)/41, -5*sqrt(41)/41, 0] assert p2.direction_cosine(Point3D(0, 0, 0)) == [-sqrt(3) / 3, -sqrt(3) / 3, -sqrt(3) / 3] assert p2.direction_cosine(Point3D(1, 1, 12)) == [0, 0, 1] assert p2.direction_cosine(Point3D(12, 1, 12)) == [sqrt(2) / 2, 0, sqrt(2) / 2]
efd8819108e95fe09d3b59ad31a5f7946bd57e4a290621612c2dd07d60ab7960
from sympy.core.numbers import (Float, Rational, oo, pi) from sympy.core.singleton import S from sympy.core.symbol import (Symbol, symbols) from sympy.functions.elementary.complexes import Abs from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import (acos, cos, sin) from sympy.functions.elementary.trigonometric import tan from sympy.geometry import (Circle, Ellipse, GeometryError, Point, Point2D, Polygon, Ray, RegularPolygon, Segment, Triangle, are_similar, convex_hull, intersection, Line, Ray2D) from sympy.testing.pytest import raises, slow, warns from sympy.core.random import verify_numerically from sympy.geometry.polygon import rad, deg from sympy.integrals.integrals import integrate def feq(a, b): """Test if two floating point values are 'equal'.""" t_float = Float("1.0E-10") return -t_float < a - b < t_float @slow def test_polygon(): x = Symbol('x', real=True) y = Symbol('y', real=True) q = Symbol('q', real=True) u = Symbol('u', real=True) v = Symbol('v', real=True) w = Symbol('w', real=True) x1 = Symbol('x1', real=True) half = S.Half a, b, c = Point(0, 0), Point(2, 0), Point(3, 3) t = Triangle(a, b, c) assert Polygon(Point(0, 0)) == Point(0, 0) assert Polygon(a, Point(1, 0), b, c) == t assert Polygon(Point(1, 0), b, c, a) == t assert Polygon(b, c, a, Point(1, 0)) == t # 2 "remove folded" tests assert Polygon(a, Point(3, 0), b, c) == t assert Polygon(a, b, Point(3, -1), b, c) == t # remove multiple collinear points assert Polygon(Point(-4, 15), Point(-11, 15), Point(-15, 15), Point(-15, 33/5), Point(-15, -87/10), Point(-15, -15), Point(-42/5, -15), Point(-2, -15), Point(7, -15), Point(15, -15), Point(15, -3), Point(15, 10), Point(15, 15)) == \ Polygon(Point(-15, -15), Point(15, -15), Point(15, 15), Point(-15, 15)) p1 = Polygon( Point(0, 0), Point(3, -1), Point(6, 0), Point(4, 5), Point(2, 3), Point(0, 3)) p2 = Polygon( Point(6, 0), Point(3, -1), Point(0, 0), Point(0, 3), Point(2, 3), Point(4, 5)) p3 = Polygon( Point(0, 0), Point(3, 0), Point(5, 2), Point(4, 4)) p4 = Polygon( Point(0, 0), Point(4, 4), Point(5, 2), Point(3, 0)) p5 = Polygon( Point(0, 0), Point(4, 4), Point(0, 4)) p6 = Polygon( Point(-11, 1), Point(-9, 6.6), Point(-4, -3), Point(-8.4, -8.7)) p7 = Polygon( Point(x, y), Point(q, u), Point(v, w)) p8 = Polygon( Point(x, y), Point(v, w), Point(q, u)) p9 = Polygon( Point(0, 0), Point(4, 4), Point(3, 0), Point(5, 2)) p10 = Polygon( Point(0, 2), Point(2, 2), Point(0, 0), Point(2, 0)) p11 = Polygon(Point(0, 0), 1, n=3) p12 = Polygon(Point(0, 0), 1, 0, n=3) r = Ray(Point(-9, 6.6), Point(-9, 5.5)) # # General polygon # assert p1 == p2 assert len(p1.args) == 6 assert len(p1.sides) == 6 assert p1.perimeter == 5 + 2*sqrt(10) + sqrt(29) + sqrt(8) assert p1.area == 22 assert not p1.is_convex() assert Polygon((-1, 1), (2, -1), (2, 1), (-1, -1), (3, 0) ).is_convex() is False # ensure convex for both CW and CCW point specification assert p3.is_convex() assert p4.is_convex() dict5 = p5.angles assert dict5[Point(0, 0)] == pi / 4 assert dict5[Point(0, 4)] == pi / 2 assert p5.encloses_point(Point(x, y)) is None assert p5.encloses_point(Point(1, 3)) assert p5.encloses_point(Point(0, 0)) is False assert p5.encloses_point(Point(4, 0)) is False assert p1.encloses(Circle(Point(2.5, 2.5), 5)) is False assert p1.encloses(Ellipse(Point(2.5, 2), 5, 6)) is False assert p5.plot_interval('x') == [x, 0, 1] assert p5.distance( Polygon(Point(10, 10), Point(14, 14), Point(10, 14))) == 6 * sqrt(2) assert p5.distance( Polygon(Point(1, 8), Point(5, 8), Point(8, 12), Point(1, 12))) == 4 with warns(UserWarning, \ match="Polygons may intersect producing erroneous output"): Polygon(Point(0, 0), Point(1, 0), Point(1, 1)).distance( Polygon(Point(0, 0), Point(0, 1), Point(1, 1))) assert hash(p5) == hash(Polygon(Point(0, 0), Point(4, 4), Point(0, 4))) assert hash(p1) == hash(p2) assert hash(p7) == hash(p8) assert hash(p3) != hash(p9) assert p5 == Polygon(Point(4, 4), Point(0, 4), Point(0, 0)) assert Polygon(Point(4, 4), Point(0, 4), Point(0, 0)) in p5 assert p5 != Point(0, 4) assert Point(0, 1) in p5 assert p5.arbitrary_point('t').subs(Symbol('t', real=True), 0) == \ Point(0, 0) raises(ValueError, lambda: Polygon( Point(x, 0), Point(0, y), Point(x, y)).arbitrary_point('x')) assert p6.intersection(r) == [Point(-9, Rational(-84, 13)), Point(-9, Rational(33, 5))] assert p10.area == 0 assert p11 == RegularPolygon(Point(0, 0), 1, 3, 0) assert p11 == p12 assert p11.vertices[0] == Point(1, 0) assert p11.args[0] == Point(0, 0) p11.spin(pi/2) assert p11.vertices[0] == Point(0, 1) # # Regular polygon # p1 = RegularPolygon(Point(0, 0), 10, 5) p2 = RegularPolygon(Point(0, 0), 5, 5) raises(GeometryError, lambda: RegularPolygon(Point(0, 0), Point(0, 1), Point(1, 1))) raises(GeometryError, lambda: RegularPolygon(Point(0, 0), 1, 2)) raises(ValueError, lambda: RegularPolygon(Point(0, 0), 1, 2.5)) assert p1 != p2 assert p1.interior_angle == pi*Rational(3, 5) assert p1.exterior_angle == pi*Rational(2, 5) assert p2.apothem == 5*cos(pi/5) assert p2.circumcenter == p1.circumcenter == Point(0, 0) assert p1.circumradius == p1.radius == 10 assert p2.circumcircle == Circle(Point(0, 0), 5) assert p2.incircle == Circle(Point(0, 0), p2.apothem) assert p2.inradius == p2.apothem == (5 * (1 + sqrt(5)) / 4) p2.spin(pi / 10) dict1 = p2.angles assert dict1[Point(0, 5)] == 3 * pi / 5 assert p1.is_convex() assert p1.rotation == 0 assert p1.encloses_point(Point(0, 0)) assert p1.encloses_point(Point(11, 0)) is False assert p2.encloses_point(Point(0, 4.9)) p1.spin(pi/3) assert p1.rotation == pi/3 assert p1.vertices[0] == Point(5, 5*sqrt(3)) for var in p1.args: if isinstance(var, Point): assert var == Point(0, 0) else: assert var in (5, 10, pi / 3) assert p1 != Point(0, 0) assert p1 != p5 # while spin works in place (notice that rotation is 2pi/3 below) # rotate returns a new object p1_old = p1 assert p1.rotate(pi/3) == RegularPolygon(Point(0, 0), 10, 5, pi*Rational(2, 3)) assert p1 == p1_old assert p1.area == (-250*sqrt(5) + 1250)/(4*tan(pi/5)) assert p1.length == 20*sqrt(-sqrt(5)/8 + Rational(5, 8)) assert p1.scale(2, 2) == \ RegularPolygon(p1.center, p1.radius*2, p1._n, p1.rotation) assert RegularPolygon((0, 0), 1, 4).scale(2, 3) == \ Polygon(Point(2, 0), Point(0, 3), Point(-2, 0), Point(0, -3)) assert repr(p1) == str(p1) # # Angles # angles = p4.angles assert feq(angles[Point(0, 0)].evalf(), Float("0.7853981633974483")) assert feq(angles[Point(4, 4)].evalf(), Float("1.2490457723982544")) assert feq(angles[Point(5, 2)].evalf(), Float("1.8925468811915388")) assert feq(angles[Point(3, 0)].evalf(), Float("2.3561944901923449")) angles = p3.angles assert feq(angles[Point(0, 0)].evalf(), Float("0.7853981633974483")) assert feq(angles[Point(4, 4)].evalf(), Float("1.2490457723982544")) assert feq(angles[Point(5, 2)].evalf(), Float("1.8925468811915388")) assert feq(angles[Point(3, 0)].evalf(), Float("2.3561944901923449")) # # Triangle # p1 = Point(0, 0) p2 = Point(5, 0) p3 = Point(0, 5) t1 = Triangle(p1, p2, p3) t2 = Triangle(p1, p2, Point(Rational(5, 2), sqrt(Rational(75, 4)))) t3 = Triangle(p1, Point(x1, 0), Point(0, x1)) s1 = t1.sides assert Triangle(p1, p2, p1) == Polygon(p1, p2, p1) == Segment(p1, p2) raises(GeometryError, lambda: Triangle(Point(0, 0))) # Basic stuff assert Triangle(p1, p1, p1) == p1 assert Triangle(p2, p2*2, p2*3) == Segment(p2, p2*3) assert t1.area == Rational(25, 2) assert t1.is_right() assert t2.is_right() is False assert t3.is_right() assert p1 in t1 assert t1.sides[0] in t1 assert Segment((0, 0), (1, 0)) in t1 assert Point(5, 5) not in t2 assert t1.is_convex() assert feq(t1.angles[p1].evalf(), pi.evalf()/2) assert t1.is_equilateral() is False assert t2.is_equilateral() assert t3.is_equilateral() is False assert are_similar(t1, t2) is False assert are_similar(t1, t3) assert are_similar(t2, t3) is False assert t1.is_similar(Point(0, 0)) is False assert t1.is_similar(t2) is False # Bisectors bisectors = t1.bisectors() assert bisectors[p1] == Segment( p1, Point(Rational(5, 2), Rational(5, 2))) assert t2.bisectors()[p2] == Segment( Point(5, 0), Point(Rational(5, 4), 5*sqrt(3)/4)) p4 = Point(0, x1) assert t3.bisectors()[p4] == Segment(p4, Point(x1*(sqrt(2) - 1), 0)) ic = (250 - 125*sqrt(2))/50 assert t1.incenter == Point(ic, ic) # Inradius assert t1.inradius == t1.incircle.radius == 5 - 5*sqrt(2)/2 assert t2.inradius == t2.incircle.radius == 5*sqrt(3)/6 assert t3.inradius == t3.incircle.radius == x1**2/((2 + sqrt(2))*Abs(x1)) # Exradius assert t1.exradii[t1.sides[2]] == 5*sqrt(2)/2 # Excenters assert t1.excenters[t1.sides[2]] == Point2D(25*sqrt(2), -5*sqrt(2)/2) # Circumcircle assert t1.circumcircle.center == Point(2.5, 2.5) # Medians + Centroid m = t1.medians assert t1.centroid == Point(Rational(5, 3), Rational(5, 3)) assert m[p1] == Segment(p1, Point(Rational(5, 2), Rational(5, 2))) assert t3.medians[p1] == Segment(p1, Point(x1/2, x1/2)) assert intersection(m[p1], m[p2], m[p3]) == [t1.centroid] assert t1.medial == Triangle(Point(2.5, 0), Point(0, 2.5), Point(2.5, 2.5)) # Nine-point circle assert t1.nine_point_circle == Circle(Point(2.5, 0), Point(0, 2.5), Point(2.5, 2.5)) assert t1.nine_point_circle == Circle(Point(0, 0), Point(0, 2.5), Point(2.5, 2.5)) # Perpendicular altitudes = t1.altitudes assert altitudes[p1] == Segment(p1, Point(Rational(5, 2), Rational(5, 2))) assert altitudes[p2].equals(s1[0]) assert altitudes[p3] == s1[2] assert t1.orthocenter == p1 t = S('''Triangle( Point(100080156402737/5000000000000, 79782624633431/500000000000), Point(39223884078253/2000000000000, 156345163124289/1000000000000), Point(31241359188437/1250000000000, 338338270939941/1000000000000000))''') assert t.orthocenter == S('''Point(-780660869050599840216997''' '''79471538701955848721853/80368430960602242240789074233100000000000000,''' '''20151573611150265741278060334545897615974257/16073686192120448448157''' '''8148466200000000000)''') # Ensure assert len(intersection(*bisectors.values())) == 1 assert len(intersection(*altitudes.values())) == 1 assert len(intersection(*m.values())) == 1 # Distance p1 = Polygon( Point(0, 0), Point(1, 0), Point(1, 1), Point(0, 1)) p2 = Polygon( Point(0, Rational(5)/4), Point(1, Rational(5)/4), Point(1, Rational(9)/4), Point(0, Rational(9)/4)) p3 = Polygon( Point(1, 2), Point(2, 2), Point(2, 1)) p4 = Polygon( Point(1, 1), Point(Rational(6)/5, 1), Point(1, Rational(6)/5)) pt1 = Point(half, half) pt2 = Point(1, 1) '''Polygon to Point''' assert p1.distance(pt1) == half assert p1.distance(pt2) == 0 assert p2.distance(pt1) == Rational(3)/4 assert p3.distance(pt2) == sqrt(2)/2 '''Polygon to Polygon''' # p1.distance(p2) emits a warning with warns(UserWarning, \ match="Polygons may intersect producing erroneous output"): assert p1.distance(p2) == half/2 assert p1.distance(p3) == sqrt(2)/2 # p3.distance(p4) emits a warning with warns(UserWarning, \ match="Polygons may intersect producing erroneous output"): assert p3.distance(p4) == (sqrt(2)/2 - sqrt(Rational(2)/25)/2) def test_convex_hull(): p = [Point(-5, -1), Point(-2, 1), Point(-2, -1), Point(-1, -3), \ Point(0, 0), Point(1, 1), Point(2, 2), Point(2, -1), Point(3, 1), \ Point(4, -1), Point(6, 2)] ch = Polygon(p[0], p[3], p[9], p[10], p[6], p[1]) #test handling of duplicate points p.append(p[3]) #more than 3 collinear points another_p = [Point(-45, -85), Point(-45, 85), Point(-45, 26), \ Point(-45, -24)] ch2 = Segment(another_p[0], another_p[1]) assert convex_hull(*another_p) == ch2 assert convex_hull(*p) == ch assert convex_hull(p[0]) == p[0] assert convex_hull(p[0], p[1]) == Segment(p[0], p[1]) # no unique points assert convex_hull(*[p[-1]]*3) == p[-1] # collection of items assert convex_hull(*[Point(0, 0), \ Segment(Point(1, 0), Point(1, 1)), \ RegularPolygon(Point(2, 0), 2, 4)]) == \ Polygon(Point(0, 0), Point(2, -2), Point(4, 0), Point(2, 2)) def test_encloses(): # square with a dimpled left side s = Polygon(Point(0, 0), Point(1, 0), Point(1, 1), Point(0, 1), \ Point(S.Half, S.Half)) # the following is True if the polygon isn't treated as closing on itself assert s.encloses(Point(0, S.Half)) is False assert s.encloses(Point(S.Half, S.Half)) is False # it's a vertex assert s.encloses(Point(Rational(3, 4), S.Half)) is True def test_triangle_kwargs(): assert Triangle(sss=(3, 4, 5)) == \ Triangle(Point(0, 0), Point(3, 0), Point(3, 4)) assert Triangle(asa=(30, 2, 30)) == \ Triangle(Point(0, 0), Point(2, 0), Point(1, sqrt(3)/3)) assert Triangle(sas=(1, 45, 2)) == \ Triangle(Point(0, 0), Point(2, 0), Point(sqrt(2)/2, sqrt(2)/2)) assert Triangle(sss=(1, 2, 5)) is None assert deg(rad(180)) == 180 def test_transform(): pts = [Point(0, 0), Point(S.Half, Rational(1, 4)), Point(1, 1)] pts_out = [Point(-4, -10), Point(-3, Rational(-37, 4)), Point(-2, -7)] assert Triangle(*pts).scale(2, 3, (4, 5)) == Triangle(*pts_out) assert RegularPolygon((0, 0), 1, 4).scale(2, 3, (4, 5)) == \ Polygon(Point(-2, -10), Point(-4, -7), Point(-6, -10), Point(-4, -13)) # Checks for symmetric scaling assert RegularPolygon((0, 0), 1, 4).scale(2, 2) == \ RegularPolygon(Point2D(0, 0), 2, 4, 0) def test_reflect(): x = Symbol('x', real=True) y = Symbol('y', real=True) b = Symbol('b') m = Symbol('m') l = Line((0, b), slope=m) p = Point(x, y) r = p.reflect(l) dp = l.perpendicular_segment(p).length dr = l.perpendicular_segment(r).length assert verify_numerically(dp, dr) assert Polygon((1, 0), (2, 0), (2, 2)).reflect(Line((3, 0), slope=oo)) \ == Triangle(Point(5, 0), Point(4, 0), Point(4, 2)) assert Polygon((1, 0), (2, 0), (2, 2)).reflect(Line((0, 3), slope=oo)) \ == Triangle(Point(-1, 0), Point(-2, 0), Point(-2, 2)) assert Polygon((1, 0), (2, 0), (2, 2)).reflect(Line((0, 3), slope=0)) \ == Triangle(Point(1, 6), Point(2, 6), Point(2, 4)) assert Polygon((1, 0), (2, 0), (2, 2)).reflect(Line((3, 0), slope=0)) \ == Triangle(Point(1, 0), Point(2, 0), Point(2, -2)) def test_bisectors(): p1, p2, p3 = Point(0, 0), Point(1, 0), Point(0, 1) p = Polygon(Point(0, 0), Point(2, 0), Point(1, 1), Point(0, 3)) q = Polygon(Point(1, 0), Point(2, 0), Point(3, 3), Point(-1, 5)) poly = Polygon(Point(3, 4), Point(0, 0), Point(8, 7), Point(-1, 1), Point(19, -19)) t = Triangle(p1, p2, p3) assert t.bisectors()[p2] == Segment(Point(1, 0), Point(0, sqrt(2) - 1)) assert p.bisectors()[Point2D(0, 3)] == Ray2D(Point2D(0, 3), \ Point2D(sin(acos(2*sqrt(5)/5)/2), 3 - cos(acos(2*sqrt(5)/5)/2))) assert q.bisectors()[Point2D(-1, 5)] == \ Ray2D(Point2D(-1, 5), Point2D(-1 + sqrt(29)*(5*sin(acos(9*sqrt(145)/145)/2) + \ 2*cos(acos(9*sqrt(145)/145)/2))/29, sqrt(29)*(-5*cos(acos(9*sqrt(145)/145)/2) + \ 2*sin(acos(9*sqrt(145)/145)/2))/29 + 5)) assert poly.bisectors()[Point2D(-1, 1)] == Ray2D(Point2D(-1, 1), \ Point2D(-1 + sin(acos(sqrt(26)/26)/2 + pi/4), 1 - sin(-acos(sqrt(26)/26)/2 + pi/4))) def test_incenter(): assert Triangle(Point(0, 0), Point(1, 0), Point(0, 1)).incenter \ == Point(1 - sqrt(2)/2, 1 - sqrt(2)/2) def test_inradius(): assert Triangle(Point(0, 0), Point(4, 0), Point(0, 3)).inradius == 1 def test_incircle(): assert Triangle(Point(0, 0), Point(2, 0), Point(0, 2)).incircle \ == Circle(Point(2 - sqrt(2), 2 - sqrt(2)), 2 - sqrt(2)) def test_exradii(): t = Triangle(Point(0, 0), Point(6, 0), Point(0, 2)) assert t.exradii[t.sides[2]] == (-2 + sqrt(10)) def test_medians(): t = Triangle(Point(0, 0), Point(1, 0), Point(0, 1)) assert t.medians[Point(0, 0)] == Segment(Point(0, 0), Point(S.Half, S.Half)) def test_medial(): assert Triangle(Point(0, 0), Point(1, 0), Point(0, 1)).medial \ == Triangle(Point(S.Half, 0), Point(S.Half, S.Half), Point(0, S.Half)) def test_nine_point_circle(): assert Triangle(Point(0, 0), Point(1, 0), Point(0, 1)).nine_point_circle \ == Circle(Point2D(Rational(1, 4), Rational(1, 4)), sqrt(2)/4) def test_eulerline(): assert Triangle(Point(0, 0), Point(1, 0), Point(0, 1)).eulerline \ == Line(Point2D(0, 0), Point2D(S.Half, S.Half)) assert Triangle(Point(0, 0), Point(10, 0), Point(5, 5*sqrt(3))).eulerline \ == Point2D(5, 5*sqrt(3)/3) assert Triangle(Point(4, -6), Point(4, -1), Point(-3, 3)).eulerline \ == Line(Point2D(Rational(64, 7), 3), Point2D(Rational(-29, 14), Rational(-7, 2))) def test_intersection(): poly1 = Triangle(Point(0, 0), Point(1, 0), Point(0, 1)) poly2 = Polygon(Point(0, 1), Point(-5, 0), Point(0, -4), Point(0, Rational(1, 5)), Point(S.Half, -0.1), Point(1, 0), Point(0, 1)) assert poly1.intersection(poly2) == [Point2D(Rational(1, 3), 0), Segment(Point(0, Rational(1, 5)), Point(0, 0)), Segment(Point(1, 0), Point(0, 1))] assert poly2.intersection(poly1) == [Point(Rational(1, 3), 0), Segment(Point(0, 0), Point(0, Rational(1, 5))), Segment(Point(1, 0), Point(0, 1))] assert poly1.intersection(Point(0, 0)) == [Point(0, 0)] assert poly1.intersection(Point(-12, -43)) == [] assert poly2.intersection(Line((-12, 0), (12, 0))) == [Point(-5, 0), Point(0, 0), Point(Rational(1, 3), 0), Point(1, 0)] assert poly2.intersection(Line((-12, 12), (12, 12))) == [] assert poly2.intersection(Ray((-3, 4), (1, 0))) == [Segment(Point(1, 0), Point(0, 1))] assert poly2.intersection(Circle((0, -1), 1)) == [Point(0, -2), Point(0, 0)] assert poly1.intersection(poly1) == [Segment(Point(0, 0), Point(1, 0)), Segment(Point(0, 1), Point(0, 0)), Segment(Point(1, 0), Point(0, 1))] assert poly2.intersection(poly2) == [Segment(Point(-5, 0), Point(0, -4)), Segment(Point(0, -4), Point(0, Rational(1, 5))), Segment(Point(0, Rational(1, 5)), Point(S.Half, Rational(-1, 10))), Segment(Point(0, 1), Point(-5, 0)), Segment(Point(S.Half, Rational(-1, 10)), Point(1, 0)), Segment(Point(1, 0), Point(0, 1))] assert poly2.intersection(Triangle(Point(0, 1), Point(1, 0), Point(-1, 1))) \ == [Point(Rational(-5, 7), Rational(6, 7)), Segment(Point2D(0, 1), Point(1, 0))] assert poly1.intersection(RegularPolygon((-12, -15), 3, 3)) == [] def test_parameter_value(): t = Symbol('t') sq = Polygon((0, 0), (0, 1), (1, 1), (1, 0)) assert sq.parameter_value((0.5, 1), t) == {t: Rational(3, 8)} q = Polygon((0, 0), (2, 1), (2, 4), (4, 0)) assert q.parameter_value((4, 0), t) == {t: -6 + 3*sqrt(5)} # ~= 0.708 raises(ValueError, lambda: sq.parameter_value((5, 6), t)) raises(ValueError, lambda: sq.parameter_value(Circle(Point(0, 0), 1), t)) def test_issue_12966(): poly = Polygon(Point(0, 0), Point(0, 10), Point(5, 10), Point(5, 5), Point(10, 5), Point(10, 0)) t = Symbol('t') pt = poly.arbitrary_point(t) DELTA = 5/poly.perimeter assert [pt.subs(t, DELTA*i) for i in range(int(1/DELTA))] == [ Point(0, 0), Point(0, 5), Point(0, 10), Point(5, 10), Point(5, 5), Point(10, 5), Point(10, 0), Point(5, 0)] def test_second_moment_of_area(): x, y = symbols('x, y') # triangle p1, p2, p3 = [(0, 0), (4, 0), (0, 2)] p = (0, 0) # equation of hypotenuse eq_y = (1-x/4)*2 I_yy = integrate((x**2) * (integrate(1, (y, 0, eq_y))), (x, 0, 4)) I_xx = integrate(1 * (integrate(y**2, (y, 0, eq_y))), (x, 0, 4)) I_xy = integrate(x * (integrate(y, (y, 0, eq_y))), (x, 0, 4)) triangle = Polygon(p1, p2, p3) assert (I_xx - triangle.second_moment_of_area(p)[0]) == 0 assert (I_yy - triangle.second_moment_of_area(p)[1]) == 0 assert (I_xy - triangle.second_moment_of_area(p)[2]) == 0 # rectangle p1, p2, p3, p4=[(0, 0), (4, 0), (4, 2), (0, 2)] I_yy = integrate((x**2) * integrate(1, (y, 0, 2)), (x, 0, 4)) I_xx = integrate(1 * integrate(y**2, (y, 0, 2)), (x, 0, 4)) I_xy = integrate(x * integrate(y, (y, 0, 2)), (x, 0, 4)) rectangle = Polygon(p1, p2, p3, p4) assert (I_xx - rectangle.second_moment_of_area(p)[0]) == 0 assert (I_yy - rectangle.second_moment_of_area(p)[1]) == 0 assert (I_xy - rectangle.second_moment_of_area(p)[2]) == 0 r = RegularPolygon(Point(0, 0), 5, 3) assert r.second_moment_of_area() == (1875*sqrt(3)/S(32), 1875*sqrt(3)/S(32), 0) def test_first_moment(): a, b = symbols('a, b', positive=True) # rectangle p1 = Polygon((0, 0), (a, 0), (a, b), (0, b)) assert p1.first_moment_of_area() == (a*b**2/8, a**2*b/8) assert p1.first_moment_of_area((a/3, b/4)) == (-3*a*b**2/32, -a**2*b/9) p1 = Polygon((0, 0), (40, 0), (40, 30), (0, 30)) assert p1.first_moment_of_area() == (4500, 6000) # triangle p2 = Polygon((0, 0), (a, 0), (a/2, b)) assert p2.first_moment_of_area() == (4*a*b**2/81, a**2*b/24) assert p2.first_moment_of_area((a/8, b/6)) == (-25*a*b**2/648, -5*a**2*b/768) p2 = Polygon((0, 0), (12, 0), (12, 30)) assert p2.first_moment_of_area() == (S(1600)/3, -S(640)/3) def test_section_modulus_and_polar_second_moment_of_area(): a, b = symbols('a, b', positive=True) x, y = symbols('x, y') rectangle = Polygon((0, b), (0, 0), (a, 0), (a, b)) assert rectangle.section_modulus(Point(x, y)) == (a*b**3/12/(-b/2 + y), a**3*b/12/(-a/2 + x)) assert rectangle.polar_second_moment_of_area() == a**3*b/12 + a*b**3/12 convex = RegularPolygon((0, 0), 1, 6) assert convex.section_modulus() == (Rational(5, 8), sqrt(3)*Rational(5, 16)) assert convex.polar_second_moment_of_area() == 5*sqrt(3)/S(8) concave = Polygon((0, 0), (1, 8), (3, 4), (4, 6), (7, 1)) assert concave.section_modulus() == (Rational(-6371, 429), Rational(-9778, 519)) assert concave.polar_second_moment_of_area() == Rational(-38669, 252) def test_cut_section(): # concave polygon p = Polygon((-1, -1), (1, Rational(5, 2)), (2, 1), (3, Rational(5, 2)), (4, 2), (5, 3), (-1, 3)) l = Line((0, 0), (Rational(9, 2), 3)) p1 = p.cut_section(l)[0] p2 = p.cut_section(l)[1] assert p1 == Polygon( Point2D(Rational(-9, 13), Rational(-6, 13)), Point2D(1, Rational(5, 2)), Point2D(Rational(24, 13), Rational(16, 13)), Point2D(Rational(12, 5), Rational(8, 5)), Point2D(3, Rational(5, 2)), Point2D(Rational(24, 7), Rational(16, 7)), Point2D(Rational(9, 2), 3), Point2D(-1, 3), Point2D(-1, Rational(-2, 3))) assert p2 == Polygon(Point2D(-1, -1), Point2D(Rational(-9, 13), Rational(-6, 13)), Point2D(Rational(24, 13), Rational(16, 13)), Point2D(2, 1), Point2D(Rational(12, 5), Rational(8, 5)), Point2D(Rational(24, 7), Rational(16, 7)), Point2D(4, 2), Point2D(5, 3), Point2D(Rational(9, 2), 3), Point2D(-1, Rational(-2, 3))) # convex polygon p = RegularPolygon(Point2D(0, 0), 6, 6) s = p.cut_section(Line((0, 0), slope=1)) assert s[0] == Polygon(Point2D(-3*sqrt(3) + 9, -3*sqrt(3) + 9), Point2D(3, 3*sqrt(3)), Point2D(-3, 3*sqrt(3)), Point2D(-6, 0), Point2D(-9 + 3*sqrt(3), -9 + 3*sqrt(3))) assert s[1] == Polygon(Point2D(6, 0), Point2D(-3*sqrt(3) + 9, -3*sqrt(3) + 9), Point2D(-9 + 3*sqrt(3), -9 + 3*sqrt(3)), Point2D(-3, -3*sqrt(3)), Point2D(3, -3*sqrt(3))) # case where line does not intersects but coincides with the edge of polygon a, b = 20, 10 t1, t2, t3, t4 = [(0, b), (0, 0), (a, 0), (a, b)] p = Polygon(t1, t2, t3, t4) p1, p2 = p.cut_section(Line((0, b), slope=0)) assert p1 == None assert p2 == Polygon(Point2D(0, 10), Point2D(0, 0), Point2D(20, 0), Point2D(20, 10)) p3, p4 = p.cut_section(Line((0, 0), slope=0)) assert p3 == Polygon(Point2D(0, 10), Point2D(0, 0), Point2D(20, 0), Point2D(20, 10)) assert p4 == None # case where the line does not intersect with a polygon at all raises(ValueError, lambda: p.cut_section(Line((0, a), slope=0))) def test_type_of_triangle(): # Isoceles triangle p1 = Polygon(Point(0, 0), Point(5, 0), Point(2, 4)) assert p1.is_isosceles() == True assert p1.is_scalene() == False assert p1.is_equilateral() == False # Scalene triangle p2 = Polygon (Point(0, 0), Point(0, 2), Point(4, 0)) assert p2.is_isosceles() == False assert p2.is_scalene() == True assert p2.is_equilateral() == False # Equilateral triagle p3 = Polygon(Point(0, 0), Point(6, 0), Point(3, sqrt(27))) assert p3.is_isosceles() == True assert p3.is_scalene() == False assert p3.is_equilateral() == True def test_do_poly_distance(): # Non-intersecting polygons square1 = Polygon (Point(0, 0), Point(0, 1), Point(1, 1), Point(1, 0)) triangle1 = Polygon(Point(1, 2), Point(2, 2), Point(2, 1)) assert square1._do_poly_distance(triangle1) == sqrt(2)/2 # Polygons which sides intersect square2 = Polygon(Point(1, 0), Point(2, 0), Point(2, 1), Point(1, 1)) with warns(UserWarning, \ match="Polygons may intersect producing erroneous output", test_stacklevel=False): assert square1._do_poly_distance(square2) == 0 # Polygons which bodies intersect triangle2 = Polygon(Point(0, -1), Point(2, -1), Point(S.Half, S.Half)) with warns(UserWarning, \ match="Polygons may intersect producing erroneous output", test_stacklevel=False): assert triangle2._do_poly_distance(square1) == 0
0453bc408a18c7b221e6b3235719daaff1eec066aef969d18e478a2826589dfe
from sympy.core.numbers import (Rational, oo) from sympy.core.singleton import S from sympy.core.symbol import symbols from sympy.functions.elementary.complexes import sign from sympy.functions.elementary.miscellaneous import sqrt from sympy.geometry.ellipse import (Circle, Ellipse) from sympy.geometry.line import (Line, Ray2D, Segment2D) from sympy.geometry.parabola import Parabola from sympy.geometry.point import (Point, Point2D) from sympy.testing.pytest import raises from sympy.abc import x, y def test_parabola_geom(): a, b = symbols('a b') p1 = Point(0, 0) p2 = Point(3, 7) p3 = Point(0, 4) p4 = Point(6, 0) p5 = Point(a, a) d1 = Line(Point(4, 0), Point(4, 9)) d2 = Line(Point(7, 6), Point(3, 6)) d3 = Line(Point(4, 0), slope=oo) d4 = Line(Point(7, 6), slope=0) d5 = Line(Point(b, a), slope=oo) d6 = Line(Point(a, b), slope=0) half = S.Half pa1 = Parabola(None, d2) pa2 = Parabola(directrix=d1) pa3 = Parabola(p1, d1) pa4 = Parabola(p2, d2) pa5 = Parabola(p2, d4) pa6 = Parabola(p3, d2) pa7 = Parabola(p2, d1) pa8 = Parabola(p4, d1) pa9 = Parabola(p4, d3) pa10 = Parabola(p5, d5) pa11 = Parabola(p5, d6) d = Line(Point(3, 7), Point(2, 9)) pa12 = Parabola(Point(7, 8), d) pa12r = Parabola(Point(7, 8).reflect(d), d) raises(ValueError, lambda: Parabola(Point(7, 8, 9), Line(Point(6, 7), Point(7, 7)))) raises(ValueError, lambda: Parabola(Point(0, 2), Line(Point(7, 2), Point(6, 2)))) raises(ValueError, lambda: Parabola(Point(7, 8), Point(3, 8))) # Basic Stuff assert pa1.focus == Point(0, 0) assert pa1.ambient_dimension == S(2) assert pa2 == pa3 assert pa4 != pa7 assert pa6 != pa7 assert pa6.focus == Point2D(0, 4) assert pa6.focal_length == 1 assert pa6.p_parameter == -1 assert pa6.vertex == Point2D(0, 5) assert pa6.eccentricity == 1 assert pa7.focus == Point2D(3, 7) assert pa7.focal_length == half assert pa7.p_parameter == -half assert pa7.vertex == Point2D(7*half, 7) assert pa4.focal_length == half assert pa4.p_parameter == half assert pa4.vertex == Point2D(3, 13*half) assert pa8.focal_length == 1 assert pa8.p_parameter == 1 assert pa8.vertex == Point2D(5, 0) assert pa4.focal_length == pa5.focal_length assert pa4.p_parameter == pa5.p_parameter assert pa4.vertex == pa5.vertex assert pa4.equation() == pa5.equation() assert pa8.focal_length == pa9.focal_length assert pa8.p_parameter == pa9.p_parameter assert pa8.vertex == pa9.vertex assert pa8.equation() == pa9.equation() assert pa10.focal_length == pa11.focal_length == sqrt((a - b) ** 2) / 2 # if a, b real == abs(a - b)/2 assert pa11.vertex == Point(*pa10.vertex[::-1]) == Point(a, a - sqrt((a - b)**2)*sign(a - b)/2) # change axis x->y, y->x on pa10 aos = pa12.axis_of_symmetry assert aos == Line(Point(7, 8), Point(5, 7)) assert pa12.directrix == Line(Point(3, 7), Point(2, 9)) assert pa12.directrix.angle_between(aos) == S.Pi/2 assert pa12.eccentricity == 1 assert pa12.equation(x, y) == (x - 7)**2 + (y - 8)**2 - (-2*x - y + 13)**2/5 assert pa12.focal_length == 9*sqrt(5)/10 assert pa12.focus == Point(7, 8) assert pa12.p_parameter == 9*sqrt(5)/10 assert pa12.vertex == Point2D(S(26)/5, S(71)/10) assert pa12r.focal_length == 9*sqrt(5)/10 assert pa12r.focus == Point(-S(1)/5, S(22)/5) assert pa12r.p_parameter == -9*sqrt(5)/10 assert pa12r.vertex == Point(S(8)/5, S(53)/10) def test_parabola_intersection(): l1 = Line(Point(1, -2), Point(-1,-2)) l2 = Line(Point(1, 2), Point(-1,2)) l3 = Line(Point(1, 0), Point(-1,0)) p1 = Point(0,0) p2 = Point(0, -2) p3 = Point(120, -12) parabola1 = Parabola(p1, l1) # parabola with parabola assert parabola1.intersection(parabola1) == [parabola1] assert parabola1.intersection(Parabola(p1, l2)) == [Point2D(-2, 0), Point2D(2, 0)] assert parabola1.intersection(Parabola(p2, l3)) == [Point2D(0, -1)] assert parabola1.intersection(Parabola(Point(16, 0), l1)) == [Point2D(8, 15)] assert parabola1.intersection(Parabola(Point(0, 16), l1)) == [Point2D(-6, 8), Point2D(6, 8)] assert parabola1.intersection(Parabola(p3, l3)) == [] # parabola with point assert parabola1.intersection(p1) == [] assert parabola1.intersection(Point2D(0, -1)) == [Point2D(0, -1)] assert parabola1.intersection(Point2D(4, 3)) == [Point2D(4, 3)] # parabola with line assert parabola1.intersection(Line(Point2D(-7, 3), Point(12, 3))) == [Point2D(-4, 3), Point2D(4, 3)] assert parabola1.intersection(Line(Point(-4, -1), Point(4, -1))) == [Point(0, -1)] assert parabola1.intersection(Line(Point(2, 0), Point(0, -2))) == [Point2D(2, 0)] raises(TypeError, lambda: parabola1.intersection(Line(Point(0, 0, 0), Point(1, 1, 1)))) # parabola with segment assert parabola1.intersection(Segment2D((-4, -5), (4, 3))) == [Point2D(0, -1), Point2D(4, 3)] assert parabola1.intersection(Segment2D((0, -5), (0, 6))) == [Point2D(0, -1)] assert parabola1.intersection(Segment2D((-12, -65), (14, -68))) == [] # parabola with ray assert parabola1.intersection(Ray2D((-4, -5), (4, 3))) == [Point2D(0, -1), Point2D(4, 3)] assert parabola1.intersection(Ray2D((0, 7), (1, 14))) == [Point2D(14 + 2*sqrt(57), 105 + 14*sqrt(57))] assert parabola1.intersection(Ray2D((0, 7), (0, 14))) == [] # parabola with ellipse/circle assert parabola1.intersection(Circle(p1, 2)) == [Point2D(-2, 0), Point2D(2, 0)] assert parabola1.intersection(Circle(p2, 1)) == [Point2D(0, -1), Point2D(0, -1)] assert parabola1.intersection(Ellipse(p2, 2, 1)) == [Point2D(0, -1), Point2D(0, -1)] assert parabola1.intersection(Ellipse(Point(0, 19), 5, 7)) == [] assert parabola1.intersection(Ellipse((0, 3), 12, 4)) == \ [Point2D(0, -1), Point2D(0, -1), Point2D(-4*sqrt(17)/3, Rational(59, 9)), Point2D(4*sqrt(17)/3, Rational(59, 9))] # parabola with unsupported type raises(TypeError, lambda: parabola1.intersection(2))
f719e9277d15ac5e44e35901c6c8802f4a5fe3fe77904312b16f2fce6ea31aa5
from sympy.external import import_module import os cin = import_module('clang.cindex', import_kwargs = {'fromlist': ['cindex']}) """ This module contains all the necessary Classes and Function used to Parse C and C++ code into SymPy expression The module serves as a backend for SymPyExpression to parse C code It is also dependent on Clang's AST and SymPy's Codegen AST. The module only supports the features currently supported by the Clang and codegen AST which will be updated as the development of codegen AST and this module progresses. You might find unexpected bugs and exceptions while using the module, feel free to report them to the SymPy Issue Tracker Features Supported ================== - Variable Declarations (integers and reals) - Assignment (using integer & floating literal and function calls) - Function Definitions and Declaration - Function Calls - Compound statements, Return statements Notes ===== The module is dependent on an external dependency which needs to be installed to use the features of this module. Clang: The C and C++ compiler which is used to extract an AST from the provided C source code. Refrences ========= .. [1] https://github.com/sympy/sympy/issues .. [2] https://clang.llvm.org/docs/ .. [3] https://clang.llvm.org/docs/IntroductionToTheClangAST.html """ if cin: from sympy.codegen.ast import (Variable, Integer, Float, FunctionPrototype, FunctionDefinition, FunctionCall, none, Return, Assignment, intc, int8, int16, int64, uint8, uint16, uint32, uint64, float32, float64, float80, aug_assign, bool_, While, CodeBlock) from sympy.codegen.cnodes import (PreDecrement, PostDecrement, PreIncrement, PostIncrement) from sympy.core import Add, Mod, Mul, Pow, Rel from sympy.logic.boolalg import And, as_Boolean, Not, Or from sympy.core.symbol import Symbol from sympy.core.sympify import sympify from sympy.logic.boolalg import (false, true) import sys import tempfile class BaseParser: """Base Class for the C parser""" def __init__(self): """Initializes the Base parser creating a Clang AST index""" self.index = cin.Index.create() def diagnostics(self, out): """Diagostics function for the Clang AST""" for diag in self.tu.diagnostics: print('%s %s (line %s, col %s) %s' % ( { 4: 'FATAL', 3: 'ERROR', 2: 'WARNING', 1: 'NOTE', 0: 'IGNORED', }[diag.severity], diag.location.file, diag.location.line, diag.location.column, diag.spelling ), file=out) class CCodeConverter(BaseParser): """The Code Convereter for Clang AST The converter object takes the C source code or file as input and converts them to SymPy Expressions. """ def __init__(self): """Initializes the code converter""" super().__init__() self._py_nodes = [] self._data_types = { "void": { cin.TypeKind.VOID: none }, "bool": { cin.TypeKind.BOOL: bool_ }, "int": { cin.TypeKind.SCHAR: int8, cin.TypeKind.SHORT: int16, cin.TypeKind.INT: intc, cin.TypeKind.LONG: int64, cin.TypeKind.UCHAR: uint8, cin.TypeKind.USHORT: uint16, cin.TypeKind.UINT: uint32, cin.TypeKind.ULONG: uint64 }, "float": { cin.TypeKind.FLOAT: float32, cin.TypeKind.DOUBLE: float64, cin.TypeKind.LONGDOUBLE: float80 } } def parse(self, filenames, flags): """Function to parse a file with C source code It takes the filename as an attribute and creates a Clang AST Translation Unit parsing the file. Then the transformation function is called on the transaltion unit, whose reults are collected into a list which is returned by the function. Parameters ========== filenames : string Path to the C file to be parsed flags: list Arguments to be passed to Clang while parsing the C code Returns ======= py_nodes: list A list of SymPy AST nodes """ filename = os.path.abspath(filenames) self.tu = self.index.parse( filename, args=flags, options=cin.TranslationUnit.PARSE_DETAILED_PROCESSING_RECORD ) for child in self.tu.cursor.get_children(): if child.kind == cin.CursorKind.VAR_DECL: self._py_nodes.append(self.transform(child)) elif (child.kind == cin.CursorKind.FUNCTION_DECL): self._py_nodes.append(self.transform(child)) else: pass return self._py_nodes def parse_str(self, source, flags): """Function to parse a string with C source code It takes the source code as an attribute, stores it in a temporary file and creates a Clang AST Translation Unit parsing the file. Then the transformation function is called on the transaltion unit, whose reults are collected into a list which is returned by the function. Parameters ========== source : string Path to the C file to be parsed flags: list Arguments to be passed to Clang while parsing the C code Returns ======= py_nodes: list A list of SymPy AST nodes """ file = tempfile.NamedTemporaryFile(mode = 'w+', suffix = '.cpp') file.write(source) file.seek(0) self.tu = self.index.parse( file.name, args=flags, options=cin.TranslationUnit.PARSE_DETAILED_PROCESSING_RECORD ) file.close() for child in self.tu.cursor.get_children(): if child.kind == cin.CursorKind.VAR_DECL: self._py_nodes.append(self.transform(child)) elif (child.kind == cin.CursorKind.FUNCTION_DECL): self._py_nodes.append(self.transform(child)) else: pass return self._py_nodes def transform(self, node): """Transformation Function for Clang AST nodes It determines the kind of node and calls the respective transformation function for that node. Raises ====== NotImplementedError : if the transformation for the provided node is not implemented """ try: handler = getattr(self, 'transform_%s' % node.kind.name.lower()) except AttributeError: print( "Ignoring node of type %s (%s)" % ( node.kind, ' '.join( t.spelling for t in node.get_tokens()) ), file=sys.stderr ) handler = None if handler: result = handler(node) return result def transform_var_decl(self, node): """Transformation Function for Variable Declaration Used to create nodes for variable declarations and assignments with values or function call for the respective nodes in the clang AST Returns ======= A variable node as Declaration, with the initial value if given Raises ====== NotImplementedError : if called for data types not currently implemented Notes ===== The function currently supports following data types: Boolean: bool, _Bool Integer: 8-bit: signed char and unsigned char 16-bit: short, short int, signed short, signed short int, unsigned short, unsigned short int 32-bit: int, signed int, unsigned int 64-bit: long, long int, signed long, signed long int, unsigned long, unsigned long int Floating point: Single Precision: float Double Precision: double Extended Precision: long double """ if node.type.kind in self._data_types["int"]: type = self._data_types["int"][node.type.kind] elif node.type.kind in self._data_types["float"]: type = self._data_types["float"][node.type.kind] elif node.type.kind in self._data_types["bool"]: type = self._data_types["bool"][node.type.kind] else: raise NotImplementedError("Only bool, int " "and float are supported") try: children = node.get_children() child = next(children) #ignoring namespace and type details for the variable while child.kind == cin.CursorKind.NAMESPACE_REF: child = next(children) while child.kind == cin.CursorKind.TYPE_REF: child = next(children) val = self.transform(child) supported_rhs = [ cin.CursorKind.INTEGER_LITERAL, cin.CursorKind.FLOATING_LITERAL, cin.CursorKind.UNEXPOSED_EXPR, cin.CursorKind.BINARY_OPERATOR, cin.CursorKind.PAREN_EXPR, cin.CursorKind.UNARY_OPERATOR, cin.CursorKind.CXX_BOOL_LITERAL_EXPR ] if child.kind in supported_rhs: if isinstance(val, str): value = Symbol(val) elif isinstance(val, bool): if node.type.kind in self._data_types["int"]: value = Integer(0) if val == False else Integer(1) elif node.type.kind in self._data_types["float"]: value = Float(0.0) if val == False else Float(1.0) elif node.type.kind in self._data_types["bool"]: value = sympify(val) elif isinstance(val, (Integer, int, Float, float)): if node.type.kind in self._data_types["int"]: value = Integer(val) elif node.type.kind in self._data_types["float"]: value = Float(val) elif node.type.kind in self._data_types["bool"]: value = sympify(bool(val)) else: value = val return Variable( node.spelling ).as_Declaration( type = type, value = value ) elif child.kind == cin.CursorKind.CALL_EXPR: return Variable( node.spelling ).as_Declaration( value = val ) else: raise NotImplementedError("Given " "variable declaration \"{}\" " "is not possible to parse yet!" .format(" ".join( t.spelling for t in node.get_tokens() ) )) except StopIteration: return Variable( node.spelling ).as_Declaration( type = type ) def transform_function_decl(self, node): """Transformation Function For Function Declaration Used to create nodes for function declarations and definitions for the respective nodes in the clang AST Returns ======= function : Codegen AST node - FunctionPrototype node if function body is not present - FunctionDefinition node if the function body is present """ if node.result_type.kind in self._data_types["int"]: ret_type = self._data_types["int"][node.result_type.kind] elif node.result_type.kind in self._data_types["float"]: ret_type = self._data_types["float"][node.result_type.kind] elif node.result_type.kind in self._data_types["bool"]: ret_type = self._data_types["bool"][node.result_type.kind] elif node.result_type.kind in self._data_types["void"]: ret_type = self._data_types["void"][node.result_type.kind] else: raise NotImplementedError("Only void, bool, int " "and float are supported") body = [] param = [] try: children = node.get_children() child = next(children) # If the node has any children, the first children will be the # return type and namespace for the function declaration. These # nodes can be ignored. while child.kind == cin.CursorKind.NAMESPACE_REF: child = next(children) while child.kind == cin.CursorKind.TYPE_REF: child = next(children) # Subsequent nodes will be the parameters for the function. try: while True: decl = self.transform(child) if (child.kind == cin.CursorKind.PARM_DECL): param.append(decl) elif (child.kind == cin.CursorKind.COMPOUND_STMT): for val in decl: body.append(val) else: body.append(decl) child = next(children) except StopIteration: pass except StopIteration: pass if body == []: function = FunctionPrototype( return_type = ret_type, name = node.spelling, parameters = param ) else: function = FunctionDefinition( return_type = ret_type, name = node.spelling, parameters = param, body = body ) return function def transform_parm_decl(self, node): """Transformation function for Parameter Declaration Used to create parameter nodes for the required functions for the respective nodes in the clang AST Returns ======= param : Codegen AST Node Variable node with the value and type of the variable Raises ====== ValueError if multiple children encountered in the parameter node """ if node.type.kind in self._data_types["int"]: type = self._data_types["int"][node.type.kind] elif node.type.kind in self._data_types["float"]: type = self._data_types["float"][node.type.kind] elif node.type.kind in self._data_types["bool"]: type = self._data_types["bool"][node.type.kind] else: raise NotImplementedError("Only bool, int " "and float are supported") try: children = node.get_children() child = next(children) # Any namespace nodes can be ignored while child.kind in [cin.CursorKind.NAMESPACE_REF, cin.CursorKind.TYPE_REF, cin.CursorKind.TEMPLATE_REF]: child = next(children) # If there is a child, it is the default value of the parameter. lit = self.transform(child) if node.type.kind in self._data_types["int"]: val = Integer(lit) elif node.type.kind in self._data_types["float"]: val = Float(lit) elif node.type.kind in self._data_types["bool"]: val = sympify(bool(lit)) else: raise NotImplementedError("Only bool, int " "and float are supported") param = Variable( node.spelling ).as_Declaration( type = type, value = val ) except StopIteration: param = Variable( node.spelling ).as_Declaration( type = type ) try: self.transform(next(children)) raise ValueError("Can't handle multiple children on parameter") except StopIteration: pass return param def transform_integer_literal(self, node): """Transformation function for integer literal Used to get the value and type of the given integer literal. Returns ======= val : list List with two arguments type and Value type contains the type of the integer value contains the value stored in the variable Notes ===== Only Base Integer type supported for now """ try: value = next(node.get_tokens()).spelling except StopIteration: # No tokens value = node.literal return int(value) def transform_floating_literal(self, node): """Transformation function for floating literal Used to get the value and type of the given floating literal. Returns ======= val : list List with two arguments type and Value type contains the type of float value contains the value stored in the variable Notes ===== Only Base Float type supported for now """ try: value = next(node.get_tokens()).spelling except (StopIteration, ValueError): # No tokens value = node.literal return float(value) def transform_string_literal(self, node): #TODO: No string type in AST #type = #try: # value = next(node.get_tokens()).spelling #except (StopIteration, ValueError): # No tokens # value = node.literal #val = [type, value] #return val pass def transform_character_literal(self, node): """Transformation function for character literal Used to get the value of the given character literal. Returns ======= val : int val contains the ascii value of the character literal Notes ===== Only for cases where character is assigned to a integer value, since character literal is not in SymPy AST """ try: value = next(node.get_tokens()).spelling except (StopIteration, ValueError): # No tokens value = node.literal return ord(str(value[1])) def transform_cxx_bool_literal_expr(self, node): """Transformation function for boolean literal Used to get the value of the given boolean literal. Returns ======= value : bool value contains the boolean value of the variable """ try: value = next(node.get_tokens()).spelling except (StopIteration, ValueError): value = node.literal return True if value == 'true' else False def transform_unexposed_decl(self,node): """Transformation function for unexposed declarations""" pass def transform_unexposed_expr(self, node): """Transformation function for unexposed expression Unexposed expressions are used to wrap float, double literals and expressions Returns ======= expr : Codegen AST Node the result from the wrapped expression None : NoneType No childs are found for the node Raises ====== ValueError if the expression contains multiple children """ # Ignore unexposed nodes; pass whatever is the first # (and should be only) child unaltered. try: children = node.get_children() expr = self.transform(next(children)) except StopIteration: return None try: next(children) raise ValueError("Unexposed expression has > 1 children.") except StopIteration: pass return expr def transform_decl_ref_expr(self, node): """Returns the name of the declaration reference""" return node.spelling def transform_call_expr(self, node): """Transformation function for a call expression Used to create function call nodes for the function calls present in the C code Returns ======= FunctionCall : Codegen AST Node FunctionCall node with parameters if any parameters are present """ param = [] children = node.get_children() child = next(children) while child.kind == cin.CursorKind.NAMESPACE_REF: child = next(children) while child.kind == cin.CursorKind.TYPE_REF: child = next(children) first_child = self.transform(child) try: for child in children: arg = self.transform(child) if (child.kind == cin.CursorKind.INTEGER_LITERAL): param.append(Integer(arg)) elif (child.kind == cin.CursorKind.FLOATING_LITERAL): param.append(Float(arg)) else: param.append(arg) return FunctionCall(first_child, param) except StopIteration: return FunctionCall(first_child) def transform_return_stmt(self, node): """Returns the Return Node for a return statement""" return Return(next(node.get_children()).spelling) def transform_compound_stmt(self, node): """Transformation function for compond statemets Returns ======= expr : list list of Nodes for the expressions present in the statement None : NoneType if the compound statement is empty """ try: expr = [] children = node.get_children() for child in children: expr.append(self.transform(child)) except StopIteration: return None return expr def transform_decl_stmt(self, node): """Transformation function for declaration statements These statements are used to wrap different kinds of declararions like variable or function declaration The function calls the transformer function for the child of the given node Returns ======= statement : Codegen AST Node contains the node returned by the children node for the type of declaration Raises ====== ValueError if multiple children present """ try: children = node.get_children() statement = self.transform(next(children)) except StopIteration: pass try: self.transform(next(children)) raise ValueError("Don't know how to handle multiple statements") except StopIteration: pass return statement def transform_paren_expr(self, node): """Transformation function for Parenthesized expressions Returns the result from its children nodes """ return self.transform(next(node.get_children())) def transform_compound_assignment_operator(self, node): """Transformation function for handling shorthand operators Returns ======= augmented_assignment_expression: Codegen AST node shorthand assignment expression represented as Codegen AST Raises ====== NotImplementedError If the shorthand operator for bitwise operators (~=, ^=, &=, |=, <<=, >>=) is encountered """ return self.transform_binary_operator(node) def transform_unary_operator(self, node): """Transformation function for handling unary operators Returns ======= unary_expression: Codegen AST node simplified unary expression represented as Codegen AST Raises ====== NotImplementedError If dereferencing operator(*), address operator(&) or bitwise NOT operator(~) is encountered """ # supported operators list operators_list = ['+', '-', '++', '--', '!'] tokens = [token for token in node.get_tokens()] # it can be either pre increment/decrement or any other operator from the list if tokens[0].spelling in operators_list: child = self.transform(next(node.get_children())) # (decl_ref) e.g.; int a = ++b; or simply ++b; if isinstance(child, str): if tokens[0].spelling == '+': return Symbol(child) if tokens[0].spelling == '-': return Mul(Symbol(child), -1) if tokens[0].spelling == '++': return PreIncrement(Symbol(child)) if tokens[0].spelling == '--': return PreDecrement(Symbol(child)) if tokens[0].spelling == '!': return Not(Symbol(child)) # e.g.; int a = -1; or int b = -(1 + 2); else: if tokens[0].spelling == '+': return child if tokens[0].spelling == '-': return Mul(child, -1) if tokens[0].spelling == '!': return Not(sympify(bool(child))) # it can be either post increment/decrement # since variable name is obtained in token[0].spelling elif tokens[1].spelling in ['++', '--']: child = self.transform(next(node.get_children())) if tokens[1].spelling == '++': return PostIncrement(Symbol(child)) if tokens[1].spelling == '--': return PostDecrement(Symbol(child)) else: raise NotImplementedError("Dereferencing operator, " "Address operator and bitwise NOT operator " "have not been implemented yet!") def transform_binary_operator(self, node): """Transformation function for handling binary operators Returns ======= binary_expression: Codegen AST node simplified binary expression represented as Codegen AST Raises ====== NotImplementedError If a bitwise operator or unary operator(which is a child of any binary operator in Clang AST) is encountered """ # get all the tokens of assignment # and store it in the tokens list tokens = [token for token in node.get_tokens()] # supported operators list operators_list = ['+', '-', '*', '/', '%','=', '>', '>=', '<', '<=', '==', '!=', '&&', '||', '+=', '-=', '*=', '/=', '%='] # this stack will contain variable content # and type of variable in the rhs combined_variables_stack = [] # this stack will contain operators # to be processed in the rhs operators_stack = [] # iterate through every token for token in tokens: # token is either '(', ')' or # any of the supported operators from the operator list if token.kind == cin.TokenKind.PUNCTUATION: # push '(' to the operators stack if token.spelling == '(': operators_stack.append('(') elif token.spelling == ')': # keep adding the expression to the # combined variables stack unless # '(' is found while (operators_stack and operators_stack[-1] != '('): if len(combined_variables_stack) < 2: raise NotImplementedError( "Unary operators as a part of " "binary operators is not " "supported yet!") rhs = combined_variables_stack.pop() lhs = combined_variables_stack.pop() operator = operators_stack.pop() combined_variables_stack.append( self.perform_operation( lhs, rhs, operator)) # pop '(' operators_stack.pop() # token is an operator (supported) elif token.spelling in operators_list: while (operators_stack and self.priority_of(token.spelling) <= self.priority_of( operators_stack[-1])): if len(combined_variables_stack) < 2: raise NotImplementedError( "Unary operators as a part of " "binary operators is not " "supported yet!") rhs = combined_variables_stack.pop() lhs = combined_variables_stack.pop() operator = operators_stack.pop() combined_variables_stack.append( self.perform_operation( lhs, rhs, operator)) # push current operator operators_stack.append(token.spelling) # token is a bitwise operator elif token.spelling in ['&', '|', '^', '<<', '>>']: raise NotImplementedError( "Bitwise operator has not been " "implemented yet!") # token is a shorthand bitwise operator elif token.spelling in ['&=', '|=', '^=', '<<=', '>>=']: raise NotImplementedError( "Shorthand bitwise operator has not been " "implemented yet!") else: raise NotImplementedError( "Given token {} is not implemented yet!" .format(token.spelling)) # token is an identifier(variable) elif token.kind == cin.TokenKind.IDENTIFIER: combined_variables_stack.append( [token.spelling, 'identifier']) # token is a literal elif token.kind == cin.TokenKind.LITERAL: combined_variables_stack.append( [token.spelling, 'literal']) # token is a keyword, either true or false elif (token.kind == cin.TokenKind.KEYWORD and token.spelling in ['true', 'false']): combined_variables_stack.append( [token.spelling, 'boolean']) else: raise NotImplementedError( "Given token {} is not implemented yet!" .format(token.spelling)) # process remaining operators while operators_stack: if len(combined_variables_stack) < 2: raise NotImplementedError( "Unary operators as a part of " "binary operators is not " "supported yet!") rhs = combined_variables_stack.pop() lhs = combined_variables_stack.pop() operator = operators_stack.pop() combined_variables_stack.append( self.perform_operation(lhs, rhs, operator)) return combined_variables_stack[-1][0] def priority_of(self, op): """To get the priority of given operator""" if op in ['=', '+=', '-=', '*=', '/=', '%=']: return 1 if op in ['&&', '||']: return 2 if op in ['<', '<=', '>', '>=', '==', '!=']: return 3 if op in ['+', '-']: return 4 if op in ['*', '/', '%']: return 5 return 0 def perform_operation(self, lhs, rhs, op): """Performs operation supported by the SymPy core Returns ======= combined_variable: list contains variable content and type of variable """ lhs_value = self.get_expr_for_operand(lhs) rhs_value = self.get_expr_for_operand(rhs) if op == '+': return [Add(lhs_value, rhs_value), 'expr'] if op == '-': return [Add(lhs_value, -rhs_value), 'expr'] if op == '*': return [Mul(lhs_value, rhs_value), 'expr'] if op == '/': return [Mul(lhs_value, Pow(rhs_value, Integer(-1))), 'expr'] if op == '%': return [Mod(lhs_value, rhs_value), 'expr'] if op in ['<', '<=', '>', '>=', '==', '!=']: return [Rel(lhs_value, rhs_value, op), 'expr'] if op == '&&': return [And(as_Boolean(lhs_value), as_Boolean(rhs_value)), 'expr'] if op == '||': return [Or(as_Boolean(lhs_value), as_Boolean(rhs_value)), 'expr'] if op == '=': return [Assignment(Variable(lhs_value), rhs_value), 'expr'] if op in ['+=', '-=', '*=', '/=', '%=']: return [aug_assign(Variable(lhs_value), op[0], rhs_value), 'expr'] def get_expr_for_operand(self, combined_variable): """Gives out SymPy Codegen AST node AST node returned is corresponding to combined variable passed.Combined variable contains variable content and type of variable """ if combined_variable[1] == 'identifier': return Symbol(combined_variable[0]) if combined_variable[1] == 'literal': if '.' in combined_variable[0]: return Float(float(combined_variable[0])) else: return Integer(int(combined_variable[0])) if combined_variable[1] == 'expr': return combined_variable[0] if combined_variable[1] == 'boolean': return true if combined_variable[0] == 'true' else false def transform_null_stmt(self, node): """Handles Null Statement and returns None""" return none def transform_while_stmt(self, node): """Transformation function for handling while statement Returns ======= while statement : Codegen AST Node contains the while statement node having condition and statement block """ children = node.get_children() condition = self.transform(next(children)) statements = self.transform(next(children)) if isinstance(statements, list): statement_block = CodeBlock(*statements) else: statement_block = CodeBlock(statements) return While(condition, statement_block) else: class CCodeConverter(): # type: ignore def __init__(self, *args, **kwargs): raise ImportError("Module not Installed") def parse_c(source): """Function for converting a C source code The function reads the source code present in the given file and parses it to give out SymPy Expressions Returns ======= src : list List of Python expression strings """ converter = CCodeConverter() if os.path.exists(source): src = converter.parse(source, flags = []) else: src = converter.parse_str(source, flags = []) return src
0f400a56f29bc7f9e69b763e7e33f6419c224569269fe0d192e0e990d86dff26
from sympy.core.numbers import Rational from sympy.core.singleton import S from sympy.core.symbol import symbols from sympy.parsing.ast_parser import parse_expr from sympy.testing.pytest import raises from sympy.core.sympify import SympifyError import warnings def test_parse_expr(): a, b = symbols('a, b') # tests issue_16393 assert parse_expr('a + b', {}) == a + b raises(SympifyError, lambda: parse_expr('a + ', {})) # tests Transform.visit_Num assert parse_expr('1 + 2', {}) == S(3) assert parse_expr('1 + 2.0', {}) == S(3.0) # tests Transform.visit_Name assert parse_expr('Rational(1, 2)', {}) == S(1)/2 assert parse_expr('a', {'a': a}) == a # tests issue_23092 with warnings.catch_warnings(): warnings.simplefilter('error') assert parse_expr('6 * 7', {}) == S(42) # Note: The test below can be removed when support for Python 3.7 is # dropped. This test exists to ensure that the visit_Num function # exists for Python 3.7, because in 3.7, Python didn't use the # visit_Constant to create AST Nodes yet. test_expr = parse_expr('1 / 3', {}) assert test_expr == S(1)/3 # sanity check assert isinstance(test_expr, Rational)
a722ba739ae14911ce22e870b71257d76e00e588cd18bc7dd31a7d379e0de0f9
# -*- coding: utf-8 -*- import sys import builtins import types from sympy.assumptions import Q from sympy.core import Symbol, Function, Float, Rational, Integer, I, Mul, Pow, Eq from sympy.functions import exp, factorial, factorial2, sin, Min, Max from sympy.logic import And from sympy.series import Limit from sympy.testing.pytest import raises, skip from sympy.parsing.sympy_parser import ( parse_expr, standard_transformations, rationalize, TokenError, split_symbols, implicit_multiplication, convert_equals_signs, convert_xor, function_exponentiation, lambda_notation, auto_symbol, repeated_decimals, implicit_multiplication_application, auto_number, factorial_notation, implicit_application, _transformation, T ) def test_sympy_parser(): x = Symbol('x') inputs = { '2*x': 2 * x, '3.00': Float(3), '22/7': Rational(22, 7), '2+3j': 2 + 3*I, 'exp(x)': exp(x), 'x!': factorial(x), 'x!!': factorial2(x), '(x + 1)! - 1': factorial(x + 1) - 1, '3.[3]': Rational(10, 3), '.0[3]': Rational(1, 30), '3.2[3]': Rational(97, 30), '1.3[12]': Rational(433, 330), '1 + 3.[3]': Rational(13, 3), '1 + .0[3]': Rational(31, 30), '1 + 3.2[3]': Rational(127, 30), '.[0011]': Rational(1, 909), '0.1[00102] + 1': Rational(366697, 333330), '1.[0191]': Rational(10190, 9999), '10!': 3628800, '-(2)': -Integer(2), '[-1, -2, 3]': [Integer(-1), Integer(-2), Integer(3)], 'Symbol("x").free_symbols': x.free_symbols, "S('S(3).n(n=3)')": 3.00, 'factorint(12, visual=True)': Mul( Pow(2, 2, evaluate=False), Pow(3, 1, evaluate=False), evaluate=False), 'Limit(sin(x), x, 0, dir="-")': Limit(sin(x), x, 0, dir='-'), 'Q.even(x)': Q.even(x), } for text, result in inputs.items(): assert parse_expr(text) == result raises(TypeError, lambda: parse_expr('x', standard_transformations)) raises(TypeError, lambda: parse_expr('x', transformations=lambda x,y: 1)) raises(TypeError, lambda: parse_expr('x', transformations=(lambda x,y: 1,))) raises(TypeError, lambda: parse_expr('x', transformations=((),))) raises(TypeError, lambda: parse_expr('x', {}, [], [])) raises(TypeError, lambda: parse_expr('x', [], [], {})) raises(TypeError, lambda: parse_expr('x', [], [], {})) def test_rationalize(): inputs = { '0.123': Rational(123, 1000) } transformations = standard_transformations + (rationalize,) for text, result in inputs.items(): assert parse_expr(text, transformations=transformations) == result def test_factorial_fail(): inputs = ['x!!!', 'x!!!!', '(!)'] for text in inputs: try: parse_expr(text) assert False except TokenError: assert True def test_repeated_fail(): inputs = ['1[1]', '.1e1[1]', '0x1[1]', '1.1j[1]', '1.1[1 + 1]', '0.1[[1]]', '0x1.1[1]'] # All are valid Python, so only raise TypeError for invalid indexing for text in inputs: raises(TypeError, lambda: parse_expr(text)) inputs = ['0.1[', '0.1[1', '0.1[]'] for text in inputs: raises((TokenError, SyntaxError), lambda: parse_expr(text)) def test_repeated_dot_only(): assert parse_expr('.[1]') == Rational(1, 9) assert parse_expr('1 + .[1]') == Rational(10, 9) def test_local_dict(): local_dict = { 'my_function': lambda x: x + 2 } inputs = { 'my_function(2)': Integer(4) } for text, result in inputs.items(): assert parse_expr(text, local_dict=local_dict) == result def test_local_dict_split_implmult(): t = standard_transformations + (split_symbols, implicit_multiplication,) w = Symbol('w', real=True) y = Symbol('y') assert parse_expr('yx', local_dict={'x':w}, transformations=t) == y*w def test_local_dict_symbol_to_fcn(): x = Symbol('x') d = {'foo': Function('bar')} assert parse_expr('foo(x)', local_dict=d) == d['foo'](x) d = {'foo': Symbol('baz')} raises(TypeError, lambda: parse_expr('foo(x)', local_dict=d)) def test_global_dict(): global_dict = { 'Symbol': Symbol } inputs = { 'Q & S': And(Symbol('Q'), Symbol('S')) } for text, result in inputs.items(): assert parse_expr(text, global_dict=global_dict) == result def test_no_globals(): # Replicate creating the default global_dict: default_globals = {} exec('from sympy import *', default_globals) builtins_dict = vars(builtins) for name, obj in builtins_dict.items(): if isinstance(obj, types.BuiltinFunctionType): default_globals[name] = obj default_globals['max'] = Max default_globals['min'] = Min # Need to include Symbol or parse_expr will not work: default_globals.pop('Symbol') global_dict = {'Symbol':Symbol} for name in default_globals: obj = parse_expr(name, global_dict=global_dict) assert obj == Symbol(name) def test_issue_2515(): raises(TokenError, lambda: parse_expr('(()')) raises(TokenError, lambda: parse_expr('"""')) def test_issue_7663(): x = Symbol('x') e = '2*(x+1)' assert parse_expr(e, evaluate=0) == parse_expr(e, evaluate=False) assert parse_expr(e, evaluate=0).equals(2*(x+1)) def test_recursive_evaluate_false_10560(): inputs = { '4*-3' : '4*-3', '-4*3' : '(-4)*3', "-2*x*y": '(-2)*x*y', "x*-4*x": "x*(-4)*x" } for text, result in inputs.items(): assert parse_expr(text, evaluate=False) == parse_expr(result, evaluate=False) def test_function_evaluate_false(): inputs = [ 'Abs(0)', 'im(0)', 're(0)', 'sign(0)', 'arg(0)', 'conjugate(0)', 'acos(0)', 'acot(0)', 'acsc(0)', 'asec(0)', 'asin(0)', 'atan(0)', 'acosh(0)', 'acoth(0)', 'acsch(0)', 'asech(0)', 'asinh(0)', 'atanh(0)', 'cos(0)', 'cot(0)', 'csc(0)', 'sec(0)', 'sin(0)', 'tan(0)', 'cosh(0)', 'coth(0)', 'csch(0)', 'sech(0)', 'sinh(0)', 'tanh(0)', 'exp(0)', 'log(0)', 'sqrt(0)', ] for case in inputs: expr = parse_expr(case, evaluate=False) assert case == str(expr) != str(expr.doit()) assert str(parse_expr('ln(0)', evaluate=False)) == 'log(0)' assert str(parse_expr('cbrt(0)', evaluate=False)) == '0**(1/3)' def test_issue_10773(): inputs = { '-10/5': '(-10)/5', '-10/-5' : '(-10)/(-5)', } for text, result in inputs.items(): assert parse_expr(text, evaluate=False) == parse_expr(result, evaluate=False) def test_split_symbols(): transformations = standard_transformations + \ (split_symbols, implicit_multiplication,) x = Symbol('x') y = Symbol('y') xy = Symbol('xy') assert parse_expr("xy") == xy assert parse_expr("xy", transformations=transformations) == x*y def test_split_symbols_function(): transformations = standard_transformations + \ (split_symbols, implicit_multiplication,) x = Symbol('x') y = Symbol('y') a = Symbol('a') f = Function('f') assert parse_expr("ay(x+1)", transformations=transformations) == a*y*(x+1) assert parse_expr("af(x+1)", transformations=transformations, local_dict={'f':f}) == a*f(x+1) def test_functional_exponent(): t = standard_transformations + (convert_xor, function_exponentiation) x = Symbol('x') y = Symbol('y') a = Symbol('a') yfcn = Function('y') assert parse_expr("sin^2(x)", transformations=t) == (sin(x))**2 assert parse_expr("sin^y(x)", transformations=t) == (sin(x))**y assert parse_expr("exp^y(x)", transformations=t) == (exp(x))**y assert parse_expr("E^y(x)", transformations=t) == exp(yfcn(x)) assert parse_expr("a^y(x)", transformations=t) == a**(yfcn(x)) def test_match_parentheses_implicit_multiplication(): transformations = standard_transformations + \ (implicit_multiplication,) raises(TokenError, lambda: parse_expr('(1,2),(3,4]',transformations=transformations)) def test_convert_equals_signs(): transformations = standard_transformations + \ (convert_equals_signs, ) x = Symbol('x') y = Symbol('y') assert parse_expr("1*2=x", transformations=transformations) == Eq(2, x) assert parse_expr("y = x", transformations=transformations) == Eq(y, x) assert parse_expr("(2*y = x) = False", transformations=transformations) == Eq(Eq(2*y, x), False) def test_parse_function_issue_3539(): x = Symbol('x') f = Function('f') assert parse_expr('f(x)') == f(x) def test_split_symbols_numeric(): transformations = ( standard_transformations + (implicit_multiplication_application,)) n = Symbol('n') expr1 = parse_expr('2**n * 3**n') expr2 = parse_expr('2**n3**n', transformations=transformations) assert expr1 == expr2 == 2**n*3**n expr1 = parse_expr('n12n34', transformations=transformations) assert expr1 == n*12*n*34 def test_unicode_names(): assert parse_expr('α') == Symbol('α') def test_python3_features(): # Make sure the tokenizer can handle Python 3-only features if sys.version_info < (3, 7): skip("test_python3_features requires Python 3.7 or newer") assert parse_expr("123_456") == 123456 assert parse_expr("1.2[3_4]") == parse_expr("1.2[34]") == Rational(611, 495) assert parse_expr("1.2[012_012]") == parse_expr("1.2[012012]") == Rational(400, 333) assert parse_expr('.[3_4]') == parse_expr('.[34]') == Rational(34, 99) assert parse_expr('.1[3_4]') == parse_expr('.1[34]') == Rational(133, 990) assert parse_expr('123_123.123_123[3_4]') == parse_expr('123123.123123[34]') == Rational(12189189189211, 99000000) def test_issue_19501(): x = Symbol('x') eq = parse_expr('E**x(1+x)', local_dict={'x': x}, transformations=( standard_transformations + (implicit_multiplication_application,))) assert eq.free_symbols == {x} def test_parsing_definitions(): from sympy.abc import x assert len(_transformation) == 12 # if this changes, extend below assert _transformation[0] == lambda_notation assert _transformation[1] == auto_symbol assert _transformation[2] == repeated_decimals assert _transformation[3] == auto_number assert _transformation[4] == factorial_notation assert _transformation[5] == implicit_multiplication_application assert _transformation[6] == convert_xor assert _transformation[7] == implicit_application assert _transformation[8] == implicit_multiplication assert _transformation[9] == convert_equals_signs assert _transformation[10] == function_exponentiation assert _transformation[11] == rationalize assert T[:5] == T[0,1,2,3,4] == standard_transformations t = _transformation assert T[-1, 0] == (t[len(t) - 1], t[0]) assert T[:5, 8] == standard_transformations + (t[8],) assert parse_expr('0.3x^2', transformations='all') == 3*x**2/10 assert parse_expr('sin 3x', transformations='implicit') == sin(3*x) def test_builtins(): cases = [ ('abs(x)', 'Abs(x)'), ('max(x, y)', 'Max(x, y)'), ('min(x, y)', 'Min(x, y)'), ('pow(x, y)', 'Pow(x, y)'), ] for built_in_func_call, sympy_func_call in cases: assert parse_expr(built_in_func_call) == parse_expr(sympy_func_call) assert str(parse_expr('pow(38, -1, 97)')) == '23' def test_issue_22822(): raises(ValueError, lambda: parse_expr('x', {'': 1})) data = {'some_parameter': None} assert parse_expr('some_parameter is None', data) is True
9c2602f62c2f328f11f41a0d28399e7a110bc226141cdbf440390332d1b19915
from sympy import sin, Function, symbols, Dummy, Lambda, cos from sympy.parsing.mathematica import mathematica, MathematicaParser from sympy.core.sympify import sympify from sympy.abc import n, w, x, y, z from sympy.testing.pytest import raises def test_mathematica(): d = { '- 6x': '-6*x', 'Sin[x]^2': 'sin(x)**2', '2(x-1)': '2*(x-1)', '3y+8': '3*y+8', 'ArcSin[2x+9(4-x)^2]/x': 'asin(2*x+9*(4-x)**2)/x', 'x+y': 'x+y', '355/113': '355/113', '2.718281828': '2.718281828', 'Sin[12]': 'sin(12)', 'Exp[Log[4]]': 'exp(log(4))', '(x+1)(x+3)': '(x+1)*(x+3)', 'Cos[ArcCos[3.6]]': 'cos(acos(3.6))', 'Cos[x]==Sin[y]': 'Eq(cos(x), sin(y))', '2*Sin[x+y]': '2*sin(x+y)', 'Sin[x]+Cos[y]': 'sin(x)+cos(y)', 'Sin[Cos[x]]': 'sin(cos(x))', '2*Sqrt[x+y]': '2*sqrt(x+y)', # Test case from the issue 4259 '+Sqrt[2]': 'sqrt(2)', '-Sqrt[2]': '-sqrt(2)', '-1/Sqrt[2]': '-1/sqrt(2)', '-(1/Sqrt[3])': '-(1/sqrt(3))', '1/(2*Sqrt[5])': '1/(2*sqrt(5))', 'Mod[5,3]': 'Mod(5,3)', '-Mod[5,3]': '-Mod(5,3)', '(x+1)y': '(x+1)*y', 'x(y+1)': 'x*(y+1)', 'Sin[x]Cos[y]': 'sin(x)*cos(y)', 'Sin[x]^2Cos[y]^2': 'sin(x)**2*cos(y)**2', 'Cos[x]^2(1 - Cos[y]^2)': 'cos(x)**2*(1-cos(y)**2)', 'x y': 'x*y', 'x y': 'x*y', '2 x': '2*x', 'x 8': 'x*8', '2 8': '2*8', '4.x': '4.*x', '4. 3': '4.*3', '4. 3.': '4.*3.', '1 2 3': '1*2*3', ' - 2 * Sqrt[ 2 3 * ( 1 + 5 ) ] ': '-2*sqrt(2*3*(1+5))', 'Log[2,4]': 'log(4,2)', 'Log[Log[2,4],4]': 'log(4,log(4,2))', 'Exp[Sqrt[2]^2Log[2, 8]]': 'exp(sqrt(2)**2*log(8,2))', 'ArcSin[Cos[0]]': 'asin(cos(0))', 'Log2[16]': 'log(16,2)', 'Max[1,-2,3,-4]': 'Max(1,-2,3,-4)', 'Min[1,-2,3]': 'Min(1,-2,3)', 'Exp[I Pi/2]': 'exp(I*pi/2)', 'ArcTan[x,y]': 'atan2(y,x)', 'Pochhammer[x,y]': 'rf(x,y)', 'ExpIntegralEi[x]': 'Ei(x)', 'SinIntegral[x]': 'Si(x)', 'CosIntegral[x]': 'Ci(x)', 'AiryAi[x]': 'airyai(x)', 'AiryAiPrime[5]': 'airyaiprime(5)', 'AiryBi[x]': 'airybi(x)', 'AiryBiPrime[7]': 'airybiprime(7)', 'LogIntegral[4]': ' li(4)', 'PrimePi[7]': 'primepi(7)', 'Prime[5]': 'prime(5)', 'PrimeQ[5]': 'isprime(5)' } for e in d: assert mathematica(e) == sympify(d[e]) # The parsed form of this expression should not evaluate the Lambda object: assert mathematica("Sin[#]^2 + Cos[#]^2 &[x]") == sin(x)**2 + cos(x)**2 d1, d2, d3 = symbols("d1:4", cls=Dummy) assert mathematica("Sin[#] + Cos[#3] &").dummy_eq(Lambda((d1, d2, d3), sin(d1) + cos(d3))) assert mathematica("Sin[#^2] &").dummy_eq(Lambda(d1, sin(d1**2))) assert mathematica("Function[x, x^3]") == Lambda(x, x**3) assert mathematica("Function[{x, y}, x^2 + y^2]") == Lambda((x, y), x**2+y**2) def test_parser_mathematica_tokenizer(): parser = MathematicaParser() chain = lambda expr: parser._from_tokens_to_fullformlist(parser._from_mathematica_to_tokens(expr)) # Basic patterns assert chain("x") == "x" assert chain("42") == "42" assert chain(".2") == ".2" assert chain("+x") == "x" assert chain("-1") == "-1" assert chain("- 3") == "-3" assert chain("+Sin[x]") == ["Sin", "x"] assert chain("-Sin[x]") == ["Times", "-1", ["Sin", "x"]] assert chain("x(a+1)") == ["Times", "x", ["Plus", "a", "1"]] assert chain("(x)") == "x" assert chain("(+x)") == "x" assert chain("-a") == ["Times", "-1", "a"] assert chain("(-x)") == ["Times", "-1", "x"] assert chain("(x + y)") == ["Plus", "x", "y"] assert chain("3 + 4") == ["Plus", "3", "4"] assert chain("a - 3") == ["Plus", "a", "-3"] assert chain("a - b") == ["Plus", "a", ["Times", "-1", "b"]] assert chain("7 * 8") == ["Times", "7", "8"] assert chain("a + b*c") == ["Plus", "a", ["Times", "b", "c"]] assert chain("a + b* c* d + 2 * e") == ["Plus", "a", ["Times", "b", "c", "d"], ["Times", "2", "e"]] assert chain("a / b") == ["Times", "a", ["Power", "b", "-1"]] # Missing asterisk (*) patterns: assert chain("x y") == ["Times", "x", "y"] assert chain("3 4") == ["Times", "3", "4"] assert chain("a[b] c") == ["Times", ["a", "b"], "c"] assert chain("(x) (y)") == ["Times", "x", "y"] assert chain("3 (a)") == ["Times", "3", "a"] assert chain("(a) b") == ["Times", "a", "b"] assert chain("4.2") == "4.2" assert chain("4 2") == ["Times", "4", "2"] assert chain("4 2") == ["Times", "4", "2"] assert chain("3 . 4") == ["Dot", "3", "4"] assert chain("4. 2") == ["Times", "4.", "2"] assert chain("x.y") == ["Dot", "x", "y"] assert chain("4.y") == ["Times", "4.", "y"] assert chain("4 .y") == ["Dot", "4", "y"] assert chain("x.4") == ["Times", "x", ".4"] assert chain("x0.3") == ["Times", "x0", ".3"] assert chain("x. 4") == ["Dot", "x", "4"] # Comments assert chain("a (* +b *) + c") == ["Plus", "a", "c"] assert chain("a (* + b *) + (**)c (* +d *) + e") == ["Plus", "a", "c", "e"] assert chain("""a + (* + b *) c + (* d *) e """) == ["Plus", "a", "c", "e"] # Operators couples + and -, * and / are mutually associative: # (i.e. expression gets flattened when mixing these operators) assert chain("a*b/c") == ["Times", "a", "b", ["Power", "c", "-1"]] assert chain("a/b*c") == ["Times", "a", ["Power", "b", "-1"], "c"] assert chain("a+b-c") == ["Plus", "a", "b", ["Times", "-1", "c"]] assert chain("a-b+c") == ["Plus", "a", ["Times", "-1", "b"], "c"] assert chain("-a + b -c ") == ["Plus", ["Times", "-1", "a"], "b", ["Times", "-1", "c"]] assert chain("a/b/c*d") == ["Times", "a", ["Power", "b", "-1"], ["Power", "c", "-1"], "d"] assert chain("a/b/c") == ["Times", "a", ["Power", "b", "-1"], ["Power", "c", "-1"]] assert chain("a-b-c") == ["Plus", "a", ["Times", "-1", "b"], ["Times", "-1", "c"]] assert chain("1/a") == ["Times", "1", ["Power", "a", "-1"]] assert chain("1/a/b") == ["Times", "1", ["Power", "a", "-1"], ["Power", "b", "-1"]] assert chain("-1/a*b") == ["Times", "-1", ["Power", "a", "-1"], "b"] # Enclosures of various kinds, i.e. ( ) [ ] [[ ]] { } assert chain("(a + b) + c") == ["Plus", ["Plus", "a", "b"], "c"] assert chain(" a + (b + c) + d ") == ["Plus", "a", ["Plus", "b", "c"], "d"] assert chain("a * (b + c)") == ["Times", "a", ["Plus", "b", "c"]] assert chain("a b (c d)") == ["Times", "a", "b", ["Times", "c", "d"]] assert chain("{a, b, 2, c}") == ["List", "a", "b", "2", "c"] assert chain("{a, {b, c}}") == ["List", "a", ["List", "b", "c"]] assert chain("{{a}}") == ["List", ["List", "a"]] assert chain("a[b, c]") == ["a", "b", "c"] assert chain("a[[b, c]]") == ["Part", "a", "b", "c"] assert chain("a[b[c]]") == ["a", ["b", "c"]] assert chain("a[[b, c[[d, {e,f}]]]]") == ["Part", "a", "b", ["Part", "c", "d", ["List", "e", "f"]]] assert chain("a[b[[c,d]]]") == ["a", ["Part", "b", "c", "d"]] assert chain("a[[b[c]]]") == ["Part", "a", ["b", "c"]] assert chain("a[[b[[c]]]]") == ["Part", "a", ["Part", "b", "c"]] assert chain("a[[b[c[[d]]]]]") == ["Part", "a", ["b", ["Part", "c", "d"]]] assert chain("a[b[[c[d]]]]") == ["a", ["Part", "b", ["c", "d"]]] assert chain("x[[a+1, b+2, c+3]]") == ["Part", "x", ["Plus", "a", "1"], ["Plus", "b", "2"], ["Plus", "c", "3"]] assert chain("x[a+1, b+2, c+3]") == ["x", ["Plus", "a", "1"], ["Plus", "b", "2"], ["Plus", "c", "3"]] assert chain("{a+1, b+2, c+3}") == ["List", ["Plus", "a", "1"], ["Plus", "b", "2"], ["Plus", "c", "3"]] # Flat operator: assert chain("a*b*c*d*e") == ["Times", "a", "b", "c", "d", "e"] assert chain("a +b + c+ d+e") == ["Plus", "a", "b", "c", "d", "e"] # Right priority operator: assert chain("a^b") == ["Power", "a", "b"] assert chain("a^b^c") == ["Power", "a", ["Power", "b", "c"]] assert chain("a^b^c^d") == ["Power", "a", ["Power", "b", ["Power", "c", "d"]]] # Left priority operator: assert chain("a/.b") == ["ReplaceAll", "a", "b"] assert chain("a/.b/.c/.d") == ["ReplaceAll", ["ReplaceAll", ["ReplaceAll", "a", "b"], "c"], "d"] assert chain("a//b") == ["a", "b"] assert chain("a//b//c") == [["a", "b"], "c"] assert chain("a//b//c//d") == [[["a", "b"], "c"], "d"] # Compound expressions assert chain("a;b") == ["CompoundExpression", "a", "b"] assert chain("a;") == ["CompoundExpression", "a", "Null"] assert chain("a;b;") == ["CompoundExpression", "a", "b", "Null"] assert chain("a[b;c]") == ["a", ["CompoundExpression", "b", "c"]] assert chain("a[b,c;d,e]") == ["a", "b", ["CompoundExpression", "c", "d"], "e"] assert chain("a[b,c;,d]") == ["a", "b", ["CompoundExpression", "c", "Null"], "d"] # New lines assert chain("a\nb\n") == ["CompoundExpression", "a", "b"] assert chain("a\n\nb\n (c \nd) \n") == ["CompoundExpression", "a", "b", ["Times", "c", "d"]] assert chain("\na; b\nc") == ["CompoundExpression", "a", "b", "c"] assert chain("a + \nb\n") == ["Plus", "a", "b"] assert chain("a\nb; c; d\n e; (f \n g); h + \n i") == ["CompoundExpression", "a", "b", "c", "d", "e", ["Times", "f", "g"], ["Plus", "h", "i"]] assert chain("\n{\na\nb; c; d\n e (f \n g); h + \n i\n\n}\n") == ["List", ["CompoundExpression", ["Times", "a", "b"], "c", ["Times", "d", "e", ["Times", "f", "g"]], ["Plus", "h", "i"]]] # Patterns assert chain("y_") == ["Pattern", "y", ["Blank"]] assert chain("y_.") == ["Optional", ["Pattern", "y", ["Blank"]]] assert chain("y__") == ["Pattern", "y", ["BlankSequence"]] assert chain("y___") == ["Pattern", "y", ["BlankNullSequence"]] assert chain("a[b_.,c_]") == ["a", ["Optional", ["Pattern", "b", ["Blank"]]], ["Pattern", "c", ["Blank"]]] assert chain("b_. c") == ["Times", ["Optional", ["Pattern", "b", ["Blank"]]], "c"] # Slots for lambda functions assert chain("#") == ["Slot", "1"] assert chain("#3") == ["Slot", "3"] assert chain("#n") == ["Slot", "n"] assert chain("##") == ["SlotSequence", "1"] assert chain("##a") == ["SlotSequence", "a"] # Lambda functions assert chain("x&") == ["Function", "x"] assert chain("#&") == ["Function", ["Slot", "1"]] assert chain("#+3&") == ["Function", ["Plus", ["Slot", "1"], "3"]] assert chain("#1 + #2&") == ["Function", ["Plus", ["Slot", "1"], ["Slot", "2"]]] assert chain("# + #&") == ["Function", ["Plus", ["Slot", "1"], ["Slot", "1"]]] assert chain("#&[x]") == [["Function", ["Slot", "1"]], "x"] assert chain("#1 + #2 & [x, y]") == [["Function", ["Plus", ["Slot", "1"], ["Slot", "2"]]], "x", "y"] assert chain("#1^2#2^3&") == ["Function", ["Times", ["Power", ["Slot", "1"], "2"], ["Power", ["Slot", "2"], "3"]]] # Invalid expressions: raises(SyntaxError, lambda: chain("(,")) raises(SyntaxError, lambda: chain("()")) raises(SyntaxError, lambda: chain("a (* b")) def test_parser_mathematica_exp_alt(): parser = MathematicaParser() convert_chain2 = lambda expr: parser._from_fullformlist_to_fullformsympy(parser._from_fullform_to_fullformlist(expr)) convert_chain3 = lambda expr: parser._from_fullformsympy_to_sympy(convert_chain2(expr)) Sin, Times, Plus, Power = symbols("Sin Times Plus Power", cls=Function) full_form1 = "Sin[Times[x, y]]" full_form2 = "Plus[Times[x, y], z]" full_form3 = "Sin[Times[x, Plus[y, z], Power[w, n]]]]" assert parser._from_fullform_to_fullformlist(full_form1) == ["Sin", ["Times", "x", "y"]] assert parser._from_fullform_to_fullformlist(full_form2) == ["Plus", ["Times", "x", "y"], "z"] assert parser._from_fullform_to_fullformlist(full_form3) == ["Sin", ["Times", "x", ["Plus", "y", "z"], ["Power", "w", "n"]]] assert convert_chain2(full_form1) == Sin(Times(x, y)) assert convert_chain2(full_form2) == Plus(Times(x, y), z) assert convert_chain2(full_form3) == Sin(Times(x, Plus(y, z), Power(w, n))) assert convert_chain3(full_form1) == sin(x*y) assert convert_chain3(full_form2) == x*y + z assert convert_chain3(full_form3) == sin(x*(y + z)*w**n)
d0e4ca5e9dd54f985b88f3547403abd76ccf87830dee7be0c10f4effb4ef0a5f
from typing import Type from sympy.core.add import Add from sympy.core.basic import Basic 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.symbol import Symbol from sympy.polys.polyroots import roots from sympy.polys.polytools import (cancel, degree) from sympy.core.containers import Tuple from sympy.core.evalf import EvalfMixin from sympy.core.logic import fuzzy_and from sympy.core.numbers import Integer, ComplexInfinity from sympy.core.symbol import Dummy from sympy.core.sympify import sympify, _sympify from sympy.polys import Poly, rootof from sympy.series import limit from sympy.matrices import ImmutableMatrix, eye from sympy.matrices.expressions import MatMul, MatAdd 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(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 isinstance(p, Integer): raise ValueError("Exponent must be an Integer.") if p == 0: 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, **kwargs): """ 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, **kwargs): """ 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, **kwargs): """ 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, **kwargs): """ 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, **kwargs): 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)
a9519a034752f0fa1b2e4dbe4a190b072c51689f1c393a109d4043fccedaa949
from sympy.core.numbers import I, pi from sympy.functions.elementary.exponential import (exp, log) from sympy.polys.partfrac import apart from sympy.core.symbol import Dummy from sympy.external import import_module from sympy.functions import arg, Abs from sympy.integrals.transforms import _fast_inverse_laplace from sympy.physics.control.lti import SISOLinearTimeInvariant from sympy.plotting.plot import LineOver1DRangeSeries from sympy.polys.polytools import Poly from sympy.printing.latex import latex __all__ = ['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_magnitude_plot', 'bode_phase_plot', 'bode_plot'] matplotlib = import_module( 'matplotlib', import_kwargs={'fromlist': ['pyplot']}, catch=(RuntimeError,)) numpy = import_module('numpy') if matplotlib: plt = matplotlib.pyplot if numpy: np = numpy # Matplotlib already has numpy as a compulsory dependency. No need to install it separately. def _check_system(system): """Function to check whether the dynamical system passed for plots is compatible or not.""" if not isinstance(system, SISOLinearTimeInvariant): raise NotImplementedError("Only SISO LTI systems are currently supported.") sys = system.to_expr() len_free_symbols = len(sys.free_symbols) if len_free_symbols > 1: raise ValueError("Extra degree of freedom found. Make sure" " that there are no free symbols in the dynamical system other" " than the variable of Laplace transform.") if sys.has(exp): # Should test that exp is not part of a constant, in which case # no exception is required, compare exp(s) with s*exp(1) raise NotImplementedError("Time delay terms are not supported.") def pole_zero_numerical_data(system): """ Returns the numerical data of poles and zeros of the system. It is internally used by ``pole_zero_plot`` to get the data for plotting poles and zeros. Users can use this data to further analyse the dynamics of the system or plot using a different backend/plotting-module. Parameters ========== system : SISOLinearTimeInvariant The system for which the pole-zero data is to be computed. Returns ======= tuple : (zeros, poles) zeros = Zeros of the system. NumPy array of complex numbers. poles = Poles of the system. NumPy array of complex numbers. Raises ====== NotImplementedError When a SISO LTI system is not passed. When time delay terms are present in the system. ValueError When more than one free symbol is present in the system. The only variable in the transfer function should be the variable of the Laplace transform. Examples ======== >>> from sympy.abc import s >>> from sympy.physics.control.lti import TransferFunction >>> from sympy.physics.control.control_plots import pole_zero_numerical_data >>> tf1 = TransferFunction(s**2 + 1, s**4 + 4*s**3 + 6*s**2 + 5*s + 2, s) >>> pole_zero_numerical_data(tf1) # doctest: +SKIP ([-0.+1.j 0.-1.j], [-2. +0.j -0.5+0.8660254j -0.5-0.8660254j -1. +0.j ]) See Also ======== pole_zero_plot """ _check_system(system) system = system.doit() # Get the equivalent TransferFunction object. num_poly = Poly(system.num, system.var).all_coeffs() den_poly = Poly(system.den, system.var).all_coeffs() num_poly = np.array(num_poly, dtype=np.complex128) den_poly = np.array(den_poly, dtype=np.complex128) zeros = np.roots(num_poly) poles = np.roots(den_poly) return zeros, poles def pole_zero_plot(system, pole_color='blue', pole_markersize=10, zero_color='orange', zero_markersize=7, grid=True, show_axes=True, show=True, **kwargs): r""" Returns the Pole-Zero plot (also known as PZ Plot or PZ Map) of a system. A Pole-Zero plot is a graphical representation of a system's poles and zeros. It is plotted on a complex plane, with circular markers representing the system's zeros and 'x' shaped markers representing the system's poles. Parameters ========== system : SISOLinearTimeInvariant type systems The system for which the pole-zero plot is to be computed. pole_color : str, tuple, optional The color of the pole points on the plot. Default color is blue. The color can be provided as a matplotlib color string, or a 3-tuple of floats each in the 0-1 range. pole_markersize : Number, optional The size of the markers used to mark the poles in the plot. Default pole markersize is 10. zero_color : str, tuple, optional The color of the zero points on the plot. Default color is orange. The color can be provided as a matplotlib color string, or a 3-tuple of floats each in the 0-1 range. zero_markersize : Number, optional The size of the markers used to mark the zeros in the plot. Default zero markersize is 7. grid : boolean, optional If ``True``, the plot will have a grid. Defaults to True. show_axes : boolean, optional If ``True``, the coordinate axes will be shown. Defaults to False. show : boolean, optional If ``True``, the plot will be displayed otherwise the equivalent matplotlib ``plot`` object will be returned. Defaults to True. Examples ======== .. plot:: :context: close-figs :format: doctest :include-source: True >>> from sympy.abc import s >>> from sympy.physics.control.lti import TransferFunction >>> from sympy.physics.control.control_plots import pole_zero_plot >>> tf1 = TransferFunction(s**2 + 1, s**4 + 4*s**3 + 6*s**2 + 5*s + 2, s) >>> pole_zero_plot(tf1) # doctest: +SKIP See Also ======== pole_zero_numerical_data References ========== .. [1] https://en.wikipedia.org/wiki/Pole%E2%80%93zero_plot """ zeros, poles = pole_zero_numerical_data(system) zero_real = np.real(zeros) zero_imag = np.imag(zeros) pole_real = np.real(poles) pole_imag = np.imag(poles) plt.plot(pole_real, pole_imag, 'x', mfc='none', markersize=pole_markersize, color=pole_color) plt.plot(zero_real, zero_imag, 'o', markersize=zero_markersize, color=zero_color) plt.xlabel('Real Axis') plt.ylabel('Imaginary Axis') plt.title(f'Poles and Zeros of ${latex(system)}$', pad=20) if grid: plt.grid() if show_axes: plt.axhline(0, color='black') plt.axvline(0, color='black') if show: plt.show() return return plt def step_response_numerical_data(system, prec=8, lower_limit=0, upper_limit=10, **kwargs): """ Returns the numerical values of the points in the step response plot of a SISO continuous-time system. By default, adaptive sampling is used. If the user wants to instead get an uniformly sampled response, then ``adaptive`` kwarg should be passed ``False`` and ``nb_of_points`` must be passed as additional kwargs. Refer to the parameters of class :class:`sympy.plotting.plot.LineOver1DRangeSeries` for more details. Parameters ========== system : SISOLinearTimeInvariant The system for which the unit step response data is to be computed. prec : int, optional The decimal point precision for the point coordinate values. Defaults to 8. lower_limit : Number, optional The lower limit of the plot range. Defaults to 0. upper_limit : Number, optional The upper limit of the plot range. Defaults to 10. kwargs : Additional keyword arguments are passed to the underlying :class:`sympy.plotting.plot.LineOver1DRangeSeries` class. Returns ======= tuple : (x, y) x = Time-axis values of the points in the step response. NumPy array. y = Amplitude-axis values of the points in the step response. NumPy array. Raises ====== NotImplementedError When a SISO LTI system is not passed. When time delay terms are present in the system. ValueError When more than one free symbol is present in the system. The only variable in the transfer function should be the variable of the Laplace transform. When ``lower_limit`` parameter is less than 0. Examples ======== >>> from sympy.abc import s >>> from sympy.physics.control.lti import TransferFunction >>> from sympy.physics.control.control_plots import step_response_numerical_data >>> tf1 = TransferFunction(s, s**2 + 5*s + 8, s) >>> step_response_numerical_data(tf1) # doctest: +SKIP ([0.0, 0.025413462339411542, 0.0484508722725343, ... , 9.670250533855183, 9.844291913708725, 10.0], [0.0, 0.023844582399907256, 0.042894276802320226, ..., 6.828770759094287e-12, 6.456457160755703e-12]) See Also ======== step_response_plot """ if lower_limit < 0: raise ValueError("Lower limit of time must be greater " "than or equal to zero.") _check_system(system) _x = Dummy("x") expr = system.to_expr()/(system.var) expr = apart(expr, system.var, full=True) _y = _fast_inverse_laplace(expr, system.var, _x).evalf(prec) return LineOver1DRangeSeries(_y, (_x, lower_limit, upper_limit), **kwargs).get_points() def step_response_plot(system, color='b', prec=8, lower_limit=0, upper_limit=10, show_axes=False, grid=True, show=True, **kwargs): r""" Returns the unit step response of a continuous-time system. It is the response of the system when the input signal is a step function. Parameters ========== system : SISOLinearTimeInvariant type The LTI SISO system for which the Step Response is to be computed. color : str, tuple, optional The color of the line. Default is Blue. show : boolean, optional If ``True``, the plot will be displayed otherwise the equivalent matplotlib ``plot`` object will be returned. Defaults to True. lower_limit : Number, optional The lower limit of the plot range. Defaults to 0. upper_limit : Number, optional The upper limit of the plot range. Defaults to 10. prec : int, optional The decimal point precision for the point coordinate values. Defaults to 8. show_axes : boolean, optional If ``True``, the coordinate axes will be shown. Defaults to False. grid : boolean, optional If ``True``, the plot will have a grid. Defaults to True. Examples ======== .. plot:: :context: close-figs :format: doctest :include-source: True >>> from sympy.abc import s >>> from sympy.physics.control.lti import TransferFunction >>> from sympy.physics.control.control_plots import step_response_plot >>> tf1 = TransferFunction(8*s**2 + 18*s + 32, s**3 + 6*s**2 + 14*s + 24, s) >>> step_response_plot(tf1) # doctest: +SKIP See Also ======== impulse_response_plot, ramp_response_plot References ========== .. [1] https://www.mathworks.com/help/control/ref/lti.step.html """ x, y = step_response_numerical_data(system, prec=prec, lower_limit=lower_limit, upper_limit=upper_limit, **kwargs) plt.plot(x, y, color=color) plt.xlabel('Time (s)') plt.ylabel('Amplitude') plt.title(f'Unit Step Response of ${latex(system)}$', pad=20) if grid: plt.grid() if show_axes: plt.axhline(0, color='black') plt.axvline(0, color='black') if show: plt.show() return return plt def impulse_response_numerical_data(system, prec=8, lower_limit=0, upper_limit=10, **kwargs): """ Returns the numerical values of the points in the impulse response plot of a SISO continuous-time system. By default, adaptive sampling is used. If the user wants to instead get an uniformly sampled response, then ``adaptive`` kwarg should be passed ``False`` and ``nb_of_points`` must be passed as additional kwargs. Refer to the parameters of class :class:`sympy.plotting.plot.LineOver1DRangeSeries` for more details. Parameters ========== system : SISOLinearTimeInvariant The system for which the impulse response data is to be computed. prec : int, optional The decimal point precision for the point coordinate values. Defaults to 8. lower_limit : Number, optional The lower limit of the plot range. Defaults to 0. upper_limit : Number, optional The upper limit of the plot range. Defaults to 10. kwargs : Additional keyword arguments are passed to the underlying :class:`sympy.plotting.plot.LineOver1DRangeSeries` class. Returns ======= tuple : (x, y) x = Time-axis values of the points in the impulse response. NumPy array. y = Amplitude-axis values of the points in the impulse response. NumPy array. Raises ====== NotImplementedError When a SISO LTI system is not passed. When time delay terms are present in the system. ValueError When more than one free symbol is present in the system. The only variable in the transfer function should be the variable of the Laplace transform. When ``lower_limit`` parameter is less than 0. Examples ======== >>> from sympy.abc import s >>> from sympy.physics.control.lti import TransferFunction >>> from sympy.physics.control.control_plots import impulse_response_numerical_data >>> tf1 = TransferFunction(s, s**2 + 5*s + 8, s) >>> impulse_response_numerical_data(tf1) # doctest: +SKIP ([0.0, 0.06616480200395854,... , 9.854500743565858, 10.0], [0.9999999799999999, 0.7042848373025861,...,7.170748906965121e-13, -5.1901263495547205e-12]) See Also ======== impulse_response_plot """ if lower_limit < 0: raise ValueError("Lower limit of time must be greater " "than or equal to zero.") _check_system(system) _x = Dummy("x") expr = system.to_expr() expr = apart(expr, system.var, full=True) _y = _fast_inverse_laplace(expr, system.var, _x).evalf(prec) return LineOver1DRangeSeries(_y, (_x, lower_limit, upper_limit), **kwargs).get_points() def impulse_response_plot(system, color='b', prec=8, lower_limit=0, upper_limit=10, show_axes=False, grid=True, show=True, **kwargs): r""" Returns the unit impulse response (Input is the Dirac-Delta Function) of a continuous-time system. Parameters ========== system : SISOLinearTimeInvariant type The LTI SISO system for which the Impulse Response is to be computed. color : str, tuple, optional The color of the line. Default is Blue. show : boolean, optional If ``True``, the plot will be displayed otherwise the equivalent matplotlib ``plot`` object will be returned. Defaults to True. lower_limit : Number, optional The lower limit of the plot range. Defaults to 0. upper_limit : Number, optional The upper limit of the plot range. Defaults to 10. prec : int, optional The decimal point precision for the point coordinate values. Defaults to 8. show_axes : boolean, optional If ``True``, the coordinate axes will be shown. Defaults to False. grid : boolean, optional If ``True``, the plot will have a grid. Defaults to True. Examples ======== .. plot:: :context: close-figs :format: doctest :include-source: True >>> from sympy.abc import s >>> from sympy.physics.control.lti import TransferFunction >>> from sympy.physics.control.control_plots import impulse_response_plot >>> tf1 = TransferFunction(8*s**2 + 18*s + 32, s**3 + 6*s**2 + 14*s + 24, s) >>> impulse_response_plot(tf1) # doctest: +SKIP See Also ======== step_response_plot, ramp_response_plot References ========== .. [1] https://www.mathworks.com/help/control/ref/lti.impulse.html """ x, y = impulse_response_numerical_data(system, prec=prec, lower_limit=lower_limit, upper_limit=upper_limit, **kwargs) plt.plot(x, y, color=color) plt.xlabel('Time (s)') plt.ylabel('Amplitude') plt.title(f'Impulse Response of ${latex(system)}$', pad=20) if grid: plt.grid() if show_axes: plt.axhline(0, color='black') plt.axvline(0, color='black') if show: plt.show() return return plt def ramp_response_numerical_data(system, slope=1, prec=8, lower_limit=0, upper_limit=10, **kwargs): """ Returns the numerical values of the points in the ramp response plot of a SISO continuous-time system. By default, adaptive sampling is used. If the user wants to instead get an uniformly sampled response, then ``adaptive`` kwarg should be passed ``False`` and ``nb_of_points`` must be passed as additional kwargs. Refer to the parameters of class :class:`sympy.plotting.plot.LineOver1DRangeSeries` for more details. Parameters ========== system : SISOLinearTimeInvariant The system for which the ramp response data is to be computed. slope : Number, optional The slope of the input ramp function. Defaults to 1. prec : int, optional The decimal point precision for the point coordinate values. Defaults to 8. lower_limit : Number, optional The lower limit of the plot range. Defaults to 0. upper_limit : Number, optional The upper limit of the plot range. Defaults to 10. kwargs : Additional keyword arguments are passed to the underlying :class:`sympy.plotting.plot.LineOver1DRangeSeries` class. Returns ======= tuple : (x, y) x = Time-axis values of the points in the ramp response plot. NumPy array. y = Amplitude-axis values of the points in the ramp response plot. NumPy array. Raises ====== NotImplementedError When a SISO LTI system is not passed. When time delay terms are present in the system. ValueError When more than one free symbol is present in the system. The only variable in the transfer function should be the variable of the Laplace transform. When ``lower_limit`` parameter is less than 0. When ``slope`` is negative. Examples ======== >>> from sympy.abc import s >>> from sympy.physics.control.lti import TransferFunction >>> from sympy.physics.control.control_plots import ramp_response_numerical_data >>> tf1 = TransferFunction(s, s**2 + 5*s + 8, s) >>> ramp_response_numerical_data(tf1) # doctest: +SKIP (([0.0, 0.12166980856813935,..., 9.861246379582118, 10.0], [1.4504508011325967e-09, 0.006046440489058766,..., 0.12499999999568202, 0.12499999999661349])) See Also ======== ramp_response_plot """ if slope < 0: raise ValueError("Slope must be greater than or equal" " to zero.") if lower_limit < 0: raise ValueError("Lower limit of time must be greater " "than or equal to zero.") _check_system(system) _x = Dummy("x") expr = (slope*system.to_expr())/((system.var)**2) expr = apart(expr, system.var, full=True) _y = _fast_inverse_laplace(expr, system.var, _x).evalf(prec) return LineOver1DRangeSeries(_y, (_x, lower_limit, upper_limit), **kwargs).get_points() def ramp_response_plot(system, slope=1, color='b', prec=8, lower_limit=0, upper_limit=10, show_axes=False, grid=True, show=True, **kwargs): r""" Returns the ramp response of a continuous-time system. Ramp function is defined as the straight line passing through origin ($f(x) = mx$). The slope of the ramp function can be varied by the user and the default value is 1. Parameters ========== system : SISOLinearTimeInvariant type The LTI SISO system for which the Ramp Response is to be computed. slope : Number, optional The slope of the input ramp function. Defaults to 1. color : str, tuple, optional The color of the line. Default is Blue. show : boolean, optional If ``True``, the plot will be displayed otherwise the equivalent matplotlib ``plot`` object will be returned. Defaults to True. lower_limit : Number, optional The lower limit of the plot range. Defaults to 0. upper_limit : Number, optional The upper limit of the plot range. Defaults to 10. prec : int, optional The decimal point precision for the point coordinate values. Defaults to 8. show_axes : boolean, optional If ``True``, the coordinate axes will be shown. Defaults to False. grid : boolean, optional If ``True``, the plot will have a grid. Defaults to True. Examples ======== .. plot:: :context: close-figs :format: doctest :include-source: True >>> from sympy.abc import s >>> from sympy.physics.control.lti import TransferFunction >>> from sympy.physics.control.control_plots import ramp_response_plot >>> tf1 = TransferFunction(s, (s+4)*(s+8), s) >>> ramp_response_plot(tf1, upper_limit=2) # doctest: +SKIP See Also ======== step_response_plot, ramp_response_plot References ========== .. [1] https://en.wikipedia.org/wiki/Ramp_function """ x, y = ramp_response_numerical_data(system, slope=slope, prec=prec, lower_limit=lower_limit, upper_limit=upper_limit, **kwargs) plt.plot(x, y, color=color) plt.xlabel('Time (s)') plt.ylabel('Amplitude') plt.title(f'Ramp Response of ${latex(system)}$ [Slope = {slope}]', pad=20) if grid: plt.grid() if show_axes: plt.axhline(0, color='black') plt.axvline(0, color='black') if show: plt.show() return return plt def bode_magnitude_numerical_data(system, initial_exp=-5, final_exp=5, freq_unit='rad/sec', **kwargs): """ Returns the numerical data of the Bode magnitude plot of the system. It is internally used by ``bode_magnitude_plot`` to get the data for plotting Bode magnitude plot. Users can use this data to further analyse the dynamics of the system or plot using a different backend/plotting-module. Parameters ========== system : SISOLinearTimeInvariant The system for which the data is to be computed. initial_exp : Number, optional The initial exponent of 10 of the semilog plot. Defaults to -5. final_exp : Number, optional The final exponent of 10 of the semilog plot. Defaults to 5. freq_unit : string, optional User can choose between ``'rad/sec'`` (radians/second) and ``'Hz'`` (Hertz) as frequency units. Returns ======= tuple : (x, y) x = x-axis values of the Bode magnitude plot. y = y-axis values of the Bode magnitude plot. Raises ====== NotImplementedError When a SISO LTI system is not passed. When time delay terms are present in the system. ValueError When more than one free symbol is present in the system. The only variable in the transfer function should be the variable of the Laplace transform. When incorrect frequency units are given as input. Examples ======== >>> from sympy.abc import s >>> from sympy.physics.control.lti import TransferFunction >>> from sympy.physics.control.control_plots import bode_magnitude_numerical_data >>> tf1 = TransferFunction(s**2 + 1, s**4 + 4*s**3 + 6*s**2 + 5*s + 2, s) >>> bode_magnitude_numerical_data(tf1) # doctest: +SKIP ([1e-05, 1.5148378120533502e-05,..., 68437.36188804005, 100000.0], [-6.020599914256786, -6.0205999155219505,..., -193.4117304087953, -200.00000000260573]) See Also ======== bode_magnitude_plot, bode_phase_numerical_data """ _check_system(system) expr = system.to_expr() freq_units = ('rad/sec', 'Hz') if freq_unit not in freq_units: raise ValueError('Only "rad/sec" and "Hz" are accepted frequency units.') _w = Dummy("w", real=True) if freq_unit == 'Hz': repl = I*_w*2*pi else: repl = I*_w w_expr = expr.subs({system.var: repl}) mag = 20*log(Abs(w_expr), 10) x, y = LineOver1DRangeSeries(mag, (_w, 10**initial_exp, 10**final_exp), xscale='log', **kwargs).get_points() return x, y def bode_magnitude_plot(system, initial_exp=-5, final_exp=5, color='b', show_axes=False, grid=True, show=True, freq_unit='rad/sec', **kwargs): r""" Returns the Bode magnitude plot of a continuous-time system. See ``bode_plot`` for all the parameters. """ x, y = bode_magnitude_numerical_data(system, initial_exp=initial_exp, final_exp=final_exp, freq_unit=freq_unit) plt.plot(x, y, color=color, **kwargs) plt.xscale('log') plt.xlabel('Frequency (%s) [Log Scale]' % freq_unit) plt.ylabel('Magnitude (dB)') plt.title(f'Bode Plot (Magnitude) of ${latex(system)}$', pad=20) if grid: plt.grid(True) if show_axes: plt.axhline(0, color='black') plt.axvline(0, color='black') if show: plt.show() return return plt def bode_phase_numerical_data(system, initial_exp=-5, final_exp=5, freq_unit='rad/sec', phase_unit='rad', **kwargs): """ Returns the numerical data of the Bode phase plot of the system. It is internally used by ``bode_phase_plot`` to get the data for plotting Bode phase plot. Users can use this data to further analyse the dynamics of the system or plot using a different backend/plotting-module. Parameters ========== system : SISOLinearTimeInvariant The system for which the Bode phase plot data is to be computed. initial_exp : Number, optional The initial exponent of 10 of the semilog plot. Defaults to -5. final_exp : Number, optional The final exponent of 10 of the semilog plot. Defaults to 5. freq_unit : string, optional User can choose between ``'rad/sec'`` (radians/second) and '``'Hz'`` (Hertz) as frequency units. phase_unit : string, optional User can choose between ``'rad'`` (radians) and ``'deg'`` (degree) as phase units. Returns ======= tuple : (x, y) x = x-axis values of the Bode phase plot. y = y-axis values of the Bode phase plot. Raises ====== NotImplementedError When a SISO LTI system is not passed. When time delay terms are present in the system. ValueError When more than one free symbol is present in the system. The only variable in the transfer function should be the variable of the Laplace transform. When incorrect frequency or phase units are given as input. Examples ======== >>> from sympy.abc import s >>> from sympy.physics.control.lti import TransferFunction >>> from sympy.physics.control.control_plots import bode_phase_numerical_data >>> tf1 = TransferFunction(s**2 + 1, s**4 + 4*s**3 + 6*s**2 + 5*s + 2, s) >>> bode_phase_numerical_data(tf1) # doctest: +SKIP ([1e-05, 1.4472354033813751e-05, 2.035581932165858e-05,..., 47577.3248186011, 67884.09326036123, 100000.0], [-2.5000000000291665e-05, -3.6180885085e-05, -5.08895483066e-05,...,-3.1415085799262523, -3.14155265358979]) See Also ======== bode_magnitude_plot, bode_phase_numerical_data """ _check_system(system) expr = system.to_expr() freq_units = ('rad/sec', 'Hz') phase_units = ('rad', 'deg') if freq_unit not in freq_units: raise ValueError('Only "rad/sec" and "Hz" are accepted frequency units.') if phase_unit not in phase_units: raise ValueError('Only "rad" and "deg" are accepted phase units.') _w = Dummy("w", real=True) if freq_unit == 'Hz': repl = I*_w*2*pi else: repl = I*_w w_expr = expr.subs({system.var: repl}) if phase_unit == 'deg': phase = arg(w_expr)*180/pi else: phase = arg(w_expr) x, y = LineOver1DRangeSeries(phase, (_w, 10**initial_exp, 10**final_exp), xscale='log', **kwargs).get_points() return x, y def bode_phase_plot(system, initial_exp=-5, final_exp=5, color='b', show_axes=False, grid=True, show=True, freq_unit='rad/sec', phase_unit='rad', **kwargs): r""" Returns the Bode phase plot of a continuous-time system. See ``bode_plot`` for all the parameters. """ x, y = bode_phase_numerical_data(system, initial_exp=initial_exp, final_exp=final_exp, freq_unit=freq_unit, phase_unit=phase_unit) plt.plot(x, y, color=color, **kwargs) plt.xscale('log') plt.xlabel('Frequency (%s) [Log Scale]' % freq_unit) plt.ylabel('Phase (%s)' % phase_unit) plt.title(f'Bode Plot (Phase) of ${latex(system)}$', pad=20) if grid: plt.grid(True) if show_axes: plt.axhline(0, color='black') plt.axvline(0, color='black') if show: plt.show() return return plt def bode_plot(system, initial_exp=-5, final_exp=5, grid=True, show_axes=False, show=True, freq_unit='rad/sec', phase_unit='rad', **kwargs): r""" Returns the Bode phase and magnitude plots of a continuous-time system. Parameters ========== system : SISOLinearTimeInvariant type The LTI SISO system for which the Bode Plot is to be computed. initial_exp : Number, optional The initial exponent of 10 of the semilog plot. Defaults to -5. final_exp : Number, optional The final exponent of 10 of the semilog plot. Defaults to 5. show : boolean, optional If ``True``, the plot will be displayed otherwise the equivalent matplotlib ``plot`` object will be returned. Defaults to True. prec : int, optional The decimal point precision for the point coordinate values. Defaults to 8. grid : boolean, optional If ``True``, the plot will have a grid. Defaults to True. show_axes : boolean, optional If ``True``, the coordinate axes will be shown. Defaults to False. freq_unit : string, optional User can choose between ``'rad/sec'`` (radians/second) and ``'Hz'`` (Hertz) as frequency units. phase_unit : string, optional User can choose between ``'rad'`` (radians) and ``'deg'`` (degree) as phase units. Examples ======== .. plot:: :context: close-figs :format: doctest :include-source: True >>> from sympy.abc import s >>> from sympy.physics.control.lti import TransferFunction >>> from sympy.physics.control.control_plots import bode_plot >>> tf1 = TransferFunction(1*s**2 + 0.1*s + 7.5, 1*s**4 + 0.12*s**3 + 9*s**2, s) >>> bode_plot(tf1, initial_exp=0.2, final_exp=0.7) # doctest: +SKIP See Also ======== bode_magnitude_plot, bode_phase_plot """ plt.subplot(211) mag = bode_magnitude_plot(system, initial_exp=initial_exp, final_exp=final_exp, show=False, grid=grid, show_axes=show_axes, freq_unit=freq_unit, **kwargs) mag.title(f'Bode Plot of ${latex(system)}$', pad=20) mag.xlabel(None) plt.subplot(212) bode_phase_plot(system, initial_exp=initial_exp, final_exp=final_exp, show=False, grid=grid, show_axes=show_axes, freq_unit=freq_unit, phase_unit=phase_unit, **kwargs).title(None) if show: plt.show() return return plt
9c74f69b89ac4b983240b60f228d97e97705ef2d294d1658254631646d180949
"""Shor's algorithm and helper functions. Todo: * Get the CMod gate working again using the new Gate API. * Fix everything. * Update docstrings and reformat. """ import math import random from sympy.core.mul import Mul from sympy.core.singleton import S from sympy.functions.elementary.exponential import log from sympy.functions.elementary.miscellaneous import sqrt from sympy.core.numbers import igcd from sympy.ntheory import continued_fraction_periodic as continued_fraction from sympy.utilities.iterables import variations from sympy.physics.quantum.gate import Gate from sympy.physics.quantum.qubit import Qubit, measure_partial_oneshot from sympy.physics.quantum.qapply import qapply from sympy.physics.quantum.qft import QFT from sympy.physics.quantum.qexpr import QuantumError class OrderFindingException(QuantumError): pass class CMod(Gate): """A controlled mod gate. This is black box controlled Mod function for use by shor's algorithm. TODO: implement a decompose property that returns how to do this in terms of elementary gates """ @classmethod def _eval_args(cls, args): # t = args[0] # a = args[1] # N = args[2] raise NotImplementedError('The CMod gate has not been completed.') @property def t(self): """Size of 1/2 input register. First 1/2 holds output.""" return self.label[0] @property def a(self): """Base of the controlled mod function.""" return self.label[1] @property def N(self): """N is the type of modular arithmetic we are doing.""" return self.label[2] def _apply_operator_Qubit(self, qubits, **options): """ This directly calculates the controlled mod of the second half of the register and puts it in the second This will look pretty when we get Tensor Symbolically working """ n = 1 k = 0 # Determine the value stored in high memory. for i in range(self.t): k += n*qubits[self.t + i] n *= 2 # The value to go in low memory will be out. out = int(self.a**k % self.N) # Create array for new qbit-ket which will have high memory unaffected outarray = list(qubits.args[0][:self.t]) # Place out in low memory for i in reversed(range(self.t)): outarray.append((out >> i) & 1) return Qubit(*outarray) def shor(N): """This function implements Shor's factoring algorithm on the Integer N The algorithm starts by picking a random number (a) and seeing if it is coprime with N. If it is not, then the gcd of the two numbers is a factor and we are done. Otherwise, it begins the period_finding subroutine which finds the period of a in modulo N arithmetic. This period, if even, can be used to calculate factors by taking a**(r/2)-1 and a**(r/2)+1. These values are returned. """ a = random.randrange(N - 2) + 2 if igcd(N, a) != 1: return igcd(N, a) r = period_find(a, N) if r % 2 == 1: shor(N) answer = (igcd(a**(r/2) - 1, N), igcd(a**(r/2) + 1, N)) return answer def getr(x, y, N): fraction = continued_fraction(x, y) # Now convert into r total = ratioize(fraction, N) return total def ratioize(list, N): if list[0] > N: return S.Zero if len(list) == 1: return list[0] return list[0] + ratioize(list[1:], N) def period_find(a, N): """Finds the period of a in modulo N arithmetic This is quantum part of Shor's algorithm. It takes two registers, puts first in superposition of states with Hadamards so: ``|k>|0>`` with k being all possible choices. It then does a controlled mod and a QFT to determine the order of a. """ epsilon = .5 # picks out t's such that maintains accuracy within epsilon t = int(2*math.ceil(log(N, 2))) # make the first half of register be 0's |000...000> start = [0 for x in range(t)] # Put second half into superposition of states so we have |1>x|0> + |2>x|0> + ... |k>x>|0> + ... + |2**n-1>x|0> factor = 1/sqrt(2**t) qubits = 0 for arr in variations(range(2), t, repetition=True): qbitArray = list(arr) + start qubits = qubits + Qubit(*qbitArray) circuit = (factor*qubits).expand() # Controlled second half of register so that we have: # |1>x|a**1 %N> + |2>x|a**2 %N> + ... + |k>x|a**k %N >+ ... + |2**n-1=k>x|a**k % n> circuit = CMod(t, a, N)*circuit # will measure first half of register giving one of the a**k%N's circuit = qapply(circuit) for i in range(t): circuit = measure_partial_oneshot(circuit, i) # Now apply Inverse Quantum Fourier Transform on the second half of the register circuit = qapply(QFT(t, t*2).decompose()*circuit, floatingPoint=True) for i in range(t): circuit = measure_partial_oneshot(circuit, i + t) if isinstance(circuit, Qubit): register = circuit elif isinstance(circuit, Mul): register = circuit.args[-1] else: register = circuit.args[-1].args[-1] n = 1 answer = 0 for i in range(len(register)/2): answer += n*register[i + t] n = n << 1 if answer == 0: raise OrderFindingException( "Order finder returned 0. Happens with chance %f" % epsilon) #turn answer into r using continued fractions g = getr(answer, 2**t, N) return g
0f98a930144287636cc48cb817a64b40017863ce3edab28a0be733095676d83b
"""Utilities to deal with sympy.Matrix, numpy and scipy.sparse.""" from sympy.core.expr import Expr from sympy.core.numbers import I from sympy.core.singleton import S from sympy.matrices.matrices import MatrixBase from sympy.matrices import eye, zeros from sympy.external import import_module __all__ = [ 'numpy_ndarray', 'scipy_sparse_matrix', 'sympy_to_numpy', 'sympy_to_scipy_sparse', 'numpy_to_sympy', 'scipy_sparse_to_sympy', 'flatten_scalar', 'matrix_dagger', 'to_sympy', 'to_numpy', 'to_scipy_sparse', 'matrix_tensor_product', 'matrix_zeros' ] # Conditionally define the base classes for numpy and scipy.sparse arrays # for use in isinstance tests. np = import_module('numpy') if not np: class numpy_ndarray: pass else: numpy_ndarray = np.ndarray # type: ignore scipy = import_module('scipy', import_kwargs={'fromlist': ['sparse']}) if not scipy: class scipy_sparse_matrix: pass sparse = None else: sparse = scipy.sparse scipy_sparse_matrix = sparse.spmatrix # type: ignore def sympy_to_numpy(m, **options): """Convert a SymPy Matrix/complex number to a numpy matrix or scalar.""" if not np: raise ImportError dtype = options.get('dtype', 'complex') if isinstance(m, MatrixBase): return np.array(m.tolist(), dtype=dtype) elif isinstance(m, Expr): if m.is_Number or m.is_NumberSymbol or m == I: return complex(m) raise TypeError('Expected MatrixBase or complex scalar, got: %r' % m) def sympy_to_scipy_sparse(m, **options): """Convert a SymPy Matrix/complex number to a numpy matrix or scalar.""" if not np or not sparse: raise ImportError dtype = options.get('dtype', 'complex') if isinstance(m, MatrixBase): return sparse.csr_matrix(np.array(m.tolist(), dtype=dtype)) elif isinstance(m, Expr): if m.is_Number or m.is_NumberSymbol or m == I: return complex(m) raise TypeError('Expected MatrixBase or complex scalar, got: %r' % m) def scipy_sparse_to_sympy(m, **options): """Convert a scipy.sparse matrix to a SymPy matrix.""" return MatrixBase(m.todense()) def numpy_to_sympy(m, **options): """Convert a numpy matrix to a SymPy matrix.""" return MatrixBase(m) def to_sympy(m, **options): """Convert a numpy/scipy.sparse matrix to a SymPy matrix.""" if isinstance(m, MatrixBase): return m elif isinstance(m, numpy_ndarray): return numpy_to_sympy(m) elif isinstance(m, scipy_sparse_matrix): return scipy_sparse_to_sympy(m) elif isinstance(m, Expr): return m raise TypeError('Expected sympy/numpy/scipy.sparse matrix, got: %r' % m) def to_numpy(m, **options): """Convert a sympy/scipy.sparse matrix to a numpy matrix.""" dtype = options.get('dtype', 'complex') if isinstance(m, (MatrixBase, Expr)): return sympy_to_numpy(m, dtype=dtype) elif isinstance(m, numpy_ndarray): return m elif isinstance(m, scipy_sparse_matrix): return m.todense() raise TypeError('Expected sympy/numpy/scipy.sparse matrix, got: %r' % m) def to_scipy_sparse(m, **options): """Convert a sympy/numpy matrix to a scipy.sparse matrix.""" dtype = options.get('dtype', 'complex') if isinstance(m, (MatrixBase, Expr)): return sympy_to_scipy_sparse(m, dtype=dtype) elif isinstance(m, numpy_ndarray): if not sparse: raise ImportError return sparse.csr_matrix(m) elif isinstance(m, scipy_sparse_matrix): return m raise TypeError('Expected sympy/numpy/scipy.sparse matrix, got: %r' % m) def flatten_scalar(e): """Flatten a 1x1 matrix to a scalar, return larger matrices unchanged.""" if isinstance(e, MatrixBase): if e.shape == (1, 1): e = e[0] if isinstance(e, (numpy_ndarray, scipy_sparse_matrix)): if e.shape == (1, 1): e = complex(e[0, 0]) return e def matrix_dagger(e): """Return the dagger of a sympy/numpy/scipy.sparse matrix.""" if isinstance(e, MatrixBase): return e.H elif isinstance(e, (numpy_ndarray, scipy_sparse_matrix)): return e.conjugate().transpose() raise TypeError('Expected sympy/numpy/scipy.sparse matrix, got: %r' % e) # TODO: Move this into sympy.matricies. def _sympy_tensor_product(*matrices): """Compute the kronecker product of a sequence of SymPy Matrices. """ from sympy.matrices.expressions.kronecker import matrix_kronecker_product return matrix_kronecker_product(*matrices) def _numpy_tensor_product(*product): """numpy version of tensor product of multiple arguments.""" if not np: raise ImportError answer = product[0] for item in product[1:]: answer = np.kron(answer, item) return answer def _scipy_sparse_tensor_product(*product): """scipy.sparse version of tensor product of multiple arguments.""" if not sparse: raise ImportError answer = product[0] for item in product[1:]: answer = sparse.kron(answer, item) # The final matrices will just be multiplied, so csr is a good final # sparse format. return sparse.csr_matrix(answer) def matrix_tensor_product(*product): """Compute the matrix tensor product of sympy/numpy/scipy.sparse matrices.""" if isinstance(product[0], MatrixBase): return _sympy_tensor_product(*product) elif isinstance(product[0], numpy_ndarray): return _numpy_tensor_product(*product) elif isinstance(product[0], scipy_sparse_matrix): return _scipy_sparse_tensor_product(*product) def _numpy_eye(n): """numpy version of complex eye.""" if not np: raise ImportError return np.array(np.eye(n, dtype='complex')) def _scipy_sparse_eye(n): """scipy.sparse version of complex eye.""" if not sparse: raise ImportError return sparse.eye(n, n, dtype='complex') def matrix_eye(n, **options): """Get the version of eye and tensor_product for a given format.""" format = options.get('format', 'sympy') if format == 'sympy': return eye(n) elif format == 'numpy': return _numpy_eye(n) elif format == 'scipy.sparse': return _scipy_sparse_eye(n) raise NotImplementedError('Invalid format: %r' % format) def _numpy_zeros(m, n, **options): """numpy version of zeros.""" dtype = options.get('dtype', 'float64') if not np: raise ImportError return np.zeros((m, n), dtype=dtype) def _scipy_sparse_zeros(m, n, **options): """scipy.sparse version of zeros.""" spmatrix = options.get('spmatrix', 'csr') dtype = options.get('dtype', 'float64') if not sparse: raise ImportError if spmatrix == 'lil': return sparse.lil_matrix((m, n), dtype=dtype) elif spmatrix == 'csr': return sparse.csr_matrix((m, n), dtype=dtype) def matrix_zeros(m, n, **options): """"Get a zeros matrix for a given format.""" format = options.get('format', 'sympy') if format == 'sympy': return zeros(m, n) elif format == 'numpy': return _numpy_zeros(m, n, **options) elif format == 'scipy.sparse': return _scipy_sparse_zeros(m, n, **options) raise NotImplementedError('Invaild format: %r' % format) def _numpy_matrix_to_zero(e): """Convert a numpy zero matrix to the zero scalar.""" if not np: raise ImportError test = np.zeros_like(e) if np.allclose(e, test): return 0.0 else: return e def _scipy_sparse_matrix_to_zero(e): """Convert a scipy.sparse zero matrix to the zero scalar.""" if not np: raise ImportError edense = e.todense() test = np.zeros_like(edense) if np.allclose(edense, test): return 0.0 else: return e def matrix_to_zero(e): """Convert a zero matrix to the scalar zero.""" if isinstance(e, MatrixBase): if zeros(*e.shape) == e: e = S.Zero elif isinstance(e, numpy_ndarray): e = _numpy_matrix_to_zero(e) elif isinstance(e, scipy_sparse_matrix): e = _scipy_sparse_matrix_to_zero(e) return e
12858674d84521bbe0274ca5d97b053d1eaa80f694e535b0db34867d4f8d0b16
"""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 in range(len(targets)): if new_qubit[targets[bit]] != (index >> bit) & 1: new_qubit = new_qubit.flip(targets[bit]) # 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)
6ff9849b7abe8196c8579c79565ea9cdfc89cadaa5a7f6bdf31a5fb1ed807e02
"""Logic for representing operators in state in various bases. TODO: * Get represent working with continuous hilbert spaces. * Document default basis functionality. """ from sympy.core.add import Add from sympy.core.expr import Expr from sympy.core.mul import Mul from sympy.core.numbers import I from sympy.core.power import Pow from sympy.integrals.integrals import integrate from sympy.physics.quantum.dagger import Dagger from sympy.physics.quantum.commutator import Commutator from sympy.physics.quantum.anticommutator import AntiCommutator from sympy.physics.quantum.innerproduct import InnerProduct from sympy.physics.quantum.qexpr import QExpr from sympy.physics.quantum.tensorproduct import TensorProduct from sympy.physics.quantum.matrixutils import flatten_scalar from sympy.physics.quantum.state import KetBase, BraBase, StateBase from sympy.physics.quantum.operator import Operator, OuterProduct from sympy.physics.quantum.qapply import qapply from sympy.physics.quantum.operatorset import operators_to_state, state_to_operators __all__ = [ 'represent', 'rep_innerproduct', 'rep_expectation', 'integrate_result', 'get_basis', 'enumerate_states' ] #----------------------------------------------------------------------------- # Represent #----------------------------------------------------------------------------- def _sympy_to_scalar(e): """Convert from a SymPy scalar to a Python scalar.""" if isinstance(e, Expr): if e.is_Integer: return int(e) elif e.is_Float: return float(e) elif e.is_Rational: return float(e) elif e.is_Number or e.is_NumberSymbol or e == I: return complex(e) raise TypeError('Expected number, got: %r' % e) def represent(expr, **options): """Represent the quantum expression in the given basis. In quantum mechanics abstract states and operators can be represented in various basis sets. Under this operation the follow transforms happen: * Ket -> column vector or function * Bra -> row vector of function * Operator -> matrix or differential operator This function is the top-level interface for this action. This function walks the SymPy expression tree looking for ``QExpr`` instances that have a ``_represent`` method. This method is then called and the object is replaced by the representation returned by this method. By default, the ``_represent`` method will dispatch to other methods that handle the representation logic for a particular basis set. The naming convention for these methods is the following:: def _represent_FooBasis(self, e, basis, **options) This function will have the logic for representing instances of its class in the basis set having a class named ``FooBasis``. Parameters ========== expr : Expr The expression to represent. basis : Operator, basis set An object that contains the information about the basis set. If an operator is used, the basis is assumed to be the orthonormal eigenvectors of that operator. In general though, the basis argument can be any object that contains the basis set information. options : dict Key/value pairs of options that are passed to the underlying method that finds the representation. These options can be used to control how the representation is done. For example, this is where the size of the basis set would be set. Returns ======= e : Expr The SymPy expression of the represented quantum expression. Examples ======== Here we subclass ``Operator`` and ``Ket`` to create the z-spin operator and its spin 1/2 up eigenstate. By defining the ``_represent_SzOp`` method, the ket can be represented in the z-spin basis. >>> from sympy.physics.quantum import Operator, represent, Ket >>> from sympy import Matrix >>> class SzUpKet(Ket): ... def _represent_SzOp(self, basis, **options): ... return Matrix([1,0]) ... >>> class SzOp(Operator): ... pass ... >>> sz = SzOp('Sz') >>> up = SzUpKet('up') >>> represent(up, basis=sz) Matrix([ [1], [0]]) Here we see an example of representations in a continuous basis. We see that the result of representing various combinations of cartesian position operators and kets give us continuous expressions involving DiracDelta functions. >>> from sympy.physics.quantum.cartesian import XOp, XKet, XBra >>> X = XOp() >>> x = XKet() >>> y = XBra('y') >>> represent(X*x) x*DiracDelta(x - x_2) >>> represent(X*x*y) x*DiracDelta(x - x_3)*DiracDelta(x_1 - y) """ format = options.get('format', 'sympy') if format == 'numpy': import numpy as np if isinstance(expr, QExpr) and not isinstance(expr, OuterProduct): options['replace_none'] = False temp_basis = get_basis(expr, **options) if temp_basis is not None: options['basis'] = temp_basis try: return expr._represent(**options) except NotImplementedError as strerr: #If no _represent_FOO method exists, map to the #appropriate basis state and try #the other methods of representation options['replace_none'] = True if isinstance(expr, (KetBase, BraBase)): try: return rep_innerproduct(expr, **options) except NotImplementedError: raise NotImplementedError(strerr) elif isinstance(expr, Operator): try: return rep_expectation(expr, **options) except NotImplementedError: raise NotImplementedError(strerr) else: raise NotImplementedError(strerr) elif isinstance(expr, Add): result = represent(expr.args[0], **options) for args in expr.args[1:]: # scipy.sparse doesn't support += so we use plain = here. result = result + represent(args, **options) return result elif isinstance(expr, Pow): base, exp = expr.as_base_exp() if format in ('numpy', 'scipy.sparse'): exp = _sympy_to_scalar(exp) base = represent(base, **options) # scipy.sparse doesn't support negative exponents # and warns when inverting a matrix in csr format. if format == 'scipy.sparse' and exp < 0: from scipy.sparse.linalg import inv exp = - exp base = inv(base.tocsc()).tocsr() if format == 'numpy': return np.linalg.matrix_power(base, exp) return base ** exp elif isinstance(expr, TensorProduct): new_args = [represent(arg, **options) for arg in expr.args] return TensorProduct(*new_args) elif isinstance(expr, Dagger): return Dagger(represent(expr.args[0], **options)) elif isinstance(expr, Commutator): A = expr.args[0] B = expr.args[1] return represent(Mul(A, B) - Mul(B, A), **options) elif isinstance(expr, AntiCommutator): A = expr.args[0] B = expr.args[1] return represent(Mul(A, B) + Mul(B, A), **options) elif isinstance(expr, InnerProduct): return represent(Mul(expr.bra, expr.ket), **options) elif not isinstance(expr, (Mul, OuterProduct)): # For numpy and scipy.sparse, we can only handle numerical prefactors. if format in ('numpy', 'scipy.sparse'): return _sympy_to_scalar(expr) return expr if not isinstance(expr, (Mul, OuterProduct)): raise TypeError('Mul expected, got: %r' % expr) if "index" in options: options["index"] += 1 else: options["index"] = 1 if "unities" not in options: options["unities"] = [] result = represent(expr.args[-1], **options) last_arg = expr.args[-1] for arg in reversed(expr.args[:-1]): if isinstance(last_arg, Operator): options["index"] += 1 options["unities"].append(options["index"]) elif isinstance(last_arg, BraBase) and isinstance(arg, KetBase): options["index"] += 1 elif isinstance(last_arg, KetBase) and isinstance(arg, Operator): options["unities"].append(options["index"]) elif isinstance(last_arg, KetBase) and isinstance(arg, BraBase): options["unities"].append(options["index"]) next_arg = represent(arg, **options) if format == 'numpy' and isinstance(next_arg, np.ndarray): # Must use np.matmult to "matrix multiply" two np.ndarray result = np.matmul(next_arg, result) else: result = next_arg*result last_arg = arg # All three matrix formats create 1 by 1 matrices when inner products of # vectors are taken. In these cases, we simply return a scalar. result = flatten_scalar(result) result = integrate_result(expr, result, **options) return result def rep_innerproduct(expr, **options): """ Returns an innerproduct like representation (e.g. ``<x'|x>``) for the given state. Attempts to calculate inner product with a bra from the specified basis. Should only be passed an instance of KetBase or BraBase Parameters ========== expr : KetBase or BraBase The expression to be represented Examples ======== >>> from sympy.physics.quantum.represent import rep_innerproduct >>> from sympy.physics.quantum.cartesian import XOp, XKet, PxOp, PxKet >>> rep_innerproduct(XKet()) DiracDelta(x - x_1) >>> rep_innerproduct(XKet(), basis=PxOp()) sqrt(2)*exp(-I*px_1*x/hbar)/(2*sqrt(hbar)*sqrt(pi)) >>> rep_innerproduct(PxKet(), basis=XOp()) sqrt(2)*exp(I*px*x_1/hbar)/(2*sqrt(hbar)*sqrt(pi)) """ if not isinstance(expr, (KetBase, BraBase)): raise TypeError("expr passed is not a Bra or Ket") basis = get_basis(expr, **options) if not isinstance(basis, StateBase): raise NotImplementedError("Can't form this representation!") if "index" not in options: options["index"] = 1 basis_kets = enumerate_states(basis, options["index"], 2) if isinstance(expr, BraBase): bra = expr ket = (basis_kets[1] if basis_kets[0].dual == expr else basis_kets[0]) else: bra = (basis_kets[1].dual if basis_kets[0] == expr else basis_kets[0].dual) ket = expr prod = InnerProduct(bra, ket) result = prod.doit() format = options.get('format', 'sympy') return expr._format_represent(result, format) def rep_expectation(expr, **options): """ Returns an ``<x'|A|x>`` type representation for the given operator. Parameters ========== expr : Operator Operator to be represented in the specified basis Examples ======== >>> from sympy.physics.quantum.cartesian import XOp, PxOp, PxKet >>> from sympy.physics.quantum.represent import rep_expectation >>> rep_expectation(XOp()) x_1*DiracDelta(x_1 - x_2) >>> rep_expectation(XOp(), basis=PxOp()) <px_2|*X*|px_1> >>> rep_expectation(XOp(), basis=PxKet()) <px_2|*X*|px_1> """ if "index" not in options: options["index"] = 1 if not isinstance(expr, Operator): raise TypeError("The passed expression is not an operator") basis_state = get_basis(expr, **options) if basis_state is None or not isinstance(basis_state, StateBase): raise NotImplementedError("Could not get basis kets for this operator") basis_kets = enumerate_states(basis_state, options["index"], 2) bra = basis_kets[1].dual ket = basis_kets[0] return qapply(bra*expr*ket) def integrate_result(orig_expr, result, **options): """ Returns the result of integrating over any unities ``(|x><x|)`` in the given expression. Intended for integrating over the result of representations in continuous bases. This function integrates over any unities that may have been inserted into the quantum expression and returns the result. It uses the interval of the Hilbert space of the basis state passed to it in order to figure out the limits of integration. The unities option must be specified for this to work. Note: This is mostly used internally by represent(). Examples are given merely to show the use cases. Parameters ========== orig_expr : quantum expression The original expression which was to be represented result: Expr The resulting representation that we wish to integrate over Examples ======== >>> from sympy import symbols, DiracDelta >>> from sympy.physics.quantum.represent import integrate_result >>> from sympy.physics.quantum.cartesian import XOp, XKet >>> x_ket = XKet() >>> X_op = XOp() >>> x, x_1, x_2 = symbols('x, x_1, x_2') >>> integrate_result(X_op*x_ket, x*DiracDelta(x-x_1)*DiracDelta(x_1-x_2)) x*DiracDelta(x - x_1)*DiracDelta(x_1 - x_2) >>> integrate_result(X_op*x_ket, x*DiracDelta(x-x_1)*DiracDelta(x_1-x_2), ... unities=[1]) x*DiracDelta(x - x_2) """ if not isinstance(result, Expr): return result options['replace_none'] = True if "basis" not in options: arg = orig_expr.args[-1] options["basis"] = get_basis(arg, **options) elif not isinstance(options["basis"], StateBase): options["basis"] = get_basis(orig_expr, **options) basis = options.pop("basis", None) if basis is None: return result unities = options.pop("unities", []) if len(unities) == 0: return result kets = enumerate_states(basis, unities) coords = [k.label[0] for k in kets] for coord in coords: if coord in result.free_symbols: #TODO: Add support for sets of operators basis_op = state_to_operators(basis) start = basis_op.hilbert_space.interval.start end = basis_op.hilbert_space.interval.end result = integrate(result, (coord, start, end)) return result def get_basis(expr, *, basis=None, replace_none=True, **options): """ Returns a basis state instance corresponding to the basis specified in options=s. If no basis is specified, the function tries to form a default basis state of the given expression. There are three behaviors: 1. The basis specified in options is already an instance of StateBase. If this is the case, it is simply returned. If the class is specified but not an instance, a default instance is returned. 2. The basis specified is an operator or set of operators. If this is the case, the operator_to_state mapping method is used. 3. No basis is specified. If expr is a state, then a default instance of its class is returned. If expr is an operator, then it is mapped to the corresponding state. If it is neither, then we cannot obtain the basis state. If the basis cannot be mapped, then it is not changed. This will be called from within represent, and represent will only pass QExpr's. TODO (?): Support for Muls and other types of expressions? Parameters ========== expr : Operator or StateBase Expression whose basis is sought Examples ======== >>> from sympy.physics.quantum.represent import get_basis >>> from sympy.physics.quantum.cartesian import XOp, XKet, PxOp, PxKet >>> x = XKet() >>> X = XOp() >>> get_basis(x) |x> >>> get_basis(X) |x> >>> get_basis(x, basis=PxOp()) |px> >>> get_basis(x, basis=PxKet) |px> """ if basis is None and not replace_none: return None if basis is None: if isinstance(expr, KetBase): return _make_default(expr.__class__) elif isinstance(expr, BraBase): return _make_default(expr.dual_class()) elif isinstance(expr, Operator): state_inst = operators_to_state(expr) return (state_inst if state_inst is not None else None) else: return None elif (isinstance(basis, Operator) or (not isinstance(basis, StateBase) and issubclass(basis, Operator))): state = operators_to_state(basis) if state is None: return None elif isinstance(state, StateBase): return state else: return _make_default(state) elif isinstance(basis, StateBase): return basis elif issubclass(basis, StateBase): return _make_default(basis) else: return None def _make_default(expr): # XXX: Catching TypeError like this is a bad way of distinguishing # instances from classes. The logic using this function should be # rewritten somehow. try: expr = expr() except TypeError: return expr return expr def enumerate_states(*args, **options): """ Returns instances of the given state with dummy indices appended Operates in two different modes: 1. Two arguments are passed to it. The first is the base state which is to be indexed, and the second argument is a list of indices to append. 2. Three arguments are passed. The first is again the base state to be indexed. The second is the start index for counting. The final argument is the number of kets you wish to receive. Tries to call state._enumerate_state. If this fails, returns an empty list Parameters ========== args : list See list of operation modes above for explanation Examples ======== >>> from sympy.physics.quantum.cartesian import XBra, XKet >>> from sympy.physics.quantum.represent import enumerate_states >>> test = XKet('foo') >>> enumerate_states(test, 1, 3) [|foo_1>, |foo_2>, |foo_3>] >>> test2 = XBra('bar') >>> enumerate_states(test2, [4, 5, 10]) [<bar_4|, <bar_5|, <bar_10|] """ state = args[0] if len(args) not in (2, 3): raise NotImplementedError("Wrong number of arguments!") if not isinstance(state, StateBase): raise TypeError("First argument is not a state!") if len(args) == 3: num_states = args[2] options['start_index'] = args[1] else: num_states = len(args[1]) options['index_list'] = args[1] try: ret = state._enumerate_state(num_states, **options) except NotImplementedError: ret = [] return ret
3b2573185c9c830ca7f19bec08d62cb83986f34d49bab7cac252b15431c8042a
"""Qubits for quantum computing. Todo: * Finish implementing measurement logic. This should include POVM. * Update docstrings. * Update tests. """ import math from sympy.core.add import Add from sympy.core.mul import Mul from sympy.core.numbers import Integer from sympy.core.power import Pow from sympy.core.singleton import S from sympy.functions.elementary.complexes import conjugate from sympy.functions.elementary.exponential import log from sympy.core.basic import _sympify from sympy.external.gmpy import SYMPY_INTS from sympy.matrices import Matrix, zeros from sympy.printing.pretty.stringpict import prettyForm from sympy.physics.quantum.hilbert import ComplexSpace from sympy.physics.quantum.state import Ket, Bra, State from sympy.physics.quantum.qexpr import QuantumError from sympy.physics.quantum.represent import represent from sympy.physics.quantum.matrixutils import ( numpy_ndarray, scipy_sparse_matrix ) from mpmath.libmp.libintmath import bitcount __all__ = [ 'Qubit', 'QubitBra', 'IntQubit', 'IntQubitBra', 'qubit_to_matrix', 'matrix_to_qubit', 'matrix_to_density', 'measure_all', 'measure_partial', 'measure_partial_oneshot', 'measure_all_oneshot' ] #----------------------------------------------------------------------------- # Qubit Classes #----------------------------------------------------------------------------- class QubitState(State): """Base class for Qubit and QubitBra.""" #------------------------------------------------------------------------- # Initialization/creation #------------------------------------------------------------------------- @classmethod def _eval_args(cls, args): # If we are passed a QubitState or subclass, we just take its qubit # values directly. if len(args) == 1 and isinstance(args[0], QubitState): return args[0].qubit_values # Turn strings into tuple of strings if len(args) == 1 and isinstance(args[0], str): args = tuple( S.Zero if qb == "0" else S.One for qb in args[0]) else: args = tuple( S.Zero if qb == "0" else S.One if qb == "1" else qb for qb in args) args = tuple(_sympify(arg) for arg in args) # Validate input (must have 0 or 1 input) for element in args: if element not in (S.Zero, S.One): raise ValueError( "Qubit values must be 0 or 1, got: %r" % element) return args @classmethod def _eval_hilbert_space(cls, args): return ComplexSpace(2)**len(args) #------------------------------------------------------------------------- # Properties #------------------------------------------------------------------------- @property def dimension(self): """The number of Qubits in the state.""" return len(self.qubit_values) @property def nqubits(self): return self.dimension @property def qubit_values(self): """Returns the values of the qubits as a tuple.""" return self.label #------------------------------------------------------------------------- # Special methods #------------------------------------------------------------------------- def __len__(self): return self.dimension def __getitem__(self, bit): return self.qubit_values[int(self.dimension - bit - 1)] #------------------------------------------------------------------------- # Utility methods #------------------------------------------------------------------------- def flip(self, *bits): """Flip the bit(s) given.""" newargs = list(self.qubit_values) for i in bits: bit = int(self.dimension - i - 1) if newargs[bit] == 1: newargs[bit] = 0 else: newargs[bit] = 1 return self.__class__(*tuple(newargs)) class Qubit(QubitState, Ket): """A multi-qubit ket in the computational (z) basis. We use the normal convention that the least significant qubit is on the right, so ``|00001>`` has a 1 in the least significant qubit. Parameters ========== values : list, str The qubit values as a list of ints ([0,0,0,1,1,]) or a string ('011'). Examples ======== Create a qubit in a couple of different ways and look at their attributes: >>> from sympy.physics.quantum.qubit import Qubit >>> Qubit(0,0,0) |000> >>> q = Qubit('0101') >>> q |0101> >>> q.nqubits 4 >>> len(q) 4 >>> q.dimension 4 >>> q.qubit_values (0, 1, 0, 1) We can flip the value of an individual qubit: >>> q.flip(1) |0111> We can take the dagger of a Qubit to get a bra: >>> from sympy.physics.quantum.dagger import Dagger >>> Dagger(q) <0101| >>> type(Dagger(q)) <class 'sympy.physics.quantum.qubit.QubitBra'> Inner products work as expected: >>> ip = Dagger(q)*q >>> ip <0101|0101> >>> ip.doit() 1 """ @classmethod def dual_class(self): return QubitBra def _eval_innerproduct_QubitBra(self, bra, **hints): if self.label == bra.label: return S.One else: return S.Zero def _represent_default_basis(self, **options): return self._represent_ZGate(None, **options) def _represent_ZGate(self, basis, **options): """Represent this qubits in the computational basis (ZGate). """ _format = options.get('format', 'sympy') n = 1 definite_state = 0 for it in reversed(self.qubit_values): definite_state += n*it n = n*2 result = [0]*(2**self.dimension) result[int(definite_state)] = 1 if _format == 'sympy': return Matrix(result) elif _format == 'numpy': import numpy as np return np.array(result, dtype='complex').transpose() elif _format == 'scipy.sparse': from scipy import sparse return sparse.csr_matrix(result, dtype='complex').transpose() def _eval_trace(self, bra, **kwargs): indices = kwargs.get('indices', []) #sort index list to begin trace from most-significant #qubit sorted_idx = list(indices) if len(sorted_idx) == 0: sorted_idx = list(range(0, self.nqubits)) sorted_idx.sort() #trace out for each of index new_mat = self*bra for i in range(len(sorted_idx) - 1, -1, -1): # start from tracing out from leftmost qubit new_mat = self._reduced_density(new_mat, int(sorted_idx[i])) if (len(sorted_idx) == self.nqubits): #in case full trace was requested return new_mat[0] else: return matrix_to_density(new_mat) def _reduced_density(self, matrix, qubit, **options): """Compute the reduced density matrix by tracing out one qubit. The qubit argument should be of type Python int, since it is used in bit operations """ def find_index_that_is_projected(j, k, qubit): bit_mask = 2**qubit - 1 return ((j >> qubit) << (1 + qubit)) + (j & bit_mask) + (k << qubit) old_matrix = represent(matrix, **options) old_size = old_matrix.cols #we expect the old_size to be even new_size = old_size//2 new_matrix = Matrix().zeros(new_size) for i in range(new_size): for j in range(new_size): for k in range(2): col = find_index_that_is_projected(j, k, qubit) row = find_index_that_is_projected(i, k, qubit) new_matrix[i, j] += old_matrix[row, col] return new_matrix class QubitBra(QubitState, Bra): """A multi-qubit bra in the computational (z) basis. We use the normal convention that the least significant qubit is on the right, so ``|00001>`` has a 1 in the least significant qubit. Parameters ========== values : list, str The qubit values as a list of ints ([0,0,0,1,1,]) or a string ('011'). See also ======== Qubit: Examples using qubits """ @classmethod def dual_class(self): return Qubit class IntQubitState(QubitState): """A base class for qubits that work with binary representations.""" @classmethod def _eval_args(cls, args, nqubits=None): # The case of a QubitState instance if len(args) == 1 and isinstance(args[0], QubitState): return QubitState._eval_args(args) # otherwise, args should be integer elif not all(isinstance(a, (int, Integer)) for a in args): raise ValueError('values must be integers, got (%s)' % (tuple(type(a) for a in args),)) # use nqubits if specified if nqubits is not None: if not isinstance(nqubits, (int, Integer)): raise ValueError('nqubits must be an integer, got (%s)' % type(nqubits)) if len(args) != 1: raise ValueError( 'too many positional arguments (%s). should be (number, nqubits=n)' % (args,)) return cls._eval_args_with_nqubits(args[0], nqubits) # For a single argument, we construct the binary representation of # that integer with the minimal number of bits. if len(args) == 1 and args[0] > 1: #rvalues is the minimum number of bits needed to express the number rvalues = reversed(range(bitcount(abs(args[0])))) qubit_values = [(args[0] >> i) & 1 for i in rvalues] return QubitState._eval_args(qubit_values) # For two numbers, the second number is the number of bits # on which it is expressed, so IntQubit(0,5) == |00000>. elif len(args) == 2 and args[1] > 1: return cls._eval_args_with_nqubits(args[0], args[1]) else: return QubitState._eval_args(args) @classmethod def _eval_args_with_nqubits(cls, number, nqubits): need = bitcount(abs(number)) if nqubits < need: raise ValueError( 'cannot represent %s with %s bits' % (number, nqubits)) qubit_values = [(number >> i) & 1 for i in reversed(range(nqubits))] return QubitState._eval_args(qubit_values) def as_int(self): """Return the numerical value of the qubit.""" number = 0 n = 1 for i in reversed(self.qubit_values): number += n*i n = n << 1 return number def _print_label(self, printer, *args): return str(self.as_int()) def _print_label_pretty(self, printer, *args): label = self._print_label(printer, *args) return prettyForm(label) _print_label_repr = _print_label _print_label_latex = _print_label class IntQubit(IntQubitState, Qubit): """A qubit ket that store integers as binary numbers in qubit values. The differences between this class and ``Qubit`` are: * The form of the constructor. * The qubit values are printed as their corresponding integer, rather than the raw qubit values. The internal storage format of the qubit values in the same as ``Qubit``. Parameters ========== values : int, tuple If a single argument, the integer we want to represent in the qubit values. This integer will be represented using the fewest possible number of qubits. If a pair of integers and the second value is more than one, the first integer gives the integer to represent in binary form and the second integer gives the number of qubits to use. List of zeros and ones is also accepted to generate qubit by bit pattern. nqubits : int The integer that represents the number of qubits. This number should be passed with keyword ``nqubits=N``. You can use this in order to avoid ambiguity of Qubit-style tuple of bits. Please see the example below for more details. Examples ======== Create a qubit for the integer 5: >>> from sympy.physics.quantum.qubit import IntQubit >>> from sympy.physics.quantum.qubit import Qubit >>> q = IntQubit(5) >>> q |5> We can also create an ``IntQubit`` by passing a ``Qubit`` instance. >>> q = IntQubit(Qubit('101')) >>> q |5> >>> q.as_int() 5 >>> q.nqubits 3 >>> q.qubit_values (1, 0, 1) We can go back to the regular qubit form. >>> Qubit(q) |101> Please note that ``IntQubit`` also accepts a ``Qubit``-style list of bits. So, the code below yields qubits 3, not a single bit ``1``. >>> IntQubit(1, 1) |3> To avoid ambiguity, use ``nqubits`` parameter. Use of this keyword is recommended especially when you provide the values by variables. >>> IntQubit(1, nqubits=1) |1> >>> a = 1 >>> IntQubit(a, nqubits=1) |1> """ @classmethod def dual_class(self): return IntQubitBra def _eval_innerproduct_IntQubitBra(self, bra, **hints): return Qubit._eval_innerproduct_QubitBra(self, bra) class IntQubitBra(IntQubitState, QubitBra): """A qubit bra that store integers as binary numbers in qubit values.""" @classmethod def dual_class(self): return IntQubit #----------------------------------------------------------------------------- # Qubit <---> Matrix conversion functions #----------------------------------------------------------------------------- def matrix_to_qubit(matrix): """Convert from the matrix repr. to a sum of Qubit objects. Parameters ---------- matrix : Matrix, numpy.matrix, scipy.sparse The matrix to build the Qubit representation of. This works with SymPy matrices, numpy matrices and scipy.sparse sparse matrices. Examples ======== Represent a state and then go back to its qubit form: >>> from sympy.physics.quantum.qubit import matrix_to_qubit, Qubit >>> from sympy.physics.quantum.represent import represent >>> q = Qubit('01') >>> matrix_to_qubit(represent(q)) |01> """ # Determine the format based on the type of the input matrix format = 'sympy' if isinstance(matrix, numpy_ndarray): format = 'numpy' if isinstance(matrix, scipy_sparse_matrix): format = 'scipy.sparse' # Make sure it is of correct dimensions for a Qubit-matrix representation. # This logic should work with sympy, numpy or scipy.sparse matrices. if matrix.shape[0] == 1: mlistlen = matrix.shape[1] nqubits = log(mlistlen, 2) ket = False cls = QubitBra elif matrix.shape[1] == 1: mlistlen = matrix.shape[0] nqubits = log(mlistlen, 2) ket = True cls = Qubit else: raise QuantumError( 'Matrix must be a row/column vector, got %r' % matrix ) if not isinstance(nqubits, Integer): raise QuantumError('Matrix must be a row/column vector of size ' '2**nqubits, got: %r' % matrix) # Go through each item in matrix, if element is non-zero, make it into a # Qubit item times the element. result = 0 for i in range(mlistlen): if ket: element = matrix[i, 0] else: element = matrix[0, i] if format in ('numpy', 'scipy.sparse'): element = complex(element) if element != 0.0: # Form Qubit array; 0 in bit-locations where i is 0, 1 in # bit-locations where i is 1 qubit_array = [int(i & (1 << x) != 0) for x in range(nqubits)] qubit_array.reverse() result = result + element*cls(*qubit_array) # If SymPy simplified by pulling out a constant coefficient, undo that. if isinstance(result, (Mul, Add, Pow)): result = result.expand() return result def matrix_to_density(mat): """ Works by finding the eigenvectors and eigenvalues of the matrix. We know we can decompose rho by doing: sum(EigenVal*|Eigenvect><Eigenvect|) """ from sympy.physics.quantum.density import Density eigen = mat.eigenvects() args = [[matrix_to_qubit(Matrix( [vector, ])), x[0]] for x in eigen for vector in x[2] if x[0] != 0] if (len(args) == 0): return S.Zero else: return Density(*args) def qubit_to_matrix(qubit, format='sympy'): """Converts an Add/Mul of Qubit objects into it's matrix representation This function is the inverse of ``matrix_to_qubit`` and is a shorthand for ``represent(qubit)``. """ return represent(qubit, format=format) #----------------------------------------------------------------------------- # Measurement #----------------------------------------------------------------------------- def measure_all(qubit, format='sympy', normalize=True): """Perform an ensemble measurement of all qubits. Parameters ========== qubit : Qubit, Add The qubit to measure. This can be any Qubit or a linear combination of them. format : str The format of the intermediate matrices to use. Possible values are ('sympy','numpy','scipy.sparse'). Currently only 'sympy' is implemented. Returns ======= result : list A list that consists of primitive states and their probabilities. Examples ======== >>> from sympy.physics.quantum.qubit import Qubit, measure_all >>> from sympy.physics.quantum.gate import H >>> from sympy.physics.quantum.qapply import qapply >>> c = H(0)*H(1)*Qubit('00') >>> c H(0)*H(1)*|00> >>> q = qapply(c) >>> measure_all(q) [(|00>, 1/4), (|01>, 1/4), (|10>, 1/4), (|11>, 1/4)] """ m = qubit_to_matrix(qubit, format) if format == 'sympy': results = [] if normalize: m = m.normalized() size = max(m.shape) # Max of shape to account for bra or ket nqubits = int(math.log(size)/math.log(2)) for i in range(size): if m[i] != 0.0: results.append( (Qubit(IntQubit(i, nqubits=nqubits)), m[i]*conjugate(m[i])) ) return results else: raise NotImplementedError( "This function cannot handle non-SymPy matrix formats yet" ) def measure_partial(qubit, bits, format='sympy', normalize=True): """Perform a partial ensemble measure on the specified qubits. Parameters ========== qubits : Qubit The qubit to measure. This can be any Qubit or a linear combination of them. bits : tuple The qubits to measure. format : str The format of the intermediate matrices to use. Possible values are ('sympy','numpy','scipy.sparse'). Currently only 'sympy' is implemented. Returns ======= result : list A list that consists of primitive states and their probabilities. Examples ======== >>> from sympy.physics.quantum.qubit import Qubit, measure_partial >>> from sympy.physics.quantum.gate import H >>> from sympy.physics.quantum.qapply import qapply >>> c = H(0)*H(1)*Qubit('00') >>> c H(0)*H(1)*|00> >>> q = qapply(c) >>> measure_partial(q, (0,)) [(sqrt(2)*|00>/2 + sqrt(2)*|10>/2, 1/2), (sqrt(2)*|01>/2 + sqrt(2)*|11>/2, 1/2)] """ m = qubit_to_matrix(qubit, format) if isinstance(bits, (SYMPY_INTS, Integer)): bits = (int(bits),) if format == 'sympy': if normalize: m = m.normalized() possible_outcomes = _get_possible_outcomes(m, bits) # Form output from function. output = [] for outcome in possible_outcomes: # Calculate probability of finding the specified bits with # given values. prob_of_outcome = 0 prob_of_outcome += (outcome.H*outcome)[0] # If the output has a chance, append it to output with found # probability. if prob_of_outcome != 0: if normalize: next_matrix = matrix_to_qubit(outcome.normalized()) else: next_matrix = matrix_to_qubit(outcome) output.append(( next_matrix, prob_of_outcome )) return output else: raise NotImplementedError( "This function cannot handle non-SymPy matrix formats yet" ) def measure_partial_oneshot(qubit, bits, format='sympy'): """Perform a partial oneshot measurement on the specified qubits. A oneshot measurement is equivalent to performing a measurement on a quantum system. This type of measurement does not return the probabilities like an ensemble measurement does, but rather returns *one* of the possible resulting states. The exact state that is returned is determined by picking a state randomly according to the ensemble probabilities. Parameters ---------- qubits : Qubit The qubit to measure. This can be any Qubit or a linear combination of them. bits : tuple The qubits to measure. format : str The format of the intermediate matrices to use. Possible values are ('sympy','numpy','scipy.sparse'). Currently only 'sympy' is implemented. Returns ------- result : Qubit The qubit that the system collapsed to upon measurement. """ import random m = qubit_to_matrix(qubit, format) if format == 'sympy': m = m.normalized() possible_outcomes = _get_possible_outcomes(m, bits) # Form output from function random_number = random.random() total_prob = 0 for outcome in possible_outcomes: # Calculate probability of finding the specified bits # with given values total_prob += (outcome.H*outcome)[0] if total_prob >= random_number: return matrix_to_qubit(outcome.normalized()) else: raise NotImplementedError( "This function cannot handle non-SymPy matrix formats yet" ) def _get_possible_outcomes(m, bits): """Get the possible states that can be produced in a measurement. Parameters ---------- m : Matrix The matrix representing the state of the system. bits : tuple, list Which bits will be measured. Returns ------- result : list The list of possible states which can occur given this measurement. These are un-normalized so we can derive the probability of finding this state by taking the inner product with itself """ # This is filled with loads of dirty binary tricks...You have been warned size = max(m.shape) # Max of shape to account for bra or ket nqubits = int(math.log(size, 2) + .1) # Number of qubits possible # Make the output states and put in output_matrices, nothing in them now. # Each state will represent a possible outcome of the measurement # Thus, output_matrices[0] is the matrix which we get when all measured # bits return 0. and output_matrices[1] is the matrix for only the 0th # bit being true output_matrices = [] for i in range(1 << len(bits)): output_matrices.append(zeros(2**nqubits, 1)) # Bitmasks will help sort how to determine possible outcomes. # When the bit mask is and-ed with a matrix-index, # it will determine which state that index belongs to bit_masks = [] for bit in bits: bit_masks.append(1 << bit) # Make possible outcome states for i in range(2**nqubits): trueness = 0 # This tells us to which output_matrix this value belongs # Find trueness for j in range(len(bit_masks)): if i & bit_masks[j]: trueness += j + 1 # Put the value in the correct output matrix output_matrices[trueness][i] = m[i] return output_matrices def measure_all_oneshot(qubit, format='sympy'): """Perform a oneshot ensemble measurement on all qubits. A oneshot measurement is equivalent to performing a measurement on a quantum system. This type of measurement does not return the probabilities like an ensemble measurement does, but rather returns *one* of the possible resulting states. The exact state that is returned is determined by picking a state randomly according to the ensemble probabilities. Parameters ---------- qubits : Qubit The qubit to measure. This can be any Qubit or a linear combination of them. format : str The format of the intermediate matrices to use. Possible values are ('sympy','numpy','scipy.sparse'). Currently only 'sympy' is implemented. Returns ------- result : Qubit The qubit that the system collapsed to upon measurement. """ import random m = qubit_to_matrix(qubit) if format == 'sympy': m = m.normalized() random_number = random.random() total = 0 result = 0 for i in m: total += i*i.conjugate() if total > random_number: break result += 1 return Qubit(IntQubit(result, int(math.log(max(m.shape), 2) + .1))) else: raise NotImplementedError( "This function cannot handle non-SymPy matrix formats yet" )
84772cb707d41927a313345deb3de03e49db1ef658deaabce7d4c14ef919a1ba
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) #------------------------------------------------------------------------- # Methods from Basic and Expr #------------------------------------------------------------------------- def doit(self, **kw_args): return self #------------------------------------------------------------------------- # 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) )
0aed843d3396a5fcb160c54e7460597b3f12059da2d901149879d388f3d28be3
"""Grover's algorithm and helper functions. Todo: * W gate construction (or perhaps -W gate based on Mermin's book) * Generalize the algorithm for an unknown function that returns 1 on multiple qubit states, not just one. * Implement _represent_ZGate in OracleGate """ from sympy.core.numbers import pi from sympy.core.sympify import sympify from sympy.core.basic import Atom from sympy.functions.elementary.integers import floor from sympy.functions.elementary.miscellaneous import sqrt from sympy.matrices.dense import eye from sympy.core.numbers import NegativeOne from sympy.physics.quantum.qapply import qapply from sympy.physics.quantum.qexpr import QuantumError from sympy.physics.quantum.hilbert import ComplexSpace from sympy.physics.quantum.operator import UnitaryOperator from sympy.physics.quantum.gate import Gate from sympy.physics.quantum.qubit import IntQubit __all__ = [ 'OracleGate', 'WGate', 'superposition_basis', 'grover_iteration', 'apply_grover' ] def superposition_basis(nqubits): """Creates an equal superposition of the computational basis. Parameters ========== nqubits : int The number of qubits. Returns ======= state : Qubit An equal superposition of the computational basis with nqubits. Examples ======== Create an equal superposition of 2 qubits:: >>> from sympy.physics.quantum.grover import superposition_basis >>> superposition_basis(2) |0>/2 + |1>/2 + |2>/2 + |3>/2 """ amp = 1/sqrt(2**nqubits) return sum([amp*IntQubit(n, nqubits=nqubits) for n in range(2**nqubits)]) class OracleGateFunction(Atom): """Wrapper for python functions used in `OracleGate`s""" def __new__(cls, function): if not callable(function): raise TypeError('Callable expected, got: %r' % function) obj = Atom.__new__(cls) obj.function = function return obj def _hashable_content(self): return type(self), self.function def __call__(self, *args): return self.function(*args) class OracleGate(Gate): """A black box gate. The gate marks the desired qubits of an unknown function by flipping the sign of the qubits. The unknown function returns true when it finds its desired qubits and false otherwise. Parameters ========== qubits : int Number of qubits. oracle : callable A callable function that returns a boolean on a computational basis. Examples ======== Apply an Oracle gate that flips the sign of ``|2>`` on different qubits:: >>> from sympy.physics.quantum.qubit import IntQubit >>> from sympy.physics.quantum.qapply import qapply >>> from sympy.physics.quantum.grover import OracleGate >>> f = lambda qubits: qubits == IntQubit(2) >>> v = OracleGate(2, f) >>> qapply(v*IntQubit(2)) -|2> >>> qapply(v*IntQubit(3)) |3> """ gate_name = 'V' gate_name_latex = 'V' #------------------------------------------------------------------------- # Initialization/creation #------------------------------------------------------------------------- @classmethod def _eval_args(cls, args): if len(args) != 2: raise QuantumError( 'Insufficient/excessive arguments to Oracle. Please ' + 'supply the number of qubits and an unknown function.' ) sub_args = (args[0],) sub_args = UnitaryOperator._eval_args(sub_args) if not sub_args[0].is_Integer: raise TypeError('Integer expected, got: %r' % sub_args[0]) function = args[1] if not isinstance(function, OracleGateFunction): function = OracleGateFunction(function) return (sub_args[0], function) @classmethod def _eval_hilbert_space(cls, args): """This returns the smallest possible Hilbert space.""" return ComplexSpace(2)**args[0] #------------------------------------------------------------------------- # Properties #------------------------------------------------------------------------- @property def search_function(self): """The unknown function that helps find the sought after qubits.""" return self.label[1] @property def targets(self): """A tuple of target qubits.""" return sympify(tuple(range(self.args[0]))) #------------------------------------------------------------------------- # Apply #------------------------------------------------------------------------- def _apply_operator_Qubit(self, qubits, **options): """Apply this operator to a Qubit subclass. Parameters ========== qubits : Qubit The qubit subclass to apply this operator to. Returns ======= state : Expr The resulting quantum state. """ if qubits.nqubits != self.nqubits: raise QuantumError( 'OracleGate operates on %r qubits, got: %r' % (self.nqubits, qubits.nqubits) ) # If function returns 1 on qubits # return the negative of the qubits (flip the sign) if self.search_function(qubits): return -qubits else: return qubits #------------------------------------------------------------------------- # Represent #------------------------------------------------------------------------- def _represent_ZGate(self, basis, **options): """ Represent the OracleGate in the computational basis. """ nbasis = 2**self.nqubits # compute it only once matrixOracle = eye(nbasis) # Flip the sign given the output of the oracle function for i in range(nbasis): if self.search_function(IntQubit(i, nqubits=self.nqubits)): matrixOracle[i, i] = NegativeOne() return matrixOracle class WGate(Gate): """General n qubit W Gate in Grover's algorithm. The gate performs the operation ``2|phi><phi| - 1`` on some qubits. ``|phi> = (tensor product of n Hadamards)*(|0> with n qubits)`` Parameters ========== nqubits : int The number of qubits to operate on """ gate_name = 'W' gate_name_latex = 'W' @classmethod def _eval_args(cls, args): if len(args) != 1: raise QuantumError( 'Insufficient/excessive arguments to W gate. Please ' + 'supply the number of qubits to operate on.' ) args = UnitaryOperator._eval_args(args) if not args[0].is_Integer: raise TypeError('Integer expected, got: %r' % args[0]) return args #------------------------------------------------------------------------- # Properties #------------------------------------------------------------------------- @property def targets(self): return sympify(tuple(reversed(range(self.args[0])))) #------------------------------------------------------------------------- # Apply #------------------------------------------------------------------------- def _apply_operator_Qubit(self, qubits, **options): """ qubits: a set of qubits (Qubit) Returns: quantum object (quantum expression - QExpr) """ if qubits.nqubits != self.nqubits: raise QuantumError( 'WGate operates on %r qubits, got: %r' % (self.nqubits, qubits.nqubits) ) # See 'Quantum Computer Science' by David Mermin p.92 -> W|a> result # Return (2/(sqrt(2^n)))|phi> - |a> where |a> is the current basis # state and phi is the superposition of basis states (see function # create_computational_basis above) basis_states = superposition_basis(self.nqubits) change_to_basis = (2/sqrt(2**self.nqubits))*basis_states return change_to_basis - qubits def grover_iteration(qstate, oracle): """Applies one application of the Oracle and W Gate, WV. Parameters ========== qstate : Qubit A superposition of qubits. oracle : OracleGate The black box operator that flips the sign of the desired basis qubits. Returns ======= Qubit : The qubits after applying the Oracle and W gate. Examples ======== Perform one iteration of grover's algorithm to see a phase change:: >>> from sympy.physics.quantum.qapply import qapply >>> from sympy.physics.quantum.qubit import IntQubit >>> from sympy.physics.quantum.grover import OracleGate >>> from sympy.physics.quantum.grover import superposition_basis >>> from sympy.physics.quantum.grover import grover_iteration >>> numqubits = 2 >>> basis_states = superposition_basis(numqubits) >>> f = lambda qubits: qubits == IntQubit(2) >>> v = OracleGate(numqubits, f) >>> qapply(grover_iteration(basis_states, v)) |2> """ wgate = WGate(oracle.nqubits) return wgate*oracle*qstate def apply_grover(oracle, nqubits, iterations=None): """Applies grover's algorithm. Parameters ========== oracle : callable The unknown callable function that returns true when applied to the desired qubits and false otherwise. Returns ======= state : Expr The resulting state after Grover's algorithm has been iterated. Examples ======== Apply grover's algorithm to an even superposition of 2 qubits:: >>> from sympy.physics.quantum.qapply import qapply >>> from sympy.physics.quantum.qubit import IntQubit >>> from sympy.physics.quantum.grover import apply_grover >>> f = lambda qubits: qubits == IntQubit(2) >>> qapply(apply_grover(f, 2)) |2> """ if nqubits <= 0: raise QuantumError( 'Grover\'s algorithm needs nqubits > 0, received %r qubits' % nqubits ) if iterations is None: iterations = floor(sqrt(2**nqubits)*(pi/4)) v = OracleGate(nqubits, oracle) iterated = superposition_basis(nqubits) for iter in range(iterations): iterated = grover_iteration(iterated, v) iterated = qapply(iterated) return iterated
75b94143719e71a6009f80515d2e624665fa980983784daf2137f94514f8dbad
"""Matplotlib based plotting of quantum circuits. Todo: * Optimize printing of large circuits. * Get this to work with single gates. * Do a better job checking the form of circuits to make sure it is a Mul of Gates. * Get multi-target gates plotting. * Get initial and final states to plot. * Get measurements to plot. Might need to rethink measurement as a gate issue. * Get scale and figsize to be handled in a better way. * Write some tests/examples! """ from typing import List, Dict as tDict from sympy.core.mul import Mul from sympy.external import import_module from sympy.physics.quantum.gate import Gate, OneQubitGate, CGate, CGateS from sympy.core.core import BasicMeta from sympy.core.assumptions import ManagedProperties __all__ = [ 'CircuitPlot', 'circuit_plot', 'labeller', 'Mz', 'Mx', 'CreateOneQubitGate', 'CreateCGate', ] np = import_module('numpy') matplotlib = import_module( 'matplotlib', import_kwargs={'fromlist': ['pyplot']}, catch=(RuntimeError,)) # This is raised in environments that have no display. if np and matplotlib: pyplot = matplotlib.pyplot Line2D = matplotlib.lines.Line2D Circle = matplotlib.patches.Circle #from matplotlib import rc #rc('text',usetex=True) class CircuitPlot: """A class for managing a circuit plot.""" scale = 1.0 fontsize = 20.0 linewidth = 1.0 control_radius = 0.05 not_radius = 0.15 swap_delta = 0.05 labels = [] # type: List[str] inits = {} # type: tDict[str, str] label_buffer = 0.5 def __init__(self, c, nqubits, **kwargs): if not np or not matplotlib: raise ImportError('numpy or matplotlib not available.') self.circuit = c self.ngates = len(self.circuit.args) self.nqubits = nqubits self.update(kwargs) self._create_grid() self._create_figure() self._plot_wires() self._plot_gates() self._finish() def update(self, kwargs): """Load the kwargs into the instance dict.""" self.__dict__.update(kwargs) def _create_grid(self): """Create the grid of wires.""" scale = self.scale wire_grid = np.arange(0.0, self.nqubits*scale, scale, dtype=float) gate_grid = np.arange(0.0, self.ngates*scale, scale, dtype=float) self._wire_grid = wire_grid self._gate_grid = gate_grid def _create_figure(self): """Create the main matplotlib figure.""" self._figure = pyplot.figure( figsize=(self.ngates*self.scale, self.nqubits*self.scale), facecolor='w', edgecolor='w' ) ax = self._figure.add_subplot( 1, 1, 1, frameon=True ) ax.set_axis_off() offset = 0.5*self.scale ax.set_xlim(self._gate_grid[0] - offset, self._gate_grid[-1] + offset) ax.set_ylim(self._wire_grid[0] - offset, self._wire_grid[-1] + offset) ax.set_aspect('equal') self._axes = ax def _plot_wires(self): """Plot the wires of the circuit diagram.""" xstart = self._gate_grid[0] xstop = self._gate_grid[-1] xdata = (xstart - self.scale, xstop + self.scale) for i in range(self.nqubits): ydata = (self._wire_grid[i], self._wire_grid[i]) line = Line2D( xdata, ydata, color='k', lw=self.linewidth ) self._axes.add_line(line) if self.labels: init_label_buffer = 0 if self.inits.get(self.labels[i]): init_label_buffer = 0.25 self._axes.text( xdata[0]-self.label_buffer-init_label_buffer,ydata[0], render_label(self.labels[i],self.inits), size=self.fontsize, color='k',ha='center',va='center') self._plot_measured_wires() def _plot_measured_wires(self): ismeasured = self._measurements() xstop = self._gate_grid[-1] dy = 0.04 # amount to shift wires when doubled # Plot doubled wires after they are measured for im in ismeasured: xdata = (self._gate_grid[ismeasured[im]],xstop+self.scale) ydata = (self._wire_grid[im]+dy,self._wire_grid[im]+dy) line = Line2D( xdata, ydata, color='k', lw=self.linewidth ) self._axes.add_line(line) # Also double any controlled lines off these wires for i,g in enumerate(self._gates()): if isinstance(g, (CGate, CGateS)): wires = g.controls + g.targets for wire in wires: if wire in ismeasured and \ self._gate_grid[i] > self._gate_grid[ismeasured[wire]]: ydata = min(wires), max(wires) xdata = self._gate_grid[i]-dy, self._gate_grid[i]-dy line = Line2D( xdata, ydata, color='k', lw=self.linewidth ) self._axes.add_line(line) def _gates(self): """Create a list of all gates in the circuit plot.""" gates = [] if isinstance(self.circuit, Mul): for g in reversed(self.circuit.args): if isinstance(g, Gate): gates.append(g) elif isinstance(self.circuit, Gate): gates.append(self.circuit) return gates def _plot_gates(self): """Iterate through the gates and plot each of them.""" for i, gate in enumerate(self._gates()): gate.plot_gate(self, i) def _measurements(self): """Return a dict ``{i:j}`` where i is the index of the wire that has been measured, and j is the gate where the wire is measured. """ ismeasured = {} for i,g in enumerate(self._gates()): if getattr(g,'measurement',False): for target in g.targets: if target in ismeasured: if ismeasured[target] > i: ismeasured[target] = i else: ismeasured[target] = i return ismeasured def _finish(self): # Disable clipping to make panning work well for large circuits. for o in self._figure.findobj(): o.set_clip_on(False) def one_qubit_box(self, t, gate_idx, wire_idx): """Draw a box for a single qubit gate.""" x = self._gate_grid[gate_idx] y = self._wire_grid[wire_idx] self._axes.text( x, y, t, color='k', ha='center', va='center', bbox=dict(ec='k', fc='w', fill=True, lw=self.linewidth), size=self.fontsize ) def two_qubit_box(self, t, gate_idx, wire_idx): """Draw a box for a two qubit gate. Does not work yet. """ # x = self._gate_grid[gate_idx] # y = self._wire_grid[wire_idx]+0.5 print(self._gate_grid) print(self._wire_grid) # unused: # obj = self._axes.text( # x, y, t, # color='k', # ha='center', # va='center', # bbox=dict(ec='k', fc='w', fill=True, lw=self.linewidth), # size=self.fontsize # ) def control_line(self, gate_idx, min_wire, max_wire): """Draw a vertical control line.""" xdata = (self._gate_grid[gate_idx], self._gate_grid[gate_idx]) ydata = (self._wire_grid[min_wire], self._wire_grid[max_wire]) line = Line2D( xdata, ydata, color='k', lw=self.linewidth ) self._axes.add_line(line) def control_point(self, gate_idx, wire_idx): """Draw a control point.""" x = self._gate_grid[gate_idx] y = self._wire_grid[wire_idx] radius = self.control_radius c = Circle( (x, y), radius*self.scale, ec='k', fc='k', fill=True, lw=self.linewidth ) self._axes.add_patch(c) def not_point(self, gate_idx, wire_idx): """Draw a NOT gates as the circle with plus in the middle.""" x = self._gate_grid[gate_idx] y = self._wire_grid[wire_idx] radius = self.not_radius c = Circle( (x, y), radius, ec='k', fc='w', fill=False, lw=self.linewidth ) self._axes.add_patch(c) l = Line2D( (x, x), (y - radius, y + radius), color='k', lw=self.linewidth ) self._axes.add_line(l) def swap_point(self, gate_idx, wire_idx): """Draw a swap point as a cross.""" x = self._gate_grid[gate_idx] y = self._wire_grid[wire_idx] d = self.swap_delta l1 = Line2D( (x - d, x + d), (y - d, y + d), color='k', lw=self.linewidth ) l2 = Line2D( (x - d, x + d), (y + d, y - d), color='k', lw=self.linewidth ) self._axes.add_line(l1) self._axes.add_line(l2) def circuit_plot(c, nqubits, **kwargs): """Draw the circuit diagram for the circuit with nqubits. Parameters ========== c : circuit The circuit to plot. Should be a product of Gate instances. nqubits : int The number of qubits to include in the circuit. Must be at least as big as the largest ``min_qubits`` of the gates. """ return CircuitPlot(c, nqubits, **kwargs) def render_label(label, inits={}): """Slightly more flexible way to render labels. >>> from sympy.physics.quantum.circuitplot import render_label >>> render_label('q0') '$\\\\left|q0\\\\right\\\\rangle$' >>> render_label('q0', {'q0':'0'}) '$\\\\left|q0\\\\right\\\\rangle=\\\\left|0\\\\right\\\\rangle$' """ init = inits.get(label) if init: return r'$\left|%s\right\rangle=\left|%s\right\rangle$' % (label, init) return r'$\left|%s\right\rangle$' % label def labeller(n, symbol='q'): """Autogenerate labels for wires of quantum circuits. Parameters ========== n : int number of qubits in the circuit. symbol : string A character string to precede all gate labels. E.g. 'q_0', 'q_1', etc. >>> from sympy.physics.quantum.circuitplot import labeller >>> labeller(2) ['q_1', 'q_0'] >>> labeller(3,'j') ['j_2', 'j_1', 'j_0'] """ return ['%s_%d' % (symbol,n-i-1) for i in range(n)] class Mz(OneQubitGate): """Mock-up of a z measurement gate. This is in circuitplot rather than gate.py because it's not a real gate, it just draws one. """ measurement = True gate_name='Mz' gate_name_latex='M_z' class Mx(OneQubitGate): """Mock-up of an x measurement gate. This is in circuitplot rather than gate.py because it's not a real gate, it just draws one. """ measurement = True gate_name='Mx' gate_name_latex='M_x' class CreateOneQubitGate(ManagedProperties): def __new__(mcl, name, latexname=None): if not latexname: latexname = name return BasicMeta.__new__(mcl, name + "Gate", (OneQubitGate,), {'gate_name': name, 'gate_name_latex': latexname}) def CreateCGate(name, latexname=None): """Use a lexical closure to make a controlled gate. """ if not latexname: latexname = name onequbitgate = CreateOneQubitGate(name, latexname) def ControlledGate(ctrls,target): return CGate(tuple(ctrls),onequbitgate(target)) return ControlledGate
d928fba1e267e6efcc24a011cbabb0f04412a2d85940866e3ce6dc612f68550b
from sympy.core.backend import sympify from sympy.physics.vector import Point, ReferenceFrame, Dyadic from sympy.utilities.exceptions import sympy_deprecation_warning __all__ = ['RigidBody'] class RigidBody: """An idealized rigid body. Explanation =========== This is essentially a container which holds the various components which describe a rigid body: a name, mass, center of mass, reference frame, and inertia. All of these need to be supplied on creation, but can be changed afterwards. Attributes ========== name : string The body's name. masscenter : Point The point which represents the center of mass of the rigid body. frame : ReferenceFrame The ReferenceFrame which the rigid body is fixed in. mass : Sympifyable The body's mass. inertia : (Dyadic, Point) The body's inertia about a point; stored in a tuple as shown above. Examples ======== >>> from sympy import Symbol >>> from sympy.physics.mechanics import ReferenceFrame, Point, RigidBody >>> from sympy.physics.mechanics import outer >>> m = Symbol('m') >>> A = ReferenceFrame('A') >>> P = Point('P') >>> I = outer (A.x, A.x) >>> inertia_tuple = (I, P) >>> B = RigidBody('B', P, A, m, inertia_tuple) >>> # Or you could change them afterwards >>> m2 = Symbol('m2') >>> B.mass = m2 """ def __init__(self, name, masscenter, frame, mass, inertia): if not isinstance(name, str): raise TypeError('Supply a valid name.') self._name = name self.masscenter = masscenter self.mass = mass self.frame = frame self.inertia = inertia self.potential_energy = 0 def __str__(self): return self._name def __repr__(self): return self.__str__() @property def frame(self): return self._frame @frame.setter def frame(self, F): if not isinstance(F, ReferenceFrame): raise TypeError("RigdBody frame must be a ReferenceFrame object.") self._frame = F @property def masscenter(self): return self._masscenter @masscenter.setter def masscenter(self, p): if not isinstance(p, Point): raise TypeError("RigidBody center of mass must be a Point object.") self._masscenter = p @property def mass(self): return self._mass @mass.setter def mass(self, m): self._mass = sympify(m) @property def inertia(self): return (self._inertia, self._inertia_point) @inertia.setter def inertia(self, I): if not isinstance(I[0], Dyadic): raise TypeError("RigidBody inertia must be a Dyadic object.") if not isinstance(I[1], Point): raise TypeError("RigidBody inertia must be about a Point.") self._inertia = I[0] self._inertia_point = I[1] # have I S/O, want I S/S* # I S/O = I S/S* + I S*/O; I S/S* = I S/O - I S*/O # I_S/S* = I_S/O - I_S*/O from sympy.physics.mechanics.functions import inertia_of_point_mass I_Ss_O = inertia_of_point_mass(self.mass, self.masscenter.pos_from(I[1]), self.frame) self._central_inertia = I[0] - I_Ss_O @property def central_inertia(self): """The body's central inertia dyadic.""" return self._central_inertia def linear_momentum(self, frame): """ Linear momentum of the rigid body. Explanation =========== The linear momentum L, of a rigid body B, with respect to frame N is given by L = M * v* where M is the mass of the rigid body and v* is the velocity of the mass center of B in the frame, N. Parameters ========== frame : ReferenceFrame The frame in which linear momentum is desired. Examples ======== >>> from sympy.physics.mechanics import Point, ReferenceFrame, outer >>> from sympy.physics.mechanics import RigidBody, dynamicsymbols >>> from sympy.physics.vector import init_vprinting >>> init_vprinting(pretty_print=False) >>> M, v = dynamicsymbols('M v') >>> N = ReferenceFrame('N') >>> P = Point('P') >>> P.set_vel(N, v * N.x) >>> I = outer (N.x, N.x) >>> Inertia_tuple = (I, P) >>> B = RigidBody('B', P, N, M, Inertia_tuple) >>> B.linear_momentum(N) M*v*N.x """ return self.mass * self.masscenter.vel(frame) def angular_momentum(self, point, frame): """Returns the angular momentum of the rigid body about a point in the given frame. Explanation =========== The angular momentum H of a rigid body B about some point O in a frame N is given by: H = I . w + r x Mv where I is the central inertia dyadic of B, w is the angular velocity of body B in the frame, N, r is the position vector from point O to the mass center of B, and v is the velocity of the mass center in the frame, N. Parameters ========== point : Point The point about which angular momentum is desired. frame : ReferenceFrame The frame in which angular momentum is desired. Examples ======== >>> from sympy.physics.mechanics import Point, ReferenceFrame, outer >>> from sympy.physics.mechanics import RigidBody, dynamicsymbols >>> from sympy.physics.vector import init_vprinting >>> init_vprinting(pretty_print=False) >>> M, v, r, omega = dynamicsymbols('M v r omega') >>> N = ReferenceFrame('N') >>> b = ReferenceFrame('b') >>> b.set_ang_vel(N, omega * b.x) >>> P = Point('P') >>> P.set_vel(N, 1 * N.x) >>> I = outer(b.x, b.x) >>> B = RigidBody('B', P, b, M, (I, P)) >>> B.angular_momentum(P, N) omega*b.x """ I = self.central_inertia w = self.frame.ang_vel_in(frame) m = self.mass r = self.masscenter.pos_from(point) v = self.masscenter.vel(frame) return I.dot(w) + r.cross(m * v) def kinetic_energy(self, frame): """Kinetic energy of the rigid body. Explanation =========== The kinetic energy, T, of a rigid body, B, is given by 'T = 1/2 (I omega^2 + m v^2)' where I and m are the central inertia dyadic and mass of rigid body B, respectively, omega is the body's angular velocity and v is the velocity of the body's mass center in the supplied ReferenceFrame. Parameters ========== frame : ReferenceFrame The RigidBody's angular velocity and the velocity of it's mass center are typically defined with respect to an inertial frame but any relevant frame in which the velocities are known can be supplied. Examples ======== >>> from sympy.physics.mechanics import Point, ReferenceFrame, outer >>> from sympy.physics.mechanics import RigidBody >>> from sympy import symbols >>> M, v, r, omega = symbols('M v r omega') >>> N = ReferenceFrame('N') >>> b = ReferenceFrame('b') >>> b.set_ang_vel(N, omega * b.x) >>> P = Point('P') >>> P.set_vel(N, v * N.x) >>> I = outer (b.x, b.x) >>> inertia_tuple = (I, P) >>> B = RigidBody('B', P, b, M, inertia_tuple) >>> B.kinetic_energy(N) M*v**2/2 + omega**2/2 """ rotational_KE = (self.frame.ang_vel_in(frame) & (self.central_inertia & self.frame.ang_vel_in(frame)) / sympify(2)) translational_KE = (self.mass * (self.masscenter.vel(frame) & self.masscenter.vel(frame)) / sympify(2)) return rotational_KE + translational_KE @property def potential_energy(self): """The potential energy of the RigidBody. Examples ======== >>> from sympy.physics.mechanics import RigidBody, Point, outer, ReferenceFrame >>> from sympy import symbols >>> M, g, h = symbols('M g h') >>> b = ReferenceFrame('b') >>> P = Point('P') >>> I = outer (b.x, b.x) >>> Inertia_tuple = (I, P) >>> B = RigidBody('B', P, b, M, Inertia_tuple) >>> B.potential_energy = M * g * h >>> B.potential_energy M*g*h """ return self._pe @potential_energy.setter def potential_energy(self, scalar): """Used to set the potential energy of this RigidBody. Parameters ========== scalar: Sympifyable The potential energy (a scalar) of the RigidBody. Examples ======== >>> from sympy.physics.mechanics import Point, outer >>> from sympy.physics.mechanics import RigidBody, ReferenceFrame >>> from sympy import symbols >>> b = ReferenceFrame('b') >>> M, g, h = symbols('M g h') >>> P = Point('P') >>> I = outer (b.x, b.x) >>> Inertia_tuple = (I, P) >>> B = RigidBody('B', P, b, M, Inertia_tuple) >>> B.potential_energy = M * g * h """ self._pe = sympify(scalar) def set_potential_energy(self, scalar): sympy_deprecation_warning( """ The sympy.physics.mechanics.RigidBody.set_potential_energy() method is deprecated. Instead use B.potential_energy = scalar """, deprecated_since_version="1.5", active_deprecations_target="deprecated-set-potential-energy", ) self.potential_energy = scalar # XXX: To be consistent with the parallel_axis method in Particle this # should have a frame argument... def parallel_axis(self, point): """Returns the inertia dyadic of the body with respect to another point. Parameters ========== point : sympy.physics.vector.Point The point to express the inertia dyadic about. Returns ======= inertia : sympy.physics.vector.Dyadic The inertia dyadic of the rigid body expressed about the provided point. """ # circular import issue from sympy.physics.mechanics.functions import inertia a, b, c = self.masscenter.pos_from(point).to_matrix(self.frame) I = self.mass * inertia(self.frame, b**2 + c**2, c**2 + a**2, a**2 + b**2, -a * b, -b * c, -a * c) return self.central_inertia + I
810e676798878174a33f4806924d21afcc54a0ec21e58ef2ef2f13ebe9e039f7
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') ol = sympify(ixx) * (frame.x | frame.x) ol += sympify(ixy) * (frame.x | frame.y) ol += sympify(izx) * (frame.x | frame.z) ol += sympify(ixy) * (frame.y | frame.x) ol += sympify(iyy) * (frame.y | frame.y) ol += sympify(iyz) * (frame.y | frame.z) ol += sympify(izx) * (frame.z | frame.x) ol += sympify(iyz) * (frame.z | frame.y) ol += sympify(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
b045f9d8e40ffa927fa48970f2856fd35a103de1e23dfd0b0a6d4632e227d58a
__all__ = ['Linearizer'] from sympy.core.backend import Matrix, eye, zeros from sympy.core.symbol import Dummy from sympy.utilities.iterables import flatten from sympy.physics.vector import dynamicsymbols from sympy.physics.mechanics.functions import msubs from collections import namedtuple from collections.abc import Iterable class Linearizer: """This object holds the general model form for a dynamic system. This model is used for computing the linearized form of the system, while properly dealing with constraints leading to dependent coordinates and speeds. Attributes ========== f_0, f_1, f_2, f_3, f_4, f_c, f_v, f_a : Matrix Matrices holding the general system form. q, u, r : Matrix Matrices holding the generalized coordinates, speeds, and input vectors. q_i, u_i : Matrix Matrices of the independent generalized coordinates and speeds. q_d, u_d : Matrix Matrices of the dependent generalized coordinates and speeds. perm_mat : Matrix Permutation matrix such that [q_ind, u_ind]^T = perm_mat*[q, u]^T """ def __init__(self, f_0, f_1, f_2, f_3, f_4, f_c, f_v, f_a, q, u, q_i=None, q_d=None, u_i=None, u_d=None, r=None, lams=None): """ Parameters ========== f_0, f_1, f_2, f_3, f_4, f_c, f_v, f_a : array_like System of equations holding the general system form. Supply empty array or Matrix if the parameter does not exist. q : array_like The generalized coordinates. u : array_like The generalized speeds q_i, u_i : array_like, optional The independent generalized coordinates and speeds. q_d, u_d : array_like, optional The dependent generalized coordinates and speeds. r : array_like, optional The input variables. lams : array_like, optional The lagrange multipliers """ # Generalized equation form self.f_0 = Matrix(f_0) self.f_1 = Matrix(f_1) self.f_2 = Matrix(f_2) self.f_3 = Matrix(f_3) self.f_4 = Matrix(f_4) self.f_c = Matrix(f_c) self.f_v = Matrix(f_v) self.f_a = Matrix(f_a) # Generalized equation variables self.q = Matrix(q) self.u = Matrix(u) none_handler = lambda x: Matrix(x) if x else Matrix() self.q_i = none_handler(q_i) self.q_d = none_handler(q_d) self.u_i = none_handler(u_i) self.u_d = none_handler(u_d) self.r = none_handler(r) self.lams = none_handler(lams) # Derivatives of generalized equation variables self._qd = self.q.diff(dynamicsymbols._t) self._ud = self.u.diff(dynamicsymbols._t) # If the user doesn't actually use generalized variables, and the # qd and u vectors have any intersecting variables, this can cause # problems. We'll fix this with some hackery, and Dummy variables dup_vars = set(self._qd).intersection(self.u) self._qd_dup = Matrix([var if var not in dup_vars else Dummy() for var in self._qd]) # Derive dimesion terms l = len(self.f_c) m = len(self.f_v) n = len(self.q) o = len(self.u) s = len(self.r) k = len(self.lams) dims = namedtuple('dims', ['l', 'm', 'n', 'o', 's', 'k']) self._dims = dims(l, m, n, o, s, k) self._Pq = None self._Pqi = None self._Pqd = None self._Pu = None self._Pui = None self._Pud = None self._C_0 = None self._C_1 = None self._C_2 = None self.perm_mat = None self._setup_done = False def _setup(self): # Calculations here only need to be run once. They are moved out of # the __init__ method to increase the speed of Linearizer creation. self._form_permutation_matrices() self._form_block_matrices() self._form_coefficient_matrices() self._setup_done = True def _form_permutation_matrices(self): """Form the permutation matrices Pq and Pu.""" # Extract dimension variables l, m, n, o, s, k = self._dims # Compute permutation matrices if n != 0: self._Pq = permutation_matrix(self.q, Matrix([self.q_i, self.q_d])) if l > 0: self._Pqi = self._Pq[:, :-l] self._Pqd = self._Pq[:, -l:] else: self._Pqi = self._Pq self._Pqd = Matrix() if o != 0: self._Pu = permutation_matrix(self.u, Matrix([self.u_i, self.u_d])) if m > 0: self._Pui = self._Pu[:, :-m] self._Pud = self._Pu[:, -m:] else: self._Pui = self._Pu self._Pud = Matrix() # Compute combination permutation matrix for computing A and B P_col1 = Matrix([self._Pqi, zeros(o + k, n - l)]) P_col2 = Matrix([zeros(n, o - m), self._Pui, zeros(k, o - m)]) if P_col1: if P_col2: self.perm_mat = P_col1.row_join(P_col2) else: self.perm_mat = P_col1 else: self.perm_mat = P_col2 def _form_coefficient_matrices(self): """Form the coefficient matrices C_0, C_1, and C_2.""" # Extract dimension variables l, m, n, o, s, k = self._dims # Build up the coefficient matrices C_0, C_1, and C_2 # If there are configuration constraints (l > 0), form C_0 as normal. # If not, C_0 is I_(nxn). Note that this works even if n=0 if l > 0: f_c_jac_q = self.f_c.jacobian(self.q) self._C_0 = (eye(n) - self._Pqd * (f_c_jac_q * self._Pqd).LUsolve(f_c_jac_q)) * self._Pqi else: self._C_0 = eye(n) # If there are motion constraints (m > 0), form C_1 and C_2 as normal. # If not, C_1 is 0, and C_2 is I_(oxo). Note that this works even if # o = 0. if m > 0: f_v_jac_u = self.f_v.jacobian(self.u) temp = f_v_jac_u * self._Pud if n != 0: f_v_jac_q = self.f_v.jacobian(self.q) self._C_1 = -self._Pud * temp.LUsolve(f_v_jac_q) else: self._C_1 = zeros(o, n) self._C_2 = (eye(o) - self._Pud * temp.LUsolve(f_v_jac_u)) * self._Pui else: self._C_1 = zeros(o, n) self._C_2 = eye(o) def _form_block_matrices(self): """Form the block matrices for composing M, A, and B.""" # Extract dimension variables l, m, n, o, s, k = self._dims # Block Matrix Definitions. These are only defined if under certain # conditions. If undefined, an empty matrix is used instead if n != 0: self._M_qq = self.f_0.jacobian(self._qd) self._A_qq = -(self.f_0 + self.f_1).jacobian(self.q) else: self._M_qq = Matrix() self._A_qq = Matrix() if n != 0 and m != 0: self._M_uqc = self.f_a.jacobian(self._qd_dup) self._A_uqc = -self.f_a.jacobian(self.q) else: self._M_uqc = Matrix() self._A_uqc = Matrix() if n != 0 and o - m + k != 0: self._M_uqd = self.f_3.jacobian(self._qd_dup) self._A_uqd = -(self.f_2 + self.f_3 + self.f_4).jacobian(self.q) else: self._M_uqd = Matrix() self._A_uqd = Matrix() if o != 0 and m != 0: self._M_uuc = self.f_a.jacobian(self._ud) self._A_uuc = -self.f_a.jacobian(self.u) else: self._M_uuc = Matrix() self._A_uuc = Matrix() if o != 0 and o - m + k != 0: self._M_uud = self.f_2.jacobian(self._ud) self._A_uud = -(self.f_2 + self.f_3).jacobian(self.u) else: self._M_uud = Matrix() self._A_uud = Matrix() if o != 0 and n != 0: self._A_qu = -self.f_1.jacobian(self.u) else: self._A_qu = Matrix() if k != 0 and o - m + k != 0: self._M_uld = self.f_4.jacobian(self.lams) else: self._M_uld = Matrix() if s != 0 and o - m + k != 0: self._B_u = -self.f_3.jacobian(self.r) else: self._B_u = Matrix() def linearize(self, op_point=None, A_and_B=False, simplify=False): """Linearize the system about the operating point. Note that q_op, u_op, qd_op, ud_op must satisfy the equations of motion. These may be either symbolic or numeric. Parameters ========== op_point : dict or iterable of dicts, optional Dictionary or iterable of dictionaries containing the operating point conditions. These will be substituted in to the linearized system before the linearization is complete. Leave blank if you want a completely symbolic form. Note that any reduction in symbols (whether substituted for numbers or expressions with a common parameter) will result in faster runtime. A_and_B : bool, optional If A_and_B=False (default), (M, A, B) is returned for forming [M]*[q, u]^T = [A]*[q_ind, u_ind]^T + [B]r. If A_and_B=True, (A, B) is returned for forming dx = [A]x + [B]r, where x = [q_ind, u_ind]^T. simplify : bool, optional Determines if returned values are simplified before return. For large expressions this may be time consuming. Default is False. Potential Issues ================ Note that the process of solving with A_and_B=True is computationally intensive if there are many symbolic parameters. For this reason, it may be more desirable to use the default A_and_B=False, returning M, A, and B. More values may then be substituted in to these matrices later on. The state space form can then be found as A = P.T*M.LUsolve(A), B = P.T*M.LUsolve(B), where P = Linearizer.perm_mat. """ # Run the setup if needed: if not self._setup_done: self._setup() # Compose dict of operating conditions if isinstance(op_point, dict): op_point_dict = op_point elif isinstance(op_point, Iterable): op_point_dict = {} for op in op_point: op_point_dict.update(op) else: op_point_dict = {} # Extract dimension variables l, m, n, o, s, k = self._dims # Rename terms to shorten expressions M_qq = self._M_qq M_uqc = self._M_uqc M_uqd = self._M_uqd M_uuc = self._M_uuc M_uud = self._M_uud M_uld = self._M_uld A_qq = self._A_qq A_uqc = self._A_uqc A_uqd = self._A_uqd A_qu = self._A_qu A_uuc = self._A_uuc A_uud = self._A_uud B_u = self._B_u C_0 = self._C_0 C_1 = self._C_1 C_2 = self._C_2 # Build up Mass Matrix # |M_qq 0_nxo 0_nxk| # M = |M_uqc M_uuc 0_mxk| # |M_uqd M_uud M_uld| if o != 0: col2 = Matrix([zeros(n, o), M_uuc, M_uud]) if k != 0: col3 = Matrix([zeros(n + m, k), M_uld]) if n != 0: col1 = Matrix([M_qq, M_uqc, M_uqd]) if o != 0 and k != 0: M = col1.row_join(col2).row_join(col3) elif o != 0: M = col1.row_join(col2) else: M = col1 elif k != 0: M = col2.row_join(col3) else: M = col2 M_eq = msubs(M, op_point_dict) # Build up state coefficient matrix A # |(A_qq + A_qu*C_1)*C_0 A_qu*C_2| # A = |(A_uqc + A_uuc*C_1)*C_0 A_uuc*C_2| # |(A_uqd + A_uud*C_1)*C_0 A_uud*C_2| # Col 1 is only defined if n != 0 if n != 0: r1c1 = A_qq if o != 0: r1c1 += (A_qu * C_1) r1c1 = r1c1 * C_0 if m != 0: r2c1 = A_uqc if o != 0: r2c1 += (A_uuc * C_1) r2c1 = r2c1 * C_0 else: r2c1 = Matrix() if o - m + k != 0: r3c1 = A_uqd if o != 0: r3c1 += (A_uud * C_1) r3c1 = r3c1 * C_0 else: r3c1 = Matrix() col1 = Matrix([r1c1, r2c1, r3c1]) else: col1 = Matrix() # Col 2 is only defined if o != 0 if o != 0: if n != 0: r1c2 = A_qu * C_2 else: r1c2 = Matrix() if m != 0: r2c2 = A_uuc * C_2 else: r2c2 = Matrix() if o - m + k != 0: r3c2 = A_uud * C_2 else: r3c2 = Matrix() col2 = Matrix([r1c2, r2c2, r3c2]) else: col2 = Matrix() if col1: if col2: Amat = col1.row_join(col2) else: Amat = col1 else: Amat = col2 Amat_eq = msubs(Amat, op_point_dict) # Build up the B matrix if there are forcing variables # |0_(n + m)xs| # B = |B_u | if s != 0 and o - m + k != 0: Bmat = zeros(n + m, s).col_join(B_u) Bmat_eq = msubs(Bmat, op_point_dict) else: Bmat_eq = Matrix() # kwarg A_and_B indicates to return A, B for forming the equation # dx = [A]x + [B]r, where x = [q_indnd, u_indnd]^T, if A_and_B: A_cont = self.perm_mat.T * M_eq.LUsolve(Amat_eq) if Bmat_eq: B_cont = self.perm_mat.T * M_eq.LUsolve(Bmat_eq) else: # Bmat = Matrix([]), so no need to sub B_cont = Bmat_eq if simplify: A_cont.simplify() B_cont.simplify() return A_cont, B_cont # Otherwise return M, A, B for forming the equation # [M]dx = [A]x + [B]r, where x = [q, u]^T else: if simplify: M_eq.simplify() Amat_eq.simplify() Bmat_eq.simplify() return M_eq, Amat_eq, Bmat_eq def permutation_matrix(orig_vec, per_vec): """Compute the permutation matrix to change order of orig_vec into order of per_vec. Parameters ========== orig_vec : array_like Symbols in original ordering. per_vec : array_like Symbols in new ordering. Returns ======= p_matrix : Matrix Permutation matrix such that orig_vec == (p_matrix * per_vec). """ if not isinstance(orig_vec, (list, tuple)): orig_vec = flatten(orig_vec) if not isinstance(per_vec, (list, tuple)): per_vec = flatten(per_vec) if set(orig_vec) != set(per_vec): raise ValueError("orig_vec and per_vec must be the same length, " + "and contain the same symbols.") ind_list = [orig_vec.index(i) for i in per_vec] p_matrix = zeros(len(orig_vec)) for i, j in enumerate(ind_list): p_matrix[i, j] = 1 return p_matrix
84f751aa37e2dacf15276fe1d02665fc5973a2a23a83476882d03eeb0a223ba0
from sympy.core.backend import sympify from sympy.physics.vector import Point from sympy.utilities.exceptions import sympy_deprecation_warning __all__ = ['Particle'] class Particle: """A particle. Explanation =========== Particles have a non-zero mass and lack spatial extension; they take up no space. Values need to be supplied on initialization, but can be changed later. Parameters ========== name : str Name of particle point : Point A physics/mechanics Point which represents the position, velocity, and acceleration of this Particle mass : sympifyable A SymPy expression representing the Particle's mass Examples ======== >>> from sympy.physics.mechanics import Particle, Point >>> from sympy import Symbol >>> po = Point('po') >>> m = Symbol('m') >>> pa = Particle('pa', po, m) >>> # Or you could change these later >>> pa.mass = m >>> pa.point = po """ def __init__(self, name, point, mass): if not isinstance(name, str): raise TypeError('Supply a valid name.') self._name = name self.mass = mass self.point = point self.potential_energy = 0 def __str__(self): return self._name def __repr__(self): return self.__str__() @property def mass(self): """Mass of the particle.""" return self._mass @mass.setter def mass(self, value): self._mass = sympify(value) @property def point(self): """Point of the particle.""" return self._point @point.setter def point(self, p): if not isinstance(p, Point): raise TypeError("Particle point attribute must be a Point object.") self._point = p def linear_momentum(self, frame): """Linear momentum of the particle. Explanation =========== The linear momentum L, of a particle P, with respect to frame N is given by L = m * v where m is the mass of the particle, and v is the velocity of the particle in the frame N. Parameters ========== frame : ReferenceFrame The frame in which linear momentum is desired. Examples ======== >>> from sympy.physics.mechanics import Particle, Point, ReferenceFrame >>> from sympy.physics.mechanics import dynamicsymbols >>> from sympy.physics.vector import init_vprinting >>> init_vprinting(pretty_print=False) >>> m, v = dynamicsymbols('m v') >>> N = ReferenceFrame('N') >>> P = Point('P') >>> A = Particle('A', P, m) >>> P.set_vel(N, v * N.x) >>> A.linear_momentum(N) m*v*N.x """ return self.mass * self.point.vel(frame) def angular_momentum(self, point, frame): """Angular momentum of the particle about the point. Explanation =========== The angular momentum H, about some point O of a particle, P, is given by: H = r x m * v where r is the position vector from point O to the particle P, m is the mass of the particle, and v is the velocity of the particle in the inertial frame, N. Parameters ========== point : Point The point about which angular momentum of the particle is desired. frame : ReferenceFrame The frame in which angular momentum is desired. Examples ======== >>> from sympy.physics.mechanics import Particle, Point, ReferenceFrame >>> from sympy.physics.mechanics import dynamicsymbols >>> from sympy.physics.vector import init_vprinting >>> init_vprinting(pretty_print=False) >>> m, v, r = dynamicsymbols('m v r') >>> N = ReferenceFrame('N') >>> O = Point('O') >>> A = O.locatenew('A', r * N.x) >>> P = Particle('P', A, m) >>> P.point.set_vel(N, v * N.y) >>> P.angular_momentum(O, N) m*r*v*N.z """ return self.point.pos_from(point) ^ (self.mass * self.point.vel(frame)) def kinetic_energy(self, frame): """Kinetic energy of the particle. Explanation =========== The kinetic energy, T, of a particle, P, is given by 'T = 1/2 m v^2' where m is the mass of particle P, and v is the velocity of the particle in the supplied ReferenceFrame. Parameters ========== frame : ReferenceFrame The Particle's velocity is typically defined with respect to an inertial frame but any relevant frame in which the velocity is known can be supplied. Examples ======== >>> from sympy.physics.mechanics import Particle, Point, ReferenceFrame >>> from sympy import symbols >>> m, v, r = symbols('m v r') >>> N = ReferenceFrame('N') >>> O = Point('O') >>> P = Particle('P', O, m) >>> P.point.set_vel(N, v * N.y) >>> P.kinetic_energy(N) m*v**2/2 """ return (self.mass / sympify(2) * self.point.vel(frame) & self.point.vel(frame)) @property def potential_energy(self): """The potential energy of the Particle. Examples ======== >>> from sympy.physics.mechanics import Particle, Point >>> from sympy import symbols >>> m, g, h = symbols('m g h') >>> O = Point('O') >>> P = Particle('P', O, m) >>> P.potential_energy = m * g * h >>> P.potential_energy g*h*m """ return self._pe @potential_energy.setter def potential_energy(self, scalar): """Used to set the potential energy of the Particle. Parameters ========== scalar : Sympifyable The potential energy (a scalar) of the Particle. Examples ======== >>> from sympy.physics.mechanics import Particle, Point >>> from sympy import symbols >>> m, g, h = symbols('m g h') >>> O = Point('O') >>> P = Particle('P', O, m) >>> P.potential_energy = m * g * h """ self._pe = sympify(scalar) def set_potential_energy(self, scalar): sympy_deprecation_warning( """ The sympy.physics.mechanics.Particle.set_potential_energy() method is deprecated. Instead use P.potential_energy = scalar """, deprecated_since_version="1.5", active_deprecations_target="deprecated-set-potential-energy", ) self.potential_energy = scalar def parallel_axis(self, point, frame): """Returns an inertia dyadic of the particle with respect to another point and frame. Parameters ========== point : sympy.physics.vector.Point The point to express the inertia dyadic about. frame : sympy.physics.vector.ReferenceFrame The reference frame used to construct the dyadic. Returns ======= inertia : sympy.physics.vector.Dyadic The inertia dyadic of the particle expressed about the provided point and frame. """ # circular import issue from sympy.physics.mechanics import inertia_of_point_mass return inertia_of_point_mass(self.mass, self.point.pos_from(point), frame)
a902742cd86e01e62c67db36365dcc0a6c9da9e84414c647667befe436d9d9e8
# isort:skip_file """ Dimensional analysis and unit systems. This module defines dimension/unit systems and physical quantities. It is based on a group-theoretical construction where dimensions are represented as vectors (coefficients being the exponents), and units are defined as a dimension to which we added a scale. Quantities are built from a factor and a unit, and are the basic objects that one will use when doing computations. All objects except systems and prefixes can be used in SymPy expressions. Note that as part of a CAS, various objects do not combine automatically under operations. Details about the implementation can be found in the documentation, and we will not repeat all the explanations we gave there concerning our approach. Ideas about future developments can be found on the `Github wiki <https://github.com/sympy/sympy/wiki/Unit-systems>`_, and you should consult this page if you are willing to help. Useful functions: - ``find_unit``: easily lookup pre-defined units. - ``convert_to(expr, newunit)``: converts an expression into the same expression expressed in another unit. """ from .dimensions import Dimension, DimensionSystem from .unitsystem import UnitSystem from .util import convert_to from .quantities import Quantity from .definitions.dimension_definitions import ( amount_of_substance, acceleration, action, area, capacitance, charge, conductance, current, energy, force, frequency, impedance, inductance, length, luminous_intensity, magnetic_density, magnetic_flux, mass, momentum, power, pressure, temperature, time, velocity, voltage, volume ) Unit = Quantity speed = velocity luminosity = luminous_intensity magnetic_flux_density = magnetic_density amount = amount_of_substance from .prefixes import ( # 10-power based: yotta, zetta, exa, peta, tera, giga, mega, kilo, hecto, deca, deci, centi, milli, micro, nano, pico, femto, atto, zepto, yocto, # 2-power based: kibi, mebi, gibi, tebi, pebi, exbi, ) from .definitions import ( percent, percents, permille, rad, radian, radians, deg, degree, degrees, sr, steradian, steradians, mil, angular_mil, angular_mils, m, meter, meters, kg, kilogram, kilograms, s, second, seconds, A, ampere, amperes, K, kelvin, kelvins, mol, mole, moles, cd, candela, candelas, g, gram, grams, mg, milligram, milligrams, ug, microgram, micrograms, t, tonne, metric_ton, newton, newtons, N, joule, joules, J, watt, watts, W, pascal, pascals, Pa, pa, hertz, hz, Hz, coulomb, coulombs, C, volt, volts, v, V, ohm, ohms, siemens, S, mho, mhos, farad, farads, F, henry, henrys, H, tesla, teslas, T, weber, webers, Wb, wb, optical_power, dioptre, D, lux, lx, katal, kat, gray, Gy, becquerel, Bq, km, kilometer, kilometers, dm, decimeter, decimeters, cm, centimeter, centimeters, mm, millimeter, millimeters, um, micrometer, micrometers, micron, microns, nm, nanometer, nanometers, pm, picometer, picometers, ft, foot, feet, inch, inches, yd, yard, yards, mi, mile, miles, nmi, nautical_mile, nautical_miles, ha, hectare, l, L, liter, liters, dl, dL, deciliter, deciliters, cl, cL, centiliter, centiliters, ml, mL, milliliter, milliliters, ms, millisecond, milliseconds, us, microsecond, microseconds, ns, nanosecond, nanoseconds, ps, picosecond, picoseconds, minute, minutes, h, hour, hours, day, days, anomalistic_year, anomalistic_years, sidereal_year, sidereal_years, tropical_year, tropical_years, common_year, common_years, julian_year, julian_years, draconic_year, draconic_years, gaussian_year, gaussian_years, full_moon_cycle, full_moon_cycles, year, years, G, gravitational_constant, c, speed_of_light, elementary_charge, hbar, planck, eV, electronvolt, electronvolts, avogadro_number, avogadro, avogadro_constant, boltzmann, boltzmann_constant, stefan, stefan_boltzmann_constant, R, molar_gas_constant, faraday_constant, josephson_constant, von_klitzing_constant, Da, dalton, amu, amus, atomic_mass_unit, atomic_mass_constant, gee, gees, acceleration_due_to_gravity, u0, magnetic_constant, vacuum_permeability, e0, electric_constant, vacuum_permittivity, Z0, vacuum_impedance, coulomb_constant, electric_force_constant, atmosphere, atmospheres, atm, kPa, bar, bars, pound, pounds, psi, dHg0, mmHg, torr, mmu, mmus, milli_mass_unit, quart, quarts, ly, lightyear, lightyears, au, astronomical_unit, astronomical_units, planck_mass, planck_time, planck_temperature, planck_length, planck_charge, planck_area, planck_volume, planck_momentum, planck_energy, planck_force, planck_power, planck_density, planck_energy_density, planck_intensity, planck_angular_frequency, planck_pressure, planck_current, planck_voltage, planck_impedance, planck_acceleration, bit, bits, byte, kibibyte, kibibytes, mebibyte, mebibytes, gibibyte, gibibytes, tebibyte, tebibytes, pebibyte, pebibytes, exbibyte, exbibytes, ) from .systems import ( mks, mksa, si ) def find_unit(quantity, unit_system="SI"): """ Return a list of matching units or dimension names. - If ``quantity`` is a string -- units/dimensions containing the string `quantity`. - If ``quantity`` is a unit or dimension -- units having matching base units or dimensions. Examples ======== >>> from sympy.physics import units as u >>> u.find_unit('charge') ['C', 'coulomb', 'coulombs', 'planck_charge', 'elementary_charge'] >>> u.find_unit(u.charge) ['C', 'coulomb', 'coulombs', 'planck_charge', 'elementary_charge'] >>> u.find_unit("ampere") ['ampere', 'amperes'] >>> u.find_unit('volt') ['volt', 'volts', 'electronvolt', 'electronvolts', 'planck_voltage'] >>> u.find_unit(u.inch**3)[:9] ['L', 'l', 'cL', 'cl', 'dL', 'dl', 'mL', 'ml', 'liter'] """ unit_system = UnitSystem.get_unit_system(unit_system) import sympy.physics.units as u rv = [] if isinstance(quantity, str): rv = [i for i in dir(u) if quantity in i and isinstance(getattr(u, i), Quantity)] dim = getattr(u, quantity) if isinstance(dim, Dimension): rv.extend(find_unit(dim)) else: for i in sorted(dir(u)): other = getattr(u, i) if not isinstance(other, Quantity): continue if isinstance(quantity, Quantity): if quantity.dimension == other.dimension: rv.append(str(i)) elif isinstance(quantity, Dimension): if other.dimension == quantity: rv.append(str(i)) elif other.dimension == Dimension(unit_system.get_dimensional_expr(quantity)): rv.append(str(i)) return sorted(set(rv), key=lambda x: (len(x), x)) # NOTE: the old units module had additional variables: # 'density', 'illuminance', 'resistance'. # They were not dimensions, but units (old Unit class). __all__ = [ 'Dimension', 'DimensionSystem', 'UnitSystem', 'convert_to', 'Quantity', 'amount_of_substance', 'acceleration', 'action', 'area', 'capacitance', 'charge', 'conductance', 'current', 'energy', 'force', 'frequency', 'impedance', 'inductance', 'length', 'luminous_intensity', 'magnetic_density', 'magnetic_flux', 'mass', 'momentum', 'power', 'pressure', 'temperature', 'time', 'velocity', 'voltage', 'volume', 'Unit', 'speed', 'luminosity', 'magnetic_flux_density', 'amount', 'yotta', 'zetta', 'exa', 'peta', 'tera', 'giga', 'mega', 'kilo', 'hecto', 'deca', 'deci', 'centi', 'milli', 'micro', 'nano', 'pico', 'femto', 'atto', 'zepto', 'yocto', 'kibi', 'mebi', 'gibi', 'tebi', 'pebi', 'exbi', 'percent', 'percents', 'permille', 'rad', 'radian', 'radians', 'deg', 'degree', 'degrees', 'sr', 'steradian', 'steradians', 'mil', 'angular_mil', 'angular_mils', 'm', 'meter', 'meters', 'kg', 'kilogram', 'kilograms', 's', 'second', 'seconds', 'A', 'ampere', 'amperes', 'K', 'kelvin', 'kelvins', 'mol', 'mole', 'moles', 'cd', 'candela', 'candelas', 'g', 'gram', 'grams', 'mg', 'milligram', 'milligrams', 'ug', 'microgram', 'micrograms', 't', 'tonne', 'metric_ton', 'newton', 'newtons', 'N', 'joule', 'joules', 'J', 'watt', 'watts', 'W', 'pascal', 'pascals', 'Pa', 'pa', 'hertz', 'hz', 'Hz', 'coulomb', 'coulombs', 'C', 'volt', 'volts', 'v', 'V', 'ohm', 'ohms', 'siemens', 'S', 'mho', 'mhos', 'farad', 'farads', 'F', 'henry', 'henrys', 'H', 'tesla', 'teslas', 'T', 'weber', 'webers', 'Wb', 'wb', 'optical_power', 'dioptre', 'D', 'lux', 'lx', 'katal', 'kat', 'gray', 'Gy', 'becquerel', 'Bq', 'km', 'kilometer', 'kilometers', 'dm', 'decimeter', 'decimeters', 'cm', 'centimeter', 'centimeters', 'mm', 'millimeter', 'millimeters', 'um', 'micrometer', 'micrometers', 'micron', 'microns', 'nm', 'nanometer', 'nanometers', 'pm', 'picometer', 'picometers', 'ft', 'foot', 'feet', 'inch', 'inches', 'yd', 'yard', 'yards', 'mi', 'mile', 'miles', 'nmi', 'nautical_mile', 'nautical_miles', 'ha', 'hectare', 'l', 'L', 'liter', 'liters', 'dl', 'dL', 'deciliter', 'deciliters', 'cl', 'cL', 'centiliter', 'centiliters', 'ml', 'mL', 'milliliter', 'milliliters', 'ms', 'millisecond', 'milliseconds', 'us', 'microsecond', 'microseconds', 'ns', 'nanosecond', 'nanoseconds', 'ps', 'picosecond', 'picoseconds', 'minute', 'minutes', 'h', 'hour', 'hours', 'day', 'days', 'anomalistic_year', 'anomalistic_years', 'sidereal_year', 'sidereal_years', 'tropical_year', 'tropical_years', 'common_year', 'common_years', 'julian_year', 'julian_years', 'draconic_year', 'draconic_years', 'gaussian_year', 'gaussian_years', 'full_moon_cycle', 'full_moon_cycles', 'year', 'years', 'G', 'gravitational_constant', 'c', 'speed_of_light', 'elementary_charge', 'hbar', 'planck', 'eV', 'electronvolt', 'electronvolts', 'avogadro_number', 'avogadro', 'avogadro_constant', 'boltzmann', 'boltzmann_constant', 'stefan', 'stefan_boltzmann_constant', 'R', 'molar_gas_constant', 'faraday_constant', 'josephson_constant', 'von_klitzing_constant', 'Da', 'dalton', 'amu', 'amus', 'atomic_mass_unit', 'atomic_mass_constant', 'gee', 'gees', 'acceleration_due_to_gravity', 'u0', 'magnetic_constant', 'vacuum_permeability', 'e0', 'electric_constant', 'vacuum_permittivity', 'Z0', 'vacuum_impedance', 'coulomb_constant', 'electric_force_constant', 'atmosphere', 'atmospheres', 'atm', 'kPa', 'bar', 'bars', 'pound', 'pounds', 'psi', 'dHg0', 'mmHg', 'torr', 'mmu', 'mmus', 'milli_mass_unit', 'quart', 'quarts', 'ly', 'lightyear', 'lightyears', 'au', 'astronomical_unit', 'astronomical_units', 'planck_mass', 'planck_time', 'planck_temperature', 'planck_length', 'planck_charge', 'planck_area', 'planck_volume', 'planck_momentum', 'planck_energy', 'planck_force', 'planck_power', 'planck_density', 'planck_energy_density', 'planck_intensity', 'planck_angular_frequency', 'planck_pressure', 'planck_current', 'planck_voltage', 'planck_impedance', 'planck_acceleration', 'bit', 'bits', 'byte', 'kibibyte', 'kibibytes', 'mebibyte', 'mebibytes', 'gibibyte', 'gibibytes', 'tebibyte', 'tebibytes', 'pebibyte', 'pebibytes', 'exbibyte', 'exbibytes', 'mks', 'mksa', 'si', ]
ce87a8dca0d930fc76c65254498c418da3052d4fc3d1d8c4a5f80b83f45849c3
""" Unit system for physical quantities; include definition of constants. """ from typing import Dict as tDict from sympy.core.add import Add from sympy.core.function import (Derivative, Function) from sympy.core.mul import Mul from sympy.core.power import Pow from sympy.core.singleton import S from sympy.physics.units.dimensions import _QuantityMapper from .dimensions import Dimension class UnitSystem(_QuantityMapper): """ UnitSystem represents a coherent set of units. A unit system is basically a dimension system with notions of scales. Many of the methods are defined in the same way. It is much better if all base units have a symbol. """ _unit_systems = {} # type: tDict[str, UnitSystem] def __init__(self, base_units, units=(), name="", descr="", dimension_system=None): UnitSystem._unit_systems[name] = self self.name = name self.descr = descr self._base_units = base_units self._dimension_system = dimension_system self._units = tuple(set(base_units) | set(units)) self._base_units = tuple(base_units) super().__init__() def __str__(self): """ Return the name of the system. If it does not exist, then it makes a list of symbols (or names) of the base dimensions. """ if self.name != "": return self.name else: return "UnitSystem((%s))" % ", ".join( str(d) for d in self._base_units) def __repr__(self): return '<UnitSystem: %s>' % repr(self._base_units) def extend(self, base, units=(), name="", description="", dimension_system=None): """Extend the current system into a new one. Take the base and normal units of the current system to merge them to the base and normal units given in argument. If not provided, name and description are overridden by empty strings. """ base = self._base_units + tuple(base) units = self._units + tuple(units) return UnitSystem(base, units, name, description, dimension_system) def get_dimension_system(self): return self._dimension_system def get_quantity_dimension(self, unit): qdm = self.get_dimension_system()._quantity_dimension_map if unit in qdm: return qdm[unit] return super().get_quantity_dimension(unit) def get_quantity_scale_factor(self, unit): qsfm = self.get_dimension_system()._quantity_scale_factors if unit in qsfm: return qsfm[unit] return super().get_quantity_scale_factor(unit) @staticmethod def get_unit_system(unit_system): if isinstance(unit_system, UnitSystem): return unit_system if unit_system not in UnitSystem._unit_systems: raise ValueError( "Unit system is not supported. Currently" "supported unit systems are {}".format( ", ".join(sorted(UnitSystem._unit_systems)) ) ) return UnitSystem._unit_systems[unit_system] @staticmethod def get_default_unit_system(): return UnitSystem._unit_systems["SI"] @property def dim(self): """ Give the dimension of the system. That is return the number of units forming the basis. """ return len(self._base_units) @property def is_consistent(self): """ Check if the underlying dimension system is consistent. """ # test is performed in DimensionSystem return self.get_dimension_system().is_consistent def get_dimensional_expr(self, expr): from sympy.physics.units import Quantity if isinstance(expr, Mul): return Mul(*[self.get_dimensional_expr(i) for i in expr.args]) elif isinstance(expr, Pow): return self.get_dimensional_expr(expr.base) ** expr.exp elif isinstance(expr, Add): return self.get_dimensional_expr(expr.args[0]) elif isinstance(expr, Derivative): dim = self.get_dimensional_expr(expr.expr) for independent, count in expr.variable_count: dim /= self.get_dimensional_expr(independent)**count return dim elif isinstance(expr, Function): args = [self.get_dimensional_expr(arg) for arg in expr.args] if all(i == 1 for i in args): return S.One return expr.func(*args) elif isinstance(expr, Quantity): return self.get_quantity_dimension(expr).name return S.One def _collect_factor_and_dimension(self, expr): """ Return tuple with scale factor expression and dimension expression. """ from sympy.physics.units import Quantity if isinstance(expr, Quantity): return expr.scale_factor, expr.dimension elif isinstance(expr, Mul): factor = 1 dimension = Dimension(1) for arg in expr.args: arg_factor, arg_dim = self._collect_factor_and_dimension(arg) factor *= arg_factor dimension *= arg_dim return factor, dimension elif isinstance(expr, Pow): factor, dim = self._collect_factor_and_dimension(expr.base) exp_factor, exp_dim = self._collect_factor_and_dimension(expr.exp) if self.get_dimension_system().is_dimensionless(exp_dim): exp_dim = 1 return factor ** exp_factor, dim ** (exp_factor * exp_dim) elif isinstance(expr, Add): factor, dim = self._collect_factor_and_dimension(expr.args[0]) for addend in expr.args[1:]: addend_factor, addend_dim = \ self._collect_factor_and_dimension(addend) if dim != addend_dim: raise ValueError( 'Dimension of "{}" is {}, ' 'but it should be {}'.format( addend, addend_dim, dim)) factor += addend_factor return factor, dim elif isinstance(expr, Derivative): factor, dim = self._collect_factor_and_dimension(expr.args[0]) for independent, count in expr.variable_count: ifactor, idim = self._collect_factor_and_dimension(independent) factor /= ifactor**count dim /= idim**count return factor, dim elif isinstance(expr, Function): fds = [self._collect_factor_and_dimension( arg) for arg in expr.args] return (expr.func(*(f[0] for f in fds)), expr.func(*(d[1] for d in fds))) elif isinstance(expr, Dimension): return S.One, expr else: return expr, Dimension(1)
a70f2efbed0058ca5d55b825cf336585d78361e8da56839211cac6c7856c7840
""" 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) {'length': 1, 'time': -1} >>> length + length Dimension(length) >>> l2 = length**2 >>> l2 Dimension(length**2) >>> dimsys_SI.get_dimensional_dependencies(l2) {'length': 2} """ _op_priority = 13.0 # XXX: This doesn't seem to be used anywhere... _dimensional_dependencies = dict() # 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) if symbol is not None: obj = Expr.__new__(cls, name, symbol) else: 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 __hash__(self): return Expr.__hash__(self) def __eq__(self, other): if isinstance(other, Dimension): return self.name == other.name return False 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, ( Dimension(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: dim = dim.name 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.name elif isinstance(dim, str): return Symbol(dim) elif isinstance(dim, Symbol): return 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.name not in dimensional_dependencies: # TODO: should this raise a warning? dimensional_dependencies[dim.name] = Dict({dim.name: 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, name): if isinstance(name, Dimension): name = name.name if isinstance(name, str): name = Symbol(name) if name.is_Symbol: # Dimensions not included in the dependencies are considered # as base dimensions: return dict(self.dimensional_dependencies.get(name, {name: 1})) if name.is_number or name.is_NumberSymbol: return {} get_for_name = self._get_dimensional_dependencies_for_name if name.is_Mul: ret = collections.defaultdict(int) dicts = [get_for_name(i) for i in 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 name.is_Add: dicts = [get_for_name(i) for i in 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 name.is_Pow: dim_base = get_for_name(name.base) dim_exp = get_for_name(name.exp) if dim_exp == {} or name.exp.is_Symbol: return {k: v*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 name.is_Function: args = (Dimension._from_dimensional_dependencies( get_for_name(arg)) for arg in name.args) result = name.func(*args) dicts = [get_for_name(i) for i in name.args] if isinstance(result, Dimension): return self.get_dimensional_dependencies(result) elif result.func == name.func: if isinstance(name, TrigonometricFunction): if dicts[0] in ({}, {Symbol('angle'): 1}): return {} else: raise TypeError("The input argument for the function {} must be dimensionless or have dimensions of angle.".format(name.func)) else: if all( (item == {} for item in dicts) ): return {} else: raise TypeError("The input arguments for the function {} must be dimensionless.".format(name.func)) else: return get_for_name(result) raise TypeError("Type {} not implemented for get_dimensional_dependencies".format(type(name))) def get_dimensional_dependencies(self, name, mark_dimensionless=False): dimdep = self._get_dimensional_dependencies_for_name(name) if mark_dimensionless and dimdep == {}: return {'dimensionless': 1} return {str(i): j for i, j 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
825c042aee17afc5701a31d27e7d3e7c956059dd527f9b90fabd5f9e748c3818
""" 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)): 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 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 @property def base(self): return self._base def __str__(self): # TODO: add proper printers and tests: 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) __repr__ = __str__ 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)) ) 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) 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, }
28f9c9ca3beb96528aa3b1796809ca9b2d86529968ee17e770f1754c28d78b02
""" Physical quantities. """ from sympy.core.expr import AtomicExpr from sympy.core.symbol import Symbol from sympy.core.sympify import sympify from sympy.physics.units.dimensions import _QuantityMapper from sympy.physics.units.prefixes import Prefix from sympy.utilities.exceptions import (sympy_deprecation_warning, SymPyDeprecationWarning, ignore_warnings) class Quantity(AtomicExpr): """ Physical quantity: can be a unit of measure, a constant or a generic quantity. """ is_commutative = True is_real = True is_number = False is_nonzero = True _diff_wrt = True def __new__(cls, name, abbrev=None, dimension=None, scale_factor=None, latex_repr=None, pretty_unicode_repr=None, pretty_ascii_repr=None, mathml_presentation_repr=None, **assumptions): if not isinstance(name, Symbol): name = Symbol(name) # For Quantity(name, dim, scale, abbrev) to work like in the # old version of SymPy: if not isinstance(abbrev, str) and not \ isinstance(abbrev, Symbol): dimension, scale_factor, abbrev = abbrev, dimension, scale_factor if dimension is not None: sympy_deprecation_warning( """ The 'dimension' argument to to Quantity() is deprecated. Instead use the unit_system.set_quantity_dimension() method. """, deprecated_since_version="1.3", active_deprecations_target="deprecated-quantity-dimension-scale-factor" ) if scale_factor is not None: sympy_deprecation_warning( """ The 'scale_factor' argument to to Quantity() is deprecated. Instead use the unit_system.set_quantity_scale_factors() method. """, deprecated_since_version="1.3", active_deprecations_target="deprecated-quantity-dimension-scale-factor" ) if abbrev is None: abbrev = name elif isinstance(abbrev, str): abbrev = Symbol(abbrev) obj = AtomicExpr.__new__(cls, name, abbrev) obj._name = name obj._abbrev = abbrev obj._latex_repr = latex_repr obj._unicode_repr = pretty_unicode_repr obj._ascii_repr = pretty_ascii_repr obj._mathml_repr = mathml_presentation_repr if dimension is not None: # TODO: remove after deprecation: with ignore_warnings(SymPyDeprecationWarning): obj.set_dimension(dimension) if scale_factor is not None: # TODO: remove after deprecation: with ignore_warnings(SymPyDeprecationWarning): obj.set_scale_factor(scale_factor) return obj def set_dimension(self, dimension, unit_system="SI"): sympy_deprecation_warning( f""" Quantity.set_dimension() is deprecated. Use either unit_system.set_quantity_dimension() or {self}.set_global_dimension() instead. """, deprecated_since_version="1.5", active_deprecations_target="deprecated-quantity-methods", ) from sympy.physics.units import UnitSystem unit_system = UnitSystem.get_unit_system(unit_system) unit_system.set_quantity_dimension(self, dimension) def set_scale_factor(self, scale_factor, unit_system="SI"): sympy_deprecation_warning( f""" Quantity.set_scale_factor() is deprecated. Use either unit_system.set_quantity_scale_factors() or {self}.set_global_relative_scale_factor() instead. """, deprecated_since_version="1.5", active_deprecations_target="deprecated-quantity-methods", ) from sympy.physics.units import UnitSystem unit_system = UnitSystem.get_unit_system(unit_system) unit_system.set_quantity_scale_factor(self, scale_factor) def set_global_dimension(self, dimension): _QuantityMapper._quantity_dimension_global[self] = dimension def set_global_relative_scale_factor(self, scale_factor, reference_quantity): """ Setting a scale factor that is valid across all unit system. """ from sympy.physics.units import UnitSystem 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 ) scale_factor = sympify(scale_factor) UnitSystem._quantity_scale_factors_global[self] = (scale_factor, reference_quantity) UnitSystem._quantity_dimensional_equivalence_map_global[self] = reference_quantity @property def name(self): return self._name @property def dimension(self): from sympy.physics.units import UnitSystem unit_system = UnitSystem.get_default_unit_system() return unit_system.get_quantity_dimension(self) @property def abbrev(self): """ Symbol representing the unit name. Prepend the abbreviation with the prefix symbol if it is defines. """ return self._abbrev @property def scale_factor(self): """ Overall magnitude of the quantity as compared to the canonical units. """ from sympy.physics.units import UnitSystem unit_system = UnitSystem.get_default_unit_system() return unit_system.get_quantity_scale_factor(self) def _eval_is_positive(self): return True def _eval_is_constant(self): return True def _eval_Abs(self): return self def _eval_subs(self, old, new): if isinstance(new, Quantity) and self != old: return self @staticmethod def get_dimensional_expr(expr, unit_system="SI"): sympy_deprecation_warning( """ Quantity.get_dimensional_expr() is deprecated. It is now associated with UnitSystem objects. The dimensional relations depend on the unit system used. Use unit_system.get_dimensional_expr() instead. """, deprecated_since_version="1.5", active_deprecations_target="deprecated-quantity-methods", ) from sympy.physics.units import UnitSystem unit_system = UnitSystem.get_unit_system(unit_system) return unit_system.get_dimensional_expr(expr) @staticmethod def _collect_factor_and_dimension(expr, unit_system="SI"): """Return tuple with scale factor expression and dimension expression.""" sympy_deprecation_warning( """ Quantity._collect_factor_and_dimension() is deprecated. This method has been moved to the UnitSystem class. Use unit_system._collect_factor_and_dimension(expr) instead. """, deprecated_since_version="1.5", active_deprecations_target="deprecated-quantity-methods", ) from sympy.physics.units import UnitSystem unit_system = UnitSystem.get_unit_system(unit_system) return unit_system._collect_factor_and_dimension(expr) def _latex(self, printer): if self._latex_repr: return self._latex_repr else: return r'\text{{{}}}'.format(self.args[1] \ if len(self.args) >= 2 else self.args[0]) def convert_to(self, other, unit_system="SI"): """ Convert the quantity to another quantity of same dimensions. Examples ======== >>> from sympy.physics.units import speed_of_light, meter, second >>> speed_of_light speed_of_light >>> speed_of_light.convert_to(meter/second) 299792458*meter/second >>> from sympy.physics.units import liter >>> liter.convert_to(meter**3) meter**3/1000 """ from .util import convert_to return convert_to(self, other, unit_system) @property def free_symbols(self): """Return free symbols from quantity.""" return set()
8909b265089bfbd39aeffb2ec701e9949f475b5f7c2cf1a6a6d0e5770a91976d
from sympy.core.function import Derivative from sympy.core.function import UndefinedFunction, AppliedUndef from sympy.core.symbol import Symbol from sympy.interactive.printing import init_printing from sympy.printing.latex import LatexPrinter from sympy.printing.pretty.pretty import PrettyPrinter from sympy.printing.pretty.pretty_symbology import center_accent from sympy.printing.str import StrPrinter from sympy.printing.precedence import PRECEDENCE __all__ = ['vprint', 'vsstrrepr', 'vsprint', 'vpprint', 'vlatex', 'init_vprinting'] class VectorStrPrinter(StrPrinter): """String Printer for vector expressions. """ def _print_Derivative(self, e): from sympy.physics.vector.functions import dynamicsymbols t = dynamicsymbols._t if (bool(sum([i == t for i in e.variables])) & isinstance(type(e.args[0]), UndefinedFunction)): ol = str(e.args[0].func) for i, v in enumerate(e.variables): ol += dynamicsymbols._str return ol else: return StrPrinter().doprint(e) def _print_Function(self, e): from sympy.physics.vector.functions import dynamicsymbols t = dynamicsymbols._t if isinstance(type(e), UndefinedFunction): return StrPrinter().doprint(e).replace("(%s)" % t, '') return e.func.__name__ + "(%s)" % self.stringify(e.args, ", ") class VectorStrReprPrinter(VectorStrPrinter): """String repr printer for vector expressions.""" def _print_str(self, s): return repr(s) class VectorLatexPrinter(LatexPrinter): """Latex Printer for vector expressions. """ def _print_Function(self, expr, exp=None): from sympy.physics.vector.functions import dynamicsymbols func = expr.func.__name__ t = dynamicsymbols._t if (hasattr(self, '_print_' + func) and not isinstance(type(expr), UndefinedFunction)): return getattr(self, '_print_' + func)(expr, exp) elif isinstance(type(expr), UndefinedFunction) and (expr.args == (t,)): # treat this function like a symbol expr = Symbol(func) if exp is not None: # copied from LatexPrinter._helper_print_standard_power, which # we can't call because we only have exp as a string. base = self.parenthesize(expr, PRECEDENCE['Pow']) base = self.parenthesize_super(base) return r"%s^{%s}" % (base, exp) else: return super()._print(expr) else: return super()._print_Function(expr, exp) def _print_Derivative(self, der_expr): from sympy.physics.vector.functions import dynamicsymbols # make sure it is in the right form der_expr = der_expr.doit() if not isinstance(der_expr, Derivative): return r"\left(%s\right)" % self.doprint(der_expr) # check if expr is a dynamicsymbol t = dynamicsymbols._t expr = der_expr.expr red = expr.atoms(AppliedUndef) syms = der_expr.variables test1 = not all(True for i in red if i.free_symbols == {t}) test2 = not all(t == i for i in syms) if test1 or test2: return super()._print_Derivative(der_expr) # done checking dots = len(syms) base = self._print_Function(expr) base_split = base.split('_', 1) base = base_split[0] if dots == 1: base = r"\dot{%s}" % base elif dots == 2: base = r"\ddot{%s}" % base elif dots == 3: base = r"\dddot{%s}" % base elif dots == 4: base = r"\ddddot{%s}" % base else: # Fallback to standard printing return super()._print_Derivative(der_expr) if len(base_split) != 1: base += '_' + base_split[1] return base class VectorPrettyPrinter(PrettyPrinter): """Pretty Printer for vectorialexpressions. """ def _print_Derivative(self, deriv): from sympy.physics.vector.functions import dynamicsymbols # XXX use U('PARTIAL DIFFERENTIAL') here ? t = dynamicsymbols._t dot_i = 0 syms = list(reversed(deriv.variables)) while len(syms) > 0: if syms[-1] == t: syms.pop() dot_i += 1 else: return super()._print_Derivative(deriv) if not (isinstance(type(deriv.expr), UndefinedFunction) and (deriv.expr.args == (t,))): return super()._print_Derivative(deriv) else: pform = self._print_Function(deriv.expr) # the following condition would happen with some sort of non-standard # dynamic symbol I guess, so we'll just print the SymPy way if len(pform.picture) > 1: return super()._print_Derivative(deriv) # There are only special symbols up to fourth-order derivatives if dot_i >= 5: return super()._print_Derivative(deriv) # Deal with special symbols dots = {0: "", 1: "\N{COMBINING DOT ABOVE}", 2: "\N{COMBINING DIAERESIS}", 3: "\N{COMBINING THREE DOTS ABOVE}", 4: "\N{COMBINING FOUR DOTS ABOVE}"} d = pform.__dict__ # if unicode is false then calculate number of apostrophes needed and # add to output if not self._use_unicode: apostrophes = "" for i in range(0, dot_i): apostrophes += "'" d['picture'][0] += apostrophes + "(t)" else: d['picture'] = [center_accent(d['picture'][0], dots[dot_i])] return pform def _print_Function(self, e): from sympy.physics.vector.functions import dynamicsymbols t = dynamicsymbols._t # XXX works only for applied functions func = e.func args = e.args func_name = func.__name__ pform = self._print_Symbol(Symbol(func_name)) # If this function is an Undefined function of t, it is probably a # dynamic symbol, so we'll skip the (t). The rest of the code is # identical to the normal PrettyPrinter code if not (isinstance(func, UndefinedFunction) and (args == (t,))): return super()._print_Function(e) return pform def vprint(expr, **settings): r"""Function for printing of expressions generated in the sympy.physics vector package. Extends SymPy's StrPrinter, takes the same setting accepted by SymPy's :func:`~.sstr`, and is equivalent to ``print(sstr(foo))``. Parameters ========== expr : valid SymPy object SymPy expression to print. settings : args Same as the settings accepted by SymPy's sstr(). Examples ======== >>> from sympy.physics.vector import vprint, dynamicsymbols >>> u1 = dynamicsymbols('u1') >>> print(u1) u1(t) >>> vprint(u1) u1 """ outstr = vsprint(expr, **settings) import builtins if (outstr != 'None'): builtins._ = outstr print(outstr) def vsstrrepr(expr, **settings): """Function for displaying expression representation's with vector printing enabled. Parameters ========== expr : valid SymPy object SymPy expression to print. settings : args Same as the settings accepted by SymPy's sstrrepr(). """ p = VectorStrReprPrinter(settings) return p.doprint(expr) def vsprint(expr, **settings): r"""Function for displaying expressions generated in the sympy.physics vector package. Returns the output of vprint() as a string. Parameters ========== expr : valid SymPy object SymPy expression to print settings : args Same as the settings accepted by SymPy's sstr(). Examples ======== >>> from sympy.physics.vector import vsprint, dynamicsymbols >>> u1, u2 = dynamicsymbols('u1 u2') >>> u2d = dynamicsymbols('u2', level=1) >>> print("%s = %s" % (u1, u2 + u2d)) u1(t) = u2(t) + Derivative(u2(t), t) >>> print("%s = %s" % (vsprint(u1), vsprint(u2 + u2d))) u1 = u2 + u2' """ string_printer = VectorStrPrinter(settings) return string_printer.doprint(expr) def vpprint(expr, **settings): r"""Function for pretty printing of expressions generated in the sympy.physics vector package. Mainly used for expressions not inside a vector; the output of running scripts and generating equations of motion. Takes the same options as SymPy's :func:`~.pretty_print`; see that function for more information. Parameters ========== expr : valid SymPy object SymPy expression to pretty print settings : args Same as those accepted by SymPy's pretty_print. """ pp = VectorPrettyPrinter(settings) # Note that this is copied from sympy.printing.pretty.pretty_print: # XXX: this is an ugly hack, but at least it works use_unicode = pp._settings['use_unicode'] from sympy.printing.pretty.pretty_symbology import pretty_use_unicode uflag = pretty_use_unicode(use_unicode) try: return pp.doprint(expr) finally: pretty_use_unicode(uflag) def vlatex(expr, **settings): r"""Function for printing latex representation of sympy.physics.vector objects. For latex representation of Vectors, Dyadics, and dynamicsymbols. Takes the same options as SymPy's :func:`~.latex`; see that function for more information; Parameters ========== expr : valid SymPy object SymPy expression to represent in LaTeX form settings : args Same as latex() Examples ======== >>> from sympy.physics.vector import vlatex, ReferenceFrame, dynamicsymbols >>> N = ReferenceFrame('N') >>> q1, q2 = dynamicsymbols('q1 q2') >>> q1d, q2d = dynamicsymbols('q1 q2', 1) >>> q1dd, q2dd = dynamicsymbols('q1 q2', 2) >>> vlatex(N.x + N.y) '\\mathbf{\\hat{n}_x} + \\mathbf{\\hat{n}_y}' >>> vlatex(q1 + q2) 'q_{1} + q_{2}' >>> vlatex(q1d) '\\dot{q}_{1}' >>> vlatex(q1 * q2d) 'q_{1} \\dot{q}_{2}' >>> vlatex(q1dd * q1 / q1d) '\\frac{q_{1} \\ddot{q}_{1}}{\\dot{q}_{1}}' """ latex_printer = VectorLatexPrinter(settings) return latex_printer.doprint(expr) def init_vprinting(**kwargs): """Initializes time derivative printing for all SymPy objects, i.e. any functions of time will be displayed in a more compact notation. The main benefit of this is for printing of time derivatives; instead of displaying as ``Derivative(f(t),t)``, it will display ``f'``. This is only actually needed for when derivatives are present and are not in a physics.vector.Vector or physics.vector.Dyadic object. This function is a light wrapper to :func:`~.init_printing`. Any keyword arguments for it are valid here. {0} Examples ======== >>> from sympy import Function, symbols >>> t, x = symbols('t, x') >>> omega = Function('omega') >>> omega(x).diff() Derivative(omega(x), x) >>> omega(t).diff() Derivative(omega(t), t) Now use the string printer: >>> from sympy.physics.vector import init_vprinting >>> init_vprinting(pretty_print=False) >>> omega(x).diff() Derivative(omega(x), x) >>> omega(t).diff() omega' """ kwargs['str_printer'] = vsstrrepr kwargs['pretty_printer'] = vpprint kwargs['latex_printer'] = vlatex init_printing(**kwargs) params = init_printing.__doc__.split('Examples\n ========')[0] # type: ignore init_vprinting.__doc__ = init_vprinting.__doc__.format(params) # type: ignore
6ad38feac4502d00cd02e1c0ed43e6230e5f7dc56ded1a2f506feb666dde8c99
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(sympify(out), recursive=True) else: return sympify(out) def __truediv__(self, other): """This uses mul and inputs self and 1 divided by other. """ return self.__mul__(sympify(1) / 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] for i, v in enumerate(newlist): newlist[i] = (sympify(other) * newlist[i][0], newlist[i][1]) return Vector(newlist) def __ne__(self, other): return not self == other 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 var = sympify(var) _check_frame(frame) 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
76e69b5cfc982433add6aa3be1e3c63b8fda9dbef0234265f15bc47fe0f5f104
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_dict[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: vel = None for f in self.pos_from(neighbor).args: if f[1] in self._vel_dict.keys(): if self._vel_dict[f[1]] != 0: vel = self._vel_dict[f[1]] break if vel is None: vel = self.pos_from(neighbor).dt(frame) self.set_vel(frame, vel + 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)
169dc5c747689cd50f8fdae4674df1142f07854cace14be880aebd6a1d92777a
from functools import reduce from sympy.core.backend import (sympify, diff, sin, cos, Matrix, symbols, Function, S, Symbol) from sympy.integrals.integrals import integrate from sympy.simplify.trigsimp import trigsimp from .vector import Vector, _check_vector from .frame import CoordinateSym, _check_frame from .dyadic import Dyadic from .printing import vprint, vsprint, vpprint, vlatex, init_vprinting from sympy.utilities.iterables import iterable from sympy.utilities.misc import translate __all__ = ['cross', 'dot', 'express', 'time_derivative', 'outer', 'kinematic_equations', 'get_motion_params', 'partial_velocity', 'dynamicsymbols', 'vprint', 'vsprint', 'vpprint', 'vlatex', 'init_vprinting'] def cross(vec1, vec2): """Cross product convenience wrapper for Vector.cross(): \n""" if not isinstance(vec1, (Vector, Dyadic)): raise TypeError('Cross product is between two vectors') return vec1 ^ vec2 cross.__doc__ += Vector.cross.__doc__ # type: ignore def dot(vec1, vec2): """Dot product convenience wrapper for Vector.dot(): \n""" if not isinstance(vec1, (Vector, Dyadic)): raise TypeError('Dot product is between two vectors') return vec1 & vec2 dot.__doc__ += Vector.dot.__doc__ # type: ignore def express(expr, frame, frame2=None, variables=False): """ Global function for 'express' functionality. Re-expresses a Vector, scalar(sympyfiable) or Dyadic in given frame. Refer to the local methods of Vector and Dyadic for details. If 'variables' is True, then the coordinate variables (CoordinateSym instances) of other frames present in the vector/scalar field or dyadic expression are also substituted in terms of the base scalars of this frame. Parameters ========== expr : Vector/Dyadic/scalar(sympyfiable) The expression to re-express in ReferenceFrame 'frame' frame: ReferenceFrame The reference frame to express expr in frame2 : ReferenceFrame The other frame required for re-expression(only for Dyadic expr) variables : boolean Specifies whether to substitute the coordinate variables present in expr, in terms of those of frame 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) >>> from sympy.physics.vector import express >>> express(d, B, N) cos(q)*(B.x|N.x) - sin(q)*(B.y|N.x) >>> express(B.x, N) cos(q)*N.x + sin(q)*N.y >>> express(N[0], B, variables=True) B_x*cos(q) - B_y*sin(q) """ _check_frame(frame) if expr == 0: return expr if isinstance(expr, Vector): # Given expr is a Vector if variables: # If variables attribute is True, substitute the coordinate # variables in the Vector frame_list = [x[-1] for x in expr.args] subs_dict = {} for f in frame_list: subs_dict.update(f.variable_map(frame)) expr = expr.subs(subs_dict) # Re-express in this frame outvec = Vector([]) for i, v in enumerate(expr.args): if v[1] != frame: temp = frame.dcm(v[1]) * v[0] if Vector.simp: temp = temp.applyfunc(lambda x: trigsimp(x, method='fu')) outvec += Vector([(temp, frame)]) else: outvec += Vector([v]) return outvec if isinstance(expr, Dyadic): if frame2 is None: frame2 = frame _check_frame(frame2) ol = Dyadic(0) for i, v in enumerate(expr.args): ol += express(v[0], frame, variables=variables) * \ (express(v[1], frame, variables=variables) | express(v[2], frame2, variables=variables)) return ol else: if variables: # Given expr is a scalar field frame_set = set() expr = sympify(expr) # Substitute all the coordinate variables for x in expr.free_symbols: if isinstance(x, CoordinateSym) and x.frame != frame: frame_set.add(x.frame) subs_dict = {} for f in frame_set: subs_dict.update(f.variable_map(frame)) return expr.subs(subs_dict) return expr def time_derivative(expr, frame, order=1): """ Calculate the time derivative of a vector/scalar field function or dyadic expression in given frame. References ========== https://en.wikipedia.org/wiki/Rotating_reference_frame#Time_derivatives_in_the_two_frames Parameters ========== expr : Vector/Dyadic/sympifyable The expression whose time derivative is to be calculated frame : ReferenceFrame The reference frame to calculate the time derivative in order : integer The order of the derivative to be calculated Examples ======== >>> from sympy.physics.vector import ReferenceFrame, dynamicsymbols >>> from sympy.physics.vector import init_vprinting >>> init_vprinting(pretty_print=False) >>> from sympy import Symbol >>> q1 = Symbol('q1') >>> u1 = dynamicsymbols('u1') >>> N = ReferenceFrame('N') >>> A = N.orientnew('A', 'Axis', [q1, N.x]) >>> v = u1 * N.x >>> A.set_ang_vel(N, 10*A.x) >>> from sympy.physics.vector import time_derivative >>> time_derivative(v, N) u1'*N.x >>> time_derivative(u1*A[0], N) N_x*u1' >>> B = N.orientnew('B', 'Axis', [u1, N.z]) >>> from sympy.physics.vector import outer >>> d = outer(N.x, N.x) >>> time_derivative(d, B) - u1'*(N.y|N.x) - u1'*(N.x|N.y) """ t = dynamicsymbols._t _check_frame(frame) if order == 0: return expr if order % 1 != 0 or order < 0: raise ValueError("Unsupported value of order entered") if isinstance(expr, Vector): outlist = [] for i, v in enumerate(expr.args): if v[1] == frame: outlist += [(express(v[0], frame, variables=True).diff(t), frame)] else: outlist += (time_derivative(Vector([v]), v[1]) + (v[1].ang_vel_in(frame) ^ Vector([v]))).args outvec = Vector(outlist) return time_derivative(outvec, frame, order - 1) if isinstance(expr, Dyadic): ol = Dyadic(0) for i, v in enumerate(expr.args): ol += (v[0].diff(t) * (v[1] | v[2])) ol += (v[0] * (time_derivative(v[1], frame) | v[2])) ol += (v[0] * (v[1] | time_derivative(v[2], frame))) return time_derivative(ol, frame, order - 1) else: return diff(express(expr, frame, variables=True), t, order) def outer(vec1, vec2): """Outer product convenience wrapper for Vector.outer():\n""" if not isinstance(vec1, Vector): raise TypeError('Outer product is between two Vectors') return vec1 | vec2 outer.__doc__ += Vector.outer.__doc__ # type: ignore def kinematic_equations(speeds, coords, rot_type, rot_order=''): """Gives equations relating the qdot's to u's for a rotation type. Supply rotation type and order as in orient. Speeds are assumed to be body-fixed; if we are defining the orientation of B in A using by rot_type, the angular velocity of B in A is assumed to be in the form: speed[0]*B.x + speed[1]*B.y + speed[2]*B.z Parameters ========== speeds : list of length 3 The body fixed angular velocity measure numbers. coords : list of length 3 or 4 The coordinates used to define the orientation of the two frames. rot_type : str The type of rotation used to create the equations. Body, Space, or Quaternion only rot_order : str or int If applicable, the order of a series of rotations. Examples ======== >>> from sympy.physics.vector import dynamicsymbols >>> from sympy.physics.vector import kinematic_equations, vprint >>> u1, u2, u3 = dynamicsymbols('u1 u2 u3') >>> q1, q2, q3 = dynamicsymbols('q1 q2 q3') >>> vprint(kinematic_equations([u1,u2,u3], [q1,q2,q3], 'body', '313'), ... order=None) [-(u1*sin(q3) + u2*cos(q3))/sin(q2) + q1', -u1*cos(q3) + u2*sin(q3) + q2', (u1*sin(q3) + u2*cos(q3))*cos(q2)/sin(q2) - u3 + q3'] """ # Code below is checking and sanitizing input approved_orders = ('123', '231', '312', '132', '213', '321', '121', '131', '212', '232', '313', '323', '1', '2', '3', '') # make sure XYZ => 123 and rot_type is in lower case rot_order = translate(str(rot_order), 'XYZxyz', '123123') rot_type = rot_type.lower() if not isinstance(speeds, (list, tuple)): raise TypeError('Need to supply speeds in a list') if len(speeds) != 3: raise TypeError('Need to supply 3 body-fixed speeds') if not isinstance(coords, (list, tuple)): raise TypeError('Need to supply coordinates in a list') if rot_type in ['body', 'space']: if rot_order not in approved_orders: raise ValueError('Not an acceptable rotation order') if len(coords) != 3: raise ValueError('Need 3 coordinates for body or space') # Actual hard-coded kinematic differential equations w1, w2, w3 = speeds if w1 == w2 == w3 == 0: return [S.Zero]*3 q1, q2, q3 = coords q1d, q2d, q3d = [diff(i, dynamicsymbols._t) for i in coords] s1, s2, s3 = [sin(q1), sin(q2), sin(q3)] c1, c2, c3 = [cos(q1), cos(q2), cos(q3)] if rot_type == 'body': if rot_order == '123': return [q1d - (w1 * c3 - w2 * s3) / c2, q2d - w1 * s3 - w2 * c3, q3d - (-w1 * c3 + w2 * s3) * s2 / c2 - w3] if rot_order == '231': return [q1d - (w2 * c3 - w3 * s3) / c2, q2d - w2 * s3 - w3 * c3, q3d - w1 - (- w2 * c3 + w3 * s3) * s2 / c2] if rot_order == '312': return [q1d - (-w1 * s3 + w3 * c3) / c2, q2d - w1 * c3 - w3 * s3, q3d - (w1 * s3 - w3 * c3) * s2 / c2 - w2] if rot_order == '132': return [q1d - (w1 * c3 + w3 * s3) / c2, q2d + w1 * s3 - w3 * c3, q3d - (w1 * c3 + w3 * s3) * s2 / c2 - w2] if rot_order == '213': return [q1d - (w1 * s3 + w2 * c3) / c2, q2d - w1 * c3 + w2 * s3, q3d - (w1 * s3 + w2 * c3) * s2 / c2 - w3] if rot_order == '321': return [q1d - (w2 * s3 + w3 * c3) / c2, q2d - w2 * c3 + w3 * s3, q3d - w1 - (w2 * s3 + w3 * c3) * s2 / c2] if rot_order == '121': return [q1d - (w2 * s3 + w3 * c3) / s2, q2d - w2 * c3 + w3 * s3, q3d - w1 + (w2 * s3 + w3 * c3) * c2 / s2] if rot_order == '131': return [q1d - (-w2 * c3 + w3 * s3) / s2, q2d - w2 * s3 - w3 * c3, q3d - w1 - (w2 * c3 - w3 * s3) * c2 / s2] if rot_order == '212': return [q1d - (w1 * s3 - w3 * c3) / s2, q2d - w1 * c3 - w3 * s3, q3d - (-w1 * s3 + w3 * c3) * c2 / s2 - w2] if rot_order == '232': return [q1d - (w1 * c3 + w3 * s3) / s2, q2d + w1 * s3 - w3 * c3, q3d + (w1 * c3 + w3 * s3) * c2 / s2 - w2] if rot_order == '313': return [q1d - (w1 * s3 + w2 * c3) / s2, q2d - w1 * c3 + w2 * s3, q3d + (w1 * s3 + w2 * c3) * c2 / s2 - w3] if rot_order == '323': return [q1d - (-w1 * c3 + w2 * s3) / s2, q2d - w1 * s3 - w2 * c3, q3d - (w1 * c3 - w2 * s3) * c2 / s2 - w3] if rot_type == 'space': if rot_order == '123': return [q1d - w1 - (w2 * s1 + w3 * c1) * s2 / c2, q2d - w2 * c1 + w3 * s1, q3d - (w2 * s1 + w3 * c1) / c2] if rot_order == '231': return [q1d - (w1 * c1 + w3 * s1) * s2 / c2 - w2, q2d + w1 * s1 - w3 * c1, q3d - (w1 * c1 + w3 * s1) / c2] if rot_order == '312': return [q1d - (w1 * s1 + w2 * c1) * s2 / c2 - w3, q2d - w1 * c1 + w2 * s1, q3d - (w1 * s1 + w2 * c1) / c2] if rot_order == '132': return [q1d - w1 - (-w2 * c1 + w3 * s1) * s2 / c2, q2d - w2 * s1 - w3 * c1, q3d - (w2 * c1 - w3 * s1) / c2] if rot_order == '213': return [q1d - (w1 * s1 - w3 * c1) * s2 / c2 - w2, q2d - w1 * c1 - w3 * s1, q3d - (-w1 * s1 + w3 * c1) / c2] if rot_order == '321': return [q1d - (-w1 * c1 + w2 * s1) * s2 / c2 - w3, q2d - w1 * s1 - w2 * c1, q3d - (w1 * c1 - w2 * s1) / c2] if rot_order == '121': return [q1d - w1 + (w2 * s1 + w3 * c1) * c2 / s2, q2d - w2 * c1 + w3 * s1, q3d - (w2 * s1 + w3 * c1) / s2] if rot_order == '131': return [q1d - w1 - (w2 * c1 - w3 * s1) * c2 / s2, q2d - w2 * s1 - w3 * c1, q3d - (-w2 * c1 + w3 * s1) / s2] if rot_order == '212': return [q1d - (-w1 * s1 + w3 * c1) * c2 / s2 - w2, q2d - w1 * c1 - w3 * s1, q3d - (w1 * s1 - w3 * c1) / s2] if rot_order == '232': return [q1d + (w1 * c1 + w3 * s1) * c2 / s2 - w2, q2d + w1 * s1 - w3 * c1, q3d - (w1 * c1 + w3 * s1) / s2] if rot_order == '313': return [q1d + (w1 * s1 + w2 * c1) * c2 / s2 - w3, q2d - w1 * c1 + w2 * s1, q3d - (w1 * s1 + w2 * c1) / s2] if rot_order == '323': return [q1d - (w1 * c1 - w2 * s1) * c2 / s2 - w3, q2d - w1 * s1 - w2 * c1, q3d - (-w1 * c1 + w2 * s1) / s2] elif rot_type == 'quaternion': if rot_order != '': raise ValueError('Cannot have rotation order for quaternion') if len(coords) != 4: raise ValueError('Need 4 coordinates for quaternion') # Actual hard-coded kinematic differential equations e0, e1, e2, e3 = coords w = Matrix(speeds + [0]) E = Matrix([[e0, -e3, e2, e1], [e3, e0, -e1, e2], [-e2, e1, e0, e3], [-e1, -e2, -e3, e0]]) edots = Matrix([diff(i, dynamicsymbols._t) for i in [e1, e2, e3, e0]]) return list(edots.T - 0.5 * w.T * E.T) else: raise ValueError('Not an approved rotation type for this function') def get_motion_params(frame, **kwargs): """ Returns the three motion parameters - (acceleration, velocity, and position) as vectorial functions of time in the given frame. If a higher order differential function is provided, the lower order functions are used as boundary conditions. For example, given the acceleration, the velocity and position parameters are taken as boundary conditions. The values of time at which the boundary conditions are specified are taken from timevalue1(for position boundary condition) and timevalue2(for velocity boundary condition). If any of the boundary conditions are not provided, they are taken to be zero by default (zero vectors, in case of vectorial inputs). If the boundary conditions are also functions of time, they are converted to constants by substituting the time values in the dynamicsymbols._t time Symbol. This function can also be used for calculating rotational motion parameters. Have a look at the Parameters and Examples for more clarity. Parameters ========== frame : ReferenceFrame The frame to express the motion parameters in acceleration : Vector Acceleration of the object/frame as a function of time velocity : Vector Velocity as function of time or as boundary condition of velocity at time = timevalue1 position : Vector Velocity as function of time or as boundary condition of velocity at time = timevalue1 timevalue1 : sympyfiable Value of time for position boundary condition timevalue2 : sympyfiable Value of time for velocity boundary condition Examples ======== >>> from sympy.physics.vector import ReferenceFrame, get_motion_params, dynamicsymbols >>> from sympy.physics.vector import init_vprinting >>> init_vprinting(pretty_print=False) >>> from sympy import symbols >>> R = ReferenceFrame('R') >>> v1, v2, v3 = dynamicsymbols('v1 v2 v3') >>> v = v1*R.x + v2*R.y + v3*R.z >>> get_motion_params(R, position = v) (v1''*R.x + v2''*R.y + v3''*R.z, v1'*R.x + v2'*R.y + v3'*R.z, v1*R.x + v2*R.y + v3*R.z) >>> a, b, c = symbols('a b c') >>> v = a*R.x + b*R.y + c*R.z >>> get_motion_params(R, velocity = v) (0, a*R.x + b*R.y + c*R.z, a*t*R.x + b*t*R.y + c*t*R.z) >>> parameters = get_motion_params(R, acceleration = v) >>> parameters[1] a*t*R.x + b*t*R.y + c*t*R.z >>> parameters[2] a*t**2/2*R.x + b*t**2/2*R.y + c*t**2/2*R.z """ def _process_vector_differential(vectdiff, condition, variable, ordinate, frame): """ Helper function for get_motion methods. Finds derivative of vectdiff wrt variable, and its integral using the specified boundary condition at value of variable = ordinate. Returns a tuple of - (derivative, function and integral) wrt vectdiff """ # Make sure boundary condition is independent of 'variable' if condition != 0: condition = express(condition, frame, variables=True) # Special case of vectdiff == 0 if vectdiff == Vector(0): return (0, 0, condition) # Express vectdiff completely in condition's frame to give vectdiff1 vectdiff1 = express(vectdiff, frame) # Find derivative of vectdiff vectdiff2 = time_derivative(vectdiff, frame) # Integrate and use boundary condition vectdiff0 = Vector(0) lims = (variable, ordinate, variable) for dim in frame: function1 = vectdiff1.dot(dim) abscissa = dim.dot(condition).subs({variable: ordinate}) # Indefinite integral of 'function1' wrt 'variable', using # the given initial condition (ordinate, abscissa). vectdiff0 += (integrate(function1, lims) + abscissa) * dim # Return tuple return (vectdiff2, vectdiff, vectdiff0) _check_frame(frame) # Decide mode of operation based on user's input if 'acceleration' in kwargs: mode = 2 elif 'velocity' in kwargs: mode = 1 else: mode = 0 # All the possible parameters in kwargs # Not all are required for every case # If not specified, set to default values(may or may not be used in # calculations) conditions = ['acceleration', 'velocity', 'position', 'timevalue', 'timevalue1', 'timevalue2'] for i, x in enumerate(conditions): if x not in kwargs: if i < 3: kwargs[x] = Vector(0) else: kwargs[x] = S.Zero elif i < 3: _check_vector(kwargs[x]) else: kwargs[x] = sympify(kwargs[x]) if mode == 2: vel = _process_vector_differential(kwargs['acceleration'], kwargs['velocity'], dynamicsymbols._t, kwargs['timevalue2'], frame)[2] pos = _process_vector_differential(vel, kwargs['position'], dynamicsymbols._t, kwargs['timevalue1'], frame)[2] return (kwargs['acceleration'], vel, pos) elif mode == 1: return _process_vector_differential(kwargs['velocity'], kwargs['position'], dynamicsymbols._t, kwargs['timevalue1'], frame) else: vel = time_derivative(kwargs['position'], frame) acc = time_derivative(vel, frame) return (acc, vel, kwargs['position']) def partial_velocity(vel_vecs, gen_speeds, frame): """Returns a list of partial velocities with respect to the provided generalized speeds in the given reference frame for each of the supplied velocity vectors. The output is a list of lists. The outer list has a number of elements equal to the number of supplied velocity vectors. The inner lists are, for each velocity vector, the partial derivatives of that velocity vector with respect to the generalized speeds supplied. Parameters ========== vel_vecs : iterable An iterable of velocity vectors (angular or linear). gen_speeds : iterable An iterable of generalized speeds. frame : ReferenceFrame The reference frame that the partial derivatives are going to be taken in. Examples ======== >>> from sympy.physics.vector import Point, ReferenceFrame >>> from sympy.physics.vector import dynamicsymbols >>> from sympy.physics.vector import partial_velocity >>> u = dynamicsymbols('u') >>> N = ReferenceFrame('N') >>> P = Point('P') >>> P.set_vel(N, u * N.x) >>> vel_vecs = [P.vel(N)] >>> gen_speeds = [u] >>> partial_velocity(vel_vecs, gen_speeds, N) [[N.x]] """ if not iterable(vel_vecs): raise TypeError('Velocity vectors must be contained in an iterable.') if not iterable(gen_speeds): raise TypeError('Generalized speeds must be contained in an iterable') vec_partials = [] for vec in vel_vecs: partials = [] for speed in gen_speeds: partials.append(vec.diff(speed, frame, var_in_dcm=False)) vec_partials.append(partials) return vec_partials def dynamicsymbols(names, level=0, **assumptions): """Uses symbols and Function for functions of time. Creates a SymPy UndefinedFunction, which is then initialized as a function of a variable, the default being Symbol('t'). Parameters ========== names : str Names of the dynamic symbols you want to create; works the same way as inputs to symbols level : int Level of differentiation of the returned function; d/dt once of t, twice of t, etc. assumptions : - real(bool) : This is used to set the dynamicsymbol as real, by default is False. - positive(bool) : This is used to set the dynamicsymbol as positive, by default is False. - commutative(bool) : This is used to set the commutative property of a dynamicsymbol, by default is True. - integer(bool) : This is used to set the dynamicsymbol as integer, by default is False. Examples ======== >>> from sympy.physics.vector import dynamicsymbols >>> from sympy import diff, Symbol >>> q1 = dynamicsymbols('q1') >>> q1 q1(t) >>> q2 = dynamicsymbols('q2', real=True) >>> q2.is_real True >>> q3 = dynamicsymbols('q3', positive=True) >>> q3.is_positive True >>> q4, q5 = dynamicsymbols('q4,q5', commutative=False) >>> bool(q4*q5 != q5*q4) True >>> q6 = dynamicsymbols('q6', integer=True) >>> q6.is_integer True >>> diff(q1, Symbol('t')) Derivative(q1(t), t) """ esses = symbols(names, cls=Function, **assumptions) t = dynamicsymbols._t if iterable(esses): esses = [reduce(diff, [t] * level, e(t)) for e in esses] return esses else: return reduce(diff, [t] * level, esses(t)) dynamicsymbols._t = Symbol('t') # type: ignore dynamicsymbols._str = '\'' # type: ignore
33b99cd296b8d4264743a55c726d7ee1547e366b48a91ee39a915c50680578d5
from sympy.core.function import diff from sympy.core.singleton import S from sympy.integrals.integrals import integrate from sympy.physics.vector import Vector, express from sympy.physics.vector.frame import _check_frame from sympy.physics.vector.vector import _check_vector __all__ = ['curl', 'divergence', 'gradient', 'is_conservative', 'is_solenoidal', 'scalar_potential', 'scalar_potential_difference'] def curl(vect, frame): """ Returns the curl of a vector field computed wrt the coordinate symbols of the given frame. Parameters ========== vect : Vector The vector operand frame : ReferenceFrame The reference frame to calculate the curl in Examples ======== >>> from sympy.physics.vector import ReferenceFrame >>> from sympy.physics.vector import curl >>> R = ReferenceFrame('R') >>> v1 = R[1]*R[2]*R.x + R[0]*R[2]*R.y + R[0]*R[1]*R.z >>> curl(v1, R) 0 >>> v2 = R[0]*R[1]*R[2]*R.x >>> curl(v2, R) R_x*R_y*R.y - R_x*R_z*R.z """ _check_vector(vect) if vect == 0: return Vector(0) vect = express(vect, frame, variables=True) # A mechanical approach to avoid looping overheads vectx = vect.dot(frame.x) vecty = vect.dot(frame.y) vectz = vect.dot(frame.z) outvec = Vector(0) outvec += (diff(vectz, frame[1]) - diff(vecty, frame[2])) * frame.x outvec += (diff(vectx, frame[2]) - diff(vectz, frame[0])) * frame.y outvec += (diff(vecty, frame[0]) - diff(vectx, frame[1])) * frame.z return outvec def divergence(vect, frame): """ Returns the divergence of a vector field computed wrt the coordinate symbols of the given frame. Parameters ========== vect : Vector The vector operand frame : ReferenceFrame The reference frame to calculate the divergence in Examples ======== >>> from sympy.physics.vector import ReferenceFrame >>> from sympy.physics.vector import divergence >>> R = ReferenceFrame('R') >>> v1 = R[0]*R[1]*R[2] * (R.x+R.y+R.z) >>> divergence(v1, R) R_x*R_y + R_x*R_z + R_y*R_z >>> v2 = 2*R[1]*R[2]*R.y >>> divergence(v2, R) 2*R_z """ _check_vector(vect) if vect == 0: return S.Zero vect = express(vect, frame, variables=True) vectx = vect.dot(frame.x) vecty = vect.dot(frame.y) vectz = vect.dot(frame.z) out = S.Zero out += diff(vectx, frame[0]) out += diff(vecty, frame[1]) out += diff(vectz, frame[2]) return out def gradient(scalar, frame): """ Returns the vector gradient of a scalar field computed wrt the coordinate symbols of the given frame. Parameters ========== scalar : sympifiable The scalar field to take the gradient of frame : ReferenceFrame The frame to calculate the gradient in Examples ======== >>> from sympy.physics.vector import ReferenceFrame >>> from sympy.physics.vector import gradient >>> R = ReferenceFrame('R') >>> s1 = R[0]*R[1]*R[2] >>> gradient(s1, R) R_y*R_z*R.x + R_x*R_z*R.y + R_x*R_y*R.z >>> s2 = 5*R[0]**2*R[2] >>> gradient(s2, R) 10*R_x*R_z*R.x + 5*R_x**2*R.z """ _check_frame(frame) outvec = Vector(0) scalar = express(scalar, frame, variables=True) for i, x in enumerate(frame): outvec += diff(scalar, frame[i]) * x return outvec def is_conservative(field): """ Checks if a field is conservative. Parameters ========== field : Vector The field to check for conservative property Examples ======== >>> from sympy.physics.vector import ReferenceFrame >>> from sympy.physics.vector import is_conservative >>> R = ReferenceFrame('R') >>> is_conservative(R[1]*R[2]*R.x + R[0]*R[2]*R.y + R[0]*R[1]*R.z) True >>> is_conservative(R[2] * R.y) False """ # Field is conservative irrespective of frame # Take the first frame in the result of the separate method of Vector if field == Vector(0): return True frame = list(field.separate())[0] return curl(field, frame).simplify() == Vector(0) def is_solenoidal(field): """ Checks if a field is solenoidal. Parameters ========== field : Vector The field to check for solenoidal property Examples ======== >>> from sympy.physics.vector import ReferenceFrame >>> from sympy.physics.vector import is_solenoidal >>> R = ReferenceFrame('R') >>> is_solenoidal(R[1]*R[2]*R.x + R[0]*R[2]*R.y + R[0]*R[1]*R.z) True >>> is_solenoidal(R[1] * R.y) False """ # Field is solenoidal irrespective of frame # Take the first frame in the result of the separate method in Vector if field == Vector(0): return True frame = list(field.separate())[0] return divergence(field, frame).simplify() is S.Zero def scalar_potential(field, frame): """ Returns the scalar potential function of a field in a given frame (without the added integration constant). Parameters ========== field : Vector The vector field whose scalar potential function is to be calculated frame : ReferenceFrame The frame to do the calculation in Examples ======== >>> from sympy.physics.vector import ReferenceFrame >>> from sympy.physics.vector import scalar_potential, gradient >>> R = ReferenceFrame('R') >>> scalar_potential(R.z, R) == R[2] True >>> scalar_field = 2*R[0]**2*R[1]*R[2] >>> grad_field = gradient(scalar_field, R) >>> scalar_potential(grad_field, R) 2*R_x**2*R_y*R_z """ # Check whether field is conservative if not is_conservative(field): raise ValueError("Field is not conservative") if field == Vector(0): return S.Zero # Express the field exntirely in frame # Substitute coordinate variables also _check_frame(frame) field = express(field, frame, variables=True) # Make a list of dimensions of the frame dimensions = [x for x in frame] # Calculate scalar potential function temp_function = integrate(field.dot(dimensions[0]), frame[0]) for i, dim in enumerate(dimensions[1:]): partial_diff = diff(temp_function, frame[i + 1]) partial_diff = field.dot(dim) - partial_diff temp_function += integrate(partial_diff, frame[i + 1]) return temp_function def scalar_potential_difference(field, frame, point1, point2, origin): """ Returns the scalar potential difference between two points in a certain frame, wrt a given field. If a scalar field is provided, its values at the two points are considered. If a conservative vector field is provided, the values of its scalar potential function at the two points are used. Returns (potential at position 2) - (potential at position 1) Parameters ========== field : Vector/sympyfiable The field to calculate wrt frame : ReferenceFrame The frame to do the calculations in point1 : Point The initial Point in given frame position2 : Point The second Point in the given frame origin : Point The Point to use as reference point for position vector calculation Examples ======== >>> from sympy.physics.vector import ReferenceFrame, Point >>> from sympy.physics.vector import scalar_potential_difference >>> R = ReferenceFrame('R') >>> O = Point('O') >>> P = O.locatenew('P', R[0]*R.x + R[1]*R.y + R[2]*R.z) >>> vectfield = 4*R[0]*R[1]*R.x + 2*R[0]**2*R.y >>> scalar_potential_difference(vectfield, R, O, P, O) 2*R_x**2*R_y >>> Q = O.locatenew('O', 3*R.x + R.y + 2*R.z) >>> scalar_potential_difference(vectfield, R, P, Q, O) -2*R_x**2*R_y + 18 """ _check_frame(frame) if isinstance(field, Vector): # Get the scalar potential function scalar_fn = scalar_potential(field, frame) else: # Field is a scalar scalar_fn = field # Express positions in required frame position1 = express(point1.pos_from(origin), frame, variables=True) position2 = express(point2.pos_from(origin), frame, variables=True) # Get the two positions as substitution dicts for coordinate variables subs_dict1 = {} subs_dict2 = {} for i, x in enumerate(frame): subs_dict1[frame[i]] = x.dot(position1) subs_dict2[frame[i]] = x.dot(position2) return scalar_fn.subs(subs_dict2) - scalar_fn.subs(subs_dict1)
e7be8a6ba90dae721cfaf5753c1cc94ea5d880b23c36b4586c68eadb4b104c69
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) amount = sympify(angle) theta = amount 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 = (amount).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'))
2ccc6c59aa35dfa28524fdc48907455141af8ff1fd5e1b28b90f0896b55bd784
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] for i, v in enumerate(newlist): newlist[i] = (sympify(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
c4ca185323f2876c9cc8d8f98289b2ff43e434a2876bd5d1944dfd9995106aa2
""" Gaussian optics. The module implements: - Ray transfer matrices for geometrical and gaussian optics. See RayTransferMatrix, GeometricRay and BeamParameter - Conjugation relations for geometrical and gaussian optics. See geometric_conj*, gauss_conj and conjugate_gauss_beams The conventions for the distances are as follows: focal distance positive for convergent lenses object distance positive for real objects image distance positive for real images """ __all__ = [ 'RayTransferMatrix', 'FreeSpace', 'FlatRefraction', 'CurvedRefraction', 'FlatMirror', 'CurvedMirror', 'ThinLens', 'GeometricRay', 'BeamParameter', 'waist2rayleigh', 'rayleigh2waist', 'geometric_conj_ab', 'geometric_conj_af', 'geometric_conj_bf', 'gaussian_conj', 'conjugate_gauss_beams', ] from sympy.core.expr import Expr from sympy.core.numbers import (I, pi) from sympy.core.sympify import sympify from sympy.functions.elementary.complexes import (im, re) from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import atan2 from sympy.matrices.dense import Matrix, MutableDenseMatrix from sympy.polys.rationaltools import together from sympy.utilities.misc import filldedent ### # A, B, C, D matrices ### class RayTransferMatrix(MutableDenseMatrix): """ Base class for a Ray Transfer Matrix. It should be used if there is not already a more specific subclass mentioned in See Also. Parameters ========== parameters : A, B, C and D or 2x2 matrix (Matrix(2, 2, [A, B, C, D])) Examples ======== >>> from sympy.physics.optics import RayTransferMatrix, ThinLens >>> from sympy import Symbol, Matrix >>> mat = RayTransferMatrix(1, 2, 3, 4) >>> mat Matrix([ [1, 2], [3, 4]]) >>> RayTransferMatrix(Matrix([[1, 2], [3, 4]])) Matrix([ [1, 2], [3, 4]]) >>> mat.A 1 >>> f = Symbol('f') >>> lens = ThinLens(f) >>> lens Matrix([ [ 1, 0], [-1/f, 1]]) >>> lens.C -1/f See Also ======== GeometricRay, BeamParameter, FreeSpace, FlatRefraction, CurvedRefraction, FlatMirror, CurvedMirror, ThinLens References ========== .. [1] https://en.wikipedia.org/wiki/Ray_transfer_matrix_analysis """ def __new__(cls, *args): if len(args) == 4: temp = ((args[0], args[1]), (args[2], args[3])) elif len(args) == 1 \ and isinstance(args[0], Matrix) \ and args[0].shape == (2, 2): temp = args[0] else: raise ValueError(filldedent(''' Expecting 2x2 Matrix or the 4 elements of the Matrix but got %s''' % str(args))) return Matrix.__new__(cls, temp) def __mul__(self, other): if isinstance(other, RayTransferMatrix): return RayTransferMatrix(Matrix.__mul__(self, other)) elif isinstance(other, GeometricRay): return GeometricRay(Matrix.__mul__(self, other)) elif isinstance(other, BeamParameter): temp = self*Matrix(((other.q,), (1,))) q = (temp[0]/temp[1]).expand(complex=True) return BeamParameter(other.wavelen, together(re(q)), z_r=together(im(q))) else: return Matrix.__mul__(self, other) @property def A(self): """ The A parameter of the Matrix. Examples ======== >>> from sympy.physics.optics import RayTransferMatrix >>> mat = RayTransferMatrix(1, 2, 3, 4) >>> mat.A 1 """ return self[0, 0] @property def B(self): """ The B parameter of the Matrix. Examples ======== >>> from sympy.physics.optics import RayTransferMatrix >>> mat = RayTransferMatrix(1, 2, 3, 4) >>> mat.B 2 """ return self[0, 1] @property def C(self): """ The C parameter of the Matrix. Examples ======== >>> from sympy.physics.optics import RayTransferMatrix >>> mat = RayTransferMatrix(1, 2, 3, 4) >>> mat.C 3 """ return self[1, 0] @property def D(self): """ The D parameter of the Matrix. Examples ======== >>> from sympy.physics.optics import RayTransferMatrix >>> mat = RayTransferMatrix(1, 2, 3, 4) >>> mat.D 4 """ return self[1, 1] class FreeSpace(RayTransferMatrix): """ Ray Transfer Matrix for free space. Parameters ========== distance See Also ======== RayTransferMatrix Examples ======== >>> from sympy.physics.optics import FreeSpace >>> from sympy import symbols >>> d = symbols('d') >>> FreeSpace(d) Matrix([ [1, d], [0, 1]]) """ def __new__(cls, d): return RayTransferMatrix.__new__(cls, 1, d, 0, 1) class FlatRefraction(RayTransferMatrix): """ Ray Transfer Matrix for refraction. Parameters ========== n1 : Refractive index of one medium. n2 : Refractive index of other medium. See Also ======== RayTransferMatrix Examples ======== >>> from sympy.physics.optics import FlatRefraction >>> from sympy import symbols >>> n1, n2 = symbols('n1 n2') >>> FlatRefraction(n1, n2) Matrix([ [1, 0], [0, n1/n2]]) """ def __new__(cls, n1, n2): n1, n2 = map(sympify, (n1, n2)) return RayTransferMatrix.__new__(cls, 1, 0, 0, n1/n2) class CurvedRefraction(RayTransferMatrix): """ Ray Transfer Matrix for refraction on curved interface. Parameters ========== R : Radius of curvature (positive for concave). n1 : Refractive index of one medium. n2 : Refractive index of other medium. See Also ======== RayTransferMatrix Examples ======== >>> from sympy.physics.optics import CurvedRefraction >>> from sympy import symbols >>> R, n1, n2 = symbols('R n1 n2') >>> CurvedRefraction(R, n1, n2) Matrix([ [ 1, 0], [(n1 - n2)/(R*n2), n1/n2]]) """ def __new__(cls, R, n1, n2): R, n1, n2 = map(sympify, (R, n1, n2)) return RayTransferMatrix.__new__(cls, 1, 0, (n1 - n2)/R/n2, n1/n2) class FlatMirror(RayTransferMatrix): """ Ray Transfer Matrix for reflection. See Also ======== RayTransferMatrix Examples ======== >>> from sympy.physics.optics import FlatMirror >>> FlatMirror() Matrix([ [1, 0], [0, 1]]) """ def __new__(cls): return RayTransferMatrix.__new__(cls, 1, 0, 0, 1) class CurvedMirror(RayTransferMatrix): """ Ray Transfer Matrix for reflection from curved surface. Parameters ========== R : radius of curvature (positive for concave) See Also ======== RayTransferMatrix Examples ======== >>> from sympy.physics.optics import CurvedMirror >>> from sympy import symbols >>> R = symbols('R') >>> CurvedMirror(R) Matrix([ [ 1, 0], [-2/R, 1]]) """ def __new__(cls, R): R = sympify(R) return RayTransferMatrix.__new__(cls, 1, 0, -2/R, 1) class ThinLens(RayTransferMatrix): """ Ray Transfer Matrix for a thin lens. Parameters ========== f : The focal distance. See Also ======== RayTransferMatrix Examples ======== >>> from sympy.physics.optics import ThinLens >>> from sympy import symbols >>> f = symbols('f') >>> ThinLens(f) Matrix([ [ 1, 0], [-1/f, 1]]) """ def __new__(cls, f): f = sympify(f) return RayTransferMatrix.__new__(cls, 1, 0, -1/f, 1) ### # Representation for geometric ray ### class GeometricRay(MutableDenseMatrix): """ Representation for a geometric ray in the Ray Transfer Matrix formalism. Parameters ========== h : height, and angle : angle, or matrix : a 2x1 matrix (Matrix(2, 1, [height, angle])) Examples ======== >>> from sympy.physics.optics import GeometricRay, FreeSpace >>> from sympy import symbols, Matrix >>> d, h, angle = symbols('d, h, angle') >>> GeometricRay(h, angle) Matrix([ [ h], [angle]]) >>> FreeSpace(d)*GeometricRay(h, angle) Matrix([ [angle*d + h], [ angle]]) >>> GeometricRay( Matrix( ((h,), (angle,)) ) ) Matrix([ [ h], [angle]]) See Also ======== RayTransferMatrix """ def __new__(cls, *args): if len(args) == 1 and isinstance(args[0], Matrix) \ and args[0].shape == (2, 1): temp = args[0] elif len(args) == 2: temp = ((args[0],), (args[1],)) else: raise ValueError(filldedent(''' Expecting 2x1 Matrix or the 2 elements of the Matrix but got %s''' % str(args))) return Matrix.__new__(cls, temp) @property def height(self): """ The distance from the optical axis. Examples ======== >>> from sympy.physics.optics import GeometricRay >>> from sympy import symbols >>> h, angle = symbols('h, angle') >>> gRay = GeometricRay(h, angle) >>> gRay.height h """ return self[0] @property def angle(self): """ The angle with the optical axis. Examples ======== >>> from sympy.physics.optics import GeometricRay >>> from sympy import symbols >>> h, angle = symbols('h, angle') >>> gRay = GeometricRay(h, angle) >>> gRay.angle angle """ return self[1] ### # Representation for gauss beam ### class BeamParameter(Expr): """ Representation for a gaussian ray in the Ray Transfer Matrix formalism. Parameters ========== wavelen : the wavelength, z : the distance to waist, and w : the waist, or z_r : the rayleigh range. n : the refractive index of medium. Examples ======== >>> from sympy.physics.optics import BeamParameter >>> p = BeamParameter(530e-9, 1, w=1e-3) >>> p.q 1 + 1.88679245283019*I*pi >>> p.q.n() 1.0 + 5.92753330865999*I >>> p.w_0.n() 0.00100000000000000 >>> p.z_r.n() 5.92753330865999 >>> from sympy.physics.optics import FreeSpace >>> fs = FreeSpace(10) >>> p1 = fs*p >>> p.w.n() 0.00101413072159615 >>> p1.w.n() 0.00210803120913829 See Also ======== RayTransferMatrix References ========== .. [1] https://en.wikipedia.org/wiki/Complex_beam_parameter .. [2] https://en.wikipedia.org/wiki/Gaussian_beam """ #TODO A class Complex may be implemented. The BeamParameter may # subclass it. See: # https://groups.google.com/d/topic/sympy/7XkU07NRBEs/discussion def __new__(cls, wavelen, z, z_r=None, w=None, n=1): wavelen = sympify(wavelen) z = sympify(z) n = sympify(n) if z_r is not None and w is None: z_r = sympify(z_r) elif w is not None and z_r is None: z_r = waist2rayleigh(sympify(w), wavelen, n) elif z_r is None and w is None: raise ValueError('Must specify one of w and z_r.') return Expr.__new__(cls, wavelen, z, z_r, n) @property def wavelen(self): return self.args[0] @property def z(self): return self.args[1] @property def z_r(self): return self.args[2] @property def n(self): return self.args[3] @property def q(self): """ The complex parameter representing the beam. Examples ======== >>> from sympy.physics.optics import BeamParameter >>> p = BeamParameter(530e-9, 1, w=1e-3) >>> p.q 1 + 1.88679245283019*I*pi """ return self.z + I*self.z_r @property def radius(self): """ The radius of curvature of the phase front. Examples ======== >>> from sympy.physics.optics import BeamParameter >>> p = BeamParameter(530e-9, 1, w=1e-3) >>> p.radius 1 + 3.55998576005696*pi**2 """ return self.z*(1 + (self.z_r/self.z)**2) @property def w(self): """ The radius of the beam w(z), at any position z along the beam. The beam radius at `1/e^2` intensity (axial value). See Also ======== w_0 : The minimal radius of beam. Examples ======== >>> from sympy.physics.optics import BeamParameter >>> p = BeamParameter(530e-9, 1, w=1e-3) >>> p.w 0.001*sqrt(0.2809/pi**2 + 1) """ return self.w_0*sqrt(1 + (self.z/self.z_r)**2) @property def w_0(self): """ The minimal radius of beam at `1/e^2` intensity (peak value). See Also ======== w : the beam radius at `1/e^2` intensity (axial value). Examples ======== >>> from sympy.physics.optics import BeamParameter >>> p = BeamParameter(530e-9, 1, w=1e-3) >>> p.w_0 0.00100000000000000 """ return sqrt(self.z_r/(pi*self.n)*self.wavelen) @property def divergence(self): """ Half of the total angular spread. Examples ======== >>> from sympy.physics.optics import BeamParameter >>> p = BeamParameter(530e-9, 1, w=1e-3) >>> p.divergence 0.00053/pi """ return self.wavelen/pi/self.w_0 @property def gouy(self): """ The Gouy phase. Examples ======== >>> from sympy.physics.optics import BeamParameter >>> p = BeamParameter(530e-9, 1, w=1e-3) >>> p.gouy atan(0.53/pi) """ return atan2(self.z, self.z_r) @property def waist_approximation_limit(self): """ The minimal waist for which the gauss beam approximation is valid. Explanation =========== The gauss beam is a solution to the paraxial equation. For curvatures that are too great it is not a valid approximation. Examples ======== >>> from sympy.physics.optics import BeamParameter >>> p = BeamParameter(530e-9, 1, w=1e-3) >>> p.waist_approximation_limit 1.06e-6/pi """ return 2*self.wavelen/pi ### # Utilities ### def waist2rayleigh(w, wavelen, n=1): """ Calculate the rayleigh range from the waist of a gaussian beam. See Also ======== rayleigh2waist, BeamParameter Examples ======== >>> from sympy.physics.optics import waist2rayleigh >>> from sympy import symbols >>> w, wavelen = symbols('w wavelen') >>> waist2rayleigh(w, wavelen) pi*w**2/wavelen """ w, wavelen = map(sympify, (w, wavelen)) return w**2*n*pi/wavelen def rayleigh2waist(z_r, wavelen): """Calculate the waist from the rayleigh range of a gaussian beam. See Also ======== waist2rayleigh, BeamParameter Examples ======== >>> from sympy.physics.optics import rayleigh2waist >>> from sympy import symbols >>> z_r, wavelen = symbols('z_r wavelen') >>> rayleigh2waist(z_r, wavelen) sqrt(wavelen*z_r)/sqrt(pi) """ z_r, wavelen = map(sympify, (z_r, wavelen)) return sqrt(z_r/pi*wavelen) def geometric_conj_ab(a, b): """ Conjugation relation for geometrical beams under paraxial conditions. Explanation =========== Takes the distances to the optical element and returns the needed focal distance. See Also ======== geometric_conj_af, geometric_conj_bf Examples ======== >>> from sympy.physics.optics import geometric_conj_ab >>> from sympy import symbols >>> a, b = symbols('a b') >>> geometric_conj_ab(a, b) a*b/(a + b) """ a, b = map(sympify, (a, b)) if a.is_infinite or b.is_infinite: return a if b.is_infinite else b else: return a*b/(a + b) def geometric_conj_af(a, f): """ Conjugation relation for geometrical beams under paraxial conditions. Explanation =========== Takes the object distance (for geometric_conj_af) or the image distance (for geometric_conj_bf) to the optical element and the focal distance. Then it returns the other distance needed for conjugation. See Also ======== geometric_conj_ab Examples ======== >>> from sympy.physics.optics.gaussopt import geometric_conj_af, geometric_conj_bf >>> from sympy import symbols >>> a, b, f = symbols('a b f') >>> geometric_conj_af(a, f) a*f/(a - f) >>> geometric_conj_bf(b, f) b*f/(b - f) """ a, f = map(sympify, (a, f)) return -geometric_conj_ab(a, -f) geometric_conj_bf = geometric_conj_af def gaussian_conj(s_in, z_r_in, f): """ Conjugation relation for gaussian beams. Parameters ========== s_in : The distance to optical element from the waist. z_r_in : The rayleigh range of the incident beam. f : The focal length of the optical element. Returns ======= a tuple containing (s_out, z_r_out, m) s_out : The distance between the new waist and the optical element. z_r_out : The rayleigh range of the emergent beam. m : The ration between the new and the old waists. Examples ======== >>> from sympy.physics.optics import gaussian_conj >>> from sympy import symbols >>> s_in, z_r_in, f = symbols('s_in z_r_in f') >>> gaussian_conj(s_in, z_r_in, f)[0] 1/(-1/(s_in + z_r_in**2/(-f + s_in)) + 1/f) >>> gaussian_conj(s_in, z_r_in, f)[1] z_r_in/(1 - s_in**2/f**2 + z_r_in**2/f**2) >>> gaussian_conj(s_in, z_r_in, f)[2] 1/sqrt(1 - s_in**2/f**2 + z_r_in**2/f**2) """ s_in, z_r_in, f = map(sympify, (s_in, z_r_in, f)) s_out = 1 / ( -1/(s_in + z_r_in**2/(s_in - f)) + 1/f ) m = 1/sqrt((1 - (s_in/f)**2) + (z_r_in/f)**2) z_r_out = z_r_in / ((1 - (s_in/f)**2) + (z_r_in/f)**2) return (s_out, z_r_out, m) def conjugate_gauss_beams(wavelen, waist_in, waist_out, **kwargs): """ Find the optical setup conjugating the object/image waists. Parameters ========== wavelen : The wavelength of the beam. waist_in and waist_out : The waists to be conjugated. f : The focal distance of the element used in the conjugation. Returns ======= a tuple containing (s_in, s_out, f) s_in : The distance before the optical element. s_out : The distance after the optical element. f : The focal distance of the optical element. Examples ======== >>> from sympy.physics.optics import conjugate_gauss_beams >>> from sympy import symbols, factor >>> l, w_i, w_o, f = symbols('l w_i w_o f') >>> conjugate_gauss_beams(l, w_i, w_o, f=f)[0] f*(1 - sqrt(w_i**2/w_o**2 - pi**2*w_i**4/(f**2*l**2))) >>> factor(conjugate_gauss_beams(l, w_i, w_o, f=f)[1]) f*w_o**2*(w_i**2/w_o**2 - sqrt(w_i**2/w_o**2 - pi**2*w_i**4/(f**2*l**2)))/w_i**2 >>> conjugate_gauss_beams(l, w_i, w_o, f=f)[2] f """ #TODO add the other possible arguments wavelen, waist_in, waist_out = map(sympify, (wavelen, waist_in, waist_out)) m = waist_out / waist_in z = waist2rayleigh(waist_in, wavelen) if len(kwargs) != 1: raise ValueError("The function expects only one named argument") elif 'dist' in kwargs: raise NotImplementedError(filldedent(''' Currently only focal length is supported as a parameter''')) elif 'f' in kwargs: f = sympify(kwargs['f']) s_in = f * (1 - sqrt(1/m**2 - z**2/f**2)) s_out = gaussian_conj(s_in, z, f)[0] elif 's_in' in kwargs: raise NotImplementedError(filldedent(''' Currently only focal length is supported as a parameter''')) else: raise ValueError(filldedent(''' The functions expects the focal length as a named argument''')) return (s_in, s_out, f) #TODO #def plot_beam(): # """Plot the beam radius as it propagates in space.""" # pass #TODO #def plot_beam_conjugation(): # """ # Plot the intersection of two beams. # # Represents the conjugation relation. # # See Also # ======== # # conjugate_gauss_beams # """ # pass
761b2a1fe983e81615b96851b75a42b31815ea5c25f42fa3cd4720148a3b6e59
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 matplotlib: skip("Matplotlib not the default backend") assert _to_tuple(*pole_zero_numerical_data(tf1)) == \ ((), ((-0.24999999999999994+1.3919410907075054j), (-0.24999999999999994-1.3919410907075054j))) assert _to_tuple(*pole_zero_numerical_data(tf2)) == \ ((0.0,), ((-0.25+0.3227486121839514j), (-0.25-0.3227486121839514j))) assert _to_tuple(*pole_zero_numerical_data(tf3)) == \ ((0.0,), ((-0.5000000000000004+0.8660254037844395j), (-0.5000000000000004-0.8660254037844395j), (0.9999999999999998+0j))) assert _to_tuple(*pole_zero_numerical_data(tf7)) == \ (((-0.6722222222222222+0.8776898690157247j), (-0.6722222222222222-0.8776898690157247j)), ((2.220446049250313e-16+1.2797182176061541j), (2.220446049250313e-16-1.2797182176061541j), (-0.7657146670186428+0.5744385024099056j), (-0.7657146670186428-0.5744385024099056j), (0.7657146670186427+0.5744385024099052j), (0.7657146670186427-0.5744385024099052j))) assert _to_tuple(*pole_zero_numerical_data(ser1)) == \ ((), (5.0, 0.0, 0.0, 0.0)) assert _to_tuple(*pole_zero_numerical_data(par1)) == \ ((-5.645751311064592, -0.5000000000000008, -0.3542486889354093), ((-0.24999999999999986+1.3919410907075052j), (-0.24999999999999986-1.3919410907075052j), (-0.2499999999999998+0.32274861218395134j), (-0.2499999999999998-0.32274861218395134j))) assert _to_tuple(*pole_zero_numerical_data(tf8)) == \ ((), ((-1.1641600331447917-3.545808351896439j), (-0.8358399668552097+2.5458083518964383j))) def test_bode(): if not matplotlib: skip("Matplotlib not the default backend") 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(Abs(a_i - b_i) < 1e-12 for \ a_i, b_i in zip(a, b)) def test_impulse_response(): if not matplotlib: skip("Matplotlib not the default backend") 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 matplotlib: skip("Matplotlib not the default backend") 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 matplotlib: skip("Matplotlib not the default backend") 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)
1b4298a159831972d33bdf241a664103934542db1109f504582e8b7b11150f18
from sympy.core.numbers import Rational from sympy.core.singleton import S from sympy.core.symbol import symbols from sympy.functions.elementary.exponential import log from sympy.external import import_module from sympy.physics.quantum.density import Density, entropy, fidelity from sympy.physics.quantum.state import Ket, TimeDepKet from sympy.physics.quantum.qubit import Qubit from sympy.physics.quantum.represent import represent from sympy.physics.quantum.dagger import Dagger from sympy.physics.quantum.cartesian import XKet, PxKet, PxOp, XOp from sympy.physics.quantum.spin import JzKet from sympy.physics.quantum.operator import OuterProduct from sympy.physics.quantum.trace import Tr from sympy.functions import sqrt from sympy.testing.pytest import raises from sympy.physics.quantum.matrixutils import scipy_sparse_matrix from sympy.physics.quantum.tensorproduct import TensorProduct def test_eval_args(): # check instance created assert isinstance(Density([Ket(0), 0.5], [Ket(1), 0.5]), Density) assert isinstance(Density([Qubit('00'), 1/sqrt(2)], [Qubit('11'), 1/sqrt(2)]), Density) #test if Qubit object type preserved d = Density([Qubit('00'), 1/sqrt(2)], [Qubit('11'), 1/sqrt(2)]) for (state, prob) in d.args: assert isinstance(state, Qubit) # check for value error, when prob is not provided raises(ValueError, lambda: Density([Ket(0)], [Ket(1)])) def test_doit(): x, y = symbols('x y') A, B, C, D, E, F = symbols('A B C D E F', commutative=False) d = Density([XKet(), 0.5], [PxKet(), 0.5]) assert (0.5*(PxKet()*Dagger(PxKet())) + 0.5*(XKet()*Dagger(XKet()))) == d.doit() # check for kets with expr in them d_with_sym = Density([XKet(x*y), 0.5], [PxKet(x*y), 0.5]) assert (0.5*(PxKet(x*y)*Dagger(PxKet(x*y))) + 0.5*(XKet(x*y)*Dagger(XKet(x*y)))) == d_with_sym.doit() d = Density([(A + B)*C, 1.0]) assert d.doit() == (1.0*A*C*Dagger(C)*Dagger(A) + 1.0*A*C*Dagger(C)*Dagger(B) + 1.0*B*C*Dagger(C)*Dagger(A) + 1.0*B*C*Dagger(C)*Dagger(B)) # With TensorProducts as args # Density with simple tensor products as args t = TensorProduct(A, B, C) d = Density([t, 1.0]) assert d.doit() == \ 1.0 * TensorProduct(A*Dagger(A), B*Dagger(B), C*Dagger(C)) # Density with multiple Tensorproducts as states t2 = TensorProduct(A, B) t3 = TensorProduct(C, D) d = Density([t2, 0.5], [t3, 0.5]) assert d.doit() == (0.5 * TensorProduct(A*Dagger(A), B*Dagger(B)) + 0.5 * TensorProduct(C*Dagger(C), D*Dagger(D))) #Density with mixed states d = Density([t2 + t3, 1.0]) assert d.doit() == (1.0 * TensorProduct(A*Dagger(A), B*Dagger(B)) + 1.0 * TensorProduct(A*Dagger(C), B*Dagger(D)) + 1.0 * TensorProduct(C*Dagger(A), D*Dagger(B)) + 1.0 * TensorProduct(C*Dagger(C), D*Dagger(D))) #Density operators with spin states tp1 = TensorProduct(JzKet(1, 1), JzKet(1, -1)) d = Density([tp1, 1]) # full trace t = Tr(d) assert t.doit() == 1 #Partial trace on density operators with spin states t = Tr(d, [0]) assert t.doit() == JzKet(1, -1) * Dagger(JzKet(1, -1)) t = Tr(d, [1]) assert t.doit() == JzKet(1, 1) * Dagger(JzKet(1, 1)) # with another spin state tp2 = TensorProduct(JzKet(S.Half, S.Half), JzKet(S.Half, Rational(-1, 2))) d = Density([tp2, 1]) #full trace t = Tr(d) assert t.doit() == 1 #Partial trace on density operators with spin states t = Tr(d, [0]) assert t.doit() == JzKet(S.Half, Rational(-1, 2)) * Dagger(JzKet(S.Half, Rational(-1, 2))) t = Tr(d, [1]) assert t.doit() == JzKet(S.Half, S.Half) * Dagger(JzKet(S.Half, S.Half)) def test_apply_op(): d = Density([Ket(0), 0.5], [Ket(1), 0.5]) assert d.apply_op(XOp()) == Density([XOp()*Ket(0), 0.5], [XOp()*Ket(1), 0.5]) def test_represent(): x, y = symbols('x y') d = Density([XKet(), 0.5], [PxKet(), 0.5]) assert (represent(0.5*(PxKet()*Dagger(PxKet()))) + represent(0.5*(XKet()*Dagger(XKet())))) == represent(d) # check for kets with expr in them d_with_sym = Density([XKet(x*y), 0.5], [PxKet(x*y), 0.5]) assert (represent(0.5*(PxKet(x*y)*Dagger(PxKet(x*y)))) + represent(0.5*(XKet(x*y)*Dagger(XKet(x*y))))) == \ represent(d_with_sym) # check when given explicit basis assert (represent(0.5*(XKet()*Dagger(XKet())), basis=PxOp()) + represent(0.5*(PxKet()*Dagger(PxKet())), basis=PxOp())) == \ represent(d, basis=PxOp()) def test_states(): d = Density([Ket(0), 0.5], [Ket(1), 0.5]) states = d.states() assert states[0] == Ket(0) and states[1] == Ket(1) def test_probs(): d = Density([Ket(0), .75], [Ket(1), 0.25]) probs = d.probs() assert probs[0] == 0.75 and probs[1] == 0.25 #probs can be symbols x, y = symbols('x y') d = Density([Ket(0), x], [Ket(1), y]) probs = d.probs() assert probs[0] == x and probs[1] == y def test_get_state(): x, y = symbols('x y') d = Density([Ket(0), x], [Ket(1), y]) states = (d.get_state(0), d.get_state(1)) assert states[0] == Ket(0) and states[1] == Ket(1) def test_get_prob(): x, y = symbols('x y') d = Density([Ket(0), x], [Ket(1), y]) probs = (d.get_prob(0), d.get_prob(1)) assert probs[0] == x and probs[1] == y def test_entropy(): up = JzKet(S.Half, S.Half) down = JzKet(S.Half, Rational(-1, 2)) d = Density((up, S.Half), (down, S.Half)) # test for density object ent = entropy(d) assert entropy(d) == log(2)/2 assert d.entropy() == log(2)/2 np = import_module('numpy', min_module_version='1.4.0') if np: #do this test only if 'numpy' is available on test machine np_mat = represent(d, format='numpy') ent = entropy(np_mat) assert isinstance(np_mat, np.ndarray) assert ent.real == 0.69314718055994529 assert ent.imag == 0 scipy = import_module('scipy', import_kwargs={'fromlist': ['sparse']}) if scipy and np: #do this test only if numpy and scipy are available mat = represent(d, format="scipy.sparse") assert isinstance(mat, scipy_sparse_matrix) assert ent.real == 0.69314718055994529 assert ent.imag == 0 def test_eval_trace(): up = JzKet(S.Half, S.Half) down = JzKet(S.Half, Rational(-1, 2)) d = Density((up, 0.5), (down, 0.5)) t = Tr(d) assert t.doit() == 1 #test dummy time dependent states class TestTimeDepKet(TimeDepKet): def _eval_trace(self, bra, **options): return 1 x, t = symbols('x t') k1 = TestTimeDepKet(0, 0.5) k2 = TestTimeDepKet(0, 1) d = Density([k1, 0.5], [k2, 0.5]) assert d.doit() == (0.5 * OuterProduct(k1, k1.dual) + 0.5 * OuterProduct(k2, k2.dual)) t = Tr(d) assert t.doit() == 1 def test_fidelity(): #test with kets up = JzKet(S.Half, S.Half) down = JzKet(S.Half, Rational(-1, 2)) updown = (S.One/sqrt(2))*up + (S.One/sqrt(2))*down #check with matrices up_dm = represent(up * Dagger(up)) down_dm = represent(down * Dagger(down)) updown_dm = represent(updown * Dagger(updown)) assert abs(fidelity(up_dm, up_dm) - 1) < 1e-3 assert fidelity(up_dm, down_dm) < 1e-3 assert abs(fidelity(up_dm, updown_dm) - (S.One/sqrt(2))) < 1e-3 assert abs(fidelity(updown_dm, down_dm) - (S.One/sqrt(2))) < 1e-3 #check with density up_dm = Density([up, 1.0]) down_dm = Density([down, 1.0]) updown_dm = Density([updown, 1.0]) assert abs(fidelity(up_dm, up_dm) - 1) < 1e-3 assert abs(fidelity(up_dm, down_dm)) < 1e-3 assert abs(fidelity(up_dm, updown_dm) - (S.One/sqrt(2))) < 1e-3 assert abs(fidelity(updown_dm, down_dm) - (S.One/sqrt(2))) < 1e-3 #check mixed states with density updown2 = sqrt(3)/2*up + S.Half*down d1 = Density([updown, 0.25], [updown2, 0.75]) d2 = Density([updown, 0.75], [updown2, 0.25]) assert abs(fidelity(d1, d2) - 0.991) < 1e-3 assert abs(fidelity(d2, d1) - fidelity(d1, d2)) < 1e-3 #using qubits/density(pure states) state1 = Qubit('0') state2 = Qubit('1') state3 = S.One/sqrt(2)*state1 + S.One/sqrt(2)*state2 state4 = sqrt(Rational(2, 3))*state1 + S.One/sqrt(3)*state2 state1_dm = Density([state1, 1]) state2_dm = Density([state2, 1]) state3_dm = Density([state3, 1]) assert fidelity(state1_dm, state1_dm) == 1 assert fidelity(state1_dm, state2_dm) == 0 assert abs(fidelity(state1_dm, state3_dm) - 1/sqrt(2)) < 1e-3 assert abs(fidelity(state3_dm, state2_dm) - 1/sqrt(2)) < 1e-3 #using qubits/density(mixed states) d1 = Density([state3, 0.70], [state4, 0.30]) d2 = Density([state3, 0.20], [state4, 0.80]) assert abs(fidelity(d1, d1) - 1) < 1e-3 assert abs(fidelity(d1, d2) - 0.996) < 1e-3 assert abs(fidelity(d1, d2) - fidelity(d2, d1)) < 1e-3 #TODO: test for invalid arguments # non-square matrix mat1 = [[0, 0], [0, 0], [0, 0]] mat2 = [[0, 0], [0, 0]] raises(ValueError, lambda: fidelity(mat1, mat2)) # unequal dimensions mat1 = [[0, 0], [0, 0]] mat2 = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] raises(ValueError, lambda: fidelity(mat1, mat2)) # unsupported data-type x, y = 1, 2 # random values that is not a matrix raises(ValueError, lambda: fidelity(x, y))
3d1d7d82853ad115cbdda537854d82277572ae519e3fac7fe77d6723d9aabe6f
from sympy.core.expr import Expr from sympy.core.mul import Mul from sympy.core.numbers import (I, Integer) from sympy.core.symbol import symbols from sympy.functions.elementary.complexes import conjugate from sympy.matrices.dense import Matrix from sympy.physics.quantum.dagger import adjoint, Dagger from sympy.external import import_module from sympy.testing.pytest import skip from sympy.physics.quantum.operator import Operator, IdentityOperator def test_scalars(): x = symbols('x', complex=True) assert Dagger(x) == conjugate(x) assert Dagger(I*x) == -I*conjugate(x) i = symbols('i', real=True) assert Dagger(i) == i p = symbols('p') assert isinstance(Dagger(p), adjoint) i = Integer(3) assert Dagger(i) == i A = symbols('A', commutative=False) assert Dagger(A).is_commutative is False def test_matrix(): x = symbols('x') m = Matrix([[I, x*I], [2, 4]]) assert Dagger(m) == m.H def test_dagger_mul(): O = Operator('O') I = IdentityOperator() assert Dagger(O)*O == Dagger(O)*O assert Dagger(O)*O*I == Mul(Dagger(O), O)*I assert Dagger(O)*Dagger(O) == Dagger(O)**2 assert Dagger(O)*Dagger(I) == Dagger(O) class Foo(Expr): def _eval_adjoint(self): return I def test_eval_adjoint(): f = Foo() d = Dagger(f) assert d == I np = import_module('numpy') def test_numpy_dagger(): if not np: skip("numpy not installed.") a = np.array([[1.0, 2.0j], [-1.0j, 2.0]]) adag = a.copy().transpose().conjugate() assert (Dagger(a) == adag).all() scipy = import_module('scipy', import_kwargs={'fromlist': ['sparse']}) def test_scipy_sparse_dagger(): if not np: skip("numpy not installed.") if not scipy: skip("scipy not installed.") else: sparse = scipy.sparse a = sparse.csr_matrix([[1.0 + 0.0j, 2.0j], [-1.0j, 2.0 + 0.0j]]) adag = a.copy().transpose().conjugate() assert np.linalg.norm((Dagger(a) - adag).todense()) == 0.0